text
stringlengths 180
608k
|
---|
[Question]
[
*This challenge is related to some of the MATL language's features, as part of the [May 2018 Language of the Month](https://codegolf.meta.stackexchange.com/questions/16337/language-of-the-month-for-may-2018-matl) event.* *Associated challenge*: [Function clipboard: paste](https://codegolf.stackexchange.com/questions/165144/function-clipboard-paste).
---
# Introduction
MATL has several *clipboards*, where you can store values (copy) to be retrieved later (paste). Some clipboards are *automatic*, which means that copying is automatically triggered by certain events. This challenge focuses on one of the automatic clipbards, called the *function-input clipboard*, or simply *function clipboard*.
This clipboard stores the inputs to the four most recent calls to normal, input-taking functions. *Normal* functions are the most common type of functions in MATL. *Input-taking* means that the function takes at least one input (functions that do not take any input are not considered by the function clipboard).
This is best explained with the following examples, which use two normal functions:
* `+`, which pops two numbers from the stack and pushes their sum.
* `U`, which pops one number and pushes its square.
**Example 1**:
```
3 2 + 6 + 12 4 U + +
```
[produces](https://tio.run/##y00syfn/31jBSEFbwQyIDY0UTBRCgQzt//8B) the result `39`. The code is interpreted as follows:
* Number literals such as `3` or `12` get pushed to the stack
* Functions such as `+` pop their inputs and push their outputs to the stack.
The function calls, in chronological order, are:
1. `3 2 +` gives `5`
2. `5 6 +` gives `11`
3. `4 U` gives `16`
4. `12 16 +` `28`
5. `11 28 +` gives `39`.
The clipboard can be viewed as a list of four lists. Each inner list contains the inputs to a function call, with *most recent calls first*. Within each inner list, *inputs are in their original order*.
So after running the code the clipboard contents are (in Python notation):
```
[[11, 28], [12, 16], [4], [5, 6]]
```
**Example 2**:
```
10 20 U 30 +
```
[leaves](https://tio.run/##y00syfn/39BAwchAIVTB2EBB@/9/AA) numbers `10` and `430` on the stack. The stack is displayed bottom to top at the end of the program.
The function calls are
1. `20 U` gives `400`
2. `400 30 +` gives `430`
Since there have been only two function calls, some of the inner lists defining the clipboard will be *empty*. Note also how `10` is not used as input to any function.
Thus, the clipboard contents after running the code are:
```
[[400, 30], [20], [], []]
```
**Example 3** (invalid):
```
10 20 + +
```
is considered invalid, because an input to the second `+` is missing (in MATL this would implicitly trigger user input).
# The challenge
**Input**: a string *S* with number literals, `+` and `U`, separated by spaces.
**Output**: the contents of the function clipboard after evaluating the string *S*.
Clarifications:
* You may use any two consistent symbols to represent those functions, other than digits. Also, you can use any consistent symbol as separator, instead of space.
* Only the two indicated functions will be considered.
* The input string will contain at least one number literal and at least one function.
* All numbers will be positive integers, possibly with more than one digit.
* It is possible that some number literals are not used by any function, as in the example 2.
* The input is guaranteed to be valid code, without requiring additional numbers. So a string as in example 3 will never occur.
* Trailing empty inner lists in the output can be ommited. So the result in example 2 can be `[[400, 30], [20]]`
* Any reasonable, unambiguous output format is acceptable. For example, a string with comma as inner separator and semicolon as outer separator: `400,30;20;;`.
Additional rules:
* Input and output can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* Programs or functions are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* Shortest code in bytes wins.
# Test cases
```
Input
Output
3 2 + 6 + 12 4 U + +
[[11, 28], [12, 16], [4], [5, 6]]
15 3 4 + 2 U 8 + U +
[[7, 144], [12], [4, 8], [2]]
3 6 9 12 + + 10 8 U 6
[[8], [6, 21], [9, 12], []]
8 41 12 25 4 5 33 7 9 10 + + + + + + + +
[[41, 105], [12, 93], [25, 68], [4, 64]]
10 1 1 + U U U U U
[[65536], [256], [16], [4]]
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 43 bytes
```
sed s/+/rdnFPrp+/g\;s/U/p2^/g|dc|tac|sed 4q
```
[Try it online!](https://tio.run/##S0oszvj/vzg1RaFYX1u/KCXPLaCoQFs/Pca6WD9Uv8AoTj@9JiW5piQxuQakyKTw/39jBSMFbQUzIDY0UjBRCAUytAE "Bash – Try It Online")
This prints the clipboard in the following format, note the usage of \x0F as the separator.
```
item_1\x0Fitem_2
item_3
.
.
item_m\x0Fitem_n
```
The key idea is to pass this into dc, a stack-based language, such that the required stack items will be printed.
The input is piped to sed where every `+` is replaced with `rdnFPrp+`, which in dc prints the second number on the stack followed by \x0F and then the top number before performing addition. sed also replaces every `U` with `p2^`, print the top stack element and square it.
>
> The first substitution command `s` replaces all, as is denoted by the **g**lobal flag `g`, `+`s with `rdnFPrp+`. In dc, `r` swaps the top two stack items, `d` duplicates the top item, `n` prints it without a newline, `F` pushes 15 onto the stack and `P` prints it as a character (which is the delimiter), `r` swaps again, `p` prints the top stack item and then `+` performs addition on the top two stack items.
>
>
> We have another command, and in sed, commands are separated by either semicolons or newlines, of which the first option is chosen. Simply having `;` will make bash interpret that as the end of the sed command, so it is escaped with a `\`.
>
>
> In the last substitution command, `U` is replaced globally with `p2^`. In dc, `p` prints, and `2^` raises it to the second power.
>
>
>
The result of sed is eval'ed as dc code, printing the entire clipboard.
>
> The pipe to dc makes dc interpret that as dc code. Now, the most recent calls are at the bottom and the older ones at the top.
>
>
>
Since the lines are in reverse order, `tac` (reverse `cat`) is used to fix that.
And finally, sed picks the first 4 lines from tac.
>
> This is a shorter way of doing `head -4`. sed performs the commands to every line of the input one at a time. If there are no commands, nothing is done to the input, and it is returned as it is. `4q` tells sed to perform the command `q` on line 4. When sed is processing line 4 of the input, the first three inputs have already been printed. The command `q` quits the program, so it prints the fourth line and quits, thus performing the equivalent of `head -4`.
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 126 bytes
```
s=[0];b=[]
for c in input().split():k='U+'.find(c)+1;b=[s[k-1::-1]][:k]+b;s=[int([c,s[0]**2,sum(s[:2])][k])]+s[k:]
print b[:4]
```
[Try it online!](https://tio.run/##TY7BboMwDIbveQorlwJpKxKg61LxGDlFvpBSDbEBaqi0PT37g3aYnNiJ/f2/vPysH/NktjDfe2pJSrnF1pd861rP4jE/KdAw4SyvNcvPcfkcUO3YHpw6nB/DdM9CrnTCox9P2tqTZvZ2ZNXd4DRMa@bDMcKyKMwxvr6y6K3hnP2IpCCyLJYnOOq8rXnDCkL0332gtFPRbLIiQ4ouuNpQTQ4PJYXUDVX4KkwdXVHd3q5AvidSJUGJiaML@leqdWqbBiJIK3pLXLlz/yI5lwR0d/wL@Qs "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~113~~ 109 bytes
```
take 4.([]#).words
x:y:s#"+":r=(x+y:s#r)++[[y,x]]
x:s#"U":r=(x*x:s#r)++[[x]]
s#n:r=read n:s#r
_#_=[]
infix 4#
```
The first line defines an anonymous function which takes a string, e.g. `"3 2 + 6 + 12 4 U + +"`, and returns a list of lists of ints: `[[11,28],[12,16],[4],[5,6]]`. [Try it online!](https://tio.run/##jVDLasMwELzrKwb7klRKsGxZcQI@9VzoxVBQRTDNoyaJG@xAHUp/ve5KTkqhORQhabUzszur17Ldrff7fps/96dyt4aajowNx9P3t2bVsm5xXrRhwINFk4867h7NmHNjzqKzlmACiwG8635AB7VhTelmXa5QO4Atw2VuLKvqTdVBhf2hrGrkOJTHB4yOTVWfMMV2zGAQJIjBoWnLGAoFBTxgEAhkioQynAgFMrqLK5IQf@743MkiAgvoAcqgpEPilKRUIMHMUSNP/bUuLSIQ25e@LMpbxj4m7JYvZoyUAnFmBYyMBaR2kXJHKqDpL9gt16SbEVmpQec1Ar5K7DQ35yGRZ2hqKF0wpxJe6yT/nZOqKLIso/TqeZ74vs5vdnGilXf@5zNIrNM00YPAX9eJLZt89l8vm325bfvJ0/3j4zc "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
A"D¸ˆn‚DˆO"4ô‡.V¯R4£
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fUcnl0I7TbXmPGma5nG7zVzI5vOVRw0K9sEPrg0wOLf7/31jBTMFSwdBIIQkIDQ0ULBQSFcwA "05AB1E – Try It Online")
-4 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) (as well as -8 thanks to him updating me about rules).
* U: `a`
* + : `b`
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 140 bytes
```
import StdEnv,Text
k[a,b:n]["+":s]=k[a+b:n]s++[[b,a]]
k[a:n]["U":s]=k[a^2:n]s++[[a]]
k n[v:s]=k[toInt v:n]s
k _[]=[]
$s=k[](split" "s)%(0,3)
```
[Try it online!](https://tio.run/##NYo9C8IwEED3/oojVmhJBa3iIHTToeAgqFOIkn5JMUmlOYv@eWPa0uG4e/deLkuhrWqKtyxBiVrbWr2aFuGMxUF30aX8oPdkIsp2mjNCyc7wxDHt2VDKWBYJzvtkCK5TcIunYNCgWTcabFKN0PXWve@MJ4x7vnGGB@YlayRATDgPltE6tGcULXozqCAB30vcJmuIgcLWzSqGDVzdQYn95ZUUD2MX6dHuv1qoOh/hJAVWTav@ "Clean – Try It Online")
In classical Clean style, it's the Haskell solution except about 50% longer.
[Answer]
# JavaScript (ES6), 107 bytes
Takes input as a list consisting of integers, `'+'` and `'U'`. Returns another list consisting of integers, arrays of 2 integers and `'_'` for empty slots.
```
a=>a.map(x=>s.push(+x?x:(c=[x>[a=s.pop(),r=a*a]?a:[r=s.pop(),(r+=a,a)],...c],r)),s=[c='___'])&&c.slice(0,4)
```
[Try it online!](https://tio.run/##fY/fTsMgFMbvfYpeDbBH0n@buoTuKXZFSHOCnc7U0YCavn09LZ1ZdJqQA3yc3/cdXvETg/XH/v3u5J7a8aBGVDXKN@z5oOog@4/wwtNhN2y5VXqoNSoSXc8FeIW3aHa41f5b4z5VCCgMSCmtAS8EBKWtYk3TMCNWKytDd7Qtz6ASo3Wn4LpWdu6ZH7guISkgYSmDZLPsOQkVnfdsEagYIW5@kPkakjJ2Tk3FQjycof2fZDlnPcakcwLdskhP4OYKRm9VHqFiPQdPE5DZfTTLLs3@K9c@Q3A@r4vhfxUCxy8 "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(x => // for each entry x in a[]:
s.push( // update the stack:
+x ? // if x is a positive integer:
x // push x onto the stack
: // else:
( c = [ // update the clipboard:
x > [ // compare x with '['
a = s.pop(), // a = first operand
r = a * a // use a² as the default result
] ? // if x is 'U' (greater than '['):
a // save the 1st operand in the clipboard
: // else:
[ r = s.pop(), // r = 2nd operand
(r += a, a) // add the 1st operand
], // save both operands in the clipboard
...c // append the previous clipboard entries
], // end of clipboard update
r // push r onto the stack
) //
), // end of stack update
s = [c = '___'] // initialize the stack; start with c = '___'
) && // end of map()
c.slice(0, 4) // return the last 4 entries of the clipboard
```
[Answer]
# Go, ~~305~~ ~~303~~ 295 bytes
Dropped 8 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)
```
func e(s string){b,v,w,x,r:=[][]int{{},{},{},{}},[]int{},0,0,0;for _,d:=range Split(s," "){if d=="+"{w,x,v=v[0],v[1],v[2:];r=w+x;b=append([][]int{[]int{x,w}},b...)}else if d=="U"{w,v=v[0],v[1:];r=w*w;b=append([][]int{[]int{w}},b...)}else{n,_:=Atoi(d);r=n};v=append([]int{r},v...)};Print(b[0:4])}
```
[Try it online!](https://tio.run/##dZDLasMwEEXX0VcMWkn1YBI3ZGGjRf@gULIyJtjxA9FENrIqG4S@3fWjaeiiaDTMDPeeEWraqcuvn3lTwT2XihB571ptgJFdCLS@G7oWvdHXVtnfRqqmp4QTUn@p6@pkHBzZVYy@QgQBnOZ7iOAI57kIKCd@WqUV62Hzc1egxQFH1LFIszSTyjjn8REet5HH/XKSutVwwTIWOlfzaz@6mzSsRwqUO1lDKQQNqFt4Vth0n6FND0uK4izRYgjGpBB511WqZI9tWx5xmJcVYRhyX936Cn5o54X2ZG2Yl@E/zF@IU3iJxZtpJSv5bFQ@sU/fotce7SpP3ufvMKxI9/Ex436avgE)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 206 bytes
```
s=strsplit(input(''));m=t=[];for z=s
if(q=str2num(p=z{1}))t=[t q];else
if(p-43)m{end+1}=(k=t(end));t(end)=k^2;else
m{end+1}=(k=t(end-1:end));t(end-1:end)=[];t(end+1)=sum(k);end
end
end
m(1:end-4)=[];flip(m)
```
[Try it online!](https://tio.run/##Zc2xCoMwEAbg3afIlgvBIVE6NNxjdCoWShshaDSa2EHx2dOoLRQ6HHc/fNzfP8L9pWP06MPoXWsCmM5NAShlTFkMeK1U3Y9kRp@ZGobNyW6y4HBexMpYEoEMldKt15tweVkwu@juycWK0GCAdKdnx8bmJg/7Z3Jx/pGftPXvmQuGPvU2TKWUfcfC7vJyl3VrHFgWIy2IJJyc0ghJSnJJB6dv "Octave – Try It Online")
If only Octave had a `pop` syntax. `m` is the memory clipboard, `t` the stack.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~218~~ 204 bytes
*-14 bytes thanks to ovs*
```
from collections import*
def f(s):
a=deque(maxlen=4);z=a.appendleft;b=[];x=b.pop
for i in s.split():
if'+'==i:c=x(),x();z(c);r=sum(c)
elif'U'==i:c=x();z(c);r=c*c
else:r=int(i)
b+=r,
print([*a])
```
[Try it online!](https://tio.run/##RcxBasMwEAXQtX2K2Vmyg6FJ6MJijpFVyEKWR3RAlhRJATeXd@VC6eLDZ/5j4nf5Cv6y7zaFFUxwjkzh4DPwGkMqfbuQBSuynNpG40LPF4lVb448XqV6ox51jOQXR7aoGe8PteE8xhDbxoYEDOwhjzk6LuL40bDthg6RJ4ObkKca9RZGqoT5tdZSCbmKbv/oD5je/K6ZpoTsi@BDzwOmU9vEdFzuvX7I3YruAmcY4LPm4wxXuNUydHL/AQ "Python 3 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 335 330 bytes
```
func[s][b: copy[]foreach c split s" "[append b either c >"+"and(c <"U")[do c][c]]r: copy[]until[t: 0 until[not parse
b[to copy c[2 integer!"+"](insert/only r reduce[c/1 c/2]replace b c c/1 + c/2 t: 1)to end]]until[not parse b[to copy
c[integer!"U"](insert/only r to-block c/1 replace b c c/1 ** 2 t: 1)to end]]t = 0]take/part r 4]
```
[Try it online!](https://tio.run/##ZZHZboMwEEXf@YpbnpKgiiVL03T5iEo8WX4wZmhQqI2MaRVV@XY60C1NZVkezb1zj2U7KocnKoUMqt1Q9UaLTopiB23bo5CVdaT0Hhpd29QeXYhQqLYlU6IA1X5PjsXHMAqVKWca92EezkVpoaXQUrrvoN74uhF@hwSfpbEerXIdBYXwdnJBiwy18fRM7ooT5aw2HTkfW9Mc4eCo7DUJHafQcSYdtY3SxPfQGHvR2AUj0jkH8g2lvEDhBxVo8QPK/4G8vS4aqw9T7CVmscAFxeMBifTqQDFjPAes5NA6WxAqvKdY8kCEDe80wwo5F9Ep@DWs2bHiZsbSls/8j7zkydtxMhoDEnbk2JzpW6zSUc7WHMJRS9yM/mTyn61zYgIemUhf6wTcwZN7qY3y1IGUa2r@2rInfg3YV3JVY9@GDw "Red – Try It Online")
## More readable:
```
f: func[s] [
s: split s " "
b: copy []
foreach c s [
append b either (c > "+") and (c < "U")[do c] [c]
]
r: copy []
until [
t: 0
until [
not parse b [to copy c[2 integer! "+"]
(insert/only r reduce[c/1 c/2]
replace b c c/1 + c/2
t: 1)
to end]
]
until [
not parse b [to copy c[integer! "U"]
(insert/only r to-block c/1
replace b c c/1 ** 2
t: 1)
to end]
]
t = 0
]
take/part r 4
]
```
[Answer]
# [R](https://www.r-project.org/), ~~205~~ 182 bytes
```
function(P){S=F
M=list()
for(K in el(strsplit(P," "))){if(is.na(x<-strtoi(K))){if(K>1){M=c(m<-S[1],M)
S[1]=m^2}else{M=c(list(m<-S[2:1]),M)
S=c(sum(m),S[-2:0])}}else S=c(x,S)}
M[1:4]}
```
[Try it online!](https://tio.run/##XY9Ba4NAEIXv/orBHjJDtLhrkqaiPfaSWAKSU2rB2pUuuBrcDSQEf7tdJYES5jAw7803b7qhlt9d0V1QCfPb/mhyKoj9oTo1pZFtgzu6Zsm7kya11Aat2na4AdmAqFGbTh9raXDnueAS0VVWKPVzU@A59q1qWomb23zzxuiaJiWq2M8OLPdScsaeqC/ei1qLSZyuTA4esZwmkx3rk0JFXnbweRTk1E8LMCpnL6PeSQ8sWuT9UBYGZ0ZoA2VhDeyzmdnI6IawgldgHOa2WABr2MPKJXiCj/12a38RSjRGg/0OhDqaC4xBnAccv@PWsGAjjS9hAUsIQ3gZ8cGE/1cuPSLCO4LZNbs8B26jrG3fj/bhDw "R – Try It Online")
`M` is the memory clipboard, `P` is the program, and `S` is the stack.
Technically `S` is initialized as a vector containing a single zero but since we never get an invalid input, it saves me a byte from `S={}`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~264~~ 249 bytes
* -15 bytes from @ceilingcat
I used recursion so that I could use the function stack as the data stack: the input list is walked through and the operations are performed: the results are displayed in reverse order, with stack pushes not displayed.
The stack is implemented as a linked list. Here's how it works:
* The current node is set up with [pointer to value,pointer to previous node]
* To push a value, it is stored and the function is called again with the current node.
* To pop a value or modify the value on the top of the stack, a previous node's value is modified and the function is called again with the previous node.
I originally used a structure for the nodes, but I switched to bare pointers to save space. An interesting feature of this linked list is that it cleans itself up when the recursion completes.
```
#define _ printf(
f(char**s,int**p){int v,*y[]={&v,p},**w=y,m,n,t,z=1;return*s?**s-85?**s-43?--z,t=14,v=atoi(*s):(t=6,w=p[1],m=**w,**w+=n=**p):(t=0,w=p,**w*=m=**p),_(v=f(s+1,w))<4?",[%d]\0,[%d,%d]"+t+!v:"",m,n),v+z:0;}g(int*s){_"[");f(s,0);_"]\n");}
```
[Try it online!](https://tio.run/##HU9db4MwDHzvr8gybcqHkaClUwWL@BV9ogghCgxpZAiyoIL46/OSPt35bJ/PddDVNeLrvWl73ZCSjFOvTcsOLau/qkmIGVwtxMg3h8SCeOSF2t4tjDsIsagHDKDBwKqidGrM76TFnLm14HJ@QnzKgmAFo6IYrKrMT8/EzBNm1AcsasyjAgbljLyZVFr5U74b@q4XhRqeIpTMqpbNMoKF8884o5C/3Ytb6AEco9LIF5tQ6hNxsHJNwnTvmM8/862kOeWpM4CQpyUtbtqVO/qvhqrXfoxUU1eD/5sI4bjlZDsQ0jHPZcTTw44YnfGEMUo84hUvDq8o/@r2u@pmDJZ/ "C (gcc) – Try It Online")
] |
[Question]
[
Some of you may be familiar with the [BigNum Bakeoff](http://djm.cc/bignum-results.txt), which ended up quite interestingly. The goal can more or less be summarized as writing a C program who's output would be the largest, under some constraints and theoretical conditions e.g. a computer that could run the program.
In the same spirit, I'm posing a similar challenge open to all languages. The conditions are:
* **Maximum 512 bytes**.
* Final result must be printed to STDOUT. This is your score. If multiple integers are printed, they will be concatenated.
* Output must be an integer. (Note: **Infinity is not an integer**.)
* No built-in constants larger than 10, but numerals/digits are fine (e.g. Avogadro's constant (as a built-in constant) is invalid, but 10000 isn't.)
* The program **must terminate** when provided sufficient resources to be run.
* The printed output must be **deterministic** when provided sufficient resources to be run.
* You are provided large enough integers or bigints for your program to run. For example, if your program requires applying basic operations to numbers smaller than 101,000,000, then you may assume the computer running this can handle numbers at least up to 101,000,000. (Note: Your program may also be run on a computer that handles numbers up to 102,000,000, so simply calling on the maximum integer the computer can handle will not result in deterministic results.)
* You are provided enough computing power for your program to finish executing in under 5 seconds. (So don't worry if your program has been running for an hour on your computer and isn't going to finish anytime soon.)
* No external resources, so don't think about importing that Ackermann function unless it's a built-in.
All magical items are being temporarily borrowed from a generous deity.
## Extremely large with unknown limit
* [*Steven H*, Pyth](https://codegolf.stackexchange.com/a/150420) f3+B³F+ω²(25626)
where B³F is the Church-Kleene ordinal with the fundamental sequence of
```
B³F[n] = B³F(n), the Busy Beaver BrainF*** variant
B³F[x] = x, ω ≤ x < B³F
```
## Leaderboard:
1. [*Simply Beautiful Art*, Ruby](https://codegolf.stackexchange.com/a/148998) fψ0(X(ΩM+X(ΩM+1ΩM+1)))+29(999)
2. [*Binary198*, Python 3](https://codegolf.stackexchange.com/a/237493/108434) fψ0(εΩω+1)+1(3) (there was previously an error but it was fixed)
3. [*Steven H*, Pyth](https://codegolf.stackexchange.com/a/149031) fψ(ΩΩ)+ω²+183(25627!)
4. [*Leaky Nun*, Python 3](https://codegolf.stackexchange.com/a/150220) fε0(999)
5. [*fejfo*, Python 3](https://codegolf.stackexchange.com/a/151329) fωω6(fωω5(9e999))
6. [*Steven H*, Python 3](https://codegolf.stackexchange.com/a/149774) fωω+ω²(99999)
7. [*Simply Beautiful Art*, Ruby](https://codegolf.stackexchange.com/a/149131) fω+35(9999)
8. [*i..*, Python 2](https://codegolf.stackexchange.com/a/150428), f3(f3(141))
## Some side notes:
If we can't verify your score, we can't put it on the leaderboard. So you may want to expect explaining your program a bit.
Likewise, if you don't understand how large your number is, explain your program and we'll try to work it out.
If you use a [Loader's number](http://googology.wikia.com/wiki/Loader%27s_number) type of program, I'll place you in a separate category called **"Extremely large with unknown limit"**, since Loader's number doesn't have a non-trivial upper bound in terms of the fast growing hierarchy for 'standard' fundamental sequences.
Numbers will be ranked via the [fast-growing hierarchy](http://googology.wikia.com/wiki/Fast-growing_hierarchy).
For those who would like to learn how to use the fast growing hierarchy to approximate really large numbers, I'm hosting a [Discord server](https://discord.gg/5v6ucfN) just for that. There's also a chat room: [Ordinality](https://chat.stackexchange.com/rooms/69263).
Similar challenges:
[Largest Number Printable](https://codegolf.stackexchange.com/q/18028)
[Golf a number bigger than TREE(3)](https://codegolf.stackexchange.com/q/139355)
[Shortest terminating program whose output size exceeds Graham's number](https://codegolf.stackexchange.com/q/6430)
For those who want to see some simple programs that output the fast growing hierarchy for small values, here they are:
### Ruby: fast growing hierarchy
```
#f_0:
f=->n{n+=1}
#f_1:
f=->n{n.times{n+=1};n}
#f_2:
f=->n{n.times{n.times{n+=1}};n}
#f_3:
f=->n{n.times{n.times{n.times{n+=1}}};n}
#f_ω:
f=->n{eval("n.times{"*n+"n+=1"+"}"*n);n}
#f_(ω+1):
f=->n{n.times{eval("n.times{"*n+"n+=1"+"}"*n)};n}
#f_(ω+2):
f=->n{n.times{n.times{eval("n.times{"*n+"n+=1"+"}"*n)}};n}
#f_(ω+3):
f=->n{n.times{n.times{n.times{eval("n.times{"*n+"n+=1"+"}"*n)}}};n}
#f_(ω∙2) = f_(ω+ω):
f=->n{eval("n.times{"*n+"eval(\"n.times{\"*n+\"n+=1\"+\"}\"*n)"+"}"*n);n}
```
etc.
To go from `f_x` to `f_(x+1)`, we add one loop of the `n.times{...}`.
Otherwise, we're diagonalizing against all the previous e.g.
```
f_ω(1) = f_1(1)
f_ω(2) = f_2(2)
f_ω(3) = f_3(3)
f_(ω+ω)(1) = f_(ω+1)(1)
f_(ω+ω)(2) = f_(ω+2)(2)
f_(ω+ω)(3) = f_(ω+3)(3)
```
etc.
[Answer]
# Ruby, fψ0(X(ΩM+X(ΩM+1ΩM+1)))+29(999)
where **M** is the first Mahlo 'ordinal', **X** is the chi function (Mahlo collapsing function), and **ψ** is the ordinal collapsing function.
```
f=->a,n,b=a,q=n{c,d,e=a;!c ?[q]:a==c ?a-1:e==0||e&&d==0?c:e ?[[c,d,f[e,n,b,q]],f[d,n,b,q],c]:n<1?9:!d ?[f[b,n-1],c]:c==0?n:[t=[f[c,n],d],n,c==-1?[]:d==0?n:[f[d,n,b,t]]]};(x=9**9**9).times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{h=[];x.times{h=[h,h,h]};h=[[-1,1,[h]]];h=f[h,p x*=x]until h!=0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
```
[Try it online!](https://tio.run/##5ZDBDoIwDIZfBS5GSWfckWHlQZoexjYCiS6ikGDQZ8diNPHkC7gt6de///5DL0N1m@ca1cFChAotdBgnBx4C2iJ1SUkdG4soZJU2AXF3v4fVyguUzgQx0GKvKSwB0DEL@zeDYxP3usxN6sVZUwVR6ZfsloBoqEeRHUQGz/JLZKVLYuPf809Yz8yPYj1inmXL22z79hSu0/gntUHi4qtpQK5sRJCUBg3UyIakrWV0TsYMRx5i3x6TJsXd4@eZ5yc)
### Code Breakdown:
```
f=->a,n,b=a,q=n{ # Declare function
c,d,e=a; # If a is an integer, c=a and d,e=nil. If a is an array, a=[c,d,e].compact, and c,d,e will become nil if there aren't enough elements in a (e.g. a=[1] #=> c=1,d=e=nil).
!c ?[q]: # If c is nil, return [q], else
a==c ?a-1: # If a==c, return a-1, else
e==0||e&&d==0?c: # If e==0 or e is not nil and d==0, return c, else
e ?[[c,d,f[e,n,b,q]],f[d,n,b,q],c]: # If e is not nil, return an array inside an array, else
n<1?9: # If n<1, return 9, else
!d ?[f[b,n-1],c]: # If d is nil, return [f[b,n-1],c], else
c==0?n: # If c==0, return n, else
[t=[f[c,n],d],n,c==-1?[]:d==0?n:[f[d,n,b,t]]] # t=[f[c,n],d]. If c==-1, return [t,n,[]], else if d==0, return [t,n,n], else return [t,n,[f[d,n,b,t]]].
}; # End of function
(x=9**9**9) # Declare x
x.times{...} # Looped within 33 x.times{...} loops
h=[]; # Declare h
x.times{h=[h,h,h]}; # Nest h=[h,h,h] x times
h=f[h,p x*=x] # Apply x*=x, print x, then h=f[h,x]
until h==0 # Repeat previous line until h==0
```
### Math Breakdown:
`f` reduces `a` based on `n,b,q`.
The basic idea is to have an extremely nested `a` and reduce it repeatedly until it reduces down to `a=0`. For simplicity, let
```
g[0,n]=n
g[a,n]=g[f[a,n],n+1]
```
For now, let's only worry about `n`.
For any integer `k`, we get `f[k,n]=k-1`, so we can see that
```
g[k,n]=n+k
```
We then have, for any `d`, `f[[0,d],n]=n`, so we can see that
```
g[[0,d],n]
= g[f[[0,d],n],n+1]
= g[n,n+1]
= n+n+1
```
We then have, for any `c,d,e`, `f[[c,0,e],n]=f[[c,d,0],n]=c`. For example,
```
g[[[0,d],0,e],n]
= g[f[[[0,d],0,e]],n+1]
= g[[0,d],n+1]
= (n+1)+(n+1)+1
= 2n+3
```
We then have, for any `c,d,e` such that it does not fall into the previous case, `f[[c,d,e],n]=[[c,d,f[e,n]],f[d,n],e]`. This is where it starts to get complicated. A few examples:
```
g[[[0,d],1,1],n]
= g[f[[[0,d],1,1],n],n+1]
= g[[[0,d],1,0],0,[0,d]],n+1]
= g[f[[[0,d],1,0],0,[0,d]],n+1],n+2]
= g[[[0,d],1,0],n+2]
= g[f[[[0,d],1,0],n+2],n+3]
= g[[0,d],n+3]
= (n+3)+(n+3)+1
= 2n+7
#=> Generally g[[[0,d],1,k],n] = 2n+4k+3
g[[[0,d],2,1],n]
= g[f[[[0,d],2,1],n],n+1]
= g[[[[0,d],2,0],1,[0,d]],n+1]
= g[f[[[[0,d],2,0],1,[0,d]],n+1],n+2]
= g[[[[[0,d],2,0],1,n+1],0,[[0,d],2,0]]],n+2]
= g[f[[[[[0,d],2,0],1,n+1],0,[[0,d],2,0]]],n+2],n+3]
= g[[[[0,d],2,0],1,n+1],n+3]
= ...
= g[[[0,d],2,0],3n+6]
= g[f[[[0,d],2,0],2n+6],3n+7]
= g[[0,d],3n+7]
= (3n+7)+(3n+7)+1
= 6n+15
```
It quickly ramps up from there. Some points of interest:
```
g[[[0,d],3,[0,d]],n] ≈ Ack(n,n), the Ackermann function
g[[[0,d],3,[[0,d],0,0]],63] ≈ Graham's number
g[[[0,d],5,[0,d]],n] ≈ G(2^^n), where 2^^n = n applications of 2^x, and G(x) is the length of the Goodstein sequence starting at x.
```
Eventually introducing more arguments of the `f` function as well as more cases for the array allows us to surpass most named computable notations. Some particularly known ones:
```
g[[[0],3,[0,d]],n] ≈ tree(n), the weak tree function
g[[[[0],3,[0,d]],2,[0,d]],n] ≈ TREE(n), the more well-known TREE function
g[[[[0,d]],5,[0,d]],n] >≈ SCG(n), sub-cubic graph numbers
g[[[0]],n] ≈ S(n), Chris Bird's S function
```
[Answer]
# Pyth, fψ(ΩΩ)+ω2+183(~25627!)
```
=QC`.pGL&=^QQ?+Ibt]0?htb?eb[Xb2yeby@b1hb)hbXb2yeb@,tb&bQ<b1=Y_1VQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQ.v%%Fms["*s[.v"*\\^2d"\"%s"*\\^2d"\"")Qs["=Y.v+*"*\\^2Q"\"*3]"*\\^2Q"\"Q\YuyFYHpQ)
```
Requires any non-empty input, but the value thereof is not used.
Explanation (for the *new and actually-reasonably-scoring* version):
```
=QC`.pG Sets the value of the autofill variable to app. 256^27!
27! ~= the number of characters in the string
containing all permutations of the alphabet.
We interpret that string as a base-256 number.
L Define a function y(b,global Q):
&=^QQ Set Q to Q^Q and:
?+Ibt]0 If (?) the variable (b) is (I)nvariant on (+)adding itself
to the empty array (i.e. if it's an array itself):
?htb If the second element of b is not 0:
?eb If the last element is not 0
[Xb2yeby@b1hG) return [b with its last element replaced with y(b[-1]), y(b[1]), b[0]]
hb else return b[0]
Xb2yeb else return b with its last element replaced with y(b[-1])
@,tb&bQ<b1 If b isn't an array,return:
either b-1 if it's a standard ordinal (1 or more)
or Q if b is ω
or 0 if b is 0
=Y_1 Set the global variable Y to -1 (representing ω)
VQ Q times, do (the rest of the explanation):
VQVQ....VQ Iterate from 0 to Q-1 183 times, each subiteration
reading the most recent value of Q when it starts:
.v%%Fms["*s[.v"*\\^2d"\"%s"*\\^2d"\"")Q
Iterate from 0 to Q-1 Q times, each subiteration
reading the most recent value of Q when it starts:
s["=Y.v+*"*\\^2Q"\"*3]"*\\^2Q"\"Q
Y = [Y,Y,Y] Q times, stacking with previous iterations.
uyFYHpQ) Run y_x(Y) for x incrementing until y_(x-1)(Y)=0
```
It's very hard for me to compute the size of this, mostly because ~~it's late in the day and I'm not super familiar with fast-growing hierarchies or how I'd even go about trying to figure out how many times Q goes through the `y()` wringer.~~ While I now know more about ordinals, I still have no idea how to calculate the value of the ordinal represented by the recursive definition in my program. I'd join the Discord server, but that's under a pseudonym I'd rather not be linked to my real name.
~~Unfortunately, because I know relatively little about said fast-growing hierarchies, I'm likely to have already lost to the Ruby answer. It's hard for me to tell.~~ ~~I may have beaten the Ruby answer, but I'm not 100% sure.~~ ¯\\_(ツ)\_/¯
[Answer]
# Pyth, f3+σ-1+ω2(25626)
Where σm[n] is the Busy Beaver function Σ of order `m` called on `n`: σm[n] = Σm(n). The order `-1` is to denote that the Busy Beaver here is not being called on a true Turing Machine, but rather an approximation with a finite wrapping tape of `Q` elements. This allows the halting problem to be solvable for these programs.
```
=QCGM.x-Hlhf!-/T4/T5.__<GH0M.x+Hlhf!-/T4/T5._>GHlGL=.<QC`m.uX@[XN2%h@N2l@N1XN2%t@N2l@N1XN1X@N1@N2%h@@N1@N2l@N1XN1X@N1@N2%t@@N1@N2l@N1XW!@@N1@N2N2nFKtPNXW@@N1@N2N2gFK)@hNeN3%heNlhNd)bLym*F[]d^UQQUQUld)^U6QJ"s*].v*\mQ"
.v+PPPP*JQ"+*\mQ\'
```
The TL;DR is that this creates all possible BrainF\*\*k programs of length Q, runs them in an environment where the maximum value of an integer is Q and the tape length is Q, and compiles all the states from these operations together to append (that's the `3+`) to Q, repeating the above on a scale of fω2.
I still have ~half the characters to work with if I wanted to do something more, but until we figure out where this is I'll just leave it as is.
[Answer]
# Python 3, probably fε0(99) I have no idea
```
def f(n,d,a,i):
if d < 0 or i >= len(a):
return n
k = a[i]
if type(k) == int:
if k < 0:
a[i] = [-2]*n
a = f(n,d,a,i+k+2)
else:
a[i] -= 1
else:
a[i] = f(n,d-1,k,0)
return a
def g(n):
d=n
a=[-2]*n
while type(a) != int:
a = f(n,d,a,0)
n += 1
print(g(99))
```
*Edit: Accidentally left d=2 from the slower-growing format, fixed and it's now d=n.*
[Try it online!](https://tio.run/##TY/BDoIwEETv@xXjrZWSCJ401h8hHppQoClZCWIMX49tRfS2O307Mx3mqbvzcVlq26ARrGpllJNngmtQ44ID7iMcrhq9ZWHiC0Y7PUcGE8FDw1TulvhpHqzwElrD8RTJIPpoEufEBbzKy9uekxC2LTPzWSmDavuH/eG5RkGbtjqkm7xQXh3CxdrGEMU/tIJjx1qXBKO/Wa/O9fbTz0jstn7/DaIXGFlKJBrGwIhWnE5SLssb)
First, this is my first CGSE post (and my first SE post in general) so this definitely looks weird. Second, I'm not sure it's fε0(99) I have no idea what this is. Third, I did no golfing on this, just trying to get something out there that I can understand (and build upon in later edits). I consider this to be "v0.1",
## Equivalent equation
Fourth, I'm not sure that g(n) grows at fε0. I sent it to the mathematics stackex discord, and ended up making an approximation of this program.
\$g(n) = f(n,n,\{-2,-2,\cdots\ n\ times\},0)\\a=\{a\_0,a\_1,\cdots a\_k\}\$
\$f(n,d,a,i) =\left\{ \begin{array}{cl} n & : \ d < 0 \\ n & : \ i > k\\ f(n,d,\{a\_0,\cdots a\_{i-1},\{-2,-2,-2,\cdots n\ times\},a\_{i+1}\cdots a\_k \},i+k+2) & : \ a\_i \in \mathbb{Z}\ \cap\ a\_i<0\\ f(n+1,d-1,\{a\_0\cdots a\_{i-1},a\_i-1,a\_{i+1},\cdots a\_k\},0) & : \ a\_i \in \mathbb{Z}\ \cap\ a\_i\geq 0 \\ \{a\_0,a\_1\cdots a\_{i-1},f(n,d-1,a\_i,0),a\_{i+1},\cdots a\_k\}&:\ a\_i\notin\mathbb{Z} \end{array} \right.\$
If f(n,d,a,i) is cutting off on the side of the screen, then use these links to an image of the equation, both with a [White background](https://i.stack.imgur.com/V2P3a.png) and with a [Discord Dark Mode background.](https://i.stack.imgur.com/kd9yp.png)
## Slower growing formats
Lastly, while testing it, to make sure it worked, I made a version that grows significantly slower.
[Slower growing function.](https://tio.run/##TY7NDoMgEITv@xTTG1RM1N6a0hcxHkjESDD4U5vGp6dAre1hE3b4dmambe1Hd/G@1R065kQrlDD8SjAdWtxQYFxgcJcYtGMq/mDR63NxcESwkFC1aRK/bpNmlkNKGLdGMog2msR34gJe51VzdkkI25GZ2aziQdXDQ//wXKKkQ9sd0k1eCiuKcLG3UUROVtSGUXLPmGVB9OrNoD/dFMfp2@0/PNrMyFIW0bQEgs3c@zc) For this, it increments an unrelated *q* variable instead of incrementing *n* directly, then outputs q. With n=2 and d=2, it outputs 714025. With n=3 and d=2 or n=2 and d=3, tio.run gives me a "Program has exceeded the 60 second time limit."
```
def f(n,d,a,i):
if d < 0 or i >= len(a):
return n
k = a[i]
if type(k) == int:
if k < 0:
a[i] = [-2]*n
a = f(n,d,a,i+k+2)
else:
a[i] -= 1
else:
a[i] = f(n,d-1,k,0)
return a
n=3
d=2
a=[-2]*n
q=0
while type(a) != int:
a = f(n,d,a,0)
q += 1
print(q)
```
[Answer]
# Python 3, Greater than fSVO(Z)≈fψ0(ΩΩω)(Z)
# Where Z = (...((9^9)^(9^9))^((9^9)^(9^9))...) with about 9^9 parenthesis
```
def R(a,n):
if type(a)==int:return a-1
if n<1:return 0
if not a:return n
if a[-1]==0:return a[:-1]
if a[0]!=0:a[0]=R(a[0],n);return a
i=0
while a[i]==0:i+=1
a[i-1]=R(a[:],n-1);a[i]=R(a[i],n);return a
def G(a,n,m=0):
A='\t'
if a==0:return n+1
if m:
prgm='';b=G(a,n)
for i in range(b):prgm+=A*i+'for _ in range(n):\n'
prgm+=A*b+'n=G(R(a,n),n,m-1)';exec(prgm)
m=0
if type(a)==list:m=n
for i in range(n):n=G(R(a,n),n,m)
return n+1
z=Z=9**9
for i in range(z):Z=Z**Z
Z=G([Z]*Z,Z)
print(Z)
```
I wrote this mess a while back but didn't upload it because I was thinking I should just go for First Place Or Bust. Turns out: First Place is hard. So here's my 4th place submission.
Ungolfed program: <https://github.com/cpaca/BignumReboot/blob/main/VeblenMethod.py>
Website to minify a python program: <https://python-minifier.com/>
Unfortunately, because I wrote it so long ago, **I've forgotten most of what I wrote.** I remembered what my goal was, I remembered finishing it, but I don't remember the mathematics behind the mess very well. The ungolfed program has comments (lots of them, actually, looking at it) but there are a *few* hints that I do remember:
---
G(a,n,m) accepts either a list, int, int *or* an int, int, int. If the last variable isn't given, it's defaulted to 0.
All integers are positive. Negative integers should be inaccessible.
G(a,n,0) for int, int, 0 should be equivalent to fa(n) under the fast growing hierarchy. This evidently isn't the case, as it's calculating G(1,1) = 3, G(1,2) = 5, G(1,5) = 11, G(2,2) = 12. (Best guess, it's actually f0(fa(n)) but I can't really confirm.)
G([],n,0) - in other words, for empty list - should be equivalent to G(n,n,0)
R(a,n) is φ(a)[n] under the Veblen hierarchy.
G(a,n,0) should be greater than fφ(a)(n), where φ is the veblen function.
However, there is one thing that could make this function less than what I expect. In the analysis of the FGH, and the Veblen function, I made one assumption which MIGHT not be true:
$$f\_{\alpha+\beta}(n) < f\_{\alpha+f\_\beta(n)}(n)$$
[Answer]
# python, f3(f3(141)), 512 bytes
```
import math
def f(x):
return math.factorial(x)
x=9
for j in range(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(x))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))):
x=f(x)
print x
```
This isn't really a valid answer, but I wanted to post it anyway. A quick rundown:
```
import math # imports the factorial function
def f(x):
return math.factorial(x) # shortens the factorial operation
x=9 # sets x to highest available number
for j in range(f(...f(x)...)): # repeats * A LOT *
x=f(x) # does the factorial of x
print x # outputs the result
```
Anyway, I don't know if this answer technically legal, but it was fun to write. Feel free to edit any errors you find in the code.
[Answer]
# Ruby, probably ~ fω+35(9999)
```
G=->n,k{n<1?k:(f=->b,c,d{x=[]
c<G[b,d]?b-=1:(x<<=b;c-=G[b,d])while c>=d
x<<[c]}
x=f[n-1,k,b=1]
(b+=1;*u,v=x;x=v==[0]?u:v==[*v]?u<<[v[0]-1]:u+f[n-1,G[v,b]-1,b])while x[0]
b)};(n=9**9**99).times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n=G[n,n]}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}};p n
```
[Try it online!](https://tio.run/##7VE7DsIwDN1zCsZ@HERGmrode4goi9NWVIUIAQ1BVc9ejGBh4gJYlt/zs588@DLRY10blJWHcfalqsci6bklcNDOEY0VrmwMQWtrkqiKJJYlknYS32p6PwzHbuMqbAWPjLOLiNgbLxWMQKisSChHpbMJAkYdMSCana2n4kWywIxtgSWpbDHlb2tjAhArXD4XIm8IShedeNxn2Sv36fY2nLrr7P/4jfwcD94uv0OfN35dnw)
### Approximate Math Explanation:
The below is approximately equal to the program above, but simplified so that its easier to understand.
`G(0,k) = k` is our base function.
To evaluate `G(n,k)`, we take `k` and write it as `G(n-1,1) + ... + G(n-2,1) + ... + G(0,1)`.
Then change all of the `G(x,1)`'s into `G(x,2)`'s and subtract `1` from the entire result.
Rewrite it in the above form using `G(x,2)`, where `x<n`, and leave the remainder at the end. Repeat, changing `G(x,2)` to `G(x,3)`, etc.
When the result reaches `-1`, return the base (the `b` that would be in `G(x,b)`.)
## Examples:
### G(1,1):
```
1: 1 = G(0,1)
2: G(0,2) - 1 = 1
3: 1 - 1 = 0
4: 0 - 1 = -1 <----- G(1,1) = 4
```
### G(1,2):
```
1: 2 = G(0,1) + G(0,1)
2: G(0,2) + G(0,2) - 1 = G(0,2) + 1
3: G(0,3) + 1 - 1 = G(0,3)
4: G(0,4) - 1 = 3
5: 3 - 1 = 2
6: 2 - 1 = 1
7: 1 - 1 = 0
8: 0 - 1 = -1 <----- G(1,2) = 8
```
### G(1,3):
```
1: 3 = G(0,1) + G(0,1) + G(0,1)
2: G(0,2) + G(0,2) + G(0,2) - 1 = G(0,2) + G(0,2) + 1
3: G(0,3) + G(0,3)
4: G(0,4) + 3
5: G(0,5) + 2
6: G(0,6) + 1
7: G(0,7)
8: 7
9: 6
10:5
11:4
12:3
13:2
14:1
15:0
16:-1 <----- G(1,3) = 16
```
### G(2,5):
```
1: 5 = G(1,1) + G(0,1)
2: G(1,2) + 1
3: G(1,3)
4: G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + 3
5: G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + 2
6: G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + 1
...
1024: -1 <----- G(2,5) = 1024
```
Doing some math, I found that
```
G(1,n-1) = 2ⁿ
G(2,n+6) ~ 2^G(2,n), large enough n.
```
And beyond that it tends to get a bit hairy.
In general, we have
```
G(n,k+G(n-1,1)) ~ G(n-1,G(n,k)), large enough n.
```
[Answer]
# Python 3, fωω+ω\*ω(99999)
```
from functools import*
h=lambda a,x,b:h(h(a,x,b-1),x-1,a)if x*b else a+b
def f(*x):
if(any(x[:2]):return reduce(lambda y,z:h(z,y,f(x[0],x[1]-1,*x[2:])),x[::-1])if x[0]*x[1]else(f(x[0]-1,f(x[0]-1,x[0],*x[2:]))if x[0]>x[1]else(f(x[1]-1,f(*([x[1]-1]*2+x[2:])),*x[2:])))
for a,k in enumerate(x):if k:return f(*[f(*[k]*a,k-1,*x[a+1:])]*a,k-1,*x[a+1:])
return 0
x,s,g,e,r,z=9**9**9**99,"f(*[%s]*%s)",lambda a,b:a%((b,)*a.count("%")),"x*=eval(\"%s\");","x","x=g(e,g(reduce(g,[s]*x,s),r));"
print(exec(z*x)or eval(r))
```
I'll get an explanation up soon.
[Answer]
# [Python 3](https://docs.python.org/3/), ~ fε0(999)
```
N=9**9**9
def f(a,n):
if a[0]==[]:return a[1:]
if a[0][0]==[]:return[a[0][1:]]*n+a[1:]
return [f(a[0],n)]+a[1:]
a=eval("["*N+"]"*N)
n=2
while a:a=f(a,n);n+=1
print(n)
```
[Try it online!](https://tio.run/##Vc7BCsIwDAbge5@i9NRuHpx6quQV9gIlh4AtK4w4Sqf49DVoEbwEki/5yfaqy53Prc1wUbeYdLJ0YOeVzklTOCJAQF9i3QtLP3n8yT@Gz0gcBx77Yj8LkikosdiFID5otSaYYR4NSnWK4aSeS16jJk/wfePKI0xqK5mrZdfaGw "Python 3 – Try It Online")
[Answer]
# Python 3, 323 bytes, g9e9(9)
```
exec("""a=`x:9**x
n=`a,f:`x:a and n(a-1,f)(f(x))or x
c=`n:`l:l[~n](l)
e=`x:n(x,c(0))([x,`l:[a(l[0]),n(*l)],c(0),`l:[a(l[0]),l[2](l[:2])[1]]+map(`i:l[1]((l[0],i))[1],l[2:])]+list(map(c,range(a(x),1,-1))))[1]
f=`l:[l[1](l[0]),e(l[1](l[0]))(l)[1]]
g=`x:e(x)((x,f))[1]((x,a))[1](x)
print(n(9e9,g)(9))""".replace('`','lambda '))
```
[Try it online!](https://tio.run/##VVAxbsMwDNz1CsOLSYcp4nSyAL9EECDWkV0DCmO4HtQlX3ckZSi68Xh3vAPX3/37IZ/H4aMfoa5rHlzUfdtGJYNjmnSCXLHcKgE@dzQhTBARH1sV1Tg40S7oYJ5iIaDy2S0QaYQLIphIiTUMwVwskkAb0Bbu3z6Ya3IbfbVoOmtPd17BLelqZ6FIaMHMZKG2aE9h@dkhq0baWGYPnCpRR@cOsSjVNOSAcuGd4eEPYKqag9Sc6/rkhVR5Ks488XuKqNZtkR0Eet/TjNAjphd9bH4NPHpoXENN4PvXjasG8The "Python 3 – Try It Online")
## Explanation
Python 3 is a truly recursive language, this means that not only can a function call itself, a function can also take other functions as input or output functions. Using functions to make themselves better is what my program is based on.
f=lambda x,a:[a(x),e(x)((x,a))[1]]
### Definition
```
a(x)=9^x
b(x,f)=a(x), f^x
c(n)(*l)=l[~n](l)
c(0)=c0 <=> c0(…,f)=f(…,f)
d(x,b,c,*l)=a(x), c0(x,b), b(x,c0), b(x,f) for f in l
e(x)=c0^x(x,b,c0,d,c(a(x)),c(a(x)-1),c(a(x)-2),…,c(3),c(2),c(1))[1]
f(x,a)=a(x),e(a(x))(x,a)[1](x)
g(x)=e(x)(x,f)[1](x,a)[1](x)
myNumber=g^9e9(9)
```
### Definition explained
`a(x)=9^x` a is the base function, I chose this function because x>0=>a(x)>x` which avoids fixed points.
`b(x,f)=a(x), f^x` b is the general improving function, it takes in any function and outputs a better version of it.
b can even be applied to itself: `b(x,b)[1]=b^x` `b(x,b^x)[1]=b^(x*x)`
but to fully use the power of `b` to improve `b` you need to take the output of b and use it as the new b, this is what c0 does:
`c0(…,f)=f(…,f)`
`c0(x,b^x)=b^x(x,b^x)[1]>b^(9↑↑x)`
the more general c(n) function takes the n last argument (starting from 0) so
`c(1)(…,f,a)=f(…,f,a)` and `c(2)(…,f,a,b)=f(…,f,a,b)`. `*l` means l is an array and `l[~n]` takes the n last argument
`d(x,b,c,*l)=a(x), c0(x,b), b(x,c0), b(x,f) for f in l` d uses c0 to upgrade b and b to upgrade all of the other input functions (of which there can be any amount because of the list)
`d(x,b,c,d)>9^x,b^x,c^x,d^x` and `d²(x,b,c,d)>a²(x), b^(9↑↑x), c^(9↑↑x), d^(9↑↑x)`
but d gets even better if you combine it with c:
`c0²(x,b,c0,d)=d^x(9^x,b^x,c0^x,d^x)=…`
`c0(x,b,c0,d,c1)=c1(x,b,c0,d,c1)=d(x,b,c0,d,c1)=9^x,b^x,c0^x,d^x,c1^x`
`c0²(x,b,c0,d,c1)=c0(9^x,b^x,c0^x,d^x,c1^x)=c1^x(9^x,b^x,c0^x,d^x,c1^x)=…`
the more c(x) you add at the end the more powerful it becomes. The first c0 always remains d: `c0(x,b,c0,d,c4,c3,c2,c1)=c1(…)=c2(…)=c3(…)=c4(…)=d(x,b,c0,d,cX,cX-1,…,c3,c2,c1)=…`
But the second leaves iterated versions behind:
```
c0²(x+1,b,c0,d,c4,c3,c2,c1)
=c0(9^x+1,b^x+1,c0^x+1,d^x+1,c4^x+1,c3^x+1,c2^x+1,c1^x+1)
=c1^x(c2^x(c3^x(c4^x(d^x(9^x+1,b^x+1,c0^x+1,d^x+1,c4^x+1,c3^x+1,c2^x+1,c1^x+1)))))
```
When `d^x` is finally calculated `c4` will take a much more iterated version of `d` the next time. When `c4^x` is finally calculated `c3` will take a much more iterated version of `c4`,…
This creates a really powerful version of iteration because `d`:
1. Improves `b` using `c0`
2. Improves `c0` using `b`
3. Improves all the layers of nesting using `b`
The improves themselves improve, this means d becomes more powerful when it is iterated more.
Creating this long chain of c is what what `e(x)=c0^x(x,b,c0,d,c(a(x)),c(a(x)-1),c(a(x)-2),…,c(3),c(2),c(1))[1]` does.
It uses `c0^x` to bypass that `c0` would just give `d`.
The `[1]` means that it will eventually return the second output of `d^…`. So `b^…`.
At this point I couldn't think of any thing to do with e(x) to significantly increase it's output except increasing input.
So `f(x,a)=a(x),e(a(x))(x,a)[1](x)` uses the `b^…` generated by `e(x)` to output a better base function and uses that base function to call `e(x)` with a bigger input.
`g(x)=e(x)(x,f)[1](x,a)[1](x)` uses a final `e(x)` to nest `f` and produces a really powerful function.
### Fgh approximation
I will need help approximating this number with any sort of fgh.
**Old version**: fωω6(fωω5 (9e999)), [Try it online!](https://tio.run/##bZHvasMgFMW/5ylECHpJMra1G4vgu2jU/IHUlrQM9/TZvS5hLdsHUc/5neMFL1@38RwP6xpScFII4UPPrIygCjb1LOJG1@YF8OA0t@VV81LGKgs@CxIXSFLrTe/PC5vYFNli4xAyTUXMVRg4aoMBRXwzEU0PTU1Uvsp1P1Wblcdyla@4fcYhANHEwnwNrOVQDNrEOqkMcSsTcDgvMnzaWVITLyMFYrNFBpqkTvBIABSdNr0ySQ3ylewesKpw2nRq1w@kd7vltXHqzj2S6@6AoI1Xj8wbMf4RG7UJ6g/5nkfcYb/Dl2WKNznIj3r8dbEKM6nCRBvatgWQI/xvo4f/@7SEy2xdkMKIWsz21HnLBMC6fgM "Python 3 – Try It Online") [Revision history of explanation](https://codegolf.stackexchange.com/revisions/151329/3)
[Answer]
# Ruby, fε02(5), 271 bytes
```
m=->n{x="";(0..n).map{|k|x+="->f#{k}{"};x+="->k{"+"y=#{n<1??k:"f1"};k.times{y=f0[y]};y";(2..n).map{|l|x+="[f#{l}]"};eval x+(n<1?"":"[k]")+"}"*(n+2)}
g=->z{t="m[#{z}]";(0...z).map{|j|t+="[m[#{z-j-1}]]"};eval t+"[->n{n+n}][#{z}]"}
p m[5][m[4]][m[3]][m[2]][m[1]][m[0]][g][6]
```
[Try it online!](https://tio.run/##RY/BboMwDIbvfYrKXICICNh2oCztg0Q@tFKp1pCo2thEMH52GtKqu3yS9fv/ZH//nvyyWFXsHY0KoE1LKV0m7fFGs5lHoaDYdwkZJuD2MRoCAV4l5D6rw8HsoKtCZuTwZc8/5FVXao/c@iCr/2V9lOng6hnD/vnv2G9Hka4SgB1og5AJYMhTJ@qMN5dw1ESDAqsTmkIn3ianp@86D6svhsW1qBhf1kGAXh9ywjE@y7y5ba3@wFB4x5VvkXVkFVkGXlA3ed40DS7LHQ)
This is based off of the [m(n) map](http://googology.wikia.com/wiki/M(n)_map).
## Explanation:
`m[0][f0][k] = f0[f0[...f0[k]...]]` with `k` iterations of `f0`.
`m[1][f0][f1][k] = f0[f0[...f0[f1]...]][k]` with `k` iterations of `f0`.
`m[2][f0][f1][f2][k] = f0[f0[...f0[f1]...]][f2][k]` with `k` iterations of `f0`.
In general, `m[n]` takes in `n+2` arguments, iterates the first argument, `f0`, `k` times onto the second argument, and then applies the resulting function onto the third argument (if it exists), then applies the resulting function onto the fourth argument (if it exists), etc.
### Examples
`m[0][n↦n+1][3] = (((3+1)+1)+1 = 6`
In general, `m[0][n↦n+1] = n↦2n`.
`m[0][m[0][n↦n+1]][3] = m[0][n↦2n][3] = 2(2(2(3))) = 24`
In general, `m[0][m[0][n↦n+1]] = n↦n*2^n`.
```
m[1][m[0]][3]
= m[0][m[0][m[0][n↦n+1]]][3]
= m[0][m[0][n↦2n]][3]
= m[0][n↦n*2^n][3]
= (n↦n*2^n)[(n↦n*2^n)[n↦n*2^n(3)]]
= (n↦n*2^n)[(n↦n*2^n)[24]]
= (n↦n*2^n)[402653184]
= 402653184*2^402653184
```
In general, `m[1][m[0]][n↦n+1] = f_ω` in the fast-growing hierarchy.
---
```
g[z] = m[z][m[z-1]][m[z-2]]...[m[1]][m[0]][n↦2n][z]
```
and the final output being
```
m[5][m[4]][m[3]][m[2]][m[1]][m[0]][g][6]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 181 bytes
```
def B(s):
D=range(1,s);B=[[A]for A in D]+[[0]]
for C in B[::-1]:
for F in D:C+=[B[C[-1]][C[0]]]
A=1;E=B[0]
while s//A*E[:A]!=E:A*=2
return A
A=0
while B(2**A)<99:A+=1
print A
```
[Try it online!](https://tio.run/##JYvNDoIwEITvfYr1BkXDz43iHraAL7HpwcQiJKaQgjE@fS14msw38y3fbZxdFcLDDqCTNVUCOvR397RJeV7TRiMzmWH2QDA56EzGXBgjYEftjjQrdSlNFA92O26qzZA1txwXEyMq0SEsmx51bAI@4/SysOY5yZ4VmRP2iiRWArzd3t4BCcJC/G86qaSk9FrXijIsxeIntwGF8AM "Python 2 – Try It Online")
Much, much larger than Loader’s number. It is well defined.
Nothing new. This is known as the Inverse Laver function.
[Answer]
# Javascript, 483 bytes
So, I'm just reusing a program I wrote for "Golf a number bigger than TREE(3)". The program results in \$f\_{TFBO+1}(3) = f\_{TFBO}(f\_{TFBO}(f\_{TFBO}(3)))\$ in the fast-growing hierarchy (3rd place), where \${TFBO}\$ is the Takeuti-Feferman-Buchholz Ordinal \$\psi(\Omega\_{\omega+1})\$. It uses Buchholz hydras and implements the BH function. Here is my compressed code, which was done with Naruyoko's Javascript compressor:
```
_="69{%t.length-1D*6m#{%B]}*6s#{t.splice(m#,14*@n=1;*6e#{7==0/s#;if(9>1/$i=0;i<n;i:t'B-1]4}}7>0&&typeof t==\"number\"/$i=98t[i]<m#8i--/}@s;$j5i8j <= 98j:s't[j]4@?5s;?[j]=?[i]-1;?[l(?)]=0;s#;$k508k <= l(?)8k:t'?[k]4}7==A/B]=n+1Dn += 1;%tD*6b(k/i5[\"+\",0];$l508l < k-28l:i'A)}while(l(i)>=0/i=e(i4%nD*Console.log(b(b(b(3))));#(t)$for(let %return '.push(*\n /){4)D5 = 6function 7if(m#8; 9l#:++/?sa@var A\"w\"Bt[9D;}";for($ of"DBA@?:987654/*'%$#")with(_.split($))_=join(pop());eval(_)
```
This is basically incomprehensible, with only fragments of the original code revealing themselves, so here is the original code:
```
function l(t){return t.length-1;}
function m(t){return t[l(t)]}
function s(t){t.splice(m(t),1);}
var n=1;
function e(t){if(m(t)==0){s(t);if(l(t)>1){for(let i=0;i<n;i++){t.push(t[l(t)-1]);}}}if(m(t)>0&&typeof t=="number"){for(let i=l(t); t[i]<m(t); i--){}var s;for(let j = i; j <= l(t); j++){s.push(t[j]);}var sa = s;sa[j]=sa[i]-1;sa[l(sa)]=0;s(t);for(let k = 0; k <= l(sa); k++){t.push(sa[k]);}}if(m(t)=="w"){t[l(t)]=n+1;}n += 1;return t;}
function b(k){i = ["+",0];for(let l = 0; l < k-2; l++){i.push("w")}while(l(i)>=0){i=e(i);}return n;}
Console.log(b(b(b(3))));
```
# Explanation
This program, as I mentioned earlier implements Buchholz hydras, which are stored as arrays. The program has functions l, m and s, which just serve as shorthand for commonly repeated chunks of code. The function e takes a given hydra and expands it using rules.
It was proven by Buchholz that you can always kill a hydra in a very large, yet finite, amount of steps, so this is what the program uses. The function b(n) produces the hydra [+,0] and then a string of n-2 \$\omega\$s, and returns the number of steps it took to be killed.
The number which it returns is \$BH^3(3)\$, which is around \$f\_{\psi\_0(\varepsilon\_{\Omega\_\omega+1})+1}(3)\$ in the FGH.
# Size
The function \$BH(n)\$ which this program implements is proven to eventually dominate (overtakes) any function which is provably total in \$\Pi^1\_1\$-comprehension with bar induction (\$\Pi^1\_1-CA+BI\$).
In fact, even if I replaced "chain of n-2 \$\omega\$s" with "chain of n-2 ones", I would still get third place.
However, I have to say, Simply Beautiful Art, your achievement of second place is simply beautiful, and I could never beat it just by trivially this program. Since \$TFBO = \psi\_0(\varepsilon\_{\Omega\_\omega + 1})\$, I could say that \$TFBO\_2 = \psi\_0(\varepsilon\_{\Omega\_{TFBO} + 1})\$, and so on, if I allowed labels up to \$TFBO\_{TFBO\_{...}}\$ instead of just \$\omega\$, my new growth rate would fall around \$\psi\_0(\chi(\Omega))+1\$, which is tiny compared to \$\psi\_0(\chi(\Omega\_{M+\chi(\Omega\_M+1^{Ω\_{M+1}})}))+29\$
] |
[Question]
[
A [graphic sequence](http://mathworld.wolfram.com/GraphicSequence.html) is a sequence of positive integers each denoting the number of edges for a node in a [simple graph](http://mathworld.wolfram.com/SimpleGraph.html). For example the sequence `2 1 1` denotes a graph with 3 nodes one with 2 edges and 2 with one connection.
Not all sequences are graphic sequences. For example `2 1` is not a graphic sequence because there is no way to connect two nodes so that one of them has two edges.
---
# Task
You will take a sequence of integers by *any reasonable* method. This includes, *but is not limited to*, an array of integers and its size, a linked list of unsigned integers, and a vector of doubles. You may assume that there will be no zeros in the input. You may also assume the input is sorted from least to greatest or greatest to least.
You must output whether or not the sequence is a graphic sequence. A truthy value if it is a falsy value otherwise.
---
# Goal
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the number of bytes in your program
# Testcases
*Sorted greatest to least*
```
-> True
3 3 3 2 2 2 1 1 1 -> True
3 3 2 2 1 1 -> True
3 3 2 -> False
8 1 1 1 1 1 1 1 1 -> True
1 1 1 1 -> True
1 1 1 -> False
9 5 4 -> False
```
[Answer]
# Mathematica, 25 bytes
```
<<Combinatorica`
GraphicQ
```
Yeah, another builtin. (Takes the input as a list of positive integers.) Requires loading the `Combinatorica` package.
[Answer]
# [Python 2](https://docs.python.org/2/) (exit code), 53 bytes
```
l=input()
while any(l):l.sort();l[~l[-1]]-=1;l[-1]-=1
```
[Try it online!](https://tio.run/##XVDBioMwEL37FcFTC3ZxolFr6bELe9@beCjdQIUQJbVsvfTX3clMtEthYt68mfcyzjCN197K@ffaGS2gjsToJvwK/dCXOI5nc@zscB8324hbznbamG1tPm69Q/ZgmqdpdtC2uyMcCCGYUYkeg@vsKL7dXUfod9HDKL7sj36cnOtdvTZ8ns1Nz41KRJaINBEyEQV9EZcEVBs1@UIB5giQyiiRpAOmAJV7ClB0lZxgGUq@c2ZQBnk4kqspOxXex9NpEGUkqmiskNPxuKIC8JxeVVCzL0nvo7inCBJJ1eVd5qvll/3wKU@XBgucCF2Yh39H0bO8L7LijcG6Eo8K3oIfAU0kL5D3JpmDcOFhnkMuARxr7cW@KETV2vkW4Yn3BNGetqDaPw "Python 2 – Try It Online")
Outputs via exit code.
Uses a version of the Havel-Hakimi algorithm. Repeatedly decrements both the largest element `k` and the `k`'th largest element (not counting `k` itself), which corresponding to assigning an edge between the two vertices with those degrees. Terminates successfully when the list becomes all zeroes. Otherwise, if there's an index out of bounds, fails with error. Any negative values created also eventually lead to an out-of-bounds error.
[Answer]
## CJam (20 bytes)
```
{{W%(Wa*.+$_0a<!}g!}
```
[Online test suite](http://cjam.aditsu.net/#code=1%3AT(%3AF%3B%0AqN%25%7B%22-%3Erueals%22-%5B~%5D)%5C%24%0A%0A%7B%7BW%25(Wa*.%2B%24_0a%3C!%7Dg!%7D%0A%0A~%3D%7D%25&input=3%203%203%202%202%202%201%201%201%20-%3E%20True%0A3%203%202%202%201%201%20%20%20%20%20%20%20-%3E%20True%0A3%203%202%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20False%0A8%201%201%201%201%201%201%201%201%20-%3E%20True%0A1%201%201%201%20%20%20%20%20%20%20%20%20%20%20-%3E%20True%0A1%201%201%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20False%0A9%204%205%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20False%0A1%201%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20True%0A2%200%200%20%20%20%20%20%20%20%20%20%20%20%20%20-%3E%20False) including a couple of extra tests I added to catch bugs in some of my attempts.
This is an anonymous block (function) which takes an array of integers on the stack and leaves `0` or `1` on the stack. It assumes that the input is sorted ascending.
The input array may not be empty, but may contain zeroes, in accordance with OP's answer to my query on the subject of empty inputs.
### Dissection
This follows OP's answer in implementing the [Havel-Hakimi algorithm](https://en.wikipedia.org/wiki/Havel%E2%80%93Hakimi_algorithm).
```
{ e# Define a block
{ e# Do-while loop (which is the reason the array must be non-empty)
e# NB At this point the array is assumed to be non-empty and sorted
W% e# Reverse
(Wa*.+ e# Pop the first element and subtract 1 from that many subsequent
e# elements. If there aren't enough, it adds -1s to the end. That's
e# the reason for using W (i.e. -1) and .+ instead of 1 and .-
$ e# Sort, restoring that part of the invariant
_0a<! e# Continue looping if array >= [0]
e# Equivalently, break out of the loop if it starts with a negative
e# number or is empty
}g
! e# Logical not, so that an empty array becomes truthy and an array
e# with a negative number becomes falsy
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 108 bytes
Here is my implementation in Python. I'm sure it can be beaten by a more experienced golfer or mathematician. It implements the Havel-Hakimi algorithm.
```
def f(x):p=x[0]+1;x=sorted(x+[0]*p)[::-1];return~x[-1]and(p<2or f(sorted([a-1for a in x[1:p]]+x[p:])[::-1]))
```
[Try it online!](https://tio.run/nexus/python2#jY7BCsIwEETvfsUeE9uCqQqamqtf4C3kENoEBUlD0kJO/rXnGmiLpVp0mMsu83a2q5QGjQKmlgW@EQkpAvO1a1SFQhIXa4s5pRkRhVNN68wj8DhIUyF7ymsX2SHNZUZ0XEi4GQicUCtEErilYjiAcSe9V65BGvFtCr3z0WSwwMAYXFyrAK/mwDQ66hfwoR44y7tXU@Dw/mHmhYZp6FvDMvDvS8cUdinsfwDd09RZKcuregE)
[Answer]
# [Haskell](https://www.haskell.org/), ~~102 98 95~~ 94 bytes
```
import Data.List
f(x:r)=length r>=x&&x>=0&&(f.reverse.sort$take x(pred<$>r)++drop x r)
f x=1<3
```
[Try it online!](https://tio.run/nexus/haskell#bY3NCoMwEITvPsUcJCgG8aeFthhPPfYNxEPA2EqrhjWUvL019g9K@S6zMzu7c9frkQyO0sj41E3GawN7oFDc1HA2F1ApLGO2FAljQRuTuiuaVDwtHd/Iq4INNKmm8EsKo6ihUcOCQq@FFWmRz73sBgg0IzwAmrrBwEcvNVpUVc1R5dyRraSOt/ky3Lh7Jl@c@SOTuv73Yr30WXdizzd860TGk6W1Rkt5fgA "Haskell – TIO Nexus")
Usage: `f [3,3,2,2,1,1]`, returns `True` or `False`. Assumes that the input ~~contains no zeros and~~ is sorted in descending order, as allowed in the challenge.
**Explanation:**
```
import Data.List -- import needed for sort
f (x:r) = -- x is the first list element, r the rest list
length r >= x -- the rest list r must be longer or equal x
&& x >= 0 -- and x must not be negative
&& (f . -- and the recursive call of f
reverse . sort $ -- with the descendingly sorted list
take x(pred<$>r) -- of the first x elements of r subtracted by 1
++ drop x r -- and the rest of r
) -- must be true
f [] = True -- if the list is empty, return True
```
Edit: This seems to follow the Havel-Hakimi mentioned in other answers, though I did not know of this algorithm when writing the answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly)
```
ṢṚḢ-€+ƊƊƬ>-Ȧ
```
A monadic Link accepting a list which yields `1` if the answers are consistent otherwise `0`.
**[Try it online!](https://tio.run/##y0rNyan8///hzkUPd856uGOR7qOmNdrHuoBwjZ3uiWX///@PNjTRUTA0AGJzIDbWUQByLXQUzHQUoHwwBrEtwBIgphGQMgGrMYEoM4oFAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzkUPd856uGOR7qOmNdrHuoBwjZ3uiWX/j056uHMGUOzonsPtQMobiCP//4@OjuXSiTbWUYAgIxgyhCCEJEIYSQzEtIArRkMgSaw8ENNSR8FUR8EklisWAA "Jelly – Try It Online").
### How?
```
ṢṚḢ-€+ƊƊƬ>-Ȧ - Link: list of integers
Ƭ - collect up while results change:
Ɗ - last three links as a monad i.e. f(L):
Ṣ - sort [min(L),...,max(L)]
Ṛ - reverse [max(L),...,min(L)]
Ɗ - last three links as a monad i.e. f([a,b,c,...,x]):
Ḣ - pop head a
-€ - -1 for each [-1,-1,...,-1] (length a)
+ - add to head result (vectorises) [b-1,c-1,...,x-1,-1,-1,...]
>- - greater than -1? (vectorises)
Ȧ - Any and all? (0 if empty or contains a 0 when flattened, else 1)
```
[Answer]
# [R](https://www.r-project.org/), 20 bytes
```
igraph::is_graphical
```
Mathematica isn't the only language with built-ins! ;-)
The `igraph` package needs to be installed. Takes input as a vector of integers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 25 bytes
```
D0*«¹v{R¬U¦X¹gn‚£`s<ì}0QP
```
[Try it online!](https://tio.run/nexus/05ab1e#@@9ioHVo9aGdZdVBh9aEHloWcWhnet6jhlmHFicU2xxeU2sQGPD/f7SxjrGOERgagmDs17x83eTE5IxUAA "05AB1E – TIO Nexus")
**Explanation**
```
D0*« # extend the input list with as many zeroes as it has elements
¹v # len(input) times do:
{R # sort in descending order
¬U¦X # extract the first element of the list
¹gn‚ # pair it with len(input)^2
£ # partition the list in 2 parts, the first the size of the
# extracted element, the second containing the rest of the list
` # split these list to stack (the second on top)
s< # decrement the elements of the first list by 1
ì # prepend it to the rest of the list
} # end loop
0Q # compare each element in the resulting list with 0
P # reduce list by multiplication
```
[Answer]
# JavaScript (ES6), ~~82 80~~ 76 bytes
```
f=([$,..._])=>1/$?_.length>=$&$>=0&f(_.map(a=>a-($-->0)).sort((a,b)=>b-a)):1
```
Thanks to ETHproductions for saving many bytes!
## Usage
```
f=([$,..._])=>1/$?_.length>=$&$>=0&f(_.map(a=>a-($-->0)).sort((a,b)=>b-a)):1
f([3,3,3,2,2,2,1,1,1])
```
## Output
```
1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 90 bytes
[Ported from this question which turned out to be a duplicate of this.](https://codegolf.stackexchange.com/a/185946/52194) Uses Havel-Hakimi since that was the one mentioned in that question.
```
->a{b=1;(a.sort_by!(&:-@);i=a.shift;a.map!{|e|i>0&&e>0?(i-=1;e-1):e};b&&=i<1)while[]!=a;b}
```
[Try it online!](https://tio.run/##bVHbaoQwEH3vV5gXMaCSideu1fY/tlJiUTZg6bIXyrK7326TGS1LLDhmMufMYebkcO4u01C/T1Gjrl0NVaDi4/fh9NFdWOBvojde6dqUdno4VSr@Unt2vfU33Qjf7xvxGujINPUR8E1/rzrfr/UL8J@dHvtty2pVdfdp7zE2xJ9qHINtFnpJ6InQk6GX49/kBSZZy58eqekCg8FM4sAJAhL1YA2DUX/GDzI8CroYKhR0plQxEpDOIQkVpJq7mpYiZoEEBUpcY75j2LxEAGgv25Uj2ULS1cyIn8/tEpnLPFQvF7vsUoKmFrOcmdRRJA48RIbjkO8oS87Dn4U2y8kpO44jKOkh1v7LNRf@KTn3lk@/ "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[D{RćD1‹#Å0<0ζO})dW
```
Port of [*JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/185954/52210), so make sure to upvote him!!
[Try it online](https://tio.run/##yy9OTMpM/f8/2qU66Ei7i@Gjhp3Kh1sNbAzObfOv1UwJB8oYmugYGugYmusYGuuY6FjomOmAmSAEZFgARYC0kQ5QmRlQHihkFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/aJfqoCPtLoaPGnYqH241sDE4t82/VjMl/L@OZsz/6GhjHRA0AkNDEIzViYaJIPGAtAVEHgGBYmgsIG2pY6pjAuKb6Bga6Bia6xga65joWOiY6YCZIARkWABFgDTQChOgjAlIzig2FgA).
**Explanation:**
```
[ # Start an infinite loop:
D # Duplicate the current list
# (which is the implicit input-list in the first iteration)
{R # Sort it from highest to lowest
ć # Extract the head; pop and push the remainder and head
D1‹ # If the head is 0 or negative:
# # Stop the infinite loop
Å0< # Create a list of the head amount of -1
0ζ # Zip/transpose it with the remainder list, with 0 as filler
O # Sum each pair
}) # After the loop: wrap everything on the stack into a list
d # Check for each value if it's non-negative (>= 0)
# (resulting in 1/0 for truthy/falsey respectively)
W # Get the flattened minimum (so basically check if none are falsey)
# (which is output implicitly as result)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~14~~ 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ε▼ü*æε<%)4‼♂
```
[Run and debug it](https://staxlang.xyz/#p=ee1f812a91ee3c252934130b&i=[]%0A[3+3+3+2+2+2+1+1+1]%0A[3+3+2+2+1+1]%0A[3+3+2]%0A[8+1+1+1+1+1+1+1+1]%0A[1+1+1+1]%0A[1+1+1]%0A[9+5+4]&a=1&m=2)
This program handles empty and unsorted inputs.
] |
[Question]
[
In case there's any doubt: `Nan = Non-numeric datatype` for the purposes of this challenge.
---
Write a program or function that takes a matrix / array as input, as well as a list of column indices.
The challenge is to remove the rows where all elements in the specified columns are `Nan`. It doesn't matter if other elements in the row are numeric or not. The following examples will hopefully make this more clear (it's one-indexed):
```
Input array:
16 NaN 3 13
5 11 NaN 8
NaN 7 NaN 12
4 14 -15 1
Input column index: [1 3]
Output array:
16 NaN 3 13
5 11 NaN 8
4 14 -15 1
----
Input array:
16 NaN 3 13
5 11 NaN 8
NaN 7 NaN 12
4 14 -15 1
Input column index: 3
Output array =
16 NaN 3 13
4 14 -15 1
----
Input array:
NaN NaN NaN NaN
NaN NaN NaN NaN
NaN NaN NaN NaN
NaN NaN NaN NaN
Input column index: 1 2 4
Output array:
[]
```
**Rules and clarifications:**
* The matrix will always be non-empty
* The numeric values will be finite, but not necessarily integers or positive values
* The column index vector can be empty (in which case no rows will be removed)
* The column index will never have values exceeding the matrix dimensions
* You can assume there won't be duplicates in the column index list
* You can choose if you want to use zero- or one-indexed values (please specify)
* You can take the input on any convenient format
+ Array as list of lists is OK. The column indices can be separate arguments
* `ans =` and similar is accepted in output
* You are free to choose what type of non-numeric datatype you want to use
+ It should be impossible to perform arithmetic operations with this datatype, or convert it to a finite number using functions such as `float(x)`.
This is code golf, so shortest code in bytes win.
[Answer]
# Pyth, ~~16~~ ~~19~~ ~~10~~ ~~9~~ ~~7~~ 10 Bytes
Column indices start at zero. Input is a list of lists. Uses an empty string as non-numeric value. Takes list of column indices on the first line and the Matrix with the values on the second line.
```
?Qf-QxkTEE
```
[Try it online!](http://pyth.herokuapp.com/?code=%3FQf-QxkTEE&input=%5B0%2C2%5D%0A%5B%5B16%2C+%22%22%2C+3%2C+13%5D%2C%5B5%2C11%2C%22%22%2C8%2C8%5D%2C%5B%22%22%2C7%2C%22%22%2C12%5D%2C%5B4%2C14%2C-15%2C1%5D%5D%0A&test_suite=1&test_suite_input=%5B0%2C2%5D%0A%5B%5B16%2C+%22%22%2C+3%2C+13%5D%2C%5B5%2C11%2C%22%22%2C8%2C8%5D%2C%5B%22%22%2C7%2C%22%22%2C12%5D%5D%0A%5B%5D%0A%5B%5B1%2C%22%22%2C%22%22%5D%2C%5B4%2C%22%22%2C6%5D%5D%0A%5B0%2C1%2C2%5D%0A%5B%5B1%2C%22%22%2C%22%22%5D%2C%5B%22%22%2C%22%22%2C%22%22%5D%5D%0A%5B1%2C2%5D%0A%5B%5B1%2C%22%22%2C%22%22%5D%2C%5B%22%22%2C%22%22%2C%22%22%5D%5D&debug=0&input_size=2)
## Explanation
```
?Qf-QxkTEE # Implicit: Q=column indices, E=Matrix
?Q E # If column list is empty no rows get removed
f E # filter the given matrix by each row T
xkT # Get the indices of all occurences of an emtpy string (k)
-Q # If the indices match with the given column indices, remove the row
```
**Update:** My first solution handled an empty list of column indices wrong. Fixed it (pretty ugly) at the cost of 3 Bytes. Gonna try to do it better after work...
**Update 2:** Golfed it down to ~~10~~ ~~9~~ 7 bytes, with some help from @FryAmTheEggman an by improving the algorithm significantly.
**Update3:** Fixed a bug @ThomasKwa discovered. His proposed 7-byte solution did not handle empty column indices right, so I just catch that case with a ternary here. I don't see how I can shorten this atm.
[Answer]
# JavaScript (ES6), ~~48~~ 46 bytes
```
(a,l)=>a.filter(r=>l.some(c=>r[a=0,c]<1/0)||a)
```
## Explanation
Expects an array of rows as arrays, and an array of 0-indexed numbers for the columns to check. Returns an array of arrays.
Straight-forward `filter` and `some`. Checks for `NaN` by using `n < Infinity` (`true` for finite numbers, `false` for `NaN`s).
```
var solution =
(a,l)=>
a.filter(r=> // for each row r
l.some(c=> // for each column to check c
r[a=0, // set a to false so we know the some was executed
c]<1/0 // if any are not NaN, do not remove the row
)
||a // default to a because if l is of length 0, some returns false but
) // we must return true
```
```
<textarea id="matrix" rows="5" cols="40">16 NaN 3 13
5 11 NaN 8
NaN 7 NaN 12
4 14 -15 1</textarea><br />
<input type="text" id="columns" value="0 2" />
<button onclick="result.textContent=solution(matrix.value.split('\n').map(l=>l.split(' ').map(n=>+n)),(columns.value.match(/\d+/g)||[]).map(n=>+n)).join('\n')">Go</button>
<pre id="result"></pre>
```
[Answer]
## CJam, 18 bytes
```
{{1$\f=_!\se|},\;}
```
An unnamed block (function) expecting the matrix and the zero-based column indices on the stack (the matrix on top), which leaves the filtered matrix on the stack. I'm using the empty array `""` as the non-numeric value.
[Test it here.](http://cjam.aditsu.net/#code=%5B0%202%5D%20%5B%5B16%20L%203%2013%5D%5B%205%2011%20L%208%5D%5B%20L%207%20L%2012%5D%5B%204%2014%2015%201%5D%5D%0A%0A%7B%7B1%24%5Cf%3D_!%5Cse%7C%7D%2C%5C%3B%7D~%0A%20%20%20%20%20%20%20%0Aed)
### Explanation
```
{ e# Filter the matrix rows based on the result of this block...
1$ e# Copy the column indices.
\f= e# Map them to the corresponding cell in the current row.
_! e# Duplicate, logical NOT. Gives 1 for empty column list, 0 otherwise.
\s e# Convert other copy to string. If the array contained only empty arrays, this
e# will be an empty string which is falsy. Otherwise it will contain the numbers
e# that were left after filtering, so it's non-empty and truthy.
e| e# Logical OR.
},
\; e# Discard the column indices.
```
[Answer]
# APL, 19 bytes
```
{⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]}
```
The left argument should be a list of indices (and it must be a list, not a scalar), the right argument is the matrix. APL has two datatypes, numbers and characters, so this filters out the character types.
Tests:
```
m1 m2
16 NaN 3 13 NaN NaN NaN NaN
5 11 NaN 8 NaN NaN NaN NaN
NaN 7 NaN 12 NaN NaN NaN NaN
4 14 ¯15 1 NaN NaN NaN NaN
1 3 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16 NaN 3 13
5 11 NaN 8
4 14 ¯15 1
(,3) {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16 NaN 3 13
4 14 ¯15 1
1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ this shows nothing
⍴1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ the nothing is in fact a 0-by-4 matrix
0 4
```
Explanation:
* `⍵[;⍺]`: select the given columns from the matrix
* `0↑¨`: take the first `0` elements from the start of each item
* `⍬∘≡¨`: compare to the numerical empty list
* `∨/`: see in which of the rows at least one item matches
* `⍵⌿⍨`: select those rows from the matrix
[Answer]
# MATLAB, ~~32~~ 28 bytes
I'll answer my own question for once. The best I can do in MATLAB is 28 bytes. ~~I was hoping to avoid using both `all` and `isnan` somehow, but haven't found a way yet.~~
```
@(A,c)A(any(A(:,c)<inf,2),:)
```
Test:
```
A =
35 1 NaN NaN NaN 24
3 32 NaN 21 23 25
31 NaN NaN NaN 27 20
NaN 28 NaN 17 NaN 15
30 5 NaN 12 14 NaN
4 36 NaN 13 18 11
f(A,[3,5])
ans =
3 32 NaN 21 23 25
31 NaN NaN NaN 27 20
30 5 NaN 12 14 NaN
4 36 NaN 13 18 11
```
This is an unnamed anonymous function that takes the input matrix as the first input variable, and a list of column indices as the second.
In MATLAB, `NaN < Inf` evaluates to false. It can be assumed that all values are finite, thus checking if values are less than `inf` is equivalent to checking if they are non-numeric. `any(...,2)` checks if there are any true values along the second dimension (rows). If that's the case, then those rows will be returned.
**Old version:**
```
@(A,c)A(~all(isnan(A(:,c)),2),:)
```
`isnan(A(:,c))` returns an array with booleans for the specified columns. `~all(isnan(A(:,c)),2)` checks if all values along the second dimension (rows) are non-numeric, and negates it. This results in a boolean vector with ones in the positions we want to keep. `A(~all(isnan(A(:,c)),2),:)` uses logical indexing to extract the entire rows for `A`.
---
The following 24 byte solution would work if the values were guaranteed to be non-zero:
```
@(A,c)A(any(A(:,c),2),:)
```
[Answer]
## Ruby, 48 bytes
```
->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}}
```
Input is 0-based indices1.
Fairly self-explanatory, actually. `select` elements from the array where `any?` of the indices `map`ped over the row are `Fixnum`s.
Sample run:
```
irb(main):010:0> (->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}})[[[16,'',3,13],[5,11,'',8],['',7,'',12],[4,14,-15,1]],[0,2]]
=> [[16, "", 3, 13], [5, 11, "", 8], [4, 14, -15, 1]]
```
---
1: I *finally* spelled this word correctly on the first try! \o/
[Answer]
# K5, 15 bytes
This uses 0-indexed columns and K's natural list-of-lists matrix representation:
```
{x@&~&/'^x[;y]}
```
Index into the matrix (`x@`) the rows where (`&`) not all of each (`~&/'`) is null (`^`).
In action:
```
m: (16 0N 3 13;5 11 0N 8;0N 7 0N 12;4 14 -15 1);
f: {x@&~&/'^x[;y]};
f[m;0 2]
(16 0N 3 13
5 11 0N 8
4 14 -15 1)
f[m;2]
(16 0N 3 13
4 14 -15 1)
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 15 ~~16~~ bytes
```
tiZ)tn?ZN!XA~Y)
```
`NaN` is represented in the input as `N`. Indexing is 1-based. For example, in the first test case the input is
```
[16 N 3 13; 5 11 N 8; N 7 N 12; 4 14 -15 1]
[1 3]
```
[**Try it online!**](http://matl.tryitonline.net/#code=dGlaKXRuP1pOIVhBflkp&input=WzE2IE4gMyAxMzsgNSAxMSBOIDg7IE4gNyBOIDEyOyA0IDE0IC0xNSAxXQpbMSAzXQ)
### Explanation
```
t % implicitly input matrix, M. Duplicate
i % input vector specifying columns
Z) % matrix N containing those columns of M
tn? % duplicate matrix N. If non-empty ...
ZN % true for NaN values in matrix N
! % transpose
XA % "all" within each column: gives true for rows of N that contained all NaN's
~ % logical negate
Y) % apply this logical index as a row index into the copy of M that was left
% at the bottom of the stack
% ... implicitly end if
% implictly display stack contents. If the input vector was empty, the stack
% contains the original matrix M and an empty matrix. The latter produces no
% displayed output. If the input vector was non-empty, the stack contains the
% resulting matrix N
```
[Answer]
# R, 49 bytes
```
function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]
```
Input is 1-based. The function takes a matrix (`m`) and a vector of column indices (`j`) which may be missing.
Two test cases:
```
> f <- function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]
> f(m)
V1 V2 V3 V4
[1,] 16 NaN 3 13
[2,] 5 11 NaN 8
[3,] NaN 7 NaN 12
[4,] 4 14 -15 1
> f(m, c(1,3))
V1 V2 V3 V4
[1,] 16 NaN 3 13
[2,] 5 11 NaN 8
[3,] 4 14 -15 1
```
[Answer]
# Lua, 148 Bytes
A function that takes a matrix and an array as input, and output a matrix with the corresponding rows at `nil`. As arrays are quite the same as C's arrays, nihilating is like `free()`ing it as the garbage collector isn't far away.
Arrays are 1-indexed in Lua, and I use the string `"NaN"` as a non-nomber element.
```
function f(m,l)c=1 while(c<#m)do x=0 for j=1,#l do x=x+((type(m[c][l[j]])=="number")and 0 or 1)end m[c]=(x<#l and m[c] or nil)c=c+1 end return m end
```
You can try [Lua online](http://www.lua.org/cgi-bin/demo), and copy/paste the following code sample to try this submission:
```
-- The function that does the stuff
function f(m,l)
c=1
while(c<#m)
do
x=0
for j=1,#l
do
x=x+((type(m[c][l[j]])=="number")and 0 or 1)
end
m[c]=(x<#l and m[c] or nil)
c=c+1
end
return m
end
-- A function to format matrixes into "readable" strings
function printMatrix(matrix,len)
s="{"
for v=1,len
do
if matrix[v]~=nil
then
s=s.."{"..table.concat(matrix[v],",").."}"..(v<len and",\n "or"")
end
end
s=s.."}"
print(s)
end
nan="NaN"
-- Datas in, indexed as matrices[testCase][row][column]
matrices={{{7,nan,5,3},{5,4,nan,4},{nan,4,nan,9},{5,7,9,8}},
{{16,nan,3,13},{5,11,nan,8},{nan,7,nan,12},{4,14,-15,1}},
{{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan}}}
indexes={{1,3},{3},{1,2,4}}
-- looping so we can test lots of things at once :)
for i=1,#matrices
do
print("\ninput: "..table.concat(indexes[i]," "))
printMatrix(matrices[i],4)
print("output:")
printMatrix(f(matrices[i],indexes[i]),4)
end
```
[Answer]
# Mathematica, ~~52~~ ~~51~~ ~~49~~ 46 bytes
```
Delete[#,Extract[#,{;;,#2}]~Position~{NaN..}]&
```
Input is [matrix as list of lists,vector of columns]
[Answer]
## Haskell, 39 bytes
```
m#[]=m
m#r=[l|l<-m,any(<1/0)$map(l!!)r]
```
This uses 0-based indices. Usage example (I'm using `sqrt(-1)` to create `NaN`s):
```
*Main> [[16,sqrt(-1),3,13], [5,11,sqrt(-1),8], [sqrt(-1),7,sqrt(-1),12], [4,14,-15,1]] # [0,2]
[[16.0,NaN,3.0,13.0],[5.0,11.0,NaN,8.0],[4.0,14.0,-15.0,1.0]]
```
It's just a simple filter as seen in other answers via list comprehension. The special case of an empty index list is caught separately.
] |
[Question]
[
This time around your goal is to find the maximum of 3 integers (from -(2^31) to 2^31 - 1 in binary 2's complement) without using branching or loops.
You are **only** allowed to use
* Inequality/Equality (`==`, `>`, `>=`, `<`, `<=`, `!=`) These count as **2** tokens.
* Arithmetic (`+`, `-`, `*`, `/`)
* Logical Operators (`!` not, `&&` and, `||` or)
* Bitwise Operators (`~` not, `&` and, `|` or, `^` xor, `<<`, `>>`, `>>>` arithmetic and logical left and right shifts)
* Constants. 0 tokens
* Variable assignment. 0 tokens
Input 3 variables as `a`, `b` and `c`. Output the maximum number.
Standard atomic code-golf rules apply. If you have any questions please leave them in the comments. One token is any of the above with the special rules.
[Answer]
# Javascript
**6 tokens**
```
function maxOf3(a, b, c) {
(b>a) && (a=b);
(c>a) && (a=c);
return a;
}
```
[Answer]
# Javascript 10 tokens
*Edit* Using < and \* instead of bit fiddling - as pointed out in comments, bits operations may fail for input near the range limit (over 30 bits)
```
function Max(x,y,z)
{
var d=y-x;
x=y-d*(d<0);
d=x-z;
return x-d*(d<0);
}
```
# C 8 tokens
Language agnostic in fact, any C like language will do. To be picky, in standard C it's not portable because right shift may not extend the sign (but in common implementations it does).
In C (and C++, C#, and Java I think) we can easily handle overflow problems using bigger temporary values:
```
int Max(int x, int y, int z)
{
long long X = x;
long long Y = y;
long long Z = z;
long long D = Y-X;
X=Y-((D>>63)&D);
D=X-Z;
return (int) (X-((D>>63)&D));
}
```
[Answer]
## C: 10 tokens
```
int max(int a, int b, int c)
{
a += (b > a) * (b - a);
a += (c > a) * (c - a);
return a;
}
```
Inspired by @openorclose's answer, but converted to C and made branchless using multiplication rather than short circuit boolean operators.
[Answer]
# Javascript
**14 tokens**
```
function max (a, b, c)
{
var ab = (a >= b) * a + (a < b) * b;
return (ab >= c) * ab + (ab < c) * c;
}
```
[Answer]
## Many languages (Python) (10 tokens)
```
def max3(x,y,z):
m = x ^ ((x ^ y) & -(x < y))
return m ^ ((m ^ z) & -(m < z))
print max3(-1,-2,-3) # -1
print max3(-1,2,10) # 10
```
<https://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax>
Oh, someone already posted it :)
[Answer]
# C++11: 15 tokens
Using only arithmetic and bitwise operators (since equality and boolean logic operators make it too easy)...
```
#include <iostream>
auto max(int32_t a, int32_t b, int32_t c)->int32_t {
return c - ((c - (a - ((a - b) & (a - b) >> 31))) & (c - (a - ((a - b) & (a - b) >> 31))) >> 31);
}
auto main()->int {
// test harness
std::cout << max(9, 38, 7) << std::endl;
return EXIT_SUCCESS;
}
```
[Answer]
# J (Not competing)
I was just wondering what the a solution in J would look like. This uses a `,` and a `#` though, so it won't be competing.
```
((a<b),(b<c),(c<a))#b,c,a
```
This would compete, but is way too long, with 9 tokens:
```
(b*a<:b)+(c*b<c)+(a*c<a)
```
[Answer]
we have the following assumptions:
* max(a;b)=(a+b + |a-b|)/2
* max(a;b;c)=max(max(a;b);c)
* abs(a)=(a + (a >> 31)) ^ (a >> 31)
we can use the pseudo-code:
>
> function max(a,b,c)
>
>
> {
>
>
> out1=( (a+b) + (( (a-b) + ((a-b) >> 31)) ^ ((a-b)>> 31))) div 2
>
>
> out2=( (out1+c) + (( (out1-c) + ((out1-c) >> 31)) ^ ((out1-c)>> 31))) div 2
>
>
> return out2
>
>
> }
>
>
>
[Answer]
## C# (2nd try)
I got it... No integrated functions...
But is it allowed to use other integrated datatypes or just plain int? If allowed I would propose:
```
int foo2(int a, int b, int c)
{
var x = new SortedList<int,int>();
x[a] = 1;
x[b] = 1;
x[c] = 1;
return x.Keys[2];
}
```
[Answer]
## javascript 8 tokens
although similar to @openorclose's answer, i do actually use the logical operators for the assignment itself.
```
function max( a, b, c ) {
x=( a > b && a) || b;
return ( x > c && x ) || c;
}
```
[fiddle](http://jsfiddle.net/mendelthecoder/Lj2zC/)
[Answer]
## R (10 tokens)
```
function max(a, b, c) {
max <- a
max <- max + (b - max) * (b > max)
max <- max + (c - max) * (c > max)
return(max)
}
```
[Answer]
## Brainfuck (Not competing)
```
>,[-<+>>>+<<]>,[-<+>>>+<<]>[>[-<->>]<<]<[-]>[-]>[-]<<<[->>>>+<<<<]>>>>[-<+>>>+<<]>,[-<+>>>+<<]>[>[-<->>]<<]<<
```
[Answer]
# TIS-100, 8 operations
```
MOV ACC UP #A
SUB UP #B
SUB 999
ADD 999
ADD UP #B
SUB UP #C
SUB 999
ADD 999
ADD UP #C
MOV ACC DOWN
```
The provider(UP) only do MOVs so not shown in the code
Maybe not work when too near the 999 edge
[Answer]
VBA (6 tokens)
```
Function max3(a As Integer, b As Integer, c As Integer)
i = IIf(a >= b And a >= c, a, IIf(b >= c, b, c))
max3 = i
End Function
```
not sure if this is not branching.
[Answer]
## JavaScript: 4 tokens (\*\* based on broad interpretation of "assignment"!)
Obviously my score of 4 is extremely generous/lenient!
To arrive at that score I've assumed "assignment" (worth 0 tokens in the question) includes such things as additive assignment, subtractive assignment, multiplicative assignment, and XOR-ing (`^=`) assignment
```
function f(a, b, c) {
d = a;
d -= b;
d = d >= 0;
a *= d; //a = a if (a>=b), else 0
d ^= true; //invert d
b *= d; //b = b if (b<a), else 0
a += b; //a is now max(a,b)
d = a;
d -= c;
d = d >= 0;
a *= d; //a = a if (a>=c), else 0
d ^= true; //invert d
c *= d; //c = c if (c<a), else 0
a += c; //a is now max(max(a,b),c)
return a;
}
```
If those assignments actually count the score is 14 :)
] |
[Question]
[
Given a list of lists of positive integers, output a subset of them so their union forms a continuous non-empty range with no numbers missing. For example, consider this input:
```
[
[1, 2, 3, 5],
[2, 4, 6],
[7, 9, 11]
]
```
The union of the first 2 forms a continuous sequence: `[1, 2, 3, 4, 5, 6]` with no numbers missing. Adding the last one would create `[1, 2, 3, 4, 5, 6, 7, 9, 11]` which is missing `8` and `10` so would not be a valid answer.
Output can be either the indexes of the included lists or the lists themselves.
Lists are guaranteed to be sorted, and the list of lists will also be sorted lexicography. All lists will have at least one element. There may be more than one valid solution, if so you may choose output any of them, or all of them, or some of them. If you output multiple solutions all must be valid and they must be clearly separated.
There will never be no solutions.
## Test cases
| Input | Output |
| --- | --- |
| `[[1, 2, 3]]` | `0` |
| `[[1, 3], [2, 4]]` | `0, 1` |
| `[[2, 4], [4, 23], [8, 10], [8, 12], [9, 13], [10, 23], [11, 14]]` | `2, 3, 4, 6` |
| `[[1, 3], [2, 4], [5,7], [6,8]]` | `0,1` OR `2,3` OR `0,1,2,3` |
| `[[1, 17], [2,23], [3,42], [4,17], [5, 3912], [6]]` | `5` |
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, ~~61~~ 57 bytes
```
[ all-subsets rest [ concat dup minmax [a,b] ⊃ ] find ]
```
[Try it online!](https://tio.run/##fY5BTsMwEEX3PcU/AFQ4SVsKB6i6YYNYRVlMHBcsYifYEwlkZcWOY3KR4CZGohtsyTPz//O3TyS5c9PT4/HhcAdD/LKWnam1pShr6eHV26CsVB6vylnVLoxnYu35DMyzI/sckd4p5o/eacuLPlgtu0bhfhVWiCvELZAhx4jxj3KeQ9SLC32ZQzyzBbiFuPltsrnZQyxWNBIkBETxT37ABru5bmPOJSd2CUxZOYosfSFZG@T79PZ2vjxOJahtr/1Qe8UeTnlGCdlZSYxm6GG0NfSOkq7qCt9fn6hw0rZBNRnqsYZsFbnpBw "Factor – Try It Online")
Returns the lists that make up the range. Returns the first solution it finds.
* `all-subsets rest` Powerset sans the empty set.
* `[ ... ] find` Find the first element that returns true when `[ ... ]` is run on it.
* `concat` The union of all sets in a sequence (with duplicates, but it doesn't matter).
* `dup minmax [a,b]` Create a range from the minimum and maximum elements in the union.
* `⊃` Is the union a superset of the range?
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
f!-.+{SsT1ty
```
[Try it online!](https://tio.run/##K6gsyfj/P01RV0@7Org4xLCk8v//6GgjHQWTWB2FaBMdBSNjEMNCR8HQAMYwAjEsgQywlKEBTJGhIVDMJDYWAA "Pyth – Try It Online")
Returns a list of all answers, each in list of lists form.
### Explanation
```
f!-.+{SsT1tyQ # implicitly add Q
# implicitly assign Q = eval(input())
yQ # power set of Q
t # all but the first element (thus excluding the empty element)
f # filter on lambda T
sT # flatten T
S # sort
{ # deduplicate
.+ # take the deltas (should be all 1s if we have a continuous range)
- 1 # remove all instances of 1
! # not (will only be true for the empty list)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPṬSṠṢƑƲƇ
```
A monadic Link that accepts a list of lists of positive integers and yields a list of the valid lists of lists for which the union forms a continuous range.
**[Try it online!](https://tio.run/##y0rNyan8///opICHO9cEP9y54OHORccmHtt0rP3/4fajkx7unPH/f3S0kY6CSayOQrSJjoKRMYhhoaNgaABjGIEYlkAGWMrQAKbI0BAoZhIbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opICHO9cEP9y54OHORccmHtt0rP2/zuH2o5Me7pzxqGlN1qOGOQq2dgqPGuZqRv7/Hx0dbaijYKSjYBwbq8OlAOYZx@ooRAOFTKBCYCZQyASoECxnoaNgaABjGIEYlkAGWMrQAKbIEGiSoQk2U4G0qY45iDLTsUAoMDSHqIBoN9YxMYJYChE3BZpgCbHMDKQnFgA "Jelly – Try It Online").
### How?
```
ŒPṬSṠṢƑƲƇ - Link: list of lists of positive integers, A
ŒP - powerset (of A)
Ƈ - keep those for which:
Ʋ - last four links as a monad:
Ṭ - untruth - e.g. [[2], [2, 5, 7]] -> [[0, 1], [0, 1, 0, 0, 1, 0, 1]]
S - sum (columns of that) -> [0, 2, 0, 0, 1, 0, 1]
Ṡ - sign -> [0, 1, 0, 0, 1, 0, 1]
Ƒ - is invariant under?:
Ṣ - sort -> 0
```
---
If we may also identify the empty set (as producing a continuous range
of zero positive integers) then \$8\$ bytes: `ŒPFṬṢƑƊƇ` - [test suite](https://tio.run/##y0rNyan8///opAC3hzvXPNy56NjEY13H2v/rHG4/OunhzhmPmtZkPWqYo2Brp/CoYa5m5P//0dHRhjoKRjoKxrGxOlwKYJ5xrI5CNFDIBCoEZgKFTIAKwXIWOgqGBjCGEYhhCWSApQwNYIoMgSYZmmAzFUib6piDKDMdC4QCQ3OICoh2Yx0TI4ilEHFToAmWEMvMQHpiAQ "Jelly – Try It Online").
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) ~~22~~ ~~18~~ ~~17~~ 15 or 10 bytes
This code output resulting range:
```
ṗƛÞfUs;'¯U1w⁼;,
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqFo4bmXxpvDnmZVczsnwq9VMXfigbw7LCIsIiIsIltbMiwgNF0sIFs0LCAyM10sIFs4LCAxMF0sIFs4LCAxMl0sIFs5LCAxM10sIFsxMCwgMjNdLCBbMTEsIDE0XV0iXQ==)
and this (@lyxal) - the lists that are used in the range:
```
ṗꜝ'ƒ∪s¯1=A
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZfqnJ0nxpLiiKpzwq8xPUEiLCIiLCJbWzIsIDRdLCBbNCwgMjNdLCBbOCwgMTBdLCBbOCwgMTJdLCBbOSwgMTNdLCBbMTAsIDIzXSwgWzExLCAxNF1dIl0=)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs all possible solutions as the original arrays.
```
à fÊkÈrâ Íän dÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4CBmymvIcuIgzeRuIGTJ&input=W1sxLCAzXSwgWzIsIDRdLCBbNSw3XSwgWzYsOF1dCi1R)
[Answer]
# [Python](https://www.python.org), 150 bytes
```
lambda l:[x for i in range(len(l))for x in combinations(l,i+1)if(s:=sorted({*chain.from_iterable(x)}))==[*range(s[0],s[-1]+1)]]
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBBbsMgEDw3r1jlBC6pjO0kTiT3IxRVODENEobIppKrKN_opRdLVfulqr8pmCSnnnaYmZ0BPr6Pb-5gzfgpq6evVycX5e-7Fm29F6C3bABpO1CgDHTCvDRINwZpjAM7BHZn21oZ4ZQ1PdJE3VOsJOq3VW871-zRKdkdhDIPsrPts3JNJ2rdoAGfMa4qlsTQnqWc9GxBuV_nfBbMEMzOWt2Dao8-LLnc7ufWjRijBDICOedkNh1yToB5pojMhDxTeNsklQRoegVZABsPJommVxP1QbT4J9PPJVmHsSLlTafraIjLOSmyWBn5pQ_YxKoV53g7uzt2yjgk56fhDNUjnGT4jjmOzxvHOP8A)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 or 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā<æ¦ʒè˜ê¥P
```
Outputs all possible result, by outputting the 0-based indices like the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f//SKPN4WWHlp2adHjF6TmHVx1aGvD/f3S0kY5JrE60iY6RMZCy0DE0gFBGQMpSxxAkaGgAkTQ01DE0iY0FAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNNocXnZo2alJh9YVH15xes7hVYeWBvyv1fkfHR1tqGOkYxwbq6MAYhrH6kQb6ZhAuCCGTrSJjhFI1ELH0ABCGQEpSx1DkKChAUTS0FDH0ATdDJ1oUx1zIGmmYwGTMjQHy4H1GOuYGIGNBwua6hhbgk02i42NBQA).
```
æ¦ʒ˜ê¥P
```
Outputs all possible results, by outputting the lists of lists themselves.
[Try it online](https://tio.run/##yy9OTMpM/f//8LJDy05NOj3n8KpDSwP@/4@ONtIxidWJNtExMgZSFjqGBhDKCEhZ6hiCBA0NIJKGhjqGJrGxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w8sOLTs16fScw6sOLQ34X6vzPzo62lDHSMc4NlZHAcQ0jtWJNtIxgXBBDJ1oEx0jkKiFjqEBhDICUpY6hiBBQwOIpKGhjqEJuhk60aY65kDSTMcCJmVoDpYD6zHWMTECGw8WNNUxtgSbbBYbGwsA).
If we're also allowed to include an empty list, the `¦` can be dropped in both programs for -1 byte.
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
< # Decrease each by 1 to the range [0, length)
æ # Get the powerset of this
¦ # Remove the empty leading list
ʒ # Filter the list of lists by:
è # Index each into the (implicit) input list of lists
˜ # Flatten it
ê # Sorted-uniquify it
¥ # Get all deltas / forward-differences
P # Take the product (only 1 is truthy in 05AB1E)
# (after which the filtered result is output implicitly)
```
The second program is similar, but without `ā<` so the powerset is done directly on the input-list of lists, and therefore also without `è`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
f=([x,...y],v=[])=>x?f(y,[...v,x])||f(y,v):v.flat().map(i=>y[i]=0)|/0,,/.test(y)?0:v
```
[Try it online!](https://tio.run/##hY7LCoMwEEX3/QqXCUxj4lsh@iEhi2C1WKxKlaDgv9tocGfpam7mHk7mpbQay08zTPeuf1TbVnMkZiCELBI0FxLzfC5qtIAwOw2zxOu6PzXONKlbNSFM3mpADc8X0UhO8epSAJdM1TihBRc001vZd2PfVqTtn6hGQjBwPHB8KTG@XXS@BEcYILgEjsIAgZEcZAIOo2fw9pCacFSMnhAzXhb8/9HMEOJ9RJD8wllseav2IfDsQXYfGl9qD4kOw/YF "JavaScript (Node.js) – Try It Online")
```
f=([x,...y],v=[])=>
x?
f(y,[...v,x])||f(y,v) // [] is always a continuous range, so it's last tested
:
v.flat().map(i=>y[i]=0) // Writing 0, so if v.flat().length==1 then it returns 0, not bother bitOR
|/0,,/.test(y)?0:v // Is there hole between, ,,,0,0,0,0 is fine, ,,,0,0,,0 isn't
```
[Answer]
# JavaScript (ES6), 81 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Returns a single solution as a space-separated string of integer lists.
```
f=([v,...a],m,o)=>v?f(a,m,o)||f(a,v.map(k=>m|=1<<k)|m,[o]+v+' '):(m|=m-1)&m+1?0:o
```
[Try it online!](https://tio.run/##nY/LTsMwEEX3fMWsqK1MXU/dF1XTfgISW8sLqzQIWtcVRV7l38M4jw1UIMhmrmPrnDtvPvnr/v318jE@x@dD01SlsAmVUt5hwCjLbdpVwre5rnNKKviLOJbbUJe02RxlHdBGV6RiBCO5Fvw7jEneh4J2eh2bfTxf4@mgTvFFVMJaQpgiGOfgP5@UMJmAvrtBNQ7BMnr2d3RPRaBv4BbI4BnXbg0rfqWHMM3hgUN7RXp4RNyHuEgHzvsyBmHxc2@ec4RlnguE1e97DL0JHp/YYvLgE3K8ZaJlr@pKciej@926K7YbavVf3Z1p3nwC "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
IΦEX²LθΦθ﹪÷ιX²μ²∧ι¬⁻…·⌊Σι⌈ΣιΣι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY7BSgMxEIZfJfQ0Cyl01z1UeqothYIrRY8hh3Q3tgPZxG6S1Xfx0oOiB1-ob-PEdqUDGT7-f_6ZvH_Xe9XVTpnj8TOG5_H09LPp0AZYKB9ghSboDir1Ahv3SlRwdq_tLuzhkGWcXfwDZ5VronGwtmGJPTYakLP_SJtmiyz1uW2S9eACVGijp0RtosdePyq700nENrbwRA9ToFJv1wIpA1HNPvy29peff4nRuDcjeboTQtDVUnImSjp8k2DKWT4ZoEhwS_Bn5ZNhKM9JK6WU542_) Link is to verbose version of code. Outputs all solutions. Explanation:
```
² Literal integer `2`
X Raised to power
θ Input list
L Length
E Map over implicit range
θ Input list
Φ Filtered where
ι Outer value
÷ Integer divided by
² Literal integer `2`
X Raised to power
μ Inner index
﹪ ² Is odd
Φ Filtered where
ι Current result
∧ Logical And
ι Current result
Σ Flattened
⌊ Minimum
ι Current result
Σ Flattened
⌈ Maximum
…· Inclusive range
⁻ Remove elements present in
ι Current result
Σ Flattened
¬ Logical Not i.e. is empty
I Cast to string
Implicitly print
```
The output format is as follows: Each result is triple-spaced from each other, while within a result, the sets that comprise the result are double-spaced from each other and each element is output on its own line.
[Answer]
# [Haskell](https://www.haskell.org/), 94 bytes
```
import Data.List
s=take 1.filter((\s->s>[]&&s==[head s..last s]).nub.sort.concat).subsequences
```
[Try it online!](https://tio.run/##NczBDoIwEATQu1@xB0MgqRuKHPRQTh79g9rDgjU0lIJs@f4KJtxeZibTEw/W@5TcOE9LhAdFwqfjeGIVabAg8eN8tEuev/jScKNNlrFSurf0Bkb0xBHYFBjWFnm7wG4KHcUCeW3ZflcbOstpJBfUvLgQz6x1JaA2AnQtoLruuAmQ5YFqx33Dv5LlMZJyy2pj0g8 "Haskell – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
⊇.cod~⟦₂∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu15yfkrdo/nLHjU1PepY/v9/dLSRjoJJrI5CtImOgpExiGGho2BoAGMYgRiWQAZYytAApsjQEChmEhv7PwoA "Brachylog – Try It Online")
Generates solution with the largest number of sublists first.
### Explanation
```
⊇. Output is a sublist of the input
cod Concatenate, sort, remove duplicates
~⟦₂ The resulting list must be a range between 2 integers
∧
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 35 bytes
```
({(⌈´¬⌊´)=≠}¨/⊢)∘((⍷∾)¨(⥊(↕2˘)/¨<))
```
[Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiIjIEdpdmVuIGEgbGlzdCBvZiBsaXN0cyBvZiBwb3NpdGl2ZSBpbnRlZ2Vycywgb3V0cHV0IGEgc3Vic2V0IG9mXG4jIHRoZW0gc28gdGhlaXIgdW5pb24gZm9ybXMgYSBjb250aW51b3VzIG5vbi1lbXB0eSByYW5nZSB3aXRoIG5vXG4jIG51bWJlcnMgbWlzc2luZy4gRm9yIGV4YW1wbGUsIGNvbnNpZGVyIHRoaXMgaW5wdXQ6XG5cbnQwIOKGkCDin6jin6gxLCAyLCAzLCA14p%2BpLCDin6gyLCA0LCA24p%2BpLCDin6g3LCA5LCAxMeKfqeKfqVxudDEg4oaQIOKfqOKfqDEsIDPin6ksIOKfqDIsIDTin6nin6lcbnQyIOKGkCDin6jin6gyLCA04p%2BpLCDin6g0LCAyM%2BKfqSwg4p%2BoOCwgMTDin6ksIOKfqDgsIDEy4p%2BpLCDin6g5LCAxM%2BKfqSwg4p%2BoMTAsIDIz4p%2BpLCDin6gxMSwgMTTin6nin6lcbnQzIOKGkCDin6jin6gxLCAz4p%2BpLCDin6gyLCA04p%2BpLCDin6g1LDfin6ksIOKfqDYsOOKfqeKfqVxudDQg4oaQIOKfqOKfqDEsIDE34p%2BpLCDin6gyLDIz4p%2BpLCDin6gzLDQy4p%2BpLCDin6g0LDE34p%2BpLCDin6g1LCAzOTEy4p%2BpLCDin6g24p%2Bp4p%2BpXG5Tb2wg4oaQICh7KOKMiMK0wqzijIrCtCk94omgfcKoL%2BKKoiniiJgoKOKNt%2BKIvinCqCjipYoo4oaVMsuYKS%2FCqDwpKVxuU29sIHQwIiwicHJldlNlc3Npb25zIjpbXSwiY3VycmVudFNlc3Npb24iOnsiY2VsbHMiOltdLCJjcmVhdGVkQXQiOjE2NzQ5Mzc2OTI1NzZ9LCJjdXJyZW50Q2VsbCI6eyJmcm9tIjowLCJ0byI6NDU4LCJyZXN1bHQiOm51bGx9fQ%3D%3D)
### Explanation
```
({(⌈´¬⌊´)=≠}¨/⊢)∘((⍷∾)¨(⥊(↕2˘)/¨<))
(↕2˘)/¨< Powerset (as a length-dimensional tensor)
(⥊ ) Deshape tensor to single dimension
((⍷∾)¨ ) Concatenate, remove dupes in each element
∘ Then...
/⊢ filter the input by...
(⌈´¬⌊´) whether range (span)...
= is equal to...
≠ length...
({ }¨ ) for each element.
```
Originally had 34 bytes but there was a bug.
[Answer]
# [Arturo](https://arturo-lang.io), 57 bytes
```
$=>[select--powerset&[[]]=>[b:flatten&[][[email protected]](/cdn-cgi/l/email-protection)\0max<=b]]
```
[Try it](http://arturo-lang.io/playground?7Gl46i)
```
$=>[ ; a function
select ; select elements from
--powerset&[[]] ; powerset of input without empty set
=>[ ; begin select, assign current elt to &
b:flatten& ; flatten sets in current elt
[]= ; is the empty block equal to
-- ; set difference of
@ ; evaluate block
.. ; range
b\0 ; first element of b
max<= ; max of b
b ; and b (second argument to set difference)
] ; end select
] ; end function
```
[Answer]
# [Julia 1.0](http://julialang.org/), 66 bytes
```
!l=all(diff(sort([l...;])).<2) ? l : maximum(i->!setdiff(l,[i]),l)
```
[Try it online!](https://tio.run/##ZY5NboMwEIX3nGLY2ZKLYiC/bdIegJ4AsRgJI7kanMgmVU7QRY/Zi9CJHRZVvZnP7735@biSRX2b55yOSCR6OwwinP0kWiqK4rmTsngpJbwCwQFGvNnxOgr7dMqDmWKYVGs7qUjOw9mDBevAG@zJOhOEzIAfwhHMJ5J4NxMWF/TBCCuTR@zlGLFhfGyN/4u3biInuP0ElOJvGILxE4zWxUsaeViOauTP91fzJ0XAEmBmXD@3rVZQKqi6LotcdQpaFuooRGCh5lB0dgr0aoHyDnuGaOnVEtI8R9f/J3Jdq@29bNRusfU2@am1UnWZFiZ9zf37tGjzuIgH/wI "Julia 1.0 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 84 bytes
```
f=lambda a:max(f(a-{i})for i in a)if a and~-len(b:={*sum(a,())})-max(b)+min(b)else a
```
[Try it online!](https://tio.run/##fY/NCoMwEITvfYo9ZtsVjP8KPkxEpQFNRS20iH11u/HnUqGnHTIz326693h/GD/p@mWp80a1RalAZa16iVooZ9Iz1o8eNGgDCnUN7Jry4zSVEUWWT9fh2QpFAnFGx7YKvLWaPayaoQK1dL02I7MmIQk8Ap8gRALBMiCIrIwJUgIpGYGXU/786h/9H2t9You53ppJmOoewrPC7lkt6R4hyUQZ/NvCMySI7YwIknNUxnt2I/IXA28/ZLO47qfbBRHZ/vIF "Python 3.8 (pre-release) – Try It Online")
Takes a set of tuples as input and recursively removes items until a valid result is found.
] |
[Question]
[
Consider an array `A` of length `n`. The array contains only positive integers. For example `A = (1,1,2,2)`. Let us define `f(A)` as the set of sums of all the non-empty contiguous subarrays of `A`. In this case `f(A) = {1,2,3,4,5,6}`. The steps to produce `f(A)` are as follows:
The subarrays of `A` are `(1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2)`. Their respective sums are `1,1,2,2,2,3,4,4,5,6`. The set you get from this list is therefore `{1,2,3,4,5,6}`.
**Task**
Given a set of sums `S` given in sorted order containing only positive integers and an array length `n`, your task is to output at least one array `X` such that `f(X) = S`.
For example, if `S = {1,2,3,5,6}` and `n = 3` then a valid output is `X = (1,2,3)`.
If there is no such array `X` your code should output any constant value.
**Examples**
Input: `n=4, S = (1, 3, 4, 5, 6, 8, 9, 10, 13)`, possible output: `X = (3, 5, 1, 4)`
Input: `n=6, S = (2, 3, 4, 5, 7, 8, 9, 10, 12, 14, 17, 22)`, possible output: `X = (5, 3, 2, 2, 5, 5)`
Input: `n=6, S = (2, 4, 6, 8, 10, 12, 16)`, possible output: `X = (4, 2, 2, 2, 2, 4)`
Input: `n=6, S = (1, 2, 3, 4, 6, 7, 8, 10, 14)`, possible output: `X = (4, 2, 1, 1, 2, 4)`
Input: `n=10, S = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25)`, possible output: `X = (1, 1, 3, 1, 2, 1, 2, 5, 4, 5)`.
Input: `n=15, S = (1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31)`, possible output: `X = (1, 2, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 2, 1, 3)`.
**Input and output format**
Your code can take input and give output in any easily human read format you find convenient. However, please show the output of testing it on the examples in the question.
**Running time**
You must be able to run the code to completion for all the examples in the question. It should in principle be correct for `n` up to `15` but you do not need to prove it would be fast enough for all inputs.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
ḟȯ⁰¦ṁ∫ṫ!¡Sof~Λ€∫×:¹g
```
[Try it online!](https://tio.run/##DcohDsIwGIbhs@Bfse/v1g2ugSRYIEEgCJZkKG6AQBDMzEhAUjsMiju0FymzT57NYb/NOb5v32dqX0MXQ5vOfQz9ZLjPd6vj75pOj1E@l9kQ1jnnhTAcJZ6ahikqkJBDJaqQRzVqsAIbr2EOK7EK81iNNbgCp2VW9Qc "Husk – Try It Online")
Returns one solution, or an empty list if it doesn't exist.
The last test case (`n=15`) finishes in 3.8 seconds on TIO.
## Explanation
The program has two parts.
In the first part (`¡` and to the right of it), we construct an infinite list whose `k`th element is a list containing all length-`k` lists whose slice sums are in `S`.
We do this inductively, starting from the 1-element slices of `S`, and at each step prepending each element of `S` to each list, and keeping those whose prefix sums are in `S`.
In the second part (`!` and to the left of it), we take the `n`th element of the list, which contains length-`n` lists.
Of these, we select the first one whose slice sums actually contain every element of `S`.
In the code, let's first replace `o` and `ȯ` (which compose two and three functions into one) by parentheses for clarity.
```
¡S(f~Λ€∫)×:¹g First part. Input is a list, say S=[1,2,3]
g Group equal adjacent elements: [[1],[2],[3]]
¡ Iterate function:
Argument is a list of lists, say [[1,1],[1,2],[2,1]]
× Mix (combine two lists in all possible ways)
: by prepending
¹ with the list S: [[1,1,1],[1,1,2],[2,1,1],[1,2,1],[2,1,2],[3,1,1],[2,2,1],[3,1,2],[3,2,1]]
f Filter by condition:
∫ Cumulative sums: [[1,2,3],[1,2,4],[2,3,4],[1,3,4],[2,3,5],[3,4,5],[2,4,5],[3,4,6],[3,5,6]]
~Λ All of the numbers
S € are elements of S: [[1,1,1]]
Only this list remains, since the other cumulative sums contain numbers not from S.
Result of iteration: [[[1],[2],[3]],[[1,1],[1,2],[2,1]],[[1,1,1]],[],[],[]...
ḟ(⁰¦ṁ∫ṫ)! Second part. Implicit input, say n=2.
! Take nth element of above list: [[1,1],[1,2],[2,1]]
ḟ Find first element that satisfies this:
Argument is a list, say [1,2]
ṫ Tails: [[1,2],[2]]
ṁ Map and concatenate
∫ cumulative sums: [1,3,2]
ȯ ¦ Does it contain all elements of
⁰ S? Yes.
Result is [1,2], print implicitly.
```
There are some parts that need more explanation.
In this program, the superscripts `⁰¹` both refer to the first argument `S`.
However, if `α` is a function, then `α¹` means "apply `α` to `S`", while `⁰α` means "plug `S` to the second argument of `α`".
The function `¦` checks whether its first argument contains all elements of the second (counting multiplicities), so `S` should be its second argument.
In the first part, the function that `¡` uses can be interpreted as `S(f~Λ€∫)(×:)¹`.
The combinator `S` behaves like `Sαβγ -> (αγ)(βγ)`, which means that we can simplify it to `(f~Λ€∫¹)(×:¹)`.
The second part, `×:¹`, is "mix with `S` by prepending", and its result is passed to the first part.
The first part, `f~Λ€∫¹`, works like this.
The function `f` filters a list by a condition, which in this case is `~Λ€∫¹`.
It receives a list of lists `L`, so we have `~Λ€∫¹L`.
The combinator `~` behaves like `~αβγδε -> α(βδ)(γε)`: the first argument is passed to `β`, the second to `γ`, and the results are combined with `α`.
This means that we have `Λ(€¹)(∫L)`.
The last part `∫L` is just the cumulative sums of `L`, `€¹` is a function that checks membership in `S`, and `Λ` takes a condition (here `€¹`) and a list (here `∫L`), and checks that all elements satisfy it.
Put simply, we filter the results of the mixing by whether their cumulative sums are all in `S`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 135 bytes
```
->a,n{r=w=1;r+=1until w=(s=a[0,r]).product(*[s]*~-n).find{|x|x.sum==a.max&&a==[]|(1..n).flat_map{|r|x.each_cons(r).map(&:sum)}.sort};w}
```
[Try it online!](https://tio.run/##Xc5da4MwFMbx@36KXknsngZPotauZF9EQsnsZIX6QlR0qPvqLg42ireH3/Pn2O79a8nVcnwzKEerekUX@6KoK9v7Y98r1iiTBrDa57Wtbl3WskPa6MP3sfR5fi9v4zRMA2@6QinDCzN4nlEq1RMjzlfyMO21MPU4Wcc@TPZ5zaqyYdZ3uGbeq1v6M28q286Xfl7qfZ6mBAGJCLGG1Lvf03oI3emEBGdQABKgEHSCENrB3dNwdfGTpD8cgeJ1QgnoDBFASIgQItLObRKbgNwG1rWz4r8BEUO4dxLIAJJcMtLLDw "Ruby – Try It Online")
Use a breadth-first search. n=10 works on TIO, n=15 takes longer than a minute, but works on my machine.
# [Ruby](https://www.ruby-lang.org/), 147 bytes
```
->a,n{r=w=1;r+=1until w=([a[-1]-a[-2]]).product(*[s=a[0,r]]*~-n).find{|x|x.sum==a.max&&a==[]|(1..n).flat_map{|r|x.each_cons(r).map(&:sum)}.sort};w}
```
[Try it online!](https://tio.run/##XY7NaoNAFEb3eYqsgqafg3dGjWmYvsgwhKmpNBB/GBUtal/djoWW4OYuPs45XNu9fy25XII3g3K0spd0sS@SurK9P/a99JRRAenAXa61z2pb3bqs9Y6qkUaFsFofv4PSZ/m9vI3TMA2s6QopDSvMcDgYKZWePGJsRR6mvRamHifrsA@TfV6zqmw86zu49g6vzvRn1lS2nS/9vNT7XCkCh0CMREPo3e@0DpGbTkhxBoUgDopAJ3CuHbh7ElcueSLpD45ByapQCjqDh@ACPAKPteM2iU1AbAOr7Vj@3wBPwN07KUQIQS4Z6@UH "Ruby – Try It Online")
Optimized version, works on TIO for n=15 (~20 sec)
Actually, this is the beginning of a non-brute-force approach. I hope somebody will work on it and find a complete solution.
### First ideas:
* The sum of the output array is the last element (max) of the input array.
* The sum of the output array minus the first (or the last) element, is the second last element of the input array.
* If an array is a solution, then the reverse array is a solution too, so we can assume the first element is the difference between the last 2 elements of the input array.
* The second element can be the difference between second and third or second and fourth last element of the input array.
Which brings us to the next optimization:
# [Ruby](https://www.ruby-lang.org/), 175 bytes
```
->a,n{r=w=1;r+=1until w=([a[-1]-a[-2]]).product([a[-2]-a[-3],a[-2]-a[-4]],*[s=a[0,r]]*(n-2)).find{|x|x.sum==a.max&&a==[]|(1..n).flat_map{|r|x.each_cons(r).map(&:sum)}.sort};w}
```
[Try it online!](https://tio.run/##XY7RisIwEEXf/QqfpHVvQ2fSVl3J/kgYJKuWFbSWtEUX67d3U2FFfAnD4dxDfPf9O5RmSL4cqps3F0Nr/2Goq9rDcXoxkXU2IUnCyyKxqv15123bB@YH1oLnnYlgbhvjbAovMo@qhONYlYdqd@uv/VU13ckYp07uOps5Y6z0ESlVBeXo2s3J1bfeB23vtj@b7blqIh8HuY5mn2EZ31Vz9u19fbkP9bS0lsDQyFEItEweaARZQAsssQKlIAZloAWYJYiTl@HoFS8m/cs5qBgntAStwClYgzNwLsF7S7wF9HtgXAeXnw1wAQ7fWUKn0BSSuQx/ "Ruby – Try It Online")
~8.5 seconds on TIO. Not bad...
...and so on (to be implemented)
[Answer]
# Haskell, ~~117~~ 111 bytes
6 bytes saved thanks to @nimi!
```
f r i n s|n<1=[r|r==[]]|1<2=[y:z|y<-s,t<-[y:map(y+)i],all(`elem`s)t,z<-f[a|a<-r,all(a/=)t]t(n-1)s]
n&s=f s[]n s
```
[Try it online!](https://tio.run/##bc/RaoMwFMbx@z7FuRhF2ZF5TtS2I3mSEGhglkk1K8Ybi@/uonXi1l2G8@P/kU/rr2Vdj@MFWqjAgR@cJKXboVVKGzOQZKX79/vQy8RjJ5PwaOwt6l/jyqCt6@hc1mVz9nGHd5lctB2sTNr5Yt9U3JkucgnF3uzc3qsLeG3CytjYyoGCj68dwK2tXAcvkMEeNKHADHMs8IgnpBRJmI0pJsOLOayGkTKkAzL/g7M5trDiCRA@esXcm1i2NZRuUb6wxyz9LOchPO1TCJyQU2SBnCHnv0r589zaEX87UyRYXlPIBXL44hFFioLM@A0 "Haskell – Try It Online")
This computes all solutions. The helper function `f` builds them incrementally, the `r` argument contains the values of \$ S \$ that were not yet seen, the `i` argument contains the sums that include the newest element, `n` is the remaining number of elements that are needed, and `s` is always the given set.
When `n` is zero (golfed to `n<1`) the list must be ready, so we check if all values have been seen. If not, we return an empty list to indicate no solutions, else we return a singleton list containing an empty list, to which the chosen elements will be prepended. This case could also have been handled with the additional equations
```
f [] _ 0 _=[[]]
f _ _ 0 _=[]
```
If `n` is not zero, we return
```
[y:z|y<-s,t<-[y:map(y+)i],all(`elem`s)t,z<-f[a|a<-r,all(a/=)t]t(n-1)s]
^1^ ^2^^ ^......3......^ ^.....4.....^ ^.............5.............^
```
This is the list of (1) lists where the first element (2) comes from `s` and the rest (5) comes from the recursive call, under the condition (4) that all new sums are in `s`. The new sums are computed in (3) - note that `t` is drawn from a singleton list, an ugly golfing hack for what in idiomatic Haskell would be `let t=y:map(y+)i`. The recursive call (5) gets as new `r` set the old one without those elements that appear among the new sums `t`.
The main function `&` calls the helper function saying that we still have to see all values (`r=s`) and that there are no sums yet (`i=[]`).
For seven more bytes, we can restrict the computation to only give the first result (if any), which is much faster and handles all test cases in less than 2 seconds.
[Try it online!](https://tio.run/##bc/RasIwFMbxe5/iXIgoO4GeJK06mss9RQgaWIvVGkeTm0rfvUu1K93cZQ4//h85WX8p6rrvS2jgAAkclG66RiltzGK4VeDAK92@37s2Zx5DzuJDt2/n7pyzyhi0db0@FnVxPfpNwHvOSm07m7MG3S18xDtYCCasHaONNwu38irYSwG0LMFrE/P91VYOFHzeFgBfTeUCLEHCCjShQIkpZrjDPVKCJMzMZIPho9lOhiNJpC1y/g@Wj9jIshdA@Oxlj97A5NxQMkfpyJ6z9LOcxvCwTzGwR54gF8gl8vRXKX2dmzrib2eIRMunFPIMefziDkWCgkz/DQ "Haskell – Try It Online") (this is the first result only variation of the old version)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 177 bytes
```
import StdEnv,Data.List
$s n=find(\a=sort(nub[sum t\\i<-inits a,t<-tails i|t>[]])==s)(?{#u\\u<-s|u<=(last s)-n}(last s)n)
?e s n|n>1=[[h:t]\\h<-:e|h<=s-n,t<- ?e(s-h)(n-1)]=[[s]]
```
[Try it online!](https://tio.run/##bY9BS8MwFMfP66d44A4NJM6kbupotss8CB6EHdscYtfZQJuNJhGG9atbXx3CCjs8SN77/X95KepS27457EJdQqON7U1zPLQetn73bD/pRnt9@2qcj6YOrNwbu4tzLR0isQ3vmQsN@Dw3KTPWeAea@pR5bWoHpvOrTCkipSPx@usm5HlImetCKuNaOw@OMPv9f7QkWpeAb3R2xWWWVUuv8rxK2bLsqlQ6ZgczrMvYsYrElnGiEHNK9VuvcWGJ6x8hDrYIbXuCKYEsmsQZp5BQuKcwp7Cg8EjhiQK/w0oU9gkdIHEBPYwgnHDsc@wKgYHFOYBWMRaPY/wiinO@OCs4IhwZgYzAtMC5mKshRKKJimYzCVMY2a@qk@vqP@0QFpd6LGTE8ANkEmQSrjDb/xT7Wn@4nr289puT1Y0pzpe3Wvv9oW16ZgvzCw "Clean – Try It Online")
Takes about 40 seconds on my machine for the `n=15` test case, but it times out on TIO.
# [Clean](https://github.com/Ourous/curated-clean-linux), 297 bytes
```
import StdEnv,Data.List
$s n=find(\a=sort(nub[sum t\\i<-inits a,t<-tails i|t>[]])==s)(~[u\\u<-s|u<=(last s)-n](last s)n(reverse s))
~e s n a|n>4=let u=a!!0-a!!1 in[[u,h:t]\\h<-[a!!1-a!!2,a!!1-a!!3],t<- ?e(s-u-h)(n-2)]= ?e s n
?e s n|n>1=[[h:t]\\h<-e,t<- ?(takeWhile((>=)(s-n-h))e)(s-h)(n-1)]=[[s]]
```
[Try it online!](https://tio.run/##vZA/b9swEMXn6lNcAA8kQDYRJbl/ILpLOhTIUCBDB0oDI9M1UYkORDJAACMfverRhlwVCDpmoHi6e@/3Dux6o900HLaxNzBo6yY7PB7GAPdh@9U9sVsd9Ps760O28uDkzrotabT0KCEuPigfBwhNY2tunQ0eNAs1D9r2HuwxbFTbUik9JS8qNk2suT/GWpJe@wCectfOpSOjeTKjN1jT7AUvcKCPblPK3gSIUl9d3XD85GCdUpHtP4e2afY1V6mZJoLNVdGmLeCLIZ5HvqfEcUFbiY2Ezc4XsnOp1IVjzh4S9C/zY297Q8hGUiQ4JFCTqhMpR5JSvm2n@6DxoSQ@2yOQ6Lo4js@woqCyd0TlDAoGJYOKwZrBRwafGOQ3eHA7KClLIrEQffhHhJMc@zl2hUDD@mIoZ95Ft/47x9QLcz0zT8LydVG10M3Z@SK/SvzzHnlCoUagRqBb4FxUbTL9J3wJLV6HnoDJLJZgPKgR6QFQU6CmyFNYRdvs@lrCCt4iEL3T727X659@4t/upttnpwfbnX@@9zrsDuMwcdfZPw "Clean – Try It Online")
This one includes some optimisations made by [G B](https://codegolf.stackexchange.com/a/174258/18730) as well as some of my own.
I think a few of them can be made more generic, so I'll add an explanation once that's done.
It takes about 10 seconds on my machine, 40 seconds on TIO.
[Answer]
# [Python 3](https://docs.python.org/3/), 177 bytes
```
from itertools import*
s,n=eval(input())
for[*t]in combinations(s[:-2],n-2):
a=[*map(int.__sub__,t+s[-2:],[0,*t,s[-2]])];
{sum(a[p//n:p%n+1])for p in range(n*n)}^{0,*s}or-print(a)
```
[Try it online!](https://tio.run/##FY3BbsIwDEDvfIUvk5LiDhxgg058SZRVYSpbJOJESTppQnx7Zw4@WO89O/@1n8S7ZbmWFCG0qbSUbhVCzKm0blWRz9Ovv6nAeW5K69U1Fds1Fxi@UrwE9i0krqraoTcOuTd68GfbRZ@laa/jWOfLOGJbV9ubwaHdYtfwuTin3ce9zlF5mzcbHvILr8lp@QAZ5EHx/D0p7lg/Pu@S1UcqfS5yVnm9LMoSgkHYIewRDghvCO8IR4QTAm1lhJMIJJiEkwgkBolC4hhxjNRGuDm4Z6T/AQ "Python 3 – Try It Online")
(some newlines/spaces added to avoid readers having to scroll the code)
A direct port of my Jelly answer (with some modifications, see "note" section below)
Local run result:
```
[user202729@archlinux golf]$ printf '%s' "from itertools import*
s,n=eval(input())
for[*t]in combinations(s[:-2],n-2):a=[*map(int.__sub__,t+s[-2:],[0,*t,s[-2]])];{sum(a[p//n:p%n+1])for p in range(n*n)}^{0,*s}or-print(a)" > a.py
[user202729@archlinux golf]$ wc -c a.py
177 a.py
[user202729@archlinux golf]$ time python a.py<<<'([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25], 10)' 2>/dev/null
[1, 4, 1, 1, 1, 1, 1, 7, 7, 1]
real 0m3.125s
user 0m3.119s
sys 0m0.004s
[user202729@archlinux golf]$ time python a.py<<<'([1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31], 15)' 2>/dev/null
[3, 1, 2, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 2, 1]
real 11m36.093s
user 11m33.941s
sys 0m0.387s
[user202729@archlinux golf]$
```
---
I heard that `itertools` is verbose, but my best `combinations` implementation is even more verbose:
```
c=lambda s,n,p:s and c(s[1:],n-1,p+s[:1])+c(s[1:],n,p)or[]if n else[p]
```
---
*Note*.
* Using division/modulo in `a[p//n:p%n+1]` takes about 2x longer, but saves some bytes.
* This is a bit different from the Jelly answer -- the Jelly answer iterates backwards.
* Thanks to `combinations` returning an iterator, this is more memory-friendly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
Ẇ§QṢ⁼³
;³ṫ-¤0;I
ṖṖœcƓ_2¤¹Ṫ©ÇѬƲ¿ṛ®Ç
```
[Try it online!](https://tio.run/##Dcs7CsJQEIXhPquYBYxw52p8kBVYWotYiI1kA5Y2ppaATToJiA8sTHVFECaYfYwbuR6YU/3fbNZ5vo3RXns9zyycfru3NkmmjYVbT2uXTRMLR9y3XHXl0mutwcJVL23RHvTePfVjodJHW8QoLs6FyTP1mQZMKdOQacQ0ZpowicPQBUCQBV0ABEJABMbDeHx7dJ8u/g "Jelly – Try It Online")
Run locally: (n=15 takes more than 1 GB of RAM)
```
aaa@DESKTOP-F0NL48D MINGW64 ~/jellylanguage (master)
$ time python scripts/jelly fu z '[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,23,24,25]'<<<10
[8, 6, 2, 1, 1, 1, 1, 3, 1, 1]
real 0m1.177s
user 0m0.000s
sys 0m0.015s
aaa@DESKTOP-F0NL48D MINGW64 ~/jellylanguage (master)
$ time python scripts/jelly fu z '[1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 2
6, 27, 28, 30, 31]'<<<15
[3, 1, 2, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 2, 1]
real 12m24.488s
user 0m0.000s
sys 0m0.015s
```
(actually I ran the UTF8-encoded version, which takes more than 35 bytes, but the result is the same anyway)
This solution uses short-circuit to reduce the run-time.
Without short-circuiting, this code takes roughly \$\binom {|S|-2}{n-2} \times \left( \frac {n^3}6 + n^2\log{n^2} \right)\$ operations, which evaluates to \$\binom {26-2}{15-2} \times \left( \frac {15^3}6 + 15^2\log{15^2} \right) \approx 5.79 \times 10^9\$, however due to the inefficiency of Python and Jelly, it takes forever to complete. Thanks to short-circuiting, it can finish much sooner.
### Explanation
We note that the sums of all non-empty prefixes are present in the input, and they are strictly increasing. We can also assume that the largest and second-largest element is a prefix sum.
Therefore, we can consider all ways to choose \$n-2\$ distinct elements from first \$|S|-2\$ elements (there are \$\binom {|S|-2}{n-2}\$ such lists), compute the consecutive differences to recover the elements; then check if it's valid naively (get all \$n^2\$ subarrays, compute the sum, uniquify. Total length of the subarrays is about \$n^3 \over 6\$)
---
Untested (but should have identical performance)
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
Ṫ©ÑẆ§QṢ⁻³
;³ṫ-¤ŻI
ṖṖœcƓ_2¤¹Ñ¿ṛ®Ç
```
[Try it online!](https://tio.run/##Dcs9CsJgDMbxvafIASI00fqBJ3B0FnEQF@kFHF10LgWXblIQFVw6xQ5CSr3H60VeH8gz/X/Z7/L8EGOwh9@7IrxPflsGu/6OrTfJ3Jtgz4HXfbtIgl1wfbn9lhv12q0r/BOs8ld3jlHSuBImZRoyjZgypjHThGnKNGOSFEMXAEEWdAEQCAERGIVRfCu6Zus/ "Jelly – Try It Online")
---
More inefficient version (without short circuit):
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
Ẇ§QṢ⁼³
ṖṖœcƓ_2¤µ;³ṫ-¤0;I)ÑƇ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrZDywMf7lz0qHHPoc1cD3dOA6Kjk5OPTY43OrTk0FbrQ5sf7lyte2iJgbWn5uGJx9r//zc0@B9tqKNgpKNgrKNgoqNgqqNgpqNgrqNgoaNgqaNgaADEQHlDoAJDoLQhUN4QqMAQqMIQqMQQqMYIqMYIqNsIKG9kGgsA "Jelly – Try It Online")
For the n=15 test, it takes up to 2GB RAM and does not terminate after ~37 minutes.
---
*note*: `Ẇ§` may be replaced with `ÄÐƤẎ`. It may be more efficient.
[Answer]
# APL(NARS), chars 758, bytes 1516
```
r←H w;i;k;a;m;j
r←⊂,w⋄→0×⍳1≥k←↑⍴w⋄a←⍳k⋄j←i←1⋄r←⍬⋄→C
A: m←i⊃w⋄→B×⍳(i≠1)∧j=m⋄r←r,m,¨∇w[a∼i]⋄j←m
B: i+←1
C: →A×⍳i≤k
G←{H⍵[⍋⍵]}
r←a d w;i;j;k;b;c
k←↑⍴w ⋄b←⍬⋄r←0 ⋄j←¯1
A: i←1⋄j+←1⋄→V×⍳(i+j)>k
B: →A×⍳(i+j)>k⋄c←+/w[i..(i+j)]⋄→0×⍳∼c∊a⋄→C×⍳c∊b⋄b←b,c
C: i+←1⋄→B
V: →0×⍳∼a⊆b
r←1
r←a F w;k;j;b;m;i;q;x;y;c;ii;kk;v;l;l1;i1;v1
w←w[⍋w]⋄r←a⍴w[1]⋄l←↑⍴w⋄k←w[l]⋄m←8⌊a-2⋄b←¯1+(11 1‼m)⋄j←2⋄i←1⋄x←↑⍴b⋄i1←0⋄v1←⍬
I: i1+←1⋄l1←w[l]-w[l-i1]⋄v1←v1,w[1+l-i1]-w[l-i1]⋄→I×⍳(l1=i1)∧l>i1⋄→B
E: r←,¯1⋄→0
F: i←1⋄q←((1+(a-2)-m)⍴0),(m⍴1),0⋄r+←q
A: i+←1⋄j+←1⋄→E×⍳j>4000
B: →F×⍳i>x⋄q←((1+(a-2)-m)⍴0),b[i;],0⋄q+←r⋄v←q[1..(a-1)]⋄→A×⍳0>k-y←+/v
q[a]←k-y⋄→A×⍳l1<q[a]⋄→A×⍳∼q⊆w⋄→A×⍳∼l1∊q⋄→A×⍳∼v1⊆⍦q⋄c←G q∼⍦v1⋄ii←1⋄kk←↑⍴c⋄→D
C: →Z×⍳w d v1,ii⊃c⋄ii+←1
D: →C×⍳ii≤kk
→A
Z: r←v1,ii⊃c
```
The function G in G x (with the help of H function) would find all the permutations of x.
The function d in x d y find if the y array generate following the exercise array x returning a Boolean value.
The function F in x F y would return the array r of length x, such that y d r is true (=1)
A little long as implementation, but it is this one that calculate all case in test less time...
The last case for n=15 it run 20 second only... i have to say this not find many solutions, return
just one solution (at last it seems so) in less time (not explored test for different inputs...)
16+39+42+8+11+11+18+24+24+54+11+12+7+45+79+69+12+38+26+72+79+27+15+6+13(758)
```
6 F (2, 3, 4, 5, 7, 8, 9, 10, 12, 14, 17, 22)
5 3 2 2 5 5
6 F (2, 4, 6, 8, 10, 12, 16)
4 2 2 2 2 4
6 F (1, 2, 3, 4, 6, 7, 8, 10, 14)
4 2 1 1 2 4
10 F (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25)
1 1 3 1 2 3 5 1 3 5
15 F (1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31)
1 2 1 3 3 1 3 3 1 3 3 1 2 1 3
ww←(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25)
ww≡dx 1 1 3 1 2 3 5 1 3 5
1
```
] |
[Question]
[
### Description
We consider an integer with at least 3 digits triple-balanced if, when split into three parts, the digits in every part sum up to the same number. We split numbers as follows:
```
abcdefghi - Standard case: the number of digits is divisable through 3:
abc def ghi
abcdefgh - Number % 3 == 2: The outer groups are both assigned another digit
abc de fgh (the inner group will have one digit less than both outer groups)
abcdefghij - Number % 3 == 1: The inner group is assigned the extra digit
abc defg hij (the inner group will have one digit more than the outer groups)
```
### Challenge
Your task is to write a program, that, given an integer with at least 3 digits, determines whether the given number is triple-balanced and outputs a truthy or falsy value based on it's result.
### Test cases
```
333 -> True
343 -> False
3123 -> True
34725 -> True
456456 -> False
123222321 -> True
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply and may the shortest answer in bytes win!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ ~~88~~ 86 bytes
*-4 bytes thanks to @LeakyNun*
*-2 bytes thanks to @Mr.Xcoder*
```
def g(i):l=-~len(i)/3;print f(i[:l])==f(i[l:-l])==f(i[-l:])
f=lambda a:sum(map(int,a))
```
[Try it online!](https://tio.run/##PY7BCsMgDIbvfYrcVLCMartBhk9SPDhaN0GtdN1hl726S1cY5M//JRDyl/f2WLKqdZo93HkQGE37iXMmPOlrWUPewPMwYrTCmJ0itn9uI1rReBNduk0OHD5fiSdXOJ1JJ0T1ywoBQoaRaa2ZZLr/9U4dw0UN5P1wpiKgtVKkjllsAI73QRLu2eoX "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
DµL‘:3‘Ṭ©œṗ⁸U®œṗЀS€€FE
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0FafRw0zrIyBxMOdaw6tPDr54c7pjxp3hB5aB2YenvCoaU0wEAORm@v/w@1A@v9/Y2NjHWMTIDY0AjHMjUx1TEzNgEgHKGBkBMSGAA "Jelly – Try It Online")
There must be a shorter way that somehow flew over my head...
[Answer]
# [Retina](https://github.com/m-ender/retina), 89 bytes
```
^|$
¶
{`¶(.)(.*)(.)¶
$1¶$2¶$3
}`^((.)*.)(.)¶((?<-2>.)*)¶(.)
$1¶$3$4$5¶
\d
$*
^(1+)¶\1¶\1$
```
[Try it online!](https://tio.run/##JYtBCgIxDEX3OUeEtGKhSasb0aWXGEoFXbhxIe4cr9UD9GL1jwN5EN7//3V/P57XsZFLHWVm6o0@tTcJToIHDoJjb6zA6FuLQPqwRiLn405PEO6/WavGiTN2043YU5G4RTrFBR7DzMgSiLo8B82U8h5HEKog/gA "Retina – Try It Online") Link includes test cases. Explanation: The first stage adds newlines at the start and end of the input. The second stage then tries to move digits across the newlines in pairs, however if there aren't enough digits left in the middle then the third stage is able to move them back, causing the loop to stop. The fourth stage then converts each digit separately to unary thus summing them, while the last stage simply checks that the sums are equal.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
DµL‘:3x2jSạ¥¥LRṁ@ḅ1E
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0FafRw0zrIwrjLKCH@5aeGjpoaU@QQ93Njo83NFq6Pr/6J7D7Y@a1rj//29sbKyjYGwCIgyNwExzI1MdBRNTMyDSUQCKGRkBsSEA "Jelly – Try It Online")
### How it works
```
DµL‘:3x2jSạ¥¥LRṁ@ḅ1E Main link. Argument: n
D Decimal; convert n to base 10, yielding a digits array A.
µ Begin a new chain with argument A.
L Compute the length of A.
‘ Increment; add 1 to the length.
:3 Divide the result by 3.
This yields the lengths of the outer chunks.
x2 Repeat the result twice, creating an array C.
L Compute l, the length of A.
¥ Combine the two links to the left into a dyadic chain.
This chain will be called with arguments C and l.
¥ Combine the two links to the left into a dyadic chain.
S Take the sum of C.
ạ Compute the absolute difference of the sum and l.
j Join C, using the result to the right as separator.
We now have an array of the lengths of all three chunks the
digits of n have to be split in.
R Range; map each chunk length k to [1, ..., k].
ṁ@ Mold swapped; takes the elements of A and give them the shape
of the array to the right, splitting A into chunks of the
computed lengths.
ḅ1 Convert each chunk from unary to integer, computing the sum
of its elements.
E Test if the resulting sums are all equal.
```
[Answer]
# Mathematica, 142 bytes
```
(s=IntegerDigits@#;c=Floor;If[Mod[t=Length@s,3]==2,a=-1;c=Ceiling,a=Mod[t,3]];Length@Union[Tr/@FoldPairList[TakeDrop,s,{z=c[t/3],z+a,z}]]==1)&
```
[Answer]
## Javascript, 178 bytes
```
(a)=>{b=a.split(/(\d)/).filter((v)=>v);s=Math.round(b.length/3);f=(m,v)=>m+parseInt(v);y=b.slice(s,-s).reduce(f,0);return b.slice(0,s).reduce(f,0)==y&&y==b.slice(-s).reduce(f,0)}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 26 bytes
```
3:jnZ^!S!tgtYswG48-*Z?da~a
```
[Try it online!](https://tio.run/##y00syfn/39gqKy8qTjFYsSS9JLK43F0xVFEryj4lsS7x/39DI2MjIyA2BAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N/YKivCKy8qTjFYsSS9JLK43EsxVFEryj4lsS7xv0vIf2NjYy5jEyA2NAIxzI1MuUxMzYCICyhgZATEhgA).
[Answer]
# [Röda](https://github.com/fergusq/roda), 82 bytes
```
f s{n=((#s+1)//3)[s[:n],s[n:#s-n],s[#s-n:]]|[chars(_)|[ord(_)-48]|sum]|[_=_,_=_1]}
```
[Try it online!](https://tio.run/##TU1BboMwEDzjV6ycHkAFRWCSVkj02Bf0ZlkEBaNYIrbltU8hb6eGtE2lXc3MzozWmaFflhHwpts03eFrme33LOPIGy1y5LrZYbGxFRshZn6@9A7TLpu5cUPEon4XM4ZrtLq2y@OW4r5ce6XhRpLROPASfXfuUcJgSJKgnZR/HnNAaVsKxQdQmMGGaQKlbfA5mOAjxooNeIHTy0NDC6f15pT2QL9ckBTUCOOjBXKKj37Mzz4KSpLBaEnuC2NsfbNWCKs3viUIK6v/zlt1@FP14RjnGY3Jqopb/ia@AQ "Röda – Try It Online")
Explanation:
```
f s{ /* function declaration */
n=((#s+1)//3)
[s[:n],s[n:#s-n],s[#s-n:]]| /* split the string */
[ /* for each of the three strings: */
chars(_)| /* push characters to the stream */
[ord(_)-48]| /* convert characters to integers */
sum /* sum the integers, push the result to the stream */
]|
[_=_,_=_1] /* take three values from the stream and compare equality */
}
```
[Answer]
# JavaScript, ~~129~~, 104 bytes
```
([...n],l=n.length/3+.5|0,r=(b,e=b*-4,z=0)=>n.slice(b,e).map(x=>z-=x)&&z)=>r(0,l)==r(-l)&&r(l,-l)==r(-l)
```
The function r slices the string based on parameters b and e, and then sums the digits and returns the value.
In order to slice in the correct sizes, we divide the length by 3 and round the result. Calling slice(0,result) gives us the first block, slice(result,-result) gives us the second, and slice(result) gives us the last. Due to the way I am calling slice, I used slice(result,4\*result) instead of the last one but it gives the same result.
Finally, I compare the results show the values are equal.
Edit: same principle, better golfing
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
gUSŽU]₂вXèûSX3÷*£OË
```
[Try it online](https://tio.run/##ASoA1f9vc2FiaWX//2dVU8W9VV3igoLQsljDqMO7U1gzw7cqwqNPw4v//zMxMjM) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf6fI/PTT46N7Q2EdNTRc2RRxecXh3cITx4e1ahxb7H@7@r/M/2tjYWMfYBIgNjUAMcyNTHRNTMyDSAQoYGQGxYSwA).
**Explanation:**
```
g # Get the length of the (implicit) input-integer
U # Pop and store this length in variable `X`
S # Convert the (implicit) input-integer to a list of digits
ŽU] # Push compressed integer 7769
₂в # Convert it to base-26 as list: [11,12,21]
Xè # Index the length `X` into it (modulair 0-based - i.e. lengths=3,6,..
# will index into 11; 4,7,.. into 12; and 5,8,.. into 21)
û # Palindromize this integer: 11→111; 12→121; 21→212
S # Convert it to a list of digits
X # Push length `X` again
3÷ # Integer-divide it by 3
* # Multiply it to each digit in the triplet
£ # Split input-list of digits into three parts of these sizes
O # Sum each inner part
Ë # And check if the three sums are all equal
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽU]` is `7769` and `ŽU]₂в` is `[11,12,21]`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16~~ 15 bytes
```
ËΣCẊ-mi¡+/3L¹0d
```
[Try it online!](https://tio.run/##yygtzv6vkPuoqfH/4e5zi50f7urSzc08tFBb39jn0E6DlP///0cbGxvrGJsAsaERiGFuZKpjYmoGRDpAASMjIDaMBQA "Husk – Try It Online")
Returns 4 for truthy and 0 for falsy.
## Explanation
```
ËΣCẊ-mi¡+/3L¹0d Input is a number, say n=34725.
L¹ Length of n (number of digits): 5
/3 Divide by 3 (gives a rational number): 5/3
¡+ Iterate addition of 5/3
0 starting from 0: [0,5/3,10/3,5,20/3,25/3,10,..]
mi Round each to the nearest integer: [0,2,3,5,7,8,10,..]
Ẋ- Differences between adjacent elements: [2,1,2,2,1,2,..]
C d Cut the digits of n to chunks of these lengths: [[3,4],[7],[2,5]]
Ë Are these lists equal by
Σ sum? (Returns 0 or length+1)
```
[Answer]
# Java 8, ~~149~~ ~~143~~ ~~140~~ ~~138~~ 137 bytes
```
q->{int l=q.length,s=-~l/3,a=0,b=0,c=0,i=0;for(;i<s;)a+=q[i++];for(s=l/3*2-~-l%3/2;i<=s;)b+=q[i++];for(;i<l;)c+=q[i++];return a==b&b==c;}
```
-9 bytes thanks to *@ceilingcat*.
Takes the input as an `int[]`.
**Explanation:**
[Try it here.](https://tio.run/##ZZHRTsIwFIbvfYoTE83mugIDNLHWxAeQGy4JF10pWCwtazsSQuDV53EsiJr2rOvXf9n/n67FTuRuq@x68dlII0KAd6Ht4QZA26j8UkgFk@8tQOmcUcKCTPBoNocqZciPWDhDFFFLmIAFDk2Vvx5QBIZX1Ci7ih8k8PxkekMieJ@UWBJL8z5bOp8w/RJYKjJezXSWzVsWOKofivyUm7thr0AJR035S4PQsFRemFex9hYE5@V9yblkx4ad7W3r0qC9zuXO6QVsMGcyjV7bFYYR6TlkVCEmQ4KjTXcBo79gQIr/mieE42s4ImPySNrnNW4/xiq6ddC18qeRrcVWi32klF4MTvchqg11daRb9B6NTdZ4ibSO2tA378U@0OjOuRKRZrfPcJtZKvG9@8mx@QI)
```
q->{ // Method with int-array parameter and boolean return-type
int l=q.length, // Length of the input-array
s=-~l/3, // (Length + 1) divided by 3
a=0,b=0,c=0, // Three sums starting at 0
i=0; // Index-integer
for(;i<s;) // Loop `i` in the range [0, `s1`):
a+=q[i++]; // Increase `a` by every `i`'th digit of the input-array
for(s=l/3*2-~-l%3/2;i<=s;)
// Loop `i` in the range [`s1`, `s2`):
b+=q[i++]; // Increase `b` by every `i`'th digit of the input-array
for(;i<l;) // Loop `i` in the range [`s2`, length):
c+=q[i++]; // Increase `c` by every `i`'th digit of the input-array
return a==b&b==c;} // Return whether `a`, `b` and `c` are all equal
```
Here is an overview of the 0-indexed \$[n,m)\$ parts for each length:
```
Length: Parts: 0-indexed ranges:
3 1,1,1 [0,1) & [1,1] & [2,3)
4 1,2,1 [0,1) & [1,2] & [3,4)
5 2,1,2 [0,2) & [2,2] & [3,5)
6 2,2,2 [0,2) & [2,3] & [4,6)
7 2,3,2 [0,2) & [2,4] & [5,7)
8 3,2,3 [0,3) & [3,4] & [5,8)
9 3,3,3 [0,3) & [3,5] & [6,9)
10 3,4,3 [0,3) & [3,6] & [7,10)
...
```
* For `a` we loop from `0` to `(length + 1) / 3)` (this value is now stored in `s`);
* For `b` we loop from `s` to and including `length / 3 * 2 - ((length + 1) % 3 / 2)`, where `((length + 1) % 3 / 2` is `0` if the length is divisible by 3 and `1` if not (this value is now stored in `s`);
* For `c` we loop from `s` to `length`.
[Answer]
# [L=tn](https://github.com/Ghilt/Listen), 35 bytes
```
cα;Gi≥l/3ö&i≤(2*l/3-1)öGi≠l¤2MαΣA=c
```
Explanation:
```
cα; - convert to digit list
G - Group to string (will be used to group the middle number)
i≥l/3ö&i≤(2*l/3-1)ö - The middle number is limited on its start & end index
Gi≠l¤2 - Group every item but the middle one
MαΣ - Map to digit sum
A=c - All sums equals to first sum of list
```
This returns a list, Only valid if empty list = falsy, and non-empty list = truthy
Note: The language is in progress and I did add stuff (specifically ≤ and ≥ operators) to code golf this. It's still competing though.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input is a string, output is an integer: `0` for false or `>0` for true.
```
ã á3 ˬ¥U«ÓDˬxÃâ Ê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=4yDhMyDLrKVVq9NEy6x4w%2bIgyg&input=IjM0NzI1Ig)
```
ã á3 ˬ¥U«ÓDˬxÃâ Ê :Implicit input of string U
ã :Substrings
á3 :Permutations of length 3
Ë :Map each D
¬ : Join
¥U : Equal to U?
« : AND NOT
Ó : Bitwise NOT of negation of
DË : Map D
¬ : Split
x : Sum
à : End map
â : Deduplicate
Ê : Length
:Implicit output of sum of resulting array
```
] |
[Question]
[
[Charcoal](https://github.com/somebody1234/Charcoal/) is a language created by ASCII-only and DLosc that specialises in ASCII art challenges.
What tips do you have for golfing in Charcoal? Obviously I am looking for tips related specifically to Charcoal, not those which can be applied to most - if not all - languages.
[Answer]
# Take advantage of the deverbosifier
Using the deverbosifier means you can write in ASCII (`--dv` or `--deverbosify` to deverbosify, `-v` or `--verbose` to execute as verbose code). Furthermore, it compresses strings for you, which can be useful in some ASCII-art challenges when the string to compress is too long.
[@Neil](https://codegolf.stackexchange.com/users/17602/neil) recommends using `-vl` or `-v --sl`. This is short for `--verbose --showlength`, meaning it will be interpreted as verbose Charcoal, and the length of the normal Charcoal code will be shown. Also, when deverbosifying, check the output to make sure that the input has actually been parsed correctly, since Charcoal generally ignores parse errors. If there *is* a syntax error, use `-a` (`--astify`) or `--oa` (`--onlyastify`) to help figure out the problem.
[Answer]
# Learn your reflections and rotations
There are a lot of variations of the basic reflection and rotation, so it pays to know what the subtle differences are. Key to tables:
* Command: Name of the command in Verbose mode.
* Transform: Whether Charcoal should attempt to flip or rotate the characters as it mirrors or rotates them. For instance, a `/` might become `\` after a rotate or flip.
* Keep Original: Whether Charcoal should merge the result with the original canvas.
* Overlap: (Only applies when Keep Original is Yes.) Determines the position of the axis of reflection/rotation, in half characters from the border. In the case of reflections, equivalent to the number of rows/columns that are not affected and end up in the middle of the result. In the case of rotations, the rotated copy is allowed to overwrite clear areas (but not spaces) in the original.
## Reflections
```
| Command | Transform | Keep Original | Overlap |
|-------------------------|-----------|---------------|---------|
| Reflect | No | No | n/a |
| ReflectCopy | No | Yes | 0 |
| ReflectOverlap | No | Yes | 1 |
| ReflectOverlapOverlap | No | Yes | n |
| ReflectTransform | Yes | No | n/a |
| ReflectMirror | Yes | Yes | 0 |
| ReflectButterfly | Yes | Yes | 1 |
| ReflectButterflyOverlap | Yes | Yes | n |
```
The direction of reflection is optional. The default is to reflect once to the right. For those reflections that keep the original, a multiple direction is allowed, which simply repeats the command for each direction. (This means that for instance `ReflectMirror(:¬)` will actually create four copies in total.)
The cursor is moved along with the reflection (even when the original is kept).
## Rotations
```
| Command | Transform | Keep Original | Overlap |
|-------------------------|-----------|---------------|---------|
| Rotate | No | No | n/a |
| RotateCopy | No | Yes | 0 |
| RotateOverlap | No | Yes | 1 |
| RotateOverlapOverlap | No | Yes | n |
| RotateTransform | Yes | No | n/a |
| RotatePrism | Yes | Yes | 0 |
| RotateShutter | Yes | Yes | 1 |
| RotateShutterOverlap | Yes | Yes | n |
```
For those rotations that keep the original, there is an optional origin of rotation. The default is the bottom right of the canvas. Allowable values are any of diagonal directions.
The amount of rotation (in 45° increments) is optional. The default is 2, i.e. 90° anticlockwise (counterclockwise). For those rotations that keep the original, there are two alternative options: a multidigit integer specifies to rotate the canvas once for each digit and then merge the results, while an integer list simply repeats the command for each rotation, with variable results depending on how the canvas changes in between.
[Answer]
# Use overloads
For example, many commands only need one argument:
* `Rectangle`, `Oblong` and `Box` make a square if only one argument is given
* `Reflect` commands default to reflecting right
* `Rotate` commands default to 90 degrees counterclockwise
* `Polygon` and `PolygonHollow` can accept a multidirectional and a side length. This can be used if all of the sides are the same length.
[Answer]
# Avoid consecutive constants of the same type
For example, `Plus(Times(i, 2), 1)` translates as `⁺×鲦¹`, but you can save a byte by switching the parameters: `Plus(1, Times(i, 2))` translates as `⁺¹×ι²` and `Plus(Times(2, i), 1)` as `⁺ײι¹` both of which save a byte. `Plus(1, Times(2, i))` (which translates as `⁺¹×²ι`) would be even better if there was another numeric constant following it.
[Answer]
# Use the predefined variables
Here is a list of all the variables that can be used, giving the succinct greek letter and the verbose letter that represents it.
```
α/a: The uppercase alphabet
β/b: The lowercase alphabet
γ/g: A string of all the ASCII characters from space to ~
δ/d: The fifth input
ε/e: The fourth input
ζ/z: The third input
η/h: The second input
θ/q: The first input
υ/u: An empty array
φ/f: 1000
χ/c: 10
ψ/y: The null character
ω/w: The empty string
```
The variables representing inputs will be empty if not enough input exists, but all other variables not shown here must be assigned before use.
[Answer]
# Use commands without a command character
An expression that is not part of a command is printed.
If it is preceded by a direction, the expression is printed in the specified direction.
Numbers are printed as a line with the specified length using a character selected from `\/-|`.
If a direction is not followed by an expression, it is counted as a move one space in the specified direction.
**Note:** This may sometimes be counted as part of the previous command so the command character may actually be required. (thanks [Neil](https://codegolf.stackexchange.com/users/17602/neil) for reminding me)
[Answer]
# Use multidirectionals
Some commands can accept multidirectionals: `+X*|-\/<>^KLTVY7¬⌊⌈`. What they expand to are [here](https://github.com/somebody1234/Charcoal/blob/master/interpreterprocessor.py#L58). In general, the direction list starts from up and continues clockwise.
[Answer]
## Make full use of `Sum`
`Sum` has lots of handy overloads:
* On a list of strings, concatenates them together. However, if it's possible that the list might be empty, this would give None, so in this case, use `Join(..., "")` instead.
* On a non-empty list of numbers, simply takes their sum.
* On a non-empty list of lists, concatenates them together (flattens to depth 1).
* On an integer, takes the sum of its digits. (Floating-point values are truncated to integer. If you want the sum of the decimal places, cast to string first.)
* On a string containing only digits and optionally one `.` character, takes the sum of the digits.
* On a string containing numbers and separators, takes the sum of the numbers cast to int or float (but note that `-` counts as a separator).
A convenient side-effect of the last two rules is that if you use `Sum` on a character then the digits `1-9` get cast to their value and everything else returns zero, unlike `Cast`, which fails for non-digit values.
[Answer]
## Use Filter to slice the first character from an array or string
Even if you're lucky, using `Slice` to slice the first character from a string takes 2 bytes: `Slice(..., 1)`. It will take longer if the expression to be sliced ends in a number, requiring a separator, or if the following code can be interpreted as an expression, as in that case `Slice` will want to consume it as an additional parameter.
Instead, just use `Filter(..., k)`, which drops the first element, thus achieving the desired result. (Obviously use the appropriate loop index variable if your expression is nested inside another loop.) This is always 2 bytes and cannot be affected by surrounding code.
[Answer]
## Use switch instead of if (Equals(...)) where possible
The construct
```
if (Equals(q, h)) ...
else ...
```
takes 4 bytes but written as a switch it only takes 3 bytes:
```
switch (q) {
case h: ...
default: ...
}
```
However this only works if the `else` portion can be unambiguously parsed as a command rather than an expression. In particular:
* If the `else` portion is empty, then this only works at the end of a block or program, but that was true for the original `if` statement.
* If the `else` portion contains multiple commands, then this works as an `if` but not as a `switch`.
* If the `else` portion prints an expression, then this only works as a `switch` at the end of a block or program.
[Answer]
## Some useful uses of `Base`
`Base(array, 1)` is like `Sum(array)` for a numeric array, but it returns `0` when the array is empty, while `Sum` returns `None`, which is usually inconvenient to process, unless you're using it in a Boolean context.
`Base(array, 0)` returns the last element of a numeric array (or `0` if the array is empty) without modifying the array.
`Base([x, y], Negate(1))` returns `y-x`. This is useful to compare the elements of a two-element array for equality (typically calculated from a `Map`).
`Base(array, number)` also works to substitute a number in a polynomial.
In all the above cases the two parameters can be exchanged if it is inconvenient to have the number second (i.e. if it would require two consecutive numbers to be separated).
[Answer]
# Use split for a string array, split and cast for a number array
Split for a string array is only three characters of overhead, and split and cast is only four characters of overhead. Compare this to writing the array literally, which would require array start and end, *and* a separator between every array element.
If your number array only has numbers less than 95, use either a cast (if all numbers are less than 10) or index into one of the predefined variables.
] |
[Question]
[
Write a function to convert CamelCased text to snake\_case: `FunctionForHTMLManipulation` becomes `function_for_html_manipulation`
The input text will be a single suitable identifier in many languages. It must start with an English letter, then be followed by any number of English letters or digits. No other characters (spaces, symbols, etc.) are allowed.
Each "word" within the CamelCased text will start with a capital letter unless at the beginning of the text or immediately after a digit, and be followed by zero or more letters, all of the same case. Groups of digits will be considered as separate words but pass through unchanged.
In other words, a lowercase letter followed by an uppercase letter indicates a word break. Any letter and digit next to each other indicates a word break. An uppercase letter followed by another uppercase letter and a lowercase letter indicates a word break.
`...lU...` => `...l_u...`
`...l9...` => `...l_9...`
`...U9...` => `...u_9...`
`...9l...` => `...9_l...`
`...9U...` => `...9_u...`
`...UUl...` => `...u_ul...`
Both `Buy24Beers` and `buy24beers` become `buy_24_beers`.
`MacDonaldAndObrian` becomes `mac_donald_and_obrian`.
`MACDonaldAndOBrian` becomes `mac_donald_and_o_brian`.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~61~~ 37 bytes
```
r1>`[A-Z]?[a-z]+|[A-Z]+|\d+
_$&
T`L`l
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApyMT5gW0EtWl0_W2Etel0rfFtBLVpdK3xcZCsKXyQmClRgTGBs&input=VGVzdFRFU1RJTkcyNFRlc3RpbmdUZXN0aW5nCkJ1eTI0QmVlcnMKYnV5MjRiZWVycwpNYWNEb25hbGRBbmRPYnJpYW4KTUFDRG9uYWxkQW5kT0JyaWFu) (Slightly modified to run a full test suite.)
### Explanation
Instead of finding word boundaries to insert underscores, we simply match each word and prepend a `_`. Matching words from the left is a bit annoying because of the `UUl` rule, but using .NET's right-to-left matching we can easily match words greedily. To avoid a leading `_`, we make use of Retina's limits.
```
r1>`[A-Z]?[a-z]+|[A-Z]+|\d+
_$&
```
The `r` activates right-to-left mode, the `1>` tells Retina to process everything except the first match (counting from left to right). Then there's four types of "words": `Ulll`, `lll`, `UUU`, `ddd`. These are easily matched with the given pattern. The substitution just writes a `_` followed by the word itself.
```
T`L`l
```
This simply turns upper case into lower case to complete the transformation.
[Answer]
# JavaScript (ES6), 79 bytes
```
s=>s.match(/[A-Z]+(?=[A-Z][a-z]|\d|$)|[A-Z]?[a-z]+|\d+/g).join`_`.toLowerCase()
```
[Answer]
## JavaScript (ES6), 89 bytes
```
s=>s.replace(/\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])/g,"$&_").toLowerCase()
```
[Answer]
# [Lua](https://www.lua.org), 135 bytes
```
function snake(s)return s:gsub('%f[^%l]%u','_%1'):gsub('%f[^%a]%d','_%1'):gsub('%f[^%d]%a','_%1'):gsub('(%u)(%u%l)','%1_%2'):lower()end
```
[Try it online!](https://tio.run/##bY4xCgIxEEWvss0wGbBZS7tVW/EAEpfRZCUYJkuSwePHYCVi8Yv3XvOjcmuLyr2GJEMRfnpTKPuquePuUfRmEJbLFaIFxQ3OMCJ9e7bg/nlngX@8AaU@iNQDjDNse4rp5bMhL66tOUg1nxMDnqbDMQlHN4k773NgQWpv "Lua – Try It Online")
This solution benefits from Lua's shorthand notation for C's character classes (lowercase `%l`, uppercase `%u`, alphabetic `%a`, digit `%d`), frontier notation (`%f[]`), and from the whole match being added as the implicit first capture in the absence of any other captures.
[Answer]
# Powershell, 77 bytes
*Based on Neil's [answer](https://codegolf.stackexchange.com/a/78242/80745).*
```
$args-creplace'\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|.(?=[A-Z][a-z])','$&_'|% *wer
```
Less golfed test script:
```
$f = {
$args-creplace'\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|.(?=[A-Z][a-z])','$&_'|% toLower
}
@(
,("Buy24Beers", "buy_24_beers")
,("buy24beers", "buy_24_beers")
,("MacDonaldAndObrian", "mac_donald_and_obrian")
,("MACDonaldAndOBrian", "mac_donald_and_o_brian")
,("BigD", "big_d")
) | % {
$s,$expected = $_
$result = &$f $s
"$($result-ceq$expected): $result"
}
```
Output:
```
True: buy_24_beers
True: buy_24_beers
True: mac_donald_and_obrian
True: mac_donald_and_o_brian
True: big_d
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 62 bytes
Shamelessly translated from the [JavaScript solution](https://codegolf.stackexchange.com/a/78242/48934).
```
\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])
$&_
T`L`l
```
[Try it online!](http://retina.tryitonline.net/#code=XGQoPz1cRCl8XEQoPz1cZCl8W2Etel0oPz1bQS1aXSl8W0EtWl0oPz1bQS1aXVthLXpdKQokJl8KVGBMYGw&input=VGVzdFRFU1RJTkcyNFRlc3RpbmdUZXN0aW5n)
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
lambda x:re.sub('(\d+|.([A-Z]*|[a-z]*)(?![a-z]))(?!$)','\\1_',x).lower()
import re
```
[Try it online!](https://tio.run/##HcZBC4IwFADge7/CINh7poM6BhFW1@ieE5ls0mBu4zXRwv@@qO/0hXd8erdP/VEkK4dOyWw@kOavsQMGQm0XDnVVPpp8qWX5aXKE0/o//G2DrGBC7FpWzMitnzQBrswQPMWMdApkXMx6IDm1xoUxAmK6VZerd9Kqyqn7mYx0Xw "Python 2 – Try It Online")
[Answer]
# PowerShell, 68 92 bytes
Briefly deleted, +24 bytes for using the wrong RegEx.
```
($args-creplace'\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|.(?=[A-Z][a-z])','$&_').Trim('_').ToLower()
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9WDe5KLUgJzE5VT0mRcPeNsZFsybGBcRI0ayJTtStigWyox11o2I1a/RgTLC4prqOuopavLqmXkhRZq6GOpiV7wOyQEPz////SaWVRiZJqUDrAA "PowerShell – Try It Online")
Basically the same as the JavaScript solutions.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 61 bytes
```
{S:g:P5/\d+|[A-Z]+(?=[A-Z]|\d)|[A-Z][a-z]*/{$/.lc~"_"}/.chop}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplmb7vzrYKt0qwFQ/JkW7JtpRNypWW8PeFsyoiUnRhAhFJ@pWxWrpV6vo6@Uk1ynFK9Xq6yVn5BfU/rfmKk6sVEjTUHIqrTQycUpNLSpW0oQL@iYmu@TnJeakOOal@CcVZSbmIUs6OiMknTAljUyA/P8A "Perl 6 – Try It Online")
[Answer]
# Factor, 140 bytes
```
[ R/ [a-z][A-Z][a-z]/ [ dup from>> swap dup to>> swap seq>> subseq R/ [A-Z][a-z]/ [ "_" prepend ] re-replace-with ] re-replace-with >lower ]
```
Ungolfed:
```
: slice>subseq ( slice -- subseq )
dup from>> swap dup to>> swap seq>> subseq ;
: camel-case>snake-case ( string -- string' )
R/ [a-z][A-Z][a-z]/ [
slice>subseq R/ [A-Z][a-z]/
[ "_" prepend ] re-replace-with
] re-replace-with >lower ;
```
] |
[Question]
[
This challenged is highly inspired by what @Mego created with his [Holy](https://codegolf.stackexchange.com/q/73426/41019) and [Holier](https://codegolf.stackexchange.com/q/74033/41019) numbers, lots of thanks to him and his puns.
Holy numbers are numbers composed of only the digits with *holes*, which are:
```
04689
```
Numbers with at least one unholy digit are considered unholy. Unholy digits are evil by definition, but being close to holy digits help them become neutral. Hence, the closer they are, the less unholy (1 when adjacent).
The unholiness of a number is the sum of the unholyness of its digits, a number composed of only unholy number has an infinite unholiness.
```
Number :8 5 5 8 7
Digital Unholiness:0+1+1+0+1
Total Unholiness :3
Number :0 1 7 5 5 2 8 5 7
Digital Unholiness:0+1+2+3+2+1+0+1+2
Total Unholiness :12
Number :1 5 7 3 2 1
Digital Unholiness:∞+∞+∞+∞+∞+∞
Total Unholiness :∞
Number :0 4 6 8 9
Digital Unholiness:0+0+0+0+0
Total Unholiness :0
```
### Your task
You have to write a program or function that takes a positive integer or a string only composed of digits as input, and output its unholiness. If you chose to use an integer as input, you can assume it will never have a leading `0` as your language may drop it.
In case of infinite unholiness, you can chose between three outputs
* The character `∞` (3 bytes)
* Infinite output containing at least 1 non-zero digit, but only digits.
* A built-in `Infinity` value.
This is code-golf, so the shortest code in byte wins, good luck!
[Answer]
# [GNU APL](https://www.gnu.org/software/apl/), 27 bytes
```
{+/⌊/|(⍳⍴⍵)∘.-(⍵⍳⍕⍟788)~⍴⍵}
```
[Try it online!](http://juergen-sauermann.de/try-GNU-APL)
To try it out using the above link, IO must be set to 0 and the input is provided as a string. For example:
```
⎕IO←0
{+/⌊/|(⍳⍴⍵)∘.-(⍵⍳⍕⍟788)~⍴⍵}'017552857'
```
## Explanation
```
{+/⌊/|(⍳⍴⍵)∘.-(⍵⍳⍕⍟788)~⍴⍵} ⍝ Note: below explanation uses as example input 017552857
{ ⍝ dfn
⍟788 ⍝ computes natural log of 788, which happens to be 6.66949809, containing only (and all) holy digits
⍕ ⍝ Converts this number to a string
⍵⍳ ⍝ Finds the indexes of chars in the right argument ⍵ which are present in the computed decimal. Items not found map to the length of the list, e.g. '017552857'⍳'6.66949809' -> 9 9 9 9 9 9 9 6 0 9
~⍴⍵ ⍝ Removed all non-found indexes from the list 9 9 9 9 9 9 9 6 0 9 -> 6 0
(⍳⍴⍵) ⍝ List of ascending integers up the length of the argument ⍵: 0 1 2 3 4 5 6 7 8
∘.- ⍝ Inner product of the ascending integers 0..8 minus the match indexes 6 0. Result is ¯6 0, ¯5 1, .., 2 8
| ⍝ Absolute value of all elements
⌊/ ⍝ Take the minimum of each pair to get the closest distance to a Holy number 0 1 2 3 2 1 0 1 2
+/ ⍝ Sum this list
```
The reason for choosing GNU APL is that handily it will return the internal representation of infinity, '∞', when calculating the minimum value of the empty list. Summing this still retains ∞, which is then returned.
`⍟788` was a cheeky way to lose a byte. I ended up writing a program to brute force inputs to functions until I found a suitable result which contained only holy numbers. Brute force program below:
```
(,(⍳99)∘.{∧/(~'12357'∊c),'04689'∊(c←⍕b←⍺÷⍵):(⍺,'f',⍵,'=',b,'|') ⋄ 0}⍳99)~0
```
In this case it sees if any values of `⍺÷⍵` in `0 < ⍺,⍵ < 100` meet the condition. I manually played around with the functions to test.
It's a bit of a shame that this challenge doesn't allow undefined behaviour for the infinity case or that Dyalog doesn't return an infinite data type instead of throwing an error, otherwise the following solution would work in Dyalog APL:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 bytes
```
{+/⌊/|(⍳⍴⍵)∘.-⍸⍵∊⍕⍟788}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6u19R/1dOnXaDzq3fyod8uj3q2ajzpm6Ok@6t0BZD/q6HrUO/VR73xzC4va/2lAHY96@yCau5oPrTd@1DYRyAsOcgaSIR6ewf/TFNQNDM1NTY0sTM3VFR71zlUwNOICClqYmlpABYxBfAMTMwtLCN8AAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
## Python (3), ~~137~~ 131 bytes
```
def f(s):
l=range(len(s))
r=[min(i)for i in zip(*[[abs(j-i)for j in l]for i in l if s[i]in'46890'])]
return sum(r)if r else'∞'
```
## Results
```
>>> [f(i) for i in ['85587', '012321857', '157321', '04689']]
[3, 12, '∞', 0]
```
[Answer]
# [Ruby (2.7+)](https://www.ruby-lang.org/), ~~69~~ 63 chars, ~~71~~ 65 bytes
```
->n{x=!r=l=0;n.map{'04689'[_1]?x=l=0*r-=l*l/4:r+=l+=1};x ?r:?∞}
```
Unsupported by TIO
# [Ruby (other)](https://www.ruby-lang.org/), ~~71~~ 65 chars, ~~73~~ 67 bytes
```
->n{x=!r=l=0;n.map{|c|'04689'[c]?x=l=0*r-=l*l/4:r+=l+=1};x ?r:?∞}
```
[Try it online!](https://tio.run/##Nc1NDoIwEIbhvacYYVHlzxasIKZykIYFVokkCKZKgindewoP50WwEt0@834Z2R0eY8lGf9@ons0lqxneNcGluKpBDAivN8kWcZFn/ffiSJ/VTr1ap9JltcuI3vWQyTR7P1965DMAjhJKkxh5AFHuTYBJTGmY0AlJ@FNC4ygkhpDZon86vTMZNpAHp0Kc4djCUHnQDqa4dvcbWLaqNPh7sFXJq0CcC3nLNSxs1eqlNTs1x/ED "Ruby – Try It Online")
## How it works:
* Iterate through the digits
* If a digit is holy
* reset increment
* subtract a number\* from the score to correct the overcounting
* If a digit is unholy
* add 1 to increment
* add increment to score
\*turns out this number depends only on the current value of the increment (`l` in the code), it's [OEIS A002620](https://oeis.org/search?q=0%2C1%2C2%2C4%2C6%2C9%2C12) (quarter squares) (`l*l/4` in the code).
Returns the `∞` character in case of infinity.
Interesting trick: `x=l=0*r-=l*l/4` is equivalent to `(r-=l*l/4;x=l=0)` but using `*` instead of `;` makes it a single statement allowing `()` to be dropped.
Edit: changed input type, now takes a list of characters.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~25~~ 24 bytes
```
7Zq1hVmt~f!wf-|X<st~?xYY
```
[**Try it online!**](http://matl.tryitonline.net/#code=N1pxMWhWbXR-ZiF3Zi18WDxzdH4_eFlZ&input=JzAxMjMyMTg1Nyc)
Input is a string. In the output, infinity is natively displayed as `Inf`.
### Explanation
```
7 % number literal
Zq % prime numbers up to a 7: [2 3 5 7]
1 % number literal
h % horizontal concatenation
V % convert numbers to string: '2 3 5 7 1'
m % take input implicitly. Determine which digits are 1,2,3,5,7
t % duplicate
~ % element-wise negate: which digits are 4,6,8,9,0
f % indices of occurrences of digits 4,6,8,9,0
! % transpose into column array
w % swap elements in stack
f % indices of occurrences of digits 1,2,3,5,7
- % element-wise subtraction with broadcast. Gives 2D array
| % element-wise absolute value
X< % minimum of each column
s % sum of elements of array
t % duplicate
~ % element-wise negate
? % if all elements are true
x % delete
YY % push infinity
% (implicit) end if
% (implicit) convert to string and display
```
[Answer]
# Pyth, ~~31~~ ~~29~~ ~~27~~ 25 bytes
```
smhS.e?}b"04689"akd.n4zUz
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=smhS.e%3F%7Db%2204689%22akd.n4zUz&input=012321857&test_suite=1&test_suite_input=85587%0A012321857%0A157321%0A04689&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=smhS.e%3F%7Db%2204689%22akd.n4zUz&input=012321857&test_suite=1&test_suite_input=85587%0A012321857%0A157321%0A04689&debug=0)
For each digit I compute the distances to each number. A distance is infinty, if the second digit is not holy. From these lists I take the minimal distance and sum it up.
### Explanation:
```
smhS.e?}b"04689"akd.n4zUz implicit: z = input string of numbers
m Uz map each d in [0, 1, ..., len(z)-1] to:
.e z map each k (index), b (value) of b to:
akd absolute difference between k and d
?}b"04689" if b in "04689" else
.n4 infinity
S sort
h take the first element (=minimum)
s print the sum
```
[Answer]
## JavaScript (ES6), 93 bytes
```
s=>[...s].map(n=>/[12357]/.test(n)?++u:u=0,u=1/0).reverse().map(n=>r+=n?n<++u?n:u:u=0,r=0)&&r
```
If `Infinity` isn't a legal infinity, then add 13 bytes for `==1/0?'∞':r`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŽāĀISåƶZĀiāδαø€ßOë'∞
```
[Try it online](https://tio.run/##ATcAyP9vc2FiaWX//8W9xIHEgElTw6XGtlrEgGnEgc60zrHDuOKCrMOfT8OrJ@KInv//MDE3NTUyODU3) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/6N7jzQeaagMPrz02LaoIw2ZRxrPbTm38fCOR01rDs/3P7xa/VHHvP@1Ov8tTE0tzLkMDM1NTY0sTM25DE3NjY0MuQxMzCwsuQwsgIIQKWMA).
**Explanation:**
```
ŽāĀ # Push compressed integer 40689
IS # Push the input-string, converted to a list of digits
# i.e. "085281755283" → [0,8,5,2,8,1,7,5,5,2,8,3]
å # Check for each digit if it's in 40689 (1 if truthy; 0 if falsey)
# → [1,1,0,0,1,0,0,0,0,0,1,0]
ƶ # Multiply each value by its 1-based index
# → [1,2,0,0,5,0,0,0,0,0,11,0]
Z # Push the maximum of this list (without popping)
# → 11
Āi # If this maximum is not 0 (so there are holy digits present):
# → 1 (truthy)
ā # Push a list in the range [1, list-length] (without popping the list)
# → [1,2,3,4,5,6,7,8,9,10,11,12]
δ # Apply double-vectorized:
α # Take the absolute difference between each value
# → [[0,1,2,3,4,5,6,7,8,9,10,11],[1,0,1,2,3,4,5,6,7,8,9,10],
# [1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12],
# [4,3,2,1,0,1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8,9,10,11,12],
# [1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12],
# [1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12],
# [10,9,8,7,6,5,4,3,2,1,0,1],[1,2,3,4,5,6,7,8,9,10,11,12]]
ø # Then zip/transpose the list of lists; swapping rows/columns
# → [[0,1,1,1,4,1,1,1,1,1,10,1],[1,0,2,2,3,2,2,2,2,2,9,2],
# [2,1,3,3,2,3,3,3,3,3,8,3],[3,2,4,4,1,4,4,4,4,4,7,4],
# [4,3,5,5,0,5,5,5,5,5,6,5],[5,4,6,6,1,6,6,6,6,6,5,6],
# [6,5,7,7,2,7,7,7,7,7,4,7],[7,6,8,8,3,8,8,8,8,8,3,8],
# [8,7,9,9,4,9,9,9,9,9,2,9],[9,8,10,10,5,10,10,10,10,10,1,10],
# [10,9,11,11,6,11,11,11,11,11,0,11],[11,10,12,12,7,12,12,12,12,12,1,12]]
ۧ # Get the minimum of each inner list
# → [0,0,1,1,0,1,2,3,2,1,0,1]
O # And sum everything together
# → 12
ë # Else (no holy digits are present)
'∞ '# Push string "∞" instead
# (after which the top of the stack 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 `ŽāĀ` is `40689`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes
```
Dµ+ỊẒµ¬TạþTṂ€µ»İS
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0Fbth7u7Hu6adGjroTUhD3ctPLwv5OHOpkdNa4ACu49sCP5/uB3I@f/fwtTUwlzHzNDc1NTIwtRcx9DU3NjIUMfEzMLSQAcuCuLqAAA "Jelly – Try It Online")
*-1 thanks to Jonathan Allan*
Did a lot of fiddling with compressed strings and `ȷ` literals before I realized that division by zero gives infinity. Takes input as an integer, since conversion to a digit list is one byte shorter (`D` versus `V€`)--and since half of the test cases have leading zeroes, which the spec also guarantees an integer-input solution never has to handle, [here's the string version as well](https://tio.run/##y0rNyan8/z/sUdOaQ1u1H@7uerhr0qGth9aEPNy18PC@kIc7m8Ayh3Yf2RD8/3A7kBP5/7@ShamphbmSjpKBobmpqZGFKYhtaGpubGQIEjQxs7BUAgA).
Jonathan Allan's golf cleverly avoids having to distinguish two different sources of zeroes by not finding the distances between holy digits and themselves.
```
Dµ Consider the decimal digits of the input.
+Ị Increment 0s to 1s and 1s to 2s.
Ẓ For each digit, is it prime?
µ With this list of 0s for holy digits and 1s for holy digits,
ạþ table the absolute differences between
¬T the indices of holy digits
T and the indices of unholy digits.
Ṃ€ Take the minimum from each row,
S and sum
» the maxima of those minima and
µ İ their inverses.
```
[Answer]
# [R](https://www.r-project.org/), 100 bytes
```
sum(sapply(0:(d=log10(n<-scan()))+1,function(x)min(abs(x-which(n%/%10^(0:d)%%10%in%c(0,4,6,8,9))))))
```
[Try it online!](https://tio.run/##HcvRCoJAEEbhpxn4h0aaLTONepVgWykXdBQ3yZ5@k87Vd3PmnNMyIPlp6r/QC9pbP76cwq5FCt7AzDsnz8XCO46GlYdo8I@Etfh0MXQw2pPT@/a2TJsoGgWolFJJLQ3/y@5wLE/VuW40/wA "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
lambda s:sum(min([9e999]+[abs(i-j)for j,c in enumerate(s)if c in'04689'])for i in range(len(s)))
```
[Try it online!](https://tio.run/##VcxBDoIwEEDRvaforjNRE6pWWhNPgiyKtlpCB9LCwtNXYGHC9uflD9/x09M5u/sjdyY0L8PSLU0BgieotNVa1/vKNAn8sUXXR9YenswTszQFG81oIaF3bGm8uFyV5vXK/IKiobeFztKMEPMQPY3ggCspVckRd/9SiFLKk5LbKsQWrf959AM "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
s=>s.reduce((m,c,i)=>m+Math.min(...s.map(c=>(i*i--)**.5+(174&1<<c?1/0:0))),0)
```
[Try it online!](https://tio.run/##dZHBToQwEIbvPMWc3JZCobArKy7sxexNT3rbA1gaqAFKaNdn8Cl8OF8Eu8SDJrV/poeZ9Pun@d/q91rzWU4mHFUjllOx6KLUdBbNhQuEhoAHEhflQB5r09FBjohSqulQT4gXJZK@DEPs@3RHEMu2N@xw4EcWxXmMMQ5ivNxX3tNleBUz/Dr5HnZWe8i8B9lKU/fwMnaql6PQOo8Js7K396z@juzL1HPxYmCQrcwEruwM/gMnJLW14kniMmCJ04Gt1NTymQv99fFJHOUyuLbdf9jCrd3@zr36j1zE2KtsIIZ3KDo36JjDucEkavGakilKrkatekF71SITwCYsNwGckKF66qWpoLJZLd8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
In the Bitcoin protocol, **2016** is a very special number. The "difficulty" of finding a hash to create a new block is adjusted every 2,016 blocks to approximate changing once every two weeks.
This number was chosen is because the difficulty adjusts itself so that every block takes about 10 minutes to be found, and in two weeks, there are 2 × 7 × 24 × 6 = 2,016 ten-minute periods.
---
To commemorate this numerical coincidence, this year's New Year's problem is about Bitcoin — specifically, the hashing algorithm it uses to sign blocks, SHA-256.
Your task is to create a program that will take byte input (in at least ASCII) and output a nonce in bytes (in the format of your choice) that will produce a SHA-256 hash containing `2016` in its *base64* representation when appended to the original byte input.
Here are some examples of valid solutions, courtesy of the engines people have already generated, as well as the hashes they produced:
```
> foo
Nonce: 196870
SHA256 hash: OCUdDDtQ42wUlKz2016x+NROo8P2lbJf8F4yCKedTLE=
> bar
Nonce: 48230
SHA256 hash: CNcaOCQgT7bnlQzQPXNwuBu8/LYEdk2016khRaROyZk=
> happynewyear
Nonce: 1740131
SHA256 hash: XsKke6z2016BzB+wRNCm53LKJ6TW6ir66GwuC8oz1nQ=
> 2016
Nonce: 494069
SHA256 hash: rWAHW2YFhHCr22016zw+Sog6aW76eImgO5Lh72u6o5s=
(note: the nonces don't actually have to be ASCII numbers; you can do
any byte input you find convenient.)
```
The only pre-built library (other than standard input and output functions) your program may use is a `SHA256(bytes)` function that takes byte input and returns a SHA256 hash, in any format including base64.
The program to do this in the fewest bytes of source code wins.
[Answer]
# Mathematica, 94
```
(For[i=0,IntegerDigits[4Hash[#<>ToString@++i,"SHA256"],64]~SequenceCount~{54,52,53,58}<1,];i)&
```
This function will try positive integers as candidates. It takes over 4 minutes on my laptop to get the correct answer.
```
%["foo"]
(* 196870 *)
```
Longer however faster (`~5x`) implementation makes use of parallelization:
```
f[k_]:=
Do[If[Length@#>0,Return[i+#[[1,1]]]]&@
Position[ParallelMap[IntegerDigits[4Hash[k<>ToString@#,"SHA256"],64]
~SequenceCount~{54,52,53,58}&,i+Range@1*^4],1]
,{i,0,∞,1*^4}]
```
[Answer]
# Perl 5.10+, 39 + 18 = 57 bytes
```
sha256_base64($_.++$i)!~2016?redo:say$i
```
This needs to be run with the `-nMDigest::SHA=/./` command line switch, which is included in the byte count. It also uses the Perl 5.10+ `say` feature, and so needs to be run with the `-M5.010` (or `-E`) command line switch, which [is considered free.](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions) The input should be provided on stdin, without a trailing newline (unless you want the newline to be considered part of the input).
Examples:
```
$ echo -n foo | perl -nMDigest::SHA=/./ -E 'sha256_base64($_.++$i)!~2016?redo:say$i'
196870
$ echo -n bar | perl -nMDigest::SHA=/./ -E 'sha256_base64($_.++$i)!~2016?redo:say$i'
48230
$ echo -n happynewyear | perl -nMDigest::SHA=/./ -E 'sha256_base64($_.++$i)!~2016?redo:say$i'
1740131
$ echo -n 2016 | perl -nMDigest::SHA=/./ -E 'sha256_base64($_.++$i)!~2016?redo:say$i'
494069
```
[Answer]
# Ruby, ~~87~~ 86 bytes
I'm not sure if I understood the challenge correctly, but it finds `196870` in a few seconds if you input `foo`.
```
require"digest"
gets.chop!
$.+=1until/2016/=~Digest::SHA256.base64digest("#$_#$.")
p$.
```
[Answer]
# PowerShell, 150 ~~152~~ ~~153~~ bytes
```
while([Convert]::ToBase64String([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("$args$i")))-notmatch2016){$i++}$i
```
# Example
```
PS > .\BitCoin.ps1 foo
196870
PS > .\BitCoin.ps1 bar
48230
PS > .\BitCoin.ps1 happynewyear
1740131
PS > .\BitCoin.ps1 2016
494069
```
[Answer]
# C#, 179 bytes
```
s=>{int i=0;while(!System.Convert.ToBase64String(System.Security.Cryptography.SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(s+i))).Contains("2016"))i++;return i;}
```
Similar to the PowerShell solution, just longer.
] |
[Question]
[
**This question already has answers here**:
[Exploit "free whitespace"](/questions/3615/exploit-free-whitespace)
(10 answers)
Closed 4 years ago.
## Introduction
Consider the following example:
```
CODE
+ GOLF
——————
GREAT
```
This is an equation where each letter represents a decimal digit and the words represent natural numbers (similar letters represent similar digits and different letters represent different digits). The task is to match each letter with its digit value so that the equation is correct. One solution for the equation above is:
```
9265
+ 1278
——————
10543
```
## Your task
Your task is to write a program or a function which can solve such equations as seen above.
**Input**
The input is a string in the following format:
```
[A-Z]+\+[A-Z]+=[A-Z]+
```
Example:
1. `CODE+GOLF=GREAT`
2. `AA+BB=CC`
Spaces are omitted and only letters between capital A and Z will be used (no special or small letters).
This string can be read from the standard input, from a file, or as a function parameter.
**Output**
You have the following two options for the output format:
1. the original equation with the digits substituted
2. list of the letters and their values
If there are multiple solutions, any (but only one) of them should be returned. If there are no solutions, the program should return an empty string or null.
The output can be returned as a string, can be written to the standard output or a file.
Example:
1. `9265+1278=10543`
2. `A=1 B=2 C=3` (you can use any delimiter)
## Rules
1. To make things easier, numbers are accepted to start with 0, but you can handle numbers with leading 0 as invalid solutions, it's up to you
2. Similar letters represent similar digits and different letters represent different digits
3. You can use any language and the standard library of the chosen language (no external libs)
4. You cannot connect to any resources on the internet (why would you anyways?)
5. This is a code golf task, shortest code wins. Consecutive whitespace characters count as a single character. (So any program written in whitespace automatically wins)
I have a somewhat hackish solution using 179 chars. If something is not clear, please ask me in the comments.
[Answer]
# Python - 48 characters
```
exec("".join(map(chr,map(len,' '.split(" ")))))
```
Abusing the whitespace rule.
First I converted every character in CesiumLifeJacket's answer to its ASCII value (I could have written my own but I am lazy, and it wouldn't have affected the final score anyway). The long string in my solution is one space for each one of those ASCII values, and tabs separating them. Split at tabs, find the lengths, convert back to characters and execute.
SE converts tabs to 4 spaces each, so copypasting won't work. You'll just have to believe me :)
[Answer]
## Ruby 2.0, 122 characters
Brute force shuffling+eval! ~~This doesn't yet meet the criteria of returning null/empty string when there is no solution; it just loops infinitely.~~ If it can't find a result after ~300 million iterations, it will return nil. Close enough?
```
f=->s{d=*0..9
d.shuffle!&&$.+=1until$.>9**9||z=eval((r=$_.tr(s.scan(/\w/).uniq*'',d*'')).gsub(/\b0/,'').sub ?=,'==')
z&&r}
```
It finds all the unique letters in the input, then repeatedly shuffles the digits 0-9 and attempts to match them up with the letters until it finds a configuration that works.
The code is presented as a function called `f` which returns a string with the numbers substituted, as in Output Option 1 above. Example usage:
```
puts f["AA+BB=CC"]
#=> 22+44=66
puts f["CODE+GOLF=GREAT"]
#=> 8673+0642=09315
```
Running time for the `CODE+GOLF=GREAT` example on my machine varies from instantaneous to about 6 seconds - depends on how lucky you are with the shuffles!
I'm particularly unhappy with the `gsub(/\b0/,'')` bit to remove leading zeroes but it was the only thing I could think to prevent `eval` from interpreting the numbers as octal ints.
(**BONUS**: Because it uses eval, it works for arbitrary Ruby expressions and not just addition!)
[Answer]
## LiveScript (179 chars)
It has deterministic and relatively quick running time and works with other operators (+, -, \*) as well.
```
f=(s)-> # define function that takes parameter s
c=s.replace /[^A-Z]/g '' # remove all the non-letters
if c # if any letters remain
for i from 0 to 9 # loop from 0 to 9
if s.indexOf(i)<0&&a=f s.split(c.0).join i # if i is not present in the number, replace the first letter with i and call the function recursively
return a # if there is a solution, return it
else # if there are no letters left
if eval s.replace(/(^|\D)0+(\d)/g,'$1$2').replace \= \== # if the expression is correct (we need to remove leading 0, because javascript interprets numbers with leading 0 as octal)
return s # return solution
f("CODE+GOLF=GREAT")
```
[Answer]
# Python, 256 213 chars
Horrific running time, will try to improve further:
```
q='='
e=input()
v=set(e)-set([q,'+'])
for x in __import__('itertools').permutations(range(10),len(v)):
t=e
for l,n in zip(v,x):t=t.replace(l,str(n))
try:
if eval(t.replace(q,q*2)):print(t);break
except:pass
```
[Answer]
# JavaScript 138
```
for(s=prompt(p='1');eval(p.replace('=','!='));)for(p=s,i=64;i++<90;)p=p.replace(new RegExp(String.fromCharCode(i),'g'),10*Math.random()|0)
```
Random bruteforce.
Can take a while (my best shot for `CODE+GOLF=GREAT` is 3 seconds, my worst 3 minutes).
Try it with a simple expression like `A+B=C`
[Answer]
# Haskell, 222
```
import Data.List
z=(\(b,(_:c))->b:z c).span Data.Char.isUpper
j(Just g)=g
main=interact$(\d@[a,b,c]->show$take 1[e|e<-map(zip$nub$d>>=id)$permutations['0'..'9'],(\f->f a+f b==(f c::Int))(read.map(j.(`lookup`e)))]).take 3.z
```
Brute force. Tries every possible matching until it finds one, or after it has finished trying them all. I stretched the output rules: prints something like `[[('C','3'),('O','8'),('D','6'),('E','7'),('G','0'),('L','5'),('F','2'),('R','4'),('A','1'),('T','9')]]` for the solution, and if none exists, prints `[]`. Let me know if I need to change this.
[Answer]
# CJam - 17
```
"
""
"f#3b127b:c~
```
Total 975 characters, but 960 of them are whitespace in 2 sequences, so those count as 2 characters, and together with the other 15, we get 17.
975 may seem like a lot, but note that undergroundmonorail's python solution has 18862 characters, they're just on a single line :)
You can run it at <http://cjam.aditsu.net/> for short words, but you should probably use the java interpreter for longer ones. With java on my laptop, `SEND+MORE=MONEY` runs in 30-40 sec and `CODE+GOLF=GREAT` in almost 3 min. It doesn't accept numbers starting with 0 (because that's not cool).
Here's a program that generates the program above (also helps if StackExchange doesn't show the whitespace correctly):
```
"{L__&=}:U;
{L!!{L))_9>{;:L;I}{+:L;}?}*}:I;
{{U!_{I}*}g}:M;
{L,N<L,g&}:K;
{I{K{L0+:L;}*MK}g}:G;
{{C#L=}%si}:R;
{XRYR+ZR=PRAb0#0<&}:F;
l'+/~'=/~:Z;:Y;:X;
[X0=Y0=Z0=]:P;
XYZ++_&:C,:NB<{0a:L;{F0{GL}?}g}*
L{XR'+YR'=ZR}{L}?"
127b3b[32 9 A]:cf='"\'"_32c9cAc"\"f#3b127b:c~"
```
The first 11 lines contain the original program (not really golfed) in a string, and the last line does the conversion and adds the decoding part.
[Answer]
# Powershell, 137 bytes
*port of [LiveScript](https://codegolf.stackexchange.com/a/32506/80745)*
```
$f={param($s)if($c=$s-replace'[^A-Z]'){0..9|?{$s-notmatch$_}|%{&$f ($s-replace$c[0],$_)}|Select -f 1}elseif($s-replace'=','-eq'|iex){$s}}
```
Ungolfed test script:
```
$f={
param($s) # parameter string
$c=$s-replace'[^A-Z]' # remove all the non-letters
if($c){ # if any letters remain
0..9|?{ # loop from 0 to 9
$s-notmatch$_ # if $s is not contains current number
}|%{
&$f ($s-replace$c[0],$_) # replace the first letter with current number and call the function recursively
}|Select -f 1 # seelct first non-null value (break if found)
}
elseif($s-replace'=','-eq'|iex){ # else if evaluated value if the expression is $true
$s # return $s as solution
}
}
&$f "AA+BB=CC"
&$f "A+AB=A" # empty because it has no solution
&$f "CODE+GOLF=GREAT"
```
Output:
```
11+22=33
2846+0851=03697
```
[Answer]
# PHP, ~~118~~ 113 bytes
```
for(;;)eval(strtr($argn,"=".$w=substr(count_chars($argn,3),2),"-".$n=str_shuffle(1234567890))."||die('$w
$n');");
```
prints digits below letters and exits program; loops infinitely if unsolvable. Run as pipe with `-nr`.
**breakdown**
```
for(;;)
eval( # 6. evaluate
strtr($argn, # 4. translate letters to digits, "=" to "-"
"=".$w=substr( # 2. remove non-letters
count_chars($argn,3) # 1. get characters used in the argument
,2),
"-".$n=str_shuffle(1234567890) # 3. shuffle digits
)."||die('$w\n$n');" # 5. if falsy (`A+B-C==0`), print translation and exit
)
;
```
[Answer]
# PHP, 145 bytes
```
function f($s){for(;$i<10*preg_match("/[A-Z]/",$s,$m);)strpos(_.$s,++$i+47)||f(strtr($s,$m[0],$i-1));$i||eval(strtr($s,"=","-")."||die('$s');");}
```
recursive function, prints solved equation and exits program; returns `NULL` when unsolvable.
[Try it online](http://sandbox.onlinephpfunctions.com/code/e200887d975ef6a885117cad1df22a51a5f2bcf6)
**breakdown**
```
function f($s)
{
for(;
$i<10 # loop $i from 0 to 9
*preg_match("/[A-Z]/",$s,$m) # find a letter; if not found: $i<10*0 == falsy
;
)
strpos(_.$s,++$i+47) # find $i in string
||f(strtr($s,$m[0],$i-1)); # if not found, replace letter with $i, recurse
$i|| # no letter found ($i is unset):
eval( # evaluate:
strtr($s,"=","-") # replace "=" with "-"
."||die('$s');" # if falsy (A+B-C==0), print equation, exit program
);
# else implicitly return NULL
}
```
] |
[Question]
[
## Background
The [special linear group](https://en.wikipedia.org/wiki/Special_linear_group) \$ SL\_2(\mathbb{Z}) \$ is a multiplicative group of \$ 2 \times 2 \$ matrices whose elements are integers and determinant is 1.
It is known that every member of \$ SL\_2(\mathbb{Z}) \$ is a product of some sequence of the following two matrices \$ S \$ and \$ T \$ ([reference pdf](https://kconrad.math.uconn.edu/blurbs/grouptheory/SL(2,Z).pdf)):
$$
S=\begin{pmatrix}0 & -1\\1 & 0\end{pmatrix},T=\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix}
$$
Note that \$ S^{-1} \$ and \$ T^{-1} \$ can also be expressed as a product of \$ S \$ and \$ T \$:
$$
S^{-1} = S^3, T^{-1} = S^3 \cdot T \cdot S \cdot T \cdot S
$$
## Task
Given a \$ 2 \times 2 \$ integer matrix whose determinant is 1, express it as the product of a sequence of \$ S \$ and \$ T \$.
Note that there are infinitely many possible answers for any valid input. Your code needs to just output one answer for a valid input.
## Example algorithm
Here is a sample algorithm to find a decomposition; you may use different algorithms to solve the task.
First, note that
$$
M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \implies
S^{-1}M = \begin{pmatrix} c & d \\ -a & -b \end{pmatrix},
T^{-1}M = \begin{pmatrix} a-c & b-d \\ c & d \end{pmatrix}
$$
Using these two operations, we can use Euclidean-like algorithm to reduce the given matrix down to \$ I \$, and then construct the chain backwards:
1. Assume \$ M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \$.
2. Left-multiply \$ S^{-1} \$ until both \$ a \$ and \$ c \$ are positive.
3. Repeat the following until we reach \$ c = 0 \$:
1. Left-multiply \$ T^{-q} \$ where \$ -c < a - qc \le 0 \$.
2. Left-multiply \$ S^{-1} \$ (exactly once). Now, \$a\$ and \$c\$ are positive again, and \$c\$ is smaller than the original.
4. Then the result is \$ \begin{pmatrix} 1 & b \\ 0 & 1 \end{pmatrix} \$, which is simply \$ T^b \$. (If \$ b < 0 \$, we can use \$ (SSSTSTS)^{-b} \$ instead.) Now invert all the left-multiplications to get the representation for the original matrix.
Here is an example for \$ M = \begin{pmatrix}17 & 29\\7 & 12\end{pmatrix} \$.
$$
T^{-3} M = \begin{pmatrix}-4 & -7\\7 & 12\end{pmatrix}
\\ S^{-1} T^{-3} M = \begin{pmatrix}7 & 12\\4 & 7\end{pmatrix}
\\ T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}-1 & -2\\4 & 7\end{pmatrix}
\\ S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}4 & 7\\1 & 2\end{pmatrix}
\\ T^{-4} S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}0 & -1\\1 & 2\end{pmatrix}
\\ S^{-1} T^{-4} S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}1 & 2\\0 & 1\end{pmatrix} = T^2
\\ M = T^3 S T^2 S T^4 S T^2
$$
## Input and output
You can take the input matrix in any suitable way, e.g. a matrix, a 4-element vector, two complex numbers, etc. You can assume that the input is always valid, i.e. the four elements are integers and the determinant is 1.
The output is a sequence of two distinct values (or objects) that represent \$ S \$ and \$ T \$ respectively. All of the following are accepted (using an example output \$ STTS \$):
```
"STTS" # string
"0110" # digit string
[0, 1, 1, 0] # array of 0s and 1s
['S', 'T', 'T', 'S'] # array of characters
[(0,-1,1,0), (1,1,0,1), (1,1,0,1), (0,-1,1,0)] # array of tuples
```
Also, by definition of [empty product](https://en.wikipedia.org/wiki/Empty_product), an empty sequence (e.g. `""` or `[]`) is a valid answer when the input is \$ I \$.
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Example I/O
Note that every valid input has infinitely many correct answers, so your code's output may differ from the sample outputs shown here.
```
[[1 0]
[0 1]] -> empty or SSSS or SSSTSTST or ...
[[0 -1]
[1 0]] -> S
[[1 10]
[0 1]] -> TTTTTTTTTT
[[17 29]
[ 7 12]] -> TTTSTTSTTTTSTT
[[-1 -7]
[-2 -15]] -> SSTSTTSTSSTTTTSSTTT
```
[Answer]
# [Python](https://docs.python.org/2/), 67 bytes
```
g=lambda z,w:(z/w).real>0and'T'+g(z-w,w)or z+w*w and'S'+g(w,-z)or''
```
[Try it online!](https://tio.run/##ZVFNb9swDD1Hv4LoDrEcObMMtMUMeECPPeTS5GYYg2wpqQt/QVLm1sN@e0Y6HjJ0gGE@vkdS0uPw4V/7LrlcTlmj2lIrmMSYBtPXkW@tUc33WHV6fVhvTsEUjWLkvYVpM4YjEL8nfhTRhPR6fTmiqEQpKqGh7iDPpYB4/mQhIMcYIUMkpQTkIkMhcvkoIPkmAINMMKfaCJMoob77okjZarB15@EUqI18C/EgCpoz9gWeoO2tAfP@qs7O1z8NeOM8q9uhtx66czt8MLbPZrBtlbf1e5DjlSJJR4u4KDg7fJalIDXGP6rs@X85/kfWlYcMfqEpKewFoGkpHH4jb46gTdVrEzieMrDGnRsqfWZAjlXklUtv/AJCwIl5VVCHP9tu4Rl7oRrVnUwQPYhHzuihPyrljEMhD5YN8Hm4ouEvMyxvsLpBfYX1EVSoozKsskwWjJHkSboNR/v/LjcDz1Y7DJ8MQR0NwQoyZGXnC9GyylC@4bI0BuR3CdKLI1iDjHLO4JYCUjLY8a1qmoALIgSm7Lr2u6emges7B@rQd5c/ "Python 2 – Try It Online")
*Thanks to Bubbler for cutting a byte*
Takes input as two complex numbers for the rows. The idea is simple and easy-to-see on a less-golfed version:
```
def f(a,b,c,d):
if (a,b,c,d)==(1,0,0,1): return ''
elif a*c+b*d>0: return 'T'+f(a-c,b-d,c,d)
else: return 'S'+f(c,d,-a,-b)
```
From \$ \begin{pmatrix} a & b \\ c & d \end{pmatrix}\$, we choose whether to apply \$S^{-1}\$ or \$T^{-1}\$ based on a simple condition: whether \$ac+bd>0\$. Repeating this enough times takes any matrix to the identity.
[Answer]
# JavaScript (ES6), 68 bytes
This is using [xnor's method](https://codegolf.stackexchange.com/a/198036/58563) -- but obviously without complex numbers.
Takes the input matrix \$\begin{pmatrix}a&b\\c&d\end{pmatrix}\$ as 4 distinct parameters `a,b,c,d`.
Returns a string of digits (\$0\$ for \$S\$, \$1\$ for \$T\$).
```
f=(a,b,c,d)=>b|c|a-1|d-1?a*c>-b*d?1+f(a-c,b-d,c,d):0+f(c,d,-a,-b):''
```
[Try it online!](https://tio.run/##bYzBDoIwEETv/ggtzhqWgEQS4Fu2LRgNoUaMJ/69brwZzFw27@3MXd6y@uft8aIlhjGlqTMCB49gu95tfhPiLRAPkvueXB4GPk5GyMNR@L61hQI9QAJyts2y5OOyxnk8zfFqJsMoNGzt4ZcXIIbKnVD6v8ENygsacLlTOkUNqNTNei9rcAU@gyqV6QM "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~114 110~~ 108 bytes
Takes the input matrix \$\begin{pmatrix}a&b\\c&d\end{pmatrix}\$ as a 4-element vector `[a,b,c,d]`.
Returns a string of digits (\$0\$ for \$S\$, \$1\$ for \$T\$).
Brute forces a solution, which is guaranteed to be as short as possible, except for the identity matrix.
```
f=(M,i=0)=>(F=(a,b,c,d,s='')=>s[i]?a+[,b,c,d]==M&&s:F(a,a+b,c,c+d,s+1)||F(b,-a,d,-c,s+0))(1,0,0,1)||f(M,i+1)
```
[Try it online!](https://tio.run/##dY1BDoIwEEX3HgSm6dS0JIZoMrpjxwkIi1LAYAg11rji7nUaXRnM7N77/8/Nvmxwj@n@VIvvhxhHghon0oLOUBFY7NBhj4HynFFopvZiZfOhLVGdZeFUcczKhJzkqDRiXSvoUFluKsdECwEGNV9yY3rBqej8Evw87Gd/hRGab6IVYvdjNCqDrDcU838tU2JxxBJNsSF5UJWoCl4@sI5v "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = wrapper function taking:
M, // M[] = input vector
i = 0 // i = maximum number of iterations (-1)
) => ( //
F = ( // F is a recursive function taking:
a, b, c, d, // the current matrix as 4 distinct parameters
s = '' // s = output string
) => //
s[i] ? // if we've reached the maximum length:
a + [, b, c, d] == M // if [a, b, c, d] matches the input matrix:
&& s // return s
: // else:
F( // try a first recursive call
a, // where the matrix is multiplied by T
a + b, // [ a b ] [ 1 1 ] [ a a+b ]
c, // [ c d ] x [ 0 1 ] = [ c c+d ]
c + d, //
s + 1 // append '1' to s
) || //
F( // try a second recursive call
b, // where the matrix is multiplied by S
-a, // [ a b ] [ 0 -1 ] [ b -a ]
d, // [ c d ] x [ 1 0 ] = [ d -c ]
-c, //
s + 0 // append '0' to s
) //
)(1, 0, 0, 1) // initial call to F with the identity matrix
|| f(M, i + 1) // if it fails, try again with i + 1
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 47 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. Gives Boolean list with 0 and 1 meaning \$S\$ and \$T\$ respectively.
```
{⍺≡⊃+.×/(r←⊤⍵)⊇2 2∘⍴¨(0 ¯1 1)(1 1 0):r⋄⍺∇1+⍵}∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9e561LnwUVeztt7h6foaRUDRR11LHvVu1XzU1W6kYPSoY8aj3i2HVmgYKBxab6hgqKkBJBQMNK2KHnW3gDR3tBtqA5XXAhUa/k8Dae/tg5jf1XxovfGjtolAXnCQM5AM8fAM/p@mADK1dwvQECA05ILxoeYrGHAhVBiiKjE0VzCyVDBXMDSCC4H0HFpvDsRGIP2mAA "APL (Dyalog Extended) – Try It Online") ([Faster edition](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXCFA0uhR19JHvYsPrTd81LWIyxMo8qhn@6PeFY86ZjzqagIy/lc/6t31qHPho65mbb3D0/U1ioBqQh71btX0VDBSMAKp691yaIWGgQLQDAVDTQ0goWCgaVX0qLsFpLOj3VAbqLoWqNDwfxrI/N4@iBO6mg@tN37UNhHICw5yBpIhHp7B/9PApvZuARoChIZcMD7UfAUDLoQKQ1QlhuYKRpYK5gqGRnAhkJ5D682B2Aik3xQA "APL (Dyalog Unicode) – Try It Online") emulating Extended in Unicode.)
`{`…`}∘1` apply the following function with 1 and the given matrix as right and left arguments:
`(0 ¯1 1)(1 1 0)` the list `[[0,-1,1],[1,1,0]]`
`2 2∘⍴¨` **r**eshape each into a 2-by-2 matrix; `[[[0,-1],[1,0]],[[1,1],[0,1]]]`
`(`…`)⊇` select the following elements from that:
`⊤` convert the right argument **T**o base **T**wo
`r←` store that in `r` (potential **r**esult)
`+.×/` reduce using matrix multiplication (this also reduces the number of dimensions from 1 to 0)
`⊃` disclose (the enclosure necessitated to reduce the number of dimensions)
`⍺≡`…`:` if the left argument (the target matrix) matches that, then:
`r` return the **r**esult
`⋄` else:
`1+⍵` increment the right argument
`⍺∇` call self with same left argument and new right argument
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~48~~ ~~44~~ ~~43~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
[*Crossed out ` 44 ` is no longer 44 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
9bS[)DðýIk©d#¼vyDÁ0T·Sǝ+y2Å€(}2ôí˜]T¾ã®è
```
`9bS` and `DÁ0T·Sǝ+` could alternatively be `9Yв`/`т1ª`/`тĆS`/`TºS` and `D2ôO13Sǝ`/`DÁ2Å€0}+` for the same byte-count.
Brute-force approach with pretty bad performance (it times out for the last three test cases - the previous 48;44;43 bytes versions only timed out for the last test case).
Input \$\begin{pmatrix}a&b\\c&d\end{pmatrix}\$ as a space-delimited string of four integers `"a b c d"`.
Output as a string of `0`s and `1`s, where `0` is \$S\$ and `1` is \$T\$.
[Try it online](https://tio.run/##AU4Asf9vc2FiaWX//zliU1spRMOww71Ja8KpZCPCvHZ5RMOBMFTCt1PHnSt5MsOF4oKsKH0yw7TDrcucXVTCvsOjwq7DqP//LTQgLTMgLTEgLTE) or [verify a few test cases at once](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXof8uk4GhNl8MbDu@NyD60MkX50J6ySpfDjQYhh7YHH5@rXWl0uPVR0xqNWqPDWw6vPT2ntjbk0L7Diw@tO7ziv4t9yKOGeSHBjxoWHtpxeo6XkoLG4f2aSjoxeoe2/o9WMlQwAEJDJR0lAwVdQwUgF8jUNVbQNQJxdUEShgrGYLYRSMYIqMRUQddYKRYA).
**Explanation:**
```
9bS # Push 9, convert it to binary, and then to a digit-list: [1,0,0,1]
[ # Start an infinite loop:
) # Wrap all lists on the stack into a list
D # Duplicate the current list of lists
ðý # Join each inner list to a string with space delimiter
Ik # Get the index of the input-string in this list
# (the join is a work-around for lack of non-vectorizing index builtin)
© # Store it in variable `®` (without popping)
d # Check if this index is non-negative (>= 0)
# # And it it is: stop the infinite loop
¼ # Increase the counter variable by 1
v # Loop over each inner [a,b,c,d]-list `y`:
yD # Push the list twice
Á # Rotate the second one once towards the right: [a,b,c,d] → [d,a,b,c]
T·S # Push 10 doubled as digit list: [2,0]
0 ǝ # Insert a 0 at those (0-based) indices: [0,a,0,c]
+ # Add it to the earlier list: [a+0,b+a,c+0,d+c] → [a,b+a,c,d+c]
y # Get the initial list [a,b,c,d] again
2Å€ } # Apply to every 0-based 2nd item (so at indices [0,2]):
( # Negate
2ô # Split the list into parts of size 2: [-a,b,-c,d] → [[-a,b],[-c,d]]
í˜ # Reverse each, and flatten: → [[b,-a],[d,-c]] → [b,-a,d,-c]
] # Close both the map and infinite loop
T¾ã # Take the cartesian product of 10 with the counter variable
# i.e. 3 → ["111","110","101","100","011","010","001","000"]
®è # And index variable `®` into this list
# (after which the result is output implicitly)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~42~~ ~~38~~ 32 bytes
```
`@B"@?FT!tqh}IlhB]]Nq:"Y*]G-z}@B
```
The code enumerates all finite sequences that begin with `S`, and stops when a solution is found. It is sufficient to test sequences beginning with `S` because `S*S*S*S` equals the identity matrix (inspiration from [@Adam's APL solution](https://codegolf.stackexchange.com/a/198015/36398)).
Outputs a binary sequence, where `1` corresponds to matrix `S` and `0` to matrix `T`. The produced solution is the first in lexicographical order.
[Try it online!](https://tio.run/##y00syfn/P8HBScnB3i1EsaQwo9YzJ8MpNtav0EopUivWXbeq1sHp//9oQwUDawUDBcNYAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽¬Pb3’s2$⁺⁸ṃæ×/⁼
0ç1#B
```
A monadic Link accepting the target matrix which outputs a list containing a single list of `1`s (\$S\$) and `0`s (\$T\$).
As a full program a Jelly representation of this list is printed.
Always yields a resulting equation with a leading \$S\$ (except for an input of \$T\$ itself).
Note that since \$S^4=I\$ this is always possible.
**[Try it online!](https://tio.run/##AUEAvv9qZWxsef//4oG9wqxQYjPigJlzMiTigbrigbjhuYPDpsOXL@KBvAoww6cxI0L///9bWzEsIDEwXSwgWzAsIDFdXQ "Jelly – Try It Online")** (very slow in general).
### How?
Starts with `i=0` and increments `i` while the binary representation of `i` with digits \$S\$ (1) and \$T\$ (0) does not have a matrix-product equal to the input, then returns the normal binary representation (using 1s and 0s).
```
⁽¬Pb3’s2$⁺⁸ṃæ×/⁼ - Link 1: integer, i; target matrix, M
⁽¬P - literal 2831
b3 - to base three [1,0,2,1,2,2,1,2]
’ - decrement [0,-1,1,0,1,1,0,1]
s2$ - split into twos [[0,-1],[1,0],[1,1],[0,1]]
⁺ - repeat that [[[0,-1],[1,0]],[[1,1],[0,1]]]
⁸ṃ - base-decompression of i
- -> i in binary using digits 1=[[0,-1],[1,0]] and 0=[[1,1],[0,1]]
æ×/ - reduce by matrix-multiplication
⁼ - is equal to M?
0ç1#B - Main Link: 2-by-2 target matrix with determinant 1, M
0 - initialise the left argument, say i, to 0
1# - count up finding the first match under:
ç - last Link (1) as a dyad - i.e. f(i, M)
B - convert to binary
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~301~~ \$\cdots\$ ~~139~~ 129 bytes
```
def f(a,b,c,d,l=''):
while c:
while 0>a or b<0:a,b,c,d=c,d,-a,-b;l+='S'
if c:q=-a//c;a+=q*c;b+=q*d;l+='T'*-q
return l+'T'*b
```
[Try it online!](https://tio.run/##LY7LDoIwEEX3fMXETXlMw8MYIliX/oDuCIsWqJAQXtYYQ/x2nBpXc@@dcyczvU07DvttqxsN2pWosMIae8GYlznwaru@gYrUX0ZnCeMC6hRlf1ZYnkvkKu8Dwa6M2E5TZxZchmGVy0DMfpUrO@ofc2M@nx1YGvNcBugDG6hN013TPAx0AxRFhDzGGKMSizjF5IgpxgkZSnmKPKH1oSzpsWnpBuPq3YXqq@1/4D4aYKt2fWu9D9t5zvYF "Python 3 – Try It Online")
Saved 18 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Takes the 4 matrix elements as separate numbers as input and outputs a string of `'S'`s and `'T'`s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 64 bytes
```
W∨§η⁰⊖§θ⁰¿‹⁰×§θ⁰§η⁰«TUMθ⁻κ§ηλ»«S≔±θι≔ηθ≔ιη»×TΠθ¿›⁰Πθ«SSS×TST±ΠθS
```
[Try it online!](https://tio.run/##VY9Na8MwDIbP9a8QPbkgQzsYPfRUNhiD9QPSW8jBJFpj5jiL7W6D0d/u2svYHN9k6Xn0qm6lrXupQ/hslSbgB8u3/tk09MVbhOUC4ZFqSx0ZT81fa0it@EC9An8h5/gS4aQ6ctMRhIksEd9sdrTKeD4/zRcbNtvJ94e@66RpErJT5uL424TTEduwK5B2lOHFD751Tp0N39NZeuJD3Kiy70gPWakQ2qRio2IMHHMgHG3fXGofBWlXuurJUjTadFjezAMUY4SprEi63zg5@D85Jr@GUJZihQBiXSGDUtwhiNV9VQXxoW8 "Charcoal – Try It Online") Link is to verbose version of code. Based on the provided algorithm. Explanation:
```
W∨§η⁰⊖§θ⁰
```
Repeat while the first column is not `[1, 0]`.
```
¿‹⁰×§θ⁰§η⁰
```
If the product of the first column is positive...
```
«TUMθ⁻κ§ηλ»
```
... then print a `T` and subtract the second row from the first row...
```
«S≔±θι≔ηθ≔ιη»
```
... otherwise print an `S`, and swap the rows, while negating the second row.
```
×TΠθ
```
If the product of the first row is positive then print that many `T`s.
```
¿›⁰Πθ«
```
But if it is negative, then...
```
SSS×TST±ΠθS
```
... print `SSS`, the appropriate number of `TST`s, and a final `S`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 96 bytes
```
->m{z=[['',1,0,0,1]];z.find{|a,q,w,e,r|z<<[a+?S,w,-q,r,-e]<<[a+?T,q,q+w,e,e+r];m==[q,w,e,r]}[0]}
```
[Try it online!](https://tio.run/##VY3LCsIwEEX3foW7LnojSUGCtNGP0N0wi4oNuKiYQBH7@PY4VSvIrM6dc2did34m75Lat0PviLIMBlrGMJf9xl9vl2GsEfBAgzj2VUV1fjgKqoAI1fAnOYkS8llq8shl6xx9OzyR5ind157od3r1Rg1l5ncLC/ztjUWxg4UplkR8ZaEKKW6Z0ws "Ruby – Try It Online")
Use the (brute) force.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~193~~ ~~192~~ 191 bytes
Takes in a 2D numpy array and returns a string of S and T. Uses the algorithm in the question.
```
import numpy
def g(m,x=0):
if m[1,0]==0:y=m[0,1];return['T','SSSTSTS'][y<0]*abs(y)
while(m[:,0]<[1,0]).any():x+=1;m=[[0,1],[-1,0]]@m
q=-m[0,0]//m[1,0];return'S'*x+'T'*-q+g([[1,q],[0,1]]@m)
```
[Try it online!](https://tio.run/##LY9LDoMgFEXnroIZoKCQ1g5Uku5BZ4SBTf0lBZVqKqu3aJs3vPfckze5pR/NZd8HPY12AWbVkwueTQs6pMkmGM4CMLRAS06YEoJlTmjJCFe5bZbVGgkrSGBZlpU/qKQrmArrxxs5HIBPP7wapGXm2eJcwHFtHMLZFgmeayHPKSLpkam7DsAs6LHPVJL8nH8PLGG4RV4W0jnqkPTZ7MED9xzeJzuYBXXofCCura2dL9GU8Kuv8Ruh11QpjPH@BQ "Python 3 – Try It Online")
] |
[Question]
[
Balanced binary search trees are essential to guarantee *O(log n)* lookups (or similar operations). In a dynamic environment where a lot of keys are randomly inserted and/or deleted, trees might degenerate to linked lists which are horrible for lookups. Thus there are various kinds of [self-balancing binary trees](https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree) that counteract this effect (such as [AVL trees](https://en.wikipedia.org/wiki/AVL_tree) or [splay trees](https://en.wikipedia.org/wiki/Splay_tree)). These trees are based on different kinds of [rotations](https://en.wikipedia.org/wiki/Tree_rotation) that re-balance the tree.
## Rotations
In this challenge we'll only look at single right-rotations, such a rotation (left-rotation would be symmetric) looks like this:
```
5 3
/ \ / \
3 6 => 1 5
/ \ / \
1 4 4 6
```
If any of the leaves `1`,`4` or `6` had left or right sub-trees a rotation would simply keep them there. If this is a subtree of a larger tree, we'd simply "cut it off" at the node `5` and "re-attach" the rotated tree (now node `3`) to that node.
## Challenge
Given a binary search tree1 and a key right-rotate the tree on that node as described above. The key provided in the above example would be `5`.
## Rules and I/O
* you may use any type for keys as long as there is a bijection between the keys of your choice and those of the test cases
* you may choose any representation for binary trees as long there's no ambiguity (eg. `[3,[]]` is ambiguous unless otherwise specified) and it's natural for your language of choice
* since the input will always be a binary search tree there are no duplicate keys
* you may assume that the key is contained in the tree
* you may assume that node containing the key has a left child
* you may **not** assume a right subtree under the provided key
* you may **not** assume that the tree is unbalanced before the rotation
* you may **not** assume that the tree is balanced after the rotation
* you may use any [default I/O method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* your submission may be a function returning the tree or full program printing the solution
## Test cases
These examples represent a tree as follows
* if it's a leaf: `[]`
* if it's a tree with key `x` and both subtrees are leaves: `[x]`
* if it's a tree with key `x` and subtrees `left` `right`: `[x,left,right]`
The first example is the one provided in the section **Rotations**. If for some reason you need a graphical representation of them, [here](https://pastebin.com/7UCP4cH1)2 you go.
```
5 [5,[3,[1],[4]],[6]] -> [3,[1],[5,[4],[6]]]
5 [5,[3,[1],[4]],[]] -> [3,[1],[5,[4],[]]]
5 [5,[3,[],[4]],[6]] -> [3,[],[5,[4],[6]]]
5 [5,[3,[1],[]],[]] -> [3,[1],[5]]
4 [8,[4,[2,[1],[3]],[6,[5],[7]]],[12,[10,[9],[11]],[14,[13],[15]]]] -> [8,[2,[1],[4,[3],[6,[5],[7]]]],[12,[10,[9],[11]],[14,[13],[15]]]]
8 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]] -> [10,[6,[4,[2,[],[3]],[5]],[8,[7],[9]]],[11]]
10 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]] -> [8,[6,[4,[2,[],[3]],[5]],[7]],[10,[9],[11]]]
9 [6,[3,[2],[5]],[9,[8],[12,[11],[15,[14],[]]]]] -> [6,[3,[2],[5]],[8,[],[9,[],[12,[11],[15,[14],[]]]]]]
7 [7,[5,[3,[1],[4]],[6]],[8]] -> [5,[3,[1],[4]],[7,[6],[8]]]
15 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]] -> [17,[9,[5,[2,[0],[4]],[8]],[13,[11,[10],[12]],[15,[14],[16]]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]
21 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]] -> [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[19,[18],[21,[20],[24,[22],[25]]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]
```
---
1: meaning that for any node all the keys in the left subtree will be smaller than that key and all the keys in the right subtree are greater than it
2: to prevent link-rot, I embedded them as a comment
[Answer]
# [Haskell](https://www.haskell.org/), ~~93~~ ~~92~~ ~~84~~ ~~83~~ 82 bytes
```
data B=B[B]Int|L
k!B[l@(B[x,y]a),r]n|k<n=B[k!l,r]n|k>n=B[l,k!r]n|1>0=B[x,B[y,r]k]a
```
Thanks to @BMO, @alephalpha and @Laikoni for a byte each and @nimi for eight bytes!
[Try it online!](https://tio.run/##jY9Ba4NAEIXv@RVPySFiDhpj20ANZW8Fe@oxhLKxgrJmG1RIA/53OzsbNS059DK8mfn2zdtCNiqvqr7UTSt1luO9@DpD4FzkdT4DGtOmSODu9u7QLwQkDVOP5y58386lUe4f7oDsPrd0fZ/bw7Ud99nVp/@UrYRIBF51S6FEl86UI6BRvbD3Ny5e3alnTYheKKcy3ZY7VHPl1F24DRIm5wIKF9T9UZaa8hzl6e0Dp7rULcXdIYZDF2KTOTIltB8ktWblISVu@Q@O5ANL5sOAHhguMPXJbpmmsiKOjcaX8SQfJ7mZZGgPWvM1h2HTwfBXpOg20uh@Y24tV1PAzUgMh1izeRhNy2tOE2Pf/wA "Haskell – Try It Online")
[Answer]
# [Vim](https://www.vim.org/), 25 bytes
Takes the input in the buffer - space separated key and tree. The tree is expected to be represented as follows:
* leaf: `[]`
* node with key `k`, left child `<left>` and right child `<right>`: `[ k <left><right>]`
Not the spaces around the key `k` which are important, such that the solution works for arbitrary trees.
```
"adw/ <C-r>a⏎3dw%l"apr[%xl%i]
```
[Try it online!](https://tio.run/##RU87DsMgDN079gQoEnOxYyfpWRADUpZKGaoOTW9P/ZIASLae4X3Mt5Qhr/vD3fNtXHe/Dfn9if63@VcqhclFR7O1p5VasVVwMcWUopMTGFoaIrBoRDvEjUzcOV1I0wVhFxCAtDMXmbRUPYcmYgGH24t2D@6bCFiChYUuKq4V3jJXsR4/0zpOVL3s/AE "V – Try It Online")
### Explanation
```
"adw " delete the key and trailing space, keep in register a
/ <C-r>a⏎ " move cursor to the key surrounded with spaces
3dw " remove key and [ (move left node to top)
%l " move cursor to the right subtree
"ap " insert key there
r[ " insert a [ (appending subtree to key)
% " move to the end of new left subtree
x " remove ] (fix parentheses)
l% " move to the end of new right subtree
i] " insert ] (fix parentheses)
```
### Preview
Here's a preview of the first test case, generated with [this](https://gist.githubusercontent.com/lynn/5f4f532ae1b87068049a23f7d88581c5/raw/d0bb63720146232eccee18598e0058175280d362/vimanim.py) script by [Lynn](https://codegolf.stackexchange.com/users/3852/lynn?tab=profile):
[](https://i.stack.imgur.com/CJx0V.gif)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
#2/.a_~b_~c_~#~d_:>b[a,c~#~d]&
```
[Try it online!](https://tio.run/##1VHBSsQwEP2VQMKeRs2kSZsKLv0E70Mo3dXFPawH6a20v17TdpIiKII3Twkzb9689@bW9W@vt66/nrv5Ip5maR7uu3Y6tdO5neT00j4eT9TBefmHw/z8cX3vaZByFHdHcSEpQxAH0TSNGAYHjgpCUqAC2PUJUG7vCN@31d5Rv80ohlvwZMmkcpGn3FaotkIAjBhN9VZFZBxawoJrjqELrYcI9lSu3CrTMiSxQp1oMKtE/efRGoYyOjSbHpeBngVGB5i1ok1BLIrjdBWpf84c/K7QAVYxCRc36a9gn0S5JZa4DXXenQPjT5mStZpMRSaCa0LWajTDTEyBDZkUMJi0x1qyhux@U4dkK/YfFfIRS0ynWQ0Y/NcGxvkT "Wolfram Language (Mathematica) – Try It Online")
A tree represented as follows:
* if it's a leaf: `$` (you can replace it by any value which is not a key)
* if it's a tree with key `x` and subtrees `left` `right`: `x[left,right]`
For example, the tree in the first test case is represented by `5[3[1[$,$],4[$,$]],6[$,$]]`.
### Explanation:
```
#2 the second input
/. replace
a_~b_~c_~#~d_ #[b[a,c],d], where # is the first input
:> by
b[a,c~#~d] b[a,#[c,d]]
& define a function
```
[Answer]
# Common Lisp, 146 bytes
```
(defun r(k a)(cond((not a)a)((=(car a)k)`(,(caadr a),(cadadr a)(,(car a),(car(cddadr a)),(caddr a))))(t`(,(car a),(r k(cadr a)),(r k(caddr a))))))
```
[Try it online](https://tio.run/##TY3NDsIgEIRfZW/OJh7Etv4cfJcS0KTB0Abx@XEpS@KJb74ZwL2Xz1YK/PP1jZQQyDLcGj0Q1yxBIh5wNgkHnnEUtr6mSr7hbrtLcF592zRkRp7/holCLXWmqU@ZC7a0xCzFSAfcCCPhTDBgMBOG/RS4ECZ11@aETF2eCHdtjOlzI8@YoetJb9T/fg) or [verify all the testcases!](https://tio.run/##7VTBbsIwDL3vK3KbI@3QpAltD/sXqpZJCFRYge/vnKRgh5YWxDbtMIkiJ3l@fi9xUm3Xh33XQb36ODWihY0oJVS7pgZodkcc4BDeoSpbjDdyCW8Yl7UbuagOoZ89z7VQ1f18wIRQSjguGbAVG7fYw/rRGSplB/t23Rxh9XkqtwLXrXgFKyAVoARI/OFn@gj/FudQIi4CWcJxmJQvD5aY454jnRb8tNLbEm9qMwjOfVHNU9JIpb3MZyQZlMtIBBSXVaUoTSGlSmmJiZChpr7a5JQbHyv5VM2h9RxlOK7cFww7EFu3FGYUFqyg4kfoyOaZciJjXDHZUCxyf7PaR4lubfuY2gL5F55TD7vQ0@TEpBlbODR1daPkNF3gCtruYRsRnGGFTNz1upB2r2siJaMsnjR2uu42q8ybsN5lMkaYs9OwodWdV5VEm8lvwyVmbw0YxGsspl0uVlR0GDqhHO16gzZcW0ahmRSDOIM4Ez9EFoeGOt06a3SrF7x/wu15yP6M9fjYmfu/aX/YESjuvyN@2/61dcXsT7n/iY7ovgA)
A tree is represented as follows:
* an empty tree is represented as `nil` (or equivalently in Common Lisp as the empty list `()`)
* a non-empty tree is represented as a list of three elements `(node left-subtree right-subtree)`
(so a leaf `L` is represented as `(L nil nil)`).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 70 bytes
```
n=>f=a=>n-a[0]?(a[i=n<a[0]?1:2]=f(a[i]),a):(i=a[1],a[1]=i[2],i[2]=a,i)
```
[Try it online!](https://tio.run/##1ZLLTgMxDEX3fAeLWAponGYeLaR8iGWpEZQyKJoiBrEBvr3YHh4Smkos2LCo43hujnPj3ufnPF4/9g9PZ8P@ZnvYpcOQ1rcpp/VwlqniK5epT8Ol5bgKnG61wuAzrFyfMiF7DamnwF5Dyr6HQ0lu8AXSmmR5fSX2xHxxMio6n5ftsHu6u8oi/8w3dPpC2saPToFga2DgN96stPKlLO6HlN9gs7KyVm1DvLk4ud4P475sz8t@50a3czU4qj0tfHEIEiKwxAYYAGbVxf2QwzHlxCX@LbW4CQvzxCjEzlP0FD67LwRLjSS17lpg2WKQXyXbpdYQVYJR04UValHNX6OTBnJSmzQffezyC7t8bbG1uLSo7FkQVn9FWgqomZ47wMdRWkrSgTm1o@ZKQ4Sj3loBtX5@0oY74kTHiK321LPasPo@29nbSh1lzIgKtq8YJleTChubS5T3CEIKKFq1gJ1qQ6WQoAMKZjHogHQ1etQPUftG@WPIJbRLbDVTRm2Db1B9H3Ee8L9ZOLwD "JavaScript (Node.js) – Try It Online") Link includes test cases. All nodes must have left and right entries but they can be `[]` indicating no subtree on that side. As an abbreviation the test suite uses `l(N)` to indicate that `N` is a leaf and `l(N,L)` to indicate that `N` has a left subtree `L` but no right subtree both on input and output.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
R=lambda T,k:k in T and T[1][:2]+[[T[0],T[1][2],T[2]]]or T[:1]+[R(i,k)for i in T[1:]]
```
[Try it online!](https://tio.run/##RUvNCsIwDL77FDlumIOpP7iCLzF6CzlUhliqXRn14NPXbIwZknz5fpK/5TkmU2t/e/n3ffDgMNoIIYEDnwZwTMLWyJ7Z8UFw4WZGIyLjpAFL6vZNwNg@VAjLM5MVqXkKqYB6KX9K0@KKbeUL8hHZIIu2znm9dHXI100njRD9qebotFGZa9f9AA "Python 2 – Try It Online")
Input format:
* Tree: `[KEY, LEFT_SUBTREE, RIGHT_SUBTREE]`
* Leaf: `[]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
ñ
Ḣ,1ịṪƊṭ@ṪṭḢð{Ḣ;ç€ɗ¹¡i?
```
[Try it online!](https://tio.run/##y0rNyan8///wRq6HOxbpGD7c3f1w56pjXQ93rnUAMoAUUPjwhmogaX14@aOmNSenH9p5aGGm/f/Dy49Oerhzxv//0WY60cY60UY60bFABMSmUBaQsNSJtoCLGwKVGBoiuEB1hiZwbiwI/LcEAA "Jelly – Try It Online")
Warning: Normally, the top line shouldn't exist, and the bottom line should have a `ß`, not a `ç`. However, clever chain tricks and `ß` don't go well together, due to `ß`'s variable arity. Technically, I could have still omitted the top line, but then the result would have had to be a full program, since otherwise it would have to be able to be incorporated as its own line inside any program, which isn't possible unless you're lucky. This means that, unfortunately, the output would've had an ambiguous representation, because, when you submit a full program, what gets actually output counts, and not what the result technically is before the program closes. So, in order to not make a mess with both recursion and proper string representation, I've decided to submit a 2-line function, where the top line's job is just to call the bottom one. The consequence? A huge waste of 2 precious and valuable bytes. In Jelly's (and Dennis's, as well as every other contributor's) defense, the language is still under active development, and is now experiencing a big wave of new features.
] |
[Question]
[
# Task
Given an array of non-negative integers `a`, determine the minimum number of rightward jumps required to jump "outside" the array, starting at position 0, or return zero/null if it is not possible to do so.
A *jump* from index `i` is defined to be an increase in array index by at most `a[i]`.
A *jump outside* is a jump where the index resulting from the jump `i` is out-of-bounds for the array, so for 1-based indexing `i>length(a)`, and for 0-based indexing, `i>=length(a)`.
## Example 1
Consider `Array = [4,0,2,0,2,0]`:
```
Array[0] = 4 -> You can jump 4 field
Array[1] = 0 -> You can jump 0 field
Array[2] = 2 -> You can jump 2 field
Array[3] = 0 -> You can jump 0 field
Array[4] = 2 -> You can jump 2 field
Array[5] = 0 -> You can jump 0 field
```
The shortest path by "jumping" to go out-of-bounds has length `2`:
We could jump from `0->2->4->outside` which has length `3` but `0->4->outside` has length `2` so we return `2`.
## Example 2
Suppose `Array=[0,1,2,3,2,1]`:
```
Array[0] = 0 -> You can jump 0 fields
Array[1] = 1 -> You can jump 1 field
Array[2] = 2 -> You can jump 2 field
Array[3] = 3 -> You can jump 3 field
Array[4] = 2 -> You can jump 2 field
Array[5] = 1 -> You can jump 1 field
```
In this case, it is impossible to jump outside the array, so we should return a zero/null or any non deterministic value like `∞`.
## Example 3
Suppose `Array=[4]`:
```
Array[0] = 4 -> You can jump 4 field
```
We can directly jump from index 0 outside of the array, with just one jump, so we return `1`.
# Edit:
Due to multiple questions about the return value:
Returning `∞` is totally valid, if there is no chance to escape.
Because, if there is a chance, we can define that number.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Haskell](https://www.haskell.org/), ~~70~~ 58 bytes
```
f[]=0
f(0:_)=1/0
f(x:s)=minimum[1+f(drop k$x:s)|k<-[1..x]]
```
[Try it online!](https://tio.run/##JYhBDsIgFAX3PQULFxAR@eqqKSchxBALlrTQBmrswrsjtIt5mXmDTqOZppytVII3FvP2SQRcq25tIsK74PzHSzhb3Md5QeOp/r@xu0hgbFMqe@2CcGE1Ub9WnIb5y7xe0JtFo3uSpVS0QfJxLOX0drA3p1D8XoC9q0Nx9Qc "Haskell – Try It Online")
EDIT: -12 bytes thanks to @Esolanging Fruit and the OP for deciding to allow infinity!
Returns `Infinity` when there is no solution which makes the solution a lot simpler. Since we can only move forwards `f` just looks at the head of the list and drops `1<=k<=x` items from the list and recurs. Then we just add 1 to each solution the recursive calls found and take the minimum. If the head is 0 the result will be infinity (since we cannot move there is no solution). Since `1+Infinity==Infinity` this result will be carried back to the callers. If the list is empty that means we have left the array so we return a cost of 0.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
Γö→▼Mo₀↓ŀ
```
Returns `Inf` when no solution exists.
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/5yYf3vaobdKjaXt88x81NTxqm3y04f///9EmOgY6RhAcyxVtoGMIZBkDsSGQZwLExkA5Y6AoSIURSDYWAA "Husk – Try It Online")
## Explanation
Husk's default return values come in handy here.
```
Γö→▼Mo₀↓ŀ Implicit input: a list, say [2,3,1,1]
Γ Deconstruct into head H = 2 and tail T = [3,1,1]
ö and feed them into this function:
ŀ Range from 0 to H-1: [0,1]
Mo For each element in range,
↓ drop that many element from T: [[3,1,1],[1,1]]
₀ and call this function recursively on the result: [1,2]
▼ Take minimum of the results: 2
→ and increment: 3
```
If the input list is empty, then `Γ` cannot deconstruct it, so it returns the default integer value, 0.
If the first element is 0, then the result of `Mo₀↓ŀ` is an empty list, on which `▼` returns infinity.
[Answer]
# [Python 2](https://docs.python.org/2/), 124 bytes
```
def f(a):
i={0};l=len(a)
for j in range(l):
for q in{0}|i:
if q<l:i|=set(range(q-a[q],q-~a[q]))
if max(i)/l:return-~j
```
[Try it online!](https://tio.run/##JYtBCsIwEEXX9hSznECKVVxFc5LiImCiU2LapBEUa68eJ5SB//mPN9MnP8ZwLOVmHTg0QjVA@tv9zl57Gxg04MYEA1CAZMLdomdnV1lkxuZCvIEcxItXtOjZZtzM2Jo@XmVs19pCbNrTvJHE3qtk8yuFdh3KlChkdNif5EF2siYff5Q/ "Python 2 – Try It Online")
-11 bytes thanks to Mr. Xcoder
-12 bytes thanks to Mr. Xcoder and Rod
[Answer]
# ~~[APL (Dyalog Classic)](https://www.dyalog.com/)~~ [ngn/apl](https://github.com/ngn/apl), 18 bytes
EDIT: switched to my own implementation of APL because Dyalog doesn't support infinities and the challenge author [doesn't allow](https://codegolf.stackexchange.com/questions/156497/we-do-tower-hopping?noredirect=1#comment381474_156497) finite numbers to act as "null"
```
⊃⊃{⍵,⍨1+⌊/⍺↑⍵}/⎕,0
```
~~[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6moGoupHvVt1HvWuMNR@1NOl/6h316O2iUChWn2gah2D/0CV/9O4TBQMFIwgmCuNy0DBEMgyBmJDIE/HBEgYgiVAgoYKhgA "APL (Dyalog Classic) – Try It Online")~~
[try it at ngn/apl's demo page](https://ngn.github.io/apl/web/index.html#code=%u2395%u2190%20%u2283%u2283%7B%u2375%2C%u23681+%u230A/%u237A%u2191%u2375%7D/%u2395%2C0)
returns ~~`⌊/⍬`~~
`∞` for no solution
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
(1%)
0%_=1/0
a%(h:t)=min(1+h%t)$(a-1)%t
_%_=0
```
[Try it online!](https://tio.run/##LYrRCsIgGEbvfYpdJCi55V9dBT6JjfFjLkfTZAq9fWbbLs7H@eA4TC87z2VU98KAciLpoOAkCVLmbpkrPwUGR0czPzBsgdNMhprI4nEKagrZLmgyS@796TzGZuwWiw9etO4FafR1WyHFeWP9UkD1SwXW/3fYfd9a9l8zzvhMpTUx/gA "Haskell – Try It Online")
Outputs `Infinity` when impossible. The auxiliary left argument to `%` tracks how many more spaces we can move in our current hop.
[Answer]
# [Perl 5](https://www.perl.org/), ~~56~~ 53 bytes
Includes `+1` for `a`
```
perl -aE '1until-@F~~%v?say$n:$n++>map\@v{$_-$F[-$_]..$_},%v,0' <<< "4 0 2 0 2 0"; echo
```
Just the code:
```
#!/usr/bin/perl -a
1until-@F~~%v?say$n:$n++>map\@v{$_-$F[-$_]..$_},%v,0
```
[Try it online!](https://tio.run/##JYpBC4IwGIbv/ooPmyedbKWXRuXJc/cKWfQFgs6xzVVE/vTWoAcensP7ajRDHWaLUJeclUwEPivXD7RplyXzBytfRG2JyvP9KPW58W/SUdKeKOkuZUm6T5H5ggURfymlNBVE7ZiY1Q3vkHmIrOBoeuXAopZGusnAFd0DUQE@5agHtAUYtHFAsE46DBUwWP9NGPDYTZQn1XfSrp@UDVT@AA "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 80 bytes
```
sub f{$_[0]>=@_||1+((sort{$a?$b?$a-$b:-1:1}map f(@_[$_..$#_]),1..$_[0])[0]||-1)}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrVolPtog1s7WIb6mxlBbQ6M4v6ikWiXRXiXJXiVRVyXJStfQyrA2N7FAIU3DIT5aJV5PT0U5PlZTxxDIAGnVBOKaGl1Dzdr/xYmVQFUmOgYwqGnNhRAzgmC4mIGOIZBvDMSGCHWa1v//5ReUZObnFf/X9TXVMzA0AAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
ṛ/ṆȧJ’Ṛ
Rḟ"ÇƤZ$$Tị$Œp+\€Ṁ<Li0ȧ@Ḣ
```
[Try it online!](https://tio.run/##AUQAu/9qZWxsef//4bmbL@G5hsinSuKAmeG5mgpS4bifIsOHxqRaJCRU4buLJMWScCtc4oKs4bmAPExpMMinQOG4ov///1s0XQ "Jelly – Try It Online")
This is just too long...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 bytes
```
<LḢ
ḊßÐƤṁḢḟ0‘Ṃµ1Ç?
```
[Try it online!](https://tio.run/##y0rNyan8/9/G5@GORVwPd3Qdnn94wrElD3c2AvkPd8w3eNQw4@HOpkNbDQ@32/8/3P6oac3//9HRJjoGOkYQHKsTbaBjCGQZA7EhkGcCxCCeIZAXCwA)
## Explanation
```
<LḢ Helper link. Input: array
< Less than
L Length
Ḣ Head - Returns 0 if its possible to jump out, else 1
ḊßÐƤṁḢḟ0‘Ṃµ1Ç? Main link. Input: array
Ç Call helper link
? If 0
1 Return 1
Else
µ Monadic chain
Ḋ Dequeue
ßÐƤ Recurse on each suffix
Ḣ Head of input
ṁ Mold, take only that many values
ḟ0 Filter 0
‘ Increment
Ṃ Minimum
```
[Answer]
# [JavaScript ES6](https://nodejs.org), 118 bytes
```
(x,g=[[0,0]])=>{while(g.length){if((s=(t=g.shift())[0])>=x.length)return t[1];for(i=0;i++<x[s];)g.push([s+i,t[1]+1])}}
```
[Try it online!](https://tio.run/##bc29DsIgHATw3adw/JMiAXWr9EUIQ1P5MqQ0QLVJ02dHauJiHG763eUe/bNPQ3RTPo3hrormBRZsuBAUUykR79aXdV6BIV6NJlu0Og2QOGRuSLJOZ0BIUIk6vnwrUeU5jscsmGx1iOA4bV3T3BaRZIsMmeZkQaTG4b3SMIm2rQxhTMEr4oMBDfWe4TO@1FRGhx/dhf2VK6Z180nV8gY "JavaScript (Node.js) – Try It Online")
Performs a breadth first search of the array to find the shortest path.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 80 bytes
```
f(A,l,M,j,r)int*A;{M=~0;for(j=0;l>0&&j++<*A;)if(M<1|M>(r=f(A+j,l-j)))M=r;A=-~M;}
```
[Try it online!](https://tio.run/##XY1BCsIwFETvUrD8b38h0eImTSEHyAnUhVQiCWmU4C62V68f3Ygws5nHzIztbRzX1YGhSJYCZfTpuTWqWL0I5e4ZghYqDqKuQ9P0TNA7sL182QGy5mITKLYBEa3Oyuh2sWpep4tPgOWRec1BtbnSR6dUkQPg8HjG0pGg3dczHfCHCJKc7tnyj3QzSUR@eAM "C (gcc) – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 79 bytes
Returns the number of jumps or `Inf` if you can't escape. Recursively look at the first element and either return `Inf` or `1` depending on if you can escape, otherwise add `1` to the shortest solution for truncated arrays representing each valid jump. The control flow is done with two ternary statements like `test1 ? ontrue1 : test2 ? ontrue2 : onfalse2`.
```
f(a,n=endof(a))=a[1]<1?Inf:a[1]>=n?1:1+minimum(f(a[z:min(z+a[1],n)]) for z=2:n)
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/TSNRJ882NS8lH8jS1LRNjDaMtTG098xLswIx7Wzz7A2tDLVzM/Myc0tzNYCKoqusgDyNKm2QvE6eZqymQlp@kUKVrZFVnuZ/h@KM/HKFNI1oAx1DHSMdYyA2jNXkggub6BgAhcAYWRik0hCk8j8A "Julia 0.6 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 97 bytes
```
f=l=>{for(int c=l.Count,s=0,j=l[0];j>0;s=f(l.GetRange(j,c-j--)))if(s>0|j>=c)return s+1;return 0;}
```
[Try it online!](https://tio.run/##tZI9a8MwEIZ3/4obJeoPOemmyEugXVIo7dAhZDCqbGRUGXRyS3H92107SU1wO2RwbzgOdHqfe4@TGMnaqV6aHBEegzaAIdDnXkt4r/UrPOTaEvRO23J/gNyVSI89p84xnj/Rq7f4rrFyc663tTFKel1bjO@VVU7LeKfRb7T1WQhjhgIE2MYY3hfCiKwtakeGB5DCDP8b60MULKyE2bMDrzLGURTEDHL@KbelIlUooyqKKKW6IJixryoTkjrlG2cBb1J@Lhnveh7Mp90Oo9VGxS9Oe7XTVpGCWPUB1xiAFm5DYCGspgwdpXyUT5LVwqiBkB4h62NOL1BsaVeT9iySJP3nBU7GkmS9MOokP3Jm9pZf4Pr3Qfyglj6L9E9LF666oOu/AQ "C# (.NET Core) – Try It Online")
Returns 0 if no path was found.
**Explanation**
```
f =
l => //The list of integers
{
for (
int c = l.Count, //The length of the list
s = 0, //Helper to keep track of the steps of the recursion
j = l[0]; //The length of the jump, initialize with the first element of the list
j > 0; //Loop while the jump length is not 0
s = f(l.GetRange(j, c - j--)) //Recursive call of the function with a sub-list stating at the current jump length.
//Then decrement the jumplength.
//Returns the number of steps needed to jump out of the sup-list or 0 if no path was found.
//This is only executed after the first run of the loop body.
)
{
if (j >= c | //Check if the current jump lengt gets you out of the list.
//If true return 1 (s is currently 0). OR
s > 0 ) //If the recursive call found a solution (s not 0)
//return the number of steps from the recursive call + 1
return s + 1;
}
return 0; //If the jump length was 0 return 0
//to indicate that no path was found from the current sub-list.
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ ~~73~~ 72 bytes
-10 thanks to @user202729
-1 thanks to @JonathanFrech
```
lambda a:a and(a[0]and-~min(f(a[k+1:])for k in range(a[0]))or 1e999)or 0
```
[Try it online!](https://tio.run/##JYpBCsMgEEX3PYVkpUSCpt0k0JNYkSlqK4lGjBRy@nSSDLyZ94eft/pdUr/752ufIb4tEBiRZCkoofGSGBL1mKZWjpq10i@FTCQkUiB93FljDH/SDcNwiNhzCanSCJl67n4wU2NCzEupxtBm3daGdWu1IXXFgaUMZ1dK8xtRj2tzwfuLMwsu0e@IPPPhEl3/AQ "Python 2 – Try It Online") Returns infinity for a null value.
] |
[Question]
[
Craps is a fairly simple dice game often played in casinos. Even if you aren't a gambler (which I'm not), it's still a fairly interesting game. Here's the rules:
At the start of a game of Craps there's what is called the *come-out* round. The player rolls two d6s (six-sided die) and the two die rolls are added. If the result is 7 or 11, the person automatically wins (this is known as a *natural*). If the result is 2, 3 or 12 the person automatically loses (this is known as *crapping out*). Otherwise, the result is set as the *point* for the point round.
After this, the *point* round begins. During the point round, the player must continuously roll 2 d6s until the person rolls a 7 or his/her point from the previous round. If the person rolls a 7, they lose. If they roll their point, they win.
# Challenge
Implement a simple program that simulates a game of craps. If the person rolls a natural or a crap-out during the come-out round, the program should output "Natural: " or "Crapping out: " followed by the die-roll and then exit. Otherwise, it should output "Point: " followed by the point. Then, during the point round, it should output every die-roll until a 7 or the point is reached. If the person wins, it should output `"Pass"`; if they lose it should output `"Don't Pass"`.
# Reference Implementation
Groovy, 277 bytes
```
def a={return Math.random()*6+1};int b=a()+a();(b<4||b==12)?{println"Crapping out: "+b}():{(b==7||b==11)?{println"Natural: "+b}():{println"Point: "+b;for(;;){int x=a()+a();println x;(x==7)?{println"Don't Pass";System.exit(0)}():{if(x==b){println"Pass";System.exit(0)}}()}}()}()
```
[Try it online.](http://ideone.com/fork/gB0YGf)
# Sample outputs
`Natural: 7`
`Crapping out: 3`
```
Point: 9
4
8
11
9
Pass
```
and
```
Point: 5
3
7
Don't Pass
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
(DISCLAIMER: This challenge is not intended to promote gambling in any way. Remember, the house always wins.)
[Answer]
# Ruby 164
Pretty straightforward. Interesting features:
The crapping out cases are summarised as `r%12<4` and the remaining natural cases are summarised as `r%4==3`.
The initial string is stored in `c` and further rolls are taken only if this is later alphabetically than the single letter `?P` (which only occurs for `Point`.)
```
f=->{rand(6)+rand(6)+2}
s=0
r=f[]
print c=r%12<4?'Crapping out':r%4==3?'Natural':'Point',": #{r}
"
c>?P&&(until s==r||s==7
p s=f[]end
print s==7?"Don't ":"","Pass")
```
[Answer]
# Python 3, 190 bytes
```
from random import*
r=randrange
p=print
a=r(5)+r(5)+2
c=890145//3**a%3
p(['Point:','Crapping out:','Natural:'][c],a)
if c<1:
while 7!=c!=a:c=r(5)+r(5)+2;p(c)
p(['Pass',"Don't pass"][c==7])
```
This is based on [Celeo's answer](https://codegolf.stackexchange.com/a/61504/39328); I replaced some lengthy conditionals with a magic number that encodes a LUT for each number, reused a variable, and did a few other miscellaneous golfs. Still room to golf; it's probably possible to get under 170.
I didn't try to use Python 2, so I don't know if it would be shorter.
[Answer]
## C99, ~~366~~ ~~312~~ ~~293~~ 277 bytes
This is my first post here, so I'm going to guess that this can be improved by a lot.
```
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){srand(time(0));s=r+r;int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";if(a){p a,s);return 0;}p"Point:%d\n",c=s);do p"%d\n",s=r+r);while(7-s&&s-c);p(7-s)?"Pass":"Don't pass");}
```
### Expanded Version
```
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){
srand(time(0));
s=r+r;
int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";
if(a) {p a,s);return 0;}
p"Point:%d\n",c=s);
do p"%d\n",s=r+r);
while(7-s&&s-c);
p(7-s)?"Pass":"Don't pass");
}
```
As you can see, there's a good amount of redundancy here that can most likely be done away with.
Credits to @Mego for helping to make this smaller.
[Answer]
# Python 2, ~~226~~ 224 bytes
First pass and there's a lot of code there:
```
from random import*
r=randrange
a=r(5)+r(5)+2
if a in[7,11]:print'Natural:',a
elif a in[2,3,12]:print'Crapping out:',a
else:
print'Point:',a
b=0
while b not in[7,a]:b=r(5)+r(5)+2;print b
print'Pass'if b-7else"Don't pass"
```
Thanks to [Mego](https://codegolf.stackexchange.com/users/45941/mego) for 2 bytes!
[Answer]
# PHP ~~230~~ ~~228~~ ~~218~~ ~~199~~ ~~192~~ 188 Bytes
186 bytes without the `<?`
```
<?$a=rand(1,6)+rand(1,6);$a%4==3?die("Natural: $a"):$a%12<4?die("Crapping out: $a"):print"Point: $a
";while(1){($b=rand(1,6)+rand(1,6))==7?die("Don't Pass"):$b==$a?die("Pass"):print"$b
";}
```
First attempt at code golf! Not sure if using `</br>` would be allowed though? As this would not work in a console (as a new line). Let me know if this is not allowed and will alter my code.
EDIT (16-8-16): After getting better at codegolf I noticed some possible improvements. This still works using the command line interface. Replaced `</br>` with an hard enter.
[Answer]
# Javascript 262
```
var r=(x=>Math.floor(Math.random()*6+1)),a=r()+r();if(a<4||a==12){alert("Crapping out: "+a)}else if(a==7||a==11){alert("Natural: "+a)}else{alert("Point: "+a);while(1){var b = r()+r();if(b==a){alert("pass");break}if(b==7){alert("dont't pass");break}alert(""+b)}}
```
[Answer]
# [Perl 5](https://www.perl.org/), 140 bytes
```
sub d{1+int rand 6}say$"=($p=&d+&d)%12<4?"Crapping out":$p%4-3?Point:Natural,": $p";if($"gt O){say$_=&d+&d until/7|$p/;say"Don't "x/7/,Pass}
```
[Try it online!](https://tio.run/##JczRCoIwGEDhVxljmqI2LU3QxIu6rXyDWKxkINvPNqEwX71ldHvgfHDXQ@GcGW@IT1kkpEWaSY52s2EvgpuAQOPzyOehl232eYsPmgEI2SM1WlwR8PJk23ZqGaszs6NmQ4wrRADX4hEQ3Ft0Caefdf07aJRWDLR8E6D10vFRyZVF@ElLGnfMmNm5jwIrlDQuORXrNEu/ "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~181~~ ~~183~~ ~~179~~ ~~178~~ ~~167~~ 165 bytes
-10 bytes thanks to mazzy
-2 bytes thanks to Xcali
```
switch -r($z=&($x={(random 6)+(random 6)+2})){'7|11'{"Natural: $z"}'2|3'{"Crapping out: $z"}default{"Point: $z"
do{($m=&$x)}until($m-in7,$z)"Don't "*!($m-7)+'Pass'}}
```
[Try it online!](https://tio.run/##TcndCoIwGMbxc6/ibbw51xdpkJB4VNBZdAcxUmswN5kTw7lrt6KTzp7/72l0X5r2WUo5YZW7qe2FvT9hbSIc8jDCV@4iw1Wha9iz5d9MPGOOpmMcU0cu3HaGywPgQDxNxt3HjoY3jVAP0J39HUVZ8U5aR65aqJ8FhXYR1nmIL@Y7ZYX81FqodIUDIyetqAWymH0xZUt65W1LvZ98EMSbTbwd546ceV0C3uBAMgixyoBSP70B "PowerShell – Try It Online")
Unrolled version:
```
#Switch using regex on $z which is...
#&($x={...}) first assigns $x to a scriptblock then calls it, saving the return to $z
switch -r($z=&($x={(random 6)+(random 6)+2})){
'7|11' {"Natural: $z"}
'2|3' {"Crapping out: $z"}
default{
"Point: $z"
#Call the diceroll scriptblock until you Pass,
#while pushing each roll to output
do{($m=&$x)}
until($m-in7,$z)
"Don't "*!($m-7)+'Pass'
}
}
```
There's a few less sticking points now that the list-building logic has been rebuilt into a switch. I think it's still a pretty alright approach. +2 bytes fixing a bug.
[Answer]
# R, 197 bytes
```
r=sum(sample(6,2,T));if(r%%12<4)cat("Crap Out",r)else if(r%%4==3)cat("Natural",r)else{cat("Point",r);while(T){cat("",q<-sum(sample(6,2,T)));if(q==7){cat(" Don't");break};if(q>r)break};cat(" Pass")}
```
Ungolfed
```
r=sum(sample(6,2,T))
if (r%%12<4) {
cat("Crap Out",r)
} else if (r%%4==3) {
cat("Natural",r)
} else {
cat("Point",r)
while (T) {
q = sum(sample(6,2,T))
cat("",q)
if (q==7) {
cat(" Don't")
break
}
if (q>r) break
}
cat(" Pass")
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 108 bytes
```
p|K?}J+OS6OS6,7 11"Natural"?}J[2 3 12)"Crapping out"k"Point"+": "JI!KW!}Z,7JIq7=Z
+OS6OS6=K"Don't "))+K"Pass
```
[Try it online!](https://tio.run/##K6gsyfj/v6DG277WS9s/2AyIdMwVDA2V/BJLSosSc5SA4tFGCsYKhkaaSs5FiQUFmXnpCvmlJUrZSgH5mXklStpKVgpKXp6K3uGKtVE65l6ehea2UVxQs2y9lVzy89RLFJQ0NbW9lQISi4v//wcA "Pyth – Try It Online")
First pass, can probably find a few savings.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 151 bytes
```
R}}6'RA6'RA2++{{B͍
00B:7=S:b={+?\"Natural: "@>
pping out: "@\:2=}:3=}:c={{++?/"Cra
{:}≠ ?\ 6?;$$k\/ak$00B:$:7≠?\
"Don't "R"Pass"a/\$:$" :tnioP"\
```
[Try it online!](https://tio.run/##FcwxCoMwFIDhPad4PAIOGRQLFl5J09rOReyaJXUoYomicQo5Qu/jIeyZUh2@4V/@cbZtE2MdQpHU110uhPfl78uyrKSjfNJLeqE0PoybR/MhwMuZDUNr39DPbk9NuQx02DTSeyFUirfRME9BrgsAKA2FOnHe6dR0fN/ybbwuSjO89zZxgDVWZprQpJoTRyBn275CHeMf "Runic Enchantments – Try It Online")
After fixing a bug regarding random numbers (it was re-seeding every time `'RA` was called, and the seed was system time, resulting in massive runs of repeated values) this works correctly.
### Explanation
Entry is on the second line, as the first line up until `B͍` is a function for rolling two dice and summing them.
Program flow, with some edge-wrapping and curled redirections unrolled for readability
```
R}}6'RA6'RA2++{{B͍ Roll 2, sum, return
>00B:7=S:b={+?\ Entry, make first roll, compare to 7 and 11.
"Natural: "@ If true, print "Natural: " and the value, else go down
\:2=}:3=}:c={{++?/ Compare to 2, 3, and 12.
"Crapping out: "@ If true, print "Crapping out: " and the value, else go up
\$:$" :tnioP"\ Print "Point: " and value (IP is travelling RTL)
/ak$00B:$ Print newline, roll, print
:7≠?\ Compare to 7
\"Don't "R"Pass"ak$$; If equal, print a newline and "Don't Pass"
{:}≠ ?\ Else compare to initial roll.
R"Pass"ak$$; If equal, print a newline and "Pass"
6?......ak$00B Else return to roll loop by printing a newline
and rolling again (. are skipped instructions)
```
There are only 4 NOP instructions (`{:}≠...?\.6?`) that would be very difficult to remove due to the space required on other lines (Namely the length of the `"Don't "` string).
] |
[Question]
[
This is not a challenge. I'm wondering if it's at all possible to get user input into two separate variables in python (2 or 3) with less than 19 bytes. These are all the shortest I can get:
```
a,b=input(),input()
a=input();b=input() (newline replaced with semicolon for readability)
i=input;a,b=i(),i()
```
Is there any shorter way to do this?
[Answer]
If prompting the user doesn't matter, this is slightly shorter than `eval` for 3 or more:
```
a,b,c=map(input,[1]*3)
a,b,c=map(input,'111')
```
It's also shorter even if prompting is not ok:
```
a,b,c=map(input,['']*3)
```
Sadly, xnor's idea doesn't save anything for 2 inputs as it is still longer (19 bytes). However if you have some string (or appropriate iterable) with the appropriate length already (because magic?) then it could be shorter.
xnor found an example of a magic string for 3 inputs in Python 2 only:
```
a,b,c=map(input,`.5`)
```
This also requires that the prompts not be important, though.
This trick actually helps to save bytes for large numbers of inputs by using `1eX` notation (getting x+3 inputs):
```
a,b,c,d,e,f=map(input,`1e3`)
```
---
Explanation:
Python's `map` function performs the function it is passed on each element of the iterable that is also passed to it, and returns the list (or map object) containing the results of these calls. For the first example, the map could be decomposed to:
```
[input(1), input(1), input(1)]
```
[Answer]
For 3 or more inputs, this is shorter:
```
a,b,c=eval("input(),"*3)
```
[Answer]
*Note that unless the question specifies the input type or requires a complete program, [you can take input as function arguments](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default input/output methods"), cutting out the need for* `input()`. *Where this is not an option, the following may help in certain cases.*
---
If you want single characters in the variables `a` and `b`, you can use
```
a,b=input()
```
Entering a 2 character string will then result in the first character being assigned to `a` and the second character being assigned to `b`. (Less than 2 or more than 2 characters in the string will give an error.)
If you require more than a single character per variable then this approach will not work. This could still be used to enter 2 single digit numbers as a string. If numbers beyond 9 are required then the full range of potential input characters could be interpreted as numbers.
Note that this also works for more than 2 variables:
```
a,b,c,d,e,f,g,h=input()
```
This works because in Python a string is a sequence of characters, and can be used anywhere a sequence is expected.
[Answer]
This may be much shorter for Python3 and inputs as integer
```
a,b,c=map(int,open(0))
```
For example expected input is:
23
45
56
The above golf code will assign respective integer values a=23, b=45, c=56
] |
[Question]
[
The challenge is really simple: given a number, you split its digits into an array of smaller numbers such that the resulting numbers are non-decreasing. The catch is that you have to split it such that the array length is maximal.
**Confused?**
* You are given a positive integer via STDIN (or closest alternative), command-line argument or function argument in any convenient, unambiguous input format.
* You have to partition the number's decimal digits into contiguous, disjoint groups.
* The array of numbers represented by these digit groups should be sorted (in the usual, non-decreasing order) **without rearranging the groups**.
* In cases where more than one such partition exists, you have to partition the input into as many numbers as possible. In the case of ties, return one such result.
* You can output the array to STDOUT (or closest alternative) or as a function return value. In case of STDOUT (or closest alternative), the array should be printed in any convenient, unambiguous list format.
* The split numbers should not have leading zeroes. So for instance `1002003` cannot be printed as either `[1, 002, 003]` or `[1, 2, 3]` and the only valid answer for it is `[100, 2003]`.
**Test cases:**
```
123456 -> [1, 2, 3, 4, 5, 6]
345823 -> [3, 4, 5, 8, 23]
12345678901234567890 -> [1, 2, 3, 4, 5, 6, 7, 8, 90, 123, 456, 7890]
102 -> [102]
302 -> [302]
324142 -> [3, 24, 142] OR [32, 41, 42]
324142434445 -> [32, 41, 42, 43, 44, 45]
1356531 -> [1, 3, 5, 6, 531]
11121111111 -> [1, 1, 1, 2, 11, 11, 111]
100202003 -> [100, 202003]
```
**Scoring**
This is code-golf so shortest code in bytes wins.
[Answer]
# Pyth, 34
```
FNyUz#aYmv:zhdedC,+0N+NlzB)efqSTTY
```
Try it [online here](https://pyth.herokuapp.com/?code=FNyUz%23aYmv%3AzhdedC%2C%2B0N%2BNlzB)efqSTTY&input=100202003&debug=0). Notice, this has a time (and space) complexity of O(n). Therefore the test case `12345678901234567890` takes too long in the online compiler. Use the offline one instead (1 minute on my laptop).
This is only my first attempt. There might be some room for improvements.
First some ideas how my algorithm works.
* I interpret the input as string and not as a number.
* Then I create all possible subsets of `[0, 1, 2, ..., len(n-1)]`
* For each of these subsets (lets take `[1, 4, 5]`), I split the input string into part using these numbers. `[input[0:1], input[1, 4], input[4,5], input[5,len(input)]]`.
* Afterwards I try to convert these numbers into strings. There can be two problems. Pyth (or Python) throws an exception for an empty string, and for a string of numbers starting with `0`. Therefore I use a `try - catch` block (actually infinity loop with an immediate break). If converting was successfully, I add the result to a list `Y`.
* After I handled all subsets, I filter the list `Y` for results, that are already sorted and print the last one (the last one has the most groups).
Now the detailed explanation:
```
Implicit: z = input() (z is a String!)
Y = empty list
FNyUz for each subset N of [0, 1, 2, ..., len(z)-1]:
# start try-catch block (actually an infinite loop,
but the Python implementation uses a try catch.
aY append to Y:
C,+0N+Nlz zip([0] + N, N + [len(z)])
m map each element d to
:zhded z[d[0]:d[-1]]
v evaluated
B if this didn't throw an exception already, end the infinite loop
) end for loop
f Y filter Y for elements T, for which
qSTT sorted(T) == T
e and print the last one (the subsets generated with yUz are sorted
by length, so the last one has the most groups)
```
[Answer]
# Mathematica, ~~134~~ 127 bytes
This is pretty inefficient since it generates a *lot* more partitions than the valid ones. The `324142434445` test case runs within a few seconds, but I wouldn't try `12345678901234567890`.
```
f/@Last@Select[Needs@"Combinatorica`";f=FromDigits;SetPartitions[d=IntegerDigits@#],0<=##&@@f/@#&&Join@@#==d&&#~FreeQ~{0,__}&]&
```
This defines an unnamed function which takes an integer and returns a list of integers.
## Explanation
The reading order of this code is a bit all over the place, so I'll break down in the order it's intended to be read (and evaluated for the most part):
* `d=IntegerDigits@#` get the decimal digits of the input and assign this list to `d`.
* `SetPartitions` (which requires `Needs@"Combinatorica`";`) gives me all partitions of this. However, it returns a lot more than I actually want since it treats the input as a *set*. This is what makes it inefficient, but I'm using this because the shortest way I know to get all list partitions is much longer. As an example, if the list was `{1, 2, 3}` the function would return:
```
{{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 2}, {3}}, {{1, 3}, {2}}, {{1}, {2}, {3}}}
```
Note that a) the consecutive partitions are all in the right order and b) the partitions are sorted from coarsest to finest.
* `Select[...,...&]` then filters this list by the anonymous function passed in as the second argument.
+ `Join @@ # == d` checks that we've actually got a list partition instead of a general set partition.
+ `#~FreeQ~{0, __}` checks that no partition starts with a leading zero.
+ `0 <= ## & @@ f /@ #` is a bit more obscure. First we map `FromDigits` onto each list in the partition to recover the numbers represented by the digits. Then we apply `0 <= ##` to those numbers, where `##` refers to all the numbers. If the partition is `{1, 23, 45}` then this expands to `0 <= 1 <= 23 <= 45`, so it checks that the array is sorted.
* `Last@` then gives me the last partition left after filtering - this works because `SetPartitions` already sorted the partitions, such that the finest ones are at the end.
* Finally, `f/@` recovers the numbers from the digit lists.
[Answer]
# Python 3, 134 bytes
```
def f(s,n=0,L=[],R=[],i=0):
while s[i:]:i+=1;m=int(s[:i]);R=max([f(s[i:],m,L+[m]),R][m<n or"1">s[i:]>"":],key=len)
return[L,R][s>""]
```
It's a little messy, but oh well. The program just generates all valid partitions recursively. The interesting part is that to disallow leading zeroes, all that was necessary was an additional `or "1">s[i:]>""` condition.
Takes input like `f("12345678901234567890")` and returns a list of ints.
[Answer]
# Pyth, ~~62~~ ~~61~~ 60
```
JlzKkef&qJsml`dTqTSTolNmmibTcjKsC,z+m>Ndt>+*J]0jk2_JKNU^2-J1
```
## Explanation
The algorithm works by generating all binary numbers between `0` (inclusive) and `2^(n-1)` (exclusive), where `n` is the length of the input.
The binary digits of each are then mapped to a separator (`N`) for 1 and nothing for 0.
These characters are then inserted between each input character, and the result is split by `N`, yielding a list.
The values in the lists are then parsed to integers, and the lists are sorted by length. Then all that is left is to filter out non-sorted ones and ones that have been split at leading zeroes, after which the longest list is picked.
```
Jlz set J to len(input)
Kk set K to ""
e take the last of:
f& only take lists where:
qJsml`dT sum of string lengths of items
is equal to length of input and
qTST list is in order
olN sort by length
m map k over...
mibT convert items to int (base-10)
c N split by N
jK join by ""
s sum to combine tuples
C,z zip input with
+ K append [""] for equal lengths
m>Nd replace 1 with N, 0 with ""
t take all but first
> _J take len(input) last values
+ pad front of binary with
*J]0 [0] times input's length
jk2 current k in binary
U^2-J1 range 0..2^(len(input)-1)-1
```
[Answer]
# Pyth, 25 bytes
```
ef&&Fmnhd\0T.A<V=NsMTtN./
```
[Try it online!](http://pyth.herokuapp.com/?code=ef%26%26Fmnhd%5C0T.A%3CV%3DNsMTtN.%2F&input=%22100202003%22&debug=0)
How it works:
```
ef&&Fmnhd\0T.A<V=NsMTtN./ Q = eval(input())
./ all partitions of Q
f ./ filter all partitions of Q where:
& both:
&Fmnhd\0T neither substring starts with "0"
and:
.A<V=NsMTtN all entries are less than their proceeding ones
e returns the last amongst the filtered partitions
```
[Answer]
# J, 109 bytes
Very long but at least takes up O(n \* (2n)!) memory and O(n \* log(n) \* (2n)!) time where n is the length of the input. (So don't try to run it with more than 5 digits.)
```
f=.3 :0
>({~(i.>./)@:(((-:/:~)@(#$])*#)@>))<@".(' 0';' _1')rplc"1~(#~y-:"1' '-."#:~])(i.!2*#y)A.y,' '#~#y
)
```
The function takes the input as a string.
Examples:
```
f every '5423';'103';'1023'
5 423
103 0
10 23
```
Method:
* Add the same number of spaces to the input as it's length.
* Permute it in every possible way.
* Check if the spaceless string is the same as the input (i.e. it's a partition of it).
* Replace ' 0's to ' \_1's to invalidate leading zero solutions.
* Evaluate each string.
* Find the longest list which is also sorted. This is the return value.
[Answer]
# Haskell, 161 bytes
```
(#)=map
f[x]=[[[x]]]
f(h:t)=([h]:)#f t++(\(a:b)->(h:a):b)#f t
g l=snd$maximum[(length x,x::[Int])|x<-[read#y|y<-f l,all((/='0').head)y],and$zipWith(>=)=<<tail$x]
```
Test run:
```
*Main> mapM_ (print . g) ["123456","345823","12345678901234567890","102","302","324142","324142434445","1356531","11121111111","100202003"]
[1,2,3,4,5,6]
[3,4,5,8,23]
[1,2,3,4,5,6,7,8,90,123,456,7890]
[102]
[302]
[32,41,42]
[32,41,42,43,44,45]
[1,3,5,6,531]
[1,1,1,2,11,11,111]
[100,202003]
```
How it works: the helper function `f` splits the input list into every possible list of sublists. `g` first discards those with a sublist beginning with `0` and then those without the proper order. Pair every remaining list with it's length, take the maximum and discard the length part again.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/3596/edit)
Build a regex that will accept a regex string as input and check if it's valid. Basically, your regex should be able to validate itself. (Any invalid regex should not be validated, so you can't use `.*`. ;))
Your flavor must be fully supported by *well known* implementations (Perl, sed, grep, gawk, etc), and it must fully support what those implementations support. [Don't worry about the lawyer speak; I'm just trying to remove any possible loopholes for the smart\*\*\*es.]
---
I'd [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") it, but I'm worried it'll give an edge to those who know and use non-feature-rich flavors. Or are my worries unfounded?
[Answer]
## Ruby
I tried to match the actual syntax of Ruby's regex flavor as much as possible, but there are a few quirks: it accepts a few lookbehinds that are actually invalid (like `(?<=(?<!))`), and it recognizes empty character ranges like `D-A`. The latter could be fixed for ASCII, but the regex is long enough as it is.
```
\A(?<main>
(?!
\{(\d+)?,(\d+)?\} # do not match lone counted repetition
)
(?:
[^()\[\]\\*+?|<'] | # anything but metacharacters
(?<cclass>
\[ \^? (?: # character class
(?: # character class
[^\[\]\\-] | # anything but square brackets, backslashes or dashes
\g<esc> |
\[ : \^? (?: # POSIX char-class
alnum | alpha | word | blank | cntrl | x?digit | graph | lower | print | punct | space | upper
) : \] |
- (?!
\\[dwhsDWHS]
) # range / dash not succeeded by a character class
)+ |
\g<cclass> # more than one bracket as delimiter
) \]
) |
(?<esc>
\\[^cuxkg] | # any escaped character
\\x \h\h? | # hex escape
\\u \h{4} | # Unicode escape
\\c . # control escape
) |
\\[kg] (?:
< \w[^>]* (?: > | \Z) |
' \w[^']* (?: ' | \Z)
)? | # named backrefs
(?<! (?<! \\) \\[kg]) [<'] | # don't match < or ' if preceded by \k or \g
\| (?! \g<rep> ) | # alternation
\( (?: # group
(?:
\?
(?:
[>:=!] | # atomic / non-capturing / lookahead
(?<namedg>
< [_a-zA-Z][^>]* > |
' [_a-zA-Z][^']* ' # named group
) |
[xmi-]+: # regex options
)
)?
\g<main>*
) \) |
\(\?<[!=] (?<lbpat>
(?! \{(\d+)?,(\d+)?\} )
[^()\[\]\\*+?] |
\g<esc> (?<! \\[zZ]) |
\g<cclass> |
\( (?: # group
(?:
\?: |
\? \g<namedg> |
\? <[!=]
)?
\g<lbpat>*
) \) |
\(\?\# [^)]* \)
)* \)
|
\(\? [xmi-]+ \) # option group
(?! \g<rep> )
|
\(\?\# [^)]*+ \) # comment
(?! \g<rep> )
)+
(?<rep>
(?:
[*+?] | # repetition
\{(\d+)?,(\d+)?\} # counted repetition
)
[+?]? # with a possessive/lazy modifier
)?
)*\Z
```
Unreadable version:
```
\A(?<main>(?!\{(\d+)?,(\d+)?\})(?:[^()\[\]\\*+?|<']|(?<cclass>\[\^?(?:(?:[^\[\]\\-]|\g<esc>|\[:\^?(?:alnum|alpha|word|blank|cntrl|x?digit|graph|lower|print|punct|space|upper):\]|-(?!\\[dwhsDWHS]))+|\g<cclass>)\])|(?<esc>\\[^cuxkg]|\\x\h\h?|\\u\h{4}|\\c.)|\\[kg](?:<\w[^>]*(?:>|\Z)|'\w[^']*(?:'|\Z))?|(?<!(?<!\\)\\[kg])[<']|\|(?!\g<rep>)|\((?:(?:\?(?:[>:=!]|(?<namedg><[_a-zA-Z][^>]*>|'[_a-zA-Z][^']*')|[xmi-]+:))?\g<main>*)\)|\(\?<[!=](?<lbpat>(?!\{(\d+)?,(\d+)?\})[^()\[\]\\*+?]|\g<esc>(?<!\\[zZ])|\g<cclass>|\((?:(?:\?:|\?\g<namedg>|\?<[!=])?\g<lbpat>*)\)|\(\?#[^)]*\))*\)|\(\?[xmi-]+\)(?!\g<rep>)|\(\?#[^)]*+\)(?!\g<rep>))+(?<rep>(?:[*+?]|\{(\d+)?,(\d+)?\})[+?]?)?)*\Z
```
] |
[Question]
[
This is the reverse of [this challenge](https://codegolf.stackexchange.com/questions/246968/who-needs-8-bits-for-one-character).
Given an encoded list of codepoints and the characters used to encode it, you need to decompress it to its original string.
For example, given the encoded list `[170, 76, 19, 195, 32]` and the encoder characters `" abcdefghijklmnopqrstuvwxyz"`, the output should be `"the fox"`.
## How, though?
First, we need to go through the encoder characters and find out what bits they correspond to. We do this by getting the binary of each corresponding (1-indexed) index in the encoder string. For example, the encoder string `6923`:
```
6, index 1 => 1
9, index 2 => 10
2, index 3 => 11
3, index 4 => 100
```
Now we need to pad each with leading zeros until they are all of equal length:
```
6, index 1 => 001
9, index 2 => 010
2, index 3 => 011
3, index 4 => 100
```
Now that we have a lookup table, let's decode it. First, let's get the binary of each codepoint. Let's say we have codepoints `[137, 147, 16]` (and still encoder string `6923`):
```
137 => 10001001
147 => 10010011
16 => 10000
```
The last one may not be 8 bits long. In this case, pad it with leading zeros until it is:
```
137 => 10001001
147 => 10010011
16 => 00010000
```
Now, smash all these bits into one string: `100010011001001100010000`. Now, we need to group it into sizes of how long each byte will be in the lookup table. Looking back at our lookup table with `6923` encoder string, we can see that each byte is 3 bits long. This means that we need to split the bits into chunks of 3:
```
100 010 011 001 001 100 010 000
```
Now, for each, check its character in the lookup table. If it is all zeros (and therefore not in the lookup table), ignore it.
```
100 => 3
010 => 9
011 => 2
001 => 6
001 => 6
100 => 3
010 => 9
000 is ignored
```
Now, joining this together, the string was `3926639`, and we're done!
## Test cases
```
Codes: [170, 76, 19, 195, 32], encoder characters: " abcdefghijklmnopqrstuvwxyz" => "the fox"
Codes: [151, 20, 40, 86, 48], encoder characters: "123456789" => "971428563"
Codes: [170, 76, 25, 89, 68, 96, 71, 56, 97, 225, 60, 50, 21, 217, 209, 160, 97, 115, 76, 53, 73, 130, 209, 111, 65, 44, 16], encoder characters: " abcdefghijklmnopqrstuvwxyz" => "the quick brown fox jumps over the lazy dog"
Codes: [108], encoder characters: "abc" => "abc"
Codes: [255], encoder characters: "a" => "aaaaaaaa"
Codes: [85, 170], encoder characters: "ab" => "aaaabbbb"
```
## Rules
* Second input can be a string, list, or even list of codepoints (same with output). It doesn't matter, I/O is very flexible for this challenge.
* First input can, again, be a list of the codepoints, or a string containing the represented codepoints (if your language uses an SBCS, you're free to use it (but you can still use UTF-8)). Again, I/O is flexible.
* Input will always be valid.
* Encoder characters will always contain **less** than 256 characters.
* Neither input will ever be empty.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes for each language wins.
* [Standard I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422).
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
## Reference implementation in JavaScript
```
function decode(points, encoderChars) {
const maxBitCount = Math.ceil(Math.log2(encoderChars.length + 1));
const charToBit = Object.fromEntries(encoderChars.map((c, i) => [c, (i + 1).toString(2).padStart(maxBitCount, "0")]));
const charBits =
points
.map((x) => x.toString(2).padStart(8, "0"))
.join("")
.match(RegExp(`.{1,${maxBitCount}}`, "g")) || [];
return charBits
.map((x) => Object.entries(charToBit).find((y) => y[1] === x)?.[0] || "")
.join("");
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVXBbtpAEFWlnviKkYXKruq42GAwQTRSo1xatZGa3qgljFmDifFSe52YEB976x-0lXJof6rHfEC_obM2YIeEUy2t2N158-bt7M7w_VfIJ-zu7ncivCPrz7O_XhK6wuchTJiLFrLkfihiFVgol9HpzIliCusagMvDWMDCSd_44pQnoYABvHfETHOZH5B8FvCpQaqeWsDCqZjBS9Ap7e9IXLR94siDFOfjOXOF5kV8cRaKyGfxQ4aFsyTEVcGnMHgNQ5wRP-fTBL9AfDglBtWWzuRCOJEgFX0qKE2F2vuB0RzDALcAisPmU4AiUpqHSZ8mtwpKuvWYoz9RFFoyCHdGPrLpWbokI22tq_V1RVCWjZBgigRwewtDW-qKmEiicCestq9kkx62Sc0uc1Tz_HBCyCpHrYa6DYPBAFJ6og2btuTf6tqp7NeyzbU_f1ekQ7BY5gJGtVNMeHwMQ73bVKHbUUHvyWGq0DLs3WvIZTquYBFiFXDG7oR505k_vwwWIV9-iWKRXF2nqxtFilLEjIHHU6VkN3UVDIzQxmFhlLZ1iFw3Wm2z07V6BVWvq7cNy-y0lMdSDVRpodwOXk8P110MYuJvr4s2aewg0MRhyOi63G3K08ltidF1syAyW_iLQ281txgdXTpobrelw39l4kviu5cwjvh1KLMC82SxjIFfIZk0B87NCiZ8Wjlg82B2MF5BLCc7B8M0Dzps4Juv9LHwcJjJw4FKxzF-Sm2k4UtcEKrFy8AXpPE5bND8waZF4Wy25aJBK5bh24vzD1hKUcxIik90C8TADVpZH6MbvmaqwmOUvo_S4sB3GcFLOtJzj70tGx99LX_lmsejMwerkwzlMZ9qcyrwRCwTYeclVba8iMka2fTHqvNQ07QqgV3tNDyKsHDRsSDNqxOZSkTIpXWLO8F6BUz4K6VEsAWf-w8x9z--5rD7n992QB4w2XnJqL7OPTKor_Nkx3kH871VRTXN4AUoiKzozvCO62vUk-G56-tCcFZfl3EbDQyKzevaiRGAx8hG2Yj2oZbRftFTtn8p_wA) (feel free to steal the test case code for your own JS answer)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
b8∆Zf⁰LbLẇvBꜝ‹İ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJiOOKIhlpm4oGwTGJM4bqHdkLqnJ3igLnEsOKIkSIsIiIsIlsxNzAsIDc2LCAxOSwgMTk1LCAzMl1cblwiIGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6XCIiXQ==)
```
b # Convert each from binary
8∆Z # Pad each to length 8
f # Flatten
ẇ # Split into chunks of length...
⁰LbL # Length of the encoder string, in binary
vBꜝ‹ # Convert each from binary, remove 0s and decrement
İ∑ # Index those into the encoder and sum
```
[Answer]
# [Uiua](https://uiua.org), ~~29~~ 25 bytes ([SBCS\*](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==))
*or **55 bytes** using native UTF-8 encoding*
```
⇌⊏-1▽±.⍘⋯↯⊂¯1⧻⋯⧻,⇌↘1⋯⊂255
```
[Try it!](https://www.uiua.org/pad?src=RWlnaHRCaXRzIOKGkCDih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikKRWlnaHRCaXRzIFsxMzcgMTQ3IDE2XSAiNjkyMyIKRWlnaHRCaXRzIFsxMDhdICJhYmMiCkVpZ2h0Qml0cyBbMTcwIDc2IDE5IDE5NSAzMl0gIiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiI=)
```
⊂255 # prepend 255 to list of codepoints (to force 8 bits)
⋯ # convert each to bits
↘1 # drop the first one (the 255)
⇌ # and reverse the rows (so concatenation of uiua's big-endian bits will work);
, # now duplicate the second stack item (the encoding characters)
⧻ # get its length
⧻⋯ # convert to bits and get the number of bits
↯⊂¯1 # reshape the codepoint-bit-array to rows of this length
⍘⋯ # and convert each row back to a number from bits (=invert bits);
±. # get the signs of a copy of this (1 or 0)
▽ # and use it to remove any zeros
⊏ # and use the resulting numbers to index into the encoding characters
-1 # (after subtracting 1 to convert to zero-based indexing)
⇌ # finally, re-reverse (to undo the earlier reversal)
```
---
\**Uiua natively supports UTF-8 encoding, allowing functions to bound to multi-byte characters [such as emojis](https://www.uiua.org/docs/bindings). However, this isn't essential for programming in Uiua, and its full functionality can be achieved using the union of printable ASCII characters with Uiua's 108 glyphs, which can each be represented using a single byte.
This answer to the challenge provides one way that such a mapping can be implemented, which can be considered as a single-byte character system (SBCS) for Uiua (with the obvious proviso that multi-byte characters other than Uiua's glyphs are not used in the code). Since Uiua's [default behaviour](https://www.uiua.org/install) is to run any file in the directory with a `.ua` filename suffix, this can even be used as a runnable implementation by simply prepending `&fwa "program.ua"` to save the output to the file "`program.ua`".*
[Answer]
# [J](http://jsoftware.com/), 35 31 bytes
```
((]i.0-.~($@]$!.0,@[)&.#:)#\){]
```
[Try it online!](https://tio.run/##Tcy7CsIwGAXg3af4NcUkkIbEaotBISg4iYNrzaC19X6/W@ir17Q6OJyznI@zzmscJ9BVgIGBAGXjcuiPh4OcELPiwuUZcbRxqlwwHdI6R4qiCU1NTiujHodShYqgTHQk4ob@Y6Qs/TGCtLFnVhMzyaSrU4fSUJUkY9repmEljpYHACK9gIFsFuVTSAD77YaHvyuRgWAQ@HZrF2kx8BolguksmsfJYrlab7a7/eF4Ol@ut/vj@Xrj/AM "J – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 70 bytes
```
f(p,e)=[e[i]|i<-digits(fromdigits(p,256)>>(8*#p%l=#binary(#e)),2^l),i]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVFBTsMwEBQ_sRIhxciRYid2HInmyBMQkmWQ2ybBkKYmTYEgfsKlF8Sb4DVdN82dw8o7uzPjkf3140xvHxp3OHzvhzqWvzd15EiFF6pSVn_a63htGzvsorrfbs6tI4wLXJaRvArdZbsIl7Yz_RiFFcaE3beYWD25_V3cGefaMTIoLpHrbTdAG3gQoDoyimqCbqsVdExjUCOlFM0TgnJBEC18cYJSBrQAmeVqXdXNo316bjfd1r30u2H_-vY-fgTaKymnBDEQZ1ASDDLpdZSlGRe5LM6s2Z6Bs4QrhCSoAJyDmsNZ5LDzSwFEDsW8LfXTxCfyY8-hlE9GPIUTiqbJzKEgEbDOMi_4X_rklBZoE2acn_CEJJhB8okRaI2nB56_7Qg)
Inputs and outputs lists of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁+b€¦JIgbgôC0K<è
```
Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/247671/52210), so make sure to upvote him/her as well!
-1 byte thanks to *@CommandMaster*
Outputs as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//UVOjdtKjpjWHlnl5pielH97ibOBtc3jF///RhuYGOuZmOkamOhaWOmYWOpZmOuaGOqZmOpbmOkZAUTMDHVMDHSNDIAIKGFjqGAJFgHKGhqYgfabGOubGOobGBhA5Q0MdM1MdExOgqlguhcSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisoqAA) or [verify all test cases](https://tio.run/##lU9LTsNADL1KlC1vMZ4Zz0dC6oJdOUI0EgmUUD5tIVAIO7rgABwCgYRYcYL0JrlIcFR6ACTLkt@z33teNmU1nw3rdpJn/etblk/ak6b7bIZ@83JQ9Zuv7n3afddVvf05UseH249hiqEoche1yVGQ8cjIjs2lhKzIs7I6PZud1xfzy6vrm8VydXvX3D@sH5/a53HfK3gHilIMo3c3pI1l50McN5igFaxCcLDhH6KaESJcQHTwBHaIHlpQp8AKWnRJACXegghHxOMdG3gDMmrHEcExrMX@I/EeTdRfllIGzbznZAoMiZBS@gU).
**Explanation:**
```
₁+ # Add 256 to each integer in the first (implicit) input-list
b # Convert them to binary-strings
€¦ # Remove the leading "1" from each
J # Join the list of strings together
I # Push the second input-string
g # Pop and push its length
b # Convert it to binary
g # Pop and push its length
ô # Split the earlier string into parts of that size
C # Convert each inner string from binary to a base-10 integer
0K # Remove all 0s
< # Decrease each by 1 the 1-based indices 0-based
è # Use it to index into the second (implicit) input-string
# (after which the resulting list is output implicitly)
```
[Answer]
# [Python](https://www.python.org), 139 bytes
```
lambda L,E:(n:=len(bin(len(E)))-2)and"".join(["",*E][int("".join(bin(i)[2:].rjust(8,"0")for i in L)[i:i+n],2)]for i in range(0,len(L)*8,n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVFLTsMwEBVbTmF5FYOLYjt2nEpddtcbhCwSmrRuUyekCbS9AkdgUwnBnUAchnH6ASQWWJo8ed6bNzPO81u9beeV3b8Uo9vXri0G-v2pTFfZNEUTOh56djgqc-tlxnoOx4SQASepnWJ8s6ggG2NMr8ZJbGzrnXJObUjMh8lNs-jWracp9jEpqgYZZCyakNgMzbVNKCfJOdukdpZ7PnV9JuRKU0vIYaSPi8-6cQ0KL2YipIgF7qMSilXEBSajERYRV0pEmFx-S0OfolCBMnIhKRIcSlCa3U3zYjY3i2W5slV936zb7uFxs931Tu08R0W1-eUkGUUc3AIIDY6BBiPGRSBVqKO-LApZwLVU4s8ROHTXMIbSFEVwD8FQAkawCHekAqGE4K4Tc1nfTe3STsOYPBhJAQjBhH_SMChRQAfB8VH-s-F9Z-6WKGuqR-u2RYtuVa9R9ZA3yNFlutuiaTX7tYzvtgbv3qTHb5JL6cgDdTw_eQ0Dwmv0BmdRBgcff_J-f8Av)
I suspect it could be shorter, but I'm not well versed in binary manipulation
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
```
lambda s,e,j=''.join:j(map(lambda*a:['',*e][int(j(a),2)],*[iter(j(map('{:08b}'.format,s)))]*len(f'{len(e):b}')))
```
[Try it online!](https://tio.run/##jVHNboMwDL73KXJLgqyKBAIBqU/COIQVVhgEBuynq/bszC7rfZEsy/5@bDnTdb2MPtqa09PWu6E6O7ZADd2J82M3tj7vxOAmsUOBywvOIajLovWr6ISToGUJQdGu9Sx2Kr/loa1@@LEZ58GtsEgpy6CvvWj4jVItc4SxuyGDprHWM3EoCpWGwNIEmMooDLBIl8A4c9XzuW5eLm332g9@nN7mZX3/@Py6fvMSSGgUMI3iGMOiQWxJp3QUmyS12R/rYa/R2eKIxALLsE5RbTBnKWIEJkg0GJpsFXVD2ojaxFHK7EYmwoyhovDBUShJEI5jEvxv@/C@LdL2Whtzr/fKGsDFdwJ1ZH5g@KaZfqAReD485C8 "Python 3 – Try It Online")
Basically the inverse of [my answer to the other question](https://codegolf.stackexchange.com/a/247080/87681).
[Answer]
# JavaScript (ES7), ~~99~~ 95 bytes
Expects `(encoder_characters)(stream)`.
```
(d,v,i=n=0)=>g=a=>d[k=2**n-1]?g(a,n++):(i>7?0:v=v<<8|a.shift(i+=8),j=v>>(i-=n)&k)?d[j-1]+g(a):a
```
[Try it online!](https://tio.run/##jVDLbsIwELz3K6wcKrsxECdx4iAcPgRxCHmRBzEkITzUf0/XtCBUeuhKK8u7M@MZl9EQdXFb7PtJo5J0zOSIEzrQQjbSIjLMZSTDZFVJ@@OjmbD1MscRbUyTzHER@ktrPshhsRCf0bTbFlmPC1MKQks5hCEuJrIh7xVZJqsSqCZQyTwaY9V0qk6ntcpxhg0UbeIkzfJtUVb1rlH7Q9v1x@F0vlwNglfMtyjyPYpYoJtT5NhrQtBshox@m6JMnY23X5LMdlzu@SK4CXBGkQ0iLrQAIVfc@YHPXFtwz3lR@K8pG/wIMOYJigK4@/AWhzPwYaeXHgA5tK1NMD21dA491hjG@LcQd@CEZo51xzCgeLB2XU14znw4FnGFNq06NTo/Ko@7fYfUkLZIr@voekGJyl9SQaibe@vxA3rygtIYm/MH5qf@kNNIARbhP57RGyhj/AI "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BUz0ZUFsLBLƊ}Ḅt0ị
```
A dyadic Link that accepts the code on the left and the alphabet on the right and yields the plain text.
**[Try it online!](https://tio.run/##y0rNyan8/98ptMogKtSt2MfJ51hX7cMdLSUGD3d3////P9rQ3EBHwdxMR8HIVEfBwlJHwcxCR8ESyDc31FEwBdKW5kA5kKQZUKEpEBsZgjBI1ACo3BAkDFJjaGgKMcjUGEgDsaGxAUyNIVCLGVDaxASkIfa/kkJiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVllRIA "Jelly – Try It Online")**
### How?
```
BUz0ZUFsLBLƊ}Ḅt0ị - Link: code (list of integers in [1,255]), alphabet (list)
B - convert code numbers to binary lists
U - reverse each
z0 - transpose with filler zero
Z - transpose
U - reverse each
F - flatten
Ɗ} - last three links as a monad - f(alphabet):
L - length of alphabet
B - to binary list
L - length
s - split flattened bits into slices of that length
Ḅ - convert these from binary
t0 - trim zeros
ị - index into the alphabet
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, 26 bytes
```
b@DFBFI(STB_+E8MJa)<>#TB#b
```
Takes a list and a string as command-line arguments. The string may need to be quoted twice, once for the shell and once for Pip. Or, add the `-r` flag and supply the list and string (as a double-quoted Pip string literal) on stdin. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuha7khxc3JzcPDWCQ5zitV0tfL0SNW3slEOclJMgCqDqbjZFK0UbmhtYm5tZG5laW1ham1lYW5pZmxtam5pZW5pbGwFFzQysTQ2sjQyBCChgYGltCBQByhkamoL0mRpbmxtbGxobQOQMDa3NTK1NTICqYpV0FJRilBQSk5JTUtPSMzKzsnNy8_ILCouKS0rLyisqq2KU4E4GAA)
### Explanation
The `-x` flag evaluates both arguments. Then:
```
b@DFBFI(STB_+E8MJa)<>#TB#b
a First argument (list of numbers)
MJ Map this function and join the results into one string:
_ The argument
+E8 Plus 2 to the 8th power
TB Converted to binary
S Without the first character
I.e. convert to binary with leading zeros as necessary
( )<> Group that string into chunks of this size:
#b Length of second argument (encoder string)
TB To binary
# Length of that
FI Filter out results that are falsey (here, equal to 0)
FB Convert each remaining value from binary
D Decrement (because Pip is 0-indexed)
b@ Use as an index into b
```
The result is a list of characters, which by default is joined together and autoprinted.
[Answer]
## Ignores the transformation process and just decodes
# [Burlesque](https://github.com/FMNSSun/Burlesque), 45 bytes
```
id[-sab2L[PpqsvZ]vv{b28'0P[}\mpPco)b2:nzqgv\m
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPo/MyVatzgxycgnOqCgsLgsKrasrDrJyELdICC6Nia3ICA5XzPJyCqvqjC9LCb3f214zv9qQ2NzBUMTIDarVVAyM7I0VuKqNjQ3UDA3UzC0BCJTBWMjoIxCYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZZUSAA "Burlesque – Try It Online")
```
id # Indices
[- # Drop first
sa # Non-destructive length
b2L[Pp # Store length of longest binary in temp stack
qsvZ] # Zip with ids and save to global map
vv # Drop empty list
{b28'0P[}\m # Map to binary, pad to 8, concat
pPco # Get from temp stack, chunks of
)b2:nz # Map from binary, filter for nonzero
qgv\m # Get each value, concat
```
## Follows the transformation process
# [Burlesque](https://github.com/FMNSSun/Burlesque), 61 bytes
```
id[-)b2J)L[>]Js1{'0P[}j+]m[qsvZ]vv{b28'0P[}\mg1cof{b2nz}qgv\m
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPo/MyVaVzPJyEvTJ9ou1qvYsFrdICC6Nks7Nje6sLgsKrasrDrJyAIsGJObbpicnwbk51XVFqaXxeT@rw3P@V9taGyuYGgCxGa1CkpmRpbGSlzVhuYGCuZmCoaWQGSqYGwElFFITEpOSU1Lz8jMys7JzcsvKCwqLiktK6@orFICAA "Burlesque – Try It Online")
Pretty sure this has some golfing to be done further, but it works.
```
id # Get indices of string
[- # Drop 0 (string ends with null so this is ok)
)b2 # Map to binary
J)L[>] # Get length of longest
Js1 # Save copy
{
'0P[ # Pad left with 0s
}
j+] # Append length of longest
m[ # Apply to each
qsvZ] # Zip binary with encoder and save to global map
vv # Drop resulting empty list (encoded string now top of stack)
{
b2 # To binary
8'0P[ # Pad to 8 with zeros
}\m # Map concat
g1 # Get max length
co # Chunks of
f{ # Filter
b2nz # Decimal value of is non-zero
}
qgv\m # Get vals from global map and concat
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~17~~ 16 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
@♠+àm╞y\£à£/åç(§
```
-1 byte implicitly thanks to *@CommandMaster*, applying the same change as in my 05AB1E answer
I/O as a list of characters.
[Try it online.](https://tio.run/##xc9JTsNAEAXQPcfoFRJfoqvb1cOOexgLhSEJEBOGMJh7sGCDLEUo97BvkouYb7LIESL5Se5fXeqqerKaz5aL6TCcbb/bk76tt18/zXm37ttufdr/9pvjbjM0Q2kuDMyELumKrumGpjSjOd3SHd3Tgmp6oCU90hM90wut6JXe6J0@qKFPU6GUaBEDJPNTeFcdlUZYdOSpIKVAkRLl/0YVOIvCIgUUaew7xOBOkTJCQg6IAg3IEY5psFALxyGFgeV@TFgT0bFPPaKHeLuriSAoioK3xk32W4wv2bTL@O9U93Wek4KDVH8)
Minor note: the spaces in the input-lists are replaced with `_`, because there is a bug in MathGolf when reading a list that contains spaces (it reads them as `", "` instead of `" "`)..
**Explanation:**
```
@ # Reverse triple swap, so the stack now contains two encoder lists and
# the integer-list
♠+ # Add 256 to each integer
à # Convert all integers in the list to binary-strings
m╞ # Remove the leading "1" from each
y # Join it to a single string
\ # Swap so an encoder-list is at the top
£ # Pop and push its length
à # Convert it to a binary string
£ # Pop and push its length again
/ # Split the earlier string into parts of that size
å # Convert each from a binary-string back to an integer
ç # Remove all 0s with a falsey filter
( # Decrease each to make the 1-based indices 0-based
§ # Index it into the remaining encode-list
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 25 bytes
```
⁻⭆⪪⭆θ◧⍘ι !⁸L↨Lη²§⁺ψη⍘ι !ψ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjenBxRl5pVo-GbmlRZrBJcAOem-iQUawQU5mSVI_EIdhYDEFJ_UtBINp8TiVIiERqaOgpKCopKmjoKFJpDwSc1LL8kAK9CAsjOAwkaaIEnHEs-8lNQKjYAcoEWVOgogGSxGgZRWampaLylOSi6GOnJ5tJJuWY5S7E3z6GhDcwMdBXMzHQVDSxA21VEwNooF6U1MSk5JTUvPyMzKzsnNyy8oLCouKS0rr6isUoqFGAMA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
θ Input array
⭆ Map over values and join
ι Current value
⍘ Custom base conversion using
! Literal string ` !`
◧ Right-padded to length
⁸ Literal integer `8`
⪪ Split into substrings of length
η Encoder characters
L Length
↨ Converted to base
² Literal integer `2`
L Length
⭆ Map over values and join
ψ Predefined variable null
⁺ Concatenated with
η Encoder characters
§ Indexed by
ι Current value
⍘ Custom base conversion using
! Literal string ` !`
⁻ Remove occurrences of
ψ Predefined variable null character
Implicitly print
```
This approach turned out to be shorter than a numerical approach based on base-256 conversion and custom string base conversion.
23 bytes using the older version of Charcoal on TIO:
```
⭆⪪⭆θ◧⍘ι !⁸L↨Lη²§⁺ψη⍘ι !
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQX5GQi8wt1FAISU3xS00o0nBKLUyESGpk6CkoKikqaOgoWmkDCJzUvvSQDrEADys4AChtpgiQdSzzzUlIrNAJySos1KnUUQDJYjAIC6///o6MNzQ10FMzNdBQMLUHYVEfB2CgWpCYxKTklNS09IzMrOyc3L7@gsKi4pLSsvKKySin2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The version of Charcoal on TIO special-cases `AtIndex` to return the empty string instead of the null character, even when indexing into an array. Most of this time that behaviour is incredibly annoying but here it's actually helpful. Unfortunately that version of Charcoal does suffer from a bug in `BaseString` so it doesn't support zero values in the input, which can happen on rare occasion.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~54~~ ~~53~~ ~~47~~ 46 bytes
```
~{256|{2base}:b~1>}%[]*\:a,b,/{b.{(a=}and}%""+
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v67ayNSsptooKbE4tdYqqc7QrlY1OlYrxipRJ0lHvzpJr1oj0bY2MS@lVlVJSfv/fyWFxKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyiolrmhDcwMFczMFQ0sgMlUwNooFAA "GolfScript – Try It Online")
This is my second GolfScript submission, so I might be able to improve it. I haven't decided on the best way to write explanations for these so this time I'll leave a commented version:
```
~ # Evaluate the input; the codepoint list is on top of the stack.
{ # Open a block (like anonymous function) to run on each codepoint:
256| # Bitwise or with 256 to set the ninth bit
{2base} # A block which calls `2 base` (convert to/from base 2).
:b # Assign the block to variable b.
~ # and call it on the codepoint.
1> # Slice from index 1 to the end, removing the extra 9 bit.
}% # Close this block and call it on each codepoint (map).
[]* # Flatten the list by joining it on nothing.
\:a # Swap and assign the second input,
# the encoder alphabet, to variable a.
, # Push the length of a.
b # Convert it to binary.
, # The length of the digit list.
/ # Split the codepoint list into chunks of this size.
{ # Open a block to run on each chunk:
b. # Convert the chunk from binary to decimal.
{ # A block taking a 1-based index:
(a= # Decrement and 0-based index into a.
} # This returns a number, so we have to coerce to string later.
and # If the number isn't zero, run the block.
}% # Run this block on each chunk (map).
""+ # Append an empty string to coerce the list.
```
] |
[Question]
[
Rubik's Clock is a round(ish) puzzle with two flat sides. On each side, front and back, there are 9 clock faces, arranged on a 3x3 grid. In addition, there are 4 pegs (switches) in between the clock faces, and they can be set to protrude either from the front or the back. Lastly, there are 4 dials on the edge of the puzzle. You can rotate them to manipulate the 4 clocks in the corners, on the front and the back simultaneously. Here's a schematic.
[](https://i.stack.imgur.com/Zn00G.png)
The switches each have 4 clocks around them, and they act as a lock to those 4 clocks. If a switch is pressed in, any movement of any of the surrounding clocks is synchronised with the three others. If the switch is not pressed in, they move independently. However, in that case, it can be seen as pressed in from the other side. Therefore, the 4 clocks around the switch on the other side of the puzzle are synchronised. The switches thus always lock 4 clocks together, either on the front or the back.
For consistency in clockwiseness and switch settings, we define one side as the front and the other as the back. As seen from the front, the switches are set to 1 if they are pressed in, and 0 if they are not pressed in.
The four corner clocks are inversely synchronised between the front and the back. If you were to turn a dial clockwise, the clock on the backside in the same position would turn counter-clockwise. Therefore, there is a total of 14 independent clocks: 4 corners, 5 independent on the front and 5 independent on the back.
Consider an example where all clocks are set to 0 (or 12), switch 0 is set to 1 and the other switches are set to 0. If we turn dial 0 to position 2, the following happens:
* Front clocks 1, 3 and 4 are synchronised to clock 0 and all move to position 2
* Back clock 0 is inversly synchronised to clock 0 and moves to position 10 (= -2 mod 12)
Now consider the same example, but instead both switches 0 and 3 are set to 1, whereas switches 1 and 2 are set to 0. If we turn dial 0 to position 2 again, the following happens:
* Front clocks 1, 3 and 4 are synchronised to clock 0 and all move to position 2
* Front clocks 5, 7 and 8 are synchronised to clock 4 and all move to position 2
* Back clock 0 is inversely synchronised to clock 0 and moves to position 10 (= -2 mod 12)
* Back clock 8 is inversely synchronised to clock 8 and moves to position 10 (= -2 mod 12)
The aim of the puzzle, given a scrambled set of clocks, is to set all clocks to 0. You do this by flipping switches and turning dials appropriately. This is also the task of the challenge.
# The challenge
Given a valid setting for both the front and back clocks, output a sequence of switch settings and dial turns which set all clocks to 0.
# Rules
* Input and output are flexible to the extent permitted by the default rules, provided that they unambiguously describe the clock and the required sequence.
+ You can redefine the indexing.
+ If convenient, you can take only the 14 unique clock faces as input.
+ Clocks on the front must always respond directly (positively) to dial turns.
+ Clocks on the back must always respond inversely to dial turns.
* Consider all switches set to 0 at the start of the solve.
* The final switch settings can be nonzero, as long as all clocks are solved.
* Your program must finish in a reasonable amount of time: no brute-forcing.
# Examples
```
Example input: [9, 9, 0, 9, 9, 0, 9, 9, 0], [3, 0, 0, 0, 0, 0, 3, 0, 0]
Example output: [0, 2, (2, 3)]
| | +---- Dial turn
+--+---------- Switch flips
Step-by-step:
Current state
Switches: 0 0 0 0
Front: Back:
9 9 0 | 3 0 0
9 9 0 | 0 0 0
9 9 0 | 3 0 0
Flipping switch 0
Flipping switch 2
Turning dial 2; 3 times
Current state
Switches: 1 0 1 0
Front: Back:
0 0 0 | 0 0 0
0 0 0 | 0 0 0
0 0 0 | 0 0 0
```
```
Example input: [11, 0, 11, 8, 8, 8, 8, 8, 8], [1, 1, 1, 1, 1, 1, 4, 0, 4]
Example output: [2, 3, (2, 4), (1, 1)]
Step-by-step:
Current state
Switches: 0 0 0 0
Front: Back:
11 0 11 | 1 1 1
8 8 8 | 1 1 1
8 8 8 | 4 0 4
Flipping switch 2
Flipping switch 3
Turning dial 2; 4 times
Current state
Switches: 0 0 1 1
Front: Back:
11 0 11 | 1 1 1
0 0 0 | 1 1 1
0 0 0 | 0 0 0
Turning dial 1; 1 times
Current state
Switches: 0 0 1 1
Front: Back:
0 0 0 | 0 0 0
0 0 0 | 0 0 0
0 0 0 | 0 0 0
```
```
Example input: [3, 11, 0, 11, 11, 5, 2, 11, 1], [9, 8, 0, 8, 8, 4, 10, 8, 11]
Example output: [1, 3, (2, 9), (0, 7), 0, 1, 2, 3, (0, 6), 2, 3, (3, 7), 0, 1, 2, 3, (0, 4)]
Step-by-step:
Current state
Switches: 0 0 0 0
Front: Back:
3 11 0 | 9 8 0
11 11 5 | 8 8 4
2 11 1 | 10 8 11
Flipping switch 1
Flipping switch 3
Turning dial 2; 9 times
Current state
Switches: 0 1 0 1
Front: Back:
0 11 0 | 0 11 0
11 11 5 | 11 11 4
11 11 1 | 1 11 11
Turning dial 0; 7 times
Current state
Switches: 0 1 0 1
Front: Back:
7 11 0 | 5 4 0
11 11 5 | 4 4 4
6 11 1 | 6 4 11
Flipping switch 0
Flipping switch 1
Flipping switch 2
Flipping switch 3
Turning dial 0; 6 times
Current state
Switches: 1 0 1 0
Front: Back:
1 5 0 | 11 4 0
5 5 5 | 4 4 4
0 5 1 | 0 4 11
Flipping switch 2
Flipping switch 3
Turning dial 3; 7 times
Current state
Switches: 1 0 0 1
Front: Back:
8 0 0 | 4 4 0
0 0 0 | 4 4 4
0 0 8 | 0 4 4
Flipping switch 0
Flipping switch 1
Flipping switch 2
Flipping switch 3
Turning dial 0; 4 times
Current state
Switches: 0 1 1 0
Front: Back:
0 0 0 | 0 0 0
0 0 0 | 0 0 0
0 0 0 | 0 0 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~203~~ ~~202~~ ~~193~~ 192 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•iN yɯzoи!••)i‰â™â•S£vy,.µNUDX4-5ÖiX9÷©èDÅs12αÐV0s‚,+®ǝD®_èDŽ8SSDUèY-Xǝ®_ǝ12%ë[DX5@è4•EβQÑ´—•Xè‚èË#εD•3bž§j’λ¬Ā%úÍp₄ÞÞ5öćzz…õôty‘[z\Ä≠Îβ¥…uи•S•Eÿ>nºØ1ǦƒÎÖ•S£2äNèXè©èN·<-12%®ǝ}¼}•I¤Ðcû®•X辂,
```
Input is similar as the example of the challenge. A pair of lists, with the first list being the front-clocks and the second being the back-clocks.
Every two lines of the output are a step. The first line indicates the 0-based indices of the four knobs that are upwards on the front; the first integer on the second line indicates the 0-based index of the wheel we're turning, and the second integer on the second line indicates how many times we turn it clockwise.
For example, this step:
```
01
[3,6]
```
means we have the top-left and top-right knobs up on the front, and we then turn the bottom-right 6 times clockwise.
It will also output no-op steps. If the second line of a step is `[x,0]` it means nothing has changed that step, since it was already correct. (And it might potentially output `[x,12]` in the three steps where it puts all relevant clocks on 12 o'clock when they were already on 12 o'clock. If this is not allowed, `12%` can be added after the `α` (+3 bytes).)
**[Try it online](https://tio.run/##JY/RSgJREIZfpQgvot1wVwWFiC62i26EEGNjk9DowggNrMAFYQlDJBKLEAuUMLONwko0Rctgfs27xWc4L7KdTc5wmP@fYWa@ZCoai@/bNjNq8eBcGnl605PT3jzXPBbjzHhHjWVrcGSIHk7TwjJ1gmFF9Yo@lOJqAF16hqngPCXJ1geKW@4UM@6EJWpOKgo1d3lt/O0PhZQwzG1RnVS4N6lIsgsvmqL61mB6@eh1q7WJK2oz44YrFSafARMXC1ZH4YYnNh7S0wEzbq0BvY4MF/q4PGJnWVRR9eFzlNN1ZjTQQfs4zYyypu8gy/L3KFgteuSVk2nPAXA24Wc1QX2UJeSo8XuNAkozNhn1IEy@2wEKUndF5Fc6GBn6yvCWDaqjuIcBNWcn0tABtW1N8wiSJLidj4dPkP@ziKAFBD@3/fx5BclJJCkSsUUxkRQPo3r6Dw) or [try it online with debug-lines](https://tio.run/##lVFRSxRRFH6fXzFd8SG6E826C2tUEzQJvSzkokyMS@wuU01uc5eZu8kOCINsiEhiIWLBSmxmE8Vm4qZoGdyj7tvgb7h/ZLzXFXzxJe7h8p3vcM8533dJUK64TpryqOMW1CYssJ8hOd27JnIR110ebUGHtzog0yL7/FpBDxq@73hUrdZIdVoNaJk6t1Vk3FXQmE8EP@2RSqA26pJElNS1mvOMqhL47vMXVK0QSsmrAXuBzwtoqFmEGCtonIieLvFkA@Um6xUmTCur5WDVtUZhl32D2IQ3gZ5JfsHypHI5AhkGUmnD94LBbjNu4CCs3GDdfttk3afi3fHffLFoTkD8RLP6bcH123pmGL7bppW7D3FWiHyYbD@Gd2yHRysisyDm0UeIYXEo6ZmCGKkcH7KvL3n0ITlgP46iYdiHt3U@14J1WM/B76P5MOTRJvRghzZ5tGaHU9DiC59gKdlmX0SlcbonrZST4N89j@3Dmg7zbPPkPSzB6sDlDGwUIBazpdgC272jiS2ljFn2Z1b5P1NFx0dsA5arcMC6A0UQG7BlsMMr7SqhMdcr1y4/FqepbY9gXce35CUihzPnqITtUZwXdF6cLNYl0PVSKdU0j2i1ctg8Aw) or [verify all test cases with debug-lines](https://tio.run/##lVHva9NAGP6ev@K8sQ/iRZauhU7UCMbBvlRcmVRikLZUjau50lw2UiiEURlDHFNkTKFD6pwRpc6xdmPTCfdu9lvZ35B/pN6lg@nwi9zD3fM@b96foW6@YJcGc3jKqXjsCsK6T3hXV/Btjw0F4g@ioGVnkA9L/GuNnuxdELbARTsKtqAVNVogzSx/P6fgm161WnIYKpZpcRa5LM9KMuk1BU9WqdBnHVpwkVeRIma0opZLDxmSpGo/esxQgTJGnw7VUx478IifhZAoeJqKnDZ1ZALlMu9kZoxcUk3Bqp2bgF3@CUIDnrlaov8NVu4qZyWwrmPEvKrjDnubt90SJsol3u41Dd5@IOKOf6SzWWMGwntqrtcUWq@pJUbhs2nkUjcgTIohb/W378BLvhMFr4WVgzAK3kIIz0f6HUMI44XjQ/7xSRS86R/wL0fBKOzDi0q00IB1WE9B92ixVouCTejADvOjYM2s3YdGtPQOlvvb/IPweCd7cpWyEvy87vB9WNNgkW/@egXLsDrccgI2MhCK2nLYDN@9qoou5Rh1/r2u/N9SRcYpvgErRTjg7eFEEOqwpfPDf66rXseTtpMvn/1ZMuBdMjBNc4IggbH4/otYBJnjsfAnThVLeJFpalpsyid9DjJcyOeQjL9PynBTZBeBY/ISSJFEzCwiWkoLOS1OkmiSaJplWQNVdahaztf83w).**
### Explanation:
Let me start with a general explanation of the 15 steps I do to solve the Rubik's Clock.
In the pictures below:
* the orange knobs are the ones that are upward for that face;
* the purple stars indicate that any of those wheels can be turned for this step;
* the red circled clocks should all face the same direction after this step.
Step 1-4, done on the front:
[](https://i.stack.imgur.com/iVry2.png)
In step 1 we have the bottom-left knob up and the other three knobs down. We then turn the bottom-left wheel until the direction of the center is facing the same way as the direction of the top-middle clock.
In step 2 we do the same with the top-left knob and wheel, until the direction of both the center AND top-middle clocks are facing the same way as the direction of the middle-right clock.
Etc.
Then in step 5, we put all four of the knobs upwards, and rotate until the five clocks that form a + are facing 12 o'clock.
For steps 6-10 we basically do the same for the backside, after we've turned the clock upside down. (In our code below we of course only use front knobs and wheel-turns, but during an irl solve you would turn the clock upside down to repeat these steps, and also finish it with the five steps below while still looking at the backside.)
After these 10 steps, the clocks that form a + on both the front and back should all face the same way, with the ones on the back facing 12 o'clock.
After that we do four more steps to fix the corners:
[](https://i.stack.imgur.com/7NY9Z.png)
After these 14 steps, all clocks on the backside (you would still be looking at irl) are now facing the same direction; all clocks that form a + on the frontside are already at 12 o'clock; and the four corner-clocks on the frontside should also all be facing the same direction.
We can now put all the knobs up at the backside, and rotate any of the four wheels to put all clocks at 12 o'clock and finish the solve.
**As for the actual code:**
```
•iN yɯzoи!• # Push compressed integer 201010123012023123233210
•)i‰â™â• # Push compressed integer 111243332011110
S # Convert it to a list of digits as well
£ # Convert the first into parts of the second:
# [2,0,1,"01","0123","012","023",123,23,"",3,2,1,0,""]
# (these indicate the front-knobs that are up)
vy # Foreach over these:
, # Pop and print it with trailing newline
.µ # Reset the counter variable to 0
NU # Save the 0-based loop-index in variable `X`
D # Duplicate the current clock-state
X4-5Öi # If the loop-index is 4, 9, or 14 (index-4 is divisible by 5):
# (these are the steps to put all relevant clocks to 12 o'clock)
X9÷ # Integer-divide the loop-index by 9
# (0 for index 4; 1 for indices 9 and 14)
© # Store this in variable `®` (without popping)
è # Use it to index into the clock-state
D # Duplicate this list
Ås # Pop and push the center value
12α # Pop and push its absolute difference with 12
Ð # Triplicate this abs(center-12)
V # Pop and store one copy in variable `Y`
0s‚ # Pair another one with leading 0
# (since it doesn't matter which wheel we turn)
, # Pop and print it with trailing newline
+ # Add the remaining third one to each clock in the list
®ǝ # Replace the list of clocks at X//9
D # Duplicate the new clock-state
®_è # Get the opposite face (using X//9==0)
D # Duplicate this list
Ž8S # Push compressed integer 2068
S # Convert it to a list of digits
DU # Store a copy in variable `X`
è # Get the clocks at these indices (the corners)
Y- # Decrease them by the abs(center-12)
Xǝ # Insert them back at the corners
®_ǝ # Replace the list of clocks at X//9==0
12% # Modulo-12
ë # Else (this is a regular step):
[ # Loop indefinitely:
D # Duplicate the clock-state
X5@ # X>=5 check
è # Use that to index into the clock-state
# (the front face for the first 5 steps;
# the back face for the remaining steps)
•EβQÑ´—• # Push compressed integer 15370135708620
Xè # Index the loop-index into that
4 ‚ # Pair it with 4 (center-index)
è # Get the clock-values at those positions
Ë # If they are the same clock-value
# # Stop the infinite loop
ε # Map over both faces:
D # Duplicate the current clock-list
•3bž§j’λ¬Ā%úÍp₄ÞÞ5öćzz…õôty‘[z\Ä≠Îβ¥…uи•
# Push compressed integer 346701341245012345830020260280682686020245781245013401234501234567012345780134567812345678
S # Convert it to a list of digits
•Eÿ>nºØ1ǦƒÎÖ•
# Push compressed integer 4446011120333311120444608888
S # Convert it to a list of digits as well
£ # Split the first into parts of the second:
2ä # Split it into two equal-sized parts
# [[[3,4,6,7],[0,1,3,4],[1,2,4,5],[0,1,2,3,4,5],[],[8],[3],[0],[0,2],[],[0,2,6],[0,2,8],[0,6,8],[2,6,8]],
# [[6],[0],[2],[0,2],[],[4,5,7,8],[1,2,4,5],[0,1,3,4],[0,1,2,3,4,5],[],[0,1,2,3,4,5,6,7],[0,1,2,3,4,5,7,8],[0,1,3,4,5,6,7,8],[1,2,3,4,5,6,7,8]]]
Nè # Index the map-index into it
Xè # Index loop-index `X` into it
© # Store it in variable `®` (without popping)
è # Index it into the clock-list
N # Push the map-index
·< # Double it, and decrease by 1
# (-1 for index 0; 1 for index 1)
- # Decrease the clock-values by that
# (so it'll increase the front and decrease the back)
12% # Modulo-12 each new clock value
®ǝ # Insert them back into the clock-list at positions `®`
} # Close the map
¼ # Increase the counter variable by 1
} # Close the infinite loop
•I¤Ðcû®• # Push compressed integer 20100310100123
Xè # Index the loop-index `X` into it
¾‚ # Pair it with the counter variable
, # Pop and print it with trailing newline
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed integers work.
In the time I wrote this program and answer I probably could have solved multiple hundreds of Rubik's Clocks irl, haha.. xD Solving a Rubik's Clock irl is easy, but translating that to a solver-program isn't as straight-forward as I hoped it would be when I started writing it.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 117 bytes
```
§≔θ⁰⁺§θ⁰↨§θ⁴±¹F⁴«≔§θI§5731ιζ≔⁺§θI§2860ι↨ζ±¹εF²«IE⁴∧κ⁼¹﹪⁻λι⁴I⟦⟦ι﹪⎇κε±ε¹²⟧⟧F²«IE⁴⁼‹λ﹪⁻μι⁴κI⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§§θ⁴κ§ζκ¹²
```
[Try it online!](https://tio.run/##dZLBT4MwFMbP46942alNarIy5pZ4QuPBROYO3giHZtTZ0IFrwShmfzu2ZTAgSkgoL@/7vt97sH9nal8w2TSh1uKQh@VTnvIvdCKwILCTlUbDEiZwzzQf1gJT2/IDKzmi2Fx33luhAAUYfrxZazpsf2C67N/nq/WSzgkIoyNQG22nmCaPZf7mdtHKLjz1iIEAt1aOw3ccs50SeYmcS8Q@UEAgzFOUEXg8VUxqRAlERVrJAkUiN9HSutvhcDvTyCGORd/@ylXO1Le14j0EtwzUx0nSaockf6BcGJ65dsEjkGMPQiDrWP6FEUeu0YuyNNd9EOggjXm3w9raGaELsbvYFiWySV3D5BNnGE/EeDLk2TP3uWnieEkgpmajm8T9Rf35elgZU/P0BzWaJM3Np/wF "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of nine clocks, with a single value for the corner clocks and an array of two values for the other clocks, and outputs lists of six integers: the first four are the peg states clockwise from top left, the fifth is the dial to rotate as an integer (counting clockwise with top left as `0`) and the sixth is the (clockwise) amount, from `0` (unnecessary moves are not removed) to `11`. Explanation:
```
§≔θ⁰⁺§θ⁰↨§θ⁴±¹
```
The first set of rotations will correct the centre clocks by rotating the top left clock, so correct its value here.
```
F⁴«
```
Loop over each dial.
```
≔§θI§5731ιζ
```
Get the pair of clocks three clocks clockwise from that dial.
```
≔⁺§θI§2860ι↨ζ±¹ε
```
The clock two clocks clockwise (i.e. the next dial's clock) will be rotated by the difference of those clocks so get the final value here.
```
F²«
```
Loop over a) rotating the other clocks to match the next corner or rotating all the clocks back to noon, or b) fixing the clock three clocks clockwise or its reverse.
```
IE⁴∧κ⁼¹﹪⁻λι⁴I⟦⟦ι﹪⎇κε±ε¹²⟧⟧
```
Enable either all the peg except the next corner or all the pegs, and then rotate the current dial appropriately. These two rotations fix that clock.
```
F²«
```
Loop over the clock three clocks clockwise and its reverse.
```
IE⁴⁼‹λ﹪⁻μι⁴κI⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§§θ⁴κ§ζκ¹²
```
Either enable only the dial's peg, or both the dial's peg and the next dial's peg, or for the reverse clock all the pegs except those pegs, then rotate the current dial appropriately, including adjusting for the centre dial on the first rotation.
The solution basically relies on two combinations:
* If you rotate a dial with just its peg toggled, and then inverse rotate the dial with its peg and the next peg toggled, you end up only rotating the second and third clocks clockwise from the dial. (For the very first rotation, take the opportunity to fix the centre clock as well, although this also rotates the top left clock.)
* If you rotate any dial with no pegs toggled, then inverse rotate any other dial while a dial has its peg toggled, you end up only rotating that dial's clock.
By accepting the clocks in a custom order it's possible to reduce the byte count to 105:
```
≔⊟θη⊞θ⁺⊟θ↨η±¹F⁴«≔§θ⊗ιζ≔⁺§θ⊕⊗ι↨ζ±¹εF²«IE⁴∧κ⁼¹﹪⁻λι⁴I⟦⟦ι﹪⎇κε±ε¹²⟧⟧F²«IE⁴⁼‹λ﹪⁻μι⁴κI⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§ηκ§ζκ¹²
```
[Try it online!](https://tio.run/##dZA9b8IwEIZn8ituPEuu1FAqVWJKPwakQjN0izK45EosjA12UrVU/PbUDiQNqLU8nOT34/EtS2GXRqimSZyTK42p2eKOcSjZNEprV@KOQ6pq1z/cC0dYcljQSlSEMfNnGr0bCzhh8B2NTkFJNdMFfQb/o6nfFBUomffvvbrTtMED4UwvLW1IV148MHWt@7NWDhSi2uZx2zxKrdQVPghX4VxsccIh0QWuOTztaqEcxhzmpqiVwbnUvlpxkD5nwtjxF2cJWSZ7@StZLexXiKIeggJDPGZ5fvQOSf5AOTE8k2uLz0A2PQiHdcfyL4zckMMXG2h@98Ghg/Th3U73Ic4b25Kwi4WpMDR1grLtuzCwi48dIn8PTZNl2a2HzDlcc8hiv807P8eDeTyYb/o5z5urD/UD "Charcoal – Try It Online") Link is to verbose version of code. Takes clocks in the order right, top right, bottom, bottom right, left, bottom left, top, top left, centre.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 576 bytes
```
(f,b,o=[],s=[])=>('012;301,13;103,01;007,2;005,13;00,3;311,31;113,10;017,2;015,13;01,012;008,31;202,10;300,02;106,2;00'.split`,`.map(S=>((n=>o.push(...[...n].map(i=>(s[i]=!s[i],i))))((T=S.split`;`)[0]),((d,w,z)=>{while((x=+w?b:f)[4]!=(z>=0?x[z]:0)){((d,q=new Set(),W=new Set())=>{[...'0268'].map((C,i,_,E=[...['0134','1254','3674','5784'][i]])=>{if(!s[d]&&!s[i]){W.add(C);E.map(j=>q.add(j))}else if(s[d]&&s[i]){q.add(C);E.map(j=>W.add(j))}});q.forEach(i=>f[i]=(f[i]+1)%12);W.forEach(i=>b[i]=(b[i]+11)%12);o.push(...(l=o.pop()).pop?(l[1]++,[l]):[l,[d,1]])})(d)}})(...T[1]))),o)
```
[Try it online!](https://tio.run/##ZVLbjtowEH3nK7wP3YzFNLJjLimW4WGF9gNYiQfLKglJSlCawIaWFYhvp@MEdSs1imfiOWeumX3yO2m37@Xh9LVusvy@ber2xF7NHQpMsTHWYUuCmzkEQkZaCYlSaSkUCqmFmGJEcuxtQqDSSkpUUkupUAotZIfLHpfoIwgRe0YkIs9Q5CUiijfpAgVhe6jK0wY34c/kACtKC7WZN@HhV7uDMAwtndp1YElga0tnnrzEktMD8GZWjxh6w61wHAEyPOOFWried2WVA3yY4XmRzgpuR@7JwGVuxOLDXtxMcH719KOp8zNb5SfguP789iF8AYGIJnHQVwEvWOJ3XBoPWJqRGgUYyGjslZpMvRpP41HgqEg/x2tZAFWcuefnrnB@XYdJlsEL18su4t7Mj51lz/ktr9qckUfv0POP//HXf/k3ro9h0bwvk@3OT6jwAwIvh5J/kRHX63/htIPTDn7gn7OGytClOVDjXi2gstINh2grx2e2QpuhpJZuHDKf2Lu8EYN@Azb8rgcDSzvkmGHWKmS0GEz0yp8xsuhxc8jsN2Rxh8fdOyJzf5GUQg/8WjZVHlbND3il1WQp5/r@Bw "JavaScript (Node.js) – Try It Online")
This answer adapts the "beginner" method of solving clock to code by walking through the same static steps. It is by no means efficient (since it often generates unnecessary switch toggles) but it is fast and simple.
Ungolfed:
```
const ungolfed = (f, b) => {
// Output steps
const o = [];
// Switches
const s = [0,0,0,0];
// *t*oggle switch(es)
// Called like t(0,1,2) with variadic argument count
const t = (...n) => o.push(...n.map(i=>{
console.log(`${s[i]?'Unp':'P'}ress ${i}`);
s[i] = !s[i];
return i;
}));
// const - corner clocks (for pressed switch dial turns)
const c = [0,2,6,8];
// const - corner/edge clocks (for unpressed switch dial turns)
const e = [[0,1,3],[1,2,5],[3,6,7],[5,7,8]];
// *r*otate a dial clockwise
// Called like r(3)
const r = d => {
// Using sets for deduplication
// Front clocks that will turn
let q = new Set();
// Back clocks that will turn
let w = new Set();
for (let i = 0; i < 4; i++) {
if (!s[d]) {
if (!s[i]) {
w.add(c[i]);
q.add(4);
e[i].map(j=>q.add(j));
}
} else {
if (s[i]) {
q.add(c[i]);
w.add(4);
e[i].map(j=>w.add(j));
}
}
}
q.forEach(i=>f[i]=(f[i]+1)%12);
w.forEach(i=>b[i]=(b[i]+11)%12);
let l = o.pop();
if (l.push) {
l[1]++;
} else {
o.push(l);
l = [d,1];
}
o.push(l);
};
// rotate a dial *u*ntil
// d - Dial to rotate
// W - truthy -> front, falsy -> back
// y - First index to check (in golfed version, always 4)
// z - Second index, or if -1, use 0 (pointing up) (in golfed version, use undefined in place of -1)
const u = (d,W,y,z) => {
x=W?b:f;
while (x[y]!=(!~z?0:x[z])) {
r(d);
x=W?b:f;
console.log(`Turn d${d} so c${W?'f':'b'}${y} ${!~z?"points up":`= c${W?'f':'b'}${z}`}`,f,b);
}
}
// Actual steps to solve (starting from all unpressed switches)
t(0,1,2);
u(3,0,4,1);
t(1,3);
u(1,0,4,3);
t(0,1);
u(0,0,4,7);
t(2);
u(0,0,4,5);
t(1,3);
u(0,0,4,-1);
t(3);
u(3,1,4,1);
t(3,1);
u(1,1,4,3);
t(1,0);
u(0,1,4,7);
t(2);
u(0,1,4,5);
t(1,3);
u(0,1,4,-1);
t(0,1,2);
u(0,0,4,8);
t(3,1);
u(2,0,4,2);
t(1,0);
u(3,0,4,0);
t(0,2);
u(1,0,4,6);
t(2);
u(0,0,4,-1);
return o;
};
```
] |
[Question]
[
This challenge will have give you a positive integer \$n\$ and ask you to output \$t(n)\$, the number of triangles (up to congruence) satisfying the three conditions:
* The triangles have perimeter of 1,
* the triangles have side lengths \$\displaystyle\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}\$, and \$\displaystyle\frac{a\_3}{b\_3}\$, and
* when written in lowest terms, \$\max \{b\_1, b\_2, b\_3\} = n\$.
### Examples
For \$n = 2\$, there are no such triangles, so \$t(2) = 0\$.
For \$n = 3\$, there is one such triangle, so \$t(3) = 1\$:
$$
\frac{a\_1}{b\_1} = \frac{a\_2}{b\_2} = \frac{a\_3}{b\_3} = \frac 1 3
$$
For \$n = 4\$, there are no such triangles, so \$t(4) = 0\$.
For \$n = 5\$, there is one such triangle, so \$t(5) = 1\$:
$$
\left(\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}, \frac{a\_3}{b\_3}\right) =
\left(\frac 1 5, \frac 2 5, \frac 2 5\right)
$$
For \$n = 6\$, there are no such triangles, so \$t(6) = 0\$.
For \$n = 7\$, there are two such triangles, so \$t(7) = 2\$:
$$
\left(\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}, \frac{a\_3}{b\_3}\right) =
\left(\frac 2 7, \frac 2 7, \frac 3 7\right)
\hspace{1em} \text{and} \hspace{1em}
\left(\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}, \frac{a\_3}{b\_3}\right) =
\left(\frac 1 7, \frac 3 7, \frac 3 7\right)
$$
For \$n = 8\$, there is one such triangle, so \$t(8) = 1\$:
$$
\left(\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}, \frac{a\_3}{b\_3}\right) =
\left(\frac 1 4, \frac 3 8, \frac 3 8\right)
$$
The first thirty pairs, \$\left(n, t(n)\right)\$ are:
```
(1,0),(2,0),(3,1),(4,0),(5,1),(6,0),(7,2),(8,1),(9,2),(10,1),(11,4),(12,2),(13,5),(14,2),(15,5),(16,4),(17,8),(18,4),(19,10),(20,8),(21,10),(22,6),(23,14),(24,8),(25,15),(26,9),(27,16),(28,14),(29,21),(30,13)
```
---
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins.
[Answer]
# JavaScript (ES6), ~~188 184~~ 183 bytes
```
n=>{for(o=r=[],a=n;x=--a/n;)for(P=n;P;P--)for(p=P;y=--p/P;)for(Q=n;Q;)!(z=Q-x*Q-y*Q,g=(a,b)=>b?g(b,a%b):z%1||a>1)(a,n)&!o[k=[x,y,z/=Q--].sort()]&x+y>z&x+z>y&y+z>x?o[k]=++r:0;return+r}
```
[Try it online!](https://tio.run/##JYvdboJAFIRfRRPFc9wfNL2TnDV9A7gmpC4WiNbukoU2LMiz0217M8l838xdf@vu6m5tL4x9r5aaFkNqqq0DS47ygmsyyUBC6Ngk@MvTANIkFeKvtZQmPug2Tv91FnSW4BpGysSwz4TfZ7wh0LxEUuW5gZLrbYmncXt8PrU6YlAGo7XNPygfuOdjHJ6ikJ11PWARDcyrMeSofORDDucwLYgxdzokruq/nGFuXq7WdPZRyYdtIJdSvjqnPbwcsJCfugV44yuDK1KrC2wmxszMN1MNBme8oLzbm4Ed3yEuPw "JavaScript (Node.js) – Try It Online")
### How?
Given \$n\$, we look for all pairs \$(x,y)\$ defined as:
$$x=\dfrac{a}{n},\:1\le a <n$$
$$y=\dfrac{p}{P},\:1\le p < P \le n$$
For each pair \$(x,y)\$, we compute \$z=1-x-y\$.
The triplet \$(x,y,z)\$ is valid if all the following conditions are met:
* \$a\$ and \$n\$ are coprime
* there is some \$Q,\:1\le Q \le n\$ such that \$Qz\$ is an integer
* we have \$x+y>z\$, \$x+z>y\$ and \$y+z>x\$
### Commented
*NB: this is the 184-byte version, which is slightly more readable*
```
n => { // n = input
for( // 1st loop:
o = r = [], // o = lookup object, r = output counter
a = n; x = --a / n; // go from a = n - 1 to 1
) // and define x = a / n
for( // 2nd loop:
P = n; P; P-- // go from P = n to 1
) //
for( // 3rd loop:
p = P; y = --p / P; // go from p = P - 1 to 1
) // and define y = p / P
for( // 4th loop:
Q = n; Q; // go from Q = n to 1
) ( //
z = Q - x * Q - y * Q, // define z = Q(1 - x - y)
g = (a, b) => // g is a helper function which
b ? // recursively computes the GCD
g(b, a % b) // of 2 given integers
: //
a < 2 // and returns true if it equals 1
)(a, n) & // use it to figure out if a and n are coprime
!(z % 1) & // make sure that z is an integer
!o[ // make sure that the key k ...
k = [x, y, z /= Q--] // ... made of [ x, y, z / Q ] ...
.sort() // ... and sorted (lexicographically)
] & // was not already found
x + y > z & // make sure that all triangle inequalities
x + z > y & // are fulfilled
y + z > x ? // if all of the above is true:
o[k] = ++r // increment r and save the key in o
: // else:
0; // do nothing
return +r // return the final result
} //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lã3ãʒàQ}€€.«/DOÏ€{ʒR`+‹}Ùg
```
Brute-force approach, so extremely slow. Already times out for \$t(10)\$..
[Try it online](https://tio.run/##yy9OTMpM/f/f5/DiU5MSDu2vNQYxDi8IrH3UtAaI9A6t1nfxP9wPZFafmhSUoP2oYWft4Znp//@bAwA) or [verify the first 15 test cases](https://tio.run/##yy9OTMpM/W9o6upnr6TwqG2SgpK936GV/32M9A63nZqUcGh/rfHhxacmHV5waF1g7aOmNUCkd2i1vov/4X4gs/rUpKAE7UcNO2sPz0z/r/MfAA) (`ã` has been replaced with `2.Æʒ`¿}` to speed things up slightly).
**Explanation:**
```
L # Push a list in the range [1,(implicit) input]
ã # Get all pairs with these integers
3ã # Create all possible triplets of these pairs
ʒ # Filter this list of triplets by:
à # Get the flattened maximum
Q # And check that it's equal to the (implicit) input
}€ # After the filter: map over each triplet:
€ # Map over each pair in this triplet:
.« # Right-reduce this pair by:
/ # Dividing
D # Then duplicate the list of triplets
O # Sum each inner triplet
Ï # And only keep the triplets at the truthy (==1) indices
€ # Map over each triplet of decimal values:
{ # Sort them from lowest to highest
ʒ # Filter the list of triplets further by:
R # Reverse the triplet from highest to lowest
` # Pop and push all three separated to the stack
+ # Add the top two (the lowest two) together
‹ # And check that they're larger than the highest one
}Ù # After this filter: uniquify the list of triplets
g # And pop and push its length
# (after which this is output implicitly as result)
```
Here all the rules, and which piece of codes covers them:
* The triangles have a perimeter of 1: `DOÏ`
* The triangles have side lengths \$\displaystyle\frac{a\_1}{b\_1}, \frac{a\_2}{b\_2}\$, and \$\displaystyle\frac{a\_3}{b\_3}\$, and when written in lowest terms, \$\max(b\_1, b\_2, b\_3) = n\$: `ʒàO}`
* The triangles are not degenerate, thus \$a+b>c\land a+c>b\land b+c>a\$: `€{ʒR`+‹}` (after sorting \$[a,b,c]\$ in descending order, we can check whether \$a<b+c\$)
The other pieces of code are to generate all possible triplets of pairs: `Lã3ã`; actually getting their decimal values: `€€.«/`; and counting the final amount of triplets that are valid: `g`. The uniquify `Ù` is to filter out duplicated triplets which are in a different order from the `3ã`.
Explanation of the snippet that slightly sped up the test suite:
```
2.Æ # Get all possible pairs in ascending order with unique values
ʒ # Filter this list of pairs by:
` # Pop and push both values separated to the stack
¿ # Get the greatest common divisor between the two: gcd(a,b)
# (Note: only 1 is truthy in 05AB1E, so this filter checks that the
# fraction cannot be lowered in terms any further)
} # Close the filter
# (Now there are less pairs we create triplets with and have to check in
# the other filters)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 190 bytes
```
lambda x:sum(1for a,b,c in i.product(*[q(range(1,x+1))]*3)if{a,b,c}&q([x])and a<=b<=c<1==a+b+c>2*c)
q=lambda a:{x/y for y in a for x in range(y)if math.gcd(x,y)<2}
import math,itertools as i
```
[Try it online!](https://tio.run/##RVHLjuMgEDwvX4F8WIHDzAact@I57k94cyDYZJDiRzCRbFn@9iwNjuZCV1dK1eVKN7rvtsleOv/3usv6Wko8nPpnTbhuLZbsyhQ2DTafnW3Lp3IkLR7EyuZWEc6GFaf0kmbU6ClI598PUgwXKpsSy3N@PefqzPNcrq4r9SVSRdEjX67I0zT8GTFcGeGCDHAAGO1H74pr6b4/b6okAxvpWczI1F1rXeCZcZV1bXvvseyxeSVJgrRta6ytVM60jSej@u9CINThPNojVFZ6uZRKekK/bOWetsHFW0wG@hOpI2ktO2Iax7D034xQffNW73gIqbvs@7B7K7COofEI1m/v@gYO3phhmCOlCEKjaugq5arSO5bGd1z4bteUERHejHH/bgLeBrwLeM@Efw@BOQbM12HhnG1giEhmbAtjE7dt3HZRsmcHGIe4HRkPZ9eBFXxZBdvB8DlAJTbxVx8FnMSOHWHsGQ@qw6LyiSBL5iNl9EIRgi5d1buff5gzLNbQT2ehDp1oMoFipr6ISRPAdMYfX3h6N1QAd5kT@voP "Python 3 – Try It Online")
The fraction part is just so it doesn't run into precision errors. It also makes it really slow though; this causes test case 20 (and supposedly later ones) to fail if disabled but uncomment it if you want to test larger numbers (though TIO won't be able to do it in time anyway; 20 takes about 10 minutes I believe).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 135 bytes
```
NθFΦθ∧ι¬﹪÷X²×ιθ⊖X²θ⊖X²ιF…·²θFΦκ∧λ¬﹪÷X²×λκ⊖X²κ⊖X²λF…·²θFΦμ∧ν¬﹪÷X²×νμ⊖X²μ⊖X²ν«≔××θκμη≔⟦×ι×κμ×λ×θμ×ν×θκ⟧ζ≔⟦η⌊ζ⌈ζ⟧ε¿∧∧⁼ηΣζ‹⊗⌈ζΣζ¬№υε⊞υε»ILυ
```
[Try it online!](https://tio.run/##lZHBasMwDIbPy1P4qIAHo9eeSrtBoS1l223skCZuYmLLS2x3o2PPnsl1m@YSaAMOtvX90i85r7I2N5nquiV@ebfxeidaaNJpsjctgxepXDhzNsMCJGcb42BtCq8MLNEt5EEWArbmm6AJZ@9SCxuwJk05W4i8FVqgE8UVochYSKbxY6fSS8yVt/IgXjMsxVnKhq7q6Erd5oqwerR0Pe5K3elKR1d4myvC9GhpPe4KL65@k4eZtbJEiAnjvwkthQScVfSWF@Sjf6C4qc/V@wn16sE1Dq5pTp@cHYcpK87WEqX2Go6kWWc/5z2BIoByzyBMJKznxmfKAmneTgwJVsJaWBi/U9TfVZ32SBonOTceHfiQNPS99baKp2nyl2xbScF5Zh2sBJaOQgRNu27y1D0e1D8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input \$ n \$. We'll assume \$ b\_1=n \$ for now.
```
FΦθ∧ι¬﹪÷X²×ιθ⊖X²θ⊖X²ι
```
Loop for all values \$ 0<a\_1<b\_1 \$ such that \$ a\_1 \$ and \$ b\_1 \$ are coprime.
```
F…·²θ
```
Loop for all values \$ 2 \le b\_2 \le n \$.
```
FΦκ∧λ¬﹪÷X²×λκ⊖X²κ⊖X²λ
```
Loop for all values \$ 0<a\_2<b\_2 \$ such that \$ a\_2 \$ and \$ b\_2 \$ are coprime.
```
F…·²θ
```
Loop for all values \$ 2 \le b\_3 \le n \$.
```
FΦμ∧ν¬﹪÷X²×νμ⊖X²μ⊖X²ν«
```
Loop for all values \$ 0<a\_3<b\_3 \$ such that \$ a\_3 \$ and \$ b\_3 \$ are coprime.
```
≔××θκμη
```
Calculate a common denominator for the fraction \$ \frac {a\_1} {b\_1} + \frac {a\_2} {b\_2} + \frac {a\_3} {b\_3} \$.
```
≔⟦×ι×κμ×λ×θμ×ν×θκ⟧ζ
```
Calculate the numerators of the three fractions using the common denominator.
```
≔⟦η⌊ζ⌈ζ⟧ε
```
Get the denominator and minimum and maximum numerator. These don't depend on the order of the fractions, so will identify duplicates.
```
¿∧∧⁼ηΣζ‹⊗⌈ζΣζ¬№υε
```
Check that the numerators sum to the denominator (i.e. the perimeter is \$ 1 \$), that the largest numerator is less than half the sum (i.e. the triangle is not degenerate), and that the fractions haven't already been seen in a different order.
```
⊞υε
```
If all the tests pass then record this as a seen set of fractions.
```
»ILυ
```
Print the number of fractions found.
[Answer]
# [Perl 5](https://www.perl.org/), 241 bytes
```
sub{sub g{($a,$b)=@_;$b?g($b,$a%$b):$a}$r=0;for$a(@m=map{$N=$_;grep g(@$_)<2,map[$_,$N,$_/$N],1..$N-1}2..($n=pop)){for$b(@m){for(@m){($A,$B,$C)=map$$\_[2],$a,$b,$\_;$r++if$A<=$B&$B<=$C&1e-9>abs$A+$B+$C-1&$A+$B>$C&&grep$$_[1]==$n,$a,$b,$_}}}$r}
```
[Try it online!](https://tio.run/##PZBNj5tADIbv/Apr66IZZZIyk48mmR2aj3Nz6m0VIWgnFDUBBGy7K8Rvz3qGqAew/fr1Y0Ntm@vyfnsH7My9fc16eiDvGaYCM252icbsW84wE5h@JmWL6YCNifSlajBlu5u5pXWPJ4OJzhtbQ852mPBnJUh/wUTgSWDyBU9nIWczPE3loGYzhqWpq5rz3mEywvjMR4Z7gQeBR@7QiMmLOgt/DoE0NpNJccH9s8FDiAcKx1Da6SZOsxb3EzxM8DiVoU9j6oXuKAeRZ2Ow/A8aBvqM4a6D19bCD9t22@33qrE6oF@x66g2LACQJo4EKP@em1gKWPh86fOVz7@aWAlYe2Xjcxn5QtL0goIaRZpfUliM1XKsVs7iFhFlTfV6HCGOdIsjryr5KIm0ouAuIZdajF13DLEUsTYUiCSda/1wuZvomrk7ag5cB/9@F1fL/EfynnYD3N4ZFmUt0L7V3LT1tfhpfV9EQmlv@VTatw6KCzgj7dOPQcyrzoTYeQAf1eoP87JxPPEEjyYYcDL8bcE1nsg9BL@q0iZuVVHm@v4B "Perl 5 – Try It Online")
TIO times out at 60 seconds, it found 28 of the 30 test cases at that time. Very brute force.
```
sub t {
$n=pop; #input number --> n
sub g{($a,$b)=@_;$b?g($b,$a%$b):$a} #greatest common divisor,
#about the worlds oldest algorithm
$r=0; #result counter r
@m=map { #m = list of 3-elem-arrays: nominator,
$N=$_; #denominator and floating point fraction
grep g(@$_)<2, #keep only irreducible fractions
#grep g(@$_)<2&&g($$\_[1],$n)>1, #run faster with this grep but same result
map [$\_,$N,$\_/$N], 1..$N-1 #all nominators 1 to N-1
}
2..$n; #with all denominators 2 to n
for $a (@m){ #loop through m on three levels a,b,c
for $b (@m){
for $c (@m){
($A,$B,$C)=map$$\_[2],$a,$b,$c;#A,B,C is the fractions, side lengths
$r++
if $A<=$B #increase r result if length A < B
&& $B<=$C #and B < C lengths ABC sorted by length
&& 1e-9 > abs $A+$B+$C-1 #and A+B+C=1, taking care of f.p. errors
&& $A+$B > $C #and A+B>C (not a trangle if not)
&& grep$$_[1]==$n,$a,$b,$_ #and at least one fraction must
#have denominator = n
}}}
$r #return result counter
}
```
] |
[Question]
[
[Recamán's Sequence](http://mathworld.wolfram.com/RecamansSequence.html) is defined as follows:
\$a\_n=\begin{cases}0\quad\quad\quad\quad\text{if n = 0}\\a\_{n-1}-n\quad\text{if }a\_{n-1}-n>0\text{ and is not already in the sequence,}\\a\_{n-1}+n\quad\text{otherwise}\end{cases}\$
or in pseudo-code:
```
a(0) = 0,
if (a(n - 1) - n) > 0 and it is not
already included in the sequence,
a(n) = a(n - 1) - n
else
a(n) = a(n - 1) + n.
```
The first numbers are ([OEIS A005132](https://oeis.org/A005132)):
```
0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 25, 43, 62, 42, 63, 41, 18, 42
```
If you study this sequence, you'll notice that there are duplicates, for instance `a(20) = a(24) = 42` (0-indexed). We'll call a number a duplicate if there is at least one identical number in front of it in the sequence.
---
### Challenge:
Take an integer input **k**, and output either the first **k** duplicate numbers in the order they are found as duplicates in Recamán's Sequence, or only the **k**'th number.
This first duplicated numbers are:
```
42, 43, 78, 79, 153, 154, 155, 156, 157, 152, 265, 261, 262, 135, 136, 269, 453, 454, 257, 258, 259, 260, 261, 262
```
A few things to note:
* **a(n)** does not count as a duplicate if there are no identical numbers in **a(0) ... a(n-1)**, even if **a(n+m)==a(n)**.
* 42 will be before 43, since its duplicate occurs before 43's duplicate
* The sequence is not sorted
* There are duplicate elements in this sequence too. For instance the 12th and the 23rd numbers are both **262** (0-indexed).
---
### Test cases (0-indexed)
```
k Output
0 42
9 152
12 262
23 262
944 5197
945 10023
10000 62114
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins!
**Explanations are encouraged!**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~88~~ ~~85~~ 76 bytes
```
(For[i=k=j=p=0,k<#,i~FreeQ~p||k++,i=i|p;p+=If[p>++j&&FreeQ[i,p-j],-j,j]];p)&
```
[Try it online!](https://tio.run/##ZY67CsIwFED3@xWBlqLkFl9VkBoRB6HgoK4hQykp3tS2IcZBrP56fawO5yxnOXXuz7rOPRV5X4pBP9i1TpKohBFWjLFaBUivndP6@LJdV3GOJKizqeUiK6Vdc26i6NcloY2NwtigUSq1w6gfpgDbS1tU8hGedHFzV2qbPdXkmWBZU1JD/o4szLx2n4X/9kQGAAdHjZcBi9es3AQqYqMNwANggjAZf5ghTBOEZTL/agHwBFD9NHkD "Wolfram Language (Mathematica) – Try It Online")
1-indexed.
### Explanation
```
For[
```
`For` loop.
```
i=k=j=p=0
```
Start with `i` (\$=\{a\_1, a\_2, \ldots\}\$), `k` (number of duplicates found), `j` (\$=n\$), `p`(\$=a\_{n-1}\$) equal to 0.
```
k<#
```
Repeat while `k` is less than the input.
```
i=i|p
```
Append `p` to `i` using the head `Alternatives` (a golfier version of `List` in this case).
```
p+=If[p>++j&&FreeQ[i,p-j],-j,j]
```
Increment `j`. If `p` is greater than `j` (i.e. \$a\_{n-1} > n\$) and `p-j` is not in `i` (i.e. \$a\_{n-1} - n\$ is new), then increment `p` by `-j`. Otherwise, increment `p` by `j`.
```
i~FreeQ~p||k++
```
Each iteration, increment `k` if `p` is not in `i` (the `||` (= `or`) short-circuits otherwise).
```
... ;p
```
Return `p`.
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
k=input();n=0;l=n,
while k:n+=1;x=l[-1]-n;u=x+2*n*(x<1or x in l);k-=u in l;l+=u,
print l[n]
```
[Try it online!](https://tio.run/##HcbBCoQgEAbge08xx8qEVTo1zZOEx4XE4U9CyZ7ehf1OX37LecH3niQi1zJODPmwCpbhOaN@KW0w4riJHtYFC67SjJ8xj213102NIkgnTlbqv6xG6jLkO6KQHgi9@/UH "Python 2 – Try It Online")
1-indexed.
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
n=input()
l=[];d=x=0
while n:d-=1;l+=x,d;x+=[d,-d][x+d in l];n-=x in l
print x
```
[Try it online!](https://tio.run/##HcbBCoAgDADQu1/hsTChog4l@xLxtkBhLAmj9fULeqdX35ZPnlUZCte7db0hiCkgCIzmyYUOyzt6mAI5kAGDOIg4eExRHNrCllJgD/LX1Ktws6K6LesH "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~56~~ ~~54~~ ~~49~~ 48 bytes (SBCS)
*Saved ~~2~~ 7 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)!*
*Saved 1 byte thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)*
```
0∘{×⍵:r,⍣d⊢(r,⍺)∇⍵-d←⍺∊⍨r←(⊃((≤∨⍺∊⍨-)⌷-,+)≢)⍺⋄⍬}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/w0edcyoPjz9Ue9WqyKdR72LUx51LdIAsXZpPupoBwrrpgDVAbmPOroe9a4oAnI0HnU1a2g86lzyqGMFXEJX81HPdl0dbc1HnYs0QaLdLY9619T@TwPr7gNqObTe@FHbRKDNwUHOQDLEwzP4f5qCkQEA "APL (Dyalog Unicode) – Try It Online")
Can be `f k`. Recursively builds up the first k duplicates.
⍺ holds Recamán's sequence (in reverse), and is set to 0 if no argument is given (at the start). If k (⍵) is 0, it returns an empty array (⍬). Otherwise, it computes the next term `r`. If `r` is present in ⍺, it calls itself with `r,⍺` as the left argument and `⍵-1` as the right argument, and prepends `r` to the result of that. If not, it just returns `(r,⍺) f ⍵`, hoping for the next iteration to find a duplicate.
`⎕IO←0` has to be used before using this, since it relies on 0-indexing.
```
0∘ ⍝ Default argument to start off the sequence
{×⍵: ⍝ If k is greater than 1:
r←(⊃((≤∨⍺∊⍨-)⌷-,+)≢)⍺
≢ ⍝ Current n is the size of ⍺.
⊃ ⍝ First element of ⍺ (a_{n-1})
⌷ ⍝ Index into
-,+ ⍝ a_{n-1} - n, a_{n-1} + n using
(≤∨⍺∊⍨-) ⍝ another train to return 1 or 0
≤ ⍝ If a_{n-1} is not greater than n
∨ ⍝ or
- ⍝ a_{n-1} - n
⍺∊⍨ ⍝ is already in a,
⍝ use a+n, otherwise a-n
d←⍺∊⍨r ⍝ Whether or not r (a_n) is a duplicate
(r,⍺)∇⍵-d
(r,⍺) ⍝ Add r to ⍺, because it's part of Recaman's sequence
⍵-d ⍝ Decrement k if r is a duplicate
∇ ⍝ Call itself, find the next duplicates
r(,⍣d)(r,⍺)∇⍵-d
⍣d ⍝ If d is 0, just return (r,⍺)∇⍵-d
r , ⍝ Otherwise, add r to the list of duplicates (which is returned from (r,⍺)∇⍵-d
⋄⍬ ⍝ If k is 0, return an empty array
}
```
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
Outputs the `nth` item `1-indexed`
```
¾ˆµ¯D¤N-DŠD0›*åN·*+©å½®Dˆ
```
[Try it online!](https://tio.run/##ATQAy/8wNWFiMWX//8K@y4bCtcKvRMKkTi1ExaBEMOKAuirDpU7CtyorwqnDpcK9wq5Ey4b//zEw "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), ~~66~~ 59 bytes
Returns the **N-th** term, 0-indexed.
```
i=>(g=x=>!g[x+=x>n&!g[x-n]?-n:n]||i--?g(g[n++,x]=x):x)(n=0)
```
[Try it online!](https://tio.run/##dclBC4IwGIDhe79iXWLDltvUQuGbP0R2ENOxkG@RETv431dRXpLe0wvPpX20U3dz1ztHf@7jANGBphYC6K1tQgJB4@59HE3NsUIzz47z2lLbYJLsg4HAqsAogmCx8zj5sT@M3tKBEiIYI2lKXuVq84vlgrJYoVQLquMKVfYfyzz/YiHL0wqLD0ohVBaf "JavaScript (Node.js) – Try It Online")
### How?
We use **g()** as our main recursive function *and* as an object to keep track of the duplicates.
```
i => ( // given i
g = x => // g = recursive function and generic object
!g[x += // update x:
x > n & !g[x - n] ? // if x is greater than n and x - n was not visited so far:
-n // subtract n from x
: // else:
n // add n to x
] // if x is not a duplicate
|| i-- ? // or x is a duplicate but not the one we're looking for:
g(g[n++, x] = x) // increment n, mark x as visited and do a recursive call
: // else:
x // stop recursion and return x
)(n = 0) // initial call to g() with n = x = 0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~34~~ 33 bytes
```
J][[email protected]](/cdn-cgi/l/email-protection)}K+=G-eJZ*yZ|}GJ<G0~+JKQ1
```
[Try it online!](https://tio.run/##K6gsyfj/3yvWwMHHSy@t1lvb1l031StKqzKqptbdy8bdoE7byzvQ8P9/IxMA "Pyth – Try It Online")
Outputs the `n` first duplicates.
*\*waits for Jelly or one of the new stack languages to enter\**
[Answer]
# [Rust](https://www.rust-lang.org/), 160 bytes
```
|k|{let(mut a,mut r,mut n,mut i,mut v)=(vec!(0),0,1usize,0,0);while i<k{v=if v>n&&!a.contains(&(v-n)){v-n}else{v+n};if a.contains(&v){r=v;i+=1}a.push(v);n+=1}r}
```
[Try it online!](https://tio.run/##TY9BjsIwDEX3nMJlUdmiVC2zIxPuUqFEWBSDkjQjEXL2kmY1mydb/1m23eLDagUeEwsSpB3AbALYM1hB/jkRHC@weH4b0Ovn/kklxccSYOo2ukqp5MpIGqO5NjhQN3RjHS3FQOrvxrMB/r2nqNlCvEjbNlN/fUooyz22GI9ClAqzmb1J8SBZFfO/Eyk5HRUf9Jin/rX4G0ZSsrUur6qcb58OGFhg7PvTUD8CeDmWMEuD@5T3HVhkok3Ou7x@AQ "Rust – Try It Online")
Ungolfed:
```
|k| {
let mut a=vec!(0);
let mut r=0;
let mut n=1usize;
let mut i=0;
let mut v=r;
while i < k {
v = if v > n && !a.contains(&(v-n)) {
v - n
} else {
v + n
};
if a.contains(&v) {
r = v;
i += 1
}
a.push(v);
n += 1
}
r
}
```
] |
[Question]
[
The first magic card trick I ever learned as a child was the following:
* Have 1 deck of cards where the pattern on the back is not vertically symmetric.
* Organize all cards to be facing one direction.
* Ask an individual to, "pick a card, any card, memorize it and give it back to you".
* Proceed to put it into the deck (in the wrong direction).
* Shuffle vigorously, giving the illusion that you won't know where their card is.
* Produce their card to their amazement.
---
This trick is obviously a little bit lack-luster in nature now-a-days, however it makes for a good challenge. Write a program, that when given no input, outputs a randomly shuffled deck of cards with one of the cards, chosen at random, reversed. However, when the input is a deck of cards with one card reversed, you must output the reversed card (in the correct order).
---
***The Deck of Cards***
A deck of cards is defined to be:
```
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
2C,3C,4C,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]
```
A card is defined as it's number, then the first letter of its suit. The reverse of a card is the exact opposite, the first letter of its suit followed by a number.
***The Drawn Card***
Example, if the card we randomly chose to reverse was the `4 of Clubs (4C)`, we'd end up with (without shuffling, obviously):
```
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
2C,3C,C4,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]
```
***The Shuffling***
Then, after shuffling:
```
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]
```
This is a valid output given empty input.
***The Deck Input***
However, conversely, when our program receives the above output as input, it should output `4C`. That is to say, for an input of:
```
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]
```
You iterate through until you find the reversed card, and return it, reversed back to the normal state. So here we'd find `C4`, know that C isn't a number, and return it as `4C`, which is correct.
---
# Rules
* You may not load the deck from any external sources.
* An empty input should result in a randomly shuffled deck with 1 random card reversed.
* A deck of cards with 1 card reversed as input should result in the reversed card.
* Any other inputs can result in explosive llamas riding segways through a futuristic tube.
+ Or anything else, for that matter.
* Both the chosen card and the shuffling order must be uniformly random.
+ I.E. all cards have equal chance of being selected to be reversed.
+ I.E. all combinations of cards have an equal chance of appearing.
* You may use `SHCD` or `shcd` for the suits, but be consistent:
+ If you choose uppercase suits (`SHCD`) you must also use `TJQKA`.
+ If you choose lowercase suits (`shcd`) you must also use `tjqka`.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), winner is lowest bytes.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~61~~ ~~60~~ 59 bytes
```
G`[HCDS].
^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S
@V`
O?`
```
[Try it online!](https://tio.run/##K0otycxLNPz/3z0h2sPZJThWjytOhcvI2MTUzNzCMsQr0JtLP85IX81HJUGPS0XN49A2FTUXEOEMIoK5HMISuPztE/7/BwA "Retina – Try It Online") Edit: Saved ~~1~~ 2 bytes thanks to @MartinEnder. Explanation:
```
G`[HCDS].
```
Delete all unreversed cards. This should leave one reversed card or no cards.
```
^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S
```
If the input is (now) empty, create a pack of cards.
```
@V`
```
Randomly select one card and reverse it (unreverses the single reversed card).
```
O?`
```
Shuffle the card(s).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
Y9ŸJ.•§®т•«.•öB•âsKDgiëDΩÂ:.r
```
[Try it online!](https://tio.run/##JY8xDoJAEEWvYreNIYqwsJaGSk9gjAWiUaFCOIDhKDTGkFgaa4itiVfwImv2TfPyefyZgUmY7qYHa9fm/Vp6v2vb3/rHt3Ghc4/Dc@HYVqvkeB665HMfmrl3sXaj6kqNR2qWwZOj3jsWmBqT08nxGp/KFCzwEc1aMt6HGl/CmNmAji978D40MJSd5IhOlmLwKbMl2cAQk9PUmECuyEXehuRAvlk2yJR08LFcZ7aEvvwLNBhDrjO1/QM "05AB1E – Try It Online")
[Answer]
# PowerShell v2 or later, 175 bytes
```
%{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}
```
Long version:
```
ForEach-Object {
$s = [char[]]'SDHC' # Create a character array with the suits
if ($_) { # If there's pipeline input ...
$_ | # ... write it to the output pipeline ...
Where-Object {$s -contains $_[0]} | # ... but let only those input elements pass where the first letter appears in the suits ...
ForEach-Object {$_[1] + $_[0]} # ... and swap the two elements
} else {
$d = $s | ForEach-Object { # Assign $d to the output of the suits, processing each element first.
$e = $_ # Store the current suit element for use in the inner loop
[char[]]'23456789TJQKA' | ForEach-Object {$_ + $e} # Process each of the numbers, joining it with the current suit, ...
} | Get-Random -Count 52 # ... and the resulting 2-char-strings goes back into the output to be shuffled
$r = Get-Random -Maximum 52
$d[$r] = $d[$r][1] + $d[$r][0] # Swap the two chars of a random array element in $d
$d # Write $d to the output pipeline
}
}
```
## Usage:
Create a shuffled deck and store it in a variable:
```
$Deck = %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}
```
Inspect the variable at will, for example
```
$Deck -join ','
```
Pipe the deck back into the script:
```
$Deck | %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 175 bytes
```
from random import*
s='SHCD';c='23456789TJQKA'
d=input()
if d:print[b+a for a,b in d if a in s];q
k=sample
r=k(c,1)+k(s,1)
print k([(a+b,b+a)[r==a+b]for a in c for b in s],52)
```
[Try it online!](https://tio.run/##Jcy9DsIgAATgnadgAyyL1frXMBgdjE5GN9IBio2kFhBw8OmR1ukuudznvvFpTZlS5@0AvTAqhx6c9XEGAkO30@GI6pahcrGsVuvN9n6@XvYIKKaN@0RMgO6g2jmvTeSyELCzHgoqoTZQwbyJsYWmfoOeBTG41wN41uOWzknR45ADTGfYY45FIWlGCPeM5d5M2Ai0kyv/Fq1KkhJvfg "Python 2 – Try It Online") empty input is denoted as `[]`
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~215~~ 193 bytes
```
i:0)?\~"CHSD":"2"$:"3"$:"4"$:"5"$:"6"$:"7"$:"8"$:"9"$:"T"$:"J"$:"Q"$:"K"$:"A"$&105&"S"=?.~~~{c0.
=+i$?\i$:::"B")$"I"(*$"S"
_oo$~/;
x0
x0
x0
x0
x0
x0
x0
x0
x0
x0
\l&>?!<
>&"3"%:?\~$>o<
\ }}&-1/
```
[Try it online!](https://tio.run/##fc67CsIwFMbxPU9RD8dgFdtUrZdj2@Bl8DJJHQMOghgQMrgI0rx6zHkB4eM3fcP/Yd/PECypVBsPu0O7B4IJIMGUmTElM2cWzJJZMVfmxFyYM7MBlIUqJbRQ68x7/72rTNQji9pYJCLYQopwhMEQ40fcnEOfr8VH/Zt5yUb3KtHI2NWn2IqNq4RJkq6T4yIP4Qc "><> – Try It Online")
Takes input as not separated cards, and output as the same (e.g. `KCAC5C6S...`)
To make it easier to test, [here's a version](https://tio.run/##fc5NasMwEAXgvU@RDKpp0tfE8b/VxMaRFqq9MvLSEEqh1FDwoptCia7uji5QGD6Q9GY0H/P357rOMto1kyNlrCZJMQlJiSf1ZJ7cU3hKT@UZPZ1n8PSelkR4irKQLF2ag3Pu9z06BJenWTTTLKSUdKWdoFd63AvOzC64LYtwx5fgJ/qvpq@wbrbnoA55swfJ24qlXt62yzmYNpv7PXw@Hdc1NogVcotUYzDIFUaNUqEwyAxUikSjsCgUeoWBMwodHzVyjdgi43uNRCGxiLnRoOchBq1BadEZjBatRqZRGaQGHU/gv/iJWzijMSq0FiM3clKh4uKxFpX@Aw) that takes input as comma separated and outputs as newline separated.
All the `x0`s are just an attempt to make a semi-uniform random number generator. More of them increases the range of possible values, and the opposite for less. 10 of them is where I judged it to be random enough.
Note that it follows the rules in that:
* All cards have an equal chance of being selected to be reversed.
* All cards have an equal chance of appearing anywhere in the shuffled deck.
*But not all* shuffled combinations are possible outputs (and in fact, the vast majority aren't).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9ḊṾ€;“AJKQT”p“CDHS”ḟ⁸ẊU-¦Ẋ
```
A monadic link accepting a list of lists of characters (a stub of 0 cards or a full-deck of 52 cards with one card reversed) and returning a list of lists of characters (a stub of the 1 reversed card but forward or a full-deck with one random card reversed).
**[Try it online!](https://tio.run/##TcytDsIwAEXhV8HNgGG/DaoZIUurGooiSAxBYHEDQ4JEISA4FA@wIRAQHqR7kTIC4qh7xJe7mC@Xa@@Fq/aufjTb26ApT1JpY5vyvGo7HxbjNl11aTaVu@8nvee1HT9q7Wv3Prj66P10GvSDbifIg1m38@8hukCPfx3Ch/AhfAiffzv6dQQfwUfwMf5j@Bg@hk/gE/gEPoFP4VP4FD6Fz@Az@Aw@gxfwAl7AC3gJL@ElvIRX8ApewSt4Da/hNbyGN/AG3sAbeAtv4S28/fvZBw "Jelly – Try It Online")** (footer to make input and output representations match - as a full program Jelly code Python-evals the argument and smashes the characters together for the output)
### How?
```
9ḊṾ€;“AJKQT”p“CDHS”ḟ⁸ẊU-¦Ẋ - Link: list of lists of characters, Z
9Ḋ - nine dequeued = [2,3,4,5,6,7,8,9]
Ṿ€ - unevaluate €ach = ['2','3','4','5','6','7','8','9']
“AJKQT” - literal list of characters = ['A','J','K','Q','T']
; - concatenate = ['2','3','4','5','6','7','8','9','A','J','K','Q','T']
“CDHS” - literal list of characters = ['C','D','H','S']
p - Cartesian product = [['2','C'],['2','D'],...,['T','S']]
- a full deck of forward cards
⁸ - chain's left argument, Z
ḟ - filter discard
- leaving either that deck or the 1 reversed card in the input
Ẋ - shuffle
¦ - sparse application...
- - ...to index: -1 (which doesn't exist when the length is only 1)
U - ...do: upend (reverses the penultimate card of the deck)
Ẋ - shuffle
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 95 (or 100) bytes
```
->n{s=(0..51).map{|i|"A23456789TJQK"[i/4]+"HCDS"[i%4]}
n[0]?s-n:s[rand 52].reverse!&&s.shuffle}
```
Given an empty array as input, returns the deck as an array of strings. Given a nonempty array as input, returns the flipped card as an array containing a single string. If the flipped card is required as a string rather than a single-element array containing a string, the following adds 5 bytes: change `s-n` to `(s-n)[0]`
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuthWw0BPz9RQUy83saC6JrNGydHI2MTUzNzCMsQr0FspOlPfJFZbycPZJRjIVjWJreXKizaItS/WzbMqji5KzEtRMDWK1StKLUstKk5VVFMr1ivOKE1Ly0mt/V@gkG2bFh0dG8tVoJAWnR37HwA "Ruby – Try It Online")
The first line generates a standard deck. The second line breaks down as follows
```
n[0]? #If the input array is not empty (contains a truthy first element)
s-n: #Find the contents of s with the contents of n removed. The only card remaining from the standard deck corresponds to the flipped card in the input.
#ELSE
s[rand 52].reverse!&& #Flip one card in place in the array s. As the result is truthy, whatever is next will be returned.
s.shuffle #shuffle the deck and return the shuffled deck with one element flipped
}
```
[Answer]
# Java 8, ~~275~~ ~~274~~ 259 bytes
```
import java.util.*;s->{if(s==null){List l=new Stack();char i=52,r=i,x,y;for(r*=Math.random();i-->0;y="23456789TJQKA".charAt(i%13),l.add(i==r?x+""+y:y+""+x))x="HSDC".charAt(i&3);Collections.shuffle(l);return l;}return s.replaceAll(".*,(.)([^HSDC]).*","$2$1");}
```
Input is a String, output is either a String or a `java.util.List` depending on the input.
**Explanation:**
[Try it online.](https://tio.run/##dVLfb9sgEH7vX4GsboL0Qlc7P2e5U4QfrGTtFpG3qpOIYy@kBEcYt7Gi/O3ZpY20lw0dgrv7vgM@bqNeVbfaFXazejnp7a5ynmwwxhuvDe/EBMftLfmpMF6VxK8Lsmx90c2rxvqrq9youiYPStvDFSHa@sKVKi/I49kl5MdyU@Se5FR6p@1vUrMY40ecaLVXXufkkViSkFPdvT/oktZJYhtj2OG7rj0xiS3eiPQqf6EsztfKEZ30Q3CJhj20cVk56jrJg/Jr7pRdVVuE6W73/kvcJkEY9fqD4Wi8mM5nk4Cf6RNP9ae7iIHharWiOknct/1NENy0X9vzsmdsnwSZTMVf/OeIxaIyBl@iK1vzet2UpSmoYbErfOMsMfHxsqu5K3YGFZgYQwPeAcoZffp1LvjMeCeA4Dq8vgtYfDzFHyrsmqVBFS5ivFZ6RbYo50Wxp2fFPqSUbe2LLa8az3eY8cZSy3MaQJhBKGAgoZfCPIOBgEUKIwHDDPoZiB5EKQwlDAXMBMwRI2CKbgqDFEIJfYynEAmIJIRIzGCGRTKYZDCSMM1gIWGSQj@FcQa9DKZYAc/CFFIQk8JCwETCAomIFDBGw7ISxikE7P3D/3n7/2fO73pvgku3HE9/AA)
```
import java.util.*; // Required import for List, Stack and Collections
s->{ // Method with String parameter and Object return-type
if(s==null){ // If the input is `null`:
char i=52, // Index-integer
r=i, // Random-integer
x,y; // Temp characters
List l=new Stack(); // Create a List
for(r*=Math.random(); // Determine the random integer in the range (0;52]
i-->0 // Loop `i` 52 times:
; // After every iteration:
y="23456789TJQKA".charAt(i%13)
// Set `y` to one of 23456789TJQKA based on `i` modulo-13
,l.add(i==r? // If the random integer equals the current `i`
x+""+y // Add the current card reversed
: // Else:
y+""+x)) // Add the current card as is
x="HSDC".charAt(i&3); // Set `x` to one of HSDC based on `i` bitwise-AND 3
Collections.shuffle(l); // Shuffle the generated Deck
return l;} // And return this Deck as result
// If the input was a Deck instead:
return s.replaceAll(".*,(.)([^HSDC]).*",
// Get the reversed card from the Deck,
"$2$1");} // and output it non-reversed
```
[Answer]
# Pyth, 45 bytes
```
J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK
```
Takes the empty list for empty input.
[Try it online](http://pyth.herokuapp.com/?code=J%22CDHS%22KO52%3DNsM.S%2A%2Bc%22AKQJT%221S9J%7Cf%7DhTJQXNK_%40NK&input=%5B%27QH%27%2C%20%273H%27%2C%20%27JD%27%2C%20%279S%27%2C%20%273S%27%2C%20%272H%27%2C%20%27AD%27%2C%20%275S%27%2C%20%273D%27%2C%20%276D%27%2C%20%271C%27%2C%20%275C%27%2C%20%275D%27%2C%20%272D%27%2C%20%27QC%27%2C%20%271D%27%2C%20%27QS%27%2C%20%27JC%27%2C%20%27QD%27%2C%20%278C%27%2C%20%277C%27%2C%20%27AH%27%2C%20%279H%27%2C%20%27TS%27%2C%20%27TH%27%2C%20%276H%27%2C%20%278S%27%2C%20%27JS%27%2C%20%275H%27%2C%20%274C%27%2C%20%27KS%27%2C%20%271H%27%2C%20%279D%27%2C%20%279C%27%2C%20%274S%27%2C%20%272C%27%2C%20%273C%27%2C%20%274D%27%2C%20%278D%27%2C%20%27JH%27%2C%20%274H%27%2C%20%27KH%27%2C%20%27TC%27%2C%20%27AS%27%2C%20%276S%27%2C%20%27KC%27%2C%20%277S%27%2C%20%27C6%27%2C%20%272S%27%2C%20%27KD%27%2C%20%27AC%27%2C%20%277H%27%2C%20%278H%27%2C%20%27TD%27%2C%20%277D%27%2C%20%271S%27%5D&debug=0)
### Explanation
```
J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK
J"CDHS" Save the suits as J.
KO52 Save a random index as K.
=NsM.S*+c"AKQJT"1S9J Save a shuffled deck as N.
f}hTJQ Find all cards with suit first.
| XNK_@NK If there aren't any, flip a card.
```
[Answer]
# [R](https://www.r-project.org/), ~~177~~ 171 bytes
```
function(l=1,F="(.)(.)",R="\\2\\1",S=sample)if(l>1)sub(F,R,grep("^[SDHC]",l,v=T))else{m=S(outer(c(2:9,"T","J","Q","K"),c("S","D","H","C"),paste0))
m[1]=sub(F,R,m[1])
S(m)}
```
[Try it online!](https://tio.run/##NY7LCsIwEEX3/YoyqxkYxXanGDctIrqy6a5RqDERMa2lDzfit9dUEObAPXdzpx1tuJ6Ndqh1f3/W6ETEWwE4J3/AmQClYqUiYCm6smqcobtFt4moGy645YxvrWkQzoVMd8kJ2PFL5ETGdeZdCYnPoTctaoxXS4YcGPaeo@cAxBpB@ph6dp7EV03Z9WZBFFRFdBL/kUkokFjRZ7wa/fA/hxYp0GWPkzOoGiiwP6HxCw "R – Try It Online")
Given empty input, (call `f` with no input), we default to `l=1` and thus create a random permutation `m` of the deck. Assuming `sample` is truly random, there is an equal probability of any card being the first in this list. So we modify the first one, and then shuffle again, returning the list.
Reversing it, we look for a card starting with one of `SDHC` and reverse it.
[Answer]
# [Python 2](https://docs.python.org/2/), 135 bytes
```
from random import*
s=shuffle
d=zip('A23456789TJQK'*4,'SCDH'*13)
s(d)
D=input()
if D:d=list(set(D)-set(d))
d[0]=d[0][::-1]
s(d)
print d
```
[Try it online!](https://tio.run/##XZE/q4MwFMX3fAq3JGLh1T@1Cg6SDEEnqZs4FFJpoFXRdHjvy/sqOhxckh@Hk3vPvRl/7XPo/WXppuHtTPdefy/zHofJumTO5uen614PorM/MzKa@0EYXeJrUhdVSd3QozchFXXPAScz05zIzPTjxzJOTOfIVGcvM1s2PyyT/LRemnOim582W48mTU/ndns5Tqa3jl6WhtGIeg6VlHsOo@XKYuNq5RvouycBPQYOwJNDnRI8ObAPfAF/ccygNq6Bc@gVgF4Cx1AnAs7B4wMXkCcCvYK3IfQtgOvjLAr8u349@gXoCvpiHQmMexMwI/bCHSr4LwG7EpBBQk38Xwn1JexBQmb8d5xxr69WTiDbN09L/gE "Python 2 – Try It Online")
Cards are tuples of `(value,suit)`
Empty input is `[]`
] |
[Question]
[
**This question already has answers here**:
[Generate programs that print n times their length](/questions/139995/generate-programs-that-print-n-times-their-length)
(19 answers)
Closed 6 years ago.
On PPCG, we have had lots of challenges where the length of your output is dependent on the length of your source code. For the purposes of this challenge, we will call these *Source-length problems*. The two most well known examples of source-length problems are
* [Output with the same length as the code](https://codegolf.stackexchange.com/q/121056/31716) (the 1X source-length problem)
* [Create output twice the length of the code](https://codegolf.stackexchange.com/q/59436/31716) (the 2X source-length problem)
More simply, the `NX` source length problem is the challenge of creating a program whose output is exactly **N** times (**X**) the length of the source code. There have even been some variants on this type of challenge, for example
* [Output with the same number of digits of pi as the length of the code](https://codegolf.stackexchange.com/q/142830/31716)
* [triplegolf - not only the source code length counts!](https://codegolf.stackexchange.com/q/5852/31716)
These usually tend to be pretty interesting, although fairly simple to implement. However, we've never had a *generalized* source-length problem. Until today that is. Here is your challenge for today:
>
> Given a positive integer **N**, output an answer to the NX source-length problem in the same language.
>
>
>
For example, let's say you wrote a submission in the language *foo*. If your program or function was given the input 3, you must output a new foo program or function **s**, that takes no input and whose output is exactly 3 times the length of **s**. Borrowing [Martin's rules on the first challenge](https://codegolf.stackexchange.com/q/121056/31716), here are some requirements for **s**:
* Your code and your **s** may use any consistent encoding you like. However, **s** may only output bytes in the printable ASCII range (0x20 to 0x7E, inclusive), or newlines (0x0A or 0x0D).
* **s** must not be a quine, so the code and the output must differ in at least one byte.
* **s** must be at least one byte long.
* If your output contains trailing newlines, those are part of the byte count.
* The output doesn't always have to be the same, as long as you can show that every possible output satisfies the above requirements.
* Usual quine rules *don't* apply. You may read the source code or its size, but I doubt this will be shorter than hardcoding it in most languages.
And adding a few rules of my own
* Output from errors does *not* count towards output length.
* If your solution fails for large **N** because of integer size restrictions, this is OK. Keep in mind, that this does not mean you can [abuse native number types](https://codegolf.meta.stackexchange.com/a/8245/31716).
I highly recommend testing your code with inputs that are a different number of digits, since naive approaches that work for 1 digit **N**s will fail for 2 digit **N**s. Please also include an explanation of how you know your program is valid. Although this isn't mandatory, it is encouraged.
Since this task will be much easier in REPL languages, if you do answer in a REPL, please post your answer as
```
# Foo REPL, N bytes
```
so that it is distinguished from a regular answer in foo.
Of course, since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, try to write the shortest possible answer in bytes as you can!
## Leaderboard
Please format your answer like this so that it shows up in the leaderboard:
```
# <Language-name>, <n> bytes
code
code
```
```
/* Configuration */
var QUESTION_ID = 154961; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 31716; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [M](https://github.com/DennisMitchell/m), 4 bytes
```
;“ x
```
For input **n**, this prints the program `**n** x`.
[Try it online!](https://tio.run/##y/3/3/pRwxyFiv///5sDAA "M – Try It Online")
The program `**n** x` sets its argument and return value to **n**, then executes the `x` atom to repeat **n** **n** times, resulting in an array of **n** **n**'s.
[Try it online!](https://tio.run/##y/3/31yh4v9/AA "M – Try It Online")
### Proof of validity
Let **d** be the number of digits of **n**, so the program `**n** x` is **d+2** bytes long.
Python 3 (and, therefore, M) prints an array of **n** **n**'s like `[n, ..., n]`.
Since all **n** copies of `n` are **d** bytes long, the first **n-1** copies of **n** are followed by `,` (**2** bytes), and `[]` surrounds the array (**2** bytes), the output is **nd + 2(n-1) + 2 = nd + 2n = n(d+2)** bytes long.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~19~~ 18 bytes
```
`@G*qVn4+@-}3M'Z"'h
```
This ouputs a program of the form
```
*abc*
Z"
```
followed by a newline, where *`abc`* represents a positive integer. The function `Z"` gives a string of that many spaces, which is implicitly printed with a trailing newline.
[Try it online!](https://tio.run/##y00syfn/P8HBXaswLM9E20G31thXPUpJ/f9/QxMjAA)
Examples:
* Input `142` produces the program
```
993
Z"
```
(plus newline). [Try it online](https://tio.run/##y00syfn/39LSmCtKiet/YPJ/AA) with footer code that changes space to `!` for visibility.
The program length is `7` (including the newline), and its output has `994` characters (`993` spaces and `1` newline), which equals `142*7`.
* Input `143` produces the program
```
1143
Z"
```
with a trailing newline. [Try it online](https://tio.run/##y00syfn/39DQxJgrSonrf2DyfwA) with the same modification.
The program length is `8` (including the trailing newline), and its output has `1144` characters (`1143` spaces and `1` newline), which equals `143*8`.
### Explanation
The most difficult part is, given input `N`, computing the number *`abc`*. Let `f` denote the function "number of digits of". The code finds the first positive integer `K` that satisfies
```
f(K*N-1)+4 = K
```
The `1` above accounts for the trailing newline which is output by the produced program after the string of spaces, and the `4` accounts for the length of the `Z"` statement and the two newlines in the produced program. The number *`abc`* to be included in the output program is then `K*N-1`.
In the examples above:
* For `N=142` the obtained `K` is `7`, which gives `K*N-1 = 993`.
* For `N=143` the obtained `K` is `8`, which gives `K*N-1 = 1143`.
### Commented code
```
` % Do...while
@ % Push iteration index. This is a potential K
G % Push input, N
* % Multiply
q % Subtract 1
V % Convert to string (*)
n % Number of characters
4 % Push 4
+ % Add
@ % Push K
- % Subtract. This is the loop condition. If 0 (meaning the
% condition f(K*N-1)+3 = K is fulfilled) the loop is exited
} % Finally (execute on loop exit)
3M % Push string (*) from automatic clipboard
'Z"' % Push string 'Z"'
h % Concatenate horizontally
% End (implicit). Display with trailing newline (implicit)
```
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 68 bytes
```
f={format["g={i=0;s={};while{i<%1}do{i=i+1;s=s+{ }+g};s}",_this]}
```
A function that takes a number *n* as input and outputs a function *g* that produces output with *n* times the length of its own source code.
**Example:**
```
3 call f
```
outputs
```
g={i=0;s={};while{i<3}do{i=i+1;s=s+{ }+g};s}
```
which outputs
```
i=0;s={};while{i<3}do{i=i+1;s=s+{ }+g};s i=0;s={};while{i<3}do{i=i+1;s=s+{ }+g};s i=0;s={};while{i<3}do{i=i+1;s=s+{ }+g};s
```
### Alternative version (~~75~~ 71 bytes):
```
f={format[{g={i=0;s={};while{i<%1}do{i=i+1;s=s+"g={"+g+"}"};s}},_this]}
```
Outputs a function *g* which outputs its own source code *n* times.
**Example:**
```
3 call f
```
outputs
```
g={i=0;s={};while{i<3}do{i=i+1;s=s+"g={"+g+"}"};s}
```
which outputs (when called with `hint call g`)
[](https://i.stack.imgur.com/kTeRS.jpg)
[Answer]
# [Befunge-98](https://pythonhosted.org/PyFunge/), ~~22 21~~ 14 bytes
Edit: Didn't see that the output has to be printable ASCII only. Funnily enough, this saved a byte.
Edit: I was being stupid. What do you do if you to do something X times, N times? You do it X times N, times, duh.
Edit: Just realised this won't work with 10 or 13, because they print newlines, so I changed to the alternate version:
```
"&3*1-''5k,@.k
```
which can't print newlines.
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XUjPWMtRVVzfN1nHQy/7/31ABAA) Try it N = [1](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XZ1LI1nP4/x8A), [2](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XZ1XI1nP4/x8A), [3](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X51DI1nP4/x8A) and [100](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X11bI1nP4/x8A)
The NX program is in the form:
```
'N k.@
```
Where N is the char code of the inputted number. Prints N\*3\*("0 ")
### Old version:
```
"&''fk,@.k7p01-1_@#!:
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XUlNXT8vWcdDLNi8wMNQ1jHdQVrT6/99QAQA "Befunge-98 (PyFunge) – Try It Online") Try N = [1](https://tio.run/##S0pNK81LT9W1tPj/X51RwUpR2SHeUNfQoMA8W@//f0MDAwA "Befunge-98 (FBBI) – Try It Online"), [2](https://tio.run/##S0pNK81LT9W1tPj/X51JwUpR2SHeUNfQoMA8W@//f0MDAwA "Befunge-98 (FBBI) – Try It Online"), and [3](https://tio.run/##S0pNK81LT9W1tPj/X51ZwUpR2SHeUNfQoMA8W@//f0MDAwA "Befunge-98 (FBBI) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
f n="'a'<$[1.."++show(n*(10+length(show$n*10+10)))++"]"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1ZJPVHdRiXaUE9PSVu7OCO/XCNPS8PQQDsnNS@9JEMDJKKSpwUUMDTQ1NTU1laKVfqfm5iZp2CrUFBaElxS5JOnoKKQpmD8HwA "Haskell – Try It Online")
[Answer]
## JavaScript (ES6), 51 bytes
```
n=>`_=>("${n}"[r="repeat"](2)+" "[r](41))[r](${n})`
```
Outputs (e.g.) `_=>("42"[r="repeat"](2)+" "[r](38))[r](42)` which has length 42 and whose output has length 1764.
[Answer]
# [Zsh](https://www.zsh.org/), ~~28~~ 22 bytes
```
repeat $1 echo rev \$0
```
For input **n**, this prints **n** copies of `rev $0` and a linefeed.
[Try it online!](https://tio.run/##qyrO@P@/KLUgNbFEQcVQITU5I1@hKLVMIUbF4P///@YA "Zsh – Try It Online")
The generated programs print **n** reversed copies of themselves.
[Try it online!](https://tio.run/##qyrO@P@/KLVMQcWAi3jq/38A "Zsh – Try It Online")
[Answer]
# Python 2, 56 bytes
```
f=lambda n:"print`f`*"+`n*n`+','+'#'*(33*n-9-len(`n*n`))
```
Creates a string of the form
```
print`f`*<number>################...#####
```
where the number is `n^2` and there are enough #s to make the string `33n` characters long. Depending on the way your OS stores memory addresses, the `33` might need to change.
There's also that annoying `+','` in the middle so that it conforms to the newline requirement; if anyone can figure out how to shorten that it would be much appreciated.
There's a less iffy version with 58 bytes in the following form:
```
f=lambda n:"print`id`*"+`n*n`+','+'#'*(22*n-10-len(`n*n`))
```
which functions identically and more reliably, but at the cost of using "id" instead of "f" as the function and having to subtract 10 instead of 9, using an extra character.
An explanation of this technique is given [here](https://codegolf.stackexchange.com/a/59438).
[Answer]
# [Clean](https://clean.cs.ru.nl), 117 bytes
```
import StdEnv
$l n="import StdEnv\nf={#'0'\\\\_<-[1.."+++fromInt n+++"],_<-[0.."+++fromInt l+++"]}"
```
#
```
\n= $(size($99n))n
```
[Try it online!](https://tio.run/##VcnBCoJAFIXhvU9xGQUVU6yFIDS7WgjtXGbFpE4MzFzDmYKKXr2btfOsfs7X6l4gmaG76R6MUEjKXIfRQe26Ld69QANyNvsalPzlh3nYTDut0/0yy1iSJHIcTIUOcGp2WPwkn4v@y5tR7cToPB8kcGiQQxBZ9eyjoCwxjtHjE0SrY5HH9GmlFhdL6ZnSakebBwqjWvsF "Clean – Try It Online")
An anonymous function taking `Int` and giving the source for a function returning a string of the requisite length, having the signature `f :: String`. While this is technically reliant on the native integer type having less than 256 bits, I don't believe that this qualifies as abuse thereof.
] |
[Question]
[
**Input:**
A Date (containing `dd`, `MM` and `yyyy`). A date-object, or three separate integers are also valid as input.
**Output:**
Each part (`dd`, `MM` and `yyyy`) individually reverted and than rounded to the nearest valid date.
For example (in the format `dd-MM-yyyy`):
`21-10-2016` becomes `12-01-6102`
**Challenge rules:**
* Only `dd`, `MM`, `yyyy` is valid, but the order and which separate-symbols you use is your own choice.
So these are some valid format examples: `dd-MM-yyyy`; `MM/dd/yyyy`; `yyyy MM dd`; `ddMMyyyy`, etc.
And these are some invalid format examples: `dd MMM yyyy`; `dd-MM-'yy`; etc.
* You can also choose to just input a Date-object if your language supports it or three separate integer parameters, instead of the string representing a date.
* **Please state which date-format you've used!** (And the input and output must be in the same format.) It is also allowed to output a Date-object, as long as it can handle all test cases and the challenge rule below.
* The Julian to Gregorian Calendar transition is ignored for this challenge. So [`1582`](https://en.wikipedia.org/wiki/Adoption_of_the_Gregorian_calendar) is just a valid reversed year for `2851`.
See Challenge info / tips for all valid years, months and days.
* Since you cannot have February as reversed of any other month, you don't have to worry about leap years.
**All reversed years, months and days:**
* The year can always be reversed without a problem, reaching from **0001** (reversed of `1000`) to **9999** (remains `9999`). (So `0000` isn't a valid input, and there are also no test cases for it.)
* The only months you'll have reversed are: **January** (reversed from October / `10`); **October** (reversed from January / `01`); **November** (remains November / `11`); and **December** (reversed from every other month / `02`-`09`, `12`).
* The only days you'll have reversed are: **01** (reversed from `10`), **02** (reversed from `20`), **03** (reversed from `30`), **10** (reversed from `01`), **11** (remains `11`), **12** (reversed from `21`), **13** (reversed from `31`), **20** (reversed from `02`), **21** (reversed from `12`), **22** (remains `22`), **30** (reversed from `03` or the same as *31* for November!), **31** (reversed from `04`-`09` / `13`-`19` / `23`-`29`).
**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](http://meta.codegolf.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 statements/output, full programs. Your call.
* [Default Loopholes](http://meta.codegolf.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.
**Test cases (`dd-MM-yyyy` as format):**
```
21-07-2016 -> 12-12-6102
12-11-1991 -> 21-11-1991
01-01-2000 -> 10-10-0002
27-08-1875 -> 31-12-5781
18-12-2010 -> 31-12-0102
13-01-1981 -> 31-10-1891
04-11-1671 -> 30-11-1761 // Semi-tricky case, since November has 30 days
28-11-2036 -> 30-11-6302 // Semi-tricky case, since November has 30 days
14-06-1855 -> 31-12-5581
30-10-9999 -> 03-01-9999
01-01-2851 -> 10-10-1582
```
[Answer]
## CJam, 24 bytes
```
qS/Wf%[_1=:=31^sCs].e<S*
```
I/O format is `dd mm yyyy`.
[Try it online!](http://cjam.tryitonline.net/#code=cU4vezpROwoKUVMvV2YlW18xPTo9MzFec0NzXS5lPFMqCgpdbn0v&input=MjEgMDcgMjAxNgoxMiAxMSAxOTkxCjAxIDAxIDIwMDAKMjcgMDggMTg3NQoxOCAxMiAyMDEwCjEzIDAxIDE5ODEKMDQgMTEgMTY3MQoyOCAxMSAyMDM2CjE0IDA2IDE4NTUKMzAgMTAgOTk5OQowMSAwMSAyODUx)
Same byte count, I/O format `mm dd yyyy`:
```
qS/Wf%_0=:=1231^s2/.e<S*
```
[Try it online!](http://cjam.tryitonline.net/#code=cU4vezpROwoKUVMvV2YlXzA9Oj0xMjMxXnMyLy5lPFMqCgpdbn0v&input=MDcgMjEgMjAxNgoxMSAxMiAxOTkxCjAxIDAxIDIwMDAKMDggMjcgMTg3NQoxMiAxOCAyMDEwCjAxIDEzIDE5ODEKMTEgMDQgMTY3MQoxMSAyOCAyMDM2CjA2IDE0IDE4NTUKMTAgMzAgOTk5OQowMSAwMSAyODUx)
### Explanation
```
qS/ e# Read input, split around spaces.
Wf% e# Reverse each component.
[ e# Set marker for new list.
_1= e# Duplicate reversed strings, extract reversed month.
:= e# Check for equality of the characters. This gives 1 for
e# November (11) and 0 for everything else.
31^ e# XOR the result with 31, giving 30 for November and 31
e# for everything else.
s e# Convert the result to a string, "30"/"31".
Cs e# Push 12, convert to string, "12".
] e# Wrap "30"/"31" and "12" in a list.
.e< e# Element-wise minimum. This clamps the day and month to their
e# respective maxima.
S* e# Join the result with spaces.
```
The other version works similarly, except that we start from the integer `1230` or `1231` before converting it to `["12" "30"]` or `["12" "31"]`.
[Answer]
# Pyth, ~~55~~ ~~53~~ ~~46~~ ~~43~~ 41 bytes
```
~~APJ\_Mczd=HhS,12sH=GhS,sGC@."❤❤ó»î"H%"%02d %02d %s"[GHeJ~~
~~APJ\_Mczd=hS,12sH=hS,sGC@."❤❤ó»î"H%"%02d %02d %s"[GHeJ~~
~~APJ\_Mcz\-%"%02d %02d %s"[hS,sGx31q11sHhS,12sHeJ~~
~~APJ\_Mczdjd[>2+\0hS,sGx31q11sH>2+\0hS,12sHeJ~~
APJ_Mczdjd.[L\02[`hS,sGx31q11sH`hS,12sHeJ
```
where `❤❤` were two unprintables, respectively U+001C and U+001F.
[Test suite.](http://pyth.herokuapp.com/?code=APJ_Mczdjd.%5BL%5C02%5B%60hS%2CsGx31q11sH%60hS%2C12sHeJ&test_suite=1&test_suite_input=21+07+2016%0A12+11+1991%0A01+01+2000%0A27+08+1875%0A18+12+2010%0A13+01+1981%0A04+11+1671%0A28+11+2036%0A14+06+1855%0A30+10+9999%0A01+01+2851&debug=0)
[Answer]
## [Convex](https://github.com/GamrCorps/Convex), 23 bytes
Byte count assumes CP-1252 encoding.
```
qS/Wf%_1=:=31^sCs¶.e<S*
```
I/O format is `dd mm yyyy`.
[Try it online!](http://convex.tryitonline.net/#code=cU4vezpROwoKUVMvV2YlXzE9Oj0zMV5zQ3PCti5lPFMqCgpdb05vfS8&input=MjEgMDcgMjAxNgoxMiAxMSAxOTkxCjAxIDAxIDIwMDAKMjcgMDggMTg3NQoxOCAxMiAyMDEwCjEzIDAxIDE5ODEKMDQgMTEgMTY3MQoyOCAxMSAyMDM2CjE0IDA2IDE4NTUKMzAgMTAgOTk5OQowMSAwMSAyODUx)
This is a direct port of [my CJam answer](https://codegolf.stackexchange.com/a/86709/8478). Convex is heavily based on CJam, and therefore the only difference is the use of Convex's `¶` operator which wraps the top two stack elements in a list, saving a byte over `[...]`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~32~~ 33 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
⍕¨{⍵-3↑31 11≡2↑⍵}31 12 1E4⌊⍎∊⍕⌽¨⎕
```
I/O is list of three strings (`'dd' 'mm' 'yyyy'`).
[TryAPL](http://tryapl.org/?a=%u2191%7B%u2355%A8%7B%u2375-3%u219131%2011%u22612%u2191%u2375%7D31%2012%209999%u230A2%u2283%u2395VFI%u220A%u2355%u233D%A8%u2375%7D%A8%28%2721%27%20%2707%27%20%272016%27%29%28%2712%27%20%2711%27%20%271991%27%29%28%2701%27%20%2701%27%20%272000%27%29%28%2727%27%20%2708%27%20%271875%27%29%28%2718%27%20%2712%27%20%272010%27%29%28%2713%27%20%2701%27%20%271981%27%29%28%2704%27%20%2711%27%20%271671%27%29%28%2728%27%20%2711%27%20%272036%27%29%28%2714%27%20%2706%27%20%271855%27%29%28%2730%27%20%2710%27%20%279999%27%29%28%2701%27%20%2701%27%20%272851%27%29&run), but note that `⎕` (prompt for input) has been replaced with `⍵` and the entire line enclosed in `{`...`}` to enable online testing, and `⍎` (execute expression) has been replaced with `2⊃⎕VFI` (verify and fix input) because execution of arbitrary code is blocked.
[Answer]
# Python 3, 82 bytes
```
lambda x:[min(x[0][::-1],['31','30'][x[1]=='11']),min(x[1][::-1],'12'),x[2][::-1]]
```
An anonymous function that takes input, via argument, of the date as a list of strings of the form `['dd', 'mm', 'yyyy']` and returns the validated reversed date in the same format.
**How it works**
Python compares characters and strings by their Unicode code-points. This means that any comparison on two or more integers returns the same as that comparison on those integers as strings. Hence, calling `min` on two integers as strings returns the smallest integer as a string; by taking the reversed date-part as one argument and the maximum value as another, the day and month are clamped to the desired range. The date-parts are reversed by indexing with steps of `-1` (`[::-1]`), and the maximum value for the month is changed from `'31'` to `'30'` if the month is November by indexing into a list with the Boolean result of a conditional.
[Try it on Ideone](https://ideone.com/hLOblm)
[Answer]
# C# ~~314~~ ~~305~~ ~~299~~ ~~249~~ ~~232~~ 223 Bytes
```
using System.Linq;string f(int d,int m,int y){Func<int,string>r=i=>string.Concat((""+i).PadLeft(2,'0').Reverse());Func<string,int,string>x=(j,k)=>int.Parse(j)>k?""+k:j;return x(r(d),m==11?30:31)+"-"+x(r(m),12)+"-"+r(y);}
```
Thanks to @KevinCruijssen for pointing out that I could shorten my variable declaration, which also made aliasing string able to save some bytes.
Saved 50 bytes storing the reversing function for reuse and another 13 by doing the same for the rounding and removing the variable declarations.
Last update makes aliasing string no longer a byte saver.
### Ungolfed Version:
```
using System.Linq;
string dateReverse(int day, int month, int year)
{
//setup a resuable function to reverse
Func<int, string> reverse = intToReverse => string.Concat((""+intToReverse).PadLeft(2, '0').Reverse());
//another function for rounding
Func<string, int, string> round = (strToRound, maxVal) => int.Parse(strToRound) > maxVal ? "" + maxVal : strToRound;
//Join the strings into the "dd-mm-yyyy" date format
return
//Round down the day value, if november cap to 30 otherwise cap to 31
round(reverse(day), month == 11 ? 30 : 31) + "-" +
//Round the month down
round(reverse(month), 12) + "-" +
//we can use the reverse function here too and pad left just won't do anything
reverse(year);
}
```
[Test it here](https://dotnetfiddle.net/Z6DMNg)
[Answer]
# Ruby, ~~92~~ 84 + 1 (`-p` flag) = ~~93~~ 85 bytes
Uses `-` as the seperator.
```
d,m,y=chomp.split(?-).map &:reverse
$_=[[d,m=="11"?"30":"31"].min,[m,"12"].min,y]*?-
```
[Answer]
## Pyke, 29 bytes
```
F_bw-o^tDI]SX(mhj_Xjth~%R@]Sh
```
[Try it here!](http://pyke.catbus.co.uk/?code=F_bw-o%5EtDI%5DSX%28mhj_Xjth%7E%25R%40%5DSh&input=%5B%222016%22%2C%2207%22%2C%2224%22%5D%0A&warnings=0)
I can definitely see this being golfable
[Answer]
# Javascript, ~~106~~ ~~105~~ 94 bytes
```
d=>d.split`,`.map((a,b,r)=>(e=[...a].reverse().join``,f=!b?r[1]==11^31:b<2&&12,f&&f<e?f:e))+''
```
[Test suite](https://repl.it/CgdX/2) (rev. 3)
**Explanation**
```
d=>d.split`,` // split into sections by `,`
.map((a,b,r)=>( // map each section
e=[...a].reverse().join``, // spread a date section into array and reverse and
// join with `` to get string result
f=!b?r[1]==11^31 // if section being mapped is day (section 0),
// then max (f) is 30 for November(month 11) or else 31
:b<2&&12, // if part being mapped is month (section 1), then max (f) is 12
f&&f<e?f:e)) // if there is a max (f)
// and the max (f) is less than the reversed string (e),
// then return the max (f),
// else return the reversed string (e)
+'' // join all the sections back together with `,`
// (concatenating [] with a string will do this)
```
Thanks @KevinCruijssen for saving 1 byte for `b==1` to `b<2`.
Thanks @Neil for saving 11 bytes by suggesting ES6 template literal and `,` separator.
[Answer]
## Python 2, 154 bytes
```
z=input().split("-");r=[x[::-1]for x in z];z[1]=r[1]if r[1]<'12'else '12';z[0]=r[0]if r[0]<'31'else '30'if z[1]=='11'else '31';z[2]=r[2];print "-".join(z)
```
Takes the input as a string, so quotes need to be specified in the input, e.g. "11-04-2016".
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#íÐÅsË31^12‚øεßт+¦}sθªðý
```
Port of [*@MartinEnder*'s CJam answer](https://codegolf.stackexchange.com/a/86709/52210), so also inputs and outputs as a string in the format `dd MM yyyy`.
[Try it online](https://tio.run/##ATsAxP9vc2FiaWX//yPDrcOQw4Vzw4szMV4xMuKAmsO4zrXDn9GCK8KmfXPOuMKqw7DDvf//MDQgMTEgMTY3MQ) or [verify all test cases](https://tio.run/##NYwxCsJAFET7PcUnllr8@ZtNdqs0nkNQsLCyCAgBBRG0sRFLGzsLQbAR0thk@4BXyEXWjeA0MwxvZllOZ4t5WK@qIqHucKakqMZh4B/@5PelP2pMIN324uv25a@f3bC5bcq2bu7@6d9hFATEOQkjUxACCM5BcWwRW2YlObEl2NwoRJeeZQXdA3A2sulvluVQYvsorONZSpzFmTFKM4HJRf1/rcEX).
**Explanation:**
```
# # Split the (implicit) input by spaces
# i.e. "04 11 1671" → ["04","11","1671"]
# i.e. "20 01 2000" → ["20","01","2000"]
í # Reverse each string
# i.e. ["04","11","1671"] → ["40","11","1761"]
# i.e. ["20","01","2000"] → ["02","10","0002"]
Ð # Triplicate this list
Ås # Pop one of them, and push it's middle element (the months)
# i.e. ["40","11","1761"] → "11"
# i.e. ["02","10","0002"] → "10"
Ë # Check if the digits are the same (1 for 11; 0 otherwise)
# i.e. "11" → 1 (truthy)
# i.e. "10" → 0 (falsey)
31^ # Bitwise-XOR with 31 (30 for November, 31 for other months)
# i.e. 1 → 30
# i.e. 0 → 31
12‚ # Pair it with 12
# i.e. 30 → [30,12]
# i.e. 31 → [31,12]
ø # Zip/transpose; swapping rows and columns
# (implicitly removes year)
# i.e. ["40","11","1761"] and [30,12] → [["40",30],["11",12]]
# i.e. ["02","10","0002"] and [31,12] → [["02",31],["10",12]]
ε } # Map each pair to:
ß # Get the minimum (implicitly converts to integer unfortunately)
# i.e. [["40",30],["11",12]] → [30,11]
# i.e. [["02",31],["10",12]] → [2,10]
т+ # Add 100
# i.e. [30,11] → [130,111]
# i.e. [2,10] → [102,110]
¦ # Remove the first character
# i.e. [130,111] → ["30","11"]
# i.e. [102,110] → ["02","10"]
s # Swap so the triplicated list is at the top of the stack again
θ # Pop and only leave it's last element (the year)
# i.e. ["40","11","1761"] → "1761"
# i.e. ["02","10","0002"] → "0002"
ª # Append it to the list
# i.e. ["30","11"] and "1761" → ["30","11","1761"]
# i.e. ["02","10"] and "0002" → ["02","10","0002"]
ðý # Join the list by spaces (and output implicitly)
# i.e. ["30","11","1761"] → "30 11 1761"
# i.e. ["02","10","0002"] → "02 10 0002"
```
] |
[Question]
[
You wake up and find out that your computer has been stolen! You have a few sensors and scanners, but unfortunately, the footage is incomplete, so you want to find and rank your suspects for further investigation.
Your computer is a rectangle, and your camera caught a bunch of people walking around with packages; however, there's a gift shop near your house so you can't be sure (and the camera footage doesn't seem to show if anyone went into your house). Based on that information, you want to determine who most likely stole your computer.
## Challenge
You will be given the dimensions of your computer and a list of (rectangular) gifts at the store by their dimensions. You will also be given a list of packages that people are holding as rectangle dimensions.
You are then to rank them by suspicion. A gift is said to fit in a package if its width and height are less than or equal to the package's width and height respectively, or height and width respectively. That is, basically whether or not it is a smaller rectangle, but with right-angle rotations allowed. If someone's package cannot fit your computer, then they have absolutely **no suspicion**. Otherwise, the more gifts they can fit, the less suspicious (basically, if they're carrying a larger package, it's more likely that they are just carrying a large gift rather than your computer).
(A formal way to describe this I guess would be: given a rectangle A, a list of rectangles B, and a list of rectangles C, sort C in increasing order of how many rectangles in B fit in each item, or infinity if A cannot fit in it, sort it to the end; then, group equal elements)
## Input
The input needs to contain the dimensions of your computer, the dimensions of all of the gifts, and the dimensions of each person's package. You can take these in any reasonable format.
Out of all gifts and your computer, no two items will have the same dimensions. No two people will have the same package dimensions. Both of these conditions are true even with rotation (so, no 2x3 and 3x2 gifts).
## Output
The output should be a two-dimensional list, where each sub-list contains people with the same suspicion level (order does not matter within a sub-list), and the sub-lists are sorted by suspicion level either up or down. You can output this in any reasonable format; as a 2D list, lines of lists, lines of space-separated values, etc.
You may either represent a person by their package dimensions (in either order, because it's unique), or by their index in the input list (you can choose any n-indexing).
You may either output all totally unsuspicious people as the last sublist or exclude them entirely (must be consistent). You may not have any empty sublists.
## Worked Example
Let your computer have dimensions `[3, 5]`. Let the gifts have dimensions `[2, 4], [2, 5], [3, 4], [3, 6], [4, 5], [4, 6]`. Let the people have packages of dimensions `[2, 4], [3, 5], [4, 6], [2, 7], [3, 6], [4, 5]`.
First, let's see who isn't suspicious. `[2, 4]` and `[2, 7]` cannot fit `[3, 5]` because the width is too small (`2 < min(3, 5)`).
Next, let's count.
`[3, 5]` can fit `[2, 4], [2, 5], [3, 4], [3, 5]`. Thus, their suspicion is 4 (3 gifts plus your computer), which turns out to be the most suspicious.
`[3, 6]` can fit `[2, 4], [2, 5], [3, 4], [3, 5], [3, 6]`, so their suspicion is 5. `[4, 5]` can fit `[2, 4], [2, 5], [3, 4], [3, 5], [4, 5]`, so their suspicion is also 5.
`[4, 7]` can fit `[2, 4], [2, 5], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6]`, so their suspicion is 7. Since they could be carrying any of the gifts, they are the least suspicious.
Thus, a valid output would be `[[1], [4, 5], [2], [0, 3]]` (including the non-suspicious people in at the end in a sublist, in 0-indexing).
A reference implementation is provided [here](https://tio.run/##nVNLj9owED7Hv2KaC0mXouWxrYRKpR5762EvVZSDIQ5YMXbkRyFC/HY6dh4bVtuqbYSs8Xge33zzUTf2oOTydtszK7hksAFBj9uCrsG6WrDEKG1ZkRxpnXBpp8Bl7WySzkwtuE3iKcQpfoTs1BEfmMYCXakkJV0wIXteWoNPWU7I6cAFg2ft2JpEVjd4RuF9RuuaySIZ8lMSsfOO1daHbDWjFSE13VV0z/5UrA/5u3oax0rK@IdyGvohJgYKfmTScCUNUM3g0j9lj/kVts3IMc@vMY5YctthKpWG8xQa5Ap6LNhxp5z0IY8k4iWc4TOMagLmNGPXPPcg@5xSKIpsc1nGfghh/LiRb7THTvvQKnDo3V3WwwabfMF1nIHKAqt7uyERAu2ZCYGIXekibO5ybdHzKaZiSSbdkWlqWYJJKdYOgdk5x9hgzpDbBBFkeQoPkPG8JzT@JtsIUCUclbFgFQhG0TDO1HzHlTNrHKYN9xhcxx8aixGTlQfSqTBUDDjcMEMLqcrTQGsFm3u2giBaSM8HBqUSQp243EPNFOobdlRKZcFvrxlLwHe1B8Z1v8JAoj24Vg8@h@JPiFfzDMvxY7yBMeoF9zs0AcqluoZ9XiZmAu8hqeDdBubp1aOiRcEtCtMzegc5tA/r82F9z/Wo53emDSZe@HUNl16auLVB1GNfq@toWFDH4lccufRtcbH2boaTcqKALYOfVPACkACENVpy/OFfv7E@WgOLvvgG1@K1L8uGSVCs4Q/pOdHq1N7QCBw5m/9/6iJPb7flFJ4IWUxh5Y8nsvQWHh/Jyl9X3mqfl8Mdr59eYn4B). The input contains three sections; the first is the computer, the second is the gifts, and the third is the packages. The output contains a brief explanation of each suspicion level, and at the end, it provides four valid output formats. These are not the only valid ones, but they would be valid.
## Rules and Specifications
* No dimensions will be smaller than 1, and all dimensions are integers. There may be no people or no gifts.
* You may demand the dimensions to be inputted in any order. Since the orientation does not matter anywhere in this challenge, you can choose any reasonable and consistent way of inputting these two numbers.
* [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), as always.
* Since your computer was stolen, you'll need to write and run your code by hand. Since shorter code runs faster obviously1, and you need to do it manualy, you need to make your code as short as possible. Thus, the shortest code in bytes wins (this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge).
1this is a joke
[Answer]
# [Python 2](https://docs.python.org/2/), ~~143~~ ~~120~~ 119 bytes
-20 bytes by assuming the smaller dimension is always given first.
-1 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!
Takes input as `computer, gifts, packages` from *STDIN*. Outputs as a list of of lists of package dimensions in descending suspicion levels. Does not include unsuspicious packages.
```
c,g,p=input()
r=[[]for _ in g+p]
for y in p:A,B=y;x=[a-A<1>b-B for a,b in[c]+g];r[sum(x)]+=[y]*x[0]
print filter(len,r)
```
[Try it online!](https://tio.run/##ZU5BboMwELzzipV6CBRHaoE0EokrJYd@YmVVBBFqCWxrbUv49RQHDo16mpmd3dkxwf1oVcxzy3pmuFTGuzRLiCOKuyb4Bqmgz41IogpRmfrCrjycJo7N/nJ@/7ztrxDdht0WH1uR9@JEaP2YTpnIOQbxOuGbSAxJ5eAuB9dROnSKUTa/gKHOuQDau@V3vS5tq7sv0iOM2jpwGoauWYj11shWam/r3aNUT9qbWOwpuE4A1pCHP2PJ4CAYIBYMqkiKbVBuesGPiNU2r6J@uij/OmvC8d@l@AU "Python 2 – Try It Online")
[Answer]
# JavaScript (ES2021), 113 bytes
```
(d,g,p)=>p.map(([W,H],i)=>(o[-[d,...g].map(([w,h])=>t+=w>W|h>H&&h>W|w>H,t=0)[0]|t]??=[]).push(i),o=[])&&o.flat(0)
```
No TIO available.
<https://jsfiddle.net/2s9xobkd/>
Based on Arnauld‘s solution.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),~~269~~ ~~252~~ 248 bytes
```
([x,y],p,g)=>[...(h=p.map(([X,Y],i)=>[i,(X>Y?Y:X)<(x>y?y:x)||g.map(([W,H])=>t+=(X>W|Y>H)&(Y>W|X>H),t=1)&&t]).sort((a,b)=>a[1]-b[1]).reduce((r,a,i)=>i&&a[1]==(I=r[r.length-1])[0][1]?(I.push(a),r):[...r,[a]],[]).map(x=>x.map(y=>y[0]))).slice(1),h[0]]
```
Very slightly less messy.
[Try it online!](https://tio.run/##TU7LboMwEPwVTmhXXaySVyVUm2vyBQFZPjgJASoKyJAKJP6dLhFVerFnZ2dm58v@2O7qyrYP6uaWzXc5gx5oNNRSjlJpIQQUshXftgXQCaWGyoUvCRKVxmmU4CcMaozHaMBpylfhmY6GZf2bZNl5StURfUgZJYyolyH6fm9QdI3rASxdWGx1aIILPyhcdntcMwBH9nmu9P1lKyWcpNNOVFmd90XAUv1ueBHDSbSPrgCL5DBaWjvS1hjSnLZUGqQanmCUamQTIh@vSj4SIhVMmPna1F1TZaJqcriD3pK3Z7/ekLcz5K2zp3fkHZaf@Y@VP6z83vw3bFbD9hXwEv4FcZH5Fw "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript (ES10), ~~129~~ 124 bytes
*-5 bytes by swithing to ES10 and using `.flat(0)`, as suggested by @tsh*
Expects `([computer_w, computer_h], gifts, packages)`.
```
(d,g,p)=>p.map(([W,H],i)=>(o[g.map(y=>t+=3*(F=([w,h])=>w>W|h>H&&h>W|w>H)(d)|!F(y),t=0)|t]=o[t]||[]).push(i),o=[])&&o.flat(0)
```
[Try it online!](https://tio.run/##ZYy9DoIwFIV3n6Iu5F69EiKoUzsa3oCh6UBEfgzaRqrEpO@OrToYnb7zk3NO5b0cDtfO2NVFV8ep5hNU1JBBLkx8Lg2ALChX1PkAtGxe2YMLu@TpAvYc5Eit8uUoCteKPIpaL0aRI1To5nt4IFmeoLOKa2mVc1JhbG5DCx2S5t5FkY7rvrSQ4HTQl0H3x7jXDdQwY0ymxDaKgpJrYpkiFrgJTD/ecxuYffIs@J9N@t29P3Z/WzVDnJ4 "JavaScript (Node.js) – Try It Online")
### How?
For each package with dimensions \$(W,H)\$ and for each gift with dimensions \$(w,h)\$ among \$N\$ distinct gifts:
* we add 3 points to the package score if it can't fit the computer
* we add 1 point to the package score if it can fit both the computer and the gift
* we don't add any point to the package score if it can fit the computer but not the gift
So the score of a package that can't fit the computer is always \$3N\$ and the score of a package that can fit it is in \$[0\dots N]\$.
Higher scores are less suspicious.
[Answer]
# [J](http://jsoftware.com/), 36 bytes
Takes `packages` as left argument and `computer, gifts` as right argument:
```
[(</.~/:~.@])[:({."1%~1#.])*/@:>:"1/
```
[Try it online!](https://tio.run/##PY1PC4JAEMXv@ykeRujGtpt/g6FCCDp16iqeRK2gFLVT4FffRsEOj5nH/Oa9p3W0W@FIcKGwA7G2Gufb9WIz72D0aGjUaS4z8r7a8dejv9K53JiUTuT4xkohiubVfoaym1JCxKJ@VEM/mQCRChCrkGeIREW8U4REtGXXN@8/w098S5jdzxwzsSiLewNvISssLQpzvrQ/ "J – Try It Online")
### How it works
* `*/@:>:"1/` a table of "can package fit computer/gift?"
* `1#.]` sum columns: the numbers of computer/gifts a package can fit
* `{."1%~` divided by 0 iff the package cannot fit the computer, otherwise divided by 1. So unsuspicious people get a score of infinity, because that's how division works. :-)
* `</.~` group the people by their scores
* `~.@]` the unique scores
* `/:` order the groups by the unique scores, lower scores first
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
>Ẹ¥þ-SḢ?€Ġ
```
[Try it online!](https://tio.run/##y0rNyan8/9/u4a4dh5Ye3qcb/HDHIvtHTWuOLPj//3@0sY6CaayOQrSRjoIJlAbzjaF8IG0Gok2g4iYg/n@4cmNkYYh2cwxtAA "Jelly – Try It Online")
A dyadic link taking the computer and gifts as a single list `[computer, gift, gift, …]` as the left argument and the packages as the right argument. Returns a list of sublists in in increasing order of suspicion starting with those who are not suspicious at all. Like Jelly does normally, this uses 1-indexing.
## Explanation
```
¥þ | For each pairing of computer/gift and package:
> | - Greater than (vectorises)
Ẹ | - Any
Ḣ?€ | For each package, is the head (i.e. computer) too big?
- | - If yes, -1
S | - If no, the sum of the remaining gifts that don’t fit
Ġ | Group indices by their values in ascending order
```
[Answer]
# [R](https://www.r-project.org/), ~~84~~ 81 bytes
```
function(i,j)split(seq(a=x<-apply(j,2,function(a,s=!colSums(a<i))sum(s/s[1]))),x)
```
[Try it online!](https://tio.run/##TYvBCsIwEER/Jd52YYuY2npJv6JH8RCCgZS0jd0E6tfHELR4mMfAzNuyFarJNi0munUBRxNy8C4CP1@gh101OgT/hokkHS9NPJzM6sc0M2jlEDnNwGe@Xx6ISDtmC7OOm9vBQEuiIyFJXCtLb2sv7GvpKnssc8nhyd/ru1f79u9VA/MH "R – Try It Online")
Takes input as two matrices: \$i\$ holds items (computer dimensions in the first column, gift dimensions in subsequent columns), \$j\$ holds package dimensions.
Output is a list (from most suspicious to non-suspicious) with 1-indexed people IDs.
Thanks for -3 bytes to Nick Kennedy.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
≔Eζ∨±∨›⌊θ⌊ι›⌈θ⌈ιLΦη∨›⌊λ⌊ι›⌈λ⌈ιεW⁻ευ⊞υ⌈ιIEυ⌕Aει
```
[Try it online!](https://tio.run/##hY87D8IgFIX3/oo7XhJcbNWhkzHRxUf3pgOppJAgKhQ1/nmEWt@D0zmXe853Qy2YqfdMeT@1VjYaV@yAVwobg2vesJZjcAvDgzO4klru3A6PhMLDSxKGZ4BdXoHeh0CMLLluWoFzqWJQdBe@ueofV31zOzQneXIWUnGIJGeRU3CEQOGsQPfRyJPCSN3ijNm2@2pYz6XeTpWKrY6Ze1@WKYVRRRMoyyGFrKIQdRQ17eeg46hZ/57F@bOSvq/uiMlPtar84KRu "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔Eζ∨±∨›⌊θ⌊ι›⌈θ⌈ιLΦη∨›⌊λ⌊ι›⌈λ⌈ιε
```
For each package, count the number of gifts that don't fit in the package, or -1 if the computer doesn't fit in the package.
```
W⁻ευ⊞υ⌈ι
```
Sort in descending order of the numbers of gifts that don't fit.
```
IEυ⌕Aει
```
Output the indices of packages grouped by the numbers of gifts that don't fit.
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~594~~ ~~571~~ 472 bytes
```
in linear
mod C is inc LIST{Set{IndexPair}}*(sort IndexPair to D). vars A B C : D
. vars N M P Q : Nat . vars S T U X Y :[D]. op p : D D D ~> D . op f : D D D
~> Nat . eq X empty = X . ceq p(A,S,X(B,C,T)Y)= p(A,S,X(B,T)C Y)if f(C,A,S)>
f(B,A,S). ceq p(A,S,X(B,T)(C,U)Y)= p(A,S,X T(B,C,U)Y)if f(B,A,S)>= f(C,A,S). eq
p(A,S,X)= X[owise]. ceq f((N,M),A,((P,Q),S))= s f((N,M),A,S)if N >= P /\ M >=
Q . eq f((N,M),(P,Q),S)= if N < P or M < Q then s | S | else 0 fi[owise]. endm
```
### Example Session
```
Maude> red p(
> (3, 5),
> ((2, 4), (2, 5), (3, 4), (3, 6), (4, 5), (4, 6)),
> ((2, 4), (3, 5), (4, 6), (2, 7), (3, 6), (4, 5))
> ) .
Advisory: <standard input>, line 7 (mod C): collapse at top of X empty may
cause it to match more than you expect.
result NeList{Set{IndexPair}}: (3,5) (3,6, 4,5) (4,6) (2,4, 2,7)
```
### Ungolfed
```
in linear
mod C is
inc LIST{Set{IndexPair}} * (
sort IndexPair to D
) .
vars A B C : D .
vars N M P Q : Nat .
vars S T U X Y : [D] .
op p : D D D ~> D .
op f : D D D ~> Nat .
eq X empty = X .
ceq p(A, S, X (B, C, T) Y) = p(A, S, X (B, T) C Y) if f(C, A, S) > f(B, A, S) .
ceq p(A, S, X (B, T) (C, U) Y) = p(A, S, X T (B, C, U) Y) if f(B, A, S) >= f(C, A, S) .
eq p(A, S, X) = X [owise] .
ceq f((N, M), A, ((P, Q), S)) = s f((N, M), A, S) if N >= P /\ M >= Q .
eq f((N, M), (P, Q), S) = if N < P or M < Q then s | S | else 0 fi [owise] .
endm
```
This program accepts input as a three-argument function `p`:
1. The dimensions of the computer
2. The set of dimensions of the gifts
3. The set of dimensions of the people's packages
All dimensions must be given smaller side first as comma-separated pairs. The second and third arguments must be comma-separated sets of dimensions (since order doesn't matter and there are guaranteed no repeats).
The output format is list of sets. Each set represents a group of the packages at that "suspicion level". I chose output the dimensions rather than the indexes because Maude doesn't have a reasonable indexed array module.
---
**Edit.** Completely rewritten to save 23 bytes.
Saved 99 bytes by replacing the bespoke dimension module `D` with `IndexPair` from the `linear.maude` standard library.
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
```
(n#p)c g=filter(>[])[[j|j<-p,c?j,sum[1|k<-g,k?j]==i]|i<-[0..n]]
[x,y]?[z,w]=x<=z&&y<=w
```
[Try it online!](https://tio.run/##bY7BCoJAEIbvPsVCEgprVGqB7OY56A2GOYhu26ptYhul@O6m5EGw08f/Df/M3JJnIcqy7x29qtyUSH5VpRG1cwJ0AfIuZ15F0zinz9cddl3BPEmLOEfOFXaKebDdbDSiBR/aYAwtfSP/MN6u1w3j7/6eKM2zh0VS5tUiyZh9ksJclBYWkUtV/VG10sZ2SqGluZFq@NJJowjO2qAre/ApCYfrsKckQEpGhiP9KQ88jAwmH4x5XvDng9@C46KIXw "Haskell – Try It Online")
The relevant function is `(#)`, which takes as input the number of packages `n` and the list of packages `p`, the computer `c` and the list of gifts `g`. It returns a list of groups of packages, sorted from the most suspicious group to the least suspicious group. Each box/item is represented as a list `[w,h]`, with `w<=h`.
] |
[Question]
[
Given positive integers \$w\$ and \$h\$ output \$w\$ columns and \$h\$ rows of text as described below.
The first row begins with 11 `0`s, the second row with 10 `1`s, third with nine `2`s and so on down the the tenth row with two `9`s. On each of these first ten rows, following the initial run of consecutive digits, the next lowest digit appears two times before the second next lowest digit appears two times, with this pattern repeating forever. If a run of `0`s occurs, the digits after it are always `9`s.
Rows below the tenth row are the same as the row immediately above it but shifted to the right by one. The new digit that appears is the same as the previous leftmost digit if it was not next to another instance of itself. Otherwise it is the next highest digit (cycling from 9 back to 0).
The first \$11\times10\$ elements are as follows:
```
00000000000
11111111110
22222222211
33333333221
44444443322
55555544332
66666554433
77776655443
88877665544
99887766554
```
Here is an image with colored text to make the pattern more clear.
[](https://i.stack.imgur.com/sYcT1m.png)
If you need to produce fewer columns/rows then you should simply crop the above text.
If you need to produce more columns/rows than this, existing staircases should be extended. If more columns/rows adds new staircases of consecutive digits, digits should be cyclicly chosen from the integers. Thus for input \$(15,13)\$ the output should be
```
000000000009988
111111111100998
222222222110099
333333332211009
444444433221100
555555443322110
666665544332211
777766554433221
888776655443322
998877665544332
099887766554433
009988776655443
100998877665544
```
Here is an image of this text with color:
[](https://i.stack.imgur.com/BqDCUm.png)
### Rules
* 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.
* You can return a list of lines if you prefer.
* You can return a 2D array of digits or list of lists of digits if you prefer.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) disallowed.
Shortest code wins.
### Test cases
Input is taken as \$(w,h)\$ for the test cases.
```
1,1
0
```
3,2
000
111
20,1
00000000000998877665
11,10
00000000000
11111111110
22222222211
33333333221
44444443322
55555544332
66666554433
77776655443
88877665544
99887766554
15,13
000000000009988
111111111100998
222222222110099
333333332211009
444444433221100
555555443322110
666665544332211
777766554433221
888776655443322
998877665544332
099887766554433
009988776655443
100998877665544
[Answer]
# Python 3, ~~94~~ ~~93~~ ~~78~~ ~~77~~ 74 bytes
```
lambda x,y:[[[(j-i+10)//2%10,j][j+i<9]for i in range(x)]for j in range(y)]
```
-1 byte from [dylnan](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407367_168544)
-15 bytes by returning a list of lists instead of printing from [xnor](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544?noredirect=1#comment407382_168544)
-1 byte by switching the order of the `(j-i+10)//2%10` and `j` parts of the `if`-`else`
-3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/168541/stacked-digit-staircases/168544#comment407390_168544) by changing the `if`-`else` to a list.
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqOjpaI0s3U9vQQFNf30jV0EAnKzY6SzvTxjI2Lb9IIVMhM0@hKDEvPVWjQhMskoUQqdSM/V9QlJlXoqGVpmFoqAM0Q6c4tcBWPSZPXZMLIgOjQSpMdQyNkVT8BwA "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 99 bytes
* Saved a byte thanks to [pizzapants184](https://codegolf.stackexchange.com/users/44694/pizzapants184).
* Saved a byte.
```
s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));}
```
[Try it online!](https://tio.run/##FctLCgIxDADQuwwIyaTFxA@MZMa7lILahR@auBr06tVuH7wcrzm3ZsE1QQkV18uzgi9fViKfq77ebjAMiN1tYbW5dMy3VOEwETiBnYWj4wjCo9EpgtE/RxHc7hA3woj6afdUHoBrAjkG2Xf5AQ "C (gcc) – Try It Online")
[Answer]
# Canvas, 14 bytes
```
[⁷{¹∔⁶+»¹m◂@]]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXUyMDc3JXVGRjVCJUI5JXUyMjE0JXUyMDc2JXVGRjBCJUJCJUI5JXVGRjREJXUyNUMyJXVGRjIwJXVGRjNEJXVGRjNE,i=MTMlMEExNQ__,v=4)
While making this I noticed in several places I had negative modulos in Canvas (here, it meant that `»` - floor div 2 - rounded towards 0). The previous 18 byte answer that worked without fixes doesn't work anymore (because I only save `main.js` between versions) but [TIO still has the old version](https://tio.run/##AUIAvf9jYW52YXP//@@8u@KBt@@9m8K54oiU4oG277yL77ya77yQ77yc77yNwrvCue@9jeKXgu@8oO@8ve@8vf//MTMKMTU)
Explanation:
```
[ ] for 1..input
⁷{ ] for 1..2nd input
¹∔ subtract from this loop counter the outer loops one
⁶+ add 12
» divide by 2, rounded to -∞
¹m minimum of that & the outer loops counter
◂@ in the string "0123456789", get the xth char, 1-indexed
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 17 bytes
```
Eη⭆θ﹪⌊⟦ι÷⁺⁻ιλχ²⟧χ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjQ0chuATISwdxCnUUfPNTSnPyNXwz8zJzS3M1ojN1FDzzSlwyyzJTUjUCckqLQVJAEiieo6mjYGgAJIw0YyFMELD@/z/a0BTINY79r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Height
E Map over implicit range
θ Width
⭆ Map over implicit range and join
⁻ιλ Subtract column from row
⁺ χ Add 10
÷ ² Integer divide by 2
ι Current row
⌊⟦ ⟧ Take the minimum
﹪ χ Modulo by 10
Implicitly print each row on its own line
```
Edit: Saved 3 bytes by switching to @dzaima's algorithm.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
_@þ:2+6«"J$’%⁵
```
A dyadic link taking \$w\$ on the left and \$h\$ on the right which yields a list of lists of digits.
**[Try it online!](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX///@Gpv8NjQE "Jelly – Try It Online")** Or see a (post-formatted) [test-suite](https://tio.run/##y0rNyan8/z/e4fA@KyNts0OrlbxUHjXMVH3UuPX/4eX6kSqPmtZkPWrcd2jboW3//0dHG@oYxupEG@sYAUkjAzDHEChmAKJNdQyNY2MB "Jelly – Try It Online").
### How?
```
_@þ:2+6«"J$’%⁵ - Link: integer w, integer h
þ - outer product using (i.e. [[f(i,j) for i in 1..w] for j in 1..h]):
_@ - subtraction with swapped arguments (i.e. f(i,j): j-i)
- e.g. the 4th row is [3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,...]
:2 - integer divide by two (vectorises)
- [1, 1, 0, 0,-1,-1,-2,-2,-3,-3,-4,-4,-5,-5,-6,...]
+6 - add six (vectorises)
- [7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0,...]
$ - last two links as a monad:
J - range of length -> [1,2,3,...,h]
" - zip with:
« - minimum (vectorises)
- [4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 2, 1, 1, 0,...]
’ - decrement (vectorises)
- [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0,-1,...]
⁵ - literal ten
% - modulo (vectorises)
- [3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 1, 0, 0, 9,...]
```
[Answer]
# [Kotlin](https://kotlinlang.org), 78 bytes
```
{w:Int,h:Int->List(h){r->List(w){c->if(c<11-r)r%10
else(r+9*((c-9+r)/2))%10}}}
```
[Try it online!](https://tio.run/##3Vbbbtw2EH3nVzBGC0iJsruym8Q2kgDpBW2AACmSAEWR@oErUSsiEqmSVDZbw9/RD@qHpWeG2rWcC@C3AiV8EYdznzNDvnOxM/bj8q78wWsVdS0b52VsTZCVq7XcuK6RVau6TtuNPhdtjEM4Xy7pkM4WIarqnf4AFpwvKtcv/xx1iMbZsCwfnj74rhSvmaWWtdmYKCFgfKWCDkL8bN5rKwcXTMSXNDbqjfZBboWytWylG@MwRrmFL93Y2yCZLIR32yBdI6P@EKUKstah8mYNG2vdue1CiDetlo3xIUrwgroxkN6a2MqylKtQIEQtg64cFBJHOlrJko@MrxPFGqvlcbIbnHRW1m5rWZh/tQXTQT5unTwLC/nSSq2qlj1sddh7Am7ihYXGdXDT2A1rMRbhq0760ZIIfIJjI2eEUzZ5aylYiCG7UyrVMGiFdJHdaHodECjKp@fB3UKqmLynog8qRu3hpwZTJA9J4XvtF/J5I9XexxXSX1Wjn1xLbkrVQFaSCfiguq3aBcqHEK@oXlyaT9Km9s6qXlMh6Zvopu91bYDHbifV2hE2olwDCqE1DaE0usRrNi0OdqiMXsg3nKXtFGds1XWwJnxmZ0Bcxo1BdrqJvTvkxzRkbAsu62LKH6wpbFqKzgLAttKUBcSs0QLyJZ1sTWAvJ0ss18K968Rn1a7qOKXe9fJMrtEWpHqV3wBsWf7zd7kSQne6R6JCymaYQBPOhVhdL1Ee1koc71dZipNpYSO@S4s24gEv3oiHtNJGPMKaNuL09HS/EWdnh40Qv2i4YqgdUCG10Qk4aE5gpE7diHh69S5VdQ@mnjBZdSgEAm3Mh4lXCEBq50bkKlV08K4ekdpGb5HpqeeX3OxQZ5k3tG7s0IymH4CNyruBTSWQkNbFV9UmN25qVZZxX0j9wQTG@/V82ttaa5wCs7WuuQs@16PqOjDyZsJf6eSpVa5VMygqiqV1AUEyONJYSNOQcD0GnsvG0jjMygdFeZILQVzTiDzou4EOKt4cIUSYo4QIc6QQYY4WIswRQ4Q5ahhpM@Qw2mboYcTNEMSoW90kiNVNgihvEr6AOp6r1GcEuGsIojP2dUr4ejV2dMtIrJcpTRV0IOcbvncwNpTdUZWwM2g12evYunrBEj8Z7nclm7HrCEMbr3rpEsVWdMOlzqwqPUS17vQ0IvenBYOQLHodR59ujalcXrFyxt/gUWlCnonJ8u83xZTsAE0KGsMDwDIJ3RhfDcbylyWOf4RvXu1IakIcPL/WE2KYHX1BI@5sWytcg51zQ@uQRzAHRRMIXSDE69b5SKONXwm4yjDm3/A@3ezPGalUIwwDS@Mr2xYtMJueF9Sqe2ZoK4tSYOKdFMdimmlCHK@IeBPLjAmwg3/1301Bbr//XZvdXQqxXMoXql/XCgMPaAiBQE4VO7wAF@K98nKQT4j30Sl6CIX8eLk9f25j0dLf@09fAF5Zm1/66XObX1b3n5omqx6X5X2f@28Rnu6Czvy9s7tZVt0/u@fz5XGe4@Dq6uojVDOWao8@9Z86gP7CFWNspvwmnMtnhPPHryO6aPM0l5fU71DwSquan23QYJodY25raswKfkNqfjjElh8hNongFYtOppDxo713ePT86l2FPKTHw6Ar0xhdJ/ZaRcXK0BhDp5IJJG3suI@j38EZ6qX3eNsx3J/gWNUv0MVZfufOAlImZkfyKF/0apiYaWEQRIdUZvkV09CfGSlYBPOXlneeyON84k0BPEdqNqp75jcjvRh@2seRHTRKefSbd5gxduzXSCl6X03c4c5RfnAzuQ9HBzb4dnVRsOtvy4vExMOqs9nRH/aby4nlqpDTd3lxNSmjmmX8krNyJUcMuO6g6BApM6WL9DO@1UV@8J6NZsm3t1B68TYJHVj2XqX9FVUHuick0Gt8n5EC8woPB6CHKzfMqlvrRkF/kplPJ1JYqYj3fMagOMd9DCdo4u9DOWTle4COL@lCjoFm@qQ1LGZJJuUBOaYx/LLJpn9lIcu82BNPChS5OGRgomImzplKklnN9g@wP8lnFeA4ECybvE78rUp9@2Lfsty3L/gtSv5p0Wdl/2TDn@hGwR80OT7@Cw "Kotlin – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
Uses a very similar approach to [pizzapants'](https://codegolf.stackexchange.com/a/168544/59487) and [Neil's](https://codegolf.stackexchange.com/a/168548/59487). Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
```
p’Ḣ_/HḞ+ʋS<9Ɗ?€5s%⁵
```
[Try it online!](https://tio.run/##y0rNyan8/7/gUcPMhzsWxet7PNwxT/tUd7CN5bEu@0dNa0yLVR81bv1/eLk@kOMOxFmPGuYc2gaCjxrm/v8fHW2oo6CgYBirw6UQbQRiGoOZIFEjAwjTQEfBEKLA0BjINI2NBSoDAA "Jelly – Try It Online")
---
**The helper link**
```
_/HḞ+5
```
This is a monadic link (the Jelly equivalent of a single argument function), that can be invoked from the next link using the quick `Ç`. It takes a list of two integers and does the following on it:
```
_/
```
Reduce by subtraction.
```
HḞ+5%⁵
```
Floor its halve to an integer and add 5, then take it modulo 10.
**The main link**
```
p’ḢÇS<9Ɗ?€s
```
This is a dyadic link (the Jelly equivalent of a two-argument function), that can be invoked from the next link using the `ç` quick. It takes two integers \$x\$ and \$y\$ and performs the following:
```
p’
```
Cartesian product of their ranges, and then subtract \$1\$ from each integer in that list. It is equivalent to \$([0, x)\cap \mathbb{Z}) \times ([0, y)\cap \mathbb{Z})\$.
```
S<9Ɗ?€
```
And for each of the pair in the Cartesian product, if their sum is less than 9, then:
```
Ḣ
```
Retrieve the head of the pair (first element). Otherwise,
```
Ç
```
Call the helper link (explained above) on the pair.
```
s%⁵
```
Finally, split the resulting list into chunks of length \$y\$ and take each mod 10.
] |
[Question]
[
Let's define a sequence of integer square roots. First, a(1) = 1. Then, a(n) is the smallest positive integer **not seen before** such that
```
sqrt(a(n) + sqrt(a(n-1) + sqrt(... + sqrt(a(1)))))
```
is an integer. Some examples:
a(2) is 3 because it's the smallest integer such that `sqrt(a(2) + sqrt(a(1))) = sqrt(a(2) + 1)` is integer, and 3 hasn't occured in the sequence before.
a(3) is 2 because it's the smallest integer such that `sqrt(a(3) + sqrt(a(2) + sqrt(a(1)))) = sqrt(a(3) + 2)` is integer, and 2 hasn't occured in the sequence before.
a(4) is 7 because `sqrt(a(4) + 2)` is integer. We couldn't have a(4) = 2 because 2 already occured in our sequence.
Write a program or function that given a parameter *n* returns a sequence of numbers a(1) to a(n).
The sequence starts 1,3,2,7,6,13,5, ....
Source of this sequence is from [this Math.SE question](https://math.stackexchange.com/questions/2469058/a-n-is-the-smallest-positive-integer-number-such-that-sqrta-n-sqrta-n-1).
---
A plot of the first 1000 elements in the sequence:
[](https://i.stack.imgur.com/aQT8D.png)
[Answer]
# [Python 2](https://docs.python.org/2/), 80 bytes
```
s=[]
exec'x=q=1\nwhile(x in s)+q%1:x+=1;q=(v+x)**.5\nv=q;s+=x,;'*input()
print s
```
[Try it online!](https://tio.run/##Hc1LDoMgEADQPacgJI18GiOabkrmJNWVJZGkGUFQp6ennwu8F99lWbGv8/r0sAkhaobHxDz5uSFIYEc8l/DyknhAnpVJF3snA9YlkIchpXV7G/GA5LIBurpGB4x7kYrFLWDhuX7Rv8d/hx6qZQPru@4D "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~103~~ 87 bytes
Horribly inefficient, but does not rely on floating point arithmetic. Here `a(x) = sqrt(f(x)+a(x-1))` is a helper sequence, that simplifies the computation.
```
a 0=0
a x=[k|k<-[1..],m<-[k^2-a(x-1)],m>0,notElem m$f<$>[1..x-1]]!!0
f x=(a x)^2-a(x-1)
```
[Try it online!](https://tio.run/##ZYy7CoNAEEV7v@IKFgqz4iOJIGqXrxADS7JLZF01UcEi/74ZmzSZ28xlzpmnXIwaBuckkjrxJPa6NR9TiTaN444sL@aWCRnuIo24NwmN03odlIUNdBU0B8e3rvP9xNOsh/wj@inOyn5EjfndjysCWDlDH07ReUJgeU7b8MC0rfO2QpdASjllVNCF0pzOBwMs6rWp8a4waciSkYyTc06U42/cFw "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
t,=s=1,
for n in~-input()*s:
while(n in s)+(t+n)**.5%1:n+=1
s+=n,;t=(t+n)**.5
print s
```
[Try it online!](https://tio.run/##Pck7CoAwDADQvafIIvSnUEEEJcdRWpC0NBFx8eoVF9f3yi0x09iaeGQMXu25AkGip09UTtHG8qLgiunY9OfAxmlxZKwdpi4s5DAoYIfkV8F/VKmJBLi1@QU "Python 2 – Try It Online")
-3 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
-5 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~30~~ 27 bytes
```
lXHiq:"`@ymH@+X^1\+}8MXHx@h
```
[Try it online!](https://tio.run/##y00syfn/PyfCI7PQSinBoTLXw0E7Is4wRrvWwjfCo8Ih4/9/cwA) Or see a [graphical display](http://matl.suever.net/?code=lXHiq%3A%22%60%40ymH%40%2BX%5E1%5C%2B%7D8MXHx%40h%5D%5D%27o%27%26XG&inputs=60&version=20.4.2) (takes a while; times out for inputs exceeding approximately `60`).
### Explanation
```
l % Push 1. This is the array that holds the sequence, initialized to
% a single term. Will be extended with subsequent terms
XH % Copy into clipboard H, which holds the latest result of the
% "accumulated" square root
iq:" % Input n. Do the following n-1 times
` % Do...while
@ % Push interaton index k, starting at 1. This is the candidate
% to being the next term of the sequence
y % Push copy of array of terms found so far
m % Ismbmer? True if k is in the array
H % Push accumulated root
@+ % Add k
X^ % Square root
1\ % Modulo 1. This gives 0 if k gives an integer square root
+ % Add. Gives nonzero if k is in the array or doesn't give an
% integer square root; that is, if k is invalid.
% The body of the do...while loop ends here. If the top of the
% stack is nonzero a new iteration will be run. If it is zero that
% means that the current k is a new term of the sequence
} % Finally: this is executed after the last iteration, right before
% the loop is exited
8M % Push latest result of the square root
XH % Copy in clipboard K
x % Delete
@ % Push current k
h % Append to the array
% End do...while (implicit)
% Display (implicit)
```
[Answer]
# Mathematica, 104 bytes
```
(s=f={i=1};Do[t=1;While[!IntegerQ[d=Sqrt[t+s[[i]]]]||!f~FreeQ~t,t++];f~(A=AppendTo)~t;s~A~d;i++,#-1];f)&
```
[Try it online!](https://tio.run/##DcnBCoJAEADQX0mCUNbAPS8DCRF0Swo6DB6WdtSFXG2dWza/vvmub7Q80GjZv2zqIeULdPD1oH/mPCGDNs/Bvwmza2DqKTbo4P6JjKwWRN9u1jXr5BKJGuGSlWpNJ3kN9TxTcI@pEDaL1OKMV6rcH/X2xSHdog@8O/Woq6pNfw "Wolfram Language (Mathematica) – Try It Online")
The sequence of the square roots is also very interesting...
and outputs a similar pattern
>
> 1,2,2,3,3,4,3,5,3,6,4,4,5,4,6,5,5,6,6,7,4,7,5,7,6,8,4,8,5,8,6,9,5,9,6,10,5,10,6,11,5,11,6,12,6,13,6,14,7,7,8,7,9,7,10,7,11,7,12,7,13,7,14,8,8,9,8,10...
>
>
>
[](https://i.stack.imgur.com/BIv8s.jpg)
also here are the differences of the main sequence
[](https://i.stack.imgur.com/MQtKV.jpg)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~117~~ ~~115~~ ~~112~~ ~~102~~ ~~99~~ 87 bytes
```
t,=r=1,;exec"x=1\nwhile(t+x)**.5%1or x in r:x+=1\nr+=x,;t=(t+x)**.5;"*~-input();print r
```
[Try it online!](https://tio.run/##Pco7CoAwDADQq5SCYD@KFVwsuYmbFCxILCFiXLx6xcX5vXLzduBYK3sgCD4mSasWCAteW95Ty06Mtf3UhIOUqIyKZnGfkwPxkeEvUduny1hObk0slJEV1ToOLw "Python 2 – Try It Online")
Used the `t=(t+x)**.5` logic from [Erik's answer](https://codegolf.stackexchange.com/a/145152/38592)
[Answer]
# JavaScript (ES7), ~~89~~ ~~82~~ ~~77~~ 76 bytes
```
i=>(g=k=>(s=(++n+k)**.5)%1||u[n]?g(k):i--?[u[n]=n,...g(s,n=0)]:[])(n=0,u=[])
```
### Demo
```
let f =
i=>(g=k=>(s=(++n+k)**.5)%1||u[n]?g(k):i--?[u[n]=n,...g(s,n=0)]:[])(n=0,u=[])
console.log(JSON.stringify(f(10)))
```
### Formatted and commented
```
i => ( // given i = number of terms to compute
u = [], // u = array of encountered values
g = p => // g = recursive function taking p = previous square root
(s = (++n + p) ** .5) % 1 // increment n; if n + p is not a perfect square,
|| u[n] ? // or n was already used:
g(p) // do a recursive call with p unchanged
: // else:
i-- ? // if there are other terms to compute:
[u[n] = n, ...g(s, n = 0)] // append n, set u[n] and call g() with p = s, n = 0
: // else:
[] // stop recursion
)(n = 0) // initial call to g() with n = p = 0
```
[Answer]
# [R](https://www.r-project.org/), ~~138~~ ~~105~~ 99 bytes
```
function(n){for(i in 1:n){j=1
while(Reduce(function(x,y)(y+x)^.5,g<-c(T,j))%%1|j%in%T)j=j+1
T=g}
T}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPszotv0gjUyEzT8HQCsjLsjXkKs/IzEnVCEpNKU1O1YArrdCp1NSo1K7QjNMz1Um30U3WCNHJ0tRUVTWsyVLNzFMN0cyyzdI25AqxTa/lCqn9n6ZhaKj5HwA "R – Try It Online")
*-33 bytes using [Tfeld's clever `sqrt()%%1` trick](https://codegolf.stackexchange.com/a/145149/67312) in the while loop*
*-6 bytes using T instead of F*
### original answer, 138 bytes:
```
function(n,l={}){g=function(L)Reduce(function(x,y)(y+x)^.5,L,0)
for(i in 1:n){T=1
while(g(c(l,T))!=g(c(l,T))%/%1|T%in%l)T=T+1
l=c(l,T)}
l}
```
[Try it online!](https://tio.run/##PcmxCsIwEIDhPU8Rh8AdjdoMLuK9QSfJ7BKTGjiuUCy2xDx7HIRuP98/t6Rvx5YWCe88CYhlKhXLSDsNeI/PJUTYZbUbwtat@Dhd7GB7VGmaIess2l0FiyenPq/MEUYIwNYjHmhPczbu600Ww@jJd04x/VdVXFsC12P7AQ "R – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 21 bytes
```
!¡oḟȯΛ±sFo√+Som:`-N;1
```
[Try it online!](https://tio.run/##ASkA1v9odXNr//8hwqFv4bifyK/Om8Kxc0Zv4oiaK1NvbTpgLU47Mf///zEwMA "Husk – Try It Online")
### How?
```
!¡oḟȯΛ±sFo√+Som:`-N;1 Function that generates a list of prefixes of the sequence and indexes into it
;1 The literal list [1]
¡ Iterate the following function, collecting values in a list
oḟȯΛ±sFo√+Som:`-N This function takes a prefix of the sequence, l, and returns the next prefix.
`-N Get all the natural numbers that are not in l.
Som: Append l in front each of these numbers, generates all possible prefixes.
ȯΛ±sFo√+ This predicate tests if sqrt(a(n) + sqrt(a(n-1) + sqrt(... + sqrt(a(1))))) is an integer.
F Fold from the left
o√+ the composition of square root and plus
s Convert to string
ȯΛ± Are all the characters digits, (no '.')
oḟ Find the first list in the list of possible prefixes that satisfies the above predicate
! Index into the list
```
] |
[Question]
[
OEIS [A000009](https://oeis.org/A000009) counts the number of *strict partitions* of the integers. A *strict partition* of a nonnegative integer `n` is a set of positive integers (so no repetition is allowed, and order does not matter) that sum to `n`.
For example, 5 has three strict partitions: `5`, `4,1`, and `3,2`.
10 has ten partitions:
```
10
9,1
8,2
7,3
6,4
7,2,1
6,3,1
5,4,1
5,3,2
4,3,2,1
```
## Challenge
Given a nonnegative integer `n`<1000, output the number of strict partitions it has.
### Test cases:
```
0 -> 1
42 -> 1426
```
Here is a list of the strict partition numbers from 0 to 55, from OEIS:
```
[1,1,1,2,2,3,4,5,6,8,10,12,15,18,22,27,32,38,46,54,64,76,89,104,122,142,165,192,222,256,296,340,390,448,512,585,668,760,864,982,1113,1260,1426,1610,1816,2048,2304,2590,2910,3264,3658,4097,4582,5120,5718,6378]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
[Answer]
# Pyth, 7 bytes
```
l{I#./Q
```
[Try it online.](https://pyth.herokuapp.com/?code=l%7BI%23.%2FQ&input=5&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=l%7BI%23.%2FQ&input=5&test_suite=1&test_suite_input=5%0A10%0A0%0A42&debug=0)
* Take the input (`Q`).
* Find its partitions (`./`).
* Filter it (`#`) on uniquify (`{`) not changing (`I`) the partition. This removes partitions with duplicates.
* Find the result's length (`l`).
[Answer]
# Mathematica, 11 bytes
```
PartitionsQ
```
---
**Test case**
```
PartitionsQ@Range[10]
(* {1,1,2,2,3,4,5,6,8,10} *)
```
[Answer]
## Python 2, 49 bytes
```
f=lambda n,k=1:n/k and f(n-k,k+1)+f(n,k+1)or n==0
```
The recursion branches at every potential summand `k` from `1` to `n` to decide whether it should be included. Each included summand is subtracted from the desired sum `n`, and at the end, if `n=0` remains, that path is counted.
[Answer]
## Haskell, 39 bytes
```
f n=sum[1|x<-mapM(:[0])[1..n],sum x==n]
```
The function `(:[0])` converts a number `k` to the list `[k,0]`. So,
```
mapM(:[0])[1..n]
```
computes the Cartesian product of `[1,0],[2,0],...,[n,0]`, which gives all subsets of `[1..n]` with 0's standing for omitted elements. The strict partitions of `n` correspond to such lists with sum `n`. Such elements are counted by a list comprehension, which is shorter than `length.filter`.
[Answer]
## ES6, 64 bytes
```
f=(n,k=0)=>[...Array(n)].reduce((t,_,i)=>n-i>i&i>k?t+f(n-i,i):t,1)
```
Works by recursive trial subtraction. `k` is the number that was last subtracted, and the next number to be subtracted must be larger (but not so large that an even larger number cannot be subtracted). 1 is added because you can always subtract `n` itself. (Also since this is recursive I have to take care that all of my variables are local.)
[Answer]
# Python, 68 bytes
```
p=lambda n,d=0:sum(p(n-k,n-2*k+1)for k in range(1,n-d+1))if n else 1
```
Just call the anonymous function passing the nonnegative integer `n` as argument... and wait the end of the universe.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
LæOQO
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5/Ay/0D///8NDQA "05AB1E – Try It Online")
Note: this is extremely slow and will timeout for inputs greater than about 20.
Explanation:
```
L # range 1..input
æ # list of subsets
O # sum each subset
Q # equal? (1 for each sum that equals the input, 0 otherwise)
O # sum the booleans
```
[Answer]
## Haskell, 58 bytes
```
import Data.List
h x=sum[1|i<-subsequences[1..x],sum i==x]
```
Usage example: `map h [0..10]` -> `[1,1,1,2,2,3,4,5,6,8,10]`.
It's a simple brute-force approach. Check the sums of all subsequences of `1..x`. This works for `x == 0`, too, because all subsequences of `[1..0]` are `[[]]` and the sum of `[]` is `0`.
[Answer]
## Haskell, 43 bytes
```
0%0=1
_%0=0
n%k=n%(k-1)+(n-k)%(k-1)
f n=n%n
```
The binary function `n%k` counts the number of strict partitions of `n` into parts with a maximum part `k`, so the desired function is `f n=n%n`. Each value `k` can be included, which decreases `n` by `k`, or excluded, and either way the new maximum `k` is one lower, giving the recursion `n%k=n%(k-1)+(n-k)%(k-1)`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 24 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3 bytes
```
Ṅ'Þu
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJsPSIsIiIsIuG5hCfDnnUiLCIiLCI1Il0=)
Vyxal forever
[Answer]
# Julia, 53 bytes
```
n->endof(collect(filter(p->p==∪(p),partitions(n))))
```
This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
We get the integer partitions using `partitions`, `filter` to only those with distinct summands, `collect` into an array, and find the last index (i.e. the length) using `endof`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅœʒDÙQ}g
```
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyacmuRyeGVib/v@/iREA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8OtRyefmuRyeGZgbfp/nf8GXKZchgZcJkYA).
**Explanation:**
```
Ŝ # Get all integer partitions of the (implicit) input
# i.e. 5 → [[1,1,1,1,1],[1,1,1,2],[1,1,3],[1,2,2],[1,4],[2,3],[5]]
ʒ } # Filter by:
D # Duplicate the current partition
Ù # Uniquify (removing any duplicated values from) this copied partition
# i.e. [1,1,1,1,1] → [1]
# i.e. [1,4] → [1,4]
Q # Check if it's still the same
# i.e. [1,1,1,1,1] and [1] → 0 (falsey)
# i.e. [1,4] and [1,4] → 1 (truthy)
g # Then take the length of the filtered list (and implicitly output it)
# i.e. [[1,4],[2,5],[5]] → 3
```
] |
[Question]
[
## Story, *or why we are doing this.*
None. This exercise is completely pointless ... unless you are [Stephen Hawking](http://www.hawking.org.uk/about-stephen.html).
# The Challenge
Given a list of angles, find the average of those angles. For example the average of 91 degrees and -91 degrees is 180 degrees. You can use a program or function to do this.
# Input
A list of degree values representing angle measures. You may assume that they will be integers. They can be inputted in any convenient format or provided as function arguments.
# Output
The average of the inputted values. If there are more than one value found for the average, only one should be outputted. The average is defined as the value for which
[](https://i.stack.imgur.com/4q4pT.png)
is minimized. The output must be within the range of (-180, 180] and be accurate to at least two places behind the decimal point.
**Examples:**
```
> 1 3
2
> 90 -90
0 or 180
> 0 -120 120
0 or -120 or 120
> 0 810
45
> 1 3 3
2.33
> 180 60 -60
180 or 60 or -60
> 0 15 45 460
40
> 91 -91
180
> -89 89
0
```
As usual with [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), the submission with the least bytes wins.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
var QUESTION_ID=60538,OVERRIDE_USER=32700;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
Here is a chatroom for any questions about the problem: <http://chat.stackexchange.com/rooms/30175/room-for-average-of-angles>
[Answer]
# Python 3, 129 bytes
```
lambda l:min([sum(((b-a)%360)**2for b in l)*len(l)-s*s,180-(180-a-s/len(l))%360]for a in l for s in[sum((b-a)%360for b in l)])[1]
```
This problem seems to have generated quite a lot of confusion. Intuitively, the idea is to cut the circle of angles at some point, unwrap the circle to a line, compute the arithmetic mean on that line, and then wrap the result back to the circle. But there are many different points where you could choose to cut the circle. It is not enough to arbitrarily pick one, such as 0° or 180°. You need to try them all and see which one results in the smallest sum of squared distances. If your solution is significantly less complicated than this, it is probably wrong.
[Answer]
## Python 3, 85 bytes
```
lambda l:180-min(range(72000),key=lambda x:sum((180-(x/200+i)%360)**2for i in l))/200
```
Takes advantage of the the answer only needing to be accurate to two decimal points by trying all possible angles with increments of `1/200` of a degree. This takes less than a second on my machine.
Because Python doesn't let us conveniently list arithmetic progressions of floats, we represent the possible angles as whole number `[0,72000)`, which convert to an angle as `(-180,180]` as `x -> 180 - x/200`. We find the one of these that gives the minimum sum of squared angular differences.
For two angles with an angular displacement of `d`, the squared angular distance is found by transforming to an equivalent angle in `(-180,180]` as `180-(d+180)%360`, then squaring. Conveniently, the angle given by `x/200` is already offset by `180` degrees.
[Answer]
# Octave, ~~97~~ 95 bytes
```
p=pi;x=p:-1e-5:-p;z=@(L)sum((p-abs(abs(x-mod(L,360)*p/180)-p)).^2);@(L)x(z(L)==min(z(L)))*180/p
```
This produces an anonymous function that just searches the minimum of the given function on a grid that is just fine enough. As input the function accepts column vectors, e.g. `[180; 60; -60]`. For testing you need to give the function a name. So you could e.g. run the code above and then use `ans([180, 60; -60])`.
[Answer]
# Javascript ES6, 87 bytes
```
with(Math)f=(...n)=>(t=>180/PI*atan(t(sin)/t(cos)))(f=>n.reduce((p,c)=>p+=f(c*PI/180)))
```
Example runs (Tested in Firefox):
```
f(-91,91) // -0
f(-90,90) // 0
f(0,-120,120) // 0
f(0,810) // 44.999999999999936
```
***Work in progress***
This version takes a slightly different approach than the average-everything-then-do-modular-math. Rather, the angles are converted to vectors, the vectors are added and the angle of the resulting vector is then computed. Unfortunately, this version is **very** unstable with the trig and I'll be working on a modular-math version.
[Answer]
# CJam, ~~44~~ 40 bytes
```
Ie3_2*,f-:e-2{ea:~f{-P*180/mcmC2#}:+}$0=
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%3AE%3B%7BS%2F%7D%3AA%3B%20e%23%20Implement%20%60ea'%20as%20%60EA'.%0A%0AIe3_2*%2Cf-%3Ae-2%7BEA%3A~f%7B-P*180%2FmcmC2%23%7D%3A%2B%7D%240%3D&input=-89%2089).
### Test cases
```
$ for i in 1\ 3 90\ -90 0\ -120\ 120 0\ 810 1\ 3\ 3 180\ 60\ -60 0\ 15\ 45\ 460 91\ -91 -89\ 89
> do cjam <(echo 'Ie3_2*,f-:e-2{ea:~f{-P*180/mcmC2#}:+}$0=') $i
> echo
> done
2.0
180.0
0.0
45.0
2.33
60.0
40.0
180.0
0.0
```
### Idea
We compute the deviation for all potential averages from **-179.99** to **180.00** with steps of size **0.01**, and select the one with the lowest deviation.
For this purpose, it doesn't matter if we take the angular distances degrees or radians. Rather than mapping the differences **δ** of angles from input and potential averages in **[0,360°)** and conditionally subtracting the result from **180°**, we can simply calculate **arccos(cos(πδ÷180°))**, since **cos** is both periodic and even, and **arccos** always yields a value in **[0,π)**.
### Code
```
Ie3 e# Push 18e3 = 18,000.
_2* e# Copy and multiply by 2. Pushes 36,000.
, e# Push the range [0 ... 35,999].
f- e# Subtract each element from 18,000. Pushes [18,000 ... -17,999].
:e-2 e# Divide each element by 100. Pushes [180.00 ... -179.99].
{ e# Sort; for each element A of that array:
ea:~ e# Push and evaluate the array of command-line arguments.
f{ e# For each input angle, push A and the angle; then:
- e# Subtract the angle from A.
P*180/ e# Convert from degrees to radians.
mcmC e# Apply cos, then arccos to the result.
2# e# Square.
} e#
:+ e# Add the squares. This calculates the deviation.
}$ e# A's with lower deviations come first.
0= e# Select the first element of the sorted array.
```
[Answer]
# [Scala](https://www.scala-lang.org/), 96 bytes
Modified from [@Roman Czyborra's answer](https://codegolf.stackexchange.com/a/261016/110802).
---
Golfed version. [Try it online!](https://tio.run/##LY7NasMwEITvfoq5FCSwjd30Lw4StLdCego9hRC2rpOoRLIrKcQm@NndTehhF2b222FCTUeajO1aHxGuIrcUD/k2Sdqvn6aO@CDjcEmA72YHy0KQ34cKr97TsF5Fb9x@Iyt8OhOhbiTQsRuPjIqlCVEUKcrHFA/XeSqklAyN/5FUrZrf9buLG6V5Q0290iIrn@eILcqXQubWuLdBkNI9l@uEUbprz0JQZu5mHMeF68OlptCgh9mh1/zFcMbHxc0elB7G9F7KPJysnMZk@gM)
```
x=>(-179 to 180).minBy(a=>x.map(i=>pow((a-i%360)match{case x if x>180=>x-360;case y=>y},2)).sum)
```
Ungolfed version. [Try it online!](https://tio.run/##TY5LS8NAFIX38yvORpiBNCS@DbRQd4KuxFURGWPa3tKZhJkrJkh@e7wTi7iYxz189@PE2h7tNJHr2sCIacqd5X3@plT7fmhqxpMlj28FfDRbOBm0DbtYYR2CHTbPHMjvXk2FF0@M5UwCnaR8FFQ/UmRdZCivMlymc10YYwQa1clpdV8hYZsHz8kkz59IL8qbO3CL8rYwuSN/P2iL5Qq99Ow0pW/XfmkJFyCc4UL8UpPr/ckA1DY26EFbuVZJNO8LL@x/ZEj5MCdjhnNj8vjpfquOapp@AA)
```
import scala.math._
object Main {
def main(args: Array[String]): Unit = {
println(a(List(0, 15, 45, 460)))
}
def a(x: List[Int]): Int = {
(-179 to 180).minBy(a => x.map(i => pow((a - i % 360) match {
case x if x > 180 => x - 360
case y => y
}, 2)).sum)
}
}
```
[Answer]
# MATLAB, 151
```
p=360;n=mod(input(''),p);a=0:0.01:p;m=[];for b=a e=b-n;f=mod([e;-e],p);c=min(f);d=c.^2;m=[m sum(d)];end;[~,i]=min(m);a=a(i);if a>180 a=a-p;end;disp(a);
```
Ok, so until I can actually understand what the methodology is, this is what I have come up with. It is a little bit of a hack, but as the question states that the answer must be correct to 2.d.p it should work.
I basically check every angle between 0 and 360 (in 0.01 increments) and then solve the formula in the question for each of those angles. Then the angle with the smallest sum is picked and converted into -180 to 180 range.
---
The code should with **Octave**. You can try it with the [online interpreter](http://octave-online.net/)
[Answer]
# JavaScript (ES6) 138
Not having the faintest idea of an algorithm, this tries all possibile values with 2 digits precision (-179.99 to 180.00). Quite fast with the test cases anyway.
Test running the snippet below in an EcmaScript 6 compliant browser (implementing arrow functions and default parameters - AFAIK Firefox)
```
A=l=>(D=(a,b,z=a>b?a-b:b-a)=>z>180?360-z:z,m=>{for(i=-18000;i++<18000;)l.some(v=>(t+=(d=D(v%360,i/100))*d)>m,t=0)||(m=t,r=i)})(1/0)||r/100
// Test
console.log=x=>O.innerHTML+=x+'\n'
;[[1,3],[89,-89],[90,-90],[91,-91],[0,120,-120],[0,810],[1,3,3],[180,60,-60],[0,15,45,460],[1,183]]
.forEach(t=>console.log(t+' -> '+A(t)))
// Less golfed
A=l=>{
D=(a,b,z=a>b?a-b:b-a) => z>180?360-z:z; // angular distance
m=1/0;
for(i=-18000;i++<18000;) // try all from -179.99 to 180
{
t = 0;
if (!l.some(v => (t+=(d=D(v%360,i/100))*d) > m))
{
m = t;
r = i;
}
}
return r/100;
}
```
```
<pre id=O></pre>
```
[Answer]
# [julia](https://julialang.org/), 101 bytes
This version works to machine precision.
The idea is that If each entry of the input vector \$x\in \mathbf{R}^n\$ satisfies \$x\_i \in (0, 360]\$, and if \$x\$ is sorted in ascending order, then the angle average is the arithmetic mean of
$$
x^{(k)}
:=x + (\overbrace{360, \dotsc, 360}^{k\text{ entries}}, 0, \dotsc, 0)
$$
for some \$k \in \{1, \dotsc, n\}\$
Hence, the problem reduces to finding
$$
k^\*
= \underset{k=1, \dotsc, n}{\mathrm{argmin}} \sum\_{i=1}^n (x\_i^{(k)} - \bar{x}^{(k)})^2.
$$
The corresponding arithmetic mean is then
$$
\bar{x}^{(k^\*)}
= \bar{x} + k^\* \cdot \frac{360}{n}
$$
Finally, we put everything on the \$(-180, 180]\$ scale by adding \$180\$ to the input, computing everything mod \$360\$ and subtracting \$180\$ at the end.
---
Expects a `Vector{Float64}` and returns a `Float64`.
```
y->(| =mod1;~=sum;s=360;x=sort(y.+.5s.|s);n=~y.^0;~x+argmin(k->(x[k]+=s;~(x.-~x/n).^2),1:n)s)/n|s-.5s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDRaoMwFEDZa78i0JcETUx0illIf6S0rLA5XGs6jIKC5Ef24sP6UdvX7KY6GLQGbvJwT-65935e3ttTeRi_CqTRpW0Kmn-_9nSDB6Sr84tQTtu2UlYnGVedtue6wT0LWGrZYIky2vVsz5XrgkP9VpUGH-Fvtz3uAm2Vwx2jrosMYfuYhOLJEEsiM1gK_yfZz8NzgbciRMmOoGGDPurSNCeD_p01ilfASB4iKvl9bI14JHLuOY-JGG64bmDP-WwEMcO5WKgJ8GO6mrtbbBC6Y0lyxXKolnl9dk8M6SgDe_YnFmkIAogbHMRXSAo_slgSzwPTXMIUcnEx06LHcXp_AQ)
[Answer]
# [Haskell](https://www.haskell.org/), 134 bytes, with fractional precision
```
a x=(/100)$fromIntegral$snd$minimum$map(\a->(sum$map((^2).(\x->last$x:[x-36000|x>18000]).(`mod`36000).(a-).(100*))x,a))[-17999..18000]
```
[Try it online!](https://tio.run/##LY1BCsIwFESv4iKLRJqYtKBGaPeeIa30Q6sN5qelqZCFd49B3czwZgZmgvAcnUsJdrGmByUlI/d1xqvfxscKjgQ/ELTe4gsJwkJb4A0Nf6C3kgnaRt44CBuJFxN5dZRSvmOjztm7XPc4D/03zQA8S37ZMxYLYMxwddJaC/GbJwTr62W1fiNgyqIsqi59AA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 97 bytes, with integer precision
```
a x=snd$minimum$map(\a->(sum$map((^2).(\x->last$x:[x-360|x>180]).(`mod`360).(a-))x,a))[-179..180]
```
[Try it online!](https://tio.run/##LYrNCsIwEIRfxUMOCWRD4k@tQvMiqdKFCgazsZgKe/DdYwRhDjPfN3csj1tKteKGh5JnQTFHepMgXOSI4GX5D3ndKiNHBp@wrILPgWHX2Q9719tLUxM956mRVhGUYo1KBXDHkzG/RyWMeVheMa8Cg9XuoPctXTNf "Haskell – Try It Online")
[Answer]
# [Julia 1.7](https://julialang.org), 61 bytes
```
p=180
!y=argmin(i->sum(j->((i-j%2p+p)%2p-p)^2,y),.01-p:.01:p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZLBisIwEIbZq08RkYWGTWymsSER2hcRBS9dWrQE1x4E38SLFx_Io_s0-6daWGkbmCHMfJl_JsnlVjW7cnu93ppjIe0j8xlZNZmesu3he1_WUSnzn2YfVTKPsK8-E__lObz0fJOIExdzRdIv4ZeeP4v8ftyLbDopohUJptecnXPmD2V93NXs35qxJDBOCSadGsZmTMWhH3ABowQergcHLmRj2Au2NFIT8CLtuhttEN3NtW4xi2omyJshYaRjA3XTCVMqIADr4RBuIUdhZBoTfg0srcMUbvRiWgbsG9AGtaF-kOxAUKdu6Ljq0c-X7b7JHw)
`argmin(f, itr)` needs julia 1.7 or later
] |
[Question]
[
The picture below shows a RLC circuit. A RLC circuit is an electrical circuit consisting of a resistor (R), an inductor (L), and a capacitor (C), connected in series or in parallel. [(1)](https://en.wikipedia.org/wiki/RLC_circuit)
[](https://i.stack.imgur.com/4NLYs.gif)
In order to simplify computations, it's common to work in the frequency (Laplace) domain instead of the time domain.
Your task is:
**Take the values `R`, `L` and `C` as input, and return the voltages `VR`, `VL` and `VC`**
The conversion to the Laplace domain is as follows:
```
R = R
XL = j*w*L // OK, XL = w*L, and ZL = j*XL, but don't mind this here.
XC = 1/(j*w*C) // I haven't ruined physics, it's only a minor terminology tweak
```
where `j = sqrt(-1)`, and `w = 2*pi*50` (The frequency is 50 Hz).
The combined impedance, when the components are in series is `Z = R + XL + XC`. You might remember `U = R*I` from high school physics lectures. It's almost the same, but a bit more *complex* now: `VS = Z*I`. The current is calculated by dividing the voltage `VS` by the total impedance `Z`. To find the voltage over a single component, you need to know the current, then multiply it by the impedance. For simplicity, the voltage is assumed to be `VS = 1+0*j`.
Equations you might need are:
```
XL = j*w*L
XC = 1/(j*w*C)
Z = R + XL + XC // The combined impedance of the circuit
I = VS / Z // The current I (Voltage divided by impedance)
VR = I * R // Voltage over resistance (Current times resistance)
VL = I * XL // Voltage over inductor (Current times impedance)
VC = I * XC // Voltage over capacitor (Current times impedance)
```
The input is from either STDIN or as function arguments. The output/result must be three complex numbers, in a list, string or whatever is most practical in your language. It's not necessary to include names (ex `VR = ...`), as long as the results are in the same order as below. The precision has to be at least 3 decimal points for both the real and imaginary part. The input and output/results can be in scientific notation if that's default in your language.
`R` and `L` are `>= 0`, and `C > 0`. `R, L, C <= inf` (or the highest possible number in your language).
A simple test case:
```
R = 1, L = 1, C = 0.00001
VR = 0.0549 + 0.2277i
VL = -71.5372 +17.2353i
VC = 72.4824 -17.4630i
```
For the results above, this could be one (of many) valid ouput format:
```
(0.0549 + 0.2277i, -71.5372 +17.2353i, 72.4824 -17.4630i)
```
Some valid ouput formats for one voltage value are:
```
1.234+i1.234, 1.23456+1.23456i, 1.2345+i*1.2345, 1.234e001+j*1.234e001.
```
This list is not exclusive, so other variants can be used, as long as the imaginary part is indicated by an `i` or a `j` (common in electrical engineering as `i` is used for current).
To verify the result for other values of R,L and C, the following must be true for all results: `VR + VL + VC = 1`.
The shortest code in bytes win!
By the way: Yes, it's voltage *over* a component, and current *through* a component. A voltage has never gone through anything. =)
[Answer]
# Mathematica, 33 bytes
*So* close to Pyth...
```
l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&
```
This is an unnamed function, which takes `R`, `L` and `C` as its three arguments and returns a list of complex numbers as the result (in the required order `VR`, `VL`, `VC`). Example usage:
```
l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&[1, 1, 0.00001]
(* {0.0548617 + 0.22771 I, -71.5372 + 17.2353 I, 72.4824 - 17.463 I} *)
```
[Answer]
# Pyth, 30 29 28 bytes
```
L*vw*100.l_1)K[Qy0c1y1)cRsKK
```
[Try it online.](https://pyth.herokuapp.com/?code=L*vw*100.l_1)K%5BQy0c1y1)cRsKK&input=1%0A1%0A.00001&debug=0)
[Answer]
# Octave / Matlab, ~~53~~ 51 bytes
```
function f(R,L,C)
k=-.01j/pi;Z=[R L/k k/C];Z/sum(Z)
```
[Try it online](http://ideone.com/TdKaiK)
Thanks to @StewieGriffin for removing two bytes.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 24 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts for `C`, `L`, `R` in that order.
```
(⊢÷+/)(⎕,⎕∘÷,÷∘⎕)÷○0J100
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/Go65Fh7dr62tqPOqbqgPEjzpmHN6uc3g7kAbyNIGM6d0GXoYGBiD1/xXAoIDLQM8ACAwVFB71zlVw5jJUgAIQ1weVGwQA "APL (Dyalog Unicode) – Try It Online")
`0J100` 100 *i*
`○` π times that
`÷` reciprocal of that
`(`…`)` apply the following tacit function:
`÷∘⎕` divide the argument by input (`C`)
`⎕∘÷,` prepend input (`L`) divided by the argument
`⎕,` prepend input (`R`)
`(`…`)` apply the following tacit function:
`+/` sum the arguments
`⊢÷` divide the arguments by that
[Answer]
# Octave, 41 bytes
```
@(R,L,C)(Z=[R L/(k=-.01j/pi) k/C])/sum(Z)
```
`1/(100*j*pi)` can be shortened to `-.01j/pi` which is a lot shorter. By assigning it to the variable `k` inline, the variable can be used twice. Assigning the entire vector to the variable `Z` costs 4 bytes, but allows us to divide by `sum(Z)`, which is 5 bytes shorter than `(R+L/k+k/C)`.
] |
[Question]
[
Your task is to make a program that decides if a real number between 0 and 1 is irrational or not. As stated, this is obviously impossible, so instead we will use the following definition:
`p` is your program, which takes in a decimal expansion of a number (list of integers), and returns 0 (≈Rational) or 1 (≈Irrational). If `x` is an irrational number, then \$\limsup\limits\_{n\rightarrow\infty}p(x[:n])=1\$, and if `x` is rational the limit superior has to be 0. \$x[:n]\$ means the truncated decimal expansion, which is just the first `n` digits after the decimal point.
Or in other words, iff `x` is rational, there should be some `n` such that all prefixes longer than `n` return `Rational`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Also, standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules apply, so instead of outputting 0 or 1, you can output true,false, "Irrational", "Rational", etc. As we know, \$0.999...=1\$, so you can assume that the decimal expansion doesn't contain a trail of repeating 9s. Instead of decimal, you can use binary. The input list is non-empty.
# Explanation
Your program will receive a list/string of decimal digits corresponding to a truncated decimal expansion of that real number. For example, if we had the real number `0.31415926...`, the program could receive `[3,1,4]` or `[3]` or `[3,1,4,1,5,9,2]` etc. as input. The program then has to guess whether the real number is irrational or not.
Of course, it's impossible to always guess correctly. What matters is what happens when the input length increases (the limiting behavior). Let's use the **rational** number `8/13=0.6153846153846153846153846...` as example. If we gave the program the first three digits `[6,1,5]`, it might (incorrectly) guess that the number is irrational. But if we gave the program at least 30 digits, it might correctly guess (every time) that the number is rational.
In other words, if your program is given the decimal expansion of a rational number \$q\$, there must be some \$n\$ so that if at least \$n\$ digits are given to your program, it will always return `Rational`.
For irrational numbers the opposite is true. For every irrational number \$r\$ there must be infinitely many \$n\$ so that if you give the first \$n\$ digits of \$r\$ as input, the program returns `Irrational`.
# Implementation hints
Every rational number has a [repeating decimal expansion](https://en.wikipedia.org/wiki/Repeating_decimal) and all irrational numbers have non-repeating decimal expansions.
# Possible program execution ("test cases")
```
# 41/333 = 0.123123123123...
[1] -> Rational
[1,2] -> Rational
[1,2,3] -> Irrational
[1,2,3,1] -> Irrational
[1,2,3,1,2] -> Irrational
[1,2,3,1,2,3] -> Rational
[1,2,3,1,2,3,1] -> Rational
[1,2,3,1,2,3,1,2] -> Rational
[1,2,3,1,2,3,1,2,3] -> Rational
[1,2,3,1,2,3,1,2,3,1] -> Rational
[1,2,3,1,2,3,1,2,3,1,2] -> Rational
[1,2,3,1,2,3,1,2,3,1,2,3] -> Rational
[1,2,3,1,2,3,1,2,3,1,2,3,1] -> Rational
# pi/10 = 0.31415926...
[3] -> Rational
[3,1] -> Rational
[3,1,4] -> Irrational
[3,1,4,1] -> Irrational
[3,1,4,1,5] -> Irrational
[3,1,4,1,5,9] -> Irrational
[3,1,4,1,5,9,2] -> Irrational
[3,1,4,1,5,9,2,6] -> Irrational
# 7/24 = 0.291666666...
[2] -> Rational
[2,9] -> Rational
[2,9,1] -> Irrational
[2,9,1,6] -> Irrational
[2,9,1,6,6] -> Irrational
[2,9,1,6,6,6] -> Rational
[2,9,1,6,6,6,6] -> Rational
[2,9,1,6,6,6,6,6] -> Rational
[2,9,1,6,6,6,6,6,6] -> Rational
[2,9,1,6,6,6,6,6,6,6] -> Rational
[2,9,1,6,6,6,6,6,6,6,6] -> Rational
# 0.10110000111111110...
[1] -> Rational
[1,0] -> Rational
[1,0,1] -> Irrational
[1,0,1,1] -> Rational
[1,0,1,1,0] -> Irrational
[1,0,1,1,0,0] -> Irrational
[1,0,1,1,0,0,0] -> Irrational
[1,0,1,1,0,0,0,0] -> Rational
[1,0,1,1,0,0,0,0,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1,1,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1,1,1,1,1] -> Irrational
[1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1] -> Rational
[1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0] -> Irrational
# 333/500 = 0.66600000000...
[6] -> Rational
[6,6] -> Rational
[6,6,6] -> Rational
[6,6,6,0] -> Irrational
[6,6,6,0,0] -> Irrational
[6,6,6,0,0,0] -> Rational
[6,6,6,0,0,0,0] -> Rational
[6,6,6,0,0,0,0,0] -> Rational
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒHṪẇṖ
```
A monadic Link that accepts a list and yields `1` (≈rational) or `0` (≈irrational).
**[Try it online!](https://tio.run/##y0rNyan8///oJI@HO1c93NX@cOe0////RxvqGOlY6JjrGAAhCexYAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJI@HO1c93NX@cOe0/zqH248tyXrUMEdB107hUcNczcj//6OVDI2M8SIlBQVlBRNDfWNjYy4dJWNDE0NTSyMzU2NTC0tzS2MjYwsTMyMzE2NjC2Mjc1MLsOqCTKBKI0tDM3wArNJc38gEqNbQwNDQAAgMocAAFRiC1SoBKW0FJQMQaaOQX5KRWuSSmZ5ZogHUrqSjUFCUWpaZX1ocnwIS1NQy0oKL5KTmpZdkKFhZ2QHtAlptgA@A7QJ6Vt/UwADkNCMLc6ALcJJg5UAH65ubm3PFAgA "Jelly – Try It Online") (results being the application to each prefix of each input).
### How?
Identify a list, `L`, as rational if the last half is a sublist of `L` without its final element (i.e. appears anywhere earlier).
```
ŒHṪẇṖ - Link: list, L
ŒH - split L into two halves (first half longer when odd in length)
·π™ - tail -> X = last half of L
·πñ - pop L -> Y = L without its final element
ẇ - is Y a sublist of X?
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
((.)+)$(?<=^(?<-2>.)+\1(?<-2>.)+)
```
[Try it online!](https://tio.run/##ZY67CkIxEAX7/Q6FBFFyNhq44KP0J0S0sLCxEP8/ZvPOvbA7M5sq39fv/Xn6tbo@vFI7vdErdTme7gFbPof7hpraexA4jJVFBCfaLBRzDdsKXXLfdjhAlgTYy8bAIXHK4mJHTDyFgayLyCyqbtFVn47CD00YERJMYlF1C7Tqc@jxmF3zc3EvHww5cjJxTURmUbX5Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Requires that at least the last half of the input is repeated somewhere between it and the start (exclusive). The middle `+` could be changed to `*` to allow matching at the start but I thought it looked prettier this way and it doesn't matter in the long run.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
```
x=>x.match(`^.{0,${x.length>>1}}(.+)\\1{9}$`)
```
[Try it online!](https://tio.run/##xY5dS8NQDIbv@yt6MTgt00NyPhNH6w9xSkvtvpjtWOsYlP72elDB4Y3gTR8CIZA3eQ7lpeyq8/7U3zftaz1tsuma5Vf5VvbVLile5AB3i@Eqj3Wz7Xd5juOYyGW6XuPA46JIp1W0eW@qft82cV93fdL15zQeoji@lOe4i7NYiFWYqrbp2mMtj@02eZJShrXn8OSUVFm@SbplVqWPAsWDAJHKQ7tviiJdRWP0eVOARKVnKREsvhy0RIOWlbPaEnvWSpNxyhmtSSvPFhSRQfboWDNrbxEsKWBv2JgQ1OAJnQGnyCkg5tAItCFltVGIHpxnUmgIyFnUikLEOeN/HEAqRjcHtw4IiBDAb@AX@AfwT24dghLMQXCYPgA "JavaScript (Node.js) – Try It Online")
Requiring any length have a \*10 loop allowing some left before, so rational number works; not well confirmed on irrational though
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes
```
a->prod(i=1,#a,#Pol(Ser(a)*(1-x^i))>#a/2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNzUTde0KivJTNDJtDXWUE3WUA_JzNIJTizQSNbU0DHUr4jI1Ne2UE_WNNCEabjGfTCwoyKnUSFTQtVMoKMrMKwEylUAcJYU0oC5NHYXoaMNYIGmoYwSldIzhDB1DJCaSAh10ZVgUY9WCQyNO7XgMwWsUwkCwChgbKGECZyCJAbEpCkfHEo0LcQSKgI4ZSAgsbgRRD6QghoIZUHkIE42DwcUigFUIhyBOYYgENGgNoBQsqIEMFCaSAhAHg4tFAKsQmqEwQZzCeCTwShGQJChNhAKilEACARzS0ACHhzwkEgyQmGgcDC4WAaBQLDRHL1gAoQE)
```
a->prod(i=1,#a,#Pol(Ser(a)*(1-x^i))>#a/2)
a -> Define a function with argument `a`
prod(i=1,#a, ) Take product, where `i` runs from `1` to the length of `a`
Ser(a) Convert `a` to (truncated) power series
*(1-x^i) Multiply `1 - x^i`
Pol( ) Convert to a polynomial
# Take the length of the polynomial, i.e., degree + 1
>#a/2 Check if the result is larger than half of the length of a
```
Take `a = [2,1,6,1,6]` as an example:
* `Ser(a)` is `2 + x + 6*x^2 + x^3 + 6*x^4 + O(x^5)`.
* When `i = 2`, `Ser(a)*(1-x^i)` is `2 + x + 4*x^2 + O(x^5)`.
* `#Pol(Ser(a)*(1-x^2))` is `3`, which is equal to the half of the length of `a`.
* So the result is `0`.
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 73 bytes
(or 59 bytes in R≥4.1 by changing two `function` keywords each to `\`)
*Edit: changed approach to give correct output for A003842.*
```
function(x,l=sum(x|1)/2,s=1:l)all(Map(function(i)any(x[l+s]-x[s+i]),s-1))
```
[Try it online!](https://tio.run/##rY/PasMwDMbP6VMIdrGpy@KkG10hhz1An6D0YDK7CFzXsxzmQd89ddslKyv7cxhGsmR9/qEv9BiCik1vOtdG3DuWhG2o27F0kPy@EtTIpeXKWrZSno0q5Mq9s7S2U9rM0pqmuOGCZpLzC5C1TIpK1OImcw5FUdxBFmWQsksg3HmrIWiv85vbAunXTrtWTwZUKYbzE/SaeQsDZaIO4IM2mEby6f88x4N4ypzHfNc5FsOSZ9kH0mCgCEa/wQtuMRLsDXicXNuV4pI/q6/995O/K/@DMfYnp7/7fC7LejGv@iM "R – Try It Online")
Returns `FALSE` for suspected rational numbers, and `TRUE` for suspected irrational numbers.
Based on approach of [Neil's answer](https://codegolf.stackexchange.com/a/243855/95126): checks whether the second half of the input sequence is identical to any subsequence except itself.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
§€ho→½
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@h5Y@a1mTkP2qbdGjv////o6MNY3WiDXWMIKSOMYzWMUSwELI6aGowVWJTjyQeCwA "Husk – Try It Online")
Or [try it online with a rational test-case with a non-repeating prefix](https://tio.run/##yygtzv6f@6ip8f@h5Y@a1mTkP2qbdGjv////o6ONYnWijXQsIaSOIYzWMUOwUNnoPCA/FgA),
or [try it online with the first few digits of pi](https://tio.run/##yygtzv6f@6ip8f@h5Y@a1mTkP2qbdGjv////o6ONY3WijXUMIaSOCYzWsYSzDHVM0Xk6RjpmsbEA),
or [try it online with the first few digits of A003842](https://tio.run/##yygtzv7//9DyR01rMvIftU06tPf////RhjpGOoY6EBLBQufjliFeJTXMIKgyFgA).
Ports [Neil's](https://codegolf.stackexchange.com/a/243855/95126) answer: checks whether the second half of the input sequence is present within the input without its last digit.
Unfortunately my initial attempt (`ṁoV=½ṫ`, which checked whether the input digits end in a repeated sequence, fails for the non-repeating sequence A003842 [credit to [Bubbler](https://chat.stackexchange.com/transcript/message/60613659#60613659) for finding this]).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
›÷Lθ²⌕θ✂θ⊘Lθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIwzOvxCWzLDMlVcMnNS@9JEOjUFNHwQiI3TLzUjQKdRSCczKTU0EMj8ScstQUhDIwsP7/38zMzAAE/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string and outputs a Charcoal boolean, i.e. `-` for probably rational, nothing for probably irrational. Explanation:
```
θ Input string
L Length
√∑ Integer divided by
² Literal integer `2`
› Is greater than
θ Input string
‚åï Find index of
θ Input string
‚úÇ Sliced from
θ Input string
L Length
‚äò Halved
```
(`Slice` truncates its parameters so I don't have to use integer division.)
[Answer]
## Haskell, 57 bytes Invalid solution
```
import Data.List
(==[[]]).intersect<*>map(\a->a++a).tails
```
True for irrational number, False for rational number
I used a different algorithm for this program. This program returns true if the sequence ends with two identical sequence next to each other. For example, this program returns true for [1,2,3,4,3,4] because it ends with [3,4,3,4], which is [3,4] repeated twice.
For rational number, it's obvious that this will return false for large enough string, because rational number always ends with repeating string of digits. However, I don't know if this program still works for irrational number. Turns out it doesn't work for irrational numbers.
## Haskell, 60 bytes
```
import Data.List
isInfixOf<$>(drop=<<(`div`2).length)<*>init
```
Turns out that the fixed solution is not that worse. This uses the more standard solution: whether the last half of the string still appears anywhere else in the string.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), 24 bytes
```
(‚Üì‚äëÀú2‚åä‚àò√∑Àú‚â†)‚ãà‚ä∏‚àä{‚àæ‚Ü묮‚Üì¬Ø1‚Üìùï©}
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=UmF0aW9uYWwg4oaQICjihpPiipHLnDLijIriiJjDt8uc4omgKeKLiOKKuOKIinviiL7ihpHCqOKGk8KvMeKGk/Cdlal9CgpSYXRpb25hbCAw4oC/MOKAvzDigL8w4oC/MeKAvzLigL8x4oC/MuKAvzHigL8y4oC/MeKAvzLigL8x4oC/Mg==)
Ungolfed: for input `ùï©`, checks whether `(SecondHalfOf ùï©) IsOneOf SublistsOf HeadOf ùï©`.
[Try the ungolfed code here](https://mlochbaum.github.io/BQN/try.html#code=SGVhZE9mIOKGkCDCrzHiirjihpMKU2Vjb25kSGFsZk9mIOKGkCDihpPiipHLnDLijIriiJjDt8uc4omgClN1Ymxpc3RzT2Yg4oaQIOKNt+KImOKIvijihpHCqOKImOKGkykKSXNPbmVPZiDihpAg4ouI4oq44oiKClJhdGlvbmFsIOKGkCB7IChTZWNvbmRIYWxmT2Yg8J2VqSkgSXNPbmVPZiBTdWJsaXN0c09mIEhlYWRPZiDwnZWpIH0KClJhdGlvbmFsIDDigL8w4oC/MOKAvzDigL8x4oC/MuKAvzHigL8y4oC/MeKAvzLigL8x4oC/MuKAvzHigL8y)
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2015 Day 3](https://adventofcode.com/2015/day/3), Part 2. This challenge was kindly contributed by Wheat Wizard (Grain Ghost).
---
Santa is delivering presents to an infinite two-dimensional grid of houses each 1 unit apart. The delivery begins delivering a present to the house at an arbitrary starting location, and then moving along a predetermined path delivering a new present at every step of the path. The path is a list of moves made of characters:
* `^` north
* `v` south
* `>` east
* `<` west
At each step Santa reads the instruction and starts heading in that direction until a house which hasn't had a present delivered yet is reached. At that point a present is delivered to that house and the next instruction starts.
## Task
Given a non-empty string representing directions, output the total length of the path that Santa will take.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes.
## Test cases
```
v^v^v^v^: 36
^>v<^>v : 10
>>>>>><<<<<<< : 19
>>>vvv<<< : 9
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 76 bytes
```
f=lambda o,c=0,*v:len(o)and-~f(o[(d:=c+1j**(ord(o[0])%11))not in v:],d,c,*v)
```
[Try it online!](https://tio.run/##VY7RCoIwFIbvfYqDEduxFQ4hcqgvkgbmkgzbxhyDbnp1m0kX/YdzcT6@H455ubtW2cnYee7LsX1eZQuadWXKEi/Gm6IaWyX3757qM5Wi7Hb8kSRUWxlA2uCWc0SlHQwKvGiYZF1o4txrC18Yx3HkL@sIyI7RpfJFWBDAU4iqb4o1C8sX5L1fzzwK/cPk7GAoHiYzDo6SWhEUYOygHO2p@2FBMHz0k5EBqd0GCIPF@7N4gzh/AA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
≔⁰ηFS«P#W℅KK«M✳⊗⌕>^<ι≦⊕η»»⎚Iη
```
[Try it online!](https://tio.run/##LY7BCoMwEETP8StCelnBQu8VoSgFD1KhdyHVrS5NE4nRHorfnqa2hznM8GZ32kHa1kjl/WmaqNdwSPgQH6O7sRxKPc7u6izpHuKYvyNWzcrRGAIHYicCx14DKeRwsR1pqaBGfAR2g1llFoSCLLaOjIbCzDeFHZxJdyCyJhUJp8B@z7BKjv8FpW4tPlE77H5b2BqtUa5QWgiu3r7ncnIwhKr3TbakQX6/qA8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰η
```
Start with no path length.
```
FS«
```
Loop over the input characters.
```
P#
```
We already delivered a present here.
```
W℅KK«M✳⊗⌕>^<ι≦⊕η»
```
Look for somewhere to deliver the next present.
```
»⎚Iη
```
Cler the canvas and output the final path length.
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
c=t=0
v=0,
for i in input():
while c in v:c+=1j**(ord(i)%11);t+=1
v+=c,
print t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNwOTbUtsDbjKbA10uNLyixQyFTLzgKigtERD04pLoTwjMydVIRkkWGaVrG1rmKWlpZFflKKRqalqaKhpXQIU4lIo07ZN1uEqKMrMK1EogRgMNX_BKqWyOAhUgogAAA)
Improvable.
`1j**(ord(i)%11)` is a sufficient hash function to give a layout of complex numbers corresponding to some transformation of the cardinal directions `^v><`.
[Answer]
# [R](https://www.r-project.org/), 85 bytes
```
function(s,x=1){for(j in utf8ToInt(s)%%11){while(x%in%T){x=x+1i^j
F=F+1}
T=c(x,T)}
F}
```
[Try it online!](https://tio.run/##JYmxCsMgFAB3v0IE4T2SDG4dYkehu7NL6KOGopCY9EHw241QjhuO2xrJeWp0pKXEnGAf2Rq8KG@wypjkUejh8ysV2FFr09fvE79vYB2T9nix5cHEsApn3WCq8HYBHj1W4WojUGf4o1D0Cs9z7ipsNw "R – Try It Online")
Uses the complex number, mod 11 trick.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67~~ 62 bytes
```
->s{*r=a=0i;s.bytes.sum{|b|1.step.find{r!=r|=[a+=1i**b%=19]}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WqvINtHWINO6WC@psiS1WK@4NLe6JqnGUK@4JLVALy0zL6W6SNG2qMY2OlHb1jBTSytJ1dbQMra2tvZ/gUJatFJZHAQqxSorWCkYm3GBRePsymyAGCJoaKAAEbUDAxsIgMpZwqXKysrgwpb/AQ "Ruby – Try It Online")
### How?
Basically the usual mod 19 (or 11 or 13) trick.
Start from (0+0i), sum the distance we have to travel for each house:
```
1.step.find{
```
`a` is the current position, b%19 is the direction, this literally counts the steps we need to find the first house that we have not visited yet.
```
r!=r|=[a+=1i**b%=19]}
```
This is the check: a is incremented once, we add it to the list with a union operator. If the house was already in the list, the list is unchanged and the result of the comparison is false, so we have to walk another step.
[Answer]
# JavaScript (ES6), 83 bytes
Expects a list of characters.
```
a=>a.map(g=c=>g[g[[x,y]]=++t,i='^>v'.indexOf(c),[x+=i%2,y+=~-i%2]]&&g(c),t=x=y=0)|t
```
[Try it online!](https://tio.run/##dc3tCoIwFAbg/12FCPnB5rSCQPDsFrqAMWGYDsOc5BgTols3P4r@2HsYHDjPObsJI/riUXc6atW1HCsYBVBB7qILJBRAJZOMWTxwDghpXIOfU@OTur2W9lIFRYiZRVDvj3hA8IqmhnPPk/NAg4UBkvCpx0K1vWpK0igZVAEjhLgmX8vlYegsiWPndN5t0OnHbHo/OdND4mxZuiRbs2zMNv1DjTFf9jmbjm8 "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), ~~81~~ 80 bytes
*Saved 1 byte thanks to @Neil*
Expects a string. Uses the `mod 11` trick.
```
s=>Buffer(s).map(g=c=>g[g[[x,y]]=++t,i=c%11-7,[x+=i%2,y+=~i%2]]&&g(c),t=x=y=0)|t
```
[Try it online!](https://tio.run/##bcxLCoMwEIDhfU8hBSUh8dVCi@C46DUkgqQmWKyKsUGh9OqpL7qQ/sMwm4955DpXvCvb3q2be2EEGAXJ7SVE0SGFvWfeIgkcEpnKNB3oyBgQ0tMSuB2G7pWmA4HSPtGRwGe6jDmORBzTHgYYIcDv3vCmVk1VeFUjkUBHna1zxNha8n3rfDnsVJboeNofmlUYWHuWLMVrM55Z9EdprTexPYvMFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1݈v¯θ1Ý‚D(«yÇ`11%è©[+Ј»¯€»s¢#®]¯g<
```
[Try it online](https://tio.run/##yy9OTMpM/f/f8PDc021lh9af2wFkHW561DDLRePQ6srD7QmGhqqHVxxaGa19eMLptkO7D61/1LTm0O7iQ4uUD62LPbQ@3eb//7I4CAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf8PDc0@3lR1af24HkHW46VHDLBeNQ6srD7cnGBqqHl5xaGW09uEJp9sO7T60/lHTmkO7iw8tUj60LvbQ@nSb/0p6YTqHtvyPViqLg0AlHaU4uzIbIAay7MDABgIg/LKyMhA7FgA).
**Explanation:**
Uses a combination of generating `[[0,1],[1,0],[0,-1],[-1,0]]` that I've also used in [my 05AB1E answer here](https://codegolf.stackexchange.com/a/238562/52210) and [*@alephalpha*'s modulo-11 trick from the AoCG2021 Day 1 challenge](https://codegolf.stackexchange.com/a/237857/52210) for indexing into it.
```
1݈ # Add starting position [0,1] to the global_array
# (where we start is irrelevant, and [0,1] is shorter to
# push than [0,0])
v # Loop over the characters of the (implicit) input-string:
¯θ # Push the last coordinate of the global_array
1Ý # Push [0,1]
 # Bifurcate it (short for Duplicate & Reverse copy): [1,0]
‚ # Pair them together: [[0,1],[1,0]]
D( # Duplicate, and negate it: [[0,-1],[-1,0]]
« # Merge the lists together: [[0,1],[1,0],[0,-1],[-1,0]]
yÇ` # Push the codepoint of the character
11% # Modulo-11 (5,6,7,8 for <^>v respectively)
è # Use it to 0-based modulair index into it
# ([1,0],[0,-1],[-1,0],[0,1] for <^>v respectively†)
© # Store this pair in variable `®` (without popping)
[ # Start an inner infinite loop:
+ # Add the top pair to the coordinate
Ð # Triplicate it
ˆ # Pop one, and add it to the global_array
» # Pop another, and join it with newline delimiter
¯ # Push the global_array
€» # Join each coordinate with newline delimiter as well
s # Swap them on the stack
¢ # Count this coordinate in the global_array*
# # If it's just 1: stop the infinite loop
® # (Else, when it's more than 1) Push the `®`-pair again
] # After both loops
¯g # Push the length of the global_array
< # Decrease it by 1, because the PATH between coordinates is
# 1 lower than the amount of coordinates
# (after which the result is output implicitly)
```
*†*: As you can see, the modular indexing into the pairs causes all four arrows to travel in the opposite direction, but just like the starting position, this is irrelevant for calculating the final result.
*\**: The count, indexOf, and contains builtins doesn't work when we want to check a list inside a list of lists, hence the join by newlines before we use the count.
[Answer]
# [Rust](https://www.rust-lang.org/), 145 138 bytes
```
|i:&str|i.bytes().scan((vec![],[0,0]),|(v,p),c|{while{v.push(*p);p[c as usize%3&1]+=1-(c%5&2)as i64;v.contains(&p)}{}Some(v.len())}).max()
```
[Try it online!](https://tio.run/##XZDLTsMwEADv/YptpUa7xVgphUrQx09wjFJkLEe11LomdhwgybeHPIpUGMsXz2FnnRfOt5mBs9AGCaoJdJyUhwx2ba1fIufzWvP3L68cEndSGMSg5DRJWRKzOCVWY2CWmKyr8qhPqgrcFu6IC0sbm0gQDgqnv9V8FS3Tu93yHuX8KXqg7l2vHzeBy4vx3XSHkaWmal4vZ4WBn1TXQw3xs/hEavuszRCXXXJAbWzhGQjjSpUTaANRMtgenIXDeGYMVmtiN@awD9vudmIZ/xH7ge1Ir5//6xDCqH5Nev2uHuGcyv2b@phiNtYRL0yZC4vEYHENHTdoJk37Aw "Rust – Try It Online")
Same trick as as days 1 and 8.
[Answer]
# Python3, 78 bytes
```
f=lambda n,c=[0]:len(n)and-~f(n[(j:=c[-1]+1j**(ord(n[0])%11))not in c:],c+[j])
```
[Try it online!](https://tio.run/##XcnNCoMwEATge58il@KuP2DopQTji4QIaazUoJsgEuilr55KA4V2hrl8E577w9PlGraUJrmY9TYaRrWVqtViuRMQGhqb1wSkwAlpVcN1xV1Zgt/GA1uNZ84Rye9sJmaFrm2lnMYUtpl2mKCIQ26BePri0Mfu2I/1n3Q5/0@MMWt6Aw)
[Answer]
# TypeScript Types, 276 bytes
```
//@ts-ignore
type a<T,P=0,N=1>=T extends[N,...infer T]?T:[...T,P];type M<I,P=[[],[]],N=[],V=0>=I extends`${infer C}${infer R}`?{"^":[P[0],a<P[1]>],v:[P[0],a<P[1],1,0>],">":[a<P[0]>,P[1]],"<":[a<P[0],1,0>,P[1]]}[C]extends infer Q?M<Q extends V?I:R,Q,[...N,0],V|P>:0:N["length"]
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgAUBeABkoDlaBGAPlvMPQA9x0iACaQA2k0oA6abEQAzdKkLkAugH5yALlHTJVaioDcuAoQCypAJI1ao0Ssr2HLe5QBqDTpZ79BIgAYAJADesgpKAMIAviFhioQASlH+asEARAB6adrUovQOZLmsKuwOAG45eQWkRQ6slPSllGns2aKFVew0osUOaaRtHfmU9Y3dvVGiESp8AsKQhHFKAIpqFss+cyKEbmqWmgmUy466EsNuAD7U7Jr0mkyiaQA2gvDgABZpKpiEhNj4RHI9EItHMAzKGQhUKy7EwIF+hAyan+pnIrBBYMy7DKpAy2JacOACKRKMBACYMRYWuwaTTSPSGQNYfDfiSTICAMyUpk0sp8hkElmI5FAA)
## Ungolfed / Explanation
```
// Increment an integer stored as e.g. [Pos, Pos] for 2, [Neg, Neg, Neg] for -3, and [] for 0
// Invoked as Inc<T> to increment, or Inc<T, 1, 0> to decrement
type Inc<T, Pos = 0, Neg = 1> = T extends [Neg, ...infer T] ? T : [...T, Pos]
type Main<
Instructions,
Pos = [[], []]
PathLength = [],
Visited = 0
> =
// Get the first character of Instructions
Instructions extends `${infer Char}${infer Rest}`
// Store the new position in NewPos
? {
"^": [Pos[0], Inc<Pos[1]>],
v : [Pos[0], Inc<Pos[1], 1, 0 /* Dec */>],
">": [Inc<Pos[0]>, Pos[1]],
"<": [Inc<Pos[0], 1, 0 /* Dec */>, Pos[1]],
}[Char] extends infer NewPos
?
Main<
// If NewPos is not in Visited, set Instructions to Rest
NewPos extends Visited ? Instructions : Rest,
// Update Pos
NewPos,
// Add one to PathLength
[...PathLength, 0],
// Add Pos to NewPos
Visited | Pos,
>
: 0
// Instructions is empty
: PathLength["length"]
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 89 bytes
```
s->a=[p=c=0];[a=setunion(a,[while(c++;setsearch(a,p+=I^d),)+p])|d<-Vec(Vecsmall(s))%11];c
```
[Try it online!](https://tio.run/##LYrBCsMgGINfRYSBosJ6bvW@F9hFLIi1q@C6n9o5Bnt3p@sSAslHwG5B3KDMSJYklJUapJNn02srk9@fa3isxHL9WkL0xDHWV5q83dxSMTB5GSfKKQNDP9Mgrt6RmnS3MZJE6anrTO@KBYhvkpBQCLaw7rXiNjCa24sjjfN4GHOER5WHmlbVT8OhP8g5t2Fo@QI "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 79 bytes
```
(a[d=p=0]=0Clear@a;(a@p=0While[a[p+=#]<++d])&/@(I^ToCharacterCode@#~Mod~11);d)&
```
[Try it online!](https://tio.run/##LYhBCoMwFESv8jEgES3qWiMBV10Uuih0ESJ8TCSCVgkhm1KvnmrtGwZm3ozO6Bnd2GMYgAWKQrGVFZIV7aTRcqwo8l08zThpgWJNGZF1miqZxDmn1@6xtAYt9k7bdlGak@22qK0sk0olcbjb8eUEgUsDgyBSQgw5h3fkuzNRBlHX@HrvMZsf9clfeO@P8wlf "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
# Task
Given a input string `s` which contains only printable ascii characters output all strings which contain only printable ascii characters and are strictly smaller than `s` in any order
String `a` is strictly smaller than a string `b` if either of the following is true:
* `len(a) < len(b)`
* `len(a) == len(b)` and string `a` is lexicographically smaller than string `b`
**Note:** here printable ascii characters refer to the characters which have a ascii value strictly greater than `0x1f` and strictly less than `0x7f`
[Reference Python Implementation](https://tio.run/##XVHLasMwELzrKyYuASlPuz0UArn2J5JQjC3XC7IsJIUmX@9Kimun1WnZ2ZmdHZm7b3v9NgzUmd56uLtjrGpL63CEIud5VxpetXYDW@ovyfPba75Bfnv/EEIwxmrZwPefpD134sAQHgVqnqqmt6g3qEAaUl87aUsvuTsdDtviMk4/GOsjeFq7I13LG68E1igEVuBcSf3Afnsr1CJxrfRXq0GzD@ctp1E5npBlqfxuSUnQvLELGGGJ/@LTgIuWEnDqsEVxATWBtQinQSonkZ3z7OmA/T7k9Ufr2eF4cvAZI1GkZYwkhL1zviY9@41Q6FkyPDvrLCSckF4F7HSZQqVIf3zIFP5TnlFpCmM22STT0L1P2@f5cceuNEbqOmglxNgk3CsxDGzJ8MIWni3wAw "Python 3 – Try It Online")
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins
# Testcases
```
'' -> []
'%' -> ['$', '', '#', '"', ' ', '!']
' #' -> ['', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', ' ', ' !', ' "']
'! ' -> ['', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', ' ', ' !', ' "', ' #', ' $', ' %', ' &', " '", ' (', ' )', ' *', ' +', ' ,', ' -', ' .', ' /', ' 0', ' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' :', ' ;', ' <', ' =', ' >', ' ?', ' @', ' A', ' B', ' C', ' D', ' E', ' F', ' G', ' H', ' I', ' J', ' K', ' L', ' M', ' N', ' O', ' P', ' Q', ' R', ' S', ' T', ' U', ' V', ' W', ' X', ' Y', ' Z', ' [', ' \\', ' ]', ' ^', ' _', ' `', ' a', ' b', ' c', ' d', ' e', ' f', ' g', ' h', ' i', ' j', ' k', ' l', ' m', ' n', ' o', ' p', ' q', ' r', ' s', ' t', ' u', ' v', ' w', ' x', ' y', ' z', ' {', ' |', ' }', ' ~']
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
*-1 byte thanks to @KevinCruijssen*
```
gžQ׿êéI¡н
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/XSkxKTlF6fD0w8sOrzq80sUz@9Di//8TU1IA "05AB1E – Try It Online")
TIO link is for "abcd" instead of printable ascii since powerset of len(input) printable ascii takes a while to compute...
---
### Explanation
```
gžQ× - repeat printable ascii length of the input times
æ - get the powerset of this string
êé - sort and uniquify lexicographically then sort by length
I¡ - split on the input
н - and take the elements that are before it
- output these implicitly
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ 62 bytes
```
f s|h:t<-mapM(\_->[' '..'~'])<$>scanr(:)""s=id=<<filter(<s)h:t
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02huCbDqsRGNzexwFcjJl7XLlpdQV1PT71OPVbTRsWuODkxr0jDSlNJqdg2M8XWxiYtM6cktUjDplgTqO1/bmJmnoKtQmYeUCwxuURBRaE4I79cQU8h7b@CMgA "Haskell – Try It Online")
---
Previous 64 byte version with explanation:
```
f s=[x|x<-mapM(\_->[' '..'~'])=<<scanr(:)""s,(0<$x)<(0<$s)||x<s]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2Da6oqbCRjc3scBXIyZe1y5aXUFdT0@9Tj1W09bGpjg5Ma9Iw0pTSalYR8PARqVC0wZEFWvWADUVx/7PTczMU7BVyMwrSS1KTC5RUFEozsgvV9BTSPuvoAwA "Haskell – Try It Online")
Given an input string `s`, e.g. `s="abc"`, `scanr(:)""s` yields all suffixes of `s`: `["abc","bc","c",""]`. `mapM(\_->[' '..'~'])` takes a string and computes all possible combinations of the printable ASCII characters of the same length as this string. We apply this function to all the suffixes and thus get all possible strings of length 3, 2, 1 and zero. `x` iterates over all those strings and we keep only those that are smaller in length (`(0<$x)<(0<$s)` using [this Tip](https://codegolf.stackexchange.com/a/146634/56433)) or lexicographically smaller (`x<s`) than the input `s`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Nick Kennedy!
```
LŻØṖṗẎṣ⁸Ṗj
```
A monadic Link accepting a list of characters which returns a list of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9/n6O7DMx7unPZw5/SHu/oe7lz8qHEHkJv1/3B75P//SooKSgA "Jelly – Try It Online")** (footer prints each on it's own line, since a full program would implicitly smash and print)
### How?
```
LŻØṖṗẎṣ⁸Ṗj - Link: list of characters (i.e. a string), S
L - length (S)
Ż - zero-range -> [0,1,2,...,length(S)]
ØṖ - list of printable ASCII characters
ṗ - Cartesian power (vectorises) - i.e. all length n strings for n in [0..len(S)]
Ẏ - tighten (join all these lists of strings to one list of strings)
⁸ - chain's left argument, S
ṣ - split (the list of strings) at occurrences of (S)
Ṗ - throw away the rightmost list of strings (those lexicographically greater than S)
j - join (the resulting list of lists of strings) with (S) (to get a list of strings)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~146~~ ~~139~~ ~~138~~ 136 bytes
```
lambda s:[v for n in range(len(s)+1)for v in g(n)if n<len(s)or v<s]
g=lambda n:n and[s+chr(c+32)for c in range(95)for s in g(n-1)]or[""]
```
[Try it online!](https://tio.run/##RYxBDoMgFAX3nuKHbqDGpJR0UaMnoSwoCpro14Ax6empqE2XbyZv5s/STSiirV9x0OO70RBKuYKdPCD0CF6ja@nQIg0s5yzxNXFHkfUWsDpUwlVQmavPCpYIGhsZctN5anJx37/m33w@dhLOWsGZmrwkRMXZ97hQS4khjGXHIgW5ittvbe7CNxm/ "Python 3 – Try It Online")
**How:**
The function `g` recursively generates all strings of length `n`. Our main function `f` only has to generate all the shorter strings and then, for the strings with the same length as the input, only keep the ones that have smaller dictionary order.
Thanks to @SurculoseSputum for fixing a mistake *and* saving 2 bytes at the same time, plus saving 2 bytes on a different golfing effort.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~142~~ ~~141~~ ~~135~~ 129 bytes
```
lambda s:["%c"*n%p for n in range(len(s)+1)for p in product(*tee(range(32,127),n))if n<len(s)or"%c"*n%p<s]
from itertools import*
```
[Try it online!](https://tio.run/##7dLZVtNgAEXh@z7FpohJSkUBFUWK8zzPA1QtNIVom8QkoIjw6jXnVJB30As@0r9J27XOzveq7SxdHA866@Nhb7TR71EurzVnNputdCZnkBWkJClFL92Kw2GchmU0Ox/pPNd5XmT9nc0qbFVxHE5uWlxozy8sRe00ipIB6crkoaw4@tCVstsYFNmIpIqLKsuGJckoz4qqNZ78p9wrG/qGYZLG@pL69VxZ9ZN0uUHSJqPDqJeH8W5v2NY99ZtFkofRXJkPkypsnlltRlGj/m1JWoWDZrCfHATosEERl/XTgzA5fr8@Ob4eJmUVlvVPiPs@j@h0OHmYRX8/OBoH@lTWuo1gZnIVnAraBPqbFk2BmArqm5j@c9eJ46O7fL@fnhGna5pBs74K9TISLTEr2uKMmBNnxTkxLxbEojgvLoiLYklcEpfFsrgiVkRHrIqr4pq4Lm6Im@KWuC3uiLvinrgvHoiH4pF4LJ6Ip@KZeC5eiJfilXgt3oi34p14Lz6INbG@Lrvio/gkPoue2BCboi9iMRBbYlsk4ov4KoZiJFKRiVx8E4UoRSV2xK74Ln6IPfFT7Itf4kAceluPi9etZ6ynn@L/9P/i9NL74oHxwnhivDEeGa@MZ8Y746Hx0nhqvDUeG6@N58Z748Hx4nhyvDkeHa@OZ8e74@Hx8nh6vD0eH6@P58f74wBwATgB3ACOAFeAM8Ad4BBwCTgF3AKOAdeAc8A94CBwETgJ3ASOAleBs8BdMAkDl4HTwG3gOHAdOA/cBw4EF4ITwY3gSHAlOBPcCQ4Fl4JTwa3gWHAtOBfcCw4GF4OTwc3gaHA1OBvcDQ4Hl8Nh0P0N "Python 3 – Try It Online")
Takes input as a string `s`, and outputs a list of strings.
## Explanation
The function generates all printable strings of length at most `len(s)`, then keeps the ones that are smaller than `s`.
```
lambda s:[
"%c"*n%p # forms string from p - a tuple of n ints (representing ASCII code points)
for n in range(len(s)+1) # for each length n from 0 to len(s), inclusive
for p in product(*tee(range(32,127),n))
# for each possible tuple of n ASCII codepoints
if n<len(s)or"%c"*n%p<s # keep only the strings that are smaller than s
]
```
To generate all printable strings of length `r`:
* `tee(range(32,127),n)` creates `n` iterators from 32 to 126 inclusive
* `product(*tee(...))` finds the Cartesian product of those `n` iterators
* `p in product(...)`: `p` will be a tuple of `n` integers, each between 32 and 126 inclusive
* `"%c"*r%p` creates a string of `n` characters from `p`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 110 bytes
Prints the strings.
```
s=>(g=o=>o[k=s.length]||o[g([...o,32]),(n=o.length)<k|(S=Buffer(o)+'')<s&&console_log(S),n-1]++<126&&g(o))([])
```
[Try it online!](https://tio.run/##TY2xDoIwFAB3v6IylPcCNAETJx6Do4MOjIQYgrQipM9QNDHh3ysDg@vdJfdsPo1rp/41J5bvnW/ZOh6728hGkHCCCrEhtSI4l9eLcvPUW9PrLzjE3U6Td1SAIaaCq4GcGjtr5ke9LFwZqJRSHB@yGmOwxJvEfFigpNNb624CxigMMXdS/v2hxNgmaR1FeZodpTRrhlDV6DUEexGg/wE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby], ~~111~~ 108 bytes
```
->s,w=[*32..126]{!s[0]? []:w.product(*([w]*(s.size-1))).map{|a|a.map{|n|n<32 ?"": n.chr}*''}.select{|t|t<s}}
```
[Try it online!](https://tio.run/##7ZV9V9JgHIb/51PczmxAsBTLikQyQrO0F8HeEA3HVAoH8YxQGX51eu4byfTYJyjP4TqM/Z4981zX2Xr9g7PxIQoYZ1dMZlCopRdznreQW6oPZ0xtvl5ErZ4feN1ep9n3o2Q6WRvU00njmdZ5kF1IpVLeSaM7jBtxY/IljMPlxRyKjpNH6PnHvVHadUeeCdqBHw3jKI6WzWg0rpYr1f3SaqVcsVsPE7B/joPCit0tMzmamxy6d9wMXH5mCYcAMeNOJzF7OfrHuemoFukSc8RdC8d17LckD1NEmrhHZIgs4RH3iXligcgRi8QD4iGxRDwiHhNPiDzxlFgmCsQKUSSeEavEc6JEvCDKxBqxTrwkNohXxGtik9gi3hBviXfEe2KbqBBVYof4QHwkPhGfiS9EjdjdJevEHrFPfCUaxAHhE00iIA6JI@KYaBHfiO9EmzghQqJDdIkfRI8wRET0iZ/EgDglzohzYkjExIi4kFvJhexajVP/M/jv/1/0T8ovJBgyDCmGHEOSIcuQZsgzJBoyDamGXEOyIduQbsg3JBwyDimHnEPSIeuQdsg7JB4yD6mH3EPyIfuQfsg/FABUAJQA1AAUAVQBlAHUARQCVAKUAtQCFANUA5QD1AMUBFQElATUBBQFVAWUBdQFJmFAZUBpQG1AcUB1QHlAfUCBQIVAiUCNQJFAlUCZQJ1AoUClQKlArUCxQLVAuUC9QMFAxUDJQM1A0UDVQNlA3UDhQOXggg@KUSJx9crxgoZ/jGYHcSvs9qMMgtOufTsFzVgPFPuTgVMNTNQKj@wjZKgprxUaTo1cR1OdfmR/tW@vQ89vtNtJDaV0yvR9PzDGnkteTmV/b5HygpNudFa82mk6XYRT2SmVypWKgzyctdWNzZ3t8mSzftjmyOWofrq607Iube8171w/M91zeus31q13opsrJrf7l/nyadRr3Fxx2394@/KtljG33GRyus5eYnKt6xcIwmbCfsa/AA "Ruby – Try It Online")
This perplexed me for far too long until I realised that I had the test cases mixed up (D'oh!).
It also creates a Cartesian product of the ASCII characters, and filters those "less than" the input string.
### Explanation
`w.product(*([w]*(s.size-1)))` to get the Cartesian product of the ASCII characters, where `w=[*32..126]`. Found [here](https://stackoverflow.com/questions/21347083/cartesian-power-cartesian-product-with-self-arbitrary-times/21347642#21347642)
`a.map{|n|n<32 ?"": n.chr}*''` to then take those arrays of code points and convert them to characters and join them into strings
`.select{|t|t<s}}` to filter down to those strings less than the input string.
**Edit**: Swap out `s.empty?` for `!s[0]`. Everything except `nil` and `false` are truthy in Ruby, and indexing an array out of bounds returns `nil`. So if there is a first element, then the array is not empty.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
f!-Trd\rk
```
[Try it online!](https://tio.run/##K6gsyfj/P01RN6QoJaa@KPv/fyVHJyUA "Pyth – Try It Online")
Contains an unprintable after the `\` so here's a hex dump:
```
00000000: 66 21 2d 54 72 64 5c 7f 72 6b f!-Trd\.rk
```
**Explanation**
* `rk(Q)` Generate a string range from the empty string to the input string. This is a list of all strings strictly smaller than the input, but it also contains characters outside the printable ASCII range.
* `rd\.` Generate a string range from the space character (ascii 32) to the DEL character (ascii 127). This is the range of printable ASCII.
* `f!-T ...` Filter for elements of the first range that contain only elements of the second range.
[Answer]
# [PHP](https://php.net/), 138 bytes
```
$c=unpack('C*',$argn);for(;$i=count($c);){for(;$i;)if(--$c[$i]<32)$c[$i--]=126;else break;if(!$i)array_pop($c);echo pack('C*',...$c),',';}
```
[Try it online!](https://tio.run/##RY1BCsIwFESvUuFDEkkKVnDzW6QIXkKKxJDaUEk@absQ8erGUAQ3w/B4zNBAqT5STjDN4kmbkbPTlknQ8e4F9iFyBNeYsPiZgxEoXj@GwvVcKTAXcF29r8TalOqaXXVA@5hscYtWj5i1DTihY9TPKwVaZ6wZQvG/K8syU8kkw3dKbfsJNLvgp6TOXw "PHP – Try It Online")
The idea is to create an array of ASCII code points and iterate over those.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
UTEΦE⍘⁺!θS⍘ιγ⁼§ι⁰!✂ι¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8kPz09JzWkKDNXQ9OaK6AoM69EwzexQMMtM6cktQjMdEosTg0uAcqkawTklBZrKCkq6Sh45hWUlkBFNTV1FNKBGElhJkgEKORaWJqYU6zhWOKZl5JaARI2AIoCTQBJBudkJqeCxAw1NTWt//9XUOb6r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. I don't know whether I should include the `UT` in the byte count but Charcoal's default of padding all lines to the same length does make distinguishing between strings that might end in spaces very tricky. Explanation:
```
UT
```
Turn off padding.
```
! Literal `!`
⁺ Concatenated with
S Input string
⍘ γ Base conversion using printable ASCII as base 95
E Map over implicit range
⍘ιγ Convert current value to base 95 as printable ASCII
Φ Filter where
§ι⁰ First character
⁼ ! Equals literal `!`
E Map over results
✂ι¹ Slice off first character
Implicitly print
```
If Charcoal had a bijective base conversion function, this could be written `Print(Map(BijectiveBaseString(InputString(), g), BijectiveBaseString(i, g)));` probably for 9 bytes, but unfortunately it doesn't, so the easiest way to fake it is to prefix all values with the same ASCII character and filter out entries that don't begin with that character.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
```
s=>(g=(x='',j=32,b=Buffer)=>(s[x.length]?b(95).map(_=>g(x+b([j++]))):x<s)&&console_log(x))
```
[Try it online!](https://tio.run/##Tc6xDoIwFEDRna@oDPS9FDtoHDQ@TBwddHAkhgC2FYKFUDT16yuDg@u5y23Ld@nqsRmmpe3vKtS9dX2niq43jJhjlLEfyZngdL2cpZvGxppGf8AJzhGjSFNwlIEh8MR52tJ6lVZ0fGmtRpyDy73slDXT43aoYLtB@SwHKCgz4EUFeSvEDRF3fu8wSf4ewCMGDfGCxQgYvg "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
The newest ["nice"](https://oeis.org/wiki/Clear-cut_examples_of_keywords#nice) OEIS sequence, [A328020](https://oeis.org/A328020), was just published a few minutes ago.
>
> Number of distinct tilings of an n X n square with free n-polyominoes.
>
>
>
This sequence counts tilings up to symmetries of the square. The sequence has six terms, but I'd like to see if folks here can extend it further.
# Example
For `n=4` there are 22 such grids, as shown in this image from the OEIS.
[](https://oeis.org/A328020/a328020.png)
*Credit: Jeff Bowermaster, Illustration of A328020(4).*
# Challenge
Like [this previous challenge](https://codegolf.stackexchange.com/q/187763/53884), the goal of this challenge is to compute as many terms as possible in this sequence, which begins `1, 1, 2, 22, 515, 56734` and where the n-th term is the number of tilings of the n X n grid with n-polyominoes.
Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code to generate it. If two users post the same number of terms, then whoever posts their last term earliest wins.
[Answer]
# C, 7 terms
The seventh term is **19846102**. (The first six are 1, 1, 2, 22, 515, 56734, as stated in the question).
```
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define N 7
#define ctz __builtin_ctzl
typedef uint64_t u64;
static u64 board[N*N] = { 0 };
static u64 adjacency_matrix[N*N] = { 0 };
static u64 count = 0;
static u64 check_symmetry()
{
static const u64 symmetries[7][3] = {
{ 0, +N, +1 },
{ N-1, -1, +N },
{ N-1, +N, -1 },
{ N*N-1, -1, -N },
{ N*N-1, -N, -1 },
{ N*N-N, +1, -N },
{ N*N-N, -N, +1 },
};
int order[N];
for (u64 i = 0; i < 7; ++i) {
u64 start = symmetries[i][0];
u64 dcol = symmetries[i][1];
u64 drow = symmetries[i][2];
memset(order, 0xFF, N*sizeof(int));
for (u64 row = 0, col = 0; col < N || (col = 0, ++row < N); ++col) {
u64 base = board[col + N*row];
u64 symmetry = board[start + dcol*col + drow*row];
u64 lex = 0;
while (order[lex] != symmetry && order[lex] != -1)
++lex;
order[lex] = symmetry;
if (lex < base)
return 0;
if (base < lex)
break;
}
}
return 1;
}
static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
{
if (cell >= N) {
++mino;
if (mino == N) {
count += check_symmetry();
return;
}
u64 next = ctz(~occupied);
board[next] = mino;
recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);
return;
}
adjacent &= ~occupied & ~forbidden;
while (adjacent) {
u64 next = ctz(adjacent);
adjacent &= ~(1ul << next);
forbidden |= 1ul << next;
board[next] = mino;
recurse(mino, cell + 1, occupied | 1ul << next, adjacent | adjacency_matrix[next], forbidden);
}
}
int main(void)
{
for (u64 i = 0; i < N*N; ++i) {
if (i % N)
adjacency_matrix[i] |= 1ul << (i - 1);
if (i / N)
adjacency_matrix[i] |= 1ul << (i - N);
if (i % N != N - 1)
adjacency_matrix[i] |= 1ul << (i + 1);
if (i / N != N - 1)
adjacency_matrix[i] |= 1ul << (i + N);
}
recurse(0, 2, 3, 4 | 3 << N, 0);
printf("%ld\n", count);
}
```
[Try it online!](https://tio.run/##nVZtb6JAEP7Or5hrUwMF77Q2bRqlH/uR@wGeMbis7V4RGliu2mp/er2ZXV4W0eSuJArsPDPzzLOzE1j/kbH9/lwkLC4iDpNcRiL9/nRvmUuZSB4P1yKRSFqzziO@FAmHAG7qZybfYD5fFCKWIpnjW2xZcvPC0QwFOt5czyUUN9djy8plKAWjF1ikYRZNg8tgBj68wwB2Y9McRr9DxhO2ma9CpLQ@jWRpkUi0DNrx2RNnz/N8s1pxmW1sx3q3AK8SwdIkV6SgRAieT29n05HKoZB0YTZPPbiBB@4Qdp5hCvpDMtK/Gxw1kVf/0OtSGdUvOG464aUoHPcKtFfDECVSd5Qf0izi2TSYlUvLNAObKhdKNLxN4HYMrisco3IljQwzUtaQSMymAwxkoiKWxh3Q8BCUpa8d0JUBWvFVzqWtuHowWD88eFhZLt54urSxCscp6bdK0FFxjzQHrIYeJtie2y3Y5SLq4hIQlx2qE5fNSiuKizDnCNd9Sa4uEkA/g2QtTNlVNVwr5SotLrUvVXzCPebrsl9Ny@uTiDloBaYImcE3v8nU60Hb0h86LXfVpS5a2/kMpybaQWaxBJs4TZQG3bAZl0WWdAiTmxJtQhV13RYZD58bNjvdmDpGGXI4tnZQH9s/qYjQwoos52p7VyJJPX2aeRzrp5Sx4kXwyDPHhNRv2BcLEUU8qU47USRXuPdx841Nd12KbRRESFoC/wBJlx4xrt8ZKm2tdVFmxa0zkPA1nSYckPZHVYURQXcSgWirNL0mshZFC4JDoPKHLQwL7PiJiu51x6aKhwfKMYM1NEuKlYzQ86HmBj34qBXV8LJHK/jhwDAqrCFN3lYS26BtYOp8sPXNyr4ik9p49x/Ukrh@SrimpSrBUDKaqqtQJDZ1bNVrx@YqzubOZKVOE3CBXdZqng4BMTM0QI8@DA2hdJQfX4gSdKIgF5oogUrxf@Hc46S@Hi5wxu05oXcUh/iVByMPrnGvRoQOmqZ@wU8WubTPLuLoV3Lm6eOKtt1@/8mWcfiY7/v4DeOzu7t9/@foLw) (for N=6, since N=7 would time out.)
On my machine, N=6 took 0.171s, and N=7 took 2m23s. N=8 would take a few weeks.
[Answer]
### An extension to @Grimy's code gets N=8
This just underlines that @Grimy deserves the bounty:
I could prune the search tree by extending the code to check, after each finished polyomino, that the remaining free space is not partitioned into components of size not divisible by N.
On a machine where the original code took 2m11s for N=7, this takes 1m4s, and N=8 was computed in 33h46m. The result is 23437350133.
Here is my addition as a diff:
```
--- tilepoly.c 2019-10-11 12:37:49.676351878 +0200
+++ tilepolyprune.c 2019-10-13 04:28:30.518736188 +0200
@@ -51,6 +51,30 @@
return 1;
}
+static int check_component_sizes(u64 occupied, u64 total){
+ u64 queue[N*N];
+ while (total<N*N){
+ u64 count = 1;
+ u64 start = ctz(~occupied);
+ queue[0] = start;
+ occupied |= 1ul << start;
+ for(u64 current=0; current<count; ++current){
+ u64 free_adjacent = adjacency_matrix[queue[current]] & ~occupied;
+ occupied |= free_adjacent;
+ while (free_adjacent){
+ u64 next = ctz(free_adjacent);
+ free_adjacent &= ~(1ul << next);
+ queue[count++] = next;
+ }
+ }
+ if (count % N){
+ return 0;
+ }
+ total += count;
+ }
+ return 1;
+}
+
static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
{
if (cell >= N) {
@@ -61,6 +85,9 @@
return;
}
+ if(!check_component_sizes(occupied,N*mino))
+ return;
+
u64 next = ctz(~occupied);
board[next] = mino;
recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);
```
[Try it online!](https://tio.run/##nVbbUtswEH33VyxlYGzstElh6IMTHnl0PyDNZBxZAbWOTW25QEv49Ka7ki@S7cxQPAORtWdXu0dHK7PJHWOHw6nIWFolHOalTET@8f7GMacKkd315xKRSZpzThO@FRmHCK7bMZO/Yb3eVCKVIlvjW@o48vmBoxkqdLy@Wkuorq9CxyllLAWjF9jkcZEso4toBQv4A1PYh6Y5Tr7HjGfseb2LMaWn40iWV5lEy9SOz@45@7Eun3c7Lotn13P@OIBPjWB5VqqkoEYIXi6/rJaXag2FpAdXC9TAjwLwZ7APDFM0mZGR/vvRqIm8Jn2vC2VUf9G46YiXSmHcK9JeXYZIkfpF@iEvEl4so1U9tc0LcKlyoUjDnzl8CcH3hWdUrqiRcUHMGhSJ1XKKgUxUwvJ0AJr1QUX@OAB9NkA7viu5dFWuAUyfbm8DrKwUv3m@dbEKz6vTt0rQUXGPdA5YDQ3mKM@XF3DrSeTFJyBOe1QnTpuVNilu4pIjXOuSXH1MAP2MJFtialW1cM2Ur7i40L5U8RH3lD/VejUtj/ci5aAZWCJkBSeLbqXzc7Atk5lnuSuV@mi11zOcumi9lcUWXMpprjgYhi24rIpskDC5KdLmVNHQbVPw@EeXzV4LU8eoQ85CZw/tsSWx6mPL8t1DnvFMrkkBpdrrnLHqQfAkUBzKXMapp3eR3n9WvOKqSegVazYVbI7Tni3tpmnMwlHFYxNzX5sFvQ6jV5kqLgnaWRowvGDQCjU47yNQtKoOVhUFVrYgserhXGWjpKknvKE6twXn67opUoaD/qhTqwOsVnAObQE9RRiZWlHDMTlaiF5eTW4Zf2pIs@HhAG6Xcb6AV7dmi4KMONRlEUG@T7wTzobtneGItKn3@AyiXtqdnId@Si/gL7RAQqezGoptBfsrFwkakPSSq73diSzX@mQ8TfXI1m1Tu35DTWxEkvCsuZ5U3ugKNwvM2@hSvk@xjRNISJqCRQ9Jjy6dyujdguEIEyYPRnj3ZPwstvVEF7S@542GdI4IZOxU6R5KINpgXWcXT7OrmcXrr5MvGMoJhgdCxcOrxDODdfXWtVpabGPj4Wm3xuonrbR7V6VR4Yj63yL4dj2jg9hafztNSkH@G9iSOH@MuE6bDWFIGbXoXSwyl6TfiHbsiwJb7uCbgiQr1IG0JDNIQKwMDtBjAjODKB3l0zuiRIMomAvdpZFa4v/C@eNJvT9c5IX2Dal3FD9fPgdwGcAV7tUloaNO1A/4sS637oezNPmWfQj0ufeoRR0Of9k2je/Kw@Tr5T8 "C (gcc) – Try It Online")
] |
[Question]
[
For each node in a balanced binary tree, the maximum difference in the heights of the left child subtree and the right child subtree are at most 1.
The height of a binary tree is the distance from the root node to the node child that is farthest from the root.
Below is an example:
```
2 <-- root: Height 1
/ \
7 5 <-- Height 2
/ \ \
2 6 9 <-- Height 3
/ \ /
5 11 4 <-- Height 4
```
Height of binary tree: 4
The following are binary trees and a report on whether or not they are balanced:
[](https://i.stack.imgur.com/KNwp0.gif)
The tree above is **unbalanced**.
[](https://i.stack.imgur.com/rOPLN.png)
The above tree is **balanced**.
Write the shortest program possible that accepts as input the root of a binary tree and returns a falsey value if the tree is unbalanced and a truthy value if the tree is balanced.
**Input**
The root of a binary tree. This may be in the form of a reference to the root object or even a list that is a valid representation of a binary tree.
**Output**
**Returns truthy value:** If the tree is balanced
**Returns falsey value:** If the tree is **un**balanced.
**Definition of a Binary Tree**
A tree is an object that contains a value and either two other trees or pointers to them.
The structure of the binary tree looks something like the following:
```
typedef struct T
{
struct T *l;
struct T *r;
int v;
}T;
```
If using a list representation for a binary tree, it may look something like the following:
```
[root_value, left_node, right_node]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ḊµŒḊ€IỊ;߀Ạ
```
[Try it online!](https://tio.run/##y0rNyan8///hjq5DW49OAlKPmtZ4PtzdZX14PpD1cNeC/4fbgYz//6O5ok0MdBSiTYA4FoiNQQxDMGEMFYoFEYamcB6CNIEJmoIYJhYgwhxZl4klQhdIC1e0oSGQZ4ZkIaq5FlCeoQGSRhAfZJAhqtkg9xkb4rZOhysWAA "Jelly – Try It Online")
The empty tree is represented by `[]`.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 49 bytes
```
N+_/B/C:-X+B,Y+C,abs(X-Y)<2,N is max(X,Y)+1.
0+e.
```
[Try it online!](https://tio.run/##XY7BTsMwEETP8VdYPa1lO46JA20AIbX3HhCHRAhFBrmoUpqg2FU4@deDnRYKHEaaWc2@3Y@hb/t3bsf9NG1pI9ZiU/KKrllNN0y/Wqh4Te6u2BbvLT7oT6hYTahMUUZNOjljXfOmrYGnwRiCS44SQEnS0JhZcI/GHluH77Ebjub292CnW2tQQkJr1w8H7WDhxxL7Dvsx9Z3vFux5ppw2XkiK0APHl5MqE6CEEZArATIqD8mQYIrZkFmgYoKiCG4ZdHMuqdWlFNh/0FIKuD7Tv1mwjElmpxivrIJ@aHn4Q/5DB@70BQ "Prolog (SWI) – Try It Online")
Represents trees as `Value/Left_Child/Right_Child`, with the empty tree being the atom `e`. Defines `+/2`, which outputs through success or failure, with an unbound variable (or one already equal to the tree's height) on the left and the tree on the right--if the height argument is unacceptable, add 9 bytes to define `-T:-_+T.`.
```
N + _/B/C :- % If the second argument is a tree of the form _Value/B/C,
X+B, % X is the height of its left child which is balanced,
Y+C, % Y is the height of its right child which is balanced,
abs(X-Y) < 2, % the absolute difference between X and Y is strictly less than 2,
N is max(X,Y)+1. % and N is the height of the full tree.
0 + e. % If, on the other hand, the second argument is e, the first is 0.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
```
f@_[x_,y_]:=f@x&&f@y&&-2<Depth@x-Depth@y<2;f@_=1>0
```
Use `Null` for null, `value[left, right]` for nodes. For example, the following tree is written as `2[7[2[Null, Null], 6[5[Null, Null], 11[Null, Null]]], 5[Null, 9[4[Null, Null], Null]]]`.
```
2
/ \
7 5
/ \ \
2 6 9
/ \ /
5 11 4
```
[Try it online!](https://tio.run/##XU7RCoJAEHz3KxaEezrJ9c7UUrmHnqP35RAJRUEjwkCJvv0yMkth2WF2Zme3zbuqaPOuPufGlCqjPuNDpndJqXrGSjUw5njxobh2leqdDw6xtx@tCaauOd3qS0c2OCmUZGsNDDbKgod0SdLx3jQchCQcS0z03TUH9P@5/qEFAPIr@j7JkGTAQUazR/PRg0jb@cQ6K5w4ugthSseIMFh@IwUJXI2i5a5@mhc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~133~~ 125 bytes
```
b=lambda t:((max(l[0],r[0])+1,abs(l[0]-r[0])<2)if(l:=b(t[1]))[1]and(r:=b(t[2]))[1]else(0,0))if t else(0,1)
h=lambda t:b(t)[1]
```
[Try it online!](https://tio.run/##tU/LToQwFN3zFU3YtLFj6MAoEvkA/YWmMcUp0ligaYuRr8dLGXRM3Lq4r3PPPT21c@jGIS@tW3RvRxeQ9AGl6HmC0o4O9fJdD29IIqMBGSeIFoVOIR/cutCDnUJiaji7NTooJ82L@pAGxwUmZGlqI/vmLFGoMO7lJzY8E9RBIjeMysZH4BCBxyPRLTZV3eDAmSAEkhzO2G3IcUOU8QpnNCNARgFdRkaS7ucpoK/UxYLLgDtsCEnSp9WTj/9S0s/odbTzwYJ1VSUpLzLKC8oF5TkUtkYeRwHBTpd2T8UGnKAUJcT9N7V4@EUVIM0Y5Xe7@pVSGVuW7cg6wDW7EgMLOftDW4jlf2S/AA "Python 3.8 (pre-release) – Try It Online")
Takes a tree in the "list" format: A node is `[value, left, right]` with `left` and `right` being nodes.
Invoke the function `h`.
Returns `0` or `False` for an unbalanced tree.
Returns `1` or `True` for a balanced tree.
## Ungolfed:
```
# Returns tuple (current height, subtrees are balanced (or not))
def balanced(tree):
if tree: # [] evaluates to False
left = balanced(tree[1])
right = balanced(tree[2])
# If the subtrees are not both balanced, nothing to do, just pass it up
if left[1] and right[1]:
height = max(left[0], right[0]) + 1
subtrees_balanced = abs(left[0] - right[0]) < 2
else:
height = 0 # Value doesn't matter, will be ignored
subtrees_balanced = False
else:
height = 0
subtrees_balanced = True
return (height, subtrees_balanced)
def h(tree):
return balanced(tree)[1]
```
-10: Reversed logic to get rid of `not`s
If taking arguments in the middle of a call is allowed, this could be shortened to (115 bytes)
```
(b:=lambda t:((max(l[0],r[0])+1,abs(l[0]-r[0])<2)if(l:=b(t[1]))[1]and(r:=b(t[2]))[1]else(0,0))if t else(0,1))(_)[1]
```
with `_` being the tree to check.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
h=([l,r])=>l?(d=h(l)-h(r))*d<2?1+h(d>0?l:r):NaN:1
```
[Try it online!](https://tio.run/##ZY5RDoIwDIbfPUmnwzAZoihwAy6w7IEwwjQLM8N4/VmYosaHv/27tf16bR7N2LrL7R4NVnXe6wKEoU6SojQVqEKDIZEGR8hanXcV22hQZVyZ3JG8buqc@dYOozXd1tgeNAghJBUhSsqSqQg2RfHZJpj46@PdybOlkx9Rh9mmOMQnxZKQ0@oPJZah9Gtl4MWS4pL9zAgv2ccn7BeHdzLMjE0c/wQ "JavaScript (Node.js) – Try It Online")
-9 bytes by Arnauld.
---
# JavaScript, 58 bytes
```
h=([l,r])=>l?(l=h(l),r=h(r),m=l>r?l:r,m+m-l-r<2?m+1:NaN):1
```
[Try it online!](https://tio.run/##ZY7REoIgEEXf@xIYsZHELAv9A3@A4cExJ2sWabDp922FspoeLvcu7O7h2jyasXWX2z0e7Kmbpl4SBcxpKkuoCMieAGUOzVFmJJSugsIxE5kYYnfcVCbiRd3UtOBTa4fRQrcGeyY9UUpppsKpGU/nIsQMJXxM0cTr4d0p8qVT7FE7HzMcErMSTelh9YdSy1D2tTLwEs1wydYzwk3@ySn/xeE/OTrnnjM9AQ "JavaScript (Node.js) – Try It Online")
Use `[]` for null, and `[left, right, value]` for nodes.
[Answer]
# JavaScript, 162 bytes
```
f=x=>{for(f=0,s=[[x,1]];s[0];){if(!((d=(t=s.pop())[0]).a&&d.b||f))f=t[1];if(f&&t[1]-f>1)return 0;if(d.a)s.push([d.a,t[1]+1]);if(d.b)s.push([d.b,t[1]+1])}return 1}
```
[Try it online!](https://tio.run/##TYzBCoMwEER/pb2EXarBnGX9kZBD0rjUHlSSWAT129NIS@ltmPdmnvZl4z0Mc6rHyfc5M63UbTwFYGqqSFqvlTKmjboxLW4DwxXAEySKcp5mQCwApRXCS7fvjMiUtDJtMVmIM9bcKQx9WsJ4ac7eS4tlvcQH6JKrU7opgx/m/pj7seN7oI6c3w "JavaScript (Node.js) – Try It Online")
The format of the input is an object
```
root={a:{node},b:{node},c:value}
```
## Explanation
```
for(f=0,s=[[x,1]];s[0];){if(!((d=(t=s.pop())[0]).a&&d.b||f))f=t[1]
```
Performing breadth first search find the depth of the first node which is missing one or more branches.
```
if(f&&t[1]-f>1)return 0;if(d.a)s.push([d.a,t[1]+1]);if(d.b)s.push([d.b,t[1]+1])}
```
Continuing the breadth first search, return zero if any element is two deeper than the depth of the first node missing branches.
```
return 1}
```
If no such node is found, return 1
[Answer]
# Julia, 56 bytes
```
f(t)=t!=()&&(-(f.(t.c)...)^2<2 ? maximum(f,t.c)+1 : NaN)
```
With the following struct representing the binary tree:
```
struct Tree
c::NTuple{2,Union{Tree,Tuple{}}}
v::Int
end
```
`c` is a tuple representing the left and right nodes and the empty tuple `()` is used to signal the absence of a node.
Falsey value is `NaN`, any integer is truthy.
[Answer]
# [Kotlin](https://kotlinlang.org), 67 bytes
```
fun N.c():Int=maxOf(l?.c()?:0,r?.c()?:0)+1
fun N.b()=l?.c()==r?.c()
```
Where
```
data class N(val l: N? = null, val r: N? = null, val v: Int = 0)
```
[Try it online!](https://tio.run/##ZY0xDsIwDEXn5hQeY1GhskaEipElDJzAFLWqcFOaphUIcfaSEMGCvXw/f/tfe8@tXS7kCSqmcQQjZ2JgBaYEDXZiziES90dmBQfrAypwqScLZl1JVAHpju7HWnIZQamK3H0VrjYiWc8SdTJondafHx21VpJrRgV75@ixPXnX2maHT5HFzCHEGZkaMf/pNKcS2S3ceLZyiDEoXssb "Kotlin – Try It Online")
[Answer]
# C, 117 bytes
```
h(T*r){r=r?1+h(h(r->l)>h(r->r)?r->l:r->r):0;}b(T*r){return r->l&&!b(r->l)||r->r&&!b(r->r)?0:abs(h(r->l)-h(r->r))<=1;}
```
Struct implementation is the following:
```
typedef struct T
{
struct T * l;
struct T * r;
int v;
} T;
```
[Try This on JDoodle](http://jdoodle.com/a/1rdN)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~99~~ ~~96~~ 94 bytes
```
lambda A:A==[]or(abs(D(A[1])-D(A[2]))<2)*f(A[1])*f(A[2])
D=lambda A:A>[]and-~max(map(D,A[1:]))
```
[Try it online!](https://tio.run/##bU7BDoIwDL37FRw3MxIKQ5E4ExL@ou4wQogmMghy0Iu/PgsIYuLh9bUv7Xttn/2lsaGr1NndTF2UxsvSTCnUTcdMcWc5yxA09wcONefHkG@rSRuZtE2uvqcn1MaW/qs2D1abluWCdlM6dG13tb1XMZSBQClQC4yIYEA0jpoA8aedi5yEmEgmhP2yKg8/q/TIEgEgcDenrByTsYVgVoaBXGBlSq9E8CeD/N0b "Python 2 – Try It Online")
3 bytes from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king).
Takes input as: empty node is `[]`, and other nodes are `[<value>, <leftNode>, <rightNode>]`. Outputs `0/1` for False/True.
] |
[Question]
[
Adapted from [this FiveThirtyEight riddle](https://fivethirtyeight.com/features/can-you-unravel-these-number-strings/).
## Background
Examine the following infinite sequence:
```
3 3 3 2 3 3 3 2 3 3 3 2 3 3 2 3 3 3 2 ...
```
Let's say the sequence is 1-indexed. The `i`th number in the sequence determines how many `3`s there are before the `i`th `2` and following any previous `2`s. So since the sequence starts with a `3` the sequence must begin `3 3 3 2` and since there are three `3`s at the beginning of the sequence the subsequence `3 3 3 2` must repeat itself three times. After that you reach `3 3 2` because the fourth number in the sequence is `2`.
The FiveThirtyEight riddle asks for the limit of the ratios of threes to twos (which I won't spoil here) but you can also ask what the cumulative ratio is after index `i`. For example the ratio at `i=4` is `3/1 = 3` and at `i=15` it's `11/4 = 2.75`.
**Let's get general**
Given numbers `n` and `k` we can make a similar sequence that starts with `n` and just like the original sequence described the number at index `i` determines how many `n`s show up before the `i`th `k` and following any previous `k`s.
Examples:
`n=2, k=5` gives the sequence `2 2 5 2 2 5 2 2 2 2 2 5 2 2 5 ...`
`n=3, k=0` gives `3 3 3 0 3 3 3 0 3 3 3 0 0 3 3 3 0 ...`
`n=1, k=3` gives `1 3 1 1 1 3 1 3 1 3 1 3 1 1 1 3 1 ...`
## The Challenge
Write a function/program and with it do the following. Take as input:
* a positive integer `n`
* a nonnegative integer `k ≠ n`
* a positive integer `i > n`
The first two inputs `n` and `k` determine a sequence as described above and `i` is an index. I am using 1-indexing in the examples but you have the freedom to use 0- or 1-indexing. If 0-indexed then the restriction on `i` is `i ≥ n`.
With the three numbers output the ratio of `n`s to `k`s in the sequence up to and including the number at the index `i`. The format of the output can either be a decimal value with at least 5 digits of precision or an exact value as a ratio like `3524/837` or `3524:837`.
In decimal form, the last digit can be rounded however you like. Trailing zeros and whitespace are allowed.
In either of the string forms the two numbers need to be normalized so that they are coprime. For example if the ratio was 22/4, `11/2` and `11:2` are acceptable but `22/4` is not.
**Examples**
```
n k i output
2 4 15 2.75 or 11/4
6 0 666 5.1101 or 557:109
50 89 64 63 or 63:1
3 2 1000 2.7453 or 733/267
9 12 345 9.4545 or 104/11
```
This is code golf per language, so shortest code in each language is the winner.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
¤/#ωȯ↑⁰J¹`C∞²N¹²
```
[Try it online!](https://tio.run/##AS4A0f9odXNr///CpC8jz4nIr@KGkeKBsErCuWBD4oiewrJOwrnCsv///zn/MTL/MzQ1 "Husk – Try It Online")
Takes inputs in the same order as the test cases.
Outputs a rational number.
I feel like this has too many superscripts, but I don't know how to get rid of them...
## Explanation
```
¤/#ωȯ↑⁰J¹`C∞²N¹² Inputs are n, k, i.
N Starting with the natural numbers [1,2,3..
ωȯ do this until a fixed point is reached:
Argument is a list s.
∞² Take the infinite list [n,n,n..
`C and split it to the lengths in s.
J¹ Join the resulting blocks with k.
↑⁰ Take the first i elements.
Call the result x.
¤ ¹² For each of n and k,
# count their number of occurrences in x
/ and perform exact division on the results.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~94~~ ~~92~~ ~~89~~ 87 bytes
```
def g(n,k,i):o,t=[n],0;exec('o+=[n]*o[t]+[k];t+=1;'*i);return-1-i/(o[1:i+1].count(n)-i)
```
[Try it online!](https://tio.run/##FcfBDoIwDADQX/FGyzp1ogdZ@JJlJ5zYkLRkKYl@/dTbe9vHXipDa4/yPCwgtBLjqGRTkkznWN5lhk7dv70myy6tOZqbQux6xliL7VV88HwCTWFkF/Jx1l0MBD1j2yr/vMCdwoWG6w2xfQE "Python 3 – Try It Online")
# Credits
* Reduced from 94 to 92 bytes: [Colera Su](https://codegolf.stackexchange.com/users/75905/colera-su).
* Reduced from 92 to 89 bytes: [dylnan](https://codegolf.stackexchange.com/users/75553/dylnan).
* Reduced from 89 to 87 bytes: [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
³ẋЀ;€⁴Ẏḣ⁵
ẋ`;ÇÐLLƙ`÷/
```
[Try it online!](https://tio.run/##y0rNyan8///Q5oe7ug9PeNS0xhqIHzVuebir7@GOxY8at3IBJRKsD7cfnuDjc2xmwuHt@v///zf@b/Tf0MDAAAA "Jelly – Try It Online")
Full program. Takes arguments `n`, `k`, `i`.
There's a bug that makes this need to be unnecessarily longer by 1 byte.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-9 bytes ~50% attributable to [Erik the Outgolfer's Jelly answer](https://codegolf.stackexchange.com/a/150270/53748) (1. using the new-ish key quick `ƙ` even with a bug in the interpreter currently costing a byte; 2. using a mapped repetition to avoid counting and indexing into the current sequence.) Go give him some credit!
```
³ẋЀj⁴ṁ⁵µÐLLƙ`÷/
```
A full program taking three arguments: `n`, `k`, `i` which prints the result.
**[Try it online!](https://tio.run/##ATIAzf9qZWxsef//wrPhuovDkOKCrGrigbThuYHigbXCtcOQTEzGmWDDty////85/zEy/zM0NQ "Jelly – Try It Online")**
### How?
```
³ẋЀj⁴ṁ⁵µÐLLƙ`÷/ - Main link
µ - monadic chain separation
ÐL - apply the monadic chain to the left repeatedly until no change occurs:
³ - program's 1st argument, n
Ѐ - map across the current sequence (initially just n)
ẋ - repeat (the first run give triangle of n i.e. [[n],[n,n],...,[n]*n]
⁴ - program's 2nd argument, k
j - join
⁵ - program's 3rd argument, i
ṁ - mould like (repeat the list to fill, or cut it, to length i)
ƙ - keyed application, map over groups of identical items:
` - (this has an arity of 2, make it monadic by repeating the argument)
L - length -> [numberOfNs, numberOfKs]
/ - reduce with:
÷ - division -> [numberOfNs / numberOfKs]
- implicit print (a single item list just prints its content)
```
example run with inputs `n=2`, `k=3`, `i=30`:
```
Start the "loop until no change", ÐL
Note: Initial left argument, n=2, implicitly range-ified by Ѐ to become [1,2]
1. mapped repeat of n: [[2],[2,2]]
join with k: [2,3,2,2]
mould like i: [2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3]
2. mapped repeat of n: [[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2]]
join with k: [2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2]
mould like i: [2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
^different to previous result
3. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2]
^different to previous result
4. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
^different to previous result
5. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
all the same as the previous result; stop loop and yield this.
length applied to equal elements: [length([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]), length([3,3,3,3,3,3,3,3,3])]
= [21,9]
reduce by division = [21/9] = [2.3333333333333335]
implicit print 2.3333333333333335
```
[Answer]
# Mathematica, 85 bytes
```
(s={#};Do[s=Join[s,#~Table~s[[t]],{#2}],{t,#3}];Last@@Ratios@Tally@s[[#+3;;#3+#+2]])&
```
[Try it online!](https://tio.run/##Rcs7C8IwFAXg3b9xQZTeIY82WEIhg5M4iHQLd4jS0kIfYLJISf967CJdDpyPc0YXumZ0oX@71Fbp5KsFor7O1le3uZ@sR1hr9xqa1VsbiHABEbcMCDKSvjsfjHlu/9mb2g3D12w7yKTWIDPIBNH5mB6ffgqmtQJz5AUd/l0hQ6XUDgXDS4kq30WiQM4Y26VELlDmBaUf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~126~~ 70 bytes
```
k n i←⎕
j←⍴v←⍬
:While j<i
v,←k,⍨n⍴⍨{v≢⍬:j⊃v⋄n}j+←1
:End
÷/+/¨n k⍷¨⊂j⍴v
```
[Try it online!](https://tio.run/##HY27DoJAEEX7@YrpwfDcjRBbezprCKIuZLUiMcZGjQ8MxsYfsKKwNKHHP5kfwdHqnHtzMxOvikG6jovlrKfbI4roeBdA51PW56gx4cg1qB/rd/nHC8LJfFFMUY0SKE3ucpPqRvOAsSnp8uRRqKjal3Q96K0yeONAONYpfFrLsLpGY0512zVU7dTvcM8v@wx8dNERkIGNEqWUbMMABSef1UUPHdu2WR0XA/R88QU)
Well, thanks to @Adám for obliterating 56 bytes out of this answer.
This is a niladic Tradfn (**trad**itional **f**unctio**n**) taking 1 input, which is a 3 element list.
`⎕PP←5` is not added to the byte count because it's only used to limit the **P**rint **P**recision to **5** digits.
`∇f` and `∇` are not added to the byte count because they're not part of the code, only delimiters for the tradfn.
### How it Works:
```
k n i←⎕ ⍝ Take input (←⎕) for k, n and i.
j←⍴v←⍬ ⍝ Assign (←) an empty vector (⍬) to v, then assign its shape (⍴, which is 0) to j.
:While j<i ⍝ while j<i, do:
v,←k,⍨n⍴⍨{v≢⍬:j⊃v⋄n}j+←1 ⍝ this:
j+←1 ⍝ increment j (+←1)
{v≢⍬: } ⍝ if (:) v does not match (≢) ⍬
j⊃v ⍝ return the jth element of v (v[j])
⋄n ⍝ else (⋄) return n
n⍴⍨ ⍝ shape (⍴) n as the result (repeats n result times)
k,⍨ ⍝ append (,⍨) k
v,← ⍝ append to (,←) v
:End ⍝ End while loop
÷/+/¨n k⍷¨⊂j⍴v ⍝ then:
j⍴v ⍝ shape (⍴) v as j (truncates v to j elements)
⊂ ⍝ enclose the resulting vector
¨ ⍝ for each element
⍷ ⍝ find (returns a boolean vector)
n k ⍝ n and k (⍷ will return a boolean vector for each)
+/¨ ⍝ cumulative sum of each vector (returns the number of times n and k appear in v)
÷/ ⍝ divide them and implicitly return the result.
```
[Answer]
# [R](https://www.r-project.org), 88 bytes
```
function(n,k,i){s=rep(n,n);for(j in 1:i){s=c(s,k,rep(n,s[j]))};z=sum(s[1:i]==n);z/(i-z)}
```
[Try it online!](https://tio.run/##JctBDsIgEAXQvaeY5UwyRrBA1IaTNF01klAjNWA3NT07Drqb9/@fXIOvYU3TOy4JEz840qf4fH8JEvVhyThDTKBvv2LCIpt/XYZ5JNr7zZf1iWWQyei9PG0njMeN9hrwzGAYtKVDQMegGJxzDVbOy1VomjoGWWqlVJPEWtgZS/UL "R – Try It Online")
[Answer]
# [Swift](https://swift.org), 152 bytes
```
func f(n:Int,k:Int,i:Int){var a=[0];(1...i).map{a+=(0..<(a.count>$0 ?a[$0]:n)).map{_ in n}+[k]};let m=a[1...i].filter{n==$0}.count;print("\(m)/\(i-m)")}
```
Will it be shorter than Java?
## Explanation
```
func f(n:Int,k:Int,i:Int){
var a=[0] // Initialize the array (the zero is to
// define the type of the array and will be
// ignored by the code)
(1...i).map{ // Repeat i times (more than enough):
a+=(0..<(a.count>$0 ?a[$0]:n)).map{_ in n} // Add the right amount of n:s to the array
+[k] // Add k to the array
} // End repeat
let m=a[1...i].filter{n==$0}.count // Count the amount of n:s in the first
// i elements of the array
print("\(m)/\(i-m)") // Print the result
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~77~~ ~~71~~ 70 bytes
```
->n,k,i{r=[n]
i.times{|c|r+=[n]*r[c]+[k]}
1r*(j=r[1,i].count n)/(i-j)}
```
[Try it online!](https://tio.run/##PctLDsIgFIXhOau4wz5uK9hCdIAbIUwkpqGNaCgMTNu1IyaG4flyfh/vnzTJ1N0cLmg3L5XTxPbBPh/rtpvdtz9pvDK6VYs@CPNNNUuvGFrdm1d0AVx9qmw310d6x7DCpM4IIwLjmvxBIFAEIUQRnvflmm0sNCDkkFFKC@UDyzaMXKcv "Ruby – Try It Online")
Returns a Rational, which both operates as a number and stringifies to the exact reduced fraction.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
AEtcH/e.u<sm+*d]QGNH]Q)G
```
[Test suite.](http://pyth.herokuapp.com/?code=AEtcH%2Fe.u%3Csm%2B%2ad%5DQGNH%5DQ%29G&test_suite=1&test_suite_input=2%0A4%2C15%0A6%0A0%2C666%0A50%0A89%2C64%0A3%0A2%2C1000%0A9%0A12%2C345&debug=0&input_size=2)
Fixed point of `[n]` under certain function of array.
[Answer]
# [Zephyr](http://github.com/dloscutoff/zephyr), 284 bytes
```
input n as Integer
input k as Integer
input m as Integer
set s to Array(m)
for i from 1 to n
set s[i]to n
next
set s[i]to k
set N to n
set K to 1
for a from 2 to m
for b from 1 to s[a]
inc i
if i<=m
set s[i]to n
inc N
end if
next
inc i
if i<=m
set s[i]to k
inc K
end if
next
print N/K
```
Takes the three numbers from stdin on three separate lines. Outputs an exact ratio such as `104/11` or `63`.
### Ungolfed
```
input n as Integer
input k as Integer
input maxIndex as Integer
set sequence to Array(maxIndex)
for i from 1 to n
set sequence[i] to n
next
set sequence[i] to k
set nCount to n
set kCount to 1
for a from 2 to maxIndex
for b from 1 to sequence[a]
inc i
if i <= maxIndex
set sequence[i] to n
inc nCount
end if
next
inc i
if i <= maxIndex
set sequence[i] to k
inc kCount
end if
next
print nCount / kCount
```
] |
[Question]
[
Your challenge is to create a regex that matches every string permutation of itself, and nothing else. The match must also be case-sensitive.
So, for example, if your regex is:
```
ABC
```
It should match (and only match) these strings:
```
ABC
ACB
BAC
BCA
CAB
CBA
```
It shouldn't match things like:
```
AABC (contains an extra A)
ABCD (contains an extra D)
AC (no B)
AAA (no B and C, extra 2 A's)
abc (case-sensitive)
```
## Rules:
* You are allowed to use any flavour of regex you like.
* Standard loopholes apply.
* You must have at least two different characters in your code. That means solutions like `1` are invalid.
* The regex should contain only printable ASCII, and nothing else.
[Answer]
# JavaScript, ~~64~~ 57 bytes
4 bytes removed thanks to Martin Ender.
```
^(?!.*([^])(.*\1){3}]?)[$$[-^?!!.'''-*11{33}5577\\-]{57}$
```
[Try it here.](https://regex101.com/r/XIYlQv/5)
### Explanations (outdated)
```
^ # Beginning of the string.
(?!.* # Match only the strings that don't contain...
(.)(.*\1){4} # 5 occurrences of the same character.
[^1]?[^1]? # Something that doesn't matter.
)
[]zzz^(?!!!.**[)\\1{{44}}666]{64} # 64 occurrences of these 16 characters.
# Some are duplicated to make sure the regex
# contains 4 occurrences of each character.
\z # End of the string.
```
[Answer]
# JavaScript, 50 bytes
```
^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,//{50}$]{50}$
```
[Try it on regex101](https://regex101.com/r/pZsC0P/1)
The key to beating [jimmy23013's solution](https://codegolf.stackexchange.com/a/100703/17216) was to reduce the number of repetitions of each character from 3 to 2.
### Explanation
`^(?!([^])+.*\1.*\1)` - assert that no character in the string is repeated at least 3 times
`([^])+` is equivalent to `.*([^])`.
`[^]` works because JavaScript allows empty character classes (unlike most other regex engines, at least by default). It is equivalent to `[\W\w]` or `.` with the `/s` flag, i.e. it matches any character including newlines. For our purposes here, newlines don't matter, so it's equivalent to `.`.
Using `^(?!([^])+.*\1.*\1)` instead of `(?!.*([^])(.*\1){2})` or `^(?!(.)+.*\1.*\1)` eliminates the need for a third `(`, `)`, or `.`, and this is the key to reducing the number of repetitions of every character from 3 to 2.
`^`...`[?!ZZ-__==''-22+,,//{50}$]{50}$` - assert that the entire string consists of the 25 characters `?` `!` `Z` `[` `\` `]` `^` `_` `=` `'` `(` `)` `*` `+` `,` `-` `.` `/` `0` `1` `2` `{` `5` `}` `$` and is 50 characters in length. Combined with the first assertion this guarantees that every character occurs exactly twice (due to the generalized pigeonhole principle, if any character occurred only once, some other character would have to occur three times).
`Z-_` is the range `Z[\]^_`. It's essential, because we already used `[`, `\`, `]`, and `^` twice each. We need to double the `Z` and `_`, because they aren't used elsewhere.
`'-2` is the range `'()*+,-./012`. It's essential, because we already used `(`, `)`, `*`, `.`, and `1` twice each. We need to double the `'`, `,`, `/`, and `2`, because they aren't used elsewhere.
There is no other way besides ranges to include the above in our character class, because octal or hexadecimal escape codes would require using `\`, and a negative character class would require using `^`.
`==` is extra padding to get us to 50 characters. It could be any arbitrary doubled character. We need it because if we went for `{48}`, we'd need to include two `0` somewhere, which would bring our 48 back up to 50.
Note that this can be trivially rearranged to include the delimiters:
```
/^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,{50}$]{50}$/
```
[Try it on regex101](https://regex101.com/r/pZsC0P/2)
# Perl / PCRE, 57 bytes
I'm pretty sure it's impossible to do 2 repetitions in Perl/PCRE, because `[^]` is not available (except with the PCRE2\_ALLOW\_EMPTY\_CLASS flag), and the only other alternatives use `\` – for example `\C`, `\N`, `\X`, `\S`, and `[^\0]`. So, with 3 repetitions:
```
^(?!(.)*(.*\1){3})[[[-\]\]^^??!!'''-*.11{335577}$$-]{57}$
```
[Try it on regex101](https://regex101.com/r/pZsC0P/3)
This is very similar to [jimmy23013's JavaScript solution](https://codegolf.stackexchange.com/a/100703/17216). It doesn't work under JavaScript however, because `^(?!(.)*(.*\1){3})` can always match on any string; it would capture an unset `\1` by doing zero repetitions on `(.)*`, and then `\1` would match an empty string 3 times.
Making it portable to both JavaScript and Perl/PCRE by using `(.)+` instead of `(.)*` would end up making it 60 bytes, due to adding the `+` character.
Alternatively:
```
((.)+(.*\2){3})?+^[[[-\]\]^^??+'''-**.22{335577}$$-]{57}$
```
[Try it on regex101](https://regex101.com/r/pZsC0P/4)
This uses the possessive quantifier `?+` to atomically try to match a character repeated 4 times. If such a match is not found, it will be forced to do zero repeats (instead of one) and the `^` will match. Otherwise it will match something non-empty, and the `^` won't match.
[Answer]
# Perl and PCRE regex, 280 bytes
```
^(?=(.*z){2})(?=(.*\(){43})(?=(.*\)){43})(?=(.*\*){22})(?=(.*\.){23})(?=(.*0){2})(?=(.*1){6})(?=(.*2){16})(?=(.*3){7})(?=(.*4){4})(?=(.*5){1})(?=(.*6){3})(?=(.*7){2})(?=(.*8){2})(?=(.*9){1})(?=(.*=){22})(?=(.*\?){22})(?=(.*\\){11})(?=(.*\^){2})(?=(.*\{){23})(?=(.*\}){23}).{280}\z
```
(Slightly) more readable:
```
^
(?=(.*z){2})
(?=(.*\(){43})
(?=(.*\)){43})
(?=(.*\*){22})
(?=(.*\.){23})
(?=(.*0){2})
(?=(.*1){6})
(?=(.*2){16})
(?=(.*3){7})
(?=(.*4){4})
(?=(.*5){1})
(?=(.*6){3})
(?=(.*7){2})
(?=(.*8){2})
(?=(.*9){1})
(?=(.*=){22})
(?=(.*\?){22})
(?=(.*\\){11})
(?=(.*\^){2})
(?=(.*\{){23})
(?=(.*\}){23})
.{280}\z
```
This runs in O(2^n) time as written, so is incredibly inefficient. The easiest way to test it is to replace every occurrence of `.*` with `.*?`, which causes the case where it matches to be checked first (meaning that it matches in linear time, but still takes exponential time if it fails to match).
The basic idea is that we enforce the length of the regex to equal 280, and use lookahead assertions to force each character in the regex to appear at least a certain number of times, e.g. `(?=(.*z){2})` forces the `z` character to appear at least twice. `2+43+43+22+23+2+6+16+7+4+1+3+2+2+1+22+22+11+2+23+23` is 280, so we can't have any "extra" occurrences of any characters.
This is a programming example of an [autogram](https://en.wikipedia.org/wiki/Autogram), a sentence that describes itself by listing the number of each character it contains (and, in this case, also the total length). I got fairly lucky in constructing it (normally you have to use brute force but I stumbled across this solution while testing my brute-force program before I'd fully finished writing it).
# Perl and PCRE regex, 253 bytes, in collaboration with Martin Ender
I hypothesized that there might be shorter solutions which omit some digits (most likely 9, 8, or 7). Martin Ender found one, shown below:
```
^(?=(.*z){2})(?=(.*\(){39})(?=(.*\)){39})(?=(.*\*){20})(?=(.*\.){21})(?=(.*0){4})(?=(.*1){6})(?=(.*2){11})(?=(.*3){6})(?=(.*4){3})(?=(.*5){2})(?=(.*6){3})(?=(.*9){4})(?=(.*=){20})(?=(.*\?){20})(?=(.*\\){9})(?=(.*\^){2})(?=(.*{){21})(?=(.*}){21}).{253}\z
```
Readable version:
```
^
(?=(.*z){2})
(?=(.*\(){39})
(?=(.*\)){39})
(?=(.*\*){20})
(?=(.*\.){21})
(?=(.*0){4})
(?=(.*1){6})
(?=(.*2){11})
(?=(.*3){6})
(?=(.*4){3})
(?=(.*5){2})
(?=(.*6){3})
(?=(.*9){4})
(?=(.*=){20})
(?=(.*\?){20})
(?=(.*\\){9})
(?=(.*\^){2})
(?=(.*{){21})
(?=(.*}){21})
.{253}\z
```
] |
[Question]
[
*This is inspired by one of Downgoat's questions in Sandbox, where I suggested that he include April 31 as Pi day for people who use day/month format, only for him to inform me that there is no April 31!*
Given a date string in *month/day* format that might be invalid, output the correct date using rollover. (First rollover the month, then rollover the day).
**Examples:**
**"15/43"** - This reads as the 43rd day of the 15th month. First, we roll over the month to the next year, so we end up with 3 (March). Now, since March only has 31 days, we rollover the extra days to April, so we output the actual date as **"4/12"** (April 12th).
**"3/16"** - This is a valid date (March 16th). Return it as is.
**"12/64"** - Ah, so many fond memories from December 64th... December has 31 days, January has 31 days, so what I really mean is **"2/2"** (February 2nd).
**"19/99"** - First, the 19 becomes a 7 (July). July has 31 days, August has 31 days, September has 30 days, so the output is **"10/7"** (October 7th).
**"1/99999"** - A year has 365 days. 99999 (mod 365) = 354. The 354 day of the year is **"12/20"**.
**"9999999/10"** - Apparently, 9999999 (mod 12) = 3, so this is **"3/10"** (March 10th).
**Criteria:**
Input month is an integer > 0. Input day is an integer > 0. Year never needs to be specified, as such there are no leap years to deal with.
**Update:**
As I think it would overly simplify the challenge, calendar functions, such as those in the Java [Calendar](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) class, are banned. Date parsing/formatting functions are still allowed though.
[Answer]
# LabVIEW, 32 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
[](https://i.stack.imgur.com/nn6fy.gif)
[Answer]
## C#, ~~269~~ 223
```
string v(string n){var x=new[]{31,28,31,30,31,30,31,31,30,31,30,31};var s=n.Split('/');Func<string,int> p=int.Parse;var m=p(s[0]);var d=p(s[1]);m=m>=12?m%12:m;while(d>x[m]){d-=x[m];m=++m>=12?m%12:m;}return(m==0?1:m)+"/"+d;}
```
**Edit**: Fixed to work for cases like 24/1, 36/1, etc. and golfed a little. Thanks for the comments, there are several places I saved a bit!
Ungolfed:
```
string v(string n)
{
var x = new [] { 31 ,28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };
var s = n.Split('/');
Func<string,int> p = int.Parse;
var m = p(s[0]);
var d = p(s[1]);
m = m >= 12 ? m % 12 : m;
while (d > x[m])
{
d -= x[m];
m = ++m >= 12 ? m % 12 : m;
}
return (m==0?1:m) + "/" + d;
}
```
[Answer]
## R, ~~208~~ 182 bytes
```
m=c(31,28,31,30,31,30,31,31,30,31,30,31)
e=scan(sep="/");n=(e[1]/12-1)*12;if(!n%%12)n=12;if(n<0)n=e[1];j=e[2];while((j<-j-m[n])>0){n=n+1;if(n>12)n=1};j=m[n]+j;cat(n,j,sep="/")
```
Get the month by dividing by 12, then loop, removing the number of days of the current month until you get a negative number., inverse last step and print.
On multiple lines (need to use a file and source it):
```
m=c(31,28,31,30,31,30,31,31,30,31,30,31)
e=scan(sep="/")
n=(e[1]/12-1)*12
if(!n%%12)n=12
if(n<0)n=e[1]
j=e[2]
while((j<-j-m[n])>0){n=n+1;if(n>12)n=1}
j=m[n]+j;cat(n,j,sep="/")
```
[Answer]
# JavaScript (ES6), 106 bytes
```
s=>eval('q="030101001010";p=s.split`/`;for(d=i=p[1],m=p[0]-1;i--;d>n&&(m++,d-=n))n=31-q[m%=12];m+1+"/"+d')
```
## Explanation
```
s=>
eval(` // use eval to enable for loop without needing to write {} or return
q="030101001010"; // q = array of 31 - days in each month
p=s.split\`/\`; // p = array of [ month, day ]
for(
d=i=p[1], // d = day
m=p[0]-1; // m = month - 1
i--; // loop for each day, this is more iterations than needed but extra
// iterations do not affect the result and it's the shortest way
// to guarantee all months have been subtracted from d, it also
// ensures the loop runs at least once to get m % 12
d>n&&(m++,d-=n) // if too many days, subtract the month's days and increment month
)
n=31-q[m%=12]; // n = number of days in month, get m % 12
m+1+"/"+d // return the result
`)
```
## Test
```
var solution = s=>eval('q="030101001010";p=s.split`/`;for(d=i=p[1],m=p[0]-1;i--;d>n&&(m++,d-=n))n=31-q[m%=12];m+1+"/"+d')
```
```
<input type="text" id="input" value="19/99" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# PHP >= 5.5, 181 bytes
```
list($m,$d)=explode("/",$argv[1]);$m%=12;$d%=365;$i=0;while($d>100)$d-=[31,28,31,30,31,30,31,31,30,31,30,31][$i++];$m+=$i;echo date_create_from_format("m/d","$m/$d")->format("n/j");
```
PHP *almost* supports rollover with date parsing and formatting instructions alone. For example:
```
echo date_create_from_format("m/d","12/64")->format("n/j"); // Output: 2/2
```
However, once either number gets bigger than 100, PHP rejects parsing it and returns an error (probably for some arbitrary reason). So, the theory with this answer is to get it back down to where PHP will parse it, then submit it to [`date_create_from_format()`](http://php.net/manual/en/datetime.createfromformat.php).
Ungolfed:
```
list($month, $day) = explode("/", $argv[1]);
$month = $month % 12;
$day = $day % 365;
$i = 0;
$days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
while($day > 31) $day -= $days[$i++];
$month += $i;
echo DateTime::createFromFormat("m/d", $month . "/" . $day)->format("n/j");
```
[Try it online](https://3v4l.org/6AVYl)
] |
[Question]
[
Given a positive integer N,
determine the starting pattern on a N x N-grid that yield
the longest non-repeating sequence under Game of Life-rules, and ends
with a fixed pattern (cycle of length 1), played on a torus.
The goal is not the shortest program, but the quickest.
Since the world is finite, you will eventually end up in a loop,
thus repeating an already visited state. If this loop has period 1, then the starting pattern is a valid candidate.
Output: Starting pattern and total number of unique states in the sequence (including starting pattern).
Now, the 1x1-torus is special, since a cell may be considered neighbouring to itself or not, but in practice, there is no problem, a single living cell will in either case just die (of overcrowding or loneliness).
Thus, input 1 yields a sequence of length 2, the sequence being one cell living, then forever dead.
The motivation for this question is that is an analogue of the busy beaver function, but definitely less complex, since we have a bound on memory. This will be a nice sequence to include on OEIS, as well.
For N=3, the sequence length is 3, any pattern on the left hand side reaches a completely black 3x3-square, and then dies. (All patterns that are part of 1-cycle removed).

[Answer]
## C++ up to N=6
```
3x3 answer 3: 111 000 000
4x4 answer 10: 1110 0010 1100 0000
5x5 answer 52: 11010 10000 11011 10100 00000
6x6 answer 91: 100011 010100 110011 110100 101000 100000
```
This technique is centered around a fast next state function. Each board is represented as a bitmask of N^2 bits, and bit-twiddly tricks are used to compute the next state for all cells at once. `next` compiles down to about 200 100 assembly instructions for N <= 8. Then we just do the standard try-all-states-until-they-repeat and pick the longest one.
Takes a few seconds up to 5x5, a few hours for 6x6.
```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define N 6
typedef uint64_t board;
// board is N bits by N bits, with indexes like this (N=4):
// 0 1 2 3
// 4 5 6 7
// 8 9 10 11
// 12 13 14 15
#if N==3
#define LEFT_COL (1 + (1<<3) + (1<<6))
#define RIGHT_COL ((1<<2) + (1<<5) + (1<<8))
#define ALL 0x1ffULL
#elif N==4
#define LEFT_COL 0x1111ULL
#define RIGHT_COL 0x8888ULL
#define ALL 0xffffULL
#elif N==5
#define LEFT_COL (1ULL + (1<<5) + (1<<10) + (1<<15) + (1<<20))
#define RIGHT_COL ((1ULL<<4) + (1<<9) + (1<<14) + (1<<19) + (1<<24))
#define ALL 0x1ffffffULL
#elif N==6
#define LEFT_COL (1 + (1<<6) + (1<<12) + (1<<18) + (1<<24) + (1ULL<<30))
#define RIGHT_COL ((1<<5) + (1<<11) + (1<<17) + (1<<23) + (1<<29) + (1ULL<<35))
#define ALL 0xfffffffffULL
#else
#error "bad N"
#endif
static inline board north(board b) {
return (b >> N) + (b << N*N-N);
}
static inline board south(board b) {
return (b << N) + (b >> N*N-N);
}
static inline board west(board b) {
return ((b & ~LEFT_COL) >> 1) + ((b & LEFT_COL) << N-1);
}
static inline board east(board b) {
return ((b & ~RIGHT_COL) << 1) + ((b & RIGHT_COL) >> N-1);
}
board next(board b) {
board n1 = north(b);
board n2 = south(b);
board n3 = west(b);
board n4 = east(b);
board n5 = north(n3);
board n6 = north(n4);
board n7 = south(n3);
board n8 = south(n4);
// add all the bits bitparallel-y to a 2-bit accumulator with overflow
board a0 = 0;
board a1 = 0;
board overflow = 0;
#define ADD(x) overflow |= a0 & a1 & x; a1 ^= a0 & x; a0 ^= x;
a0 = n1; // no carry yet
a1 ^= a0 & n2; a0 ^= n2; // no overflow yet
a1 ^= a0 & n3; a0 ^= n3; // no overflow yet
ADD(n4);
ADD(n5);
ADD(n6);
ADD(n7);
ADD(n8);
return (a1 & (b | a0)) & ~overflow & ALL;
}
void print(board b) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d", (int)(b >> i*N+j & 1));
}
printf(" ");
}
if (b >> N*N) printf("*");
printf("\n");
}
int main(int argc, char *argv[]) {
// Somewhere in the starting pattern there are a 1 and 0 together. Using translational
// and rotational symmetry, we can put these in the first two bits. So we need only consider
// 1 mod 4 boards.
board steps[10000];
int maxsteps = -1;
for (board b = 1; b < 1ULL << N*N; b += 4) {
int nsteps = 0;
board x = b;
while (true) {
int repeat = steps + nsteps - find(steps, steps + nsteps, x);
if (repeat > 0) {
if (repeat == 1 && nsteps > maxsteps) {
printf("%d: ", nsteps);
print(b);
maxsteps = nsteps;
}
break;
}
steps[nsteps++] = x;
x = next(x);
}
}
}
```
[Answer]
I see the following possible solution approaches:
* Heavy theory. I know there is some literature on Life on a torus, but I haven't read much of it.
* Brute force forwards: for every possible board, check its score. This is basically what Matthew and Keith's approaches do, although Keith reduces the number of boards to check by a factor of 4.
+ Optimisation: canonical representation. If we can check whether a board is in canonical representation much quicker than it takes to evaluate its score, we get a speed-up of a factor of about 8N^2. (There are also partial approaches with smaller equivalence classes).
+ Optimisation: DP. Cache the score for each board, so that rather than walking them through until they converge or diverge we just walk until we find a board we've seen before. In principle this would give a speed-up by a factor of the average score / cycle length (maybe 20 or more), but in practice we're likely to be swapping heavily. E.g. for N=6 we'd need capacity for 2^36 scores, which at a byte per score is 16GB, and we need random access so we can't expect good cache locality.
+ Combine the two. For N=6, the full canonical representation would allow us to reduce the DP cache to about 60 mega-scores. This is a promising approach.
* Brute force backwards. This seems odd at first, but if we assume that we can easily find still lifes and that we can easily invert the `Next(board)` function, we see that it has some benefits, although not as many as I originally hoped.
+ We don't bother with diverging boards at all. Not much of a saving, because they are quite rare.
+ We don't need to store scores for all of the boards, so there should be less memory pressure than the forward DP approach.
+ Working backwards is actually quite easy by varying a technique I saw in the literature in the context of enumerating still lifes. It works by treating each column as a letter in an alphabet and then observing that a sequence of three letters determines the middle one in the next generation. The parallel with enumerating still lifes is so close that I've refactored them together into an only slightly awkward method, `Prev2`.
+ It might seem that we can just canonicalise the still lifes, and get something like the 8N^2 speed-up for very little cost. However, empirically we still get a big reduction in the number of boards considered if we canonicalise at each step.
+ A surprisingly high proportion of boards have a score of 2 or 3, so there is still memory pressure. I found it necessary to canonicalise on the fly rather than building the previous generation and then canonicalising. It might be interesting to reduce memory usage by doing depth-first rather than breadth-first search, but doing so without overflowing the stack and without doing redundant calculations requires a co-routine / continuation approach to enumerating the previous boards.
I don't think that micro-optimisation will let me catch up with Keith's code, but for the sake of interest I'll post what I have. This solves N=5 in about a minute on a 2GHz machine using Mono 2.4 or .Net (without PLINQ) and in about 20 seconds using PLINQ; N=6 runs for many hours.
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sandbox {
class Codegolf9393 {
internal static void Main() {
new Codegolf9393(4).Solve();
}
private readonly int _Size;
private readonly uint _AlphabetSize;
private readonly uint[] _Transitions;
private readonly uint[][] _PrevData1;
private readonly uint[][] _PrevData2;
private readonly uint[,,] _CanonicalData;
private Codegolf9393(int size) {
if (size > 8) throw new NotImplementedException("We need to fit the bits in a ulong");
_Size = size;
_AlphabetSize = 1u << _Size;
_Transitions = new uint[_AlphabetSize * _AlphabetSize * _AlphabetSize];
_PrevData1 = new uint[_AlphabetSize * _AlphabetSize][];
_PrevData2 = new uint[_AlphabetSize * _AlphabetSize * _AlphabetSize][];
_CanonicalData = new uint[_Size, 2, _AlphabetSize];
InitTransitions();
}
private void InitTransitions() {
HashSet<uint>[] tmpPrev1 = new HashSet<uint>[_AlphabetSize * _AlphabetSize];
HashSet<uint>[] tmpPrev2 = new HashSet<uint>[_AlphabetSize * _AlphabetSize * _AlphabetSize];
for (int i = 0; i < tmpPrev1.Length; i++) tmpPrev1[i] = new HashSet<uint>();
for (int i = 0; i < tmpPrev2.Length; i++) tmpPrev2[i] = new HashSet<uint>();
for (uint i = 0; i < _AlphabetSize; i++) {
for (uint j = 0; j < _AlphabetSize; j++) {
uint prefix = Pack(i, j);
for (uint k = 0; k < _AlphabetSize; k++) {
// Build table for forwards checking
uint jprime = 0;
for (int l = 0; l < _Size; l++) {
uint count = GetBit(i, l-1) + GetBit(i, l) + GetBit(i, l+1) + GetBit(j, l-1) + GetBit(j, l+1) + GetBit(k, l-1) + GetBit(k, l) + GetBit(k, l+1);
uint alive = GetBit(j, l);
jprime = SetBit(jprime, l, (count == 3 || (alive + count == 3)) ? 1u : 0u);
}
_Transitions[Pack(prefix, k)] = jprime;
// Build tables for backwards possibilities
tmpPrev1[Pack(jprime, j)].Add(k);
tmpPrev2[Pack(jprime, i, j)].Add(k);
}
}
}
for (int i = 0; i < tmpPrev1.Length; i++) _PrevData1[i] = tmpPrev1[i].ToArray();
for (int i = 0; i < tmpPrev2.Length; i++) _PrevData2[i] = tmpPrev2[i].ToArray();
for (uint col = 0; col < _AlphabetSize; col++) {
_CanonicalData[0, 0, col] = col;
_CanonicalData[0, 1, col] = VFlip(col);
for (int rot = 1; rot < _Size; rot++) {
_CanonicalData[rot, 0, col] = VRotate(_CanonicalData[rot - 1, 0, col]);
_CanonicalData[rot, 1, col] = VRotate(_CanonicalData[rot - 1, 1, col]);
}
}
}
private ICollection<ulong> Prev2(bool stillLife, ulong next, ulong prev, int idx, ICollection<ulong> accum) {
if (stillLife) next = prev;
if (idx == 0) {
for (uint a = 0; a < _AlphabetSize; a++) Prev2(stillLife, next, SetColumn(0, idx, a), idx + 1, accum);
}
else if (idx < _Size) {
uint i = GetColumn(prev, idx - 2), j = GetColumn(prev, idx - 1);
uint jprime = GetColumn(next, idx - 1);
uint[] succ = idx == 1 ? _PrevData1[Pack(jprime, j)] : _PrevData2[Pack(jprime, i, j)];
foreach (uint b in succ) Prev2(stillLife, next, SetColumn(prev, idx, b), idx + 1, accum);
}
else {
// Final checks: does the loop round work?
uint a0 = GetColumn(prev, 0), a1 = GetColumn(prev, 1);
uint am = GetColumn(prev, _Size - 2), an = GetColumn(prev, _Size - 1);
if (_Transitions[Pack(am, an, a0)] == GetColumn(next, _Size - 1) &&
_Transitions[Pack(an, a0, a1)] == GetColumn(next, 0)) {
accum.Add(Canonicalise(prev));
}
}
return accum;
}
internal void Solve() {
DateTime start = DateTime.UtcNow;
ICollection<ulong> gen = Prev2(true, 0, 0, 0, new HashSet<ulong>());
for (int depth = 1; gen.Count > 0; depth++) {
Console.WriteLine("Length {0}: {1}", depth, gen.Count);
ICollection<ulong> nextGen;
#if NET_40
nextGen = new HashSet<ulong>(gen.AsParallel().SelectMany(board => Prev2(false, board, 0, 0, new HashSet<ulong>())));
#else
nextGen = new HashSet<ulong>();
foreach (ulong board in gen) Prev2(false, board, 0, 0, nextGen);
#endif
// We don't want the still lifes to persist or we'll loop for ever
if (depth == 1) {
foreach (ulong stilllife in gen) nextGen.Remove(stilllife);
}
gen = nextGen;
}
Console.WriteLine("Time taken: {0}", DateTime.UtcNow - start);
}
private ulong Canonicalise(ulong board)
{
// Find the minimum board under rotation and reflection using something akin to radix sort.
Isomorphism canonical = new Isomorphism(0, 1, 0, 1);
for (int xoff = 0; xoff < _Size; xoff++) {
for (int yoff = 0; yoff < _Size; yoff++) {
for (int xdir = -1; xdir <= 1; xdir += 2) {
for (int ydir = 0; ydir <= 1; ydir++) {
Isomorphism candidate = new Isomorphism(xoff, xdir, yoff, ydir);
for (int col = 0; col < _Size; col++) {
uint a = canonical.Column(this, board, col);
uint b = candidate.Column(this, board, col);
if (b < a) canonical = candidate;
if (a != b) break;
}
}
}
}
}
ulong canonicalValue = 0;
for (int i = 0; i < _Size; i++) canonicalValue = SetColumn(canonicalValue, i, canonical.Column(this, board, i));
return canonicalValue;
}
struct Isomorphism {
int xoff, xdir, yoff, ydir;
internal Isomorphism(int xoff, int xdir, int yoff, int ydir) {
this.xoff = xoff;
this.xdir = xdir;
this.yoff = yoff;
this.ydir = ydir;
}
internal uint Column(Codegolf9393 _this, ulong board, int col) {
uint basic = _this.GetColumn(board, xoff + col * xdir);
return _this._CanonicalData[yoff, ydir, basic];
}
}
private uint VRotate(uint col) {
return ((col << 1) | (col >> (_Size - 1))) & (_AlphabetSize - 1);
}
private uint VFlip(uint col) {
uint replacement = 0;
for (int row = 0; row < _Size; row++)
replacement = SetBit(replacement, row, GetBit(col, _Size - row - 1));
return replacement;
}
private uint GetBit(uint n, int bit) {
bit %= _Size;
if (bit < 0) bit += _Size;
return (n >> bit) & 1;
}
private uint SetBit(uint n, int bit, uint value) {
bit %= _Size;
if (bit < 0) bit += _Size;
uint mask = 1u << bit;
return (n & ~mask) | (value == 0 ? 0 : mask);
}
private uint Pack(uint a, uint b) { return (a << _Size) | b; }
private uint Pack(uint a, uint b, uint c) {
return (((a << _Size) | b) << _Size) | c;
}
private uint GetColumn(ulong n, int col) {
col %= _Size;
if (col < 0) col += _Size;
return (_AlphabetSize - 1) & (uint)(n >> (col * _Size));
}
private ulong SetColumn(ulong n, int col, uint value) {
col %= _Size;
if (col < 0) col += _Size;
ulong mask = (_AlphabetSize - 1) << (col * _Size);
return (n & ~mask) | (((ulong)value) << (col * _Size));
}
}
}
```
[Answer]
# Factor
```
USING: arrays grouping kernel locals math math.functions math.parser math.order math.ranges math.vectors sequences sequences.extras ;
IN: longest-gof-pattern
:: neighbors ( x y game -- neighbors )
game length :> len
x y game -rot 2array {
{ -1 -1 }
{ -1 0 }
{ -1 1 }
{ 0 -1 }
{ 0 1 }
{ 1 -1 }
{ 1 0 }
{ 1 1 }
} [
v+ [
dup 0 <
[ dup abs len mod - abs len mod ] [ abs len mod ]
if
] map
] with map [ swap [ first2 ] dip nth nth ] with map ;
: next ( game -- next )
dup [
[
neighbors sum
[ [ 1 = ] [ 2 3 between? ] bi* and ]
[ [ 0 = ] [ 3 = ] bi* and ] 2bi or 1 0 ?
] curry curry map-index
] curry map-index ;
: suffixes ( seq -- suffixes )
{ }
[ [ [ suffix ] curry map ] [ 1array 1array ] bi append ]
reduce ;
! find largest repeating pattern
: LRP ( seq -- pattern )
dup length iota
[ 1 + [ reverse ] dip group [ reverse ] map reverse ] with
map dup [ dup last [ = ] curry map ] map
[ suffixes [ t [ and ] reduce ] map [ ] count ] map
dup supremum [ = ] curry find drop swap nth last ;
: game-sequence ( game -- seq )
1array [
dup [
dup length 2 >
[ 2 tail-slice* [ first ] [ last ] bi = not ]
[ drop t ] if
] [ LRP length 1 > not ] bi and
] [ dup last next suffix ] while ;
: pad-to-with ( str len padstr -- rstr )
[ swap dup length swapd - ] dip [ ] curry replicate ""
[ append ] reduce prepend ;
:: all-NxN-games ( n -- games )
2 n sq ^ iota [
>bin n sq "0" pad-to-with n group
[ [ 48 = 0 1 ? ] { } map-as ] map
] map ;
: longest-gof-pattern ( n -- game )
all-NxN-games [ game-sequence ] map [ length ] supremum-by but-last ;
```
Some time stats:
```
IN: longest-gof-pattern [ 3 longest-gof-pattern ] time dup length . .
Running time: 0.08850873500000001 seconds
3
{
{ { 1 1 1 } { 0 0 0 } { 0 0 0 } }
{ { 1 1 1 } { 1 1 1 } { 1 1 1 } }
{ { 0 0 0 } { 0 0 0 } { 0 0 0 } }
}
IN: longest-gof-pattern [ 4 longest-gof-pattern ] time dup length . .
Running time: 49.667698828 seconds
10
{
{ { 0 1 1 0 } { 0 1 0 0 } { 0 1 0 0 } { 1 1 0 1 } }
{ { 0 1 1 0 } { 0 1 0 0 } { 0 1 0 0 } { 0 0 0 1 } }
{ { 0 1 1 0 } { 0 1 0 0 } { 0 0 1 0 } { 1 1 0 0 } }
{ { 0 1 1 0 } { 0 1 0 0 } { 0 0 1 0 } { 0 0 0 1 } }
{ { 0 1 1 0 } { 0 1 0 0 } { 0 0 1 0 } { 1 1 0 1 } }
{ { 0 1 1 0 } { 0 1 0 0 } { 0 0 1 1 } { 0 0 0 1 } }
{ { 0 1 0 1 } { 0 1 0 1 } { 0 0 1 1 } { 1 1 0 1 } }
{ { 1 1 0 1 } { 1 1 0 1 } { 0 0 0 0 } { 1 1 0 0 } }
{ { 1 1 0 1 } { 1 1 0 1 } { 0 0 1 1 } { 1 1 1 1 } }
{ { 0 0 0 0 } { 0 0 0 0 } { 0 0 0 0 } { 0 0 0 0 } }
}
```
And testing 5 crashed the REPL. Hmph.
The most inefficient portion of the program is probably the function game-sequence. I might be able to make it better later.
] |
[Question]
[
Given a binary integer inclusively between `0` and `1111111111111111` (i.e. a 16-bit unsigned integer) as input, output the same integer in [negabinary](https://mathworld.wolfram.com/Negabinary.html).
The input can be in whatever format is most convenient for your language; for example, if it is easier for the program to handle input with 16 digits, like `0000000000000101`, rather than simply `101`, you can write the program to only accept input that way.
## Sample I/O
```
> 1
1
> 10
110
> 1010
11110
> 110111001111000
11011001110001000
> 1001001
1011001
```
Here is a [sample program](https://web.archive.org/web/20141225180424/https://dl.dropboxusercontent.com/u/25059665/BaseConverter.htm) I wrote that does base conversions, including negative and non-integer bases. You can use it to check your work.
[Answer]
# APL, 21 characters
```
'01'[-(16/¯2)⊤-2⊥⍎¨⍞]
```
I used Dyalog APL for this, with `⎕IO` set to 0, allowing us to index arrays starting at 0 rather than 1.
Explanation, from right to left:
* `⍞` gives us the user's input as a character vector.
* `⍎¨` applies the execute function (`⍎`) to each (`¨`) of the aforementioned characters, resulting in a vector of integer 1's and 0's.
* `2⊥` decodes the vector from base 2 into decimal.
* `-` negates the resulting decimal integer.
* `(16/¯2)⊤` encodes the decimal integer into base `¯2` (negative 2). (`16/¯2` replicates `¯2`, `16` times, yielding 16 digits in our negabinary number.)
* `-` negates each element of our newly encoded number (before this, it consists of -1's and 0's), so that we can use it to index our character vector.
* `'01'[ ... ]` indexes the character array (`'01'`) using the 0's and 1's of the negated negabinary vector. This is so we get a prettier output.
Example:
```
'01'[-(16/¯2)⊤-2⊥⍎¨⍞]
10111010001
0001101011010001
```
[Answer]
# Ruby, 32 31 characters
```
m=43690
'%b'%(gets.to_i(2)+m^m)
```
Uses the [negabinary calculation shortcut](https://en.wikipedia.org/wiki/Negative_base#To_negabinary).
[Answer]
## GolfScript, 34 29 27 characters
```
n*~]2base{.2%\(-2/.}do;]-1%
```
A plain straigt-forward approach. It is quite interesting that the shortest version is the one which first converts to number and then back to base -2 (at least the shortest version I could find up to now). But the nice thing about this one is, that it contains almost 15% `%`.
*Edit 1:* For base 2 we can save one modulo operation and also join both loops.
*Edit 2:* I found an even shorter code to convert binary string to integer.
[Answer]
## Haskell, ~~86~~ 83 Bytes
```
import Data.Bits
import Data.Digits
c n|m<-0xAAAAAAAA=digits 2$xor(unDigits 2 n+m)m
```
Call using c and then an integer array for digits, e.g.
```
c [1,1]
```
PS: I'm new, did I submit this correctly?
EDIT: Saved some bytes thanks to Laikoni and also fixed some typos
EDIT2: Alternatively, c :: String -> String:
```
import Data.Bits
import Data.Digits
c n|m<-0xAAAAAAAA=concatMap show.digits 2$xor(unDigits 2(map(read.(:[]))n)+m)m
```
For 114 bytes (but you call it with a string: c "11")
[Answer]
## Python (2.x), 77 characters
(not as short as the other solutions due to the need to manually switch base...)
Should satisfy the requirements.
```
i=input();d=""
while i:i,r=i//-2,i%-2;i+=r<0;d+=`r+[0,2][r<0]`
print d[::-1]
```
Suggestions for further improvements are welcome!
Feed it with starting values like this:
`0b1001001`
[Answer]
## JavaScript, 68 bytes
```
function(b){for(r='',n=parseInt(b,2);r=(n&1)+r,n>>=1;n=-n);return r}
```
Would be 52 bytes in ES6, but that post-dates the challenge:
```
b=>eval(`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes, language postdates challenge
```
Ḅb-2
```
[Try it online!](https://tio.run/nexus/jelly#@/9wR0uSrtH///@jDXUMdQx0DHUgNIwFYRvEAgA "Jelly – TIO Nexus")
Takes input, and produces output, as a list of digits.
## Explanation
```
Ḅb-2
Ḅ Convert binary to integer
b-2 Convert integer to base -2
```
This is pretty much just a direct translation of the specification.
[Answer]
# k, 17 bytes noncompeting
Some of the features used probably postdate the challenge.
```
1_|2!{_.5+x%-2}\2/
```
Input is a list of 1's and 0's, and output is also a list of 1's and 0's.
[](https://i.stack.imgur.com/Xupzk.png)
[Answer]
# PHP, 69 Bytes
```
for($i=bindec($argn);$i;$i+=$i%2&$c,$i>>=1,$c^=1)$r=($i%2).$r;echo$r;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/7160ab7652db0829712bea72dd809bd7c4fdd1e7)
[Answer]
# ES8, 54B
```
b=>eval`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
C2(в
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f2Ujjwqb//w0NDA0A "05AB1E – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input as a binary string, output as a negabinary digit array.
```
Íì2n
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zewybg&input=IjEwMTAi)
Or, taking input as a binary digit array:
```
ì2JÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7DJKyQ&input=WzEsMCwxLDBd)
] |
[Question]
[
Thanks to @ComradeSparklePony for the title.
This challenge should be very simple. You are given three lists.
The first is a list of first names, in title case.
The second is a list of adjectives, in lower case.
The third is a list of nouns, in lower case.
Please randomly select a name, optional adjective, and noun, and output `<Name>'s <adjective> <noun>`. However, each word must begin with the same letter. You can assume that all words begin with a letter. You can also assume (but note in your answer if you do):
* that all words are composed solely of alphabetic characters
* that there is at least one noun for each name
* that there is at least one name for each noun
You cannot however assume that an adjective exists for a particular pair of name and noun, as the adjective is optional so the output will still be valid.
You do not have to select the shared letter uniformly, although all available letters must have a non-zero chance of occurring. You must however ensure that all outputs for a given letter have as near equal chance of occurring as possible within the limits of your language's random number generator. In the case of the adjective, this is equivalent to having an extra entry meaning "no adjective for this letter" which has the same chance as all of the other adjectives for that letter.
Example input lists:
```
Joan Neil Nicola Oswald Sherman Stephanie
new novel old original second silent
jeep noun novel output second sheep snake
```
Example outputs for these inputs (each line is a separate example):
```
Stephanie's second second
Sherman's silent snake
Oswald's original output
Nicola's novel novel
Neil's noun
Joan's jeep
```
Note no extra space between words in the last two examples.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code that breaks no standard loopholes wins!
In the unlikely event that it helps, you can input everything in upper case, but you still need to output in sentence case.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27 25~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Erik the Outgolfer (use a zero instead of a space character)
```
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K
```
A full program accepting an argument in the form of a Python formatted list of lists of strings which prints the output to STDOUTt.
**[Try it online!](https://tio.run/##y0rNyan8///o7kdNa4wOLTs6qeDhjvlAtkHUwx2Ljk4qdT226Vh7xNE9jxrmqBcDiUcNc73///8fHa3ul5qZo66joO6XmZyfkwhi@ReXJ@akgFjBGalFuYl5YGZJakFGYl5mqnqsDpdCtHpeajlIOC@/LBWsPR@iI78oMz0zLxEsVJyanJ8HFi3OzEnNK4HpzC/NQ9VaWlJQWoKmIyM1tQDMyEvMBtoZCwA "Jelly – Try It Online")**
### How?
```
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K - Main Link: list of lists of lists of characters
€ ¦ - sparse application...
2 - ...to indices: [2]
Ż - ...action: prepend a zero (place holder for no adjective)
Œp - Cartesian product (all choices, including invalid ones)
€ - for each:
ḟ 0 - filter out any zeros
Ƈ - filter keep those for which:
Ʋ - last four links as a monad:
Z - transpose
Ḣ - head
Œu - upper-case
E - all equal?
X - random (uniform) choice e.g. [['B','o','b'],['b','l','u','e'],['b','a','g']]
ż - zip with:
“'s“” - list [["'", 's'], []] [[['B','o','b'],["'", 's']],[['b','l','u','e'],[]],['b','a','g']]
K - join with spaces [['B','o','b'],["'", 's'],' ',['b','l','u','e'],[],' ','b','a','g']
- implicit (smashing) print Bob's blue bag
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24 23~~ 21 bytes
Assumes there is a noun for each name, as allowed by the challenge.
```
„'s«I¯ªâI‘ʒl€нË}Ωðý
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcM89eJDqz0PrT@06vAiz8OLHjWtOT3n1KQcIH1h7@Hu2nMrD284vPf//2glv9TMHCUdBSW/zOT8nEQQy7@4PDEnBcQKzkgtyk3MAzNLUgsyEvMylWK5opXyUstBYnn5ZalgvfkQ5flFmemZeYlgoeLU5Pw8sGhxZk5qXglEX35pHqrG0pKC0hI09RmpqQVgRl5idqpSLAA "05AB1E – Try It Online")
**Explanation**
```
„'s« # append "'s" to all names in the name-list
I¯ª # append an empty list to the adjective-list
â # cartesian product between the lists
Iâ # cartesian product with the noun-list
€˜ # deep flatten each sublist
ʒ } # filter, keep only lists that when
l # converted to lowercase
€н # with only heads kept
Ë # have all elements equal
Ω # pick a valid list uniformly at random
ðý # and join by spaces
```
[Answer]
# [R](https://www.r-project.org/), ~~155~~ 148 bytes
-7 bytes thanks to Giuseppe (using `*` for `sample`)
```
function(x,y,z){`*`=sample
while(T)T=length(unique(c(tolower(substr(c(a<-x*1,b<-c(y,"")*1,c<-z*1),1,1)),"")))-2
paste0(a,"'s ",b,if(nchar(b))" ",c)}
```
[Try it online!](https://tio.run/##Xc87bsMwDIDhPacQtFQyaKDubF8hGZIDhFboSKhCuXrUSYqe3VUHd@jIH/wIMK7TsE6FTXaB1R0e8NRf5@Y8JLzNnnaLdZ7USZ8GT3zNVhV2H4WUUTn4sFBUqYwpxxqwb@9NB2PfGvUAKXUdTN8@m05DB53Wv03r9m03Y8r0qhDkSxISRnCTYmMxqlFrWYvR3@ukkkFWeZB7cl7snQkexSEt6C/iaCnekMUx02yRHUlYhnoexIaYFsHhk7wIdT9Ed3WMXiQygS8i1a84SxD/VSi8sZLnkv@AJZpFYnynTen1Bw "R – Try It Online")
Uses rejection sampling: draw at random a name, an adjective (possibly the empty string) and a noun until the first letters match. This condition is checked by counting if the number of unique elements in the vector formed of the first letters, plus the empty string, is of length 2 - this allows for an empty adjective.
Then print the result, with an extra space if the adjective is non-empty.
The different possibilities starting with the same letter have equal occurrence probabilities, since `sample` draws from the uniform distribution. The easiest way to see this is to condition on the event that the name and noun start with the same letter (which is fine: if they don't, we would reject). Now condition on the event that we accept: this means we draw either the empty adjective, or an adjective starting with the same letter. Each of these possibilities still has equal probability.
[Check the probabilities on \$10^5\$ replicates.](https://tio.run/##TZDNbsIwEITvPMXKl9poIzWVeiOvQA/wAGzMQtyadeqfBqj67KlpVdTjjPTt7EycD918KGKzC6LPeMGr@dwtd12i0@h5MQ3Os96abedZjnnQRdx7YW11Dj5MHHUqfcqxGrRqzssW@1Vj9QWVMlXYVXNdtgZbbI25ecY0T4uRUuZHTageEijs0R202IGi7o1R1bHmaxY6cYIOkiXRuVNrdh7WzgZP8JIm8nvYDBxPJLDJPA4kjhVOXQ1Z0P71Hyk8gYQP9hAqFKI7OiEPiW2QPaRaULJC@EUlFPkfe9N/dMljyXduYB4hCb3xHc7U17Uij95Zyqxbfkao3W5VEOpXCD/36wzzNw)
[Answer]
# JavaScript (ES6), ~~139 124 122~~ 120 bytes
*Save 2 bytes thanks to @Neil*
Takes input as `(names,adjectives)(nouns)`.
```
(N,a)=>F=n=>/^(.)\S+( \1\S+)+$/i.test(s=(g=a=>a[Math.random()*a.length|0])(N)+"'s "+[(o=g([,...a]))&&o+' ']+g(n))?s:F(n)
```
[Try it online!](https://tio.run/##XY8xT8MwEIX3/opThWobB7eIDXDYuhGGjmmQTu0lMaTnKHbbAfjtIUlhgOl9eqf3nu4NTxh2nWvjDfs99aXtZZagsunask2Xr9Ko7UZL2N4OovTV0plIIcpgZWXRppg/Y6xNh7z3B6mu0TTEVaw/V4WSmdJzEWCuc@ltJfPEGIOFUouF1wJEoSvJSj2F@/Wgfek76cDC6gEcPMLdqFor@JgB7DwH35BpfCVLORgAucjINSIBkbmdb3Ckl3DGZj/SpqbugDxhpLZGdiSK5CfJdB4v7E80NfhLyHeucoyTFWjYnNzghpeiKIas@p1mf@S/DcfYHuO/YE3UTsD4TpcCNfvqvwE "JavaScript (Node.js) – Try It Online")
Or [check the distribution](https://tio.run/##XVBNU8IwFLzzKzKMQxJbAh70IKae5CYcOJY48yyPNrQknSbAOIh/vaZFD3rafR@7b/bt4Agua3Ttx8ZusN3Kli1i4DKZSyOTyRsTfL2KGFnfBeDRzUQLj84zJ1kuQSaQvoIvRANmY/eM34Ko0OS@@JwqzhY8GlJHhlHKrMxZGgshQHE@GtmIEqqinBnOn93jPGC7tQ1zHjyR5HyJiQ44nQV4Ivf4EEgUcXIeENLtpC5MtyxUhKR0gbqiMaELndkKOrZ0J6g2HVsV2OzB9NRjXYDRSFX8ozR46ibGHrF3sFeRbXSuDfQth5k1fdfpkM1TFbT897SxB/PX4eDrg/8nLBDrnhgo8WqgQoDx1zWLmg0ug@X7DjMvSvxw/Ru4cLbxjIvwlxfIClYSmZBg6WyForJ5v5WWKiYl5@03) on 5 million draws
### How?
The helper function \$g\$ takes an array and returns a random element from this array, with a uniform distribution.
```
g = a => a[Math.random() * a.length | 0]
```
By invoking \$g\$ three times, we generate a random string \$s\$ with a valid format, but without taking the initial letters into account. For the adjective, we append an empty entry and make sure not to insert a trailing space if it's chosen.
```
s = g(N) + "'s " +
[(o = g([, ...a])) && o + ' '] +
g(n)
```
We then check if all initial letters are identical with the following regular expression:
```
/^(.)\S+( \1\S+)+$/i
```
It not, we simply try again until \$s\$ is valid.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~161 154 151 147~~ 145 bytes
(*Thanks ArBo, EmbodimentOfIgnorance, Neil who have contributed 2, 3 and 4 bytes to my first golf!*)
```
from random import*
c=choice
def f(N,a,n):
s=c(N);w=s[0].lower();o=N
while o[0]!=w:o=c(n)
print(s+"'s",c([x+" "for x in a if x[0]==w]+[""])+o)
```
[Try it online!](https://tio.run/##dZJNbtswEIX3PMWUgFAyNlQZQbtIoAMkC2fhpWMUjDSyiNKkQI4iFUXP7o5k5ReotCA0/ObN46O639QGf30@NzGcIBpf82JPXYh0JaqyaoOtUNTYQKO2a7P2@kZAKiu11bdDmfbFIXdhwKj0bSi3AobWOoTA9S/lcBMY9FpAF60nlVbya5LrSu3HlQTZhAgjWA8GbAMjt5TlcFjtpTzoVdDniwuwQczequAJR3L2afEHEWsbsaKfierQk5j9QQlKbtE62NoqOAMPaTCuhl2L8WQ87Ai71niLMk@ds6T0GqTHAXx4RgeB0RDt0XrjICEPrSHxkTx94EPvXxp66np6RVvEDpI3v970tRCX88v7PhFsCsARq55s8OnRSy2mIOwUBMd/RLUppozhNXAhcCy/F9PzIvTop3dHhhIED1n9UTLDUYuLscR5/PkrPs9gYJ4BiSKaE0M25Dti9ePdg9Lz1mCp/ZyxuvBLM7x3OX0wwVIXJj8iPRvXo9J55JLtFl2@7IljL4vFN7GlsOf1AKsSNvMOuoT/YSZkPtuimPi/wFotzGJzCS37kV83kGUy44iLq/c63zgPvlZm5XqS0ud/ "Python 3 – Try It Online") (with 500k executions)
* Takes three lists as inputs.
* Assumes at least one noun for each name.
---
Same score, more golf-y:
# [Python 3](https://docs.python.org/3/), 145 bytes
```
from random import*
c=choice
def f(N,a,n):
s=c(N);y=lambda p,e=[]:c([x+" "for x in p if x[0]==s[0].lower()]+e);print(s+"'s",y(a,[""])+y(n)[:-1])
```
[Try it online!](https://tio.run/##dZLNjtsgFIX3PMUVklWYuK6jUbvIyA/QLjKLLD1WxdjXMSoBC64njqo@e4p/5lcaIxkBH@ceDvQX6py9vV5b707glW1ip0@983TD6qLunK6RNdhCK/apSq3cMQhFLfby7lIYdXpsFPQpFmW1q0U5bjjw1nkYQVvoQbcwlnlVFCH@M@PO6IWsNijveq8tibDhXwJPL0KlJeeV3FyEleXu67aS18UFaMdmb7WzhCMZ/bj6A4@N9ljT70CNG4jN/qAAwfeoDex17YyC@3BWpoFDh/6kLBwI@05ZjTwLvdEkZArc4hmse0IDLqLO66O2ykDAWLSBoA1aese7wT5vGKgf6AXtEHsIVv151ZeMLYflv4ZAsM0BR6wH0s6GB8slm/LSU14x/iOKbT5lDC@BM4Zj8T2fvmehBzu1AykK4CwkzXvJBEfJFmMh5vH3H/tYIwJzDQjkUZ0ipF12oKh@/Hkv5Lx01tR9zFgs/LoZ3rqcBpGIUguTHZGelBlQyMzHKd2vuvFNTFz0slp8FVsnythXsClgO6@gCfgJMyHz2VbFEN8FNmJlVptraMmP7LaFJOFJjDi/eavzLeYRrzWyPJ2k5PU/ "Python 3 – Try It Online") (with 500k executions)
It's just 140 if trailing whitespaces are allowed (by removing square face `[:-1]`)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 39 bytes
```
℅‛'s+:→a\ ?'h←a⇩h=;``J℅\ ?'h←a⇩h=;℅++++
```
Finally figured out what I'm doing.
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%84%85%E2%80%9B%27s%2B%3A%E2%86%92a%5C%20%3F%27h%E2%86%90a%E2%87%A9h%3D%3B%60%60J%E2%84%85%5C%20%3F%27h%E2%86%90a%E2%87%A9h%3D%3B%E2%84%85%2B%2B%2B%2B&inputs=%5B%27Stephanie%27%2C%27Bob%27%2C%27Jim%27%5D%0A%5B%27jolly%27%2C%27buoyant%27%2C%27starry%27%5D%0A%5B%27jam%27%2C%27stone%27%2C%27boat%27%5D&header=&footer=)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
1ịZḢXɓŒuḢ=ɗƇ€Ż€2¦X€ḟ0ż“'s“”K
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4e7uqIc7FkWcnHx0UimQYXty@rH2R01rju4GEkaHlkUAqYc75hsc3fOoYY56MZB41DDX@////9FKXqmJeUo6Sn6pmTkgKjM5PycRyPAvLk/MSQEygjNSi3LBSoJLUgsyEvMyU5VidaKV8lLLgWJ5@WWpIH35YLX5RZnpmXmJIIHi1OT8PJBYcWZOal4JWEtWamoBWE9pHrLW0pKC0hIULRkQhcV5idlAywA "Jelly – Try It Online")
Wrote this before I saw @JonathanAllan’s shorter answer, but thought it worth posting since it uses a different approach. Saved 3 bytes by @EriktheOutgolfer’s suggestion on that answer.
A full program taking a list of lists of strings and implicitly printing a randomly selected alliteration. Assumes at least one noun per name.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 176 bytes
```
(a,b,c)=>(a=a[z.Next(a.Count)])+"'s "+b.Where(x=>(x[0]&95)==a[0]).Append("").OrderBy(x=>z.Next()).Last()+" "+c.OrderBy(x=>z.Next()).Last(x=>(x[0]&95)==a[0]);var z=new Random();
```
[Try it online!](https://tio.run/##fZBNSwMxEIb/ypCDJuwaevEg7RZUEJTSghV6KD1Ms9NuNJ0sSbZff76mUHsQ8TQMPO8Hr4l3JtrTS8dmUB8YN9aUryMb0yCmYHk9/PVdmOGqOkksl6VR1VBihfOjHtM@SdTPvuOkFqoQtxFEsdSzhgLJfeb2897i5uFeVZnvLZR@bFviWgqh9CTUFJ4OZ@zipJQeYcy3ENnG/EP8Yd3fYoBjxbSDd@Tab6Tqn2bBJhpZJrmSYkzWwdga7xAmcYeuhmkuukGGaaK2QbYEb/hFQk9bZ3Oa/vDnKaQqxdmX/ZYc@Kzzwa4to4NIxnMN0TridNVlPE/yw3ep7dKVbIhaiJxj4DMnJh@uMpUbfwM "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 179 bytes
```
func[a b c][random a random c
foreach k c[if k/1 = h: a/1/1 + 32[g: rejoin[sp k]]]collect/into[foreach
d b[if d/1 = h[keep rejoin[sp d]]]]e: copy[""]random e rejoin[a/1"'s"e/1 g]]
```
[Try it online!](https://tio.run/##VY/BbsMgEETP9VesuPTQg5v0Zqm/kErpccWBwDqmtncR4Fr9ehcSV0pPjIZ5MxDJbWdyqJu@2/qFLRq4gNUYDTuZwcAubNNLJGMHGMGi72FsD/AOQwemPRT5Am9HvHYQ6Us8Ywowaq2tTBPZ3HrOgntB4@BSC9y9AEei8IC5gmnqwEr4QaX0vk9/kTKnnpOiQl@13u7XbSJywLK22c/UTCIBjq@AIZZl6AHVifykQJ18eZIp4iOtZnJFfA4UZ8NVZQqDYU9KQ/OEimktLss3VVJuaYn@6tlUI5EVrl7yE3FW@sbIwo/QksOS/4WH8t16shnLkN5@AQ "Red – Try It Online")
## Explanation:
```
Red[]
f: func[a b c][ ; a function with 3 arguments
random a ; shuffle the list of names in place
random c ; shuffle the list of nouns in place
foreach k c [ ; for each item in the shuffled list of nouns
if k/1 = h: a/1/1 + 32 [ ; check if it begins with the same lowercase letter
; as the first name in the shuffled list of names
g: rejoin [" " k] ; if yes, then insert a " " in front of it save it as g
] ; thus I always get the last match
]
collect/into [ ; collect in a new list e
foreach d b [ ; all items form the adjectives list
if d/1 = h [ ; that start with the same lowercase letter as the 1st noun
keep rejoin [" " d] ; insert a " " in form of the adjective
]
]
] e: copy[""] ; the list initially has a single item - the empty string
random e ; shuffle the extracted adjectives list
rejoin [a/1 "'s" e/1 g] ; return the formatted string
]
```
[Answer]
# [Scala](https://scala-lang.org), 234 226 234 206 bytes
*-28 due to the fact I thought it had to accept StdIn, it's a function now*
```
def f(a:List[String],b:List[String],c:List[String])=scala.util.Random.shuffle(for(d<-a;e<-("" +: b);g<-c;if(d.head.toLower==g.head&&(e.isEmpty||e.head==g.head))) yield s"$d's $e $g".replace(" ", " ")).head
```
[Try it online!](https://scastie.scala-lang.org/pxVvwJr1Tvu3JfiFsTqxBw)
Ungolfed:
```
def f(names: List[String], adjectives: List[String], nouns: List[String]) = {
val allPossible = for {
name <- names
adjective <- ("" +: adjectives) // Add the choice of no adjective
noun <- nouns
if (name.head.toLower == noun.head && (adjective.isEmpty || adjective.head == noun.head)) // Filter out so only matching entries remain
} yield
s"$name's $adjective $noun"
.replace(" ", " ") // Get rid of artifact created by the empty adjective selection
scala.util.Random.shuffle(allPossible.toList).head // Get a random element
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 94 bytes
```
->a,b,c{"#{n=a.sample}'s #{s=[p,*b.grep(r=/^#{n[0]}/i)].sample;s+" "if s}#{c.grep(r).sample}"}
```
[Try it online!](https://tio.run/##bc6xboNADMbxPU9hwdCmpaR7RR@gQzowUiIZYsDtxXc6H0UV4tnJVUoyZbP0/@mT/dj8rV3xtb68Y9Zk7ZyksxSYK56coeVBIZ21qFz21OS9J/foi90hkuq1Xna8rS/wTZ8TSLgDXdK5vcjtdSVZVjcGha7qKWiuznDI4P5drx8WBfbEBvbcWoPwqROaI5QD@VNMZSA3oDBthCYQ@0sGbOzWc8@CBpRaK0dQNiRh803kohrlSscQn7mh4T@r4A@dAQ "Ruby – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~167~~ 163 bytes
```
procedure f(a,b,c)
!a:=:?a&\x;!c:=:?c&\x;d:=[""]
e:=!b&e[1]==(t:=char(32+ord(a[1,1])))&put(d," "||e)&\x
!d:=:?d&\x;return(!a||"'s"||!d||" "||(k:=!c&t==k[1]&k))
end
```
[Try it online!](https://tio.run/##dZCxTsMwEIZn8hSOh2CLDKRsQRZvUAbGkOFqX4mV9Bw5Tgso717stANU4qbPp9@fTr/Vjs6DpZ55IOMO59E7jWb2yPYCyl2pZZZDreoXKN4/n3OdUCc0tWo4bzOsVb4rsKlapUSole7Ai6fNg/NGQFOVVSulLMY5CFNyxpcFZfye5SaZTDJ5DLMnkcOy8PspJnITKUVFH@W6CEr10V/0UmZI5teNB7AkZMbiXO6333h94xH9F6NaVSw4tnlkxrGTtwHFXjR8i3bgJeNbq90AiV6nEwwm0VuH/gC0YsCxA7LI25Jld3fsdhpOeEpJckdcje4icd5@WIJ1NWFsed1OdkAKUfaPy830VzaH2NyNo0McVyDo42HXUn4A "Icon – Try It Online")
Uses the same algorithm as my `Red` answer.
[Answer]
# Excel, 201 bytes
```
=LET(a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s",f,LEFT(a),b,FILTER(B:B,LEFT(B:B)=f,""),y,INT(RAND()*(ROWS(b)+1)),c,FILTER(C:C,LEFT(C:C)=f),a&IF(y," "&INDEX(b,y),"")&" "&INDEX(c,INT(RAND()*ROWS(c))+1))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnCevb89h3jaMoJyM?e=WbtJI9)
## Explanation
```
=LET(
a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s", 'a = rand name from first list & "'s"
f,LEFT(a), 'f = first letter of a
b,FILTER(B:B,LEFT(B:B)=f,""), 'b = all items in second list starting with f
y,INT(RAND()*(ROWS(b)+1)), 'y = rand from {0 .. size b}
c,FILTER(C:C,LEFT(C:C)=f), 'c = all items in third list starting with f
a 'result = a
&IF(y," "&INDEX(b,y),"") ' & if y = 0 then "" else " " & b(y)
&" "&INDEX(c,INT(RAND()*ROWS(c))+1)) ' & " " & random item from c
```
] |
[Question]
[
Given two different positions on a chess board and the type of piece, output the minimum number of moves it will take for that piece to go from one position to another.
### Rules
The given piece can be King,Queen,Rook,Knight and Bishop. (This input can be taken as any 5 unique characters)
The 2 positions can be taken in any convenient format,
```
Example:
a8 b8 c8 d8 ... h8
a7 b7 c7 d7 ... h7
...
...
a1 b1 c1 d1 ... h1
```
In case the piece cannot reach there, output anything other than a positive integer.
### Examples
```
i/p ---- o/p
King
a1,a4 3
a1,h6 7
b3,h5 6
Queen
a1,a4 1
a1,h6 2
b3,f7 1
Rook
a1,a4 1
a1,h6 2
h2,c7 2
Knight
a1,a4 3
a1,h6 4
b2,d3 1
b2,c3 2
b3,c3 3
a1,b2 4
Bishop
a1,a4 -1
a1,h6 2
b2,d3 -1
e1,h4 1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~183~~ ~~180~~ 179 bytes
```
with(Math)(a,b,c,d,t,x=abs(a-c),y=abs(b-d),v=x<y?y:x,q=0|.9+max(/[18][18]/.test(a+b+9+c+d)-v?x/2:3,y/2,x*y?x*y-4?(x+y)/3:3:2))=>t?t==2&x+y?0:t&1>x*y|t/2&x==y?1:t<4?2:v:q+(q+x+y&1)
```
[Try it online!](https://tio.run/##hVDdbtsgFL7vU/hmKczHcQG3UFbqu97tCaZJBdu1W6XxElPPlvruGcab0i4hEQeE@Ph@znnRve6K7fMvm6zbsto9qKrXK/S4@/1sG/Rd2wYjDQYKKMHCoLTpkE4KDKO/mqTE0KvhbsxHOcBGXb0vb@NXPaD0BxE/p50ubdVZpGMT38ZFXOKkz4eUSgZjSmH4OuZuJ1mOhnjEKZNMUozVvc2tUnThHvMraRfk3v16t6l7UWrMibR3WU5lLzcx2sTu14Lg3SP@dvGk9nmdzIMzvrwEMx3FdJTTYb8IfFG0665dVctVW6MnRGBaGWT4GCLg5ghCgTnk2iMBORaUY0flboB7JCBHgnKHiIBJkHskICeCcuJIOjr1E0BYAGEBZPKZeCIcjgbD0WC4Q@Tac2a1A1JEfLmLyxGlaWSIpjLqmvZtVUamiuh/FO7/i4@UmjQnKbP@7PWXoqkhpyizPv9IaWhNzrjwOdXehRtxxoX72lMaXp@kzPqz17@JCc3PTEz42lNq0fAzvbhinyZGis/tQ7St7Nt23UXZ7g8 "JavaScript (Node.js) – Try It Online")
So long for edge case, thank Arnauld for checking. [Knight test](https://tio.run/##vZldc6M2FIbvz6/QTQ0qGBskbC8J9nQ6s3fd/oA004jv7CTxJjBbe3b721Ocj7U5SOCdqXQhRwJCHl5Jz5zgz@KrqNOn2y/N9GGb5c8f4/yruLNvnv@5bSr7D9FU1BZu4qZu5jbuLhZJbYtpSt39SzeZZtR9jOffvQ/OvdjZsyt/dX1oM6/J68YWTuJ8cFIno5Pdr/s49jcs2s0Cd9@29sCmbVO@sXfOns5YxKKA0njdbJo4Dibtwc08aib@ur3qezNrj8TxfuNHzSXfBNHucr/ZR7vo0bEfnfbaiU@fb@hF/fhJ3OckJjWJ18QSSZrlRVlZVzWZkOU1cYjtHz5qsl4TRukF/P7np9iyLqDYPtn1vP3N@QVpf16SBT90HIeSb0BIe5kT26@3b6@j7U0sMp2uifCJ55FqFbVjh1x5nvfb05PY2wtOr7178cW2/3ZJ7dMDT@2TOD7cfUOsqUUi8tH2ndr/ZeVYlvvSnR269Gp@7baj@fHE/McJSr3P29sH2yIWpY7110PL/i@k24d6e5d7d9vSPjxRDDctWJdvShgJ3hon4cun/zY6tKAd8c7549Wv509H4Y/e64ijUfj2@d4WkGAghpBee0ckHyEFCAkDcoTUB@wgQYqBAoTkIySOkBhC6gN2kTBgNyEOWT@hLlKAkBhCChASBuQIqQ/YTSiXJXSKxBBSgJAYQuI9wKGEWC@hQp7QEYkjJIaQ5ABdQAwwlFCJgThCYgiJIyQVwPsROYA6oQoDhQiJnyAdn/CIpAZ4B5QDvB9ZoIREIJmyU@/0vRTo9BIkgXTK/JNta9RLkGIg7B3DXoIs6G177B2jXoJcvYaO3jHoJSiG1tDRO8a8BGU/IY7WiFEvQSVL6PRPDnkp@P@9BIJJFjUf8I5mL0HCJNu@7xVjXoKU9aase0vDXoKMSRZ11ytGvQQ5k9RD2CsGvQQFk9ZD2CvGvAQlU9RD2Cu@5Ak1eAkqpqyHsFeMeAkEV5awaq9o9BIkXFHkD3tFm5cgVSck94pmL0E2lJDcK1q9BPlwQoFpL0HBB/4NOj6BMS9ByRX1EBvxiiYvQcWV9RAb8YoWL4EIFYuaK72h1UuQhKNiNOolSMMRMRr2EmThiBgNewny8Kxtb8xLUIRnbntDXoIyHNn2hr0EVSith/hIQaXNSyAW0ik7vrEx7CVIFoop4yMFlSYvQTqU0HBBpcVLkA0nxEx7CfKxhAx7CYrxhIx6CcqFctt3XwYY8hJU/YRCxRsuI14CsVROWSh9r6zZS5AsR8So20vovTiky1ExGvUSZMsztr1BL0G@PGvbG/MSFMszt70hL0G5PHvbm/ASh0qWUDjyhZtGL4FYKYDevkfX4CU@5CVIVtIpC5UAmr0E6XBC3LSXIPuZhAx4CfKfS0i7l6AYS8iwl6AcT8iol6DCQAtJQrq8xPteghugz/8B)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~117~~ ~~107~~ ~~105~~ ~~103~~ ~~98~~ ~~97~~ ~~95~~ ~~92~~ ~~89~~ 87 bytes
```
{(⍎⍺⊃'⌈/' '≢∘∪~∘0' '+/×' '{⍺∊⍵:0⋄1+⍺∇i/⍨∨⌿2=|×/↑⍵∘.-i←,⍳8 8}/,¨⊂¨↓⍵' '≢∘∪×2=.|⊢')⊣|-⌿⍵}
```
[Try it online!](https://tio.run/##TY7NTsJAFIX3PEV3A4HSdgZoQ8KGLQkJDS8wLZQ2NsHAylBcqMFSGaIxBrbihrhVNmxM5E3ui9TbH8XNzDd3zj3n8EtfHlxxfzySbZ9Pp54dw/rFG8PiUY0dPGdFEGsQR4huCaxChUgEljsItxC@X@Ol4qCsnDZ4zRJZGIE4NFV4uNPK6fveU0DsIdzD6ou2gtNGgcUTanC3KnuYUAHxYUjGXKl87yG6wWPxjP//g04b2qoGEO1ICaK3QEYrVMzjuJ80TMyWrxPEIun0zG6boCP2xfiSIxkB4ZY9GDojV6OsVm/oRvJPJQriU0uzjk0yviBYmTjc80lSWxwm8wLpcI3XSF9iKboNRB3RYm4dsVEgvVygpZgKKKLFHD2bmmeBeRaYLrX1DLvniG4uqCFadMCyNUSb5VqL2fRvzaKZtp07qCn@RrRzh2Q61Nysg/wD "APL (Dyalog Classic) – Try It Online")
left arg is piece type: 0=king, 1=queen, 2=rook, 3=knight, 4=bishop; right arg is a 2x2 matrix of coords, each row representing a position; returns 0 for unreachable
`|-⌿⍵` computes the pair [abs(∆x),abs(∆y)]
`(⍎⍺⊃`...`)⊣` chooses an expression from the "..." list; if it's a function, it's applied to `|-⌿⍵`; if it's a value (this happens only for a knight), `⊣` makes sure to return it instead of `|-⌿⍵`
* king: max (`⌈/`) of the abs ∆-s
* queen: remove zeroes (`~∘0`) and count (`≢`) unique (`∪`)
* rook: sum (`+/`) of signa (monadic `×`; 0 for 0, 1 for positive)
* knight: `{⍺∊⍵:0⋄1+⍺∇i/⍨∨⌿2=|×/↑⍵∘.-i←,⍳8 8}/,¨⊂¨↓⍵` - start with the initial position and recursively compute generations of knight moves until the final position is in the set; return recursion depth
* bishop: are the parities of the two ∆-s equal? (`2=.|⊢`, equivalent to `=/2|⊢`) multiply the boolean result (0 or 1) by the count-unique (`≢∘∪`)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 229 bytes
```
(p,a,b,c,d)->{c^=a/4*7;a^=a/4*7;d^=b/4*7;b^=b/4*7;int x=c<a?a-c:c-a,y=d<b?b-d:d-b,z=(x^=y^(y=y<x?y:x))-y;return p<1?x:p<2?z*y<1?1:2:p<3?2-z%2:p<4?x+y<2?3:(a<c?a+b:c+d)+x<2|x==2&z<1?4:z+2*Math.ceil((y-z)/(y>z?3:4.)):z<1?1:~z*2&2;}
```
[Try it online!](https://tio.run/##dZRNb5tAEIbv@RUjJCLWLNhgkjgYwqHHKuqhl0SWLS2wjvEHUMAukNK/7i4LGCcNkq0dmN1n3n3H4y05EWXr787enqQpPJMghPcbgCDMaLImHoVvG5qmz9GJpjwB4EdHd08hPB5cmvxY85TE9kMcUI/i@iisk@jw0oevTZhFL13wiuYMVrFvzGiBB2lGMracosCHA1Mh/cySIHxbLIEkbylqa1@J8frQhrMUY4Jd7GEfKU/v3somY2P0MCdd4K9slwduF9Q6ctuziEMUz/QUggvbt1zHVXzTV1xc2lK@souVVNiFlTuFmSOkFPOEZsckhNjSnNyMLd0pRwWLNVNnT1NHV0qxjgwnlwuWnZoSsTyHyK7pyT6Sc0v/k9u2fluyQ4ZZyvromWQb1aPBXpIKpURjqXgq2TlDRcgsOfpvOdJv9Xl1nnMTTiSBjKZZffGQ/q4dXSyZUY1FAO0yHsOOOdg@vcME958pVPj/xAOGu08JDYPOE0ad6Mm/jpSGl43aEFobQmsd@g7D/Ud0EkW7yz59iKwPkRu5DfwT2Q3STRRfdhpDbGOIbeBW@JThPyWM7sT0UrRq@rWOEqnrmdl0Dl2a1fzMm9lh/RTqlmHuLq6NwLsweNtkuJEuqGm8DzJJwAJa1KDFZLmcd6QizehBjY6ZGjNmtpYE8T7l8weiJ/ps6vhqgqhO1mIo4G5iHx9kDtOWmMtb6EtZ619Pu9cGf90PnvrxP6AV1G6@grXBFQehRnV1M6Q8/M4vnjauiSHTi3o76@ENmF2TOVssuDfYKstXrn5BrC1QlCcgGqgqbGYmMyAYz@RH1rNAnMka6pzsKmybCtu2wva6wpc1QExrKNg2O@SAoAhgQo1Cg6ZNuQiuAMO2jrbiDF2kVAMX2ofSlYXVTXX@Bw "Java (JDK) – Try It Online")
## Explanations
* The board is a 0-based board.
* The returned-value is an integer, represented as a double. There will never be any decimal part.
**Code:**
```
(p,a,b,c,d)->{ // double-returning lambda.
// p is the piece-type (0: king, 1: queen, 2: rook, 3: knight, 4: bishop)
// a is the origin-X
// b is the origin-Y
// c is the destination-X
// d is the destination-Y
c^=a/4*7;a^=a/4*7; // Mirror board if origin is in the top part of the board
d^=b/4*7;b^=b/4*7; // Mirror board if origin is in the left part of the board
int x=c<a?a-c:c-a, // x is the X-distance between a and c
y=d<b?b-d:d-b, // y is the Y-distance between b and d
z=(x^=y^(y=y<x?y:x))-y; // z is the delta between x and y
// also, swap x and y if necessary so that x is the greater value.
// At this point,
// x cannot be 0 (because the two positions are different)
// z<1 means the origin and destination are on the same diagonal
// y<1 means the origin and destination are on the same horizontal/vertical line
return
p<1?x: // For a king, just take the max distance.
p<2?z*y<1?1:2: // For a queen, just move once if in direct line, or twice.
p<3?2-z%2: // For a rook, just move once if on the same horizontal or vertical line, or twice
p<4? // For a knight,
x+y<2?3: // Hardcode 3 if moving to the next horizontal/vertical square
(a<c?a+b:c+d)+x<2|x==2&z<1?4: // Hardcode 4 if moving 2 cases in diagonal or one case in diagonal in a corner.
z+2*Math.ceil((y-z)/(y>z?3:4.)): // Compute the number of moves necessary for the usual cases
z<1?1: // For a bishop, hardcode 1 if they are on the same diagonal
~z*2&2; // Return 2 if they have the same parity else 0.
}
```
## Credits
* -2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), as well as for making me realize that I had an issue with all my corner-cases.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 67 bytes
```
®ra
g[_rw}_â è}@=ã ü;@pUÌïVõ á ÈíaY})Ìde[TT]}a Ä}_è}_ra v *Zâ l}]gV
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rnJhCmdbX3J3fV/iIOh9QD3jIPw7QHBVzO9W9SDhIMjtYVl9KcxkZVtUVF19YSDEfV/ofV9yYSB2ICpa4iBsfV1nVg==&input=W1sxLDhdLFsxLDhdXQoyCi1R)
That was quite an experience. I took a lot of inspiration from the excellent [APL Answer](https://codegolf.stackexchange.com/a/176577/71434). I suspect there is a lot of golfing still possible especially in the Knight code.
The positions are the first input, in the form `[[x1,x2],[y1,y2]]`. It should work fine on `[[y1,y2],[x1,x2]]` as well. Piece selection is the second input, with 0=king, 1=queen, 2=knight, 3=rook, 4=bishop. Note that Knight and Rook are swapped compared to the APL answer.
Explanation:
```
®ra :Turn absolute positions into relative movement and store in U
® : For each of X and Y
ra : Get the absolute difference between the start position and the end position
g[...]gV :Apply the appropriate function
[...] : A list of functions
gV : Get the one indicated by the second input
g : Apply it to U
_rw} :King function
rw : Get the maximum of X and Y
_â è} :Queen function
â : Get unique elements
è : Count non-zero elements
@=ã ü;@pUÌï2õ á ÈíaY})Ìde[TT]}a Ä} :Knight function
=ã ü; : Wrap U twice (U -> [[U]])
@ }a Ä : Repeat until True; return number of tries:
UÌ : Get the previous positions
ï : Cartesian product with:
2õ : The range [1,2]
á : All permutations, i.e. [[1,2],[2,1]]
ÈíaY}) : Apply each move to each position
p : Store the new positions
Ìde[TT] : True if any are at the destination
_è} :Rook function
è : Count non-zero elements
_ra v *Zâ l} :Bishop function
ra : Absolute difference between X and Y
v : Is divisible by 2? (returns 1 or 0)
* : Times:
Zâ : Get the unique elements
l : Count them
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 108 bytes
```
F…β⁸F⁸⊞υ⁺ι⊕κ≔⟦⟦η⟧⟧δW¬№§δ±¹ζ⊞δΦυΦ§δ±¹⁼⁵ΣEμX⁻℅ξ℅§κπ²≔Eη↔⁻℅ι℅§ζκε≡θKI⌈εQI∨∨¬⌊ε⁼⊟ε⊟ε²RI∨¬⌊ε²BI∧¬﹪Σε²∨⁼⊟ε⊟ε²NI⊖Lδ
```
[Try it online!](https://tio.run/##dZLBT8IwFMbv@yteOL0m9YCJhuhpTk2IMlCOhEPZKm3o2rF2ghj/9tltDEWw6aF5@d7vfV/bRLAiMUxV1ZspAKOPRPFImBwXFAaEQFMdEJiUVmBJYaJKi5LCUCcFz7h2PMUVIeQ2CK2VS42zmZjPKaS@shFSccDYOIxMqR2GbqhTvsWUQsyXzHHsE0JhR/Z8X3@UyvGinrQ//dPzsC6ZsnhFYVpmOGI5Zt6c2fiOkdTe47hIpWYKt17cnTvWikJeQy5Juw7ma46gEC7sH4o8Q9lRWDXtFLhH2I10iQBcE/gMEmY59J56NzAppE8eMes8fSsz75Y3I1vJy7FkXNS7vjE/vxMf0k78u3BS58wbSJugQ72eoE44v@V3x/JQp63epKUyOG1amo46OZ53sL/CDhkfI@/5zx955nrp/Au38q@qigPWD8R1dfGuvgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F…β⁸F⁸⊞υ⁺ι⊕κ
```
List all the 64 squares of the board into the predefined empty list variable.
```
≔⟦⟦η⟧⟧δ
```
Make a list of lists whose first entry is a list containing the start position.
```
W¬№§δ±¹ζ
```
Repeat until the last entry of the list contains the end position.
```
⊞δΦυΦ§δ±¹⁼⁵ΣEμX⁻℅ξ℅§κπ²
```
Filter all the board positions that are a knight's move away from any entry in the last entry of the list of lists and push that list to the list of lists. This includes positions previously visited but we weren't interested in them anyway, so we end up with a breadth first search of the board for the end position.
```
≔Eη↔⁻℅ι℅§ζκε
```
Calculate the absolute coordinate differences between the start and end positions.
```
≡θ
```
Select based on the input piece.
```
KI⌈ε
```
If it's a king then print the maximum absolute coordinate difference.
```
QI∨∨¬⌊ε⁼⊟ε⊟ε²
```
If it's a queen then print 2 unless the two differences are equal or one is zero.
```
RI∨¬⌊ε²
```
If it's a rook then print 2 unless one of the differences is zero.
```
BI∧¬﹪Σε²∨⁼⊟ε⊟ε²
```
If it's a bishop then print 0 if the squares are of opposite parity otherwise print 2 unless the two differences are equal.
```
NI⊖Lδ
```
If it's a knight then print the number of loops taken to find the end position.
] |
[Question]
[
[Hexagonal chess](https://en.wikipedia.org/wiki/Hexagonal_chess) describes a family of chess variants played on a board where the cells are hexagons instead of the traditional squares. There are many such variants; in this challenge we'll be focusing on Gliński's variant, which is the most common.
The board is composed of three colors (so that the same color doesn't share an edge), with the edges of the hexagons facing the players. The board has 11 files, marked by letters `a` through `l` (letter `j` is not used), and 11 ranks (which bend 60° at file `f`). Ranks `1` through `6` each contain 11 cells, rank `7` has 9 cells, rank `8` has 7, and so on. Rank `11` contains exactly one cell: **f11**. (If it helps, think of each rank as making a very wide "V" shape.)
Here is an example picture of the board, with the knight on the center cell. The cells marked with a dot are the legal moves of this particular knight. The knight moves in a similar fashion to "normal" chess, two-down-and-one-over. In hexagonal chess terms, it's an orthogonal move (across an edge), then a diagonal move in the same direction (the closest move to the same color). For example with the knight below, an orthogonal move "up" to the light brown is then accompanied by a diagonal move "up and right" or "up and left" to the nearest light brown.
[](https://i.stack.imgur.com/E7SWp.png)
*From the public domain via <https://commons.wikimedia.org/wiki/File:Glinski_Chess_Knight.svg>*
This knight is positioned at **f6** and the legal moves are thus
```
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5
```
### Input
A single input giving the starting cell of our knight. This can be as a single string `"b6"`, as two strings, `"b", "6"`, etc., [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). The input letters can be uppercase or lowercase -- your choice.
### Output
A list of the valid moves that a knight on that location can make. This can be as an array of strings, a single string with an unambiguous and consistent delimiter, separate strings by newlines, etc., whatever is most convenient. The output does not necessarily need to be in sorted order, and can be in either uppercase or lowercase -- your choice.
### Rules
* Assume no other pieces are on the board or interfere with the moves. We're focusing on just the knight.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
```
b6
a3, c4, d5, d9, e7, e8
f6
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5
f11
d8, e8, g8, h8
i1
f2, f3, g4, h4, l2, k3
```
[Answer]
## JavaScript (ES6), 184 bytes
Takes the file `F` as a character and the rank `R` as an integer in currying syntax `(F)(R)`. Returns an array of strings.
```
F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)
```
### How?
**Step #1: convert file/rank to Cartesian coordinates**
We convert the hexagonal chess coordinates to Cartesian coordinates ***(x, y)*** with ***x*** in **[0 .. 10]** and ***y*** in **[0 .. 20]**:
```
00 01 02 03 04 05 06 07 08 09 10
+----------------------------------
00 | f11 F = file (letter)
01 | e10 g10 R = rank in [1 .. 11]
02 | d09 f10 h09
03 | c08 e09 g09 i08 F | a b c d e f g h i k l
04 | b07 d08 f09 h08 k07 --+-----------------------
05 | a06 c07 e08 g08 i07 l06 x | 0 1 2 3 4 5 6 7 8 9 10
06 | b06 d07 f08 h07 k06
07 | a05 c06 e07 g07 i06 l05 y = 22 - |x - 5| - 2R
08 | b05 d06 f07 h06 k05
09 | a04 c05 e06 g06 i05 l04
10 | b04 d05 f06 h05 k04
11 | a03 c04 e05 g05 i04 l03
12 | b03 d04 f05 h04 k03
13 | a02 c03 e04 g04 i03 l02
14 | b02 d03 f04 h03 k02
15 | a01 c02 e03 g03 i02 l01
16 | b01 d02 f03 h02 k01
17 | c01 e02 g02 i01
18 | d01 f02 h01
19 | e01 g01
20 | f01
```
**Step #2: apply the move vectors**
Below is the list of the move vectors in the Cartesian system:
```
(-2, +4), (-1, -5), (+3, +1),
(-3, +1), (+1, -5), (+2, +4),
(-3, -1), (+2, -4), (+1, +5),
(-2, -4), (+3, -1), (-1, +5)
```
We apply each of them to the source coordinates ***(x, y)*** and get a list of target coordinates ***(X, Y)***.
**Step #3: test the target coordinates**
We now need to check which target coordinates are actually located inside the board. This is done by testing ***X + Y*** and ***X - Y***:
[](https://i.stack.imgur.com/YkrdQ.png)
The coordinates are valid if all the following comparisons are true:
* ***X + Y > 3***
* ***X + Y < 27***
* ***X - Y < 7***
* ***X - Y > -17***
We should also verify that ***X*** is in **[0 .. 10]**. This is not done explicitly because `s[X]` is *undefined* if it's not, which eventually results in a falsy value that gets filtered out.
**Step #4: convert back to hexagonal chess coordinates**
Finally the valid target coordinates are converted back to hexagonal chess coordinates, using the inverse of the formulas described at step #1.
### Test cases
```
let f =
F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)
console.log(JSON.stringify(f('b')(6)))
console.log(JSON.stringify(f('f')(6)))
console.log(JSON.stringify(f('f')(11)))
console.log(JSON.stringify(f('i')(1)))
```
[Answer]
## Batch. 403 bytes
```
@echo off
set j=a b c d e f g h i k l
set f=0
for %%f in (%j%)do set/af+=1&if %%f==%1 goto l
:l
set j=j%j: =%
set/a"r=6-f,r*=r>>31,r+=%2
for %%s in ("-3 -2" "-3 -1" "-2 1" "2 -1" "3 1" "3 2")do call:c %%~s
exit/b
:c
call:l %2 %1
:l
set/ag=f+%1,s=r+%2,t=g-s
if %g% geq 1 if %g% leq 11 if %s% geq 1 if %s% leq 11 if %t% geq -5 if %t% leq 5 set/a"t=6-g,s-=t*=t>>31"&call echo %%j:~%g%,1%%%%s%%
```
Adjusts the coordinate system, although in a different way to @Arnauld's answer. The `c` subroutine takes advantage of the symmetry by trying the mirror reflection of each move. (I also tried rotating but that took too many bytes.)
[Answer]
## JavaScript (ES6), 184 bytes
```
(s,t,j=' abcdefghikl',f=j.search(s),r=f<6?t:t+f-6)=>[...'120405..162645'].map((c,i)=>[(i>>1)-3+f,c-3+r]).filter(([f,r])=>f>0&f<12&r>0&r<12&f-r<6&r-f<6).map(([f,r])=>j[f]+(f<6?r:r+6-f))
```
I thought I'd port my Batch solution to ES6 to see how it compared... I didn't expect it to be *that* close...
[Answer]
# CJam, 77
```
1Z2W2Z]_Wf*+2/_Wf%+[r('a-_9>-_6-We>@~+]f.+{_~m5++B,-!},{~1$6-We>-\_8>+'a+\S}/
```
[Try it online](http://cjam.aditsu.net/#code=1Z2W2Z%5D_Wf*%2B2%2F_Wf%25%2B%5Br('a-_9%3E-_6-We%3E%40~%2B%5Df.%2B%7B_~m5%2B%2BB%2C-!%7D%2C%7B~1%246-We%3E-%5C_8%3E%2B'a%2B%5CS%7D%2F&input=i1)
**Overview:**
I'm using a coordinate system that looks like a..f and 1..6 on the left side, extended without bending, with letters replaced with numbers, and changed to be 0-based (b3→[1 2], g1→[6 1], k3→[9 6]). The relative moves in this system are [1 3], [2 -1], [2 3] and their reflections (negative and swapped, e.g. [1 3] → [-1 -3], [3 1], [-3 -1]). A resulting [x y] position is valid iff [x y z] ⊂ [0 1 .. 10] where z=x-y+5.
[Answer]
# Dyalog APL, 72 bytes
```
(6=|×/t,-/t←↑j[a⍳⊂⍞]-j←⊃,/i,¨¨↓∘i¨i-6)/a←⊃,/(11⍴⎕a~'J'),∘⍕¨¨⍳¨5+i⌊⌽i←⍳11
```
[try](http://tryapl.org/?a=%7B%20%286%3D%7C%D7/t%2C-/t%u2190%u2191j%5Ba%u2373%u2282%u2375%5D-j%u2190%u2283%2C/i%2C%A8%A8%u2193%u2218i%A8i-6%29/a%u2190%u2283%2C/%2811%u2374%u2395a%7E%27J%27%29%2C%u2218%u2355%A8%A8%u2373%A85+i%u230A%u233Di%u2190%u237311%20%7D%A8%27B6%27%20%27F6%27%20%27F11%27%20%27I1%27&run)
builds a list `a` of all valid cells: `'A1' 'A2' ... 'L6'`
`a` is used for both input and output
builds a list `j` of the corresponding coordinates to `a` in a system where
the x axis is along `A6-L1` and y along `F1-F11`
an imaginary third coordinate is the difference of the first two
if the input cell is translated to coords `0 0 0`, a knight can move to those cells whose product of coords is 6 or -6
[Answer]
# Python 3.6, 149
```
H='abcdefghikl'
lambda f,r:[H[i]+str(j)for i,j in[(H.find(f)+p%4*s,int(r)+p//4)for p in[9,6,-1,-5,-11,-10]for s in(1,-1)]if 0<i<11if 0<j<12-abs(6-i)]
```
An anonymous function called with two strings for the file and rank; returns a list of strings.
## Ungolfed:
```
def h(f,r):
H='abcdefghikl'
A = []
for p in[9,6,-1,-5,-11,-10]:
for s in(1,-1):
i = H.find(f) + p%4*s
j = int(r) + p//4
A.append(i, j)
B = []
for i,j in A:
if 0 < i < 11 and 0 < j < 12 - abs(6 - i):
B.append(H[i] + str(j))
return B
```
] |
[Question]
[
# Background
The [Random Domino Automaton](http://arxiv.org/abs/1009.4609) is a toy model for earthquakes, inspired by cellular automata.
In this challenge, your task is to simulate a simplified version of this model, and collect data out of it.
The automaton is defined on an array `A` of `k` bits, representing a fault line on which earthquakes may occur.
The array wraps around at its borders.
The condition `A[i] = 0` means that position `i` is *relaxed*, and `A[i] = 1` means that it's *excited*, or contains stored energy.
At each time step, one position of the array is chosen uniformly at random.
If that position is relaxed, it becomes excited (potential energy is added to the system).
If that position is already excited, it triggers an earthquake, and the chosen position and all excited positions connected to it are relaxed again.
The number of excited positions that become relaxed is the *magnitude* of the earthquake.
# Example
Consider the array
```
100101110111
```
of length 12.
If the random process chooses the second bit from the left, the array is updated to
```
110101110111
^
```
since the chosen bit (marked with `^`) was `0`.
If we next choose the fourth bit from the left, which is an isolated `1`, an eartquake of magnitude 1 is triggered, and the bit is set to `0` again:
```
110001110111
^
```
Next, we might choose the second bit from the right, which triggers an earthquake of magnitude 5:
```
000001110000
^
```
Note that all `1`s in the same "cluster" as the chosen one were part of the quake, and the array wraps around at the border.
# The Task
You shall take as inputs two positive integers `k` and `t`, and your task is to simulate the random domino automaton for `t` time steps, starting from an initial length-`k` array of all `0`s.
Your output shall be a list `L` of `k` integers, where `L[i]` (with 1-based indexing) contains the number of earthquakes of magnitude `i` that occurred during the simulation.
You are allowed to drop trailing zeroes from the output.
For the inputs `k = 15` and `t = 1000`, some representative outputs are
```
[117, 97, 45, 26, 10, 5, 3, 1, 3, 0, 0, 0, 0, 0, 0]
[135, 91, 58, 21, 8, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0]
[142, 63, 51, 31, 17, 4, 2, 1, 1, 0, 0, 0, 0, 0, 0]
[106, 75, 45, 30, 16, 8, 5, 2, 2, 0, 0, 0, 0, 0, 0]
[111, 96, 61, 22, 3, 8, 3, 2, 0, 0, 0, 1, 0, 0, 0]
```
# Rules
Both full programs and functions are allowed.
The shortest byte count wins, and standard loopholes are disallowed.
Note that you are not required to simulate the automaton using any particular implementation, only the output matters.
[Answer]
# CJam, ~~57~~ 55 bytes
```
{:K,K0a*@[{Kmrm<){_{_0#>W%K0e]}2*_)}1?+}*;]1fb2/::-fe=}
```
This is an anonymous function that pops **k** and **t** from the stack (**k** on top of **t**) and leaves the desired array in return.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%20e%23%20Read%20and%20evaluate%20input%20from%20STDIN.%0A%0A%7B%3AK%2CK0a*%40%5B%7BKmrm%3C)%7B_%7B_0%23%3EW%25K0e%5D%7D2*_)%7D1%3F%2B%7D*%3B%5D1fb2%2F%3A%3A-fe%3D%7D%0A%0A~p%20e%23%20Execute%20the%20code%20block%20and%20print%20the%20result.&input=1000%2015).
### How it works
```
:K e# Save the topmost integer (k) in K.
, e# Push I := [0 ... K-1].
K0a* e# Push J := [0 ... 0] (K elements).
@ e# Rotate the other integer (t) on top of the stack.
[{ e# Do t times:
Kmr e# Pseudo-randomly select an integer between 0 and t-1.
m< e# Rotate the array J than many units to the left.
) e# Pop out the last element.
{ e# If it is 1:
_ e# Copy J.
{ e# Do 2 times:
_0# e# Push the first index of 0 in J.
> e# Discard the preceding elements.
W% e# Reverse the array.
K0e] e# Pad it with zeroes to length K.
}2* e#
_) e# Copy J and pop out the last element.
} e#
1? e# Else: Push 1.
+ e# Push the integer on the stack on J.
}* e#
; e# Discard the last value of J.
] e# Collect the intermediate values of J in an array.
1fb e# Replace each array by the sum of its elements (number of ones).
2/ e# Split the array into chunks of length 2.
::- e# Replace each chunk by the difference of its elements.
fe= e# Count the occurrences of each integer in I.
```
[Answer]
# Python 2, 153 bytes
```
from random import*
k,t=input()
E=[0]*k
L=E+[0]
def g(i,x=0):y=E[i];E[i]=y&x^x;return y and-~g(i-1)+g(-~i%k)
exec"L[g(randrange(k),1)]+=1;"*t
print L[1:]
```
Turns out I had almost the same solution as [Fry's](https://codegolf.stackexchange.com/a/52076/21487), but with a bit more bit fiddling.
[Answer]
# Java, ~~278~~ 272 bytes
Java isn't the best Golf language, and I'm not the best golfer, but it was a lot of fun to write so here it is! Let me know about bugs and improvements! (I decided to resubmit as just a function.)
```
void e(int k, int t){int[]d=new int[k],b=d.clone();for(;t-->0;){int m=0,q=(int)(Math.random()*k),i=q,h=1,f=0;d[q]++;if(d[q]>1){for(;;){if(i<0){i=k-1;h=-1;}if(d[i%k]>0){m++;d[i%k]=0;}else{if(f>0)break;h*=-1;i=q;f=1;}i+=h;}b[m-1]++;}}System.out.println(Arrays.toString(b));}
```
And the file with spaces and comments:
```
void e(int k, int t){
int[]d=new int[k],b=d.clone(); //b is the record, d is the map
for(;t-->0;){ //do time steps //q is the spot
int m=0,q=(int)(Math.random()*k),i=q,h=1,f=0;
//m-magnitude,i spot examining, h moving index, f change counter
d[q]++; //add the energy
if(d[q]>1){ //double energy, quake here
for(;;){ //shorthand while true
if(i<0){ //i has wrapped negative, need to start a left hand search from the end now
i=k-1; //Start at the end
h=-1; //Left handed search
}
if(d[i%k]>0){ //is the spot energetic and set off
m++; //add one to the mag counter
d[i%k]=0; //remove energy
} else { //it's a non active spot so we need to flip search direction
if(f>0) break; //we've already flipped once, break
h*=-1; //flip the direction now
i=q; //reset the spot we look at to the epicenter
f=1; //add one to the flip counter
}
i+=h; //add the search increment to the spot we look at
}
b[m-1]++; //update the mag record
}
}
System.out.println(Arrays.toString(b)); //print it out
}
```
[Answer]
# Python 2, ~~174~~ 170
```
from random import*
k,t=input()
D=[0]*k
E=D+[0]
def U(x):b=D[x];D[x]=0;return b and-~U(x-1)+U(-~x%k)
for x in[0]*t:r=randint(0,k-1);e=U(r);E[e-1]+=1;D[r]=e<1
print E[:-1]
```
Thanks @Vioz for finding a shorter way to make `D`, and proving again that `not` is usually golfable. And also for writing the explanation.
I had tried to make a similar program in Pyth, but there seems to be a scope issue in what I was trying to do. This pretty naively implements the dominoes and the function `U` propagates earthquakes. The subtraction direction in `U` doesn't need a mod because it will wrap around naturally. The last element of `E` counts the number of times a zero is turned into a one, so it is not printed at the end.
**Ungolfed + Explanation:**
```
from random import*
k,t=input() # Takes input in form k,t
D = [0]*k # Empty array of size k is made for
# performing the simulation.
E = D+[0] # Empty array of size k+1 is made for
# storing the magnitudes.
def U(x): # Define a function U that takes an int x
b = D[x] # Assign b to the value at x in D
D[x] = 0 # Clear the value at x in D
return b and U(x-1)+1 + U((x+1)%k) # Return the sum of U(x-1)+1 and U((x+1)%k)
# if b is a 1.
for x in[0]*t: # Perform t tests
r=randint(0,k-1) # Generate a random number between 0 and k-1
e=U(r) # Assign e to the value of U(r)
E[e-1]+=1; # Increment the magnitude array at position
# e-1
D[r] = e<1 # Set D[r] to be 1 if no earthquake happened.
print E[:-1] # Print the magnitude list
```
[Answer]
# Pyth, 48 bytes
```
Km0QJsM.u?<+vM.sjkZ\1KQe=Z.>NOQ+PZ1vwKm/-VJtJhdQ
```
Got a little bit inspired by @Dennis's explanation. Had some similar thoughts yesterday, but didn't really follow them.
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=Km0QJsM.u%3F%3C%2BvM.sjkZ%5C1KQe%3DZ.%3ENOQ%2BPZ1vwKm%2F-VJtJhdQ&input=15%0A1000&debug=0)
### Explanation:
```
implicit: Q is the first input number
m0Q create a list with Q zeros
K store the list in K
.u vwK apply the following expression eval(input) times,
start with N = K:
.>NOQ shift N by a random integer of [0, ..., Q-1]
=Z store the result in Z
? e Z if the last digit == 1:
jkZ convert Z to string
.s \1 remove "1"s from the start and end
vM convert to list of integers
+ K add K (adds a bunch of zeros)
< Q correct size (take the first Q elements)
implicitly update N with this result
else:
PZ all but last of Z
+ 1 append 1
implicitly update N with this result
.u gives all the intermediate states
sM sum each list
J store in J
m/-VJtJhdQ
m Q map each d in [0, 1, ..., Q-1] to:
-VJtJ vectorized minus between J and J[1:]
/ hd count d+1 in ^
implicitly print
```
[Answer]
# ES6, ~~224~~ ~~196~~ ~~189~~ ~~179~~ 172
The easy stuff has been golfed, but still some work to do. I'll type out an explanation later. Also, if someone can tell me why the short `new Date%k` thing doesn't work so well anymore, that'd be swell.
```
f=(k,t)=>{a=Array(k).fill(0);o=a.slice(0);for(;t--;){c=0;r=Math.random()*k|0;if(a[r]){for(d=r+1;d<k&a[d];c++)a[d++]--;for(d=r-1;d&a[d];c++)a[d--]--;o[c]++};a[r]^=1}return o}
```
Usage is
```
f(10, 1000);
```
[Answer]
# Perl, 212
The previous version I had put up was not correctly wrapping, and implementing that took some work.
```
sub f{sub n{$i=($i+$d)%($#a+1)}($k,$t)=@_;@L=@a=(0)x$k;for(1..$t){$i=$x=int rand($k);if(++$a[$x]>1){$d=1;my%z;for(;;){$z{$i}=1;n;if(!$a[$i]){$d*=-1;n}last if($d>0&&$i==$x)}@z=keys %z;@a[@z]=(0)x@z;++$L[$#z]}}@L}
```
This is probably not the right algorithm for this, but I can't think right now. The ungolfed version is below.
Ungolfed:
```
sub f {
# n() implements the iterator, so that each time it is called a
# global index is incremented or decremented correctly wrapping
# around
sub n { $i = ($i + $d) % ($#a + 1) }
# Receive input
($k, $t) = @_;
# Initialise the array for earthquake magnitudes an the fault
# line
@L = @a = (0) x $k;
for(1..$t){
# Assign a random integer value to two control variables
# $i is used for moving along the fault, and $x to remember
# the initial value
$i = $x = int rand($k);
# The corresponding value in the fault line is incremented,
# and earthquakes detected
if(++$a[$x]>1){
# Earthquake!
# To propagate the earthquake, we move along the fault
# bouncing on unactivated nodes. We stop when we've covered
# the entire activated block.
# $d tracks the direction (initially forward);
$d = 1;
# %z keeps the indeces of known activated nodes
my %z;
for(;;){
$z{$i} = 1; # Read current node
n; # Move head
if (!$a[$i]) { # If next one is deactivated
$d *= -1; # change direction
n # and move the head (bounce!)
}
# If we've reached the beginning, and we're moving
# forward we've covered the entire activated block
last if ($d > 0 && $i == $x);
}
# Deactivate all consecutive activated nodes
@z = keys %z;
@a[@z] = (0) x @z;
# And store the magnitude of the earthquake
++$L[$#z];
}
}
# Return list of magnitudes
@L
}
print join ' ', f(15, 1000), "\n";
```
[Answer]
# CJam, 76 bytes
```
l~_0a*:R@{1$mr_2$={W@@[W1]{{_@0t@)\@K+_2$=}g2$+)}fK;\(_R=)R\t:R;}{1t}?}*;;Rp
```
Well, this is not very competitive. But since it took me long enough, I thought I'd post it anyway.
```
l~ Get input.
_0a* Initial bit pattern, list of k zeros.
:R Save away the list of zeros, will be used for histogram.
@{ Pull number of tries to top of stack, and start main loop.
1$mr Generate random position in range 0 to k-1.
_2$ Duplicate current pattern and position.
= Get current value of bit at position.
{ Start if statement. This is the block for bit value 1.
W@@ Create initial count of 1 bits in quake, and push it down the stack.
[W1]{ Start for loop over value [-1 1], the two increments for going left/right.
{ Start while loop that proceeds as long as 1 bits are found.
_@0t Set current value of bit to 0.
@) Get current bit counter to top of stack, and increment it.
\@ Pull list and bit position back to top of stack.
K+ Increment/decrement bit position.
_2$= Get value at new bit position.
}g End of while loop over 1 bits.
2$+) Restore position to get ready to move in opposite direction.
}fK End for loop over left/right increment.
;\(_ Pull counter of 1 bits in quake to top of stack.
R= Get current value in histogram,
) increment it,
R\t:R and store it back in the histogram.
;} End of if branch for 1 bit.
{1t}? Else branch of if. For 0 bit, simply set it.
}* End main loop.
;;Rp Clean up stack and print histogram.
```
[Try it online](http://cjam.aditsu.net/#code=l~_0a*%3AR%40%7B1%24mr_2%24%3D%7BW%40%40%5BW1%5D%7B%7B_%400t%40)%5C%40K%2B_2%24%3D%7Dg2%24%2B)%7DfK%3B%5C(_R%3D)R%5Ct%3AR%3B%7D%7B1t%7D%3F%7D*%3B%3BRp&input=1000%2015)
] |
[Question]
[
[Someone built a really fancy clock](http://basbrun.com/2015/05/04/fibonacci-clock/) using Fibonacci numbers, which looks really nice but is fairly unusable. Just the way we like it! Let's recreate this.
The clock is made up of 5 sections corresponding to the first five Fibonacci numbers, starting from 1 (i.e. 1, 1, 2, 3, 5):
```
ccbeeeee
ccaeeeee
dddeeeee
dddeeeee
dddeeeee
```
The clock is capable of displaying the 12-hour time in increments of 5 minutes. Here is how that works. Consider the time 7:20. The hour 7 can be decomposed into the given Fibonacci numbers as
```
7 = 2 + 5
```
There are also 4 units of five minutes. The 4 can be decomposed as
```
4 = 2 + 1 + 1
```
Now the hours are shown in red, the minute chunks in green, and if a number is used for both hours and minutes it's shown in blue. If a number isn't used at all, it remains white. So the above would be shown as:
```
BBGRRRRR
BBGRRRRR
WWWRRRRR
WWWRRRRR
WWWRRRRR
```
But wait, there's more. The above decompositions aren't the only possibilities. One can also write `7 = 3 + 2 + 1 + 1` and `4 = 3 + 1`, which would give one of
```
GGRWWWWW GGBWWWWW
GGBWWWWW GGRWWWWW
BBBWWWWW or BBBWWWWW
BBBWWWWW BBBWWWWW
BBBWWWWW BBBWWWWW
```
depending on which `1` is chosen. Of course there are other combinations as well. The clock chooses from all valid decompositions at random.
As I said... this might not win a usability award, but it sure is nice to look at.
## The Challenge
Your task is to implement such a clock. Your program (or function) should print an ASCII representation of the current time (rounded down to the last multiple of 5 minutes) as described above to STDOUT or closest alternative. You may choose to read the time in any common format as input or obtain it with standard library functions. You must not assume that the current/given time is divisible by 5 minutes.
Your solution *must* choose randomly from all possible representations of the current time. That is each representation must be printed with non-zero probability.
Midnight and noon should be treated as `0:00` (as opposed to `12:00`).
You may optionally print a single trailing newline character.
You may use any four distinct printable ASCII characters (character codes 0x20 to 0xFE) in place of `RGBW`. Please state your choice in your answer and use it consistently.
This is code golf, so the shortest answer (in bytes) wins.
[Answer]
# Python 2, ~~194~~ 182 bytes
```
from random import*
h=m=H,M=input()
while[h,m]!=[H,M/5]:
h=m=0;s=[]
for n in 1,1,2,3,5:c=randint(0,3);h+=c%2*n;m+=c/2*n;s=zip(*(["WRGB"[c]*n]*n+s)[::-1])
for L in s:print"".join(L)
```
The algorithm is just rejection sampling, so it keeps generating clocks until it gets one that's right. The clock is built by starting with nothing, then doing "add a square above and rotate clockwise" 5 times.
Takes two comma-separated integers via STDIN.
```
>>> ================================ RESTART ================================
>>>
7,17
BBBWWWWW
BBRWWWWW
RRRWWWWW
RRRWWWWW
RRRWWWWW
>>> ================================ RESTART ================================
>>>
7,17
GGBRRRRR
GGRRRRRR
WWWRRRRR
WWWRRRRR
WWWRRRRR
```
[Answer]
# CJam, 61 bytes
```
l~5/]:A{;L[TT][XXYZ5]{4mr_2bW%Mf*@.+\Ps=M*aM*@+W%z\}fMA=!}gN*
```
Takes two space-separated integers via STDIN, and uses `3.14` instead of `WRGB` respectively. [Try it online](http://cjam.aditsu.net/#code=l~5%2F%5D%3AA%7B%3BL%5BTT%5D%5BXXYZ5%5D%7B4mr_2bW%25Mf*%40.%2B%5CPs%3DM*aM*%40%2BW%25z%5C%7DfMA%3D!%7DgN*&input=7%2017).
Here is the "sane" `RGBW` version for a few extra bytes:
```
l~5/]:A{;L[TT][XXYZ5]{4mr_2bW%Mf*@.+\"WRGB"=M*aM*@+W%z\}fMA=!}gN*
```
## Explanation
The algorithm is the same as my [Python answer](https://codegolf.stackexchange.com/a/49837/21487) — rejection sampling by generating clocks until we get one that's correct.
```
l~5/]:A Read input and make array [<hours> <minutes>/5]
{...}g Do...
; Pop the only element on the stack
L Push empty array, which will become our clock
[TT] Push [0 0] for [h m], to keep track of our sample
[XXYZ5]{...}fI For I in [1 1 2 3 5]...
4mr Push random number from [0 1 2 3]
_2bW% Copy and get reversed base 2 rep for one of [0] [1] [0 1] [1 1]
If* Multiply bit(s) by I
@.+ Add element-wise to [h m] array
\Ps= Index the random number into stringified pi for one of "3.14"
I*aI* Make into I by I square
@+W%z\ Add above clock and rotate clockwise
A=! ... while the resulting clock is incorrect
N* Riffle clock with newlines
```
[Answer]
# Python 2, 421 bytes
Ugh, I'm *sure* this can be golfed more.
```
from itertools import*
from random import*
f,r=[1,1,2,3,5],range
c={_:[x for x in chain(*[combinations(f,i)for i in r(6)])if sum(x)==_]for _ in r(13)}
k=[[2,1,4],[2,0,4]]+[[3,4]]*3
def b(h,m):
o=['W']*5;m/=5;h,m=choice(c[h]),choice(c[m])
l=dict(zip(zip('WWR',[m,h,m]),'GRB'))
for x in h,m:
d={1:[0,1],2:[2],3:[3],5:[4]}
for _ in x:j=d[_].pop();o[j]=l[o[j],x]
print'\n'.join([''.join(o[i]*f[i]for i in _)for _ in k])
```
Test case:
```
>>> b(7,20)
WWBRRRRR
WWRRRRRR
GGGRRRRR
GGGRRRRR
GGGRRRRR
>>> b(7,20)
RRBWWWWW
RRRWWWWW
BBBWWWWW
BBBWWWWW
BBBWWWWW
```
[Answer]
# Ruby, 286 bytes
It may be golfable, but will try some other time.
```
z=[]
13.times{z<<[]}
(0..5).to_a.permutation{|p|l=p.take_while{|n|n<5};z[l.map{|n|[1,1,2,3,5][n]}.reduce(0,:+)]<<l}
t=Time.now
h,m=z[t.hour%12].sample,z[t.min/5].sample
5.times{|y|puts (0..7).map{|x|a=(x>2?4:y>1?3:x<2?2:y<1?1:0);q=m.include?(a);h.include?(a)?q ? ?B:?R: q ??G:?W}*""}
```
Explanation:
```
z=[]
13.times{z<<[]} # Initialize the array where we will have all the combinations
(0..5).to_a.permutation{|p| # Get all the permutations of the 5 positions plus a 5, which will be used as a separator
l=p.take_while{|n|n<5}; # Get the permutation until the separator. This way we get all the possible sum combinations of the other five numbers
z[l.map{|n|[1,1,2,3,5][n]}.reduce(0,:+)]<<l} # Add the permutation to the list with id=the permutation's sum
t=Time.now # Get current time
h,m=z[t.hour%12].sample,z[t.min/5].sample # For the hour and the minute, get a random permutation that has the expected sum
5.times{|y| # For each row
$><<(0..7).map{|x| # For each column
a=(x>2?4:y>1?3:x<2?2:y<1?1:0); # Get the panel we are in
q=m.include?(a);h.include?(a)?q ? ?B:?R: q ??G:?W # Get the color this panel is painted
}*""} # Join the string and print it
```
] |
[Question]
[
In this pixelated font of uppercase letters of the alphabet, all the characters are 5 units wide and 5 tall.
```
███ ████ ███ ████ █████ █████ ████ █ █ █████ █ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ ██
█████ ████ █ █ █ ████ ████ █ ██ █████ █ █ ███ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █ ████ ███ ████ █████ █ ████ █ █ █████ ███ █ █ █████ █ █
█ █ ███ ████ ███ ████ ████ █████ █ █ █ █ █ █ █ █ █ █ █████
██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █ █ █ █ ████ █ █ ████ ███ █ █ █ █ █ █ █ █ █ █ █
█ ██ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █ ███ █ ████ █ █ ████ █ ███ █ █ █ █ █ █ █████
```
There is also 1 unit of space between letters and between lines, as can be seen. So each letter can take up to 6×6 units of space.
Suppose that instead of using the [full block character](http://www.fileformat.info/info/unicode/char/2588/index.htm) (`█`) to directly form the shapes of the letters, we wanted to use *other letters in the same font*. This involves increasing the dimensions of the text 6-fold so that letters made of full-blocks can be used as full-block replacements in the larger text.
If that didn't make sense hopefully this example will. Here is an A made of B's using the pixelated font:
```
████ ████ ████
█ █ █ █ █ █
████ ████ ████
█ █ █ █ █ █
████ ████ ████
████ ████
█ █ █ █
████ ████
█ █ █ █
████ ████
████ ████ ████ ████ ████
█ █ █ █ █ █ █ █ █ █
████ ████ ████ ████ ████
█ █ █ █ █ █ █ █ █ █
████ ████ ████ ████ ████
████ ████
█ █ █ █
████ ████
█ █ █ █
████ ████
████ ████
█ █ █ █
████ ████
█ █ █ █
████ ████
```
The B's are made of full blocks and the A is made of B's. Notice that the B's still have one unit between them horizontally and vertically.
We can extend this idea by using words instead of just letters. Here is "WATER" made of "FIRE":
```
█████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
████ █ ████ ████ ████ █ ████ ████ ████ █ ████ ████ ████ █ ████ ████ ████ █ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █
█████ █████ ████ █████ █████ █████ ████ █████
█ █ █ █ █ █ █ █ █ █
████ █ ████ ████ ████ █ ████ ████
█ █ █ █ █ █ █ █ █ █
█ █████ █ █ █████ █ █████ █ █ █████
█████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████ █████ █████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
████ █ ████ ████ ████ █ ████ ████ ████ █ ████ ████ ████ █ ████ ████ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █ █████ █
█████ █████ ████ █████ █████ █████ ████ █████ █████
█ █ █ █ █ █ █ █ █ █ █
████ █ ████ ████ ████ █ ████ ████ ████
█ █ █ █ █ █ █ █ █ █ █
█ █████ █ █ █████ █ █████ █ █ █████ █
█████ █████ ████ █████ █████ █████ ████ █████ █████ █████ ████ █████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █
████ █ ████ ████ ████ █ ████ ████ ████ █ ████ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █████ █ █ █████ █ █████ █ █ █████ █ █████ █ █ █████
```
Notice how "FIRE" appears repeatedly on each line, and always in order, no matter how much space is between the letters. Three of the rightmost instances of "FIRE" were cut off early because of how "WATER"'s letters are shaped.
This idea can be expanded even further, by using these *words made of words* to make *words made of words made of words*, or even *words made of words made of words made of words*. There is no limit theoretically.
Another example would put this post over the 30k character limit, but you can see what is meant by "words made of words made of words" by running this nifty Stack Snippet. Just leave the parameters at their defaults and press "Go!". You should see the word "DOG" made of the word "CAT" made of the word "MOUSE".
```
alphabet = {A:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],C:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,0,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],B:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],E:[[1,1,1,1,1,0],[1,0,0,0,0,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],D:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],G:[[0,1,1,1,1,0],[1,0,0,0,0,0],[1,0,0,1,1,0],[1,0,0,0,1,0],[0,1,1,1,1,0],[0,0,0,0,0,0]],F:[[1,1,1,1,1,0],[1,0,0,0,0,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[0,0,0,0,0,0]],I:[[1,1,1,1,1,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],H:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,1,1,1,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],K:[[1,0,0,0,1,0],[1,0,0,1,0,0],[1,1,1,0,0,0],[1,0,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],J:[[0,0,0,0,1,0],[0,0,0,0,1,0],[0,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],M:[[1,0,0,0,1,0],[1,1,0,1,1,0],[1,0,1,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],L:[[1,0,0,0,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],O:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],N:[[1,0,0,0,1,0],[1,1,0,0,1,0],[1,0,1,0,1,0],[1,0,0,1,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],Q:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,1,1,0],[0,1,1,1,1,0],[0,0,0,0,0,0]],P:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[0,0,0,0,0,0]],S:[[0,1,1,1,1,0],[1,0,0,0,0,0],[0,1,1,1,0,0],[0,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],R:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],U:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],T:[[1,1,1,1,1,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],W:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,1,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,0,0,0,0]],V:[[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,0,1,0,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],Y:[[1,0,0,0,1,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],X:[[1,0,0,0,1,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,1,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],Z:[[1,1,1,1,1,0],[0,0,0,1,0,0],[0,0,1,0,0,0],[0,1,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]]}
empty = ['\xA0', '.']
full = ['\u2588', 'X']
w = 6
h = 6
function makeGrid(height, width) {
var grid = new Array(height)
for(var y = 0; y < height; y++) {
grid[y] = new Array(width)
}
return grid
}
function unfoldGrid(grid) {
var newGrid = makeGrid(h * grid.length, w * grid[0].length)
for (var y = 0; y < newGrid.length; y++) {
for (var x = 0; x < newGrid[0].length; x++) {
var yf = Math.floor(y / h), xf = Math.floor(x / w)
if (grid[yf][xf] != 0) {
newGrid[y][x] = grid[yf][xf][y % h][x % w]
} else {
newGrid[y][x] = 0
}
}
}
return newGrid
}
function makeWords(words, empty, full) {
var grid = makeGrid(1, words[0].length)
for (var i = 0; i < words[0].length; i++) {
grid[0][i] = alphabet[words[0][i]]
}
console.log(grid.length)
console.log(grid[0].length)
grid = unfoldGrid(grid)
console.log(grid.length)
console.log(grid[0].length)
for(var i = 1; i < words.length; i++) {
for (var y = 0; y < grid.length; y++) {
var offset = 0
for (var x = 0; x < grid[0].length; x++) {
if (grid[y][x]) {
grid[y][x] = alphabet[words[i][offset++ % words[i].length]]
}
}
}
grid = unfoldGrid(grid)
}
var output = ''
var height = Math.pow(h, words.length) - (Math.pow(h, words.length) - 1) / (h - 1)
var width = words[0].length * Math.pow(w, words.length) - (Math.pow(w, words.length) - 1) / (w - 1)
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
output += grid[y][x] ? full : empty
}
if (y + 1 != height) {
output += '\r\n'
}
}
return output
}
function go() {
plain = document.getElementById('plain').checked ? 1 : 0
document.getElementById('canvas').value = makeWords(document.getElementById('words').value.split(' '), empty[plain], full[plain])
resize()
}
function resize() {
document.getElementById('canvas').style.fontSize = document.getElementById('size').value
}
function zoom(magnify) {
canvas = document.getElementById('canvas')
match = canvas.style.fontSize.match(/^(\d+(?:\.\d+)?)(.*)$/)
if (match !== null) {
number = parseFloat(match[1])
unit = match[2]
canvas.style.fontSize = document.getElementById('size').value = (number + (magnify ? 0.1 : -0.1)) + unit
}
}
```
```
#canvas {
font-family: Consolas, "Courier New", sans-serif;
white-space: nowrap; overflow: auto;
width: 6in;
height: 3in;
}
```
```
<p>Words: <input type='text' id='words' value='DOG CAT MOUSE'> <button type='button' onclick='go()'>Go!</button> Plain ASCII <input type='checkbox' id='plain'></p>
<p>Font Size: <input type='text' id='size' value='0.4mm'> <button type='button' onclick='resize()'>Resize</button> <button type='button' onclick='zoom(1)'>+</button> <button type='button' onclick='zoom(0)'>-</button> (use any unit: in, cm, mm, em, pt, px)</p>
<textarea id='canvas'></textarea>
```
Typing any space separated list of words **containing only capital letters** in the textbox will produce the first word made of the second word made of the third, made of the fourth, made of ... etc.
**WARNING: Entering more than 4 or even 3 words will produce A LOT of text and take a LONG time. It may crash your browser/computer/car.**
# Challenge
The goal of this challenge is to mirror what the Stack Snippet does in the fewest number of characters.
You must write a program that takes in a space separated string of words containing only capital letters, and outputs the first word "made of" the second "made of" the third and so on, using the pixelated font given above.
The "Plain ASCII" checkbox and the font size features of the snippet do not need to be supported in your program. Mirroring the transformation from lists of words to words made of words is the main point and only requirement.
# Details
* Input should come from stdin, the command line, or you may just write a function that takes a string.
* You may assume the input is always valid, i.e. a string of words made of capital letters, separated by exactly one space, with no leading or trailing spaces.
* Output should go to stdout (or similar alternative) or to a file with the name of your choice.
* The output should consist entirely of *empty-space characters*, *full-space characters*, and newlines.
+ The *empty/full-space characters* should either be space and full block (, `█`) respectively, or period and X (`.`, `X`) respectively.
* The output should not contain any leading columns containing only *empty-space characters*, though any combination of trailing *empty-space characters* on any lines is allowed.
+ So this is allowed:
```
X...X.XXXXX..
X...X.X
X.X.X.XXXX....
X.X.X.X..
.X.X..XXXXX..
```
+ But this isn't:
```
.X...X.XXXXX..
.X...X.X
.X.X.X.XXXX....
.X.X.X.X..
..X.X..XXXXX..
```
* There should be no leading or trailing rows containing only *empty-space characters*. A single trailing newline is optionally allowed.
Here is a more string-friendly version of the font:
```
.XXX.
X...X
XXXXX
X...X
X...X
XXXX.
X...X
XXXX.
X...X
XXXX.
.XXX.
X...X
X....
X...X
.XXX.
XXXX.
X...X
X...X
X...X
XXXX.
XXXXX
X....
XXXX.
X....
XXXXX
XXXXX
X....
XXXX.
X....
X....
.XXXX
X....
X..XX
X...X
.XXXX
X...X
X...X
XXXXX
X...X
X...X
XXXXX
..X..
..X..
..X..
XXXXX
....X
....X
....X
X...X
.XXX.
X...X
X..X.
XXX..
X..X.
X...X
X....
X....
X....
X....
XXXXX
X...X
XX.XX
X.X.X
X...X
X...X
X...X
XX..X
X.X.X
X..XX
X...X
.XXX.
X...X
X...X
X...X
.XXX.
XXXX.
X...X
XXXX.
X....
X....
.XXX.
X...X
X...X
X..XX
.XXXX
XXXX.
X...X
XXXX.
X..X.
X...X
.XXXX
X....
.XXX.
....X
XXXX.
XXXXX
..X..
..X..
..X..
..X..
X...X
X...X
X...X
X...X
.XXX.
X...X
X...X
.X.X.
.X.X.
..X..
X...X
X...X
X.X.X
X.X.X
.X.X.
X...X
.X.X.
..X..
.X.X.
X...X
X...X
.X.X.
..X..
..X..
..X..
XXXXX
...X.
..X..
.X...
XXXXX
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest submission [in bytes](https://mothereff.in/byte-counter) wins. Any instance of a full block (`█`) can be counted as 1 byte instead of 3 so submissions that use `X` don't have an advantage.
[Answer]
## Python 3, 437 bytes
```
from numpy import*
s=input().split()
d=fromstring('NONO__^Q_PQAQQNONO^_QQQQQ_QQQQAAAQDPIA[SQQQQADQQQJJH_OAQOOY_DPGAUUQOQONDQJUDDDQQQQAAQQDQIAQYQAYIPDQJUJDBQONO_A^Q_NQ_QQNA^QODNDJQD_',byte)[:,None]>>arange(5)&1
b=0
x=1
y=len(s[0])
n=[[1]*y]
for w in s:
g=n;b+=x;x*=6;n=zeros((x,x*y),int);i=-6
for q in g:
o=j=0;i+=6
for p in q:n[i:i+5,j:j+5]|=d[ord(w[o%len(w)])-65::26]*p;o+=p;j+=6
for r in n[:-b]:print(''.join(' █'[x] for x in r))
```
The character shapes are encoded in ASCII. Each ASCII byte corresponds to one row of one character, with bits representing unit blocks. It isn't a very efficient scheme, but it's easy to unpack into NumPy bitmasks for each character.
We start off with a 2d array of 1s. It has one column for each character in the first word and a single row. Then, for each word, we create a new array of 0s, six times higher and six times wider than the previous array. Where the previous array had a 1, the corresponding 6x6 section of the new array is filled with the appropriate character's bitmask.
Here's an example (with an extremely small font):

[Answer]
# CJam, ~~171 165 162~~ [161](https://mothereff.in/byte-counter#qS%2F_0%3D%2C0a*a%5C%7B%7BW%3AI%3B%7B%27%5B%7BRI%29%3AI%3D%7D%3Fi65-%22%06%0Ec%C2%BF%C2%BB%C3%90%C2%9D%C3%B2%16O*4%C2%95%C3%95%5D%25%C3%90%C2%8D%C3%8E%3C%C2%94%C3%83%C2%83%C2%96%20IX%5D%7B-%C3%AF%C3%A8q%3D%C3%B4%7Ds%C3%97%1Bo%29%C2%9C%C2%8D%C2%BD2%7E%19%1B%C3%BB%C2%86%C2%B3%27%C3%A9%C2%A8%10%C2%981%C3%83l%C3%98e%C3%BAN!%C3%96%193%7E4%11%C3%9C%C2%9B%C3%8B%7C%C3%95%C3%87%C3%A4%1C%C2%8Daep%C3%BD%C2%AE%C2%9D%22255b2b5%2F5%2F%3D%7D%25z1af*%7D%25R%2C1a*a*%7DfR2a*%22%E2%96%88%20%0A%22f%3D) bytes
```
qS/_0=,0a*a\{{W:I;{'[{RI):I=}?i65-"c¿»ÐòO*4Õ]%ÐÎ<à IX]{-ïèq=ô}s×o)½2~û³'é¨1ÃlØeúN!Ö3~4ÜË|ÕÇäaepý®"255b2b5/5/=}%z1af*}%R,1a*a*}fR2a*"█
"f=
```
I am treating `█` as 1 byte. Rest all characters are well within ASCII range, so treating them as 1 byte too.
You can use [this pastebin](http://pastebin.com/jXtEdV58) for the exact code
Example output for input:
```
FIRST HELLO WORLD
```

**How it works**
First of all
```
"c¿»ÐòO*4Õ]%ÐÎ<à IX]{-ïèq=ô}s×o)½2~û³'é¨1ÃlØeúN!Ö3~4ÜË|ÕÇäaepý®"255b2b5/5/
```
is simply the pattern for each of the 27 characters (`A-Z` and space) which is made up of `0` (at `X` positions) and `1` (at `.` positions). After decoding, this gives a 27 element array of 2D arrays of 5 rows and 5 columns representing `X` and `.` for each of the 27 characters. Let us call this array as `L`.
Now the remaining code:
```
qS/ "Read the input and split it on space to get array Q";
_0= "Get a copy of the first element of the above array";
,0a* "Create an array filled with 0 with length of the first element";
a\ "Wrap that array in another array and swap to get Q on top";
{ ... }fR "This is a for each loop on the array Q with R having the";
"current element value in each loop";
{...}% "In the first iteration, the 0 array we created will be the";
"only thing on stack, in subsequent iterations, the result";
"of previous iteration will be on stack";
W:I; "Initialize variable I with -1";
{...}% "Run this block on each element of the current array";
{'[{RI):I=}?i65-L=}% "This is the above code block. In each iteration, we figure";
"out what character needs to be be put at the current index";
"Then we get the pattern of 0 and 1 for that character";
'[{ }? "Stack contains either 0 or 1. If it is 1, we want to leave";
"that index blank, so we put pattern of '[ which is 5X5 spaces";
RI_:I= "When we do not want a blank character, we get the next"
"character from R to fill the non empty space";
i65- "Convert A-Z to 0-27 notation";
L= "Get the corresponding pattern from the pattern array L";
z1af* "After the above iterations, for each line of the previous";
"iteration's output, we get a vertical 2D array for next";
"iteration. We transpose it and join each character in";
"this line using a space";
R,1a*a* "After getting all lines from current iteration, we join them";
"with one full line of space characters";
2a* "After all iterations, we have the 0 1 based 2D array for the";
"final output ASCII with each row representing a line. We join";
"these lines with 2, to get a 0 1 2 based array";
"█ "A brick, a space and a newline. Mapping 1 to 1 with 0 1 2";
" "based array";
f= "For each of the 0 1 2 based array element, convert them to";
"one of the brick, space and new line character";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# CJam, ~~181~~ ~~174~~ 170 bytes
All those non-ASCII characters are still within the extended ASCII range, so they can all be encoded in a single byte. (Except for the `█`, but that one is treated specially according to the challenge spec.) Therefore, I'm counting each character as a byte.
```
"Á :½A%õÍú£à˪ë8!Õ*j4¶fVËa¡ùÔ¯{+ÛyéâõKn#@?
9Ôia)(Ñç;~LÒª"257b2bYYb" █"er5/5/:L;lS/_0=,'█*a\{f{W:T;\{' ={S5*a5*}{T):T1$='A-L=}?\}%W<zSf*}Sa*}/N*
```
Stack Exchange has probably mangled some of the unprintable characters, so you might have to copy the code [from this pastebin](http://pastebin.com/1ei1Tj8t).
[Test it here.](http://cjam.aditsu.net/)
Takes input via STDIN as a space-separated list of words. The first word is the largest scale. For instance:
```
HOLISM REDUCTIONISM
```
yields
```
████ █████ ████ █ █ ███ █████ █████ ███ █ █ █████ ████ █ █ ████ █████ ████ █ █ ███
█ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ ██ ██ █ █ █ █ █ █ █ █ █
████ ████ █ █ █ █ █ █ █ █ █ █ █ █ █ ███ █ █ █ ████ ████ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ █ █ █
█ █ █████ ████ ███ ███ █ █████ ███ █ █ █████ ████ █ █ █ █ █████ ████ ███ ███
████ █████ ████ █ █ ███ █████ █████ ███ █ █ █████ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █
████ ████ █ █ █ █ █ █ █ █ █ █ █ █ █ ███
█ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █
█ █ █████ ████ ███ ███ █ █████ ███ █ █ █████ ████
████ █████ ████ █ █ ███ █████ █████ ███ █ █ █████ ████ █ █ ████ █████ ████
█ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ ██ ██ █ █ █ █ █
████ ████ █ █ █ █ █ █ █ █ █ █ █ █ █ ███ █ █ █ ████ ████ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ █ █ █ █ █ █
█ █ █████ ████ ███ ███ █ █████ ███ █ █ █████ ████ █ █ █ █ █████ ████
████ █████ ████ █ █ ███ █████ █████ ███ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ ██ █
████ ████ █ █ █ █ █ █ █ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ ██
█ █ █████ ████ ███ ███ █ █████ ███ █ █
████ █████ ████ █ █ ███ █████ █████ ███ █ █ █████ ████ █ █ ████ █████ ████ █ █ ███ █████ █████ ███ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ ██ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ █
████ ████ █ █ █ █ █ █ █ █ █ █ █ █ █ ███ █ █ █ ████ ████ █ █ █ █ █ █ █ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ██
█ █ █████ ████ ███ ███ █ █████ ███ █ █ █████ ████ █ █ █ █ █████ ████ ███ ███ █ █████ ███ █ █
```
## Explanation
First, we store a lookup table for letter shapes in `L`:
```
"Á :½A%õÍú£à˪ë8!Õ*j4¶fVËa¡ùÔ¯{+ÛyéâõKn#@?
9Ôia)(Ñç;~LÒª"257b2bYYb" █"er5/5/:L;
```
The first string just a compressed number. We treat the code points as base-257 digits, then we convert the resulting number to binary. `YYb` is 2 is in base 2, so it gives `[1 0]`. We use element substitution with `" █"` to turn the digits into spaces and block characters. Lastly, we split the string into rows of 5 characters, and again into blocks of 5 rows. The result is stored in `L` and discarded from the stack.
Now the general idea is to start with a single line of `█` of the length of the largest-scale word. And then for each word we go through the existing grid, and expand all blocks to the corresponding character at the next smaller scale (while inserting empty rows and columns for separation). Here is the input preparation:
```
lS/_0=,'█*a\
lS/ "Read input, split on spaces.";
_0= "Duplicate and get first word.";
,'█* "Get length repeat █ that many times.";
a "Wrap in array, to make the grid two-dimensional.";
\ "Swap with word list.";
```
Let's look at the outermost structure of the remaining program first. The next block `{...}/` is run for every word, and expands each of the block characters.
```
{f{...}Sa*}/N*
{ }/ "Process each word in the input.";
f{...} "Map this block onto each line of the grid, passing in the current word as well.";
Sa* "Since each original line will be turned into 5 lines, the grid is still grouped
into blocks of 5 lines. We join them together with empty lines as required.";
N* "Join all lines together with newlines.";
```
Lastly, let's look at how a single line is expanded:
```
W:T;\{' ={S5*a5*}{T):T1$='A-L=}?\}%
W:T; "Store -1 in T.";
\ "Swap word with line.";
{ }% "Map this block onto each character.";
' = "Check if the character is a space.";
{ }{ }? "If it is, run the first block, otherwise the second.";
S5* "Create a string of five spaces.";
a5* "Create an array of five such strings.";
T):T "Push T, increment, store in T.";
1$= "Copy the word and access the T'th character, cyclically.";
'A- "Subtract A from the letter.";
L= "Use the result to get the character shape from L.";
\ "Swap resulting block with word.";
"At this point each character is replaced with a 5x5 array of new characters.
So we actually have a 3D array right now. Since we used a map operation, the
current word will also be at the end of the array, which we need to get rid off.";
W<zSf*
W< "Discard last array element - the current word.";
z "Zip or transpose the top two levels of the array.";
Sf* "Join each line together with spaces.";
```
The result is printed automatically at the end of the program.
] |
[Question]
[
The challenge is to write a solver for the classic pencil and paper game [Dots and Boxes](http://en.wikipedia.org/wiki/Dots_and_Boxes) . Your code should take two integers `m` and `n` as input which specifies the size of the board.
>
> Starting with an empty grid of dots, players take turns, adding a
> single horizontal or vertical line between two unjoined adjacent dots.
> A player who completes the fourth side of a 1×1 box earns one point
> and takes another turn. (The points are typically recorded by placing
> in the box an identifying mark of the player, such as an initial). The
> game ends when no more lines can be placed. The winner of the game is
> the player with the most points.
>
>
>

You can assume that either `n = m` or `n = m - 1` and `m` is at least 2.
The challenge is to `solve` the largest possible Dots and Boxes game in under a minute. The size of a game is simply `n*m`. The output of your code should be `win` , `draw` or `lose` which should be the result for the first player assuming both players play optimally.
Your code must be compilable/runnable on ubuntu using easily installable and free tools. Please report your score as the largest area you can solve on your computer in 1 minute together with the time. I will then test the code on my computer and make a rank ordered table of entries.
In the case of a tie-break, the winner will be the fastest code on the largest size board it can solve in under a minute.
---
It would be better if the code outputted not just win or lose but the actual score as well. This makes for a sanity check of correctness.
[Answer]
## C99 - 3x3 board in 0.084s
**2020 edit/disclaimer:** See comments section. It looks like there may have been errors in the original code. Proceed to the remainder of this answer with some skepticism until it is fixed.
**Edit:** I refactored my code and did some deeper analysis on the results.
**Further Edits:** Added pruning by symmetries. This makes 4 algorithm configurations: with or without symmetries X with or without alpha-beta pruning
**Furthest Edits:** Added memoization using a hash table, finally achieving the impossible: solving a 3x3 board!
Primary features:
* straightforward implementation of minimax with alpha-beta pruning
* very little memory management (maintains dll of valid moves; O(1) updates per branch in the tree search)
* second file with pruning by symmetries. Still achieves O(1) updates per branch (technically O(S) where S is the number of symmetries. This is 7 for square boards and 3 for non-square boards)
* third and fourth files add memoization. You have control over the hashtable's size (`#define HASHTABLE_BITWIDTH`). When this size is greater than or equal to the number of walls, it guarantees no collisions and O(1) updates. Smaller hashtables will have more collisions and be slightly slower.
* compile with `-DDEBUG` for printouts
Potential improvements:
* fix small memory leak fixed in first edit
* alpha/beta pruning added in 2nd edit
* prune symmetries added in 3rd edit (note that symmetries are *not* handled by memoization, so that remains a separate optimization.)
* memoization added in 4th edit
* currently memoization uses an indicator bit for each wall. A 3x4 board has 31 walls, so this method couldn't handle 4x4 boards regardless of time constraints. the improvement would be to emulate X-bit integers, where X is at least as large as the number of walls.
## Code
Due to lack of organization, the number of files has grown out of hand. All code has been moved to [this Github Repository](https://github.com/wrongu/codegolf/tree/master/dots%20and%20boxes). In the memoization edit, I added a makefile and testing script.
## Results

## Notes on Complexity
Brute-force approaches to dots and boxes blow up in complexity *very quickly*.
Consider a board with `R` rows and `C` columns. There are `R*C` squares, `R*(C+1)` vertical walls, and `C*(R+1)` horizontal walls. That is a total of `W = 2*R*C + R + C`.
Because Lembik asked us to *solve* the game with minimax, we need to traverse to the leaves of the game tree. Let's ignore pruning for now, because what matters is orders of magnitude.
There are `W` options for the first move. For each of those, the next player can play any of the `W-1` remaining walls, etc.. That gives us a search-space of `SS = W * (W-1) * (W-2) * ... * 1`, or `SS = W!`. Factorials are huge, but that's only the beginning. `SS` is the number of *leaf nodes* in the search space. More relevant to our analysis is the total number of decisions which had to be made (i.e. the number of *branches* `B` in the tree). The first layer of branches has `W` options. For each of those, the next level has `W-1`, etc.
```
B = W + W*(W-1) + W*(W-1)*(W-2) + ... + W!
B = SUM W!/(W-k)!
k=0..W-1
```
Let's look at some small table sizes:
```
Board Size Walls Leaves (SS) Branches (B)
---------------------------------------------------
1x1 04 24 64
1x2 07 5040 13699
2x2 12 479001600 1302061344
2x3 17 355687428096000 966858672404689
```
These numbers are getting ridiculous. At least they explain why the brute-force code seems to hang forever on a 2x3 board. **The search-space of a 2x3 board is 742560 times larger than 2x2**. If 2x2 takes 20 seconds to complete, a conservative extrapolation predicts **over 100 days** of execution time for 2x3. Clearly we need to prune.
## Pruning Analysis
I started by adding very simple pruning using the alpha-beta algorithm. Basically, it stops searching if an ideal opponent would never give it its current opportunities. "Hey look - I win by a lot if my opponent lets me get every square!", thought no AI, ever.
**edit** I have also added pruning based on symmetrical boards. I don't use a memoization approach, just in case someday I add memoization and want to keep that analysis separate. Instead, it works like this: most lines have a "symmetric pair" somewhere else on the grid. There are up to 7 symmetries (horizontal, vertical, 180 rotation, 90 rotation, 270 rotation, diagonal, and the other diagonal). All 7 apply to square boards, but the last 4 don't apply to non-square boards. Each wall has a pointer to it's "pair" for each of these symmetries. If, going into a turn, the board is horizontally symmetric, then only *one of each horizontal pair* needs to be played.
**edit edit** Memoization! Each wall gets a unique id, which I conveniently set to be an indicator bit; the nth wall has the id `1 << n`. The hash of a board, then, is just the OR of all walls played. This is updated at each branch in O(1) time. The size of the hashtable is set in a `#define`. All tests were run with size 2^12, because why not? When there are more walls than bits indexing the hashtable (12 bits in this case), the least significant 12 are masked and used as the index. Collisions are handled with a linked list at each hashtable index. The following chart is my quick-and-dirty analysis of how hashtable size affects performance. On a computer with infinite RAM, we would always set the table's size to the number of walls. A 3x4 board would have a hashtable 2^31 long. Alas we don't have that luxury.

Ok, back to pruning.. By stopping the search high in the tree, we can save *a lot* of time by not going down to leaves. The 'Pruning Factor' is the fraction of all-possible-branches which we had to visit. Brute-force has a pruning factor of 1. The smaller it is, the better.


[Answer]
# Python - 2x2 in 29s
Cross-posting from [puzzles](https://puzzling.stackexchange.com/a/1739/1497). Not especially optimized, but may make a useful starting point for other entrants.
```
from collections import defaultdict
VERTICAL, HORIZONTAL = 0, 1
#represents a single line segment that can be drawn on the board.
class Line(object):
def __init__(self, x, y, orientation):
self.x = x
self.y = y
self.orientation = orientation
def __hash__(self):
return hash((self.x, self.y, self.orientation))
def __eq__(self, other):
if not isinstance(other, Line): return False
return self.x == other.x and self.y == other.y and self.orientation == other.orientation
def __repr__(self):
return "Line({}, {}, {})".format(self.x, self.y, "HORIZONTAL" if self.orientation == HORIZONTAL else "VERTICAL")
class State(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.whose_turn = 0
self.scores = {0:0, 1:0}
self.lines = set()
def copy(self):
ret = State(self.width, self.height)
ret.whose_turn = self.whose_turn
ret.scores = self.scores.copy()
ret.lines = self.lines.copy()
return ret
#iterate through all lines that can be placed on a blank board.
def iter_all_lines(self):
#horizontal lines
for x in range(self.width):
for y in range(self.height+1):
yield Line(x, y, HORIZONTAL)
#vertical lines
for x in range(self.width+1):
for y in range(self.height):
yield Line(x, y, VERTICAL)
#iterate through all lines that can be placed on this board,
#that haven't already been placed.
def iter_available_lines(self):
for line in self.iter_all_lines():
if line not in self.lines:
yield line
#returns the number of points that would be earned by a player placing the line.
def value(self, line):
assert line not in self.lines
all_placed = lambda seq: all(l in self.lines for l in seq)
if line.orientation == HORIZONTAL:
#lines composing the box above the line
lines_above = [
Line(line.x, line.y+1, HORIZONTAL), #top
Line(line.x, line.y, VERTICAL), #left
Line(line.x+1, line.y, VERTICAL), #right
]
#lines composing the box below the line
lines_below = [
Line(line.x, line.y-1, HORIZONTAL), #bottom
Line(line.x, line.y-1, VERTICAL), #left
Line(line.x+1, line.y-1, VERTICAL), #right
]
return all_placed(lines_above) + all_placed(lines_below)
else:
#lines composing the box to the left of the line
lines_left = [
Line(line.x-1, line.y+1, HORIZONTAL), #top
Line(line.x-1, line.y, HORIZONTAL), #bottom
Line(line.x-1, line.y, VERTICAL), #left
]
#lines composing the box to the right of the line
lines_right = [
Line(line.x, line.y+1, HORIZONTAL), #top
Line(line.x, line.y, HORIZONTAL), #bottom
Line(line.x+1, line.y, VERTICAL), #right
]
return all_placed(lines_left) + all_placed(lines_right)
def is_game_over(self):
#the game is over when no more moves can be made.
return len(list(self.iter_available_lines())) == 0
#iterates through all possible moves the current player could make.
#Because scoring a point lets a player go again, a move can consist of a collection of multiple lines.
def possible_moves(self):
for line in self.iter_available_lines():
if self.value(line) > 0:
#this line would give us an extra turn.
#so we create a hypothetical future state with this line already placed, and see what other moves can be made.
future = self.copy()
future.lines.add(line)
if future.is_game_over():
yield [line]
else:
for future_move in future.possible_moves():
yield [line] + future_move
else:
yield [line]
def make_move(self, move):
for line in move:
self.scores[self.whose_turn] += self.value(line)
self.lines.add(line)
self.whose_turn = 1 - self.whose_turn
def tuple(self):
return (tuple(self.lines), tuple(self.scores.items()), self.whose_turn)
def __hash__(self):
return hash(self.tuple())
def __eq__(self, other):
if not isinstance(other, State): return False
return self.tuple() == other.tuple()
#function decorator which memorizes previously calculated values.
def memoized(fn):
answers = {}
def mem_fn(*args):
if args not in answers:
answers[args] = fn(*args)
return answers[args]
return mem_fn
#finds the best possible move for the current player.
#returns a (move, value) tuple.
@memoized
def get_best_move(state):
cur_player = state.whose_turn
next_player = 1 - state.whose_turn
if state.is_game_over():
return (None, state.scores[cur_player] - state.scores[next_player])
best_move = None
best_score = float("inf")
#choose the move that gives our opponent the lowest score
for move in state.possible_moves():
future = state.copy()
future.make_move(move)
_, score = get_best_move(future)
if score < best_score:
best_move = move
best_score = score
return [best_move, -best_score]
n = 2
m = 2
s = State(n,m)
best_move, relative_value = get_best_move(s)
if relative_value > 0:
print("win")
elif relative_value == 0:
print("draw")
else:
print("lose")
```
[Answer]
# Javascript - 1x2 board in 20ms
Online demo available here (warning - **very slow if larger than 1x2 with full search depth**):
<https://dl.dropboxusercontent.com/u/141246873/minimax/index.html>
Was developed for the original win criteria (code golf) and not for speed.
Tested in google chrome v35 on windows 7.
```
//first row is a horizontal edges and second is vertical
var gameEdges = [
[false, false],
[false, false, false],
[false, false]
]
//track all possible moves and score outcome
var moves = []
function minimax(edges, isPlayersTurn, prevScore, depth) {
if (depth <= 0) {
return [prevScore, 0, 0];
}
else {
var pointValue = 1;
if (!isPlayersTurn)
pointValue = -1;
var moves = [];
//get all possible moves and scores
for (var i in edges) {
for (var j in edges[i]) {
//if edge is available then its a possible move
if (!edges[i][j]) {
//if it would result in game over, add it to the scores array, otherwise, try the next move
//clone the array
var newEdges = [];
for (var k in edges)
newEdges.push(edges[k].slice(0));
//update state
newEdges[i][j] = true;
//if closing this edge would result in a complete square, get another move and get a point
//square could be formed above, below, right or left and could get two squares at the same time
var currentScore = prevScore;
//vertical edge
if (i % 2 !== 0) {//i === 1
if (newEdges[i] && newEdges[i][j - 1] && newEdges[i - 1] && newEdges[i - 1][j - 1] && newEdges[parseInt(i) + 1] && newEdges[parseInt(i) + 1][j - 1])
currentScore += pointValue;
if (newEdges[i] && newEdges[i][parseInt(j) + 1] && newEdges[i - 1] && newEdges[i - 1][j] && newEdges[parseInt(i) + 1] && newEdges[parseInt(i) + 1][j])
currentScore += pointValue;
} else {//horizontal
if (newEdges[i - 2] && newEdges[i - 2][j] && newEdges[i - 1][j] && newEdges[i - 1][parseInt(j) + 1])
currentScore += pointValue;
if (newEdges[parseInt(i) + 2] && newEdges[parseInt(i) + 2][j] && newEdges[parseInt(i) + 1][j] && newEdges[parseInt(i) + 1][parseInt(j) + 1])
currentScore += pointValue;
}
//leaf case - if all edges are taken then there are no more moves to evaluate
if (newEdges.every(function (arr) { return arr.every(Boolean) })) {
moves.push([currentScore, i, j]);
console.log("reached end case with possible score of " + currentScore);
}
else {
if ((isPlayersTurn && currentScore > prevScore) || (!isPlayersTurn && currentScore < prevScore)) {
//gained a point so get another turn
var newMove = minimax(newEdges, isPlayersTurn, currentScore, depth - 1);
moves.push([newMove[0], i, j]);
} else {
//didnt gain a point - opponents turn
var newMove = minimax(newEdges, !isPlayersTurn, currentScore, depth - 1);
moves.push([newMove[0], i, j]);
}
}
}
}
}//end for each move
var bestMove = moves[0];
if (isPlayersTurn) {
for (var i in moves) {
if (moves[i][0] > bestMove[0])
bestMove = moves[i];
}
}
else {
for (var i in moves) {
if (moves[i][0] < bestMove[0])
bestMove = moves[i];
}
}
return bestMove;
}
}
var player1Turn = true;
var squares = [[0,0],[0,0]]//change to "A" or "B" if square won by any of the players
var lastMove = null;
function output(text) {
document.getElementById("content").innerHTML += text;
}
function clear() {
document.getElementById("content").innerHTML = "";
}
function render() {
var width = 3;
if (document.getElementById('txtWidth').value)
width = parseInt(document.getElementById('txtWidth').value);
if (width < 2)
width = 2;
clear();
//need to highlight the last move taken and show who has won each square
for (var i in gameEdges) {
for (var j in gameEdges[i]) {
if (i % 2 === 0) {
if(j === "0")
output("*");
if (gameEdges[i][j] && lastMove[1] == i && lastMove[2] == j)
output(" <b>-</b> ");
else if (gameEdges[i][j])
output(" - ");
else
output(" ");
output("*");
}
else {
if (gameEdges[i][j] && lastMove[1] == i && lastMove[2] == j)
output("<b>|</b>");
else if (gameEdges[i][j])
output("|");
else
output(" ");
if (j <= width - 2) {
if (squares[Math.floor(i / 2)][j] === 0)
output(" ");
else
output(" " + squares[Math.floor(i / 2)][j] + " ");
}
}
}
output("<br />");
}
}
function nextMove(playFullGame) {
var startTime = new Date().getTime();
if (!gameEdges.every(function (arr) { return arr.every(Boolean) })) {
var depth = 100;
if (document.getElementById('txtDepth').value)
depth = parseInt(document.getElementById('txtDepth').value);
if (depth < 1)
depth = 1;
var move = minimax(gameEdges, true, 0, depth);
gameEdges[move[1]][move[2]] = true;
lastMove = move;
//if a square was taken, need to update squares and whose turn it is
var i = move[1];
var j = move[2];
var wonSquare = false;
if (i % 2 !== 0) {//i === 1
if (gameEdges[i] && gameEdges[i][j - 1] && gameEdges[i - 1] && gameEdges[i - 1][j - 1] && gameEdges[parseInt(i) + 1] && gameEdges[parseInt(i) + 1][j - 1]) {
squares[Math.floor(i / 2)][j - 1] = player1Turn ? "A" : "B";
wonSquare = true;
}
if (gameEdges[i] && gameEdges[i][parseInt(j) + 1] && gameEdges[i - 1] && gameEdges[i - 1][j] && gameEdges[parseInt(i) + 1] && gameEdges[parseInt(i) + 1][j]) {
squares[Math.floor(i / 2)][j] = player1Turn ? "A" : "B";
wonSquare = true;
}
} else {//horizontal
if (gameEdges[i - 2] && gameEdges[i - 2][j] && gameEdges[i - 1] && gameEdges[i - 1][j] && gameEdges[i - 1] && gameEdges[i - 1][parseInt(j) + 1]) {
squares[Math.floor((i - 1) / 2)][j] = player1Turn ? "A" : "B";
wonSquare = true;
}
if (gameEdges[i + 2] && gameEdges[parseInt(i) + 2][j] && gameEdges[parseInt(i) + 1] && gameEdges[parseInt(i) + 1][j] && gameEdges[parseInt(i) + 1] && gameEdges[parseInt(i) + 1][parseInt(j) + 1]) {
squares[Math.floor(i / 2)][j] = player1Turn ? "A" : "B";
wonSquare = true;
}
}
//didnt win a square so its the next players turn
if (!wonSquare)
player1Turn = !player1Turn;
render();
if (playFullGame) {
nextMove(playFullGame);
}
}
var endTime = new Date().getTime();
var executionTime = endTime - startTime;
document.getElementById("executionTime").innerHTML = 'Execution time: ' + executionTime;
}
function initGame() {
var width = 3;
var height = 2;
if (document.getElementById('txtWidth').value)
width = document.getElementById('txtWidth').value;
if (document.getElementById('txtHeight').value)
height = document.getElementById('txtHeight').value;
if (width < 2)
width = 2;
if (height < 2)
height = 2;
var depth = 100;
if (document.getElementById('txtDepth').value)
depth = parseInt(document.getElementById('txtDepth').value);
if (depth < 1)
depth = 1;
if (width > 2 && height > 2 && !document.getElementById('txtDepth').value)
alert("Warning. Your system may become unresponsive. A smaller grid or search depth is highly recommended.");
gameEdges = [];
for (var i = 0; i < height; i++) {
if (i == 0) {
gameEdges.push([]);
for (var j = 0; j < (width - 1) ; j++) {
gameEdges[i].push(false);
}
}
else {
gameEdges.push([]);
for (var j = 0; j < width; j++) {
gameEdges[(i * 2) - 1].push(false);
}
gameEdges.push([]);
for (var j = 0; j < (width - 1) ; j++) {
gameEdges[i*2].push(false);
}
}
}
player1Turn = true;
squares = [];
for (var i = 0; i < (height - 1) ; i++) {
squares.push([]);
for (var j = 0; j < (width - 1); j++) {
squares[i].push(0);
}
}
lastMove = null;
render();
}
document.addEventListener('DOMContentLoaded', initGame, false);
```
] |
[Question]
[
I tested the waters on this sort of question with [python](https://codegolf.stackexchange.com/questions/209734/), but now I get to the real question I want to ask.
[restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges are uniquely rewarding in Haskell because of Haskell's strict rule set. Type coercion which is the bread and butter for other languages in these sort of challenges is arguably non-existent but when pushed to the limits Haskell provides some weird and interesting solutions.
What are some [tips](/questions/tagged/tips "show questions tagged 'tips'") for solving [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges in Haskell?
Please only include 1 tip per answer. If your tip only works for a specific compiler, or version of Haskell please note that.
---
## What makes a good tip here?
There are a couple of criteria I think a good tip should have:
1. It should be (somewhat) non obvious.
Similar to the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips it should be something that someone who has golfed in python a bit and read the tips page would not immediately think of. For example "Replace `a + b` with `a+b` to avoid using spaces", is obvious to any golfer since it is already a way to make your code shorter and thus not a good tip for this question.
2. It should not be too specific.
Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction. For example tips of the form **How to X without using character(s) Y** are generally useful since banned characters is a common source restriction, or the byproduct of more unique restrictions. The thing your tip helps to do should also be somewhat general. For example tips of the form **How to create numbers with X restriction** are useful since many programs utilize numbers regardless of the challenge. Tips of the form **How to implement Shor's algorithm with X restriction** are basically just answers to a challenge you just invented and not very helpful to people solving other challenges.
[Answer]
# Break tokens with comments
A neat fact I discovered a little while ago (and the impetus for this sort of tips question in the first place), is that a block comment allows you to split tokens apart without a space.
For example if you want to write
```
main=interact tail
```
Without using whitespace, parentheses or `$` you can do the following:
```
main=interact{--}tail
```
Here `{--}` is a block comment, which normally would do nothing, however here placed between `interact` and `tail` it serves to prevent the two as being parsed as a single token, `interacttail`.
This could also be used to split other kinds of tokens for example:
```
main=print${--}-3
```
Here we split the `$` and the `-` without using spaces or parentheses.
```
data{--}K=K
```
Here we split a keyword from a type declaration (which unlike the earlier example cannot be done with `$`).
Pretty much anywhere you would use a space outside a `String` or `Char` literal you can use a block comment instead.
[Answer]
## Anything can be an infix operator
While `(&)` is usually the "prefix form" of an infix function, it doesn't have to be defined as infix, or even a function.
The following definition of a unary function `(#)` with argument `(&)`, a list of numbers, compiles and runs just fine:
```
(#)(&)=(&)!!0+(&)!!3
```
This could be useful if alphabetic characters are forbidden/restricted/penalized.
[Answer]
# Name your variables `__` and `_'`
Before you go naming things as [infix operators](https://codegolf.stackexchange.com/a/211348/) if you need to avoid letters you can name things `__` and `_'`. These are only 2 bytes long whereas infix operators are 3. And once you run out of 1 character infix operators `___`, `__'`, `_'_` and `_''` are all available.
You can see this used [here](https://codegolf.stackexchange.com/a/230458/56656) by Lynn.
] |
[Question]
[
This is essentially the inverse of [Generate a US License Plate](https://codegolf.stackexchange.com/questions/128705/generate-a-us-license-plate)
**Challenge:** Given a string that matches one of the below license plate formats, output all possible states that match that formatting. In the below table `0` stands for a single digit `0` through `9` inclusive, and `A` stands for a single letter `A` through `Z` inclusive. For the purposes of this challenge, we're ignoring states with complex format rules (like Delaware, which has variable number of digits), and ignoring removal of look-alike letters (e.g., `I` and `1`).
```
AAA 000: AK, IA, MS, MP, VT
0000: AS
AAA0000: AZ, GA, WA
000 AAA: AR, KS, KY, LA, ND, OR
0AAA000: CA
AA-00000: CT
AA-0000: DC
AAA A00: FL
AA 00000: IL
000A,000AA,000AAA,AAA000: IN
0AA0000: MD
AAA 0000,0AA A00,AAA 000: MI
000-AAA: MN
00A-000: NV
000 0000: NH
A00-AAA: NJ
000-AAA,AAA-000: NM
AAA-0000: NY, NC, PA, TX, VA, WI
AAA 0000: OH
000AAA: OK
AAA-000: PR
000-000: RI
AAA 000,000 0AA: SC
A00-00A: TN
A00 0AA: UT
```
Examples:
```
B32 9AG
[UT]
1YUC037
[CA]
285 LOR
[AR, KS, KY, LA, ND, OR] (in any order)
285-LOR
[MN, NM] (in any order)
285LOR
[IN, OK] (in any order)
```
**Rules and Clarifications**
* The input string is guaranteed non-empty, and guaranteed to be of one of the above formats
* Behavior if given a format other than the above is undefined
* Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963)
* You can print the result to STDOUT or return it as a function result
* Either a full program or a function are acceptable
* [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]
# JavaScript (ES6), ~~203 202 201~~ 200 bytes
*Saved 1 byte thanks to @NahuelFouilleul*
```
s=>'xMiAZGAWaMIOhNvInxMNNmARKSKYLANDOrNMPrAKIAMIMSMPSCVtAsMdxScRiNhUtDcCtxFlxNYNCPATXVAWiInIlINOkNjCaTn'.match(/[A-Z]*./g)[s.replace(/./g,c=>c<'!'?0:1/c?9:6-~(c+1))*3%47%30].toUpperCase().match(/../g)
```
[Try it online!](https://tio.run/##dcwxb4JAAIbhvb@CDgawBQRsraZormc0F7yDgGjROFxOFCwC4Yhh6l@nOHRp6PANX57kvdAb5axMikrJ8mPUnKyGW1OxxgnYLcGWYuTE5IayGhNyBZ7t2@EKkLlTEuyWwEYAI@xj14ebCnB8rH3mJSQOqjmDVb1IaxIS6IL15wZsE5ShFBHni1wgXWeieqUViyVtD5Tdoa9qZ3nP1TIqUsoiSWv/M7Om7F18FGeDia6x2XjyqnxL7EmX5b7ZG4565uCgVnlQFFEJKY8k@Tep3msNyzOep5Ga5mfpJIkfpiGMwVKU5Yc/oocBHJijDjHeXoSV43WL8q90g26YQrthBy0c506tND8 "JavaScript (Node.js) – Try It Online")
## How?
### Input conversion
We turn the input string into an integer \$n\$ by applying the following substitutions:
* spaces are replaced with \$0\$
* digits are replaced with \$9\$
* letters are replaced with \$7\$
* hyphens are replaced with \$6\$
As JS code:
```
c < '!' ? // if c is a space:
0 // replace it with 0
: // else:
1 / c ? // if c is a digit:
9 // replace it with 9
: // else:
6 - ~(c + 1) // if c is a hyphen, this gives:
// 6 - ~('-1') --> 6 - 0 --> 6
// if c is a letter (e.g. 'A'), this gives:
// 6 - ~('A1') --> 6 - ~NaN --> 6 - (-1) --> 7
```
### Hash function
We then apply the following hash function:
$$f(n) = ((3\times n) \bmod 47) \bmod 30$$
This gives a unique ID in \$[1..29]\$. There's actually a collision between `000AA` and `AAA000` which both result in \$24\$, but that's perfectly fine as these plate formats are used in Indiana exclusively.
```
format | n | * 3 | mod 47 | mod 30 | states
------------+----------+-----------+--------+--------+----------------------
'AAA 000' | 7770999 | 23312997 | 10 | 10 | AK,IA,MI,MS,MP,SC,VT
'0000' | 9999 | 29997 | 11 | 11 | AS
'AAA0000' | 7779999 | 23339997 | 32 | 2 | AZ,GA,WA
'000 AAA' | 9990777 | 29972331 | 8 | 8 | AR,KS,KY,LA,ND,OR
'0AAA000' | 9777999 | 29333997 | 28 | 28 | CA
'AA-00000' | 77699999 | 233099997 | 19 | 19 | CT
'AA-0000' | 7769999 | 23309997 | 18 | 18 | DC
'AAA A00' | 7770799 | 23312397 | 21 | 21 | FL
'AA 00000' | 77099999 | 231299997 | 25 | 25 | IL
'000A' | 9997 | 29991 | 5 | 5 | IN
'000AA' | 99977 | 299931 | 24 | 24 | IN
'000AAA' | 999777 | 2999331 | 26 | 26 | IN,OK
'AAA000' | 777999 | 2333997 | 24 | 24 | IN
'0AA0000' | 9779999 | 29339997 | 12 | 12 | MD
'AAA 0000' | 77709999 | 233129997 | 33 | 3 | MI,OH
'0AA A00' | 9770799 | 29312397 | 1 | 1 | MI
'000-AAA' | 9996777 | 29990331 | 7 | 7 | MN,NM
'00A-000' | 9976999 | 29930997 | 34 | 4 | NV
'000 0000' | 99909999 | 299729997 | 46 | 16 | NH
'A00-AAA' | 7996777 | 23990331 | 27 | 27 | NJ
'AAA-000' | 7776999 | 23330997 | 9 | 9 | NM,PR
'AAA-0000' | 77769999 | 233309997 | 23 | 23 | NY,NC,PA,TX,VA,WI
'000-000' | 9996999 | 29990997 | 15 | 15 | RI
'000 0AA' | 9990977 | 29972931 | 44 | 14 | SC
'A00-00A' | 7996997 | 23990991 | 29 | 29 | TN
'A00 0AA' | 7990977 | 23972931 | 17 | 17 | UT
```
### State encoding
All state patterns are joined together into a single string, with each pattern ending with a lower case letter. Empty slots are filled with an arbitrary `x`.
```
[ [], [ 'MI' ], [ 'AZ', 'GA', 'WA' ], [ 'MI', 'OH' ], ... ] --> 'xMiAZGAWaMIOh...'
```
We split them back into an array of strings with `match(/[A-Z]*./g)` and pick the correct one according to \$f(n)\$.
Finally, the pattern itself is converted to full upper case and split into groups of 2 characters.
[Answer]
# T-SQL, 475 bytes
```
SELECT STUFF(value,1,8,'')
FROM STRING_SPLIT('000 0000NH|000 055 SC|000 555 AR,KS,KY,LA,ND,OR|0000 AS|000-000 RI|0005 IN|00055 IN|000555 IN,OK|000-555 MN,NM|005-000 NV|055 500 MI|0550000 MD|0555000 CA|500 055 UT|500-005 TN|500-555 NJ|55 00000IL|55-0000 DC|55-00000CT|555 000 AK,IA,MI,MS,MP,SC,VT|555 0000MI,OH|555 500 FL|555000 IN|555-000 NM,PR|5550000 AZ,GA,WA|555-0000NY,NC,PA,TX,VA,WI','|')
,i WHERE v LIKE TRIM(REPLACE(REPLACE(LEFT(value,8),5,'[A-Z]'),0,'[0-9]'))
```
Line breaks are for readability only.
Limited to SQL 2017 or higher by use of the `TRIM` function. SQL 2016 (required for `STRING_SPLIT`), is possibly by substituting `RTRIM` at the cost of 1 byte.
Input is taken via pre-existing table \$i\$ with varchar field \$v\$, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341)
I'm basically doing a reverse `LIKE` match: I expand the pattern of each plate to a full [wildcard pattern matching string](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/wildcard-character-s-to-match-transact-sql?view=sql-server-2017) like `'[A-Z][0-9][0-9] [0-9][A-Z][A-Z]'`, then compare to the input value, and return the matching states (which is combined into a single field).
Might be able to save some more space by GZIP'ing the lengthy string; I'll see if that helps...
[Answer]
# [Perl 5](https://www.perl.org/) `(-p)`, 165 bytes
Port of @Arnauld's Javascript answer, also upvote him.
```
y/0-8/9/;y/- A-Z/607/;$_=('xMiAZGAWaMIOhNvInxMNNmARKSKYLANDOrNMPrAKIAMIMSMPSCVtAsMdxScRiNhUtDcCtxFlxNYNCPATXVAWiInIlINOkNjCaTn'=~/[A-Z]*./g)[$_*3%47%30];s/../\U$& /g
```
[Try it online!](https://tio.run/##Lc1Bb4IwGIDhu7@iB5ybSfmQ6tAQD98wMw22EBAdOmOMW5SNIQGy1Mt@@qomHt48x7f8rPKB1mew6BBG4J6BEqQreLYccI3t@LGjRIarKS53ggdH@csLJaT8wciP/XSGchJUUoQV@hwFF7EIY2/RYC0@VLyPMnlMmsnea9RrrmQqvRDnbwtcZrzgOZfBt/zydvOiM/6D9fW66ZpweFob2y5r9502szZuDaYJ74nxQOCg9QuzyQinrV6aeBZzWvZwQGZBdJPevdGzGbnW/z@VTXYqak3L/AI "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 177 bytes
```
§⪪”}∧▶⧴βμÞ∕×peH✂d‽n➙MR⁶↙↷◨5⁶;πNM﹪θW:¡✂⧴O^(P↷kⅉχR⁺≔º↶∨§º⊞B⎚×p↔L\`²‖6'⁶⁹‴XüR⦃N4U⊙YF⁻ZMχLS⁸CX\hγ”;⌕⪪”{⊟“◨⦄»U>⌕⁻9“]±R▷Q↔θü&$▷l⁹Z⁼¡⁷×À›¶aA*βZ³δ¡⟲²Y«№⌕TμN»πX·SΣ"εl⊙=3✂S?K”;⭆S⎇№αιA⎇Σι⁰ι
```
[Try it online!](https://tio.run/##TZFda4MwFIbv9yuCVxkcIQwGg3N1SOmaaaIY1667k7ZsgrMiOrZf75Jou4Ykz3u@8sE5fFb94Vw105T3dTtwGlR7PP1w2zX1wCOzQSuRCkgsJHtICcwKsgILhdqA0UgWlZknZAmaLWoXWqEkLA2aF3wtcSVRlqhSn2Y05AWaPRgJOUH5BluCnUJKQBFoBdqCzsFK2JbuKMg2uE6R3uHZpRFGwCKM7oGt6/Z4eaQQgrklMAiiQJoZL/54sYMRFC27B81pRIxmisX2AikcQ4E@n5ZrKJSJC71gF0EL4hsGwW44C7oWiOv37OC68aGrjqu2G4fZ5C5Qnvq26n@5PI@uWxWw2jkjiv4jdvzi3il8LAycpjQr2MPT490Ufzd/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
⎇ If
ι Current character
№α Is an uppercase letter
A Then literal string `A`
⎇ Else if
ι Current character
Σ Is non-zero
⁰ Then digit `0`
ι Else original character
⌕ Find index in
”...” Compressed string of plates
⪪ ; Split on semicolons
§ Index into
”...” Compressed string of states
⪪ ; Split on semicolons
Implicitly print
```
[Try all test cases!](https://tio.run/##TZFva4MwEMa/SvCVgxOylrGNe3VLaZtpohjbrSt9IW3ZBGeL2LF9emei/ROMz@9yTy4Jt/3K6@0hL9s2qYuq8VV@9GV1PDX@HTBqZLXb//rmWBaN7@k5GoGUQmggXEFEoCcQp5hKVBq0QjIodf9BHKJeoupSExSEmUb9iosMJwJFhjKyNq0gSVGvQAtICLJ3WBK8SaQQJIGSoAyoBIyAZdaVgniO0wjpA2adjdAD5qHX3XNaVLvzJTnnrJscHRA5pV6DYT0YYhc4ouFvhXobEaNe@RBbQHJlyKn103AMuW38rBbYGWiQ4EYdsBvtgS4b@OV5pula82k7UwDL9nWV13@@OJy6duXAys7hkXfNmNO3bxe5zfUD23a99l7GI/ZMM1v3frUQfPxocfT0wKI4HTC4oqXNpg1@yn8 "Charcoal – Try It Online") Link is to verbose version of code. (Slightly different code needed to process multiple cases.)
Unsurprisingly a port of @Arnauld's solution is much shorter at only 121 bytes:
```
§⪪”}∧↨¦↑↧‴q⁰mπi3JE⪫³yS⪪c)?0≦·ê⊞Þ«ⅉ⁺&±<pARιaγ1A↑1L¶⟧/)Vº;Π∧,b✂≦¤ⅉαX⊕|″IνB[w∕¦H´Gγ§ν⟲^π!⪪¶ςbFü⊟»2”;﹪׳I⭆S⎇№αι⁷⎇⁼ι ⁰⎇⁼ι-⁶9⁴⁷
```
[Try it online!](https://tio.run/##bU9NT4QwEL37KxpOJZlNjF@reaemGLdCC6EVXW/NLlEShJUFo78eix68OIfJm/dm5uXtXv2w6307z8XQdCMXo@r29Se3h7YZeQStIJ7pTtCjCJjyDUwFZQBtyGiIklJL6ZYyQSahvITRVJQQKSlB4UBb0gVZSZWDsNAJYCVKBbPBg0MiIR2QZIDZkpFUCHJPVAU/tdioLHTKU5h7SAFnImIRopiY7vdT23PXvNVHfk5M@uPI7RhCvGh/4Ko7TOPvyMO2q4fOD19c9lMI6Yk1gVz/8bfvk2@PvAnf2fL99F9ptUhXAdxE8U8Ru1jHMeY5y0t2dn15Mq8@2m8 "Charcoal – Try It Online") Link is to verbose version of code. The second modulo by 30 is implicit in the indexing into the array.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~382~~ 378 bytes
```
import re;f=lambda p,l='[A-Z]',r=re.sub,f=re.findall:f(l+'{2}',f(r(l,'1',r('[0-9]','0',p))+l+'+','0000AS0001IN00011IN000111INOK111000IN000 011SC000 111ARKSKYLANDOR000-000RI000-111MNNM001-000NV011 100MI0110000MD0111000CA100-001TN100-111NJ11-0000DC111 100FL111 000AKIAMIMSMPSCVT111-000NMPR1110000AZGAWA11 00000IL11-00000CT111 0000MIOH111-0000NYNCPATXVAWI1100 011UT000 0000NH')[0])
```
[Try it online!](https://tio.run/##VVBfb5swEH/vp/DbgUIqk2jqmomHG1lbCjYISNoU5YE2oEWiKXJcadPUz56eTbItSNydf/840//WP99208Nh@9q/Kc1U860Nuvr1eVOz3usCqHD8tAZPBaq53L8/e60Z2u1uU3fdrHW6EfyZfIDXOsrpPPBJ6UDFx9fkAQ5e77oj0ozMiR4sqPiRNPXUqKcxNTpYhBFWhGYgEPO4iFcJynmaEzSmN4/MQJyQUlCAweSSTIwiRMRtEhdzPmSG6FufX0p/8Ml735r4PPQH101iBrNfHKGIRCGyIlyW/qCTIsuHLI5Pt/iAg5bWTY5BPCyPAbRAenf0cbmSYYbl4xIfIuM3N1uU9oqGvQO34mv3sGlappu9dnqPKXd2wVivtjvtVHCDUQIegwyLAtbVvtGOclkQMDO1Dv3ctftXDoxlXa0bNiNLf4b/@NU3L9rg6gzHF/1edwa3YURd2EXg@3TCrvGWiAoWJdBXBtxfLUI@vbJ4iP/wydcvLElzi6NpEBe2rkxN0FQ5N5VE/7vGJ5eQViPO2BMZWTKNiTx8Ag "Python 3 – Try It Online")
Replaces numbers with `0` and letters with `1`, then searches the string for the plate followed by a string of letters. Then it simply returns every non-overlapping pair of letters in that string.
Not the most byte efficient, but a good start (maybe).
I enjoy challenges based on information that can't just be generated.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 176 bytes
```
•1–ºʒÉQ÷¦PαN]lā?¨ìÎ₆™@ΔîÅλEŸʒ»ú<ŧa–½ã…ôkƒ¼½Ü%-ò∊aÍÙ•44374в4вε©gIgQi…'-Q'd'a„ðQ)VIεY®Nèè.V}Pë0].•=#îYn«ÈO4êʒIWj∊bÛˆ_ãZÑ"yŠótм‰иÔN–HδÖc°ìSJ9Ç\}ζÎäǝÑïÒ∞V.÷ζkÚ"¿Õнα£!ɪB…žä•#sÏ`2ô
```
[Try it online!](https://tio.run/##FY5bSwJRAIR/S0pID0rWQgRFEQXZg7oFhpHUWiFm1IO99CBskaZChpsF3SRcMVMxNW94KTiTBQaH/Q3nj2wnmJeBmW/mKCh5/Xu6zuSMlcnXpDNUEBPRIjknrdo9B1@ncySPEhLsLMLOM/M0hTLCtLs0aA8V0kVnBmHyIv1X@1CZnEM98K2QHnePo2bUWDQu4RJ3nC8Ik1OCVuOiDfLqs/lEP8@bzKJp18QBaVTEMZeNNtykbEceeYsr5ERx3GPh3Vkjyu5DUkTUIaAwVGzr@5zsxcNvZAvqBpKGk8Ez3o@1HpMrWhspO3@0TOu43SEVlNZWpnGxGaJNJJD9eUISb1BYNO2yoEWbAdwbyCdutD6tEnUEMVJY4M8GH8jyaWMQV9sTqOv6omPVbBWswh8 "05AB1E – Try It Online")
```
•1–ºʒÉQ÷¦PαN]lā?¨ìÎ₆™@ΔîÅλEŸʒ»ú<ŧa–½ã…ôkƒ¼½Ü%-ò∊aÍÙ•44374в4в
push all patterns as base 4 integers (0="-", 1=number, 2=letter, 3=" ")
ε for each pattern
© copy it for later use inside another for for-loop
gIgQi if it has the same length, as input
…'-Q'd'a„ðQ)V store ["'-Q", "d", "a", "ðQ"] in Y (05AB1E codes for "equals '-', is positive, is letter and equals ' ')
Iε for each letter of input
Y®Nèè get the 05AB1E code corresponding to the current index of the pattern
.V run it
}
P check if all positions of that pattern were true
ë else
0 push false
]
.•=#îYn«ÈO4êʒIWj∊bÛˆ_ãZÑ"yŠótм‰иÔN–HδÖc°ìSJ9Ç\}ζÎäǝÑïÒ∞V.÷ζkÚ"¿Õнα£!ɪB…žä•#
push list of states matching the pattern
sÏ get the entry of that list, that is true in the other list
`2ô split into groups of 2 letters and print
```
] |
[Question]
[
We can represent a [Rubik's Cube](https://en.wikipedia.org/wiki/Rubik%27s_Cube) as a net as follows (when solved):
```
WWW
WWW
WWW
GGGRRRBBBOOO
GGGRRRBBBOOO
GGGRRRBBBOOO
YYY
YYY
YYY
```
Each letter represents the corresponding colour (`W` is white, `G` green etc.)
It [has been shown](https://en.wikipedia.org/wiki/Rubik%27s_Cube#Mathematics) that there are exactly \$43,252,003,274,489,856,000\$ (~\$43\$ quintillion) different permutations that a Rubik's Cube can be in.
Your task is to take an integer between \$1\$ and \$43,252,003,274,489,856,000\$ and output the corresponding permutation, in the manner shown above. You may choose how the permutations are ordered, but the algorithm you use must be shown to generate a unique, and correct, permutation for each possible input.
**Invalid permutation rules**
Taken from [this](https://ruwix.com/the-rubiks-cube/unsolvable-rubiks-cube-invalid-scramble/) page
To start with, the centre of each 3x3 face must stay the same, as the centre square on a Rubik's Cube cannot be rotated. The entire cube can be rotated, changing where a face appears to be, but this doesn't affect the net of the cube.
If we say each permutation has a parity, based on the parity of the number of swaps to reach that permutation, we can say
* Each corner piece has three possible orientations. It can be oriented correctly (0), clockwise (1) or counterclockwise (2). The sum of corner orientations always remain divisible by 3
* Each legal rotation on the Rubik's Cube always flips an even number of edges so there can't be only one piece oriented wrong.
* Considering the permutation of all the corners and edges, the overall parity must be even which means that each legal move always performs the equivalent of an even number of swaps (ignoring orientation)
For example the following three net are invalid outputs:
```
WWW
WWW
WWW
GGGWWWBBBOOO
GGGRRRBBBOOO
GGGRRRBBBOOO
YYY
YYY
YYY
(Too many whites/not enough reds)
WRW
WRW
WRW
GGGRWRBBBOOO
GGGWRRBBBOOO
YYGRWROOOBBB
YYY
GGY
YYY
(There are two red/green center squares and no white/yellow center squares.
In all valid permutations, the center squares are all different colours)
WWW
WWW
WWW
GGGRRRBBBOOO
GGGRRRBBBOOO
GGGRRRBBOYOO
YYY
YYY
YYB
(The yellow/orange/blue corner is rotated into an impossible permutation)
```
## Rules
* You must prove, however way you wish, that the algorithm is valid. You do not have to enumerate every single permutation, as long as you prove the validity of your algorithm.
* As long as your program will work *theoretically* for all integers between \$1\$ and \$43,252,003,274,489,856,000\$, you don't have to worry about the practicalities of actually taking in inputs greater than your language can handle
+ This means that, if your language/type/whatever can only handle numbers up to \$2^{53}-1\$, the *program* itself can fail if the input is greater than \$2^{53}-1\$, but the algorithm that you use should not.
+ For example, if your Javascript program fails for an input of \$27,946,105,037,114,827,095\$ purely because that number is out of bounds, that's fine. However, if your algorithm were ported to a language with arbitrary sized integers and failed for that input, your program would not be valid.
* You *must* include some sort of proof of validity in your answer. This proof can prove the validity in any accepted proof method, except for enumerating all possibilities.
* You may choose to use an alternate input method if you wish, so long as:
+ The input is bounded
+ Each input corresponds to a unique output
+ You clearly explain the input format and how it corresponds to each output
* You may change the characters used to use 6 different ASCII characters, between 33 (`!`) and 126 (`~`), instead of `WGRBOY`
* You may output in any manner you wish, so long as it forms a clear representation of a cube where all 6 faces are able to be shown, including any valid cube net, a single lined string or a 3D rendering. If you are unsure about a specific format, don't hesitate to ask in the comments.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code, in bytes, in each language wins.
## Example valid outputs
```
YYY
YYY
YYY
GGGRRRBBBOOO
GGGRRRBBBOOO
GGGRRRBBBOOO
WWW
WWW
WWW
(The `W` and `Y` faces have been swapped)
ZZZ
+++
+}}
+[[}77ZZ7bbb
bb[}[[7}}+Z7
bb[}++[}}+Z7
7bb
[7Z
[7Z
(To start with, the colours have been mapped W -> +, G -> b, R -> [, B -> }, O -> Z and Y -> 7.
Then, the moves L, R, U and F' have been applied, in that order.
Notice that each centre square is different, and corresponds to the same colour as in the mapping)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~334~~ 297 bytes
```
Nθ≔׳﹪θ²¹⁸⁷ε≧⁺﹪±Σ⍘峦³ε≧÷²¹⁸⁷θ≔⁴⁰³²⁰δ≔﹪θδζ≧÷δθ≔⊗﹪θ²⁰⁴⁸η≧⁺﹪Σ⍘粦²η≧÷²⁰⁴⁸θF⪪”B"↷:μêKO″KW#})”³«J⌕α§ι⁰I§ι¹§ι²»≔⁰ω≔⪪”A‽}y≔W⊞≦≦⧴!O×➙⟧ï!Y9⁺`↙1δQ1ξzT”⁶υ≔⪪”{➙∧⊙ηr⸿ξd⊕÷M→¡$≧”³δF²«Fδ«≔§υ⎇⁼Lυ⊗ιωζδ≧÷Lυζ≧⁺⌕υδω≔Φυ¬⁼λδυFLκ«J⌕α§δ⊗⁺λεI§δ⊕⊗⁺λε§κλ»≧÷Lκε»≔⪪”A‽}R›K<≡^μ≡⟦σD⎚+πη±t¿e∧L⸿~↑�w”⁴υ≔⪪”{➙∧⊙ηr⸿ξe'→↑Þ³№¹”²δ≔θζ≔ηε
```
[Try it online!](https://tio.run/##jVNdb6JAFH3GX0F8GhI2AWZG2fRJ5EPUSoMmhEcqs0JEUBjabTf@dnf4Wqm1u/sGM@eee@45d7ZRkG@zILlc7PRY0lV5eCY5OAkPg0lRxLsUbOIDKQAU@ccsLJMMnERekdWxIIg8YajH4NgA3XgXUfCUlMUf6IrsAkrAujwALSjImuZxugNE5KFQlcP7FHZK9fglDknTSOR7YpAEFUnkw@vJVVXI6N7/Shd@4NKz8jkhYY9BkZBaCYv@MdfNQBGrrMqU@6X9eViDRsOPLOfB@pjEFAwN5M6QZoz9BXIM2dOQNawt4n8NuHl5OG4yYMZpCAKRn1A7DclPEIu8VLWcBgUFvUOZGfsw4J6Yrg/nSnV87iZnDr5efWhVmNjC5kjH@miKdTiFumJCU7HgEurSBC7xBOvqHJuqjefQhqbENI6YgvITkav5rm@5lud6muNZjuU7vuZo3rBJPOymV@oB68@w/uRank53KfIbkqdB/gaMUxkkBViSdEcjUDKaLr24suG1Sr7l5riv/e/Vv9@DNinXZpfNQr3WsFaYGSeUPQ52tcpopympgELrBNfM0/bZNxlyX6UYXseoOldURBA@5cpgdrrNyYGklEHvltSxczfB70U@aS7O/2PLvn2PFfpmN5CFDGyMdDRFBjSUGTbH@ljDGtRlU57BBTSkJZqgBTbUObIRixp1jtwuh@u7FtsM37csr1oQx3J8Rxs2zyfsVZzakNrfqBF3vlxkVcLfFSgjLKmXby/Jbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the integer into variable `q`.
```
≔׳﹪θ²¹⁸⁷ε≧⁺﹪±Σ⍘峦³ε≧÷²¹⁸⁷θ
```
Divide `q` by 3⁷, putting the remainder in `e`. Then, considering `e` as a number in base 3, suffix a digit to `e` so that its digits (in base 3) add up to a multiple of 3. This allows `e` to define the rotations of the corners.
```
≔⁴⁰³²⁰δ≔﹪θδζ≧÷δθ
```
Divide `q` by 8!, putting the remainder in `z`. (8! is temporarily stored in `d` to save a byte.) This allows `z` to define the positions of the corners.
```
≔⊗﹪θ²⁰⁴⁸η≧⁺﹪Σ⍘粦²η≧÷²⁰⁴⁸θ
```
Divide `q` by 2¹¹, putting the remainder in `h`. Then, considering `h` as a number in base 2, suffix a digit to `h` so that its digits (in base 2) add up to a multiple of 2. This allows `h` to define the flips of the edges.
```
F⪪”B"↷:μêKO″KW#})”³
```
Loop over a string representation of the centres.
```
«J⌕α§ι⁰I§ι¹§ι²»
```
Jump to the position of each centre and print it.
```
≔⁰ω
```
Keep track of the parity of the corner positions in variable `w`.
```
≔⪪”A‽}y≔W⊞≦≦⧴!O×➙⟧ï!Y9⁺`↙1δQ1ξzT”⁶υ
```
Create an array of corner positions.
```
≔⪪”{➙∧⊙ηr⸿ξd⊕÷M→¡$≧”³δ
```
Create an array of corner colours.
```
F²«
```
Loop twice, once for corners, once for edges, hereinafter referred to as "cubes".
```
Fδ«
```
Loop over the array of cube colours.
```
≔§υ⎇⁼Lυ⊗ιωζδ≧÷Lυζ≧⁺⌕υδω≔Φυ¬⁼λδυ
```
Extract the next cube position from `z`, updating the parity in `w`. Use this parity for the last but one edge. This ensures that the sum of parity of the edges and corners is even.
```
FLκ«J⌕α§δ⊗⁺λεI§δ⊕⊗⁺λε§κλ»
```
Print the cube at that position, adjusted for the next rotation or flip as appropriate.
```
≧÷Lκε»
```
Remove the rotation or flip from `e`.
```
≔⪪”A‽}R›K<≡^μ≡⟦σD⎚+πη±t¿e∧L⸿~↑�w”⁴υ
```
Create an array of edge positions. This will be used the second time through the loop.
```
≔⪪”{➙∧⊙ηr⸿ξe'→↑Þ³№¹”²δ
```
Create an array of edge colours.
```
≔θζ≔ηε
```
Overwrite the corner variables `z` and `e` with the corresponding edge variables `q` and `h` so that the edges are permuted and flipped during the second pass of the loop.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~570~~ 408 bytes
```
->g,h{z=[]
c=a="\x19)!$'%\x177\x1F495.)@7g~yp"
20.times{|i|z<<a[k=g%r=12+i/12*8-i];a[k]="";g/=r}
19.times{|i|z[0..i].map{|j|j>z[i+1]&&c=!c}}
c||(z[19],z[18]=z[18,2])
h+=h+("%b"%(h%2048)).sum%2
j=0
b="023451"
20.times{|i|b<<("%0*o"%[r=2+i/12,z[i].ord-20]*2)[h%r+i/19*j%3,r];j-=r/3*h;h/=r}
s=(t="...
"*3)+(?.*12+$/)*3+t
54.times{|i|s["<QTWZo;MP[ngD@RS^k=GVUpaJ8XYdsAFE?CN7LK9IHl_`jh]reftbc"[i].ord-55]=b[i]}
s}
```
[Try it online!](https://tio.run/##xVRrd5s4EP3Or1BpqQ0mWBI4htrq47Rut9tt0nXTJ8u2gGUjByNX4LZOnP3rqYDYm7huunvOnrN8GBhp7tyrmRFiES3Px@R87@7ETE5PiB8oMQmJ@sdX5Ok3bjU0@dHtSvPY8TqWfr87@Ws5VxUMrYLNaH66YquTfj/0j8lEEwThFmsjbLh7LOjJxYCoam/SJuJMQd4lhA8tiwXWLJyfrqar6d0Tn7VQcPt2TG7EZ2dKvFo1T3zkBaa0bkBKa@JAV5IWSVpNVYtUrZloGDqurlv5YqZhZUqgEhEVYtvpoKsCo35fYqDBVc0XpJYoM0sBXIz2MAwMrPuJJsoNz5hqtimC3nSPiLZtJL2kkp@TZkFUy7IU1bD1VvOeZcjD3mrrht0qlI7zN1vuq/3fj968573nL/xs8uj@8OWfx@TJ61fz8Ff37btR/uDx4N7Dg@5vz7ynv6QfPk6TQNBxEcXqWlGnE5BIOpL17Hy@KHLQGDx6MgAvBsPnr44eHD09PHgJmhkv6B0QZksgaM5GizAF81CwYglYDqIwDbOYjkC0BPmXcD5n2QQUCQVpmBcAg5iLjIocIBeoyOmoMs8IIE86tqPqDaCUtJUBYx@ZMAA3yzSAjiY0B7AONwEfjS5IrwBwBZjxz7QCSL6Cg4hOWJZJHSagn2m2C@d0PQjRPoRtvE2JLjh3kNboxsPD4cFg@P8VydioL7VfiN@kwDXY/nHNtvFV@Wo8QM6/raDhGl1j3@gYjoHqfIIXYXFxNnsjrLlmcAHLNnRdME/DmJplNbLyyJUrC0XHXNByX74vi9B/qgL/IxXeDhW6oqx7XF2D4eF17a0IGM@2G7xZ5@Oqx2MmpIRqPKEJVNhRtxoKTSRHcJyyegQB@m4bYqc80qUQtBUCkXzWWcI0BfTTIiy4YFJoPddNHhfSyRaziAp9G47ls6Eo8REvCj67Bnv1Mvw3paqatemQWc9/Y7saRvk7LsWuI8uRL1ic8vj4C8vpVjzeEf@jWPf75PvXJnftnwFMsIv2/Bs "Ruby – Try It Online")
**Original version, with arrays of magic numbers instead of magic strings**
```
->g,h{z=[]
a=[05,025,015,020,023,021,03,043,013,040,045,041, 032,025,054,043,0123,0152,0145,0134]
#PERMUTE
20.times{|i|r=12+i/12*8-i;z<<a.delete_at(g%r);g/=r}
c=1
19.times{|i|z[0..i].map{|j|j>z[i+1]&&c=!c}}
c||(z[19],z[18]=z[18],z[19])
#ROTATE
h+=h+(h%2048).to_s(2).sum%2
j=0
b="023451"
20.times{|i|r=2+i/12;b<<("%0*o"%[r,z[i]]*2)[h%r+i/19*j%3,r];j-=r/3*h;h/=r}
#DISPLAY
s=(t="...
"*3)+(?.*12+$/)*3+t
54.times{|i|s[
[5,26,29,32,35,56,
4,22,25,36,55,48,
13,9,27,28,39,52,
6,16,31,30,57,42,
19,1,33,34,45,60,
10,15,14,8,12,23,0,21,20,2,18,17,
53,40,41,51,49,38,59,46,47,61,43,44][i]]=b[i]}
s}
```
[Try it online!](https://tio.run/##xVRhb9s2EP3OX8EpcyPJF5mkKFmaoxbBagwF1qZIsw@DIBSyTdvMbMmT5BZxnN@eniTHbV2n3YABE0ASPN67e7x3VLEe3T5Mo4ez5zOY322iOCFpFDMPmMDB65XhcHFwYLhIHLxe0SzxWHKglDJXtAhP7lxqCPfQymsv7sqEnLwdXr3@43pIBHMqvVTl3VZvi4iLru5xYQdnerA5P0@diVqoSr1PK3PWKazBrBcV92QcccLDz7hNzBxHJ84yXd1tb7Y3zzex7vLk2bNx9NP4Hv23W3MT8zABnIMkamZoLBY5ubq8vkAi824075rzjmAysJwqf1@awnLK9bIjyE3EyCgy8O7S48YB55byYHR@bhodZudGJy4wuE4SW1jxvFPU56F903GhSAY3Z1HRc@35YN5c5eTlq3dvf7/4k5SRWUWG4zjEsF2ra75wbCzGzz3LdrsV8eTnjGVMYg@EDyIELLXrgecDkSAEYNVdHzwPZACUoDQhiD6IANwQsP7EB@6Dy8Fl4PVBooWHgFsXXAmojc/QwgCl5hIC4BgRpQOUG5UXwNHUB@K5gIqj2B4HiRwC8EKQPsg@@GjBU5nU149GON@T8v5hta5Kejp8@duQtrpfXL@6fPOOmlleqV9omt3SQpV6sk4XdJUWurqluqSjdJFmYzWho1tafkxXK53NaDVXdJGWFRV0nBeZKkrKA2pgZxkYZ0J5iBtXGtYpJXXaZqLTGDs2oSd1GKomM1VS1roDzSeTXdKvAKIBLPMPqgFgviqnIzXTWYY8gKoPKjuGk/2QMe4z1hOHKfku55GkLfr018urN8Or/69I9p59zX1Hfh9CtGD36Zod4pvytXjK5b@toB3Yfdu3PVvavI1X5FVa7e7m7omZjxkCqrN9uj5dLdKxgroaWX3lZouFUtO8UPU5rl@SsH7IQvwjFuERFhYhjxo3z6D56Twpb5NA59mhwHt7Pm00nuoCKTTtyYAazDMOBMW3jC04Xei2BSn/5pgJWV/pCxd@4MI4fo9R0sWCqr/XaZUXGom2fW3m4wo32Xo5UoV1CBf47VPU@FFeVfnyO9ivH8N/U6pGrL1C0Pb/6WE17PrvX5N99KxbvtLjRT7@66Mu1YG/OOL/lG/wbXD/u8ED90cAoMfSPnwC "Ruby – Try It Online")
An anonymous function which in its current form takes an input of two integers, which seems to be allowed: "you may choose an alternate input method." The first is the permutation in the range 0 to `12!*8!/2 - 1` and the second is the orientation of the pieces in the range 0 to `2**11 * 3*7 - 1`. The output in the solved state is the following string:
```
000
000
000
222333444555
222333444555
222333444555
111
111
111
```
**Further golfing**
There are approximately 10 more characters to be saved by adjusting the output format to the following shape. But this would reduce the readability, so I will not be doing it at present
```
#########
#########
#########
#########
#########
#########
```
**Explanation**
**Permutation**
Internally, the solved state is represented by the series of octal numbers in the array `a`. The input `g` is divided by the numbers `12..1` with the modulus being used to pick and remove an edge from `a` and place it in `z`. Once this is done, only the corners remain in `a`, so `g` is divided by the numbers `8..1` with the modulus being used to remove a corner from `a` and place it in `z`.
As there is insufficient info to determine the order of the last two corners, the value of `g` will have been divided down to zero by the time it reaches them, so they will always be added to `z` in there original order. A check is then made to determine if the overall permutation is even or odd, and if necessary the last two corners are swapped to make the permutation even.
**Orientation**
There are various different ways of deciding if a corner or edge is in the correct orientation if it is not in its solved location. For the purpose of this answer, a corner is considered in its correct orientation if it shows `0` or `1` on the top or bottom face. Therefore rotating the top or bottom face does not change the corner orientation. Rotating the other faces does change the orientation, but in such a way that the overall parity sum remains unchanged. The edges are considered in the correct orientation if they show a `2` or `4` to the front / back or a `3` or `5` to the left / right. This means that rotation of the top or bottom by a quarter turn flips the four edges but rotation of the other faces leaves the flip status unchanged.
The input contains explicit information for all but the first edge and the last corner. The 11 least significant bits `h%2048` are summed and the modulus used to determine the orientation of the first edge. `h` is multiplied by 2 by adding it to itself and the value for the orientation of the first edge is added as the least significant bit. The orientation of the last corner is found by progressively subtracting the orientation of the other corners from `j`. For the very last corner (where `i/19` = `1`) the value of `j%3` is added to `h` (which will have been reduced to zero) and this determines the orientation of the last corner.
The string `b` comes preinitialized with the text for the centres of the faces. `h` is divided by `2` twelve times then by `3` eight times, with the modulos being used to determine the orientation of the pieces. In each case, the number in `z` is converted to a string with the appropriate number of digits (2 or 3) and the string is then duplicated. This allows the correct rotation of the digits as found by the modulo to be extracted from the string by indexing and appended to `b`
**Display**
Finally, the raw stickers are copied from `b` into a more human readable format in `s` using the magic numbers in the index table.
] |
[Question]
[
Consider the infinite matrix:
```
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 2 3 0 0 2 3 0 0 2 3 0 0 2 3
0 0 0 4 5 6 0 0 0 4 5 6 0 0 0 4 ...
0 0 0 0 7 8 9 10 0 0 0 0 7 8 9 10
0 0 0 0 0 11 12 13 14 15 0 0 0 0 0 11
...
```
Each new row of the matrix is constructed by starting with `z` zeros, where `z` is the length of positive digits we're using in that row. The positive digits are constructed by starting with `1` and incrementing and adding an additional digit each time you iterate rows. That pattern is repeated infinitely to the right. So, for example, the first row starts `0, 1, 0, 1...` while the second row starts `0,0, 2,3, 0,0, 2,3...`. Following the pattern, the third row starts `0,0,0, 4,5,6, 0,0,0, 4,5,6...`.
Given two integers as input, `n` and `x`, output the first (top-most) `x` numbers of the `n`th column of the above matrix. (You can choose 0- or 1-indexing for the columns, just specify which in your submission.)
For example, for input `n = 0` (0-indexed), the column is entirely `0`s, so the output would just be `x` `0`s.
For input `n = 15` and `x = 6`, the output would be `[1, 3, 4, 10, 11, 0]`.
For input `n = 29` and `x = 15`, the output would be `[1, 0, 6, 8, 15, 0, 0, 34, 39, 0, 0, 0, 0, 0, 120]`.
For input `n = 99` and `x = 25`, the output would be `[1, 3, 4, 0, 15, 0, 0, 0, 37, 55, 56, 0, 87, 93, 0, 0, 151, 163, 176, 0, 0, 0, 0, 0, 325]`.
## I/O and Rules
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* The input and output can be assumed to fit in your language's native number type.
* 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]
# JavaScript (ES6), 45 bytes
Takes input in currying syntax `(n)(x)`.
```
n=>g=x=>x?[...g(x-1),n/x&1&&n%x+x*~-x/2+1]:[]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7dtsLWrsI@Wk9PL12jQtdQUydPv0LNUE0tT7VCu0KrTrdC30jbMNYqOvZ/cn5ecX5Oql5OfrpGmoahqaaGmaZeVn5mnoa6joK6piYXqgIjS02QIjwqLIEqjFBV/AcA "JavaScript (Node.js) – Try It Online")
### How?
We use a direct formula to get the value of the cell at column **n** (0-indexed) and row **x** (1-indexed):
```
n / x & 1 && // is this cell zero or non-zero?
n % x + // column modulo row --> increment for a non-zero value at this position
x * ~-x / 2 + 1 // minimum value of non-zero values for this row:
// ∑(i=1...x-1)(i) + 1 = x(x - 1) / 2 + 1
```
[Answer]
# [R](https://www.r-project.org/), ~~80~~ 76 bytes
Thanks to @JayCe for pointing out a bug!
```
function(n,x)for(a in 1:x)print(rep(c(rep(0,a),((y=sum(1:a))-a+1):y),,n)[n])
```
[Try it online!](https://tio.run/##HcRBCoAgEAXQq7icTyNo0EbqJNFCJMFFo1iBnt6gt3h1RLXqEV8JT8pCwg0xV/IqibKuodQkD9WzUPg37MFEfbvfi6zzgPaThetgFuxyYESyxvC8YHw "R – Try It Online")
Uses 1-based indexing for `n`. Very likely a golfier algorithm exists but `rep` is the enabler for the naive solution.
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
n,x=input()
a=i=1
exec"print(([0]*i+range(a,a+i))*n)[n];a+=i;i+=1;"*x
```
[Try it online!](https://tio.run/##BcExCsAgDADAvc9wMupQhQ4ieYk4hCJtllTEgn29vWvfuB8Ja4mbyNLeoWEjZPRbnfVUrbMMrfNeDNtOclVNjiwDGIEsJZFFTmzRJ2XmWjG6cPw "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~27~~ ~~24~~ 23 bytes
-1 thanks to @FrownyFrog
```
⊢∘⍳(<×(+\⊣)--){+\⍵/2}|⊣
```
[Try it online!](https://tio.run/##TUw7CsJAEO1ziukSkeDsrpu44lFsghIJBiJqI5pKET9EbERb9QhqY@tN5iJxElHkwfDm/YJB7HYnQZz03E4cjEZRJ6fdIUpoucc85EubC61OlN2c1uvoVNu0uVZctzJllj1qMp2xkOdjTk5ZoPV5WJbmYY2yZ9NO@jZtF3YYRLHNAkeGqYUgEGDMl7I7WkKDV76goF5YQgBa0gAbhYpsN4oHGaoOypTsAyHRMgak/g3gN8phH7QG7TFt@GDUp6EFCE@B8L2/HSX1Gw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~25~~ 18 bytes
```
x:"@:t~ys:b@-)h1G)
```
[Try it online!](https://tio.run/##y00syfn/v8JKycGqpK6y2CrJQVczw9Bd8/9/QzMuMwA "MATL – Try It Online")
*Thanks to Luis Mendo for golfing out 6 bytes!*
This is essentially a MATL port of my R answer.
```
x % implicit input, read n and delete
: % implicit input, read x and push [1..x]
" % for loop with i = 1..x
@: % push [1..i]
t % duplicate
~ % logical negate, turn to array of zeros
% stack: [[1..i], [0 .. (i times)]]
y % duplicate from below
% stack: [[1..i], [0 .. (i times)], [1..i]]
s: % sum and range
% stack: [[1..i], [0 .. (i times)], [1..(i * (i + 1)/2)]]
b % bubble up
% stack: [[0 .. (i times)], [1..(i * (i + 1)/2)], [1..i]]
@- % push i and subtract. This will be used as a modular index to get the last i elements
% stack: [[0 .. (i times)], [1..(i * (i + 1)/2)], [1-i..0]]
) % index into array modularly to get the last i elements
% stack: [[0 .. (i times)], [(i-1)*i/2 + 1, .. (i * (i + 1)/2)]]
h % horizontally concatenate the array
1G) % push n and index modularly, leaving the result on the stack
% implicit end of for loop. The stack now contains the appropriate elements in order
% implicit end. Print stack contents
```
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), ~~33~~ 31 bytes
```
{(a>i)*(+\i)-i-a:(2*1+i:!y)!'x}
```
[Try it online!](https://tio.run/##TYzLCoMwEEX3/YoRSmsUIZOYaDLQH7GCbizBYkFc@MD@ug3aQpnNuTNnbpt0j27bGruE9c2xKIzvjiUuqW0oIoydDSYWXMd1G@xyLuZ3b5tipKmk6tVSWDW1e5LPNFPPyvU0FJyQ0wV56RkVaUKQkAJyQIR9Kwz5gw@gIQdUHjjIFKTZ6RgUu2sMCfWt4D/X2xkoBUp7zDMw8nhRCKglYKb/iqRQ5fYB "K (ngn/k) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
↑!Tzo¢+MRN0CNN
```
The argument `n` (first) is 1-indexed, [try it online!](https://tio.run/##yygtzv7//1HbRMWQqvxDi7R9g/wMnP38/v//b2j23wwA "Husk – Try It Online")
Alternatively we could use [`↑!TṠzo¢+†K0CNN`](https://tio.run/##ASIA3f9odXNr///ihpEhVOG5oHpvwqIr4oCgSzBDTk7///8xNv82 "Husk – Try It Online") for the same number of bytes.
### Explanation
```
↑!Tz(¢+)MRN0CNN -- example inputs n=4, x=3
C N -- cut the natural numbers: [1,2,3,4,…]
N -- | using the natural numbers
-- : [[1],[2,3],[4,5,6],[7,8,9,10],…]
M N -- map over the naturals
R 0 -- | replicate 0 that many times
-- : [[0],[0,0],[0,0,0],[0,0,0,0],…]
z( ) -- zip these two lists
+ -- | concatenate
¢ -- | cycle
-- : [[0,1,0,1,…],[0,0,2,3,0,0,2,3,…],…]
T -- transpose: [[0,0,0,0,…],[1,0,0,0,…],[0,1,0,0,…],[1,3,4,0,…],…]
! -- index into that list using n: [1,3,4,0,…]
↑ -- take x: [1,3,4]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~21~~ 19 bytes
```
↑mȯ!⁰¢§+`R0§…ȯ→Σ←ΣN
```
Takes arguments as `n` (1-indexed), then `x`.
Saved 2 bytes thanks to BMO, but still not as short as BMO's answer.
My first attempt at using Husk.
[Try it online!](https://tio.run/##ATEAzv9odXNr///ihpFtyK8h4oGwwqLCpytgUjDCp@KApsiv4oaSzqPihpDOo07///8xNv82)
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
```
u!v=take v[cycle((0<$l)++l)!!u|n<-[1..],l<-[take n$drop(sum[1..n-1])[1..]]]
```
[Try it online!](https://tio.run/##HY3fCoIwHEZf5Sd4sWGODLpQpjd12xPYiOFGDfePbRpB777Mu8P5DnwvHmepdVbGu5DgyhMnN2edEoAA0QEDzkux9onPEtZx@kxaInSkpcZVpXFRLF9L67EhhB30BntnSxGcR3Ex/8HWDcN7wVg2XFnowQdlExBAd7R0a/fAUA@w/eDNGe4hSC42fLsgIvSUwlOmi7NJ2hRz28Lp/AM "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
lambda n,x:[n/y%2*(n%y+y*~-y/2+1)for y in range(1,x+1)]
```
[Try it online!](https://tio.run/##ZY1LDoJADIb3nqIbEh410BlnYEw4CbLAKEqiAyEsmI1Xx0qEYEzaxdf@j84N99aKqc5P06N6ni8VWByPhY2dJ0Lfei5y4WvvYhFRULc9OGgs9JW9XX3CkY/l1PWNHaD2SaEO8rwgBIlwQKCElykpd4tGGCT1FfFXI2SsUTPwSHZJs9A6JDYRxqBQPz3JNuKTkiIoPig9Y8Zo5Jql2EeamVL91ySFKqc3 "Python 2 – Try It Online")
Developed independently; but I note that this ends up being a port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s Javascript answer.
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 52 bytes
```
/ /;say+(((0)x$_,($.+=--$_)..$.+$_)x$`)[$`]for 1..$'
```
[Try it online!](https://tio.run/##K0gtyjH9/19fQd@6OLFSW0NDw0CzQiVeR0NFT9tWV1clXlNPD8gE0hUqCZrRKgmxaflFCoZAQfX//40sFQxN/@UXlGTm5xX/1/U11TMwNPivmwcA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ṖS+R¬;$)⁹ịⱮ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//4bmWUytSwqw7JCnigbnhu4visa7///82/zE2 "Jelly – Try It Online")
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Argument 1: **x**
Argument 2: **n + 1**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
LO©LsL£¹£¹LÅ0s)øε˜®Ì∍}ø¹è
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fx//QSp9in0OLD@0EYZ/DrQbFmod3nNt6es6hdYd7HnX01h7ecWjn4RX//xtZchmaAgA "05AB1E – Try It Online")
---
05AB1E goes with matrices like toothpaste and orange juice, but not a bad byte-count considered how bad my implementation is. Even my code is laughing at me "`LO©L`".
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
IE…·¹N§⁺Eι⁰EιL⊞Oυωη
```
[Try it online!](https://tio.run/##LYtBCsIwEEX3niLLCUSwC924ElcBq8EbjHFoCnEakkn19rEVV@/z@M8HzH7C2JrLIwucsQj0mMCyj7WMM92RB4LOKMupyrW@HpRBa6NOYvlJH3DL75eMRu0W/58X4kECuFrCLVFGmTJUo95ar3FYcWztsOn2bTvHLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
¹ Literal 1
N First input (`x`) as a number
…· Inclusive range
E Map (value `i`, 0-indexed counter `k`)
ι Current value
E Map over implicit range
⁰ Literal 0 (i.e. create array of `i` zeros)
ι Current value
E Map over implicit range
ω Arbitrary variable
υ Predefined array
⊞O Push
L Length
⁺ Concatenate arrays
§ η Index by second input (`n`)
I Cast to string and implicitly print on separate lines
```
The snippet `EιL⊞Oυω` generates the next `i` integers by the expedient of pushing a dummy value to an array each pass through the loop and taking the length of the resulting array.
[Answer]
# Java 8, ~~65~~ ~~63~~ 60 bytes
```
n->x->{for(;x>0;)System.out.println(n/x%2*(n%x+x*--x/2+1));}
```
`n` is 0-indexed, `x` is 1-indexed, outputs the numbers new-line delimited and reversed.
Port of [*@Arnauld's JavaScript (ES6) answer*](https://codegolf.stackexchange.com/a/164909/52210).
[Try it online.](https://tio.run/##bY9Ba8MwDIXv@xW6FOzWcZtACyFrLoXBDjv1OHbwUqc4SxQTK8Wl5Ldn7pqxDgpGWNLjvU@VOqmoOnyNRa2cgzdl8PIE4EiRKaAKW9mTqWXZY0GmRfkyfZ5fkfRRd@KRaNei6xvd/YryHErYjhjlPsovZduxzOerjO/PjnQj256k7QxSjQyXfpbMGc78ws@jyC@TRcx5NoxZwArP9p91IJsAT605QBOg2Z6CwfH9AxS/HgBA2hFbiTXP/tp4LTb3fZKK@J8gTUVyGwy3uPucH0WgBBTX6qegUipr6zNDLlVRaEvMT5YPzpu8h/Eb)
A pretty-printed result in correct order is ~~8~~ 6 bytes longer: [Try it online.](https://tio.run/##jU/BaoNAEL33KwYhsBvXTRQSkK0eCz30lGPpYZtoWGtGWUfZEPx2u6lC01thGN6becx7U@lBR9XpazrWuuvgTRu8PQF0pMkcofJb2ZOpZdnjkUyD8mUBz69Ixbmw4n@iA1mD5zyHErIJo9xF@W3QFmwWBKpsLFMu3ypuM9y4VbJmuHKhW0eR2yRhzMMAgtAqW1BvEawaJ@VD@mr7z9rnXOIOjTnBxb/AZrv3D9D8/g4AFR2xrdhx9Uvjndg/8iQV8R9BmopkHoyz3aPPj8IgAYp7d4vR4dpRcZFNT7L1GahGVkrdtvWVIV@A48vRcfoG)
[Answer]
## Haskell, 67 bytes
```
i#l=cycle((++)=<<(0<$)$[i..l-1]):l#(l+l-i+1)
n!x=take x$(!!n)<$>1#2
```
[Try it online!](https://tio.run/##TchBC8IgGAbg@37FK34HRTZSMFhofyQ6yBKSfbmoHdavt7rtOT739J4zc2tFcpw@E2eljNExBHUIpOlShoF7e9UnlooN98VY3VWxxTXNGRspIaoOdLbStUcqFRG3pQPwfJW6gmA9BHDclxt/Zf2@xn85374 "Haskell – Try It Online")
```
i#l -- function # builds the infinite matrix
-- input: i and l are lowest and highest+1 non-zero number of
-- the current line
= cycle -- for the current line, repeat infinitely
[i..l-1] -- the non-zero numbers of the line appended
(++)=<<(0<$) -- to a list of 0s with the same length
: -- append next row of the matrix
l#(l+l-i+1) -- which is a recursive call with i and l adjusted
n!x = -- main function
1#2 -- create matrix
(!!n)<$> -- pick nth element of each row
take x -- take the first x numbers thereof
```
] |
[Question]
[
# Problem
Given an input `a` where a is a truthy/falsy value output the exact impossible cube below if truthy and the exact normal cube below if falsey.
Input `truthy`:
```
___________________________________
/ _______________________________ /|
/ / _____________________________/ / |
/ / /| | / / |
/ / / | | / / |
/ / /| | | / / /| |
/ / / | | | / / / | |
/ / / | | | / / /| | |
/ /_/___| | |____________________/ / / | | |
/________| | |_____________________/ / | | |
| _______| | |____________________ | | | | |
| | | | | |___________________| | |__| | |
| | | | |_____________________| | |____| |
| | | / / _____________________| | |_ / /
| | | / / / | | |/ / /
| | | / / / | | | / /
| | |/ / / | | |/ /
| | | / / | | /
| | |/_/_________________________| | /
| |______________________________| | /
|__________________________________|/
```
Input `falsy`:
```
___________________________________
/ _______________________________ /|
/ / _____________________________/ / |
/ / /| | / / |
/ / / | | / / |
/ / /| | | / / /| |
/ / / | | | / / / | |
/ / / | | | / / /| | |
/ /_/___|_|_|____________________/ / / | | |
/__________________________________/ / | | |
| ________________________________ | | | | |
| | | | | |___________________| | |__| | |
| | | | |_____________________| | |____| |
| | | / / _____________________| | |_ / /
| | | / / / | | |/ / /
| | | / / / | | | / /
| | |/ / / | | |/ /
| | | / / | | /
| | |/_/_________________________| | /
| |______________________________| | /
|__________________________________|/
```
# Rules
* Trailing whitespace allowed.
* Trailing newlines allowed.
* truthy/falsey values may be swapped (truthy for real cube and falsey for impossible cube)
* Input style should be specified
* **Shortest code in bytes wins**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~187~~ 166 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“Ė⁸ġṾṗ¢œƝṇRK⁹ṄẸŒÐ¤ɓḂı)ḥṆqƓị¹÷ḄƝṁPʠVW1JĊTc;[¤ÆWŒṠṬ#ʋÆ6ẉ⁷ZḷƊḤƑẹẠGḊ|qi×Ƭ®ÐėƁ1(⁸ṪU¹Bgoƭ<Gḋ×c:ȦṚƇĊ¬e*⁽%ḷݰU’Fs27ǹ⁸?x€15¦€19Y
```
A full program.
[**Try it online!**](https://tio.run/##FY/PSgJRFMb3PYUUQbUxAw2boIgoqE1EJdXChUgUgkibglnMNXFo3JhCU5GhNbkIC1uY90xocO44lG9x7otMd1bn3/f7ON9ZNpe7DALiL0lNsqEeIWBxdPLYk8WONB6xhwP8kcYdtifUGElHI3pUl0ZDC@/sS1NtWjGTobZFrkn8KSGN@3V0CK5W1da7lYx7LYIhgY3Po7rfIDB3tyUDghK5fFQTVXT@6sSL3ucs8VeCcsGv03cFQfSJl0KA7YybB6nYlmftZbRjdEQ5NaoRNAk6U@OKKCfIvZasf0S871vEHf@GXCC3uUnc0gunwvY7@CGqnu2z2Ix6iOBtH2HtJO@/LytNRdiZpd82wYNvehZ2snOSDaaVmdfF7r7Ks3G@sChMBIWuXKjosTi2w5I8DIJg/h8 "Jelly – Try It Online")
### How?
103 bytes are a 101 digit base 250 number, which is a base-8 compression of a possible cube, with trailing spaces added to equalise the row-lengths, without new lines, and without 18 characters from the middle of each row, like this, but without newlines:
```
_________________
/ _____________ /|
/ / ___________/ / |
/ / /| | / / |
/ / / | | / / |
/ / /| | | / / /| |
/ / / | | | / / / | |
/ / / | | | / / /| | |
/ /_/___|_|_|__/ / / | | |
/________________/ / | | |
| ______________ | | | | |
| | | | | |_| | |__| | |
| | | | |___| | |____| |
| | | / / ___| | |_ / /
| | | / / / | | |/ / /
| | | / / / | | | / /
| | |/ / / | | |/ /
| | | / / | | /
| | |/_/_______| | /
| |____________| | /
|________________|/
```
The 8 base-8 digits represent the strings of characters:
```
1 2 3 4 5 6 7 0
" ", "_", "/", " ", "|", "/ / /", "| | |", "_____"
```
So the compression is then like the below where `1`s, `6`s, `7`s and `0`s are to be replaced by the strings shown above:
```
111000__111/ 00___ /|11 / / 00_/ / |116| |11 / / |1 6 | |11/ /1|1 671 6| |16 71 6 | | 6 7167 6___|_|_|__6 7/000_/ / 7| 00____ | | 771 7_7__771 | |___7____| |71/ / ___7_ / / 7 6176 7 61 7 / /1761 7/ /1 7 / /11| |1/1 7/_/0__| | /11| |00__| | /11 |000_|/11
```
The program reverses the process and changes the characters that need changing if the cube should be an impossible one:
```
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“ ... ’Fs27ǹ⁸?x€15¦€19Y Main link: V
...splitting this up...
...Main link part 1:
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ - make the list of strings of characters
“ _/ |/|” - list of characters = " _/ |/|"
⁶ - literal space character
;€ - concatenate €ach -> [" ","_ ","/ "," ","| ","/ ","| "]
”_ - literal = '_'
; - concatenate -> [" ","_ ","/ "," ","| ","/ ","| ", '_']
¤ - nilad followed by link(s) as a nilad:
“¡ẇḞ6’ - base 250 literal = 31111555
D - convert to decimal list -> [3,1,1,1,1,5,5,5]
" - zip with:
ṁ - mould like
- -> [" ","_","/"," ","|","/ / /","| | |","_____"]
...Main link, part 2:
...ṃ@“ ... ’Fs27 - make the rows of a possible cube without the middle repetitions:
... - part 1, above
“ ... ’ - the 101 digit base 250 number
ṃ@ - base decompression with swapped @rguments
F - flatten (because the digit values we are using are actually lists)
s27 - split into chunks of length 27 (into the rows)
...Main link part 3:
...ǹ⁸?x€15¦€19Y - make "impossible" if need be, add the row middles and output
... - part 2, above
? - if:
⁸ - chain's left argument = V
Ç - ...then: call last link (1) as a monad
- (make it an impossible cube - see link 1, below)
¹ - ...else: identity (do nothing)
€ - for €ach
¦ - apply sparsely:
15 - ...to index: 15
x€ 19 - ...this: repeat €ach nineteen times
Y - join with newlines
- implicit print
ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦ Link 1, replace characters to make impossible: rows
¦ apply sparsely:
“µ½¿‘ ...to indexes: code-page indexes = [9,10,11]
...this:
µ€ for €ach:
ḣ9 head to index 9
¤ nilad followed by link(s) as a nilad:
⁾| list of characters = ['|',' ']
ṁ5 mould like 5 = ['|',' ','|',' ','|']
; concatenate
o logical or (vectorises) with the row
(which has the effect of appending the rest of the row)
```
[Answer]
## JavaScript (ES6), ~~352~~ ~~344~~ 333 bytes
*Saved 2 bytes thanks to @YairRand*
```
x=>[...'mnopqrstuvwxyz01~'].reduce((p,c)=>(l=p.split(c)).join(l.pop()),`1yup
1z uux z|
1/z uu_/z |
yqswtqvy|
yys wtyvq|
qs0t sw
ys 0ts w
snt/v0
v_/x${x?0:'|_|_|'}m/v 0
/~_${b=x?0:'o_'}p/zn
| ~${b}m wnrynuo_0__0ryywp0owryv p0_ vr st0/vrst 0vr/vtn/zrvtqwyzr/_/pow z
wuu__wz
|um|/~xo1yyq0w |z /q o__w| |szp~t111svzr
0qy pu~ox_ny0muxx`)
```
### Demo
```
let f =
x=>[...'mnopqrstuvwxyz01~'].reduce((p,c)=>(l=p.split(c)).join(l.pop()),`1yup
1z uux z|
1/z uu_/z |
yqswtqvy|
yys wtyvq|
qs0t sw
ys 0ts w
snt/v0
v_/x${x?0:'|_|_|'}m/v 0
/~_${b=x?0:'o_'}p/zn
| ~${b}m wnrynuo_0__0ryywp0owryv p0_ vr st0/vrst 0vr/vtn/zrvtqwyzr/_/pow z
wuu__wz
|um|/~xo1yyq0w |z /q o__w| |szp~t111svzr
0qy pu~ox_ny0muxx`)
flag = true
setInterval(_ => o.innerHTML = f(flag = !flag), 750)
```
```
<pre id=o></pre>
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 145 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
─3n{_⁰
ā"¹K╚=+ƨψ≡tšÆA%εW#žt─M^_ξ0“6²⁰ _*ž}"⁵æκLνbΡ°■=μθΝv╝xxΛTγ►℮ΞyF“'№⁰┐∙ž}"⁸Βλμž╚⅔\Ρ═⁴-θ=╚_>◄4℮`ε║t“'¦⁰ā;∫0 /ž}╬5}'Æ6«@┐2Ο3∙:Aža.?X"≥YΤ%‘5n}L9ž
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTAwM24lN0JfJXUyMDcwJTBBJXUwMTAxJTIyJUI5SyV1MjU1QSUzRCsldTAxQTgldTAzQzgldTIyNjF0JXUwMTYxJUM2QSUyNSV1MDNCNVclMjMldTAxN0V0JXUyNTAwTSU1RV8ldTAzQkUwJXUyMDFDNiVCMiV1MjA3MCUyMF8qJXUwMTdFJTdEJTIyJXUyMDc1JUU2JXUwM0JBTCV1MDNCRGIldTAzQTElQjAldTI1QTAlM0QldTAzQkMldTAzQjgldTAzOUR2JXUyNTVEeHgldTAzOUJUJXUwM0IzJXUyNUJBJXUyMTJFJXUwMzlFeUYldTIwMUMlMjcldTIxMTYldTIwNzAldTI1MTAldTIyMTkldTAxN0UlN0QlMjIldTIwNzgldTAzOTIldTAzQkIldTAzQkMldTAxN0UldTI1NUEldTIxNTQlNUMldTAzQTEldTI1NTAldTIwNzQtJXUwM0I4JTNEJXUyNTVBXyUzRSV1MjVDNDQldTIxMkUlNjAldTAzQjUldTI1NTF0JXUyMDFDJTI3JUE2JXUyMDcwJXUwMTAxJTNCJXUyMjJCMCUyMC8ldTAxN0UlN0QldTI1NkM1JTdEJTI3JUM2NiVBQkAldTI1MTAyJXUwMzlGMyV1MjIxOSUzQUEldTAxN0VhLiUzRlglMjIldTIyNjVZJXUwM0E0JTI1JXUyMDE4NW4lN0RMOSV1MDE3RQ__,inputs=MA__)
This program stores the line data as 3 separate base 36-46 numbers and decodes each and `ž`s the values in the main array.
Because of the abusive way of how I draw the diagonal lines, the output has 27 lines of lines with spaces (which is allowed by the OP)
input:
0 - impossible
1 - possible
Explanation:
```
The first line is basically a substitute ⁰ with ─3n{_
ā push an empty array (the canvas for the whole cube)
"...“ pushes 29714643711764388252557994982458231735529743027583646902
6²─ base-36 decodes it
3n{ } for each group of 3 numbers do (where the numbers are X, Y, length)
_ put all the contents on the stack (in the order X, Y, length)
_* get POP amount of underscores
ž in the canvas at the positions x;y (the position of the 1st char, 1-indexed) put the underscores
"...“ pushes 19564601770087915522037775830252836261712294966673526596188
'№─ base-46 decodes it
3n{ } for each group of 3 numbers do
_ put all the contents on the stack
┐∙ get an array of "|"s with the length of POP
ž in the canvas at the position x;y (position of the top char, 1-indexed) put the vertical bar
"...“ pushes 124633728256573776407884156928319785312464662536125755768
'¦─ base-40 decodes it
3n{ } for each group of 3 numbers do
_ put all the contents on the stack
ā; one below the stack put an empty array (canvas for the diagonal line)
∫ } for range(length) do
0 TMP
/ push "/"
ž at the position (iter; 0), 1-indexed put a "/". This extends the array one line upward and causes the extra spaces.
╬5 in the canvas at the position x;y(1-indexed, the top position) put the diagonal line canvas without overriding with spaces
'Æ push 36
6« push 12
@┐2Ο push two spaces, encased in vertical bars - "| | |"
3∙ get an array of 3 of those
:A save on variable A
ž in the canvas, at the positions 36; 12 put the array
a push the variable A
.? } if the input is non-0, then
X remove the variable A off of the stack
"≥YΤ%‘ push "|_|_|__________"
5n chop that into an array of strings of length 5
L9ž at positions 10;9 insert the top of stack (either the ["| | |","| | |","| | |"] or ["|_|_|","_____","","_____"]) in the canvas
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 188 bytes
```
__¶____¶_¶↙¹↓↑⁷↗³P↓⁶↗²↓↓⁷←↙⁴↓↓↓↙↗⁸↑¹²←P←×_³⁵↓↙⁹↑←×_³⁴P↗⁹↓↓¹¹↗→×_³⁴↑¹¹↖P←×_²⁹↗⁷←P←×_³¹↙←×_²⁹↓↙⁶↑←_P↗⁷↓↘P↓⁹←←P×_³²↓↓⁹↗→×_³⁰P↑⁹↖←×_²⁷↗⁶←←↙⁵↘→→↗⁵UO²¹±²_↗↗P×_¹⁹←↙|←P↑²←←↑²FNUO⁵±³ |↑↑P↑⁴F²«→→P↑⁶
```
[Try it online!](https://tio.run/##VZBNCsIwEIWv4hG8UShuXAiC626yybpRMO0FuhH8STU10FW8SS7QI9SZl8YfGErz5s33Mlmti91qW2ymSYjghMA3uKia4KM6RKWj7KMyoRuHKwvS8cmid0CvInOU91nhasgS5ZOGg2drhdnqZUToonzMHumZ/pHvMBnIjKFRz2e1z4bEI/H45Vn4TbrITwzbmj9PynQpU@SwHo06L@exDoMS5bPn/1Wu8GvIx29KD6RLDMTRrjWNoaj1GAeqS7C0xy1YAaiZ03yOb8q8i8broeh3HNpxOCcEsYjQLUrso/N96BFbop9SZlbdNC3f "Charcoal – Try It Online") Link is to falsy version; change the input from `0` to `1` for the truthy version. Here is the approximate verbose code for the above program:
```
Print("__\n____\n_\n");
```
Print the part of the back visible through the right "hole".
```
Print(:DownLeft, 1);
Move(:Down);
Print(:Up, 7);
Print(:UpRight, 3);
Multiprint(:Down, 6);
Print(:UpRight, 2);
Move(:Down);
Print(:Down, 7);
Move(:Left);
Print(:DownLeft, 4);
```
Print the right "hole".
```
Move(3, :Down);
Move(:DownLeft);
Print(:UpRight, 8);
Print(:Up, 12);
Move(:Left);
Multiprint(:Left, Times("_", 35));
Move(:Down);
Print(:DownLeft, 9);
Move(:Up);
Print(:Left, Times("_", 34));
Multiprint(:UpRight, 9);
Move(:Down);
Print(:Down, 11);
Move(:UpRight);
Print(Times("_", 34));
Print(:Up, 11);
```
Print the outer edge of the cube.
```
Move(:UpLeft);
Multiprint(:Left, Times("_", 29));
Print(:UpRight, 7);
Move(:Left);
Multiprint(:Left, Times("_", 31));
Move(:DownLeft);
Print(:Left, Times("_", 29));
Move(:Down);
Print(:DownLeft, 6);
Move(:Up);
Print(:Left, "_");
Multiprint(:UpRight, 7);
```
Print the top "hole" of the cube.
```
Jump(1, 2);
Multiprint(:Down, 9);
Move(2, :Left);
Multiprint(Times("_", 32));
Move(:Down);
Print(:Down, 9);
Move(:UpRight);
Print(Times("_", 30));
Multiprint(:Up, 9);
Move(:UpLeft);
Print(:Left, Times("_", 27));
```
Print the front "hole" of the cube.
```
Print(:UpRight, 6);
Move(2, :Left);
Print(:DownLeft, 5);
Jump(3, 1);
Print(:UpRight, 5);
Oblong(21, Negate(2), "_");
Move(2, :UpRight);
Multiprint(Times("_", 19));
Move(:Left);
Print(:DownLeft, "|");
Move(:Left);
Multiprint(:Up, 2);
Move(2, :Left);
Print(:Up, 2);
```
Print the part of the back visible through the front "hole".
```
for (InputNumber()) Oblong(5, Negate(3), " |");
```
Make the cube impossible if necessary.
```
Move(2, :Up);
Multiprint(:Up, 4);
for (2) {
Move(2, :Right);
Multiprint(:Up, 6);
}
```
Print the part of the back visible through the top "hole".
] |
[Question]
[
Given a dictionary of 4-letter words that have no repeated characters ([***from this list of words***](https://pastebin.com/M9ZChdP8)), you must choose ONE of those words, and output that specific word using the following dictionary of block letters:
```
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | __ | || | ______ | || | ______ | || | ________ | |
| | / \ | || | |_ _ \ | || | .' ___ | | || | |_ ___ '. | |
| | / /\ \ | || | | |_) | | || | / .' \_| | || | | | '. \ | |
| | / ____ \ | || | | __'. | || | | | | || | | | | | | |
| | _/ / \ \_ | || | _| |__) | | || | \ '.___.'\ | || | _| |___.' / | |
| ||____| |____|| || | |_______/ | || | '._____.' | || | |________.' | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | _________ | || | _________ | || | ______ | || | ____ ____ | |
| | |_ ___ | | || | |_ ___ | | || | .' ___ | | || | |_ || _| | |
| | | |_ \_| | || | | |_ \_| | || | / .' \_| | || | | |__| | | |
| | | _| _ | || | | _| | || | | | ____ | || | | __ | | |
| | _| |___/ | | || | _| |_ | || | \ '.___] _| | || | _| | | |_ | |
| | |_________| | || | |_____| | || | '._____.' | || | |____||____| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | _____ | || | _____ | || | ___ ____ | || | _____ | |
| | |_ _| | || | |_ _| | || | |_ ||_ _| | || | |_ _| | |
| | | | | || | | | | || | | |_/ / | || | | | | |
| | | | | || | _ | | | || | | __'. | || | | | _ | |
| | _| |_ | || | | |_' | | || | _| | \ \_ | || | _| |__/ | | |
| | |_____| | || | '.___.' | || | |____||____| | || | |________| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .-----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | ____ ____ | || | ____ _____ | || | ____ | || | ______ | |
| ||_ \ / _|| || ||_ \|_ _| | || | .' '. | || | |_ __ \ | |
| | | \/ | | || | | \ | | | || | / .--. \ | || | | |__) | | |
| | | |\ /| | | || | | |\ \| | | || | | | | | | || | | ___/ | |
| | _| |_\/_| |_ | || | _| |_\ |_ | || | \ '--' / | || | _| |_ | |
| ||_____||_____|| || ||_____|\____| | || | '.____.' | || | |_____| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | ___ | || | _______ | || | _______ | || | _________ | |
| | .' '. | || | |_ __ \ | || | / ___ | | || | | _ _ | | |
| | / .-. \ | || | | |__) | | || | | (__ \_| | || | |_/ | | \_| | |
| | | | | | | || | | __ / | || | '.___'-. | || | | | | |
| | \ '-' \_ | || | _| | \ \_ | || | |'\____) | | || | _| |_ | |
| | '.___.\__| | || | |____| |___| | || | |_______.' | || | |_____| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | _____ _____ | || | ____ ____ | || | _____ _____ | || | ____ ____ | |
| ||_ _||_ _|| || ||_ _| |_ _| | || ||_ _||_ _|| || | |_ _||_ _| | |
| | | | | | | || | \ \ / / | || | | | /\ | | | || | \ \ / / | |
| | | ' ' | | || | \ \ / / | || | | |/ \| | | || | > '' < | |
| | \ '--' / | || | \ ' / | || | | /\ | | || | _/ /''\ \_ | |
| | '.__.' | || | \_/ | || | |__/ \__| | || | |____||____| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
.----------------. .----------------.
| .--------------. || .--------------. |
| | ____ ____ | || | ________ | |
| | |_ _||_ _| | || | | __ _| | |
| | \ \ / / | || | |_/ / / | |
| | \ \/ / | || | .'.' _ | |
| | _| |_ | || | _/ /__/ | | |
| | |______| | || | |________| | |
| | | || | | |
| '--------------' || '--------------' |
'----------------' '----------------'
```
Depending on how old you are, you may have just been given an injection of nostalgia from these block-based letters. Then again, past a certain point, you may have the nostalgia from watching your kids spell these block-based words out on their own. [First originating in 1693](https://en.wikipedia.org/wiki/Toy_block), alphabet blocks were a pretty common education piece of the nuclear family and beyond. We're going to recreate this nostalgia by spelling a word [***from this list of words***](https://pastebin.com/M9ZChdP8).
In other words, this challenge is to pick four letters from the keyspace definition and render them "stacked" in an order specified by the dictionary. You'll notice the dictionary omits 4-letter words like `moon` as they repeat letters, and are basically cheat-words.
Here is the block structure itself with no character inside:
```
.----------------.
| .--------------. | # Tops are periods.
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| '--------------' | # Bottoms are apostrophe's.
'----------------'
```
# Rules
* Characters inside the blocks only use: `|/\_'.]-><`.
* Numbers don't exist, nor do symbols; only the letters in the word list.
* This is a kolmogorov-complexity problem after you've chosen your word, you must output each block exactly as shown.
* You may output them in any format you want, vertical, horizontal, stacked in a square; however, it must read top-to-bottom, left-to-right. Also, each block must be displayed without being altered, in a coherent format. This is to give more freedom to save bytes and allow a diverse output structure, much like how it would be when playing with blocks.
* The main competitive element of this challenge is both compression optimization and, [like my other problem](https://codegolf.stackexchange.com/questions/99913/5-favorite-letters), also factors in your ability to problem solve given the leg-room of seemingly "aesthetic" choice.
# Examples
```
.----------------. .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. |
| | _________ | || | ____ ____ | || | ______ | || | _________ | |
| | | _ _ | | || | |_ _||_ _| | || | |_ __ \ | || | |_ ___ | | |
| | |_/ | | \_| | || | \ \ / / | || | | |__) | | || | | |_ \_| | |
| | | | | || | \ \/ / | || | | ___/ | || | | _| _ | |
| | _| |_ | || | _| |_ | || | _| |_ | || | _| |___/ | | |
| | |_____| | || | |______| | || | |_____| | || | |_________| | |
| | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------'
```
Is the same validity as:
```
.----------------.
| .--------------. |
| | _________ | |
| | | _ _ | | |
| | |_/ | | \_| | |
| | | | | |
| | _| |_ | |
| | |_____| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | ____ ____ | |
| | |_ _||_ _| | |
| | \ \ / / | |
| | \ \/ / | |
| | _| |_ | |
| | |______| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | ______ | |
| | |_ __ \ | |
| | | |__) | | |
| | | ___/ | |
| | _| |_ | |
| | |_____| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | _________ | |
| | |_ ___ | | |
| | | |_ \_| | |
| | | _| _ | |
| | _| |___/ | | |
| | |_________| | |
| | | |
| '--------------' |
'----------------'
```
Which is just as valid as:
```
.----------------.
| .--------------. |
| | _________ | |
| | | _ _ | | |
| | |_/ | | \_| | |
| | | | | |
| | _| |_ | |
| | |_____| | |
| | | |
| '--------------' |
'----------------'
.----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. |
| | ____ ____ | || | ______ | || | _________ | |
| | |_ _||_ _| | || | |_ __ \ | || | |_ ___ | | |
| | \ \ / / | || | | |__) | | || | | |_ \_| | |
| | \ \/ / | || | | ___/ | || | | _| _ | |
| | _| |_ | || | _| |_ | || | _| |___/ | | |
| | |______| | || | |_____| | || | |_________| | |
| | | || | | || | | |
| '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------'
```
This also works:
```
.----------------. .----------------.
| .--------------. || .--------------. |
| | _________ | || | ____ ____ | |
| | | _ _ | | || | |_ _||_ _| | |
| | |_/ | | \_| | || | \ \ / / | |
| | | | | || | \ \/ / | |
| | _| |_ | || | _| |_ | |
| | |_____| | || | |______| | |
| | | || | | |
| '--------------' || '--------------' |
'----------------' '----------------'
.----------------. .----------------.
| .--------------. || .--------------. |
| | ______ | || | _________ | |
| | |_ __ \ | || | |_ ___ | | |
| | | |__) | | || | | |_ \_| | |
| | | ___/ | || | | _| _ | |
| | _| |_ | || | _| |___/ | | |
| | |_____| | || | |_________| | |
| | | || | | |
| '--------------' || '--------------' |
'----------------' '----------------'
```
Even stuff that seems like it would cost bytes for you to do:
```
.----------------. .----------------.
| .--------------. || .--------------. |
| | _________ | || | ____ ____ | |
| | | _ _ | | || | |_ _||_ _| | |
| | |_/ | | \_| | || | \ \ / / | |
| | | | | || | \ \/ / | |
| | _| |_ | || | _| |_ | |
| | |_____| | || | |______| | |
| | | || | | |
| '--------------' || '--------------' |
'----------------' '----------------'
.----------------. .----------------.
| .--------------. || .--------------. |
| | ______ | || | _________ | |
| | |_ __ \ | || | |_ ___ | | |
| | | |__) | | || | | |_ \_| | |
| | | ___/ | || | | _| _ | |
| | _| |_ | || | _| |___/ | | |
| | |_____| | || | |_________| | |
| | | || | | |
| '--------------' || '--------------' |
'----------------' '----------------'
```
However you can stack the blocks to save yourself bytes is a winner in my book.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~180~~ ~~164~~ ~~162~~ ~~159~~ ~~158~~ 155 bytes
```
→⁸↘.↓⁹← '←⁸↗→⁶↗'↑⁷← .←⁶↘F³C⁰¦¹¹↓↓↗²____↓←|_↓↓³↗↘_←|_____↑¹↗²↓↓²↖↙_M⁶↓↘_↘⁴↑↘_←|____↑¹→↖\_↓\_Mχ↓↗²← _↑¹ ____↓←|↙_↙²|_↓←|___↘M⁵↓_↘_→'↘.↓\|↙¹←'.__↗→¹↗'↖|←.-‖M←
```
[Try it online!](https://tio.run/##TVC9CoMwEH4VN6fmiYQgLh0Khc4OzZKuUSGmc8GtULR/glNeoO9wL@AjpHcXWwxJLnw/9x0ptvmh2Oe7EEDXoN6gnQDdgBpBmyTFi8GW2Sc@EKpAvYgVzCLo5qnzwzxdQN1850c/Ugvare8lLn6bMtbGD9zQScYiX5EH1YsCqwV9lvN05YQmyh2oO@WvvIu1RkNG/TPyfE6/dJozapLVINQaj@/L/2jEOY57ICRjRJ0u/5GRhXJMKkhJ/8ETo8AiZ8QGjpbs2oTwBQ "Charcoal – Try It Online") Edit: Saved ~~16~~ 18 bytes by manually drawing the letters `WAY`; unfortunately `X` turns out to be too hard to draw, so it's still printed using a string literal. Saved a further 3 bytes by switching from `WAXY` to `AHOY`. Saved another byte by switching to `MAYO` because I can use the predefined `χ` variable for 10. Saved a further 3 bytes by repeating the copy of the border in a loop. Explanation:
```
→⁸↘.↓⁹← '←⁸↗ Draw the outer right half of a block
→⁶↗'↑⁷← .←⁶↘ Draw the inner right half of a block
F³C⁰¦¹¹ Make three copies of the right half of the block
↓↓ Move into position and draw an M right half
↗²____↓←|_↓↓³↗↘_←|_____↑¹↗²↓↓²↖↙_
M⁶↓ Move into position and draw an A right half
↘_↘⁴↑↘_←|____↑¹→↖\_↓\_
Mχ↓ Move into position and draw a Y right half
↗²← _↑¹ ____↓←|↙_↙²|_↓←|___↘
M⁵↓ Move into position and draw an O right half
_↘_→'↘.↓\|↙¹←'.__↗→¹↗'↖|←.-
‖M← Reflect to the left
```
Full list of letter right halves:
```
A ↘_↘⁴↑↘_←|____↑¹→↖\_↓\_ (22 bytes)
H _↑¹←↑¹ ____↓←|_↓↓³↗↘_←|____↑¹→↑¹←↓_ (35 bytes)
M ↗²____↓←|_↓↓³↗↘_←|_____↑¹↗²↓↓²↖↙_ (33 bytes)
O _↘_→'↘.↓\|↙¹←'.__↗→¹↗'↖|←.-↘ (28 bytes)
W ↘²↑↑²← _↑¹ _____↓←|_↓↓⁴↖←__↖²↘ (30 bytes)
X ____¶|_ _|¶ / /¶' <¶'\ \_¶|____|¶ (35 bytes)
Y ↗²← _↑¹ ____↓←|↙_↙²|_↓←|___↘ (28 bytes)
```
If `O`, `W`, `X` or `Y` is the last letter then the last byte can be removed. On the other hand, `M`, `W` and `Y` cost 2 bytes as a first letter or a byte as the letter after `O`; `H` costs a byte as a first letter. With the above byte counts, the following words are possible:
```
MAYO 155 bytes (43+33+22+28+28+2-1)
AHOY 156 bytes (43+22+35+28+28+1-1)
WAXY 159 bytes (43+30+22+35+28+2-1)
WHOA 160 bytes (43+30+35+28+22+2)
HOAX 163 bytes (43+35+28+22+35+1-1)
WHAM 165 bytes (43+30+35+22+33+2)
WHOM 171 bytes (43+30+35+28+33+2)
```
[Answer]
# PHP, 362 Bytes
MILK
```
$a="--------------";$b=977775;echo strtr("2222
1111
5 6886 5976_885576_7759___8675
507\8/7_|59807_|75907_|7855 08|08_|85
9|7\/7|85577975989875575_/ /885
95\8/955779759857_7557|8__'.885
5 _5_\/_5_ 597_5_88557_5__/ |859_9\ \_85
506|06|59806|759|66|855 |6||6| 5
$b$b$b$b
3333
4444",
["|_","| .$a. |"," .-$a-. ","| '$a' |"," '-$a-' ","| |",____," "," ","| | "]);
```
[Try it online!](https://tio.run/nexus/php#VVDLasQwDLz7K4QxpIWNkz5ky6RLP6QpIlsKe@uy3aP@PR0lpdCx8YiZsSz88no5X9a0HGP/D3FKp2OrAE@fH@cv@r5db9e7@AiEByAwFZFC3GpREWYQwk1VpVQOPNZZhqrGTUYQrI2QpFFsFDXh0KzOQzW/Xhsi0qSiZh1oEPcZTdqfy1XdNlHtsvtMyjoPOHwQ0DYJGA3QtWmbaVYPjsWwfZjis1gp/ipZMWzikE77Ck9AeAbiIbxF03iIRjktmQwl5T4tfaZN7dLS7WrnarerEPAJCpVcoF8V/H4/resP "PHP – TIO Nexus")
## PHP, 258 Bytes Only compressed
```
echo gzinflate(base64_decode("pZI5DsUgDET7nMJdqsCFkHyROfxnHJaB6iu4iOFhjxfF0rNZMjtgF3aaDCesCsK8mlULDwbC+j0eBhtksgAN4xUEz8UsMwNTMLhDkicZjCgUiJugRX7JEaUdWj9Ikf40GUVzdKOCYIf4V9BXwTrxnVTQWaTkcMsO34l0hyS1Hyns8S1WXHZIG052GGDZYTPIDkcu5shqOvIHVgXv9V+6GfidXTsjPWE/"));
```
[Try it online!](https://tio.run/nexus/php#BcHJboJAAADQX2k8aTwUKyDGJk1lWBWxOgPIpRlhFpYiOiDLz9v3Pr9qXr9Iwm9vbMwqWuKGTK9YEFX@TUlyS8l0UseOAgRiwICrynPTu9DNwh5OPu0r28VbNWvlzDd53lNTehxiL2@YucQY6EToYqf9lWgPuqs@zyWy5U0h2PdB7pExakh43QF6ew6KLIlznaHMbdkpWrkGRmmYr52CypKFgjHd@frFoXKw3kYdfPRVAH9CDIvEE/5SLiU@nBf2UAntvAgjO3YsSfmwLBBf4NEBRdIqgt/9p2MHLHqug7lq0SyNoMiPofE@mc02r9c/ "PHP – TIO Nexus")
## PHP, 323 Bytes Code above compress with use of eval
```
eval(gzinflate(base64_decode("VVBdawQhDHz3VwQRbOF2135EI8v9klrCXincW+F6j/nxneyWQkdxwswYg2k7x+kf4pou594AXj8/rl/0fb/dbw/xGQhPQGCqIpW4t6oizCCEu6pKbRy4tCFLU+MuBQRrJySpiBVREw7d2lia+fXWEZEuDTXrQou4z2jS/1xu6raJap7dZ1LWseDwQUD7JGA0QNeufdBQD5Zq2D5M9VmsVn+VrBo2cUiXY4UXILwC8RTeomk8RaM5bTMZSpqntE0z7WpOWz7U7Go+VAj4BIVKLtCvCn5/XH8A")));
```
[Try it online!](https://tio.run/nexus/php#BcHJcoIwAADQf/GkwwHFsDjtTAcCIhZqgxKQSwdMUBYhshjk5@17n1/sxt70mVTz65TXWZX0dJ4mHVXAH6GXhtD5DGODJBzdzN20xhz56WErrday5WjPTVm1MMrrSyhslUKsx5q@QlSSkXf8fJVKdRTKDLBmkDdAjwpNbCtxmaUiSbk42uj2i2z4cFgIeqXJJwitQWHfqf8CPdy6geANBvLb/evIcgP7FleJVOWJkEWhFVuDeYpa1AxgkoqjuBoHpU32CVNJvHLDjpocBaa6t/Ul@qFDRgxkyvFDMmVvg@8drgXcGo10CfLoDILIcTnU/BNt7qXmJ56cnrz4yB51by0nNWSHcFID1W4ErBfAcPC328MnrGUx2mn6bLFYfLzf/w "PHP – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~119~~ 114 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### WHAM
```
“ƭHGE94=ẠĊỴI>ạȧⱮṅƇṾ'Ñɦȥ⁴7?6ụ\ĖḂẆṾƇṗyZḣ&c%~Œ’ṃ“ |\_”s7;€“| |”µṚ“\/”y;µ€s6U4¦
“ŒUỴ2,Ɠ’ṃ“|'-. ”s4µṪẋ7ṭµ€m€0s3ṚjЀ¢Y€Y
```
**[Try it online!](https://tio.run/nexus/jelly#@/@oYc6xtR7urpYmtg93LTjS9XD3Fk@7h7sWnlj@aOO6hztbj7U/3LlP/fDEk8tOLH3UuMXc3uzh7qUxR6Y93NH0cFcbUA6kYHpl1MMdi9WSVeuOTnrUMPPhzmagsQo1MfGPGuYWm1s/aloD5Nco1AC5h7Y@3DkLyIvRB3IqrQ9tBUoWm4WaHFrGBRQ9OikU6AAjnWOT4cbUqOvqKYDMMQFpXfVwV7f5w51rwfpygdig2BhoYNbhCUD2oUWRQDLy/38A)**
### How?
The general idea is to choose letters which have left-right symmetry with minimal character translation so as to (a) reduce the base in which the data may be encoded and (b) keep the "reflection" function small.
The letter `H` has left-right symmetry with no need for translation. The letters `W` and `A` also have left-right symmetry if the `/`s on the left become `\`s on the right. Unfortunately there are not four such letters (with the same sides having the same slopes of slashes).
Letters such as `O` introduce more characters, which increases the base needed for encryption making for a far larger number and hence more bytes.
`M`, however, only introduces the other slash - if the half rows for the `M` are stored in reverse *and* with the wrong slashes, the base is kept at four and a post-decryption, post-reflection reversal of just these rows puts everything right again (this is the `U4¦` in Link 1). This also means the character translation only needs to cater for `\` becoming `/` and not the other way around too (i.e. `Ṛ“\/”y;` rather than `Ṛ“\/“/\”y;`).
```
“...’ṃ“ |\_”s7;€“| |”µṚ“\/”y;µ€s6U4¦ - Link 1: middle rows of blocks: no arguments
“...’ - base 250 number
ṃ“ |\_” - convert to base 4 with digits [0-3]="_ |\"
s7 - split into sevens
“| |” - literal "| |"
;€ - concatenate €ach
µ - monadic chain separation (call that rhs)
µ€ - for each r in rhs:
Ṛ - reverse r
“\/”y - convert any '\'s to '/'s
; - concatenate with r
s6 - split into sixes
¦ - apply to indexes...
4 - four (the M)
U - upend
“ŒUỴ2,Ɠ’ṃ“|'-. ”s4µṪẋ7ṭµ€m€0s3ṚjЀ¢Y€Y - Main link: no arguments
“ŒUỴ2,Ɠ’ - base 250 number
ṃ“ -|.'” - convert to base 5 with digits [0-4]="' -|."
s4 - split into fours
µ - monadic chain separation (call that lhs)
µ€ - for each l in lhs:
Ṫ - tail l
ẋ7 - repeat (the tail) seven times
ṭ - tack to l
m€0 - reflect €ach
s3 - split into threes
Ṛ - reverse
¢ - call last link (1) as a nilad
jЀ - join mapped over right
Y€ - join each with newlines
Y - join with newlines
- implicit print
```
[Answer]
## Javascript ~~433~~ 416 characters
Yeah, it is not very impressive. But I put this much work in and I don't see any easy way to get a lot better :)
\_=>{r=(s,x)=>s.repeat(x)
```
Z='| |'
q=(s,x)=>Z+r(_=' ',x)+s+r(_,14-s.length-x)+Z
h=r('-',14)
Y=(a,o)=>` .-${h}-. \n| .${h}. |
`+a.map((s,i)=>q(s,[2,1,3,3,2,1][i]+o)).join(N='\n')+N+q(r(_,14))+`
| '${h}' |
'-${h}-'
`
return Y([i=r(U='_',5),j='|_ _|',Z,Z+' _',l='_| |___/ |',m=`|${i}____|`],1)+Y([i,j,Z,Z,I=U+Z+U,J=`|${i}|`],3)+Y([e=r(U,9),f='|_ ___ |',g=Z+'_ \\_|','| _|',I,J],0)+Y([e,f,g,'| _| _',l,m],0)}
```
Not sure my letters are perfectly well formed:
```
.----------------.
| .--------------. |
| | _____ | |
| | |_ _| | |
| | | | | |
| | | | _ | |
| | _| |___/ | | |
| | |_________| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | _____ | |
| | |_ _| | |
| | | | | |
| | | | | |
| | _| |_ | |
| | |_____| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | _________ | |
| | |_ ___ | | |
| | | |_ \_| | |
| | | _| | |
| | _| |_ | |
| | |_____| | |
| | | |
| '--------------' |
'----------------'
.----------------.
| .--------------. |
| | _________ | |
| | |_ ___ | | |
| | | |_ \_| | |
| | | _| _ | |
| | _| |___/ | | |
| | |_________| | |
| | | |
| '--------------' |
'----------------'
```
The result is saved to the `a` variable.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 119 bytes
```
00000000: d5d2 0106 0341 1483 6100 e614 3fb0 60a6 .....A..a...?.`.
00000010: 172a b948 0e5f 08d2 a754 a9d2 80f5 2df8 .*.H._...T....-.
00000020: bde1 ecb1 b33c f1e0 650c 4892 00c0 412c .....<..e.H...A,
00000030: 406e cc27 bc46 3522 63e9 860b adac b017 @n.'.F5"c.......
00000040: bcf6 d32e bcda a2eb b3c8 ce34 c1ce 2c4c ...........4..,L
00000050: d17b 4ce6 40a7 f1f7 91ca ea14 2994 e853 .{L.@.......)..S
00000060: 901f 770d ccc9 0b53 d858 85ff 1b29 66e4 ..w....S.X...)f.
00000070: 78ae d637 9feb 03 x..7...
```
[Try it online!](https://tio.run/##bdC9jhUxDAXgnqc4okGgxbLzH4TE0iCK7ZaCjk0chwboViDx8BeP7tyO00yKyefjzOc5f9j355@XC595h5VXAAsXcEwCSS2iCDOsSELck1F4FICOfCQa/vlAT/TiKogbUsPA7KmBLW9wc3LUnDC6nxrvjLB2c@MNfaZvDnw5sLc3I7gxlwlMp2DGqNhiPjizIrXuBVkZSYKePd4TmVNe6O40ohuJi0E1VExNBTGHgBKtoxWeGGsoJksF7n/RK/qUXypdcxrp6KG7YMVgfloDI9j0RtqgFhNU1BA03Xpck4juHk4jH28qdSKpFW80qu@yK7rogA1/09B7grUc3fj7QPcn8pro8TSKG51lo1ZevpB28PT/V8sNLe8NmaGjFEtHj9/H9Uf6eiD7tkt1o7ZhWCX69O1rsE/8f/4QVb99ufwD "Bubblegum – Try It Online")
LIFE. [Here](https://hastebin.com/hurujeleti) is a list of all letters in a more readable format I used for trying out every single word.
[Answer]
# Deadfish~, 3977 bytes
```
{iii}iic{i}iiiicd{c}ccccccic{d}ddddcc{i}iiiicd{c}ccccccic{d}ddddcc{i}iiiicd{c}ccccccic{d}ddddcc{i}iiiicd{c}ccccccic{d}ddddc{dd}ddc{{i}}{i}iiiic{{d}i}ddc{i}iiiicd{c}ccccic{d}ddddc{{i}d}iicc{{d}i}ddc{i}iiiicd{c}ccccic{d}ddddc{{i}d}iicc{{d}i}ddc{i}iiiicd{c}ccccic{d}ddddc{{i}d}iicc{{d}i}ddc{i}iiiicd{c}ccccic{d}ddddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}iiiccccccccc{dddddd}dddccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}iiicccc{dddddd}dddcc{iiiiii}iiicccc{dddddd}dddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{iiiiii}iiicccccc{dddddd}dddccccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}iiiccccccccc{dddddd}dddccc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}iiic{dddddd}dddccc{iiiiii}iiic{dddddd}dddcc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}ic{dddddd}dddcc{iiiiii}iiic{iii}dcc{ddd}ic{dddddd}dddcc{iiiiii}iiic{iii}dc{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{{i}d}iic{ddd}ic{dddddd}dddccc{iiiiii}iiicc{dddddd}dddc{iiiiii}c{dddddd}ccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}ic{dddddd}dddccc{iiiiii}iiiccc{dddddd}dddcc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}ic{ddddd}iic{d}dddddc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}i}ddc{iiiiii}ciiic{iii}dc{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{iiiiii}c{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{d}dddddccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}icc{ddddd}ddddc{d}ic{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}ic{dddddd}dddcc{iiiiii}ciiic{iii}dc{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddccccc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}i}ddcccccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcccc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcc{iiiiii}iiiccc{ddddd}iic{d}dddddccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}i}ddcc{iiiiii}iiic{iii}dc{{d}i}ddcc{iiiiii}iiic{dddddd}dddccc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddcccc{iiiiii}iiic{iii}dc{{d}i}ddc{{i}d}iic{ddd}ic{dddddd}dddccccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcccc{iiiiii}iiic{iii}dc{{d}i}ddcc{{i}d}iic{ddd}ic{dddddd}dddcccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{iiiiii}iiic{iii}dc{{d}i}ddc{{i}d}iic{ddd}ic{dddddd}dddcccccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}iiic{iii}dc{{d}i}ddc{{i}d}iic{ddd}iccc{ddddd}iic{d}dddddc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}ddccc{{i}d}iic{ddd}iccccc{iii}dc{{d}i}ddcccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddccc{{i}d}iic{ddd}icccccc{iii}dc{{d}i}ddccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{{i}d}iic{ddd}iccccc{iii}dc{{d}i}ddccccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}ddc{{i}d}iic{ddd}iccccccccc{iii}dc{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iic{{d}i}dd{c}cccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}dd{c}cccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}dd{c}cccc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}i}ddc{{i}d}iic{{d}i}dd{c}cccc{{i}d}iic{{d}i}ddc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{i}dddciiiiii{c}ccccddddddc{d}iiic{{i}d}iicc{{d}i}ddc{i}dddciiiiii{c}ccccddddddc{d}iiic{{i}d}iicc{{d}i}ddc{i}dddciiiiii{c}ccccddddddc{d}iiic{{i}d}iicc{{d}i}ddc{i}dddciiiiii{c}ccccddddddc{d}iiic{{i}d}iic{{d}}{d}ddddc{ii}iic{i}dddciiiiii{c}ccccccddddddc{d}iiicc{i}dddciiiiii{c}ccccccddddddc{d}iiicc{i}dddciiiiii{c}ccccccddddddc{d}iiicc{i}dddciiiiii{c}ccccccddddddc
```
[Try it online!](https://deadfish.surge.sh/#LHaVkXu+5XqZ6qWOAAmvVBnqpY4ACa9UGeqljgAJr1QZ6qWOAAmvVGr0bP+eqm130Z6qWOAJr1Rs+6htd9GeqljgCa9UbPuobXfRnqpY4AmvVGz7qG130Z6qWOAJr1Rs+6m1/r1Rs/56qbXfRs+6m130GVV6oAAGqq9QGz7qbXfRs+6htd9Gz7qbXfQZVXqgGqq9QZVXqgGqq9QbPuptd9Gz7qG130bPuptd9AZVXqgAaqr1ABs+6m130bPuobXfRs+6m130GVV6oAAGqq9QGz7qbXfRs+6m1/r1Rs/56qbXfRs+6m130bPuptd9BlVeqaqr1AZVXqmqq9QbPuptd9Bs+6m130bPuobXfRs+6m130bPupqumqq9QZVXqmV8Gq6aqr1BlVeqZXxtd9Gz7qbXfRs+6htd9Gz7qbXfQbPupqumqq9QGVV6oaqr1GVV5qquBs+6m130bPuobXfRs+6m130bPupqumqq9QGVV6oGqq9QbPuptd9Bs+6m130bPuptf69UbP+eqm130bPuptd9Gz7qarpqq6mvVRs+6m130bPuptd9GVV4qZXxtd9Bs+6m130bPuobXfRs+6m130BlVeaqrmVV5qquGeqpr1UZ6qmvVQGz7qbXfRs+6htd9Gz7qbXfQBs+6m130bPupquhqq9Ua6bPuptd9Bs+6m130bPuobXfRs+6m130Bs+6m130bPupqumqq9QZVXiplfG130Gz7qbXfRs+6m1/r1Rs/56qbXfRs+6m130AGz7qbXfRs+6m130ABs+6m130bPuobXfRs+6m130AZVXmqq5lVeaq9VGvVRnqqa9VAGz7qbXfRs+6htd9Gz7qbXfQBs+6m130GVV6oGqrqa9VAbPuptd9Gz7qG130bPuptd9AbPuptd9BlVeqZXxtd9BlVeqaqr1AbPuptd9Gz7qbX+vVGz/nqptd9Gz7qbXfQBlVeqZXxtd9Gz7qarpqqvUAGz7qbXfRs+6htd9Gz7qbXfQBlVeqZXxtd9Bs+6mq6aqr1AGz7qbXfRs+6htd9Gz7qbXfQGVV6plfG130bPupqumqq9QAGz7qbXfRs+6htd9Gz7qbXfQZVXqmV8bXfRs+6mq6Bqq6mvVRs+6m130Gz7qbXfRs+6m1/r1Rs/56qbXfRs+6m130Bs+6mq6AGV8bXfQBs+6m130bPuobXfRs+6m130Bs+6mq6ABlfG130Bs+6m130bPuobXfRs+6m130Gz7qaroAZXxtd9ABs+6m130bPuobXfRs+6m130bPupqugAAZXxtd9Bs+6m130bPuptf69UbP+eqm130bPuptd9Y4Bs+6m130bPuobXfRs+6m131jgGz7qbXfRs+6htd9Gz7qbXfWOAbPuptd9Gz7qG130bPuptd9Y4Bs+6m130bPuptf69UbP+eqm130Z9QqrjgFVRrqmz7qG130Z9QqrjgFVRrqmz7qG130Z9QqrjgFVRrqmz7qG130Z9QqrjgFVRrqmz7qbX+vVGXqZ9QqrjgAVVGuqGfUKq44AFVRrqhn1CquOABVUa6oZ9QqrjgAVVAA=)
] |
[Question]
[
# The Challenge
Given a CSV input, output a proper unicode table using box characters.
# Formatting
The table will be formatted using the following rules:
* Column width will be equal to the longest value of that column
* All table data will be left justified
* Each table will assume the first csv row to be the header
* The table will use the following characters for its borders:
`┌ ┬ ┐ ├ ┼ ┤ └ ┴ ┘ ─ │`
# Example
```
Input:
Name,Age,Gender
Shaun,19,Male
Debra,19,Female
Alan,26,Male
George,15,Male
Output:
┌──────┬───┬──────┐
│Name │Age│Gender│
├──────┼───┼──────┤
│Shaun │19 │Male │
│Debra │19 │Female│
│Alan │26 │Male │
│George│15 │Male │
└──────┴───┴──────┘
```
# Rules
* Standard loopholes apply
* You may submit a full program, a function or a lambda
* Input can be from a file, a program argument or any acceptable alternative
* Output can be to a file, returned or any acceptable alternative
* CSV input should take the same format as used in my example.
* Shortest answer in bytes wins.
CSV input should take the following form:
```
Header1,Header2,Header3 newline
Column1,Column2,Column3 newline
Column1,Column2,Column3 optional_newline
```
[Answer]
# [Try (Dyalog) APL](http://goo.gl/9KrKoM), ~~38~~ 43 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
Last input line must have a trailing newline.
```
{{(⊃⍵)⍪⍉⍪↑¨↓⍉↑1↓⍵}s¨',',¨(s←1↓¨⊢⊂⍨⊢=⊃)¯1⌽⍵}
```
[Try it online!](http://tryapl.org/?a=%7B%7B%28%u2283%u2375%29%u236A%u2349%u236A%u2191%A8%u2193%u2349%u21911%u2193%u2375%7Ds%A8%27%2C%27%2C%A8%28s%u21901%u2193%A8%u22A2%u2282%u2368%u22A2%3D%u2283%29%AF1%u233D%u2375%7D%27Name%2CAge%2CGender%27%2C%28%u2395UCS%2010%29%2C%27Shaun%2C19%2CMale%27%2C%28%u2395UCS%2010%29%2C%27Debra%2C19%2CFemale%27%2C%28%u2395UCS%2010%29%2C%27Alan%2C26%2CMale%27%2C%28%u2395UCS%2010%29%2C%27George%2C15%2CMale%27%2C%28%u2395UCS%2010%29&run) In the offline version of Dyalog APL, execute `]boxing ON -style=min` for the same effect.
### Explanation
`{` ... `}` an anonymous function where `⍵` represents the argument:
`¯1 ⌽ ⍵` rotate the trailing newline to the front
`(s ←` ... `)` define the function *s* as follows, and apply it
`1 ↓¨` drop the first character of each
`⊢ ⊂⍨` line, split where
`⊃ = ⊢` the first character equals the characters in the string
`',' ,¨` then prepend a comma to each line
`s¨` apply the function *s* to each line
`{` ... `}` now apply the following anonymous function:
`1 ↓ ⍵` drop the first element (the row headers)
`↓ ⍉ ↑` transpose the list of rows into list of columns
`↑¨` make each element (a list of entries) into a matrix of padded entries
`⍉ ⍪` make into one-column matrix, then transpose into one-row matrix
`(⊃⍵) ⍪` put the argument's first element (the list of headers) on top`
**Note:** While the line drawing characters are not explicitly used in my solution, they are part of the APL character set, and would also be counted as single bytes.
[Answer]
# PowerShell 3+, 365 bytes
```
$d=$input|ipcsv
$h=$d[0].PSObject.Properties.Name|%{$_|Add-Member -type NoteProperty -na c -v(($d.$_+$_|measure Length -ma).Maximum)-pa}
"┌$(($h|%{'─'*$_.c})-join'┬')┐"
"│$(($h|%{$_.PadRight($_.c)})-join'│')│"
"├$(($h|%{'─'*$_.c})-join'┼')┤"
$d|%{$i=$_;"│$(($h|%{$i.$_.PadRight($_.c)})-join'│')│"}
"└$(($h|%{'─'*$_.c})-join'┴')┘"
```
I feel like this could be improved a lot but I ran out of time. All line endings are `\n` with no `\r`, encoding is UTF8 with no BOM.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~36~~ 25 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Assumes that `ABCDEFGHIJKLMNOPQRSTUVWXYZ` is the CSV file. Prints to stdout.
```
⌂disp(1↑m)⍪↑¨↓⍉1↓m←⎕CSV⎕A
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmv8airSd0vMTdVxzE9VccdJFikrqAenJFYmqdjaKnjm5iTCuS7pCYVJYL4bqm5EBHHnMQ8HSMzmAL31PwioAGGphABzUd9U/0CQkOAlCMX16OO9oL/j3qaUjKLCzQMH7VNzNV81LsKSB9a8aht8qPeTqDY5NxHbROAyp2Dw0Ca/gP1/FcAgwIA "APL (Dyalog Extended) – Try It Online")
`⎕A` the uppercase **A**lphabet (the shortest-to-reference built-in string)
`⎕CSV` read that file and convert from CSV to matrix
`m←` store as `m` (for **m**atrix)
`1↓` drop the first row
`⍉` transpose
`↓` split into list of columns
`↑¨` mix each list of strings into a matrix
`(`…`)⍪` stack the following on top of that:
`1↑m` take the first row of `m`
`⌂disp` apply [`dfns.disp`](http://dfns.dyalog.com/n_disp.htm) to that
(draws line drawing characters)
[Answer]
# JavaScript, 261 bytes
```
(t,[H,...D]=T=t.split`
`.map(r=>r.split`,`),w=H.map((_,i)=>Math.max(...T.map(r=>r[i].length))),L=(x,i,_,[[[a,b=a,c=a]],p]=1/i?`│`:[x,'─'])=>a+w.map((n,j)=>(p?'':x[j]).padEnd(n,p)).join(b)+c+`
`)=>L`┌┬┐`+L(H,0)+L`├┼┤`+D.map(L).join``+L`└┴┘`
```
[Try it online!](https://tio.run/##PZAxT8MwEIX3/Aq22MphKBJItHKrSoV2SFnoFkW1m7ito8SJUkMzImYGBg8dGBkZGfk1/iPBbRDj9969d6fL@DPfJbWs9LkqU9Guz2iLNEQzIIRMYrqgmuyqXGrmMVLwCtV0WP8pwDDs6ewkoyVITIdzrreOG@TSi//5SMYkF2qjtxhjCClqQMISoijisKIcEsrjGKqY9i7kiFnzyvpRA741L37sSnmw73YoyByiauT7/SbKYkwqnt6p1BkVxiQrpUIrHCSBO9YNhq7qzZova95ZEKIZXOLgqH1Y82PNJwsmp9qwSzJ2Mo0139YcWDvwvKRUuzIXJC83aI2Y98ALAeONgKlQqai9xy1/UtC7hTnPhTcRq5of6V4URx7nXMHVTWdORVm7YO@6Q0Z0LQvk3jFofwE "JavaScript (Node.js) – Try It Online")
## Ungolfed and explained
```
(
tableCSV,
[header, ...data] = table = tableCSV.split(`\n`).map(row => row.split(`,`)),
widths = header.map((_, i) => Math.max(...table.map(row => row[i].length))),
drawLine = ( // create data row or border
x, // either data array or singleton string array
i, // either data index or undefined
_, // ignored (data.map(drawLine) sets this to data)
[[[a, b = a, c = a]], pad] = 1 / i ? `│` : [x, '─']
// a = start, b = separator, c = end, pad = '─' if making border
) =>
a +
widths.map((n, j) => (pad ? '' : x[j]).padEnd(n, pad)).join(b) +
c +
`\n`
) =>
drawLine`┌┬┐` +
drawLine(header, 0) +
drawLine`├┼┤` +
data.map(drawLine).join(``) +
drawLine`└┴┘`
```
[Answer]
## Racket 578 bytes
```
(let*((ll(map(λ(x)(string-split x","))ll))(lr list-ref)(sl string-length)(d display)(dl displayln)(nc(length(lr ll 0)))
(nl(for/list((i nc))(apply max(for/list((j ll))(sl(lr j i))))))(pl(λ(sy)(d(lr sy 0))(for((n nc))(for((m(lr nl n)))(d(lr sy 1)))
(if(< n(sub1 nc))(d(lr sy 2))(dl(lr sy 3))))))(g(λ(i n)(for((m(-(lr nl n)(sl i))))(d" ")))))(pl'("┌""─""┬""┐"))
(for((i(lr ll 0))(n(in-naturals)))(d"│")(d i)(g i n))(dl"│")(pl'("├""─""┼""┤"))(for((j(range 1(length ll))))
(for((i(lr ll j))(n nc))(d"│")(d i)(g i n))(dl"│"))(pl'("└" "─" "┴" "┘")))
```
Ungolfed:
```
(define(f1 ll)
(let* ((ll (map (λ (x)(string-split x ",")) ll)) ; use this to convert csv format to list of lists;
(lr list-ref) ; make short names of standard fns
(sl string-length)
(d display)
(dl displayln)
(nc (length (lr ll 0))) ; number of cols;
(nl(for/list ((i nc)) ; get list of max string-length for each column
(apply max
(for/list ((j ll))
(sl (lr j i))
))))
(pl (λ (sy) ; put lines using sent symbol list
(d (lr sy 0))
(for ((n nc))
(for ((m (lr nl n))) (d (lr sy 1)))
(if (< n (sub1 nc))
(d (lr sy 2))
(dl (lr sy 3))
))))
(g (λ (i n) ; pad with spaces if needed
(for ((m (- (lr nl n) (sl i)))) (d " ")) )))
; put line above header:
(pl '("┌" "─" "┬" "┐"))
; put header:
(for ((i (lr ll 0)) (n (in-naturals)))
(d "│")
(d i)
(g i n)
)
(dl "│")
; put line below header;
(pl '("├" "─" "┼" "┤"))
; put rows:
(for ((j (range 1 (length ll))))
(for ((i (lr ll j))
(n nc))
(d "│")
(d i)
(g i n)
)
(dl "│")
)
; put bottom line:
(pl '("└" "─" "┴" "┘"))
))
```
Testing:
```
(f (list "Name,Age,Gender"
"Shaun,19,Male"
"Debra,19,Female"
"Alan,26,Male"
"George,15,Male"))
```
Output:
```
┌──────┬───┬──────┐
│Name │Age│Gender│
├──────┼───┼──────┤
│Shaun │19 │Male │
│Debra │19 │Female│
│Alan │26 │Male │
│George│15 │Male │
└──────┴───┴──────┘
```
[Answer]
# JavaScript (ES6|FireFox), 286 bytes
```
f=>(d=f.split`
`.map(a=>a.split`,`),s=d[0].map((a,i)=>d.reduce((b,c)=>(n=c[i].length)>b?n:b,0)),d=d.map(a=>`│${a.map((b,i)=>b.padEnd(s[i])).join`│`}│`),d.splice(1,0,(g=h=>h[0]+s.map(a=>'─'.repeat(a)).join(h[1])+h[2])('├┼┤')),g('┌┬┐')+`
${d.join`
`}
`+g('└┴┘'))
```
Uses `padEnd`, which is FireFox specific.
[Answer]
# JavaScript (ES6), 281 bytes
Note: input as a single string with newlines - as requested by OP. Other answers use a string list - using a string array in input I can avoid the first split and cut 9 bytes.
```
l=>(l=l.split`
`.map(r=>r.split`,`.map((w,i)=>(v=w.length)<c[i]?w:(c[i]=v,w)),c=[k=0]),l=l.map(r=>r.map((v,i)=>(v+' '.repeat(c[i]-v.length)))),[h=c.map(x=>'─'.repeat(x)),l.shift(),h,...l,h].map(a=>'│┌├└'[j=a!=h?0:++k]+a.join('│┬┼┴'[j])+'│┐┤┘'[j]).join`
`)
```
*Less golfed*
```
l=>(
// split input in an array of string arrays
// meanwhile find the column widths and put them in *c*
l = l.split`\n`.map(r=>r.split`,`.map((w,i)=>(v=w.length)<c[i]?w:(c[i]=v,w)),c=[]),
// pad each column to the max column width
l = l.map(r=>r.map((v,i)=>(v+' '.repeat(c[i]-v.length)))),
// put in *h* the horizontal lines for top,bottom and head separator
h = c.map(x => '─'.repeat(x) ),
// add the *h* line at top, bottom and after head line
l = [h, l.shift(), h, ...l, h],
// rebuild a string, joining columns with '|' unless the row is *h*
// if the row is *h* use different characters to join columns
k = 0,
l.map(a=> '│┌├└'[j=a!=h?0:++k] + a.join('│┬┼┴'[j]) + '│┐┤┘'[j])
.join`\n`
)
```
**Test**
```
F=
l=>(l=l.split`
`.map(r=>r.split`,`.map((w,i)=>(v=w.length)<c[i]?w:(c[i]=v,w)),c=[k=0]),l=l.map(r=>r.map((v,i)=>(v+' '.repeat(c[i]-v.length)))),[h=c.map(x=>'─'.repeat(x)),l.shift(),h,...l,h].map(a=>'│┌├└'[j=a!=h?0:++k]+a.join('│┬┼┴'[j])+'│┐┤┘'[j]).join`
`)
function update() {
O.textContent = F(I.value)
}
update()
```
```
#I { width:60%; height: 8em}
```
```
<textarea id=I>Name,Age,Gender
Shaun,19,Male
Debra,19,Female
Alan,26,Male
George,15,Male</textarea><br>
<button onclick='update()'>Go</button>
<pre id=O></pre>
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) for Windows, ~~256...236~~ 238 bytes
```
$v=$args-split'
'-ne''|%{,($_-split',')}
function z($b,$a){$b[1]+(($v[0]|%{@($a)[$x++]+''|% p*ht($v|%{$_[$x-1]}|% le*|sort -b 1)$b[0]})-join$b[2])+$b[3]}
z '─┌┬┐'
$v|%{z ' │││'$_;if(!$r++){z '─├┼┤'}}
z '─└┴┘'
```
[Try it online!](https://tio.run/##RYxBS8MwGIbv@RURImmWFNaJgojQgbiTXjyWUFLN1kqWlrSbsq4gnj14yGEHjx49evTX5I/UzCpC4Mv7vLxPVT5IU@dSqb5H63MkzKIO60oVDQY41BLj7WHLApT@QoZJB@YrfdsUpYabAGUMCdKiLIk4DQK0TsbcL@LA0wQ9UsrpXgGrUd741lco9TyMeOepkqNtXZoGhhmMiJeMeUfC@7LQ/j/hhPpzxDuwgdjZJ2dfnP1w9hWDH5On0Nnn4WGUnhXz4AAZSkn7N3hz9svZd9z9O6yzn87ucN/3MQbXYinZdCHZTOo7acBNLlaaRafsSigJLmRmxD5dyuU@T5XQbHIylDNZGj@MjocIcPwN "PowerShell – Try It Online")
Notes:
* The `Sort` alias defined for Windows only. It need `Sort-Object` for Linux instead `sort` or command `set-alias sort sort-object` before this script (TIO way).
* The `p*ht` shortcut expands to the `PadRight`-method for a string.
* The `le*` shortcut expands to the `Length`-method for a string.
An input csv contains:
* comma and newline are delimiters only (no comma and no newline inside values|headers)
* spaces in the values|headers are significant letter (keep due justifying)
* at least 2 not empty lines (headers and values)
* an "optional\_newline" at the end
* optional empty values|headers
* optional empty inner lines
[Answer]
# [JavaScript (V8)](https://v8.dev/), 291 bytes
```
d=>([h]=r=d.split`
`.map(s=>s.split`,`),l=h.map((_,i)=>Math.max(...r.map(k=>k[i].length))),s=([[x,y,z]])=>h.reduce((a,_,i)=>a+"─".repeat(l[i])+(i==h.length-1?z:y),x)+`
`,[f,...t]=r.map(r=>r.reduce((s,x,i)=>s+x.padEnd(l[i])+z,z="│")+`
`),s`┌┬┐`+f+s`├┼┤`+t.join``+s`└┴┘`)
```
[Try it online!](https://tio.run/##PZC9TsMwFIX3PEYnW7m1VCQQUDmoEtCpLIxRhE3jNGmdH9lplWZCzAwMHhgYGRkZeRq/SHCSivGcq/Odo7vlB67XKqvq6eGyS2gX0wCFaUQVjYmuZFYzj5GcV0jTQJ8cYBgkTQcbPUGGabDida8bRAhRw2FHg12YRUSKYlOnGGPQFIVhA0doo8hFUqJEvF8LhDiMEO5PrHmZOL8SvEbSxbGPMuqqRsp0dtNeHzE02HezIEzA1dVu7NCoaKD@mRqagan9hlQ8viviE6@Flrqa18nAcKuYNW/WfFvzzvzE7@WnNb/WfDG/JtsyKxgbXGPNjzUfDHdzz1uXhS6lILLcoAQx74HnAhYbAUtRxEJ5jynfFzC7ghWXwrsVz4r36l7kvV5IXsDZxXhcilK54Ox8lIzUKsuRe9i8@wM "JavaScript (V8) – Try It Online")
Not exactly a competitive score compared to the three other answers written in JS (???), but its as good as I can do.
Ungolfed/explained:
```
csvString => (
// convert the string into an array of row content arrays (string[][])
// extracting first element h to save a few bytes off of r[0] later
[h] = rows = d.split(`\n`).map(s=>s.split(`,`)),
// get the lengths of the longest entry of each column
columnLengths = h.map((_, i) => Math.max(...rows.map(row => row[i].length))),
// build strings for the top line, header separator, and bottom line
// [[x,y,z]] to extract chars from tagged template literal
// "─" repeated by the length of the column + correct separator if
// last/middle character
buildLine = ([[x,y,z]]) => h.reduce(
(a,_,i) =>
a + "─".repeat(columnLengths[i]) + (i === h.length - 1 ? z : y),
x
) + `\n`,
// get lines that contain data seperated by "│" - f is header, t is rest
[header, ...rest] = rows.map(row =>
row.reduce((s, x, i) => s + x.padEnd(l[i]) + z, z = "│") + `\n`
),
// final return value: top row + header + header separator + rest of
// data + bottom row
buildLine`┌┬┐` + header + buildLine`├┼┤` + rest.join("") + buildLine`└┴┘`
)
```
[Answer]
# Python 3, 318 bytes
-3 bytes for using the `%` formatting and -1 for abbreviating `str.join`
```
L=[c.split(',')for c in input().split('\n')]
m=[max(len(x)for x in c)for c in zip(*L)]
L=[[""]+[d.ljust(n)for d,n in zip(c,m)]+[""]for c in L]
g=["─"*i for i in m]
J=str.join
print('\n'.join(["┌%s┐"%J("┬",g),J("│",L[0]),"├%s┤"%J("┼",g)]+[J("│",L[i])for i in range(1,len(L))]+["└%s┘"%J("┴",g)]))
```
Requires input enclosed in quotes.
[Answer]
# C#, 696 Bytes
Golfed:
```
string T(string[]f){int w=f.Max(r=>r.Length),a=f.Select(r=>r.Split(',')[0].Length).Max(),b=f.Select(r=>r.Split(',')[1].Length).Max(),c=f.Select(r=>r.Split(',')[2].Length).Max();string o="",n="\r\n",d="",j=string.Concat(Enumerable.Repeat("─",a)),k=string.Concat(Enumerable.Repeat("─",b)),l=string.Concat(Enumerable.Repeat("─",c));Func<string,int,string>z=(q,p)=>{return q.PadRight(p);};d="┌"+j+"┬"+k+"┬"+l+"┐";o+=d+n;var g=f.First().Split(',');o+="|"+z(g[0],a)+"|"+z(g[1],b)+"|"+z(g[2],c)+"|";d="├"+j+"┼"+k+"┼"+l+"┤";o+=n+d+n;for(int i=1;i<f.Length;i++){var h=f[i].Split(',');o+="|"+z(h[0],a)+"|"+z(h[1],b)+"|"+z(h[2],c)+"|"+n;}d="└"+j+"┴"+k+"┴"+l+"┘";o+=d;return o;}
```
Ungolfed (and nicer, because ^that is no use to anyone):
```
public string T(string[] c)
{
int width = c.Max(r => r.Length),
longestFirstColumn = c.Select(r => r.Split(',')[0].Length).Max(),
longestSecondColumn = c.Select(r => r.Split(',')[1].Length).Max(),
longestThirdColumn = c.Select(r => r.Split(',')[2].Length).Max();
string o = "", lr = "\r\n", border = "",
firstColumnFiller = string.Concat(Enumerable.Repeat("─", longestFirstColumn)),
secondColumnFiller = string.Concat(Enumerable.Repeat("─", longestSecondColumn)),
thirdColumnFiller = string.Concat(Enumerable.Repeat("─", longestThirdColumn));
Func<string, int, string> padRight = (a, b) => { return a.PadRight(b); };
border = "┌" + firstColumnFiller
+ "┬" +
secondColumnFiller + "┬"
+ thirdColumnFiller
+ "┐";
o += border + lr;
var firstRow = c.First().Split(',');
o += "|" + padRight(firstRow[0], longestFirstColumn) +
"|" + padRight(firstRow[1], longestSecondColumn) +
"|" + padRight(firstRow[2], longestThirdColumn) + "|";
border = "├" +
firstColumnFiller + "┼" +
secondColumnFiller + "┼" +
thirdColumnFiller
+ "┤";
o += lr + border + lr;
for (int i = 1; i < c.Length; i++)
{
var row = c[i].Split(',');
o += "|" + padRight(row[0], longestFirstColumn) + "|"
+ padRight(row[1], longestSecondColumn) + "|" +
padRight(row[2], longestThirdColumn) + "|" + lr;
}
border = "└" +
firstColumnFiller + "┴" +
secondColumnFiller + "┴" +
thirdColumnFiller
+ "┘";
o += border;
return o;
}
```
Testing:
```
┌──────┬───┬──────┐ ┌──────────┬───────────────────────────┬─────┐
|Name |Age|Gender| |Name |PPCG Challenge |Votes|
├──────┼───┼──────┤ ├──────────┼───────────────────────────┼─────┤
|Shaun |19 |Male | |Pete Arden| Print all integers | 4 |
|Debra |19 |Female| |Pete Arden| Yes of course I'm an adult| 3 |
|Alan |26 |Male | |Pete Arden| 5 Favorite Letters | 1 |
|George|15 |Male | └──────────┴───────────────────────────┴─────┘
└──────┴───┴──────┘
```
[Answer]
# Perl, 273 + 9 (`-CS -nlaF,` flags) = 282 bytes
```
$v[$.-1]=[@F];map$l[$_]<($l=length$F[$_])&&($l[$_]=$l),0..$#F}sub p{printf$p,@_}sub o{p
pop,map{$\x$l[$_],$_-$#l?$_[0]:pop}0..$#l}$p=join'%s','',(map"\%-${_}s",@l),$/;($\,$c,@c)=map
chr$_*4+9472,0,.5,3..15;o@c[8,1,0];p($c,map{$_,$c}@$_),$i++||o@c[12,6,4]for@v;o@c[10,3,2];{
```
Using:
```
cat file.csv | perl -CS -nlaF, script.pl
```
Try it on [Ideone](http://ideone.com/bFtC4P).
[Answer]
# PHP, 313 bytes
```
for(;$r=fgetcsv(STDIN);$a[]=$r)foreach($r as$x=>$s)$e[$x]=max($e[$x],strlen($s));$t=["┬","┌","┐"];eval($L='foreach($e as$i=>$n)echo$t[!$i],str_repeat("─",$n);echo"$t[2]\n";');foreach($a as$k=>$r){foreach($r as$i=>$s)echo"│",str_pad($s,$e[$i]);echo"│\n";$t=["┼","├","┤"];if(!$k)eval($L);}$t=["┴","└","┘"];eval($L);
```
**breakdown**
```
for(;$r=fgetcsv(STDIN);$a[]=$r) // read csv from STDIN, append to array $a
foreach($r as$x=>$s)$e[$x]=max($e[$x],strlen($s)); // remember max length in array $e
// print top border
$t=["┬","┌","┐"];eval($L='foreach($e as$i=>$n)echo$t[!$i],str_repeat("─",$n);echo"$t[2]\n";');
foreach($a as$k=>$r)
{
foreach($r as$i=>$s)echo"│",str_pad($s,$e[$i]);echo"│\n"; // print row
$t=["┼","├","┤"];if(!$k)eval($L); // print border below header
}
$t=["┴","└","┘"];eval($L); // print bottom border
```
[Test it at ideone](http://ideone.com/md4yY3)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 588 bytes
```
#define H char
P(c,n){for(H*s[]={"\n","┌","┬","┐","├","┼","┤","└","┴","┘","─","│"};n--;)printf("%s",s[c]);}S(s,n)H*s;{printf("%-*s",n,s);}E(n,c,Z,i)int*Z;{for(i=P(3*n+1,1);i<c;P(3*n+(++i-c?2:3),1))P(10,Z[i]);P(0,1);}V(t,c,Z,r,i)H**t;int*Z;{for(i=P(11,1);i<c;i++,P(11,1))S(t[i+r],Z[i]);P(0,1);}f(s,p)H*s,*p;{int r,R,C,i,m,L;R=C=i=m=r=0;for(p=s;*p;*p++==44&&C++)!(p[1]&&*p^10)&&R++;C/=R;H*t[R*++C];for(p=s;i<R*C;*p++=0)for(t[i++]=p;*p^44&&*p^10;)p++;int Z[C];for(i=0;i<C;Z[i++]=m)for(m=r=0;r<R;m=m<L?L:m)L=strlen(t[i+C*r++]);E(0,C,Z);V(t,C,Z,0);for(E(i=1,C,Z);i<R;)V(t,C,Z,C*i++);E(2,C,Z);}
```
[Try it online!](https://tio.run/##XVI9j9NAEO3zK4wR0X5MhJ07ELnN6nQy4VIEFPkkCvt8kvFtjpXijbX2FSiKhKgpKK6goKSkpOTX8EfC7DqkOBfPO/Nm3nteuRrdVdV@//RWrbRRwTyoPpZ2sCQVGLpdbSyZszYv5Da8NiGEfx@@evzl8ZvHHx7/ePzp8cHjb4/fPX72@CXcCTMaCdpYbboVCZ@1IbR5VVCxuyItOqKZ2B7ZEUPeQIv0jBioIANNkWOZ8NG0XJITZngMMRV6Wom@JJzrUXU@PjuhSNAliSPIco0uSxK50d170nk1i3pzxjrxSDQ@KmrO4VDTK9LlmtvikdgKkzcuObBGbFEpsJBCAhpqWIhUJlLLWloZCSffyFbgHGs4l/L0dDhMOKdPSJPHxXDImps4osNhyrlInstUzFmXp4zzpDgu62nKkn4/oq7pQvFCOs0bJ@hF8I5Rw4XJ8sOyxgR6moisn6/9ch/MTlNRy3q6OF@c1XQh286ulfHKCbM4TcUMvzaBjAp3d3iAiHrVGerGPYPJBP1PJwxd3Nq4J3d7F6YutSF0sB0E@Lg/LUCrfDKZFMK3sKqaTwRfEITvylrBxZ2CS2Vulb02rze1NrqC@BW8LdcKG@qDLSGewBtV@8bFujQwfnmgL9XG4nr84lCHtHdZOYPD2aru3pogEoPd/h8 "C (gcc) – Try It Online")
] |
[Question]
[
# Introduction
Most code-golfers here add explanations to their submissions, so it's easier to understand what's going on. Usually the codelines go on the left and the corresponding explanation to the right with some kind of separator. To make it look pretty, the separators are all on the same column. Also long explanation text is usually wrapped to the next line, so the readers don't have to scroll horizontally to read everything.
However, when you want to edit this explanation because you made some crazy golfs, you often end up spending time to make your explanation pretty again. Since this is a very repetitive task, you want to write a program for this.
# The Challenge
Given several lines of code with explanation and a separator, output the nicely formatted code with explanation.
### Example
**Input**
```
shM-crz1dc4."ANDBYOROF # z = input
rz1 # convert input to uppercase
c d # split input on spaces
c4."ANDBYOROF # create a list of the words from a packed string which shall be ignored
- # filter those words out
hM # only take the first letter of all words
s # join them into one string
```
**Output**
```
shM-crz1dc4."ANDBYOROF # z = input
rz1 # convert input to uppercase
c d # split input on spaces
c4."ANDBYOROF # create a list of the words from a packed string which shall be
# ignored
- # filter those words out
hM # only take the first letter of all words
s # join them into one string
```
*One cookie for the first one who can find out what this code does.*
### The formatting algorithm
* Find the longest code-line (excluding the explanation and the spaces between code and separator).
* Add 5 spaces after this code-line and append the corresponding separator with explanation. This is now the reference line.
* Adjust every other line to this reference line, so that the seperators are all in the same column.
* Wrap all lines that are longer than 93 characters to a new line in the following way:
+ Find the last word which end is at column 93 or lower.
+ Take all words after this one and wrap them to a new line with the leading separator and the correct spacing. The space between those two words has to be deleted, so the first line ends with a word character and the second line starts with one after the separator.
+ If the resulting line is still longer than 93 characters do the same again until every line is below 94 characters.
### Notes
* A word consists of non-whitespace characters. Words are separated by a single space.
* The word wrapping is always possible. This means that no word is so long that it would make the wrapping impossible.
* The input will only contain printable ASCII and won't have any trailing whitespaces
* The separator will only appear once per line.
* While the explanation can have unlimited length, the separator and the code can only have a combined maximum length of `93 - 5 = 87` chars. The 5 chars are the spaces between code and separator. Code and separator will always be at least one character long.
* The input may contain empty lines. Those will never contain any characters (except a newline if you take input as multiline string). Those empty lines have to be present in the output as well.
* Every line will have some code, a separator and an explanation. Exceptions are empty lines.
* You may take the input in any reasonable format, as long as it is not pre-processed. Make it clear in your answer which one you use.
* Output can be a multiline string or a list of strings.
# Rules
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
Input format here is a list of string representing the lines and a single string for the separator. Both are separated by a comma. Output is a list of strings.
```
['shM-crz1dc4."ANDBYOROF # z = input', '', ' rz1 # convert input to uppercase', ' c d # split input on spaces', ' c4."ANDBYOROF # create a list of the words from a packed string which shall be ignored', ' - # filter those words out', ' hM # only take the first letter of all words', 's # join them into one string'], "# " -> ['shM-crz1dc4."ANDBYOROF # z = input', '', ' rz1 # convert input to uppercase', ' c d # split input on spaces', ' c4."ANDBYOROF # create a list of the words from a packed string which shall be', ' # ignored', ' - # filter those words out', ' hM # only take the first letter of all words', 's # join them into one string']
['codecodecode e#Explanation', 'sdf dsf sdf e#A Very very very very very very very very very long long long long long long long long long long long explanation and it keeps getting longer and longer', '', 'some more codee# and some more explanation'], "e#" -> ['codecodecode e#Explanation', 'sdf dsf sdf e#A Very very very very very very very very very long long long long long ', ' e#long long long long long long explanation and it keeps getting longer', ' e#and longer', '', 'some more code e# and some more explanation']
```
**Happy Coding!**
[Answer]
# LiveScript, ~~243~~ ~~236~~ ~~233~~ ~~228~~ ~~219~~ 225 bytes
```
f = (x,k,m+5)->l=(.length);x.=map(->it/"#k"=>..0-=/ +$/;m>?=5+l ..0);i=0;[..0&&..0+' '*(m- l ..0)+k+..1 for x]=>while i<(l ..),++i=>j=(s=..[i])lastIndexOf ' ' 93;(..splice i+1 0 ' '*m+k+s[j to]*'';s.=substr 0 j) if 94<l s;..[i]=s
```
How it works: mostly like the Java code. Start off by aliasing length (LiveScript allows to create a function from operators by using parentheses).
`.=` is `a = a.b` - which we use here to map.
`=> blabla ..` is the Smalltalk-ish cascade construct: the left side of `=>` is accessible as `..` for the rest of the block; and will be returned. Here, it's the element split on k. Note: I'm using string interpolation, because `/` only means "split" with a literal string.
LS allows us to use `a-=/regexp/` in this lambda as well (also works with string literals): it's just sugar for a `.replace` call.
Finally, the `>?=` is the combinatory `>?`-assign operator, which returns the greater of two operands.
LS has Python/Haskell-style for comprehensions, with nothing fancy in them, except the "string \* times" to repeat the space long enough.
This for comprehension serves as the topic (see the block about cascades anove).
We then loop into each element of the array (the one we just built with the comprehension), and if any line is bigger than 93chars, we find the last index of , split there, and push the separated line right after this current iteration's (... So that the next iteration will split again if the line's too big).
Only last thing fancy `a[j to]` is a range (from j to the end), but since it uses Array methods we have to join it back to a string, which we do using overloaded `*`: `*''`.
example
```
s = """this is kod # Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
d # y
efgh # z"""
f = (x,k,m=5)->l=(.length);x.=map(->it/"#k"=>..0-=/ +$/;m>?=5+l ..0);i=0;[..0&&..0+' '*(m- l ..0)+k+..1 for x]=>while i<(l ..),++i=>j=(s=..[i])lastIndexOf ' ' 93;(..splice i+1 0 ' '*m+k+s[j to]*'';s.=substr 0 j) if 94<l s;..[i]=s
console.log (f s / '\n', '#') * \\n
```
output:
```
this is kod # Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
# tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
# veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
# commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
# velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
# cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
# est laborum.
d # y
efgh # z
```
[Answer]
## Java, 347 + 19 = 366 bytes
Requires
```
import java.util.*;
```
Thus the +19 bytes.
```
(c,s)->{int p=0,i=0,t;String l;for(;i<c.size();i++){l=c.get(i);l=l.replaceAll(" *"+s,s);p=Math.max(l.indexOf(s),p);c.set(i,l);}p+=5;for(i=0;i<c.size();i++){l=c.get(i);t=l.indexOf(s);while(t>-1&t<p)l=l.substring(0,t)+" "+l.substring(t++);t=93;if(l.length()>t){while(l.charAt(t)!=' ')t--;c.add(i+1,s+l.substring(t));l=l.substring(0,t);}c.set(i,l);}}
```
Takes in the format `f.accept(List<String> code, String seperator)`. Formats in-place. A version that creates and returns a new `List<String>` would be trivial to implement but cost some bytes.
Indented + example usage:
```
static BiConsumer<List<String>, String> prettify = (code, seperator) -> {
int space = 0, i=0, t;
String line;
for (; i<code.size(); i++) { // for each line
line = code.get(i); // get line
line = line.replaceAll(" *" + seperator, seperator); // strip space before seperator
space = Math.max(line.indexOf(seperator), space); // save biggest space until seperator
code.set(i, line); // save line
}
space += 5;
for (i=0; i<code.size(); i++) { // for each line
line = code.get(i); // get line
t = line.indexOf(seperator); // get index of seperator
while (t>-1&t<space) // while the seperator exists and is further left than desired
line = line.substring(0,t) + " " + line.substring(t++); // move it right by adding a space before it
t = 93; // get desired line length
if (line.length()>t) { // if the line is longer than that
while (line.charAt(t)!=' ') t--; // scan backwards for a space
code.add(i+1, seperator + line.substring(t)); // add a line after this one with seperator and the rest of the line
// the next pass will space it correctly
line = line.substring(0,t); // cut off this line at that point
}
code.set(i, line); // save edited line back to List
}
};
public static void main(String[] args) {
List<String> code = new ArrayList<>();
code.add("shM-crz1dc4.\"ANDBYOROF # z = input");
code.add("");
code.add(" rz1 # convert input to uppercase");
code.add(" c d # split input on spaces");
code.add(" c4.\"ANDBYOROF # create a list of the words from a packed string which shall be ignored");
code.add(" - # filter those words out");
code.add(" hM # only take the first letter of all words");
code.add("s # join them into one string");
prettify.accept(code, "#");
code.stream().forEach(System.out::println);
}
```
... I should probably run this through itself :P
[Answer]
# Ruby, ~~245~~ ~~237~~ ~~220~~ ~~216~~ ~~212~~ ~~209~~ 205 bytes
Anonymous function. Pretty basic approach (find max length, add 5, then do processing on each line, with recursion to deal with wrapping) and there might be another approach that saves more bytes.
I deleted the answer earlier that didn't fulfill all the requirements; I didn't want to have a half-answered code as an answer (it was getting downvotes for being incomplete too) but it should do everything the question asks for, now.
```
->x,d{l,S=0," "
s=->n{m,q=n.size,94-l-d.size
m>q ?(i=n.rindex(S,q)
n[0,i]+"
"+S*l+d+s[n[i+1,m]]):n}
x.map{|n|c,t=n.split d
c=(c||S).rstrip
l=[l,5+c.size].max
[c,t]}.map{|c,t|c+S*(l-c.size)+d+s[t]if t}*"
"}
```
---
### Changelog:
* Saved some bytes by leveraging some of the promises in the input, especially the promise that all non-empty lines have the separator character and an explanation.
* Managed to golf a little more by saving the split strings from the first `map` call and taking out some unnecessary `strip` functions based on the promise that the words in the explanation always have exactly one space between them. Also, `" "` is assigned to a constant now since I use it so much.
* Chained both of the `map` calls together by leveraging the power of higher-order functions, meaning that the first map call will set the length variable `l` correctly even if it's called after the declaration of the helper function `s`. -4 bytes.
* Abused multiline strings to replace `\n` with actual newlines, plus a little trick using `if` over ternary operators (when `join` is called on an array with `nil` values, they become empty strings)
* `.join` can apparently be replaced with a `*`.
[Answer]
# PowerShell, ~~224~~ ~~217~~ 235 bytes
```
param($d,$s)$d=$d-split"`r`n";$p="\s+\$([char[]]$s-join"\")\s";$m=($d|%{($_-split$p)[0].Length}|sort)[-1];$d|%{$l,$c=$_-split$p;$c=if($c){"$s "+(("$c "-split"(.{1,$(87-$m)})\s"|?{$_})-join"`n$(" "*($m+5))$s ")}$l.PadRight($m+5," ")+$c}
```
Updated the logic to determine the max code string length. Updated to allow multiple separators that include regex meta characters.
---
**Little Explanation**
This takes in a whole newline delimited string for input.
```
param($d,$s)
# $d is a newline delimited string. $s is the separator.
# Take the string and turn it into a string array. Stored as $d
$d=$d-split"`r`n"
# Save a regex pattern as it is used more than once
$p="\s+\$([char[]]$s-join"\")\s"
# Get the longest string of code's length
$m=($d|%{($_-split$p)[0].Length}|sort)[-1]
# Split each line again into code and comment. Write out each line with formatted explanations based on separator column position $m
$d|%{
# Split the line
$l,$c=$_-split$p
# Build the comment string assuming there is one.
$c=if($c){"$s "+(("$c "-split"(.{1,$(87-$m)})\s"|?{$_})-join"`n$(" "*($m+5))$s ")}
# Pad the right amount of space on the code and add the comment string.
$l.PadRight($m+5," ")+$c
}
```
**Sample Output with some Lorem Ipsum**
```
shM-crz1dc4."ANDBYOROF # z = input
rz1 # convert input to uppercase
c d # split input on spaces
c4."ANDBYOROF # But I must explain to you how all this mistaken idea of
# denouncing pleasure and praising pain was born and I will give
# you a complete account of the system, and expound the actual
# teachings of the great explorer
- # filter those words out
hM # only take the first letter of all words
s # join them into one string
```
[Answer]
# MATLAB, ~~270~~ ~~265~~ 262 bytes
```
function d=f(I,s);S=@sprintf;R=@regexprep;m=regexp(I,['\s*\',s]);L=max([m{:}])+4;a=@(x)S('%-*s%s',L,x,s);b=@(x)R(R(x,S('(.{1,%d}(\\s+|$))',93-L),S('$1\n%*s ',L+1,s)),['\n\s*\',s,' $'],'');c=R(I,['(.*?)\s*\',s,'\s*(.*$)'],'${a($1)} ${b($2)}');d=S('%s\n',c{:});end
```
The program accepts the input `I` in the form of a cell array of strings where each element of the cell array is a separate line of the input. It also accepts a second input which indicates what the comment character is (i.e. `#`). The function returns a multi-line string that is properly formatted.
**Brief Explanation**
```
function d = f(I,s)
%// Setup some shortcuts for commonly-used functions
S = @sprintf;
R = @regexprep;
%// Find the location of the space AFTER each code block but before a comment
m = regexp(I, ['\s*\',s]);
%// Compute the maximum column location of the code and add 4 (5 - 1)
L = max([m{:}]) + 4;
%// This is a callback for when we detect code
%// It left justifies and pads the string to L width
a = @(x)S('%-*s%s', L, x, s);
%// This is a callback for when we detect a comment.
b = @(x)R(...
R(x, ...
S('(.{1,%d}(\\s|$))', 93 - L), ... Regex for wrapping text to desired width
S('$1\n%*s ', L+1, s)), ... Append a newline and padding for next line
['\n\s*\',s,' $'], ''); ... Remove the trailing newline (to be improved)
%// Perform replacement of everything.
c = R(I, ...
['(.*?)\s*\',s,'\s*(.*$)'], ... Match "code comment_char comment"
'${a($1)} ${b($2)}'); ... Replace using the output of the callbacks
%// Concatenate all of the strings together with a newline in between
d=S('%s\n',c{:});
end
```
**Example Input**
```
I = {
'shM-crz1dc4."ANDBYOROF # z = input'
''
' rz1 # convert input to uppercase'
' c d # split input on spaces'
' c4."ANDBYOROF # create a list of the words from a packed string which shall be ignored'
' - # filter those words out'
' hM # only take the first letter of all words'
's # join them into one string'
};
disp(f(I,'#'));
```
**Example Output**
```
shM-crz1dc4."ANDBYOROF # z = input
rz1 # convert input to uppercase
c d # split input on spaces
c4."ANDBYOROF # create a list of the words from a packed string which shall be
# ignored
- # filter those words out
hM # only take the first letter of all words
s # join them into one string
```
] |
[Question]
[
Australians love public holidays, and drinking. Yesterday, the 26th January, was Australia day, which is a public holiday. I was glad to not be at work yesterday, and eager to know the next time I get a public holiday! Unfortunately, I had a bit too much to drink, and I'm not able to work it out for myself.
Write a program that will take a [date in Australian date/time notation](https://en.wikipedia.org/wiki/Date_and_time_notation_in_Australia) (dd/mm) as input, and output the amount of days until the next public holiday. Because I'm a Queensland (QLD) resident, I'm only interested in [public holidays that affect Queenslanders](http://www.australia.gov.au/about-australia/special-dates-and-events/public-holidays):
>
> 25/03 | Good Friday
>
> 26/03 | Easter Saturday
>
> 28/03 | Easter Monday
>
> 25/04 | Anzac Day
>
> 02/05 | Labour Day
>
> 03/10 | Queen's Birthday
>
> 25/12 | Christmas Day
>
> 26/12 | Boxing Day
>
> 27/12 | Christmas Day holiday
>
>
>
Note the following from the site:
>
> ### Christmas Day holiday
>
>
> An additional public holiday to be added when New Year's Day, Christmas Day or Boxing Day falls on a weekend.
>
>
>
Because Christmas day is on Sunday, there is an **extra** public holiday. Christmas day is still a public holiday.
Because I'm a morning person, you should include the current date as a day (as that's the most likely time I will check your program for the next public holiday). That is, if a public holiday's date is entered, your output should be `0`; if the day before a public holiday is entered, your output will be `1`.
I'm only interested in dates between **now** (the 27/01) until the end of the year. The final date you will need to account for is 31/12 where your output will be `1` (for New Year's day).
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
### Input
* Input will always be 5 characters: 4 letters, separated with a hyphen `-` or slash `/`
* Input will only be a date between 27/01 and 31/12
### Output
* The number of days until the next public holiday in Queensland Australia, inclusive of the input date: should be a number between `0` and `153` (the longest gap)
* No new lines or errors
### Examples
```
01-05 = 1
02-05 = 0
03-05 = 153
25/12 = 0
26-12 = 0
27/12 = 0
30/12 = 2
31-12 = 1
```
Hopefully this is clear and nothing is missed; however, this is my second question so I will appreciate any feedback and do my best to fix problems ASAP.
[Answer]
# Visual Basic for Applications, 155 or 118 bytes
Version 1 - locale-independent, 155 bytes
```
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-DateSerial(16,Val(Right(d,2)),Val(Left(d,2)))
If h>=0Goto 9
Next
9 End Function
```
Version 2 - locale-dependent, 118 bytes
```
Function h(d)
For i=0To 9
h=Array(0,1,3,31,38,192,275,276,277,282)(i)+42454-CDate(d)
If h>=0Goto 9
Next
9 End Function
```
Byte count is for final .BAS file, including linefeed characters. Edited outside standard VBA editor (as it imposes additional spaces and verbose forms of some keywords) - but imports and runs smoothly on any Office Application (to test type e.g. `? h("10/08")` in immediate window, or in Excel use directly in a cell formula).
(EDITED) Initially I chose to use `DateSerial` to make the function locale-safe (version 1). As I live in Brazil and thus my system is configured to use "dd/mm/yy" format for dates (just like Australia) I could write a even smaller version by using `CDate` instead (version 2). `CDate` uses system locale information to convert text into date. I also assumed in this version that the code would only be run during 2016 (if year is omitted (-6 bytes) `CDate` assumes current year as per system clock).
The number 42454 on third line is the sum of 42450 that is the numeric representation of 01/01/2016 on VBA, and 84 that is the day-of-the-year for the first holiday. The Array contains day-of-the-year for each holiday (including 01/01/2017) offset by -84 as this takes some digits away. Using 16 instead of 2016 on `DateSerial` takes away two more bytes.
Creating an identical array nine times inside the iteration is "bad" code, but works and saves 3 more bytes (one for array name and one for equal sign outside loop, and one more to reference the array inside the loop).
The "missing" spaces between 0 and the following keyword on second and fourth lines are not necessary as they are reintroduced automatically by VBE when the module is imported. Used outdated but byte-cheap `If <...> Goto <linenumber>` to break from loop (both `If <...> Then Exit For` and `If <...> Then Exit Function` use more characters).
Also took advantage of the fact that the function name in VBA behaves as a local variable, and its value is automaticaly returned by the function in the end of execution.
[Answer]
# JavaScript (ES6), ~~131~~ 128 bytes
```
d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r
```
## Explanation
Uses the JavaScript built-in `Date` constructor to convert the input string into a number of milliseconds since epoch, then compares this with the number of milliseconds for each public holiday.
It does this by storing the public holidays in an array as the number of days since a reference date. I chose `2016-01-29` for the reference date because the number of milliseconds since epoch can be condensed the shortest for this date. Any number of milliseconds between this day and the next works because the result is rounded down, and keeping the number in the middle avoids daylight saving effects (although the OP's timezone does not have daylight savings). The number of this day is `1453986000000` and rounding it up to `1454000000000` (adding a couple of hours) means it can be written as `1454e9`.
```
d=>
[56,57,59,87,94,248,331,332,333,338] // list of day offsets from 01/29
.map(n=> // for each public holiday offset n
r=r|| // if r is already set, do nothing
(q= // q = approximate difference in ms
1454e9+n*864e5 // time of public holiday
-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`) // time of input date
)
>=0&& // if q >= 0
q/864e5, // r = q in days
r=0 // r = result
)
|r // floor and return r
```
## Test
This solution is dependent on the user's timezone. This works in the OP's (and my) time zone (GMT +1000). If you want to test it in a different time zone, adding `numberOfHoursDifferentFromGMT1000 * 60 * 60 * 1000` to the reference date number *should* work. (eg. GMT +0430 would be `-5.5 * 60 * 60 * 1000 + 1454e9+n*864e5`)
```
var solution = d=>[56,57,59,87,94,248,331,332,333,338].map(n=>r=r||(q=1454e9+n*864e5-new Date(d[3]+d[4]+`/${d[0]+d[1]}/16`))>=0&&q/864e5,r=0)|r
```
```
<input type="text" id="input" value="03/05" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## T-SQL, ~~210~~, ~~206~~, 194 Bytes
(First post here, Hope this is ok, but please be nice :)
Input goes into `@i`, caters for both `/` and `-` as the separator. I'm in Australia, so my date format is the same as @Tas
```
DECLARE @i CHAR(5)='23-09';DECLARE @c INT=DATEPART(dy,CAST(REPLACE(@i,'-','/')+'/2016' AS DATE))-1;SELECT MIN(b)-@c FROM(VALUES(84),(85),(87),(115),(122),(276),(359),(360),(361))a(b)WHERE b>=@c;
```
**Update** `varchar` to `char` saves 3 bytes plus removed a space :)
**Update 2** declare `@c` and assign without a select
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~98~~ ~~84~~ ~~62~~ 67 Bytes
**Update:** Saved 14 Bytes by shortening the list of the day count for all 12 months for the day number calculation. Haven't found a good way to compress the other list tho, still trying!
**Update2:** Saved another 22 bytes by endcoding the list of the day-numbers as a base256 string.
```
J30KhJ=Yc:z"\W"dd=N+s<[KtJKJKJKKJKJK)tseYshY-hfgTNCMc"UVXt{ĕŨũŪů"1N
```
[Try it online!](http://pyth.herokuapp.com/?code=J30KhJ%3DYc%3Az%22%5CW%22dd%3DN%2Bs%3C%5BKtJKJKJKKJKJK%29tseYshY-hfgTNCMc%22UVXt%7B%C4%95%C5%A8%C5%A9%C5%AA%C5%AF%221N&input=01%2F05&test_suite=1&test_suite_input=01%2F05%0A02-05%0A03%2F05%0A25%2F12%0A26%2F12%0A27-12%0A30-12%0A31%2F12&debug=0)
Same algorithm as in my Python answer. And no builtin to get the day of the year, so I had to do it myself. Creating those 2 lists for the day-of-the-year calculation and for the days of the holidays is quite costly...gonna have a look at it again and try to generate them in fewer bytes.
[Answer]
# T-SQL, 296 bytes
Created as a table valued function
```
create function d(@ char(5))returns table return select min(o)o from(select datediff(day,cast('2016'+right(@,2)+left(@,2)as date),cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1)o from(values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231))d(d))d where 0<=o
```
Used in the following manner
```
SELECT *
FROM (
VALUES
('01/05') --= 1
,('02/05') --= 0
,('03/05') --= 153
,('25/12') --= 0
,('26/12') --= 0
,('27/12') --= 0
,('30/12') --= 2
,('31/12') --= 1
)testData(i)
CROSS APPLY (
SELECT * FROM d(t)
) out
i o
----- -----------
01/05 1
02/05 0
03/05 153
25/12 0
26/12 0
27/12 0
30/12 2
31/12 1
(8 row(s) affected)
```
A brief explanation
```
create function d(@ char(5)) returns table -- function definition
return
select min(o)o -- minimum set value
from(
select datediff( -- date difference
day, -- day units
cast('2016'+right(@,2)+left(@,2)as date), -- convert input parameter to date
cast(right('2016'+right('0'+cast(d as varchar(4)),4),8)as datetime)+1 -- convert int values into datetimes and add a day
)o
from(
values(324),(325),(327),(424),(501),(1002),(1224),(1225),(1226),(1231) -- integers representing the day before public holidays
)d(d)
)d
where 0<=o -- only for values >= 0
```
[Answer]
# JavaScript (ES6), 134 bytes
```
x=>[0,1,3,31,38,192,275,276,277,282].find(z=>z>=(q=x[0]+x[1]- -[...'20212122121'].slice(0,x[3]+x[4]-1).reduce((a,b)=>+b+a+29,0)-85))-q
```
user81655 still has me beat by 3 bytes, but I can't find anywhere else to squeeze anything out of here. Works by calculating the number of days gone by instead of using Date, then comparing it to an array of holiday offsets.
[Answer]
# Python 2, ~~204~~ ~~185~~ ~~165~~ 166 Bytes
**Update:** Golfed it down by ~20 Bytes by calculating the day of the year by myself. No need for the long imports anymore :)
**Update 2:** Another 20 Bytes down by realizing that I can treat new years just as day 367 and making some other small adjustments.
```
def f(d):d=[d[:2],d[3:]];y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0]);return filter(lambda n:n>=y,[85,86,88,116,123,277,360,361,362,367])[0]-y
```
[Try it online!](https://repl.it/BiaD)
Ungolfed:
```
def f(d):
l=[85,86,88,116,123,277,360,361,362,367]
d=[d[:2],d[3:]]
y=sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])+int(d[0])
f=filter(lambda n:n>=y,l)
return f[0]-y
```
Works by storing the day-of-the-year number of the holidays in a list, filtering out the ones which are before the given date, taking the first element in that filtered list and subtracting the day-of-the-year, which got calculated from the input.
[Answer]
# PHP, 116 bytes
Pretty straight forward approach. It stores the days of the year for the holidays and pops them as long as they are in the past. Finally the requested day of the year is subtracted.
```
for($x=[366,361,360,359,276,122,115,87,85,84];($a=date(z,strtotime($argv[1].'-2016')))>$t=array_pop($x););echo$t-$a;
```
Past all test cases. Runs from command line and accepts the input using a hyphen, like:
```
$ php holidays.php "12-05"
```
[Answer]
# ruby 1.9.3, ~~155~~ 153 bytes
After Christmas Day holiday, we need our super-special-day 366! Similar case as @DenkerAffe.
```
require'date'
c=(Date.strptime(ARGV[0],'%d/%m')-Date.parse('01/01')).to_i
print [84,85,87,115,122,276,359,360,361,366].map{|i|(i-c)}.select{|i|i>=0}.min
```
Usage:
```
$ ruby i_want_to_break_free.rb "03/05"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•9JRt€ª´Q®Ië•368вDI„-/S¡`•Σ₁t•ºS₂+s<£O+©@Ïн®-
```
It may not be 2016 anymore, but whatever.. ;) Still assumes the year is 2016 for the sake of being a leap year with `29` for February.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMiS6@gkkdNaw6tOrQl8NA6z8OrgWLGZhYXNrl4PmqYp6sffGhhAlDo3OJHTY0lQMahXcGPmpq0i20OLfbXPrTS4XD/hb2H1un@/29soGtoBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDYssvYJKHjWtObTq0JbAQ@s8D68GihmbWVzY5FL5qGGern7woYUJQKFzix81NZYAGYd2BT9qatIutjm02F/70EqHw/0X9h5ap/tf53@0koGhroGpko6SgRGUNobQRqb6hkYg2kwXQptD@MYGUNoQJB4LAA).
**Explanation:**
```
•9JRt€ª´Q®Ië• # Push compressed integer 10549819042671399072072399
368в # Converted to base-368 as list: [85,86,88,116,123,277,360,361,362,367]
D # Duplicate this list
I # Take the input
„-/S¡ # Split it on ["-","/"]
` # Push both integer separated to the stack
•Σ₁t• # Push compressed integer 5354545
º # Mirror it without overlap: 53545455454535
S # Converted to a list of digits: [5,3,5,4,5,4,5,5,4,5,4,5,3,5]
₂+ # Add 26 to each: [31,29,31,30,31,30,31,31,30,31,30,31,29,31]
s # Swap to get the month-integer
< # Decrease it by 1
£ # Only leave the first month-1 values from the integer-list
O # Sum that sublist
+ # And add it to the day-integer (so we now have the N'th day of the year)
© # Save this in the register (without popping)
@ # Do a >= check with each integer in the first (duplicated) list we created
Ï # Only leave the truthy values from the list
н # Then pop this sublist and only leave its first value
®- # And subtract the integer we saved in the register (N'th day of the year)
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•9JRt€ª´Q®Ië•` is `10549819042671399072072399`; `•9JRt€ª´Q®Ië•368в` is `[85,86,88,116,123,277,360,361,362,367]`; and `•Σ₁t•` is `5354545`.
] |
[Question]
[
The "ascending matrix" is an infinite matrix of whole numbers (0 included) in which any element is the smallest available element which has not been previously used on the respective row and column:
```
| 1 2 3 4 5 6 ...
--+----------------
1 | 0 1 2 3 4 5 ...
2 | 1 0 3 2 5 4 ...
3 | 2 3 0 1 6 7 ...
4 | 3 2 1 0 7 6 ...
5 | 4 5 6 7 0 1 ...
6 | 5 4 7 6 1 0 ...
. | ...............
```
Your task is to write a program that will output the element found at the row and column specified by the input. (standard input and output)
Test cases:
```
5 3 -> 6
2 5 -> 5
```
Code Golf rules apply—the shortest code wins.
P.S. Even if this has an algorithmic nature the code can be very, **very** concise.
**EDIT:** I wasn't expecting to see the xor solution so early. I was really hoping to see 10 posts with an algorithmic approach and THEN the xor solution. Now, having in mind that it's not much fun to see how to write xor in different languages I recommend that you also try an algorithmic approach.
So, yes, I think no one can beat the 5 character mark now—therefore I congratulate Ilmari Karonen for the smartest and shortest solution. But there's a new challenge up ahead: **write the shortest algorithmic solution**.
[Answer]
## GolfScript, 5 chars
```
~(\(^
```
Indeed, this task is very simple once you recognize the pattern. The only awkward bit is the 1-based indexing — if the input indices were zero-based, this **2-character solution** would suffice:
```
~^
```
To explain this to readers unfamiliar with GolfScript, the `~` command evals the input, leaving the two numbers on the stack. `^` then XORs the two topmost numbers on the stack together, leaving the result for output. To deal with 1-based input, two more commands are needed: `(` decrements the topmost number on the stack by one, while `\` swaps the top two items on the stack.
[Answer]
# Mathematica 10 44
**Edit**
My first response was based on a misunderstanding about the nature of the challenge, as noted by Ilmari.
Here's another try.
**Usage**
```
f[n___, 1, n___] := n - 1;
j_~f~k_ := BitXor[j - 1, k - 1]
```
[Answer]
# K, 31
```
{0b/:{(x|y)&~x~y}. 0b\:'-1+x,y}
```
Stole Ilmari Karonen's XOR logic, which I would never have spotted myself.
[Answer]
# PHP, 38
Just a simple implementation of Ilmari Karonen's XOR
`<?php echo --$_GET['a']^--$_GET['b']?>`
Usage:
.../xor.php?a=4&b=7
will print 6
[Answer]
# Python 2, 36
I figure since I'm just starting to learn Python that this would be the perfect time to submit my first answer using it (and no one has answered using Python) and perhaps I could receive some feedback.
Thank you @IlmariKaronen for the very cool shortcut.
Thank you @Gareth for the code below.
```
import sys
print(input()-1^input()-1)
```
---
### Python 3, 56
The original program that I had written.
```
import sys
x=int(input())
y=int(input())
x-=1
y-=1
print(x^y)
```
**[IDEONE with 2 and 5](http://ideone.com/WXF9c)**
**[IDEONE with 3 and 3](http://ideone.com/zltUZ)**
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Z~
```
[Try it online!](https://tio.run/##y00syfn/P6ru/39jLlMA "MATL – Try It Online")
MATL post-dates the challenge by several years, but, hey, natural 1-based indexing and a bitwise xor function makes this nice and neat!
[Answer]
## Haskell 174
Figured I'd make a solution that did not rely on XOR. Too lazy to golf it properly.
```
a 0 0=0
a b c
|m==n=a(b-m)(c-n)
|m>n=m+a(b-m)c
|m<n=n+a b(c-n)
where{g f=until(>f)(*2)1`div`2;m=g b;n=g c;}
main=do
[x,y]<-fmap(map read.words)getLine
print$a(x-1)(y-1)
```
**Edit:** I realized a day later that this is just calculating XOR. Thus if this counts as an algorithmic solution, so should Ilmari Karonen's.
[Answer]
# [Perl 5](https://www.perl.org/), 12 bytes
```
say<>-1^<>-1
```
[Try it online!](https://tio.run/##K0gtyjH9/784sdLGTtcwDkT8/2/EZfovv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online")
[Answer]
## Javascript 13 bytes
```
a=>b=>--a^--b
```
```
f=a=>b=>--a^--b
result = document.getElementById('result')
```
```
<input type="text" onkeyup="result.innerHTML = f(this.value.split(',')[0])(this.value.split(',')[1])" >
<p id="result"></p>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
UÉ^VÉ
```
[Try it online!](https://tio.run/##y0osKPn/P/RwZ1zY4c7//025jAE "Japt – Try It Online")
] |
[Question]
[
The square number digit density (SNDD) of a number - invented by myself - is the ratio of the count of square numbers found in consecutive digits to the length of the number. For instance, 169 is a 3-digit number containing 4 square numbers - 1, 9, 16, 169 - and thus has a square number digit density of 4/3, or 1.33. The 4-digit number 1444 has 6 squares - 1, 4, 4, 4, 144, 1444 - and thus a ratio of 6/4, or 1.5. Notice in the previous example that squares are allowed to be repeated. Also, 441 is not allowed, because it cannot be found consecutively inside the number 1444.
Your task is to write a program that searches a given range A - B (inclusive) for the number with the highest square number digit density. Your program should abide by the following specifications:
* Take input A, B in the range 1 to 1,000,000,000 (1 billion). Example: `sndd 50 1000`
* Return as a result the number with the largest SNDD. In the case of a tie, return the smallest number.
* 0 does not count as a square in any form, 0, 00, 000, etc. Neither do squares starting with 0, such as 049 or 0049.
* Note that the entire number does not have to be a square number.
Examples:
```
sndd 14000 15000
Output: 14441
sndd 300 500
Output: 441
```
Bonus: What is the number with the largest SNDD between 1 and 1,000,000,000? Can you prove whether this is the largest possible, or there might be a larger one in a higher range?
**Current Scores:**
1. Ruby: 142
2. Windows PowerShell: 153
3. Scala: 222
4. Python: 245
Now that an answer has been selected, here is my (ungolfed) reference implementation in JavaScript: <http://jsfiddle.net/ywc25/2/>
[Answer]
Answering the bonus: the best score for numbers <1e9 is 5/3=1.666..., generated by 144411449 (and maybe others?).
But you can do better with larger numbers. Generally if n has a score of x, then you can concatenate two copies of n and get the same score x. If you're lucky and n has the same first and last digit, then you can drop one of those digits in the concatenation and improve your score slightly (one less than double the number of squares and one less than double the number of digits).
n=11449441 has a score of 1.625 and has the same first & last digit. Using that fact, we get the following sequence of scores:
```
1.625 for 11449441
1.666 for 114494411449441
1.682 for 1144944114494411449441
1.690 for 11449441144944114494411449441
1.694 for 114494411449441144944114494411449441
```
which gives an infinite sequence of numbers which are strictly (although decreasingly) better than previous numbers, and all but the first 2 better than the best score for numbers < 1e9.
This sequence may not be the best overall, though. It converges to a finite score (12/7=1.714) and there may be other numbers with better scores than the limit.
**Edit**: a better sequence, converges to 1.75
```
1.600 14441
1.667 144414441
1.692 1444144414441
1.706 14441444144414441
1.714 144414441444144414441
```
[Answer]
## Ruby 1.9, 142 characters
```
$><<($*[0]..$*[1]).map{|a|n=0.0;(1..s=a.size).map{|i|n+=a.chars.each_cons(i).count{|x|x[0]>?0&&(r=x.join.to_i**0.5)==r.to_i}};[-n/s,a]}.min[1]
```
* (139 -> 143): Fixed output in case of a tie.
[Answer]
## Windows PowerShell, 153 ~~154~~ ~~155~~ ~~164~~ ~~174~~
```
$a,$b=$args
@($a..$b|sort{-(0..($l=($s="$_").length)|%{($c=$_)..$l|%{-join$s[$c..$_]}}|?{$_[0]-48-and($x=[math]::sqrt($_))-eq[int]$x}).Count/$l},{$_})[0]
```
Thanks to Ventero for a one-byte reduction I was too stupid to find myself.
154-byte version explained:
```
$a,$b=$args # get the two numbers. We expect only two arguments, so that
# assignment will neither assign $null nor an array to $b.
@( # @() here since we might iterate over a single number as well
$a..$b | # iterate over the range
sort { # sort
( # figure out all substrings of the number
0..($l=($s="$_").length) | %{ # iterate to the length of the
# string – this will run off
# end, but that doesn't matter
($c=$_)..$l | %{ # iterate from the current position
# to the end
-join$s[$c..$_] # grab a range of characters and
# make them into a string again
}
} | ?{ # filter the list
$_[0]-48 -and # must not begin with 0
($x=[math]::sqrt($_))-eq[int]$x # and the square root
# must be an integer
}
).Count ` # we're only interested in the count of square numbers
/ $l # divided by the length of the number
},
{-$_} # tie-breaker
)[-1] # select the last element which is the smallest number with the
# largest SNDD
```
[Answer]
## Python, 245 256
```
import sys
def t(n,l):return sum(map(lambda x:int(x**0.5+0.5)**2==x,[int(n[i:j+1])for i in range(l)for j in range(i,l)if n[i]!='0']))/float(l)
print max(map(lambda x:(x,t(str(x),len(str(x)))),range(*map(int,sys.argv[1:]))),key=lambda y:y[1])[0]
```
* 256 → 245: Cleaned up the argument parsing code thanks to a tip from [Keith Randall](https://codegolf.stackexchange.com/users/67/keith-randall).
This could be a lot shorter if the range were read from `stdin` as opposed to the command line arguments.
**Edit:**
With respect to the bonus, my experiments suggest the following:
**Conjecture 1**. *For every n* ∈ ℕ*, the number in* ℕ≤*n* *with the largest SNDD must contain solely the digits 1, 4, and 9.*
**Conjecture 2.** ∃ *n* ∈ ℕ ∀ i ∈ ℕ≥*n* : SNDD(*n*) ≥ SNDD(*i*).
**Proof sketch**. The set of squares with digits 1, 4, and 9 are [likely finite](http://oeis.org/A006716). ∎
[Answer]
## Scala, 222
```
object O extends App{def q(i: Int)={val x=math.sqrt(i).toInt;x*x==i}
println((args(0).toInt to args(1).toInt).maxBy(n=>{val s=n+""
s.tails.flatMap(_.inits).filter(x=>x.size>0&&x(0)!='0'&&q(x.toInt)).size.toFloat/s.size}))}
```
(Scala 2.9 required.)
[Answer]
Considering the bonus question:
Outside of the range the highest possible SNDD is infinite.
At least, if I read the question correctly, a square like 100 (10\*10) does count.
If you consider the number 275625, the score is 5/6, since 25, 625, 5625, 75625 and 275625 are all square.
Adding 2 zero's gives: 27562500, which has a score of 10/8.
The limit of this sequence is 5/2=2.5
Along the same lines, you can find squares which end in any number of smaller squares desired. I can proof this, but you probably get the idea.
Admittedly, this is not a very nice solution, but it proofs there's no upper limit to the
SNDD.
[Answer]
## Clojure - 185 chars
Probably could be optimised further but here goes:
```
(fn[A,B]((first(sort(for[r[range]n(r A(inc B))s[(str n)]l[(count s)]][(/(count(filter #(=(int%)(max 1%))(for[b(r(inc l))a(r b)](Math/sqrt(Integer/parseInt(subs s a b))))))(- l))n])))1))
```
Used as a function with two parameters:
```
(crazy-function-as-above 14000 15000)
=> 14441
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes, language postdates challenge
```
DµẆ1ị$ÐfḌƲS÷L
rµÇÐṀḢ
```
[Try it online!](https://tio.run/nexus/jelly#ATIAzf//RMK14bqGMeG7iyTDkGbhuIzDhsKyU8O3TApywrXDh8OQ4bmA4bii////MzAw/zUwMA "Jelly – TIO Nexus")
## Explanation
Helper function (calculates digit density of its input):
```
DµẆ1ị$ÐfḌƲS÷L
Dµ Default argument: the input's decimal representation
Ẇ All substrings of {the decimal representation}
Ðf Keep only those where
1ị$ the first digit is truthy (i.e. not 0)
Ḍ Convert from decimal back to an integer
Ʋ Check each of those integers to see if it's square
S Sum (i.e. add 1 for each square, 0 for each nonsquare)
÷L Divide by the length of {the decimal representation}
```
Main program:
```
rµÇÐṀḢ
rµ Range from the first input to the second input
ÇÐṀ Find values that maximize the helper function
Ḣ Choose the first (i.e. smallest)
```
The program's arguably more interesting without the `Ḣ` – that way, it returns all maximal-density numbers rather than just one – but I added it to comply with the specification.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Well, this is pretty hideous!
```
õV ñÈì ã fÎxÈì ¬v1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=9VYg8cjsIOMgZs54yOwgrHYx&input=MTQwMDAgMTUwMDA)
```
õV ñÈì ã fÎxÈì ¬v1 :Implicit input of integers U & V
õV :Range [V,U]
ñ :Sort by
È :Passing each through the following function
ì : Convert to digit array
ã : Sub-arrays
f : Filter by
Î : First element (0 is falsey)
x : Reduce by addition after
È : Passing each through the following function
ì : Convert from digit array
¬ : Square root
v1 : Divisible by 1?
:Implicit output of last element
```
] |
[Question]
[
Given a list of intervals, perform the union of them, and reduce overlaps.
That means, overlapping parts are reduced. (`[a, b] U [c, d] = [a, d]` if `b > c`)
Assuming all a < b in all intervals `[a, b]`.
Implement as a function of a list of input intervals -> list of output intervals.
Shortest code wins. You cannot use any existing libraries.
Clarifications:
* Open and closed intervals are not distinguished.
* Intervals for real numbers, not integers. (`[2, 3], [4, 5] -> [2, 3], [4, 5]`)
* No need to sort output intervals
* The order if inputs do not matter
* Illegal inputs are only `[a, b]` where `b >= a`, it has nothing to do with the order of input intervals and the number of input intervals.
* You do not need to show an error message on undefined behaviors
Examples (with number lines)
```
[2, 4], [7, 9] --> [2, 4], [7, 9]
234
789
-> 234 789
[1, 5], [2, 10] --> [1, 10] (overlapping [2, 5] reduced)
12345
234567890
-> 1234567890
[2, 4], [3, 6], [8, 9] -> [2, 6], [8, 9]
234
3456
89
-> 23456 89
[4, 2], [2, 2] -> (undefined behavior: against the assumption)
```
[Answer]
## Haskell (103)
I think, it is way too verbose for Haskell. Thanks to Hoa Long Tam for his sorting function.
```
m%(x:y)|x>m=m:x:y|2>1=x:m%y;m%_=[m]
(x:y)?l|x`elem`l=y?l|0<1=x:y?(x:l);a?_=a
a∪b=foldr(%)[](a++b)?[]
```
In Haskell, an intervall from `a` to `b` is denoted by `[a..b]`. My notation is very similar to the mathematical notation. Use it like this:
```
[a..b] ∪ [c..d] ∪ ... ∪ [y..z]
```
[Answer]
Ok, here's my 250 character crack at it.
```
void n(int a[]){if(!a[2])return;if(a[2]<=a[1]){if(a[1]<a[3])a[1]=a[3];
int *b=a+2;while(*b=*(b+2))++b;n(a);}n(a+2);}
void m(int a[]){if(!a[2])return;if(a[0]>a[2]){int s=a[0],t=a[1];
a[0]=a[2];a[2]=s;a[1]=a[3];a[3]=t;m(a+2);m(a);n(a);}m(a+2);n(a+2);}
```
The function takes an int array, and operates on it in-situ. The array is terminated by a 0, and the intervals may be given in any order.
Sample output:
```
input list: (7,9) (5,6) (1,4) (15,18) (13,16) (2,3) (8,11)
output list: (1,4) (5,6) (7,11) (13,18)
```
Sample program:
```
#include <stdio.h>
void n(int a[]){if(!a[2])return;if(a[2]<=a[1]){if(a[1]<a[3])a[1]=a[3];
int *b=a+2;while(*b=*(b+2))++b;n(a);}n(a+2);}
void m(int a[]){if(!a[2])return;if(a[0]>a[2]){int s=a[0],t=a[1];
a[0]=a[2];a[2]=s;a[1]=a[3];a[3]=t;m(a+2);m(a);n(a);}m(a+2);n(a+2);}
/*
void n(int a[])
{
if(!a[2])return;
if(a[2]<=a[1]) {
if(a[1]<a[3])
a[1]=a[3];
int *b=a+2;
while(*b=*(b+2))++b;
n(a);
}
n(a+2);
}
void m(int a[])
{
if(!a[2])return;
if(a[0]>a[2]) {
int s=a[0],t=a[1];
a[0]=a[2];a[2]=s;
a[1]=a[3];a[3]=t;
m(a+2);m(a);n(a);
}
m(a+2);n(a+2);
}
*/
void p(int a[])
{
if(!*a) {
printf("\n");
return;
}
printf("(%d,%d) ",a[0],a[1]);
p(a+2);
}
int main (int argc, const char * argv[])
{
// Code golf entry
// Interval Merging
int a[] = {7,9,5,6,1,4,15,18,13,16,2,3,8,11,0};
printf( "input list: " ); p(a);
m(a);
printf( "output list: " ); p(a);
return 0;
}
```
[Answer]
# GolfScript, 32
```
[{1$1$*-2%~2->{*$[(\)\;]}{}if}*]
```
* Add 2 characters if you prefer a
block, 4 if you prefer a named block.
* Input and output are array of pairs, e.g. `[[2 4] [3 5]]`
* Assumes that input is ordered by the first element.
* Compacts "adjacent" ranges ([2 4][5 6] -> [2 6])
* First GolfScript effort. Advice & rotten fruit appreciated.
Full test program:
```
[~](;2/[{1$1$*-2%~2->{*$[(\)\;]}{}if}*]`
```
Example invocation:
```
ruby golfscript.rb intervals.gs <<EOF
3
2 4
3 6
8 9
EOF
# Expected output: [[2 6] [8 9]]
```
[Answer]
## Python, 100 chars
```
def f(L):R=sorted(set(p for p in sum(L,[])if 1-any(x<p<y for x,y in L)));return zip(R[::2],R[1::2])
print f([[2, 4], [7, 9]])
print f([[1, 5], [2, 10]])
print f([[3, 6], [2, 4], [8, 9]])
print f([[1, 5], [3, 5], [4, 5]])
```
generates
```
[(2, 4), (7, 9)]
[(1, 10)]
[(2, 6), (8, 9)]
[(1, 5)]
```
Takes all the endpoints of the intervals, removes any that are strictly inside another interval, uniquifies & sorts them, and pairs them up.
[Answer]
## Haskell, 55 characters
```
v(q@(a,b):p@(c,d):r)|c>b=q:v(p:r)|1<3=v((a,d):r);v x=x
```
If the input is unsorted, then 88 characters:
```
p@(a,b)§(q@(c,d):r)|b<c=p:q§r|a>d=q:p§r|1<3=(min a c,max b d)§r;p§_=[p]
u i=foldr(§)[]i
```
Test runs:
```
ghci> testAll v
pass: [(2,4),(7,9)] --> [(2,4),(7,9)]
pass: [(1,5),(2,10)] --> [(1,10)]
pass: [(2,4),(3,6),(8,9)] --> [(2,6),(8,9)]
ghci> testAll u
pass: [(2,4),(7,9)] --> [(2,4),(7,9)]
pass: [(1,5),(2,10)] --> [(1,10)]
pass: [(2,4),(3,6),(8,9)] --> [(2,6),(8,9)]
```
I'm assuming that "can't use any existing libraries" precludes importing `List` and calling `sort`. If that were legal, than the unsorted version would be only 71 characters.
[Answer]
## Scala, 272 characters
```
type p=List[(Int,Int)];def f(l:p):p={var(a,s,c,o)=(new Array[Int]((l map(x=>x._2)max)+1),0,0,List[Int]());l map(x=>(a(x._1)+=1,a(x._2)-=1));while(c<a.size){s+=a(c);if(a(c)==1&&s==1)o=o:+c;if(a(c)== -1&&s==0)o=o:+c;c+=1};return(o.grouped(2).map(x=>(x.head,x.last)).toList)}
```
Usage:
```
object Intervals2 extends Application
{
type p=List[(Int,Int)];def f(l:p):p={var(a,s,c,o)=(new Array[Int]((l map(x=>x._2)max)+1),0,0,List[Int]());l map(x=>(a(x._1)+=1,a(x._2)-=1));while(c<a.size){s+=a(c);if(a(c)==1&&s==1)o=o:+c;if(a(c)== -1&&s==0)o=o:+c;c+=1};return(o.grouped(2).map(x=>(x.head,x.last)).toList)}
print(f(List((1,2),(3,7),(4,10))))
}
```
Creates an array and inserts a 1 for every interval start and a -1 for every interval end. Then steps through the array adding the values to a counter outputting a start every time the counter steps from 0 to 1 and an end when it steps from 1 to 0. Probably unnecessarily complicated.
Output:
```
List((1,2), (3,10))
```
[Answer]
## Perl (146) (92) (90)
golfed down to 90 chars, creatively using the regex engine
```
sub u{map$h[$_]=1,@$_[0]..@$_[1]for@_;$w.=$_+0for@h;push@r,$-[0],$+[0]-1while$w=~/1+/g;@r}
```
usage example:
```
my @out1 = u([1, 5], [2, 10]); # (1,10)
my @out2 = u([2, 4], [3, 6], [8, 9]); # (2, 6, 8, 9)
```
let's explain this code a bit.
this subroutine receives an array of arrayrefs, each aref pointing to an array containing two elements, start and end of the interval: `([2, 4], [3, 6], [8, 9])`
for every aref, we generate an array of elements from first to last `($_->[0] .. $_->[1])`.
then we use map to set elements of such indexes in @h to 1.
```
for (@_) {
map {$h[$_] = 1} ($_->[0] .. $_->[1]);
}
```
after this, `@h` will contain either ones (for intervals) or undefs, depicted below as hyphens for clarity.
```
index: 0 1 2 3 4 5 6 7 8 9
@h: - - 1 1 1 1 1 - 1 1
```
next we build a string from @h, adding 0 to replace undefs with something more useful (undef + 0 = 0).
`$w .= $_+0 for @h;`
$w contains `011111011` now.
it's time to abuse the regex engine a bit.
`push @r, ($-[0], $+[0]-1) while $w=~/1+/g;`
after successful matches, @- and @+ arrays contain respectively position of start and end of each match; 0th element is used for the entire match, first for $1, second for $2 and so on.
`$+[0]` actually contains the position of first non-matching char, so we have to substract one.
`@r` contains `(2, 6, 8, 9)` now.
`@r`
to make the sub return `@r`.
[Answer]
### Scala 305 279 chars without invocation:
```
type I=(Int,Int)
def l(p:I,q:I)=if(p._1<q._1)true else if(p._1>q._1)false else p._2<q._2
def r(l:List[I]):List[I]=l match{case x::y::z=>{if(y._1<=x._2&&y._2>x._2)(x._1,y._2)::r(z)else
if(y._1<=x._2&&y._2<=x._2)x::r(z)else
x::r(y::z)}case _=>l}
def c(v:List[I])=r(v.sortWith(l))
```
invocation:
```
val i=List((7,9),(5,6),(1,4),(15,18),(13,16),(2,3),(8,11))
c(i)
res0: List[(Int, Int)] = List((1,4), (5,6), (7,11), (13,18))
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
⟦₂ᵐcod~c~⟦₂ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8ZSDe1gnJ@Sl1yXVw7v//0QrR0UY6JrE60eY6lrGxOkCuoY4pkGukY2gA4UOkjXXMgKQFuiITGNcIaoROtKmORWysQiwA "Brachylog – Try It Online")
A delightfully declarative solution, taking input as a list of lists through the input variable and outputting a list of lists through the output variable.
```
~⟦₂ᵐ The output is a list of intervals, where each interval is a range in
~c the smallest partition of
ᵐ each element of the input
⟦₂ converted to an inclusive range,
c concatenated,
o sorted,
d and deduplicated
~⟦₂ᵐ for which each element of the partition is a range.
```
[Answer]
## Clojure, 138 bytes
```
#(let[S(set(apply mapcat range(apply map list %)))Q(sort S)](map list(for[s Q :when(not(S(dec s)))]s)(for[s(map inc Q):when(not(S s))]s)))
```
This shortens to **119 bytes** if the input is more flexible, namely a list of intervals' starting points AND a list of intervals' ending points:
```
#(let[S(set(mapcat range % %2))Q(sort S)](map list(for[s Q :when(not(S(dec s)))]s)(for[s(map inc Q):when(not(S s))]s)))
```
There has to be a better way.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
This feels far too long. I/O as sorted, 2D array of intervals.
```
c_ròÃòÈaY Éîg[TJ]
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y19y8sPyyGFZIMnDrmdbVEpd&input=W1syLCA0XSwgWzMsIDZdLCBbOCwgOV1dCi1R)
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 11 bytes
```
r/€FṢQŒġ.ịⱮ
```
[Try it online!](https://tio.run/##y0rNyan8/79I/1HTGreHOxcFHp10ZKHew93djzau@3@4HSj6/390tJGOgkmsjkK0uY6CZSyIARcx1lEwA9EWcBlDHQVTEAOowtAgNhYA "Jelly – Try It Online") or rather, don't
Outputs the ranges as `[b, a]` where \$b > a\$ (so the example `[2, 4], [3, 6], [8, 9]` is output as `[6, 2], [9, 8]`)
## How it works
```
r/€FṢQŒġ.ịⱮ - Main link. Takes a list of pairs on the left
€ - Over each pair:
r/ - Reduce into a range
FṢQ - Flatten, sort and deduplicate
Œġ - Group adjacent consecutive elements
.ịⱮ - Select the first and last from each group
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=max -n`, 89 bytes
```
@r=/\S+/g;map{/ /;$`<=$r[1]?$r[1]=max@r,$'*1:(say"@r")|(@r=($`,$'))}sort{$a-$b}<>;say"@r"
```
[Try it online!](https://tio.run/##K0gtyjH9/9@hyFY/JlhbP906N7GgWl9B31olwcZWpSjaMNYeTNrmJlY4FOmoqGsZWmkUJ1YqORQpadZoAPVpqCQAhTU1a4vzi0qqVRJ1VZJqbeysoWr@/9c1VDDiMlCw5DJWMPuXX1CSmZ9X/F/X11TPwNAASPtkFpdYWYWWZOaArPivmwcA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 75 bytes
```
->a{a.map{[*_1.._2]}.reduce(:|).sort.slice_when{_2-_1>1}.map{|a,*,b|[a,b]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3vXXtEqsT9XITC6qjteIN9fTijWJr9YpSU0qTUzWsajT1ivOLSvSKczKTU-PLM1LzquONdOMN7QxrwVpqEnW0dJJqohN1kmJra6FGehUouEVHRxvpKJjE6ihEm-soWMbGxnJBRA11FExBokBZQwOEMEyxsY6CGYi2gGiCmLhgAYQGAA)
[Answer]
# Mathematica, 18 bytes
```
List@@Interval@@#&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/01ca11fe-5ad5-4dbf-ac34-f481a4566e29)
] |
[Question]
[
[Hermite polynomials](https://en.wikipedia.org/wiki/Hermite_polynomials) refer to two sequences of polynomials:
* The **"probabilist's Hermite polynomials"**, given by
$${He}\_n(x) = (-1)^n e ^ \frac {x^2} 2 \frac {d^n} {dx^n} e ^ {-\frac {x^2} 2}$$
where \$\frac {d^n} {dx^n} f(x)\$ refers to the \$n\$th derivative of \$f(x)\$
* The **"physicist's Hermite polynomials"**, given by
$$H\_n(x) = (-1)^n e ^ {x^2} \frac {d^n} {dx^n} e ^ {-x^2}$$
The first few terms are
| \$n\$ | \$He\_n(x)\$ | \$H\_n(x)\$ |
| --- | --- | --- |
| \$0\$ | \$1\$ | \$1\$ |
| \$1\$ | \$x\$ | \$2x\$ |
| \$2\$ | \$x^2 - 1\$ | \$4x^2 - 2\$ |
| \$3\$ | \$x^3 - 3x\$ | \$8x^3 - 12x\$ |
| \$4\$ | \$x^4 - 6x^2 + 3\$ | \$16x^4 - 48x^2 + 12\$ |
| \$5\$ | \$x^5 - 10x^3 + 15x\$ | \$32x^5 - 160x^3 + 120x\$ |
Both sequences can be expressed via recurrence relations:
$$
He\_{n+1}(x) = xHe\_n(x) - nHe\_{n-1}(x) \\
H\_{n+1}(x) = 2xH\_n(x) - 2nH\_{n-1}(x)
$$
with the base cases
$$
He\_0(x) = 1, He\_1(x) = x \\
H\_0(x) = 1, H\_1(x) = 2x
$$
---
You should write a polyglot program that works in at least 2 languages. In one language, it should take a non-negative integer \$n\$ as input and output the polynomial \$H\_n(x)\$, and in the second, it should take a non-negative integer \$n\$ and output the polynomial \$He\_n(x)\$.
Your programs should be true polyglots, so are the same bytes, rather than the same characters. For example, if your program is `g)ʠẹṁ` in the [Jelly code page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page), the bytes are `67 29 A5 D6 EF`, and the same program in the [05AB1E code page](https://github.com/Adriandmen/05AB1E/wiki/Codepage) would be `g)¥Öï`.
You may output the polynomial in any reasonable format, such as a list of coefficients (little- or big-endian) (e.g. \$x^4 - 6x^2 + 3\$ as `[1,0,-6,0,3]`), a list of pairs of coefficients and powers (e.g. `[[1,4], [-6,2], [3,0]]`), or a string such as `x^4-6x^2+3`.
Different versions of languages (e.g. Python 2 and 3) are considered the same language. As a general rule, if 2 languages are considered to be versions of each other (e.g. Seriously and Actually), they may not both be used. Additionally, using command line flags, in this case, does not count as different languages.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
---
## Test cases
The polynomials here are represented in little-endian format
```
n -> He(x) H(x)
0 -> [1] [1]
1 -> [0, 1] [0, 2]
2 -> [-1, 0, 1] [-2, 0, 4]
3 -> [0, -3, 0, 1] [0, -12, 0, 8]
4 -> [3, 0, -6, 0, 1] [12, 0, -48, 0, 16]
5 -> [0, 15, 0, -10, 0, 1] [0, 120, 0, -160, 0, 32]
6 -> [-15, 0, 45, 0, -15, 0, 1] [-120, 0, 720, 0, -480, 0, 64]
7 -> [0, -105, 0, 105, 0, -21, 0, 1] [0, -1680, 0, 3360, 0, -1344, 0, 128]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) + [Python 3](https://docs.python.org/3/), 63 bytes
```
#+HermiteH[#,x]-#&(*
import scipy.special as s;s.hermitenorm#*)
```
[Try it online! (Mathematica)](https://tio.run/##y00syUjNTSzJTE78/19Z2yO1KDezJNUjWlmnIlZXWU1DiysztyC/qEShODmzoFKvuCA1OTMxRyGxWKHYulgvA6I8L78oV1lL8/9/AA)
[Try it online! (Python)](https://tio.run/##K6gsycjPM/7/X1nbI7UoN7Mk1SNaWaciVldZTUOLKzO3IL@oRKE4ObOgUq@4IDU5MzFHIbFYodi6WC8DojwvvyhXWUvz/38A)
Boring solution with built-ins... Gives physicists' version for Mathematica and probabilists' version for Python. There will be floating errors for Python though. The following eliminates that for 102 bytes
```
#+HermiteH[#,x]-#&(*
f=lambda n:n<2 and[0]*n+[1]or[a-~-n*b for a,b in zip([0]+f(n-1),f(n-2)+[0,0])]#*)
```
with the Python solution outputting a coefficient list in ascending power
[Answer]
# [Ruby](https://www.ruby-lang.org/)/[Crystal](https://crystal-lang.org), 84 bytes
```
def f(n)n<1?[1]:([0]+f(n-1)).zip(f(n-2)+[0,0]).map{|i,j|('a'=="a"?1:2)*(i+j-n*j)}end
```
[Try it online in Ruby! (probabilist)](https://tio.run/##FY1BCoMwFAWvUtz4n9FP4qYgFQ8SskhrpAk0hEIX1Xj2NN0Nw8C8P/dvKavbLhtFxJtatDITaWlEFYMCePeJ/jxCaNlLA37ZdGTfh0ytbee5sc2iphEdeRGG2AWcLq6FJPMV7OzjWeuc6sHjLD8 "Ruby – Try It Online")
[Try it online in Crystal! (physicist)](https://tio.run/##FY1BCoMwEAC/Ury4a3RJvBSk4kNCDotGmtCGoPbQNr49TW/DMDDz9t4PfuS82PWyQsBwU5NWZgAtjSiiU4j0cRH@3KPQspUG6cnxm1zrE9Rcj2PF1aSGHhtwwneh8XjasGSQRFcky/O91Cm@jr1MHJ75Bw "Crystal – Try It Online")
Outputs in little-endian format, as in provided test cases.
This may look similar to a loophole of using different versions of the same language, but Crystal **is** a different language that just shares most of its syntax with Ruby. The languages are distinguished by their approach to quotes:
* In Ruby, both single and double quotes denote string literals
* In Crystal, single quotes denote chars, which do not pass equality check with analogous strings
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish) and [J](http://jsoftware.com/) (902), 86 bytes
```
60.]{{'01IF00}L:2+F:}*$:@-{@@}}|{$2+F$}}||LFN~|h'
{{2*-/(0,p=:y),:p*#p}}^:y,1[p=:0$0}}
```
[Try it online in Gol><>!](https://tio.run/##S8/PScsszvj/38xAL7a6Wt3A0NPNwKDWx8pI282qVkvFykG32sGhtramWgUoogJk1Pi4@dXVZKhzVVcbaenqaxjoFNhaVWrqWBVoKRfU1sZZVeoYRgOFDFQMamv//zcFAA "Gol><> – Try It Online")
[Try the equivalent code in J 806!](https://tio.run/##y/r/P83WysxAL9ZYwUrBgEvdwNDTzcCg1sfKSNvNqlZLxcpBt9rBoba2ploFKKICZNT4uPnV1WSocwF1qBtp6eprGOgU2FpVaupYFWgpF6jHWVXqGEYDRQxUDLg0uVKTM/IV0hRM//8HAA "J – Try It Online")
A full program in Gol><> that outputs He(n) in big endian, and a function in J that outputs H(n) in little endian.
## Gol><> path
Gol><> operates on a single stack of numbers, and the challenge requires zipping two lists and maintaining two previous states. So I decided to interleave the two coefficient lists on the stack.
```
60. 01IF00}L:2+F:}*$:@-{@@}}|{$2+F$}}||LFN~|h
60. Jump into the main code
01 Push 0, 1 (-1th and 0th polynomial, respectively)
IF..| Take n from input and repeat n times (L: 0..n-1)
Example: 2nd iteration
The stack content is 1 0 0 1, which represents two polynomials
1 0 -> 1 (0th polynomial; P)
0 1 -> x (1st polynomial; Q)
00} Push a 0 at the top and another 0 at the bottom
1 0 0 -> 1
0 0 1 -> x^2
L:2+F..| Push L, and then iterate L+2 times (L+2 is the number of pairs)
L
1 0 0
0 0 1
:} Put a copy of L to the bottom of the stack
L L
1 0 0
0 0 1
*$:@- Multiply L to the current coef of P, and subtract from that of Q
L
1 0 1-0*L
0 0 1
{@@}} Pull the copy of L back to the top, and rotate the two coefs to the bottom
L
1-0*L 1 0
1 0 0
At the end of this loop:
L
0-1*L 0-0*L 1-0*L
0 0 1
{$2+F$}}| Rotate once, consume L, and swap the positions for P and Q
0 1 0 -> new P
0-1*L 0-0*L 1-0*L -> new Q
LFN~|h Print Q from top to bottom and halt
```
## J path
A multi-line function evaluates each line sequentially, and returns the last line evaluated. So the relevant part is this (with `y` being the argument and `p` being a scratch global variable):
```
{{2*-/(0,p=:y),:p*#p}}^:y,1[p=:0$0
```
Within the inner function, `p` stores the previous polynomial, and the return value is the next polynomial. All polynomials are stored in little endian. As in the Gol><> part, `P` denotes the second-to-last polynomial and `Q` denotes the last polynomial.
```
{{2*-/(0,p=:y),:p*#p}}^:y,1[p=:0$0 y: value of n in H(n)
p=:0$0 Initialize P to zero polynomial
{{ }}^:y,1[ Iterate inner func n times to [1]...
p*#p each item of P times length of P
(0,p=:y),: Zip two arrays Q*x and the above, and update p to Q
2*-/ Subtract the 2nd row from 1st, and double
```
---
Just for fun and more golfiness, replacing J with the Mathematica built-in:
# [Gol><>](https://github.com/Sp3000/Golfish) and [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
```
(*1IF00}L:2+F:}*$:@-{@@}}|{$2+F$}}||LFN~|h*)#~HermiteH~x&
```
[Try it online in Gol><>!](https://tio.run/##S8/PScsszvj/X0PL0NPNwKDWx8pI282qVkvFykG32sGhtramWgUoogJk1Pi4@dXVZGhpKtd5pBblZpaketRVqP3/bwoA "Gol><> – Try It Online")
[Try it online in Mathematica!](https://tio.run/##y00syUjNTSzJTE78n2Yb819Dy9DTzcCg1sfKSNvNqlZLxcpBt9rBoba2ploFKKICZNT4uPnV1WRoaSrXeaQW5WaWpHrUVaj9DyjKzCtxSIs2jf0PAA "Wolfram Language (Mathematica) – Try It Online")
These combine smoothly because the comment starter in Mathematica `(*` pushes a single 0 in Gol><>.
[Answer]
# Using calculus package (for R)
## [Jelly](https://github.com/DennisMitchell/jelly), probabilist, 51 bytes
```
\(n)calculus::hermite(n)[[n+1]]$t$c#¶1W¤Ż_בɼ_Ɗ}Ḥʋ¡
```
[Try it online!](https://tio.run/##y0rNyan8/z9GI08zOTEnuTSntNjKKiO1KDezJBUoFh2dp20YG6tSopKsfGibYfihJUd3xx@e/qhhxsk98ce6ah/uWHKq@9DC//9NAQ)
## [R](https://www.r-project.org/) >= 4.1, physicist, 51 bytes
```
\(n)calculus::hermite(n)[[n+1]]$t$c#1WÒ_ü¦_}¯©
```
[Try it at RDRR](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction%28n%29calculus%3A%3Ahermite%28n%29%5B%5Bn%2B1%5D%5D%24t%24c%23%7F1W%03%D2_%11%FC%A6_%91%7D%AF%A9%00%0Af%285%29)
[Try both online](https://tio.run/##lZJNa@MwEIbv@RWDUohEjF1v6ZYaQi976qVgCnuwTPCH3KjIklYag33ob89KyWJy6GUNtqTRM/O@8sgueDL64SxHaxzCp1BqScD4BPwSPpNTSrapbZwX58704tDuOKeadY3qJjX5ojgJN0oUIVZVep/X9R3edVs@Pw35bz7fP/C5/3Hkc57zeej43PwMi@f8K8yG8D4H5H53DrqH3S79NFLT6mIijWpH23yISmqkM6thMA5mkBriVs021sUdsoXXq2sCe/DoqBKaRoSxECDQLig812RNgPBENuisMa7fJrQTFlxzfQESELoPptjm6mdsgrcwTaCqE4jxNZXrLZT/rx@ZtBdxoEQ1KHVO2PeObtyEvqQeezNhOoQGnCjbuOO1NVGIkuHA9TDpDqWJeWvlfYSqvKj3/8CA0Ud2i2y2JhRfPIqRksxYzFzWSp2VvnPSIlijlg9lMJCud@5ATojWF1kWV6k0mdfSWoE@E2Mr@uzl4iue9fYipX8mEy7M1fV63urdLSARGoTyV1nWNKbFuvEnMsLOj38B) (sort of - no calculus package on tio so produces link to RDRR)
---
# No external packages
## [Jelly](https://github.com/DennisMitchell/jelly), probabilist, 81 bytes
```
\(n){a=1[-1];for(i in seq_len(n))T=-c(a,0,0)*(i-1)+c(0,a<-T);T+0}#¶1W¤Ż_בɼ_Ɗ}Ḥʋ¡
```
[Try it online!](https://tio.run/##AWgAl/9qZWxsef//XChuKXthPTFbLTFdO2ZvcihpIGluIHNlcV9sZW4obikpVD0tYyhhLDAsMCkqKGktMSkrYygwLGE8LVQpO1QrMH0jwrYxV8Kkxbtfw5figJjJvF/Gin3huKTKi8Kh////NQ "Jelly – Try It Online")
## [R](https://www.r-project.org/) >= 4.1, physicist, 81 bytes
```
\(n){a=1[-1];for(i in seq_len(n))T=-c(a,0,0)*(i-1)+c(0,a<-T);T+0}#1WÒ_ü¦_}¯©
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7M60dYwWtcw1jotv0gjUyEzT6E4tTA@JxUkpxliq5uskahjoGOgqaWRqWuoqZ2sYaCTaKMbomkdom1Qq1xvGM58eFK84OE9h5bFH5pYe2j9oZX/0zRMNf8DAA)
A full program in Jelly and a function in R both of which take an integer; the Jelly one takes it via STDIN. Note this is the same code for both, but in the Jelly codepage for Jelly and latin1 codepage for R. Both return the polynomial as the coefficients starting with the coefficient for \$x^0\$.
[Python script to try both online](https://tio.run/##lZFRa9swEMff8ykO5SHS4jhWSzeazl9gL4US2INlgmPLjYpz0iyZ2JR@9uyUQrrCHjaB0Onu/7/7CbkpHCzens3R2T7Ai@66KQHrE/CTP9e20fl@oRRH8VrlsljJ8qG1PTdgELz@tes0Uk1s81XNqyRLMvGFm5UUy5pnSfV9tRUP22X2Nlfjt1b@VGN2q8bmZqdGKdXY1mqsvtLlXr5R1NK@J0m2OBNHvlikL9YgLy5QaWTZuepZFwYDH0UJBAJjBImlUsxcHytsDj/eX8FgCT70PDJGiRCUYLCfgvYK2dUAtKKW5lxzCh@H4IawUajwIkhAY0NQYvbOc6yIjcIEijKBmL9aFc7h6f/nR03a6Hhw1lXBoGTin4jor1IfGjuEtO0Gf@BidjLhANbRaOZsNz13NpCBnfZMQOWhNZ3ezC5HeupN0PyCxVmbK2wHrIOxGA0fHH@KI2MhN6X4WwtqwO/EZ7MlwMkHfeRsbV1Y9@u9wfWTr3vjAlwJxfnuNw)
[Answer]
# [Mathics](http://mathics.github.io/) + [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Expand[s=Sqrt@Depth@{};HermiteH[#,x/s]/s^#]&
```
[Try it online (Mathics physicist)!](https://tio.run/##y00sychMLv6foWD737WiIDEvJbrYNriwqMTBJbWgJMOhutbaI7UoN7Mk1SNaWadCvzhWvzhOOVbtv0t@dEBRZl5JdJ6Crp1CRnRebKyOQnWejoKBjoKhQW3sfwA "Mathics – Try It Online")
[Try it online (Mathematica probabilist)!](https://tio.run/##BcGxCoAgEADQXzkImoxqjqKhoDFoPC6QEnTwKr1BiL7d3vNarPFa3KGzhT7P6dZ8Yuy3J8g4mVvs@H7dYoJ3YhYsVKoj1XEvqMzThWtwLMhQDWCRiRS8rKBR0DYf5R8 "Wolfram Language (Mathematica) – Try It Online")
Mathics and Mathematica are two different implementations of the Wolfram Language. According to [this meta post](https://codegolf.meta.stackexchange.com/questions/13593/default-recommended-ruling-on-counting-implementation-variants-of-languages-as), they are considered different languages.
`Depth@{}` returns `1` in Mathics, `2` in Mathematica.
I'm not sure if `Expand` is necessary. Without it the Mathematica probabilist answer would return unsimplified results like `(-6*Sqrt[2]*x + 2*Sqrt[2]*x^3)/(2*Sqrt[2])`.
] |
[Question]
[
An **[unrooted binary tree](https://en.wikipedia.org/wiki/Unrooted_binary_tree)** is an unrooted tree (a graph that has single connected component and contains no cycles) where each vertex has exactly one or three neighbors. It is used in bioinformatics to show evolutionary relationships between species.
If such a tree has \$n\$ internal nodes, it necessarily has \$n+2\$ leaves. Therefore it always has an even number of vertices.
## Challenge
Given a positive integer \$n\$, compute the number of distinct unrooted, unlabeled binary trees having \$2n\$ vertices. This is OEIS [A000672](http://oeis.org/A000672). You may take \$2n\$ as input instead, and in that case, you may assume the input is always even.
The shortest code in bytes wins.
## Illustration
```
n=1 (2 nodes, 1 possible)
O-O
n=2 (4 nodes, 1 possible)
O
\
O-O
/
O
n=3 (6 nodes, 1 possible)
O O
\ /
O-O
/ \
O O
n=4 (8 nodes, 1 possible)
O O
\ /
O-O
/ \
O O-O
/
O
n=5 (10 nodes, 2 possible)
C
\
A B C O-C
\ / \ /
O-O A O-O
/ \ / / \
A O-O C O-C
/ \ /
B A C
n=6 (12 nodes, 2 possible)
(branching from A) (branching from B or C)
O O
/ \
O-O O O O-O
\ / \ /
O-O O O-O O
/ \ / / \ /
O O-O O O-O
/ \ / \
O O O O
```
## Test cases
The values for first 20 terms (for \$n=1\dots 20\$) are as follows:
```
1, 1, 1, 1, 2, 2, 4, 6, 11, 18,
37, 66, 135, 265, 552, 1132, 2410, 5098, 11020, 23846
```
[Answer]
# JavaScript (ES6), 265 bytes
This code actually builds all possible trees and filters out isomorphic results. This is quite slow for \$n>9\$ but \$a(10)=18\$ was checked locally.
```
n=>(K=A=>A.map(a=>[...a].sort()).sort(),g=(A,k)=>k>n-3?g[K(A)]||(N--,P=(p,a)=>a.map((v,i)=>P([...p,v],a.filter(_=>i--)))+a?1:g[K(A.map(a=>a.map(v=>~p[v])))]=1)(i=[],A.map(_=>--i)):A.map((a,i)=>a.some((v,j)=>~v?0:a[g([...A,[i,v,v]],a[j]=-~k),j]=v)))([[N=-1,N,N]])|~N
```
[Try it online!](https://tio.run/##NY7BbsIwEETvfIUPHHbF2mrUU2nXUc5IEXfLKhZNIgdwogT5AuTXUxPa02i0s/OmddGNx8H3Vxm6n2queQ6sYccF60JdXA@OtVFKOavGbrgC4p9Sw1DQCVmfdJDveWN2UKC936GUkvYMPbl0dEsJRPLJ7OFZ1VO05FTtz9dqgG/WXkpE3Lg82y4t/9zXb2Q99SbaFLGcIXg2ll6Z9CulR9y@LLiF4tLCS/VktslNMX/bOtMs6IKMp5j4aYBpLcvphJQ0pnIwpmSZUUmltXifyrnuBgiCRfYpgvhi8ZF0s0FxWwlx7MLYnSt17ho4OFjfwgNTdH2rIeDjgKvH/As "JavaScript (Node.js) – Try It Online")
## How?
### Tree representation
Only internal nodes are stored explicitly as triplets \$[n\_0,n\_1,n\_2]\$ where each value is either the 0-indexed ID of another internal node, or \$-1\$ for a leaf.
The final list of triplets can be normalized with the helper function \$K\$ which first sorts each triplet and then the entire list:
```
K = A => A.map(a => [...a].sort()).sort()
```
### Main algorithm
The main recursive function \$g\$ builds all possible trees with \$n-1\$ internal nodes1. We start with an arbitrary root node \$[-1,-1,-1]\$ and attach each new internal node to the first available slot in one of the previous nodes.
For the first iteration, there's only one possible option:
$$\big[[-1,-1,-1]\big] \rightarrow \big[[1,-1,-1],[0,-1,-1]\big]$$
The underlying object of \$g\$ is also used to store all normalized trees that were already found.
Whenever a new tree is generated, we use the helper function \$P\$ to generate all permutations of the vertex identifiers. This allows us to store in \$g\$ all normalized trees that are isomorphic to the one we've found.
---
*1: For obscure golfing reasons, the code actually generates at least 2 internal nodes. This is inconsistent for \$n<3\$ but leads to only one possible tree anyway, which is the expected result.*
[Answer]
# JavaScript (ES6), 267 bytes
A slightly longer but *much* faster version that implements the formula described in [A000672](http://oeis.org/A000672), which itself is based on [A001190](http://oeis.org/A001190).
```
n=>n<5||-(b=n=>(B=(n,g=i=>i<n/2&&B(i)*B(n-i)+g(i+1))=>v=n%1?0:n<2?n:g(1)+B(n/2)*-~v/2)(n+1))(n)+b(--n/2)+2*b(n)-2*(C=(n,r)=>!r||C(n,--r)*(r-n)/~r)(1+b(--n/3),3)-(S=(c,b,i=1)=>i>b?0:c(i)+S(c,b,i+1))(i=>C(b(i),2)*b(n-2*i),~-n/2)+S(i=>b(i)*S(j=>b(j)*b(n-j),--n/2,i),n/3)
```
[Try it online!](https://tio.run/##LY9NboMwEIX3OYUrpdEMtktM1E2KiQRH4AIBGpBRNFROxYafq9Nx0pWf573x99xXY/VovPv51TR837bWbmQzSj/nWUNtWUNugVRnnc1cSnFyOOTgMMqBtEPZgZMG0WajpXdzOZ4pTS507sCg5EicYKTXkQ@gkANCWYPWwZBJVPNdJxEUAeH5lTc/zwVrrT1G4DVhvHoE8790QnVCDaWFRtXKWcMrLqsZ23AnWb7GTxDXLaDmqeIKzGEM6/VFLoMdzKiEPqj@lelRPbspjgba1g4eSFhhvgSJ1IrkyEJKFNNOiGagx3C/fdyHDq4V7CdakLP7Sbb8r@WKu2X7Aw "JavaScript (Node.js) – Try It Online")
Please [follow this link](https://tio.run/##bVFBbtswELzzFVMgDchIqiUHPSS1EtR6gj8QUZFcGfYqoCQXhWN/3R2KTpoAvZC75Mzuzuym3Jd95dqXIZHuuT6fZzNU3e5lHOoeP9M0y@5SLSZG5@DqYXTSI0XbQND2kG5AyUiGel07tUQOrQCJeayZtMgfeCyInmGO62ssdWtww0uQgGGEtW55ZkYZgsnbkyf4igyP7HTPeEHqI@97YjNP8WzW84WS096HSv137lDYThU5yfLt5RNaCgd90bSAM6rwMiRm6ElfHF5fUfiHJHG@p3acXQz7ntznUv240xUVGjT0i@pRYuhgY/xuh19Mcsqyf/BcN@W4HdTKd6piD/DgzAS/HmAv4n0xjrx6B72PvytbQTNKNbSdqAa5kuCfF/GdIzNMLFfHO4LVSRI8m9I5VVz@kikpdPYBdct934bPlZ52WGjLSeLguZ2W52n@6fSx8AVuw5ZXehOyzT/axngfJ0o88UPDMw3jPz344RXkmKcMosjgwMJVJ323rb9tu7V@KvXVQY60CleHqKGK45NRx/Nf) for a formatted version of the code.
] |
[Question]
[
# Leaderboard
```
154 Calculator
144 Taxman
138 Statistician
137 Solver
137 RandoAggroLawyer
136 Gambler
134 Turncoat
119 Lawyer
119 BloodyMurder
113 Bandit
79 Challenger
74 Mask
64 Random
```
[An archive of the latest match, including the log and all output files, is available.](https://drive.google.com/open?id=1gSBM8g-dF9Nnx11WbfXS48yIsR2QBJXN)
**Calculator, by Brilliand, is the winner!** His answer is accepted, but that doesn't mean the challenge is over. Feel free to submit new entries or edit your current ones and try to knock him off his throne. Contests will be run with each new entry or edit for the foreseeable future.
# Rules of Play
[Coup](https://boardgamegeek.com/boardgame/131357/coup) is a card game designed for 2-6 players, which we shall play with two. It consists of a treasury of coins (infinite for our purposes) and a deck of 15 cards, containing 3 each of the following types: Ambassador, Assassin, Captain, Contessa, Duke. At the start of the game, each player is given one coin and dealt two cards at random, which they keep secret until necessary. The object is to be the last player with cards in your hand.
On their turn, a player may take one of the following actions regardless of their cards:
* Income: take 1 coin from the treasury. Unblockable and unchallengeable.
* Foreign Aid: take 2 coins from the treasury. Can be blocked by a player with a Duke. Unchallengeable.
* Coup: Remove a card of one opponent of your choice from play. Costs 7 coins. The victim may choose which card to discard. If a player has 10 or more coins at the start of their turn, they *must* Coup. Unblockable and unchallengeable.
Depending on their cards, players may also take one of the following actions as their turn:
* Exchange: a player with an Ambassador may take two cards from the deck. Then they may choose from their hand and the drawn cards as many cards as they originally had. (That is, if they had only one card they may exchange it for one of the drawn cards or keep it, and if they had two cards they may choose any two of the four cards.) The two undesired cards are returned to the deck. Unblockable, but challengeable.
* Assassinate: a player with an Assassin may spend 3 coins to remove an opponent's card from the game. The victim may choose which card to discard. Can be blocked by a player with a Contessa, in which case the coins are not returned. Challengeable, in which case the coins *are* returned.
* Steal: A player with a Captain may take two coins from their opponent. If the opponent has one coin, they will take that one coin. If the opponent has zero coins, they may not Steal. Can be blocked by a player with an Ambassador or a Captain. Challengeable.
* Tax: A player with a Duke may take 3 coins from the treasury. Unblockable, but challengeable.
The tricky part of Coup is that **players are allowed to lie about what cards they have!** One need not have a card to attempt to perform the action or block associated with it.
When a player performs a card's action, any opponent (even one who is not harmed by that action) may challenge the actor and say they do not believe they have the card for that action. If the challenger is correct, the action is cancelled and the actor must discard one card of their choice (gaining back any coins they spent if applicable). If not, the action is taken, the actor returns the card they were challenged about to the deck and draws a new one, and the challenger must discard one of their cards. Players must be truthful about what cards they hold when challenged.
Cards eliminated from play with Assassinate, Coup, and lost challenges are not returned to the deck, but cards revealed as part of a won challenge are returned to the deck.
Blocks may be challenged just like actions. For example, if player A claims Foreign Aid and player B says "I have a Duke and I block your Foreign Aid", A may say "I don't believe you have a Duke." If that assertion is correct, B loses a card for being caught in a lie and A takes 2 coins; if it is not, A loses a card and gets no coins, and B must return their Duke to the deck and draw a new card.
The way blocks and challenges work with Assassinate must be fleshed out. Suppose Player A says "I have an Assassin, and I Assassinate Player B". If B does not attempt to challenges or blocks A, then the assassination goes through: B loses a card and A pays 3 coins.
Alternatively, B can challenge by saying "I don't believe you have an Assassin". If that is true, then A discards a card and their coins are returned, while B is unaffected, and A's turn ends. If B's belief is incorrect and A holds an Assassin, then B loses both their cards and fails, one for the incorrect challenge and one from the Assassination.
Instead of challenging, B could say "I have a Contessa, and I block the Assassinate". If A believes B, then A's turn ends and their coins are not returned. But A can challenge the block and say "I don't believe you have a Contessa." If B does in fact hold a Contessa, then A loses a card for the incorrect challenge. But if B does not, then B loses one card for being caught in a lie and another from the Assassination.
Similar logic to the above explanation applies to the Captain’s Steal ability, where either the action or the block can be challenged.
It is possible to lose both your cards and be eliminated in one turn, if you unsuccessfully challenge an Assassinate or you are caught falsely claiming you have a Contessa to block an Assassination. You lose one card from the challenge and one card from the Assassination.
# Challenge
Your task is to write a program that will play Coup. It will be given as its command line arguments:
* The name of a file containing the list of its and its opponents' actions so far.
* An integer from 0 to 12 indicating the opponent's coin count.
* An integer from 0 to 12 indicating its coin count.
* A string from one to four characters long indicating its cards. Normally this will simply be the one or two cards your program has, but if your program has just succeeded at an Exchange, it will be *n* + 2 characters long, where *n* is your number of cards remaining. Your program must then output the *n* cards it wishes to keep to STDOUT. (Programs must not read or access STDOUT other than for this purpose — if you wish to produce debug output, please write to STDERR.)
* One or more arguments indicating the legal moves it may make.
(Example invocation: `yourprogram file.txt 1 7 '~!' a c p q`, meaning "Your opponent has 1 coin. You have 7 coins, an Ambassador, and a Contessa. Write to file.txt your choice of a, c, p, or q given the game history and current game state.")
Your program must append one or (in two specific situations) two characters to the provided file indicating its action. It must not otherwise alter the existing contents of the file. It may create any new files it wishes, but only within the directory in which it is run. Please provide all necessary commands to compile and run your program.
I have provided two example competitors below, written in Go.
The output format is:
* `I\n`: Income. Legal responses: any turn action (assuming one has the coins for Assassinate/Coup).
* `F`: Foreign aid. Legal responses: `d` (block as a Duke), `p` (let it pass).
* `C`: Coup. Legal responses: whichever of `_`, `'`, `<`, `=`, `0` is in your hand.
* `E`: Exchange. Legal responses: `q` (challenge, not believing the player has an Ambassador), `p`.
* `T`: Tax. Legal responses: `q` (challenge, not believing the player has a Duke), `p`.
* `A`: Assassinate. Legal responses: `s` (block as a Contessa), `q` (challenge), and whichever of `_`, `'`, `<`, `=`, `0` is in your hand.
* `S`: Steal. Legal responses: `a` (block as an Ambassador), `c` (block as a Captain), `q` (challenge, not believing the player has a Captain), `p`.
* `d`: block Foreign Aid as a Duke. Legal responses: `\n` (accept the block), `q` (challenge, not believing the player has a Duke).
* `a`: block a Steal as an Ambassador. Legal responses: `\n` (accept the block), `q` (challenge, not believing the player has an Ambassador).
* `c`: block a Steal as a Captain. `\n` (accept the block), `q` (challenge, not believing the player has a Captain).
* `s`: block an Assassinate as a Contessa. Legal responses: `\n` (accept the block), `q` (challenge, not believing the player has a Contessa).
* `p`: pass challenging an Exchange/Tax/Steal when it is not your turn. **Not used with `A`; to decline to challenge an Assassination write one of `_'<=0`.** Legal response: `\n` (end your turn), and if you have just succeeded at an Exchange, writing the cards you wish to keep from the fourth command line argument to STDOUT.
* `q`: challenge the most recent action or block. Legal response: if you have the card for the action that was challenged, whichever of `~^*!$` it was. If you don't, then whichever of `_'<=0` from your hand which you wish to give up, followed by a newline if and only if it is your turn.
* `~`, `^`, `*`, `!`, `$`: reveal that you were telling the truth about holding, respectively, an Ambassador, an Assassin, a Captain, a Contessa, and a Duke (also used to represent these cards in command line arguments, and STDOUT output in an Exchange). Legal responses: whichever of `_`, `'`, `<`, `=`, `0` you have in your hand.
* `_`, `'`, `<`, `=`, `0`: give up as punishment, respectively, an Ambassador, and Assassin, a Captain, a Contessa, and a Duke because you lost a challenge or were Assassinated/Couped. Legal response: `\n`.
* `\n`: end your turn, in doing so declining to challenge a block if applicable. Legal responses: any capital-letter action (assuming one has the coins for Assassinate/Coup and the opponent has the coins for Steal).
The format has the following useful properties:
* Turns begin with a capital letter.
* Lines follow the pattern: uppercase letter, lowercase letters, optionally punctuation marks or 0 for revealed cards, newline.
* A file ending with a newline, or an empty file, indicates that it is the start of your program's turn and it must choose a capital letter action.
* The legal actions you are allowed to take on an invocation are usually uniquely determined by the last character in the file. The exception is `q`, which will have some logic associated with it. See the function `get_legal_actions` in the arbiter to help understand this. Or you can just use the legal actions you're given on the command line.
* An even number of characters on a line indicate that the turn is yours and your program is asked to choose an action, challenge a block, or end its turn.
* An odd number of characters on a line indicate that the turn is not yours and your program is asked to block, challenge, or reveal/surrender a card.
I will give an example for every action.
`I\n` is the easiest to understand. A program takes one coin of Income, then ends its turn. This is one of the two cases where programs must print two characters, as Income is the only action where the opponent is both unaffected and cannot block or challenge.
`Fp\n` means that one program took Foreign Aid, then its opponent declined to block (`p`). On its next invocation, the first program noted that by the final lowercase `p` and/or the even number of characters on this line it took this turn, which has not ended yet, so it knows to end its current turn by printing a newline.
`C=\n` means that one program launched a Coup. Its opponent, knowing that it was called to react by the odd number of letters on the line, gave up a Contessa. Again, the first program knew that this was its incomplete turn on its next invocation by the even number of characters on the line, so it wrote a newline to end its turn.
`Eq~<\n` would mean that one program attempted an Exchange (`E`) and its opponent challenged (`q`). The Exchanging program revealed that it truthfully had an Ambassador (`~`) and the challenger gave up a Captain as punishment (`<`). After the challenger exits, the Exchanging program is invoked again with a four-character string as its fourth command-line argument (or three characters, if it had only one card). It writes the characters representing the cards it wishes to keep to STDOUT and a newline to the file.
`Tq'\n` means that one program attempted an untruthful Tax, was challenged, and gave up an Assassin. It illustrates the other case where two characters are written: if it is your turn and you are forced to give up a card — either from an opponent's correct challenge (as here) or from your incorrect challenge of a block — then you must write both the card you give up and a newline to end your turn.
`Asq!'\n` would mean that Player B attempted to Assassinate player A (`A`), but A claimed to have a Contessa to block it (`s`). B did not believe A and challenged (`q`). A revealed that they did, in fact, have a Contessa (`!`). B gave up an Assassin as punishment, losing their coins, and ended their turn (`'\n`), writing two characters as in that special case. (If A had decided not to block or challenge, it could have written `=`, and then its opponent would have seen that the turn was over and written a newline. The line would then have read `A=\n`, like the Coup example.)
`Sq*0\n` means that one program attempts a Steal; the opponent challenges, not believing the thief has a Captain; and the original program reveals a Captain, so the challenge is unsuccessful and the challenger gives up a Duke as punishment. (Another option for its opponent would be to accept the Steal by writing `p`. Its opponent would then detect the end of its turn and write `\n`, resulting in a line of `Sp\n`.)
## The Arbiter
Programs will be invoked by this Python script. It conducts ten rounds, in which every competitor faces every other competitor while going both first and second. It tracks cards and coin counts and determines the loser by the first program to end a line with a punctuation mark twice. Programs that exit with a non-zero status, modify the file, write an illegal move to the file, or attempt an illegal Exchange will automatically forfeit. If each player takes more than 100 actions, including blocks and challenges, with no winner, then both programs lose. A winner is granted one point. The player whose program scores the most points wins.
I suggest you read the Arbiter's source code, especially the `get_legal_actions` function. It may help you understand the specification and write your own programs.
```
import itertools
import os
import random
import subprocess
class Player:
def __init__(self, name, command):
self.name = name
self.command = command
self.score = 0
self.coins = 1
self.cards = ""
actions_dict = {
'E': '_', 'T': '0', 'A': "'", 'S': '<',
'd': '0', 'a': '_', 'c': '<', 's': '='
}
punishment_to_reveal = {'_': '~', "'": '^', '<': '*', '=': '!', '0': '$'}
reveal_to_punishment = {
punishment_to_reveal[k]: k for k in punishment_to_reveal
}
def get_legal_actions(history, player, opponent):
c = history[-1]
result = ""
# Our turn begins; choose an action.
if c == '\n':
if player.coins >= 10:
return ["C"]
ret = ['I\n'] + list("FET")
if player.coins >= 3:
ret.append("A")
if player.coins >= 7:
ret.append('C')
if opponent.coins > 0:
ret.append("S")
return ret
# Opponent attempted foreign aid; can pass or claim Duke to block.
elif c == 'F':
return list('dp')
# We have been Couped; must surrender a card.
elif c == 'C':
return player.cards
# We failed a challenge; must surrender a card and print a newline
# if it is our turn.
elif c in '~^*!$':
if history[-3] in 'acds':
return [card + '\n' for card in player.cards]
return player.cards
# Opponent attempted Exchange or Tax; can pass or challenge.
elif c == 'E' or c == 'T':
return list('pq')
# Opponent attempted an Assassination; can block, challenge, or give in.
elif c == 'A':
return list('sq') + player.cards
# Opponent attempted to Steal; can pass, block as Ambassador/Captain,
# or challenge.
elif c == 'S':
return list('acpq')
# Opponent blocked; can challenge or withdraw.
elif c in 'acds':
return list('q\n')
# Opponent passed on blocking Foreign Aid/Tax/Exchange or they gave up a
# card as punishment, must end turn.
elif c in "p_'<=0":
return ['\n']
# Opponent challenged us.
elif c == 'q':
challenged_action = history[-2]
# If we have the card they challenged us over, must reveal it.
necessary_card = actions_dict[challenged_action]
if necessary_card in player.cards:
return [punishment_to_reveal[necessary_card]]
# Otherwise, we can give up either of our cards, writing a newline
# if it is our turn.
if challenged_action in 'acds':
return list(player.cards)
else:
return [card + '\n' for card in player.cards]
else:
return None
deck = ['_', "'", '<', '=', '0'] * 3
random.shuffle(deck)
def determine_turn_effects(line, output, cards, current_player, opponent):
last_action = line[-2]
# Only operate if the opponent declined to challenge (p) or the
# program successfully challenged their block
if last_action in "p_'<=0":
primary_action = line[0]
# Foreign Aid
if primary_action == 'F':
print current_player.name, "received 2 coins of Foreign Aid"
current_player.coins += 2
# Tax
elif primary_action == 'T':
print current_player.name, "received 3 coins of Tax"
current_player.coins += 3
# Steal
elif primary_action == 'S':
stolen_coins = 1 if opponent.coins == 1 else 2
print current_player.name,\
"stole %d coins from %s" % (stolen_coins, opponent.name)
current_player.coins += stolen_coins
opponent.coins -= stolen_coins
# Exchange, store desired cards and replace undesired ones
elif primary_action == 'E':
print current_player.name, "tried to take %r" % output, "from", cards
legal_outputs = [''.join(p) for p in itertools.permutations(
cards, len(current_player.cards))]
if output not in legal_outputs:
print current_player.name, "forfeits by illegal exchange"
return opponent
current_player.cards = [
reveal_to_punishment[c] for c in output
]
undesired_cards = list(cards)
for c in output:
undesired_cards.remove(c)
for card in undesired_cards:
deck.append(reveal_to_punishment[card])
random.shuffle(deck)
# Coins are not returned from a successful Contessa block
elif last_action == 's':
print current_player.name, "lost 3 coins from a Contessa block"
current_player.coins -= 3
return None
def play_game(player1, player2, round_number, game_number):
outfilename = os.path.abspath(__file__)[:-len(__file__)] + '_'.join([
player1.name, player2.name, str(round_number), str(game_number)
]) + '.txt'
print outfilename
f = open(outfilename, 'w')
f.close()
players_list = [player1, player2]
player1.cards = [deck.pop(), deck.pop()]
player2.cards = [deck.pop(), deck.pop()]
current_player_index = 0
for i in range(200):
current_player = players_list[current_player_index]
opponent = players_list[(current_player_index+1) % 2]
legal_actions = []
original_contents = []
original_contents_joined = ""
with open(outfilename, 'r') as outfile:
original_contents = outfile.readlines()
original_contents_joined = ''.join(original_contents)
if len(original_contents) == 0:
legal_actions = ['I\n'] + list("FEST")
else:
legal_actions = get_legal_actions(
original_contents[-1], current_player, opponent)
if not legal_actions:
print "Error: file ended in invalid character"
return current_player
# Has the player completed an Exchange? Pass them new cards if so.
exchange_cards = ""
old_last_line = original_contents[-1] if len(original_contents) > 0 else '\n'
if old_last_line[-1] != '\n' and old_last_line[0] == 'E' and \
len(old_last_line) % 2 == 0 and old_last_line[-1] in "p_'<=0":
exchange_cards = punishment_to_reveal[deck.pop()] + \
punishment_to_reveal[deck.pop()]
cards = exchange_cards + ''.join(
punishment_to_reveal[card] for card in current_player.cards)
args = current_player.command + [
outfilename,
str(opponent.coins),
str(current_player.coins),
cards
] + legal_actions
print ' '.join(args)
output = ""
os.chdir(current_player.name)
try:
output = subprocess.check_output(args)
# Competitors that fail to execute must forfeit
except subprocess.CalledProcessError:
print current_player.name, "forfeits by non-zero exit status"
return opponent
finally:
os.chdir('..')
new_contents = []
new_contents_joined = ""
with open(outfilename, 'r') as outfile:
new_contents = outfile.readlines()
new_contents_joined = ''.join(new_contents)
if original_contents_joined != new_contents_joined[:-2] and \
original_contents_joined != new_contents_joined[:-1]:
print current_player.name, "forfeits by modifying the file"
print "old:", original_contents
print "new:", new_contents
return opponent
new_last_line = new_contents[-1]
the_move_made = ""
for action in legal_actions:
if new_last_line.endswith(action):
the_move_made = action
break
# Competitors that make an illegal move must forfeit
if not the_move_made:
print current_player.name, "forfeits with an illegal move,",\
"last line: %r" % new_last_line
print opponent.name, "wins!"
return opponent
print current_player.name, "played %r" % the_move_made
# Side effects of moves.
#
# Income, give the current player a coin.
if the_move_made == "I\n":
print current_player.name, "received 1 coin of income"
current_player.coins += 1
# The program surrendered a card on its turn; take it away.
elif len(the_move_made) == 2:
print current_player.name, "lost a card from being challenged"
current_player.cards.remove(the_move_made[0])
# Coins are not returned from a successful Contessa block
if new_last_line[-3] == '!':
print current_player.name, "lost 3 coins from a Contessa block"
current_player.coins -= 3
# The program surrendered a card when it was not its turn.
elif the_move_made in "_'<=0":
print current_player.name, "gave up a", the_move_made
current_player.cards.remove(the_move_made)
if new_last_line[0] == 'C':
opponent.coins -= 7
elif new_last_line[0] == 'A':
opponent.coins -= 3
# Did the program unsuccessfully challenge an Assassination
# (e.g. Aq^0\n)
# or get caught falsely blocking with a Contessa
# (e.g. Asq0\n)?
# If yes, it loses right away.
if new_last_line[0] == 'A' and new_last_line[1] in 'qs' and \
len(new_last_line) == 4:
print current_player.name, "lost both cards in the same turn."
print opponent.name, "wins!"
return opponent
elif the_move_made == 'S':
print current_player.name, "attempted Steal"
elif the_move_made == 'T':
print current_player.name, "attempted Tax"
elif the_move_made == 'A':
print current_player.name, "attempted Assassinate"
elif the_move_made == 'C':
print current_player.name, "launched a Coup"
elif the_move_made == 'F':
print current_player.name, "attempted Foreign Aid"
elif the_move_made == 'E':
print current_player.name, "attempted Exchange"
elif the_move_made == 'q':
print current_player.name, "challenged"
elif the_move_made == 'p':
print current_player.name, "passed"
elif the_move_made == 'a':
print current_player.name, "blocked with an Ambassador"
elif the_move_made == 'c':
print current_player.name, "blocked with a Captain"
elif the_move_made == 's':
print current_player.name, "blocked with a Contessa"
elif the_move_made == 'd':
print current_player.name, "blocked with a Duke"
# The program revealed a card from an opponent's unsuccessful challenge.
# Give it a new card.
# Special case: a program whose Exchange is unsuccessfully challenged
# may keep the Ambassador it revealed in the Exchange, so give a new
# card for a revealed Ambassador only if it was used to block a Steal.
elif the_move_made in '^*!$' or (the_move_made == '~' and
new_last_line[0] == 'S'):
p = reveal_to_punishment[the_move_made]
current_player.cards.remove(p)
current_player.cards.append(deck.pop())
deck.append(p)
random.shuffle(deck)
print current_player.name, "did have a", the_move_made
# The program ended its turn. We must examine the rest of the line to
# determine the side effects.
elif the_move_made == '\n':
potential_winner = determine_turn_effects(
new_last_line, output.strip(), cards, current_player,
opponent)
if potential_winner:
print potential_winner.name,\
"wins because their opponent made an illegal exchange!"
return potential_winner
# One player has lost all their cards. Victory for the opponent!
if current_player.cards == []:
print opponent.name, "wins by eliminating both opponent cards!"
return opponent
current_player_index += 1
current_player_index %= 2
return None
competitors = []
competitors.append(Player("Challenger", ["./challenger"]))
competitors.append(Player("Random", ["./random"]))
# ...More competitors here
for i in range(10):
print "-- Round", i
j = 0
for pairing in itertools.permutations(competitors, 2):
player1, player2 = pairing
print '--- Game', j, ':', player1.name, 'vs.', player2.name
winner = play_game(player1, player2, i, j)
if not winner:
j += 1
continue
winner.score += 1
player1.coins = 1
player1.cards = ""
player2.coins = 1
player2.cards = ""
deck = ['_', "'", '<', '=', '0'] * 3
random.shuffle(deck)
j += 1
competitors.sort(reverse=True, key=lambda player: player.score)
for player in competitors:
print '%5d %s' % (player.score, player.name)
```
## Miscellaneous
One program can not have code specific for another program, and programs can not help each other. (You may have multiple programs, but they can't interact with each other in any way.)
If your program loses both its cards in the same turn, it need only write one. The Arbiter will detect that it has been eliminated.
It is possible and encouraged, but not required, for programs to examine the game's history in the file. By doing so they can determine what cards their opponent has claimed to have and catch them in a lie.
In the real game of Coup, you can challenge an action and then attempt to block it in the same turn. I could not make the specification work if I allowed that, so you may either challenge or block a given action, but not both.
My apologies to @PeterTaylor, who on the previous time I posted this suggested I post it to the sandbox and rework the protocol to pipe output back and forth in STDOUT/STDIN. I tried so, so hard to make that work, spending a full day on it (when I'd already spent a full day writing the original challenge). But Exchanges proved very complicated to implement that way, plus it would have increased the complexity of submissions by requiring them to keep track of their own coin count. So I have posted the challenge more or less as it was originally.
[Answer]
# Calculator
Plans out his winning series of moves, and challenges anything that would prevent him from winning.
```
from __future__ import division
import sys
import random
import operator
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legalActions = sys.argv[5:]
actions_dict = {'E': '_', 'T': '0', 'A': "'", 'S': '<', 'd': '0', 'a': '_', 'c': '<', 's': '='}
punishment_to_reveal = {'_': '~', "'": '^', '<': '*', '=': '!', '0': '$'}
reveal_to_punishment = {punishment_to_reveal[k]: k for k in punishment_to_reveal}
obviousActions = ['~', '^', '*', '!', '$']
lossActions = ['_', "'", '<', '=', '0']
statefilename = './state.txt'
flags = set()
# Flags:
# 1 We went first
# $ Attacking with Duke
# * Attacking with Captain
# ^ Attacking with Assassin
# d Opponent used Duke
# c Opponent used Captain
# A Opponent used Assassin
# F Opponent used Foreign Aid
with open(statefilename, "a+") as statefile:
statefile.seek(0)
if statefile.readline().strip() == filename:
flags = set(statefile.readline().strip())
with open(filename, "r+") as history:
line = "\n"
turn = 0
oppcardcount = 4 - len(mycards)
for a in history:
line = a
turn += 1
if [c for c in line if c in lossActions]:
oppcardcount -= 1
else:
flags.add("1")
mycoins = int(mycoins)
othercoins = int(othercoins)
mycardcount = len(mycards)
if line == 'T':
othercoins += 3
flags.add('d')
elif line == 'S':
othercoins += (2 if mycoins > 2 else mycoins)
mycoins -= (2 if mycoins > 2 else mycoins)
flags.add('c')
elif line == 'A':
othercoins -= 3
mycardcount -= 1
flags.add('A')
elif line == 'F':
flags.add('F')
elif line == 'I\n':
# If opponent is backing down, they're not so scary anymore
flags.discard('d')
flags.discard('c')
flags.discard('F')
# What's the least aggressive play that still wins?
iGetStolen = ('c' in flags and not '*' in mycards and not '~' in mycards)
iGetAssassinated = ('A' in flags and not '!' in mycards)
incomeTimeToWin = max(0,7*oppcardcount-mycoins)+oppcardcount if not iGetStolen else 1000
faidTimeToWin = max(0,7*oppcardcount-mycoins+1)//2+oppcardcount if not iGetStolen else 1000
dukeTimeToWin = max(0,7*oppcardcount+(2*(oppcardcount-mycardcount) if iGetStolen else 0)-mycoins+2)//(3 if not iGetStolen else 1)+oppcardcount
assassinTimeToWin = max(0,3*oppcardcount-mycoins)+oppcardcount if not iGetStolen else oppcardcount if mycoins >= 5*oppcardcount-2 else 1000
captainTimeToWin = max(0,7*oppcardcount-mycoins+1)//2+oppcardcount
faidAssassinTimeToWin = max(0,3*oppcardcount-mycoins+1)//2+oppcardcount if not iGetStolen else 1000
dukeAssassinTimeToWin = max(0,3*oppcardcount+(2*(oppcardcount-mycardcount) if iGetStolen else 0)-mycoins+2)//(3 if not iGetStolen else 1)+oppcardcount
captainAssassinTimeToWin = max(0,3*oppcardcount-mycoins+1)//2+oppcardcount
opponentMoneySpeed = (2 if iGetStolen else 3 if 'd' in flags else 2 if 'F' in flags and not '$' in mycards else 1)
opponentTimeToWin = max(0,(3 if iGetAssassinated else 7)*mycardcount-othercoins+opponentMoneySpeed-1)//opponentMoneySpeed+mycardcount
opponentTimeToWinCaptained = max(0,(3 if iGetAssassinated else 7)*mycardcount+2*(mycardcount-oppcardcount)-(othercoins-2 if othercoins>2 else 0)+opponentMoneySpeed-3)//(opponentMoneySpeed-2)+mycardcount if opponentMoneySpeed > 2 else 1000
def pickCardToLose():
favoriteCards = []
if dukeTimeToWin < opponentTimeToWin and '$' in mycards:
favoriteCards = ['$', '!', '*', '~', '^']
elif dukeAssassinTimeToWin < opponentTimeToWin and ('$' in mycards or '$' in flags) and '^' in mycards:
favoriteCards = ['^', '$', '!', '*', '~']
elif assassinTimeToWin < opponentTimeToWin and '^' in mycards:
favoriteCards = ['^', '!', '*', '~', '$']
elif captainTimeToWin < opponentTimeToWinCaptained and '*' in mycards:
favoriteCards = ['*', '!', '$', '^', '~']
elif faidTimeToWin < opponentTimeToWin and '^' in mycards and not 'd' in flags:
favoriteCards = ['!', '*', '~', '$', '^']
elif faidAssassinTimeToWin < opponentTimeToWin and '^' in mycards and not 'd' in flags:
favoriteCards = ['^', '!', '*', '~', '$']
elif captainAssassinTimeToWin < opponentTimeToWinCaptained and '*' in mycards and '^' in mycards:
favoriteCards = ['^', '*', '!', '$', '~']
else:
favoriteCards = ['!', '*', '~', '$', '^']
# Losing a card. Decide which is most valuable.
for k in favoriteCards:
if k in mycards:
cardToLose = k
return reveal_to_punishment[cardToLose]
action = legalActions[0]
if line == "\n":
# First turn behavior
if '$' in mycards and 'T' in legalActions:
action = 'T'
flags.add('$')
elif '*' in mycards and 'S' in legalActions:
action = 'S'
flags.add('*')
elif '^' in mycards and 'I\n' in legalActions:
action = 'I\n'
flags.add('^')
elif '~' in mycards and 'E' in legalActions:
action = 'E'
elif 'T' in legalActions:
# Contessa/Contessa? Need to lie.
action = 'T'
flags.add('$')
elif set(obviousActions).intersection(legalActions):
# Always take these actions if possible
for a in set(obviousActions).intersection(legalActions):
action = a
# This might change our strategy
flags.discard(action)
elif '$' in mycards and 'd' in legalActions:
action = 'd'
elif '~' in mycards and 'a' in legalActions:
action = 'a'
elif '*' in mycards and 'c' in legalActions:
action = 'c'
elif '!' in mycards and 's' in legalActions:
action = 's'
elif 'q' in legalActions and line[-1] in 'dacs':
# We're committed at this point
action = 'q'
elif 'q' in legalActions and '*' in flags and line[-1] in 'SE':
# Don't allow these when using a steal strategy
action = 'q'
elif 'q' in legalActions and turn == 1:
if line == 'T':
if mycards == '$$' or mycards == '^^' or mycards == '!!':
action = 'q'
else:
action = 'p'
flags.add('d')
elif line == 'S':
if '$' in mycards and '^' in mycards:
action = 'p'
flags.add('c')
else:
action = 'q'
elif line == 'E':
action = 'p'
elif line == 'A' and len(mycards) > 1:
# Don't challenge the first assasination. We'll get 'em later.
action = pickCardToLose()
flags.add('A')
elif line == 'A':
# Can't let this pass
action = 'q'
elif line == 'C':
# Taking damage
action = pickCardToLose()
elif len(line) == 2 and line[1] == 'q':
# My base action was successfully challenged
action = pickCardToLose()+"\n"
# Also stop claiming what we were challenged for
if line == "Tq":
flags.discard('$')
elif line == "Sq":
flags.discard('*')
elif line == "Aq":
flags.discard('^')
elif len(line) == 3 and line[1] == 'q':
# I failed challenging a base action
action = pickCardToLose()
elif len(line) == 3 and line[2] == 'q':
# My block was successfully challenged
action = pickCardToLose()
elif len(line) == 4 and line[2] == 'q':
# I failed challenging a block
action = pickCardToLose()+"\n"
else:
if 'p' in legalActions:
# Default to pass if no other action is chosen
action = 'p'
if dukeTimeToWin <= opponentTimeToWin and ('$' in mycards or '$' in flags):
if 'C' in legalActions:
action = 'C'
elif 'T' in legalActions:
action = 'T'
elif incomeTimeToWin <= opponentTimeToWin:
if 'C' in legalActions:
action = 'C'
elif 'I\n' in legalActions:
action = "I\n"
elif dukeAssassinTimeToWin <= opponentTimeToWin and ('$' in mycards or '$' in flags) and '^' in mycards and mycardcount > 1:
if 3*oppcardcount <= mycoins - (2*(oppcardcount-1) if iGetStolen else 0) and 'A' in legalActions:
action = 'A'
elif 'T' in legalActions:
action = 'T'
flags.add('^');
elif assassinTimeToWin <= opponentTimeToWin and '^' in mycards:
if 'A' in legalActions:
action = 'A'
elif 'I\n' in legalActions:
action = 'I\n'
flags.add('^');
elif captainTimeToWin <= opponentTimeToWinCaptained and '*' in mycards:
if 'C' in legalActions:
action = 'C'
elif 'S' in legalActions:
action = 'S'
elif 'I\n' in legalActions:
action = 'I\n'
flags.add('*');
elif faidTimeToWin <= opponentTimeToWin and not 'd' in flags:
if 'C' in legalActions:
action = 'C'
elif 'F' in legalActions:
action = 'F'
elif faidAssassinTimeToWin <= opponentTimeToWin and '^' in mycards and not 'd' in flags:
if 'A' in legalActions:
action = 'A'
elif 'F' in legalActions:
action = 'F'
flags.add('^');
elif captainAssassinTimeToWin <= opponentTimeToWinCaptained and '*' in mycards and '^' in mycards:
if 'A' in legalActions:
action = 'A'
elif 'S' in legalActions:
action = 'S'
flags.add('^');
flags.add('*');
elif 'q' in legalActions:
action = 'q'
# No winning strategy. Find something useful to do anyway.
elif 'C' in legalActions and not '^' in flags:
action = 'C'
elif 'S' in legalActions and '*' in flags:
action = 'S'
elif 'A' in legalActions and '^' in flags:
action = 'A'
elif 'E' in legalActions and '~' in mycards and dukeAssassinTimeToWin < opponentTimeToWin:
action = 'E'
elif 'F' in legalActions and not 'd' in flags:
action = 'F'
elif 'T' in legalActions:
action = 'T'
flags.add('$');
if action == 'q':
if line == 'T' or line == 'Fd':
flags.discard('d')
elif line == 'S' or line == 'Sc':
flags.discard('c')
elif line == 'A':
flags.discard('A')
history.write(action)
if len(mycards) > 2:
favoriteCards = []
if dukeTimeToWin < opponentTimeToWin and '$' in mycards:
favoriteCards = ['$', '!', '*', '~', '^']
elif dukeAssassinTimeToWin < opponentTimeToWin and ('$' in mycards or '$' in flags) and '^' in mycards:
favoriteCards = ['^', '$', '!', '*', '~']
elif assassinTimeToWin < opponentTimeToWin and '^' in mycards:
favoriteCards = ['^', '!', '*', '~', '$']
elif captainTimeToWin < opponentTimeToWinCaptained and '*' in mycards:
favoriteCards = ['*', '!', '$', '^', '~']
elif faidTimeToWin < opponentTimeToWin and '^' in mycards and not 'd' in flags:
favoriteCards = ['!', '*', '~', '$', '^']
elif faidAssassinTimeToWin < opponentTimeToWin and '^' in mycards and not 'd' in flags:
favoriteCards = ['^', '!', '*', '~', '$']
elif captainAssassinTimeToWin < opponentTimeToWinCaptained and '*' in mycards and '^' in mycards:
favoriteCards = ['^', '*', '!', '$', '~']
else:
favoriteCards = ['!', '*', '~', '$', '^']
# Losing two cards. Decide which is most valuable.
possibleCards = [k for k in favoriteCards if k in mycards]
if len(possibleCards) < len(mycards) - 2:
possibleCards = list(mycards)
random.shuffle(possibleCards)
mycards = ''.join(possibleCards[:(len(mycards)-2)])
print mycards
with open(statefilename, "w") as statefile:
statefile.write(filename+"\n")
statefile.write(''.join(list(flags))+"\n")
```
# Turncoat
Tells the truth at first, but starts lying when it stops being challanged. Also has some solver-behavior. (An approximation of how I behave when playing this game with humans)
```
import sys
import random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legalActions = sys.argv[5:]
actions_dict = {'E': '_', 'T': '0', 'A': "'", 'S': '<', 'd': '0', 'a': '_', 'c': '<', 's': '='}
punishment_to_reveal = {'_': '~', "'": '^', '<': '*', '=': '!', '0': '$'}
reveal_to_punishment = {punishment_to_reveal[k]: k for k in punishment_to_reveal}
obviousActions = ['C', '~', '^', '*', '!', '$']
lossActions = ['_', "'", '<', '=' '0']
statefilename = './state.txt'
myclaims = set()
otherclaims = set()
mycaughtlies = set()
othercaughtlies = set()
flags = set()
# Flags:
# * Opponent had a chance to challenge us just now
# & Opponent has stopped wildly challenging everything
# E We have exchanged at least once
# S Opponent did not block a steal. Go for the jugular!
# _ Opponent has lost a card
with open(statefilename, "a+") as statefile:
statefile.seek(0)
if statefile.readline().strip() == filename:
myclaims = set(statefile.readline().strip())
otherclaims = set(statefile.readline().strip())
mycaughtlies = set(statefile.readline().strip())
othercaughtlies = set(statefile.readline().strip())
flags = set(statefile.readline().strip())
def getFavoriteCards():
favoriteCards = []
if '*' in otherclaims:
favoriteCards.append('~')
elif not '~' in otherclaims:
favoriteCards.append('*')
if len(otherclaims) > (0 if '_' in flags else 1) and mycoins > 1 and not '!' in otherclaims:
favoriteCards.append('^')
favoriteCards.append('!')
favoriteCards.append('$')
if not '~' in favoriteCards:
favoriteCards.append('~')
return favoriteCards
def pickCardToLose():
# Losing a card. Decide which is most valuable.
favoriteCards = getFavoriteCards()
cardToLose = ''
for k in favoriteCards:
if k in mycards:
cardToLose = k
for k in mycards:
if not k in favoriteCards:
cardToLose = k
return reveal_to_punishment[cardToLose]
with open(filename, "r+") as history:
line = "\n"
for a in history:
line = a
if 'q' in legalActions:
otherclaims.add(punishment_to_reveal[actions_dict[line[-1]]])
if len(line) > 2 and line.endswith('\n') and line[-2] in lossActions:
otherclaims.discard(punishment_to_reveal[line[-2]])
flags.add('_')
if len(line) > 2 and line.endswith('\n') and (line.startswith('Ep') or line.startswith('Eq~')):
othercaughtlies = set()
if '*' in flags:
flags.discard('*')
if line[-1] not in 'qdacs':
flags.add('&')
if line[-2] == 'F':
othercaughtlies.add('$')
if line[-2] == 'S':
othercaughtlies.add('*')
othercaughtlies.add('~')
if line[-2] == 'A':
othercaughtlies.add('!')
action = legalActions[0]
if set(obviousActions).intersection(legalActions):
# Always take these actions if possible
for a in set(obviousActions).intersection(legalActions):
action = a
if action in reveal_to_punishment:
myclaims.discard(action)
elif '&' in flags:
preferredActions = []
mysafecards = myclaims.union(mycards)
# Calculate the financial situation
mygain = 0
oppgain = 0
if '*' in mysafecards and not '*' in otherclaims and not '~' in otherclaims:
mygain += 2
oppgain -= 2
elif '$' in mysafecards:
mygain += 3
elif not '$' in otherclaims:
mygain += 1 # This script doesn't use foreign aid
else:
mygain += 1
if '*' in otherclaims and not '*' in mysafecards and not '~' in mysafecards:
oppgain += 2
mygain -= 2
elif '$' in mysafecards:
oppgain += 3
elif not '$' in otherclaims:
oppgain += 2
else:
oppgain += 1
mydist = 7 - int(mycoins)
oppdist = 7 - int(othercoins)
if '^' in mysafecards and len(otherclaims) > (0 if '_' in flags else 1) and not '!' in otherclaims:
mydist -= 4
if '^' in otherclaims and not '!' in mysafecards:
oppdist -= 4
if mydist > 0 and (oppdist <= 0 or mygain <= 0 or (oppgain > 0 and ((oppdist+oppgain-1) // oppgain) < ((mydist+mygain-1) // mygain))):
# Not winning. Do something desperate.
timeToLive = ((oppdist+oppgain-1) // oppgain) if oppdist > 0 else 0
favoriteCards = getFavoriteCards()
if timeToLive < len(otherclaims):
preferredActions.append('q')
if (timeToLive or len(mycards) > 1) and favoriteCards[0] not in mysafecards:
preferredActions.append('E')
elif mycoins >= 3 and random.randint(0,2):
preferredActions.append('A')
else:
preferredActions.append('S')
preferredActions.append('s')
if 'a' in legalActions and ('~' in mycards or '*' in mycards) and not 's' in flags:
# Allow the first steal, as bait
preferredActions.append('p')
flags.add('s')
if '~' in mycards:
flags.discard('E')
if '$' in mysafecards:
preferredActions.append('d')
if '~' in mysafecards:
preferredActions.append('a')
elif '*' in mysafecards:
preferredActions.append('c')
else:
preferredActions.append('c' if random.randint(0,1) else 'a')
if not 'E' in flags:
preferredActions.append('E')
if not ('~' in otherclaims or '*' in otherclaims):
preferredActions.append('S')
if len(otherclaims) > (0 if '_' in flags else 1) and ('^' in mycards or not '_' in flags) and not '!' in otherclaims:
preferredActions.append('A')
preferredActions.append('T')
if line[-1] in actions_dict and punishment_to_reveal[actions_dict[line[-1]]] in othercaughtlies:
preferredActions.append('q')
preferredActions += ['p', '\n']
if len(myclaims) < len(mycards):
# Slip a lie in before admitting all cards in hand
preferredActions = [a for a in preferredActions
if not a in actions_dict
or not punishment_to_reveal[actions_dict[a]] in mysafecards]
else:
preferredActions = [a for a in preferredActions
if not a in actions_dict
or punishment_to_reveal[actions_dict[a]] in mycards
or not punishment_to_reveal[actions_dict[a]] in mycaughtlies]
preferredActions = [a for a in preferredActions if a in legalActions]
if preferredActions:
action = preferredActions[0]
else:
loss = pickCardToLose()
if loss in legalActions:
action = loss
elif loss+"\n" in legalActions:
action = loss+"\n"
else:
preferredActions = []
if not ('~' in otherclaims or '*' in otherclaims):
preferredActions.append('S')
preferredActions += ['T', 'E', 'd', 'a', 'c', 's', 'p', '\n']
if not '!' in otherclaims:
preferredActions.append('A')
preferredActions = [a for a in preferredActions if a in legalActions]
# Filter out lies, provided that doesn't filter out everything
preferredActions = [a for a in preferredActions
if not a in actions_dict
or punishment_to_reveal[actions_dict[a]] in mycards
] or [a for a in preferredActions
if not a in actions_dict
or not punishment_to_reveal[actions_dict[a]] in mycaughtlies
]
if preferredActions:
action = preferredActions[0]
else:
loss = pickCardToLose()
if loss in legalActions:
action = loss
elif loss+"\n" in legalActions:
action = loss+"\n"
if 'a' in legalActions:
if action not in 'acq':
# If vulnerable to stealing, don't admit it!
action = random.choice('acq')
elif not 's' in flags:
# Allow the first steal, as bait
action = 'p'
flags.add('s')
if '~' in mycards:
flags.discard('E')
if action.strip("\n") in lossActions:
myclaims.discard(punishment_to_reveal[action.strip("\n")])
if line[-1] == 'q':
# Also stop claiming what we were challenged for
myclaims.discard(punishment_to_reveal[actions_dict[line[-2]]])
mycaughtlies.add(punishment_to_reveal[actions_dict[line[-2]]])
if action == 'q':
# We challenged it. One way or another, they will not have this card later.
otherclaims.discard(punishment_to_reveal[actions_dict[line[-1]]])
othercaughtlies.add(punishment_to_reveal[actions_dict[line[-1]]])
if action in actions_dict:
myclaims.add(punishment_to_reveal[actions_dict[action]])
flags.add('*')
history.write(action)
if len(mycards) > 2:
flags.add('E')
mycaughtlies = set()
# Losing two cards. Decide which is most valuable.
favoriteCards = getFavoriteCards()
# After an exchange, we can claim what we like. Throw in some lying for more flexibility.
myclaims = set()
possibleCards = [k for k in favoriteCards if k in mycards]
if random.randint(1,len(possibleCards)) > len(mycards) - 2:
myclaims.add(possibleCards[0])
possibleCards = possibleCards[1:]
if len(possibleCards) < len(mycards) - 2:
possibleCards = list(mycards)
random.shuffle(possibleCards)
mycards = ''.join(possibleCards[:(len(mycards)-2)])
print mycards
with open(statefilename, "w") as statefile:
statefile.write(filename+"\n")
statefile.write(''.join(list(myclaims))+"\n")
statefile.write(''.join(list(otherclaims))+"\n")
statefile.write(''.join(list(mycaughtlies))+"\n")
statefile.write(''.join(list(othercaughtlies))+"\n")
statefile.write(''.join(list(flags))+"\n")
```
# Bandit
Tries to get rid of the opponent's Ambassadors and Captains, and win by stealing.
```
import sys
import random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legalActions = sys.argv[5:]
actions_dict = {'E': '_', 'T': '0', 'A': "'", 'S': '<', 'd': '0', 'a': '_', 'c': '<', 's': '='}
punishment_to_reveal = {'_': '~', "'": '^', '<': '*', '=': '!', '0': '$'}
reveal_to_punishment = {punishment_to_reveal[k]: k for k in punishment_to_reveal}
obviousActions = ['C', '~', '^', '*', '!', '$']
lossActions = ['_', "'", '<', '=' '0']
def getFavoriteCards():
return ['*', '!', '~', '$', '^']
def pickCardToLose():
# Losing a card. Decide which is most valuable.
favoriteCards = getFavoriteCards()
cardToLose = ''
for k in favoriteCards:
if k in mycards:
cardToLose = k
for k in mycards:
if not k in favoriteCards:
cardToLose = k
return reveal_to_punishment[cardToLose]
with open(filename, "r+") as history:
line = "\n"
turn = 0
for a in history:
line = a
turn += 1
action = legalActions[0]
if set(obviousActions).intersection(legalActions):
# Always take these actions if possible
for a in set(obviousActions).intersection(legalActions):
action = a
elif 'p' in legalActions and turn == 1 and line == "E":
# Let this pass... once
action = 'p'
elif 'q' in legalActions and line[-1] in 'SEac':
# These get in the way of stealing, get rid of them even if it costs us a card
action = 'q'
elif 'E' in legalActions and '~' in mycards and '*' not in mycards:
action = 'E'
elif 'S' in legalActions:
action = 'S'
elif 's' in legalActions:
if '!' in mycards:
action = 's'
elif len(mycards) == 1:
action = random.choice('sq')
else:
action = pickCardToLose()
elif 'p' in legalActions:
action = 'p'
elif line == 'A' or line == 'C':
# Taking damage
action = pickCardToLose()
elif len(line) == 2 and line[1] == 'q':
# My base action was successfully challenged
action = pickCardToLose()+"\n"
elif len(line) == 3 and line[1] == 'q':
# I failed challenging a base action
action = pickCardToLose()
elif len(line) == 3 and line[2] == 'q':
# My block was successfully challenged
action = pickCardToLose()
elif len(line) == 4 and line[2] == 'q':
# I failed challenging a block
action = pickCardToLose()+"\n"
history.write(action)
if len(mycards) > 2:
# Losing two cards. Decide which is most valuable.
favoriteCards = getFavoriteCards()
possibleCards = [k for k in favoriteCards if k in mycards]
if mycards.count('*') > 1:
# Hooray captains!
possibleCards = ['*'] + possibleCards
if len(possibleCards) < len(mycards) - 2:
possibleCards = list(mycards)
random.shuffle(possibleCards)
mycards = ''.join(possibleCards[:(len(mycards)-2)])
print mycards
```
# Bloody Murder
A counterpart to Bandit, this one goes all-in on a Duke+Assassin strategy.
```
import sys
import random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legalActions = sys.argv[5:]
actions_dict = {'E': '_', 'T': '0', 'A': "'", 'S': '<', 'd': '0', 'a': '_', 'c': '<', 's': '='}
punishment_to_reveal = {'_': '~', "'": '^', '<': '*', '=': '!', '0': '$'}
reveal_to_punishment = {punishment_to_reveal[k]: k for k in punishment_to_reveal}
obviousActions = ['C', '~', '^', '*', '!', '$']
lossActions = ['_', "'", '<', '=' '0']
def getFavoriteCards():
return ['^', '$', '!', '*', '~']
def pickCardToLose():
# Losing a card. Decide which is most valuable.
favoriteCards = getFavoriteCards()
cardToLose = ''
for k in favoriteCards:
if k in mycards:
cardToLose = k
for k in mycards:
if not k in favoriteCards:
cardToLose = k
return reveal_to_punishment[cardToLose]
with open(filename, "r+") as history:
line = "\n"
stealHappened = 0
oppcardcount = 4 - len(mycards)
for a in history:
line = a
if line[0] == 'S':
stealHappened = 1
if [c for c in line if c in lossActions]:
oppcardcount -= 1
action = legalActions[0]
if set(obviousActions).intersection(legalActions):
# Always take these actions if possible
for a in set(obviousActions).intersection(legalActions):
action = a
elif 'q' in legalActions and line[-1] in 's':
# We need this gone
action = 'q'
elif 'E' in legalActions and '~' in mycards:
action = 'E'
elif 'A' in legalActions and (len(mycards) == 1 or mycoins >= 3*oppcardcount+(2 if stealHappened and oppcardcount>1 else 0)):
action = 'A'
elif 'T' in legalActions:
action = 'T'
elif 'd' in legalActions:
action = 'd'
elif 'c' in legalActions and '*' in mycards:
action = 'c'
elif 'a' in legalActions and '~' in mycards:
action = 'a'
elif 's' in legalActions:
if '!' in mycards:
action = 's'
elif len(mycards) == 1:
action = random.choice('sq')
else:
action = pickCardToLose()
elif 'p' in legalActions:
action = 'p'
elif line == 'A' or line == 'C':
# Taking damage
action = pickCardToLose()
elif len(line) == 2 and line[1] == 'q':
# My base action was successfully challenged
action = pickCardToLose()+"\n"
elif len(line) == 3 and line[1] == 'q':
# I failed challenging a base action
action = pickCardToLose()
elif len(line) == 3 and line[2] == 'q':
# My block was successfully challenged
action = pickCardToLose()
elif len(line) == 4 and line[2] == 'q':
# I failed challenging a block
action = pickCardToLose()+"\n"
history.write(action)
if len(mycards) > 2:
# Losing two cards. Decide which is most valuable.
favoriteCards = getFavoriteCards()
possibleCards = [k for k in favoriteCards if k in mycards]
if mycards.count('^') > 1:
# Hooray assassins!
possibleCards = ['^'] + possibleCards
if len(possibleCards) < len(mycards) - 2:
possibleCards = list(mycards)
random.shuffle(possibleCards)
mycards = ''.join(possibleCards[:(len(mycards)-2)])
print mycards
```
[Answer]
# Solver
Solver try to remember what cards are played before and what was the previous moves of the opponent.
this is the 2nd version not finished yet (and it is a big mess now)
to make it work on node 10 add `competitors.append(Player("Solver", ["node", "--experimental-modules", "./solver.mjs"]))`
if node 12 `competitors.append(Player("Solver", ["node", "./solver.js"]))`
be carefull with the file type
```
import fs from 'fs'
import { promisify } from 'util'
const appendFile = promisify(fs.appendFile)
const writeFile = promisify(fs.writeFile)
const readFile = promisify(fs.readFile)
const delay = ms => new Promise(_ => setTimeout(_, ms));
let [filename, othercoins, mycoins, mycards ] = process.argv.slice(2)
othercoins = +othercoins
mycoins = +mycoins
const move = async m => await appendFile(filename, m)
const message = m => process.stdout.write(m)
const endTurn = async _ => await move(`\n`)
const stateFileName = `./state.json`
const defaultState = {
inTheDeck: [],
oponentCards: [],
oponentMissingTempCard: "",
oponentMissingCards: [],
oponentDropedCards: [],
oponentCardModifier: 0
}
const CardTypes = Object.freeze({
Ambassador : `Ambassador`,
Assassin : `Assassin`,
Captain : `Captain`,
Contessa : `Contessa`,
Duke : `Duke`,
})
const revealTable = Object.freeze({
[CardTypes.Ambassador]: `~`,
[CardTypes.Assassin]: `^`,
[CardTypes.Captain]: `*`,
[CardTypes.Contessa]: `!`,
[CardTypes.Duke]: `$`,
})
const giveUpTable = Object.freeze({
[CardTypes.Ambassador]: `_`,
[CardTypes.Assassin]: `'`,
[CardTypes.Captain]: `<`,
[CardTypes.Contessa]: `=`,
[CardTypes.Duke]: `0`,
})
function GetRevealCardChar(cardType) {
return revealTable[cardType]
}
function GetRevealCardType(char) {
return Object.keys(revealTable).find(key => revealTable[key] === char)
}
function GetGiveUpCardChar(cardType) {
return giveUpTable[cardType]
}
function GetGiveUpCardType(char) {
return Object.keys(giveUpTable).find(key => giveUpTable[key] === char)
}
async function GiveUpCard(cardType, endTurn = false) {
return await move(
GetGiveUpCardChar(cardType) + `${endTurn?`\n`:``}`
);
}
function OponentCanHave(cardType) {
// it has it
if (!!~state.oponentCards.indexOf(cardType)) return true
if (state.oponentCards.length + state.oponentDropedCards.length >= 2) return false
return true
}
function GiveCard(getOrder = false) {
// TODO: Tactic
const giveAwayOrder = [
CardTypes.Captain,
CardTypes.Ambassador,
CardTypes.Contessa,
CardTypes.Assassin,
CardTypes.Duke,
]
const tmp = mycards
.split('')
.map(GetRevealCardType)
let [unique, duplicate] = tmp.reduce(([unique, duplicate], item) => {
return unique.includes(item) ?
[unique, [...duplicate, item]] :
[[...unique, item], duplicate]
}
, [[],[]])
unique.sort(
(a, b) => giveAwayOrder.indexOf(a) - giveAwayOrder.indexOf(b));
duplicate.sort(
(a, b) => giveAwayOrder.indexOf(a) - giveAwayOrder.indexOf(b))
const out = [...duplicate, ...unique]
return getOrder? out: GetGiveUpCardChar(out[0]);
}
const iHaveAmbassador = !!~mycards.indexOf(`~`)
const iHaveAssassin = !!~mycards.indexOf(`^`)
const iHaveCaptain = !!~mycards.indexOf(`*`)
const iHaveContessa = !!~mycards.indexOf(`!`)
const iHaveDuke = !!~mycards.indexOf(`$`)
let state = defaultState
;(async ()=>{
const data = (await readFile(filename, `utf8`)).replace(/\r/g, ``)
const isNewGame = data === "" && mycoins === 1 && othercoins === 1
if (isNewGame) {
await writeFile(stateFileName, JSON.stringify(state))
} else {
state = JSON.parse(await readFile(stateFileName, `utf8`))
}
//console.error(state);
let line = data.split(/\n/g).pop()
// I am in the exchnage
if (mycards.length >= 3) {
const [c1, c2] = GiveCard(true).reverse()
if (mycards.length === 3) {
state.inTheDeck.push(c1)
message(GetRevealCardChar(c1))
}
if (mycards.length === 4) {
state.inTheDeck.push(c1, c2)
message(`${GetRevealCardChar(c1)}${GetRevealCardChar(c2)}`)
}
return await move(`\n`)
}
const newTurn = line === ``
if (newTurn) {
if (mycoins >= 7) {
return await move(`C`)
}
if (othercoins >= 6) {
if (iHaveCaptain)
return await move(`S`)
if (mycoins <= 6 && mycards.length <= 1) {
// TODO: bluff
}
}
if (
!iHaveDuke &&
!iHaveContessa &&
iHaveAmbassador
) {
return await move(`E`)
}
// Assasinate if oponent has no Contessa
if (
mycoins >= 3 &&
iHaveAssassin &&
!~state.oponentCards.indexOf(CardTypes.Contessa)
) {
return await move(`A`)
}
if (iHaveDuke) {
return await move(`T`)
}
return await move(`I\n`)
}
// Exchange
if (line === `Eq`) {
if (iHaveAmbassador)
return await move(GetRevealCardChar(CardTypes.Ambassador))
return await GiveUpCard(GiveCard(true)[0])
}
// Tax Challenge
if(line === `Tq`) {
if (iHaveDuke)
return await move(GetRevealCardChar(CardTypes.Duke))
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `Sa`) {
if (!~state.oponentCards.indexOf(CardTypes.Ambassador)) {
state.oponentMissingTempCard = CardTypes.Ambassador
return await move(`q`)
}
return await endTurn()
}
if (line === `Sc`) {
if (!~state.oponentCards.indexOf(CardTypes.Captain)) {
state.oponentMissingTempCard = CardTypes.Captain
return await move(`q`)
}
return await endTurn()
}
if (line=== `Saq${GetRevealCardChar(CardTypes.Ambassador)}`) {
state.oponentMissingTempCard = ``
state.oponentCards.push(
CardTypes.Ambassador
);
return await GiveUpCard(GiveCard(true)[0], true)
}
if (line=== `Scq${GetRevealCardChar(CardTypes.Captain)}`) {
state.oponentMissingTempCard = ``
state.oponentCards.push(
CardTypes.Captain
);
return await GiveUpCard(GiveCard(true)[0], true)
}
if (line === `Sq`) {
if (iHaveCaptain)
return await move(GetRevealCardChar(CardTypes.Captain))
return await GiveUpCard(GiveCard(true)[0])
}
// Assassinate Block and Chalange it
if (line === `As`) {
state.oponentMissingTempCard = CardTypes.Contessa
return await move(`q`)
}
// Assasint blocked by Contessa
if (line === `Asq${GetRevealCardChar(CardTypes.Contessa)}`) {
state.oponentMissingTempCard = ``
state.oponentCards.push(
CardTypes.Contessa
)
// Assassin useless here lets give it up
return await GiveUpCard(CardTypes.Assassin, true)
}
// Assassinate challenge
if (line === `Aq`) {
if (iHaveAssassin)
return await move(GetRevealCardChar(CardTypes.Assassin))
return await GiveUpCard(GiveCard(true)[0])
}
// Defense Moves
if (line === `C`) {
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `A`) {
if (iHaveContessa)
return await move(`s`)
if (!!~state.oponentCards.indexOf(CardTypes.Assassin)) {
// If oponent has an Assasin card lets bluff
return await move(`s`)
} else {
state.oponentMissingTempCard = CardTypes.Assassin
return await move(`q`)
}
}
if (line === `Aq${GetRevealCardChar(CardTypes.Assassin)}`) {
state.oponentMissingTempCard = ``
state.oponentCards.push(
CardTypes.Assassin
);
return await GiveUpCard(GiveCard(true)[0], true)
}
if (line === `Asq`) {
if (iHaveContessa)
return await move(GetRevealCardChar(CardTypes.Contessa))
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `S`) {
if (iHaveAmbassador)
return await move(`a`)
if (iHaveCaptain)
return await move(`c`)
return await move(`p`)
}
if (line === `Saq`) {
if (iHaveAmbassador)
return await move(GetRevealCardChar(CardTypes.Ambassador))
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `Scq`) {
if (iHaveCaptain)
return await move(GetRevealCardChar(CardTypes.Captain))
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `F`) {
if (iHaveDuke)
return await move(`d`)
return await move(`p`)
}
if (line === `Fdq`) {
if (iHaveDuke)
return await move(GetRevealCardChar(CardTypes.Duke))
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `E`) {
if (!OponentCanHave(CardTypes.Ambassador)) {
return await move(`q`)
}
state.oponentCards = []
state.oponentMissingCards = []
state.oponentMissingTempCard = ''
return await move(`p`)
}
if (line === `Eq${GetRevealCardChar(CardTypes.Ambassador)}`) {
console.error(111, `THIS SHOULD NEVER HAPPEN`)
return await GiveUpCard(GiveCard(true)[0])
}
if (line === `T`) {
if (!OponentCanHave(CardTypes.Duke)) {
return await move(`q`)
}
return await move(`p`)
}
if (line === `Tq${GetRevealCardChar(CardTypes.Duke)}`) {
console.error(111, `THIS SHOULD NEVER HAPPEN`)
return await GiveUpCard(GiveCard(true)[0])
}
// remove oponents drop card from the state
// can't detect if oponent has the same card twice
if (!!~Object.values(giveUpTable).indexOf(line.substr(-1))) {
// Catch the bluff
if (state.oponentMissingTempCard !== "") {
state.oponentMissingCards.push(state.oponentMissingTempCard)
state.oponentMissingTempCard = ""
}
// maybe we should asume user doeas not has the same card?
const cardType = GetGiveUpCardType(line.substr(-1))
state.oponentCards.filter(c => c !== cardType)
state.inTheDeck.push(cardType)
state.oponentDropedCards.push(cardType)
}
return await endTurn()
})()
.then(async () => {
await writeFile(stateFileName, JSON.stringify(state))
})
.catch(console.error.bind(console))
```
```
[Answer]
# Lawyer
The Lawyer makes his way cautiously through the world, never lying, blocking when possible, challenging when not to his immediate detriment. He does not attack except when required by couping, but will take coins as often as possible in order to coup quickly. He is smart enough to sacrifice cards he does not use first, but not smart enough to use them to get rid of them and get new ones.
```
import sys
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
def give_card():
if "^" in mycards:
return "'"
if "~" in mycards:
return "_"
if "!" in mycards:
return "="
if "*" in mycards:
return "<"
return "0"
with open(filename, "r+") as history:
line = "\n"
for a in history:
print("line:", a)
line = a
if line.endswith("\n"):
if int(mycoins) >= 10:
history.write("C")
elif "$" in mycards:
history.write("T")
elif "*" in mycards and int(othercoins) > 0:
history.write("S")
else:
history.write("F")
elif line == "F":
if "$" in mycards:
history.write("d")
else:
history.write("p")
elif line == "C":
history.write(give_card())
elif line == "E":
if len(mycards) > 1:
history.write("q")
else:
history.write("p")
elif line == "T":
if len(mycards) > 1:
history.write("q")
else:
history.write("p")
elif line == "A":
if "!" in mycards:
history.write("s")
else:
history.write(give_card())
elif line == "S":
if "~" in mycards:
history.write("a")
elif "*" in mycards:
history.write("c")
elif len(mycards) > 1:
history.write("q")
else:
history.write("p")
elif line.endswith("d") and len(mycards) > 1:
history.write("q")
elif line.endswith("a") and len(mycards) > 1:
history.write("q")
elif line.endswith("c") and len(mycards) > 1:
history.write("q")
elif line.endswith("s") and len(mycards) > 1:
history.write("q")
elif line.endswith("sq"):
history.write("!")
elif line.endswith("aq"):
history.write("~")
elif line.endswith("cq"):
history.write("*")
elif line.endswith("dq"):
history.write("$")
elif line.endswith("Tq"):
history.write("$")
elif line.endswith("Sq"):
history.write("*")
elif line[-1] in "~^*!$":
history.write(give_card())
if line[-3] in "acds":
history.write("\n")
else:
history.write("\n")
```
There are probably bugs in this program. When you find them, please let me know.
[Answer]
# Mask
The Mask is a master of disguise. He prevents opponents from keeping track of his cards by Exchanging every time he acts or blocks. His winning strategy is to take 3 coins as the Duke, then Assassinate.
Compile with `go build mask.go`, run with `./mask`.
```
package main
import (
"bytes"
"io/ioutil"
"os"
"strconv"
"strings"
)
var revealToPunishment = map[byte]byte{'~': '_', '^': '\'', '*': '<', '!': '=', '$': '0'}
var assertedCardMap = map[byte]byte{'A': '^', 'E': '~', 'S': '*', 'T': '$', 'a': '~', 'c': '*', 's': '!', 'd': '$'}
func actWithOneCard(file *os.File, coinCount int, ourCards string) {
if coinCount >= 7 {
file.WriteString("C")
} else if ourCards == "$" {
file.WriteString("T")
} else {
file.WriteString("I\n")
}
}
func mostRecentClaim(lines [][]byte) byte {
// If we blocked and were not challenged on the opponent's last turn, return
// what we claimed to have in the block.
opponentsLastTurn := lines[len(lines)-1]
switch b := opponentsLastTurn[len(opponentsLastTurn)-1]; b {
case 'a', 'c', 's', 'd':
return b
}
// Otherwise, return the first character of our last turn.
ourLastTurn := lines[len(lines)-2]
return ourLastTurn[0]
}
func whatWePlanToDoNext(lines [][]byte, coinCount int) string {
if len(lines) < 2 || mostRecentClaim(lines) == 'E' {
if coinCount >= 3 {
return "A"
} else {
return "T"
}
} else {
return "E"
}
}
func ourTurn(file *os.File, coinCount int, ourCards string, lines [][]byte) {
if len(ourCards) == 1 {
actWithOneCard(file, coinCount, ourCards)
return
}
file.WriteString(whatWePlanToDoNext(lines, coinCount))
}
func handleChallenge(file *os.File, ourCards string, lines [][]byte) {
lastLine := lines[len(lines)-1]
attemptedAction := lastLine[len(lastLine)-2]
assertedCard := assertedCardMap[attemptedAction]
for i := range ourCards {
if ourCards[i] == assertedCard && ourCards[i] != '\x00' {
file.Write([]byte{assertedCard})
return
}
}
cardToGiveUp := giveUpCard(ourCards)
file.Write([]byte{revealToPunishment[cardToGiveUp]})
switch attemptedAction {
case 'a', 'c', 'd', 's':
default:
file.WriteString("\n")
}
}
func giveUpCard(ourCards string) byte {
// If we have a Duke, give up the other card.
if dukeIndex := strings.Index(ourCards, "$"); -1 < dukeIndex && len(ourCards) == 2 {
return ourCards[(dukeIndex+1)%2]
}
return ourCards[0]
}
func main() {
filename := os.Args[1]
coinCount, _ := strconv.Atoi(os.Args[3])
ourCards := os.Args[4]
file, _ := os.OpenFile(filename, os.O_RDWR, 0755)
defer file.Close()
rawBytes, _ := ioutil.ReadAll(file)
lines := bytes.Split(rawBytes, []byte{'\n'})
if len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
if len(rawBytes) == 0 {
file.WriteString("T")
return
}
// Exchange. Prioritize Ambassador, Duke, Assassin.
if len(ourCards) > 2 {
var has_ambassador, has_duke, has_assassin bool
var keptCards string
for len(ourCards) > 2 {
var i int
if i = strings.Index(ourCards, "~"); !has_ambassador && i > -1 {
keptCards += "~"
has_ambassador = true
ourCards = ourCards[:i] + ourCards[i+1:]
} else if i = strings.Index(ourCards, "$"); !has_duke && i > -1 {
keptCards += "$"
has_duke = true
ourCards = ourCards[:i] + ourCards[i+1:]
} else if i = strings.Index(ourCards, "^"); !has_assassin && i > -1 {
keptCards += "^"
has_assassin = true
ourCards = ourCards[:i] + ourCards[i+1:]
} else {
keptCards += ourCards[:1]
ourCards = ourCards[1:]
}
}
ourCards = keptCards
os.Stdout.WriteString(ourCards)
}
switch rawBytes[len(rawBytes)-1] {
case '\n':
ourTurn(file, coinCount, ourCards, lines)
// Opponent Couped us. Give up a card.
case 'C':
file.Write([]byte{revealToPunishment[giveUpCard(ourCards)]})
// Opponent blocked, or we Assassinated/Couped them. End our turn.
case 'a', 'c', 'd', 's', 'p', '_', '\'', '<', '=', '0':
file.WriteString("\n")
case 'q':
handleChallenge(file, ourCards, lines)
// Opponent did something blockable, block it.
case 'F':
file.WriteString("d")
case 'A':
file.WriteString("s")
case 'S':
if strings.Contains(ourCards, "*") {
file.WriteString("c")
} else {
file.WriteString("a")
}
// Opponent took some other action. Let it pass.
default:
file.WriteString("p")
}
}
```
[Answer]
# Random
Random doesn't know what to do, so he randomly selects something legal.
```
package main
import (
"fmt"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
filename := os.Args[1]
ourCards := os.Args[4]
legalActions := os.Args[5:]
file, _ := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, 0755)
defer file.Close()
file.WriteString(legalActions[rand.Intn(len(legalActions))])
switch len(ourCards) {
case 3:
os.Stdout.Write([]byte{ourCards[rand.Intn(3)]})
case 4:
i1 := 0
i2 := 0
for ok := true; ok; ok = i1 == i2 {
i1 = rand.Intn(4)
i2 = rand.Intn(4)
}
keptCards := []byte{ourCards[i1], ourCards[i2]}
os.Stdout.Write(keptCards)
}
}
```
# Challenger
Challenger trusts no one in this game of deception. If you do something challengeable, he will challenge you. Otherwise he just takes income every turn and tries to Coup you if he has the coins.
```
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strconv"
)
var revealToPunishment = map[byte]byte{'~': '_', '^': '\'', '*': '<', '!': '=', '$': '0'}
func main() {
filename := os.Args[1]
coinCount := os.Args[3]
ourCards := os.Args[4]
file, _ := os.OpenFile(filename, os.O_RDWR, 0755)
defer file.Close()
rawBytes, _ := ioutil.ReadAll(file)
if len(rawBytes) == 0 {
file.Write([]byte("I\n"))
return
}
lines := bytes.Split(rawBytes, []byte{'\n'})
switch rawBytes[len(rawBytes)-1] {
case '\n':
// Our turn, do we have enough coins for a Coup?
if c, _ := strconv.Atoi(coinCount); c >= 7 {
file.Write([]byte{'C'})
// We don't, so take income.
} else {
file.Write([]byte("I\n"))
}
// Opponent did something challengeable. We don't believe them for a second.
// Challenge it.
case 'E', 'T', 'A', 'S', 'a', 'c', 'd', 's':
file.Write([]byte{'q'})
// Opponent Couped us or our challenge failed. Give up a card.
case 'C':
file.Write([]byte{revealToPunishment[ourCards[0]]})
case '~', '*', '^', '!', '$':
file.Write([]byte{revealToPunishment[ourCards[0]]})
lastLine := lines[len(lines)-1]
switch lastLine[len(lastLine)-3] {
case 'a', 'c', 'd', 's':
file.WriteString("\n")
}
// Our challenge succeeded or we Couped the opponent! End our turn.
case '_', '\'', '<', '=', '0':
file.Write([]byte{'\n'})
default:
// Opponent took some other action. Let it pass.
file.Write([]byte{'p'})
}
}
```
Compile these programs with `go build random.go/challenger.go` and run with `./random` or `./challenger`.
[Answer]
# Taxman
The Taxman is here to collect tax. Uses assassin if they have one. Only blocks if they have the card to block. Randomly challenges.
Written in c#, I spent far too long building a class hierarchy for all the different actions that can be taken.
**Edit:** Now with improved logic like not claiming to have a duke when they've given up a duke after being challenged. Also no longer tries to continually assasinate if the opponent blocks with contessa (and isn't challenged).
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
internal static class Program
{
public static void Main(string[] args)
{
#if DEBUG
// Can't figure out how to pass newline as a command line arg.
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "I\\n")
args[i] = "I\n";
}
#endif
if (!ProcessArgs(args, out string filename, out int opCoin, out int myCoin, out IEnumerable<Card> cards, out IEnumerable<Output> validOutputs))
{
Console.WriteLine("Error with args.");
return;
}
var taxman = new Taxman(filename, opCoin, myCoin, cards, validOutputs);
taxman.DukeEm();
}
private static bool ProcessArgs(string[] args, out string filename, out int opCoin, out int myCoin, out IEnumerable<Card> cards, out IEnumerable<Output> validOutputs)
{
if (args.Length < 4)
{
throw new InvalidOperationException("Error: Not enough args.");
}
bool success = true;
filename = args[0];
success &= int.TryParse(args[1], out opCoin) && opCoin >= 0 && opCoin <= 12;
success &= int.TryParse(args[2], out myCoin) && myCoin >= 0 && myCoin <= 12;
cards = Card.ParseSymbols(args[3]);
IEnumerable<char> validOutputArgs = args.Skip(4).Select(outputArg => outputArg.First());
// Income and Surrenders on our turn include \n, we use chars below so don't include the newline, hence the call to .First().
// Code below should be smart enough to also write a newline if necessary.
validOutputs = Output.ParseSymbols(validOutputArgs);
return success;
}
}
internal sealed class Taxman
{
private const string _OustedAsDukeFileName = "MyTotallyCoolStateFile.txt";
private const string _OppClaimsContessaFileName = "OppClaimsContess.txt";
private readonly Random _Rand = new Random();
private readonly List<Card> _GiveUpPreferences = new List<Card> { Card.Duke, Card.Assassin, Card.Ambassador, Card.Contessa, Card.Captain };
private double BaseProbabilityToChallenge => 0.1d;
private bool _Written = false;
private bool _MyTurn;
private bool? _OustedAsDuke = null;
private bool? _OppClaimsContessa = null;
private string FileName { get; }
private int OppCoin { get; }
private int MyCoin { get; }
private IEnumerable<Card> Cards { get; }
private IEnumerable<Output> ValidOutputs { get; }
private IEnumerable<Output> GameSoFar { get; }
private int OppCardCount { get; }
private int MyCardCount => Cards.Count();
private int OppScore => (10 * OppCardCount) + OppCoin;
private int MyScore => (10 * MyCardCount) + MyCoin;
private bool OustedAsDuke
{
get
{
if (_OustedAsDuke.HasValue)
{
return _OustedAsDuke.Value;
}
else
{
if (string.IsNullOrWhiteSpace(File.ReadAllText(_OustedAsDukeFileName)))
{
_OustedAsDuke = false;
return false;
}
else
{
_OustedAsDuke = true;
return true;
}
}
}
set
{
File.WriteAllText(_OustedAsDukeFileName, value ? "Ousted" : string.Empty);
_OustedAsDuke = value;
}
}
private bool OppClaimsContessa
{
get
{
if (_OppClaimsContessa.HasValue)
{
return _OppClaimsContessa.Value;
}
else
{
if (string.IsNullOrWhiteSpace(File.ReadAllText(_OppClaimsContessaFileName)))
{
_OppClaimsContessa = false;
return false;
}
else
{
_OppClaimsContessa = true;
return true;
}
}
}
set
{
File.WriteAllText(_OppClaimsContessaFileName, value ? "Claimed" : string.Empty);
_OppClaimsContessa = value;
}
}
public Taxman(string fileName, int oppCoin, int myCoin, IEnumerable<Card> cards, IEnumerable<Output> validOutputs)
{
FileName = fileName; OppCoin = oppCoin; MyCoin = myCoin; Cards = cards; ValidOutputs = validOutputs;
GameSoFar = ReadFile();
//calculate how many cards the opponent has.
int giveUps = GameSoFar.Count(output => output is GiveUp);
int myGiveUps = 2 - MyCardCount;
var oppGiveUps = giveUps - myGiveUps;
OppCardCount = 2 - oppGiveUps;
}
public void DukeEm()
{
if (Cards.Skip(2).Any())
{
Exchange();
Write(Output.EndTurn);
return;
}
var prev = GameSoFar.LastOrDefault() ?? Output.EndTurn;
if (prev == Output.EndTurn) // Income is I\n so shows up as an EndTurn
{
ChooseAction();
}
else if (prev == Action.ForeignAid)
{
if (!OustedAsDuke)
Write(Block.Duke);
else
Write(Output.Pass);
}
else if (prev == Action.Coup)
{
GiveUpDecide();
}
else if (prev == ChallengeableAction.Exchange || prev == ChallengeableAction.Tax)
{
if (ShouldChallenge((ChallengeableAction)prev))
Write(Output.Challenge);
else
Write(Output.Pass);
}
else if (prev == ChallengeableAction.Assassinate)
{
RespondToAssassinate();
}
else if (prev == ChallengeableAction.Steal)
{
RespondToSteal();
}
else if (prev == Block.Duke || prev == Block.Ambassador || prev == Block.Captain || prev == Block.Contessa)
{
Debug.Assert(prev == Block.Contessa, "We should never take an action that a different card would block.");
if (ShouldChallenge((Block)prev))
Write(Output.Challenge);
else
{
Write(Output.EndTurn);
OppClaimsContessa = true;
}
}
else if (prev == Output.Pass)
{
Write(Output.EndTurn);
}
else if (prev == Output.Challenge)
{
var challengedOutput = (IChallengeable)GameSoFar.TakeLast(2).First();
RespondToChallenge(challengedOutput);
}
else if (prev is Card)
{
GiveUpDecide();
}
else if (prev is GiveUp)
{
if (prev == GiveUp.Contessa)
OppClaimsContessa = false;
Write(Output.EndTurn);
}
else
{
Debug.Fail("Should have hit one of the conditions above.");
WriteRandomValid();
}
}
private void Exchange()
{
int handSize = MyCardCount - 2;
var cardsToKeep = new List<Card>();
var workingCards = Cards.ToList();
while (cardsToKeep.Count < handSize)
{
if (!cardsToKeep.Contains(Card.Duke) && workingCards.Remove(Card.Duke))
cardsToKeep.Add(Card.Duke);
else if (!cardsToKeep.Contains(Card.Assassin) && !OppClaimsContessa && workingCards.Remove(Card.Assassin))
cardsToKeep.Add(Card.Assassin);
else if (!cardsToKeep.Contains(Card.Ambassador) && workingCards.Remove(Card.Ambassador))
cardsToKeep.Add(Card.Ambassador);
else if (!cardsToKeep.Contains(Card.Contessa) && workingCards.Remove(Card.Contessa))
cardsToKeep.Add(Card.Contessa);
else if (!cardsToKeep.Contains(Card.Captain) && workingCards.Remove(Card.Captain))
cardsToKeep.Add(Card.Captain);
else
{
cardsToKeep.Add(workingCards[0]);
workingCards.RemoveAt(0);
}
}
var keptCards = new string(cardsToKeep.Select(card => card.Symbol).ToArray());
Console.WriteLine(keptCards);
}
private IEnumerable<Output> ReadFile()
{
var text = File.ReadAllText(FileName);
// Check if we're at the start of the game, 1 character means our opponent went first.
if (text == null || text.Length <= 1)
{
// Do any start up like creating a state file.
Debug.Assert(MyCardCount == 2 && MyCoin == 1 && OppCoin == 1, "Should always start with 2 cards in hand and have 1 coin each.");
using (File.Create(_OustedAsDukeFileName))
using (File.Create(_OppClaimsContessaFileName))
{ ; }
}
var lastLine = text.Split('\n').LastOrDefault();
_MyTurn = lastLine == null || lastLine.Length % 2 == 0;
return Output.ParseSymbols(text);
}
private void ChooseAction()
{
if (MyCoin >= 3 && Cards.Contains(Card.Assassin))
{
// If we have the coins to assasinate and have the card to assasinate then go for it.
Write(ChallengeableAction.Assassinate);
}
else if (MyCoin >= 7)
{
// If we have the coins to coup then go for it.
Write(Action.Coup);
}
else if (Cards.Contains(Card.Ambassador) && !Cards.Contains(Card.Duke))
{
// If we don't /actually/ have a duke but we do have ambassador and can exchange into one, then try do that.
Write(ChallengeableAction.Exchange);
// TODO if we've exchanged multiple times already perhaps we should try something different?
}
else if (!OustedAsDuke)
{
// Take tax because We totally always have a duke.
// Except if we've been previously challenged and shown to not have a duke, in which case exchange to get a new Duke.
Write(ChallengeableAction.Tax);
}
else
{
Write(ChallengeableAction.Exchange);
// Even if we don't find a duke from the exchange we can pretend that we did.
OustedAsDuke = false;
}
}
private void RespondToAssassinate()
{
if (Cards.Contains(Card.Contessa))
Write(Block.Contessa);
else if (MyCardCount <= 1)
{
// We will lose if we don't challenge or block.
if (ShouldRandomChallenge(0.5d))
Write(Output.Challenge);
else
Write(Block.Contessa);
}
else if (ShouldChallenge(ChallengeableAction.Assassinate))
Write(Output.Challenge);
else
GiveUpDecide();
}
private void RespondToSteal()
{
// prefer to block with ambassador before captain.
if (Cards.Contains(Card.Ambassador))
Write(Block.Ambassador);
else if (Cards.Contains(Card.Captain))
Write(Block.Captain);
else if (ShouldChallenge(ChallengeableAction.Steal))
Write(Output.Challenge);
else
Write(Output.Pass);
// TODO if opp is continually stealing we need to figure out who wins the race if we keep taking Tax.
}
private void RespondToChallenge(IChallengeable challengedAction)
{
if (Cards.Contains(challengedAction.RequiredCard))
Write(challengedAction.RequiredCard);
else
GiveUpDecide();
if (challengedAction == ChallengeableAction.Tax)
OustedAsDuke = true;
}
private void GiveUpDecide()
{
Write(Cards.OrderBy(card => _GiveUpPreferences.IndexOf(card)).Last().GiveUp);
if (_MyTurn)
Write(Output.EndTurn);
}
private bool ShouldChallenge(IChallengeable prev)
{
// Never challenge if we're far enough ahead, always challenge if far enough behind
if (MyScore > (OppScore + 7))
{
return false;
}
else if (MyScore < (OppScore - 10))
{
return true;
}
else
{
if (prev == ChallengeableAction.Assassinate)
return ShouldRandomChallenge(BaseProbabilityToChallenge * 0.5d);
else if (prev is Block)
return ShouldRandomChallenge(BaseProbabilityToChallenge * 2d);
else if (prev == ChallengeableAction.Tax && OppCoin >= 4 && MyCardCount <= 1 && (MyCoin < 7 || OppCardCount > 1))
return true;
else
return ShouldRandomChallenge(BaseProbabilityToChallenge);
}
}
private bool ShouldRandomChallenge(double prob)
{
return _Rand.NextDouble() < prob;
}
private void WriteRandomValid()
{
int index = _Rand.Next(0, ValidOutputs.Count());
var randomOutput = ValidOutputs.ElementAt(index);
Write(randomOutput);
}
private void Write(Output output)
{
Debug.Assert(!_Written || (_MyTurn && output == Output.EndTurn), "If we've already written a value we shouldn't be trying to write another.");
Debug.Assert(ValidOutputs.Contains(output), "Should only be writing valid outputs to file.");
File.AppendAllText(FileName, output.Symbol.ToString());
_Written = true;
}
}
[DebuggerDisplay("{Symbol}")]
internal class Output
{
public static readonly Output Pass = new Output() { Symbol = 'p' };
public static readonly Output Challenge = new Output() { Symbol = 'q' };
public static readonly Output EndTurn = new Output() { Symbol = '\n' };
private static readonly Output[] _BaseOutputs = new Output[3] { Pass, Challenge, EndTurn };
protected Output() { }
public static IEnumerable<Output> AllOutputs => ChallengeableAction.Actions.Concat(Block.Blocks.Concat(Card.Cards.Concat(GiveUp.GiveUps.Concat(_BaseOutputs))));
public static IList<Output> ParseSymbols(IEnumerable<char> symbols)
{
var parsedOutputs = new List<Output>();
foreach (var symbol in symbols)
{
if (symbol == '\r') continue; // newlines can show up as \r\n so need to skip the \r.
var matchingOutput = AllOutputs.FirstOrDefault(output => output.Symbol == symbol);
if (matchingOutput == null)
{
throw new InvalidOperationException($"Could not parse Output symbol: \"{symbol}\"");
}
parsedOutputs.Add(matchingOutput);
}
return parsedOutputs;
}
public char Symbol { get; protected set; }
}
internal sealed class Card : Output
{
public static readonly Card Ambassador = new Card() { Symbol = '~', GiveUp = GiveUp.Ambassador, AvailableAction = ChallengeableAction.Exchange, AvalableBlock = Block.Ambassador };
public static readonly Card Assassin = new Card() { Symbol = '^', GiveUp = GiveUp.Assassin, AvailableAction = ChallengeableAction.Assassinate };
public static readonly Card Captain = new Card() { Symbol = '*', GiveUp = GiveUp.Captain, AvailableAction = ChallengeableAction.Steal, AvalableBlock = Block.Captain };
public static readonly Card Contessa = new Card() { Symbol = '!', GiveUp = GiveUp.Contessa, AvalableBlock = Block.Contessa };
public static readonly Card Duke = new Card() { Symbol = '$', GiveUp = GiveUp.Duke, AvailableAction = ChallengeableAction.Tax, AvalableBlock = Block.Duke };
private static readonly Card[] _Cards = new Card[5] { Ambassador, Assassin, Captain, Contessa, Duke };
private Card() { }
public static IEnumerable<Card> Cards => _Cards;
public GiveUp GiveUp { get; private set; }
public ChallengeableAction AvailableAction { get; private set; }//=> ChallengeableAction.ChallengeableActions.SingleOrDefault(action => action.RequiredCard == this);
public Block AvalableBlock { get; private set; }// => Block.Blocks.SingleOrDefault(block => block.RequiredCard == this);
new public static IEnumerable<Card> ParseSymbols(IEnumerable<char> cardSymbols)
{
var parsedCards = new List<Card>();
foreach (var symbol in cardSymbols)
{
var matchingCard = Cards.FirstOrDefault(card => card.Symbol == symbol);
if (matchingCard == null) throw new InvalidOperationException($"Could not parse card symbol: {symbol}");
parsedCards.Add(matchingCard);
}
return parsedCards;
}
}
internal class Action : Output
{
public static readonly Action Income = new Action() { Symbol = 'I' };
public static readonly Action ForeignAid = new Action() { Symbol = 'F', BlockedBy = new Block[1] { Block.Duke } };
public static readonly Action Coup = new Action() { Symbol = 'C' };
protected Action() : base() { }
public IEnumerable<Block> BlockedBy { get; protected set; } = new Block[0];
}
internal sealed class ChallengeableAction : Action, IChallengeable
{
public static readonly ChallengeableAction Tax = new ChallengeableAction() { Symbol = 'T' };
public static readonly ChallengeableAction Assassinate = new ChallengeableAction() { Symbol = 'A', BlockedBy = new Block[1] { Block.Contessa } };
public static readonly ChallengeableAction Exchange = new ChallengeableAction() { Symbol = 'E' };
public static readonly ChallengeableAction Steal = new ChallengeableAction { Symbol = 'S', BlockedBy = new Block[2] { Block.Ambassador, Block.Captain } };
private static readonly Action[] _Actions = new Action[7] { Income, ForeignAid, Coup, Tax, Assassinate, Exchange, Steal };
private static readonly ChallengeableAction[] _ChallengeableActions = new ChallengeableAction[4] { Tax, Assassinate, Exchange, Steal };
private ChallengeableAction() : base() { }
public static IEnumerable<Action> Actions => _Actions;
public static IEnumerable<ChallengeableAction> ChallengeableActions => _ChallengeableActions;
public Card RequiredCard => Card.Cards.Single(card => card.AvailableAction == this);
}
internal sealed class Block : Output, IChallengeable
{
public static readonly Block Duke = new Block() { Symbol = 'd' };
public static readonly Block Ambassador = new Block() { Symbol = 'a' };
public static readonly Block Captain = new Block() { Symbol = 'c' };
public static readonly Block Contessa = new Block() { Symbol = 's' };
private static readonly Block[] _Blocks = new Block[4] { Ambassador, Captain, Contessa, Duke };
private Block() : base() { }
public static IEnumerable<Block> Blocks => _Blocks;
public Card RequiredCard => Card.Cards.Single(card => card.AvalableBlock == this);
public Action ActionBlocked => ChallengeableAction.Actions.Single(action => action.BlockedBy.Contains(this));
}
internal sealed class GiveUp : Output
{
public static readonly GiveUp Ambassador = new GiveUp() { Symbol = '_' };
public static readonly GiveUp Assassin = new GiveUp() { Symbol = '\'' };
public static readonly GiveUp Captain = new GiveUp() { Symbol = '<' };
public static readonly GiveUp Contessa = new GiveUp() { Symbol = '=' };
public static readonly GiveUp Duke = new GiveUp() { Symbol = '0' };
private static readonly GiveUp[] _GiveUps = new GiveUp[5] { Ambassador, Assassin, Captain, Contessa, Duke };
private GiveUp() : base() { }
public static IEnumerable<GiveUp> GiveUps => _GiveUps;
public Card Card => Card.Cards.Single(card => card.GiveUp == this);
}
internal interface IChallengeable { Card RequiredCard { get; } }
```
[Answer]
# Rando Aggro Lawyer
Similar to the lawyer, it only does legal things. However it Assassinates, coups earlier, and it chooses some actions randomly (like when to Challenge).
```
#! /usr/bin/env python3
import sys
import random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
def give_card():
if "~" in mycards: # give up Ambassador
return "_"
if "!" in mycards: # give up Contessa
return "="
if "^" in mycards: # give up Assassin
return "'"
if "*" in mycards: # give up Captain
return "<"
return "0" # give up Duke
with open(filename, "r+") as history:
line = "\n"
for a in history:
line = a # get the last line of the file
print("{}, {}, {}, {}".format(line, othercoins, mycoins, mycards))
if line.endswith("\n"): # it has an endline, eg this is a new action
if int(mycoins) >= 7:
history.write("C") # coup if I have to
elif int(mycoins) >= 3 and "^" in mycards:
history.write("A") # assassinate if I can
elif "*" in mycards and int(othercoins) > 0:
history.write("S") # steal if i can
elif "$" in mycards:
history.write("T") # tax if i can
elif random.randint(0,1):
history.write("F") # foreign aid 50% of the time
else:
history.write("I\n") # income
elif line == "F": # they tried to foreign aid
if "$" in mycards:
history.write("d") # block if i can
else:
history.write("p")
elif line == "C": # they coup, sad
history.write(give_card())
elif line == "E": # they Exchange
if random.randint(0,1):
history.write("q") # challenge 50% of the time
else:
history.write("p")
elif line == "T": # they tax
if random.randint(0,1):
history.write("q") # challenge 50% of the time
else:
history.write("p")
elif line == "A": # they assassinate
if "!" in mycards:
history.write("s") # block with contessa if i can
elif random.randint(0,1):
history.write("q") # challenge 50% of the time
else:
history.write(give_card()) # otherwise give up a card
elif line == "S": # they steal
if "~" in mycards:
history.write("a") # block with ambassador if i can
elif "*" in mycards:
history.write("c") # block with captain if i can
elif random.randint(0,1):
history.write("q") # challenge 50% of the time
else:
history.write("p")
elif line.endswith("d") and random.randint(0,1): # they block my foreign aid
history.write("q") # challenge 50% of the time
elif line.endswith("a") and random.randint(0,1): # they block as ambassador
history.write("q") # challenge 50% of the time
elif line.endswith("c") and random.randint(0,1): # they block as captain
history.write("q") # challenge 50% of the time
elif line.endswith("s") and random.randint(0,1): # they block as contessa
history.write("q") # challenge 50% of the time
elif line.endswith("sq"): # they challenged my contessa block
history.write("!") # reveal that i have contessa (no condition because i never lie block)
elif line.endswith("aq"): # they challenge my Ambassador block
history.write("~") # reveal that i have a captain (no condition because i never lie block)
elif line.endswith("cq"): # they challenged my Captain block
history.write("*") # reveal that I have a Captain (no condition because i never lie block)
elif line.endswith("dq"): # they challenge my Duke block
history.write("$") # reveal that I have a Duke (no condition because i never lie block)
elif line.endswith("Tq"): # they challenge my Tax
history.write("$") # reveal that I have a Duke (no condition because i fake tax)
elif line.endswith("Aq"): # they challenge my assassinate
history.write("^") # reveal that I had an Assasin
elif line.endswith("Sq"): # they challenge my steal
history.write("*") # reveal that I have a Captain
elif line[-1] in "~^*!$": # they respond to my challenge successfully
history.write(give_card()) # give up card
if line[-3] in "acds":
history.write("\n")
else:
history.write("\n")
history.seek(0)
print("out")
print(history.read())
```
[Answer]
# Gambler
The gambler has a fleshed out strategy but trusts his gut when a situation isn't accounted for in his winning strategy. He tries to steal a lot and coups/assassinates whenever possible.
Written in Python3:
```
import sys
import random
import time
random.seed(time.time()) # lets keep it rather random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legal_actions = sys.argv[5:]
othercoins = int(othercoins)
mycoins = int(mycoins)
income = 'I\n'
foreign_aid, coup, exchange, tax, assassinate, steal, block_aid, \
block_steal_amb, block_steal_cap, block_assassinate, \
pass_challange, do_challenge = "FCETASdacspq"
loosing_actions = "_'<=0"
loose_ambassador, loose_assassin, loose_captain, loose_contessa, loose_duke = loosing_actions
have_ambassador, have_assassin, have_captain, \
have_contessa, have_duke = "~^*!$"
actions_dict = {
exchange: loose_ambassador, tax: loose_duke, assassinate: loose_assassin, steal: loose_captain,
block_aid: loose_duke, block_steal_amb: loose_ambassador, block_steal_cap: loose_captain, block_assassinate: loose_contessa
}
def guess_opponents_hand():
# get number of each card still in play and not in hand
card_counts = [3] * 5
card_give_up = list("_'<=0")
with open(filename, 'r') as history:
while True:
line = history.readline()
if not line:
break
for card in card_give_up:
if card in line:
card_counts[card_give_up.index(card)] -= 1
have_cards = list("~^*!$")
if sum(card_counts) == 15:
num_cards = 2
elif sum(card_counts) == 14:
if len(mycards) == 1:
num_cards = 2
else:
num_cards = 1
else:
num_cards = 1
for card in mycards:
card_counts[have_cards.index(card)] -= 1
# randomly sample a hand for the opponent
card_1 = sample_from_probabilities([i / sum(card_counts) for i in card_counts], card_give_up)
if num_cards == 1:
return card_1
card_counts[card_give_up.index(card_1)] -= 1
return card_1 + sample_from_probabilities([i / sum(card_counts) for i in card_counts], card_give_up)
def sample_from_probabilities(success_probabilities, actions):
# weighted random
return random.choices(actions, success_probabilities)[0]
def get_prev_char(line, x=1):
try:
return line[-1*x]
except:
return ""
def get_prev_line(lines):
try:
return lines[-2]
except:
return []
def give_card(not_swap=True):
if have_ambassador in mycards: # give up Ambassador
return loose_ambassador if not_swap else have_ambassador
if have_contessa in mycards: # give up Contessa
return loose_contessa if not_swap else have_contessa
if have_assassin in mycards: # give up Assassin
return loose_assassin if not_swap else have_assassin
if have_duke in mycards: # give up duke
return loose_duke if not_swap else have_duke
return loose_captain if not_swap else have_captain # give up captain
action = legal_actions[0] # failsafe
with open(filename, 'r') as file:
all_lines = file.readlines()
try:
curr_line = all_lines[-1]
except IndexError:
curr_line = ""
obvious_actions = ['C', '~', '^', '*', '!', '$'] # borrowed from Brilliand
obvious = list(set(obvious_actions).intersection((set(legal_actions))))
otherhand = guess_opponents_hand()
# take care of easy choices
if obvious:
action = coup if coup in obvious else obvious[0]
elif len(set(list(loosing_actions)).intersection(set(legal_actions))) == len(set(legal_actions)):
action = give_card()
elif len(set([i+'\n' for i in list(loosing_actions)]).intersection(set(legal_actions))) == len(set(legal_actions)):
action = give_card() + '\n'
elif len(legal_actions) == 1:
action = legal_actions[0]
elif assassinate in legal_actions and have_assassin in mycards: # if we can legally assassinate, we try to
action = assassinate
elif steal in legal_actions and othercoins > 1 and have_captain in mycards: # we steal when we can or have to prevent a killing coup
action = steal
elif steal in legal_actions and 7 <= othercoins <= 8 and len(mycards) == 1 and have_assassin not in mycards:
action = steal
elif block_assassinate in legal_actions and have_contessa in mycards:
action = block_assassinate
elif block_aid in legal_actions and have_duke in mycards:
action = block_aid
elif block_steal_cap in legal_actions and have_captain in mycards:
action = block_steal_cap
elif block_steal_amb in legal_actions and have_ambassador in mycards:
action = block_steal_amb
elif tax in legal_actions and have_duke in mycards:
action = tax
elif foreign_aid in legal_actions and foreign_aid in get_prev_line(all_lines): # opponent wouldn't foreign aid with a duke
action = foreign_aid
elif block_aid in legal_actions:
if loose_duke not in otherhand and len(mycards) > 1:
action = block_aid
else:
action = pass_challange if pass_challange in legal_actions else "\n"
elif do_challenge in legal_actions:
no_challenge = pass_challange if pass_challange in legal_actions else "\n"
action = do_challenge if len(mycards) > 1 else no_challenge # failsafe
if get_prev_char(curr_line) == block_aid and (not loose_duke in otherhand or len(mycards) > 1): # we don't think opponent has a duke
action = do_challenge
elif get_prev_char(curr_line) == exchange:
action = pass_challange
elif block_assassinate in legal_actions:
if len(mycards) == 1:
if loose_assassin in otherhand and loose_contessa not in otherhand:
action = block_assassinate
elif loose_assassin not in otherhand:
action = do_challenge
else:
action = random.choice([block_assassinate, do_challenge])
else:
action = give_card()
elif block_steal_amb in legal_actions:
if len(mycards) > 1 and 7 <= mycoins <= 8:
if loose_captain in otherhand:
probs = [0.4, 0.4, 0.2]
else:
probs = [0.2, 0.2, 0.6]
action = sample_from_probabilities(probs, [block_steal_amb, block_steal_cap, do_challenge])
elif len(mycards) == 1 and len(otherhand) == 1 and 7 <= mycoins <= 8:
action = do_challenge # worth the risk if we defend a winning move
else:
action = do_challenge if len(mycards) > 1 else pass_challange # failsafe
# go with default
elif get_prev_char(curr_line) == tax and loose_duke not in otherhand and len(mycards) > 1:
action = do_challenge
elif get_prev_char(curr_line) == exchange:
action = pass_challange
elif get_prev_char(curr_line) in {block_steal_cap, block_steal_amb, block_aid, block_assassinate}:
if get_prev_char(curr_line) == block_aid:
action = do_challenge
elif get_prev_char(curr_line) == block_assassinate:
if len(otherhand) == 1 and loose_contessa not in otherhand:
action = do_challenge
elif get_prev_char(curr_line) == block_steal_amb:
action = pass_challange if pass_challange in legal_actions else "\n"
# other choices shall be weighted random choices
elif len(set(legal_actions).intersection({assassinate, steal, tax, income, exchange})) >= 3:
# decide between aggro ass, aggro steal, aggro Tax, Income, Exchange
assumed_values = [(assassinate in legal_actions) * (loose_assassin not in otherhand) * 0.1 * len(mycards) * (len(otherhand) - 1) * (mycoins >= 3),
(othercoins > 1) * ((othercoins > 5 * 0.3) + othercoins * 0.05) * (len(mycards) - 1) * (loose_ambassador not in otherhand),
0.1 * (loose_duke not in otherhand) * (len(mycards) - 1)**(len(otherhand) - 1),
0.3,
(have_ambassador in mycards) * 0.5/len(mycards)
]
normalized_probs = [float(i) / sum(assumed_values) for i in assumed_values]
actions = [assassinate, steal, tax, income, exchange]
action = sample_from_probabilities(normalized_probs, actions)
elif get_prev_char(curr_line) == do_challenge or get_prev_char(curr_line) == coup:
# we lost a challenge or coup
card = give_card()
action = card if card in legal_actions else action
else:
# We missed a case. This shouldn't happen. Please tell me so I can fix it!
# Note: A failsafe always taking a legal action is in place, so please comment out the error raising after telling me :)
raise RuntimeError("Please tell me this happened, give me the history file, comment out this line, "
"and replay. THANKS!")
pass
with open(filename, "a") as history:
history.write(str(action))
if len(mycards) > 2:
mycards = mycards.replace(give_card(False), "", 1)
mycards = mycards.replace(give_card(False), "", 1)
print(mycards)
```
# Statistician
Knows his winning strategy, just like the gambler, but always trusts maximum probabilities instead of randomly sampling from them.
```
import sys
import random
import time
random.seed(time.time()) # lets keep it rather random
_, filename, othercoins, mycoins, mycards = sys.argv[:5]
legal_actions = sys.argv[5:]
othercoins = int(othercoins)
mycoins = int(mycoins)
income = 'I\n'
foreign_aid, coup, exchange, tax, assassinate, steal, block_aid, \
block_steal_amb, block_steal_cap, block_assassinate, \
pass_challange, do_challenge = "FCETASdacspq"
loosing_actions = "_'<=0"
loose_ambassador, loose_assassin, loose_captain, loose_contessa, loose_duke = loosing_actions
have_ambassador, have_assassin, have_captain, \
have_contessa, have_duke = "~^*!$"
actions_dict = {
exchange: loose_ambassador, tax: loose_duke, assassinate: loose_assassin, steal: loose_captain,
block_aid: loose_duke, block_steal_amb: loose_ambassador, block_steal_cap: loose_captain, block_assassinate: loose_contessa
}
def guess_opponents_hand():
# get number of each card still in play and not in hand
card_counts = [3] * 5
card_give_up = list("_'<=0")
with open(filename, 'r') as history:
while True:
line = history.readline()
if not line:
break
for card in card_give_up:
if card in line:
card_counts[card_give_up.index(card)] -= 1
have_cards = list("~^*!$")
if sum(card_counts) == 15:
num_cards = 2
elif sum(card_counts) == 14:
if len(mycards) == 1:
num_cards = 2
else:
num_cards = 1
else:
num_cards = 1
for card in mycards:
card_counts[have_cards.index(card)] -= 1
# randomly sample a hand for the opponent
card_1 = sample_from_probabilities([i / sum(card_counts) for i in card_counts], card_give_up)
if num_cards == 1:
return card_1
card_counts[card_give_up.index(card_1)] -= 1
return card_1 + sample_from_probabilities([i / sum(card_counts) for i in card_counts], card_give_up)
def sample_from_probabilities(success_probabilities, actions):
# statistical max, decide randomly on equivalent probabilities
max_prob = max(success_probabilities)
indicies = []
idx = 0
for i in success_probabilities:
if i == max_prob:
indicies.append(idx)
idx += 1
choice = random.choice(indicies)
return actions[choice]
def get_prev_char(line, x=1):
try:
return line[-1*x]
except:
return ""
def get_prev_line(lines):
try:
return lines[-2]
except:
return []
def give_card(not_swap=True):
if have_ambassador in mycards: # give up Ambassador
return loose_ambassador if not_swap else have_ambassador
if have_contessa in mycards: # give up Contessa
return loose_contessa if not_swap else have_contessa
if have_assassin in mycards: # give up Assassin
return loose_assassin if not_swap else have_assassin
if have_duke in mycards: # give up duke
return loose_duke if not_swap else have_duke
return loose_captain if not_swap else have_captain # give up captain
action = legal_actions[0] # failsafe
with open(filename, 'r') as file:
all_lines = file.readlines()
try:
curr_line = all_lines[-1]
except IndexError:
curr_line = ""
obvious_actions = ['C', '~', '^', '*', '!', '$'] # borrowed from Brilliand
obvious = list(set(obvious_actions).intersection((set(legal_actions))))
otherhand = guess_opponents_hand()
# take care of easy choices
if obvious:
action = coup if coup in obvious else obvious[0]
elif len(set(list(loosing_actions)).intersection(set(legal_actions))) == len(set(legal_actions)):
action = give_card()
elif len(set([i+'\n' for i in list(loosing_actions)]).intersection(set(legal_actions))) == len(set(legal_actions)):
action = give_card() + '\n'
elif len(legal_actions) == 1:
action = legal_actions[0]
elif assassinate in legal_actions and have_assassin in mycards: # if we can legally assassinate, we try to
action = assassinate
elif steal in legal_actions and othercoins > 1 and have_captain in mycards: # we steal when we can or have to prevent a killing coup
action = steal
elif steal in legal_actions and 7 <= othercoins <= 8 and len(mycards) == 1 and have_assassin not in mycards:
action = steal
elif block_assassinate in legal_actions and have_contessa in mycards:
action = block_assassinate
elif block_aid in legal_actions and have_duke in mycards:
action = block_aid
elif block_steal_cap in legal_actions and have_captain in mycards:
action = block_steal_cap
elif block_steal_amb in legal_actions and have_ambassador in mycards:
action = block_steal_amb
elif tax in legal_actions and have_duke in mycards:
action = tax
elif foreign_aid in legal_actions and foreign_aid in get_prev_line(all_lines): # opponent wouldn't foreign aid with a duke
action = foreign_aid
elif block_aid in legal_actions:
if loose_duke not in otherhand and len(mycards) > 1:
action = block_aid
else:
action = pass_challange if pass_challange in legal_actions else "\n"
elif do_challenge in legal_actions:
no_challenge = pass_challange if pass_challange in legal_actions else "\n"
action = do_challenge if len(mycards) > 1 else no_challenge # failsafe
if get_prev_char(curr_line) == block_aid and (not loose_duke in otherhand or len(mycards) > 1): # we don't think opponent has a duke
action = do_challenge
elif get_prev_char(curr_line) == exchange:
action = pass_challange
elif block_assassinate in legal_actions:
if len(mycards) == 1:
if loose_assassin in otherhand and loose_contessa not in otherhand:
action = block_assassinate
elif loose_assassin not in otherhand:
action = do_challenge
else:
action = random.choice([block_assassinate, do_challenge])
else:
action = give_card()
elif block_steal_amb in legal_actions:
if len(mycards) > 1 and 7 <= mycoins <= 8:
if loose_captain in otherhand:
probs = [0.4, 0.4, 0.2]
else:
probs = [0.2, 0.2, 0.6]
action = sample_from_probabilities(probs, [block_steal_amb, block_steal_cap, do_challenge])
elif len(mycards) == 1 and len(otherhand) == 1 and 7 <= mycoins <= 8:
action = do_challenge # worth the risk if we defend a winning move
else:
action = do_challenge if len(mycards) > 1 else pass_challange # failsafe
# go with default
elif get_prev_char(curr_line) == tax and loose_duke not in otherhand and len(mycards) > 1:
action = do_challenge
elif get_prev_char(curr_line) == exchange:
action = pass_challange
elif get_prev_char(curr_line) in {block_steal_cap, block_steal_amb, block_aid, block_assassinate}:
if get_prev_char(curr_line) == block_aid:
action = do_challenge
elif get_prev_char(curr_line) == block_assassinate:
if len(otherhand) == 1 and loose_contessa not in otherhand:
action = do_challenge
elif get_prev_char(curr_line) == block_steal_amb:
action = pass_challange if pass_challange in legal_actions else "\n"
# other choices shall be weighted random choices
elif len(set(legal_actions).intersection({assassinate, steal, tax, income, exchange})) >= 3:
# decide between aggro ass, aggro steal, aggro Tax, Income, Exchange
assumed_values = [(assassinate in legal_actions) * (loose_assassin not in otherhand) * 0.1 * len(mycards) * (len(otherhand) - 1) * (mycoins >= 3),
(othercoins > 1) * ((othercoins > 5 * 0.3) + othercoins * 0.05) * (len(mycards) - 1) * (loose_ambassador not in otherhand),
0.1 * (loose_duke not in otherhand) * (len(mycards) - 1)**(len(otherhand) - 1),
0.3,
(have_ambassador in mycards) * 0.5/len(mycards)
]
normalized_probs = [float(i) / sum(assumed_values) for i in assumed_values]
actions = [assassinate, steal, tax, income, exchange]
action = sample_from_probabilities(normalized_probs, actions)
elif get_prev_char(curr_line) == do_challenge or get_prev_char(curr_line) == coup:
# we lost a challenge or coup
card = give_card()
action = card if card in legal_actions else action
else:
# We missed a case. This shouldn't happen. Please tell me so I can fix it!
# Note: A failsafe always taking a legal action is in place, so please comment out the error raising after telling me :)
raise RuntimeError("Please tell me this happened, give me the history file, comment out this line, "
"and replay. THANKS!")
pass
with open(filename, "a") as history:
history.write(str(action))
if len(mycards) > 2:
mycards = mycards.replace(give_card(False), "", 1)
mycards = mycards.replace(give_card(False), "", 1)
print(mycards)
```
] |
[Question]
[
Given a black and white image with a white background and a set of black dots, paint a set of white pixels red, such that there is a path between each pair of black pixels.
### Details
* A path is a set of connected pixels (8-neighbourhood connectivity). Black pixels can be used as part of the paths. The goal is trying to minimize the set of red pixels under the above conditions, and outputting a corresponding image.
* You don't *have to* find the optimal solution.
* A trivial and at the same time worst solution is just painting all the white pixels red.
* Example (Pixels are enlarged for visibility):
[](https://i.stack.imgur.com/TSYo4.png)
## Details
* Given a pixel image (in any suitable format) return another image with the dots connected as specified above, as well as a integer indicating how many red pixel were used.
* The Score is the product of (1+the number of red pixels) for each of the 14 testcases.
* The goal is having the lowest score.
## Testcases
The 14 testcases are shown below. A python program to verify the connectedness of the outputs can be found [here.](https://pastebin.com/raw/PrqtQJqM)




## Meta
Thanks to @Veskah, @Fatalize, @wizzwizz4 and @trichoplax for the various suggestions.
[Answer]
# Python, 2.62 \* 10^40
This algorithm just floodfills (BFS) the plane starting from the black parts of the image, where for each new pixel we record what black part it was flooded from. As soon as we have two neighbouring pixels with different black parts as ancestors, we basically merge these two black parts by joining them through the ancestors of the two neighbours we just found. In theory this could be implemented in `O(#pixels)`, but to keep the amount of code at an acceptable level this implementation is slightly worse.

### Output
[](https://i.stack.imgur.com/EY51R.png)
[](https://i.stack.imgur.com/6iMWV.png)
[](https://i.stack.imgur.com/DaM7o.png)
[](https://i.stack.imgur.com/hK8SX.png)
[](https://i.stack.imgur.com/RHfqn.png)
[](https://i.stack.imgur.com/MXTsg.png)
[](https://i.stack.imgur.com/oDvnd.png)
[](https://i.stack.imgur.com/turKe.png)
[](https://i.stack.imgur.com/Cfx7Y.png)
[](https://i.stack.imgur.com/2vN2M.png)
[](https://i.stack.imgur.com/8xI5U.png)
[](https://i.stack.imgur.com/ReeGC.png)
[](https://i.stack.imgur.com/c2egv.png)
[](https://i.stack.imgur.com/iHQ11.png)
```
import numpy as np
from scipy import ndimage
import imageio
from collections import deque
# path to your image
for k in range(1, 15):
fname=str(k).zfill(2) +'.png'
print("processing ", fname)
# load image
img = imageio.imread("./images/"+fname, pilmode="RGB")
print(img.shape)
# determine non_white part
white = np.logical_and(np.logical_and(img[:,:,0] == 255, img[:,:,1] == 255), img[:,:,2] == 255)
non_white = np.logical_not(white)
# find connected components of non-white part
neighbourhood = np.ones((3,3))
labeled, nr_objects = ndimage.label(non_white, neighbourhood)
# print result
print("number of separate objects is {}".format(nr_objects))
# start flood filling algorithm
ind = np.nonzero(labeled)
front = deque(zip(ind[0],ind[1]))
membership = np.copy(labeled)
is_merge_point = np.zeros_like(labeled) > 0
parent = np.zeros((2,) + labeled.shape) #find ancestor of each pixel
is_seed = labeled > 0
size_i, size_j = labeled.shape
# flood from every seed
while front: #while we have unexplored pixels
point = front.popleft()
# check neighbours:
for (di,dj) in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:
current = membership[point[0], point[1]]
new_i, new_j = point[0]+di, point[1]+dj
if 0 <= new_i < size_i and 0 <= new_j < size_j:
value = membership[new_i, new_j]
if value == 0:
membership[new_i, new_j] = current
front.append((new_i, new_j))
parent[:, new_i, new_j] = point
elif value != current: #MERGE!
is_merge_point[point[0], point[1]] = True
is_merge_point[new_i, new_j] = True
membership[np.logical_or(membership == value, membership == current)] = min(value, current)
# trace back from every merger
ind = np.nonzero(is_merge_point)
merge_points = deque(zip(ind[0].astype(np.int),ind[1].astype(np.int)))
for point in merge_points:
next_p = point
while not is_seed[next_p[0], next_p[1]]:
is_merge_point[next_p[0], next_p[1]] = True
next_p = parent[:, next_p[0], next_p[1]].astype(np.int)
# add red points:
img_backup = np.copy(img)
img[:,:,0][is_merge_point] = 255 * img_backup[:,:,0]
img[:,:,1][is_merge_point] = 0 * img_backup[:,:,1]
img[:,:,2][is_merge_point] = 0 * img_backup[:,:,2]
#compute number of new points
n_red_points = (img[:,:,0] != img[:,:,1]).sum()
print("#red points:", n_red_points)
# plot: each component should have separate color
imageio.imwrite("./out_images/"+fname, np.array(img))
```
### Score
```
(1+183)*(1+142)*(1+244)*(1+42)*(1+1382)*(1+2)*(1+104)*(1+7936)*(1+26)*(1+38562)*(1+42956)*(1+6939)*(1+8882)*(1+9916)
= 26208700066468930789809050445560539404000
= 2.62 * 10^40
```
[Answer]
# C, score 2.397x10^38
Man this took way too long to do, most likely due to my choice of language. I got the algorithm working fairly early, but ran into a lot of problems with memory allocation (couldn't recursively free stuff due to stack overflows, leak sizes were huge).
Still! It beats the other entry on every test case, and ~~might even be optimal~~ gets pretty close or exactly optimal solutions a lot of the time.
Anyway, here's the code:
```
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define WHITE 'W'
#define BLACK 'B'
#define RED 'R'
typedef struct image {
int w, h;
char* buf;
} image;
typedef struct point {
int x, y;
struct point *next;
struct point *parent;
} point;
typedef struct shape {
point* first_point;
point* last_point;
struct shape* next_shape;
} shape;
typedef struct storage {
point* points;
size_t points_size;
size_t points_index;
shape* shapes;
size_t shapes_size;
size_t shapes_index;
} storage;
char getpx(image* img, int x, int y) {
if (0>x || x>=img->w || 0>y || y>=img->h) {
return WHITE;
} else {
return img->buf[y*img->w+x];
}
}
storage* create_storage(int w, int h) {
storage* ps = (storage*)malloc(sizeof(storage));
ps->points_size = 8*w*h;
ps->points = (point*)calloc(ps->points_size, sizeof(point));
ps->points_index = 0;
ps->shapes_size = 2*w*h;
ps->shapes = (shape*)calloc(ps->shapes_size, sizeof(shape));
ps->shapes_index = 0;
return ps;
}
void free_storage(storage* ps) {
if (ps != NULL) {
if (ps->points != NULL) {
free(ps->points);
ps->points = NULL;
}
if (ps->shapes != NULL) {
free(ps->shapes);
ps->shapes = NULL;
}
free(ps);
}
}
point* alloc_point(storage* ps) {
if (ps->points_index == ps->points_size) {
printf("WHOAH THERE BUDDY SLOW DOWN\n");
/*// double the size of the buffer
point* new_buffer = (point*)malloc(ps->points_size*2*sizeof(point));
// need to change all existing pointers to point to new buffer
long long int pointer_offset = (long long int)new_buffer - (long long int)ps->points;
for (size_t i=0; i<ps->points_index; i++) {
new_buffer[i] = ps->points[i];
if (new_buffer[i].next != NULL) {
new_buffer[i].next += pointer_offset;
}
if (new_buffer[i].parent != NULL) {
new_buffer[i].parent += pointer_offset;
}
}
for(size_t i=0; i<ps->shapes_index; i++) {
if (ps->shapes[i].first_point != NULL) {
ps->shapes[i].first_point += pointer_offset;
}
if (ps->shapes[i].last_point != NULL) {
ps->shapes[i].last_point += pointer_offset;
}
}
free(ps->points);
ps->points = new_buffer;
ps->points_size = ps->points_size * 2;*/
}
point* out = &(ps->points[ps->points_index]);
ps->points_index += 1;
return out;
}
shape* alloc_shape(storage* ps) {
/*if (ps->shapes_index == ps->shapes_size) {
// double the size of the buffer
shape* new_buffer = (shape*)malloc(ps->shapes_size*2*sizeof(shape));
long long int pointer_offset = (long long int)new_buffer - (long long int)ps->shapes;
for (size_t i=0; i<ps->shapes_index; i++) {
new_buffer[i] = ps->shapes[i];
if (new_buffer[i].next_shape != NULL) {
new_buffer[i].next_shape += pointer_offset;
}
}
free(ps->shapes);
ps->shapes = new_buffer;
ps->shapes_size = ps->shapes_size * 2;
}*/
shape* out = &(ps->shapes[ps->shapes_index]);
ps->shapes_index += 1;
return out;
}
shape floodfill_shape(image* img, storage* ps, int x, int y, char* buf) {
// not using point allocator for exploration stack b/c that will overflow it
point* stack = (point*)malloc(sizeof(point));
stack->x = x;
stack->y = y;
stack->next = NULL;
stack->parent = NULL;
point* explored = NULL;
point* first_explored;
point* next_explored;
while (stack != NULL) {
int sx = stack->x;
int sy = stack->y;
point* prev_head = stack;
stack = stack->next;
free(prev_head);
buf[sx+sy*img->w] = 1; // mark as explored
// add point to shape
next_explored = alloc_point(ps);
next_explored->x = sx;
next_explored->y = sy;
next_explored->next = NULL;
next_explored->parent = NULL;
if (explored != NULL) {
explored->next = next_explored;
} else {
first_explored = next_explored;
}
explored = next_explored;
for (int dy=-1; dy<2; dy++) {
for (int dx=-1; dx<2; dx++) {
if (dy != 0 || dx != 0) {
int nx = sx+dx;
int ny = sy+dy;
if (getpx(img, nx, ny) == WHITE || buf[nx+ny*img->w]) {
// skip adding point to fringe
} else {
// push point to top of stack
point* new_point = (point*)malloc(sizeof(point));
new_point->x = nx;
new_point->y = ny;
new_point->next = stack;
new_point->parent = NULL;
stack = new_point;
}
}
}
}
}
/*if (getpx(img, x, y) == WHITE || buf[x+y*img->w]) {
return (shape){NULL, NULL, NULL};
} else {
buf[x+y*img->w] = 1;
shape e = floodfill_shape(img, ps, x+1, y, buf);
shape ne = floodfill_shape(img, ps, x+1, y+1, buf);
shape n = floodfill_shape(img, ps, x, y+1, buf);
shape nw = floodfill_shape(img, ps, x-1, y+1, buf);
shape w = floodfill_shape(img, ps, x-1, y, buf);
shape sw = floodfill_shape(img, ps, x-1, y-1, buf);
shape s = floodfill_shape(img, ps, x, y-1, buf);
shape se = floodfill_shape(img, ps, x+1, y-1, buf);
point *p = alloc_point(ps);
p->x = x;
p->y = y;
p->next = NULL;
p->parent = NULL;
shape o = (shape){p, p, NULL};
if (e.first_point != NULL) {
o.last_point->next = e.first_point;
o.last_point = e.last_point;
}
if (ne.first_point != NULL) {
o.last_point->next = ne.first_point;
o.last_point = ne.last_point;
}
if (n.first_point != NULL) {
o.last_point->next = n.first_point;
o.last_point = n.last_point;
}
if (nw.first_point != NULL) {
o.last_point->next = nw.first_point;
o.last_point = nw.last_point;
}
if (w.first_point != NULL) {
o.last_point->next = w.first_point;
o.last_point = w.last_point;
}
if (sw.first_point != NULL) {
o.last_point->next = sw.first_point;
o.last_point = sw.last_point;
}
if (s.first_point != NULL) {
o.last_point->next = s.first_point;
o.last_point = s.last_point;
}
if (se.first_point != NULL) {
o.last_point->next = se.first_point;
o.last_point = se.last_point;
}
return o;
}*/
shape out = {first_explored, explored, NULL};
return out;
}
shape* create_shapes(image* img, storage* ps) {
char* added_buffer = (char*)calloc(img->w*img->h, sizeof(char));
shape* first_shape = NULL;
shape* last_shape = NULL;
int num_shapes = 0;
for (int y=0; y<img->h; y++) {
for (int x=0; x<img->w; x++) {
if (getpx(img, x, y) != WHITE && !(added_buffer[x+y*img->w])) {
shape* alloced_shape = alloc_shape(ps);
*alloced_shape = floodfill_shape(img, ps, x, y, added_buffer);
if (first_shape == NULL) {
first_shape = alloced_shape;
last_shape = alloced_shape;
} else if (last_shape != NULL) {
last_shape->next_shape = alloced_shape;
last_shape = alloced_shape;
}
num_shapes++;
}
}
}
free(added_buffer);
return first_shape;
}
void populate_buf(image* img, shape* s, char* buf) {
point* p = s->first_point;
while (p != NULL) {
buf[p->x+p->y*img->w] = 1;
p = p->next;
}
}
bool expand_frontier(image* img, storage* ps, shape* prev_frontier, shape* next_frontier, char* buf) {
point* p = prev_frontier->first_point;
point* n = NULL;
bool found = false;
size_t starting_points_index = ps->points_index;
while (p != NULL) {
for (int dy=-1; dy<2; dy++) {
for (int dx=-1; dx<2; dx++) {
if (dy != 0 || dx != 0) {
int nx = p->x+dx;
int ny = p->y+dy;
if ((0<=nx && nx<img->w && 0<=ny && ny<img->h) // in bounds
&& !buf[nx+ny*img->w]) { // not searched yet
buf[nx+ny*img->w] = 1;
if (getpx(img, nx, ny) != WHITE) {
// found a new shape!
ps->points_index = starting_points_index;
n = alloc_point(ps);
n->x = nx;
n->y = ny;
n->next = NULL;
n->parent = p;
found = true;
goto __expand_frontier_fullbreak;
} else {
// need to search more
point* f = alloc_point(ps);
f->x = nx;
f->y = ny;
f->next = n;
f->parent = p;
n = f;
}
}
}
}}
p = p->next;
}
__expand_frontier_fullbreak:
p = NULL;
point* last_n = n;
while (last_n->next != NULL) {
last_n = last_n->next;
}
next_frontier->first_point = n;
next_frontier->last_point = last_n;
return found;
}
void color_from_frontier(image* img, point* frontier_point) {
point* p = frontier_point->parent;
while (p->parent != NULL) { // if everything else is right,
// a frontier point should come in a chain of at least 3
// (f point (B) -> point to color (W) -> point in shape (B) -> NULL)
img->buf[p->x+p->y*img->w] = RED;
p = p->parent;
}
}
int main(int argc, char** argv) {
if (argc < 3) {
printf("Error: first argument must be filename to load, second argument filename to save to.\n");
return 1;
}
char* fname = argv[1];
FILE* fp = fopen(fname, "r");
if (fp == NULL) {
printf("Error opening file \"%s\"\n", fname);
return 1;
}
int w, h;
w = 0;
h = 0;
fscanf(fp, "%d %d\n", &w, &h);
if (w==0 || h==0) {
printf("Error: invalid width/height specified\n");
return 1;
}
char* buf = (char*)malloc(sizeof(char)*w*h+1);
fgets(buf, w*h+1, fp);
fclose(fp);
image img = (image){w, h, buf};
int nshapes = 0;
storage* ps = create_storage(w, h);
while (nshapes != 1) {
// main loop, do processing step until one shape left
ps->points_index = 0;
ps->shapes_index = 0;
shape* head = create_shapes(&img, ps);
nshapes = 0;
shape* pt = head;
while (pt != NULL) {
pt = pt->next_shape;
nshapes++;
}
if (nshapes % 1024 == 0) {
printf("shapes left: %d\n", nshapes);
}
if (nshapes == 1) {
goto __main_task_complete;
}
shape* frontier = alloc_shape(ps);
// making a copy so we can safely free later
point* p = head->first_point;
point* ffp = NULL;
point* flp = NULL;
while (p != NULL) {
if (ffp == NULL) {
ffp = alloc_point(ps);
ffp->x = p->x;
ffp->y = p->y;
ffp->next = NULL;
ffp->parent = NULL;
flp = ffp;
} else {
point* fnp = alloc_point(ps);
fnp->x = p->x;
fnp->y = p->y;
fnp->next = NULL;
fnp->parent = NULL;
flp->next = fnp;
flp = fnp;
}
p = p->next;
}
frontier->first_point = ffp;
frontier->last_point = flp;
frontier->next_shape = NULL;
char* visited_buf = (char*)calloc(img.w*img.h+1, sizeof(char));
populate_buf(&img, frontier, visited_buf);
shape* new_frontier = alloc_shape(ps);
new_frontier->first_point = NULL;
new_frontier->last_point = NULL;
new_frontier->next_shape = NULL;
while (!expand_frontier(&img, ps, frontier, new_frontier, visited_buf)) {
frontier->first_point = new_frontier->first_point;
frontier->last_point = new_frontier->last_point;
new_frontier->next_shape = frontier;
}
free(visited_buf);
color_from_frontier(&img, new_frontier->first_point);
__main_task_complete:
img = img;
}
free_storage(ps);
char* outfname = argv[2];
fp = fopen(outfname, "w");
if (fp == NULL) {
printf("Error opening file \"%s\"\n", outfname);
return 1;
}
fprintf(fp, "%d %d\n", img.w, img.h);
fprintf(fp, "%s", img.buf);
free(img.buf);
fclose(fp);
return 0;
}
```
Tested on: Arch Linux, GCC 9.1.0, `-O3`
This code takes input/output in a custom file I call "cppm" (because it's like a condensed version of the classic PPM format). A python script to convert to/from it is below:
```
from PIL import Image
BLACK='B'
WHITE='W'
RED ='R'
def image_to_cppm(infname, outfname):
outfile = open(outfname, 'w')
im = Image.open(infname)
w, h = im.width, im.height
outfile.write(f"{w} {h}\n")
for y in range(h):
for x in range(w):
r, g, b, *_ = im.getpixel((x, y))
if r==0 and g==0 and b==0:
outfile.write(BLACK)
elif g==0 and b==0:
outfile.write(RED)
else:
outfile.write(WHITE)
outfile.write("\n")
outfile.close()
im.close()
def cppm_to_image(infname, outfname):
infile = open(infname, 'r')
w, h = infile.readline().split(" ")
w, h = int(w), int(h)
im = Image.new('RGB', (w, h), color=(255, 255, 255))
for y in range(h):
for x in range(w):
c = infile.read(1)
if c==BLACK:
im.putpixel((x,y), (0, 0, 0))
elif c==RED:
im.putpixel((x,y), (255, 0, 0))
infile.close()
im.save(outfname)
im.close()
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("Error: must provide 2 files to convert, first is from, second is to")
infname = sys.argv[1]
outfname = sys.argv[2]
if not infname.endswith("cppm") and outfname.endswith("cppm"):
image_to_cppm(infname, outfname)
elif infname.endswith("cppm") and not outfname.endswith("cppm"):
cppm_to_image(infname, outfname)
else:
print("didn't do anything, exactly one file must end with .cppm")
```
## Algorithm explanation
How this algorithm works is that it starts by finding all the connected shapes in the image, including red pixels. It then takes the first one and expands its frontier one pixel at a time until it encounters another shape. It then colors all the pixels from the touching to the original shape (using the linkedlist it made along the way to keep track). Finally, it repeats the process, finding all the new shapes created, until there is only one shape left.
## Image gallery
Testcase 1, 183 pixels
[](https://i.stack.imgur.com/SQCYl.png)
Testcase 2, 140 pixels
[](https://i.stack.imgur.com/YACe4.png)
Testcase 3, 244 pixels
[](https://i.stack.imgur.com/fNTag.png)
Testcase 4, 42 pixels
[](https://i.stack.imgur.com/76Tbb.png)
Testcase 5, 622 pixels
[](https://i.stack.imgur.com/n6WXy.png)
Testcase 6, 1 pixel
[](https://i.stack.imgur.com/uN40o.png)
Testcase 7, 104 pixels
[](https://i.stack.imgur.com/mCOw3.png)
Testcase 8, 2286 pixels
[](https://i.stack.imgur.com/hRF4d.png)
Testcase 9, 22 pixels
[](https://i.stack.imgur.com/ZUgh3.png)
Testcase 10, 31581 pixels
[](https://i.stack.imgur.com/UaNYN.png)
Testcase 11, 21421 pixels
[](https://i.stack.imgur.com/etvba.png)
Testcase 12, 5465 pixels
[](https://i.stack.imgur.com/dXOPR.png)
Testcase 13, 4679 pixels
[](https://i.stack.imgur.com/H8yN2.png)
Testcase 14, 7362 pixels
[](https://i.stack.imgur.com/BWcRZ.png)
[Answer]
# Python 3: ~~1.7x10^42~~ 1.5x10^41
Using `Pillow`, `numpy` and `scipy`.
Images are assumed to be in an `images` folder located in the same directory as the script.
**Disclaimer**: It takes a long time to process all the images.
## Code
```
import sys
import os
from PIL import Image
import numpy as np
import scipy.ndimage
def obtain_groups(image, threshold, structuring_el):
"""
Obtain isles of unconnected pixels via a threshold on the R channel
"""
image_logical = (image[:, :, 1] < threshold).astype(np.int)
return scipy.ndimage.measurements.label(image_logical, structure=structuring_el)
def swap_colors(image, original_color, new_color):
"""
Swap all the pixels of a specific color by another color
"""
r1, g1, b1 = original_color # RGB value to be replaced
r2, g2, b2 = new_color # New RGB value
red, green, blue = image[:, :, 0], image[:, :, 1], image[:, :, 2]
mask = (red == r1) & (green == g1) & (blue == b1)
image[:, :, :3][mask] = [r2, g2, b2]
return image
def main(image_path=None):
images = os.listdir("images")
f = open("results.txt", "w")
if image_path is not None:
images = [image_path]
for image_name in images:
im = Image.open("images/"+image_name).convert("RGBA")
image = np.array(im)
image = swap_colors(image, (255, 255, 255), (255, 0, 0))
# create structuring element to determine unconnected groups of pixels in image
s = scipy.ndimage.morphology.generate_binary_structure(2, 2)
for i in np.ndindex(image.shape[:2]):
# skip black pixels
if sum(image[i[0], i[1]]) == 255:
continue
image[i[0], i[1]] = [255, 255, 255, 255]
# label the different groups, considering diagonal connections as valid
groups, num_groups = obtain_groups(image, 255, s)
if num_groups != 1:
image[i[0], i[1]] = [255, 0, 0, 255]
# Show percentage
print((i[1] + i[0]*im.size[0])/(im.size[0]*im.size[1]))
# Number of red pixels
red_p = 0
for i in np.ndindex(image.shape[:2]):
j = (im.size[1] - i[0] - 1, im.size[0] - i[1] - 1)
# skip black and white pixels
if sum(image[j[0], j[1]]) == 255 or sum(image[j[0], j[1]]) == 255*4:
continue
image[j[0], j[1]] = [255, 255, 255, 255]
# label the different groups, considering diagonal connections as valid
groups, num_groups = obtain_groups(image, 255, s)
if num_groups != 1:
image[j[0], j[1]] = [255, 0, 0, 255]
# Show percentage
print((j[1] + j[0]*im.size[0])/(im.size[0]*im.size[1]))
red_p += (sum(image[j[0], j[1]]) == 255*2)
print(red_p)
f.write("r_"+image_name+": "+str(red_p)+"\n")
im = Image.fromarray(image)
im.show()
im.save("r_"+image_name)
f.close()
if __name__ == "__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
main()
```
## Explanation
Trivial solution. We begin by changing the color of all the white pixels in an image to red. By doing this, it is guaranteed that all the elements (any isle of black pixels) are connected.
Then, we iterate over all the pixels in the image starting from the top left corner and moving right and down. For every red pixel we find we change its color to white. If after this change of color there is still only one element (an element being now any isle of black and red pixels), we leave the pixel white and move on to the next pixel. However, if after the color change from red to white the number of elements is bigger than one, we leave the pixel red and move on to the next pixel.
**Update**
As it can be seen (and expected) the connections obtained by only using this method show a regular pattern and in some cases, such as in the 6th and 11th images, there are unnecessary red pixels.
This extra red pixels can be easily removed by iterating again over the image and performing the same operations as explained above but from the bottom right corner to the top left corner. This second pass is much faster since the amount of red pixels that have to be checked.
## Results
The images which are modified after the second pass are listed twice to show the differences.
[](https://i.stack.imgur.com/lmfZI.png)
Number of red pixels: 18825
[](https://i.stack.imgur.com/J84oc.png)
Number of red pixels: 334
[](https://i.stack.imgur.com/KJG1R.png)
Number of red pixels: 1352
[](https://i.stack.imgur.com/lKgxg.png)
Number of red pixels: 20214
[](https://i.stack.imgur.com/UdPMC.png)
Number of red pixels: 47268
[](https://i.stack.imgur.com/CEkBX.png) [](https://i.stack.imgur.com/AX3i0.png)
Number of red pixels: ~~63~~ 27
[](https://i.stack.imgur.com/NDZqF.png)
Number of red pixels: 17889
[](https://i.stack.imgur.com/v9Psm.png)
Number of red pixels: 259
[](https://i.stack.imgur.com/bWEGF.png)
Number of red pixels: 6746
[](https://i.stack.imgur.com/gzmso.png)
Number of red pixels: 586
[](https://i.stack.imgur.com/iNC7D.png) [](https://i.stack.imgur.com/Mx2ot.png)
Number of red pixels: ~~9~~ 1
[](https://i.stack.imgur.com/NXytO.png)
Number of red pixels: 126
[](https://i.stack.imgur.com/BtKpN.png)
Number of red pixels: 212
[](https://i.stack.imgur.com/PBSmB.png)
Number of red pixels: 683
Score computation:
(1+6746) \* (1+126) \* (1+259) \* (1+17889) \* (1+334) \* (1+586) \* (1+18825) \* (1+9) \* (1+683) \* (1+1352) \* (1+20214) \* (1+212) \* (1+63) \* (1+47268) = 1778700054505858720992088713763655500800000 ~ 1.7x10^42
Updated score computation after adding second pass:
(1+ 18825) \* (1+ 1352) \* (1+ 20214) \* (1+ 47268) \* (1+ 27) \* (1+ 17889) \* (1+ 6746) \* (1+ 586) \* (1+ 1) \* (1+ 126) \* (1+ 212) \* (1+ 334) \* (1+259) \* (1+683) = 155636254769262638086807762454319856320000 ~ 1.5x10^41
] |
[Question]
[
## Input:
* An integer `n` in the range `2 <= n <= 10`
* A list of positive integers
## Output:
Convert the integers to their binary representation (without any leading zeroes), and join them all together.
Then determine all binary substrings that form a 'binary fence' using `n` amount of fence posts. The spaces (zeros) between each fence post are irrelevant (at least 1), but the fence posts themselves should all be of equal width.
Here the regexes the binary substrings should match for each `n`:
```
n Regex to match to be a 'binary fence' Some examples
2 ^(1+)0+\1$ 101; 1100011; 1110111;
3 ^(1+)0+\10+\1$ 10101; 1000101; 110011011;
4 ^(1+)0+\10+\10+\1$ 1010101; 110110011011; 11110111100001111001111;
etc. etc. You get the point
```
Looking at the `n=4` examples:
```
1010101
^ ^ ^ ^ All fence posts have a width of one 1
^ ^ ^ with one or more 0s in between them
110110011011
^^ ^^ ^^ ^^ All fence posts have a width of two 1s
^ ^^ ^ with one or more 0s in between them
11110111100001111001111
^^^^ ^^^^ ^^^^ ^^^^ All fence posts have a width of four 1s
^ ^^^^ ^^ with one or more 0s in between them
```
We then output the numbers that use binary digits of the matches 'binary fences'.
## Example:
Input: `n=4`, `L=[85,77,71]`
The binary representation of these integer joined together is:
`1010101 1001101 1000111` (NOTE: The spaces are only added as clarification for the example).
Since `n=4`, we look for substrings matching the regex `(1+)0+\10+\10+\1`, in which case we can find two:
`1010101` (at position `(1010101) 1001101 1000111`); and `11001101100011` (at position `101010(1 1001101 100011)1`)
The first binary fence only uses binary digits from `85`, and the second binary fence uses binary digits from all three integers. So the output in this case would be:
`[[85],[85,77,71]]`
## Challenge rules:
* Although it's also mentioned in the example above, the last sentence is an important one: **We output the numbers for which binary digits are used in the 'binary fence' substring.**
* I/O is flexible. Input can be a list/array/stream of integers, space/comma/newline delimited string, etc. Output can be a 2D integer-list, a single delimited string, a string-list, new-line printed to STDOUT, etc. All up to you, but please state what you've used in your answer.
* Output order of the list itself is irrelevant, but the output of each inner list is of course in the same order as the input-list. So with the example above, `[[85,77,71],[85]]` is a valid output as well, but `[[85],[77,85,71]]` is not.
* As you may have already noticed from the example (the `85`), binary-digits can be used multiple times.
* The regexes should match the substring entirely. So `110101` or `010101` aren't ever a valid 'binary fences' (`10101` is however, iff `n=3`).
* Items in the output-list aren't unique, only the binary-positions of the 'binary fences' are unique. If multiple 'binary fences' can be created with the same integer(s), we add them multiple times to the output-list.
For example: `n=2`, `L=[109, 45]` (binary `1101101 101101`) can form these 'binary fence' substrings: `11011` (at position `(11011)01 101101`); `101` (at position `1(101)101 101101`); `11011` (at position `110(1101 1)01101`); `101` (at position `1101(101) 101101`); `11011` (at position `110110(1 1011)01`); `101` (at position `1101101 (101)101`); `101` (at position `1101101 101(101)`), so the output would be `[[109],[109],[109,45],[109],[109,45],[45],[45]]`.
Another example: `n=2`, `L=[8127]` (binary `1111110111111`) can form these 'binary fence' substrings: `1111110111111` (at position `(1111110111111)`); `11111011111` (at position `1(11111011111)1`); `111101111` (at position `11(111101111)11`); `1110111` (at position `111(1110111)111`); `11011` (at position `1111(11011)1111`); `101` (at position `11111(101)11111`), so the output would be `[[8127],[8127],[8127],[8127],[8127],[8127]]`.
* If no valid output is possible, you can return an empty list or some other kind of falsey output (`null`, `false`, throws an error, etc. Again, your call).
## 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 (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: Output
(the binary below the output are added as clarification,
where the parenthesis indicate the substring matching the regex):
4, [85,77,71] [[85],[85,77,71]]
(1010101) 1001101 1000111; 101010(1 1001101 100011)1
2, [109,45] [[109],[109],[109,45],[109],[109,45],[45],[45]]
(11011)01 101101; 1(101)101 101101; 110(1101 1)01101; 1101(101) 101101; 110110(1 1011)01; 1101101 (101)101; 1101101 101(101)
3, [990,1,3,3023,15,21] [[990,1,3,3023],[990,1,3,3023],[1,3,3023],[21]]
(1111011110 1 11 1)01111001111 1111 10101; 11110(11110 1 11 101111)001111 1111 10101; 1111011110 (1 11 101111001111) 1111 10101; 1111011110 1 11 101111001111 1111 (10101)
2, [1,2,3,4,5,6,7,8,9,10] [[1,2,3],[2,3],[4,5],[5],[5,6,7],[6,7],[6,7],[8,9],[9],[10]]
(1 10 11) 100 101 110 111 1000 1001 1010; 1 (10 1)1 100 101 110 111 1000 1001 1010; 1 10 11 (100 1)01 110 111 1000 1001 1010; 1 10 11 100 (101) 110 111 1000 1001 1010; 1 10 11 100 10(1 110 111) 1000 1001 1010; 1 10 11 100 101 (110 11)1 1000 1001 1010; 1 10 11 100 101 1(10 1)11 1000 1001 1010; 1 10 11 100 101 110 111 (1000 1)001 1010; 1 10 11 100 101 110 111 1000 (1001) 1010; 1 10 11 100 101 110 111 1000 1001 (101)0
3, [1,2,3,4,5,6,7,8,9,10] [[4,5],[8,9]]
1 10 11 (100 101 )110 111 1000 1001 1010; 1 10 11 100 101 110 111 (1000 1001) 1010
10, [1,2,3,4,5,6,7,8,9,10] []
No binary fences are possible for this input
6, [445873,2075] [[445873,2075],[445873,2075],[445873,2075]]
(1101100110110110001 1)00000011011; 110(1100110110110001 100000011)011; 1101100(110110110001 100000011011)
2, [8127] [[8127],[8127],[8127],[8127],[8127],[8127]]
(1111110111111); 1(11111011111)1; 11(111101111)11; 111(1110111)111; 1111(11011)1111; 11111(101)11111
2, [10,10] [[10],[10,10],[10]]
(101)0 1010; 10(10 1)010; 1010 (101)0
4, [10,10,10] [[10,10],[10,10,10],[10,10]]
(1010 101)0 1010; 10(10 1010 1)010; 1010 (1010 101)0
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~114~~ ~~112~~ ~~110~~ ~~107~~ ~~106~~ 104 bytes
```
->\n,\L{L[map {[...] flat(^L Zxx(L>>.msb X+1))[.from,.to-1]},L.fmt('%b','')~~m:ov/(1+)<{"0+$0"x n-1}>/]}
```
[Try it online!](https://tio.run/##JYzbCoJAFEXf/YpDVM7gcZzxktnFL5gPiNTCoHlyNExCMf11E4P9sjaL9XrWxW7SHWwVnCc7TktMZS8Tnb@gTxhjGagib8hNwrVtiYxjpt8PuFiC0oSputLImsoW2YCSKd0Qc/Mw0TTpOOpD9XGIsOipX3FrzVctlLYYYicbpnfegSLf9Z2CqmqD@AhkH2AYYjiH0SDufAgeoR8s6M0YRRwFeuhx10MRoPs3/cXEZZQepx8 "Perl 6 – Try It Online")
### Explanation
```
->\n,\L{ # Anonymous block taking arguments n and L
L[ # Return elements of L
map { # Map matches to ranges
[...] # Create range from start/end pair
# Map indices into binary string to indices into L
flat( # Flatten
^L # indices into L
Zxx # repeated times
(L>>.msb X+1) # length of each binary representation
)
# Lookup start/end pair in map above
[.from,.to-1]
},
L.fmt('%b','') # Join binary representations
~~ # Regex match
m:ov/(1+)<{"0+$0"x n-1}>/ # Find overlapping matches
]
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 33 bytes
```
ṠṘmȯF-mȯ#öΛΛ=⁰Fzż+C2gQṁḋmëhohttIQ
```
[Try it online!](https://tio.run/##AUQAu/9odXNr///huaDhuZhtyK9GLW3IryPDts6bzps94oGwRnrFvCtDMmdR4bmB4biLbcOraG9odHRJUf///zL/WzEwLDEwXQ "Husk – Try It Online")
Passes all test cases.
This was a difficult challenge and my solution feels somewhat convoluted.
## Explanation
The program loops through the slices of the input, and repeats each as many times as it contains a match of the regex.
We want to count only those matches that overlap the binary expansion of every number in the slice.
This seems difficult, but it's easier to count those matches that do not use the first number: just remove that number and count all matches.
To get the good matches, we thus count all matches, then subtract the number of matches that don't use the first number, and those that don't use last number.
The matches that use neither are counted twice, so we must add them back to get the correct result.
Counting the number of matches in a slice is a matter of concatenating the binary expansions and looping over the slices of the result.
Since Husk has no support for regexes, we use list manipulation to recognize a match.
The function `g` splits a slice to groups of equal adjacent elements.
Then we must verify the following:
1. The first group is a 1-group.
2. The number of groups is odd.
3. The number of 1-groups is equal to the first input `n`.
4. The 1-groups have equal lengths.
First we cut the groups into pairs.
If 1 and 2 hold, then the first group of each pair is a 1-group and the last pair is a singleton.
Then we reduce this list of pairs by zipping them with componentwise addition.
This means that the 1-groups and 0-groups are added separately.
The addition preserves overflowing elements, so adding `[1,1,1]` and `[1,1]` gives `[2,2,1]`.
Zipping does not, so if the last pair is a singleton, the componentwise sum of the 0-groups vanishes from the result.
Finally, we check that all numbers in the result are equal to `n`.
```
ṠṘm(...)Q First input is explicit, say 3, second is implicit.
Q List of slices.
m(...) Map this function (which counts good matches) over the slices
ṠṘ and replicate each by the corresponding number.
F-m(...)mëhohttI Count good matches. Argument is a slice, say [6,2,5].
ë Define a list of 4 functions:
h remove first element,
oht remove first and last element,
t remove last element,
I identity.
m Apply each: [[2,5],[2],[6,2],[6,2,5]]
m(...) Map function (which counts all matches): [0,0,1,2]
F- Reduce by subtraction: 1
In Husk, - has reversed arguments, so this computes
M(x) - (M(tx) - (M(htx) - M(hx)))
where M means number of matches.
#(...)Qṁḋ Count all matches. Argument is a slice.
ṁ Map and concatenate
ḋ binary expansions.
Q List of slices.
#(...) Count number of truthy results of function (which recognizes a match).
ΛΛ=⁰Fzż+C2g Recognize a match. Argument is list of bits, say [1,1,0,1,1,0,0,0,1,1].
g Group elements: [[1,1],[0],[1,1],[0,0,0],[1,1]]
C2 Cut into pairs: [[[1,1],[0]],[[1,1],[0,0,0]],[[1,1]]]
F Reduce by
z zip (discarding extraneous elements) with
ż zip (preserving extraneous elements) with
+ addition: [[3,3]]
Λ For all lists
Λ all elements
=⁰ are equal to first input.
```
[Answer]
# JavaScript (ES6), ~~187~~ ~~184~~ ~~177~~ 173 bytes
Takes input as `(n)(list)`. Returns an array of arrays.
```
n=>a=>(g=p=>(m=s.slice(p).match(`(1+)(0+\\1){${n-1}}`))?[a.filter((_,i)=>-~b[i-1]<p+m[0].length&b[i]>=p,p-=~m.index),...g(p)]:[])(s=[],b=a.map(n=>(s+=n.toString(2)).length))
```
[Try it online!](https://tio.run/##jZLfb4IwEMff91fwsCxtPCrlh@Cyuvc9bA97xGaiArIgECHLFqP/ursyf3QuE0l6bbnr53vX3nv0EdWzVVY1ZlHO410idoUYRWJEUlGhXYqa1Xk2i0lF2TJqZgsyIbxHidUbjzld364Lk282E0ofw4glWd7EK0LeIKNiZG6nYWZy@VD1lqElWR4XabO4w59yJCqoTLFdsqyYx58UGGMpSsj7UFJSi1DCVEQoWBFMh9Q9UbCmfG1WWZESm9I9i9LdrCzqMo9ZXqbk6fXlmdVtUJZ8kYQYLiVh4IHvg8@loX2UUqPfN0L0SjiFyJvLPBt53BqC6/2iaTz0IvBoVeSf7cF0qTmoNhxawMEBx7Id4B7Yqo6jmu5F5tlWW9pX1gY2nnHBgwH4EMAQuCVPtSmvgrUWo9C2Q0XjrFs8qxJqy76q0MvSP2IK2sHiVherK5kBAlzXC3wHbMvXHvqUjOaFC7trbjzgtn/WS3p3Ki90T9f1rboF49@@bZ8K9nMn0T0Qz6EaEU5QbSnl7hs "JavaScript (Node.js) – Try It Online")
### How?
We first compute the binary string \$s\$ and a list \$b\$ that describes the bounds of each number in \$s\$.
```
s = [], b = a.map(n => (s += n.toString(2)).length)
```
*Example:*
```
(0) 7 13
v v v
a = [109, 45] --> s = "1101101101101" --> b = [7, 13]
\_____/\____/
109 45
```
We use the following template to generate a regular expression matching binary fences:
```
`(1+)(0+\\1){${n-1}}`
```
This regular expression is applied to \$s\$, starting from a position \$p\$.
```
m = s.slice(p).match(`(1+)(0+\\1){${n-1}}`)
```
We start with \$p=0\$ and update it at each iteration according to the position of the previous match.
Whenever a match \$m\$ is found in \$s\$: for each \$i\$-th number in the input array, we test whether the interval made of its bounds (stored in \$b\$) overlaps the interval made of the starting and ending positions of \$m\$ in \$s\$.
```
a.filter((_, i) => -~b[i - 1] < p + m[0].length & b[i] >= p, p -= ~m.index)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~271~~ ~~246~~ ~~223~~ ~~214~~ ~~208~~ ~~202~~ ~~200~~ 195 bytes
```
lambda n,l,R=range,L=len:sum([next(([l[i:j+1]]for j in R(i,L(l))if re.match('(1+)'+r'(0+\1)'*~-n,('{:b}'*(1+j-i)).format(*l[i:])[o:])),[])for i in R(L(l))for o in R(L(bin(l[i]))-2)],[])
import re
```
[Try it online!](https://tio.run/##hZHfboIwFMbvfYomu6CVo2kLCJj4Bl55W3uBG8waKIaxZMuyvTo7xSn@iyPhlJPv@309tPvPdltb2RWLdVdm1eYlIxZKWC2azL7msFyUuZ2/vVdU2fyjpVSVysx3vtC6qBuyI8aSFTWwpCVjpiBNPq2y9nlLPSp85vmNR7m/Fswb/0wsUO9rvvn2xqjtJoaxKWagnY5dqGaqxsJAaeayzSG7T3Z9few3xlIE0DqRTDv7yFT7umlx927fGNuSgoZAVBJBHEMsNHsiV49CEdGTQ4@OoERQ8BTC6A7mQBSRPFVnvGmPZYgNMDZNOQgIIOAyABGBHCZTFyLCV@3Zp7yZFiSqIUQwgxgSSEHwv2ClUHKjgBuof50J1/OKiNux/4GrkR9mH1IdPUCCP6TU4JyhMQyjJA5A8vjmtNWFCA@6y9NIhIzv3lx/6U6E/xfd/QI "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 182 bytes
```
lambda n,L,b='{:b}'.format:[zip(*set([t
for t in enumerate(L)for _ in b(t[1])][slice(*m.span(1))]))[1]for
m in re.finditer('(?=((1+)'+r'[0]+\2'*~-n+'))',''.join(map(b,L)))]
import re
```
[Try it online!](https://tio.run/##Zc1BboMwEAXQPafwzmOYImyghEioF@AGDqqgMYqr2FjGXbRVe3VqKkVqle37f/6493BZrNjm7rRdRzOdR2Kxx6mjn8fpi@bz4s0YjvJDO0hXFUCGJBoJRFui7JtRfgwKerbj844TBMkHNsj1ql8UpCZf3WiBMzYwFpNYTMxe9CqftT3roDxQeOoAeMZo5qkshuwkaPr9YDPKGEVK89dFWzCjgwl7FqcSbdziQxzZnNc2kBkqJPJQY9NgE/8nNxaRedFiVf/BMmLbFsixxLIQJfIaxd0VihhXWOMjNnjAFnlxN/zfqpv98vYD "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Œεy¨D¦y¦)bJεŒεγ0KDËsgIQyнyθP}}OÆFy,
```
Inspired by [*@Zgarb*'s Husk answer](https://codegolf.stackexchange.com/a/173714/52210).
Output the lists newline-delimited.
[Try it online](https://tio.run/##yy9OTMpM/f//6KRzWysPrXA5tKzy0DLNJK9zW0Ei5zYbeLsc7i5O9wysvLC38tyOgNpa/8NtbpU6//9HW5jqmJvrmBvGcpn819XNy9fNSayqBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4KbkmVdQWmKloGTv6WKvpJCYlwJmhtorWSlw@ZeWQCR1/h@dVFZZeWiFy6FllYeWaSZ5ndt6dNK5rec2G3i7HO4uTo8IrLywt/LcjoDaWv/DbW6VOv9raw9ts/8fbWGqY26uY24Yy2XCFW1oYKljYhrLZcQVbWlpoGOoY6xjbGBkrGNoqmMEVGEMVKFjBBQ00THVMdMx17HQsdQxNACrxy6BU4ehAVe0iYmphbmxjpGBOdBKM65oC0Mjc4hZBnBTQSwwxwQA).
**Explanation:**
```
Œ # Get the sublists of the (implicit) input-list
ε # Loop `y` over each sublist:
# (implicitly push `y`)
y¨ # Push `y` with the last item removed
D¦ # Push `y` with the first and last items removed
y¦ # Push `y` with the first item removed
) # Wrap all four into a list
b # Get the binary-string of each integer
J # Join each inner list together
ε # Map each converted binary-string to:
Œ # Get all substrings of the binary-string
ε # Map each binary substring to:
γ # Split it into chunks of equal adjacent digits
0K # Remove all chunks consisting of 0s
DË # Check if all chunks consisting of 1s are the same
sgIQ # Check if the amount of chunks of 1s is equal to the second input-integer
yн # Check if the substring starts with a 1
yθ # Check if the substring end with a 1
P # Check if all four checks above are truthy for this substring
# (1 if truthy; 0 if falsey)
}} # Close both maps
O # Take the sum of each inner list
Æ # Reduce the list of sums by subtraction
F # Loop that many times:
y, # And print the current sublist `y` with a trailing newline
```
] |
[Question]
[
## Introduction
This is a follow-up of [this challenge](https://codegolf.stackexchange.com/questions/150954/be-as-fair-as-possible) where you're taking the role of that person's evil twin. Being evil you don't want to maximize your share, but rather be as unfair as possible and you're not going to make it too obvious, that's why you came up with the following scheme:
You're going to tell the others that you want to be as fair as possible like your sibling and thus you're going to split the integer into pieces of equal length. So for each integer you will come up with the right amount of people such that the difference between the largest and the smallest piece is maximal.
For example if you're given the integer `6567` you could leave it as is, split it into two pieces `65,67` or four `6,5,6,7`. This gives you the following maximal differences:
```
6567 -> max() = 0
65,67 -> max(|65-67|) = 2
6,5,6,7 -> max(|6-5|,|6-5|,|6-6|,|6-7|,|5-6|,|5-7|,|6-7|) = 2
```
Since you only want to be evil you don't prefer `67` over `7` and thus you will output either `2` or `4`.
---
Another (less special case); given the integer `121131` you could split it like this:
```
121131 -> max() = 0
121,131 -> max(|121-131|) = 10
12,11,31 -> max(|12-11|,|12-31|,|11-31|) = 20
1,2,1,1,3,1 -> max(…) = 2
```
This time there's only one solution - namely `3` - since with three people the difference is maximal.
## Challenge
Given an integer determine *any* possible way of being maximally evil and report the **number of people** needed to achieve this.
## Rules
* Input will always be ≥ 1
* Input can be either an integer, list of digits or string
* You don't have to handle invalid inputs
## Testcases
You only need to report the resulting number of people needed, the possible partitions are only for illustration:
```
In -> splits (difference) -> Out
1 -> [1] (0) -> 1
10 -> [1,0] (1) -> 2
11 -> [11] or [1,1] (0) -> 1 or 2
12 -> [1,2] (1) -> 2
42 -> [4,2] (2) -> 2
101 -> [1,0,1] (1) -> 3
2222 -> [2222] or [22,22] or [2,2,2,2] (0) -> 1 or 2 or 4
6567 -> [65,67] or [6,5,6,7] (2) -> 2 or 4
123000 -> [123,000] (123) -> 2
123001 -> [123,001] (122) -> 2
121131 -> [12,11,31] (20) -> 3
294884 -> [294,884] (590) -> 2
192884729 -> [192,884,729] (692) -> 3
123456189012 -> [123456,189012] (65556) -> 2
123457117346 -> [1234,5711,7346] (6112) -> 3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṁ_Ṃ
sLÆD$ḌÇÞṪL
```
A monadic link taking a list of integers (the digits) and returning an integer.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4bmAX@G5ggpzTMOGRCThuIzDh8Oe4bmqTP///1sxLDFd "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8///hzob4hzubuIp9Dre5qDzc0XO4/fC8hztX@fx3OdzOdXTP4fZHTWvc//@PNtQxNNAxBJJGOiZGQLahjhEQ6JiZmpkDxYwNDAwgFEiFoaExUNrSxMLCRMfQ0ghImRtZgqRNTM0MLSwNgGaAOeaGhubGJmaxAA "Jelly – Try It Online")
### How?
```
Ṁ_Ṃ - Link 1, maximal difference: list of numbers
Ṁ - maximum
Ṃ - minimum
_ - subtract
sLÆD$ḌÇÞṪL - Main link: list of numbers, theDigits e.g. [1,2,3,0,0,1]
$ - last two links as a monad:
L - length 6
ÆD - divisors [1,2,3,6]
s - split into chunks (vectorises) [[[1],[2],[3],[0],[0],[1]],[[1,2],[3,0],[0,1]],[[1,2,3],[0,0,1]],[[1,2,3,0,0,1]]]
Ḍ - from decimal (vectorises) [[1,2,3,0,0,1],[12,30,1],[123,1],[123001]]
Þ - sort by:
Ç - call last link (1) as a monad 3 29 122 0
- ... [[123001],[1,2,3,0,0,1],[12,30,1],[123,1]]
Ṫ - tail [123,1]
L - length 2
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
leoeSaM^N2vcRQ*M{yPl
```
**[Try it here!](https://pyth.herokuapp.com/?code=leoeSaM%5EN2vcRQ%2aM%7ByPl&input=%22121131%22&debug=0)**
I no longer use partitions, because it turns out to be longer!!! I ended up splitting into sublists of length equal to the divisors of the length.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
gDÑΣôDδαà}θ÷
```
[Try it online!](https://tio.run/##ASoA1f8wNWFiMWX//2dEw5HOo8O0RM60zrHDoH3OuMO3//8xMjM0NTYxODkwMTI "05AB1E – Try It Online")
### [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
gDÑΣôàsß-}θ÷
```
[Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//2dEw5HOo8O0w6Bzw58tfc64w7f//zEyMzQ1NjE4OTAxMg "05AB1E – Try It Online")
### How it works
```
gDÑΣôDδαà}θ÷ | Full program.
g | Length (count of digits).
D | Duplicate (push two copies of the length to the stack).
Ñ | Get the divisors (of the top of the stack).
Σ } | Sort by a key function.
--------------------------------------------------------------
ôDδαà | Key function #1.
ô | Split (the input) into chunks of that size.
D | Duplicate.
δα | Outer product of absolute difference.
à | Get the maximum.
ôàsß- | Key function #2 (alternative).
ô | Split (the input) into chunks of that size.
à | Maximum.
s | Swap top two elements.
ß | Minimum.
- | Subtract.
--------------------------------------------------------------
θ÷ | Divide the length by the maximum element using the custom sorting.
```
05AB1E is just incredibly terse for this challenge.
[Answer]
# JavaScript (ES6), ~~118~~ 115 bytes
*Saved 3 bytes thanks to @edc65*
Takes input as a string.
```
f=(s,k=l=s.length,m)=>k?f(s,k-1,l%k||(d=Math.max(...a=s.match(eval(`/.{${l/k}}/g`)))-Math.min(...a))<m?m:(r=k,d)):r
```
### Test cases
```
f=(s,k=l=s.length,m)=>k?f(s,k-1,l%k||(d=Math.max(...a=s.match(eval(`/.{${l/k}}/g`)))-Math.min(...a))<m?m:(r=k,d)):r
console.log(f('1')) // [1] (0) -> 1
console.log(f('10')) // [1,0] (1) -> 2
console.log(f('11')) // [11] or [1,1] (0) -> 1 or 2
console.log(f('12')) // [1,2] (1) -> 2
console.log(f('42')) // [4,2] (2) -> 2
console.log(f('101')) // [1,0,1] (1) -> 3
console.log(f('2222')) // [2222] or [22,22] or [2,2,2,2] (0) -> 1 or 2 or 4
console.log(f('6567')) // [65,67] or [6,5,6,7] (2) -> 2 or 4
console.log(f('123000')) // [123,0] (123) -> 2
console.log(f('123001')) // [123,1] (122) -> 2
console.log(f('121131')) // [12,11,31] (20) -> 3
console.log(f('294884')) // [294,884] (590) -> 2
console.log(f('192884729')) // [192,884,729] (692) -> 3
console.log(f('123456189012')) // [123456,189012] (65556) -> 2
console.log(f('123457117346')) // [1234,5711,7346] (6112) -> 3
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ 132 bytes
```
n=input()
l=len(n)
print len(max([[int(n[l/i*j:][:l/i])for j in range(i)]for i in range(1,l+1)if l%i<1],key=lambda a:max(a)-min(a)))
```
[Try it online!](https://tio.run/##RU5LasMwEN3rFEJQkNqUamTFP@pbdGe8UBOlmVQeG@PQ5PSupFA6i/ebxzDzfT1PZLbDdPSdEGKjDmm@rlKx0AVPkhSbF6SVJzO6m@z76CT14Q2fL@3Qt1EM6jQt/MKR@OLoy0tUQ0rwP4FdeAGFJx6e8B2G3be/d8GNn0fHXZvuOvU6IkVSaouPsJ8zBs8/lqtvGef@5g88PbkJEEyATpCViWBNzpI3cSKV@7LK20Jr/ScefYAiFxtb1zYljYmiMs2jZvcl1I3Od7OtAKrCluIX "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 114 bytes
```
f n|l<-length n=snd$maximum[(a-b,div l i)|i<-[1..l],mod l i<1,a<-i%n,b<-i%n]
i%[]=[]
i%n=read(take i n):i%drop i n
```
[Try it online!](https://tio.run/##XZDfboIwFMbveYrGaKLJwfQcSpFFd7@rPQDxgg3YmkE1iMuSbc/uelpQM0jo4fd951/fy9NH3baXSyPsT7uN29q@De/C7k62mnfll@nOXbEs4xeozKdohVn9mG1c4Hrd7qE7VIy2COU2NgsLL/7YR2ZR7HcFn3bX12W1HMqPWhhhVw9mUfWHI8eXrjRW7MSxN3YQc9GIGRJigrPoO46erIgfxenYmuEklpVpmrqv7Wu9Yvx8HiLkoMC9WErPMEIZEEgH0UOKcPQ546Fn8S6DiXPQmEZ3aSpA5SFNtSROHXyZYE4ico8XOAh9iOAagn//teWPinSqM5@pU9BZ8GtwMWS3vsGKlEg5bkgJuJgnoGSajWW8k/2AdB3d3@woAyIkrJOcNsjVZqPCDrkCFzs1zeWUnZNDGeWhQE7sAPfvXDqnsYjrq1KNm1xOV@oBBMLWNE31bV6VZohZovTVDEyAEbsRp8rx7@UP "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
```
s%.%/A/g;/$/,map$;[$-=$`-$_]=@1,@1for@1=(/.{@{+}}/gc)x!/./g%eg;$_=pop@
```
[Try it online!](https://tio.run/##NUrdSsMwGL3PU8QtBcU1yZemf4RKfABv3KXI7GZaCrMNTYqOsVc3ZgzPgfPDOdbMxzy49rRaDR2hT6DwGm@NbefWGzwt3i4e7094NN/HYTQOLeOn6bRS@Io1fjXOeOx8fAeX0IQ9s14xwjZfrSXqjaQN@UjJ7r3RsNHQTbOG5p7Rsz4/Xi6sPzz83DHK@sT0iuwaO1kdQpEXJQIBkAGK5AiiCiRFzIBERKwZ5/xm8P8VtawqiaAW0UpRX2eZF1DVHMStlABlJgv0O1k/TKMLqQ3pS06BU/4H "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ŒṖL€E$ÐfḌạþ`ẎṀ$$ÐṀḢL
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p/k8alrjqnJ4QtrDHT0Pdy08vC/h4a6@hzsbVIBiQOrhjkU@////NzQyNjE1NzQ0NzYxAwA "Jelly – Try It Online")
] |
[Question]
[
Given an email address, the result of a transformation applied to that email address, and a second email address, return the output of the same transformation applied to the second email address.
The email addresses will all have the following structure:
A string of positive length containing alphanumeric characters and at most one `.` (the local part), followed by an `@` symbol, followed by a string of positive length containing alphanumeric sumbols (the domain), followed by a `.` symbol, and a final string of positive length containing alphanumeric characters (the TLD).
There are four allowed transformations:
* Identity (no change). (`[[email protected]](/cdn-cgi/l/email-protection) -> [[email protected]](/cdn-cgi/l/email-protection)`)
* Returning just the local part (everything before the `@`) unmodified (`[[email protected]](/cdn-cgi/l/email-protection) -> a.b`).
* Returning the local part split on the `.` if present, with the first symbol of each half capitalised. (`[[email protected]](/cdn-cgi/l/email-protection) -> A B`).
* Returning just the domain (everything between the `@` and the final `.`) unmodified. (`[[email protected]](/cdn-cgi/l/email-protection) -> c`).
When more than one transformation is possible, you can give the output of any of the possibilities. Whitespace at the start and end of output don't matter, but in the middle does (i.e. if you split `a.b` to `A B` there should be just one space in the middle [and any number at the start and end of output], but if you split `a.`, then `A` with any number of spaces on either side are all acceptable).
Examples (`input | output`):
```
[[email protected]](/cdn-cgi/l/email-protection), John Doe, [[email protected]](/cdn-cgi/l/email-protection) | Phillip Maini
[[email protected]](/cdn-cgi/l/email-protection), John Doe, [[email protected]](/cdn-cgi/l/email-protection) | Phillip Maini
[[email protected]](/cdn-cgi/l/email-protection), foo.bar, [[email protected]](/cdn-cgi/l/email-protection) | gee.whizz
[[email protected]](/cdn-cgi/l/email-protection), foo.bar, [[email protected]](/cdn-cgi/l/email-protection) | gEe.Whizz
[[email protected]](/cdn-cgi/l/email-protection), comedy, [[email protected]](/cdn-cgi/l/email-protection) | office
[[email protected]](/cdn-cgi/l/email-protection), Jones, [[email protected]](/cdn-cgi/l/email-protection) | A
[[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection) | [[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection), .jones, [[email protected]](/cdn-cgi/l/email-protection) | a.
[[email protected]](/cdn-cgi/l/email-protection), x, [[email protected]](/cdn-cgi/l/email-protection) | 3
[[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection) | [[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection), John Jones, [[email protected]](/cdn-cgi/l/email-protection) | 1in Thehand
[[email protected]](/cdn-cgi/l/email-protection), Chicken Soup, [[email protected]](/cdn-cgi/l/email-protection) | Fab
[[email protected]](/cdn-cgi/l/email-protection), lange, [[email protected]](/cdn-cgi/l/email-protection) | fat.so
[[email protected]](/cdn-cgi/l/email-protection), Lange, [[email protected]](/cdn-cgi/l/email-protection) | {fat.so, Fat So} # either acceptable
[[email protected]](/cdn-cgi/l/email-protection), chicken, [[email protected]](/cdn-cgi/l/email-protection) | {horse, pig} # either acceptable
```
Usual rules and loopholes apply.
[Answer]
# Java 8, ~~254~~ ~~240~~ 236 bytes
```
(a,b,c)->{String A[]=a.split("@"),C[]=c.split("@"),x="";for(String p:C[0].split("\\."))x+=(p.charAt(0)+"").toUpperCase()+p.substring(1)+" ";return a.equals(b)?c:A[0].equals(b)?C[0]:A[1].split("\\.")[0].equals(b)?C[1].split("\\.")[0]:x;}
```
-4 bytes thanks to *@LukeStevens*.
**Explanation:**
[Try it here.](https://tio.run/##rZNPbxoxEMXv@RTWnnYFGUFyA9EakV6qJKoUVT0QDl6vFxuM7ay9KRDx2am9fwhJ1SLSSqAdv533G3l4LMgzudSGqUW23FNJrEV3RKiXC4SEcqzICWXoPhwRenCFUHNE46Yg3VZKDxVNhr5357/@Yx1xgqJ7pNAI7WPSTbs0ufz00vSOp7MRAWukcHGEo6Q78QI9FtajKBrmumgnmsFk2pu1HY@PECXJujOKDVBOirGLe0knihJw@rsxrJgQy@KkY8CWqa0Icd83oGhYMFcWChFgTyWRNk6Tz3QwDuxXIYzyWv/tvPc9v78erIe7/bDegClT6TfQLOJZiwyt/Hqb@0xniCTNbjfWsRXo0oHxr5xUsQIaRwvNFWSa4bn3SaB6FXVR9NWr6EazUBsupBQGAlcctSXVL/FncmDAzd/I3xry3ZnkXGtISYG5dsfoRg7lnDH4ycV2i71Zar38X9wvDH6czS10ptgGMqLmPvCCyQx7G8s2oJgL2PoUqpXwQWMSLNXOYZ3ngjLonZwAC62YxWvo1zv2h1AQwNewPdP99vQPiA/b1@c4cQq0mtkWfXwF1yd9Ve7rqTnkh2QeVtcXChxnnKgMX3kfZ5CWlp/kUi7okimwujT4yV/Asya1hh68VgWKpLiUugR7EidDZjAnpAgx8N5KqCHOD8HhEVJ0CnT7HnT7QVBzQdxetHlWMX4tuS4sw0bMISdF@w/ZXez2vwA)
```
(a,b,c)->{ // Method with three String parameters and String return-type
String A[]=a.split("@"), // Split `a` by "@" into two parts
C[]=c.split("@"), // Split `c` by "@" into two parts
x=""; // Temp-String
for(String p:C[0].split("\\."))
// Loop over the first part of `c`, split by dots
x+= // Append String `x` with:
(p.charAt(0)+"").toUpperCase()
// The first character as uppercase
+p.substring(1) // + the rest of the String
+" "; // + a space
// End of loop (implicit / single-line body)
return a.equals(b)? // If input `a` and `b` are exactly the same:
c // Return `c`
:A[0].equals(b)? // Else-if the first part of `a` equals `b`:
C[0] // Return the first part of `c`
:A[1].split("\\.)[0].equals(b)?
// Else-if the domain of `a` equals `b`
C[1].split("\\.)[0] // Return the domain of `c`
: // Else:
x; // Return String `x`
} // End of method
```
[Answer]
# [Haskell](https://www.haskell.org/), 208 bytes
```
import Data.Char
s c""=[]
s c a=w:f t where
(w,t)=span(/=c)a
f(_:y)=s c y
f _=[]
h=head
u""=""
u(x:y)=toUpper x:y
l=h.s '@'
f x y=h[t|t<-[id,l,unwords.filter(/="").map u.s '.'.l,h.s '.'.last.s '@'],t x==y]
```
[Try it online!](https://tio.run/##TZBBb9wgEIXv/IonX9aWCFF6XJUqUnPqJYduT@4qGtk40LBAAWttqf99O95023J68@abN4Cl8ma8v7hTirni50zeTc6MeKJK6mCWCio43PpX97OlLAqGptH9cRMgfd5PqDhbk41Ae5a10yVRaO/10JHA1L7sV7aYXbnCyzZptTU0iplzmkbM7bIhNX5LyWRwIby2qmD3uBMTFqza9vVX/XjXu1F6OYdzzGNRk/PVZF7UNJ06UcK8zaid8tLeFJX6HnSUFYvW6/FSknf1OWC/x9eaXXjF3af/VP8u@Xl/uGISZaoxQ2PbclBzSDS8QbG8Qe1BXb2/cHdtb54QJ3KBh8cowMcFvjUNFe1374LZdnpT0S8PEqvE8uHI7C23kWhwxTiC/@IBKxPd5Ue0QY3RPL5yuFdDPEl8YQ9P0Ugk67x3SW2L3T/kNw "Haskell – Try It Online")
It is sad I had to spend 59 bytes on reinventing `split` (`s`).
The solution creates a list of transformations and returns the first one that leads to the expected result.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Pre-emptive thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for noticing the failure of using `Œt` (title-case) and hence `Œu1¦€K` over `ŒtK`
-1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (rearrangement of `⁵⁸ç⁹¤Ŀ` to `çµ⁵⁸Ŀ`)
```
ÑṪṣ”.Ḣ
ṣ”@
ÇḢ
Çṣ”.Œu1¦€K
⁹ĿðЀ5i
çµ⁵⁸Ŀ
```
A full program taking `exampleEmail`, `exampleOutput`, `realEmail` and printing the result.
**[Try it online!](https://tio.run/##y0rNyan8/5/r8MSHO1c93Ln4UcNcvYc7FnFBmA5ch9tBPCAJkTo6qdTw0LJHTWu8uR417jyy//CGwxOAPNNMIHfro8Ydh5cDhQ8tObL/////Smn5@XpJiUUOGfkluYmZOXrJ@blKcFEgK901VS88I7OqyiG/tCQnPz8brAIA "Jelly – Try It Online")**
### How?
Performs all four transforms (plus a precursor one), finds the first one that yields the example from the first email, then applies it to the second email:
```
- Link 1, do nothing: email
- do nothing but return the input
ÑṪṣ”.Ḣ - Link 2, the domain: email
Ñ - call the next link (3) as a monad (split at "@")
Ṫ - tail
ṣ”. - split at "."
Ḣ - head
ṣ”@ - Link 3, split at @: email
ṣ”@ - split at "@"
ÇḢ - Link 4, local part: email
Ç - call the last link (3) as a monad (split at "@")
Ḣ - head
Çṣ”.Œu1¦€K - Link 5, name-ified: email
Ç - call the last link (4) as a monad (get the local part)
ṣ”. - split at "."
¦€ - for €ach sparsley apply:
1 - ...to index: 1
Œu - ...action: uppercase
K - join with space(s)
⁹ĿðЀ5i - Link 6, index of first correct link: exampleEmail; exampleOutput
Ѐ5 - map across (implicit range of) 5 (i.e. for each n in [1,2,3,4,5]):
ð - dyadicly (i.e. with n on the right and exampleEmail on the left):
Ŀ - call referenced link as a monad:
⁹ - ...reference: chain's right argument, n
i - first index of exampleOutput in the resulting list
çµ⁵⁸Ŀ - Main link: exampleEmail; exampleOutput
ç - call the last link (6) as a dyad (get the first "correct" link index)
µ - monadic chain separation (call that L)
⁸ - chain's left argument, L
Ŀ - call the link at that reference as a monad with input:
⁵ - program's third input, realEmail
```
Notes:
1. Assumes the input exampleOutput is strictly the same as the output would be.
2. The "precursor" (the result of link 3) is tested for matching the `exampleOutput`, but it won't match unless the `exampleOutput` itself is a list of lists of characters. As such the inputs should probably be quoted (Python formatting may be used here) to avoid the possibility of interpreting it as such.
[Answer]
# [Python 2](https://docs.python.org/2/), 135 bytes
```
s,r,x=input()
def f(x):S,D=x.split('@');return x,S,' '.join(map(str.capitalize,S.split('.'))),D.split('.')[0]
print f(x)[f(s).index(r)]
```
[Try it online!](https://tio.run/##lZLBbhshEIbvfoq9wVarUeyol1aWkOpcolSq5EMPUQ6YHQwJBgKsuvbLu4Dt1IksRz3xz8z/wWgGv03K2dkeRxSEkH3sQjfOtfVDou2kR9lIOrbflt1iPkL0RidKGGm/B0xDsM3YLTvSEHh22tIN9zSmAIJ7nbjRO@yWJwZI27bd4ix8vHma@KBtqi88Shpb0LbHkYb2aZ97@TL9uqfk2SkLvUO23nBtQLgN6Rpyn7PNwmHRXmljtIdct/rM1k5o9cHiGv3rSP@8QEvnYMUDUy6d48d0kWtE@KP0bsfckIxzL//D3iH8vsgG11vcQs/tGoPUaHqWS9hvwWIq6CEqaqOF4mggCpcSc1JqgXBTb8lLsRjZCNNibO5LVBQHdgu7C5b30Se2q5bxY5WtQFT2JKZsBre1Vhd8oCXIt/W8tTvVFpJCxW3PZvm7KITVEFVlhdLiBS1EN3j2mh/L/h@HXLPMuTpxvmKDcQPEipgyVKY4D2VOuV4TB2PKF7FylDEX88NH88MV87EZdmrqeNZ9/ZPKhYjM6zVIHvK6/wI "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 145 bytes
Invoke with currying syntax, e.g. `f('[[email protected]](/cdn-cgi/l/email-protection)')('Chicken Soup')('[[email protected]](/cdn-cgi/l/email-protection)')`
```
x=>y=>[x=>x,s=x=>x.split`@`[0],x=>s(x).split`.`.map(w=>w&&w[0].toUpperCase()+w.slice(1)).join` `.trim(),x=>/@(.+)\./.exec(x)[1]].find(f=>f(x)==y)
```
```
f=x=>y=>[x=>x,s=x=>x.split`@`[0],x=>s(x).split`.`.map(w=>w&&w[0].toUpperCase()+w.slice(1)).join` `.trim(),x=>/@(.+)\./.exec(x)[1]].find(f=>f(x)==y)
for(const [x, y, z] of [
['[[email protected]](/cdn-cgi/l/email-protection)', 'John Doe', '[[email protected]](/cdn-cgi/l/email-protection)'], // Phillip Maini
['[[email protected]](/cdn-cgi/l/email-protection)', 'John Doe', '[[email protected]](/cdn-cgi/l/email-protection)'], // Phillip Maini
['[[email protected]](/cdn-cgi/l/email-protection)', 'foo.bar', '[[email protected]](/cdn-cgi/l/email-protection)'], // gee.whizz
['[[email protected]](/cdn-cgi/l/email-protection)', 'foo.bar', '[[email protected]](/cdn-cgi/l/email-protection)'], // gEe.Whizz
['[[email protected]](/cdn-cgi/l/email-protection)', 'comedy', '[[email protected]](/cdn-cgi/l/email-protection)'], // office
['[[email protected]](/cdn-cgi/l/email-protection)', 'Jones', '[[email protected]](/cdn-cgi/l/email-protection)'], // A
['[[email protected]](/cdn-cgi/l/email-protection)', '[[email protected]](/cdn-cgi/l/email-protection)', '[[email protected]](/cdn-cgi/l/email-protection)'], // [[email protected]](/cdn-cgi/l/email-protection)
['[[email protected]](/cdn-cgi/l/email-protection)', '.jones', '[[email protected]](/cdn-cgi/l/email-protection)'], // a.
['[[email protected]](/cdn-cgi/l/email-protection)', 'x', '[[email protected]](/cdn-cgi/l/email-protection)'], // 3
['[[email protected]](/cdn-cgi/l/email-protection)', '[[email protected]](/cdn-cgi/l/email-protection)', '[[email protected]](/cdn-cgi/l/email-protection)'], // [[email protected]](/cdn-cgi/l/email-protection)
['[[email protected]](/cdn-cgi/l/email-protection)', 'John Jones', '[[email protected]](/cdn-cgi/l/email-protection)'], // 1in Thehand
['[[email protected]](/cdn-cgi/l/email-protection)', 'Chicken Soup', '[[email protected]](/cdn-cgi/l/email-protection)'], // Fab
['[[email protected]](/cdn-cgi/l/email-protection)', 'lange', '[[email protected]](/cdn-cgi/l/email-protection)'], // fat.so
['[[email protected]](/cdn-cgi/l/email-protection)', 'Lange', '[[email protected]](/cdn-cgi/l/email-protection)'], // {fat.so, Fat So} # either acceptable
['[[email protected]](/cdn-cgi/l/email-protection)', 'chicken', '[[email protected]](/cdn-cgi/l/email-protection)'], // {horse, pig} # either acceptable
]) console.log( f(x)(y)(z) )
```
[Answer]
# Mathematica, 217 bytes
```
(L=Capitalize;T@x_:=(M=StringSplit)[x,"@"];P@x_:=#&@@T[x];W@x_:=If[StringContainsQ[P@x,"."],StringRiffle@L@M[P@x,"."],L@P@x];Z@x_:=#&@@M[T[x][[2]],"."];If[#==#2,#3,If[#2==P@#,P@#3,If[#2==W@#,W@#3,If[#2==Z@#,Z@#3]]]])&
```
[Try it online!](https://tio.run/##TY1RC4IwFIX/imwgBcMHfWsMLvgUKFgGQmPEElcjU8sJ0p@3m0J14cD97jmce9fuWt21s6WejCe8aZWIWHfW6dq@Kn6A8bQRq1Tk7mmbS97V1q3lyAgQxbPZpD7AQY6KFzNujVyycds4bZt@JzHHSEAUW4y9NaauIIH05ySAq@LHb2MqP51ShkrNCY69VAgaMhqxzx4KkQFlqC8XyMUfH5FRkcJZ@1OGz50HRpLyastb1QR9O3TwCF6EkXg5eTmeEI0@w1C3Q9ATNb0B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~117~~ ~~106~~ 102 bytes
```
->a,b,c{r=[/.*/,/(?<=@)\w*/,/[^@]*/].find{|x|r=c[x];a[x]==b}?r:r.sub(?.," ").gsub(/\b(.)/){$1.upcase}}
```
[Try it online!](https://tio.run/##lZFNb9QwEIbv/RVRxGF3FSZsewPCWqJcUJGQOHBIg2Q749ht1g5OrO7nb9/a8bYUWC3iEr8z8z72ZMY6tj6I4vD6A81Yxre2KHOY5Vk@WbwvyPT2IejyB6lmeQVC6Xq7W@1swctV9Y76T1Gw/cK@tdA7NllAlibpFJoQ5LdsAtN8un01B9dx2uN@fygvyvTOSA21QdIsqWqBm2WaJelnn02uDQbdSdW2qgNf1@qFrco8HoxwfQ7/esS/nMKFMcCoJdIML/ljOsgGER6k2myIcUNrzP1/wZ8Qvp@Grak1rqGmukErFLY18TWs16BxCGyMgloqLim20HMzDMQIoTjCm3gN3BmNPVnBPP63D4KgQK5gc8rye/Qv33nP6q8yYcBH@knMySVcxeK46cgLEM9reu55rjQMEiXVNblU2ktgrpcR5lLxe9TQG9eRn/49D3yMueSbz42Dp4y41jjoI9OG2RJJqQ3j8oYxEZ2Dv4mEI0x7dN/86b455z72Q576Op7j4n5JaWyPpFMNCGr94i8qQMplst3hLunc0CeinGG1PzwC "Ruby – Try It Online")
[Answer]
# CJam, 42
```
q~@{[_\'@/~'./0=\_'.%{(eu\+}%S*]}:T~@a#\T=
```
[Try it online](http://cjam.aditsu.net/#code=q~%40%7B%5B_%5C'%40%2F~'.%2F0%3D%5C_'.%25%7B(eu%5C%2B%7D%25S*%5D%7D%3AT~%40a%23%5CT%3D&input=%22john.doe%40gmail.com%22%20%22John%20Doe%22%20%22phillip.maini%40gmail.com%22)
**Explanation:**
```
q~ read and evaluate the input (given as 3 quoted strings)
@ bring the first string to the top of the stack
{…}:T define a function T that calculates the 4 transformations of a string:
[ begin array
_\ duplicate the string, and swap with the other copy to bring it in the array
(1st transformation)
'@/~ split by '@' and put the 2 pieces on the stack
'./0= split the 2nd piece by '.' and keep the first part
(4th transformation)
\_ swap with the piece before '@' and duplicate it
(2nd transformation)
'.% split by '.', removing the empty pieces
{…}% transform the array of pieces
(eu take out the first character and capitalize it
\+ prepend it back to the rest
S* join the pieces by space
(3rd transformation)
] end array
~ execute the function on the first string
@a bring the 2nd string to the top of the stack, and wrap it in an array
# find the position of this string in the array of transformations
\T bring the 3rd string to the top and call function T
= get the transformation from the array, at the position we found before
```
[Answer]
# PHP 7.1, 176 bytes
```
<?$e=explode;[,$p,$q,$r]=$argv;echo$p==$q?$r:($e('@',$p)[0]==$q?$e('@',$r)[0]:($e('.',$e('@',$p)[1])[0]==$q?$e('.',$e('@',$r)[1])[0]:ucwords(join(' ',$e('.',$e('@',$r)[0])))));
```
[Try it online!](https://tio.run/##VYrNDoJADAZfhUMTIMENXkEiiUcfgXAg0MDKul3Kj/ryriAapYcv6cyYxlh7OAImeDeKKoyzAEwAXQCcJ1BwPcVYNgQmSaA7AkceoOem7lz5WZiv9EN4IWsg5vfX7fNN@yf5K6OxvBFXvXchqT3XWZNtGeb@crG1tlQFt6JFPaRVIdXDqELjIIhre1qUc56VJSUnZNGNiDp9r9TV2A8ssRclXZ9kBkm6tzv9Ag)
# PHP < 7.1, 180 bytes
Versions under 7.1 would need to change the `[,$p,$q,$r]=$argv` to `list(,$p,$q,$r)=$argv`, adding 4 bytes.
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 105 + 1(r flag) = 106 bytes
The first three `s` commands check for the **identity**, **local part** and **domain** transformations respectively. If one transformation matches, then it is applied to the second email address and the following `s` commands will fail due to a lack of the input format.
```
s:^(.*),\1,::
s:(.*)@.*,\1,(.*)@.*:\2:
s:.*@(.*)\..*,\1,.*@(.*)\..*:\2:
s:.*,([^.]*)\.?(.*)@.*:\u\1 \u\2:
```
[Try it online!](https://tio.run/##hVBNT4NAEL3zK3qszXYi9MbFSawXUxMTDx7EJlsY2G1hB1mIbX@8uBRaq9Z4mXnzPjKZsZRMM9O0rQ2XY5hcicgXYejZsBsQJt08wDAKOgEm2BER9OLZeDKI8csSXjvy5pRtIn/kShC27ZqVgYQJs0LqHGIuxL2jRnMmUSqd57oEpxj9ZfA6A8wvZx6HzMOPTMoMK1mh4voUGjiREcG70vs9clPnzJv/E3cEz78SFSeGdpBIk1GVasoTdDQlOzBUix6KQsdKUg425rpGTlMdE1x7sGZDFrfgu1scEhJwBvtz/gz@JV4QticOVxCLvvoYwMw7/L53ppD2P@yX@9pArUhJk2CgjYOwaqzyYqXjDRmw3JT4Bntx2xOjJ0eIVK6wybkB6@XdD1BJWbnjxGFycu2C2DX3D2/xzbK4ZBnW4XHt0MWxK64sYakzSGVVfHBZaza2nVaf)
The **local part split** transformation (last `s` command) is the most expensive to check, in terms of bytes, therefore I placed it at the end and assumed it matches (since the other ones failed by that time), going directly to its application.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes
```
ḢŒlṣ”.Œu1¦€K
ṣ”@Wẋ4j”@$ḷ/ÇṪṣ”.Ḣ$$4ƭ€
Çiị⁵Ǥ
```
[Try it online!](https://tio.run/##y0rNyan8///hjkVHJ@U83Ln4UcNcvaOTSg0PLXvUtMabCyLiEP5wV7dJFoil8nDHdv3D7Q93roIqBupUUTE5thaonOtwe@bD3d2PGrcebj@05P///3pZ@XmpxQ4Veob/FbxAzP@Jeg7GelUA "Jelly – Try It Online")
] |
[Question]
[
What general tips do you have for golfing in LOLCODE? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to LOLCODE. (e.g. "remove comments" is not an answer). Please post one tip per answer.
[Answer]
Define variables using the syntax `variable R value` rather than `I HAS A variable ITZ value`.
If you want to set a variable `n` equal to 1,
```
n R 1
```
is only 5 bytes, whereas
```
I HAS A n ITZ 1
```
is 15 bytes.
[Answer]
In many cases it's shorter to read variable values from STDIN rather than defining a function. However, note that `GIMMEH`, which reads input from STDIN, always reads a `YARN` (i.e. string). But you can take advantage of LOLCODE's dynamic typing and add 0 to convert to a `NUMBR`.
For example,
```
GIMMEH n
n R SUM OF n AN 0
... (operations on n)
```
Defining `n` is 26 bytes, including newlines. Compare this to a user-defined function:
```
HOW DUZ I f YR n
... (operations on n)
IF U SAY SO
```
This requires 28 bytes.
Note that you could also multiply by 1 to convert to a `NUMBR`, but that requires 4 more bytes than the sum:
```
GIMMEH n
n R PRODUKT OF n AN 1
```
[Answer]
In many LOLCODE implementations, such as the one on [repl.it](http://repl.it/languages/LOLCODE), `HAI` and `KTHXBYE`, which begin and end programs respectively, are unnecessary. In implementations in which they are necessary, the version number after `HAI` isn't necessary (e.g. `HAI 1.2`).
Similarly, the `STDIO` library is typically loaded by default, so `CAN HAS STDIO?` is also unnecessary.
[Answer]
When printing the value of a variable to STDOUT, consider the following:
```
VISIBLE variable
```
is much shorter than
```
VISIBLE ":{variable}"
```
Also, whenever a trailing newline is acceptable,
```
VISIBLE variable
```
which includes a trailing newline by default, is shorter than
```
VISIBLE variable!
```
which suppresses the newline.
[Answer]
Many operators have optional `AN`s in between them, as defined in the [spec](https://github.com/justinmeza/lolcode-spec). For example:
```
SMOOSH "hello" AN ", world" MKAY
```
can be turned into this:
```
SMOOSH "hello" ", world" MKAY
```
Other operators that support this include `BOTH`, `EITHER`, `WON`, `ALL`, `ANY`, `BOTH SAEM`, and `DIFFRINT`. For some reason, the numerical operators don't allow you to remove the `AN`, though.
The spec also says, specifically for `SMOOSH`, [that](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md#concatenation):
>
> The line ending may safely implicitly close the `SMOOSH` operator without needing an `MKAY`.
>
>
>
Meaning this code should also be valid:
```
SMOOSH "hello" ", world"
```
However, the current version of lci doesn't seem to accept this behaviour :(
[Answer]
LOLCODE (surprisingly) doesn't actually need indentation, meaning you can turn this:
```
HOW IZ I FIB YR N
I HAS A SML ITZ SMALLR OF N AN 1
BOTH SAEM N AN SML
O RLY?
YA RLY
FOUND YR 1
NO WAI
I HAS A FIRST ITZ I IZ FIB YR DIFF OF N AN 1 MKAY
I HAS A SECOND ITZ I IZ FIB YR DIFF OF N AN 2 MKAY
FOUND YR SUM OF FIRST AN SECOND
OIC
IF U SAY SO
```
Into this:
```
HOW IZ I FIB YR N
I HAS A SML ITZ SMALLR OF N AN 1
BOTH SAEM N AN SML
O RLY?
YA RLY
FOUND YR 1
NO WAI
I HAS A FIRST ITZ I IZ FIB YR DIFF OF N AN 1 MKAY
I HAS A SECOND ITZ I IZ FIB YR DIFF OF N AN 2 MKAY
FOUND YR SUM OF FIRST AN SECOND
OIC
IF U SAY SO
```
] |
[Question]
[
**Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/8562/edit).
Closed last year.
[Improve this question](/posts/8562/edit)
Lately there have been quite a [number of questions](https://mathematica.stackexchange.com/questions/11350/xkcd-style-graphs) regarding the [recreation](https://tex.stackexchange.com/questions/74878/create-xkcd-style-diagram-in-tex) of [xkcd](http://xkcd.com)-style graphs like the following one ([1064](http://xkcd.com/1064/)) in [various languages](https://stackoverflow.com/questions/12675147/xkcd-style-graphs-in-r).

Your goal is to recreate any existing xkcd comic as close to the original as possible. The comic has to have at least one simple graph or pie chart or similar element.
**The highest voted answer wins**, not sooner than 10 days after the first valid answer.
Your entry must contain code that displays an xkcd-comic as described above in a graphing language, making at least some use of its plotting tool (Mathematica, MatLab, etc.)
* the comic must not be stored as an image, it has to be generated procedulally
* there must not be any link whatsoever to the original website, or a mirror of it, or its contents on your hard drive, etc.
Votes should evaluate the similarity of the results to the original, and to a lesser extent, the beauty of the solution. No code golf here, but a solution as short and simple as possible is expected.
[Answer]
Here's a stab.
## Postscript
[*Count deleted because this isn't a golf question.*]

Added a "style" section to make it look more hand-drawn.

*Edit:* Helvetica responds better than Courier. Tweaked and enhanced this "style" section. And added comments.

```
%!
%futz with a coordinate pair
/f { 2 { rand 100 mod 100 div 1.47 mul
dup .4 mul sub add
exch } repeat } def
/op 2 array def %original point
/cp 2 array def %current point
/setcp { 2 copy cp astore pop } def %set current point
/difcp { cp aload pop %x' y' x y %diff between cp and point on stack
3 2 roll exch sub %x' x y'-y
3 1 roll sub %y'-y x'-x
exch %dx dy
} def
/scale2 { /n exch def %scale two values
n mul exch n mul exch
} def
/add2 {
3 2 roll add
3 1 roll add exch
} def
%futz with a path
/fpath {
2 {
%flattenpath
% replace lines with curves
[ { setcp cp op copy pop /moveto cvx }
{
%cp aload pop 4 2 roll 2 copy
2 copy difcp %x3 y3 x30 y30
2 copy 1 4 div scale2 %x3 y3 x30 y30 (1/3)x30 (1/3)y30
cp aload pop add2 %x3 y3 x30 y30 x1 y1
4 2 roll 3 4 div scale2 %x3 y3 x1 y1 (2/3)x30 (2/3)y30
cp aload pop add2 %x3 y3 x1 y1 x2 y3
6 4 roll %x1 y1 x2 y2 x3 y3
setcp
/curveto cvx }
{ setcp /curveto cvx }
{ op cp copy pop /closepath cvx } pathforall ] cvx newpath exec
% chop the curves
flattenpath
% futz all the points
[ { f
/moveto cvx }
{ f
/lineto cvx }
{ %f
f 6 2 roll
f 6 2 roll
f 6 2 roll
2 copy
/curveto cvx
3 1 roll
3{f}repeat /lineto cvx % extra triple-futz'd line after each curve
}
{ /closepath cvx } pathforall ] cvx newpath exec
} repeat
} def
%futz with strokes
/oldstroke /stroke load def
/stroke { fpath oldstroke } def
%futz with fills
/oldfill /fill load def
/fill { fpath oldfill } def
%make sure rectstroke doesn't bypass being futzed with
/rectstroke {
4 2 roll moveto
1 index 0 rlineto
0 exch rlineto
neg 0 rlineto
closepath
stroke
} def
%futz with strings
%by making sure show uses our futz'd fill
/show { gsave currentpoint newpath moveto dup
false charpath 1{fpath}repeat fill grestore stringwidth rmoveto } def
%fatter lines
1 setlinejoin %round joins
currentlinewidth 1.9 mul setlinewidth
%chop curves very small so there's lots of points for futzing
currentflat 6 div setflat
/Helvetica 10 selectfont
<<
/in{72 mul}
>>begin
1 in 1 in translate
0 0 6 in 4 in rectstroke
1 in 3 in moveto (WALKING BACK TO MY) show
1 in 2.8 in moveto (FRONT DOOR AT NIGHT:) show
36 3.5 in moveto
0 -2.8 in rlineto
5 in 0 rlineto
3.45 in .55 in moveto
0 20 rlineto
4.05 in .55 in moveto
0 20 rlineto
2.7 in .40 in moveto
(YARD STEPS DOOR INSIDE ) show
0 .05 in rmoveto
.4 in 0 rlineto
currentpoint
stroke
moveto
-10 3 rlineto
0 -6 rlineto fill
2.6 in .45 in moveto
-2 in 0 rlineto
currentpoint
stroke
moveto
10 3 rlineto
0 -6 rlineto fill
(FEAR) .9 in 2.3 in moveto show
(THAT THERE'S) .9 in 2.1 in moveto show
(SOMETHING) .9 in 1.9 in moveto show
(BEHIND ME) .9 in 1.7 in moveto show
1.8 in 1.86 in moveto
2 -26 rlineto
stroke
(FORWARD) 2.2 in 2.1 in moveto show
(SPEED) 2.2 in 1.9 in moveto show
2.75 in 2 in moveto
3 -13 rlineto
stroke
(EMBARRASSMENT) 4.5 in 2.5 in moveto show
4.6 in 2.65 in moveto
-2 20
-5 22
-27 25 rcurveto
stroke
.6 setgray %gray
40 1.6 in moveto
2.7 in 0
2.9 in 20
3.2 in 1.5 in rcurveto
10 20
20 20
30 0 rcurveto
15 -1.7 in
30 -1.8 in
1.4 in -2 in rcurveto
stroke
0 0 1 setrgbcolor %blue
40 1.2 in moveto
.9 in 27
.8 in 20
1.4 in 21 rcurveto
1 in -20
1.2 in 6
1.3 in 1.6 in rcurveto
10 20
20 20
30 0 rcurveto
15 -1.8 in
30 -1.9 in
1.8 in -2.1 in rcurveto
stroke
1 0 0 setrgbcolor %red
40 .9 in moveto
3.3 in 0
3.5 in 20
3.6 in 1.5 in rcurveto
10 72
20 80
30 80 rcurveto
.7 in -10
.3 in -35
1.1 in -40 rcurveto
stroke
%thank you for scrolling all the way down to here. :)
```
[Answer]
# HTML5
```
@font-face {
font-family: 'Humor Sans';
font-style: normal;
font-weight: 400;
src: local('Humor Sans'), local('Humor Sans-Regular'), url("data:font/woff;base64,d09GRgABAAAAACokAAoAAAAAZOgAAgAJAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABaAAAADsAAABOgsNwLGNtYXAAAAJkAAAA4gAAAXxBSLIzZ2x5ZgAAA0gAACMtAABaPjPOy39oZWFkAAAA9AAAADIAAAA27dShd2hoZWEAAAEoAAAAHwAAACQGmAKjaG10eAAAAaQAAAC9AAABsNS6DQBsb2NhAAAmeAAAAT4AAAG0ABGuUm1heHAAAAFIAAAAIAAAACAA8wGVbmFtZQAAJ7gAAAG8AAADUQ4h4Rpwb3N0AAApdAAAAK8AAAD6DKoM2njaY2BkYGBgepb2+tO8F/H8Nl8ZGFgYQODoFxtjBP3vDNM1pmdALjMDEwNQBwCz2g42AAB42mNgZGBgZvjPwNDALMagwKDA9I0BKIICcgBG5ANCAAABAAAAbAFTADQAAAAAAAIACABAAAoAAABAAAAAAAAAeNpjYGCyZ5zAwMrAwLSHqYuBgaEfQjMeZTBiZAbyGVgYsAPHnJJiBgcGBYU1zAz/gXymZ4wmAGsVCdoAeNpjYIAAxrdQbMSgwBjHoMDEB6R/QDCIzfABIs64AMhXAdJdQLFbQHobkF4HoZmsgDRI/xkgOwDCZ6qBqGe6AhUD6ZWB4m0QtTAMVmcFVbcCqncSxH6mNIgcwxEEG6x+BZRfA8VWSHQawk5mMahZNUhuAPqB0QOIS4D4ERCzIekPQJgJDoMaiHmgcADbyYcwGyz3CslOmPwkJPfD7Aax90HsYpgBNY8Pqv8KNCxKoOH6ASnc4yB+AACzuz5fAAAAeNpjYGBgZgADRhUGRjBDBijCCOYzMLIxQAWBNBOQYGJABUBJZhZWNnYOTi5uHl4+fgFBIWERUTFxCUkpaRlZOXkFRSVlFVU1dQ1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP/+AwKDgkNCw8IjIqOiY2Lj4hEQGwiApGYWbii6fgsJLY8jMSs8AeyuboNEQz7MwRABJIQYBYMgwMdQxLGZYw7BRQVhBUkFWYc3//0A5BYZFUDEJBRmQ2P/H/w/83/F/y4PgB/4PfO/vhwcjEgAAPvcvSwAAeNrNXH+IZdddP+fO3Ptm52T33evmnYlNzOQ6zW5tbjM1s5OrZem0l2jT2GnDashtoTV2bLpSfbamroyNQfFRaV1cCCmVQWiNlpaKMAasC9LQfzooli2lNaUwCg2Li7WgLAVDMLN+f55z7tv4n5Qmb3be3Hffved8z/fH5/v5fs81mTE3vmCuZ0+ZVbNhzMnR2rrdXF/a3Mo2VvPJajYZnRzbtfVMDow+U7smL5y8cl81pS9yh6+ircuu8nzQVXC8sPfWTTXFP+jl8ZgvK1d6+Nmrjj5V49kdHobrwceVMTAiM7V32ivmdvPTOKLJOKf7b24tbuCAVuBIhsPEQxkeeSLnr+PNaSg53+oSX5MOehlQ2cCt4yhppAWd1pY9HofhuGqfRzqj8eQ3nrdX7FVzwuwac/e6HWeTVbuxhQNYo/cwCjsBMY3h3wzlB28XcNhwyiL+BW/aDRjuerYlX9zcsvgdGD6cAQf5D/o9srfBVBoYSVPCZD5LMiUJeg8CponCP87hL543TxsnIdKs9dsgirLglSpVMvQ3nFcUL8CpDUkIDrvTcKmGrgVX93kh8uhLD3ehJaO/PS2mg2X3JNemrPHaIs4CvyZnwgG8C4ucLmEWQd8et89lp4wzK+a0+R1YYZKXFZmeXhuxJFZAWukneBgXHtc+I7nCm5xEubSB2kknoNIuTvYKndRHVVHdfSQrhyvvmt1cFc7BcHsWD03f0+msRW0hWkJTxlmiYF2hL7uEwuRbzUpYG5z3f3uSg0ft8U1Lt9DL9qSXORuNr0T/SAfbig0Jx1XnKLO6nOIF2Vgq50wOsnveXrZnzJK52zxozpkPGtOeBgmBCtqV8eLa+ggtYjQZteNbQOm2biG9QoUkKbYrYstgSIuT0VM88tK3XmVBGpV3Yq8wuS/BkW0YDuijaAqpVFfku6JLZVHSVcj6QWvrgk0I1augz0DoaprsBbpCPAhcsIJTtvG+Des8fRNHsFuxbL8bZOxA+CBJXgj8dleZBfRf9kp2FvTpdvPLoE3rGVmVPYkKgtNe3MB5o7agW0OtAoUBPRkv4mdoe/SNyehQXAi7CrImUnBfXgPJtOUBLIksZF2IlnhWchh0U5CU8EjrxNfBgFtwOpfF7+G1j/6mob8c28glh6eg0OhKPUyu1ysGfWhAE1j8cPfW0bVqHBH6Swt6cWj2waJOibdkJyRuZglX+jPqskHIPupvoV6hsM+JlsEvnINLNJNdOX+Gd7vxLXtnds68GW49Xp6s3jImycodUeNG9rgjhanVlupCFlbVrOMP+SPSCzSLHk7I7uJh1njDfTy3Fj+nOtShKc7AA6GYalEYst8Sx2dufMc+BvHsLeCrxwVowNppdLBbMMQcIhuudwk+9l00ghn6JkeeopexiAE2KF+JB3qTVk95gUY1g2GRl+0rPqVhNwFuRHwHOQweeytTmvIYn7ZX7WPmvThGDBbgyUAd0YJp1TDG0NuFzXX4DKNGyxLeQNWWgEHhgt3jajay38QFCoFBhMZGRj6dV5AUlN/i5CA40+zZhfuy4MDQelbgsyx3CSPBGUkUaCSU+IABRKEceQYJQujLSAKO3AzpkOnsA/aiuUfmn0nc5ElTHEAzxXnxLCf2Z3nEEvwQaHjSl3B/dKpfEafuc/Wxzktk8qR8PQmIVuBbZg/+/3HwoCh+u5UHAU9Gn8D1bySswj08rWlxKrooiglOwidez+zZC3bJnMQZZTUsGUSkjNblMZDY0Us4poakdoCC3ZeY3Ajy4WsA8jEzU+GY7HoAPO+tg/ukRTlFqMlHgyKr/DTcnyRqx2NU+ZMEJT4AZtjmotPwpnOeja4mFYX32wWMCy5kH2CVd+Jbqg69ACpGTdEJ3m+zlxOUBn7gZfC7a+ZX4Z6wXiRGWksEjmBw4ItOrDvyQjn53GUY0LNFz040REWURMMeD21wm4ba6VjCq0kCM3sBVyXBsyBPu9TDNQhiBlfjIA439EU0U9SimvxPq/fm6zV4sT2N9RyldPnp5JIAoiHdeR4Q8znzemMooNpqncIKoRGc5WpWjb7rSNncHFgmP1Lrle9D7bUPyV29zojhcHAYoD5fY6/xBXsRJN4bk1MgVyzEr4I8x8IaOD08mFOMW5owWkU9sh9zBMUQnxGobFUHJArgMGuSNNtQj5LtBriEZJGDoGCMD5LwdGYtjL8VrczjfNiVssL2tEie18TJ/BB4N5Wif7LMrMxK8xha0iJNMedZkj1tIPJjP5kTPEQRbGU1Sh49KCnZjR11VQ2rQCNxnQc1ZdPhcaDyUYBr6E8yU7ukmoXQd4e+WouQzu8MFUc8ZTgUcHeDYcAr3iZbFzmSi94hM0Cop5EVkfHLMPMdnDklX+AVM5kkLnixyastsZZWFZc3Q/wr0CanyEBAeGSvBjhLkZ8gE669C8mDLGHwLY4TMtHCOtcZFjGH6mMKx2AB5MnzDwDPYXxGMTt1vNd1EegyeyBNzRFJwWeVTzXg4ews4Jkd9GU8eVp70OUl1Pp11nqKhTkpQ76pZsCSANUfZfc4QGyo7Y3OCdeQsWdfshxo0Tle7AnWaVQxXBmTAQ9eWyFRzZnkcxFRqX/t+Fv9nHYoVmwwYCXHGeZ1MYGuORKgb33YXs3eb15jnsSMc3FNoCxPb3EFXO04p2nn5FvZwy5vrC6MHdo8GvwSrP+HfbSDPOQyeL8dlIH4x04QmRt62HrO1TonuNuXwXHLd2i5RXinwnRgZX0AybXIRW7RRT8bfvWMouiIOF/H5iGBX1MhQTIB03YcAR/OngGt6VFrjjEMDq9AF0Rxrdsaj2P2Tc4DHGT2h3l0c/VgigQ50twviqjA6C5Da8B3XFHrAVCdeLm6DOqWql0japDIwSuaDIrj2HVgfkoZz9PgIU+ZCUT7xyn25msSc+0KKAsmNqwmlnIetg5HBpSRX7jAM2oE4npYv8Z7HWDF9oL33L1U7gXtkGXdDsGUMxZeLciI2pyT5sI+5MW424DHmmshjHDwwYBbX8qDggUBbLNrSPF4h1LsBBG06i2/AzZynrzESBe6iAtN1AGHDw2GHDOXUDjLlAHbbyYrjDm2EkjkonHN+jj1KTg0tn0YSk2+L6AXGTxBJSfc13vIs3UBMyOM7MWLeAostaTaJMOp2D9C9Jr8teKeqGxtypLdeNgc2gfMbeZexCGLuMYjnFQbCDt0kZj9+UF2ral97ThhJ1ckg36QmSeEYwn6gTu+ItP0bJSkiTiGJ2EMF8yKeR2OYUGlvwCeCJnDTJlDSzloR26opSjB3uQOtQNPaccdqGm5AAkxf1/ZdQ5LXsK0kdW/ABjspyhGTGR1R5tbx5lC+8Bhnu8w3HDgd6ZCSG2TXgldBcnm8iFcf6ckCOJ7XAQeCaLink5j8oFYyc5eBIR9J2e+EpeETmEHgm6Z4chGjEQCvKYCvLwyY4dKiLo6hMCElGyCF7l3ACB1WVAN/r6WwzH/ciEjMDe+B2jxvNnE0Z6AQS1h9rtIceFjuVAICAlw/qxkM9KBLjF3gtaXyK/bTAELpWA7bMFVOWOSrCtS2gjs/hLnUCi5oxdhJM9AbvRrgpgZpxC5XBDOydcpQ9gaMagF3LMoYpU8CtT4iZqFFzHXKxTIO2YskyShCSma+hBPjk3AYJXnVQK5g/ctipdiZuX5S9knKG51And8vP6U8RxLqVaaJMJAXyZrIh5mD3R3QbL/q2ZsGvMHxCivRUrZrsAyMRWcTTj9bVcEB5NTG03AtlZzEoxFFHCCcivHvLEGFbjrJ4XGYB8ScAZaF4XTGc2oQzia58KhOMF+4n+6NPdi3osdP4VqnX/xfRIWxkdU29u78CFBf0nEyK8pdABdgfEQrRWk6phAm0vJiIyvJRzEGRGRIkjp5WzZ3GE+ApLcXB9h9MNgiNLk7Ix4wIz+IYYl2wopU4ADI9QwKXjYiwosnI8wgHKeHaFYVJM6kUxQzJtfNc/DcUQLCrGnVZGGDDEgMdC/a45J9yIg916DcuIbfKTnAmZo2GUGYHfAYkKNe5xyqgl4gxkhBkuYmmoXG1sLJ0FuA4hZrADUptipuW2mXg4iKdJ+jnL58lBcR0WYv+aEqbsZdTIjnLvtkNdyCcgNsGTOCacm4k1iO5JERrBsH+qjmirLePTtiB1BnQ6SihBB0GQ9yY3YM4k4S0mH5XYp8xC4J5dka2/K3g/Z+EcwGz+GZig5SMWliPVMkm94LVHiOsLQlD0qVwQpHMyZ1zz8Voc6FeGRl2MQNKWZ1Dpvz7yjo9BZFhSqm/tEbLFoER0jX7SLsCVlOwI92NKfU9bQWrBMrXHASSyH4NA4ssXHIW8rwat9kGwxJ1e+OAmODDXLgWyOa+wk5iQ6+RHb3xXFewGOyhImOBn1oN5RoC70qmItJl5gtjMBVyIVjgWzfcGr4pQ7yfamKb5Hge6w/yO1aVNPQFpzGNWz5eVkjWd08nR2LrsLOQxGCjXRtCFTx5A3Isy+uCHH7MbKhE9dz8TmkAjNauZ6R9lbeW5HX5KqRBcoCk5YBV8oU6hIE367hl3I0YuRcKPP7QXmMO0/SI7jhBiKQGKQAcUKEZ7QcCUYrehCcExFqESyHD5tr9iXzcMoh0xi+4j0QVbdokse5ygQ8dU081GNzOnlWP/qQujWoguHbk8W0SU8R6hPq1uyDxGMuqxcR4L3E7/NJc82GnmHydxBSgqqBfLMnsxOQQ72MeRqTlAQZuuHNGuZOasxV4cB1WAClgBDSjUnecLx6QQpHWNmMuqhQvZZCt6TEMRRPPgLSZ95HlKPn9LaMIPt5r0gVypaTUSmgSMYgpekAqNJ2aFQqZrSTwODJJxhU+4rpwdR+pR5BHylMJYkkbHwVxNOX+SFPB6bC7uMBSK8FpFVtVeFROLp7afQwSX1f61rESW1L1DQqU4gXJG4NE16D1TTRKvVeRyohTXEm4UaqHNJ+8BRIZjbzADZvSbiXDRjGj+uezV6ItJgLiY1fMOpmKuMCi76PpHe46BrpXk3e5P1xKmiAJeQxGg3sJYpoTrkXYMsJJskppQP1jZyK1Mi/V3oyejYsXnFxeJSwCgwJfizYFKB1TjQKwXubOq8pi/7dIWOiMW0dYR1xQ905V2kK8sK2mA6FVXEqC/Fbh0j31FQOnPVI0Yn82kVT6hpR24z1hm1gYHNT7nZz8EYOOlrhafuIxkCbuROTVqFKIk9FY76JjgQca79OQwEVCmwVwEj3M2MvWaMFXm+StSb02Ms3x0GFRR5C5F+KPWrtJSQnSK1PLojLGWIPc9n5+Ge70NepCIGmSuKOXHIqD+CSpgYY4cLcWh5A4W6NMoeFVaTzaqT7MeF2J+EB5+kO07TIBYTk0RJIds+hwpNhMN1MquQahKGEZe2F9n6AzpLWUdxWeLUscyjiiuWBzZyzrwD/DH3B40Yzir/RwoETuS4FhcxqazID2OaOqWr987nAQD6pGdBql+kGk2k9DneFd9nImXKA/OB5ZtF6hlCpNrbtqhqI7xpr/7l6CXmVJ4GFPUOs2F+j1AUrA9AccfNLYwjV8a3CA1OHQ1bYyw68aKCMaRJkp+Hl7VSz1MFUdvChifMqnyvHwJSwnrbsrz7MTgQpppq3dvNI2hW6HpAppd1QgcPbtJXgRZnqRNw2+bEZj+5JMuYOSiqFjSEtjZZMBJ7A8BaRoSecZ2Z4NUWJ9BLAjfVL3aDhCFmBly2Y7zZl9SaUysrrShIzt+X86fMg3ah6BM7LIazpqqkyLvO2RIOpA51RnrRBt56GhjAL5CnfKP5bdKUgnLfALalWgRQawGCkSIsLRxgorJaURJHkX3bcVYhsdwFljAXdIDJW5MrN4rtSYS4+5uWsAt+QIF6q+M/lDRwW2bBy9hVndOSWc0BsSWKpm0Eo3FtpM5ZPRpVX351CVHMLqGNFAFJifSjIqZ4XRQDvMDJNTQsG8KLpLkjdcpLWEgZgYQuw5LvSZ6LMaz7aAMOPmTsw2iTIk8fChtOqLJQiKe0iblydGVNaEvsjn4TIpG69JlGoF6AaB+0cQ6ezWLl3lfSvuK11wTr9L9LvRbSQTfOtJC2yLkXYVRly7mfLueTwPWgNuWU8f+7V3ph/ifEyWnAn52mJNwV5grp3poFfi1UaIN7CC1H4QU44zyeebOiVYEjAZ1r4h+NVpJQxHWR9oaK/EMEnwO4jcTQ/MYj2SnIW96AiAvyE1uN2XwWCIZk9IayM0rNJqQKe1VIoqSJkvgtFwNAKBqWR58l9fQKT+2SABPHsTJgIeZt3o1rt0ChDKx3qUIUBAlVhcmFNrXhwlmhsUb2hpTqMXmPFb6azMo1RUqyNZL71wNZ5LEEIB1PjupFPnESaOj2WTyNDBXyy1Cy6IRXaEJGoYxskdTxpjpLe9X+wDyB0l6gnoUT2FHG00JOdF1aZ1cVuDB1tZTQd3aumpO+aql/DI8Ha00CV8CIr8rlNZQsf7hMqOS0JFnVUjzhufaRpXOxVUVtPeEqQpI3qAEGerATJJm9AJrwAa52gRaMxkvr6cJb9fvHWUxbS0kPVTbKvkrqMAt1K1IIDtJd2qTiGmaUnAI3LZdQNwOblAT+QNHZe7k6N9PZE7RrhOlNoijEsgacGjWKh+yWqywNw75Goockbcp+slU+nZ2D7OrtlBmA76Zm9a2RSoBDOodA8NvZWRpTx1iO+6DwjVOA3+bSotawZ9rVMgBXJffx7RTP7ZjjosACI3QMS1pqeoHRdsxDwtLvai50idViP4+oHFHKWfNL1J/FJQ9Yuopw6HFkDdCR3KPqymB3Nw/YIbKkdTxBcoRaX16CSkSp9geqmMwz7GpHESPsw8j/1ZVW3zUvqsUt45LQdLX5Syw2Wzbvkbwm10rYCep2x2jKvBX21h7XPD7fEC7LfrNWQic0YIeGgxrhHpZKaISSdWmLzTdC35ZPG1Q9O7X7kpq95h61TnCbZOXTGiYO4RsBLrgBha99fTeeN4cwU6xvrgl0tBvSJkjoAWkKSeVW7ehgpoGMu19KjgEu6ULslHfekxKnIy3BBOvok9qqyTrzn/YB+xwgW5ODqpeY5N+KnZBxCwbTkliRd4KT26RxwxVOnRFrKgmB4V7sSJXucrSv79kl8DF34VxP044FmGmlLUi0iQE5jOt7VdL+qf3+zJN4daK4cNIYhPsEkM24g2dlDuwZe9nUENOw7TUPJXvaYGLv5JpUqR1BoV1kSsH8AK0xtFOLrwS4ISQ190P39lkzM8fgDjU2/9bYk3wRhAuCfwyG1Oec/NO5DYznXnObMe36Mk4QPMe+uEhUNfKHJNSiEefWUpxuRIKKxZ8ElHUeMv0nOQvZ5I7e0KCVb7S4uWaRPlpcUxg2EWDB6amUpLCaF+IcdmvUecyo5roJcRl2UXcTmi52mfj/ozw15f6Oej7EFSB+qSRIa2pIjZJrHH3KBQq2CQm608JYH6o+oY+ukYyoiTrnQyeio7qoFaR+1nxIWXNyk4pVbaXhLBInhHxYf0Jf4Bo7JGoQ5D4w7tXIdwpms6aVtkHmSffwfgi8VAKfyRywMqLsmAvBXsifmpM9zPQ+zhhjhxtGQuM7wiPeBAP6/2CVdoV1ug8EiVvnQ7+TS0ZVa/1FpFNm57DbFvvakXF2jNM1sTtOnCnWmpgdIxTYlFpnc8MOrJrq/QnaaDCzqxnZTBOUpCXMtMlF934MC7Z9ylTX1BqQ0AEw6TAf9TrCKTXDcWnTBe29ei1lb2fM7ysbwtUj9rkQUkbsPAAUVWuh0UsSusXNWLVcYmN6OYbRpGpCG2E6taeYseauTQxrGvJKrjnqLhBa765Ksr1GyrEMlQ58uocoqbO98l+xuMUMvJwZCx6Dxcg5RZ6JRe1RdHNp6a6WzRNNUot6Prsf9KZPulbQI8mWtUz55EVuKMiSvhbNiokswVQHbemgCn1Dh4jmfOiklAouCfF6gG77wzKLtk/0kvVkd9Uh9UKP75qU0e+rudYA9nxap0jKxExMSJf05ewZ8zaqOTE2ofny7rHFhPTkmTFszEb281IM1IoKlgB85IGV8KxfpWdNCPPsHXHbRcdVqcCSSjUapcYOdj/UXAOhWkn/89nsKfNb0c6XQlcrKTh5OFDn4+rzxC9S/EQM2TM1U8cycZqxdaHLI7a5oCX2wUnI5oAmsrk9Lwc1dIr6caL6VKStkP9UFDlNiZkUxEYXB6PsZKdBE1xNH1uNfRkZ3k40+UPZXYBP3sYc7wJm4dIcneOfpymAyl5KrbViakCJ0QSpXvQ5eQAt2uNLR9PNkaxhwlNIQvhCeR3Xlv1bDHiU9XPTJx4mde/SQtQBOf99hFiMnGmv1ut4r9Zcb2rg4jPds5VsQwlsay6NYVnsb5bKikvCmJQqDivJPt4PksOaAMXGcVaNHZn5MnIJixucSK9zPF1MavILE6wHeHbWsdXZDwqzskVL+/pq4rRT3x8qKdoLch2XGRtkPWfinptoAxE0v3GM9KZOevhnielreUe7OKWKhLsCf0H2SuS8j5RCZV5Jux7ny9g2zZsBOUJ8mfvaKVX2zMU0IdtqNPFV3ZYiAPH6uYS84g72cjPmSvtKfB6AAR/z/zztGxP5bpMbnQmrJt67BFz5FpmHnXfP5MRoYrHfeRWc9SKEOrqmdPyD7fbD/gYM+WkTd4OYnR1RQo70WpYcmH3j4urPyPk3Ek9D1eu8eVTHHFRrfMv6IpJpUuqvhKBGtsIp4K10J1t0G0neK/bKu9pCPMDWqtAbxIXwoH+4FqF7P9RaJLuVjb+4wUaSCcpbaHtLr3XPuHMgVokBzNFMt8BXnzPvTHuQkZtA+6KdQeKRTuiub9x5q3m+co6U8OzoVgKMgMHIBYjUiWeMW0wwu58KuvORd9thKFcefbTysKYXpdbmk91dvaCdw7gRRisK2V+C1dxv/pjQ1tLa+KT0Gm658bG1iA6c6t6tEnjEx54NOKmpdEb1YA+UrEQXGd5+J6IrH7BL5Nj8kPadb60TfnEWPjmQfuoAG3ya6dKu9vkL9nWCtOr5DT5Jk6gfcNN1sqlnltTOXOhMvB/y3EekLsVbElZHVMEr1nSHAteDpV1bNm5cLJq5HShhn3HHuzdqFNg09s/p1mWJ7k62U0jp9TEfdhr6pCE9IBlWi2nS5zPly2Xny5ia1DEc0/yyU6ArDfK23Hm5pHEXprtInRsroSKl7T/JXh3tl5E097Ji8i5VGorFjb4lTnrHx2pmIf0/gne6m3roNCfphD847MNOLp90Iu4T0eVCyQrbBX1avtR+uFo6bfyQ4eUGTO3wpOJWjWktd8VhPf612OvL9UncrrEqPaq48C13W4JqYOPzGvO70WvGl4TlE1TmTfY3ptsEvGtpQLNyN0lxqOl8L5n2tdjUNWyLcuFJBbGWqc2rhX2omYvsipe9pEwRAHNTxJ425oDUrgXqcdB47QfN2P2wJNNLw6VUsq5AXPl1RMbHNArSNjCmAhxukcNquB2Xq5QN2y/HMXbaZK++p5fNYF6igVoFb4rVTa+OthknMcNrHUX7JhEInBqW2dNtX502lAtLG5qHQkeBFPvSOOfjvvc6dOEIskEW/GVkBTlbq2J/TKjgWS5MnaXoMNcQk5TdUBjZKeSJn2VBQMxwuluTalY+PujAl0mPycPZOUCxaPnjH1tbnzdrQlc5uTosTw3qFCewlzHZZNWXaSNb+tSAV9lcibKbhq1BUVHqfH4jOu9E+qJ6/rntZ00VkrBkq4XX9O8gdBv2VbIpbbA9q9NOIHnF3cGopXeZ8ykmCG0oJzZl116o2CyRmKyWshaYufnysFjVJNuNbt6clsd9ITfVq9K6Fjd7fjzZ+Kipe1K20mcYpBWpKRMyr1b2arzW4vm5FdQNFfZJg5aU1HGewlMCSciE5uPRvIMLYtEaHz8dp5isLmy0KeTFjD17q7+p1ucjSarIsbt5v+JAXsLJNG5QV8+Hz8nwvKPPD4p3TWx2i01QijA7zSOVrdACQAjBU6ESWdKN9KSSjAcOMmbqobv4fvAAj6JcC+pysZQOj2ifA5ICy9gvuUwt55DA3UNOcEpj3JVtVY3sgadilUSP3aT4lGsBPfQyFNzg1Gnm1mgPR7Ur7GhF+LOVEhor1G58iID2BydEdh5xmubHD4P1nDK/wtbjFCJpMHS4iSkTu1nA3lDc/BItph4YTdqUcfO2TkR23ZyBJPvz2eOBufiwi1PW7YDpr1mKCeuh4ciKdfM7VllLYtrng6U8BbN+u9bTamrD0JaMLKbjaDrU6Yk1jew3Ak8ICQyDgD0KK8GZ7UVUeCgZM4bkvTz0N9kzg85Cco4dQoXtxP3Gll7hJPYoskdyjis73hwA0nmQnl/BD2cCHIiGDou0MpG9XlnYtQ5T+NvUgPhRVj7UEwL6Bvcn/riVTekxyJ7S8/qUrhmuAz/EQ8Ngq7txQ41E7eqvTW+vmFuRm6k0c622LKRsb5NnR8WHJdgPU4bFakBC1Pw3v/Ets58tYwdry7tsMipVby1yHwP9k0vloiXMn0vivjAZ7Q2arPWhLYPNZdLIpz2Y/LQeH8MhEegHwx3TejwyKPGBNdrx7alT1w/6APMiVNX27BX7HnOGn8sAOe6SdMFw2pLzs9iQPkm6etIneMAQeslNfGwRg3l9JeV7Bj0ocHIfcg8X4Ivmql+E/OpB8+e6o8lKS8A686M58/5bJ1eiJ8G+gcGDw2jw4Q0xqOcDvUFPvXL63IS0028uF/TFoIAdCwep02m4a26+yTLdm9NJV3kdn27iQjt+YS80Stk0FHmFI22StHbuiSODErijTVCJO6vjUxzmSoF97NppNP9LzlE1mVaoD0fXsj/J/s0smJF5jbnT/KR5HaDTN8InP2POmreAHfwixKo/NX9hPm/+yvyd+ar5R/N188/mO+ZfzHfNNfMf5gfmJfM/1thFu2xP2FvtbfYOe5c9ZV9v77X32fvtm+ybbWd/3j5k32nPgVVtbkzwZ+G0YIYJt/qO9IP2dLuxMrbwbgQ/J/FU+U1fg7NH+IicBXBKJ/WkcXZ6k7ca4CPoUI/WRhBYePs4WiycvdHirVBJTlKBHB9TR9/mK9i103jWaGHdcv2cPqY7wJ8r8q/ecSUcb/nbWKpeoZHqqEc0SZgLzewkXyT9nD7TM0c6e/lJr6LHYOmcNvrosz9c+o7+a6WgzM3tfAa6oqRCST5IeIPw+BjWDb4gb6UrQC2d6LEr+FlbJbGLqHdU6qL3FT6UigKw47/4t9dDcYxFOG1+1Ol/tzsc99FL+ogNpzXf6/TBFG/XOzdzzp6B874Evy+Ar3Hula8jxJO+dZedde4APv82tfRJNcSXOHS4QJ0+wCzxBzT0lo3S/lHO+x+mfLePFIwyy+roa2JMuMX9Mef+iWbD/9pnneORfoL+hoHZR3C+GAVwtHAgK+nX0Ys4FPBYdoFOheEewh93wgXwA7xSR4fgYvvONTQh+5DDAXl6CQKxF8Gbvp2fyLWex0cvUkcVhPCA0UOj4aLsbq9Dp4F309A5KMX+tC/2kjAUIS1hQPKMEvv7pZ9SRaXUrKROAhbTLZckXPlQ2M7j3hHj7Rn7r/RUAGyysNr6n4enbvJzH+6kqI/RrUseSyNZAY1vG3shhB0+ZCzfKMCY6RMeq+3/v6d//ZCf4vdDvNuP3hNdf7TGcwtE0K9lL2RfhFU5Zo6bykzMT5i7QYvfYH7OPGcnMEaISRB91iYbE/jB3yv4+zRo+AoEjdPjbAU0XD46SXX98MisRQgQtBtmbXwMwhJizs01CYEtPyQT3p3GR9bGxPvExlag+DOmMSoCTic3Y/Gcn6SZSbvSqKcIQOHCk6NBkAJKPuXcc+bJE9UuEVDMCV/Usrl4auyd1BYUCkbezYGbuVJAJHqHW+3pVd/EE0zTx/GEPb6vegvdX72faPc0NExdBie7CxFzx11y17AyBpbeUj/arIbDr2xG7toHSF/ZBe297PhuvLeFH8VC+8lIjhQVfVkGsiBBjnOUVl8Nu4dhpC3VXZsBCJ8OJxZZzuSrhymn7ZO90qncAPr9L+WmlycAAAB42m2QOy/DYRTGf25F1b1uQdG6VNzqr6qooqqotmmkShqDiBhFxCcQgxhExCRiMIiIQQwiBhGDGAxiEKPBRxCjeOze5De8533Pc57nwL9nH9LskL4GGReQeQ9ZD2ByiRfI3oCcP74hNyR2xCOYvZBniHOw7EG+6gXSKjyAoicovoKSGygVVp+4hjKneIfyJahYh8o7qPqEamnVhKE2AbYFqPNA/TI0RMQJ2KXvUN0hP42a3aR7s3y23ILzA1pFm1UcQfsmdJxCp3x1rYDLDd02cQiGWSin8Sp+oEd53PLdewaeY+iTjlcz+qU/oP7BVSF/vjcY0rt/BoaVZcQCo/MQkO+xRQjq7/glhDRrIg6TKZhS/vAuTG9BRNmimh1Vf0w7iGkn8QAkTOIZZoNiW2jHSeVOfsGc+lL+X8EbRswAAHjajZC9btswFIUPFSdFOmToz5KJQ9HYg2VJcRB7CDoYCLJ4cYB0C0rblCJUFg1KiuFn6av0zbL0hGSAoimKkhD18eKey3MvgI8iwsv6iftAAh/Ep8ARTsSXwAf4Jn4E7jHna+BDfI5OAh/hXXTFCn7du2q+5ltxGjjCGzEJfIBEfA/cY8488CHei6fARziOxswUvePg07P36dn79Ox9evY+PXufnp3PmdnubVk8tLK/GsiFqteqquS8q63RZ41clkWhm1bmqpZZkkxjObNatXotl3u52+3i3NRtmZfaxiuziWXXqGFaldvhOH/s0gvMYLDFHhYlCjyghUQfKwz4X0ChxppnxS0xR8e7pULjDA0jS6cqeG+cMncKiQwJ9xQxeUaFZrzluXaaPc+d2zEVhoqWdXJ+mrkxXzfYOG3HugpDpHy/pM8hxsx7ZDzFxU23MVbeqrrBDSMbqiw1t85Ds9BFVynLJjQNdiygYP8tuX4Zlcziqeynl9ng9QjlbzWuX5l/bj1m489DTHHJ2+C/mpV/83OnbVOa2rnJJqPzUTLFnZM1lJswaf9chglGOOfHuTuLf3QZav4Cg/GRt3jabcNHMgMAAADAlSBRI3onokfvXZDo0Xs34+gZvMDV0QuMcvI2jLOdWQF/vp/d+c/97ywBQdly5AoJy5OvQKEixSJKRJUqU65CpSrVatSqU69BoybNYlrEtWrTrkOnLt0SevTq02/AoCHDRowaM27CpCnTZsyaMy9pwaIlKWnLVqxas27Dpowt23bs2rPvwKEjx06cOnPuwqUr127cevDoxZNXHz69eff1A6d8G4QA") format('woff');
}
body {
font-family: 'Humor Sans';
margin: 2em;
background: #DDD;
text-shadow: 1px 1px 2px #FFF;
}
h1 {
font-family:Lucida,Helvetica,sans-serif;
}
.h1d {
display: inline;
font-size: .8em;
}
path,rect { fill: none;
stroke:#000000;
stroke-width:0.00329859;
stroke-linecap:butt;
stroke-linejoin:round;
stroke-miterlimit:10.43299961;
}
text {
text-align:start;
letter-spacing:0px;
word-spacing:0px;
writing-mode:lr-tb;
font-size:14px;
text-anchor:start;
fill:#000000;
fill-opacity:1;
stroke:none;
font-family:Humor Sans;
}
text {
font-size:0.01944444px;
text-anchor:middle;
fill:#000000;
fill-opacity:1;
stroke:none;
font-family:Humor Sans;
}
```
```
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Front Door ( from xkcd.com 1064 )</title>
</head>
<body><h1>Front Door <div class="h1d">( from xkcd.com 1064 )</div></h1>
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="434"
version="1.1" viewBox="0 0 0.7876308 0.53355077">
<defs>
<marker id="Aen" style="overflow:visible">
<path d="M 0,0 5,-5 -12.5,0 5,5 0,0 z" transform="matrix(-0.4,0,0,-0.4,-4,0)"
style="fill-rule:evenodd;fill:#000;stroke:#000000;stroke-width:1pt" />
</marker>
<marker orient="auto" id="Ast" style="overflow:visible">
<path d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
transform="matrix(-0.4,0,0,-0.4,-1.4,0)"
style="fill-rule:evenodd;fill:#000;stroke:#000000;stroke-width:1pt" />
</marker>
</defs>
<rect width="0.75612795" height="0.50201935" x="0.015758738" y="0.015780471" />
<path d="m 0.08162198,0.08036774 c -3.384e-4,3.2166e-4 -7.6617e-4,0.35262886 -7.6617e-4,0.35262886 0,0 0.20318503,-6.6026e-4 0.29000566,-0.003213 0.0402085,3.6731e-4 0.0806898,-1.3866e-4 0.12100339,-4.2191e-4 0.0422491,-4.676e-5 0.0848177,0.001196 0.12714108,1.4026e-4 0.0292134,0.0012 0.0579496,7.8663e-4 0.0872307,8.041e-5" />
<path d="M 0.45045642,0.44967094 C 0.45097434,0.43767424 0.44992661,0.42569324 0.4498655,0.41370014" />
<path d="m 0.52462262,0.44857719 c 0.001364,-0.0112841 -0.001303,-0.022673 8.8508e-4,-0.0339046" />
<path d="m 0.34455432,0.46185837 c -0.0838098,-0.00177 -0.16763839,9.02e-5 -0.25145536,-4.499e-4" style="marker-end:url(#Ast)" />
<path d="m 0.36372087,0.26833529 c 3.15e-6,-3.093e-5 0.003925,0.021959 0.003958,0.0219625" />
<path d="m 0.59455272,0.18635665 c 0.00168,-0.0249062 -0.0194278,-0.0449558 -0.0436226,-0.042955 -0.001466,-1.5486e-4 -0.002932,-3.0973e-4 -0.004398,-4.6459e-4" />
<path d="m 0.08896568,0.31883844 c 0.0589995,-0.004388 0.11835478,4.8486e-4 0.17689559,-0.007727 0.0452821,-0.002558 0.0920316,-0.008761 0.13292997,-0.0296799 0.0495136,-0.0206019 0.0702543,-0.0754087 0.082167,-0.12423165 -0.001544,-0.0316524 0.0363005,-0.0771322 0.0574533,-0.031946 0.009799,0.0468904 0.0124403,0.0957944 0.0257953,0.14199884 0.0103229,0.0424564 0.0381648,0.0821154 0.0814383,0.0955288 0.0230248,0.006738 0.0463641,0.0136174 0.0701731,0.01698" style="stroke:#888" />
<path d="m 0.08766361,0.36678952 c 0.0463076,-0.0161779 0.0920382,-0.0420708 0.14283849,-0.0357173 0.0467333,-0.004581 0.0974621,0.0266481 0.14082991,-0.00179 0.0400306,-0.0301432 0.041483,-0.0866619 0.0490443,-0.13214834 0.003929,-0.030081 -0.00375,-0.0999028 0.0422392,-0.0879794 0.0291414,0.0376662 0.0177989,0.0902038 0.0319018,0.1336763 0.009362,0.0507676 0.0330856,0.10817744 0.0871312,0.12415282 0.0508722,0.0193263 0.0767224,0.0174745 0.11889504,0.0257316" style="stroke:#00f" />
<path d="m 0.08912193,0.4046365 c 0.10169167,1.097e-5 0.2041028,3.5438e-4 0.3047905,-0.0155419 0.0458292,-0.008171 0.0971567,-0.0242812 0.12178371,-0.0670869 0.025388,-0.0534434 0.0183231,-0.11451516 0.0333489,-0.17061477 -0.003977,-0.0433016 0.0436224,-0.0993166 0.0831427,-0.0568712 0.0246552,0.0226559 0.0477548,0.0560862 0.0858377,0.0521295" style="stroke:#f00" />
<path d="m 0.70840577,0.46185837 c -0.002849,8.248e-5 -0.0849355,0.001616 -0.0849355,0.001616" style="marker-start:url(#Aen)" />
<path d="m 0.24465913,0.2858699 c 9.6794e-4,0.0147144 0.001383,0.0294673 0.002814,0.0441494" />
<text x="100.15588" y="48.485607" transform="scale(0.00138889,0.00138889)"
style="font-size:14px;text-anchor:start">
<tspan x="100.15588" y="48.485607" id="tspan7010">WALKING BACK TO MY</tspan>
<tspan x="100.15588" y="65.285591" id="tspan7012">FRONT DOOR AT NIGHT:</tspan></text>
<rect width="0.24843951" height="0.065260872" x="0.12345294" y="0.039088331" />
<text x="0.23551519" y="0.20231472"><tspan x="0.23551519" y="0.20231472">fear</tspan>
<tspan x="0.23551519" y="0.22564805">ThAT there's</tspan>
<tspan x="0.23551519" y="0.24898137">something</tspan>
<tspan x="0.23551519" y="0.2723147">behing me</tspan></text>
<text x="0.36015913" y="0.22917171"><tspan x="0.36015913" y="0.22917171">fORWarD</tspan>
<tspan x="0.36015913" y="0.25250503">SPEED</tspan></text>
<text x="0.37393194" y="0.46812996"><tspan x="0.37393194" y="0.46812996">yarD</tspan>
<tspan x="0.45037103" y="0.46812996">step</tspan>
<tspan x="0.52267832" y="0.46812996">door</tspan>
<tspan x="0.58878779" y="0.46812996">inside</tspan></text>
<text x="0.63905853" y="0.20506927">
<tspan x="0.63905853" y="0.20506927">emBARRASSMENT</tspan></text>
</svg>
</body></html>
```
[Answer]
# Python
Makes use of the slightly cheat-y xkcd method in matplotlib:
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d
plt.xkcd()
x = np.linspace(0,10,1000)
unit = np.linspace(0,1,100)
speed = np.r_[np.ones(500)*3,3+5*unit**4.,np.ones(100)*8,1+7*unit[::-1]**2,np.ones(200)]
speed = gaussian_filter1d(speed,18)
fear = np.r_[np.linspace(0.5,2,450),2+6*unit**4,np.ones(100)*8,8*unit[::-1]**2,np.zeros(250)+0.1]
fear = gaussian_filter1d(fear,18)
fear_gauss_bump = 0.8*np.exp(-np.power(x-2.5,2.)/(2*np.power(1, 2.)))
fear += fear_gauss_bump
embarrassment = np.r_[np.zeros(600)+0.1, 9.5*unit**2, 9.5-np.linspace(0,1.5,300)]
embarrassment = gaussian_filter1d(embarrassment,60)
plt.figure(figsize=(12,6))
plt.plot(x,speed,c="gray")
plt.plot(x,fear,c="#1E9FDB")
plt.plot(x,embarrassment,c="r")
plt.plot([2.5,2.7],[3.9,2.3],c='k')
plt.plot([4.3,4.5],[3.6,3.1],c='k')
plt.plot(np.linspace(7.3,7.8,15),(0.25-(np.linspace(7.3,7.8,15)-7.3)**2)**0.5+7,c='k')
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
#plt.ylim([0,10])
ax.set_xticks([6,7])
ax.set_xticklabels(["STEPS","DOOR"])
ax.set_yticks([])
ax.text(2,4,"FEAR\nTHAT THERE'S\nSOMETHING\nBEHIND ME",horizontalalignment='center')
ax.text(3.9,3.4,"FORWARD\nSPEED",horizontalalignment='center')
ax.text(7.4,6.6,"EMBARRASSMENT")
ax.text(1,8,"WALKING BACK TO MY\nFRONT DOOR AT NIGHT:",bbox={'facecolor':'none', 'edgecolor':'black'})
ax.annotate("YARD", xy=(0.5,-0.3), xytext=(4.5,-0.4),annotation_clip=False,arrowprops={'facecolor':'black', 'shrink':0.01, 'width':0.5})
ax.annotate("INSIDE", xy=(10,-0.3), xytext=(7.5,-0.4),annotation_clip=False,arrowprops={'facecolor':'black', 'shrink':0.01, 'width':0.5})
plt.show()
```
[](https://i.stack.imgur.com/UV9mY.png)
] |
[Question]
[
## Background
A **fractal sequence** ([Wikipedia](https://en.wikipedia.org/wiki/Fractal_sequence); [MathWorld](https://mathworld.wolfram.com/FractalSequence.html)) is an infinite sequence of positive integers meeting the following conditions:
1. Each positive integer appears infinitely many times in the sequence.
2. Before the first occurrence of a number \$i > 1\$, every number smaller than \$i\$ appears at least once.
3. Between consecutive occurrences of \$i > 1\$, each number smaller than \$i\$ appears exactly once.
More formal definitions can be found on the Wikipedia and MathWorld pages linked above.
Fractal sequences are named as such because deleting the first occurrence of each number ([upper-trimmed subsequence](https://mathworld.wolfram.com/Upper-TrimmedSubsequence.html)) yields the original sequence unchanged.
A few notable properties:
* Decreasing all terms by one and removing all zeros ([lower-trimmed subsequence](https://mathworld.wolfram.com/Lower-TrimmedSubsequence.html)) gives another fractal sequence, which may or may not be identical to the original sequence.
* The [signature sequence](https://mathworld.wolfram.com/SignatureSequence.html) of an irrational number \$x\$ is a fractal sequence, and it is also identical to its lower-trimmed subsequence. The signature sequence of \$x\$ is defined as: sort the numbers \$i + jx\$ in ascending order where \$i, j \in \mathbb{N}\$, and extract the corresponding values of \$i\$.
A few notable fractal sequences:
* [A002260](https://oeis.org/A002260) and [A004736](https://oeis.org/A004736): Count each number upwards and downwards, respectively. These are also ordinal transforms of each other.
```
1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, ...
1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 5, 4, 3, 2, 1, ...
```
* [A054073](https://oeis.org/A054073): Triangle where the \$n\$th row consists of \$1 \cdots n\$ sorted in the order of fractional parts of each number multiplied by \$\sqrt2\$.
```
1,
1, 2,
3, 1, 2,
3, 1, 4, 2,
5, 3, 1, 4, 2,
5, 3, 1, 6, 4, 2,
5, 3, 1, 6, 4, 2, 7, ...
```
* [A122196](https://oeis.org/A122196) and [A122197](https://oeis.org/A122197): Count each number down by steps of 2, and count each number upwards twice, respectively. These are also ordinal transforms of each other.
```
1, 2, 3, 1, 4, 2, 5, 3, 1, 6, 4, 2, 7, 5, 3, 1, 8, 6, 4, 2, ...
1, 1, 1, 2, 1, 2, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, ...
```
## Challenge
Given a nonempty finite sequence \$s\$ of positive integers, determine if it is a prefix of some infinite fractal sequence. In other words, determine if \$s\$ satisfies the following:
1. (from condition 2 above) for each number \$n\$ appearing in \$s\$, every number \$i < n\$ appears before the first appearance of \$n\$, and
2. (from condition 3 above) for each number \$n\$ in \$s\$, every number \$i < n\$ appears exactly once between every consecutive appearance of \$n\$ AND at most once after the last appearance of \$n\$.
For output, you can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
### Truthy
```
[1]
[1, 1, 1]
[1, 2, 3]
[1, 2, 1]
[1, 2, 1, 3, 2, 1, 4, 3]
[1, 1, 2, 3, 1, 2, 3, 1, 4, 2, 5, 3, 1]
```
### Falsy
```
[999]
[1, 3]
[1, 2, 1, 3, 2, 1, 4, 1]
[1, 3, 1, 5, 3, 1, 7, 5]
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 22 19 17 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
*-3 thanks to Bubbler*
*-2 by further rearrangement*
```
×∘⊒⊸(/≡∨⊸/)∧⊢≡1+⊐
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgw5fiiJjiipLiirgoL+KJoeKIqOKKuC8p4oin4oqi4omhMSviipAKRsKo4p+oCiAg4p+oMeKfqQogIOKfqDEsIDEsIDHin6kKICDin6gxLCAyLCAz4p+pCiAg4p+oMSwgMiwgMeKfqQogIOKfqDEsIDIsIDEsIDMsIDIsIDEsIDQsIDPin6kKICDin6gxLCAxLCAyLCAzLCAxLCAyLCAzLCAxLCA0LCAyLCA1LCAzLCAx4p+pCgogIOKfqDk5OeKfqQogIOKfqDEsIDPin6kKICDin6gxLCAyLCAxLCAzLCAyLCAxLCA0LCAx4p+pCiAg4p+oMSwgMywgMSwgNSwgMywgMSwgNywgNeKfqQrin6k=)
Explanation:
```
×∘⊒⊸(/≡∨⊸/)∧⊢≡1+⊐ #
×∘⊒⊸( ) # Between the sign of the running occurrence count and the input:
/ # filter (removing first occurrences)
≡ # and match against
∨⊸/ # the equal length prefix of the input (sorts down the boolean mask, bringing 1's to front)
∧ # and
⊢≡ # does the input match
1+⊐ # its classification + 1
```
Why it works:
Classify (`⊐`) assigns each unique element a number (starting from 0) according to the order of first appearance. That means that if the input matches its classification (+ 1 since starting from 0), every number less than n appears before n, thus satisfying condition 2.
For condition 3, we can use the useful property of fractal sequences that if the first occurrence of each element is removed the result remains the same. Since this is not an infinite sequence we simply check if the remaining sequence is a prefix of the input.
[Answer]
# JavaScript (ES6), 52 bytes
Returns *false* for valid or *true* for invalid.
```
a=>a.some(v=>v^=a[~v]^=a[~v]?v-a[j++]&&-1:++i,i=j=0)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5Rrzg/N1WjzNauLM42MbquLBZK2ZfpJkZnaWvHqqnpGlppa2fqZNpm2Rpo/k/OzyvOz0nVy8lP11CPDkvMyUyJVdfkQhZO04g2jNXEFNNRACHsMkY6CsY4ZXDrAZLGMIYJTiOg5qMyTMBsUwgXpA9Fo3pMXrRnXhkO71laWmK3yZhYl@LwEsRppjCGOZANVPgfAA "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array, re-used as an object to store
// a 1-indexed ID for each unique value in a[]
a.some(v => // for each value v in a[]:
v ^= // test whether v is different from:
a[~v] ^= // the updated value of a[~v]:
a[~v] ? // if this is not the first occurrence of v:
v - a[j++] // leave a[~v] unchanged if a[j++] == v
&& -1 // otherwise: XOR it with -1, which forces
// the comparison with v to fail
: // else:
++i, // increment i and set a[~v] to i
i = j = 0 // start with i = 0 (ID of unique values)
// and j = 0 (pointer in a[])
) // end of some()
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~91~~ 65 bytes
```
f=lambda s:s and{*s[-max(s):]}=={*range(1,max(s)+1)}and f(s[:-1])
```
[Try it online!](https://tio.run/##dY9dCoMwEITfc4rFJ2MjNP5QFNKLhFBS1LagUUwKLeLZrRrFliIsy5dhZyfbvM29VuEwFKyU1TWToFMNUmWdp7lfyZercSp6xjqvleqWu5RY8UBxP45B4Wqe@lTgweTa6Itpnzkw4JwKgjglMNWCAYFwwy917OEK0Ta0WH4hmjm2TyEQsrmFLLUNTpJk8Ye7CWu2XRmvcBp5WlnULRh4KNhuShE07UMZ1xBw2Nkh4@UGY4Ss6viOFxzxn3X@1o53@AA "Python 3 – Try It Online")
uses the empty list `[]` as truthy value and `False` for falsey
## How it works :
* `s and` : if the list is empty, return it (truthy value)
* `{*s[:-max(s)]}=={*range(1,max(s)+1)}` verify that all numbers are present once in the last chunk of the list;
* `and f(s[:-1])` if the above is `True` (the last item doesn't contradict the sequence), it tests the list truncated to the last item.
By recursivity, it check that all items are correct
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page)
```
ṀRḟṣṪṪƊƲƤ⁼W€
```
A monadic Link that accepts a list of positive integers and yields `1` if a prefix of some infinite fractal sequence, or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8///hzoaghzvmP9y5@OHOVUB0rOvYpmNLHjXuCX/UtOb////RhjoKQGSko2CMyjABs00h3FgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzoaghzvmP9y5@OHOVUB0rOvYpmNLHjXuCX/UtOb/4XYQ@T862jBWRyHaUEcBhKBMIx0FYwQTSRRIGsMYJghFUC2oDBMw2xTCBSm0tLSEqjfGaSLMLogRpjCGOZAdGwsA "Jelly – Try It Online").
### How?
Checks that every non-empty prefix contains all integers up to and including its maximum *after* the penultimate\* occurrence of its ultimate value.
\* If a prefix only has one occurrence of its ultimate value then the whole prefix is used.
```
ṀRḟṣṪṪƊƲƤ⁼W€ - Link: list, L
Ƥ - for each non-empty prefix, P, of L:
Ʋ - last four links as a monad, f(P):
Ṁ - maximum -> M
R - range -> [1,2,3,...,M] = X
Ɗ - last three links as a monad, f(P):
Ṫ - tail -> ultimate value = U
ṣ - P split at occurrences of U
Ṫ - tail -> values after "penultimate" U = T
ḟ - filter discard -> X without any of T
W€ - wrap each of L in a list
⁼ - equal?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
Ù0.;0KÅ?IηεÙZLQ}P*
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8EwDPWsD78Ot9p7ntp/benhmlE9gbYDW///RhjoKQGSko2CMyjABs00h3FgA "05AB1E – Try It Online")
-5 thanks to @ovs
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
⬤θ⬤…¹ι∧№…θκλ›⁼№…θκλ⁺№…θ⌕θιλ№…θκι›№θλ⁺№…θκλ№θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEcBRAUl5qWnahjqKGRqAgXyUjSc80uBKpwrk3NSnTPyC0DqsoFSOUDsXpSaWJJapOFaWJqYU4xPZUBOKVZ5t0ygDYUgy6AKcZgBlEeyD6KoEL/R2SgmQuyAAOv//6OjgT4EIiMdBWNUhgmYbQrhxsb@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a fractal sequence, nothing if not. Explanation:
```
θ Input array `q`
⬤ All values `i` match
…¹ι Range from `1` to `i`
⬤ All values `l` match
…θκ Prefix of `q`
№ λ Contains `l`
∧ Logical And
№…θκλ Count of `l` in prefix
⁼ Equals
№…θ λ Count of `l` before
⌕θι First `i` occurrence
⁺ Plus
№…θκι Count of `i` in prefix
› And Not
№θλ Count of `l` in `q`
› Is greater than
№…θκλ Count of `l` in prefix
⁺ Plus
№θι Count of `i` in `q`
Implicitly print
```
For a given positive integer `i` appearing in the input sequence `q`, each positive integer `l<i` must pass the following tests:
* `l` must appear before the given occurrence of `i`
* The number of times `l` appears before the given occurrence of `i` equals the number of times `l` appears before the first occurrence of `i` plus the number of previous occurrences of `i`
* The number of times `l` appears in total must not exceed the number of times `l` appears before the given occurrence of `i` plus the number of occurrences of `i`
Note that the first and third tests are only useful for the first occurrence of `i`, but it's golfier to uselessly test them for each occurrence.
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
Based on wasif's 05AB1E answer.
```
import Data.List
f x=isPrefixOf(x\\nub x)x&&[1..maximum x]==nub x
```
[Try it online!](https://tio.run/##ZYzBCsIwEETvfsWeSgshENsiPeTmUdF7GiRCg4tNLW0K@/cxjdWLLMzsMm/2YeZn1/choBtfk4ej8YafcPY7CyRxvk6dRbrYnNp2WO5ABWWZEpw7Q@gWB6SlTEFwBgeQ4Mx4vkE@Tjh4bgtQSmimBIuTfM/Kzb@3YGXSaksS89Mqer1uMWuaJhHlX/Pza@UTyw6s1jq8AQ "Haskell – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), 125 bytes
Golfed version. [Try it online!](https://tio.run/##lVHfS8MwEH7fX/FRxkhkK@4XsmEG@iAI6oPTpyESu3Srds1MTlFK//aathuurA8akvDd5e677y42kLHM9curCgi3MkqQ5ksVImR2Olfvi@uEnvj0UutYyURYbCQF6zSQVuEuisWMzIdCaT6LmfVJvqn7aLUmZv2N/OI@6bkiIVgfpHHo63RcCX9p9PYwnmc5UNTfOClMmpWd4sIY@b2Yk4mSldOCxyQiCKQtuPUpY5CyZB8KIQI3kSVWvqDCfd6tmV0U@8g56GLY5GyMdPdwD0ZNiTvCOhiVeFyZvMzgrXoTVzK2jV1MJpOjIsM/SDuWX2kZ78GZwzUtoTZghPPe71j5btbA1v0BxQmzXjulDGKGdhoy4plXcWQVxz7M63k4weC0mbps9j/cxcla@Q8)
```
def f(s:Seq[Int]):Boolean=s match{case Nil=>true case _=>s.takeRight(s.max).toSet==(1 to s.max).toSet&&f(s.dropRight(s.max))}
```
Ungolfed version. [Try it online!](https://tio.run/##lVJdS8MwFH3vr7iUMRLpivtCNqygD4KgPjh9GiKxS7tql4zkKsrob69Jm1FL@6DQj5PTc27PSatjlrOylK9vPEa4Y5mAgwew4QkkRC/hNtO4vhH4TJdwJWXOmYAINOwYxttKChAzzeE@yyG6AFQfvCFfDFWtAD5Zbkxf1hya@y9WMZFyw5MxoLQaGqJccXQSHSJ75w9ZukXSPIQocsbh0CYNN0ruGxE15sJzRXamFWEqNXUulWLf6xWqTKS20pPIzCjXw4ZBrlE/mhKGtd2JS1HhMQ1aywDs0SEnAUz7yF6luU6PYNZndAPbYFbheb2klYN67RLXLNe9LRaLRecl0z9E68avs8yP4MzgVpZEKiAI56NmW6nba4C9@QaYC6L9wQEL@@8MDglBWvj1jKKecZT5Ix9OYHLaP7oq@5/Z9iy8svwB)
```
object Main {
def f(s: List[Int]): Boolean = s match {
case Nil => true
case _ =>
val max = s.max
val range = (1 to max).toSet
s.takeRight(max).toSet == range && f(s.dropRight(max))
}
def main(args: Array[String]): Unit = {
val testsTrue = List(
List(1),
List(1, 1, 1),
List(1, 2, 3),
List(1, 2, 1),
List(1, 2, 1, 3, 2, 1, 4, 3),
List(1, 1, 2, 3, 1, 2, 3, 1, 4, 2, 5, 3, 1)
)
val testsFalse = List(
List(999),
List(1, 3),
List(1, 2, 1, 3, 2, 1, 4, 1),
List(1, 3, 1, 5, 3, 1, 7, 5)
)
for (t <- testsTrue) {
println(s"${t} => ${f(t)}")
}
println("-" * 20)
for (t <- testsFalse) {
println(s"${t} => ${f(t)}")
}
}
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 113 bytes
```
(a=Union@#;f=1>0;Do[f=f∧First@(s=Split[#,#=!=e&])⋂(l=Range@(e-1))==l;(f=f∧l⋂#==l)&/@s[[2;;-2]],{e,a}];f)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPRNjQvMz/PQdk6zdbQzsDaJT86zTbtUcdyt8yi4hIHjWLb4IKczJJoZR1lW0XbVLVYzUfdTRo5tkGJeempDhqpuoaamra2OdYaEF05QFllIF9TTd@hODrayNpa1yg2Vqc6VSexNtY6TVPtf0BRZl6JQ7pDtaGOAhAZ6SgYozJMwGxTCLeWC1k9RIEpjGEOZNf@BwA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Your task is when given a chemical formula as input, output the total number of atoms in the formula.
### Input
A chemical formula in any reasonable format. Each chemical formula has the following:
* A leading coefficient, which is a number \$N > 1\$.
* At least 0 groupings of elements surrounded by parentheses.
+ Groupings can have both elements and groupings inside of them.
* At least 1 element.
+ Elements match the regex `[A-Z][a-z]*`.
* Each grouping and element can have an optional subscript, which is an `_` followed by a number \$N > 1\$
### Output
The total number of atoms in the formula. Rules for counting are as follows:
* A coefficient before the formula multiplies the total count that many times.
* A subscript multiples the group or atom it follows that many times.
* An element with no coefficient or subscript represents 1 atom.
### Testcases
```
In -> Out (Notes)
H_2O -> 3
CO_2 -> 3
Co_2 -> 2 (2 cobalts)
3 C_2H -> 9
EeeEeuEetUue -> 4
3 (C_21H_30O_2)_3 -> 477 (= 3 * (53) * 3)
32H -> 32
C_10H_16N_5O_13P_3 -> 47
(Ga(U(Y_2)_3)_4)_5 -> 145 (= (1 + (1 + (2 * 3)) * 4) * 5)
Ti(Ca_2(HSO_4)_2)_2 -> 29 (= 1 + (2 + (1 + 1 + 4) * 2) * 2))
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# JavaScript (ES6), 87 bytes
```
s=>eval(s.replace(/[A-Z][a-z]*|_|^\d+|\(/g,s=>+s?`n=${s};n*=`:s>{}?"*":"+"+(s>"0"||s)))
```
[Try it online!](https://tio.run/##jdDfT4JQFAfw9/4KdtfDuRACF8hpA9cYi6doKx9K7XiHV2dj4LzqQ@LfTtiy5qW2zvPnfM@PN77jMlsvVxuzKGeinge1DEKx4znIzlqscp4JsEa35stkxM33iV5h9TqeGdUYrMVVQw05mBbB5V4ebgo9mPZluD8MiE76xCAGyJDYpKokpbTOykKWuejk5QLmQBJkKdHOi1LNsjT3QqFRiuy/tPyLMpW6WoQsIb/QnkpjIWKxjcVmuBXkjHrtVGhinQRdu9maoku@abfbwur8n8Na60bo2Ak61/fop@i4D8fkU7Bq4Y7DEJ4/51P0KPon63i@ip@WEHFkkDymR9r0MPL1sl79AQ "JavaScript (Node.js) – Try It Online")
### How?
Matched patterns and replacements are summarized in the following table.
```
pattern | replacement
-------------+-------------------------------------------
[A-Z][a-z]* | "+true"
_ | "*"
^\d+ | "n=N;n*=" (where N is the matched number)
\( | "+("
```
For instance, `"3 (C_21H_30O_2)_3"` is turned into:
```
"n=3;n*= +(+true*21+true*30+true*2)*3"
```
This string is simply evaluated as JS code.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~81~~ 79 bytes
```
\d+
$*
(1+) (.+)
($2)_$1
[A-Z][a-z]*(_|())
$#2$*
+1`(\((1+)\)_)1|\(1+\)_
$2$1
1
```
[Try it online!](https://tio.run/##HYuxCsJAEET7/YqAJ@wmKNk9tZcjeJUR1EKTsAa8wkZBtBH/PW5shuHNm2d63e79MMXNZWivBbgckAvKcF4QoBNSx9CsZ@eu6WefLkf9IhG4iZhZ8AVbHP2WlPjbWrUGTuzEwxBVagi1CoSHhc@CSoQqpSq9q/Q6vpMxNMhRfWkeqQcvWYSgXEbl1VaXtbLfGcdNj0c8/SXSBekSDjcMvQrGfT0CW@QH "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert the numbers to unary.
```
(1+) (.+)
($2)_$1
```
Turn any coefficient into a group.
```
[A-Z][a-z]*(_|())
$#2$*
```
Delete all elements with suffixes, but if an element did not have a suffix, then replace it with `1`.
```
+1`(\((1+)\)_)1|\(1+\)_
$2$1
```
Multiply out all of the groupings. (These have to be done one at a time to be able to collect the results correctly.)
```
1
```
Convert to decimal.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 57 bytes
```
y/_a-z/*/d;s/^\d+\K.*/*($&)/;s/\pL/+1/g;s/\(/+(/g;$_=eval
```
[Try it online!](https://tio.run/##NY9BS8QwFITv@RU5LPLSUt8maVyWZb2UYkCxgu5BKD6iG2Sh2GK7gv54a9LWQybDDPPB6/xnY8YeeXZ9mSDuxm8kl/1ggsddjy/1Ma1vQ5HA6kJgSOruDlOJ79ECphDcivb@yzXjaElVgcM1KypSi2tnpzgo/ta@umboBdO8IGVjvmWl96U/l344nH1M8tBCqKUlvQ4cQXqKNxsOe655wsFoET4dODNEK1aQXFuSV/dkKpL64X/E4MbBAZ4njqBckImFzE2kgeTpImoiRm4exQj2dILCkQL7WMVdAMyXbONy2Szr@KaZmkX8tt1waj/6MeuaPw "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 88 bytes
*A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/216728/83605) in Ruby!*
```
p eval gsub(/_|\(/,?_=>?*,?(=>'+(').gsub(/[A-Z][a-z]*/,'+1').gsub /^\d+/,"k=#{'\&'};k*="
```
[Try it online!](https://tio.run/##LYpba8IwGEDf8yuKgvl6MyZRX6QtI5TlaRWcD2r1o8UwRLGiVtjFv74sbns5D@ecc1u/W3vyzK06eG@XtgaGXyWwKMMkzYIogySlIVC//xdXT/Fyvarij3XAIhry/@CxTbkNWdTZJ91PWvbofbIPko61GkVBVIGCqMZBegqFJrkxuWlzc523xjlwkmuUA/f5KIl0i0I@0MjHLzgqkMup0/BcwRwWv4@PQx9H5HUHqkIBelY8hCviuzldd83xYuPj4Qc "Ruby – Try It Online")
[Answer]
# [PHP](https://php.net/), 111 bytes
```
eval('$n='.preg_replace(["/^(\d+)/","/[A-Z][a-z]*/","/_/","/\(/"],['$1;$n*=',"+1","*","+("],$argn).';');echo$n;
```
[Try it online!](https://tio.run/##jdBda4MwFAbg@/0KCYInVk3jx0pxZQxx82oOtl5s1h3EZbYgKq7dxX58XSrrRnWDBRJI8uQ9SZp1011cNnIU71kJmlotNKtpRYGtaMosF5AQ9gyrlwllxCAsuTKf0iQzP1K9n2M/roCR1Eg0lftqpS80g0y4XNdln4DcUbO2qKil@Rr1Rb6u1crvmJ7X1VtdCqusC3gFEqEdE@W0UaowpjhnAxrEaP@X1n9Re0gdJUA7Ir/Q@ZCGQoRiF4rtcifICXXHqSBjeYTOVN6aokO@6Ww2wsP6Pw8bXTdAPo2Qn9@iFyN37g7Jx@ChhZsMlvDY16foUvSOlrveED9sIMjQhug@PlB5xiZfXzbXWTd60L5uthsZ0ZnXnw "PHP – Try It Online")
Just a port of [Arnauld's clever trick](https://codegolf.stackexchange.com/a/216728/90841) with `eval` and some adaptations:
* in PHP it was shorter to use a list of regexes instead of using `preg_replace_callback` (what a long function name)
* the evaled string has to be valid php prefixed with `$n=` and ended by `;` (in PHP `eval` does not return the result), example with "Ti(Ca\_2(HSO\_4)\_2)\_2": `$n=+1+(+1*2+(+1+1+1*4)*2)*2;`
* output of `$n` has to be explicit
Longer than what I thought, but "c'est de bonne guerre ma bonne dame", it's our good old PHP after all
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 92 bytes
I think there's definitely some room for optimization here; A lot of the bytes are just there to handle the cases with the leading "\d "
```
$t=1;-split$args|%{$t*=$_-replace'\(','+('-creplace'[A-Z][a-z]*','+1'-replace'_','*'|iex};$t
```
[Try it online!](https://tio.run/##pZNRb5swEMff8yksyx0mCVOBZNVSIWXLsvKUVGuraWPIYuSWoVJgtlG7JXz21EBDmSKWSvOL73zn3/19trP0Hrj4CXG8Iz/yJJRRmjg9pMZmR6RjnhsiiyNJAr4W25MNkX2HMINDFgchaN@oNtQGVDPC/Yr3zvjqe4Hxx@@XIVNrcpny@9o2gofinMhd0SMShJwFAgRy0JRWRaebaipHlGS5LI0yiF1mLbHeBOEhg1DCqg7aT5Fi2Ll/tmTW/@y30YxZbifh7XHCHGAO@RzkTQ6dnNFLlFAlxXSZfarOpDO7G3Z29oLGMPPUZeabBRsvmWlf/pN3HEcvAnpDv1TCdDbS2bgTZ47Gx3nXEZ0FzKLu1bKkKWz3NVrNLfT09uvaohO0qfxFfvcduGMWdTlS1Roi0uIQ9rpeVcZ@uU7mIPJYqpRXzU9B0yq3jos8DEGUjxk/5WJkwC/l7Tm4SvzMIwmGmwqJsHetVKGWNh9hdDiMRbqA@zhK4JBAKNU@BlGcc1A/7KoWoeneXo@v@7hNQMb7ILxd8zRPVrM0TjlSgA8Bv/0EKwUorQsOkPyFOCg7Qc9n7BantGHkzffdbRrh46EnJI@StT@ZzO8y@btdDKO6oc9dGQx6xe4R "PowerShell – Try It Online")
# Honorary Mention, PowerShell, 99 92 bytes
This was my first solution, and I really liked it. Including it here because I think it's fun.
```
$o="'-creplace'";"'$args$o^(\d)(.*)','`$1*(`$2)$o\(','+($o[A-Z][a-z]*','+1$o`_','*'"|iex|iex
```
[Try it online!](https://tio.run/##pZNhb5swEIa/51dYljdMEqoCyaplipSNsfIpqdZW00aZw8gtQ6WYGqN2TfPbMwNNyhSxVJolxJ3v/Nzrs53xOxD5L0iSDflZpJGMeTruIDVWG8LHWDMiAVkSRqDhd1gjoVjmhH@nVwudHnV1ra/Nidmlc2LphF9R5fco4f5741vgh8ZD0C1nTMLnTBldDT/GcF9@m3WHSMilE@aQozGa0KroZFX9yhGnWSFLowxij1kzrO@CcJ9BJGFRB@2nyLrfut6ZMet/1tvIYZbXSnh7mOACuFC4IC8LaOUMXqKEKimmx@xjtSed2e2wk5MXNIaZxx4z30zZcMZM@@yfvMM4ehrSS/q1Eqazgc6GrThzMDzMu4ipEzKLeuezkqaw7cdo7U6hozdv1yN6hVaVPy1ufoAYm@u6HKlq9RFpcAg7qmeVsZ2ukwXkRSJVyuvdS0GTKreO50UUQV5eZvyUi5EBt8rbcnCV@EXEEgyP5xJh/0KpQg1tAcJofxhTPoW7JE5hn0Ao1T6FcVIIUE/svBah6f5WT6AHuElAxocwul4KXqQLhydcIAX4GIrrz7BQgNI6FQDpX4i9siP0vMd2cUobRr677e6uEQHu@7kUcboMRiP3JpO/m8Uwqhv63JVer7Pe/AE "PowerShell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~84~~ ~~83~~ 88 bytes
inspired by `Honorary Mentioned Solution` by [Zaelin Goodman](https://codegolf.stackexchange.com/a/216785/80745)
-1 byte thanks to Zaelin Goodman
+5 bytes the `32H` test case added
```
$o="'-creplace'"
"'$args$o^\d+','`$0*($'')#$o\(','+($o[A-Z][a-z]*','+1$o`_','*'"|iex|iex
```
[Try it online!](https://tio.run/##VZBdT8IwFIbv@ytOZrUdjIR9IDGEBLKgu3IkyIUCljkOihkp7iMSgd8@u8kAL5q073OenpOzkd8YJx8YRTldQhd2OZVdjTXCGDdRECLTiMZoEL8nVL5OF3VmsDlt1jhlTL@icspVUOdUTvqNl9kkaPzMakViUjkX6lJj2n6F2@LkB0J6nBCDA9iWAcy2PAZ6@QZbvT1h@f8C1xfWKbgrDHDFheSoaIA4wGyA6TjDI3Da7bKWq2LTE3ZTfaMLu9KcgrrCbHrCvH0ULV@Y9vCETaelMH8I@Jg/l54uHF20Ktsq5nhacTcQFvdGfgFVVTkn0WEP17AjajaguN1gmOLCALqU8TqLArVeKv5gjEkWpSq4UVuveIkmw8TNklSu/bdP5c96OxhlYYhJUuhHr4Ff5wYd6KvyC9yB@3PDqveBHPJf "PowerShell – Try It Online")
Powershell expands the formula `32H` to:
```
'32H'-creplace'^\d+','$0*($'')#'-creplace'\(','+('-creplace'[A-Z][a-z]*','+1'-creplace'_','*'
```
The first `iex` calculates this expression to:
```
32*+(+1)#+1
```
The second `iex` calculates the expression before the comment to `32`.
---
Another example. Powershell expands the formula `3 (C_21H_30O_2)_3` to:
```
'3 (C_21H_30O_2)_3'-creplace'^\d+','$0*($'')#'-creplace'\(','+('-creplace'[A-Z][a-z]*','+1'-creplace'_','*'
```
The first `iex` calculates this expression to:
```
3*+( +(+1*21+1*30+1*2)*3)# +(+1*21+1*30+1*2)*3
```
The second `iex` calculates the expression before the comment to `477`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
AмAuS„+1:'_'*:'(„+(.:.γd}ćDdi'*«}šJ.E
```
Similar approach as the other answers, except without regex. Especially the `^\d+` to `N*` therefore costs quite a few bytes (16 to be exact: `.γd}ćDdi'*«}šJ`).
[Try it online](https://tio.run/##yy9OTMpM/f/f8cIex9LgRw3ztA2t1OPVtazUNUAcDT0rvXObU2qPtLukZKprHVpde3Shl57r///GChrO8UaGHvHGBv7xRprxxgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf8cLexxLgx81zNM2tFKPV9eyUtcAcTT0rPTObU6pPdLukpKprnVode3RhV56rv91/nvEG/lzOfvHG3E55wMJYwXneCMPLtfUVNfUUtfUktDSVKCYBlDQ0CPe2ACoTjPemMsYqMQ53tDAI97QzC/e1D/e0DgAKKzhnqgRqhEJVqMZb6IZb8oVkqnhnBhvpOER7A8SAMoYAQA).
**Explanation:**
```
Aм # Remove all lowercase letters from the (implicit) input-string
AuS„+1: # Replace all uppercase letters with "+1"
'_'*: # Replace all "_" with "*"
'(„+(.: '# Replace all "(" with "+("
.γ } # Adjacent group the string by:
d # Whether it's a digit
ć # Extract head; pop and push the remainder-list and first item
# separated to the stack
D # Duplicate this first item
di # Pop, and if it's a (non-negative) integer:
'*« '# Append "*" to it
} # After the if-statement:
š # Prepend the potentially modified first item back to the list
J # Join everything together again
.E # And evaluate and execute it as Python code
# (after which the result is output implicitly)
```
[Verify all test cases without the `.E`.](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf8cLexxLgx81zNM2tFKPV9eyUtcAcTT0rPTObU6pPdLukpKprnVode3RhV7/df57xBv5czn7xxtxOecDCWMF53gjDy7X1FTX1FLX1JLQ0lSgmAZQ0NAj3tgAqE4z3pjLGKjEOd7QwCPe0Mwv3tQ/3tA4ACis4Z6oEaoRCVajGW@iGW/KFZKp4ZwYb6ThEewPEgDKGAEA)
] |
[Question]
[
## Background
**[Shakashaka](https://en.wikipedia.org/wiki/Shakashaka)** is a puzzle on a grid, whose objective is to place some *half-squares* (right triangles) on the empty cells so that all the remaining contiguous regions form rectangles, either upright or 45 degrees rotated. Here is an example puzzle with a solution:
[](https://i.stack.imgur.com/lJrTK.png) [](https://i.stack.imgur.com/sRoM2.png)
Ignore the number clues for this challenge.
## Challenge
Given a grid with black squares and half-squares placed on some of the cells, determine if it is a valid solution to some Shakashaka puzzle, i.e. all the white regions form rectangles.
The input is a 2D grid (in any valid form) with each cell containing its encoded state. Each cell will be in one of the six states: white square (empty), black square, and four possible orientations of the half-square (NW, NE, SW, SE). You may encode them as six distinct numbers or (possibly multi-dimensional) arrays of numbers, and you can use characters instead of numbers (so strings or string arrays are also acceptable).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Because it is pretty hard to reproduce a Shakashaka board with Unicode chars, I include a Python script to convert the input to any form of your choice. The default configuration renders them using Unicode geometric shapes, so you can roughly see how the actual grid will look like.
```
def gentest(tc,mapping,charjoin='',linejoin='\n',preamble='',postamble=''):
return preamble+linejoin.join(charjoin.join(mapping[x] for x in line.split())for line in tc.strip().splitlines())+postamble
```
[Try it online!](https://tio.run/##bVRLj4IwEL73V8ytENH4fiVeSLxy8cDB9cCyqGywEiiJZrO/3e10Wqi6CRnab7755pFMy7s8X8Xk8fjKjnDKhMxq6ck0uCRlmYtTkJ6T6vuaiw3nQZGLjM4fggdllSWXzyJDT3mtpb34awZQZbKpBFhOz4YO0HhWlG4m1f52gOO1ghvkApA/qMsil57vI4oAOmQ6qGWVl55PbsRrxem1JTyM3uZH1cFDDmv@0YxnyZAHCMQtMCJgt@UEZGMDxBaYEBC1wNQAbciMs18m05Hqm7MohmgLMeAXakuItmwXa8RckaCQ3ZYse752sajDnpXQ2YrFmBUBG0mJzZm1GMEvJYXQKdLZUTLCJg108m47xA8dWY107cROObYonJVMx3pm5I/f/sSZuHM1zViO1ZlqDrUYvv3Rp0gzTVKFUczc5o5ofgZe2HS6f8KWHdWdtx6LGUL40rKJXNnCqGKDjobPguGrYDt/za8aeb4Hx6So77CBvYoP1A6M0UzQTA8BojM8z9Es0CzRrNCMhgfGcIFwsesml3qLPFdXL6ympHrDLBFhUCucC@n98zK4rwES3RdB333fEeD9fp/7jz8 "Python 3 – Try It Online")
### How to use it
```
tc - the testcase string, which will be supplied in the footer
mapping - the dict of 6 keys 'B', 'W', 'NE', 'NW', 'SE', 'SW' mapped to
6 distinct strings
'B' is filled (black) square, 'W' is white square,
the rest four represent half-cell filled in that direction
charjoin - string to insert between each cell on a horizontal line
linejoin - string to insert between each line of cells
preamble - string to add in front of the entire grid
postamble - string to add at the end of the entire grid
```
---
Alternatively, you can use this Stack Snippet kindly written by @Arnauld to better visualize the test cases (it shows the 10 test cases by default):
```
function draw2() { let grids = document.getElementById("in").value.split('\n\n').map(g => g.split('\n').map(r => r.split(/ +/))), out = ""; grids.forEach(g => { out += '<div class="wrapper" style="width:' + g[0].length * 17 + 'px;height:' + g.length * 17 + 'px;">'; g.forEach(r => { r.forEach(s => { out += '<div class="cell"><div class="cell ' + s + '"></div></div>'; }); }); out += '</div>'; }); document.getElementById("out").innerHTML = out;}window.onload = () => { document.getElementById("in").value = [ "NW NE W W B W NW NE NW NE", "SW W NE NW NE B SW SE SW SE", "B SW SE SW SE W NW NE B W", "W NW NE NW NE W SW W NE W", "NW W SE SW SE B W SW SE B", "SW SE B B W W NW NE NW NE", "B NW NE W B NW W SE SW SE", "NW W W NE W SW SE B NW NE", "SW W W SE B NW NE NW W SE", "B SW SE W W SW SE SW SE B", "", "W W W", "W W W", "W W W", "", "NW NE W", "SW SE W", "W W B", "", "B B B", "B B B", "B B B", "", "SE", "", "W NW", "NW W", "", "NW W SE", "", "W NW NE W", "NW W W NE", "SW W B SE", "W SW SE W", "", "B W", "W W", "", "W NW NE B", "NW W W NE", "SW SE SW SE" ].join('\n'); draw2();};
```
```
textarea { width: 400px; } #wrapper, .wrapper { border-left: 1px solid #555; border-top: 1px solid #555; margin-top: 10px; } .cell { float: left; width: 16px; height: 16px; border-right: 1px solid #555; border-bottom: 1px solid #555; overflow: hidden; } .NW { width: 0; height: 0; border-right: 16px solid #fff; border-top: 16px solid #00b496; } .SW { width: 0; height: 0; border-right: 16px solid #fff; border-bottom: 16px solid #00b496; } .NE { width: 0; height: 0; border-left: 16px solid #fff; border-top: 16px solid #00b496; } .SE { width: 0; height: 0; border-left: 16px solid #fff; border-bottom: 16px solid #00b496; } .W { width: 16px; height: 16px; } .B { width: 16px; height: 16px; background-color: #000; }
```
```
<textarea id="in" oninput="draw2()"></textarea><div id="out"></div>
```
---
### Truthy test cases
```
# The 10x10 puzzle solution above
NW NE W W B W NW NE NW NE
SW W NE NW NE B SW SE SW SE
B SW SE SW SE W NW NE B W
W NW NE NW NE W SW W NE W
NW W SE SW SE B W SW SE B
SW SE B B W W NW NE NW NE
B NW NE W B NW W SE SW SE
NW W W NE W SW SE B NW NE
SW W W SE B NW NE NW W SE
B SW SE W W SW SE SW SE B
# all white
W W W
W W W
W W W
# a diamond and some rectangles
NW NE W
SW SE W
W W B
# all black
B B B
B B B
B B B
```
### Falsy test cases
```
# a triangle
SE
# a larger triangle, with a valid white square
W NW
NW W
# a parallelogram
NW W SE
# a slanted square with a black hole in the middle
W NW NE W
NW W W NE
SW W B SE
W SW SE W
# a region that contains two rectangles but is not a rectangle by itself
B W
W W
# same as above, but 45 degrees rotated
W NW NE B
NW W W NE
SW SE SW SE
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 179 bytes
```
lambda C:all({'','11','1'*4}>={*bin(65793*(a&3|c&12|d&48|b&192)).split("0")[2:-1]}for
i,j in p(C,[0]*len(C[0]))for(a,b),(c,d)in p([*zip(i,j)],(0,0)))
p=lambda l,d:zip([d]+l,l+[d])
```
[Try it online!](https://tio.run/##hVTBcoIwEL3nKzIeJMG0A2pbZYYecLxy8eAh5QCiLR3EjDhTW/XbbRICEo0to5C8fS9vd2GWfe8@NsVgxLbn0n875/E6SWM48eI8RwfLIpbriptlD0@v/sFOsgI9P72MBzaKu4Pjouv2j2l3ODomXXfcx/ixZHm2Qx2ng2nfe3Cj02qzBRn5hFkBGZoQ6kR2vizQhC8w5kEUkwQTtCAplhRq/2QMcQWOCHKIgzEGzFd55ST1RJimUS8neY8/8XkRl8vSp4BSK5zzZMMpv83VP1DPS6ReRQRQa1bztFAlk7HZtLWSEnPo2qXylQKzfSXQ/ZUgrMErh6AtUsilioYStMq/U3Zwk0iDmItuQrfZN77mxhopupehrfMbB63oCBDxui8eTaPNW8UPrzvdNtQ0F4@g6WqTpnmr@KKeVnqh/k61TOrydfqdb8HY3OCPBrYL0Koz@wX/@ekfhTgjAuuYsax49w8AQn4C9JzEURcR0FxCrrokxMUCclz@Uyx@qGQJwK2gUEIVoIShFFaAw6ETYNus2KFV51CncepgwEcKFBNBDBw5GTwuhrDilohSRab7CAruXhC3m69qxxe1kI@n8y8 "Python 3.8 (pre-release) – Try It Online")
mapping=`{'B': 0, 'W': 255, 'SE': 180, 'SW': 210, 'NW': 75, 'NE': 45}`
Mapping visualization:
[](https://i.stack.imgur.com/BxnZ1.png)
The numbers are the bit position (least significant bit position is 0). Black has value 0, white has value 1. With this bit order, some simple bitmasking will give the state of the 8 triangles around a corner.
Use the [method that I posted in chat](https://chat.stackexchange.com/transcript/message/54727649#54727649).
Other key ideas for golfing:
* `65793 = 0x10101`.
* `{'','11','1'*4}>={*bin(65793*X).split("0")[2:-1]}` checks the condition with `X` a 8-bit number.
The function `p` returns the consecutive pairs in the list `l`, with the added first element `(d, l[0])` and last element `(l[-1], d)`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~667~~ ~~554~~ ~~526~~ 461 bytes
*-49 bytes thanks to @ovs and @pppery*
```
C=eval(input())
N=next
E=enumerate
def F(x,y,f):
try:1/-~x/-~y;c=C[y][x];(x,y)in v<Q;n[c]+=1;c&f<1<Q;C[y][x]=0;v[:0]=[(x,y)];[c>>i&1and F(x+i%2*(2-i),y+(i-1&~i),1<<(i^2))for i in(0,1,2,3)]
except:1
while l:=[(x,y)for y,r in E(C)for x,e in E(r)if e]:
a=0;v=[];n={k:0for k in range(16)};F(*l[0],15);a=len(v)+n[15];(len(v)!=n[15]or(N(M:=map(max,zip(*v)))-N(m:=map(min,zip(*v)))+1)*(N(M)-N(m)+1)!=a/2)and(a!=4*n[6]*n[12]or n[6]!=n[9]or n[3]!=n[12]or n[0]>0)and z
```
[Try it online! (all testcases)](https://tio.run/##dVRdb5swFH33r3AzrbUTJ7FJoQ3Efanat1WatDfGJkSc1SoxyNAAnda/ntl8tVk1FMg999x77jFg8qZ8zNTqOtdHwSeTyfGWi0OcIqny5xJhDB64EnUJ7rhQz3uh41KArdjBe1SThuywD2CpG58t56@1OZsg4bdhE4V1FNgKLBU8bL4GKkyiGWdBcr7bMIP7Gk6DQ@jTiIdtcRSEyc2NPGex2toJM/nZmSJnLjFpZkjO2fmrCdlmg@QPB@NdpqGEUiFKGHHICkcAijoReekzUD3KVMDU76VtbUNMvYJ36LaFNREd1FjuoIjMUmJriIdRoPjvJ5/aqidbo2P1SyDm4T/BPZqmIY0Ic3EQ81QodMAzFTLXLLhDZ7yFmUYP6IvP93GO9nFNXmSOpgeM8fwB7fu0VG/pGcNT29HyFp3xeOlgcytQfMYvpyr0InNhjlGGFtg56w6sWjBQNLqhtg@@HM0TBSCJC1HwMAw9whxj3P6ovbTYXiISrlqig4ZdkbU9DTHGY4ftNcR7AcsNCi3pWdC10Y40QTvGJmjv4r0BOgq1kTsa8PriYcq6K3gz7Y6pvnF03bGDfxoZIuzF@hV8CG2JNy6jExn5TsH6p@2M9/@WWQ8TvN73IGdNDdTpPWoXNiyFnnjvh73NP5GgHxW6OxZFAMh9nukSZgUpmgJ8go9lmRf@clmUcfKUHYTepVm1SLL9Ml4yl7qu53jLq8tr5rIroAmsIDfNi1zmAmGgRPWzKLdmI7TZ3TbLzZtuyi70BQZZuu1YAs2wxVA4xgSO/aA6UaiMQmUU7D6zL6ndau3LaraiOapFpWUpkBa5RjaP4QxOvqsJBsZ7mhXW23967UepDewhapEggUeca6lK9E0/97n@o/EPfx@nZuTxLw "Python 3 – Try It Online")
Throws NameError for false and doesn't throw for true.
Golf notes:
* `or` has a higher precedence than `and`
### Commented, Ungolfed
```
# bit order of a cell:
# truthy bit if that side is white(opeN)
# 0
# 3 1
# 2
# black: 0
# white: 15
# SE: 9
# SW: 3
# NW: 6
# NE: 12
# helper function to flood fill starting at (x,y)
# passes x,y position
# passes down mutable values
# visited: array of coordinates visited
# num_visited: dict counting how many of each cell type have been visited
def flood_solve(case, x, y, coming_from):
global touched0, white_area, visited, num_visited
# if out-of-bounds in the positive direction, this will throw
try: c = case[y][x]
except: return
if (x,y) in visited: return
# maybe can include touched0 into num_visited dict, then del num_visited[0] later
# Keep track if the white region touches a full-black cell (0)
touched0 = touched0 or c == 0
# Check if this new cell is white on the side of the previous cell
if not c & coming_from: return
# Turn all visited cells to 0 to avoid flood-filling the same region
case[y][x] = 0
# Keep track of which cells are visited
visited += [(x,y)]
# Keep track of the counts of NE,NW,SE,and SW cells (3,6,9,12)
num_visited[c] += 1
# Keep track of the area of cells visited (1 for full-white, 0.5 for all else)
if c != 15:
white_area += 0.5
else:
white_area += 1
# Flood recurse in each direction
# Call flood_solve on (x,y-1) if (x,y) is white on its top side
# Whether (x,y-1) is white on its bottom side is determined using coming_from
if c & 1 and y>0: flood_solve(case, x, y-1, 4)
if c & 2: flood_solve(case, x+1, y, 8)
if c & 4: flood_solve(case, x, y+1, 1)
if c & 8 and x>0: flood_solve(case, x-1, y, 2)
return(visited, num_visited)
def solve(case):
global touched0, white_area, visited, num_visited
touched0 = False
white_area = 0
visited = []
num_visited = {3:0,6:0,9:0,12:0,15:0}
# Pick a cell with white
for y,row in enumerate(case):
for x,e in enumerate(row):
if e > 0:
# Floodfill whites from it
# Pass 15 (0b1111) as coming_from since (x,y) can always be reached
# Pass case mutably
visited, num_visited = flood_solve(case, x, y, 15); break
# (Maybe rectangular checks can be moved here to avoid looping by re-calling solve)
# flooding always visits at least one cell, so visited is equivalent to the proposition
# "A cell containing some white has already been found"
if visited: break
# Base case: if no white remains, then return True
if not visited:
return True
v = list(zip(*visited))
# v = [list of x positions visited, list of y positions visited]
top_left = list(map(min, v))
bottom_right = list(map(max, v))
# If only entered all-white cells and area of bounding box of cells entered == area of cells entered:
if len(visited)==num_visited[15] and (bottom_right[1] - top_left[1] + 1) * (bottom_right[0] - top_left[0] + 1) == white_area:
# looks like an infinite recursion, but visited cells are replaced with 0 in flood_solve
return solve(case)
# If touched an all-black cell, can't be an angled rectangle, since angled rectangles only have angled sides
if touched0:
return
n = num_visited
# Should have #(NW entered)=#(SE entered) and #(NE)=#(SW)
# (is this check redundant with the next area check? Maybe the area check can be rearranged by using area<=2*(perimeter/2)^?)
if not n[6] == n[9] or not n[3] == n[12]:
return
if 2*n[6]*n[12] == white_area:
# Success! it's an angled rectangle
return solve(case)
```
### Pseudo-code algorithm
* Start
* Pick a cell with white; floodfill whites from it
+ (Base case: if no white remains, then return True)
+ While floodfilling:
- Keep track of which cells are visited
- Keep track of the counts of cells
- Keep track if the white region touches a full-black cell (0)
- Keep track of the area of cells visited (1 for full-white, 0.5 for all else)
- Turn all visited cells to 0 to avoid flood-filling the same region
* If only entered all-white cells and area of bounding box of cells entered == area of cells entered:
+ Success! it's an upright rectangle.
+ GOTO Start; use the updated case (all visited cells turned black)
* If touched an all-black cell
+ Can't be an angled rectangle, since angled rectangles only have angled sides
+ return False
* Should have #(NW enetered)=#(SE entered) and #(NE)=#(SW) (is this check redundant with the next area check?)
* Each NW cell contributes sqrt(2) to the length of the NW side of the rectangle
* Each NE cell contributes sqrt(2) to the length of the NE side of the rectangle
* If area == 2\*#(NW)\*#(NE):
+ Success! it's an angled rectangle
+ GOTO Start; use the updated case (all visited cells turned black)
White region filled can't be angled or upright rectangle anymore
return False
] |
[Question]
[
Write a function or program that encodes a string into a [Code 39](https://en.wikipedia.org/wiki/Code_39) format barcode, where each character is encoded as five bars separated by four gaps. Either two of the bars and one of the gaps are wide and others are narrow (10\*4 codes), or three of the gaps are wide and none of the bars are (4 codes). This gives 44 different codes, from which one is a reserved code that is used to denote the start and end of the encoded string.
## The challenge
The input is a string containing only characters from the set
```
1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%
```
The output is the string encoded as a barcode string. The narrow gap and intercharacter gaps are a single space and a wide gap is three spaces. The narrow bar is the UTF-8 byte sequence for the Unicode character "Full block", █, i.e. `0xE2 0x96 0x88` and wide bar is three such byte sequences / characters (`███`). The full list of codes is:
```
Spaces
0100 0010 0001 1000 1011 1101 1110 0111
Bars
00000 + / $ %
10001 1 A K U
01001 2 B L V
11000 3 C M W
00101 4 D N X
10100 5 E O Y
01100 6 F P Z
00011 7 G Q -
10010 8 H R .
01010 9 I S space 1=wide
00110 0 J T start/end 0=narrow
```
The bars and spaces are interleaved, starting at a bar, so for example Q is
```
bar 0 0 0 1 1
code █ █ █ ███ ███
space 0 0 0 1
```
After encoding all the characters, the string is delimited at both ends with `█ █ ███ ███ █`. The intercharacter gap, a single space, is inserted between every letter. Your solution may output trailing spaces and a trailing newline (in that order).
## Examples
```
"" → "█ █ ███ ███ █ █ █ ███ ███ █"
"A" → "█ █ ███ ███ █ ███ █ █ █ ███ █ █ ███ ███ █"
"C++" → "█ █ ███ ███ █ ███ ███ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ███ ███ █"
"GOLF" → "█ █ ███ ███ █ █ █ █ ███ ███ ███ █ ███ █ █ █ ███ █ █ ███ █ ███ ███ █ █ █ █ ███ ███ █"
```
Standard input/output formats are allowed and standard loopholes are disallowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code measured in bytes wins!
[Answer]
# JavaScript (ES6), ~~225~~ 212 bytes
*Saved 4 bytes thanks to @l4m2*
```
s=>`#${s}#`.replace(/./g,c=>'0202020202'.replace(/./g,(j,k)=>[C='█',C+C+C,' ',' '][(i="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT".indexOf(c),[170,257,260,5,272,17,20,320,65,68,80][i>>2]^2<<i%4*2)>>k&1|j]))
```
[Try it online!](https://tio.run/##dY3LToNAGIX3PgWB1pmRvzBMy8WkM0mltlareL8hpoRCAyXQlMaYqHufwAf0RZCNC02ak29xzrc4WfgSVtE6XW06RTmP64TXFRczpfVWfSgzbR2v8jCKsa7pC4i4QJT9Bv2VOIMl4cJ3Ofr@@kTgqk0ASahBklDg45TLbVVv3RiDk1t2ML3ruqf3veHZg3noPVqj8449vtCco0tpf3Kl0ONrWUuLefzqJTgi4Bs2BWbawCwKJjCbgdEUCt0GywTLAYcGfioEC55Zv5@2e3uMCLHcNd6zgJA6KouqzGMtLxc4wbJMAD0ViOz82wfbhKuq29TYm47k5uIH "JavaScript (Node.js) – Try It Online")
### How?
The table can be rearranged such that the 9-bit binary mask of the character is quickly deduced from its row and column using the following formula:
```
n = m XOR (2 << k)
```
with:
```
m | k: 0 2 4 6
-----+------------------ Examples:
170 | % + / $
257 | U 1 A K 'G' = 320 XOR (2 << 4) = 320 XOR 32 = 352
260 | V 2 B L
5 | W 3 C M '+' = 170 XOR (2 << 2) = 170 XOR 8 = 162
272 | X 4 D N
17 | Y 5 E O
20 | Z 6 F P
320 | - 7 G Q
65 | . 8 H R
68 | spc 9 I S
80 | # 0 J T
```
[Answer]
# [Red](http://www.red-lang.org), 452 445 bytes
```
func[s][q: func[x y z][append/dup x y z]append insert s"*""*"b:
func[n][v: copy[]until[append v n % 2 * 2 + 1
1 > n: n / 2]q v 1 5 - length? v
reverse v]a: q":1234567890:ABCDEFGHIJ:KLMNOPQRST:UVWXYZ-. *"" "44
a/45: #"+"a/56: #"/"a/67: #"$"a/78: #"%"foreach t s[i: index? find a t
k: b pick[0 17 9 24 5 20 12 3 18 10 6]either 0 = j: i % 11[11][j]m:
b pick[8 4 2 16 22 26 28 14]i - 1 / 11 + 1 z: copy""repeat n 5[q z"█"k/(n)
q z" "m/(n)]prin z]]
```
[Try it online!](https://tio.run/##fVHtTtswFP3vpzi6DIlRdalNkhZLgBhf42t8bAOG5UmhcdZQMGmaRtAn4An2gLxIuaFI@7VZ/jj3Ht8rn@PSpbNzlxorMj3LJr5vxtaMNN7gI54wtSYpCufTIJ0UmGfmCeR@7MoKY1omnjdavBV5a2qN/kPxZOzEV/ndez1qeCxCYZlXC1JIrMNrTgZQdsS0RIQ27pz/XQ02UIvS1a4cO9Q20RiRlmoljOJub7WjNz9vbe/s7n3ZP9CHR8dfT07Pzr991z8uLq9@Xrc/gR8ECkORBGGksUAtSoIoblDAKO426AOjbq9Bi5Q9lC7pD8BiTK5ZWOoeN5DxiQSVGGrcoMj7Q9OB7GIVKuSnKg4UViB7kB3E1uXVwJXoYA233IO1SmmktObW3mvx3qCHkOXLGEpB8c61oc1ZtmQbpGyMwXRuH1HpCpdU7FBkRpjSy59nGgZL/qNoItB9g21R5p7/xM4yEIkmqkC/gvbfQYKpzf9wW63Wv9h5lu/snRzt0uwV "Red – Try It Online")
I'll try to golf it further, but I don't expect much from this naive solution.
[Answer]
# Java 10, 455 bytes
```
s->{String r="",R=r;for(var c:("~"+s+"~").split(""))r+=r.format("%9s",Long.toString(new int[]{148,289,97,352,49,304,112,37,292,100,52,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,138,162,168,42}["~1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%".indexOf(c)],2)).replace(' ','0');for(int l=r.length(),i=0,c;i<l;R+=""+(i%9%2<1?c<49?"█":"███":c<49?" ":" ")+(i%9>7&++i<l?" ":""))c=r.charAt(i);return R;}
```
[Try it online.](https://tio.run/##nVTbUtswEH3vVwhN01ijxbVlJ7YTAhNCoLSBtIFegQfXEWBqnNRWKB0mPPcL@oH9kXR9gZl0QkM7Y8va21np7Hov/Ct/9WL4ZRZEfpqSPT@Mb54QEsZKJqd@IMl@JhJyoJIwPiOBVm5S1kT9FF98UuWrMCD7JCYtMktX129Kr6RFKQxaSfN0lGhXfkKChkZvKU85rkxPx1GoNEoZS3gr0dHp0ke54qUUeqP4TFejAkiL5bfsTEcnN6btgnA98BywagJsDyzDBtMUYDkgPAGmYQAaRL0GjgWWQPcaRhjgumBaqHfBqUOu9qCOKAJjPBCODa4AxKjjagBqLbeGFgtsTGnaNbARWRgZCuJmaF4d9/jFCBNhbTE9oremsOxa3XE9o73Z2epu77zYffmqt7fff/1mcHD49t37Dx8/reqEP39aoXoYD@V1/1QL2AkIxvREjiNkXauSKlSNKsuJw4uTCPmJZHymzjUGYcuAoBmuRc0BR4a5Fla8ilgzN4I129ugv37@oI1sLR7aKNQElVhJynL/decZ5whR6LEEAWYIzv2krbSQNROpJklMBs3prFkUeTz5HGGRy1pfjcIhucRuKRvi6IT4rGgVJdOsqECyI6CcrfeHmd@RpR4077M70PajUZfn@Je8Hc7/I/OiXH9IZKH8V8vy0@70e9uPp38uwSKvB4mdu9QiwpcQ8wApD19wftzkLZjfuJw2YTyeKLgbVfJ6LAMlh2xugCUynUQKx1SsB1oeUFJ38D1V8lIfTZQ@Rk8VxYWZ08axoryI4/QY@eVaIeny68SPUu0@0wbt9AeDbudwBX@p7fZur7u1QrqltUEov/fklN1daTr7DQ)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
String r="", // Temp-String, staring empty
R=r; // Result-String, starting empty as well
for(var c:("~"+s+"~") // Prepend and append "~" to the input
.split("")) // And loop over each character
r+=r.format("%9s",Long.toString(
// Convert the following integer to a 9-bit binary String:
new int[]{148,289,97,352,49,304,112,37,292,100,52,
265,73,328,25,280,88,13,268,76,28,259,67,322,
19,274,82,7,262,70,22,385,193,448,145,400,208,
133,388,196,138,162,168,42}
// Array containing all decimal values of the binary Strings
["~1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%".indexOf(c)]
// with the index based on the current character
,2)).replace(' ','0');
// (also part of the integer to 9-bit binary String conversion)
for(int l=r.length(),i=0,c;i<l;
// Loop `i` over the temp-String
R+= // After every iteration: append the following to the result:
""+(i%9%2<1? // If `i` modulo-9 modulo-2 is 0:
c<49? // And `c` is '0':
"█" // Append a single block
: // Else:
"███" // Append three blocks
:c<49? // Else-if `c` is '0':
" " // Append a single space
: // Else:
" ") // Append three spaces
+(i%9>7 // If `i` modulo-9 is 8,
&++i<l? // and this is not the very last character
" " // Append a space delimiter
: // Else:
"")) // Append nothing more
c=r.charAt(i); // Set `c` to the current character in `r`
return R;} // Return the result
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~311~~, 303 bytes
```
(*P)()=printf;i;j;w;m[]={170,257,260,5,272,17,20,320,65,68,80};char*b=" \0\xE2\x96\x88",*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT",*c;p(x){j=256;w=2;while(j){P(b+w);if(x&1){P(b+w);P(b+w);}x/=2;j>>=1;w=2*!w;}P(" ");}f(char*_){p(82);for(c=_;*c;c++){i=strchr(t,*c)-t;p(m[i>>2]^(2<<(i&3)*2));}p(82);}
```
[Try it online!](https://tio.run/##dVBrb4IwFP3ur2C4mRaqQh2IqSVxTt3DTfd@iDNaRWsUDWIgIfz1sW5uyz7MmzQ35557em4Oy08ZS7PcY4vteCJVN4HPvWlhZmf@zsZ8JUYpULoQQLoWK4FLOJmTkCx7fRrrZQ1ho4ywqSED4TJGugAaKolnGsi0kKUlhM2GvjKisuRoTtTATlQxnciyZKQEVD5Si4cPeu3yEZ@0n0r1q@fj0@sXo9F5NZvdfLl1U7DObqXK@V1Wu7gXCkbWIILxnGLDJCHFJJzxxQTMYdwFIzWEhLsgyum/8LslUVHszm2b6p8q5SAkSRfIkiwoF3wdOIDxGlgYEnflA0YHRHgxVYUxpyIcNvNBIOxhPhAXLHvctnH/DeBqFfBcCSoYip92@iQVMUnLIfcAjDOSKBfIwkja5QdkxxPoh6jtZeqqupdrddrN/0l/Emx9T9JIJknfmbsYTjdpPvwA "C (gcc) – Try It Online")
-8 thanks to ceilingcat
Uses encoding strategy from Arnauld's answer. TIO link includes `-w` switch and boilerplate to remove warnings, these are unnecessary and thus not included in the score.
Aside from the encoding scheme as explained by Arnauld, the other trick here is to maintain the `w` variable as toggling between 2 and 0 (`w=2*!w`). This allows me to choose between the first and second strings in `b`. The first is a space, the second is the filled rectangle.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~241 239 227 213~~ 207 bytes
```
#define P printf(i%2?" ":"█")
i;p(x){for(i=9;i--;x/=2)P,x&1&&P+P;P;}f(char*_){p(82);for(char*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT";*_;p(L"ªāĄ\5Đ\21\24ŀADP"[i/4]^2<<i%4*2))i=index(t,*_++)-t;p(82);}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpJqU1ySkpmvl2H3XzklNS0zL1UhQKGgKDOvJE0jU9XIXklByUrp0bQOJU2uTOsCjQrN6rT8Io1MW0vrTF1d6wp9WyPNAJ0KNUM1tQDtAOsA69o0jeSMxCKteM3qAg0LI01rkHKwSImtkqq2vkqooaN3mJGTT7ixs2@EiYtfpKmrf5SZW4CuuXugnoVHkIKlZ7CygVeIkrVWPNBCH6VDq440HmmJMT0yIcbIMMbI5GiDo0uAUnSmvklsnJGNTaaqiZaRpmambWZeSmqFRomOVry2tqZuiTXE@tr/QK8o5CZm5mloVnMpAEGahpKSpjXMj0oxeUAeTMIRp4yztjZOOXd/HzfskkWpJaVFeQoG1ly1/wE "C (gcc) – Try It Online")
Based on [@LambdaBeta's implementation](https://codegolf.stackexchange.com/questions/163964/code-39-barcode-encoder/164007#164007).
Slightly less golfed:
```
#define P printf(i%2?" ":"█")
i;
p(x){
for(i=9;i--;x/=2)
P,
x&1&&
P+
P;
P;
}
f(char*_){
p(82);
for(char*t="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT";*_;p(L"ªāĄ\5Đ\21\24ŀADP"[i/4]^2<<i%4*2))
i=index(t,*_++)-t;
p(82);
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 90 bytes
```
⪫EE⪫**S⌕⁺⁺⭆…αχ﹪⊕μχα-. *+/$%ι⪫E⁵⁺⎇μ× ∨⁼›ι³⁹⁼²﹪⁻÷ι∨›ι³⁹χμ⁴¦³ω×█∨›ι³⁹∨§↨℅§.6':+3<-59ι²⊕μ³ω
```
[Try it online!](https://tio.run/##bVBtSsQwEP3vKUJQnLTpqltXWPWP1g8qlF1wLxCawQ2kaU3T1b2BJ/CAXqQmrRQRf8yQeTNv3suUW2HLWui@X1tlHDzVykAhmiGGgkYR5SQ3TeeenZ95AcY4eVBGwlp37ZjGTuBk@1Jjtq0bEJycnfrRopadriE3pcUKjUMJFRt6PgsfNJmRKD45PKK@UAGdXCw4GfZv0Bph91BxslEVtkCJN7WycP/aCd3Co0Xh0ILiJF36BT/wfFIvlPFrcuPu1E5JDIOe/Zc2egruzll4pSG9sUn06/OD/kv00I3LjcR3uBUtwspKZYSeQDq7OL6M0@tksaR8@OKchaP@Psmox0bJcBZCGbvq@yyOD/pkp78B "Charcoal – Try It Online") Note: Trailing space. Link is to verbose version of code. Explanation:
```
⪫EE⪫**S...⪫E⁵⁺...ω
```
Wrap the input string in `*`s and then map over it twice, finally joining the result with spaces. For the second map, there is then an additional map over the implicit range `0..4`, where two substrings are concatenated, and those results are then joined with the predefined empty string constant.
```
⌕⁺⁺⭆…αχ﹪⊕μχα-. *+/$%ι
```
For the first inner map, create a string formed by taking the incremented digits, the uppercase alphabet, and the symbols `-. *+/$%`, and look up the position of the mapped input character. For example, `C++` would map to `[12, 40, 40]`.
```
⎇μ× ∨⁼›ι³⁹⁼²﹪⁻÷ι∨›ι³⁹χμ⁴¦³ω
```
The first substring represents the spaces before the bars. There is nothing before the first bar, but the other bars depend on the position of the mapped input character: if it is over 39, then only one place has a single space, while if it is under 40, then only one place has three spaces, and the position is also converted to a column by dividing it by 10. If the column and the loop index differ by 2 (modulo 4) then that is the odd place out.
```
×█∨›ι³⁹∨§↨℅§.6':+3<-59ι²⊕μ³
```
The second substring represents the bars. If the position is over 39 then there is always one bar otherwise the position is looked up in an array of bits mapped to characters. For instance, if the position is 12, then that is circularly indexed to the character `'`, which is `100111` in binary, indicating wide bars in columns 1 and 2. (The leading `1` is ignored, it simply ensures a consistent bit count.)
[Answer]
## [Perl 5](https://www.perl.org/), 244 bytes
```
$l="{ , ,...,.........}"x9;@h{$",qw($ % + - . /),0..9,'',A..Z}=(<"$l">)[q{..=9...Z.>>...J=9..j.%r1...=).[.>=-..Ux?V.^=8.>.6o+ax_.=(..B=,..Yx6..b=(..#r'p.^...G.<=,..Sx5B.\=(.V.It..z:..-z.=<6.}=~s/./ord$&/gre=~/.{6}/g];s/^|./$h{$&} /g;$\=$h{''}
```
[Try it online!](https://tio.run/##nZNvb9MwEMbf71OcSlg3rb0mdvyPNgWGxARC4gViEtsYSmxnHapo6YZWrXRffdwlGRJvJrS8cOzE97vnnrOr8mp2f79eBxiuAC9/LH9d4/XlAqbgFyEOpRtW5aqZxh/8WuFyPt5ZxtUchsv5I5tgMplAvz/eiX62GDfD/4e9fmLcm4ODJ0Yeffzw9t/QGw9D/6gL7T727pFd9/dp97wAkWsPMggBphIpCM9D2syiAKetbWeQzIveBgYAMEDEAe60hIwYza4onAZrH4JMg7TSgazyFLQ1FQB2z7a3duNXs03HEI0O2i@8ycAYYXlJEhQPjazAQ6QBkt7g581eAs/hAIaA0DEkM2rhiCGbrRGkEx6EEYa@5Vn7TZUmAIz2BymiG/T7g9eIJ9uOkRODrLAgPYthZ4SQEYRTFZiMKijTjLiBqoJib9JL5r3p/unPDWLhOoYiRuaDBpqWEAyFy@g8BBkC5KUMJCtEsEGXjR8nOJ3S633hEL93DE0M8lyBETKDrA4kJlKkcGkKqvKM5GWomPF8lRGg2MdTnBbDh74YYlivFPegBqUdRXKQtOxMJJDUuiZ3dUaMz@uXx3heWJyiXhyUHcMSw1hVUy2czloJPuSCPfLUb1uBcobc0hnpWH/DYg/xsKDj8WWtH3Q41lFr0RpLHSGQNFSQMSl7RO5G62mWG9JRMeLZqr/Ec6rpqGOU7EeQvk1cak4sObEiMbZWvoUTTRNjwgo@rdUhnhHtuGNUxAghd2Byqj0LpgRZkm7nRQBTes1tJZBOmfHuGvH2BeLwFovJ31o8@0GNBBON5NNG4msy0Qid84nVvDS8VADb4u5qhKPFKiS7o4tV7BihOWMmtuGmkpqvSg3aKGpO1XDJFOPpLxR3I9zo7eji6/hqdP77QUdsz3re3qomsWkuCGeXFf1QnhuWa0tnPZltkt0tjC7GyVmRzDpGzbVUfDcM34jHn02/v/0D "Bash – Try It Online")
Contains many unprintables and high-byte characters, TIO link provides an `xxd` representation. I'd hoped this would have ended up smaller, and I might still be able to pack the data in a more efficient way so I'll see how I go. This builds up all permutations of `" "," ","█","███"` and then maps the indicies of the list to the corresponding characters.
[Answer]
# [Haskell](https://www.haskell.org/), ~~275~~ 270 bytes
```
z=0:z
x!0=[]
x!n=mod n x:x!div n x
e c|Just a<-lookup c.zip"W3YZ56C$EF. 89*HM/ORU1QGNTDJ7%40LSBIP2-+XVKA".((++)<*>(reverse<$>))$take 9.(++z).(2!)<$>scanl(+)7(67!0x117CDBC49F9EEEF11C3A659CACB31236)=zipWith(\l c->c<$[1..2*l+1])(a++[0])(cycle"█ ")>>=id
f s='*':s++"*">>=e
```
[Try it online!](https://tio.run/##NY7hToJQAIX/@xSXO5r3cvPGBYVwwKYIlmlWVlbkGsPrZCIyQUesB@gJesBehPBHf853ds7OdtZBtuFxXFWlJXfLRiHIlr@okVjb3RIkoOgWwjI6nlyDg/BrdMhyEJiteLfbHFIQ0jJK4Vx9fetojuh6FFwa0tXkYvrwxO6Ht4@DkX7Wlsez/vWd0iIvzzc9SBEiBJuSjfb8yPcZN0UbYzEPNhwYtO5KTJEi4DrOwiCJEcE60nRBLhjTnUHfaRue4bqux5ij9rSO4fScvsoUVcNWfWYe5Wv0HoOwZYem6DNKFSkmbIFRQIgv1ww/w5jD359vALFtW9GysQKZ1ZSa3YwQKME649U2iBJggW2QTj4AQradHvJZvh8nEGL67@kKAx/CcwB7J3HqeY3hdOzBRfUH "Haskell – Try It Online")
The operator `x!n` that calculates the x-base digits of n, is used twice to decompress the codes. The codes are compressed first as binary strings with wide = 1 and narrow = 0, with no regard to color, e.g. `R↔10000110↔262`. These numbers are then sorted and differenced to get numbers in the range [3,66], which are compressed with reverse of the binary digit algorithm as `0x117CDBC49F9EEEF11C3A659CACB31236`. This contains only half of the codes, the rest are reverses of these.
Ungolfed:
```
z=0:z -- infinite zeroes for padding
x!0=[] -- digits of n in base x, recursion base case
x!n=mod n x:x!div n x -- digits of n in base x
e c | Just a -- read upwards from (*)
<-lookup c -- lookup code, given letter
. zip"W3YZ56C$EF. 89*HM/ORU1QGNTDJ7%40LSBIP2-+XVKA"
-- combine codes with correct letters
. ((++)<*>(reverse<$>)) -- concatenate list and list with reverse codes
$ take 9 -- take nine
. (++z) -- pad with infinite zeroes on right
. (2!) -- convert to binary digits – [[1,1,1],[1,0,1,1]…]
<$> scanl (+) 7 -- cumulative sum starting from 7 – [7,13,19,22,25…]
(67!0x117CDBC49F9EEEF11C3A659CACB31236)
-- (*) digits in base 67 – [6,6,3,3,3,9,5,7…]
= zipWith
(\l c->c<$[1..2*l+1]) -- combine width and color, length is 2*l+1
(a++[0]) -- list of widths as 0/1, 0 added for interchar gap
(cycle"█ ") -- infinite list of bar colors, leftovers are unused
>>=id -- concatenate
f s='*':s++"*">>=e -- surround string with delimiters, map e and concat
```
] |
[Question]
[
Given a nonnegative integer `n`, your solution must output a program in your chosen language whose output has `n` times as many bytes as the outputted program.
## Rules
* You must specify the language and encoding of the programs your solution outputs, and you may not choose different languages or encodings for different inputs to your solution. The language of your output program may or may not be the same as the language of your solution.
* Your submission only needs to handle integers in your language's range, but please do not abuse this rule.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest submission in bytes wins.
## Example
Suppose `n` is 4. My solution then outputs `f_8`, a program which, in my (imaginary) language outputs `j3 1s+/2]!mz`. The program output has length 3 and its output has length 3 \* 4 = 12, so the solution is correct for input 4.
Suppose instead that `n` is 1 and my program outputs `ffffpfpffp` (10 bytes). The program `ffffpfpffp` in my chosen language would have to produce an output of 10 \* 1 = 10 bytes.
[Answer]
# JavaScript (ES6), 38 bytes
```
n=>`(x="${n}")=>(x+1/7+1e9).repeat(x)`
```
### Demo
```
let f =
n=>`(x="${n}")=>(x+1/7+1e9).repeat(x)`
function update() {
let n = I.value,
func = f(n),
res = eval(func)();
O.innerText =
'n = ' + n + '\n\n' +
'Function (' + func.length + ' bytes):\n' + func + '\n\n' +
'Function output (' + res.length + ' bytes):\n' + res;
}
update()
```
```
<input type=range id=I min=0 max=100 oninput="update()">
<pre id=O>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
;“DL+8×x@⁶
```
[Try it online!](https://tio.run/##y0rNyan8/9/6UcMcFx9ti8PTKxweNW77//@/oREA "Jelly – Try It Online")
For input `12`, it outputs `12DL+8×x@⁶`, which outputs 120 spaces. [Try it online!](https://tio.run/##y0rNyan8/9/QyMVH2@Lw9AqHR43b/v8HAA)
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 348 bytes
```
--[>+<++++++]>>--[>+<++++++]>++[-<+>]----[>+<----]>---[-<+>]----[>+<----]>-[-<+>]-[>+<---]>++++++[-<+>]-[>+<---]>++++++++[-<+>]--[>+<++++++]>+++[-<+>]<[<],[->.<]>>>>>.<<<.>>.<<<.>>>.<<<.>>>.<<<.>>...>>>.<<....<<.>>>.<<..<<.>>>..<<.......>>>>.<<<..<<.>.....>>>.<<.>>.>>.<<<<<.>>>>.<<.<<.>>.>.<<<.>>.<<<.>>...<<.>>>..>>.<<.>.<<<.>.<<.>>>.>>.<<<..>>>.
```
[Try it online!](https://tio.run/##bY7RCoAwCEXf@xXTLxB/ZOyhgiCCHoK@f83pNhb5op676916L8e1P9uZEmIQYCgVRcYVICCDRETj2qPo8ocdOlG31j/tl8c8xxw4zgGFOP8pFzEztfbtRL7kgZrSRhfslXmKVJG98/PmKczxmN0TyJ0mVFoDdE5pegE "brainfuck – Try It Online") Or see the [Ungolfed version](https://tio.run/##lVLLTsMwELzvV@wRFGKJl7hYlhBwqISgqsqpyiFN3bQ0saPEQfx9WMcpsUUqYA9ONLOezOxmXad7tW2zQ9fF8UpEPOorEVgVbQMCQjSKsNwrIlYxj0RCrOPtMxF0YCGbUyzmtUyNrL/pgbOytlBXUp0iic4K3chRO/QV4UabgeQAK55grtFoXMutriWanXSRAC5wr6rWUFMsGPVZGD/xrEfPAR7f5s@zh/vl6wJA2GLOGeecDfEtdkzTw25a/4QZY/28xsP1uqAwX8xelk9kIt28t41ByoFVrfM6LalZ5WYHJMesyqBOKW7Adzla9z8FgbXx9uiRuXI6pHoHwnPGT8qFt24BalnqD4mZLtpS4SWEno6ZB8S@2C1yHozaG8lGZqQolTkqXvUj8J1PbIhcVEWaBTb@vtOJLf0yP8@wn/469DplgU3oT8nSr71OswP8WIU3rK6DLw "brainfuck – Try It Online") (i.e. what I had to work with)
---
### Disclaimer
I spent more time making this than I thought was humanly possible. I'd like to thank my girlfriend for allowing me to ditch her to work on this; as well as [my savior](https://esolangs.org/wiki/Brainfuck_constants).
### How does it even work?
No clue.
### *How* does it work?
All outputs have a trailing snippet of code that are all the same:
```
[->+>+>+<<<]>>>>-[<<+>>-------]<<+-----[<[.-]>->[->+<<<+>>]>[-<+>]<<]
```
Let's split it into three parts called `a,b,c`
```
a : [->+>+>+<<<]>>>> THE DUPLICATOR
b : -[<<+>>-------]<<+----- THE ADJUSTER
c : [<[.-]>->[->+<<<+>>]>[-<+>]<<] THE PRINTER
```
The input `i` is simply tacked on to the front in unary:
```
iabc
```
*(e.g; if the input was 10, then `i = '++++++++++'`)*
**The Duplicator**
- Splits the input into two identical numbers `m, n`, equivalent to the input
**The Adjuster**
- Adjusts `n` such that it equals the length of the program
**The Printer**
- Prints `m*n` ASCII characters
---
*Note that the input in the example is a `newline`, which as an ASCII value of 10, therefore the input is `10`. If you want to test other small numbers, replace the `,` with however many `+`'s you desire.*
[Answer]
# [Cheddar](https://cheddar.vihan.org), ~~10~~ 9 bytes
```
(*)&" "*9
```
An awkward Proton polyglot >\_<
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
f n=(++)<*>show$"main=putStr$[1.."++show n++"*2]>>'#':"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1ZDW1vTRsuuOCO/XEUpNzEzz7agtCS4pEgl2lBPT0lbGyShkKetraRlFGtnp66sbqX0H6RMwVYBolBBRSFNwZBLVxddsyFCBx6p/wA "Haskell – Try It Online") Example usage: `f 1` yields the following 54 bytes program:
```
main=putStr$[1..1*2]>>'#':"main=putStr$[1..1*2]>>'#':"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIJdpQT89QyyjWzk5dWd1KCY/U//8A "Haskell – Try It Online")
which produces the following 54 byte output:
```
#main=putStr$[1..1*2]>>'#':#main=putStr$[1..1*2]>>'#':
```
[Answer]
# [Python 3](https://docs.python.org/3/) -> HQ9+, 11 bytes
```
'Q'.__mul__
```
It had to be done
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPNfPVBdLz4@tzQnPv5/QVFmXolGmoappuZ/AA "Python 3 – Try It Online")
[Answer]
# Java 8, ~~175~~ 174 bytes
```
interface M{static void main(String[]a){System.out.printf("interface M{static void main(String[]a){int i=(88+%s)*%s;for(;i-->0;System.out.print(0));}}",a[0].length(),a[0]);}}
```
**Examples:**
[`n=1` outputs](https://tio.run/##jYyxCoMwFEV/JQhC0jYh3YRQ/6CTozg8NNpnayLJq1DEb09tx04dz@HcO8IC0s/Wjd09JXRkQw@tZdc1EhC2bPHYsQnQ8YoCuqFuQKzVK5KdlH@SmndJPc/@ne4dwwsvimMexSGPpveBG5Sy1Ob3lmshzLZlJ6h1ox7WDXTj4ksfn1I6vwE):
```
interface M{static void main(String[]a){int i=(88+1)*1;for(;i-->0;System.out.print(0));}}
```
(length=89) [which outputs 89 zeroes](https://tio.run/##DcqxCoAgEADQX3HUwsgtkPqDpsZoOMrijDTsCkL6dvPNz8ID0p/G2WVPCR2ZsMJsWB8vAsKZPR4XdgA6PlBAt40TiJgfw5Y3TalEofTqA9coZVfr4b3IHJW/qTpzJ14Lob8vpR8):
```
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
---
[`n=10` outputs](https://tio.run/##jYyxCoMwFEV/JQhC0jYh3YRQ/6CTozg8NNpnayLJq1DEb09tx04dz@HcO8IC0s/Wjd09JXRkQw@tZdc1EhC2bPHYsQnQ8YoCuqFuQKzVK5KdlH@SmndJPc/@ne4dwwsvimMexSGPpveBG5Sy1Ob3lmshzLZlJ6h1ox7WDXTj4ksfn1I66zc):
```
interface M{static void main(String[]a){int i=(88+2)*10;for(;i-->0;System.out.print(0));}}
```
(length=90) [which outputs 900 zeroes](https://tio.run/##DcqxCoAgEADQX3HUwrCmQOoPmhqj4TCLK9KwKwjp2603vxVukP6wbp22lNCRDTMYy7p4EhAadnuc2A7oeE8B3TKMIOL/GDa8rvNKZKXSsw9co5St0v1zkt0Lf1Fx/J@4EkK/b0of):
```
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
---
[`n=100` outputs](https://tio.run/##jYyxCoMwFEV/JQhC0jYh3YRQ/6CTozg8NNpnayLJq1DEb09tx04dz@HcO8IC0s/Wjd09JXRkQw@tZdc1EhC2bPHYsQnQ8YoCuqFuQKzVK5KdlH@SmndJPc/@ne4dwwsvimMexSGPpveBG5Sy1Ob3lmshzLZlJ6h1ox7WDXTj4ksfn1I6a/0G):
```
interface M{static void main(String[]a){int i=(88+3)*100;for(;i-->0;System.out.print(0));}}
```
(length=91) [which outputs 9100 zeroes](https://tio.run/##DcuxCoAgEADQX3HUwjBaAqk/aGqMhsMsrkjDriCkb7f291a4QfrDunXaUkJHNsxgLOviSUBo2O1xYjug4z0FdMswgoi/Y9jwus4rkZVK6dkHrlHKVun@Ocnuhb@oOP5AXAmh3zelDw):
```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
**Explanation:**
```
interface M{ // Class:
static void main(String[]a){ // Mandatory main method
System.out.printf("interface M{static void main(String[]a){
// Print a new program with:
int i=(88+%s)*%s; // Integer containing (88*A)+B
for(;i-->0;System.out.print(0));}}", // And print that many zeroes
a[0].length(), // Where A is the length of the number
// (0-9 = 1; 10-99 = 2; 100-999 = 3; etc.)
a[0]);}} // and B is the number itself
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), ~~7~~ 5 bytes
```
«•.*
```
*With a trailing space*
## Explained
```
«•.*
« # Yield a function from the remaining string.
•. # Append a space and stringify, which builds the original program (Because stringifying a function removes noops, which spaces are)
* # Repeat the implicit input times.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6///Q6kcNi/S0FP7//28KAA "RProgN 2 – Try It Online")
[Answer]
# CJam, ~~8~~ 13 bytes
```
q_,S\" 8+*S*"
```
[Try it Online](http://cjam.aditsu.net/#code=q_%2CS%5C%22%208%2B*S*%22&input=100)
The generated program outputs spaces so it's kind of hard to tell.
[Answer]
# [Ly](https://esolangs.org/wiki/Ly), 29 bytes
```
"\"9>("&onu")[<&s&ol>1-]<;"&o
```
[Try it online!](https://tio.run/##y6n8/18pRsnSTkNJLT@vVEkz2katWC0/x85QN9bGGij2/7@hAQA) ~~(does not work currently due to a pre-processing bug)~~ All good!
[Answer]
# Python → TECO, 20 bytes
The answer is in Python while the generated code is in TECO. The Python is a function returning `VV12345\VV` repeated *n* times. See [here](https://codegolf.stackexchange.com/a/45380/30688) for an explanation of the TECO.
```
'VV12345\VV'.__mul__
```
[Answer]
# PHP, 47+1 bytes
```
<?="<?=str_pad(_,",strlen($argn)+18,"*$argn);";
```
prints one underscore followed by spaces.
Run as pipe with `-F`; run outputted program with `-f` or `-F`.
This would fail for input with more than 64 digits,
which is far higher than `PHP_INT_MAX` (at this time).
However, it fails for input larger than `PHP_INT_MAX`-18 ... does it still qualify?
[Answer]
# PHP → Python 2, 40+1 bytes
```
print "A"*<?=13+strlen($argn),"*",$argn;
```
prints a Python program that prints repeated `A`s. Run as pipe with `-F`.
[Answer]
## Batch → Charcoal, 22 bytes
I'm not sure which encoding I should be using, since these are bytes. Here are the bytes interpreted as Windows-1252:
```
@set/p=Á%1ñªÉñ«Ìñ¹<nul
```
The same bytes as PC-850:
```
@set/p=┴%1±¬╔±½╠±╣<nul
```
The same bytes in Charcoal's code page:
```
@set/p=A%1θ×Iθ⁺Lθ⁹<nul
```
The resulting Charcoal program is `Plus(Length(Cast(n)), 9)` bytes long:
```
A Assign
%1 (String representation of n)
θ To variable q
Implicitly print a number of `-`s equal to:
× Product of:
Iθ Cast of q to integer
⁺ Sum of:
Lθ Length of q
⁹ Integer constant 9
```
[Answer]
# [Recursiva](https://github.com/officialaimm/recursiva), ~~16~~ 15 bytes
```
++"*"V*15a'"*"'
```
[Try it online!](https://tio.run/##K0pNLi0qzixL/P9fW1tJSylMy9A0UR3IUP//3wgA "Recursiva – Try It Online")
This for input of `n=2` prints:
```
*30"*"
```
which outputs 30 `*`.
[Try it online!](https://tio.run/##K0pNLi0qzixL/P9fy9hASUvp/38A "Recursiva – Try It Online")
[Answer]
# JavaScript (ES8), ~~43~~ ~~41~~ 39 bytes
```
n=>`f=_=>"".padEnd(${n}*(88+f).length)`
```
---
## Test it
The output of the generated function is a string of spaces which are replaced with `*`s in this Snippet.
```
g=
n=>`f=_=>"".padEnd(${n}*(88+f).length)`
o.innerText=(h=n=>`Function: ${x=g(n)}\nLength: ${x.length}\nOutput: "${x=eval(x)().replace(/./g,"*")}"\nLength: `+x.length)(i.value=10);oninput=_=>o.innerText=h(+i.value)
```
```
<input id=i type=number><pre id=o>
```
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
function(n)sprintf("cat(rep('a',%d*23),'')",n)
```
[Try it online!](https://tio.run/##LcvLCYAwDADQu1OIIE2kHtSr7uAKpaYiSFpi/GxfETw/nuRQjm2Zw8let8jAeCTZWANU3ikIJTDO2Hpp@gGtMVhZxsx0zxLXrwbosKDL7ZCcHARKj06/I@YX "R – Try It Online")
Anonymous function that returns the string
```
cat(rep('a',n*23),'')
```
Which prints `a` (that's `a` followed by a space) 23 times `n` times. I needed the `''` because otherwise `cat` wouldn't print the last space character.
[Answer]
# C, 94 bytes
```
main(int c,char**a){if(c>1){c=atoi(a[1]);if(c>0&&c<0xFFFFFF){c*=94;while(c--)printf("r");}}}
```
this would be 94 bytes include the last \n that stadard C says it should be written.
return as 'r' characters as the (lenght of the program) \* (argument of the program)
if the program argument not exist or it is <=0 or it is >0xFFFFF print nothing
example
```
C:\>nameProg.exe 1
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
```
[Answer]
## MATLAB (63 bytes)
```
a=@(n)['repmat(''a'',1,',num2str(n*(15+numel(num2str(n)))),')']
```
For example:
```
>> a(5)
ans =
repmat('a',1,80)
```
and:
```
>> repmat('a',1,80)
ans =
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```
] |
[Question]
[
I am writing a golfing language.
Do you suggest variables, stack(s), tapes, registers, etc for storage in a code-golf language? What about implicit input?
Rough definitions:
* A **variable** is simply a name (usually one character long in golfing languages) that a value can be assigned to, and later retrieved by that name.
* A **register** is like a variable, but it has its own (usually single-byte) commands for setting/getting the value.
* A **stack** is a variable-length array/list of values, where the most recently added values (the values "on top") are the ones that are being modified.
* A **queue** is like a stack, except the values "on the *bottom*" are the ones that are being modified.
* A **tape** is a static array/list of values where each value has an index. The main difference between a stack and a tape is that values on a tape are modified in-place.
I would appreciate to know the advantages and disadvantages of each option for different scenarios, and overall. Please avoid opinions, and backup statements with reasoning.
[Answer]
### I suggest all of them!
More seriously, they all come in handy some of the time, and the more the better! Implicit input is never *bad*, just have a flag to turn it off. Variables are helpful so they don't need to be found on a stack or tape; same with registers. Stacks are helpful to store data, and so are tapes. I recommend trying to implement multiple, say a stack *and* registers, or a stack and variables, like GolfScript. If you can make each function one byte, then your language will probably be effective at golfing, as you can use the advantages of each.
An example:
* Say I want to take two numbers as inputs, and add their string lengths
* Variables might be better for this (a stack might not)
* Example code in GolfScript (with implicit input):
```
~,\,+
~ # Eval input (e.g. "1 2" > 1, 2)
, # Take Length
\ # Reverse items on the stack
, # Take Length
+ # Add
# Implicit output
```
However, with variables (I know it's longer, it just doesn't have to swap places on the stack):
```
~,:a;,:b;ab+
~ # Eval input
, # Get length
:a# Store in "a"
; # Discard value left on stack
, # Length
:b# Store in "b"
; # Discard
a # Recall a
b # Recall b
+ # Add
# Implicit output
```
### Overloads
Another thing that can be helpful is overloads. For example, if you have a variable storing function, maybe it could be used as a monad (one-input function; I'm not sure of the term out side of J/K/APL) to add to the stack or tape.
Example:
```
c12 # Stores "1" into register 2
c1] # Pushes "1" onto the stack ("]" is used to denote the end of the monad)
```
[Answer]
All of the storage types involve storing something at one point and retrieving it later. To do this in only one operation, you should do either storing or retrieving automatically, and specify the position of the stored value in the other operation.
That is, for explicit storage, you could create an operator to retrieve the nth calculated value before this operation, or put back the current value after n operations. Alternatively, you could use the absolute position from the start of the program, or do more things such as removing some elements automatically after some operations (like in a stack). You could also make multiple operators, retrieving from different copies of the storage with or without these automatic operations. And you should try to make the maximum number needed to specify in the operations reasonably small, so you could assign one operator for each number.
But in most cases, you don't even need an operator and the language will do this implicitly. That is when you need to consider a more standardized model such as stacks or queues. The most successful for now seemed to be tacit programming, which doesn't even mention storage directly.
If you want to design a new such model, you could try expanding the evaluations as a dag, and try to think of a default dag if nothing else is specified. Most likely, the default is just a tree, except for that multiple leaves may be linked to the same input. You could for example use a queue for a balanced tree, or a stack for a deep tree where leaves are mostly constant, or something like Jelly for a deep tree where leaves are mostly copies of the input.
But note that, you could encode the shape of a binary tree in only 2 bits per operator. So, if your language has less than 64 operators, you may actually ignore the traditional models and just encode the complete tree in the spare bits (call them combine\_parent and below\_leaf flags). Even if there are more operators, you could make a fairly good default (such as the model of Jelly) and 3 modifiers to change it.
You could use the same model for implicit and explicit storage for convenience, but you don't have to. For example, you could use a stack for implicit storage, but don't pop elements in the explicit storage (or in another explicit storage in addition to the implicit one). It's likely it won't be called a stack in the final documentation, but you get the idea.
For reference, the size of the perfect encoding of a binary tree is the logarithm of the [Catalan numbers](http://oeis.org/A000108). And the size of the perfect encoding of a "binary" dag is the logarithm of [A082161](http://oeis.org/A082161), but obviously impractical. This assumes an operator with different argument order two different operators, adding another bit when it is not.
Sometimes you may still want variables for the loops. It might be possible to rewrite the loops in other ways. But if you really need it, don't use a 1-byte construct in addition to a name to define the variable. unless you are only using the preinitialized values, it's usually more efficient to use a 1-bit flag to specify whether you are reading or writing this variable.
[Answer]
I'd suggest having some quickly usable storage (from the given - tape, queue, stack) and some permanent storage (variables, registers) for things to not get in the way while the program is doing something unrelated. I'd say that much more would rarely give anything and leave more characters free for more 1-byte instructions.
From the definitions given, the ones I think would work the best would be a stack and registers.
A stack, because a tape has to use functions just to store a new thing in it, while a stack should have simple push and pop functions (usually built in the commands).
Registers, because they take less bytes usually compared to variables and if you need to store more than 2-4 different things for something, you're doing something wrong.
Don't limit the functions of them only to what their names or definitions suggest trough - some functions like `put the 1st thing of the stack on top of the stack` can definitely help.
[Answer]
There are basically two sorts of storage that need to be handled differently; access to recently generated values and/or the inputs; and long-term storage.
For long-term storage, variables seem to work best; anything with a limited number of options doesn't scale (although languages with this property, like Jelly, nonetheless can do fairly well even on medium-sized tasks). However, there's no need to provide variable *names* when storing the variable, most of the time; just have a command to store a value in the variable, and autogenerate the names according to a predictable pattern so that storing and retrieving the value can be one command each in simple cases. (For example, you could have commands to restore the most recently assigned variable, the second most recently, the third most recently, and so on, up to a small fixed number, plus a general command that took an argument.)
For short term storage, you want as much to be implicit as possible. Almost all golfing languages I've seen connect the output of one command to an input of the next, by default; the exact way in which this is done differs from language to language but normally comes to the same thing. However, the second input for a 2-input command is more interesting. Taking it from a stack works well in cases where values are only used once, but doesn't scale well when reusing values. (Try to avoid stack manipulation primitives; if you have to resort to using them, you're wasting a lot of bytes.) Alternatively, using user input or a recently assigned variable as the implicit second argument tends to give a few byte savings on simple programs, although you'll then need a parenthesis equivalent to make it possible to place nontrivial expressions on both sides of a binary operator.
In a golfing language I'm working on at the moment, I use a combination of a very cheap mechanism (a single *bit*) to specify the shape of the parse tree, automatically filling in missing arguments from user inputs by default, and a checkpointing approach that makes it possible to set the default for missing arguments to something else (plus plenty of special cases). At some point I'm likely going to add variables to communicate information greater distances along the program.
[Answer]
## A stack is sufficient for a terse golfing language.
First of all, implicit input is always nice, it's indisputable (it saves a lot from your source code, see [this](https://codegolf.stackexchange.com/a/96423/92069) 05AB1E tip.)
I created [W](https://github.com/Random-People/w) as a language which only allows manipulations upon the stack. If you read W's instruction reference, you will realize that W has absolutely no support for queues or tapes. Also, it doesn't even have assignable variables and accumulators! However, it still manages to be competitive, as well as having a similar bytecount as other stack-based golfing languages.
In my opinion, if you ever need an accumulator/variable, there's always a shorter way to re-write your program that purely uses stack manipulation.
[Answer]
I suggest a tape and a register.
I prefer tapes over stacks because tapes tend to have fewer elements, making manipulation of them easy. Also, being able to place elements in the tape in the register and vice versa makes for easy, short code.
] |
[Question]
[
First question here, don't yell at me if this is a duplicate or a bad challenge.
# Introduction
I thought of this challenge myself, and it seems to be a good basic puzzle for beginner code-golfers. It also might help me decide which code-golfing language to learn.
# Challenge
Given an array of integers that are less than or equal to `n`, output or return the minimum number of numbers from the array that sum up to exactly `n`.
You can choose to write a function or a full program.
### Input
You can safely assume `0 <= n < 2^31`.
Take an array or list of any kind (`vector` for C++ or Java's `LinkedList` are allowed), along with `n` and an optional parameter `length`, which specifies the length of the array.
You can also take the input as a space-separated string, separated from `n` by either a comma or a space:
```
1 5 7 3 7 3 6 3 2 6 3,10
1 5 7 3 7 3 6 3 2 6 3 10
```
if it is easier.
### Output
Output, or return the minimum number of numbers from the array that sum up to exactly `n`. Using the above example:
```
1 5 7 3 7 3 6 3 2 6 3,10
```
Your program should print:
```
2
```
because the minimum number of numbers that sum up to `10` is `2` (`7` and `3`).
In the case that there is no solution, print or return either a negative, `0`, "No solution" (though that would not be smart), `∞` (as suggested), or any other falsy value, with the exception of an empty string.
# Example Input and Output
### Input:
```
1 5 7 3 7 3 6 3 2 6 3,10
143 1623 1646 16336 1624 983 122,18102
5 6 9,12
```
### Output:
```
2
3
-1
```
# Scoring
This is code-golf, so shortest code in bytes wins.
The top answer will be accepted on Christmas.
[Answer]
## Pyth, ~~12~~ 11 bytes
```
lhafqsTQyEY
```
This takes `n` as the first line of input and the list on the second line.
```
lhafqsTQyEY (Implicit: Q = 1st line of input; E = 2nd line)
E The list
yE Powerset (sorted by increasing length; empty set first)
f Filter by lambda T:
sT sum(T)
q ==
Q Q
fqSTQyE Sublists that sum to Q, sorted by increasing length
a Y append an empty array (in case none match)
lh take the length of the first element (0 for empty array)
```
Try it [here](http://pyth.herokuapp.com/?code=lhafqsTQyEY&input=10%0A%5B1%2C5%2C7%2C3%2C7%2C3%2C6%2C3%2C2%2C6%2C3%5D&debug=1).
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), ~~30~~ ~~21~~ 18 bytes
Turns out there was a much more efficient method. ;)
```
Uà f_x ¥V} ml n- g
```
[Test it online!](http://ethproductions.github.io/japt/?v=master&code=VeAgZl94IKVWfSBtbCBuQFgtWX0gZw==&input=WzEgNSA3IDMgNyAzIDYgMyAyIDYgM10gMTA=) (Note: `n-` has been changed to `n@X-Y}` for compatibility reasons)
This takes input as a space- or comma-separated array, followed by a number. Outputs `undefined` for test cases without solutions.
```
Uà f_ x ¥ V} ® l} n- g
UàfmZ{Zx ==V} mZ{Zl} n- g
// Implicit: U = input array, V = input integer
Uà fZ{ } // Generate all possible combinations of U, then filter to only items Z where
Zx ==V // the sum of Z is equal to V.
mZ{Zl} // Map each remaining combination to its length.
n- // Sort by subtraction; smaller items end up in the front.
g // Take the first item.
// Implicit: output last expression
```
I can't believe I didn't think of this version when I originally wrote this...
Several optimizations have been made since then which come in handy here:
* A `U` at the beginning of the program can usually be left out.
* `Ã` is a shortcut for `}`.
* `n` now sorts numbers properly by default.
Each of these takes off a byte, for a total of 15:
```
à f_x ¥VÃml n g
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=4CBmX3ggpVbDbWwgbiBn&input=WzEgNSA3IDMgNyAzIDYgMyAyIDYgM10gMTA=)
[Answer]
## Mathematica, ~~73~~ 65 bytes
```
Min[Length/@Select[IntegerPartitions[#2,#2,#],Sort@#==Union@#&]]&
```
Pure function, returns `∞` if there is no solution.
[Answer]
# Python 3, 128 bytes
This isn't as golfed as I'd like it to be, but I'll work on it later.
```
from itertools import*
def s(a,n):
for i in range(len(a)):
for j in permutations(a,i+1):
if sum(j)==n:return i+1
return 0
```
[Answer]
# Mathematica, 45 bytes
```
Min@Cases[Subsets@#,i_/;Tr@i==12:>Length@#2]&
```
[Answer]
# CJam, 34 bytes
```
0q~_,2,m*\f.*{:+1$=},\;0f-{,}$0=,+
```
[Try it online](http://cjam.aditsu.net/#code=0q~_%2C2%2Cm*%5Cf.*%7B%3A%2B1%24%3D%7D%2C%5C%3B0f-%7B%2C%7D%240%3D%2C%2B&input=18102%20%5B143%201623%201646%2016336%201624%20983%20122%5D). The input format is the sum followed by the list of values, e.g.:
```
18102 [143 1623 1646 16336 1624 983 122]
```
Note that this will raise an exception if no solution is found. The exception goes to stderr when CJam is run from the command line, and the correct result (`0`) is still printed to stdout. So this meets the consensus established at [Should submissions be allowed to exit with an error?](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error)
The code may look longer than you would expect. The main reason is that CJam has no built-in for generating combinations. Or at least that's my excuse, and I'm sticking to it.
Explanation:
```
0 Push 0 result for exception case.
q~ Get and interpret input.
_, Copy and get length of input value list.
2, Push [0 1].
m* Cartesian power. This generates all possible lists of 0/1 values with the
same length as the input value list.
\ Swap input value list to top.
f.* Apply element-wise product of input value list with all 0/1 lists.
We now have all combinations of values, with 0 in place of unused values.
{ Start filter block.
:+ Sum values.
1$ Copy target sum to top.
= Compare.
}, Filter.
\; Swap target sum to top and discard.
0f- Remove 0 values. We now have all solution lists.
{,}$ Sort by length.
0= Get first solution, which after sorting is the shortest.
This will raise an exception if the list of solutions is empty, bailing
out with the initial 0 on the stack.
, Get length of solution.
+ Add the 0 we initially pushed for the exception case.
```
[Answer]
# JavaScript (ES6), 84 bytes
```
f=(a,n,m=1e999,x)=>n&&a.map((v,i)=>(x=[...a],x.splice(i,1),x=f(x,n-v)+1)<m?m=x:0)&&m
```
## Explanation
Takes an `Array` of `Number`s and a `Number` as arguments. Returns a number of `Infinity` if no result. It is a recursive function that subtracts from `n` and removes each element from the array one-by-one until `n == 0`.
```
f=(a,n,m=1e999,x)=> // m and x are not passed, they are here to declare them in the local
// scope instead of globally, initialise m to Infinity
n&& // if n == 0, return 0
a.map((v,i)=> // iterate over each number in a
(x=[...a], // x = copy of a
x.splice(i,1), // remove the added number from the array
x=f(x,n-v)+1) // x = result for the numbers in this array
<m?m=x:0 // set m to minimum result
)
&&m // return m
```
## Test
This test sets `m` to `Infinity` later instead of as a default argument to make it work in Chrome (instead of just Firefox).
```
var solution = f=(a,n,m,x)=>n&&a.map((v,i)=>(x=[...a],x.splice(i,1),x=f(x,n-v)+1)<m?m=x:0,m=1e999)&&m
```
```
Array (space-delimited) = <input type="text" id="array" value="143 1623 1646 16336 1624 983 122" /><br />
n = <input type="number" id="N" value="18102" /><br />
<button onclick="result.textContent=solution(array.value.split` `,N.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## Haskell, 72 bytes
```
import Data.List
n#l=head$sort[length x|x<-subsequences l,sum x==n]++[0]
```
Returns `0` if there's no solution.
Usage example: `10 # [1,5,7,3,7,3,6,3,2,6,3]` -> `2`.
Find all sub-lists of the input list `l` which have a sum of `n`. Take the length of each such sub-list and sort. Append a `0` and take the first element.
If a singleton list is allowed for output, e.g. `[2]`, we can save 7 bytes: `n#l=minimum[length x|x<-subsequences l,sum x==n]`. In case of no solution, the empty list `[]` is returned.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ṗ'∑₀=;vLg
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%97%27%E2%88%91%E2%82%80%3D%3BvLg&inputs=%5B1%2C5%2C7%2C3%2C7%2C3%2C6%2C3%2C2%2C6%2C3%5D%0A10&header=&footer=)
```
ṗ # Powerset
' ; # Filtered by
∑₀= # Sublists that sum to input
vL # Get length of each
g # Minimum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒPS=¥ƇẈṂ
```
[Try it online!](https://tio.run/##y0rNyan8///opIBg20NLj7U/3NXxcGfT/8PLlSL//4821DHVMdcxBmMzIDYCkbE6CtGmQIZl7H9DAx0FQyMA "Jelly – Try It Online")
Outputs `0` if there's no solution
## How it works
```
ŒPS=¥ƇẈṂ - Main link. Takes L on the left and n on the right
ŒP - Powerset of L
¥Ƈ - Keep those lists for which the following is true:
S - The sum...
= - ...equals n
Ẉ - Lengths of those kept
Ṃ - Minimum
```
[Answer]
# [Python 3.9](https://docs.python.org/3/), 101 bytes
```
def f(l,t):
s={0:0}
for i in l:s|={k+i:min(s[k]+1,s.get(k+i,s[k]+1))for k in s}
return s.get(t,-1)
```
[Try it online!](https://tio.run/##TY7BDoIwDIbve4rG0xqnoRsgkvAkxpsgCxMIGzFGfXbsxIOH/vn792va8RHaoTfLcqkbaKRTAUsBvnomZfIW0AwTWLA9uNK/qme3teXN9tKfuvOWlN9f6yA5VGuAGPku8p6XpzrME9svFdSOcLm31tVAfIIvQcXkOAeJez86G@RGbVDAmvMGe8f@FBuLf7/8cDwLGKc4XR/HhSCDA5hv5Vw6qqJEUGqAch0lzVmMiapTOBacaa2ooESLjPmjIv0B "Python 3 – Try It Online")
Note : the `|=` operators was introduced in python 3.9 but TIO doesn't support that version.
# [Python 3](https://docs.python.org/3/), 105 bytes
```
def f(l,t):s={0:0};[s.update({k+i:min(s[k]+1,s.get(k+i,s[k]+1))for k in s})for i in l];return s.get(t,-1)
```
[Try it online!](https://tio.run/##RY7RasMwDEXf/RWiTxb1QmSnWZvSLwl5GNRZTbzUxA6jlH57KieDPehydXwlOTzS7T6aZbnaHnrpVcImXp5lU77ObSzmcP1KVj6HvWt@3ChjO3R7UrH4tkkyVBtA7O8TDOBGiK/Vu@x9d55smiem60BSH4TL7815C9QI4Gtw4WCYk8QiBu@S3KkdCtg4T7D37NvcOIT/1X9x7ASEKb9un8eF4ACfYNaquXRWRaWgygDVOktVsxiTVVdwOjLTWtGRSi0OnD8p0m8 "Python 3 – Try It Online")
## Ungolfed version:
```
def f(l,t):
s={0:0} # initialize the reached numbers
for i in l: # iterate through the list
new_s = {} # create a dict for the newly reached numbers
for k in s: # iterate through all the reached numbers
new_s[k+i] = min(s[k]+1,s.get(k+i,s[k]+1)) # set the new number to the minimal number of steps
s.update(new_s) # update out dict with the new values
return s.get(t,-1) # returns the number of steps or -1 if the number is unreachable
```
[Try it online!](https://tio.run/##fVJhb4IwEP3Or7hsX2hEQ0GdmvhLjFmqFLlYgdBjxhl/O7tSNZJsI@mlfXfv3ruW@kJFVaZdl@kc8tBEJFYBgF1f41V8g8H3DlgioTL4rYEKDY1W@0JnULannW4s8/KqAeQyMKsBj3SjyJGaqj0UPdmgpcClS33@tLCG622gtefuTFGQ4Z76xo7Fxebyi7CXPjpp@6@0MuYP708vm@MIt2zohGXIh@1IRnZy0BQyHnlACG5tNT083dsAVT3CTDwp80CrHCzp2ovYSVtn7CjstcTDpwehaskPfEYqnt2/lGm1ozea2oZH7O1QNJaiJ3vY@vqhJvC1jCVg/ppEC23Z34DaGd2dCzQaJD88vz8PjmXdUigmtjZI4Vv0JgLwOIvy3vB@4w4oXl78Xi62AdSNy/rfSXQSZvABab/mvBIXIxkHcpqCnCcuTOcc0tTFZArLBWNJEsmFjJNgxvXLSCY/ "Python 3 – Try It Online")
## Note:
there is probably some potential
] |
[Question]
[
When is it beneficial to use inline, single use importing in Python?
For example:
```
__import__("x").doSomething()
```
Is the above ever shorter than the below?
```
import x
x.doSomething()
```
Or
```
from x import*
doSomething()
```
[Answer]
This can be useful if you want to use a module just once in an anonymous lambda function, as it allows you to avoid writing a separate statement:
```
lambda x:__import__('SomeModule').foo(x,123)
```
is one byte shorter than
```
from SomeModule import*;f=lambda x:foo(x,123)
```
If the code is a named function or program, then `__import__` is unlikely to help except in the most extreme or contrived circumstances.
[Answer]
When importing multiple modules with sufficiently long names, it can be helpful to assign the `__import__` function to a shorter variable and use it for imports
### Example:
Regular import statements - 97 bytes
```
from itertools import*
from datetime import*
print list(permutations("abc"))
print datetime.now()
```
Assigning `__import__` to `i` - 94 bytes:
```
i=__import__
print list(i("itertools").permutations("abc"))
print i("datetime").datetime.now()
```
[Answer]
### Almost never.
`__import__("x").doSomething()` needs 15+*x* characters to refer to a module with a name of length *x*.
`import x\nx.doSomething()` needs 9+2\**x* characters. These functions overlap at *x*=6, so compared to this way any module with a longer name is better off using `__import__`, anything shorter benefits from normal imports:

However, `from x import*\ndoSomething()` needs only 14+*x* characters, so compared to the normal import it is not worth it unless the module name is longer than 5 characters:

This all assumes that you are referring to a function/class/whatever only once. If you refer to it more than once, the formulas change, and the latter version might become the winner. In case you use something long from an imported module several times, yet another version wins:
`from x import y as z` nets you 18+*x*+*y*+*z*\*(*n*+1) characters for *n* uses of *z*, which is a large improvement if *y* is big, because *z* can be made 1.
] |
[Question]
[
## Semiperfect numbers
A semiperfect/pseudoperfect number is an integer equal to the sum of a part of or all of its divisors (excluding itself). Numbers which are equal to the sum of all of their divisors are perfect.
```
Divisors of 6 : 1,2,3
6 = 1+2+3 -> semiperfect (perfect)
Divisors of 28 : 1,2,4,7,14
28 = 14+7+4+2+1 -> semiperfect (perfect)
Divisors of 40 : 1,2,4,5,8,10,20
40 = 1+4+5+10+20 or 2+8+10+20 -> semiperfect
```
## Primitive
A primitive semiperfect number is a semiperfect number with no semiperfect divisors (except itself :))
```
Divisors of 6 : 1,2,3
6 = 1+2+3 -> primitive
Divisors of 12 : 1,2,3,4,6
12 = 2+4+6 -> semiperfect
```
As references, please use the OEIS series [A006036](https://oeis.org/A006036) for primitive semiperfect numbers, and [A005835](https://oeis.org/A005835) for semiperfects.
## Goal
Write a program or a function in any language.
It will take as input a number n as a function parameter or from STDIN/your language's closest alternative, and will output all the primitive semi-perfect numbers from 1 to n (inclusive).
The output must be formated as `6[separator]20[separator]28[separator]88...` where [separator] is either as newline, a space or a comma. There must not be a starting [separator] nor a ending one.
**Edit : you can leave a trailing newline**
## Examples
input :
```
5
```
output :
input :
```
20
```
output :
```
6
20
```
input :
```
100
```
output :
```
6 20 28 88
```
## Scoring
This is code-golf, so the shortest code in bytes win.
Don't try to fool us with [loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) please :).
I'd be glad you could leave an explanation of your golfed code once you think you're done golfing it!
## As this challenge already have some nice answers, and is slowly getting quiet, I'll put an end to it. The winner of this code-golf will be decided on Monday 29th, 00:00 GMT. Well done to all of you that have answered, and good luck to those who will try to beat them :)
[Answer]
# Pyth, ~~28~~ 27 bytes
```
VQI}KhNsMyJf!%KTSNI!@JYeaYK
```
*1 byte thanks to @Jakube*
[Demonstration.](https://pyth.herokuapp.com/?code=VQI%7DKhNsMyJf!%25KTSNI!%40JYeaYK&input=100&debug=0)
```
VQI}KhNsMyJf!%KTSNI!@JYeaYK
Implicit:
Y = []
Q = eval(input())
VQ for N in range(Q):
KhN K = N+1
f SN filter T over range(1, N)
!%KT the logical not of K%T.
This is the list of divisors of K.
J Store the list in J.
y Create all of its subsets.
sM Map each subset to its sum.
I}K If K is in that list: (If K is semiperfect)
I!@JY If the intersection of J (the divisors)
and Y (the list of primitive semiperfect numbers)
is empty:
aYK Append K to Y
e And print its last element, K.
```
[Answer]
# Julia, ~~161~~ 149 bytes
```
n->(S(m)=!isempty(filter(i->i==unique(i)&&length(i)>1&&all(j->m%j<1,i),partitions(m)));for i=2:n S(i)&&!any(S,filter(k->i%k<1,1:i-1))&&println(i)end)
```
This creates an unnamed function that accepts an integer as input and prints the numbers to STDOUT separated by a newline. To call it, give it a name, e.g. `f=n->...`.
Ungolfed + explanation:
```
# Define a function that determines whether the input is semiperfect
# (In the submission, this is defined as a named inline function within the
# primary function. I've separated it here for clarity.)
function S(m)
# Get all integer arrays which sum to m
p = partitions(m)
# Filter the partitions to subsets of the divisors of m
d = filter(i -> i == unique(i) && length(i) > 1 && all(j -> m % j == 0, i), p)
# If d is nonempty, the input is semiperfect
!isempty(d)
end
# The main function
function f(n)
# Loop through all integers from 2 to n
for i = 2:n
# Determine whether i is semiperfect
if S(i)
# If no divisors of i are semiperfect, print i
!any(S, filter(k -> i % k == 0, 1:i-1) && println(i)
end
end
end
```
Examples:
```
julia> f(5)
julia> f(40)
6
20
28
```
[Answer]
# JavaScript (*ES6*) 172
Run the snippet below to test
```
f=
v=>eval("for(n=h=[];n++<v;!t*i&&n>1?h[n]=1:0){for(r=[l=i=t=1];++i<n;)n%i||(h[i]?t=0:l=r.push(i));for(i=0;t&&++i<1<<l;)r.map(v=>i&(m+=m)?t-=v:0,t=n,m=.5)}''+Object.keys(h)")
// Less golfed
ff=v=>
{
h=[]; // hashtable with numbers found so far
for (n=1; n <= v; n++)
{
r=[1],l=1; // r is the list of divisors, l is the length of this list
t=1; // used as a flag, will become 0 if a divisor is in h
for(i=2; i<n; i++)
{
if (n%i == 0)
if (h[i])
t = 0; // found a divisor in h, n is not primitive
else
l = r.push(i); // add divisor to r and adjust l
}
if (t != 0) // this 'if' is merged with the for below in golfed code
{
// try all the sums, use a bit mask to find combinations
for(i = 1; t != 0 && i < 1<<l; i++)
{
t = n; // start with n and subtract, if ok result will be 0
m = 0.5; // start with mask 1/2 (nice that in Javascript we can mix int and floats)
r.forEach( v=> i & (m+=m) ? t -= v : 0);
}
if (t == 0 && n > 1) h[n] = 1; // add n to the hashmap (the value can be anything)
}
}
// the hashmap keys list is the result
return '' + Object.keys(h) // convert to string, adding commas
}
(test=()=> O.textContent=f(+I.value))();
```
```
<input id=I type=number oninput="test()" value=999><pre id=O></pre>
```
[Answer]
# CJam, 54 bytes
This solution feels a bit awkward, but since there have been few answers, and none in CJam, I thought I'd post it anyway:
```
Lli),2>{_N,1>{N\%!},_@&!\_,2,m*\f{.*:+}N#)e&{N+}&}fNS*
```
A good part of the increment over the posted Pyth solution comes from the fact that, as far as I could find, CJam does not have an operator to enumerate all subsets of a set. So it took some work to complete that with available operators. Of course, if there actually is a simple operator I missed, I'll look kind of silly. :)
Explanation:
```
L Start stack with empty list that will become list of solutions.
li Get input N and convert to int.
),2> Build list of candidate solutions [2 .. N].
{ Start for loop over all candidate solutions.
_ Copy list of previous solutions, needed later to check for candidate being primitive.
N,1> Build list of possible divisors [1 .. N-1].
{N\%!}, Filter list to only contain actual divisors of N.
_ Check if one of divisors is a previous solution. Start by copying divisor list.
@ Pull copy of list with previous solutions to top of stack
&! Intersect the two lists, and check the result for empty. Will be used later.
\ Swap top two elements, getting divisor list back to top.
_, Get length of divisor list.
2, Put [0 1] on top of stack.
m* Cartesian power. Creates all 0/1 sequences with same length as divisor list.
\ Swap with divisor list.
f{.*:+} Calculate element by element product of all 0/1 sequences with divisors,
and sum up the values (i.e. dot products of 0/1 sequences with divisors).
The result is an array with all possible divisor sums.
N#) Find N in list of divisor sums, and covert to truth value.
e& Logical and with earlier result from primitive test.
{N+}& Add N to list of solutions if result is true.
}fN Phew! We finally made it to the end of the for loop, and have a list of solutions.
S* Join the list of solutions with spaces in between.
```
[Try it online](http://cjam.aditsu.net/#code=Lli)%2C2%3E%7B_N%2C1%3E%7BN%5C%25!%7D%2C_%40%26!%5C_%2C2%2Cm*%5Cf%7B.*%3A%2B%7DN%23)e%26%7BN%2B%7D%26%7DfNS*&input=100)
[Answer]
# PHP, 263 Bytes
```
function m($a,$n){for($t=1,$b=2**count($a);--$b*$t;$t*=$r!=$n,$r=0)foreach($a as$k=>$v)$r+=($b>>$k&1)*$v;return$t;}for($o=[];$i++<$argn;m($d,$i)?:$o=array_merge($o,range($r[]=$i,3*$argn,$i)))for($d=[],$n=$i;--$n*!in_array($i,$o);)$i%$n?:$d[]=$n;echo join(",",$r);
```
[Try it online!](https://tio.run/nexus/php#HY/BTsMwEETv/Yo0WlDsuBIFKQdcpwfUAxe4cKuqyEncxFRdR4tTCSH49bDJbaWZeTO72w/9sHJEgSpyQ6Doscv@DtXb@8fry0HoFVjq0KRFUaR6Oo/YRB8wuWZgFaD4OQfKIJqtgto8StmEESNrQm82UEuIGqI0QGsDqIDMg@CAs03PnsR@wcWUcBNAucmgLku43G@FhJsmF0dCjv8uBcEcTxp8nu@WOZrrWwVe7J9ZskT2u7o66hw7FVmcDzqeDHj1JJfEbBZiYbXM4ukszhtRrj1WCyJjOwShBfg7QEa3MwK1a/qQfAaPWapSfkLoafoH "PHP – TIO Nexus")
Expanded
```
function m($a,$n){
for($t=1,$b=2**count($a);--$b*$t;$t*=$r!=$n,$r=0) #loop through bitmasks
foreach($a as$k=>$v)$r+=($b>>$k&1)*$v; # loop through divisor array
return$t;} # returns false for semiperfect numbers
for($o=[];$i++<$argn;
m($d,$i)?
:$o=array_merge($o,range($r[]=$i,3*$argn,$i))) # Make the result array and the array of multiples of the result array
for($d=[],$n=$i;--$n*!in_array($i,$o);) # check if integer is not in multiples array
$i%$n?:$d[]=$n; # make divisor array
echo join(",",$r); #Output
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ÆDṖŒPS€i
ÆDÇ€TL’
RÇÐḟY
```
[Try it online!](https://tio.run/nexus/jelly#@3@4zeXhzmlHJwUEP2pak8kF5B5uB7JCfB41zOQKOtx@eMLDHfMj////b2hgAAA "Jelly – TIO Nexus")
**Explanation**
```
ÆDṖŒPS€i - helper function to check if input is a semiperfect number
ÆD - list of divisors of input
Ṗ - except for the last one (the input)
ŒP - power set = every possible subset of divisors
S€ - sum of each subset
i - return truthy iff input is one of these
ÆDÇ€TL’ - helper function to check if input is a primitive semiperfect number
ÆD - list of divisors of input
Ç€ - replace each with if they are a semiperfect number, based on
the above helper function. If input is a primitive semiperfect
number, we get something like [0,0,0,0,0,94].
T - get all truthy values.
L’ - return falsy iff there is only one truthy value
RÇÐḟY - main link
R - Range[input]
ÇÐḟ - Filter out those elements which are not primitive semiperfect
numbers, based on the helper function
Y - join by newlines.
```
] |
[Question]
[
# Introduction
In this challenge, you are given a directed graph with self-loops, and your task is to convert it to an undirected graph without self-loops.
# Input
Your input is a directed graph with vertex set `{0, 1, ..., n-1}` for some natural number `n ≥ 0` (or `{1, 2, ..., n}` if you use 1-based indexing).
The graph is given as a length-`n` list `L` where `L[i]` is a list of the out-neighbors of vertex `i`.
For example, the list `[[0,1],[0],[1,0,3],[]]` represents the graph
```
.-.
| v
'-0<--2-->3
^ |
| |
v |
1<--'
```
Note that the neighbor lists are not necessarily ordered, but they are guaranteed to be duplicate-free.
# Output
Your output is another graph in the same format as the input, obtained from it as follows.
1. Delete all self-loops.
2. For each remaining edge `u -> v`, add the reversed edge `v -> u` if it's not already present.
As with the input, the neighbor lists of the output graph may be unordered, but they cannot contain duplicates.
For the above graph, a correct output would be `[[1,2],[0,2],[0,1,3],[2]]`, which represents the graph
```
0<->2<->3
^ ^
| |
v |
1<--'
```
# Rules
You can use 0-based or 1-based indexing in the graphs.
Both functions and full programs are acceptable.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
These test cases use 0-based indexing; increment each number in the 1-based case.
These neighbor lists are sorted in ascending order, but it is not required.
```
[] -> []
[[0]] -> [[]]
[[],[0,1]] -> [[1],[0]]
[[0,1],[]] -> [[1],[0]]
[[0,1],[0],[1,0,3],[]] -> [[1,2],[0,2],[0,1,3],[2]]
[[3],[],[5],[3],[1,3],[4]] -> [[3],[4],[5],[0,4],[1,3,5],[2,4]]
[[0,1],[6],[],[3],[3],[1],[4,2]] -> [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]]
[[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]] -> [[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
[[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]] -> [[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
[[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]] -> [[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9],[0,1,2,4,9],[0,3,5,6,7,8]]
```
[Answer]
# Pyth, ~~17~~ 16 bytes
```
.e-.|f}k@QTUQbkQ
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=.e-.%7Cf%7Dk%40QTUQbkQ&input=%5B%5B0%2C1%5D%2C%5B0%5D%2C%5B1%2C0%2C3%5D%2C%5B%5D%5D&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=FQ.Qp%22+-%3E+%22Q.e-.%7Cf%7Dk%40QTUQbkQ&input=%22Test+Cases%3A%22%0A%5B%5D%0A%5B%5B0%5D%5D%0A%5B%5B%5D%2C%5B0%2C1%5D%5D%0A%5B%5B0%2C1%5D%2C%5B%5D%5D%0A%5B%5B0%2C1%5D%2C%5B0%5D%2C%5B1%2C0%2C3%5D%2C%5B%5D%5D%0A%5B%5B3%5D%2C%5B%5D%2C%5B5%5D%2C%5B3%5D%2C%5B1%2C3%5D%2C%5B4%5D%5D%0A%5B%5B0%2C1%5D%2C%5B6%5D%2C%5B%5D%2C%5B3%5D%2C%5B3%5D%2C%5B1%5D%2C%5B4%2C2%5D%5D%0A%5B%5B6%5D%2C%5B0%2C5%2C1%5D%2C%5B5%2C4%5D%2C%5B3%2C5%5D%2C%5B4%5D%2C%5B5%2C6%5D%2C%5B0%2C3%5D%5D%0A%5B%5B1%2C0%5D%2C%5B5%2C1%5D%2C%5B5%5D%2C%5B1%5D%2C%5B5%2C7%5D%2C%5B7%2C1%5D%2C%5B%5D%2C%5B1%5D%5D%0A%5B%5B2%2C8%2C0%2C9%5D%2C%5B5%2C2%2C3%2C4%5D%2C%5B0%2C2%5D%2C%5B3%2C7%2C4%5D%2C%5B8%2C1%2C2%5D%2C%5B5%2C1%2C9%2C2%5D%2C%5B6%2C9%5D%2C%5B6%2C5%2C2%2C9%2C0%5D%2C%5B9%2C1%2C2%2C0%5D%2C%5B3%2C9%5D%5D&debug=0)
### Explanation
```
implicit: Q = input
.e Q enumerated mapping of Q (k index, b out-neighbors):
f UQ filter [0, 1, ..., len(Q)-1] for elements T, which satisfy:
}k@QT k in Q[T]
# this are the in-neighbors
.| b setwise union with b
- k remove k
```
[Answer]
# CJam, ~~43~~ ~~40~~ ~~35~~ ~~34~~ 33 bytes
*2 bytes saved by Sp3000.*
This started out as a really elegant solution and then grew increasingly hideous as I tried patching up some holes I overlooked. I'm not sure yet if the original idea is still salvageable, but I'll try my best...
```
q~_,,\ff{&W+0=)}_z..-{_,{;(},+}%`
```
[Test it here.](http://cjam.aditsu.net/#code=q~_%2C%2C%5Cff%7B%26W%2B0%3D)%7D_z..-%7Bee%7B1%3D%7D%2C0f%3D%7D%25%60&input=%5B%5B1%200%5D%20%5B5%201%5D%20%5B5%5D%20%5B1%5D%20%5B5%207%5D%20%5B7%201%5D%20%5B%5D%20%5B1%5D%5D) Alternatively, [run the entire test harness](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3D'%2CSer%3AQ%3B%0A%0AQ~_%2C%2C%5Cff%7B%26W%2B0%3D)%7D_z..-%7Bee%7B1%3D%7D%2C0f%3D%7D%25%60%0A%0AoNo%7D%2F&input=%5B%5D%20-%3E%20%5B%5D%0A%5B%5B0%5D%5D%20-%3E%20%5B%5B%5D%5D%0A%5B%5B%5D%2C%5B0%2C1%5D%5D%20-%3E%20%5B%5B1%5D%2C%5B0%5D%5D%0A%5B%5B0%2C1%5D%2C%5B%5D%5D%20-%3E%20%5B%5B1%5D%2C%5B0%5D%5D%0A%5B%5B0%2C1%5D%2C%5B0%5D%2C%5B1%2C0%2C3%5D%2C%5B%5D%5D%20-%3E%20%5B%5B1%2C2%5D%2C%5B0%2C2%5D%2C%5B0%2C1%2C3%5D%2C%5B2%5D%5D%0A%5B%5B3%5D%2C%5B%5D%2C%5B5%5D%2C%5B3%5D%2C%5B1%2C3%5D%2C%5B4%5D%5D%20-%3E%20%5B%5B3%5D%2C%5B4%5D%2C%5B5%5D%2C%5B0%2C4%5D%2C%5B1%2C3%2C5%5D%2C%5B2%2C4%5D%5D%0A%5B%5B0%2C1%5D%2C%5B6%5D%2C%5B%5D%2C%5B3%5D%2C%5B3%5D%2C%5B1%5D%2C%5B4%2C2%5D%5D%20-%3E%20%5B%5B1%5D%2C%5B0%2C5%2C6%5D%2C%5B6%5D%2C%5B4%5D%2C%5B3%2C6%5D%2C%5B1%5D%2C%5B1%2C2%2C4%5D%5D%0A%5B%5B6%5D%2C%5B0%2C5%2C1%5D%2C%5B5%2C4%5D%2C%5B3%2C5%5D%2C%5B4%5D%2C%5B5%2C6%5D%2C%5B0%2C3%5D%5D%20-%3E%20%5B%5B1%2C6%5D%2C%5B0%2C5%5D%2C%5B4%2C5%5D%2C%5B5%2C6%5D%2C%5B2%5D%2C%5B1%2C2%2C3%2C6%5D%2C%5B0%2C3%2C5%5D%5D%0A%5B%5B1%2C0%5D%2C%5B5%2C1%5D%2C%5B5%5D%2C%5B1%5D%2C%5B5%2C7%5D%2C%5B7%2C1%5D%2C%5B%5D%2C%5B1%5D%5D%20-%3E%20%5B%5B1%5D%2C%5B0%2C3%2C5%2C7%5D%2C%5B5%5D%2C%5B1%5D%2C%5B5%2C7%5D%2C%5B1%2C2%2C4%2C7%5D%2C%5B%5D%2C%5B1%2C4%2C5%5D%5D%0A%5B%5B2%2C8%2C0%2C9%5D%2C%5B5%2C2%2C3%2C4%5D%2C%5B0%2C2%5D%2C%5B3%2C7%2C4%5D%2C%5B8%2C1%2C2%5D%2C%5B5%2C1%2C9%2C2%5D%2C%5B6%2C9%5D%2C%5B6%2C5%2C2%2C9%2C0%5D%2C%5B9%2C1%2C2%2C0%5D%2C%5B3%2C9%5D%5D%20-%3E%20%5B%5B2%2C7%2C8%2C9%5D%2C%5B2%2C3%2C4%2C5%2C8%5D%2C%5B0%2C1%2C4%2C5%2C7%2C8%5D%2C%5B1%2C4%2C7%2C9%5D%2C%5B1%2C2%2C3%2C8%5D%2C%5B1%2C2%2C7%2C9%5D%2C%5B7%2C9%5D%2C%5B0%2C2%2C3%2C5%2C6%2C9%5D%2C%5B0%2C1%2C2%2C4%2C9%5D%2C%5B0%2C3%2C5%2C6%2C7%2C8%5D%5D).
I'll add an explanation once I'm sure the patient is dead.
[Answer]
# Python 2, 107 bytes
Still trying to figure out if I can golf this more, but for now, this is the best I can do.
```
def u(g):e=enumerate;o=[set(_)-{i}for i,_ in e(g)];[o[j].add(i)for i,_ in e(o)for j in _];print map(list,o)
```
I use sets to prevent duplicates; also, unlike `list.remove(i)`, `{S}-{i}` doesn't throw an error if `i` is not in `S`.
[Answer]
# Ruby, 78 bytes
Finally some use for ruby's set operators (`[1,2]&[2]==[2]` and `[3,4,5]-[4]==[3,5]`).
```
->k{n=k.size;n.times{|i|n.times{|j|(k[j]&[i])[0]&&k[i]=(k[i]<<j).uniq-[i]}};k}
```
[ideone](http://ideone.com/a1DsTd), including all test cases, which it passes.
[Answer]
# CJam, 26 bytes
```
l~_,,:T.-_T\ff&Tf.e&.|:e_p
```
Not very short...
### Explanation
```
l~ e# Read the input.
_,,:T e# Get the graph size and store in T.
.- e# Remove self-loops from the original input.
_T\ff& e# Check if each vertex is in each list, and
e# return truthy if yes, or empty list if no.
Tf.e& e# Convert truthy to vertex numbers.
.| e# Merge with the original graph.
:e_ e# Remove empty lists.
p e# Format and print.
```
[Answer]
# JavaScript(ES6), 96 ~~110~~
Creating adjacency sets from adjacency list, that helps avoiding duplicates.
Ad last it rebuilds the lists starting from the sets.
```
//Golfed
U=l=>
l.map((m,n)=>m.map(a=>a-n?s[n][a]=s[a][n]=1:0),s=l.map(m=>[]))
&&s.map(a=>[~~k for(k in a)])
// Ungolfed
undirect=(adList)=>(
adSets=adList.map(_ => []),
adList.forEach((curAdList,curNode)=>{
curAdList.forEach(adNode=>{
if (adNode!=curNode) {
adSets[curNode][adNode]=1,
adSets[adNode][curNode]=1
}
})
}),
adSets.map(adSet=>[~~k for(k in adSet)])
)
// Test
out=s=>OUT.innerHTML+=s+'\n'
test=[
[ [], [] ]
,[ [[0]], [[]] ]
,[ [[],[0,1]] , [[1],[0]] ]
,[ [[0,1],[]] , [[1],[0]] ]
,[ [[0,1],[0],[1,0,3],[]] , [[1,2],[0,2],[0,1,3],[2]] ]
,[ [[3],[],[5],[3],[1,3],[4]] , [[3],[4],[5],[0,4],[1,3,5],[2,4]] ]
,[ [[0,1],[6],[],[3],[3],[1],[4,2]] , [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]] ]
,[
[[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]] ,
[[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
]
,[
[[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]] ,
[[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
]
,[
[[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]] ,
[[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9], [0,1,2,4,9],[0,3,5,6,7,8]]
]
]
show=l=>'['+l.map(a=>'['+a+']').join(',')+']'
test.forEach(t => (
r = U(t[0]),
ck = show(r) == show(t[1]),
out('Test ' + (ck ? 'OK: ':'FAIL: ') + show(t[0])+' -> ' +
'\nResult: ' + show(r) +
'\nCheck : ' + show(t[1]) + '\n\n')
) )
```
```
<pre id=OUT></pre>
```
[Answer]
# Java, 150
```
a->{int i=0,j,k=a.size();for(;i<k;a.get(i).remove((Object)i++))for(j=k;j-->0;)if(a.get(j).contains(i)&!a.get(i).contains(j))a.get(i).add(j);return a;}
```
Expanded, runnable code:
```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function
public class C {
static Function<List<List<Integer>>, List<List<Integer>>> f = a -> {
int i = 0, j, k = a.size();
for (; i < k; a.get(i).remove((Object) i++)) {
for (j = k; j-- > 0;) {
if (a.get(j).contains(i) & !a.get(i).contains(j)) {
a.get(i).add(j);
}
}
}
return a;
};
public static void main(String[] args) {
System.out.println(f.apply(new ArrayList(Arrays.asList(
new ArrayList(Arrays.asList(0, 1)),
new ArrayList(Arrays.asList(1)),
new ArrayList(Arrays.asList(1, 0, 3)),
new ArrayList(Arrays.asList()))
)));
}
}
```
[Answer]
# Groovy - 87
```
u={g->g.eachWithIndex{n,i->g[i]=n-i;g[i].each{g[it]<<i}};g.each{it=it.sort().unique()}}
```
Full script to run tests:
```
u={g->g.eachWithIndex{n,i->g[i]=n-i;g[i].each{g[it]<<i}};g.each{it=it.sort().unique()}}
assert u([]) == []
assert u([[0]]) == [[]]
assert u([[],[0,1]]) == [[1],[0]]
assert u([[0,1],[]]) == [[1],[0]]
assert u([[0,1],[0],[1,0,3],[]]) == [[1,2],[0,2],[0,1,3],[2]]
assert u([[3],[],[5],[3],[1,3],[4]]) == [[3],[4],[5],[0,4],[1,3,5],[2,4]]
assert u([[0,1],[6],[],[3],[3],[1],[4,2]]) == [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]]
assert u([[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]]) == [[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
assert u([[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]]) == [[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
assert u([[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]]) == [[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9],[0,1,2,4,9],[0,3,5,6,7,8]]
```
[Answer]
# Mathematica, ~~84~~ ~~66~~ 64 bytes
Using 1-based indexing.
```
MapIndexed[Union[#,First/@l~Position~Tr@#2]~Complement~#2&,l=#]&
```
[Answer]
# Python 3, 127 bytes
```
l=list;g=l(map(set,eval(input())))
for i in range(len(g)):
for j in g[i]:g[j]=g[j]^g[j]&{j}|{i}
print(l(map(l,g)))
```
[Try online](http://repl.it/oH4)
Not my best attempt...
] |
[Question]
[
A string `x` *generates* a string `y` if `y` is a substring of an infinite repeat of `x`. For example `abc` generates `bcabcab`.
Write a program to find the shortest, lexicographically smallest string that will generate the input. You are given on standard input a single line of text. You should print the generating string to standard output. For example:
**input**
```
bcabcabca
```
**output**
```
abc
```
Shortest code wins. You may assume the input contains only the characters a-z (and a trailing newline if you want).
[Answer]
## Ruby 1.9, 40 characters
```
gets;a=?a;a.next!until(a*~/$/)[$_];$><<a
```
Assumes the input is not terminated by a newline. Also it's probably ridiculously slow for larger results.
```
$ echo -n "bcabcabca" | ruby genlex.rb
abc
$ echo -n "barfoobarfoobarfoo" | ruby1.9 genlex.rb
arfoob
```
[Answer]
**Python ~~88~~ 185 chars**
```
import re
s=raw_input()
m=s.index(min(s))
s=s[m:]+s[:m]
i=0
while s.replace(s[:i],''):i+=1
m=min(s[:i])
s=re.findall('%s[\w]*?(?=%s|$)'%(m,m),s[:i])
m=s.index(min(s))
print ''.join(s[m:]+s[:m])
```
Output:
```
bcabcabca
abc
aaa
a
abc
abc
cccbbcccbbcccbb
bbccc
barfoofoobarfoofoo
arfoofoob
bacabac
abacbac
```
[Answer]
Haskell, 299 128 characters
```
import Data.List
main=interact(\z->minimum$filter(\w->isInfixOf z$concat$replicate(length z)w) $filter((/=)"")$inits=<<tails z)
```
Thanks to jloy! Now the version is both far shorter and I believe correct.
[Answer]
**Python, 121 137 129 chars**
```
s=raw_input()
n=len(s)
l=[(s+s)[i/n:i/n+i%n+1]for i in range(n*n)]
print min(filter(lambda x:(x*len(s)).find(s)+1,sorted(l)),key=len)
```
EDIT: fixed the bug spotted by JiminP
[Answer]
## Ruby 1.9, 36
```
$><<(?a..gets).find{|s|(s*~/$/)[$_]}
```
Uses the same approach as Ventero's solution.
[Answer]
## Python, ~~161 159 166 140 141 134~~ 132 chars
```
y=raw_input();i=n=l=len(y)
while i:
if (y[:i]*l)[:l]==y:n=i
i-=1
x=y[:n];y=x*2
while i<n:
x=min(x,y[i:i+n])
i+=1
print x
```
**EDIT** : Golfed the code after reading Jules Olléon's comment. Removed a 'bug' that `bcdabcdab` results in `abbc`.
**EDIT2** : Fixed the bug (`abaa` results in `aaa`) spotted by Jules Olléon.
I don't know about Python well, so this code is probably 'not golfed'.
I love this rule:
*You may assume the input contains only the characters a-z...*
## Inputs & Outputs
```
bcdabcd
abcd
bcabcabca
abc
abcdabcd
abcd
bcdabcdab
abcd
barfoofoobarfoofoobar
arfoofoob
cccbbcccbbcccbb
bbccc
aaaaaaaaaaaaaaaa
a
thequickbrownfox
brownfoxthequick
ababa
ab
abaa
aab
```
[Answer]
## Mathematica 124 bytes
```
x = StringLength@(y = "");
For[i = 1, ! (s = y~StringTake~i)~StringRepeat~x~StringContainsQ~y,i++];
First@Sort@StringPartition[s <> s, i, 1]
```
Whitespace and newlines (in the presence of semicolons at the ends of lines) have no meaning in Mathematica and are included here for readability.
Input goes in between the quotation marks in the first line. If recast as a function, that takes string input like so:
```
f=(x=StringLength@(y=#);For[i=1,!(s=y~StringTake~i)~StringRepeat~x~StringContainsQ~y,i++];First@Sort@StringPartition[s<>s,i,1])&
f@"bca"
(* "abc" *)
f@"abaa"
(* "aab" *)
```
then it's 128 bytes.
The `For` loop takes the first `i` characters of the input and repeats them at least up to the length of the input, then checks if the input is a substring of the result. Having found the length of the period of the string, the `StringPartition` command concatenates two copies of that period and takes all substrings of that length from it (basically gets all cyclic permutations), then `First@Sort` finds the first one of them when lexicographically ordered.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 23 bytes
```
-join($args|group|% N*)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9XzcrPzNPQyWxKL24Jr0ov7SgRlXBT0vzfy0Xl0pmHlCJelJyIgSpc6kBNTlk5v3/DwA "PowerShell – Try It Online")
[Answer]
javascript 96 Chars.
```
var temp = {},len = str.length;
for(i in str)
temp[str[i]] = true;
Object.keys(temp).join("");
```
[Working Plunkr](http://plnkr.co/edit/CLFx07mLdSwU9iNDDp7d?p=preview)
] |
[Question]
[
## Background
In Minesweeper, you will often encounter a horizontal or vertical wall of one's and two's (not yet revealed cells are marked as `?`):
```
... 1 1 1 1 2 2 2 1 2 1 1 ...
... ? ? ? ? ? ? ? ? ? ? ? ...
... A B C D E F G H ...
```
It is equivalent to a problem of recovering zeros and ones in a boolean array when only windowed sums of size 3 are given, where a zero means a safe cell and a one means a mine:
```
A + B + C = 1
B + C + D = 1
C + D + E = 1
D + E + F = 2
E + F + G = 2
F + G + H = 2
...
```
If you focus on `CDEF`, you can logically determine that `C` should be zero and `F` should be one. If `C` were 1, it would mean `D + E = 0`, which is impossible due to `D + E + F = 2`. (Remember that all variables are booleans.)
## Challenge
This challenge is an extension of this problem to arbitrary window size.
Given `n` windowed sums with window size `k`, recover the `n+k-1` boolean cells in the original array as much as possible. It is possible that some cells cannot be determined by the given information; those cells should be marked as such in the output.
The input is the number `k` and an array (or any ordered collection) of `n` integers between 0 and `k` inclusive. The output is an array of zeros, ones, and unknowns, which can be represented as any three distinct values of your choice. You can assume the input is valid, `n` and `k` are at least 2, and it has at least one corresponding boolean array.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The output format uses `?` for unknown.
```
k = 2
sums = 0 0
answer = 0 0 0
sums = 0 1 2 1 0
answer = 0 0 1 1 0 0
sums = 1 1 1 1 1 1 1
answer = ? ? ? ? ? ? ? ?
sums = 1 1 1 1 1 1 0 1 1
answer = 0 1 0 1 0 1 0 0 1 0
sums = 1 1 2 1 1 1
answer = 1 0 1 1 0 1 0
---
k = 3
sums = 1 1 1 2 2 2
answer = ? ? 0 ? ? 1 ? ?
sums = 3 2 1 0 1 2 3
answer = 1 1 1 0 0 0 1 1 1
sums = 1 1 1 2 2 2 2 1 1
answer = 1 0 0 1 0 1 1 0 1 0 0
sums = 2 2 2 2 2 2 2 1
answer = 1 ? ? 1 ? ? 1 ? ? 0
sums = 2 1 2
answer = 1 0 1 0 1
---
k = 4
sums = 1 2
answer = 0 ? ? ? 1
sums = 3 2 1
answer = 1 1 ? ? 0 0
sums = 1 1 2 1 1
answer = 0 0 1 0 0 1 0 0
sums = 1 1 2 2 2 3
answer = 0 0 ? ? 0 1 ? ? 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 18 bytes
```
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€
```
[Try it online!](https://tio.run/##y0rNyan8/99H@1HDzMMz9B7unK79qHFLzKPGPYeWHmt/1Lgj6uHORY@a1gQC8f@HOzYdnRR2ePnRSQ93zvj/31DBUMEIDI3/mwAA "Jelly – Try It Online")
*-5 bytes thanks to @Jonathan Allan*
Uses `[0,1]` as `?`, `[0]` as `0`, and `[1]` as `1`.
### How?
Brute force of all possible boolean matrices.
```
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€
Ø. # [0,1]
ṗ # Cartesian power:
L+’ # Length of answer = length of sums + k - 1
Ƈ # Filter by:
+⁴\⁼¥ # n-wise overlapping sums are equal to
⁸ # the given sums
Z # Get the lists of all possibilities for each position (some binary list)
Ṣ€ # Sort each possibility list (0s then 1s)
Q€ # Take unique entries from every possibility ([0],[1],or [0,1])
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 39 bytes
Bit frustrating, as a nice attempt that inverts the moving window with `~{sᶠ↙L}` does not work. So this is basically just brute-force.
```
{tL&lʰ+-₁~l.{0|1}ᵐsᶠ↙L+ᵐ~h?∧}ᶠ\{=h|∧2}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7rERy3n1AZt3UdNjXU5etUGNYa1D7dOKH64bcGjtpk@2kB2XYb9o47ltUCRmGrbjBog2wik5P//6GhDHRA0AsFYHePY/1EA "Brachylog – Try It Online")
### How it works
```
{tL&lʰ+-₁~l.{0|1}ᵐsᶠ↙L+ᵐ~h?∧}ᶠ
{ }ᶠ find all solutions:
tL& store the window size as L
lʰ+-₁ length of input + window size - 1
~l. the output has this as length
{0|1}ᵐ and contains only 0's and 1's
sᶠ↙L get all windows of length L
+ᵐ that summed
~h? result in the input array
∧ return the output defined earlier
\{=h|∧2}ᵐ
\ transpose the solutions
{ }ᵐ map over each position
=h either all solutions are equal, then return first
|∧2 or return 2 (should be equivalent to ∨2 but isn't)
```
[Answer]
# Dyalog APL, ~~48~~ 44 43 bytes
```
{0 1⍳(+/÷≢)¨↓s[;⍸⍵≡⍤1⍉⍺+⌿s←2⊥⍣¯1⍳2*⍺+≢1↓⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2kDB8FHvZg1t/cPbH3Uu0jy04lHb5OJo60e9Ox71bn3UufBR7xKggs5Hvbu0H/XsL37UNsHoUdfSR72LD60HaTTSAst0LjIE6gPqiK39/6hvqqc/UJ0BVxqQpL4FXEALQKoU0hSAZisYAbEBVMwYKGaEAg2hMiZAGUOwahA0/g8A "APL (Dyalog Classic) – Try It Online")
This program uses `2` to represent `?`, and this program is run using `⎕IO←0`. This is basically a brute force algorithm, and could probably be golfed.
[Answer]
# Python 3, 168 bytes
```
import itertools
lambda k,s:[[q[0],"?"][len(set(q))>1]for q in zip(*[z for z in itertools.product((0,1),repeat=len(s)+k-1)if[sum(z[i:i+k])for i in range(len(s))]==s])]
```
Fairly straightforward: brute forces over all possible binary sequences of length `n+k-1`, collecting all the results, and then aggregating by position, replacing with a "?" if there's multiple possibilities for a given position.
The only clever saving here is in the last step where I use `zip()` to join all the results together by position, and then using `len(set(q))>1` to tell whether or not there's multiple possibilities for a position.
**Ungolfed:**
```
import itertools
def recover(k,sums):
def window_sum(seq):
return [sum(seq[i:i+k]) for i in range(len(sums))]
valid = []
for poss in itertools.product((0,1), repeat=(len(sums)+k-1)):
if window_sum(poss) == sums:
valid.append(poss)
ans = []
for by_position in zip(*valid):
if len(set(by_position)) == 1:
ans.append(by_position[0])
else:
ans.append("?")
return ans
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
≔⁺⊖θLηζ⭆EζEΦEX²ζ◧⍘λ²ζ⬤η⁼ν№✂λξ⁺θξ¹1Σ§λι∧⌈ι∨⌊ι?
```
[Try it online!](https://tio.run/##PU7LisMwDLzvV5icZPAekh57KNk@oNDSQI@lB5OoiUFxmthpQ3/elRNYkKyRNCNP2eih7DSFkDtnagsFjQ52WA7YovVYQS@VOKGtfQONZPyR659iMNbD1XOpz/oJMT9KxHIw5HGYJ0X3ZpRFiRKFrk748PCnHS5CICWy@SA/ORE0Suz7UZMDq8S2G@MXZEqMxIkvRGc9Q6annEmaSBm117GF3B9thVOkmmWa24pdTKblreH@wqaM/W@Tzaxeh3BbKXFL@eYc2RL3e/h90Rc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁺⊖θLηζ
```
Calculate the length of the result up-front, saving a byte.
```
⭆Eζ
```
Loop over each desired output.
```
EΦEX²ζ
```
Count all possible binary patterns...
```
◧⍘λ²ζ
```
... generating padded base 2 strings...
```
⬤η⁼ν№✂λξ⁺θξ¹1
```
... keeping only those with the correct window totals...
```
Σ§λι
```
... keep only the current bit. (Yes, we throw away all of the other results each time. That's code golf for you. If you want efficiency, well I guess you're looking at more like 57 bytes.)
```
∧⌈ι∨⌊ι?
```
Of those bits, if their maximum is 0 or minimum is not 0 then print that otherwise print `?`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1ÝDIgI+<ãʒ'üI«.VO¹Q}øÅAk
```
Port of [*@fireflame241*'s Jelly answer](https://codegolf.stackexchange.com/a/207287/52210), so make sure to upvote him!
Outputs `-1` for `?`.
[Try it online](https://tio.run/##yy9OTMpM/f/f8PBcF890T22bw4tPTVI/vMfz0Gq9MP9DOwNrD@843OqY/f9/tKEOCBqBYCyXMQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNh/w8NzXSLSI7VtDi8@NUn98J7IQ6v1wvwjAmsP7zjc6pj931BD3d7q8Hqd/9HRRjrRBjoGsbE6EJahjhEQw/iGOkgQi5gBmrgRQqUxTKURCEJFjCGmg0WNMVVB9EPFjXSQIULUEGKaCUgnjGUMU2GC5A4UvhHExlgA). (Feel free to remove the `1('?:ï` in the footer of the test suite - which converts all `-1` to `"?"` - to see the actual output.)
**Explanation:**
```
1Ý # Push a list [0,1]
D # Duplicate it
Ig # Push the first input-list, and pop and push its length
I+ # Add the second input-integer `k`
< # Decrease it by 1
ã # Get the cartesian product of [0,1] with the length+k-1
ʒ # Filter this list of potential windows by:
'ü '# Push character "ü"
I« # Append the input `k` to it
.V # Execute it as 05AB1E code
# `üN` creates overlapping sublists of size `N`
O # Sum each overlapping sublist
¹Q # And check if it's equal to the first input-list
}ø # After the filter: zip/transpose the remaining lists
ÅA # Get the arithmetic mean of each inner list
k # Use it to index into the [0,1] list, which results in -1 if it isn't in the
# list for the decimal values
# (after which the result is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~113~~ 112 bytes
```
->k,n{(a=0,1).product(*[a]*z=n.size+k-2).select{|x|n==x.each_cons(k).map(&:sum)}.transpose.map{|x|x.minmax.sum}}
```
[Try it online!](https://tio.run/##bY7NDoIwEITvPoUnA1gaWjyZ1BchxFQskWALoZBUfp69UolQlEz2sN9MZrdqbi@dEu1fciA6h5IAIBeWVXFvktrxIhp7LRFQZi075j52oWRPltRdr3pBiIKMJo9rUgjp5C7ktHQOZ9lwd4B1RYUsC8kMNXEFeSY4VXD0h0GX@zTCIApAEMe7eUEAj2MhBCxt4@Dfwqt8@M1jowWG07GPEW5mp6LFwsDWykBz88lUWEtoRU/Wf78IT2/oNw "Ruby – Try It Online")
Returns false cells as 0, unknowns as 1, and true cells as 2.
Also, this doesn't use new fancy numerical block variables from Ruby 2.7, so that it's still runnable on TIO.
[Answer]
# JavaScript (ES6), ~~127 126~~ 121 bytes
Expects `(k)(array)`. Returns a string, using `123` instead of `01?`.
```
k=>F=(a,i=w=a.length+k-1)=>i--?F(a,i)+(g=n=>n--&&!a.some(h=(v,j)=>++x%~k?h(v-=n>>j&1,j+1):v,x=0)<<(n>>i&1)|g(n))(2<<w):''
```
[Try it online!](https://tio.run/##jVPLcoMgFN33K@yiCqMkXHSVitnlJ9ounNT4SrHTZEwWnf669VULCpkI3AV4Duccr0Vcx6f9V/55JqJ6T5oDb0oe7TiKvZxfeLw6JiI9Z25JAPMoJ2S7646wi1IueCQIse3HeHWqPhKUcVR7Rfua616ffspthmrCRRQVNniFC3hTe1dOcRiidjO3AX@nSGCMWBhe8MZxmn0lTtUxWR2rFDmlxS3m4OcHefeAGEYv1LOopXveMLbW6/awHXoceBbrKzXgoB16NPQ4ZSrorTruYhgUwXQ/SKuvRhY2E/GvAyYXHV4hcF5FF6u/jNWX5bFhzok7W7SvoDHYMfhTun88/kzaGO8oEe5QMVmV7FHV5CKmjoepDCOPrGVyMlYDC8hR6MNulzboYBl0MFhkt/t36CHQYP3Jh0nQaGZhJ5j3jvEPoIZYFQYmf1@VYbh/jLb5BQ "JavaScript (Node.js) – Try It Online")
### Commented
```
k => // outer function taking k
F = ( // main function taking:
a, // a[] = input array
i = // i = counter initialized to ...
w = a.length + k - 1 // w = length of output array
) => //
i-- ? // decrement i; if it was not equal to 0:
F(a, i) + // prepend the result of a recursive call to F
( g = n => // g is a recursive function taking a counter n:
n-- && // decrement n; stop if it was equal to 0
!a.some(h = (v, j) => // otherwise, for each v at position j in a[]:
++x % ~k ? // increment x; if it's not equal to 0 modulo k + 1:
h( // do a recursive call to the callback of some():
v -= n >> j & 1, // subtract the j-th bit of n from v
j + 1 // increment j
) // end of recursive call
: // else:
v, // stop recursion and return v
x = 0 // start with x = 0
) << (n >> i & 1) // end of some(); turn true into 0; turn false into 2
// if the if i-th bit of n is set, or 1 otherwise
| g(n) // bitwise OR with the result of a recursive call to g
)(2 << w) // initial call to g with n = 2 ** (w + 1)
: // else:
'' // end of recursion on F: return an empty string
```
] |
[Question]
[
...or is there?
Your challenge is to parse my lunch bill, which contains the base price, tips, discounts, coupons, and extras and **find out if my lunch was $0 or less**. If this is the input:
```
12.34
15 tip
25 discount
1.5 extra
2 coupon
```
Then the output might be `false`. Here's how it works:
`12.34` is the base price.
`15 tip` means to *add 15% to the total.*
`25 discount` means to *subtract 25% from the total.*
`1.5 extra` means to *add 1.5 to the total.*
`2 coupon` means to *subtract 2 from the total.*
There may be **any amount of** tips, discounts, coupons, and extras, but there will always be one base price.
Then we do `(12.34 * 1.15) * 0.75 + 1.5 - 2` for an output of 10.14. 10.14 is greater than 0, so we output false. My lunch was not free.
# Rules
*number* `tip` means to add *number* percent to the total.
*number* `discount` means to subtract *number* percent from the total
*number* `extra` means to add *number* to the total
*number* `coupon` means to subtract *number* from the total
# Another example:
```
10
20 tip
20 discount
2 coupon
2 coupon
1 coupon
50 discount
2.55 coupon
```
The price is `-0.24` ((10 \* 1.20 \* 0.80 - 2 - 2 - 1) \* 0.5 - 2.55), so the output is true (my lunch was free.)
Notes:
* Precision must be at least 2 decimal places.
* You can take input as a string with newlines (trailing newline optional) or another separation character, or an array/list of the inputs.
[Answer]
## JavaScript (ES6), ~~88~~ 85 bytes
Takes input as an array of strings. Returns `0` for not free or `1` for free.
```
a=>a.map(s=>([a,b]=s.split` `,t+={e:+a,c:-a,t:x=t*a/100,d:-x}[(b||'e')[0]]),t=0)|t<=0
```
### How it works
Each line is split on the space to get `a` = amount, `b` = type of operation. If there's no operation at all (which is the case on the first line), `b` is set by default to `"e"` for "extra".
To add the correct amount to the total `t`, we use an object whose keys are the first letter of the operation:
```
{
e: +a, // extra
c: -a, // coupon
t: t * a / 100, // tip
d: -t * a / 100 // discount
}
```
**Note**: If the bill consisted of only one element, `map()` would return a single-element array which would be coerced to an integer when applied the `|` operator, making the final test fail. But the OP confirmed that this can't happen. (Arrays of 2 or more elements are coerced to 0.)
### Demo
```
let f =
a=>a.map(s=>([a,b]=s.split` `,t+={e:+a,c:-a,t:x=t*a/100,d:-x}[(b||'e')[0]]),t=0)|t<=0
console.log(f([
'12.34',
'15 tip',
'25 discount',
'1.5 extra',
'2 coupon'
]))
console.log(f([
'10',
'20 tip',
'20 discount',
'2 coupon',
'2 coupon',
'1 coupon',
'50 discount',
'2.55 coupon'
]))
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~45~~ 42 bytes
```
q~Sf/(sd\{L(d\~ci6%"1\-* + )* -"S/=~}fL0>!
```
Take input as an array of strings, and takes the tip and discount as decimals.
[Try it online!](https://tio.run/nexus/cjam#@19YF5ymr1GcElPto5ESU5ecaaaqZBijq6WgraCppaCrFKxvW1eb5mNgp/j/f7SSoYESl5KekYFCSWYBlJWSWZycX5pXAuQaKQBZBfl5qExDBFPPFFW9nqkpTDIWAA "CJam – TIO Nexus")
**Explanation**
```
q~ e# Read and eval the input.
Sf/ e# Split each string by spaces.
(sd e# Pull out the first element (base price) and cast it to a double.
\ e# Bring the array back to the top.
{ e# For each element L in the array:
L e# Push L.
(d e# Pop out the first element and cast it to a double.
\~ e# Bring the second element to the top of the stack.
ci6% e# Mod its first character's ASCII value by 6. (c,d,e,t) -> (3,4,5,2)
"1\-* + )* -"S/ e# Push this string and split it on spaces.
= e# Get the element given by number from the mod. CJam uses modular arrays,
e# so 4 and 5 get elements 0 and 1 respectively.
~ e# Eval whichever string was retrieved.
}fL e# (end of loop)
0>! e# Check if it's not greater than 0.
```
The code which is evaluated depending on the first letters:
```
t -> ")*" Adds 1 to the tip amount and multiplies it by the current price.
d -> "1\-*" Subtracts the discount amount from 1 and multiplies it by the current price.
e -> "+" Adds the extra amount to the current price.
c -> "-" Subtracts the coupon amount from the current price.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁾_@
⁾C×
”+
⁾‘×
ḲµṪḢO%7µĿṭ
ḢW;Ç€j”µFV>0¬
```
Takes a list of strings with decimal formatted numbers
(Leading zeros *will* work, but have the side effect of printing zeros to STDOUT prior to the final result).
**[Try it online!](https://tio.run/nexus/jelly#@/@ocV@8AxeQdD48netRw1xtEPtRwwwg7@GOTYe2Pty56uGORf6q5oe2Htn/cOdaoOiicOvD7Y@a1mQBlR/a6hZmZ3Bozf///6PVDY30jE3UddT1DE0VSjILQCwjU4WUzOLk/NK8EiDXUM9UIbWipCgRyDZSAIoW5OepxwIA)** - not free; or [free](https://tio.run/nexus/jelly#@/@ocV@8AxeQdD48netRw1xtEPtRwwwg7@GOTYe2Pty56uGORf6q5oe2Htn/cOdaoOiicOvD7Y@a1mQBlR/a6hZmZ3Bozf///6PVDQ3UddT1jAwUSjILoKyUzOLk/NK8EiDXSAHIKsjPQ2UaIph6pqjq9UxNYZKxAA).
### How?
```
⁾_@ - Link 1: a coupon
⁾_@ - literal "_@" - the Jelly code for subtraction with reversed arguments
⁾C× - Link 2: a discount
⁾C× - literal "C×" - the Jelly code for complement (1-input) then multiply
”+ - Link 3: extra cost
”+ - literal '+' - the Jelly code for add
⁾‘× - Link 4: a tip
⁾‘× - literal "‘×" - the Jelly code for increment (input+1) then multiply
ḲµṪḢO%7µĿṭ - Link 5, switch: char list
Ḳ - split on spaces (gives [amount, type] as char lists)
µ µ - monadic chain separation to get a value, say v
Ṫ - tail (get the type: "coupon", "discount", "extra", or "tip")
Ḣ - head (get the first character: 'c', 'd', 'e' or 't')
O - cast to ordinal (99, 100, 101, or 116)
%7 - mod 7 (1, 2, 3, or 4)
Ŀ - call link v as a monad
ṭ - tack to the amount char list
ḢW;Ç€j”µFV>0¬ - Main link: list of strings (char lists)
Ḣ - head - the base price char list
W - wrap in a list
Ç€ - call the last link (5) as a monad for €ach of the rest
; - concatenate
”µ - literal 'µ' - Jelly's monadic chain separator
j - join all the parts with 'µ's "10",".2 tip",".2 discount", "2 coupon","2 coupon","1 coupon",".5 discount","2.55 coupon":
F - flatten (makes a char list, for example: "10µ.20‘×µ.20C×µ2_@µ2_@µ1_@µ.50C×µ2.55_@")
V - evaluate as Jelly code (the above evaluates to -0.2499999999999991)
>0 - greater than 0?
¬ - not
```
[Answer]
# GNU sed + dc, ~~117~~ ~~111~~ 107 bytes
Using `-z` interpreter flag (included in score as 1 byte):
```
s/discount/_tip/g
s/tip/.01*1+*/g
s/extra/+/g
s/coupon/-/g
s/.*/dc -e '& 0r-p'/e
s/[^-]*$/free/
s/-/not /
```
## Explanation
```
#!/bin/sed -fz
# Convert to dc expression (discount is just a negative tip)
s/discount/_tip/g
s/tip/.01*1+*/g
s/extra/+/g
s/coupon/-/g
# Run dc
s/.*/dc -e '& 0r-p'/e
# Convert to pretty output
s/[^-]*$/free/
s/-/not /
```
Since the input is already very close to Reverse Polish notation, it's a simple matter to transform `extra` and `coupon` to `+` and `-`, and not much more to change the percentages into multipliers. Then invoke `dc` and produce a readable result depending on whether `-` is found (we have to negate the result, so a `-` implies "not free", otherwise 0 would be a special case that would need its own handling).
## Example
The second case from the question is:
```
10
20 tip
20 discount
2 coupon
2 coupon
1 coupon
50 discount
2.55 coupon
```
That becomes this `dc` program:
```
10
20 .01*1+*
20 _.01*1+*
2 -
2 -
1 -
50 _.01*1+*
2.55 -
0r-p
```
Resulting in:
```
free
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~37~~ ~~33~~ 34 bytes
```
I|vy#`0èÇ7%`">* - (>* +"#sè.V}î0›_
```
[Try it online!](https://tio.run/nexus/05ab1e#@@9ZU1apnGBweMXhdnPVBCU7LQVdBQ0gqa2kXHx4hV5Y7eF1Bo8adsX//29owGWgZ2SgUJJZAGGkZBYn55fmlXAZKQDpgvw8BMMQxjDQM0VWqGdqCpUBAA "05AB1E – TIO Nexus")
**Explanation**
Borrows the `mod 7` trick from [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/117841/47066)
```
I # initialize stack with first input
|v # loop over all other inputs
y#` # split input on space as separate to stack
0èÇ # get the character code of the first letter of the type
7%` # mod by 7
">* - (>* +"# # push the list ['>*','-','(>*','+'] where
# '>*' = increment and multiply
# '-' = subtract
# '(>*' = negate, increment, multiply
# '+' = add
s # swap the top 2 items on the stack
è # use the mod result to index into the list
.V # run as 05AB1E code
} # end loop
î0›_ # check if the result rounded up to nearest integer
# is less than or equal to 0
```
[Answer]
# JavaScript, ~~173~~ ~~169~~ 145 bytes
```
i=>{w=i.split`\n`.map($=>$.split` `);t=+w.shift()[0];p=$=>t*$/100;w.map(x=>{k=+x[0];f=x[1][0];l={e:k,c:-k,t:p(k),d:-p(k)},t+=l[f]});return t<=0;}
```
There should still be plenty of golfing to do
[Try it online!](https://tio.run/nexus/javascript-node#LYxNboMwFIT3PoUXLOxCXEzLBvdxEYrkiODEwrUteBFIiLNTiLKa0Tc/BnYL9TqDFVN0FvWv1@LvGlkCdfJGVHOFkM5ieliDjDd5qyIcBfxIPmWeq/m1WI6fAdLljA0sjWxP52DtqyHrqsuQYRXZwLNbdTl1yzAF15h242rs8Tl6ij@Qq23vgp@C64ULd2aYloX4@iaypGgjKUp6s1MXnh6JFCXtFxyvpKAHicFrzsn@Dw "JavaScript (Node.js) – TIO Nexus") (145 bytes currently)
Try it out:
```
<script>var _=i=>{w=i.split('\n').map($=>$.split(' '));t=+w.shift()[0];p=$=>t*$/100;w.map(x=>{k=+x[0];f=x[1][0];t+=f=='e'&&k||f=='c'&&(-k)||f=='t'&&p(k)||f=='d'&&(-p(k))});return t<=0;}</script>
<textarea oninput="document.querySelector('pre').innerText=_(this.value)"></textarea>
<pre></pre>
```
Thanks to programmer5000 for all his golfing advice
[Answer]
# JavaScript (ES6), 97 ~~107~~
Input as a multiline string with a trailing newline.
```
t=>t.replace(/(\S+) ?(.*)?\n/g,(x,d,b)=>t-=b>'t'?-t*d/100:b>'e'?d:b>'d'?t*d/100:b?-d:d,t=0)&&t>=0
```
The regexp splits the numeric and optional text part for each line in *d* and *b*.
The calculations should be more or less obviuos. Just some note:
- using `-=` to avoid problems mixing number with strings
- the sum is negated to save 1 byte, so the last check is for `>= 0` instead of `<= 0`
PS still way longer than @Arnauld's. Rats.
**Test**
```
var f=
t=>t.replace(/(\S+) ?(.*)?\n/g,(x,d,b)=>t-=b>'t'?-t*d/100:b>'e'?d:b>'d'?t*d/100:b?-d:d,t=0)&&t>=0
a=`12.34
15 tip
25 discount
1.5 extra
2 coupon
`
b=`10
20 tip
20 discount
2 coupon
2 coupon
1 coupon
50 discount
2.55 coupon
`
console.log('Not free: '+a,f(a))
console.log('Free: '+b,f(b))
```
[Answer]
# Python 133 bytes
```
def f(b):
t=float(b.pop(0))
for l in b:
v,a=l.split(' ');v=float(v);t+={'t':t*v/100,'d':-t*v/100,'c':-v,'e':v}[a[0]]
return t<=0
```
Similar to the JavaScript ES6 version. But type conversion is required for `float` values in Python.
Explanation:
Extract the first value and convert it to float.
For each other line in the bill:
1. split and convert the value to `float`
2. Use a `dict` to select the right operation according to the first letter
3. Accumulate the value
Usage:
```
print(f([
'12.34',
'15 tip',
'25 discount',
'1.5 extra',
'2 coupon'
]))
print(f([
'10',
'20 tip',
'20 discount',
'2 coupon',
'2 coupon',
'1 coupon',
'50 discount',
'2.55 coupon'
]))
```
[Answer]
# C# ~~324~~ 219 bytes
```
bool a(string[] l){var x=0f;foreach(var s in l){var b=float.Parse(s.Split(' ')[0]);if(s.EndsWith("p"))x*=b;else if(s.EndsWith("t"))x*=1-b;else if(s.EndsWith("n"))x-=b;else if(s.EndsWith("a"))x+=b;else x=b;}return x<=0;}
```
It's not pretty, and probably not the best way, but here it is.
Requires input be passed as a string array, and tips/discounts passed as floats (`0.15 tip` instead of `15 tip`) as this has been clarified as acceptible in the comments of the spec.
Explaination:
```
bool a(string[] l){ //Define method with input string array l and bool output
var x=0f; //Initialize float x
foreach(var s in l){ //Iterate through lines
var b=float.Parse(s.Split(' ')[0]); //Parse the number from the line and store it in float b
if(s.EndsWith("p")) //If line ends with "p" then line is "tip"
x*=b; //Parse number from line to float add 1 and multiply by x
else if(s.EndsWith("t")) //If line ends with "t" then line is "discount"
x*=1-b; //Parse number from line to float, subtract from 1 and multiply by x
else if(s.EndsWith("n")) //If line ends with "n" then line is "coupon"
x-=b; //Parse number from line to float and subtract from x
else if(s.EndsWith("a")) //If line ends with "a" then line is "extra"
x+=b; //Parse number from line to float and add to x
else x=b; //Line is base price
} //End foreach
return x<=0; //Return x less than or equal to 0
} //End method
```
There's gotta be a better way to do this, but this works at least
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 218 156 143 bytes
```
($n=$args)|%{[float]$v,$w=$_-split' ';switch -w($w){"t*"{$t+=$v}"d*"{$d+=$v}"e*"{$e+=$v}"c*"{$c+=$v}}};($n[0]*(1+$t/100)*(1-$d/100)+$e-$c)-lt 0
```
[Try it online!](https://tio.run/nexus/powershell#Jc1BCoMwFATQqwT5JUYba2xdiScRKRLTNiBRzK8WrMfuOo26ezOzGBeCKaEZn5Z9T0v16PoGa5jOMJdw53boNFJCCztrlC/C5xBmtgQYBQtgXMK0Bu3m9rDarA7LzXL3uhb@pkrrKBQx4EWkKfPk0O6MQXGQjHdIUuecyJLrzVGRE9QDdTTLSaut7N8GfRJJTtQHx2ZbiG@H3tCf6bls5Ev9AQ "PowerShell – TIO Nexus")
**EDIT** Saved bytes by splitting the piped variable beforehand
**EDIT 2** Stored second part of string so I could make better wildcard calls
[Answer]
# Java 227 bytes
Been a while and still no Java answer that I can see, so here's my [C# answer](https://codegolf.stackexchange.com/a/117925/44998) ported to Java, at the cost of 8 bytes
```
boolean a(String[] l){Float x=0f;for(String s:l){Float b=Float.parseFloat(s.split(" ")[0]);if(s.endsWith("p"))x*=b;else if(s.endsWith("t"))x*=1-b;else if(s.endsWith("n"))x-=b;else if(s.endsWith("a"))x+=b;else x=b;}return x<=0;}
```
For an explanation and such, see my [C# answer](https://codegolf.stackexchange.com/a/117925/44998)
Like that answer, this answer expects that the tip and discount be passed as floats (`0.15` not `15`)
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), ~~129~~ ~~119~~ ~~114~~ 112 bytes
```
reduce (.[]/" "|.[0]|=tonumber|.[1]|=length)as[$n,$c](0;[$n,0,0,.+.*($n/100),0,.+$n,.-$n,0,.-.*($n/100)][$c])<=0
```
Expanded
```
reduce (
.[]/" " # split each element into [value,command]
| .[0]|=tonumber # convert value to number
| .[1]|=length # convert command to length
) as [$n,$c]
( 0
; [ $n # "" -> set base
, 0
, 0
, .+.*($n/100) # "tip"
, 0
, .+$n # "extra"
, .-$n # "coupon"
, 0
, .-.*($n/100) # "discount"
][$c] # ... depending on command length
) <=0 # true if lunch was free
```
[Try it online!](https://tio.run/##VYtBDoIwEAC/0jQcQGlpTTgpL2l6QGi0BrcV2njh7dYFYwjZy8zO7uOVFJWClvQkSLD@B72dOhchLEaQvIM9yg3r/Tmv63/TcxpNHztDcq50RQmduRJ6boKD@LyaEVWiDgZu4V60k8qgzDqdi/NCAocf@SHPoJJCFKvinrM1crYlrfCtuDQipY/zwTqYEmMQh4FZ8DGgjO2buRhQvg "jq – Try It Online")
] |
[Question]
[
The Euclidean algorithm is a widely known algorithm for calculating the greatest common divisor (GCD) of two positive integers.
# The algorithm
For the purpose of this challenge, the algorithm is described as below:
1. Display the two input as adjacent lines of a certain character
e.g. an input of `3,4` can be represented by the adjacent lines `000` and `0000`
2. Turn the first `length(short_line)` characters in the longer line into another character, say `-`
now it looks like `000` and `---0`
3. Eliminate the first `length(short_line)` characters in the longer line.
now `000`, `0`
4. Repeat step 2 and 3 until the two have equal length, using the shorter and longer lines after each iteration, e.g.
`000`,`0`
`-00`,`0`
`00`,`0`
`-0`,`0`
`0`,`0`
5. You can choose whether to stop here or continue the iteration and turn one of the lines into an empty line.
Each of these steps should be separated by an interval between 0.3s and 1.5s.
# The challenge
Write a program that, given two natural numbers as input, creates an output that looks exactly the same as the output of the algorithm above. You can use other non-whitespace printable ASCII characters than `0` and `-`, but be consistent and use only two characters. You can also use alternative algorithms provided the output, including the timing, is exactly the same as would be produced by the algorithm above.
# Examples
This is an example with input `24,35`, which are coprimes so their GCD is 1.
[](https://i.stack.imgur.com/3mE1F.gif)
This is an example with input `16,42`, which have the GCD 2.
[](https://i.stack.imgur.com/2HayM.gif)
# Rules
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytes wins
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* You can assume input to be positive decimal integers
+ [Unless you are using sed, Retina, ///, etc, in which case you can use unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary/5349#5349)
---
**Clarifications**
* The lines that represent the numbers need to stay in their original order, i.e. the first and second lines of the first displayed "frame" need to be the first and second lines respectively, in all subsequent frames.
* After the algorithm ends, no additional *visible* entity should appear. However, this also means that it is okay to blank the lines, if you make sure that the last "frame" is displayed for at least the same amount of time as did all other frames before blanking out.
[Answer]
## JavaScript (ES6), ~~128~~ 124 bytes
```
t=0
f=
(a,b,o,c,d)=>setInterval(e=>{e=[b,d,a,c];o.data=`-0
-0`.replace(/./g,c=>c.repeat(e.pop()));c|d?c=d=0:a>b?a-=c=b:b-=d=a},1e3)
```
```
<form><input id=a><input id=b><button onclick=clearTimeout(t),t=f(+a.value,+b.value,o.firstChild)>Go!</button><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
VY“ñc‘ỌœS.⁸
1ẋǵ+M¦ṚÇt€2ǵ⁻/¿
```
[Try it online!](https://tio.run/nexus/jelly#@x8W@ahhzuGNyY8aZjzc3XN0crDeo8YdXIYPd3Ufbj@0Vdv30LKHO2cdbi951LTGCCTyqHG3/qH9/42O7H@4czZQ6///0SYWOuYGsQA "Jelly – TIO Nexus")
This defines a function `2Ŀ` (not a full program; the TIO link contains a footer that converts a function into a program) that takes a list of two elements as input, and displays the output on the screen (one of our legal I/O methods, and one that is kind-of necessary for this challenge because it talks about the appearance on screen). This assumes that the program is run in a terminal that complies with the ANSI standard (I used `gnome-terminal` but most will work), and that the terminal is initially empty (which seems like the most sensible default); note that Try it online! does *not* conform to these assumptions, and thus the output is distorted there (I ran the program locally to verify that it animates as expected). I use `1` where the question uses `0`, and `2` in place of `-`.
## Explanation
**Helper function** `1Ŀ` (given a list of two lists of digits, outputs them on the first and second lines of the screen, then waits 0.5 seconds; returns its input)
```
VY“ñc‘ỌœS.⁸
V Convert each list of digits to an integer
Y Separate these integers by newlines
“ñc‘ {Output that; then restart with} the list [27, 99]
Ọ Convert codepoints to characters (i.e. "\x1bc"
œS. Wait (œS) 0.5 (.) seconds
⁸ {Output that; then return} the initial argument
```
The string "\x1bc", when sent to an ANSI-compatible terminal, is interpreted as a control code to reset the terminal; this clears the screen and moves the cursor to the top left corner (thus resetting the terminal ready for the next output).
The helper function is named `1Ŀ` (Jelly autogenerates names of this form for functions, and in fact there's no other way to name them), but it can be referred to simply as `Ç` from the main program (because the language has shorthand for functions with numbers nearby).
**Main function** `2Ŀ` (implements the task requested in the question)
```
1ẋǵ+M¦ṚÇt€2ǵ⁻/¿
1ẋ Convert input to unary
Ç Call helper function (producing one animation frame)
µ µ ¿ While
⁻/ the elements differ:
M¦ Change the largest element
+ Ṛ by adding corresponding elements of the other element
Ç Call helper function (producing one animation frame)
t€2 Delete all 2s from each side of each element
Ç Call helper function (producing one animation frame)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~152~~ 146 bytes
```
import time
s,o='-0'
a,b=input()
while a*b:
d,e=o*a,o*b
if a>b:a=a-b;d=s*b+o*a
elif b>a:b=b-a;e=s*a+o*b
else:a=0
print d+'\n'+e;time.sleep(1)
```
[Try it online!](https://tio.run/nexus/python2#Hc1BDoMgEIXh/Zxidihgo110IcGTdDMTpykJChFMj29p19//8q6w5XRUrGETKDZ5NYwKyLIPez5r18PnHaIgaZ4BVys@abJJM2B4IS08k6eB3eqLZtMMUGITXmhmzwM5aULmv5BYpPUjYD7CXnE16rkrI@73fitRJHdTf13T3U6PLw "Python 2 – TIO Nexus")
---
Takes two comma-separated integers as input
[Answer]
# Javascript (ES6), ~~215 194~~ ... ~~135 129~~ 127 bytes
```
a=>b=>F=(c=0)=>alert('-'[d='repeat'](e=c&a>b&&b)+'0'[d](a-=e)+`
`+'-'[d](f=c&a<b&&a)+'0'[d](b-=f))|a-b|c&&setTimeout(F,1e3,1-c)
```
# Usage
This takes input in a variation on currying. To use it, fist assign the function to a variable (for example `G`), then call it like this:
```
G(5)(6)()
```
# Explanation
Somewhat recursive function that calls itself after 1 second as long as the algorithm hasn't finished. It keeps track of a third variable `c` that determines whether `a` and `b` should be changed (if `c` is `1`, it's time for change).
First, the function writes something to the console. If `c` is `0`, it writes two strings of zeroes with a newline inbetween. Since `c` is initialised to `0`, we can take advantage of this, and set up global variables `f` and `g` that hold some strings we need often (like `0` and `repeat`).
Otherwise, it builds up a string with zeroes and minuses. All such strings consist of two parts: first some (call this amount `A`) minuses, then some (call this amount `B`) zeroes, then a newline, then some (call this amount `D`) minuses and lastly some (call this amount `E`) zeroes.
If the first input is smaller than the second input, we need to remove zeroes from the second input, so `A` is zero, `B` equals the first input, `D` equals the first input and `E` equals the second input minus the first input. If the first input is not smaller than the second input, the reverse applies (`A` is the second input, `B` is the first input minus the second input etc.).
With these new values for the input and a switched variable `c`, the function is scheduled to be called again in `1e3` milliseconds, which equals one second.
# Notes
* Uses `alert` for output
* Uses `0` and `-`, just like in the examples
* Delay between steps is 1000 ms (1 second)
* After the first step, the function will (due to the nature of JavaScript) return some number which is to be ignored
* The version on TIO outputs everything at once, pasting the code in the browser console will properly take the delays into account
# Try it online
[Try it here!](https://tio.run/nexus/javascript-node#PY7BCoJAFEX3/UUb5z2cCSVqMfSanV/QTgRnxucQWBNpq@zbTTHaXTjnwJ0KAiud9JQjnd8@3vvY8a6LAbyBQCITWLYknvxgO4gKLKb1pk5D2VbgUAsllgUNAZPFk0OTaYcrb4zVYBU5XKOf3BjW2V8Bp4hxblDOrhvHrcck6Xm4XG8cXwMUMue9XE7myuNnKuAgjzh9AQ)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~208~~ ~~204~~ 194 bytes
-4 with thanks to @math\_junkie for the sneaky trick with `time.sleep`
-10 with thanks to @busukxuan for clarifying the "clear screen" rule.
```
def z(a,b,y='-',w=1):
import time;c,d,n,s='0'*a,'0'*b,'\n',time.sleep
if w:print c+n+d;s(1)
if b>a:d=y*a+d[a:]
else:c=y*b+c[b:]
print c+n+d;s(1)
if c!=d:z(len(c),len(d),('','-')[y!='-'],0)
```
[Try it online!](https://tio.run/nexus/python2#bY7LCoMwFET3fkVc3cTcFu1jE0l/xLrI4wqCpmIE0Z@3putuZuAMB@bw1LGdG7S4abgArroSKmP9OH3mhS39SLVDjwGjhhIKgyktwjsApvUaB6LpFDq2qmnuw8KcDNLXkVfih@3LKK@3wkjfGNVmjIZIyp3EStfYRP56Ltde7XygwJ3AVF4gB8Dzpmi2PN1tsRTHzm8PvD/F8QU "Python 2 – TIO Nexus")
Pretty sure this could be more golfed. It pains me to duplicate the `print` and the `for` loop to create the pause but I can't find a way round it at the moment.
**Notes**
* The pause now uses a hint from @math\_junkie
* Doesn't fully work on TIO as it stores the output and dumps it out when the program finishes. Works fine in the console though.
[Answer]
# perl, ~~161~~ 149 bytes
...without indentations and newlines:
```
($a,$b)=map 0 x$_,@ARGV;
sub p{say"\n$a\n$b";sleep 1}p;
while($a ne$b){
($A,$B)=$b lt$a?(\$a,\$b):(\$b,\$a);
map$$A=~s/0/-/,1..length$$B;
p;
$$A=~s/-//g;
p
}
```
Put it into a file gcd.pl and run like this:
```
perl -M5.010 gcd.pl 16 42
```
[Answer]
# GNU Sed (with `e`xec extension), 88
Score includes +3 for `-zrf` options to `sed`.
```
p
:
x
esleep 1
g
ta
:a
s/o+//p
t
s/^((O+)(O+)\n\2\b|(O+)\n\4\B)/\L\2\U\3\4\n\2\L\4\U/p
t
```
Input is given as two newline separated unary integers, using the upper case `O` as digits.
For example, the 16, 42 example may be run as:
```
printf "%0*d\n%0*d\n" 16 0 42 0 | tr 0 O | sed -znrf euclidvis.sed
```
As per the latest comments, I am not clearing the screen between iterations.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~47~~ 44 bytes
```
Àé0á
Àé0Hqwmmjlhmmkl@wqòHî@w
gs`mlhv0r-gsÓ-ò
```
[Try it online!](https://tio.run/nexus/v#s8pNLFBIL1bIzfOozHIvSMj7f7jh8EqDwwu5wLRHYXlublZORm5udo5DeeHhTR6H1zmUc6UXJ@TmZJQZFOmmFx@erHt403@PlKz//y0M/xsZAgA "V – TIO Nexus")
The header and footer on TIO just modify `gs` to copy the current two lines to the bottom of the screen, and then delete the first two at the end. This visualizes the operation for TIO, but if you ran it in V (without the header and footer), it would just wait a second between each operation.
```
Àé0 " Print (Arg1) zeroes
á " Newline
Àé0 " Print (Arg2) zeroes
H " Go home
qwmmjlhmmkl@wq " Store a recursive macro in w that finds the shorter line
ò " recursively
Hî@w " find the longest line
gs " wait a second
`mlhv0r- " replace the zeroes of the long line with -
gs " wait a second
Ó- " delete all -
ò " end recursion
```
] |
[Question]
[
Two distinct vertices in a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) are strongly connected if there is [path](https://en.wikipedia.org/wiki/Path_(graph_theory)) in the graph from each to the other. A [strongly connected component](https://en.wikipedia.org/wiki/Strongly_connected_component) of the graph is a subset of the graph such that each pair of distinct vertices in the subset are strongly connected, and adding any more vertices to the subset would break this property.
Your challenge is to separate a graph into its strongly connected components. Specifically, you must output all of the SCCs in the graph.
**I/O:**
As input, you may use a list of directed edges, an adjacency list, an adjacency matrix, or any other reasonable input format. Ask if you're not sure. You may assume the graph has no totally disconnected vertices, and that there are no self edges, but you may not make any further assumptions. You may also optionally take the list of vertices as input, as well as the number of vertices.
As output, you must either give a partitioning of the vertices, such as a list of lists of vertices, where each sublist is a strongly connected component, or a labeling of vertices, where each label corresponds to a different component.
If you use a labeling, the labels must either be vertices, or a consecutive sequence of integers. This is to prevent offloafing the computation into the labels.
**Examples:**
These examples take lists of edges, where each edge is directed from the 1st entry to the second entry, and output partitions. You are free to use this format or another.
The input is on the first line, the output is on the second line.
```
[[1, 2], [2, 3], [3, 1], [1, 4]]
[[1, 2, 3], [4]]
[[1, 2], [2, 3], [3, 4]]
[[1], [2], [3], [4]]
[[1, 2], [2, 1], [1, 3], [2, 4], [4, 2], [4, 3]]
[[1, 2, 4], [3]]
[[1, 2], [2, 3], [2, 5], [2, 6], [3, 4], [3, 7], [4, 3], [4, 8], [5, 1], [5, 6], [6, 7], [7, 6], [8, 7], [8, 4]]
[[1, 2, 5], [3, 4, 8], [6, 7]]
```
**Scoring and restrictions:**
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned, as always. Also, built-ins which specifically deal with strongly connected components are banned.
Solutions should run in no more than an hour on the examples provided. (This is intended to prevent slow exponential solutions, and nothing else.)
This is code golf. Fewest bytes wins.
[Answer]
## Python 2 using numpy, ~~71~~ 62 bytes
```
import numpy
def g(M,n):R=(M+M**0)**n>0;print(R&R.T).argmax(0)
```
Takes input as a `numpy` matrix representing adjacency and the number of nodes. Produces output as a `numpy` row matrix that labels each vertex by the lowest vertex number in its component.
For an adjacency matrix `M`, the matrix power `M**n` counts the number of `n`-step paths from each start vertex to each end vertex. Adding the identity to `M` via `M+M**0` modifies the adjacency matrix to add a self-loop to every edge. So, `(M+M**0)**n` counts paths of length at most `n` (with redundancy).
Since any path has length at most `n`, the number of nodes, any `(i,j)` where vertex `j` can be reached from `i` corresponds to a positive entry of `(M+M**0)**n`. The reachability matrix is then`R=(M+M**0)**n>0`, where the `>0` works entrywise.
Computing the entrywise `and` as `R&R.T`, where `R.T` is the transpose, then gives a matrix indicating the pairs of mutually reachable vertices. It's `i`th row is an indicator vector for vertices in the same strongly connected component as it. Taking its `argmax` of each row gives the index of the first `True` in it, which is the index of the smallest vertex in its component.
[Answer]
## JavaScript (ES6), 125 bytes
```
a=>a.map(([m,n])=>(e[m]|=1<<n|e[n],e.map((o,i)=>o&1<<m?e[i]|=e[m]:0)),e=[])&&e.map((m,i)=>e.findIndex((n,j)=>n&1<<i&&m&1<<j))
```
Takes a list of directed pairs as an argument, while the result is a array for each vertex giving the first vertex strongly connected to it, which I believe counts as a valid labelling. For example, with the input `[[1, 2], [2, 3], [2, 5], [2, 6], [3, 4], [3, 7], [4, 3], [4, 8], [5, 1], [5, 6], [6, 7], [7, 6], [8, 7], [8, 4]]` it returns `[, 1, 1, 3, 3, 1, 6, 6, 3]` (there is no vertex 0; vertexes 1, 2 and 5 have label 1; 3, 4 and 8 have label 3 while 6 and 7 have label 6).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~26~~ 22 bytes
```
tnX^Xy+HMY^gt!*Xu!"@f!
```
This uses the same approach as [@xnor's answer](https://codegolf.stackexchange.com/a/76302/36398).
Works in [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language.
Input is the adjacency matrix of the graph, with rows separated by semicolons. The first and last test cases are
```
[0 1 0 1; 0 0 1 0; 1 0 0 0; 0 0 0 0]
[0 1 0 0 0 0 0 0; 0 0 1 0 1 1 0 0; 0 0 0 1 0 0 1 0; 0 0 1 0 0 0 0 1; 1 0 0 0 0 1 0 0; 0 0 0 0 0 0 1 0; 0 0 0 0 0 1 0 0; 0 0 0 1 0 0 1 0]
```
[**Try it online!**](http://matl.tryitonline.net/#code=dG5YXlh5K0hNWV5ndCEqWHUhIkBmIQ&input=WzAgMSAwIDAgMCAwIDAgMDsgMCAwIDEgMCAxIDEgMCAwOyAwIDAgMCAxIDAgMCAxIDA7IDAgMCAxIDAgMCAwIDAgMTsgMSAwIDAgMCAwIDEgMCAwOyAwIDAgMCAwIDAgMCAxIDA7IDAgMCAwIDAgMCAxIDAgMDsgMCAwIDAgMSAwIDAgMSAwXQ)
```
t % implicitly input adjacency matrix. Duplicate
n % number of elements
X^ % square root
Xy % identity matrix of that size
+ % add to adjacency matrix
HM % push size again
Y^ % matrix power
g % convert to logical values (0 and 1)
t!* % multiply element-wise by transpose matrix
Xu % unique rows. Each row is a connected component
! % transpose
" % for each column
@ % push that column
f! % indices of nonzero elements, as a row
% end for each. Implicitly display stack contents
```
[Answer]
# Pyth, 13 bytes
```
.gu+Gs@LQG.{k
```
[Demonstration](https://pyth.herokuapp.com/?code=.gu%2BGs%40LQG.%7Bk&input=%7B1%3A+%5B2%5D%2C+2%3A+%5B3%2C+5%2C+6%5D%2C+3%3A+%5B4%2C+7%5D%2C+4%3A+%5B3%2C+8%5D%2C+5%3A+%5B1%2C+6%5D%2C+6%3A+%5B7%5D%2C+7%3A%5B6%5D%2C+8%3A%5B4%2C+7%5D%7D&test_suite_input=%7B1%3A+%5B2%2C+4%5D%2C+2%3A+%5B3%5D%2C+3%3A+%5B1%5D%2C+4%3A+%5B%5D%7D%0A%7B1%3A+%5B2%5D%2C+2%3A+%5B3%5D%2C+3%3A+%5B4%5D%2C+4%3A+%5B%5D%7D%0A%7B1%3A+%5B2%2C+3%5D%2C+2%3A+%5B1%2C+4%5D%2C+3%3A+%5B%5D%2C+4%3A+%5B2%2C+3%5D%7D%0A%7B1%3A+%5B2%5D%2C+2%3A+%5B3%2C+5%2C+6%5D%2C+3%3A+%5B4%2C+7%5D%2C+4%3A+%5B3%2C+8%5D%2C+5%3A+%5B1%2C+6%5D%2C+6%3A+%5B7%5D%2C+7%3A%5B6%5D%2C+8%3A%5B4%2C+7%5D%7D&debug=0), [Test suite](https://pyth.herokuapp.com/?code=.gu%2BGs%40LQG.%7Bk&input=%7B1%3A+%5B2%5D%2C+2%3A+%5B3%2C+5%2C+6%5D%2C+3%3A+%5B4%2C+7%5D%2C+4%3A+%5B3%2C+8%5D%2C+5%3A+%5B1%2C+6%5D%2C+6%3A+%5B7%5D%2C+7%3A%5B6%5D%2C+8%3A%5B4%2C+7%5D%7D&test_suite=1&test_suite_input=%7B1%3A+%5B2%2C+4%5D%2C+2%3A+%5B3%5D%2C+3%3A+%5B1%5D%2C+4%3A+%5B%5D%7D%0A%7B1%3A+%5B2%5D%2C+2%3A+%5B3%5D%2C+3%3A+%5B4%5D%2C+4%3A+%5B%5D%7D%0A%7B1%3A+%5B2%2C+3%5D%2C+2%3A+%5B1%2C+4%5D%2C+3%3A+%5B%5D%2C+4%3A+%5B2%2C+3%5D%7D%0A%7B1%3A+%5B2%5D%2C+2%3A+%5B3%2C+5%2C+6%5D%2C+3%3A+%5B4%2C+7%5D%2C+4%3A+%5B3%2C+8%5D%2C+5%3A+%5B1%2C+6%5D%2C+6%3A+%5B7%5D%2C+7%3A%5B6%5D%2C+8%3A%5B4%2C+7%5D%7D&debug=0)
Input is an adjacency list, represented as a dictionary which maps vertices to the list of vertices it has edges to (its directed neighbors). Output is a partition.
The essence of the program is that we find the set of vertices that are reachable from each vertex, and then group the vertices by those sets. Any two vertices in the same SCC have the same set of vertices reachable from them, because each is reachable from the other, and reachability is transitive. Any vertices in different components have different reachable sets, because neither's set contains the other.
**Code explanation:**
```
.gu+Gs@LQG.{k
Implicit: Q is the input adjacency list.
.g Q Group the vertices of Q by (Q is implicit at EOF)
u .{k The fixed point of the following function,
starting at the set containing just that vertex
+G Add to the set
s The concatenation of
@LQG Map each prior vertex to its directed neighbors
```
] |
[Question]
[
The American football championship, [Super Bowl 50](https://en.wikipedia.org/wiki/Super_Bowl_50), is happening today at 11:30pm [UTC](http://www.worldtimeserver.com/current_time_in_UTC.aspx) (and you can [watch it live online](http://www.cbssports.com/nfl/superbowl/live/player?ttag=SB16_os_lk_nstar_watch)). This challenge was made to celebrate it.
---
In an American football game, two teams compete to get the most points and there are [six ways to score](https://en.wikipedia.org/wiki/American_football_rules#Scoring) these points. We'll give each an abbreviation:
* [Field goal](https://en.wikipedia.org/wiki/Field_goal) - `FG`: 3 points
* [Touchdown](https://en.wikipedia.org/wiki/Touchdown) - `TD`: 6 points
* [Extra point](https://en.wikipedia.org/wiki/Conversion_(gridiron_football)) - `XP`: 1 point - Can only be scored directly after a touchdown.
* [Two-point conversion](https://en.wikipedia.org/wiki/Two-point_conversion) - `XD` (like an extra point but happier): 2 points - Can only be scored directly after a touchdown.
* [Safety](https://en.wikipedia.org/wiki/Safety_(gridiron_football_score)) - `S`: 2 points
* [Fair catch kick](https://en.wikipedia.org/wiki/Fair_catch_kick) - `FCK`: 3 points (a very rare play)
Write a program or function that takes in a single line string containing only these six abbreviations, in both uppercase and lowercase.
This string represents all the scoring events in a game (or portion of a game) of football, with the uppercase terms belonging to one team and the lowercase belonging to the other.
Your job is to report the final scores of the game and indicate who won with output of the form
```
[score 1] [to] [score 2]
```
where:
* `[score 1]` is always the larger of the two scores (if not equal), regardless of if uppercase or lowercase won.
* `[score 2]` is the smaller of the two scores (if not equal).
* `[to]` is `TO` if the uppercase team won, `to` if the lowercase team won, and `To` if it's a tie.
>
> **Example:** All the [scoring events](http://espn.go.com/nfl/playbyplay?gameId=400749027) in [Super Bowl XLIX](https://en.wikipedia.org/wiki/Super_Bowl_XLIX)
> could be summarized by the string
>
>
>
> ```
> TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP
>
> ```
>
> where uppercase is the [New England Patriots](https://en.wikipedia.org/wiki/New_England_Patriots) and lowercase is the
> [Seattle Seahawks](https://en.wikipedia.org/wiki/Seattle_Seahawks). The Patriots scored 28 and the Hawks 24, so
> the output would be:
>
>
>
> ```
> 28 TO 24
>
> ```
>
>
# Notes
* Your program/function must support any arbitrary input, including the empty string.
* `XP` and `XD` will only occur right after `TD`. `xp` and `xd` will only occur right after `td`.
* You may not assume the input string starts or ends in a certain case.
* A single trailing newline is optionally allowed in both the input and output
# Scoring
**The shortest code in bytes wins.** Answers that are posted before the kickoff (**too late now!**) of Super Bowl 50 may predict the winning team (either [Panthers](https://en.wikipedia.org/wiki/Carolina_Panthers) or [Broncos](https://en.wikipedia.org/wiki/Denver_Broncos)), and if they are correct, get a -10% byte bonus!
(I will check revision history to ensure predictions have not changed and really were made before kickoff.)
# Test Cases
```
[empty string] -> 0 To 0
TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP -> 28 TO 24
FG -> 3 TO 0
fg -> 3 to 0
TD -> 6 TO 0
td -> 6 to 0
TDXP -> 7 TO 0
tdxp -> 7 to 0
TDXD -> 8 TO 0
tdxd -> 8 to 0
S -> 2 TO 0
s -> 2 to 0
FCK -> 3 TO 0
fck -> 3 to 0
TDTDXDSssFCKfgfckFGtd -> 22 TO 16
fcksFCKS -> 5 To 5
tdtdtdtdxp -> 25 to 0
SSSSSSSTD -> 20 TO 0
fgSfckFGfgtdxptdxdTDs -> 26 to 11
FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK -> 29 To 29
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 51\*0.9 = 45.9 ~~54~~ ~~57~~ ~~58~~ ~~63~~ bytes
*Thanks to Dennis for removing 3 bytes!*
```
'%i To %i'j0h!3'PDFTS'tkXc=s4:Hh*sSPYD3MdXK?kK0<?Xk
```
An empty input string is represented in the online compiler as a single newline character.
*EDIT (June 8, 2016): The link below includes a modification as per release 18.1.0 of the language (move he first `3` right before `Xc`)*
[**Try it online!**](http://matl.tryitonline.net/#code=JyVpIFRvICVpJ2owaCEnUERGVFMndGszWGM9czQ6SGgqc1NQWUQzTWRYSz9rSzA8P1hr&input=ZmdTZmNrRkdmZ3RkeHB0ZHhkVERzCg)
I bet on the Broncos.
### Explanation
The scores are detected using a single letter, either upper or lowercase (uppercase is shown in the following):
* `P` for XP (1 point)
* `D` for XD (2 points)
* `F` for FG (3 points) and for FCK (3 points)
* `T` for TD (6 points)
* `S` for S (2 points)
Each of these five letters corresponds uniquely to a score event except that
* `F` is reused for `FG` and `FCK`, which have the same score. *Thanks to @Dennis for this*!
* `D` will detect both TD and XD. So `T` will be assigned 4 points instead of 6 to compensate.
The ordering `PDFTS`, saves a few bytes when defining the number array that specifies the points: `[1,2,3,4,2]`.
Each event is detected by the presence of one of the above letters in uppercase or lowercase. The comparison is done in three dimensions: input string length (*N*) × number of teams (2) × number of detected score events (5). Extensive use is made of [broadcasting](https://www.gnu.org/software/octave/doc/interpreter/Broadcasting.html), which is the automatic expansion of an array along a singleton dimension to match the size of a larger array.
```
'%i To %i' % string with format specifiers for two integers
j0h % input string. Attach 0 so it's never empty. Gives string of length N>0
! % transpose into char array of size N×1
3 % number literal
'PDFTS' % characters to detect the five combined types of score
tk % duplicate and convert to lowercase
Xc % concatenate along the third dimension to produce a 1×5×2 array
= % test for equality with broadcast. Gives N×5×2 array
s % sum along 1st dim. Gives 1×5×2 array
4:Hh % array [1,2,3,4,2] to compute the total score. Size 1×5(×1)
* % multiply with broadcast. Gives 1×5×2 array
s % sum along 2nd dim. Gives 1×1×2 array with the two scores
SP % sort in reverse order along 3rd dim
YD % sprintf. Gives output string with "To"
3M % push array with the two scores again
dXK % difference along 3rd dim. Gives a number. Copy to clipboard K
? % is it non-zero? If so we need to make either lowercase or uppercase
k % make (tentatively) lowercase
K0< % did the uppercase team win?
? % if so...
Xk % make uppercase
% implicitly end the two if's and display string
```
[Answer]
# Pyth, ~~49~~ ~~46~~ ~~43~~ 42 bytes (37.8 bytes with bonus)
```
jr" to "xh._-FJmsmhx"PSFT"kXd\D\S,rz2z2_SJ
```
*Thanks to @Maltysen for helping me save 4 bytes!*
Try it in the [Pyth Compiler](https://pyth.herokuapp.com/?code=jr%22+to+%22xh._-FJmsmhx%22PSFT%22kXd%5CD%5CS%2Crz2z2_SJ&input=TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP&test_suite=1&test_suite_input=TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP%0ATDTDXDSssFCKfgfckFGtd%0AfgSfckFGfgtdxptdxdTDs%0AFGTDXPtdxdtdsStdxpfgTDfckTDXDFCK&debug=0).
I like covering all bases, so I'll bet on the Broncos.
### How it works
```
jr" to "xh._-FJmsmhx"PSFT"kXd\D\S,rz2z2_SJ Input: z
rz2 Swap the case of z.
, z Pair the result with z.
m Map; for each d in the pair:
Xd\D\S Replace each D with an S.
m Map; for each character k:
x"PSFT"k Compute k's first index on "PSFT".
h Increment the index.
s Compute the sum of the incr. indices.
"FG" -> [3, 0] -> 3
"TD" -> [4, 2] -> 6
"XP" -> [0, 1] -> 1
"XD" -> [0, 2] -> 2
"S" -> [2] -> 2
"FCK" -> [3, 0, 0] -> 3
(lowercase letters) -> 0
J Save the resulting list of scores in J.
-F Reduce J by subtraction.
._ Compute the sign of the difference.
h Add 1.
x 2 XOR the result with 2.
r" to " Pick‡ a function and apply it to " to ".
_SJ Sort and reverse the list of scores.
j Join, separating by the modified string.
```
‡ `r` is a family of functions that operate on strings.
* If the first score in `J` (corresponding to swapped case `z`, i.e., the original lowercase letters) is lower than the second score, the sign function will return `-1`, `(-1 + 1) ^ 2 == 2` and `r" to "2` is `swapcase`, so it returns `" TO "`.
* If the first score is higher than the second score, the sign function will return `1`, `(1 + 1) ^ 2 == 0` and `r" to "0` is `lowercase`, so it returns `" to "`.
* If the scores are equal, the sign function will return `0`, `(0 + 1) ^ 2 == 3` and `r" to "3` is `title`, so it returns `" To "`.
[Answer]
# CJam, ~~57~~ ~~55~~ ~~54~~ ~~53~~ ~~50~~ 49 bytes
```
q_32f^]{"PSFTD"f#:)5Yer1b}%_$(@:-g"ToTOto"2/=\]S*
```
[Try it online!](http://cjam.tryitonline.net/#code=cV8zMmZeXXsiUFNGVEQiZiM6KTVZZXIxYn0lXyQoQDotZyJUb1RPdG8iMi89XF1TKg&input=ZmdTZmNrRkdmZ3RkeHB0ZHhkVERz)
I have no idea what a Bronco is, so I'll bet on the Panthers.
### How it works
```
q Read all input from STDIN.
_ Push a copy.
32f^ XOR all characters with 32. This swaps case.
] Wrap both strings in an array.
{ }% Map; push the string S, then:
"PSFTD" Push that string (T).
f# Compute the index of each character of S in T.
:) Increment each index.
5Yer Replace 5's with 2's.
1b Add the resulting integers.
"FG" -> [3 0] -> 3
"TD" -> [4 2] -> 6
"XP" -> [0 1] -> 1
"XD" -> [0 2] -> 2
"S" -> [2] -> 2
"FCK" -> [3 0 0] -> 3
(lowercase letters) -> 0
We've now computed the scores of the first (input)
and second (swapped case) team.
_$ Push a copy of the array of scores and sort it.
( Shift out the first (lower) score.
@ Rotate the array of scores on top.
:- Reduce it by subtraction.
g Compute the sign (1, 0 or -1) of the difference.
"ToTOto"2/ Push ["To" "TO" "to"].
= Select the string that corresponds to the sign.
\ Swap it with the lower score.
] Wrap the entire stack in an array.
S* Join the resulting array, separating by spaces.
```
[Answer]
# JavaScript (ES6), 128 ~~130~~ bytes
**Edit** 2 bytes saved applying @Neil's tip
```
s=>(l=u=0,s.replace(/fck|s|../gi,x=>(z=+' 231 362'[parseInt(x,36)%10],x>'a'?l+=z:u+=z)),l>u?l+' to '+u:u+(u>l?' TO ':' To ')+l
```
**TEST**
```
f=s=>(
l=u=0,
s.replace(/fck|s|../gi,x=>(
z=+' 231 362'[parseInt(x,36)%10],
x>'a'?l+=z:u+=z
)),
l>u?l+' to '+u:u+(u>l?' TO ':' To ')+l
)
//TEST
console.log=x=>O.textContent+=x+'\n'
;[
["","0 To 0"],
["TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP", "28 TO 24"],
["FG", "3 TO 0"],
["fg", "3 to 0"],
["TD", "6 TO 0"],
["td", "6 to 0"],
["TDXP", "7 TO 0"],
["tdxp", "7 to 0"],
["TDXD", "8 TO 0"],
["tdxd", "8 to 0"],
["S", "2 TO 0"],
["s", "2 to 0"],
["FCK", "3 TO 0"],
["fck", "3 to 0"],
["TDTDXDSssFCKfgfckFGtd", "22 TO 16"],
["fcksFCKS", "5 To 5"],
["tdtdtdtdxp", "25 to 0"],
["SSSSSSSTD", "20 TO 0"],
["fgSfckFGfgtdxptdxdTDs", "26 to 11"],
["FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK", "29 To 29"]
].forEach(t=>{
var i=t[0],x=t[1],r=f(i)
console.log(i+' -> '+r+(r==x?' OK':' FAIL expected '+x))
})
```
```
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6), ~~165~~ ~~156~~ ~~151~~ 149 bytes
```
s=>(a=b=0,s.match(/S|FCK|../gi)||[]).map(m=>(u=m.toUpperCase(),p=u>"XO"?1:u=="TD"?6:u>"R"?2:3,u<m?a+=p:b+=p))&&a>b?a+" to "+b:b+(b>a?" TO ":" To ")+a
```
*9 bytes saved thanks to [@dev-null](https://codegolf.stackexchange.com/users/48657/dev-null), 5 thanks to [@Not that Charles](https://codegolf.stackexchange.com/users/13950/not-that-charles) and 2 thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
## Explanation
```
var solution =
s=>(
a=b=0, // scores for teams A and B
s.match(/S|FCK|../gi) // get an array of each abbreviation
||[] // if it returns null, default to an empty array
).map(m=>( // for each abbreviation m
u=m.toUpperCase(), // u = abbreviation in upper-case
p= // p = number of points for the abbreviation
u>"XO"?1 // case "XP"
:u=="TD"?6 // case "TD"
:u>"R"?2 // case "XD" or "S"
:3, // case "FG" or "FCK"
u<m?a+=p:b+=p // add the points to the appropriate team
))
// Output the scores
&&a>b?a+" to "+b
:b+(b>a?" TO ":" To ")+a
```
```
<input type="text" id="input" value="FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
### Perl, ~~144~~ 140 + 2 = 142 bytes
```
%a=qw(fg 3 td 6 xp 1 xd 2 s 2 fck 3);@a=(0,0);$^=lc,$a[$^eq$_]+=$a{$^}for/fck|s|../gi;$,=$".(To,TO,to)[$a[1]-$a[0]<=>0].$";say sort{$b-$a}@a
```
Requires the `-n` flag and `-E`:
```
$ echo "
TDXPtdxpTDXPtdxpfgtdxpTDXPTDXP
FG
fg
SSSSSSSTD
FGTDXPtdxdtdsStdxpfgTDfckTDXDFCK" | \
perl -nE'%a=qw(fg 3 td 6 xp 1 xd 2 s 2 fck 3);@a=(0,0);$^=lc,$a[$^eq$_]+=$a{$^}for/fck|s|../gi;$,=$".(To,TO,to)[$a[1]-$a[0]<=>0].$";say sort{$b-$a}@a'
0 To 0
28 TO 24
3 TO 0
3 to 0
20 TO 0
29 To 29
```
Edit: Forgot to support `to`, `To` and `TO`.
[Answer]
# Lua, ~~231~~ 200 Bytes
It was a lot of fun, even if I don't really know the rules of american football (We have Rugby here :)). I had to test a lot of things to make it as short as possible, I don't think there's a lot of things to improve, maybe there isn't.
**Edit: I'm a total retard. The first solution I've worked on revolved around using array expansion, then I changed it and the array containing the scores for both the lowercase and the uppercase team wasn't useful anymore. Removing it and using plain variable makes a beautiful -31 bytes.**
```
a={F=3,D=2,T=4,P=1,S=2}l,u=0,0 io.read():gsub(".",function(c)x=a[c:upper()]if a[c]then u=u+a[c]elseif x then l=l+x end end)w=l>u and" to "or l<u and" TO "or" To "print(math.max(l,u)..w..math.min(l,u))
```
### Ungolfed and explanations
```
a={F=3,D=2,T=4,P=1,S=2} -- define the table a with our scoring values
l,u=0,0 -- scores for the upper and lowercase teams
io.read():gsub(".",function(c) -- iterate over each character in the input
x=a[c:upper()] -- x contains the score for a lowercase character
if a[c] -- if a contains c (would evaluate to nil otherwise)
then
u=u+a[c] -- increment the score of the uppercase team
elseif x -- if x isn't nil
then -- same as "a contains c:upper()"
l=l+x -- increment the score of the lowercase team
end
end) -- exit the anonyme function
w=l>u and" to " -- nested ternary, lower > upper, we will use "to"
or l<u and" TO " -- lower < uppercase, use "TO"
or" To " -- else (draw), use "To"
print(math.max(l,u) -- output the concatenated string using
..b.w..math.min(l,u))-- min/max to put the winner in the first position
```
[Answer]
# Python, 167 bytes
The superb owl is long past, but since there isn't a Python solution yet:
```
def f(s):g=lambda s:0if s==""else{68:1,70:3,83:2,84:5,88:1}.get(ord(s[0]),0)+g(s[1:]);a=g(s);b=g(s.upper())-a;return"%i %s %i"%((a,("To","TO")[a>b],b),(b,"to",a))[a<b]
```
Works in Python 2 or 3.
] |
[Question]
[
## The Challenge
I present to you another spy vs. spy challenge pitting obfuscators versus crackers. In this case, however, the datum to be protected is not an input but an *output*.
The rules of the challenge are simple. Write a routine with the following specifications:
1. The routine may be written in any language but may not exceed 320 bytes.
2. The routine must accept three 32-bit signed integers as inputs. It can take the form of a function that accepts 3 arguments, a function that accepts a single 3-element array, or a complete program that reads 3 integers from any standard input.
3. The routine must output one signed 32-bit integer.
4. Over all possible inputs, the routine must output between 2 and 1000 (inclusive) unique values. The number of unique values a routine can output is called its *key*.
As an example, the C program
```
int foo( int i1, int i2, int i3 ) {
return 20 + (i1^i2^i3) %5;
}
```
has a key of 9, since it (hopefully) can only output the nine values `16`,`17`,`18`,`19`,`20`,`21`,`22`,`23`, and `24`.
Some additional limitations are as follows:
5. The routine must be fully deterministic and time-invariant, returning identical outputs for identical inputs. The routine should make no call to pseudorandom number generators.
6. The routine may not rely on "hidden variables" such as data in files, system variables, or esoteric language features. For example, routines should generally not refer to constants unless the constants are clearly defined in the code itself. Routines that rely on compiler quirks, outputs from mathematically undefined operations, arithmetic errors, etc. are also strongly discouraged. When in doubt, please ask.
7. You (the coder) must know precisely how many unique outputs the routine can produce, and should be able to provide at least one input sequence that produces each output. (Since there can potentially be hundreds of unique outputs, this set would only ever be requested in the event your key is contested.)
Since this problem bares far less resemblance to classical encryption than the previous one, I expect it will be accessible to a broader audience.
The more creative, the better.
## The Scoring
The shortest non-cracked submission(s) per byte count will be declared the winner(s).
If there's any confusion, please feel free to ask or comment.
## The Counter-Challenge
All readers, including those who have submitted their own routines, are encouraged to "crack" submissions. A submission is cracked when its key is posted in the associated comments section. If a submission persists for 72 hours without being modified or cracked, it is considered "safe" and any subsequent success in cracking it will be ignored for sake of the contest.
Only one cracking attempt per submission per reader is permitted. For example, if I submit to user X: "your key is 20" and I'm wrong, user X will disclaim my guess as incorrect and I will no longer be able to submit additional guesses for that submission.
Cracked submissions are eliminated from contention (provided they are not "safe"). They should not be edited. If a reader wishes to submit a new routine, (s)he should do so in a separate answer.
A cracker's score is the number of submissions (either compliant or not) (s)he cracks. For crackers with identical counts, the ranking is determined by total byte count across all cracked submissions (the higher, the better).
The cracker(s) with the highest score(s) will be declared the winners along with the developers of the winning routines.
*Please do not crack your own submission.*
Best of luck. :)
# Leaderboard
**Last Updated Sept 2, 10:45 AM EST**
**Immovable Barriers (non-cracked submissions):**
1. [CJam, 105](https://codegolf.stackexchange.com/a/37146/31019) [Dennis]
**Unstoppable Forces (crackers):**
1. Dennis [[Java, 269](https://codegolf.stackexchange.com/a/37136/31019); [C, 58](https://codegolf.stackexchange.com/a/37149/31019); [Mathematica, 29](https://codegolf.stackexchange.com/a/37153/31019)]
2. Martin Büttner [[Java, 245](https://codegolf.stackexchange.com/a/37147/31019)]
[Answer]
# CJam, 105 bytes
```
1q~]4G#b2A#md"M-k^XM-WHM-n^GM-0%M-uwM-gM-^XeM-kM-^VO^Ph,M-^MM-^PM-qM-!M-8M-AM-OM-~tM-^FM-cM-h^AM-0M-0M-lM-@M-^[MF=M-^Z^SM-1M-KM-T2M-9M-UmSM-N
M-8M-^^M-n$4M-^M^SM-x M-OM-^@^?"256b@D#Y256#%2+md!A3#*)%)%
```
The above uses caret and M notation, since it contains unprintable character. After converting the byte stream into an integer (`256b`), the following code gets executed:
```
1q~]4G#b2A#md
12313030820310059479144347891900383683119627474072658988524821209446180284434934346766561958060381533656780340359503554566598728599799248566073353154035839
@D#Y256#%2+md!A3#*)%)%
```
You can try this version online in the [CJam interpreter](http://cjam.aditsu.net/).
### How it works
This submission uses number theory instead of obfuscation. The program will return 0 for almost all inputs. From the few inputs that result in a non-zero output, a secret modulus is derived that is applied to the 10 least significant bits of the third integer.
The most efficient way of solving this challenge (that I can think of) would be factorizing the 512 bit integer, which I hope won't be achievable in 72 hours.
```
" Prepend 1 to the numbers read from STDIN and convert the resulting array into an integer
(“N”) by considering them digits of a base 2**32 number. ";
1q~]4G#
" Compute “N / 1024” and “N % 1024”. ";
2A#md
" Push a carefully selected 512 bit semi-prime (“S”). ";
12313030820310059479144347891900383683119627474072658988524821209446180284434934346766561958060381533656780340359503554566598728599799248566073353154035839
" Compute P = (N / 1024) ** 13 % 2 ** 256 + 2. ";
@D#Y256#%2+
" Compute “S / P” and “S % P”. ";
md
" Compute “M = (S / P) % (1000 * !(S % P) + 1) + 1”.
“M” is the key if P is a divisor of S; otherwise, “M == 1”. ";
!A3#*)%)
" Compute the final output: “N % 1024 % M”. ";
%
```
### Example run
```
$ base64 -d > outputs.cjam <<< MXF+XTRHI2IyQSNtZCLrGNdI7gewJfV355hl65ZPEGgsjZDxobjBz/50huPoAbCw7MCbTUY9mhOxy9QyudVtU84KuJ7uJDSNE/ggz4B/IjI1NmJARCNZMjU2IyUyK21kIUEzIyopJSkl
$ wc -c outputs.cjam
105 outputs.cjam
$ LANG=en_US cjam outputs.cjam < outputs.secret; echo
1
$ LANG=en_US cjam outputs.cjam <<< '1 2 3'; echo
0
```
[Answer]
# Java - 269
Thanks for everyone's patience, this should now be fixed.
shortened:
```
int a(int a,int b,int c){double d=180-360.0/(int)(Math.abs(Math.sin(a*60))*50+2),e=180-360.0/(int)(Math.abs(Math.cos(b*60))*50+2),f=180-360.0/(int)(Math.atan2(c*60, a*60)*51+2);if(Math.abs(d+e+f-360)<.1)return Integer.valueOf((int)d+""+(int)e+""+(int)f);else return 1;}
```
Not shortened:
```
int a(int a, int b, int c) {
double d = 180 - 360.0 / (int) (Math.abs(Math.sin(a * 60)) * 50 + 2);
double e = 180 - 360.0 / (int) (Math.abs(Math.cos(b * 60)) * 50 + 2);
double f = 180 - 360.0 / (int) (Math.atan2(c * 60, a * 60) * 51 + 2);
if (Math.abs(d + e + f - 360) < .1)
return Integer.valueOf((int) d + "" + (int) e + "" + (int) f);
else
return 1;
}
```
[Answer]
## A Sampler
Not an official entry of course, and the character count is too high, but I figure if anyone wants a mind-numbing challenge, they can try to determine how many unique outputs the following function produces (given three inputs as described in the OP):
```
function z(y,_,$){M=[];N=[];O=[];C=1792814437;P=72;r=t=0;(f=function(a,k,L){if(k<a.length){for(L=a[k],a[k]=0;a[k]<L;a[k]++)f(a,k+1)}else
if(!t){f([P-1,P-1],0,++t);N=M;while(t<2*P){s=!(t&1);f([P,P,P,P],0,++t);r=r||(s?0:t);t&1&&(N=O);O=[]}}else
((t<2)&&(((d=P*a[0]+(P+1)*a[1]+P)<(P<<6))&&(M[d]=(((y^~_)>>a[0])+((_^~$)>>(a[0]-32)))&1),((a[1]<P-a[0])&&
(M[a[1]+(P+1)*a[0]]=(($^C)>>a[0]+16-a[1])&1))||1))||((t&1)&&((O[P*a[2]+a[3]]|=M[a[1]+P*a[2]]&N[P*a[0]+a[3]]&&
!(a[0]-a[1]))||1))||(s|=N[(a[0]+1)*a[1]+a[3]]);})([],0,0);return r;}
```
In fact, I'm so confident that it's uncrackable, I'll award anyone who cracks it the "Supreme Unstoppable Force of Nature Award".
Because really, they deserve it.
[Answer]
## C, 58 bytes (Cracked)
A simple one:
```
f(a,b,c){return(long long)a*b*c-0x1d21344f8479d61dLL?0:a;}
```
[Answer]
# Java - 245
### Cracked by Martin Büttner
```
int a(int[]_$){return $($($_(_$[0],0)))+$_(_$[1],1)*11+$($($_(_$[1+1],0)))*(1+1);}int $_(int $,int $_){int OO=0,o=1,O=1;for($=$<0?-$:$;++O*O<=$;OO+=$%O<1?O:0,o+=$%O<1?1:0,$/=$%O<1?O--:1);return $_>0?o:OO+$;}int $(int $){return(int)Math.sqrt($);}
```
Feed the input as an int array: `a(new int[]{1,2,3})`. I'm not expecting it to go 72 hours, but have fun with it.
Here it is with line breaks, to make it a bit more readable:
```
int a(int[]_$){return $($($_(_$[0],0)))+$_(_$[1],
1)*11+$($($_(_$[1+1],0)))*(1+1);}int $_(int $,int
$_){int OO=0,o=1,O=1;for($=$<0?-$:$;++O*O<=$;OO+=
$%O<1?O:0,o+=$%O<1?1:0,$/=$%O<1?O--:1);return $_>
0?o:OO+$;}int $(int $){return(int)Math.sqrt($);}
```
[Answer]
## Mathematica, 29 bytes, Key: 715, Cracked by Dennis
This is just a fixed version of my initial answer, which didn't work for non-positive inputs.
```
f=Plus@@Mod[NextPrime@#,240]&
```
Takes a list of integers like
```
f[{1,2,3}]
```
[Answer]
207 characters, in C/C++, not yet obfuscated:
```
int x(int a, int b, int c) {
int d, e, f;
for (int i=0; i!=1<<31; ++i) {
d=10*(b-a);
e=a*(28-c)-b;
f=a*b-2.7*c;
a += d;
b += e;
c += f;
}
return ((a%5+5)*10+(b%5+5))*10+c%5+5;
}
```
] |
[Question]
[
Your task is to write a file which contains a line with many [pep8 violations](http://pep8.readthedocs.org/en/latest/intro.html#error-codes).
**The rules:**
* We use pep8 version 1.5.7 and the default settings.
* Calling pep8 with other command line options or using a custom rc file is not allowed.
* Maximum line length 120 characters. You can violate E501, sure, but the line which your score is calculated on has to be <= 120 characters.
* Your module can have other lines before or after, but only one line contributes to your score.
* Your file can contain SyntaxErrors or any kind of garbage, it needn't import or run.
**Example of scoring:**
The following module `thing.py` has a score of 2, because it contains a line (line 1) with 2 pep8 violations.
```
spam='potato'
```
**To check a score:**
```
~$ mktmpenv
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pip install pep8==1.5.7
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ echo -n "spam='potato'" > thing.py
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pep8 thing.py
thing.py:1:5: E225 missing whitespace around operator
thing.py:1:14: W292 no newline at end of file
```
[Answer]
# 241
if you want the most error, just go crazy with semicolon
```
$ cat test.py
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
$ cat test.py | wc -m
120
$ pep8 test.py | wc -l
241
```
most of the error are:
```
test.py:1:119: E231 missing whitespace after ';'
test.py:1:119: E702 multiple statements on one line (semicolon)
```
with those error at the end:
```
test.py:1:120: E703 statement ends with a semicolon
test.py:1:121: W292 no newline at end of file
```
[Answer]
# 123
Yes, more violations than characters!
```
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | cat
( = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | wc -m
120
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | pep8 - | wc -l
123
```
The trick is that an `=` after a `(` makes pep think you're doing a keyword in a function call (e.g. `foo(bar=12)`). In this context, doing `[TAB]=` triggers both
```
killpep.py:1:3: E223 tab before operator
killpep.py:1:3: E251 unexpected spaces around keyword / parameter equals
```
And doing `=[TAB]` triggers both
```
killpep.py:1:5: E224 tab after operator
killpep.py:1:5: E251 unexpected spaces around keyword / parameter equals
```
Gleefully enough, you can just chain these.
This gives a violation count of one per character. I need `(` to set it up, but not providing the `)` gives us:
```
killpep.py:2:1: E901 TokenError: EOF in multi-line statement
```
That's 120. No newline = 121. It managed to trigger the "line too long" error, so that's 122. Finally, using one character to start with a space (thanks [eric\_lagergren](https://codegolf.stackexchange.com/questions/34581/maximum-number-of-pep8-violations-in-a-single-line/34595#comment74154_34595)) gives 2 violations instead of 1:
```
killpep.py:1:2: E111 indentation is not a multiple of four
killpep.py:1:2: E113 unexpected indentation
```
Victory!
] |
[Question]
[
*This challenge was originally [posted on codidact](https://codegolf.codidact.com/posts/288535).*
---
You are a low-level censor working for the *Ministry of Media Accuracy*. Part of your job is to make sure that certain words don't appear in publications. Every morning you get a fresh stack of next week's newspapers and its your job to comb through them and fix any of the words that were mistakenly included. A naive censor might simply remove the entire word completely, but you know that if you remove part of the word that still prevents the word from appearing in print. So for you it is a point of pride to remove as little of the offending word as possible while still ensuring it does not appear in print.
## Task
Given non-empty strings \$X\$ and \$Y\$ output the longest substring of \$X\$ which does not contain \$Y\$ as a *contiguous* substring
This is code-golf so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
For each input output pair a *possible* correct output is given, your output should always be the same length, but it is not necessary to reproduce these outputs exactly.
```
chat, cat -> chat
escathe, cat -> esathe
homology, o -> hmlgy
ccatt, cat -> cctt
aababbabab, abab -> aaabbbab
ababab, abab -> abbab
aaaaaaaa, aaa -> aa
a, a ->
```
[Answer]
# [Python 3](https://www.python.org), 86 bytes
```
f=lambda s,t,i=0:s if t not in s else max([f(s[:i]+s[(i:=i+1):],t)for x in s],key=len)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFBTsQwDBTXXvmAb2m1QYIbipRvcIkilIaURKTJam2k7Vu47AX-BK8h2bSwCB9seWZsyeO3j_1CPqfT6f2Vppv7z4dJRjOPTwaQEw_yViCECQhSJggJEFxEB7M59mrqUYmgd6j6IGTY3Q1CcxqmfIDjWav5i1tkdGlo27-urskhPVqDDkGCUsx6Q4wDs2upreYdKOawYN5dkA7PQKN9nnPMz0slck1-jqVrpC0Tf9Za2tYaM5pxrKkSP7XAFd1E_wWX7BrrYCtM666rpyMH4pCrAb_Hig5K7A8hUd8ExbziVRGu3mwf-AY)
## Ungolfed and commented
```
def f(s, t):
if t not in s: # return s if it's valid (ie. doesn't contain t)
return s
return max([ # recurse on all substrings with 1 character removed
f(
s[:i] + s[i+1:], # s without the character at index i
t
)
for i in range(len(s))
], key=len) # find the longest valid substring
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes
```
ŒPwÐḟṪ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFklB3w5DhuJ/huaoiLCLDpy/igqxZIiwiIixbIltcImNoYXRcIiwgXCJjYXRcIl0sIFtcImVzY2F0aGVcIiwgXCJjYXRcIl0sIFtcImhvbW9sb2d5XCIsIFwib1wiXSwgW1wiY2NhdHRcIiwgXCJjYXRcIl0sIFtcImFhYmFiYmFiYWJcIiwgXCJhYmFiXCJdLCBbXCJhYmFiYWJcIiwgXCJhYmFiXCJdLCBbXCJhYWFhYWFhYVwiLCBcImFhYVwiXSwgW1wiYVwiLCBcImFcIl0iXV0=)
## Explanation
```
ŒPwÐḟṪ Main Link
ŒP Powerset (all subsequences) of the left argument
Ðḟ Filter where falsy:
w The sublist index of the right argument (0 if not found)
Ṫ Tail (Last Element) - powerset generates in increasing order of length
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ṗ'⁰c¬;ÞG
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4bmXJ+KBsGPCrDvDnkciLCIiLCJjaGF0LCBjYXRcbmVzY2F0aGUsIGNhdFxuaG9tb2xvZ3ksIG9cbmNjYXR0LCBjYXRcbmFhYmFiYmFiYWIsIGFiYWJcbmFiYWJhYiwgYWJhYlxuYWFhYWFhYWEsIGFhYSJd)
```
ÞG # Longest
ṗ # Subsequence of input
' ; # Which
¬ # Does not
c # Contain
⁰ # The other input
```
[Answer]
# Python3, 108 bytes
```
lambda x,y:max(f(x,y),key=len)
f=lambda x,y,r='':[r]*(y not in r)if''==x else f(x[1:],y,r)+f(x[1:],y,r+x[0])
```
[Try it online!](https://tio.run/##XZDBbsMgDIbP5SmsXAgLqzbtMkViL5Lm4KQkQSUQAdLC02dmnbZqHCz@359tzJbT4t3b@xaOWV0Oi@twRdhlblfc66mmm5A3nZXVTrBJ/QEyKM7bLvRPdQbnExgHQZiJc6V20DZqoPLute0LK5oH0ezdSy8Os24@JAiaTT6AKQ2qqhoXTBJGTPD8AUUwHUkt@tfUsUi2@NVbP2cJvrjLaufMRmIeyseUGOKAw1CChBJLAsksHsP/ibv7c2QB7zy97Bw3a1LNL46Llp12CTQ7gKINzpNxV7SWkp8Nl2AEO2GMmtabv/8QFGFsC8ZRg6RjirAV4MrF8QU)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
+%`(.),
,$'¶$`,$1
Ar`\1.* (.+)$
O^#$`
$.&
,| .+
1G`
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX1s1QUNPU4dLR0X90DaVBB0VQy7HooQYQz0tBQ09bU0VLv84ZZUELhU9NS6dGgU9bS4uQ6Cu/8kZiSU6CsmJJVypxUAyIxXCycjPzc/JT6/UUcjnSgYKQNUkJiYlJiWBCB0FEMmViMKBAiA3MREA "Retina 0.8.2 – Try It Online") Link includes test cases. Assumes that the strings don't contain commas or spaces. Explanation:
```
+%`(.),
,$'¶$`,$1
```
Generate all subsequences of the first input.
```
Ar`\1.* (.+)$
```
Delete those that contain the second input.
```
O^#$`
$.&
```
Sort the remainder in descending order of length.
```
,| .+
```
Delete the second input.
```
1G`
```
Keep only the longest subsequence.
[Answer]
# [Scala 3](https://www.scala-lang.org/), 141 bytes
Port of [@SuperStormer's Python answer](https://codegolf.stackexchange.com/a/263710/110802) in Scala.
---
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=ZVBLTsMwEBXbnmKIsrBVNypig4AiATsEKw6AHNdpjFw76kxRqyhH4ARssoE7cBQ4DU5qSgAv5nnmfWTPyxsqaeVx--7zR60I7qRxoDek3Rzhsqqgfl1TMTn5eJ7rAgqGp_e0Mm4hKF54xFltCnaImfKOQgYy4hzPtEVdsymsHRkLmFntFlTybCmr2swuQl6G6xz7BDYVho-HAzM-4oJ4E-Sbqy17-LY3ze5Rnwc38CQtkEa6lqgRZnBrkNgIwmGJKiUlAhIVoWu5iKQOP6dSD3iN_WCvKP3SW7_YdpzvSrm0odvzKvh-5Ssa5EuZyzzvSsftMYy76UD3X_NHEE-07yDhgeWjUAq_AsZQAAnwHM4nP-vgUPcZVdgmWccwSRFSgrQuegNvIPV9UjOKK23bHX4B)
```
def f(s:String,t:String):String={if(!s.contains(t))s;else{(0 until s.length).map{i=>f(s.substring(0,i)+s.substring(i+1),t)}.maxBy(_.length)}}
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=dVJLTsMwEJVY5hRDlIUt0qiIDUIUCdiWVQ-AnOAkRo5dOtOqVZWTsOkGDsVpsFMnBFAtxfN788nzvH9iIbS4Ohw-1lROrr_O3mz-KguCJ6EMyC1J84Jwv1zCPooAXmQJK9nYjZxbU0mkxTpHWilTMbyBRaelQL3KewVmLh_cUSWwc8wKa8g1QEacA3YRqVEGEACbwtqQ0oCZlqaimmeNcDOAgtldwMDJSTIc9GkKisMFjH3K2ZfcjclDpdYV3z7s2HPfrPO3kf_ctREayHV4FCjR_clcIbEOwuKiFhSnEBdBeJOnISgduVTLUVxi5xgQtW2sttXOx6y_6kY7a4gXLu9X_YJG9YXIRZ77y8cG6dzeO8L9x_wBhBPSjyL2NHBPQGlXwBg6xlKwHG4nP3Tw8GRLxyxpwzBOEBKCZH_qcTzvLSS2K99GbXTcvLCA_SJ-Aw)
```
object Main extends App {
def removeLongestSubstring(s: String, t: String): String = {
if (!s.contains(t)) s
else {
(0 until s.length).map { i =>
removeLongestSubstring(s.substring(0, i) + s.substring(i + 1), t)
}.maxBy(_.length)
}
}
val testCases = List(
("chat", "cat", "chat"),
("escathe", "cat", "esathe"),
("homology", "o", "hmlgy"),
("ccatt", "cat", "cctt"),
("aababbabab", "abab", "aaabbbab"),
("ababab", "abab", "abbab"),
("aaaaaaaa", "aaa", "aa")
)
for ((s, t, o) <- testCases) {
println(s"$s $t ${removeLongestSubstring(s, t)} $o")
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
æéR.ΔIå≠
```
[Try it online](https://tio.run/##yy9OTMpM/f//8LLDK4P0zk3xPLz0UeeC//9Ti5MTSzJSuYAkAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/Dyw6vDNI7NyXi8NJHnQv@1@r8j45WSs5ILFHSUUoGkrE60UqpxUBWRiqSSEZ@bn5OfnolUCgfLJAMlEHWkpiYlJiUBCKAgmAKLIopAgUgMSAJFgKxlWJjAQ).
**Explanation:**
```
æ # Get the powerset of the first (implicit) input-string
é # Sort it by length (shortest to longest)
R # Reverse it, so it's sorted from longest to shortest
.Δ # Find the first string that's truthy for:
≠ # Check that the current powerset-string does NOT
å # contain
I # the second input-string
# (after which the found result is output implicitly)
```
The `R.Δ...` could alternatively be `ʒ...}θ` (filter, and keep last item after the filter) for the same byte-count.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
⊟⌈EΦEX²LθΦθ﹪÷ιX²μ²¬№ιη⟦Lιι
```
[Try it online!](https://tio.run/##PY0xC8IwEIV3f0XGC8Slq6MiCFa6i8OlDeYgybUhqf77mJTi8t3j3bt3o8U4MrpShkghwcAz9Pgln32dM1zJJRM3OfCnqk6JuwnvZGGRUol9vyjR85Qdwy2kC600GSAl/ie@ZTvZ@OAEZ871Vw3YzXrujVQ1vap1KgVRo9YNh4ZyXN0P "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal integer `2`
X Raised to power
θ First input
L Length
E Map over implicit range
θ First input
Φ Filtered where
ι Outer value
÷ Integer divided by
² Literal integer `2`
X Raised to power
μ Inner index
﹪ ² Is odd
Φ Filter over subsequences where
ι Current subsequence
¬№ Does not include
η Second input
E Map over remaining subsequences
ι Current subsequence
L Length
ι Current subsequence
⟦ Make into list
⌈ Get a subsequence with the longest length
⊟ Get the subsequence
Implicitly print
```
[Answer]
# JavaScript (ES12), 76 bytes
Expects `(Y)(X)`.
```
y=>o=g=([c,...x],s='')=>c?g(x,s+c)|g(x,s)||o:o=s.match(y)||o?.[s.length]?o:s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZFBbsIwEEXVLadAbLDVYLYVkskFuAFiMTGOvUgySHalWMpN2ERVORScBk9MCirgzZ_5evM9so-_De51_1PK07cvF1_nTZBrlEayrcqEEO0uc3I-53KtcsPazH0q3g0F7zpcoXSiBq8sC9TnYutEpRvj7S7HlUuZl49WYeOw0qJCw0o2U-BnPIol5dPxLJdTsiavae1iYfXfQKS1I-c_j0RbrDH24Z4feVtXJryJV1Eft6FllH9aBgooCAcqitTxgYZokfN24k7f8uElDpDy0xn54YIndiAfn3Bkma4PPvD0AX2f9Ao)
### Commented
```
y => // y = forbidden word
o = // o = output, initially not a string
g = ( // g is a recursive function taking:
[ c, // c = next character from the input text
...x ], // x[] = remaining characters
s = '' // s = censored text
) => //
c ? // if c is defined:
g(x, s + c) | // do a 1st recursive call with c added to s
g(x, s) || // do a 2nd recursive call with s unchanged
o // eventually return o
: // else:
o = // update o:
s.match(y) || // if s contains y
o?.[s.length] ? // or o is a string longer than s:
o // leave o unchanged
: // else:
s // update o to s
```
[Answer]
# [Haskell](https://www.haskell.org), 161 bytes
```
c=concatMap
l=length
[]%y=y/=[]
x%y=(l x<l y||or(zipWith(/=)x y))&&tail x%y
r[]=[]
r(x:y)=y:map(x:)(r y)
x#0=[x]
x#n=c r$x#(n-1)
x!y=head$c(filter(%y).(x#))[0..]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVLNbtswDMauego2fyABJ21vQ1Ht2FtvBXYwjELRlNqYYgWyAkiF32SX7jDsmdY36FuMih2vxXygyO8jKfKzfvyuVffdWPvy8usYduvPf35qqV2rVbhXB2GlNe1TqEVZLZNMl7KsRGQPLcRbC6nvncfn5vC1CTVeSoqQiFaroBpOWCbhyyqXeIw3iWS62asDu4Se80ScX8kycsN5KzX4RZxju75m_CLJ2qhvC427xgbjcZlog3FOVF5tNtUw6OunN56Tb2rhEcoKJDz4oxFnjJFHxu6U7f6BPB4wOOzE0ZfJT7BagbIW8Njqo_cJUEoiyMvlMoK-h3MbHPYjSEIE0wWtOtNx31IA4EzXKswKmOnxyCEVJ8p0DNbmHWu6EzDytds7655SZlw29d5yNLKaaz501mHqrNRWbbfZZGY6Gc7olPV_xgd6_MbS4ZjIU5jNjCohdiDxgsQ-6yHh4Js2wAJK3GW1irOsQ0ggJ6FdFrp1AXBSc8zhlwM9YCxS4Qhu1zBJO_7x8xP9Cw)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
y=>g=([c,...x],s=o='')=>c?g(x,s+c)|g(x,s)||o:o=s[s.match(y)||o.length]?s:o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZE9jsIwEIVFyykQDbYIpl0hGfq9AqKYGMcukgySjRRLuck20Wo5FJwGT0wWxI-bN_P0zfPI_vmrca-730Kejr5YfJ2_g1wbybYqE0I0u8xJlLMZl2u1MazJ3Fzxti942-IKpds6UYFXlgVyRKlr4-1u41aYEi-jRmHtsNSiRMMKNlXgpzyKJeWT4SyXE7LG72ntYmH1_0CktSPnmUeiLVYY-3DPj7ytShM-xKuoj9vQMsq_LAM55IQDFXnqeE9DtMj5OHGnb_nwFgdI-ekMfH_BC9uTj084sExXBx94-oCuS3oF)
Optimized from Arnauld's
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
S=>g=(T,...U)=>T.join``.match(S)?g(...U,...T.map((_,i)=>T.filter(_=>i--))):T
```
[Try it online!](https://tio.run/##dZDNbsIwEITvfQqU066UmDvI6Y0XID1VFWyMExslcUSsCj99WKekIH72MvLst6ORj/RLgzrZ3medO@hxI8etzGsJRSqE@EKZF@LobLffi5a8MrDFzxriKu4LNnuAXWonsLKN1yfYydxmGSKuinFdSTingdcbOCN881H4wWvk@kO5bnCNFo2roYJEkU/SRBkWxMU8y@UiWq9hPbAa/c8zrIfoPOKOYeNax89wS2fctE0d3jRhua8Smyj/1IRKKpmmqOX0iCcME1vReXdwg6/p9JImmtL/Zsan@Cc0gvd/N6Og294HHC8 "JavaScript (Node.js) – Try It Online")
Same length as Arnauld's but worse at almost all other ways
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `t`, 7 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ʠþlæ¹Ƈ}
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDQSVBMCVDMyVCRWwlQzMlQTYlQzIlQjklQzYlODclN0QmZm9vdGVyPSZpbnB1dD1lc2NhdGhlJTBBY2F0JmZsYWdzPXQ=)
Port of Kevin Cruijssen's 05AB1E answer.
#### Explanation
```
ʠþlæ¹Ƈ} # Implicit input
ʠ # Powerset of the first input
þl # Sort it by length
æ } # Remove items which:
¹Ƈ # Contain the second input
# Implicit output of last item
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
ef!}zTy
```
[Try it online!](https://tio.run/##K6gsyfj/PzVNsbYqpPL/f6XU4uTEkoxUJS4gBQA "Pyth – Try It Online")
### Explanation
```
ef!}zTyQ # implicitly add Q
# implicitly assign Q=eval(input()); z=input()
yQ # powerset of Q
f # filter on lambda T
!}zT # z not in T
e # last element (longest)
```
] |
[Question]
[
Traditionally presents are kept secret in boxes wrapped in paper. Since the ice caps are melting Santa Claus has begun to investigate some ways they might make the whole gift wrapping operation a little more eco-friendly. The first thing they've decided to do is to put all presents in perfectly cubic boxes. This makes things more efficient to process and cuts down on waste. The second thing they are doing is to reuse some of the scrap paper to wrap boxes as opposed to tossing it.
In this challenge you will help Santa make a machine which will identify which pieces of scrap can still be used to wrap gifts. Because of the industrial wrapper cutting machine used scraps will always be connected faces of a square tiling. The squares will also always be the exact size of the faces that make up the boxes Santa uses.
For example you might get the following scrap:
```
#
####
#
```
This scrap can fold around the cube perfectly with no overlap and no empty space. Some scraps might overlap, for example:
```
#
#######
#
```
Can wrap around the cube perfectly, but since there are more than 6 squares there must be overlap. This is fine and this scrap can be used to wrap.
Some scraps can't wrap a cube without leaving some gaps. For example
```
######
```
This has 6 squares, but there's no way to fold them which covers all sides of a cube. So this should be sent to the recycling plant.
Some scraps *can* wrap the cube but require fancy folding techniques. For example:
```
####
####
####
```
This can be folded to wrap around a cube, but it requires folds that aren't along the edges of the squares. The wrapping machine just isn't that fancy, so this should be sent to the recycling plant.
The following can be folded with the only permanent creases being along the edges of the squares:
```
####
# #
# #
####
```
However it requires making multiple folds at once and bending the paper to make the geometry fit. The machine can't do anything that fancy, it makes one fold at a time along one straight axis, folding every edge that meets that axis.
## Task
For this challenge, take a scrap as input in any reasonable method. Output one of two consistent distinct values. One value should only be output if the scrap can be used as gift wrapping, the other should only be output if the scrap should be sent to the recycling plant.
Some folds are almost possible, but require paper to pass through itself to complete the fold. If the a shape *requires* this to fold you can output either value. That is you can choose to assume that paper can pass through itself or not, whichever is more convenient for you.
In order to be eco-friendly Santa is asking you to minimize the size of your source code as measured in bytes. (You've tried to explain that that's not how things work.) So this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and the goal is to minimize the size of your source code as measured in bytes.
## Test cases
### Truthy
```
#
####
#
```
```
#
#
#
####
```
```
##
####
#
#
#
```
```
###
# #
# #
####
#
```
### Falsy
```
######
```
```
#
######
```
```
#
#
######
```
```
##
####
#
```
```
###
# #
###
```
```
####
# #
# #
####
```
```
######
######
######
######
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~209~~ 206 bytes
```
WS⊞υι≔ΣEυ⁺⌕Aι#×I1jκθ≔”)⊟⬤e~±”η≔⪪⁺⮌ηη⁴η≔ΣEηE⁴⁺✂ιλ⁴¦¹…ιλη≔⟦⟧υFθ«≔ΦE⁴XI1jκ№θ⁺ικζ¿⁼¹Lζ⊞υ⟦ι⊟ζ⦃ι0⦄⌊η⟧»Fυ«≔⊟ιδ≔⊟ιε≔Σιζ¿⁼LεLθP⬤⁶№εIκ¿№θζF⁼§δ¹∨§εζ§δ¹⊞υ⟦ζ⊟ι⁺ε⦃ζ§δ¹⦄⁺Φδμ§δ⁰⟧F⁻θEελ«≔ΦE⁴XI1jλ№θ⁺κλζ¿⁼¹LζFη⊞υ⟦κΣζ⁺ε⦃κ§λ⁰⦄λ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVM9b9swEB06Rb_ioCwkwABW4hRFOhlGAwRo0KDuZnhQZdpkTOuLZNLK0C_pkiFFsvX_9Nf0SCqOlBZFOEji8e7xvXenH4-ZSOusSNXd3U9rVkfvfr-5vxVScSAXeWnNzNQyXxNK4cpqQSwDSd9HE63lOiczuyWXaemiV8pqci7z5UQpIhnEhzFl8EVuuSbTVBsSJ9cusqG4GFTPIPEoOR0nx-OT49HJacxA9PBLJQ3x0J_5Da81J4K6DAZjOszsmAgG7jXuCM2UzLijo7CCQYJF0--Z4lNRlD5MA50e0nzBwOJ2VdRAKgq76KA7OZfK8Jo84Re3uHkhDeELmxtSdffLIJhBg4gHcgXkQ2VTpUnC4CPP10aQhva8nUsHXGKQwU6eQTyKW1Qkc7lFgYIuEKYN1GyfmquRWLN017yI8V7M2ST_QafjwumeVuVoXVplZIkDYIhr69sneRw_nHDfTETiSnNwcHv1qAo8ze6CibnIl_wbWYYmfKr3Ee6SGQwSBpY0wRJH23uKBbvmbFjQ0v0E-h5hcDsEHVFvXqDqmaGrWFCFgeFhFpylr223-rvdm4DS-fuffnsCoicSK11vmr7IzbNI5QQ4kcqLaKP2Xn_NdPfLPszjoxsVL34dAkAUHriicPoH "Charcoal – Attempt This Online") Link is to verbose version of code. Outputs `-` for wrapping, nothing for recycling. Port of @Ajax1234's Python answer, except using complex numbers as coordinates as Charcoal has no tuples and lists can't be used as dict keys. No explanation as I don't actually understand how it works. Edit: Saved 3 bytes because the bleeding edge version of Charcoal on ATO will now `Cast` strings containing complex constants thus avoiding the need to `PythonEvaluate`.
Previous 138 byte version only handled 90° folds:
```
WS⊞υιυ≔⌊Φυ№ι#θ≔⟦⁺E⁶ι⟦⌕υθ⌕θ#⟧⟧η≔EυEι⟦⟧θ≔¹ζFη«J⊟ι⊟ι≔§θⅉ§εⅈ«§≔εⅈιF⌕AKV#«M✳⊗⁻¹κ⊞η⁺E§⪪”)⊟Z➙.κ⊗φαμ”⁶κ§ιIλ⟦ⅉⅈ⟧M✳⊗⁻³κ»»¿¬⁼§εⅈι≔⁰ζ»⎚∧ζ¬Φ⁶⬤θ⬤λ⌕νι
```
[Try it online!](https://tio.run/##fVLLTsMwEDwnX2G1l7VkqqRpuXCqCkggFUUCIVDVQ2gNsXDtJrEBgfj2sOuk5XEgsuLHzsyux7sui3ptC922r6XSksGF2Xl37WplnoBzlvumBC@Y4idxjocOPK5mTaOeDCyUUVu/hXOlnawJNrceIUqwwXDAORes@kYvc@0bWBQ7OCY9wZbnymyIVeEmrKuOuFoJVv5IgxRE0YTKy9Uf3VSwd9w92ppBydlHHF367e7GQm6RgNhuRkjUM2buwmzkG6W7B1KTFFSPDK6sO0SlYHcY5UGyp/6OdbZEUUhNF5hpDbmUz7fWXEm/LYwhUPAiiEQL@yLhVNVy7ZQ1cGr9g5YbMhKtwYs8Uz6SjILxJRa/N22f@nqnlYNBOh1nyWScTpNJNknG2TTN0mQ6GQ8EO@YkJNiegabNi8aBDi@yvKeasPpVn@nfmrIfNX3GNKRuJNt7dVb5Qjd/LSNf8Ma920n3Pp/xXMuihkMjzfDB3wUjmb6BsC/IwaqbdN8UppMLVbTtkL54OBqNDv9w0h696C8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for wrapping, nothing for recycling. Explanation:
```
WS⊞υιυ
```
Input the scrap and also print it to the canvas so that it can be peeked later.
```
≔⌊Φυ№ι#θ≔⟦⁺E⁶ι⟦⌕υθ⌕θ#⟧⟧η
```
Find the coordinates of a `#` and place a die at that spot.
```
≔EυEι⟦⟧θ
```
Start tracking dice placed at each position.
```
≔¹ζ
```
Assume the scrap does not need recycling.
```
Fη«
```
Loop over each die as it is placed.
```
J⊟ι⊟ι
```
Jump to its position.
```
≔§θⅉε
```
Get the row of the tracking matrix for convenience.
```
¿¬§εⅈ«
```
If we haven't seen this spot yet, then:
```
§≔εⅈι
```
Place the die at this spot.
```
F⌕AKV#«
```
Loop over potential adjacent spots.
```
M✳⊗⁻¹κ
```
Move to that position.
```
⊞η⁺E§⪪”)⊟Z➙.κ⊗φαμ”⁶κ§ιIλ⟦ⅉⅈ⟧
```
Calculate the die obtained by rolling the current die in this direction and push it to the list of placed dice.
```
M✳⊗⁻³κ
```
Move back to the original position.
```
»»¿¬⁼§εⅈι
```
But if there was already a different die placed here, then...
```
≔⁰ζ
```
... mark the scrap as for recycling.
```
»⎚∧ζ¬Φ⁶⬤θ⬤λ⌕νι
```
Check that each side of the die touched the scrap.
[Answer]
# Rust + NAlgebra + arrayvec, 1019 bytes
Needless to say I'm not winning this one. There probably is *way way* more efficient way to do this.
```
use nalgebra::*;use arrayvec::*;fn g(a:[[bool; 9];9],b:&mut[Vec<(isize,isize)>;27],c:(isize, isize),d:Quaternion<f32>,)->bool{let m=Matrix4::from(UnitQuaternion::new_normalize(d))*Vector4::new(0.,0.,1.,0.);let n=(((1.+m.x).round()as usize)*9+((1.+m.y).round()as usize)*3+(1.+m.z).round()as usize);c.0<0||c.1<0||c.0>8||c.1>8||!a[c.0 as usize][c.1 as usize]||b[n].contains(&c)||(b.iter().all(|j|!j.contains(&c))&&{b[n].push(c);g(a,b,(c.0-1,c.1),d*Quaternion::new((0.5).sqrt(),0.,(0.5).sqrt(),0.,))&&g(a,b,(c.0+1,c.1),d*Quaternion::new((0.5).sqrt(),0.,-(0.5).sqrt(),0.))&&g(a,b,(c.0,c.1+1),d*Quaternion::new((0.5).sqrt(),(0.5).sqrt(),0.,0.))&& g(a,b,(c.0,c.1-1),d*Quaternion::new((0.5).sqrt(),-(0.5).sqrt(),0.,0.))})}let f=|a:[[bool; 9]; 9]|{let mut c = (0..27).map(|_|Vec::new()).collect::<ArrayVec::<_,27>>().into_inner().unwrap();let f=(0..9).find_map(|j|{a[j].iter().position(|&m| m).and_then(|k|Some((j as isize, k as isize)))}).unwrap();g(a,&mut c,f,Quaternion::identity())&&c.iter().filter(|i|i.len()>0).count()>5};
```
[Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d22f181f7b2f0569eb4ab49ffe7735e2)
## Explained
Basically, I have a 3x3x3 array that has the coordinates of each normal. If all 6 normals are represented we return true.
To keep track of the rotation of the current face we use quaternions. These are convenient since we can cover the same face from different angles.
```
use nalgebra::*; // 0.31.4
use arrayvec::*; // 0.7.2
// this function recurses on the sides of a square, and adds it to the collection. Returns false if it's impossible to make a square
fn g(a: [[bool; 9]; 9],b: &mut [Vec<(isize,isize)>;27],c: (isize, isize),
d: Quaternion<f32>,
) -> bool {
// The normal vector of this face
let m = Matrix4::from(UnitQuaternion::new_normalize(d)) * Vector4::new(0., 0., 1., 0.);
// The index of this face in the map of all normals
let n =(((1.+m.x).round()as usize)*9+((1.+m.y).round()as usize)*3+(1.+m.z).round()as usize);
// If we are out of bounds, just return True
c.0 < 0
|| c.1 < 0
|| c.0 > 8
|| c.1 > 8
// If this face is not actually present in the wrapping paper, return True
|| !a[c.0 as usize][c.1 as usize]
// If we already checked this face, return true
|| b[n].contains(&c)
// If this face already has a different normal, return false. This is the "fancy wrapping" variant
|| (b.iter().all(|j|!j.contains(&c)) && {
// Set this normal to our coordinates
b[n].push(c);
// Recurse in all 4 directions, using a quaternion to represent our rotation.
g(a, b, (c.0 - 1, c.1), d * Quaternion::new( (0.5).sqrt(), 0., (0.5).sqrt(), 0.,))
&& g(a, b, (c.0 + 1, c.1), d * Quaternion::new((0.5).sqrt(), 0., -(0.5).sqrt(), 0.))
&& g(a, b, (c.0, c.1 + 1), d * Quaternion::new((0.5).sqrt(), (0.5).sqrt(), 0., 0.))
&& g(a, b, (c.0, c.1 - 1), d * Quaternion::new((0.5).sqrt(), -(0.5).sqrt(), 0.,0.))
})
};
// f is the main function
let f = |a: [[bool; 9]; 9]| {
// Create a map of empty vectors
let mut c = (0..27).map(|_|Vec::new()).collect::<ArrayVec::<_,27>>().into_inner().unwrap();
// find the starting point, the first cell that's true.
let f = (0..9)
.find_map(|j| {
a[j].iter()
.position(|&m| m)
.and_then(|k| Some((j as isize, k as isize)))
})
.unwrap();
// Execute g on this cell
g(a, &mut c, f, Quaternion::identity())
// check if we have at least 6 faces
&& c.iter().filter(|i|i.len()>0)
.count()
> 5
};
```
Edit: This assumes all folds are 90 degrees inwards, so won't pass the new test cases. This approach fundamentally can't handle 180 degree folds.
[Answer]
# Python3, 636 bytes:
```
E=enumerate
g=lambda e,x,y:[(x,y,X,Y)for X,Y in[(1,0),(-1,0),(0,1),(0,-1)]if(n:=(x+X,y+Y))in e]
def f(b):
e,C=[(x,y)for x,r in E(b)for y,t in E(r)if'#'==t],['0231','0435','2415']
C+=[i[::-1]for i in C]
C=[a[i:]+a[:i]for a in C for i,_ in E(a)]
q=[(*t[0],{(x,y):k[0]},1,k)for k in C for x,y in e if len(t:=g(e,x,y))==1]
while q:
x,y,X,Y,m,I,p=q.pop(0)
if len(m)==len(e):
if{*m.values()}=={*'012345'}:return 1
continue
if(n:=(x+X,y+Y))in e:
if n not in m or m[n]==p[I%4]:q+=[(*n,X,Y,{**m,n:p[I%4]},I+1,p)]
else:
for x,y in e:
if(x,y)not in m and len(t:=g(e,x,y))==1:q+=[(*t[0],{**m,(x,y):k[0]},1,k)for k in C]
```
[Try it online!](https://tio.run/##dVNNb@IwED0vv2JEtIodDIohtDSST6gHLnvppZU3qsLitBaJE0LYBSF@O2s7H9tuQw7j@L2ZN29GSXGq3nM1WxTl9frIhDpkoowrMXhjaZytNzEIciSnkCMdyTN5wUlegj5BKo4o8TFB4/rwCbVxTHEkE6RCho6jZ3IavWAsFYhosBEJJGiNw4FWXTKrafWOpNR68Kg5cz2Rqr6WWCau4zJWRYS7/nRGXeL6wWyuj2lA5240gOWIccnDcEwjUytN5dLgjMdchtEo5qG0VGwpsFnkte4QY52601a8ivsROVtL4Va/XwglW2tn@69Os@YiQCaQCoWqkL0huyGMGaNa68@7TAXs9IjQbIxkZEUKtpsUeYF8rImmONMl5hRmIQY9e9nkd5wexB7hC2Nnz/XpdBbM3UtYiupQKqAm8VeuKqkOwip93XMjBgpUbveYgXaecRUxVvDV9yAKdyMzsbLuzp6XERXWzIWsRpQUZikg0n2t9XFwC5i2ZuROP1abvnU0ferNmja3txtd98BgOBxqfQcGjn7qNwPtacM5uncTTILlpi3nQFcHTbAJM2BW11IONOG/DoFNcuxjgXlrx7SrhduOd5@pnoz7LuPrLAtWu9UWahs1/NDCBoc2dDT1u/V05s3ANUk/OWq9WBF7N5z5@ar8dZ3H5QY96U/uW/NNce7JCLp/J5FpJUr0I1eCwNNkX6SyQu5P5WL9VQyKUqoKJahT2mOMe1B6A/Zv4B/y3bHrBX5fVtBfPO@H7/rh@3540Q8/aPj6Fw)
Does not allow paper folding through itself.
] |
[Question]
[
The purpose of this challenge is to figure out whether all the dominoes will fall, given an input string representing a top view of the table.
## Input format
The program can take the input as a single string with newlines or a list of strings. Spaces denote, well, empty spaces, and the rest represent dominoes.
The start domino and the direction the dominoes start to fall will be denoted by one of `<`(left),`>` (right), `^` (up), `v`(down). There will be exactly one start domino in the input.
The other dominoes will be represented by one of the following four characters:
* `|` - falls right when pushed from the left, falls left when pushed from the right
* `-` - falls up when pushed from the bottom, falls down when pushed from above
* `/` - falls right when pushed from the top and vice versa, falls left when pushed from the bottom and vice versa
* `\` - falls left when pushed from the top and vice versa, falls right when pushed from the bottom and vice versa.
Basically, `|` and `-` keep the momentum going in the same direction, and the slashes (`/` and `\`) cause quarter-turns.
Dominoes may not fall twice. If a domino falls, you may consider that an empty space in the next iteration.
Pushing `-` from the left or right and pushing `|` from the top or bottom are undefined behavior.
## Output
A truthy/consistent value if all the dominoes will fall, and a consistent falsy value otherwise
Here's an example to make it a bit more clear (`o` represents a fallen domino for the sake of this example):
```
Step 1 - Starts at the 4th domino in the first row
\||<
-
- -
\||\
Step 2 - start domino has fallen
\||o
-
- -
\||\
Step 3 - Go left because start was '<'
\|oo
-
- -
\||\
Step 4 - keep going left
\ooo
-
- -
\||\
Step 5 - keep going left
\ooo
-
- -
\||\
Step 6 - keep going to left, will go down next
oooo
-
- -
\||\
Step 7 - change direction, go down because of '\'
oooo
o
- -
\||\
Step 8 - keep going down
oooo
o
o -
\||\
Step 9 - go down, will go left next because of '\'
oooo
o
o -
o||\
Oops! Can't go any further, so output should be a falsy value
```
## Rules
Just to clarify, there's no gravity or anything. The direction depends on the position of the domino (`/`, `\`, `|`, or `-`)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
## More test cases:
### Truthy
```
>
_________________________________________________________
\|||<
-
-
/|||
__________________________________________________________
\|/
/|/
-
-
\||\
^
```
### Falsy
```
\|/
- -
/|/| <-This last '|' doesn't fall, because the '/' before it has already fallen once
^
__________________________________________________________
|< | <- This last '|' doesn't fall, because the dominoes don't wrap around.
__________________________________________________________
>||\|| Because after the '\', it tries to go up
```
Undefined behavior:
```
>- Can't push '-' from the left
```
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~86~~ 69 bytes
```
WS⊞υι≔⪫υ¶θ≔v>^<ηPθ…θ⌈Eη⌕θιW№ηKK«↶⊗⁺³⌕ηKK≔ⅈι ≔§⪪\-//|\³⁻ⅈιη»≔⌈KAθ⎚→‹θ!
```
[Try it online!](https://tio.run/##VVDBasMwDD03X6H5JENKDr2tY1AyBh0NhPWygylkqVeLuU6a2FnHsm/P7DbdOp0eetLTeypV0ZRVoYfhQ5GWgEtTO7u2DZkdcg65axW6GIjPo0Xb0s7gU0UmtJgwjMdw@GNYd7@5YzEo38qctlR7GYthIj@h9LPUMlVVjYcYsuJIe7fHrKhRxfBIZhvaxEPNo9FPWjm/6PlcynfviMNXNMmpq@xKvll8qNyrllvMtWtxNqpcTQelyWjvBfk5yOTshgG7Yhd2abbyiOtak@eEmCZJL4SPM/NrGRl/YFTg54jfl9yXJOHoQmvk41tSLYsGf9PfPtNO2RhWsm1DUnbDgr9hgFCiT6ITSC4AYPofiL4XJ7CJhmmnfwA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if all the dominoes fall, nothing if some remain. Explanation:
```
WS⊞υι≔⪫υ¶θ
```
Input the table as an array of strings and join them together.
```
≔v>^<η
```
Make a string of rotations for the starting domino characters. The string starts with the character for a clockwise rotation, then the one for no rotation, then an anticlockwise rotation, then a u-turn.
```
Pθ…θ⌈Eη⌕θι
```
Print the table and then up until the (last) occurrence of one the starting domino characters.
```
W№ηKK«
```
While the current character is present in the table of rotations...
```
↶⊗⁺³⌕ηKK
```
... pivot according to the position of the character in the table of rotations (annoyingly I have to spend an extra byte adding 3 instead of subtracting 1 because Charcoal can't pivot by negative amounts)...
```
≔ⅈι ≔§⪪\-//|\³⁻ⅈιη
```
... and, temporarily saving the current X-coordinate, erase the current character, moving in the current direction, then choose the list of valid characters (again listed in the order rotate clockwise, don't rotate, rotate anticlockwise) depending on whether the current direction is vertical or horizontal (detected via the change in X-coordinate, since Charcoal has no builtin to read the current direction).
```
»≔⌈KAθ⎚→‹θ!
```
Check that only spaces are left.
[Answer]
# Java 10, ~~312~~ ~~304~~ ~~298~~ 295 bytes
```
m->{int i=m.length,j,x=0,y=0,d=0,t;for(;i-->0;)for(j=m[i].length;j-->0;d=t<0?d:t+(m[y=i][x=j]=0))t="<>^v".indexOf(m[i][j]);try{for(;;t=m[y+=d/2*t][x+=d<2?t:0],m[y][x]=0,d=t>99?d<2?d:d/0:t>91?(d+3)%6-d%3*2:t>46?d+2&3:t>44&d>1?d:d/0)t=d%2*2-1;}finally{for(var r:m)for(var c:r)i+=c/33;return i<0;}}
```
-9 bytes thanks to *@ceilingcat*.
Input as a character matrix.
[Try it online.](https://tio.run/##hVHBbqMwEL33KyyktHYIhEBVqRiDqp720PbQI2ElF5PWLJjIGbJBwLdnTdJK3VWkPVh6M/PmzZtxyffcKcWvY17x3Q49cal6qaDQG54X6Ll/a5qq4ArlOP/gOs3SrCZ03AEHmaNnpNixduKpA0lWu1Wh3uFjUS4OzFt05gnzgG4ajal0nNijZMIlq1OZfbJpeSoIBpGXiBBsXKcdk1l6YGXGPEKAWVH8c2@5Uoni8LLBU3NaZoSC7vqTNgWj2NlMLP05mE6DIj@B0MsWJm8S2ckLxPf3yVQRoVh6oQlXCRZ2QGZ3jpgFc9@kbu8SYfvXwQRvr0W8OpONCzHz576zouNGKl5V59F7rpEOa/KF81ATabN8GQRUF9BqhWTk0XE80m37Vpmjfd5u30iBanNu/Apaqvc046QHrIrf6OvSvRVbLjSPJnzQmneYjGbnfyhDhIb/s@JhWK@HC8Tx6i9D8O2b@9duB0XtNi24W2MRKoWtH2rbQogsQr9vf4E5zT9vhjUh9JLWSwtnMVu5Oa6JfbNWN5Ol8fgH)
**Explanation:**
```
m->{ // Method with char-matrix input & boolean return
int i=m.length, // Index-integer `i`, starting at the amount of rows
j, // Index-integer `j`, uninitialized
x=0,y=0, // Current `x,y`-coordinates, starting at 0,0
d=0, // Current direction, starting at 0
t; // Temp-integer
for(;i-->0;) // Loop `i` over all rows:
for(j=m[i].length;j-->0 // Inner loop `j` over each cell:
; // After every iteration:
d= // Set `d` to:
t<0? // If index `t` is -1 (thus NOT our start position):
d // Leave `d` as is
: // Else (we've found out start position):
t // Set `d` to `t`
+(m[y=i] // Set `y` to `i`
[x=j] // Set `x` to `j`
=0)) // Empty this cell containing the starting character
t="<>^v".indexOf(m[i][j])
// Set `t` to the index of the current character in
// "<>^v", or -1 if it's a different character
try{for(; // Loop indefinitely:
; // After every iteration:
t=m[y+=d/2*t] // Adjust the `y`-coordinate based on the direction
[x+=d<2?t:0],// Do the same for the `x`-coordinate
// And set `t` to the character of this new cell
m[y][x]=0, // Then empty this cell
d= // And change the direction to:
t>99? // If the current character is '|':
d<2? // If the direction is left/right:
d // Leave the direction as is
: // Else (it's up/down instead)
d/0 // Throw a division-by-zero error
:t>91? // Else-if the character is '\':
(d+3)%6-d%3*2
// Change the direction: 0→3; 1→2; 2→1; 3→0
:t>46? // Else-if the character is '/':
d+2&3 // Change the direction: 0→2; 1→3; 2→0; 3→1
:t>44 // Else-if the character is '-':
&d>1? // And the direction is up/down:
d // Leave the direction as is
: // Else (the character is '-', but the direction is
// left/right, OR the character is ' ' or an emptied
// cell):
d/0) // Throw a division-by-zero error
t=d%2*2-1;} // Set `t` depending on `d`: 0→-1; 1→1; 2→-1; 3→1
finally{ // After an error has occurred (either a manual
// division-by-zero, or ArrayIndexOutOfBoundsException):
for(var r:m) // Loop over all rows of the matrix:
for(var c:r) // Inner loop over all cells:
i+= // Increase `i` by:
c/33; // The codepoint of the cell integer-divided by 33
return i<0;}} // Return whether `i` is still -1
// (`i` is -1 when we enter the finally, and will
// remain that way if all cells are either a space or
// emptied)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 323 bytes
```
def f(m,e=enumerate,z='^v<>'):
for a,r in e(m):
for b,i in e(r):
if i in z:x,y=b,a;c,d=[(0,-1),(0,1),(-1,0),(1,0)][z.index(i)]
while 1:
try:
m[y][x]=' '
if all(i==' 'for i in sum(m,[])):return 1
x+=c;y+=d;n=m[y][x];assert (n!=' ')&(x>=0)&(y>=0)
except:return 0
if n=='/':c,d=d,c
if n=='\\':c,d=-d,-c
```
[Try it online!](https://tio.run/##bZHBbqMwEIbvforpZW2rpiTaG4lz7Atsb0BXDhjVEhBkmxYi3j3rMaHVqgXJM/o1843n9zD7t0v/@3ardQMN64SWuh87bZXX4irp6/vxRHlGoLlYUMKC6UGzDpUonYVZJRslMA1E4ZpNYpZnoQ6VqGXOdiLZcxECnsle7ELAs8yvT6av9cQMLwl8vJlWwx5R3s6R2OVzmU@lpEDvA1TbMiNRwBvEcW7swt3zkvPMaj/aHvZYPD3K6jA/yvrQyzvnoJzT1gPrH5DAf7HpJHchzBhCk54qPfgNsyNxZB/GpTTDXWpRfWlFsYpJLZIqeui188yrc6tFQA268rperQHl/ipr1QwS8taEMnv54NHFkOAWse3JDa3xjBY9RUfCd79KwzYAByk/4YTgSIfQWM3oiQp4saPmYhUspbRYluVIkvCnIQvC9xJMoFjSqEC6JQDJ/0lAFTF5/RGDhARwTrqQrehZte6zii5HWL6Jp4BdvmRSEjdWlXa4Gb74amwwdbUMs@gZLs/JYE0fTPuztjxQfKCtXwce0Gdl2tFqyBjl5PYP "Python 3 – Try It Online")
[Version showing each step](https://tio.run/##fVJNb@MgEL37V0wvC6i4SbS3JOTYP7B7s90VsScqkkMijLd25P@eZTBWt9tqQYLx88ybj8d19K8X@/1@b/AEJ36WqND2Z3Tao7wp9vJ7f2Bim8Hp4kBLB8YC8jMhETpKM0MuQmBOEIHbdpCjOkq9q2WjCr6W@UbIcNGZb@Q6XHRWxe3J2AYHbkSVwduraRE2C/s/Cb/MSCm5lkcBSgEf5ZBggKsz1vO5heI/JaQCeKhUiEoC2kYxJiILth1@5DMfHFKO@JFs9feKP7wbI8e5GKtiqBQDlmal25YbRQC1Fhvr@nOQoaiE2Dr0vbOwIefhUdW78VE1O6sSz053HToP3D4Qg/jGh4Nah2ukKwThUOPVLzTrLKa0Id2KbUmWRtbvWFnOYN7IvI7PwWPnudfHFkPLwxVrj00abmq1tLTTqHT3SzunR1BQtCaEusubiJIFgzqLVE/dtTUxlJHgYaXyTnwhiEouCbOMyuiINHpzdmASfroehZwBxxgrp2naZ3nYq2AF4LNLlLCcVrOYq8UAyD8agaqMxsuXNMSQA@VZTdni9KzDM1m82LSH6RN4CLTTO5xVWdfXNXbUGb2Cedhh0PPIyIozo@ZFlub9Yw55YCTaEk9PFNizNm3vELY8yHH/Aw)
Quite simply moves through the dominoes, recording the current coordinates and direction, and making sure we haven't gone of the board/stopped knocking over dominoes/removed all dominoes.
Less golfed version:
```
def main(chars):
for this_y, row in enumerate(chars):
for this_x, char in enumerate(row):
if char in '^v<>':
x, y = this_x, this_y
dx, dy = [(0, -1), (0, 1), (-1, 0), (1, 0)]['^v<>'.index(char)]
while True:
try:
chars[y][x] = ' '
if all(i == ' ' for i in sum(chars, [])):
return True
x += dx
y += dy
char = chars[y][x]
except IndexError:
return False
if char == ' ':
return False
if x < 0 or y < 0:
return False
elif char == '/':
dx, dy = dy, dx
elif char == '\\':
dx, dy = -dy, -dx
```
] |
[Question]
[
## Background
I feel that for a site named code-golf we have a shockingly little amount of golf being played. Let's fix that.
## Challenge
Determine whether the hole of a minigolf course can be reached after exactly a certain number of movements and whether it can be reached at all.
## How to play
Inputs are an integer "power level" and an ASCII art minigolf course. The ball starts on the `X` (capital) and the hole is an `O` (capital). The walls of the course are made of the characters `+` `|` `-` `\` and `/`. The characters `+` `|` and `-` rotate the direction of the ball 180 degrees and the characters `\` and `/` rotate the direction 90 degrees as you would expect. When a ball hits the wall it enters the wall for that turn and then leaves the next turn.
Launch the ball in each of the four cardinal directions from the starting `X`.
* If the ball enters the hole after **exactly** the power level moves, then output `truthy`.
* If the ball could make it to the hole given a different power level, then output `mediumy`.
* If the ball cannot enter the hole regardless of the power level, output `falsy`.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins.
* Assume only valid input will be given.
* All input strings will be rectangular. (All rows will be the same length)
* Assume that there is no way to escape the course and leave the edge of the string.
* No solution will require the ball to be in the same place facing the same direction twice.
* Standard loopholes disallowed.
* Only a string or a list of strings is acceptable for the course input.
* Output can be any three distinct values.
* The ball will never hit the characters `|` or `-` "end-on."
## Example
```
11
-----+
/ X |
| +----+
| |
|O|
+-+
```
This is true. If the ball starts heading east it will be on the wall after two movements.
```
-----+
/ X o<- ball right here. movements:2
| +----+
| |
|O|
+-+
```
It will then change directions until it hits the corner
```
-----+
o X | movements:8
| +----+
| |
|O|
+-+
```
Now it is heading south and will end in the hole after 11 moves. Note that 13 would also be true as the ball could bounce off of the bottom wall and into the hole. Other valid power levels for this course are 7 and 9.
## Test Cases
All answers validated using this java code: <https://github.com/Dragon-Hatcher/CodeGolfMiniGolf/tree/master/MinigolfCodeGolf/src>
```
power
course
output
11
-----+
/ X |
| +----+
| |
|O|
+-+
truthy
10
+---+
| X |
+---+
+-+
|O|
+-+
falsy
25
---------
/ X \
+++-------+ |
| | | |
|O| | |
| \-------/ |
\ /
---------
truthy
2
+-+
|X|
| |
| |
|O|
+-+
mediumy
34
+------+
|/ \|
| +--+ |
|X| | |
+---+ +--+ |
| O /|
+---+ +----+
+-+
true
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~146~~ 115 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
```
{(∨/+⍺⊃⊢)∨⌿↑{'O'=1↓⊃¨⊢∘(((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨1⌈¯2+'X O\/'⍳⊃)\(4×≢,⍵)⍴⊂⍵}¨({¯1+⊃⊃⍸'X'=⍵}⌽⍉)⍣2¨(⊢,⌽∘⊖¨)(⊂,⊂∘⍉)⍵,⍳≢⍵}
```
*-31 bytes (!) thanks to @Bubbler (combining transformations; simplifying iteration end condition; smaller details)*
[Try it online!](https://tio.run/##tVI9T8MwEN37K7zZkVuFlI@tEwtMkShDhiyVECyVYEUJC0hVE9UVFeJjLksGpA5QCSEhpPBP7o@EZztpQkVHLNl398737p2TwcWwc3I5GJ6fFUUkaJy5ktQHpTeUzh2ENPmi0SziPu95NLpDIs@QovGTEAJOm1SCgNIHfU4@88zxjKH0uo2tUZU4mlBlyIzzRVfygPmhy0m9AndCsfP9SImmWjqk3nSVWl7lmYjyhSeNFlS/84D3dAL0hlI9d3HHaABiNKC7WGuslm3dJ5nr0uKURrekpobwBb3yxTbGo@l9/2gf5/HBYb@AxS1hjec5DEUzzhjr6CU5g@8iDFis/ZjJFR6XkG@MBNiyNAhbv3i7e//D623VvIZAMkPMwAHiKqgzIGNmlQ3qwGY2T7Db6FQOoVdVrpdrzgA7rFEpZXlVQlAtr2xtvQr1/0RZWDK4DdT0YKu@FbqmbOM41TSyfJg4sK8VszXrx6vn2czW@G20ACtGywrhSqvFfFTo93XKuoH17AM12H8A "APL (Dyalog Unicode) – Try It Online")
Outputs `2` for truthy, `1` for mediumy, and `0` for falsy.
Similarly to my solution to [Solve the Halting Problem for Modilar SNISP](https://codegolf.stackexchange.com/a/206773/68261), this moves the grid around the ball location, so the ball is always in the top-left, moving right. This might not be the best strategy (as opposed to storing a pointer position and direction) in this case because the ball doesn't always start from the top-left moving right, so I spend many bytes rotating and aligning the grid.
## Details
Append 1,2,3,4,...,n to the input grid.
This prevents symmetric grids from comparing equal after some sequence of moves
```
⍵,⍳≢⍵
```
We must be careful here and elsewhere in the code that we do not affect
the angle of `/` and `\`. Using a simple reflection `⌽` to reverse direction
should change `/` to `\`, but the reflection of the character `'/'` is `'/'`.
Conveniently, APL matrix reflection operators are visually sensible:
* `⌽` reflects across a vertical line: swaps `/` and `\`
* `⊖` reflects across a horizontal line: swaps `/` and `\`
* `⍉` (transpose) reflects across the main diagonal: no change
Thus we must use an even total number of `⌽` and `⊖` in all transforms.
Obtain all 4 starting directions/rotations:
```
(⊢,⌽∘⊖¨)(⊂,⊂∘⍉)
```
Shift each grid so that 'X' is in the top left
(Shifts 'X' to the left edge twice, transposing the matrix in between)
```
{(¯1+⊃⊃⍸'X'=⍵)⌽⍉⍵}⍣2¨
```
For each starting grid, beginning with the starting grid, repeat 4×#coordinates (= max # of states) times...
```
\(4×≢,⍵)⍴⊂⍵
```
...move by one step:
```
(((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨1⌈¯2+'X O\/'⍳⊃)
⍝ Get the ID of the entry: `X`, ` `, or `O`:1, `\`:2, `/`:3, `|`,`+`, or `-`:4
⍝ We can consider |, +, and - as the same because we are always travelling
⍝ horizontally (albeit on a rotated grid), and these all do the same action
1⌈¯2+'X O\/'⍳⊃
⍝ Get the corresponding grid position after the move
((⊢,⍉∘⊖∘⌽¨)1⌽¨⊂,⊂∘⍉)⊃⍨
```
`1` if there exists a move history whose final move's top-left element is `O`, and add another `1` if there exists a move history where the `⍺`-th move has top-left element equal to `O`.
```
(∨/+⍺⊃⊢)∨⌿↑{'O'=1↓⊃¨
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~170 ... 147~~ 145 bytes
Expects `(n)(a)`, where `n` is an integer and `a` is an array of strings. Returns `3` for *truthy*, `0` for *falsy* or `1` for *mediumy*.
```
n=>a=>(g=(d,y=a.findIndex(r=>~(x=r.search`X`),j=n))=>+(a+a+1)[~j]?D&&g(--D):!(k=Buffer(a[y+=(d-2)%2])[x+=~-d%2]*5%26%5)*-~!--j|g(d^4-k&3,y))(D=3)
```
[Try it online!](https://tio.run/##XVDBjtowEL37K2YPwHgdmyUsPVRyKlW0Uk8c9oJEqNZKnGxY5GwdtgLJ4tepHZJu2IlsvXnzMvM8O/VXNZmt3g7c1Lm@FPJiZKJkgqXEPDpJJYrK5L9Mro9oZXLGo7Si0cpmL8/rZxrtpKFUJgwVU2xGN@fd9ttyPC6R8yX9eoev8vt7UWiLanNiviWP6Sje0s2RyTPPPbxfjOIvowW95@c7zneuxPz3I38dz6MTpbiUc3qx@s97ZTVOimZChdUq/1nt9dPJZPhAxaF@OtjKlEhF87avDjhJTWq8sKjtD5W9YAMyAdyYCIQQagsSmg/lhEaQ1aap91rs6xILZIaioj4usxkBAB6CeTT1yRocAQes45z/Qni06hHj7IrI7CH834oZtNCFBnDD9vJBjxuWxAvSmQgRitO2svYnBcIY60rMe@sNhVE@W91kkHbKaXhFCn1M4dMEEl8deEvrYNfB4F65zh8h80dy7cB6B9ARrvWYug8iaBgMCN/5uj/SL2OgaH2vWnOfFMMp/7cE/wA "JavaScript (Node.js) – Try It Online")
### How?
We use the following compass for the directions:
```
1
0 + 2
3
```
Which means that we have \$dx=(d-1)\bmod 2\$ and \$dy=(d-2)\bmod 2\$, assuming that the sign of the modulo is the sign of the dividend.
With this setup, we want to update \$d\$ to:
* \$(d\operatorname{XOR}2)\$ for a 180° turn (bouncing on either `-`, `+` or `|`)
* \$(d\operatorname{XOR}1)\$ for a 90° turn when bouncing on a `\`
* \$(d\operatorname{XOR}3)\$ for a 90° turn when bouncing on a `/`
We use the following formula to convert any board character of ASCII code \$n\$ to \$k\in[0..4]\$:
$$k=((n\times5)\bmod 26)\bmod 5$$
The great thing about this formula is that the value that \$d\$ must be XOR'ed with when going through a character is immediately given by \$4-k\$ (except `O` which is turned into \$4\$).
```
char. | code | *5 | %26 | %5 | 4-k
-------+------+-----+-----+----+-----
' ' | 32 | 160 | 4 | 4 | 0
'X' | 88 | 440 | 24 | 4 | 0
'O' | 79 | 395 | 5 | 0 | 4
'/' | 47 | 235 | 1 | 1 | 3
'\' | 92 | 460 | 18 | 3 | 1
'|' | 124 | 620 | 22 | 2 | 2
'-' | 45 | 225 | 17 | 2 | 2
'+' | 43 | 215 | 7 | 2 | 2
```
### Commented
```
n => a => ( // n = number of moves; a[] = array of strings
g = ( // g is a recursive function using:
d, // d = current direction
y = a.findIndex(r => // y = index of the row r[] in a[]
~(x = r.search`X`), // which contains an 'X' at position x
j = n // j = move counter, initialized to n
) //
) => //
+(a + a + 1)[~j] ? // if j is negative and we have visited at
// least more than twice the total number of
// cells in a[]:
D && // if D is not equal to 0:
g(--D) // do a recursive call with D - 1
: // else:
!(k = // compute k:
Buffer( // get the ASCII code at (x + dx, y + dy)
a[y += (d - 2) % 2] // add dy to y
)[x += ~-d % 2] // add dx to x
* 5 % 26 % 5 // apply the formula described above
) * // k = 0 means that we've reached the hole,
-~!--j // in which case we yield 1 if j != 0
| // or 2 if j = 0 (j is first decremented)
g(d ^ 4 - k & 3, y) // update d and do a recursive call
)(D = 3) // initial call to g with d = D = 3
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~384~~ 378 bytes
```
def l(d,r,m,i,c,p):
m+=[[d]+p];p[1]+=(d-1)*(~d%2);p[0]-=(d-2)*(d&1);s=r"/\-|+OX ".index(c[p[1]][p[0]])
if s<2:d+=(s^d&1)*2+1;d%=4
if 1<s<5:d+=2;d%=4
if s==5:r+=[i]
if [d]+p in m:return r
return l(d,r,m,i+1,c,p)
def f(c,v):
i=c.index("X");i2=c.index("\n");p=[i%(i2+1),i//i2];c=c.split("\n");r=[];
for d in range(4):r+=l(d,[],[],1,c,p)
print([[1,0],[2,2]][v in r][r==[]])
```
[Try it online!](https://tio.run/##bVDbjpswEH3nK0ZIWdlrpwQneQnxN/CKZFypwqG1tGGRya5aCfXX07ExkK4yXDQ@njlzzvR/br/eu/39bi4tvBHDHb9yyxve01MCVyaVMpr1uuhVrpkkZpvTV/LXbARFaKe3HhIImZecFoN0aVZvR1ZWkH6znbn8Jo3yrVr5ak0TsC0MZ3EySDZ8912vguWF2chDuMvPw/nob8WKDVIeTw61WB3OQRLYDq4nd7l9uA5cAjFbPLA8uEi8sZY0/NMbsrKJstIqpYUV67nuEOhxxoZYVES5zTIrdNFgydC/2VsscVLpIoH23YHxGtyP7ueFHKgX6Icr7d84HHpnuxtRKuc7xAUXuInP0KaVk0il6b0laZrWCQBsfTDANMNTBSOmI7AZHfEJgWm5pAzvfCAJh3xPk2QlDL2BELB3InxA59bnhJFx9z9jVOljKveRhX@FXz1jjLFYxrzsKCEOmbIJK59gUMfebMECMyzTnmkJesXxQS@b9laNcXvLvxyj0annq0U2K5/njMFhPa6Ar1mdQRiyWJgW/FARPJZB/JeKxynL5idZ@wO9/wM)
*Edit*: Saved 6 Bytes thanks to [Ad Hoc Garf Hunter](https://codegolf.stackexchange.com/users/56656/ad-hoc-garf-hunter)'s suggestion.
Takes input c = string, v = power level
Outputs 0 for falsy, 1 for mediumly and 2 for truthy
This is my first codegolf submission, so there's most likely a better way but I tried best:
**Explanation:**
Note: Directions are encoded as an integer, where 0 = North, 1 = East, 2 = South, 3 = West
```
def l(d,r,m,i,c,p): # d:=direction, r:=result, m:=moves
# i:=steps, c:=course, p:=position
m += [[d]+p] # add direction and position as a move
p[1] += (d-1)*(~d%2) # if direction is even move up or down
p[0] -= (d-2)*(d&1) # if direction is odd move to the left or to the right
s = r"/\-|+OX ".index(c[p[1]][p[0]]) # get next token as an int
if s<2: # case "/" or "\"
d += (s^d&1)*2+1 # rotate either 270 or 90 degrees, depending on
# whether the direction is odd or even
# flip the condition depending if "/" or "\"
d%=4 # correct direction in case of overflow
if 1 < s < 5: # edge hit
d += 2 # rotate 180 degrees
d %= 4 # if direction overflows
if s == 4: # case "O"
r+=[i] # add number of steps to result list
if [d]+p in m: # if move was already made
return r # return result
return l(d,r,m,i+1,c,p) # call next step
def f(c,v): # c is the string, v the power level
i = c.index("X") # getting the index of the "X"
i2 = c.index("\n") # getting the width of the course
p = [i % (i2+1), i // i2] # transforming it to a [x,y] position
c = c.split("\n") # splitting the string into a list
# so it can be accessed via [y][x]
r = []
for d in range(4): # the 4 starting directions
r += l(d,[],[],1,c,p) # starting the loop with the init values
print(2 if v in r else 0 if r == [] else 1) # if the power level is in the list
# output 2
# if the list is empty (hole could not be reached)
# output 0
# else output 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 94 bytes
```
WS⊞υι≔⪫υ¶ηPη…η⌕ηX≔⟦⟧υF⁴«≔⟦⟧ζW¬№ζ⟦ⅈⅉι⟧«⊞ζ⟦ⅈⅉι⟧M✳⊗ι≡KKO⊞υLζ\≦⁻³ι/≔﹪⁻⁵ι⁴ι¿№+|-KK≔﹪⁺²ι⁴ι»»⎚FυP=№υN
```
[Try it online!](https://tio.run/##ZVFRb4IwEH6GX3HpUxswJtO9aPawaJZsETXZi4v4gFCkWdcSoJo5/O2sLTiJu5Cj/e677653cRYVsYx405wyxingV5Gr6r0qmDhgQmCtygwrHxiZus9lyQ4Cv0kmDIRCgYgPmY4Eilcs1zkVNte1Pc2@Y05nmcxx5sMLE4n5ow0i5Ka13fmg9DWVBeAxgR/X6UXOOuJ0fS2lVpRK65592G6wrvxhHNtpPZPn2Fb/BbWCE8gjxXNW0LhiUuC5VHtOE8xsJ45TnlgVZ4DXlH7iTiyOSgpohSZ/E1hQcah0gTanjYehJgRR3va8oGmFAyZU6cOoHdmVONS87mGBTBSXLQ8/GpoPY3KlJzSN9DAnwFLo3ou8eoB86LojdzprrmUe7mUurv4u7ozTqMDX@SoCvUWhJ3RblS2kH2m3v1Rfe1qYWtOmAWvewJoH4LZAPTQ@rG@A4XjQAza1QVvAs8k9Rm0oK@OGd4x@Fc@crbnuaNwMjvwX "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the course and power level separated by a blank line, and outputs `-` for correct power level, `=` for incorrect power level, and nothing for an impossible course. Explanation:
```
WS⊞υι
```
Input the course until the blank line is reached.
```
≔⪫υ¶ηPη
```
Join the lines back together and print the course without moving the cursor.
```
…η⌕ηX
```
Print the course up to the `X`, which leaves the cursor at the start.
```
≔⟦⟧υ
```
Start keeping track of the working power levels.
```
F⁴«
```
Loop over all orthogonal directions.
```
≔⟦⟧ζ
```
Start keeping track of visited positions. (Because I really need a repeat...until loop here, this is slightly golfier than just comparing the current position with the initial position. I also need the number of steps anyway.)
```
W¬№ζ⟦ⅈⅉι⟧«
```
Repeat until we're at a previous position and direction. (This can only happen when we get back to our starting point and direction, since the other saved positions can only be reached from there.)
```
⊞ζ⟦ⅈⅉι⟧
```
Save the current position and direction.
```
M✳⊗ι
```
Move in the current direction. (In Charcoal, direction 0 is to the right, increasing by 45 degrees anticlockwise each time, so that e.g. 6 is down. Since we're not interested in diagonals, I work in multiples of right angles and double them for the `Move` command.)
```
≡KK
```
Switch on the character under the cursor.
```
O⊞υLζ
```
If it's an `O` then save the power level (i.e. number of steps) needed to get here.
```
\≦⁻³ι
```
If it's a `\` then XOR the direction with 3, which here is simply equivalent to subtracting it from 3, as Charcoal has no XOR operator.
```
/≔﹪⁻⁵ι⁴ι
```
If it's a `/` then XOR the direction with 1, which is equivalent to subtracting from 5 modulo 4.
```
¿№+|-KK≔﹪⁺²ι⁴ι
```
Otherwise if it's any other wall then XOR the direction with 2, which is equivalent to adding 2 modulo 4.
```
»»⎚
```
Clear the canvas once all directions have been considered.
```
FυP=
```
If it was possible to get the ball in the hole then output a `=`.
```
№υN
```
But if the input power level was correct then change that to a `-`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 240 bytes
```
(g,P,w=g.indexOf('\n')+1,f=(d,i=g.indexOf('X'),p=P,a=[],c=g.replace(/-|\|/g,'+')[i],s=Math.sign(d),q=w+1-d/s)=>a.includes(k=''+[i,d])?0:!p&&c=='O'?3:c=='O'|f((d=c=='/'?-s*q:c=='\\'?s*q:c=='+'?-d:d),i+d,p-1,[...a,k]))=>f(1)|f(-1)|f(w)|f(-w);
```
Returns `3` for truthy, `1` for mediumy, and `0` for falsey.
[Try it online!](https://tio.run/##fVRdb5swFH33r7h7qWE2UJrtJZGXXzBRKS@RAKkIDGWlQDFZNs377dnFfCRqshrhHI6v78exb34kPxOVdmXbO3WTydNOnKyCP/KjKNyyzuSvILdoVFOb@TwXVsbLy4U9tXkrHnkiwpinuNLJtkpSaXmOjrRXcMqoHZYxV@J70j@7qixqK7P5mzgy38k8ZYtvCbpLq0MmlfUiKGVhybPY3t6vP7V3d6kQNKDb1XoEOresTAzYo1tHfX4zfBTR7YwZ8tkaQ5Qs463j89B13YS/xDaGyi3fRheOmY8GHu3Nqe8O/fNvELDakFeZlYfX4cPfkDyplBzw/YaQNFFSiZCQcNd3ZY21JscnAgDOMBgg9PBrDxqhBjazGh8zEAYLZLg2widOfJ/DmETMyXWA92PinHmcOc/Me3yjmWOMTWZsSMRwS0ojGrngBgfRtNdbOOMZlmg3c8GSHr5elnRd0agASrLXk0bLHOh5dfDDYTqS236uZWFztTOhjSqRPhODzVkNMEksZTOz@cLC6BKYgt9ZXEZZDhSuE8M6Vl8@PmIjHZlEjYCwUUrQRI/BPRjQ3hgQNmttJPI/lJrNt3OoZLydF@z5Hv7/dt5zGDth8B9jK@RNB1YlewiLTsqaQ1tx6KQ6VH0MTQ6mVWz4g5GMAXaQ@XVVVeKfA@aLLbjB1bSpVVNJt2oKa9wPDCgIgRODnbW4t9H87@kf "JavaScript (Node.js) – Try It Online")
Nice question!
I'm not super happy with my result, but I did learn a cool trick in the meantime: you can save some bytes by replacing
```
(a1,a2)=>{x=f(a1,a2);return g(x)}
```
with
```
(a1,a2,x=f(a1,a2))=>g(x)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 298 bytes
```
l=>s=>{def h(d:Int,c:(Int,Int),p:Int,r:Set[Any]):Int={val x=(c._1+(d-2)%2,c._2+(d-1)%2)
val a=s(x._2)(x._1)
if(a==79)if(p==1)1 else math.max(0,h(d,x,p-1,r+(c->d)))else if(!r(x->d))h(d^(4-5*a%26%5),x,p-1,r+(c->d))else-1}
0 to 3 map(h(_,s.map(_ indexOf'X').zipWithIndex.find(_._1>=0)get,l,Set()))max}
```
[Try it online!](https://tio.run/##lVFRb5swEH7Pr7hFimIPQwJtNg3JSH2stImHPixS00UemISJEgTexBby29nZEEq6PixGNnefz/d9d1dFIhPt4fsPGSn4ItIcZK1kHldwVxRwnPwSGex8uM8V8AA@p5V6fFBlmu@etG/gNuNBxYNjLBPYk9hHkEU@0T/clBUGKf0HqR7v8t9PVPv8qDPXnETO1rVIbHt05jF0PO246FDDLXhFakSpPl06SRMiOP/4iaJRcO5SF2RWSXgWau88i5osGWpgNStsl5UWiewgppSaGHzyriS1QTDoG7m1V@/FzPswW9HXL/QD2z1NlqAOcIPpC7InW1Y52tpCmseyDpP5ek6dP2nxNVX7ew05Cd6QLUoN@JLupGIZw7oJSkBxp1aXlHCSmZZU/riflAc7klFS0UmBgMpykhDXZdPpFAAmuG29LG0u0FtDg2YD1hlt8DMLzXAwLXOHSZyqyFJF5pscNauDpnaUSDN6wbca8ZnUVmc2Pd8I1Znf5oMrGL0Lxr5IvWDAFuZc494MyiyrD7N01b3EXkRndVj4Bgab/u1iwExmGNj@1XJFQUM9XeubddMPZzjD5urB3Nxetsk6V38GGtOlTfMC6JiX7oARMrShG@IowvQpNA14FTFmGWb@HzM@ta2dSKF@lvIv "Scala – Try It Online")
I used the brilliant formula Arnauld used in their [answer](https://codegolf.stackexchange.com/a/207811/95792), but it's still a pretty large amount of code.
Outputs -1 for false, 0 for mediumy, and 1 for truthy.
Prettier version:
```
//l is the power level, s is the golf course, split on \n
l => s => {
//h is a recursive helper function
//dir is the direction, c is the (x,y) coordinates of the ball,
//p is the power level, and seen is a set holding a tuple of all the coordinates and directions
//(In reality, seen is a Set[((Int,Int),Int)], but I was lazy)
def h(dir: Int, c: (Int, Int), p: Int, seen: Set[Any]): Int = {
//The new position
val x = (c._1 + (dir - 2) % 2, c._2 + (dir - 1) % 2)
//The character at the new position
val a = s(x._2)(x._1)
if (a == 79) { //Found the hole!
if (p == 1) 1 //Power level is right
else math.max(0, h(dir, x, p - 1, seen + (c->d))) //Power level is right
} else if (seen(x, d)) -1 //We're just looping around, it's never going to work
else h(dir ^ (4 - 5 * a % 26 % 5), x, p - 1, seen + (c -> d)) //Go on to the next move
}
//Try out every direction
(0 to 3).map(h(d =>
d,
s.map(_.indexOf('X')).zipWithIndex.find(_._1 >= 0).get, //The start coordinate
l,
Set()
)).max
}
```
] |
[Question]
[
This is [the exact same question I asked earlier](https://codegolf.stackexchange.com/questions/195931/can-this-village-have-a-wedding), but without the annoying Cyrillic factor which many found superfluous. I hope this is a better puzzle!
---
The quaint hamlet of North Codetown in the Scottish far north has a problem: their population is low (below 52), and no new people have arrived for years. Moreover, after centuries of near-isolation in their secluded valley without much economic opportunity, just about everybody is related to each other.
Mayor Montgomery has a solution that should keep the morale high: organise a wedding. However, the question is, are there two bachelors in the town that aren't at least cousins of each other?
The mayor fired up his state-of-the-art Microsoft Bob computer to consult the genealogy charts. They had just been updated to the brand-new ASCII format, and look like this:
```
b┬K
l
```
And this:
```
A┬d
O┴p┬Z
q
```
And this:
```
e┬N
L┬m┴p─┬F
B┴y┬A z┬Y
f E
```
And even this:
```
i┬────────N
m┬E
│ Z
│
│
z
```
Here's how it works. Each person is a letter from the Latin alphabet. Males are capital letters (any of ABCDEFGHIJKLMNOPQRSTUVWXYZ), females are lowercase letters (any of abcdefghijklmnopqrstuvwxyz).
A '┬' between two people means they are married. Right below that is either another person - their child - or a '┴', meaning that this couple has two children; located to the left and right of the symbol.
Moreover, to the right and left of '┬' and '┴' there can be any number of '─' characters, to extend the lines, as it were. Similarly, there can be any number of '│' characters above a '┴' or below a '┬'.
Lastly, a character without any defined symbol above them is considered a new arrival to the village, and by definition unrelated to anybody.
Also be aware that this is a very conservative village. Nobody marries more than once, and every marriage is heterosexual. Furthermore, assume everybody in the graph is alive, and no two people share the same name: e.g., the same character never occurs more than once.
The two bachelors should be of the opposite gender, and they should not be first cousins or any more closely related. First cousins once removed is okay. In other words: they should not share a parent, or a grandparent, or have one's grandparent be another's parent.
## Challenge
Make the shortest possible program (by byte count) with as input either a string (containing newline characters), or a string array, or a rectangular two-dimensional string or char array (no higher or wider than 100 characters), containing the family tree of the town. Assume the input is a valid family tree, consisting of nothing but ASCII printable characters and the mentioned line/forking characters. Ignore any character not given an explicit function in the above description.
Return a boolean value of true or false (or a bit/int of 1 or 0, or any consistent truthy/falsey value used by the language of your choice) to indicate whether there can be a wedding given the family tree.
## Examples
1.
```
b┬K
i
```
FALSE (there's only one bachelor)
2.
```
A┬d
i┬O┴p┬Z
z F
```
FALSE (z and F are cousins)
3.
```
e┬N
L┬m┴p─┬F
B┴y┬A W┬y
E T
```
FALSE (B, E and T are all male)
4.
```
e┬N
L┬m┴p─┬F
q┴A┬y w┬R
U E
```
TRUE (q and E can marry)
5.
```
i┬────────N
m┬E
│ w
│
│
W
```
TRUE (w is not related to anybody)
6.
```
d┬F
a┬────────N┴─e┬E
│ │
│ w
│
│
V
```
FALSE (V and w are cousins)
7.
```
Ww
```
TRUE (W and w are unrelated)
8.
```
fw
```
FALSE (f and w are of the same gender)
9.
```
e┬N
L┬m┴p─┬F
n┬B┴y┬A w┬Y
C E i
```
TRUE (i and E, and also i and C)
10.
```
A┬d f┬H
m┴P┬z i┬Y
F u
```
TRUE (F and u)
NOTE: You are free to substitute the control characters with ASCII characters if it makes your program simpler. In that case switch out │ with | (vertical bar), ─ with - (hyphen), ┬ with + and ┴ with =.
Example:
```
d+F
a+--------N=-e+E
| |
| w
|
|
V
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~399~~ ~~393~~ ~~390~~ ~~388~~ 385 bytes
```
def f(s):
V=S(''.join(s))-S(' |+-^');P={v:[]for v in V}
for j,r in E(s):
for i,c in E(r):
if'+'==c:
p,q=a=h(r,i);A=a+P[p][:2]+P[q][:2];V-=S(a);v=j;b='|'
while'z'<b:v+=1;b=s[v][i]
if'^'==b:w,x=h(s[v],i);P[w]=P[x]=A
else:P[b]=A
return 1-all((b>'Z')==(c>'Z')or S(P[b])&S(P[c])for b in V for c in V)
h=lambda r,i:[x.strip('-')[0]for x in r[i-1::-1],r[i+1:]]
E=enumerate;S=set
```
[Try it online!](https://tio.run/##lVNRj5pAEH6WXzFPXTYLpt4jdJvYRtOkzZXkjMZblwQU4hpFDlDUs7/d7iyod7mkSTfZ3ZlvZj5mPiA/Vstt9nC5LJIUUrukngVj/mQT0l1tVaYB6moPzswNCfUD/rr3hEy3BexBZTD@YwE6K6dAd2AIOogoZ94gBSKgUsII53Ntd3LnhUd8aReOon6fRywQuRTeg9TGizH8sat7iKi/5ys/5uRMdFm9VOuEnMiX2Nsz3tN4KfZSKKljmj7U9LFXOwfNjAEkD0QteSAOkvd1UrIuEy8QMXpQJNWuyKDnRuu1bcdfyTOhnNtzY@j@n2zMpJ/wnkuKI8VmYjOvmW1MrSVfR5t4EYGexROHblkVKreJS6j4bFQ6YGIhlNvzPLcnHW2ynielNeBJttskRVQl/hMvk@oyAg7C6hCAhD3Osl9sE@YuG86yb@GR9eHEprMMAHZ6D4hjEk0qXoChawV6GWuqajbF2Hcs0lsB3EpvSzG3XY8N0X1t2OCN9z4GZ3PW/4jBf8cmzWWanNRNr322aNCU/WgqNmHATm3v0yvHsKVAgYiFlrSsYStqzH42pQruErTEiLLfYc6eG6qTIWuT7gK/lbcRd8KOzbNRpNFHaRf49iC6yxu6CRtgxTsJzh@Q2iC3Y3yTJK1vk@HXVeLXNWJD/VflhcoqKK@G/pW7Zb5WlU1mGaG0xS3r8hc "Python 2 – Try It Online")
2 bytes thx to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse); 3 bytes thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg).
Jeez! I think I could golf this a bit more; but at least I got it under 400 bytes :).
The input `s` is a list of strings. The encoding is `A-Z` for males, `a-z` for females, `+` to indicate a marriage, `^` for when a marriage produces 2 children (instead of `=`, 'cause I liked the look better :) ). Then `-` for horizontal extensions, `|` for vertical extensions.
Output is `1` for truthy, `0` for falsey.
`V` is the set of all villagers, initially; then as we scan, we will remove from `V` those who are already married. So at the end, `V` will be the set of un-mated villagers.
`P` is a dictionary with keys for all villagers `v`. `P[v]` will be the list of those parents of `v`, followed those grandparents of `v`, who are also villagers. Note that then `P[v][:2]` are the parents of `v` (assuming they are villagers).
`h` is a helper function to skip over any horizontal extensions (runs of `-`). Useful both for extracting a pair of parent villagers as well as dual children.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~155~~ 153 bytes
```
Ø.UAƭN,Ɗ⁺+Ṫ¥+œị⁾+|yⱮ$ɼ=⁾|=⁼Ø.Ɗɗ¡ƬṪ¥ƒ⁸’1¦⁺œị®⁼”|ƊпṖṪ+2¦œị®⁻1Ɗ¡ƬṪ¥ⱮØ+$“”¹?
o@e¥€€ØẠ“-=“==”;U¤œṣjƭƒ$€ƬṪ©=1ŒṪ+2¦œị®ɗⱮØ+f⁾-+ƊÐḟWÇ€Ẏ$Ƭḣ3ẎƲ€Œcf/ÐḟḢ€€ȧœị¥>”ZIFẸ
```
[Try it online!](https://tio.run/##rVNbaxNBFH6fXzHCPrlGiT6WVKM0KEoUMYb2TW0CDfX2IMuWPGyKEIgXJAYbweIltqKkBaWETTYqzJLB/IyZP7J@MxNzI4QGHHbPnHPm@85l9mwht7npRlFYP51J8oP0KV6RpY4t2t/Ynt17LYJnsvTLLrry@6HV7yZgFCG6gPNKf4d95E0N5VVZ8qX3Ns72Qdc8dgic9HaLvBK@Yr9F@w2Q9lm2PzwN4rwyjIAEYd22pPcOHNY@Tx5eyMG73cQT1kXnA05iCYgExO5Shn1GnHajwA941QLGhPmaiPeqk3n6OyZ0HrXHbFWM8N9nwzI4ovPSAs9vnIPGf8DTq97Ln9EI4X8yyf98MYH2lpF37UpKdPxoCXWwFo0tU1WLCI7CskV0PUjCWqylwxcGBpGlnydE8EKzGifRule3wqcieN7rqq6Ktmop5eIKw3IU3ZW15lVKKaEbVG0EIgnfOjVOqNdl7egR9jXloFvwpwbIHLxpqpHXoN43QA8qEOQiTBd6kmYhXUWmK3hvHYf8GGZS0xzIm5qcMQF0jaOlStS8GU9alzxaSNJcGbMnI8natt6deYd04cPsxNH42bppdv4i9M68DnFP2HJTjc0KM13llHkcirMogf5/wu1F4CTrEJJ3zK2PTRylM2buAfbR0Kq5WwXy0mBsN/THG/4blOahXtbBVJwbsLaGA7k6GIJ/X/cJ3r8 "Jelly – Try It Online")
Minor modification of my [Cyrillic version](https://codegolf.stackexchange.com/a/196118/42248).
A monadic link that takes a list of Jelly strings and returns 1 for true and 0 for false.
I’m sure this could be golfed more. Full explanation to follow.
] |
[Question]
[
[Quylthulg](https://github.com/catseye/Quylthulg) is a language by Chris Pressey that attempts to solve the problem of infix notation using what it calls *panfix*:
>
> like postfix, panfix does not require the deployment of arcane contrivances such as parentheses to override a default operator precedence. At the same time, panfix allows terms to be specified in the same order and manner as infix, an unquestionably natural and intuitive notation to those who have become accustomed to it.
>
>
>
---
How do you get the convenience of infix notation along with the unambiguity of prefix or postfix? Use all three, of course!
```
=y=+*3*x*+1+=
```
More formally, let `+` be an operator, and `a` and `b` be expressions. Then `(a+b)` is a valid (parenthesized) infix expression, the panfix representation of that expression is `+a+b+`, where juxtaposition represents concatenation.
Your goal is to take a panfix string and convert it to fully parenthesized infix:
```
(y=((3*x)+1))
```
For simplicity, we'll make the following changes:
* Operators can only consist of two unique characters (you can choose any, but here I'll use `*` and `+`).
* There is only one literal, which consists of another distinct character (you can choose any, but here I'll use `_`).
* The input will be a well-formed panfix expression.
For *complexity*, we'll make the following change:
* Operators can consist of *any positive number* of characters, not just one.
This makes the challenge more tricky because you can't necessarily determine how a given substring of operator characters is partitioned without looking at the rest of the string.
Here is a [reference implementation](https://tio.run/##fVTRbuowDH1uvsLbldaWUka7txV4uZ/BRVVXMohWkioJG7tXfDvXTlooGxoSkNrn2D62m7pt001dn06/hKyb/ZrDTChjNa92C3axvfPaKj20IEbIzdBSNRulhd0ikRm7fn72EDCqeefRlcXG8I8FzuQjz76du/gLWLcFCx4f8X/ZcLlaGltpu4I5CPkqDqB5q7nh0lZWKAnqFeyWg2c7nrETs39BQ@SYY8Ao8RhelaYTLGA6BjzzXWs/QTi65o4pjAwtVPKTsWDdThDRVDUvX6r6LYoLIIRc8wNMb/gxK0bf2G0Ux1g/ZYuM@MtLC64MrH8AKTpjmmI5hWtOgKVglLPcOYRlGKMdUy2zcxsSZ8cMVLCi2j@E4aiseucgrJfFgiO7roGUzyEv3GH2pZYkoRa5In6QBakjJ5CRwJsKke2bNSHHbZnBYNoP2GzjeMNRF@wLDBStxHXKXXUoVct1hQtU@hIxUISnNI/hEZ7GxAhU26A5K4AOqPsGjfSjl@BdhciiPvfDQOEZykbMypXhJqV6qcNJBcELvkhvXkAHg7v515WkdqcYbkwx445ZK2mF3POeLLGtmdsaYiDQ574aKvlpJlRgCk8jQqG1wIY3WS/GhWpyD00dCL1jMPk5ek7GBIkdAQu/o5nQ2mWridspVPrwAB4QOG@O3nzo7Zyoef5ds8/QSe5L86lwCfooF49fgJprDbMZ3P9We2nxRT1UuJ78Ge57GDqNJUj4R4ZFb7VbrT5w57rnY/fv1y2MQpznRaAbbmfxovAhjPtonnyk91/yA7WdXT33@wR@n9jQ5xeoVUbQbcWGUTyYBZrbvZaUfPCyrZZTXDZ8i2l4u0rI6HKDni9VrO9jKxoO/rKtBd5ui/6y7fqn9q45/Z0cDzp1POeeUqrTKRmNEvqUg99ROUpG3fnKgS6WeJ//OmR5ZUn@Aw) for the challenge, courtesy of @user202729.
## Test Cases
```
format: input -> output
+*+_*+_*+++_+*+_*+_*+++ -> ((_*+_)+(_+(_*+_)))
**++*+***++_+_++_+*++*+***_*++*+*****_**_*_*** -> ((((_+_)+_)*++*+***_)*(_*(_*_)))
***_**_***_* -> ((_**_)*_)
+_+_+ -> (_+_)
*+*+++**+***+++++_*+*+++**+***+++++_*+*+++**+***+++++ -> (_*+*+++**+***+++++_)
*++++*+*_*_*+*+++****+_++****+_++****++*+*+++_*+++ -> (((_*_)+*+(_++****+_))*+++_)
+**+_*+_*+*_*+*_*+*_+*_+**+ -> (((_*+_)*_)+(_*(_+*_)))
+**+++++_+++++_+++++*_*+*+_++++++_+++++_+++++++* -> (((_+++++_)*_)+*(_+(_+++++_)))
+*+*+_+*+_+*+*_*+*_*+*+_+*+_+*+*+ -> (((_+*+_)*_)+(_*(_+*+_)))
**_**_**_*_****_* -> ((_*(_*(_*_)))*_)
```
I used [this program](https://tio.run/##fZBBDoIwEEX3PcWkq1YTDLozehaCMEANdJqhJnr6WqBRg8Zuuvh/3pvWPXxH9hCCGRyxBy5tTYMQNTbQoi/IIZeeWOmjgHh6tK3v4AzGepXDLg1ky6W0nluM/sYWpMyuZKxKnaojU6GS243U0BBDESkToEW1cOP4y4x3xziOhqxyTJfkN83aCCeY8iX@lCsJ21@kuPRep@j9vP9dqeXMx37Eb1MhhXA8/cgKkWsdwhM "Python 3 – Try It Online") to generate infix strings for this challenge (converting to panfix was trivial, but reversing is not).
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~194~~ 163 bytes
*Saved a whopping 31 bytes using [this tip](https://codegolf.stackexchange.com/a/153160/16766) from [0 '](https://codegolf.stackexchange.com/users/20059/0)!*
```
[C|T]/O/R:-C\=x,(T/P/R,concat(C,P,O);O=C,R=T).
[x|R]-x-R.
L-X-R:-L/O/A,A-Y-B,B/O/C,C-Z-D,D/O/R,atomics_to_string(['(',Y,O,Z,')'],X).
X^P:-string_chars(X,L),L-P-[].
```
The operator `^` takes for its left argument a string containing a panfix expression and sets its right argument to a string containing the corresponding parenthesized infix expression. It uses `x` as the literal in place of `_`.
[Try it online!](https://tio.run/##LUzNCoJAGLz7FNLF3ZhP74aHXI@CsniwzEQkSrA23A09@O62YTDMD8PMe1SDupOe@nWtxFLUQRbIkMQlmsGKIA8kOvXqWsMEcmT8kEUCMiq471TzImuaSfpOSiXZVWrHRxzpRDFi6wUEnSlB8jtFa9Sz73RjVKPN2L/urPKYhxMynOFxr0ZpX8trHtLWN92jHTUrkXKklFNV@2tI7m6/n/@w9JOde3XlTX8GA3cae3NjW@L@@gU "Prolog (SWI) – Try It Online")
### Explanation
Since Prolog is a declarative language, we just have to describe the relation between a panfix and a parenthesized expression.
The explanation uses this slightly ungolfed version:
```
oper([C|T],O,R) :- C\=x, oper(T,P,R), concat(C,P,O).
oper([C|T],C,T).
expr([x|R],x,R).
expr(L,X,R) :- oper(L,O,A), expr(A,Y,B), oper(B,O,C), expr(C,Z,D), oper(D,O,R),
atomics_to_string(['(',Y,O,Z,')'],X).
parenthesize(X,P) :- string_chars(X,L), expr(L,P,[]).
```
Our main production is `parenthesize`, which takes in a panfix expression `X` as a string and sends out the corresponding parenthesized infix expression `P` as a string. It uses `string_chars` to convert the input string into a list of characters and then simply passes it on to `expr`.
`expr` takes in a list of characters `L`, parses the first panfix expression it finds in `L`, and sends out the parenthesized equivalent `X` and the remainder of the list of characters `R`. There are two possible kinds of expressions:
* If the first character of `L` is `x`, then the expression is `x` and the remainder is everything after the `x`.
* Otherwise, parse an operator `O` (see `oper` below); parse an expression `Y`; parse `O` again; parse another expression `Z`; and parse `O` a third time. The remainder is everything after the third instance of `O`. The expression is the result of joining `Y`, `O`, and `Z`, surrounded by parentheses, into a string.
`oper` takes in a list of characters, where the first character is `C` and the rest are `T`; it parses an operator (i.e. a run of one or more operator characters) and sends out the operator `O` and the remainder of the list of characters `R`. To form an operator, the character `C` must be something other than `x`; also, either
* an operator `P` must be parseable from `T`, with remainder `R`; in this case, `O` is the concatenation of `C` and `P`; or,
* `O` is the single character `C`; in this case, `R` is just `T`.
### A worked example
Let's take the input `+*+x+x++*x+*` for an example.
* We want to parse an expression from `+*+x+x++*x+*`. This doesn't start with `x`, so we parse an operator from the beginning.
* `oper` will parse as big of an operator as possible, so we try `+*+`.
+ Next we parse an expression from `x+x++*x+*`. This has to be `x`.
+ Now we try to parse the same operator, `+*+`, from `+x++*x+*`. However, this *fails*.
* So we backtrack and try parsing the operator `+*` instead.
+ We parse an expression from `+x+x++*x+*`. This doesn't start with `x`, so we need to parse an operator.
+ The only possibility is `+`.
+ Now parse a subexpression from `x+x++*x+*`. This has to be `x`.
+ Now parse `+` again from `+x++*x+*`.
+ Now parse another subexpression from `x++*x+*`. This has to be `x`.
+ Finally, parse `+` again from `++*x+*`.
+ The expression has been successfully parsed. We return the string `(x+x)`.
* Back at the previous recursion level, we parse the operator `+*` again from `+*x+*`.
* Now parse another subexpression from `x+*`. This has to be `x`.
* Finally, parse `+*` again from `+*`.
* The expression has been successfully parsed. We return the string `((x+x)+*x)`.
Since there are no more characters left, we have successfully translated the expression.
[Answer]
# Perl, ~~78~~ ~~60~~ ~~58~~ ~~57~~ 50 bytes
Includes `+1` for `p`
Uses `1` for `+` and `2` for `*` (or in fact any digit works for any operator)
```
perl -pe 's/\b((\d+)((?1)|_)\2((?3))\2)\b/($3 $2 $4)/&&redo' <<< 22_22_22_2_2222_2
```
For convenient testing versus the given examples you can use this which does the translations and space removal for you:
```
perl -pe 'y/+*/12/;s/\b((\d+)((?1)|_)\2((?3))\2)\b/($3 $2 $4)/&&redo;y/ //d;y/12/+*/' <<< "**_**_**_*_****_*"
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~200~~ ~~192~~ 189 bytes
```
import StdEnv,Text
f"_"=["_"]
f l=["("+a+p+b+")"\\p<-[l%(0,i)\\i<-[0..indexOf"_"l]|endsWith(l%(0,i))l],t<-[tl(init(split p l))],n<-indexList t,a<-f(join p(take n t))&b<-f(join p(drop n t))]
```
[Try it online!](https://tio.run/##jVLbTsMwDH2mXxEFgXJpp33A9gYPSJNAGhIPaxVlawuBNI1aDw2Jb6fk0m0dT6i245zjY7dWd7qSZmjacq8r1EhlBtXYtgO0hvLefKbP1QGSGgu83LhQJDXSLiOYS275lmOK89wuso2@IfNU0TxX7jKfzZQpq8OjF@riuzJl/6LgjYxVVBcpuDrQRBkFpLdaAbJIU1qkZpEF8Ur1gCCVi6wm760yyBKQHxUyCCi93U7gsmtthIthDbKD5BopY/fQoyXaJFeYMy6CcS4mOU4dx1zGOPOHcE8oiIA4Jj515gIbJRHwHoCgjJRXO01s6Of9AxmVPIzzc8YCR4s/J4/c@fV9n/g97OTB2JkPUycxToj5BeGoURT46Ke@Z@S4OTHZjN9FkSzdP2RRPa5/@NnVWr72Q/awGu6@jGzULl6etIS67Zpf "Clean – Try It Online")
Defines the function `f`, taking `String`, and returning a singleton `[String]` with the result inside.
Some neat stuff:
* Doesn't use regex
* Works with any character for operators *except `_`*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~138~~ 134 bytes
```
.+
($&)
+`\((\d+)(_|((?<i>(?<i>\d+))|_(?<-i>\k<i>)+)+(?(i)$.))\1(_|((?<i>(?<i>\d+))|_(?<-i>\k<i>)+)+(?(i)$.))\1\)
(($2)$1($4))
\(_\)
_
```
[Try it online!](https://tio.run/##lU7LCsJADLznOxaZJFioeBT7Ez0uZIV6KIIH8dh/X5O1VG8izOQxE3bncX3O90sdi0qZaqeEtGPSkoE8KcMWYDjN51ZC4cV83vtyc4WVFQNmTh1z7v88z0xAOnDqkY7MlGEumaeZPE9VUWtQta@ZRMQanOSWuaThiDeJQePyp0KxvF@VjQ0SXny5crM/SsSwFRHFyws "Retina 0.8.2 – Try It Online") Link includes the faster test cases. Explanation: The regex engine uses backtracking to split the string up into tokens which are then pushed on or popped from the `i` balancing group. There is a run of always at least one operator pushed at the start before the first variable. After a variable, at least one operator is popped, at which point either a pushed operator run or another variable is legal. Operators get pushed to the group in duplicate so that they can be popped correctly. Example:
```
Input Stack
Push * * *
Push *++*+*** * * *++*+*** *++*+***
Push + * * *++*+*** *++*+*** + +
Push + * * *++*+*** *++*+*** + + + +
Variable _
Pop + * * *++*+*** *++*+*** + + +
Variable _
Pop + * * *++*+*** *++*+*** + +
Pop + * * *++*+*** *++*+*** +
Variable _
Pop + * * *++*+*** *++*+***
Pop *++*+*** * * *++*+***
Variable _
Pop *++*+*** * *
Pop * *
Push * * * *
Variable _
Pop * * *
Push * * * * *
Variable _
Pop * * * *
Variable _
Pop * * *
Pop * *
Pop *
```
Unfortunately this doesn't help us capture the results in order to bracket them, so the outer operator is matched manually. The brackets are added outside-in, so the first stage wraps the entire expression in brackets and the last stage removes them now that they have propagated down to the variables.
[Answer]
# [Haskell](https://www.haskell.org/), ~~167~~ 166 bytes
```
head.e
e('_':r)=["_",r]
e(x:r)=[x]%r
e _=[]
o%t@(c:r)|[x,u]<-e t,n<-length o,[y,v]<-e$drop n u,all((==o).take n)[u,v]=['(':x++o++y++")",drop n v]|p<-o++[c]=p%r
o%_=[]
```
[Try it online!](https://tio.run/##lVLbboMwDH3nKyy0qkkMlaa9VU21D9ie9pihCDG6TqWAKJ2Y1G8fc5IG2H2DXCxfjo8db9PDLi@KfiPv@22ePizyIGfdsuGnbj3HuVSqS6ImOV2uriSJsybIQUuVBNWsvWaZcVRddExWcQ5tVK7iIi8f2y1UkXqJno364qGpaijhGKVFwZiUFV@06S6HkqsjuUg1Z/Nlh1ghviCGPIzOEc/JqV7FpFZZImtKXc1M6n6fPpUgYZ/Wt8DqY3vXNjclLGDDQQUAEKJAbReinshhBD9/cQzxGhgzARyZRidxHpAlFIQhUJhL02@hnUJ7wYi06BBjMo9KuAZW8yGMC0pAy6YwxD2A2b@y/ZK4AdUOzLL8D8p7MEPW1W3qJL6udNPTP2gor8f57O1x0TbC9OvsQg76w43ONnnAoZ@mcWRkQwjnwsG7IfAvL4Ztl/i5KRN4tM1E@0gohkFAX8fkdDU4@Z2BTD7diHxug@Vvx@ys4J66xXJ7YD9qvitgkuADd5yMmJ5MqZmz5J8jNs4sHf1rtinSx0MfZ3X9Bg "Haskell – Try It Online") Example usage: `head.e "**_**_**_*_****_*"` yields `((_*(_*(_*_)))*_)`. All characters except `_` are interpreted as operators, `_` itself denotes an identifier.
[Answer]
# Python 3, 226 bytes
```
from re import*
P=r'([*+]+)'+r'(\(.+?\)|_)\1'*2;R=lambda i,J=lambda i,o:i[:o]+sub(P,lambda o:'('+o[2]+o[1]+o[3]+')',i[o:],1),s=search:s(P,i)and R([J(i,o)for o in range(len(i))if s(P,J(i,o))or J(i,o)[0]+J(i,o)[-1]=='()'][0])or i
```
Defines an anonymous function named `R`.
[Try it Online!](https://tio.run/##RY9Ba8MwDIXv@xW@SbLdsbQ3j7B7TyVXxxR3TVpBYwUnPQz23zOHBgbi6fH49EDjz3yXdFiWPsugcqd4GCXP@u1UA3ptgiEwGbDFd/PV0u@Z2gr0/rOpH3G4XKNie/y34tg7CWZ6XvBkt1gcIBjx@1CkWuUQDBBY9uKCrchO9dTF/H13U7liiumqGvRHLIXUS1aiOKkc063DR5eQibhXK/tCqCAv5z@C2dyuCnV5gSCUcCV4GTOnGRsErc/bFFkXEC1/)
] |
[Question]
[
This challenge is based off of [Helka Homba](https://codegolf.stackexchange.com/users/26997/helka-homba)'s question [Programming a Pristine World](https://codegolf.stackexchange.com/questions/63433/programming-a-pristine-world). From that question, the definition of a pristine program is:
>
> Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where `1 <= N < program length`.
>
>
> For example, the three character Python 2 program
>
>
>
> ```
> `8`
>
> ```
>
> is a pristine program ([thanks, Sp](https://chat.stackexchange.com/transcript/message/25274283#25274283)) because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
>
>
>
> ```
> 8`
> ``
> `8
>
> ```
>
> and also all the programs resulting from removing substrings of length 2 cause errors:
>
>
>
> ```
> `
> `
>
> ```
>
> If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.
>
>
> **Notes:**
>
>
> * Compiler warnings do not count as errors.
> * The erroring subprograms can take input or give output or do anything else as long as they error no matter what eventually.
>
>
>
Your task is to create a program of non-zero length that prints its own source code exactly, follows the [rules for a proper quine](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine), and is pristine.
Shortest answer in bytes for each language wins.
[Answer]
# [Haskell](https://www.haskell.org/), 132 bytes
```
q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1ChwjYzTSEnNS@9JAPItjU0NirJSM1TKCgtCS4pUqhQSM0pTlVIS8zMiY61zk3MzLMtVNHQ1ta00bIrzsgvV1Gi3IT//wE "Haskell – Try It Online")
This is an extension of the quine
```
main=putStr$(++)<*>show$"main=putStr$(++)<*>show$"
```
which works by concatenating the data string with a quoted version (by using `show`) of itself and printing the result. However, this is not pristine as any characters in the data string can be removed without failing and also the `$(++)<*>show$` or `(++)<*>` part could be dropped without the program breaking.
To fix this, a custom print function `q` is defined which checks the length of the given string and calls `fail` if it's shorter than 132. This catches the removing of any sequence from the data string and also the removals of `$(++)<*>show$` or `(++)<*>`, as in both cases the resulting string passed to `q` is shorter.
In `q` the number `132` could be shortened to `1`, `13`, `32` or `2`, but in each case again `fail` is called.
As far as I can tell, the removal of any other substring causes either an syntax or type error, so the program does not even compile in the first place. (Haskell's strict type system comes in handy here.)
**Edit:** Thanks to Ørjan Johansen and Shelvacu for pointing out a flaws!
[Answer]
# [Python 3](https://docs.python.org/3/), 113 bytes
```
for[]in{113:[]}[open(1,"w").write((lambda s:s%s)('for[]in{113:[]}[open(1,"w").write((lambda s:s%%s)(%r))]:a'))]:a
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/KDo2M6/a0NDYKjq2Njq/IDVPw1BHqVxJU6@8KLMkVUMjJzE3KSVRodiqWLVYU0OdNB0gLapFmpqxVonqYPL/fwA "Python 3 – Try It Online")
### How it works
We can’t easily use multiple statements since the second one could be deleted, so we start with a single-expression quine:
```
print((lambda s:s%s)('print((lambda s:s%%s)(%r))'))
```
To protect it against substring deletions, we use `open(1,"w").write` instead of `print`. In Python 3, `write` returns the number of written characters, which we will verify is `113` to ensure that no part of the string was deleted. We do this by looking up the return value in the dictionary `{113:[]}`, and looping over the result with `for[]in…:a`, which will fail if we didn’t get an empty iterable or if the `for` statement is deleted.
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), ~~204~~ ~~182~~ 189 bytes
```
val()=hd[(fn s=>let val$ =s^"\""^String.toString s^"\"]"val(189,%)=(size$,$)in print%end)"val()=hd[(fn s=>let val$ =s^\"\\\"\"^String.toString s^\"\\\")\"val(189,%)=(size$,$)in print%end)"]
```
[Try it online!](https://tio.run/##K87N0c3NKcnP@/@/LDFHQ9NWIy1PodjWLie1RAEooKhga2wCpFUUbIvjikuKNJIzihQ145DYIF1GxhY6qkCtigraOal56SUZGqkVBTn5Kakqmjoqmpl5CgVFmXklqql5KZpK9LHl/38A "Standard ML (MLton) – Try It Online")
For MLton, full SML programs are either expressions delimited and terminated by `;` (e.g. `print"Hello";print"World";`) or declarations with the `var` and `fun` keywords (e.g. `var _=print"Hello"var _=print"World"`) where `_` is a wild card which could also be replaced by any variable name.
The first option is useless for pristine programming because `;` on its own is a valid program (which does nothing, but doesn't error either). The problem with the second approach is that declarations like `var _=print"Hello"` can be shortened to just `var _="Hello"` (or even `var _=print`) because the declaration with `var` works as long as the right-hand side is a valid SML expression or value (SML is a functional language, so functions can be used as values too).
At this point, I was ready to declare pristine programming in SML impossible, when by chance I stumbled upon *pattern matching* in `val`-declarations. It turns out that the syntax for declarations is not `val <variable_name> = <expression>` but `val <pattern> = <expression>`, where a pattern can consist of variable names, constants and constructors. As the `print` function has type `string -> unit`, we can use a pattern match on the `unit`-value `()` to enforce that the print function is actually applied to the string: `val()=print"Hey"`. With this approach, removing either `print` or `"Hey"` results in a `Pattern and expression disagree`-error.
With this way of pristine printing at hand, the next step is to write a quine, before finally some more save-guarding needs to be added. I previously used an easy SML quine technique (see the [revision history](https://codegolf.stackexchange.com/revisions/140849/4)), but Anders Kaseorg pointed out a different approach which can save some bytes in his case. It uses the built-in `String.toString` function to handle string escaping and is of the general form `<code>"<data>"`, where `"<data>"` is an escaped string of the `code` before:
```
val()=(fn s=>print(s^"\""^String.toString s^"\""))"val()=(fn s=>print(s^\"\\\"\"^String.toString s^\"\\\"\"))"
```
This is a working quine but not yet pristine. First of all Anders Kaseorg found out that MLton accepts a single quote `"` as code without producing errors, which means we cannot have code ending in a quote as above. The shortest way to prevent this would be to wrap everything after `val()=` in a pair of parenthesis, however then the code could be reduced to `val()=()`. The second shortest way I found is to use `val()=hd[ ... ]`, that is we wrap everything into a list and return its first element to make the type checker happy.
To make sure that no part of the data string can be removed without being noticed, the pattern-matching in `val`-declarations comes in handy again: The length of the final string to be printed (and thus the program length) should equal 195, so we can write `let val t=... val 195=size t in print t end` in the body of the `fn` abstraction instead of `print(...)`. Removing a part of the string results in a length less than 189, thus causing a `Bind` exception to be thrown.
There is still an issue left: the whole `val 195=size t` check could simply be dropped. We can prevent this by expanding the check to match on a tuple: `val t=... val(216,u)=(n+size t,t)in print u end`, such that removing the check results in an unbound variable `u`.
Altogether, this yields the following 195 byte solution:
```
val()=hd[(fn s=>let val t=s^"\""^String.toString s^"\")"val(195,u)=(size t,t)in print u end)"val()=hd[(fn s=>let val t=s^\"\\\"\"^String.toString s^\"\\\")\"val(195,u)=(size t,t)in print u end)"]
```
Applying the golfing trick of using operator variable names like `!`, `$` and `%` instead of `n`, `t` and `u` in order to save some white space (see [this tip](https://codegolf.stackexchange.com/a/150560/56433)) leads to the final 182 byte version.
All other substring-removals which where not explicitly stated in the explanation should result in a syntax or type error.
*Edit 1:* `length(explode t)` is just `size t`.
*Edit 2:* Thanks to Anders Kaseorg for a different quine approach and pointing out a "vulnerability".
[Answer]
## Ruby, 78 bytes
```
eval(*[($>.write((s=%{eval(*[($>.write((s=%%{%s})%%s)-78).chr])})%s)-78).chr])
```
I wrote this when I thought of the challenge to make sure it was possible. It uses the same "wrapper" from [one of my answers](https://codegolf.stackexchange.com/a/63625/13400) to the original pristine challenge.
Explanation:
* `eval(*[` *expr* `])`
This evaluates whatever *code* returns as a ruby program. This effectively tests that the string that *code* returns is a valid ruby program. Conveniently, ruby programs can be blank, or only consist of whitespace.
The "splat" operator `*` allows you to use an array as arguments to a function. This also means that if `eval` is removed, the resulting program is `(*[` *expr* `])`, which is not valid ruby.
* `($>.write(` *str* `)-78).chr`
`$>` is a short variable for STDOUT.
`$>.write(foo)` writes foo to STDOUT and, importantly for this code, returns the number of bytes written.
`$>.write(foo)-78`: Here `78` is the length of the program, and so if the program is not mangled, will also be the number of bytes written. Therefor, in the unmangled case, this will return zero.
`num.chr` returns num as a character, eg `0.chr` will return a string containing a single null byte. In the unmangled program, this will give a string with a single null byte to `eval`, which is a valid ruby program that is a no-op.
Also, the program can have a substring removed such that it's just `eval(*[(78).chr])` or `eval(*[(8).chr])`, which means that the numeric constant cannot end with any of the numbers (0, 4, 9, 10, 11, 12, 13, 26, 32, 35, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 64, 95) because they are ascii codes for valid single-character ruby programs.
* `%{` str `}`
This is a lesser-known syntax for string literals in ruby. The reason it's used here is that balanced pairs of `{}` can be used within the string, which means this syntax can contain itself. For example, `%{foo{bar}}` is the same as `"foo{bar}"`.
* `(s=%{` *data* `})%s`
This defines the variable `s` which is the data of this quine, as a printf string.
Assignments in ruby return what was assigned, so this is the same as first assigning `s` and then running `s%s`
`%` on a string is syntatic sugar for ruby's equivalent of sprintf. The `%s` signifies where within the data the data itself should be embedded.
This bit of code defines the data portion of the quine and embeds it within itself to create the full code.
] |
[Question]
[
Here is the 3rd ABACABA city:
```
_
A|_|
B|__|
A|_|_
C|___|
A|_|
B|__|
A|_|
```
It is made out of the [ABACABA](https://codegolf.stackexchange.com/questions/68978/generate-the-abacaba-sequence) sequence, which is basically:
* A (1st iteration)
* place B - AB
* repeat A - ABA (2nd iteration)
* Place C - ABAC
* Repeat ABA - ABACABA (3rd iteration)
and you get the idea.
The buildings have a height (corresponded by no. of underscores) equal to the letters converted to numbers as A = 1, B = 2 e.t.c.
### Input
An iteration number 1<=*n*<=26.
### Output
The ABACABA city of order *n*, including the letters at the start of the lines.
[Answer]
# Python 2, 82 bytes
```
f=lambda n,s=1:n*"'"and" _"*s+f(n-1,0)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1,0)
```
I noticed no one had posted the binary recursion method and decided to give it a shot...and now with a trick borrowed from Sherlock9, it is the shortest python answer! (Also, thanks to xnor for one more shortening.) (And then Dennis who shaved a handful more...)
Ungolfed:
```
def f(n,s=1):
if n>0:
strsofar = " _" if s==1 else "" #prepend overhang for top-level call
strsofar += f(n-1,0) #build the city above the current line
strsofar += "_"*(n-2) #add the overhang to reach the current tower
strsofar += "\n%c|%s|" % (64+n, "_"*n) #write the current (center) line
strsofar += f(n-1,0) #build the city below the current line
return strsofar
else:
return "" #only this line will be executed when n==0 (base case)
print " _"+f(input())
```
[Answer]
## Python 2, 99 bytes
```
b=1;i=2**input(' _\n')-1
while i:i-=1;a=len(bin(i&-i))-2;print'%c|%s|'%(64+b,'_'*b)+'_'*(a+~b);b=a
```
To find the `i`th number of the ABACABA sequence, write `i` in binary, count the number of trailing zeroes, and add one. We use the classic bit trick `i&-i` to find the greatest power of `2` that divides `i`, then compute bit length. Actually, we count `i` down from `2**n-1` to `0`, which is fine because the ABACABA sequence is symmetric.
We track both the current and last number of the sequence with the help of a "previous" variable `b`. This tells us how many underscores to print as the "overhang". The final building is drawn correctly without overhang because `0` is treated as have bit length `1`.
The string format for printing is [taken from Sp3000](https://codegolf.stackexchange.com/a/76306/20260), as is the trick of using the `input` to print the first line.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 59 bytes
```
vi:"t@wv]!-1hPXJtPvX>"'|'@Z"63+h6MJ2+X@)(]XhcJ64+!wh!32H:(!
```
This uses [current release (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language.
[**Try it online!**](http://matl.tryitonline.net/#code=dmk6InRAd3ZdIS0xaFBYSnRQdlg-Iid8J0BaIjYzK2g2TUoyK1hAKShdWGhjSjY0KyF3aCEzMkg6KCE&input=NQ)
---
(If the letters didn't have to be included in the output: the following would work, 48 bytes):
```
vi:"t@wv]!-1hPXJtPvX>"' |'X@1=o)@Z"63+h6MJ2+X@)(
```
### Explanation
```
v % vertically concatenate the stack contents: gives an empty array
i: % input number n. Generate [1,2,...,n]
" % for each k in [1,2,...n]
t % duplicate
@ % push k
wv % swap, vertically concatenate
] % end. Poduces the numeric ABACABA: [1 2 1 3 1 2 1]: ceiling heights
! % transpose into a row
-1h % append -1
PXJ % reverse array. Copy into clipboard J
tP % duplicate. Reverse again, so undo the reversing
v % vertically concatenate reversed and non-reversed row arrays
X> % max of each column. Gives array of wall heights: [1 2 2 3 3 2 2 1]
" % for each value in that array
'|' % push "floor" char
@ % push height
Z" % create string with that many spaces
63+ % transform spaces into "wall" chars, '_'
h % concatenate horizontally
6M % push "floor" char '|' again, to be used as ceiling
J % push array of ceiling heights
2+X@) % index into that to get height of current building
( % at that position, overwrite the string with '|'
] % end
Xhc % concatenate all strings into a 2D char array, padding with spaces
J % push array of ceiling heights (numeric ABACABA sequence)
64+ % add 64 to transform into letters
! % transpose into column array
wh % swap, concatenate horizontally. This appends letters below the floor
! % transpose
32H:( % overwrite first two positions (in linear order) with spaces
! % transpose back. Implicitly display
```
[Answer]
# CJam, ~~37~~ 35 bytes
```
SS'_Lri{[H)'_*_2>N@H'A+'|@'|6$]+}fH
```
This is an iterative implementation of the recursive algorithm from [@quintopia's answer](https://codegolf.stackexchange.com/a/76482).
[Try it online!](http://cjam.tryitonline.net/#code=U1MnX0xyaXtbSCknXypfMj5OQEgnQSsnfEAnfDYkXSt9Zkg&input=Mw)
### How it works
```
SS'_ e# Push two spaces and an underscore.
L e# Push "".
ri e# Read an integer I from STDIN.
{ e# For each H in [0 ... I-1]:
[ e# Set an array marker.
H) e# Push Push H+1.
'_* e# Push a string of that many underscores.
_2> e# Push a copy and remove the first two underscores.
N e# Push a linefeed.
@ e# Rotate the longer string of underscores on top of it.
h'A+ e# Add H to the character 'A', pushing the corresponding letter.
'| e# Push a vertical bar.
@ e# Rotate the string of underscores on top of it.
'| e# Push another vertical bar.
6$ e# Push a copy of the previous iteration (initially "").
] e# Wrap everything up to the former marker in an array.
}fH e#
```
[Answer]
## JavaScript (ES6), 162 bytes
```
n=>(a=[...Array(1<<n)]).map((_,i)=>i?(a[i]=String.fromCharCode(64+(n=1+Math.log2(i&-i)))+`|${"_".repeat(n)}|`,a[i-1]+='_'.repeat(--n&&--n)):a[i]=' _')&&a.join`\n`
```
Where `\n` is the literal newline character.
[Answer]
## Python 2, ~~123~~ 121 bytes
```
f=lambda n:n*[n]and f(n-1)+[n]+f(n-1)
L=f(input(' _\n'))
for i,j in zip(L,L[1:]+L):print'%c|%s|'%(64+i,'_'*i)+'_'*(j+~i)
```
[ideone link](http://ideone.com/kUMAb4) *(-2 bytes thanks to @xsot)*
`f` generates the ABACABA sequence as a list of numbers, e.g. `f(3) = [1, 2, 1, 3, 1, 2, 1]`. The offset of the input by 1 compared to the [ABACABA sequence challenge](https://codegolf.stackexchange.com/questions/68978/generate-the-abacaba-sequence) lets us golf off a byte in `f`.
The first line is printed separately, after which all other lines are printed using an expression which takes into account the current number and the next number. Just for fun, the first line is printed using `input()`.
[Answer]
# Pyth - 64 62 bytes
Probably could be golfed more, but good enough for now.
```
Lsl.&Jhb_J" _"Vtt^2Qpr@G=ZyN1p"|_"p*\_Zp\|W<=hZyhNp\_)d)"A|_|
```
[Try it here!](http://pyth.herokuapp.com/?code=Lsl.%26Jhb_J%22++_%22Vtt%5E2Qpr%40G%3DZyN1p%22%7C_%22p%2a%5C_Zp%5C%7CW%3C%3DhZyhNp%5C_%29k%29%22A%7C_%7C&input=4&debug=0)
Explanation:
```
|Predefined vars: Q = evaluated input, G = lowercase alphabet
L |Lambda definition. y(b) = return (following code)
.& |bitwise and
Jhb |J = b + 1, pass b + 1 to the bitwise and
_J |-J
l | base 2
s |̲c̲o̲n̲v̲e̲r̲t̲ ̲t̲o̲ ̲i̲n̲t̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
" _" |print " _" with a trailing newline
Vtt^2Q |For N in 2^Q - 2
pr 1 |print in caps
=ZyN |Z = y(N) remember the first lambda?
@G |G[Z], basically convert 1-26 to A-Z
p"|_" |print "|_", no trailing newline
p*\_Z |print "_" Z times
p\| |̲p̲r̲i̲n̲t̲ ̲"̲|̲"̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
W<=hZyhN |While ++Z<y(N+1)
p\_ |print "_"
)k |end while,
|print newline
)"A|_| |end for,
|print "A|_|"
```
[Answer]
# Python 3.5 - 262 236 220 bytes:
-16 bytes thanks to @CatsAreFluffy! My entire function can now finally be in a single line! :)
```
from collections import*
def a(v):o=OrderedDict;j=[chr(i+97)for i in range(26)];d=o((j[i],(' '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26));f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1);[print(d[g])for g in f(v)]
```
It may be a bit long, and it may print new lines in between building, but in does what it needs to. You can test it out yourself to confirm it.
**EDIT:**
My previous golfed code did not print the right pattern whatsoever. However, now the one shown above does, and it does it good in my opinion. You can also run it for yourself to confirm that.
**Note:** The program prints all lowercase letters behind every "building". I hope that's okay.
# Ungolfed version with Explanation:
```
from collections import*
def a(v):
o=OrderedDict # Assign the OrderedSict function to "o"
j=[chr(i+97)for i in range(26)] # Create a list with all 26 lowercase letters of the alphabet
d=o((j[i],(' '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26)) # Create a dict assigning each letter it's corresponding building with its corresponding length
f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1) # Return the ABACABA sequence based on the user input
[print(d[g])for g in f(v)] # Print out the building according to the sequence returned by the above lambda function (thanks to @CatsAreFluffy for this method to print it! :) )
```
Basically what I am doing is first importing the collections module's Ordered Dictionary function, and then creating an ordered dictionary, with each lower case letter in the list "j" being assigned to its corresponding building, with its corresponding length in underscores. Then I compute the sequence, based on the user's input, using the `f=lambda w:"a"[w:]or f(w-1)+j[w]+f(w-1)` function, and then based on the sequence returned by that, the buildings, with each's corresponding letter behind it, are printed out.
[Answer]
# Ruby, 129 bytes
Anonymous function, returns a multiline string.
```
->x{a=->n{n<1?[]:(b=a[n-1];b+[n]+b)}
r=" _
"
a[x].zip(a[x][1,9**x]<<0).map{|n,m|r+=(64+n).chr+"|#{?_*n}|#{?_*(m+~n)if m>n}
"}
r}
```
[Answer]
# JavaScript (ES6), 143
There are 2 newline inside the backticks that are significant and counted.
```
n=>` _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`
```
... or 138 if the letters can be lowercase.
```
n=>` _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>(x+9).toString(36)+u(x)+u(t[i+1]-x-1)).join`
```
**Less golfed**
```
n=>{
// recursive function for ABACABA returning an array of integers
var r=n=>n?[...r(n-1),n,...r(n-1)]:[]
// function to build "|__..."
// if argument <=0 just returns the vertical bar
var u=n=>'|'+'_'.repeat(n>0&&n)
var t = r(n)
t = t.map((x,i)=>
// current building + extension to the len of next building if needed
String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)
)
return ' _\n' // the top line is fixed
+ t.join('\n')
}
```
**Test**
```
solution=
n=>` _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`
function update() {
var n=+N.value
if (n>=0 && n<=26) O.textContent=solution(n)
}
update()
```
```
#N { width: 2em }
```
```
N:<input id=N value=4 oninput='update()'><pre id=O></pre>
```
[Answer]
# Powershell, 67 Bytes
```
1..(Read-Host)|%{' _'}{$x+=@([char]($_+96)+'|'+'_'*$_+'|')+$x}{$x}
```
] |
[Question]
[
The [winding number](https://en.wikipedia.org/wiki/Winding_number) is the integer number of net counterclockwise revolutions an observer must have made to follow a given closed path. Note that any clockwise revolutions count negative towards the winding number. The path is allowed to self intersect.
Some examples (shamelessly taken from Wikipedia) are given below:
[](https://i.stack.imgur.com/Ozurm.png)
Your goal is to compute the winding number for a given path.
# Input
The observer is assumed be at the origin `(0,0)`.
The input is a finite sequence of points (pair-like of integer numbers) from any desired input source which describes the piece-wise linear path. You may flatten this into a 1D sequence of integer numbers if desired, and may also swizzle the input to take all x coordinates before all y coordinates/vise-versa. You may also take the input as a complex number `a+b i`. The path may self intersect and may contain zero-length segments. The first point is the start of the path and is assumed to lie somewhere on the positive x axis.
No part of the path will intersect the origin. The path will always be closed (i.e. the first and lost point are the same). Your code may either imply the last point or require it to be included.
For example, depending on your preference both inputs specify the same square:
**implied end point**
```
1,0
1,1
-1,1
-1,-1
1,-1
```
**explicit end point**
```
1,0
1,1
-1,1
-1,-1
1,-1
1,0
```
# Output
The output is a single integer for the winding number. This may be to any source (return value, stdout, file, etc.).
# Examples
All examples have the end point explicitly defined and are given as x,y pairs. Incidentally, you should be able to also directly feed these examples into any codes assuming implicitly defined end points and the outputs should be the same.
**1. Basic test**
```
1,0
1,1
-1,1
-1,-1
1,-1
1,0
```
**Output**
```
1
```
**2. Repeated point test**
```
1,0
1,0
1,1
1,1
-1,1
-1,1
-1,-1
-1,-1
1,-1
1,-1
1,0
```
**Output**
```
1
```
**3. Clockwise test**
```
1,0
1,-1
-1,-1
-1,1
1,1
1,0
```
**Output**
```
-1
```
**4. Outside test**
```
1,0
1,1
2,1
1,0
```
**Output**
```
0
```
**5. Mixed winding**
```
1,0
1,1
-1,1
-1,-1
1,-1
1,0
1,-1
-1,-1
-1,1
1,1
1,0
1,1
-1,1
-1,-1
1,-1
1,0
1,1
-1,1
-1,-1
1,-1
1,0
```
**Output**
```
2
```
# Scoring
This is code golf; shortest code wins. Standard loopholes apply. You may use any builtin functions so long as they were not specifically designed to compute the winding number.
[Answer]
## ES6, 83 bytes
```
a=>a.map(([x,y])=>r+=Math.atan2(y*b-x*c,y*c+x*b,b=x,c=y),b=c=r=0)&&r/Math.PI/2
```
Takes as input an array of pairs of points which are interpreted as complex numbers. Rather than converting each point into an angle, the points are divided by the previous point, which Math.atan2 then converts into an angle between -π and π, thus automatically determining which way the path is winding. The sum of the angles is then 2π times the winding number.
Since Math.atan2 doesn't care about the scale of its arguments I don't actually perform the full division `z / w = (z * w*) / (w * w*)` instead I just multiply each point by the complex conjugate of the previous point.
Edit: Saved 4 bytes thanks to @edc65.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 bytes
```
X/Z/0)2/YP/
```
Input is a sequence of complex numbers including the end point.
[**Try it online!**](http://matl.tryitonline.net/#code=WC9aLzApMi9ZUC8&input=WzErMGkgMSsxaSAtMSsxaSAtMS0xaSAxLTFpIDErMGkgMS0xaSAtMS0xaSAtMSsxaSAxKzFpIDErMGkgMSsxaSAtMSsxaSAtMS0xaSAxLTFpIDErMGkgMSsxaSAtMSsxaSAtMS0xaSAxLTFpIDErMGld)
### Explanation
Most of the work is done by the `Z/` function (`unwrap`), which unwraps angles in radians by changing absolute jumps greater than or equal to pi to their 2\*pi complement.
```
X/ % compute angle of each complex number
Z/ % unwrap angles
0) % pick last value. Total change of angle will be a multiple of 2*pi because
% the path is closed. Total change of angle coincides with last unwrapped
% angle because the first angle is always 0
2/ % divide by 2
YP/ % divide by pi
```
[Answer]
## Jelly, 11 bytes
```
æAI÷ØPæ%1SH
```
This takes input as a list of y-coordinates and a list of x-coordinates.
Try it [here](http://jelly.tryitonline.net/#code=w6ZBScO3w5hQw6YlMVNI&input=&args=WzAsIDEsIDEsIC0xLCAtMSwgMCwgLTEsIC0xLCAxLCAxLCAwLCAxLCAxLCAtMSwgLTEsIDAsIDEsIDEsIC0xLCAtMSwgMF0+WzEsIDEsIC0xLCAtMSwgMSwgMSwgMSwgLTEsIC0xLCAxLCAxLCAxLCAtMSwgLTEsIDEsIDEsIDEsIC0xLCAtMSwgMSwgMV0).
[Answer]
# Python, 111
Longest answer so far. My motivations are 1) learn python and 2) possibly port this to pyth.
```
from cmath import *
q=input()
print reduce(lambda x,y:x+y,map(lambda (x,y):phase(x/y)/pi/2,zip(q[1:]+q[:1],q)))
```
Input is given as a list of complex numbers.
[Ideone.](https://ideone.com/gum8zk)
I think the approach is similar to the ES6 answer.
When 2 complex numbers are multiplied, the argument or phase of the product is the sum of the argument or phase of the two numbers. Thus when a complex number is divided by another, then the phase of the quotient is the difference between the phases of the numerator and denominator. Thus we can calculate the angle traversed through for each point and the next point. Sum these angles and divide by 2π gives the required winding number.
] |
[Question]
[

You are given, as a list or vector or whatever, a bunch of 3-tuples or whatever, where the first two things are strings, and the third thing is a number. The strings are cities, and the number is the distance between them. The order of the cities in the tuple is arbitrary (i.e. it doesn't matter which comes first and which comes second) since it is the same distance each way. Also, there is exactly one tuple for each pair of connected cites. Not all cities may be connected. Also, the distance is always positive (not `0`). You do not need to check these conditions, you may assume input will be well formed. Your job is to return the cities in a cyclic sequence, such that, if you start at any one city, and go around the sequence back to the same city, the total of the distances between the cities will be minimum (exactly and in all cases.) You may assume a solution exists. For example, let us say you are given
```
[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]
```
You could output any of the following (but you only need to output one):
```
["Detroit","Hong Kong","Dillsburg","New York"]
["Hong Kong","Dillsburg","New York","Detroit"]
["Dillsburg","New York","Detroit","Hong Kong"]
["New York","Detroit","Hong Kong","Dillsburg"]
["Dillsburg","Hong Kong","Detroit","New York"]
["New York","Dillsburg","Hong Kong","Detroit"]
["Detroit","New York","Dillsburg","Hong Kong"]
["Hong Kong","Detroit","New York","Dillsburg"]
```
because it is the shortest trip: 13.9
but not
```
["Dillburg","Detroit","New York","Hong Kong"]
```
because it is not the shortest.
See [en.wikipedia.org/wiki/Travelling\_salesman\_problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem)
**Scoring**
This is where it gets interesting. You take the number of characters you have, and then plug them into the bare worst case O-notation formula. For example, let us say you write a brute force program that is 42 characters. As we all know, the worst case is `n!` where `n` is the number of cities. 42!=1405006117752879898543142606244511569936384000000000, so that is your score. The **lowest score wins**.
Note: I relieved this afterwards too, but wasn't sure how to solve it and hoped that no one would notice. People did, so I will go with issacg's suggestion:
>
> the only options are O(n!) and O(b^n*n^a*ln(n)^k), and all bounds must
> be as tight as possible given that notation
>
>
>
[Answer]
# Haskell, 259
I thought I would be able to get it shorter. maybe I will.
this has time complexity of O(n^2\*2^n)\* so score is about 6.2e82
\*i'm not actually sure, but if there is any "addition" to the complexity it's not more than polynomial, so this shouldn't change the score much.
```
import Data.List
g e=tail$snd$minimum[r|r@(_,b)<-iterate(\l->nubBy((.f).(==).f)$sort[(b+d,c:a)|(b,a)<-l,c<-h\\init a,d<-a!!0%c])[(0,[h!!0])]!!length h,b!!0==h!!0]where h=sort$nub$e>>= \(a,b,_)->[a,b];a%b=[z|(x,y,z)<-e,x==a&&y==b||x==b&&y==a]
f(_,x:b)=x:sort b
```
[Answer]
# Python 2, 237 231 228 225 characters
Since this is a naive algorithm, its score is probably about 225! ≈ 1.26e433.
```
from itertools import*
a=input()
n=lambda*a:tuple(sorted(a))
d=dict((n(*x[:2]),x[2])for x in a)
print min(permutations(set(chain(*[x[:2]for x in a]))),key=lambda x:sum(d.get(n(x[i],x[i+1]),1e400)for i in range(-1,len(x)-1)))
```
[Answer]
# Julia, 213 chars
Probably goes like `n!n`, so ~2e407.
```
a=[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]
f(a)=(
d(x,y)=(r=filter(z->x in z&&y in z,a);r==[]?Inf:r[1][3]);
m=Inf;
q=0;
c=unique([[z[1] for z=a],[z[2] for z=a]]);
n=length(c);
for p=permutations(c);
x=sum([d(p[i],p[mod1(i+1,n)]) for i=1:n]);
x<m&&(m=x;q=p);
end;
q)
f(a)
```
For readability and to demonstrate use I left in some unscored newlines and tabs as well as example input and a call to the function. Also I used an algorithm that requires `n!` time, but not `n!` memory, its slightly more feasible to run.
[Answer]
# Python 3 - 491
I did not count the length of the input graph variable `g`. This solution uses dynamic programming, and has a complexity of n^2 \* 2^n, for a total score of ~6.39e147. I am still pretty new to golfing, so please chime in if you see a big waste of code somewhere!
```
g=[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]
s=''
c={s:1}
D={}
for t in g:c[t[0]]=1;c[t[1]]=1;D[(t[0],t[1])]=t[2];D[(t[1],t[0])]=t[2];D[('',t[0])]=0;D['',t[1]]=0
V={}
y=[x for x in c.keys() if x!='']
f=''
def n(z,p):
if(len(p)==len(y)-1):
global f;f=z
if(0==len(p)):
return (D[(z,f)] if (z,f) in D else float('inf'))
Y=[(float('inf'),'')]
for P in p:
if((z,P) in D):
Y.append((D[(z,P)] + n(P,[m for m in p if m!=P]), P))
V[(z,tuple(p))]=min(Y)
return min(Y)[0]
n('',y)
for i in range(len(c)-1):
N=V[(s,tuple(y))][1]
print(N)
s=N
y.remove(N)
```
[Answer]
## Mathematica, 66 bytes
```
Most@Last@FindShortestTour@Graph[#<->#2&@@@#,EdgeWeight->Last/@#]&
```
No idea on the complexity, so the score is somewhere between `10^23` and `10^93`.
[Answer]
# Ruby, ~~198~~ 180 bytes
```
G=eval(gets.tr("()","[]"))
C=G.map{|t|[t[0],t[1]]}.flatten.uniq
D=Hash.new(+1.0/0)
G.map{|p|D[[p[0],p[1]]]=D[[p[1],p[0]]]=p[2]}
p C.permutation.map{|l|d=0;p=l[-1];l.map{|c|d+=D[[p,c]];p=c};[d,l]}.sort[0][1]
```
The first line that reads the input is unscored, as that seems to be what everyone else is doing. Also, there is no final newline needed for ruby.
It just dumbly generates all permutations of cities, so put me down for `O(n!*n)`. Actually, on second thoughts, it's slower even than that, because it sorts all `O(n!)` paths rather than keeping track of the best so far.
] |
[Question]
[
This is [a challenge on the internet asked by Palantir Technologies in their interviews](http://www.careercup.com/page?pid=palantir-technology-interview-questions).
>
> A group of farmers has some elevation data, and we’re going to help
> them understand how rainfall flows over their farmland. We’ll
> represent the land as a two-dimensional array of altitudes and use the
> following model, based on the idea that water flows downhill:
>
>
> If a cell’s four neighboring cells all have higher altitudes, we call
> this cell a sink; water collects in sinks. Otherwise, water will flow
> to the neighboring cell with the lowest altitude. If a cell is not a
> sink, you may assume it has a unique lowest neighbor and that this
> neighbor will be lower than the cell.
>
>
> Cells that drain into the same sink – directly or indirectly – are
> said to be part of the same basin.
>
>
> Your challenge is to partition the map into basins. In particular,
> given a map of elevations, your code should partition the map into
> basins and output the sizes of the basins, in descending order.
>
>
> Assume the elevation maps are square. Input will begin with a line
> with one integer, S, the height (and width) of the map. The next S
> lines will each contain a row of the map, each with S integers – the
> elevations of the S cells in the row. Some farmers have small land
> plots such as the examples below, while some have larger plots.
> However, in no case will a farmer have a plot of land larger than S =
> 5000.
>
>
> Your code should output a space-separated list of the basin sizes, in
> descending order. (Trailing spaces are ignored.)
>
>
> A few examples are below.
>
>
> Input:
>
>
>
```
3
1 5 2
2 4 7
3 6 9
```
>
> Output: `7 2`
>
>
> The basins, labeled with A’s and B’s, are:
>
>
>
```
A A B
A A B
A A A
```
>
> Input:
>
>
>
```
1
10
```
>
> Output: `1`
>
>
> There is only one basin in this case.
>
>
> Input:
>
>
>
```
5
1 0 2 5 8
2 3 4 7 9
3 5 7 8 9
1 2 5 4 2
3 3 5 2 1
```
>
> Output: `11 7 7`
>
>
> The basins, labeled with A’s, B’s, and C’s, are:
>
>
>
```
A A A A A
A A A A A
B B A C C
B B B C C
B B C C C
```
>
> Input:
>
>
>
```
4
0 2 1 3
2 1 0 4
3 3 3 3
5 5 2 1
```
>
> Output: `7 5 4`
>
>
> The basins, labeled with A’s, B’s, and C’s, are:
>
>
>
```
A A B B
A B B B
A B B C
A C C C
```
[Answer]
**Mathematica**
The basin size list can be gotten by
```
WatershedComponents[
Image[Rest@ImportString[m,"Table"]] // ImageAdjust,
CornerNeighbors -> False,
Method -> "Basins"
] // Reverse@Sort@Part[Tally[Flatten@#], All, 2] &
```
where `m` is the given input data. To display a matrix like the ones in the question one can replace `// Reverse@Sort@Part[Tally[Flatten@#], All, 2] &` with `/. {1 -> "A", 2 -> "B", 3 -> "C"} // MatrixForm` or one can display it as an image instead using `//ImageAdjust//Image`.
[Answer]
### JavaScript - 673 ~~707 ~~730~~ 751~~
`e=[],g=[],h=[],m=[],q=[];function r(){a=s,b=t;function d(d,A){n=a+d,p=b+A;c>e[n][p]&&(u=!1,v>e[n][p]&&(v=e[n][p],w=n,k=p))}c=e[a][b],u=!0,v=c,w=a,k=b;0!=a&&d(-1,0);a!=l&&d(1,0);0!=b&&d(0,-1);b!=l&&d(0,1);g[a][b]=w;h[a][b]=k;return u}function x(a,b,d){function c(a,b,c,k){g[a+b][c+k]==a&&h[a+b][c+k]==c&&(d=x(a+b,c+k,d))}d++;0!=a&&c(a,-1,b,0);a!=l&&c(a,1,b,0);0!=b&&c(a,0,b,-1);b!=l&&c(a,0,b,1);return d}y=$EXEC('cat "'+$ARG[0]+'"').split("\n");l=y[0]-1;for(z=-1;z++<l;)e[z]=y[z+1].split(" "),g[z]=[],h[z]=[];for(s=-1;s++<l;)for(t=-1;t++<l;)r()&&m.push([s,t]);for(z=m.length-1;0<=z;--z)s=m[z][0],t=m[z][1],q.push(x(s,t,0));print(q.sort(function(a,b){return b-a}).join(" "));`
Test results (using Nashorn):
```
$ for i in A B C D; do jjs -scripting minlm.js -- "test$i"; done
7 2
1
11 7 7
7 5 4
$
```
There would probably be stack problems for maps of size 5000 (but that's an implementation detail :).
The unminified source in all it's fugliness:
```
// lm.js - find the local minima
// Globalization of variables.
/*
The map is a 2 dimensional array. Indices for the elements map as:
[0,0] ... [0,n]
...
[n,0] ... [n,n]
Each element of the array is a structure. The structure for each element is:
Item Purpose Range Comment
---- ------- ----- -------
h Height of cell integers
s Is it a sink? boolean
x X of downhill cell (0..maxIndex) if s is true, x&y point to self
y Y of downhill cell (0..maxIndex)
Debugging only:
b Basin name ('A'..'A'+# of basins)
Use a separate array-of-arrays for each structure item. The index range is
0..maxIndex.
*/
var height = [];
var sink = [];
var downhillX = [];
var downhillY = [];
//var basin = [];
var maxIndex;
// A list of sinks in the map. Each element is an array of [ x, y ], where
// both x & y are in the range 0..maxIndex.
var basinList = [];
// An unordered list of basin sizes.
var basinSize = [];
// Functions.
function isSink(x,y) {
var myHeight = height[x][y];
var imaSink = true;
var bestDownhillHeight = myHeight;
var bestDownhillX = x;
var bestDownhillY = y;
/*
Visit the neighbors. If this cell is the lowest, then it's the
sink. If not, find the steepest downhill direction.
This would be the place to test the assumption that "If a cell
is not a sink, you may assume it has a unique lowest neighbor and
that this neighbor will be lower than the cell." But right now, we'll
take that on faith.
*/
function visit(deltaX,deltaY) {
var neighborX = x+deltaX;
var neighborY = y+deltaY;
if (myHeight > height[neighborX][neighborY]) {
imaSink = false;
if (bestDownhillHeight > height[neighborX][neighborY]) {
bestDownhillHeight = height[neighborX][neighborY];
bestDownhillX = neighborX;
bestDownhillY = neighborY;
}
}
}
if (x !== 0) {
// upwards neighbor exists
visit(-1,0);
}
if (x !== maxIndex) {
// downwards neighbor exists
visit(1,0);
}
if (y !== 0) {
// left-hand neighbor exists
visit(0,-1);
}
if (y !== maxIndex) {
// right-hand neighbor exists
visit(0,1);
}
downhillX[x][y] = bestDownhillX;
downhillY[x][y] = bestDownhillY;
return imaSink;
}
function exploreBasin(x,y,currentSize) {//,basinName) {
// This cell is in the basin.
//basin[x][y] = basinName;
currentSize++;
/*
Visit all neighbors that have this cell as the best downhill
path and add them to the basin.
*/
function visit(x,deltaX,y,deltaY) {
if ((downhillX[x+deltaX][y+deltaY] === x) && (downhillY[x+deltaX][y+deltaY] === y)) {
currentSize = exploreBasin(x+deltaX,y+deltaY,currentSize); //,basinName);
}
return 0;
}
if (x !== 0) {
// upwards neighbor exists
visit(x,-1,y,0);
}
if (x !== maxIndex) {
// downwards neighbor exists
visit(x,1,y,0);
}
if (y !== 0) {
// left-hand neighbor exists
visit(x,0,y,-1);
}
if (y !== maxIndex) {
// right-hand neighbor exists
visit(x,0,y,1);
}
return currentSize;
}
// Read map from file (1st argument).
var lines = $EXEC('cat "' + $ARG[0] + '"').split('\n');
maxIndex = lines.shift() - 1;
for (var i = 0; i<=maxIndex; i++) {
height[i] = lines.shift().split(' ');
// Create all other 2D arrays.
sink[i] = [];
downhillX[i] = [];
downhillY[i] = [];
//basin[i] = [];
}
// Everyone decides if they are a sink. Create list of sinks (i.e. roots).
for (var x=0; x<=maxIndex; x++) {
for (var y=0; y<=maxIndex; y++) {
if (sink[x][y] = isSink(x,y)) {
// This node is a root (AKA sink).
basinList.push([x,y]);
}
}
}
//for (var i = 0; i<=maxIndex; i++) { print(sink[i]); }
// Each root explores it's basin.
//var basinName = 'A';
for (var i=basinList.length-1; i>=0; --i) { // i-- makes Closure Compiler sad
var x = basinList[i][0];
var y = basinList[i][1];
basinSize.push(exploreBasin(x,y,0)); //,basinName));
//basinName = String.fromCharCode(basinName.charCodeAt() + 1);
}
//for (var i = 0; i<=maxIndex; i++) { print(basin[i]); }
// Done.
print(basinSize.sort(function(a, b){return b-a}).join(' '));
```
I got better minimization results by breaking up the element objects into separate arrays, globalizing everywhere possible and embracing side-effects. NSFW.
The effects of code minimization:
* 4537 bytes, unminified
* 1180 bytes, [packer](http://dean.edwards.name/packer/)
* 855 bytes, packer + hand optimizations (1 character global names)
* 751 bytes, Google Closure Compiler with ADVANCED\_OPTIMIZATIONS (NB, it elided a vestigial "return 0" as dead code)
* 730 bytes, reckless hand optimization (I'm not changing the unminified source, so NSFW)
* 707 bytes, more reckless hand optimization (remove all references to sink[]);
* 673 bytes, remove all "var"s, drop Nashorn -strict flag
I could have achieved close to 700 bytes without editing the minimized code if I'd been willing to modify the original source. But I didn't because I think leaving it as-is gives an interesting view from the starting point.
[Answer]
### Python: 276 306 365 bytes
This is my first golf attempt. Suggestions are appreciated!
*edit:* imports and closing files take too many characters! So does storing files in variables and nested list comprehension.
```
t=map(int,open('a').read().split());n=t.pop(0);q=n*n;r,b,u=range(q),[1]*q,1
while u!=0:
u=0
for j in r:
d=min((t[x],x)for x in [j,j-1,j+1,j-n,j+n]if int(abs(j/n-x/n))+abs(j%n-x%n)<=1 and x in r)[1]
if j-d:u|=b[j];b[d]+=b[j];b[j]=0
for x in sorted(b)[::-1]:print x or '',
```
**fully commented (2130 bytes...)**
```
from math import floor
with open('a') as f:
l = f.read()
terrain = map(int,l.split()) # read in all the numbers into an array (treating the 2D array as flattened 1D)
n = terrain.pop(0) # pop the first value: the size of the input
valid_indices = range(n*n) # 0..(n*n)-1 are the valid indices of this grid
water=[1]*(n*n) # start with 1 unit of water at each grid space. it will trickle down and sum in the basins.
updates=1 # keep track of whether each iteration included an update
# helper functions
def dist(i,j):
# returns the manhattan (L1) distance between two indices
row_dist = abs(floor(j/n) - floor(i/n))
col_dist = abs(j % n - i % n)
return row_dist + col_dist
def neighbors(j):
# returns j plus up to 4 valid neighbor indices
possible = [j,j-1,j+1,j-n,j+n]
# validity criteria: neighbor must be in valid_indices, and it must be one space away from j
return [x for x in possible if dist(x,j)<=1 and x in valid_indices]
def down(j):
# returns j iff j is a sink, otherwise the minimum neighbor of j
# (works by constructing tuples of (value, index) which are min'd
# by their value, then the [1] at the end returns its index)
return min((terrain[i],i) for i in neighbors(j))[1]
while updates!=0: # break when there are no further updates
updates=0 # reset the update count for this iteration
for j in valid_indices: # for each grid space, shift its water
d =down(j)
if j!=d: # only do flow if j is not a sink
updates += water[j] # count update (water[j] is zero for all non-sinks when the sinks are full!)
water[d] += water[j] # move all of j's water into the next lowest spot
water[j] = 0 # indicate that all water has flown out of j
# at this point, `water` is zeros everywhere but the sinks.
# the sinks have a value equal to the size of their watershed.
# so, sorting `water` and printing nonzero answers gives us the result we want!
water = sorted(water)[::-1] # [::-1] reverses the array (high to low)
nonzero_water = [w for w in water if w] # 0 evaulates to false.
print " ".join([str(w) for w in nonzero_water]) # format as a space-separated list
```
[Answer]
# JavaScript (ECMAScript 6) - 226 Characters
```
s=S.split(/\s/);n=s.shift(k=[]);u=k.a;t=s.map((v,i)=>[v,i,1]);t.slice().sort(X=(a,b)=>a[0]-b[0]).reverse().map(v=>{i=v[1];p=[v,i%n?t[i-1]:u,t[i-n],(i+1)%n?t[i+1]:u,t[+n+i]].sort(X)[0];p==v?k.push(v[2]):p[2]+=v[2]});k.join(' ')
```
**Explanation**
```
s=S.split(/\s/); // split S into an array using whitespace as the boundary.
n=s.shift(); // remove the grid size from s and put it into n.
k=[]; // an empty array to hold the position of the sinks.
u=k.a; // An undefined variable
t=s.map((v,i)=>[v,i,1]); // map s to an array of:
// - the elevation
// - the position of this grid square
// - the number of grid squares which have flowed into
// this grid square (initially 1).
X=(a,b)=>a[0]-b[0]; // A comparator function for sorting.
t.slice() // Take a copy of t
.sort(X) // Then sort it by ascending elevation
.reverse() // Reverse it to be sorted in descending order
.map(v=>{ // For each grid square (starting with highest elevation)
i=v[1]; // Get the position within the grid
p=[v,i%n?t[i-1]:u,t[i-n],(i+1)%n?t[i+1]:u,t[+n+i]]
// Create an array of the grid square and 4 adjacent
// squares (or undefined if off the edge of the grid)
.sort(X) // Then sort by ascending elevation
[0]; // Then get the square with the lowest elevation.
p==v // If the current grid square has the lowest elevation
?k.push(v[2]) // Then add the number of grid square which have
// flowed into it to k
:p[2]+=v[2]}); // Else flow the current grid square into its lowest
// neighbour.
k.join(' ') // Output the sizes of the block with space separation.
```
# Previous Version - 286 Characters
```
s=S.split(/\s/);n=s.shift()*1;k=[];u=k[1];t=s.map((v,i)=>({v:v,p:i,o:[]}));for(i in t){t[p=[t[i],i%n?t[i-1]:u,t[i-n],(+i+1)%n?t[+i+1]:u,t[+i+n]].sort((a,b)=>(a.v-b.v))[0].p].o.push([i]);p==i&&k.push([i])}k.map(x=>{while(x[L="length"]<(x=[].concat(...x.map(y=>t[y].o)))[L]);return x[L]})
```
Assumes that the input is in a variable `S`;
**Explanation**
```
s=S.split(/\s/); // split S into an array using whitespace as the boundary.
n=s.shift()*1; // remove the grid size from s and put it into n.
k=[]; // an empty array to hold the position of the sinks.
u=k[1]; // Undefined
t=s.map((v,i)=>({v:v,p:i,o:[]})); // map s to an Object with attributes:
// - v: the elevation
// - p: the position of this grid square
// - o: an array of positions of neighbours which
// flow into this grid square.
for(i in t){ // for each grid square
p=[t[i],i%n?t[i-1]:u,t[i-n],(+i+1)%n?t[+i+1]:u,t[+i+n]]
// start with an array containing the objects
// representing that grid square and its 4 neighbours
// (or undefined for those neighbours which are
// outside the grid)
.sort((a,b)=>(a.v-b.v)) // then sort that array in ascending order of elevation
[0].p // then get the first array element (with lowest
// elevation) and get the position of that grid square.
t[p].o.push([i]); // Add the position of the current grid square to the
// array of neighbours which flow into the grid square
// we've just found.
p==i&&k.push([i]) // Finally, if the two positions are identical then
// we've found a sink so add it to the array of sinks (k)
}
k.map(x=>{ // For each sink start with an array, x, containing the
// position of the sink.
while(x.length<(x=[].concat(...x.map(y=>t[y].o))).length);
// Compare x to the concatenation of x with all the
// positions of grid squares which flow into squares
// in x and loop until it stops growing.
return x.length // Then return the number of grid squares.
})
```
**Test**
```
S="3\n1 5 2\n2 4 7\n3 6 9";
s=S.split(/\s/);n=s.shift()*1;k=[];u=k[1];t=s.map((v,i)=>({v:v,p:i,o:[]}));for(i in t){t[p=[t[i],i%n?t[i-1]:u,t[i-n],(+i+1)%n?t[+i+1]:u,t[+i+n]].sort((a,b)=>(a.v-b.v))[0].p].o.push([i]);p==i&&k.push([i])}k.map(x=>{while(x[L="length"]<(x=[].concat(...x.map(y=>t[y].o)))[L]);return x[L]})
```
Outputs: `[7, 2]`
```
S="5\n1 0 2 5 8\n2 3 4 7 9\n3 5 7 8 9\n1 2 5 4 2\n3 3 5 2 1"
s=S.split(/\s/);n=s.shift()*1;k=[];u=k[1];t=s.map((v,i)=>({v:v,p:i,o:[]}));for(i in t){t[p=[t[i],i%n?t[i-1]:u,t[i-n],(+i+1)%n?t[+i+1]:u,t[+i+n]].sort((a,b)=>(a.v-b.v))[0].p].o.push([i]);p==i&&k.push([i])}k.map(x=>{while(x[L="length"]<(x=[].concat(...x.map(y=>t[y].o)))[L]);return x[L]})
```
Outputs: `[11, 7, 7]`
```
S="4\n0 2 1 3\n2 1 0 4\n3 3 3 3\n5 5 2 1"
s=S.split(/\s/);n=s.shift()*1;k=[];u=k[1];t=s.map((v,i)=>({v:v,p:i,o:[]}));for(i in t){t[p=[t[i],i%n?t[i-1]:u,t[i-n],(+i+1)%n?t[+i+1]:u,t[+i+n]].sort((a,b)=>(a.v-b.v))[0].p].o.push([i]);p==i&&k.push([i])}k.map(x=>{while(x[L="length"]<(x=[].concat(...x.map(y=>t[y].o)))[L]);return x[L]})
```
Outputs: `[5, 7, 4]`
[Answer]
# Julia, 315
```
function f(a,i,j)
z=size(a,1)
n=filter((x)->0<x[1]<=z&&0<x[2]<=z,[(i+1,j),(i-1,j),(i,j-1),(i,j+1)])
v=[a[b...] for b in n]
all(v.>a[i,j]) && (return i,j)
f(a,n[indmin(v)]...)
end
p(a)=prod(["$n " for n=(b=[f(a,i,j) for i=1:size(a,1),j=1:size(a,2)];sort([sum(b.==s) for s=unique(b)],rev=true))])
```
Just a recursive function that either determines the current cell is a sink or finds the drain, then call that on every set of indices. Didn't bother to do the input part since I wasn't going to win anyway, and that part isn't fun.
[Answer]
## Haskell, 271 286
```
import Data.List
m=map
q[i,j]=[-1..1]>>= \d->[[i+d,j],[i,j+d]]
x%z=m(\i->snd.fst.minimum.filter((`elem`q i).snd)$zip(zip z[0..])x)x
g(n:z)=iterate(\v->m(v!!)v)(sequence[[1..n],[1..n]]%z)!!(n*n)
main=interact$unwords.m show.reverse.sort.m length.group.sort.g.m read.words
```
Might be still some code to be golf'd here.
```
& runhaskell 19188-Partition.hs <<INPUT
> 5
> 1 0 2 5 8
> 2 3 4 7 9
> 3 5 7 8 9
> 1 2 5 4 2
> 3 3 5 2 1
INPUT
11 7 7
```
**Explanation**
Basic idea: For each cell *(i,j)* find the lowest cell in the "neighborhood". This
gives a graph [*(i,j)* → *(mi,mj)*]. If a cell is the lowest cell itself, then
*(i,j)* == *(mi,mj)*.
This graph can be iterated: For each *a → b* in the graph, replace it with *a → c*
where *b → c* is in the graph. When this iteration yields no more changes, then
each cell in the graph points at the lowest cell it will flow to.
To golf this, several changes have been made: First, coordinates are represented
as a list of length 2, rather than a pair. Second, once the neighbors have been
found, cells are represented by their index into a linear array of the cells,
not 2D coordinates. Third, as there are n\*n cells, after n\*n iterations, the
graph must be stable.
**Ungolf'd**
```
type Altitude = Int -- altitude of a cell
type Coord = Int -- single axis coordinate: 1..n
type Coords = [Coord] -- 2D location, a pair of Coord
-- (Int,Int) would be much more natural, but Coords are syntehsized
-- later using sequence, which produces lists
type Index = Int -- cell index
type Graph = [Index] -- for each cell, the index of a lower cell it flows to
neighborhood :: Coords -> [Coords] -- golf'd as q
neighborhood [i,j] = concatMap (\d -> [[i+d,j], [i,j+d]]) [-1..1]
-- computes [i-1,j] [i,j-1] [i,j] [i+1,j] [i,j+1]
-- [i,j] is returned twice, but that won't matter for our purposes
flowsTo :: [Coords] -> [Altitude] -> Graph -- golf'd as (%)
flowsTo cs vs = map lowIndex cs
where
lowIndex is = snd . fst -- take just the Index of
. minimum -- the lowest of
. filter (inNeighborhood is . snd) -- those with coords nearby
$ gv -- from the data
inNeighborhood :: Coords -> Coords -> Bool
inNeighborhood is ds = ds `elem` neighborhood is
gv :: [((Altitude, Index), Coords)]
-- the altitudes paired with their index and coordinates
gv = zip (zip vs [0..]) cs
flowInput :: [Int] -> Graph -- golf'd as g
flowInput (size:vs) = iterate step (flowsTo coords vs) !! (size * size)
where
coords = sequence [[1..size],[1..size]]
-- generates [1,1], [1,2] ... [size,size]
step :: Graph -> Graph
step v = map (v!!) v
-- follow each arc one step
main' :: IO ()
main' = interact $
unwords . map show -- counts a single line of text
. reverse . sort -- counts from hi to lo
. map length -- for each common group, get the count
. group . sort -- order cells by common final cell index
. flowInput -- compute the final cell index graph
. map read . words -- all input as a list of Int
```
[Answer]
## Ruby, 216
```
r=[]
M=gets('').split.map &:to_i
N=M.shift
g=M.map{1}
M.sort.reverse.map{|w|t=[c=M.index(w),c%N<0?c:c-1,c%N<N-1?c+1:c,c+N,c-N].min_by{|y|M[y]&&y>=0?M[y]:M.max}
M[c]+=1
t!=c ?g[t]+=g[c]:r<<g[c]}
$><<r.sort.reverse*' '
```
It's a slightly different approach, only invoking "flow" on each square once (performance depends what the performance of Array::index is). It goes from the highest elevation to the lowest, emptying out one cell at a time into its lowest neighbor and marking the cell done (by adding 1 to the elevation) when it's done.
Commented and spaced:
```
results=[]
ELEVATIONS = gets('').split.map &:to_i # ELEVATIONS is the input map
MAP_SIZE = ELEVATIONS.shift # MAP_SIZE is the first line of input
watershed_size = ELEVATIONS.map{1} # watershed_size is the size of the watershed of each cell
ELEVATIONS.sort.reverse.map { |water_level|
# target_index is where the water flows to. It's the minimum elevation of the (up to) 5 cells:
target_index = [
current_index = ELEVATIONS.index(water_level), # this cell
(current_index % MAP_SIZE) < 0 ? current_index : current_index-1, # left if possible
(current_index % MAP_SIZE) >= MAP_SIZE-1 ? current_index : current_index+1, # right if possible
current_index + MAP_SIZE, # below
current_index - MAP_SIZE # above
].min_by{ |y|
# if y is out of range, use max. Else, use ELEVATIONS[y]
(ELEVATIONS[y] && y>=0) ? ELEVATIONS[y] : ELEVATIONS.max
}
# done with this cell.
# increment the elevation to mark done since it no longer matters
ELEVATIONS[current_index] += 1
# if this is not a sink
(target_index != current_index) ?
# add my watershed size to the target's
watershed_size[target_index] += watershed_size[current_index]
# else, push my watershed size onto results
: results << watershed_size[current_index]}
```
### Changelog:
216 - better way to deselect out-of-bounds indices
221 - turns out, "11" comes before "2"... revert to `to_i`, but save some space on our `gets`es.
224 - Why declare `s`, anyway? And `each` => `map`
229 - massive golfing - sort the elevations first into `s` (and thereby drop the `while` clause), use `min_by` instead of `sort_by{...}[0]`, don't bother `to_i` for elevations, use `flat_map`, and shrink `select{}` block
271 - moved watershed size into new array and used sort\_by
315 - moved results to array which gave all sorts of benefits, and shortened neighbor index listing. also gained one char in index lambda.
355 - first commit
[Answer]
# Python - 470 447 445 393 392 378 376 375 374 369 bytes
I can't stop myself!
Not a winning solution, but I had a lot of fun creating it. This version does not assume the input to be stored anywhere and instead reads it from stdin. Maximum recursion depth = longest distance from a point to it's sink.
```
def f(x,m=[],d=[],s=[]):
n=[e[a]if b else 99for a,b in(x-1,x%z),(x+1,x%z<z-1),(x-z,x/z),(x+z,x/z<z-1)];t=min(n)
if t<e[x]:r=f(x+(-1,1,-z,z)[n.index(t)])[0];s[r]+=x not in m;m+=[x]
else:c=x not in d;d+=[x]*c;r=d.index(x);s+=[1]*c
return r,s
z,e=input(),[]
exec'e+=map(int,raw_input().split());'*z
for x in range(z*z):s=f(x)[1]
print' '.join(map(str,sorted(s)[::-1]))
```
I don't have time to explain it today, but here's the ungolfed code:
It actually is quite different than the original code. I read S lines from the stdin, split, map to ints and flatten the lists to get the flattened field. Then I loop through all tiles (let me call them tiles) once. The flow-function checks the neighboring tiles and picks the one with the smallest value. If it's smaller than value of the current tile, move to it and recurse. If not, the current tile is a sink and new basin is created. The return value of the recursion is the id of the basin.
```
# --- ORIGINAL SOURCE ---
# lowest neighboring cell = unique and next
# neihboring cells all higher = sink and end
basinm = [] # list of the used tiles
basins = {} # list of basin sizes
basinf = [] # tuples of basin sinks
field = [] # 2d-list representing the elevation map
size = 0
def flow(x, y):
global basinf, basinm
print "Coordinate: ", x, y
nearby = []
nearby += [field[y][x-1] if x > 0 else 99]
nearby += [field[y][x+1] if x < size-1 else 99]
nearby += [field[y-1][x] if y > 0 else 99]
nearby += [field[y+1][x] if y < size-1 else 99]
print nearby
next = min(nearby)
if next < field[y][x]:
i = nearby.index(next)
r = flow(x+(-1,1,0,0)[i], y+(0,0,-1,1)[i])
if (x,y) not in basinm:
basins[r] += 1
basinm += [(x,y)]
else:
c = (x,y) not in basinf
if c:
basinf += [(x,y)]
r = basinf.index((x,y))
if c: basins[r] = 1
return r
size = input()
field = [map(int,raw_input().split()) for _ in range(size)]
print field
for y in range(size):
for x in range(size):
flow(x, y)
print
print ' '.join(map(str,sorted(basins.values(),reverse=1)))
```
[Answer]
# JavaScript (ES6) 190 ~~203~~
**Edit** A little more ES6ish (1 year later...)
Define a function with input rows as a string, including newlines, return output as string with trailing blanks
```
F=l=>{[s,...m]=l.split(/\s+/);for(j=t=[];k=j<s*s;t[i]=-~t[i])for(i=j++;k;i+=k)k=r=0,[for(z of[-s,+s,i%s?-1:+s,(i+1)%s?1:+s])(q=m[z+i]-m[i])<r&&(k=z,r=q)];return t.sort((a,b)=>b-a).join(' ')}
// Less golfed
U=l=>{
[s,...m] = l.split(/\s+/);
for (j=t=[]; k=j<s*s; t[i]=-~t[i])
for(i=j++; k; i+=k)
k=r=0,
[for(z of [-s,+s,i%s?-1:+s,(i+1)%s?1:+s]) (q=m[z+i]-m[i]) < r && (k=z,r=q)];
return t.sort((a,b)=>b-a).join(' ')
}
// TEST
out=x=>O.innerHTML += x + '\n';
out(F('5\n1 0 2 5 8\n 2 3 4 7 9\n 3 5 7 8 9\n 1 2 5 4 2\n 3 3 5 2 1'))// "11 7 7"
out(F('4\n0 2 1 3\n2 1 0 4\n3 3 3 3\n5 5 2 1')) //"7 5 4"
```
```
<pre id=O></pre>
```
[Answer]
## Perl 6, ~~419~~ 404
Newlines added for clarity. You can safely remove them.
```
my \d=$*IN.lines[0];my @a=$*IN.lines.map(*.trim.split(" "));my @b;my $i=0;my $j=0;
for @a {for @$_ {my $c=$_;my $p=$i;my $q=$j;my &y={@a[$p+$_[0]][$q+$_[1]]//Inf};
loop {my @n=(0,1),(1,0);push @n,(-1,0) if $p;push @n,(0,-1) if $q;my \[[email protected]](/cdn-cgi/l/email-protection)(
&y)[0];my \h=y(o);last if h>$c;$c=h;$p+=o[0];$q+=o[1]};@b[$i][$j]=($p,$q);++$j};
$j=0;++$i};say join " ",bag(@b.map(*.flat).flat.map(~*)).values.sort: {$^b <=>$^a}
```
Old solution:
```
my \d=$*IN.lines[0];my @a=$*IN.lines.map(*.trim.split(" "));my @b;my $i=0;my $j=0;
for @a {for @$_ {
my $c=$_;my $p=$i;my $q=$j;
loop {my @n=(0,1),(1,0);@n.push: (-1,0) if $p;@n.push: (0,-1) if $q;
my \[[email protected]](/cdn-cgi/l/email-protection)({@a[$p+$_[0]][$q+$_[1]]//Inf})[0];
my \h=@a[$p+o[0]][$q+o[1]];last if h>$c;
$c=h;$p+=o[0];$q+=o[1]};@b[$i][$j]=($p,$q);++$j};$j=0;++$i};
say join " ",bag(@b.map(*.flat.flat).flat.map(~*)).values.sort: {$^b <=>$^a}
```
And yet I get beaten by Python and JavaScript solutions.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.