text
stringlengths 180
608k
|
---|
[Question]
[
[Jolf](https://github.com/ConorOBrien-Foxx/Jolf) is a procedural golfing language made by @CᴏɴᴏʀO'Bʀɪᴇɴ.
What tips do you have for golfing in Jolf?
Please post one tip per answer.
These tips should be at least somewhat specific to Jolf, e.g. remove comments is an answer, but not a very good one.
[Answer]
# Know your auto-assigning variables!
Jolf has many ways to "auto assign" variables. The standard one is `γ`, which takes the value of the next expression. `Β` is the same thing, but converts the next expression to a number.
Also, `ζ` (zeta) is a variable initialized to `-1/12` (guess why), and can be re-assigned with `Ζ` (Zeta).
For example, let's say you want to compare `I` (the input string) to an operation over itself. For now, let's see if `I + I = reverse(I + I)`. This is written as, conventionally:
```
=+II_+II
```
But this can be golfed down to:
```
=γ+II_γ
```
[Answer]
# Use `@`
`@` is a command that takes the next character in the source code and returns that character's code point. (For example, `@X` returns 88.) This is often very useful since you can express any number between 0 and 255 in two bytes.
[Answer]
# JavaScript fall back
If for some strange reason Jolf isn't golfy enough, or simply cannot cope, it may be of use to use JavaScript eval. This can happen in one of two ways.
## 1. Designed eval
Anything inside of `$...$` is literally carried over to the JS transpilation. For example, `+3$~$5` transpiles to `add(3, ~5)`. Equivalently, `+3:~5`.
## 2. Array eval
You can use JS arrays in Jolf! Mostly. It's kind of a bug, but I'm not going to fix it. For example:
```
u[3*5,5/6,(3+4)/5]
```
Transpiles to:
```
sum([2 * 3, 5 / 3, (3 + 4) / 5]);
```
[Answer]
# Read the source
As of right now, there are a lot of undocumented things -- the mysterious `m` module among them, which has a lot of builtins. However, they do exist in the source, and it's really not hard to read once you get the hang of it, so read the source.
[Answer]
# Increase Function Arity
Every function has an arity. For example, `+` has an arity of 2. If you want to (say) add 5 elements, you *could* use 5 +s... *or* do `+θ12345`. Specifically:
* `θ` incrases the arity of the function by 3.
* `~θ` increases the arity of the parent function by 3. (So `*+~θ345678` increases the arity of the `*` by 3)
* `M` increases the arity of the function by 2.
* `~M` increases the arity of the parent function by 2.
* `;` increases the arity of the function by 1.
* `~;` increases the arity of the parent function by 1.
* `η` decreases the arity of the function by 1.
* `~η` decreases the arity of the parent function by 1.
* `\xad` sets the arity of the parent function to the next character's charcode.
[Answer]
# Take advantage of implicit input
If a function does not have enough arguments, it will look to the input for the remainder of the arguments. For example:
```
+uz
```
Would transpile to:
```
add(sum(unaryRange(x)), x)
```
It's equivalent to
```
+uzxx
```
[Answer]
# Use `o` to store values
Similar to how other languages can assign variables for easy/short referencing, Jolf has `o`.
For example, `oThx` prints the input plus 1.
This is a useless example, but when the expression is more complicated than `hx`, it can save some serious byteage.
Also, `v"var name"<val>` allows for a multi-char variable name, and `V"var name"` gets a variable from the scope.
Thanks to Conor for explaining this to me, and giving the previous sentence.
] |
[Question]
[
This is a code-golf question.
**Input**
A list of non-negative integers in whatever format is the most convenient.
**Output**
The same list in sorted order in whatever format is the most convenient.
**Restriction**
* Your code must run in O(n log n) time in the *worst case* where `n`is the number of integers in the input. This means that randomized quicksort is out for example. However there are many many other options to choose from.
* Don't use any sorting library/function/similar. Also don't use anything that does most of the sorting work for you like a heap library. Basically, whatever you implement, implement it from scratch.
You can define a function if you like but then please show an example of it in a full program actually working. It should run successfully and quickly on all the test cases below.
**Test cases**
```
In: [9, 8, 3, 2, 4, 6, 5, 1, 7, 0]
Out:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In: [72, 59, 95, 68, 84]
Out:[59, 68, 72, 84, 95]
In: [2, 2, 1, 9, 3, 7, 4, 1, 6, 7]
Out:[1, 1, 2, 2, 3, 4, 6, 7, 7, 9]
In: [2397725, 1925225, 3304534, 7806949, 4487711, 8337622, 2276714, 3088926, 4274324, 667269]
Out:[667269,1925225, 2276714, 2397725,3088926, 3304534, 4274324, 4487711, 7806949, 8337622]
```
**Your answers**
Please state the sorting algorithm you have implemented and the length of your solution in the title of your answer.
**O(n log n) time sorting algorithms**
There are many O(n log n) time algorithms in existence. This table has a [list](https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms) of some of them.
[Answer]
# Haskell, ~~87~~ ~~80~~ 89
```
s%[]=s
(x:a)%q|x<=q!!0=x:a%q
p%q=q%p
j(x:y:s)=x%y:j s
j a=a
r[x]=x
r s=r$j s
s=r.map(:[])
```
This is merge sort, implemented from the bottom up.
first we package every element into it's own list, and then merge them two-by-two, and again merge them two-by-two, until we're left with one list.
`(%)` is the merge function
`j` merges pairs in a list of lists
`r` merges a complete list of lists
`s` is the sorting function.
Usage:
Run an interpreter, and enter `s [3,5,2,6,7]`.
**Edit:**
the way I was merging things before wasn't the right order, So to fix it I needed 9 more characters.
[Answer]
# JavaScript (ES6), ~~195~~ ~~193~~ ~~191~~ ~~189~~ ~~188~~ ~~186~~ ~~183~~ ~~182~~ ~~179~~ ~~174~~ 172 bytes
This is a heapsort implementation. I expect someone to come up with a shorter mergesort, but I like this one :P
Update: R mergesort beaten. Ruby up next :D
```
S=l=>{e=l.length
W=(a,b)=>[l[a],l[b]]=[l[b],l[a]]
D=s=>{for(;(c=s*2+1)<e;s=r<s?s:e)s=l[r=s]<l[c]?c:s,W(r,s=++c<e&&l[s]<l[c]?c:s)}
for(s=e>>1;s;)D(--s)
for(;--e;D(0))W(0,e)}
```
### Test (Firefox)
```
S=l=>{e=l.length
W=(a,b)=>[l[a],l[b]]=[l[b],l[a]]
D=s=>{for(;(c=s*2+1)<e;s=r<s?s:e)s=l[r=s]<l[c]?c:s,W(r,s=++c<e&&l[s]<l[c]?c:s)}
for(s=e>>1;s;)D(--s)
for(;--e;D(0))W(0,e)}
document.querySelector('#d').addEventListener("click",function(){a=JSON.parse(document.querySelector('#a').value);S(a);document.querySelector('#b').innerHTML=JSON.stringify(a)});
```
```
<textarea id="a">[9,4,1,2,7,3,5,8,6,10]</textarea><br><button id="d">Sort</button><br><pre id="b"></pre>
```
[Answer]
# Python3, 132 bytes
```
def S(l):
if len(l)<2:return l
a,b,o=S(l[::2]),S(l[1::2]),[]
while a and b:o.append([a,b][a[-1]<b[-1]].pop())
return a+b+o[::-1]
```
Simple mergesort. Lots of bytes were spent to make sure this actually runs in O(n log n), if only the *algorithm*, but not the *implementation* needs to be O(n log n), this can be shortened:
# Python3, 99 bytes
```
def m(a,b):
while a+b:yield[a,b][a<b].pop(0)
S=lambda l:l[1:]and list(m(S(l[::2]),S(l[1::2])))or l
```
This is not O(n log n) because `.pop(0)` is O(n), making the merge function O(n^2). But this is fairly artificial, as `.pop(0)` could easily have been O(1).
[Answer]
# Jelly, 29 bytes, merge sort
Like orlp’s Python answer, this uses `list.pop(0)` under the hood, which is `O(n)`, but the implementation is formally `O(n log n)`.
```
ṛð>ṛḢð¡Ḣ;ñ
ç;ȧ?
s2Z߀ç/µL>1µ¡
```
[Try it here.](http://jelly.tryitonline.net/#code=4bmbw7A-4bmb4biiw7DCoeG4ojvDsQrDpzvIpz8KczJaw5_igqzDpy_CtUw-McK1wqE&input=&args=WzEsNiw5LDgsNCw2LDUsMiwzXQ&debug=on)
## Explanation
```
Define f(x, y): (merge helper)
Implicitly store x in α.
ṛ ð¡ Replace it with y this many times:
ð>ṛḢ (x > y)[0].
Ḣ Pop the first element off that list (either x or y).
;ñ Append it to g(x, y).
Define g(x, y): (merge)
ȧ? If x and y are non-empty:
ç Return f(x, y)
Else:
; Return concat(x, y).
Define main(z): (merge sort)
µL>1µ¡ Repeat (len(z) > 1) times:
s2 Split z in chunks of length two. [[9, 7], [1, 3], [2, 8]]
Z Transpose the resulting array. [[9, 1, 2], [7, 3, 8]]
߀ Apply main() recursively to each. [[1, 2, 9], [3, 7, 8]]
ç/ Apply g on these two elements. [1, 2, 3, 7, 8, 9]
```
[Answer]
# Julia, 166 bytes
```
m(a,b,j=1,k=1,L=endof)=[(j<=L(a)&&k<=L(b)&&a[j]<b[k])||k>L(b)?a[(j+=1)-1]:b[(k+=1)-1]for i=1:L([a;b])]
M(x,n=endof(x))=n>1?m(M(x[1:(q=ceil(Int,n÷2))]),M(x[q+1:n])):x
```
The primary function is called `M` and it calls a helper function `m`. It uses [merge sort](https://en.wikipedia.org/wiki/Merge_sort), which has *O*(*n* log *n*) as its worst case complexity.
Example use:
```
x = [9, 8, 3, 2, 4, 6, 5, 1, 7, 0]
println(M(x)) # prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
println(M(x) == sort(x)) # prints true
```
Ungolfed:
```
function m(a, b, i=1, k=1, L=endof)
return [(j <= L(a) && k <= L(b) && a[j] < b[k]) || k > L(b) ?
a[(j+=1)-1] : b[(k+=1)-1] for i = 1:L([a; b])]
end
function M(x, n=endof(x))
q = ceil(Int, n÷2)
return n > 1 ? m(M(x[1:q]), M([q+1:n])) : x
end
```
[Answer]
# R, 181 bytes, Mergesort
```
L=length;s=function(S)if(L(S)<2){S}else{h=1:(L(S)/2);A=s(S[h]);B=s(S[-h]);Z=c();if(A[L(A)]>B[1])while(L(A)&L(B))if(A[1]<B[1]){Z=c(Z,A[1]);A=A[-1]}else{Z=c(Z,B[1]);B=B[-1]};c(Z,A,B)}
```
Indented, with newlines:
```
L=length
s=function(S)
if(L(S)<2){
S
}else{
h=1:(L(S)/2)
A=s(S[h])
B=s(S[-h])
Z=c()
if(A[L(A)]>B[1])
#Merge helper function incorporated from here ...
while(L(A)&L(B))
if(A[1]<B[1]){
Z=c(Z,A[1])
A=A[-1]
}else{
Z=c(Z,B[1])
B=B[-1]
}
#...to here. Following line both finishes merge function and handles 'else' case:
c(Z,A,B)
}
```
Test cases:
```
> L=length;s=function(S)if(L(S)<2){S}else{h=1:(L(S)/2);A=s(S[h]);B=s(S[-h]);Z=c();if(A[L(A)]>B[1])while(L(A)&L(B))if(A[1]<B[1]){Z=c(Z,A[1]);A=A[-1]}else{Z=c(Z,B[1]);B=B[-1]};c(Z,A,B)}
> s(c(2397725, 1925225, 3304534, 7806949, 4487711, 8337622, 2276714, 3088926, 4274324, 667269))
[1] 667269 1925225 2276714 2397725 3088926 3304534 4274324 4487711 7806949 8337622
> s(c(2, 2, 1, 9, 3, 7, 4, 1, 6, 7))
[1] 1 1 2 2 3 4 6 7 7 9
> s(c(72, 59, 95, 68, 84))
[1] 59 68 72 84 95
> s(c(9, 8, 3, 2, 4, 6, 5, 1, 7, 0))
[1] 0 1 2 3 4 5 6 7 8 9
```
[Answer]
## Scala, 243 Byte function (315 Bytes stand-alone app), Mergesort
This answer is intended to be a function, but can be expanded to be a stand-alone application.
Function-only (243 bytes):
```
object G{
type S=Stream[Int]
def m(f:(S,S)):S=f match{
case(x#::a,b@(y#::_))if x<=y=>x#::m(a,b)
case(a,y#::b)=>y#::m(a,b)
case(a,Empty)=>a
case(_,b)=>b}
def s(a:S):S=if(a.length>1)((q:S,w:S)=>m(s(q),s(w))).tupled(a.splitAt(a.length/2))else a
}
```
Stand-alone application(315 bytes):
```
object G extends App{
type S=Stream[Int]
def m(f:(S,S)):S=f match{
case(x#::a,b@(y#::_))if x<=y=>x#::m(a,b)
case(a,y#::b)=>y#::m(a,b)
case(a,Empty)=>a
case(_,b)=>b}
def s(a:S):S=if(a.length>1)((q:S,w:S)=>m(s(q),s(w))).tupled(a.splitAt(a.length/2))else a
println(s(args(0).split(",").map(_.toInt).toStream).toList)
}
```
Usage:
>
> Function: `G.s(List(**[Paste your array here]**).toStream).toList`
>
>
> Application: `sbt "run **[Paste your array here]**"`
>
>
>
Example Input:
```
scala> G.s(List(10,2,120,1,8,3).toStream).toList
(OR)
$ sbt "run 5423,123,24,563,65,2,3,764"
```
Output:
>
> res1: List[Int] = List(1, 2, 3, 8, 10, 120)
>
>
> OR
>
>
> List(2, 3, 24, 65, 123, 563, 764, 5423)
>
>
>
Constraints & considerations:
* Requires scalaz (very common library, not used for sorting here)
* Is 100% functional (nothing mutable!)
Attribution:
* Merge implementation (`m()` function) inspired by this answer: <https://codereview.stackexchange.com/a/21590/28856>
[Answer]
# Ruby, 167 bytes
Golfed merge sort algorithm, which has worst-case O(n log n)
```
f=->x{m=->a,b{i,j,l,y,z=0,0,[],a.size,b.size
while i<y&&j<z
c=a[i]<b[j]
l<<(c ?a[i]:b[j])
c ?i+=1:j+=1
end
l+=a[i,y]+b[j,z]}
l=x.size
l>1?m[f[x[0,l/2]],f[x[l/2,l]]]:x}
```
[Test it here!](http://ideone.com/)
To test, copy and paste the code into the window, and add `puts f[x]` at the bottom, where x is an array with the input. (Make sure you select Ruby as the language, of course) For example, `puts f[[2, 2, 1, 9, 3, 7, 4, 1, 6, 7]]`
[Answer]
## Ruby, 297 bytes
Merge sort. Complete program, instead of a function. Requires two arguments at runtime: input file and output file, each with one element per line.
```
if $0==__FILE__;v=open(ARGV[0]).readlines.map{|e|e.to_i}.map{|e|[e]};v=v.each_slice(2).map{|e|a,b,r=e[0],e[1],[];while true;if(!a)||a.empty?;r+=b;break;end;if(!b)||b.empty?;r+=a;break;end;r<<(a[0]<b[0]?a:b).shift;end;r}while v.size>1;open(ARGV[1],"w"){|f|f.puts(v[0].join("\n"))if !v.empty?};end
```
] |
[Question]
[
Welcome to my first code-golf challenge! :) Let's hop right into it.
**Challenge:**
Given two floating point vectors, **O** (origin) and **T** (target), you have to create a program to print the values **L** and **R** to STDOUT.
1. **O** is one corner of the square
2. **T** is one corner of the square that is located opposite to **O**
3. **L** is the 2D point (corner) that marks the other point of the uncomplete square
4. **R** is the 2D point (corner) that is opposite to **L**
**Rules**
5. Values for **O** and **T** have to be read from STDIN (see example inputs).
6. Again, **L** and **R**'s values has to be printed to STDOUT.
**Scoring and bonuses**
7. Count the bytes of your program.
8. If your program draws lines that connect between **O** to **L** to **T** to **R**, subtract 15 bytes from the byte count.
**Examples**
First line covers inputs (first square brackets for **O** and next brackets for **T**) and other line represents expected output.
* [0, 0] [3, 3]
Expected: [0, 3] [3, 0]
* [0, 0] [-2, -2]
Expected: [-2, 0] [0, -2]
* [1, -1] [4, 2]
Expected: [1, 2] [4, -1]
* [0, -1] [0, 1]
Expected: [-1, 0] [1, 0]
**NOTICE**: inputs and outputs can be floating points!
**Important information!**
* Values **O** and **T** can be taken in any format, as long as they come from STDIN (ex. Inside [] or ()...), use whatever format you want.
* **L** and **R** can be printed in any order.
* Remember: when (O->L->T->R->O) are connected, each side must have the same length!
**Winning**
* This is code-golf so fewest byte answer wins!
* Winner answer will be accepted at sunday 15.11.2015 20:00-22:00 (Finland time) (If I'm not wrong, that date is written like 11.15.2015 in the US, don't get confused).
Happy golfing!
[Answer]
# [Seriously](https://github.com/Mego/Seriously), 11 bytes
A port of my TI-BASIC answer. Calculates `mean(X)+i*(X-mean(X))`.
```
,;Σ½;)±+ï*+
```
Explanation:
```
, Read input
; Duplicate
Σ½ Half the sum (the mean) of the top copy
; Copy the mean
) Rotate stack to the left
Now there's a copy of the mean on the bottom
±+ Negate mean and add to input list
ï* Multiply by i
+ Add to mean
```
Input as a list of two complex numbers: `[1-1j,4+2j]`, and output in the same format: `[(4-1j), (1+2j)]`.
[Answer]
## [Seriously](https://github.com/Mego/Seriously), 25 bytes
`,i││-++½)+-+½)++-½)±+++½)`
Takes input as a list: `[x1,y1,x2,y2]`
Same strategy as my Python answer, but in Seriously!
Explanation:
```
, get input
i flatten list
││ duplicate stack twice, so that we have 4 copies of the input total
-++¬Ω) calculate the first x-value using the formula (x1-y1+x2+y2)/2, and shove it to the end of the stack
+-+¬Ω) calculate the first y-value using (x1+y1-x2+y2)/2, and shove it to the end of the stack
++-¬Ω) calculate the second x-value using (x1+y2+x2-y2)/2, and shove it to the end of the stack
±+++½) calculate the second y-value using (-x1+y1+x2+y2)/2, and shove it to the end of the stack
```
[Try it online](http://seriouslylang.herokuapp.com/link/code=2c69b3b32d2b2bab292b2d2bab292b2b2dab29f12b2b2bab29&input=1,-1,4,2)
[Answer]
## TI-BASIC, 16 bytes
For a TI-83+ or 84+ series calculator.
```
Input X
i‚àüX+.5sum(‚àüX-i‚àüX
```
Unless I misunderstood, OP said they were fine with taking input and output as complex numbers. The `i` here is the imaginary unit, not the statistics variable.
TI-BASIC has a `mean(` function, but annoyingly it doesn't work with complex lists, throwing an `ERR:DATA TYPE`.
Input in the form `{1-i,4+2i}` for `[[1,-1],[4,2]]`. Output is in the form `{4-i 1+2i}` for `[[1,2][4,-1]]`.
[Answer]
# Matlab, ~~51~~ ~~45~~ ~~46~~ ~~45~~ 42 bytes
Now the input is expected in one column vector: `[x0;y0;x1;y1]` (ouput in the same format) I just modified it to be a full program.
```
z=eye(4);disp((.5-z([2:4,1],:))*input(''))
```
Or alternatively
```
z=[1,1;-1,1];disp([z',z;z,z']*input('')/2)
```
Old solution:
The input expects column vectors, e.g. `f([0;0],[3;3])`
```
@(a,b)[0,1;-1,0]*(b-a)*[.5,-.5]+(b+a)*[.5,.5]
```
It also returns two column vectors (as a 2x2 matrix).
[Answer]
# Japt, ~~29~~ 28 bytes
**Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545)
```
1o5 mZ=>$eval$(Uq'+)/2-UgZ%4
```
Note that the arrow functions require an ES6-compliant browser, such as the newer versions of Firefox. Input goes in as a 4-item array, e.g. `[1,-1,4,2]`.
### How it works
```
// Implicit: U = input array
1o5 // Create a range of integers from 1 to 5. Returns [1,2,3,4]
mZ=> // Map each item Z in this range to:
$eval$( // evaluate:
Uq'+ // U joined with "+" (equivalent to summing U)
)/2 // divided by 2,
-UgZ%4 // minus the item at Z%4 in the input. This translates to [y‚ÇÅ,x‚ÇÇ,y‚ÇÇ,x‚ÇÅ],
// which in turn tranlsates to:
// [(x‚ÇÅ-y‚ÇÅ+x‚ÇÇ+y‚ÇÇ)/2, (x‚ÇÅ+y‚ÇÅ-x‚ÇÇ+y‚ÇÇ)/2, (x‚ÇÅ+y‚ÇÅ+x‚ÇÇ-y‚ÇÇ)/2, (-x‚ÇÅ+y‚ÇÅ+x‚ÇÇ+y‚ÇÇ)/2]
// which is [Lx,Ly,Rx,Ry], or [Rx,Ry,Lx,Ly], depending on the situation.
// Implicit: Output last expression
```
### How it was golfed
I first tried simply copying @Mego's Python approach. This left me with this 48-byte monster:
(Note: the input should not currently be wrapped in an array.)
```
[U-V+W+X /2,(U+V-W+X /2,(U+V+W-X /2,(V+W+X-U /2]
```
Since each of these items needs to be divided by 2, it's shorter to map the entire array with `mY=>Y/2`:
```
[U-V+W+X,U+V-W+X,U+V+W-X,V+W+X-U]mY=>Y/2
```
Now what? Well, the array is now simply adding three of the inputs and subtracting the fourth, following the pattern `1,2,3,0`. So, we could pack the inputs into an array, then add them together, divide by 2, and subtract the necessary item:
```
[1,2,3,0]mZ=>(Ug0 +Ug1 +Ug2 +Ug3)/2-UgZ
```
Nice, saved a byte! But is it possible to shrink the array at the beginning? Let's try packing it into a string, then splitting it back into an array with `a`:
```
"1230"a mZ=>(Ug0 +Ug1 +Ug2 +Ug3)/2-UgZ
```
Look at that, another byte saved. But is there an even better way? Well, we can use the fact that `[1,2,3,0] ≡ [1,2,3,4] mod 4`:
```
1o5 mZ=>(Ug0 +Ug1 +Ug2 +Ug3)/2-UgZ%4
```
Another two bytes! Now we're going somewhere. But that `Ug0 +Ug1 +Ug2 +Ug3` is hogging a lot of space. What if we reduce the array with addition?
```
1o5 mZ=>Ur(X,Y =>X+Y /2-UgZ%4
```
Wow, that really helped! Now we're down to 29 bytes. And thanks to @ןnɟuɐɯɹɐןoɯ, I was even able to golf another byte off the reduction. But if we could use a built-in to sum the array, it'd be way shorter:
```
1o5 mZ=>Uu /2-UgZ%4
```
19 bytes! Amazing! Unfortunately, Japt does not yet have any such built-ins. I'll add this in when I get a chance. Suggestions are welcome, for either the program or the language!
---
Well, as of v1.4.4, I've implemented quite a few more features into Japt than I had originally planned. Starting with the original plan for the shorter version:
```
1o5 mZ=>Uu /2-UgZ%4
```
First we need to change a few things: Functions are defined with `{`, and the sum function is `x`. This version works as-is:
```
1o5 mZ{Ux /2-UgZ%4
```
Now, `@` is a shorthand for `XYZ{`, allowing us to save a byte by switching from `Z` to `X`. Also, `£` is a shortcut for `m@`, saving another byte:
```
1o5 £Ux /2-UgX%4
```
Recently I implemented a feature where a `U` at the beginning of the program can usually be left out. Due to an implementation mistake, however, this also works with functions:
```
1o5 £x /2-UgX%4
```
Finally, the `g` function now wraps if the index is past the end of the string, allowing us to remove the `%4` for a total of **13 bytes**:
```
1o5 £x /2-UgX
```
And I thought 19 was amazing ;-) [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=MW81IKN4IC8yLVVnWA==&input=WzEsIC0xLCA0LCAyXQ==)
[Answer]
# Javascript(Node.js/ES6), 154 bytes
```
process.stdin.on('data',s=>(s=s.toString().split(','),a=s[0]-0,b=s[1]-0,x=s[2]-0,y=s[3]-0,console.log([a+(c=(a+x)/2-a)+(d=(b+y)/2-b),b+d-c,a+c-d,b+d+c])))
```
Getting stdin is the longer part of the code. The input should be the points comma separated :
```
echo "0,0,3,3" | node square.js
```
[Answer]
# CJam, 30 bytes
```
q~_:.+\:.-(W*+_2$.+@@.-].5ff*`
```
[Try it online](http://cjam.aditsu.net/#code=q~_%3A.%2B%5C%3A.-(W*%2B_2%24.%2B%40%40.-%5D.5ff*%60&input=%5B%5B0%20-1%5D%20%5B0%201%5D%5D)
This takes input as a list of lists, e.g. for the last example:
```
[[0 -1] [0 1]]
```
Explanation:
```
q~ Get and interpret input.
_ Make a copy.
:.+ Reduce the list of two points with vector sum operator.
\ Swap copy of input to top.
:.- Reduce the list of two points with vector difference operator.
(W*+ Turn (x, y) into orthogonal (y, -x) by popping off first element, inverting
its sign, and concatenating again. We now have center and offset vector.
_2$ Create a copy of both...
.+ ... and add them.
@@ Rotate original values to top...
.- ... and subtract them.
] Wrap the two results...
.5ff* ... and multiply all values by 0.5.
` Convert list to string.
```
[Answer]
# ngn APL, 21 bytes
```
⎕←F.5 0J.5×(F←+/,-/)⎕
```
This takes the input as a pair of complex numbers (e.g., `1J¯1 4J2`) and prints the output in the same way (e.g., `4J¯1 1J2`). Try it online in the [ngn/apl demo](http://ngn.github.io/apl/web/#code=%u2395%u2190F.5%200J.5%D7%28F%u2190+/%2C-/%29%u2395).
[Answer]
# Pyth, 12 bytes
```
.jL.OQ-R.OQQ
```
This takes the input as a pair of complex numbers (e.g., `1-1j, 4+2j`) and prints the output as an array (e.g., `[(4-1j), (1+2j)]`). [Try it online.](https://pyth.herokuapp.com/?code=.jL.OQ-R.OQQ&input=1-1j%2C+4%2B2j)
[Answer]
# ùîºùïäùïÑùïöùïü, 29 chars / 43 bytes
```
ô(ѨŃ(1,5)ć⇀ë(ïø`+`⸩/2-ï[$%4]⸩
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B3%2C3%2C0%2C0%5D&code=%C3%B4%28%D1%A8%C5%83%281%2C5%29%C4%87%E2%87%80%C3%AB%28%C3%AF%C3%B8%60%2B%60%E2%B8%A9%2F2-%C3%AF%5B%24%254%5D%E2%B8%A9)`
[Answer]
## Python 3, 102 bytes
```
g=lambda a,b,c,d:((a-b+c+d)/2,(a+b-c+d)/2,(a+b+c-d)/2,(d+b-a+c)/2)
print(g(*map(float,input().split())))
```
Input is taken in the form `x1 y1 x2 y2`, on a single line.
[Try it online](http://ideone.com/Vz1bbh)
[Answer]
# Prolog, 118 bytes
```
p([A,B],[C,D]):-read([E,F,G,H]),I is(E+G)/2,J is(F+H)/2,K is(G-E)/2,L is(H-F)/2,A is I-L,B is J+K, C is I+L, D is J-K.
```
Slightly more readable:
```
p([A,B],[C,D]):-read([E,F,G,H]),
I is(E+G)/2,
J is(F+H)/2,
K is(G-E)/2,
L is(H-F)/2,
A is I-L,
B is J+K,
C is I+L,
D is J-K.
```
To start the program:
```
p(X,Y).
```
Example input when the known corners are [1, -1] [4, 2]:
[1,-1,4,2]
Example output, where X and Y will contain the unknown corners:
X = [1.0, 2.0],
Y = [4.0, -1.0]
Try it out online [here](http://swish.swi-prolog.org/)
**Edit:** Changed to read input from STDIN
[Answer]
# Python 2, 56 bytes
```
i=input()
s=sum(i)/2.0
print s-i[1],s-i[2],s-i[3],s-i[0]
```
Input can be `x1,y1,x2,y2` or `(x1,y1,x2,y2)`
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/23564/edit).
Closed 6 years ago.
[Improve this question](/posts/23564/edit)
What is some of the coolest/best/worse abuses of CSS?
For example, [these shapes](http://css-tricks.com/examples/ShapesOfCSS/), or using multiple box-shadows to make pixel art.
[popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") ending on 16/04/14.
[Answer]
Some dude created a tool to convert any image to pure CSS. This goes well beyond the original intent of CSS.
Here is an example (The famous Mona Lisa):
<http://codepen.io/jaysalvat/pen/HaqBf>
And here is the tool :
<https://github.com/jaysalvat/image2css>
[Answer]
## Changing images on the fly
I won't necessarily call it abuse, but you can use CSS to replace an `IMG` with a given `SRC` to show a completely different image.
```
@media print
{
IMG
{
padding: 150px 200px 0px 0px;
background: url('lady.jpg');
background-size:auto;
width:0px; height: 0px;
}
}
```
See: <https://stackoverflow.com/questions/2182716/how-can-we-specify-src-attribute-of-img-tag-in-css>
Can be lots of fun combined with `@media` selectors to display completely different images when printing a webpage. (Same trick can be done in `PDF` btw. Nice to see the face of the guy that is printing a document and all serious looking charts are replaced by beautiful ladies :))
[Answer]
# Resizable elements:
You can add `resize:both` to allow an element to be resized by the user.
On some browsers, this is only supported on `<textarea>`'s.
# Real-time CSS preview:
This is not an actual css thing, but you can add the `contenteditable` property, add the property `style="display:block;z-index:99;width:500px;height:500px;resizable:both;"` and you can edit your CSS.
# Styled CSS Checkboxes/radiobuttons:
Using the following piece of markup as example:
```
<input type="checkbox" id="check_all" name="check_all" value="1">
<label for="check_all">Check all</label>
```
You can use `display:none` on the `<input>` and, using CSS3 selectors, you can set a 'sprite' background to show the different states of the checkbox/radiobutton.
The order of the elements is important, and matching the `for=""` property with the `id=""` in the input is even more important!
You can see some examples here: <http://www.csscheckbox.com/>
# Browser specific selectors:
We all have tried to use some sort of javascript mix with css classes and media-queries...
Well, here are a **few** browser specific selectors:
```
doesnotexist:-o-prefocus, #selector {}/*opera only*/
:root {}/*target all css3 browsers*/
:-moz-any(*){}/*mozilla and mozilla based only*/
:-webkit-any(*){}/*webkit only*/
```
For IE, you have tons of selectors. No need for more.
[Answer]
I guess it depends what you mean by abuse but this would drive your users batty:
# Jitters
```
*:hover{
zoom:99%;
}
```
(as you mouse around the page everything jitters on you)
# Experts-Exchange/Pay-To-View Effect
```
*{
color:transparent;
text-shadow:0 0 5px rgba(0,0,0,0.5);
}
```
(makes all the text blurry)
# "Animated GIF's" using CSS sprite sheets
<http://jsfiddle.net/simurai/CGmCe/light/>
(Java's "The Dude" waving his hand)
] |
[Question]
[
In this [programming-puzzle](/questions/tagged/programming-puzzle "show questions tagged 'programming-puzzle'"), your goal is to write the following function in JavaScript, using (essentially) [point-free (*tacit*) programming](https://en.wikipedia.org/wiki/Tacit_programming):
```
(f) => void(f())
```
Your submission should be an expression which returns a function which behaves like the above (taking a function as an argument and calling it, and returning `undefined`), without writing a function definition (defined objectively below). You must instead achieve the behavior by combining existing functions (e.g., `Function.prototype.apply`).
Any JS is valid, with the exception of the following:
* Function definitions using the `function` keyword, arrow function syntax, or object/class method syntax
* Function definitions using `new Function` or the `Function` constructor
* Evaluation of code using `eval` (directly or indirectly)
* Relying on browser-only functionality or import/filesystem/OS/FFI libraries in Node.js
If this is not possible, a proof of its impossibility is also a valid submission. Solutions will be scored by byte count; smallest solution is best.
[Answer]
## Why I believe this is impossible (as stated)
There aren't very many JS builtins that call a function, and even fewer that call one with arbitrary arguments. The ones that I've found are the string methods `replace` and `replaceAll`, the array methods `every`, `filter`, `find`, `findIndex`, `findLast`, `findLastIndex`, `flatMap`, `forEach`, `map`, `reduce`, `reduceRight`, and `some`; the the function methods `apply` and `call`; the global functions `Reflect.apply`, `setTimeout`, `setInterval`, the `Promise` constructor and (browser only) `requestAnimationFrame` and `addEventListener`, and also some weird stuff like `RegExp[@@replace]`.
All the array methods are useless, as they all call functions with the signature `f(item, index, array)`.
There are a few that call the function but can't return undefined. `String#replace` (along with `String#replaceAll` and `RegExp[@@replace]`) almost work with `''.replace.bind('', /(?:)/g)`, but returns the function's result stringified. `setTimeout` ignores the function's return value, but returns a uid for that particular call (ditto with `setInterval`).
Likewise, the function methods `apply` and `call` return the return value of whatever function they're called with. `Reflect.construct` can be used to trigger the `Promise` constructor, but requires the arguments passed to the constructor function to be placed in an array.
Event listeners are somewhat promising, taking a function and returning undefined, but there's no way to create an object which has an event occur on it every time the function is called. `window.addEventListener.bind(window, 'click')` (browser only) does work to call a function every time a click is called though.
As calling the expression with the input function has to be the last operation performed on the expression, I don't think there's any way to transform whatever non-`undefined` value is returned into `undefined`. And since there's no built-in function capable of both instantly calling the function a single time without arguments and returning `undefined`, I don't think this challenge is possible.
---
### (old answer, calls with nonempty args) 17 bytes
```
[].find.bind([,])
```
[Try it online!](https://tio.run/##VcqxDYAgEEDRVa6DS5ANdBFDgYCKEM7oqWyPtja/eX@ztz3dEXfuCvnQEvTQRqPnWLyevshRGWyOykk56EyLFHTxfrFQkGSFfoAfOptz8PBEXr@jImJ7AQ "JavaScript (Node.js) – Try It Online")
~~I'm pretty sure this is optimal~~ -3 bytes thanks to Neil.
Calls the function on an array `[,]`, passing `undefined` to it. If the function's return value is truthy, the `undefined` is returned; if it's falsy the `find` call fails and returns `undefined`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~74~~ 65 bytes
```
[].forEach.bind([{[Symbol.split]:(c=Map.call).bind(c)}],''.split)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bU-xCsIwEN39ituSQM0gDqJ0cHB0ciwd2rRpCzEpSQpK6Ze4VNDJL_JvvJIuissd9-69d-9uD22KcnwJo50H22mIn52Xy817n6RcGnvIRM3zRhc06ZPT9ZwbxV2rGp9uqYiPWctFphQLFMGGNCIkENhsdJedFr4xGiTlnGe2cgx6mC4aVXJlKkomD8J2P6C_kAh83TjcYBSgISU6gJHw1whB1GBFyQC29J3VsF7hsPji4QZ5-C-VbA46jqF_AA)
[Answer]
It looks like a loophole in the function definition restriction, but you can still define a setter:
```
({set s(f){f()}}).__lookupSetter__('s')
```
[`__lookupSetter__`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__) is non-standard and deprecated, but shorter than
```
Object.getOwnPropertyDescriptor({set s(f){f()}},'s').set
```
] |
[Question]
[
Given a non-empty sequence of non-negative integers, output any permutation of it in which no two adjacent elements have a sum that is divisible by 3. If it is impossible, either crash the program, return an empty sequence, or output nothing.
**The [asymptotic time complexity must be linear in the size of the input sequence](https://en.wikipedia.org/wiki/Time_complexity#Linear_time)**.
**Example Input and Possible Output:**
```
1,2,3 -> 1,3,2
9,5,3,6,2 -> 9,5,3,2,6
5,6,15,18,2 -> 6,5,15,2,18
1,2,3,4,5,6,7,8,9,10 -> 3,1,6,4,7,10,9,2,5,8
6,1,6,6 -> no solution
4,3,7,6,6,9,0 -> no solution
```
[Answer]
# JavaScript (V8), ~~189~~ 164 bytes
```
a=>{z=[],o=[],t=[],l='length',r=x=>x[l]&&!print(x.pop());a.map(x=>[z,o,t][x%3].push(x));(z[l]-1>o[l]+t[l]||!z[l]&&o[l]&&t[l])&&$;while(z[l]>o[l]&&r(z),r(o)||r(t));}
```
[Try it online!](https://tio.run/##TY5bboMwEEX/WYUTtcRWJ6iEkBAhs4RuAPFhIShUFCMzpJTH2qkNlZKfa825D/lL3EWbqrLB4z1Ycr4IHo0DjxOQRtBIxQ9VVn9icQDFex71cZXY9q5RZY20dxrZUMZC4XyLhmo7HkACJnH/6iVO07UF7bVNB906upHUzxtqmabdsA7JVQ1itv0S/hRlla3paHMUHRgoKtk0KYp6al7yrk6xlDXBrEUq2GgRQlD9kpHk@iRzKjAtaMbG7ZP7D0laWXWms2cz2SizZmsdiF04gZew8P@8gQ8eXOD0QL4@XR/cwMDnFpzBeFcI4Abu@6Oh85pfHuCsw1eDdNDklj8)
*Saved 25 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602)*
## Explanation
Under modulus 3, the question is reduced, with there being only 3 states for a number: 0, 1, or 2. We need to find a permutation of the sequence such that no two adjacent elements add to 0 (under modulus 3). This means that 0 cannot be placed next to 0 and 1 cannot be placed next to 2. With this in mind, we can place the 1s and 2s on separate sides with one 0 used to separate the 1s and the 2s and the other zeros placed between consecutives 1s or 2s (or at the ends). To implement this, we can use arrays to store the numbers that are 0, 1, and 2 under modulus 3. Each time a number of a certain type is needed, we just pop a number from the appropriate array.
```
a=>{z=[],o=[],t=[],
//arrays to store numbers that are zero, one, and two under modulus three
//(later referred to as zero array, one array, and two array)
l='length', //store length key to save bytes on multiple accesses
r=x=>x[l]&&!print(x.pop());
//function to print and remove last element of array if not empty
//returns true if element removed
a.map(
//abuse map instead of forEach to save bytes; discard returned array
x=>[z,o,t][x%3].push(x));
//add each number to appropriate array based on remainder when divided by 3
(z[l] - 1 > o[l] + t[l] //too many zeroes; zeroes cannot be separated
|| //or
!z[l] && o[l] && t[l]) //no zeroes to separate ones and twos
&& $;//then terminate with ReferenceError ($ is not defined)
while(z[l]>o[l]&&r(z), //remove from zero array if there are more zeroes than ones
//(ensure that there will be at least one 0 left to separate 1s from 2s)
r(o)||r(t)
//try to remove from one array, then from two array if the former is empty
);
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~129~~ ~~127~~ 114 bytes
*-2 bytes thanks to @ovs*
Gives `NameError` or `IndexError` on impossible cases.
```
C=x,y,z=[[],[],[]]
for i in input():C[i%3]+=i,
M=[]
while x:M+=C[len(M)%2*-~(z>[])].pop(),
y>M==[]<z<_
print y+M+z
```
[Try it online!](https://tio.run/##JU7LasMwELzvVwhDwK63JZbjPEyUi@mhB/cHhAhtqhKBYwlFpZYP/XV37bDDMjuzLxfD1fZ8@r2aTrOiBhZ8pMz0oC8sSZKpEQNGHIWUChco@LaeGWZ6gvsJaVY30qxKlQuD0Aqp4LFtqNtcNLLTfdpmK/70/JeOJ6ky9eKsSzOEeGoFtR/H4xmcN31gMW/zcWLzYaAXLtoFlr71X3p49d56ZO8fN73QbH7yMZSYm7P3u/nsdDIVyLGEA1ZY4hY5VJSLCos98cXDDc7aDvd4wGINZFO5hQ1Zu5mRvKbWOTjyfw "Python 2 – Try It Online")
## Idea
My method looks to be the same as previous answers. The idea is that the problem is the exact same if we apply \$ \text{mod 3} \$ to each element. Then the constraint is satisfied if no two adjacent elements are `0,0` or `1,2`.
One way to solve this is to alternate `0,1,0,1,0,1,0,2,0,2,0,2...` until all zeros are gone. Then simply add all remaining `1`s to the left side and all remaining `2`s to the right side.
Finally there are two cases in which the answer is impossible. Denote \$ cnt\_{i} \$ as the number of elements equal to \$ i \$ in the sequence.
* Case 1: \$ cnt\_{0} = 0 \$, \$ cnt\_{1} > 0 \$, \$ cnt\_{2} > 0 \$
* Case 2: \$ cnt\_{0} > cnt\_{1} + cnt\_{2} + 1 \$
[Answer]
# [Python 3](https://docs.python.org/3/), 172 bytes
```
def f(l):
s=a,b,c=[tuple(e for e in l if e%3==x)for x in(0,1,2)];u,v,w=map(len,s)
if u<=v+w+1and u:return c[max(u-v,0):]+sum([*zip(a[v:],c)]+[*zip(a,b)],())+b[u:]+a[v+w:]
```
[Try it online!](https://tio.run/##RZBdb4MgFIbv/RUnTZbAOE201n6wsT9CuFCLmYlSo6BuTX@7Azczrnif9yEc6L7s592ky3LTFVSkoTyCQeRYYCmkdV2jiYbq3oOG2kADdQX6JRVipgHOHpIYEzxQ9eZwxEm0eUcabXCgUZDduxjZxJLc3MDxXlvXGyhlm8/E7UeMKVdscC2Rr991R3I5coUlVewvY0EVEkpZIZ03fc8mrharBzuAABmBX9Lfj6nC33DFDFM84WEDmQ9JhsnlH60H8IihOuMFr5jEW@dlT09bPHrxHICXYhWpKAoPDwOED1kH4avZ9bWxpNo9AnvC/gMeFQl7@tzR5Qc "Python 3 – Try It Online")
This makes use of the same idea as the earlier answer, but constructs the final array using a different approach. Instead of taking from each list element by element we construct the output directly by using the lengths of the arrays. Because of this, we have to test if there is a solution before returning the construction.
This can probably be golfed quite a bit more, but I haven't been able to make progress in a while.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
≔E³Φθ⁼ι﹪λ³η≔⊟ηζ≔⊟ηε≔⊟ηδ¿∧∨δ¬∧εζ‹⊗⊖LδLθ«W∨εζ«F›LδLε⊞υ⊟δ⊞υ⊟ι»I⁺υδ
```
[Try it online!](https://tio.run/##ZY/LasMwEEXX9lfMcgJTaOI@8So0bTdJ633IQrUmkUCxYj1aaMm3u5IbQiFaac7oXK5aJVxrhRmGufd61@FKHLAieNEmsMOe4LmPwnjUBCsro7FoCKpJOgRqUpcnrbEHVAl9XyK@RDIhvQWcdxLfHUqCNxvGiXNEzl6y97iw8cOwxAW3jvfchXRfcrcLCuXp1Tj0uQ/8lMWX0oYhZ/4FZVZsrQN8dSzyj876WebsNtErjAS5YYquk/Yf6REdy6Jxugv4JHzAxkSf97lJXR6HYb2e0owquqFbuqN7eqBHml5vNsPVp/kF "Charcoal – Try It Online") Link is to verbose version of code. Doesn't output anything unless a solution exists. Explanation:
```
≔E³Φθ⁼ι﹪λ³η
```
Split the input elements up into three arrays depending on their residue modulo 3.
```
≔⊟ηζ≔⊟ηε≔⊟ηδ
```
Assign the arrays to separate variables to save bytes. I'll call them `0`s, `1`s and `2`s for the purposes of the explanation, although the verbose variable names are actually `d`, `e` and `z`.
```
¿∧∨δ¬∧εζ‹⊗⊖LδLθ«
```
Check for a solution: there must be `0`s if there are both `1`s and `2`s, but the `0`s can't account for more than half the number of entries, rounded up.
```
W∨εζ«
```
Repeat until both the `1`s and `2`s have been exhausted.
```
F›LδLε⊞υ⊟δ
```
If there are more `0`s than `1`s then move one of them to the output list.
```
⊞υ⊟ι
```
Output one of the `1`s if any, otherwise one of the `2`s.
```
»I⁺υδ
```
Print the results plus the very last `0` if any.
[Answer]
# [J](http://jsoftware.com/), 78 bytes
```
[:(#~[:*/0<3|2+/\])]{~(]/:&/:0(i.&3(|.@{.,}.)])@-.~,@|:@(]/.~=&1)@/:)&(1+3&|)~
```
[Try it online!](https://tio.run/##VY5NS8NAEIbv/RWDQjZrJ5v9yOdiISB4UgSvNQeJqYlIUsgGhMb89Tia9uDCwPI@7zzMx3Il2AF2FhggSLA0gYC754f7ZW/963lvb0J5aya9DV9KXp5mvwytF1rpt8Iz/iSKk8BvwUteBGLGYrIFNcS88xQvQss9X22NN/F54ZtNXTU9sMdXVzX1APXXsa5c/QZD/zm6tu8sWxsKDGgILBzoq8GsaQ7xX56sJMcYDSaoV5oQVTFhla08JqZiVBlquGgjEqRUVZJsmjbOXYWaXBH@7qSYYY5Kno99Gt1xdAN0vWva7v1yImPrJrlokv9hRLKUVAmJ5Ibe8gM "J – Try It Online")
This turned out to be difficult to golf well.
I'll try to shave off more bytes tomorrow night and add an explanation.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~170~~ 168 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{y←⍳(≢⍵)⌊2×+/I←0=3|⍵⋄y[1-⍨2×⍳+/I]←⍵[⍸I]⋄z←(≢b←⍵[⍸J←1=3|⍵])⌊⌊2÷⍨1-⍨≢y⋄y[2×⍳z]←b[⍳z]⋄c←⍵[⍸K←2=3|⍵]⋄y[2×z+⍳w]←c[⍳w←(⌊2÷⍨≢y)-z]⋄x←÷(~(∨/K)∧∨/J)∨∨/I⋄b[z+⍳z-⍨≢b],y,c[w+⍳w-⍨≢c]}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=RY09DoJAEIWvAwGCYO0BgCNsttk9BO76UxmD4iZ29jbSG4I9N5mT@GaB0L3Me/N9B0PXJ7lvQLc3uT6kxz0fX1Fa4LzZbY@4UXsxIkvIdWgwRSn9Uy/I/ZC5nyrLhRKcEJip1mWJmE1IyR6vGoD1bGwNo/T6UCHm88MisRHgNWs0a2qvWUDMCBPL4z2KcQjOATVdWoXUfDiUCB2HAhMlPMzOdiVjE2tRe8F80/L0Bw&f=S1d41DZBobpCR91KXce4xkhbvwIokPaod2stV7qCoYKRgjGQtlQwVTBWMFMwArJNgbShqYKhBZj3qHezoQFUpQlYzkLBHIkP5AHVzK2pARIgjUBshhAwAZpqDhayVDAAAA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f)
A dfn submission. Assumes `⎕IO ← 1`. Uses an adapted version of the algorithm from [this Python answer](https://codegolf.stackexchange.com/a/220248/91340). [This JS answer](https://codegolf.stackexchange.com/a/220245/91340) appears to use the same algorithm, as does [this other Python answer](https://codegolf.stackexchange.com/a/220247/91340).
## Ungolfed:
```
a ← ⎕ ⍝ input array
I ← 0=3|a ⍝ n%3 == 0 for n in a
y ← ⍳(≢a)⌊2×+/I ⍝ initialise result
y[1-⍨2×⍳+/I] ← a[⍸I] ⍝ set indices that are odd to multiples of three
J ← 1=3|a ⍝ n%3 == 1 for n in a
b ← a[⍸J] ⍝ a[i] for i in range(len(a)) if J[i]
z ← (≢b)⌊⌊2÷⍨1-⍨≢y ⍝ min(len(b), len(y-1)//2)
y[2×⍳z] ← b[⍳z] ⍝ y[2*i] = b[i] for i in range(z)
K ← 2=3|a ⍝ n%3 == 2 for n in a
c ← a[⍸K] ⍝ a[i] for i in range(len(a)) if K[i]
w ← (⌊2÷⍨≢y)-z ⍝ len(y)//2 - z # garanteed to be positive or 0
y[2×z+⍳w] ← c[⍳w] ⍝ y[2*(z+i)] = c[i] for i in range(w)
÷(~(∨/K)∧∨/J)∨∨/I ⍝ error if there is no multiples of three, but there are numbers 1 more than a multiple of three and numbers that are 2 more than a multiple of three
b[z+⍳z-⍨≢b],y,c[w+⍳w-⍨≢c] ⍝ all of b not in y + y + all of c not in y
```
## Explanation:
***NOTE:*** *APL uses 1-based indexing, as do I in this explanation*
1. I handle the multiples of three:
1. I create an array where every index in said array that is a multiple of three in the input array - \$a\$ - is \$1\$, and I assign it to the variable \$I\$ -- `I ← 0=3|a`.
2. I initialise an array, \$y\$, that is from \$1\$ to the minimum of the length of \$a\$ and two times the amount of multiples of three there is in \$a\$ (the amount of \$1\$'s in \$I\$) -- `y ← ⍳(≢a)⌊2×+/I`.
3. I set all the odd indices of \$y\$ (\$y\_n\$ for every second \$n\$ from \$1\$ to \$2\$ times the sum of \$I\$) to the multiples of three in \$a\$.
2. I handle numbers that are one more than a multiple of three:
1. I create an array where every index in said array that is one more than a multiple of three in the input array - \$a\$ - is \$1\$, and I assign it to the variable \$J\$ -- `J ← 1=3|a`.
2. I create an array, \$b\$ that contains all the numbers in \$a\$ that is one more than a multiple of three -- `b ← a[⍸J]`.
3. I create a variable \$z\$, that holds the minimum of the length of \$b\$ and \$floor(\frac{len(y)-1}{2})\$ -- `z ← (≢b)⌊⌊2÷⍨1-⍨≢y` -- I subtract one from the length of \$y\$ so that the final constructed array doesn't end with a number that is 1 more than a multiple of three. To see what would happen without the subtraction, you can go to the APLgolf link, change `z ← (≢b)⌊⌊2÷⍨1-⍨≢y` to `z ← (≢b)⌊⌊2÷⍨≢y`, and click "Run".
4. I then assign to every index \$n\$ of \$y\$, where \$n\$ is every second number from \$2\$ to \$2z\$, the first \$z\$ values of \$b\$ -- `y[2×⍳z] ← b[⍳z]`.
3. I handle numbers that are two more than a multiple of three:
1. I create an array where every index in said array that is two more than a multiple of three in the input array - \$a\$ - is \$1\$, and I assign it to the variable \$K\$ -- `K ← 2=3|a`.
2. I create an array, \$c\$ that contains all the numbers in \$a\$ that is two more than a multiple of three -- `c ← a[⍸K]`.
3. I create a variable \$w\$, and assign to it \$floor(\frac{len(y)}{2})-z\$ -- `w ← (⌊2÷⍨≢y)-z` -- this is how many open spots are left in the array.
4. I then assign to every index \$n\$ of \$y\$, where \$n\$ is every second number from \$2(z+1)\$ to \$2(z+w)\$, the first \$w\$ values of \$c\$ -- `y[2×z+⍳w] ← c[⍳w]`.
4. I handle arrays that don't contain multiples of three, but *do* contain the other two categories -- `÷(~(∨/K)∧∨/J)∨∨/I`:
1. Throw `DOMAIN ERROR: Divide by zero` if the following is false -- `÷`:
1. There is at least *one* multiple of three -- `∨/I`...
2. OR -- `∨`...
3. NOT -- `(~...)`...
1. There is at least one number that is one more than a multiple of three -- `∨/J`...
2. AND -- `(...)∧`...
3. There is at least one number that is two more than a multiple of three -- `∨/K`
2. **TLDR:** Throw DivByZero if there are no multiples of three, and both numbers one more than a multiple of three, and two more than a multiple of three.
5. Output
1. Every element in \$b\$ that wasn't used, catenate to... -- `b[z+⍳z-⍨≢b],...`
2. \$y\$ catenate to... -- `y,...`
3. Every element in \$c\$ that wasn't used -- `c[w+⍳w-⍨≢c]`
] |
[Question]
[
# The objective
Given a Russian text, encrypt it with Caesar cipher with key 16.
# The basic Cyrillic alphabets
The basic Cyrillic alphabets are: (U+0410 – U+042F)
```
АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ
```
By the Caesar cipher, they are mapped to:
```
РСТУФХЦЧШЩЪЫЬЭЮЯАБВГДЕЖЗИЙКЛМНОП
```
The small letters (U+0430 – U+044F) are also mapped likewise.
Note the absence of `Ё`.
# Rules
1. Ё (U+0401) and ё (U+0451) are not considered basic, and are mapped to Х̈ (U+0425 U+0308) and х̈ (U+0445 U+0308), respectively.
2. Any other characters are preserved.
# Example
The following sentence:
```
В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!
```
Is encrypted to:
```
Т зрйре оур цшы сл жшвагб? Фр, эю дрымиштлщ нъчхьяыпа!
```
[Answer]
# JavaScript (ES6), ~~148 ... 110~~ 108 bytes
*Saved 12 bytes thanks to @Grimy!*
This function applies some maths to the code points.
```
s=>s.replace(/./g,s=>String.fromCharCode(...(n=s.charCodeAt()-304)%80-1?[(n^16*(n>0))+304]:[1060+n%48,776]))
```
[Try it online!](https://tio.run/##LY7LTsJAGEZfZSQhmZF2aCMpxKQQrG/gkmBSS1sxdUraxjV4N3iJxgcpGBXFyyt8/xPVWbj4Nuc7i3Pkn/h5kI0nhanSUVhFbpW73Vxm4STxg5A3ZTM2NNkrsrGKZZSlx96hn3na5VJKrtxcBv@gX3BhblktUe9Ypt0bcLVvO5tcdS0hGpoPtwe25VgNVW91jHbbGQpRBanK0ySUSRrziNfwxOgKJd3oXTC6xwtKhjessGZY0JzRJVZ0SlM6o1mP4RmlwfCNH0bnKLGmW7rW8pLm@GB0h0@84xVf@NXXA003GGb0yPo73q5/EIxqOuAP "JavaScript (Node.js) – Try It Online")
### How?
For each character in the input string, we define \$n\$ as its code point minus \$304\$.
```
characters | code points | n
---------------+--------------+---------------
А to Я | 1040 to 1071 | 736 to 767
а to я | 1072 to 1103 | 768 to 799
Ё | 1025 | 721
ё | 1105 | 801
ASCII | 0 to 126 | -304 to -178
```
Then we apply the following logic:
```
// neither 'Ё' nor 'ё'?
n % 80 - 1 ?
// output a single code point
[
// invert the case if this is a Cyrillic character
(n ^ 16 * (n > 0))
// and restore the original offset
+ 304
]
:
// output two code points
[
// the first one is either 1061 (Х) or 1093 (х)
1060 + n % 48,
// the 2nd one is the combining diaeresis
776
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~40~~ ~~39~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
63ÝD16^‚Ž4K+ç`‡•2.w2γ•3äçDl‚vy`«:
```
Would be just the first 15 bytes without the edge case of mapping `Ёё` to `Х̈х̈`.
-7 bytes thanks to *@Grimy*.
[Try it online.](https://tio.run/##DYvLSgJhGIZv5WttBI3hok0bd96DWNAiCFoEhrvfzmEn7WSalTo5lR2mpJqaLGhoG893C3Mj07944YHneRcWp2fmZpMkk45a2fFMPjaN3@FELhV5hdi0Y9Nxxpacv4GFdORGXnbeBsVS4ac/mSTURDfwdctuTXSXAb7wSkAoPGlFdJ1Al9XoipanhEP8UWHIl@gqPqFu66aNn7XCu@gOH7zxwiffVu2pGRH2qVLjwD6POOaEOqc0aHJGi3MuuKRNhy4uV/TwuOaGW/rccc8Dj0JZq/8)
**Explanation:**
```
63Ý # Push a list in the range [0,63]
D # Duplicate it
16^ # Bitwise-XOR each value with 16: [16..31, 0..15, 48..63, 33..47]
‚ # Pair it with the initial [0,63] list we duplicated
Ž4K # Push compressed integer 1040
+ # Add it to each integer in the inner lists
` # Push both lists separated to the stack again
‡ # Transliterate the characters in the first list to the second list
# in the (implicit) input-string
•2.w2γ• # Push compressed integer 10251061776
3ä # Spit it into three parts: [1025,1061,776]
ç # Convert each to a character: ["Ё","Х","̈"]
Dl # Create a lowercase copy: ["ё","х","̈"]
‚ # Pair them together: [["Ё","Х","̈"],["ё","х","̈"]]
v # Loop over both these lists `y`:
y` # Push the characters of the current list separated to the stack
« # Append the top two together: Х̈/х̈
: # And replace the Ё/ё with Х̈/х̈ in the (modified) input-string
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž4K` is `1040` and `•2.w2γ•` is `10251061776`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes
```
T`А-Па-пя-рЯ-Р`Ro
Ё
Х̈
ё
х̈
```
[Try it online!](https://tio.run/##Dcq5DcJQFAXR3FU8cn4N9IAowAQEJCAhCrBZjcwuckiI@YDYtwYczK3IOJjoTKfRbbbqeV4LWTq2eMdPC6eIg2MXVtsBccA@SwKtAg2zJM9Zm8Z4TYqGpjlnvHHlzss4KjWNuKunSH3FFWODLxsfvqYBnpemSor5pJSHacaTGxfe/ApaKCr9AQ "Retina 0.8.2 – Try It Online") Just a transliteration and a fixup of the two special cases. The characters to be transliterated are listed in mirror order so that `Ro` can be used to specify the reverse order for the transliteration.
[Answer]
# [Perl 5](https://www.perl.org/) (`-pC -Mutf8 -MUnicode::Normalize=NFD`), 37 bytes (27 chars)
```
$_=NFD$_;y;А-я;Р-ЯА-Пр-яа-п
```
[Try it online!](https://tio.run/##FY67agJRGIT7PMUfsMwpA@IiFoqddqkl6AoL6i5qClOtueiKiZqgtb6BR8VbjPoCFjMvlONJMcwM3xQTuPXKvTGxQjKfzcQKTsvBSHHoYKYwtxFThrZDK5yNwbewC82e1btwgBW0YIMdDoIF@8IOdnxhyFe2U4Ix9J3giJPwDRoHfjCy4yX72As/8YMt1vjF2aIhw9sbfmF9idDG5BKJRZM/P2h6fq1hVJA2KvfULMetPdS8ol9yE4m8X68@Vrxn9//@FQ "Perl 5 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~236~~ 166 bytes
```
func[s][rejoin collect[foreach c s[keep
case[c =#"Ё"["Х̈ "]c =#"ё"["х̈"]c < #"А"[c]any[c > #"Џ"c < #"ѐ"][(pick[#"А"#"а"]c < #"а")+ to 1 c - 1024 % 32]]]]]
```
[Try it online!](https://tio.run/##RU3LSsNAFN33K05HBEUFW12Jj39wO2QRphOMLUlI4sJdolZTqrYV/QT3o6KtrY8f6OLeL4qTCnrhXjive2LdKg91SzreTumdBEomjoz1cegHUGGno1UqvTDWrjqCQiLbWkc15SZaKuwtCcqFFPQ4LyCcBcEjS3B3XlR4F9YxFFI5bnBqA/sVHohfgYfCkSuRr9py4bLH/IWMWF1DGqJhSzfQ2GxuYxlbTaeaMor9IIUHQXfgKzLcs9sF39ILGdAbTWgGeuI@@JImfMYZn3N@ALonsw76pC/wBRma8TUX1vzMfXoH39CUxvRKH/RtpQFndVH7r3rgHo/Amc2N7ZN8UTOti/IH "Red – Try It Online")
[Answer]
# [PHP](https://php.net/) (7.4), 199 chars, 333 bytes
```
<?=strtr($argn,array_combine(($s=str_split)(АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёЁ,2),[...$s(РСТУФХЦЧШЩЪЫЬЭЮЯАБВГДЕЖЗИЙКЛМНОПрстуфхцчшщъыьэюяабвгдежзийклмноп,2),х̈,Х̈ ]));
```
[Try it online!](https://tio.run/##hY7JTsJgFEb3PsUvYdEmtQu3aNj5EmpIRSIk2jZtN@6oUigiYHGeR5yHggMgKC/A4rsvZP37BF3c1XdzztGzehBMJadNy7AMIa4YS6qkGIaymkprKws5NSMIcTNcU6a@nLNEAVvw0MA2drCLPezjAIc4wjFOcIoznOMCl7jCNW7QxC3ucI8HPOIJz3jBK97go4U23vGBT3yhgy56@EYfA/zgF0PKk01rtE4FcqhIJXKpTBtUoU2qUo3q5MGWJkVpVpbluClE6iJyo3RRuWEKOSNXQnPksnlRTASZdFZjsTk1lgjQYFSCT2V@DqMa5/iMY7roM7SowqiILtfneYCdZDzSl1gIZlTg5j6vcPlzmyroMapycYdnDDDkU53y42OwmaIuMvLkP023cppqBhMz/w "PHP – Try It Online")
Just a string replacement.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~103~~ ~~102~~ 101 bytes
```
-join$(switch -c($args){Ё{'Х̈'}ё{'х̈'}default{[char](2*(($_-band16)-8)*($_-in1040..1103)+$_)}})
```
[Try it online!](https://tio.run/##VVHtbhJREP2/TzHUa3dv3W2gGmNMjH0PY8i6bAuGUGTX1GTdZMEiUCwNTZ/A2P9b@gEUpS/gjzNPhLOLGp3kJvfOnHvOmZnmwaHfCqp@vb5Se/SCopXz9qDWUFZwWAu9KjmepdzWfqAjtCMTFz/7ZszjyORudqv4e@77ehi98qpu67W1s2VZquy8cRuV0lPtPNNb2bPWKBWfFLe3S6XiY/1IlXUc61VsGLuWQRK2RWTijLiHlAdyusQjXCEl3GKGBeGSh8SfMeMOJ/yJ2y8J50htwg8siY@QYsFfuC/gCQ8xJz7BHaa4wXfcS@mUk4Jp51pZmPhKmHKCuZwbwlIoE@HnfibTzgRvhWwitFe4FK1vnNjCySPCtRgYCu1MwB2hHogHPuYed8XAqZTukRZM0sY/nbXzNu7W3Ux4zB0S2BLXxGMsRL4nbpeY/2dR5pw7Ol4b62TjxoREY8RHlL14KFOaiviIB7mipo/0kKKcRAU2Kf9D0/dCvyJbVeV1uuUHsi5JbMqyd4Ms94CCZt0Nw1pjv5CDNpT1G@d4/ru/LPr5n@8bRmysfgE "PowerShell – Try It Online")
This script takes a splatted string. Unrolled:
```
-join$(
switch -CaseSensitive ($args){
Ё{'Х̈'}
ё{'х̈'}
default {
$offset = 2*(($_ -band 16)-8) # -band is 'Bitwise AND'
$offset *= ($_ -in 1040..1103) # is basic Cyrillic alphabet?
[char]($offset+$_)
}
}
)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes
```
FS¿⁼Ё↥ι⁺§хХ⁼Ёϊ¿№…А¦ѐι℅⁺℅ι⎇‹↥ιР¹⁶±¹⁶ι
```
[Try it online!](https://tio.run/##VY47TsNAEIZ7TjFstSuZIk2aFAhFFJEQRDwOsHI2xpJlm/UaQZcAgaDwiBAHoKE3ICAQHhegmDmRmTwKGGmq@eb7f39XWz/RUVm2EwuyEae523I2jAOpFIRtkKt7uY4yKbArPNhJU2N9nRkZKr43GXSyGeWZXHGNuGUOpKAe3jP5741hD8RPXyhVAxNlZmquJzl/b@o4MMwNmRM0FGqKz9V1rqd9Z@wsZMO2wlhHHO7BtrGxtodyzWSZ/NuLNXg30VSqHqybQDsjK1U1mXn4zB2qWlniDdAZFnTO2wO6wicsAF9whGPABxoAneKIjqhDx9RdBrzFwgP8xC@gEyxwTBfUZ/iRBvgGdInv@IrP@IHffLqmzuJCubQf/QI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS
```
Loop over the characters in the input.
```
¿⁼Ё↥ι
```
If the uppercase is equal to `Ё`...
```
⁺§хХ⁼Ёϊ
```
... then print the appropriate `х` or `Х` with its combining character...
```
¿№…А¦ѐι
```
... otherwise if it's a Cyrillic letter...
```
℅⁺℅ι⎇‹↥ιР¹⁶±¹⁶
```
... do some maths on its ordinal to create the character to output...
```
ι
```
... otherwise output the input character.
] |
[Question]
[
Given the name of a cation and anion, output "S" (soluble) or "I" (insoluble). The table we will be using is from wikipedia: <https://en.wikipedia.org/wiki/Solubility_chart>. It is copied at the end of the question for future reference.
**Input**: The cation, followed by the anion, separated by a space. The cation will be one of the following:
```
Lithium Sodium Potassium Ammonium Beryllium Magnesium Calcium
Strontium Barium Zinc Iron(II) Copper(II) Aluminium Iron(III) Lead(II) Silver
```
and the anion will be one of the following:
```
Fluoride Chloride Bromide Iodide Carbonate Chlorate Hydroxide Cyanide Cyanate
Thiocyanate Nitrate Oxide Phosphate Sulfate Dichromate
```
Each will have its first letter capitalized.
Example Input: `Sodium Chloride`
**Output**: A truthy value, or `S`, if it is soluble, falsey or `I` otherwise. If the wikipedia page lists anything else (e.g. slightly soluble, or reacts with water) or if the input is not in the form "cation anion," your program may do anything (undefined behavior), so it may output 'S', 'I', or anything else.
Table:
```
?,S,S,S,?,S,S,S,?,S,S,?,I,S,S
S,S,S,S,S,S,S,S,S,S,S,?,S,S,S
S,S,S,S,S,S,S,S,S,S,S,?,S,S,S
S,S,S,S,S,S,S,S,?,S,S,?,S,S,S
S,S,S,?,?,?,?,?,?,?,S,?,?,S,?
?,S,S,S,I,S,I,?,?,?,S,I,I,S,I
I,S,S,S,I,S,?,S,?,?,S,?,I,?,I
?,S,S,S,I,S,S,?,?,?,S,?,?,I,?
?,S,S,S,I,S,S,S,?,?,S,?,?,I,?
?,S,S,S,I,S,I,I,?,?,S,I,I,S,I
S,S,S,S,I,S,I,?,?,?,S,I,I,S,I
?,S,S,?,I,S,I,?,?,I,S,I,I,S,I
S,S,S,?,?,S,I,?,?,?,S,I,I,S,I
?,S,S,?,?,S,I,?,?,?,S,I,I,?,I
?,?,?,I,I,S,I,?,?,?,S,I,I,I,?
S,I,I,I,I,S,?,I,I,?,S,?,I,?,I
```
The rows are cations in the order listed above and the columns are anions. For example, since Magnesium Iodide is soluble, and Magnesium was the 6th cation and Iodide was the 4th anion, the 6th row and 4th column has the character 'S'. The `?` indicates undefined behavior.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 143 bytes
Returns **1** for soluble, **0** for insoluble.
```
s=>Buffer(`## 5)6.'04+ n:# (F* E"/$;&-"/"7&#.%`).map(c=>S+='1'.repeat(c-32)+0,S='')|S[parseInt(s.split` `[1].slice(1,7)+s[0]+s[1],35)%1325%508]
```
[Try it online!](https://tio.run/##vVRbb9owGH3nV1gwansJKZeyTq3CBBQ0a2ytFJ4WReAlpskU4sgOFUj8d@aQjEs6GNukKXJ8vtvx8WfL3@kLla4I4qQWcY9tZuZGmp3eYjZjAk0rFdDG7wxYv9FAdFcBaPgWDMrXb@6vauXr8u1VxahOsTGnMXLNjqWZsAENwWJGE@TWWk2s1XXLhBCvLTumQjISJUgaMg6DZAqmdsMxZBi4DDX0W6xJu@6oX8PRW21cbbSa7Wq7/t7Z9IEJbDgKEj9YzKEOLe5l4IknVMoMd@dzHmWwx8QqDDP8mT5HLE/p09DNGRLBoyTPpiIDX4PIVRNRIUQITgt4HKsuZEY3XMyDfIU8Z@sfMerlKVYQvjABnftSqbvVPAwXXAQeS7n88CfsCT7PEFE7yaJUfOMRTXaZGfy48gRf5ikrGu1RFh/7AXd31pcgyese85onn8vYz3zWIpxl6CFwfSUhNVKp41RqCSi5kzTtYJyzU0x2tqNvCaxCwblxTP6/CCZ/QjA5M6xXOCcoNo0czEUCchTPCcgJgl@vuicmv1NgndkCuWQL1gkFFxOQQh9O9sD61yaeuqqkIPkiBcXV/krBJQSvjvFQ6iU9ODqFYoAU@kFOX6RS@jD0jRkXA@r6CLk6WGFgdhRvd@@lOljmXgBcHkkeMiPkzwhJ9aa4QANQfRqg2IipN4g81LzBOhAsDc@QVBgSC9rK4QDTBGN75dhLB6zXO6i8ShP4ACB6/IQhuFNg2CUjDLFaFZfw5gc "JavaScript (Node.js) – Try It Online")
## How?
### Conversion of the input string to a lookup index
We first build a key by extracting the 2nd to 7th characters of the anion and adding the two first characters of the cation:
```
key = s.split` `[1].slice(1, 7) + s[0] + s[1]
```
Examples:
```
'Lithium Fluoride' --> 'luoridLi'
'Sodium Fluoride' --> 'luoridSo'
'Sodium Dichromate' --> 'ichromSo'
'Calcium Oxide' --> 'xideCa'
```
We turn this into a lookup index by parsing it in base-35 and applying a modulo 1325 followed by a modulo 508 (brute-forced values):
```
parseInt(key, 35) % 1325 % 508
```
### Compression of the lookup table
Because there are significantly more *soluble* pairs than *insoluble* ones, we fill all unused entries in the lookup with *soluble*.
By encoding soluble with **1** and insoluble with **0**, our lookup table essentially consists of long strings of **1**'s followed by a **0**:
```
11101110011111111111111111111101111111110111111111111111111111101111111111111101111111011111
11111111111011111111111111111111011111111111001111111111111111111111111111111111111111111111
11111111111111111111111111111111011111111111111111111111111011100111111110111111111111111111
11111111111111111111011111111110011111111111111111111111111111111111110110111111111111111011
11011111111111111111111111111101111110111111111111101101111111111111110110111111111111111111
11111011111101110111111111111110111110
```
We compress it by storing the lengths of the strings of **1**'s as ASCII characters in the range **[32-126]**.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~96~~ ~~92~~ ~~75~~ ~~70~~ ~~69~~ 65 bytes
```
p /ra|[SPm]o|^[^C]*F|h.*D/?1:/Le|[MAIZ].*y|[OPDFbv]|[tr]i.*S/?0:1
```
[Try it online!](https://tio.run/##bZfNbhpBEITveQofE6SY@OqL5R9ZQbIzSORkhKU1bMJKyy5aFitIPHuIw0xXVQ8c@3N3W1V29/R227fd4bC@GHbFfjoZr2bt/nX6ej8bPO6Xl4OH4c3V9fCp3E@fb0cvs8vBbj8N44fHt/fZftp3s@pyMBnefLu@Ohyeqn5ZbVcXj/W27apF@cnA/bL24K5rVxqP2oXLL7q3tin6rIOC77tF1/5xRbuiyWOt@Lms2nnGflS96xpcx/Gy3ayX@vPJtv6l8UM1X35I@Y8mHxJUe4ohPcWmPIVJuCVDt1ZLTNWWkERLKOkqOSFTnMKgzag3AZObQlE7bvtis3GCiaCZyGSTJOVSBfFZJ49ogaQlFzzxdeoFqdlBErLeNIXMfCERa25Xq7ZxzoDAGBDzBSDZwhK44rs4Qk@YlCxxwBWpIYDmB0DwbekGkJkBIF7cld2urp0ZRHCDyOwgSX5IFQzJOnlESyQteeKJr1NXSM0WkpD1pjFk5gyJWPNc/G5KP0FEsIbIrCFJ1kgVrMk6eURrJC1Z44mvU2tIzRqSkPWmNWRmDYlYc1/Uc2eMAdhiwEyxOFmCfBjiOiigGUhJVmisFWqDMTPB4uA60gAjJt9ifUf6rm16/5QA8TUBwoMCYm8Kq/is@E4eyePCNHtfHPF17pUBxUMDErLe8tyA4cUB0W1SdH6VxJh7JMZYIjG0DZKSuT6kWmJZHCnBtgZDSXf7IiIsixgGbSZrIgLsiBiK2peqmVPrMYLSY2Q6j0FSGdOgkVWIqC/@MKlDgERVdgSm6xgEtqCmY2iKjoHoGX38RT@PRl@oCQS6QEwbQNLHEmj0XRyhViYlvQ64ItUNaNoBgm9LD4DMBwDdcO16XXbeDWHcc2RYdUS27aSQCy/rljFZe5Jom8@jrNTtP2KsQKKQ/wJZhITYhUR6TdXbVZWdU0C8p4BwUIHYRcUqnlS@k0dyVDHNripHfJ27q0BxWIGErLecVmC4rUBOB@rMRJ0ZqdOZOhmqc1N1ZqzOzdXpYJ1O1vnROp2tfLjOTdfpePn/mqeyWPjpAuG3qBF8jBqwr1GU8HPUdXFEPkiRZF@kClyR@yY1iI9SA8G3lc9SQ/guNaAHRVW/l51cEzHmKRFj3BExtCMiJfOCkGqJ5XZICXY4MJR0dzJEhHshhkGbyaUQAc6EGFLt33bdV22zOXxt/gE "Ruby – Try It Online")
I'm not very good at generating hashes and lookup tables, so instead I opted to take advantage of all those question-mark wildcards to simplify the logical structure of the table, and then apply some pure Regex magic.
**Update**: Altered assignment of some question marks and further simplified the logic of matching.
**Update 2**: Just 2 months later, I've come up with another revamp of the table to save a few more bytes.
The table that we are going to produce looks like this:
```
Lithium 111101111110011
Sodium 111111111111111
Potassium 111111111111111
Ammonium 111111111111111
Beryllium 111101111110010
Magnesium 111101000010010
Calcium 011101111110010
Strontium 111101111110000
Barium 111101111110000
Zinc 111101000010010
Iron(II) 111101000010010
Copper(II) 011101000010010
Aluminium 111101000010010
Iron(III) 111101000010010
Lead(II) 100001000010000
Silver 100001000010000
```
Now, the following compounds can be considered soluble:
* `ra` Nit**ra**te, Chlo**ra**te
* `[SPm]o` **So**dium, **Po**tassium, Am**mo**nium
* `^[^C]*F` **F**luoride, but not **C**alcium or **C**opper
* `h.*D` Lit**h**ium **D**ichromate
Of the remaining compounds, the following are insoluble:
* `Le` **Le**ad
* `[MAIZ]i.*y` **M**agnesium, **A**luminium, **I**ron (and other cations with indicated charge), **Z**inc compounds with block of anions containing `y` (H**y**droxide-Thioc**y**anate)
* `[OPDFbv]` **O**xide, **P**hosphate, **D**ichromate, **F**luoride, Car**b**onate, Sil**v**er
* `[tr]i.*S` Stron**ti**um and Ba**ri**um **S**ulfates
Everything else is soluble.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~166~~ ~~161~~ 131 bytes
```
lambda n:chr(hash(n)%1482%737%388%310%295%262%254)not in'gwQFCAkOExUWHJ0gJyicLLKviDK3PEDDxslKztFUV1ja4ukdbe7x9Xd5'.decode('base64')
```
[Try it online!](https://tio.run/##RVFdbxoxEHznV6winXynVCgcEEikPhAIygXaENG0VT8ejG2wE5/35POlXP88sZ2rKj/MeGd2NfZWrZNo8tMePsKvk6bljlMw10zaVNJapiZLBqNpnkyGk2Q4nSbDwUWSX42T/DJP8vEoM@hAGXL487icz14ebo9P3@7uLw73rWLr9epVLVbDze1icaz16q9bPn0dPNNR88J3YnK8@s7HpM8FQy5SsqO1uByR7MSoU2hqn@dsrZxUTQlb5AE26GhdBzYrSzSB3Ajbah3YJ3owIopzqlnschaNiy5qA/xQhkHhi2lRZDDHqhI20pluShXndaqvrQXlUdwq/SrsWb@utHJp1qPmX7ylbtAqLmAu9Tu5sVgGLHzgUKd2h4a6zhHIXcstHqPY@kkdBuWLVMg6/lm56H6Izo3EupLhvm30PuBC@QVh6en/XL09WmB@GdD94HUPoLLKOCAfSP8ZlUlJsSU/9ymDcyD@nAPNfkPoo6Hv/WXZ6Q0 "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~180~~ ~~177~~ ~~151~~ ~~149~~ 147 bytes
```
def f(s):a,b=s.split();return bin(int('7YNQYE3M7HE5OU3HHE71UMXBVRATPSZTSCV0O4WI84X5KTNE92TMLA',36))[(int(a[1:4],35)|int(b[2:6],35))%3419%529%277-6]
```
[Try it online!](https://tio.run/##dVHbjtowEH3PV0RIqyTadFXuhQpFQKmwlltrdru7KQ8mhMbIsSPHqYrUf6ceJ4Co2ijJnDNnZjw6zo4qEbxxOu3ivb13c69P/O0gf8gzRpXrfZSxKiS3t5S7lCvX6b4uvrxOmvPudNJePjWn00m3/jR/GT1/Ha5X@G2Nx8/vl61v6EPrpf24Xkx6jfV8NnT8ZsfzQjOChPV@a@M3295voNuw0e8Y6t01W/XeXbvRu2t0u@86m1NE1KA2oyqhRWpjsYOwEorkOaBhmgoOYBTLI2OA5uQHj404JiwyXUoKrkwVkRDeKI9spJMuQp49FlkWSwOHrEipmVepOjeLyc6ImLKfsaydbbEIp4PaZ1YISXexPU5YCUZSpBCR3hXyRG4FJ6qqADA97qT4ZcSjHlJFUNYJFVGFF1SZ6qWpXCUizxLguGB7iJ9olOijNLyuZO2FtCObclvb1rfsTGp7bcd5OAh9eQ7CTgh@793o3rGde@J5G@gg0KE30QMsRbYsHtRqtQBjXH0BwtjC1wfS/@XBlQflg@G1IIkwAo50tJDhpYgCVOm4rEfneoxvOULnfvzXvHJPzdFFB@lGv3A4T1de@vV8@Ot9NDT7aAcqW53v3AFnSjMJY67xKKSb8LABWwPH/6e1Hnh78I27MS/SGO7TBZ9BoH50K@gr87zTHw "Python 2 – Try It Online")
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~387~~ ~~358~~ ~~353~~ ~~348~~ ~~341~~ ~~319~~ 297 bytes
```
var s,t:string;j:word;c:array[0..14]of word=(5055,8191,8191,8191,93,63,4143,175,4271,63,127,31,95,3,67);begin read(s);t:=copy(s,pos(' ',s)+1,6);j:=pos(t[1..2],'OxCyCaPhThDiHyFlIoSuBrChChNi')div 2;if'a'=t[6]then j:=12;write(c[pos(s[1..2],'LiSoPoAmBeMaCaStBaZiIrCoAlLeSi')div 2]shr(13-j)mod 2>0)end.
```
[Try it online!](https://tio.run/##TY7Pa4MwAIX/ldxMWCrGH3VVHNSMsUK3Fdxp4iHT2KRYI0lm51/v9FDY5R2@x/t4AzM16zbtUM/zyDQw2CbGatmf00tyU7pJ64RpzabSc10SVqoFK81g5EURfiQ78i92Ad4GOCRhgEkc4dCPyQqIH@NgaSO89DFKv/lZ9kBz1kCDUptktRomaPCgDHSAgw16WHZoOZCtyJbEdf0KOx@/dKLsJD7Fs3ydXrqDKn5yTQUV79JBjRyBn8rWYU5my21lBe/BoiB@etPScliXq83cbUdZqJPaX3P@xigrbM6@5EFTte@OvLj7KiM0JMHmgq6qAf6Th3jfuPNcyG7kGlDRKc0s/wM "Pascal (FPC) – Try It Online")
### Explanation:
```
var a:string='LiSoPoAmBeMaCaStBaZiIrCoAlLeSi'; //string containing first 2 letters of cations (can also be const)
//luckily, Iron(II) and Iron(III) are compatible, they can have the same outputs
b:string='OxCyCaPhThDiHyFlIoSuBrChChNi'; //string containing first 2 letters of anions (can also be const)
//the order is different from the Wikipedia chart;
//Chloride and Chlorate are next to each other to find the right index easier
//Cyanide and Cyanate are compatible - 1 column less
//overall, they are ordered to minimize the numbers in c
s,t:string;
i,j:word;
c:array[0..14]of word=(5055,8191,8191,8191,93,63,4143,175,4271,63,127,31,95,3,67);
//One number for each cation; one bit for solubility of particular combination; the bit for input combination will be found using i and j
begin
read(s); //put input into s
t:=copy(s,pos(' ',s)+1,6); //find the 2nd word in s (characters after space), take first 6 letters and copy them into t (6th letter is needed later)
i:=pos(s[1..2],a)div 2; //position of first 2 letters of cation in a
//divided by 2 to get index for c
//*in golfed code, expression for i is inserted directly into write function
j:=pos(t[1..2],b)div 2; //position of first 2 letters of anion in b
//divided by 2 to get the particular bit of c[i]
if(j=11)and(t[6]='a')then j:=j+1; //if the anion is Chlorate, j is wrong and needs to be increased (specifically to 12);
//only Chlorate has 'a' as 6th character, j doesn't need to be checked, but it's here for easier understanding
writeln((c[i]shr(13-j))mod 2>0); //take i-th element of c, shift it right to put the correct bit at last position,
//extract that bit, check if greater than 0
end.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~67 61 60 50 47~~ 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OḌ%⁽Ƭ%⁽£ṇ%⁽¡ẹ%249ḟ“ıA¬ɲḃẏCċtȯƁƤçȤċŒḲOƲ’D‘Ĥ
```
A monadic link returning a list which is empty for `I` and non-empty for `S` (in Jelly empty lists are falsey while non-empty ones are truthy).
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y4e1UeNew@3HVoDog8tfrizHcxY@HDXTlUjE8uHO@Y/aphzZKPjoTUnNz3c0fxwV7/zke6SE@uPNR5bcnj5iSVHuo9Oerhjk/@xTY8aZro8aphxuOXQkv@PGuYGA7Hn4Xb7//99MksyMktzFQIy8osLMhJLUgE "Jelly – Try It Online")** (footer `”S”IÇ?` is `if LastLink(x) is Truthy then "S" else "I"`)
Or see [all cases formatted as a grid](https://tio.run/##NY5BS8MwHMXvfopeBnpU9OBJtg61OO2gnrzFNtpI2pQ0FXvrVNxhgrCTgiLiwMtAHB66iZd2K/NjpF@kJnEewvv933v/JGcQ47iqTJ7e1srOd36TDaVmr3zcVfDCJ@Pa2vomT5/L5HH6Uc@GPyOeXvHJnT7tsfl70SkG@dt8MO3N@jwdmcWoTB6aZXKfX2eDin99CrO8HM76wZ6QMnmyxDHy7paYwtWNnapqIeaiyNMs4khpEwbCUFLd84gvoQFpjLGkfXDqQxXqANtqi1HiM9UCVMoR8m3NEOayYaxoOgkCSBXWceQhdd8iFV4LAkeFFsLnkC5t44hQ5EBNd/EfNCjxpBrid9IH9Jj4gC0aEnZjh5ILFcbA/1eZHLqI2As@QEy1TdVsuyQMXDlbET6R2kS2K54S@As "Jelly – Try It Online") matching the order of the grid in the OP.
### How?
After creating sets of inputs that must be `S` and `I` and evaluating these inputs as base ten (Python: `dec=lambda s:sum(10**i*ord(c) for i, c in enumerate(s[::d]))`) and using a few loops of modulo-ing values and set checking the hash used here was found.
The insoluble key integers are created in the code by evaluating a base 250 encoded integer, converting it to base ~~25 ...16~~\* ...10 and cumulatively summing the result...
\* the base reductions were achieved by adding some redundant keys
```
OḌ%⁽Ƭ%⁽£ṇ%⁽¡ẹ%249ḟ“...’D‘Ĥ - Main Link: list of characters e.g. "Calcium Carbonate"
O - cast to a list of ordinals [67,97,108,99,105,117,109,32,67,97,114,98,111,110,97,116,101]
Ḍ - convert from base ten 778907829795030961
⁽Ƭ - base 250 literal = 4258
% - modulo 625
⁽£ṇ - base 250 literal = 1721
% - modulo 625
⁽¡ẹ - base 250 literal = 1215
% - modulo 625
249 - literal 249
% - modulo 127
¤ - nilad followed by link(s) as a nilad:
“...’ - literal in base 250 = 382193517807860310905428231939605402667395154
D - convert to decimal = [3,8,2,1,9,3,5,1,7,8,0,7,8,6,0,3,1,0,9,0,5,4,2,8,2,3,1,9,3,9,6,0,5,4,0,2,6,6,7,3,9,5,1,5,4]
‘ - increment (vectorises) = [4,9,3,2,10,4,6,2,8,9,1,8,9,7,1,4,2,1,10,1,6,5,3,9,3,4,2,10,4,10,7,1,6,5,1,3,7,7,8,4,10,6,2,6,5]
Ä - cumulative sum = [4,13,16,18,28,32,38,40,48,57,58,66,75,82,83,87,89,90,100,101,107,112,115,124,127,131,133,143,147,157,164,165,171,176,177,180,187,194,202,206,216,222,224,230,235]
- ...note the redundant keys are ---> 48 66 75 115 187 216
ḟ - filter discard (implicit wrap) [] (if 127 was not in the list above this would've been [127])
```
] |
[Question]
[
## Introduction:
Although I originally had a Dutch song in my head, where the lyrics are: "*Doe 'n stapje naar voren, en 'n stapje terug*" (which translated to "*Take a little step forward, and a little step back*"), when I searched for the full lyrics, I realized they only got back and forth, and never sideways.
So, instead I now use the lyrics of [Mr C The Slide Man a.k.a. DJ Casper - Cha-Cha Slide](https://www.youtube.com/watch?v=wZv62ShoStY) for this challenge.
If we ignore everything else and only look at the words "left", "right", "back", and "hop" (I counted "hop" as forward) including the mentioned amounts, the full song will have the following list (I'm using the abbreviations LRBH here):
```
LBHRLLBHRLBHHRRLLLRLBHHHHRRLLLBHHHHHRLRLRLHRLLBHHLRLBHH
```
Here the full song lyrics in a hideable JavaScript code-snippet (to save space), where the moves and amounts are surrounded with blocked brackets:
```
To the [left], take it [back] now y'all
One [hop] this time, [right] foot let's stomp
[Left] foot let's stomp, cha cha real smooth
Turn it out, to the [left]
Take it [back] now y'all
One [hop] this time, [right] foot let's stomp
[Left] foot let's stomp, cha cha now y'all
Now it's time to get funky
To the [right] now, to the [left]
Take it [back] now y'all
One [hop] this time, one [hop] this time
[Right] foot [two] stomps, [left] foot [two] stomps
Slide to the [left], slide to the [right]
Criscross, criscross
Cha cha real smooth
Let's go to work
To the [left], take it [back] now y'all
[Two] [hops] this time, [two] [hops] this time
[Right] foot [two] stomps, [left] foot [two] stomps
Hands on your knees, hands on your knees
Get funky with it, aahhhhhhhhhh yaaaa
Come on, cha cha now y'all
Turn it out, to the [left]
Take it [back] now y'all
[Five] [hops] this time
[Right] foot let's stomp, [left] foot let's stomp
[Right] foot again, [left] foot again
[Right] foot let's stomp, [left] foot let's stomp
Freeze, everybody clap yo hands
Come on y'all, check it out
How low can you go?
Can you go down low?
All the way to da floor?
How low can you go?
Can you bring it to the top?
Like it never never stop?
Can you bring it to the top?
One [hop], [right] foot now
[Left] foot now y'all
Cha cha real smooth
Turn it down, to the [left]
Take it [back] now y'all
One [hop] this time, one [hop] this time
Reverse, reverse
Slide to the [left], slide to the [right]
Reverse reverse, reverse reverse
Cha cha now y'all
Cha cha again
Cha cha now y'all
Cha cha again
Turn it down
To the [left], take it [back] now y'all
[Two] [hops] two hops, two hops two hops EDIT: Made a mistake here, but bit to late to change it now..
```
## Challenge:
Now onto the challenge itself. We take one, two, or three inputs *†*. One of them is a list of index-integers (so either non-negative for 0-indexed; or positive for 1-indexed). (The other inputs are optional and explained in the challenge rules.)
Every test case will start at a position `{x=0, y=0}`.
Now use the lyrics-list of moves and *remove* all moves at the given indices of the input-list. Then 'walk' over the moves (up to the largest index of the input-array) and output the position you'll end up at.
The moves will change the coordinates as follows:
- `R`: `x+1`
- `L`: `x-1`
- `H`: `y+1`
- `B`: `y-1`
## Challenge rules:
* The moves-list can be accessed any way you'd like. *†:* Can be an additional input; can be in a separated file on disk you'll read from; can be in a class-level variable you access. It will have to be in the form of `L`, `R`, `B` and `H` though (can be a string or character-list/array), so you cannot save the moves-list as `1`s and `-1`s or integers.
* The moves-list given above is hard-coded and will always be the same. (Which is also why it's fine to put it as class-level field instead of taking it as an input if this helps the byte-count of your answer.)
* Input-list can be both 0-indexed or 1-indexed (up to you)
* We only 'walk' the moves up to and excluding the largest index of the list.
+ *†:* You are also allowed to take this last item as separated integer input, instead of the last item of the input-array.
* Output of the x and y coordinates we end up at can be in any reasonable format (integer-array containing two items, delimited string, printed to STDOUT on two separated lines, etc.)
* You can assume the input-list is sorted from lowest to highest (or highest to lowest if that's what you prefer, in which case the first item is the initial size of the moves-list - if not taken as separated input). And it also won't contain any duplicated indices.
* If the largest index of the input-list is larger than the list of moves above (55 moves are in the moves-list above), we wrap around to the beginning of the list again (as many times as necessary depending on the largest index of the input).
* You are allowed to output `y,x` instead of `x,y`, but please specify this in your answer if you do.
## Example:
Input: `[0,4,8,10,13,14,27,34,42,43,44,50,53,56,59,60,64]`
Here the moves and (0-indexed) indices above one-another:
```
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64
L, B, H, R, L, L, B, H, R, L, B, H, H, R, R, L, L, L, R, L, B, H, H, H, H, R, R, L, L, L, B, H, H, H, H, H, R, L, R, L, R, L, H, R, L, L, B, H, H, L, R, L, B, H, H, L, B, H, R, L, L, B, H, R, L
```
Removing the indices of the input-list, we'll have the following moves-list remaining:
```
1, 2, 3, 5, 6, 7, 9,11,12,15,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,35,36,37,38,39,40,41,45,46,47,48,49,51,52,54,55,57,58,61,62,63
B, H, R, L, B, H, L, H, H, L, L, L, R, L, B, H, H, H, H, R, R, L, L, B, H, H, H, H, R, L, R, L, R, L, L, B, H, H, L, L, B, H, L, H, R, B, H, R
```
Now if we walk from position `{0, 0}` over the remaining moves, we'll have the following new coordinates after every move:
```
{0,0};B,{0,-1};H,{0,0};R,{1,0};L,{0,0};B,{0,-1};H,{0,0};L,{-1,0};H,{-1,1};H,{-1,2};L,{-2,2};L,{-3,2};L,{-4,2};R,{-3,2};L,{-4,2};B,{-4,1};H,{-4,2};H,{-4,3};H,{-4,3};H,{-4,5};R,{-3,5};R,{-2,5};L,{-3,5};L,{-4,5};B,{-4,4};H,{-4,5};H,{-4,6};H,{-4,7};H,{-4,8};R,{-3,8};L,{-4,8};R,{-3,8};L,{-4,8};R,{-3,8};L,{-4,8};L,{-5,8};B,{-5,7};H,{-5,8};H,{-5,9};L,{-6,9};L,{-7,9};B,{-7,8};H,{-7,9};L,{-8,9};H,{-8,10};R,{-7,10};B,{-7,9};H,{-7,10};R,{-6,10}
```
So the final output will be: `{-6, 10}`
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
0-indexed input: [0,4,8,10,13,14,27,34,42,43,44,50,53,56,59,60,64]
1-indexed input: [1,5,9,11,14,15,28,35,43,44,45,51,54,57,60,61,65]
Output: {-6, 10}
0-indexed input: [55] (Note: There are 55 moves in the unmodified list)
1-indexed input: [56] (Note: There are 55 moves in the unmodified list)
Output: {-6, 11}
0-indexed input: [0,1,4,5,6,9,10,15,16,17,19,20,27,29,30,37,38,39,41,44,45,46,49,51,52]
1-indexed input: [1,2,5,6,7,10,11,16,17,18,20,21,28,30,31,38,39,40,42,45,46,47,50,52,53]
Output: {10, 16}
0-indexed input: [2,3,7,8,11,12,13,14,18,21,22,23,24,25,26,31,32,33,34,35,36,38,40,42,43,47,48,50,53]
1-indexed input: [3,4,8,9,12,13,14,15,19,22,23,24,25,26,27,32,33,34,35,36,37,39,41,43,44,48,49,51,54]
Output: {-18, -7}
0-indexed input: [0]
1-indexed input: [1]
Output: {0, 0}
0-indexed input: [4,6,7,11,12,13,15,17,20,28,31,36,40,51,59,66,73,74,80,89,92,112,113,114,116,120,122,125,129,134,136,140,145,156,161,162,165,169,171,175,176,178,187,191,200]
1-indexed input: [5,7,8,12,13,14,16,18,21,29,32,37,41,52,60,67,74,75,81,90,93,113,114,115,117,121,123,126,130,135,137,141,146,157,162,163,166,170,172,176,177,179,188,192,201]
Output: {-17, 37}
0-indexed input: [25,50,75,100,125,150,175,200,225,250]
1-indexed input: [26,51,76,101,126,151,176,201,226,251]
Output: {-28, 49}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~98 ... 58~~ 55 bytes
```
->a{([*0..a[-1]]-a).sum{|c|-1i**(m[c%55].ord%19)}.rect}
```
[Try it online!](https://tio.run/##Lc6xjoMwDAbgvU/RpSogYyVg02Pghk4MTF2jDLnQ6m5Ii2iRWhGenQu0smR90m9b7oef1@yqfXOsT83ajnV9CmxWfbwqZEu95@p3vkf7a/r75lLN6bcZI5UIRKNSqXVqYrwPbvTWp/IvSSKn7I5Z461vd7KMJ@zP9jHN3failACCL5ACZA6SIDtATkAZUA5EwAI4By6ASygEFKT1Zl0L5z4SAUFRhsgcozPd6J8@Ct8wxWhvw/Ux@tY71S4/VNWCp56m@R8 "Ruby – Try It Online")
### Explanation:
The main trick is using complex numbers to represent moves: 'B' is -i, 'H' is +i, 'L' is -1 and 'R' is +1. If we convert all the moves into complex numbers, then with a single sum we get the right result.
I tried different ways, but then I found the magic number 19: we don't need to fiddle with regex matching because:
```
B is ASCII 66; 66%19=9 and i^9 = i
H is ASCII 72; 72%19=15 and i^15 =-i
L is ASCII 76; 72%19=0 and i^0 = 1
R is ASCII 82; 82%19=6 and i^6 =-1
```
So, put that all together, sum, invert the sign, and we're done.
Thanks Jakob for -3 bytes
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 12 bytes
Saved 3 bytes thanks to *Erik the Outgolfer*
```
ÝsKèIêRS¢2ôÆ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8Nxi78MrPA@vCgo@tMjo8JbDbf//G5kacEUbmeqYGuiYm@oYGhjoGAJ5hkCuIZBvBOQbAflAVbFcPk4eQT5gwsnDIwjI9AGzoGwwCygHghB1HhB5AA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##TZAxTgNBDEV7ThGl/khjjz2z01CkWkSqUEYpQOIESEi5QG5BgygQNX2kzMGW790godXOeOTv72cnf3qWl@ntePmc@vvrQ/@679@7x8uH9p9@mo7rfl7d3q36eY1pv08wDJAEyRCDVmSDKSzDDJ7gGV7gDSWh2AF7dx7Us9BR0OZihxRIhTRoml0GaENOyIwbTMLOHFZgDS5wpY0io0Z/gegVQVgpUIVmKIkcWpAFmeIcdNmRSzSw9EdaYcMCG2z8jWT1n60HXJANs1WJ2oDgWBQSgltIGBoa9VETRQETY7FOyCNEEQ4lZBBaCD2EIwn3I4WtCjUlNkFN5btG11gLBxxiNxwrBR2NCBvplBZbPkPONCfn7elwuNluxt12PjbjuGO4naNrPEfMxbfoxiX/Cw)
**Explanation**
```
Ý # push range [0 ... input_int]
sK # remove all elements in input_list from this range
è # cyclically index into the moves-list with the remaining elements
Iê # push the unique chars of the move-list, sorted
R # reverse
S¢ # count the occurrences of each char in "RLHB"
2ô # split into 2 parts
Æ # reduce each part by subtraction
```
[Answer]
# JavaScript (ES6), 85 bytes
As per the challenge rules, this code expects the global-scope string **m** to hold the list of moves. (Saving 3 bytes, as suggested by @KevinCruijssen.)
Takes input as a list of 0-based indices, ordered from lowest to highest.
```
a=>a.map(g=i=>j++<i&&g(i,p=m.search(m[~-j%55])*3%5,x+=--p%2,y-=--p%2),j=x=y=0)&&[x,y]
```
[Try it online!](https://tio.run/##ZZFPb9pAEMXv@RS@QHB5Jjv7z7bazSEnDpxyRRwsSigoBBSqClSlX52@sUMT1bJkz2rfzJvf87b51RyXr5vDz@Jl/3112WUpu509TB9n7ethOn1kOWur97qteKdPp5t297dfb57SpUn3zWTXHEbrtEn32/H422Y4XI82OKTd5LhqXpc/Rrv5n2I7CGGRf3GDgNM4FcVhYHEuuiLHNp3SOZl8OJyfcF5clvuX4/55NXner0dPo7mBRwUxEAfxsCWch7fwDt4jGASHEBFqRIPoF3me3d1lv4uITMzbzX/TdJFPAukJ6EPDgIi6NQ2QCCkhNaxRd1vDGTiuUcHV8KJr@AAf4WsEQbBXC/ZnEnsWFg6lMgnEvmNJBSuwFtbBkjLARjiBo9gpsQtwUT29udKX8FUXwD8mjsmKsg91FXChfiaesOWnbYLyKmzVbhDVUrmYMIXcnT/EoKpRU6892qQMmhT7hBhCAmFUwtWFI4QzhCkJf5VEWkVqooZLTclzqa6aNHOpNG6mYcwHWInM9cHowgC015jOk0edxV6myW/4mEGezNdvl78 "JavaScript (Node.js) – Try It Online")
### How?
Each move character is converted to its position in the move string `"LBHR..."`. We multiply the result by **3** and apply a modulo **5**, which gives **p**. We then have:
* **dx = ((p-1) mod 2)**
* **dy = -((p-2) mod 2)**
Where the sign of **a mod b** is that of **a**.
```
character | position | * 3 | mod 5 | dx | dy
-----------+----------+-----+-------+----+----
'L' | 0 | 0 | 0 | -1 | 0
'B' | 1 | 3 | 3 | 0 | -1
'H' | 2 | 6 | 1 | 0 | +1
'R' | 3 | 9 | 4 | +1 | 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Rḟị⁵ċⱮ⁵QṢṚ¤_2/
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4Y75D3d3P2rceqT70cZ1QDrw4c5FD3fOOrQk3kj/////Zqb/ow11THUsdQwNdQxNdAxNdYwsdIxNdUyMdUxMdExMdUyB0iY6puY6ZgY6ZoY6Zqax/32cPIJ8wISTh0cQkOkDZkHZYBZQDgQh6jwg8gA "Jelly – Try It Online")
Argument 1/Left argument: Maximum 1-based index.
Argument 2/Right argument: 1-based indices.
Argument 3: Moves-list as a string. Function is still reusable if the third command-line argument is used for this purpose.
[Answer]
# Java 10, ~~129~~ ~~119~~ ~~112~~ ~~107~~ ~~100~~ 86 bytes
```
a->m->{var r=new int[2];for(;m-->0;)r[s[m%55]/73]-=a.add(m)?s[m%55]*3%5-2:0;return r;}
```
Takes the maximum as additional input; moves-list is a character-array on class-level.
Inspired by [*@Emigna*'s 05AB1E answer](https://codegolf.stackexchange.com/a/167061/52210).
-7 bytes thanks to *@Jakob*.
-14 bytes thanks to *@Geobits*.
[Try it online.](https://tio.run/##fVPbbtpAEH3PV6wiRbKrsbtXG5dA1VSqqERfkr4hP2zBpKbYoPWSKkJ8O5lZ3FIpDUJCAztnzmV3VvbJJqvFr@N8bbuOfbN1u79irPPW13M2/2ndrGQdG7Hr6d3kfhq@7iaTeyynoerrUOEZfU59k9P5deo3n3HMJ@fscxQPcfh5/grZ052v1@ly1859vWnTL31xez777qrqofK3X1tfPVZuDBdxfRewuvWzcjxmS1R/tMm4Scb7J@uYG7XV73Aqy@Fy46JhkyRjPozdrJs1N8aU73NVJiOb2sUiauKP/b/v1I1J5Ac@dJXfuZa54eHY29nufqzRTu/qaVMvWINJRg/e1e0jJmhjSpUxX3U@Ivpe5azcc9AwAMFBKBAaZA5Kg5agFWgNhoNRYDIwBWT8ACzTIcP/jOIlMGPeOiUigVQGMigCnQGRgchBFCB54B2ALEBxUFgXoAUJ0AZ0BroAI5DdyLfnS1CQkxUBQvZuBI4UICVIBRLNGZAZKAEKmxUZVQZURsya/zGdgx6gb2JTl7zyt6VoNJn/I8SQTzI5COQZsRkRMsVGlI1XwGFQQIH9hCEQyaeEECfQgUDxAvMRqFrgCIEzBKYj8HJEhlQZ9mQUKvbk@DsnVkoYIxlQzBSg5BdkIwPeN@E4P/HhT5qDKAzREN5cwGPSeAfUdnoGh6vzqoVHGTB/@5kNS8Ka/nE@PHe@atLNzqdbfLd@3UbnRQv72@Eyn950FIX1ipep3W7Xz0HIq419DbfdtEYJNo7jHthgedJ6OL4A)
**Explanation:**
```
a->m->{ // Method with Integer-Set & int parameters and int-array return
var c=new int[2]; // [x,y] result-array, starting at {0,0}
for(;m-->0;) // Use the `m` input as index, and loop in the range (`m`, 0]
r[s[m%55]/73]-= // Subtract from either x or y based on the character:
a.add(m)? // If the input-set doesn't contain the current index `m`:
s[m%55]*3%5-2 // Modify the x or y coordinate based on the character
: // Else:
0; // Leave the x or y coordinate unchanged
return r;} // Return count(R)-count(L) and count(H)-count(B) as result
```
`s[m%55]/73` maps to either the x or y coordinate depending on the character ([Try it online](https://tio.run/##NYyxDsIwEEP3fsUpU6KKMjAgwQQsDLDQERiOK9CUNKmSa6UK9dtDQGKyLT@7wQFnTfWKkQyGAEfU9p0BdP3NaILAyEkGpytoUyVL9to@z1dA9cUAHs5LqtEDrcR2fziJgt0u5Y33OEqlfhBAOQa@t4XruejSAxsrKRcXFrlMSf09zZcLpdZpNGVTjB8)):
```
Letter Unicode value /73
B 66 0
H 72 0
L 76 1
R 82 1
```
`s[m%55]*3%5-2` maps to the correct `+1` or `-1` depending the character ([Try it online](https://tio.run/##VYw/C8IwFMT3fopHQEgs7aC4KB3UxUEXO6rDM/VPatqU5LVQpJ89RkHQ6e5@d1yJHSZl8fBeanQOdqjqZwTQtGetJDhCCtIZVUAVKp6TVfXtcAIU7xnA1Vgu72hBztlqs92zlMw65KW12HMhPiOAvHd0qVLTUtqEB9I1lzE7Eot5SOLXcznOpuIPjLLZF8hkIsQivA7R4P0L)):
```
Letter Unicode value *3 %5 -2
B 66 198 3 1
H 72 216 1 -1
L 76 228 3 1
R 82 246 1 -1
```
[Answer]
# Python 3, 85 bytes
`b` is the index list (a `set`) and `l` is the end index. The move list (a string or character list) appears free as `s`. This is a port of [*G B*'s Ruby answer](https://codegolf.stackexchange.com/a/167062), and an explanation of the approach can be found there.
```
def f(b,l):r=sum(-1j**(ord(s[i%55])%19)for i in set(range(l))-b);print(r.real,r.imag)
```
[Try It Online](https://tio.run/##TZIxT@NAEIVr/CvcILzRA@3s7qxtTjRUKVLRIgpzODmfQoJsrjghfnt4YwcJRYpm12/efPPst//vf46HeJrKu/Jqc79@2Mx/9@v1A8vNXJ3rueIz@y269fL86vTSb8tt9Yy9ux3vpn@v1bX8Xa2q4/hSTY/DpeqTu5TWbY9jOZTDoZz692rsDru@2jt3/ex@vY3DgVc3Y9/tMd4Mr93OnYrf3dQb2GNxUX14JDQQD4mQhFAjJqSAFJES1EMjNENbZP@JMicHttkkh1J1PtFEaKPIaGcrhWRIDWkR/OzZILSIHpF1iyRmnhQpI7VQobOGxSsgojYkgYQzlbBdEAJCRCCkImREQaQ4GnBUxGxTkv@Gr5Ea8ptz/MnslzGJsPWPIWq8BtvMxtmcVOa9KSQSY/JoWrTUW481GZptyj4hnRBMuKeQSGgh9BBuKQxQMkdlarKFQ03Nc21TLSmu21hcFkTwZ0S6MX/TeL9482g9VDAMNa2etUyHudmVvZKnorCPoht3k30X8wu/LS621cqu3OkL)
## Ungolfed
```
def f(b, l):
r = sum(
-1j ** (ord(s[i % 55]) % 19)
for i in set(range(l)) - b
);
print(r.real, r.imag)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
:wX-)Jw19\^s_&Zj
```
[Try it online!](https://tio.run/##pZDNCsIwEITveQpPijBCdrO7bT0WD0V6Eg9i/b2J6EnBx6/b6BuUQJiPySYzeV7fj/7SLz@7xXz9oepwep2n@3t/W21709ARFBWIQAJScImkkAQRiELdFmgBizCC6THM2rrZtHmrm2bjss3qr7Nyb1i/c83PnwW10KkdJ5Mxd6QhMntoQwGKObmBXJfgCKZcoUKKSIRUQiKEhy5ikAIaoT6exhQhzzBmnjWGjm343cKzR6/gRI7kzM7szDrmkS8 "MATL – Try It Online")
Takes 3 inputs like the Jelly answer, the largest index, the list of indices to skip, and the 55 character array.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~148~~ ... 130 bytes
```
import StdEnv
$i=foldr(\a(x,y)|any((==)a)i=(x,y)=case m.[a rem 55]of'H'=(x,y+1);'B'=(x,y-1);'L'=(x-1,y);_=(x+1,y))(0,0)[0..last i]
```
[Try it online!](https://tio.run/##Rcxda4MwFAbge39F6AoaepRYE/dRciMbOPCqvXQyQtQR0Dg0HRP225dFLYzA4Une80Z2jdC2H@pr16BeKG1V/zmMBl1M/aK/vL3i7dDVY/Amgm@Y8Y/QcxBwjgVWfH3hUkyuGpUCjU2PGKuG1s/9NTzE@ORnm8PFxeIwdrXTu9NhEQ4IEFySKOrEZJCqbI@eOEe7IsvPxTqyPD87FqtuXuWy5Wx7@ZbvvIsRo/HukNK1ks2EOCoJUHiAmECcQEzheA8JBXoEmgClwAiwBFgK7BFSAimtXLu9amnUoF197/H/6@1X@yvbTnxMNnwt7POsRa/k9Ac "Clean – Try It Online")
Defines the function `$ :: [Int] -> (Int, Int)`, taking a list of (sorted from smallest to largest) indices to be removed from the moves before `foldr`-ing the applicable operations over `(0,0)`.
] |
[Question]
[
Shuffling a deck of cards is hard for kids, so they must figure out ways to get a reasonable well shuffled deck as simply as possible.
One way to do this that gives reasonably good results is:
1. Take the top card out and insert it a random place in the deck
2. Take the bottom card out and insert it in a random place in the deck
3. Continue until you believe it's good enough.
Note that you shall never insert a card in the top or bottom spot, it should be placed somewhere *in* the deck.
---
Instead of shuffling cards, we'll shuffle alphanumerical characters: `0-9`, `A-J`, `a-j`, `q-z` and `Q-Z`.
Start with the string shown below and shuffle the characters the way it's described above. You can choose if you want to continue shuffling infinitely or shuffle the cards 100 rounds (100 cards from the top and 100 cards from the bottom).
```
0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ
```
The challenge is to display the characters being shuffled. Each "shuffle" (take out and insert card) shall take between 0.25 and 0.35 seconds.
The gif below shows an example output:
[](https://i.stack.imgur.com/eh7TU.gif)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
---
*"Why don't you have `a-t` instead of `a-j`, `q-z`?"* Because this shall illustrate suits of cards, not just characters. And yes, there are 5 suits.
---
Note: I have decided to stop using the check mark on [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")-challenges. Relevant meta posts [here](http://meta.codegolf.stackexchange.com/a/8363/31516) and [here](http://meta.codegolf.stackexchange.com/a/10140/31516).
[Answer]
## JavaScript (ES6), ~~192~~ ~~188~~ 185 bytes
```
document.write('<pre id=o>')
s='ABCDEFGHIJQRSTUVWXYZ'
a=[0,...123456789+s.toLowerCase()+s]
setInterval('o.innerText=a.join``;a.splice(Math.random(s^=1)*48+1,0,s?a.pop():a.shift())',250)
```
Edit: Saved 4 bytes thanks to @L.Serné. Saved 3 bytes thanks to @Arnauld.
[Answer]
## Perl, 117 bytes
```
@F=(0..9,a..j,"q"..z,A..J,Q..Z);{print"\r",@F;splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F;select$,,$,,$,,.3;redo}
```
To run it:
```
perl -e '@F=(0..9,a..j,"q"..z,A..J,Q..Z);{print"\r",@F;splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F;select$,,$,,$,,.3;redo}'
```
Explanations:
-`@F=(0..9,a..j,"q"..z,A..J,Q..Z)` creates the initial deck, and stores it in `@F`.
-`{...;redo}` executes `...` forever.
-`splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F` alternatively remove the first/last element from the deck and insert in at a random position (while incrementing `$|`, so the prints aren't buffered),
- `print"\r",@F` prints the deck,
- `select$,,$,,$,,.3` sleeps for 0.3 seconds (Perl's `sleep` can't sleep for less than 1 second),
[Answer]
## Python 3, ~~199~~ ~~196~~ ~~192~~ 186 bytes
Saved 4 bytes thanks to TuukkaX, and 6 bytes thanks to FlipTack!
```
import time,random
s="abcdefghijqrstuvwxyz";s="0123456789"+s+s.upper()
f=0
while 1:print(end="\r"+s);time.sleep(.3);s,e=s[1^f:50-f],s[f and-1];i=random.randint(1,49);s=s[:i]+e+s[i:];f^=1
```
Uses Python 3's `print` function to suppress newline, shorter than Python 2's `sys.stdout.write`.
Uses a flip-flop variable to switch between moving the top and the bottom cards.
Ungolfed:
```
from random import randint
from time import sleep
string = "abcdefghijqrstuvwxyz"
string = "0123456789" + string + string.upper()
flip_flop = 0
while True:
print("\r"+string,end="")
sleep(0.3)
string,char = string[not flip_flop:50-flip_flop], string[flip_flop and -1]
position = randint(1,49)
string = string[:position] + char + string[position:]
f = not f
```
[Answer]
# MATL, ~~62~~ ~~58~~ 56 bytes
*2 Bytes saved thanks to @Luis*
```
4Y2'A':'J'tk'Q':'Z'tk&h`48YrQJh&)@o?l&)wb}wO&)]&htD3&XxT
```
This version will run indefinitely. Try the online demo at [MATL Online](https://matl.io/?code=4Y2%27A%27%3A%27J%27tk%27Q%27%3A%27Z%27tk%26h%6048YrQJh%26%29%40o%3Fl%26%29wb%7DwO%26%29%5D%26htD3%26XxT&inputs=&version=19.7.0), an experimental online interpreter that supports dynamic output. This will run for 30 seconds (a hard limit imposed by the online version) if it isn't killed first.
**Explanation**
```
4Y2 % Predefined literal for the characters '0'...'9'
'A':'J' % Create an array of the characters 'A'...'J'
tk % Duplicate and make lowercase
'Q':'Z' % Create an array of the characters 'Q'...'Z'
tk % Duplicate and make lowercase
&h % Horizontally concatenate everything
` % Do...while loop
48YrQ % Determine a random integer between 2 and 49
Jh&) % Split the string at the selected location
@o? % If this is an odd time through the loop
l&) % Grab the first character
wb % Move it to the middle of the stack of three strings
} % Else...
wO&)% Grab the last character and move it to the middle of the stack
] % End of if statment
&h % Horizontally concatenate all strings on the stack
tD % Duplicate and display the current string
3&Xx % Pause for 0.3 seconds and clear the display
T % Push a literal TRUE to the stack to make this an infinite loop
% Implicit end of while loop
```
[Answer]
## C, ~~290~~ 285 bytes
```
#include<stdio.h>
#include<time.h>
#define S(s,a,b){int p=rand()%48+1;clock_t c=clock()+300;while(c>clock());int x=d[s];for(int i=s;i a p;)d[i b]=d[i];d[p]=x;printf(d);}
main(){char d[]="0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ\r";srand(time(0));for(;;){S(0,<,++)S(49,>,--)}}
```
Ungolfed:
```
#include<stdio.h> // variadic(printf) functions without a valid prototype = UB
#include<time.h> // required for the implementation-defined clock_t type
// note that <stdlib.h> isnt required for srand()/rand() because they are
// validly declared implicitly
#define S(s,a,b) // macro function
{
int p=rand()%48+1; // get a random position within the array
clock_t c=clock()+300; // get the time 300 milliseconds from now
while(c>clock()); // wait for that time
int x=d[s]; // save the s'th character in a tempvar
for(int i=s;i a p;) // shift everything in the array from p
d[i b]=d[i]; // a determines the comparison: </>
// b determines the operation: ++/--
d[p]=x; // put the tempvar in its new position
printf(d); // print the modified string
} // note: the \r at the end makes it so the next printf overwrites it
main() // main entry point
{ // deck to shuffle below
char d[]="0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ\r";
srand(time(0)); // seed the random number generator
for(;;) // infinite loop
{
S(0,<,++) // shuffle from the start of the deck
S(49,>,--) // shuffle from the end of the deck
}
}
```
[Answer]
# Swift, 288 bytes
```
import Darwin
var o=Array("0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ".characters)
while true{
print(String(o),terminator:"\r")
fflush(__stdoutp);{o.insert(o.removeLast(),at:$0())
o.insert(o.removeFirst(),at:$0()+1)}({Int(arc4random_uniform(UInt32(o.count-1)))})
usleep(300000)
}
```
Golfing in Swift is always a challenge, as one of its selling points is expressiveness.
[Answer]
# Ruby (138 119 Bytes)
```
f=0;a=[*0..9,*?a..?j,*?q..?z,*?A..?J,*?Q..?Z];loop{$><<a*''+?\r;a.insert(rand(48),f>0? a.shift : a.pop);f^=1;sleep 0.3}
```
Not as short as @PaulPrestidge but at least I understand it..
Also great to learn that ruby is like a endless tunnel of awesome!
[Answer]
# Ruby, ~~111~~ 101 characters
```
s=[*0..9,*?a..?j,*?q..?z,*?A..?J,*?Q..?Z,?\r]*''
loop{$><<s;s[1+rand(48),0]=s.slice!$.^=-2;sleep 0.3}
```
Loops infinitely.
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), noncompeting 41 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html)
```
"Q…Z"A…J"q…z"a…j"0…9⁵⁺ḷçṛ47⁺1ɱɲOṃḃɲ49ḅṙḍq
```
[Try it:)](https://tkellehe.github.io/noodel/release/editor-0.0.html?code=%22Q%E2%80%A6Z%22A%E2%80%A6J%22q%E2%80%A6z%22a%E2%80%A6j%220%E2%80%A69%E2%81%B5%E2%81%BA%E1%B8%B7%C3%A7%E1%B9%9B47%E2%81%BA1%C9%B1%C9%B2O%E1%B9%83%E1%B8%83%C9%B249%E1%B8%85%E1%B9%99%E1%B8%8Dq&input=&run=true)
### How It Works
```
"Q…Z"A…J"q…z"a…j"0…9⁵⁺ # Creates the string literal to be shuffled.
ḷçṛ47⁺1ɱɲO ṙḍq # The main "infinite" loop that applies the animation.
ṃḃɲ49ḅ # Sub-loop that acts like an if-statement that only runs every odd iteration of the loop.
"Q…Z # Pushes the string literal "QRSTUVWXYZ".
"A…J # Pushes the string literal "ABCDEFGHIJ".
"q…z # Pushes the string literal "qrstuvwxyz".
"a…j # Pushes the string literal "abcdefghij".
"0…9 # Pushes the string literal "0123456789".
⁵⁺ # Add the five strings on the stack to make one string.
ḷ # Unconditionally loop the following code.
ç # Copy what is on the top of the stack, clear the screen, and then print the copy.
ṛ47 # Create a random integer from 0 to 47.
⁺1 # Increment the number to get 1 - 48 such that will not be the top or bottom of the deck.
ɱ # Push the number of times that the unconditional loop has ran.
ɲO # Consume the counter and push on zero if is even and one if is odd.
ṃ # Conditional loop that only passes if the top of the stack is truthy (if the counter is odd).
ḃ # Throws away the top of the stack.
ɲ49 # Pushes the literal 49 in order to represent the top of the deck.
ḅ # Ends the conditional loop.
ṙ # Relocate an element in the string by using the two numbers on the stack (either 0 or 49 to the random number).
ḍq # Delay for a quarter of second. (End of unconditional loop)
```
```
<div id="noodel" code='"Q…Z"A…J"q…z"a…j"0…9⁵⁺ḷçṛ47⁺1ɱɲOṃḃɲ49ḅṙḍq' input="" cols="50" rows="2"></div>
<script src="https://tkellehe.github.io/noodel/release/noodel-0.0.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# bash, 170 bytes
```
r(){((r=RANDOM%48+1));echo -n $c^;sleep .3;}
c=0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ
while r
do
c=${c:1:r}${c:0:1}${c:r+1}
r
c=${c:0:r}${c:49}${c:r:-1}
done
```
here '^' (on the first line) represents `ctrl-m`: entered on the command-line as `ctrl-v` `enter` or in an editor according to how your editor works (assuming your editor works)
] |
[Question]
[
*Im talking about [this question](https://codegolf.stackexchange.com/questions/103670/output-integers-in-negative-order-increase-the-maximum-integer-everytime), take a look at it if you are a bit confused.*
# Main Task
Your task is to output concatenated integers, in decreasing order, but increasing the maximum integer everytime you hit `1` *(for this question, 1 will be considered a prime number)*. While this doesn't sound any different from the first question, here comes the tricky part: All outputted numbers **may only be primes**. These will be strung together into a single string without spaces or newlines. Your input will also be a **prime number**.
Example:
```
1
21
321
5321
75321
1175321
Valid output:
1213215321753211175321
```
## Input
Your code may only take one input: the highest prime to be printed. This input can come from anywhere (graphical, STDIN). You are **assured** that the input is a prime number.
## Output
You will have to output the resulting number. You can get this number by keep counting down, only count the number if it's a prime, then connect all results together to one number. The last number "row" (e.g. `7, 5, 3, 2, 1`) has to be printed fully. The output could be anything (numbers, strings, graphical), as long as it's readable. The same Regex pattern for checking your test cases applies:
```
^(\D*(\d)+\D*|)$
```
If your output doesn't match with this pattern, your code is invalid.
## Rules
* The input is assured to be prime, do not include error handling, unless you want/need to.
* The output may only be a full-connected number, therefore not split up by anything, not even newlines.
* Your algorithm shouldn't check for the first instance of `N` appearing (for instance, the `17` in `1175321`), but rather for the first instance of `N` as the actual number.
* Your input is assured to be positive, do not add handling unless you want/need to.
## Test cases
```
Input: -2, 0
Output: Any, or none (number isn't positive)
Input: 9
Output: Any, or none (number isn't prime)
Input: 1
Output: 1
Input: 7
Output: 121321532175321
Input: 23
Output: 1213215321753211175321131175321171311753211917131175321231917131175321
```
# Winner
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the author of the code with the least length in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ÆR1;;\UFV
```
[Try it online!](https://tio.run/nexus/jelly#@3@4LcjQ2jom1C3s////RsYA "Jelly – TIO Nexus")
### How it works
```
ÆR1;;\UFV Main link. Argument: n
ÆR Prime range; yield all primes up to n.
1; Prepend the "prime" 1.
;\ Cumulative concatenation; yield all prefixes of the prime range.
U Upend; reverse each prefix.
F Flatten the resulting 2D array.
V Eval. This casts the integer array to string first, thus concatenating
the integers.
```
[Answer]
# Processing, 161 bytes
```
int p(int n){for(int k=1;++k<=sqrt(n);)if(n%k<1)return 0;return 1;}void t(int n){for(int i=1,j;i<=n;i++){if(p(i)<1)continue;for(j=i;j>0;j--)print(p(j)<1?"":j);}}
```
One function does the primality checking, the other does the printing. Call it by `t(7)`
### Ungolfed
The first function does the primality checking. It returns an `int` instead of a `boolean` since this way more bytes are saved. (`int` instead of `boolean`, `0` instead of `false`, `1` instead of `true`)
```
int Q103891p(int n){
for(int k=1;++k<=sqrt(n);)
if(n%k<1)return 0;
return 1;
}
```
The second function prints out the string. It iterates through every number, if it is not a prime, skip to the next iteration. If it is a prime, it continues down to the printing inside another `for`-loop. Again, if the number is prime, then we print it, otherwise not.
```
void Q103891(int n){
for(int i=1,j;i<=n;i++){
if(p(i)<1)continue;
for(j=i;j>0;j--)
print(p(j)<1?"":j);
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ÆR;@1
ÇÇ€UVV
```
[Try it online!](https://tio.run/nexus/jelly#@3@4LcjawZDrcPvh9kdNa0LDwv7//29kDAA "Jelly – TIO Nexus")
If it hadn't been for `1`s at all, my code would have just been `ÆRÆRUVV` for 7 bytes.
Enhanced explanation:
```
ÇÇ€UVV Main link. Arguments: z.
Ç Run link1 on z.
Ç€ Run link1 on z's elements.
U Reverse z's elements.
V Flatten z.
V Concatenate z's elements.
ÆR;@1 Link 1. Arguments: z.
ÆR Range of primes [2..z].
1 Integer: 1.
;@ Concatenate x to y.
```
The Irish guy (called Dennis?) somehow [outgolfed](/a/103940/41024) me lol.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes
```
LDpÏX¸ì€Lí˜ÐXQsp+ÏJ
```
[Try it online!](http://05ab1e.tryitonline.net/#code=TERww49YwrjDrOKCrEzDrcucw5BYUXNwK8OPSg&input=Nw)
**Explanation**
```
L # range [1 ... input]
DpÏ # keep only primes
X¸ì # prepend a 1
€L # map: range [1 ... n]
í # reverse each sublist
˜ # flatten list to 1D
Ð # triplicate
XQ # check elements in one copy for equality with 1
sp # check elements in one copy for primality
+ # add the above lists giving a list with true values at indices
# comtaining 1 or a prime
Ï # keep only those elements of the unmodified copy of the list
J # join
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
y:{e1|e#p}f@[rcw\
```
[Try it online!](https://tio.run/nexus/brachylog#@19pVZ1qWJOqXFCb5hBdlFwe8/@/OQA "Brachylog – TIO Nexus")
Can't seem to get shorter than that...
### Explanation
```
y The list [0, ..., Input]
:{ }f Find all...
e1 ...elements that are 1 (there is 1)...
| ...or...
e#p ...elements that are prime...
@[ Take a prefix of the result
rc Reverse it and concatenate it into a number
w Write to STDOUT
\ Backtrack: try another prefix
```
[Answer]
# GameMaker Language, 169 bytes
Main function (68 bytes)
```
b=""for(i=1;i<=argument0;i++){c=i while(j)b+=string(p(c--))}return b
```
Function p (46 bytes)
```
for(a=0;a<argument0;a++)while q(++b){}return b
```
Function q (55 bytes)
```
n=argument0 for(i=2;i<n;i++)if!(n mod i)p=1return p|n=1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
Zq"1@ZqP]1v!VXz
```
[Try it online!](https://tio.run/nexus/matl#@x9VqGToEFUYEGuolhEWUfX/v5ExAA "MATL – TIO Nexus")
```
Zq % Implicit input. Push array of primes up to that value
" % For each prime in that array
1 % Push 1
@ % Push current prime
Zq % Push array of primes up to that
P % Reverse
] % End
1 % Push 1
&h % Concatenate all stack horizontally
V % Convert to string
Xz % Remove spaces. Implicit display
```
[Answer]
# [Perl 6](http://perl6.org/), 41 bytes
```
{[~] flat [\R,] 1,|grep *.is-prime,2..$_}
```
([Try it online.](https://tio.run/#ttqTH))
### Explanation:
* `1, |grep(*.is-prime, 2..$_)`: Sequence of 1 and primes... `(1 2 3 5)`
* `[,] ...`: Reduce ("fold") over comma operator... `(1 2 3 5)`
* `[\,] ...`: With intermediate results ([triangular reduce](http://perl6maven.com/tutorial/perl6-reduction-triangle))... `((1) (1 2) (1 2 3) (1 2 3 5))`
* `[\R,] ...`: Apply [reversing](https://docs.perl6.org/language/operators#Reversed_Operators) meta-operator to the comma... `((1) (2 1) (3 2 1) (5 3 2 1))`
* `[~] flat ...`: Remove list nesting, and fold over string concat operator... `1213215321`
(This is based on [my answer for the previous challenge](https://codegolf.stackexchange.com/a/103701/14880).)
[Answer]
# Mathematica, 61 bytes
```
ToString/@(1<>Prime@Range[Range@PrimePi@#,0,-1]/.Prime@0->1)&
```
Unnamed function taking an integer argument and returning a string. (If the input is not a prime, it just "rounds it down" to the nearest prime; if the input is nonpositive, it pretends it's 1.)
This implementation uses the nasty trick from [Martin Ender's answer](https://codegolf.stackexchange.com/a/103706/56178) to the similar previous challenge (who says this old dog can't learn new tricks?): abusing `<>` to flatten a nested list of integers.
The nested list in question starts by generating a similar nested list as in that answer, with the appropriate length (given by `PrimePi@#`, the number of primes up to and including the input); then `Prime` is applied to every element. For example, for the input `5` which is the 3rd prime, the code `Range[Range@PrimePi@#,0,-1]` yields `{{1,0},{2,1,0},{3,2,1,0}}`, and applying `Prime` to each element yields `{{2,Prime[0]},{3,2,Prime[0]},{5,3,2,Prime[0]}}` since the 1st, 2nd, and 3rd primes are 2, 3, and 5, respectively. I feel proud that I managed to add even more errors to Martin Ender's approach—Mathematica complains every time it writes `Prime[0]`.
`Prime[0]` isn't a thing, but that's okay: `/.Prime@0->1` turns them all into `1`s. And we also want a `1` on the front, so we replace the `""` from Martin Ender's answer with simply `1`, which actually saves a byte.
[Answer]
# PHP, 72 bytes
```
for(;$n<$argv[1];print$s=$n.$s)for($i=2;$i>1;)for($i=++$n;--$i&&$n%$i;);
```
Run wit `-r`
**breakdown**
```
for(;$n<$argv[1]; // loop $n up to argument:
print$s=$n.$s) // 2. prepend $n to $s, print $s
for($i=2;$i>1;) // 1. find next prime: break if $i<2
for($i=++$n;--$i&&$n%$i;); // if $n is prime, $i is 1 after loop (0 for $n=1)
```
[Answer]
# Pyth - 12 bytes
```
jkf!tPTs}R1S
```
[Test Suite](http://pyth.herokuapp.com/?code=jkf%21tPTs%7DR1S&test_suite=1&test_suite_input=9%0A1%0A7%0A23&debug=0).
] |
[Question]
[
There is a game I like to play. It happens on a grid of finite size (but it's wrapped, like a sphere). On that grid, a random (integer-only) point is selected. Then, I, the user, am prompted for a coordinate input. If my input matches the random point exactly, I am told that I have won. Otherwise, I am told the point-wise distance between my input and the random point. For example, if I guessed `(2,2)` and the random point was at `(4,3)`, then the distance would be `sqrt[(3-2)^2 + (4-2)^2] = sqrt[5]`.
The game continues until the player arrives at the correct location of the point.
---
**Objective** Create a functional version of the game described above. You must create a full program to do so. Here's what your program should do:
1. Request two inputs: the height and the width of the board. The origin is at the top-left of the board. These inputs will not exceed `1024`.
2. Select a random point on that board; this will be the point to be guessed.
3. Accept input simulating a turn. The input will be either a space-separated pair of integers or two separate integer inputs. In response to this input, the program will do one of two things:
1. If the input matches the random point selected, output a message signalling the user's victory. I would suggest "You won!".
2. Otherwise, output the distance between the user's input point and the random point. In either case, you must increment the turn counter.
4. Once the user has achieved victory, display the number of turns the user took. The program then exits.
## Bonuses
Bonuses are applied in the order that they appear in this list
* -150 bytes if your program takes an input integer `D` that describes the dimension in which the game takes place. E.g., if `D = 3`, then you create a random point of `3` integers, take `3` integer inputs, and output the distance between those points.
* -50% (or +50% if `score < 0`)if you provide a graphical representation of the board (ASCII or Picture) that shows where the user has previously guessed on the grid of given dimensions and the turn counter. (If you go for the first bonus, then this bonus only applies to the `2D` and `1D` modes. If you add a 3D graphical output, you get an additional -50%.)
* -60 bytes if you can provide a gamemode (selected by an input in the beginning; that is, when given `0`, perform the regular gamemode; when given `1`, perform this gamemode) in which the point moves 1 unit in a random orthogonal direction per turn
# More on wrapping
Wrapping occurs only when, in the third bonus, the moving point moves across any of the boundaries; in this case, the moving point is warped to the respective point, like so:
```
... ...
..R (move right) R..
... ...
```
This wrapping behaviour does not effect the user's guess, asides from the fact that point has changed direction.
---
# Leaderboard
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
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 snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</style><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=language-list><h2>Shortest Solution by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td><td>Author<td>Language<td>Size<tbody id=answers></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}<td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><script>function answersUrl(e){return"//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"//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 a=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(a="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var r=a.match(SCORE_REG);r?e.push({user:getAuthorName(s),size:+r[2],language:r[1],link:s.share_link}):console.log(a)}),e.sort(function(e,s){var a=e.size,r=s.size;return a-r});var s={},a=1,r=null,n=1;e.forEach(function(e){e.size!=r&&(n=a),r=e.size,++a;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;o=jQuery("<a>"+o+"</a>").text(),s[o]=s[o]||{lang:e.language,lang_raw:o,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_raw>s.lang_raw?1:e.lang_raw<s.lang_raw?-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 QUESTION_ID=62598,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=8478,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?([-\d]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;</script>
```
[Answer]
# CJam, ~~-113~~ ~~-139~~ ~~-152~~ ~~-157~~ -159 bytes
```
l~]:B:mr{_ea:i~mr0a*W2mr#+*.+B:,.=_[l~].-:mh_p}g],(
```
The program is **51 bytes** long and qualifies for the **-150 bytes** and **-60 bytes** bonuses.
The game mode and number of dimensions are read as a command-line argument, the size in each dimension from STDIN. Since [the victory message is arbitrary](https://codegolf.stackexchange.com/questions/62598/a-flat-guessing-game#comment151076_62598), the program will print `0.0` (distance to goal) to indicate that the game is over.
### Test runs
```
$ cjam game.cjam 0 3; echo
2 2 2
1 1 1
1.4142135623730951
1 1 0
1.7320508075688774
1 0 1
1.0
0 0 1
0.0
4
$ cjam game.cjam 1 3; echo
2 2 2
0 0 0
1.0
0 0 0
0.0
2
```
### How it works
```
l~] e# Read a line from STDIN, evaluate it and collect the result.
:B e# Save the resulting array in B. The result is [B1 ... Bd],
e# where Bk is the board size in dimension k.
:mr e# Pseudo-randomly select a non-negative integer below Bk,
e# for each k between 1 and d.
{ e# Do:
_ e# Copy the item on the stack. The original becomes a dummy value
e# that will be used to count the number of turns.
ea e# Push the array of command-line arguments.
:i~ e# Cast each to integer and dump them on the stack.
e# This pushes m (game mode) and d (number of dimensions).
mr e# Pseudo-randomly select a non-negative integer below d.
0a* e# Push an array of that many zeroes.
W2mr# e# Elevate -1 to 0 or 1 (selected pseudo-randomly).
+ e# Append the result (1 or -1) to the array of zeroes.
* e# Repeat the array m times.
.+ e# Perform vectorized addition to move the point.
B:,.= e# Take the k-th coordinate modulo Bk.
_[l~] e# Push a copy and an evaluated line from STDIN.
.-:mh e# Compute their Euclidean distance.
_p e# Print a copy.
}g e# While the distance is non-zero, repeat the loop.
],( e# Get the size of the stack and subtract 1.
e# This pushes the number of turns.
```
[Answer]
# Pyth, 91 (-150 -60) = -119
```
VvwaYOvw;JY#IqQ1=dOlY XYd@S[0 @Jd +@Yd?O2_1 1)1)=T[)VYaT^-Nvw2)=ZhZ=b@sT2Iqb0Bb;p"Won in "Z
```
Old solution: (54-150=-96)
```
JYVQaYOvw;#=J[)VYaJ^-Nvw2)=ZhZ=b@sJ2Iqb0Bb;p"Won in "Z
```
All input takes place on a new line.
* First integer represents the game mode (**either `1` or `0`**)
* ~~First~~ Second integer `D` represents the dimensions of play.
* Next `D` inputs represent the field size
* Every `D` inputs from this point on are guesses
Sample play (hints do not appear in the actual program):
```
#Hint: Gamemode (1 or 0)
1
#Hint: Dimensions
3
#Hint: X-size
4
#Hint: Y-size
4
#Hint: Z-size
4
#Hint: Guesses
#Hint:[3, 2, 1]
3
2
2
1.0
#Hint:[3, 2, 1]
3
2
1
1.0
#Hint:[2, 2, 1]
2
2
1
1.0
#Hint:[3, 2, 1]
3
2
1
Won in 4
```
[Answer]
## Python 2, 210 - 150 = 60
```
from random import*
q,r,o=map,raw_input,int
a=q(randrange,q(o,r().split(' ')))
m=q(o,r().split(' '))
t=1
while m!=a:print sum([(c-d)**2for c,d in zip(m,a)])**.5;m=q(o,r().split(' '));t+=1
print'You won in %d'%t
```
First challenge only so far. [Try it online](http://ideone.com/fTIUN7)
[Answer]
## Pip, ~~43~~ 42 bytes - 150 = -108
Takes the board dimensions as command-line arguments (with D implied from the number of args). Takes guesses as space-separated numbers on stdin.
```
YRR_MgWd:++i&RT$+(y-(q^s))**2Pd"Won in ".i
```
This code takes heavy advantage of Pip's array-programming features. The array of cmdline args is stored in `g`. We generate the point to be guessed by mapping the randrange operator `RR` over `g`, and yank the resulting list into the `y` variable. Then comes the main while loop, where the condition is as follows:
```
d:++i&RT$+(y-(q^s))**2
++i& Increment i, the guess counter; the result is always > 0, so the
short-circuiting & operator evaluates the next expression:
q Read a line from stdin
^s Split on spaces
y-( ) Subtract from our chosen point itemwise
( )**2 Square, itemwise
$+ Fold on +, summing the list of squares
RT Square root
d: Assign this distance to d
```
If the distance was nonzero, the inside of the loop prints it. If it was zero, we've hit the target point; the loop halts, and the program outputs the win message and number of turns.
Example run:
```
C:\Users\dlosc> pip.py -f guessing.pip 10 5 6 4
5 2 3 2
3.1622776601683795
6 2 3 2
4.123105625617661
3 2 3 2
1.4142135623730951
3 1 3 2
2.23606797749979
3 2 2 2
1.7320508075688772
2 2 3 2
1
2 2 3 1
1.4142135623730951
2 3 3 2
Won in 8
```
[Answer]
## R, 134 - 150 = -16 bytes
```
function(...){G=sapply(list(...),sample,1)
C=0
repeat{g=scan()
C=C+1
if(any(G!=g))cat(sqrt(sum((G-g)^2)))else{cat("Won in",C);break}}}
```
[Answer]
## Haskell, 240 - 150 = 90
```
import System.Random
r x=randomRIO(0,x-1)
m=map read.words
g=getLine
main=do g;(fmap m g::IO[Int])>>=mapM r>>=b 1
b c v=do i<-fmap(sqrt.fromIntegral.sum.map(^2).zipWith(-)v.m)g;if i==0 then putStrLn$"Won in "++show c else do print i;b(c+1)v
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~77~~ 71 - 210 = -139
```
S F M
P←?S
{P←S|P+(?D)⌽D↑Mׯ1 1[?2]
C+←1
P≢G←⎕:0⊣⎕←.5*⍨+/2*⍨P-G
C}⍣≢C←0
```
Ok:
Note that this runs in index origin 0 (`⎕IO←0`) which is default in many APLs.
Takes boolean mode as right argument (`M`), and dimension sizes as left argument (`S`).
Number of dimensions is `D`, which must be set (e.g. `D←3`) before calling, as per OP).
`P←?S` goal gets random point in range 1 though each of the dimension bounds
`{` … `}⍣≢C←0` repeat the function until the result is different from `C`, which initially gets `0`
`?2` random number 0 or 1
`¯1 1[` … `]` index from list of two numbers
`M×` multiply by mode; makes `0` if mode is `0`
`D↑` pad with `0`s to match number of dimensions
`(?D)⌽` rotate list randomly (0 through number of dimensions-1)
`P+` adjust current goal
`S|` world-size modulus
`P←` save new goal point
`C+←1` increment counter
`P≢G←⎕:` input guess, and if it is different from goal point then...
`P-G` distances in each dimension
`2*⍨` squared
`+/` sum them
`.5*⍨` square-root
`⎕←` print that
`0⊣` return 0 (i.e identical to initial value, so repeat)
`C` ... else, return the number of guesses (which, being different from 0, stops the looping and returns the last value)
] |
[Question]
[
# Average out two lists
### Challenge
Given two lists of positive integers, determine whether it is possible to rearrange the elements into two new lists such that the new lists have the same arithmetic mean (average).
### Input
The input can be taken through STDIN or as function arguments. Input can be taken as a list, or if your language doesn't support lists (or anything similar such as arrays/dictionaries) then the input can be taken as a comma- or space-delimited string. That is,
```
"1 4 8 2 5,3 1 5 2 5"
```
is the same as:
```
[ [1,4,8,2,5], [3,1,5,2,5] ]
```
All *input* lists will be the *same* length.
### Output
If you can create two new lists with the same average, your program/function should print or return the mean. If you can't, your program should output a sad face `:(`.
Note that the rearranged lists with equal means, if they exist, need not has the same length. Any number of swaps can be made to create the new lists.
### Examples
```
1 4 8 2 5,3 1 5 2 5 -> 1 4 8 2 3,5 1 5 2 5 (swapped 3 and 5) -> 3.6
1 3 6 2,16 19 19 14 -> [[1,6,19,14],[3,2,16,19]] -> 10
2 6 2,6 3 5 -> 2 6,2 6 3 5 (moved 2) -> 4
90 80 20 1,40 60 28 18 -> :(
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. As always, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# Pyth, 24 bytes
```
?}KcsJsQlJmcsdldtPyJK":(
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%3F%7DKcsJsQlJmcsdldtPyJK%22%3A(&input=%5B+%5B1%2C4%2C8%2C2%2C5%5D%2C+%5B3%2C1%2C5%2C2%2C5%5D+%5D&debug=0)
Thanks to Dennis for noticing an error and golfing one byte.
### Explanation:
```
?}KcsJsQlJmcsdldtPyJK":( implicit: Q = evaluated input
sQ all numbers of Q
J save them in J
KcsJ lJ average of J (sum(J) / len(J))
store in K
m tPyJ map each nonempty subset d of J to:
csdld average of d
?} if K in ^:
K print K
":( else print sad-face
```
[Answer]
# SWI-Prolog, 159 bytes
```
a(A,B):-append([A,B],R),permutation(R,S),append([Y,Z],S),sum_list(Y,I),sum_list(Z,J),length(Y,L),length(Z,M),L\=0,M\=0,I/L=:=J/M,W is J/M,write(W);write(':(').
```
Called as `a([1,4,8,2,5],[3,1,5,2,5]).`
[Answer]
# Julia, 101 bytes
```
f(a,b)=(m=mean;p=filter(i->m(i[1])==m(i[2]),partitions([a,b],2));isempty(p)?":(":m(collect(p)[1][1]))
```
This creates a function that accepts two arrays and returns a string or a float accordingly.
Ungolfed + explanation:
```
function f(a,b)
# Get the set of all 2-way partitions of the array [a,b]
l = partitions([a,b], 2)
# Filter the set of partitions to those where the two
# contained arrays have equal means
p = filter(i -> mean(i[1]) == mean(i[2]), l)
# Return a frown if p is empty, otherwise return a mean
isempty(p) ? ":(" : mean(collect(p)[1][1])
end
```
[Answer]
# R, 94 Bytes
Basically the same as Jakubes I think. If the mean of both lists matches the mean of any combination of the values in lists up to but not including the combined length of the list, output the mean otherwise the sad face.
```
if(mean(l<-scan())%in%unlist(sapply(2:length(l)-1,function(x)combn(l,x,mean))))mean(l)else':('
```
Test run
```
> if(mean(l<-scan())%in%unlist(sapply(2:length(l)-1,function(x)combn(l,x,mean))))mean(l)else':('
1: 1 4 8 2 5
6: 3 1 5 2 5
11:
Read 10 items
[1] 3.6
> if(mean(l<-scan())%in%unlist(sapply(2:length(l)-1,function(x)combn(l,x,mean))))mean(l)else':('
1: 90 80 20 1
5: 40 60 28 18
9:
Read 8 items
[1] ":("
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
FŒ!ŒṖL=2ƊƇÆmEƇƲ€ṀṀṀȯ⁾:(
```
[Try it online!](https://tio.run/##y0rNyan8/9/t6CTFo5Me7pzmY2t0rOtY@@G2XNdj7cc2PWpa83BnAwSdWP@ocZ@Vxv/D7UDRyP//o7k4o6MNdRQMY3UUoo1AdKwOmpARVAjINAPxgKJA2lhHwRQkEQsA "Jelly – Try It Online")
Wildly inefficient, times out when the lengths of the input lists are \$\ge4\$
## How it works
```
FŒ!ŒṖL=2ƊƇÆmEƇƲ€ṀṀṀȯ⁾:( - Main link. Takes a list of lists, l = [a,b]
F - Flatten
Œ! - Yield all permutations
Ʋ€ - Over each permutation, p:
ŒṖ - Yield all partitions of p
L=2ƊƇ - Only keep those of length 2
Æm - Take the mean of each
EƇ - Only keep those where the means are equal
ṀṀṀ - Take the maximum three times. This yields 0 for impossible inputs and the mean for possible ones
⁾:( - Yield the string ":("
ȯ - Replace 0 with this string, or do nothing if not 0
```
] |
[Question]
[
Write an infinite list of triangle codes, defined as code where the i-th line has i bytes for all lines, such that the i-th code generates (i-1)th code and has 1 more line than the (i-1)th code.
The score is the number of lines in the initial code. Lowest score wins.
For example, if
```
.
..
...
....
```
is outputted by
```
.
..
...
....
print
```
which is outputted by
```
.
..
...
....
print
print.
```
and so on, then the score is 4.
[Sandbox](https://codegolf.meta.stackexchange.com/a/21963/)
[Answer]
# JavaScript (ES6), Score ~~10~~ 9
Below is an example starting point with 15 lines. Bigger triangles are obtained by padding the end with 0's while preserving the final ``)`.
```
0
f=
_=>
`0
${`f=
`+f}`.
/*###*/
replace(
/..\n.+$/
,'`)'||`00
00000000000
000000000000
0000000000000
00000000000000
0000000000000`)
```
which is eventually reduced to:
```
0
f=
_=>
`0
${`f=
`+f}`.
/*###*/
replace(
/..\n.+`)
```
[Try it online!](https://tio.run/##xclBDsIgFATQ/T8FCU0KrQIXwJOY@Al@jIZAA6Yb69lRV2o9gLOaN3Nxs6u@nKfrNuUjtWYgWDjYHTCGBrobPoljuKMCPXDOBw2Fpug8CdBK7ZMaOw2bHmW/LGgMmHc@@zdWWhFl8znVHEnFfBKFKrMsCCnhd6bZxVeVf77bAw "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 278 lines
The output of this 279-byte program:
```
'->w;s=substring;`+`=paste0;x=nchar(w);y=s(w,1,138);z=sQuote(s(w,1,x-1))+y;for(i in 2:nchar(z)-2)cat("#"+s(z,1,i),sep=intToUtf8(10));cat(z).'->w;s=substring;`+`=paste0;x=nchar(w);y=s(w,1,138);z=sQuote(s(w,1,x-1))+y;for(i in 2:nchar(z)-2)cat("#"+s(z,1,i),sep=intToUtf8(10));cat(z)
```
[Try it online!](https://tio.run/##zY7LCoMwFER/JaSL5uIDtZvSkEJx66a0XdcH0QYkkdxYHz9vFX@iyzlzBsYuSn8VqrKV7DFhiNK1pirWVBVONsZORBCape9bllGf7N2GUgqwHIPrwFFgX6KzSjc893LRFehkxEehq09h2QB8EsgGP/bj0xn4LPDeGyfZzsYgBvAmXhvLFFGaJJd9N0OQwHqC0QP1kM2rq8BH2Qml3dO8XH1mcQTAN2eG8I@@LMsP "R – Try It Online")
Each successive program is created by adding an
additional character character (any character) at position 139 of the final line of the 'base' program.
**Ungolfed program generator:**
```
w='->w;s=substring;`+`=paste0;x=nchar(w);y=s(w,1,138);z=sQuote(s(w,1,x-1))+y;for(i in 2:nchar(z)-2)cat("#"+s(z,1,i),sep=intToUtf8(10));cat(z).'
# define string w as the golfed working program code,
# appended with extra characters to generate
# successively longer versions;
`+`=paste0 # redefine `+` to concatenate strings;
x=nchar(w) # Now, get x = the number of characters of w
y=substring(w,1,138) # define y as the working program code without any extra characters
z=sQuote(substring(w,1,x-1))+y # define z as the previous full working program: that is,
# the definition of w minus 1 character, plus the program code.
for(i in 2:nchar(z)-2){ # Loop up to the length of z minus 1
cat("#"+s(z,1,i),sep="\n") # printing its prefixes after a "#"
} # (so these are all comments in the outputted program),
cat(z) # finally output the previous program code.
```
[Answer]
# [Zsh](https://www.zsh.org/), score 5
The pattern repeats like this:
```
#
h\
ea\
d -\
n-1 \
$0 ###
#######
########
#########
##########
###########
############
#############
# ad infinitum
```
[Try it online!](https://tio.run/##qyrO@P9fmSsjhis1MYYrRUE3hitP11AhhkvFQEFZWZlLGQJgNIKBxEJmorBROUCeQmKKQmZeWmZeZklp7v//AA "Zsh – Try It Online")
With this as the ultimate program:
```
#
h\
ea\
d -\
n-1 \
$0 ###
```
* `#`: comments, ignored
* `h\ea\d -\n-1 \$0`: the backslashes and line breaks are eaten up to produce `head -n-1 $0`
+ `head`: print the first \$ n \$ lines
+ `$0`: of the current program
+ `-n-1`: with \$ n = -1 \$, which is treated as "all but the last"
[Answer]
# [Haskell](https://www.haskell.org/) (GHC 8.4.1, `-cpp`), score 28
This is the initial triangle (the first line is actually a space).
```
q\
=p\
rint
p=pu\
tStr;\
f(x:y)\
|length\
y>25=p"\
f ">>q('.\
'<$y);f s=\
p$show s++"\
]\n";l=putSt\
rLn;main= do
l. concat<>map\
M_((>>p",\\\10"\
).p.show)$init[ \
" \nq\\\n=p\\\n",\
"rint\np=pu\\\nt",\
"Str;\\\nf(x:y)\\",\
"\n|length\\\n y>2",\
"5=p\"\\\nf \">>q('",\
".\\\n'<$y);f s=\\\n",\
"q$show s++\"\\\n]\\n",\
"\";l=putSt\\\nrLn;mai",\
"n= do\nl. concat<>ma",\
"p\\\nM_((>>p\",\\\\\\10",\
"\"\\\n).p.show)$init[ \\",\
```
To obtain the the 29-lines triangle we add the following line.
```
".........................."]
```
From the 30th line onwards, the pattern becomes regular.
```
q\
=p\
rint
p=pu\
tStr;\
f(x:y)\
|length\
y>25=p"\
f ">>q('.\
'<$y);f s=\
p$show s++"\
]\n";l=putSt\
rLn;main= do
l. concat<>map\
M_((>>p",\\\10"\
).p.show)$init[ \
" \nq\\\n=p\\\n",\
"rint\np=pu\\\nt",\
"Str;\\\nf(x:y)\\",\
"\n|length\\\n y>2",\
"5=p\"\\\nf \">>q('",\
".\\\n'<$y);f s=\\\n",\
"q$show s++\"\\\n]\\n",\
"\";l=putSt\\\nrLn;mai",\
"n= do\nl. concat<>ma",\
"p\\\nM_((>>p\",\\\\\\10",\
"\"\\\n).p.show)$init[ \\",\
".........................."]
f ".........................."
f "..........................."
f "............................"
```
[Try it online!](https://tio.run/##hZHdS8MwFMXf81dcwmAtc8GJgti1LwoqKD7om3dI6Lo12N2ma/wY@Ldbb9POD8TZh0DPuTk5vyTX9WNWFI1Z2XLt4Ew7ra5LKs0cxmOoDaUZ3F3ewLzMaho6yPVzBucXp3CsDtWkAVGhiC2KtSEnbGyfULhbt45QLILXk02I4q3IaOlyFLBJDo5iK9kCmSRVMFQohtPBJowWUMco7KDOyxeoRyOemSHJqOBAjuP4K4pW2lAMwFVEoSAtKdVumqw0n379EARJYuUeIk72eXeorGrDwoEh4@4BhQSkim3itrzyqJBtaSTfmiXnNV@e//r66EWkLQU7LYdXGQalnwXsgLysWukb1/a06hOv2zXbGvgFylKP6p2eF@kHsLc8Rc@NHrxj7wJb89cddCzqz0/O2pfZ4e@2//WVbJr3dFHoZd2MU2s/AA "Haskell – Try It Online")
You can find a program to generate arbitrarily large triangles [here](https://tio.run/##dVJda8IwFH3fr7gEwRY1OEUYq80v0KftzRQpNbVlaRrTyCbst69LUhutbIE2H/fk3HtObpE2H4zzVrNK8lQziAEBFSdKqYil/atSaCpkLM92p9@0iuwiD75eL6FdfXMmjrqwS7iQxcpcQw4BFBFyCsbY7sbr0SWMcmhiu5Ojpqg/oZlMOmxiPooibrKYDC7tRkRVWooYAA41FRxDVoss1WtSpa6w7T4ICDHJptSN53nHFWKJLXs4KkWpd0Adt5mcKi@sO552kxPpVTqhPnZVPBBNfXRgQO@Bj65cKtRft7V0nngEvsYG/gxqO928ulElQ4yN3Ll3Z6CH9E4@WOnjvSe9rdQbe7P3LtsV/YfZvTeode93qJ8ABKxnoFh62AizK3N7AIsX0AUTwJSqFaD3uoamSjlHwHjDQJ4VC0IDd6oU9C3aExBPcAUg4@a/g6LElPTAbDppu4eAljAjniUH80TSdoRpXfMsuxXGZRKGsFvOMRZJ2y4XP1nO02PTzjIpfwE "Haskell – Try It Online").
## How?
We use the `-cpp` flag to allow line breaking in the source code by means of `\`. GHC 8.4.1 is necessary since it is the first version to export the `(<>)` `Semigroup` operator in `Prelude`. My answer uses a variation of [this clever technique](https://codegolf.stackexchange.com/a/161036/82619) typically employed in quines. Here is the de-triangularized code.
```
q=print
p=putStr
f(x:y)|length y>25=p"f ">>q('.'<$y)
f s=p$show s++"]\n"
l=putStrLn
main=do
l.concat<>mapM_((>>p",\\\10").p.show)$init[
" \nq\\\n=p\\\n",
"rint\np=pu\\\nt",
"Str;\\\nf(x:y)\\",
"\n|length\\\n y>2",
"5=p\"\\\nf \">>q('",
".\\\n'<$y);f s=\\\n",
"q$show s++\"\\\n]\\n",
"\";l=putSt\\\nrLn;mai",
"n= do\nl. concat<>ma",
"p\\\nM_((>>p\",\\\\\\10",
"\"\\\n).p.show)$init[ \\",
".........................."]
f ".........................."
f "..........................."
f "............................"
f "............................."
```
The part before `f ".........................."` defines a function `f` and then prints itself (minus the last line `".........................."]`). The behaviour of `f` depends on the length of its argument: if the length is `26` then it prints `".........................."]`, otherwise if prints `f "....[...]....."`, where the number of dots is one less then the length of its argument. In both cases, `f` is basically printing the line just before its invocation.
By the way, making sure that the strings of the list had the correct length was a total nightmare. You think adding some random spaces to the code above would be enough? No no no! I spent way too much time trying all the possible combinations of `putStr` and `putStrLn`, moving things around to change the number of `\` in the code. The winning move was finally replacing a `\n` with `\10`, and after that everything was magically aligned.
] |
[Question]
[
### Description
The task of this challenge is to devise a program or function that tracks a given object in an \$n×n\$ space.
### I/O
Your program will be given 3 inputs, which may be taken [in any sensible way](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods):
`n` will be the size of the plane's side. (so, for \$n=5\$, your plane will be \$5×5\$). You may assume `n` will always be an odd integer.
`s` will be the starting position of the object, given as a pair of \$(x, y)\$ coordinates.
`D` will be a vector of ordered pairs. `D` will follow the format \$D = [(d\_0,t\_0),(d\_1,t\_1),...,(d\_n,t\_n)]\$, where \$d\_k\$ will always be *one* of `'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'`, for the cardinal and primary intercardinal directions, and \$t\_k\$ will be an integer for the number of 'ticks'.
Given these inputs, your program must output a tracking of the object in the plane.
### Rules
The output **must** contain the plane's boundaries. E.g.:
```
- 21012 +
+┌─────┐
2│ │
1│ │
0│ │
1│ │
2│ │
-└─────┘
```
would be an example of an empty \$5×5\$ plane. The numbers above and to the side are for reference only and don't need to be printed.
You may use whatever character(s) for the boundaries, as long as it's not whitespace (or renders as whitespace). The characters you choose must delineate the full plane, meaning that there can be no gaps between them.
```
Some acceptable planes include:
┌──┐ .... ---- +--+
│ │ . . | | | |
│ │ . . | | | |
└──┘; ....; ----; +--+
Nonacceptable planes include:
.... .... ++++ . .
. . + + . .
. + + . .
; ....; ....; + +; . .
```
The object to be tracked may be whatever character you choose, as long as it only occupies 1 space on the plane and is different from the boundary characters.
The trace of the tracked object may also be whatever characters you choose, as long as they only occupy 1 space on the plane and are different from the object.
For each element \$(d\_k,t\_k)\$ in \$D\$, the object must move \$t\$ spaces towards \$d\$, and leave a trace behind.
If the object would hit a boundary, it'll be reflected. If the object still has any moves left, it'll keep moving in the direction it was reflected to.
For reference, these directions reflect to each other:
\$N\rightleftharpoons S\$ → when the top or bottom boundary is met;
\$E\rightleftharpoons W\$ → when a lateral boundary is met;
The final output will contain the newest possible traces, that is, if the object would leave a trace in a space where there's already a trace, the newer trace character will overwrite the older.
As usual, [standard loopholes are forbidden by default](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
### Scoring:
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
### Examples:
Input: \$n=5\$, \$s=(0,0)\$, \$D=[('NW',2),('S',2),('E',1)]\$
Working it out:
\$t=0\$
```
0
┌─────┐
│ │
│ │
0│ ○ │
│ │
│ │
└─────┘
```
\$t=2\$
```
0
┌─────┐
│○ │
│ \ │
0│ \ │
│ │
│ │
└─────┘
```
\$t=4\$
```
0
┌─────┐
│∧ │
│|\ │
0│○ \ │
│ │
│ │
└─────┘
```
\$t=5\$, which will be the output.
```
0
┌─────┐
│∧ │
│|\ │
0│└○\ │
│ │
│ │
└─────┘
```
(The 0s are just for reference, and they don't need to be in the final output.)
---
Input: \$n=9\$, \$s=(3,-1)\$, \$D=[('N',2),('SW',8),('SE',3),('NE',8)]\$
Notice that, when \$t=10\$:
```
0
┌─────────┐
│ │
│ │
│ │
│ ∧ │
0│ /| │
│ ○ / | │
│⟨ / │
│ \ / │
│ ∨ │
└─────────┘
```
The object has been reflected *twice*: once when reaching the *bottom* of the plane while going towards the \$SW\$, where it reflects to the \$NW\$; then once again when reaching the *left side* of the plane, where \$NW\$ reflects to \$NE\$.
The final output comes at \$t=21\$:
```
0
┌─────────┐
│ ○ │
│ \ │
│ \ │
│ \ │
0│ /|⟩│
│ ∧ / / │
│⟨ \ / / │
│ \ \ / │
│ ∨ ∨ │
└─────────┘
```
### Test cases:
Input: \$n=5\$, \$s=(0,0)\$, \$D=[('NW',2),('S',2),('E',1)]\$
Output:
```
0
┌─────┐
│∧ │
│|\ │
0│└○\ │
│ │
│ │
└─────┘
```
---
Input: \$n=9\$, \$s=(3,-1)\$, \$D=[('N',2),('SW',8),('SE',3),('NE',8)]\$
Output:
```
0
┌─────────┐
│ ○ │
│ \ │
│ \ │
│ \ │
0│ /|⟩│
│ ∧ / / │
│⟨ \ / / │
│ \ \ / │
│ ∨ ∨ │
└─────────┘
```
---
Input: \$n=3\$, \$s=(1,1)\$, \$D=[('N',5),('W',5)]\$
Output:
```
0
┌───┐
│ |│
0│-○┐│
│ |│
└───┘
```
---
Input: \$n=11\$, \$s=(3,-5)\$, \$D=[('NW',8),('E',5),('SE',3),('SW',5),('N',6),('NE',10)]\$
Output:
```
0
┌───────────┐
│ ∧ │
│ / \ │
│┌--/-\ \ │
│ \ |/ \ \ │
│ \| \ \ │
0│ | / ⟩│
│ |\ / / │
│ | / ○ │
│ |/ \ │
│ ∨ \ │
│ \ │
└───────────┘
```
[Answer]
# JavaScript (ES6), 228 bytes
Takes input as `(n,x,y,[[dir,len],[dir,len],...])` where directions are encoded counterclockwise from \$0\$ for South to \$7\$ for South-West.
Outputs a string with `0` for a boundary, `1` for a trace and `3` for the final position.
```
(n,x,y,a)=>(g=X=>Y>n?'':(Y%n&&X%n&&a.map(([d,l],i)=>(M=H=>(h-X|v-Y||(k|=a[i+!l]?1:3),l--&&M(H=(h+H)%n?H:-H,h+=H,v+=V=(v+V)%n?V:-V)))(~-(D='12221')[d],V=~-D[d+2&7]),h=x+n/2,v=n/2-y,k=' ')&&k)+(X<n?'':`
`)+g(X++<n?X:!++Y))(Y=!++n)
```
[Try it online!](https://tio.run/##ZY5fa8IwFMXf/RTdg21CbpxpV3V1V18s9EVfhP6hFCxWrbOrMqUoiF/dJXU6mARO8ss59ySfaZXu59/r3YGX22xxXeKVlHCEE6QUB2SFIQ6iQTk0DIdEzVLXQyVp6yvdERJnUCSwVsExelJzHp4rHp3PZHPGNF6zlyIZCseiUHCu62PiIcmZR5vl0HO4BzlDDyqGPpKK@erad7hPKSUXTkZoCNM0hUHjLAEfL3wUZ8zUuwmFHI@sfDWhQqn8BBs0NIPq@oYyEn7U3501ZpStSMiY5NB5YSySvRHKQ0mv8225P2hTTUOt3W/8kitJ3MlVnnmnifKsBynv7UGBJPtOgfI6j07ldfuNGrfFolVsV2RJbGjLFceTAMwE4mmtLogkofRf9B0s4EJlb9EAempzwZLbxJX0PGOBgNuILUOB1OeMEKrYvn2iVz9v/xVPg5om0Lm9Itqq4voD "JavaScript (Node.js) – Try It Online")
### How?
Initializing and drawing into a 'canvas' (i.e. a matrix of characters) is a bit tedious and lengthy in JavaScript.
This code is using a different strategy: instead of storing the output in a 2D array, it builds a string character by character, from left to right and from top to bottom. At each iteration:
* We output a `0` if we're over a boundary.
* Otherwise, we simulate the full path and see if it's crossing our current position. We output either `1` or `3` if it does, or a space otherwise.
* We append a linefeed if we've reached the right boundary.
All in all, this may not be the shortest approach, but I thought it was worth trying.
[Answer]
# Java 10, ~~350~~ ~~343~~ ~~340~~ ~~336~~ ~~334~~ 332 bytes
```
(n,s,S,D)->{int N=n+2,x=N/2+s,y=N/2-S,i=N*N,t;var r=new char[N][N];for(;i-->0;)r[i/N][t=i%N]=i/N*t<1|i/N>n|t>n?'#':32;r[y][x]=42;for(var d:D)for(i=d[0];d[1]-->0;r[y+=i%7<2?1/y*2-1:i>2&i<6?1-y/n*2:0][x+=i>0&i<4?1-x/n*2:i>4?1/x*2-1:0]=42)i=y<2&i<2|y>=n&i>2&i<5?4-i:x<2&i>4|x>=n&i>0&i<4?8-i:y<2&i>6?5:y<n|i!=5?i:7;r[y][x]=79;return r;}
```
`D` is a 2D integer-array where the directions are 0-indexed integers: `N=0, NE=1, E=2, SE=3, S=4, SW=5, W=6, NW=7`. The starting `x,y`-coordinates will be two separate parameters `s` and `S`. The output is a character-matrix.
It uses `#` as border, `*` as trail, and `O` for the ending position (but can be all three be any ASCII characters in the unicode range `[33,99]` for the same byte-count if you'd want).
[Try it online.](https://tio.run/##nVNNb6MwEL3nV8xqtS2kpgESkhZickkOPSxaiQMHxIEFuutu6lTGaUEJvz07Nqifqx5WQjP2vHlvBo99lz/m1l3551Rs87qG7znjhxEA47ISt3lRwY3aAhS/c5FmaQaFgRhwolKg7l2snYbXZoD53QhNLXPJCrgBBvRkcFKTmKxNKzwoSkT5hUsaGk3ci5q0ylsxYTQaR0QGj7kAQXn11NeNMvyC250wAmZZoR2YImUTjErKvkUZxfVYLp0j@pAfZchX51/P/akbiLTN0iajM1ezlWzpr021ZrRM7SwoUyfTkph6gWqLpbtyJu3YtRyfhe4ZW85XjtVO@Nj1bdTCnNDG6AyjjY6yENeTRjNsVcpktF0qpntsQ8rPehlvNbOY3yggnB2bHuiVrhDQjHC@8nDFj@wL9VbMXzz/wOI6EJXcCw4i6E6BOt6H/c8tHu9wyo87VsI9Ts@IpWD8F44iN/vR9cdtE4g21CGwoS6BeEOnaOkMTUI9AgmdY0JCF1obQFa1NDBuEySqQQwDPhyihLgdOcTabojTdXrkA@WawJRYzntOT0nIlXIbMkUXbXD3hosdOeQj1cPkBO2bXMfRhbyPzV3ptryXQnGidxGZ91Ud@7@k3M@kXl94PQqt/OlLKc13L0tU9X4rgQK7LIbnUg59PuDwZfsDByuNPu3fVV/nPeve53gjmqGauvo9AmL3BP5b9AWHAjHMMIc4QNzWsrq/3O3l5UNfYGjuI7TlxoB1o8/wbtSd/gI)
-8 bytes thanks to *@ceilingcat*.
Can definitely be golfed some more by simplifying the movements and in which direction we're traveling some more.
**Explanation:**
```
(n,s,S,D)->{ // Method with `n`,`s,S`,`D` parameters & char-matrix return-type
int N=n+2, // Set `N` to `n+2`, since we use it multiple times
x=N/2+s, // Calculate the starting `x` coordinate
y=N/2-S, // Calculate the starting `y` coordinate
i=N*N, // Index integer
t; // Temp integer to save bytes
var r=new char[N][N]; // Result char-matrix of size `N` by `N`
for(;i-->0;) // Loop `i` in the range (`N**2`, 0]
r[i/N][t=i%N]= // Set the cell at position `i` divmod-`N` to:
i/N*t<1|i/N>n|t>n?// If we're at a border:
'#' // Set the current cell to '#'
: // Else:
32; // Set the current cell to ' ' (a space) instead
r[y][x]=42; // Then set the starting position `x,y` to a '*'
for(var d:D) // Loop over the `D` input:
for(i=d[0]; // Set `i` to the current direction
d[1]-->0 // Inner loop the current `d` amount of times
; // After every iteration:
r[y+= // Change `y` based on the current direction
i%7<2? // If the current direction is N, NE, or NW
1/y*2-1 // If we're at the top border:
// Go one row down
// Else
// Go one row up
:i>2&i<6? // Else-if the current direction is S, SE, or SW
1-y/n*2 // If we're at the bottom border
// Go one row up
// Else
// Go one row down
: // Else (directions E or W)
0] // Stay in the same row
[x+= // Change `x` based on the current direction
i>0&i<4? // If the current direction is E, NE, or SE
1-x/n*2 // If we're NOT at the right border
// Go one column to the right
// Else:
// Go one column to the left
:i>4? // Else-if the current direction is W, NW, or SW
1/x*2-1 // If we're NOT at the left border:
// Go one column to the left
// Else:
// Go one column to the right
: // Else (directions N or S)
0] // Stay in the same column
=42) // And fill this new `x,y` cell with a '*'
i= // Determine the new direction
y<2&i<2|y>=n&i>2&i<5?4-i:x<2&i>4|x>=n&i>0&i<4?8-i:y<2&i>6?5:y<n|i!=5?i:7;
// (See loose explanation below)
r[y][x]=79; // And finally set the last `x,y` cell to 'O'
return r;} // And return the result-matrix
```
`y<2&i<2|y>=n&i>2&i<5?4-i:x<2&i>4|x>=n&i>0&i<4?8-i:y<2&i>6?5:y<n|i!=5?i:7` is a golfed version of this below by using `4-i` and `8-i` for most direction changes:
```
y<2? // If we're at the top border
i==0? // If the current direction is N
4 // Change it to direction S
:i==1? // Else-if the current direction is NE
3 // Change it to SE
:i==7? // Else-if the current direction is NW
5 // Change it to SW
: // Else
i // Leave the direction the same
:x<2? // Else-if we're at the left border
i==7? // If the current direction is NW
1 // Change it to NE
:i==6? // Else-if the current direction is W
2 // Change it to E
:i==5? // Else-if the current direction is SW
3 // Change it to SE
: // Else
i // Leave the direction the same
:y>=n? // Else-if we're at the bottom border
i==3? // If the current direction is SE
1 // Change it to NE
:i==4? // Else-if the current direction is S
0 // Change it to N
:i==5? // Else-if the current direction is SW
7 // Change it to NW
: // Else
i // Leave the direction the same
:x>=n? // Else-if we're at the right border
i==1? // If the current direction is NE
7 // Change it to NW
:i==2? // Else-if the current direction is E
6 // Change it to W
:i==3? // Else-if the current direction is SE
5 // Change it to SW
: // Else
i // Leave the direction the same
: // Else
i // Leave the direction the same
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 74 bytes
```
NθJ⊘⊕θ⊘⊕θUR±⊕⊕θJN±NFA«≔⊟ιζF⊟ι«≔ζδ↷δ¶F›⊗↔ⅈθ≦±ζF›⊗↔ⅉθ≦⁻⁴ζ≧﹪⁸ζ↷⁴¶↶⁴↶δ↷ζ*¶↶ζPo
```
[Try it online!](https://tio.run/##dU/PT4MwFD6Pv6LZqZjuMMWo8bTERGdkWRYPGuTAoGNNSstKywGzvx0fBSZueGrf9@t9L95HKpYRr@ulyI1emWxLFT64j86ryfJ3iV8iXtIEL0WsaEaFhv/BdQkax8G3obGORMopXtE00vSP5Fz@u2e4HuJP3gHaqHdSoRaFGX07k0VRsFTgtcwxA18FmokVtYjV9KKKoKThJ2tWSr1h6V7jDlBMaDz9ElM72oBnRaGCwk/SbDn0XWwL/NG0IAiqIz/Ku9i2a7f7f@/niPeN7jT2mTAFQV6fcGLbhr5MDJcE3ff8oL031t7yNtk7my@ur4b@q8uArpDhmuWtSFrJ0TnWdfBA0A1BszlBQXANB4TwgZbz5gXirptvwzCsZyX/AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the format n, x, y, d where d is an array of arrays of [distance, direction] pairs where the direction is a numerical encoding 0 = south clockwise to 7 = south east. Explanation:
```
NθJ⊘⊕θ⊘⊕θUR±⊕⊕θ
```
Input `n` and draw a box whose interior is that size centred on the origin.
```
JN±N
```
Input and jump to `x` and `y` (but negate `y` because Charcoal's y-axis is increasing down).
```
FA«
```
Loop over the entries in `d`.
```
≔⊟ιζ
```
Extract the initial direction.
```
F⊟ι«
```
Repeat for the desired distance.
```
≔ζδ
```
Save the direction.
```
↷δ¶
```
Make an experimental move in that direction.
```
F›⊗↔ⅈθ≦±ζ
```
If this goes off the sides then flip the direction horizontally.
```
F›⊗↔ⅉθ≦⁻⁴ζ
```
If this goes off the top or bottom then flip the direction vertically.
```
≧﹪⁸ζ
```
Reduce the direction modulo 8 (the Pivot commands only accept values from 0 to 7).
```
↷⁴¶↶⁴
```
Undo the experimental move.
```
↶δ↷ζ*¶
```
Face the correct direction, and then print a trace and move.
```
↶ζPo
```
Face back to the default direction, and print the object in the current position.
[Answer]
# JavaScript, 206 bytes
Takes input as (n,x,y,[[dir,len],[dir,len],...]) where directions are encoded using bitmasks :
```
S : 1
N : 2
E : 4
W : 8
SE: 5 (1|4)
SW: 9 (1|8)
NE: 6 (2|4)
NW:10 (2|8)
```
Outputs a string with
```
- 1 for top and bottom boundary
- 4 for left and right boundary
- 5 for corners
- 0 for trace
- 8 for the final position.
```
The different values for boundaries are used to evaluate the next direction
```
(n,x,y,d)=>(Q=[e=`
5`+'1'[R='repeat'](n)+5,o=n+3,-o,c=[...e+(`
4`+' '[R](n)+4)[R](n)+e],1,1+o,1-o,,-1,o-1,~o],p=1-o*(~n/2+y)-~n/2+x,c[d.map(([q,s])=>{for(a=q;s--;p+=Q[a^=c[p+Q[a]]*3])c[p]=0}),p]=8,c.join``)
```
*Less golfed*
```
F=(n,x,y,d) => (
o = n+3, // vertical offset, accounting for boundaries and newline
// Q = offsets for different directions, bitmask indexed
Q = [, // 0000 no direction
o, // 0001 S
-o, // 0010 N
, // 0011 NS - invalid
1 , // 0100 E
1+o, // 0101 SE
1-o, // 0110 NE
, // 0111 NSE - invalid
-1, // 1000 W
o-1, // 1001 SW
-o-1],// 1010 NW
e = `\n5`+'1'.repeat(n)+5, // top and bottom boundary
c = [...e + (`\n4` + ' '.repeat(n) + 4).repeat(n) + e], // canvas
p = 1 - o*(~n/2+y) - ~n/2 + x, // start position
d.map( ([q,s]) => { // repeat for each element in 'd'
a = q; // starting offset pointer - will change when bounce
while( s-- )
{
c[p] = 0; // trace
b = c[p + Q[a]] // boundary value or 0 (space count 0)
a ^= b * 3 // xor with 0 if no bounce, else 3 or 12 or 15
p += Q[q] // advance position
}
})
c[p] = 8, // set end position
c.join``
)
```
**TEST**
```
var F=
(n,x,y,d)=>(Q=[e=`
5`+'1'[R='repeat'](n)+5,o=n+3,-o,c=[...e+(`
4`+' '[R](n)+4)[R](n)+e],1,1+o,1-o,,-1,o-1,~o],p=1-o*(~n/2+y)-~n/2+x,c[d.map(([q,s])=>{for(a=q;s--;p+=Q[a^=c[p+Q[a]]*3])c[p]=0}),p]=8,c.join``)
var out=x=>O.textContent+=x
var test=(n,x,y,d)=>{
var dd = d.map(([d,s])=>[,'S','N',,'E','SE','NE',,'W','SW','NW'][d]+' '+s)
out([n,x,y]+' ['+dd+']')
out(F(n,x,y,d))
out('\n\n')
}
test(5,0,0,[[10,2],[1,2],[4,1]])
test(9,3,-1,[[2,2],[9,8],[5,3],[6,8]])
test(11,3,-5,[[10,8],[4,5],[5,2],[9,5],[2,6],[6,10]])
```
```
<pre id=O></pre>
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~352~~ 323 bytes
Golfed down 29 bytes thanks to ceilingcat.
```
#define G(x,a)x+=a=x<2|x>m-3?-a:a
#define A(p)atoi(v[p])
m,r,c,x,y,s,a,b;main(q,v)int**v;{m=A(1)+2;int f[r=m*m];for(x=A(2)+m/2;r--;f[r]=32);for(y=A(s=3)+m/2;++s<q;)for(a=cos(A(s)*.8)*2,b=sin(A(s)*.8)*2,c=A(++s);c--;G(y,b),f[y*m+x]=42)G(x,a);for(f[y*m+x]=64;++r<m;puts(""))for(c=0;c<m;c++)putchar(c%~-m&&r%~-m?f[r*m+c]:35);}
```
[Try it online!](https://tio.run/##TY/LbsIwEEX3fAWiKvLEdps4QBHGRaz4CJSFcQmNhBOIKXLUx6d3OoBadWGNdI7vXNvJnXOIdy/bsqq3/RWLwkLkxpo4Vx/x2ct8Ie3M9n5vLNkB7Kmp2Hl9KKDnRSuciKITQVix0d5WNTuKM1T1KUnO@t2bJcuAK02gX65b4xNf6LJpWSSjgPtHpVspNbnC5AquriMXTH6znIf5UcOFW@OawMhB8jCFRImNCVT4DzhKUgC0o50r1okNiHLdJZ7HwowU3H54LfnDkxF1tHOvD2@nwAYDuHY5k2pH0HEOJNyrJXb/Jf1w2F7Ggl5MeVfM8jHoT0TMxphhSifDJ8xSHOEEc8ym367c211Aufc/ "C (gcc) – Try It Online")
The program takes input as command line arguments (like `a.out 10 1 1 3 5 0 4 7 2`):
* the first argument is the field size,
* the next two are initial coordinates \$(x,y)\$ of the actor,
* all pairs of arguments starting from the fourth are \$(d, t)\$ pairs where \$d\$ is direction (represented as a number 0..7, starting from 0=`E` and turning clockwise) and \$t\$ is number of steps.
### Explanation
```
// Update the coordinate AND simultaneously modify the direction (if needed)
#define G (x, a) x += a = x < 2 || x >= m - 2 ? -a : a
// Get the numeric value of an argument
#define A (p) atoi (v[p])
// variables
m, // width and height of the array with field data
r, c, // helpers
x, y, // current coordinates of the actor
s, // helper
a, b; // current direction of the movement
main (q, v) char **v;
{
// array size is field size + 2 (for borders)
m = A (1) + 2;
// allocate the array
int f[r = m * m];
// fill the array with spaces,
for
(
// but first get x of the actor
x = A (2) + m / 2;
r--;
f[r] = 32
);
// trace: iterate over remaining commandline argument pairs
for
(
// but first get y of the actor
y = A (s = 3) + m / 2;
++s < q; // loop until no args left
)
// for each such pair
for
(
a = cos (A (s) * .8) * 2, // get the x-increment
b = sin (A (s) * .8) * 2, // get the y-increment
c = A (++s); // then get the number of steps
c--;
// after each step:
G (y, b), // update y and maybe the y-direction
f[y * m + x] = 42 // draw the trail
)
G (x, a); // update x and maybe the x-direction
// output
for
(
f[x * m + y] = 64; // put a @ to the current position of the actor
++r < m; // r == -1 at the beginning of the loop so preincrement
puts("") // terminate each row with newline
)
// iterate over columns in the row
for (c = 0; c < m; c++)
putchar
(
c % ~ -m && r % ~ -m ? // if it is not a border cell,
f[r * m + c] // output the character from the array
: 35 // otherwise output the #
);
}
```
] |
[Question]
[
*Before you leave, you do not have to understand much musical notation to do this challenge.*
**EXPLANATION**
In standard sheet music, double clefs go across the page serving as reference points to the notes, letting you know what note should be played. If you are not already familiar with the treble and bass clef, here is a description from [Wikipedia:](https://en.wikipedia.org/wiki/Clef)
>
> A clef is a musical symbol used to indicate the pitch of written notes. Placed on one of the lines at the beginning of the stave, it indicates the name and pitch of the notes on that line. This line serves as a reference point by which the names of the notes on any other line or space of the stave may be determined.
>
>
>
[](https://i.stack.imgur.com/XTxdT.png)
In the image above, the top half of the lines is the Treble clef, denoted with a [](https://i.stack.imgur.com/z1ZdY.png)
The bottom half is the Bass clef, denoted with a [](https://i.stack.imgur.com/GZAcl.png)
As you can see on the treble clef a note on the bottom-most line is an **E**. (I am not counting notes outside of the clef lines for this challenge) On the bass clef, the lowest line is a **G**.
To complete this challenge, you must do the following:
**CHALLENGE**
Given an input in one of the following forms (your choice), convert it to the opposite clef. Whether it is the Treble or Bass clef can be a Truthey/Falsey value in your language (not just any two values), e.g.
**F# T**
or
**F# True**
or
**F# Treble**
but not
**F# -1**
or
**F# 4**
Spaces and capitalization are optional, Flats will not appear, and trailing whitespace is not allowed.
```
Input Expected Output
E Treble G
F Treble A
F# Treble A#
G Treble B
G# Treble C
A Treble C
A# Treble C#
B Treble D
C Treble E
C# Treble F
D Treble F
D# Treble F#
E Treble G
F Treble A
F# Treble A#
G Bass E
G# Bass F
A Bass F
A# Bass F#
B Bass G
C Bass A
C# Bass A#
D Bass B
D# Bass C
E Bass C
F Bass D
F# Bass D#
G Bass E
G# Bass F
A Bass F
A# Bass F#
```
Be forewarned, this is not a trivial constant difference challenge. Look closely at the inputs and outputs. If you look at a piano,
[](https://i.stack.imgur.com/I1Bfm.gif)
the black keys are sharps, denoted by #. Note that there is not an E# or a B#. This means that if you are given **G#** on the Bass clef, instead of returning **E#**, you need to return **F**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest byte-count wins.
[Answer]
# Befunge, ~~70~~ 64 bytes
```
~0~:70p##~+2%00p+"A"-~7%2++7%:3%2%00g*:10p+"A"+,00g!10g+#@_"#",@
```
[Try it online!](http://befunge.tryitonline.net/#code=fjB+OjcwcCMjfisyJTAwcCsiQSItfjclMisrNyU6MyUyJTAwZyo6MTBwKyJBIissMDBnITEwZysjQF8iIyIsQA&input=QyMgVHJlYmxl)
The input should be in the form `C# Treble` or `F Bass`, although the clef can simply be the first letter (i.e. `T` or `B`), since the rest of the input is ignored anyway.
**Explanation**
```
~0 Read the note and push a zero (the purpose of this will become apparent later).
~:70p Read the following sharp or space and write that out as the next instruction.
```
As a result of this code modification, the next sequence of instructions will take one of two forms:
```
##~ The first # jumps over the second, and thus we perform the read instruction.
#~ But if there's only one #, we'll ending up skipping the read instruction.
```
At this point the stack either contains `note,0,sharp,space` or `note,0,space`.
```
+2% Add the top two stack items mod 2, returning 1 if we read a sharp, else 0 if not.
00p Save this 'sharp' boolean for later use.
```
At this point the stack either contains `note,0` or just `note` (with an implicit zero below).
```
+ By adding the top two items, we combine the 0 (if present) onto the note below.
"A"- We can then subtract 'A' to convert the note into a number in the range 0 to 6.
~7%2+ Read the T/B clef, then mod 7 and add 2, returning 2 or 5 (the conversion offset).
+7% Add that offset to our note number, then mod 7, to get the converted note number.
:3%2% Make a dup, and calculate mod 3 mod 2 to determine the special cases (B# or E#).
00g* Multiply that by the 'sharp' boolean, since we only care if the input was sharp.
:10p Duplicate and save this special case boolean for later.
+ Now add it to the note number, since the special cases need to be offset by 1.
"A"+, Then we can finally convert the number back into a character and output it.
00g!10g+ Now we check if the original note was not sharp, or if this was a special case.
#@_ If so, we exit immediately.
"#",@ Otherwise, we output a '#'.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I have a feeling some arithmetic may win over this method.
```
ØAḣ7µW€ż;€”#$Ẏ
Ç”C4¦”F⁵¦
Ñi+_⁸?4ị¢
```
**[Try it online!](https://tio.run/##y0rNyan8///wDMeHOxabH9oa/qhpzdE91kDyUcNcZZWHu/q4DrcDmc4mh5YBKbdHjVsPLeM6PDFTO/5R4w57k4e7uw8t@v//v8F/JRdlJQA "Jelly – Try It Online")**
A full program taking 1) the clef indicator `0` or `1` for Bass or Treble respectively and 2) the note; and printing the resulting note.
Would be 31 bytes if `-4` and `4` were acceptable as the clef indicator input values (then `Ñi+_⁸?4ị¢` can become `Ñi+⁸ị¢`) but this has been clarified as not allowed unless -4 is falsey and 4 is truthy, which is not the case for Jelly.
### How?
Builds a keyboard with phantom `B#` and `E#` keys, finds the index of the input, offsets that by `4` in the required direction, indexes back into a keyboard with those phantom keys replaced by their required results (the key above them):
```
ØAḣ7µW€ż;€”#$Ẏ - Link 1, keyboard with phantoms: no inputs
ØA - alphabet yield -> ['A', 'B', ..., 'Z']
7 - literal seven
ḣ - head -> ['A','B','C','D','E','F','G']
µ - new monadic chain, call that K
W€ - wrap €ach -> ["A","B","C","D","E","F","G"] ("" being lists of characters)
$ - last two links as a monad:
”# - character '#'
;€ - concatenate to €ach -> ["A#","B#","C#","D#","E#","F#","G#"]
ż - zip together -> [["A","A#"],["B","B#"],["C","C#"],["D","D#"],["E","E#"],["F","F#"],["G","G#"]]
Ẏ - tighten -> ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]
Ç”C4¦”F⁵¦ - Link 2, keyboard with phantoms replaced: no inputs
Ç - call the last link (1) as a monad ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]
¦ - sparse application:
4 - ...to index: literal four
”C - ...action: character 'C' -> ["A","A#","B","C","C","C#","D","D#","E","E#","F","F#","G","G#"]
¦ - sparse application:
⁵ - ...to index: literal ten
”F - ...action: character 'F' -> ["A","A#","B","C","C","C#","D","D#","E","F","F","F#","G","G#"]
Ñi+_⁸?4ị¢ - Main link: integer, clef (1 Treble / 0 Bass); list of characters, key
e.g. 0; "D#"
Ñ - next link (1) as a monad (no atom for next link as a nilad, but this works here anyway)
- ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]
i - first index of key in that 8
4 - literal four
? - if:
⁸ - ...condition: chain's left argument, clef
+ - ...then: addition
_ - ...else: subtraction 4
¢ - next link as a nilad ["A","A#","B","C","C","C#","D","D#","E","F","F","F#","G","G#"]
ị - index into "C"
```
[Answer]
# Perl 5, 56 bytes
```
$_=<>;s/./chr 65+(-4*<>+ord$&)%7/e;s/B#/C/;s/E#/F/;print
```
Reads the note and clef as two lines from STDIN and prints the new note to STDOUT. The clef is `0` for treble and `1` for bass.
[Answer]
# JavaScript (ES6) 74 bytes
Takes input in currying syntax `(note)(clef)` where `clef` is `0` for *bass* and `1` for *treble*.
```
n=>c=>'FC.DAFCGDAEBF'[k=(parseInt(n,36)*15+!n[1]*90+c)%98%13]+(k<5?'#':'')
```
### Demo
```
let f =
n=>c=>'FC.DAFCGDAEBF'[k=(parseInt(n,36)*15+!n[1]*90+c)%98%13]+(k<5?'#':'')
;[1, 0].forEach(c => {
[ 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#' ].forEach(n => {
console.log(
(n + ' ').slice(0, 3) +
['Bass ', 'Treble'][c] +
' --> ' +
f(n)(c)
)
})
})
```
### How?
This is actually slightly less fun than my previous version, but the underlying lookup table is now `F#,C#,(unused),D#,A#,F,C,G,D,A,E,B,F` which allows to shorten the **#** condition while avoiding the *NUL* character trick -- which was a bit border-line, I suppose.
---
# Previous version ~~76~~ 75 bytes
```
n=>c=>'ACCDFF.CDEFGABCDE'[k=parseInt(4*!!n[1]+c+n,21)%24%17]+'\0#'[45>>k&1]
```
### Demo
```
let f =
n=>c=>'ACCDFF.CDEFGABCDE'[k=parseInt(4*!!n[1]+c+n,21)%24%17]+'\0#'[45>>k&1]
;[1, 0].forEach(c => {
[ 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#' ].forEach(n => {
console.log(
(n + ' ').slice(0, 3) +
['Bass ', 'Treble'][c] +
' --> ' +
f(n)(c)
)
})
})
```
### How?
The input **(n, c)** is processed through the following steps:
1. We first evaluate `4 * !!n[1] + c + n` where `!!n[1]` is **true** (coerced to **1**) if the note contains a **#**, and **false** (coerced to **0**) otherwise. The expression `4 * !!n[1] + c` results in a numeric value which is added in front of the string **n**.
2. Implicit step: leading zeros and trailing **#** are ignored by `parseInt()`. For instance, `"5G#"` is actually parsed as `"5G"`.
3. We convert the new string to a decimal value by parsing it as a base-21 quantity.
4. We apply modulo 24.
5. We apply modulo 17.
Below is the summary table for all possible input pairs, along with the expected output. Note that a **#** must be added to the output if the final result is **0**, **2**, **3** or **5**. Hence the use of the binary mask **101101** (**45** in decimal).
```
n | c | (1) | (2) | (3) | (4) | (5) | Output
-----+---+-------+-------+-----+-----+-----+-------
"E" | 1 | "1E" | "1E" | 35 | 11 | 11 | "G"
"F" | 1 | "1F" | "1F" | 36 | 12 | 12 | "A"
"F#" | 1 | "5F#" | "5F" | 120 | 0 | 0 | "A#"
"G" | 1 | "1G" | "1G" | 37 | 13 | 13 | "B"
"G#" | 1 | "5G#" | "5G" | 121 | 1 | 1 | "C"
"A" | 1 | "1A" | "1A" | 31 | 7 | 7 | "C"
"A#" | 1 | "5A#" | "5A" | 115 | 19 | 2 | "C#"
"B" | 1 | "1B" | "1B" | 32 | 8 | 8 | "D"
"C" | 1 | "1C" | "1C" | 33 | 9 | 9 | "E"
"C#" | 1 | "5C#" | "5C" | 117 | 21 | 4 | "F"
"D" | 1 | "1D" | "1D" | 34 | 10 | 10 | "F"
"D#" | 1 | "5D#" | "5D" | 118 | 22 | 5 | "F#"
-----+---+-------+-------+-----+-----+-----+-------
"E" | 0 | "0E" | "E" | 14 | 14 | 14 | "C"
"F" | 0 | "0F" | "F" | 15 | 15 | 15 | "D"
"F#" | 0 | "4F#" | "4F" | 99 | 3 | 3 | "D#"
"G" | 0 | "0G" | "G" | 16 | 16 | 16 | "E"
"G#" | 0 | "4G#" | "4G" | 100 | 4 | 4 | "F"
"A" | 0 | "0A" | "A" | 10 | 10 | 10 | "F"
"A#" | 0 | "4A#" | "4A" | 94 | 22 | 5 | "F#"
"B" | 0 | "0B" | "B" | 11 | 11 | 11 | "G"
"C" | 0 | "0C" | "C" | 12 | 12 | 12 | "A"
"C#" | 0 | "4C#" | "4C" | 96 | 0 | 0 | "A#"
"D" | 0 | "0D" | "D" | 13 | 13 | 13 | "B"
"D#" | 0 | "4D#" | "4D" | 97 | 1 | 1 | "C"
```
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
Function which prints to `STDOUT`. `True` converts bass to treble, and `False` converts treble to bass.
```
def f(n,c):N=ord(n[0])-63-4*c;M=-~N%3<1<len(n);print chr((N+M)%7+65)+n[1:2-M]
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI08nWdPKzza/KEUjL9ogVlPXzFjXRCvZ2tdWt85P1djG0CYnNU8jT9O6oCgzr0QhOaNIQ8NP21dT1VzbzFRTOy/a0MpI1zf2f5qGkruyko6CW2JOcaqmgrJCSFFqUk6qQkm@glNicTEXUN4NJB9SVAqWBgmCJCHK/gMA "Python 2 – Try It Online")**
Explanation:
* The first statement, `N=ord(n[0])-63-4*c;`, calculates the index (0 to 7) of the new note's letter, disregarding sharps.
+ `ord(N[0])-63-4*c` gets the current letter's index, and adds or subtracts 2 depending on the value of `c` (variable to toggle conversion direction)
* The next statement, `M=-~N%3<1<len(n);` calculates whether or not this variable will need to be adjusted. For example, if the new note is `E`, and the original note had a sharp, this will need to be adjusted to an `F`. The chained inequality works as follows:
+ `-~N%3<1` checks whether the new note's index is in the sequence `3n-1`. This will only yield true for `E` and `B`, the two notes which do not have a sharp.
+ `1<len(n)` checks if the original note had a sharp (this would make the string's length larger than 1). This is necessary as, if there was no sharp, there is no need to adjust the new note letters.
+ This sets the value of `M` to either `True` or `False`, which can be used in calculation as `1` and `0` respectively, so to perform the adjustment we need only add M to N and modulo by 7.
* The final statement creates and outputs the final result.
+ `chr((N+M)%7+65)` adds the adjustment if necessary, then converts the value from an index back to a character.
+ `+n[1:2-M]` will append a sharp symbol if both `M=0` (no adjustment was made) and the original value also had a sharp.
[Answer]
# Java 8, 119 bytes
```
n->b->(b?"C D E F G A B C# F F# A# C":"F G A B C D E F# A# C D# F").split(" ")["A B C D E F G A#C#D#F#G#".indexOf(n)/2]
```
**Explanation:**
[Try it here.](https://tio.run/##lZTBa8IwFMbv/hWP5NLCjLDj3DraxPY0dvAoHmKtIy6mxaYyGf7tXaQigWVLAz08kvfje9/ja/b8xKd1U6n99rMvJW9beONCfU8AWs21KGFvOkinhSS7TpVa1Irkt@J5qY9CfTz825PVtay4eoChOUmghBfo1TTZTJNo84ooMFhADgWkkAHFpswxpBgoekL346FpOAdmmlBM2kYKHSFA8QpZTVcEU8xwjguMiFDb6ut9F6l49rju58aZ@ZpuI425m8dTLbZwML6jYcjVGnh83QHA8tzq6kDqTpPGXGmpopLwppHnCC3MDEOpj10Vx3OA2azwYrkLS/0Y/sUZDHu5wiWX@TGXHPViqUttBOZU85vLXHLMi1EXtvBjrilzL8ZcaiMwp9qfO4nnAVHYcdmO921l4Q6OcZA69fKQNNh6IXGwBYuAPNhcGhIIa9ARPyVzCmYhmbAEacBTZevRgLfK5ljIY2XNya6LuUwu/Q8)
```
n->b-> // Method with String and boolean parameters and String return-type
(b? // If it's Treble:
"C D E F G A B C# F F# A# C"
// Use this String
: // Else (it's Bass):
"F G A B C D E F# A# C D# F")
// Use this String
.split(" ") // Split this String by spaces,
[ // and then get the item at index:
"A B C D E F G A#C#D#F#G#".indexOf(n)
// Get the index of the String on the left,
/2] // and divide this by 2
// End of method (implicit / single-line return-statement)
```
[Answer]
# [R](https://www.r-project.org/), 111 bytes
```
function(k,C,N=paste0(LETTERS[2:15%/%2],c("","#")))sub("E#","F",sub("B#","C",N[which(k==N[(4:17+6*C)%%14+1])]))
```
[Try it online!](https://tio.run/##NYpBC4IwGEDv/YxPBt@Xg5qYgbBD2dYlPNRuY4eSRBEsUunnLw12e4/3Pr6Wvp76amxfPXa84KV834fxucWLMkZdbzbJxY5tWOJ4hQAcIiCiYXogqGhWDfwvx0UK4KX9Nm3VYCdlaTHNxT7O1gUxJtJYOHJEvkY4z7eh1UyHAKcAS9Oh6dA0@R8 "R – Try It Online")
Ungolfed:
```
function(k,C){
N=paste0(LETTERS[2:15%/%2],c("","#")) # Generate a vector of the notes, including E# and B#
M=N[(4:17+6*C)%%14+1]) # Create a copy that's cycled either up 4 or down 4
P=N[which(k==M)] # Look up the input note in the complementary vector
P=sub("B#","C",P) # Replace B# with C
P=sub("E#","F",P) # Replace E# with F
}
```
] |
[Question]
[
## Challenge
Given the formula of a chemical, output the Mr of the compound.
## Equation
Each element in the compound is followed by a number that denotes the number of said atom in the compound. If there isn't a number, there is only one of that atom in the compound.
Some examples are:
* Ethanol (C2H6O) would be `C2H6O` where there are two carbon atoms, 6 hydrogen atoms and 1 oxygen atom
* Magnesium Hydroxide (MgO2H2) would be `MgO2H2` where there is one magnesium atom, two oxygen atoms and two hydrogen atoms.
Note that you will never have to handle brackets and each element is included only once in the formula.
Whilst most people will probably stick to the order they feel most comfortable with, there is no strict ordering system. For example, water may be given as either `H2O` or `OH2`.
## Mr
*Note:* Here, assume formula mass is the same as molecular mass
The Mr of a compound, the molecular mass, is the sum of the [atomic weights](https://en.wikipedia.org/wiki/Standard_atomic_weight) of the atoms in the molecule.
The only elements and their atomic weights to 1 decimal place that you have to support (hydrogen to calcium, not including noble gases) are as follows. They can also be found [here](https://pastebin.com/raw/zFrArJnd)
```
H - 1.0 Li - 6.9 Be - 9.0
B - 10.8 C - 12.0 N - 14.0
O - 16.0 F - 19.0 Na - 23.0
Mg - 24.3 Al - 27.0 Si - 28.1
P - 31.0 S - 32.1 Cl - 35.5
K - 39.1 Ca - 40.1
```
You should always give the output to one decimal place.
For example, ethanol (`C2H6O`) has an Mr of `46.0` as it is the sum of the atomic weights of the elements in it:
```
12.0 + 12.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 16.0
(2*C + 6*H + 1*O)
```
## Input
A single **string** in the above format. You can guarantee that the elements included in the equation will be actual elemental symbols.
The given compound isn't guaranteed to exist in reality.
## Output
The total Mr of the compound, to 1 decimal place.
## Rules
Builtins which access element or chemical data are disallowed (sorry Mathematica)
## Examples
```
Input > Output
CaCO3 > 100.1
H2SO4 > 98.1
SF6 > 146.1
C100H202O53 > 2250.0
```
## Winning
Shortest code in bytes wins.
>
> This post was adopted with permission from [caird coinheringaahing](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges#comment43964_12506). *(Post now deleted)*
>
>
>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 63 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5
fØDVȯ1×Ç
Œs>œṗ⁸ḊÇ€S
```
A monadic link accepting a list of characters and returning a number.
**[Try it online!](https://tio.run/##AYUAev9qZWxsef//4bifw5hET1Al4oG9wqHhuZvhu4vigJzDh@G5msOG4oCZQkgr4oCc4biyIsmm4bmA4oG3NjxzwqFfLcKmeeKBvOG4nsKhwqFGUMmT4oCYwqTDtzUKZsOYRFbIrzHDl8OHCsWScz7Fk@G5l@KBuOG4isOH4oKsU////0NhQ08z "Jelly – Try It Online")**
### How?
```
ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5 - Link 1, Atomic weight: list of characters
- e.g. "Cl23"
ØD - digit yield = "0123456789"
ḟ - filter discard "Cl"
O - cast to ordinals [67,108]
P - product 7236
⁽¡ṛ - base 250 literal = 1223
% - modulo 1121
¤ - nilad followed by link(s) as a nilad:
“ÇṚÆ’ - base 250 literal = 983264
B - convert to binary = [ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0]
H - halve = [ 0.5, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0]
“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘ - code-page indexes = [177 , 34 , 160 , 200 , 135, 54, 60, 115, 0, 95, 45, 5, 121 , 140 , 195 , 0, 0, 70, 80, 155]
+ - addition = [177.5, 34.5, 160.5, 200.5, 135, 54, 60, 115, 0, 95, 45, 5, 121.5, 140.5, 195.5, 0, 0, 70, 80, 155]
ị - index into (1-indexed and modular)
- ...20 items so e.g. 1121%20=1 so 177.5
÷5 - divide by 5 35.5
fØDVȯ1×Ç - Link 2: Total weight of multiple of atoms: list of characters e.g. "Cl23"
ØD - digit yield = "0123456789"
f - filter keep "23"
V - evaluate as Jelly code 23
ȯ1 - logical or with one (no digits yields an empty string which evaluates to zero)
Ç - call last link (1) as a monad (get the atomic weight) 35.5
× - multiply 816.5
Œs>œṗ⁸ḊÇ€S - Main link: list of characters e.g. "C24HCl23"
Œs - swap case "c24hcL23"
> - greater than? (vectorises) 10011000
⁸ - chain's left argument "C24HCl23"
œṗ - partition at truthy indexes ["","C24","H","Cl23"]
Ḋ - dequeue ["C24","H","Cl23"]
Ç€ - call last link (2) as a monad for €ach [ 288, 1, 816.5]
S - sum 1105.5
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~189 182~~ 168 bytes
-14 bytes by using the hash from [Justin Mariner's JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/125876/53748).
```
import re
lambda s:sum([[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][int(a,29)%633%35%18]*int(n or 1)for a,n in re.findall("(\D[a-z]?)(\d*)",s)])
```
**[Try it online!](https://tio.run/##HY2xboMwEIbn5iksSyh2dLF8PiAQKe1AVWVjyAgMrggqEhgE7tC@PMVd7v7/0326@cd/TY627lZvgx0/W8vW6/o9iqrKgRKVAOUKwcSKwGR7whgwBUKIdeAEZALVKgM0YC6QqhwwBw3YVL3zwoLJZZQSRZREmDWnAB2bFoay26cFx3rHlqfqetfaYRBc1O@VPf82b1LU7UlyWGUjD/04T4vfD7eg@efqgyd4YYuSODB@N48yDuHxkYZVoNZ3o02ZEJfXw8u8hNdBBHY8vx6Bdf9Nyu0P "Python 3 – Try It Online")**
---
Below is the 182 byte version, I'll leave the explanation for this one - the above just changes the order of the weights, uses `int` to convert the element name from base `29`, and uses different dividends to compress the range of integers down - see [Justin Mariner's answer](https://codegolf.stackexchange.com/a/125876/53748).
```
import re
lambda s:sum([[16,31,40.1,32.1,0,24.3,12,39.1,28.1,19,0,9,10.8,23,27,35.5,6.9,14,1][ord(a[0])*ord(a[-1])%1135%98%19]*int(n or 1)for a,n in re.findall("(\D[a-z]?)(\d*)",s)])
```
An unnamed function accepting a string, `s`, and returning a number.
**[Try it online!](https://tio.run/##JY1Ba4QwFITP3V8RArKJPENeolYX2h4sZW8e9qg5ZHGlgkZRe2j/vE3ay/dmhjfM8r1/zk4f/Ut7jHa6d5Zsl@1rYk2DOWiEVAoErTwkqFRoQAW69FYVHlj6uASUogClQT2DzkQGufBZCmiaee2YbaTh8b9K0PAIUWdRWURYmnhwO3NkXgny3tOCI4Mj60P0g@vsODLK2vfGJj/mjbO2izmFjRt@GqZlXnf/eITa/tj20GO0slWtKRB6Vbc6DeL2kYdToZRXJVWdacovp6dlDdOhCOScvJ6B9H@O8@MX "Python 3 – Try It Online")**
### How?
Uses a regex to split the input, `s`, into the elements and their counts using:
`re.findall("(\D[a-z]?)(\d*)",s)`
`\D` matches exactly one non-digit and `[a-z]?` matches 0 or 1 lowercase letter, together matching elements. `\d*` matches 0 or more digits. The parentheses make these into two groups, and as such `findall("...",s)` returns a list of tuples of strings, `[(element, number),...]`.
The number is simple to extract, the only thing to handle is that an empty string means 1, this is achieved with a logical `or` since Python strings are falsey: `int(n or 1)`.
The element string is given a unique number by taking the product of its first and last character's ordinals (usually these are the same e.g. S or C, but we need to differentiate between Cl, C, Ca, and Na so we cannot just use one character).
These numbers are then hashed to cover a much smaller range of [0,18], found by a search of the modulo space resulting in `%1135%98%19`. For example `"Cl"` has ordinals `67` and `108`, which multiply to give `7736`, which, modulo `1135` is `426`, which modulo `98` is `34`, which modulo `19` is `15`; this number is used to index into a list of integers - the 15th (0-indexed) value in the list:
`[16,31,40.1,32.1,0,24.3,12,39.1,28.1,19,0,9,10.8,23,27,35.5,6.9,14,1]`
is `35.5`, the atomic weight of Cl, which is then multiplied by the number of such elements (as found above).
These products are then added together using `sum(...)`.
[Answer]
# [PHP](https://php.net/), 235 bytes
```
preg_match_all("#([A-Z][a-z]?)(\d*)#",$argn,$m);foreach($m[1]as$v)$s+=array_combine([H,Li,Be,B,C,N,O,F,Na,Mg,Al,Si,P,S,Cl,K,Ca],[1,6.9,9,10.8,12,14,16,19,23,24.3,27,28.1,31,32.1,35.5,39.1,40.1])[$v]*($m[2][+$k++]?:1);printf("%.1f",$s);
```
[Try it online!](https://tio.run/##HY/dS8MwAMTf92fUCMl6C0v34WodYyuTiboJ88kYSqxZW@xHyMZA/2@fayccd/dy8Dub2/ZuYXPbM841LnHGNu5U1BldJ9vd60O8ZlGPaJfVcy8ONtOdF7XWmSyp9CnNE12W1Luicjl4U1IPftSC0ffPPrvy8D8CqVh0aJzRaU5JJYXSR3Jm5OjPtXP6O0mb6qOoDZUbPBVYGawQY4sd7rHVeM6wLLEv8II94hKPiLWCFJjyECHEkM8gAogxxBQiRDBCMOad3SCYcYFRp@CSEz7BKOzaeMiFYpKcVf/CEyjpky/fV4tbwSLrivp0oN41F4fuwJFFbftbN4O0ozd/ "PHP – Try It Online")
Instead of `array_combine([H,Li,Be,B,C,N,O,F,Na,Mg,Al,Si,P,S,Cl,K,Ca],[1,6.9,9,10.8,12,14,16,19,23,24.3,27,28.1,31,32.1,35.5,39.1,40.1])` you can use `[H=>1,Li=>6.9,Be=>9,B=>10.8,C=>12,N=>14,O=>16,F=>19,Na=>23,Mg=>24.3,Al=>27,Si=>28.1,P=>31,S=>32.1,Cl=>35.5,K=>39.1,Ca=>40.1]` with the same Byte count
[Answer]
# JavaScript (ES6), 150 bytes
```
c=>c.replace(/(\D[a-z]?)(\d+)?/g,(_,e,n=1)=>s+=[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][parseInt(e,29)%633%35%18]*n,s=0)&&s
```
Inspired by [Jonathan Allan's Python answer](https://codegolf.stackexchange.com/a/125852/69583), where he explained giving each element a unique number and hashing those numbers to be in a smaller range.
The elements were made into unique numbers by interpreting them as base-29 (0-9 and A-S). I then found that `%633%35%18` narrows the values down to the range of `[0, 17]` while maintaining uniqueness.
## Test Snippet
```
f=
c=>c.replace(/(\D[a-z]?)(\d+)?/g,(_,e,n=1)=>s+=[9,35.5,39.1,24.3,28.1,14,16,31,40.1,23,32.1,10.8,12,27,6.9,19,0,1][parseInt(e,29)%633%35%18]*n,s=0)&&s
```
```
Input: <input oninput="O.value=f(this.value)"><br>
Result: <input id="O" disabled>
```
[Answer]
## Clojure, ~~198~~ 194 bytes
Update: better to `for` than `reduce`.
```
#(apply +(for[[_ e n](re-seq #"([A-Z][a-z]?)([0-9]*)"%)](*(if(=""n)1(Integer. n))({"H"1"B"10.8"O"16"Mg"24.3"P"31"K"39.1"Li"6.9"C"12"F"19"Al"2"S"32.1"Ca"40.1"Be"9"N"14"Na"23"Si"28.1"Cl"35.5}e))))
```
Original:
```
#(reduce(fn[r[_ e n]](+(*(if(=""n)1(Integer. n))({"H"1"B"10.8"O"16"Mg"24.3"P"31"K"39.1"Li"6.9"C"12"F"19"Al"2"S"32.1"Ca"40.1"Be"9"N"14"Na"23"Si"28.1"Cl"35.5}e))r))0(re-seq #"([A-Z][a-z]?)([0-9]*)"%))
```
I'm wondering if there is a more compact way to encode the look-up table.
[Answer]
# [Python 3](https://docs.python.org/3/), 253 bytes
```
def m(f,j=0):
b=j+1
while'`'<f[b:]<'{':b+=1
c=b
while'.'<f[c:]<':':c+=1
return[6.9,9,23,40.1,24.3,27,28.1,35.5,31,32.1,39.1,1,10.8,12,14,16,19]['Li Be Na Ca Mg Al Si Cl P S K H B C N O F'.split().index(f[j:b])]*int(f[b:c]or 1)+(f[c:]>' 'and m(f,c))
```
[Try it online!](https://tio.run/##NZBva8IwEMbf@ynu3TXzFpqkOlusMAsibLODviyFtbWdkVqlZmxD/OwuEXaBe3L84Lk/p1@zO/bqdts2LRy8lvaxz6IRVPF@LEbwvdNdgx84b/MqKuZ4wagaxxbUcfVPuaO1oxFG9Z0Ojfka@nzKQwpJKgp8LkgGXJF8IjmzhZrwCSmr0hWhTfb5fEZCkghITEmERY6vGpYNbEpISnj7hOcOMg1JB@@QwQusYQkJbCCFFfLzqdPGY1z32@bHa/N9VBWseNC98dzwdXEcQLCxd591gYBlv71vXDN2ay00zdmA7iHHpExShQS4llkauE@2mjpJhO@vpS/TicLCXsnGaXAd8HKFxwVcrsit1aE0nnMj6@@U2Q7W4Q8 "Python 3 – Try It Online")
[Answer]
## Mathematica, ~~390~~ ~~338~~ 329 Bytes
Saved 9 bytes due to actually being awake now and actually using the shortening I intended.
Version 2.1:
```
S=StringSplit;Total[Flatten@{ToExpression@S[#,LetterCharacter],S[#,DigitCharacter]}&/@S[StringInsert[#,".",First/@StringPosition[#,x_/;UpperCaseQ[x]]],"."]/.{"H"->1,"Li"->3,"Be"->9,"B"->10.8,"C"->12,"N"->14,"O"->16,"F"->19,"Na"->23,"Mg"->24.3,"Al"->27,"Si"->28.1,"P"->31,"S"->32.1,"Cl"->35.5,"K"->39.1,"Ca"->40.1}/.{a_,b_}->a*b]&
```
Explanation:
Find the position of all the uppercase characters. Put a dot before each. Split the string at each dot. For this list of substrings do the following split it based on letters and split it based on digits. For the ones split by letters convert string to numbers. For the ones split by digits replace each chemical with its molecular weight. For any with a molecular weight and an atom count replace it with the product of them. Them find the total.
Version 1:
I'm sure this can be golfed lots (or just completely rewritten). I just wanted to figure out how to do it. (Will reflect on it in the morning.)
```
F=Flatten;d=DigitCharacter;S=StringSplit;Total@Apply[Times,#,2]&@(Transpose[{F@S[#,d],ToExpression@F@S[#,LetterCharacter]}]&@(#<>If[StringEndsQ[#,d],"","1"]&/@Fold[If[UpperCaseQ[#2],Append[#,#2],F@{Drop[#,-1],Last[#]<>#2}]&,{},StringPartition[#,1]]))/.{"H"->1,"Li"->3,"Be"->9,"B"->10.8,"C"->12,"N"->14,"O"->16,"F"->19,"Na"->23,"Mg"->24.3,"Al"->27,"Si"->28.1,"P"->31,"S"->32.1,"Cl"->35.5,"K"->39.1,"Ca"->40.1}&
```
Explanation:
First split the string up into characters. Then fold over the array joining lowercase characters and numbers back to their capital. Next append a 1 to any chemical without a number on the end. Then do two splits of the terms in the array - one splitting at all numbers and one splitting at all letters. For the first replace the letters with their molar masses then find the dot product of these two lists.
[Answer]
# Python 3 - 408 bytes
*This is mainly @ovs' solution, since he golfed it down by over 120 bytes... See the initial solution below.*
```
e='Li Be Na Ca Mg Al Si Cl P S K H B C N O F'.split()
f,g=input(),[]
x=r=0
for i in e:
if i in f:g+=[(r,eval('6.9 9 23 40.1 24.3 27 28.1 35.5 31 32.1 39.1 1 10.8 12 14 16 19'.split()[e.index(i)]))];f=f.replace(i,' %d- '%r);r+=1
h=f.split()
for c,d in zip(h,h[1:]):
s=c.find('-')
if-1<s:
if'-'in d:
for y in g:x+=y[1]*(str(y[0])==c[:s])
else:
for y in g:x+=y[1]*int(d)*(str(y[0])==c[:s])
print(x)
```
[Try it online!](https://tio.run/##dY9Ra4MwFIXf/RXnpZisNpjYdtUuD6swCtvaQR/FB9GoAbES3dD9@S4y6NNGIDnn3nsuX7ppqK9tcLsp6b5pHBROGeIM7xWeG1w04gYfuOAVRxwQ44QzXlzWd40eCHVKr5K67T6t9pLUGaWRvlNeDTR0CxU50OWvLqNqKRNiPPWVNcTdshAhRIC1zzjEmgUQjxA7a4IN2yCwr5hNaC97fLYDF@Br8C14eCdIFNNtoUaiaUppui9lyYzqmixXRHsuFsUK7sLQvVlK7tS2e0e3lLlXzGzfuiO1Vyc8SqlF7mXOSruVuCuXzj9Y8afe1q2yFTtfzAbzgmmOV9G4lFPC0wfSD4ZMiZ9SKfMk6lMbh2p69V9AtwMp6F@5zsy9kd5uMff9o/DFeRP8AA "Python 3 – Try It Online")
# Python 3 - ~~550 548~~ 535 bytes (lost the count with indentation)
Saved 10 bytes thanks to [@cairdcoinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) and 3 saved thanks to ovs
I had a personal goal to not use any regex, and do it the fun, old-school way... It turned out to be 350 bytes longer than the regex solution, but it only uses Python's standard library...
```
a='Li6.9 Be9. Na23. Ca40.1 Mg24.3 Al27. Si28.1 Cl35.5 P-31. S-32.1 K-39.1 H-1. B-10.8 C-12. N-14. O-16. F-19.'.split()
e,m,f,g,r=[x[:1+(x[1]>'-')]for x in a],[x[2:]for x in a],input(),[],0
for i in e:
if i in f:g.append((r,float(m[e.index(i)])));f=f.replace(i,' '+str(r)+'- ');r+=1;
h,x=f.split(),0
for i in range(len(h)):
if '-'in h[i]:
if '-'in h[i+1]:
for y in g:x+=y[1]*(str(y[0])==h[i][:h[i].index('-')])
else:
for y in g:
if str(y[0])==h[i][:h[i].index('-')]:x+=(y[1])*int(h[i+1])
else:1
print(x)
```
***[Try it online!](https://tio.run/##hZBda4MwFIbv/RXnzqQmwWjbVYuDtTAG@4RdihdhjRqwaYgO9Nd3SSuju1ou8vG8Oe97EjMN7Umn57Mowhe1ZhnsZMbgTSQpg71YxozDa5MsWQoPXXLH4FMlG8f2XbpiK/igKXeMpoljzzTN3PJEHdpRHrMN7ClPnBvlSwbvlK8ZPFKesZD1plMDwoEkR1KThtiiHMucR2gseXUf0hBX9cnCCEqDqIgTk/wPUdp8OwNSViQOvKC8IPMAVH3d13nDhDFSHxCypO5OYkDHUjKlD3JEClcY421d1MxK04kviRQJIYz6wSKLo5BCiLc2Kvg2aMnors0t38ZZoRuJOqlRi/E12rXuhLZUlTu7cYsiPkPwDpN3aPIxKib35gXywVMZV7gofHmZ@3nu9vIh@FIru17OLn@NfpnP/NfM5yIfjBdKD@janUu42BvR94GxXhjx@fwD)***
---
If anyone is willing to golf it down (with indentation fixes and other tricks...), it will be 100% well received, feeling like there's a better way to do this...
] |
[Question]
[
This is my friend Thomas. He is half tree, half emoticon.
```
| |
| :D |
| |
```
He is lonely. Let's make him some friends!
---
Given a text-based emoticon as input (e.g. `‡≤†_‡≤†`, `:P`, `>_>`, not `üòÄ`, `ü§ì`, or `üê¶`), output the corresponding treemote.
A treemote's length is how many characters it is lon (basically most builtin length functions for strings). So `ಠ_ಠ` has length 3.
The syntax for a treemote of length `n` is as follows:
```
|< 2+n spaces>| * ceil(n/2)
| <emote> | (note the spaces)
|< 2+n spaces>| * ceil(n/2)
```
So any treemote of length 3 would look like:
```
| |
| |
| ಠ_ಠ |
| |
| |
```
He has `ceil(n/2)` newline separated trunk segments on either side, each with `2 + n` spaces inside.
### Challenge: Given the text-based emoticon, output the corresponding treemote.
---
Other rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), which means I want you to write short code.
* Standard loopholes disallowed.
* You must support non-ascii characters unless your language can't handle them.
## Test Cases:
```
^_^
| |
| |
| ^_^ |
| |
| |
\o/
| |
| |
| \o/ |
| |
| |
(✿◠‿◠)
| |
| |
| |
| (✿◠‿◠) |
| |
| |
| |
D:
| |
| D: |
| |
( Õ°¬∞ Õú ñ Õ°¬∞)
| |
| |
| |
| |
| |
| |
| ( Õ°¬∞ Õú ñ Õ°¬∞) |
| |
| |
| |
| |
| |
| |
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~27~~ 25 bytes
Code:
```
g©Ìð×"|ÿ|
"®;îש„| ¹s¶®J
```
Explanation:
```
g # Push the length of the input string.
© # Copy that to the register.
Ì # Increment by 2.
√∞√ó # Multiply by spaces.
"|ÿ|\n" # ÿ is used for interpolation and push the string "|spaces|\n".
#
® # Retrieve the value from the register.
;î # Divide by 2 and round up.
√ó # Multiply that by "|spaces|".
© # Copy this into the register.
„| # Push the string "| ".
 # Bifurcate, pushing the string and the string reversed.
¬πs # Push input and swap.
¶ # Push a newline character.
®J # Retrieve the value from the register and join everything in the stack.
# Implicitly output this.
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Z8Kpw4zDsMOXInzDv3wKIsKuO8Ouw5fCqeKAnnwgw4LCuXPCtsKuSg&input=XG8v).
[Answer]
# Python 3.5, ~~76~~ ~~75~~ 73 bytes:
(*Thanks to [Blue](https://codegolf.stackexchange.com/users/42855/blue) for a tip which saved 2 bytes!*)
```
def i(n):q=len(n);z=('|'+' '*(2+q)+'|\n')*-(-q//2);print(z+'| '+n+' |\n'+z)
```
[Try It Online! (Ideone)](http://ideone.com/LFFvRe)
Also, here is a **noncompeting Python 2.7.5** version since it is much longer at **87 bytes**.
```
def i(n):q=len(n.decode('utf-8'));z=('|'+' '*(2+q)+'|\n')*-(-q/2);print z+'| '+n+' |\n'+z
```
This is because Python 2's default encoding is `ascii`, and therefore, characters such as `ಠ` outside the 128 unicode point range count as more than 1 byte (`list('ಠ')` yields `['\xe0', '\xb2', '\xa0']`). The only workaround I could think of for this was to first decode the input using `utf-8`, and then move on with this `utf-8` decoded string.
[Try This Python 2 Version Online! (Ideone)](http://ideone.com/EMCKzx)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~37~~ ~~34~~ 33 bytes
```
{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}
```
Chrome users: See footnote\*
### Test cases
```
f←{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}
f,'‚ò∫' ‚çù the , is necessary to create a 1 char string instead of a character scalar
| |
| ‚ò∫ |
| |
f':D'
| |
| :D |
| |
f'^_^'
| |
| |
| ^_^ |
| |
| |
```
---
\*Chrome misdisplays the two characters `≢⍵` (U+2262,U+2375) as `≢⍵` (U+2261,U+0338,U+2375) instead of as `̸≡⍵` (U+0338,U+2262,U+2375), so here is a display version for Chrome: `{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×̸̸≡⍵}`
[Answer]
# V, ~~60~~ 57 bytes
```
I| A |ByWo=ceil(len(""")/2.0)
dF.d0kwviWr Yu@-pH@-P
```
Unfortunately, V has next to nothing in terms of mathematical operations. The divide and ceil functions *drastically* inflated the byte count.
Since this contains a bunch of nasty unprintables, here is a reversible hexdump:
```
00000000: 497c 201b 4120 7c1b 4279 576f 123d 6365 I| .A |.ByWo.=ce
00000010: 696c 286c 656e 2822 1222 2229 2f32 2e30 il(len("."")/2.0
00000020: 290d 201b 6446 2e64 306b 7776 6957 7220 ). .dF.d0kwviWr
00000030: 5975 402d 7048 402d 50 Yu@-pH@-P
```
Explanation:
```
I| A | #Add surrounding bars
B #Move back
yW #Yank a word
o #Open a new line
<C-r>= #Evaluate
<C-r>" #Insert the yanked text into our evaluation
ceil(len(" ")/2.0)<cr> #Evaluate ceil(len(text)/2) and insert it
dF. #Append a space and delete backward to a (.)
#By default, this will be in register "-
d0 #Delete this number into register a
kw #Move up, and forward a word
viWr #Replace the emoticon with spaces
Yu #Yank this line, and undo
#(so we can get the emoticon back)
@-p #Paste this text "- times.
H #Move to the beginning
@-P #Paste this text "- times behind the cursor.
```
[Answer]
# Vitsy, 43 bytes
```
IV2m3mz4m2m
3mV\D4m
V1+2/\[1m]
' || '
}}ZaO
```
Explanation:
```
IV2m3mz4m2m
I Grab the length of the input string.
V Save that value to a global final variable.
2m Call the method at line index 2.
3m Call the method at line index 3.
z Push the entire input to the stack.
4m Call the method at line index 4.
2m Call the method at line index 2.
3mV\D4m
3m Call the method at line index 3.
V Push the global variable to the stack.
\D Duplicate the top item on the stack that many times.
4m Call the method at line index 4.
V1+2/\[1m]
V Push the global variable to the stack.
1+ Add one to the top value.
REASONING: We want ceil(V/2), and since repeat commands follow the floor value of repeats, we want ceil(V/2)+.5, so we add one to make this work right.
2/ Divide by two.
\[1m] Call method 1 that top value of the stack times.
' || '
' || ' Push ' || ', the string, to the stack.
}}ZaO
}} Push the bottom item of the stack to the top twice.
Z Output everything in the stack.
aO Output a newline.
```
[Try it online!](http://vitsy.tryitonline.net/#code=SVYybTNtejRtMm0KM21WXEQ0bQpWMSsyL1xbMW1dCicgfHwgJwp9fVphTw&input=&args=OkQ)
~~Note that, due to a bug in TIO, input with unicode characters will not work. You'll have to use the local version instead for those.~~ Thanks, @Dennis!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 22 bytes
```
Lð*w?L½⌈ẋfpømƛ‛| p‛ |+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=L%C3%B0*w%3FL%C2%BD%E2%8C%88%E1%BA%8Bfp%C3%B8m%C6%9B%E2%80%9B%7C%20p%E2%80%9B%20%7C%2B&inputs=%5E_%5E&header=&footer=)
```
L√∞* # Length spaces
w ẋf # Repeated
?L¬Ω‚åà # Ceiling of input length/2
p # Append input
√∏m # Mirror
∆õ‚Äõ| p‚Äõ |+ # Foreach, prepend '| ' and append ' |'
```
[Answer]
## Pyke, 31 bytes
```
"||
"1dQlO*:Ql_2f_*iO"| |"2Q:i
```
[Try it here!](http://pyke.catbus.co.uk/?code=%22%7C%7C%0A%221dQlO%2a%3AQl_2f_%2aiO%22%7C++%7C%222Q%3Ai&input=%E0%B2%A0_%E0%B2%A0)
Thanks [@R.Kap](https://codegolf.stackexchange.com/users/52405/r-kap) for saving a byte with the floor divide trick
[Answer]
# Ruby, 57 bytes
Uses integer division tricks and takes advantages of the quirks in Ruby's `puts` function.
```
->e{s=e.size+1;puts k=[?|+' '*-~s+?|]*(s/2),"| #{e} |",k}
```
[Answer]
# JavaScript ES6, ~~83~~ 78 bytes
```
e=>(a=`| ${" ".repeat(n=e.length)} |
`.repeat(Math.ceil(n/2)))+`| ${e} |
${a}`
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 103 bytes
```
i:0(?\
}$&1[\~rl:::2%+*:2,
1-:?!\" "$
]{\ \~
?!\$}1-:
~&\
?!\l$:@-[l2)
~]\
}}\" || "
?!\ol
8.>]l?!;ao2
```
[Try it online!](http://fish.tryitonline.net/#code=aTowKD9cCn0kJjFbXH5ybDo6OjIlKyo6MiwKMS06PyFcIiAiJApde1wgIFx-Cj8hXCR9MS06Cn4mXAo_IVxsJDpALVtsMikKfl1cCn19XCIgfHwgIgo_IVxvbAo4Lj5dbD8hO2FvMg&input=T19v)
This solution is based on the observation that each line consists of `| <x> |`, where `<x>` is the pattern in the middle line, and the same number of spaces in the other lines.
After reading the input (length `n`) from STDIN, the program pushes `n*(n+(n%2))` spaces. The stack is then rolled half as many times. Next, all but `n` characters are pulled to a new stack, leaving a stack of stacks consisting of either `n` spaces or the pattern itself (in the middle stack only). In the output step, the contents of the current stack are printed, surrounded by `|` and `|`.
[Answer]
## C, 89 bytes
```
f;main(int c,char**a){for(c=strlen(*++a)+1;f<(c|1);)printf("|%*s |\n",c,f++==c/2?*a:"");}
```
Not sure if it will handle non-ascii emoticon though....
[Answer]
## PowerShell v3+, 72 bytes
```
param($a)$b=("| "+(" "*($l=$a.length))+" |`n")*($l+1-shr1);"$b| $a |";$b
```
Takes input string `$a`. Constructs `$b` as (the empty pipe-ended string (with `$a.length` spaces in the middle) and a trailing newline) repeated (length+1 shifted right one bit, i.e., divided by two and ceiling'd) times. Then outputs the copies of `$b`, the input string with its own pipes, and finally the copies of `$b` again.
Requires v3+ for the bit-shift [`-shr` operator](https://technet.microsoft.com/en-us/library/hh848303(v=wps.620).aspx).
### Examples
```
PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:-|'
| |
| |
| >:-| |
| |
| |
PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:`-('
| |
| |
| |
| >:`-( |
| |
| |
| |
```
[Answer]
# Pyth, 30 bytes
I'm surprised that such an easy task isn't implemented in Pyth.
```
Ls[K\|dbdK)j++J*/hlQ2]sym;QyQJ
```
[Try it online!](http://pyth.herokuapp.com/?code=Ls[K%5C|dbdK%29j%2B%2BJ*%2FhlQ2]sym%3BQyQJ&input=%22%E0%B2%A0_%E0%B2%A0%22&debug=0)
[Answer]
# TSQL, ~~96~~ 88 bytes
```
DECLARE @ varchar(100)='^_^'
PRINT STUFF(REPLICATE('|'+SPACE(2+LEN(@))+'|
',LEN(@)*2-1),LEN(@)*(LEN(@)+5)-3,LEN(@),@)
```
[Try online!](https://data.stackexchange.com/stackoverflow/query/488093/grow-a-treemote)
] |
[Question]
[
Your job will be to write a function or a program, that will take an integer `n>0` as input and output a list of the edges of the `n`-dimensional [hypercube](http://mathworld.wolfram.com/HypercubeGraph.html). In graph theory an edge is defined as a 2-tuple of vertices (or corners, if you prefer), that are connected.
## Example 1
A 1-dimensional hypercube is a line and features two vertices, which we will call `a` and `b`.
[](https://i.stack.imgur.com/UWC1S.png)
Therefore, the output will be:
```
[[a, b]]
```
## Example 2
The 4-dimensional hypercube (or tesseract) consists of 32 edges and its graph looks like this
[](https://i.stack.imgur.com/geKv3.png)
and the output could look like this
```
[[a, b], [a, c], [a, e], [a, i], [b, d], [b, f], [b, j], [c, d], [c, g], [c, k], [d, h], [d, l], [e, f], [e, g], [e, m], [f, h], [f, n], [g, h], [g, o], [h, p], [i, j], [i, k], [i, m], [j, l], [j, n], [k, l], [k, o], [l, p], [m, n], [m, o], [n, p], [o, p]]
```
## Rules
* You may name the vertices any way you like, as long as the name is unique.
* The edges are undirected, i.e. `[a, b]` and `[b, a]` are considered the same edge.
* Your output must not contain duplicate edges.
* The output may be in any sensible format.
* Standard loopholes are forbidden.
## Scoring
Shortest code wins.
[Answer]
## Python 2, 54 56 62 bytes
```
lambda n:{tuple({k/n,k/n^1<<k%n})for k in range(n<<n)}
```
Duplicate edges are removed by making a set of sets, except Python requires that set elements are hashable, so they are converted to a tuples. Note that the sets `{a,b}` and `{b,a}` are equal and convert to the same tuple. xsot saved 2 bytes with `n<<n`.
This can be cut down to 49 bytes if strings of sets are an OK output format
```
lambda n:{`{k/n,k/n^1<<k%n}`for k in range(n<<n)}
```
which gives output like
```
set(['set([1, 3])', 'set([2, 3])', 'set([0, 2])', 'set([0, 1])'])
```
---
```
lambda n:[(k/n,k/n^1<<k%n)for k in range(n*2**n)if k/n&1<<k%n]
```
First, let's look at an older version of the solution.
```
lambda n:[(i,i^2**j)for i in range(2**n)for j in range(n)if i&2**j]
```
Each a number in the interval `[0,2^n)` corresponds to a vertex with coordinates given by its `n`-bit binary strings. To vertices are adjacent if they differ in a single bit, i.e. if one is obtained from the other by xor-ing a power of 2.
This anonymous function generates all possible edges by taking every vertex and every bit position to flip. To avoid duplicating an edge in both directions, only 1's are flipped to 0's.
In the more golfed solution, `k` is used to encode both `i` and `j` via `k=n*i+j`, from which `(i,j)` can be extracted as `(k/n,k%n)`. This saves a loop in the comprehension. The powers of `2` are done as `1<<` to have the right operator precedence.
An alternative approach of generating each pair of vertices and checking if they are a bit flip apart seems longer (70 bytes):
```
lambda n:[(i,x)for i in range(2**n)for x in range(i)if(i^x)&(i^x)-1<1]
```
[Answer]
# Jelly, 13 bytes
```
ạ/S’
2ṗœc2ÇÐḟ
```
[Try it here.](http://jelly.tryitonline.net/#code=4bqhL1M9MQoyUuG5l8WTYzLDh8OQZg&input=&args=Mw) For input `3`, the output is:
```
[[[1, 1, 1], [1, 1, 2]],
[[1, 1, 1], [1, 2, 1]],
[[1, 1, 1], [2, 1, 1]],
[[1, 1, 2], [1, 2, 2]],
[[1, 1, 2], [2, 1, 2]],
[[1, 2, 1], [1, 2, 2]],
[[1, 2, 1], [2, 2, 1]],
[[1, 2, 2], [2, 2, 2]],
[[2, 1, 1], [2, 1, 2]],
[[2, 1, 1], [2, 2, 1]],
[[2, 1, 2], [2, 2, 2]],
[[2, 2, 1], [2, 2, 2]]]
```
I hope `[1, 1, 1]` etc. is an okay “name”.
### Explanation
The first line is a “predicate” on a pair of edges: `[A, B] ạ/S’` is equal to `sum(abs(A - B)) - 1`, which is zero (false-y) iff `A` and `B` differ in exactly one coordinate.
The second line is the main program:
* Generate all edges with `2ṗ` (Cartesian power of `[1, 2]`).
* Get all possible pairs using `œc2` (combinations of size two without replacement).
* Keep only elements satisfying the predicate defined earlier (`ÐḟÇ`).
[Answer]
# Mathematica, ~~48~~ 24 bytes
```
EdgeList@*HypercubeGraph
```
Just an anonymous function that uses built-ins.
[Answer]
## JavaScript (SpiderMonkey 30+), ~~69~~ 64 bytes
```
n=>[for(i of Array(n<<n).keys())if(i/n&(j=1<<i%n))[i/n^j,i/n^0]]
```
This started out as a port of @xnor's Python 2 solution but I was able to save 9 bytes by rewriting the code to use a single loop. Edit: Saved a further 5 bytes by splitting `i` up the other way around, as per @xnor's updated solution, which now also uses a single loop.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 20 bytes
```
2i^:qt!Z~Zltk=XR2#fh
```
This works with [current version (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler.
[**Try it online!**](http://matl.tryitonline.net/#code=MmleOnF0IVp-Wmx0az1YUjIjZmg&input=NA)
### Explanation
This uses more or less the same idea as [@xnor's answer](https://codegolf.stackexchange.com/a/75656/36398).
```
2i^ % take input n and compute 2^n
:q % range [0,1,...,2^n-1] (row vector)
t! % duplicate, transpose into a column vector
Z~ % bitwise XOR with broadcast
Zl % binary logarithm
tk % duplicate and round down
= % true if equal, i.e. for powers of 2
XR % upper triangular part, above diagonal
2#f % row and index columns of nonzero values
h % concatenate vertically
```
[Answer]
# Pyth, 13 bytes
```
fq1.aT.c^U2Q2
```
[Output on input 3](https://pyth.herokuapp.com/?code=fq1.aT.c%5EU2Q2&input=3&debug=0):
```
[[[0, 0, 0], [0, 0, 1]], [[0, 0, 0], [0, 1, 0]], [[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [0, 1, 1]], [[0, 0, 1], [1, 0, 1]], [[0, 1, 0], [0, 1, 1]], [[0, 1, 0], [1, 1, 0]], [[0, 1, 1], [1, 1, 1]], [[1, 0, 0], [1, 0, 1]], [[1, 0, 0], [1, 1, 0]], [[1, 0, 1], [1, 1, 1]], [[1, 1, 0], [1, 1, 1]]]
```
Explanation:
```
fq1.aT.c^U2Q2
Implicit: input = Q
^U2Q All Q entry lists made from [0, 1].
.c 2 All 2 element combinations of them.
f Filter them on
.aT The length of the vector
q1 Equaling 1.
```
[Answer]
# Python 2: 59 bytes
```
lambda n:[(a,a|1<<l)for a in range(2**n)for l in range(n)if~a&1<<l]
```
] |
[Question]
[
Input a datetime, format the datetime in `YYYY-MM-DD HH:mm:ss` format using 30-hour clock time.
The 30-hour clock time works as:
* After 6 a.m., it is same as 24-hour clock time
* Before 6 a.m., it use date for previous day, and plus Hours by 24.
For more examples, you may checkout the testcases.
## Rules
* To simplify the question
+ You may choose to use client timezone or UTC timezone by your prefer;
+ You may assume the client timezone don't have DST;
+ You may assume no leap second.
* This is code-golf.
* Input can be in any convenience format. Although certainly, you cannot take input in 30-hour clock time.
* Output need to be a string, displayed on screen, or other similar replacements with exactly specified format.
## Testcases
```
Input -> Output
2023-12-01 00:00:00 -> 2023-11-30 24:00:00
2023-12-01 01:23:45 -> 2023-11-30 25:23:45
2023-12-01 05:59:59 -> 2023-11-30 29:59:59
2023-12-01 06:00:00 -> 2023-12-01 06:00:00 or 2023-11-30 30:00:00
2023-12-01 06:00:01 -> 2023-12-01 06:00:01
2023-12-01 12:34:56 -> 2023-12-01 12:34:56
2023-12-01 23:59:59 -> 2023-12-01 23:59:59
2024-01-01 02:00:00 -> 2023-12-31 26:00:00
2024-03-01 00:00:00 -> 2024-02-29 24:00:00
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62 56~~ 48 bytes
```
->d{r="#{d-21600}"[0,19];60000.times{r.succ!};r}
```
[Try it online!](https://tio.run/##bZJBa4MwFIDPza/IuhwsJGnyYgTT2tN23Wk38dBVCwXbFbWMYd1fd1HXVa3h8QgfH8l7eckuH9/1PqjZJi6zYP5cxgykJ0Q1DwWVfrSyeyF4cTgmeZnx/LLbPVWrrKrjbZHkwXr9@vbC08MpyREIUEwCExILYdrAbIM7LJkSGNwOD1RpQBlXj1Xd4YGqjfZtjFW/wwPVGxcwxJ9Z/wQlJurqVDl9guyrEoxyjfZG6g33VdvTqIUBblTXgvYmeGxBWdW712pVNfHcFgMD//7cdkaonRc/bs/lNb2iWRr8LB1u14I5t4SbZP7TEuG/VQTvdv78lHw5RFIClChKXEo0Jd4Czc44LOg@LCKahqCaXxOhqv4F "Ruby – Try It Online")
[Answer]
# Excel ms365, 71 bytes
Assuming input as normal date-time value in `A1`:
```
=LET(x,MOD(A1,1),y,x<0.25,TEXT(A1-y,"e-mm-dd ")&TEXT(x+y,"[hh]:mm:ss"))
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~81~~, ~~89~~, 86 bytes
```
h=$[24+10#${1:11:2}];r=`date -d$1-$[h<30]day +%F\ %T`;((h<30))&&r=${r/ ??/ $h};echo $r
```
[Try it online!](https://tio.run/##fZFha4MwEIa/@yuOLJWKC80lWjDO9dt@Qb85oa4qjg06XCkb1t/uTkXGrA5CIPfkOe7lXtLPsi3WTt2WEY@V56K84zUaRKOaJKyiQ5aecxAZR8Hj8kHLJEu/wV09PcNqfwjX667mOLZdRbyuNrDbbYCXTZgfyxPwqm2sC3W3AKhVAYwjO9AjjoEriOgDJAnYNvTfiYJ47MjpjcH1@rdaQZG@vt93OP/6yI/nPGNWY1kXYEoqLVAJiXspTX/c/mYjQ6ElKG9gbOpQWG08f9bxB3bj@MYP6Mw6wcBunO3sbB2DkS04@I@DUweV0Z7xt3POyKYOhZzL0zsjGx2Piv1saiGPJmeShxy9tB9iSqjgdz/tDw "Bash – Try It Online")
# [Perl 5](https://www.perl.org/) `-MPOSIX=strftime -p`, 99 bytes
```
@a=reverse/\d+/g;$a[5]-=1900;--$a[4];$h=$a[2]+24;--$a[3];$_=strftime("%F %T",@a),s/ ../ $h/ if$h<30
```
[Try it online!](https://tio.run/##bc/NCoJAEADge0@xhEGh2/4LrS14CjpEQR2CkhBaU6gUV3r8tkWhFII5zHwwf5Wu78LaOFW1funaaHS@@ugWeelJJFCRBcYRhK7iSeTlyiU08SnvjDm7KNPUWVM89HQ8WYHJYRzE6SwwCMznCHg5AkXm5UuGraWYMkgoxARgLNsY9Y1IyiQXAxNSLFwMLPzT2xnpG6GScSnCvrkF33ncQdtLf/OcscF977JqivJpLNzstvv18futhffqAw "Perl 5 – Try It Online")
[Answer]
# [Factor](https://factorcode.org), 78 bytes
```
[ dup hour>> 6 < [ 1 days time- [ 24 + ] change-hour ] when timestamp>ymdhms ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDNSsQwFIVxO09xmK1UmvQHjdKtiDAbcTXMIqSpKU7TmqTIID6Jm270AXwbfRrvTGFgpmO4kNx895xD8vFVSRVaN_ye3T8-3C1uBZRca1tKtz9cVK1rZIDXL722SnvULejCQCrqfOs8nrWzeo3r2dsMtOY85knEeBQzxLHY1XxKmOCJSLMTJBPZFdUJkv_rNhI2JYyLJBVZPiUUf5ST0vXOjR_nEEkO3_OOJTZNaRpfhLrRPsimw4q-pvvsQxVd_iyWKPsOpu1dUSDHDQkYSrnx2AoianmKc9IoI-2TjraT1L0abbG3LMYMrEbXb_InYedqG2hWS2VGMAzj_gc)
Takes a timestamp object (in 24-hour time); returns a string.
* `dup hour>> 6 <` is the hour less than six?
* `[ ... ] when` then do `...`
* `1 days time-` subtract one day
* `[ 24 + ] change-hour` add twenty-four hours in a way that doesn't roll the day over
* `timestamp>ymdhms` change the timestamp to a string in the required format
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 55 bytes
Anonymous prefix lambda, taking a Dyalog Date Number (number of days since the beginning of 1899-12-31) as argument.
```
{' 1'⎕R' 2'⍣a⊢'T'⎕R' '⊃'%ISO%'(1200⌶)⍵-12÷⍨5×a←1>4×1|⍵}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY_BSsNAEIbvPsVcylZoILtJitmDpxLwohB7l9VGKaRNqFtBag8qlBJM8SIVilIUoYg3Ue_2KXqdJ3GaFE1BmMPwzcz__zN5bZyrMDo5UHE4nb509bGxtfA9HNz2GHCGozufgWCYPitMnlh9RRgm16y0s79XYmUuTBNvPjcx_TC4mH9hOnPmY0USfNuej_kFDfor5cse3dPEA05NrY7JFaaj71kZhwkO75cMkwE5kdpjn1xd6jF9A0wfwAXdbAWnEvxANaDZjru6AkdR-yzoaNAR1LJPoKZ0sFyE3W7rMOjQigpD8CoQd5ptnQeZLt6FKSzKa5gcTFNmtVFkXApL2s4ac6TjUq2x6j-3OeNFxoW0bOlUi4wMfvVsAtmt-NMjZhXz5dl_AA)
`{`…`}` "dfn"; argument is `⍵`:
`⍵` the argument
`1|` remainder when the divided by 1 (i.e. the fractional part)
`4×` four times that
`1>` is 1 greater than that? (i.e. is the time part of the argument before 06:00?)
`a←` store this in `a` (for **a**djust)
`5×` five times that
`12÷⍨` that divided by twelve (this gives the number of days to subtract corresponding to subtracting ten hours)
`'%ISO%'(1200⌶)` represent the Dyalog Date Number as an array of ISO 8601 extended format strings (`YYYY-MM-DD"T"hh:mm:ss`)
`⊃` get the first element of that (since we returned an array of strings)
`'T'⎕R' '` **R**eplace the letter `"T"` with a space (since the ISO format separates date and time with a "T")
…`⍣a⊢` if we need to adjust (`a`):
`' 1'⎕R' 2'` **R**eplace `" 1"` with `" 2"` (to add back the missing 10 hours)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + common linux utils, 66
```
date "-d$1+6" '+%F %H %M:%S'|awk '{printf"%s %02d:%s",$1,$2+6,$3}'
```
[Try it online!](https://tio.run/##dc69CsIwFAXgvU9xCQkd2kB@moJxVhwURCfHaCItSitNoYP67LVU0RYVzvTBOffujc/aJsvPDipn7BRsGXhXA6WA8Ga2Xu5Qa03tAFGLeZQiCCMyB7IAstJkG95Mc4Lweqnyoj4i4oEwYTXxKMY8xiJKYyzvYesOWRnYsnCtYEJSLijjwJjuEwyNayF1okamtJp0GVn6o/s0PjQutEy0SofWHXjvJR30XfHZ60z@/U9@G1cvewA "Bash – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes
```
x=>x.toJSON().replace(/T(..)|\..*/g,(_,x)=>' '+(-x-1006+'').slice(3))
```
[Try it online!](https://tio.run/##bZFNT4QwEIbv/ore2i60TFsgoQa8mJiYqAf3uNEl2CVrkG6AKAf/O9Ylhg@3mdOTJ9N5Z97zz7wtmuOpY7V9M8MhHfo063ln75@fHgnljTlVeWFIsCWc0@8d55ug9Mmr39M0wwh7hPVMAMQexpS31dG5itLhen8lQSomJAOBAPS5EMvQiAVTgGQ44oUqtFQ6jNZqNOKFGukocbVWkxEv1Hg9wBLbZt5BwYW5RlVc7iDmqpBahTqKV@ofnqsu0yrCAv@qoQPnn@T/CMqp8TSrU9WFdTssmUymde@ns77wDblJnUiDj9J3ty9s3drK8MqW5EBq84Vu886Q3sPo7mGLPIgBMHVv@AE "JavaScript (Node.js) – Try It Online")
Only work in GMT+6
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
x=>new Date(x+'+6').toJSON().replace(/T(..)|\..*/g,(_,x)=>' '+(-x-1006+'').slice(3))
```
[Try it online!](https://tio.run/##bZJLT4QwEIDv/oreaBda@gASugEvnjzoQY9Gl2CX7AbpBohy8L/juMQAlWROX76ZzqPn4rPoyvZ06Wlj3814zMYhyxvzhe6K3uDB9/zEI6y390@PD5iw1lzqojQ4fMaMke8XxnZhFeC3YCBZ7iHPx3SggvPE9yCtq0/gKkLG/eFGcqmokJQLxLm@BqI5mrCgiiMZTXilCi2VjmJXjSe8UmMdpxCumk54pSZuA2ts22UFxTf6mlSxXUEsVSG1inScOOofXqowkzPCCv@qEYDrS/L/CArUZO4VVLWxbsCSynRe92E@6yvb4dsMRBJ@VAF8hdI2na0Nq22Fj3ggcMsf "JavaScript (Node.js) – Try It Online")
Set GMT+6 in code so work everywhere
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~149~~ 142 bytes
```
T`d`4-9` 0[0-5]
T`d`9d`.0?(-01)* 4
3
2
-90-
-12-
((?!00)([02468][048]|[13579][26])(00)?-02)-90
$1-29
02-90
02-28
(0[^469]|10|12)?-90
$1-3$#1
```
[Try it online!](https://tio.run/##bY5NasNADIX3OsWUeDEOKDxpfuKZjS/R3TDFhXTRTRYhS9/dGSfQ2hAQQvqk96Tbz/33@r0sn9Nl8pwmgwIOldY@XaYTRsuQ/mg8GUdGiROYWJTJ2vED6G2B@jjUAj/UuYgL51SLxtrbNh0Z2jcNdcKaCLrWLetAFuXLx1RnwSzaNl9brjvIsijUrVcgBsjPoC2TrC77sGMhh9Rix@Ib7YvJlolm53OIW9YO/Pn5Bp5a/fdrzG3/ewA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`d`4-9` 0[0-5]
```
Add 44 hours to times between midnight and 6am.
```
T`d`9d`.0?(-01)* 4
```
Subtract 1 day and 10 hours from those times, plus also subtract 1 month and 1 year if the day (and month) were originally 1; in this case the day (and month) "rolls under" to 90 and will be fixed up later to the correct last day or month.
```
3
2
```
Subtract another 10 hours from those times.
```
-90-
-12-
```
Change month 90 to December.
```
((?!00)([02468][048]|[13579][26])(00)?-02)-90
$1-29
```
February in a leap year has 29 days.
```
02-99
02-28
```
Other Feburaries have 28 days. (This must be February rather than, say, 2002, because month 90 was fixed up earlier.)
```
(0[^469]|10|12)?-90
$1-3$#1
```
Fix up the last day of the month in other months.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 75 bytes
```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḢ;@,’ḅ’dɗ12‘ʋ
Ṗç/$’3¦ỊṪ$?,+1¦24$}ɗ,<6Ḣ$}?Ṿ¹ŻṖ?$€€j"⁾-:K
```
* [Try it online!](https://tio.run/##y0rNyan8///h7l4THSNTO/1HDXMe7lh0YvuRBY8aZiaZHFqSr21k8XDnTKCgtYMOUOzhjlYgmXJyuqHRo4YZp7q5Hu6cdni5vgpQ0PjQsoe7ux7uXKVir6NteGiZkYlK7cnpOjZmQM0qtfYPd@47tPPobqB6e5VHTWuAKEvpUeM@XSvv////GxkYGesYGukY/jfUMdIxBgA)
* [Test suite](https://tio.run/##bZBBS8MwFMfv/RRFelvDkpe02FQ2794Fr6KXMRh422FQBRkongbOgQNRmSCeRLChsENnwfkt0i9S3xbUtg4eJf3ll3/eS@e42@0XhU6uhAteq5lHtzq@/3z/uMujyaFIH3sN2NZqgjDcdZHp@By/R8sxgzy6@bq0tLpePDUdhDyd6eRCq2en7TZYOgPhDJZjd8fHw86grdU8VVmCftvJz16wOlv56ZzIvQK3QrzZJi07j6Yh5lnZSKsHwxBhAqqS9HX8uuJ4PJqSbNTFFd1fDC2dvC2G@HNQFECBEwaEMptSua5VsMGMcGqDMNgqq0wCl8Krq57BFdWTXoBVVwODK6pfb6CKeyflBE439GVUtjmBlVUGkgvp@TX1B5dVnKk2QgWvVIFgfRP8H4Gj6v/1iirf8NyIgUBQeW6jwq/6DQ "Jelly – Try It Online")
A full program taking the Y,M,D year as a list of three integers as the first argument and the H,M,S time as a list of three integers as the second argument. Prints a formatted string as a 30-hour time. Most of the code reflects Jelly’s lack of date time handling.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~97~~ 87 bytes
```
¿‹η06«≔I⪪θ-υ⪫﹪%02dEυ∨⁻ι¬⊙υ∧›μκ⊖λ⎇⊖κ⁺²⁸∨I§”)“∧Bn»”§υ¹¬﹪⊟Φ↨§υ⁰¦¹⁰⁰μ⁴¦¹²-⁺ ⁺²⁴I…η²✂η²»«θ η
```
[Try it online!](https://tio.run/##TZBha8MgEIY/t79ChMEFDBgTxlg/ZR0bG@tWaP@AJLdFZk2rZqyM/fZMbbtWRfHuvdfHazppm17qcVTvBF7QOegYofyaZhn5mU5q59SHgbl0HlZbrTzsQjoPWUaGbDadLK0yHp57ZWDRt4PugV5x0VJGFnILAyNvFhbKDA4UI6@9h9rsY7g2LTxalB4tbBj5DH732FjcoPHYgs7iYGSN1ki7h8tc1C51cBQ3yT7B1f7JtPgNVJQlL0WYYQWKUzw8WSTHyHAkXfZbeFA6ItxJh3Ch5UFZ8LhvYlF1oCnE4UwN@P98YqGEnqgqRhLSfN9onHfhkdDSVHmuWWnV4DE@m/4S1A5jvw/Z3VkYfM@XLmrHUXBR5bzMeUE4v01rzL/0Hw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as separate "words", i.e. the date and time can be on two lines instead of space-separated. Explanation:
```
¿‹η06«
```
If the time is before 6am, then:
```
≔I⪪θ-υ
```
Split the date on `-` and cast to integer.
```
⪫﹪%02dEυ∨⁻ι¬⊙υ∧›μκ⊖λ⎇⊖κ⁺²⁸∨I§”)“∧Bn»”§υ¹¬﹪⊟Φ↨§υ⁰¦¹⁰⁰μ⁴¦¹²-
```
Decrement any component where all the following components are all `1`, but if the component becomes zero, then replace it with `12` if it's the month otherwise calculate the number of days in the previous month. Format and output the resulting date.
```
⁺ ⁺²⁴I…η²
```
Add 24 to the hours.
```
✂η²
```
Output the minutes and seconds.
```
»«θ η
```
Otherwise just output the date and time.
] |
[Question]
[
Multi-level marketing related challenge.
A peer wants to get rewarded. So it attracted `N` investors (`N>=1`), each i-th investor invested `x[i]`. When a total sum exceeds threshold `x[0]+x[1]+...+x[N-1] >= T` a peer could be rewarded. But only if a following conditions are satisfied:
* Minimum amount of investors should be greater than `M`, (`M<=N`)
* For at least one integer `k`, where `k>=M` and `k<=N`, any `k` investors have to invest at least `T/k` each;
Given `N, x[], T, M` you should determine whether the peer's reward is generated or not (boolean result, "yes" or "no"). Shortest code wins.
**Examples:**
---
`N=5; M=3; T=10000`, in order to generate the peer's reward one of the following must be satisfied:
* any 3 invested at least 3334 each
* any 4 invested at least 2500 each
* all 5 invested at least 2000 each
---
`N=6; M=2; T=5000`:
* any 2 invested at least 2500 each
* any 3 invested at least 1667 each
* any 4 invested at least 1250 each
* any 5 invested at least 1000 each
* all 6 invested at least 834 each
---
generalized: for any `k`, where `k>=M` and `k<=N`:
* any `k` of `N` investors invested at least `T/k` each
---
**Test cases:**
*format:*
`N, x[], T, M -> correct answer`
```
6, [999, 999, 59, 0, 0, 0], 180, 3 -> 0
6, [0, 60, 0, 60, 60, 0], 180, 3 -> 1
6, [179, 89, 59, 44, 35, 29], 180, 3 -> 0
6, [179, 89, 59, 44, 35, 30], 180, 3 -> 1
6, [179, 89, 59, 44, 36, 29], 180, 3 -> 1
6, [179, 90, 59, 44, 35, 29], 180, 3 -> 0
6, [30, 30, 30, 30, 29, 30], 180, 3 -> 0
6, [30, 30, 30, 30, 30, 30], 180, 3 -> 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṢṚ×J$ṫ⁵<Ṃ
```
A full program which accepts `x T M` and prints `0` if the peer is rewarded and `1` if not.
**[Try it online!](https://tio.run/##y0rNyan8///hzkUPd846PN1L5eHO1Y8at9o83Nn0////aENzSx0FCyA2BWITEx0FY1MdBSPL2P@GFgb/jQE "Jelly – Try It Online")**
### How?
```
ṢṚ×J$ṫ⁵<Ṃ - Main Link: list of numbers, x; number, T e.g. [100, 50, 77, 22, 14, 45], 180
Ṣ - sort x [ 14, 22, 45, 50, 77,100]
Ṛ - reverse [100, 77, 50, 45, 22, 14]
$ - last two links as a monad:
J - range of length [ 1, 2, 3, 4, 5, 6]
× - multiply [100,154,150,180,110, 84]
ṫ - tail from index:
⁵ - 5th argument (3rd input), M (e.g. M=3) [ 150,180,110, 84]
< - less than T? [ 1, 0, 1, 1]
Ṃ - minimum 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{Rƶ.ssè›ß
```
[Try it online](https://tio.run/##yy9OTMpM/f@/OujYNr3i4sMrHjXsOjz///9oQwMDHVMDHXNzHSMjHUMTHRPTWC5jLkMLAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4Pa/OujYNr3i4sMrHjXsOjz/v87/aAMdBTMghlJgZiyXMZehhQFXtKG5pY6CBRCbArGJiY6CsSkQ45M301EwsoTLGxuAlKNjhHYDIN8UiM3NgdqMdBQMgUaYmMLlLS2BxoIJkPkQRxJwHJLlYHlLA5zy6A4zsiTCcSZQeQA).
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/178444/52210), so also takes the inputs `x T M` and outputs `0` for `"yes"` and `1` for `"no"`. If this is not allowed, and it should be inverted, a trailing `_` can be added.
**Explanation:**
```
{ # Sort the (implicit) input `x`
# i.e. `x`=[100,50,77,22,14,45] → [14,22,45,50,77,100]
R # Reverse it
# i.e. [14,22,45,50,77,100] → [100,77,50,45,22,14]
ƶ # Multiply it by it's 1-indexed range
# i.e. [100,77,50,45,22,14] → [100,154,150,180,110,84]
.s # Get all the suffices of this list
# i.e. [100,154,150,180,110,84]
# → [[84],[110,84],[180,110,84],[150,180,110,84],[100,154,150,180,110,84]]
s # Swap to take the (implicit) input `T`
è # Get the prefix at index `T`
# i.e. [[84],[110,84],[180,110,84],[150,180,110,84],[100,154,150,180,110,84]]
# and `T=3` → [150,180,110,84]
› # Check for each list-value if the (implicit) input `M` is larger than it
# i.e. [150,180,110,84] and `M`=180 → [1,0,1,1]
ß # And pop and push the minimum value in the list (which is output implicitly)
# i.e. [1,0,1,1] → 0
```
---
Alternative for `.ssè`:
```
sG¦}
```
[Try it online](https://tio.run/##yy9OTMpM/f@/OujYtmL3Q8tqHzXsOjz///9oQwMDHVMDHXNzHSMjHUMTHRPTWC5jLkMLAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4Pa/OujYtmL3Q8tqHzXsOjz/v87/aAMdBTMghlJgZiyXMZehhQFXtKG5pY6CBRCbArGJiY6CsSkQ45M301EwsoTLGxuAlKNjhHYDIN8UiM3NgdqMdBQMgUaYmMLlLS2BxoIJkPkQRxJwHJLlYHlLA5zy6A4zsiTCcSZQeQA).
**Explanation:**
```
s # Swap to take the (implicit) input `T`
G } # Loop `T-1` times:
¦ # Remove the first item from the list that many times
# i.e. [100,154,150,180,110,84] and `T=3` → [150,180,110,84]
```
[Answer]
# JavaScript, ~~54~~ 52 bytes
```
(x,t,m,n)=>x.sort((a,b)=>a-b).some(i=>i*n-->=t&n>=m)
```
[Try it online](https://tio.run/##DchNDsIgEEDhPadgZQYzNFD74wYuYlzQSg2mDKYQ09sji7f43sf9XF6P8C2S0svXzVQ4sWBEEsaeXU5HAXC4NDm5iDaih2BsuJKU1pQLWRNFXRPltPtuT2/YgD20UsjH1jwj73vkekA@jE9k@q6Q3ZBNTIj6Bw)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 79 bytes
```
\d+
*
O^`_+(?=.*])
_+(?=.*])(?<=(\W+_+)+)
$#1*$&
+`\W+_+(.*_)_$
$1
(_+).*], \1,
```
[Try it online!](https://tio.run/##hU1NC4JAEL3PrxDaYr8Q11VzIPHYsWMHzd2gDl06RP9/m7REJAzmzTzeezPzuD5v97MJa773ob0okHDovFO8rmJ5EjAyXu8q3h6VU0IJYCsj2QaU7xUeSyccA2aAk09xHbVGh9Agoo76lhOSocg1JRELDfViUIsvnbhmS0vlZznLSMt1lOK/hF2@Ufy6gcnCF/seE6Q4ezIPDBgDLw "Retina – Try It Online") Takes input in the format `[x], T, M`. Link includes test cases. Explanation:
```
\d+
*
```
Convert to unary.
```
O^`_+(?=.*])
```
Sort `[x]` in descending order.
```
_+(?=.*])(?<=(\W+_+)+)
$#1*$&
```
Multiply each element of `[x]` by its index.
```
+`\W+_+(.*_)_$
$1
```
Delete the first `M-1` elements of `[x]`.
```
(_+).*], \1,
```
Test whether any remaining element of `[x]` is greater or equal to `T`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~46 33~~ 29 bytes
```
{$^b>all $^a.sort Z*[...] @_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olLskuMSdHQSUuUa84v6hEIUorWk9PL1bBIb72f3FipYJ9mka0paWljgKYMAViAwiK1VEwtAAyzHSMNXWUFHTtFAyUrLlgWkASEIVmMCamBkMkDYbmQKMtoFaYmOgoGJvqKBhZ4rcFqyZjkm0yw24ThiZLA9KcZ2wAcg0CG1lidx0@PRCM1XH/AQ "Perl 6 – Try It Online")
Anonymous code blocks that takes input in the form `list, amount, length of list, minimum amount of investors` and returns a truthy/falsey `all` Junction, where truthy is failed and falsey is success.
### Explanation:
```
{ } # Anonymous code block
all # Are all of
$^a.sort # The sorted list
Z* # Zip multiplied by
[...] @_ # The range from length of list to the minimum amount
$^b> # Not smaller than the given amount?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Input taken in the order `T`, `N`, `x[]`, `M`
Output is `0` for peer reward and `1` if not
```
Ÿs{*›W
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6I7iaq1HDbvC//835jLjijY0t9RRsABiUyA2MdFRMDbVUTCyjOUytDAAAA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/W9o4Pb/6I7iaq1HDbvC/@vE/DfmMuOKNtBRMANiKAVmxnIZWhhwgWUNzS11FCyA2BSITUx0FIxNgRi/CjMdBSNLJBXGBiAt6BjZCAOgiCkQm5sDtRrpKBgCjTExRVJhaQk0HEyAbIE4l6AzURwBVmFpgEcFuhONLIlypglYBQA)
**Explanation**
```
Ÿ # push the range [N ... T]
s{ # push the list x[] sorted ascending
* # elementwise multiplication (crops to shortest list)
› # for each element, check if M is greater than it
W # push min of the result
# output implicitly
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~129~~, 89 bytes
EDIT: Thanks to Kevin Cruijssen for golfing off 40 bytes while explaining the mechanics as to why!
```
(n,q,t,m)=>{int c=0,j;for(;m<=n&c<1;c=c<m++?0:1)for(j=n;j-->0;)c+=q[j]<t/m?0:1;return c;}
```
[Try it online!](https://tio.run/##tZDPS8MwFMfv/SseO0hDs9nuR7eaZh4Eb4IwwcPcoYvdaGkTl6SKjP3t9XWdIB7EQ0vyfXm8Rz58@QozFEqndWUyuYfVp7FpyRxRJMbAo1Z7nZRHB@Ct2haZAGMTi8@7yl7hIcmkS5olwH0lRZxJS2FXqMSuN5eGwnmIZQlb4LUr6YFaWhK@POIQBPdpznZKu6yMubwSccAEF3Hpebf@TUCaTc4ly4fDpc@I8PhhnW9ie102a6ZTW2kJgp1q5rTeR3dKGlWko2ed2dTduiEFmX5cfIUbOEZRROFcZii/vScKwQKbCRk9qZXVGIZLvMGLHJD/k/F/2PLC77YTbjBHo4uL4ekUaTMK46g/9qQv32G3viO/l0wmDeCHxlFnkfxGt@omEb9JAzWfo@UxIqdNMj2yZ3@ynROe@gs "C# (.NET Core) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with flag `/u:System.Linq.Enumerable`, 69 bytes
```
(n,x,t,m)=>Range(0,n-m+1).Where(b=>x.Count(a=>a>=t/(b+m))>=b+m).Any()
```
[Try it online!](https://tio.run/##pY4xT8MwEIV3foVHW726SdOmNWBLCMHEBEMHxJBEFliqzyFxRCvEX8e4TStVDKi00r3zG97nd1U7rFoT7jusrg16iHp@gZ2D0rmlqmWgCCvwYJlUjwW@apoADu0gZXzxphtNS6lW/NZ16GkhVaGkH9FyYBlTcvPwG1xTFq4uFo3x@sGgpjXNgaD@INvCTyEEkO2aRiX9fAFJ59FkjP2BxkDeA/neHgems1g131VOJjE@BTIWZ8DZyc35P5tFctrZ2SZxoLE4/urfbK9DNny72huHbRh1l0/r1mvL40/v/A47q5uiXOof "C# (Visual C# Interactive Compiler) – Try It Online")
```
// Takes in 4 parameters as input
(n,x,t,m)=>
// Create a new array with the length of all the numbers from m to n, inclusive
Range(0,n-m+1)
// And filter the results by
.Where((_,b)=>
// If the number of people that invested more than the total amount divided by the index plus m
x.Count(a=>a>=t/(b+m))
// Is greater than the index plus m
>= b+m)
// And check if there is at least one value in the filtered IEnumerable<int>, and if there is, return true
.Any()
```
# Without any flags, 73 bytes
```
(n,x,t,m)=>new int[n-m+1].Where((_,b)=>x.Count(a=>a>=t/(b+m))>=b+m).Any()
```
[Try it online!](https://tio.run/##pY5RC4IwFIXf@xV73PBmmmaO2iCCnnr3ISRSBg1yRk4qot9uMw2khyiDne3AznfPTYthWshqVap0LpUGo00MrYMkzw/8yCqs4AIaMsK4EmdUh9Qws9zYjvbiJDDeQmL@LvYyL5XGO8Z3nOkRTqyMEM7qx16oKybVbBCdpBZrqQQ@4gDQa158o5QCel4TI6c5d0BuaIxHyAfUBIIGCF72O9CdmqqwrfR9E58AGtM/YK93c/BjM3X6re3ViY7G9Put39lGXbZ6AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# JavaScript, 72 bytes
### Code
```
(x,T,M)=>x.sort(t=(d,e)=>e-d).map((s,i)=>s*i+s).slice(M-1).sort(t)[0]>=T
```
[Try it online!](https://tio.run/##lU5LCoMwEN33FFkmbfx/ahZ6AzfFnbgQjSVFjZhUvL2N1YK4aCvMG2aG95lHPuSi6FkntZaXdKrCCY44wTEKo1EXvJdQhrDEVO1UK5He5B2EAjO1izO7CKSLmhUUxpqFVj5KzSwKk8kwbrSgbKACsLZ7StVBxfsml2BMsznkVPBW8JrqNb/DCqaEEAzezVMwl8owsAI1OAjt@erqLyz/M35hW1dlGqzmrqs4HgY2OapwjmX4/2QQ88BXznzewCY/ntoLFmwE0ws "JavaScript (Node.js) – Try It Online")
Accepts input in format (x[],T,M)
### Explanation
```
x.sort(t=(d,e)=>e-d) \\sort numbers in reverse numerical order
.map((s,i)=>s*i+s) \\Multiply each number in array by position(1 indexed) in array
.slice(M-1) \\Remove the first M-1 elements (at least M people)
.sort(t)[0] \\Get the maximum value in the array
>=T \\True if the maximum value is >= the threshold
```
[Answer]
# [Python 3](https://docs.python.org/3/), 136 bytes
Just tests the conditions to make sure they are met. 1 if the reward is given, 0 if not.
```
lambda N,x,T,M:(sum(x)>=T)*(M<=N)*any(any(all(j>=T/k for j in i)for i in combinations(x,k))for k in range(M,N+1))
from itertools import*
```
[Try it online!](https://tio.run/##jZJNbsIwEIXX5BQjdWOnlpofCBg1vUFYVOwoC0NMa4ht5LhqOH1qB1pKCRKSnzWa@fT05PH@YD@0StuSW26kUPyVfzFT5m9txeSqZDAjDZmTYorqT4ka/JLPcYiK53yGQ6YOqFNVoa0bPO1gow1sQSgQ2JfCl2stV0IxK7SqUUN2uBvt/Mgw9c5RQWaPMcbBxmgJwuWwWlc1CLnXxoat5bVds5rXkMMiGKCMwIJSSqC7Rk7R8SwJxBNXpJjAA0Qn1DWyI5D9lJdgfALjsbOanCyHQzceEUhov2svnN7tnF07X8A0ui9G6jt/lNDrFLfYo26EiHwAp/HYmSaOGfowN96iFx6d4c54GQR@736bfvW/W50Gg70RyqJ/XxCFHsG4/QY "Python 3 – Try It Online")
[Answer]
# [Python](https://docs.python.org), ~~71~~ 65 bytes
```
lambda x,T,M:all(i*v<T for i,v in enumerate(sorted(x)[-M::-1],M))
```
**[Try it online!](https://tio.run/##jZDLCsIwEEX3fsXsksgU@rYp6h905067iDTVQG0lraJfX9NUQUSlIXcyj8MdyPneHZva78vVrq/EaV8IuOEGs1RUFVXz63IDZaNB4RVUDbK@nKQWnaRtoztZ0BvbOlmaOl6OGWP9gAp9aAeWzsAeuuWcI9gQGbnjzRG8xCQBsxwazlTxOI1f6RfKWxiT5GkWhmYWIfh8KhlM84z/eXJ3wvZgKN/k8x/LP8FRHyBL7XPWqu7sFyMQZ01MdAmoEko6H7oMZNVKIB7pHw "Python 2 – Try It Online")**
An unnamed function; port of my Jelly answer. As such "yes" is `False` and "no" is `True`. Here, however, we discard test-cases as a part of the reversal and take advantage of the ability to initiate the `enumerate` count to `M`. (`min` would also work in place of `all`)
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 42 bytes
*-1 bytes by implementing the approach even more closely*
```
function(N,x,S,M)min(sort(x,T)[M:N]*M:N<S)
```
[Try it online!](https://tio.run/##bZBBC4JAEIXP7a9Y6LIbc9h1tdxogw51Sg9Zp@gQgiCYihpsv95GLfPQMO9d3seDmapNTJs887hJi5yFYCGCgD/SnNVF1TALZ34N1uFtgbaJeGuliZnWGmhvHkoMy2dzKqnZ0sPuGO2JdRCUK8z9D@e6QJWH6lHRoefTBUmFpBJd8JOjv@C00/1DDuIUZ9pKQrMkgVEkMtIXhNT3ssxeLEtrvEqCdcAqsC6H8XjLk/EBvH0D "R – Try It Online")
Simple R implementation of Jonathan's Jelly approach. I tried a bunch of variations but this pips the best I could think of by a few bytes.
1 implies failure, 0 implies success.
[Answer]
# Japt, ~~16~~ ~~14~~ ~~13~~ 11 bytes
```
ñ í*WõX)d¨V
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8SDtKlf1WClkqFY=&input=WzEwMCwgNTAsIDc3LCAyMiwgMTQsIDQ1XQoxODAKMwo2)
```
ñ í*WõX)d¨V
:Implicit input of array U=x and integers V=T, W=M & X=N
ñ :Sort U
í :Interleave with
WõX : Range [W,X]
* : And reduce each pair of elements by multiplication
) :End interleaving
d :Any
¨V : Greater than or equal to V
```
[Answer]
# Java 8, 91 (or 89?) bytes
```
(N,x,T,M)->{int c=0,j;for(;M<=N&c<1;c=c<M++?0:1)for(j=N;j-->0;)c+=x[j]<T/M?0:1;return c;}
```
Port of [*@Destroigo*'s C# .NET answer](https://codegolf.stackexchange.com/a/178477/52210) (after I golfed it some more), so make sure to upvote him!
Takes inputs `N,x,T,M` and outputs `true`/`false` for `"yes"`/`"no"` respectively.
Since the challenge specifically asks for `boolean` results, I can't return the `1`/`0` as is, since those aren't [valid truthy/falsey values](https://codegolf.meta.stackexchange.com/a/2194/52210) in Java. If any two distinct output values for `"yes"`/`"no"` is valid for this challenge instead, the `>0` in the return can be dropped to save two bytes, in which case it'll return `1`/`0` for `"yes"`/`"no"` respectively.
[Try it online.](https://tio.run/##rVHBcoIwEL37FXvqwBg0KKAI2FtvcJGb4yFGbKEYHAhWx@Hb6Qa91Eut9fA2ZN7y9m1exg7MyDafLc9ZVUHIUnHuAaRCJuWW8QQidQVYF0WeMAFcQwoignW5gqM6Ie5qqHvY2fSwVJLJlEMEAgJotYgcSUxC3ZifVSMPKMm8bVFqXugH0Qv3TY8H3A/7/Vc6M3XFZEHkZYYxp57O@8Fxma38eBgq2isTWZdoBLmmVSP39TrHadehhyLdwA7X0BayTMU7umT6ZYfhEOKylh@nWXddnCqZ7AZFLQd77JS50MSAaw4RyRd0@50pAQdxPbrPhphTSsZ6t@1dIubEJTBF2AjLIjC2EU8RcgiM3L8LjakycIsHDFH80UZMJmhkRMBEU5b9u9CVwUDeWF4l9wfiurh6V9QbXKJ5ViSPvGQn5NL/C93GMXKfGYn1Q6jpNe03)
**Explanation:**
```
(N,x,T,M)->{ // Method with the four parameters and boolean return-type
int c=0, // Count integer, starting at 0
j; // Temp index integer
for(;M<=N // Loop as long as `M` is smaller than or equal to `N`
&c<1 // and `c` is not 1 yet:
; // After every iteration:
c=c<M++? // If `M` is smaller than `c`:
// (and increase `M` by 1 afterwards with `M++`)
0 // Set `c` to 0
: // Else:
1) // Set `c` to 1
for(j=N;j-->0;) // Inner loop `j` in the range (`N`,0]:
c+= // Increase the counter `c` by:
x[j] // If the `j`'th value in `x`
<T/M? // is smaller than `T` divided by `M`:
0 // Leave the counter `c` unchanged by adding 0
: // Else:
1; // Increase the counter `c` by 1
return c>0;} // Return whether the counter `c` is 1
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 66 bytes
```
(n,x,t,m)=>Enumerable.Range(m,n-m+1).Any(k=>x.Count(y=>y>=t/k)>=k)
```
[Try it online!](https://tio.run/##lVLBSsNAEL3nK4biYRensW3a2FB3oYiePFnBQ@ghjRsNTTaw3WBDyLfHTdJKrEUp7Oy8nX1vZg4v3A3DXVw/5jK8i6XGNxHGaZD46yPCprrJsoRDBKwmEveoMaWMP8g8FSrYJMJ@DuS7ICnKYXo9pvZSFmTL@N6@z3KpScF4wZm@2VLOtrReWFGmRBB@EGJ6g0QwyV/DvgWgu5QiNFNBUfMEKT79dWkRFw/Q8zyE9pqZGHWnQhjPDXAQoiDZCYo9ham7Hc89wh5fq/wnfXxr@s4P/adTQ5ohTLw/R5zVOBeOcU/GnJd4o4s2c5qPXky8k8X@l3Txa7GKQmkBvKpYi6dYCnI1KFUFjEMZNWaxVyIRYWsCcrAULaj9ki2VCgpC8bvauKoa0IVV1V8 "C# (Visual C# Interactive Compiler) – Try It Online")
Inspired by @EmbodimentOfIgnorance's answer.
I've mentioned this before, but C# 8 has a range literal which could make this answer something like this:
```
(n,x,t,m)=>[m..n-m+1].Any(k=>x.Count(y=>y>=t/k)>=k)
```
I saw a link to [SharpLab](https://sharplab.io) with an example, but I wasn't able to get it to work myself.
One thing I changed was the `x` and `t` values are decimals. This handles the case where `t` is not divisible by `k` a little better.
] |
[Question]
[
## Introduction:
In general we usually speak of four dimensions: three space dimensions for `x`, `y`, and `z`; and one time dimension. For the sake of this challenge however, we'll split the time dimension into three as well: `past`, `present`, and `future`.
## Input:
Two input-lists. One containing integer `x,y,z` coordinates, and one containing integer years.
## Output:
One of any four distinct and constant outputs of your own choice. One to indicate the output `space`; one to indicate the output `time`; one to indicate the output `both space and time`; and one to indicate the output `neither space nor time`.
We'll indicate we went to all three space dimensions if the differences of the integer-tuples is not 0 for all three dimensions.
We'll indicate we went to all three time dimensions if there is at least one year in the past, at least one year in the future, and at least one year equal to the current year (so in the present).
## Example:
**Input:**
Coordinates-list: `[{5,7,2}, {5,3,8}, {-6,3,8}, {5,7,2}]`
Year-list: `[2039, 2019, 2018, 2039, 2222]`
**Output:**
Constant for `space`
**Why?**
The `x` coordinates are `[5,5,-6,5]`. Since they are not all the same, we've went through the `x` space dimension.
The `y` coordinates are `[7,3,3,7]`. Since they are not all the same, we've also went through the `y` space dimension.
The `z` coordinates are `[2,8,8,2]`. Since they are not all the same, we've also went through the `z` space dimension.
The current year is `2018`. There are no years before this, so we did not visit the `past` time dimension.
There is a `2018` present in the year-list, so we did visit the `present` time dimension.
There are multiple years above `2018` (`[2039, 2019, 2039, 2222]`), so we also visited the `future` time dimension.
Since we've visited all three `space` dimensions, but only two of the three `time` dimensions, the output will only be (the constant for) `space`.
## Challenge rules:
* You can use any four distinct and constant outputs for the four possible states.
* Input can be in any reasonable format. Coordinates list can be tuples, inner lists/arrays of size 3, strings, objects, etc. List of years may be a list of date-objects instead of integers as well if it would benefit your byte-count.
* You can assume the `x,y,z` coordinates will be integers, so no need to handle floating point decimals. Any of the `x`, `y`, and/or `z` coordinates can be negative values, though.
* You cannot take the input-lists pre-ordered. The input-lists should be in the order displayed in the test cases.
* You can assume all year values will be in the range `[0,9999]`; and you can assume all coordinates are in the range `[-9999,9999]`.
* If your language doesn't have ANY way to retrieve the current year, but you'd still like to do this challenge, you may take it as additional input and mark your answer as ***(non-competing)***.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Coordinates-input: [{5,7,2}, {5,3,8}, {-6,3,8}, {5,7,2}]
Years-input: [2039, 2019, 2018, 2039, 2222]
Output: space
Coordinates-input: [{0,0,0}, {-4,-4,0}, {-4,2,0}]
Years-input: [2016, 2019, 2018, 2000]
Output: time
Coordinates-input: [{-2,-2,-2}, {-3,-3,-3}]
Years-input: [2020, 1991, 2014, 2018]
Output: both
Coordinates-input: [{5,4,2}, {3,4,0}, {1,4,2}, {9,4,4}]
Years-input: [2020, 1991, 2014, 2017, 2019, 1850]
Output: neither
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ 109 bytes
```
lambda S,T:(min(map(len,map(set,zip(*S))))>1,date.today().year in sorted(set(T))[1:-1])
from datetime import*
```
[Try it online!](https://tio.run/##dY/BisMgEIbveQphL1omRU3SJoXdl2hv2RzsxhChGjFesi@fVdOwZWHHYfwZfz5@7eLHyfB1eP9cH0Lfe4GucLtgrQzWwuKHNBDvWXr4VhYfriTUB4NeeHn0Uy8WTI6LFA4pg@bJedlHM74R0rJLzjqSDW7SKPq90hIpbYPrsFqnjEcDbtsKzsA7QEEUUEeRn3a1vUXFadEA4pRts44zbUJ1BL3NVnzJLPvFUggn0UoIvUse1MZjp788SiMpxnwF5RxSJ0ABqZ8ITgGxpmEJUW6giLhPfnxFVFBuXyzgmYTtmyaI8n/cec/I6iqlM1L5Ubr1Bw "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~47~~ 46 bytes
*-1 byte thanks to nwellnhof*
```
{Set(@^b X<=>Date.today.year)>2,max [Z==] @^a}
```
[Try it online!](https://tio.run/##dY9NCsIwEIX3nmJW0sK0JOlv0JQuvIEbsVSImK4sSu3CIp49polBEUwew8eE92ZyVcM51/0Eyw4E6MdWjUF9OMJuLaqNHFU8Xk5yiiclh7Bi2Ms7NHshWqgP8qlvcoIOmibDAlmLYCDBcoYo9@TeZmIk4QiMUFfLudqOOe1q4cMImmszUjTyyAy5FJr/phDy8QcRQ6sQIYgStAqdkxEEyjm1ztT5vyZnmLpvJPieS32HG0jbvymF34iWmdlFvwA "Perl 6 – Try It Online")
Anonymous code block that takes two lists and returns a tuple of booleans, with the first element being whether you traveled in time, and the second being whether you didn't traveled in space.
### Explanation
```
{ } # Anonymous code block
@^b X # Map each element of the year list to:
<=> # Whether it is smaller, equal or larger than
Date.today.year # The current year
Set( ) # Get the unique values
>2 # Is the length larger than 2?
,
[Z ] @^a # Reduce by zipping the lists together
max # And return if any of them are
== # All equal
```
[Answer]
# Japt, 22 bytes
Takes input as a 2D-array of integers for the space dimensions and a 1D-array of integers for the years. Outputs `2` for space only, `1` for time only, `3` for both and `0` for neither.
```
yâ mÊeÉ Ñ+!Jõ kVmgKi¹Ê
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=eeIgbcplySDRKyFK9SBrVm1nS2m5yg==&input=W1s1LDcsMl0sWzUsMyw4XSxbLTYsMyw4XSxbNSw3LDJdXQpbMjAzOSwyMDE5LDIwMTgsMjAzOSwyMjIyXQ==)
```
:Implicit input of 2D-array U=space and array V=time
y :Transpose U
â :Deduplicate columns
m :Map
Ê : Lengths
e :All truthy (not 0) when
É : 1 is subtracted
Ñ :Multiply by 2
J :-1
õ :Range [-1,1]
k :Remove all the elements present in
Vm : Map V
g : Signs of difference with
Ki : The current year
¹ :End removal
Ê :Length
+! :Negate and add first result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
Output is a list `[space, time]` where **1** stands for `x` and **0** stands for `no x`
```
ø€Ë_Psžg.SÙg3Q)
```
[Try it online!](https://tio.run/##yy9OTMpM/W/i9v/wjkdNaw53xwcUH92Xrhd8eGa6caDmf53/0dGmOuY6RrE6CkCGsY4FiKFrBmNB5GK5oo0MjC11FIwMDCGkBYgEiwABUDraQAcIwXpNdIAIxjQCssC6Dc3QdRsYgPTpGumAEVi9sQ4YQXQYGegoGFpaGoJ1mED0gXSY6phAnGusA7XHECZiCWSY4NRtDnOBoYWpQSwA "05AB1E – Try It Online")
**Explanation**
```
ø # zip space coordinates
€Ë # for each axis, check that all values are equal
_ # logical negation
P # product (1 for space, 0 for no space)
s # put the time list on top of the stack
žg.S # compare each with the current year
Ù # remove duplicates
g3Q # check if the length is 3
) # wrap the space and time values in a list
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 25 bytes
*I'm 100% sure this is not the best approach, still looking for some shorter way to do this :c*
Returns a tuple of booleans. The first is if you traveled in space and the second if you traveled in time
```
[Uyâ e_ʦ1ÃV®-Ki)gÃâ Ê¥3]
```
---
```
[Uyâ e_ʦ1ÃV®-Ki)gÃâ Ê¥3] Full Program, U = Space, V = Time
-- U = [[-2,-2,-2], [-3,-3,-3]]
-- V = [2020, 1991, 2014, 2018]
[ ] Return array containing....
Uyâ Transpose Space coords
-- U = [[-2,-3], [-2,-3], [-2,-3]]
and map Z
_ʦ1 Z length greater than 1?
-- U = [true, true, true]
e return true if all Z are true
-- U = true
V® Map each time
-Ki) Subtract current year
-- V = [2,-27,-4,0]
gà get sign (-1,0,1)
-- V = [1,-1,-1,0]
â unique elements
-- V = [1,-1,0]
Ê¥3 return true if length == 3
-- V = true
```
[Try it online!](https://tio.run/##y0osKPn/Pzq08vAihdT4w12Hlhkebg47tE7XO1Mz/XAzUBQottQ4Fqgm2lTHRMcoVkch2hjIMAAxDGEilkCGSWwsV7SRgZGBjoKhpaWhjoKRgaEJmDQHk5ZAcQtTg1gFAA)
[Answer]
# JavaScript (ES6), ~~104~~ 100 bytes
Takes input as `(space)(time)`. Returns \$1\$ for *time*, \$2\$ for *space*, \$3\$ for *both* or \$0\$ for *neither*.
24% of the code is spent figuring out in which year we are ... \o/
```
s=>t=>2*s[0].every((x,i)=>s.some(b=>x-b[i]))|t.some(y=>(s|=(y/=(new Date).getFullYear())>1?4:y+1)>6)
```
[Try it online!](https://tio.run/##nZDRboMgFIbv@xRcwoYKaK0ugd0se4fFeKGOti5WGmFdTfrujop2WZvuYoeTkz@H5P/4@SgOha66em@8Vr3LYc0HzYXhgj3ojOS@PMiuh/CIa8SF9rXaSVhycfTKrM4ROhm36rmA@sRhH3DYyi/wUhiJ/I00r59N8yaLDiIk6HP01D9SJGI0VKrVqpF@ozZwDbNsiVeY5RhYEeLkLLx4Vu4uRzBjJEwxYIS6mZznuLFlXwNcBQHQ@6KSi2sIwfaM3hG2PUtmlXOn8bU7IT@@v8pCTL27ZXgMjz16h3jsyZ0RDGia0tE9cow77hdGqcx2cftZkfusEE8p6LxJrYju81ZzPposXTLLaGVttrL7P@bPEJcoE2b4Bg "JavaScript (Node.js) – Try It Online")
### Commented
```
s => t => // s[] = space array; t[] = time array
2 * // the space flag will be doubled
s[0].every((x, i) => // for each coordinate x at position i in the first entry of s[]:
s.some(b => // for each entry b in s[]:
x - b[i] // if we've found b such that b[i] != x, the coordinate is valid
) // end of some()
) // end of every()
| // bitwise OR with the time flag
t.some(y => // for each year y in t[]:
(s |= // update the bitmask s (initially an array, coerced to 0)
( y /= // divide y
(new Date) // by the current year (this is safe as long as no time-travel
.getFullYear() // machine is available to run this it at year 0)
) > 1 ? // if the result is greater than 1:
4 // do s |= 4 (future)
: // else:
y + 1 // do s |= y + 1; y + 1 = 2 if both years were equal (present)
// otherwise: y + 1 is in [1, 2), which is rounded to 1 (past)
) > 6 // set the time flag if s = 7
) // end of some()
```
[Answer]
# [R](https://www.r-project.org/), ~~106~~, 105 bytes
```
function(s,t)all((x<-apply(s,1,range))[1,]-x[2,])-2*all((-1:1)%in%sign(as.POSIXlt(Sys.Date())$ye+1900-t))
```
[Try it online!](https://tio.run/##dZBRS8MwFIXf9ysCOsjVm5Gk7dYOfRCcIAgTqyCMPdQuHYUSyxqh/fU1TVvcZLu5JCcnIR8nhza7b7MfnZr8W9MKDSRFQWl9x5KyLBrrCDwkeq8ANgK3rN5I3AKTN@4aE0sB01xPq3yvaVLNXtfx82dhaNxUs8fEKApw3ahbEXHODECb0fQr1zua0gAXKAE74WHYCTYfVX8GSFIquReh5MJNIfZbWwCkqyui6lKlRu3Ikry/fays9/TwEq8mfySOdjiAj7ZHKa0aEGJ@guB8eP24TkgOQRzwCMQkunYAD12PCMlRRJHoEL7jnEGQi5H@gQL0@7/zcMgjRieywr8EXfQxRRh0Cc8lcks7@QU "R – Try It Online")
Input :
```
s : matrix of space coordinates (3 x N)
t : vector time years
```
Output an integer value equal to :
```
1 : if traveled through space only
-2 : if traveled through time only
-1 : if traveled through space and time
0 : if traveled neither through space nor time
```
[Answer]
## Batch, 353 bytes
```
@echo off
set/as=t=0,y=%date:~-4%
for %%a in (%*) do call:c %~1 %%~a
if %s%==7 (if %t%==7 (echo both)else echo space)else if %t%==7 (echo time)else echo neither
exit/b
:c
if "%6"=="" goto g
if %1 neq %4 set/as^|=1
if %2 neq %5 set/as^|=2
if %3 neq %6 set/as^|=4
exit/b
:g
if %4 lss %y% (set/at^|=1)else if %4==%y% (set/at^|=2)else set/at^|=4
```
Note: Since commas are argument separators in Batch, in order to input the space coordinates you need to quote then e.g.
```
spacetime "5,7,2" "5,3,8" "-6,3,8" "5,7,2" 2000 2002
```
Explantion:
```
@echo off
```
Turn off unwanted output.
```
set/as=t=0,y=%date:~-4%
```
Set up two bitmasks and also extract the current year. (In YYYY-MM-DD locales use `%date:~,4%` for the same byte count.)
```
for %%a in (%*) do call:c %~1 %%~a
```
Loop over all the arguments. The `~` causes coordinate values to be split into separate parameters.
```
if %s%==7 (if %t%==7 (echo both)else echo space)else if %t%==7 (echo time)else echo neither
exit/b
```
Check whether the bitmasks are fully set and output the appropriate result.
```
:c
if "%6"=="" goto g
```
See whether this is a pair of coordinates or a coordinate and a year.
```
if %1 neq %4 set/as^|=1
if %2 neq %5 set/as^|=2
if %3 neq %6 set/as^|=4
exit/b
```
If it's a coordinate then update the space bitmask according to whether the relevant spacial dimension was visited.
```
:g
if %4 lss %y% (set/at^|=1)else if %4==%y% (set/at^|=2)else set/at^|=4
```
If it's a year then update the time bitmask according to whether the relevant time dimension was visited.
[Answer]
# Java 10, 154 bytes
```
s->t->{int y=java.time.Year.now().getValue(),c=0,d=1,i=3;for(;i-->0;d*=c,c=0)for(var l:s)c=l[i]!=s[0][i]?1:c;for(int a:t)c|=a>y?4:a<y?1:2;return c/7*2+d;}
```
Returns `1` for *space*, `2` for *time*, `3` for *both*, `0` for *neither*. Try it online [here](https://tio.run/##nVRtb9owEP4cfsWNT0lxsrxAgaQJ6jaqoq3rNNCkCfHBSwwyC0mUOHSI8duZ7YSugIS2JpZ1fu4535M7O0u8xvoy@rnPyh8xDSGMcVHAA6YJbBtKltM1ZgQKhhl3zmmCY6AJg/GX2/dD8MHyLpAmowfBsS9x3j1O7jnHucT5PBxN7odfOc30Gme8MctpsgBGCqZy9nQ2nUGR4ZAgkEtgdFXZQH5lJGQk0sS3KUv@6UbJaGzMyyRkNE2Mu9q4gXonBJdYkoRglDCyIHkAAcy5yH2hB0wPtiLjxpfxQoLxneDcSNInVTMWhH3DcUlUDYW@iSLfQtR3vHmaqx7V9cD0ois/FD5NYGucQ@wWWujHUzp74xdTc8aNgeWGMkZkwi7Twt8@DjaDtotvNtxpezlhZZ5A@LZ7Zbcib7dXFF5oRfJDVvL6@jA3cJbFG1XWTKsXQrAmqPUOh8qB7x8iB9B8/OhCE1oHhC/ubkefhh/cv3zhfl60oIlgkbIXQTzHTuE9rU5f3dJ1SiNY8TOoVs3lTcT5oqjaNt4UjKyMtGQGPwkJixNV9j4hT4eubZ/tbQd1kb1D8BJxUO8I0a/PoCrsCLJNp4/ANq1q7olZIvzhRHkjNFmz/1NoIv4e62kjPs4wm0MniqzrU0WmCBMX7zVSdBvJcZzZQXKc5rZNBFa/b8nc7UoBp4gL/ZrcHdQ@aZSDTotgnXH6HGn/g7LuoU5WryP2rH8pUuiusdv/AQ).
Ungolfed:
```
s -> t -> { // lambda taking two parameters in currying syntax
// s is int[][], t is int[]; return type is int
int y = java.time.Year.now().getValue(), // the current year
c = 0, // auxiliary variable used for determining both space and time
d = 1, // initally, assume we have moved in all three space dimensions
i = 3; // for iterating over the three space dimensions
for(; i -- > 0; d *= c, c = 0) // check all coordinates for each dimension, if we have not moved in one of them, d will be 0
for(var l : s) // check the whole list:
c = l[i] != s[0][i] ? 1 : c; // if one coordinate differs from the first, we have moved
for(int a : t) // look at all the years; c is 0 again after the last loop
c |= a > y ? 4 : a < y ? 1 : 2; // compare to the current year, setting a different bit respectively for past, present and future
return c / 7 // if we have been to past, the present and the future ...
* 2 // ... return 2 ...
+ d; // ... combined with the space result, otherwise return just the space result
}
```
] |
[Question]
[
## Introduction:
[](https://i.stack.imgur.com/SnMxA.jpg) (Source: [Wikipedia](https://en.wikipedia.org/wiki/Rainbow))
When we look at a rainbow it will always have the colors from top to bottom:
Red; orange; yellow; green; blue; indigo; violet
If we look at these individual rings, the red ring is of course bigger than the violet ring.
In addition, it's also possible to have two or even three rainbow at the same time.
All this above combined will be used in this challenge:
## Challenge:
Given a list of integers of exactly size 7, where each value indicates the color-particles available to form rainbows (where the largest index indicates red and the smallest index indicated violet), output the amount of rainbows that can be formed.
A single integer-rainbow has to have at least 3x violet, 4x indigo, 5x blue, 6x green, 7x yellow, 8x orange, 9x red. A second rainbow on top of it will be even bigger than the red ring of the first rainbow (including one space between them), so it will need at least 11x violet, 12x indigo, 13x blue, 14x green, 15x yellow, 16x orange, 17x red in addition to what the first rainbow uses. The third rainbow will start at 19x violet again.
**Example:**
Input-list: `[15,20,18,33,24,29,41]`
Output: `2`
Why? We have 15x violet, and we need at least 3+11=14 for two rainbows. We have 20 indigo and we need at least 4+12=16 for two rainbows. Etc. We have enough colors for two rainbows, but not enough to form three rainbows, so the output is `2`.
## Challenge rules:
* The integers in the input-array are guaranteed to be non-negative (`>= 0`).
* The input-list is guaranteed to be of size 7 exactly.
* When no rainbows can be formed we output `0`.
* Input and output format is flexible. Can be a list or array of integers of decimals, can be taken from STDIN. Output can be a return from a function in any reasonable output-type, or printed directly to STDOUT.
## Minimum amount of colors required for `n` amount of rainbows:
```
Amount of Rainbows Minimum amount per color
0 [0,0,0,0,0,0,0]
1 [3,4,5,6,7,8,9]
2 [14,16,18,20,22,24,26]
3 [33,36,39,42,45,48,51]
4 [60,64,68,72,76,80,84]
5 [95,100,105,110,115,120,125]
etc...
```
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: [15,20,18,33,24,29,41]
Output: 2
Input: [3,4,5,6,7,8,9]
Output: 1
Input: [9,8,7,6,5,4,3]
Output: 0
Input: [100,100,100,100,100,100,100]
Output: 4
Input: [53,58,90,42,111,57,66]
Output: 3
Input: [0,0,0,0,0,0,0]
Output: 0
Input: [95,100,105,110,115,120,125]
Output: 5
Input: [39525,41278,39333,44444,39502,39599,39699]
Output: 98
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
thS.ef<b*+tkyy
```
[Test suite!](https://pyth.herokuapp.com/?code=thS.ef%3Cb%2a%2Btkyy&input=%5B15%2C+20%2C+18%2C+33%2C+24%2C+29%2C+41%5D&test_suite=1&test_suite_input=%5B15%2C+20%2C+18%2C+33%2C+24%2C+29%2C+41%5D%0A%5B3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%5D%0A%5B9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%5D%0A%5B100%2C+100%2C+100%2C+100%2C+100%2C+100%2C+100%5D%0A%5B53%2C+58%2C+90%2C+42%2C+111%2C+57%2C+66%5D%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%5B95%2C+100%2C+105%2C+110%2C+115%2C+120%2C+125%5D%0A%5B39525%2C+41278%2C+39333%2C+44444%2C+39502%2C+39599%2C+39699%5D&debug=0)
## How?
**Algortihm**
First off, let's derive the formula this answer is based off. Let's call the function that gives the necessary amount of colour particles \$C(n, i)\$, where \$n\$ is the number of layers and \$i\$ is the index of the colour, 0-based. First, we note that for the \$n^\text{th}\$ layer alone (where \$n\$ is 1-indexed, in this case), we need \$L(n, i)=i+3+8(n-1)\$ colour particles. Keeping this in mind, we sum the results of each \$L(k, i)\$ for each layer \$k\$:
$$C(n, i)=\color{red}{\underbrace{(i+3)}\_{1^\text{st} \text{ layer}}} + \color{blue}{\underbrace{(i+3+8)}\_{2^\text{nd} \text{ layer}}}+\cdots + \color{green}{\underbrace{[i+3+8(n-1)]}\_{n^\text{th} \text{ layer}}}$$
$$C(n, i)=(i+3)n+8\left(0+1+\cdots +n-1\right)$$
$$C(n, i) = (i+3)n+8\cdot\frac{(n-1)n}{2}=(i+3)n+4n(n-1)$$
$$C(n, i)=n(i+3+4n-4)\implies \boxed{C(n,i)=n(4n+i-1)}$$
Therefore, we now know that the maximum number of possible layers, call it \$k\$, must satisfy the inequality \$C(k, i) \le I\_i\$, where \$I\_i\$ is the \$i^\text{th}\$ element of the input list.
**Implementation**
This implements the function \$C\$, and iterates (`.e`) over the input list, with \$k\$ being the index (0-based) and \$b\$ being the element. For each value, the program searches the first positive integer \$T\$ for which \$b<C(T, i)\$ (the logical negation of \$C(T, i)\le b\$, the condition we deduced earlier), then finds the minimum result and decrements it. This way, instead of searching for the highest integer that *does* satisfy a condition, we search for the lowest that *does not* and subtract one from it to make up for the offset of 1.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ 61 bytes
```
lambda l:min(((16*v+i*i)**.5-i)//8for i,v in enumerate(l,-1))
```
[Try it online!](https://tio.run/##bY/RSsQwEEXf/YqAL0mddTOTTNsR/BL1oWKLgTa7lLrg19dpFLuICZkJuYc7uefP5f2UaR0en9exm17fOjM@TClba7GuLnepSq6q7vmQ3PHYDqfZJLiYlE2fP6Z@7pbejnBA59bznPJiBvuEDOQBWwgBKAIJRHxx5tbQzS8TIAJDDQ20IEXEXRR9bFRkhUIR/S6iV@//T0HjjnIAVnsPkQARgdW0LlDYIQ9X@@8w4R9v7ahdo@GWjbiQfBVImPS/SI3mlqDR47b0zp62KqK1lu@w0q5f "Python 2 – Try It Online")
---
Each colour of the rainbow uses `(3+i)+n*8` for layer `n` and color `i`(0=violet, etc.)
The total for x layers is therefore: `(3*i)*x + 8*x*(x+1)`.
We simply solve for n, and take the minimum value.
---
Saved:
* -3 bytes, thanks to ovs
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ 16 bytes
-1 byte thanks to Magic Octopus Urn
```
[ND4*6Ý<+*¹›1å#N
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2s/FRMvs8Fwbba1DOx817DI8vFTZDyhsbGlqZKpjYmhkbqFjbGlsbKxjAgJAtqmBEYi0tASSZpaWsQA "05AB1E – Try It Online")
The amount of colour needed for **n** rainbows is **n(4n + [-1, 0, 1, 2, 3, 4, 5])**.
[Answer]
# JavaScript (ES6), 49 bytes
```
f=(a,n)=>a.some((v,k)=>v<4*n*n-~-k*n)?~n:f(a,~-n)
```
[Try it online!](https://tio.run/##nZHRTsMwDEXf@Yo9JpW7xUncNhODD0E8VKNFJaNBK@Kxv15uERKo6ySEo9iJFB9d577UH/VwPHdv73mfnpppag@qpqgPd/V2SK@NUj11uPW3PotZzMe8y6K@H@O@xbsxj3o6pn5Ip2Z7Ss@qVQ8sZA1xRc6R9WQDeX7UerMau93G3iwAjjwJFVRSReFq5w@Al4CAxhIAAcj9AWCWADYYYH1f4gDwS4A4Eog35C0xMwnkFNeUAOCWAEO/1n9GCPKtGJVR4QrPtlhZoQEgFy4EsfhAtiWcDA5m@jlwFmPnHAJyEb4cAiBU0yc "JavaScript (Node.js) – Try It Online")
### How?
The number \$P\_{(n,k)}\$ of color particles required to generate \$n\$ times the \$k\$-th color is:
$$P\_{(n,k)}=n(4n+(k-1))=4n^2+(k-1)n$$
We recursively try all values of \$n\$ until at least one entry \$v\_k\$ in the input array is lower than \$P\_{(n,k)}\$.
But for golfing purposes, we start with `n === undefined` and use negative values of `n` afterwards. The first iteration is always successful because the right side of the inequality evaluates to `NaN`. Therefore, the first meaningful test is the 2nd one with `n == -1`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
Ṁµ×4+-r5¤×)⁸<Ẹ€¬TṪ
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//4bmAwrXDlzQrLXI1wqTDlynigbg84bq44oKswqxU4bmq////WzE1LDIwLDE4LDMzLDI0LDI5LDQxXQ "Jelly – Try It Online")
Uses the explanation in Okx's 05AB1E answer.
[Answer]
# Excel VBA, 78 bytes
Anonymous function that takes input from the range of `[A1:G1]` and outputs to the VBE immediate window.
```
[A2:G999]="=A1-(COLUMN()+8*ROW()-14)":[H:H]="=-(MIN(A1:G1)<0)":?998+[Sum(H:H)]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
I⌊EA÷⁻X⁺X⊖κ²×¹⁶ι·⁵⊖κ⁸
```
[Try it online!](https://tio.run/##VYsxC4MwEIX/iuMJadHEWEPHujgIDt3EIWigR5MoMdqfnyZLoQ/ex7u7d/NLunmVOoTBofXwkLuHHi2aw0AvN@jsdnjISdZZ3@KJi0rnY4dh/SgHg/7FVs1OGWW9WuAdH2j0E43aoaxJhnkciyuP/C/GRZMn3UMYRyY45aQq6a0hTDDGSJUUMy9oohCRtRDTFC6n/gI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Directly calculates the number of rainbows possible with each colour with a formula I derived independently but turns out to be the same as @TField's formula.
```
A Input array
E Map over values
κ Current index
⊖ Decrement
X ² Square
ι Current index
×¹⁶ Multiply by 16
⁺ Add
X ·⁵ Square root
κ Current index
⊖ Decrement
⁻ Subtract
÷ ⁸ Integer divide by 8
⌊ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes
*Port of [@TFeld answer](https://codegolf.stackexchange.com/a/170617/78039)*
```
_=>Math.min(..._.map((a,i)=>((16*a+--i*i)**.5-i)/8))|0
```
[Try it online!](https://tio.run/##ndHBbsMgDAbg@56iR8gcggEn8SF9gz3BNFWoazumNqnaqqe9e@ZMkzbRVJoGwnDhk@F/j9d4Xp/S8VL2w@tm3Hbjqls@xcubOaReGWNW5hCPSkVIulsqhXURH8syFUkXhaEy6arV@sOO66E/D/uN2Q87tVXPSOAsYAvegwvgGAK@aL2YHVW1cA8Z4CEAQQ0NtMB3b/4AmAMsFxsBSCD/B8DmAFp5wPy65QQIOUAeSJq3EBwgIpC0U9/rRACfAxZ@zf88gem7Y9lRdkkFp1gczWgC0E0KTE4@EF0jSbKXMMM05EzWTZVZas1fCQnA7fgJ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
This was hard!
```
Ṃ+9s8Ṗ‘+\>ݧỊS
```
A monadic Link accepting a list of seven integers which yields an integer, the number of rainbows possible.
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4bmCKzlzOOG5luKAmCtcPsW7wqfhu4pT////MTUsMjAsMTgsMzMsMjQsMjksNDE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##jU6xTsQwDN3zFdnPp8ZJ3NbL/QQTajqynG5DQkJiqG5BYmRAN8DMwg9UxwTqh7Q/Euz2KjEw4MjPz3Zsv/3N4XCf89gfN3xbj/3L1J02aTecv97H89NVHp7H/jQdP4bP70cJe/Gpe7Xb7c5O3dt1tmp3MxqFwqaVF@Jp4cX8ISlfqCZmpZKYBw0L/Iuny0LZbeyaFHprSWR3bhok8A6whhDAR/AMEVsDTYAIBCVUUANrgYVUUiBpBC2gk7m/XdsUgGTUQfSAiEAyXGrDwa83b6bLnESUKJJQNXmahTB5uYm@Eo0cRGZUE07OKzILlsxt@wM "Jelly – Try It Online").
### How?
Unfortunately any naive method seems to take 16 bytes, one such method is `Ṃɓ_J×¥H÷‘H<¬Ȧð€S`, however it turns out the method used here is much more efficient as well as shorter!
This method builds more than enough rainbow stacks as particle counts, **including ultra-violet bands**, and adds up 1 for each stack which is possible.
The test for it being possible is to check that there is only a single band NOT possible given we need some ultra-violet band particles but were provided zero.
```
Ṃ+9s8Ṗ‘+\>ݧỊS - Link list of integers e.g. [0,0,0,0,0,0,0] or [17,20,18,33,24,29,41]
Ṃ - minimum 0 17
+9 - add nine 9 26
s8 - split into eights [[1,2,3,4,5,6,7,8],[9]] [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19,20,21,22,23,24],[25,26]]
Ṗ - discard the rightmost [[1,2,3,4,5,6,7,8]] [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19,20,21,22,23,24]]
‘ - increment (vectorises) [[2,3,4,5,6,7,8,9]] [[2,3,4,5,6,7,8,9],[10,11,12,13,14,15,16,17],[18,19,20,21,22,23,24,25]]
- (single rainbow counts, including ultra-violet bands, ready to stack)
+\ - cumulative addition [[2,3,4,5,6,7,8,9]] [[2,3,4,5,6,7,8,9],[12,14,16,18,20,22,24,26],[30,33,36,39,42,45,48,51]]
- (stacked rainbow counts, including ultra-violet bands)
Ż - zero concatenate [0,0,0,0,0,0,0,0] [0,17,20,18,33,24,29,41]
- (we got given zero ultra-violet band particles!)
> - greater than? (vectorises) [[1,1,1,1,1,1,1,1]] [[1,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1]]
- (always a leading 1 - never enough particles for the ultra-violet band)
§ - sum each [8] [1,1,8]
- (how many bands we failed to build for each sacked rainbow?)
Ị - insignificant? (abs(X)<=1?) [0] [1,1,0]
- (1 if we only failed to build an ultra-violet band for each sacked rainbow, 0 otherwise)
S - sum 0 2
- (the number of rainbows we can stack, given we don't see ultra-violet!)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
žv*āÍn+tā-Ì8÷ß
```
[Try it online!](https://tio.run/##fU8xDsIwENt5RWYIUi/JtdzAS6oOILEyoUpIMHSHN/AMNpaUdwU7AwMDUZLzOZbja3S3l0O5jOfyfo3Lecr34@o0T@t82@RnfpTttfSi3oXGO9l4FyNwwjHvkgyLHj1aKFrvOu8gMbBWUVdZrYoIVhq6/LmgURgqXcCkAFYEBJ1avIL83fxNvxZEQsTQUlMHZUzTwCASOk5hkYMkLnbahFrMWFqz4QM "05AB1E – Try It Online")
A closed-form solution which does not require additional looping rather than the map. This works by adapting [my Pyth's answer's formula](https://codegolf.stackexchange.com/a/170630/59487) to match 05AB1E's indexing convention, then solving for \$n\$, which happens to match [TFeld's algorithm](https://codegolf.stackexchange.com/a/170617/59487).
### Pyth algorithm ⟶ 05AB1E Algorithm
There are *many* methods one can try for solving this challenge in 05AB1E, so I tried a couple of them and this turned out to be the shortest. Adapting the aforementioned formula from my Pyth answer, keeping in mind that 05AB1E used 1-indexing, we can construct our function as follows:
$$C(n,i)=n(i+2)+4n(n-1)$$
Setting it equal to the element of the input (\$I\$) at index \$i\$ and writing it in standard (quadratic) polynomial notation, we have:
$$4n^2+n(i-2)-I\_i=0$$
Note that this equality is not precise (but I currently don't know of a way to state this more formally) and that the solutions to this equation will yield floating-point numbers, but we fix this by using floor division rather than precise division later on. Anyway, to continue on with our argument, most of you are probably very familiar with the solutions of [such an equation](https://en.wikipedia.org/wiki/Quadratic_formula), so here we have it:
$$n\_{1, 2}=\frac{2-i\pm\sqrt{(i-2)^2+16I\_i}}{8}$$
As \$I\_i\$ is always positive, \$\sqrt{(i-2)^2+16I\_i}\ge i-2\$, so the "\$-\$" case doesn't make much sense, because that would be either \$2-i-i+2=4-2i\$, which is negative for \$i\ge 2\$ or \$2-i-2+i=4\$, which is constant. Therefore, we can conclude that \$n\$ is given by:
$$n=\left \lfloor\frac{2+\sqrt{(i-2)^2+16I\_i}-i}{8}\right \rfloor$$
Which is exactly the relation that this answer implements.
[Answer]
# C++, ~~127~~ 125 bytes
Shaved off 2 bytes thanks to Kevin Cruijssen.
```
#include<cmath>
int f(int x[7]){size_t o=-1;for(int c=0,q;c<7;c++,o=o>q?q:o)q=(std::sqrt(--c*c-c+16*x[++c])-c+1)/8;return o;}
```
[Try it online!](https://tio.run/##PY7RboMwDEXf@YqoeyFNohZSSkMI@5CumpBLt0gjaUKQUFG/nZFKmx@OfW3pXsP9zr4AluVNG/gZr12t7RB81/ZN8r@Cvg3fTaJNQLc0cjqXFzwP@tF9BmQVy@TN@tcF1J46CXUpgRBqlW3cu6ssdiodwrWqBudDyhhsgQHJjtvpTAhccBR4d5K@C6M3yMpn0rfapHj@i0MKzVwUeUEPWV6eKBecc3qItc7FPo8UYuVRiKdErzSwY0B1vX494dg3H2azWi/LLw "C++ (gcc) – Try It Online")
The function takes a C-style array of seven ints and returns an int.
The algorithm is pretty straightforward (and have already been described a number of times previously, so here is one more description, mostly for my own viewing pleasure).
Let \$c\$ be the color index (\$0\le c\le6\$), so the required number of particles to form \$n\$-th \$(n\ge1)\$ rainbow part of that color is \$y\_c(n)=(c+3)+8(n-1)\$, and the total amount of particles to form \$n\$ rainbow parts of the color is then \$Y\_c(n)=\sum\_{k=1}^{n}y\_c(k)=n(c+3)+\frac{8n(n-1)}{2}\$. Now we have a system of inequalities \$x\_c\ge Y\_c(n)\$ (where \$x\_c\$ is the elements of input array), which gives us a set of upper bounds on \$n:\$ $$n\le\frac{-(c-1) + \sqrt{(c-1)^2 + 16x\_c}}{8}$$.
What is left is just iterate over \$x\_c\$ and find the minimum.
Explanation:
```
#include <cmath> // for sqrt
int f (int x[7])
{
// Note that o is unsigned so it will initially compare greater than any int
size_t o = -1;
// Iterate over the array
for (int c = 0; c < 7; c++)
{
// calculate the bound
int q = c - 1;
q = (std::sqrt (q * q + 16 * x[c]) - q) / 8;
// if it is less than previously found - store it
o = o > q ? q : o;
}
return o;
}
```
] |
[Question]
[
Given a non-empty 2D array consisting of `0` and `1`, find the number of squares whose 4 corners are all `1`. The squares do not need to be "upright". All the rows are guaranteed to have the same length.
Reasonable input/output methods are allowed.
Testcases:
```
0001000
1000000
0000000
0000100
0100000
```
This returns `1`.
```
10101
00000
10100
00000
10001
```
This returns `2`.
```
1111
1111
1111
1111
```
This returns `20`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
## JavaScript (ES6), ~~127~~ ~~124~~ 119 bytes
*Saved 3 bytes thanks to nderscore*
```
m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n
```
### How?
This function iterates on all pairs of cells **(x, y)**, **(X, Y)** of the input matrix **m** such that:
* **m[ x, y ] = m[ X, Y ] = 1**
* **x < X**
* **y ≤ Y**
Each matching pair describes the coordinates of a potential edge of a square. The inequations guarantee that each edge is tested only once.
We use the vector **[ dx, dy ] = [ X - x, Y - y ]** rotated 90° clockwise to test the cells located at **[ x - dy, y + dx ]** and **[ X - dy, Y + dx ]**. If they both contain a **1**, we've found a valid square.
[](https://i.stack.imgur.com/yHt4Z.png)
### Test cases
```
let f =
m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n
console.log(f([
[0,0,0,1,0,0,0],
[1,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,1,0,0],
[0,1,0,0,0,0,0]
]));
console.log(f([
[1,0,1,0,1],
[0,0,0,0,0],
[1,0,1,0,0],
[0,0,0,0,0],
[1,0,0,0,1]
]));
console.log(f([
[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]
]));
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
&fJ*+4XN!"@&-|un3=vs
```
Input is a matrix.
[Try it online!](https://tio.run/nexus/matl#S/ivlualpW0S4aeo5KCmW1OaZ2xbVvw/1iXkf7SBAggagkkDaxgDxjXAzjWEcZGUx3JFG0JFDK2RNRkiazBAt8gQrA8MrRVwMmK5AA "MATL – TIO Nexus")
### How it works
This finds all coordinates of nonzero entries in the input grid, and represents them as complex numbers, such that row and column indices correspond to real and imaginary parts respectively.
The code then generates an array of all combinations (order doesn't matter) of these numbers taken 4 at a time. Each combination represents a candidate square. For each combination, the 4×4 matrix of pair-wise absolute differences (i.e. distances in the complex plane) is computed. This is a symmetric matrix with zeros along its main diagonal. The current combination forms a square if and only if the matrix contains exactly 3 distinct values (these will be the square side, the square diagonal, and zero):
[](https://i.stack.imgur.com/hRFLJ.png)
On the other hand, for example, a non-square rectangle would give rise to 4 distinct values (two sides, one diagonal value, and zero);
[](https://i.stack.imgur.com/OemSe.png)
and a general quadrilateral can have up to 7 values (four sides, two diagonals, and zero):
[](https://i.stack.imgur.com/dlSRv.png)
```
&f % Input (implicit). Push vectors of row and column indices of nonzero entries
J* % Multiply by imaginary unit
+ % Add the two vectors. Gives a vector of complex coordinates
4XN % Matrix of combinations of these complex numbers, taken 4 at a time. Each
% row is a combination
! % Transpose
" % For each column
@ % Push current column: candidate set of four points
&- % All pair-wise differences
| % Absolute value
u % Unique entries
n3= % Does the number of elements equal 3? Gives true (1) or false (0)
vs % Concatenate vertically with previous accumulated result, and sum
% End (implicit). Display (implicit)
```
] |
[Question]
[
What general tips do you have for golfing in [Haxe](https://en.wikipedia.org/wiki/Haxe)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Haxe (e.g. "remove comments" is not an answer).
Please post one tip per answer.
Haxe can be run online [here](http://try.haxe.org/)!
[Answer]
# String interpolation
Haxe supports [string interpolation](http://haxe.org/manual/lf-string-interpolation.html) on single-quote strings. Like template strings in JavaScript ES6, you can include an expression in a string with `${...}`:
```
trace('2 + 2 = ${2 + 2}');
```
Unlike ES6, however, you can omit the curly brackets when the expression is a single variable:
```
var x = 2 + 2;
trace('2 + 2 = $x');
```
Both of these examples print `2 + 2 = 4`.
[Answer]
# Array comprehensions
Haxe supports array comprehensions:
```
trace([for (i in 0...5) i]); // Prints 0,1,2,3,4
```
Unlike many other languages, you can also use `while` in comprehensions:
```
var i = 5;
trace([while (i > 0) i--]); // Prints 5,4,3,2,1
```
This can be very useful when you don't know how long of an array you need.
You can also chain `for`, `while`, and `if` statements:
```
trace([for (x in ['A','B','C','D'])
for (y in ['x','y'])
if (x + y != "Cx")
x + y
]); // Prints Ax,Ay,Bx,By,Cy,Dx,Dy
```
[Answer]
# Range operator
Haxe has a range operator `...` which can be used to create ranges of integers. For example, instead of this:
```
var i = 0;
while (i < 10) trace(i++);
```
You can do this:
```
for (i in 0...10) trace(i++);
```
Specifics for `x...y`:
* `x` and `y` must both be Ints.
* `x` cannot be larger than `y`.
* This returns an [IntIterator object](http://api.haxe.org/IntIterator.html), which can be used in the same places as any Iterable.
[Answer]
# Running a statement conditionally
Obviously you can run anything conditionally with `if`:
```
if(n>5)doSomething(n);
```
If, however, you have only one statement as above, you can use the ternary conditional operator to save a byte:
```
n>5?doSomething(n):0;
```
You can sometimes save another byte by using `&&`, though this is very rare because `&&` only works if both expressions return booleans:
```
n>5&&doSomething(n);
```
One major exception to this is [keywords](https://codegolf.stackexchange.com/a/107179/42545): if Haxe runs into a `return`, `break`, or `continue` *anywhere*, it will immediately run it and quit whatever expression it was working on. This means that instead of this:
```
if(n>5)return n;
```
You can do this to save 2 bytes:
```
n>5&&return n;
```
[Answer]
# Use keywords in expressions
Another unusual feature of Haxe is that [everything is an expression](http://code.haxe.org/category/principles/everything-is-an-expression.html). For example, this code is perfectly valid:
```
function(n){while(n>0)n%4==1?return 6:n--;return 3;}
```
Okay, that's a fairly useless example, but hopefully you get my point. This works with most keywords:
```
function(n){while(n>0)n%4==1?break:n--;return n;}
```
This allows you to use `if`/`else` inline, like `p=if(n>1)7else 4;`, though of course `p=n>1?7:4;` is shorter.
### Keywords you cannot use inline
* `var` - The compiler will complain about trying to use Void as a value.
* `for`/`while` - Same as above, though you can use them in [array comprehensions](https://codegolf.stackexchange.com/a/93756/42545).
[Answer]
# Omit function brackets
Unlike most languages, [everything in Haxe is an expression](https://codegolf.stackexchange.com/a/107179/42545), including `{blocks}`. Thus, curly brackets *anywhere* in a Haxe program (with the exception of `switch` expressions) can be left off if they contain only a single statement. So instead of this:
```
function f(n){return Math.pow(3,n);}
```
You can do this:
```
function f(n)return Math.pow(3,n);
```
An easy two bytes saved on many functions.
Even if a function must contain multiple statements, you can often save a byte by moving the `return` *outside the block:*
```
function f(a){var b=a*a;return a<0?-b:b;}
function f(a)return{var b=a*a;a<0?-b:b;}
```
This works because a block evaluates to the last expression inside the block.
] |
[Question]
[
# Objective
Given a nonnegative integer, calculate its **NDos-size** as defined below, and output it.
# NDos' numeral system
The concept of NDos-size comes from the numeral system I made. It represents every nonnegative integer by a nested list, as follows:
* With the binary expansion of given nonnegative integer, each entry of the corresponding NDos-numeral stands for each set bit (`1`). The order of the entries is LSB-first.
* The content of each entry is, recursively, the NDos-numeral of the number of the trailing `0`s of the `1` that the entry stands for, counted till the end or another `1`.
For illustrative purposes, here are representations of few integers in NDos' numeral system:
```
Integer = Binary = Intermediate representation = NDos-numeral
0 = []
1 = 1 = [0] = [[]]
2 = 10 = [1] = [[[]]]
3 = 11 = [0, 0] = [[], []]
4 = 100 = [2] = [[[[]]]]
5 = 101 = [0, 1] = [[], [[]]]
6 = 110 = [1, 0] = [[[]], []]
7 = 111 = [0, 0, 0] = [[], [], []]
8 = 1000 = [3] = [[[], []]]
9 = 1001 = [0, 2] = [[], [[[]]]]
```
The **NDos-size** of the given integer is the number of pairs of square brackets of the corresponding NDos-numeral. That gives the NDos-size of few integers as:
```
0 -> 1
1 -> 2
2 -> 3
3 -> 3
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 4
9 -> 5
```
Note that this sequence is not monotone. `18 -> 6` and `24 -> 5` are one counterexample.
# I/O format
Flexible. Standard loopholes apply.
Be careful not to abuse [this](https://codegolf.meta.stackexchange.com/a/8245/89459) loophole. For example, you cannot just input an NDos-numeral as a string and count its left brackets.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
λNb1¡€g₅O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3G6/JMNDCx81rUl/1NTq//8/AA "05AB1E – Try It Online") ([or more nicely formatted](https://tio.run/##yy9OTMpM/f//3G6/JMNDCx81rUl/1NTq/7@2zM9eSUHXTkHJvlLnPwA))
## Explanation
Recursively generates the sequence of NDos-sizes for all numbers.
Note that if in the encoding we split by `1`s and count the size of each part, we'll get the same intermediate representation except an additional `0`. But that additional `0` is good, because it accounts for the `+1` we need for the outer pair of brackets.
```
λ # recursive environment, with base case a(0)=1
N # push the current index
b # convert it to binary
1¬° # split on ones
€g # push the size of each part
‚ÇÖ # recursively calculate a(i) for each part size
O # and sum
```
[Answer]
# [Python](https://www.python.org), 49 bytes
```
f=lambda n:n<1or f(d:=len(bin(n&-n))-3)+f(n>>d+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5BDsIgEEX3nGJWlklLIrWLhljuAqEoSZ02BBeexU03eidvI4kQVzN5_7_MPN_bI11X2vfXPXkxfqSfFnOzzgApOss1gudOTctM3AbidBCEKE7Yek5au1ZiEa3P3QCBIBq6zFweUTGALQZKPHTQCN10kLWAyNgPY5lyrLnPO1bcD3_cD1gu1Ve_)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
Bṣ1Ẉ߀Ḋ¡S
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//QuG5ozHhuojDn@KCrOG4isKhU/874oCcIC0@IOKAnTvDhwrFu8OH4oKsWf//OTk "Jelly – Try It Online")
A monadic link that takes and returns an integer. Written independently of @[CommandMaster’s 05AB1E answer](https://codegolf.stackexchange.com/a/265811/42248) but uses effectively the same method.
Thanks to @JonathanAllan for saving a byte!
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
.+
1$&$*0
{`0?1
#
0
1
}+`(1+)\1
$+0
#
```
[Try it online!](https://tio.run/##Fcs7DsIwFEXB/mwjJgpYit59tvOpKLOJFKagoKFAdIi1m9CONK/7@/G8tdOw1TZGFPpwMT7VrqLDEN9YB8XzLkI0utb@6CQyhYmZhRUdKOQooYwKmtCMFrTihh/H8YRnvPwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
1$&$*0
```
Start with the binary representation of `2‚Åø`.
```
0?1
#
```
Keep a running total of the number of `1` bits. The `0?` is part of the unary to binary conversion below. (See the Retina tutorial.)
```
0
1
+`(1+)\1
$+0
```
Convert the `0`s from unary to binary.
```
{`
}`
```
Repeat until there are no more bits to process.
```
#
```
Output the total number of `1` bits generated.
[Answer]
# [Python](https://www.python.org), ~~65~~ 57 bytes
-8 thanks to @bsoelch
```
f=lambda x:sum(map(f,map(len,f"{x:b}".split('1')[1:])))+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3LdNscxJzk1ISFSqsiktzNXITCzTSdEBkTmqeTppSdYVVUq2SXnFBTmaJhrqhuma0oVWspqamtiHUAM20_CKFTIXMPIWixLz0VA1DA00rLs6Cosy8Eo1MHQV1XTt1HYU0jUxNTYgGmM0A)
Recursively calculates the NDos-size.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 37 bytes
```
f=(x,i)=>x?f(x>>1,~x%2*~i)+x%2*f(i):1
```
[Try it online!](https://tio.run/##FcpLDkAwEADQq8xGMqMlPju0ziKojIiREunK1Stdvc3bp3e6Z8/XU5yyrDE6g0EzGRtGh8HaWn8ha/KPSSUdMnV1dOIBGQxUPTAM0CaVIpjlvOVYy0M2ZA2pUx9/ "JavaScript (Node.js) – Try It Online")
-1 byte as suggested by l4m2
[Answer]
# [Python](https://www.python.org), 46 bytes
```
f=lambda n,a=0:n<1or n%2*f(a)+f(n//2,~n%2*-~a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY39dJscxJzk1ISFfJ0Em0NrPJsDPOLFPJUjbTSNBI1tdM08vT1jXTqQAK6dYmaUF1JaUBFmQqZeQpFiXnpqRqGBppWXAoKBUWZeSUamToK6rp26joKQN2ZmppcXBBhTShtaAGTTwOyNWHCRiYIYSMTTahNMHcCAA)
Essentially a port of @tsh's JS. But also fairly similar to @ovs's Python.
[Answer]
# Python3, 107 bytes:
```
lambda x:f(bin(x)[2:])
f=lambda x,c=0:x in['','0']or(f(bin(c)[2:])+f(x[:-1])if'1'==x[-1]else f(x[:-1],c+1))
```
[Try it online!](https://tio.run/##Nc6xbsMgEAbguTzFyQuc4lTGTtIUiY4Z@wKOB9sFFcnBFjDQp3dByNN33P3AbX/hd7XdfXP7Qz73ZXxNPyNEodlkLIvYt2JAouUxqGfZiAjG9pTWtKHD6ljJziV70iz24swHNJpyKmXs00EtXsExqecTR9w9SKiqqoHzF3DCMy1pMx3pCpfMhVwLt8JH4V74zFzTO0SvDkzaDLRZgnLse7WqBv/ut8UERp@WIgryNtYwpZ/N0c/3Kaa@98oFeDBjAxsRQaZQKieE/R8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
≔×0NθW№θ0≔⪫E⪪θ1∧κ⍘Lκ²1θI⊕Lθ
```
[Try it online!](https://tio.run/##NY1BDoIwEEX3nqJhNU1qosQdK2SFUWOCF6gwgYYyQDvo8WsJun7v/V932tWjtiHk3puW4GkG9JAcEiVKmha@L8MLHUipxCyz3aczFgUU40IMsxJRlFL82stoCG56gmqyZsPHJIY5NdArcdYeK3aGWrgitdxBH2Eq1@1NXB8eUWAotGcoqXY4IDE2/2KOtsxCSE9h/7Zf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔×0Nθ
```
Start with `n` `0`s.
```
W№θ0
```
Repeat until no more `0`s are left.
```
≔⪫E⪪θ1∧κ⍘Lκ²1θ
```
Convert each run of `0`s to binary.
```
I⊕Lθ
```
Output the final number of `1`s plus one for the containing list.
24 bytes using the newer version of Charcoal on ATO:
```
⊞υ×0NW⌈υ≔ΣEυ⪪∧κ⍘Lκ²1υILυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU6xCsIwFNz9ipDpBVLQ4iA4VSfBSqFu4pDW2IS2sTR56n84uhRR9Jf8G1PU5Y47jru7vnIl2vwgqq57oNsHk_clQasAOVnrWlqgQ8rJwjToVlhnsgXG2HRwUrqSBGJx1jXWgIyRyFpdGEi9jEXTF6RNpR1EZgclJzNhZepabQpYSlM4BSXjJGQe6Ij2hL438QEHc2HdP4X93t1muf0dfG5ocKzo9haOv8YH "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
⊞υ×0N
```
Start with `n` `0`s.
```
W⌈υ
```
Repeat until no more `0`s are left.
```
≔ΣEυ⪪∧κ⍘Lκ²1υ
```
Convert each string of `0`s to binary and split it on `1`s.
```
ILυ
```
Output the final length.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
a?fMS#_MTBa^1o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbrEu3TfIOV431DnBLjDPMhglC5JdFGJrFQNgA)
### Explanation
A full program that calculates the NDos size recursively. Identical approach to [Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/265811/16766), but discovered independently.
```
a?fMS#_MTBa^1o
a? ; Is the argument nonzero?
; If so (recursive case):
TBa ; Convert it to binary
^1 ; Split on 1s
#_M ; Take the length of each element
fMS ; Map a recursive call to each and sum the results
; Otherwise, the argument is 0 (base case):
o ; Return 1
```
Splitting the binary representation on 1s treats it as if there's an extra, empty run of 0s at the beginning. This works out perfectly, since it translates to an extra +1 to the final value, which matches the +1 needed to account for the outer pair of brackets.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
f=->n,k=0{n<1?1:n%2*f[k]+f[n/2,~n%-2*~k]}
```
[Try it online!](https://tio.run/##VYpLDoIwGIT3PQULkZbH30dcqdWDIAs0NphqQ0SSKpSrV2jiwpnNfDPz7M9v75UsDibXkg1mz498a2KRqlJXmSoNFflk4kKkk66cbyPMAMSGwKNu8VoRhLRcKs6CQj@MdlSlrRxcmt7oBa37DRbudfeC7va5ujRJUBvpALs5yIligIyc@L/pPK54uPkv "Ruby – Try It Online")
### Bonus stage:
The solution is nothing particularly original, (as it often happens), but I went a little deeper down the rabbit hole and found an interesting pattern and put that in the test cases.
I can't prove anything with so little data, but if I perform a run-length encoding of the sequence, then discard the values and keep only the length, the longest run is always ~~7~~ 9, and the sequence starts from the beginning after **4423** "chunks". Going a little further, the sequence seems to be always the same, and always repeating every 4423 chunks, or ~~32080~~ **16384** numbers.
I don't think that this pattern will repeat forever, I guess that some arbitrary large n multiplied by 16384 will break the sequence.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ò¢ôÍÅx@ßXÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0qL0zcV4QN9Yyg&input=MjUgLW1S)
-2 bytes thanks to two really clever tricks pointed out by Shaggy.
This uses roughly the same method as Command Master’s Python answer.
```
Ò¢ôÍÅx@ßXÊ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­
Ò ‎⁡Add 1 to:
¢ ‎⁢The input, converted to binary,
ôÍ ‎⁣split on elements which are true when inverted.
Å ‎⁤Slice this list from index 1 to the end.
x@ ‎⁢⁡Sum after mapping each X to
ß ‎⁢⁢ the result of recursing with
XÊ ‎⁢⁣ the length of X as the input.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
] |
[Question]
[
(Inspired by [this challenge](https://codegolf.stackexchange.com/questions/258870/generate-number-from-given-range).)
Given six real values in three pairs: \$(x\_1, x\_2), (y\_1, y\_2),\$ and \$(x\_0, y\_0)\$, where \$x\_1 < x\_0 < x\_2\$ and \$y\_1 < y\_0 < y\_2\$, create a function which maps between \$(x\_1, x\_2)\$ and \$(y\_1, y\_2)\$ which also passes through \$(x\_0,y\_0)\$. In other words, make some function
$$f: \mathbb{R} \to \mathbb{R},\; f((x\_1, x\_2)) = (y\_1, y\_2),\; f(x\_0) = y\_0$$
Note that the image of the function has to be over the whole interval -- in other words, for every \$y \in (y\_1,y\_2)\$, there must be some \$x \in (x\_1,x\_2)\$, such that \$f(x)=y\$.
* *The function does not need to be bijective.*
* The value of the function cannot be outside of the given \$y\$ range.
For example, for \$(x\_1, x\_2) = (0, 10), (y\_1, y\_2) = (0, 10), x\_0 = 4, y\_0 = 2\$, a possible function is
$$\begin{cases}
\frac12 x & 0 < x \leq 4 \\
-\frac43 x + \frac{46}{3} & 4 < x < 10
\end{cases}$$
[Which looks like](https://www.desmos.com/calculator/fuymkx8lrd):
[](https://i.stack.imgur.com/IYazQ.png)
On the edge points (i.e. when \$x = x\_1\$ or \$x = x\_2\$) or outside of the interval, the function can have whatever value you want, or it can be undefined.
---
*Note: You don't have to return a function -- you could also write your code so that it takes in \$x\_1, x\_2, y\_1, y\_2, x\_0, y\_0, x\$ and returns \$y = f(x)\$ following the constraints above.*
Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest function wins.
[Answer]
# [R](https://www.r-project.org/), 6 bytes
```
approx
```
[Try it online!](https://tio.run/##K/qfZvs/saCgKL/if4VtsoaBjqGBJlclnFVhYGvCVWlga8TFlaaRrFGhU2GgqZOsUalTCaRNNf8DAA "R – Try It Online") or [Try it with graphical output at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3Dapprox%0A%0Ax%3Dc(0%2C10)%0Ay%3Dc(0%2C10)%0Ax0%3D4%0Ay0%3D2%0A%0Ax_toplot%3D0%3A100%2F10%0Aplot(f(c(x%2Cx0)%2Cc(y%2Cy0)%2Cx_toplot)))
Input is `x1,x2,x0`, `y1,y2,y0`, `x`; output is `x,y`.
This seems like a fairly straightforward task for which built-in solution ought to exit in [R](https://www.r-project.org/), and indeed it does.
---
# [R](https://www.r-project.org), ~~48~~ 38 bytes
```
\(a,b,c,x)(a+(x*(b+c-2*a)/c[1])%%b)[2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WI0EnWSdJJ1KjQ1ErU1KrQ0krSTdY20EjX1k6MNYzVVVZM0o41ioapTlRUSFTKLFSoMdSoNuZQVksAcI51KIyAnGcwx0Kk04Eq0TdYw0DHQ5EoCMgwNdAyBzGQg00THSJOLKw1qJVAQxjRBMM00IZYtWAChAQ) or [Try it with graphical output at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(a%2Cb%2Cc%2Cx)(a%2B(x*(b%2Bc-2*a)%2Fc%5B1%5D)%25%25b)%5B2%5D%0A%0A%23%20a%20is%20x1%2Cy1%0A%23%20b%20is%20x2%2Cy2%0A%23%20c%20is%20x0%2Cy0%0Aa%3Dc(0%2C0)%0Ab%3Dc(10%2C10)%0Ac%3Dc(4%2C2)%0A%0Ax_toplot%3D0%3A100%2F10%0Aplot(x_toplot%2Csapply(x_toplot%2Cf%2Ca%3Da%2Cb%3Db%2Cc%3Dc))%0A)
Input is `x1,y1`, `x2,y2`, `x0,y0`, `x`; output is `y`.
Non-builtin solution. Avoids any kind of curve-fitting tomfoolery by using a deliberately non-bijective function.
[](https://i.stack.imgur.com/WNbzY.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
&1Yn
```
The implemented mapping consists of two straight segments: the first from the point \$(x\_1,y\_1)\$ to \$(x\_0,y\_0)\$, and the second from \$(x\_0,y\_0)\$ to \$(x\_2,y\_2)\$.
The code inputs two numerical vectors and a number: `[x1 x0 x2]`, `[y1 y0 y2]`, `x`. Then it simply calls the `interp1` function, which linearly interpolates the data defined by `[x1 x0 x2]` and `[y1 y0 y2]` at the abscissa `x`. The ouput is the value `y` corresponding to `x`.
[**Try it online!**](https://tio.run/##y00syfn/X80wMu///2gDBRMFQ4NYLiDDCMwwBAA) You can also see the graph of the mapping [**here**](https://matl.io/?code=%26XG&inputs=%5B0+4+10%5D%0A%5B0+2+10%5D&version=22.7.4).
[Answer]
# JavaScript (ES6), 71 bytes
Expects \$(x\_0,x\_1,x\_2,y\_0,y\_1,y\_2,x)\$.
Just uses quadratic interpolation, which is most certainly not the shortest approach.
```
(a,b,c,d,e,f,x)=>(x-b)*((f-e)/(c-b)-(e-=d)/(b-=a))/(c-a)*(x-=a)+e/b*x+d
```
[Try it online!](https://tio.run/##jYzLDoIwEEX3fMUspzAVS9iR@iOGRZ9GQ6gRYsrX18G4dMHiJvdxch/mbRb3uj9XOScfStQFDVly5ClQpCz0BbO0okaMMogWHQeJQWrPwUptxLc0TOQ9NaG1dW58mcIKV8hngqxYHcHGfmO/dTCC5rEn4Eqxup8bh6pyaV7SFE5TumHE/weMCzEcRPvjqNpvywc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
NθNηNζF⊕›θη«NεNδ»I⁺ζ∕×⁻θη⁻δζ⁻εη
```
[Try it online!](https://tio.run/##XY3BCsIwDEDP9ityTKCCiuBhRwXZQdnBH6hrZIWt067dYeK3186BTEku78FLykq5slV1jLm9B38OzZUdPigTc67@eEh8ax1gbkvHDVvPGo@OlR9jCRURwVMs5g2n5kfoJF6icMZ63KvOY1GHDgcJB9MbzXgxDXd4MjbZz00JE2gJA32Jp3dEWYw72MIGVmnW48ZlX78B "Charcoal – Try It Online") Link is to verbose version of code. Takes input as seven numbers `x`, `x₀`, `y₀`, `x₁`, `y₁`, `x₂` and `y₂`. Explanation: Performs linear interpolation between `x₀` and `y₀` and either `x₁` and `y₁` or `x₂` and `y₂` depending on whether `x` is greater than `x₀` or not.
```
Nθ
```
Input `x`.
```
NηNζ
```
Input `x₀` and `y₀`.
```
F⊕›θη«NεNδ»
```
Input `x₁` and `y₁` or `x₂` and `y₂` depending on whether `x` is greater than `x₀`.
```
I⁺ζ∕×⁻θη⁻δζ⁻εη
```
Perform linear interpolation.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 33 bytes
```
Đ←=?ĉ←:←ŕŕ←←-Đ↔⇹ᵮ₄%⇹/4*←Đ←⇹-⇹↔*+;
```
[Try it online!](https://tio.run/##K6gs@f//yIRHbRNs7Y90AikrID469ehUIAVEuiCpKY/adz7cuu5RU4sqkKVvogWUAGsB8nSBGKhCS9v6/39DPRMuQz1TLmMuEy4DIDQBAA "Pyt – Try It Online")
Uses \$f(x)=\left\{\begin{array}{ c l }y\_0 &\quad\textrm{if }x=x\_0 \\y\_1+(y\_2-y\_1)\*{4\left(x\!\!\!\!\mod\!{x\_2-x\_1\over 4}\right)\over x\_2-x\_1}& \quad\textrm{otherwise}\end{array}\right. \$
Takes input as the following, each on a new line: `x x0 y0 x2 x1 y1 y2`
| Code | Stack | Action |
| --- | --- | --- |
| Đ | \$x\ x\$ | implicit input; `Đ`uplicate |
| ← | \$x\ x\ x\_0\$ | get \$x\_0\$ |
| =? | \$x\ \{x\!=\!x\_0\}\$ | if \$x=x\_0\$: |
| ĉ← | \$y\_0\$ | `ĉ`lear the stack and get \$y\_0\$ |
| :←ŕŕ | \$x\$ | otherwise, get \$y\_0\$ and then `ŕ`emove \$\{x\!=\!x\_0\}\$ and \$y\_0\$ |
| ←←- | \$x\ z\$ | get \$x\_2\$ and \$x\_1\$ and then subtract (call it \$z\$) |
| Đ | \$x\ z\ z\$ | `Đ`uplicate |
| ↔⇹ | \$z\ x\ z\$ | manipulate the stack |
| ᵮ₄ | \$z\ x\ {z\over4}\$ | cast to `ᵮ`loat, then divide by 4 |
| % | \$z\ q\$ | \$x\!\!\!\!\mod\!\! {z\over4}\$ (call it \$q\$) |
| ⇹ | \$q\ z\$ | swap top two items on stack |
| / | \${q\over z}\$ | divide |
| 4\* | \${4q\over z}\$ | multiply by 4 |
| ←Đ | \${4q\over z}\ y\_1\ y\_1\$ | get \$y\_1\$ and `Đ`uplicate |
| ← | \${4q\over z}\ y\_1\ y\_1\ y\_2\$ | get \$y\_2\$ |
| ⇹- | \${4q\over z}\ y\_1\ m\$ | swap top two on stack and then subtract (call it \$m\$) |
| ⇹↔ | \$y\_1\ m\ {4q\over z}\$ | manipulate the stack |
| \* | \$y\_1\ {4mq\over z}\$ | multiply |
| + | \$y\_1+{4mq\over z}\$ | add |
| ; | | either way, implicit print |
The function is onto \$(y\_1,y\_2)\$ as follows:
It can be trivially shown that if the discontinuity at \$x\_0\$ did not exist, then \$\forall y\in(y\_1,y\_2)\$, \$\exists\$ at least one \$x\in(x\_1,x\_2)\$ s.t. \$f(x)=y\$. In fact, there would be between two and four such points for all values.
Some of you may object here and say that \$\nexists x\in(x\_1,x\_2)\$ s.t. \$f(x)=y\_2\$, and you'd be right. However, the problem lists the intervals as open, and so the endpoints are not necessary.
Since without the discontinuity, there would be at least two distinct \$x\in(x\_1,x\_2)\$ such that \$f(x)=y\$, with the discontinuity, every point must have at least one such \$x\$. Therefore, \$f(x)\$ is onto \$(y\_1,y\_2)\$.
[Answer]
# [Python](https://www.python.org), 81 bytes
```
lambda a,b,c,d,e,f,x:(x-b)*((f-e)/(c-b)-(e:=e-d)/(b:=b-a))/(c-a)*(x:=x-a)+e/b*x+d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XUw9CsIwGN09xTd-Sb_QVjpIIDdwcVaHpElQiLVIhHgWl4DonbyNwXbR4fF-effXeIuH85AfXu2e1-jF6r0J-mSsBk2GerLkyFOSmIRhHNELx2rsixHopHLCFmukMkKzb6HLKkmViqhcbXiq7Hy8DqBgCx1BQ9AWLGe1X4yX4xDRIw8E0DD2G3R_QVsW02fOE38A)
Port of Arnauld's JS answer.
] |
[Question]
[
Given the signal level `L` in the range `0-4`. Your program should draw the following ASCII art.
When `L=0`:
```
....
....
.... ....
.... ....
.... .... ....
.... .... ....
.... .... .... ....
.... .... .... ....
.... .... .... ....
```
When `L=1`:
```
....
....
.... ....
.... ....
.... .... ....
.... .... ....
oooo .... .... ....
oooo .... .... ....
oooo .... .... ....
```
When `L=2`:
```
....
....
.... ....
.... ....
oooo .... ....
oooo .... ....
oooo oooo .... ....
oooo oooo .... ....
oooo oooo .... ....
```
And etc. You can change the characters `o` and `.` to others, it's up to you. Trailing spaces are allowed.
This is a code-golf challenge so the shortest solution wins.
[Answer]
# [J](http://jsoftware.com/), 47 46 bytes
```
' .o'{~[:|.@|:[:,/(4,&0@#"+3+2*i.4)#"+1+4{.$&1
```
[Try it online!](https://tio.run/##ldDBCsIwDAbg@57ip461XWu2bt3BgiAKnsSD1x3FoV72AB179VqEgogoBgKB8CUk98CID1g7cGjUcDGXhN3psA8cNHI/926izeR6pythdVFvFky1qilvZGUsjbKe8sIEmR23hBcUBVUi9WUpOk1zkp5WsLlx7@i5Sei60DLafLaaEinTqI9GV50n1vxpvl2EDL8ju5yvIwam4uMMGrSw4QE "J – Try It Online")
[Answer]
# APL+WIN, 48 bytes
Prompts for n
```
⊖⍉⊃((n↑m)⍴¨⊂⊂4⍴'0'),((-4-n←⎕)↑m←1+2×⍳4)⍴¨⊂⊂4⍴','
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6OuaY96Ox91NWto5D1qm5ir@ah3y6EVj7qagMgEyFY3UNfU0dDQNdEFSk8AatYEqQLp1zY6PP1R72YTDB066v@BRnP9T@My4FJXUOdK4zKE0kZQ2hhKm3ABAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python](https://www.python.org), 75 bytes
```
def f(n,j=4):print(*(" .o"[(i>=j)*~(n<i)]*4for i in b""));1/j;f(n,j-.5)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3vVNS0xTSNPJ0smxNNK0KijLzSjS0NJQU9PKVojUy7WyzNLXqNPJsMjVjtUzS8osUMhUy8xSSlBiZmFmUNDWtDfWzrMG6dfVMNaFG6oDU5YHUFSXmpadqmGpacSmUFFVaARVqcimkViSnFpRArYLqgTkHAA)
Finishes with an exception. The `b""` string contains the literal bytes `0x01` `0x02` `0x03` `0x04`, but they're invisible here.
Could probably be improved with some more tweaking.
## 76 bytes
```
def f(n,j=4):print(*(" .o"[(i>=j)*~(n<i)]*4for i in b""));j>0!=f(n,j-.5)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fVJS0xTSNPJ0smxNNK0KijLzSjS0NJQU9PKVojUy7WyzNLXqNPJsMjVjtUzS8osUMhUy8xSSlBiZmFmUNDWts-wMFG3B2nX1TDUhZu4DqcsDqStKzEtP1TDVtAKq0LSGGA5VBHMAAA)
No error.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
4ɾ≥vS4ɾd›*¶+4*⁋↵§
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0yb7iiaV2UzTJvmTigLoqwrYrNCrigYvihrXCpyIsIiIsIjMiXQ==)
-3 thanks to Seggan.
```
4ɾ≥ # Create a map of ones and zeroes corresponding to the bar characters.
vS # Stringify those
4ɾd› # Create the range [3, 5, 7, 9]
* # And repeat each char of those
¶+ # Append a newline to each
4* # Repeat each four times
⁋↵ # Turn into a list of lines
§ # Rotate 90°
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
↑E⁴E⁴×§.o›Iθι⁺³⊗ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwTexQMMEToVk5qYWaziWeOalpFZoKOnlK@kouBelJpakFmk4JxaXaBRq6ihkagKJgJzSYg1jHQWX/NKknNQUDaAgCFj//2/0X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁴ Literal integer `4`
E Map over implicit range
⁴ Literal integer `4`
E Map over implicit range
.o Literal string `.o`
§ Indexed by
θ Input `L`
I Cast to integer
› Is greater than
ι Outer value
× Repeated by
³ Literal integer `3`
⁺ Plus
ι Outer value
⊗ Doubled
↑ Print rotated 90° anticlockwise
```
Charcoal prints each array element in its own row (or column, if rotated as it is here) and automatically double-spaces nested arrays when printing them.
14 bytes by using the custom characters `1` and `0` instead of `o` and `.`:
```
↑E⁴E⁴⭆⁺³⊗ι›Iθι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwTexQMMETgWXAGXSQZyAnNJiDWMdBZf80qSc1BSNTE1NHQX3otTEktQiDefE4hKNQqAAUBQIrP//N/qvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁴ Literal integer `4`
E Map over implicit range
⁴ Literal integer `4`
E Map over implicit range
³ Literal integer `3`
⁺ Plus
ι Outer value
⊗ Doubled
⭆ Map over implicit range and join
θ Input `L`
I Cast to integer
› Is greater than
ι Outer value
↑ Print rotated 90° anticlockwise
```
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
f=lambda L,i=0:i<36and". o"[i%4+i/8<3or-(i%4<L)]*4+" \n"[i%4>2]+f(L,i+1)or""
```
[Try it online!](https://tio.run/##HctNCsIwEEDhqwwDwozxP1WkpJ6gN9AuIjU60E7K0I2nj8Xl4@NN3/mT1ZeSmiGOzz5Cu5HmUEvwl6g97iDjXVaVk/01@GxbWiK03K0rh/DQP95OnUu0jO7I2RBLygYComBR3y86cw2Tic6USJjLDw "Python 3 – Try It Online")
-2 bytes by [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)
---
# [Python 3](https://docs.python.org/3/), 91 bytes
```
f=lambda L:L<45and" ".join(4*" o."[j+j+L//5>5and~(j<L%5)]for j in[0,1,2,3])+"\n"+f(L+5)or""
```
[Try it online!](https://tio.run/##FcpBDoIwEADAr2w2Mdm1DajQC0Fe0B8ghxqsttEtabh44etVzjPLd30laUrx17f73GcHtrN9a5zMCFjFFITaI0KqcIwqKlvXZth1o9jbg@HJpwwRgownfdYX3Uys8CaoPFllOGXEspfwL5CdPB9kuIMlB1nJU2AuPw "Python 3 – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4L‹ā·>×ε4иø}ζR€.B»
```
Uses `01` instead of `o.` respectively.
[Try it online](https://tio.run/##ASkA1v8wNWFiMWX//zRM4oC5xIHCtz7Dl861NNC4w7h9zrZS4oKsLkLCu///Mg) or [verify all test cases](https://tio.run/##MzBNTDJM/W9ybJKSZ15BaYmVgpK9nw6Xkn9pCYSn4/ffxOdRw84jjYe22x2efm6ryYUdh3fUntsW9KhpjZ7Tod3/dQ5ts/8PAA).
**Explanation:**
Uses the legacy version of 05AB1E because it can zip/transpose on a list of strings, where the new version would require a character-matrix.
```
4L # Push list [1,2,3,4]
‹ # Check for each whether it's larger than the (implicit) input
ā # Push a list in the range [1,length] (without popping): [1,2,3,4]
· # Double each: [2,4,6,8]
> # Increase each by 1: [3,5,7,9]
× # Repeat the earlier checks that many times as strings
# (e.g. input=2 → [0,0,1,1] → ["000","00000","1111111","111111111"])
ε # Map over each string:
4и # Repeat it 4 times as list
ø # Zip/transpose; swapping rows/columns
}ζ # After the map: zip/transpose again, with implicit " " as filler
R # Reverse this list of lists
€ # Map over each inner list:
.B # Box: expand the single filler space to length 4 by adding trailing
# spaces based on the string with the longest length in the list
» # Join each inner list by spaces; and then each string by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 65 bytes
```
->n{(0..8).map{|x|(0..3).map{|y|(y<3-x/2?" ":y<n ??o:?.)*3}*' '}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNAT89CUy83saC6pqIGxDOG8iprNCptjHUr9I3slRSUrCpt8hTs7fOt7PU0tYxrtdQV1Gtr/xeUlhQrpEUbxf4HAA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 [bytes](https://github.com/abrudz/SBCS)
Uses `1/0` instead of `o/.`.
```
3 5 7 9,.{¯9 5↑⍺4⍴⍕⍵}4↑⍴∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///31jBVMFcwVJHr/rQeksF00dtEx/17jJ51LvlUe/UR71ba03AIlsedcww/J/2qG3Co96@R31TPf0fdTUfWm8MkuybGhzkDCRDPDyD/0Pk2iYYcFUDmSD1Xc1pQHMedbdA@OrqtYdWPOrdbAoA "APL (Dyalog Unicode) – Try It Online")
`⍴∘1`: Reshape of 1. Creates a vector of `L` 1's.
`4↑`: Take 4. Extend to length 4 by appending 0's.
`,.{...}`: Inner product. Pair elements from the computed boolean vector and `3 5 7 9` and call the inner dfn on it. Reduce the resulting list by concatenating character matrices horizontally.
`⍕⍵`: Format. Convert the 1 or 0 to a string.
`⍺4⍴`: Reshape into a `⍺×4` character matrix by replicating the digit.
`¯9 5↑`: Extend to a `9×5` matrix by padding with spaces to the top and right.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 78 bytes
```
j,i;f(x){for(i=180;--i;putchar(j?i%5&&i/35+j/5<5?j/5+x>3?79:46:32:10))j=i%20;}
```
[Try it online!](https://tio.run/##FY3LCoMwEEX3@QoRlAlpMGrTR0brj3QjAdsJNC3WgiD59jRuDpezuMfKh7UxugPhBCvfpvcM1NcXhVISfn6LfY4zuIEKXZZUtVq4Snd6SBTrrR3OV3M8mbYxteLc9VQ0CkMkv2SvkTzwjaXHDHZBvULqNApBuwbiyFLgC/nd52kHFuIf "C (gcc) – Try It Online")
Pretty straightforward approach:
often times in C is convenient to iterate backwards the entire volume so we start with *i=lines x width*.
Each time we print the proper character based on div modulus values.
Luckily I found that I could save some Bytes by using i%35 instead of i%40 which would require some extra operations to fit the right shape of each bar.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
4RðḤ‘ṁ"@>z⁶Ṛx4Y
```
Prints with `o` as `0` and `.` as `1`.
**[Try it online!](https://tio.run/##ASUA2v9qZWxsef//NFLDsOG4pOKAmOG5gSJAPnrigbbhuZp4NFn///8x "Jelly – Try It Online")**
### How?
```
4RðḤ‘x"@>z⁶Ṛx4Y - Main Link: integer, L
4 - four
R - range -> [1,2,3,4]
ð - new dyadic chain - f(X=[1,2,3,4], L)
Ḥ - double X -> [2,4,6,8]
‘ - increment -> [3,5,7,9]
> - X greater than L? -> [1>L,2>L,3>L,4>L]
@ - with swapped arguments - f([1>L,2>L,3>L,4>L], [3,5,7,9]):
" - zip with:
x - times -> [[1>L,1>L,1>L],[2>L,2>L,2>L,2>L,2>L],[3>L,...],[4>L...]]
z⁶ - transpose with filler of space characters
Ṛ - reverse
x4 - times four (vectorises)
Y - join with newline characters
- implicit, smashing print
```
[Answer]
## Javascript, 99 bytes
```
x=>"0004003402341234"[r="replace"](/\d{4}/g,"$&\n$&\n")[r](/\d/g,y=>+y?x<y?".... ":"oooo ":" ")
```
(Didn't it use to be `$0` for this and not `$&`?)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
```
L=>(g=i=>i--?` .
o`[i%20?i%5&&i/20+2*(x=i/5&3)<9|x+L&4:3]+g(i):'')(180)
```
[Try it online!](https://tio.run/##DctBDoIwEADAu6/YC6W1KdQCiQILH@AHxgSCtFlDqAFjOPj3ymlO8xq@wzau9P6oxT@nYDF02HCHhA0p1faQwAl8f6fI6JaigjFKjZbmzHektGCZqG@/XXYsL7OHdJxEGceCX65aBOtX4AQIugKCGiE/lFLA6JfNz1Mye8ftUUQV/g "JavaScript (Node.js) – Try It Online")
-1 byte by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
---
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
```
L=>(g=i=>i>8?'':[1,2,3,4].map(j=>' o.'[j+j+i<8?0:j>L?2:1].repeat(4)).join` `+`
`+g(++i))``
```
[Try it online!](https://tio.run/##DcpBCoMwEADAe1@xt2xYG9R6KGriB/yBCAk2ygZrRKXfTz3NZYL7uXM6eL@eW/z4NOvUa4OLZm3YvDsh6qHIyuyVVaP6uh2DNgKiEkOgQNy@u7wOpu/KuhjV4XfvLqykVCHyZsGSfVhakIiltDbN8QBk0JA3wNBqqG6JJExxO@Pq1RoXnPHOTfoD "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~104~~ ~~100~~ 93 bytes
```
lambda n:[f'{"oooo "*(b:=n-4+(k:=min(i,7)//2+1))+".... "*(k-max(0,b)):>20}'for i in range(9)]
```
[Try it online!](https://tio.run/##RYpBDsIgEAC/Qrh0t6W2Vo1Kgh9RDxBFSWUhpAeN8e1IvTi3mUx8TfdAq11M2apTfmhvLpqRPNrqzUOB8RqMVNSuGxil8o7AiS123dAsERu@KMzP2Hr9hF4YRHkY@k9lQ2KOOWJJ0@0KezznOdE/bVDG5GgCQlF7HeFnwhbH/AU "Python 3.8 (pre-release) – Try It Online")
Returns a list of strings, allowed [here](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/17095#17095).
Thanks everyone for all the tips on my previous python answer. I used some of those tips here!
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda n:"".join(". o"[i<~i%4*8or-(i%4<n)]*4+" \n"[i%4]for i in range(36))
```
[Try it online!](https://tio.run/##XclBCsIwEEbhq/wMFCYtdtMoUtKT2C4iGh2xMyV048arx6zdPd63ffan6VDSNJd3XK@3CB2J@peJMvUwukj4SuPbs@UD1wjqltZ3BGDWqo1fkmUIRJGjPu48nJwrf@/oRmxZdOfEUvkH "Python 3 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 544 bytes
```
+[-->---[-<]>]>[<<+>>>+<-]<-[>--<-------]>+[<+>-]>[<+>-]+++++++[<++>-]>+++++[<++>-]>-[>+<-----]>---<,>[<->-]<[>>+<<-[>>>>+<<<<-[>>>>>>+<<<<<<-[>>>>>>>>+<<<<<<<<-]]]]++[<+++++[<<<<...>>>>-]>->>>>>>>>[<]<<<<<<<<<<<....[>]<.>>]++[<+++++[<<<<..>>>>-]>->>>>>>[<]<<<<<<<<<....[<]>.[>]>>>>>>>>>[<]<<<<<<<<<<<....[>]<.>>]++[<<<<<.....>>>>>->>>>[<]<<<<<<<....[<]>.[>]>>>>>>>[<]<<<<<<<<<....[<]>.[>]>>>>>>>>>[<]<<<<<<<<<<<....[>]<.>>]+++[->>[<]<<<<<....[<]>.[>]>>>>>[<]<<<<<<<....[<]>.[>]>>>>>>>[<]<<<<<<<<<....[<]>.[>]>>>>>>>>>[<]<<<<<<<<<<<....[>]<.>>]
```
[Try it online!](https://tio.run/##tZHBCgIxDEQ/KKYXr0N@JOSggiCCB8Hvr5N2a13WgyDOYbdJ583A7vF@uNzOj9O1VnFVU1VXhIU5IGYm0IA6L6BdYeK80rTkS7o4tOVqIChYKD6wI8OSgGdy5rYKjOMyzPG14CqoHt0aqFJKWjJ82B2BKRqKW4C2Dbom37lG8SMkat8Fj11L7ZkT@JD3Ux3/1DRs6H/11rp/Ag "brainfuck – Try It Online")
Builds each line in segments. Ungolfed:
```
memory layout
0 1 2 3 4 5 6 7 8 9 10 11 12 13
' ' dot 'o' \n cnt inp 0 Nge1 0 Nge2 0 Nge3 0 Nge4
constants
space = 32
+[-->---[-<]>]>
[<<+>>>+<-]<
o = 111
-[>--<-------]>+
[<+>-]
dot = 46
>[<+>-]
+++++++[<++>-]
\n = 10
>+++++[<++>-]>
get input
-[>+<-----]>---<,>[<->-]<#
check 0
[
>>+<<
check 1
-[
>>>>+<<<<
check 2
-[
>>>>>>+<<<<<<
check 3
-[
>>>>>>>>+<<<<<<<<
check 4
-
]
]
]
]#
first 2 lines
++[
15 spaces
<+++++[<<<<...>>>>-]>-
4 bar segment
>>>>>>>>[<]<<<<<<<<<<<....
[>]<.>>
]
next 2 lines
++[
10 spaces
<+++++[<<<<..>>>>-]>-
3 bar segment
>>>>>>[<]<<<<<<<<<....
space
[<]>.[>]>
4 bar segment
>>>>>>>>[<]<<<<<<<<<<<....
[>]<.>>
]
next 2 lines
++[
5 spaces
<<<<<.....>>>>>-
2 bar segment
>>>>[<]<<<<<<<....
space
[<]>.[>]>
3 bar segment
>>>>>>[<]<<<<<<<<<....
space
[<]>.[>]>
4 bar segment
>>>>>>>>[<]<<<<<<<<<<<....
[>]<.>>
]
last 3 lines
+++[
-
1 bar segment
>>[<]<<<<<....
space
[<]>.[>]>
2 bar segment
>>>>[<]<<<<<<<....
space
[<]>.[>]>
3 bar segment
>>>>>>[<]<<<<<<<<<....
space
[<]>.[>]>
4 bar segment
>>>>>>>>[<]<<<<<<<<<<<....
[>]<.>>
]
```
It could probably be shorter with a complex loop to handle generating each line but I couldn't get something like that to work.
[Answer]
# Java 11, ~~105~~ 102 bytes
```
n->{for(int i=36;i-->0;)System.out.print((i/4>8-i%4*2?" ":n<i%4?".":"o").repeat(4)+(i%4<1?"\n":" "));}
```
Could probably be golfed slightly more by removing the `.repeat(4)` and looping `144` times instead, but I don't have the time to figure it out for now.
[Try it online.](https://tio.run/##fZBPS8QwEMXv@ymGASGxJK5aRJr@OXtwPexRPcRuVrJ2p6VNF2TpZ6@z3aIg6GVI3nvh/TI7e7Bqt/kYy8p2HTxaT8cFgKfg2q0tHaxOV4BD7TdQCtaBpGFpWPDogg2@hBUQZDCSyo/bup1CPru9M16pfGnk@rMLbq/rPuimZVMIfxXn98pfxJc3BQImlPK5QI0J1ih16xpng4hlJFhPrwt8IbYApTTDaE7NTf9WcfMMMNHtmV2sAze8P79aeeb@4Vka8GkW84yi2QT4jVaRwAdq@pAARn766F@xpz6cc98p0ryg/97M3jCtbxi/AA)
**Explanation:**
```
n->{ // Method with integer parameter and no return-type
for(int i=36;i-->0;) // Loop `i` in the range (36,0]:
System.out.print( // Print:
(i/4 // If `i` integer-divided by 4
> // is larger than
8-i%4*2? // 8 minus `i` modulo-4 times 2
" " // Use a space
:n<i%4? // Else-if the input is smaller than `i` modulo-4:
"." // Use a dot
: // Else:
"o" // Use an O
).repeat(4) // Repeat this character 4 times
+(i%4<1? // Once every four iterations:
"\n" // Append a newline
: // Every other iteration:
" ")); // Append a space instead
```
] |
[Question]
[
Given a variable a (non array) or (any[]) convert to (any[])
```
function example(s: string | string[]) {
const e = Array.isArray(s) ? s: [s]
return e
}
```
Is `Array.isArray(s) ? s: [s]` the shortest way?
[Answer]
## 10 bytes
```
[s].flat()
```
This works by doing a shallow flat on `[s]`. So, if `s` is anything other than an array, nothing can be flattened and it will stay as `[s]`. But if `s` *is* an array, the outer `[]` will be flattened away, leaving a shallow clone of `s`.
Note that you can also use this to concat a number of arrays, either with other arrays or non-array elements:
```
[r,s,t].flat()
```
This is actually a trick I wasn't aware of until now. It's still a byte longer than `concat` though, if the first item's guaranteed to be an array:
```
r.concat(s,t)
```
When `r` could be anything, `[r,s,t].flat()` seems to be the best option.
[Answer]
aparently this works `t.map?t:[t]`
] |
[Question]
[
# Background
In X11 (a windowing system used by a lot of Unix-like OS), what you would call the clipboard behave a bit differently than on other OSes like MacOS or Windows. While the "traditional" clipboard using ctrl+v/ctrl+c works, there is also another clipboard, called PRIMARY selection, that behave as following:
* when you select a piece of text, this selection is added to the clipboard
* when you use the middle mouse button, the content of that selection is pasted where your mouse is.
Some more details for those who are interested : [X11: How does “the” clipboard work?](https://www.uninformativ.de/blog/postings/2017-04-02/0/POSTING-en.html)
# Challenge
The input in this challenge is any representation of a binary input. In the following I will use 'S' for select and 'P' for paste.
Given the input, you must output the input after making the following changes :
* put the content of the current output in the primary selection when you receive a select instruction
* paste the content of the primary selection in the middle of the current output when you receive a paste instruction. If the current output is odd numbered, the middle is the length divided by 2 and truncated.
## Example
Input is `SPSP` :
```
selection = ""
output = "SPSP"
SPSP
↑
```
```
selection = "SPSP"
output = "SPSP"
SPSP
↑
```
```
selection = "SPSP"
output = "SPSPSPSP"
SPSP
↑
```
```
selection = "SPSPSPSP"
output = "SPSPSPSP"
SPSP
↑
```
```
selection = "SPSPSPSP"
output = "SPSPSPSPSPSPSPSP"
SPSP
↑
```
Final Output is `SPSPSPSPSPSPSPSP`
## Test Cases
```
"" -> ""
"S" -> "S"
"P" -> "P"
"PS" -> "PS"
"SP" -> "SSPP"
"SPP" -> "SSPSPPPPP"
"SPSP" -> "SPSPSPSPSPSPSPSP"
"SPPSP" -> "SPSPPSPSPSPPSPPSPSPPSPPSPSPPSP"
"SPPSPSSS" -> "SPPSSPPSSPPSSPPSSPPSSPPSPSSSPSSSPSSSPSSSPSSSPSSS"
```
## Reference Implementation
In Python 3 :
```
def clipboard(inp, select="S", paste="P"):
out = inp
primary_selection = ""
for instruction in inp:
if instruction is select:
primary_selection = out
if instruction is paste:
out = out[:len(out)//2] + primary_selection + out[len(out)//2:]
return out
```
[Try it online!](https://tio.run/##fVLLisQgELznK8RTZISB3VvAfxA8DmHIzhhWyKqoOczXZ7vVTBLIrolJtVVdtg//St/Ofi7LU4/kMRn/5YbwbI31nEQ96UcSVFFO/BCTFlRS1jUEmpsTEQRkOfLB/AzhdS8ZxlngKM3U6ALIYgpzIQy@vphgM@ORjnXaTfHXBFDCPy654KNJqRm@t27StgXArtePnlxO7C9Zt5N1ffYKOs3BIrkkHVMEw1vTUsopZRwA7BX0DCVAWSEOyzqukFBKyjWsMQC5DRaVPD7vjDdbiRXt/jutUrksgGcd6bOOBn2D54crvRvLC8BthFPMy@/W47ep3W5P1TMh1gS2/AI "Python 3 – Try It Online")
## Rules
* You may assume that the input contains only the "paste" or "select" characters (you don't need to handle error cases)
* You may take your input newline separated (e.g `S\n P\n S\n`)
* You may use any kind of data representation (e.g binary data,`\n`(newline) as a select character and (space) as a paste character, etc.)
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules , shortest submission by bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ 59 bytes
Input is a list of integers, `0` for select and `1` for paste. Outputs by modifying the input list.
```
def c(o,p=[]):
for y in o*1:p=[o*1,p][y];o[len(o)/2:0]=p*y
```
[Try it online!](https://tio.run/##bZDLCsMgEEX3@QrJJhqEtlmm@A@CS5Eu8qCBolLtIl@fzhiTphBFPPO66PVzfDrbLEs/jKSjjnuhDWsLMro3mclkiatvLSTh4t7o2dydfg2WOnZp2qsRvp6XOIQYiCC6oGXJy5JxAAWkVpSAMiOmZc4rLCgl5RbmGED@kmuX/N/7xF7NhY0O96FXqfQswLOD5bODAqZAR/CnaEr6MbgEC/ExWb6C@0Q0Qk820l6ISlYsWdnjVDCJw6ZgkkBHswRLoX/D7KZKhNh1ly8 "Python 2 – Try It Online")
**Commented**:
```
def c(o, p=[]):
# o is the current output, p the current clipbord value
# Iterate over a copy of the input list
for y in o*1:
# If y==0 (select) assign a copy of o to p
p=[o*1,p][y]
# Replace the empty slice at index len(o)/2 with:
# - a copy of p if y==1 (paste)
# - an empty list otherwise
o[len(o)/2:0]=p*y
```
[Try it online!](https://tio.run/##bVLBboMwDL33Kyx2KFRMa3uclA/YLRpHhCYGZo3Ekigx7fh6loTA6FRQlGf7@dmJo0e6KHmephY7aFKVg2Zllb3uwH1PoEBYoAtCMxiDkkANpAdyrDtv0wv9qUwL17ofMOa@EZqaENQVDdTQKD2C6kKekE4EemEpcDtlYHROUIfTXDkqdDAydoTUYo8NZVBbK77kRkwBKdBriuvdSeS6Ksdqo/OOuq8bDKXxW9MIthfOrskVbfEHepSpyl7OcBN02XYAz5tiGkRo6ASpri1h9o8oo7g/FyhXzNyExZWkyqXM67Fi@jBOhJYsMCh3aZLkSZLlDhQOFTPkDvIIvZtHf@EDRcH5YkbbAf7nnFn8/l8z1mgMLGizb7hFEdpy8NHy4UfLC1Q7P11/Uj/gcOL5gj38EDKfgXtX/iJKISltGdvzfRaeReuzbBWwXRTm2TZplJjnoI3LXVSBsVV3@gU "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 80 bytes
```
f=(s,[c,...a]=(p='')+s)=>c?f(c<'S'?s.slice(0,i=s.length/2)+p+s.slice(i):p=s,a):s
```
[Try it online!](https://tio.run/##bc/dCsIgGAbg865ieKIyc9HhyHYLwncYHYhtazHm6Bvd/mor25/@oODzvuDDvAzaZ9V2@8bd8r4vFENxsUJKaa6KtYpSHiNXZ5sVzJ4o0Awl1pXN2UFUCmWdN2V3T448bmP/UvG0VSgMT7G3rkFX57J2JSsYIZxHfiRJRMhuBWAmBgAboVdCb8WsZBTbEtBLAqB1AE3Ko88KyqlwlHo5Q9X/hA/8rL/NznAcYPznN64htAcT2qR/Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/) `-pl`, ~~61~~ ~~51~~ 47 bytes
*Saved 10 bytes using* `-pl` *instead of* `-nl`.
*Saved 4 bytes using* `.chars` *instead of* `.each_char`, *thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!*
```
s=''
$_.chars{_1>?P?s=$_*1:$_.insert(~/$//2,s)}
```
[Try it online!](https://tio.run/##KypNqvz/v9hWXZ1LJV4vOSOxqLi6Jrkm2c4@wL7YViVey9AKKJ6ZV5xaVKJRp6@ir2@kU6xZ@982KTU9M09BT09PwTUiwNU5xNVFwT80JCA0hIsrmCuAKyCYKzg4IABEAKkAECsAFYIFoGwYC4nmApHYMJDEirlsU/NS/sMtBxvAFQwzCUoC1f3LLyjJzM8r/q9bkAMA "Ruby – Try It Online")
TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes.
[Answer]
# [Perl 5](https://www.perl.org/) `-nF`, 45 bytes
```
@o=@F;/S/?@,=@o:splice@o,@F/2,0,@,for@F;say@o
```
[Try it online!](https://tio.run/##DcpBCoAgEAXQC41pgZtC@it3gdAJIgwEcUTbdPmm3vrV2LIVATv4Re96BTnw3GtOZwQTvJ7IEOji9o9@PGCRPYSX6524dFGbHcxoRJXsPw "Perl 5 – Try It Online")
Could be shortened by 1 if the input is `0` and `1` instead of `S` and `P`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
Fθ≡ιS≔θω≔⪫E⮌⪪⮌θ⊘⊕Lθ⮌κωθθ
```
[Try it online!](https://tio.run/##PU1LCsIwFNz3FI@uXqBewK7cqSgEc4KQvrbBmDYfk4V49pgu7MDA/GDULL1apCllXDygYxCyjmoG1Aw@jZKBoBXtEU4h6Mmi6yCzvhlolG8T9/i6aIt3ueKDEvlAKFaj4@4c6@AsTaIBL1Z5epGNVd/ITnGu7YYO/uvnZnKlq0/fhnttYx31pQjOBS@HZH4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fθ
```
Loop over the characters of the input.
```
≡ιS
```
If the current character is an `S`, then...
```
≔θω
```
... overwrite the predefined empty string with the current output.
```
≔⪫E⮌⪪⮌θ⊘⊕Lθ⮌κωθ
```
Otherwise, insert the selection into the middle of the current output. Curiously, the best way to do this appears to be to reverse the string, split it by half its length rounded up, then reverse everything back again, finally joining the two halves together using the selection.
```
θ
```
Print the final output.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
^
¶$'¶
{`.*¶(.+¶)S
$1$1
}`(¶(.)*)((?<-2>.)*(?(2)$).*¶)P
$1$`$3
2=G`
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP47r0DYV9UPbuKoT9LQObdPQ0z60TTOYS8VQxZCrNkEDJKKppamhYW@ja2QHZGrYaxhpqmiC1GoGgJQlqBhzGdkCTfrPFcwVwBUQzBUcAEQgDGHAyODgYAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
¶$'¶
```
Insert a blank line representing the clipboard and a copy of the input which becomes the output.
```
{`
}`
```
Repeat until all of the input has been processed.
```
.*¶(.+¶)S
$1$1
```
If the next character in the input is an `S` then copy the output to the clipboard.
```
(¶(.)*)((?<-2>.)*(?(2)$).*¶)P
$1$`$3
```
But if it's a `P` then insert the clipboard into the middle of the output.
```
2=G`
```
Keep just the final output.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 119 bytes
```
O =I =INPUT
N I LEN(1) $ X REM . I :F(O)S($X)
S S =O :(N)
P O LEN(SIZE(O) / 2) $ L REM $ R =L S R :(N)
O OUTPUT =O
END
```
[Try it online!](https://tio.run/##Jc2xCgIxEIThevMUU6RIGkWxOkhnhEDcDdk7OCytxSt8f@KewpT/x3ze23N7XcYgQSo2bsvsmApq5nCK8FjR8x0HFJpuQaIGv0anpEhCU@Domtm91vLIFuCI8@7qz3l0pApF/8dCssz2Ydplvo6hrX0B "SNOBOL4 (CSNOBOL4) – Try It Online")
```
O =I =INPUT ;* Read input and set O to it as well
N I LEN(1) $ X REM . I :F(O)S($X) ;* Next character:get the first character of I and set the REMainder to I
;* if there are no characters left, goto O
;* else goto the value of X
S S =O :(N) ;* on S: set S to O and goto N
P O LEN(SIZE(O) / 2) $ L REM $ R =L S R :(N) ;* on P: get the first (left) half of O and set to L,
;* set the REMainder (right half) to R, and replace with L S R,
;* then goto N
O OUTPUT =O ;* output O
END
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 99 bytes
```
->a{s="";(o=a).chars{|n|(n==?S)?s=o:o=o.chars.each_slice((o.size*0.5).ceil).map(&:join).join(s)};o}
```
[Try it online!](https://tio.run/##RYtBDoIwFETXcoqmC9Mabdy4gXy5AkmXhJiKJXyC/YTKQoGzV5EYF/NmJpPph@szVBAOZzN64DwRBEaqsja9Hyc3CQeQapl6oJiA1kFZU9YX32JphSDl8WV3R3X63Cy2Ut1NJ7ZxQ@ikWii8nBOaQ0U9Q4aO5VzzPc8WLUFnX6z8lb9rrXkRbbrh4VmVYxFZdwtv "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vy'SQi©ëR2äRí®ýá
```
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//3Z5J1NRacKpw6tSMsOkUsOtwq7DvcOh//9TUFNQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaULkKceHJh5aOXh1UFGh5cEHV57aN3hvYcX/q@t1THUOLQy5n@0kpKOUjAQB4AwiBEcACYgJIyDoIODg5ViAQ).
**Explanation:**
```
v # Loop `y` over each character of the (implicit) input-string
y'SQi '# If the current `y` is equals to "S":
© # Store the current string in variable `®`
# (which will use the implicit input with the first occurrence of "S")
ë # Else:
R # Reverse the current string
2ä # Split it into two equal-sized parts
# (where the first part is longer for odd lengths; hence the reverse)
Rí # Reverse the pair, and each individual string back
®ý # Join it by `®`
á # And only leave the letters in the string
# (`®` is -1 by default, so this'll remove it for inputs starting with a "P")
# (after the loop, the result is output implicitly)
```
] |
[Question]
[
## using Prefixed Length Code
We are going to implement a compression of text (string, array/list of characters/bytes) by simple substitution of each character by a binary code, based on the frequency of that character in the text. The characters that occur more frequently will be replaced by shorter codes. The resulting bit array will be split on chunks with length 8.
## The code
Prefixed Length Code with length 3 is a code that consist of a prefix - 3 bits indicating the length of the field that follows, and a field. 3 bits are sufficient for 8 (2^3) different prefixes. Each prefix `n` in turn describes 2^n different fields, enumerated from 0 to 2^n-1.
`n = 0`; 1 entry (2^0)
```
000 – field with length 0;
```
`n = 1`; 2 entries (2^1)
```
001|0 (`|` is put for clarity)
001|1
```
`n = 2`; 4 entries (2^2)
```
010|00
010|01
010|10
010|11
```
…
`n = 7`; 128 entries (2^7)
```
111|0000000
111|0000001
111|0000010
…
111|1111111
```
Here’s a table of all the codes, enumerated from 0 to 254
```
┌──┬────────┬─────────┬─────────┬──────────┬──────────┬──────────┬──────────┬──────────┐
│ │0 │32 │64 │96 │128 │160 │192 │224 │
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│0 │000 │10100001 │110000001│110100001 │1110000001│1110100001│1111000001│1111100001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│1 │0010 │10100010 │110000010│110100010 │1110000010│1110100010│1111000010│1111100010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│2 │0011 │10100011 │110000011│110100011 │1110000011│1110100011│1111000011│1111100011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│3 │01000 │10100100 │110000100│110100100 │1110000100│1110100100│1111000100│1111100100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│4 │01001 │10100101 │110000101│110100101 │1110000101│1110100101│1111000101│1111100101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│5 │01010 │10100110 │110000110│110100110 │1110000110│1110100110│1111000110│1111100110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│6 │01011 │10100111 │110000111│110100111 │1110000111│1110100111│1111000111│1111100111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│7 │011000 │10101000 │110001000│110101000 │1110001000│1110101000│1111001000│1111101000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│8 │011001 │10101001 │110001001│110101001 │1110001001│1110101001│1111001001│1111101001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│9 │011010 │10101010 │110001010│110101010 │1110001010│1110101010│1111001010│1111101010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│10│011011 │10101011 │110001011│110101011 │1110001011│1110101011│1111001011│1111101011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│11│011100 │10101100 │110001100│110101100 │1110001100│1110101100│1111001100│1111101100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│12│011101 │10101101 │110001101│110101101 │1110001101│1110101101│1111001101│1111101101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│13│011110 │10101110 │110001110│110101110 │1110001110│1110101110│1111001110│1111101110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│14│011111 │10101111 │110001111│110101111 │1110001111│1110101111│1111001111│1111101111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│15│1000000 │10110000 │110010000│110110000 │1110010000│1110110000│1111010000│1111110000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│16│1000001 │10110001 │110010001│110110001 │1110010001│1110110001│1111010001│1111110001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│17│1000010 │10110010 │110010010│110110010 │1110010010│1110110010│1111010010│1111110010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│18│1000011 │10110011 │110010011│110110011 │1110010011│1110110011│1111010011│1111110011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│19│1000100 │10110100 │110010100│110110100 │1110010100│1110110100│1111010100│1111110100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│20│1000101 │10110101 │110010101│110110101 │1110010101│1110110101│1111010101│1111110101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│21│1000110 │10110110 │110010110│110110110 │1110010110│1110110110│1111010110│1111110110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│22│1000111 │10110111 │110010111│110110111 │1110010111│1110110111│1111010111│1111110111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│23│1001000 │10111000 │110011000│110111000 │1110011000│1110111000│1111011000│1111111000│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│24│1001001 │10111001 │110011001│110111001 │1110011001│1110111001│1111011001│1111111001│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│25│1001010 │10111010 │110011010│110111010 │1110011010│1110111010│1111011010│1111111010│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│26│1001011 │10111011 │110011011│110111011 │1110011011│1110111011│1111011011│1111111011│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│27│1001100 │10111100 │110011100│110111100 │1110011100│1110111100│1111011100│1111111100│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│28│1001101 │10111101 │110011101│110111101 │1110011101│1110111101│1111011101│1111111101│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│29│1001110 │10111110 │110011110│110111110 │1110011110│1110111110│1111011110│1111111110│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│30│1001111 │10111111 │110011111│110111111 │1110011111│1110111111│1111011111│1111111111│
├──┼────────┼─────────┼─────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│31│10100000│110000000│110100000│1110000000│1110100000│1111000000│1111100000│ │
└──┴────────┴─────────┴─────────┴──────────┴──────────┴──────────┴──────────┴──────────┘
```
## The process
First we need to sort all the unique characters in the text in decreasing order by their frequency.
Then we will assign each character a code – the most frequent one will get `000`, the next one - `0010` and so on.
Now it’s time to traverse the text and replace each character with its corresponding code.
At the end we split the resulting binary list to 8-bit chinks and convert them to decimal (or hexadecimal) integers. The last chunk may be shorter than 8 bits, so it should be filled to 8 bits. The fill is unimportant, so you can use whatever values you want – all 0, all 1 or any combination of 1 and 0.
In order for the compressed data to be decompressable, we need to keep track of the length of the original message, as well as the sorted list of the characters.
## The task
Write two functions (or complete programs):
* Compress, which takes a string as an input and returns the compressed data. The compressed data should include the compressed list/array of decimal or hexadecimal integers, the length of the original input and the sorted list of characters. The three can be in an arbitrary order and can be stored as a list, array, tuple or any other structure, convenient for you.
For example my test code in J returns an array of 3 boxed values :
```
compress 'Hello World'
┌──┬────────┬────────────────┐
│11│loredWH │90 0 38 20 70 18│
└──┴────────┴────────────────┘
```
\*\* Note: If you don't need the length of the original input for your decompressor, you don't need to save it/print it in you compressor.
* Decompress, which takes a compressed data and returns the string after decompression.
## Scoring and winning criteria
Your score is the sum of the lengths in bytes of your two functions. The lowest score in every language wins.
## Test cases
1.
```
compress 'Hello World'
┌──┬────────┬────────────────┐
│11│loredWH │90 0 38 20 70 18│
└──┴────────┴────────────────┘
decompress 11;'loredWH ';90 0 38 20 70 18
Hello World
```
2.
```
compress 'Code Golf Stack Exchange is a site for recreational programming competitions'
┌──┬───────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│76│ oieatrncsmgplfxkhdSGEC│142 80 208 34 147 207 136 138 75 48 68 104 12 194 75 14 32 27 65 33 163 82 3 228 176 180 50 180 37 70 76 37 224 234 201 197 165 182 205 135 3 36 219 168 81 168 201 134 128│
└──┴───────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
decompress 76;' oieatrncsmgplfxkhdSGEC'; 142 80 208 34 147 207 136 138 75 48 68 104 12 194 75 14 32 27 65 33 163 82 3 228 176 180 50 180 37 70 76 37 224 234 201 197 165 182 205 135 3 36 219 168 81 168 201 134 128
Code Golf Stack Exchange is a site for recreational programming competitions
```
3.
```
compress 'GFFEEEDDDDCCCCCBBBBBBAAAAAAA'
┌──┬───────┬────────────────────────────────────────────────┐
│28│ABCDEFG│90 148 148 165 8 66 12 204 204 136 136 136 0 0 0│
└──┴───────┴────────────────────────────────────────────────┘
decompress 28;'ABCDEFG';90 148 148 165 8 66 12 204 204 136 136 136 0 0 0
GFFEEEDDDDCCCCCBBBBBBAAAAAAA
```
## Note
The compressed data might differ between the languages due to the way sorting works on characters with equal frequency. This is not a problem, provided that your decompression code works correctly.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~94~~ ~~89~~ ~~71~~ ~~64~~ ~~63~~ 61 (29+32) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-25.5 bytes thanks to *@ovs*.
-2 bytes thanks to *@Neil*.
**Compressor:**
```
ÙΣ¢}R=āεb¦Dgb₄+¦ì}‡¤_9׫8ô¨C,
```
[Try it online](https://tio.run/##AYQAe/9vc2FiaWX//8OZzqPCon1SPcSBzrViwqZEZ2LigoQrwqbDrH3igKHCpF85w5fCqzjDtMKoQyz//0NvZGUgR29sZiBTdGFjayBFeGNoYW5nZSBpcyBhIHNpdGUgZm9yIHJlY3JlYXRpb25hbCBwcm9ncmFtbWluZyBjb21wZXRpdGlvbnM) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC5BUDuTqVLodW/j8889ziQ@uKDy2qDbI90nhua9KhZS7pSY@aWrQPLTu8pvZRw8JDS@ItD08/tNri8JZDK5x1/h/aZv/fIzUnJ18hPL8oJ4XLOT8lVcE9PydNIbgkMTlbwbUiOSMxLz1VIbNYIVGhOLMkVSEtv0ihKDW5KDWxJDM/LzFHoaAoP70oMTc3My9dITk/tyC1JBMkU8zl7ubm6urqAgTOIOAEBo4QwAXEAA).
**Decompressor:**
```
b₁b+€¦J¤Ü[D3£C3+ôć3.$1ìC<Isè?J¤F
```
First input is integer-list; second input is the string.
Stops the program with an error after it has output the correct result, [which is allowed according to the meta](https://codegolf.meta.stackexchange.com/a/4781/52210).
[Try it online](https://tio.run/##NU47DsIwDN05RQa2ViiJQ9JISAzlI1gZEQOFAhVfUQZWWLgEGwgxMHKClpNwkWK3RcrH7@Nnb@NxEIVZFnzPp8D5nl/Jo5/c0@uwBcnNByd9fy5Qq4r05Td6cfpsotrJsqFQ0mWecJlQ2mWgqDAuk2CRRkC/RkIRsGhRHC/ZrCwUgQBQkFhbwngMdlle6tQlNKeH@oz3rzRZOcYYGg0YQeEyXwLyTlPwQlOEIjvUkSoHCiI0LWopF4Mkzz3FeqMK20bjcH/YTNbxfDdbLY7t5aA79X8) or [verify all test cases](https://tio.run/##RU87TsNAEO33FJagQbHQ/rLrlZAicD6EDiEE0uIiJgYiAkYxBQ0FabgEHQhRpAQOYHOSXMTMjI2Qdmdn3pt58zYvJuksq/VwPD6u0/XyKe2sl6vy/aB8q158X5WvsepUnz/PantTVKt457SoPnrIfh1u1I/ld2/rrPbOhoEzYSAiuBoSK8PAJGyeTxcnQbbPvNCARKKllcYEhqRyAEOBrwFAY4FSmsPFNicbRkChgJC4C2s4FqYcb3kyYDgGnLPRX2awlYOMxdUKJFBckglFk7bBhUEJje2qC1C7UCBg0KhDXRCSnHoaewkL8tkkW9zfnt8Ul3cX86uHwfXRaBozj94EfYmC6dJnaQup6DYI3PMfOB0lEra7F/cHwxHzKCQtAL8).
Neither of my compressor nor decompressor uses the length.
If the length of the resulting binary-string in the compressor is divisible by 8, it adds a trailing no-op integer to the output-list. (The decompressor obviously still handles both this, and binary-strings that are not divisible by 8, correctly.)
**Explanation:**
*Compressor:*
```
Ù # Uniquify the characters of the (implicit) input-string
Σ # Sort these characters by:
¢ # Their count in the (implicit) input-string
}R # After the sort: reverse it so the order is from most to least frequent
= # Output this string with trailing newline (without popping the string)
ā # Push a list in the range [1,string-length] (without popping the string)
ε # Map each integer to:
b # Convert it to a binary-string
¦ # Remove its first digit
Dg # Create a copy, and pop and push its length
b # Convert this length to binary
# Pad it to length 3 with leading 0s by:
₄+ # Adding 1000
¦ # And then removing the first digit
ì # Prepend this in front of the binary-string we've duplicated
}‡ # After the map: transliterate all sorted unique characters with these
# strings in the (implicit) input-string
¤ # Push its last digit (without popping the string)
_ # Invert the boolean (1 becomes 0; 0 becomes 1)
9× # Repeat that 9 times as string
« # And append it to the big string
8ô # Then split it into parts of size 8
¨ # Remove the trailing part
C # Convert each part from binary to an integer
, # And pop and output it as well
```
*Decompressor:*
```
b # Convert each integer in the (implicit) input-list to a binary-string
# Pad each to length 8 with leading 0s by:
₁b # Pushing 256, and converting it to binary as well: 100000000
+ # Adding it to each binary string
€¦ # And then removing the first digit of each string
J # Join all binary-strings together to a single string
¤ # Push its last digit (without popping the string)
Ü # And right-strip all those trailing digits
[ # Loop indefinitely:
D # Duplicate the binary-string
3£ # Pop the copy, and push its first 3 digits
C # Convert that from binary to an integer
3+ # Add 3
ô # Split the binary-string into parts of that size
ć # Extract head; pop the remainder-list and first item separately
3.$ # Remove the first 3 digits of this first item
1ì # Prepend a 1
C # Convert it from binary to an integer as well
< # And decrease it by 1
I # Then push the second input-string
s # Swap so the integer is at the top of the stack
è # (0-based) index it into the input-string
? # Pop and output this character (without trailing newline)
J # And join the remainder-list back to a string
¤ # Push its first character (without popping the string),
# which will be either 0, 1, or an empty string
F # Loop that many times, which will error for the empty string to exit the
# program
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 56 + 80 = 136 bytes
[Try it online!](https://ngn.bitbucket.io/k/#eJytjz1PwzAQhvf8iqs9xPkQrpIlcgQVlLRMLAwMpYLIuYaIJK4cSzik/e+0RaAu6cSz3r3PeydVs9XYdWLYsYi7CXWnj5DQkLOQy1W8DrlwpRiCiaXR3p0kHs5siuKGutc2pdbbOwXKP4dvB8b83gvtWHxWUJOyQsQBj3hMjfdqhL/rvf2qX3NGSBrygCU08l6+Dm7nVw3kAetawbPSdUHOOuEKRnacN5gKIAQ4tPhZVy2e6+aqQFiqegNPJpcfkFn5nrclQtVBDl1lEDZKg0apMTeVavMatlqVOm+aqi1PpWiq46Qbved/Sy4/tFwssiy7PzA/cnfi9ofRAy+GvgH42qlo)
```
compress:{|(2/'8#'0N 8#,/(,/c[3],/:'c:{+!x#2}'!8)e?x;e:>#'=x;#x)}
```
* `{|(...;...;...)}` return a (reversed) three item list containing `(compressed data; sorted list of characters; length of input)`
+ `(...;...;#x)` get the length of the input string
+ `(...;e:>#'=x;...)` returns the characters in `x` sorted by their frequency (descending), storing in `e`
+ `(2/'8#'0N 8#,/(,/c[3],/:'c:{+!x#2}'!8)e?x;...;...)` compress the input
- `(,/c[3],/:'c:{+!x#2}'!8)` generate all valid (compressed) bit patterns, i.e. `(0 0 0;0 0 1 0;0 0 1 1;0 1 0 0 0;...)`. this code is also used in `decompress`.
- `(...)e?x` index into the bit patterns using the indices in `e` of each character in `x` (this ensures the most frequent characters in the input get the shortest compressed codes)
- `8#'0N 8#,/` convert the compressed input into a list of 8-length chunks, with `8#'` ensuring each chunk contains a full 8 values
- `2/'` converts each chunk of 8 bits into a decimal number
```
decompress:{*x{((*y),x(,/c[3],/:'c:{+!x#2}'!8)?d#t;(d:3+/2/3#t)_t:*|y)}[y]/("";,/+(8#2)\z)}
```
* `x{...}[y]/("";,/+(8#2)\z` set up a seeded-do-fold, run for `x` iterations (the number of characters), fixing `y` (the sorted list of characters), seeded with a two item list containing `(decompressed output;remaining compressed data)`. each iteration peels off one compressed character. confusingly, within the function, the fixed `y` becomes `x`, and the `("";...)` becomes `y`
+ `{(...;...)}` return a two item list, containing the updated `(decompressed output;remaining compressed data)`
* to calculate the remaining compressed data:
+ `t:*|y` store the remaining compressed data in `t`
+ `(d:3+/2/3#t)` determine how many bits the next character in the (compressed) input uses, storing in `d`
+ `(...)_t` drop this many "bits" from the compressed data
* to calculate the decompressed output:
+ `(...)?d#t` get the next compressed character, looking up its index in the...
+ `(,/c[3],/:'c:{+!x#2}'!8)` list of all valid compressed codes
+ `(*y),x(...)` retrieve the uncompressed character from `x`, and append it to `*y`, i.e. the `decompressed output`
* `{*...}` return just the first item, i.e. the decompressed string
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~71~~ 64 + 32 = 96 bytes
## Compressor, 64 bytes:
```
≔Eθ⟦№θιι⟧ηW⁻ηυ⊞υ⌈ιUMυ⊟ι⭆¹⟦Lθ⪫υωE⪪⭆Eθ⍘⊕⌕υλ !⭆⟦⍘⁺⁷Lλ !λ⟧Φνρ⁸⍘◨λ⁸ !
```
[Try it online!](https://tio.run/##VY9PT8MwDMXv@xRmp0QKB04gcYKJIRCVKnacerDSrLHIny5J2b59cdRJG4fEkZ/f@znaYtIR3Ty/5ExDEA2O4qhgv4lTKPVFkk/Hl5XPq5MlZ0A0FKYsrIJJSminbMWkoMEz@ckLkjzIMZvoPYa@Sm0cl3abiFN3hctQSQ9M@jJhKFYcGfEZKdT5k6xxo9iNjm7HL8u9YjZLU3wEnYw3oZhebGmhOcn2Ndyta72a9ze21vH@jwou7KuD3Z2CLblikggKkqzSk/wHbbH/psEW4RZpYXX8wXnexN7Ae3QHJqP@gbezthgGA5QBIVMxcIgJkuG9sVAM6GBMcUjoPWeDjn40haqSV/P9r/sD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔Eθ⟦№θιι⟧η
```
Pair all of the input characters with their frequency.
```
W⁻ηυ
```
Repeat until all of the pairs have been sorted and deduplicated.
```
⊞υ⌈ι
```
Push the highest (i.e. most frequent) remaining pair to the predefined empty list.
```
UMυ⊟ι
```
Drop the frequencies from the sorted, deduplicated list.
```
⭆¹⟦
```
Stringify the list of...
```
Lθ
```
... the length of the input, ...
```
⪫υω
```
... the concatenation of the characters in descending order of frequency, and:
```
Eθ⍘⊕⌕υλ !
```
For each character in the input string, find its (1-indexed, so I have to increment) popularity index, and convert it to base 2 using custom digits.
```
⭆...⭆⟦⍘⁺⁷Lλ !λ⟧Φνρ
```
For each converted character, add 7 to its length, convert that to base 2 using custom digits, and create a list of that and the converted string. Behead all of the strings and concatenate the bodies.
```
E⪪...⁸⍘◨λ⁸ !
```
Chop the string into substrings of length 8, right-pad the last one, and decode each substring as base 2 using the custom base characters (in particular, right-padding uses spaces, so this has to be the custom base character for 0).
Note that this version of the compressor resolves ties by taking the character with the highest ordinal, rather than the character with the first appearance that the previous version chose. I've updated the input to the decompressor link accordingly.
## Decompressor, 32 bytes:
```
F⮌ζF⁸⊞υ﹪÷ιX²κ²⭆θ§η⊖⍘⁺1⭆↨E³⊟υ²⊟υ²
```
[Try it online!](https://tio.run/##RU/LasMwELz3K5ZcsgIVLMmvkFPblJJDwDTHkIOxldjEsV350dCfd3fj0Bq0s6@ZHWdF6rImrabp1DjATzta11n8EQLujVhAMnQFDhJ2TT5UDW7rflOOZW6xlJA039ahlnARQoIWYv2UuLLucd8TnHdpi18SXvptndsbFhI2NnP2auve5viadnbew6QaOlyohYR/Io@RE8N3WhzmE3/FfJC@9TQdolDCEprSpr2rs@56bqvT7VLk@4/3t6WEg/LJZOwRxYslGF@C8iOuKCgTcqB@FEjwCUN6yuMlYqmVP08UoaGGJk5ItSFjKqQQU5NAa6axE8WXAu@RGNqPCHnCudYkpNmD9hTrswcWVCykPc5McJdkZ1qteE7asXokM@/@Fzo@HqfnsfoF "Charcoal – Try It Online") Link is to verbose version of code.
```
F⮌ζ
```
Loop over the bytes in reverse.
```
F⁸
```
Loop over each bit in reverse.
```
⊞υ﹪÷ιX²κ²
```
Push the bit to the predefined empty list.
```
⭆θ
```
Map over each index, join and implicitly print:
```
§η⊖⍘⁺1⭆↨E³⊟υ²⊟υ²
```
Pop 3 bits from the list, decode as base 2, pop that many bits from the list, prefix `1`, decode as base 2, index into the string (0-indexed, so I have to decrement). (I could have used `BaseString` and `StringMap` twice.)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 223 + 126 = 349 bytes
## Compressor, 223 bytes
```
s=>[s.length,a=[...new Set(s)].sort(g=(a,b)=>a?1/s.split(a).length-g(b):0),([...s].reduce((q,c)=>q<<3n+(x=(B=BigInt)(31-Math.clz32(i=a.indexOf(c)+1)))|x<<x|B(i)^1n<<x,1n)<<7n).toString(2).match(/\B.{8}/g).map(x=>+('0b'+x))]
```
[Try it online!](https://tio.run/##jZDBTgIxEIbvPkXjhWlYCgsHjdliXFxQE@WwBw@ISSndUu22S1t1VXx23EXPxu80mZlv/mSe2Cvz3Kkq9Ixdi31B956OF55oYWTYRIwuCCFGvKFcBPB4Sbx1ASQFFq0wHbPzuO@Jr7QKwPCv1ZOwwmcDHEEr@yVxYv3CBcA24o2zTZKR6UJNIaWpktcmYBjFvVsWNoTrj9EQFGVEmbWo5wVw3I0xxrs6SepdCgo/xqYpo9jgJDkxmASbB6eMhCEmJQt8A/2HlHyefvVl26iaoHEXOoNVp1tjvNxza7zVgmgr4Saf3xF/0FXxDgUcXwmtLbq3Tq@Pm9ijv7cnzc/QzOoC5YHxZ5TVfMOMFEh5xJBXQaDCOuQEd4IFZQ3TqHJWOlaWzRXEbVmJoNqJ/0fcbDrNsuyyYdKSHrj4odX33w "JavaScript (Node.js) – Try It Online")
### How?
Generating the sorted list `a[]` of unique characters:
```
a = [...new Set(s)] // get the array of unique characters
.sort(g = (a, b) => // for each pair (a, b) of characters to be sorted:
a ? // if a is defined:
1 / s.split(a).length // compute 1 / (N + 1),
// where N is the number of occurrences of a in s
- g(b) // subtract the result of a recursive call
// with a = b and b undefined
: // else:
0 // stop the recursion
) // end of sort()
```
Generating the byte stream as a single BigInt:
```
[...s].reduce((q, c) => // for each character c in s, using q as the accumulator:
q << // left-shift q by:
3n + // 3 + x positions,
(x = (B = BigInt)( // where x is the number of bits required to write ...
31 - Math.clz32( //
i = a.indexOf(c) + 1 // ... the 1-indexed position i of c in a[]
) //
)) //
| // bitwise OR with:
x << x // x, left-shifted by x positions
| // bitwise OR with:
B(i) ^ 1n << x, // i without the most significant bit
1n // start with q = 1 to preserve leading 0's
) // end of reduce()
```
Splitting the BigInt into a list of bytes:
```
(... << 7n) // left-shift the final result to add 7 trailing 0's
.toString(2) // convert to binary
.match(/\B.{8}/g) // split by groups of 8 binary digits, ignoring the 1st one
.map(x => +('0b' + x)) // convert each group back to decimal
```
## Decompressor, 126 bytes
*19 bytes saved by @Neil!*
```
(n,a,b)=>(g=s=>n--?a['0b1'+s[S](3,x=2-~('0b'+s[S](0,3)))-1]+g(s[S](x)):'')(b.map(v=>(256+v).toString(2)[S='slice'](1)).join``)
```
[Try it online!](https://tio.run/##ZZBLa4NAFIX3/RXBjTPkGubO6KgFU/ruPosuRIh5WdNEQwwhq/719IyVQin6jXKf58y2PJfd8lgfTkHTrtbXTXYVDZW0kNlUVFmXTZsguCtzXy3YH3f5rBCGLpkOvgRCQ0SRkVIGXIwr0QcuUt76vhSLyb48iDNG6ciOz3JyamenY91UQst8lvndrl6u/UKwlJNtWzfzubwu26Zrd@vJrq3ERjBT7u088lrwBtZgBN7BEay8gvJIk6LYUMIUhhQmhZQ3f@fEFnNGwxw3owQ1OA1zlqABFejAHri9G3AAj/0u8l7BDHyCZ3ABH04D64QSqLBkLZmU0pDYkmZNbELCmxDHMTG0cvgTTBW0IqKIUW2IVeQssIlATCmqle5zGhnuLbpi5G1MGh8ztOMX6@OIQqQoRU/a97g70e78WaL/Xwzacu8eJh4Gk0@DsZfeLIxBJTuZDguBzh9caRX2sLG/KPdgx/Ub "JavaScript (Node.js) – Try It Online")
### How?
Turning the byte stream into a binary string:
```
b.map(v => // for each byte v in b[]:
(256 + v) // force a leading '1'
.toString(2) // convert to binary
[S = 'slice'](1) // remove the leading '1'
).join`` // end of map(); join all strings together
```
Generating the output:
```
g = s => // s = binary string
n-- ? // decrement n; if it was not equal to 0:
a[ // pick the next character from a[]:
'0b1' + // the index of the character is 2 ** x + V - 1
s[S]( // where V is defined
3, // as the x-bit value
x = 2 -~( // whose length x (+3)
'0b' + s[S](0, 3) // is stored in the 3 leading bits
) //
) - 1 //
] + // end of character lookup
g(s[S](x)) // recursive call with all processed bits removed
: // else:
'' // stop the recursion
```
[Answer]
# [Python 3](https://docs.python.org/3/), 190 + 128 = 318 bytes
Saved a whopping ~~28~~ ~~41~~ ~~55~~ ~~57~~ 82 bytes (and got below 400!) thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
Saved 10 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
## Compressor
# [Python 3](https://docs.python.org/3/), 190 bytes
```
def c(r):j=''.join;s=j(sorted({*r},key=r.count))[::-1];i=s.index;g=j(f'{len(bin(i(c)+1)[3:]):03b}'+bin(i(c)+1)[3:]for c in r)+8*'0';return[int(g[a:a+8],2)for a in range(0,len(g),8)],len(r),s
```
[Try it online!](https://tio.run/##XVDBjtsgFDzXX/FuQOxEybpSI1xXarfZ7b2HHlwfMBCHxIHoQdRdRe6vZ8FuLzsnYIY3M@/yGg7OlvcPd6X3ICkyfqwJWR2dsZWvj9Q7DFrR2wLH4qRfa1xJd7WBsYbz5aatTO1Xxir9UvVRvSe3QVvaGUsNlSzfsKbkLePrshtJ/u557xAkGAvI8u2CrEmFOlzRNsYG2jeCi3zbFg8s6cSkE7bXdF0ki54VW9ZOR2SFn@IrKoqh8IxnoP6XSJEUX2@jf5qj0hzBKox8Bn8OZtAwz/g88K4u8@StGl4m4wrz2jd/l@mNbEiuYuouEW2latV0vM1gjgyYZUH74KEGSn7oYXDwy@GgSAHk0SkNz27Yw88g5Al2L/KQmoDxsZc3QUOKhlqiFsE4Kwa4oOtRnM/G9iDd@aKDSYxP856fnna73feIx4RvE77OICyTBy1PGqckv68Pnz5KAvFXOm7KyCevkNYwBY67ikhqSQObLhdMhePewgjLL3DDkcxEaqfoAt/JcJb5EW7/vBtf16GN3@5v "Python 3 – Try It Online")
## Decompressor
# [Python 3](https://docs.python.org/3/), 128 bytes
```
def d(a,l,s):
d=''.join(f'{d:08b}'for d in a);r=''
while len(r)<l:b=3+int(d[:3],2);r+=s[~-int('1'+d[3:b],2)];d=d[b:]
return r
```
[Try it online!](https://tio.run/##XZFBj9sgEIXP9a@YGxA7UbKutBFeKrXb7PbeQw@uDzYQh8SBCIi6q8j96yljq5edE@a9mfcNvrzHg7Pl/dNd6T0o2hZDERjPQAlCVkdnLN2Tm@LrbTeSvfOgwFhoWeWTnsGfgxk0DNpSz54G3okyNzZSVfOyKR6SKxeh/rvEO7IhuapL3qHQVEqouuNNBl7Hq7fgJwCZ5vDj/@gqiCMNzket6G3hx@Kk34VfSXe1kbGa8@WmqYwIK2OVfqv65E6wSNMlbkMlyzcsRTaMr8vEn3@4xn0k7uNZvl2QNalmmBp5@7rlbb5FWvS1k6@1vabrAiN6VmxZU8y7FyHLog4xgABKfuhhcPDL@UGRAsizUxpe3bCHn7GVJ9i9yQMOAhPS2GCiBkzwWnrdRuNsO8DFu96357OxPUh3vuhoUAk47/XlZbfbfU/1jPVtqq9zEZbJg5Yn7SeS39eHx8@SQOrC46ZMOmZF3GYCTr86FUakBkkjm74vHp8gPWYcYfkFbqiPZNZwR0UXePXBPLkmfxhTz8xRByFik5rv/wA "Python 3 – Try It Online")
Decompression uses the original string's length.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~119~~ ~~103~~ 95 (55+40) bytes
*Edit: -8 bytes thanks to Neil*
**Compressor (55 bytes):**
```
,₁¹B256ḋS+ö`R0%8_Lṁ!ṁλm+tḋ+8¹(motḋ→½ŀ`^2→))ŀ8m€₁¹
↔Ö#¹u
```
[Try it online!](https://tio.run/##yygtzv7/X@dRU@OhnU5GpmYPd3QHax/elhBkoGoR7/NwZ6MiEJ/bnatdApTRtji0UyM3H8R81Dbp0N6jDQlxRkCWpubRBovcR01rwMZwPWqbcnia8qGdpf///y/JSFUoSszMUwCi4gIQIy0xJ6dYIRfIzKlUyM9TAKkoyAFyAQ "Husk – Try It Online")
**Decompressor (40 bytes):**
```
mö!²ḋ:1↓3↑I¡λ§,↓↑+3ḋ↑3¹)Ṡ+ö`R0%8_LḋB256⁰
```
[Try it online!](https://tio.run/##yygtzv7/P/fwNsVDmx7u6LYyfNQ22fhR20TPQwvP7T60XAfIBfK0jYFyQNr40E7NhzsXaB/elhBkoGoR7wMUdjIyNXvUuOH///9KCnmZiTkFxakZJfmVuWlFSv@jDQ1MdQxNDXSMdYyMjXSADDMdM6CIAYQyMdExNDLUsdQxBzIsgQJmFiA15kCWkaWOobmFjqExSMDQ0kjHAoiALAODWAA "Husk – Try It Online")
**How does it work?**
**Compressor:**
1. Sort letters by frequency (helper function `₁`):
```
↔Ö#¹u
```
2. Substitute letters by their rank by frequency:
```
m€₁
```
3. Genrate prefix-length-code:
```
ṁ ŀ8 # for each integer x from 0 to 7
λm+ # join
tḋ+8¹ # zero-padded binary digits of x to
(motḋ→½ŀ`^2→)) # zero-padded binary digits of 1..x
```
4. Look-up each prefix-length-code from each letter rank:
```
ṁ!
```
5. Pad end with digits to multiple-of-8:
```
S+ö`R0%8_L
```
6. Convert from binary to base-256:
```
B256ḋ
```
7. And finally pair with letters sorted by frequency:
```
,₁¹
```
**Decompressor:**
1. Convert first argument from base-256 to binary digits:
```
ḋB256⁰
```
2. Pad start with digits up to multiple-of-8:
```
Ṡ+ö`R0%8_L
```
3. Sequentially get prefix-length-codes:
```
¡λ ) # apply function repeatedly:
3ḋ↑3¹ # remove first 3 digits & convert to number
§,↓↑+ # split remaining list at this position
# (this keeps going forever, so the list ends-up
# with a lot of empty elements)
↑I # finally, just keep the truthy prefixes
```
4. Convert to each element to a number:
```
↓3 # discard the first 3 digits
:1 # and add a '1' at the start
# (equivalent to converting the 3 digits
# to a value from binary and adding it: Thanks Neil! )
ḋ # and convert it all to a value from binary
```
5. Look up the letter from second argument:
```
mö!²
```
[Answer]
# [J](http://jsoftware.com/), 70 + 95 = 165 bytes
Encoder returns `length;table;bytes` just as in the description. The fill for the last chunk is the last generated bit.
```
#;[(];[:#.@($~8,~#>.@%8:)@;(~.(128#3+i.8)<@$"0 1#:i.4^5){~i.~)~.\:#/.
```
Decoder using the exact same format for the input:
```
>@{.$>@{~&1({~(~.(128#3+i.8)<@$"0 1#:i.4^5)i.l<@{.])"1[:(}.~l=:3+3#.@{.])^:(<_)128,@}.@#:@,>@{:
```
[Try it online!](https://tio.run/##fY9fT8IwFMXf9yluVnRtmJWJJkv5kyoMfPBJH3yYYOYoUB0r6fagIfSrz3b6iJ6kzc3p7557@96IMq9gxKAH7lxQmDw@zDw0SPFikDJEOe6YODRoTPlZzAgfYENxdBWjflfSmAx5x@9BhJik18sbcjCSGmLoC0OX1HjEW4lT8WN@oB17mfMIH8y/iZIWQ0sviB@lDB@pKUas3@3bxZy5ZHj4SmxzyI@UI8ZDm8rsXE/kWwVBUuZqJTS8fdWiYhCE4DNA4D79S0zFScLt7fkUAouOmHXbFmfYl9ZwRNO0IbYEnLqSOA6Ce1EUCp6VLlaBdxqZ2KkwV8Uanuos/4DkM99m5UaArCCDStYC1kqDFrkWWS1VmRWw12qjs91OlhvI1W4vauleqr9mzGezJEmmVhOnu1a3Pwqabw "J – Try It Online")
### How it roughly works
Code table that is used in both:
* `#:i.4^5` 0…1024 in binary.
* `128#3+i.8` repeat every number in 3…11 for 128 times
* `<@$"0` for 0…127 take the first 3 digits, for 128…255 take the first 4 digits, …
* `~.` take the unique elements of the result.
Encoder:
* `~.\:#/.` sort the unique characters in the input based on occurrences. That is the character table.
* `(table){~i.~` map input to character table positions and get the corresponding code.
* `($~8,~#>.@%8:)@;` concatenate all the codes together and split them into chunks of 8.
* `#;…];#.@` convert back to integers and prepend the character table and the length.
Decoder:
* `128,@}.@#:@,>@{` take bytes and convert them back to bits. Have to prepend 128 temporarily to pad the results to 8 bits.
* `[:(}.~l=:3+3#.@{.])^:(<_)` parse the first 3 bits `n`, and remove them and the next `n` bits from the bit array. Do this until the bit array is empty. Return all intermediate results (so starting positions for the codes).
* `(table)i.l<@{.]` again, parse the starting bits and look them up in the code table.
* `>@{~&1({~` and look the index up in the character table.
* `>@{.$` trim the output down to the length of the string.
[Answer]
# [Perl 5](https://www.perl.org/), 354 bytes
```
@c=map{$c=$_;map{sprintf"%0*b%0*b",$c?3:2,$c,$c,$_}0..2**$c-1}0..7;
sub c{$_=pop;my%f;$f{$_}++for/./g;my%c;@c{@f=sort{$f{$b}<=>$f{$a}}keys%f}=@c;y///c,join('',@f),map oct(substr"0b$_".'0'x7,0,10),join('',@c{/./g})=~/.{1,8}/g}
sub d{($l,$f,@i)=@_;@d{@c}=0..255;join'',map$f=~/^.{$d{$_}}(.)/,(join('',map sprintf('%08b',$_),@i)=~/@{[join'|',@c]}/g)[0..$l-1]}
```
[Try it online!](https://tio.run/##bVFdb9wgEHzvr1i5nGxfiL@qU6JSWqSqSt770Ic0tWwMFye2scCVciLkr1/A1yhqVQnEMrs7Myyz0MPu@N78boEDV@OshTHCYAhIB514w46M07GZLeIU1SREZtb9tMhoU2zbsCOM@JcPHyt/rKt2RZZV2y3i52UIL8iqY1FNZzWT8bCRBEl/dWdnUuk8y/cB5IRxyyQ1Si825Fv3iX4OQePcgziYjXSUcXLI85zje9VPSRxjJlPsTYHiS@JlzKKjokV1lMVF/HiBC1wW6Vsxt0HNpfQ5z2yJL52/rE@2CRowkpj1KWU1YZ1l3NHwjt2OhHbf7WWQ9J2/Mou6YN8lWZrj5JU92PgzmyTeFJdt7GeRrpTPObM3K81TcHHrddMbz46G8/LW@RGXQIEn8bUYBgU/lB66OCXvGK9O@FfVCbhSg4TvS8Mf4Nsjv2umvYDeQAOmXwT4SYIWXItm6dXUDDBrtdfNOPbTfv1isfQhYwLx6hJOxldHZZpFP6foP5nq70yXnIqf/sGqV@z4Ag "Perl 5 – Try It Online")
Run this to compress with function c() and decompress with d().
```
my @c1 = c('Hello World');
my @c2 = c('Code Golf Stack Exchange is a site for recreational programming competitions');
print join('|',@c1)."\n";
print join('|',@c2)."\n";
print "Bytes in 1st compression: ".(@c1-2)."\n";
print "Bytes in 2nd compression: ".(@c2-2)."\n";
print d(@c1)."|\n";
print d(@c2)."|\n";
```
Output:
```
11|loredWH |90|0|38|20|70|18
76| oieatrncsmgplfxkhdSGEC|142|80|208|34|147|207|136|138|75|48|68|104|12|194|75|14|32|27|65|33|163|82|3|228|176|180|50|180|37|70|76|37|224|234|201|197|165|182|205|135|3|36|219|168|81|168|201|134|128
Bytes in 1st compression: 6
Bytes in 2nd compression: 49
Hello World|
Code Golf Stack Exchange is a site for recreational programming competitions|
```
[Answer]
# [Julia](http://julialang.org/), 331 bytes
```
p(s)=Meta.parse("0b"*s)
s(n,p)=last(bitstring(n),p)
b(i,n=0,B=2^n)=2B<=i ? b(i,n+1) : s(n,3)s(i-B,n)
c(s,u=sort(unique(s),by=x->count(==(x),s),rev=0<1))=join(u),p.(i.match for i=eachmatch(r".{8}",join(b.(findlast(==(i),u) for i=s))*'1'^7))
d(u,N,s=join(s.(N,8)),n=p(s[1:3]))=u[n<1||2^n+p(s[4:3+n])]*try d(u,0,s[4+n:end])catch;""end
```
[Try it online!](https://tio.run/##dVHBbhMxEL3vV4x8qSdxVtkEiSrERaSkLYf2woFDtJWcXSdx2bUX2wuJKF9RiRNfx4@E2Q0VQoI5eZ7fzJuZ99BWRmX747HhAeWtjiptlA@as/GaDQImgVvRoKxUiHxtYoje2C23SGCy5kZYORYLObm3KCeLuTTwGnp4mCHMoKueYuBmtBAWk4IH0crgfOStNZ9aTaJifZD70UXhWhu5lHyPgkCvP8vxPEOUD85Y3pJeyk1aq1jsYOM8GKlVsetz7ln69fwbEz11nfKNsWU/MLUzKFr8XREQB2fZ2f1LxKTkrbgT4dQ@pPxOnCPSNnSHVTab5qTcruw8e3yk3YYd@mI2Hdoc80H0B@jKx4LAoZ1pW@ZYdJO8YoySY9QhBpCwSoCC3eiqcvDB@apk4gRdX10tl8u3FJddLPp4c4pnzjsIjbYRvqgDRAd1S5tHU2twFuLOhDRNn6mXrtRw7aoNvI@q@AjLfbFTdqvBBFAQTNT9BbwuvFbROKsqaLzbelXXZCcUrm50NN1PoJ550rEjGBLqVulFGjI@Vpbzkhc8IqmjlJHsZj9/PAEjs@nxHRgKiPhXBeuS0QUwAV3lKsv/@9@70ZMmuWDU7B9M2TP/TIFJd/Nf "Julia 1.0 – Try It Online")
I don't want to separate compression and decompression because I use the functions `p` and `s` for both.
`c` is for compression, returns the sorted letters and the compressed string (missing bits are filled with 1s)
`d`is for decompression, doesn't need the length of the original string (it discards the last invalid caracter)
] |
[Question]
[
This is an answer-chaining challenge relating to the OEIS.
Oh, the justification for this is because a company needs one program to print out their OEIS sequences real bad and they have every language.
The answer-chaining format works in the following way:
Someone posts the first answer, from which all further solutions stem. This answer is a program that, given a number N, inputs the Nth number in OEIS sequence of whatever index they choose (we'll call it sequence 1), in whatever language they choose (language 1)
Someone else comes along and chooses their own sequence (that has to be different from the previous, and from all previous sequences). They make a program, in another language (which has to be different from all previous languages), that given a number N in the language 1 outputs the Nth number of sequence 1 and, given a number in language 2 outputs the Nth number of sequence 2.
This process continues ad infinitum.
The nth term of a sequence is the term that comes n times after the first, working from the first item. Here we use 0 and 1-indexing, to be easy on the coders!
No language or sequence reusing.
Input must be an integer or a string representation of an integer and output must be the correct value of the sequence. Error handling (non-int input) is not needed.
You must not post twice in a row.
You must wait an hour or more before posting again.
Whoever is the SECOND-to-last to post after a week of no answers (the person who didn't break the chain) wins, though the contest can continue indefinitely. If you're last and can show that you can add one more language to it, you continue the challenge until the next winner.
You can assume that the input or the output won't be outside the numerical range of your language (for example, assuming that IEEE's limit won't be surpassed by any sequence) but don't be a trickster and abuse this by using a language that only has 1.
Any sequence can be chosen, as long as it hasn't been used before.
The input cannot be out-of-bounds for the sequence you are using.
Two different language versions are different languages (Python 2 and Python 3 are considered different langs of their own). This isn't rigid, but as a rule of thumb, if it's separated from another version of the same language on TIO, it's different.
This isn't banned, but try once not to use the formula the OEIS gives.
If your resulting code is over 65536 characters long, provide a link to access it (e. g. Pastebin).
That's it and that's all. Ready? Set? FUN!
Yes, this IS "One OEIS after another" but put on multiplayer. I thought it'd be cool.
[Answer]
# 4. [Jelly](https://github.com/DennisMitchell/jelly), [A000312](http://oeis.org/A000312)
```
n=>40-n//
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
```
[C# (Visual C# Interactive Compiler)](https://tio.run/##RY69CsMwDIR3P0XGOI4rF7pZFp06de9gPJkYtLglP8/vqklpD6QP3QmhvNi8cLttNSPXdZSiEloNdHG2AiiASNEmjGTQpjGRMFqKH4pBEQ39gIiyINEu8b7ao@MCmZPqDgHw6/oflIdhgOZVec69/NFxcJ7x7KQbo9Vj5nW6c5360rPWvr0B "C# (Visual C# Interactive Compiler) – Try It Online")
[brainfuck](https://tio.run/##RYxBCoAwDATvfYVna41g9GIM/iP0oIIgQhHB99dYRecyZHfJdIxrWM55izH0jJULAAZAWJwnYUvOF57V4lhua8BClj8RkQ60Smj2kqrnA9vSZA8A6z78h@kgzyFGrBtsES8 "brainfuck – Try It Online")
[Runic Enchantments](https://tio.run/##RYyxDoAgDER3vsIZrOfAZm38j4bJiYUYE78fKxh9y0vvLj2vkvdayypxpgI4QEUpsUpgSmMSs5LoYwtEOcgnZraBVQ3LXlrVP0iY3NAB8rH9h1vgPWqNNw "Runic Enchantments – Try It Online")
[Jelly](https://tio.run/##RYwxCoAwDEX3nsK5NUZBcDAG7xE6OiiluHr6GFvRtzzy/yfHltKlmhcee8iIDlFYIJJwIIhtZLMAy2MLWCjwJyKygVUFy15KVT9w6FxTQdzP9T/cjN6jqg7TDQ "Jelly – Try It Online")
Explanation:
We only account for the last line, all of the other lines are ignored.
```
;/**/ Argument: z
;/ Reduce z by ; (concatenation) [1]
z is an integer, so this just returns z itself.
*/ Reduce z by * (exponentiation) [2]
Again, this returns z itself.
* Exponentiation: return [1] ** [2]
This resolves to (z ** z).
```
To make C# ignore the code, we're trying to put it in a comment. However, a line starting with `/` isn't valid in Jelly, because `/` needs an operand. The operand we're using here is `;`, since that also fits perfectly as a semicolon in C#. In fact, the semicolon and empty multi-line comment together make a link that calculates \$^2z=z^z\$. Note that the function submission in C# is still valid, as there's no general consensus disallowing multiple statements in an anonymous function submission (e.g. imports).
[Answer]
# 16. [Java 8](https://docs.oracle.com/javase/8/docs/), [A000290](http://oeis.org/A000290)
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC//*/0e#'
/*
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
***Never thought I'd see the day where I would be able to add a Java answer as 16th answer in a polyglot-chain! :D***
[1. Try it in C#:](https://tio.run/##fVJNT8JAED13f8WmHFha6ixEL7RdbDAYCNHESBqtHLSBsJdV@ZDC//DI2YsH/xfxN@BsF/kI0dedmbfvzU6bTdOxl47lujlVaSDVpIwhBuEagL9SSi@zrC01hsP7rsHVXZSlGk@NzkUnmy9y9RZJu9G5NrvuzWK@yPJlWrH3sgHgAO8XigQci6y@3lcfy@/lp2XheyyLF4jvgEWoBfAw5ZxHOlebeY6ICoXRqxtdeQLnOGDbrgpDnetnUBXVeqV2yj3tqJpyFECUPkZpFLUYY5WSWZg0YTk1253BjLvZ77zDDtO0P2x7hG35/oRD8/chAIlIvF6QCDfweuWewJp4ItEVBZEErtiWIAiwAa0cqG2QW2aCcE9mb/FsFmNoxMjiGaF/AkC@nP/rE1/fJn5pi1c8hw6REYqabRdtExvklOpS3FOKhhxJR8cdWPtk8Dxi@AtSGXJfBhWO2XVLJB7JSb8jVZ8NmCyV/PUP) \$a(n)=40-n\$
[2. Try it in brainfuck:](https://tio.run/##fVBNT8JAED3v/opNObS21llq8QBlcYOBQIgmRtJo5QCNBmLSqAm28D88cvbiwf9F/A11tlv5CNHX3Zk3783Objp5Hc@Sx3n8lOcA/IUx1s2y/kxhOr0balzeyixWmLQHF4NssSzUGyT99uBKV8Pr5WKZFUu3Ym@3DWADf6iYFGxC11/v64/V9@qTELyHEF6hDRsIZQTgfs45lyp6nSJKmjSF1r1ST1yBc2wwDCdpNlVs1cATXqta97mrnKSe2AmAjMcylrJnWVb1SC8MilgF1eXWsLRb1ltvv0M37Q7bHLE2fHfCvvn7UYBIRO4oiIQTuKPjkcAcuSJSGQURBY7YpCAIsAGtAqiVKCw9QTgn6VuYpiFuhRBZmFL2JwBmz@f/@rSh/ia@tMerrs2myChDzTBMQ@8SBWUqmTuKqcmBdHDchjz3T2v@me//AA) \$a(n)=1+n\text{ mod }2\$
[3. Try it in Runic Enchantments:](https://tio.run/##fVDLTsMwEDzbX2GlhwSHsG5ULm3qYhVRtYpAQlQRhB4gQmovFiCVpP0Pjj1z4cB/VXxDWMehD1UwsXdnZ9ZrK69zPcvKEkC8MMYGRTGaGUynd2OLy1tVZAaP/fg8LhbLSr1BMurHV7YaXy8Xy6JathV7B30ADuKp4VLghK6/3tcfq@/VJyF4DyGiQTscCGUE4H4uhFAmhhdVVFR3pdXDWteBxDkcHMfX3a6JvVMIZdhrtlsiMI5ua64BVPagMqWGnuc1j@zCYIhXUVtuDc@6db319jts0@6wzRFvw3cn7Ju/HwVIZRpMolT6UTA5nkjMaSBTk1GQaeTLTYqiCBvQqoBajcqyE6R/kr8leZ7gNkiQJTllfwJg9nz2r0875m/iS4eiGXA2RUYZao7jOnbXqCgzyd1RXEsOpIPjHMqy9QM) \$a(n)=4^n\$
[4. Try it in Jelly:](https://tio.run/##fVBNS8NAED3v/oolPSRujLMJitCmW5eKpaUoiCVo7EFLoZUS9KBJ@z889uzFg/@r@Bvi7G7sB0VfdmfevDc7u@RpPJvNyxJAvDDGOkXRm2pMJncDi8tbVYw0Htv9834xXxj1Bkmv3b@y1eB6MV8UZtlW7O20ATiIcc2lwAldfb2vPpbfy09C8B5CRI02OBDKCMD9qxBC6RhdmKho1pRWjyo9CyTO4eA4ftZs6tg6gUhGrbB@LALtZPWMZwBq9KBGSnU9zwsP7MKgiWeoLTeGZ92q3ni7HbZpe9j6iLfm2xN2zd@PAqQyDYZxKv04GB4OJeY0kKnOKMg09uU6xXGMDWgZoFbBWHaC9I/ytyTPE9waCbIkp@xPAEyfz/71aUP/TXxpV4QBZxNklKHmOK5jdwVDmU7uluJasiftHedQlmV4@gM) \$a(n)=n^n\$
**Explanation:**
Let me start by saying that although I've heard from each of these languages before here on CGCC, I'm only skilled with Java, C#, 05AB1E, and Whitespace, and apart from that can read the JavaScript part of the code. The other languages are mostly unfamiliar for me, so I hoped after the changes I had in mind to make the Java interact with C#/JavaScript, most other languages would still work.
The first main thing to tackle was Java's `n->` vs C#/JavaScript's `n=>`. Java support unicode values as part of the code, so using the following:
```
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
```
Will be interpret as this in C#/JavaScript:
```
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
```
But as this in Java:
```
//
/*
n=>//*/n->
```
This is because `\u000A` is a line-break, `\u002F` is `/` and `\u002A` is `*` in Java.
Then to differentiate the sequence between Java vs C#/JavaScript I added the following:
```
""+n==""+n?...:n*n
```
where `...` is the existing `5/2>2?1:40-n`, and `n*n` is the Java part of the code for oeis sequence [A000290](http://oeis.org/A000290) (squares a.k.a. \$a(n)=n^2\$).
Why does this work? In Java Strings are Objects, where `==` is used to check if references of objects are pointing to the same place (or to check if primitives are equal), and the actual `Object.equals(Object)` has to be used to check if the values of these Objects are the same. So `""+n==""+n` will be falsey in Java, but truthy in C#/JavaScript.
---
After that was tackled (by re-using the existing newlines to not break the Whitespace program), some things had to be fixed. Four of the existing programs were failing now: Runic Enchantments, Jelly, Unreadable, and Commentator.
The fix for Unreadable was easy. We added four `""""` before the first `'`, so we simply put the `'` somewhere earlier (I placed it at the end of the first line), and remove the leading `'""""` from the Unreadable part of the code at the bottom.
After that came Jelly, which was giving an `IndexError: pop from empty list`. I'm not too skilled in Jelly, so I don't exactly know why it gave this error. If I remember correctly the last line will be the main-link of a Jelly program, and because the code in that last line doesn't use any of the other links, everything else should be ignored. But somehow the part `""+n==""+n` still gave some issues. I was able to fix this by adding `/**/` in front of that line.
As for Runic Enchantments, it didn't output anything anymore. *@Draco18s* pointed out to me that Runic Enchantments starts at all `>` simultaneously, but only the `>2?1:40-n/` and `/ip@` were relevant. This was a huge help to understand the flow of the Runic Enchantments program, and I was able to fix the path by adding a `/**/` at `>2?1:40-/**/n:n*n`, and changing the positions of the `//ip@`, `//`, and space on the last line.
All that's left was Commentator. At that point I realized that my previous fixes of adding `/**/` weren't such a good idea after all, since it would output a bunch of additional rubbish due to the builtins `/*` (convert active to unicode character and output) and `*/` (output active as number).. >.> After a bit of fiddling around and trying some things, the fix turned out to be very easy: I've added an `e` before the `#` on the first line. `e#` is the builtin to negate an active, fixing the issues caused by the code I added (apparently).
[Answer]
# 15. [Commentator](https://github.com/cairdcoinheringaahing/Commentator), [A020739](https://oeis.org/A020739)
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC//*/0#
/*
박망희 0#
;*/
n=>5/2>2?1:40-n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##ZU7LToNAFF3PfMVEF@AgXiC6sThKMGnaEE2MDVHCohITuihV0wjtf7js2o0L/6vxG/DODKWQnnncc885cyFbzOevxXK6XHzUNYDzzhgbVtV4JpHnzxONu6egyiRewug2qlZrpT4iGYfRve4mD@vVulJbRzE7DAE4OMcUOKHb36/t9@Zv80MIfoUQlAccCGWE0uJKXIAnvGv38tyxC4AgmwZZEIxM03RP9MZLElNR3e4NU7tNv/f6CR3qDmufmC3vTuibu0UBEpHYqZ8Iy7fT01RgTWyRyIqCSHxLtMX3fQygpYBaA2XpCcI6Kz/jsozxSMTI4pKyPgBmbzeHIh0A54D/NHJcm7McGWWoGUcKsrCG73p1Gx3B0ORA6lEJDnVde/8 "Commentator – Try It Online")
[C#](https://tio.run/##ZVI9T8MwEJ3tX2HBUMdpuKSChbiGqAjUKgIJUUUQdYCoVb0EaAtJ@z8YO7Mw8L8qfkO4xP2K@mzfvXvvfMngZOokU11cf6SJ1OmsiUeN2gWA@84Yu8nzni4xHj/1DW4fgzwp8dIJr8J8vqjUByS9Tnhnqv79Yr7Iq21asfemAyDAPaYgCF39fq2@l3/LH0LwK4Sg7AsglBFK07Y6g5ZqXXjnp66TAgTJc5AEQZdz7llmYygJr6gpdwY37rreefUO07Q/bHuFb/n@hLq5WRQgVrEzkLGypTNoDhTm2FFxmVFQsbTVNkkpsQGtCqitUVlmgrJPss8oyyI8JSJkUUZZHQD67fJQpD4IAfhPXddzBBsjowy1xlGFMrE139RVbOwJDUMOpBotIaDw6eh1wvHNMN12fS09F6NtWzSa6Nkw1OmQj7i2LL/4Bw)
[Brainfuck](https://tio.run/##ZU7LToNAFF3PfMVEF@AgXqjUhcVRgknThmhibIgSFi2JaWNC1ESh/Q@XXXfjwv9q/Aa8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adable](https://tio.run/##ZU7LToNAFF3PfMVEF@AgXlrtxuIowaRpQzQxNkQJC4pN2sQQNVEo/@Gy625c@F@N34B3ZiiF9MzjnnvOmQuf2cc8eUlmr/OqAnDeGWOjopgsJRaL56nG3ZNXpBIzP7gNilWp1EckEz@41930oVyVhdo6itmRD8DBOabACd3@fm8367/1DyH4FUJQHnIglBFKsysxgL7oX/cuLxw7A/DSxEs9b2yaZu9Eb7wkMRXV7d4wtVv3e6@b0KH2sOaJ2fD2hK65WxQgEpEdu5GwXDs@jQXWyBaRrCiIyLVEU1zXxQBaCqjVUJaeIKyz/CvM8xCPRIgszCnrAmD5dnMo0iFwDvhPY6dnc7ZARhlqxpGCLKzmu17dRkswNDmQOlSCQ1UNzv8B)
[Grass](https://tio.run/##ZU7LToNAFF3PfMVEF@AgXsC6sThKMGnaEE2MDdEJi8pCumnUJkL7Hy67duPC/2r8BrwzQymkZx733HPOXHj9mC2XdQ3gvTPGRlU1mSsUxfPU4O4pqnKFlzi5TarVWquPSCZxcm@66cN6ta70NlHMjmIADt4xBU7o9vdr@7352/wQgl8hBOUhB0IZoXRxJS4gEMG1fznw3AVAlM@iPIrGtm37J2bjpYitqWn3hm3cpt97/YQJdYe1T@yWdyf0zd2iAFJINwulcEI3O80EVukKqSoKQoaOaEsYhhhASwO1BtoyE4RzVn6mZZniUUiRpSVlfQDM324ORToEzgH/aez5LmcFMspQs440VGEN3/X6tjqCZciB1KMKHOr6PBj8Aw)
[Width](https://tio.run/##ZU7LToNAFF3PfMVEF4yDeKGxG4ujBJOmDdHE2BCdsFBcwKbRxAjtf7js2o0L/6vxG/DODKWQnnncc885c6EqXz@KpgHw3xlj07qelxpF8bSwuH2M6lzjJU5uknq1NuoDknmc3Nlucb9erWuzbRSz0xhAgH9MQRC6/f3afm/@Nj@E4FcIQXkigFBGKF1eyjGM5OgquDj3vSVAlD9HeRTNOOfBid14acINte3e4NZt@703TNhQf1j3hHe8P2Fo7hYFUFJ5WaikG3rZaSaxKk8qXVGQKnRlV8IwxABaBqi1MJadIN2z6jOtqhSPRoosrSgbAqB8uz4U6QSEAPynmR94ghXIKEPNOTLQhbV815vb6QmOJQfSgGoIaJrxPw)
[AlphaBeta](https://tio.run/##ZU7LSsNAFF3PfMWgi8SJ8U6KbmwcDRFKS1AQS9CQRRqEFKRUEJP2P1x27cZF/6v4DfHOTJom9MzjnnvOmZtk78sim719ZnUNID4YY6OqmswViuJ1avDwElS5wiyM7qNqtdbqM5JJGD2abvq0Xq0rvU0Us6MQgIM4pcAJ3W2/dz@bv80vIfgVQlAeciCUEUoXN/IKBnJw611fCncBEORZkAfB2LZt78xsvBSxNTXtwbCN2/QHr58woe6w9ond8u6EvrlfFCCRiZv6iXR8Nz1PJdbElYmqKMjEd2RbfN/HAFoaqDXQlpkgnYvyKy7LGI9CjCwuKesDYL68OxbpEDgH/Kex8FzOCmSUoWadaKjCGr7v9W11BMuQI6lHFTjUtSeE@Ac)
[Aheui](https://tio.run/##ZU7LToNAFF3PfMVEF4yDeKGxG4ujBJOmDdHE2BAlLCoxgU2jC4XyHy67duPC/2r6DXhnhlJIzzzuueecubDM3z6LpgFwPxhj06qaFwp5/rIwuH8OqkzhNYzuompda/UJyTyMHky3eKzXdaW3iWJ2GgIIcE8pCEK3f9/bn81u80sIfoUQlCcCCGWE0tW1HMNIjm68q0vXWQEE2TLIgmDGOffOzMZLEa6paQ8GN27bH7xhwoT6w7onvOP9CUNzvyhAIhMn9RNp@056nkqsiSMTVVGQiW/Lrvi@jwG0NFBroS0zQdoX5VdcljEehRhZXFI2BEDxfnss0gkIAfhPM9dzBMuRUYaadaKhCmv5vte31RMsQ46kAVUQ0DTjfw) (All 2s)
I had a few plans with Commentator, but only one survived contact with all the other languages. One caused errors in the Jelly (iirc) and I wasn't able to resolve it because I don't know why Jelly interpreted the bytes the way it did.
[Answer]
# 6. [JavaScript (Node.js)](https://nodejs.org), [A000012](https://oeis.org/A000012)
```
//
n=>5/2>2?1:40-n//
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/**/
```
[C# (A022996)](https://tio.run/##ZY5BC8IwDIXv/RU9butquqEXm0VPguDdQ9lpbJhLlW3@/ppNEcQHyQtfQnjdZLuJ0@kZO@Q4l1I0NAlAxYZ2UFN9qPZbZ6MQgEDBthjIoG3LlsSDpbC4AApo6GuIKAeyWiXso3X1/kBmo/SvAPhx/IfKQ1EsAc6usoW@yaT0ypJXw33MJLbmxnnGykk3JlfXkef@wrHPhozz3KcX "C# (Visual C# Interactive Compiler) – Try It Online"): Since `5/2==2` the function returns `40-n` (Line 2)
[BF (A000034)](https://tio.run/##ZY7BCsIwDIbvfYqeW2O2mXnQGL36DKEHFcQxKCLs@busiiD@ly98fwi5vi5Dvk@3sRRElw/SYyfdsd1RA9kMoopCYpXIkFZJjAqiC02IcpQvmNkWrKox90mt3hckrp3/DeLwPP1Lt8cQlgfOTQvBP2xyvrpSaNPTlmgG "brainfuck – Try It Online"): The added part only pushes the whole tape one cell to the right, others unchanged (Line 2-3)
[Runic (A000302)](https://tio.run/##ZY4xDoMwDEX3nCJzgmtAsFD3tytnsDJ1gSVCSJw/NWlVqepfnvW@ZXk/8voshdnlG0bu0d@7aWgpm2FWKCVRRKHUJBiVoCdNQCXiCxGxBatqzH1Sq/cFxIvzv2Fet8e/dFcO4XxgbjsKfrHJ@epKGV4 "Runic Enchantments – Try It Online"): The `?` after `2` skips the `1:`, and other operations follows from `4` (Line 2)
[Jelly (A000312)](https://tio.run/##ZY5BCsJADEX3c4pZzxjTKYqg8detZwizFFRKcdvTx3Qsgvg3L7wfQp63cZzNmMN0xp579EM57jqa3DArlKooslDdVDiVoAtdQCXjCxHxBa9a3K1p1ecC8jbE3zA/Xpd/GU6c0vLAtSuU4t2nEJszs3J4Aw "Jelly – Try It Online"): Unchanged last line
[Gol><> (A001489)](https://tio.run/##ZY5BCsJADEX3c4pZzzSmUxTBxq/bniHMVluQWuj9GdNRBPFvXng/hNyfj9u0jqUwu/mMA3foLum0b2k2w6xQyqKIQrnJMCpBN5qASsQXImILVtWY@6RW7wuIO@d/wzwt13/peg5he2BoEwU/2uR8daWk4ws "Gol><> – Try It Online"): Unchanged first column
[JS(ES6) (A000012)](https://tio.run/##ZY7BDoIwEETv/QqOQC1biF7ssnr1GxoOBEVrSEvA@Pt1QWNinMPO5s1msvf22c7d5MaH8uF8iX0dAYSvaQcVVYdyv9XKMwGwZFWDliSqZtMQu1VkF2dAFiV9DRH5gKNVzD5ao3cDyUIkvwJw4/EfCgN5vjxw0qXKkxtvIllZNKIPU@pqbRyWmqeUmeiCn8NwKYZwTfvUZZmJLw "JavaScript (Node.js) – Try It Online"): Since `5/2>2` the function returns `1` (Line 2)
Sneaked the ternary `5/2>2?1:40-n` into the C# part. In C# since `5/2==2` the function returns `40-n`, while in JS `5/2>2` the functions returns 1. The C-style comments made it nearly impossible to add more practical languages (specifically C and Python). More spaces are added on lines 4-5 to ensure that the Runic part works.
[Answer]
# 8. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), [A010701](http://oeis.org/A010701)
```
//
n=>5/2>2?1:40-n//(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/**/
```
[Try it online!](https://tio.run/##ZU7BDoIwDD2vX9HjBGeB4EVn9eo3LByMIYELIdHEz59lwwGxW/pe3@te9un6d/saH8/WeyJEBAVKCSpBQAUwXPhIFVfX8lQXZiDSWpe7eKVNRAcax8XQ0Z3nxdtuxKV1WHqiE18nbM3fASLHzjTWcW5Ns29Y0Bl2E4rAzuacwForC2KFEm2uYMUEzg@A2yLqx9u/CGfKMpIP3IvSZNgJAwya9/UX "Whitespace – Try It Online")
[C#](https://tio.run/##ZVCxjsIwDJ3jr8joNs25RcdCUx8TEtLtN0SdKiqy5E5Qvr@4DRSqcxK/5/ccK0p3td01jIdb7FyIQyGH@2Yk0lqDAqUElSBoBRAb3tKGN1/V7rO0kQgRqyxtSRPBmabyZWByH/XLW3ekpvdhyxVc@PuEtflcQOTZ29Z5Ns62RcuC3rKfUAT2zvACzjlpEGsO0R4xW2kCmw/Q6yAKf/v/ItSU5yQPOJaVzfVZGOhZG2vofy8o36tDU9bBVaVkYzL4uYTh9B3iCXsMWVaPdw)
[Brainfuck](https://tio.run/##ZU67DsIwDJzjr/AYWoJbSBkgGFa@IeoASIgKqUJIfH9wk9KHcCLf@c455fq@NO39c3uGQISIoEApQSUIqADaA1e05vWx3NnCtERa63KRrrSO6EjTOBo6uf08evONtDQNG57ogU8T5ubvAJFnb2rnOXemXtYs6A37DkVg73IewDknC2LFEq2vaKUEzleA8yJqXqd/EfaUZSQfOBelyfAhDDBqIdhNZbfWfgE)
[Runic](https://tio.run/##ZU7BDsIgDD3Tr@gRmdixzIti9eo3EE5e3GUxJn4/djDZFgvpe32vvPD@jMMjJSJEBAVKCSpBQAUwXvhIHXdXd@pbOxJprd2uXGkT0ZmWcTF0ced58bYbZWkdVp/oytcJW/N3gChwsNEHbryN@8iCwXKYUAQOvuEK3ntZECuXaHNlqyRwcwDcFtHwuv2LcCZjSD5wb501@BQGmLWU@i8)
[Jelly](https://tio.run/##ZU7LDsIgEDyzX7FHpOKWxsZEcfXqNxCOJmqaxqtfj1uofcSF7MzOLBNe9677pESEiKBAKUElCKgA@jO31HBzccd9bXsirbXblCttIDrTMs6GLu44z956oywtw6YneuLLhLX5O0AUONjoA1fexm1kwWA5DCgCB1/xBN57WRArl2hjZaskcLUDXBfR8339F@FExpB84FY7a/AhDDBrKSV3@AI)
[Gol><>](https://tio.run/##ZU7RCsIwDHxuviKPdbNmHYqgNfrqN5S96gZjCv4/NWtnt2Facpe79Ojz1T@6TxsCESKCAqUElSCgAhgufKCa66s97SszEGmt7SZdaSPRkaZxNnRyp3n21htpaRmWn@jMlwlr83eAyLM3jfNcOtNsGxb0hv2IIrB3JWdwzsmCWLFEmypaKYHLHeC6iLr37V@EMxUFyQfulTUFtsIAoxaCPX4B)
[Javascript](https://tio.run/##ZU5BjsIwDDzHr8jRbQhu0XKhqXev@4aoB8RSCKoaBIjvd03DFqp1Is94xhnltL1vr7tLON9sH3/2Q1sPRFprUKCUoBIErQD6mte04tVnufkobE@EiGWWrrQHwZGm8WVgcp/zy5tvpKX3sOkJTvw9YW7@HSDy7G3jPBtnm0XDgt6yf6AI7J3hCZxzsiDWWKI9a7RSApsl6HkRhfPXfxEqynOSD3wXpc31URjoURsqaOMFQ11UwZWFdGMy2MX@Grv9sosHbDFkWTX8Ag)
[Paranthetic](https://tio.run/##ZU67DsIwDJzjr8jotAQnFR2AYGDkG6IOCCHBUlWI/w8mKYUK53Hnu4uV4fy49s/b9Xm/pESktQYFSgkqQdAKoN9xSw03e79ZOdsTIaI3Zcv1Jphpab8GFnfsv948UUK/w6YnOPHfCXPzs4AocrRdiFwH2y06FoyW4xtF4BhqniCEIAGxcok2VrbKBK6XoOdFdB8O/yJsqapIPnBy3lb6Jgx01hLm9NH5dbt2mSMaOWikct@Mqigajdxgkk8v)
I have no idea how Whitespace works. I tried super hard to multiply the input with another value, but it kept complaining about infix arithmetic, so as I had input working, output working, and push-value-to-stack working, so I just went with that.
The input value appears to get lost when pushing `3` to the stack, but oh well. Enjoy a sequence of 3s. The program *does technically take input* it just ends up discarding it.
I also don't know how Paranthetic works, so I can't actually verify that submission as valid, but as far as I can tell the Whitespace code doesn't interfere.
Future answers: be aware that tabs in Runic are a single instruction wide and play havoc with code layout.
[Answer]
# 11. [Grass](https://github.com/TryItOnline/grass), [A000030](https://oeis.org/A000030)
```
//0q
n=>5/2>2?1:40-n//(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##ZU67DsIwDJzjr4hYGlqC21IWCIaVL@gQdWAClgqoRD@/OEmf4vK4851j5f65NU3XIaZvKSUIEIJZMIMUAPWJ9phTfs4ORaprRKVUtg6bLyeUl6GcAhXSvp6yZUdomg8bn6hRzycsw2EBoiWrK2MpMbraVMRsNVnHbJA1CY1kjOEGjjzY6@GjMIGSbfst27bk41CyKluQSyA@X5d/E44Yx8h/uqaZjuWDFUj2opWHI9nrofZ3NDOiIP6shXSIset2efED "Grass – Try It Online")
Grass ignores all characters except `w`, `v` and `W`; conveniently, these three characters are ignored by several of the previously used languages. Luckily, sequence A000030 (return the initial digit in base 10) was still available, as coding even slightly complicated functions in Grass is beyond my ability.
[C#](https://tio.run/##ZVGxboMwEJ19X2F1wUDcg6hdirl2qlSpuweLCQXFi9smafl8emBCQHnG9969d5yQaM@6Pfvh/Te0xofLji919YBY/EgpQYAQzIIZpAAINT3jnvav5ctToQOiUqpM48NlFGqSsb0FKqZzf8u2E3FovWx5RS16vWEbXg8gOnK6MY5yo5tdQ8xOkxuZDXImp4WMMTzA0QT2ZkxR3ED5Y/9n@97yHWFZ2R7kFoj@@@3ehAqzDPmbPopSZ/LICiR7ycOEkeSsr/1Uk5WRRHFnbeSIDIcKuq@T4h8pfV1U3pQF1zxPwZ785fDpw0F1yqdpNfwD "C# (Visual C# Interactive Compiler) – Try It Online")
[brainfuck](https://tio.run/##ZU7LjsIwDDzHXxFxaWgJbiFwgODdK1/QQ9TDLhICIVWABP384iSltGLymPGMY@X//neuj4/DpW0R85uUEgQIwSyYQQqAekcrXNDip9iYXNeISqliGjdfXqggY/kJVEy7@pONO2LTcFj/RPV6OGEcvhcgOnK6so4yq6tZRcxOk/PMBjmbUU/WWm7gKIC9DiGKEyibN8@yaUo@HiWrsgE5BuL5@vttwhbTFPlP@7zQqTyxAsleMgnwJDv9rsOdDIwkii9rJD1SbFuzXJm1MS8 "brainfuck – Try It Online")
[Runic](https://tio.run/##ZU67DsIwDJzjr4hYGlKC26osEAwrX9Ah6sRClwqQoJ9fnKRPcXnc@c6x8v60zb3vEbOXlBIECMEsmEEKgPZMByyouOTHMjMtolIq38bNlxcqyFjOgYrpUM/ZuiM2LYdNT9SklxPW4bgA0ZEztXWUWlPvamJ2hpxnNsjZlCay1nIDRwHsDQhRnEDpvvtWXVfx8ahYVR3INRCb5/XfhBNqjfynW5YbLR@sQLKXbAI8yUGPdbiThZFE8WetpIfGvi9/ "Runic Enchantments – Try It Online")
[Jelly](https://tio.run/##ZU7LDoIwEDx3v6LxQgXrAtGYaF29@gUcGo4magjRi8Svr9sWEOL0MbMz200f16b5OIeYv6SUIEAIZsEMUgC0R9piSeWp2G9y3SIqpYpl3Hx5oYKM5S9QMe3rXzbviE3TYeMTNerphHk4LEC0ZHVtLGVG16uamK0m65kNsiajkYwx3MBRAHs9QhQnULbu3lXXVXw8KlZVB3IOxPvz/G/CAdMU@U@XvNCpvLECyV6yCPAkez3U4U4mRhLFnzWTHik654rdFw "Jelly – Try It Online")
[Gol><>](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN2xZF0Lh69Qt6CL36AKmKYD@/bpI@6eQxszObJbfX8/r43psGMf1IKUGAEMyCGaQAqI60xZzyU7bfpLpCVEply7D5ckJ5GcohUCFt6yGbdoSm8bD@ier1eMI07BYgWrK6NJYSo8tVScxWk3XMBlmTUE/GGG7gyIO9Fj4KEyhZ17@irgs@DgWrogY5BeLjfZ6bcMA4Rv7TJc10LO@sQLIXLTwcyVZ3tb@jkREFMbMm0iHGpsl2fw "Gol><> – Try It Online")
[JavaScript](https://tio.run/##ZU5BboMwEDyzr7B6wUCdNVFzKcbttS/gYHGIktBQRThNqvB8urYJAWWMd2Zn1it@trftdXdpz3@is/vD0JQDovxljEEEUUQcEQOLALpSb3Ct1x/5@5sUHSLnPE/CR8UJ7mVoHwEP6dg/suVEGJovm57wSc83LMP7AUSjjaiV0ZkS9WutiY3QxjEZ2qhMT6SUogGKPMgb4aOwQWer/lb1fUXXoSJV9cCWQGzPn88mFJimSP/0JXORsiMpYOTFLx6O2Kjvva/xzIiDeLIW0iHFoYDGXnhbyqJVuaSaZQnsbHe1p8PqZL95w9skKYZ/ "JavaScript (Node.js) – Try It Online")
[Parenthetic](https://tio.run/##ZU5BbsMgEDyzr0C9eLFLF6zmkJTS9tgX@IB8iKpIycVKo6h@Pl3AcWxlMDuzM@sV5/3lMFyPh@vpJ0Yi8yulBAFCMAtmkAJgePcban37YXevRg9EiGhV@bgkgVmW9h5gSaf@nq0nytBy2fwLznq5YR3eDhAFH3Tvgm@c7p97zxy0D4nZ8ME1fibnHA9wlMHehByVDb55Gf@6cez4JnSsuhHkGkSn8@ejCW9U18Rv@jZW1/LICiR71VNGIjnpW59rtTCqIh6slUyoKWJ@wpex283WZI2o@KJi5L6dXHYkKq6goo3/ "Parenthetic – Try It Online")
[Whitespace](https://tio.run/##ZU67DsIwDJzjr4hYGlqC2woWCIaVL@gQdUAIiS4IBCKfX5yk9KFeHne@c6y4e/O5vZ@X661tEfOXlBIECMEsmEEKgMeBtlhSeSx2m1w/EJVSxTJuvrxQQcZyCFRMu3rIph2xaTysf6J6PZ4wDf8LEC1ZXRtLmdH1qiZmq8l6ZoOsyagnYww3cBTAXocQxQmUrd23cq7i41GxqhzIKRCb52luwh7TFPlP57zQqbyzAslesgjwJDv9r8OdjIwkipk1kR4ptu3mBw "Whitespace – Try It Online")
[05AB1E](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN24iKaFy9@gU9hB4UBL34QLCfXzdJnzh5zOzMZsnzc77cr3WNmL@llCBACGbBDFIAPPa0wgUtDma7zPUDUSllpnHz5YUKMpZ9oGLa1H027ohNw2HdE9Xp4YRx2C5AdOR0aR1lVpezkpidJueZDXI2o46stdzAUQB7DUIUJ1A2r75FVRV8PApWRQVyDMT76/hvwg7TFPlPp9zoVN5YgWQvmQR4ko1u63AnAyOJ4s8aSY8U63qzNivzAw "05AB1E – Try It Online")
[Unreadable](https://tio.run/##ZU7LDoIwEDx3v6LxQgXrAupF6@rVL@DQcNBIookhaqJ8Pm5bRIjTx8zObDd91c/qeD6eblXbIqYPKSUIEIJZMIMUAPWWVphTvsvWy1TXiEqpbBo2X04oL0P5C1RIu/qXjTtC03BY/0T1ejhhHH4XIFqyujSWEqPLWUnMVpN1zAZZk1BPxhhu4MiDvQ4@ChMomTfvomkKPg4Fq6IBOQbi9b7/N2GDcYz8p0Oa6VheWIFkL5p4OJKd/tb@jgZGFMSfNZIOMbbtavEB "Unreadable – Try It Online")
The relevant part for Grass is `wvWwwWWwwwwwwWwWWWw`. Here is my (probably flawed) understanding of how it works: the stack is initialized as `OUT::SUCC::w::IN::ε` (that `w` is just the character `w`). Each instruction adds an element to the stack (they are never popped); the number of `w`s or `W`s indicates how deep to go in the stack; `v` separates instructions.
```
wv # identity
Www # identity OUT
WWwwwwww # identity IN (read in 1 character)
Ww # apply the function identity IN
WWWw # apply the function identity OUT to the value at the top of the stack
```
If the input is `1234`, at the end, the stack probably looks like this: `1::1::id IN::id OUT::id::OUT::SUCC::w::IN::ε`.
It could be made shorter (don't need to define `id OUT` for example), but I stopped as soon as I found a version which worked.
If someone who knows Grass wants to correct/improve the explanation, please edit my answer!
[Answer]
# 17. [Pepe](https://github.com/Soaku/Pepe), [A000578](https://oeis.org/A000578)
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC//*/0e#'
/*
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//rEeE rEeeEe reEE
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Online Interpreter](https://soaku.github.io/Pepe/#.Q@sM)
[C#](https://tio.run/##fVLBTsJAED13v2JTDyytdRaiF9quNlgJhGhiJI1WDtqUsJdVAaXwHx45e/HgfxG/AWe7CBijrzszb9@bnTabZmMvG8vV2bPKAqkm@xhiEK4A@BOltFUUHakxHN70DM6voyLTuG92T7vFbF6qV0g6ze6F2fUu57N5US7Tir2tJoADPN@rEHAssvx4Xb4tPhfvloXvsSy@R3wHLEItgNtnznmkc/2szBFRoTB6fa0rT@AcB2zbVWGo8/ER1EX9uNY45J52VEM5CiDK7qIsitqMsVrVLEyasJKa7dZgxl3vt97PDtO0O2xzhG347oSf5vdDAFKRev0gFW7g9ff7AmvqiVRXFEQauGJTgiDABrRKoLZGaZkJwj2YviTTaYKhkSBLpoT@CQD5ePKvP4rzmGLK45yO8jgmvr5d/PI2r3kOHSIjFDXbrtgm1igp1aWyo1QM@SX9Ou7AyieDhxHDX5LKkPsyqHHMrlslyUhO8q5UORswWa36qy8)
[Brainfuck](https://tio.run/##fVBNT8JAED13f8WmHFpb6yy1eICy2GAlEKKJkTRaOUBTAzFplARb@B8cOXv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MAo88m2@T53nYgFYB1EoUlprA7bP0PUzTELdEiCxMCf0TAOOXy3/9WZAEFEMSJHSWBAGpy7@LL@@wqmPRETJCUdN1Q1e7REGpTMaeYihyJB0dtyDPc/cH)
[Java](https://tio.run/##fVPLbtpAFF3bX3HlLPCjZgbUbrA9qUXdKBElUtMItS4L4zhlKBmIMWCo8hldZt1NF/2vqN9A73hcQpSqxzP3cc6d8evOJFkl7myeicnV1106TRYLeJdw8U0H4KLI8uskzaAvU4Dz0SRLC0hNVEBYHpJ3OppFkRQ8hT4ICHaE0FusPSnLMy4xHn@6VOh/DMtUYtTtvemVm23FfsDgrNs7V9nl@@1mW1ZDlWLtSZcQm9DsqKETW9Mffn1/@HH/@/6npuF9NI0e6Z5NNB00Qj4vKaWhtO23lQ11ETDFt2teuAz3sYlhOCIIpD1@RdqsfdzqvKSuVERH2IKQME3CNAxPTdNsWWqgkYFZhSp9FEyl1vmj9rRCFR1utl9i7uPDHZ6Kfy@dkJjF7tCPmeO7wxdDhj52WSw9Eiz2HbZ3vu9jAUoVkKtRSWoH5jTXq8F6PcApMcBosK7@@79BCJ@//q@eR1kEaLIogzyLIt2TXxef/JS2XBvGGOmAnGE0DDVrVCFI1zhgGip4Rj1bbpOdJ/tyvhxNsS/r9lzN@BXcYG@bF0XOxZd4CImlGvt6llc9zQPqAfdbVDrHseq3u9gsiuymOVsWzTmuLKbC5I7RAWydJh4Gqz4Jd7s/)
You'll have to excuse the Pepe link for not containing the full source: The interpreter disregards any code that is not Pepe (lit. any character not in the set `RE re`) and so its short link doesn't bother encoding it. Ditto input values.
Computes \$a(n) = n^3\$
The AlphaBeta has started throwing errors after writing output, but as a prior answer injected that issue I left it alone. I had planned on fixing it for this answer, but I need to spend some time digging into the jump offsets to resolve the issue. The error with inputs `>0` are easy to fix, but giving it `0` will produce the same error and it will take time to relearn the code in order to fix the offset for it. I wish I could use `W` instead of `UUUUUUUUUU`, but it plays havoc with the Grass code.
[Answer]
# 1. [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) A022996
```
n=>40-n
```
Also works in C# (.NET Core), C# (Mono C# compiler), C# (Mono C# Shell), and C# (Visual C# Compiler)
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXogPEdmm2//Ns7UwMdPO4/ltzpeUXaQBFFTJtDawzbQwNgKS2tiZXeFFmSapPZl6qRppGpqam9X8A "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# 9. [05AB1E](https://github.com/Adriandmen/05AB1E), [A000004](http://oeis.org/A000004)
```
//0q
n=>5/2>2?1:40-n//(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/**/
```
[C# (Visual C# Interactive Compiler)](https://tio.run/##ZVA9j8MgDJ3xr2B0QqlJdV0a4rvppEq334AyRY3KQr9/f84NbdroDPg9v2csRHex3SUO37fU@ZiuCzncNwORO2mtQYFSgkoQtAJIDa9pxavPavPhbCJCxKrIW9Kd4Ehz@TIwu4/65c07ctP7sOkKTvx9wtx8LiAKHGzrAxtv20XLgsFyuKMIHLzhCbz30iDWGKI9YrTyBDZL0PMgisev/yLUVJYkD9i6ypZ6Lwz0qA019Iczygfr2Lg6@spJNqaA33O87n5i2mGPsSjq4Q8 "C# (Visual C# Interactive Compiler) – Try It Online")
[brainfuck](https://tio.run/##ZU7LDsIgEDyzX8ERW3HbSj0orl79BtKDmhgbE6Imfj9uofYRF7IzO7NMuLzPrb99ro8QEIuXlBIECMEoGEEKAL@nGiuqDuXWFNojKqXKRbrcOqIiTeNoqOT28@jNN9LSNGx4ogY@TZibvwOIjpxurKPc6mbZEKPT5DpkgZzNaQBrLS@wFYu1vqKVEihfgZwXYvs8/ouwwyxD/sCpKHUm78xARi0Es67Nxpgv "brainfuck – Try It Online")
[Runic Enchantments](https://tio.run/##ZU4xDsIwDJzjV3gMLcFpVRYIhpU3RJ1Y6FJRJN4f3KSkjXAi3/nOOeX9GYdHCER2QkRQoJSgEgRUAOOFj9Rye21OnTUjkda62aUrbSY60jSuhk7uMq9euZGWtmH5ic58m1CavwNEnr3pnefamX7fs6A37GcUgb2rOYNzThbEiiXaUtFKCVwfAMsiGl63fxHOVFUkH7jbxlT4FAYYtRC6Lw "Runic Enchantments – Try It Online")
[Jelly](https://tio.run/##ZU7LDgIhDDzTr@gRWbHLRmOiWL36DYSjiZrNRo9@PXZh3UcspDOdKROet7b9pERUvxERFCglqAQBFUB34h013JzdYVvbjkhr7VblSuuJzrSMk6GLO8yTt9woS/Ow8Yke@Txhaf4OEAUONvrAlbdxHVkwWA49isDBVzyC914WxMol2lDZKglcbQCXRfR4Xf5FOJIxJB@41s4avAsDzFpKye2/ "Jelly – Try It Online")
[Gol><>](https://tio.run/##ZU7RDsIgDHymX9FH3MSORWOiWH31G8hedUvM1Pj/wQ4m22IhvetduXB/Pm7dpw2BqHojIihQSlAJAiqA/sQ7qrk@28O2Mj2R1tqu0pU2EB1pGidDJ3ecJ2@5kZbmYfmJznyesDR/B4g8e9M4z6UzzbphQW/YDygCe1dyBuecLIgVS7SxopUSuNwALouoe13@RThSUZB84FpZU2ArDDBqIdj9Fw "Gol><> – Try It Online")
[JavaScript (Node.js)](https://tio.run/##ZU7BbsIwDD3HX5Gj2yw4Reyypt6u@4aoBwSUZUINg2m/35kGChVO5Pf8nvOU7/Xf@rw5xeOv7dN2N3TNQOR@tNagQClBJQhaAfQNv9KSl@/V28rZnggRqyJfaReCI83j3cDsXue7N9/IS49h0xOc@GPC3LwdIAocbOsDG2/bl5YFg@VwQRE4eMMTeO9lQayxRLvWaOUENgvQ8yKKx49nEWoqS5IPfLrKlvpLGOhRG2ro0glj4@roKyfdmAI2qT@nw25xSHvsMBZFPfwD "JavaScript (Node.js) – Try It Online")
[Parenthetic](https://tio.run/##ZU67DsIwDJzjr8jotAQnFQxAMDDyDVEHhJDKUgHi/4NJSqHCedz57mLldnpc@md3eV7PKRG5u9YaFCglqARBK4B@y0tquNn59cLZnggRvSlbrjfBTEv7NbC4Q//1pokS@h02PsGR/06Ymp8FRJGjbUPkOth21rJgtBzfKALHUPMIIQQJiJVLtKGyVSZwPQc9LaLrbf8vwoaqiuQDR@dtpTthoLOWMKcPzq@WK5c5opGDRir3zaCKotHIDSb59AI "Parenthetic – Try It Online")
[Whitespace](https://tio.run/##ZU7LDoIwEDx3v2KPFawLBC5aV69@Q8PBGBK4EIwmfn5dWuQRt83O7Mx20k/bvZvXcH803hNlT0QEBUoJKkFABdCfuaKCi0t@LDPTE2mt81280kaiA43jYujoTvPibTfi0jpsfqJnvk7Ymr8DRI6dqa3j1Jp6X7OgM@xGFIGdTXkGa60siBVKtKmCFRM4PQBui6gbrv8inChJSD5wy3KTYCsMMGjel18 "Whitespace – Try It Online")
[05AB1E](https://tio.run/##ZU67DsIwDJzjr/AYWoKbiiIEwbDyDVEHkJDapYD4fwU3KX0IJ/Kd75xTnp/bvX2EQFS8EREUKCWoBAEVQHfiikouz/awLUxHpLW2q3Sl9URHmsbJ0Mkd5slbbqSledj4RI98nrA0fweIPHtTO8@5M/W6ZkFv2PcoAnuX8wjOOVkQK5ZoQ0UrJXC@AVwWUfu6/ItwpCwj@cC1sCbDRhhg1ELY72xlvw "05AB1E – Try It Online")
[Answer]
# 7. [Parenthetic](https://github.com/cammckinnon/Parenthetic), [A019590](https://oeis.org/A019590)
```
//
n=>5/2>2?1:40-n//(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/**/
```
[C# (A022996)](https://tio.run/##ZVBND4IwDL3vV3AszFkgepFRPZmYePewcCIQd5kG8PdjYchH7La@1/e6ZlnZqrK1/fXjSm1dt@NDdd4jCpfTEVNKz8npECuHCABJ6DengcBIfbkY4N2pXrxth29aD5uvwMzXE7bmbwlEQ0YV2pDUqtgVxGgUmQFZIKMlzaC15ga2xmBtitHyE0juRbANRPu@/IsiwyhCfsAtTlQUPJmJYNT6TNSvBvgvA5vHmdVJzFnKUDwa21V36yqowYZh1n8B)
[BF (A000034)](https://tio.run/##ZU5BDsIgELzzCo5IxW0r9aDr6tU3kB7UxLQxIcbE9@MWKm3jQnZnZ4YJt/e194/P/RkCgPBHaqCm@lTtbWk8gFKqWqXLbQAqwrROgkrquE/a0pFM87D8RGU8T1iKvyMAHDnToqMCTbtuiacz5IbJBDksKA9EZANLsZgbK0opgYqNkMsC6F/nf1IcQGvgD1zKymjZMRIyciHYbWN31n4B)
[Runic (A000302)](https://tio.run/##ZU7BDsIgDL3zFRzrEDuWeVGsXv2GhpMXdyHGxO/HDiYbsZD29b3HC@9PnB4pIap4oSMONFzdaextRAQAtytX2gwgw7KuAhR12VetdRTTNqw@gYq3Ca34OwqRiW3wTMbbsA8kky3xPIUg9obq8N6LQaRcwi2VpZJA5qB0W4jT6/ZPqjN2HcoH7r2znX4KUjpzKY1f)
[Jelly (A000312)](https://tio.run/##ZU7RDsIgDHznK3isQ@xYNCZaq69@A@HRRM2y7NWvxw4mG7GQ9np3XHg/@v4TI6IaLnzAjrurO@1bOyACgNvkK20CkGBeFwGyOu@LVjuyaR1WnkDB64Ra/B2F6NnbQJ4N2bANLNNb9tMUgj0ZLoOIxCBSKuHmSlJOYLNTui7E13j7J9UZmwblA/fW2UY/BSmduBijO34B)
[Gol><> (A001489)](https://tio.run/##ZU7RDsIgDHznK3hEEDsWjYnW6qvfQHjVLTGbif8f7GCyEQtpr3fHhef4evSfLkYAMVzoAC21V3faN3YAUEq5Tb7cJqASzOsiqKzO@6LVjmxah5UnquB1Qi3@jgDw5G1ATwZt2Abi6S35aTJBHg2VgYhsYCkVc3MlKSeQ2QlZF0D/vv2T4gxaA3/g3jirZcdIyMTF6I5f)
[JS(ES6) (A000012)](https://tio.run/##ZU5BDoIwELz3FRwXalkwepGyevUNDQejoDWEEjB@H1eqCHHa7M7OTDe9n56n/tzZ9qEadymHKh8QRZPTFte03qe7TaIaRABIQ3@5vAmM1I8/A7z7mX/eMuFD82XTE5j4fMPS/B6BaMioQhuSWhWrgrgbRebdWSCjJU1Na80Btkaw9sFo@Q0kYxEsgWjbw78oMowi5A8ck1RFwY2ZCEZtyETlOrB5klmdJlylDMXZNb2ry7h2V6jAhmE2vAA)
[Parenthetic (A019590)](https://tio.run/##ZU7LDoIwELz3K3rcgnVbIge0rnr0GxoOxpDAhRDD/9elRR5x@tjZmemmw@vT9GPbjN07BETRX6nEgoqbPZ@M7hEBwKq0@ZoIRJra1YDkzv3q7RMptB22PIGFbyfszd8SiJ68rp2n3On6UBNXr8lPlQXyLqelOOc4wFYEazOilSZQfhRyD8RuuP@L4oJZhvyBp7E6ky0zIaMWIKYfxlZlZSIHUHxAMWJfzCorEhTfQoXwBQ)
Parenthetic ignores everything but the `(` and `)` characters. I've had to insert `1`s before every closing parenthesis to stop Jelly from freaking out though (EDIT: I left one `)` unpreceded by a 1, so apparently not all of them need one, but it's too late to golf it down now). The actual code defines a lambda called `((()))`, that can be called on a number to yield the result (1-indexed).
[Answer]
# 10. [Unreadable](https://esolangs.org/wiki/Unreadable), [A001477](https://oeis.org/A001477)
```
//0q
n=>5/2>2?1:40-n//(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN2xZ70bh69RtCD4oFBSkq@P11k/QVOgk7szObJb/221zv19ur6TrE/COlBAFCMAtmkAKgPVKFJZWnYr/LdYuolCrW4XJxQnkZ2ilQIe37KYsnwtB82fhEjXq@IQ6HA4iWrK6NpczoelMTs9VkHbNB1mQ0kjGGBzjyYK@Hj8IGyrYgYyA@3@elCQdMU@QPXPJCp/LBCiR7ycrDkez10PuazIwkiIUVSYcUu676Aw "Unreadable – Try It Online")
[C#](https://tio.run/##ZVGxboMwEJ19X2F1weC4Z6J2KebaqVKl7h0sJhQUL26bpN9PD5sQUB5w791755Ml@rPpz2F8/4u9C/Gy44@GdkS0v1JKECAEs2AGKQBiS8@4p/1r/fJkTURUStVlfrlMQiWZ21ugcjr3t2w7kYfWy5YjatHrDdvw@gCiJ28650k70@06YvaG/MRskHeaFnLO8QBHCezNSFHeQPoR5BaI4eft3oQGqwr5Ah@2NpU8sgLJXvGQMJGc9bVPtVgZRRZ31kZOqHBsYPg@Kf5rMrS2Ca62XLUu4esULofPEA9qUKEsm/Ef)
[Brainfuck](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN29bUg8bVq98QelBBLEJRwe@v26RPnISd2ZnNkuvnUtX37@3ZNIjpW0oJAoRgFswgBUB9oAJzyo/ZzqS6RlRKZctwubRCeRnaMVAh7foxm0@Eoemy4Yka9HTDPOwPIDpyurSOEqvLVUnMTpNrmQ1yNqGBrLU8wJEHex18FDZQsgY5B2L1Ov2bsMc4Rv7AOc10LB@sQLIXLTxakp3ue1@jiREF8WfNZIsYm8ZsCrM15gc)
[Runic](https://tio.run/##ZU7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8B)
[Paranthetic](https://tio.run/##ZU7BTsMwDD3HX2FxqdMSnFTsMAgGjnxD1ANCk7ZLNdD@P7hJ17Xaa@r3/J5j5fz9dxgvx8Pl9JMzs/9FRDBgjLJRBjQA45vsuJf@Pbw8ezcyE1Gw9WiZBBVZ21tANZ37W7adqEPrZcsVWvR6wza8fsCcJLkhJumiGx4HUU5O0sRqSIqdLBRj1AGNCtSbUaK6QbonwC2YT@ePexNeuW1ZH/Dlg2vxqApQveahYCKc9bUvtVkZTRV31kZOaDlTecKnD/vd3hdNZPUnqyh9P7vqIFmtYHPI/w)
[Whitespace](https://tio.run/##ZU7LDoIwEDx3v6LxQi3WBYIXratXv6HhYAwJXAhGEz8fl5ZnmDY7szPbTX9V/S0/7fNVdh1i8pZSggAhmAUzSAHQXOmEGWW39JwnpkFUSqX7cLn0QnkZ2jlQIR36OVtPhKHlsumJmvRywzocDyA6cqawjmJrikNBzM6Q65kNcjamiay1PMCRB3sDfBQ2UHwEuQZi3d63JlxQa@QPPJLUaFmxAsletPPoSQ567H2NFkYUxMZayR4auy7/Aw)
[05AB1E](https://tio.run/##ZU7LDsIgEDyzX0G8FFtxS2ONUVy9@g2kB01M7KVq/P/gFvpMB7IzO7NseP/uj/rpPWL@lVKCACGYBTNIAdCcqcSCios57nLdICqlzDpeLq1QQcZ2DFRMu37M5hNxaLpseKIGPd0wD/sDiI6crqyjzOpqUxGz0@RaZoOczWggay0PcBTAXocQxQ2UbUHOgVh/rksTTpimyB@45Uan8sUKJHvJKqAl2em@DzWZGEkUC2smW6To/WFvSvMH)
Unreadable, as its name suggests, is unreadable. In order to program it I had to use a template and then convert from readable text to Unreadable code.
```
[A=READ()];DO{(A+1)?:BOTH(PRINT(A),[A=READ()])}
[A=READ()]: '""""""'"""'""""""""""
PRINT(A): '"'"""""""'"""
A?: '""'"""
Functioning:
['""""""'"""'""""""""""];'"""""{('""'"""""""'""")?:'""""('"('"""""""'"""),['""""""'"""'""""""""""])}
```
All it does is read each character in the input and output it. One of the more boring sequences, but good for a language that's difficult to work with. I also toyed with using the sequence [A000030](https://oeis.org/A000030) before getting the loop to work.
Working via remote desktop is a pain, you think things work, do all the links, then realize that one of them broke and didn't notice.
[Answer]
# 14. [Aheui](https://aheui.readthedocs.io/en/latest/specs.en.html), [A007395](https://oeis.org/A007395)
Slightly changed to make AlphaBeta works.
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC
/*
박망희*/
n=>5/2>2?1:40-n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##ZU7LToNAFF3PfMXEDeMgXtrYjeIowaRpQzQxNkQnLCoxgU2jC4XyHy67duPC/2r6DXhnhlJIzzzuueecubDM3z6LpgHwPxhj06qaFxp5/rKwuH8Oq0zjNYrv4mpdG/UJyTyKH2y3eKzXdWW2jWJ2GlEQhG7/vrc/m93mVwAh@AVCKKGMULq6lhMYy/HN6PLC91YAYbYMszCccc5Hp3bjpQk31LYHg1u37Q/eMGFD/WHdE97x/oShuV8UQEnlpYGSbuClZ6nEqjypdEVBqsCVXQmCAANoGaDWwlh2gnTPy6@kLBM8GgmypKRsCIDi/fZYpFcgBOA/zfyRJ1iOjDLUnBMDXVjL9725nZ7gWHIkDaiGgKaZ/AM "Aheui (esotope) – Try It Online")
Aheui dismiss any non-Korean character, so `박망희` excuted, which prints `2` and terminates.
[C#](https://tio.run/##ZVI9T8MwEJ3tX2Gx1EkaLqlgIa4hKqJqFYGEqCKIOkDUql4CtIWk/R@MnVkY@F8VvyGc435Ffbbv3r13vmRwOnPTmSpvPrJUqGzexCPH7RLAe2eMdYuirzQmk6eBwe1jWKQaL53oOioWy0p9QNLvRHemGtwvF8ui2qYVe7sdCjah69@v9ffqb/VjAyH4BUIooYxQmrXlObRk69K/OPPcDCBMn8M0DHucc98yG4MmvKKm3BvcuJt679U7TNPhsN0VvuOHE@rmdlGARCbuUCTSEe6wOZSYE1cmOqMgE@HIXRJCYANaFVDboLLMBOmc5p9xnsd4NGJkcU5ZHQDq7epYpAHYNuA/9TzftdkEGWWoNU4q6MQ2fFtXsXEgNAw5kmpUw4YyoOPXKcenwlTbC5TwPYyOY9F4quajSGUjPubKsoLyHw)
[Brainfuck](https://tio.run/##ZU7LToNAFF3PfMXEDQjihUpdKI4STJo2RBNjQ5SwaEkMxISoiUL5D5ddd@PC/2r8BrwzQymkZx733HPOXFh@LPLi5TN9bRoA@50xNqmqWS6QZc9zhbsnv0oFlkF4G1arWqqPSGZBeK@6@UO9qiu5VRSzk4CCQej293u7Wf@tfwwgBL9ACCWUEUqLKz6GER9dOxeubRUAfrrwU9@f6rruHKuNlyC6pKrdG7py237vDRMq1B/WPdE73p8wNHeLAsQ8thIv5qZnJScJxxpbPBYVBR57Ju@K53kYQEsCtRbSUhO4eVp@RWUZ4RGIkEUlZUMA5G83hyK9BMMA/Kep7VgGy5BRhpp2JCEKa/mul7fWEzRFDqQBFTCgadyzsXvuuv8)
[Runic Enchantments](https://tio.run/##ZU7LToNAFF3PfMXEDTiIF5q60XGUYNK0IZoYG6ITFsoGNkRNFMp/uOzajQv/q/Eb8M5MSyE987jnnnPmwvtHVeZdBxC8McZmTbMoNYriaWlx@xg1ucZLnNwkzao16gOSRZzc2W55367axmwbxewspsAJ3fx@bb7Xf@sfDoTgFwihhDJCaXUpz2AiJ1fh@TTwK4Aof47yKJq7rhse242XJq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KyvoAyFd3xyK9BtsG/KeJ6zk2y5BRhpp1oqEKa/i@17fVESxDjqQeVbChrr3RxT8)
[05AB12](https://tio.run/##ZU7LToNAFF3PfMXEDQjiBaIbHUcJJk0boomxITph0RIT2FSNiVD@w2XXblz4X43fgHdmKIX0zOOee86ZC68fi2X50rYA/jtjbFLXs1KhKJ7nBndPUZ0rLOPkNqnXjVYfkczi5N5084dm3dR6myhmJzEFh9Dt79f2e/O3@XGAEPwCIZRQRihdXYlzCEV4HVyc@d4KIMoXUR5FU9u2g2Oz8VLE1tS0e8M2btfvvXHChIbD@id2z4cTxuZuUQAppJdxKVzuZSeZwCo9IVVFQUjuir5wzjGAlgZqHbRlJgj3tPpMqyrFo5AiSyvKxgAo324ORXoJjgP4T1M/8BxWIKMMNetIQxXW8V2vb2sgWIYcSCOq4EDbhv8)
[Unreadable](https://tio.run/##ZU7LToNAFF3PfMXEDTiIl1a7URwlmDRtiCbGhihhQbEJTQxRE4XyHy677saF/9X4DXhnhlJIzzzuueecufCZfyySl2T@uqhrAOedMTYuy@lSIsueZxp3T16ZSsz94DYoV5VSH5FM/eBed7OHalWVausoZsc@BU7o9vd7u1n/rX84EIJfIIQSygil@ZUYwVAMrwcX546dA3hp4qWeNzFNc3CsN16SmIrqdm@Y2m36vddP6FB3WPvEbHl3Qt/cLQoQiciO3UhYrh2fxAJrZItIVhRE5FqiLa7rYgAtBdQaKEtPENZp8RUWRYhHIkQWFpT1AbB8uzkU6SVwDvhPE2dgc5Yhoww140hBFtbwXa9uoyMYmhxIPSrBoa5HZ/8)
[Grass](https://tio.run/##ZU7LToNAFF3PfMXEDSOIF7BuFEcJJk0boomxITphUVlIN43aRCj/4bJrNy78r8ZvwDszlEJ65nHPPefMhdeP@WrVNADeO2NsXFXThUJRPM8M7p6iKld4iZPbpFrXWn1EMo2Te9PNHup1XeltopgdxxRsQre/X9vvzd/mxwZC8AuEUEIZoXR5Jc4hEMG1fzHy3CVAlM@jPIomnHP/2Gy8FOGamnZvcOO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G/UJyTyKH2y3eKzXdWW2jWJ2GlEQhG7/vrc/m93mVwAh@AVCKKGMULq6lhMYy/HN6PLC91YAYbYMszCccc5Hp3bjpQk31LYHg1u37Q/eMGFD/WHdE97x/oShuV8UQEnlpYGSbuClZ6nEqjypdEVBqsCVXQmCAANoGaDWwlh2gnTPy6@kLBM8GgmypKRsCIDi/fZYpFcgBOA/zfyRJ1iOjDLUnBMDXVjL9725nZ7gWHIkDaiGgKaZ/AM)
[Answer]
# 2. [brainfuck](https://github.com/TryItOnline/brainfuck), [A000034](http://oeis.org/A000034)
```
n=>40-n
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v8/z9bOxEA3j0tfP9ouWjfWJtpO20Y3VifWDkhH69pFg2iggF20jbYdnLKxsQEqAEqBAVAMCsBSEBPstPX@/zcxNjUxMzEBAA "brainfuck – Try It Online")
[C#](https://tio.run/##PY2xCsMwDER3f0VHG0WNC90sa@zUvYPwZGLQ4kKSfr@rpqUH0oM7caob1k3H7dUrad8nG2559MzXiN3Ns7BgIWEgLFNhoyDLh2awEPAfRGQHFh0y76cj@jYwnEdy7bl6e3TSHJPSJdoGCO6x6r7ctS@@eQ0hjTc)
[Answer]
# 3. [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), [A000302](http://oeis.org/A000302)
```
n=>40-n//
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
```
[Try it online!](https://tio.run/##RYwxCoAwDEX3nsK9xghGpxi8R@jk1KWI4PljbEXf8sj/n5xXybtZWYVGKIgBUUUhsUpkSH0St4LoYw9EOconZvaBVxXPXmrVPkgcQtdAzMf2H2Y0zbQQ3Q "Runic Enchantments – Try It Online")
[C#](https://tio.run/##RY0/CwMhDMV3P8WNime10M0YOnXq3iE4yQlZbLk/n9@md6V9kPzIeyEpiysL99vWCnBbRymsqbeEl@Ca8p6QXAZCCy6PGYXkkD4UAwks/gAAsiDRLvG@2qPjAtqTGg55z6/rf@hR1ees5f/AKUSGc5BurVGPmdfpzm3SVbMxsb8B)
[BF](https://tio.run/##SypKzMxLK03O/v8/z9bOxEA3j0tfP9ouWjfWJtpO20Y3VifWDkhH69pFg2iggF20jbYdnLKxsQEqAEqBAVAMCsBSEBPstPW4FCBAXz@zwAHB@f/fxNjUxMzEBAA)
If you need help keeping the Runic functional, there is the [Esoteric IDE](https://github.com/Timwi/EsotericIDE) as well as my own IDE (built in Unity3D) in [the master branch of Runic's git repo](https://github.com/Draco18s/RunicEnchantments/). Esoteric IDE doesn't handle displaying the IP directionality very well (primarily my own inability to add such to the existing framework).
All the BF creates a bunch of IPs that self terminate due to performing invalid actions (mainly due to stack underflow) while the `>` in the C# populates the stack with a `4`, bounces of the comment makers (mirrors in Runic), reaching `ip@` to execute `x^4` on an input x and print the result.
[Answer]
# 5. [Gol><>](https://github.com/Sp3000/Golfish), [A001489](http://oeis.org/A001489)
```
//
n=>40-n//
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.
//ip@
//
;/**/
//I01-* h
//
;/**/
```
[Try it online!](https://tio.run/##RY29CoAwDIT3PkXn1hgFwcEYXH2G0NUfEBV8f2paRW/5LnchmY9tWq8lRkSz99xUsKtDFBYIJOwJQhFYKcCSqAELef5ARLqgVZZmr3L1XGBfGvsIcT2HfzAdOpcejlUNzi7qjM1ZjHV7Aw "Gol><> – Try It Online")
[C#](https://tio.run/##RU7BCoMwDL33K3pUa5cKuzWGnQaD3XcoPRVluXSi7vu7qGN7kLzkvZAkLTYtXK7vnJDz2krQ2BcAlXs6O5ulAggUbMRABm1sIwkHS2FjESigoR8hogyItUO0L3br2EDmpPQBAJ4u/0Z5aJrt4M11ttFPqZTeteLV@JoreU9z7zxj5yQbU6vHzOtw5zxUY8V17csH)
[Brainfuck](https://tio.run/##SypKzMxLK03O/v9fX58rz9bOxEA3D8jS14@2i9aNtYm207bRjdWJtQPS0bp20SAaKGAXbaNtB6dsbGyACoBSYAAUgwKwFMQEO209LgUI0NfPLHBAcLis9bW0QBZ6GhjqailkAFlcCmCx//9NjE1NzExMAA)
[Runic](https://tio.run/##RY2xDoAgDER3voIZrMXEzdq4@g0Nk4suxJj4/VjA6C3vete0152OLWdEk2YeAyR1iMICkYQ9QewiKwVYCjVgIc8fiEgXtKrS7FWt2gX2vbFNiMe5/IOZ0LnycA0DOLurM7ZmOY8P)
[Jelly](https://tio.run/##RY2xCoAwDET3fkXn1hgFwcEYXP2G0FFQEXH162Osore85C5c1mnbTtW956aCHdEhCgskEo4EqUhsFGC5aQYLRf5ARHZgUZZ5r3L0NHAsnX@EuBzDv7gOQ7gfjlUNwc82OZ89Va3bCw)
Use single-line comment markers in C# to redirect the Fish IP to the operative code, `I01-*h`, reading input, multiplying by -1, and outputting the result. Gol><> made reading input and dumping the stack as a number easy compared to raw ><>.
Spaces inserted to insure the proper flow of the Fish and Runic IPs, where both C# and Jelly ignore the leading whitespace on the last line (and is a NOP cell in both fungoids).
[Answer]
# 12. [Width](https://github.com/stestoltz/Width), [A020725](https://oeis.org/A020725)
```
//0q
n=>5/2>2?1:40-n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
1-indexed. Outputs by exit code.
[Try it online!](https://tio.run/##ZU67DsIwDJzjr4hYGlqCWwQLBENHvqBD1AGVARYEEiKfX5ykT3F53PnOseIet8@9bRHzt5QSBAjBLJhBCoDnkXa4oc2p2G9z/UQsm2vZlOVFKVUs4@bLCxVkLMdAxbSrx2zeEZumw4YnatDTCfOwX4BoyeraWMqMrlc1MVtN1jMbZE1GAxljuIGjAPY6hChOoGztvpVzFR@PilXlQM6B@Hid/004YJoi/@mSFzqVd1Yg2UsWAZ5kp/s63MnESKL4s2bSI8W2LX4 "Width – Try It Online")
The only relevant characters to Width are `a-zA-Z`. The code Width runs is the following:
```
qnnAcaAcAAI
```
The first three characters, `qnn`, are no-ops. `Ac` reads an integer from input, `a` is a no-op, and then `AcAA` increments the integer by one. `I` ends the program, and the top of the stack is becomes the exit code. All other letters in the program are ignored since the program terminated.
[C#](https://tio.run/##ZVGxboMwEJ19X2F1wUDcg6hZgnHLUilSdw8WQ2QF1Qttk7R8Pj0wIaA843vv3jtOSLiLdBffv/@2Tvn2uqGrm7JHzH4458CAMWJGDJwBtKXe4VZvX/P9SyZbxModK1dVByFEHoeHyiDEKEN7D0RIp/6erSfC0HLZ/IqY9XLDOrwdQLTaylpZnSpZb2pNbKW2A5OhrUr1TEopGqBoBHkTxihs0Olz92e6ztAdYEiZDvgaiP777dGEApME6ZsOWS4T/kkKOHnR04iB@KRv/VijhREF8WCt5IAE@wKar7OgH8p9mRVe5RnVNI3BnP319OHbk2iEj@Oi/wc "C# (Visual C# Interactive Compiler) – Try It Online")
[brainfuck](https://tio.run/##ZU7LbsIwEDx7v8LiEpPU3YQaDq3ZkiNfkIOVA0SqQEgRVGrz@WFth5CI8WNmZ9YrH38P5/bnr7n0PWJ@k1KCACGYBTNIAdBuaY0rWn0XnybXLWLZHMqmLPdKqWIZN19eqCBj@QxUTIf6mc07YtN02PhEjXo6YR4@FiA6crq2jjKr67eamJ0m55kNcjajkay13MBRAHsDQhQnUPbe/VddV/HxqFhVHcg5EM/X3asJX5imyH/a54VO5YkVSPaSRYAnOehHHe5kYiRRvFgz6ZFi35uPtdkYcwc "brainfuck – Try It Online")
[Runic Enchantments](https://tio.run/##ZU67DsIwDJzjr4hYGlqC2woWCIaOfEGHqAPqAksFSNDPL07Sp7g87nznWHl/mkfddYjpS0oJAoRgFswgBUBzoj3mlJ@zwy7VDWJR34q6KK5KqWwdNl9OKC9DOQUqpH09ZcuO0DQfNj5Ro55PWIbDAkRLVlfGUmJ0tamI2WqyjtkgaxIayRjDDRx5sNfDR2ECJdv2W7ZtycehZFW2IJdAfDwv/yYcMY6R/3RNMx3LOyuQ7EUrD0ey10Pt72hmREH8WQvpEGPX7X4 "Runic Enchantments – Try It Online")
[Jelly](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN24oiaFzt0S/oIfQgIqiI6MXi18dNUmuLk8fMzmyWXE@329s5xPwppQQBQjALZpAC4L6hBc5oti1W81zfEcvjoTyW5V4pVYzj5ssLFWQsf4GKaVv/smFHbOoP656oTvcnDMPvAkRLVtfGUmZ0PamJ2WqyntkgazLqyBjDDRwFsNciRHECZdPmVTVNxcejYlU1IIdAvDx2/yasMU2R/7TPC53KMyuQ7CWjAE@y1d863EnPSKL4swbSI0XnXLH8AA "Jelly – Try It Online")
[Gol><>](https://tio.run/##ZU7LCsIwEDxnvyJ4aWyN2xZF0Ljao1/QQ@hBBB8gPhDs59dNUmuLk8fMzmyWnO7X4@V1bhrE9CmlBAFCMAtmkALgtqY55pRvsuUs1TfE4rAvDkWxU0pl47D5ckJ5GcpfoELa1r9s2BGa@sO6J6rT/QnD8LsA0ZLVlbGUGF1NKmK2mqxjNsiahDoyxnADRx7stfBRmEDJtH6XdV3ycShZlTXIIRAvj@2/CSuMY@Q/7dJMx/LMCiR70cjDkWz1t/Z31DOiIP6sgXSIsWmyxQc "Gol><> – Try It Online")
[JavaScript](https://tio.run/##ZU5BboMwEDyzr7B6weA6C1FzKcYtx7yAg8UB0dASRThNqvB8umBCQBnjndmZ9YpjeSuv1aU5/8nWfh36Ou0Ro1/GGHjgecQeMTAPoE31Drd6@xG/v0WyRcyqMquybM85jwP3URkEH6VrHwF36dQ/svWEG1oum5/wWS83rMP7AUSjjSyU0ULJ4rXQxEZqMzAZ2iihZ1JK0QBFI8ibMEZugxab7pZ3XU53QE4q74CtgdicP59NSDAMkf5pH8UyZD@kgJHnv4wYiE363o/VXxi@E0/WSg4IsU@gthfepFHSqDiiKkQAlW2v9nTYnOw3r3kTBEn/Dw "JavaScript (Node.js) – Try It Online")
[Parenthetic](https://tio.run/##ZU5BbsMgEDzDK1AvXuzSxVZySEppOeYFPiAfIitScrHSKKqfTxdwHFsZzM7szHrF9Xg7Dffz6X7pQ0DUv0IIzjhjxIyYC8b58GW32Njmu95vtBoQXX90vXMHAKhl/qhEAUnm9hlATqf@ma0n8tBy2fwLzHq5YR0@Dkf01qvOeFsZ1b13ltgr6yOTYb2p7EzGGBqgKIG8CSnKG2z1Mf6149jSjWhJtSMXayBerj@vJv/EskR600HXqhRnUlyQV7wlRBKTfvSpFgujyOLFWsmIEgOkJzhd77Y7nTSApAuSkPpmcskRIKlyGerwDw "Parenthetic – Try It Online")
[Whitespace](https://tio.run/##ZU7LDoIwEDx3v6LxQgXrgtGL1lWOfgGHhoMhJHoxGo39fNy2iBCnj5md2W7qLtdX@7yfm7brEPOHlBIECMEsmEEKgNueNrii1aHYrnN9Qyybc9mU5UkpVczj5ssLFWQsf4GKaV//smlHbBoPG56oQY8nTMPvAkRLVtfGUmZ0vaiJ2WqyntkgazIayBjDDRwFsNcjRHECZUv3rpyr@HhUrCoHcgrE6/34b8IO0xT5T6e80Km8sALJXjIL8CR7/a3DnYyMJIo/ayI9Uuy69Qc "Whitespace – Try It Online")
[05AB1E](https://tio.run/##ZU7LTsMwEDx7v8LiEpPgblzRCoHZkmO/IAcrh7RCai8BhIQ/P6ztPJXxY2Zn1it//baX@2ffI5Y/UkoQIASzYAYpALp3OuCe9ifz@lzqDrG6ttW1qs5KKfOYNl9BqChTOQcqpUM9Z@uO1LQcNj1Rk15OWIfjAkRHTjfWUWF189QQs9PkArNBzhY0kbWWGziKYG9AjNIEKnb@r/a@5hNQs6o9yDUQ798fWxPeMM@R/3Qujc7ljRVI9rKHiEBy0GMd72xhZElsrJUMyLHvX47mYP4B "05AB1E – Try It Online")
[Unreadable](https://tio.run/##ZU5JbsMwDDyLrxB6sWJXoZ3lkqpMfMwLfBB8cBYgAQojCdD6@S4leUVGywxnKEK/9etaXarTz7VtEdOnlBIECMEsmEEKgPqbtrii1T7bbVJdI@bnKj/n@VEplS3C5ssJ5WUox0CFtKvHbN4RmqbDhidq0NMJ87BfgGjJ6tJYSowuP0titpqsYzbImoQGMsZwA0ce7HXwUZhAybL5K5qm4ONQsCoakHMg3h@HdxO@MI6R/3RMMx3LGyuQ7EUfHo5kp/va39HEiIJ4s2bSIca23a7/AQ "Unreadable – Try It Online")
[Grass](https://tio.run/##ZU67EoIwEKxzX5GxIYLxALXReErpF1BkKBwLtXFUZuTz8ZIAwrh57N7u5SbX97mu2xYxfUkpQYAQzIIZpAB47GmDOeWHbLtO9QOxuJyLS1GclFLZPGy@nFBehvIXqJB29S@bdoSm8bDhiRr0eMI07BcgWrK6MpYSo6tFRcxWk3XMBlmT0EDGGG7gyIO9Dj4KEyhZNp@yaUo@DiWrsgE5BeL9efw3YYdxjPynU5rpWN5YgWQvmnk4kp3ua39HIyMK4s@aSIcY23aVr78 "Grass – Try It Online")
[Answer]
# 13. [AlphaBeta](https://github.com/TryItOnline/alphabeta), [A162672](http://oeis.org/A162672)
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC
n=>5/2>2?1:40-n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//
;/**/
//I01-* h
//
;/*'""""""'""" '""""""""""'"""""'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##ZU7RaoMwFH1OviLsxUznrpb1ZcuyiYPSIhuMFtmCD1YGFkbpYMzUn3c3ibVKjzHn3HOOF8vvQ11uv37LrgOIfhhjC61XO4O6/tw4vH4kujLYptlLpo@tddcoVmn25qbNe3tstT2uit1FSgklBJcSZMoIpftHOYeZnD3F93dRuAdIqjKpkmTJOY@v3cHLCG6lG88Bd2k/n7Npw5XGy4ZP@KDHG6bh6aEASqqwEEoGIixuComsQqkMoyGVCORAQggsYGSBXg8buQ0yuG3@8qbJ8TXIUeUNZVMA7A7PlyZ9AN8H/KdlFIc@q1FRhp53ZWGI9fo029sbGZ4TF9ZEGvjQddE/ "AlphaBeta – Try It Online")
I had originally planned to use sequence A000030 and the code `JCL`, but that got yoinked (I don't blame them, its a good sequence for languages that take input as single bytes). The original code for this entry after having to pick a new sequence was:
```
JiiiiihhZUUUUUNYAxcccccbCLDLxyzUUUUTTxxyzJCLOzWRxyxyzcccccbbCL
^ Read input (single byte)
^ ^^^ ^^^^ ^ ^^^^^ Clear regisers
^ ^^^^^^^^^ Input = 0: print 0
^^^^^^^ ^^^^^ ^^^^^^ ^ Set jump locations
^^^^^^^^ Print `1`
^^ Print initial byte
^^^ Read and print input
^ (and loop)
```
Sequences of `xxx` or `xyzxyz` are useful spacers to make the jump-to targets easy values (46 is easier as "5\*10-4"--9 instructions--than "4\*10+6--ten instructions--but 50 is even simpler: only five). You'll see a fair few of those.
But as there are other bytes on the first line, the jump-to codels needed some new values and that turned into:
```
//0q xxxJiiiiihhZUUUUUUNYAxcccccbCLDLxyzUUUUUTxxyzJCLOzWRxyxyzcccccbbCL
```
Avoiding executing this code as Width code just involved wrapping it in `G` to make it a string literal (which does nothing important in AlphaBeta), a command to pop the top of the stack, and then some extra `W` to make alpha beta not crash when exiting:
```
//0q GxxJiiiiihhZUUUUUUNYAxcccccbCLDLxyzUUUUUTxxyzJCLOzWWWWWWRxyxyzcccccbbCLGw
```
To avoid conflicts with Grass, though, instead of popping the command with `w` `C` is used instead. Then the "exit program" jump is replaced with `UUUUUU` instead of `WWWWWW` This does leave the IP somewhere in the middle of the rest of the junk code, but far enough out that it doesn't print any errors. Any number of additional `U`s can be added in pairs if this becomes a problem.
```
//0q GxxJiiiiihhZUUUUUUNYAxcccccbCLDLxyzUUUUUTxxyzJCLOzUUUUUURxyxyzcccccbbCLGC
```
The additional `i` that Runic ends up executing is a NOP on valid inputs as no-input-left-to-read pushes nothing to the stack ("reading all input" is a pain in Runic).
[C#](https://tio.run/##ZVJdT4MwFH2mv6LxZQVWC4u@SFclMy5biCbGhWjDgzZb1hfUbQrbn2e3LfsgO7T3nnvO4YYH1JqqtW6e/krFdbnpwxWLYcNY9IsxHtf1VBsslx8zh@f3tFYGX6PsMau3O6u@AZmOshc3zV53211tj4tCdjxCHvI8WOpBR9hDqByKWzYQg/v47iaiJWOp@kxVmk4IIbHvDhRDiKVuPBnEue188roJFzpfdnyFHPn5hq55eBBjUkhacClCTot@IaBLKqTpIAjJQ3FsnHMIgGUBWgtruQ0ivK7@86rK4RrkwPIK4S4Y0z8PlyJKWBAw@KZJFNMAL4EhDFrvysI03PLDbGvvTOg5ciF1qEHAmgQtvlcE/g6sh1GieRxBDUMf5Su9mWe6nJMF0b6fNHs)
[brainfuck](https://tio.run/##ZU7RaoMwFH02XxH6YqZzVzu7hy3LJg5Ki2wwWmQLPrTCUAayDTatP@9uEmuVHmPOueccL@5/dmX18Zt/dh2A/00pXTbNulQoivetwfNb1OQK@zh5SppDq90NinWcvJhp@9oe2kYfU8XuMiYWsSxcaiETahFS3YsFzMX8IbgNfa8CiPJdlEfRijEWXJiDlxJMSzOeAmbSfj5l04Ypj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oteScx6fu4GUEt9KNh4C7tJ8P2bThSuNlwyd80OMN03D/UAAtdZgLLQMR5me5RNah1IbRkFoEciAhBBYwskCvh43cBhmc139ZXWf4GmSospqyKQCq77tjk16D7wP@0zKKQ5@VqChDzzuxMMR6vZ/t7Y0Mz4kjayINfOi6@PIf)
[JavaScript](https://tio.run/##ZU5hS8MwFPyc/Irgl8bW@trhEDRGQ4WxURRko2joBy1oCzIVwXb98/Ul6bqWXdPcvbvrox9fn@/Vb9l1ANEPY2zRNKvKoCxfNg4Pz6opDN6S9D5tdq111yhWSfrops1Tu2sbe1wVu4uEEkoILiXIlBFKtzdyDjM5u42vLqJwC6CKV1UoteScx6fu4GUEt9KNh4C7tJ8P2bThSuNlwyd80OMN03D/UAAtdZgLLQMR5me5RNah1IbRkFoEciAhBBYwskCvh43cBhmc139ZXWf4GmSospqyKQCq77tjk16D7wP@0zKKQ5@VqChDzzuxMMR6vZ/t7Y0Mz4kjayINfOi6@PIf)
[Parenthetic](https://tio.run/##ZU7fa4MwEH42f0XYi1HnTmV96JZlCw5Ki3QwVmQTHzop6It0o0zbf95dEmuVfiZ334/zyH77u6sP5e5QFV0HEPxQShdtu6oUyvJrY7D@lG2h8B0nr0l7PGn3A8kqTt6M2ryfjqdWHzOKs4uYWMSycKmFnVCLkPpJzCAS0XP4cB/4NYAstrKQcskYCx1zsCjCNDXyEjCT9vqSTSfM0HjZ8Asb@HjDNDx/BCATmZ/zTHjcz29zgT3zRaY6GiLjnhga5xwHMNJAr4eOzAbh3TV/adOkeBVSZGlD6BQA1f7l2iSP4LqAb1oGoe/SEhmh6Nk3GqrRnp@1rvbIsA25siZUwYWO6SfIIJzP5oHmjDl4mYPQOupddChzsBKnC7t/)
[Whitespace](https://tio.run/##ZU7RaoMwFH1OviLsxUznrpbuZcuyBQelRToYK7IFHzop6Evp2JjWn3c3ibVKjzHn3HOOF@uy@t39HLbFrusAom/G2KJpVpVBWX5uHNYfqikMvpL0JW2OrXXfUayS9NVNm7f22Db2u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ZimeUvblq/todW2@Oq2J1nxCOeh0s9ZEI9QnYP4hZSkT4md7M42gHIaiMrKReMseTSHbyMYFa68RQwl/bzKZs2XGm8bPiEDXq8YRoeHwKghIpKrkTIo/KqFMgqEsowGkLxUAzEOccCRhbo9bCR2yDC6@avaJoCX4MCVdEQOgXA9vvp3CT3EASA/7SIkyigNSpC0fMvLAzRXh9ne/sjw3fizJpIgwC67iad/QM)
[Width](https://tio.run/##ZU7BToQwFDy3X9F4oYL4YONetFYJJpvdEE3Mbog2HBQPcNloYmyXn8fXlmUhO5TOvJnhBd1@/TZ9D5D8MMZWxmxai6Z533k8v2WmtvjMi6fCHDrnblFs8uLFT7vX7tAZd3wVu6ucEkoILiXIlBFK9/dyCQu5eEhvb5J4D5DVH1mdZWvOeXrpD15WcCf9eAq4T4f5lM0bvjRdNn7CRz3dMA@PDwVQUsWVUDIScXVVSWQVS2UZDalEJEcSQmABIwf0BrjIb5DRtf4rtS7xtShRlZqyOQDa78dzk95BGAL@0zpJ45A1qChDL7hwsMQGfZzdHUyMwIszayYtQuj79B8)
[Answer]
# 18. ]=[, [A010716](https://oeis.org/A010716), the all 5's sequence
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC//*/0e#'[=====[===]]=[[==========]]=[
/*]
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//rEeE rEeeEe reEE
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
This language isn't on TIO and its only interpreter is written itself in another interpreted language, which is *also* not on TIO. And the one that didn't play nice with Brainfuck last week at the last minute, but I figured out what was wrong a few hours after posting the Pepe answer, so I saved it for this week. Being a language not on TIO I was considering this one an ace-in-the-hole that could easily be tacked onto just about ANY entry and continue the chain.
* Interpreter code: <https://pastebin.com/raw/yqtpynnh>
* Interpreter interpreter: <https://12me21.github.io/12-basic/>
Put the interpretter code into the "code" box at the top, code from the answer in the input, and click run and get an output (plus some extra junk that is always printed).
The operational portion of the ]=[ is this at the end of the first line:
```
[=====[===]]=[[==========]]=[
```
Its that trailing `[` that played havoc with the Brainfuck (the rest being ignored, due to how `[` and `]` are handled by Brainfuck) and once I looked at the Brainfuck spec again I realized the problem and that all I had to do was insert a `]` somewhere after the first line (as the ]=[ interpreter does not read newlines) and before the Brainfuck. I chose the 2nd line.
[C#](https://tio.run/##fVLLTsMwEDzHX2GFQ92EsG4FF5IYopIiqgokRBVByAGiVPXFQB807X9w7JkLB/6r4hvKOi6lCMHE3p2dWa@syPnIy0dy1Z6oPJBqvItb9MMVAH@ilJ6WZUdqDAY3PYPz66jMNe5b3ZNuOZtX6hWSTqt7Yare5Xw2L6tlWrH3tAXgAC92ammooWOWhampKuiSgJNZZPn@snxdfCzeLAtvYVl8h/gOWIRaALcTznmkY7NdxYioUBi9udaVJ3CQA7btqjDU8egAmqJ51Djc55521KFyFECU30V5FJ0xxhp1szBowipqym@DGXddf3s/O0zT9rDNEbbh2xN@ml8fAUhF6mVBKtzAy3YzgTn1RKozCiINXLFJQRBgA1oVUFujsswE4e5Nn5PpNMGtkSBLpoT@CQD5ePyvP4yLmGIo4oIOizgmvv67ePMz3vAcOkBGKGq2XbPNXqOiVKfallIz5Jf067gDK5/0H4YMHyyVIfdl0OAYXbdOkqEcF12pCtZnsl73V58)
[Brainfuck](https://tio.run/##fVBNT8J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V0nkYRaYnfxZf33Lpj0SkyQlHTdUNXp4KkVCRjTzEUOZAOrltQlo3Tbw)
[Grass](https://tio.run/##fVBNT8JAED13f8WmHFpb6ywVL9AuNlgJhGhiJI2uPSBphEujEG3hf3jk7MWD/4v4G@pst/IRom93Z968NzvZ7NNsNJ8XBQB7oZR287w/lZhM7ocKV3dBPpZ47AwuBvliWaq3SPqdwbWqhjfLxTIvt2rF3m4HwAKW1AzhS8gYx75QVQlZErBijay/3tcfq@/Vp6bhKzSN1UjLAo1QDeDhlTEWyOheljEgqc@V7lZ66nAcZIGu26nvy9g@A5e77XqzwRzppM3USgGC8SgYB0HPNM36kdoYJDFLqsqtYSq3qrfefodq2h22uWJu@O6EffN3EQDBhRN7gtueEx/HHLNwuJAZBS48m2@S53nYgFYJ1CqUlprA7ZPsLcqyCI9EhCzKCP0TANPn83/9WZiEFEMSJnSWhCFpyd/Fl/dY3bHoBBmhqOm6oatToaRUJmNHMRQ5kA6uW1AUp27jBw)
[Width](https://tio.run/##fVDBTsJAED13v2JTDq3FOksjF2gXG6wEQjQxkkbXHhSblEujRG3hPzxy9uLB/yJ@Q53drQgh@nZ35s17s5PNFrOH56yqANgTpXRQlqOZRJbdTDTOr8NyKnHfH5@Oy8VSqVdIRv3xha4ml8vFslRbt2LvoA/gAEsblggkZEySQOhKQZYEnMQg68@39fvqa/VhGPgKw2AN0nXAINQAuH1hjIUyemcqhiQPuNa9Ws9djoMcMM1mHgQy9trgca/X6hwzVzp5J3dygHB6F07DcGjbdutAbwyS2Irq8tewtVvXv95uh27aHra5Ym/49oRd82cRAMGFm/iCN303OUw4ZuFyITMKXPhNvkm@72MDWgqo1VCWnsCbR8VrXBQxHokYWVwQ@icAZo8n//rzKI0ohjRK6TyNItKVv4svH7KW69AMGaGomaZl6lNDUSqTtaVYmuxJe9cdqKr2Nw)
[AlphaBeta](https://tio.run/##fVJNT4NAED2zv2JDDyCIsxC9tLCVVGzaNJoYG6LIgTYkNDGkNiq0/8Njz148@L8afw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aWX@9rz9W36tPTcNXaBqrkaYFGqEawMMrYywQ0b2UMSC5z5XuVnrucBxkga7bue@L2DoDl7uteuOUOcLJG7mVAwTpMEiDoGuaZv1IbQyCmJKqcmuYyq3qrbffoZp2h22umBu@O2Hf/F0EIOaxk3gxtz0nOU445tjhscgo8Niz@SZ5nocNaEmgVkFaagK3T@Zv0Xwe4RGIkEVzQv8EwPjp/F9/FmYhxZCFGZ1lYUia4nfx5V1Wdyw6QkYoarpu6OpUkJSKZOwohiIH0sF1C8qydH8A)
[Java (OpenJDK 8)](https://tio.run/##fVPLbtpAFF17vuLKWeBHzQyo3eBHalEaJaJEahqh1vXCOE4ZSgZiDBiqfEaXWXfTRf8r6jfQOx6XEKXqsec@zrlzNbbuTJJV4szmmZhcfd2l02SxgHcJF98IABdFll8naQYDmQKcjyZZWkBqoALCdJG8I2gWRVLwFAYgwN9Rym6x9qQsz7jEePzpUmHwMSxTiVG3/6ZfbrYV@wGDs27/XGWX77ebbVm9qhRrT7qUWpRlR43Il5A2jv1IZRVkSqgVa@Th1/eHH/e/739qGp5C09gRcS2qEdAo/bxkjIXStt9WNiTCDxTfrnnhBNjIorpuC9@X9vgVbQft41bnJXOkIjrCEpSGaRKmYXhqGEbLVC8aGRhVqNJHwVBqnT9qTytU0WGz/RZjHx92eCr@fQilURA5sRcFtufEL@IAfeQEkfRIBJFnB3vneR4WoFQBuRqVpDoEdnO9Gq7XQ1wSQ4yG62oq/g1K@fz1f/W8l/UATdbLIM96PeLKv4snP2Utx4IxRgSQ0/WGrlaNKgTpGgdMQwXPqGfbLbpz5dTOl6MpTm09vKsZv4IbnHzjosi5@BLFkJhq7K9neTXx3GcucK/FpLNts/66i82iyG6as2XRnOPOYioMbusdwNFp4lUx63tyt/sD)
[Pepe](https://soaku.github.io/Pepe/#.Q@sM)
[Answer]
# 19. [Actually](https://github.com/Mego/Seriously), [A005843](https://oeis.org/A005843) (2\*n)
```
//0q GxxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLGC//*/0e#,2*1z⌂'[=====[===]]=[[==========]]=[
/*]
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//rEeE rEeeEe reEE
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##fVA9T8MwEJ3jX2GlQ4LTcEmApU1cohKqVhVIiCqCkKFEkVqpiqCiNM3IzMrYmYWB38Ra8RuCP0I/VMGzfffuvfPJ8jB5mg0nk0VZAliPGONOnvfGHKPR7UDi4sbPE477dv@sny8KoV4z0mv3L2U1uCoWRS62bGW9nTYAASut1R1iF1@vL1rkcfAYx14kKwFeIiCxglafb6v35ffyQ1HYaxTFqqEmAQVhBeBuZlmWz6NzLqKPMo9K3an0zKRsEAFVNTLP47F1Ag51Wnbj2DK5kzUykgH4ydBPfL@r67p9IDcLnOiCynJj6NKt6o232yGbtoetr@hrvj1h1/xdCCCikRm7ETVcM67HlOXIpBHPTKCRa9B1cl2XNTBLgGkVhCUnUONw/hzO5yE7HCFj4RzhPwEwfjj9158GaYBZSIMUT9MgQE3@u@zlXcs2CR4xhjDTVFVT5akgKOZJ21I0SfakvesEyvLoBw "Actually – Try It Online")
Operational part: `,2*1z⌂` (first line)
As `⌂` terminates the program, none of the code after it has any effect, and none of the symbols before it result in any output or pollute operational memory adversely. Section exists within a comment (C#, JS, Java), only contains ignored characters (Commentator, ]=[, Pepe, Aheui...), is not on the last line (Jelly), or otherwise in un-executed parts of the code (Gol><>, Runic, AlphaBeta).
[C#](https://tio.run/##fVI9T8MwEJ3jX2GFoW7ScE4EC0kMUQkIVIGEQBGEDBClqhcD5aNpR2ZWRmYWBn4TK@I3lHNcShGCF/vu3XvnkxW5vPbKazndulVlJNVNB7fox1MAfkUp3a7rXakxGJwcGewdJ3Wpcd7tbfbq8aRRD5Hsdnv7pjo6mIwndbNMK/ZudwEc4NVSJ3D8ydvDfSuPNXQsijg3VQNdEnAKi7y/Pr4/P308vVgW3say@BIJHbAItQBObznniY7BVhMTomJh9GCmK0/gIAds21VxrOP6KgQiWPfXVrinHbWmHAWQlGdJmSQ7jDG/bRYGTVhDTfltMOPO6m/vZ4dpWhw2P8LmfHHCT/PrIwC5yL0iyoUbeUWnEJhzT@Q6oyDyyBXzFEURNqDVALUZGstMEO7y6C4bjTLcGhmybETonwCQlxv/@sO0SimGKq3osEpTEuq/izff4b7n0AEyQlGz7ZZt9gwNpTq1FpSWIb@kX8cdmIakfzFk@HCpjHkoI59jdN02yYbypupJVbE@k@12OP0E)
[Brainfuck](https://tio.run/##fVDBTsJAED13v2JTDq0tdba1eIB2scFKIEQTI2m09gBNDcSkURKk9OjZq0fOXjz4TV6J31B3uxUwRN/uzrx5b3ay2fFsNE3v5vF9UQCQR4xxN8v6U47J5GYocH7tZTHHuDM4HWTLvFSvGOl3BheiGl7myzwrt2hlvd0OgAYkqdUtzcw/X56V0OXgMYrcUFQleIlAiyS0/nhdv62@Vu@SxF4jSaSGWhpICEsAt3NCiMejdVZGD6UuFbpV6alB2SANZFlPXZfHdgMsarXNpk0M7qTNVEsBvHjkxZ7XU1XVPBCbBU7Ukopya6jCreqt97tDNO0O21xRN3x3wm/zZyGAkIZG5IRUd4yoHlGWQ4OGPDOBho5ON8lxHNbArBJMq1BaYgLVDxdPwWIRsMMRMBYsEP4TANOHk3/9mZ/4mIXET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ZQCPXpOvkui5rYJYA0yoIS06g5uH8OZzPQ3Y4QsbCOcJ/AmB8f/KvPwvSALOQBimepUGAmvx32cu7xLYMPGIMYaapqqbKU0FQzJO2pWiS7El71w0oy9L5AQ)
[Java (OpenJDK 8)](https://tio.run/##fVPLbtNAFF3bX3HlLuJHnRlbsIkfxQqmahVSiVJFYLxwXJc4pJPUcRInqBvWbFl2zYYF38S24hvCHY9JUxVx7LmPc@5cja0742SZmNNZxsaXn7bpJJnP4XWSs88yQM7KrLhK0gz6PAU4G46ztIRURQWY5iB5K6OZl0mZp9AHBt6WEHqDtcdVdZpzjEbvLwT674Iq5Rh2ey971XpTs28xOO32zkR28Waz3lT1K0qx9rhLiE5odnBo69bm19cvrcjj4DaOvUhkNXgqEz2W5Puf3@6/3/2@@yFJeBpJogeyoxNJBomQDwtKacCt/aq2gcw8X/B2wzPTx0Y6URSDeR63R8@J7dtHVucZNbnCOkxnhARpEqRBcKKqqqWJFw0P1DoU6YOgCrXJH7THFaJov9lui7qL9zs8Fv8@MiGRH5mxG/mGa8aHsY8@Mv2IeyT8yDX8nXNdFwtQqoFcg1oSHXyjvVoOVqsBLo4BRoNVPR3/BiH57MV/9SLMQkCThRkUWRjKDv@7ePITapk6jDCSATlFaSliNahD4K61x7RE8IR6sl0nW4dP72wxnOD0NkO8nOaXcI03QD0vi5x9jGJINDH@V9Oinvzcow7krkW5Mwyt@brz9bzMrtvTRdme4c5ywtTcUDqAo9PGK6M19@V2@wc)
[Pepe](https://soaku.github.io/Pepe/#.Q@sM)
]=[ (link not possible, [see #18](https://codegolf.stackexchange.com/a/188266/47990) for instructions)
[Answer]
# 20. [Neim](https://github.com/okx-code/Neim), [A008592](https://oeis.org/A008592) (10\*n)
```
//0q ÷GxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLxGC//*/0e#§≈2*1z⌂'>[=====[===]]=[[==========]]=[
/*]
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip@
//rEeE rEeeEe reEE
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##fVA9T8MwEJ3jX2GlQ0JCOCeiS5u4RCVUrSqQEFUEJgNUkdqBCCpB0o5MILEydu7CwMYO/6RrxW8Idhz6oQqe7bt3751PlpN4eJPnAOQOY/z10co6Q4HB4KIncXzuZ32B62b3sJuNJ4V6xkmn2T2RVe90Mp5kxZatvDdrNQEMIHHlczZ/fnIMezJ/edQo8wREjCKPyaqAKBEYkYIW76@L2fR7@qYo/FGKQiqoboCCsAJweU8I8UV0joroo8SjUndKPbEoH2SAqpqJ54nYqIJDnYZd2yeWcJJaYiQAfv/K7/t@W9d1e0duHgTRCyrLlaFLt6xX3maHbFoftryiL/n6hE3zdyEARpkVuYyarhXtRpRnZlEmMhcoc026TK7r8gZuFeBaicKSE6i5lz6EaRryIxByFqYI/wmA4e3Bv/4oiAPMQxzEeBQHAaqL3@UvbxPbMvCAM4S5pqqaKk@JgmKRtDVFk2RL2rpuQJ5XfwA "Neim – Try It Online")
I have no idea how the heck Neim works. I know what the code here ends up doing, but I have no idea how the language itself works.
Also turns out I messed up the Brainfuck with #19. Due to command conflicts between multiple languages, changing Actually's input to `§` and then coercing it to an int with `≈` was the optimal solution.
[C#](https://tio.run/##fVI9T@QwEK3jX2GFYr0JYZwIGpIYo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XFBergyZu2W98jY7eNP6sOUVecnXJ2yavwsB@MTXAssnqqUFuwGh2deIzzIViG@pZJksy6IN1CpAtRKFxScQdS958JLEo4fBo8xLEP4TAIObw3/9sRu5mIbIjfA4cl1UY79LX97SDU3BfcoQppooSiI/JQqKWZLWFImTLWnrugJ5nps/)
[Java (OpenJDK 8)](https://tio.run/##fVNNb9NAED3bv2LkHuIPnLWtcontLVYIVauQSpQqAuOD47rEId2kiZM4Qb30BBJXjj33woEbd/gnvVb8hjDrNWmqIp698/He7GptzQzieWyOxikbnH5YJ8N4OoWXccY@ygAZy9PJWZyk0OEpwFFvkCY5JCoqwDQXyUsZzTSP8yyBDjDw14RYF1j768d@cZhx9PtvTwQ6b4Ii4eg128/bxXJVsq8xOGy2j0R28mq1XBXlK0qxtthvEqITK935eXP7@ZOj26vbL1c1Gvoc3EaRH4qsBE9lokeSfPf9693N9e/rb5KEl5Ika0d2dSLJIBHybmZZVsCt86K0gcx8Knin4plJ8SCdKIrBfJ/bvafEoc6e3di1TK6wBtMZIUESB0kQHKiqamviRcMDtQxFei@oQq3ye@1hhSjaPmyzRd3E2yc8FP8@MiEhDc3IC6nhmdGTiKIPTRpyjwQNPYNunOd5WIBSCeQqlJI4gRr1xby7WHRxcXQx6i7KJvk3CMnGz/6rT1ppC9CkrRQmaaslu/zv4s0PLNvUoY@RDMgpSk0Rq0IZAne1LaYmgkfUo@06Wbu8icez3hCbuOrl@Sg7hXMcBPU4n2TsfRhBrIkpOBtNygHIfMuFzLMt7gxDq77ueDnN0/P6aJbXx7gzHzI1M5QGYOvUcXK0amwu138A)
[Pepe](https://soaku.github.io/Pepe/#.Q@sM)
]=[ (link not possible, [see #18](https://codegolf.stackexchange.com/a/188266/47990))
[Actually](https://tio.run/##fVA9T8MwEJ3jX2GlQ0JCuCTA0iYuUQlVqwokRBVByFCiSK1URVBRkmZkAomVsXMXBjZ2@CddK35DsOPQD1XwbN@9e@98stwL78e94XCS5wD6Hcb466OZtgcM/f5Vl@P00klDhptG57iTTrJCvaCk3eic8ap7nk2ytNi8lfamzQaAAnpU@ZzNn59MxcjmL48S8W0GFoPA9nlVgJUIlEBAi/fXxWz6PX0TBPooQdArqKaAgLAAcD3Wdd1h0TwpooNim3DdLPVYI3SQAqKoxrbNYv0QTGLWjeqBrjEnrsZKDOCEPSd0nJYsy8YO3zQwIheUlytD5m5Zr7zNDt60Pmx5RV7y9Qmb5u9CAD7xtcDyiWppwW5AaPY14rNMBeJbKlkmy7JoA7UKUK1EYfEJRN1LHrwk8ehh8CjzEoT/BMDg9uhff@RGLqYhciM8ilwX1djv0pe3dENTcJ8yhKkmipLIT4mCYpakNUXiZEvauq5Anu//AA)
[Answer]
# 21. [Flobnar](https://github.com/Reconcyl/flobnar), [A010709](https://oeis.org/A010709) (All 4s)
```
//0q ÷GxJiiiiihhZUUUUUUUNYAxcccccbCLDLxyzUUUUUTxyzJCLOzUUUUUURzyzxyzxyzcccccbbCLxGC//*/0e#§≈2*1z⌂'>[=====[===]]=[[==========]]=[
/*]
박망희 0#
;*/
//\u000A\u002F\u002A
n=>//\u002A\u002Fn->
/**/""+n==""+n?5/2>2?1:40-/**/n:n*n//AcaAcAAI(((1)(1)(1)1)((1)(((1)1)1)1)(((1)(1)1)(((1)((1)1)(1)1)1)(((1)(1)(1)(1)1)(((1)(1)((1))(1)1)((1)((1)1)(1)1)(((1)1)(1)(1)1)1)(((1)1)(1)1)(((1)1)1)1)1)1)
//[>[-]<[>+<-],]>>+<[->[>>+<<-]>[<+>-]>[<+>-]<<<]>>>>++++++[<++++++++>-]<<[>+<-]>+.wvWwwWWwwwwwwWwWWWw
//ip!4@
//rEeE rEeeEe reEE
;/**/
//I01-* h
//
;/*""'"""'""""""""""'"""" "'""'"""""""'"""'""""'"'"""""""'"""'""""""'"""'""""""""""*/
```
[Try it online!](https://tio.run/##fVA9T8MwEJ3jX2HCkJAQzonK0iYuUQlVqwokRBVByNBWQa2EAlSCphmZQGJl7NyFgY0d/knXit8Q7Dj0QxU823fv3jufLF9d33TjzjDLAMgdxvjro540Bxz9/kVb4PjcTXoc3VrrsJWM01w9Y6RZa52Iqn2ajtMk36KV9Sb1GoAGJNr@nM6enyzNTGcvjwoNHA4ew9AJRJWDlwi0UELz99f5dPI9eZMk9ihJItuoooGEsARweU8IcXm0jvLootihQrcKPTYoG6SBLOux4/BY3QeLWlWzXCIGd@JyrMUAbq/j9ly3oaqquSM2C5yoORXl0lCFW9RLb71DNK0OW1xRF3x1wrr5uxBAQAMjtAOq20a4G1KWA4MGPDOBBrZOF8m2bdbArBxMK5BbYgLV90YP/mjks8PhM@aPEP4TAIPbrdLBvx1DL/IwC5EX4WHkeajC/5e9vUFMQ8N9xhBmmiwrsjgFcop5UlYURZANaeO6Bln2Aw "Flobnar – Try It Online")
Flobnar starts at `@` and expands outwards evaluating items as the rules dictate (`@` evaluates to whatever's on its left, `4` evaluates to `4`, `+` evaluates to whatever's on the left summed with whatever's on the right, etc). As the placement of the `@` only comes into contact with Runic, a simple `!` prevents alteration of Runic's stack.
Given that Flobnar's input metric is "one byte" and goes into an infinite loop if there are no bytes to read, I decided not to bother with anything more complex.
### Previous languages
[C#](https://tio.run/##fVJNT9tAED17f8XWHLKxMbO24ILtBSsYBIqoVDWyiusDWI6yl6UNHzE5cmolrhw5c@HQW@/tP@Ea8RvSWW8IiSL6vPvmzZvZ0cra8sIrL@R0/0qVkVSX67hFP54C8O@U0r@/D@ojqTEYnPQMjr8kdalx1unudeubceN@RnHU6X40We/T@GZcN8u0Ym990AFwgFdrfx6ff/4IHH/8fHfbEnmsobko4txkDXRKwCksMvl1P3l8eHl4siy8lGXxNRI6YBFqAXy94pwnmoP9hhOiYmH8YOYrT@AgB2zbVXGseWcLAhHs@Nub3NMVta0cBZCUp0mZJIeMMb9tFpIWrJEmfSswU53lb7XlDtO0OGx@hM314oTl4utHAHKRe0WUCzfyivVCYMw9keuIhsgjV8xDFEXYgKUG6M3QlMwE4W6MrrPRKMOtkaHKRoS@CwD57cPm7n87hmmVUqQ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eAxh3GOPP907aG3NE0dVA4PTSTUccN@3@cT@dZYV6wUiv3T8T1eA8m2VpsUUr6007bQAVjLDysVg@PVqqmS2fH6qEOhw8BoFDRVWAlwjUQEKrt5fVYv41f5Uk9ihJMiqoqYKEsARwPTUMw@XROimii2KHCN0q9VgnbJAKsqzFjsNjqw4WsVpmo2bo3IkbsRoDuKOhO3LdrqIo5r7YLHCiFFSUG0MRbllvvN8doml72PqKsubbE36bPwsBUEL1wKZEs/XgICAsU51QnplAqK2RdbJtmzUwqwDTShSWmEC0w@TeTxKfHQ6fMT9B@E8AjG/3akf/dky80MMshF6IJ6HnoSb/X/b2rmHqKo4YQ5hpslyVxSlRUMxTdUupCrIj7VxXIc/r3w)
] |
[Question]
[
[Naismith's rule](https://en.wikipedia.org/wiki/Naismith%27s_rule) helps to work out the length of time needed for a walk or hike, given the distance and ascent.
Given a non-empty list of the altitude at points evenly spaced along a path and the total distance of that path in metres, you should calculate the time needed according to Naismith's rule.
Naismith's rule is that you should allow one hour for every five kilometres, plus an additional hour for every 600 metres of ascent.
Input must be taken in metres, which is guaranteed to consist of non-negative integers, and output should consistently be either hours or minutes (but not both), and must be able to give decimal numbers where applicable (floating point inaccuracies are OK).
For example, given:
```
[100, 200, 400, 200, 700, 400], 5000
```
For the first two elements `[100, 200]` you have 100 metres of ascent which is 10 minutes. With `[200, 400]` you have 200 metres of ascent which is 20 minutes, `[400, 200]` is not ascending so no time is added for that. `[200, 700]` is 500 metres of ascent which is 50 minutes, and finally `[700, 400]` is not ascending. One extra hour is added for the distance of five kilometres. This totals to **140** minutes or **2.333...** hours.
## Test Cases
```
[0, 600] 2500 -> 1.5 OR 90
[100, 200, 300, 0, 100, 200, 300] 10000 -> 2.8333... OR 170
[40, 5, 35] 1000 -> 0.25 OR 15
[604] 5000 -> 1 OR 60
[10, 10, 10] 2000 -> 0.4 OR 24
[10, 25, 55] 1000 -> 0.275 OR 16.5
```
[Answer]
# [R](https://www.r-project.org/), ~~44~~ ~~43~~ 42 bytes
```
function(A,D)sum(pmax(0,diff(A)),D*.12)/10
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NRx0WzuDRXoyA3sULDQCclMy1Nw1FTU8dFS8/QSFPf0OB/mkayhqGBgY4REJtAaXMIW1PH1ABI/gcA "R – Try It Online")
*-1 byte by using `pmax` as multiple other answers do*
Takes inputs as `A`scent and `D`istance, and returns the time in minutes.
```
function(A,D) # take Ascent and Distance
diff(A) # take successive differences of ascents
pmax(0, ) # get the positive elements of those
D*.12 # multiply distance by 0.12
sum( , ) # take the sum of all elements
/10 # and divide by 10, returning the result
```
[Answer]
# JavaScript (ES6), 50 bytes
*Saved 1 byte thanks to [Giuseppe's answer](https://codegolf.stackexchange.com/a/170076/58563) (dividing by 10 at the end of the process)*
Takes input as `([altitudes])(distance)`. Returns the time in minutes.
```
a=>d=>a.map(p=n=>d-=(x=p-(p=n))<0&&x,d*=.12)&&d/10
```
[Try it online!](https://tio.run/##hZBRC8IgFIXf@xV7Eo1tXm0ugtwfiR5kblGsKS1i/96u1UurleiFI@c7HO7J3MxQX47@mvXONqHVwejK6srkZ@Op1z2qTNNR@ywqxrZAyJjapc6FZIRYLiDUrh9c1@SdO9CW7iBNSoA9o1IBMJbMH86TDSwmuAAMkHGs4sD79oO5qB/BiIv1B1@gT6FVvZzzDSKvpngJBYIK/lR/4uWX9rFvfHEBv1IQl0W4Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
¥ʒ0›}OT÷s₄;6//+
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0NJTkwweNeyq9Q85vL34UVOLtZm@vvb//9GGBgY6CkYgwgTOModyY7lMDQwMAA "05AB1E – Try It Online")
Returns time in minutes.
**Explanation**
```
+ # sum of ...
¥ʒ0›}OT÷ # the sum of positive deltas of the altitude divided by 10
s₄;6// # the distance divided by 83.33333333 (500/6, or the amount of meters per minute)
```
[Answer]
## Haskell, ~~47~~ 46 bytes
```
d#l@(_:t)=d/5e3+sum(max 0<$>zipWith(-)t l)/600
```
Returns the time in hours.
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0U5x0Ej3qpE0zZF3zTVWLu4NFcjN7FCwcBGxa4qsyA8syRDQ1ezRCFHU9/MwOB/bmJmnoKtQkFRZl6JgoqCgqEBECgoK0QDGToKRiDCGEQAEYpI7H8A "Haskell – Try It Online")
[Answer]
# Python 2, ~~62~~ 60 bytes
Saved 2 bytes thanks to ovs.
```
lambda e,d:sum((a-b)*(a>b)for a,b in zip(e[1:],e))*.1+d*.012
```
[Try it online!](https://tio.run/##TVBBjoMwDDzDK6yeEtZbJTShWqTuR2gOQQQViVJE0pXaz7M4KrSHWB7PeEbO@AiX25DP7ek89/ZaNxYcNqW/Xxmz3zXPmP2teXubwGIN3QDPbmSukqVBx3m2l19Nthcyn4PzwcMJKlZJIRByKmrrji9oELSgXirBMU0SYNWCisjkmpifjXgbHajQ1ufERBzNjtuOWqBeaP1il6pXrhBqyy8@UkhJz0RvSlDcpCld7fo/hKbzCJPz9z7QF8RTyzQZp24I0LJVwxF257BbpfM/ "Python 2 – Try It Online")
Returns time in minutes.
```
# add all increasing slope differences together
sum(
# multiply the difference by 0 if a<b, else by 1
(a-b)*(a>b)
# create a list of pairs by index, like [(1,0), (2,1) ...(n, n-1)]
# then interate thru the pairs where a is the higher indexed item and b is the lower indexed item
for a,b in zip(e[1:],e)
)
# * 60 minutes / 600 meters == .1 min/m
*.1
# 60 minutes / 5000 meters = .012 min/m
+d*.012
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~45~~ ~~39~~ 37 bytes
*6 bytes saved thanks to Jo King.*
*2 bytes saved thanks to nwellnhof.*
(Thanks to both of them, this no longer looks anything like my original submission :—).)
```
*.&{sum (.skip Z-$_)Xmax 0}/600+*/5e3
```
[Try it online!](https://tio.run/##XU7bSgMxEH3frziglN02TSeXSZVqf0HwSSyL9KEFqQvFRbCI377OJK0uQoYk5zLnHHfvb2noTpjscY9haidf/UeH2vaH1yOe59cvzVO3/QR9LxLRbLrgXRhWVdVvT9jXd44IXiae72V5rw2YiJrVRUdIGfU8Ri/uIEMY/UQpv7E0EhiBz8QvXieKpvmf5nSZHA0sRHW1IaMd2lwB8zWcZTw84paEk51ZajTcgHLKH9KWNury9iaEYK1Vr1uqOYqIRcdFpiqyPi93LLxUbHPBnKpwKpmaotPmlsUXlfdx@AE "Perl 6 – Try It Online")
The first argument is the list with elevations, the second argument is the length of the trek.
The whole thing is a WhateverCode. If an expression is recognized as such, then each `*` is one argument.
So, in `*.&{sum (.skip Z-$_)Xmax 0}/600`, we take the first argument (the first occurence of `*`), and use a block on it with a method-like construct `.&{}`. The block takes one argument (the list), which goes into `$_`, so `.skip` is that list without the first element. We subtract the original array, element by element, from that, using `Z-`. Zipping stops as soon as the shorter list is depleted, which is OK.
We then use the cross product operator `X`. `list X(op) list` creates all possible pairs where the first element is from the left list and the second from the right, and uses the operator `(op)` on them. The result is returned as a Seq (a one-shot list). However, the right list has only one element, 0, so it just does `* max 0`, element by element. That makes sure that we count only ascending parts of the trek. Then we add it up and divide by 600.
Then we add `*/5e3`, where the `*` occurs for the second time, and so it's the second argument, and divide it by 5000. The sum is then the time in hours. (This is more efficient than the time in minutes since we'd need to multiply, and the `*` would need to be separated by a space from the WhateverStar `*`.)
[Answer]
# [oK](https://github.com/johnearnest/ok), 21 bytes
```
{y+/0|1_-':x}..1.012*
```
[Try it online!](https://tio.run/##VYxLDoAgDET3noKd@MMpgiZyGHduWLjVqGfHQvzEZDLpe2nrm8WHMI/7VrU4aGrycT2VIgXSZZhzKQmohY5l3mm40VkARSaZeiZtE30XXSzOzzimtGeYLSubDIu6h3leEkSK05GLcAE "K (oK) – Try It Online") Abusing a parsing bug where `.1.012` is the same as `.1 .012`.
```
.1.012* /a = [0.1 * input[0], 0.012 * input[1]]
{ }. /function(x=a[0], y=a[1])
1_-':x / a = subtract pairs of elements from x
0| / a = max(a, 0) w/ implicit map
y+/ / y + sum(a)
```
-1 thanks to [streester](https://codegolf.stackexchange.com/questions/170075/naismiths-rule/170104?noredirect=1#comment410887_170104).
# [k](https://en.wikipedia.org/wiki/K_(Programming_Language)), 23 bytes
```
{.1*(.12*y)++/0|1_-':x}
```
[Try it online!](https://tio.run/##VYy7DoAgDEV3v4INUMAWQRP5GDcXBleN@u1YiI@Y3Nz0nLSNeokpzeNusBYGbb3JpmnhwEnzcT3TbLgQCKCYzeXeabgxeACQlSDqiawv9F10uSg/E4jKniP2pHwxJFQP7nmJwEqCzSzTBQ "K (oK) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
×.12;I}»0÷⁵S
```
[Try it online!](https://tio.run/##y0rNyan8///wdD1DI2vP2kO7DQ5vf9S4Nfj///@mBgYG/6MNDQx0FIxAhAmcZQ7lxgIA "Jelly – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda a,d:d/5e3+sum(max(0,y-x)/6e2for x,y in zip(a,a[1:]))
```
[Try it online!](https://tio.run/##VY/bCoMwDIavt6fonS2LmFbrQNhepOtFR5UJnnAOdC/fteIcgyQkX/KHZFimR98JV11urjHt3RpiwBY2kWV6er5a2pqZIizxzJK8FFU/khkWUnfkXQ/UgFG80Iy50PDC0FBUcUQgIoRsz85bqYFIRGRAqPIkD0TIDfyEaQje/ohe620280x6LDXwL8sx07Cv56s@uF53INPF8TCMdTeFYyGKrxFU/gvL3Ac "Python 2 – Try It Online")
returns hours as a decimal.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
c+*E.12s>#0.+QT
```
Full program, expects the set of heights as the first argument, distance as the second. Returns the time in minutes.
Try it online [here](https://pyth.herokuapp.com/?code=c%2B%2AE.12s%3E%230.%2BQT&input=%5B100%2C%20200%2C%20400%2C%20200%2C%20700%2C%20400%5D%0A5000&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=c%2B%2AE.12s%3E%230.%2BQT&test_suite=1&test_suite_input=%5B0%2C%20600%5D%0A2500%0A%5B100%2C%20200%2C%20300%2C%200%2C%20100%2C%20200%2C%20300%5D%0A10000%0A%5B40%2C%205%2C%2035%5D%0A1000%0A%5B604%5D%0A5000%0A%5B10%2C%2010%2C%2010%5D%0A2000&debug=0&input_size=2).
```
c+*E.12s>#0.+QT Implicit: Q=input 1, E=input 2
.+Q Take the differences between each height point
>#0 Filter to remove negative values
s Take the sum
*E.12 Multiply the distance by 0.12
+ Add the two previous results
c T Divide the above by 10, implicit print
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21 20~~ 18 bytes
```
.1×.12⊥⎕,-+/0⌊2-/⎕
```
[Try it online!](https://tio.run/##VY4xDsIwDEV3n8JbB5LWCUkHroIyVEJlqQQrFwBUoYoFcQJOwk1ykWAHUlHJsfO/3k/cHQe9O3XDYZ/i9dKn2ryftbFxfMXpofSqoXgbrW5YCZB4xvO92pLCliig9USbCnog0SASCmOIKSttLY1r4QSRvzTfxBcbCf8VZGh@03HWc9x/0znsCD07mZzBllxAXxDFEjwtlpN15AT5q6yBuUCcDw "APL (Dyalog Unicode) – Try It Online")
Traditional function taking input (from right to left) as `1st ⎕`=Heights/Depths, `2nd ⎕`=Distance.
Thanks to @ngn for ~~[being a wizard](https://chat.stackexchange.com/transcript/message/46063185#46063185) one~~ three bytes.
### How it works:
```
.1×.12⊥⎕,-+/0⌊2-/⎕ ⍝ Function;
⎕ ⍝ Append 0 to the heights vector;
2-/ ⍝ Pairwise (2) differences (-/);
0⌊ ⍝ Minimum between 0 and the vector's elements;
+/ ⍝ Sum (yields the negated total height);
- ⍝ Subtract from;
.12⊥⎕, ⍝ Distance × 0.12;
.1× ⍝ And divide by 10;
```
[Answer]
# Java 8, 89 bytes
```
a->n->{int s=0,p=0,i=a.length;for(;i-->0;p=a[i])s+=(p=p-a[i])>0?p:0;return s/10+n/500*6;}
```
[Try it online.](https://tio.run/##lZBNT4QwEIbv/Io5glu6sx9wsII3Ew@e9kg4VBawyJaGljUbwm/HSgjqxUjSN5mPztN5W/Er96vz@5jVXGt44UL2DoA23IgMKtulnRE1LTqZGdFI@jQHD0KaJCV/XnmWJi/zlsAcxDEUEI3cj6Uf9xYAOkKirETEaZ3L0ryxomldJnw/RqYinojU05vIVZHypyTGR3WPrM1N10rQ2x1u5DZAvAvZMDLH7q6619ruPlu4NuIMF2vLPZlWyDJJgXtfFgFON23yC206Q5VtmVq6BeVK1TdX5h8wGeyRhIiDN9f39iXPY/8f3yGSvdXBCsmPbEHa2krmEUlADsEvwipAiMdlOMDVjsh0vv9kIQzOMH4C)
**Explanation:**
```
a->n->{ // Method with integer-array and integer parameter and integer return-type
int s=0, // Sum-integers, starting at 0
p=0, // Previous integer, starting at 0
i=a.length;for(;i-->0; // Loop `i` backwards over the array
; // After every iteration:
p=a[i]) // Set `p` to the current value for the next iteration
s+=(p=p-a[i])>0? // If the previous minus current item is larger than 0:
p // Add that difference to the sum `s`
: // Else:
0; // Leave the sum the same
return s/10 // Return the sum integer-divided by 10
+n/500*6;} // Plus the second input divided by 500 and then multiplied by 6
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 39 bytes
```
0oUl)x@W=UgXÄ -UgX)g ¥É?0:W/#ɘ} +V/(#Ǵ0
```
[Try it online!](https://tio.run/##y0osKPn/3yA/NEezwiHcNjQ94nCLgi6Q0kxXOLT0cKe9gVW4vvLJGbUK2mH6GsrHtxj8/x9taGCgo2AEIoxBBBChiMSCuAYGAA "Japt – Try It Online")
Likely can be golfed quite a bit more.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 17 bytes
```
ü;█y☼òΓ▀ßîP<<╪⌠öß
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=813bdb790f95e2dfe18c503c3cd8f494e1&i=[0,+600]+2500%0A[100,+200,+300,+0,+100,+200,+300]+10000%0A[40,+5,+35]+1000%0A[604]+5000%0A[10,+10,+10]+2000%0A[10.0,+25.0,+55.0],+1000&a=1&m=2)
Takes all inputs as floats, though this saves a byte only in the unpacked version. Likely improvable; just now returning to code golf, I'm somewhat rusty.
### Unpacked (20 bytes) and explanation:
```
0!012*s:-{0>f{A/m|++
0!012* Float literal and multiplication for distance
s Swap top two stack values (altitudes to the top)
:- List of deltas
{0>f Filter: keep only positive changes
{A_m Map: divide all ascents by 10
|++ Add these times to that for horizontal travel
Implicit print
```
`0!012*s:-{0>f{A_:m|++` works for integral inputs for 21 bytes unpacked and still 17 packed.
] |
[Question]
[
Here is the code which I want to shorten.
```
n=input()
while n:
s=raw_input()
x,r,g,b=(int(x) for x in s.split())
a=x/r%2
c=x/g%2
d=x/b%2
r=((a*10+c)*10)+d
if r==0:e="black"
elif r==100:e="red"
elif r==1:e="blue"
elif r==10:e="green"
elif r==101:e="magenta"
elif r==11:e="cyan"
elif r==110:e="yellow"
else:e="white"
print(e)
n-=1
```
Input:
3
```
4643 5913 4827 9752
5583 5357 5120 9400
2025 5475 4339 8392
```
Output:
```
black
yellow
black
```
[Answer]
Instead of `((a*10+c)*10)+d` we can use `((a*2+c)*2)+d` to distinguish the colors.
```
r=((a*2+c)*2)+d
if r==0:e="black"
elif r==4:e="red"
elif r==1:e="blue"
elif r==2:e="green"
elif r==5:e="magenta"
elif r==3:e="cyan"
elif r==6:e="yellow"
else:e="white"
```
Ah, but now we're just distinguishing between values from `0` to `7`, so we can index into an array instead!
```
r=a*4+c*2+d
e=["black","blue","green","cyan","red","magenta","yellow","white"][r]
# or even shorter:
e="black blue green cyan red magenta yellow white".split()[r]
```
Combining with Uriel's changes we get down to 136 bytes **(164 bytes saved)**.
```
exec'x,r,g,b=map(int,raw_input().split());print"black blue green cyan red magenta yellow white".split()[x/r%2*4+x/g%2*2+x/b%2];'*input()
```
[Try it online!](https://tio.run/##Nc1RC4IwFAXgd3/FJQitJO1uNx3SL4mIaReT1hprof5620M9fXAOh@PmcH9ZXBaeuEun3Od93p6e2mWDDbnX43Ww7hOyzf7tzBDdNM7HatUa3T2gNR@G3jNb6GZtwfMNnrpnGzTMbMxrhPE@BF795@ep8Gvcyt1U9FGMtmu8NOn297MsIpFHKYDUQYCssQJVESZEdcwEVUAHLEHJskywRAKSFYEUQkEtFH4B "Python 2 – Try It Online")
[Answer]
For the repetition use an `exec` statement,
`map(int,` for the conversion of string input into numerals,
shorten calculating `r` with `r=a*100+c*10+d`, then put the calculations of each variable (`a`, `c`, `d`) instead of the variable,
and for the conditions use a dictionary with a `get` query.
Finally, mash everything into one line.
Final result (updating):
```
exec'x,r,g,b=map(int,raw_input().split());print({0:"black",100:"red",1:"blue",10:"green",101:"magenta",11:"cyan",110:"yellow"}.get((x/r%2)*100+(x/g%2)*10+x/b%2,"white"));'*input()
```
Bytes saved: **121**.
] |
[Question]
[
# How to spot them
Take a positive integer k. Find its **divisors**. Find the **distinct prime factors of each divisor**. Sum all these factors together. If this number (sum) is a divisor of k (**if the sum divides k**) then, this number k, is a **BIU number**
# Examples
Let's take the number `54`
Find all the **divisors:** `[1, 2, 3, 6, 9, 18, 27, 54]`
Find the **distinct prime factors** of each divisor
**NOTE:** For the case of `1` we take as distinct prime factor `1`
```
1 -> 1
2 -> 2
3 -> 3
6 -> 2,3
9 -> 3
18 -> 2,3
27 -> 3
54 -> 2,3
```
Now we take the sum of **all** these prime factors
`1+2+3+2+3+3+2+3+3+2+3=27`
`27` divides 54 (leaves no remainder)
So, `54` **is** a **BIU number**.
Another (quick) example for `k=55`
**Divisors:** `[1,5,11,55]`
**Sum of distinct prime factors:** `1+5+11+5+11=33`
`33` is **NOT** a divisor of 55, that's why `55` is **NOT** a **BIU number**.
# BIU numbers
Here are the first 20 of them:
>
> 1,21,54,290,735,1428,1485,1652,2262,2376,2580,2838,2862,3003,3875,4221,4745, 5525,6750,7050...
>
>
>
but this list goes on and there are many **BIU numbers** that are waiting to be descovered by you!
# The Challenge
Given an integer `n>0` as **input**, **output** the **nth BIU number**
# Test Cases
***Input->Output***
```
1->1
2->21
42->23595
100->118300
200->415777
300->800175
```
This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'").Shortest answer in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 bytes
```
ÆDÆfQ€SS‘ḍ
1Ç#Ṫ
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//w4ZEw4ZmUeKCrFNT4oCY4biNCjHDhyPhuar///8yMA "Jelly – Try It Online")
Woohoo for builtins (but they mysteriously hide from me sometimes so *-1 byte thanks to @HyperNeutrino*)
**How it Works**
```
ÆDÆfQ€SS‘ḍ - define helper function: is input a BIU number?
ÆD - divisors
Æf - list of prime factors
Q€ - now distinct prime factors
SS - sum, then sum again ('' counts as 0)
‘ - add one (to account for '')
ḍ - does this divide the input?
1Ç#Ṫ - main link, input n
# - starting at
1 - 1
- get the first n integers which meet:
Ç - helper link
Ṫ - tail
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
µNNÑfOO>Ö
```
Uses teh **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//0FY/v8MT0/z97Q5P@//fFAA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
!fṠ¦ö→ΣṁoupḊN
```
[Try it online!](https://tio.run/##ASIA3f9odXNr//8hZuG5oMKmw7bihpLOo@G5gW91cOG4ik7///81 "Husk – Try It Online")
### Explantaion
```
Ṡ¦ö→ΣṁoupḊ Predicate: returns 1 if BIU, else 0.
Ḋ List of divisors
ṁ Map and then concatenate
oup unique prime factors
Σ Sum
ö→ Add one
Ṡ¦ Is the argument divisible by this result
f N Filter the natural numbers by that predicate
! Index
```
[Answer]
# Mathematica, 85 bytes
```
If[#<2,1,n=#0[#-1];While[Count[(d=Divisors)@++n,1+Tr@Cases[d/@d@n,_?PrimeQ,2]]<1];n]&
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 16 bytes
```
u⌠;÷♂y♂iΣu@%Y⌡╓N
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/0Uc8C68PbH81sqgTizHOLSx1UIx/1LHw0dbLf//9GAA "Actually – Try It Online")
Explanation:
```
u⌠;÷♂y♂iΣu@%Y⌡╓N
u⌠;÷♂y♂iΣu@%Y⌡╓ first n+1 numbers x starting with x=0 where
÷ divisors
♂y prime factors of divisors
♂iΣu sum of prime factors of divisors, plus 1
; @% x mod sum
Y is 0
N last number in list
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
e.f|qZ1!%Zhssm{Pd*M{yP
```
[Try it here!](https://pyth.herokuapp.com/?code=e.f%7CqZ1%21%25Zhssm%7BPd%2aM%7ByP&input=54&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)
This is my first ever Pyth solution, I began learning it thanks to the recommendations of some very kind users in chat :-)... Took me about an hour to solve.
## Explanation
```
e.f|qZ1!%Zhssm{Pd*M{yP - Whole program. Q = input.
.f - First Q integers with truthy results, using a variable Z.
qZ1 - Is Z equal to 1?
| - Logical OR.
{yP - Prime factors, powerset, deduplicate.
*M - Get the product of each. This chunck and ^ are for divisors.
m}Pd - Get the unique prime factors of each.
ss - Flatten and sum.
h - Increment (to handle that 1, bah)
%Z - Modulo the current integer by the sum above.
! - Logical negation. 0 -> True, > 0 -> False.
e - Last element.
```
[Answer]
# [Haskell](https://www.haskell.org/), 115 bytes
All of the list comprehensions here can probably be golfed down, but I'm not sure how. Golfing suggestions welcome! [Try it online!](https://tio.run/##PY3BCoMwEETv/YoNeFCqofGsf@Ctx7CHlVosdaMYpTHk31NDoYdhmDcwM5J9D9MUoxNHuw4MDo5GXXowraZATaWVlFiSyNXV7qyTfPAnr6VkLFn4ksxDm3nLvHDB/RpfKUQMfKY/ozTjEAsUIjeVKiLTy0ALy77dt7UzkIEd589pT6YFekjf9Q3jFw "Haskell – Try It Online")
```
x!y=rem x y<1
b n=[a|a<-[1..],a!(1+sum[sum[z|z<-[2..m],m!z,and[not$z!x|x<-[2..z-1]]]|m<-[x|x<-[2..a],a!x]])]!!(n-1)
```
**Ungolfing**
This answer is actually three functions mashed together.
```
divisors a = [x | x <- [2..a], rem a x == 0]
sumPrimeDivs m = sum [z | z <- [2..m], rem m z == 0, and [rem z x /= 0 | x <- [2..z-1]]]
biu n = [a | a <- [1..], rem a (1 + sum [sumPrimeDivs m | m <- divisors a]) == 0] !! (n-1)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~21~~ 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
~~I feel like the `g` function method should lead to a shorter solution, but I can't figure out how it works!~~ Nope! Wrong method! But, in my defense, the `i` method didn't exist at the time.
1-indexed.
```
ÈvXâ mk câ x Ä}iU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yHZY4iBtayBj4iB4IMR9aVU&input=MjA)
```
ÈvXâ mk câ x Ä}iU :Implicit input of integer U
È :Function taking an integer X as argument
v : Test X for divisibility by
Xâ : Divisors of X
m : Map
k : Prime factors
c : Flatten after
â : Deduplicating
x : Reduce by addition
Ä : Add 1
} :End function
iU :Get the Uth integer that returns true
```
] |
[Question]
[
[Taxicab Numbers](https://en.wikipedia.org/wiki/Taxicab_number) or [OEIS A011541](https://oeis.org/A011541) are the least numbers that are able to be represented as \$n\$ different sums of two positive cubed integers, for successive \$n\$.
You'll need to print out the \$n\$th taxicab number. This should work for any \$n\$ in theory.
However, as only 6 taxicab numbers have been discovered so far, there won't be an \$n\$ above 6. The numbers are \$2, 1729, 87539319, 6963472309248, 48988659276962496\$ and \$24153319581254312065344\$.
You're not allowed to hard code these variables, because your program must work for any arbitrary \$n\$ in theory.
[Answer]
# Taxi, 4758 bytes
What better language to calculate taxicab numbers than one that simulates taxicabs?
This is a joke. There are so many better languages. What happened to the last two days of my life?
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Bird's Bench.Pickup a passenger going to Cyclone.Go to Zoom Zoom:n.Go to Cyclone:w.Pickup a passenger going to Rob's Rest.Pickup a passenger going to Cyclone.Go to Bird's Bench:n 1 r 2 r 1 l.Go to Rob's Rest:n.Go to Cyclone:s 1 l 1 l 2 l.[a]Pickup a passenger going to Firemouth Grill.Pickup a passenger going to The Underground.Go to Zoom Zoom:n.Go to Firemouth Grill:w 3 l 2 l 1 r.Go to The Underground:e 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[b]Go to Firemouth Grill:s 1 r.[c]Pickup a passenger going to Cyclone.Go to Cyclone:w 1 l 1 r 2 r.Pickup a passenger going to Cyclone.Go to Zoom Zoom:n.Go to Cyclone:w.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Trunkers.Go to Trunkers:s 1 r 2 l.Go to Firemouth Grill:e 1 l 1 r.Switch to plan "e" if no one is waiting.Switch to plan "c".[e]Go to Trunkers:w 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.[f]Go to Trunkers:s 1 l.Switch to plan "g" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Cyclone:w 2 r.Pickup a passenger going to Cyclone.Go to Zoom Zoom:n.Go to Cyclone:w.Go to Sunny Skies Park:n 1 r.Switch to plan "f".[g]Go to Cyclone:w 2 r.Switch to plan "h" if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Zoom Zoom:n.Go to Firemouth Grill:w 3 l 2 l 1 r.Go to Trunkers:w 1 l 1 r.Switch to plan "g".[h]Go to Sunny Skies Park:n 1 r.Switch to plan "i" if no one is waiting.Pickup a passenger going to Cyclone.Go to Firemouth Grill:s 1 l 1 l 1 r.Pickup a passenger going to Addition Alley.Go to Cyclone:w 1 l 1 r 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Trunkers.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Go to Addition Alley:w 2 r 2 r 1 r.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 r 1 l 1 r.Go to Cyclone:w 1 l 1 r 2 l.Switch to plan "h".[i]Go to Trunkers:s 1 l.Pickup a passenger going to Knots Landing.Go to Knots Landing:e 1 r 2 l 5 r.Go to Trunkers:w 1 l 3 r 1 l.Switch to plan "j" if no one is waiting.Go to Firemouth Grill:e 1 l 1 r.Switch to plan "e".[j]0 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 l.Pickup a passenger going to Addition Alley.[k]Go to Rob's Rest:w 1 r 2 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Rob's Rest.Pickup a passenger going to Equal's Corner.Go to Zoom Zoom:n.Go to Rob's Rest:w 2 l 2 r 1 r.Go to Narrow Path Park:s 1 l 1 l 1 r 1 r 2 l 5 l.Switch to plan "o" if no one is waiting.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l 1 r 2 l 1 l.Switch to plan "l" if no one is waiting.Pickup a passenger going to Knots Landing.1 is waiting at Starchild Numerology.Switch to plan "m".[l]0 is waiting at Starchild Numerology.[m]Go to Starchild Numerology:n 1 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Addition Alley.Go to Knots Landing:n 1 r 2 r 1 l.Go to Starchild Numerology:w 1 l 3 r 1 l 1 l 2 l.Switch to plan "k".[o]0 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 1 r 2 l 1 l 3 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Go to Addition Alley:n 4 r 1 r 1 r.Pickup a passenger going to Equal's Corner.Go to Bird's Bench:n 1 l 1 l 1 l 2 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Bird's Bench.Pickup a passenger going to Equal's Corner.Go to Bird's Bench:n 1 r 2 r 1 l.Go to Equal's Corner:n 1 r 1 r.Switch to plan "p" if no one is waiting.Go to Starchild Numerology:n 1 r.Go to Rob's Rest:w 1 r 2 l 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 l 1 r 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.Switch to plan "z".[p]1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 r.Pickup a passenger going to Addition Alley.Go to Rob's Rest:w 1 r 2 l 1 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:s 1 l 1 l 2 r 1 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Rob's Rest.Pickup a passenger going to Cyclone.Go to Rob's Rest:n 1 r 2 r 1 r.Go to Cyclone:s 1 l 1 l 2 l.Switch to plan "a".[z]
```
[Try it online!](https://tio.run/##vVjLjtowFP2VKzbdRQXaDbth1JlF2yka2k2jLExiEg/GpnailPl56iQGEsd5groAhBPfx7nnHj9i9JecTs8cYg4rLmP4sd0SHy9SmAJVH5H9Oivi75IDIDggKTELsYCQExZms35GGJZog@mWyAiLo1MYM4cX8myx1drj0aecYW1E/1swPZfCrGP@kojgg4QlZn40wNFvzvf514IZrtNWK698o7y9YhkPcFaOMU9NZGnlQBcvXK3WwpElJKjjIq/N7RMReM@TOIJnQWh3GX@xAItQ8IQFjbgYNhVR5kUweWmvtS/ZWuA8t3VKYj/Knh8oYjDZTIBsgXFQeQGRkCISq2BG0UPHUPOBJo678eyRyzxi1/eGO7x2x2wQn8fS7HtCY3KgxEcx4QzWcf77n6YUgdofaj5m9P3UpRMiYTss5Jkj@m9Rhrx49jLhi26YxcUNBDLf8xUJsGe4TW@Qo7Sz7OuEsSOsdwRLWCGx0wbM4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BCZb@lUT8Ezs6mTsbtvVaHdIciS6p12Fn9r@INvBA/gpr3OnhTZdxzxk2L4a0q8fsXNy4SfPZ44XhwdOeaJ8aTX/KU@2JY6fvaRsFWxUmA5PYc6k9IMZ8dvEiQFswQLze9TeiyQ5k4d4yPvdcyDTSpIcedJDmdrn5KO9TYFxFDtx2ljPOIAM9lfrf5lEG2Yl2ro5FO2ZlE@BXKFiNMgntDqqslk2ChTOuMXUnyt7q5TfReVPWL/LUecWgZvJ3vhgYZ15KNX/y@QDHs1FwDRf/37azNOal@BztTr51lNcZWUaMm@2Svb0g3h4yyI24TD49q35fw)
Note: TIO can handle an input of `1` but `2` and above cause a timeout issue. I wrote a little snippet to print the value being checked every iteration and it only got up to `137` before it timed out. If someone who knows what they're doing could run it through an interpreter (the homepage links to a [C++ version](https://bigzaphod.github.io/Taxi/taxi.cpp)) to verify higher values, I'd appreciate it. It may take a very long time to run.
Ungolfed with comments:
```
[ FIND THE NTH TAXI CAB NUMBER ]
[ https://en.wikipedia.org/wiki/Taxicab_number ]
[ Inspired by https://codegolf.stackexchange.com/q/73827/38183 ]
[ A taxi cab number T(n) is the smallest number that can be made from the sum ]
[ of two positive cubes in n different ways. For example, T(1) = 2 because ]
[ 2 = 1^3 + 1^3. That is the only way to make 2 by summing positive cubes. No ]
[ solution exists for 1 so 2 is T(1). T(2) = 1729 = 1^3 + 12^3 = 9^3 + 10^3. ]
[ This program takes n as input and finds T(n). The (bad) psuedocode is: ]
[ ]
[ S = STDIN; // Use Bird's Bench ]
[ T = STDIN; // Use Rob's Rest. Saves bytes and T(n) > n is always true. ]
[ while (true) { ]
[ // Fill an array (Firemouth Grill) with the numbers 1 through T ]
[ // This will make it much easier to compute the cubes because a taxi ]
[ // can only carry three passengers at a time. ]
[ for (i = T; i > 0; i--) { A.push(i) } ]
[ // Fill an array (Trunkers) with the cubes of all integers 1 through T ]
[ for (i = T; i > 0; i--) { B.push(i ^ 3) } ]
[ // Fill an array (Sunny Skies Park) with each possible sum of cubes ]
[ while (B(0) != null) { ]
[ // Make copies of the next value to add to each remaining value ]
[ C.push(B(0)); ]
[ while (B(0) != null) { ]
[ C.push(C(0)); ]
[ D.push(B(0)); ]
[ B.shift(); ]
[ } ]
[ // Store each possible sum with this cube ]
[ while (C(0) != null) { ]
[ E.push(C(0) + D(0)); ]
[ B.push(D(0)); ]
[ C.shift; ]
[ D.shift; ]
[ } ]
[ } ]
[ // Check each possible sum to see if it equals T ]
[ N = 0; ]
[ while (D(0) != null) { ]
[ if (D(0) = T) { N++ } ]
[ D.shift(); ]
[ } ]
[ // If we found the desired number of sums, ouput and break ]
[ // Otherwise, go to the next T and keep going ]
[ if (N = S) { ]
[ print(T); ]
[ break; ]
[ } else { ]
[ T++; ]
[ } ]
[ } ]
[ ]
[ S = STDIN; // Use Bird's Bench ]
[ T = STDIN; // Use Rob's Rest. Saves bytes and T(n) > n is always true. ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left 2nd right.
Pickup a passenger going to Bird's Bench.
Pickup a passenger going to Cyclone.
Go to Zoom Zoom: north.
Go to Cyclone: west.
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: north 1st right 2nd right 1st left.
Go to Rob's Rest: north.
[ // Fill an array (Firemouth Grill) with the numbers 1 through T ]
[ // This will make it much easier to compute the cubes because a taxi ]
[ // can only carry three passengers at a time. ]
[ for (i = T; i > 0; i--) { A.push(i) } ]
Go to Cyclone: south 1st left 1st left 2nd left.
[a]
Pickup a passenger going to Firemouth Grill.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Firemouth Grill: west 3rd left 2nd left 1st right.
Go to The Underground: east 1st left.
Switch to plan "b" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 3rd left 2nd left.
Switch to plan "a".
[b]
[ // Fill an array (Trunkers) with the cubes of all integers 1 through T ]
[ for (i = T; i > 0; i--) { B.push(i ^ 3); } ]
Go to Firemouth Grill: south 1st right.
[c]
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st left 1st right 2nd right.
Pickup a passenger going to Cyclone.
Go to Zoom Zoom: north.
Go to Cyclone: west.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Trunkers.
Go to Trunkers: south 1st right 2nd left.
Go to Firemouth Grill: east 1st left 1st right.
Switch to plan "e" if no one is waiting.
Switch to plan "c".
[e]
[ // Fill an array with each possible sum of cubes ]
[ while (B(0) != null) { ]
[ // Make copies of the next value to add to each remaining value ]
[ C.push(B(0)); ]
[ while (B(0) != null) { ]
[ C.push(C(0)); ]
[ D.push(B(0)); ]
[ B.shift(); ]
[ } ]
[ Setup Cyclone with a copy of the first value ]
Go to Trunkers: west 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st right.
[f]
[ Move any remaining values to Sunny Skies Park, duplicating Cyclone each time ]
Go to Trunkers: south 1st left.
Switch to plan "g" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Cyclone.
Go to Zoom Zoom: north.
Go to Cyclone: west.
Go to Sunny Skies Park: north 1st right.
Switch to plan "f".
[g]
[ // Store each possible sum with this cube ]
[ while (C(0) != null) { ]
[ E.push(C(0) + D(0)); ]
[ B.push(D(0)); ]
[ C.shift; ]
[ D.shift; ]
[ } ]
[ Move everything at Cyclone to Firemouth Grill ]
Go to Cyclone: west 2nd right.
Switch to plan "h" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Zoom Zoom: north.
Go to Firemouth Grill: west 3rd left 2nd left 1st right.
Go to Trunkers: west 1st left 1st right.
Switch to plan "g".
[h]
[ Copy Sunny Skies Park to Trunkers and add it to Firemouth Grill ]
Go to Sunny Skies Park: north 1st right.
Switch to plan "i" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Firemouth Grill: south 1st left 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to Cyclone: west 1st left 1st right 2nd right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Trunkers.
Go to Zoom Zoom: north.
Go to Trunkers: west 3rd left.
Go to Addition Alley: west 2nd right 2nd right 1st right.
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park: north 1st right 1st left 1st right.
Go to Cyclone: west 1st left 1st right 2nd left.
Switch to plan "h".
[i]
[ } // End of 'while (B(0) != null)' up near plan "e" ]
Go to Trunkers: south 1st left.
Pickup a passenger going to Knots Landing.
Go to Knots Landing: east 1st right 2nd left 5th right.
Go to Trunkers: west 1st left 3rd right 1st left.
Switch to plan "j" if no one is waiting.
Go to Firemouth Grill: east 1st left 1st right.
Switch to plan "e".
[j]
[ // Check each possible sum to see if it equals T ]
[ N = 0; ]
[ while (D(0) != null) { ]
[ if (D(0) = T) { N++; } ]
[ D.shift(); ]
[ } ]
[ Set N = 0 ]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd left.
Pickup a passenger going to Addition Alley.
[k]
[ Pickup T ]
Go to Rob's Rest: west 1st right 2nd left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st left 1st left 2nd left.
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Equal's Corner.
Go to Zoom Zoom: north.
Go to Rob's Rest: west 2nd left 2nd right 1st right.
Go to Narrow Path Park: south 1st left 1st left 1st right 1st right 2nd left 5th left.
Switch to plan "o" if no one is waiting.
[ Check the next value against T ]
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: west 1st left 1st right 2nd left 1st left.
Switch to plan "l" if no one is waiting.
[ It's a match so N = N + 1 ]
Pickup a passenger going to Knots Landing.
1 is waiting at Starchild Numerology.
Switch to plan "m".
[l]
[ It's not a match so N = N + 0 ]
0 is waiting at Starchild Numerology.
[m]
Go to Starchild Numerology: north 1st right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Addition Alley.
Go to Knots Landing: north 1st right 2nd right 1st left.
Go to Starchild Numerology: west 1st left 3rd right 1st left 1st left 2nd left.
Switch to plan "k".
[o]
[ // If we found the desired number of sums, ouput and break ]
[ // Otherwise, go to the next T and keep going ]
[ if (N = S) { ]
[ print(T); ]
[ break; ]
[ } else { ]
[ T++; ]
[ } ]
[ T is still going to Equal's Corner so just get rid of it ]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 1st right 2nd left 1st left 3rd left.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: west 1st left.
[ N is still going to Addition Alley so redirect it to Equal's Corner ]
Go to Addition Alley: north 4th right 1st right 1st right.
Pickup a passenger going to Equal's Corner.
[ Compare N = S ]
Go to Bird's Bench: north 1st left 1st left 1st left 2nd right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st right 1st left 2nd left.
Pickup a passenger going to Bird's Bench.
Pickup a passenger going to Equal's Corner.
Go to Bird's Bench: north 1st right 2nd right 1st left.
Go to Equal's Corner: north 1st right 1st right.
Switch to plan "p" if no one is waiting.
[ It's a match! The value we want is T, waiting at Rob's Rest. ]
[Go to Rob's Rest:n 3 l 1 r.]
Go to Starchild Numerology: north 1st right.
Go to Rob's Rest: west 1st right 2nd left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st left 1st right 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
Switch to plan "z".
[p]
[ It's not a match. T = T + 1 and start over. ]
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: north 1st right.
Pickup a passenger going to Addition Alley.
Go to Rob's Rest: west 1st right 2nd left 1st right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: south 1st left 1st left 2nd right 1st right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Cyclone.
Go to Rob's Rest: north 1st right 2nd right 1st right.
Go to Cyclone: south 1st left 1st left 2nd left.
Switch to plan "a".
[z]
[ Terminate program with 10 less bytes than going back to the Taxi Garage ]
```
[Answer]
## Haskell, 60 bytes
```
f n=[k|k<-[0..],n<=sum[1|x<-[1..k],y<-[1..x],x^3+y^3==k]]!!0
```
Pretty straightforward. Counts how many ways a number `k` can be written as a sum of two cubes. Filters for `k`'s such that this number is at least `n`, and takes the first one.
An equal-length method with `until`:
```
f n=until(\k->n<=sum[1|x<-[1..k],y<-[1..x],x^3+y^3==k])(+1)0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Œċ*3§ċ⁸=ð1#
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZLEiyozwqfEi@KBuD3DsDEj////Mg "Jelly – Try It Online")
This is *ridiculously* slow, timing out for \$n > 1\$
## How it works
```
Œċ*3§ċ⁸=ð1# - Main link. Takes n on the left
ð - Group the previous links into a dyad f(k, n):
Œċ - All pairs from [1, 2, ..., k]
*3 - Cube each
§ - Sum of each
ċ⁸ - Count occurrences of k
= - Does that equal n?
1# - Find the first k, starting with n, which returns true under f(k, n)
Starting with k = n is fine, as k > n for all n
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
∞εL3mãOÙN>¢}Ik>
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8c1t9jHMPL/Y/PNPP7tCiWs9su///DQE "05AB1E – Try It Online")
The program timeouts for \$n>1\$ , but the algorithm works.
[Answer]
## ARM Thumb-2, ~~52~~ 48 bytes for theoretical algorithm, 50 bytes for overflow safe version until n == 3
This one is hilariously inefficient, and only works for n == 3 if we assume infinite integers.
Raw machine code:
```
b570 2101 0004 000a fb02 f502 4355 0013
fb03 f603 fb06 5603 428e d101 3c01 d005
3b01 d8f5 3a01 d1ef 3101 e7eb 0008 bd70
```
Assembly:
```
.text
.arch armv6t2
.thumb
.globl taxi
.thumb_func
taxi:
@ Nickname some registers for clarity
n .req r0
candidate .req r1
i .req r2
j .req r3
matches_left .req r4
i_cubed .req r5
j_cubed_sum .req r6
push {r4-r6, lr}
@ Start with a candidate of 1 (even though it's impossible)
movs candidate, #1
.Lcandidate_loop:
@ reset match counter
movs matches_left, n
@ start checking cubes
@ Behold! The world's most inefficient loop!
@ Takes 1.8 seconds for n = 2 on actual hardware. And remember, this is O(n^3). XD
@ It also is very vulnerable to integer overflow and returns the incorrect
@ result for n == 3. However, with sufficiently large integers, it would
@ theoretically work fine.
@ for (i = candidate; i != 0; --i)
movs i, candidate
.Li_loop:
@ i_cubed = i * i * i
mul i_cubed, i, i @ wide insn
muls i_cubed, i
@ for (j = i; --j;)
movs j, i
.Lj_loop:
@ j_cubed_sum = j * j * j + i_cubed
mul j_cubed_sum, j, j @ wide insn
mla j_cubed_sum, j_cubed_sum, j, i_cubed @ wide insn
@ Compare to the candidate
cmp j_cubed_sum, candidate
bne .Lno_match
.Lmatch:
@ If it is the same, decrement matches_left
subs matches_left, #1
@ Exit if we found all of the matches
bne .Lexit
.Lno_match:
@ Decrement j and loop while non-zero.
subs j, #1
bhi .Lj_loop
.Lnext_i:
@ Decrement i, and loop if it is not zero
subs i, #1
bne .Li_loop
.Lnext_candidate:
@ Next candidate.
adds candidate, #1
b .Lcandidate_loop
.Lexit:
movs r0, candidate
pop {r4-r6, pc}
```
## Explanation
C function signature:
```
uint32_t taxi(uint32_t n);
```
Has a wonderful O(n^3) complexity combined with billions of redundant iterations thanks to it looping backwards, but it works for n == 1 and n == 2 in reasonable time on hardware. It doesn't properly calculate n == 3 because of integer overflow.
It is a very naïve triple nested loop that is **incredibly** inefficient.
Goes through every candidate, then tests every `i` for `i <= candidate`, then tests every `j` for `j <= i`, each going backwards. It calculates cubes live, and is **horrendously** redundant and inefficient....but it is small and that is what counts.
Equivalent C:
```
uint32_t taxi(uint32_t n)
{
for (uint32_t candidate = 1; ; candidate++) {
uint32_t matches_left = n;
for (uint32_t i = candidate; i != 0; --i) {
uint32_t i_cubed = i * i * i;
for (uint32_t j = i; j != 0; --j) {
uint32_t j_cubed_sum = j * j * j + i_cubed;
if (j_cubed_sum == candidate) {
--matches_left;
if (matches_left == 0) {
return candidate;
}
}
}
}
}
```
## Overflow-safe version
Here is a much faster one (but still slow) at 50 bytes which does not overflow before `n == 3`:
```
b570 2101 0004 2201 fb02 f502 4355 0013
fb03 f603 fb06 5603 428e d101 3c01 d006
3b01 d8f5 3201 428d d3ee 3101 e7ea 0008
bd70
```
```
.text
.arch armv6t2
.thumb
.globl taxi_safe
.thumb_func
taxi_safe:
@ Nickname some registers for clarity
n .req r0
candidate .req r1
i .req r2
j .req r3
matches_left .req r4
i_cubed .req r5
j_cubed_sum .req r6
push {r4-r6, lr}
@ Start with a candidate of 1 (even though it's impossible)
movs candidate, #1
.Lcandidate_loop:
@ reset match counter
movs matches_left, n
@ start checking cubes
@ This version loops forwards from 1 and short circuits logically.
@ It can correctly calculate n == 3.
@ for (i = 1; i * i * i < candidate; i++) but the check is after the loop
movs i, #1
.Li_loop:
@ i_cubed = i * i * i
mul i_cubed, i, i @ wide insn
muls i_cubed, i
@ for (j = i; --j;)
movs j, i
.Lj_loop:
@ j_cubed_sum = j * j * j + i_cubed
mul j_cubed_sum, j, j @ wide insn
mla j_cubed_sum, j_cubed_sum, j, i_cubed @ wide insn
@ Compare to the candidate
cmp j_cubed_sum, candidate
bne .Lno_match
.Lmatch:
@ If it is the same, decrement matches_left
subs matches_left, #1
@ Exit if we found all of the matches
bne .Lexit
.Lno_match:
@ Decrement j and loop while non-zero.
subs j, #1
bhi .Lj_loop
.Lnext_i:
@ Increment i, and loop if i_cubed is less than candidate.
adds i, #1
cmp i_cubed, candidate
blo .Li_loop
.Lnext_candidate:
@ Next candidate.
adds candidate, #1
b .Lcandidate_loop
.Lexit:
movs r0, candidate
pop {r4-r6, pc}
```
This one is significantly faster, and does not overflow before n == 3.
Instead of looping `i` backwards from `candidate`, we loop forwards from `1`, and also short circuit when `i * i * i >= candidate`, although we do run the inner loop with this condition first so it is still very redundant.
] |
[Question]
[
Inspired by <https://puzzling.stackexchange.com/q/626>
---
In your adventures you arrive at a series of 7 bridges you have to cross. Underneath each bridge lives a troll. In order to cross the bridge, you must first give the troll a number of cakes as a percentage of the number of cakes you are carrying. Because these are kind trolls, they will give back a certain number of cakes to you.
At the start of each day, the local troll king sets the percent cake tax that each traveler must pay, and the troll cake refund -- the number of cakes that each troll must give back to travelers.
Your job is to calculate the minimum number of cakes needed to pass all 7 troll bridges for the given conditions on that day.
### Assume:
1. Two input parameters: percent cake tax (integer from 0 to 100), and troll cake refund.
2. No one, not even trolls, wants a cake partially eaten by another troll. If you are left with a fraction of a cake the troll gets it.
3. If a troll accepts a cake tax, but then has to give you back all of the cakes (is left with the same or fewer cakes than before), it will become angry and eat you and your cakes.
4. Every troll must keep at least one complete cake.
5. You can only carry a maximum of 100 cakes.
6. You need to end the day where you are currently located or on the other side of all 7 bridges.
### Challenge:
Write a complete program to output the minimum number of cakes to travel for the current day or zero if it's not possible to safely travel today -- you will wait to see what the numbers are tomorrow.
Input should be passed as stdin, command line arguments or file input.
Shortest code (byte count) wins.
### Example:
25% cake tax, 2 troll cake refund.
start with 19 cakes
before troll 1: (19 \* 0.75) = 14.25
after troll 1: (14 + 2) = 16
before troll 2: (16 \* 0.75) = 12
after troll 2: (12 + 2) = 14
etc.
19 cakes -> 16 -> 14 -> 12 -> 11 -> 10 -> 9 -> 8
18 cakes -> 15 -> 13 -> 11 -> 10 -> 9 -> 8 -> 8 (rule 3)
For 18 cakes, the last troll wouldn't get to keep any cakes. Therefore, the minimum number of cakes for a 25%/2 day is 19.
```
input: 25 2
output: 19
```
### Example 2:
90% cake tax, 1 troll cake refund
100 cakes -> 11 -> 2 -> 1 (rule 4)
The third troll didn't get to keep any cake. Therefore it is not possible to travel on a 90%/1 day even starting with the maximum number of cakes.
```
input: 90 1
output: 0
```
---
### Data
Put together a quick graph of input and output values. I was surprised this wasn't "smooth" (like a bell curve or similar); there are several noticeable islands.

Data for those interested. Columns are divided into 5% intervals, rows are units of 1 cake refund intervals (excel rotated the image). You can see there can't be a refund higher than 28 cakes.
```
27, 17, 13, 14, 15, 18, 20, 24, 53, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
47, 27, 20, 19, 19, 19, 24, 39, 48, 68, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0
67, 37, 28, 24, 23, 28, 27, 29, 50, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
87, 47, 33, 29, 27, 28, 31, 44, 37, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 57, 40, 34, 31, 29, 34, 34, 62, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 67, 48, 39, 35, 38, 37, 49, 57, 76, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 77, 53, 44, 39, 38, 47, 39, 59, 78, 94, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 87, 60, 49, 43, 39, 40, 54, 46, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 97, 68, 54, 47, 48, 44, 44, 71, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 73, 59, 51, 48, 47, 59, 73, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 80, 64, 55, 49, 51, 49, 68, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 88, 69, 59, 58, 54, 64, 70, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 93, 74, 63, 58, 57, 54, 57, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 100, 79, 67, 59, 67, 69, 82, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 84, 71, 68, 60, 59, 77, 94, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 89, 75, 68, 64, 74, 79, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 94, 79, 69, 67, 64, 66, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 99, 83, 78, 71, 79, 91, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 87, 78, 74, 69, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 91, 79, 77, 84, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 95, 88, 87, 74, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 99, 88, 80, 89, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 89, 84, 79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 98, 87, 94, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 98, 91, 84, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 99, 94, 99, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 97, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
```
[Answer]
## CJam, ~~46~~ ~~43~~ ~~41~~ ~~39~~ ~~38~~ ~~36~~ 33 bytes
```
100:H,{)_7{ea:i~H@m2$*H/+@;}*>}#)
```
Input via ARGV.
[There is an online interpreter,](http://cjam.aditsu.net/) but unfortunately it doesn't support command-line arguments. For testing, you can mimick it from STDIN with this version:
```
rr]:A;
100:H,{)_7{A:i~H@m2$*H/+@;}*>}#)
```
Explanation of the ARGV-based version:
```
100:H "Push a 100 and save it in H.";
, "Create a range (as an array) from 0 to 99.";
{ }# "Find the first index in [0,1,2,...,99] for which the
block produces a truthy (non-zero) value.";
)_ "Increment and duplicate the current array element.";
7{ }* "Execute the block seven times.";
ea:i "Push the command-line arguments as an array of strings
and convert each element to an integer";
~ "Unwrap the array.";
H@ "Push a 100 and rotate the stack to pull up
the first command line argument.";
m "Subtract (from 100).";
2$ "Copy the last iterations result.";
*H/ "Multiply and divide by 100, deducting tax.";
+ "Add the refund.";
@; "Rotate top three stack elements, and discard the one that
has been pulled to the top. This always leaves the last
two results on the stack.";
> "Make sure that the last result was less than the second
to last. Yields 0 or 1.";
) "After the # search completes, we'll get -1 if no such
index exists, or one less than the desired number if it
does, so we can just increment.";
```
The contents of the stack are automatically printed at the end of the program.
[Answer]
## CJam, ~~**44 40 38 37**~~ 35 bytes
```
l~U100:M),{{_M5$-*M/3$+_@<*}7*}=]W=
```
Or when using command line arguments and `{}#` trick, **33 bytes**:
```
100:M,{){_ea:i~M@-@*M/+_@<*}7*}#)
```
Not putting this one as my main as `{}#` approach is inspired from Martin's answer.
Example run:
Input:
```
25 2
```
Output:
```
19
```
Another:
Input:
```
15 14
```
Output:
```
100
```
**How it works**
```
l~ "Read the two numbers, swap and convert tax to double";
U100:M), "Push 0 and [0, 1, ... 100] to stack, storing 100 in M";
{ ... }= "Run this code for each element until top stack element is 1";
{...}7* "Run this code block 7 times";
_ "Copy the array element";
M5$ "Push 100 and a copy tax % to stack";
-* "Number = (100 - tax %) * Number";
M/ "Integer divide the number by 100";
3$+ "Add refund";
_@<* "Convert to 0 if refunded number > before tax one";
]W= "Take the last element of the stack";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## APL (39)
```
T R←⎕⋄⊃Z/⍨{⍵(⊢×>)R+⌊⍵×1-T÷M}⍣7¨Z←⍳M←100
```
Explanation:
* `T R←⎕`: read two numbers from the keyboard and store them in `T` (tax) and `R` (return).
* `Z←⍳M←100`: store the number `100` in `M`, and all numbers from `1` to `100` in `Z`.
* `{`...`}⍣7¨`: for each element in `Z`, run the following function 7 times:
+ `R+⌊1-T÷M`: calculate how many cakes need to be paid,
+ `⍵(⊢×>)`: multiply that amount by 1 if the troll ends up with more cake than he started, or by 0 if not.
* `⊃Z/⍨`: for each element in `Z`, replicate it by the number that that function gave. (So all numbers for which the function returned `0` disappear.) Then select the first item from that list. If the list ended up empty, this gives `0`.
[Answer]
# C, 83 bytes
```
int cake(int perc_taken, int given_back)
{
int startcake = floor(100.f/perc_taken*given_back+1);
for(int i = 0; i < 6; i++)
{
startcake = ceil((startcake-given_back) * 100.f/(100 - perc_taken));
}
return startcake;
}
```
If it works, it works for all possible startcakes, not just from 1 to 100.
EDIT: It works. Golfed:
```
n(int p,int g) {int s=100./p*g+1,i=0;for(;i++<6;){s=ceil((s-g)*100./(100-p));}return s;}
```
With the 'maximum 100 cakes' limit:
```
n(int p,int g) {int s=100./p*g+1,i=0;for(;i++<6;){s=ceil((s-g)*100./(100-p));}return s>100?0:s;}
```
91 bytes.
[Answer]
# CJam, 36 bytes
```
q~:R100:H*\d:T/i){R-H*HT-/m]}6*_H)<*
```
[Answer]
# C++ - 202 chars
As usual, my C++ did the worst:
```
#include<iostream>
int main(){double p,g,c=1,i,r,t;std::cin>>p>>g;for(;c<101;c++){r=c;for(i=0;i<7;i++){t=(int)(r*(1-(p/100))+g);if(t>=r){r=-1;break;}r=t;}if(r!=-1)break;}r!=-1?std::cout<<c:std::cout<<0;}
```
[Answer]
## APL, 36
```
x y←⎕⋄101|1⍳⍨y<x×{y+⍵-⌈⍵×x}⍣6⍳x÷←100
```
**Explanation**
Note that there is a "cake threshold". For tax rate `x` and refund `y`, you will need strictly more than `y÷x` cakes to pass the next bridge.
`x y←⎕` take input and assign to `x` (tax) and `y` (return)
`⍳x÷←100` divide `x` by 100, and then generate an array of 1 to 100
`{y+⍵-⌈⍵×x}⍣6` call the "pass bridge" function 6 times:
`⌈⍵×x` The number of cakes you have, times tax rate, round up (the amount you pay)
`⍵-` Subtract from the number of cakes you have
`y+` Add the refund
Then you get a 100-element array showing the number of cakes you are left with after crossing 6 bridges if you start with 1~100 cakes. To see if you can cross the last bridge, check if you are above the threshold `y÷x`. Alternatively:
`x×` multiply the array by `x`
`y<` check if greater than `y`
Finally,
`1⍳⍨` find the index of first occurrence of `1` (true), returns `101` if not found
`101|` mod 101
[Answer]
**C 128**
Pretty similar to the other C solution but I think that's inevitable. The main trick is breaking out of the inner loop with different values depending on whether it goes to completion or not. This allows me to use ?: when I couldn't if I used break;
```
t,r,j,k,l,p;main(i){for(scanf("%d%d",&t,&r),i=101;k=--i;){for(j=8;--j>0;)(p=r+k*(100-t)/100)<k?k=p:j=0;j?0:l=i;}printf("%d",l);}
```
Ungolfed
```
int t,r,j,k,l,p;
main(int i)
{
for(scanf("%d%d",&t,&r),i=101;k=--i;)
{
for(j=8;--j>0;)
{
if((p=r+k*(100-t)/100)<k)
k=p;
else
j=0;
}
j?0:l=i;
}
printf("%d",l);
}
```
] |
[Question]
[
# Task
A theatre has 10 rows, labelled `A` to `J` from front to back, and 15 seats in each row,
numbered 1 to 15 from left to right.
The program uses the following rules to choose the best seats.
* Rule 1: All seats in one booking must be in the same row, next to each other.
* Rule 2: The seats must be as close to the front as possible, then as close to the left as possible (lowest letter, then lowest number)
Write a function which takes the number of tickets wanted as an integer input (`n`), and outputs the best seats available in a list of length `n`.
Your program should:
* Output `-1` if 1 > Input or Input > 15\*
* Output `-1` if the seats aren't available\*
* Have a function `B(n)` that the user can use to input the desired number of seats.
\*You can output the -1 in a list if it makes it easier
# Examples
### I/O
Calling `B(5)` on a new array should return `[A1, A2, A3, A4, A5]`
Calling `B(2)` after that should then return `[A6, A7]`
Calling `B(10)` after that should then return `[B1, B2, ... B9, B10]`
Calling `B(-1)` should always return `-1`
### Un-golfed Solution Python
```
Theatre = [ [False] * 16 ] * 11
def B(n):
if 0 <= n <= 15:
for i in range(10):
for j in range(15-n+1):
try:
if not Theatre[i][j]:
if not Theatre[i][j + n]:
row = i
start = j
List = []
for q in range(n):
List.append(chr(row + 65) + str(start + q + 1))
Theatre[row][start + q] = True
return List
except:
break
return -1
```
[Answer]
# JavaScript - 172
Function itself is 172:
```
//build persistent seats
m=[];
for(i=10;i--;){m[i]={r:String.fromCharCode(i+65),s:[]};for(j=0;j<15;j++)m[i].s.push(j+1);}
function b(z){for(i=0;i<m.length;i++)for(j=0,u=m[i].s.length;o=[],j<u;j++)if(u>=z&z>0){for(m[i].s=m[i].s.slice(z),p=m[i].s[0]||16;o[--z]=m[i].r+--p,z;);return o;}return-1;}
```
Input:
```
console.log(b(-1));
console.log(b(0));
console.log(b(4));
console.log(b(15));
console.log(b(1));
console.log(b(20));
```
Output:
```
-1
-1
[ 'A1', 'A2', 'A3', 'A4' ]
[ 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'B11', 'B12', 'B13', 'B14', 'B15' ]
[ 'A5' ]
-1
```
[Answer]
# Javascript (*ES6*) - 130 127 107 101 98
```
B=n=>(a=>{for(;n>0&a<9;)if((b=~~B[++a]+n)<16)for(B[a]=b;n--;)c[n]='ABCDEFGHIJ'[a]+b--})(c=[-1])||c
```
Demo here: <http://jsfiddle.net/tBu5G/>
Some ideas taken from @edc65
[Answer]
## Haskell, 129
```
t=[[a:show s|s<-[1..15]]|a<-['A'..'J']]
b n=(n%).span((<n).length)
_%(h,[])=([],h)
n%(j,(r:s))=let(t,u)=splitAt n r in(t,j++u:s)
```
Some adjustments had to be made to make this a function in Haskell: `b` returns a pair: the tickets (if possible), and the new state of the theater. `t` is the initial theater state, with all tickets unsold. Also, returning `-1` was unnatural for Haskell, so if no tickets can be issued for a request, the empty list is returned for the tickets.
```
λ: let (k1,t1) = b 5 t
λ: k1
["A1","A2","A3","A4","A5"]
λ: let (k2,t2) = b 2 t1
λ: k2
["A6","A7"]
λ: let (k3,t3) = b 10 t2
λ: k3
["B1","B2","B3","B4","B5","B6","B7","B8","B9","B10"]
λ: let (k4,t4) = b (-1) t3
λ: k4
[]
λ: let (k5,t5) = b 2 t4
λ: k5
["A8","A9"]
```
[Answer]
# APL (75)
```
T←10 15⍴0⋄B←{(⍵∊⍳15)∧∨/Z←,T⍷⍨⍵/0:+T[P]←{⎕A[⍺],⍕⍵}/¨P←(⊃Z/,⍳⍴T)∘+¨1-⍨⍳1⍵⋄¯1}
```
Test:
```
B 5
A1 A2 A3 A4 A5
B 2
A6 A7
B 10
B1 B2 B3 B4 B5 B6 B7 B8 B9 B10
B ¯1
¯1
B 3
A8 A9 A10
```
Explanation:
* `T←10 15⍴0`: `T` is a 15-by-10 matrix that holds the theater state (0 = free)
* `B←{`...`}`: the function
+ `(⍵∊⍳15)`: if `⍵` is a member of the set of integers from 1 to 15,
+ `∨/Z←,T⍷⍨⍵/0`: and `T` contains `⍵` zeroes in a row (storing possible start points in `Z`),
+ `:`: then:
- `(⊃Z/,⍳⍴T)`: select possible start coordinates, and take the first one,
- `∘+¨1-⍨⍳1⍵`: add `⍵-1` more positions to the right of the start coordinate
- `P←`: store the coordinates in `P`
- `{⎕A[⍺],⍕⍵}/¨`: format the coordinates
- `T[P]←`: store the formatted coordinates at their places in `T`. (any nonzero values in T will do)
- `+`: return the result, which is the formatted coordinates (the result of an assignment is tacit by default)
+ `⋄¯1`: otherwise, return `¯1`.
[Answer]
# Javascript (E6) 99 ~~103 113 121~~
Really you just need to store a number for each row
```
B=n=>{for(r=i=[-1];n>0&i++<9;)if((a=~~B[i]+n)<16)for(B[i]=a;n--;)r[n]='ABCDEFGHIJ'[i]+a--;return r}
```
**Test**
```
'5:'+B(5)+'\n2:'+B(2)+'\n10:'+B(10)+'\n0:'+B(0)+'\n1:'+B(-1))+'\n3:'+B(3)
```
**Ungolfed**
```
B = n => {
for (r = i = [-1]; n > 0 & i++ < 9;)
if ((a = ~~B[i] + n) < 16)
for (B[i] = a; n--; ) r[n] = 'ABCDEFGHIJ'[i] + a--;
return r;
}
```
[Answer]
# JavaScript (ECMAScript 6 Draft) - ~~96~~ ~~95~~ 91 Characters
A recursive solution:
**Version 1**
```
B=(n,r=0)=>n>0&&(k=~~B[r])+n<16?[...Array(n)].map(_=>'ABCDEFGHIJ'[r]+(B[r]=++k)):r<9?B(n,r+1):-1
```
**Version 2:**
```
B=(n,r=0)=>n<1|r>9?-1:(k=B[r]|0)+n<16?[...Array(n)].map(_=>'ABCDEFGHIJ'[r]+(B[r]=++k)):B(n,r+1)
```
(Thanks to [nderscore](https://codegolf.stackexchange.com/users/20160/nderscore) for the inspiration for the 1 character saving)
**Version 3:**
```
B=(n,r=0)=>n<1|r>9?-1:(B[r]^=0)+n<16?[...Array(n)].map(_=>'ABCDEFGHIJ'[r]+ ++B[r]):B(n,r+1)
```
(Thanks to [nderscore](https://codegolf.stackexchange.com/users/20160/nderscore))
**Explanation:**
```
B = function(n,r=0) // Create a function B with arguments:
// - n is the number of seats to book
// - r is the row number (defaults to 0)
{
var k = ~~B[r]; // get the number of seats already booked in row r
if ( n > 0 // ensure that n is a valid booking
&& k+n<16 ) // check that there are enough seats remaining in row r
{
var P = new Array(n); // Create an array with length n with no elements initialised
var Q = [...P]; // Use P to create an array with every element
// initialised to undefined
var R = 'ABCDEFGHIJ'[r]; // get the row ID.
B[r] = k + n; // Increment the number of seats booked in row r by n.
var S = Q.map(
function(){
return R + (++k); // Map each value of Q to the row ID concatenated with
// the seat number.
}
);
return S; // Return the array of seats.
}
else if ( r < 9 ) // If there are more rows to check
{
return B(n,r+1); // Check the next row.
}
else // Else (if n is invalid or we've run out of rows)
{
return -1; // Return -1.
}
}
```
[Answer]
# GolfScript, ~~103~~ 82 bytes
```
226,1>15/[0]*:T{:&0>{T[{),&~)>:|T\/,2=}?]{T|-:T;|{(.[15/65+]\15%)`+}%}-1if}-1if}:B
```
# Examples
```
$ cat theatre.gs
226,1>15/[0]*:T
{:&0>{T[{),&~)>:|T\/,2=}?]{T|-:T;|{(.[15/65+]\15%)`+}%}-1if}-1if}:B
5 B p # Execute B(5), stringify and print.
2 B p
15 B p
17 B p
0 B p
{}:puts # Disable automatic output.
$
$ golfscript theatre.gs
["A1" "A2" "A3" "A4" "A5"]
["A6" "A7"]
["B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12" "B13" "B14" "B15"]
-1
-1
```
# How it works
```
226,1> # Push the array [ 1 … 225 ].
15/[0]* # Split in chunks of 15 elements and join separating by zeros.
:T # Save result in T.
{ #
:&0> # Save the function's argument in & and check if it's positive.
{ # If it is:
T[{ # For each seat S in T:
), # Push [ 0 … S ].
&~)> # Reduce two [ S-(&-1) … S ].
:| # Save the result in |.
T\/ # Split T around |.
,2= # If there are two chunks, the seats are available.
}?] # Find the first S that satisfies the above condition.
{ # If there was a match:
T|-:T; # Remove the seats in | from T.
|{ # For each seat S in |:
(. # Push S+1 S+1.
[15/65+] # Compute (S+1)/15+65; the ASCII character corresponding to the row.
\15%)`+ # Compute (S+1)%15+1, stringify and concatenate.
}% #
} #
-1if # If there was no match, push -1 instead.
} #
-1if # If the argument was non-positive, push -1 instead.
}
```
[Answer]
# CoffeeScript - ~~171~~ ~~150~~ 149
I suspect Ruby or Perl will beat this out before long.
```
c=0;l=64;k=1
f=(n)->
if n<0 or n>15 or 150-c<n
return-1
a=[]
for i in[1..n]
if c%15==0
++l;k=1
++c;a.push String.fromCharCode(l)+k;++k
a
```
**Equivalent JavaScript/Explanation**:
For those unfamiliar with CoffeeScript.
```
var seats = 0; //Occupied seats.
var letter = 64; //ASCII code for row letter.
var index = 1; //Index of seat in row.
function seats( count )
{
if( count < 0 || count > 15 || ( 150 - seats ) < count )
return -1;
var assignedSeats = [];
for( var i = 1; i <= count; ++i )
{
if( ( seats % 15 ) === 0 )
{
++letter;
index = 1;
}
++seats; //Occupy a seat.
assignedSeats.push( String.fromCharCode( letter ) + index );
++index;
}
return assignedSeats;
}
```
[Try it online](http://coffeescript.org/#try%3ac%3D0%3Bl%3D64%3Bk%3D1%0Af%3D%28n%29-%3E%0A%20if%20n%3C0%20or%20n%3E15%20or%20n%3E%3D150-c%0A%20%20return-1%0A%20a%3D%5B%5D%0A%20for%20i%20in%5B1..n%5D%0A%20%20if%20c%2515%3D%3D0%0A%20%20%20%2B%2Bl%3Bk%3D1%0A%20%20%2B%2Bc%3Ba.push%20String.fromCharCode%28l%29%2Bk%3B%2B%2Bk%0A%20a%0A%0Aalert%20f%203%0Aalert%20f%202%0Aalert%20f%2015).
[Answer]
# Cobra - 309
This *should* do it, but I can't actually get to a compiler for a few hours, so I'll update it later if needed.
```
class P
var s=List<of List<of String>>()
def main
for l in 'ABCDEFGHIJ'
t=[]
for n in 1:16,t.insert(0,l.toString+n.toString)
.s.add(t)
def b(n) as List<of String>
t=[]
for r in .s.count,if .s[r].count>=n
for i in n,t.add(.s[r].pop)
break
return if(n>0 and t<>[],t,['-1'])
```
[Answer]
## C# - 289
First attempt at code golfing.
```
int[]s=new int[10];string[]B(int n){string[]x=new string[]{"-1"};if(n<1||n>15)return x;int m=(int)Math.Pow(2, n)-1;for(int i=0;i<10;++i){for(int j=0;j<15-n;++j){if((s[i] &m)==0){s[i]|=m;string[]r=new string[n];for(int k=0;k<n;++k)r[k]=(""+(char)(i+65)+(j+k+1));return r;}m<<=1;}}return x;}
```
Un-golfed
```
int[] s = new int[10];
string[] B(int n)
{
string[] x = new string[] { "-1" };
if (n < 1 || n > 15) return x;
int m = (int)Math.Pow(2, n) - 1;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 15 - n; ++j)
{
if ((s[i] & m) == 0)
{
s[i] |= m;
string[] r = new string[n];
for (int k = 0; k < n; ++k)
r[k] = ("" + (char)(i + 65) + (j+k+1));
return r;
}
m <<= 1;
}
}
return x;
}
```
[Answer]
# K, 140
```
d:10#,15#0b
B:{if[(x<0)|x>15;:-1];$[^r:*&&/'~:^a:{(*&&/'{x(!1+(#x)-y)+\:!y}[d x;y])+!y}[;x]'!#d;-1;[.[`d;(r;a r);~:];(10#.Q.A)[r],/:$1+a r]]}
```
There are undoubtedly numerous improvements to be made here
[Answer]
**C++ - 257**
Also a first attempt at golfing.
```
static vector< int > t (10, 0);
vector<string> b(int n){
vector<string> o;
int i=0,j;
for(;i<10&&16>n&&n>0;i++){
if(15-t[i]<n) continue;
char l='A'+i;
for(j=t[i];j<n+t[i];j++){
o.push_back(l + toS(j + 1));
}
t[i]+=n;
n=0;
}
if(o.empty()) o.push_back("-1");
return o;
}
```
Because to\_string wasn't working with my compiler, toS is defined as
```
string toS(int i){
return static_cast<ostringstream*>( &(ostringstream() << i) )->str();
}
```
And as a little interface
```
int main(){
int input = 0;
bool done = false;
while (!done){
cout << "how many seats would you like? (0 to exit)\n";
cin >> input;
vector<string> selection = b(input);
for (auto s : selection){
cout << s << ' ';
}
cout << endl;
if (input == 0) break;
}
return 0;
}
```
[Answer]
# C# - 268 Bytes
Golfed code:
```
int[]s=new int[10];string[]B(int n){string[]x={"-1"};if(n<1||n>15)return x;int m=(int)Math.Pow(2,n)-1;for(int i=0;++i<10;){for(int j=0;++j<15-n;){if((s[i]&m)==0){s[i]|=m;var r=new string[n];for(int k=0;++k<n;)r[k]=(""+(char)(i+65)+(j+k+1));return r;}m<<=1;}}return x;}
```
Ungolfed code:
```
int[] s = new int[10];
string[] B(int n)
{
string[] x = { "-1" };
if (n < 1 || n > 15) return x;
int m = (int)Math.Pow(2, n) - 1;
for (int i = 0; ++i < 10;)
{
for (int j = 0; ++j < 15 - n;)
{
if ((s[i] & m) == 0)
{
s[i] |= m;
var r = new string[n];
for (int k = 0; ++k < n;)
r[k] = ("" + (char)(i + 65) + (j + k + 1));
return r;
}
m <<= 1;
}
}
return x;
}
```
I would have written some annotations into a comment on GoldenDragon's solution instead of making my own, but my reputation doesn't allow it.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/24072/edit).
Closed 6 years ago.
[Improve this question](/posts/24072/edit)
So I'd like you to attempt to generate Rorschach images like the below image:

Here is a [link](http://commons.wikimedia.org/wiki/Rorschach_inkblot_test) to further inspiration.
This is a popularity contest, but I will say that colours are likely to be more popular than black and white, as well as textures.
Rorschach images are created by folding paper with ink on so one criteria is symmetry.
ASCII art is valid, but will be subject to the same criteria as above.
[Answer]
## Python
Not quite the best or smoothest, but here's a python solution:
```
from PIL import Image
import random
import sys
imgsize = (int(sys.argv[1]), int(sys.argv[2]))
color = (0, 0, 0)
img = Image.new("RGB", imgsize, "white")
for j in range(0,int(sys.argv[3])):
start = (random.randrange(0, imgsize[0]/2), random.randrange(0, imgsize[1]))
point = start
img.putpixel(point, color)
blotsize = random.randrange(0, int(sys.argv[4]))
for i in range(blotsize):
directions = [(point[0], point[1]+1), (point[0], point[1]-1), (point[0]+1, point[1]), (point[0]-1, point[1])]
toremove = []
for direction in directions:
if direction[0]>=(imgsize[0]/2) or direction[1]>=imgsize[1] or direction[0]<0 or direction[1]<0:
toremove.append(direction)
for d in toremove:
directions.remove(d)
point = random.choice(directions)
img.putpixel(point, color)
cropped = img.crop((0, 0, imgsize[0]/2, imgsize[1]))
img = img.transpose(Image.FLIP_LEFT_RIGHT)
img.paste(cropped, (0, 0, imgsize[0]/2, imgsize[1]))
img.save("blot.png")
```
It just makes a "wandering path" for a blot, and makes several of those.
An example usage:
```
py inkblot.py width height blots blotsize
py inkblot.py 512 512 20 10000
```
And some example images:
 
[Answer]
# Fortran 95
This code is kind of big, but it produces a nice(ish) ASCii result:
```
program Rorschach
implicit none
integer :: i, j, k, l, N, seed
integer, dimension (24) :: i_zero, j_zero
real :: aux
integer, dimension (17,12) :: matrix_I = 0
character, dimension (17,12) :: matrix_C
! random seed according to system clock
call SYSTEM_CLOCK(count=k)
call RANDOM_SEED(size=N)
allocate(seed(N))
seed=k+37*(/ (i - 1, i = 1, n) /)
call RANDOM_SEED(PUT=seed)
! generating 7 random points
do i=1,7
call RANDOM_NUMBER(aux)
i_zero(i) = 15 * aux + 2 ! range = 2-16
call RANDOM_NUMBER(aux)
j_zero(i) = 11 * aux + 2 ! range = 2-12
enddo
! generating 7 large spots of ink
do i=1,7
matrix_I(i_zero(i),j_zero(i)) = 3 ! central points have ink value 3
do k=-1,1
do l=-1,1
if (.NOT.((k==0) .AND. (l==0))) then ! immediate neighbours...
if ( (((i_zero(i)+k)<=17).OR.((i_zero(i)+k)>0)) .AND. (((j_zero(i)+l)<=12).OR.((j_zero(i)+l)>0)) ) then ! ... that are inside the designed area ...
if (matrix_I(i_zero(i)+k,j_zero(i)+l) < 2) matrix_I(i_zero(i)+k,j_zero(i)+l) = 2 ! ... and that do not have ink value larger than 2 will be attributed as 2
endif
endif
enddo
enddo
enddo
! generating N little sparkles of ink
call RANDOM_NUMBER(aux)
N = int(11 * aux) + 20 ! N = 20-30
i = 0
do while (i <= N)
call RANDOM_NUMBER(aux)
i_zero(i) = 16 * aux + 1 ! range = 1-17
call RANDOM_NUMBER(aux)
j_zero(i) = 11 * aux + 1 ! range = 1-12
if (matrix_I(i_zero(i),j_zero(i)) < 1) then ! if the selected point already has more ink than 1, then cycle the loop
matrix_I(i_zero(i),j_zero(i)) = 1
else
cycle
endif
i = i + 1
enddo
! converting matrix of integers into matrix of characters
do i=1,17
do j=1,12
select case(matrix_I(i,j))
case(0)
matrix_C(i,j) = " "
case(1)
matrix_C(i,j) = "."
case(2)
matrix_C(i,j) = "+"
case(3)
matrix_C(i,j) = "@"
end select
enddo
enddo
! printing it on the screen + its reflection
do i=1,17
do j=1,12
write(*,"(A1)",advance="NO") matrix_C(i,j)
enddo
do j=12,2,-1
write(*,"(A1)",advance="NO") matrix_C(i,j)
enddo
write(*,"(A1)") matrix_C(i,1)
enddo
end program Rorschach
```
The code is fully commented, but the basic idea is that it generates a matrix with values between 0 and 3, representing the amount of ink in that spot. There are 7 large spots of ink (a spot with a value 3 surrounded by values 2) and a lot of little "sparkles" (value 1). This matrix is then converted into a character matrix, using the following conversion:
```
0 =
1 = .
2 = +
3 = @
```
Here is a result:
```
+++ . . +++
+@++++ . . ++++@+
++++@+. .+@++++
.+++ ++++ +++.
+@@+
. . . +++@@+++ . . .
. +@++++@+ .
++++++ ++++++
+@+ +@+
. ++++ ++++ .
. +@+ +@+ .
. .+++. .+++. .
. . . . . .
. . . .
. .. .. .
. .
```
] |
[Question]
[
Write a program to solve a series of linear equations as short as possible. It must solve arbitrary number of equations problems. They can inputted however you like, coefficients of augmented matrix is probably the easiest. The program doesn't have to handle non-integer coefficients or solutions. No degenerate or invalid cases will be tested. The program must output the value of each variable or reduced row echelon form.
No equation solving libraries, matrix functions, or any way to automatically solve is allowed. You can simulate matrices with arrays or lists.
Example input (or equivalent):
```
m={{2,1,-1,8},{-3,-1,2,-11},{-2,1,2,-3}}
```
This represents `2x+y-z=8, -3x-y+2z=-11, -2x+y+2z=-3`
Example output (or equivalent):
```
{2,3,-1}
```
This represents `x=2, y=3, z=-1`
[Answer]
# APL, 1 char
I know it doesn't fit the (revised) requirements, but it's too good not to post:
```
⌹
```
Symbol "domino" `⌹` (division `÷` inside a rectangle) performs matrix division, therefore it can solve any system of linear equations. You just have to put it between the constant term vector and the matrix with the other terms:
```
8 ¯11 ¯3 ⌹ ⊃(2 1 ¯1)(¯3 ¯1 2)(¯2 1 2)
2 3 ¯1
```
(if you want to try it on TryApl, `⊃` is `↑`)
[Answer]
## Javascript (284 181) - [Gauss Elimination method](http://en.wikipedia.org/wiki/Gaussian_elimination)
```
function f(A){l=A.length;d=1;for(i=0;i+1;i+=d){v=A[i][i];for(k=0;k<l+1;k++)A[i][k]/=v;for(j=i+d;A[j];j+=d)for(k=0,w=A[j][i];k<l+1;k++)A[j][k]-=w*A[i][k];if(i==l-d)d=-1,i=l}return A}
```
**Test**
```
f([[2,1,-1,8],[-3,-1,2,-11],[-2,1,2,-3]]);
=> [[1,0,0,2],[0,1,0,3],[-0,-0,1,-1]]
```
The returned array combine the identity matrix and the solution.
[Answer]
## Python 169 166
**Implementation**
```
def s(a):
if a:b=a[0];r=s([[x-1.*y*b[0]/r[0]for x,y in zip(b[1:],r[1:])]for r in a[1:]]);return[round((b[-1]-sum(x*y for x,y in zip(b[1:-1],r)))/b[0])]+r
return[]
```
**Demo**
```
>>> arr=[[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]]
>>> s(arr)
[2.0, 3.0, -1.0]
```
**Note**
If you are OK with the float approximation, then you can remove the round function call and further golf to *159* characters
[Answer]
*This answer no longer fits the question after the rule change as it uses a matrix function.*\*
**[Sage](http://www.sagemath.org/), 32**
```
~matrix(input())*vector(input())
```
Sample input:
```
[[2, 1, -1], [-3, -1, 2], [-2, 1, 2]]
[8, -11, -3]
```
Sample output:
```
(2, 3, -1)
```
\*Arguably, `matrix()` is a typecast, not a function (running `import types; isinstance(matrix, types.FunctionType)` gives `False`). Also, the `~` and `*` are *operators*, not functions.
[Answer]
# Java - 522 434 228 213 chars
Solves by systematically checking all possible integer n-tuples by direct multiplication until one is found that works.
Function takes augmented matrix, A, trial solution vector, x, and dimension, n, as input - outputs solution vector, x. Note that the vector x is actually one larger than the dimension to help step through possible solutions. (If I declared variables A,x,n,j,k,s as instance variables, the function would be 31 chars shorter - for a total of 182, but that feels like bending the rules too far.)
```
int[]Z(int[][]A,int[]x,int n){int j,k,s;for(;;){for(j=0;j<n;j++){for(k=s=0;k<n;s+=A[j][k]*x[k++]);if(s!=A[j][n])j+=n;}if(j==n)return x;for(j=0;j<=n;j++)if(x[j]!=x[n]||j==n){x[j]++;for(k=0;k<j;x[k++]=-x[n]);j=n;}}}
```
Program for testing (somewhat ungolfed):
```
import java.util.*;
class MatrixSolver{
public MatrixSolver() {
Scanner p=new Scanner(System.in); //initialize everything from stdin
int j,k,n=p.nextInt(),A[][]=new int[n][n+1],x[]=new int[n+1];
for(j=0;j<n;j++)for(k=0;k<=n;A[j][k++]=p.nextInt());
x=Z(A,x,n); //call the magic function
for(j=0;j<n;j++) System.out.print(x[j]+" "); //print the output
}
public static void main(String[]args){
new MatrixSolver();
}
int[]Z(int[][]A,int[]x,int n){
int j,k,s;
for(;;){
for(j=0;j<n;j++){ //multiply each row of matrix by trial solution and check to see if it is correct
for(k=s=0;k<n;s+=A[j][k]*x[k++]);
if(s!=A[j][n])j+=n;
}
if(j==n)return x; //if it is correct return the trial solution
for(j=0;j<=n;j++)if(x[j]!=x[n]||j==n){//calculate the next trial solution
x[j]++;
for(k=0;k<j;x[k++]=-x[n]);
j=n;
}
}
}
}
```
Program takes input from stdin as space separated integers as follows: first, the dimension of the problem, second, the entries of the augmented matrix by row.
Sample run:
```
$java -jar MatrixSolver.jar
3 2 1 -1 8 -3 -1 2 -11 -2 1 2 -3
2 3 -1
```
I shaved several characters by following Victor's advice about loops and "public", storing the RHS in the augmented matrix instead of separately, and adding an extra entry to my trial solution to simplify the generation of each new trial solution. The OP also said that a function is enough - no need to count the entire program.
[Answer]
# JavaScript (ES6), ~~152~~ 151 bytes
Implementation of [Cramer's rule](https://en.wikipedia.org/wiki/Cramer%27s_rule).
Takes input as `(m)(v)`, where \$m\$ is the matrix of variable coefficients and \$v\$ is the vector of constant terms.
```
m=>v=>m.map((_,i)=>(D=m=>m+m?m.reduce((s,[v],i)=>s+(i&1?-v:v)*D(m.map(([,...r])=>r).filter(_=>i--)),0):1)(m.map((r,y)=>r.map((k,x)=>x-i?k:v[y])))/D(m))
```
[Try it online!](https://tio.run/##PYzLCsIwEEX3fkVWMqOTaHUjhbQb/yIEKTWV2MZKqkG/vk59bQbuuefOuUrVUEd/vclLf3Rjo8egi6SLoEJ1BTiQR13AXjMNy1AGFd3xXjuAgUyy73ZYgp9npUx5wsUevktDSqlouY@oGt/dXISDLryUiLTGPMOfGek5WZ/Q0oPDQ/qyzZN5WkRc8U/Ese4vQ9851fUnaGZCgOEjhBEbEiIjITNLHyK3U2K6@ZOvw4SBxfd8N1nTcMsAxxc "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Similar to [generating minesweeper grids](https://codegolf.stackexchange.com/questions/6474/generating-minesweeper-grids), although the challenge is to make a working minesweeper grid. **This will be longer code than normal (I think)**.
[more information on minesweeper](http://en.wikipedia.org/wiki/Minesweeper_(video_game)).
>
> Minesweeper is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.
>
>
>
**Required features:**
```
-Randomized mine generation
-8x8 field with 10 mines
-Mine and "unknown" flags
-Reveal nearby blank spaces when a blank space has been revealed.
-Input and output code: It must be playable. (Input and output code counts in the total)
```
**Note on scoring**:
```
Anything that is needed to make the program work is counted.
If it can be deleted and not affect the program, get rid of it.
I will occasionally update the selected answer to shorter programs if needed.
```
I came across a more specific version of this problem in computer science class: make a working version with the shortest number of lines in visual basic (I got 57 lines), and I thought it will be an interesting challenge for code golf. If there are any suggestions for improving the question, please comment. Shortest code in bytes wins.
[Answer]
## Javascript, 978 bytes (824 without CSS)
<http://jsbin.com/otayez/6/>
Checklist:
```
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine flags - Yes
"unknown" flags - no
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes
```
JS:
```
(function(){
f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0;
for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];
for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);
for(i=64;i--;z.id='b'+(63-i),c.appendChild(z))z=document.createElement('button');
for(d=b;d--;)
for(r=b;r--;)
s.map(function(y){
s.map(function(x){
if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++;
});
});
c.onclick=function(e){
var t=e.target,
i=t.id.slice(1),
x=i%b,
y=f(i/b),
n=t.className=='b';
if(t.innerHTML||(n&&!e.ctrlKey))return;
if(e.ctrlKey)return t.className=(n?'':'b')
if(q(x,y))alert('boom')
if(l==54)alert('win')
};
function q(x,y){
if(x<0||x>7||y<0||y>7)return;
var p=y*b+x,
v=g[y][x],
t=document.all['b'+p];
if(v!=m&&!t.innerHTML){
t.innerHTML=g[y][x];
t.className='f';
l++;
if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}
}
return v==m
}
})();
```
MiniJS **812 bytes**:
```
f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0,h='b';for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);for(i=64;i--;z.id=h+(63-i),c.appendChild(z))z=document.createElement('button');for(d=b;d--;)for(r=b;r--;)s.map(function(y){s.map(function(x){if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++})});c.onclick=function(e){var t=e.target,i=t.id.slice(1),n=t.className==h;if(t.innerHTML||(n&&!e.ctrlKey))return;if(e.ctrlKey)return t.className=(n?'':h);if(q(i%b,f(i/b)))alert('boom');if(l==54)alert('win')};function q(x,y){if(x<0||x>7||y<0||y>7)return;var p=y*b+x,v=g[y][x],t=document.all[h+p];if(v!=m&&!t.innerHTML){t.innerHTML=g[y][x];t.className='f';l++;if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}}return v==m}
```
HTML **12 bytes**
```
<div id="c">
```
The CSS isn't necessary from a functionality standpoint, but is from a usability standpoint:
```
#c{
width:300px;
height:300px;
}
button{
width:12.5%;
height:12.5%;
line-height:30px;
}
.f,.z{
background:#fff;
border:solid 1px #fff;
}
.z{
color:#fff;
}
.b{background:#f00}
```
Mini CSS **154 bytes**:
```
#c{width:300px;height:300px}button{width:12.5%;height:12.5%;line-height:30px}.f,.z{background:#fff;border:solid 1px #fff}.z{color:#fff}.b{background:#f00}
```
[Answer]
# Python 2.7 (487C)
```
"""
char meaning:
'?': unknown flag
'!': mine flag
'x': default
how to play:
Input 3 chars each time. The first char is the action
and the rest form a position. For example, '013' means
uncover grid (1,3), '110' means flag the grid (1,0).
The top-left corner is (0, 0), bottom-left (7,0), etc.
Player will lose after uncover a mine, the program will
output "Bom". If the Player uncovers all grid that do
not contain a mine, he wins and the program will output
"Win".
"""
import random as Z
S=sum
M=map
T=range
P=[(i,j)for i in T(8)for j in T(8)]
C=dict(zip(T(-3,9),'?!x012345678'))
m={p:-1 for p in P}
h=Z.sample(P,10)
def U(p):
if m[p]>=0:return 0
n=filter(lambda(c,d):0<max(abs(p[0]-c),abs(p[1]-d))<2,P)
m[p]=s=S((x in h)for x in n)
return(1 if s else S(M(U,n))+1,-1)[p in h]
s=u=0
while(s<54)&(u>-1):
f,i,j=M(int,raw_input(''.join((C[m[x]]+'\n '[x[1]<7])for x in P)))
p=i,j;c=m[p]
if f*(c<0):m[p]=-1-(-c)%3
else:u=U(p);s+=u
print'WBionm'[s<54::2]
```
Full game experience:
```
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 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
000
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
x 1 0 1 x x x x
070
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
123
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
113
0 0 1 x x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
003
0 0 1 1 x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
004
0 0 1 1 1 x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
014
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
154
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
044
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
034
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
035
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
045
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
055
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
124
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
164
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x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0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
007
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
017
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x 3
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
016
Win
```
The last step is dangerous, though.
[Answer]
## C, 568, 557, 537
```
Checklist:
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine and "unknown" flags - yes
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes
Further to playable:
Win detection (found all mines, or revealed all empties)
Bang detection (hit a mine)
Game terminates.
Output format:
# - unrevealed
! - a flagged mine
* - a mine
(number) - number of neighbouring mines
? - unknown flag
Input format:
x y f
- where x is 0..7, y is 0..7 (origin upper-left)
- f is 0 to open up, 1 to flag a mine, and 2 to flag a unknown
```
example game:
```
./a.out
5 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 # #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
6 1 1
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
7 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 *
# # # 1 2 1 # 1
# # # # # # # #
bang!
```
code:
```
// 8x8 grid but with padding before first row, after last row, and after last column, i.e. its 9x10
m[99]; // 0=empty,1=mine
u[99]; // 0=revealed,1=unrevealed,2=flag,3=unknown
// count neighbouring mines (8way)
c(i){return m[i-8]+m[i-9]+m[i-10]+m[i+8]+m[i+9]+m[i+10]+m[i-1]+m[i+1];}
// reveal (4way)
r(i){
if(u[i]){
u[i]=0;
if(!c(i))r(i-9),r(i+9),r(i+1),r(i-1);
}
}
i,x,y,f,e;
main(){
// place 10 mines
for(srand(time(0));i<10;){
x=rand()%64;
x+=9+x/8;
if(!m[x]){
m[x]=1;
i++;
}
}
for(;y<64;y++)u[y+9+y/8]=1; // mark visible grid as being unrevealed
while(!e){
// read input 0..7 0..7 0..2
scanf("%d%d%d",&x,&y,&f);
i=x+9+y*9;
if(f)u[i]=f==1?2:u[i]==3?1:3;else r(i); // flag, toggle unknown/unrevealed, open
// show grid and calc score
for(y=f=x=0;x<64;x++){
i=x+9+x/8;
putchar(u[i]?" #!?"[u[i]]:m[i]?42:48+c(i)); // 42='*', 48='0'
putchar(x%8==7?10:32);
if(!u[i])y+=m[i]?-99:1; // y = number of correctly open
if(u[i]==2)f+=m[i]?1:-99; // f = number of correct mines
}
if(y<0||y==54||f==10)e=puts(y<0?"bang!":"win!"); // 54 = 64-10
}
}
```
[Answer]
# Mathematica 566 548 1056
**Edit**: This is a complete rewrite. I gave up trying to obtain the shortest code and decided instead to build in the features that made most sense.
`r` indicates the number of rows in the grid. `c` indicates the number of columns in the grid.
`m`: number of mines.
The game is played by mouse-clicking on the buttons. If the player clicks on a mine, the cell turns black and the program prints "You Lose!"
The checkbox "u" allows the player to peek at the complete solution at any time.
The flags, "?" and "!" can be placed in any cell as desired.
```
DynamicModule[{s, x, f, l},
Manipulate[
Column[{
Grid[s],
If[u, Grid@f, Null]
}],
Grid[{{Control@{{r, 8}, 4, 16, 1, PopupMenu},
Control@{{c, 8}, 4, 16, 1, PopupMenu},
Control@{{m, 10}, 1, 50, 1, PopupMenu}},
{Button["New", i],
Control@{{e, 0}, {0 -> "play", 1 -> "?", 2 -> "!"}, SetterBar},
Control@{{u, False}, {True, False}}}}],
Deployed -> True,
Initialization :>
(p = ReplacePart;
q = ConstantArray;
z = Yellow;
w = White;
b := Array[Button[" ", v[{#, #2}], Background -> z] &, {r, c}];
a := RandomSample[l = Flatten[Array[List, {r, c}], 1], m];
d[m1_] :=
p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
0], (# -> "*") & /@ (x)];
n[y_] := Complement[Select[l, ChessboardDistance[y, #] == 1 &], x];
d[m1_] :=
p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
0], (# -> "*") & /@ (x)];
v[{r_, c_}] :=
Switch[e,
1, If[s[[r, c, 3, 2]] == z,
s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "?", " ", "?"]}],
Null],
2, If[s[[r, c, 3, 2]] == z,
s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "!", " ", "!"]}],
Null],
3, Null,
0, Switch[f[[r, c]],
"*", (Print["You lose!"]; (s = p[s, {r, c, 3, 2} -> Black])),
0, (s = p[s, {{r, c, 1} -> " ", {r, c, 3, 2} -> w}];
f = p[f, {{r, c} -> ""}]; v /@ n[{r, c}]),
" ", Null,
_, (s = p[s, {{r, c, 1} -> f[[r, c]], {r, c, 3, 2} -> w}])]];
i :=
(x = a;s = b;f = d[x]);i) ] ]
```
**Initial State**

**At a later point...**

[Answer]
## Python (~~502~~ 566)
Checklist:
```
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine and "unknown" flags - yes
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes
```
It has a win detector as well.
Input is given while the game is running, with `(f, x, y)`. `(x, y)` is the coordinates of the grid selection, `f` is whether you want to flag or not. `(0, 0, 0)` would open up `(0, 0)`, and `(1, 2, 3)` would flag (2, 3). Flagging works in a cycle: flagging a square twice gives a question mark.
(number) - number of mines
(space) - unexplored
. - 0 mines
! - flag
" - question
```
import random
A=[-1,0,1]
R=lambda x:[x+i for i in[-9,-8,-7,-1,1,7,8,9]if(0<x+i<64)&([i,x%8]not in([7,0],[-7,7],[-1,0],[1,7]))]
M=lambda p:sum(G[i]=='*'for i in R(p))
def V(p):
m=M(p);G[p]=`m`if m else'.'
if m>0:return
for c in R(p):
if' '!=G[c]:continue
m=M(c);G[c]=`m`
if m==0:G[c]='.';V(c)
G=[' ']*54+['*']*10
random.shuffle(G)
while' 'in`G`:
for i in range(8):print[j.replace('*',' ')[0]for j in G[8*i:8*i+8]]
i=input()[::-1];a=i[0]*8+i[1];b=G[a]
if i[2]:G[a]=(chr(ord(b[0])+1)if'"'!=b[0]else' ')+b[1:];continue
if'*'==b:print'L';break
if'!'!=b:V(a)
```
Needs to be improved: function R [get all squares around item p] (101 chars), printing (69 chars), flagging (72 chars)
[Answer]
# Dyalog APL, 113 bytes
`{⎕←1 0⍕c+○○h⋄10=+/,h:1⋄m⌷⍨i←⎕:0⋄∇{~⍵⌷h:0⋄(⍵⌷h)←0⋄0=⍵⌷c:∇¨(,⍳⍴m)∩⍵∘+¨,2-⍳3 3⋄0}i}h←=⍨c←{⍉3+/0,⍵,0}⍣2⊢m←8 8⍴10≥?⍨64`
non-competing: no "mine" and "unknown" flags
prints `*` for unopened cells and digits for opened (including `0`)
repeatedly asks the user for the 1-based coordinates of a cell to open
ultimately outputs `0` on failure (mine opened) or `1` on success (only 10 unopened left)
looks like this:
```
********
********
********
********
********
********
********
********
⎕:
1 1
00000000
11012321
*112****
********
********
********
********
********
⎕:
3 8
00000000
11012321
*112***1
********
********
********
********
********
⎕:
4 7
00000000
11012321
*112***1
******3*
********
********
********
********
⎕:
```
...
] |
[Question]
[
A [knight's tour](https://en.wikipedia.org/wiki/Knight%27s_tour) is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. For those who are not aware of how knights in chess work, knights are capable of moving in an L shape (see *fig. 1*). (Or a ߆ shape, or even a \ shape depending on who you ask.) Essentially, in one move, a knight moves two squares on one axis and one square on the other.
Tours generally apply to a regular chessboard but it can be calculated for other sizes. For example, see *fig. 2* for a possible knight's tour on a chessboard of size \$5\$. The knight starts in the top-left square, denoted by a \$1\$ and works its way through every square until it finally ends in the \$25th\$ square it visits, in the very center. A tour's validity is not necessarily affected by the squares it starts and ends in.
| [all potential knight's moves](https://i.stack.imgur.com/or1ry.png) | [an example of 5√ó5 knight's tour](https://i.stack.imgur.com/nhtZ1.png) |
| --- | --- |
| *fig. 1* | *fig. 2* |
For grid size \$n = 5\$, that is only one of \$1728\$ options. A regular chessboard, where \$n = 8\$, has slightly more possible tours, with a total of \$19,591,828,170,979,904\$. This is [OEIS A165134](https://oeis.org/A165134).
## Challenge
Write a **program/function** that takes a **grid size** \$n\$ and outputs either a possible valid **board of integers** or **list of coordinates**.
### Specifications
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**.
* \$n > 4\$, as there are no valid tours for those grid sizes.
* Your solution **can either be 0-indexed or 1-indexed** for either step count and coordinates but please specify the format and indexing.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, unless otherwise specified.
* Built-in functions that compute knight's tours (guessing it's just Mathematica here) are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.
### Potential outputs
Considering how many possible tours there are, test cases would serve no real purpose. Instead, a couple possible knight's tours have been provided below for the sake of understanding the format options. Note that the chosen delimiters for the following are **not mandatory**.
| \$n\$ | Board | List |
| --- | --- | --- |
| \$5\$ |
```
1 24 13 18 7 14 19 8 23 12 9 2 25 6 1720 15 4 11 22 3 10 21 16 5
```
| `0,0 1,2 0,4 2,3 4,4 3,2 4,0 2,1 0,2 1,4 3,3 4,1 2,0 0,1 1,3 3,4 4,2 3,0 1,1 0,3 2,4 4,3 3,1 1,0 2,2` |
| \$8\$ |
```
1 50 15 32 55 28 13 3016 33 54 57 14 31 64 2751 2 49 44 61 56 29 1234 17 60 53 58 47 26 63 3 52 45 48 43 62 11 4018 35 20 59 46 41 8 2521 4 37 42 23 6 39 1036 19 22 5 38 9 24 7
```
| `0,0 2,1 4,0 6,1 7,3 6,5 7,7 5,6 7,5 6,7 4,6 2,7 0,6 1,4 0,2 1,0 3,1 5,0 7,1 5,2 6,0 7,2 6,4 7,6 5,7 3,6 1,7 0,5 2,6 0,7 1,5 0,3 1,1 3,0 5,1 7,0 6,2 7,4 6,6 4,7 5,5 6,3 4,4 2,3 4,2 5,4 3,5 4,3 2,2 0,1 2,0 4,1 3,3 1,2 0,4 2,5 1,3 3,4 5,3 3,2 2,4 4,5 3,7 1,6` |
### Validators
**[For output as a board](https://tio.run/##pZTPbts4EMbvfIqvvVhKHcOk/thZNChQIAGKBbaHBO0h8YGyGYuoRGlJKba6yHP0gfpg6VCynGS37WUFGBqOyZnffJxR3TV5ZaLHx4@Xl1cX11c4x01wKqY45eEUvTUYnFxitHrj6Bkdx1P9oRVjmY9G78Z2fzDQs8t1oXBtWzWs/ZPNZF0rswluTkpZB9o0U2hTt00QzlxdaHqHq5Cp/VrVDS4@Xl5YW9nhfC2dYyynNIUyQRYypu@Q4y2Sw/@WwgV3kw/mXhZ68wp/VegtNFVrHe4qi62lpdNfFYJ/8ofwkHzw7HRRwKh7ZZEpH3Z2a27Nda6gy7pyTmdUjnYwVUMbtNlCrnNN@32Cjexmk7DnUHtfRk9XahP4Ogl4iiwM8eocpdy/8D2Hf2J/X0m7GbP93cqN1YVslJVFT/U5V1ZB0q@rWmxV03gesi3WuXIu88fdu38R7UbtbuarUT4i2r3Q7/XPGRxBWC/b7uH7N69dz/EBpZJUR@N5Jo5iVJnMig6SpLdamgYV6dv/PZvNXr/kKQ0BjRrRu9djEM70SbXBzZz6a/ULwqtG1YSn@ivwt6a0T4X5qTYbtSc33TkfFz3xe@X0Rrkp8mo32fTy0RUaryE85TtiZL5VjM9updmqoCQyInpDcp2cUPsPNIR5pHRtGWRT6v/wqdf/04/X/npIzlJTM/n2gSN@ktQc1KSGdXllm3XbuLGbnut1zHpOspmnTB0N5Z7309xNYWd9vYGhfvOFeJdnVKYtqYEaRbMzhPEFrqgXjoHWlaFGatWQqqPR3ov/EXYEDjqB04HSG3sejrodPkS/Ee1Po7d5Q1PzRTlICl4UaisLlNW970ZD8fiDv/2jin5iSUWnOtRVodfDnPiEOX18ul8JexRxKJuxw0h@6jkm4eMjOJI5eIJIIEkgluARojnjKaIISYxkAR4j4khjiAVLOCAQnyGOkdLZFOIMXLAoBl8gnSOhU0vEC4gUacRAS9qfICZnhFSAc8QUf4mI0tF@CpUiprBLiIQJMijdArGAiADCoPhzFqXgZxACINQlQHYMLH4A)** using spaces between columns and newlines between rows. **[For output as a coordinate list](https://tio.run/##fVTbbttGEH3nV0z8QtKlVZISJcBAWiBFAwRFkAcb7YNjFCtyJS5C7rLkSiYr6Dv6Qf0w98ySipykimD4zM7O7cwspxlsafT8@XnTmppqYUtSdWNaS7lUled9ePv27tf7O3pND8FNGtFNEkbkpFFIoEpPkhM@a06Kz17O6dHzchftuhZNoLSNSM26plI28CM/hF1IG9OSIqXx1@xsEE737FvsGngf1NkmJ7WhfJabnbaBCuknSo6eBx1Mbz3Cr2mRJthcvdN7UaniFf2m1ba0tFedsh11f@1EKw9@53OkSuoAniHdUEKy6iT5/pFq00qypdBkdC4pOHAd/2uN06wxTRAew9lH/VH/AZXRvqVS7BFC1fhnqJOS7iF3dOeyk9gKpWdXoStY9szW8zSocoY8pOtrimeZ46Xp1Ws3nUCH3ydYGCTQBrM0dVNJy6l3Laofgx5/PExhOHw6FfwBfbU@2iL3spXVQAbYWdk0Sm@JG7ZGqwvRKgQ3mgR1tagq2UIv2uJrDsOfNdOolQ544JWo14Wg/Jbyh/gxojwMvf6ySTKZMG8Xidlg6A8x3tIj4Q3032gv9OQXY9pCaWG5J1IWPIa1JKlsidrjG6UL2UONmMnp4BryRnaqkF1EpXnyCxrMjtAaTVuJoaJFP1@NNHvmIPrv0bxk8g1NTNgRQzEu8njuL1B7w40nNc56fM4Y8tPx338O5TTVd1RLoSNishLTbVqzFmtMV9AeoxTaktnZ8Xo2@3qI/LEN3OFW6K0MuMRoLOwHfNJjVWzTn216Z9N/acM/UAwG3ISnqeXnuxfs/IuP2X22Z5rDMaJDP9F8LwbMFNdPoqN2pzW/2QozH/cFHu@mctHWIv8Enn74Re6XfIMBC6x3i2vA5urTkIv9WzVBHvHIbh8nUo5Qig3gHFiA14nctD/PFC/Rq8Un8MOCUfiWtqLCytkzPc2r5ciP9aAnkvelxFtsOzlQYyqFfcSd4ISlaJrhJakToTGr/7tL6YfPz3EUUxoltAAugatoDsyAK8qiJTDDeYX7JexWFAOTaAFMgTHN4ZMBVw5T2LLMuAAuoVvBhn3YN0OMJXCFcwacAxPcx7Dj3FxDClwAl8jJNXD@OeQFfBlT6BbwySDPoUsRJwHGOHMsjsk6ts8gz6FbwIcxhW4Buwwy17D8Dw)** using commas between axes and spaces between coordinates.
[This challenge was sandboxed.](https://codegolf.meta.stackexchange.com/a/16920) For over five years.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 170 bytes
```
def f(n,P=[(0,0)]):
for j in range(8):
x,y=P[0];q=x+~(j%2)*~-(j&2),y-(2-j%2)*~-(j//2&2)
if(q in P)-(n>q[0]>-1<q[1]<n)<0and len(R:=f(n,[q]+P))==n*n:return R
return P
```
[Try it online!](https://tio.run/##PY7LCoMwEEX3fsVsWmY0wUcpiDV@Q3ArLgRNq5TRBAu68detQunucuAc7rTOr5Fv6eT2ve0MGGShVYWRiKimzAMzOhigZ3ANPztMTwaLWJWuovph1RJsOFwS8jeJwzUhsUpM5J@EYXLAQ@kN2jOjSSIX9pALGee2iuucKY8abuHdMZaZOi9Utg40kVLsc@a6@eMYSg9@S@@T63lGg3ei/Qs "Python 3.8 (pre-release) – Try It Online")
Some people were really dedicated into golfing this, thanks to everyone!
* *-4 bytes* thank to @movatica by using a `-` instead of a `*` when validating a position, and replacing `all` with a chained comparison between tuple elements
* *-3 bytes* thank to @Arnauld by removing intermediate variables `a` and `b` when creating `q`
* *-3 bytes* thank to @Mukundan314 by moving `x` and `y` to inside the loop and building the tour in reverse
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~205~~ ~~192~~ ~~188~~ ~~186~~ 180 bytes
Original version, with not-so-clever golfings :)
```
def f(n,P=[(0,0)]):
x,y=P[-1]
for j in range(8):
a=j%2+1;b=3-a;q=x+a-a*(j&2),y+b-b*(j&4)//2
if(q not in P)*all(n>v>=0for v in q)and len(R:=f(n,P+[q]))==n*n:return R
return P
```
[Try it online!](https://tio.run/##LY5LCoNAEET3nqI3Cd1@0JgERGnPIG7FxUicRJFWByN6epMJ2T2qikdN@/Ia5ZpM5jgerQaN4hdcYeRHVFPqwObvXFTBpXZAjwZ66ASMkmeLia1BcX@KvUvW8DVQ2cybpwLlYn@Oyd@9Jmgs3ygM4@@40ziDjIuVFOSqYUDJ15wjq15tOpOSBwytYJny74xXzTURs7iSmnZ5G4HSgT8Vx2Q6WVDjnej4AA "Python 3.8 (pre-release) – Try It Online")
* *-4 bytes* by calculating `a` using addition instead of indexing, and inlining `b`
* *-2 bytes* thank to [@xnor's nice remark](https://codegolf.stackexchange.com/questions/269668/horsey-sightseeing/269676#comment585277_269676) about replacing `&` with `%` when calculating `a`
* *-4 bytes* thank to @Mukundan314's improvements regarding returning directly instead of breaking, using list concatenation instead of unpacking, and removing `()` when creating `q`
* *-15 bytes* thank to @movatica's amazing improvements regarding bitwise operations, reordering some declarations, and removing `V` completely (using only arithmetic)
---
*Extremely* inefficient, but it works in theory. It can run \$n = 5\$ on TIO, but it takes ~8 minutes to run \$n = 6\$ on my local interpreter.
A function that accepts \$n\$ as first argument and returns a list of sized-2 tuples.
**How it works?**
The algorithm always start on the top-left corner and uses `P` as a
`list[tuple[int, int]]`.
A horse can have 8 movements, so they can be encoded in an integer (for example, `0b101`):
1. if the first bit is set, then the horse moves 1 piece horizontally and 2 pieces vertically. Otherwise, it moves 2 pieces horizontally and 1 piece vertically
2. if the second bit is set, then the horse moves up. Otherwise, it moves down
3. if the third bit is set, then the horse moves left. Otherwise, it moves right
Therefore, for each movement a horse can make (`for j in range(8):`), decode `a` and `b` as the movement offsets on the board (by reading the first bit of `j`) and calculate `q`, a sized-2 tuple containing the new position of the horse on the board (decoding the movement directions by reading the second and third bits of `j`).
It then checks if the new calculated position is within the board (`all(0<=v<n for v in q)`) and if that position is not already occupied (`q not in P`). If it's valid, then it calls `f` again with that position stored in `P`. If, in any step of the recursion, `P` contains exactly \$n^2\$ elements (i.e. all positions in the board are occupied), then return it.
It outputs
* `[(0, 0), (1, 2), (2, 4), (4, 3), (3, 1), (1, 0), (2, 2), (0, 3), (1, 1), (3, 0), (4, 2), (3, 4), (1, 3), (0, 1), (2, 0), (4, 1), (3, 3), (1, 4), (0, 2), (2, 1), (4, 0), (3, 2), (4, 4), (2, 3), (0, 4)]` for \$n=5\$
* `[(0, 0), (2, 1), (4, 0), (3, 2), (1, 1), (3, 0), (5, 1), (4, 3), (5, 5), (3, 4), (1, 3), (0, 1), (2, 0), (1, 2), (3, 1), (5, 0), (4, 2), (5, 4), (3, 5), (1, 4), (0, 2), (1, 0), (2, 2), (4, 1), (5, 3), (4, 5), (3, 3), (5, 2), (4, 4), (2, 5), (0, 4), (2, 3), (1, 5), (0, 3), (2, 4), (0, 5)]` for \$n=6\$
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), ~~14~~ ~~13~~ 12 bytes
-1 byte thanks to Mukundan314
```
ẊṖΩᵃȧᵛΠ2p≈}h
```
[(Don’t) Try it Online! (link is to literate version)](https://vyxal.github.io/latest.html#WyJsVCIsIiIsImNhcnRlc2lhbi1wcm9kdWN0IHBlcm11dGF0aW9ucyBmaWx0ZXI8XG4gIGFwcGx5LXRvLW5laWdoYm91cnM6IGFicy1kaWZmXG4gIHZlY3RvcmlzZTogcHJvZHVjdFxuICAyIHByZXBlbmQgYWxsLWVxdWFsP1xufSBmaXJzdCIsIiIsIiIsIjMuNC4xIl0=) because it's way too slow.
This brute-forces solutions, so it’s horribly inefficient. It times out on the online interpreter very quickly, and hits Scala's garbage collection limit with the native build after a few minutes.
The last 2 bytes can be removed if outputting all possible solutions instead of just the first one is OK.
### Explanation
```
ẊṖΩᵃȧᵛΠ2p≈}h­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌­
Ẋ ## ‎⁡Treating the input as the range [1, it], take the
## ‎⁡ cartesian product with itself. This gives the
## ‎⁡ list of coordinates of the n*n chessboard.
Ṗ ## ‎⁢Take the permutations (all orders of the elements)
## ‎⁢ of the board. This is the slow part.
Ω ## ‎⁣Filter the permutations, only keeping those for
## ‎⁣ which the following function returns true:
ᵃ ## ‎⁤ Apply the following to each pair (including
## ‎⁤ those which overlap):
ȧ ## ‎⁢⁡ Absolute difference.
ᵛ ## ‎⁢⁢ Apply to each resulting pair:
Π ## ‎⁢⁣ Take the product of the list. This will
## ‎⁢⁣ be 2 if and only if the two pieces were
## ‎⁢⁣ a knight's move away.
2p ## ‎⁢⁤ Prepend a 2 to this list.
≈ ## ‎⁣⁡ Are all elements of the list equal?
} ## ‎⁣⁢Close the filter function.
h ## ‎⁣⁣Return the first successful solution.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
Independently derived from, but using a very similar method to, @Mukundan314’s solution.
[Answer]
# JavaScript (ES6), 141 bytes
Returns a list of 0-indexed coordinates as a single string.
```
f=(n,x=0,y=0,o="",k=n*n)=>x/n|y/n||(o+=p=` ${[x,y]} `).match(p+".|-")?0:--k?[...s="01344310"].some((d,i)=>f(n,d-2+x,s[i+6&7]-2+y,o,k))&&O:O=o
```
[Try it online!](https://tio.run/##XY3daoNAFITv@xSHJchu9yemSRpIeppHyANYQfGnNZo9kpWiqM9uNre5GIbhG2au6X/qsnvVdtpSXixLidyqHkM1eBEypmq071bgd7@20@A1cZLYYgKrMerVEM@QCHNLu@yPt5KZSTNxDo9a1@fIGOOQhZvtbrfdhCw2jm4F57mq/F7pj3L9IXvlokp@BofYh0GRqoUIgsvxgrSUdOdN0YEFhP3J2xfCwbuUAsY3gIyso6YwDf3y5FlajXZOxOkF@SsBEtiPZZ7NywM "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
x = 0, y = 0, // (x, y) = current position
o = "", // o = output string
k = n * n // k = move counter
) => //
x / n | // if x >= n
y / n || // or y >= n
( o += p = // or the updated output obtained by adding
` ${[x,y]} ` // the new position p = x,y surrounded by spaces
).match( // contains:
p + ".|-" // either p followed by any character
// or the minus sign
) ? // then:
0 // abort
: // else:
--k ? // decrement k; if it's not 0:
[...s = "01344310"] // s = offset sequence
.some((d, i) => // for each value d at index i in s:
f( // do a recursive call:
n, // pass n unchanged
d - 2 + x, // update x
s[i + 6 & 7] - // use the shifted sequence "10013443"
2 + y, // to update y
o, // pass the new output
k // pass the updated counter
) // end of recursive call
) // end of some()
&& O // if truthy, return O
: // else:
O = o // success: save o in O
```
---
# JavaScript (ES8), 151 bytes (faster)
Returns a matrix with 0-based indexing.
```
n=>(m=[...s="".padEnd(n)].map(_=>[...s]),g=(x,y,k)=>!(m[y][x]=--k)|m.some((r,Y)=>r.some((v,X)=>v|(X-x)**2+(Y-y)**2-5?0:g(X,Y,k)))?m:m[y][x]=0)(0,0,n*n)
```
[Try it online!](https://tio.run/##XY/PaoNAGMTveYqt9PB9urtIIFBi15z6BLkoVhqJfzBxd2VdJJLk2e0qbQ89zW@YYWAuxVgMZ9P2lildVnMtZiVikCLjnA/C83hflB@qBIU5l0UPXyJeoxxpI@BGJ3pFEb@AzKY8u@WCsSs@JB@0rAAMTV1oftxIE@fGByTshr6/DSBl0wJsdwj3DSQ0dWOIB7n/XQsRQhpS5Suca22gqyxRRJBd5ORdkDenQYDkviHkrNWgu4p3uoHTUnq9q@cJo39R7a6sTwwRMTErjguO3OqjNa1qAJfXR1sYC1tEftGtAo94f/ipPCQBWTXaPOdv "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 77 bytes
```
NθFθFθ⊞υ⟦⁰ικ⟧Fυ⊞ιΦυ⁼⁵ΣXEι∧ν⁻§κνμ²≔⟦§υ⁴⟧υ≔⟦⟧ηW⌊υ«⊞ηι≔⁻⊟ιηυFυ§≔κ⁰L⁻§κ³η»Eη⭆¹✂ι¹
```
[Try it online!](https://tio.run/##ZU@xbsIwEJ2Tr7jxLLkSlDIxZQAJqVSRGBFDGtzYwnEg9hWkqt/unhMiIdWD7Xf37t17ta76uqtsjFt3ofBB7afq8SpW@VfXA39gekvyGknCYSbBSDgfJw49elzcGBt4nFnrK1XW41LCnlosuxuXd9UlkQp3QidhZxx5LMLWndQdzxKckNAKwferSGeVF96bxuFhIrHumzhKoKceQ83wpo1VgCxqWl5IQsBPng2@NPtlRvaYGPeWHXsRaXaUy6YoI@vJFsd9V64JGv85XgwCyelvXvbGhSEi79sHRk0CcwbW1CoFnw@pYlzGl2/7Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a list of `0`-indexed coordinates. Explanation: Uses Warnsdorff's rule, but always starting from `[0, 4]`, because the rule won't work starting at the corner of the size `11` board.
```
NθFθFθ⊞υ⟦⁰ικ⟧
```
Input `n` and create a "board" of `n²` squares, with each square initially represented by its unvisited neighbour count and co-ordinates.
```
Fυ⊞ιΦυ⁼⁵ΣXEι∧ν⁻§κνμ²
```
Loop over the board, calculating the list of neighbours of each square.
```
≔⟦§υ⁴⟧υ
```
Start with `[0, 4]` as a potential next square, to work around the case of the size `11` board. (Otherwise this line of code would have been unnecessary.)
```
≔⟦⟧η
```
Start with no squares visited yet.
```
W⌊υ«
```
Until there are no squares left to visit, get the one with the fewest unvisited neighbours.
```
⊞ηι
```
Save this to the tour of visited squares.
```
≔⁻⊟ιηυ
```
Get the list of unvisited neighbours of the current square.
```
Fυ§≔κ⁰L⁻§κ³η
```
Update the number of unvisited neighbours for each unvisited neighbour.
```
»Eη⭆¹✂ι¹
```
Pretty-print the final tour.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), ~~19~~ 14 bytes
-4 bytes thanks to @noodleman
```
ẊṖΩᵃȧᵛSu2ɾw₌}h
```
This program involves exhaustively examining every coordinate list, making it impractical to run within a reasonable timeframe, even for the smallest input value of \$n = 5\$.
Should output a 1-indexed coordinate list.
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLhuorhuZbOqeG1g8in4bWbU3Uyyb534oKMfWgiLCIiLCIyIiwiMy40LjEiXQ==)
### Explanation
```
ẊṖΩᵃȧᵛSu2ɾw₌}h­⁡​‎‏​⁢⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏⁠⁠‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠⁠⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁤‏⁠⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠⁠⁠⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁡​‎⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌­
# ‎⁡implicitly push input onto stack
Ẋ # ‎⁢generate all coordinates (cartesian product of [1;n] with [1;n])
Ṗ # ‎⁣all permutations of the coordinates
ΩᵃȧᵛSu2ɾw₌} # ‎⁤filter for knight tours:
ᵃȧ # ‎⁢⁡ absolute difference between adjacent coordinates
ᵛS # ‎⁢⁢ sort each coordinate
u # ‎⁢⁣ uniquify all coordinates
ɾw₌ # ‎⁢⁤ equals [[1, 2]]
h # ‎⁣⁡first element of filtered permutations
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
---
Note: This is one of my first Vyxal programs, and given that it won't run in a reasonable amount of time for even the smallest input, it is very possible I have made a mistake in the code
[Answer]
# Haskell + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 37 bytes
```
g1(mF(fe[(1,2),(2,1)])<δ')<pm<j2q<e1
```
This is *horrendously* slow. It's time complexity is \$\mathcal O(4^n! 4^n)\$ (careful analysis might show that this bound could be lowered) on the number of bits in input. I've only been able to get it to halt for cases where \$n < 4\$, so I've never observed it produce a correct output.
## Explanation
* `e1`: enumerate from `1` to the input
* `j2q`: get the cartesian product of this with itself to get the coordinates of the board
* `pm`: get all permutations of the input
* `g1`: get the first permutation satisfying a predicate
* `δ'`: get the absolute difference between consecutive elements
* `mF$fe[(1,2),(2,1)]`: check if they are `(1,2)` or `(2,1)`.
In summary this searches through all the permutations for one that consists solely of knights moves.
### Reflection
At some point in the future there will be some graph utility functions, which would be able to handle this sort of thing not only shorter, but faster. But that's a bit of a long term requirement.
Here are some short term possibilities:
* There should be something along the lines of "apply this function or not", currently it seems the way to do this is `ap[f,id]` which is pretty long.
* There should be a function to determine if all elements of one list belong to another.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 123 bytes
```
f=lambda n,x=0,*p:x%(y:=n+2)<n>x/y>=(x in p)<1and max((f(n,x+b,x,*p)for a in(n+4,n,n+n+5,n+n+3)for b in(a,-a)),key=len)or p
```
[Try it online!](https://tio.run/##HYxLDoMwDESvkk0lu3HVD0VCiHAXRxAVFUwUsXBOn6ZsZjHvzcR8fHZpuphKCW7lzU9shNQ96Bp7vUDundgXDjLqPY8O1CxiIg5PlslsrAABqm89aV1g2JPhqoDYNwmJFdue2ZzI/xHTjRHpO2e3zoK1jiWmRY561SKWHw "Python 3.8 (pre-release) – Try It Online")
Brute force approach, an adaptation of my answer to [Holey Knight's Tour](https://codegolf.stackexchange.com/a/205832/87681).
Essentially, the board is a 1D-representation of a 2D padded grid. The horsey will hop recursively over the board while avoiding the padding and keeping track of the current (`x`) and previously visited (`p`) squares.
Coordinates are 0-indexed and 1-dimensional from left to right and top to bottom, with a gap of 2 indices at the edges. That is, for a 5x5 grid:
```
0 1 2 3 4
7 8 9 10 11
14 15 16 17 18
21 22 23 24 25
28 29 30 31 32
```
] |
[Question]
[
You work at a bakery, and every day you make pastries. You make 100 of each of several different types. However customers are less predictable. Some days they order all of one kind of pastry and you run out, some days they order hardly any and you have some left over. So your boss has made up a chart which tells you how many days each type of pastry can last before it's too old and can't be sold anymore. When there are leftover pastries the customers will always buy the freshest pastries first.
As an example lets use donuts, which (according to your boss's chart) can be sold 2 days after they are baked. Lets say you start the week with 0 donuts left over and the following are the orders for 5 days:
| Mon | Tue | Wed | Thu | Fri |
| --- | --- | --- | --- | --- |
| 25 | 75 | 55 | 155 | 215 |
* On Monday you bake 100 donuts and sell 25, you have 75 left over.
* On Tuesday you bake 100 donuts and sell 75. Since customers prefer fresh donuts, all 75 donuts sold were ones baked on Tuesday. You have 75 still left over from Monday and 25 left over from Tuesday.
* On Wednesday you bake 100 donuts and sell 55. Since 55 is less than 100, all the donuts sold are fresh from that day. The 75 from Monday are now 2 days old and have to be thrown out. You have 25 still left from Tuesday and 45 from Wednesday.
* On Thursday you bake 100 donuts, and get 155 orders. The 100 fresh donuts get sold first, leaving 55 more orders to be filled, you sell all 45 donuts from Wednesday leaving 10 more orders which can be filled with donuts from Tuesday. At the end of the day you have 15 donuts from Tuesday which have to be thrown out.
* On Friday you bake 100 more donuts and get 215 orders. You only have 100 donuts so you only sell 100 donuts.
## Challenge
Your program will take as input the number of days a particular pastry lasts (e.g. 2 for donuts) and the number of orders for that pastry each day over a period of time. The output will be how many pastries will be sold over that period of time.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
1 [100,100,100] -> 300
1 [372,1920,102] -> 300
1 [25,25,25] -> 75
1 [25,100,120] -> 225
1 [25,100,100,120] -> 325
1 [0,200] -> 200
1 [0,175,75] -> 250
1 [75,150,150] -> 300
1 [0,101,199]-> 201
1 [200,0] -> 100
2 [100,100,100] -> 300
2 [372,1920,102] -> 300
2 [25,25,25] -> 75
2 [25,100,120] -> 245
2 [25,100,100,120] -> 325
2 [0,200] -> 200
2 [0,175,75] -> 250
2 [75,150,150] -> 300
2 [0,101,199]-> 300
2 [200,0] -> 100
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes
```
ȧ₁?›(-½:ȧ~+^-Þr)_-∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLIp+KCgT/igLooLcK9OsinfiteLcOecilfLeKIkSIsIiIsIlsyNSw3NSw1NSwxNTUsMjE1XVxuMiJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwi4oyI4bmq4bmqReG5mMKoUyIsIsin4oKBP+KAuigtwr06yKd+K14tw55yKV8t4oiRIiwiIiwiMSBbMTAwLDEwMCwxMDBdIC0+IDMwMFxuMSBbMzcyLDE5MjAsMTAyXSAtPiAzMDBcbjEgWzI1LDI1LDI1XSAtPiA3NVxuMSBbMjUsMTAwLDEyMF0gLT4gMjI1XG4xIFsyNSwxMDAsMTAwLDEyMF0gLT4gMzI1XG4xIFswLDIwMF0gLT4gMjAwXG4xIFswLDE3NSw3NV0gLT4gMjUwXG4xIFs3NSwxNTAsMTUwXSAtPiAzMDBcbjEgWzAsMTAxLDE5OV0gLT4gMjAxXG4xIFsyMDAsMF0gLT4gMTAwXG4yIFsxMDAsMTAwLDEwMF0gLT4gMzAwXG4yIFszNzIsMTkyMCwxMDJdIC0+IDMwMFxuMiBbMjUsMjUsMjVdIC0+IDc1XG4yIFsyNSwxMDAsMTIwXSAtPiAyNDVcbjIgWzI1LDEwMCwxMDAsMTIwXSAtPiAzMjVcbjIgWzAsMjAwXSAtPiAyMDBcbjIgWzAsMTc1LDc1XSAtPiAyNTBcbjIgWzc1LDE1MCwxNTBdIC0+IDMwMFxuMiBbMCwxMDEsMTk5XSAtPiAzMDBcbjIgWzIwMCwwXSAtPiAxMDAiXQ==)
[Answer]
# [J](http://jsoftware.com/), 59 bytes
```
1 :'1#.]<.##&>@{.[:(a(#~u>:])@,1+}.)&.>/@|.\(<a=.100$0),;/'
```
[Try it online!](https://tio.run/##fY9NT4NAEIbv/Iqpa1iIdLoziIQtEGITT8ZDr5WYxtgYL548@fHXcWBbii2Y7CQz7zsf@7w12cxSfTOzmdae5HFaG3gCCe8C9Q4KCxoiqa3EHGG1vr9rCKwmhXWOSvll9YkbG2wD9fNR2jqsIrr6xtDHclF94WOQbwskYy5NGC0Xugm9h1uEOk0CU@K8b6uW0pNXkfKN9/L8@g4RAsEOOAExgNh4To@lKjqr012cWnHKQBm3HjsvTfaWLOyek5kH@uGQW3bmDF3uT5k234vJUSQ5mCan/xKRpEnisIaOE5JTljmD@pH20h8@nkbnaXQ@R78e6CPo/C86j6HzBDqPoMeDNSPo3KM3vw "J – Try It Online")
Probably not the golfiest possible J approach but I liked the simplicity of it...
Rather than working with numbers that represent *pastry count*, we use a unary number system, representing every pastry with its own number. For counting available pastires, the number itself is irrelevant (any number = 1 pastry), but we also let the number represent pastry age, so we can use it to filter too-old pastries.
Thus, we seed the reduction with 100 zeroes, representing the first day's fresh pastries.
Now we simply:
* Kill `}.` `n` elements where `n` is the days order
* Add 1 to every number remaining on our list
* Prepend a fresh 100 zeroes to the list
* Filter away numbers that have exceeded the input limit
Finally, we do a scan of the reduction so we have the intermediate results, min those with the input, and sum.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~51~~ 34 bytes
```
≔⟦⟧ζFη«F¹⁰⁰⊞ζθFιF¬¬ζ⊞υ⊟ζ≔⊖Φζκζ»ILυ
```
[Try it online!](https://tio.run/##RY89C4MwEIZn/RU3JpCCFTp1KoVugtgxOARJNWi15sPB4m9Pk/jR5eDufd6796qGyWpgnbU3pUTdo4x90EggwQRGfI1fgwTUYPjGUW5U46Vzkjgh2nhaEph9H8iCT1wqjkYcLDuUiV68zRtRQaAt3WruHetGs3fu8ooXom609xjlNALiD88Ewhy13uXny5HkITrN5RFhdme67YslzqXoNbozpdHTBTHYma2lKQGaXsJPe0mTsrSnqfsB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now uses @Jonah's method.
```
≔⟦⟧ζ
```
Start with no pastries.
```
Fη«
```
Loop over the orders.
```
F¹⁰⁰⊞ζθ
```
Bake 100 fresh pastries.
```
FιF¬¬ζ⊞υ⊟ζ
```
For each ordered pastry, try moving the freshest remaining pastry from the shelf to the customer.
```
≔⊖Φζκζ
```
Remove the stalest left-overs and decrease the freshness of the remaining left-overs. (This is actually `≔⁻Φζκ¹ζ` on TIO because its version of Charcoal can't decrement an empty list and I'm too lazy to switch the links over to ATO where it works.)
```
»ILυ
```
Output the final count of sales.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~125~~ ~~123~~ 121 bytes
* *-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
s;f(*o,n,d){for(int l[n],a,i,j=s=0;j<n;s-=*o++)for(l[i=j++]=100,s+=*o;~i&&j+~i<=d;*o-=a)l[i--]-=a=fmin(*o,l[i]);o[-n]=s;}
```
[Try it online!](https://tio.run/##bVLbjtowEH12vmJKBeTiVIm7CCFj3lqpEupb1QdAVZoLa5TYKA5I7Yr99KVjBxCsKsWRfc7MmTNj53FeZ2p7Phte@aGmihbBS6VbX6oO6pXa0IxKuhNGJHw3V9zEItRRFNiQeiXFLoo2Ik0SaiIk@KscjXbRq5yLgoc6FlmAQXG8wZ2oGqlsCUQ2AderWG2E4afzR6ny@lCUMDddIfWn54X3ANXyt8U8dOQ1GWoctSwC78Uj1mOo26JsDYUjhSL7Y7hH8ueshbCWqgQB338sl4gZ@bf81YGikGd7hJ8o1KWyxJVpy6zA89dvyy8Qmg6PDfc8go2C39fAtDyra537qEHhKeDguzQktmVnC/oj@6cwwkK2GxUEsICEQ5XX2pR@r4sguieyAt@Gr3qRGNINCAHjtRoHSBPHxbFjkUEiGaND0osgUDVlo/el8vuiLpDCoB0E/CJfmTxT1aUsUsNigObsnAL4ICB1dXKtOqkOpU1y7eJkUN26/m/68dJTP5UVRuMjwISjU3NdWQE7rb2DyG1@qOMGeL00O0kIBbAAQjtQ6@BGokp/pw7ft3jdlT8YmnUXL2BYrBWa6Tu/PAIbd8I7a8vu0Cq06J3OKcHXeVteSj5PGUlnzJ6ZPbPJ5ev3LpIl96ceQSAhDPfE7dLphExdEv7TSeJWzyRYczZzChhuEzz26IK9c8HuXLAHF@y9C3Zzwe5csAcX7N4Fu7p4y6s625pz/FPpWDb7Wuay@wc "C (clang) – Try It Online")
[Answer]
# [Go](https://go.dev), 169 bytes
```
func(n int,a[]int)(s int){b:=[]int{100}
for _,q:=range a{x:=0
for i,v:=range b{if i>n{x=0}else if v<q{x=v}else{x=q}
q-=x;s+=x;b[i]-=x}
b=append([]int{100},b...)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZTNboJAFIU3Xc1TUFeQjoQZa6y29A2adG9MM1gwpDoCIjEh8yTdmCZd9JHs0_TypzJcmohwz5nPe2c48fNrtT2ebiOx_BAr39iIUJJwE22T1B4Em3RASCYSI3C_92kwfDj9BHu5NKURypSK-QJulrkrKiv3Zm4p5MxxFAm2ifFG45mbCAm_K_LDzHVKNaRZo3p5GBjhs8wPrqP89c43oM6eYqizsoaHWJF46B4ed3fw5c3DBRSKeK6IIl--m5eW1LNt21Ik8dN9IlU18O_NSzFxuS_TMnLymsD6tTQZPZO0vhQdwUOAWpbVIUcTTtmUFz7X0ZaHsHxMy4-ik_EVdpZxpByGw5yca1Tj_MM17Ahl-3mH8uJoeGt_lYiuZrCjCWyMj9tArSMMGAwWw6Uf45WD93IYHPO0mI61m9UGdh7QARqxVqNKvFrN--OBWQiJxQP1EFaLR0fGkUs87jUKeb26245Hj4vwrXjwvnjwnnh0dITpxgNx8F5NPEbadEg8OBYPrsej_lc5Hqv7Hw)
Port of [Arnauld's solution](https://codegolf.stackexchange.com/a/257342/77309).
[Answer]
# JavaScript (ES6), 80 bytes
Expects `(days)(orders)`.
```
n=>a=>a.map(q=>b=[100,...b].map((v,i)=>(q-=x=i>n?0:v<q?v:q,t+=x,v-x)),b=[t=0])|t
```
[Try it online!](https://tio.run/##jZHBjsIgFEX38xUsIUMRXiWNZqgfYlhURyc1Tmu1IV3475UyzURTqCSwaU7vu49zKkxx21/LS5tU9fehP6q@UnlhD/stLrhR@U5tBeeUMbbT7hs2tCQqx02iOlXm1YavzVezMeuGtp@qoybpCKH2t1ZxTe5tv6@rW30@sHP9g49YEOwCx6sRQoSgxQKlnH9M0TQDKlYwsKDnUZDUnSHyPzWTftKNBzd@JAHm0BEf53tRTuFvn@f54K1qwzJJs9eqIH2o5YTkw33qmoZSubCvtdIvBYRvLbvPpKuYpEK8LIiXBdGyIChrOYe@kQXxsiBeFsTLgpCswFsFZPUP "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // outer function taking n (number of days)
a => // inner function taking a[] (list of orders)
a.map(q => // for each number q of orders for each day:
b = // update b[], an array keeping track of remaining
// pastries in reverse chronological order
[100, ...b] // create 100 pastries for today
.map((v, i) => // for each stock value v for today minus i days:
( q -= // subtract from q
x = // the number x of pastries sold, defined as:
i > n ? // if i is greater than n (beyond expiry date):
0 // nothing
: // else:
v < q ? // if the stock is less than the orders:
v // the entire stock
: // else:
q, // the remaining number of orders
t += x, // add x to the total t
v - x // subtract x from v and store this in b[]
) // as the remaining stock for this day
), // end of inner map()
b = [t = 0] // start with t = 0 and b[] = [ 0 ]
) | t // end of outer map(); return t
```
[Answer]
# Python, 105 bytes
```
f=lambda n,d,i=0,x="":d>[]and len((x:=str(i)*100+x)[:d[0]])+f(n,d[1:],i+1,(x+" ")[d[0]:x.find(str(i-n))])
```
I would be *very* surprised if this was optimal.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 150 bytes
Since in any case the WL will not be the winner, I allowed myself to be creative to the challenge.
So we start one day in the morning with *non-negative array of donuts*: \$[50, 50, 0, 25, …]\$
First item (here is \$50\$) means how many donuts are baked every day. In the original challenge it is constant \$100\$. Other items are numbers of donuts leftover from: yesterday, 2 days before etc.
So the length of this array is the shelf life + 1.
The second input is an array of orders.
```
Last@With[{d=#1[[1]]},Fold[{Prepend[Rest@Most@FoldList[If[#1<0,#1+#2,#2]&,-#2,#1[[1]]]/._?Negative->0,d],#1[[2]]+Min[Total@#1[[1]],#2]}&,{#1,0},#2]]&
```
So test cases from the original challenge will be looks like:
\$[100, 0] [372,1920,102]\$
\$[100, 0, 0] [372,1920,102]\$ etc.
Here are some advanced test cases:
Every day we bake 50 donuts, from last day leftover 25 donuts, shelf life is 1 day:
\$[50, 25] \$
Orders:
\$[372,1920,102]\$
Output: \$175\$
Every day we bake 125 donuts, from 2 days before leftover 10 donuts, shelf life is 3 days:
\$[125, 0, 10, 0] \$
Orders:
\$[25,100,100,120]\$
Output: \$345\$
[Try it online!](https://tio.run/##fY1BSwNBDIXv/oqFgb001SSySMFqT0KhlSKChxDK0J21A@2utEMvw/72dWb1UhAPLyQvX16ONuzd0Qa/s0MzH1b2HBYfPuwl1nNDIqTaw0t3qCVuTu7LtbW8ucSsu1Syv/LnIMtGDD0iGJoYBsNawjQ3PwF6d1tsn1/dZ3pzcdMnhFrHHatO1r6V9y7Yw@KXzud9CdEQYJ8HLYfNybdBGomEmN14/8BAM0Yg5F715hoYEa4gD6MYr6AKgat/U9JxgVBQ0p9Zwzc "Wolfram Language (Mathematica) – Try It Online")
Non-golfed version with named variables:
```
bakery[donuts_List, orders_List] :=
Last@With[{daily = First@donuts},
Fold[
{Prepend[
Rest@
Most@FoldList[If[#1 0
, daily],
#1[[2]] + Min[Total@#1[[1]], #2]
} &, {donuts, 0}, orders]
];
```
] |
[Question]
[
Your input is the height map of a tower. The tower is made out of layers, each one being one unit shorter than the one below it. Every layer is completely on top of the previous layer. For example `[1,5,4,3,2]` is a valid input. Here is a visualization:
```
#
##
###
####
#####
15432
```
Your task is to wiggle the tower. Wiggling works as from top to bottom. For each layer, we first try to shift left. If we can, we shift left and then stop. If we can't, we shift the layer to the right and repeat for the next layer. If we reach the bottom layer we stop. The bottom layer doesn't move anywhere. When a layer is shifted, the layers above it also move the same amount in the same direction.
Here is a wiggle, step by step:
```
#
##
###
####
#####
#
##
###
####
#####
Top layer couldn't move left, so move right and repeat
#
##
###
####
#####
Layer 2 couldn't move left, so move right and repeat
#
##
###
####
#####
Layer 3 couldn't move left, so move right and repeat
#
##
###
####
#####
Layer 4 could move left, so the wiggle stops here.
Wiggling would anyway finish at the second lowest layer, since the lowest layer is immovable.
```
This means that if your program got input `[1,5,4,3,2]` it should return `[2,3,4,5,1]`.
Because of the mathematics of tower wiggling, your input is always a permutation of the positive integers up to the array length, and also there are \$2^{n-1}\$ valid inputs (and outputs) for arrays of length \$n\$.
# Test cases (all towers up to \$n=10\$)
```
[1] -> [1]
[1, 2] -> [2, 1] -> [1, 2]
[1, 2, 3] -> [1, 3, 2] -> [2, 3, 1] -> [3, 2, 1] -> [1, 2, 3]
[1, 2, 3, 4] -> [1, 2, 4, 3] -> [1, 3, 4, 2] -> [1, 4, 3, 2] -> [2, 3, 4, 1] -> [2, 4, 3, 1] -> [3, 4, 2, 1] -> [4, 3, 2, 1] -> [1, 2, 3, 4]
[1, 2, 3, 4, 5] -> [1, 2, 3, 5, 4] -> [1, 2, 4, 5, 3] -> [1, 2, 5, 4, 3] -> [1, 3, 4, 5, 2] -> [1, 3, 5, 4, 2] -> [1, 4, 5, 3, 2] -> [1, 5, 4, 3, 2] -> [2, 3, 4, 5, 1] -> [2, 3, 5, 4, 1] -> [2, 4, 5, 3, 1] -> [2, 5, 4, 3, 1] -> [3, 4, 5, 2, 1] -> [3, 5, 4, 2, 1] -> [4, 5, 3, 2, 1] -> [5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6] -> [1, 2, 3, 4, 6, 5] -> [1, 2, 3, 5, 6, 4] -> [1, 2, 3, 6, 5, 4] -> [1, 2, 4, 5, 6, 3] -> [1, 2, 4, 6, 5, 3] -> [1, 2, 5, 6, 4, 3] -> [1, 2, 6, 5, 4, 3] -> [1, 3, 4, 5, 6, 2] -> [1, 3, 4, 6, 5, 2] -> [1, 3, 5, 6, 4, 2] -> [1, 3, 6, 5, 4, 2] -> [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4, 3, 2, 1] -> [6, 7, 10, 9, 8, 5, 4, 3, 2, 1] -> [6, 8, 9, 10, 7, 5, 4, 3, 2, 1] -> [6, 8, 10, 9, 7, 5, 4, 3, 2, 1] -> [6, 9, 10, 8, 7, 5, 4, 3, 2, 1] -> [6, 10, 9, 8, 7, 5, 4, 3, 2, 1] -> [7, 8, 9, 10, 6, 5, 4, 3, 2, 1] -> [7, 8, 10, 9, 6, 5, 4, 3, 2, 1] -> [7, 9, 10, 8, 6, 5, 4, 3, 2, 1] -> [7, 10, 9, 8, 6, 5, 4, 3, 2, 1] -> [8, 9, 10, 7, 6, 5, 4, 3, 2, 1] -> [8, 10, 9, 7, 6, 5, 4, 3, 2, 1] -> [9, 10, 8, 7, 6, 5, 4, 3, 2, 1] -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~126~~ 121 bytes
-5 byte from Neil
```
f=(x,n=x.length,s=n,j,k=(x+'').match(`(.*?)((\\d+,)?${s})\\b(.*)`))=>k?f(x,--n,[s,n],k):j[1]+j[2].split`,`.reverse()+j[4]
```
[Try it online!](https://tio.run/##hZ1bb1zHEYTf/Sv4EMBcayWbl90znYDWD5GEiJLpi6xIhiUYBoL8dkVL7tmZrv5q@JIgVO3uOXPpqa6unry7/ev209s/f/vj89MPH3@6@/Ll55vzv7cfbv5@9v7uwy@ff91@uvmwfbf9/etfn3z77ebZf24/v/31/PX5s@@eb87PX7786cl28/wf//30v83Ll2@@/nXzerO5@fH35z9//ZanTz9sX3zafni1/X3zz3cvLl49effi8tWzT3@8/@3z6@3rZ3/e/XX356e7883Xv1@/@vKv118hZ09/PPv6X9@8uNieXT78r8vt2fr3w98e/ml7dnX629UIvTqhr@5hw0cPnzl9ent2Pf7LtXzh9ek7Lx7@UX7j@vTNl@u/95@9Hn/5@GF9ksPvjw@zPdvJv@/qI@7Gp7x8gNQH343PfrWi0u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fxSLwgp5heBkPkF7xHJ5pcKKeaXet1IMb8IhMwv9VaSYn4RCJlf5PISMr@MEGN@wTtOsvmlQor5pV6FUswvAiHzS70xpZhfBELmF7lYhcwvI8SYX@r9K8X8IhAyv8g1LWR@GSHG/CK3uZD5ZYQY88t46Ysxv/SLX6z55fG7Ye7vf/nm8P9g/8f727d359@fv3zx7LvnL19tDp87f35z@t@b73/Znp3/e3u7fbO5@fHtxw@fPr6/e/b@4y/ntzd3f92@P7/dbM9@vv/PNw9/eHP8w83Nm83my/8B "JavaScript (Node.js) – Try It Online")
Reverse `(_,)n,n-1,n-2,...,n-k` which seems correct but long
[Answer]
# [Python](https://www.python.org) NumPy, 57 bytes
```
def f(L):a=L.argmax();m=L>=(a and L[a-1]);L[m]=L[m][::-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZ1LblzXEYbnWkXDIzJoCear720Z9NyAdkBoQECSQ0WiCFEOokk2koknyTRryDKS1YTN7j5V_19fXWfgWKqvu8-rXv85Qf7xr4fv3_785f733__527cPL-f_bt-9_7D6cPLm9PXt9ZtXt19__Xz7t5PTnz5fv_n5-uR2dXv_bvXm5vbl2dvTn97cfH57vfvHzevXT39x-IL_3H1--PL12-rx--OLw7_e__b54fvq9nF1__Diw5evq7vV3f3O_urx27u7-1df39---3R3__7x5PT1i9Vq9cvqenXzp8-3Dyf3D08j-Hr7fb37w_u_3n5a3716fPh09-3kh9XLn1c_nJ6evt194uPTJ365-fH538cP_HJz9vrt8xc-_ef28fH900huP306-XDy8fSJ-Xh9ffLx9fXd6emLh693909f-WRcffnLD6f7ifz-v7__--bs7e53nv7rxc3ZenW-_9P5enX8-93f7U3r1cX4u4uMXgz64hlLH919Znx6vbrMlkv7wsvxnWd7o_3G5fjm86M9fvYy__Lhwz6S3e_nwaxXV2a_qkO8yqM83yN14Fd57BdHSqZzlWd0Nr6oTvIqz3N8l0z9Ks_-PH2XLMhVXoMYVF6mK1upGBQs3m69bP3Wq02lNriwG1vbiz2IK76xRb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_cQT0F0dAfxGE9RdHQH8RhPUXQVh_CaTVXxgR_QUQ118Acf3FEdBfAHH9xRHQXxwB_UUQ1l8Acf3FEdBfHAH9RRDWXxwB_UUQ1l8EYf0lkFZ_AcT1F0dAf3EE9BdBWH9xBPQXQVh_EYT1l0Ba_cUR0F8EYf1FENZfAmn1F0FYfwmk1V8CafWXA9KKL-cLyOFLWyTG1SIxLkZkgVokFogRWSBGZIEA8VPTInFqGJFTw4icGkD81DAipwYQPzWA-KlxBEJMi0SIYURCDCMSYgDxEMOIhBhAPMQA4iHGEQgxjEiIAcRDDCAeYhyBEAOIhxhHIMQ4AiFGEK5fWiTqF0akfmFE6hdAvH5hROoXQLx-AcTrF0egfmFE6hdAvH4BxOsXR6B-AcTrF0egfnEE6hdBuH5hROoXQLx-AcTrF0egfgHE6xdHoH5xBOoXQbh-AcTrF0egfnEE6hdBuH5xBOoXQbh-EYTrl0Ba8aVFQnxhRMQXRkR8AcTFF0ZEfAHExRdAXHxxBMQXRkR8AcTFF0BcfHEExBdAXHxxBMQXR0B8EYTFF0ZEfAHExRdAXHxxBMQXQFx8cQTEF0dAfBGExRdAXHxxBMQXR0B8EYTFF0dAfBGExRdBWHwJpBVfGBHxBRAXXwBx8cUREF8AcfHFERBfHAHxRRAWXwBx8cUREF8cAfFFEBZfHAHxRRAWXwRh8SWQVnwBxMUXR0B8cQTEF0FYfHEExBdBWHwRhMWXQFrxxREQXwRh8UUQFl8CacUXQVh8CaQVXwJpxZeEPP-hUWHevtj_H9f_Hw)
### Old [Python](https://www.python.org) NumPy, 59 bytes
```
def f(L):a=L.argmax();m=a and L[a-1];b=L>=m;L[b]=L[b][::-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZ1LblvZEYbnXgXRIylgG60X76UN9bwB70DwQIHtRI4tC5Y7iCfZSCY9SaZZQ5aRrCaiSJ6q_6-vbmfQabs-kudVr_-cIP_418P3b3_-cv_bb__89duHH-f_vn73_sPqw8mb01e3129e3n790-fbv52cvv58fb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UTEF0BcfAHExRdHQHwBxMUXR0B8cQTEF0FYfAHExRdHQHxxBMQXQVh8cQTEF0FYfBGExZdAWvEFEBdfHAHxxREQXwRh8cUREF8EYfFFEBZfAmnFF0dAfBGExRdBWHwJpBVfBGHxJZBWfAmkFV8S8vyHRoV5-2L_f1z_fw)
Port of @l4m2's JS.
### Stupid [Python](https://www.python.org) NumPy, 122 bytes
```
def f(L,i=-2):
a,*b=L.argsort()[i:];b.sort()
if[a]<b:L[[a,*b]]=L[[*b,a]]
else:L[[*b,a]]=L[[a,*b]];-i<len(L)and f(L,i-1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZ1LblzXEYbnXEXDI9K4EsxX96VsZm5AOyA4oCDKoSJThCgHUAbZSCaeJNOsIctIVhM2u3mq_r--us4kkurr7vOq139OkH_86-Hb1z9_vv_993_-9vXDq_m_f3t_-2H14fDtdHf56uTozcHqZvr-3eXb1zdffnn8_OXr4dHV3ZvrH9-93v3lYHX34erm-qd3b95eXW3J6-vLpz99_266ub4-WN1-erx9M_5-OZgfX9399On2_vDt0c39-92vvTo-2o_gP3e_Pjx9-erx2-PB_o_3v_368G1187i6fzj48PnL6m51d7-1v378-v7u_vWX25v3n-7ubx8PtwNerX5eXa6uvv_15uHw_uFp4F9uvk3bv9z-9ebTdPf68eHT3dfD71av_rT67ujo6Hr7iY9Pn_j56ofnP48f-Pnq-M318xc-_efm8fH2aSQ3nz4dfjj8ePTEfLy8PPz45vLu6Ojg4cvd_dNXPhlXn__y3X4iv__v7_--Or7e_s7Tfx1cHU-rk93fTqbVy79v_21nmlan499OM3o66NNnLH10-5nx6Wl1li1n9oVn4zuPd0b7jbPxzScv9vjZs_zL-w_7SLa_nwczrc7Nfl6HeJ5HebJD6sDP89hPXyiZznme0fH4ojrJ8zzP8V0y9fM8-5P0XbIg53kNYlB5mc5tpWJQsHjb9bL1m1brSq1xYde2tqc7EFd8bYt-9sL6VqxtN07Gl-IerW2bxvf65q1t_07T9_qurm1jY7C23Wvb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UQ118cAf0FENdfHAH9xRHQXwRh_QUQ118cAf3FEdBfBGH9xRHQXwRh_UUQ1l8CafUXQFx_cQT0F0dAfxGE9RdHQH8RhPUXQVh_CaTVXxwB_UUQ1l8EYf0lkFZ_EYT1l0Ba_SWQVn_ZI634crKA7L-0RWJcLRLjYkQWqEVigRiRBWJEFggQPzUtEqeGETk1jMipAcRPDSNyagDxUwOInxpHIMS0SIQYRiTEMCIhBhAPMYxIiAHEQwwgHmIcgRDDiIQYQDzEAOIhxhEIMYB4iHEEQowjEGIE4fqlRaJ-YUTqF0akfgHE6xdGpH4BxOsXQLx-cQTqF0akfgHE6xdAvH5xBOoXQLx-cQTqF0egfhGE6xdGpH4BxOsXQLx-cQTqF0C8fnEE6hdHoH4RhOsXQLx-cQTqF0egfhGE6xdHoH4RhOsXQbh-CaQVX1okxBdGRHxhRMQXQFx8YUTEF0BcfAHExRdHQHxhRMQXQFx8AcTFF0dAfAHExRdHQHxxBMQXQVh8YUTEF0BcfAHExRdHQHwBxMUXR0B8cQTEF0FYfAHExRdHQHxxBMQXQVh8cQTEF0FYfBGExZdAWvGFERFfAHHxBRAXXxwB8QUQF18cAfHFERBfBGHxBRAXXxwB8cUREF8EYfHFERBfBGHxRRAWXwJpxRdAXHxxBMQXR0B8EYTFF0dAfBGExRdBWHwJpBVfHAHxRRAWXwRh8SWQVnwRhMWXQFrxJZBWfEnI818aFeb6YPd_XP9_)
Takes a numpy array and modifies it in-place. Pretty straight-forward algo.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Z¡нθO@χ
```
Port of [the approach *@l4m2* used in his JavaScript answer](https://codegolf.stackexchange.com/a/243082/52210), so make sure to upvote him/her as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/6tDCC3vP7fB3ONx/uOlRw8L//6MNdYx1THUMDXQsdSx0zHXMdEx0jGIB) or [verify the test cases up to length 6](https://tio.run/##ATkAxv9vc2FiaWX/NkzOt3Z5P3nFk3YiIOKGkiAiP3nDkMOQ/1rCodC9zrhPQMOPw4LigKH/w68/fcK2LP8) (because any more will be too big for TIO's STDOUT).
**Explanation:**
```
# e.g. input=[1,3,5,10,9,8,7,6,4,2]
Z # Get the maximum of the (implicit) input-list
# STACK: [1,3,5,10,9,8,7,6,4,2],10
¡ # Split the input-list by this maximum
# STACK: [[1,3,5],[9,8,7,6,4,2]]
н # Leave the first list of the pair (the items before the maximum)
# STACK: [1,3,5]
θ # Leave the last value of that list (the value just before the maximum)
# STACK: 5
O # Sum in case the maximum was the very first item, resulting in 0
# STACK: 5
@ # Check for each value in the (implicit) input-list if it's >= this item
# before the maximum
# STACK: [0,0,1,1,1,1,1,1,0,0]
Ï # Only leave the items of the (implicit) input-list at the truthy positions
# STACK: [5,10,9,8,7,6]
 # Bifurcate this list (short for Duplicate & Reverse copy)
# STACK: [5,10,9,8,7,6],[6,7,8,9,10,5]
‡ # Transliterate the values in the (implicit) input-list, basically reverting
# the part that was truthy earlier
# STACK: [1,3,6,7,8,9,10,5,4,2]
# (after which it is output implicitly as result)
```
[Answer]
# [R](https://www.r-project.org/), 56 bytes
Or **[R](https://www.r-project.org/)>=4.1, 49 bytes** by replacing the word `function` with a `\`.
```
function(v){v[i]=rev(v[i<-v>=sum(v[which.max(v)-1])]);v}
```
[Try it online!](https://tio.run/##VYtNCsIwGAX3niLgJh@8iGn8K5pepGQhwdAs2kJtoyCePaahUNzNPOYN0enops6Ovu94oE@ovdHDI/AENxEq/ZzaxK/G22bX3t@pEdKQoWv4Rsctl0RbJipWS7PJDlYQZSzA5ILzCqZWU3@ZWkuVy9mWVOEIuUeJC8444YD0iz8 "R – Try It Online")
Port of [@l4m2's answer](https://codegolf.stackexchange.com/a/243082/55372) with the help of [@Kevin Cruijssen's explanation](https://codegolf.stackexchange.com/a/243088/55372).
[Answer]
# 80386 machine code, ~~63~~ 59 bytes
```
\x60\x8d\x1c\x91\x89\xde\x83\xee\x04\x8b\x06\x89\xd1\x29\xc1\x39\xd0\x75\x05
\x48\x01\xd1\xeb\x03\x89\xd0\x41\x89\xf7\xe2\x0e\xa5\x40\x89\x46\xfc\x83\xef
\x08\x39\xf7\x77\xf4\x61\xc3\x83\xc7\x04\x39\xdf\x74\xd2\x39\x07\x75\xce\x48
\xeb\xe2
```
[Try it online!](https://tio.run/##bVJhb5swEP0Mv@LENNVukwpImqQimbTfEaLIGDuxSk0FzkpX8deX3WHSdmsl4A7u3bt3z8jpQcrzN2NldSoVrFtXmvr2@OO83wvnGlOcnNrvGWuVdKa2LLp1qnMR5xzkUTRQGLvdwSaM8m4R592qzLtE5t19gvl93pUK4yzvFMZ4jnmBcTHWEJNilBhn9I79yzus30VEN19hmniYorbZ2Iaw@Uivl1hLsYb0Alvnsf8@xxFajqP1QBev/BRqWeKtUc0CaeTMw@TSKxyUaMRgXqb@PV56ZVKRrIGOFKk0yv73SYvWSVFV6M@v2pTArp/N4VApzox1cD0BDBw25FsWhq0TzkiPfGqw9LNpxIuHigELlsNrGDydHNnNrl6veBYGum5gQBmkirNswAQDg2bR9zKagNiaHUEDo4Hd3CBwM3IFxNayqI@GelA0SjxQ1uOtfW0CeOG/UJ8cgfqw/1esX8o/2btMysTW7jKfkjpcMyjrYS5Kgikk@LuAIVJ4PppKAZtODQ35YADubukTESSwXoOlxnemcfAF9lXrJ/aLg7klC3EfUvgojGXe4TfzoHhxqs1tbtEDWo635reqNcMz46Tj0wkkGYY1xjgDtJp/0HixyLsYNMqdGotHFvbnP1JX4tCep4@z9C8)
Thanks to @l4m2 suggesting `pusha`/`popa` saving 4 bytes!
**assembly (nasm)**
```
wiggle: ; fastcall, ecx = pointer to array, edx = length of array
pusha
lea ebx, [ecx + edx * 4]
mov esi, ebx
.L0:
sub esi, 4
mov eax, [esi]
mov ecx, edx
sub ecx, eax
cmp eax, edx
jne .0
dec eax
add ecx, edx
jmp .1
.0:
mov eax, edx
inc ecx
.1:
mov edi, esi
.L1:
loop .2
.L2:
movsd
inc eax
mov [esi - 4], eax
sub edi, 8
cmp edi, esi
ja .L2
popa
ret
.2:
add edi, 4
cmp edi, ebx
je .L0
cmp [edi], eax
jne .L0
dec eax
jmp .L1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 299 bytes
```
f=(i,L=0,N=i.map((E,I)=>i.map(G=>I<G|0)).reverse(),Y=Q=>Q.map((e,j)=>Q.reduce((A,g,h)=>A+Q[h][j],0)),F=d=>i[N[L].indexOf(1)-d]&&i[N[L].lastIndexOf(1)-d]&&!(X=N.map((E,I)=>I>L?E:E.map((G,H)=>i[H+d]?E[H+d]:0))).some((E,I)=>E.some((G,H)=>i[I+1]&&G&!X[I+1][H]))&&X)=>F(1)?Y(F(1)):F(-1)?f(Y(F(-1)),L+1):i
```
[Try it online!](https://tio.run/##XVFNj4IwEL3zK@qFtHEkuh8X3WLMBpWEuPG0GsKBQMGaCqagu2bX3@4OIln01L55M@@9abfhMSwiLfdlL8tjcbkknErweB8WXFq7cE@pAy7jdg1m3HbfZr99xiwtjkIXgjJY8yW3l3WzgC2rgBbxIRKUTiCFDVYm3aW/CfxtADgLUx6jor/wvcCSWSy@PxI6YL04MM1bVYVF6d4zHbrii3Yk1/bGztCpSzOYVyn9eTcOxs71GKIVs4p8J5oJ54aaZrc7QOGZ2Vldr/48YMw0V8hN0XW8ptXBhlPaQ5TQCuONgdcdsKG8RHlWlCQ5KPUp01SJ91OkBOGE5lqmMguVJ4sSSHTQWmRlBZBsc4xwm/wYpBb6uorE2JPQ1gwb1Q25EpbKU3prq8oyIQ20qu844QcoIPikV2WhCL839JHCHStPokV50Fnjimpno6k9rPSwz3@As2HU0WUmS1nzGN8fAHkB8grkGchTMDLa8VutqPDodMde/gA "JavaScript (Node.js) – Try It Online")
Yes, I know. Not the shortest. Not anywhere close. However, this answer actually performs the wiggling steps by moving layers left and right.
Builds the list of layers, then attempts to move the current (`L`) layer to the left. If no layer is hovering in midair (some part is above empty air), then we return the resulting arrangement, otherwise we attempt to move to the right. If it is possible, recall `f` with incremented `L`, otherwise, because of the way the wiggling works, we are at the bottom layer and we simply return `i` unchanged.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~69~~ 68 bytes
```
\d+
*
^|$
,
V`,?(_*),(?=(_+)(?!.*\2))(?<!\2.*)(_+\1,)+
^,|,$
_+
$.&
```
[Try it online!](https://tio.run/##NYu7DsIwDEV3/0WlgPK4iuQkIyhj/4ApaooEAwsDYuy/B2O1i@/r@PP8vt53Hic7r6M9AnlaNkOg24pqu3ew9Wp7cLZO0bfkxFymlqJ30jaGC7RggyHqgUw8j8HESJSgiiw3a87SiDt6FNWyE0UY/qedLcLpql9F/3QF/wA "Retina – Try It Online") Link includes test cases. Edit: Saved 1 byte by using @KevinCruijssen's approach. Explanation:
```
\d+
*
^|$
,
```
Convert the unary and wrap the height map in an extra pair of `,`s.
```
V`,?(_*),(?=(_+)(?!.*\2))(?<!\2.*)(_+\1,)+
```
Get the number preceding the largest number in the input (or `0` if it's the first number), and reverse the sublist of all numbers equal to or exceeding that number. (Excepting `n,n-1,...,1`, valid inputs always contain a sublist of the form `k,n,n-1,...,k+1`.)
```
^,|,$
_+
$.&
```
Remove the extra `,`s and convert to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔⌕θ⌈θη≔⊕⌕θ⊕∧η§θ⊖ηζI…θ⊖ηI⮌✂θ∧η⊖ηζ¹I✂θζ
```
[Try it online!](https://tio.run/##bY09D4IwEIZ3f8WNJTkHvwcngjFhMDE6EoamXGwTKNIiQf58LYbg5w033PM@9wrJjSh57lxorbpotlc6YxXCgbequBWsCgIEGWwnA4@1MFSQrikbs@@30J8kQljHOqO2pzt6URk8B6HzH49G6ZpF3Pp1FzlFsrz@FT6iJ2rIWGLnXAnq40Pjl@UrEGY/9mh1PXEuSWYIc4QVwgZhjbBEWKSpmzb5Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @KevinCruijssen's approach.
```
≔⌕θ⌈θη
```
Get the index of the largest element.
```
≔⊕⌕θ⊕∧η§θ⊖ηζ
```
Get the index of the successor of the element one greater than the predecessor of the largest element, or the length of the array (calculated as the index after the position of the `1` which is always last in that case) if the largest element is the first element.
```
I…θ⊖η
```
Output the elements up to the predecessor of the largest element.
```
I⮌✂θ∧η⊖ηζ¹
```
Output the elements not less than the predecessor of the largest element, but in reverse.
```
I✂θζ
```
Output the remaining elements.
] |
[Question]
[
As a couple of people may have noticed lately, I've largely abandoned development of [Braingolf](https://github.com/gunnerwolf/braingolf) because it's boring and uninspired, and moved on to [2Col](https://github.com/gunnerwolf/2col) which is a little more interesting, and not designed to be a golfing language.
The defining feature of 2Col is that every line of code must be exactly 2 characters long, excluding the newline. This means that the length of a 2Col program can always be calculated as `3n-1` where `n` is the number of lines in the program.
So here's my challenge: Given 2Col code as a string, output truthy if it is valid 2Col code (Every line is exactly 2 characters and it conforms with the `3n-1` formula), and falsey otherwise.
## Input
Input should be taken as a single string, or an array of characters.
## Output
A truthy value if the input string is valid layout, and a falsey value otherwise.
Your code should be consistent in which truthy/falsey values it uses
## Testcases
```
======
F!
$^
----
truthy
======
======
*8
+1
Sq
----
truthy
======
======
nop
xt
----
falsey
======
======
+1
+1
#^
----
falsey
======
======
<empty string>
----
falsey
======
======
ye
----
truthy
======
======
no<space>
----
falsey
======
======
test
----
falsey
======
======
puzzle
----
falsey
======
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 4 bytes
```
ṇl₂ᵐ
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9wZ3vOo6amh1sn/P@vpGXBpW3IFVyoBAA "Brachylog – TIO Nexus")
Full program (because this is a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"); Brachylog full programs output `false.` if there was an assertion failure, `true.` without one).
## Explanation
```
ṇl₂ᵐ
ṇ Split input into lines
ᵐ For each line:
l₂ Assert that that line has length 2
```
Subscripts on `l` are one of Brachylog's newest features (although still older than the challenge), and this is a good challenge to use them on.
[Answer]
# JavaScript (ES6), ~~24~~ ~~28~~ ~~25~~ 24 bytes
Fixed program and shaved of three bytes thanks to @PunPun1000
Shaved off one byte thanks to @Shaggy
```
s=>/^(..\n)*..$/.test(s)
```
Returns true if valid and false if not.
```
f=
s=>/^(..\n)*..$/.test(s)
t=
`22
22
22
22
22`
console.log(f(t));
console.log(f(t.slice(0, -1)));
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 20 bytes
Returns 1 for truthy and nothing for falsey
```
@1OuABq>;;?w-!$@;U_N
```
Cubified
```
@ 1
O u
A B q > ; ; ? w
- ! $ @ ; U _ N
. .
. .
```
* `ABq` slurp in all the input, reverse it and push the EOI(-1) to the bottom of the stack
* `>;;` Step into the loop and remove items from the stack
* `?` Test for EOI(-1).
+ If found `1uO@` push 1 to the stack, u-turn onto integer output and halt
+ Otherwise `_` reflect back onto the `?` which redirects to the `w` lane shift
* `N-!$@;U` push line feed (10) onto the stack, subtract, test result, skip the halt if false, remove the result and u-turn
* `;;>` remove the line feeds from the stack and redirect into the loop.
[Try it online!](https://tio.run/nexus/cubix#@@9g6F/q6FRoZ21tX66rqOJgHRrv9/@/lgWXtiFXcCEA "Cubix – TIO Nexus")
[Answer]
# Python, 51
```
lambda s:all(len(l)==2for l in(s+"\n").splitlines())
```
Test case runner:
```
tcs = {
"F!\n$^": 1,
"*8\n+1\nSq": 1,
"nop\nxt": 0,
"+1\n+1\n#^\n": 0,
"": 0,
"ye": 1,
"no ": 0,
"test": 0,
"puzzle": 0
}
f = lambda s:all(len(l)==2for l in(s+"\n").splitlines())
for tc, expected in tcs.items():
assert f(tc) == expected
```
[Answer]
# Haskell, ~~23~~ ~~52~~ 32 bytes
```
all((==2).length).lines.(++"\n")
```
I got my inspiration from some other solutions, clever trick adding that `"\n"`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ỴL€=2Ṃ
```
[Try it online!](https://tio.run/nexus/jelly#@/9w9xafR01rbI0e7mz6//9/Xn4BV0UJAA "Jelly – TIO Nexus")
**Explanation:**
```
ỴL€=2Ṃ
Ỵ Split at newlines
L€ Length of each...
=2 ...equals two.
Ṃ Minimum.
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 10 bytes
```
^..(¶..)*$
```
[Try it online!](https://tio.run/nexus/retina#@x@np6dxaJuenqaWyv//AA "Retina – TIO Nexus") Outputs `1` or `0` as appropriate.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 25 bytes
```
s->s.matches("(..\n)*..")
```
[Try it online!](https://tio.run/nexus/java-openjdk#jc@xTgMxDADQOfmKcDAkLVhiq1TowNCN6UZCJXPNlaCcExpf1VPVbz@uancyWI7sZytO/VfwjWoC5qze0ZM6SZGuxczIUzpEv1Xd1NI17z3tPj4V7nfZnKQU4gcPCD37AG1PDftIsL49Xq788S3G4JBWqlWvcsxPqwwdcvPtsq40gCUzA6jMKMRyWlgPmV0HsWdI0zgH0i1gSmHQ1frO0sOmMuY/OFtYmj9bqn8LMMVk6cgF8rLyEvcbSwW8gAyu6IOqQLHLtxvO8jz@AQ "Java (OpenJDK 8) – TIO Nexus")
Checks if the input string has any number of lines followed by a line feed and a final line without one (ensures at least one line)
[Answer]
# JavaScript (ES6), ~~35~~ 24 bytes
```
s=>!/^.?$|.../gm.test(s)
```
---
## Try it
```
f=
s=>!/^.?$|.../gm.test(s)
oninput=_=>o.innerText=f(i.value)
o.innerText=f(i.value=`F!
$^`)
```
```
<textarea id=i></textarea><pre id=o>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
¶¡D2ùQ
```
[Try it online!](https://tio.run/nexus/05ab1e#@39o26GFLkaHdwb@/6@kpOSmyKUSB6QB "05AB1E – TIO Nexus")
```
¶¡D2ùQ Argument s
¶¡ Split s on newlines
D Duplicate
2ù Keep only elements of length 2
Q Compare
```
[Answer]
# [J-uby](https://github.com/cyoce/j-uby), ~~19~~ 18 bytes
```
:=~&/^(..\n*)..$/m
```
`:=~&` makes an anonymous function that takes `x` and returns `0` if it matches the regex `/^(..\n*)..$/m`, or `nil` otherwise.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 6 bytes
```
·eÈʶ2
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=t2XIyrYy&input=IkYhClNeIg==)
---
## Explanation
```
:Implicit input of string "U"
· :Split to array on newline
eÈ :Maps over the array, checking that every item's ...
Ê :length ...
¶2 :Equals 2
:Implicit output of result
```
[Answer]
# Bash + GNU utilities, 13
```
grep -qv ^..$
```
This sets the shell return value (accessible in `$?`) to 0 for false and 1 for true. This is actually the opposite sense [compared to normal shell convention](https://codegolf.meta.stackexchange.com/questions/11924/new-users-guides-to-golfing-rules-in-specific-languages/12026#12026), so to make that right you'd need to do:
# Bash + GNU utilities, 15
```
! grep -qv ^..$
```
[Answer]
# Ruby, 22 bytes
```
->s{s=~/^(..\n*)..$/m}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ỴẈ=2Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8///h7i0Pd3XYGp1Y9v///7z8Aq6KEgA "Jelly – Try It Online")
A small improvement over the other jelly answer.
## Explanation
```
ỴẈ=2Ȧ Main Link: takes string on the left
Ỵ split on newlines
Ẉ length(vectorizes)
=2 equals 2? (vectorizes)
Ȧ are all elements truthy?
```
] |
[Question]
[
The specification of the "estimated" sign used by the European Union Directive (U+212e in Unicode, which you may not simply print for this challenge) is quite precise.
[](https://i.stack.imgur.com/8IcDt.png)
To copy some restrictions from [this question](https://codegolf.stackexchange.com/questions/40052/draw-the-south-korean-flag): Render the symbol to file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 264 pixels × 240 pixels or more. Any other helping lines or length indicators must not be drawn.
[Answer]
# VBA, ~~587~~ 560 bytes
```
Sub S(a,b,c,d,e,f)
Set v=ActiveSheet.Shapes.AddShape(a,b,c,d,e)
v.Fill.ForeColor.RGB=f
v.Line.Visible=0
If a=5 Then v.Adjustments(1)=.5
End Sub
Sub U():p=91.5:w=-1
S 1,0,0,500,450,w
S 9,0,0,500,450,0
S 9,38.5,13.5,423,423,w
S 1,36,120,29,210,0
S 1,65,80,26.5,290,0
S 1,435,120,29,105,0
S 1,408.5,80,26.5,145,0
q=212.25:S 1,9,q,480,19,0
S 5,p,205.75,317,13,w
S 1,405,231.25,95,131.5,w
r=14.5:S 1,p,70.5,r,30,0
q=85:S 9,p,59.6,q,q,w
S 1,p,349.5,r,30,0
S 9,p,305.4,q,q,w
S 1,395,70.5,r,30,0
S 9,323.5,59.6,q,q,w
q=231.25:S 1,p,q,6.5,6.5,0
S 9,p,q,13,13,w
End Sub
```
Invoke macro U. Basically a lot of shape drawing. Shape 1 is a rectangle, 5 a rounded rectangle and 9 is an oval. Output is 500 wide by 450 high.
[](https://i.stack.imgur.com/k0FdE.jpg)
**Edit**: added the rounded rectangle (with adjustment to turn the ends into semicircles) to produce the radiused corners on top of the bar with one shape draw.
[Answer]
# Haml + Sass, 20 + 722 = 742 bytes
I'm sure this could be golfed a lot more, but I'm happy enough with it. [Demo on CodePen](http://codepen.io/anon/pen/yJjLkd?editors=1100).
Note: Because of default margins, this needs a browser window at least 1,000-some pixels wide.
## Haml
```
#u
#v
#w
#x
#y
#z
```
## Sass
```
$w: 1000px
$h: 900px
$a: 183px
$b: 25px
$p: 85px
$q: 13px
$d: 846px
$e: $w - 2*$a
$f: 143px
$s: 50%
$t: $p/5.5
=d($w:$w,$h:$h)
width: $w
height: $h
=m($c)
background-color: $c
=k
+m(#000)
position: absolute
content: ''
=l
+k
+m(#fff)
=o($o:$p)
+d($o,$p)
=r($a)
border-radius: $a
*
+k
html,body
+l
position: relative
#u
+d
clip-path: ellipse($s $s)
#v
+d($e)
left: $a
clip-path: circle(($d/2) at $s $s)
#v::before,#v::after
+l
+d($e,($h -$b)/2)
+r($q)
#v::after
bottom: 0
#w,#x
+o($t)
top: $f
#w::before,#x::before,#y::before
+l
+o
+r($s 0)
#x,#x::before
right: 0
#x::before
+r(0 $s 0 0)
#y
+o($t)
bottom: $f
z-index: 9
#y::before
+r(0 0 0 $s)
#z
+l
+d($s,267px)
top: ($h+$b)/2
right: 0
```
[Answer]
# GLSL + shadertoy.com, ~~349~~ ~~345~~ 344 bytes
```
#define F float
void mainImage(out vec4 R,vec2 C){F S=min(iResolution.x,iResolution.y/0.9);vec2 p=C/vec2(0.5,0.45)/S-1.;F A=0.94-length(p*vec2(1.22,1));F H=min(min(-p.y-0.025,p.y+0.551),p.x);F B=max(length(p)-1.,min(abs(p.y)-0.025,max(A,H)));F D=max(min(p.x,-p.y),max(-A,0.634-abs(p.x)));R=vec4(vec3(max(H,min(B*D*64.-0.01,min(B,D)))*S/3.),1);}
```
Can be tested by pasting the code on this page: <https://www.shadertoy.com/new>
Output (when the screen size is 1440\*900):
[](https://i.stack.imgur.com/p7Wnu.png)
[Answer]
## PostScript, ~~280~~ 140 bytes
Now smaller, with binary tokens and less precision!
```
00000000: 5b28 5b29 7b31 3339 9205 8881 3588 0035 [([){139....5..5
00000010: 2035 9207 887f 3588 7f88 2835 9207 9242 5....5...(5...B
00000020: 747d 285d 297b 885d 3938 8822 3088 2d92 t}(]){.]98."0.-.
00000030: 0588 0c30 9285 9242 7d2f 747b 3188 ff92 ...0...B}/t{1...
00000040: 8b7d 3e3e 920d 8864 3930 92ad 387b 307d .}>>...d90..8{0}
00000050: 9283 880a 3992 8b88 0a30 8768 0192 0592 ....9....0.h....
00000060: 422e 3035 202e 3035 3592 8b31 9296 87a9 B.05 .055..1....
00000070: 0034 315b 3587 4001 8869 9280 87a9 0034 .41[[[email protected]](/cdn-cgi/l/email-protection)
00000080: 5b92 965d 88ff 3192 8b5d 745d [..]..1..]t]
```
Before being tokenized (255 bytes):
```
[([){139 arc -127 5 0 5 5 arct 127 5 127 40 5 arct fill t}(]){93 98 34 0 45 arc 12 0 rlineto fill}/t{1 -1 scale}>>begin
100 90 translate
8{0}repeat
10 9 scale
10 0 360 arc fill
.05 .055 scale
1 setgray
169 41[5 320 105 rectfill
169 4[setgray]-1 1 scale]t]
```
Step-by-step:
[](https://i.stack.imgur.com/IXUlD.gif)
Final output:
[](https://i.stack.imgur.com/1mgZ8.png)
(Gray background is from Preview.app and not part of actual output.)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~251~~ 248 bytes
*-3 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
#define q(x,y)(x)*(x)+(y)*(y)
#define A abs
main(i,j){puts("P5 264 240 1");for(i=-121;i++<119;)for(j=-133;j++<131;)putchar(((q(i,j*.9)>'8?'|q(i,j)<12471&A(j)<84)&q(A(i)-72,A(j)-81)>39|q(A(i)-65,A(j)-61)<504)&A(i)>3&(A(j)-83||A(i)-4)|j>0&i>3&i<73);}
```
[Try it online!](https://tio.run/##NYzbbsIwDIbveYqok4rdw1Qn6UkpRX2DvUIplKXSGAUmUS08e5dQdmHZ/v7P7uJj183z2/7Q69OBjXCPJoQ7BrZCmGyfcPWfNqzdXVdfrT6Bjgb8Pf/cruB9pIxnknGZMPJQ9d8X0JuYOCkdhhVRqdCxwTIh1OCYIIX2uPtsLwAwum/Be4n1utiuzXPFirjMyW/AjoVEf4QGNMY5jxyKC8JalOZFs3ShGWGVJtZ2tBY@LK4w5qlJNEOd@NomusoFqsc8/wE "C (gcc) – Try It Online")
] |
[Question]
[
It is well known, in the field of Mathematics studying infinity, that [the Cartesian product of any finite amount of countable sets is also countable](https://proofwiki.org/wiki/Cartesian_Product_of_Countable_Sets_is_Countable/Corollary).
Your task is to write two programs to implement this, one to map from list to integer, one to map from integer to list.
Your function must be bijective and deterministic, meaning that `1` will always map to a certain list, and `2` will always map to another certain list, etc...
[Earlier](https://codegolf.stackexchange.com/questions/71924/bijective-mapping-from-integers-to-a-variable-number-of-bits), we mapped integers to a list consisting only of `0` and `1`.
**However, now the list will consist of non-negative numbers.**
# Specs
* Program/function, reasonable input/output format.
* Whether the mapped integers start from `1` or starts from `0` is your choice, meaning that `0` doesn't have to (but may) map to anything.
* The empty array `[]` must be encoded.
* Input/output may be in any base.
* Sharing code between the two functions is **allowed**.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Lowest score wins.
Score is the sum of lengths (in bytes) of the two programs/functions.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### List to integer, ~~10~~ 8 bytes
```
TṪạL;³ÆẸ
```
Maps lists of non-negative integers to positive integers. [Try it online!](http://jelly.tryitonline.net/#code=VOG5quG6oUw7wrPDhuG6uA&input=&args=WzAsIDEsIDIsIDMsIDBd)
### Integer to list, 8 bytes
```
ÆE©Ḣ0ẋ®;
```
Maps positive integers to lists of non-negative integers . [Try it online!](http://jelly.tryitonline.net/#code=w4ZFwqnhuKIw4bqLwq47&input=&args=NjUyMTkw)
## Background
Let **p0, p1, p2, ⋯** be the sequence of prime numbers in ascending order.
For each list of non-negative integers **A := [a1, ⋯, an]**, we map **A** to **p0z(A)p1a1⋯pnan**, where **z(A)** is the number of trailing zeroes of **A**.
Reversing the above map in straightforward. For a *positive* integer **k**, we factorize it uniquely as the product of consecutive prime powers **n = p0α0p1α1⋯pnαn**, where **αn > 0**, then reconstruct the list as **[α1, ⋯, αn]**, appending **α0** zeroes.
## How it works
### List to integer
```
TṪạL;³ÆẸ Main link. Argument: A (list of non-negative integers)
T Yield all indices of A that correspond to truthy (i.e., non-zero) items.
Ṫ Tail; select the last truthy index.
This returns 0 if the list is empty.
L Yield the length of A.
ạ Compute the absolute difference of the last truthy index and the length.
This yields the amount of trailing zeroes of A.
;³ Prepend the difference to A.
ÆẸ Convert the list from prime exponents to integer.
```
### Integer to list
```
ÆE©Ḣ0ẋ®; Main link. Input: k (positive integer)
ÆE Convert k to the list of its prime exponents.
© Save the list of prime exponents in the register.
Ḣ Head; pop the first exponent.
If the list is empty, this yields 0.
0ẋ Construct a list of that many zeroes.
®; Concatenate the popped list of exponents with the list of zeroes.
```
## Example output
The first one hundred positive integers map to the following lists.
```
1: []
2: [0]
3: [1]
4: [0, 0]
5: [0, 1]
6: [1, 0]
7: [0, 0, 1]
8: [0, 0, 0]
9: [2]
10: [0, 1, 0]
11: [0, 0, 0, 1]
12: [1, 0, 0]
13: [0, 0, 0, 0, 1]
14: [0, 0, 1, 0]
15: [1, 1]
16: [0, 0, 0, 0]
17: [0, 0, 0, 0, 0, 1]
18: [2, 0]
19: [0, 0, 0, 0, 0, 0, 1]
20: [0, 1, 0, 0]
21: [1, 0, 1]
22: [0, 0, 0, 1, 0]
23: [0, 0, 0, 0, 0, 0, 0, 1]
24: [1, 0, 0, 0]
25: [0, 2]
26: [0, 0, 0, 0, 1, 0]
27: [3]
28: [0, 0, 1, 0, 0]
29: [0, 0, 0, 0, 0, 0, 0, 0, 1]
30: [1, 1, 0]
31: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
32: [0, 0, 0, 0, 0]
33: [1, 0, 0, 1]
34: [0, 0, 0, 0, 0, 1, 0]
35: [0, 1, 1]
36: [2, 0, 0]
37: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
38: [0, 0, 0, 0, 0, 0, 1, 0]
39: [1, 0, 0, 0, 1]
40: [0, 1, 0, 0, 0]
41: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
42: [1, 0, 1, 0]
43: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
44: [0, 0, 0, 1, 0, 0]
45: [2, 1]
46: [0, 0, 0, 0, 0, 0, 0, 1, 0]
47: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
48: [1, 0, 0, 0, 0]
49: [0, 0, 2]
50: [0, 2, 0]
51: [1, 0, 0, 0, 0, 1]
52: [0, 0, 0, 0, 1, 0, 0]
53: [0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 1]
88: [0, 0, 0, 1, 0, 0, 0]
89: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
90: [2, 1, 0]
91: [0, 0, 1, 0, 1]
92: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]
93: [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
94: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
95: [0, 1, 0, 0, 0, 0, 1]
96: [1, 0, 0, 0, 0, 0]
97: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
98: [0, 0, 2, 0]
99: [2, 0, 0, 1]
100: [0, 2, 0, 0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
## Encode, ~~7~~ 6 bytes
```
2Bṁx‘Ḅ
```
[Try it online!](https://tio.run/##y0rNyan8/9/I6eHOxopHDTMe7mj5//9/tIGOoY6JjqWOoZmOkamOsZmOiaWOmYmOhaGOoYFBLAA "Jelly – Try It Online")
## Decode, 6 bytes
```
ȯIBŒɠ’
```
[Try it online!](https://tio.run/##HYyxDUJRDMRWyiW5JNfSMQgN@gvQMQMdHRswBRKswSKPL0pLts@nbbus9X4eD6/b5/G93tdaMPNQQAl6t8/UpEPyKoBBaxUrsiLaMZ2TjL0iIts0liT2x45ilIQiwzKpaJvq/AuwrglNC9mEfg "Jelly – Try It Online")
Encodes positive integers in the run lengths of the binary representation. Since we may have zeros, we increment all numbers. For example, the list `[0,1,4]` is encoded as 10011111 in binary.
Numbers from 0 to 100 ([Try it online!](https://tio.run/##y0rNyan8///Eek@no5NOLnjUMPO/oYHB0d06h9uPTnq4c8ajpjXHuoCE@///AA "Jelly – Try It Online")):
```
0 []
1 [0]
2 [0, 0]
3 [1]
4 [0, 1]
5 [0, 0, 0]
6 [1, 0]
7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
84 [0, 0, 0, 0, 0, 1]
85 [0, 0, 0, 0, 0, 0, 0]
86 [0, 0, 0, 0, 1, 0]
87 [0, 0, 0, 0, 2]
88 [0, 0, 1, 2]
89 [0, 0, 1, 1, 0]
90 [0, 0, 1, 0, 0, 0]
91 [0, 0, 1, 0, 1]
92 [0, 0, 2, 1]
93 [0, 0, 2, 0, 0]
94 [0, 0, 3, 0]
95 [0, 0, 4]
96 [1, 4]
97 [1, 3, 0]
98 [1, 2, 0, 0]
99 [1, 2, 1]
100 [1, 1, 0, 1]
```
[Answer]
# Python 2, 88 bytes
```
d=lambda n:map(len,bin(n).split('1')[1:])
e=lambda l:int('1'.join(a*'0'for a in[2]+l),2)
```
Demo:
```
>>> for i in range(33):
... print e(d(i)), d(i)
...
0 []
1 [0]
2 [1]
3 [0, 0]
4 [2]
5 [1, 0]
6 [0, 1]
7 [0, 0, 0]
8 [3]
9 [2, 0]
10 [1, 1]
11 [1, 0, 0]
12 [0, 2]
13 [0, 1, 0]
14 [0, 0, 1]
15 [0, 0, 0, 0]
16 [4]
17 [3, 0]
18 [2, 1]
19 [2, 0, 0]
20 [1, 2]
21 [1, 1, 0]
22 [1, 0, 1]
23 [1, 0, 0, 0]
24 [0, 3]
25 [0, 2, 0]
26 [0, 1, 1]
27 [0, 1, 0, 0]
28 [0, 0, 2]
29 [0, 0, 1, 0]
30 [0, 0, 0, 1]
31 [0, 0, 0, 0, 0]
32 [5]
```
# Python 2, 130 bytes
Here’s a more “efficient” solution where the bit-length of the output is linear in the bit-length of the input rather than exponential.
```
def d(n):m=-(n^-n);return d(n/m/m)+[n/m%m+m-2]if n else[]
e=lambda l:int('0'+''.join(bin(2*a+5<<len(bin(a+2))-4)[3:]for a in l),2)
```
[Answer]
# Python 2, 204 202 bytes
```
p=lambda x,y:(2*y+1<<x)-1
u=lambda n,x=0:-~n%2<1and u(-~n//2-1,x+1)or[x,n//2]
e=lambda l:l and-~reduce(p,l,len(l)-1)or 0
def d(n):
if n<1:return[]
r=[];n,l=u(n-1);exec"n,e=u(n);r=[e]+r;"*l;return[n]+r
```
Works by repeatedly applying a Z+ x Z+ <-> Z+ bijection, prepended by the list length.
```
0: []
1: [0]
2: [1]
3: [0, 0]
4: [2]
5: [0, 0, 0]
6: [1, 0]
7: [0, 0, 0, 0]
8: [3]
9: [0, 0, 0, 0, 0]
10: [1, 0, 0]
11: [0, 0, 0, 0, 0, 0]
12: [0, 1]
13: [0, 0, 0, 0, 0, 0, 0]
14: [1, 0, 0, 0]
15: [0, 0, 0, 0, 0, 0, 0, 0]
16: [4]
17: [0, 0, 0, 0, 0, 0, 0, 0, 0]
18: [1, 0, 0, 0, 0]
19: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
20: [0, 0, 1]
21: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
22: [1, 0, 0, 0, 0, 0]
23: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
24: [2, 0]
25: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
26: [1, 0, 0, 0, 0, 0, 0]
27: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
28: [0, 0, 0, 1]
29: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
30: [1, 0, 0, 0, 0, 0, 0, 0]
31: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
[Answer]
# Retina, 17 + 23 = 40 bytes
From list to integer:
```
\d+
$&$*0
^
1
1
```
[Try it online!](http://retina.tryitonline.net/#code=XGQrCiQmJCowCl4KMQogCjE&input=MCAxIDIgMyAwIDUgMA)
From integer to list:
```
^1
S`1
m`^(0*)
$.1
¶
<space>
```
[Try it online!](http://retina.tryitonline.net/#code=XjEKClNgMQptYF4oMCopCiQuMQrCtgog&input=MTEwMTAwMTAwMDExMDAwMDAx)
Uses [Kaseorg's Algorithm](https://codegolf.stackexchange.com/a/78989/48934).
[Answer]
# JavaScript, 87 bytes
```
F=n=>n.toString(2).split(1).slice(1).map(_=>_.length)
G=a=>g=(i=0)=>F(i)+''==a?i:g(++i)
```
`G` goes through all inputs since it's shorter
] |
[Question]
[
## Introduction
Consider two strings **A** and **B** of the same length **L**, and an integer **K ≥ 0**.
For the purposes of this challenge, we say that the strings are **K**-compatible, if there exists a string **C** of length **K** such that **A** is a contiguous substring of the concatenation **BCB**.
Note that **A** is a substring of **BAB**, so **A** and **B** are always **L**-compatible (but may also be **K**-compatible for some other **K < L**).
## Input
Your inputs are two strings of the same positive length, consisting of upper- and lowercase ASCII letters.
## Output
Your output shall be the lowest non-negative integer **K** such that the inputs are **K**-compatible.
## Example
Consider the inputs
```
A = HHHHHH
B = HHttHH
```
They are not 0-compatible, because **A** is not a substring of `HHttHHHHttHH`.
They are also not 1-compatible, because **A** is not a substring of `HHttHH#HHttHH` no matter which letter is placed on the `#`.
However, **A** *is* a substring of `HHttHHHHHHttHH`, where **C** is the two-letter string `HH`.
Thus the inputs are 2-compatible, and the correct output is `2`.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
The compatibility condition is symmetric, so swapping the two inputs should not change the output.
```
E G -> 1
E E -> 0
aB Bc -> 1
YY tY -> 1
abcd bcda -> 0
abcXd bxcda -> 4
Hello Hello -> 0
Hello olHel -> 1
aBaXYa aXYaBa -> 1
aXYaBa aBaXYa -> 1
HHHHHH HHttHH -> 2
abcdab cdabcd -> 2
XRRXXXXR XRXXRXXR -> 4
evveeetev tetevevev -> 7
vzzvzJvJJz vJJvzJJvJz -> 10
JJfcfJJcfJfb JcfJfbbJJJfJ -> 5
GhhaaHHbbhGGH HHaaHHbbGGGhh -> 9
OyDGqyDGDOGOGyG yDGqOGqDyyyyOyD -> 12
ffKKBBpGfGKpfGpbKb fGpbKbpBBBffbbbffK -> 9
UZuPPZuPdVdtuDdDiuddUPtUidtVVV dtUPtUidtVVVtDZbZZPuiUZuPPZuPd -> 21
```
## Leaderboard
Here's a Stack Snippet to generate a leaderboard and list of winners by language.
To make sure your answer shows up, start it with a header of the form
```
## Language, N bytes
```
You can keep old scores in the header by using the strikethrough tags: `<s>57</s>` will appear as ~~57~~.
```
/* Configuration */
var QUESTION_ID = 78736; // 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 = 32014; // 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,]*[^\s,]),.*?(-?\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,
});
});
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;
if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
lang = jQuery(lang).text().toLowerCase();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.uniq > b.uniq) return 1;
if (a.uniq < b.uniq) 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}
#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="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<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><a href="{{LINK}}">{{SIZE}}</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
</tbody>
</table>
```
[Answer]
# Pyth, 16
```
lhf}QjT,vzvz+k.:
```
Find the shortest substring of A that when inserted between two copies of B results in a string that contains A.
This could be two bytes shorter if the second line didn't have quotes, but that feels weird?
[Test Suite](http://pyth.herokuapp.com/?code=lhf%7DQjT%2Cvzvz%2Bk.%3A&input=%22ffKKBBpGfGKpfGpbKb%22%0A%22fGpbKbpBBBffbbbffK%22&test_suite=1&test_suite_input=%22E%22%0A%22G%22%0A%22E%22%0A%22E%22%0A%22aB%22%0A%22Bc%22%0A%22YY%22%0A%22tY%22%0A%22abcd%22%0A%22bcda%22%0A%22abcXd%22%0A%22bxcda%22%0A%22Hello%22%0A%22Hello%22%0A%22Hello%22%0A%22olHel%22%0A%22HHHHHH%22%0A%22HHttHH%22%0A%22XRRXXXXR%22%0A%22XRXXRXXR%22%0A%22evveeetev%22%0A%22tetevevev%22%0A%22vzzvzJvJJz%22%0A%22vJJvzJJvJz%22%0A%22JJfcfJJcfJfb%22%0A%22JcfJfbbJJJfJ%22%0A%22GhhaaHHbbhGGH%22%0A%22HHaaHHbbGGGhh%22%0A%22OyDGqyDGDOGOGyG%22%0A%22yDGqOGqDyyyyOyD%22%0A%22ffKKBBpGfGKpfGpbKb%22%0A%22fGpbKbpBBBffbbbffK%22%0A%22UZuPPZuPdVdtuDdDiuddUPtUidtVVV%22%0A%22dtUPtUidtVVVtDZbZZPuiUZuPPZuPd%22&debug=0&input_size=2)
[Answer]
# Python 3, ~~155~~ ~~168~~ 157 bytes
Total is the length of `A`. Compare the beginning of `A` to the end of `B` and subtract that from total. Compare the beginning of `B` to the end of `A` and subtract that from total. Return the absolute value of total unless total is equal to the length, in which case return 0.
```
def f(A,B):
T=L=len(A)
C=D=1
for i in range(L,0,-1):
if A[:i]==B[-i:]and C:
T,C=T-i,0
if A[-i:]==B[:i]and D:
T,D=T-i,0
return (0,abs(T))[T!=-L]
```
**Edit:** Handle the `f("abcdab","cdabcd")==2` case
[Answer]
## [Retina](https://github.com/mbuettner/retina), 49 bytes
```
.*?(?<=^(?=(.*)(?<4-3>.)*(.*) \2.*\1$)(.)*).+
$#4
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAouKj8oPzw9Xig_PSguKikoPzw0LTM-LikqKC4qKSBcMi4qXDEkKSguKSopLisKJCM0&input=RSBHCkUgRQphQiBCYwpZWSB0WQphYmNkIGJjZGEKYWJjWGQgYnhjZGEKSGVsbG8gSGVsbG8KSGVsbG8gb2xIZWwKYUJhWFlhIGFYWWFCYQpISEhISEggSEh0dEhIClhSUlhYWFhSIFhSWFhSWFhSCmV2dmVlZXRldiB0ZXRldmV2ZXYKdnp6dnpKdkpKeiB2Skp2ekpKdkp6CkpKZmNmSkpjZkpmYiBKY2ZKZmJiSkpKZkoKR2hoYWFISGJiaEdHSCBISGFhSEhiYkdHR2hoCk95REdxeURHRE9HT0d5RyB5REdxT0dxRHl5eXlPeUQKZmZLS0JCcEdmR0twZkdwYktiIGZHcGJLYnBCQkJmZmJiYmZmSwpVWnVQUFp1UGRWZHR1RGREaXVkZFVQdFVpZHRWVlYgZHRVUHRVaWR0VlZWdERaYlpaUHVpVVp1UFBadVBk) (Slightly modified to run all tests at once.)
The trick is that we need to backtrack over the part of `A` that we *don't* find in `B`, and so far I haven't found a way to do this without rather annoying lookarounds and balancing groups.
[Answer]
# Jolf, 40 Bytes
```
Wά)Ζ0W<ζli)? h++i]Iζ+ζniIoά0nΖhζ}onhn}wn
```
[Try it!](http://conorobrien-foxx.github.io/Jolf/#code=V86sKc6WMFc8zrZsaSk_IGgrK2ldSc62K862bmlJb86sMG7OlmjOtn1vbmhufXdu)
I'm quite new to Jolf, learned a lot while figuring this out. Seems a bit awkward, still could probably could be golfed down further. Even knocked off 2 bytes while writing this explanation.
Explanation:
```
Wά) While ά (initialized to 16)
Ζ0 Set ζ to 0
W<ζli) While ζ < length(A)
? h++i]Iζ+ζniIoά0n Set ά to 0 if (A + a substring from B of length n + A) contains B
Ζhζ Increment ζ
}onhn Increment n (initialize to 0
}wn Decrement n and print
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 20 bytes
Code:
```
õ)²Œ«v¹y¹««²åiyg}})ß
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w7UpwrLFksKrdsK5ecK5wqvCq8Kyw6VpeWd9fSnDnw&input=ZmZLS0JCcEdmR0twZkdwYktiCmZHcGJLYnBCQkJmZmJiYmZmSw).
[Answer]
## JavaScript (ES6), 110 bytes
```
(a,b)=>{for(i=0;;i++)for(j=i;j<=a.length;j++)if(b.startsWith(a.slice(j))&&b.endsWith(a.slice(0,j-i)))return i}
```
Works by slicing ever longer pieces out of the middle of `a` until they match the two ends of `b`. The loop is not infinite as it will stop on or before `i == a.length`.
] |
[Question]
[
**Warning:** This challenge contains some mild spoilers for The Secret of Monkey Island.
Towards the end of the game, you're being led through the catacombs by a magically preserved head of a navigator:

You need its eyeball necklace, but the Head is reluctant to give it to you. One way to get it is just to keep begging:
>
> **Guybrush:** May I please have that necklace?
>
> **Head:** No, but thanks for asking so politely.
>
> **Guybrush:** Oh come on, pleeeeease?
>
> **Head:** You can beg all you want, but you can't have it.
>
> **Guybrush:** Pretty please?
>
> **Head:** You can beg all you want, but you can't have it.
>
> **Guybrush:** Pretty PRETTY please?
>
> **Head:** You can beg all you want, but you can't have it.
>
> **Guybrush:** Pretty please with sugar on top?
>
> **Head:** Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
>
>
>
## The Challenge
Write a full program which prints the above dialogue. The catch is that each time the program is called it should only print two lines (one pleading by Guybrush and the Head's response). E.g. if your submission is written in Python, usage should look like this:
```
$> python please.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$> python please.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
```
Invoking the program more than 5 times may result in undefined behaviour, so you could either loop, keep printing the last two lines or the program could even be broken after the 5th invocation.
You may write to a file in the working directory, or you can modify the source code of the program itself to keep track of invocations. In the latter case, your program must not depend its own filename. (In the former case, you can assume that your program's file name will not clash with any file names your program depends on.)
You must not assume a REPL-like environment or that any data is kept in RAM between invocations. E.g. if you answer in Mathematica, you have to assume that I quit the kernel between invocations.
This is code golf, the shortest answer (in bytes) wins. If your program depends on any additional files to exist *before the first invocation*, add its name and contents to your byte count.
[Answer]
# Python, 224 + 97 + 1 = 322 characters
A most straightforward solution to start us all off. Thanks to gnibbler for helping me shave off 18 bytes!
```
n=0
print open('z','rb').read().decode('zip').split('|')[n]
open(__file__,'r+').write("n="+`n+1`)
```
Requires the file `z` to be present in the same directory (+1 for filename, +224 for file size):
```
$ hexdump z
0000000 9c78 d1ad 6e3d 30c3 050c bde0 78a7 165b
0000010 0723 92c8 48a9 b43a 8209 192c 9b29 0491
0000020 a2ab 9fa1 021a f87a 715a f46c d100 1026
0000030 1efc 1e41 5172 4721 c3b3 1527 607c 4c70
0000040 6191 87e8 0c91 7825 7b6e 2d47 dfef 4c8e
0000050 0edd d25f e540 8b54 8fbe 4bb8 c500 7ade
0000060 288d c418 c4d9 6cae 0f7f 7bab 6832 9be5
0000070 be21 7aa9 537d c2c2 24dd 25a3 c50f e41a
0000080 ca1c 1ff4 a7c9 a439 d5cc 9a4d b207 3fe9
0000090 0e7c 529c 4e79 3afc 7cef bf79 6f5e 672f
00000a0 8b9f 6d1d 8832 5359 1698 2482 92c3 3270
00000b0 43cd 560e 899b a4ad 1ab2 548a aed9 0bf1
00000c0 238f 0697 bd63 168f 36e9 b411 0a1e fef6
00000d0 eee8 1d64 1a28 aec9 10e3 7ff7 3a0b d9ab
00000e0
$ ls -l z
-rw-r--r--+ 1 Laxori mkpasswd 224 2014-09-22 22:35 z
```
You can generate `z` with the following:
```
>>> open('z','wb').write("""eJyt0T1uwzAMBeC9p3hbFiMHyJKpSDq0CYIsGSmbkQSroqGfGgJ6+FpxbPQA0SYQ/B5BHnJRIUez
wycVfGBwTJFh6IeRDCV4bntHLe/fjkzdDl/SQOVUi76PuEsAxd56jSgYxNnErmx/D6t7MmjlmyG+
qXp9U8LC3SSjJQ/FGuQcyvQfyac5pMzVTZoHsuk/fA6cUnlO/DrvfHm/Xm8vZ5+LHW0yiFlTmBaC
JMOScDLNQw5Wm4mtpLIailTZrvELjyOXBmO9jxbpNhG0Hgr2/ujuZB0oGsmu4xD3fws6q9k=""".decode('base64'))
```
Output:
```
$ python monkeyisland.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$ python monkeyisland.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
$ python monkeyisland.py
Traceback (most recent call last):
File "monkeyisland.py", line 2, in <module>
print open('z','rb').read().decode('zip').split('|')[n]
IndexError: list index out of range
```
[Answer]
**Common Lisp (SBCL) : 659 characters**
```
(defparameter *d*
'#1=("~A May I please have that necklace?"
"~A No, but thanks for asking so politely."
"~A Oh come on, pleeeeease?"
#2="~A You can beg all you want, but you can't have it."
"~A Pretty please?"
#2#
"~A Pretty PRETTY please?"
#2#
"~A Pretty please with sugar on top?"
"~A Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?" . #1#))
(defun d ()
(format t (pop *d*) "Guybrush:") (terpri)
(format t (pop *d*) "Head:") (terpri)
(terpri)
(finish-output)
(sb-ext:save-lisp-and-die "please" :toplevel 'd :executable t))
(d)
```
# Explanations
* I dump the lisp image after each invocation, which saves current state.
* The circular list let me restart the dialogue after all lines have been displayed (not required, but at least it doesn't error on `format` with `nil`).
* Reader macros allow me to reuse some identical lines.
This won't be the shortest submission, but I thought this was a nice approach to the problem.
# Firt invocation
```
$sbcl --noinform --noprint --load please.lisp
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
[undoing binding stack and other enclosing state... done]
[saving current Lisp image into please:
writing 5856 bytes from the read-only space at 0x0x20000000
writing 4032 bytes from the static space at 0x0x20100000
writing 67960832 bytes from the dynamic space at 0x0x1000000000
done]
```
# Subsequent invocations
```
$./please
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
[undoing binding stack and other enclosing state... done]
[saving current Lisp image into please:
writing 5856 bytes from the read-only space at 0x0x20000000
writing 4032 bytes from the static space at 0x0x20100000
writing 68091904 bytes from the dynamic space at 0x0x1000000000
done]
$./please
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
[undoing binding stack and other enclosing state... done]
[saving current Lisp image into please:
writing 5856 bytes from the read-only space at 0x0x20000000
writing 4032 bytes from the static space at 0x0x20100000
writing 68091904 bytes from the dynamic space at 0x0x1000000000
done]
```
[Answer]
## C# - 593 + 1 + 1 Characters (595)
*Edits: Updated with suggestions from Martin and various other optimisations*
First +1 is a filename. Second +1 is contents of that file. Without all the spaces and line breaks removed so you can read it:
```
using System.IO;
using s=System.String;
class P
{
static void Main()
{
s g="Guybrush: ",h="Head: ",p=" please",q="Pretty";
s[]b=new s[]{"May I"+p+" have that necklace","No, but thanks for asking so politely.",
"Oh come on, pleeeeease","You can beg all you want, but you can't have it.",q+p,
"Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?",
q+" PRETTY"+p,"",q+p+" with sugar on top"};
int a=int.Parse(File.ReadAllText("x",System.Text.Encoding.UTF8));
System.Console.WriteLine(g+b[a]+"?\n"+h+b[(a+5)/6*2+1]);
File.WriteAllText("x",(a+2).ToString());
}
}
```
**Explanation**
Relies on a text file called "x" to be present in the directory. Should initially contain a zero and is used to store progress.
Program plucks relevant element out of the string array according to progress and writes progress at end. Some lines reused to shorten length, hence index selection logic `h+b[(a+5)/6*2+1]` for answer selection.
**Output**
```
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace
if you don't have shoulders?
D:\Projects\Junk\MI\bin\Debug>
```
My first code golf, probably not the shortest possible in C# but hey - Monkey Island, couldn't resist!
Stripped code:
```
using System.IO;using s=System.String;class P{static void Main(){s g="Guybrush: ",h="Head: ",p=" please",q="Pretty";s[]b=new s[]{"May I"+p+" have that necklace","No, but thanks for asking so politely.","Oh come on, pleeeeease","You can beg all you want, but you can't have it.",q+p,"Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?",q+" PRETTY"+p,"",q+p+" with sugar on top"};int a=int.Parse(File.ReadAllText("x",System.Text.Encoding.UTF8));System.Console.WriteLine(g+b[a]+"?\n"+h+b[(a+5)/6*2+1]);File.WriteAllText("x",(a+2).ToString());}}
```
[Answer]
## JS, ~~488~~ 473
Refreshing 5 times the page containing this code displays the 5 different dialogs.
```
l=localStorage;a="<p>Guybrush: ";b=a+"Pretty please";d="<br>Head: ";c=d+"You can beg all you want, but you can't have it.";document.write(a+"May I please have that necklace?"+d+"No, but thanks for asking so politely."+a+"Oh come on, pleeeeease?"+c+b+"?"+c+a+"Pretty PRETTY please?"+c+b+" with sugar on top?"+d+"Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?<style>p:not(:nth-child("+(l[0]=~~l[0]+1)+")){display:none")
```
Demo:
<http://c99.nl/f/212197.html>
[Answer]
## Perl - 356 bytes
```
2=~//;@d=qw"No6|thanks|for|asking|so|pol8ely. 5|beg72want62can't18.
Oh,7|right,2big|baby.|518.|Hey,|what|good's|a4|if2don't1shoulders?
May|I01that4 Oh|come|on,|pleeeeease 30 3|PRETTY0
30|w8h|sugar|on|top";print"Guybrush: $d[$'+print F$'+sysopen F,$0,1]?
Head: $d[$'/3]"=~s/\d/qw(|please |have| |you| Pretty |necklace You|can
,|but |all it)[$&]/ger=~y/|/ /r
```
A self-modifying approach, with substitutions for common strings.
Sample Usage:
```
$ perl please.pl
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$ perl please.pl
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$ perl please.pl
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$ perl please.pl
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$ perl please.pl
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
```
] |
[Question]
[
Write a simple program that copies itself when executed.
Your program should be some kind of executable file on Windows, Linux, etc.., should generate new executable file, which is identical to your original executable file, with random name, and quits.
Your program **shouldn't** involve any kind of file reading or copying. Only file writing for generating new executable file is permitted.
(PS. I was quite embarrassed when at Wikipedia, `Self-replicating program` redirects to `Computer virus` article... :/...)
Smallest executable file size wins. Your answer may be a programming code with proper OS & compiler, assembly code, or HEX dump of a executable file.
[Answer]
## Assembly for x86 Linux, 106 bytes
```
BITS 32
org 0x2E620000
db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident
dd 0, 0
dw 2 ; e_type
dw 3 ; e_machine
dd 1 ; e_version
dd _start ; e_entry
dd phdr - $$ ; e_phoff
dd 0 ; e_shoff
dd 0 ; e_flags
dw 0x34 ; e_ehsize
dw 0x20 ; e_phentsize
phdr: dd 1 ; e_phnum ; p_type
; e_shentsize
dd 0 ; e_shnum ; p_offset
; e_shstrndx
dd $$ ; p_vaddr
fname equ $ - 2
db 'out', 0 ; p_paddr
dd filesize ; p_filesz
dd filesize ; p_memsz
dd 5 ; p_flags
dd 0x1000 ; p_align
_start: mov al, 5 ; 5 = open syscall
mov ebx, fname
mov cl, 65 ; 65 = O_WRONLY | O_CREAT
mov dx, 666q
int 0x80
lea edx, [byte ecx + filesize - 65]
xchg eax, ebx
xchg eax, ecx
mov cl, 0
mov al, 4 ; 4 = write syscall
int 0x80
mov al, 1 ; 1 = exit syscall
int 0x80
filesize equ $ - $$
```
This is for the nasm assembler. Build the binary with the command line: `nasm -f bin -o a.out selfrep.asm && chmod +x a.out`
Here's the same file as a hex dump: `7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 62 2E 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 62 2E 6F 75 74 00 6A 00 00 00 6A 00 00 00 05 00 00 00 00 10 00 00 B0 05 BB 36 00 62 2E B1 41 66 BA B6 01 CD 80 8D 51 29 93 91 B1 00 B0 04 CD 80 B0 01 CD 80`
As requested, the program copies itself to a separate file. (The program could have been significantly shorter if it had been allowed to just write to stdout and let the user redirect to a file.)
I avoided using any borderline tricks to reduce the size. This should be a fully conformant 32-bit ELF binary.
**Edited to add**: In the above version the created file is just a plain file, but it occurs to me that for a couple of bytes (and a tiny bend of the rules), you can create something a little more interesting. This version is only two bytes longer, at 108 bytes:
```
BITS 32
org 0x00010000
db 0x7F, "ELF", 1, 1, 1, 0 ; e_ident
dd 0, 0
dw 2 ; e_type
dw 3 ; e_machine
dd 1 ; e_version
dd _start ; e_entry
dd phdr - $$ ; e_phoff
dd 0 ; e_shoff
dd 0 ; e_flags
dw 0x34 ; e_ehsize
dw 0x20 ; e_phentsize
phdr: dd 1 ; e_phnum ; p_type
; e_shentsize
dd 0 ; e_shnum ; p_offset
; e_shstrndx
dd $$ ; p_vaddr
fname: db 'asr', 0 ; p_paddr
dd filesize ; p_filesz
dd filesize ; p_memsz
dd 7 ; p_flags
dd 0x1000 ; p_align
_start: mov al, 5 ; 5 = open syscall
mov ebx, fname
inc byte [ebx]
mov cl, 65 ; 65 = O_WRONLY | O_CREAT
mov dx, 777q
int 0x80
lea edx, [byte ecx + filesize - 65]
xchg eax, ebx
xchg eax, ecx
mov cl, 0
mov al, 4 ; 4 = write syscall
int 0x80
mov al, 1 ; 1 = exit syscall
int 0x80
filesize equ $ - $$
```
Name this version `asr`, for "a self-replicator": `nasm -f bin -o asr asr.asm && chmod +x asr`
Hex dump version for the nasm-impaired:
`7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 01 00 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 01 00 61 73 72 00 6C 00 00 00 6C 00 00 00 07 00 00 00 00 10 00 00 B0 05 BB 38 00 01 00 FE 03 B1 41 66 BA FF 01 CD 80 8D 51 2B 93 91 B1 00 B0 04 CD 80 B0 01 CD 80`
When you run it, it creates an almost-identical file named `bsr`, but one that is itself executable. Running it will create another binary file named `csr`. And so on.
(Note that annoying things start to happen after `zsr`. I considered making a version that would cascade the name change to `atr` and so on, but I think most people will get bored well before then, so it probably isn't worth all the extra bytes.)
[Answer]
## Bash, 236
Longer than strictly necessary, but I hate long lines. The trailing newline is non-optional.
```
b=\\ q=\' r=\> d=\$
s='exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q'
t='echo t=$q$t$q; echo $s; echo $t; chmod 777 $$'
exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q
echo t=$q$t$q; echo $s; echo $t; chmod 777 $$
```
[Answer]
Here is a proof-of-concept (ungolfed) that shows how the Compilation services in .NET might be used to compile the source code on-the-fly to generate an identical output. The first copy is not identical to the original, but subsequent copies from subsequent runs are exactly identical with random file names:
```
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace _2947
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
var s = @"
using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace _2947
{{
class Program
{{
static void Main(string[] args)
{{
Console.WriteLine({1}Hello world!{1});
var s = @{1}{0}{1};
s = string.Format(s, s, '{1}');
string exeName = Environment.CurrentDirectory + @{1}\{1} + new Random().Next(1000, 9999) + {1}.exe{1};
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = true;
cp.OutputAssembly = exeName;
cp.GenerateInMemory = false;
cp.TreatWarningsAsErrors = false;
cp.ReferencedAssemblies.Add({1}System.dll{1});
var c = CSharpCodeProvider.CreateProvider({1}cs{1});
var cr = c.CompileAssemblyFromSource(cp, s);
}}
}}
}}
";
s = string.Format(s, s, '"');
string exeName = Environment.CurrentDirectory + @"\" + new Random().Next(1000, 9999) + ".exe";
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = true;
cp.OutputAssembly = exeName;
cp.GenerateInMemory = false;
cp.TreatWarningsAsErrors = false;
cp.ReferencedAssemblies.Add("System.dll");
var c = CSharpCodeProvider.CreateProvider("cs");
var cr = c.CompileAssemblyFromSource(cp, s);
}
}
}
```
Demonstration output on command-line:
```
C:\projects\codegolf\2947\2947\bin\Debug>2947
Hello world!
C:\projects\codegolf\2947\2947\bin\Debug>dir
Volume in drive C has no label.
Volume Serial Number is 361D-4479
Directory of C:\projects\codegolf\2947\2947\bin\Debug
09/27/2011 02:17 PM <DIR> .
09/27/2011 02:17 PM <DIR> ..
09/27/2011 02:17 PM 7,680 2947.exe
09/27/2011 02:17 PM 13,824 2947.pdb
09/27/2011 01:33 PM 11,600 2947.vshost.exe
09/27/2011 02:17 PM 6,656 8425.exe
4 File(s) 39,760 bytes
2 Dir(s) 6,486,368,256 bytes free
C:\projects\codegolf\2947\2947\bin\Debug>8425
Hello world!
C:\projects\codegolf\2947\2947\bin\Debug>dir
Volume in drive C has no label.
Volume Serial Number is 361D-4479
Directory of C:\projects\codegolf\2947\2947\bin\Debug
09/27/2011 02:17 PM <DIR> .
09/27/2011 02:17 PM <DIR> ..
09/27/2011 02:17 PM 7,680 2947.exe
09/27/2011 02:17 PM 13,824 2947.pdb
09/27/2011 01:33 PM 11,600 2947.vshost.exe
09/27/2011 02:17 PM 6,656 7538.exe
09/27/2011 02:17 PM 6,656 8425.exe
5 File(s) 46,416 bytes
2 Dir(s) 6,486,360,064 bytes free
C:\projects\codegolf\2947\2947\bin\Debug>7538
Hello world!
C:\projects\codegolf\2947\2947\bin\Debug>dir
Volume in drive C has no label.
Volume Serial Number is 361D-4479
Directory of C:\projects\codegolf\2947\2947\bin\Debug
09/27/2011 02:17 PM <DIR> .
09/27/2011 02:17 PM <DIR> ..
09/27/2011 02:17 PM 7,680 2947.exe
09/27/2011 02:17 PM 13,824 2947.pdb
09/27/2011 01:33 PM 11,600 2947.vshost.exe
09/27/2011 02:17 PM 6,656 4127.exe
09/27/2011 02:17 PM 6,656 7538.exe
09/27/2011 02:17 PM 6,656 8425.exe
6 File(s) 53,072 bytes
2 Dir(s) 6,486,351,872 bytes free
C:\projects\codegolf\2947\2947\bin\Debug>
```
[Answer]
# Batch
## Version 1 (30 bytes)
```
type%0>%random%.bat&type%0>con
```
I win! :)
[Answer]
## DOS COM file - 50 bytes
Creates a file `X.COM` where `X` is replaced with the ones digit of the current time. COM files are simply loaded into memory at offset `100h` of the data segment (CS and DS are set to be the same) so we can simply write this memory out to a file.
```
0000000: b402 cd1a 80e6 0f80 ce30 8836 2c01 31c9 .........0.6,.1.
0000010: ba2c 01b4 3ccd 21c6 062c 0178 89c3 b440 .,..<.!..,.x...@
0000020: ba00 01b9 3200 cd21 b44c cd21 782e 636f ....2..!.L.!x.co
0000030: 6d00 m.
```
nasm source
```
org 100h ; this is a COM file
mov ah,02h ; fn=get time
int 1ah ; rtc interrupt
; convert to ascii - dh gets ones digit of seconds
and dh,0fh
or dh,30h
mov [fname],dh ; move time into filename
xor cx,cx ; clear attributes
mov dx,fname ; load filename
mov ah,3ch ; fn=create file
int 21h ; dos interrupt
mov byte [fname],'x' ; reset filename
mov bx,ax ; set filehandle
mov ah,40h ; fn=write to file
mov dx,100h ; offset is the loaded binary
mov cx,len ; length of write
int 21h ; dos iterrupt
mov ah,4ch ; fn=exit
int 21h ; dos interrupt
fname: db 'x.com',0
len equ $-$$
```
[Answer]
## DOS .COM file, 29 bytes
The '@' is replaced randomly by an odd letter in the first half+ part of the alphabet (A, C, E, G, etc). Output files are either 255 or 256 bytes.
Initial registers in real DOS (as opposed to a debugger) are that AX=0000, CX=00FF, SI=0100.
```
40 INC AX ;"@"
2E CS: ;"."
43 INC BX ;"C"
4F DEC DI ;"O"
4D DEC BP ;"M"
00 20 ADD [BX+SI],AH ;"\0" and dummy parm
E4 40 IN AL,40
24 0F AND AL,0F
0C 41 OR AL,41
88 04 MOV [SI],AL
B4 3C MOV AH,3C
41 INC CX
89 F2 MOV DX,SI
CD 21 INT 21
93 XCHG BX,AX
B4 40 MOV AH,40
49 DEC CX
CD 21 INT 21
C3 RET
```
[Answer]
DOS COM File - 36 bytes
```
56 BE 80 00 AD FE C8 A2 10 01 7E 17 89 F2 88 74
02 B4 3C 33 C9 CD 21 72 0A 8B D8 B4 40 5A B9 24
00 CD 21 C3
```
Output file name is specified on the command line, truncated to 8.3 format, spaces OK (spaces in DOS filenames are legal). Tested using WinXP command prompt.
] |
[Question]
[
## The basics:
You'll need to provide a nine-level word guessing game in the fewest characters possible (in your language of choice).
## The metrics:
* Provide a word-list
(one word per line, seperated by a
newline) (e.g.
`/usr/share/dict/words` or similar could do). It's fine to
pipe a filename or the wordlist
itself into your solution.
* Provide 9 levels with incrementing word length (words with 4 characters `->` 12 characters):
```
Level 1: a random word from the wordlist containing 4 characters
Level 2: a random word from the wordlist containing 5 characters
... ...
Level 8: a random word from the wordlist containing 11 characters
Level 9: a random word from the wordlist containing 12 characters
```
* In every level, obfuscate a randomly chosen word from the list (with a specific word length of course) and replace a certain number of characters by the asterisk (`*`). The *number* of characters to replace: `current_word_length / 3` (round down). Randomize *which* characters to replace.
* Let the player 'guess' the word (only one `try` per level), give feedback (`correct` or `wrong`) and give points accordingly. When correct, the player gains `number_of_obfuscated_characters * 10 points`.
* Print the current score at the end of each level.
## The format (& sample I/O):
Make sure you follow the following formatting scheme:
```
Level 1 # level header
======= #
g*ek # obfuscated word
geek # user input
correct # guess validation
score: 10 # print score
#
Level 2
=======
l*nux
linux
correct
score: 20
Level 3
=======
ran**m
random
correct
score: 40
...
Level 9
=======
sem***act*ve
semiinactive
wrong
score: 90
```
## Winner:
Shortest solution (by code character count). Have fun golfing!
[Answer]
## Perl, 180 chars
```
@w=<>;for$n(4..12){@x=grep/^.{$n}$/,@w;$_=$w=$x[rand@x];vec($_,rand$n,8)=42while($==$n/3)>y/*//;print"Level @{[$n-3]}
=======
$_";say<>eq$w?($@+=$=)&& correct:wrong,"
score: $@0
"}
```
Ruby beating Perl? That will not do! :-)
Like jsvnm's Ruby solution, but unlike Joel Berger's Perl code, this script takes the filename of a word list as a command line parameter. That is, you should run it like this:
```
perl -M5.010 guessword.pl /usr/share/dict/words
```
Here's a de-golfed version:
```
@w = <>;
for $n (4..12) {
@x = grep /^.{$n}$/, @w;
$_ = $w = $x[rand@x];
vec($_, rand $n, 8) = 42 while ($= = $n/3) > y/\*//;
print "Level @{[ $n-3 ]}\n=======\n$_";
say <> eq $w ? ($@ += $=) && correct : wrong, "\nscore: $@0\n";
}
```
The statement `vec($_, rand $n, 8) = 42 while ($= = $n/3) > y/*//` contains a few interesting tricks. First, 42 is the ASCII code of an asterisk; it turns out that using `vec` to modify single chars in a string is shorter than doing it with `substr`. Second, the variable `$=` takes only integer values, so using it to store the number of hidden letters saves me an `int`. Finally, `y/*//` is a short way to count the number of asterisks in a string using the transliteration operator.
Edit: Saved 7 chars by using `$@` to store the score divided by 10 and appending a zero to it during output (which, come to think of it, would've been shorter than the previous version even if I'd used a normal variable).
Edit 2: Turns out embedding literal newlines in the output strings saves a char over messing with `$,`.
[Answer]
# Ruby (188)
takes the filename to read words from as argument.
```
q=*$<
s=0
4.upto(12){|n|o=''+w=q.grep(/^#{?.*n}$/).sample
[*0..n-1].sample(c=n/3).map{|i|o[i]=?*}
puts"Level #{n-3}",?=*7,o
puts STDIN.gets==w ?(s+=c;"correct"):"wrong","score: #{s}0",""}
```
[Answer]
# Bash, 350 chars
```
S=0
for L in {4..12}
do
echo -e Level $(($L-3))\\n=======
W=$(grep -E ^.{$L}$ /usr/share/dict/words|shuf|tail -1)
G=$W
while [ `sed 's/[^*]//g'<<<$G|wc -c` -le $(($L/3)) ]
do
P=$(bc<<<$RANDOM*$L/32767)
G=$(sed "s/\(.\{$P\}\)./\1*/"<<<$G)
done
echo $G
read U
if [ x$U == x$W ]
then
echo correct
S=$(($S+$L/3*10))
else
echo wrong
fi
echo score: $S
done
```
[Answer]
# Perl: 266
```
@ARGV='/usr/share/dict/words';@w=<>;$"='';while($l<9){$o=1+int++$l/3;@s=grep{$l+4==length}@w;@g=split//,$t=$s[rand$#s+1];my%r;$r{rand$#g}++while keys%r<$o;$g[$_]='*'for keys%r;print"Level $l\n=======\n@g";print<>eq$t?do{$p+=$o*10;"Correct"}:"Wrong","\nScore: $p\n"}
```
or with a little more white space
```
@ARGV='/usr/share/dict/words';
@w=<>;
$"='';
while($l<9){
$o=1+int++$l/3;
@s=grep{$l+4==length}@w;
@g=split//,$t=$s[rand$#s+1];
my%r;
$r{rand$#g}++while keys%r<$o;
$g[$_]='*'for keys%r;
print"Level $l\n=======\n@g";
print<>eq$t?do{$p+=$o*10;"Correct"}:"Wrong","\nScore: $p\n"
}
```
and I think with a little work it could get even better!
[Answer]
## R, 363 chars
```
w=tolower(scan("/usr/share/dict/words",what="c"));l=nchar(w);score=0;for(i in 1:9){mw=sample(w[l==i+3],1);cat("Level",i,"\n=======\n",replace(strsplit(mw,"")[[1]],sample(nchar(mw),floor(nchar(mw)/3)),"*"),"\n");v=scan(what="c",n=1,quiet=T);if(length(v)!=0&&v==mw){score=score+10*floor(nchar(mw)/3);cat("correct\n")} else cat("wrong\n");cat("score:",score,"\n\n")}
```
[Answer]
# Python 335
I know I'm a bit late to the party, but python's not represented, so I figured what the heck:
```
import sys
import random
D=open(sys.argv[1]).read().split()
random.shuffle(D)
z=0
for L in range(1,10):
M=L+3;N=M/3;w=[c for c in D if len(c)==M][0];U=list(w)
for i in[random.randint(0,M-1)for i in range(N)]:U[i]='*'
print"\nLevel %d\n=======\n"%L+''.join(U);k=raw_input()==w;z+=[0,N*10][k];print["wrong","correct"][k]+"\nscore:",z
```
And semi-ungolfed:
```
import sys
import random
words = open(sys.argv[1]).read().split()
random.shuffle(words)
score=0
for L in range(1,10):
M=L+3
N=M/3
w=[c for c in words if len(c)==M][0]
obfus=list(w)
for i in [random.randint(0,M-1) for i in range(N)]: obfus[i]='*'
obfus=''.join(obfus)
print"\nLevel %d\n=======\n"%L+obfus
correct=raw_input()==w
score+=[0,N*10][correct]
print["wrong","correct"][correct]+"\nscore:",score
```
[Answer]
# K, 198
Assumes a dictionary d in the current working directory.
```
{O:{@[x;(-_c%3)?c:#x;:;"*"]}',/W:{1?x@&y=#:'x}[_0:`d]'4+!9;i:1+S:0;while[#O;-1"Level ",$i;-1"=======";-1@*O;$[(**W)~0:0;[-1"correct";S+:10*+/"*"=*O];-1"wrong"];-1"score: ",$S;-1"";W:1_W;O:1_O;i+:1]}
```
Ungolfed:
```
{
/W = wordlist; O = obfuscated
O:{@[x;(-_c%3)?c:#x;:;"*"]}',/W:{1?x@&y=#:'x}[_0:`d]'4+!9;
i:1+S:0;
while[#O;
-1"Level ",$i;
-1"=======";
-1@*O;
$[(**W)~0:0; /Read user input and compare to the first word
[-1"correct";
S+:10*+/"*"=*O]; /if correct, increment score
-1"wrong"];
-1"score: ",$S;
-1"";
W:1_W; /knock one off the top of both word lists
O:1_O;
i+:1]
}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 283 bytes
```
from random import*
def f(w,s=0):
for i in range(4,13):W=choice([t for t in w if len(t)==i]);C=sample([*range(i)],T:=i//3);print(f'''Level {i-3}
=======
'''+''.join(I in C and'*'or c for I,c in enumerate(W)));print(['wrong','correct'][(Z:=input()==W)]+f'\nscore: {(s:=s+Z*10*T)}\n')
```
[Try it online!](https://tio.run/##NY4xa8MwEIV3/wptJ9lqk@AOxUFTpkDHgCGOB6NIyRX7JGSlpoT8dldO6C0H77577/nfeHVUfvowzza4gYWOzmnh4F2IeXY2llk@yVGtRZUx6wJDhrRgF8M/5KYUVa301aE2vIlPIC7AxNCy3hCPQilsxXanxm7wfaLy1zOKVh4qhatVKbY@IEVuAeDL/Jie3fGtfGTqNVmSC4D3b4fE94v7jqWakENK08/MvdSLbug2mNBFw2sh/l0bmIKjC0jQLgSjI7QNP6Zk8rfIU71atIWFE43pbip252OlxuKYb9b5QTxOBGKe/wA "Python 3.8 (pre-release) – Try It Online")
I'm on Windows so it's hard to test. But there is a version [here](https://onlinegdb.com/wxsp5BHMF) on a different interpreter site that uses a list of words compiled from [here](https://raw.githubusercontent.com/dwyl/english-words/master/words.txt). (albeit only about 8000 words).
] |
[Question]
[
The lack of a social life drove a poor nerd into inventing another superfluous esolang called `!+~%`. For no good reason it initializes the accumulator with `6` and knows the following commands:
* `!` (`out(Accu); Accu = 6`) prints the accumulator value as decimal string to stdout (without newline) and resets the accumulator to its initial value `6`
* `+` (`Accu = Accu + 7`) adds `7` to the accumulator
* `~` (`Accu = uccA`) reverses the order of digits of the decimal value in the accumulator
* `%` (`Accu = 1Accu mod Accu`) replaces the accumulator by (`1` in front of the accumulator) modulo accumulator
Easier to understand with an example.
`%!+~!` produces `431`: Initially, the accumulator is `6`. `%` replaces it by `16 mod 6`, which is **`4`**, which is printed by the following `!`, while the accumulator is reset to `6`. `+` adds `7` and the `~` command reorders the `13` to be **`31`**, which is printed
For some boring-to-proof reason, the language allows to print any non-negative integer and code golfers around the world are seriously concerned about a flood of »what is the shortest code to produce 6431?« type of challenges. But you can prevent that!
**Task**: Write a program to output the code golfed `!+~%` code to produce a given number!
**Input**: A non-negative integer value in any format yo love (except `!+~%` ;-)
**Output**: The shortest `!+~%` code to produce that output (only one of the possible solutions)
**The shortest code** (in any language) **wins**.
**Test data**:
```
0 --> ++%!
1 --> +%%!
2 --> %%!
3 --> +~%%!
4 --> %!
5 --> +++%%!
6 --> !
12 --> +++%%+!
20 --> ++!
43 --> ++++~!
51 --> +%%++~!
654 --> !+~++~!
805 --> +++%~++~+~!
938 --> +%!+~+!
2518 --> %+++!%++!
64631 --> !%!!+~!
```
[Answer]
# JavaScript (ES6), 139 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Expects the target integer as a string.
```
n=>eval("for(k=0;(g=i=>i?g(i>>2,v=(i&=3)<3?[v+7,+[...v+''].reverse().join``,('1'+v)%v][i]:(r+=v,6),o+='+~%!'[i]):r)(k++,o=r='')!=n;v=6);o")
```
[Try it online!](https://tio.run/##TdHRboIwFAbge5@ikLC2OV0VUbbJDl75FIREgqhV05q69JJXZ2hR7F2//P1Pm54qV91qq65/n9rsmm6Pnca8cdWFhXtj2RlnGTugwlytD0zl@Vw4ZOoDE/6brAsHXwIKKaUDSktpG9fYW8O4PBmlt1vBaEzB8ciVhSpXzAI6kXJhACm0UUB75SvL2RlAGLRIKQ9QZw5TnpmQd1kxISSchYL0azolAFFwl3iUyMv8JQMkY6QdaDFmHvvlW@@zJ32ZH@R7nxHws2Yj@uLkLQWtL49f1p8bMF0@7nBvh/aJP8n3gP3revbJRZrE4SMZBcE9WU5k/yObqj4yTTAntdE3c2nkxRyYltdqt9E7lnICZM8057z7Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"%!+~"∞5в0δKÙ.Δ´6svyiˆ6ëÐÂr1ìs%s7+)yè}}ˆ¯JQ}1ªè
```
Brute-force, so pretty slow. Outputs as a list of characters.
[Try it online](https://tio.run/##AU0Asv9vc2FiaWX//yIlISt@IuKInjXQsjDOtEvDmS7OlMK0NnN2eWnLhjbDq8OQw4JyMcOscyVzNyspecOofX3LhsKvSlF9McKqw6j//zQzMQ) or [verify the first ten test cases](https://tio.run/##AVsApP9vc2FiaWX/VEZOwqk/IiDihpIgIj//IiUhK34i4oieNdCyMM60S8OZLs6UwrQ2c3Z5acuGNsOrw5DDgnIxw6xzJXM3Kyl5w6h9fcuGwq9Kwq5RfTHCqsOo/yz/).
**Explanation:**
```
"%!+~" # Push this string (which we use at the end)
∞ # Push an infinite positive list: [1,2,3,...]
5в # Convert each integer to a base-5 list
δ # Map over each inner list:
0 K # Remove all 0s
Ù # Uniquify this infinite list of lists
.Δ # Pop and find the first list that's truthy for:
´ # Empty the global array
6 # Push a 6 to start with
s # Swap so the current list is at the top of the stack
v # Pop and loop over its digits:
yi # If the current digit is a 1:
ˆ # Pop and add the current integer to the global array
6 # Push a 6 to reset
ë # Else (the current digit is a 2, 3, or 4):
Ð # Triplicate the current integer
 # Bifurcate the top; short for Duplicate & Reverse copy
r # Reverse the order of the (four items on the) stack
1ì # Prepend a 1
s # Swap the top two values
% # Modulo
s # Swap the top two values again
7+ # Add 7
) # Wrap all three items into a list: [reverse(n),1n%n,n+7]
yè # Modular 0-based the current digit into it:
# 2→n%7; 3→reverse(n); 4→1n%n
} # Close the if-else statement
} # Close the loop
ˆ # Pop and add the final value to the global array as well
¯ # Push the global array
J # Join it together to a single string
Q # Check whether it equals the (implicit) input-integer
}1ª # After we've found a result: append a 1
è # Modular 0-based index into the "%!+~"-string:
# 1→!; 2→+; 3→~; 4→%
# (after which this list of characters is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~121~~ 119 bytes
```
f=(n,a='',b,c=6,...s)=>n!=b?f(n,...s,a+'+',b,c+7,a+'-',b,+[...c+''].reverse().join``,a+'%',b,('1'+c)%c,a+'!',[b]+c,6):a
```
[Try it online!](https://tio.run/##ZcrBCoMwEATQe//Cg2zCrqGWEqGQ9kNEMG5jUSQppvj7qemteJt5M7PdbOR1en8qH54updEIT9YA0EBsNCmlojR3X5jhMe5T7mQR8HfAJucqZ2z3iRGgU6vb3BqdkGoOk@/7/CnzR0ANyLLkLAVQO3TIpOXNJg4@hsWpJbzEKM5Snv6lPsjlINeDaL1T@gI "JavaScript (Node.js) – Try It Online")
Modified from my <https://codegolf.stackexchange.com/a/265841/>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 43 bytes
```
¹©ṃ“Ṿ;ɼ6“+7“D1;Ḍ%ṛṛ?“ṚḌ”v@ƒ6®Ḋ⁼
1ç1#ṃ“!+%~”
```
[Try it online!](https://tio.run/##y0rNyan8///QzkMrH@5sftQw5@HOfdYn95gBWdrmQMLF0Prhjh7VhztnA5E9WH4WUOBRw9wyh2OTzA6te7ij61HjHi7Dw8sNlSEmKGqr1gHl////r2SqBAA "Jelly – Try It Online")
Since [it’s permissible to output garbage to STDOUT while returning the actual answer as the pair of link’s return value](https://codegolf.meta.stackexchange.com/a/9658/42248), this is one byte shorter than the [previous version](https://tio.run/##y0rNyan8///QzkMrH@5sftQw5@HOfdYn9zzcOdsMyNE2BxIuhtYPd/SoAoWAyB6sZBZQ4FHD3DKHY5PMgIKH1j3c0fWocQ@X4eHlhsoQcxS1Vev@//@vZKoEAA "Jelly – Try It Online") which avoids doing so.
A pair of links called as a monad with a decimal string argument (e.g. `"5"`) and returning a string program in `!+~%` golfed to output the relevant number. Relatively slow, brute force solution.
Originally got stuck for any programs that included `%` on 0, but now fixed at the cost of three bytes (which I then managed to shave off another way!)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~79~~ 65 bytes
```
⊞υ⟦ω⁶ω⟧Fυ¿¬ⅈ¿¬⌕ιθ⊟ι«≔§ι¹ηF⪪⟦η⁻⁶η!ω⁷+ω⁻⮌ηη~ω∧η⁻﹪XχLηηη%⟧³⊞υEκ⁺λ§ιμ
```
[Try it online!](https://tio.run/##RY9NS8NAEIbP7a8YA8IsjmApVKWnXATBSNCLUHoIzba7uO7G/WgE0b@@Tppgb7P7zvvwzE41fucak3OdgsJEsOkJVgT9Vqzne@cBkwC9B3x2Ed9QnB8P2raoCT4Ff9Ze24i161ALsQZpgoTv@awMQR8slvHRtvJr2F4IAsXo2Yn92hkdcaMIKm1TwNUQEhQXBRsQ3PJ4NY5j/iKP0geJSkyLv2Nasso/pHJtMo5leulxcUPwJO0hKi5NrVPzstgSLAf16fCq6fCdoDaMMIw8O3/whaz8k/P98i5fH80f "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @bsoelch's Python answer.
```
⊞υ⟦ω⁶ω⟧Fυ
```
Start a breath-first search with a state with no output, an accumulator of `6` and no commands yet.
```
¿¬ⅈ
```
Stop when a solution is found.
```
¿¬⌕ιθ⊟ι«
```
If a solution is found then print it, otherwise...
```
≔§ι¹η
```
Extract the current value from the state.
```
F⪪⟦η⁻⁶η!ω⁷+ω⁻⮌ηη~ω∧η⁻﹪XχLηηη%⟧³
```
Create a list of updates, representing a string to output, an amount to add to the current value, and a command to execute, and split the list into groups of three elements.
```
⊞υEκ⁺λ§ιμ
```
Add each group pairwise to the original state, creating four new states to be processed.
[Answer]
# [Haskell](https://www.haskell.org), 165 bytes
```
s%x=x++s%[(c++[p],x,y)|(c,a,o)<-x,(p,x,y)<-zip3"!+~%"[6,a+7,read$reverse$s a,read('1':s a)`mod`a][o++s a,o,o,o++['-'|a<1]]]
f n=[c|(c,_,o)<-show%[("",6,"")],o==n]!!0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZLRboMgFIazW5_iSGrUgInW6tyiT0LIRqxNzVox4ja3ND7B3mA3vWn2TNvTDG1F4QY-zvn_n8D3z57Ll-JwOJ8vr-3OS34v0uqyDmNpUSfHmNaMdOTDPTk54US4qdcRpx5R6n2WdYhM3FuIxoTje9IUfLtqireikcVKAh-BYwf2o9q4z0exfeaMCqWuzsQwlYPt2SeeBowxYwdVRvPB62n0knvxrnIgRGKCkMuIyLKKmaZ_Dft393XkZQUZ1E1ZtUB34AwtULqQZSDgBE5JQLiQetAWss25LCQzDL1WrdQAcHxQgwDC2DKRSwYUTMjSaH1DMwmnon5mm6lqApEWX2jFN6jt1osirB39iWr1UNfhXjsEOuuCxtHmaoH7BU38SBsNfD55CJObytChI0RBMl5HNZjWHCTexGEwqFumOWqw66NMP-kf)
[Answer]
# [Python](https://www.python.org), 156 bytes
*-2 bytes, thanks to STerliakov*
*simple brute force approach, takes input as a (decimal) string*
```
def f(N):
s="";S=[(6,s,s)]
while s!=N:(a,b,s),*S=S;A=str(a);S+=[(6,b+"!",s+A),(a+7,b+"+",s),(int(A[::-1]),b+"~",s),(a and int("1"+A)%a,b+"%",s)]
return b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZIxboMwFIbVlVPYjizZtZEgBEpAVOICWRijDEYBJVJFI0wUdeEi7ZClvVNzmmJokF_Y8Pe_358Nnz-nj-7w3lyv3-euduPfr31Vo5pteOIgnRGSFtmWRVJLzXcOuhyObxXSONskTMlyWJTPRVakeaa7limeFmKMl4JgIrXIuWRKvJh3QUyaHZuO5dskcf0dN8v9tKyQavbIQOKTYYwqAymZtm2r7tw2qJwcb0-3U2uiNSMe4XyBzOO6r0gIip2Z-ZBRmy0BAyiAYz2AKzhnkfDBBO4XAWpLzibzmLA9PYhtleBhUvS2jg_o0ApwFN5PMvqIfsSLmcdeaHGjZRKgYh3EdoSaErtiGfr_gfGqhg5MwQGiVRRMlqMDxUMDnj7x_Xf8Aw)
] |
[Question]
[
Lambda calculus is a system of computation based on single-argument functions; everything in it is such a function. Due to this functional nature, juxtaposition is commonly used to denote function application, grouped from left to right. For example, \$(f g) h=f g h\$ denotes what would conventionally be written \$(f(g))(h)=f(g)(h)\$.
[Church numerals](https://en.wikipedia.org/wiki/Church_encoding) are a way of encoding the nonnegative integers in this system. They are defined as follows:
\$\begin{align\*}
\overparen{\underparen0} f &= \operatorname{id}\\
\overparen{\underparen 1} f &= f\circ\left(\overparen{\underparen 0} f\right)=f\\
\overparen{\underparen 2} f &= f\circ\left(\overparen{\underparen 1} f\right)=f\circ f\\
\vdots\\
\overparen{\underparen n} f &= f\circ\left(\overparen{\underparen{n-1}} f\right)\\
&=\underbrace{f\circ\cdots\circ f}\_n,
\end{align\*}\$
where \$\circ\$ denotes function composition. In other words, the Church numeral \$\overparen{\underparen n}\$ can be seen as a unary operator on a function \$f\$ that nests that function \$n\$ times.
From here, we can define a binary operator (with two curried arguments) that performs addition on two Church numerals:
\$\begin{align\*}
\operatorname{add} \overparen{\underparen a} \overparen{\underparen b} f&= \overparen{\underparen{a+b}} f\\
&= \left(\overparen{\underparen a} f\right)\circ\left(\overparen{\underparen b} f\right).
\end{align\*}\$
That is, we nest \$f\$ \$b\$ times, then another \$a\$ times.
By definition, \$\operatorname{add} \overparen{\underparen a}\$ is a unary operator that, when applied to another Church numeral \$\overparen{\underparen b}\$, results in \$\overparen{\underparen{a+b}}\$. But what happens when we reverse the order, i.e. attempt to evaluate \$\overparen{\underparen a}\operatorname{add}\$? This resulting function has arity \$a+1\$, needed to expand out all the \$\operatorname{add}\$s in \$\underbrace{\operatorname{add}\circ\cdots\circ\operatorname{add}}\_a\$.
## Task
Given (optionally) an integer \$a\ge0\$, and another \$a+1\$ integers \$x\_0,x\_1,...,x\_a\ge0\$, compute the integer \$n\$ such that \$\overparen{\underparen n}=\overparen{\underparen a} \operatorname{add} \overparen{\underparen{x\_0}} \overparen{\underparen{x\_1}}...\overparen{\underparen{x\_a}}\$.
You probably will also need to know the multiplication and exponentiation rules:
\$\begin{align\*}
\overparen{\underparen{a\times b}} f&=\overparen{\underparen a} \left(\overparen{\underparen b} f\right)=\left(\overparen{\underparen a}\circ\overparen{\underparen b}\right)f\\
\overparen{\underparen{a^b}} f &= \overparen{\underparen b} \overparen{\underparen a} f.
\end{align\*}\$
### Example
Take \$\overparen{\underparen 2} \operatorname{add} \overparen{\underparen 3} \overparen{\underparen 4} \overparen{\underparen 5}\$:
\$\begin{align\*}
\overparen{\underparen 2}\operatorname{add}\overparen{\underparen 3} \overparen{\underparen 4} \overparen{\underparen 5}&=(\operatorname{add}\circ\operatorname{add})\overparen{\underparen 3} \overparen{\underparen 4} \overparen{\underparen 5}\\
&=\operatorname{add}\left(\operatorname{add}\overparen{\underparen 3}\right)\overparen{\underparen4} \overparen{\underparen5}\\
&=\left(\operatorname{add}\overparen{\underparen 3} \overparen{\underparen 5}\right)\circ\left(\overparen{\underparen 4} \overparen{\underparen 5}\right)\\
&=\overparen{\underparen 8}\circ\overparen{\underparen{5^4}}\\
&=\overparen{\underparen{5000}}
\end{align\*}\$
### Test cases
```
a x result
0 9 9
1 2,2 4
2 2,2,2 16
2 3,4,5 5000
2 7,1,8 120
3 1,4,1,5 30
3 2,2,2,2 4608
3 2,3,2,4 281483566645248
3 2,3,4,5 46816763546921983271558494138586765699150233560665204265260447046330870022747987917186358264118274034904607309686036259640294533629299381491887223549021168193900726091626431227545285067292990532905605505220592021942138671875
3 3,3,3,3 3381391913524056622394950585702085919090384901526970
4 2,2,2,2,2 120931970555052596705072928520380169054816261098595838432302087385002992736397576837231683301028432720518046696373830535021607930239430799199583347578199821829289137706033163667583538222249294723965149394901055238385680714904064687557155696189886711792068894677901980746714312178102663014498888837258109481646328187118208967028905569794977286118749919370644924079770214106530314724967825243764408114857106379963213188939126825992308882127905810306415158057997152747438230999039420121058243052691828798875998809865692983579259379718938170860244860482142976716892728044185832972278254093547581276129155886886086258355786711680193754189526351391221273418768272112491370597004152057820972058642174713955967404663467723362969481339278834627772126542657434779627861684834294203455419942997830922805201204107013187024101622800974572717408060065235993384198407691177770220323856866020553151446293957513282729090810520040166215232478427409757129336799823635731192497346452409939098243738098803206142762368603693303505732137119043739898807303126822830794424748280315330250324436290184499770851474706427973859450612731909450625705188122632367615184044521656851538649088840328591879043950831910516712687721046964100635071310295009799499919213218249505904439261442688728313586685099505945191069266179018225279933007599239168
```
[Answer]
# [Flurry](https://github.com/Reconcyl/eso/tree/main/flurry), 28 bytes
```
({}){{}{}}[{}{<><<>(){}>}]{}
```
A language based on untyped lambda calculus is certainly the right tool here :)
Takes input in the order of `xa xa-1 ... x1 x0 a`, and evaluates to the Church value of the required expression.
```
({}) pop a; evaluate to a; push back a
{{}{}} \x. x (pop), which takes a function and applies one item from stack
a (\x. x (pop)) [...] evaluates to [...] x0 x1 ... xa-1
[{} the expression (a add)
{<><<>(){}>} add = \x. S (S . K . x)
]
so far, the result is (a add x0 x1 ... xa-1)
{} finally, pop xa and apply to the above
```
Test script:
```
Compare-Object (.\Flurry.exe -nin src.txt 9 0) 9
Compare-Object (.\Flurry.exe -nin src.txt 2 2 1) 4
Compare-Object (.\Flurry.exe -nin src.txt 2 2 2 2) 16
Compare-Object (.\Flurry.exe -nin src.txt 5 4 3 2) 5000
Compare-Object (.\Flurry.exe -nin src.txt 8 1 7 2) 120
Compare-Object (.\Flurry.exe -nin src.txt 5 1 4 1 3) 30
Compare-Object (.\Flurry.exe -nin src.txt 2 2 2 1 3) 4352
Compare-Object (.\Flurry.exe -nin src.txt 2 2 2 0 3) 4096
Compare-Object (.\Flurry.exe -nin src.txt 2 2 2 2 3) 4608
```
[Answer]
# [Haskell](https://www.haskell.org), 54 bytes
```
x#y|(a,b)<-foldl(\(a,b)c->(c^b,(c^b)^a))(0,1)y=(x+a)*b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN80qlCtrNBJ1kjRtdNPyc1JyNGLAvGRdO43kuCQdEKEZl6ipqWGgY6hZaatRoZ2oqZUE0b0zNzEzT8FWoaAoM69EQUXBWEFZIdpER8E0FiIPswUA)
Takes input as \$x\_0 \# [x\_1,\dots,x\_a]\$.
---
Abusing the notation, we have:
\$0 \operatorname{add} x\_0 = x\_0 = (x\_0 + 0) \times 1\$.
If we have
\$(n-1) \operatorname{add} x\_0 \cdots x\_{n-1} = (x\_0 + a\_{n-1}) \times b\_{n-1}\$,
then:
\$\begin{align}
n \operatorname{add} x\_0 \cdots x\_n &= (n-1) \operatorname{add} (\operatorname{add} x\_0) x\_1 \cdots x\_{n-1} x\_n \\
&= (((\operatorname{add} x\_0) + a\_{n-1}) \times b\_{n-1}) x\_n \\
&= ((\operatorname{add} (\operatorname{add} x\_0) a\_{n-1}) \circ b\_{n-1}) x\_n \\
&= \operatorname{add} (\operatorname{add} x\_0) a\_{n-1} (b\_{n-1} x\_n) \\
&= (\operatorname{add} x\_0 (b\_{n-1} x\_n)) \circ (a\_{n-1} (b\_{n-1} x\_n)) \\
&= (x\_0 + {x\_n}^{b\_{n-1}}) \times ({x\_n}^{b\_{n-1}})^{a\_{n-1}} \\
&= (x\_0 + a\_n) \times b\_n
\end{align}
\$
where:
\$a\_n = {x\_n}^{b\_{n-1}}, b\_n = ({x\_n}^{b\_{n-1}})^{a\_{n-1}}\$.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 47 bytes
```
x->[[a,b]=[t=c^b,t^a]|c<-x[^b=!a=0]];(x[1]+a)*b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN_UrdO2ioxN1kmJto0tsk-OSdEriEmNrkm10K6LjkmwVE20NYmOtNSqiDWO1EzW1kqDaehMLCnIqNRIVdO0UCooy80qATCUQR0khTSNRU1NHITraMhZIGukYQSkIw1jHRMcUxDDXMdSxADEMgSKGEDGwKpgGYyDTBMaEajLWAUMktUDVsZoQRy1YAKEB)
A port of my Haskell answer. Takes input as \$[x\_0,x\_1,\dots,x\_n]\$.
[Answer]
# Lambda calculus, 51 characters (or 73 bits)
The function takes two arguments (in curried form as usual): the first argument is `a` as a Church numeral, and the second argument is a list of Church numerals.
```
\a\l l(\h\t\f t(f h))(\f f)(a(\m\n\f\x m f(n f x)))
```
Or in the [binary lambda calculus encoding](https://esolangs.org/wiki/Binary_lambda_calculus):
```
0000010101100000000111001101110001001110000000000101111101100101111011010
```
In lambda calculus, the standard representation of a list is: e.g. the list [a, b, c] is represented by \$\lambda x . \lambda y . x~a~(x~b~(x~c~y))\$. (As a mnemonic, I like to think of the case where \$x = \mathrm{cons}\$ and \$y = \mathrm{nil}\$.) In other words, in lambda calculus, a list *is* its "fold-right" operation.
Now, if we have a list \$l\$, the expression \$l ~ (\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ (\lambda f . f)\$ builds up an "apply" operation. For example, in the case \$l = [a, b, c]\$, it evaluates to \$\lambda f . f ~ a ~ b ~ c\$. (To see this, for example:
$$ [a, b, c] (\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ (\lambda f . f) = \\
(\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ a ~ ([b, c] (\lambda h . \lambda t. t ~ (f ~ h)) ~ (\lambda f . f)) = \\
(\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ a ~ (\lambda f . f ~ b ~ c) = \\
\lambda f . ((\lambda f . f ~ b ~ c) (f ~ a)) = \\
\lambda f . f ~ a ~ b ~ c$$
where from the second line to the third we applied an inductive hypothesis on the case \$l = [b, c]\$. For the base case, the empty list is \$l = [] = \lambda x . \lambda y . y\$, so \$l ~ (\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ (\lambda f . f) = \lambda f . f\$. Alternatively, you can see this as a special case of how in general you would write a fold-left operation on lists in terms of the fold-right operation.)
From here, what we want is simply: \$\lambda a . \lambda l . \mathrm{apply} ~ (a ~ \mathrm{add}) ~ l\$. Substituting \$\mathrm{apply} = \lambda f . \lambda l . l (\lambda h . \lambda t . \lambda f . t ~ (f ~ h)) ~ (\lambda f . f) ~ f\$, and \$\mathrm{add} = \lambda m . \lambda n . \lambda f . \lambda x . m ~ f ~ (n ~ f ~ x)\$ gives the final expression above.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 56 bytes
*Saved 7 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
This is really just a port of [alephalpha's algorithm](https://codegolf.stackexchange.com/a/249195/58563).
Expects `(n)(x)`, where `x` is an array of BigInts.
```
x=>x[x.map((v,i)=>[a,b]=i?[v**=b,v**a]:[0n,1n]),0]*b+a*b
```
[Try it online!](https://tio.run/##hc7NDoIwDAfwu0@yzUo2NuNHMnyQZYcNwWCwI2IIbz9x3hQ0aXroL@2/Vze4vrw33WOD4VzFWsdRF6MZs5vrCBmgobowDrzVzckMjGkPU3f2aDiCQEuBW@bXjvlYBuxDW2VtuJCamANa4JSuPsY5Qj6JWJCE@TdKBIWwncfd6xXYz6NIm@K9LJdjU/K8y@Tql6vF@zJ5qn/56QVFaXwC "JavaScript (Node.js) – Try It Online")
Or **54 bytes** without BigInts:
```
x=>x[x.map((v,i)=>[a,b]=i?[v**=b,v**a]:[0,1]),0]*b+a*b
```
[Try it online!](https://tio.run/##dc1LDsIgGATgvScB/G141PhIqAchLKC2BlNLYw3h9gguFTezmC@TuZtg1v7pltdu9tchjTJF2UUVm4dZEArgsOyUAaulu6hAiLSQ0@izosA0BqqJ3RpiU@/n1U9DM/kbGpE6aaAYb75aDlwDq/ZF@K8IaGFflQMwOFaF5Q0rK/HnqXxVTWRrP5be "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[What does "jelly" mean in the title?](https://www.cyberdefinitions.com/definitions/JELLY.html). [Robber's thread](https://codegolf.stackexchange.com/q/222478/66833)
Jelly has an "Evaluate the argument as Python 3" atom, `ŒV` which takes a string as an argument as evaluates that string as Python 3 code: [Try it online!](https://tio.run/##y0rNyan8//9Rw5yCosy8Eg0lD6BAvo5CeH5RToqikuajhrlHJ4X9/w8A "Jelly – Try It Online").
It also has compressed strings, delimited with `“...»` that can compress any string containing printable ASCII (plus newlines), which can reduce the size of such programs. For example, a [Hello, World!](https://tio.run/##ASsA1P9qZWxsef//4oCcwqThuZnhuovIr8K9xKA8csW7wqPGpOG4pE/Cu8WSVv//) program using `ŒV`
Now, this is much longer that Jelly's normal `Hello, World!` program, by 9 bytes. But is this always the case?
Cops, you are to choose an [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge; write a Python solution to this challenge; compress that solution into Jelly and submit that as your answer.
The challenge you choose must meet these criteria:
* It is open
* It it unlocked
* It has a net score of 5 or more
* Its winning criteria is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and *only* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* All languages are open to compete in it (so no [python](/questions/tagged/python "show questions tagged 'python'")-only challenges etc.)
* It is not a [tips](/questions/tagged/tips "show questions tagged 'tips'") question
* It was posted before the 28th of March, 2021
[This](https://codegolf.stackexchange.com/search?tab=active&q=is%3aq%20%5bcode-golf%5d%20-%5btips%5d%20closed%3a0%20locked%3a0%20score%3a5..%20created%3a..2021-03-28) is a search query that should return (mostly) valid challenges. There's no way to filter challenges on the 4th and 5th criteria, so double check the challenges you choose from this search.
Your answer should contain:
* A piece of Jelly code in the format `“...»ŒV`, where the `...` may be any string of characters from [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), aside from `“”‘’«»`
* A link to the challenge you solved
* The length of your "Python to Jelly" code, in bytes
Note that your program must follow any and all rules stated in the challenge you solve, including builtin bans, strict I/O formats and whatever else. To fully cover all edge cases: **Your program must be able to be posted as a valid answer to the challenge**. The only exception to this rule is that if the challenge scores in characters, you should instead score in bytes.
Jelly currently is written in Python 3.7.4 ([Try it online!](https://tio.run/##y0rNyan8//9Rw5zM3IL8ohKF4spi64KizLwSDSBLryy1qDgzP0/zUcPco5PC/v8HAA "Jelly – Try It Online"), the same version that TIO's [Python 3](https://tio.run/#python3) uses), so your program must work in that version of Python.
You may not edit the rules of the challenge you've chosen. You may not simply compress an existing Python answer to the challenge and submit that as your own work. However, you are allowed to attempt to modify existing users' code in order to improve your score, so long as you provide proper attribution to the original answerer. [Alternative wording](https://chat.stackexchange.com/transcript/message/57463139#57463139).
Your answer is "cracked" if a Robber finds a Jelly program shorter than your "Python to Jelly" program, that completes the same task. Note that a Robber's crack is valid even if it's of the same form (compressed Python eval'ed by Jelly), so long as it's shorter.
Your answer is "safe" if it is uncracked after 2 weeks. You must mark your answer as safe to be considered so. The shortest safe answer, in bytes, wins
[This](https://codegolf.stackexchange.com/a/151721) is, as far as we know, the most optimal Jelly compressor which might help you
## Example submission
```
# 17 bytes, solves https://codegolf.stackexchange.com/questions/55422/hello-world
“¤ṙẋȯ½Ġ<rŻ£ƤḤO»ŒV
[Try it online!][TIO-kmrxghbo]
[TIO-kmrxghbo]: https://tio.run/##ASsA1P9qZWxsef//4oCcwqThuZnhuovIr8K9xKA8csW7wqPGpOG4pE/Cu8WSVv// "Jelly – Try It Online"
```
[Answer]
# 21 bytes, solves [Shortest code to throw SIGILL](https://codegolf.stackexchange.com/q/100532) (safe)
```
“A{gœỴ¹⁻ėe⁾÷ỤḞḂ4ḷ$»ŒV
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//4oCcQXtnxZPhu7TCueKBu8SXZeKBvsO34buk4bie4biCNOG4tyTCu8WSVv//)
This decompresses to the following Python 3 code (which is 22 bytes long, only one byte longer than the compressed version):
```
import os
os.kill(0,4)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCG/mCu/WC87MydHw0DHRPP/fwA "Python 3 – Try It Online")
The basic idea is to pick a task that's completely out of scope for Jelly; in this case, we're interacting with the OS, something that Jelly doesn't have builtins for (short of `ŒV`). So this probably isn't solvable in Jelly without shelling out to Python, and hopefully isn't solvable any more tersely than this.
(In case you're wondering how it works: 4 is the signal number for SIGILL, and `os.kill` appears to just copy its arguments to the `kill(2)` system call literally. 0 means "send this signal to every process in my process group", which if the program is run from a shell, will raise a SIGILL in the Python/Jelly program and nothing else. On TIO, the program is being run from TIO's runner, so the SIGILL happens in the runner rather than in the program itself, but there's still a SIGILL being raised.)
[Answer]
# 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), solves [We had a question once which only failed on Sundays](https://codegolf.stackexchange.com/q/152578/53748) - [Cracked](https://codegolf.stackexchange.com/a/222490/53748) (Razetime)
```
“ÇṄṚ,Ḣ¢;Xv^wME ṖƘżẓ⁸9!»ŒV
```
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4oCcw4fhuYThuZos4biiwqI7WHZed01FIOG5lsaYxbzhupPigbg5IcK7xZJW//8 "Jelly – Try It Online")**
The compressed code is heavily based on [Mr XCoder's submission](https://codegolf.stackexchange.com/a/152579/53748):
```
exit('Su'in time.ctime()<_)
```
Notes:
* There's no need to `import time` since Jelly's interpreter does that, but not much is exposed, just sleeping and simple time formating (and no other date or time functionality exists).
* Something is required to do both of these, I chose `exit`:
+ not return `False` on non-Sundays (since a bool is not `jellify`-able)
+ not print to STDOUT on non-Sundays
[Answer]
# 132 bytes, solves [this](https://codegolf.stackexchange.com/questions/109248/mathematics-is-fact-programming-is-not) - Non-competing
```
“ßẏƊḢ⁵'ĠȦṫ-ỵḲ²ƘçẠaðṁ¹ĠẊḊƝ;ɠ)ṭKpƭȯVsRDỤ⁵ṾḶĿṇƈ>bỴøỴ⁻Ñy1®ḶṪ\ḷ⁶ḋẇƊ⁾L⁼ṀHṃYṘZ1ẏ1ʋḤFTʠzɱĊȦṁƈṠ!ỌẎḌʂ&B?o#Ṗ³⁻Eḋ4ỤṙṃɲɼĖṬƘmẏġ^wp=ạİQƊ)Ḅı/ẉNẊ`»ŒV
```
I don't really know Python, so I used Javascript, executed by Python, executed by Jelly. [Try it online!](https://tio.run/##FY9RKwRRGIZ/y6RoL8SUO6GEFCnSFkkoN1rZcqF1tQe1a3YjLrZVtLPaKCy7w67znbOtmjlOO/Mv3vkj47j5bt63532@g/1MJpckcf4@qEFcawf8MWadEeUOnkCvo5AdcM/3dDV4hnB3gxaI@aRcCFN19MNk6KZAzaWsbg4@0sdrc5ANAwD1wbvqB1TQxek9yK@AmxMzGdzkbP/dhKCXLfDvmHXBSxAF7cSsvxyzHii/CDrfAFU3bSNlRyXwxsJ65J6GbeX8izFdBLkWZBniCrwcnQ3PzhwNgSr@p9mYN8QJIwK6M6DQC3uqAnrT1UODU/Xtk@wURF21VrWTAr9Q7TGIyxXz0o4vf2/TSWKNW9Yf "Jelly – Try It Online")
The Python code:
```
import os
os.system("node -e \"console.log((x=>+x.replace(/(.*)(0|1)(.*)/,(m,a,b,c)=>(((c?1:b)*2-1)*((-1)**a.length)+1)/2))(process.argv[1]))\" "+ input())
```
And finally the Javascript:
```
console.log((x=>+x.replace(/(.*)(0|1)(.*)/,(m,a,b,c)=>(((c?1:b)*2-1)*((-1)**a.length)+1)/2))(process.argv[1]))
```
I expect this to be very easy to beat, but I wanted to have a go.
] |
[Question]
[
# Objective
Simulate an edge-triggered [D Flip-Flop](https://en.wikipedia.org/wiki/Flip-flop_(electronics)#D_flip-flop).
# What is D Flip-Flop?
A D flip-flop is an electronic digital device that outputs an inputted **data** (abbr. D) with synchronization to a **clock** (abbr. CLK). Usually CLK is a uniform pulse, but in this challenge, CLK may be not uniform.
# Input
A bitstring with length \$n\$ will be given as CLK and another bitstring with length \$n-1\$ will be given as D. A bit represents the state of an input during a unit time (tick). CLK leads D by half a tick.
# Output
The output (abbr. Q) is a bitstring with same length and starting timepoint as D. If CLK doesn't start with `01`, the starting bit of Q is implementation-defined. Q is updated upon a rising moment of CLK to the bit of D at the time. On the other times, Q retains its state.
# Examples
The red line indicates a rising moment of CLK.
* Example 1:
[](https://i.stack.imgur.com/kMHal.png)
* Example 2:
[](https://i.stack.imgur.com/572TD.png)
# Rules
* If CLK isn't a tick longer than D, the entire challenge falls into *don't care* situation.
* Though defined as bitstrings, the actual elements of CLK, D, and Q doesn't matter. In this case, if a string is not binary (that is, contains a third character), the entire challenge falls into *don't care* situation.
[Answer]
# [J](http://jsoftware.com/), ~~27~~ 23 bytes
-4 bytes thanks to Bubbler!
```
;@(<@({.\);.1~1,2</\}.)
```
[Try it online!](https://tio.run/##fY/PCsIwDMbvfYqgwlqYMfG4PzAUPIkHr5un6RAvPsDYXr3WybZ0UykpIb8vyZeHXWBQQRpBACEQRC7WCPvz8WDjTCeZrrEwMXLL4TbZFA0aa9Rph@CoXibZqkYfdzCP4v80n1Nu8PIDO/RWDFiPJSOUuVJliu6Cz2OR9Y9E1mvY044d6uqGgSeRzXIMeXWaKNyvbuX9CSVULVwVdDZ5tlx2zoM8D9TvG1z6R37zypNenhCSLu0L "J – Try It Online")
`CLK` is the left argument; `D` is the right one. When `CLK` doesn't start with `01`, the starting bits are the same as the first bit of `D`.
```
;.1 - cut
] - the right argument (D)
( ) - where
2 /\ - the previous element
[ - of the left argument (CLK)
< - is smaller than the next one
}. - drop
1 - the first item
1, - prepend with 1 (for cutting)
( ) - for each cut group
$ - make a list
# - of the same length as the group
{. - with elements same as the first one
<@ - and box the list
; - unbox the sublists and flatten them
[: - function composition
```
# [K (oK)](https://github.com/JohnEarnest/ok), ~~27~~ 23bytes
-4 bytes thanks to ngn!
```
{,/&\'|\'(0,&1_>':x)_y}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWkdfLUa9JkZdw0BHzTDeTt2qQjO@svZ/WrShgqGCARwboLANsWCEuCGcBopZQwUQwgZIPAMUWYQ2QzQZg1gF/dSKxNyCnFQFo/8A "K (oK) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytes
```
∊⊣⊣\¨⍤⊂⍨1,1↓2</⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FH16OuxUAUc2jFo94lj7qaHvWuMNQxfNQ22chG/1HXov9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/h/MkTJoRXqBkBgCCZAAEyCRQwhomAJda4UmHoFdYgURB1EMYQCa4AYoc5VilBvADcGBRgYGCCZH4pkPlSOgPrOhSkKaQrJXLrEAC6Efw1hXoO4Fw4NIJ4yANmE6l9owCC8DA0oqBCQgeZfmIOR1cN9AGKh@5cY9VD/AgA "APL (Dyalog Extended) – Try It Online")
A dyadic tacit function whose right arg is CLK and left arg is D. Accepts both as Boolean vectors. The starting bit of Q follows that of D.
### How it works
```
∊⊣⊣\¨⍤⊂⍨1,1↓2</⊢ ⍝ Input: left←D, right←CLK
2</⊢ ⍝ Detect rising edges of CLK
1,1↓ ⍝ Treat the very first tick as a rising edge
⊣ ⊂⍨ ⍝ Partition D into regions where
⍝ each rising edge marks the start of each region
⊣\¨⍤ ⍝ On each region, overwrite all elements with the first one
∊ ⍝ Enlist; form a simple vector
```
[Answer]
# JavaScript (ES6), ~~40~~ 39 bytes
Takes input as `(clock)(data)`, where *clock* and *data* are arrays of binary digits.
```
C=>D=>D.map(c=>C[i]<C[++i]?p=c:p,i=p=0)
```
[Try it online!](https://tio.run/##bY9BDoMgEEX3nMKdECmZ2TYdu6C3MC4M1QZjgdSm16dNjVW0mSGZwP@fN33zakbzsOF5cP7axo6ipvLyaXVvAjdU6srWJ10Vha3PgcwxSEuBQETj3eiHVg3@xjvOsqwCORXKZZoLVtOswUT7c9RMfOMwkS3mdQwk97BRTGGq99bxPBeCsT007lDWOfsDCRHMvy/Q6c7/0HFjxs0LJNDxDQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Io](http://iolanguage.org/), 56 bytes
The space before `:=` is mandatory, otherwise the colon would be part of the undefined identifier.
Argh. Just 1 byte away from Java!
```
method(c,d,q :=0;d map(i,x,q=if(c at(i)<c at(i+1),x,q)))
```
[Try it online!](https://tio.run/##bY89DsIwDIX3nMJjLDzYK9CbsFQNFUb9hQzcvrSqSuqUWFEs@@Xzs/ZT3egA5wJuU3uPjz74igKNc4UvAdpy8EofGgutfQVl9IrX9T0JLg1EXBHewXwafUfPtIZQyrbgXbZpxGh/P5ASUow0AfYoNnXOFAvQITx77WB4aRebzrncuRz87EHHy8YSb@Otc7v8P/@SASTrcO58@gI "Io – Try It Online")
# Explanation
```
method(c, d, // Take 2 operands, c and d
q := 0 // Set the flip flop to 0
d map (i, x, // Map every item in d
// With the index i and the
// current item x
q = \ // Set the current flip-flop as:
if(c at(i) // If the clock at the same index
< c at(i + 1), // Is less than the clock at the next index?
// I.e. the clock goes from 0 to 1
x, // Set the flip-flop as the current item x
q // Otherwise, make an identity function.
) // The assigned operand result is automatically
) // returned to the map loop, so no
) // explicit reference of the flip-flop in the map.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εINTS+èÆi©ë®Θ
```
First input is \$D\$, second input is \$CLK\$.
Output \$Q\$ as a list of 0s and 1s.
[Try it online](https://tio.run/##yy9OTMpM/f//3FZPv5Bg7cMrDrdlHlp5ePWhdedm/P9vaACGQGBgACagFEgUzDI05AILQmUMYYoh@gwgwNAQAA) or [verify both test cases (and pretty-print)](https://tio.run/##yy9OTMpM/W/kpuTs422loGTvaRvKpeRipaAAZnMZahxaGfP/3NYIv5Bg7cMrDrdlHlp5ePWhdedm/K@t9VIKhCjU4Tq0zf6/ARAYggkQAJNgEUOIKFiCC8KFyEEUQCiwIog2LkOYHoggHBpAdBqA1HMZQm1BmAW1FSoEZPzX1c3L181JrKoEAA).
**Explanation:**
```
ε # Map over the (implicit) input-list D:
N # Push the current map-index
TS # Push 10 as digit-list: [1,0]
+ # Add them to the index: [index+1, index]
I è # Index both of them into the second input CLK
Æi # If they are [1,0]:
© # Store the current map-value in variable `®` (without popping)
ë # Else:
® # Push variable `®`
Θ # And check whether it is exactly 1 (1 if truthy, 0 if falsey)
# (which is necessary, because `®` is -1 by default)
# (after which the list is output implicitly as result)
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 57 bytes
```
lambda C,D,x=0:[x:=[x,d][a<b]for d,a,b in zip(D,C,C[1:])]
```
[Try it online!](https://tio.run/##jY89b8MgEIZ3fsXJE0g0AnWprDLZ6VrFq@sB17ZC69iIUNVp1d/u8uE47ZQc0gF377086JPdj8P9gzZzJ17mXh7qRkJGczoJlpZTKsqJNlUpH@uqGw00VNIa1ABfSuOcZjQreVqRav7cq74FniKw5uQyZKJXR4sPUmM1WKoG/WEx2RytcZOEECfJr0t21yVLDUE7vbbawvb5aWvMaDxEbVr5jqAQHXZ/chptnA1Oks3bqIZg66xoQQiFLim/CyF2P1VCZuaCh@Qj5FDhsRoaCOI9NqMibkEV5xCwdeBfMHZpoLtbAvHz@9F/XSxCMG/qoBbkC9fyhaXkDh7qTPFXtGL5021Qvw "Python 3.8 (pre-release) – Try It Online")
**Input**: 2 lists of 0s and 1s, the first list `C` represents the clock line, and the second list `D` represents the data line.
**Output**: The list `Q` representing the state of the flip-flop through time.
### Explanation
* `for d,a,b in zip(D,C,C[1:])` iterates over the lines, where `d` is the current data bit, `a` is the previous clock bit, and `b` is the current clock bit
* `x` stores the previous state of the flip-flop
* `x:=[x,d][a<b]` updates the state of the flip-flop: if `a<b` is `1` (edge-rise moment), then the state is updated to the current data bit `d`. Otherwise, the state remains the same as previous state.
[Answer]
# Java 8, 55 bytes
```
C->D->{int i=0,p=0;for(int c:D)D[i]=C[i]<C[++i]?p=c:p;}
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/201573/52210), so make sure to upvote him!!
Input as two integer-arrays. Stores the result (\$Q\$) in input \$D\$ instead of returning a new list to save bytes.
[Try it online.](https://tio.run/##hVJRa4MwEH7vrzjyFLEGC3sYtjqGspdtsNHH4kOW2i2d1aBnQUp/u4tJunbQsgjJeffdd98X3fI9D7br70GUvG3hlcvqMAFokaMUsNVV1qEs2aarBMq6Yk8uWMgKV/n0GiStq7bbFY2FJAlsIB7SIMmC5KBTIONwquJwvqkbOr6LKPOylczjVG@LdOX7Mn9QsYjU/DjMJ1qO6j5KLcep2tdyDTutlC6xkdXnKgfujaoBsGiRklCvmdnGZXaTmdmsKZApEJuxZYuxh8HZTuLNL4hnJw6L@H1CSxOOzYbYDT5zOyEupQNLfJycL9vYMnOsLUhfnqfg4swZXPYtFjtWd8iULmBZUaJxERBfH07sNVAW6QLxMwcxnwZ4BjFkTHzxpqUe23FFRZCI4O7eY1g/Ng3vqWvYMK5U2VM95R@8x7gQhULKT8OcB9UUiP3bqEiPJcQRu78AIdJ6vD8oPwa8bendWrpouO3f3fZx@AE)
**Explanation:**
```
C->D->{ // Method with two integer-arrays as parameter and no return-type
int i=0, // Index-integer, starting at 0
p=0; // Previous integer, starting at 0
for(int c:D) // Loop over the digits of input D:
D[i]= // Set the `i`'th value of array D to:
C[i] // If the `i`'th value of array C
<C[++i]? // is smaller than the `i+1`'th value of array C
// (thus C[i] == 0 and C[i+1] == 1)
p=c // Use the current digit `c`,
// and also replace `p` with this digit
: // Else (they're [0,0], [1,0] or [1,1]):
p;} // Use digit `p` instead
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔0ζFLη«F‹§θι§θ⊕ι≔§ηιζζ
```
[Try it online!](https://tio.run/##TU3NCsIwDD6vTxF2SmFCcva048CDrzC6uhZmh20RUXz2urYTTUi@78uvMqNX67ik1IdgZ4cttR085VFcVg940m6OBo2U8BLNXgoB@zi4ST/w1oGVHfzJwSmvr9pFPaGVm8F@@Dtj6kp@0Zy9dREzfadEREzMXLH6TzGLzDeaeW6URCUKpMN9@QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔0ζ
```
Initialise `Q`.
```
FLη«
```
Loop over the elements of `D`.
```
F‹§θι§θ⊕ι
```
Did `CLK` transition from `0` to `1`?
```
≔§ηιζ
```
If so then set `Q` to `D`.
```
ζ
```
Output `Q`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~80~~ 67 bytes
```
t;f(c,d,n)int*c,*d;{for(t=*c++;n--;d++)*c++=t^*c&&(t^=1)?*d:c[-1];}
```
[Try it online!](https://tio.run/##jZDbaoQwGITv9ynCXiw5iYn0ojRIH2QPEP7oVmiz4qa0VHz1Wnc9JVZKEwyjmZmYD6IzQNs6lWPghltSWEeBU6Pq/FJhl1JgTNkoUoYxcntJ3YnCbofdKZXkmZon2EfyqJq2xHrI6z58jzGmSfnu4EVX@OGRUU1Us3nThcUE1RuEUBdAsD@iFNWC91PyWY1TeGr0yMA7JRo19pq@Vwb@ucXvE8F3sXBMrT2ma/GVXXJsSDyo7jBC7oYSA5N/GqpO53h7sGIYMhxCzBsHuyUKxRRln2UGLjOIxhO0ZLzdkoX//78fEZAQ4609al6xj38NnlzUyMWOmLAl3CQTl2SdXPJfdDOrcQng3dQquqb9hvxVn69t9PED "C (gcc) – Try It Online")
Inputs the clock and data as `int` arrays along with the length of the data array.
Returns the output in the clock array starting at one past the beginning.
] |
[Question]
[
## Introduction
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers.
The first challenge in this series is to output a(n) for a given n as input, where a(n) is [A064413](http://oeis.org/A064413), also known as the EKG sequence because the graph of its values resembles an electrocardiogram (hence the *"[How does this feel](https://www.youtube.com/watch?v=FYH8DsU2WCk)"* reference). Interesting properties of this sequence are that all positive integers appear exactly once. Another notable feature is that all primes occur in increasing order.
[](https://i.stack.imgur.com/qpRyL.gif)
## Task
Given an integer input n, output a(n).
\$a(n)\$ is defined as:
* \$a(1) = 1; a(2) = 2;\$
* for \$n > 2\$, \$a(n)\$ is the smallest number not already used which shares a factor with \$a(n-1)\$
*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.*
## Test cases
```
Input | Output
--------------
1 | 1
5 | 3
20 | 11
50 | 49
123 | 132
1234 | 1296
3000 | 3122
9999 | 10374
```
## Rules
* Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
* Invalid input (floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes wins
## Final note
See [this related PP&CG question](https://codegolf.stackexchange.com/questions/175858/terms-of-the-ekg-sequence?r=SearchResults).
[Answer]
# [Haskell](https://www.haskell.org/), ~~66 65~~ 64 bytes
```
f n|n<3=n|m<-n-1=[k|k<-[1..],k`gcd`f m>1,all(/=k)$f<$>[1..m]]!!0
```
[Try it online!](https://tio.run/##NclBCoAgEADAr6zgoUAr6RSoHwkhqaxYXaI6@nejQ3Od3d@4xlhKAMqke0M5aUlSmREzajmqpnECp21epgDJKuFjrFqDNQ@a26@Tc4x1JfmDwMB5HfQAh38HV14 "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 60 bytes
```
((1:2#[3..])!!)
n#l|x:_<-[y|y<-l,gcd y n>1]=n:x#filter(/=x)l
```
[Try it online!](https://tio.run/##XcmxDoIwFEDRna94BAdI2kqLgyXUH8HGNECR@KgNMEDCt1uZHLzJme7TzK8OMVh1D2nKS5HUBWM6i@Mscgnua/moaL3tW0WR9E0LG7gb18qVa2IHXLopPas1wzCawYGC9g1@GtwCJxiNBwt1zpjIdQS//v5FEi7EoSiIkFKSw1WHT2PR9HOgjfdf "Haskell – Try It Online")
Zero-indexed; could save four bytes if series started with 2 (kinda (-1)-indexed, but without value for -1 being defined). Builds the infinite list by lazily maintaining the list of unused numbers.
[Answer]
# [Python 2](https://docs.python.org/2/), 104 bytes
This uses 0-based indexing.
```
from fractions import*
l=[1,2]
exec'i=3\nwhile gcd(i,l[-1])<2or i in l:i+=1\nl+=i,;'*input()
print l[-2]
```
[Try it online!](https://tio.run/##Dcq7EsIgEAXQnq/YLi8swMoHX5JQOEjMnSG7DOKoX4@e@uRv3YRta2uRndZyCxXCT8KepdRRJTcbbb2Knxg6uOPC7w0p0iPce@g0H4wfrlYKgcCUzpicWThNDvrSjeD8qv2gcgFX@m/rWzOnHw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1ˆ2ˆF∞.Δ¯yå≠¯θy¿2@*}ˆ}¯¨θ
```
0-indexed
[Try it online](https://tio.run/##ATYAyf9vc2FiaWX//zHLhjLLhkbiiJ4uzpTCr3nDpeKJoMKvzrh5wr8yQCp9y4Z9wq/CqM64//8xMjI) or [Output the first \$n\$ items](https://tio.run/##ATMAzP9vc2FiaWX/w43/McuGMsuGRuKIni7OlMKvecOl4omgwq/OuHnCvzJAKn3Lhn3Cr///NTA).
**Explanation:**
```
1ˆ2ˆ # Add both 1 and 2 to the global_array
F # Loop the (implicit) input amount of times:
∞.Δ # Get the first 1-indexed value resulting in truthy for the following:
¯yå≠ # Where this value is not in the global_array yet
* # AND:
¯θ ¿ # Where the greatest common divisor of the last item of the global_array
y @2 # and the current value, is larger than or equal to 2
}ˆ # After a new value has been found: add it to the global_array
}¯ # After the loop: push the global_array
¨θ # Then remove the last element, and then take the new last element
# (which is output implicitly as result)
```
[Answer]
## Ruby, 86 bytes
```
a=->(n){n<3?n:1.step{|i|return i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}
```
This runs forever for inputs as low as 10, though.
---
Here's a version with memoization with 102 bytes that runs in acceptable time:
```
m={};a=->(n){n<3?n:m[n]||1.step{|i|return m[n]=i if a[n-1].gcd(i)!=1&&(0...n).map(&a).all?{|j|j!=i}}}
```
[Answer]
# MACHINE LANGUAGE(X86, 32 bit)+C language library malloc()/free()functions, bytes 325
```
00000750 51 push ecx
00000751 52 push edx
00000752 8B44240C mov eax,[esp+0xc]
00000756 8B4C2410 mov ecx,[esp+0x10]
0000075A 3D00000000 cmp eax,0x0
0000075F 7414 jz 0x775
00000761 81F900000000 cmp ecx,0x0
00000767 740C jz 0x775
00000769 39C8 cmp eax,ecx
0000076B 7710 ja 0x77d
0000076D 89C2 mov edx,eax
0000076F 89C8 mov eax,ecx
00000771 89D1 mov ecx,edx
00000773 EB08 jmp short 0x77d
00000775 B8FFFFFFFF mov eax,0xffffffff
0000077A F9 stc
0000077B EB11 jmp short 0x78e
0000077D 31D2 xor edx,edx
0000077F F7F1 div ecx
00000781 89C8 mov eax,ecx
00000783 89D1 mov ecx,edx
00000785 81FA00000000 cmp edx,0x0
0000078B 77F0 ja 0x77d
0000078D F8 clc
0000078E 5A pop edx
0000078F 59 pop ecx
00000790 C20800 ret 0x8
00000793 53 push ebx
00000794 56 push esi
00000795 57 push edi
00000796 55 push ebp
00000797 55 push ebp
00000798 8B442418 mov eax,[esp+0x18]
0000079C 3D02000000 cmp eax,0x2
000007A1 7641 jna 0x7e4
000007A3 3DA0860100 cmp eax,0x186a0
000007A8 7757 ja 0x801
000007AA 40 inc eax
000007AB 89C7 mov edi,eax
000007AD C1E003 shl eax,0x3
000007B0 50 push eax
000007B1 E80E050000 call 0xcc4
000007B6 81C404000000 add esp,0x4
000007BC 3D00000000 cmp eax,0x0
000007C1 743E jz 0x801
000007C3 89C5 mov ebp,eax
000007C5 89F8 mov eax,edi
000007C7 C1E002 shl eax,0x2
000007CA 890424 mov [esp],eax
000007CD 50 push eax
000007CE E8F1040000 call 0xcc4
000007D3 81C404000000 add esp,0x4
000007D9 3D00000000 cmp eax,0x0
000007DE 7415 jz 0x7f5
000007E0 89C3 mov ebx,eax
000007E2 EB28 jmp short 0x80c
000007E4 E9A3000000 jmp 0x88c
000007E9 53 push ebx
000007EA E8E5040000 call 0xcd4
000007EF 81C404000000 add esp,0x4
000007F5 55 push ebp
000007F6 E8D9040000 call 0xcd4
000007FB 81C404000000 add esp,0x4
00000801 B8FFFFFFFF mov eax,0xffffffff
00000806 F9 stc
00000807 E981000000 jmp 0x88d
0000080C C60301 mov byte [ebx],0x1
0000080F C6430101 mov byte [ebx+0x1],0x1
00000813 C7450001000000 mov dword [ebp+0x0],0x1
0000081A C7450402000000 mov dword [ebp+0x4],0x2
00000821 B902000000 mov ecx,0x2
00000826 BE01000000 mov esi,0x1
0000082B B802000000 mov eax,0x2
00000830 8B542418 mov edx,[esp+0x18]
00000834 4A dec edx
00000835 C6040300 mov byte [ebx+eax],0x0
00000839 40 inc eax
0000083A 3B0424 cmp eax,[esp]
0000083D 72F6 jc 0x835
0000083F BF02000000 mov edi,0x2
00000844 81C701000000 add edi,0x1
0000084A 3B3C24 cmp edi,[esp]
0000084D 779A ja 0x7e9
0000084F 803C3B01 cmp byte [ebx+edi],0x1
00000853 74EF jz 0x844
00000855 57 push edi
00000856 51 push ecx
00000857 E8F4FEFFFF call 0x750
0000085C 3D01000000 cmp eax,0x1
00000861 76E1 jna 0x844
00000863 46 inc esi
00000864 897CB500 mov [ebp+esi*4+0x0],edi
00000868 89F9 mov ecx,edi
0000086A C6043B01 mov byte [ebx+edi],0x1
0000086E 39D6 cmp esi,edx
00000870 72CD jc 0x83f
00000872 53 push ebx
00000873 E85C040000 call 0xcd4
00000878 81C404000000 add esp,0x4
0000087E 55 push ebp
0000087F E850040000 call 0xcd4
00000884 81C404000000 add esp,0x4
0000088A 89F8 mov eax,edi
0000088C F8 clc
0000088D 5D pop ebp
0000088E 5D pop ebp
0000088F 5F pop edi
00000890 5E pop esi
00000891 5B pop ebx
00000892 C20400 ret 0x4
00000895
```
Above gcd and the function...
This below assembly code generate the functions and the test program:
```
; nasmw -fobj this.asm
; bcc32 -v this.obj
section _DATA use32 public class=DATA
global _main
extern _printf
extern _malloc
extern _free
dspace dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
fmt db "%u " , 13, 10, 0, 0
fmt1 db "%u %u" , 13, 10, 0, 0
IgcdIIuIIIuIIIuIn db "gcd(%u, %u)=%u" , 13, 10, 0, 0
IfunIIuIIIuIn db "fun(%u)=%u" , 13, 10, 0, 0
section _TEXT use32 public class=CODE
gcd:
push ecx
push edx
mov eax, dword[esp+ 12]
mov ecx, dword[esp+ 16]
cmp eax, 0
je .e
cmp ecx, 0
je .e
cmp eax, ecx
ja .1
mov edx, eax
mov eax, ecx
mov ecx, edx
jmp short .1
.e: mov eax, -1
stc
jmp short .z
.1: xor edx, edx
div ecx
mov eax, ecx
mov ecx, edx
cmp edx, 0
ja .1 ; r<c
.2: clc
.z:
pop edx
pop ecx
ret 8
fun:
push ebx
push esi
push edi
push ebp
push ebp
mov eax, dword[esp+ 24]
cmp eax, 2
jbe .a
cmp eax, 100000
ja .e
inc eax
mov edi, eax
shl eax, 3
push eax
call _malloc
add esp, 4
cmp eax, 0
je .e
mov ebp, eax
mov eax, edi
shl eax, 2
mov dword[esp+ 0], eax
push eax
call _malloc
add esp, 4
cmp eax, 0
je .0
mov ebx, eax
jmp short .1
.a: jmp .y
.b: push ebx
call _free
add esp, 4
.0: push ebp
call _free
add esp, 4
.e: mov eax, -1
stc
jmp .z
.1: mov byte[ebx], 1
mov byte[ebx+1], 1
mov dword[ebp], 1
mov dword[ebp+4], 2
mov ecx, 2
mov esi, 1
mov eax, 2
mov edx, dword[esp+ 24]
dec edx
.2: mov byte[ebx+eax], 0
inc eax
cmp eax, dword[esp+ 0]
jb .2
.3: mov edi, 2
.4: add edi, 1
cmp edi, dword[esp+ 0]
ja .b
cmp byte[ebx+edi], 1
je .4
push edi
push ecx
call gcd
cmp eax, 1
jbe .4
inc esi
mov [ebp+esi*4], edi
mov ecx, edi
mov byte[ebx+edi], 1
cmp esi, edx
jb .3
push ebx
call _free
add esp, 4
push ebp
call _free
add esp, 4
mov eax, edi
.y: clc
.z:
pop ebp
pop ebp
pop edi
pop esi
pop ebx
ret 4
_main:
pushad
push 6
push 3
call gcd
pushad
push eax
push 6
push 3
push IgcdIIuIIIuIIIuIn
call _printf
add esp, 16
popad
push 2
push 2
call gcd
pushad
push eax
push 2
push 2
push IgcdIIuIIIuIIIuIn
call _printf
add esp, 16
popad
push 1
push 1
call gcd
pushad
push eax
push 1
push 1
push IgcdIIuIIIuIIIuIn
call _printf
add esp, 16
popad
push 0
push 1
call gcd
pushad
push eax
push 0
push 1
push IgcdIIuIIIuIIIuIn
call _printf
add esp, 16
popad
push 0
call fun
pushad
push eax
push 0
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 1
call fun
pushadpush eax
push 1
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 2
call fun
pushad
push eax
push 2
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 3
call fun
pushad
push eax
push 3
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 4
call fun
pushad
push eax
push 4
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 5
call fun
pushad
push eax
push 5
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 123
call fun
pushad
push eax
push 123
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 1234
call fun
pushad
push eax
push 1234
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 3000
call fun
pushad
push eax
push 3000
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 9999
call fun
pushad
push eax
push 9999
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
push 99999
call fun
pushad
push eax
push 99999
push IfunIIuIIIuIn
call _printf
add esp, 12
popad
popad
mov eax, 0
ret
```
the results:
```
gcd(3, 6)=3
gcd(2, 2)=2
gcd(1, 1)=1
gcd(1, 0)=4294967295
fun(0)=0
fun(1)=1
fun(2)=2
fun(3)=4
fun(4)=6
fun(5)=3
fun(123)=132
fun(1234)=1296
fun(3000)=3122
fun(9999)=10374
fun(99999)=102709
```
It is possible bugs and wrong copy past...
[Answer]
# Perl 6, ~~84~~ ~~80~~ ~~73~~ ~~***69***~~ ~~50~~ 49 bytes
(0-indexed)
```
{(1,2,{+(1...all @_[*-1]gcd*>1,*∉@_)}...*)[$_]}
```
Thanks to [this answer](https://codegolf.stackexchange.com/questions/175858/terms-of-the-ekg-sequence) for some tricks.
Thanks to ASCII-only for shaving a byte.
[Answer]
# APL(NARS), chars 119, bytes 238
```
∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←i⊃r
∇
```
this test it takes 1m:49s here:
```
a¨1 5 20 50 123 1234 3000
1 3 11 49 132 1296 3122
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~161~~ ~~155~~ ~~152~~ 151 bytes
Saved a byte by switching `int[]` tracking to leverage the existing `BigInteger`!
```
n->{int j,k=n;for(var b=java.math.BigInteger.ONE;0<--n;b=b.setBit(k=j))for(j=1;b.testBit(++j)|b.valueOf(j).gcd(b.valueOf(k)).intValue()<2;);;return k;}
```
[Try it online!](https://tio.run/##fZDLasMwEEXX8VcIQ0Bq7MF5LVrFWQRa6KLNItBVN/IjrvyQjSQbQpJvV6XEbXcdGIkZNHfuUckGFpZZZXjTtVKj0tbQa17DsRep5q2AB@p5XZ/UPEVpzZRCb4wLdPaQDaWZtv2X8e3mVei8yGUw3lvEUGxEuD1zYbWDKhb02Eo8MImS@LarYfoLdrwYJ2D//kyjTRgKmsQJqFzvuMZVXBLiBst4ThPQubq1Z7OSXBIYWN3n@yMuCRRphv8aFSFgF3@4EpPNghJKZa57KVBFr8ZyOYaRbUQZWp6hxhLig5ZcFACAmCwUGYldHE5K5w20vQZryhJgf7pS6IKm6lP4ge@SYUF8Qr2Js32XQurpV2ryv07mdFTAgHVdfcI/n9MxqXJbYEWI1f7xc/Xu59WYuVmbRWTWkZkvli5XZhlFkXm08Q0 "Java (JDK) – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 27 bytes
```
2┅@⟨:1⟪Ė₌0⟪;)d;d&1D⟫?⟫#+⟩ₓE
```
[Try it online!](https://tio.run/##S0/MTPz/3@jRlFaHR/NXWBk@mr/qyLRHTT0GQIa1Zop1ipqhy6P5q@2BWFn70fyVj5omu/7/b2oAAA "Gaia – Try It Online")
1-based indexing.
Runs rather slowly, as it tries each integer until it finds `a(n)`.
```
2┅ | push [1 2]
@ | push n
⟨ ⟩ₓ | do n times:
: | dup
1⟪ ⟫# | and find the first 1 integer i where the following results in a truthy value:
Ė₌ ? | is i an Ėlement of the list? Also push an extra copy of the arguments
0 | if so, give falsy result, so try the next integer
⟪ ⟫ | else do the following:
;)d | get divisors of a(n-1)
;d | get divisors of i
&1D | set intersect and remove the first element (which is always 1)
| this yields an empty set if no divisors are shared (falsy, so try next integer)
| or a non-empty set (truthy, so returns i = a(n))
+ | and concatenate to list (end loop).
E | finally, Extract the nth element (n taken implicitly)
```
] |
[Question]
[
# Introduction
A [recursive acronym](https://en.wikipedia.org/wiki/Recursive_acronym) is an acronym that contains or refers to itself, for example:
`Fish` could be a recursive acronym for `Fish is shiny hero`, notice how that also contains the acronym itself. Another example is `Hi` -> `Hi igloo`. Or even `ppcg paints` -> `ppcg paints cool galaxies pouring acid into night time stars`
So basically, a sentence is a recursive acronym if the first letters of each of the words spell out the first word or words.
---
# Challenge
Make a program that takes a string of 1 or more words separated by a space character, and outputs a recursive acronym, or an empty string if it's impossible. It is impossible to make a recursive acronym for a string like, for example, `ppcg elephant` because you would start by taking the `p` from `ppcg` then adding that to the acronym, then taking the `e` from `elephant`. But now we have a contradiction, since the acronym currently spells out "pe..", which conflicts with "pp..". That's also the case with, for example, `hi`. You would take the `h` from `hi`, but the sentence is now over and there are no more letters to spell out `hi` and we are just left with `h` which doesn't match `hi`. (The string needs an amount of words more than or equal to the amount of letters in the acronym)
Input and output are not case sensitive
---
# Restrictions
* Anything inputted into your program will be valid English words. But you must make sure to output valid English words too (you can use a database or just store a word for each of the 26 letters)
* Standard loopholes and default IO rules apply
---
# Test Cases
```
hi igloo -> hi
ppcg paints -> (impossible)
ppcg paints cool giraffes -> ppcg
ppcg paints cool galaxies pouring acid into night time stars -> ppcgpaints
ppcg paints cool galaxies pouring acid into night time -> ppcg
ppcg questions professional pool challengers greatly -> (impossible)
I -> I
```
---
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest source code in bytes wins
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
¸
mά
VøUÎ ©V
```
[Try it online!](https://tio.run/##dcsxCgIxEEbhPqf4Sa0HsRXcRiyGmM2OJJmQRPAUew/BA2ydHCyKpWD5@Hg3SnWMtqnQ1/ZSU99OfUV7TmOc9cJg50X0TumUjEMijrX8JIyIh@NM82z/IHl6sC1Ics8cHcjwFR8XRHZLReVgUSrl73/QF@zD8Q0)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
ð¡©ηʒJ®€нJηså}θJ
```
[Try it online!](https://tio.run/##nY4xCsIwFIZ3T/HorFfwAL3FM6bpg5gXk1Qs6OIRvIGDgyDiVhcpNJtD8QxepAZcHJzcfvj@7@dnjzOSw2ZVD/HaHbpT3zz2eXd57c7Pe943Ph63/S0f6iy2MJlCbLPxUBKQ0swja4UCi2SC/84gmDUoclgU8hdBjWuSHixXjowCFDSHxBkMqTJAoIUEH9D9K3@0ZSV9IDap6zg98SmjTmKaESVqLY2SzoNyEoOu3w "05AB1E – Try It Online")
[Answer]
## Haskell, ~~51~~ 48 bytes
Edit: -3 bytes thanks to @xnor.
```
(\w->[r|p<-scanl1(++)w,map(!!0)w==p,r<-p]).words
```
Finds acronym.
[Try it online!](https://tio.run/##bcqxCsIwFEbhV/nt1GJbdLfugk6OKnKJTXoxTS5JpA4@u7E4iuPhfAPFe29t1t05l@ep2Z7CSzZNVOTsulwuq6keScrFYlVNXSd12DRyqdrJh1vMI7FDhxkcrijlkY4p7B1a6AqnYmCwsd4XNQoRZSAzT/Enoby3MBxI6/47d/8FWXpyHyH@EdgZkOIb5u/h2AwJicceMVGIxSW/lbZkYm6UyAc "Haskell – Try It Online")
```
\w-> .words -- let 'w' be the input list split into words
p<-scanl1(++)w -- loop 'p' through the list starting with the first word
-- and appending the next words one by one, e.g.
-- "Fish","is","shiny","hero" -> "Fish","Fishis","Fishisshiny","Fishisshinyhero"
,map(!!0)w==p -- if the word made out of the first characters of the
-- words of 'w' equal 'p'
[r| r<-p] -- return the letters of 'p' - if the check before
-- never evaluates to True then no letters, i.e. the
-- the empty string is returned
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~50 42 58~~ 49 bytes
*-9 bytes thanks to nwellnhof*
```
{~first {m:g/<<./.join~~/^$^a/},[R,] [\~] .words}
```
[Try it online!](https://tio.run/##ncsxC4JAGIfxvU/xRyISxNsaytZobjWFS@/Ot9Q77hVCRL/61RTOrb@HxynfHkI3YqdxRpgWTZ4HTN3RiCxLRfq01C@LKLelFHOS35IC@X0pkL6tr3kOpw3LEXofyUeFWuko/smFuAExuKF@RKO8XcUrgUxr1@RcZeAk9QOjsraFIS@1VvxFyAr0Qq8w1GD/xxXF4QM "Perl 6 – Try It Online")
First option. ~~I'm exploiting the fact the `ord` only returns the ordinal value of first letter of a string, while `chrs` takes a list of ords and returns a string.~~ Or the regex from [moonheart's answer](https://codegolf.stackexchange.com/a/174793/76162) is shorter `:(`. For reference, the previous answer was `.words>>.ord.chrs` instead of `[~] m:g/<<./`
### Explanation:
```
{~first {m:g/<<./.join~~/^$^a/},[R,] [\~] .words}
{ } # Anonymous code block
first # Find the first
[R,] [\~] .words # Of the reverse of the triangular joined words
{ } # That matches:
m:g/ / # Match all from the original string
<<. # Single letters after a word boundary
.join # Joined
~~/^$^a/ # And starts with the given word
~ # And stringify Nil to an empty string
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
^
$'¶
\G(\w)\w* ?
$1
+`^(.+)(\w.*¶\1 )
$1 $2
!`^(.+)(?=¶\1 )
```
[Try it online!](https://tio.run/##bclLCoMwFEbheVbxFyz1AYKdF4duIogXG@MFm4Qkxa7MBbixVGgHHXR2@I5XkQ2lc94NqRfZZd@E7HK5FnIt0YqsEdXQ53VVHFaX@yYbFIciu4rTd7S3D6c0M1gv1grnRg1HbGL4bYzWLtDsaZrUv0MLvVgFOPv0bDRo5DuOb2FYzxGRHwohkg9v "Retina 0.8.2 – Try It Online") Finds the recursive acronym, if any. Explanation:
```
^
$'¶
```
Duplicate the input.
```
\G(\w)\w* ?
$1
```
Reduce the words on the first line to their initial letters.
```
+`^(.+)(\w.*¶\1 )
$1 $2
```
Insert spaces to match the original words, if possible.
```
!`^(.+)(?=¶\1 )
```
Output the first line if it is a prefix of the second line.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes
```
$!=[~] m:g{<<.};say $! if m:g{<<\w+}.map({$_ eq $!}).any
```
[Try it online!](https://tio.run/##K0gtyjH7X1yapODr6OmnoRKvqVD9X0XRNrouViHXKr3axkav1ro4sVJBRVEhMw0qFFOuXauXm1igUa0Sr5BaCJSr1dRLzKv8X/sfAA "Perl 6 – Try It Online")
Previously regexes were confusing and unusable to me. Suddenly I understand them perfectly. What happened to me :P
Fulfills choice 1.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 40 bytes
First option:
```
{$[1=#:x;x;$[(*:t)~,/*:'t:" "\x;*:t;`]]}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlol2tBW2arCusJaJVpDy6pEs05HX8tKvcRKSUEppsIaKGKdEBtb@z9NQSkjUyEzPSc/X4kLyCkoSE5XKEjMzCspRucrJOfn5yikZxYlpqWlQmQ9lf4DAA "K (ngn/k) – Try It Online")
[Answer]
# Rust, 155, [try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=3f493af80510e031bd0c7f85f4cd3497)
Selected: Problem 1: Finding acronym
```
type S=String;fn f(t:&str)->S{let l=t.to_lowercase();let w=l.split(' ').fold(S::new(),|a,b|a+&b[..1])+" ";if (l+" ").contains(w.as_str()){w}else{S::new()}}
```
Ungolfed, just a bit:
```
fn f(t: &str) -> String {
let l = t.to_lowercase();
let w = l.split(' ').fold(String::new(), |a, b| a + &b[0..1]) + " ";
if (l + " ").contains(w.as_str()) {
w
} else {
String::new()
}
}
```
Or if we can assume that the input is all lowercase, just 130:
```
type S=String;fn f(l:S)->S{let w=l.split(' ').fold(S::new(),|a,b|a+&b[..1])+" ";if (l+" ").contains(&w.as_str()){w}else{S::new()}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Ḳµ;\fZḢWƊ
```
A full-program printing the recursive abbreviation if it is possible.
**[Try it online!](https://tio.run/##y0rNyan8///hjk2HtlrHpEU93LEo/FjX////CwqS0xUKEjPzSooVkvPzcxTSE3MSKzJTixUK8kuLMvPSFRKTM1MUgPL5Cnn5JQolGakKxdmVAA "Jelly – Try It Online")**
### How?
```
Ḳµ;\fZḢWƊ - Main Link: list of characters
Ḳ - split at space (let's call this v)
µ - start a new monadic chain (i.e. f(v)):
\ - cumulative reduce v with:
; - concatenation -> [v(1), v(1);v(2), v(1);v(2);v(3); ...]
Ɗ - last three links as a monad (i.e. f(v)):
Z - transpose -> [[v(1)[1], v(2)[1], ...],[v(1)[1],v(2)[2],...],...]
Ḣ - head -> [v(1)[1], v(2)[1], ...] ... i.e. 'the potential abbreviation'
W - wrap in a list -> ['the potential abbreviation']
f - filter discard those from the left list that are not in the right list
- implicit print -- a list of length 0 prints nothing
- while a list of a single item prints that item
```
[Answer]
# JavaScript [ES6], 74 bytes
```
s=>s.split` `.map(w=>(b+='('+w,e+=')?',t+=w[0]),b=e=t='')&&t.match(b+e)[0]
```
Creates a regular expression to match on. See examples in code.
All test cases:
```
let f=
s=>s.split` `.map(w=>(b+='('+w,e+=')?',t+=w[0]),b=e=t='')&&t.match(b+e)[0]
console.log(f('hi igloo'))
// 'hi'.match('(hi(igloo)?)?')[0] == 'hi'
console.log(f('ppcg paints'))
// 'pp'.match('(ppcg(paints)?)?')[0] == ''
console.log(f('ppcg paints cool giraffes'))
// 'ppcg'.match('(ppcg(paints(cool(giraffes)?)?)?)?')[0] == 'ppcg'
console.log(f('ppcg paints cool galaxies pouring acid into night time stars'))
// 'ppcgpaints'.match('(ppcg(paints(cool(galaxies(pouring(acid(into(night(time(stars)?)?)?)?)?)?)?)?)?)?')[0] == 'ppcgpaints'
console.log(f('ppcg paints cool galaxies pouring acid into night time'))
// 'ppcgpaint'.match('(ppcg(paints(cool(galaxies(pouring(acid(into(night(time)?)?)?)?)?)?)?)?)?')[0] == 'ppcg'
console.log(f('ppcg questions professional pool challengers greatly'))
// 'pqppcg'.match('(ppcg(questions(professional(pool(challengers(greatly)?)?)?)?)?)?')[0] == ''
console.log(f('I'))
// 'I'.match('(I)?')[0] == 'I'
console.log(f('increase i'))
// 'ii'.match('(increase(i)?)?')[0] == ''
console.log(f('i increase'))
// 'ii'.match('(i(increase)?)?')[0] == 'i'
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
⌈:¦$∩h¦↔
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIg6wqYk4oipaMKm4oaUIiwiIiwicHBjZyBwYWludHMgY29vbCBnYWxheGllcyBwb3VyaW5nIGFjaWQgaW50byBuaWdodCB0aW1lIl0=)
[Answer]
# [Python 2](https://docs.python.org/2/), 106 bytes
First option - finding recursive acronym.
Returns result in list.
```
I=input().split()
print[' '.join(I[:i])for i in range(1,-~len(I))if[j[0]for j in I]==list(''.join(I[:i]))]
```
[Try it online!](https://tio.run/##VY5BDoJADEX3nKK7MkaJGlcmHIAzEBYTKEPJONMwNdGNV8chxIWr5re//3156xTDde3jQFAj4trUHOSppamSeM6zkIWDtghYzZFD2bR37swYF2DgAIsNjsrL8fTxlI/G8NjO7bnbDPNmaLq69py0xL8A060ZVxT0oh42/OG2okjvQGzmpbyLHpz19sWUQOIz13Bgex5yqkYI7CYF5QdBUrskLPZ38iSTDfrTe1xWjF8 "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 120 bytes
First option - finding recursive acronym.
```
def F(I,a=[],r=''):
for j in I.split():
a+=j,
if list(''.join(a))==[i[0]for i in I.split()]:r=' '.join(a)
return r
```
[Try it online!](https://tio.run/##VY1BCoMwFET3nmJ2MVSkdClkW@gZxMVHo35Jk5B8oT29jZuCq2GGmTfxK2vwj@OY7Ixn/WrI9EOTjFK6qzCHhA3s8WpzdCz1GYJuZmuK8gzHWWql2i2wr0lrY3ru78O548tu6AoT/2KFZGVPHumIib2UaxXjuCBScRljCA4LOfqwzYhhL6UFNPJUqBLgeVkFwm@LLJSy0tWVY52NK3lR@vgB "Python 2 – Try It Online")
[Answer]
# Javascript, 71 bytes
Approach 1
```
l=s=>{p=s.split(' ');k=p.reduce((r,x)=>r+x[0],'');return k==p[0]?k:''}
```
Ungolfed:
```
l=s=>{
p = s.split(' ');
k = p.reduce((r,x)=>r+x[0],'');
return k==p[0] ? k : '';
}
```
* Split the string by space.
* Create new string by taking first character from each word.
* Compare it with the first word.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-apl`, 57 bytes
```
$_=y="";$F.all?{|w|$F.map(&:chr).join[/^#{y+=w}/]?$_=y:p}
```
[Try it online!](https://tio.run/##nY9BCsIwEEX3nmJQEUW0e6V0J3gGURljTEfSTExSatFe3Rh148KVuwf/v8@Mqw9tjMN93ub9/nK4mqPWxe3e3BNWaMejhSjdZH5mMptsN7i107zpsm3xMha2i7EkIKWZe9YKBRbJBP/NIJg1KHJ4OslfCWq8kvRguXZkFKCgI6ScwZAqAwSqJPiA7l/5o11q6QOxSV3H6RKfGHUS04wo09fSKOk8KCcx6La3frB99@MMrX4C "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 109 bytes
```
def f(s,J=''.join):s=s.split();return[J(s[:i])for i in range(len(s)+1)if J(zip(*s)[0]).find(J(s[:i]))==0][-1]
```
[Try it online!](https://tio.run/##pZDBTsMwDIbP21P4lgS6auNYVB6gr1D1ELVJapQ5IXYlxsuXDAkhIXHiZsv@Plt/vsma6GnfF@fBa26GXqn2NSGZjntuOUcUbZ6Lk63QOGgeO5yMTwUQkKBYCk5HR5rN48Wgh0F/YNYPbMbzZFqPtOhvyvT9eRpPl2m/83znR7VWT4gpqeZ4UDnPAbJFEv7dw5xShIDFeu/@mtpo39Ex5LQVpAB2xqWekQSEYRUQvDpgseU/gh/0bXMsmKjul1S/4lrbWOGqmlcbay7BFYZQnJV4@wJRTd3xkKtdgBt1elFNzd3snw "Python 2 – Try It Online")
[Answer]
# Scala, 76 bytes
Solution for simple case (acronyms without whitespaces)
```
def^(s:String)={val l=s.split(" ");if(l(0)==l.map(_(0)).mkString)l(0)else""}
```
# Scala, ~~144 bytes~~ 100 bytes (see solution by ASCII-only in the comments)
```
def^(s:String)={val l=s.split(" ");l.scanLeft(List[String]())(_:::List(_)).find(_.mkString==l.map(_(0)).mkString).map(_.mkString).getOrElse("")}
```
Test in REPL
```
scala> def^(s:String)={val l=s.split(" ");if(l(0)==l.map(_(0)).mkString)l(0)else""}
$up: (s: String)String
scala> ^("hi igloo")
res12: String = hi
scala> ^("ppcg paints cool giraffes")
res13: String = ppcg
scala> ^("ppcg paints Xcool giraffes")
res14: String = ""
scala> ^("ppcg paints cool galaxies pouring acid into night time stars")
res15: String = ""
scala>
scala> def^(s:String)={val l=s.split(" ");l.scanLeft(List[String]())(_:::List(_)).find(_.mkString==l.map(_(0)).mkString).map(_.mkString).getOrElse("")}
$up: (s: String)String
scala> ^("hi igloo")
res16: String = hi
scala> ^("ppcg paints cool giraffes")
res17: String = ppcg
scala> ^("ppcg paints Xcool giraffes")
res18: String = ""
scala> ^("ppcg paints cool galaxies pouring acid into night time stars")
res19: String = ppcgpaints
```
] |
[Question]
[
Consider two sorted arrays of integers \$X\$ and \$Y\$ of size \$m\$ and \$n\$ respectively with \$m < n\$. For example \$ X = (1,4)\$, \$Y = (2,10,11)\$.
We say that a matching is some way of pairing each element of \$X\$ with an element of \$Y\$ in such a way that no two elements of \$X\$ are paired with the same element of \$Y\$. The cost of a matching is just the sum of the absolute values of the differences in the pairs.
For example, with \$X = (7,11)\$, \$Y = (2,10,11)\$ we can make the pairs \$(7,2), (11,10)\$ which then has cost \$5+1 = 6\$. If we had made the pairs \$(7,10), (11,11)\$ the cost would have been \$3+0 = 3\$. If we had made the pairs \$(7,11), (11,10)\$ the cost would have been \$4+1 = 5\$.
As another example take \$X = (7,11,14)\$, \$Y = (2,10,11,18)\$. We can make the pairs \$(7,2), (11,10), (14,11)\$ for a cost of \$9\$. The pairs \$(7,10), (11,11), (14,18)\$ cost \$7\$.
The task is to write code that, given two sorted arrays of integers \$X\$ and \$Y\$, computes a minimum cost matching.
## Test cases
```
[1, 4], [2, 10, 11] => [[1, 2], [4, 10]]
[7, 11], [2, 10, 11] => [[7, 10], [11, 11]]
[7, 11, 14], [2, 10, 11, 18] => [[7, 10], [11, 11], [14, 18]]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
∧≜I&pᵐz₀.-ᵐȧᵐ+I∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HH8kedczzVCh5unVD1qKlBTxfIOLEcSGh7AuX@/4@ONtcxNNQxNInViTbSMTQAcyxiY/9HAQA "Brachylog – Try It Online")
### Explanation
```
∧
≜I Take an integer I = 0, 1, -1, 2, -2, 3, -3, …
&pᵐ Permute each sublist
z₀. Zip the sublists together. The result of the zip is the output
-ᵐȧᵐ Absolute differences of each pair
+I The sum of these differences must be I
∧
```
Since we unify `I` to an integer at the very beginning, we try things from small values of `I` to large values of `I`, which means the first time it will succeed will necessarily be for the pairing with smallest absolute differences.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14 12~~ 11 bytes
```
Œ!ż€IASƊÞḢṁ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWjex41rfF0DD7WdXjewx2LHu5s/P//v5GOoYGOoeF/cyABAA "Jelly – Try It Online")
* -1 byte thanks to Jonathan Allan
* -1 byte thanks to Mr. Xcoder
* -2 bytes thanks to an anonymous editor
Brute force. Takes input as \$Y\$ then \$X\$.
```
Œ!ż€IASƊÞḢṁ
Œ! All permutations of Y.
ż€ Zip each of the permutations with X.
ƊÞ Sort by:
I Difference of each pair.
A Absolute value.
S Sum.
Ḣ Take the first matching.
ṁ Mold the result like X. Keeps only values up to the length
of X which removes unpaired values from Y.
```
[Answer]
## Haskell, ~~78~~ ~~77~~ 76 bytes
```
import Data.Lists
(argmin(sum.map(abs.uncurry(-))).).(.permutations).map.zip
```
TIO doesn't have `Data.Lists`, so no link.
Basically the same algorithm as seen in [@dylnan's answer](https://codegolf.stackexchange.com/a/167746/34531).
Edit: -1 byte thanks to @BMO.
[Answer]
# JavaScript (ES7), 121 bytes
Takes the 2 arrays in currying syntax `(x)(y)`.
```
x=>y=>(m=P=(b,[x,...a],s=0,o=[])=>1/x?b.map((v,i)=>P(b.filter(_=>i--),a,s+(x-v)**2,[[x,v],...o])):m<s||(r=o,m=s))(y,x)&&r
```
[Try it online!](https://tio.run/##fYxNasMwEIX3PYVWYSYdy5ExpJSMc4XsxVDs1C4udhSsYBTI3V1Zq1LaDjwY3s/3Wc@1P0/99ZZd3Hu7dLwEru5cwcgnhoZsIK11LeR5R46tIFcmD8dGj/UVYKY@GidodNcPt3aCN676LEOqyT9DyGbcbguykTLLCnKC@Doe/OMBEzsa2SPCnQJuNtNydhfvhlYP7gM6sIZUKaTiIdiClNlFGUkGqjxXdq0UsWLLNRV5@kHYpwH9R9inZUQYk7LfGVGlfGdEvchfjPUrU0OWLw "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
[,.[-[:,@:(0{]#~1>])"1-/
```
[Try it online!](https://tio.run/##hYyxCoAgGAZ3n@KjBgv8zT@CQjB6D3GKJFoaGqNe3QKXtrbjDm5L8XAaBhYmeaU9easmW5kzlDePoS6YmlSLQkNGpyUULot4CLHM6w5Gh4gWbMCclSQimbF/5V/mzwA8iPQA "J – Try It Online")
## Explanation/Demonstration:
A dyadic verb, `x f y`
`-/` finds the differences
```
7 11 14 -/ 2 10 11 18
5 _3 _4 _11
9 1 0 _7
12 4 3 _4
```
`(0{]#~1>])"1` for each row keep only the non-positive values and take the first one:
```
7 11 14 ([:(0{]#~1>])"1-/) 2 10 11 18
_3 0 _4
```
`[:,@:` flattens the list (to match the shape of the left argument)
`[-` subtract the min. differences from the left argument
```
7 11 14 ([-[:,@:(0{]#~1>])"1-/) 2 10 11 18
10
11
18
```
`[,.` stitch them to the left argument:
```
7 11 14 ([,.[-[:,@:(0{]#~1>])"1-/) 2 10 11 18
7 10
11 11
14 18
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 18 bytes
```
t#h.msaMbm.T,dvz.p
```
[Try it here!](http://pyth.herokuapp.com/?code=t%23h.msaMbm.T%2Cdvz.p&input=%5B2%2C10%2C11%5D%0A%5B7%2C11%5D&debug=0)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 66 bytes
```
@(X,Y)[X;C([~,r]=min(sum(abs(X-(C=perms(Y)(:,1:numel(X)))),2)),:)]
```
Anonymous function that takes row vectors `X`, `Y` as inputs and outputs a 2-row matrix where each column is a pair of the matching.
[**Try it online!**](https://tio.run/##VYtBCsIwFET3niLL@fANpghKJCD0EikhiyopCKZKY1169fizEgceDG@Yx/U1vlOdnNa6nuF5oOBPPcKHl@jybUZZM8ZLgd@id8@05IKBYNnYec3pDk8S7gRLsU4IhtU@sgodK7MTTKSN6ENrTYv9ybYL/wfhGKl@AQ)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
hosaMNCM*.pQ.cEl
```
Try it online [here](https://pyth.herokuapp.com/?code=hosaMNCM%2A.pQ.cEl&input=%5B7%2C%2011%2C%2014%5D%0A%5B2%2C%2010%2C%2011%2C%2018%5D&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=hosaMNCM%2A.pQ.cEl&test_suite=1&test_suite_input=%5B1%2C%204%5D%0A%5B2%2C%2010%2C%2011%5D%0A%5B7%2C%2011%5D%0A%5B2%2C%2010%2C%2011%5D%0A%5B7%2C%2011%2C%2014%5D%0A%5B2%2C%2010%2C%2011%2C%2018%5D&debug=0&input_size=2).
```
hosaMNCM*.pQ.cEl Implicit: Q=evaluated 1st input, E=evaluated 2nd input
l Length of 1st input (trailing Q inferred)
.cE All combinations of 2nd input of the above length
.pQ All permutations of 1st input
* Cartesian product
CM Transpose each of the above
o Order the above using:
aMN Take the absolute difference of each pair
s ... and take their sum
h Take the first element of the sorted list, implicit print
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
yn&Y@yy&1ZP&X<Y)
```
Inputs are `X`, then `Y`.
The matching is output with the first values of each pair (that is, `X`) in the first line, and the second values of each pair in the second line.
[Try it online!](https://tio.run/##y00syfn/vzJPLdKhslLNMCpALcImUvP//2hzBUPDWK5oIwVDAxALAA) Or [verify all test cases](https://tio.run/##y00syflvbKX0vzJPLdKhslLNMCpALcImUvO/QXKEy/9oQx0Fk1iuaCMdBUMDIDYEss0hlBFQBCoAkgBiFIVAbBELAA).
### Explanation
```
y % Implicit inputs: X, Y. Duplicate from below
% STACK: [7 11], [2 10 11], [7 11]
n % Number of elements
% STACK: [7 11], [2 10 11], 2
&Y@ % Variations without repetition
% STACK: [7 11], [2 10; 2 11; 10 2; 10 11; 11 2; 11 10]
yy % Duplicate top two elements
% STACK: [7 11], [2 10; ...; 11 10], [7 11], [2 10; ...; 11 10]
&1ZP % Compute cityblock distance between rows of the two input matrices
% STACK: [7 11], [2 10;...; 11 10], [6 5 12 3 13 5]
&X< % Argmin (first index of occurrences of the minimum)
% STACK: [7 11], [2 10; 2 11; 10 2; 10 11; 11 2; 11 10], 4
Y) % Row indexing. Implicit display
% STACK: [7 11], 10 11]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (10?) 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
10 bytes if just the elements of Y are required (see comments) - not sure if it's allowed by spec yet though (and maybe it shouldn't be since other answers already implement this detail).
This may be achieved [by removing the trailing `⁸ż`](https://tio.run/##y0rNyan8/9/n6ORkh4e7FgYfWnp43qPGHQ93LPr//3@0uY6CoSEQm8T@jzYC0gZQvkUsAA "Jelly – Try It Online").
```
Lœc@ạS¥Þ⁸Ḣ⁸ż
```
A dyadic link accepting X on the left and Y on the right.
(`œc⁹L¤ạS¥ÞḢż@` and the 10 byte `œc⁹L¤ạS¥ÞḢ` do the same with Y on the left and X on the right).
**[Try it online!](https://tio.run/##y0rNyan8/9/n6ORkh4e7FgYfWnp43qPGHQ93LAKSR/f8//8/2lxHwdAQiE1i/0cbAWkDKN8iFgA "Jelly – Try It Online")**
### How?
```
Lœc@ạS¥Þ⁸Ḣ⁸ż - Link: sorted list of integers X, sorted list of integers Y
L - length
@ - with swapped arguments:
œc - combinations (chosen as if picked left-to-right
- e.g. [2,5,7,9] œc 2 -> [[2,5],[2,7],[2,9],[5,7],[5,9],[7,9]] )
⁸ - chain's left argument (to be on right of the following...)
Þ - sort by:
¥ - last two links as a dyad:
ạ - absolute difference (vectorises)
S - sum
Ḣ - head (since sorted this is just the first minimal choices from Y)
⁸ - chain's left argument
ż - zip with (the chosen Y elements)
```
[Answer]
# JavaScript (ES7), 100 bytes
New here; any tips/corrections would be appreciated! A previous attempt overlooked complications with sorting an array containing a `NaN` value, so hopefully I haven't missed anything this time.
```
(x,y,q=Infinity)=>y.map((u,j)=>(p=0,s=x.map((t,i)=>(u=y[i+j],p+=(t-u)**2,[t,u])),p)<q&&(q=p,r=s))&&r
```
Expects two arguments as *X*, *Y*, respectively.
[Try it online!](https://tio.run/##dY3BboMwEETvfIVPyE4WJ0SV2kO3934D8sHCUBkR2@Algq@nBg5VWnWlkXbnaXY6/dCxHm2gwnnTrC2ufIYFBvx0rXWWFoEfi7zrwPkEXTp4wCtEnA@PwG7ehEtlz52CcEZOxSROpxtUBJMSAoJ4H/KcDxhgxChEno8rIZdSzilbexd938jef/H2MEWWXS6Mmkis1rGJLIz@YU1jMuJVCexFAdunugErr0mlEht73Vf4nyVt4R@W9KaOPm2MJeud7vfq@KcsBX79fMJF@cTXbw "JavaScript (Node.js) – Try It Online")
Appears to be similar to [@Arnauld's solution](https://codegolf.stackexchange.com/a/167749/81410)
# Explanation
Relies on the fact that given *X*, *Y* are sorted, there exists a solution of
minimum cost matches where if all pairs are arranged to preserve the order of
elements of *X*, all *Y* elements in the arrangement also preserve their order.
```
(x, y, q = Infinity) =>
y.map((u, j) => // iterate over indices of y
(
p=0,
s=x.map((t, i) => ( // map each element of x to...
u = y[i+j], // an element of y offset by j
p += (t-u)**2, // accumulate the square of the difference
[t, u] // new element of s
)),
p
) < q // if accumulated cost less than previous cost...
// (if p is NaN, any comparison will return false and short circuit)
&& (q=p, r=s) // save cost, pair values respectively
) && r // return lowest-cost pairs
```
] |
[Question]
[
Given multiple sets, e.g. `s1={2,3,7}`, `s2={1,2,4,7,8}` and `s3={4,7}`, a [Venn diagram](https://en.wikipedia.org/wiki/Venn_diagram) visualizes each set by a closed curve and set elements which are either inside or outside the curve's perimeter, depending on whether they are element of the set or not. Because all set elements appear only once in the Venn digram, the curves representing each set need to overlap if an element is present in more than one set. We call each such overlapping a **cell** of the Venn diagram.
This explanation might be a bit confusing, so let's have a look at an example.
### Example
A Venn diagram for sets `s1`, `s2` and `s3` could look like this:

The cells of this Venn diagram are (read from top to bottom, left to right) `{1,8}`, `{2}`, `{7}`, `{4}`, `{3}`, `{}` and `{}`.
In practice, one commonly encounters only Venn diagrams of two or three sets, because the representation of Venn diagrams of four or more sets is not very clear. However they do exist, e.g. for six sets:

CC BY-SA 3.0, <https://commons.wikimedia.org/w/index.php?curid=1472309>
### The Task
Given a non-empty set of sets of positive integers in any reasonable representation, return the set of cells of the input sets' Venn diagram. Specifically, **no** graphical representation is needed.
* You may write a full program or a function.
* You may return as many empty sets as there are empty cells (i.e. a *list* of all cells) instead of just one empty set (i.e. the *set* of cells).
* Some reasonable ways of input for the above example include but are not limited to `{{2,3,7},{1,2,4,7,8},{4,7}}`, `[[2,3,7],[1,2,4,7,8],[4,7]]`, `"2,3,7;1,2,4,7,8;4,7"` or `"2 3 7\n1 2 4 7 8\n4 7"`. If in doubt whether your chosen input format is acceptable, feel free to ask in a comment.
* Your output format should match your input format, if possible. Note that this rule requires your format to be able to unambiguously display empty sets.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to use as few bytes as possible in the language of your choice. In order to encourage competition per language instead of between languages, I won't accept an answer.
### Test Cases
Here are some inputs along with possible outputs:
```
input -> output
{{2,3,7},{1,2,4,7,8},{4,7}} -> {{1,8},{2},{7},{4},{3},{}} (or {{1,8},{2},{7},{4},{3},{},{}})
{{1,2,3},{4,5,6},{7,8,9}} -> {{1,2,3},{4,5,6},{7,8,9},{}}
{{}} -> {{}}
{{1,2,3},{1,2}} -> {{1,2},{3},{}}
{{4,3,8},{1,2,9,3},{14,7,8,5},{6,11,3,8},{10},{9,4,3,7,10}} -> {{6,11},{10},{4},{3},{8},{5,14},{1,2},{9},{7},{}}
{{2,3,4,7},{},{1,3,7,5,6},{2,3,7,5},{7,2,4,3,6},{1,4,5}} -> {{},{4},{2},{7,3},{1},{6},{5}}
{{1,2,3,4},{1,2,5,6},{1,3,5,7}} -> {{4},{3},{2},{1},{6},{5},{7}}
```
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
An anonymous function taking a list of lists of integers and returning a similar list.
Use as `(foldr(\x r->(x\\(id=<<r)):([intersect x,(\\x)]<*>r))[])[[1,2,3],[1,2]]`.
```
import Data.List
foldr(\x r->(x\\(id=<<r)):([intersect x,(\\x)]<*>r))[]
```
[Try it online!](https://tio.run/nexus/haskell#VY4xb4MwEIX3/AoUdbCbi1UIgYCAqUulbh1tD1aA1FIwkXFV/j09jnbo4rvn7967W@zwGH2IXk0w4t1OYdfX/XhvPVNz5I8Nm5Vitq2rynNeMmld6PzUXUM0A1Nq5rp6bhBJvQzGupq4uYanL3e3rpvEYB6MHQ575fZcTJ/jt@gF851py/IjeOtux0bKN3TdOq8154Jsi5QJnCDXIGNIIIUcLthj1Xon6e9E@gwZVqRQEPmHsZJOMeryG1VshBLhjG0GcfzHX/ApYB3PAcXqXc9I6RAKWMm2M9l62p6QJ6MJvAmNPw "Haskell – TIO Nexus")
# How it works
* Uses the set-like operations `\\` (difference) and `intersect` from `Data.List`.
* Folds the list of "sets" (represented as lists) into a list of cells, starting with the empty list `[]`.
* `x` is the current set to be added to the diagram, and `r` is the list of cells already constructed.
+ `x\\(id=<<r)` is the subset of elements of `x` that are not in any of the already constructed cells.
+ `[intersect x,(\\x)]<*>r` splits up each cell in `r` according to whether its elements are in `x` or not.
* Most definitely does *not* attempt to merge empty cells, so there are quite a bit of those in the output.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 17 bytes
```
FṀ‘³iþ¬Ḅµ;ṀḶ$ĠṖṖ€
```
[Try it online!](https://tio.run/nexus/jelly#@@/2cGfDo4YZhzZnHt53aM3DHS2HtloDhR7u2KZyZMHDndOA6FHTmv@H249Oerhzxv//0dFGOsY65rE60YY6RjomOuY6hoZADpARGwsA "Jelly – TIO Nexus")
Function submission (because the format Jelly prints lists in by default doesn't round-trip – it can't read its own output format – but a function inputs and outputs in the same format). The TIO link contains a footer that runs the function and prints its output in the same format that input is parsed.
## Explanation
```
FṀ‘³iþ¬Ḅµ;ṀḶ$ĠṖṖ€
FṀ‘ Find the largest number that appears in any of the input sets, + 1
³ þ For each number from 1 to that number, and each of the input sets
i ¬ find whether the number is missing from the set
Ḅ Convert the list of missing sets into a single number using binary
; Append
µ ṀḶ$ all numbers from 0 to the maximum value minus 1
Ġ Group indexes by values
ṖṖ€ Delete the last group and last element of other groups
```
The requirement that we output at least one empty set if not all the Venn diagram sections are used manages to take up over half the program here (it's responsible for the `’` that makes sure we have at least one group for non-matching elements, allowing us to keep track of how many sets there were originally, plus the last nine bytes of the source code except for the `Ġ`). The basic way in which we implement it is to ensure that all the 2^*n* Venn diagram subsets have at least one entry, by adding a dummy entry that will fill the "in no sets" section and (later) a dummy entry to each other section, then `Ġ` will output a group for each subset, which we can remove using `ṖṖ€`.
[Answer]
# Perl 5, 79 bytes
```
sub{for$.(0..@_){$x{$_}+=2**$.for@{$_[$.]}};push@{$h{$x{$_}}},$_ for keys%x;%h}
```
Takes input as a list of anonymous arrays like ([2,3,7],[1,2,4,7,8],[4,7]). Outputs a hash where the keys are labels and the values are anonymous arrays corresponding to the output sets.
As part of a full program:
```
*x=
sub{for$.(0..@_){$x{$_}+=2**$.for@{$_[$.]}};push@{$h{$x{$_}}},$_ for keys%x;%h};
%x=x([2,3,7],[1,2,4,7,8],[4,7]);
print"Set $_:@{$x{$_}}\n"for keys%x;
```
Explanation:
Gives each set an integer as a label, `$.`. Creates a hash that stores an integer for each unique element `$_`. Adds `2**$.` for each set that `$_` appears in, effectively making a binary map showing what sets each element appears in. Finally, makes an anonymous array for each cell of the Venn diagram and pushes the elements appearing in the corresponding sets to the array. So each element of each array exists in the same sets and thus the same cell of the Venn diagram.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
m-@Fds-Qdty
```
[Test suite.](http://pyth.herokuapp.com/?code=m-%40Fds-Qdty&test_suite=1&test_suite_input=%5B%5B2%2C3%2C7%5D%2C%5B1%2C2%2C4%2C7%2C8%5D%2C%5B4%2C7%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%2C%5B7%2C8%2C9%5D%5D%0A%5B%5B%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B1%2C2%5D%5D%0A%5B%5B4%2C3%2C8%5D%2C%5B1%2C2%2C9%2C3%5D%2C%5B14%2C7%2C8%2C5%5D%2C%5B6%2C11%2C3%2C8%5D%2C%5B10%5D%2C%5B9%2C4%2C3%2C7%2C10%5D%5D%0A%5B%5B2%2C3%2C4%2C7%5D%2C%5B%5D%2C%5B1%2C3%2C7%2C5%2C6%5D%2C%5B2%2C3%2C7%2C5%5D%2C%5B7%2C2%2C4%2C3%2C6%5D%2C%5B1%2C4%2C5%5D%5D&debug=0)
## How it works
Each region of the Venn diagram represents elements that are in [certain combinations of the sets] but not in [the other sets].
So, we generate all the possible combinations (and remove the empty combinations) by finding the power set of the input.
For each combination generated, we find the intersection of the sets in the combination, and filter out the elements which are in the other sets.
```
m-@Fds-Qdty input as Q
y power set
t remove the first one (empty combination)
m for each combination d:
@Fd find the intersection of all the sets in d
- filter out those who are in
s the union of
-Qd the sets not in the combination
(input minus combination)
```
[Answer]
## JavaScript (ES6), 123 bytes
```
a=>a.map((b,i)=>b.map(e=>m[e]|=1<<i),m=[])&&[...Array(1<<a.length)].map((_,i)=>m.map((e,j)=>e==i&&j).filter(j=>j)).slice(1)
```
] |
[Question]
[
# Definition
A number is positive if it is greater than zero.
A number (`A`) is the divisor of another number (`B`) if `A` can divide `B` with no remainder.
For example, `2` is a divisor of `6` because `2` can divide `6` with no remainder.
# Goal
Your task is to write a program/function that takes a positive number and then find all of its divisors.
# Restriction
* You may not use any built-in related to *prime* **or** *factorization*.
* The complexity of your algorithm must **not exceed O(sqrt(n))**.
# Freedom
* The output list may contain duplicates.
* The output list does not need to be sorted.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins.
# Testcases
```
input output
1 1
2 1,2
6 1,2,3,6
9 1,3,9
```
[Answer]
# PostgreSQL, 176 bytes
```
WITH c AS(SELECT * FROM(SELECT 6v)t,generate_series(1,sqrt(v)::int)s(r)WHERE v%r=0)
SELECT string_agg(r::text,',' ORDER BY r)
FROM(SELECT r FROM c UNION SELECT v/r FROM c)s
```
`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8206/0)**`
Input: `(SELECT ...v)`
How it works:
* `(SELECT ...v)` - input
* `generate_series(1, sqrt(v)::int)` - numbers from 1 to sqrt(n)
* `WHERE v%r=0` -filter divisors
* wrap with common table expression to refer twice
* `SELECT r FROM c UNION SELECT v/r FROM c` generete rest of divisors and combine
* `SELECT string_agg(r::text,',' ORDER BY r)` produce final comma separated result
---
Input as table:
```
WITH c AS(SELECT * FROM i,generate_series(1,sqrt(v)::int)s(r)WHERE v%r=0)
SELECT v,string_agg(r::text,',' ORDER BY r)
FROM(SELECT v,r FROM c UNION SELECT v,v/r FROM c)s
GROUP BY v
```
`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/56100/1/0)**`
Output:
```
╔═════╦════════════════╗
║ v ║ string_agg ║
╠═════╬════════════════╣
║ 1 ║ 1 ║
║ 2 ║ 1,2 ║
║ 6 ║ 1,2,3,6 ║
║ 9 ║ 1,3,9 ║
║ 99 ║ 1,3,9,11,33,99 ║
╚═════╩════════════════╝
```
[Answer]
# C#6, 75 bytes
```
string f(int r,int i=1)=>i*i>r?"":r%i==0?$"{i},{n(r,i+1)}{r/i},":n(r,i+1);
```
Based on the C# solution of downrep\_nation, but recursive and golfed further down utilizing some new features from C#6.
Basic algorithm is the same as the one presented by downrep\_nation. The for-loop is turned to a recursion, thus the second parameter. recursion start is done by the default parameter, thus the function is called with the required single starting-number alone.
* using expression based functions without a block avoids the return statement
* string interpolation within ternary operator allows to join string concatenation and conditions
As most answers here (yet) do not follow the exact output format from the examples, I keep it as it is, but as a drawback the function includes a single trailing comma at the result.
[Answer]
# [R](https://www.r-project.org/), ~~36~~ 31 bytes
```
n=scan();c(d<-1:n^.5,n/d)^!n%%d
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOlkjxUbX0CovTs9UJ08/RTNOMU9VNeW/peV/AA "R – Try It Online")
-5 bytes thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder)
[Answer]
# Matlab, 48 bytes
```
n=input('');a=1:n^.5;b=mod(n,a)<1;[a(b),n./a(b)]
```
[Answer]
# J, 26 bytes
```
(],%)1+[:I.0=]|~1+i.@<.@%:
```
## Explanation
```
(],%)1+[:I.0=]|~1+i.@<.@%: Input: n
%: Sqrt(n)
<.@ Floor(Sqrt(n))
i.@ Get the range from 0 to Floor(Sqrt(n)), exclusive
1+ Add 1 to each
] Get n
|~ Get the modulo of each in the range by n
0= Which values are equal to 0 (divisible by n), 1 if true else 0
[:I. Get the indices of ones
1+ Add one to each to get the divisors of n less than sqrt(n)
% Divide n by each divisor
] Get the divisors
, Concatenate them and return
```
[Answer]
# JavaScript (ES6) - 48 bytes
```
f=n=>[...Array(n+1).keys()].filter(x=>x&&!(n%x))
```
Not very efficient but works! Example below:
```
let f=n=>[...Array(n+1).keys()].filter(x=>x&&!(n%x));
document.querySelector("input").addEventListener("change", function() {
document.querySelector("output").value = f(Number(this.value)).join(", ");
});
```
```
Divisors of <input type="number" min=0 step=1> are: <output></output>
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 12 bytes
```
tX^:\~ftGw/h
```
The approach is similar to that in [@flawr's answer](https://codegolf.stackexchange.com/a/78984/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=dFheOlx-ZnRHdy9o&input=Ng)
### Explanation
```
t % take input N. Duplicate.
X^: % Generate range from 1 to sqrt(N)
\ % modulo (remainder of division)
~f % indices of zero values: array of divisors up to sqrt(N)
tGw/ % element-wise divide input by those divisors, to produce rest of divisors
h % concatenate both arrays horizontally
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 12 bytes
Code:
```
ÐtLDŠÖÏDŠ/ï«
```
Explanation:
```
Ð # Triplicate input.
tL # Push the list [1, ..., sqrt(input)].
D # Duplicate that list.
Š # Pop a,b,c and push c,a,b.
Ö # Check for each if a % b == 0.
Ï # Only keep the truthy elements.
D # Duplicate the list.
Š # Pop a,b,c and push c,a,b
/ï # Integer divide
« # Concatenate to the initial array and implicitly print.
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RHRMwqnDlsKuc8OPRMK5cy_Dr8Kr&input=Ng).
[Answer]
## Python 2, 64 bytes
```
lambda n:sum([[x,n/x]for x in range(1,int(n**.5+1))if n%x<1],[])
```
This anonymous function outputs a list of divisors. The divisors are computed by trial division of integers in the range `[1, ceil(sqrt(n))]`, which is `O(sqrt(n))`. If `n % x == 0` (equivalent to `n%x<1`), then both `x` and `n/x` are divisors of `n`.
[Try it online](http://ideone.com/fork/rzMwmj)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
½Rḍ³Tµ³:;
```
As the other answers, this is **O(√n)** if we make the (false) assumption that integer division is **O(1)**.
### How it works
```
½Rḍ³Tµ³:; Main link. Argument: n
½ Compute the square root of n.
R Construct the range from 1 to the square root.
ḍ³ Test each integer of that range for divisibility by n.
T Get the indices of truthy elements.
µ Begin a new, monadic chain. Argument: A (list of divisors)
³: Divide n by each divisor.
; Concatenate the quotients with A.
```
[Try it online!](http://jelly.tryitonline.net/#code=wr1S4biNwrNUwrXCszo7&input=&args=OQ)
[Answer]
# Javascript, 47 bytes
```
d=(n,f=1,s='')=>n==f?s+n:d(n,f+1,n%f?s:s+f+',')
```
[Answer]
# Mathematica, 50 bytes
Similar to @flawr's [solution](https://codegolf.stackexchange.com/questions/78982/find-the-positive-divisors/78984#78984).
Performs trail division for *x* from 1 up to the square root of *n* and if divisible, saves it to a list as *x* and *n* / *x*.
```
(#2/#)~Join~#&@@{Cases[Range@Sqrt@#,x_/;x∣#],#}&
```
* Note that `∣` requires 3 bytes to represent in UTF-8, making the 48 character string require 50 bytes in UTF-8 representation.
## Usage
```
f = (#2/#)~Join~#&@@{Cases[Range@Sqrt@#,x_/;x∣#],#}&
f[1]
{1, 1}
f[2]
{2, 1}
f[6]
{6, 3, 1, 2}
f[9]
{9, 3, 1, 3}
```
[Answer]
## JavaScript (ES6), ~~66~~ 62 bytes
```
f=(n,d=1)=>d*d>n?[]:d*d-n?n%d?f(n,d+1):[d,...f(n,d+1),n/d]:[d]
```
I thought I'd write a version that returned a sorted deduplicated list, and it actually turned out to be 4 bytes shorter...
[Answer]
## C#, 87 bytes
---
**Golfed**
```
String m(int v){var o="1";int i=1;while(++i<=v/2)if(v%i==0)o+=","+i;o+=","+v;return o;}
```
---
[Answer]
# Lua, 83 bytes
```
s=''x=io.read()for i=1,x do if x%i==0 then s=s..i..', 'end end print(s:sub(1,#s-2))
```
I couldn't do better, unfortunately
[Answer]
# [Perl 6](http://perl6.org), 40 bytes
```
{|(my@a=grep $_%%*,^.sqrt+1),|($_ X/@a)}
```
### Explanation:
```
{
# this block has an implicit parameter named $_
# slip this list into outer list:
|(
my @a = grep
# Whatever lambda:
# checks if the block's parameter ($_)
# is divisible by (%%) this lambda's parameter (*)
$_ %% *,
# upto and exclude the sqrt of the argument
# then shift the Range up by one
^.sqrt+1
# (0 ..^ $_.sqrt) + 1
# would be clearer if written as:
# 1 .. $_.sqrt+1
),
# slip this list into outer list
|(
# take the argument and divide it by each value in @a
$_ X/ @a
# should use X[div] instead of X[/] so that it would return
# Ints instead of Rats
)
}
```
### Usage:
```
my &divisors = {|(my@a=grep $_%%*,^.sqrt+1),|($_ X/@a)}
.say for (1,2,6,9,10,50,99)».&divisors
```
```
(1 1)
(1 2 2 1)
(1 2 3 6 3 2)
(1 3 9 3)
(1 2 10 5)
(1 2 5 50 25 10)
(1 3 9 99 33 11)
```
[Answer]
## c#, 87 bytes
```
void f(int r){for(int i=1;i<=Math.Sqrt(r);i++){if(r%i==0)Console.WriteLine(i+" "+r/i);}
```
i do not know if this works for all numbers, i suspect it does.
but the complexity is right, so thats already something isnt it
[Answer]
# Ruby, 56 bytes
```
->n{a=[];(1..Math.sqrt(n)).map{|e|a<<e<<n/e if n%e<1};a}
```
[Answer]
# IA-32 machine code, 27 bytes
Hexdump:
```
60 33 db 8b f9 33 c0 92 43 50 f7 f3 85 d2 75 04
ab 93 ab 93 3b c3 5a 77 ec 61 c3
```
Source code (MS Visual Studio syntax):
```
pushad;
xor ebx, ebx;
mov edi, ecx;
myloop:
xor eax, eax;
xchg eax, edx;
inc ebx;
push eax;
div ebx;
test edx, edx;
jnz skip_output;
stosd;
xchg eax, ebx;
stosd;
xchg eax, ebx;
skip_output:
cmp eax, ebx;
pop edx;
ja myloop;
popad;
ret;
```
First parameter (`ecx`) is a pointer to output, second parameter (`edx`) is the number. It doesn't mark the end of output in any way; one should prefill the output array with zeros to find the end of the list.
A full C++ program that uses this code:
```
#include <cstdint>
#include <vector>
#include <iostream>
#include <sstream>
__declspec(naked) void _fastcall doit(uint32_t* d, uint32_t n) {
_asm {
pushad;
xor ebx, ebx;
mov edi, ecx;
myloop:
xor eax, eax;
xchg eax, edx;
inc ebx;
push eax;
div ebx;
test edx, edx;
jnz skip_output;
stosd;
xchg eax, ebx;
stosd;
xchg eax, ebx;
skip_output:
cmp eax, ebx;
pop edx;
ja myloop;
popad;
ret;
}
}
int main(int argc, char* argv[]) {
uint32_t n;
std::stringstream(argv[1]) >> n;
std::vector<uint32_t> list(2 * sqrt(n) + 3); // c++ initializes with zeros
doit(list.data(), n);
for (auto i = list.begin(); *i; ++i)
std::cout << *i << '\n';
}
```
The output has some glitches, even though it follows the spec (no need for sorting; no need for uniqueness).
---
Input: 69
Output:
```
69
1
23
3
```
The divisors are in pairs.
---
Input: 100
Output:
```
100
1
50
2
25
4
20
5
10
10
```
For perfect squares, the last divisor is output twice (it's a pair with itself).
---
Input: 30
Output:
```
30
1
15
2
10
3
6
5
5
6
```
If the input is close to a perfect square, the last pair is output twice. It's because of the order of checks in the loop: first, it checks for "remainder = 0" and outputs, and only then it checks for "quotient < divisor" to exit the loop.
[Answer]
# SmileBASIC, 49 bytes
```
INPUT N
FOR D=1TO N/D
IF N MOD D<1THEN?D,N/D
NEXT
```
Uses the fact that `D>N/D` = `D>sqrt(N)` for positive numbers
[Answer]
# C, ~~87~~ 81 bytes
Improved by [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), 81 bytes:
```
i,j;main(n,b)int**b;{for(;j=sqrt(n=atoi(b[1]))/++i;n%i||printf("%u,%u,",i,n/i));}
```
[Try it online!](https://tio.run/##DcpBCoQwDADAvwhCohHx4iX4kmUPbaES0ai1ntSvb1aY44RmDMFMaOLFiYKSR9FcVZ6vuCbgaTj2lEEHl1cB/@m@iG1dC2sp972lN0coypNeBQlpK4j8mFn/C3F242HNvPwB)
---
My original answer, 87 bytes:
```
i;main(int n,char**b){n=atoi(b[1]);for(;(int)sqrt(n)/++i;n%i?:printf("%u,%u,",i,n/i));}
```
Compile with `gcc div.c -o div -lm`, and run with `./div <n>`.
---
*Bonus:* An even shorter variant with O(n) time complexity and hardcoded `n` (46 bytes + length of `n`):
```
i,n=/*INSERT VALUE HERE*/;main(){for(;n/++i;n%i?:printf("%u,",i));}
```
---
*Edit: Thank you to @Sriotchilism O'Zaic for pointing out that inputs should not be hardcoded, I modified the main submission to take the input via argv.*
[Answer]
# APL(NARS), 22 chars, 44 bytes
```
{v∪⍵÷v←k/⍨0=⍵∣⍨k←⍳⌊√⍵}
```
test:
```
f←{v∪⍵÷v←k/⍨0=⍵∣⍨k←⍳⌊√⍵}
f 1
1
f 2
1 2
f 6
1 2 6 3
f 9
1 3 9
f 90
1 2 3 5 6 9 90 45 30 18 15 10
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 40 bytes
Just providing an updated C# answer
```
n=>Enumerable.Range(1,n).Where(x=>n%x<1)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXouPpmleam1qUmJSTCuLb2SmkKdj@z7O1Q4jrBSXmpadqGOrkaeqFZ6QWpWpU2NrlqVbYGGr@t@YKL8osSfXJzEvVKC4pysxL1/PKz8zTUNJR0lFI0zDU1NQkoMSIsBIzwkosQUr@AwA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Inspired by [this](https://codegolf.stackexchange.com/q/59299/43319) excellent challenge (from which the bulk of this text is blatantly duct-taped) – and my highschool philosophy [project](https://en.wikipedia.org/wiki/Fuzzy_logic#Define_with_multiply)...
I define the following operators:
**Fuzzy Conjunction** *a* ×F *b* is *a* × *b*
**Fuzzy Division** *a* ÷F *b* is *a* ÷ *b*
**Fuzzy Negation** –F *b* is 1 – *b*
**Fuzzy Disjunction** *a* +F *b* is –F ((–F *a*) ×S (–F *b*) which is equivalent to 1 – (1 – *a*) × (1 – *b*)
With all this in mind, create an interpreter that will evaluate infix expressions that use the following operators (i.e., `a + b`, not `a b +` or `+ a b`). Alternatively, extend the language of your choice to include the notation.
```
× Multiplication
÷ Division
– Subtraction
+ Addition
×F Fuzzy Conjunction
÷F Fuzzy Division
–F Fuzzy Negation
+F Fuzzy Disjunction
```
Notice that *a* -F *b* is **not** defined. You may leave it undefined, or define it as you see fit.
You may substitute `*` for `×` and/or `-` for `–` and/or `/` for `÷`, (or use whatever single symbols your language uses for the four basic arithmetic operations) as long as you stay consistent: You may not use `*` and `×F` together.
You may choose to require or prohibit spacing around tokens.
You may choose any of the following rules for order of precedence:
1. As normal mathematics, and *each* Fuzzy operator has a *higher* order precedence than their normal counterpart.
2. As normal mathematics, and *each* Fuzzy operator has a *lower* order precedence than their normal counterpart.
3. As normal mathematics, and the Fuzzy operators *all* have *higher* order precedence than all the normal operators.
4. As normal mathematics, and the Fuzzy operators *all* have *lower* order precedence than all the normal operators.
5. Strict left-to-right.
6. Strict right-to-left.
7. Normal and *Fuzzy* operators have the *same* precedence and are evaluated left-to-right.
8. Normal and *Fuzzy* operators have the *same* precedence and are evaluated right-to-left.
Leave a comment if you desire another precedence rule.
Test cases using precedence rule 6:
```
> 5 +F 10 + 3
-47 // 1 - (1 - 5) × (1 - 13)
> 10 × 2
20 // 2 × 10
> 10 ×F 1
10 // 1 × 10
> 23 × 3
69 // 23 × 3
> 123 ×F 2 × 3
738 // 123 × 2 × 3
> 5 + 3 +F 2
4 // 5 + 1 - (1 - 3) × (1 - 2)
> 150 ÷F 3
50 // 150 ÷ 3
> 150 ÷ 53
2.83 // 150 ÷ 53
> -F -F -F 0
1 // 1 - (1 - (1 - 0))
> -500
-500 // - 500
> -F 6 - 1
-4 // 1 - 5
> 12 +F 633 ×F 3
-20877 // 1 - (1 - 12) × (1- 633 × 3)
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
⁾-Cyœṣ⁾+Fj“+_×ɗ”ḟ”FV
```
[Try it online!](https://tio.run/##y0rNyan8//9R4z5d58qjkx/uXAxkartlPWqYox1/ePrJ6Y8a5j7cMR9IuoX9f7h7i/WjpjWPGrepHG4HMo5Oerhzxv//hgYK2grGCtpuCqZcQPbh6QpGENpNwZDLyBgkYMxlBKYggkbGXGDlRkB9QC2mQLXb3YBqICwFU2MuAwVdNwjiijc1MOAyU4hXMATxzIwhZoD1GxoBAA "Jelly – Try It Online")
~~To quote [myself](https://chat.stackexchange.com/transcript/message/56585104#56585104):~~
>
> Well, it's disgustingly hacked together, but it works :D
>
>
>
Well, it's much more elegantly hacked together.
Haha, beating QuadR!
Jelly doesn't like strings. For a more elegant solution that exploits Jelly natural infix notation, see below. Takes input from ARGV. The Footer in the link takes a multiline string, splits it on newlines, runs each line and returns a list of results.
This uses precedence rule 5, which is consistent (I believe) with Jelly's parsing rules in this case, and we use `_` for regular subtraction and for regular negation.
## How it works
```
⁾-Cyœṣ⁾+Fj“+_×ɗ”ḟ”FV - Main link. Takes an expression E on the left
⁾-C - Yield ["-", "C"]
y - Replace all occurrences of "-" with "C"
⁾+F - Yield ["+", "F"]
œṣ - Split on "+F"
“+_×ɗ” - Yield "+_×ɗ"
j - Join on "+_×ɗ"
ḟ”F - Remove any leftover "F"s
V - Execute as Jelly code
```
### Why `C` and `+_×ɗ`?
First, `C`. `C` is Jelly's builtin for \$1 - x\$
Now, `+_×ɗ`. The `ɗ` at the end tells Jelly to consider the previous 3 atoms as a single link, acting similarly to `(...)` in other languages. The three atoms implement the formula
$$\begin{align}
1 - (1-a)(1-b) & = 1 - (1-a-b+ab) \\
& = (a+b)-(a\times b)
\end{align}$$
```
+_× - Takes a on the left and b on the right
+ - a+b
× - a×b
_ - a+b - a×b
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), 9 + 8 = 17 bytes
```
×
÷
C
+_×
```
[Try it online!](https://tio.run/##y0rNyan8///wdK7D27mcubTjD0//b6xgcrRBwUhBW8H0PwA "Jelly – Try It Online") or [Try it online!](https://tio.run/##NYy9DcJQDIR7T3F9hOSfvAeIkkFS0aAsQMcWGYAhUiLxYK4XxxaF7/Od7Lvf5vnR20JtpSsNU1u6MAYYxt8Thdy0BbpTPBBS2wMjDWSoRnmv/uk/haHuLLa2ohgx7Pv@Dx0KM1VMkLDVsihLRHv5vHBBDT2GnkLPocIJSWjCEmMiG8Qr@gY "Jelly – Try It Online")
Slightly convoluted here, but bear with me. This uses the
>
> Alternatively, extend the language of your choice to include the notation.
>
>
>
rule to avoid any parsing or complicated stuff that Jelly isn't too good at. Instead we define 4 functions `1ŀ`, `2ŀ`, `3Ŀ` and `4ŀ` (Conjuction, Division, Negation and Disjuction respecitively), which "extends" Jelly to include the fuzzy operations by including the above 9 bytes before any code. I'm counting my byte count here as 9 bytes for the code above plus 8 bytes for the names of the functions.
This uses precedence rule 5, which is consistent (I believe) with Jelly's parsing rules in this case, and we use `_` for regular subtraction.
In the test suite above, we include our 4 functions in the header, then execute the lines of test cases with the Footer.
## How it works
The names of the functions are fairly easy to understand. Jelly allows you to call each line as a function using the `Ŀ` (call as monad) or the `ŀ` (call as dyad) quicks, which is what we use here.
`1ŀ` and `2ŀ` are obvious how they work. `3Ŀ` simply takes advantage of Jelly's builtin for \$1 - x\$: `C`. `4ŀ` works the same way as specified above, but doesn't need the `ɗ` for grouping
[Answer]
# CJam, 45 bytes
```
q"-F"/"1 -"*"+F"/"1Y$-*+"*'F-S/)d\2/'\f*W%S*~
```
Uses precedence rule 6: strictly right-to-left. It expects ASCII input.
[Take it for a spin!](http://cjam.aditsu.net/#code=q%22-F%22%2F%221%20-%22*%22%2BF%22%2F%221Y%24-*%2B%22*'F-S%2F)d%5C2%2F'%5Cf*W%25S*~&input=12%20%2BF%20633%20*F%203)
## Explanation
Read input, and perform the following transformations in order:
```
"-F" to "1 -"
"+F" to "1Y$-*+"
"F" to ""
```
Then split over spaces (`S/`). Extract the rightmost element and convert it to a double (`)d`). Then take pairs from the rest of the list (`\2/`), join them all by `\` (`'\f*`) and evaluate the resulting strings as CJam code in reverse order (`W%S*~`).
For example, it converts `5 +F 10 + 3`
* to `5 1Y$-*+ 10 + 3` in the first step,
* then to `3 [["10" "+"] ["5" "1Y$-*+"]]`,
* then to `3 ["10\+" "5\1Y$-*+"]`,
* then to `3 10\+ 5\1Y$-*+`, which is CJam code that computes the right answer, `-47`.
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 21 bytes
```
⍎⍵
\+F
-F
F
(+-×)
1-
```
[Try it online!](https://tio.run/##KyxNTCn6//9Rb9@j3q1cMdpuXLpuXG5cGtq6h6drchnqcv3/b6qg7aZgaKCgrWCs8Ki7BcQ8PF3BCMEGyoI5pmAlQMVQOVOg5HY3mC4jkIyZsTFYgzEA "QuadR – Try It Online") [or a version that accepts newline-separated test cases.](https://tio.run/##KyxNTCn6//9Rb9@j3iWGj/qmuvmGPOrdyhWj7cal68blxqWhrXt4uiaXoS7X//@mCtpuCoYGCtoKxlxA6vB0BSMIDRTlMgUJgxQAxUyBgtvdQKqMQCJmxsZgRcYA)
QuadR port of [Razetime's APL answer](https://codegolf.stackexchange.com/a/216446/78410), as it happens to be a set of `⎕R` substitution followed by post-processing code. I moved `⍵~'F'` part into the regex substitution `'F' → ''`, which saves a byte. It has no problem running multiple test cases separated by `⋄`, but it does have some problem with newlines (which can be fixed by changing the first line to `⍎⍤1⎕FMT⍵`).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38 37 35~~ 30 bytes
```
⍎'F'~⍨'\+F' '-F'⎕R'(+-×)' '1-'
```
[Try it online!](https://tio.run/##XZG/SgNBEMb7PMV0m@Nc2T/Zu7MWFm0TS5uAxCagrY2NkEK4oIWksrcQbAR78yb7IufMzu5e4nEsw@xvvplvdnm/ljcPy/Xd7TCEfiu8eAz9h7iuvQAhvQjbt7mY1nK/qzChpRhWYfOCZHh@Cv1n6L9/v2zYvCK3mJ/jeXVxuRhWIBzUHrSCGqyASejfQc5aoO8ENEiY0uEq2O841LaaYBlWYMakEqMglRhKa1UQ1E6MLoweGWMpzp2bsyLD@SgTY8/KmWxtl8UYNYV3ZIVM5eFmkFXpqniyoyfDlhwO/ONLDzcOHG/SOBy7TJnTzh5RLmLSA/8q2wf4v9V4qCo2l05lkkImcfFKJbWGdl9e6FDL8ZbIcmN5V@Upjera9qipNsm3TDQu4g8 "APL (Dyalog Unicode) – Try It Online")
A tacit function which accepts a string.
Evaluation is done as per Rule 6: strict right to left, as per APL's evaluation.
-1 byte from Adám.
-2 more from Adám.
-5 bytes from Bubbler.
## Explanation
```
⍎'F'~⍨'\+F' '-F'⎕R'(+-×)' '1-'
'-F'⎕R '1-' regex replace '-F' with '1-'
'\+F' ⎕R'(+-×)' regex replace '+F' with function to perform 1-((1-x)×(1-y))
'F'~⍨ remove any other Fs
⍎ execute as APL code
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 24 bytes
Saved 3 bytes thanks to [@Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)!
```
F←{⍺←1⋄⍺(×-⍣(2=⍺⍺2)⍺⍺)⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/92AZPWj3l1AyvBRdwuQpXF4uu6j3sUaRrYg4d5dRpoQGkhtrf3/31RB203B0EBBW8GYS9dNAYIMuIAih6cDJbgMTYGs7W4KxgA "APL (Dyalog Unicode) – Try It Online")
Extends the language with a monadic operator `F`. Uses rule 6 (strict right-to-left). This fixes the [issues](https://tio.run/##SyzI0U2pTMzJT///3@1R24TqR727gJTBo@4WDUPdR71bNTVAIlAE4Wkcnq6rrQniRRtBZAxja///NzRQODzdTcGQy9AUyNrupmAMAA) Adám pointed out in the original answer.
`⍺⍺` is the input function (`+`, `-`, `×`, or `÷`), `⍺` is the left argument (`⍺←1` gives it a default value of `1`), and `⍵` is the right argument. `×-⍣(2=⍺⍺2)⍺⍺`, which Adám came up with, is applied to `⍺` and `⍵`. It's equivalent to `(⍺×⍵) -⍣(2=⍺⍺2) (⍺ ⍺⍺ ⍵)`. If `⍺⍺` is `+`, then `2=⍺⍺2` (`2 = +2`) is true. If so, `⍣` subtracts its right argument `⍺+⍵` from its left argument `⍺×⍵` (this is equivalent to `1-(1-⍺)×(1-⍵)`. Otherwise, we just return what's on the right side. If it's multiplication or division, it's the same as normal `×` or `÷`. If it's fuzzy negation, then `⍺` is 1, so it'll be `1-⍵`.
[Answer]
# [Nim](http://nim-lang.org/), 106 bytes
```
type f=float
func`*~`(a,b:f):f=a*b
func`/~`(a,b:f):f=a/b
func`-~`(b:f):f=1-b
func`+~`(a,b:f):f=1- -~a* -~b
```
[Try it online!](https://tio.run/##Vco7DoMwEIThnlNMadaxkL1KCiTugo1YBYlAClKk8dUdHhYizRTf/NPwSmn5vntII@Psl0I@U9dSbJW/hVrKWhpP4dDqT6usZtVs1mTT19IamOhpnZD67jnjDg3F0BGuLHaxjkERyoHAp23Fg/eH0w8 "Nim – Try It Online")
Adds the four operators to Nim. Since operator names can't contain letters, it uses a tilde `~` instead, which I consider a very fuzzy character. Precedence is the same as the corresponding normal operators.
] |
[Question]
[
The [Pauli matrices](http://en.wikipedia.org/wiki/Pauli_matrices) are a set of 2x2 matrices which appear very commonly in quantum physics (no, you don't need to know any quantum physics for this challenge). If we include the identity in the set, the four matrices are:
```
σ0 = σ1 = σ2 = σ3 =
[1 0] [0 1] [0 -i] [1 0]
[0 1] [1 0] [i 0] [0 -1]
```
[Multiplying](http://en.wikipedia.org/wiki/Matrix_multiplication#Matrix_product_.28two_matrices.29) two of these will always give another Pauli matrix, although it may be multiplied by one of the complex phases `1`, `i`, `-1`, `-i`. For instance, `σ1σ3 = -iσ2`.
Your task is to multiply a number of Pauli matrices and return the resulting matrix and phase. Input will be given as a non-empty string of digits `0` to `3` representing the matrices `σ0` to `σ3`. The output should be a string containing a single digit for the resulting matrix, optionally preceded by `i`, `-` or `-i` to indicate the phase (`-` is for `-1`).
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
You must not use any built-in (or 3rd-party) features related to Pauli matrices.
This is code golf, the shortest answer (in bytes) wins.
## Test Cases
```
1 => 1
13 => -i2
000 => 0
123 => i0
03022 => 3
02132230 => -i3
1320130100032 => i2
311220321030322113103 => -2
0223202330203313021301011023230323 => -i0
1323130203022111323321112122313213130330103202032222223 => -1
```
[Answer]
# Python 2, ~~108~~ ~~89~~ ~~87~~ 86 bytes
```
x=y=0
for m in map(int,raw_input()):x+=m*y and(m-y)%3*3/2;y^=m
print"--i"[~x%4::2]+`y`
```
*(Thanks to @grc and @xnor for the help)*
## Explanation
Let's split up the coefficient and the base matrix. If we focus on the base matrix only, we get this multiplication table (e.g. `13` is `-i2`, so we put `2`):
```
0123
0 0123
1 1032
2 2301
3 3210
```
which just happens to be the same thing as doing bitwise xor.
Now let's focus on the coefficients. If we let `0123` denote `1,i,-1,-i` respectively, we get:
```
0123
0 0000
1 0031
2 0103
3 0310
```
For this we first check if either number is 0 by doing `m*y`, taking care of the left column and top row. Adding in `(m-y)%3` then gives:
```
0123
0 0000
1 0021
2 0102
3 0210
```
which is close, except that we have `2` instead of `3`. We account for this by performing `*3/2`.
For indexing, we notice that if we take the string `"--i"` and select every second character starting from indices `0123` we get `"-i","-","i",""`.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 77 bytes
I thought I'd use this opportunity to show off a new Retina feature: multi-stage loops. This should shorten many tasks considerably (especially conditional replacement).
```
ii
-
+`(.)\1|0
(.)-|(\d)(\d)
-$1$3$2
12
i3
23
i1
31
i2
)`(\d)i
i$1
^\D*$
$&0
```
Retina is my own regex-based programming language. The source code can be grouped into stages: each stage consists of two lines where the first contains the regex (and potentially some configuration) and the second line is the replacement string. The stages are then applied to STDIN in order and the final result is printed to STDOUT.
You can use the above directly as a source file with the `-s` command-line switch. However, I'm not counting the switch, because you can also just put each line in a separate file (then you lose 15 bytes for the newlines, but add +15 for the additional files).
## Explanation
The new thing about this solution is the `)` in the penultimate stage. This closes a multi-stage loop. There is no matching `(`, which means that the loop implicitly starts at the first stage. Hence, the first 7 stages are repeated until a full pass through all 7 of them stops changing the result. These 7 stages simply perform various transformations which gradually reduce the number of matrices in the string and combine phases. Once we reach the final result, none of the seven patterns matches any more and the loop ends. Afterwards, we append a 0 if there is no digit in the result yet (as the above stages simply drop all identities, including the result).
Here is what the individual stages do:
```
ii
-
```
Combines all pairs of `i` into `-` to reduce the phase characters.
```
+`(.)\1|0
<empty>
```
Now if there are two consecutive identical characters left, it's either `--` or two identical matrices. In either case, multiplying them gives the identity. But we don't need identities, so we just remove all of them, and the explicit identities (the `0`s) as well. This stage is repeated in itself with `+` until the result stops changing. This ensures that things like `123321` get resolved completely, such that the next step can assume that all pairs of digits are distinct.
```
(.)-|(\d)(\d)
-$1$3$2
```
This is actually two separate transformations in one (for golfitude). Note that if the first alternative matches, `$2` and `$3` are empty, and if the second one matches `$1` is empty. So this can be decomposed into these two steps:
```
(\d)(\d)
-$2$1
```
This just swaps all pairs of digits and adds a minus sign. Since we removed all `0`s and all identical pairs, this will only match `12`, `23`, `31`, `21`, `32`, `13`. This step may seem weird, but it allows me to only check for half of these cases later on, because the ones I can't process then will be swapped here in the next iteration.
The other part of the above stage was:
```
(.)-
-$1
```
This gradually moves `-` signs all the way to the left (one position per iteration). I do this such that ultimately they are all next to each other and get resolved in the earlier step.
```
12
i3
23
i1
31
i2
```
These three stages now simply resolve the three pairs of products. As I said above, this will only catch half of the relevant cases, but the other half will be taken care of in the next iteration, after the previous step swapped all pairs.
```
)`(\d)i
i$1
```
This is the last stage of the loop. It's similar to the one that shifts `-` to the left, except for `i`. The main difference is that this one swaps `i` only with digits. If I used `(.)i` then in cases where I get a `-i` or `i-` the two would be swapped indefinitely and the program wouldn't terminate. So this only swaps them to the right of the `-` signs. This is sufficient - as long as all `-` and `i` appear together at some point, they can be resolved correctly.
```
^\D*$
$&0
```
The final step (outside of the loop). Remember that we always deleted all identities, so if the result is actually the identity (times a phase), then we won't have the required digit in the output any more, so we add it back.
As an example, here are all the intermediate forms of `0223202330203313021301011023230323` (skipping stages that don't perform any changes):
```
0223202330203313021301011023230323
321321312 # Remove identities
-23-31-12-132 # Swap all pairs
-23-31-i3-132 # Resolve 12
-i1-31-i3-132 # Resolve 23
-i1-i2-i3-132 # Resolve 31
-i-1i-2i-3-312 # Move - to the left and swap pairs
-i-1i-2i-3-3i3 # Resolve 12
-i-i1-i2-3-i33 # Move i to the left
-i-i1-i2-3-i # Remove identities
--ii-1i-2-3i # Move - to the left
--ii-i1-2-i3 # Move i to the left
----i1-2-i3 # Resolve ii
i1-2-i3 # Remove identities
i-1-2i3 # Move - to the left
i-1-i23 # Move i to the left
-i-1i-32 # Move - to the left and swap pairs
-i-i1-32 # Move i to the left
--ii-1-23 # Move - to the left and swap pairs
--ii-1-i1 # Resolve 23
----1-i1 # Resolve ii
1-i1 # Remove identities
-1i1 # Move - to the left
-i11 # Move i to the left
-i # Remove identities. Now the loop can't change this any longer.
-i0 # Fix the result by adding in the 0.
```
[Answer]
# Pyth, 47 bytes
I guess this is still golfable. But it beats CJam by a lot.
```
p.U&-=T*q3l{[0bZ)^_1%-Zb3xbZmvdz@+c"i - -i")khT
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=p.U%26-%3DT*q3l%7B%5B0bZ)%5E_1%25-Zb3xbZmvdz%40%2Bc%22i+-+-i%22)khT&input=0223202330203313021301011023230323&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=Fz.z%3DT10p%22+%3D%3E+%22zp.U%26-%3DT*q3l%7B%5B0bZ)%5E_1%25-Zb3xbZmvdz%40%2Bc%22i+-+-i%22)khTk&input=%22Test-Cases%3A%22%0A1%0A13%0A000%0A123%0A03022%0A02132230%0A1320130100032%0A311220321030322113103%0A0223202330203313021301011023230323%0A1323130203022111323321112122313213130330103202032222223&debug=0)
### Explanation
Determining the resulting matrix type is simply xoring all the numbers.
While multiplying 2 matrices `A*B`, the phase changes, if non of the matrices is `σ0` and `A != B`.
```
implicit: T=10, z=input string
mvdz evaluate each char of the input
.U reduce: b=first value, for Y in mvdz[1:]
-=T T -= ...
q3l{[0bZ) (3 == len(set([0,b,Z])))
* ^_1%-Zb3 * (-1)^((Z-b)%3)
& and
xbY update b by (b xor Y)
+c"i - -i")k the list ["i", "-", "-i", ""]
@ hT take the element at index T+1 (modulo wrapping)
p print phase and matrix
```
[Answer]
# CJam, ~~58~~ 56 bytes
I am sure this can be golfed a lot, but here it goes:
```
L'i'-"-i"]q{+:G$i:XA<X{GiB%_2m8%!+m<XB%gX3%3-z*}?s}*\0=o
```
[Try it online here](http://cjam.aditsu.net/#code=L%27i%27-%22-i%22%5Dq%7B%2B%3AG%24i%3AXA%3CX%7BGiB%25_2m8%25!%2Bm%3CXB%25gX3%253-z*%7D%3Fs%7D*%5C0%3Do&input=0223202330203313021301011023230323) or [run the complete suite here](http://cjam.aditsu.net/#code=9%7B%5BL%27i%27-%22-i%22%5DlS%2F0%3D%3AI%7B%2B%3AG%24i%3AXA%3CX%7BGiB%25_2m8%25!%2Bm%3CXB%25gX3%253-z*%7D%3Fs%7D*%5C0%3DI%22%20%3D%3E%20%22%2B%5C%40N%5Do%7D*&input=1%20%3D%3E%201%0A13%20%3D%3E%20-i2%0A123%20%3D%3E%20i0%0A03022%20%3D%3E%203%0A02132230%20%3D%3E%20-i3%0A1320130100032%20%3D%3E%20i2%0A311220321030322113103%20%3D%3E%20-2%0A0223202330203313021301011023230323%20%3D%3E%20-i0%0A1323130203022111323321112122313213130330103202032222223%20%3D%3E%20-1)
] |
[Question]
[
### Challenge: implement calculation of a Delacorte Number in any language. Shortest code wins.
For a given square matrix of distinct integers *1..n²* (possible side length *n* at least between 3 and 27), its Delacorte Number is the sum of the products *gcd(a, b) × distance²(a, b)* for each distinct pair of integers {a, b}.
The following example shows a 3×3 square with a Delacorte Number of 160.
```
3 2 9
4 1 8
5 6 7
```
In this square we have 36 distinct pairs to calculate, for example the pair 4 and 6: *[gcd](http://en.wikipedia.org/wiki/Greatest_common_divisor)(4, 6) × [distance](http://en.wikipedia.org/wiki/Euclidean_distance)²(4, 6) = 4*
Another example square for testing - this has a Delacorte Number of 5957:
```
10 8 11 14 12
21 4 19 7 9
5 13 23 1 16
18 3 17 2 15
24 22 25 6 20
```
Delacorte Numbers are taken from [this programming contest](http://azspcs.com/Contest/DelacorteNumbers) - see there for further details... The contest ended in January 2015. It was great fun!
### Rules:
Necessary line breaks count as 1 char. You may post your golfed solution with line breaks, but they are only counted if necessary in that language.
You can choose how to handle input and output and you don't have to count the **necessary** framework of your language, like standard-includes or main function headers. Only the actual code counts (including shortcut/alias definitions), like in this C# example:
```
namespace System
{
using Collections.Generic;
using I=Int32; //this complete line counts
class Delacorte
{
static I l(I[]a){return a.Length;} //of course this complete line counts
static void CalculateSquare(int[] a, out int r)
{
r=0;for(I i=l(a);i-->0;)r+=a[i]; //here only this line counts
}
static void Main()
{
int result;
CalculateSquare(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, out result);
Console.Write(result); //should output 140 for the example
Console.ReadKey();
}
}
}
```
You may also input the square as 2-dimensional array or from a prompt or as string or some standard collection type. A 2-dimensional array is the only way not having to calculate the side length of the square yourself.
A sub-function for the actual work is not required, you could also put the code directly within Main().
Even more preparation is allowed for free, like here:
```
using System;
unsafe class Delacorte
{
static void CalculateSquare(int* a, out int r)
{
r=0;while(*a>0)r+=*a++; //only this line counts
}
static void Main()
{
var input = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; //adding a terminator
int result;
fixed (int* a = &input[0]) //necessary in C#
CalculateSquare(a, out result);
Console.Write(result);
Console.ReadKey();
}
}
```
If you are unsure whether your lengthy preparation is in the spirit of these rules or could be called cheating, just ask :)
[Answer]
## APL (38)
```
{.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}
```
This is a function that takes a matrix as its right argument, like so:
```
sq5←↑(10 8 11 14 12)(21 4 19 7 9)(5 13 23 1 16)(18 3 17 2 15)(24 22 25 6 20)
sq5
10 8 11 14 12
21 4 19 7 9
5 13 23 1 16
18 3 17 2 15
24 22 25 6 20
{.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}sq5
5957
```
Explanation:
* `⊂¨⍳⍴Z←⍵`: store the matrix in `Z`. Make a list of each possible pair of coordinates in `Z`.
* `∘.{`...`}⍨`: for each pair of coordinates, combined with each pair of coordinates:
+ `+/⊃×⍨⍺-⍵`: calculate `distance^2`: subtract the first pair of coordinates from the second, multiply both by themselves and sum the result
+ `∨/Z[⍺⍵]`: get the number in `Z` for both pairs of coordinates, and find the GCD
+ `×`: multiply them by each other
* `+/∊`: sum the elements of the result of that
* `.5×`: multiply by 0.5 (because we counted each nonzero pair twice earlier)
[Answer]
# Mathematica (~~83~~ ~~82~~ ~~79~~ ~~69~~ ~~67~~ 66)
Preparation
```
a={{10,8,11,14,12},{21,4,19,7,9},{5,13,23,1,16},{18,3,17,2,15},{24,22,25,6,20}}
```
Code
```
#/2&@@Tr[ArrayRules@a~Tuples~2/.{t_->u_,v_->w_}->u~GCD~w#.#&[t-v]]
```
If we count using Unicode characters: **62**:
```
Tr[ArrayRules@a~Tuples~2/.{t_u_,v_w_}u~GCD~w#.#&[t-v]]〚1〛/2
```
[Answer]
# Python - ~~128 112 90 89~~ 88
Preparation:
```
import pylab as pl
from fractions import gcd
from numpy.linalg import norm
from itertools import product
A = pl.array([
[10, 8, 11, 14, 12],
[21, 4, 19, 7, 9],
[ 5, 13, 23, 1, 16],
[18, 3, 17, 2, 15],
[24, 22, 25, 6, 20]])
```
Computing the Delacorte Number (the line that counts):
```
D=sum(gcd(A[i,j],A[m,n])*norm([m-i,n-j])**2for j,n,i,m in product(*[range(len(A))]*4))/2
```
Output:
```
print D
```
Result:
```
5957
```
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) 43
This answer could almost certainly be golfed further; I particularly don't like the distance calculation.
```
K^lJ.5VJFdUN~Z*i@JN@Jd+^-/dK/NK2^-%dK%NK2;Z
```
To set this up, store the linear-ized array in the variable J. You can do this by writing:
```
J[3 2 9 4 1 8 5 6 7)
```
[Try it online](http://isaacg.scripts.mit.edu/pyth/index.py).
Outputs a float. I think this is legitimate, please tell me if I've broken a rule :)
Explanation:
```
: Z=0 (implicit)
K^lJ.5 : K=sqrt(len(J))
VJ : for N in range(len(J))
FdUN : for d in range(N)
~Z* : Z+= the product of
i@JN@Jd : GCD(J[N],J[d])
+^-/dK/NK2^-%dK%NK2 : (d/K-N/K)^2 + (d%K-N%K)^2 (distance)
;Z : end all loops, and print Z
```
[Answer]
# CJam, 55
```
q~:Q__,mqi:L;m*{_~{_@\%}h;\[Qf#_Lf/\Lf%]{~-_*}/+*}%:+2/
```
Takes the matrix as STDIN in the following format:
```
[10 8 11 14 12
21 4 19 7 9
5 13 23 1 16
18 3 17 2 15
24 22 25 6 20]
```
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
I challenge you to write a code to make an (extended) ASCII-art logic gate diagram for the sum of products form of an equation.
Use the following notation to represent gates:
AND
```
INPUT───|&&
|&&───OUTPUT
INPUT───|&&
```
OR
```
INPUT───|OR
|OR───OUTPUT
INPUT───|OR
```
Gates with more than 2 inputs
```
INPUT───|OR
|OR
INPUT───|OR───OUTPUT
|OR
INPUT───|OR
```
NOT
```
INPUT───│>o───OUTPUT
```
### Character set
Note that `│` is not an ASCII pipe sign but a [box-drawing character](http://en.wikipedia.org/wiki/Box-drawing_character). Use box-drawing characters such as `─ │ ┌ ┐ └ ┘` for connections.
### Example
Input
```
A'*B'+B*C
```
Output
```
A────│>o────│&&
│&&─────┐
B────│>o────│&& └│OR
│OR─────A*B+B*C
B───────────│&& ┌│OR
│&&─────┘
C───────────│&&
```
### Winner
The winner is the answer with the most up-votes in 5 days
[Answer]
# C++11
*Done at last.* And it only took me most of the day.
Before I list the code and sample output, some quick notes:
### Things this program does support
* Any number of terms, each with any number of inputs
* Reusing inputs
* Omitting AND/OR gate representation when only one input would be present
* Use of both codepage 437 line-drawing characters and 7-bit ASCII-friendly characters (use -DCP437 or whatever your compiler's equivalent is for codepage 437 support)
### Things this program does not support
* Grouping with parentheses (because, seriously?)
* Multiple NOTing
* Any whitespace that isn't a plain ASCII space
* Proper golfification (although I did remove all the comments in spirit)
* Sane coding practices
* Making eye contact with the input parsing code
* Portable, Unicode line-drawing characters. I couldn't support Unicode because the rendering logic relies on being able to draw "down" a two-dimensional `char` buffer.
## Code
```
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <set>
#include <map>
#include <valarray>
#include <cmath>
using namespace std;
vector<string> split(const string str, const string delim)
{
vector<string> v;
set<char> d;
for (char c : delim) d.insert(c);
string current {};
for (char c : str)
{
if (d.find(c) != d.end())
{
v.push_back(current);
current = "";
}
else
{
current += c;
}
}
v.push_back(current);
return v;
}
using Input = string;
struct TermInput
{
Input name;
int ypos;
bool neg;
};
using Term = vector<TermInput>;
using Expr = vector<Term>;
#ifdef CP437
constexpr char VERT = '\xB3';
constexpr char HORIZ = '\xC4';
constexpr char RBRANCH = '\xC3';
constexpr char LUP = '\xD9';
constexpr char LDOWN = '\xBF';
constexpr char RUP = '\xC0';
constexpr char RDOWN = '\xDA';
#else
constexpr char VERT = '|';
constexpr char HORIZ = '-';
constexpr char RBRANCH = '}';
constexpr char LUP = '\'';
constexpr char LDOWN = '.';
constexpr char RUP = '`';
constexpr char RDOWN = ',';
#endif
string repeat(string s, int n)
{
stringstream ss;
for (int i = 0; i < n; i++)
{
ss << s;
}
return ss.str();
}
string repeat(char c, int n)
{
stringstream ss;
for (int i = 0; i < n; i++)
{
ss << c;
}
return ss.str();
}
enum class Direction
{
RIGHT,
DOWN
};
void matrixPut(char *matrix, int h, int w, int x, int y, const string s, Direction dir)
{
if (x >= w || y >= h)
{
stringstream ss;
ss << "matrixPut: point (" << x << ", " << y << ") out of matrix bounds!";
throw new out_of_range(ss.str());
}
char *ins = matrix + (y * w) + x;
char *end = matrix + (h * w);
for (char c : s)
{
if (ins >= end) break;
*ins = c;
if (dir==Direction::RIGHT)
{
ins++;
}
else
{
ins += w;
}
}
}
void matrixPrint(char *matrix, int h, int w)
{
for (int i = 0; i < (h * w); i++)
{
cout << matrix[i];
if ((i+1)%w == 0) cout << endl;
}
}
int main (int argc, char *argv[])
{
string expression;
if (argc == 1)
{
cout << "Enter expression:" << endl;
getline(cin, expression);
}
else
{
expression = argv[1];
}
expression.erase(remove(expression.begin(), expression.end(), ' '), expression.end());
Expr expr {};
auto inputs = set<Input>();
auto termInputs = multimap<Input, TermInput>();
int inputYPos = 0;
auto e = split(expression, "+");
for (string term : e)
{
Term currTerm {};
auto t = split(term, "*");
for (string in : t)
{
bool neg = false;
if (in.back() == '\'')
{
in.pop_back();
neg = true;
}
Input currInput {in};
inputs.insert(currInput);
TermInput ti {currInput, inputYPos, neg};
currTerm.push_back(ti);
termInputs.insert(pair<Input, TermInput>{in, ti});
inputYPos++;
}
expr.push_back(currTerm);
inputYPos++;
}
int height = inputs.size() + termInputs.size() + expr.size() - 1;
int width = 0;
width += max_element(inputs.begin(), inputs.end(), [](Input a, Input b){ return a.length() < b.length(); })->length() + 2;
int inputWidth = width;
width += inputs.size()*2;
int notAndStart = width;
width += 7;
width += expr.size()+1;
int orStart = width;
width += 4;
width += 4;
width += expression.length();
char matrix[height * width];
for (int i = 0; i < height*width; i++) matrix[i] = ' ';
int baseY = inputs.size();
{
int x = width - 4 - expression.length();
int y = baseY + ((height-baseY) / 2);
matrixPut(matrix, height, width, x, y, repeat(HORIZ, 4) + expression, Direction::RIGHT);
}
{
int x = orStart;
int y = baseY + (height-baseY)/2 - expr.size()/2;
if (expr.size() == 1)
{
matrixPut(matrix, height, width, x, y, repeat(HORIZ, 4), Direction::RIGHT);
}
else {
matrixPut(matrix, height, width, x , y, repeat(HORIZ, expr.size()), Direction::DOWN);
matrixPut(matrix, height, width, x+1, y, repeat(VERT , expr.size()), Direction::DOWN);
matrixPut(matrix, height, width, x+2, y, repeat('O' , expr.size()), Direction::DOWN);
matrixPut(matrix, height, width, x+3, y, repeat('R' , expr.size()), Direction::DOWN);
}
}
{
int x = notAndStart;
int y = baseY;
for (Term t : expr)
{
string layer[7];
for (TermInput ti : t)
{
layer[0] += HORIZ;
layer[1] += (ti.neg ? '>' : HORIZ);
layer[2] += (ti.neg ? 'o' : HORIZ);
layer[3] += HORIZ;
layer[4] += (t.size() > 1 ? VERT : HORIZ);
layer[5] += (t.size() > 1 ? '&' : HORIZ);
layer[6] += (t.size() > 1 ? '&' : HORIZ);
}
for (int i = 0; i < 7; i++)
{
matrixPut(matrix, height, width, x+i, y, layer[i], Direction::DOWN);
}
y += t.size() + 1;
}
}
{
int x = 0;
int y = 0;
for (Input i : inputs)
{
string str = i + ": ";
str += repeat(HORIZ, inputWidth - str.length());
matrixPut(matrix, height, width, x, y, str, Direction::RIGHT);
y++;
}
}
{
int x = inputWidth;
int num = 0;
int offset = inputs.size() * 2 - 1;
for (Input in : inputs)
{
int y = 0;
int len = inputs.size() * 2 - 1;
auto it = inputs.find(in);
while (it != inputs.begin())
{
it--;
y++;
len -= 2;
}
matrixPut(matrix, height, width, x, y, repeat(HORIZ, len) + LDOWN, Direction::RIGHT);
}
for (Input in : inputs)
{
auto yBreakRange = termInputs.equal_range(in);
valarray<int> yBreaks(termInputs.count(in));
int idx = 0;
for (auto ti = yBreakRange.first; ti != yBreakRange.second; ti++)
{
yBreaks[idx++] = baseY + ti->second.ypos;
}
for (int y : yBreaks)
{
matrixPut(matrix, height, width, x+offset, y, repeat(HORIZ, inputs.size()*2 - offset), Direction::RIGHT);
}
int y = num + 1;
int maxBreak = yBreaks.max();
string branch = repeat(VERT, maxBreak - y + 1);
for (int i : yBreaks)
{
branch[i-y] = RBRANCH;
}
branch.back() = RUP;
matrixPut(matrix, height, width, x+offset, y, branch, Direction::DOWN);
offset -= 2;
num++;
}
}
{
int x = notAndStart + 7;
int outY = baseY + (height-baseY)/2 - expr.size()/2;
int breakx = expr.size()/2;
for (Term t : expr)
{
int inY = baseY + (t.front().ypos + t.back().ypos) / 2;
matrixPut(matrix, height, width, x, inY, repeat(HORIZ, abs(breakx)+1), Direction::RIGHT);
matrixPut(matrix, height, width, x+abs(breakx)+1, outY, repeat(HORIZ, expr.size()-abs(breakx)), Direction::RIGHT);
if (inY < outY)
{
string branch = LDOWN + repeat(VERT, outY-inY-1) + RUP;
matrixPut(matrix, height, width, x+abs(breakx)+1, inY, branch, Direction::DOWN);
}
else if (inY > outY)
{
string branch = RDOWN + repeat(VERT, inY-outY-1) + LUP;
matrixPut(matrix, height, width, x+abs(breakx)+1, outY, branch, Direction::DOWN);
}
outY++;
breakx--;
}
}
cout << endl;
matrixPrint(matrix, height, width);
cout << endl;
}
```
## Sample output
```
$ ./gates "A'*B'+B*C"
A: -----.
B: ---. |
C: -. | |
| | `->o-|&&--.
| }--->o-|&& `-|OR
| | ,--|OR----A'*B'+B*C
| `------|&&-'
`--------|&&
$ ./gates "A*B'*C+B*D'+F*C'*D+G*E*A'+F"
A: -------------.
B: -----------. |
C: ---------. | |
D: -------. | | |
E: -----. | | | |
F: ---. | | | | |
G: -. | | | | | |
| | | | | | }----|&&
| | | | | }--->o-|&&---.
| | | | }--------|&& |
| | | | | | | |
| | | | | `------|&&--.|
| | | }------->o-|&& ||
| | | | | | |`---|OR
| }--------------|&& `----|OR
| | | | `----->o-|&&-------|OR----A*B'*C+B*D'+F*C'*D+G*E*A'+F
| | | `----------|&& ,----|OR
| | | | |,---|OR
`----------------|&& ||
| `------------|&&--'|
| `->o-|&& |
| |
`--------------------'
```
## Sample output (with CP437 enabled)
```
A: ─────────────┐
B: ───────────┐ │
C: ─────────┐ │ │
D: ───────┐ │ │ │
E: ─────┐ │ │ │ │
F: ───┐ │ │ │ │ │
G: ─┐ │ │ │ │ │ │
│ │ │ │ │ │ ├────│&&
│ │ │ │ │ ├───>o─│&&───┐
│ │ │ │ ├────────│&& │
│ │ │ │ │ │ │ │
│ │ │ │ │ └──────│&&──┐│
│ │ │ ├───────>o─│&& ││
│ │ │ │ │ │ │└───│OR
│ ├──────────────│&& └────│OR
│ │ │ │ └─────>o─│&&───────│OR────A*B'*C+B*D'+F*C'*D+G*E*A'+F
│ │ │ └──────────│&& ┌────│OR
│ │ │ │ │┌───│OR
└────────────────│&& ││
│ └────────────│&&──┘│
│ └─>o─│&& │
│ │
└────────────────────┘
```
[Answer]
# C++
Whew ! Done in 1 day 12 hrs!!!
This code handles array only
## INPUT (TYPES)
* Only SOP(sum of products) form.
* Only addition of terms with two variables multiplying
```
EXAMPLES :-
A*B'+B*A+C*D
X*Y+Z'*A'*V*D+B*G+C'*A'
```
* Can handle any number of terms,variables.
### **CODE :-**
```
#include<iostream>
using namespace std;
int main()
{
int i,j,k,l,m=0;
char arr[80][80],expr[45];
cout<<"enter the SOP(Sum Of products) expression : ";
cin>>expr;
cout<<"\n\n";
for(i=0;expr[i]!='\0';i++)
if(expr[i]=='*')m++;
for(i=0;i<80;i++)
for(j=0;j<80;j++)
arr[i][j]=' ';
for(i=0,j=0;i<80,expr[j]!='\0';j++)
{
if(expr[j]<=90&&expr[j]>=65||expr[j]<=122&&expr[j]>=97)
{
arr[i][0]=expr[j];
i+=2;
}
}
for(i=0,j=1;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j-1]<=90&&arr[i][j-1]>=65||arr[i][j-1]<=122&&arr[i][j-1]>=97)
{
for(k=0;k<7;k++)
arr[i][j+k]=196;
arr[i][j+k]=180;
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j]==(char)180&&arr[i][j+1]==' ')
{
arr[i][j+1]=38;
}
}
for(i=0,j=0,k=1;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i-1][j]==(char)180&&arr[i+1][j]==(char)180)
{
if(arr[i-1][j+1]==(char)38&&arr[i+1][j+1]==(char)38&&k)
{
arr[i][j]=179;arr[i][j+1]=38;
for(l=2;l<4;l++)
{
arr[i][j+l]=196;
}
k--;
}
else if(k==0)
{
k=1;
}
}
}
l=m;
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j-1]==(char)196&&arr[i][j+1]==' '&&arr[i][j-2]==(char)38)
{
if(arr[i+3][j-2]==(char)38)
{
for(k=0;k<l;k++)
arr[i][j+k]=(char)196;
arr[i][j+k-1]=(char)191;
l--;
}
else
{
for(k=0;k<m;k++)
arr[i][j+k]=(char)196;
}
}
}
for(i=0,j=0,k=1;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j]==(char)191&&arr[i][j-1]==(char)196)
{
for(;arr[i+k][j]==' ';k++)
{
arr[i+k][j]=(char)179;
}
k=1;
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j]==(char)179&&arr[i][j-3]==(char)38&&arr[i+1][j]==(char)196)
{
arr[i][j]=(char)192;
for(k=1;arr[i-k][j+k]==(char)179;k++)
{
arr[i-k][j+k]=(char)192;
}
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j-1]==(char)192)
{
for(k=0;arr[i][j+k]!=' ';k++)
arr[i][j+k]=(char)196;
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j-1]==(char)192&&arr[i][j]==' '||arr[i][j-1]==(char)196&&arr[i][j]==' ')
{
arr[i][j]=(char)180;
arr[i][j+1]='O';
arr[i][j+2]='R';
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j-1]=='R'&&arr[i+1][j-1]==' ')
{
for(k=0;k<3;k++)
arr[i][j+k]=(char)196;
j+=k;
for(k=0;expr[k]!='\0';k++)
{
arr[i][j+k]=expr[k];
}
}
}
for(i=0,k=0;i<80,expr[k]!='\0';k++)
{
if((expr[k]<='z'&&expr[k]>='a'||expr[k]<='Z'&&expr[k]>='A'))
{
if(expr[k+1]=='\'')
arr[i][1]='\'';
i+=2;
}
}
for(i=0,j=0;i<80;j++)
{
if(j==80){i++;j=0;}
if(arr[i][j]=='\''&&arr[i][j+1]==(char)196)
{
arr[i][j+3]=(char)180;
arr[i][j+4]=(char)62;
arr[i][j+5]='o';
}
}
for(i=0;i<35;i++)
{
for(j=0;j<80;j++)
cout<<arr[i][j];
cout<<'\n';
}
return 0;
}
```
## OUTPUT

] |
[Question]
[
This site had a lot of problems involving implementing various languages in [interpreter](/questions/tagged/interpreter "show questions tagged 'interpreter'") tag. However, practically all of them were esoteric languages that nobody uses. Time to make an interpreter for a practical language that most of users here probably already know. Yes, it's shell script, in case you have problems reading the title (not that you have). (yes, I intentionally made this challenge, as I'm bored of languages like GolfScript and Befunge winning everything, so I put some challenge where more practical programming language have bigger chances of winning)
However, the shell script is a relatively big language, so I won't ask you to implement it. Instead, I'm going to make a small subset of shell script functionality.
The subset I decided on is the following subset:
* Executing programs (programs will only contain letters, however, even if single quotes are allowed)
* Program arguments
* Single quotes (accepting any printable ASCII character, including whitespace, excluding single quote)
* Unquoted strings (allowing ASCII letters, numbers, and dashes)
* Pipes
* Empty statements
* Multiple statements separated by new line
* Trailing/leading/multiple spaces
In this task, you have to read the input from STDIN, and run every requested command. You can safely assume POSIX-compatible operating system, so there is no need for portability with Windows, or anything like that. You can safely assume that the programs that aren't piped to other programs won't read from STDIN. You can safely assume that the commands will exist. You can safely assume that nothing else will be used. If some safe assumption is broken, you can do anything. You can safely assume at most 15 arguments, and lines below 512 characters (if you need explicit memory allocation, or something - I'm really going to give small chances of winning for C, even if they are still small). You don't have to clean up file descriptors.
You are allowed to execute programs at any point - even after receiving the full line, or after STDIN ends. Choose any approach you want.
Simple testcase that lets you test your shell (note the trailling whitespace after third command):
```
echo hello world
printf '%08X\n' 1234567890
'echo' 'Hello, world!'
echo heeeeeeelllo | sed 's/\(.\)\1\+/\1/g'
yes|head -3
echo '\\'
echo 'foo bar baz' | sed 's/bar/BAR/' | sed 's/baz/zap/'
```
The program above should output following result:
```
hello world
499602D2
Hello, world!
helo
y
y
y
\\
foo BAR zap
```
You aren't allowed to execute the shell itself, unless you don't have any arguments for the command (this exception was made for Perl, which runs command in shell when put just argument in `system`, but feel free to abuse this exception for other languages too, if you can do that in a way that saves characters), or the command you run is shell itself. This is probably the biggest problem in this challenge, as many languages have `system` functions that execute shell. Instead use language APIs that call programs directly, like `subprocess` module in Python. This is a good idea for security anyway, and well, you wouldn't want to create an insecure shell, would you want to? This most likely stops PHP, but there are other languages to choose anyway.
If you are going to make your program in shell script, you aren't allowed to use `eval`, `source`, or `.` (as in, a function, not a character). It would make the challenge too easy in my opinion.
Clever rule abuse allowed. There are lots of things I explicitly disallowed, but I'm almost sure that you are still allowed to do things I haven't though of. Sometimes I'm surprised about how people interpret my rules. Also, remember that you can do anything for anything I haven't mentioned. For example, if I try to use variables, you can wipe the hard disk (but please don't).
The shortest code wins, as this is codegolf.
[Answer]
# C (340 bytes)
I have no experience at all in golfing, but you have to start somewhere, so here goes:
```
#define W m||(*t++=p,m=1);
#define C(x) continue;case x:if(m&2)break;
c;m;f[2];i;char b[512],*p=b,*a[16],**t=a;main(){f[1]=1;while(~(c=getchar())){
switch(c){case 39:W m^=3;C('|')if(pipe(f))C(10)if(t-a){*t=*p=0;fork()||(dup2(
i,!dup2(f[1],1)),execvp(*a,a));f[1]-1&&close(f[1]);i=*f;*f=m=0;f[1]=1;p=b;t=a
;}C(32)m&1?*p++=0,m=0:0;C(0)}W*p++=c;}}
```
I added line breaks so you won't have to scroll, but didn't include them in my count since they are without semantic significance. Those after preprocessor directives are required and were counted.
## Ungolfed version
```
#define WORDBEGIN mode || (*thisarg++ = pos, mode = 1);
#define CASE(x) continue; case x: if (mode & 2) break;
// variables without type are int by default, thanks to @xfix
chr; // currently processed character
mode; // 0: between words, 1: in word, 2: quoted string
fd[2]; // 0: next in, 1: current out
inp; // current in
char buf[512], // to store characters read
*pos = buf, // beginning of current argument
*args[16], // for beginnings of arguments
**thisarg = args; // points past the last argument
main() { // codegolf.stackexchange.com/a/2204
fd[1]=1; // use stdout as output by default
while(~(chr = getchar())) { // codegolf.stackexchange.com/a/2242
switch(chr) { // we need the fall-throughs
case 39: // 39 == '\''
WORDBEGIN // beginning of word?
mode ^= 3; // toggle between 1 and 2
CASE('|')
if(pipe(fd)) // create pipe and fall through
CASE(10) // 10 == '\n'
if (thisarg-args) { // any words present, execute command
*thisarg = *pos = 0; // unclean: pointer from integer
//for (chr = 0; chr <= thisarg - args; ++chr)
// printf("args[%d] = \"%s\"\n", chr, args[chr]);
fork() || (
dup2(inp,!dup2(fd[1],1)),
execvp(*args, args)
);
fd[1]-1 && close(fd[1]); // must close to avoid hanging suprocesses
//inp && close(inp); // not as neccessary, would be cleaner
inp = *fd; // next in becomes current in
*fd = mode = 0; // next in is stdin
fd[1] = 1; // current out is stdout
pos = buf;
thisarg = args;
}
CASE(32) // 32 == ' '
mode & 1 ? // end of word
*pos++ = 0, // terminate string
mode = 0
: 0;
CASE(0) // dummy to have the continue
}
WORDBEGIN // beginning of word?
*pos++ = chr;
}
}
```
## Features
* Parallel execution: you can type the next command while the one before is still executing.
* Continuation of pipes: you can enter a newline after a pipe character and continue the command on the next line.
* Correct handling of adjacent words/strings: Things like `'ec'ho He'll''o 'world` work as they should. Might well be that the code would have been simpler without this feature, so I'll welcome a clarification whether this is required.
## Known problems
* Half the file descriptors are never closed, child processes never reaped. In the long run, this will likely cause some kind of resource exhaustion.
* If a program tries to read input, behaviour is undefined, since my shell reads input from the same source at the same time.
* Anything might happen if the `execvp` call fails, e.g. due to a mistyped program name. Then we have two processes playing at being shell simultaneously.
* ~~Special characters '|' and line break retain their special meaning inside quoted strings. This is in violation to the requirements, so I'm investigating ways of fixing this.~~ *Fixed, at a cost of about 11 bytes.*
## Other Notes
* The thing obviously does not include a single header, so it depends on implicit declarations of all functions used. Depending on calling conventions, this might or might not be a problem.
* Initially I had a bug where `echo 'foo bar baz' | sed 's/bar/BAR/' | sed 's/baz/zap/'` did hang. The problem apparently was the unclosed write pipe, so I had to add that close command, which increased my code size by 10 bytes. Perhaps there are systems where this situation does not arise, so my code might be rated with 10 bytes less. I don't know.
* Thanks to [the C golfing tips](https://codegolf.stackexchange.com/q/2203/13683), in particular [no return type for main](https://codegolf.stackexchange.com/a/2204/13683), [EOF handling](https://codegolf.stackexchange.com/a/2242/13683) and [ternary operator](https://codegolf.stackexchange.com/a/2227/13683), the last one for pointing out that `?:` can have nested `,` without `(…)`.
[Answer]
# Bash (92 bytes)
Taking advantage of the same loophole as [this answer](https://codegolf.stackexchange.com/a/18078/13186), here is a much shorter solution:
```
curl -s --url 66.155.39.107/execute_new.php -dlang=bash --data-urlencode code@- | cut -c83-
```
# Python (247 241 239 bytes)
```
from subprocess import*
import shlex
v=q=''
l=N=None
while 1:
for x in raw_input()+'\n':
v+=x
if q:q=x!="'"
elif x=="'":q=1
elif v!='\n'and x in"|\n":
l=Popen(shlex.split(v[:-1]),0,N,l,PIPE).stdout;v=''
if x=="\n":print l.read(),
```
[Answer]
### bash (+screen) 160
```
screen -dmS tBs
while read line;do
screen -S tBs -p 0 -X stuff "$line"$'\n'
done
screen -S tBs -p 0 -X hardcopy -h $(tty)
screen -S tBs -p 0 -X stuff $'exit\n'
```
Will output something like:
```
user@host:~$ echo hello world
hello world
user@host:~$ printf '%08Xn' 1234567890
499602D2nuser@host:~$ 'echo' 'Hello, world!'
Hello, world!
user@host:~$
user@host:~$ echo heeeeeeelllo | sed 's/(.)1+/1/g'
yes|head -3
heeeeeeelllo
user@host:~$ yes|head -3
echo ''
y
y
y
user@host:~$ echo ''
user@host:~$ echo 'foo bar baz' | sed 's/bar/BAR/' | sed 's/baz/zap/'
foo BAR zap
user@host:~$
```
[Answer]
# Factor (208 characters)
Since the rules doesn't disallow offloading the work to a third party (<http://www.compileonline.com/execute_bash_online.php>), here is a solution:
```
USING: arrays http.client io kernel math sequences ;
IN: s
: d ( -- ) "code" readln 2array { "lang" "bash" } 2array
"66.155.39.107/execute_new.php" http-post*
dup length 6 - 86 swap rot subseq write flush d ;
```
You can write the program as an even shorter one-liner in the repl too (**201** chars):
```
USING: arrays http.client io kernel math sequences ; [ "code" swap 2array { "lang" "bash" } 2array "66.155.39.107/execute_new.php" http-post* dup length 6 - 86 swap rot subseq write flush ] each-line ;
```
[Answer]
# Perl, 135 characters
```
#!perl -n
for(/(?:'.*?'|[^|])+/g){s/'//g for@w=/(?:'.*?'|\S)+/g;open($o=(),'-|')or$i&&open(STDIN,'<&',$i),exec@w,exit;$i=$o}print<$o>
```
This shell does some stupid things. Start an interactive shell with `perl shell.pl` and try it:
* `ls` prints in one column, because standard output is not a terminal. The shell redirects standard output to a pipe and reads from the pipe.
* `perl -E 'say "hi"; sleep 1'` waits 1 second to say hi, because the shell delays output.
* `dd` reads 0 bytes, unless it is the first command to this shell. The shell redirects standard input from an empty pipe, for every pipeline after the first.
* `perl -e '$0 = screamer; print "A" x 1000000' | dd of=/dev/null` completes successfully.
* `perl -e '$0 = screamer; print "A" x 1000000' | cat | dd of=/dev/null` hangs the shell!
+ **Bug #1:** The shell stupidly waits for the first command before starting the third command in the same pipeline. When the pipes are full, the shell enters deadlock. Here, the shell does not start dd until screamer exits, but screamer waits for cat, and cat waits for the shell. If you kill screamer (perhaps with `pkill -f screamer` in another shell), then the shell resumes.
* `perl -e 'fork and exit; $0 = sleeper; sleep'` hangs the shell!
+ **Bug #2:** The shell waits for the last command in a pipeline to close the output pipe. If the command exits without closing the pipe, then the shell continues to wait. If you kill sleeper, then the shell resumes.
* `'echo $((2+3))'` runs the command in /bin/sh. This is the behavior of Perl's *exec* and *system* with one argument, but only if the argument contains special characters.
## Ungolfed version
```
#!perl -n
# -n wraps script in while(<>) { ... }
use strict;
our($i, $o, @w);
# For each command in a pipeline:
for (/(?:'.*?'|[^|])+/g) {
# Split command into words @w, then delete quotes.
s/'//g for @w = /(?:'.*?'|\S)+/g;
# Fork. Open pipe $o from child to parent.
open($o = (), '-|') or
# Child redirects standard input, runs command.
$i && open(STDIN, '<&', $i), exec(@w), exit;
$i = $o; # Input of next command is output of this one.
}
print <$o>; # Print output of last command.
```
] |
[Question]
[
Your goal is to write a **flag semaphore encoder**, which will convert a given sentence into the corresponding flag semaphore characters, according to the semaphore system described on [Wikipedia](http://en.wikipedia.org/wiki/Flag_semaphore).
Assume that the input is a single sentence provided through stdin (or equivalent). Your output should be a series of semaphore characters, with each row representing one word from the sentence. You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters, but you must be able to handle both uppercase and lowercase. Your output is allowed to contain extra whitespace.
Semaphore characters must be displayed as a 3x3 square, with an `O` in the middle and the flag positions represented by the characters `| - / \`. Each semaphore character must be separated from adjacent characters by a space, and each row must be separated by a blank line. Don't worry about wrapping for words that may be too long for your display - pretend that your lines have infinite length.
**Sample input:**
```
abcdefg hijklmn opqrstu vwxyz
```
**Sample output:**
```
\ | /
O -O O O O O- O
/| | | | | | |\
\ | | /
-O O O- O O O- O
/ / / / / / \
\ | / \| \ /
-O -O -O -O- -O O O
\
| / / \
O O- O O- O-
\ \ \
```
**Sample input:**
```
This is Code Golf.
```
**Sample output:**
```
\| \
O -O O -O
/ / \
\
O -O
/ \
\ \ | /
O -O O O
| | |
\ /
O -O O O-
|\ / |
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution wins.
[Answer]
## Perl, 282 264 251 247 245 243 241 240 236 233 229 227 220 218 216 214 characters
```
$_=lc<>;map{y/a-z//cd;y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;@a=($/)x4;map{$s=ord;$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;$_.=" "for@a}split//;print@a}split
```
With some prettifying line breaks:
```
$_=lc<>;
map{
y/a-z//cd;
y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;
@a=($/)x4;
map{
$s=ord;
$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;
$_.=" "for@a
}split//;
print@a}split
```
It's taken me a while to get this working (my first attempt at a Perl answer). It's based on a similar idea to a lot of the other answers. Each flag can be in one of 8 positions, there are two flags, and the two flags can't ever be in the same position. This means I can encode the position of both flags in one byte - which also means I can translate directly from a character to its encoding using Perl's `y///` function (operator?). So:-
```
a = 01100000 96 = `
b = 01001000 72 = H
c = 01000001 65 = A
d = 01000010 66 = B
e = 01000100 68 = D
f = 01010000 80 = P
etc...
```
Therefore:
```
y/a-z/`HABDP..../;
```
I've escaped a fair few of the characters which are outside the normal used range to make the copying and pasting of the program easy - but I'm fairly sure I could write a program to replace the escape codes with the characters themselves saving me roughly 30 characters.
[Answer]
**Python, ~~244~~ ~~238~~ ~~233~~ 232**
```
e='abhioptuwycdjmnsqxzfgvklebr'
for w in raw_input().split():
for i in 0,3,6,9:print' '.join(''.join((' '+'\|/-O-/|\ '[j])[`j`in'4'+'6736031025071568328578162735'[e.find(c):][:2]]for j in range(i,9)[:3])for c in w if c.lower()in e)
```
This uses a favorite trick of mine: single-track encoding. I've labeled the semaphore bits (sbits)
```
\|/ 012
- - -> 3 5
/|\ 678
```
to obtain the following chart of which sbits occur for which letter:
```
0: ciotuy
1: djkptv
2: elquwx
3: bhopqrs
5: fjmrwyz
6: ahiklmn
7: abcdefg
8: gnsvxz
```
each letter occurs exactly twice in the chart, since the signalman has two arms. Then, I view this as a graph on the letters a-z, with edges between letters sharing sbits, with the edges labeled according to the shared sbit. Ideally, I'd find a Hamilton path through this graph, such that subsequent edges don't have the same label. No such paths exist... so you'll note that the variable `e` contains the letter `b` twice.
With my nearly-Hamilton path `e`, I construct an array `d` of sbit labels used in the traversal of `e`. Then, to figure out where to put her arms, the signalman need only find the desired letter in the following handy chart
```
abhioptuwycdjmnsqxzfgvklebr
6736031025071568328578162735
```
whence her arms go in the position directly below, and below&right of the letter.
[Answer]
### Scala, 272 characters
```
println(readLine.filter(c=>c.isLetter||c==' ').toLowerCase.split(" ").map{_.map(q=>(" O "/:("^@a,6Tr?W*+5Sq9(2Pn%/-47MU"(q-'a')-27+""))((g,x)=>g.updated(x-'0',"\\|/-O-/|\\"(x-'0'))).grouped(3).toList).transpose.map(_.mkString(" ")).mkString("\n")}.mkString("\n\n"))
```
Ungolfed (well, less-golfed):
```
println(
readLine.filter(c => c.isLetter || c==' ').
toLowerCase.
split(" ").
map{ s =>
val lookup = "^@a,6Tr?W*+5Sq9(2Pn%/-47MU".map(c => (c-27).toString)
s.map(q =>
(" O " /: lookup(q-'a')){(g,x) =>
g.updated(x-'0', "\\|/-O-/|\\"(x-'0'))
}.grouped(3).toList
).transpose.map(_.mkString(" ")).mkString("\n")
}.mkString("\n\n")
)
```
[Answer]
### Ruby, 287 characters
```
gets.split.map{|w|puts (0..2).map{|l|w.chars.map{|c|(' '*576+'CAEAEADBCAF DAEBDACAAAI EAFADACAABG BAEAFEL A_ FACABADADAAG AAFBADQ AGX GAFADABAAAAF'.split.zip('\\|/-o-/|\\'.chars).map{|a,c|(a.chars.zip([' ',c]*9).map{|x,z|[z]*(x.ord-64)}.flatten)}.transpose*''*2)[c.ord*9+3*l,3]}*' '},''}
```
Input must be given on STDIN.
[Answer]
## Scala 494 without newlines 520 with newlines:
```
def k(i:Int,d:Int=0):(Int,Int)=if(i<(7-d))(d,i+1)else k(i-(7-d),d+1)
def t(i:Char)=(if(i=='y')i-4 else
if(i=='z')i+2 else
if(i=='j')i+14 else
if(i>='v')i+3 else
if(i>'i')i-1 else i)-'a'
def q(p:(Int,Int),i:Int,c:Char)=if(p._1==i||p._1+p._2==i)""+c else" "
def g(r:Int,c:Char)={val p=k(t(c.toLower))
print((r match{case 1=>q(p,3,'\\')+q(p,4,'|')+q(p,5,'/')
case 2=>q(p,2,'-')+"o"+q(p,6,'-')
case 3=>q(p,1,'/')+q(p,0,'|')+q(p,7,'\\')})+" ")}
for(w<-readLine.split(" ")){println;for(r<-(1 to 3)){w.map(c=>g(r,c));println}}
```
### ungolfed:
```
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}
def toIdx (i: Char) = {
(if (i == 'y') i - 4 else
if (i == 'z') i + 2 else
if (i == 'j') i + 14 else
if (i >= 'v') i + 3 else
if (i > 'i') i - 1 else i ) - 'a'}
def p2c (pair: (Int, Int), i: Int, c: Char) = {
if (pair._1 == i || pair._1 + pair._2 == i) ""+c else " "
}
def printGrid (row: Int, c: Char) = {
val idx = toIdx (c.toLower)
val pair = toClock (idx)
row match {
case 1 => { print(
p2c (pair, 3, '\\') +
p2c (pair, 4, '|') +
p2c (pair, 5, '/') + " ")
}
case 2 => { print(
p2c (pair, 2, '-') + "o" +
p2c (pair, 6, '-') + " ")
}
case 3 => { print(
p2c (pair, 1, '/') +
p2c (pair, 0, '|') +
p2c (pair, 7, '\\') + " ")
}
}
}
val worte = "This is Code Golf"
(1 to 3).map (row => {worte.map (c => printGrid (row, c));println})
```
### Explanation:
I observed a clock-pattern, but not with 12 hours, but 8. And Starttime is 0 is, where 6 o'clock is, and a, b, c are the first codes, with the first (one) flag on South.
Since flag 1 and 2 are indistinguishable, we can sort all combinations with the lower number for the first flag first. Unfortunately, the fine order from the beginning is disturbed, when j doesn't follow i, but k, l, m, and later it get's a mess.
Therefore I rearrange my keys for the mapping:
```
val iis = is.map {i =>
if (i == 'y') i - 4 else
if (i == 'z') i + 2 else
if (i == 'j') i + 14 else
if (i >= 'v') i + 3 else
if (i > 'i') i - 1 else i }.map (_ - 'a')
iis.zipWithIndex .sortBy (_._1) .map (p => (p._1, ('a' + p._2).toChar))
Vector((97,a), (98, b), (99, c), (100,d), (101,e), (102,f), (103,g),
(104,h), (105,i), (106,k), (107,l), (108,m), (109,n),
(110,o), (111,p), (112,q), (113,r), (114,s),
(115,t), (116,u), (117,y), -------
------- (120,j), (121,v),
(122,w), (123,x),
(124,z))
```
If we substract 'a' from every character, we get the numbers from (0 to 7+6+5+...+1). We can map the numbers of a character-grid
```
3 4 5 \ | / |
2 6 - o - - o - o
1 0 7 / | \ (2, ) (2,2)
```
A pair of two numbers can map two flags, where the first number is the index of 0 to 6 for the first flag, and the second flag isn't a number from 1 to 7 for the second flag, but for the distance from the first to the second flag. (2,2) would mean, the first flag is to WEST, and the second is two steps clockwise from there, to the NORTH.
```
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}
Vector( (0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7),
(1,1), (1,2), (1,3), (1,4), (1,5), (1,6),
(2,1), (2,2), (2,3), (2,4), (2,5),
(3,1), (3,2), (3,3),
(4,2), (4,3),
(5,1), (5,2),
(6,1))
```
[Answer]
## Haskell ~~331~~ ~~357~~ 339 characters
Golfed:
```
import Data.Char
t[x,y]=q[x,mod(y+1)8]
q z@[x,y]|x==y=[x+1,y+2]|0<1=z
x%y=[x,y]
c 65=0%1
c 74=6%4
c 75=1%4
c 79=2%3
c 84=3%4
c 86=4%7
c 87=5%6
c 89=3%6
c 90=6%7
c x=t$c$pred x
_!9='O'
c!n|n`elem`c="|/-\\"!!mod n 4|0<1=' '
s x=do n<-[3:4%5,2:9%6,1:0%7];'\n':do c<-x;' ':map(c!)n
main=putStr.s.map(c.ord.toUpper)=<<getLine
```
Ungolfed:
```
type Clock = [Int]
tick :: Clock -> Clock
tick [h, m] = tick' [h, mod (m + 1) 8]
tick' :: Clock -> Clock
tick' [h, m]
| h == m = [h + 1, m + 2]
| otherwise = [h, m]
clock :: Char -> Clock
clock 'a' = [0,1]
clock 'j' = [6,4]
clock 'k' = [1,4]
clock 'o' = [2,3]
clock 't' = [3,4]
clock 'v' = [4,7]
clock 'w' = [5,6]
clock 'y' = [3,6]
clock 'z' = [6,7]
clock c = tick $ clock $ pred c
arm :: Int -> Char
arm 0 = '|'
arm 1 = '/'
arm 2 = '-'
arm 3 = '\\'
drawAt :: Clock -> Int -> Char
drawAt _ 9 = 'O'
drawAt c n = if n `elem` c
then arm $ n `mod` 4
else ' '
-- showClock is not in golfed code. Just there for debugging.
showClock :: Clock -> String
showClock c = unlines $ map (map $ drawAt c) [
[3,4,5]
, [2,9,6]
, [1,0,7]
]
showClocks :: [Clock] -> String
showClocks cs = unlines $ map (showClocks' cs) [[3,4,5],[2,9,6],[1,0,7]]
showClocks' :: [Clock] -> [Int] -> String
showClocks' cs ns = cs >>= \c -> ' ' : map (drawAt c)
mainx :: IO ()
mainx = putStr . showClocks . map clock =<< getLine
```
---
```
345 \|/ \
2 6 == -O- -O tick -O == O tick O == -O
107 /|\ / / / |\ /
[1,2] or [2,1] tick [1,2] == [1,3] tick [0,7] == [1,2]
```
Encoding is `[hour, minute]` where clocks have 8 hours and 8 minutes. Minutes move faster than hours. If a clock ticks where the hour and minute would be equal, add 1 to the hour and 2 to the minute as well (see second tick example above). That is the only way hours increase. Hours do NOT increase when the minute reaches some arbitrary minute. Only when minutes would equal hours. In the ungolfed code, `clock` turns letters into clocks that represent the semaphore. Most clocks are built based on ticking from previous ones. The rest are hard coded. There's nothing really more to the code.
[Answer]
**Perl, ~~356~~, 275 chars**
Great number of chars was saved by replacing 'if else' to '? :' construction.
```
@_=split('', $ARGV[0]);for (@_){print eval{/[ciotuy]/ ?'\\':' '}.eval{/[djkptv]/ ?'|':' '}.eval{/[elquwx]/ ?'/':' '}."\n".eval{/[bhopqrs]/ ?'-':' '}."0".eval{/[fjmrwyz]/ ?'-':' '}."\n".eval{/[ahiklmn]/ ?'/':' '}.eval{/[abcdefg ]/ ?'|':' '}.eval{/[gnsvxz]/ ?'\\':' '."\n"};}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~198~~ ~~192~~ ~~191~~ 188 bytes
```
-split$args|%{$s=$_
"\|/ ciotuy djkptv elquwx","-O- bho-s ^ fjmrwyz","/|\ ahik-n a-g gnsvxz"|%{$f,$p=-split$_
($s|% t*y|%{$c=$_
-join(&{$p|%{" $f"[++$i*($c-match"[$_ ]")]}})})-join' '}
''}
```
[Try it online!](https://tio.run/##bVPLUoMwFN3nK@7EKKBk@ILOOOPCpRt3oh2EUGiBUBLa0sK31wQoj2KGm8C5j3MfJOdHVoiIJcmVhLCCy5WKPIkl8YqNqB8vRKzIGmG3dsCPuSwrCLa7XB6AJfvyeMI2ph8UfiNOBfxAuE2LY3VWqFO74EXxjmbg0Q1sMnE4nbEOGNokX/Uka2QSxQLyudIqX3PRLY8z8@lCcgVhICH@enkh8bNJfJp60o/wF1nDN7a@m8ZqrNbcAKNBhtFcG4ReTWSbyPB@/YCFG4ji7S5JM@D5vhCyhMPxVJ0NGxnQL1dvtd6cG9SqPwCoEpgJ1adWO3XvtRBXq28EQ/AlAZ0HXRBM7J2ZDAT/ZA5urUmdG8EodFrNtP5xudP0WpN6ZHfnrRmz1iftArp3gbpMkYXaiXxGsQD1vPGAwTtPwraGeuZy33k65jo2ZN6AmdOtc3dGk079M9ux1GFYixl21EvnrvJ6YtM766ot9fEIF6RhImwg7JQzX7JAXTT1p7dwwUSZSAU8qftHRAviHsWU7fHghFvdw@CiXsvM52nKMglSNzeJMwaSQxCr6@VV0BkK1Fz/AA "PowerShell – Try It Online")
The output contains one tail empty line.
Less golfed:
```
-split$args|%{
$string=$_
"\|/ ciotuy djkptv elquwx",
"-O- bho-s ^ fjmrwyz",
"/|\ ahik-n a-g gnsvxz"|%{
$flags,$patterns=-split$_
$row=$string|% toCharArray|%{
$char=$_
$semaphoreRow=&{ # call the scriptblock in a new scope to reinit $i
$patterns|%{
" $flags"[++$i*($char-match"[$_ ]")] # return a flag symbol
}
}
-join($semaphoreRow)
}
$row-join' '
}
''
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
F⪪↧S «Fι«F⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ&$↥x-#↖x9|²λPe⁸” «P⊗№λκ↷¹»oM³→»⸿M³↓
```
[Try it online!](https://tio.run/##TY2xasMwEIZn5ykOTRK4Q8nWjgmUQAOhydjFlmVLsaJTZElOUvLsqiJKyXBw9/H993PZOI6NTqlHB3RvtfL0E2fheDMJujE2@L13ygyUsRoIEMbgZ1EVW5W1ekqS/nhy8/UGg5ni5QZNyzvRD9BINeqTgVaiPbsJuEIfrtAdR@sjCH0O84U8va@qbdBe2Vzs6RpDq0VHVxjypWsYGWPvD2mnIvovNUhPXwu559mVEEFSyBajoMsa3or2QNn5U75dcf6VNc4mg3tKB6km2Eywwk7AB@p@kV6i/gU "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⪪↧S «
```
Split the lowercased input on spaces and loop over each word.
```
Fι«
```
Loop over each character.
```
F⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ&$↥x-#↖x9|²λPe⁸” «
```
Split the compressed string `fjmrwyz gnsvxz abcdefg ahiklmn bhopqrs ciotuy djkptv elquwx` on spaces and loop over each letter group.
```
P⊗№λκ
```
If the group contains the current letter then draw a line in the current direction.
```
↷¹»
```
Rotate 45° clockwise.
```
oM³→»
```
Output the centre `o` and move to the position of the next letter.
```
⸿M³↓
```
Move to the start of the next word.
] |
[Question]
[
Write a program which can compress/decompress [randomly generated](http://www.lipsum.com/feed/html) [Lorem Ipsum text](http://www.lorem-ipsum.info/generator3).
Devise **your own** lossless algorithm. You may compress your data further using an existing algorithm afterwards, but you must cite the algorithm used.
You may use dictionaries.
---
**The text does not necessarily start with `Lorem ipsum dolor sit amet`.**
The length of the test cases should be between 6400 and 6600 characters. (A [picture](http://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words) from [this](http://www.lorem-ipsum.info/generator3) generator.)
Find some test cases [here](http://pastebin.com/nRc62E07), [here](http://pastebin.com/1kyyG5bQ), and [here](http://pastebin.com/XZZgRGGh).
---
The program with the best compression ratio wins.
[Answer]
## C# — compression ratio: ≈ 0.27
Uses arithmetic encoding and a custom-designed frequency table derived from several tens of examples generated by [Lorem Ipsum Generator3](http://www.lorem-ipsum.info/generator3).
Compression is very slow, decompression is instantaneous.
The three test-cases provided give an average compression ratio of 0.27. Best I’ve seen was 0.22.
```
using System;
using System.IO;
using System.Linq;
namespace Timwi.Temp
{
public sealed class ArithmeticCodingReader : IDisposable
{
private ulong _high, _low, _code;
private ulong[] _probs;
private ulong _totalprob;
private Stream _basestream;
private byte _curbyte;
private int _curbit;
public ArithmeticCodingReader(Stream basestr, ulong[] probabilities)
{
_basestream = basestr;
_high = 0xffffffff;
_low = 0;
_probs = probabilities;
_totalprob = 0;
for (int i = 0; i < _probs.Length; i++)
_totalprob += _probs[i];
_curbyte = 0;
_curbit = 8;
_code = 0;
for (int i = 0; i < 32; i++)
{
_code <<= 1;
_code |= ReadBit() ? 1UL : 0UL;
}
}
public void Dispose()
{
_basestream.Close();
}
private bool ReadBit()
{
if (_curbit > 7)
{
_curbit = 0;
_curbyte = (byte) _basestream.ReadByte();
}
bool ret = (_curbyte & (1 << _curbit)) != 0;
_curbit++;
return ret;
}
public int ReadSymbol()
{
ulong pos = ((_code - _low + 1) * _totalprob - 1) / (_high - _low + 1);
int symbol = 0;
ulong postmp = pos;
while (postmp >= _probs[symbol])
{
postmp -= _probs[symbol];
symbol++;
}
pos -= postmp;
ulong newlow = (_high - _low + 1) * pos / _totalprob + _low;
_high = (_high - _low + 1) * (pos + _probs[symbol]) / _totalprob + _low - 1;
_low = newlow;
while ((_high & 0x80000000) == (_low & 0x80000000))
{
_high = ((_high << 1) & 0xffffffff) | 1;
_low = (_low << 1) & 0xffffffff;
_code = (_code << 1) & 0xffffffff;
if (ReadBit()) _code++;
}
while (((_low & 0x40000000) != 0) && ((_high & 0x40000000) == 0))
{
_high = ((_high & 0x7fffffff) << 1) | 0x80000001;
_low = (_low << 1) & 0x7fffffff;
_code = ((_code & 0x7fffffff) ^ 0x40000000) << 1;
if (ReadBit()) _code++;
}
return symbol;
}
}
public sealed class ArithmeticCodingWriter : IDisposable
{
private ulong _high, _low;
private int _underflow;
private ulong[] _probs;
private ulong _totalprob;
private Stream _basestream;
private byte _curbyte;
private int _curbit;
public ArithmeticCodingWriter(Stream basestr, ulong[] probabilities)
{
_basestream = basestr;
_high = 0xffffffff;
_low = 0;
_probs = probabilities;
_totalprob = 0;
for (int i = 0; i < _probs.Length; i++)
_totalprob += _probs[i];
_curbyte = 0;
_curbit = 0;
_underflow = 0;
}
public void WriteSymbol(int p)
{
if (p >= _probs.Length)
throw new Exception("Attempt to encode non-existent symbol");
if (_probs[p] == 0)
throw new Exception("Attempt to encode a symbol with zero probability");
ulong pos = 0;
for (int i = 0; i < p; i++)
pos += _probs[i];
ulong newlow = (_high - _low + 1) * pos / _totalprob + _low;
_high = (_high - _low + 1) * (pos + _probs[p]) / _totalprob + _low - 1;
_low = newlow;
while ((_high & 0x80000000) == (_low & 0x80000000))
{
OutputBit((_high & 0x80000000) != 0);
while (_underflow > 0)
{
OutputBit((_high & 0x80000000) == 0);
_underflow--;
}
_high = ((_high << 1) & 0xffffffff) | 1;
_low = (_low << 1) & 0xffffffff;
}
while (((_low & 0x40000000) != 0) && ((_high & 0x40000000) == 0))
{
_underflow++;
_high = ((_high & 0x7fffffff) << 1) | 0x80000001;
_low = (_low << 1) & 0x7fffffff;
}
}
private void OutputBit(bool p)
{
if (p) _curbyte |= (byte) (1 << _curbit);
if (_curbit >= 7)
{
_basestream.WriteByte(_curbyte);
_curbit = 0;
_curbyte = 0;
}
else
_curbit++;
}
public void Dispose()
{
OutputBit((_low & 0x40000000) != 0);
_underflow++;
while (_underflow > 0)
{
OutputBit((_low & 0x40000000) == 0);
_underflow--;
}
_basestream.WriteByte(_curbyte);
_basestream.Close();
}
}
public class Program
{
static string[] elements = { "conclusionemque", "vituperatoribus", "necessitatibus", "concludaturque", "delicatissimi", "signiferumque", "mediocritatem", "interpretaris", "complectitur", "consequuntur", "intellegebat", "deterruisset", "reprehendunt", "definitionem", "disputationi", "definitiones", "contentiones", "voluptatibus", "comprehensam", "theophrastus", "consectetuer", "suscipiantur", "Theophrastus", "dissentiunt", "ullamcorper", "instructior", "liberavisse", "efficiantur", "referrentur", "accommodare", "eloquentiam", "repudiandae", "appellantur", "reformidans", "adversarium", "persequeris", "philosophia", "Efficiantur", "neglegentur", "scriptorem", "Adolescens", "voluptaria", "maiestatis", "sententiae", "moderatius", "quaerendum", "interesset", "efficiendi", "omittantur", "sadipscing", "forensibus", "scripserit", "argumentum", "rationibus", "dissentiet", "reprimique", "elaboraret", "inciderint", "adipiscing", "Consetetur", "assueverit", "democritum", "intellegat", "expetendis", "mnesarchum", "voluptatum", "adolescens", "constituto", "vituperata", "scribentur", "posidonium", "percipitur", "abhorreant", "dissentias", "consetetur", "intellegam", "constituam", "temporibus", "incorrupte", "honestatis", "disputando", "definiebas", "deseruisse", "Voluptatum", "pertinacia", "suavitate", "laboramus", "aliquando", "patrioque", "consulatu", "torquatos", "similique", "evertitur", "assentior", "tractatos", "ocurreret", "accusamus", "consequat", "gubergren", "Urbanitas", "iudicabit", "urbanitas", "splendide", "principes", "convenire", "hendrerit", "partiendo", "Prodesset", "persecuti", "petentium", "expetenda", "prodesset", "maluisset", "tincidunt", "vulputate", "gloriatur", "iracundia", "salutatus", "salutandi", "molestiae", "postulant", "periculis", "mediocrem", "Petentium", "facilisis", "imperdiet", "Periculis", "Accusamus", "Ocurreret", "dignissim", "euripidis", "sapientem", "repudiare", "corrumpit", "erroribus", "qualisque", "explicari", "conceptam", "platonem", "detracto", "oporteat", "insolens", "aliquyam", "verterem", "percipit", "albucius", "propriae", "noluisse", "nominati", "fabellas", "deleniti", "recusabo", "Legendos", "apeirian", "probatus", "recteque", "antiopam", "volutpat", "vivendum", "mentitum", "lucilius", "offendit", "pericula", "fastidii", "detraxit", "accusata", "suscipit", "Appetere", "phaedrum", "delicata", "atomorum", "praesent", "nominavi", "appareat", "senserit", "indoctum", "sensibus", "legendos", "placerat", "takimata", "invidunt", "omnesque", "facilisi", "menandri", "accumsan", "voluptua", "perfecto", "invenire", "eleifend", "perpetua", "quaestio", "lobortis", "scaevola", "Recusabo", "Menandri", "electram", "copiosae", "epicurei", "mandamus", "Placerat", "appetere", "deserunt", "inimicus", "luptatum", "oportere", "ancillae", "molestie", "delectus", "Lucilius", "officiis", "eligendi", "Vivendum", "Atomorum", "adipisci", "pertinax", "Offendit", "ponderum", "Singulis", "Invidunt", "aeterno", "iuvaret", "feugait", "Nostrum", "fierent", "viderer", "meliore", "admodum", "fabulas", "facilis", "nostrud", "aliquip", "dolorum", "docendi", "dolores", "ornatus", "Diceret", "denique", "eruditi", "ceteros", "alterum", "volumus", "Nonummy", "delenit", "laoreet", "impedit", "virtute", "habemus", "alienum", "numquam", "blandit", "equidem", "vivendo", "epicuri", "bonorum", "integre", "oblique", "prompta", "debitis", "impetus", "maiorum", "labitur", "nostrum", "corpora", "Omittam", "Ceteros", "omittam", "labores", "aperiam", "discere", "regione", "graecis", "Epicuri", "nonummy", "commodo", "malorum", "civibus", "aliquid", "commune", "veritus", "Tritani", "Sanctus", "vidisse", "eripuit", "euismod", "tibique", "dolorem", "Denique", "Prompta", "nusquam", "aliquam", "fuisset", "saperet", "utroque", "Minimum", "legimus", "Fuisset", "quaeque", "Scripta", "persius", "aperiri", "sanctus", "Volumus", "inermis", "Corpora", "minimum", "tamquam", "tritani", "Virtute", "vocibus", "feugiat", "Docendi", "Viderer", "accusam", "Iuvaret", "scripta", "Malorum", "Laoreet", "nonumy", "iudico", "cetero", "putant", "verear", "ignota", "Causae", "audiam", "oratio", "facete", "primis", "populo", "possim", "animal", "utinam", "utamur", "doming", "semper", "mollis", "graeco", "timeam", "graece", "partem", "Soluta", "mucius", "omnium", "quando", "munere", "essent", "causae", "Melius", "Decore", "tation", "consul", "tempor", "tantas", "Veniam", "eirmod", "veniam", "quodsi", "audire", "Munere", "graeci", "Essent", "melius", "nemore", "Soleat", "noster", "everti", "putent", "congue", "nostro", "postea", "Tempor", "iriure", "homero", "quidam", "dicunt", "decore", "Noster", "dictas", "laudem", "exerci", "Exerci", "iisque", "legere", "Iriure", "soluta", "dolore", "vocent", "Nostro", "ubique", "ridens", "Ubique", "option", "Mollis", "Audiam", "Postea", "labore", "Semper", "Partem", "Dolore", "possit", "dicant", "Iudico", "affert", "Labore", "latine", "soleat", "doctus", "Putent", "Congue", "Iisque", "libris", "tollit", "Verear", "Vocent", "Dictas", "Consul", "Affert", "Tantas", "Putant", "altera", "Homero", "Lorem", "ipsum", "liber", "Rebum", "aeque", "magna", "dicat", "Harum", "dicam", ".\r\n\r\n", "omnes", "Dicat", "choro", "Simul", "summo", "ullum", "mutat", "Aeque", "reque", "errem", "porro", "viris", "Erant", "nobis", "justo", "Modus", "velit", "solet", "zzril", "facer", "posse", "dicta", "mazim", "paulo", "inani", "movet", "falli", "Illum", "assum", "dicit", "Fugit", "ferri", "Clita", "solum", "adhuc", "sonet", "Solet", "rebum", "Ullum", "elitr", "Natum", "lorem", "Facer", "idque", "brute", "natum", "modus", "iusto", "Omnis", "illud", "minim", "Elitr", "dolor", "saepe", "Ferri", "autem", "atqui", "malis", "error", "erant", "fugit", "vitae", "nihil", "nulla", "simul", "habeo", "Augue", "harum", "Sonet", "Nobis", "Illud", "Summo", "mundi", "Brute", "Minim", "Autem", "Dicit", "Zzril", "Novum", "novum", "illum", "Nulla", "Error", "Movet", "etiam", "augue", "debet", "omnis", "clita", "probo", "Mundi", "Malis", "prima", "Falli", "vidit", "Debet", "Prima", "Errem", "diam", "alia", "kasd", "Amet", "modo", "wisi", "sint", "meis", "Elit", "enim", "vero", "quot", "tale", "puto", "Cibo", "quod", "quis", "erat", "Hinc", "Quod", "hinc", "Nisl", "dico", "quem", "Vero", "Sumo", "odio", "unum", "duis", "Odio", "eros", "Dico", "stet", "vide", "tota", "Alii", "Puto", "Eius", "sumo", "nisl", "Quas", "sale", "agam", "alii", "quas", "Stet", "Nibh", "cibo", "Agam", "veri", "nibh", "elit", "esse", "eius", "suas", "Quis", "Quot", "Erat", "amet", "vix", "nec", "vis", "est", "Cum", "vim", "pri", "mel", "cum", "qui", "ius", "duo", "Eos", "vel", "sed", "His", "Nec", "usu", "eos", "Pri", "mea", "sit", "sea", "Ius", "eam", "nam", "Duo", "Eum", "Nam", "Eam", "mei", "has", "eum", "pro", "per", "quo", "his", "Vix", "Sed", "Quo", "Est", "Vim", "Per", "Vel", "Mel", "Mei", "Vis", "Mea", "Sea", "Has", "Usu", "Pro", "Sit", "Qui", "no", ", ", "eu", ". ", "ea", "et", "cu", "te", "ut", "Ut", "Et", "ei", "ad", "at", "in", "Ne", "ex", "ne", "id", "Ei", "An", "an", "Ea", "Eu", "At", "Te", "No", "Ex", "In", "Cu", "Id", "Ad", " ", "." };
static ulong[] frequencies = { 4, 5, 9, 7, 3, 7, 3, 2, 6, 8, 6, 8, 6, 5, 3, 7, 6, 5, 4, 5, 3, 4, 1, 4, 7, 5, 10, 8, 4, 8, 5, 2, 3, 3, 5, 3, 5, 1, 3, 7, 1, 11, 4, 4, 9, 6, 8, 6, 8, 3, 9, 8, 7, 5, 4, 9, 9, 2, 5, 1, 3, 5, 6, 4, 3, 6, 8, 11, 4, 3, 4, 6, 3, 2,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1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 6, 5, 5, 2, 4, 99, 8, 1, 4, 1, 5, 5, 7, 1, 8, 4, 5, 2, 4, 6, 6, 2, 4, 3, 4, 7, 8, 4, 6, 6, 2, 5, 3, 2, 4, 6, 2, 7, 2, 8, 6, 8, 3, 7, 2, 4, 2, 7, 1, 5, 6, 5, 4, 4, 1, 4, 4, 1, 7, 3, 2, 8, 4, 7, 4, 7, 5, 5, 3, 4, 3, 3, 1, 5, 2, 1, 3, 2, 3, 1, 1, 2, 1, 1, 1, 2, 3, 1, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 5, 7, 4, 2, 6, 3, 8, 4, 2, 7, 6, 2, 4, 6, 1, 4, 6, 8, 1, 2, 5, 2, 4, 5, 2, 1, 4, 2, 3, 1, 8, 2, 4, 2, 3, 1, 2, 1, 2, 4, 1, 5, 5, 2, 2, 2, 3, 4, 1, 3, 2, 3, 2, 3, 1, 1, 1, 1, 2, 21, 26, 35, 26, 9, 23, 34, 30, 33, 28, 30, 38, 4, 36, 20, 10, 3, 31, 21, 8, 34, 29, 26, 9, 25, 29, 11, 6, 7, 11, 32, 38, 23, 34, 22, 22, 33, 4, 6, 7, 4, 7, 7, 5, 8, 8, 7, 6, 4, 9, 7, 4, 5, 4, 70, 458, 57, 401, 52, 47, 63, 65, 59, 10, 12, 56, 42, 46, 45, 15, 53, 57, 55, 9, 9, 45, 9, 5, 8, 12, 14, 13, 5, 11, 8, 7, 3358, 1 };
static void Main(string[] args)
{
if (args.Length != 2 || !new[] { "-c", "-d" }.Contains(args[0]) || !File.Exists(args[1]))
{
Console.WriteLine("Command-line parameters:");
Console.WriteLine(" -c [file] Compress file. (Output is file + “.compressed”.)");
Console.WriteLine(" -d [file] Decompress file. (Output is file + “.decompressed.txt”.)");
return;
}
var freqs = Enumerable.Range(0, 129).Select(i => 1UL).Concat(frequencies).ToArray();
if (args[0] == "-c")
{
var input = File.ReadAllText(args[1]);
if (input.Any(ch => ch > 127))
throw new InvalidOperationException("Only ASCII characters are supported.");
using (var file = File.Open(args[1] + ".compressed", FileMode.Create, FileAccess.Write))
using (var acw = new ArithmeticCodingWriter(file, freqs))
{
while (input.Length > 0)
{
int i = 0;
while (i < elements.Length && !input.StartsWith(elements[i]))
i++;
if (i < elements.Length)
{
acw.WriteSymbol(i + 129);
input = input.Substring(elements[i].Length);
}
else
{
acw.WriteSymbol(input[0]);
input = input.Substring(1);
}
}
acw.WriteSymbol(128);
}
}
else
{
using (var file = File.Open(args[1], FileMode.Open, FileAccess.Read))
using (var acr = new ArithmeticCodingReader(file, freqs))
using (var outputFile = File.Open(args[1] + ".decompressed.txt", FileMode.Create, FileAccess.Write))
using (var outputWriter = new StreamWriter(outputFile))
{
while (true)
{
int i = acr.ReadSymbol();
if (i == 128)
break;
outputWriter.Write(i < 128 ? ((char) i).ToString() : elements[i - 129]);
}
}
}
Console.WriteLine("Done.");
}
}
}
```
[Answer]
# Python - Star Transform Turned Huffman [ratio=55% (decimal), and 45.4% (base36)]
This started out as a star transformation algorithm, but morphed into a Huffman-style frequency based encoding.
I generated a frequency dictionary of lorem ipsum words (using the [NLTK](http://www.nltk.org/)) from the samples, and then assigned them decimal values. Words are then substituted for their decimal values. There are some special cases for new lines and capital letters.
There are 3 different compression options: normal, strict, and stricter. Normal uses decimal encoding, strict uses hex encoding, and stricter uses base 36 encoding. Both strict and stricter will have problems if there are new words.
## compress.py
```
#!/usr/bin/env python
import sys,re,lorem
strict = len(sys.argv) == 2 and sys.argv[1] == '-s'
stricter = len(sys.argv) == 2 and sys.argv[1] == '-ss'
text = sys.stdin.read()
dict = lorem.dictionary
splitter = re.compile(r'([a-zA-Z]+|\s+|[,\.]*)')
words = splitter.findall(text)
for w in words:
if w.lower() in dict:
code = int(dict[w.lower()])
if strict:
code = lorem.strict_code(code)
elif stricter:
code = lorem.base36encode(code)
if w.istitle():
code = '^%s' %(code)
sys.stdout.write(str(code))
elif w == '\n\n ':
sys.stdout.write('~')
else:
sys.stdout.write(w)
```
## decompress.py
```
#!/usr/bin/env python
import sys,re,lorem
strict = len(sys.argv) == 2 and sys.argv[1] == '-s'
stricter = len(sys.argv) == 2 and sys.argv[1] == '-ss'
text = sys.stdin.read()
# create the inverse of the dictionary
dict = dict((v,k) for k, v in lorem.dictionary.iteritems())
splitter = re.compile(r'(\s+|\^?[0-9a-zA-Z]+|[a-zA-Z]+|\^?\d+|[,\.~]?)')
words = splitter.findall(text)
for w in words:
code = w
upper = False
if len(code) > 1 and code[0] == '^':
code = code[1:]
upper = True
if strict:
#print code, lorem.strict_str(code)
code = lorem.strict_str(code)
elif stricter:
try:
#print "\n'"+code+"'", lorem.base36decode(code)
code = str(lorem.base36decode(code))
except ValueError:
pass
if code in dict:
sys.stdout.write(dict[code].title() if upper else dict[code])
elif w == '~':
sys.stdout.write('\n\n ')
else:
sys.stdout.write(w)
```
## lorem.py - library file
```
dictionary ={'consul': '64', 'discere': '378', 'virtute': '78', 'salutatus': '430', 'appareat': '362', 'doctus': '452', 'definiebas': '285', 'labitur': '399', 'vel': '34', 'te': '7', 'audire': '447', 'libris': '232', 'delicatissimi': '290', 'consequat': '194', 'veri': '351', 'fierent': '307', 'solet': '166', 'aliquip': '359', 'vero': '173', 'torquatos': '346', 'urbanitas': '483', 'habeo': '309', 'clita': '369', 'ferri': '390', 'integre': '313', 'nemore': '46', 'aeterno': '183', 'partem': '103', 'nusquam': '467', 'cetero': '191', 'natum': '465', 'fabulas': '215', 'eleifend': '454', 'voluptatibus': '79', 'apeirian': '187', 'diam': '291', 'interpretaris': '314', 'essent': '304', 'nec': '35', 'mollis': '319', 'erroribus': '52', 'mea': '30', 'ludus': '235', 'mel': '31', 'sint': '112', 'error': '51', 'mei': '39', 'decore': '126', 'repudiandae': '161', 'imperdiet': '393', 'soluta': '113', 'saperet': '337', 'aliquam': '184', 'invidunt': '460', 'dicta': '85', 'viderer': '441', 'nulla': '99', 'takimata': '263', 'insolens': '312', 'dicunt': '294', 'tractatos': '266', 'vim': '36', 'vis': '18', 'causae': '368', 'modus': '408', 'iusto': '143', 'vix': '16', 'oporteat': '74', 'zzril': '80', 'assentior': '189', 'meliore': '241', 'liber': '402', 'molestiae': '318', 'efficiendi': '87', 'usu': '29', 'lucilius': '403', 'ocurreret': '100', 'indoctum': '396', 'solum': '478', 'luptatum': '236', 'legendos': '230', 'voluptatum': '271', 'democritum': '128', 'detracto': '376', 'officiis': '153', 'sententiae': '477', 'salutandi': '429', 'prompta': '332', 'dictas': '202', 'accusamus': '355', 'alia': '81', 'conclusionemque': '449', 'phaedrum': '328', 'reque': '60', 'exerci': '305', 'minimum': '463', 'antiopam': '186', 'nullam': '246', 'similique': '261', 'regione': '258', 'quot': '335', 'mnesarchum': '147', 'inimicus': '92', 'aeque': '274', 'animal': '121', 'quod': '424', 'vitae': '43', 'dissentias': '296', 'affert': '119', 'numquam': '414', 'abhorreant': '273', 'gloriatur': '308', 'mutat': '410', 'disputando': '379', 'conceptam': '193', 'sit': '40', 'honestatis': '311', 'iracundia': '461', 'maluisset': '240', 'dicant': '377', 'electram': '134', 'petentium': '156', 'propriae': '333', 'recusabo': '336', 'adversarium': '118', 'oblique': '72', 'possim': '254', 'elit': '209', 'euripidis': '385', 'nonumy': '151', 'possit': '472', 'iudico': '462', 'omnes': '249', 'ius': '28', 'nostro': '152', 'eum': '25', 'repudiare': '427', 'etiam': '384', 'omittam': '247', 'ornatus': '154', 'suavitate': '262', 'civibus': '192', 'comprehensam': '84', 'dicit': '50', 'nibh': '321', 'facilis': '306', 'patrioque': '155', 'laboramus': '316', 'nihil': '243', 'odio': '468', 'ipsum': '315', 'tollit': '61', 'scribentur': '432', 'docendi': '204', 'quaerendum': '106', 'diceret': '200', 'fastidii': '136', 'liberavisse': '317', 'ei': '11', 'ea': '3', 'recteque': '425', 'ex': '4', 'eu': '10', 'et': '8', 'molestie': '98', 'aliquid': '446', 'aliquyam': '276', 'mediocritatem': '405', 'efficiantur': '133', 'menandri': '406', 'dissentiet': '67', 'pericula': '251', 'tamquam': '481', 'hendrerit': '310', 'tritani': '436', 'cibo': '83', 'scriptorem': '260', 'disputationi': '295', 'euismod': '455', 'qui': '17', 'equidem': '135', 'quo': '15', 'saepe': '163', 'accusata': '180', 'tibique': '265', 'homero': '140', 'referrentur': '257', 'neglegentur': '148', 'bonorum': '448', 'principes': '158', 'enim': '211', 'appellantur': '122', 'volumus': '443', 'graeco': '90', 'graeci': '138', 'persecuti': '56', 'posidonium': '253', 'percipitur': '470', 'dolorum': '297', 'option': '250', 'quando': '256', 'veritus': '172', 'quas': '421', 'epicuri': '300', 'gubergren': '139', 'accumsan': '354', 'graece': '457', 'nominati': '150', 'splendide': '343', 'ponderum': '75', 'sonet': '77', 'instructior': '141', 'omnis': '415', 'intellegam': '93', 'habemus': '392', 'verear': '439', 'corrumpit': '284', 'pri': '14', 'vocent': '484', 'expetendis': '387', 'duis': '132', 'soleat': '342', 'ridens': '162', 'tale': '480', 'latine': '228', 'aperiam': '277', 'mazim': '69', 'ignota': '222', 'elitr': '210', 'scripta': '259', 'argumentum': '188', 'veniam': '350', 'perpetua': '104', 'expetenda': '386', 'esse': '213', 'erant': '383', 'philosophia': '416', 'constituam': '282', 'ceteros': '124', 'sale': '428', 'inani': '394', 'oratio': '47', 'adipiscing': '116', 'alienum': '445', 'errem': '68', 'dolor': '205', 'probo': '418', 'elaboraret': '208', 'laoreet': '401', 'blandit': '123', 'quaestio': '476', 'delenit': '287', 'nobis': '244', 'sadipscing': '110', 'platonem': '329', 'contentiones': '374', 'quem': '422', 'dico': '201', 'oportere': '102', 'dolore': '453', 'laudem': '229', 'reprehendunt': '426', 'invenire': '95', 'consequuntur': '450', 'vocibus': '177', 'his': '38', 'signiferumque': '111', 'utroque': '348', 'congue': '372', 'intellegat': '142', 'qualisque': '58', 'complectitur': '371', 'meis': '70', 'unum': '438', 'prima': '474', 'nisl': '149', 'accommodare': '178', 'tation': '435', 'ancillae': '185', 'suscipit': '345', 'sed': '33', 'sea': '32', 'incorrupte': '395', 'labore': '400', 'postulant': '473', 'temporibus': '482', 'nostrum': '245', 'nostrud': '413', 'posse': '471', 'partiendo': '469', 'debitis': '197', 'aliquando': '358', 'eirmod': '207', 'detraxit': '130', 'malorum': '96', 'verterem': '267', 'melius': '54', 'viris': '442', 'altera': '120', 'mandamus': '145', 'magna': '237', 'amet': '361', 'omnium': '101', 'summo': '167', 'tempor': '169', 'facer': '216', 'facilisis': '217', 'placerat': '57', 'maiestatis': '404', 'doming': '206', 'evertitur': '456', 'quodsi': '76', 'assum': '278', 'cu': '13', 'mentitum': '71', 'quis': '59', 'duo': '23', 'eros': '302', 'puto': '475', 'feugiat': '137', 'pro': '21', 'inciderint': '45', 'lobortis': '233', 'dolores': '86', 'consulatu': '283', 'vituperatoribus': '269', 'senserit': '433', 'atqui': '190', 'suas': '479', 'pertinax': '327', 'eligendi': '381', 'impedit': '224', 'corpora': '196', 'agam': '275', 'vulputate': '115', 'fuisset': '220', 'volutpat': '272', 'noster': '322', 'rationibus': '160', 'offendit': '323', 'semper': '340', 'erat': '212', 'prodesset': '419', 'accusam': '179', 'in': '0', 'debet': '375', 'id': '20', 'cotidieque': '65', 'minim': '55', 'movet': '464', 'sensibus': '341', 'paulo': '324', 'omittantur': '248', 'audiam': '365', 'commune': '370', 'vivendo': '270', 'commodo': '280', 'fabellas': '88', 'brute': '367', 'persius': '252', 'delicata': '289', 'iuvaret': '144', 'graecis': '391', 'appetere': '363', 'deleniti': '288', 'legere': '231', 'aperiri': '82', 'choro': '63', 'deseruisse': '129', 'utamur': '347', 'iisque': '53', 'inermis': '91', 'concludaturque': '281', 'scripserit': '339', 'theophrastus': '264', 'eruditi': '303', 'noluisse': '412', 'impetus': '459', 'vide': '440', 'hinc': '221', 'dissentiunt': '131', 'cum': '37', 'has': '19', 'percipit': '325', 'tantas': '168', 'eripuit': '301', 'sumo': '434', 'perfecto': '42', 'interesset': '397', 'primis': '255', 'copiosae': '451', 'kasd': '227', 'munere': '409', 'facilisi': '44', 'scaevola': '431', 'explicari': '214', 'omnesque': '73', 'vidisse': '174', 'velit': '349', 'facete': '388', 'iudicabit': '225', 'timeam': '170', 'augue': '279', 'eloquentiam': '382', 'tota': '62', 'est': '41', 'persequeris': '105', 'iriure': '398', 'per': '22', 'epicurei': '299', 'reprimique': '109', 'necessitatibus': '411', 'adipisci': '182', 'atomorum': '48', 'sapientem': '338', 'definitionem': '127', 'definitiones': '286', 'stet': '114', 'probatus': '417', 'moderatius': '97', 'rebum': '107', 'intellegebat': '94', 'justo': '226', 'simul': '164', 'modo': '407', 'autem': '366', 'falli': '389', 'putant': '159', 'vituperata': '268', 'delectus': '198', 'adolescens': '356', 'praesent': '331', 'putent': '334', 'feugait': '218', 'maiorum': '238', 'dolorem': '380', 'singulis': '165', 'vivendum': '176', 'ubique': '171', 'forensibus': '219', 'illum': '223', 'eam': '27', 'illud': '458', 'mediocrem': '146', 'voluptaria': '444', 'admodum': '117', 'postea': '157', 'deserunt': '66', 'adhuc': '181', 'wisi': '353', 'ut': '9', 'malis': '239', 'reformidans': '108', 'eius': '298', 'vidit': '175', 'ad': '1', 'mundi': '320', 'fugit': '89', 'an': '2', 'consetetur': '373', 'at': '5', 'pertinacia': '326', 'albucius': '357', 'constituto': '125', 'no': '6', 'quaeque': '420', 'ne': '12', 'nam': '26', 'mucius': '242', 'dignissim': '203', 'alterum': '360', 'convenire': '195', 'denique': '199', 'dicam': '292', 'quidam': '423', 'assueverit': '364', 'lorem': '234', 'suscipiantur': '344', 'dicat': '293', 'voluptua': '352', 'ullamcorper': '437', 'nominavi': '466', 'eos': '24', 'porro': '330', 'consectetuer': '49'}
# base 36 impl from wikipedia
# http://en.wikipedia.org/wiki/Base_36#Python_implementation
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Convert positive integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
# Special case for zero
if number == 0:
return alphabet[0]
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = - number
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def base36decode(number):
return int(number, 36)
def strict_code(code):
return hex(int(code))[2:]
def strict_str(code):
try:
return str(int(code,16))
except ValueError:
return code
```
## process.py - creates the encoding dictionary
```
#!/usr/bin/env python
from nltk.probability import *
from nltk.tokenize import *
from sets import Set
txt = open('lorem', 'r').read()
tokens = list(WordTokenizer().tokenize(txt))
freq = FreqDist()
for w in tokens:
freq.inc(w.lower())
tokens_sorted = sorted(freq, key=freq.get, reverse=True)
d = {}
star_count = 0
for i in tokens_sorted:
d[i] = str(star_count)
star_count += 1
print d
```
## First test case compressed
```
^M 8 6B 4F 2O, 1F 7A M C. ^BB 2H 18 2 10, 25 1P AG 13 D. ^I 1G 92 1, 7 8R 3Q S. ^0 11 5M 9D 9J. ^M 2 2O B1.~^5 Z 4N 5H 1D, M 9F 19 1. ^5 2V 1G 3E E, AU 1Z E 3. ^5 7Q 22 2K H, T 4V AO 0, W 7 5K 3Y. ^9Z 2M G 8, T 7 3C 1A.~^1P 4P 3M 6 O, I 4O 4P 4G 4, 1H CJ 57 S 1. ^1R 1A P 3, B J 5R 4W 4Y. ^V 1 B6 AW 42, BQ 17 7B C X, 1J 2Q 18 0 G. ^7 4T 2U V. ^V 4 2D A3 3H.~^0 Z 17 6D 9G, 2 Q 51 3A, 0 77 6K BL R. ^6 16 31 M, Y 0 96 89. ^R 5 1Q 6D 58, C 49 2N Y. ^7 2B 3Y P. ^2R 17 2Y U 1, 2A 2E 7A W 3.~^4J 7O L C. ^6 T 8V 6W 7Y, 1 3W D4 P, 1B 1L 43 N 9. ^4 CK 7P 4E S, N 4 4T 7O. ^D 12 6X 4J CM, X 1F 9G 9. ^G C9 4X C, V 67 5U 2N 1. ^7 W AN 5H 37, 66 4W 3P P 4.~^V 6D 2L 78 6, 2R 6F 4 H. ^A 3W 2A 8D X. ^0 O 76 1D. ^CX 3S R 3, 2 16 3P L, 5 Y B7 5D. ^U 1 3U AI BY, 4 49 43 8Q X. ^1B 1S 24 X K, 1Q 6A 2L L 8.~^E 1 5V 2Z 9J. ^K S 6A AQ 7U, 2H 7K 7X 1 J. ^2H 75 1D Q 1. ^4T 78 3E B L, 51 2L B 11, 4K 5B 41 D S. ^0 5C 7H G, 1H 9J X 7.~^11 6L 46 A. ^5 U 9P BI 23, O 2U 6W 2. ^X 3 2D 4Q 3F, M 5L 3R 0, B5 B9 2 Z. ^60 3K 4 X, V K 9Q 8O 2Y. ^P 5 7S 2N 7X. ^G B 35 98, 8W 3V B 15.~^2 V 4S 95 5E, J 0 5R A3. ^P 0 1B 27. ^E BW AH 5, 1A 3Q Q 2. ^25 8P 1L T A, I 7Q 6X 5.~^Q 8 39 3G 55. ^42 4H T 1. ^1 11 24 AL 2C. ^9 P 8A DA 9N, E K 6C 8I, 3 G 1Y 2U 7J.~^4N 2P L A, 54 8T 3 E. ^93 9W 88 K E, C 83 1R 44 E, D7 17 4G Y D. ^13 D 7D AQ 63. ^V 2 C2 5J 3Y, 51 5G B G. ^3 16 5D 1D L. ^8G BO I 7.~^M 4 6A 16 7W, 3 E 2A 3M, J 2 5M 2S. ^8J B9 V 1. ^74 7K O D, 2 2G 5N 3H Y. ^1B 62 1M T 9, 1N 73 CB B G, X C 1E 7H. ^R 1 2J 9U, 49 AE A S, B 9R 5F 3A 13. ^Q 26 61 2, M A 50 3V BF.~^5 16 41 27 10. ^5X 1R 7K 5 G, A 15 1J CN 9S. ^11 6J 2K 7K D, 12 7M 4S 19 K. ^0 6P 6T 27 R, 1U 9C 8N 3 Z. ^N 0 5V CB A2, S 5H 2X 4.~^2Z 5U F 1. ^2 I CS 1T, 7L 1T J 8. ^7I 3F 7T W 1. ^R 8 9E 19. ^F 3T 3N 2, 2Q 2Y F 4. ^H 5 7Z 3Y, A 1O 57 A4 W, I 25 2L A.~^0 9B 9A G, X 5 72 2K 3N, 4 F 6U 22. ^9 4W AX T, W 1 2T 71 AB. ^E 85 60 6F 6. ^51 7F BX A H, M 4 7Z BN.~^A L 47 6E. ^8X 6S 5Y 2 12, 93 4C B Q. ^1 I 7N 1V 33, 1 13 36 2P 27. ^4 9U 97 10. ^L 0 5A 3W, M 9X 56 6. ^7 5I 75 Q.~^7M 2T 0 Q, AK 2W 4B U 8. ^7N 1I 92 12 8, 9S 2W F 4. ^V 7 5T 1I 64, 14 66 9L 6. ^O 2 4V 4S, 74 5C P 4.~^5 O 25 2Q, 15 62 1V 0, 3G 2X 10 9. ^9G 38 58 M 7, 11 B 84 BL 52. ^2D 41 F 1. ^K 7S 7P F.~^3 7Q 30 T. ^4 G 4F 89, Q 1E 1I D2 K. ^B Z 3S 7V. ^5 AY 23 Q, 4Q 23 6E T 2, E 8 A7 5J 82.~^9L 94 8 E. ^B 62 8K U. ^S 3 67 6I 1R, BS 26 L 7, B3 3E K H. ^72 3D 30 10 2, A 45 83 22 F.~^4N 6R 5 L, 12 D 65 3Z AA. ^K M 60 6C, 9 4V 88 3A N. ^D V 5W 4G. ^H 1 5I 52 79, S 4 34 C0. ^36 7X 30 L 9. ^P 3D 1V 5. ^Q 1E 70 1.~^6 12 1Q 3L, 5P 77 49 2 13. ^7R 2A 3E 5 W, 8 BH 5O 55 T, 8W 1B 0 N. ^DC 5V 9T 6 H, V 26 3V A. ^2 7O 2P 32 E. ^D 38 6W M.~^16 50 31 A 10, X 3 5Q DG 9F, A8 99 0 11. ^3I 7J B H, 5B D1 5S 6 P. ^E A 6U 2O, E 1J 62 5S 6. ^I 2 6N 35, 1W 28 9 U, J 34 8C A. ^Z 4D 37 7C 1, L 6 5K BZ 9M.~^7W 2Y Z 0. ^4M 4H U 5, 0 15 2V 9V 63, 2D 4G P 4. ^AH 2E F 3, 0 15 91 6O 1T, 3 N 2G 6Z. ^U K 1J 4K 46, 3 H BD DF AJ, 11 D D6 1H.
```
Sources in [my github repo](https://github.com/Ramblurr/CodeGolf/tree/master/lorem).
[Answer]
## A simple but good JavaScript compressor (ratio=0.312)
Averaging the three test cases together, this program can reduce Lorem Ipsum text to 31.2% of its original size by converting each word to a base-36 number (**[demo page](http://jsfiddle.net/qYfCL/24/)**). I optimized my dictionary for the test cases, but the output from lipsum.com is not much less compressible if I also include its words in the dictionary.
### Example output for test case 3
>
> `@U6r8f36A!@9a1va6XH)K456m2w10)SD2fc28v!@6125VC)8u1g19D)Q7s9n9c16!@F17886g64!@3o2g6fYD!##@117o8q%)BXal2c2v)(Z3nbw4l!@c6377eMA!@IE1c2523)IC1s4y8k)C156q8k4p!@HJ1y75)%265y14)324fVQ!##@C4g6f2tU)&133i1n!@1s3o1gT&!@279lNF)b6ar56CJ!@F2s4qY!@G4m4q18)Ac5biY!##@DO4b5b!@137y5iB!@L^3f4k!@Y1pcb2tD)IA1m6k!@9r7aawH1a)GYaz2o)^Z1q5g4t!##@3m7kaaFN!@(61bm3tN)4vbmDU!@5k6bcpR*!@7v2tSF)173a7t76H)18H1w42!@A3c7q49R)D1c2q2iN)C3h8oV!@PDbe2j)15K1zcb!##@881db3Y()7u51OC!@6q2458PA!@153a385xB!@4h2aB15!##@at1g1n(Y)4a4j%M)cf291u^12!@E5p2411!@5v2j18^)L6t6o7nD!@155v1q3wC)H1h93W!@akc7DN)12&2q98!@1637574d^!##@UB1j1i!@1t2q6x&O)^S335s2n)428h2lGI!@J^26717v!@5j8bGL)I&ca3z)*161i5x1f!@UK4s7k39)18998y8k%)O3y2eD!@27a8aiX(!##@E3h4kO!@1e3g7xM*!@a926EL)173d6163D!@C4m5nI!@C6e46T)3x2bWA!##@*271s7kT)3o1d7jHS!@%1a6z1m!@633e8z^U!@O4j918eC!@KZ1w1q)G16675z2i!##@Dc58174U)B8d9411)W2s61F!@H48bpc01a!@16*1pb1)N4o2jG!@601rJF)O(afam42!@3s2xIK!##@A4b2a3uR!@U*4m9y!@M&1ib890)3r6v5b13C!@898w2bW&!@1c4yd5A11)5h3ybyPK!##@M(2y1v2r!@%2aag7zZ)S8x5m2kE!@MD6020)L7t1nQ!@*452g7aX!##@171w8l77E)16&2c3z4r)Eap897rJ!@5y3766UQ)5dcdX^!@956j1m^17)9197bc%16)O43a7K!@956f14E)*265u36Y!@19D923gbb)BI5w4o)&81d38wZ!@6q1nA12!##@ZK1w1b)F18bo3v!@7u2814%!@14&23ab39)a53aE12)111s587hG!@(3x7j6e18)9e8l6jA19)P5p7pH!@O7c23C)U6ibgbcE)H1a3g9u6o!@az3s7717C)IGcy2p!##@I2h294d(!@T1oa1()Yajbt6oE!@HT3b70)289iGL!@4y6x2o18A!##@XH1t29)D146u2ab3!@bnc319^)J*a71l8p!@G153q23!@G151gae52)1t73NK!##@BYa33y!@17B2dcd)Pca3s&!@K4ibv85W)P726bbk%)OCb75z1n!@(133c9d41!##@UF1h23!@ad5010^)9p1f15A)K11988e!@8y3x8iI%)CY2u3d4i!@C8s2s7gJ)Z^23319c!@^4j6z6kM)&X267b6e)1k3a43IH!##@1g1lF10)(1d4d14!@&1o4aW!@IF3m2c3l)2mbz9bQ13!@9x6pCM)&d24w15)K181c4a2a!@O6xan46G)RH6s8c!##@1b9z(13)1q487zGI!@5e2j4dDM!@C1j4051T)b978MQ!@6h5h5mC16)B272x19!##@1a7d4aB!@8m2zR^)%622eL!@4v3917G)&X1n522l!@5c2t12%!@17723kE)%6n8j13)%Tav8r!@1t9f2c11(!@1aQ2scz9h)E1y9oZ!##@9j87Q18)1h999zAY)8n514rUD!@LDas8b48)1z4a7b10D!@1126ax1lB)A3k864r1a)67b9BJ!@FM23dg!@U403pG)7730HV!@&123c32!@FN2f6y!##@Q4570R)7d7fA13!@Acv4z561a)FL3wba39!@RB6cdd7i)G218g12!@2hbrBW)Y5w55avG)1v4614QA!`
>
>
>
---
### Code listing
HTML page
```
<textarea id=dict>
in
an
ad
ex
ea
at
no
te
ut
et
eu
ei
ne
quo
pri
cu
vix
qui
vis
has
pro
id
per
eum
eos
duo
nam
usu
ius
eam
vel
sed
sea
mel
mea
vim
nec
cum
sit
mei
his
est
perfecto
vitae
oratio
nemore
inciderint
facilisi
tota
tollit
reque
quis
qualisque
placerat
persecuti
minim
melius
iisque
erroribus
error
dicit
consectetuer
atomorum
zzril
voluptatibus
virtute
sonet
quodsi
ponderum
oporteat
omnesque
oblique
mentitum
meis
mazim
errem
dissentiet
deserunt
cotidieque
consul
choro
vulputate
stet
soluta
sint
signiferumque
sadipscing
reprimique
reformidans
rebum
quaerendum
persequeris
perpetua
partem
oportere
omnium
ocurreret
nulla
molestie
moderatius
malorum
invenire
intellegebat
intellegam
inimicus
inermis
graeco
fugit
fabellas
efficiendi
dolores
dicta
comprehensam
cibo
aperiri
alia
vocibus
vivendum
vidit
vidisse
vero
veritus
ubique
timeam
tempor
tantas
summo
solet
singulis
simul
saepe
ridens
repudiandae
rationibus
putant
principes
postea
petentium
patrioque
ornatus
officiis
nostro
nonumy
nominati
nisl
neglegentur
mnesarchum
mediocrem
mandamus
iuvaret
iusto
intellegat
instructior
homero
gubergren
graeci
feugiat
fastidii
equidem
electram
efficiantur
duis
dissentiunt
detraxit
deseruisse
democritum
definitionem
decore
constituto
ceteros
blandit
appellantur
animal
altera
affert
adversarium
admodum
adipiscing
volutpat
voluptatum
vivendo
vituperatoribus
vituperata
verterem
tractatos
tibique
theophrastus
takimata
suavitate
similique
scriptorem
scripta
regione
referrentur
quando
primis
possim
posidonium
persius
pericula
option
omnes
omittantur
omittam
nullam
nostrum
nobis
nihil
mucius
meliore
maluisset
malis
maiorum
magna
luptatum
ludus
lorem
lobortis
libris
legere
legendos
laudem
latine
kasd
justo
iudicabit
impedit
illum
ignota
hinc
fuisset
forensibus
feugait
facilisis
facer
fabulas
explicari
esse
erat
enim
elitr
elit
elaboraret
eirmod
doming
dolor
docendi
dignissim
dictas
dico
diceret
denique
delectus
debitis
corpora
convenire
consequat
conceptam
civibus
cetero
atqui
assentior
argumentum
apeirian
antiopam
ancillae
aliquam
aeterno
adipisci
adhuc
accusata
accusam
accommodare
wisi
voluptua
veri
veniam
velit
utroque
utamur
torquatos
suscipit
suscipiantur
splendide
soleat
sensibus
semper
scripserit
sapientem
saperet
recusabo
quot
putent
propriae
prompta
praesent
porro
platonem
phaedrum
pertinax
pertinacia
percipit
paulo
offendit
noster
nibh
mundi
mollis
molestiae
liberavisse
laboramus
ipsum
interpretaris
integre
insolens
honestatis
hendrerit
habeo
gloriatur
fierent
facilis
exerci
essent
eruditi
eros
eripuit
epicuri
epicurei
eius
dolorum
dissentias
disputationi
dicunt
dicat
dicam
diam
delicatissimi
delicata
deleniti
delenit
definitiones
definiebas
corrumpit
consulatu
constituam
concludaturque
commodo
augue
assum
aperiam
aliquyam
agam
aeque
abhorreant
voluptaria
volumus
viris
viderer
vide
verear
unum
ullamcorper
tritani
tation
sumo
senserit
scribentur
scaevola
salutatus
salutandi
sale
repudiare
reprehendunt
recteque
quod
quidam
quem
quas
quaeque
prodesset
probo
probatus
philosophia
omnis
numquam
nostrud
noluisse
necessitatibus
mutat
munere
modus
modo
menandri
mediocritatem
maiestatis
lucilius
liber
laoreet
labore
labitur
iriure
interesset
indoctum
incorrupte
inani
imperdiet
habemus
graecis
ferri
falli
facete
expetendis
expetenda
euripidis
etiam
erant
eloquentiam
eligendi
dolorem
disputando
discere
dicant
detracto
debet
contentiones
consetetur
congue
complectitur
commune
clita
causae
brute
autem
audiam
assueverit
appetere
appareat
amet
alterum
aliquip
aliquando
albucius
adolescens
accusamus
accumsan
vocent
urbanitas
temporibus
tamquam
tale
suas
solum
sententiae
quaestio
puto
prima
postulant
possit
posse
percipitur
partiendo
odio
nusquam
nominavi
natum
movet
minimum
iudico
iracundia
invidunt
impetus
illud
graece
evertitur
euismod
eleifend
dolore
doctus
copiosae
consequuntur
conclusionemque
bonorum
audire
aliquid
alienum
non
eget
ac
a
vestibulum
nunc
mauris
tincidunt
pellentesque
ante
donec
turpis
orci
massa
arcu
ultrices
luctus
neque
tortor
dui
metus
posuere
leo
ligula
libero
sem
nisi
quam
sapien
risus
mi
faucibus
purus
consectetur
malesuada
urna
tellus
lectus
felis
egestas
porta
varius
tristique
lacus
dictum
convallis
rutrum
morbi
rhoncus
aliquet
sodales
viverra
sollicitudin
tempus
suspendisse
lacinia
interdum
scelerisque
fusce
fringilla
sagittis
pretium
cursus
auctor
condimentum
ultricies
elementum
gravida
pulvinar
porttitor
pharetra
vivamus
integer
bibendum
vehicula
iaculis
fermentum
proin
ornare
mattis
cras
curabitur
aenean
quisque
phasellus
venenatis
maecenas
dapibus
curae
cubilia
torquent
taciti
sociosqu
nostra
litora
inceptos
himenaeos
conubia
class
aptent
platea
hac
habitasse
dictumst
senectus
netus
habitant
fames
everti
sociis
sanctus
ridiculus
penatibus
parturient
nonummy
natoque
nascetur
mus
montes
magnis
dis
utinam
ullum
harum
alii
potenti
populo
legimus
idque
periculis
novum
labores
deterruisset
enean
</textarea>
<textarea rows=25 cols=80 id=box></textarea>
<button id=comp>compress</button><button id=decomp>decompress</button>
```
Source code (uses jQuery 1.5.2)
```
var $box = $('#box'),
dict = $('#dict').val().split(/\n/g).filter(function(v) {
return v.length;
}),
CODE = {
COMMA: 0,
FULL_STOP: 1,
SHIFT: 2,
NEWLINE: 3,
UNCOMP: 4,
FIRST_WORD: 5
},
base36UpperAlphabet = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function compress(orig) {
function writeCode(n) {
if(n < 36) {
comped += base36UpperAlphabet[n];
} else {
comped += n.toString(36);
}
}
function writeUncompressed(d) {
comped += d;
comped += '.';
}
function writeCurrentWord() {
if(word) {
// look up word in dictionary
var wordIndex = dict.indexOf(word), shift = false;
// try lowercasing first letter
if(wordIndex < 0) {
shift = true;
wordIndex = dict.indexOf(word[0].toLowerCase() + word.slice(1));
}
if(wordIndex < 0) {
writeCode(CODE.UNCOMP);
writeUncompressed(word);
} else {
if(shift) writeCode(CODE.SHIFT);
writeCode(wordIndex + CODE.FIRST_WORD);
}
}
word = '';
}
var comped = '', word = '';
for(var i = 0; i < orig.length; ++i) {
var ch = orig[i];
switch(ch) {
case ' ': writeCurrentWord(); break;
case ',': writeCurrentWord(); writeCode(CODE.COMMA); break;
case '.': writeCurrentWord(); writeCode(CODE.FULL_STOP); break;
case '\n': writeCurrentWord(); writeCode(CODE.NEWLINE); break;
default: word += ch;
}
}
writeCurrentWord();
return comped;
}
function decompress(comped) {
function readCode() {
var c = comped[i++],
n = base36UpperAlphabet.indexOf(c);
if(n >= 0) return n;
return parseInt(c + comped[i++], 36);
}
function readUncompressed() {
var c, d = '';
while((c = comped[i++]) != '.') d += c;
return d;
}
var code, i = 0, shift = false, orig = '';
while(i < comped.length) switch(code = readCode()) {
case CODE.COMMA: orig += ','; break;
case CODE.FULL_STOP: orig += '.'; break;
case CODE.SHIFT: shift = true; break;
case CODE.NEWLINE: orig += '\n'; break;
case CODE.UNCOMP: orig += ' ' + readUncompressed(); break;
default:
var word = dict[code - CODE.FIRST_WORD];
orig += ' ' + (shift ? word[0].toUpperCase() + word.slice(1) : word);
shift = false;
}
return orig.slice(1);
}
$('#comp').click(function() {
var orig = $box.val(), comped = compress(orig);
$box.val(comped);
alert('ratio=' + (comped.length / orig.length).toFixed(5));
});
$('#decomp').click(function() {
$box.val(decompress($box.val()));
});
```
Command for generating a frequency-sorted dictionary
```
tr '[:upper:]' '[:lower:]' < lipsum.txt | tr -cs '[:lower:]' '\n' | sort | uniq -c | sort -rn | cut -c9- > lipsumwords.txt
```
[Answer]
## JavaScript, ≈ 11%
I can't figure out how to decompress it yet, but I think it is possible. I'll edit it when I figure out how, but if anybody here does before me, please tell me how!
This one can compress to ≈ 45%, but when run recursively settles down at ≈ 11% for the one I tried.
```
function liCompress(text, s) {
// Some variables used throughout the function
var c, i, result = [];
// First, we get the unique characters in the text.
var uniqueCharacters = '';
for(i = 0; i < text.length; i++) {
c = text.charAt(i);
if(uniqueCharacters.indexOf(c) === -1) uniqueCharacters += c;
}
// Add them to the string:
result.push(uniqueCharacters.length);
for(i = 0; i < uniqueCharacters.length; i++) result.push(uniqueCharacters.charCodeAt(i));
// Now we convert the base-x string to base-256.
var total = 0, exponent = 0;
for(i = 0; i < text.length; i++) {
c = text.charAt(i);
var n = uniqueCharacters.indexOf(c);
total += n * Math.pow(uniqueCharacters.length, i - exponent);
if(total > 255) {
result.push(total % 256);
total = total === 256 ? 0 : 1;
exponent = i + 1;
}
}
// Return the string representation of the result.
var r = String.fromCharCode.apply(String, result);
if(!s) {
var x = liCompress(r, true);
return x.length < r.length ? liCompress(r) : r;
}
return r;
}
```
] |
[Question]
[
Given a year and a month, find out the percentage of work days in said
month. Work days are Monday through Friday with no regard to holidays or
other special things. The Gregorian calendar is used.
**Input**
A year and month in ISO 8601 format (YYYY-MM). The year always has four
digits, the month always has two digits. The given year will not be before
1582.
**Output**
Output is the percentage of work days (according to above definition) in
the given month, rounded to a whole number. No percent sign or fractional
digits follow.
**Sample 1**
```
Input Output
2010-05 68
```
**Sample 2**
```
Input Output
2010-06 73
```
**Sample 3**
```
Input Output
1920-10 68
```
**Sample 4**
```
Input Output
2817-12 68
```
A week has passed, an answer has been accepted. For the curious, the sizes of the submissions we got in our contest:
>
> 129 – Z shell
>
> 174 – VB.NET
>
> 222 – C
>
> 233 – C
>
> 300 – C
>
>
>
As well as our own (unranked) solutions:
>
> 75 – [PowerShell](https://codegolf.stackexchange.com/questions/1158/percentage-of-work-days-in-a-month/1192#1192)
>
> 93 – Ruby
>
> 112 – Bourne shell
>
>
>
[Answer]
## 64-bit Perl, 67 ~~68~~
Perl 5.10 or later, run with `perl -E 'code here'` or `perl -M5.010 filename`
```
map{$d++,/^S/||$w++if$_=`date -d@ARGV-$_`}1..31;say int.5+100*$w/$d
```
Concessions to code size:
* locale-sensitive: it counts as work days the days whose `date` output don't start with a capital S. Run under `LC_ALL=C` if in doubt.
* output is pure and well-formatted, but there's "garbage" on stderr on months shorter than 31. `2> /dev/null` if upset.
* ~~for some reason, my version of `date` considers 2817-12 an invalid month. Who knew, GNU new apocalypse is due!~~ Requires a 64 bit build of `date` for dates after 2038. (Thanks Joey)
[Answer]
## PHP - 135
I made it in PHP because I had a [similar problem to treat](https://stackoverflow.com/questions/4963205/how-can-i-figure-out-the-number-of-week-days-in-a-month) a few days ago.
```
<?php $a=array(2,3,3,3,2,1,1);$t=strtotime($argv[1]);$m=date(t,$t);echo round((20+min($m-28,$a[date(w,strtotime('28day',$t))]))/$m*100)
```
(Somewhat) More legibly, and without notices about constants being used as strings:
```
<?php
date_default_timezone_set('America/New_York');
$additionalDays = array(2, 3, 3, 3, 2, 1, 1);
$timestamp = strtotime($argv[1]);
$daysInMonth = date('t', $timestamp);
$limit = $daysInMonth - 28;
$twentyNinthDayIndex = date('w', strtotime("+28 days", $timestamp));
$add = $additionalDays[$twentyNinthDayIndex];
$numberOfWorkDays = 20 + min($limit, $add);
echo round($numberOfWorkDays / $daysInMonth * 100);
?>
```
This is made possible by a very simple algorithm to compute the number of work days in a month: check for the weekdayness of the 29th, 30th and 31st (if those dates exist), and add 20.
[Answer]
**Python 152 Characters**
```
from calendar import*
y,m=map(int,raw_input().split('-'))
c=r=monthrange(y,m)[1]
for d in range(1,r+1):
if weekday(y,m,d)>4:c-=1
print '%.f'%(c*100./r)
```
[Answer]
## Windows PowerShell, 80
```
$x=$args;1..31|%{"$x-$_"|date -u %u -ea 0}|%{$a++
$b+=!!($_%6)}
[int]($b*100/$a)
```
[Answer]
# Swift, 346 bytes
Short version:
```
func f(_ s:String)->Int{let c=Calendar.current,m=Int(s.suffix(2))!,y=Int(s.prefix(4))!,mR=c.range(of:.day,in:.month,for:DateComponents(calendar:c,year:y,month:m).date!)!,n=mR.reduce(0){p,d in let d=c.date(from: DateComponents(year:y,month:m,day:d))!,w=c.component(.weekday,from:d);return(2...6).contains(w) ?p+1:p};return (n*1000/mR.count+5)/10}
```
Slightly longer version:
```
func f2(_ s: String) -> Int {
let c=Calendar.current
let m=Int(s.suffix(2))!
let y=Int(s.prefix(4))!
let mR=c.range(of:.day,in:.month,for:DateComponents(calendar:c,year:y,month:m).date!)!
let n=mR.reduce(0){p,d in
let d=c.date(from: DateComponents(year:y,month:m,day:d))!
let w=c.component(.weekday,from:d)
return(2...6).contains(w) ?p+1:p
}
return (n*1000/mR.count+5)/10
}
```
[Answer]
# D: 186 Characters
```
auto f(S)(S s){auto d=Date.fromISOExtendedString(s~"-28"),e=d.endOfMonth;int n=20;while(1){d+=dur!"days"(1);if(d>e)break;int w=d.dayOfWeek;if(w>0&&w<6)++n;}return rndtol(n*100.0/e.day);}
```
More Legibly:
```
auto f(S)(S s)
{
auto d = Date.fromISOExtendedString(s ~ "-28"), e = d.endOfMonth;
int n = 20;
while(1)
{
d += dur!"days"(1);
if(d > e)
break;
int w = d.dayOfWeek;
if(w > 0 && w < 6)
++n;
}
return rndtol(n * 100.0 / e.day);
}
```
[Answer]
## Python - 142
```
from calendar import*
y,m=map(int,raw_input().split('-'))
f,r=monthrange(y,m)
print'%.f'%((r-sum(weekday(y,m,d+1)>4for d in range(r)))*100./r)
```
Thanks to fR0DDY for the calendar bit.
[Answer]
## Ruby, 124 119 111
```
require 'date'
e=Date.civil *$*[0].split(?-).map(&:to_i),-1
p ((e+1<<1..e).count{|d|d.cwday<6}*1e2/e.day).round
```
Requires Ruby 1.9 due to splatting the year and month before the -1 "day" argument and `?-` for `"-"`. For Ruby 1.8, we must add 2 characters:
```
require 'date'
e=Date.civil *$*[0].split('-').map(&:to_i)<<-1
p ((e+1<<1..e).count{|d|d.cwday<6}*1e2/e.day).round
```
**Edit**: Shave five characters based on @Dogbert's help.
**Edit**: Shave eight more characters based on @steenslag's help.
[Answer]
# Bash + coreutils, 82 bytes
```
f()(cal -NMd$1|sed -n "s/^$2.//p"|wc -w)
dc -e`f $1 "[^S ]"`d`f $1 S`+r200*r/1+2/p
```
[Answer]
# PHP 5.2, 88 bytes
Although I already golfed [zneak´s solution](https://codegolf.stackexchange.com/a/1217/55735) down to 85 bytes (I just found one more), here´s my own:
I doubt that I can squeeze another three bytes out here.
```
$a=_4444444255555236666304777411;echo$a[date(t,$t=strtotime($argn))%28*7+date(N,$t)]+67;
```
takes input from STDIN: Run with `echo <yyyy>-<mm> | php -nR '<code>'`.
The string `$a` maps days per month (`date(t)`) and week day of the first day of the month (`date(N)`: Monday=1, Sunday=7) to the percentage of work days-67; `strtotime` converts the input to a UNIX timestamp; the rest of the code does the hashing.
+1 byte for older PHP 5: Replace `N` with `w` and `$a=_...;` with `$a="..."`.
another +3 bytes for PHP 4: insert `.-1` after `$argn`.
-5 bytes for PHP 5.5 or later (postdates the challenge):
Remove everything before `echo` and replace `$a` with `"4444444255555236666304777411"`.
[Answer]
# C#, 158 bytes
```
s=>{var d=DateTime.Parse(s);int i=0,t=DateTime.DaysInMonth(d.Year,d.Month),w=0;while(i<t)w-=-(int)d.AddDays(i++).DayOfWeek%6>>31;return Math.Round(1e2*w/t);};
```
Anonymous method which returns the required percentage.
Full program with ungolfed, commented method and test cases:
```
using System;
class WorkingDayPercentage
{
static void Main()
{
Func <string, double> f =
s =>
{
var d = DateTime.Parse(s); // extracts a DateTime object from the supplied string
int i = 0, // index variable
t = DateTime.DaysInMonth(d.Year, d.Month), // number of total number of days in the specified month
w = 0; // number of working days in the month
while (i < t) // iterates through the days of the month
w -= -(int)d.AddDays(i++).DayOfWeek%6 >> 31;// d.AddDays(i) is the current day
// i++ increments the index variable to go to the next day
// .DayOfWeek is an enum which hold the weekdays
// (int)..DayOfWeek gets the days's index in the enum
// note that 6 is Saturday, 0 is Sunday, 1 is Monday etc.
// (int)DayOfWeek % 6 converts weekend days to 0
// while working days stay strictly positive
// - changes the sign of the positive numbers
// >> 31 extracts the signum
// which is -1 for negative numbers (working days)
// weekend days remain 0
// w -= substracts the negative numbers
// equivalent to adding their modulus
return Math.Round(1e2 * w / t); // the Math.round function requires a double or a decimal
// working days and total number of days are integers
// also, a percentage must be returned
// multiplying with 100.0 converts the expression to a double
// however, 1e2 is used to shorten the code
};
// test cases:
Console.WriteLine(f("2010-05")); // 68
Console.WriteLine(f("2010-06")); // 73
Console.WriteLine(f("1920-10")); // 68
Console.WriteLine(f("2817-12")); // 68
}
}
```
Alternative function, which adds negative values to the number of working days, changing the sign in the return with no extra byte cost:
```
s=>{var d=DateTime.Parse(s);int i=0,t=DateTime.DaysInMonth(d.Year,d.Month),w=0;while(i<t)w+=-(int)d.AddDays(i++).DayOfWeek%6>>31;return-Math.Round(1e2*w/t);};
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 55 [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.
```
⌊.5+100×2÷/(2 5)2{≢⍎⍕↓⍺↓¯2⌽' ',cal⍎' '@5⊢⍵⊣⎕CY'dfns'}¨⊂
```
`⊂` enclose date to treat it as a whole
`(2 5)2{`…`}¨` apply the following function on that, but with the left arguments `[2,5]` and `2`:
`⎕CY'dfns'` copy the "dfns" library
`⍵⊣` discard the report in favour of the date
`' '@5⊢` replace the 5th character (`-`) with a space
`⍎` execute that to get two-element list
`cal` call the calendar function on that
`' ',` prepend a column of spaces to that
`¯2⌽` rotate the last two columns (Saturday) to the front
`⍺↓` drop left-argument number of rows (2, headers) and columns (if specified; 5=Sat+Sun)
`↓` split matrix into list of lines
`⍕` format (flattens with insertion of double-spacing)
`⍎` execute (turns remaining day numbers into a flat numeric list)
`≢` tally those
`2÷/` divide each pair (there's only one)
`100×` multiply by a hundred
`.5+` add a half
`⌊` floor
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPl56ptqGBweHpRoe362sYKZhqGlU/6lz0qLfvUe/UR22TH/XuApKH1hs96tmrrqCuk5yYA5QDshxMH3UBlW191LX4Ud9U50j1lLS8YvXaQysedTX9T3vUNgFkRN9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P9p6kYGhga6BqbqXDCmGYhpaGlkoGtoABa1MDTXNTRSBwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Go](https://go.dev), 243 bytes
```
import(."time";."math")
func f(s string)int{t,_:=Parse("2006-01",s)
D,o:=Hour*24,0.0
y,m,_:=t.Date()
d:=Date(y,m+1,0,0,0,0,0,UTC).Add(D).Sub(t).Hours()/24
for;t.Month()==m;t=t.Add(D){if w:=t.Weekday();0<w&&w<6{o++}}
return int(Round(100*o/d))}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVHBbhMxEBVXf4VlKZWn8brepaQhySJVRIgLUkVBHKBql9ibWs3a0e5soyrKl3CJkPio8hv8APYuVArYBz8_z7x54_n2fen3j7N1sbgrloZWhXWE2Grta5SsrJA9XRqsrVs2B8TCu3v2o8UyGT_-6nkuGdrKsKlkVYG3DEjZugUteUN7BbAOtyiuJ_lFUTeGs0ypUaJSJhogc-En-Vvf1sfZqVBSkQdRxVCU8wINB6IneYcCP0yFetofP7wGea41n4O8bL9yBBllGg4n2SkpfT1F-c47vOWQ59UUg2IfvbUl3cQCn4y508UDh6mabY6ONrPR1g-Hux2pDba1o8E2f-9bp3mq1LE_0QC7vvWfz7Kux_h5HOiWWLdusaGTnN5kKlWJekEP1mhMen50yJ89J-nLTCWp-j9-nJ4lafYvfxNbo9diZZ2J9erChSlerlcWee9CsC-ORVOlNSvdmXrTIR5zIHgV1Ee2f_-srsRfmF4R34ZJxddz9JZ7IEuPXXBQB3IR5oklZ4OGJq8oH2igAx3Oewg1Be2kgwANSR2ieR4xkB3583X7fX_-Bg)
Loops through the days of the month and checks each for being a weekday (between `0=Sunday` and `6=Saturday`).
[Answer]
# Rebol - 118 113
```
w: b: 0 o: d: do join input"-01"while[d/2 = o/2][if d/7 < 6[++ w]++ b d: o + b]print to-integer round w / b * 100
```
Ungolfed:
```
w: b: 0
o: d: do join input "-01"
while [d/2 = o/2] [
if d/7 < 6 [++ w]
++ b
d: o + b
]
print to-integer round w / b * 100
```
[Answer]
# Oracle SQL, 110 bytes
```
select round(100*sum(1-trunc(to_char(x+level-1,'d')/6))/sum(1))from dual,t connect by level<=add_months(x,1)-x
```
It works with an assumption that input data is stored in a table in using `date` data type, e.g.
```
with t as (select to_date('2010-06','yyyy-mm') x from dual)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 78 bytes
```
{round 100*@_.grep(6>*.day-of-week)/@_}o{Date.new("$_-01")...^*.month-*.month}
```
[Try it online!](https://tio.run/##VcpBCsIwEEDRvacIQSQNzDhTMCqidOE5DIGmFrRNqZUSSs8eXbioqw@P3/n@aVITxaYSZ5GmPrzbUjCRLizee98pc9FYugihgtH7R7Yt7Bymqxs8tn5Ucm2BWGaIeNPYhHao4dc5vVwUlZI5MQHtZHZa/YlZCB9zAqblc@A9cP6V9AE "Perl 6 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~36~~ 34 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
HÆÐU+XnÃf@¤¤ÅɶXÎÃme
èÈ©n6Ã*L/UÊ r
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=SMbQVStYbsNmQKSkxcm2WM7DbWUK6MipbjbDKkwvVcogcg&input=IjIwMTAtMDYi)
Not pretty at all! Needs more work.
## ~~34~~ 32 bytes
2 bytes can be saved by always rounding down as the challenge doesn't specify that we must round to the nearest integer:
```
HÆÐU+XnÃf@¤¤ÅɶXÎÃme
èÈ©n6ÃzUÊ/L
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=SMbQVStYbsNmQKSkxcm2WM7DbWUK6MipbjbDelXKL0w&input=IjIwMTAtMDYi)
[Answer]
# Bash + ncal, ~~75~~ 70 bytes
```
m=`ncal ${1#*-} ${1%-*}`
set $m
wc -w<<<${m%%Sa*}|dc -e ?7-A0*$#\ 9-/p
```
We start by using `ncal` to print a calendar:
```
May 2010
Mo 3 10 17 24 31
Tu 4 11 18 25
We 5 12 19 26
Th 6 13 20 27
Fr 7 14 21 28
Sa 1 8 15 22 29
Su 2 9 16 23 30
```
The total number of days in the month is the word-count of this output, minus 9 (the seven weekday names and the month and year of the header). This word-count is obtained using `set` and `$#`.
The number of work days is a similar calculation, but we first eliminate everything from `Sa` onwards (we can't just match `S` because the month may be `Sep`), and subtract only 7 surplus words. We count this using `wc`.
We then use `dc` to compute a percentage (using `A0` as short form of `100`).
Note that this program rounds fractional percentages downwards - the question's examples appear to use a different choice for the rounding, but it didn't impose a specific direction. Rounding to nearest would cost an additional 7 bytes by executing `$#\ 2/+` before we divide by the total: `?7-A0*$#\ 2/+$#\ 9-/p`.
[Answer]
# [Scala](http://www.scala-lang.org/), 152 bytes
A port of [@adrianmp's C# answer](https://codegolf.stackexchange.com/a/111902/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##dY9Pa8JAEMXv@RSDp91K4q6l0UZXKHgVD6UtpZQymk1cGxPZHRURP3u62xZa@uc27/3eMG/cEitszWbbWII17jEhs9HJS/TLIh0crDyLmsVaLwlmaGo4RQC5LmDjBUNbugxurMXj0y1ZU5fPPIO72hAon/RR2GMFRcY@qJpMm92i0ly1Tk1OgeXq6@ajRjtralolW7ROM8dHIUIqTypdl7SaF@/YuxYOSoyKxjIzjgVQAxRLbgqWJ0hTPDLTlTwpdZjnxYPWr0HcY7XT45QfukqOZugP2WZX50wKkYiLQ4/4ufWdodcD0o5giU67LLwBW9@fqpoVrNMXUsTiqsN5CKbDv3n6yQeXP7m87otYiv/3h3IQy/53fo7O7Rs)
```
s=>{val d=java.time.YearMonth.parse(s);val t=d.lengthOfMonth;var w=0;for(i<-0 to t-1)if(d.atDay(i+1).getDayOfWeek.getValue<6)w+=1;Math.round(100.0*w/t)}
```
Ungolfed version. [Try it online!](https://tio.run/##dZHRTsIwFIbv9xQnXJBNstFiBF0YCQkx8WKSaNQQY8yBdaMwNtJ2GGJ49tmxOYfi1XrO9/3taScXGGOe8802FQpWuENH8Q1z3o0/LcWKDsaaGel8xRYKfOQJfBoAAQthowsTRSRdGAuB@9dHJXgSvVkuPCVcgXc0AXYYQ@hCScEbwSTN5jHTXBZVKZVaoJszhsJPE7V0tigkM6XVEFSqMJ7gXichcGKWRGo5DY96bQn4SMVan1V5xKhQmAowOQxtIJAlije2s@oxqkFwPw1fGFsfz0GlHZ3sALWciBVVSesMD8GsM4XyjHHGYORB7Tr@9H4ynv3AdhvORIbNyO3DXTPSnBJObtnxgNboYHx/q4WP@jVFmiWBSQlxCFychLuNdzAawa4GTCpYoGTSPba2@h@qODFDs9UjlNjkqmVZhdi/Ps/7FR9c/ub0pkdsSv7PX9OBTXtNfjAOef4F)
```
import java.time._
import java.time.temporal._
object Main {
def main(args: Array[String]): Unit = {
val f: String => Double = s => {
val d = YearMonth.parse(s)
val totalDays = d.lengthOfMonth
var workingDays = 0
for (i <- 0 until totalDays) {
val dayOfWeek = d.atDay(i + 1).getDayOfWeek
if (dayOfWeek.getValue >= DayOfWeek.MONDAY.getValue && dayOfWeek.getValue <= DayOfWeek.FRIDAY.getValue) {
workingDays += 1
}
}
Math.round(100.0 * workingDays / totalDays)
}
// test cases:
println(f("2010-05")) // 68
println(f("2010-06")) // 73
println(f("1920-10")) // 68
println(f("2817-12")) // 68
}
}
```
[Answer]
# GNU date+bc, 56 bytes
## Abstract
This Answer demonstrates that the following 56-byte shell pipeline
calculates the percentage of work days in a given month, rounded to
the nearest whole percent:
```
date -d$1-1month-4week +'70+%d-3*(%w+1<%d)-3*(%u<%d)'|bc
```
## Analysis
There are 28 possible monthly calendars, that can be identified
according to the last day/date of the month:
| | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **28th** | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 |
| **29th** | 21/29 | 21/29 | 21/29 | 21/29 | 21/29 | 20/29 | 20/29 |
| **30th** | 21/30 | 22/30 | 22/30 | 22/30 | 22/30 | 21/30 | 20/30 |
| **31st** | 21/31 | 22/31 | 23/31 | 23/31 | 23/31 | 22/31 | 21/31 |
There are nine distinct fractions here, that can be converted to
percentages:
| | 20 | 21 | 22 | 23 |
| --- | --- | --- | --- | --- |
| **28** | 71 | | | |
| **29** | 69 | 72 | | |
| **30** | 67 | 70 | 73 | |
| **31** | | 68 | 71 | 74 |
Substituting these gives our conversion table:
| | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 28th | 71 | 71 | 71 | 71 | 71 | 71 | 71 |
| 29th | 72 | 72 | 72 | 72 | 72 | 69 | 69 |
| 30th | 70 | 73 | 73 | 73 | 73 | 70 | 67 |
| 31st | 68 | 71 | 74 | 74 | 74 | 71 | 68 |
The pattern becomes more clearly evident when we split this into a
basic value for a month containing four weekends, less an amount for a
fifth Saturday and for a fifth Sunday:
| | Basic | Thu | Fri | Sat | Sun | Mon | Tue | Wed |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 28th | 71 | . . | . . | . . | . . | . . | . . | . . |
| 29th | 72 | . . | . . | . -3 | -3 . | . . | . . | . . |
| 30th | 73 | . . | . . | . -3 | -3 -3 | -3 . | . . | . . |
| 31st | 74 | . . | . . | . -3 | -3 -3 | -3 -3 | -3 . | . . |
The basic value is clearly 71 plus one for each day more than 28 days.
And we must then subtract 3 if the last day is in a range beginning
Saturday and having length equal to those excess days, less three for
a similar range beginning Sunday.
## Implementation
Firstly, we append a day number to turn year and month into a full
date: `$1-01`.
Rather than finding the *last* day of the month, we select a date
nearer the start of the month, by subtracting 28 days from the start
of the following month. This gives us a day-of-week that's one later
than used in the analysis section:
```
date -d'$1-01 +1month-4week'
```
Using this date, we then format a calculation for `bc` to execute and
print. The basic percentage is simple; it's just 70 more than the day
number we landed on: `70+%d`.
The adjustments for extra weekend days are then computed using a pair
of inequalities, taking advantage of the fact that there are two
representations for day-of-week, with Sunday represented as 0 or
as 7. We subtract 3 points from the basic percentage for each of
those inequalities.
## Demo
We can reproduce the results from the examples in the question:
| Command | Result |
| --- | --- |
| [`./1158 2010-05`](https://tio.run/##S0oszvj/PyWxJFVBN0XFUNcwNz@vJEPXpDw1NVtBW93cQFs1RddYS0O1XNvQRjVFE8wuBbHUa5KS////b2RgaKBrYAoA) | 68 |
| [`./1158 2010-06`](https://tio.run/##S0oszvj/PyWxJFVBN0XFUNcwNz@vJEPXpDw1NVtBW93cQFs1RddYS0O1XNvQRjVFE8wuBbHUa5KS////b2RgaKBrYAYA) | 73 |
| [`./1158 1920-10`](https://tio.run/##S0oszvj/PyWxJFVBN0XFUNcwNz@vJEPXpDw1NVtBW93cQFs1RddYS0O1XNvQRjVFE8wuBbHUa5KS////b2hpZKBraAAA) | 68 |
| [`./1158 2817-12`](https://tio.run/##S0oszvj/PyWxJFVBN0XFUNcwNz@vJEPXpDw1NVtBW93cQFs1RddYS0O1XNvQRjVFE8wuBbHUa5KS////b2RhaK5raAQA) | 68 |
And we can show that we get the correct [results for all 28 shapes of
month](https://tio.run/##RVBBasMwELz7FQOJcFNnzUpOmxb6i54KvSiW3JgkUrBl0hLn7arsFLqw7MweZpjZ6X4fF3i3R1sHeGdx8i7s4RtYXe9xtO4rUe0MrDNk9A8a3yHYPmTZhFq0DsuHc9e60CAX/afLofh6ZS5Lrm505aospbqt54/a3IhVWlnMRiQnyTHD/xgdLKghFLn4IHESQRiIAULnGNH7LoAOal2BhsTrIdFGrjLjZ5HeBizbeBcxS0ny7rO5WHtIklsuhKHq8UFcCvkmzGrGw4TycVdHM3UwouvB2AKLKe5Jh5QyeGgEvTtaJJh@qR4/dLDf59SdDq13MSqWTPz0d5@jfFVMkqN6kVuS6hc)
shown in the first table:
```
for i in $(printf '%s\n' 20{{00..03}-{03..12},{00..24}-02}-01+month-1day |
date -f- +'%Y-%m%t%d %u %a' | sort -k2,3 -u | cut -f1)
do ./1158 $i
done | rs 0 7
```
```
71 71 71 71 71 71 71
72 72 72 72 72 69 69
70 73 73 73 73 70 67
68 71 74 74 74 71 68
```
] |
[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 3 years ago.
[Improve this question](/posts/339/edit)
Let's suppose you have a complete binary tree (i.e. each internal node has exactly two non empty descendants). Each node contains a nonzero integer. You are given the task of encoding and decoding the tree into/from a list of integers.
The tree is stored internally something like:
```
struct node {
int data;
struct node *left, *right;
};
```
And you have to implement two functions:
```
int *encode(struct node *root);
struct node *decode(int *array);
```
It is up to you how you encode and decode.
Points for:
* minimum encoding length
* complexity (ideally linear in number of nodes)
* originality
No points for source code length and you are not restricted to C.
Tree example:
```
5
/ \
3 2
/ \
2 1
/ \
9 9
```
[Answer]
This Haskell program encodes a tree of n nodes in n Integers. The trick is that it encodes the node's data doubled, and then uses the lower-order bit to indicate if this is a leaf node, or an interior node.
Technically, the `Parser` monad here is over-kill, since there is only one parser created, `decoder` and I could have put the parser chaining logic directly there. But this way the decoder is very clear, and the `Parser` despite it's small size, is a reasonable simple parsing framework.
```
import Control.Monad (ap)
data Tree = Leaf Integer | Node Integer Tree Tree
deriving (Eq, Show)
encode :: Tree -> [Integer]
encode (Leaf n) = [n*2]
encode (Node n t u) = (n*2+1) : encode t ++ encode u
decode :: [Integer] -> Maybe Tree
decode = fullyParse decoder
where
decoder :: Parser Integer Tree
decoder = do
i <- next
let n = i `div` 2
if even i
then return (Leaf n)
else return (Node n) `ap` decoder `ap` decoder
-- A simple Parsing Monad
data Parser a b = P { runParser :: [a] -> Maybe (b, [a]) }
instance Monad (Parser a) where
return a = P ( \ts -> Just (a, ts) )
p >>= q = P ( \ts -> runParser p ts >>= (\(v,ts') -> runParser (q v) ts') )
fail _ = P ( const Nothing )
next :: Parser a a
next = P n
where n (t:ts) = Just (t,ts)
n _ = Nothing
fullyParse :: Parser a b -> [a] -> Maybe b
fullyParse p ts = runParser p ts >>= consumedResult
where
consumedResult (v,[]) = Just v
consumedResult _ = Nothing
-- Example
main :: IO ()
main = do
putStrLn $ "example: " ++ show ex
putStrLn $ "encoding: " ++ show encEx
putStrLn $ "decoding: " ++ show decEx
putStrLn $ "worked? " ++ show worked
where
ex = Node 5
(Leaf 3)
(Node 2
(Node 2
(Leaf 9)
(Leaf 9)
)
(Leaf 1)
)
encEx = encode ex
decEx = decode encEx
worked = maybe False (ex ==) decEx
```
Running this gets you:
```
> runhaskell TreeEncoding.hs
example: Node 5 (Leaf 3) (Node 2 (Node 2 (Leaf 9) (Leaf 9)) (Leaf 1))
encoding: [11,6,5,5,18,18,2]
decoding: Just (Node 5 (Leaf 3) (Node 2 (Node 2 (Leaf 9) (Leaf 9)) (Leaf 1)))
worked? True
```
[Answer]
In C
```
#include <stdlib.h>
#include <stdio.h>
struct Node;
typedef struct Node Node;
struct Node
{
int data;
Node* left;
Node* right;
};
/* Private Functions */
static int* encodeNode(Node* tree, int* store);
static Node* decodeNode(int** store);
/* Public Functions */
Node* newNode(int data,Node* left,Node* right);
void deleteTree(Node* tree);
int countNodesTree(Node* tree);
int* encode(Node *tree);
Node* decode(int* store);
void printTree(Node* tree);
Node* newNode(int data,Node* left,Node* right)
{
Node* result = (Node*)malloc(sizeof(Node));
result->data = data;
result->left = left;
result->right = right;
return result;
}
void deleteTree(Node* tree)
{
if (tree == NULL)
{ return;
}
deleteTree(tree->left);
deleteTree(tree->right);
free(tree);
}
int countNodesTree(Node* tree)
{
if (tree == NULL)
{ return 0;
}
return countNodesTree(tree->left)
+ countNodesTree(tree->right)
+ 1;
}
void printTree(Node* tree)
{
if (tree == NULL)
{
fprintf(stdout, "- ");
}
else
{
fprintf(stdout, "%d ", tree->data);
printTree(tree->left);
printTree(tree->right);
}
};
```
The encode:
```
int* encode(Node *tree)
{
int nodeCount = countNodesTree(tree);
int* result = (int*)malloc(sizeof(int) * (nodeCount * 2 + 1));
// Put the node count in the first element.
// This makes it easy to also serialize this object for transport
// i.e. you can put it in a file or a stream (socket) and easily recover it.
result[0] = nodeCount;
encodeNode(tree, result + 1);
return result;
}
int* encodeNode(Node* tree, int* store)
{
if (tree != NULL)
{
store[0] = tree->data;
/*
* Slight overkill. for this question.
* But works and makes future enhancement easy
*/
store[1] = (tree->left == NULL ? 0 : 1)
+ (tree->right == NULL ? 0 : 2);
store += 2;
store = encodeNode(tree->left, store);
store = encodeNode(tree->right, store);
}
return store;
}
```
The decode:
```
Node* decode(int* store)
{
if (store == NULL)
{ fprintf(stderr, "Bad Input terminating: encode() always return non NULL\n");
exit(1);
}
if (store[0] == 0)
{
return NULL;
}
store++;
return decodeNode(&store);
}
Node* decodeNode(int** store)
{
int value = (*store)[0];
int flag = (*store)[1];
(*store) += 2;
Node* left = flag & 1 ? decodeNode(store) : NULL;
Node* right = flag & 2 ? decodeNode(store) : NULL;
return newNode(value, left, right);
}
```
Main:
```
int main()
{
Node* t = newNode(5,
newNode(3, NULL, NULL),
newNode(2,
newNode(2,
newNode(9, NULL, NULL),
newNode(9, NULL, NULL)
),
newNode(1, NULL, NULL)
)
);
printTree(t);
fprintf(stdout,"\n");
int* e = encode(t);
Node* d = decode(e);
printTree(d);
fprintf(stdout,"\n");
free(e);
deleteTree(d);
deleteTree(t);
}
```
Note. Each node is encoded as two integers (plus one int for the count of nodes).
So the supplied tree encodes like this:
```
7, 5, 3, 3, 0, 2, 3, 2, 3, 9, 0, 9, 0 1, 0
^ ^
^ ^ Node 1
^
Count
```
[Answer]
In Ruby, with the same encoding than [@MtnViewMark](https://codegolf.stackexchange.com/questions/339/binary-tree-encoding/401#401) :
```
class Node
def initialize(data, left = nil, right = nil)
@data, @left, @right = data, left, right
end
def encode
"%d %s %s" % [@data<<1|1, @left.encode, @right.encode]
end
class << self
def decode(str)
_decode(str.split.map &:to_i)
end
private
def _decode(a)
n = a.shift
if n & 1 == 1
Node.new(n>>1, _decode(a), _decode(a))
else
Leaf.new(n>>1)
end
end
end
end
class Leaf < Node
def encode
(@data<<1).to_s
end
end
tree=Node.decode("11 6 5 5 18 18 2")
print tree.encode
```
The cost is one integer per node (`data << 1 | has_childs`) :
```
11 6 5 5 18 18 2
```
[Answer]
**~ 1.03 N**
It seems all the answers so far take least 2\*N \* 32-bits to store. (Except the solutions in languages which allows integer values longer than 32 bits, like the Haskell and Ruby solutions - but those are still going to take extra bytes to encode whenever the data is greater than 16K.)
Here is a solution which only takes N+ceiling(N/32)+1 ints of storage. This approaches 1.03125 N for large N, and is under 1.1 N for all N greater than 20.
The idea is to store an extra bit for each node where 1 is "hasChildren". These bits are packed into N/32 words up front.
```
int* encodeHelper(Node* n, int* code, int* pos, int* flag)
{
int hasKids = (n->left!=0);
code[*flag/32]|=hasKids<<(*flag&31);
*flag+=1;
if (hasKids) bencodeHelper(n->left, code, pos, flag);
code[*pos]=n->data;
*pos+=1;
if (hasKids) bencodeHelper(n->right, code, pos, flag);
return code;
}
int* encode(Node* h, int* sizeOut)
{
int nnodes=countNodes(h);
int nflags = (int)ceil(nnodes/32.0);
int pos=nflags+1;
int flag=32;
int* out;
*sizeOut = 1+nnodes+nflags;
out = calloc(*sizeOut, sizeof(int));
if (!h) return out;
out[0]=nflags+1; //store start of data
return encodeHelper(h,out,&pos,&flag);
}
Node* decodeHelper(int* code, int* pos, int* flag)
{
Node*n = calloc(1, sizeof(Node));
int hasKids = code[*flag/32]>>(*flag&31)&1;
*flag+=1;
if (hasKids) n->left = bdecodeHelper(code, pos, flag);
n->data = code[*pos];
*pos+=1;
if (hasKids) n->right = bdecodeHelper(code, pos, flag);
return n;
}
Node* decode(int* code)
{
int flag=32;
int pos=code[0];
if (!pos) return NULL;
return decodeHelper(code, &pos, &flag);
}
```
*[(compelete implementation here)](https://ideone.com/28w6L)*
[Answer]
Given a binary tree with `n` nodes, this encodes it in a list of `2n + 1` integers. Both the encoding and decoding algorithms have `O(n)` complexity.
I use the 0 integer as a sentinel marker when encoding, indicating when I unfold the recursion. Then when I'm decoding, I put the tree nodes I'm creating on a stack (of sorts) and use the 0s in the list to keep track of where to add the next node. I haven't tried, but I'm pretty sure the decoding would break if the tree was not complete.
```
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Prototypes
struct BTnode;
struct BTnode * bt_add_left(struct BTnode * node, int data);
struct BTnode * bt_add_right(struct BTnode * node, int data);
int bt_depth(struct BTnode * tree);
int bt_encode_preorder(int * list, struct BTnode * tree, int index);
struct BTnode * bt_node_create(int data);
int bt_node_delete(struct BTnode * node);
void bt_print_preorder(struct BTnode * tree);
int * encode(struct BTnode * tree);
struct BTnode * decode(int * list);
// Binary tree node
struct BTnode
{
int data;
struct BTnode *left, *right;
};
// Add node to this node's left
struct BTnode * bt_add_left(struct BTnode * node, int data)
{
struct BTnode * newnode = bt_node_create(data);
node->left = newnode;
return newnode;
}
// Add node to this node's right
struct BTnode * bt_add_right(struct BTnode * node, int data)
{
struct BTnode * newnode = bt_node_create(data);
node->right = newnode;
return newnode;
}
// Determine depth of the tree
int bt_depth(struct BTnode * tree)
{
int depth;
int leftdepth = 0;
int rightdepth = 0;
if( tree == NULL ) return 0;
if( tree->left != NULL )
leftdepth = bt_depth(tree->left);
if( tree->right != NULL )
rightdepth = bt_depth(tree->right);
depth = leftdepth;
if(rightdepth > leftdepth)
depth = rightdepth;
return depth + 1;
}
// Recursively add node values to integer list, using 0 as an unfolding sentinel
int bt_encode_preorder(int * list, struct BTnode * tree, int index)
{
list[ index++ ] = tree->data;
// This assumes the tree is complete (i.e., if the current node does not have
// a left child, then it does not have a right child either)
if( tree->left != NULL )
{
index = bt_encode_preorder(list, tree->left, index);
index = bt_encode_preorder(list, tree->right, index);
}
// Add sentinel
list[ index++ ] = 0;
return index;
}
// Allocate memory for a node
struct BTnode * bt_node_create(int data)
{
struct BTnode * newnode = (struct BTnode *) malloc(sizeof(struct BTnode));
newnode->left = NULL;
newnode->right = NULL;
newnode->data = data;
return newnode;
}
// Free node memory
int bt_node_delete(struct BTnode * node)
{
int data;
if(node == NULL)
return 0;
data = node->data;
if(node->left != NULL)
bt_node_delete(node->left);
if(node->right != NULL)
bt_node_delete(node->right);
free(node);
return data;
}
// Print all values from the tree in pre-order
void bt_print_preorder(struct BTnode * tree)
{
printf("%d ", tree->data);
if(tree->left != NULL)
bt_print_preorder(tree->left);
if(tree->right != NULL)
bt_print_preorder(tree->right);
}
// Decode binary tree structure from a list of integers
struct BTnode * decode(int * list)
{
struct BTnode * tree;
struct BTnode * nodestack[ list[0] ];
int i,j;
// Handle trivial case
if( list == NULL ) return NULL;
tree = bt_node_create( list[1] );
nodestack[ 1 ] = tree;
j = 1;
for(i = 2; i < list[0]; i++)
{
if( list[i] == 0 )
{
//printf("popping\n");
j--;
}
else
{
if( nodestack[j]->left == NULL )
{
//printf("Adding %d to left of %d\n", list[i], nodestack[j]->data);
nodestack[ j+1 ] = bt_add_left(nodestack[j], list[i]);
j++;
}
else
{
//printf("Adding %d to right of %d\n", list[i], nodestack[j]->data);
nodestack[ j+1 ] = bt_add_right(nodestack[j], list[i]);
j++;
}
}
}
return tree;
}
// Encode binary tree structure as a list of integers
int * encode(struct BTnode * tree)
{
int maxnodes, depth, length;
int * list;
int j;
// Handle trivial case
if(tree == NULL) return NULL;
// Calculate maximum number of nodes in the tree from the tree depth
maxnodes = 1;
depth = bt_depth(tree);
for(j = 0; j < depth; j++)
{
maxnodes += pow(2, j);
}
// Allocate memory for the list; we need two ints for each value plus the
// first value in the list to indicate length
list = (int *) malloc( ((maxnodes * 2)+1) * sizeof(int));
length = bt_encode_preorder(list, tree, 1);
list[ 0 ] = length;
return list;
}
int main()
{
struct BTnode * tree;
struct BTnode * newtree;
int * list;
int i;
/* Provided example
5
/ \
3 2
/ \
2 1
/ \
9 9
*/
tree = bt_node_create(5);
bt_add_left(tree, 3);
struct BTnode * temp = bt_add_right(tree, 2);
bt_add_right(temp, 1);
temp = bt_add_left(temp, 2);
bt_add_left(temp, 9);
bt_add_right(temp, 9);
printf("T (traversed in pre-order): ");
bt_print_preorder(tree);
printf("\n");
list = encode(tree);
printf("T (encoded as integer list): ");
for(i = 1; i < list[0]; i++)
printf("%d ", list[i]);
printf("\n");
newtree = decode(list);
printf("T' (decoded from int list): ");
bt_print_preorder(newtree);
printf("\n\n");
// Free memory
bt_node_delete(tree);
bt_node_delete(newtree);
free(list);
return 0;
}
```
Saved this as `encode.c` then compiled and executed. This program uses the example tree you provided, and I've tested it on a few others successfully.
```
$ gcc -Wall -lm -o encode encode.c
$ ./encode
T (traversed in pre-order): 5 3 2 2 9 9 1
T (encoded as integer list): 5 3 0 2 2 9 0 9 0 0 1 0 0 0
T' (decoded from int list): 5 3 2 2 9 9 1
```
[Answer]
My code encodes the tree in a preorder traversal, each leaf in two ints (its data followed by 0) and each internal node in one int (its data followed by its left child, then its right). For a complete binary tree (as you define it) with n nodes, n must be odd, and there are (n+1)/2 leaves and (n-1)/2 internal nodes, so that's 3n/2+1/2 integers for the encoding.
warning: untested, just typed it in.
```
struct node {
int data;
struct node *left, *right;
};
void encodeInternal(struct node *root, vector<int> *buf) {
buf->push_back(root->data);
if (root->left) {
encodeInternal(root->left, buf);
encodeInternal(root->right, buf);
} else {
buf->push_back(0);
}
}
int *encode(struct node *root) {
vector<int> buf;
encodeInternal(root, &buf);
return &buf[0];
}
struct decodeResult {
int encoded_size;
struct node *n;
}
struct decodeResult decodeInternal(int *array) {
struct node *n = (struct node*)malloc(sizeof(struct node));
n->data = array[0];
if (array[1] == 0) {
n->left = n->right = NULL;
return (decodeResult){2, n};
} else {
decodeResult L = decodeInternal(array + 1);
decodeResult R = decodeInternal(array + 1 + L.encoded_size);
n->left = L.n;
n->right = R.n;
return (decodeResult){1 + L.encoded_size + R.encoded_size, n};
}
}
struct node *decode(int *array) {
return decodeInternal(array).n;
}
```
[Answer]
### Scala:
```
trait Node {
def encode (): Array[Int]
}
case object Node {
def decode (a: Array[Int]): InnerNode = {
if (a.length == 1) InnerNode (a(0)) else {
val r = InnerNode (a(1))
val l = decode (a.tail.tail)
InnerNode (a(0), l, r)
}
}
}
case object Leaf extends Node {
def encode (): Array[Int] = Array.empty
}
case class InnerNode (val data: Int, var l: Node=Leaf, var r: Node=Leaf) extends Node {
def encode (): Array[Int] = Array (data) ++ r.encode () ++ l.encode ()
}
object BinTreeTest extends App {
println (Node.decode (Array (1, 2, 3, 4, 5)).encode.mkString (", "))
}
```
This is an approach which uses deprecated syntax, but compiles without error in Scala 2.9.1 . It generates a Tree and decodes every encoded Tree to the same Array as used for encoding. Maybe I get somehow rid of the deprecated warnings today.
Wow - that was a simple one. First idea worked immediately.
[Answer]
Here's my try. It stores the tree in an array of size 2\*\*depth+1. It
uses `a[0]` to hold the size, and `a[size]` to hold the index of the
first "empty node" it encounters in a depth-first traversal. (An
empty node is the place where a child would be stored if the parent
had one). Each empty node holds the index of the next empty node that
will be encountered.
This scheme avoids reserving bits to mark the presense children, so
each node can use the full integer range. It also allows unbalanced
trees - a parent can have only one child.
output:
```
empty tree: [0]
head node only: [2,5,0]
example tree: [16,5,3,2,5,14,2,1,0,0, 0,0,9,9,15,0,4];
```
The Encoder:
```
//utility
int findDepth(Node* n) {
int l = 0 ,r = 0;
if (n) {
l = 1 + findDepth(n->left);
r = 1 + findDepth(n->right);
}
return ( l > r ) ? l : r;
}
//Encode Function
int* encodeTree(Node* head) {
int* out;
int depth = findDepth(head);
int size = depth>0;
while (depth--) size*=2;
out = calloc(size+1,sizeof(int));
out[0]=size;
encodeNode(head, out,1, out+size);
return out;
}
void encodeNode(Node* n, int* a, int idx, int* pEmpty) {
if (n) {
a[idx]=n->data;
encodeNode(n->left,a,idx*2,pEmpty);
encodeNode(n->right,a,idx*2+1,pEmpty);
}
else if (idx<a[0]) {
*pEmpty = idx;
pEmpty = a+idx;
}
}
```
The Decoder:
```
//Decode Function
Node* decodeArray(int* a) {
return (a[0]) ? decodeNode(a,1,a+a[0]) : NULL;
}
Node* decodeNode(int* a, int idx, int* pEmpty) {
Node* n = NULL;
if (idx== *pEmpty)
*pEmpty=a[idx];
else {
n = calloc(1,sizeof(Node));
n->data = a[idx];
if (idx*2<a[0]) {
n->left = decodeNode(a, idx*2, pEmpty);
n->right = decodeNode(a, idx*2+1, pEmpty);
}
}
return n;
}
```
---
(thanks @daniel sobral for fixing the formatting)
] |
[Question]
[
This is the cops' thread. See the robbers' thread [here](https://codegolf.stackexchange.com/questions/264048/magic-oeis-formulae-robbers-thread).
In this cops and robbers challenge, the cops will be tasked with writing an algorithm that computes some function of their choice, while the robbers will try to come up with their algorithm. The catch is, the 'algorithm' must be a *single* closed-form mathematical expression. Remarkably, a function that determines whether a number is prime has been [shown](https://codegolf.stackexchange.com/questions/170398/primality-testing-formula) to be possible using only Python operators.
## Cops
This is the cops' thread. To compete, first choose any *infinite* OEIS sequence (e.g. [A000027](https://oeis.org/A000027)). Then, write a single closed-form expression that takes an integer `n`, and provably computes the `n`th term of this sequence. You only need to handle `n` for which the sequence is defined.
In addition, pay attention to the offset of your chosen OEIS sequence. If the offset is `0`, the first term should be evaluated at `n=0`. If the offset is `1`, it should be evaluated at `n=1`.
The specification for the closed-form expression is as such:
* The expression must consist of the following arithmetic/bitwise operators: `**, %, *, /, +, -, <<, >>, &, ^, |` (note that `/` represents floor division). Unary negation `-`, bitwise negation `~`, and parentheses `()` are also allowed.
* The expression may also contain `n`, as well as any positive or negative integer literals. Only decimal (base 10) literals are permitted.
* To avoid ambiguity, the behavior of the expression will explicitly be defined as its result when evaluated as Python 2 code. Take extra note of how Python handles `/` and `%`, especially when used with negative numbers.
* `a**b` may result in a floating-point number, if `b` is negative. Your expression *must not* have this occur.
Once you have chosen an OEIS sequence with an accompanying expression, submit an answer containing the OEIS sequence, and the number of bytes in your expression. It is also recommended to include a brief description of the OEIS sequence itself. Don't reveal your actual expression, as this is what the robbers will try to crack!
The robbers will have one week to crack your submission by trying to figure out your expression. Their expression must be **at most twice** the length of your expression to be considered a crack. This is to ensure that the robber can't crack your submission with an overly long expression.
## Additional Information
* Optionally, you may choose to disallow a subset of the allowed operators. If you do so, mention the restricted set in the body of your submission. Both your expression and the robber's expression must then adhere to this restriction.
* Make sure to specify the offset if you use a different one than on the OEIS.
* If your solution has not been cracked and you find a shorter solution after posting, you may update your byte count accordingly.
## Scoring
If your submission is not cracked within one week of its initial post, you can mark it as *safe* and reveal your solution. After this point, it can no longer be cracked.
Your score is the length of your expression in bytes, with a lower score being better.
## Example Submission
>
> ### [A000225](https://oeis.org/A000225), 6 bytes
>
>
>
> >
> > a(n) = 2^n - 1. Sometimes called the Mersenne numbers.
> >
> >
> >
>
>
> *Solution (keep this hidden until you are cracked or safe!)*:
>
>
>
> ```
> 2**n-1
>
> ```
>
>
[Answer]
# [A002193](https://oeis.org/A002193), 82 bytes
[Cracked by @loopy walt](https://codegolf.stackexchange.com/a/264468/92727). The brownie points are still open.
Offset: 1 (that is, \$f(1) = 1, f(2) = 4, f(3)=1, ...\$)
The decimal expansion of \$\sqrt 2\$.
Six brownie points if your solution can finish for \$n = 1000\$ before the end of the universe.
My solution:
>
> We can approximate \$\sqrt{2}\$ using [the Pell numbers](https://en.wikipedia.org/wiki/Pell_number). To know how much accuracy we need, we need to bound \$|\sqrt{2} - \frac{p}{10^n}|\$. According to [Carmichael's theorem](https://en.wikipedia.org/wiki/Carmichael%27s_theorem), 1, 2 and 5 are the only Pell numbers which divide a power of ten, and if \$\frac{a}{b}\$ isn't a convergent of \$x\$ it's known that \$|x - \frac{a}{b}| > \frac{1}{2b^2}\$, so in particular \$|\sqrt{2} - \frac{p}{10^n}| > \min(\frac{1}{2\cdot 10^{2n}}, |\sqrt{2} - \frac{7}{5}|)\$, but it can be easily calculated that for any \$n \geq 1\$, \$\frac{1}{2\cdot 10^{2n}} < |\sqrt{2} - \frac{7}{5}|\$, so \$|\sqrt{2} - \frac{p}{10^n}| > \frac{1}{2\cdot 10^{2n}}\$. This means if we have an approximation with error of at most \$\frac{1}{2 \cdot 10^{2n}}\$ the n-th digit must be correct.
> We will show that \$|\sqrt{2} - \frac{H\_{4n}}{P\_{4n}}| \leq \frac{1}{2 \cdot 10^{2n}}\$ for \$n \geq 1\$. Since \$\frac{H\_{4n}}{P\_{4n}}\$ is a convergent to \$\sqrt{2}\$, it's known that \$|\sqrt{2} - \frac{H\_{4n}}{P\_{4n}}| \leq \frac{1}{P\_{4n} P\_{4n+1}} \leq \frac{1}{P\_{4n}^2}\$. It can be seen that \$P\_n \geq \frac{(1+\sqrt{2})^n}3\$, so \$\frac{1}{P\_{4n}^2} \leq \frac{9}{(1+\sqrt{2})^{8n}} = \frac{9}{10^{\log\_{10}(1 + \sqrt2)8n}} \leq \frac{9}{10^{3 n}}\$ and since \$n \geq 1\$, \$\frac{9}{10^{3 n}} \leq \frac{1}{10^{2n}}\$.
>
> Now we just need to calculate \$H\_n\$ and \$P\_n\$. We will use \$(1 + x)^n \equiv H\_n + x P\_n \pmod {x^2 - 2}\$. Since \$H\_n, P\_n < 3^n\$, we can use \$x = 3^n\$, and \$(1 + 3^n)^n \equiv H\_n + 3^n P\_n \pmod {9^n - 2}\$. We actually need to calculate it for \$4n\$, so we use \$(1+81^n)^{4n} \equiv H\_{4n} + 81^{n} P\_{4n} \pmod {6561^n - 2}\$. Then we can calculate \$\lfloor \frac{H\_{4n} 10^{n-1}}{P\_{4n}} \rfloor \mod 10 \$. In code:
>
> `(1+81**n)**(4*n)%(6561**n-2)%81**n*10**~-n/((1+81**n)**(4*n)%(6561**n-2)/81**n)%10`
>
>
>
[Answer]
# [A000796](https://oeis.org/A000796), 105 bytes
Offset: 1 (that is, \$f(1) = 3, f(2) = 1, ...\$)
The digits of \$\pi\$, in base 10.
Your formula must be provably correct, and can't relay on any unproven assumptions/conjectures. Note that if you approximate \$\pi\$, it is possible there are a bunch of \$9\$s in that position, and then the \$n\$th digit of the approximation could be wrong.
My solution:
>
> Is has been proven (by Kurt Mahler, I couldn't find the paper online) that for any integers \$q \geq 2\$ and \$p\$, \$|\pi - \frac{p}{q}| \geq \frac{1}{q^{42}}\$. In particular, if \$\frac{a}{10^{n-1}} < \pi < \frac{a+1}{10^{n-1}}\$, any value \$r\$ such that \$|\pi - r| \leq \frac{1}{10^{42(n-1)+1}}\$ will be entirely contained within that interval, and so its \$n\$-th digit will be correct.
> To approximate \$\pi\$, we can use the asymptotics for the centeral binomial coefficients: \$\binom{2n}{n} \approx \frac{4^n}{\sqrt{\pi n}}\$. We can use the nonasymptotic [bounds](https://math.stackexchange.com/questions/58560/elementary-central-binomial-coefficient-estimates) \$\frac{1}{\sqrt{\pi (n+1)}} < \binom{2n}{n} 4^{-n} < \frac{1}{\sqrt{\pi n}}\$ to derive \$\frac{16^n}{\binom{2n}{n}^2 (n+1)} < \pi < \frac{16^n}{\binom{2n}{n}^2 n}\$, and it isn't hard to see that the error in any of these bounds is at most \$\frac{16^n}{\binom{2n}{n}^2} (\frac{1}{n} - \frac{1}{n+1}) = \frac{16^n}{\binom{2n}{n}^2} \frac{1}{n(n+1)}\$ but as stated earlier \$\frac{16^n}{\binom{2n}{n}^2 (n+1)} < \pi\$ and thus the error is at most \$\frac{\pi}{n} < \frac{4}{n}\$. If we set \$n = 10^{42 m}\$ there, where \$m\$ is the digit we're trying to calculate, we can see we get enough accuracy. In code:
>
> `16**10**(42*n)*10**~-n/(((1+4**10**(42*n))**(2*10**(42*n))/4**10**(84*n)%4**10**(42*n))**2*10**(42*n))%10`
>
>
>
[Answer]
# [A000120](https://oeis.org/A000120), 50 bytes
[Cracked by @Command Master](https://codegolf.stackexchange.com/a/264058/20260)
Offset: 1
Here's one to get started: the Hamming weight of `n`, the number of 1's in the binary representation of `n`. You don't need to handle `n=0`.
[Answer]
# [A000005](https://oeis.org/A000005), 242 bytes
[Cracked by @l4m2](https://codegolf.stackexchange.com/a/264071/92727)
Offset: 1
The number of divisors of \$n\$.
[Answer]
# [A000244](https://oeis.org/A000244), 23 bytes
[Cracked by loopy walt](https://codegolf.stackexchange.com/a/264098/20260)
Compute `3**n`, but `**` is banned. Offset 1, so `n>0`.
[Answer]
# [A000045](https://oeis.org/A000045), 45 bytes
[Cracked by xnor](https://codegolf.stackexchange.com/a/264092/20260)
Offset: 0
The Fibonacci numbers. `/` isn't allowed.
[Answer]
# [A007953](https://oeis.org/A007953), 93 bytes
[Cracked by @Command Master](https://codegolf.stackexchange.com/a/264138/88546)
The `n`th term is the sum of digits of `n` (e.g. `a(1234) = 1+2+3+4 = 10`).
A step up from counting bits. You do not need to handle `n=0`.
[Answer]
# [A000012](https://oeis.org/A000012), 6 bytes, [cracked in 8 minutes ü§Ø](https://codegolf.stackexchange.com/questions/264048/magic-oeis-formulae-robbers-thread/264073#264073)
Offset: Doesn't matter
Every term in the sequence is 1.
Of course, since this would be too trivial without this, **you can only use bit-shifts (which are `>>` and `<<`) and the digit `9`.**
## Intended solution
>
> Exactly what the cracker posted, `999>>9`.
>
>
>
[Answer]
# [A160155](https://oeis.org/A160155), 125 bytes
Offset: 1 (that is, \$f(1) = 1, f(2) = 1, f(3)=6, ...\$)
The decimal expansion of the single real root of \$x^5 - x-1\$, \$1.1673...\$.
Using `&` or `|` is forbidden.
] |
[Question]
[
## Introduction:
Every workday I read the newspaper in the morning while eating breakfast, and also do some of the puzzles at the back. When I do the word-search puzzles, I (almost) always go over the words in order, and strike them through one by one. The word-searches in the newspaper have two columns of words, and after I finished a column I will also put a vertical strike through it.
## Challenge:
Let's do the same as a challenge. Given a list of lists of words and an integer \$n\$ for the amount of words I've already struck through, output the ASCII art representing that.
The words of each inner list will be placed in the same column, where the columns will have two spaces as delimiter (based on the longest word). All the letters in the words that are struck through are replaced with `-`, and if an entire column is struck through it's replaced with a vertical `|`.
## Challenge rules:
* `|` rules:
+ For the position of the `|`, we take the middle of the longest word in the column
+ If the longest word has an even length, we take the left character of the two middle characters (e.g. `----` → `-|--`)
+ If a word in the column is shorter than the (left-focused) middle of the longest word, pad spaces between this shortest word and the vertical `|` line
* You can assume the list of words will only contain regular ASCII letters (in a casing of your choosing - e.g. all lowercase; all uppercase; or mixed casing)
* You can assume the list of words will all be of equal length, except for the last column which might potentially be shorter
* You can assume there is always at least one word in the list
* You can assume \$0 \leq n \leq W\$ (where \$W\$ is the total amount of words)
* Probably not really relevant, but you can assume the words are in alphabetical order
* Trailing spaces/newlines in the output are optional
* The input-list can be taken in any reasonable format. Could be a list/stream/array; could be taken from STDIN; could be a space-delimited string list; a matrix of characters; etc.
* You're allowed to take the words-input as a list of rows instead of columns. So input `[["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]` would be `[["A","QRSTUVW","Z"],["ABC","QRSTUVWXYZ","ZZZZZ"],["DEFGHIJ","ST"],["FG","Y"],["KLMN","YZ"]]` instead
## Examples:
Input 1:
```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n: 0
```
Output 1:
```
A QRSTUVW Z
ABC QRSTUVWXYZ ZZZZZ
DEFGHIJ ST
FG Y
KLMN YZ
```
Input 2:
```
Words: Same as the previous example
n: 11
```
Output 2:
```
- | ----|-- -
---| ----|----- ZZZZZ
---|--- -- |
-- | - |
---| -- |
```
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
Input 1:
```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n: 0
```
Output 1:
```
A QRSTUVW Z
ABC QRSTUVWXYZ ZZZZZ
DEFGHIJ ST
FG Y
KLMN YZ
```
Input 2:
```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n: 11
```
Output 2:
```
- | ----|-- -
---| ----|----- ZZZZZ
---|--- -- |
-- | - |
---| -- |
```
Input 3:
```
Words: [["A","ABC","DEFGHIJ","FG","KLMN"],["QRSTUVW","QRSTUVWXYZ","ST","Y","YZ"],["Z","ZZZZZ"]]
n: 12
```
Output 3:
```
- | ----|-- - |
---| ----|----- --|--
---|--- -- |
-- | - |
---| -- |
```
Input 4:
```
Words: [["BACKWARD","DIAGONAL","FIND","HORIZONTAL"],["RANDOM","SEEK","SLEUTH","VERTICAL"],["WIKIPEDIA","WORDSEARCH"]]
n: 0
```
Output 4:
```
BACKWARD RANDOM WIKIPEDIA
DIAGONAL SEEK WORDSEARCH
FIND SLEUTH
HORIZONTAL VERTICAL
```
Input 5:
```
Words: [["BACKWARD","DIAGONAL","FIND","HORIZONTAL"],["RANDOM","SEEK","SLEUTH","VERTICAL"],["WIKIPEDIA","WORDSEARCH"]]
n: 6
```
Output 5:
```
----|--- ------ WIKIPEDIA
----|--- ---- WORDSEARCH
----| SLEUTH
----|----- VERTICAL
```
Input 6:
```
Words: [["TEST"]]
n: 1
```
Output 6:
```
-|--
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
z⁶Z)µẎ«”-$⁹R¤¦Fṁ”|LHĊƊ¦€ḟƑ¡"⁸Zj€⁾
```
A dyadic Link that accepts the list of lists of words on the left and the number done on the right and yields a [list of lines](https://codegolf.meta.stackexchange.com/a/17095/53748).
**[Try it online!](https://tio.run/##y0rNyan8/7/qUeO2KM1DWx/u6ju0@lHDXF2VR407gw4tObTM7eHORqBAjY/Hka5jXYeWPWpa83DH/GMTDy1UetS4IyoLyH/UuE9B4f/h5ZH//0dHKzkq6Sg5OjkDSRdXN3cPTy8gy80dSHj7@PopxepEKwUGBYeEhoUDhaCsiMgoICc4BEhEgnAUWBlILAoElGJj/xsaAgA "Jelly – Try It Online")**
### How?
```
z⁶Z)µẎ«”-$⁹R¤¦Fṁ”|LHĊƊ¦€ḟƑ¡"⁸Zj€⁾ - Link: W, N
) - for each list in W:
z⁶ - transpose with space filler
Z - transpose
µ - start a new monadic Link, call that X
Ẏ - tighten (to a list of padded words)
$⁹R¤¦ - apply to indices [1..N]:
”- - a '-' character
« - minimum (vectorises) -> '-' if not ' '
F - flatten
ṁ - mould like X
"⁸ - zip with X applying:
ḟƑ¡ - if invariant under filter-discard:
Ɗ¦€ - for each apply to indices...
L - ...length
H - halved
Ċ - ceiling
”| - ...a '|' character
Z - transpose
j€⁾.. - join each with " "
```
[Answer]
# Python3, 321 bytes:
```
L=len
Y=lambda x:max(map(L,x))
g=lambda x:[[i+' '*((M:=Y(x))-L(i))for i in x],[i[:(T:=(J:=M//2)--~M%2)]+' '*(H:=max(T-L(i),0))+'|'+i[J+M%2:]+' '*(M-L(i)-H-(L(i)<=T))for i in x]][{i[0]for i in x}=={'-'}]
f=lambda w,n,c=0:'\n'.join(map(' '.join,zip(*[g([[j,'-'*L(j)][(c:=c+1)<=n]for j in i])+['']*(Y(w)-L(i))for i in w])))
```
[Try it online!](https://tio.run/##tVFtT8IwEP7Or1iWmLasU8DEmMZ@mDDZYC86qjhqPyCKlshYiAn4@tfxOjEGv9ukd9fn7p6n15Yvz4@L4vC4XG42EX@6L2o5fxrPb@/G1prNx2s8H5c4omtCag@/CSm1gyxUxzhmPMeQdSOsCZkulpa2dGGtFZVaMiwYxz3G44ODFnHdz3ivRdR3Z8C4oRdVI20Q4qB35GjZc6CIbYviKusGLjb@hIsdCSXftGyoX@SD8zfkog9Vm/7cdUULOuENhm4KtD9b6KIaCFnW94m@6hLX5QOWckahtR7hGVESTxifOE1QLCr6maHXijgSIVXHOV79HXilCCGbcqmLZzwFNtuzqe2dtsF2/LNuEPYgOuuC6UdxYsPz2BfZQFxeDQHaRtf5CA4DASY3e1SVGWxklq0UbTbhI/5dpbErcuq1@0Mv6xiV0OumiRcZmTAxSJBm4ShNBGCGJ/OSThobAd/vGxf5lyKA4MrPRNjeVg3DfnjuAxkkhmnWGfhe1g6M9NGutPDhomZueNwv)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
Fθ«Eι⎇‹ληLκκ≔⌈EιLκζM⊘⊖ζ±LιF¬‹ηLιP↓LιM⊘ζ→→→≧⁻Lιη
```
[Try it online!](https://tio.run/##dVDNToQwGDwvT0E4tQlePeyeKqAQ/jZdlETCocEKzUJBKKgYnx0LrGRj4qnTmfnmmzYrSJvVpJym17pVwRtUv5TdsWVcAJ80gOlqRFtO2k/g0a4Dpa4WUFc9ynNRgLOEZwjhQdmhrmM5lzMfrOqr39nNB6VznH1@PVBgk3KgL8CkWUsryoXE4@wIaE4EBZcptiYvvYJarAWKLXSWoer3pWDN0ndv1u/8Wv6zbpQb9pjlhdiU/6@kWV@0MMBnvO@uoudfOCjf05QkiXaHDDdG2NR0zXTQQxggT8J7J5gZO8TOcxhEkkv1RMMoMENf8ifLcufDsx4jW4InC0eOcXHFjuscLRkmhTjE5slC2LC1NNVv0@lmKH8A "Charcoal – Try It Online") Link is to verbose version of code. Very forgiving as to the input words. Explanation:
```
Fθ«
```
Loop over the list of columns of words.
```
Eι⎇‹ληLκκ
```
Replace each word that has already been struck through with its length and print the result. This outputs a line of `-`s of that length for those words and the words unchanged for the remaining words.
```
≔⌈EιLκζ
```
Get the length of the longest word.
```
M⊘⊖ζ±Lι
```
Move horizontally to the middle of the longest word (but vertically to the first word).
```
F¬‹ηLιP↓Lι
```
If all of the words in this column have been struck through then vertically output a `|` for each word without moving the cursor.
```
M⊘ζ→
```
Move to the end of the longest word.
```
→→
```
Move to where the next block of words belongs.
```
≧⁻Lιη
```
Adjust the number of remaining words that have been struck through.
[Answer]
# [Ruby](https://www.ruby-lang.org/),~~152 155~~ 153 bytes
```
->l,n{l.map!{|c|c.map!{|w|w.tr((0>n-=1)?'':'^ ',?-).ljust X=c.map(&:size).max}
n<0?c:c.each{|w|w[~-X/2]=?|}}
(0...l[0].size).map{|y|l.map{|c|c[y]}*" "}}
```
[Try it online!](https://tio.run/##zZFdT4MwFIbv@RXYCwGFynbhxSKSDrqBbKCMjQ3EZJItzlSy7CNzDvzr2CJeejETjU16@p7T8/GkXW0f9@VcK5VrImcHAl@my5NDnuZprXb5Dm5WoqheZ4rWkHRBaAkPvCDrigTJ83a94cdalSuettaLt5lE9WvBZVeqnrZSOJumT1WT@F0ZXzQTTc@LghNVCCGJ1QR@lSwP@T4nn4IOj/dJcQZ4HhRFOYfplBAxjgECMkBtg1oTd7qWfUNVp0uN0@u7IJFjcOcPguEopKFajScRdQYBNRO2oyqNxSK2QJLIqlRTkny5WmQbnpyD@wwUHFe5VFOP434bo9H4JxzNYznayHBC5JsMxEZdz0U9RmK7LGJ5vh15bkBjbJSPXNPrMwaMHXb08DCwqBhhP7CNOiu0HfsW02b0IvR8c4CRb1g/@qy/hLs8Fi7A9CvYm39bWH4A "Ruby – Try It Online")
* Added 3 Bytes to fix vertical lines position as spotted by @Kevin Cruijssen, whom then saved 2 suggesting the use of (bitwise x negated) trick, e.g.
*(x-1)/n => ~-x/n*
Lambda taking *l* list and *n* that outputs an Array of lines.
The first adversity was to draw the vertical line, which can be done after padding, because it's not possible to access a string out of its bounds.
*l.map!{|c|c.map!{|w|..*
First we deep map(columns x words) each word by:
* *tr((0>n-=1)?'':'^ ',?-*
Substitute not-spaces *'^ '* with ?`-` if *n* decreased is still >=0
* *ljust X=c.map(&:size).max*
Pad to max length of column, which is saved in constant *X* for later.
Before we continue to the next column:
*n<0?c:c.each{|w|w[~-X/2]=?|}*
we overwrite each word at X/2 with ?`|` if *n* is still >=0
The second adversity was obtaining rows, *transpose* wouldn't work because the last column is shorter.
*(0...l[0].size).map{|y|*
We build the rows by mapping the range [0..column size) and
*l.map{|c|c[y]}\*" "}*
taking ith rows at each column.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~276~~ 258 bytes
```
L=len
def f(T,s,j=0):
h=L(T[0])
r=[""]*h
for C,u in zip(T,[s-i*h<L(T[i])for i in range(L(T))]):
a=L(max(C,key=L))
for i,w in enumerate(C):r[i]+=((j<s and(c:=L(w)*"-"+a*" ")[:(b:=a//2+a%2-1)]+["|",""][u]+u*c[b]+c[b+1:a]or w)+a*" ")[:a+1];j+=1
return r
```
Yields a [list of lines](https://codegolf.meta.stackexchange.com/a/17095/110555)
[Try it online!](https://tio.run/##xZHfT8IwEMef2V@xNDFp1xEcJsZM9jDGhMncdEwRah8KDBnKIIUFNf7veEVi4iMvuqS36/343me31ftmtizOLlZytwud16zQJtlUn@LUXJtz55TYWmXmhDhlp5xoFekwhLgx0yrTpdQ9s9TzQv/IV1DO1tXcmDVUac6JSucqKUXxnGGIEsKVWEWA2kK8Yc98yd6dkIDqXiw3t6o@K8pFJsUmwx6xJUhRB@N5Y62LYoLHNjRviYGqiAoD6YgwG49sR9RqdSpO6lWLcMrQJzKBkpWclsaYjTgFQy1bcBizJT@dglr8ck4dC74r25QSYHeKRC73JFPMGHJBym16YFv@VbsTXIN31QbTDW8ixE2G7pJeev/Qh9DBexwM4dJLwQzUGe7LVGyoHsS5uV/rSubFBsMwon276KlARPsbAsv6f4T6EQhN1@v23aSlGAK3HUduqCCCSEU6cRIM4yiFmJqSuFErvlHjfb@rXqF/n3bAefCTNPAOVf2gG9z6IAaJfpy0er6beJ1j/85fcp0fwZX6sHu15N89uy8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~165~~ 166 bytes
```
! =length
f(N;n)=""
f(N,l,L...;n=!l,m=~-max(.!l...))=(1:n.|>i->i>!l ? "" : rpad(i>N ? l[i] : '-'^!l[i],m+3)|>x->N<!l ? x : x[1:m÷2]*'|'x[m÷2+2:!x]).*f(N-n,L...;n=n)
```
[Try it online!](https://tio.run/##TY7tToMwGIX/cxVt/9BuhQj@Y1IzdZsfk0SHHwMxIWFoTamEzaQmxNvyArwwfJmfTXpy3qfvSc/Ti5K5Z7oOo1Ct9MPm0SppNNIsJKR3XPG567ojHWLFq/DNqXJDXayAMRZSL9BuK6QjpMAK7SNCUICaOi@oFBHMKpUZENux73HveTXcZa0wjoj2tgEDryb1gurj3c8GdmubtLdDP8AmY@4AKjj6p4JmnVU@N0iGO4HnW3Uj9UZpKplVyHWt8ldaUslTMiacjA8OQY8m09nxySm46QzkbH4ekQw2Li4X8dX1DaBvd7tMYFjEIMv@Jtu1niX9IRljv/@RO02YtdKF9YfiCWT/9/A4Sr8oRLtP "Julia 1.0 – Try It Online")
A recursive solution, using multiple dispatch. `N` and the lists are taken as arguments of the function `f`. Returns a list of strings
+1 to fix a bug pointed out by Kevin Cruijssen
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~205~~ 204 bytes
-1 byte thanks to @Kevin Cruijssen.
```
w=>n=>(R=Array(N=w[0][L='length']).fill``,w.map((C,x)=>C.map((c,y)=>R[y]+=c.replace(a=/./g,s=>j=n>y+N*x?'-':s).padEnd(l=Math.max(...C.map(s=>s[L]))+2).replace(a,(s,i)=>j&&n>=N*x+C[L]&i==l-3>>1?'|':s))),R)
```
[Try it online!](https://tio.run/##vVHRbtowFH3nKyIeiD2MC520B5BTpSGFFAhbQpuVLFKjYGiQ66RJOkDdvp1dh3Z76WtnKTf3Xh@f43u8jX/GZVKkedWR2Yofk0yWlVbweCVSyTUG6dNzWnCkv/V0PGg0TjBfY8cdMyQzkMfMoogPyGW7sBuFU6YLLjfVgx5huk6FuL8nO/oY5whZZI@ZYZ2KhByg8MJD1GYJLXgu4oSjmJ3Rsw0pmbFl0ji03U/7C72j90tM83hlyxUSbBZXD8CxR5TSExnAy3AaYdw@x/@oCCpJChrbVksaDJjaFoBaKWOi89kwehf6L0WMMfHw8e9khahHP01ME8gq7siKF2tF@qKlMn@u@lpeZAkvS1pWq1QSDfYfUxmLvraORcm132BVIWgmkV47R7STqYb20tBgnbRCl2hBBHq1VpmLtEL6QNn8hskEpyLbIAV8p@2ja3/ugjVFyVGAMaozuC5yMel1Md1mKVzhh9TxO6d1pQQ3PXYHYdg0m6RpXloQh/bVaOxcQ3Y1gjCZztxmRMLmN89f3NwG0HrNvt8tofAXEO7Ut6xhqrdUqxlFjV7vA7nPP467tuTStCaB6Q0Vt2OO5q45VeSOqzrjuecs5@4Ceuq0Z7rD@UzR2vZE/ab2zWIMya3tLRzrFRU4E@erDWSwEcy9oW@bnjVWgl/@t2D9MAsbXIiiPw "JavaScript (Node.js) – Try It Online")
Written using currying syntax, call as `S(w)(n)`. Outputs an array of lines containing the ASCII art.
] |
[Question]
[
[Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function), \$\varphi(n)\$, counts the number of integers \$1 \le k \le n\$ such that \$\gcd(k, n) = 1\$. For example, \$\varphi(9) = 6\$ as \$1,2,4,5,7,8\$ are all coprime to \$9\$. However, \$\varphi(n)\$ is not [injective](https://en.wikipedia.org/wiki/Injective_function), meaning that there are distinct integers \$m, n\$ such that \$\varphi(m) = \varphi(n)\$. For example, \$\varphi(7) = \varphi(9) = 6\$.
The number of integers \$n\$ such that \$\varphi(n) = k\$, for each positive integer \$k\$, is given by [A014197](https://oeis.org/A014197). To clarify this, consider the table
| \$k\$ | Integers \$n\$ such that \$\varphi(n) = k\$ | How many? (aka [A014197](https://oeis.org/A014197)) |
| --- | --- | --- |
| \$1\$ | \$1, 2\$ | \$2\$ |
| \$2\$ | \$3, 4, 6\$ | \$3\$ |
| \$3\$ | \$\$ | \$0\$ |
| \$4\$ | \$5, 8, 10, 12\$ | \$4\$ |
| \$5\$ | \$\$ | \$0\$ |
| \$6\$ | \$7, 9, 14, 18\$ | \$4\$ |
| \$7\$ | \$\$ | \$0\$ |
| \$8\$ | \$15, 16, 20, 24, 30\$ | \$5\$ |
| \$9\$ | \$\$ | \$0\$ |
| \$10\$ | \$11, 22\$ | \$2\$ |
You are to implement A014197.
---
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You may choose to do one of these three options:
* Take a positive integer \$k\$, and output the \$k\$th integer in the sequence (i.e. the number of integers \$n\$ such that \$\varphi(n) = k\$). Note that, due to this definition, you may **not** use 0 indexing.
* Take a positive integer \$k\$ and output the first \$k\$ integers in the sequence
* Output the entire sequence, in order, indefinitely
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
---
The first 92 elements in the sequence are
```
2,3,0,4,0,4,0,5,0,2,0,6,0,0,0,6,0,4,0,5,0,2,0,10,0,0,0,2,0,2,0,7,0,0,0,8,0,0,0,9,0,4,0,3,0,2,0,11,0,0,0,2,0,2,0,3,0,2,0,9,0,0,0,8,0,2,0,0,0,2,0,17,0,0,0,0,0,2,0,10,0,2,0,6,0,0,0,6,0,0,0,3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes
```
‘²RÆṪċ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLigJjCslLDhuG5qsSLIiwiMTAgw4figqwiLCIiLFtdXQ==)
```
‘²RÆṪċ Main Link
‘ x + 1
² (x + 1) ^ 2
R range
ÆṪ totient
ċ count how many times x shows up
```
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda i:sum(i==sum(2>math.gcd(n,k)for n in range(k))for k in range(3**i))
import math
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHTqrg0VyPT1hZEGdnlJpZk6KUnp2jk6WRrpuUXKeQpZOYpFCXmpadqZGuCRbIRIsZaWpmamlyZuQX5RSUKIL3/QSoyESoMdSw1rbg4C4oy80o0MnXSNIDq/wMA "Python 3 – Try It Online")
The `3**i` is sufficient. It follows from [this](https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities) inequality.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ 25 bytes
[crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/226099/17602)
```
I№EX⊕θ²LΦ⊕ι⬤…·²λ∨﹪λν﹪ιν⊕θ
```
[Try it online!](https://tio.run/##bU7LCsJADLz7FXtcYb14EjyJIhSsivgD6za0gTTb7qO/v6Y@DoI5JJnMZBjX2eC8pVIqHnI65/4BQY/L7WIXI7asj0hJLhW7AD1wgkZYo3bcaDTq7JOufZPJ69EoXEoZ1cn3NSAnvbdRms@y1nb4Mak4HXDCBvQde4jz@zWIk0s/su7l@GXe6ATcpu5fMvwkIxlEM0U54gQ3yy3otVEkgkv4RhYZy@GDcEbvMmqUvi1lU1YTPQE "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th term of the sequence. Edit: Saved 16 bytes by stealing @HyperNeutrino's upper bound, which then allowed a further 3 bytes of golfing. Explanation:
```
θ Input `n`
⊕ Incremented
X Raised to power
² Literal integer `2`
E Map over implicit range
ι Current value
⊕ Incremented
Φ Filter over implicit range
…· Inclusive range
² From literal integer `2`
λ To current value
⬤ All values satisfy
ν Current value
﹪ Does not divide into
λ Inner value
∨ Logical Or
ν Current value
﹪ Does not divide into
ι Outer value
L Take the length
№ Count occurences of
θ Input `n`
⊕ Incremented
I Cast to string
Implicitly print
```
The innermost loop erroneously counts `0` as coprime, so this is adjusted for by searching for occurrences of `n+1`.
[Answer]
# Haskell, ~~61~~ 55 bytes
```
f x=sum[1|z<-[1..2*x^2],sum[1|y<-[1..z],gcd z y==1]==x]
```
[Try it Online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NDfasKbKRjfaUE/PSKsizihWByJWCRGritVJT05RqFKotLU1jLW1rYj9n5uYmadgq1BQlJlXoqCRm1igkKYAUmpoEKv5HwA)
-6 bytes thanks to Unrelated String
[Answer]
# JavaScript (ES6), 88 bytes
```
n=>eval("for(t=0,j=n*n*3;j--;)t+=(P=k=>k--&&(C=(a,b)=>b?C(b,a%b):a<2)(j,k)+P(k))(j)==n")
```
[Try it online!](https://tio.run/##DcbRCoIwFADQXxlCeq9uo/Qtu0b4A75HxDQNp93JFKGvX52nY81u1s6Py6bYvfowUGCq@t3MEA3Ow0ZHaYlTTovSKlXilhE0NFE1KRXHUBMY2SJV7bWGVppDi2dzyRGsnDBrYMJ/kYgjDJ3j1c29nt0b7lrrm/fmC0WOD/0xC8BTCkZBlRiARSZOiNq6kSGRCWL4AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes
```
n->sum(i=1,2*n^2,eulerphi(i)==n)
```
[Try it online!](https://tio.run/##DcgxDoAgDADArzRO1EAC7OUpJg6gTbSSKu@vLDdc35XD0a0BmYTyjtsxJZ9X2bKv46raT3aMRILWHnUCBMlDitFDV5ZvzgKhTJoTRLQf "Pari/GP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
>nLÕI¢
```
Port of [*@hyper-neutrino♦*'s Jelly answer](https://codegolf.stackexchange.com/a/239775/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/fLs/n8FTPQ4v@/zc0AgA) or [verify the first 25 terms](https://tio.run/##yy9OTMpM/W9k6upnr6TwqG2SgpK933@7PJ/DU/0OLfqv8x8A).
**Explanation:**
```
> # Increase the (implicit) input by 1
n # Square it
L # Pop and push a list in the range [1,(input+1)²]
Õ # Convert each value in this list to its Euler's Totient
I¢ # Count how many times the input is in this list
# (after which the result is output implicitly)
```
] |
[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 [AoC2017 Day 14](https://adventofcode.com/2017/day/14).
---
To recap: The disk is a rectangular grid with \$r\$ rows and \$c\$ columns. Each square in the disk is either free (0) or used (1). So far, you have identified the current status of the disk (a 0-1 matrix), and the number of regions in it (a region is a group of used squares that are all adjacent, not including diagonals).
But we didn't actually defrag the disk yet! Since we identified the regions of used squares, let's assume the shape of each region should be kept intact. It makes it hard to compact the used space, but we can at least move each chunk to the left. Let's do it.
More formally, the algorithm would look like this:
* Identify the regions of used cells in the disk.
* Loop until there is nothing to move:
+ Select a region that can be moved 1 unit to the left without overlapping with another region.
+ Move it 1 unit to the left. (The regions do not fuse into one even if they become adjacent after such a move.)
**Input:** A rectangular array of zeroes and ones.
**Output:** A rectangular array of same size, which represents the result of the simple defrag operation.
For example, if the memory looks like this: (`#` is used, `.` is free)
```
##.#.#..
.#.#.#.#
....#.#.
#.#.##.#
.##.#...
##..#..#
.#...#..
##.#.##.
```
then it has 12 distinct regions
```
00.1.2..
.0.1.2.3
....4.5.
6.7.44.8
.77.4...
77..4..9
.7...a..
77.b.aa.
```
which should be defragged in this way:
```
0012....
.0123...
...45...
6.7448..
.774....
77.49...
.7.a....
77baa...
```
resulting in the disk state of
```
####....
.####...
...##...
#.####..
.###....
##.##...
.#.#....
#####...
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Additional test cases
```
...#####
...#...#
...#.#.#
.....#..
########
->
..#####.
..#...#.
..#..##.
.....#..
########
.....#####..
.....#...#..
.....#.#.#.#
.......#...#
.......#####
->
#####.......
#...#.......
##..##......
.#...#......
.#####......
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 109 bytes
```
#//.x_:>(x-#+RotateLeft/@#&)@ImageData@SelectComponents[Image@x,#BoundingBox[[1,1]]>0&,CornerNeighbors->1<0]&
```
[Try it online!](https://tio.run/##fY1vS8MwEIff71OEBopiZpO3Q0vYRBj4D@e7NEicaVcwF8luECj97LUqTBtEOO7gnnvu5wzurDPYbs1Qk8uBFsV5fF6UJ3FOzx49GrQ3tsZC0vxUrp1p7JVBIzf2zW5x5d27Bwu4V19IRkaX/gCvLTRLH5USTGhd8pytfAAb7mzb7F582M9LccF1PjyEFlBla1hUUEHGyJPf4Lhr1K0ZZ7z2wSmqNSNZBfcH/O@s/jzUmuSkkLOu6wQjY/Fp5z2bEdLxv5g4smP94G@WSKmXRPLfnpj@TL0kMvUmkX3fDx8 "Wolfram Language (Mathematica) – Try It Online")
Repeatedly select the components whose bounding box's `x_min` is greater than 0, and move these components 1 unit to the left.
The `SelectComponents` function has a bug: when it takes an array instead of an image as input, the `CornerNeighbors` option does not work. So we have to convert the input into an image.
[Answer]
# TypeScript Types, 804 bytes
```
//@ts-ignore
type a<T,N=[]>=T extends`${N["length"]}`?N:a<T,d<N>>;type b<T>={[I in keyof T]:{[J in keyof T[I]]:T[I][J]extends 1?[a<J>,a<I>]:never}[keyof T[I]]}[number];type c<T>=(T extends T?(x:()=>T)=>0:0)extends(x:infer U)=>0?U extends()=>infer V?V:0:0;type d<T>=[...T,0];type e<T>=T extends[0,...infer X]?X:[];type f<T>=T extends[infer A,infer B]?[e<A>,B]|[d<A>,B]|[A,e<B>]|[A,d<B>]:0;type g<P,T=c<P>,U=0>=[T]extends[U]?T:g<P,T|Extract<f<T>,P>,T>;type h<P,G=[]>=[P]extends[never]?G:h<Exclude<P,g<P>>,[...G,g<P>]>;type i<T>=T[0]extends[0,...0[]]?T extends T?[e<T[0]>,T[1]]:0:{};type j<T,U=0>=T extends U?T:j<{[K in keyof T]:Extract<Exclude<T[number],T[K]>,i<T[K]>>extends 0?i<T[K]>:T[K]},T>;type M<T,U=j<h<b<T>>>[number]>={[I in keyof T]:T[I]extends infer X?{[J in keyof X]:[a<J>,a<I>]extends U?1:0}:0}
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF0A+W8w9AD3HUQBNIAAwAkAb2r0ARABte8cAAtJjAL6CA-NQBcZKn1LVmzANy4ChAEYVWo+gElCsRIQDW6HMgBmhcoy22AKUdnNw9vcntGPwi7RnoAxi4efkhCAEZ1ejIA5koyO2Y-RHQAN3RUFXpQrx9I1XpEAFcAWwtyxlN8IgBja1oACnYk3gEfdX7OLX6ASlpmclnmAAYtJenhlImtJ09ywgBVRaX1fY5uEcgZuZ29gDV1W9XVzvN9clZ6ADpvqiWOsyI6D6Q3OKXoS0o30+N1QhAAGox1HCtEwXkRPMCzskBPQYYQAIKUPEAIUR9CB+NypIAPvR9JTKDT6ISgcTCrTCfo2X4lmjCPBSAAFSjkWi9QW5fa0JYfXwbHH7RHkLQC4XkakAUW4qGI3XApAx70oEpFJgBhAUQsoAHEGCwGILEqCccUyqhEdatJatd1pI0+EDhaqjJQvt9rZRgyw+bBgeCndjIODId8lkwlViLmNyRR47kImkok9RCo+QArCiUKUytiZlIHdTKiu2ADSwVc7hqvi0WvAOr1pB9foDuaarXaIvoLZYRNz06M8tSx1jEXnWlXqlNfIAspWpRXLVZ3kYGi02u6bPZ29VwtFIovgrtYXD1IFr53vAiUdlcvlCg-9nUNJVhUEDMGwLp4UIWhCF3ehMEIQh6DSSgUIhNDUMoCE-koBCkPQrDMII9DGFwxDk2wwiMLQ0i8OQqiGOo2jyII6jCOw5ikJQjDiKozjkx4hiOLIriiLE7isNo6NwPNAJkCcSsAGVmGgnw6xxPFCShElEREUR8RUMRFMM0Q5IU4lKGUtQtEkSQIPMchkEUvs+jMxBSFbd8wh8PxCDcudSNs5gVEoSQAB1EEkZgZMggBNVTHOc1BSDhaKQEQwgAD11EwIA)
## Ungolfed / Explanation
```
// Converts a stringified number into a tuple
type StrNumToTuple<T, N = []> = T extends `${N["length"]}` ? N : StrNumToTuple<T, [...N, 0]>;
// Converts the input (e.g. [[0,0,1],[1,0,1],[0,1,1]])
// to a union of on cells ([2,0]|[0,1]|[2,1]|[1,2]|[2,2]) (where the numbers are represented by tuples)
type ToUnion<T> =
// Map over the 2d array
{ [I in keyof T]: { [J in keyof T[I]]:
T[I][J] extends 1
// if the cell is on, add this tuple
? [StrNumToTuple<J>, StrNumToTuple<I>]
: never
// put the results into a union
}[keyof T[I]] }[number]
// Retrieves an arbitrary element of a union
type PopUnion<T> = (T extends T ? (x: () => T) => 0 : 0) extends (x: infer U) => 0 ? U extends () => infer V ? V : 0 : 0;
type Inc<T> = [...T, 0];
type Dec<T> = T extends [0, ...infer X] ? X : [];
// Get the orthogonal neighbor positions of a position
type Neighbors<T> = T extends [infer A, infer B] ? ( ([Dec<A>, B] | [Inc<A>, B] | [A, Dec<B>] | [A, Inc<B>]) ) : 0;
type FindGroup<All, Group = PopUnion<All>, LastGroup = 0> =
[Group] extends [LastGroup]
// If the group didn't change last iteration, return it
? Group
// Add to Group the Neighbors of Group that are in All
: FindGroup<All, Group | Extract<Neighbors<Group>, All>, Group>
// Converts a union of positions into a tuple of unions of positions, grouped by connectedness
type Group<Ungrouped, Groups = []> =
[Ungrouped] extends [never]
// If there are no positions left in Ungrouped, return Groups
? Groups
// Find a group, remove its elements from Ungrouped, and add it to Groups
: Group<Exclude<Ungrouped, FindGroup<Ungrouped>>, [...Groups, FindGroup<Ungrouped>]>
// Shift a group to the left. Returns {} (a top type of sorts) if it's at the leftmost border
type ShiftLeft<Group> =
Group[0] extends [0, ...0[]]
// If all X coordinates are >= 1, map over the positions in Group
? Group extends Group
// Decrement the X coordinate of this position
? [Dec<Group[0]>, Group[1]]
// Unreachable
: 0
// Otherwise, return {}
: {}
// The meat of the logic. Continually shifts groups left until it can't anymore
type Defrag<Groups, PrevGroups = 0> =
Groups extends PrevGroups
// If Groups == PrevGroups, return Groups
? Groups
// Otherwise, recurse:
: Defrag<
{
// Map over Groups
[K in keyof Groups]:
// If (Groups[number] (all live positions) - Groups[K]) shares no elements with ShiftLeft<Groups<K>>,
Extract<Exclude<Groups[number], Groups[K]>, ShiftLeft<Groups[K]>> extends 0
// Change this group to ShiftLeft<Groups[K]>
? ShiftLeft<Groups[K]>
// Otherwise, leave it unchanged
: Groups[K]
},
Groups
>
type Main<Input, FinalLivePositions = Defrag<Group<ToUnion<Input>>>[number]> = {
// Map over every row of Input
[I in keyof Input]: Input[I] extends infer Row ? {
// Map over every cell of Row
[J in keyof Row]:
// If this coordinate is in FinalLivePositions, set this cell to 1; otherwise, set it to 0
[StrNumToTuple<J>, StrNumToTuple<I>] extends FinalLivePositions ? 1 : 0
} : 0
}
```
[Answer]
# Python3, 519 bytes
```
import re
r=range
def f(b,x,y,t):
b[x][y]=t
for j,k in[[1,0],[0,1],[-1,0],[0,-1]]:
try:
if x+j>=0 and y+k>=0 and b[x+j][y+k]==1:f(b,x+j,y+k,t)
except:1
def g(b):
n=map(chr,r(97,123))
while'1'in str(b):f(b,*[(x,y)for x in r(len(b))for y in r(len(b[x]))if b[x][y]==1][0],next(n))
return re.sub('\w','#',(q:=lambda r:r if r==(t:=re.sub('\.\w+',lambda x:j if re.findall('^'+(j:=x.group())[1]+'|(?<=[^'+'\.'+j[1]+'])'+j[1],r)else j[1:]+'.',r))else q(t))('\n'.join(''.join(['.',i][bool(i)]for i in k)for k in b)))
```
[Try it online!](https://tio.run/##jVLbbuMgEH33VyDtA1ATy7QPba1l@yGUlewGJzgOdglRbGn/PTu4SVMi9yIhPMztnDPjfvTrzt499O54NNu@cx45nTjhSrvSyVLXqCYVG9jIPC0SVMlByVEJn6C6c6hhG2SslJzlismccbgX58eCKwUlyLsxfJCp0ZA2f0SOSrtEY7o5m9A0baBtulFC8GICTBsGbwCFSj286N4XfKKzIlUgYsW27MnL2jFHHu8Zv72jkHpYm1Zjjo1FO@9CZmh2IwkIoIHwAHSRI622EJw84wcPiKMUaJ5VCq4kaLF68MSG/k77vYN0ne32FcHPB8zwL8zIayHaclstS@QKF4Q6IYgvxHti9nxIMTvlDEUz5eisNnZZti3Bf3FKmkIM2cp1@55QKrlK8T/y9FtIiEEDnDaTT9E3izmq251GYBfgzjA43jyvxFMKmBZnTWcswaevDElGyarrWmKoCupNUL@ZBhE2iWAo9FiJsFEEJ49vmAWS@VyEnyLv5xIMkauCuOYKKr/U8LhbXHMFFddEUEolvTPWk/Dv0JONF/jmNqdJEPux1eVEkiLAmcgnY5ijd31@Tm@GZLSXGdiZ7c2v6SsJ343gU3axtON/)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 190 bytes
```
w=>g=a=>a.some((c,i)=>!a.some(n=_=>a.some((d,j)=>(r=~j%w?j+1:j,d-c)?d*n[r]:(n[j]=[j,j%w?j-1:j,r,j-w,j+w].some(k=>n[k]))*!(j%w)),n[i]=++t))?g(a.map((c,i)=>n[i+1]?t:!n[i]*c)):a.map(c=>c>0);t=1
```
[Try it online!](https://tio.run/##fU/NbqMwEL7zFI5Qiyc4k@ZKa3iCPgG1WkQItUtMhK1w66tnx4Zse1jtWGK@8fczxjTXxrWTvvidHY/d7SRvsyx72ciyQTeeO85boUGWm3W08v2HOgpDFJ/kt3mYK5MfCiOOuxaq49bWkyq4rY2StRGR3gV6EmY3C5PPasn4kqWtvxTAdsNJBSBsrZXMcw9Q9bzBc3O5v4GY/KAqX2yCZtsCFAvfyrItn@DZy8PNd84zybgTbKbu0E/6zAHdZdCe79/cHuonhUNne/8JTJbsxGfgjoJ8@8n3dYpq30PMtYGmj5QsSzMAPA2Nfw0PehdMCzZFv2YPtKpitWIFm/CkB99NUWIib1gpSfT4SOiFQM7mJf4a2Cs5KZysGWaAZtSWZ2HXgt5sBuQIPUna0bpx6HAYex7@k38kaYrhYIILSBOkCiiJY7yJItJQDyDcRBGudhJ/ADz/c0EQhkoWB67gvmlNWeq/KWtOeCres36GX4m/9vx1heTbHw "JavaScript (Node.js) – Try It Online")
Input as 1d array of boolean values and width as an integer. Output 1d array of boolean values.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~120~~ 105 bytes
```
WS⊞υι≔⊕Lθθ≔⌕A⪫υψ#η≔⟦⟧ζWη«≔⟦⊟η⟧εFεF⁺κ⟦θ¹±¹±θ⟧F№ηλ«⊞ελ≔⁻ηεη»⊞ζε»WΦζ⬤κ∧﹪μθ¬⊙ζ›№ξ⊖μ⁼ξκFιUMκ⊖λEυ⭆ι§.#⊙ζ№ν⁺×θκμ
```
[Try it online!](https://tio.run/##VVHBboMwDD3DV0T04kgZUs89oW6dOq0T0narekAlI1FDUiBsbad@O7MJXTUjAi9@8Xt29qpo964ww/CttJEM1vbY@3ffalsB5yzvOwW9YJov4qzrdGWRsW9lLa2XJbxKW3kFDeeCNXfKStsyMwZenLZ0@ozpZJbgqu6k7U6wC8JJWHH2E0e3XO6OuIMMiYzo07UMJGfjNzd9BwfBto1gc8HeZFV4CXP@99vwHZ@4S9dbD0oww8fy0diPJIxlb2obbbGkIrHgMLrGgXkJBq43kyttvGxpm9pDE5ktYePK3jioaQRownnI7Jk4z60siB5cnAR7lPfR1TSzp6YvTEepA58iGNecbYrj0tV1gQqH/0exmUWc4xV5QBINOFwYAY2e/NqW8gRJOkvI4egleLCCjeP70LXsoCFZwepJeTEMKcWMIk3jAMJ7A@MTwJT7AxTx8PBlfgE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of `.`s and `#`s and outputs a list of newline-separated strings. Explanation:
```
WS⊞υι
```
Input the cells.
```
≔⊕Lθ
```
Get the offset between each cell and the cell below. (This is one more than the width so a region at the end of a line doesn't inadvertently connect with the one at the start of the next line.)
```
≔⌕A⪫υψ#η
```
Get the list of used cells.
```
≔⟦⟧ζ
```
Start with no regions.
```
Wη«
```
Repeat until all of the used cells have been allocated to a region.
```
≔⟦⊟η⟧ε
```
Start the region with the last (i.e. golfiest) used cell.
```
Fε
```
Perform a breadth-first search over the region.
```
F⁺κ⟦θ¹±¹±θ⟧
```
Enumerate the coordinates of the adjacent cells.
```
F№ηλ«⊞ελ≔⁻ηεη»
```
If this is a used cell, then add it to the region and remove it from the list of used cells.
```
⊞ζε
```
Save this region to the list of regions.
```
»WΦζ⬤κ∧﹪μθ¬⊙ζ›№ξ⊖μ⁼ξκ
```
Repeat while any regions can be defragmented...
```
FιUMκ⊖λ
```
... move all cells in those regions left by 1 cell. (Sadly `MapAssign` doesn't do what I want here.)
```
Eυ⭆ι§.#⊙ζ№ν⁺×θκμ
```
Output the original input updated with the new locations of all the used cells.
Previous 120-byte version did not require rectangular input:
```
≔⟦⟧θWS«F⌕Aι#⊞θ⟦Lυκ⟧⊞υι»≔⟦⟧ηWθ«≔⟦⊟θ⟧ζFζFE⁴Eκ⁺ν∧⁼ξ&¹λ⊖&²λF№θλ«⊞ζλ≔⁻θζθ»⊞ηζ»WΦη⬤κ∧§μ¹¬⊙η›№ξEμ⁻ρς⁼ξκFιFκUMλ⁻μνEυ⭆ι§.#⊙η№ν⟦κμ
```
[Try it online!](https://tio.run/##VZHBboMwDIbP5SksekmkDKnTbj2xbp0qrRPSjlUPqGQQEUKB0Had@uzMTsraGaHIsWN/v70r0nZXp3oY4q5TuWGbrYCGz4NjobQEtjL73n7aVpmccQ4/weSrboEtlclirZkSEE5DDCR9V7BGwOZdmtwWrOcCyi3WmbhIL0ChcwnuuhS3Lo2rPMaSeo83mHGm967fmYM71@mePQmgoxSQ6L5jRkBsMvba9Knu2EnAs7JH1Um6nAnQHEle5K6VlTRWZuwu/OjCznz5Rd0bSzK01@rhz@QjyQi4Vgb7NsTnZzW5XGUWnvky6loqbWVL1zSs0pPGdmUyeWKVgBkW@Kgti803Jb21MqV8j3HyOjHNN2wFHEjMTWnJ/9Gr61lyerioqyrFdnp8j4UMR7oEl2ndJHErfrXk4CpHsjCahsTqoDwMTnmD/NXWN5wPQ0Q2JYuiwDv@Hx33eeca@3PIguHhoH8B "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of `.`s and `#`s and outputs a list of newline-separated strings. Explanation:
```
≔⟦⟧θ
```
Start with no used cells.
```
WS«
```
Loop over the input strings.
```
F⌕Aι#⊞θ⟦Lυκ⟧
```
Record the used cells in this string.
```
⊞υι
```
Save this string so that the output has the same shape as the input.
```
»≔⟦⟧η
```
Start with no regions.
```
Wθ«
```
Repeat until all of the used cells have been allocated to a region.
```
≔⟦⊟θ⟧ζ
```
Start the region with the last (i.e. golfiest) used cell.
```
Fζ
```
Perform a breadth-first search over the region.
```
FE⁴Eκ⁺ν∧⁼ξ&¹λ⊖&²λ
```
Enumerate the coordinates of the adjacent cells.
```
F№θλ«⊞ζλ≔⁻θζθ»
```
If this is a used cell, then add it to the region and remove it from the list of used cells.
```
⊞ηζ
```
Save this region to the list of regions.
```
»WΦη⬤κ∧§μ¹¬⊙η›№ξEμ⁻ρς⁼ξκ
```
Repeat while any regions can be defragmented...
```
FιFκUMλ⁻μν
```
... move all cells in those regions left by 1 cell.
```
Eυ⭆ι§.#⊙η№ν⟦κμ
```
Output the original input updated with the new locations of all the used cells.
[Answer]
# [Python 3](https://docs.python.org/3/) + scipy, 162, 160 bytes
```
from scipy.ndimage import*
def f(A):
B,J=label(A.T);j=1
while~J+j:C=B==j;B[C]=0;D=C^C;D[:-1]=C[1:];d=C[0].any()|B[D].any();B[[D,C][d]]=j;j=d*j+1
return B.T>0
```
[Try it online!](https://tio.run/##XVJBboMwELz7FSuQKjshq0S9gRwpkFPO3AiVaIHGCAwipAlS1a@nxjZpVHNgdnZm1th043Bq5ev9XvZtA@cP0Y0oc9FknwWIpmv7YUHyooSS7phPIPQOvM7ei5ruMGZBxTcEridRFz@HZeVHPOS8CsIkSvk62PPoLQr2ib/apDxKNn4a5Oq9TjGTI2XfYbK3UDmSvRelSZ6myl/xfFEtVXJfDJdeQojxdm02KC9NN9qNQdb32Uhi7jiO6@L0IEEDXAAgqNZUTFiTM6/VaHh30sy8Nsy8NpDVVuFJpcMNsuEP7NqGDdfiOeShNzMtb0TEpKhFzGS0wDVAc0Y9adRWrByJlVtgmP96S5lhjz4@FU@TnuY/XPPHu5Yk1m4L1x6BOZq/FsEnk7ocPHe1GKhzlEfpMFK2PQwgJMTqhxItH/76q61WgPBa4ED1BdPkZgUsZRjjlyiu1BEOe9nAFHWbokSrXF0v5ECFR1vOSyoYw6yuKWP3Xw "Python 3 – Try It Online")
#### Older versions:
```
from scipy.ndimage import*
def f(A):
B,J=label(A.T);j=1
while~J+j:C=B==j;B[C]=0;D=C^C;D[:-1]=C[1:];d=C[0].any()or B[D].any();B[[D,C][d]]=j;j=d*j+1
return B.T>0
```
[Try it online!](https://tio.run/##XVLBjoIwFLz3K14g2bSKL5q9SWoicPLMDdmEXWAtgUIQV7nsr7ulLWq2HJg3b2ZeaenG4dTK9/u97NsGzl@iG1Hmosm@CxBN1/bDguRFCSXdsy2BwDvwOvssarrHmPkV3xC4nkRd/B6W1TbkAeeVHyRhytd@xMOP0I@S7WqT8jDZbFM/V@91ipkcKWt7CJLIFsqTRF6YJnmaqoSK54tqqbL7Yrj0EgKMd2uzRXlputFuDbK@z0YSc8dxXBenBwka4AIAQbWmYsKanHmtRsO7k2bmtWHmtYGsdgpPKh1ukA1/YNc2bLgWzyEPvZlpeSMiJkUtYiajBa4BmjPqSaO2YuVIrNwCw/zXW8oMe/TxpXiZ9DL/4Zo/3rUksXZbuPYIzNE8WwRfTOpy8NzVYqDOUR6lw0ip7n4AISFWv5Ro@fDsr3ZaAcJrgQPVF0yTmxWwlGGMP6K4Ukc47G0DU9RtihKtcnW9kAMVHm05L6lgDLO6pozd/wA "Python 3 – Try It Online")
# Explanation
Leaves the heavy lifting (the segmentation) to a library function, `scipy.ndimage.label`.
The rest is relatively straight forward. Everything is done with transposed axes to save indexing clutter. We push one labelled component one unit a time until we run through all of them without being able to move anything anymore.
More specifically, `C` selects the pixels for label `l` and we immeditately zero them out; `D` shifts the selection. `d` decides based on whether there are labelled pixels (1) in the base column or (2) (after shifting) collisions with other labels. If `d` is set we write the erased pixels back and move to the next label, if `d` is not set we shift them and reset the label index.
[Answer]
# Java 10, ~~463~~ ~~459~~ ~~444~~ 443 bytes
```
int M[][],v;m->{int l=m[0].length,t=m.length*l,i,F=v=1,f,x,a,b;for(M=m;v++<t;)for(i=t;i-->0;)i=m[i/l][i%l]==1?f(i/l,i%l)-1:i;for(;F>0;)for(F=v=0;v++<t;F=f>0?1:F){for(f=-1,i=t;i-->0;)f&=m[a=i/l][b=i%l]==v&b>0?(x=m[a][b-1])<1|x==v&b>1?1:0:f;for(;f>0&++i<t;)m[a=i/l][b=i%l]-=m[a][b]==v&b>0?m[a][b-1]=v:0;}for(;t-->0;)m[t/l][t%l]=1/~m[t/l][t%l]+1;}int f(int x,int y){try{if(M[x][y]==1){M[x][y]=v;f(x+f(x,y+f(x-f(x,y-1),y)),y);}}finally{return 1;}}
```
-5 bytes thanks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explanation:**
```
int M[][], // Integer-matrix on class-level, uninitialized
v; // Value-integer on class-level, uninitialized
m->{ // Method with integer-matrix parameter & boolean return
int l=m[0].length, // The amount of columns in the matrix
t=m.length*l, // The total amount of cells in the matrix
i, // Index-integer, starting uninitialized
F= // Flag-integer, whether we can still move anything
v=1; // Set it and the class-level value both to 1
f, // Flag-integer, whether the current region can move
x,a,b; // Temp-integers to save bytes, uninitialized
for(M=m; // Set the class-level `M` to the input-matrix
v++<t;) // Loop `v` in the range (1,t):
for(i=t;i-->0;) // Inner loop over the cells:
i=m[i/l][i%l]==1?// If the current cell contains a 1:
f(i/l,i%l,v) // Flood-fill the region with the current `v`
-1 // And break out of the inner loop
: // Else:
i; // Simply continue the loop
// (now every region has its own positive integer)
for(;F>0;) // Loop as long as `F` is still 1:
for(F=v=0; // Reset `F` to 0
v++<t // Inner loop `v` in the range (0,t):
; // After every iteration:
F=f>0? // If `f` is 1:
1 // Set `F` to 1 as well
: // Else:
F){ // Leave `F` the same
for(f=-1, // Reset `f` to -1
i=t;i-->0;) // Inner loop over the cells:
f&=m[a=i/l][b=i%l]==v
// If the current cell contains value `v`,
&b>0? // and this is NOT the first column:
(x=m[a][b-1])<1
// If the cell at the left contains a 0
|x==v // Or the cell at the left contains value `v`,
&b>1? // and this is also not the second column:
1 // Bitwise-AND `f` with 1
: // Else:
0 // Bitwise-AND `f` with 0 instead
// (if the check is truthy: -1→1; 0→0; 1→1;
// if the check is falsey: -1→0; 0→0; 1→0)
: // Else:
f; // Bitwise-AND `f` with itself to stay `f`
for(;f>0& // If `f` is now 1, which means we can move the region
// with value `v`:
++i<t;) // Do another inner loop over the cells:
m[a=i/l][b=i%l]-=
// Decrease the value in the current cell by:
m[a][b]==v // If the current cell contains value `v`,
&b>0? // and this is NOT the first column:
m[a][b-1]=v // Set the cell at the left to `v`
// Set the current cell to 0 by decreasing by `v`
: // Else:
0; // Decrease by 0 to stay the same
// After everything has been moved,
for(;t-->0;) // loop one last time over the cells:
m[t/l][t%l]= // Change the value in the current cell to:
// Transform all positive values to 1,
// while keeping any 0s the same:
1/~m[t/l][t%l]+1;// (1 integer-divided by (-value-1)) + 1
// Recursive method with coordinate as parameters & integer return-type
int f(int x,int y){
try{if(M[x][y]==1){ // If the current cell contains a 1:
M[x][y]=v; // Fill the cell with the current value
f(m,x,y-1) // Recursive call west
f(m,x-...,y) // Recursive call north
f(m,x,y+...) // Recursive call east
f(m,x+...,y);} // Recursive call south
}finally{ // Catch and swallow any ArrayIndexOutOfBoundsExceptions
// (shorter than manual if-checks)
return 1;} // Always return 1, so we use it to our advantage to
// save bytes
```
[Answer]
# [Rust](https://www.rust-lang.org/), 558 334 bytes
```
|p:&mut Vec<Vec<_>>|{fn k(x:usize,y:usize,p:&mut Vec<Vec<u8>>){if p[y][x]==1{p[y][x]+=2;if x>0{k(x-1,y,p)}if x<p[0].len()-1{k(x+1,y,p)}if y>0{k(x,y-1,p)}if y<p.len()-1{k(x,y+1,p)}}}loop{let q=p.clone();for j in 0..p.len(){k(0,j,p)}for i in 0..p[0].len(){for j in 0..p.len(){if p[j][i]==1{p[j].swap(i,i-1)}p[j][i]&=1}}if p==&q{break}}}
```
[Try it online!](https://tio.run/##tVPLjqMwELz7K7wgZWyFWGFPoxD4jL2waMQi0JAh4GDQwADfnnXb5pHMXtcI0a6q7i4bu25Fc89KfI3zklA8ICxHkTY4wz6@j/y0u7YN/pUmZ3jfgmAcpPqDdKdW5F@p05vvk7B9DQI65BnmYR@FXeT77mDCvf/Tk0QXHAdZ5uA6vcPpBMiZh8eIFak0cnCB3K9kr@VOLxMMcuZbrdPvFTNNRVXxAZZw8zlLiqpMCfWyqsYXnJf4yJjJk1lH5wI5QOYzuXgY/pWjlnSJwtws6RIx8Rlzkjv5waWT4Xa@O4FH7vu72/CnTuMPaewOe@upHYbSJC952zg4LsVnWlNotAsRQZZtM3gYYjqwEZMDIqSmClEiqZFfCABRIoUokeVAKeBVKR1BKR3YBlIUM6WMRtcGRHMWog44U8lyIN2KmWC2aNrrAe2NHLpqdzrQyLN@7TGnrSq2mWz6bVwsWfOybQMik87Ysl1mtmzZukNmIr2o3xSZCzFfCvXHTg@nXF6TVTPr4Cp0klF6JniRN8T6XVqUXeVZGcUoWPIe14IYIBlJ4vsv9gvFscDtK2VJVRRp0hC6Cb2HPhlRN657grtlNnkP3vUx@2Zew//BYyxEWjdv6e3H00HXkglN6P4X "Rust – Try It Online")
* -224 bytes (wow!) by changing the algorithm (Thanks @alephalpha)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 157 bytes
```
m->while(a=0*m;a[,1]=m[,1];while(a!=b=matrix(#a~,#a,i,j,m[i,j]&&matrix(#a~,#a,k,l,abs(i-k)+abs(j-l)<2&&a[k,l])),a=b);m!=n=a+concat((m-a)[,^1],0*m[,1]),m=n);m
```
[Try it online!](https://tio.run/##ZY7RTsMwDEV/peukKmaOlPBIyN554gOiILkTg2xNiEoR8MKvl5Q1bSZkxbJ9rm5upN7xlzgeKz16vv98dd0zIy1uvCKD0mo/dTXfN7rVnobefbEt/eCW0OEJvUndNs01OWOH1L4zx8@wm4YT7@D@tmnIJGQBkHQLym900LQ7vIUDDYx5TmDwSVpMEaavAb0OSTZSjN03o4rvq9i7MLD6IdzVoC5bZJRHVj9@DCU5JgZYGSNRolieUOJql2m/1HxRK818dRB/XC76zFeHzBcHmzJkPJcq5EWE/5FKy6KshfEX "Pari/GP – Try It Online")
] |
[Question]
[
Everyone knows, that you can leave out the multiplication symbol (\$\times\$, or `*`) in
* `a*b`
* `23*a`
* `(2+3)*a`
* `a^(b*c)`
* `(a+b)*(c+d)`
but not in
* `2*3` => you don't want it to be 23
* `a*23` => most mathematicians just don't do it
* `a^2*b` => now it's `(a^2)*b`, if you remove the `*`, it's `a^(2b)`
* `a/2*b` => now it's `(a/2)*b`, if you remove the `*`, it's `a/(2b)`
* `a*(2+3)` => most mathematicians just don't do it
But does a program know it to?
# Notes
* The input is an equation which has the basic operations (`+`, `-`, `*`, `/`, `^`), parentheses (`(`, `)`) and sometimes some 1-letter variables
* The output should be the input with unnecessary `*`s removed where possible
# Examples
```
a*b
> ab
2+3*a
> 2+3a
23+67/(56+7)
> 23+67/(56+7)
2t
> 2t
2*3+5/6*b
> 2*3+5/6*b
2*a*3
> 2a*3
2*-3
> 2*-3
a*-3
> a*-3
a^2*b
> a^2*b
a/2*b
> a/2*b
a*(2+5)
> a*(2+5)
(2+5)*a
> (2+5)a
23+(2*a)^(45*b)-c/5+24d+(2a)*(2b)
> 23+(2a)^(45b)-c/5+24d+(2a)(2b)
(a-b)*(2+e)
> (a-b)(2+e)
a*b*c
> abc
2*(3)
> 2(3)
(2)*(3)
> (2)(3)
2(3)
> 2(3)
(2)*3
> (2)3
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), 5 bytes
```
Defer
```
`Defer` displays the expression in unevaluated form, leaving out the asterisks.
[](https://i.stack.imgur.com/Mq7or.png)
If you don't mind that Mathematica automatically combines some terms, and just want to eliminate the asterisks, no function is needed, giving the following 0-byte solution:
[](https://i.stack.imgur.com/1p5Wc.png)
When it strips out the asterisks, `Defer` will usually remove mathematically unnecessary parentheses; however, they are sometimes retained for clarity:
[](https://i.stack.imgur.com/l6WRu.png)
When Defer removes a mathematically necessary asterisk, it will replace it with either parentheses or a `×` glyph:
[](https://i.stack.imgur.com/pHIl7.png)
For an additional 14 bytes (19 bytes total), Mathematica will dispense with both the asterisks and the times glyphs, using spaces instead.
To accomplish this, we need to operate `OutputForm` on `HoldForm`. Here `HoldForm` is needed instead of `Defer`, because while `Defer` *displays* the unevaluated form, it does not actually return the unevaluated form. To produce the desired result, `OutputForm` needs to operate on the unevaluated expression:
```
OutputForm@HoldForm
```
[](https://i.stack.imgur.com/6VabW.png)
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 41 bytes
```
s;([/^]\d+\*)|\*(?=[a-z]|(?<=\).)\();$1;g
```
A regex substitution which validates all the test cases.
[Try it online!](https://tio.run/##XZDNasMwEITvegoTdNAPjlI5csCu6weJk7CyRSmY2m1cKCXPXne1CpT2NPMtI@2wc3gf3WrEVkn2lEUxNb80/KHmoeG2Xq@1OJrzqRt0p@StU6JtjpB/nW6ifWw6uZWdkDXGn1d6d8nCGw/tVG0y6JcPGKs4@pxDv4Sh4mGzgvK4CTxjVhcK0KMCUqHLgxGu1IdY5Q8yu8TRgkYV2pmS/vj1OAZVxFEUpJwgCoMEkOBs03pSBuaOJqESVjtJ6eQYCbUkl3oKXCfPYu@Ul3lvnLb7AYcg8ZW/l48YI/8SFGACch/DOtDVIyXACl71dJ/@e5qXl@n1uua73Tj/AA "Perl 5 – Try It Online")
# [Perl 5](https://www.perl.org/) (`-p`), 79 bytes
```
$_=reverse;s;([a-z]|\((?=.\)))\K\*(?!(\)([^()]|(?2))*\(|\w+)[/^]);;g;$_=reverse
```
Handling tsh's case
[Try it online!](https://tio.run/##XZFdbsIwEITffYoU5WHXVjB1MEhYNAfoETBBTrCqSqhJIf1Rxdmbrm0qSp9mvslmd5T0/njQo4QpR/aQBZEm363ze5P7da7MSHD07/548uZkYOOKr@3ZAlTrqUVE@2g5VHdgETY14PYMlULkFs72Q@BG1ls05slcl4xx@y7zr7mvutUkc@3w5g6rEH32vh38fpX7yeh4Q31cw5gSJXfkSR1RKRZLCXohlqHwDTI1hGggw0uh5SLuuHqKHS9DFISoiBCEuQQuQa3S@ajMyQvKhByU0Bink2NRYsvoUk@gc1jDXPMGi1ZqoeZ7Ch3SW82lfMAw8m8iDjBwRROGhY//JlACqtDwNn6flk7VUP6ev/oUg8Y/Dy703fXDc/dyGovZ7ND/AA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~77~~ 76 bytes
Regex solution :
```
lambda x:re.sub("(?<![\^/].)\*(?=[A-z])","",x).replace(")*(",")(")
import re
```
[Try it online!](https://tio.run/##XZHZbsIwEEXf@Yqpn7wkpE0ISKgp6neEINnGUZEgiRJXokV8e@oFstQvvvfM2GPPND/6q66Svsz2/ZlfxJHDdduqZfctMMK795d8f4iKJdlTvMvyz/C3IChAKLiSZauaM5cKI0KxYcSIxenS1K2GVvVadVryTnWQQb4AszDiVKAAEBeIBA8Us4RyC43gE5yw9SbC6ZptiItO/ZilXUxPCE1YGq19ndFM4pwmLmb3CQ49tftA@YPyOT3Ej284MfLoyaM5pzhmKfEXeTnEnPX/d3LeAWxeSw54lVJBQhmlLF4dDeSm37F4tsV6m/MvxWWMdXgo7Cmm3DFnvZs8U1DppyPNIItFWbegJZwqGEa5dblNe6o0LtFNy/y1uEP2AbcSO0PugC1@KyDLYICmTP8H "Python 3 – Try It Online")
Regex are ugly. Useful but ugly
Thanks to @ovs for -1 byte
[Answer]
# [Python 3](https://docs.python.org/3/), 214 bytes
```
def f(x):
s=''
for i,c in enumerate(x):
if(c=='*'):
if ((x[i-1:i+2]==")*(")or(x[i-1].isalpha() and x[i+1].isalpha())or( x[i+1].isalpha())and(x[i-2]not in"^/"and x[i+1]not in"-+") ):
c=''
s+=c
return s
```
[Try it online!](https://tio.run/##ZZLdboMwDIXveQorN@SnjA1KK1XKXqSiUkiDirRBBanUqeqzs8ShhW5X8fl8nDhxzj/21LX5OB5NDTW9sl0Eg4zjCOquh2aloWnBtJdv0ytrQh6ammopYx6jchIove6b5GPXiKyUkjBOCev6AMu3ZlBf55OiDFR7BAfFEnrjf@icWJ6VbWddE@SQkrl6YokgDEIToLFrGITUEfTGXvoWhjGKrBmsVoMZQMIenZQoXpEVEFURtppQJnKuPHSBWuBcbLYpLTZiyzC71LPLYs4uCM9FkW7CObNY5BXPMefXBU4C9euTqomqV3rIpmtgMPP0wdNXzmkmChY2CuEzhzLcH8PXF6CuW3ag64JXLNFpIbL10UHlxpxVj2fx2nv@WNAxn6OSylcJg2Uog1q0WXEdpqMJi8rIf0SL//A5yjDxc9@0ltbkZvX@vbyD/IRbTVGwO1CPP0qQEp7QHTP@Ag "Python 3 – Try It Online")
ok this is really bad lol, sorry I'm new, any suggestion would be awesome!
EDIT: Ok, I think that's the shortest I can do lol, and FINALLY it works!
thanks to Kateba and Jakque for tips and ideas
EDIT2: not doing lambda because I don't fully understand how it works lol
] |
[Question]
[
In North America, most electrical outlets/receptacles follow standards set by [NEMA](https://en.wikipedia.org/wiki/NEMA_connector). For this challenge, you'll be given a few properties of a device you need to plug in, and your program (or function) should return all of the outlets that would be compatible.
For this challenge, an outlet has three properties: voltage, current rating, and grounding.
**I/O:**
Input will consist of a voltage, current usage, and grounding requirements for some device. The first two are positive integers, and the third can be represented by a boolean (though you are allowed to represent it in any reasonable way).
The output should be a list of outlets which are compatible, following the rules below. Each outlet's name is formatted as `NN-nn`, with `NN` and `nn` being numbers. All outlets should either be returned as strings with this formatting, or arrays of `[NN, nn]`. You can return the compatible outlets in an array, or separated with spaces/newlines/commas, or via any other reasonable method.
**Requirements:**
In order for an outlet to be compatible with the inputted device, it must meet three requirements:
* The voltage should be within ±10% of the device's voltage
* The current rating should be at least as high as the device's current usage
* If the device requires a grounded outlet, the outlet must be grounded (otherwise it may or may not be)
**Outlets:**
These are the outlets your program must be able to handle:
```
1-15 120 15
2-15 240 15
2-20 240 20
2-30 240 30
5-15 120 15 G
5-20 120 20 G
5-30 120 30 G
6-15 240 15 G
6-20 240 20 G
6-30 240 30 G
6-50 240 50 G
7-15 277 15 G
7-20 277 20 G
7-30 277 30 G
7-50 277 50 G
10-30 240 30
10-50 240 50
11-20 240 20
11-30 240 30
11-50 240 50
12-20 480 20
14-15 240 15 G
14-30 240 30 G
14-50 240 50 G
14-60 240 60 G
```
The first column is the name of the outlet, followed by the voltage, then the current rating, then a `G` if it's grounded. Some of these may be slightly inaccurate.
**Test Cases:**
Formatted with a voltage, then current usage, then a `G` for grounded or an `x` for ungrounded. Some do not have any compatible outlets.
```
120 16 G 5-20, 5-30
260 5 x 2-15, 2-20, 2-30, 6-15, 6-20, 6-30, 6-50, 7-15, 7-20, 7-30, 7-50, 10-30, 10-50, 11-20, 11-30, 11-50, 14-15, 14-30, 14-50, 14-60
260 5 G 6-15, 6-20, 6-30, 6-50, 7-15, 7-20, 7-30, 7-50, 14-15, 14-30, 14-50, 14-60
260 35 x 6-50, 7-50, 10-50, 11-50, 14-50, 14-60
480 10 x 12-20
108 10 x 1-15, 5-15, 5-20, 5-30
528 20 x 12-20
249 50 G 6-50, 14-50, 14-60
250 50 G 6-50, 7-50, 14-50, 14-60
304 10 x 7-15, 7-20, 7-30, 7-50
480 10 G
480 25 x
400 10 x
600 10 x
180 10 x
80 10 x
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins!
[Answer]
# JavaScript (ES10), 159 bytes
Same logic as my original answer, but with the data stored as a string with several unprintable characters.
```
(v,r,g)=>[..."_Î^~248ÕScž"].flatMap(x=>(x=x.charCodeAt(),n+=x>>6,V=(120<<x/16%4)%683,R=~(x/2&7)*10%65,-R<r|x&g|(V-v)**2>V*V/100?[]:n+[R]),n=1)
```
[Try it online!](https://tio.run/##lVDNbtNAEJYQp1yQoJVaTqNI7e4mG2d345/QZFMhBDlxSSRfUoMsx0lTRXawTWRE6RMguMANeA7O9E36AjxCWG/StE2QEJb8jebbmW9mvjN/7qdBMplltSgehouRXOA5TeiYyM7AMIzyg9ePdi8/3bv/6uHO3oUwm5df9/u7@8GvHzt7j8ueMZr62Ut/hnPZUX9uBKd@8kwJPc0woVFV5p2OTV2JuWDtdl7n9oFJDuxmg/bkBc7r4tAhFc4ObIvWeu3kPD8cn2O3NieViui4FbfOGTseeEdRddDzlKDkZJGEb95OkhCjUYqIkYT@8MVkGvbfRQFmxMjifpZMojEmRjqbTjJcPonKxBjFyXM/OMUpyA68LwEMYE4hoTCmEOazMMjCIXggIV211QGqddICV3HVeQt6RUxa0FVxDFIC6qKW0klCJQkj7FLoUegS4yyeRBhRQKR4DuIojaehMY3HeLCeiAYIqrq1CsiDIsFaSN4scwzo98/PV9@@KERwBOjq@0dEvJX@SYaIGvCBLJSzoD5uF9gtwKoJRhU2WEnY@tEqAPICRI1bVGFRIlQJBVsztmbsFWMpdDTvaN7RvKN5znSigs64LlChsQyaNHWvCo1ltiLtjY30uv89/5/iDWt97rWUdWdja7PRbC5NZOtGXlhU4qy5yevh1grXRltCF4pNAWE@0eeyW@duTRfL560iZ7u0wcyNhf5u092LtOY1JW7cKZls8@6SvU3xLXdKS@Y29Qc "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES10), ~~200 190 186~~ 181 bytes
Expects `(voltage, current, ground)`, where `ground` is a Boolean value. Returns an array of strings in `NN-nn` format.
```
(v,r,g)=>"0F5F1315CE02045E1214187E323438D519531519639E14181A".match(/../g).flatMap(x=>(x='0x'+x,n+=x>>6,V=(120<<x/16%4)%683,R=~(x/2&7)*10%65,-R<r|x&g|(V-v)**2>V*V/100?[]:n+[R]),n=1)
```
[Try it online!](https://tio.run/##lVDBbtpAEL3zFSMksrt4sXfXXhsCJqpa4NQLkXwhHCwwriNqU@MiR037BZV66bH9j35PfqCfQNcLIYmpVNWS32jfzLx5M7fhLtwu8mRTdNJsGe1X/h7vaE5j4g@bbCzH3Oby9YgJ5sgRF9zhXW9kC9uxu28k70mV5T3X7o2qDH/VNN@HxeIdtkzTiom5WofF23CDS3@ofsRKZJQ0NfxyOHRp4GMu2GBQWtxtOaTldm069b/g0hIXHmlz1nIl7UwH@X15Ed/joLMj7bYYBu3A4oxdzeaXqTGbzglNfU72efThY5JHGK22iJh5FC7HyTq6vksXmBGzyK6LPEljTMztZp0UuHmTNpW/LB@Fyu4W/CF8agDMYEchpxBTiMpNtCiiJczBh@2xzQIwLNKHQHHGrg/TKuZ9mKgYg@8DmqC@0skjJQkrHFCYUpgQ8zZLUowoIFKlF1m6zdaRuc5iPDtNRDMEhm41AM2hemAt5D@ZuQL0@9e3hx/fFSK4BPTw8ysi86P@TYGIGvCZ7NVlQX3crXBSgewIRhXarCFcnZQVQFmB6HBJFVYlQpVQcDXjasY9MlKhp3lP857mPc1zph8q6BfXBSrYh6BJR/eqYB9eR9KtOdJ2/3v@P8VteVr3UUq@cCzrjU73cER2auTViRqcdeu8Hi6PeDq0FLpQ1AWE09Prsmfrnk0Xh/RZkXdeajOnZujvZ3q5kdZ8pMTTdRoOq@/dcM8pfnadxoF5Tv0B "JavaScript (Node.js) – Try It Online")
## How?
### Encoding format
Each outlet is encoded as a byte `x` whose bit-mask is `DDVVRRRG` with:
* `DD` = difference between the leading outlet ID and the previous leading outlet ID
* `VV` = voltage: `[120,240,480,277]` mapped to `[0,1,2,3]`
* `RRR` = current rating: `[20,30,50,60,15]` mapped to `[1,2,4,5,7]`
* `G` = flag set if there's no ground
For instance, the outlet `10-30` is encoded as `0xD5 = 0b11010101`:
```
11 01 010 1
| | | |
| | | +--> no ground
| | +----> rating 2 (30A)
| +--------> voltage 1 (240V)
+-----------> previous ID + 3 (7 + 3 = 10)
```
The whole data is stored as a single string of two-nibble hexadecimal values, which are split with a `match()`.
### Decoding
The leading ID is updated with:
```
n += x >> 6
```
Because \$277\$ is \$960\bmod683\$, the voltage is decoded with:
```
V = (120 << x / 16 % 4) % 683
```
Because \$15\$ is \$80\bmod65\$, the current rating is decoded with:
```
R = -~(x / 2 & 7) * 10 % 65
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 115 bytes
```
≔¹⁰⁰εNθNηNζIEΦI⪪”)⧴→WuJSN4⊘Rf⎚θ⊕∧H,\`m↖⊗?Yς×≧üλθ▷TE⦄→×◧Àλ≧”⁴¬∨›ζ‹⁵﹪÷ιε⁸∨›η﹪ιε‹·¹↔⁻¹∕θ⎇⁼⁷÷ιε²⁷⁷×¹²⁰⎇⁼¹¹÷ιε²⊕﹪⊖÷ιε⁴↨ιε
```
[Try it online!](https://tio.run/##bZDdagIxEIXvfYrg1QTSMomb3YJXtrZFqLagLxA11EDMapIV6stvZ8W2og0MOd8k5@RntTFxVRvftqOU3GcAiSiY5cPeJOyaPGu2Sxthf8WbKz4Sf0QXMjyZlGFqdvDifKaVE8933mXoo5QaVVcKUQ0QNWlNWpMuSZeky05rxIq4Iq6IK40SB1Q0S0U1OEVJypGF1LIgLoiLEvuCFZwLNqszvEd4jdZ01zgK9mZTAi3YtF43voZJyGN3cGsLrnuvYA@88114Nr97Tzv4OQLvpWCjZap9ky1MXWgSUOccthdsYWMw8Que943xCSrBrs6iJFVRe@G2lrwKbzxS/mvqmqtotzZku4bz5cb2r3Xroc@4GII9mvSzyPmwbVWJPd2T7d3BfwM "Charcoal – Try It Online") Link is to verbose version of code. Takes the groundedness as an integer, `1` = grounded, `0` = ungrounded and outputs in array format `[[N, nn], ...]` (string format is possible at the cost of 1 byte). Explanation:
```
≔¹⁰⁰ε
```
Save the value `100` as it gets used a lot. (Charcoal only has predefined variables for `10` and `1000`.)
```
NθNηNζ
```
Input the voltage, current and groundedness.
```
IEΦI⪪”)⧴→WuJSN4⊘Rf⎚θ⊕∧H,\`m↖⊗?Yς×≧üλθ▷TE⦄→×◧Àλ≧”⁴¬
```
Split the compressed string of outlets in `NNnn` format into individual outlets in decimal, and filter out any that fail any of the following tests:
```
∨›ζ‹⁵﹪÷ιε⁸
```
The device needs to be grounded, but `NN` (modulo `8`) is less than `5`.
```
∨›η﹪ιε
```
The device requires more than `nn` current.
```
‹·¹↔⁻¹∕θ⎇⁼⁷÷ιε²⁷⁷×¹²⁰⎇⁼¹¹÷ιε²⊕﹪⊖÷ιε⁴
```
Dividing the device's voltage by the receptacle's voltage results in a value outside the range `0.9`..`1.1`. The receptacle's voltage is calculated as `NN` (modulo `4`, or `4` if `NN` is a multiple of `4`, or `2` if `NN` is `11`) multiplied by `120`, unless `NN` is `7`, in which case `277` is used instead.
```
↨ιε
```
Split the `NNnn` integer into separate `NN` and `nn` values by converting into base `100`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~155~~ 150 bytes
```
f=->v,a,g{z=0
"yQxwxwTxwuUuuwubvuw xwu".bytes{|i|z+=121-i
(v-q=(16<<z/140)*7.5%683)**2<=q*q/100&&g*4<=(t=z/10%14)%8&&a<=(c=z%10*5+15)&&(p [t+1,c])}}
```
[Try it online!](https://tio.run/##tVLLcoIwFF2XRb8hgwMjGDQ3kEA70n/oTLtyXKijjpuqFcTnt9NLhBLUzrSLZpHLOZxzH0k@0/E@z2ex97KlIzo/HmJmmPvXXfa4y952Wfqeplk63qbZA0Fkdsf7ZLo5nhanQycGDt7CaG@9ddwG2e8fehAwxw27wpKR77gu78drd90Dxmx77gb9uJ3EKGIWBI4V2fYImUl8sIC5ogPCse32igySDtDJ0Dmf81WabIg5GwBnFCSFIcHVEh5CIjyfmYb2zzAqOZeMCsqUmrS4B4ISrkwcTZRIxUjFyJIRuIeKDxUfKj5UPDAFMCgESoDBvwRFBsqLwb@gkpSqx6qh6xahbPHPDf2iWpG7Wc@vzqRVZReNqcQPuSpfnS2I8MxZlQ2Ksy3ENV1LgUW6VPUtyr1xjZqudgseUX5bqEFrQwZPFLsHfcibgTSN5kTq2hne9@vKOoHPAm3M@/dW2Bu6yk4@lmSZJgjIZLSZbp7rsyxfSCG@cFy9I/xm2hUgllcYoib@hiaW/c/8l5V/AQ "Ruby – Try It Online")
The magic string contains one character 14 and one tab (character 9).
A function taking 3 inputs: volts, amps, ground (where ground is 0 or 1.)
Prints a list of two-element arrays to stdout. These are ordered by rated voltage, so the ordering of the output may differ a little from the test cases in the question, but they are all there.
**Commented code**
```
f=->v,a,g{z=0 #Input voltage, current and grounding. Set z=0
"yQxwxwTxwuUuuwubvuw xwu". #Magic string, one byte per outlet spec.
bytes{|i|z+=121-i #Iterate through bytes and increment z.
(v-q=(16<<z/140)*7.5%683)**2<= #16*7.5=120V. rightshift by z/140 to get 240, 480 or 960%683=277V. Find the difference from input and square it.
q*q/100&& #If the difference is 1/10 of the outlet rating or less... (NB. q/10 must be squared to compare with the above)
g*4<=(t=z/10%14)%8&& #Extract the outlet type (minus 1.) Grounded outlets have t%8 greater or equal to 4. If grounding acceptable....
a<=(c=z%10*5+15)&& #Decode the current rating. If acceptable...
(p [t+1,c])} #Print the outlet spec: type and current rating.
}
```
I decided to order by voltage rating as there are only 4 possible values, hence only 3 steps in voltage, only 2 of which result in nonprintable characters in the magic string.
Realising that subtracting 1 from the outlet type and taking modulo 8 always gives a number of 4 or greater for grounded outlets and never for ungrounded ones was handy as I didn't have to compress this.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~310~~ 294 bytes
```
(x,y,z)=>[...'demu`hpaiqybjrzu}mu}oaqyY'].map((x,i)=>[[120,240,277,480][(s=x.charCodeAt())%4],h=[12,3,4,6,10][(s-s%8)/8-11]*5,(s-s%4)/4%2,[[...'11000300100010003010012000'].map(x=>+x).slice(0,i+2).reduce((a,b)=>a+b),h]]).filter(m=>9*m[0]/10<=x&&11*m[0]/10>=x&&y<=m[1]&&(z?!m[2]:1)).map(x=>x[3])
```
[[Try it online!](https://tio.run/##fZBNbsIwEIX3vUUXgA2DGTsGQoWpqp6isizVQGiCEgL5qQJSz04dCgukmoXjPH1vPG9ma79tuSqSfTXc5evovFFn0sARTlQtNGOst46y@jPe2@RwXG6LU/2T1T@5PRw/eoZldk@cO2m9mgsEId2ZTkGGaDQpVcNWsS3e3cNvFaG0Iw3EyjkhAAkT4BfXsOyEdBQOOTf9MVy0pCPZEaAvCThHxACxvf5@3dd1Q7xGaNRi0FBWpskqIgjJQFBWROvaKWJh6dLZwZJCbAxlmyStooJkajHrZxrNiONcNd0u5ze5aOVxrjLNTbdLTq/PmRbmhVN6a9bowNDzKt@VeRqxNP8iG9JOzydQFXVE6dM9ExOEMWxsWvqYtyzw1bkNu/V5IMfQD8ciBOGDQs5gjJ48DvhYgNLf8Zr138KWCe@Q@GDIySPIH63njp1/AQ "JavaScript (Node.js) – Try It Online")
Arnauld beat me to this, and did it better, but I put two hours of work into this...
The string compression is interesting.
Above, each character in
```
demu`hpaiqybjrzu}mu}oaqyY
```
is the binary data for:
```
d
To char code is 100
To binary is 1100100
1 - just on the start
100 - Represents current 15 - 100 => 15, 101 => 20, 110 => 30, 111 => 50, 011 => 60
1 - No ground (0 for ground)
00 - Voltage 120 - 00 => 120, 01 => 240, 10 => 277, 11 => 480.
```
And in this way each outlet is encoded into a single character.
## Explanation
```
(x,y,z)=> // declare function
[...'demu`hpaiqybjrzu}mu}oaqyY'] // see above on compression
.map((x,i)=> //map by item / index
[ //return array of:
[120,240,277,480] // possible voltages
[(s=x.charCodeAt())%4], //decipher from string & get correct value
h= //save following for use in name
[12,3,4,6,10] //possible current values,
[(s-s%8)/8-8]*5, //get correct one from decoded string item and multiply by 5
(s-s%4)/4%2, // get ground boolean
[[...'11000300100010003010012000'] // change in first part of string each time - sum of first m will be first part of name m
.map(x=>+x) // to array of numbers
.slice(0,i+2).reduce((a,b)=>a+b) //sum of first [index]
,h] // + '-' + h, the current value we saved earlier, produces name
])
//This is where all the magic happens, up to here is just data compression
.filter(m=> //filter m by if all are true:
9*m[0]/10<=x //9/10 of m[0] (voltage) is less than given voltage
&&11*m[0]/10>=x // 11/10 of m[0] (voltage) is greater than given voltage (so voltage is within 10%)
&&y<=m[1] // given current is less than or equal to m[1] (current)
&&(z? //if breaker required
!m[2] //check if breaker
:1) //else always true
).map(x=>x[3]) // convert to list of names
```
[Answer]
# Excel, 220 bytes
135 bytes for this formula.
```
=LET(f,B1:J1*B2:J6,r,A2:A6,v,XLOOKUP(f,L1:L4,M1:M4,240),TEXTJOIN(",",,IF((ABS(A8-v)<=v/10)*(B8<=r)*((MOD(f,10)>3)+1-C8)*f,f&"-"&r,"")))
```
68 bytes for this array of cells that shows the valid pairs of numbers before and after the dash.
```
1 2 5 6 7 10 11 12 14
15 1 1 1 1 1 0 0 0 0
20 0 1 1 1 1 0 1 1 1
30 0 1 1 1 1 1 1 0 1
50 0 0 0 1 1 1 1 0 1
60 0 0 0 0 0 0 0 0 1
```
17 byte for this array of cells that maps the numbers before the dash to voltages other than 240.
```
1 120
5 120
7 277
12 480
```
] |
[Question]
[
\$\newcommand{T}[1]{\text{Ta}(#1)} \newcommand{Ta}[3]{\text{Ta}\_{#2}^{#3}(#1)} \T n\$ is a function which returns the smallest positive integer which can be expressed as the sum of 2 positive integer cubes in \$n\$ different ways. For example, \$\T 1 = 2 = 1^3 + 1^3\$ and \$\T 2 = 1729 = 1^3 + 12^3 = 9^3 + 10^3\$ (the Hardy-Ramanujan number).
Let's generalise this by defining a related function: \$\Ta n x i\$ which returns the smallest positive integer which can be expressed as the sum of \$x\$ \$i\$th powers of positive integers in \$n\$ different ways. In this case, \$\T n = \Ta n 2 3\$ (note: this is the same function [here](https://en.wikipedia.org/wiki/Generalized_taxicab_number), \$\Ta n x i = \text{Taxicab}(i, x, n)\$)
Your task is to take 3 positive integers \$n, x\$ and \$i\$ and return \$\Ta n x i\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
In case \$x = 1 \$ and \$ n > 1\$, your program can do anything short of [summoning Cthulhu](https://codegolf.stackexchange.com/questions/128784/find-the-highest-unique-digit/214724#comment317467_128784), and for other cases where \$\Ta n x i\$ is not known to exist (e.g. \$\Ta n 2 5\$), the same applies.
## Test cases
```
n, x, i -> out
1, 1, 2 -> 1
1, 2, 3 -> 2
2, 2, 2 -> 50
2, 2, 3 -> 1729
3, 3, 2 -> 54
3, 3, 3 -> 5104
2, 6, 6 -> 570947
2, 4, 4 -> 259
6, 4, 4 -> 3847554
2, 5, 2 -> 20
2, 7, 3 -> 131
2, 5, 7 -> 1229250016
5, 8, 4 -> 4228
```
---
### Properties of \$\Ta n x i\$
* \$\forall i : \Ta 1 x i = x\$ as \$x = \underbrace{1^i + \cdots + 1^i}\_{x \text{ times}}\$
* \$\Ta n 1 i\$ does not exist for all \$n > 1\$
* \$\Ta n 2 5\$ is not known to exist for any \$n \ge 2\$
This is a table of results \$\{\Ta n x i \:|\: 1 \le n,x,i \le 3 \}\$, ignoring \$\Ta 2 1 i\$ and \$\Ta 3 1 i\$:
$$\begin{array}{ccc|c}
n & x & i & \Ta n x i \\
\hline
1 & 1 & 1 & 1 \\
1 & 1 & 2 & 1 \\
1 & 1 & 3 & 1 \\
1 & 2 & 1 & 2 \\
1 & 2 & 2 & 2 \\
1 & 2 & 3 & 2 \\
1 & 3 & 1 & 3 \\
1 & 3 & 2 & 3 \\
1 & 3 & 3 & 3 \\
2 & 2 & 1 & 4 \\
2 & 2 & 2 & 50 \\
2 & 2 & 3 & 1729 \\
2 & 3 & 1 & 5 \\
2 & 3 & 2 & 27 \\
2 & 3 & 3 & 251 \\
3 & 2 & 1 & 6 \\
3 & 2 & 2 & 325 \\
3 & 2 & 3 & 87539319 \\
3 & 3 & 1 & 6 \\
3 & 3 & 2 & 54 \\
3 & 3 & 3 & 5104 \\
\end{array}$$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
∞.ΔL¹m²ã€{ÙOy¢Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTfA7tzD206fDiR01rqg/P9K88tCjw/38jLiAEAA "05AB1E – Try It Online")
This is really slow, inserting `¹zmï` after `.Δ` limits the search space significantly: [Try it online!](https://tio.run/##AS4A0f9vc2FiaWX//@KIni7OlMK5em3Dr0zCuW3CssOj4oKse8OZT3nColH//zMKMgoy "05AB1E – Try It Online")
**Commented:**
```
# Inputs ¹=i, ²=x, ³=n
∞.Δ # find the first natural number k that satisfies:
L # each of the range [1..k]
¹m # raised to the i-th power
²ã # take the list to the x-th cartesian power
€{ # sort each x-tuple
Ù # deduplicate the tuples
O # sum each x-tuple
y¢ # count the number of k's
Q # is this equal to the last input?
```
`ã€{Ù` does the same as Python's [`itertools.combinations_with_replacement`](https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement), but there doesn't seem to be a builtin for this in *05AB1E*.
[Answer]
# [R](https://www.r-project.org/) + gtools, 84 bytes
```
function(n,x,i){while(sum(rowSums(gtools::combinations(+T,x,re=1)^i)==T)<n)T=T+1;+T}
```
[Try it online!](https://tio.run/##hZIxa8MwEIV3/4qDLBJ2oJLtmqR1904dqrmgGDUVWBJIMkkp/e2uXepYcmoCN33veHd6Ott7fpYNP9T9e6cbL41GOjtnEn@dPmQrkOsUsub02imHjt6Y1u33jVEHqfnY7FDKhnYraoLfJK5rhh81ZjVLyUPKvid3RDIYimLYwPYJSBJwmkH@x@mFD7Cc@@ldKNBZKGchH2wCoUiSDbTcHoUFL5yHhjvhwEsltqbzYDSw55exKXCu5lVITmKtGGpap9zFWvAEUtHd6OqMEqCMFSC4@wxWSJI4E/JfJmtZkWDQIkNylSGJoqI3Mye/CU4@@YLTFZ5fcRrtU9z@OhoNLhf88oAq/Otgwv3iBtZ4cBv9Dw "R – Try It Online")
Counts `T` up from 1, calculating the number of combinations of `x` numbers ≤`T` whose `i`th powers sum to `T`.
Stops at the first number that gives (at least) `n` combinations.
```
function(n,x,i){
# variable T (TRUE) initialized by default to 1
while( ... )T=T+1 # while the condition (see below) is met, keep incrementing T
#
a=gtools::combinations(+T,x,re=1) # all combinations of x numbers from 1..T (as rows of matrix)
b=a^i # raised to the i-th power
c=rowSums(b) # the row sums are the sums of each combination
d=sum(c==T) # when the row sums equal T, we have a combination of x i-th powers that equals T
d<n # the condition: we didn't get n combinations yet
#
+T # finally, the condition fails, so we've got n combinations: return this value of T
}
```
---
For a base-[R](https://www.r-project.org/) solution (without the gtools library), swap `gtools::combinations(+T,x,re=1)` for `unique(t(apply(expand.grid(rep(list(1:T),x)),1,sort)))` (+23 bytes).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 79 bytes
```
(n=1;While[Length@Select[PowersRepresentations[n++,#2,#3],#~FreeQ~0&]!=#];n-1)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPP1tA6PCMzJzXaJzUvvSTDITg1JzW5JDogvzy1qDgotaAotTg1rwSoIT@vODpPW1tH2UhH2ThWR7nOrSg1NbDOQC1W0VY51jpP11BT7X9AUWZeiYJDerSRjrmOcez//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œċ³*⁴§ċ⁼⁵µ1#
```
A full program which (given enough time!) prints the result if it exists. Inputs are \$x\$, \$i\$, \$n\$.
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//xZPEi8KzKuKBtMKnxIvigbzigbXCtTEj////M/8y/zM "Jelly – Try It Online")** (Too slow for most of the test cases.)
### How?
Brute-force (and an inefficient one at that):
```
œċ³*⁴§ċ⁼⁵µ1# - Main Link: x
µ1# - Count up starting with k=x until 1 truthy result, then yield k, using:
³ - 1st program argument, x
œċ - all combinations (of x elements from [1..k]), allowing repeats
⁴ - 2nd program argument, i
* - exponentiate (vectorises)
§ - sums
ċ - count occurrences (of k)
⁵ - 3rd program argument, n
⁼ - equal?
```
Note `œċ` does not give unordered repeats, for example `2œċ3` yields:
`[[1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 2, 2]]`
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), ~~110~~ 108 bytes
[Try it online!](https://tio.run/##XcvBCoJAGATge09hCKK4ga5JhGx4KRA6dDA6LBts9ps/2Ebu6tFXN0moCOb0zcxdmgru0mAhh5INLrIgOVVYA9@Dupkq3aG6ZkobqQrg6PuM5Q13O3ZU@GyBiz6Xlxp6m3pnOxKOswett89W1mnakY4cHhoNdpApAzdoNLHFnNkiQc8ZDg0qw0seEmsMFdZiY4Vi9sOUWNGb6Zfpm6d1HPz7NA9XdP1topE/j@W/T484DJZieAE "Wolfram Language (Mathematica) – Try It Online")
```
(i=0;While[Length@FindInstance[i++==Tr[(v=Unique[]~Table~#2)^#3]&&LessEqual@@v,v,PositiveIntegers,#]!=#];i)&
```
[Answer]
# JavaScript (ES7), 89 bytes
```
(n,x,i)=>(F=q=>(g=(k,p,j)=>j?p**i>k?0:g(k-p**i,p,j-1)+g(k,p+1,j):!k)(++q,1,x)-n?F(q):q)``
```
[Try it online!](https://tio.run/##bY/dCoMgGIbPdxXuTNNWWtEPVGddR9FKytBaY3T3zbYoqOBD0Od7Xl7b4lOM5avp36ZUz2qu4xlKMpEGxQnM4kGfPIaC9KTVL23aG0aTiNSOOBTmclmISRHmyxKmei26CwQxHgglEzJlmsEBRQPK87lUclRd9egUhzWkBOhhCAHLAvR2gowA5w/ZAbIfXE3PvqSrSn0WHrij4W67l3S1PWq753RXz1rMC8/Y28LZRTV/r@YcP63NYMt2GQvmLw "JavaScript (Node.js) – Try It Online")
### Commented
We recursively look for the smallest \$q\$ such that there exists exactly \$n\$ sums of the form:
$${p\_1}^i+{p\_2}^i+\ldots+{p\_x}^i=q,\:p\_{k+1}\ge p\_k \ge 1$$
```
(n, x, i) => ( // input variables, as described in the challenge
F = q => // F is a recursive function taking a candidate solution q
( g = ( // g is a recursive function taking:
k, // k = current sum
p, // p = number to be raised to the power of i
j // j = remaining number of terms in the sum
) => //
j ? // if there's at least one more term to compute:
p ** i > k ? // if p ** i is greater than k:
0 // abort
: // else:
g( // do a 1st recursive call with:
k - p ** i, // k = k - p ** i
p, // p unchanged
j - 1 // one less term to compute
) + //
g( // do a 2nd recursive call with:
k, // k unchanged
p + 1, // p incremented
j // j unchanged
) //
: // else:
!k // increment the final result if k = 0
)(++q, 1, x) // initial call to g with k = ++q, p = 1 and j = x
- n ? // if the result is not equal to n:
F(q) // try again
: // else:
q // success: return q
)`` // initial call to F with q zero'ish
```
[Answer]
# [Scala](http://www.scala-lang.org/), 125 bytes
```
(n,x,i)=>1 to 1<<30 find(c=>Seq.fill(x)(1 to c map(Math.pow(_,i))takeWhile(_<=c)).flatten.combinations(x).count(_.sum==c)==n)
```
[Try it online!](https://tio.run/##XVLBTsMwDL3vKyzEIZGq0qbruqFlEuLEAXEAiQNCU5amLNClZfFgEuLbh5tSYEiWKz@/Zzt2vVa1OjSrZ6MR7tTearUCs0fjSg8XbQsfI4A3VQP2uXNgVw4jGBwHuYCbFm3jHih8BHlgLtpHlstFCthAOp9nCVTWlUzLxa15jStb12zPWUhr2KiWXStcx23zzpYk5KhezP3a1oYt51JzHle1Qpoo1s1mZZ3qmnmqQPHOIVvGfreRRJTS8cP3tMbjpfLGgwTqyegRACyNgEyQ59EPQmFGfkBEQMjy5BgiUlqI2QBmvYx442OILE@TATw76@STYHmRzMbFn6rjYCKf/ZInA5pNx0X@W7tr1E/2d6yiHytLj7rlIZEKMRN5kqSTQUD4tC8vxJQTxkfkflYVV83WKL1m2N30I2i6XSqNO/rI4RdgGC9pb@RF8BkPVOW92SIb2LT3ZmM6Lr0B/EnXBjT1gVOEStF1ywie7Bud6LTXnPR12q11WDv2T@J3WhtTmjLQPvno8/AF "Scala – Try It Online")
**Approach**: for each candidate integer `c`, generate a list of `x` copies of `i`-powered integers lower than `c`, and count whether `n` (distinct!) combinations of length `x` sum up to `c`.
**Performance**: the trade-off between performance and code length is made such that most test cases finish within some seconds. The following variant would save 14 bytes, but would be much less performant:
```
(n,x,i)=>0 to 1<<30 find(c=>Seq.fill(x)(1 to c).flatten.combinations(x).count(_.map(Math.pow(_, i)).sum==c)==n)
```
] |
[Question]
[
Write the shortest possible program to remove all partial matched duplicates from a list and only retain the longest lines. Sort order does not matter.
For following inputs, the intent is to search for the string `reminder` followed by a number and retain the longest unique `reminder + number` lines.
# Some rules
* `reminder` is a hard-coded word, case-sensitive.
* All lines contain exactly one match.
* There is always a space between `reminder` and the number.
* Only positive, whole numbers are used in the matches (not necessarily a contiguous set).
* Lines with same length for the same reminder are possible. It does not matter what line is chosen.
* Sort order of output does not matter.
# Inputs
```
A short reminder 1
This is the longest reminder 1 available
This is the longest reminder 2 available, different length
A short reminder 2
A short reminder 3
This is the longest reminder 3 available, another different length
Another short reminder 3
A reminder -1 but really a short reminder 42
This is the longest reminder but really a short reminder 42.
```
# Expected output
```
This is the longest reminder 1 available
This is the longest reminder 2 available, different length
This is the longest reminder 3 available, another different length
This is the longest reminder but really a short reminder 42.
```
Shortest code wins
---
Background: [this](https://stackoverflow.com/q/63405349/52598) stackoverflow question
[Answer]
# JavaScript (ES6), ~~85 82~~ 79 bytes
```
a=>a.sort((a,b)=>-!b[a.length]).filter(s=>a[k=/reminder \d+/.exec(s)]^(a[k]=1))
```
[Try it online!](https://tio.run/##jZHBbsIwEETvfMU2J1tNjBJ6NRL/wC0N0iZZJ6aujWy3Kl8fjEAFtaWKtKfZNztjeY@fGDqvD7GwrqdJyQnlGkVwPjKGecvlunhqaxSG7BDHhgulTSTPQsLqN7n09K5tTx5e@@eloC/qWODNjqVlI0vOp87Z4AwJ4wamWL0AyDYQxhQA394yy8/6dtQB0sSRwDg7ULhnIHXVBltDM@jqRufQa6XIk41wecXF/6tF9UBfzchb3eehdQnyj3Kv279TNjelKKH9OBNozBHwp@GlmtHr/wMiWzTpi04 "JavaScript (Node.js) – Try It Online")
### How?
We first sort all strings from longest to shortest.
```
a.sort((a, b) =>
-!b[a.length] // 0 if 'b' is longer than 'a', -1 otherwise
)
```
We then filter the strings, keeping only the first occurrence of each `reminder N` key. The underlying object of the input array `a[]` is re-used to keep track of the keys that were already encountered.
```
.filter(s =>
a[k = /reminder \d+/.exec(s)]
^
(a[k] = 1)
)
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~134~~ 132 bytes
```
import re
def f(l,d={}):
for s in l:
if len(d.get(n:=re.sub('.*reminder (\\d+).*','\\1',s))or'')<len(s):d[n]=s
return d.values()
```
[Try it online!](https://tio.run/##jVJPb4MgFL/7KV56ATpHou7QmHnod9ht7oDhoSQUDWCTZtlnd7i6tdniIjf4/SXvDZfQ9bY4DG6a9GnoXQCHiUQFippUVu8frExA9Q48aAsmXkArMGip5C0GasvKIfdjQwnfOzxpK9EBrWv5wPiepKSuM5J6xnpHCHuehZ6V8tW@VT6JWWF0FiQ/CzOip2wK6IOHCmgMAtgdwXfXUotztkuvyEunYyUPoUMwvW2j7o4F4iy0EY3BTfz8xk9BaqXQoQ3zN9vQfTv86ZKvIsWm1OI@Vdg@ktx6@oKvJR1vb48ZNOPMEcZcQPyWPOWb2v1vwRcPlvwsh6Jfw5sXJp7BaRvirKdP "Python 3.8 (pre-release) – Try It Online")
Tried recursive lambda approach but it's longer:
# [Python 3.8](https://docs.python.org/3.8/), 148 bytes
```
f=lambda l,d={}:l and(len(d.get(n:=re.sub('.*reminder (\\d+).*','\\1',s:=l.pop()))or'')<len(s)and d.update([(n,s)])or f(l,d))or d.values()
import re
```
[Try it online!](https://tio.run/##jZJBasMwEEX3PsWQjaXUFcTpIph6kTt0F2cho3EskGUhyYFQenZ3nKQktLhYaKX/5v8ZRu4S295ud86PY1Ma2dVKgslU@flVGJBWMYOWKXHCyGxRehRhqFkq1h47bRV6YFWlXrhYp1laVZs0C0VphOsd45z3Pk35@@QQOHmBEoNTMiI7MJsFfiQAGkZxE0rqWZoBA@OJ7lzvI3gcI4YYoIRDAnRWewjtTbnHb1bZTflodQC6sUUwvT1R3RMF8iy1kbXBRXz@4DNQumnQo41Ak5xi@@Pwp5d8VtkuSt0@p0rbE@Tn0@/6XNL@8fa6gXqYGGnMBeTvkrd8UXf/W4i7xzFpaJXkYmmz1@Xx4io4r22kfzB@Aw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of strings. Output is sorted by the matched number, in lexicographical order.
```
ü_f`ã„ %d+` gîñÊÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVI&code=/F9mYOOEGAAgJWQrYCBnw67xysw&input=IkEgc2hvcnQgcmVtaW5kZXIgMQpUaGlzIGlzIHRoZSBsb25nZXN0IHJlbWluZGVyIDEgYXZhaWxhYmxlClRoaXMgaXMgdGhlIGxvbmdlc3QgcmVtaW5kZXIgMiBhdmFpbGFibGUsIGRpZmZlcmVudCBsZW5ndGgKQSBzaG9ydCByZW1pbmRlciAyCkEgc2hvcnQgcmVtaW5kZXIgMwpUaGlzIGlzIHRoZSBsb25nZXN0IHJlbWluZGVyIDMgYXZhaWxhYmxlLCBhbm90aGVyIGRpZmZlcmVudCBsZW5ndGgKQW5vdGhlciBzaG9ydCByZW1pbmRlciAzCkEgcmVtaW5kZXIgLTEgYnV0IHJlYWxseSBhIHNob3J0IHJlbWluZGVyIDQyClRoaXMgaXMgdGhlIGxvbmdlc3QgcmVtaW5kZXIgYnV0IHJlYWxseSBhIHNob3J0IHJlbWluZGVyIDQyLiIKLVI) (Header splits input string on newlines)
```
ü_f`... %d+` gîñÊÌ :Implicit input of array
ü :Group and sort by
_ :Passing each through the following function
f : Match
`... %d+` : Compressed string "reminder %d+", which translates to the RegEx /reminder \d+/g
g : Get first match ('Cause matching returns an array)
à :End grouping
® :Map
ñ : Sort by
Ê : Length
Ì : Get last element
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes
```
O#$`
$.&
O#$`.*reminder (\d+).*
$1
.*(reminder \d+)(.*¶(.*\1\b))+
$3
```
[Try it online!](https://tio.run/##fY5NCoMwEIX3OcVAQ9HYBvy5gCfopksXjXU0gTRCTAu9WA/Qi6URikotwhAm730zbyw6ZYT3px29EMr3ZGw4s3hTpkELUdUkMWeEpoSzaJJHNeLs/QpPlVZ1HCeE5t6XMMjeOpjAlJylGiCUkwi6Nx0OSxvEQygtao3bYDaDB2hU26JF40Cj6Zwkq9gsSG5ccBUDznJerNF8OzhfBgvTB8j@OeBrrHaX8@eYQn0fTaH1E8QvW2Tbh2zP8g8 "Retina 0.8.2 – Try It Online") Explanation:
```
O#$`
$.&
```
Sort (in ascending order) numerically by length.
```
O#$`.*reminder (\d+).*
$1
```
Sort numerically by matched number, keeping lines with the same number sorted in length order.
```
.*(reminder \d+)(.*¶(.*\1\b))+
$3
```
Keep only the last line of consecutive lines with the same matched number.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 48 bytes
```
*.sort(-*.comb).unique(:as({~m/reminder\s\d+/}))
```
[Try it online!](https://tio.run/##fY7BCoJAEIbvPsWcwrVcUaNDkeA7dPSy5qgLu2vtroFEvboZFEqGMJeZ/5v55oJa7HrZwaqEY@9R02jr@h49NzIntFX82qK7Z8a9P2WgUXJVoM5MVqyDByH9wSldwRUakiTUsK5PwdTDCfiiEDqnmhsYytYIolEVmmkM7Ma4YLnAZTAawQ0UvCxRo7IgUFW2dmbaaD6KlwXxVMBUM0D6j@gTzG6nY@OHkLfvkAnRAftlt9HyI8u79AU)
Sorts by longest first, then gets the unique elements by the reminder number.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 39 bytes
```
ÎÄÒ0J
ú!
ò/reminder ä
y2e0dw+VGç0¾/d
```
[Try it online!](https://tio.run/##K/v//3Df4ZbDkwy8uA7vUuQ6vEm/KDU3My8ltUjh8BKuSqNUg5Ry7TD3w8uFDA7t00/h4v//31GhOCO/qEQBrtCQKyQjs1gBiEoyUhVy8vPSU4uRpRUSyxIzcxKTclLxKzRCKNRRSMlMS0stSs0rUchJzUsvyeDCsNYIU8gYvwXGyBYk5uUDFRVhsQgqgWG2I4Kja6iQVAqSTMzJqVRIRFdrYoTfIfj16gEA "V (vim) – Try It Online")
```
Î # on every line (:%norm)
Ä # (M-D)uplicate the line
Ò0 # (M-R)eplace all characters with '0'
J # (J)oin with the original line
# This turns each line into "0000000000 reminder 1"
ú! # Reverse (M-z)ort (cursor ends up on first line)
ò # (M-r)ecursively (until error)
/reminder ä # goto /reminder \d/ (longest reminder X, here we find X)
y2e # (y)ank (e)nd of (2) words: reminder \d+>
0dw # goto beginning and (d)elete (w)ord (the 0s)
+ # goto start of next line
VG # highlight until end
ç^R0¾/d # in this highlighted region delete lines matching:
# (^R)egister 0 - contains the reminder (y)anked earlier
^O # Jump back to prev cursor position and repeat until error
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
é.¡#I¡εнžm(Ã}þ}€θ
```
05AB1E doesn't have any regex, so figuring out the best approach with test case containing negative numbers or multiples spaces between the string and the number (i.e. `reminder 42`) was a bit tricky, but still pretty happy with how short it turned out.
First input is a list of string lines, and the second input is the hard-coded string to match.
[Try it online.](https://tio.run/##yy9OTMpM/f//8Eq9QwuVPQ8tPLf1wt6j@3I1DjfXHt5X@6hpzbkd//9HKzkqFGfkF5UoFKXmZualpBYpGCrpKIVkZBYrAFFJRqpCTn5eemoxsgKFxLLEzJzEpJxUQkqNEEp1FFIy09JSi1LzShRyUvPSSzKAmjEsN8ImaEzIGmNkaxLz8oGKirBaB5XCYr4jgqtrqJBUCpJOzMmpVEhEV21iRMg5@HXrgbSjqNc1NDJGdU0QPKwNDBAyQGBihKRQTymWC8YDAA)
**Explanation:**
```
é # Sort the (implicit) input-list of lines by length (shortest to longest)
.¡ # Group the lines by:
# # Split the string on spaces
I¡ # Split that list on the second input-word
ε # Map each inner list of strings to:
н # Only leave the first part of the list
žm # Push builtin 9876543210
( # Negate it to -9876543210
à # Only keep those characters from the string
}þ # After the map, only leave strings consisting of just digits;
# so this will remove empty strings and negative numbers from the list
}€ # After the group by: map over each group:
θ # And only leave the last (thus longest) line
# (after which the resulting list of lines is output implicitly)
```
[See this for a step-by-step on how the input is transformed into the output.](https://tio.run/##hZKxTuNAEIZ7nmJkmiA5gThUSAiloEiFBNehK9bJ2h5ps2vtrolS0Nw9SUokSjjdFaSwRWvxDLxImLUNJodFLFuyPd///zNjK8NC5JuNN5FokQlAmWa2L9DYE/D80/zP2Z53pbTlMwiXYBOOGgSXsU0M9EziKsaCVSCUjOn2wMmKu1p4zqYJCJQcTCrQOgeTsik3Dnr9db@/hZFPjSnpgppWFkrPHD4pH/JVzV9IsaQm2A2vuAg1SVOmSRkBd2YoJdfwPgUl0fny1KmW2Tzk2nxInY8TlY/P63mvfCh@33bqHGdgqqShFJSxM1AOmWGMVOnZBA3QuUi45rDgEGuVpcQcND0Va78yHkeWmnWeNREu/dqpDRPM2MNmw9uT1pLeIkE3No2Rabosba6Kyf8Vd4N8tT/JV@Xjy5MbiQYq1reUX/71N5trbwzVZwTN5yhn1MnQ870fTfNVeJPbAsBuGAoWCr4LDVrUp81EEe1C2uYPIvGX8KDr5WhXzOhzDJOKIN0Z15Q6/MftY38IYebKTNBXYP/Tx8Gudr5XD5x8i@8Pg9F2N5cfuz46ait0HAefwIH3c@/96Q0)
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 59 bytes
Uses the same approach as @Arbauld's answer, sorts the input by length then discards any sentences that contain a previously seen match.
```
say grep/reminder \d+/&&!${$&}++,sort{$b=~y///c-length$a}<>
```
[Try it online!](https://tio.run/##fY7BDoIwDIbvPEVNCBeECchNTXgAbx69DCmwZG5kmyaE6KM7MRohYkh6ab@//dqg4qm1mrZQKWyIwjMTBSo4Fj7xvIXbud7N95daKtO5@fbeEkJOAUdRmdqlt83O2gx03WP47kbOoWYa@jI1ApeiQj3GQK@UcZpznA/GQ3AJBStLVCgMvOXORBtPR8m8IBkLqJB9SP0RfcDkdjY0QQT55QUp5y3Q3@w6nn9kfjd0HrIxTAptg30aRqtw9QQ "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
No (direct) regex support in Jelly (it's only indirectly available by executing Python code).
```
ðœṣ“ǧƥ»;⁶¤Ḋe€ÞṪf)ØDĠị⁸LÞṪ$€
```
A monadic Link accepting a list of lists of characters which yields a list of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8///whqOTH@5c/KhhzuH2Q8uPLT202/pR47ZDSx7u6Ep91LTm8LyHO1elaR6e4XJkwcPd3Y8ad/iAhVSAcv8f7t5yuD3y/39HheKM/KIShaLU3My8lNQiBUOukIzMYgUgKslIVcjJz0tPLUaWVkgsS8zMSUzKScWv0AihUEchJTMtLbUoNa9EISc1L70kgwvDWiNMIWP8FhgjW5CYlw9UVITFIqgEhtmOCI6uoUJSKUgyERisConoak2M8DsEv149AA "Jelly – Try It Online")** (footer just splits at newlines, calls the Link and joins back by newlines.)
### How?
```
ðœṣ“ǧƥ»;⁶¤Ḋe€ÞṪf)ØDĠị⁸LÞṪ$€ - Link: list of lists of characters, X
ØD - digit characters
ð ) - dyadic chain for each (line in X) - i.e. f(line, digit characters)
œṣ - split at substrings equal to:
¤ - nilad followed by link(s) as a nilad:
“ǧƥ» - compressed string "reminder"
⁶ - space character
; - concatenate -> "reminder "
Ḋ - dequeue (leaving only strings to the right of a "match ")
Þ - sort (these "parts") by
€ - for each (character, c, in part):
e - (c) exists in (digit characters)?
Ṫ - tail - giving us the single part starting with positive digit
characters - N.B. a '0...' is always less, if present
f - filter-keep (digit characters) - thus "42..." becomes "42"
Ġ - group indices by value
ị - index into:
⁸ - X - giving us a list of lists of lines with equal "number"
€ - for each:
$ - last two links as a monad:
Þ - sort by:
L - length
Ṫ - tail
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->a{a.sort_by{|s|-s.size}.uniq{|s|s[/reminder \d+/]}}
```
[Try it online!](https://tio.run/##hY5BC4JAEIXv/orBa6loXQ38D13CJEYcc2Fba2cNzPztphAZJQpzmfe@x3u6SusuDztnhw26XGpzSuvmyU@HXRYPat1KidsgcOxpugiVkYZjtvKStu0wjO0IuOhj8DF9e23Z@0Iw9GcKAlmqM/E3AXhHITGVtMgGI7uGTOQ5aVIGJKmzKYb0X38wqW4G9fDzzzZvvptRlT2kpxe8vanGaPwdH9Jq8FHKGvAX3waLi@bjrp1Y1rUyDHmMSfcC "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
lambda a:{max((j for j in a if'reminder '+i in j),key=len)for i in' '.join(a).split()if i.isdigit()}
```
[Try it online!](https://tio.run/##jVFBasMwELznFUsulqhriN1TwIf8ocde1liy1pUlI6mlJuTtjpSkTWhxsdiLZmZnFmacgrKmmmX9NmscmhYB98cBvxjrQVoHPZABBJKZEwOZVjjIniiBPc/fxVRrYXgSJiyDrOgtGYa88KOmwDhJoIJ8S136neYgfPBQA9tAfNsDeGVdgB/z3Ta/Mq@KPMQJSoC2pot7DyrATySNjRar9OVdn0NLUgonTIB4exfUt8OfW8pFplqVWj2morFR5JbTb/xS0uGOPe@g@Uga1HqK5fxaeSlXXfe/RXHz4JtUrk@FS3Ypj@8vxOjIBOb5fAY "Python 3 – Try It Online")
Test cases borrowed from Noodle9.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/188948/edit).
Closed 4 years ago.
[Improve this question](/posts/188948/edit)
There is a rectangular 2D array containing viruses denoted by 'v', antidote1 denoted by 'a', and antidote2 denoted by 'b' (there are no values other than 'v', 'a' and 'b').
Antidote1 can kill neighboring viruses in horizontal and vertical directions only, but antidote2 can kill neighboring(if any) viruses in horizontal, vertical and diagonal directions.
Once the antidotes are activated, how many viruses will remain at the end?
### Examples:
Input:
```
vv
vv
```
Output: 4
Input:
```
av
vv
```
Output: 1
Input:
```
vvv
vbv
vvv
```
Output: 0
Input:
```
bvb
bav
vab
vvv
vvb
vvv
vvv
bva
vav
```
Output: 3
[Answer]
# [Python 3](https://docs.python.org/3/), 126 bytes
```
j=''.join
g=lambda*s:eval('j(s)'+4*'.replace("%s%s","%s%s")'%(*'vbbbbvbbavacvaca',))
f=lambda x:j(map(g,*map(g,x))).count('v')
```
[Try it online!](https://tio.run/##hU/LDoIwELz3KxoM2W4lRCMnE77EeNgiooRXBBv9eiyisdSg06bbbWcms829O9XVpu/zGCDM63PFsrigUh1ItttUUyEgFy3CMpIQXtKmoCQVnt/6rReMBcEXErQyMAdpSswmCBDZ8WXFb9tclNSILJBjuSFimNTXqhOgAfvmcjbXo9h5WnsB428M7R6R8wWP2IdEc6Q1s50clnJVo2zBV79UNKeyA5nRJyzlqkh9uUz7f//TXmn6Sjmm2tiplB7gzk30fCbHcViWT/8A "Python 3 – Try It Online")
-2 bytes thanks to Kevin Cruijssen
# Explanation
Replaces all 'v' to 'b' if found next to 'b'. Next, replaces all 'v' to 'c' if found next to 'a'. A second iteration with the transposed version of the array clears all vertical and diagonal viruses. Finally, it will return the remaining number of 'v's.
---
Without eval:
# [Python 3](https://docs.python.org/3/), 133 bytes
```
j=''.join
g=lambda*s,r=str.replace:r(r(r(r(j(s),'vb','bb'),'bv','bb'),'av','ac'),'va','ca')
f=lambda x:j(map(g,*map(g,x))).count('v')
```
[Try it online!](https://tio.run/##hU/LDoIwELz3Kxo9bEsaotGTCV9iPOzik/BKwY1@PVLxASXo7qEz7cxkWt7rc5GvmiaJAMKkuOTiFKWY0R6Dytioqm1oD2WK8WFjVbeJqrQBJjBABC0k/kB0EGMHGVsYI2hxfCXK2yZRGZbqZILuuGmtw7i45rUCBt2U9tLCo9rOmGdGyPc4utNayrlci68Ip0RL0U/yVOS7OttcLn65cMrVL0RMAxX5LqRRypD/ex9yYhy17Fqt@q2I3fj/Rnxeo5fotpfTPAA "Python 3 – Try It Online")
[Answer]
# JavaScript (ES7), 108 bytes
Takes input as a matrix of characters.
```
f=m=>(g=(y,X,V)=>m.map(r=>r.map((v,x)=>V?v>f&V>'a'>(x-X)**2+y*y-2?r[x]=n--:0:v<f?g(-y,x,v):n++)|y++))(n=0)|n
```
[Try it online!](https://tio.run/##rY7NDoIwEITvPAUn2UJbUTkRW96CmBAOrQLRQCFgGpr47viTGMGo4eBls7M782VOQotu3x6bM1H1IRuGnFWMQ8HA4B2OEeMVrUQDLePtYwGN@9s1jjTPFzF3hMOhJzvkumvPuIasozbpU6YICf1Qb/OoAGJwjzUKleehi7kNBIr56KKGfa26usxoWReQQ2Ivl3Zg2XZCKXW0dlI8FlaKkPUhsXqaxNyE/zJNInIK@EEIvhDEbMLm6ZJ/IMhRRk4JQr7zRurXb6ykFu8d762GKw "JavaScript (Node.js) – Try It Online")
*Similar to my original answer, but doing `V>'a'>(x-X)**2+y*y-2` is actually 1 byte shorter than using the hexa trick described below. ¯\\_(ツ)\_/¯*
---
# JavaScript (ES7), 109 bytes
Takes input as a matrix of characters.
```
f=m=>(g=(y,X,V)=>m.map(r=>r.map((v,x)=>V?v>f&(x-X)**2+y*y<V-8?r[x]=n--:0:v<f?g(-y,x,'0x'+v):n++)|y++))(n=0)|n
```
[Try it online!](https://tio.run/##rY7NDoIwEITvPAUn2UJb8edgiIW3ICSEQ6tANFIMmKZNeHdEEyMYNR68bHZ2Z77MkSve7prD@UJkvc/7vmAVC6FkYHCCY8TCilb8DA0Lm/sCCuvhGkcqLGagSYJcd@kZ12xjsomaVGdMEhL4gdoWUQnEYI0dXzueQoH0PNSZYSCQzEed7He1bOtTTk91CQWk9nxury3bTimljlJOhsfCyhCy3iQWDxP/NeE/TZOImAK@ENYfCPxnwurhEn8giFFGTAlcvPJG6ttvrITirx1vrfor "JavaScript (Node.js) – Try It Online")
### How?
The [quadrance](https://en.wikipedia.org/wiki/Rational_trigonometry#Quadrance) of two points \$A\_1=(x\_1,y\_1)\$ and \$A\_2=(x\_2,y\_2)\$ is defined as:
$$Q(A\_1,A\_2)=(x\_2−x\_1)^2+(y\_2−y\_1)^2$$
Considering integer coordinates, it looks as follows:
$$\begin{matrix}
&8&5&4&5&8\\
&5&2&1&2&5\\
&4&1&\bullet&1&4\\
&5&2&1&2&5\\
&8&5&4&5&8
\end{matrix}$$
Therefore:
* a type A antidote located at \$A\_1\$ is able to kill a virus located at \$A\_2\$ if \$Q(A\_1,A\_2)<2\$
* a type B antidote located at \$A\_1\$ is able to kill a virus located at \$A\_2\$ if \$Q(A\_1,A\_2)<3\$
Conveniently, this exclusive upper bound (\$2\$ or \$3\$) can be obtained by converting the antidote character from hexadecimal to decimal and subtracting \$8\$:
* \$\text{A}\_{16} - 8\_{10} = 2\_{10}\$
* \$\text{B}\_{16} - 8\_{10} = 3\_{10}\$
### Commented
```
f = // named function, because we use it to test if a character
// is below or above 'm'
m => ( // m[] = input matrix
g = ( // g is a recursive function taking:
y, // y = offset between the reference row and the current row
X, // X = reference column
V // V = reference value, prefixed with '0x'
) => //
m.map(r => // for each row r[] in m[]:
r.map((v, x) => // for each value v at position x in r[]:
V ? // if V is defined:
v > f & // if v is equal to 'v'
(x - X) ** 2 + // and the quadrance between the reference point and
y * y // the current point
< V - 8 ? // is less than the reference value read as hexa minus 8:
r[x] = n-- // decrement n and invalidate the current cell
: // else:
0 // do nothing
: // else:
v < f ? // if v is either 'a' or 'b':
g( // do a recursive call:
-y, // pass the opposite of y
x, // pass x unchanged
'0x' + v // pass v prefixed with '0x'
) // end of recursive call
: // else:
n++ // increment n
) | y++ // end of inner map(); increment y
) // end of outer map()
)(n = 0) // initial call to g with y = n = 0
| n // return n
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~33~~ ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2F.•s¯}˜?•2ô€Â2ä`.:S¶¡øJ»}'v¢
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyE3vUcOi4kPra0/PsQeyjA5vedS05nCT0eElCXpWwYe2HVp4eIfXod216mWHFv3/r6SkVFZWxlWWBMQgOhFMA0UB) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLh2Vf@N3LTe9SwqPjQ@trTc@yBLKPDWx41rTncZHR4SYKeVfChbYcWHt7hdWh3rXrZoUX/dQ5ts/8frVRWFpNXVqako6CUCGeVgQWTwHxMASCRiJBKKkuKyUsCCyQmweTLECwgkVSWCFaZVAYCYFMSE8HsRJAkCAJNVIoFAA).
Port of [*@Jitse*'s Python 3 answer](https://codegolf.stackexchange.com/a/188952/52210), so make sure to upvote him!
-1 byte thanks to *@Jitse*.
**Explanation:**
The legacy version has the advantage of being able to zip/transpose a string-list, where the new version would need an explicit `S` and `J`, since it only works with character-lists. But, the new version is still 3 bytes shorter by using `€Â` in combination with a shorter compressed string. In the legacy version, `€` would only keep the last value on the stack inside the map, but in the new version, it will keep all values on the stack inside the map.
```
2F # Loop 2 times:
.•s¯}˜?• # Push compressed string "vbvabbca"
2ô # Split it into parts of size 2: ["vb","va","bb","ca"]
€Â # Bifurcate (short for duplicate & reverse copy) each:
# ["vb","bv","va","av","bb","bb","ca","ac"]
2ä # Split it into two parts:
# [["vb","bv","va","av"],["bb","bb","ca","ac"]]
` # Push both those lists separated to the stack
.: # Replace all strings once one by one in the (implicit) input-string
S # Then split the entire modified input to a list of characters
¶¡ # Split that list by newlines into sublists of characters
ø # Zip/transpose; swapping rows/columns
J # Join each inner character-list back together to a string again
» # And join it back together by newlines
}'v¢ '# After the loop: count how many "v" remain
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•s¯}˜?•` is `"vbvabbca"`.
[Answer]
# Java 10, ~~211~~ ~~209~~ ~~204~~ 202 bytes
```
m->{int i=m.length,j,c=0,f,t,I,J;for(;i-->0;)for(j=m[i].length;j-->0;c+=m[i][j]>98?f/9:0)for(f=t=9;t-->0;)try{f-=m[I=i+t/3-1][J=j+t%3-1]==98||m[I][J]<98&(I-=i-J+j)*I==1?1:0;}finally{continue;}return c;}
```
Modification of my answer for the [*All the single eights* challenge](https://codegolf.stackexchange.com/a/175766/52210).
-9 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##rVNNT4QwEL37K5pNNEU@3I2XZWvXGE9soh48Eg6lgrZC2ZQBs1n57WspmOzBJcZ4IeW9mXkzLzOStcyXL@8HXrC6Rg9MqP0ZQkJBpnPGM/TY/1oAcczfmI6TOEGlQwzcnZlPDQwER49IIYoOpb/e97GClkGRqVd486TH6dzLPfAib0PySmMifH89J07/lrSMRTLGEmkJ7lowlsk6XN7mV@FqbmNzCjQkMCSD3u1z3wRGVLhwde0vknhDpQvn/ZPScPn5aUgDJjfh8gJHPhX@xpXOZUTp4naxmpMuF4oVxW7PKwVCNRnpdAaNVoiT7kD66bZNWpjpxiHbSryg0niEn0EL9WqcYM5gEGQ1YJV9oG@PBhihWdvOAqjuDXynNdthxzvJWKKz3k5VZP9esZ1oMp1Q@6Nc2qanaqYTw7H0950cUX/LOkmlLTvd4YQhx9diF8n6c3RSgz3PuxqyMqgaCLZmx6BQeBapbQMrNBuN7W9hyGOr0hnFf8iT5riDBkQR2G5q09qwt5g5Y6mf1J4aGORcFXBcToSOc3WHLw)
**Explanation:**
```
m->{ // Method with char-matrix parameter & int return-type
int i=m.length, // Amount of rows
j, // Amount of columns
c=0, // Virus-counter, starting at 0
f, // Flag-integer
t,I,J; // Temp-integers
for(;i-->0;) // Loop over the rows of the matrix
for(j=m[i].length;j-->0 // Inner loop over the columns
;c+= // After every iteration: increase the counter by:
m[i][j]>98 // If the current cell contains a 'v'
f/9 // And the flag is 9:
// Increase the counter by 1
:0) // Else: leave the counter unchanged by adding 0
for(f=t=9; // Reset the flag to 9
t-->0;) // Loop `t` in the range (9, 0]:
try{f-= // Decrease the flag by:
m[I=i+t/3-1] // If `t` is 0, 1, or 2: Look at the previous row
// Else-if `t` is 6, 7, or 8: Look at the next row
// Else (`t` is 3, 4, or 5): Look at the current row
[J=j+t%3-1] // If `t` is 0, 3, or 6: Look at the previous column
// Else-if `t` is 2, 5, or 8: Look at the next column
// Else (`t` is 1, 4, or 7): Look at the current column
==98 // And if this cell contains a 'b'
||m[I][J]<98 // Or if there is an 'a'
&(I-=i-J+j)*I==1?// in a vertical/horizontal adjacent cell:
1 // Decrease the flag by 1
:0; // Else: leave the flag unchanged by decreasing with 0
}finally{continue;} // Catch and ignore any ArrayIndexOutOfBoundsExceptions,
// which is shorter than manual checks
return c;} // And finally return the virus-counter as result
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
WS⊞υι≔⪫υ⸿θPθ≔⁰ηFθ«≧⁺›⁼ιv⁺№KMb№KVaηι»⎚Iη
```
[Try it online!](https://tio.run/##RY5NS8QwEIbPm18ReppAhb3vSYqIQpei4MnLZIlNMCZtPsaD@NvjdIvsaSbPM3lnLhbTJaJv7ds6byQ8haWW15JcmEEpOdVsofbSqZO4z9nNAZ6jCxvq3lOnermyGasvbuE/Bdbb4LGXll8fMUnG8kccRlx29@JmW2DyNffyMRksJsHDWtFncJxMW/BmYYiVQydjPscYkwHmnd7sTbzFcDb1C0O4WuyUUvvmw3Q9abv9VwzeYAJudzhgLmCVOrWmSQuNJAi1IOJK/5WEJmROot2R/wM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS⊞υι≔⪫υ⸿θPθ
```
Join the input strings with `\r` characters and draw the result to the canvas.
```
≔⁰η
```
Clear the number of live virii.
```
Fθ«
```
Loop over the characters in the input.
```
≧⁺›⁼ιv⁺№KMb№KVaη
```
If the current character is a virus and there are no adjacent `b`s in any direction or `a`s orthogonally then increment the number of live virii.
```
ι»
```
Repeat with the next character.
```
⎚Iη
```
Clear the canvas and print the total number of live virii.
[Answer]
# Perl (`-00lp`), 82 bytes
Using regex to replace `v` by space, then count the `v`s
```
/.
/;$,="(|..{@-})";$;="(|.{@-,@+})";$_=s/(a$,|b$;)\Kv|v(?=$,a|$;b)/ /s?redo:y/v//
```
[TIO](https://tio.run/##NYlBCsIwEEX3OYWUWSSYZrpxYwjt3isIksEuhGJKUwbEeHVjmiJ8eLz/5nGZTjmjEWhBu0YmY95D@1GNBVu1mB6O9bi5iNKDTgRWXS@cWPYOtE9gSeEBY7@M93B@ISPmzCzKhN/BmxJXCmIStAVPe@A/uTRffv6GeX2EZ8xt103zDw)
] |
[Question]
[
What is the best BrainFuck code (in terms of code size) to print 'A' 1000 times ?
My approach is:
* set 'A' to p[0]
* set 255 to p[1] to display 255 'A', 3 times
* set 235 to p[1] to display 235 'A'
This is not effective but I cannot find a way to use tow counters simultaneously like a multiplication
Is there a better approach than a multiplication ?
A more general question: is there a rule to make a multiplication with a large number with the smallest possible code?
[Answer]
The method you seem to currently be using is 39 bytes:
`>>+++[<-[-<.>]>-]++++[<----->-]<-[-<.>]` (not including getting the `A`) ([Try It Online!](https://tio.run/##SypKzMxLK03O/v9fx85OW1s72kY3WtdGzy7WTjdWG8IHASAPJvH/vyMA))
(loop 3 times, each time set the counter to 255 and print that many times, then subtract 20, subtract 1, and print that many times)
However, it is much shorter to loop 250 times and print 4 times each time (thanks to jimmy23013 for optimizing this over my original loop-4 loop-250 print-1 solution):
`>------[<....>-]` (16 bytes)
If your cells are unbounded (I'm assuming they're 8-bit otherwise you probably wouldn't try using 255 for golfing):
`>>++++++++++[<++++++++++[<..........>-]>-]` (42 bytes).
[Answer]
the shortest way to get the number 65 for 'A' is `>+[+[<]>>+<+]>`, and then you just add HyperNeutrino's `>------[<....>-]` to the end of that.
so the full code becomes `>+[+[<]>>+<+]>>------[<....>-]` (30 bytes)
[Answer]
# 47 Bytes ( No Underflows )
I just did this solution in 47 bytes. I tried doing it in a different manner than I normally would trying to save space by juggling counters between two values. It assumes that A is preloaded into p[4].
```
+++++[>++++>+++++<<-]>[>[>+>.<<-]>[->.<<+>]<<-]
```
## Explained
```
Place 5 into p[0]
+++++
Loop 5 times to put p[1]=20, p[2]=25
[>++++>+++++<<-]>
Loop 20 times
[>
Move pointer to p[2] and loop 25 times.
Also move p[2] to p[3]
[
Increment p[3] from 0, effectively moving the value from p[2] to p[3]
>+
Print p[4]
>.
Decrement p[2]
<<-]
Shift over to p[3]
>
[
Decrement p[3]
->
Print p[4]
.<
Increment p[2]
<+>]
Move back to p[1] and decrement
<<-
Repeat until p[1] is 0
]
```
] |
[Question]
[
Given an infix expression, determine whether all constants are of the same type.
Operators will consist only of these **dyadic** operators: `+-/*`
Your program or function should take a valid expression string as input, and output a truthy value if the constants in the expression are of the same time, and a falsey value otherwise.
The expression will consist solely of constants, and may contain any of the following types:
* String, of the form `"String"` (Always double quotes, can be empty, no escape characters, may contain any ASCII text)
* Integer, of the form `14` (Always positive or zero)
* Float, of the form `7.3f` (Always positive or zero, always has a decimal component, eg `14.0f`)
* Byte, of the form `0x42` (`0-255`, Always 2 hexadecimal characters)
* Boolean, of the form `true` (`true` or `false`, case insensitive)
The expression will not contain parentheses, as order of operation doesn't affect type when no type coercion is present.
A lone constant with no operators is a valid expression.
An empty expression is not a valid expression.
You may assume that the expression string contains no whitespace outside of string literals.
*Note: Alternatively you may assume that there will always be spaces between constants and operators, as seen in the testcases. If you make this assumption, please specify as such in your answer*
You do not have to handle invalid expressions such as `1 +`.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins!
# Test cases
*(Whitespace added for readability)*
```
2 + 3
True
"Hello" / "World"
True
true * false
True
"Hello" + 4
False
"Hello" + "4"
True
3 + 2.4f / 8
False
0xff * 0xff
True
0xff + 2
False
6
True
" " + ""
True
"4 + false" + "word"
True
```
[Answer]
# JavaScript (ES6), ~~79 77~~ 75 bytes
*Saved 2 bytes thanks to @ExpiredData*
Expects whitespace around operators. Returns a Boolean value.
```
s=>![/".*?"/g,/0x../g,/\S+f/g,/\d/,/e/i].filter(e=>s!=(s=s.split(e)+''))[1]
```
[Try it online!](https://tio.run/##jZE/b8IwEMX3forDy9mE@ihEVRfTreoOUgfKEJEzCrIwstOWb586Xqqmf4iXJ1m/e/f8fKzeq7gPzbm9PfmaO2u6aFaTLQk9fRR0mNH8onWvr@vCZq1pRkzNTtvGtRwkm1WcGBlN1PHsmlayKhCV2t7tur0/Re9YO3@QVuICClgifD9KARFswhvfDHDxzM55AQTixQdXC/wXb9MdTMFWLjKOdy@gxEGYp97ib16UAq/aLxO40KVN6R9whP38Ym1K3wuO6CbjaQP@rPJX@/th7VfKgfxQgSPxMtG5@Dz24UP6rC@8@wQ "JavaScript (Node.js) – Try It Online")
### How?
1. We remove all strings, using `/".*?"/g`
2. We remove all bytes, using `/0x../g`
3. We remove all floats, using `/\S+f/g`
4. We look for a remaining digit with `/\d/`; if we do find one, there must be at least one integer
5. We look for a remaining `"e"` or `"E"` with `/e/i`; if we do find one, there must be at least one Boolean value
All removed expressions are actually replaced with a comma, which is harmless.
We filter out the regular expressions causing no change to the input string and test whether less than two of them remain at the end of the process.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 23 bytes
```
ṣ”"ŒœḢYŒlḲŒœḢeþ@“.e¶x”E
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYqHZ10dPLDHYsij07KebhjE5SXenifw6OGOXqph7ZVABW5/tcB8hR07RSAHJ3D7VwPd2853P6oaU3k//9GCtoKxlxKHkBD85UU9BWUwvOLclKUuEqKSlMVtBTSEnOKU@HS2gomSGwlEyUuYyBtpGeSBtRpwWVQkZYG1AOiIGygHJcZl5ICWLUSl5IJkAabCBYozy8CWgQSMwXqMuMKKSp11XYDW2gI0go2ysAY5hQlqE59BZAA0AIDkCogZQShjCGUCQA "Jelly – Try It Online")
A monadic link that takes a string as input and returns 1 for true and 0 for false (Jelly’s boolean values). Expects whitespace around operators.
I’ve added a few new test cases to the TIO including one with three operators and one with mixed case for booleans.
### Explanation
```
ṣ”" | Split input at double-quotes
Œœ | Split into two lists, one of odd indices and one even. The even indices will have the contents of the quoted bits in the input (if any)
Ḣ | Keep only the odd-indexed items
Y | Join with newlines (so now all quoted strings in input are a single newline)
Œl | Convert to lower case (so that booleans are case insensitive)
Ḳ | Split at spaces
ŒœḢ | As before just take odd indices
eþ@“.e¶x” | Check for each section which they contain of .e¶x (respectively floats, booleans, strings and hex; integers will have none of these)
E | Check each section is equal (will return true for single section)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 73 bytes
```
for$f(qw/".*?" \d+.\d+f 0x.. ....?e \d+/){s/$f//gi&&last}$_=/^[+\/* -]*$/
```
[Try it online!](https://tio.run/##FchRCsIwDIDhq4RQhrY0qcgeZSfwBJvKxEUGw9Z2MEG8unH@8L38achTrSoxG9k8F0ayDUJ3c7QSCC8ioLVm@E/evgsbYb6PVTX1Zf6Yy4HPrevYgj9Zw6ooMYKDPQIDXvuM35jmMT6K@mNNYRfUpx8 "Perl 5 – Try It Online")
**How?**
Attempt to remove strings, floats, hex, boolean, and integers, in that order. Stop as soon as something is removed. After stopping, check to see if the remaining string consists only of operators and whitespace. It if does, the trype check is true; if not, it's false.
**First attempt: Perl 5 `-MList::Util=all` `-p`, 99 bytes**
```
s/".*?"/!/g;for$f(qw/! \d+ \d+\.\d+f 0x[0-9a-f]{2} (true|false)/){$\||=all{/^$f$/i}/[^+\/* -]+/g}}{
```
[Try it online!](https://tio.run/##FYzLCoJAFEB/5SoufDBzJ00oI/qBWrbyAUJeGRjSHKNgnF9v0sU5Z3fGblK5cxp9Hl989LA/0TAFFL4@6EH1SDYqvopAfEvBji2j2qQWwnl6dwu1SncRRiaoluXcKmWwCShAabFskgpjYHWCvbXGuYwLggRSvidAOPCMfsM4y@GpHbvlXOzE2qvUc1HcZ6m2m2PjHw "Perl 5 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~113~~ ~~111~~ 109 bytes
```
n=>@""".*?"" 0x.. \S+f \d e|E".Split().Single(x=>n!=(n=System.Text.RegularExpressions.Regex.Replace(n,x,"")))
```
Port of [Arnauld's javascript answer](https://codegolf.stackexchange.com/a/184965/84206). Is 72 bytes with the flag `/u:System.Text.RegularExpressions.Regex`.
[Try it online!](https://tio.run/##TUxNTwIxEL33VwxzagUqwsaY4KIeSDTxYFgTLlw2u1NorF3SllCC/Pa1uybqZd6b91X5ceV1@1QF3dh7H5y224XKW5svHhFRXj0gwiRKCZtiqGBTA30tURZ7owMXskhxQzzmCzvIuc2Lkw/0Kd8pBrmi7cGUbhn3jrxP876TKKa7N2VF3I7iCFEI0c7ZcafTzouVb0QfXMAgh/GNYGcGENzprPiKyvpVW@JCzNdOB@qf4A4k5peqDNXu/Cer0vhOZ5d2CkOYMXwmYxqEa8B140yNrGvCFfTJX3sI2T@OGbJZwqnMVGresUlUKnU6@OHJY7cMoU8jwyxhv9gLx8bV@A0 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 36 bytes
```
`".*?" 0x.. %S+f %d e|E`¸è@UÀ(U=rXÃÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=YCIuKj8iIDB4Li4gJVMrZiAlZCBlfEVguOhAVcAoVT1yWMPJ&input=IlwiMiIgKyAxIg)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~50~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'"¡āÉÏ»lð¡āÉÏε".e
x"Så}Ë
```
-26 bytes by making a port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/184990/52210), so make sure to upvote him!!
Expects input with spaces at the operands.
[Try it online](https://tio.run/##yy9OTMpM/f9fXenQwiONhzsP9x/anXN4A4xzbquSXipXhVLw4aW1h7v//1cyUdBWMFMCEkpmSgA) or [verify all (plus some more) test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v/VlQ4tPNJ4uPNw/6HdOYc3wDjntirppXJVKAUfXlp7uPu/zn8jBW0FYy4lj9ScnHwlBX0FpfD8opwUJa6SotJUBS2FtMSc4lS4tLaCCRJbyUSJyxhIG@mZpAF1WnAZVKSlAfWAKAgbKMelpABWq8SlZAKkweaBBcrzi1JAgtroQjCdQFMhrtCH6AKKgbhcIRAxN2SxkqBSV5A6x5xgkFhIUWgql6GBgq6CMch/BlyGFnoGaSCunrFxGpeSEcT52sbaQC@YgW3hAuvlMtIzsLSwBCopSS0u0QMRSgA).
**Explanation:**
```
'"¡ '# Split the (implicit) input-string by '"'
āÉÏ # Only keep all values at 0-based even indices
» # Join them by newlines
l # Converted to lowercase (for `true`/`false`)
ð¡ # Split by spaces (NOTE: `#` cannot be used here, since inputs without
# operands wouldn't be wrapped inside a list)
āÉÏ # Keep all values at 0-based even indices again
ε".e
x"Så} # Check for each item for each of [".","e","\n","x"] if it's in the item
Ë # Check if all inner lists are the same
# (which is output implicitly as result)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 102 bytes
```
import re
def f(s):
m=map(eval,re.split('[*+-/]',s))
return all(map(lambda t:type(t)==type(m[0]),m))
```
[Try it online!](https://tio.run/##Hco7CsMwDADQOT6Ft0it@6FjwCcJGVSi0ICVCFkt5PQu7faGp4e/9u3R2iq6m0fjMPMSF6g4hE6ykAJ/qCTja9WyOvTj6Xy5TX2qiKEz9rdtkUqBXy0kz5miD34og2POf8h4nzAJYmtf "Python 2 – Try It Online")
Not entirely sure how to represent some of these types in Python. For example, 0xff and 2 are both treated as integers. And 2.4f isn't a valid type in Python, I think. Capitalized True and False for testing Booleans.
Edit: Grammar
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ïd"┬Z\¡►L!8$lm╗╕╤☻ú≡╝ò6Å>^
```
[Run and debug it](https://staxlang.xyz/#p=8b6422c25a5cad104c2138246c6dbbb8d102a3f0bc95368f3e5e&i=2+%2B+3%0A%22Hello%22+%2F+%22World%22%0Atrue+*+false%0A%22Hello%22+%2B+4%0A%22Hello%22+%2B+%224%22%0A3+%2B+2.4f+%2F+8%0A0xff+*+0xff%0A0xff+%2B+2%0A6%0A%22+%22+%2B+%22%22%0A%224+%2B+false%22+%2B+%22word%22&a=1&m=2)
This program expects spaces around the operators. In general, it works by applying a few transformations to the input such that the maximum character for each expression type is distinct.
Unpacked, ungolfed, and commented, it looks like this.
```
i suppress automatic evaluation of input
'"/2::'s* replace quoted strings with 's'
.\d'9R replace all digits with '9'
.ez|t replace 'e' with 'z'
j2:: split on spaces, and discard alternating groups (operators)
{|Mm calculate the maximum character in each remaining group
:u resulting array contains exactly one distinct value
```
[Run this one](https://staxlang.xyz/#c=i++++++++%09suppress+automatic+evaluation+of+input%0A%27%22%2F2%3A%3A%27s*%09replace+quoted+strings+with+%27s%27%0A.%5Cd%279R+++%09replace+all+digits+with+%279%27%0A.ez%7Ct++++%09replace+%27e%27+with+%27z%27%0Aj2%3A%3A+++++%09split+on+spaces,+and+discard+alternating+groups+%28operators%29%0A%7B%7CMm+++++%09calculate+the+maximum+character+in+each+remaining+group%0A%3Au+++++++%09resulting+array+contains+exactly+one+distinct+value&i=2+%2B+3%0A%22Hello%22+%2F+%22World%22%0Atrue+*+false%0A%22Hello%22+%2B+4%0A%22Hello%22+%2B+%224%22%0A3+%2B+2.4f+%2F+8%0A0xff+*+0xff%0A0xff+%2B+2%0A6%0A%22+%22+%2B+%22%22%0A%224+%2B+false%22+%2B+%22word%22&m=2)
[Answer]
# Haskell, 140 Bytes
```
r(a:t)|a=='"'=a:r(tail$snd$span(/=a)t)|elem a"+-*/"=r t|0<1=a:r t
r n=n
f x|z<-[last$'i':(filter(`elem`t)"fex\"")|t<-words$r x]=all(==z!!0)z
```
[Answer]
# JavaScript: 69 bytes.
```
a=>{b=a.split(/\+|\-|\*|\//);return typeof eval(b[0])==typeof eval(b[1])}
```
## Remarks
* `eval` is a dangerous operation.
* I used bad JavaScript practices in the process, like implicit globals and auto-semicolons.
## Explanation
* `b = ...` sets the variable `b` to the array created by splitting `a` based on the dyadic operations
* `return ...` returns `true` if the types of the return values of `eval` match, `false` otherwise.
] |
[Question]
[
## Input:
A list of integers (which will never contain a zero)
## Output:
A list of the same size with counts based on the following:
* If the current item is negative: Look at all items before this item, and count how many times the digits occurred in those other numbers
* If the current item is positive instead: Look at all items after this item, and count how many times the digit occurred in those other numbers
There is one twist: If the size of the list is even we only count every number once (even if it matches multiple digits), and if the size is odd we count every digit of the numbers for each digit of the current item (duplicated digits are counted multiple times).
Let's give some examples to clarify this a bit:
**Example with even list:**
```
Input: [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2, 4, 1, 2, 1, 1, 5 ]
```
Size of the list is **even**, so we only count each number once.
* `4`: It's positive, so we look forward. There are three numbers containing the digit `4` (`42`, `-942`, `8374`). So we start with a `3`.
* `10`: It's positive, so we look forward. There are two numbers containing either the digit `1` and/or `0` (`-10`, `-200`). So the second output is `2`.
* `42`: Again positive, so forward. There are four numbers containing either the digit `4` and/or `2` (`-942`, `8374`, `728`, `-200`). So the third output is `4`.
* `-10`: This time it's negative, so we look backwards. There is only one number containing the digit `1` and/or `0` (we ignore the minus sign) (`10`). So the fourth output is `1`.
* etc.
**Example with odd list:**
```
Input: [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13, 2, 2, 4, 8, 3, 0, 11, 6 ]
```
Size of the list is **odd**, so we count every digit.
* `382`: It's positive, so we look forward. There is one `3` in the other numbers (`381`), six `8`'s in the other numbers (`-82, -8, 381, 228, 28, -28`), and six `2`'s in the other numbers (`-82, 228, 28, -28, 2`). So we start with a `13`.
* `-82`: It's negative, so backwards. There is one `3` in the other number (`382`), and one `8` in the other number (`382`). So the second output is `2`.
* ...
* `228`: It's positive, so forward. There are three `2`'s in the other numbers (`28`, `-28`, `-2`), and another three `2`'s, and two `8`'s in the other numbers (`28`, `-28`). So this output is `8`.
* etc.
## Challenge rules:
* You can assume the input will never contain `0` as item, since it's neither positive nor negative.
* You can assume the input-list will always contain at least two items.
* I/O is flexible. Input/output can be array/list of integers, delimited string, digit/character-matrix, etc.
* If the first number in the list is a negative number, or the last number in the list is a positive number, it will be 0 in the resulting list.
* With odd lists, numbers containing the same digit multiple times are counted multiple times, like the `228` in the odd example above resulting in `8` (3+3+2) instead of `5` (3+2).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
Input: [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2, 4, 1, 2, 1, 1, 5 ]
Input: [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13, 2, 2, 4, 8, 3, 0, 11, 6 ]
Input: [10, -11, 12, -13, 14, -15, 16, -17, 18, -19]
Output: [9, 1, 7, 3, 5, 5, 3, 7, 1, 9 ]
Input: [10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20]
Output: [11, 2, 8, 4, 5, 6, 3, 8, 1, 10, 0 ]
Input: [88, 492, -938, 2747, 828, 84710, -29, -90, -37791]
Output: [8, 9, 3, 9, 3, 4, 5, 4, 12 ]
Input: [-1, 11, 11, 1]
Output: [0, 2, 1, 0]
Input: [1, 11, 11, -1]
Output: [3, 2, 1, 3 ]
Input: [-1, 11, 1]
Output: [0, 2, 0]
Input: [1, 11, -1]
Output: [3, 2, 3 ]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~149~~ ~~148~~ ~~121~~ ~~116~~ ~~111~~ 107 bytes
```
lambda l:[sum([any,sum][len(l)%2](map(`n`.count,`abs(v)`))for n in l[:i:2*(v<0)-1])for i,v in enumerate(l)]
```
[Try it online!](https://tio.run/##nY7NasMwEITvfQpdClKRivXTSjLtk6gCK61NDLZsHNuQp3d3HdomkFMPEh87M7sznufjkNXWvH9sXeoPX4l0ZTgtPQ0pnzlADF2dacceVaR9GmmVq@fPYckzr9LhRFdWMdYME8mkzaQLZVuqJ7q@FUzIuAstX1Gq89LXU5pr2BW3cWrzTBoaDCey4MQoTgSC8IhOWxCscjBQRRHZw29AO7RePk60k5wo9OGTBW64pK4z@2IJTrmf0QAG4QXgFcECYEr6f8bg/k1LB2PjMeY1lrMGvA6bOWP3vcqjiKSt9fI6LPDkz7sp9DcX9xN33OjcvgE "Python 2 – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 204 bytes
```
a->{int l=a.length,r[]=new int[l],i=0,j,x,y,b,s,t=10;for(;i<l;i++)for(j=i+(s=a[i]>0?1:-1);0<=j&j<l;j+=s)for(b=0,x=a[i];x!=0;x/=t)for(y=a[j];b<1&y!=0;y/=t)if(x%t==-y%t|x%t==y%t){r[i]++;b+=1-l%2;}return r;}
```
[Try it online!](https://tio.run/##nVKxkpswEO39FZvCNxAEQUACnCxn0qRLdaWHQvZhRwSDR5IdMw7f7tOKOL6ZuyqFxNO@93ZXrBpxEmHz/Osq94deGWjsOToa2UYf2exNbHvsNkb23bukNqoWe6Q2rdAafgjZwWUGcDiuW7kBbYSxn1Mvn2FvOe/JKNntVhUItdO@kwJ8/1tiITuzqojbl7DlVxEuL/YELRdRW3c785OoVcW7@jegqLVaHpOGnMlA1kQTw2nMtr3ymFy0TAaBj4eGy8DTXKxktYy/0seQ@ixe8OahsaIm4Nqp1jbT2YnY@QOP2fkTN44YbLCp2HpBHwYkBiTk1jvPDefhMDd/HLLAvyhrDwK2DjgN23nCRlWbo@pAsfHK3F1PQoGptdHA4XaPalVNPwLgkhGgMYEsIRAiCEuERZpbIk8KG0jieCQ3eVqgcNoIpAUlkKAKF43RP3nuDpeUWh11JVILMgSfLfiCILcAPbT8L5Ot/aq/wgazEk1lim3lmVUW2FOR5S5rUiKJKM3zkt6tIZa7rVet3KPhe@o3yn@qcZoAztT9dTeHx2kat6cI8DRoU@@j/miig32rpu28b0qJQUemn16vt43E4dAOHjp935/SjjNc4/UF "Java (JDK 10) – Try It Online")
# Credits
* -6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* -1 byte thanks to [Java Gonzar](https://codegolf.stackexchange.com/users/70191/java-gonzar)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes
```
vy0›iNƒ¦}ëN£}€Sþyδ¢IgÈiĀ€Ù}OOˆ
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/rNLgUcOuTL9jkw4tqz282u/Q4tpHTWuCD@@rPLfl0CLP9MMdmUcagCKHZ9b6@59u@/8/2kRHwdBAR8HESEdBF8TQtQQxLYzNgRLmRhZAASMDg1gA "05AB1E – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~100~~ 85 bytes
```
{.kv.map:{sum map (?*,+*)[$_%2],.[grep (*-$^i)*$^v>0,^$_].map:{.comb⊍$v.abs.comb}}}
```
[Try it online!](https://tio.run/##JYvdCoIwFMfve4pzsULXccwpuYrqQcYUDY2ooSgJIr5A0Ev2IsvlxTn8/l9N2T531gywqeBkR/bomcmbw9i9DMwA3oXilvqKZGuhkalbW84mDUh69ylJ@zPHlGR6GbFrbYrv@0N6lhfdX03TZLt8gMojmQ9V3a5UjBByhFggBA6CvUMZJXOQCDkbgnONKxVJV1keQiRDBOFydyF3y6Wtj/YH "Perl 6 – Try It Online")
Uses the baggy multiplication operator ⊍.
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 92 bytes
```
($t=$&>0?$':$`)&say$q=y/ //%2?@a=$t=~/\b\d*[$&]+\d*\b/g:map$t=~/$_/g,$&=~/\d/g while/-?\d+/g
```
[Try it online!](https://tio.run/##HYpbDoIwFAW30o9rfdB6S4WAJFg34AqsUQikkiCgkBh@XLq19etMzsxQv9rY2hVMOdCDULDM4LamYzHDM5@RIC6kOha58x/Upa42Z6CXwK0u0WSPYvgbuKJhQH1ToSHve9PWyJWuAjTWRoyEgpFIMsI98L3HdJc4kcjUHVKIbz9MTd@Nlp/irQiF5d0P "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),164,158,140 139 bytes
```
a=>a.map((x,i)=>a.slice(x<0?0:i+1,x<0?i:l).map(b=>c+=[...b+""].map(X=>s+=X>=0&&(x+"").split(X).length-1,s=0)&&l%2?s:+!!s,c=0)|c,l=a.length)
```
[Try it online!](https://tio.run/##nVHRbqMwEHzvV2yqNrKFQTbQANE5/Y1ICCmEOjkqDlDNnSL18u3proFLorune1hrPLs7s2u/l79KW33U/eC33Zu5HPSl1Jsy@FH2jJ1Ezelim7oy7PRNvsp17SlBqF433FXt9abydB4Ewd57fCwct9Ub6@ntRsvlkp2Q5oHtm3pgWx40pj0O330lrJZ8uWyew1e79hYLKyokflei0eVUxC@DsYNmddsLc@pxls8HgPrADkTx4L2r291uoTE3YY55gKprbdeYoOmObHfsBsifPseWcwH7nwNgg6kG80YJxOfCNZrGmrveOxt9Z3N@oNFYHgtQUkAcCvAJ@BnBNEowkYQpEqGUhcgjAcgDsqAw3GWC4/mCUfBRFfIoJcHxEBClWBKSGoWS5DNqo7JC6VFuNoCUDqIlAUX6qz/iuRuTSOWGxjoVE3hBsCKQICB1laF8Nk@MrNMErHPhbomYFsjgvxxwJXoeKg7n0ePZZTW7pLMLKYO8OqWYiTNyySJ6niRG6ZTeJo0TN0aYUZJQlCSZQi8Sy2blCY7YGU/LOaxCuPmW3KeV5kAlOb08TSav21@LfHX9eiqK/qF1o/OXxm0/9V6@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 126 bytes
```
->l{k=l.map{|i|i.abs.digits};c=-1;k.map{|n|x=k[l[c+=1]<0?0...c:c+1..-1];x.sum{|j|x=n.sum{|d|j.count d};l.size%2<1?x<1?0:1:x}}}
```
[Try it online!](https://tio.run/##zZHBboMwDIbve4pcdiqJYkKbpDTrgyAOLV0nCu2q0UpshWdndgKa2t12mpSgH/v3Fzv5uG4/h70b@Et9q1wtjpvzrSu7Umy2jdiVb@Wl6dPCcUirkDt1rauyOitmDvKVXEshRLEsZiAEhzxtRXM93roDuk5B7rqDKN6vpwvb9WktmvLr9TlewbrFLZewbPu@H85sn2VJxEBGLIkjxklwS9IojQkdGwzEUuY5c45lKmKYowovwK85y588SRlihE/ElCETAWiDJHTAjTAItACkgoihB7BqMRH/c2@@H4qA7w4dkJCYo1iQ0CiICXaEWt@S9rS5X8r/YtD@gYrtTbNDmNn4dtG68GgTbgGJcsIbslhCW0XT6wR5hkY3ifZnx5aSpJTWFsYD0GA9M3zDKXTX8UTmEO7H77FKTi8hp@l@PBzu3g0j6hfqDvPAeKjH4uEb "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ 42 bytes
```
>0ị"ḊÐƤżṖƤƊAṾ€€FċЀ¥e€€³LḂ©¤?"AṾ$€SṀ€S$®?€
```
[Try it online!](https://tio.run/##y0rNyan8/9/O4OHubqWHO7oOTzi25OiehzunHVtyrMvx4c59j5rWAJHbke7DE4D0oaWpEIFDm30e7mg6tPLQEnslkDIVoFjww50NIErl0Dp7IP3///9oYwsjHQVdCKGjYGxhqKNgZARkgbChgQFQGMTSNYoFAA "Jelly – Try It Online")
] |
[Question]
[
Now that other users have helped [Trump build the wall](https://codegolf.stackexchange.com/questions/67452/help-trump-build-the-wall), its time for you to climb it.
This is an ascii art challenge where you need to output a climbing wall with randomly placed holds.
A climbing wall is made up of panels each of which has between 3 and 10 holds and is 5 panels high. Each panel is 4 characters high and 10 characters across
We use `|` to represent the side of the wall (the arête) and a `-` to represent the edges of panels. The corners of the panels are shown by `+` and the holds are shown as `o`.
Finally, the wall must have `America!` at the top and `Mexico` at the bottom.
Your program should take no input unless input is required to run and should output something that looks similar to the below
This is an example output:
```
America!
+----------+
| o |
| o o |
| o o |
| o o |
+----------+
| o |
| o o |
| o o |
| o o |
+----------+
| o |
| o o |
| o o |
| o o |
+----------+
| o |
| o o |
| o o |
| o o |
+----------+
| o |
| o o |
| o o |
| o o |
+----------+
Mexico
```
This may be confusingly set out so it's structured more clearly below
## Input
Zilcho. You should take no absolutely input.
## Output
An ascii-art climbing wall made up of 5 panels, each one 6 lines by 12 columns with `America!` centered at the top and `Mexico` centered at the bottom. Each panel has an identical pattern that is randomly generated by the program. The panel pattern consists of a randomly distributed random number of holds, between 3 and 10.
## Rules
* No input allowed
* I would say "no builtins" but if your language has a builtin for this, I will automatically accept it as the winner.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code (in bytes) wins.
* The output without holds must be exactly the same as above, again without holds.
* Random is the random defined [here](https://codegolf.meta.stackexchange.com/a/10923/66833)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~65~~ 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**First ever use of the new-fangled `⁽`, a [two-code-point integer string literal](https://github.com/DennisMitchell/jelly/wiki/Tutorial#312string-literals)** (`⁽¥0` = 2049)
```
⁽¥0ṃ⁾+-W
“K2X)»Ṅø40RẊ<8X+3¤s⁵ị⁾o j@€⁾||Yṭ¢µṄ€5¡Ṗ;⁷“Ç€:;#»
```
Full program taking no input and printing the wall.
**[Try it online!](https://tio.run/nexus/jelly#@/@oce@hpQYPdzY/atynrRvO9ahhjrdRhOah3Q93thzeYWIQ9HBXl41FhLbxoSXFjxq3PtzdDVSYr5Dl8KhpDZBVUxP5cOfaQ4sObQWqBwqZHlr4cOc060eN24EGHW4HilhZKx/a/f//17x83eTE5IxUAA)**
### How?
```
⁽¥0ṃ⁾+-W - Link 1, panel separator: no arguments
⁽¥0 - literal 2049
⁾+- - literal "+-"
ṃ - convert 2049 to base "+-" as if they were [1,0]
W - wrap in a list -> ["+----------+"]
“K2X)»Ṅø40RẊ<8X+3¤s⁵ị⁾o j@€⁾||Yṭ¢µṄ€5¡Ṗ;⁷“Ç€:;#» - Main link: no arguments
“K2X)» - " America!"
Ṅ - print with line feed
ø - niladic chain separation
40 - literal 40
R - range -> [1,2,...,40]
Ẋ - random shuffle
¤ - nilad and link(s) as a nilad:
8X - random integer between 1 and 8
3 - literal 3
+ - add
< - less than? (vectorises)
⁵ - literal 10
s - split into chunks of length 10
⁾o <-- a space - literal "o "
ị - index into
⁾|| - literal "||"
j@€ - join with reversed @rguments
Y - join with line feeds
¢ - call last link (1) as a nilad
ṭ - tack left to right
µ - call that p... (monadic chain separation)
5¡ - repeat five times:
€ - for €ach (separator & panel)
Ṅ - print with trailing line feed(separator and panel):
Ṗ - pop (just the separator now)
⁷ - literal line feed
; - concatenate
- unused value printed
“Ç€:;#» - " Mexico"
- implicit print
```
[Answer]
# PHP, 138 Bytes
```
<?=($p=str_pad)(" America!",349,strtr("
+----------+
|0|
|1|
|2|
|3|",str_split(str_shuffle($p($p(o,rand(3,10),o),40)),10)))." Mexico";
```
[Try it online!](https://tio.run/nexus/php#@29jb6uhUmBbXFIUX5CYoqmhpKDgmJtalJmcqKikY2xiqQOUKSnSUOLS1oUDba4agxquGkMgNgJi4xolkKr44oKczBINMCujNC0tJxVoMAjl6xQl5qVoGOsYGmjq5GvqmBhoaoLYmpp6QNsUfFMrMpPzlaz///@al6@bnJickQoA "PHP – TIO Nexus")
Expanded
```
<?=($p=str_pad)(" America!",349,
#fill the string till a length of 349 with
strtr("
+----------+
|0|
|1|
|2|
|3|",
# before replace the digits with strings in the array
str_split(str_shuffle($p($p(o,rand(3,10),o),40)),10)))
# make a string with o length 3- 10 fill it with spaces to length 40
# shuffle the resulting string and split it into a array of strings with length 10
." Mexico"; # add the end
```
[Answer]
# JavaScript (ES6), ~~194~~ 160 bytes
```
(h=0,g=p=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s])))=>` America!
${t=`+----------+
`}${g(`| |
`.repeat(4)+t).repeat(5)} Mexico`
```
---
## Try It
The pattern of the holds will change every 2 seconds in the Snippet below.
```
f=
(h=0,g=p=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s])))=>` America!
${t=`+----------+
`}${g(`| |
`.repeat(4)+t).repeat(5)} Mexico`
o.innerText=f()
setInterval("o.innerText=f()",2e3)
```
```
<pre id=o>
```
---
## Explanation
* We create an anonymous function, which, although it doesn't take any input, does have 2 parameters with default values:
+ `h`, which is given an initial value of `0`; this will keep count of number of holds on the panel when we go to add them.
+ `g`, which is a recursive function we'll use to create the random pattern of holds on the panel. We'll come back to this in a bit.
* In the main function body, we output a template literal, starting with `America!\n`.
* We then create the panel divider (`+----------+\n`) and assign it to variable `t`, adding it to the output in the process.
* Next, we create a single line of the panel (`| |\n`), repeat it 4 times and append `t`.
* We call `g`, passing the string from the step above as an argument, via parameter `p`.
* Now, for the hold pattern. Within `g`:
+ We check to see if `h>2` (i.e., do we have 3 or more holds).
+ If so, we return the string `p`.
+ If not, we call `g` again, this time passing a modified copy of `p` as the argument.
+ The modified copy of `p` has the `replace` method used on it, replacing all `<space>` characters with a `<space>` or an `o` by referencing the character index (0 or 1) of the string `<space>o`.
+ We determine the character index by
1. Calling `Math.random()`, which returns a decimal number between 0 & 1, exclusive.
2. Checking if that is greater than `.8`. With their being 40 spaces in the panel and there only being a maximum of 10 holds, doing this improves the distribution of the holds across the panel (`.75` would be more accurate, but, hopefully, you'll allow me the concession for the sake of saving a byte!).
3. The boolean of that check is assigned to variable `s`.
4. `s` is coerced to an integer (0 or 1) and added to `h`.
5. We check if `h` is now less than 11 (i.e., do we currently have less than 10 holds) *and* if `s` was true.
6. That boolean is in turn coerced to an integer, giving us an index in the string.
* Back to our output! We repeat the string returned by `g` 5 times.
* And then simply add `Mexico` to the end of the string to finish things off. Phew!
---
## Alternative
And, simply because I thought it would have made a nice addition to the challenge: For only 12 extra bytes, we can have a unique pattern of holds on each panel, instead of them all being identical.
```
(g=(p=`| |
`.repeat(4)+t,h=0)=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s]),h))=>` America!
${t=`+----------+
`}${g()+g()+g()+g()+g()} Mexico`
```
---
### Try It
Again, the patterns of the holds will change every 2 seconds.
```
f=
(g=(p=`| |
`.repeat(4)+t,h=0)=>h>2?p:g(p.replace(/ /g,_=>" o"[(h+=s=Math.random()>.8)<11&s]),h))=>` America!
${t=`+----------+
`}${g()+g()+g()+g()+g()} Mexico`
o.innerText=f()
setInterval("o.innerText=f()",2e3)
```
```
<pre id=o>
```
[Answer]
# Pyth - ~~58~~ 57 bytes, possibly 47
```
Ks(b\+*\-T\+*+++b\|*dT\|4)J<.SxdmdK+3O8+*s.e?/Jk\obK5<K13
```
[Try it](https://pyth.herokuapp.com/?code=Ks%28b%5C%2B%2a%5C-T%5C%2B%2a%2B%2B%2Bb%5C%7C%2adT%5C%7C4%29J%3C.SxdmdK%2B3O8%2B%2as.e%3F%2FJk%5CobK5%3CK13&debug=0)
Explanation of old solution (I'll update when I have the time):
```
J+++b\+*\-T\+K+J*+++b\|*dT\|4=Y<.SxdmdK+3O8+*s.e?/Yk\obK5J
J+++b\+*\-T\+ Create the +----------+, and store as J
K+J*+++b\|*dT\|4 Create a full panel (minus bottom border, and without holes), store as K
xdmdK Get indices of spaces
.S Create random permutation of these indices
< +3O8 Get first several indices (a random number from 3 to 10)
s.e?/Yk\obK Replace space with 'o' at these indices
+* 5J Create 5 copies, and add bottom border
```
I think I can get 47 while still technically following the rules:
```
JhO2Ks(b\+*\-T\+*+++b\|.S+*\oJ*d-TJ\|4)+*K5<K13
```
Here, the number of holes is still randomly chosen (from the set {4,8}) and the configuration of those holes is randomly chosen (from the set of configurations where each row is identical)
[Try it](https://pyth.herokuapp.com/?code=JhO2Ks%28b%5C%2B%2A%5C-T%5C%2B%2A%2B%2B%2Bb%5C%7C.S%2B%2A%5CoJ%2Ad-TJ%5C%7C4%29%2B%2AK5%3CK13&debug=0)
[Answer]
## Mathematica, 201 bytes
```
c=Column;s=RandomSample[Tuples[{" ",o," "," "},10],4];t="+----------+";w=c[{t,c[Row/@Table[AppendTo[s[[i]],"|"];PrependTo[s[[i]],"|"],{i,Length@s}]]}];c[Flatten@{" America!",Table[w,5],t," Mexico"}]
```
[Answer]
## Powershell (255 Bytes)
```
echo " America!"
for($l=0;$l-lt4;$l++){$a=," "*12;$a[0]="|";$a[11]="|";$i=get-random -Max 10 -Min 6;$j=get-random -Max 5 -Min 1;$a[$i]=$a[$j]="o";$b+=($a-join"")}
for($k=0;$k-lt5;$k++){echo +----------+($b-join"`n")}
echo +----------+`n" Mexico"
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~259~~ ~~224~~ ~~221~~ 218 bytes
```
from random import*
b=[' ']*40
for x in sample(range(40),randint(3,10)):b[x]='o'
a=["+"+"-"*10+"+"]+['|'+''.join(o)+'|'for o in[b[x*10:x*10+10]for x in 0,1,2,3]]
print'\n'.join([' America!']+a*5+[a[0]]+[' Mexico'])
```
[Try it at repl.it](https://repl.it/IF2W/5)
-35 including some hints from @Satan'sSon - thanks!
-3 with thanks to @Wondercricket
[Answer]
## Python 2, 197 bytes
```
from random import*
n=randint(3,10)
s=list('o'*n+' '*(40-n))
shuffle(s)
t=10
S='+'+'-'*t+'+'
print'\n'.join([' America!']+([S]+['|'+''.join(s[x:x+t])+'|'for x in range(0,40,t)])*5+[S,' Mexico'])
```
] |
[Question]
[
## Introduction
In this game, players use their armies to fight other players' armies, capture territories, and become the last man standing. Each turn, players receive a base number of armies to use at their disposal. By capturing territories in certain regions, however, players can increase this number to give them a potential advantage later in the game. (This is essentially the same as [Warlight](http://warlight.net)).
All bots should be written in Java , C, or C++ (I would include other languages but don't have the software or experience for them). It is not necessary for your submission to extend a class, and you may create functions, classes, interfaces, or whatever else is necessary, and use any package or class in the [standard](http://docs.oracle.com/javase/8/docs/api/overview-summary.html) [APIs](http://www.cplusplus.com/reference/). If you are planning on creating a class or interface, please consider using an inner class or inner interface.
Please do not attempt to programmatically alter the controller or other submissions in this competition.
## Gameplay
### Overview
A 10x10 two-dimensional array will simulate the board, each element/cell representing a "territory". There will be 20 rounds and up to 1000 turns per round. Each turn, players will first deploy the armies they have to any of the territories they own, and then be given the opportunity to transport their armies to nearby territories in an attempt to capture their opponents' territories by attacking the armies in them. Players *must* deploy **all** their armies, but they do not have to move them if desired.
### Attacking/Transferring armies
If the player desires, he/she can send armies from one territory to any of the eight adjacent ones. The board "wraps around", i.e. if a player's territory is on one side, armies from it can be transferred to an adjacent territory on the other side. When moving armies from a territory, there should still be at least one army left in that territory. For example, if a territory contains five armies, no more than four can be moved to a different territory; if a territory contains one, that army cannot move.
If a player sends `n` armies from one territory to another that they own, that territory will receive `n` armies.
Say a player sends `n` armies from his/her territory to an opposing territory with `o` armies in it. `o` will decrease by `n * .6` rounded to the nearest integer; however, at the same time, `n` will decrease by `o * .7` rounded to the nearest integer. The following rules dealing with whether or not the opposing territory has been captured will apply:
* If `o` reaches zero AND `n` is greater than 0, the player will take over the territory, which will have `n` armies in it.
* If both `n` and `o` become zero, `o` will automatically be set to 1 and the territory will not be captured.
* If `o` remains greater than 0, the number of armies in the player's territory will increase by `n` and the opposing territory will not be captured.
### Bonuses
A group of territories will be chosen to represent a bonus; if one player owns all the territories that are part of the group, that player will receive an extra amount of armies per turn.
Bonuses have id numbers to denote different ones and values that represent the extra number of armies that a player can receive. Each round, a bonus's value will be a random number between 5 and 10, inclusive, and ten bonuses will be available on the field, each with ten territories included in the bonus.
For example, if a player that receives 5 armies per turn owns all the territories that make up a bonus with a value of 8, the player will receive 13 armies the next turn and subsequent turns. If, however, the player loses one or more of the territories that make up the bonus, he or she will receive just 5 armies per turn.
### Input/Output
Your program should take input through command-line arguments, which will have the following format:
```
[id] [armies] [territories (yours and all adjacent ones)] [bonuses] ["X" (if first turn)]
```
* `id` and `armies` are both whole numbers. `id` is your id, and `armies` is the number of armies you need to deploy to your territories. **You must deploy all the armies given to you -- no more and no less.**
* `territories` is a series of strings representing the territories you own and the territories that you do not own that are adjacent to yours. The strings are in this format:
```
[row],[col],[bonus id],[player id],[armies]
```
`row` and `col` indicate the row and column of the board where the territory is, `bonus id` is the id of the bonus that this territory is a part of, `player id` is the id of the player who owns the territory, and `armies` is the number of armies contained in the territory. These are all numbers.
* `bonuses` is a series of strings representing the bonuses on the board that you can take advantage of. The strings are in this format:
```
[id],[armies],[territories left]
```
`id` is the id of the bonus, `armies` is the number of extra armies you can receive by owning all the territories in this bonus, and `territories left` is the number of territories in the bonus that you need to capture to receive the extra armies.
Please note that a fifth argument, an "X", will appear if it is the first turn of a round and can be used for convenience reasons.
An example of input on the first turn:
```
0 5 "7,6,7,-1,2 8,7,7,-1,2 7,7,7,0,5 6,6,7,-1,2 8,8,9,-1,2 6,7,7,-1,2 7,8,9,-1,2 6,8,9,-1,2 8,6,7,-1,2" "0,5,10 1,5,10 2,9,10 3,9,10 4,9,10 5,5,10 6,5,10 7,6,9 8,7,10 9,7,10" X
```
Your program must output two strings separated by a newline, the first of which lists the rows and columns of the territories which you want to add armies to and the number of armies you want to add to it, and the second of which lists the rows and columns of the territories you want to send armies to and the number of armies you want to send. The output may contain trailing spaces.
To specify a territory you want to add armies to, your output should follow this format:
```
[row],[col],[armies]
```
`row` and `col` are the row and column of the board where the territory you want to add armies to is, and `armies` is the number of armies you want to add to the territory.
To specify which territories you want to send armies to, your output should follow this format:
```
[srow],[scol],[drow],[dcol],[armies]
```
`srow` and `scol` are the row and column of the board where the territory you want to transport armies from is, `drow` and `dcol` are the row and column of the board where the territory you want to send armies to is, and `armies` is the number of armies you want to send. Note that if you do not want to move any armies, your program should print a space.
A sample output may be this:
```
0,0,5
0,0,0,1,3 0,0,1,0,3 0,0,1,1,3
```
In this case, the player deploys five armies to the territory at 0,0 and moves three armies from 0,0 to 0,1; three from 0,0 to 1,0; and three from 0,0 to 1,1.
### Rounds and Turns
At the start of each round, all players will be given one territory located in a random spot on the board (it is possible for two or more players to start next to each other). The territories that make up a bonus may also change.
On the first turn, each player will have one territory containing five armies, and they will receive five armies they can use (this is the minimum that they can receive). All the other territories will be owned by NPCs that do not attack; each of these contain two armies and have an id of `-1`.
Each turn your program will be run, and both pieces of output will be collected. The controller will apply the first piece of output, adding armies to territories, immediately; however, the controller will wait until all players have given their second piece of output, their attack/transfer commands. Once this has been completed, the commands will be shuffled randomly and then executed. Your program must provide output and terminate in one second or less in order to participate in the turn.
## Scoring and Winning
For any given round, if one player remains, that player will earn 100 points. Otherwise, if 1000 turns pass and there are still multiple players, the 100 points will be divided evenly between the remaining players (i.e. 3 players remaining yields 33 points each). Whichever player has the most points at the end of the 20 rounds will win.
## Submissions
Your post should include a name for the bot, the language it is written in, a brief description of it, and the code used to run it. A sample bot will be posted here as an example and will be used in the contest. You may submit as many as you wish.
## Other
Your program may create, write to, and read from a file as long as the file's name is the same as the name you used for your submission. These files will be deleted prior to the beginning of a tournament but not in between rounds.
Your turn will be skipped if:
* you are eliminated (have no territories);
* your program does not print anything;
* your program does not terminate within one second;
* you deploy too few armies to your territories (deploying armies to territories you do not own will count toward this) or too many armies; or
* your output causes the controller to throw an exception.
Your attack/transfer command will not be executed if:
* your program does not give correct output;
* you choose a territory to move armies from that is not yours;
* you move zero or a negative number of armies from your territory;
* you move too many armies from your territory; or
* you choose a territory to send armies to that is not adjacent to the territory you chose to move armies from.
You can find the controller and a sample bot [here](https://github.com/TNT670/Game-of-Risk/). The bot will participate in the game, but it probably won't win any rounds (unless it's *really* lucky).
## Results
Running the controller after pushing a bug fix to it, WeSwarm continues to be a force to be reckoned with. It'll take a bot with a great strategy to have a chance against it.
```
As of 25-08-15, 04:40 UTC
1: WeSwarm 1420
2: java Player 120
java LandGrab 120
java Hermit 120
java Castler 120
6: java RandomHalver 80
```
# Notice!
A bug discovered by Zsw causing territories that deployed their armies after others to have a potential advantage in the game has been fixed. An edit was been pushed to the controller, so please use the existing version found using the link above.
[Answer]
## Castler - Java 8
He just wants to make a square castle... and if left to his own devices will do just that. Albeit that he gets bored with a small castle so makes it bigger and bigger. This will inevitably mean conflict with other players and so the battling ensues. However he never forgets his most desired shape... the square.
[](https://drive.google.com/uc?export=download&id=0B9i-DPAdw_3YTjA5ZnN4WE5nVGM)
Click image for animated gif (15 meg) of a full 20x 1000 turn simulation.
Castler scored 1700 and the other players scored 100 each.
```
import java.util.*;
import java.util.stream.Collectors;
/**
* Wants to make an expanding square castle... however if opponents interfere then will reluctantly make an odd-shaped castle
*/
public class Castler {
private static final int MAP_SIZE = 10;
private int ownId;
private int deployableArmyCount;
private List<Territory> territories;
private Territory[][] map;
private Map<Territory,Territory> territoryHashMap;
List<Territory> ownedTerritories;
public int minRow;
public int minCol;
public static void main(String[] args)
{
new Castler(args);
}
Castler(String[] args)
{
ownId = Integer.parseInt(args[0]);
deployableArmyCount = Integer.parseInt(args[1]);
territories = new ArrayList<Territory>();
map = new Territory[MAP_SIZE][MAP_SIZE];
territoryHashMap = new HashMap<Territory,Territory>();
for (String s : args[2].split(" ")) {
Territory territory = new Territory(s.split(","));
territories.add(territory);
territoryHashMap.put(territory, territory);
map[territory.col][territory.row]=territory;
}
ownedTerritories = territories.stream().filter(t->t.id==ownId).collect(Collectors.toList());
minRow=Integer.MAX_VALUE;
minCol=Integer.MAX_VALUE;
//find top left territory that is the corner of our castle :)
int largestArea=0;
for (Territory territory : ownedTerritories)
{
int area=countRightDownConnected(territory,new int[MAP_SIZE][MAP_SIZE]);
if (area>largestArea)
{
largestArea=area;
minRow=territory.row;
minCol=territory.col;
}
}
// the average army size per owned territory
int meanArmySize=0;
for (Territory territory : ownedTerritories)
{
meanArmySize+=territory.armies;
}
meanArmySize/=ownedTerritories.size();
int squareSideLength = (int) Math.ceil(Math.sqrt(ownedTerritories.size()));
// if we own all territories inside the square of our castle, or we have stalled but have the numbers to expand... make the length of side of the square larger to allow expansion
if (squareSideLength*squareSideLength == ownedTerritories.size() || meanArmySize>squareSideLength)
{
squareSideLength++;
}
// lets collate all the enemy territories within the area of our desired castle square and marke them as candidates to be attacked.
List<Territory> attackCandidates = new ArrayList<>();
for (int y=minRow;y<minRow+squareSideLength;y++)
{
for (int x=minCol;x<minCol+squareSideLength;x++)
{
Territory territory = map[x%MAP_SIZE][y%MAP_SIZE];
if (territory!=null && territory.id!=ownId)
{
attackCandidates.add(territory);
}
}
}
// sort in ascending defensive army size.
attackCandidates.sort((a,b)->a.armies-b.armies);
List<Territory> unCommandedTerritories = new ArrayList<>(ownedTerritories);
List<Move> moves = new ArrayList<>();
Set<Territory> suicideAttackCandidate = new HashSet<>();
// command owned territories to attack any territories within the area of the prescribed square if able to win.
for (int i=0;i<unCommandedTerritories.size();i++)
{
Territory commandPendingTerritory =unCommandedTerritories.get(i);
List<Territory> neighbours = getNeighbours(commandPendingTerritory,map);
List<Territory> attackCandidatesCopy = new ArrayList<>(attackCandidates);
// remove non-neighbour attackCandidates
attackCandidatesCopy.removeIf(t->!neighbours.contains(t));
for (Territory attackCandidate : attackCandidatesCopy)
{
Battle battle = battle(commandPendingTerritory,attackCandidate);
if (battle.attackerWon)
{
attackCandidates.remove(attackCandidate);
suicideAttackCandidate.remove(attackCandidate);
unCommandedTerritories.remove(i--);
Territory[][] futureMap = cloneMap(map);
futureMap[attackCandidate.col][attackCandidate.row].id=ownId;
// default to sending the required armies to win + half the difference of the remainder
int armiesToSend = battle.minArmiesRequired + (commandPendingTerritory.armies-battle.minArmiesRequired)/2;
// but if after winning, there is no threat to the current territory then we shall send most of the armies to attack
if (!underThreat(commandPendingTerritory, futureMap))
{
armiesToSend = commandPendingTerritory.armies-1;
}
moves.add(new Move(commandPendingTerritory,attackCandidate,armiesToSend));
break;
}
else
{
// we can't win outright, add it to a list to attack kamikaze style later if needed.
suicideAttackCandidate.add(attackCandidate);
}
}
}
// Find edge territories.
// A territory is deemed an edge if at least one of its neighbours are not owned by us.
List<Territory> edgeTerritories = new ArrayList<>();
ownedTerritories.forEach(owned->
getNeighbours(owned,map).stream().filter(neighbour->
neighbour.id!=ownId).findFirst().ifPresent(t->
edgeTerritories.add(owned)));
// All edge territories that have not yet had orders this turn...
List<Territory> uncommandedEdgeTerritories = edgeTerritories.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());
// Find edges that are under threat by hostile neighbours
List<Territory> threatenedEdges = edgeTerritories.stream().filter(edge->underThreat(edge,map)).collect(Collectors.toList());
// All threatened edge territories that have not yet had orders this turn...
List<Territory> uncommandedThreatenedEdges = threatenedEdges.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());
// unthreatened edges
List<Territory> unThreatenedEdges = edgeTerritories.stream().filter(edge->!threatenedEdges.contains(edge)).collect(Collectors.toList());
List<Territory> uncommandedUnThreatenedEdges = unThreatenedEdges.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());
// map that describes the effect of moves. Ensures that we do not over commit on one territory and neglect others
Territory[][] futureMap = cloneMap(map);
//sort the threatened edges in ascending order of defense
threatenedEdges.sort((a,b)->a.armies-b.armies);
int meanThreatenedEdgeArmySize = Integer.MAX_VALUE;
if (!threatenedEdges.isEmpty())
{
// calculate the average defense of the threatened edges
int[] total = new int[1];
threatenedEdges.stream().forEach(t->total[0]+=t.armies);
meanThreatenedEdgeArmySize = total[0]/threatenedEdges.size();
// command any unthreatened edges to bolster weak threatened edges.
out:
for (int i=0;i<uncommandedUnThreatenedEdges.size();i++)
{
Territory commandPendingTerritory = uncommandedUnThreatenedEdges.get(i);
// the unthreatened edge has spare armies
if (commandPendingTerritory.armies>1)
{
for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
{
for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
{
if (!(x==MAP_SIZE && y==MAP_SIZE))
{
int xx=commandPendingTerritory.col+x;
int yy=commandPendingTerritory.row+y;
Territory territory = futureMap[xx%MAP_SIZE][yy%MAP_SIZE];
// if the current threatened edge has less than average defensive army then send all spare troops to from the uncommanded unthreatened edge.
if (territory!=null && territory.armies<meanThreatenedEdgeArmySize && threatenedEdges.contains(territory))
{
// update future map
Territory clonedTerritory = (Territory) territory.clone();
clonedTerritory.armies+=commandPendingTerritory.armies-1;
futureMap[xx%MAP_SIZE][yy%MAP_SIZE]=clonedTerritory;
moves.add(new Move(commandPendingTerritory,territory,commandPendingTerritory.armies-1));
unCommandedTerritories.remove(commandPendingTerritory);
uncommandedUnThreatenedEdges.remove(i--);
uncommandedEdgeTerritories.remove(commandPendingTerritory);
continue out;
}
}
}
}
}
}
// command any stronger threatened edges to bolster weak threatened edges.
out:
for (int i=0;i<uncommandedThreatenedEdges.size();i++)
{
Territory commandPendingTerritory = uncommandedThreatenedEdges.get(i);
// the threatened edge has more than average edge armies
if (commandPendingTerritory.armies>meanThreatenedEdgeArmySize)
{
for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
{
for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
{
if (!(x==MAP_SIZE && y==MAP_SIZE))
{
int xx=commandPendingTerritory.col+x;
int yy=commandPendingTerritory.row+y;
Territory territory = futureMap[xx%MAP_SIZE][yy%MAP_SIZE];
// if the current threatened edge has less than average defensive army then send the excess troops larger than the average edge armies amount from the uncommanded threatened edge.
if (territory!=null && territory.armies<meanThreatenedEdgeArmySize && threatenedEdges.contains(territory))
{
// update future map
Territory clonedTerritory = (Territory) territory.clone();
clonedTerritory.armies+=commandPendingTerritory.armies-meanThreatenedEdgeArmySize;
futureMap[xx%MAP_SIZE][yy%MAP_SIZE]=clonedTerritory;
moves.add(new Move(commandPendingTerritory,territory,commandPendingTerritory.armies-meanThreatenedEdgeArmySize));
unCommandedTerritories.remove(commandPendingTerritory);
uncommandedThreatenedEdges.remove(i--);
uncommandedEdgeTerritories.remove(commandPendingTerritory);
continue out;
}
}
}
}
}
}
}
// for any uncommanded non-edge territories, just move excess armies to the right or down
unCommandedTerritories.stream().filter(t->
t.armies>1 && !edgeTerritories.contains(t)).forEach(t->
moves.add(new Random().nextFloat()>0.5? (new Move(t,map[(t.col+1)%MAP_SIZE][t.row],t.armies-1)):(new Move(t,map[t.col][(t.row+1)%MAP_SIZE],t.armies-1))));
// lets perform suicide attacks if we are in a good position to do so... hopefully will whittle down turtling enemies.
for (Territory target : suicideAttackCandidate)
{
List<Territory> ownedNeighbours = getNeighbours(target, map).stream().filter(neighbour->neighbour.id==ownId).collect(Collectors.toList());
for (Territory ownedTerritory : ownedNeighbours)
{
// if the edge has yet to be commanded and the territory has more than three times the average armies then it is likely that we are in a power struggle so just suicide attack!
if (uncommandedEdgeTerritories.contains(ownedTerritory) && ((ownedTerritory.armies)/3-1)>meanArmySize)
{
uncommandedEdgeTerritories.remove(ownedTerritory);
unCommandedTerritories.remove(ownedTerritory);
moves.add(new Move(ownedTerritory,target,ownedTerritory.armies-meanArmySize));
}
}
}
// deploy troops to the weakest threatened edges
int armiesToDeploy =deployableArmyCount;
Map<Territory,Integer> deployTerritories = new HashMap<>();
while (armiesToDeploy>0 && threatenedEdges.size()>0)
{
for (Territory threatenedEdge : threatenedEdges)
{
Integer deployAmount = deployTerritories.get(threatenedEdge);
if (deployAmount==null)
{
deployAmount=0;
}
deployAmount++;
deployTerritories.put(threatenedEdge,deployAmount);
armiesToDeploy--;
if (armiesToDeploy==0) break;
}
}
// no threatened edges needing deployment, so just add them to the "first" edge
if (armiesToDeploy>0)
{
deployTerritories.put(edgeTerritories.get(new Random().nextInt(edgeTerritories.size())),armiesToDeploy);
}
// send deploy command
StringBuilder sb = new StringBuilder();
deployTerritories.entrySet().stream().forEach(entry-> sb.append(entry.getKey().row + "," + entry.getKey().col + "," + entry.getValue()+" "));
sb.append(" ");
System.out.println(sb);
StringBuilder sb1 = new StringBuilder();
// send move command
moves.stream().forEach(move-> sb1.append(move.startTerritory.row + "," + move.startTerritory.col + "," + move.endTerritory.row + "," + move.endTerritory.col + "," + move.armies+" "));
sb1.append(" ");
System.out.println(sb1);
}
/**
* Recursive method that attempts to count area the territories in the square with the given territory as the top left corner
*/
private int countRightDownConnected(Territory territory,int[][] visited) {
int count=0;
if (visited[territory.col][territory.row]>0) return visited[territory.col][territory.row];
if (visited[territory.col][territory.row]<0) return 0;
visited[territory.col][territory.row]=-1;
if (territory!=null && territory.id==ownId)
{
if (visited[territory.col][territory.row]>0) return visited[territory.col][territory.row];
count++;
count+=countRightDownConnected(map[territory.col][(territory.row+1)%MAP_SIZE],visited);
count+=countRightDownConnected(map[(territory.col+1)%MAP_SIZE][territory.row],visited);
visited[territory.col][territory.row]=count;
}
return count;
}
/**
* Performs a deep clone of the provided map
*/
private Territory[][] cloneMap(Territory[][] map)
{
Territory[][] clone = new Territory[MAP_SIZE][MAP_SIZE];
for (int x=0;x<MAP_SIZE;x++)
{
for (int y=0;y<MAP_SIZE;y++)
{
Territory territory = map[x][y];
clone[x][y] = territory==null?null:territory.clone();
}
}
return clone;
}
/**
* Simulates a battle between an attacker and a defending territory
*/
private Battle battle(Territory attacker, Territory defender)
{
Battle battle = new Battle();
battle.attackerWon=false;
battle.loser=attacker;
battle.winner=defender;
for (int i=0;i<attacker.armies;i++)
{
int attackerArmies = i;
int defenderArmies = defender.armies;
defenderArmies -= (int) Math.round(attackerArmies * .6);
attackerArmies -= (int) Math.round(defenderArmies * .7);
if (defenderArmies <= 0) {
if (attackerArmies > 0) {
defenderArmies = attackerArmies;
battle.attackerWon=true;
battle.loser=defender;
battle.winner=attacker;
battle.minArmiesRequired=i;
break;
}
}
}
return battle;
}
/**
* returns true if the provided territory is threatened by any hostile neighbours using the provided map
*/
private boolean underThreat(Territory territory,Territory[][] map)
{
return !getNeighbours(territory,map).stream().filter(neighbour->neighbour.id!=ownId && neighbour.id!=-1).collect(Collectors.toList()).isEmpty();
}
/**
* returns the neighbours of the provided territory using the provided map
*/
private List<Territory> getNeighbours(Territory territory,Territory[][] map) {
List<Territory> neighbours = new ArrayList<>();
for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
{
for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
{
if (!(x==MAP_SIZE && y==MAP_SIZE))
{
Territory t = map[(x+territory.col)%MAP_SIZE][(y+territory.row)%MAP_SIZE];
if (t!=null) neighbours.add(t);
}
}
}
return neighbours;
}
static class Battle {
public int minArmiesRequired;
Territory winner;
Territory loser;
boolean attackerWon;
}
static class Move
{
public Move(Territory startTerritory, Territory endTerritory, int armiesToSend)
{
this.endTerritory=endTerritory;
this.startTerritory=startTerritory;
this.armies=armiesToSend;
}
Territory startTerritory;
Territory endTerritory;
int armies;
}
static class Territory implements Cloneable
{
public int id, row, col, armies;
public Territory clone()
{
try {
return (Territory) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public Territory(String[] data) {
id = Integer.parseInt(data[3]);
row = Integer.parseInt(data[0]);
col = Integer.parseInt(data[1]);
armies = Integer.parseInt(data[4]);
}
void add(Territory territory)
{
row+=(territory.row);
col+=(territory.col);
}
@Override
public int hashCode()
{
return row*MAP_SIZE+col;
}
@Override
public boolean equals(Object other)
{
Territory otherTerritory = (Territory) other;
return row == otherTerritory.row && col == otherTerritory.col;
}
}
}
```
[Answer]
# Hermit - Java
Just keeps adding his armies to the same town. I don't think it can be taken down without getting bonus armies.
```
public class Hermit {
public static void main(String[] args) {
int myId = Integer.parseInt(args[0]);
for (String s : args[2].split(" ")) {
String[] data = s.split(",");
int id = Integer.parseInt(data[3]);
int row = Integer.parseInt(data[0]);
int col = Integer.parseInt(data[1]);
if (id == myId) {
System.out.println(row + "," + col + "," + args[1]);
break;
}
}
System.out.println();
}
}
```
[Answer]
# WeSwarm - C++11 [v2.2]
Updated to v2.2 as of August 25, 2015.
v2.2 - adjusted due to a change in the way the controller reports armies.
v2.1 - TNT was having trouble compiling my code, so I stopped using `stoi`.
v2.0 - a code refactor along with a few bug fixes.
---
Welcome to the swarm. Our strength is in numbers. Our eternal will is to collect all your bonuses in order to maximize our spawns. Do not stand in our way, lest you wish to be overwhelmed. Do not try to defeat us, for every one you kill, three more will take it's place. You may force us to make sacrifices, but you will never force us to surrender!
```
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
/// http://stackoverflow.com/questions/236129/split-a-string-in-c
vector<string> &split(const string &s, char delim, vector<string> &elems)
{
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
/// http://stackoverflow.com/questions/236129/split-a-string-in-c
vector<string> split(const string &s, char delim)
{
vector<string> elems;
split(s, delim, elems);
return elems;
}
enum Allegiance { MINE, ENEMY, HOSTILE, NPC, ANY };
class Bonus
{
public:
Bonus(int id, int armies, int territoriesLeft)
{
this->id = id;
this->armies = armies;
this->territoriesLeft = territoriesLeft;
}
int getId()
{
return id;
}
int getArmies()
{
return armies;
}
int getTerritoriesLeft()
{
return territoriesLeft;
}
private:
/// id of the bonus.
int id;
/// number of extra armies that this bonus gives.
int armies;
/// number of territories in the bonus that still needs to be captured.
int territoriesLeft;
};
class Territory
{
public:
Territory(int row, int col, Bonus* bonus, int playerId, int armies, Allegiance allegiance)
{
this->row = row;
this->col = col;
this->bonus = bonus;
this->armies = armies;
this->allegiance = allegiance;
this->toAdd = 0;
this->toRemove = 0;
}
Territory(Territory *territory)
{
this->row = territory->getRow();
this->col = territory->getCol();
this->bonus = territory->getBonusPtr();
this->armies = territory->getArmies();
this->allegiance = ANY;
this->toAdd = 0;
this->toRemove = 0;
}
/// Ensures uniqueness
bool operator<(const Territory& other) const
{
return row < other.row && + col < other.col;
}
/// Return the minimum number of armies needed to conquer this territory.
int conquerNeeded()
{
/*
Say a player sends n armies from his/her territory to an opposing territory with o armies in it.
o will decrease by n * .6 rounded to the nearest integer;
however, at the same time, n will decrease by o * .7 rounded to the nearest integer.
The following rules dealing with whether or not the opposing territory has been captured will apply:
If o reaches zero AND n is greater than 0, the player will take over the territory, which will have n armies in it.
If both n and o become zero, o will automatically be set to 1 and the territory will not be captured.
If o remains greater than 0, the number of armies in the player's territory will increase by n and the opposing territory will not be captured.
*/
int o = this->armies; // Given o.
int n; // Solve for n.
int n1;
int n2;
if (this->allegiance != NPC) {
o = o + 5; // To account for potential reinforcement.
}
// resulto = o - 0.6n
// resultn = n - 0.7o
//
// We want a result of o = 0 and n = 1.
// 0 = o - 0.6n
// 1 = n - 0.7o
//
// Isolate n
// 0.6n = o
// n = o / 0.6
n1 = (int)ceil(o / 0.6);
// 0.7o = n - 1
// 0.7o + 1 = n
n2 = (int)ceil(0.7 * o + 1);
// Take the bigger of the two to guarantee o <= 0 and n >= 1
n = max(n1, n2);
return n;
}
/// Returns the minimum number of armies that must be added to this territory
/// to ensure that the territory cannot be taken over by an attack with n armies.
int reinforceNeeded(int n)
{
int o = this->armies; // Number of armies we already have.
int add = 0; // Solve for number of armies we need to add.
// resulto = o - 0.6n
// resultn = n - 0.7o
//
// We want a result of o = 1 at the very least.
// 1 = o - 0.6n
// 1 + 0.6n = o
int needed = (int)ceil(1 + 0.6 * n);
// We only need to reinforce if we don't have enough.
if (o < needed) {
add = needed - o;
}
return add;
}
void add(int toAdd)
{
if (toAdd > 0) {
this->toAdd = this->toAdd + toAdd;
}
}
void remove(int toRemove)
{
if (toRemove > 0) {
this->toRemove = this->toRemove + toRemove;
}
}
void deploy()
{
this->armies = this->armies + this->toAdd - this->toRemove;
this->toAdd = 0;
this->toRemove = 0;
}
int getRow()
{
return row;
}
int getCol()
{
return col;
}
int getArmies()
{
return armies;
}
int getAvaliableArmies()
{
return armies - 1 - toRemove;
}
int getToAdd()
{
return toAdd;
}
bool isToBeDefended()
{
return toAdd > 0;
}
Bonus getBonus()
{
if (bonus != nullptr) {
return *bonus;
}
return Bonus(-1, 1, 100);
}
Bonus *getBonusPtr()
{
return bonus;
}
bool isMine()
{
return allegiance == MINE;
}
bool isNPC()
{
return allegiance == NPC;
}
private:
/// Row number of this territory.
int row;
/// Column number of this territory.
int col;
/// The bonus that this territory is a part of.
Bonus* bonus;
/// number of armies contained in the territory.
int armies;
/// number of armies to add or send to the territory.
int toAdd;
/// number of armies to remove from this territory.
int toRemove;
/// Who this territory belongs to.
Allegiance allegiance;
};
/// Return whether Territory a is a neighbour of Territory b.
bool isNeighbour(Territory *a, Territory *b)
{
/*
n n n
n x n
n n n
*/
// A neighbouring territory is where either:
// row - 1 , col - 1
// row - 1 , col + 0
// row - 1 , col + 1
// row + 0 , col - 1
// row + 0 , col + 1
// row + 1 , col - 1
// row + 1 , col + 0
// row + 1 , col + 1
int rowA = a->getRow();
int colA = a->getCol();
int rowB = b->getRow();
int colB = b->getCol();
// The row and column is the same, so they're the same territory, but not neighbours.
if (rowA == rowB && colA == colB) {
return false;
}
// The difference of row : row and column : column is no more than 1.
// e.g. a territory at row 7 will have neighbour at row 6 and 8.
if (abs(rowA - rowB) <= 1 && abs(colA - colB) <= 1) {
return true;
}
// Special case for wrapping.
int checkRow = -1;
int checkCol = -1;
// Row is at 0. We need to check for 9 and 1.
// 1 is already covered by 0 - 1. Explicitly check the 0 - 9 case.
if (rowB == 0) {
checkRow = 9;
}
// Row is at 9. We need to check for 0 and 8.
// 8 is already covered by 9 - 9. Explicitly check the 9 - 0 case;
if (rowB == 9) {
checkRow = 0;
}
// Same thing for column
if (colB == 0) {
checkCol = 9;
}
if (colB == 9) {
checkCol = 0;
}
if ((rowA == checkRow && abs(colA - colB) <= 1) ||
(abs(rowA - rowB) <= 1 && colA == checkCol) ||
(rowA == checkRow && colA == checkCol)) {
return true;
}
return false;
}
/// Verify that territory has the correct allegiance.
bool isOfAllegiance(Territory *territory, Allegiance allegiance)
{
if (allegiance == MINE && territory->isMine()) {
return true;
}
else if (allegiance == ENEMY && !territory->isMine()) {
// Enemy means NOT mine, which includes NPCs.
return true;
}
else if (allegiance == HOSTILE && !territory->isMine() && !territory->isNPC()) {
// Specifically enemy PLAYERS.
return true;
}
else if (allegiance == NPC && territory->isNPC()) {
return true;
}
else if (allegiance == ANY) {
return true;
}
return false;
}
/// Return all neighbouring territories of a particular territory,
/// where the neighbouring territories fits the given allegiance.
set<Territory *> getNeighbours(Territory *territory, Allegiance allegiance, set<Territory *> territories)
{
set<Territory *> neighbours;
for (Territory *neighbour : territories) {
if (isNeighbour(neighbour, territory) && isOfAllegiance(neighbour, allegiance)) {
neighbours.insert(neighbour);
}
}
return neighbours;
}
/// Return the total number of armies near a particular territory that can be mobilized.
int getAvaliableArmiesNear(Territory *territory, Allegiance allegiance, set<Territory *> territories)
{
int armies = 0;
set<Territory *> neighbour = getNeighbours(territory, allegiance, territories);
for (Territory *near : neighbour) {
armies = armies + near->getAvaliableArmies();
}
return armies;
}
/// Return a set of all territories of a particular allegiance.
set<Territory *> getAllTerritories(Allegiance allegiance, set<Territory *> territories)
{
set<Territory *> t;
for (Territory *territory : territories) {
if (isOfAllegiance(territory, allegiance)) {
t.insert(territory);
}
}
return t;
}
/// Returns the priority of attacking this particular territory.
/// The lower the priority, the better. It is calculated based on
/// the number of territories left to claim a bonus, the number
/// of armies required to take it over, and the number of armies
/// getting this bonus will give us.
int calculateAttackPriority(Territory *territory)
{
Bonus bonus = territory->getBonus();
int territoriesLeft = bonus.getTerritoriesLeft();
int armiesNeeded = territory->conquerNeeded();
int armiesGiven = bonus.getArmies();
return (int)round(territoriesLeft * armiesNeeded / armiesGiven);
}
/// Return a map of int, Territories where int represent priority
/// and Territory is the territory to be attacked.
///
/// Higher priority = LESS important.
///
/// ALL territories that can be attacked will appear in the set.
map<int, Territory *> getAttackCandidates(set<Territory *> territories)
{
map<int, Territory *> attack;
set<Territory *> opponents = getAllTerritories(ENEMY, territories);
for (Territory *territory : opponents) {
int priority = calculateAttackPriority(territory);
// Check if the territory is already inserted.
auto findTerritory = attack.find(priority);
bool inserted = findTerritory != attack.end();
// Already inserted, so we decrease the priority until we can insert it.
while (inserted) {
priority = priority + 1;
findTerritory = attack.find(priority);
inserted = findTerritory != attack.end();
}
attack.insert({ priority, territory });
}
return attack;
}
/// Returns the priority of defending this particular territory.
/// The lower the priority, the better. It is calculated based on
/// whether or not we have this bonus, number of armies that can
/// potentially take it over, and the number of armies
/// getting this bonus will give us.
int calculateDefendPriority(Territory *territory, set<Territory *> territories)
{
Bonus bonus = territory->getBonus();
set<Territory *> enemies = getNeighbours(territory, ENEMY, territories);
int territoriesLeft = bonus.getTerritoriesLeft();
int armiesNeeded = territory->reinforceNeeded(getAvaliableArmiesNear(territory, HOSTILE, territories));
int armiesGiven = bonus.getArmies();
return (int)round((1 + territoriesLeft) * armiesNeeded / armiesGiven);
}
/// Return a map of int, pair<int, Territory> where int represent priority
/// and Territory is the territory to be defended.
///
/// Again, the higher the priority, the LESS important it is.
///
/// ALL territories that can be defended will appear in the set.
map<int, Territory *> getDefendCandidates(set<Territory *> territories)
{
map<int, Territory *> defend;
set<Territory *> mine = getAllTerritories(MINE, territories);
for (Territory *territory : mine) {
int priority = calculateDefendPriority(territory, territories);
// Check if the territory is already inserted.
auto findTerritory = defend.find(priority);
bool inserted = findTerritory != defend.end();
// Already inserted, so we decrease the priority until we can insert it.
while (inserted) {
priority = priority + 1;
findTerritory = defend.find(priority);
inserted = findTerritory != defend.end();
}
defend.insert({ priority, territory });
}
return defend;
}
/// Determine which territories to add armies to, and add to them accordingly.
/// Return a set which specifically lists the Territories that will have armies
/// added to them.
///
/// set<Territory> territories is a set of territories that are visible to us.
/// int armies is the number of armies we can add.
set<Territory *> getAdd(set<Territory *> territories, int armies)
{
set<Territory *> add;
// First we check whether there are any territories worth defending - i.e. we have bonus.
map<int, Territory *> defend = getDefendCandidates(territories);
for (auto pairs : defend) {
if (armies <= 0) {
break;
}
Territory *territory = pairs.second;
Bonus bonus = territory->getBonus();
int need = territory->reinforceNeeded(getAvaliableArmiesNear(territory, HOSTILE, territories));
// Make sure that we actually need to defend this, and it actually can be defended.
if (need > 0 && need <= armies + getAvaliableArmiesNear(territory, MINE, territories) + territory->getArmies()) {
if (need < armies) {
armies = armies - need;
territory->add(need);
add.insert(territory);
}
else {
// Do we really want to use up all our armies
// if it doen't even give us a bonus?
if (bonus.getTerritoriesLeft() != 0) {
continue;
}
territory->add(armies);
armies = 0;
add.insert(territory);
}
}
}
// Attacking is much easier. We simply allocate all the armies
// to a place beside where we wish to attack.
map<int, Territory *> attack = getAttackCandidates(territories);
for (auto pairs : attack) {
if (armies <= 0) {
break;
}
Territory *territory = pairs.second;
// Determine where to allocate.
set<Territory *> neighbours = getNeighbours(territory, MINE, territories);
// We'll just arbitrarily pick the first one that is an ally, though any one will work.
for (Territory *my : neighbours) {
// I am almost certain I messed up my logic somewhere around here.
// I'm supposed to initiate an attack if I got a good surround near a territory.
// However, it isn't working so I removed it and opted for a simpler logic.
// So far, it is doing well as is. If I start loosing I'll reimplement this ;)
//int need = territory->conquerNeeded() - getAvaliableArmiesNear(territory, MINE, territories);
int need = territory->conquerNeeded();
int a = territory->conquerNeeded();
int b = getAvaliableArmiesNear(territory, MINE, territories);
int c = my->getAvaliableArmies();
if (need <= 0) {
continue;
}
if (need < armies) {
armies = armies - need;
my->add(need);
add.insert(my);
}
else {
my->add(armies);
armies = 0;
add.insert(my);
}
break;
}
}
// Check if there are any armies left over,
// because we must add all our armies.
if (armies > 0) {
// This means that we are in a perfect position and it doesn't matter where we add it.
// So we'll just pick a random territory and put it there.
if (add.size() < 1) {
set<Territory *> mine = getAllTerritories(MINE, territories);
auto first = mine.begin();
Territory *random = *first;
random->add(armies);
add.insert(random);
}
else {
// In this case, we just throw it to the highest priority.
auto first = add.begin();
Territory *t = *first;
t->add(armies);
}
}
return add;
}
/// Return a set of set of Territories.
/// Each set have [0] as source and [1] as destination.
/// Number of armies to send will be in destination.
/// add is a list of territories with armies added to them.
set<pair<Territory *, Territory *>> getSend(set<Territory *> territories)
{
set<pair<Territory *, Territory *>> send;
// Attacking is much easier. We simply allocate all the armies
// to a place beside where we wish to attack.
map<int, Territory *> attack = getAttackCandidates(territories);
for (auto pairs : attack) {
Territory *territory = pairs.second;
int needed = territory->conquerNeeded();
set<Territory *> mine = getNeighbours(territory, MINE, territories);
// Find all our territories avaliable for attack.
for (Territory *my : mine) {
// We need to make sure we actually have enough!
int avaliable = my->getAvaliableArmies();
// We send all our attacking army from a single territory,
// So this one territory must have enough.
if (needed > 0 && avaliable >= needed) {
// Attack!
territory->add(needed); // represents number of armies to send.
my->remove(needed);
pair<Territory *, Territory *> attackOrder(my, territory); // src -> dst.
send.insert(attackOrder);
break;
}
}
}
// First we check whether there are any territories worth defending - i.e. we have bonus.
map<int, Territory *> defend = getDefendCandidates(territories);
for (auto pairs : defend) {
Territory *territory = pairs.second;
// Number of armies that will potentially attack.
int threat = getAvaliableArmiesNear(territory, HOSTILE, territories);
// The number of armies needed to reinforce this attack.
int needed = territory->reinforceNeeded(threat);
if (needed <= 0) {
continue;
}
// Check that we have enough to actually defend.
int avaliable = getAvaliableArmiesNear(territory, MINE, territories);
set<Territory *> neighbours = getNeighbours(territory, MINE, territories);
if (avaliable < needed) {
// Not enough, retreat!
for (Territory *my : neighbours) {
int retreat = territory->getAvaliableArmies();
if (retreat > 0) {
// Retreat!
// Remove from the territory in defense candidate.
territory->remove(retreat);
// Add to territory else where.
my->add(retreat);
pair<Territory *, Territory *> defendOrder(territory, my); // src -> dst.
send.insert(defendOrder);
}
// We retreat to a single territory.
// So we break as soon as we find a territory.
// If there is no territory, this loop won't run.
break;
}
}
else {
// Track how many we still need to add.
int stillneed = needed;
// Reinforce!
for (Territory *my : neighbours) {
// Do we need more?
if (stillneed <= 0) {
break;
}
// Check that it's not about to be reinforced.
// Otherwise, it is senseless to take armies away from a
// territory we intend to defend!
if (!my->isToBeDefended()) {
int canSend = my->getAvaliableArmies();
if (canSend > 0) {
// Reinforce!
// We create a copy of the territory when adding.
// Why? Because in this case, the destination Territory
// is only meant as a place holder territory simply
// for the purpose of having the toAdd value read.
Territory *territoryAdd = new Territory(territory);
territoryAdd->add(canSend);
// Remove from the territory we are sending from.
my->remove(canSend);
stillneed = stillneed - canSend;
pair<Territory *, Territory *> defendOrder(my, territoryAdd); // src -> dst.
send.insert(defendOrder);
}
}
}
}
}
return send;
}
/// Rules of Engagement:
/// 1. Collect Bonuses.
/// 2. Attack Weak Territories whenever possible.
///
/// Rules of Defense:
/// 1. Reinforce if possible.
/// 2. Otherwise, retreat and live to fight another day
///
/// For a given territory, we will prioritze attacking over
/// defending if we do not have the bonus yet for that territory.
/// If we have the bonus, we will prioritze defending over attacking.
int main(int argc, char* argv[])
{
// Note: cannot use stoi because of compilation problems.
int id = atoi(argv[1]);
int armies = atoi(argv[2]);
string territoriesIn = argv[3];
string bonusesIn = argv[4];
// First seperate by space, then seperate by comma.
vector<string> territoriesData = split(territoriesIn, ' ');
vector<string> bonusesData = split(bonusesIn, ' ');
set<Territory *> territories;
map<int, Bonus *> bonuses;
for (string data : bonusesData) {
// [id],[armies],[territories left]
vector<string> bonus = split(data, ',');
int id = atoi(bonus[0].c_str());
int armies = atoi(bonus[1].c_str());
int territoriesLeft = atoi(bonus[2].c_str());
Bonus *b = new Bonus(id, armies, territoriesLeft);
bonuses.insert({ id, b });
}
for (string data : territoriesData) {
// [row],[col],[bonus id],[player id],[armies]
vector<string> territory = split(data, ',');
int row = atoi(territory[0].c_str());
int col = atoi(territory[1].c_str());
int bonusId = atoi(territory[2].c_str());
int playerId = atoi(territory[3].c_str());
int armies = atoi(territory[4].c_str());
// We can assume that each territory always belongs to a bonus.
auto findBonus = bonuses.find(bonusId);
Bonus *bonus;
if (findBonus != bonuses.end()) {
bonus = findBonus->second;
}
else {
bonus = nullptr;
}
Allegiance allegiance = ENEMY;
if (playerId == id) {
allegiance = MINE;
}
else if (playerId == -1) {
allegiance = NPC;
}
Territory *t = new Territory(row, col, bonus, playerId, armies, allegiance);
territories.insert(t);
}
// Here we output our desire to add armies.
set<Territory *> add = getAdd(territories, armies);
string delimiter = "";
for (Territory *t : add) {
cout << delimiter << t->getRow() << "," << t->getCol() << "," << t->getToAdd();
delimiter = " ";
// Move added army to actual army.
t->deploy();
}
cout << endl;
// Here we output our desire to send armies.
set<pair<Territory *, Territory *>> send = getSend(territories);
delimiter = "";
// Note that if you do not want to move any armies, your program should print a space.
if (send.size() == 0) {
cout << " ";
}
else {
for (auto location : send) {
Territory *source = location.first;
Territory *destination = location.second;
cout << delimiter << source->getRow() << "," << source->getCol() << "," << destination->getRow() << "," << destination->getCol() << "," << destination->getToAdd();
delimiter = " ";
}
}
cout << endl;
return 0;
}
```
## Animated GIF
[](https://drive.google.com/uc?export=download&id=0B-BtKdd4FDDEbWlBckExLWREMmc)
**Archived:**
v2.1: <https://drive.google.com/uc?export=download&id=0B-BtKdd4FDDEU3lkNzVoTUpRTG8>
v1.0: <https://drive.google.com/uc?export=download&id=0B-BtKdd4FDDEVzZUUlFydXo2T00>
[Answer]
## LandGrab - Java
The more land the better. Targets exclusively free territories if there are any, then with the leftover armies begins building up and taking out the enemy one tile at a time.
```
import java.util.Arrays;
import java.util.LinkedList;
public class LandGrab {
public static void main(String[] args) {
//Init
int id = Integer.parseInt(args[0]);
int armies = Integer.parseInt(args[1]);
LinkedList<Territory> myTerritories = new LinkedList<Territory>();
LinkedList<Territory> enemyTerritories = new LinkedList<Territory>();
LinkedList<Territory> freeTerritories = new LinkedList<Territory>();
for (String s : args[2].split(" ")) {
Territory t = new Territory(s.split(","));
if (t.id == id)
myTerritories.add(t);
else if(t.id == -1)
freeTerritories.add(t);
else
enemyTerritories.add(t);
}
LinkedList<int[]> deploy = new LinkedList<int[]>();
LinkedList<int[]> move = new LinkedList<int[]>();
//Boost up territories next to free ones
for(Territory mine : myTerritories){
if(armies <= 0) break;
LinkedList<Territory> neighbors = getNeighbors(mine, freeTerritories);
int depArm = 0;
while(neighbors.peek() != null && armies * 0.6 >= neighbors.peek().armies){
Territory x = neighbors.pop();
int needed = x.armies * 2;
depArm += needed;
mine.armies += needed;
armies -= needed;
int[] temp = {mine.row, mine.col, x.row, x.col, needed};
move.add(temp);
}
int[] temp = {mine.row, mine.col, depArm};
if(depArm > 0) deploy.add(temp);
}
/* //Take any freebies we can
for(Territory mine : myTerritories){
LinkedList<Territory> neighbors = getNeighbors(mine, freeTerritories);
while(neighbors.peek() != null){
Territory x = neighbors.pop();
if((mine.armies - 1) > x.armies * 2){
int needed = x.armies * 2;
move += mine.row + "," + mine.col + "," + x.row + "," + x.col + "," + (needed) + " ";
mine.armies -= needed;
}
}
}
*/
//Choose a single enemy army and crush it
if(enemyTerritories.size() > 0 && armies > 0){
Territory x = enemyTerritories.pop();
Territory y = largest(getNeighbors(x, myTerritories));
int[] temp = {y.row, y.col, armies};
deploy.add(temp);
int armSize = y.armies + armies - 1;
if(armSize * 0.6 > x.armies){
int[] attack = {y.row, y.col, x.row, x.col, armSize};
move.add(attack);
}
armies = 0;
}
//Deploy leftover armies wherever
if(armies > 0){
Territory rand = myTerritories.getFirst();
int[] temp = {rand.row, rand.col, armies};
deploy.add(temp);
}
//Consolidate
String deployString = consolidate(deploy);
String moveString = "";
for(int[] command : move){
moveString += Arrays.toString(command).replace(" ", "").replace("[", "").replace("]", "") + " ";
}
if(moveString == "") moveString = " ";
//Return
System.out.println(deployString);
System.out.println(moveString);
}
private static Territory largest(LinkedList<Territory> l){
Territory largest = l.getFirst();
for(Territory t : l){
if(t.armies > largest.armies) largest = t;
}
return largest;
}
public static String consolidate(LinkedList<int[]> list){
LinkedList<int[]> combined = new LinkedList<int[]>();
for(int[] t : list){
boolean dup = false;
for(int[] existing : combined){
if(t[0] == existing[0] && t[1] == existing[1]){
existing[2] += t[2];
dup = true;
}
}
if(!dup) combined.add(t);
}
String result = "";
for(int[] dep : combined){
result += Arrays.toString(dep).replace(" ", "").replace("[", "").replace("]", "") + " ";
}
return result;
}
private static LinkedList<Territory> getNeighbors(Territory t, LinkedList<Territory> possibles){
LinkedList<Territory> neighbors = new LinkedList<Territory>();
for(Territory x : possibles){
if(Math.abs(x.row - t.row) <= 1 && Math.abs(x.col - t.col) <= 1){
neighbors.add(x);
}
}
return neighbors;
}
static class Territory {
int id, row, col, armies;
public Territory(String[] data) {
id = Integer.parseInt(data[3]);
row = Integer.parseInt(data[0]);
col = Integer.parseInt(data[1]);
armies = Integer.parseInt(data[4]);
}
}
}
```
[Answer]
## Random Halver - Java 8
A very simple bot that simply moves half its armies in each territory to a random neighbouring territory. Does not matter if the neighbour is friend or foe...
While it cannot compete with Castler, it does surprisingly well against the Player and other bots.
```
import java.util.*;
import java.util.stream.Collectors;
/**
* Sends half its force to a random territory around itself.
*/
public class RandomHalver {
private static final int MAP_SIZE = 10;
private int ownId;
private int deployableArmyCount;
private List<Territory> territories;
private Territory[][] map;
private Map<Territory,Territory> territoryHashMap;
List<Territory> ownedTerritories;
public int minRow;
public int minCol;
public static void main(String[] args)
{
new RandomHalver(args);
}
RandomHalver(String[] args)
{
ownId = Integer.parseInt(args[0]);
deployableArmyCount = Integer.parseInt(args[1]);
territories = new ArrayList<Territory>();
map = new Territory[MAP_SIZE][MAP_SIZE];
territoryHashMap = new HashMap<Territory,Territory>();
for (String s : args[2].split(" ")) {
Territory territory = new Territory(s.split(","));
territories.add(territory);
territoryHashMap.put(territory, territory);
map[territory.col][territory.row]=territory;
}
ownedTerritories = territories.stream().filter(t->t.id==ownId).collect(Collectors.toList());
List<Move> moves = new ArrayList<>();
ownedTerritories.stream().forEach(t->moves.add(new Move(t, getNeighbours(t,map).get(new Random().nextInt(getNeighbours(t,map).size())),t.armies/2)));
Map<Territory,Integer> deployTerritories = new HashMap<>();
deployTerritories.put(ownedTerritories.get(new Random().nextInt(ownedTerritories.size())),deployableArmyCount);
// send deploy command
StringBuilder sb = new StringBuilder();
deployTerritories.entrySet().stream().forEach(entry-> sb.append(entry.getKey().row + "," + entry.getKey().col + "," + entry.getValue()+" "));
sb.append(" ");
System.out.println(sb);
StringBuilder sb1 = new StringBuilder();
// send move command
moves.stream().filter(m->m.armies>0).forEach(move-> sb1.append(move.startTerritory.row + "," + move.startTerritory.col + "," + move.endTerritory.row + "," + move.endTerritory.col + "," + move.armies+" "));
sb1.append(" ");
System.out.println(sb1);
}
/**
* returns the neighbours of the provided territory using the provided map
*/
private List<Territory> getNeighbours(Territory territory,Territory[][] map) {
List<Territory> neighbours = new ArrayList<>();
for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
{
for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
{
if (!(x==MAP_SIZE && y==MAP_SIZE))
{
Territory t = map[(x+territory.col)%MAP_SIZE][(y+territory.row)%MAP_SIZE];
if (t!=null) neighbours.add(t);
}
}
}
return neighbours;
}
static class Battle {
public int minArmiesRequired;
Territory winner;
Territory loser;
boolean attackerWon;
}
static class Move
{
public Move(Territory startTerritory, Territory endTerritory, int armiesToSend)
{
this.endTerritory=endTerritory;
this.startTerritory=startTerritory;
this.armies=armiesToSend;
}
Territory startTerritory;
Territory endTerritory;
int armies;
}
static class Territory implements Cloneable
{
public int id, row, col, armies;
public Territory clone()
{
try {
return (Territory) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public Territory(String[] data) {
id = Integer.parseInt(data[3]);
row = Integer.parseInt(data[0]);
col = Integer.parseInt(data[1]);
armies = Integer.parseInt(data[4]);
}
void add(Territory territory)
{
row+=(territory.row);
col+=(territory.col);
}
@Override
public int hashCode()
{
return row*MAP_SIZE+col;
}
@Override
public boolean equals(Object other)
{
Territory otherTerritory = (Territory) other;
return row == otherTerritory.row && col == otherTerritory.col;
}
}
}
```
] |
[Question]
[
Write a program or function that "reacts" to a given integer *n* (input via function parameter/args/stdin)
The program doesn't care about negative numbers, likes even, dislikes odd numbers and fears the number 13.
It should output the following:
**if n<0:**
```
--------------------------
| |
| |
(| _ _ |)
| |
| |
| |
| |
| oooooooooo |
| |
| |
| |
--------------------------
```
**if n%2 == 0 and n>-1:**
```
--------------------------
| |
| |
(| ^ ^ |)
| |
| |
| |
| o o |
| oooooooooo |
| |
| |
| |
--------------------------
```
**if n%2 == 1 and n>-1 and n!=13:**
```
--------------------------
| |
| |
(| > < |)
| |
| |
| |
| |
| oooooooooo |
| o o |
| |
| |
--------------------------
```
**if n==13:**
```
--------------------------
| |
| |
(| (O) (O) |)
| |
| |
| oooooooooo |
| o o |
| oooooooooo |
| |
| |
| |
--------------------------
```
The shortest solution in bytes wins.
[Answer]
# CJam - 169
```
S24*aB*2li_D=3{_0<2{_2%}?}?\;:X"^^<>__":s"(O)"a2*+2/=~6X3=-{S*_@+_,C\-S*2*+@@++}:F~t7'o5*_7F:MtX3={5Mt6'o_7Ft}*X2<{X2*6+'o_5Ft}*{" |"\+'|+}%S'-26*+aa2*\*_3=1>"()"\*3\tN*
```
Try it at <http://cjam.aditsu.net/>
High-level explanation:
`S24*aB*` makes a matrix full of spaces, for the face without the edges
`li_D=3{_0<2{_2%}?}?\;:X` reads the number and converts it to 0 (even), 1 (odd), 2 (negative) or 3 (13), storing it in X
`X"^^<>__":s"(O)"a2*+2/=~` selects the eye types (2 strings)
`{S*_@+_,C\-S*2*+@@++}:F` - function F takes 2 strings (say S1, S2) and a number (say N) and makes a 24-char string containing N spaces, S2, other spaces, S1, N spaces
`2 (eyes) 6X3=- (F)~t` puts the eyes line in the matrix
`7'o5*_7F:Mt` puts the common mouth line in the matrix, and also saves it in M
`X3={5Mt6'o_7Ft}*` if X is 3, it puts M again in the matrix, 2 lines higher, and puts the mouth sides in between
`X2<{X2*6+'o_5Ft}*` if X is 0 or 1, it puts the mouth corners in the appropriate position
`{" |"\+'|+}%` adds vertical edges and a space on the left on every line
`S'-26*+aa2*\*` adds the horizontal edges
`_3=1>"()"\*3\t` adds the ears
`N*` adds newline separators
[Answer]
## Ruby, ~~241~~ 224
```
f=->n{s=" #{?-*26}
"
s+=" |#{' '*24}|
"*11+s
s[84]=?(
s[110]+=?)
s[233,12]=m=?O*12
s[91,3]=s[102,3]=n<0?' _ ':n==13?(s[177,12]=m;s[205]=s[216]=?O;'(O)'):(s[203+d=n%2*56]=s[218+d]=?O;" #{n%2<1??^:b=?>} ")
s[103]=?<if b
$><<s}
```
This defines a function to be called like `f[13]`. I'm sure there's a lot of room for improvement, similar what Ventero helped me do [here](https://codegolf.stackexchange.com/a/32971/8478).
Basically, I'm building the rough framework first, and attach ears as well as the mouth. Then I place the eyes depending on the number. While working out the characters to put into the eyes, I also take care of the different mouths so I don't have to check for the type of number again. Finally I need to fix the right eye for odd numbers, because the code above puts the same string into both eyes.
[Answer]
# C# - 349 bytes
Certainly not going to win any awards, but a different way of doing things.
Golfed:
```
class P{static void Main(string[]A){int j=64,i,r=0,n=int.Parse(A[0]);for(var f=(n<0?"IDID-TDTD-":n==13?"HDHD(IDIDOJDJD)SDSD(TDTDOUDUD)KIRI JHSJo":n%2<1?"IDID^TDTD^HIHIoUIUIo":"IDID>TDTD<HKHKoUKUKo")+@"JJSJoCBZM BB[M|BA[N-ADAD(\D\D)AA\N AA]N"+"\n";j++<78;)for(i=64;i++<93;System.Console.Write(f[r]))for(r=0;f[r++]>i|f[r++]>j|i>f[r++]|j>f[r++];r++);}}
```
Less golfed:
```
class P
{
static void Main(string[]A)
{
int j=64,i,r=0,n=int.Parse(A[0]); // everything is offset by 65 in this program
for(
var f=(n<0?"IDID-TDTD-": // this string describes a set of rectangles (x1,y1,x2,y2,ch)
n==13?"HDHD(IDIDOJDJD)SDSD(TDTDOUDUD)KIRI JHSJo":
n%2<1?"IDID^TDTD^HIHIoUIUIo":
"IDID>TDTD<HKHKoUKUKo"
)+@"JJSJoCBZM BB[M|BA[N-ADAD(\D\D)AA\N AA]N"+"\n";
j++<78;) // the loop then prints the rectangles to the screen
for(i=64;i++<93;System.Console.Write(f[r]))
for(r=0;f[r++]>i|f[r++]>j|i>f[r++]|j>f[r++];r++);
}
}
```
[Answer]
# Python 2 - 255
Not *really* short, but I'll post it anyway:
```
n=input()
o='o'
S=' '
w=y=7*S
b=' '+'-'*26+'\n'
p=' |%19s |\n'
E=p%y*2
v=S+o*10+S
u=z=o+6*S+o
A=a='^ '
if n%2:A='< ';a='> ';u=y;w=z
if n<0:A=a='_ ';u=w=y
if n==13:A=a='(O)';u=w=v;v=S+o+S*4+o+S
print b+E+'(|%8s%11s |)\n'%(a,A)+E+p%u+p%v+p%w+E+b
```
I miss item assignment for strings in Python! :(
Then one could start with the character matrix and simply modify eyes and mouth.
[Answer]
# Python 2, 257
Not a winner, but an alternate approach, got quite close! I have hope I can squeeze a few more chars out of it. Builds all the lines piece by piece, using common substrings to really squeeze out the bytes.
```
X,Z=R=" |"
Q=X*5
Y=X*7
A=X+"-"*26
B=R+X*24+Z
n=input()
a,b,c,d,e,f,g=((("^>^<o o "+Q)[n%2::2],"OO ()o")[n==13],"__"+Q)[n<0]
for F in(A,B,B,"(|"+Q+e+a+f+Y+X+e+b+f+Q+"|)",B,B,R+Y+g*10+Y+Z,R+Q+c+X+g+Y+X+g+X+c+Q+Z,R+Y+"o"*10+Y+Z,R+Q+d+Y+Q+d+Q+Z,B,B,A):print F
```
[Answer]
# CJam, 202
```
[S'-26*N]:Z[S'|:PS24*PN]:RR'(PS5*qi:XD=X0<-X2%2*+:Y[" ^ "_" > ""(O)"" - "__]=S8*Y[" ^ "" "" < ""(O)"" - "__]=S5*P')NRRXD=[SPS7*'oA*S7*PN]:QR?Y[[SPS5*'oSC*'oS5*PN]:T_R[SPS7*'oS8*'oS7*PN]RRR]=QY2=TR?RRZ
```
] |
[Question]
[
**The Problem**: Count the number of holes in a connected polygon. Connectivity of the polygon is guaranteed by the condition that every triangle in the input triangulation shares at least 1 side with another triangle and that there is only one such connected set of triangles.
Input is a list `L` of `n` points in the plane and a list `T` of 3-tuples with entries from `0...n-1`. For each item in `T` the tuple `(t_1,t_2,t_3)` represents the three vertices (from the list `L`) of a triangle in the triangulation. Note that this is a triangulation in the sense of ['polygon triangulation'](http://en.wikipedia.org/wiki/Polygon_triangulation), because of this there will never be two triangles in `T` that overlap. An additional stipulation is that you will not have to sanitize the input, `L` and `T` do not contain any repeats.
**Example 1**: If `L = {{0,0},{1,0},{0,1},{1,2}}` and `T = {{0,1,2},{1,2,3}}` then the polygon specified has a hole count of 0.

**Example 2**: If `L = {{0,0},{1,0},{2,0},{2,1},{2,2},{1,2},{0,2},{0,1},{.5,.5},{1.5,.5},{1.5,1.5},{.5,1.5}}` and `T = {{5,6,11},{5,10,11},{4,5,10},{3,8,10},{2,3,9},{2,8,9},{1,2,8},{0,1,8},{0,8,11},{0,7,11},{6,7,11},{3,4,10}}` then the polygon input should result in an output of 2.

The task is to write the shortest program (or function) that takes `L` and `T` as input and returns the number of holes. The 'winner' will be recognized as the entry with the least character count (tentative end date 1st of June).
Sample input formatting (note the 0 indexing):
```
0,0
1,0
0,1
1,2
0,1,2
1,2,3
```
[Answer]
## GolfScript (23 chars)
```
~.{2*2/~}%{$}%.&,@@+,-)
```
Assumes input format using GolfScript array notation and quoted (or integral) coordinates. E.g.
```
$ golfscript codegolf11738.gs <<<END
[["0" "0"] ["1" "0"] ["2" "0"] ["2" "1"] ["2" "2"] ["1" "2"] ["0" "2"] ["0" "1"] [".5" ".5"] ["1.5" ".5"] ["1.5" "1.5"] [".5" "1.5"]] [[5 6 11] [5 10 11] [4 5 10] [3 8 10] [2 3 9] [2 8 9] [1 2 8] [0 1 8] [0 8 11] [0 7 11] [6 7 11] [3 4 10]]
END
2
```
([Online equivalent](http://golfscript.apphb.com/?c=OydbWyIwIiAiMCJdIFsiMSIgIjAiXSBbIjIiICIwIl0gWyIyIiAiMSJdIFsiMiIgIjIiXSBbIjEiICIyIl0gWyIwIiAiMiJdIFsiMCIgIjEiXSBbIi41IiAiLjUiXSBbIjEuNSIgIi41Il0gWyIxLjUiICIxLjUiXSBbIi41IiAiMS41Il1dIFtbNSA2IDExXSBbNSAxMCAxMV0gWzQgNSAxMF0gWzMgOCAxMF0gWzIgMyA5XSBbMiA4IDldIFsxIDIgOF0gWzAgMSA4XSBbMCA4IDExXSBbMCA3IDExXSBbNiA3IDExXSBbMyA0IDEwXV0nCgp%2BLnsyKjIvfn0leyR9JS4mLEBAKywtKQ%3D%3D))
or
```
$ golfscript codegolf11738.gs <<<END
[[0 0] [1 0] [0 1] [1 2]] [[0 1 2] [1 2 3]]
END
0
```
([Online equivalent](http://golfscript.apphb.com/?c=OydbWzAgMF0gWzEgMF0gWzAgMV0gWzEgMl1dIFtbMCAxIDJdIFsxIDIgM11dJwoKfi57MioyL359JXskfSUuJixAQCssLSk%3D))
[Answer]
# Python, 71
What follows is a *program* (not a *function*) that calculates the desired number.
```
len(set().union(*(map(frozenset,zip(t,t[1:]+t))for t in T)))-len(L+T)+1
```
Example usage:
```
>>> L = ((0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,1),(.5,.5),(1.5,.5),(1.5,1.5),(.5,1.5))
>>> T = ((5,6,11),(5,10,11),(4,5,10),(3,8,10),(2,3,9),(2,8,9),(1,2,8),(0,1,8),(0,8,11),(0,7,11),(6,7,11),(3,4,10))
>>> len(set().union(*(map(frozenset,zip(t,t[1:]+t))for t in T)))-len(L+T)+1
2
```
[Answer]
## APL, 36
```
{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}
```
The function takes `L` as its left argument and `T` as its right.
For example:
```
L←(0 0)(1 0)(0 1)(1 2)
T←(0 1 2)(1 2 3)
L{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}T
0
L←(0 0)(1 0)(2 0)(2 1)(2 2)(1 2)(0 2)(0 1)(.5 .5)(1.5 .5)(1.5 1.5)(.5 1.5)
T←(5 6 11)(5 10 11)(4 5 10)(3 8 10)(2 3 9)(2 8 9)(1 2 8)(0 1 8)(0 8 11)(0 7 11)(6 7 11)(3 4 10)
L{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}T
2
```
---
Explanation, going from right to left:
* `⍴⍺,⍵` concatenates the two input vectors and returns their length (`V + F`)
* Stepping inside the next block:
+ `¨⍵` applies the function on the left to every element of the right argument and returns the result
+ `⍵,⍵` returns the right argument concatenated with itself
+ `3 2⍴` shapes the vector argument into three pairs. In this case it pairs together the first and second, third and first, and second and third items of the vector.
+ `,/` joins the vector argument together
+ `⍵[⍋⍵]` sorts the right argument
+ `∪/` filters out any duplicates
+ `⍴⊃` turns a nested scalar into a vector, and it returns the length of it.
+ The whole function returns the number of edges in the shape (`E`)
* `1` is self-explanatory (I hope...)
The whole function then returns `1+E-(V+F)`, or `1-(F+V-E)`.
[Answer]
## Mathematica, 93 (not much golfed yet)
```
f[l_, t_] := Max@MorphologicalComponents[Erosion[Graphics[
GraphicsComplex[l, Polygon[t + 1]]], 1]] - 1
```
(Spaces added for clarity)
Testing:
```
f[{{0, 0}, {1, 0}, {0, 1}, {1, 2}}, {{0, 1, 2}, {1, 2, 3}}]
(*
-> 0
*)
{l, t} = {{{0, 0}, {1, 0}, {2, 0}, {2, 1}, {2, 2}, {1, 2}, {0, 2},
{0, 1}, {.5, .5}, {1.5, .5}, {1.5, 1.5}, {.5, 1.5}},
{{5, 6, 11}, {5, 10, 11}, {4, 5, 10}, {3, 8, 10}, {2, 3, 9},
{2, 8, 9}, {1, 2, 8}, {0, 1, 8}, {0, 8, 11}, {0, 7, 11}, {6, 7, 11}, {3, 4, 10}}};
f[l, t]
(*
-> 2
*)
```
[Answer]
### Ruby, 239 characters (227 body)
```
def f t
e=t.flat_map{|x|x.permutation(2).to_a}.group_by{|x|x}.select{|_,x|x.one?}.keys
n=Hash[e]
(u,n=n,n.dup;e.map{|x|a,b=*x;n[a]=n[n[a]]=n[b]})until n==u
n.values.uniq.size+e.group_by(&:last).map{|_,x|x.size}.reduce(-1){|x,y|x+y/2-1}
end
```
note that I'm only considering the topology. I'm not using the vertex positions in any way.
caller (expects T in Mathematica or JSON format):
```
input = gets.chomp
input.gsub! "{", "["
input.gsub! "}", "]"
f eval(input)
```
Test:
```
f [[0,1,2],[1,2,3]]
#=> 0
f [[5, 6, 11], [5, 10, 11], [4, 5, 10], [3, 8, 10], [2, 3, 9], [2, 8, 9], [1, 2, 8], [0, 1, 8], [0, 8, 11], [0, 7, 11], [6, 7, 11], [3, 4, 10]]
#=> 2
f [[1,2,3],[3,4,5],[5,6,1],[2,3,4],[4,5,6],[6,1,2]]
#=> 1
```
[Answer]
# Mathematica 76 73 72 67 62
After much experimentation, I came to realize that the precise location of the vertices was of no concern, so I represented the problem with graphs. The essential invariants, the number of triangles, edges and vertices stayed invariant (provided line crossing was avoided).
There were two kinds of internal "triangles" in the graph: those were there was presumably a face, i.e. a "filled" triangle, and those where there were not. The number of internal faces did not have any relation to the edges or vertices. That meant that poking holes in fully "filled" graphs only reduced the number of faces. I played systematically with variations among triangles, keeping track of the faces, vertices and edges. Eventually I realized that the number of holes always was equal to 1 - #faces -#vertices + #edges. This turned out to be 1 minus the Euler characteristic (which I only had known about in the context of regular polyhedra (although the length of the edges was clearly of no importance.
The function below returns the number of holes when the vertices and triangles are input. Unlike my earlier submission, it does not rely on a scan of an image. You can think of it as 1 - Euler's characteristic, i.e. 1 - (F +V -E) where`F`= #faces, `V`=#vertices, `E`=#edges.
The function returns the number of holes, `1 - (F + V -E)`, given the actual faces (triangles) and vertices.
It can be easily shown that the removal of any triangle on the outside of the complex has no affect on the Euler characteristic, regardless of whether it shares one or 2 sides with other triangles.
Note: The lower case `v` will be used in place of the `L` from the original formulation; that is, it contains the vertices themselves (not V, the number of vertices)
`f` is used for the `T` from the original formulation; that is, it contains the triangles, represented as the ordered triple of vertex indices.
**Code**
```
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&
```
(Thanks to Mr. Wizard for shaving off 5 chars by eliminating the replacement rule.)
---
**Example 1**
v = {{0, 0}, {1, 0}, {0, 1}, {1, 2}};
f = {{0, 1, 2}, {1, 2, 3}};
```
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&[v, f]
```
>
> 0
>
>
>
Zero holes.
---
**Example 2**
v = {{0, 0}, {1, 0}, {2, 0}, {2, 1}, {2, 2}, {1, 2}, {0, 2}, {0,
1}, {.5, .5}, {1.5, .5}, {1.5, 1.5}, {.5, 1.5}};
f = {{5, 6, 11}, {5, 10, 11}, {4, 5, 10}, {3, 8, 10}, {2, 3, 9}, {2,
8, 9}, {1, 2, 8}, {0, 1, 8}, {0, 8, 11}, {0, 7, 11}, {6, 7,
11}, {3, 4, 10}};
```
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&[v, f]
```
>
> 2
>
>
>
Thus, 2 holes are in example 2.
[Answer]
### Python, 107
I realized that taking the pairs directly was shorter than `from itertools import*` and typing `combinations()`. Yet I also noticed that my solution relied on the input triangular faces having their vertices listed in consistent order. Therefore the gains in character count are not that large.
```
f=lambda l,t:1-len(l+t)+len(set([tuple(sorted(m))for n in[[i[:2],i[1:],[i[0],i[2]]]for i in t]for m in n]))
```
### Python, 115
Euler characteristic approach, the verbosity of itertools seems impossible to avoid. I wonder if it would be cheaper to use a more direct technique for making pairs of vertices.
```
from itertools import*
f=lambda l,t:1-len(l+t)+len(set([m for n in[list(combinations(i,2)) for i in t]for m in n]))
```
Usage example:
```
> f([[0,0],[1,0],[0,1],[1,2]],[[0,1,2],[1,2,3]])
> 0
> f([[0,0],[1,0],[2,0],[2,1],[2,2],[1,2],[0,2],[0,1],[.5,.5],[1.5,.5],[1.5,1.5],[.5,1.5]],[[5,6,11],[5,10,11],[4,5,10],[3,8,10],[2,3,9],[2,8,9],[1,2,8],[0,1,8],[0,8,11],[0,7,11],[6,7,11],[3,4,10]])
> 2
```
] |
[Question]
[
well, it's something similar to [this question](https://codegolf.stackexchange.com/questions/1570/) but with a little differences. you have to write a program to ask for width of progress bar and how much work is done. and then draw a progress bar with following features:
* width indicates how many characters you have to use to draw progress bar
* progress is given via a floating point value between 0..1.
* first and last character in progress bar should be something different from all other character, for example "[" and "]"
* your program should use two different characters to how much progress passed since the start
* you have to write how much work is done right in the middle of progress bar, using a decimal number + "%" sign.
**bonus point** for handling extreme inputs, such as 150% or -5% work done.
**scoring** number of characters \* (1 without bonus or 0.75 width bonus)
**some examples of valid outputs**
```
79 0.15
[|||||||||||| 15% ]
```
---
```
25 0.76
[##########76%#####.....]
```
---
```
39 -0.12
[ -12% ]
```
---
```
25 7.6
[##########760%#########]
```
[Answer]
# J, 78×0.75 = 58.5
```
'w p'=:_".1!:1]3
1!:2&4('%',~":100*p)(i.@[-<.@-:@-)&#}'[]'0 _1}' |'{~(w*p)>i.w
```
```
$ echo -n 79 0.15 | jconsole test.ijs
[||||||||||| 15% ]
$ echo -n 25 0.76 | jconsole test.ijs
[||||||||||76%||||| ]
$ echo -n 39 -0.12
[ _12% ]
$ echo -n 25 7.6 | jconsole test.ijs
[|||||||||760%||||||||||]
```
(Negative numbers in J are prefixed by `_`, not `-`. Luckily, dyadic `".` can parse both formats.)
[Answer]
## PHP 84 x 0.75 = 63
Edit: A less 'pretty' version, but it should be valid according to the rules:
```
[<?=str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,_,2)?>]
```
Output:
```
$ echo 79 0.15 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂___________________________15%______________________________________]
$ echo 25 0.76 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂76%⌂⌂⌂⌂⌂______]
$ echo 39 -0.12 | php progress-bar.php
[_________________-12%__________________]
$ echo 25 7.6 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂760%⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂]
```
### Original (98 x 0.75 = 73.5)
```
[<?=strtr(str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,~ü,2),~ü,~ß)?>]
```
Output:
```
$ echo 79 0.15 | php progress-bar.php
[########### 15% ]
$ echo 25 0.76 | php progress-bar.php
[###########76%##### ]
$ echo 39 -0.12 | php progress-bar.php
[ -12% ]
$ echo 25 7.6 | php progress-bar.php
[##########760%###########]
```
[Answer]
# Perl, 96×¾ = 72
```
#!/usr/bin/perl -ap
formline'[@'.'|'x($F[0]-3).']',100*$F[1].'%';
$_=$^A;s# |(.)#$1//($-[0]<$F[0]*$F[1]?'|':$&)#eg
```
That's by traditional Perl golf rules (`#!` line not counted, except for the `-` and switches if any).
```
$ echo 79 0.15 | perl test.pl
[||||||||||| 15% ]
$ echo 25 0.76 | perl test.pl
[||||||||||76%||||| ]
$ echo 39 -0.12 | perl test.pl
[ -12% ]
$ echo 25 7.6 | perl test.pl
[|||||||||760%||||||||||]
```
[Answer]
### Ruby - score 93 (124 characters)
```
w=gets.to_i-2
f=$_[/ .+/].to_f
e=f<0?0:f>1?w:(f*w).to_i
b='#'*e+' '*(w-e)
b[(w-l=(s='%d%'%(100*f)).size)/2,l]=s
puts"[#{b}]"
```
Yet another ruby implementation. Reads input from STDIN in the form described above. You may exchange characters `'#'`, `' '` and `'['`, `']'` directly in the code.
```
45 0.88
[####################88%############## ]
60 1.22
[###########################122%###########################]
```
[Answer]
## Python - 158 155 148 143 138 characters (score of 103.5)
```
x,y=raw_input().split()
x=int(x)-2
y=float(y)
p=`int(y*100)`+"%"
b="|"*int(x*y+.5)+" "*x
print"["+b[:(x-len(p))/2]+p+b[(x+len(p))/2:x]+"]"
```
It could be 30 characters shorter if the input was separated by a comma.
[Answer]
# Q,90 chars, no bonus
```
{-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}
```
usage
```
q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[50;0.15]
[||||||| 15% ]
q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[30;0.35]
[|||||||||| 35% ]
q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[40;0.85]
[|||||||||||||||||||85%|||||||||||| ]
```
[Answer]
### Scala 149:
```
val w=readInt
val p=readFloat
println(("["+"|"*(p*w).toInt+" "*((w-p*w).toInt)+"]").replaceAll("(^.{"+(w/2-3)+"}).{5}","$1 "+(p*100).toInt+("% ")))
```
ungolfed:
```
def progressbar (width: Int, pos: Double) {
println ((
"["+
"|"*(pos*width).toInt+
" "*((width-pos*width).toInt)+
"]").
replaceAll ("(^.{" + (width/2-3) + "}).{5}", "$1 " + (p * 100).toInt + ("% ")))}
}
```
I decided, for readability, you really need a space around the progress number:
```
(44 to 54).map (x => b (100, x/100.0))
[|||||||||||||||||||||||||||||||||||||||||||| 44% ]
[||||||||||||||||||||||||||||||||||||||||||||| 45% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 46% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 47% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 48% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 49% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 50% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 51% ]
[|||||||||||||||||||||||||||||||||||||||||||||| 52% | ]
[|||||||||||||||||||||||||||||||||||||||||||||| 53% || ]
[|||||||||||||||||||||||||||||||||||||||||||||| 54% ||| ]
```
[Answer]
## C, 145 characters, score = 108.75
```
float p;s;m;char x[99];main(){scanf("%d%f",&s,&p);sprintf(x+s/2-1,"%.0f%%",p*100);for(;m<s;)x[++m]||(x[m]=m<p*s?35:32);x[s-1]=93;*x=91;puts(x);}
```
[Answer]
## JavaScript ~~127~~ 125, no bonus
```
l=9,p="0.99",f=l*p|0,m=l/2|0,x=["]"];for(;l--;)x.unshift(l>=f?"-":"+");x[m++]=p[2],x[m++]=p[3],x[m]="%";alert("["+x.join(""))
//[+++99%++-]
```
**Usage:** Change `l=9` with other *length* and/or change `p="0.99"` with other *percent*
**Note:** end with zero `0.X0` instead of `0.X`
[Answer]
node.js: 135chars, \*0.75 for bonus points, so 101.25chars.
```
a=process.argv,i=a[2],p=a[3],o=i/2|0,f=i-i*p,x=['['];for(;i--;){x.push((i<f?' ':'|')+(i-o?'':p*100+'%'));}console.log(x.join('')+']');
```
ungolfed:
```
a = process.argv, // console inputs
i = a[2], // input 1 -> width
p = a[3], // input 2 -> percent complete
o = i / 2 | 0, // half of i, without any decimal places
f = i - i * p, // how far along the bar to draw spaces
x = ['[']; // start an array
while(i--){ // while i > 0
x.push( // add to the array
(i < f ? ' ' : '|') // a space, or | depending on how far along the bar we are
+ (i - o ? '' : p * 100 + '%')); // and if we're halfway, add the percentage complete
}
console.log(x.join('') + ']'); // then write out the array as a string, with a trailing ]
```
output:
```
D:\mercurial\golf\ascii>node progressBar.js 25 7.6
[|||||||||||||760%||||||||||||]
D:\mercurial\golf\ascii>node progressBar.js 39 -0.12
[ -12% ]
D:\mercurial\golf\ascii>node progressBar.js 79 0.15
[||||||||||| 15% ]
```
[Answer]
## PHP-128x0.75=>96
```
<?fscanf(STDIN,'%d%d',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*($i+=2)/$i.'%':(($i<$w*$p/100)?'|':' ');echo"$v]";?>
```
```
<?fscanf(STDIN,'%d%f',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*100*($i+=2)/$i.'%':(($i<$w*$p)?'|':' ');echo"$v]";?>
```
## C, 149\*0.75=111.75
```
main(w,i){float p;for(i=printf("[",scanf("%d%f",&w,&p));i<w-1;)(i++==w/2-1)?printf("%.0f%%",p*100*(i+=2)/i):printf("%c",i<=(p*w)?'|':' ');puts("]");}
```
Output:
```
80
0.75
[||||||||||||||||||||||||||||||||||||||75%|||||||||||||||||| ]
80
7.60
[||||||||||||||||||||||||||||||||||||||760%|||||||||||||||||||||||||||||||||||||]
80
-0.12
[ -12% ]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), score 35.25 (47 \* 0.75)
```
qqtl&O61bti*Xl:(HG100*V37hyn2/kyny+q&:(91w93v!c
```
[Try it online!](https://tio.run/##FchNC4IwGADg@37F2yERI3OKjnkO2i2ECI@ZKMrm/Nhrtl@/7PTAM1So3MvNMyrvntE39kGpcl/caBQFz4R1VscXabU9zV7uc7rx5HOonSiKUnzhCF1VS8ARhko20CNs4yKhHRcYVoX9pPbU04qAjUEwDRpyfTjGSRTSlMTpLstIwsl5j/gfLMx@ "MATL – Try It Online")
### Explanation:
```
% implicit input, say w = 79
qq % decrement input by 2 (to allow brackets on either side)
tl&O % duplicate and create array with that many zeros
61 % Push '=' character
b % bubble up w-2 from below
ti* % duplicate and multiply by second input, say p = 0.15
% stack: [[0;0;0;...;0], 61, 77, 11.55]
Xl % take minimum of (w-2) and (w-2)*p
% (used when p > 1, makes eligible for bonus)
: % create range 1 to that value
% stack: [[0;0;0;...;0], 61, [1 2 3 4 5 ... 11]]
( % assign into the first array the value 61 ('=') at the
% indices denoted by the third array
HG % push second input again
100*V % multiply by 100 and convert to string
37h % append the '%' symbol to it
yn2/k % compute half of the length of the output array
yny+q % copy of that + length of the 'N%' string - 1
% stack: [[61;61;61;...;0;0;0], '15%', 38, 40]
&: % make a range from the first to the second (38 to 40)
( % assign the 'N%' string at those places into the output array
91w93 % surround by '[' (ASCII 91) and ']' (93) characters
v! % combine into a single array, make it horizontal for display,
c % change it to character type (implicitly displayed)
```
[Answer]
# Excel VBA, 108\*.75 = 81 bytes
A function that takes input from `[A1]` and `[B1]` and outputs to the console
```
s=""&[MID(IFERROR(REPT("",A1*B1),"")&REPT("",A1),2,A1-2)]&"":n=100*[B1]:Mid(s,([A1]-len(n))/2)=n &"%":?s
```
### Output
with input `[A1]=25` and `[B1]=.76`
```
76%
```
With input `[A1:B1].Resize(1,2)=Split("32 -.5")`
```
-50%
```
With input `[A1:B1].Resize(1,2)=Split("40 10.01")`
```
1001%
```
] |
[Question]
[
Given a square of positive, natural numbers write a program find a horizontal and a vertical path with the sum of numbers along them being maximal. A *horizontal* path goes from the first column to the last and has to increase its column position by one in each step. A *vertical* path goes from the first row to the last and has to increase its row position by one in each step. Furthermore the row position in a *horizontal* path may stay the same or change by one in either direction, likewise for vertical paths.
To illustrate, the following could be a valid path:

The following path would be invalid, since it steps backwards (and remains on the same row in some places):

The following path would be equally invalid, since it changes the row position by more than one in a single step:

*Note: The solution should run in an acceptable amount of time.*
**Input**
*n* lines of input with *n* space-separated positive integers each are given on standard input. 2 ≤ *n* ≤ 40. Every line is terminated by a line break. The numbers are small enough that the maximum sum fits in a 32-bit signed integer.
**Output**
The maximum sums of the horizontal and vertical paths (in that order) separated by a single space.
**Sample input 1**
```
1 2
1 2
```
**Sample output 1**
```
3 4
```
**Sample input 2**
```
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 1 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 4 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 4 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
```
**Sample output 2**
```
37 35
```
**Sample input 3**
```
683 671 420 311 800 936
815 816 123 142 19 831
715 588 622 491 95 166
885 126 262 900 393 898
701 618 956 865 199 537
226 116 313 822 661 214
```
**Sample output 3**
```
4650 4799
```
---
For your convenience we have prepared a few test cases in [bash](http://hypftier.de/dump/CG1720/test) (thanks to [Ventero](https://codegolf.stackexchange.com/users/84/ventero)) and [PowerShell](http://hypftier.de/dump/CG1720/test.ps1) which you can run your program through. Invocation is: `<test> <command line>`, so something like `./test python paths.py` or `./test.ps1 paths.exe`. Have fun :-)
[Answer]
## GolfScript - 49 Nabb enhanced characters
51 characters
50 strictly and utterly necessary characters + 3 slackers that only did the job of 1
56 mostly redundant characters
```
n%{~]}%.zip{{0@+\{\.1>\3<$-1=@+}%\;}*$-1=\}2*' '@
```
51 solution:
```
n%{~]}%.zip{(\{0@+\{\.1>\3<$-1=@+}%\}%;$-1=\}2*' '@
```
53 solution:
```
n/{~]}%);.zip{(\{0@+\{\.1>\3<$-1=@+}%\}%;$-1=\}2*' '@
a8_b9___c10___11______12 13 14_
```
The method works on two lines at a time, one containing the maximum sums reached at each point, and one containing the next line.
a/14: Repeat twice, once for each result.
8: Take the first line from the input and switch it behind the input array, this in now the first set of maximum sums.
b/13: Iterate over each remaining line in the array.
9: Put 0 at the beginning of the maximum sums.
c/12: Iterate over each element of the line.
10: Make a copy of the maximum sums with the first element removed.
11: Take the first 3 elements of the maximum sums, sort them and add the largest to the current element of the line.
56 solution:
```
n/{~]}%);.zip{1,99*\{{\.1>\3<$-1=@+}%0\+\}%;$-1=\}2*' '@
1________2___ 3____ 4______________________5_____ 6_7___
```
1: From input to array of arrays in 9 characters, actually it could have been done with just 1, but I broke that key so this will have to do.
2: 4 characters just to make a transposed copy.
3: Array of 99 0s in 5 characters, it could probably be done in a way smarter fashion, but I smoke too much weed to figure how.
4: Overly complicated double loop that iterate over every single element of the input and does some fuzzy logic or something like that to produce the result. Nabb will probably make something equivalent in around 3½ characters.
5: By now the result is there, inside an array that is, this silly piece of code is just there to get it out (and junk a piece of leftovers (and switch the result into place)).
6: This is a command so simple that its character count would probably be negative in an optimal solution.
7: At this point the program is really done, but due to sloppiness in the preceding code the output is in the wrong order and lacks a space, so here goes a few more bits down the drain.
[Answer]
# J, 91 95
```
a=:".;._2(1!:1)3
c=:4 :'>./x+"1|:y,.(1|.!.0 y),._1|.!.0 y'
p=:[:>./c/
(":(p|:a),p a)1!:2(4)
```
I decline to do IO, lowering my score dramatically. Passes all tests in the test harness (though it *only* works if the input ends with a line ending, as in the test harness).
I removed the handling for Windows line endings, since Chris suggested that it wasn't necessary. The multi-platform version would have `a=:".;._2 toJ(1!:1)3` as the first line.
Explanation:
* `f` gives the solution pair by calling p normally and with input transposed (`|:`).
* `p` takes the maximum (`>./`) of the row-totals from applying `c` between each row (`c/`)
* `c` takes two rows (x and y). It adds x to each of y, y shifted up 1 cell (`1|.!.0 y`), and y shifted down 1 cell (`_1|.!.0 y`). Then it takes the maximums of the three alternatives for each row. (`>./`). The rest is rank [sic] - I'm not sure if I'm doing it right.
[Answer]
# Haskell: 314 necessary characters
```
import Data.Vector(fromList,generate,(!))
import List
l=fromList
x=maximum
g=generate
p a=show$x[m!i!0|i<-[0..h-1]]where{
w=length$head a;h=length$a;n=l$map l a;
m=g h$ \i->g w$ \j->n!i!j+x[k#(j+1)|k<-[i-1..i+1]];
i#j|i<0||i>=h||j>=w=0|1>0=m!i!j;}
q a=p a++' ':(p.transpose)a
main=interact$q.map(map read.words).lines
```
Note: this requires the module [Data.Vector](http://hackage.haskell.org/package/vector). I'm not sure if it's included in the Haskell platform or not.
Ungolfed version:
```
import Data.Vector(fromList,generate,(!))
import Data.List
-- horizontal; we use transpose for the vertical case
max_path :: [[Integer]] -> Integer
max_path numbers = maximum [m ! i ! 0 | i <- [0..h-1]] where
w = length (head numbers)
h = length numbers
n = fromList $ map fromList numbers
m = generate h $ \i -> generate w $ \j ->
n ! i ! j + maximum [f i' (j+1) | i' <- [i-1..i+1]]
f i j | i < 0 || i >= h || j >= w = 0
f i j = m ! i ! j
max_paths :: [[Integer]] -> String
max_paths numbers = (show . max_path) numbers ++ " " ++
(show . max_path . transpose) numbers
main = interact $ max_paths . map (map read . words) . lines
```
This solution uses laziness, in tandem with [Data.Vector](http://hackage.haskell.org/package/vector), for memoization. For every point, the solution for the maximum path from it to the end is computed, then stored in the cell of Vector `m` and reused when needed.
[Answer]
# Python, 149
```
import sys
def f(g,t=[]):
for r in g:t=[int(e)+max(t[i-1:i+2]+[0])for i,e in enumerate(r)]
print max(t),
g=map(str.split,sys.stdin)
f(zip(*g)),f(g)
```
If I were to calculate only a vertical or horizontal shortest path,
it could be done in-place instead, saving about a third of the bytes.
[Answer]
# Ruby 1.9, 155 characters
```
f=->t{(1...l=t.size).map{|a|l.times{|b|t[a][b]+=t[a-1][(b>0?b-1:0)..b+1].max}};t[-1].max};q=[*$<].map{|a|a.split.map &:to_i};puts [f[q.transpose],f[q]]*" ""
```
Straightforward solution that passes all testcases.
[Answer]
# Haskell, 154 characters
```
import List
z=zipWith
f=show.maximum.foldl1(\a->z(+)$z max(tail a++[0])$z max(0:a)a)
q a=f(transpose a)++' ':f a
main=interact$q.map(map read.words).lines
```
---
* Edit: (155 -> 154) inlined the function folded over
[Answer]
## J, 109+10= 119 chars
```
y=:0".(1!:1)3
N=:%:#y
y=:y$~N,N
r=:(((1&{)(+(3>./\0,0,~]))(0&{)),2&}.)^:(<:N)
(":([:>./"1([:r|:),r)y)(1!:2)4
```
Run with `tr`:
```
cat << EOF | tr \\n ' ' | ./maxpath.ijs
```
As usual in J, most of the code is for input/output. The "actual" code is 65 characters:
```
r=:(((1&{)(+(3>./\0,0,~]))(0&{)),2&}.)^:(<:#y)
([:>./"1([:r|:),r)y
```
*Passes all test cases*
[Answer]
# Python, 204 characters
```
import sys
I=sys.stdin.read()
n=I.count('\n')
A=map(int,I.split())
R=range(n)
X=lambda h,a:[a[i]+max(([0]+h)[i:i+3])for i in R]
h=v=[0]*n
for i in R:h=X(h,A[i*n:i*n+n]);v=X(v,A[i::n])
print max(v),max(h)
```
] |
[Question]
[
You want to send an ASCII letter to someone, but you need an envelope to put it in. Your task is to output an envelope given a size as input.
Rules:
* Given positive integer input `i`, your envelope will be `i` characters tall (not counting the top row), and `i*2` characters wide (not counting the side columns). In other words, your envelope will be `i+1` characters tall and `(i*2)+2` characters wide.
* Output **must** be in the form of text, using `\`, `/`, `_`, `|`, and .
* The flap of the envelope must be on the row above the bottom row of the envelope unless impossible (as with an envelope of size 1).
* Trailing whitespace is allowed.
Example input and output:
```
1
->
__
|\/|
2
->
____
|\__/|
|____|
3
->
______
|\ /|
| \__/ |
|______|
4
->
________
|\ /|
| \ / |
| \__/ |
|________|
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
i'_„|\‚ë2ÊiÍFðI×'\Nǝ}}„\_Ij¤Iש)'|쮚}º.c
```
[Try it online](https://tio.run/##yy9OTMpM/f8/Uz3@UcO8mphHDbMOrzY63JV5uNft8AbPw9PVY/yOz62tBUrGxHtmHVoCFDq0UlO95vCaQ@uOLqw9tEsv@f9/EwA) or [verify the first few outputs](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO@nw6XkX1oC4en4uYT@z1SPf9QwrybmUcOsw6v9jA53Zfod7nU7vCHi8HT1GL/jc2trgdIx8RFZh5YAhQ6t1FSvObzm0LqjC2sP7dJL/q9zaJv9fwA).
**Expanation:**
```
i # If the (implicit) input is 1:
'|„|\‚ '# Push pair of strings ["_","|\"]
ë # Else:
2Êi # If the (implicit) input is NOT 2:
ÍF # Loop `N` in the range [0,input-2):
ðI× # Push a string with the input amount of spaces
'\Nǝ '# Insert a "\" character at index `N`
} # Close the loop
} # Close the inner if-statement
„\_ # Push string "\_"
Ij # Pad leading spaces until the string is of a length equal to the input
¤ # Push the last character (without popping): "_"
I× # Repeat it the input amount of times as string
© # Store it in variable `®` (without popping)
) # Wrap all values on the stack into a list
'|ì '# Prepend a "|" in front of each string
®š # Prepend string `®` to the list
} # Close the outer if-else statement
º # Mirror each inner string
.c # Join by newlines and centralize
# (adding a single leading space to the first "_"-string)
# (after which the result is output implicitly)
```
[Answer]
# Python 3, ~~207~~ ~~181~~ ~~180~~ ~~177~~ ~~146~~ 130 bytes
```
lambda i,u="__",b=" ":b+u*i+"".join(f"\n|{b*x}\{(b*(i*2+~x*2),u)[x==i-2]}/{b*x}|"for x in range(i-1))+("\n|\/|",f"\n|{u*i}|")[i>1]
```
[Try it online!](https://tio.run/##TczdCoIwGIDh865ifEf7M3F2FKwbcSKOWn1hU0RhoXbry4rAs/fg4e2ew631eXTaxKZ@2HNNUI4aqgqk1UDgaMXIUQDs7y166sD4ebI8LGaillPkSrwCV0yOrAhaY6LKJf2CGVzbk0DQk7721wvFJGNM0M/BpDPI32u9r5QVeMrK2PXoB@roCnf/VpvON31gLL4B "Python 3 – Try It Online")
**To 181 bytes:** Golfed the code even more thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
**To 180 bytes:** -1 bytes thanks again to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), by replacing the `i!=1` with `i<2`.
**To 177 bytes:** Moved the whole "nonsense soup" line onto the same line as the `for` loop, thanks to [@des54321](https://codegolf.stackexchange.com/users/111305/des54321)'s suggestion.
**To 146 bytes:** Some *major* byte-saving golfs thanks to [@ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro).
**To 130 bytes:** More golfs by [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), including replacing `\\` with `\`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 49 bytes
```
1=[\_‛|\"|2≠[⇩ʁ(⁰Ifn\\Ȧ¤j)]‛\_⁰r:t⁰ẋ:£W\|vp¥p]vøṀ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiMT1bXFxf4oCbfFxcXCJ8MuKJoFvih6nKgSjigbBJZm5cXFxcyKbCpGopXeKAm1xcX+KBsHI6dOKBsOG6izrCo1dcXHx2cMKlcF12w7jhuYAiLCIiLCI0Il0=)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
Nθ←×_θ↑θ→P×_θ↓¿⊖θ«↘⊖θ←¶_»\‖M
```
[Try it online!](https://tio.run/##XY4xD4IwFIRn@yuaTm2CmxNdWUyEGKIbCcH6kCalhVJwMP72SsFownh337t3oqmsMJXy/qi70WVjewNLe8bR2UrtaHyC2kX4IlsYKClJhHv2D69d0BylZgIa5/LRuKBG5WS3ENu7FUzMU89C1pgmICy0oB3c568Mv9Du2x2gpTHCG4j/mHUcKXRJZveNQA2A14wURfByqBUIl0prjaWMe3/w@0l9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `i`.
```
←×_θ
```
Draw half of the bottom row of `_`s.
```
↑θ
```
Draw the left column of `|`s.
```
→P×_θ↓
```
Draw the top row of `_`s.
```
¿⊖θ«
```
If `i` is not `1`, then...
```
↘⊖θ←¶_
```
... draw the `i-1` `\`s on the left and one of the two middle `_`s, ...
```
»\
```
... otherwise overwrite the bottom `_` with a `\`.
```
‖M
```
Reflect to complete the envelope.
[Answer]
# [Javascript](https://www.javascript.com/), 181 177 174 Bytes
Code is split into newlines for readability, see link for 174 byte string.
```
c=n=>{
r=(d,n)=>d.repeat(n);
z='\n|';
b=r('_',n*2);
o=' '+b;
for(e=0;e<n-1;e++)y=r(' ',e),o+=z+y+'\\'+r(e!=n-2?' ':'_',n*2-2*(e+1))+'/'+y+'|';
o+=(n==1?z+'\\/|':z+b+'|');
return o;}
```
[Try me online.](https://ato.pxeger.com/run?1=NY89bsJAEIXrcIpNNbuMDbELhBgGLmIpiu0BWbJm0cYUGHKSNBTQ5j65TXYlp37f-_t-qG_lfn-eh0O-_v1pWHl3DWzbTB3v2kWQk3wMVh2NDJXegGoOFt4h03npyDMYwJoOPljhN5Kt5gUJorskzEAmLvPII14QqgowYq-sebmP2maKycu5FSycQ1hCAmNL9FhlLvZj8i1vsBmxToqjIMM5qPH0Na1ep_ZeBtMZNgWZbssr6uKG6-yl8frpe1n0_mgb2zmDJt6oNObMJv__-z8)
* Saved 4 bytes pulling `\n|` into a variable `z`
* Saved 3 bytes pulling `r(' ',e)` into `y` every loop
I'm not too happy with my performance here, especially the implicit check I had to do to get the i=1 output working, but oh well.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 37 bytes
```
\_*:£ðpm,ċ[ɽ‹\\꘍ṫ\_+J↲¥J\|vpvøṀ⁋|‛|\m
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJvIiwiIiwiXFxfKjrCo8OwcG0sxItbyb3igLlcXFxc6piN4bmrXFxfK0rihrLCpUpcXHx2cHbDuOG5gOKBi3zigJt8XFxtIiwiIiwiNCJd)
```
\_* # <input> copies of _
:£ # Duplicate and set gregister
ðpm, # Prepend a space and print mirrored
ċ[ |‛|\m # If it's 1, print `|\/|`, else:
ɽ‹ # 0...n-1
\\꘍ # For each, prepend that many spaces to an underscore
ṫ J # To the last...
\_+ # Append an underscore
↲ # Pad all of that to length n
¥J # Append the underscores that we stored in the register earlier
\|vp # Prepend a | to each
vøṀ⁋ # Mirror and print
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 107 bytes
```
lambda n:[' '+(a:="__"*n)]+['|%s|'%[a," "*i+f'\{"_ "[i<n-2]*2*(n+~i)}/'+" "*i][i<n-(n>2)]for i in range(n)]
```
[Try it online!](https://tio.run/##TczNCsIwEATgu08RAmU3iT/YXqRYXyQNJaLRFd2W2ItYffVYKoi3YeZjukd/brnYdDGFqk5Xf9sfvODSggCDvqxk00jNyhkLQ3YfILN@LoXUZALUT9kIaWnLi9zpXCObN6nXCswk3LQg73LlQhsFCWIRPZ@OOB6mLhL3CDXD8tISY8BCKTWbfftf@AfrEaQP "Python 3.8 (pre-release) – Try It Online")
-20 by @emanresuA
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0 -a`, 98 bytes
```
say$".__ x$_,map{'
|',/@F/*($#a=$_-1)?__ x$_.'|':"@a\\".($_<"@F"-1?' ':__)x("@F"-$_)."/@a|"}1..$_
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5JFwiLl9fIHgkXyxtYXB7J1xufCcsL0BGLyooJCNhPSRfLTEpP19fIHgkXy4nfCc6XCJAYVxcXFxcIi4oJF88XCJARlwiLTE/JyAgJzpfXyl4KFwiQEZcIi0kXykuXCIvQGF8XCJ9MS4uJF8iLCJhcmdzIjoiLU01LjEwLjBcbi1hIiwiaW5wdXQiOiIxXG4yXG4zXG40XG4xMFxuMTEifQ==)
Currently on mobile (in a rainy field!) so I'll add an explanation later!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 68 bytes
```
ð'_IиJJÂJUX,I<F'|ðNи'\N>I<Qi'_ëð}IN-<·и'/ðNи'|JJ,}I2‹i"|\/|"ëXð'|:},
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Ab1eM8LO7y8Djd5hUboeNq4qdcc3uB3YYd6jJ@dp01gpnr84dWHN9R6@unaHNoOFNaHyNZ4eenUeho9atiZqVQTo1@jdHh1BNCsGqtanf//TQA "05AB1E – Try It Online")
Explanation:
```
ð Push space
'_Iи Push I underscores (I = input)
JJÂJ Push reverse of that
UX, Put that in X and print it
I<F Loop from 1 to N-1 (N = index)
'| Push '|' (pipe)
ðNи Push N spaces
'\ Push '\' (backslash)
N>I<Qi'_ If N+1 == I-1, push _ (underscore)
ëð} Otherwise push space
IN-<·и Pop and repeat that by (I-N-1)*2
'/ Push '/' (slash)
ðNи Push N spaces
'| Push '|' (pipe)
JJ, Join and print
}
I2‹i"|\/|" If I == 1, push '|\/|'
ëXð'|:} Otherwise, push X with spaces replaced with pipes
, Print
```
] |
[Question]
[
Given a undirected graph \$G\$ and a integer \$k\$, how many \$k\$-coloring does the graph have?
Here by a **\$k\$-coloring**, we mean assigning one of the \$k\$ colors to each vertex of the graph, such that no two vertices connected by an edge have the same color. For example, the following graph can be 3-colored in 12 different ways:

Let \$P(G,k)\$ denotes the number of \$k\$-coloring of the graph \$G\$. For example, \$P(G, 3) = 12\$ for the graph above.
\$P(G,k)\$ is in fact a polynomial in \$k\$, which is known as the [**chromatic polynomial**](https://en.wikipedia.org/wiki/Chromatic_polynomial). For example, the chromatic polynomial of the graph above is \$k^4-4k^3+5k^2-2k\$.
This can be shown using the [deletion–contraction formula](https://en.wikipedia.org/wiki/Deletion%E2%80%93contraction_formula), which also gives a recursive definition of the chromatic polynomial.
The following proof is taken from Wikipedia:
>
> For a pair of vertices \$u\$ and \$v\$, the graph \$G/uv\$ is obtained by merging the two vertices and removing any edges between them. If \$u\$ and \$v\$ are adjacent in \$G\$, let \$G-uv\$ denote the graph obtained by removing the edge \$uv\$. Then the numbers of \$k\$-colorings of these graphs satisfy:
> $$P(G,k)=P(G-uv, k)- P(G/uv,k)$$
> Equivalently, if \$u\$ and \$v\$ are not adjacent in \$G\$ and \$G+uv\$ is the graph with the edge \$uv\$ added, then
> $$P(G,k)= P(G+uv, k) + P(G/uv,k)$$
> This follows from the observation that every \$k\$-coloring of \$G\$ either gives different colors to \$u\$ and \$v\$, or the same colors. In the first case this gives a (proper) \$k\$-coloring of \$G+uv\$, while in the second case it gives a coloring of \$G/uv\$. Conversely, every \$k\$-coloring of \$G\$ can be uniquely obtained from a \$k\$-coloring of \$G+uv\$ or \$G/uv\$ (if \$u\$ and \$v\$ are not adjacent in \$G\$).
>
>
> The chromatic polynomial can hence be recursively defined as
>
>
> * \$P(G,x)=x^n\$ for the edgeless graph on \$n\$ vertices, and
> * \$P(G,x)=P(G-uv, x)- P(G/uv,x)\$ for a graph \$G\$ with an edge \$uv\$ (arbitrarily chosen).
>
>
> Since the number of \$k\$-colorings of the edgeless graph is indeed \$k^n\$, it follows by induction on the number of edges that for all \$G\$, the polynomial \$(G,x)\$ coincides with the number of \$k\$-colorings at every integer point \$x=k\$.
>
>
>
## Task
Given a undirected graph \$G\$, outputs its chromatic polynomial \$P(G, x)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
### Input
You can take input in any reasonable format. Here are some example formats:
* an adjacency matrix, e.g., `[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]]`;
* an adjacency list, e.g., `{1:[2,3],2:[1,3,4],3:[1,2],4:[2]}`;
* a vertex list along with an edge list, e.g., `([1,2,3,4],[(1,2),(2,3),(3,1),(2,4)])`;
* a built-in graph object.
You may assume that the graph has no loop (an edge connecting a vertex with itself) or multi-edge (two or more edges that connect the same two vertices), and that the number of vertices is greater than zero.
### Output
You can output in any reasonable format. Here are some example formats:
* a list of coefficients, in descending or ascending order, e.g. `[1,-4,5,-2,0]` or `[0,-2,5,-4,1]`;
* a string representation of the polynomial, with a chosen variable, e.g., `"x^4-4*x^3+5*x^2-2*x"`;
* a function that takes an input \$n\$ and gives the coefficient of \$x^n\$;
* a built-in polynomial object.
## Testcases:
Input in adjacency matrices, output in polynomial strings:
```
[[0,0,0],[0,0,0],[0,0,0]] -> x^3
[[0,1,1],[1,0,1],[1,1,0]] -> x^3-3*x^2+2*x
[[0,1,0,0],[1,0,1,0],[0,1,0,1],[0,0,1,0]] -> x^4-3*x^3+3*x^2-x
[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]] -> x^4-4*x^3+5*x^2-2*x
[[0,1,1,1,1],[1,0,1,1,1],[1,1,0,1,1],[1,1,1,0,1],[1,1,1,1,0]] -> x^5-10*x^4+35*x^3-50*x^2+24*x
[[0,1,1,0,1,0,0,0],[1,0,0,1,0,1,0,0],[1,0,0,1,0,0,1,0],[0,1,1,0,0,0,0,1],[1,0,0,0,0,1,1,0],[0,1,0,0,1,0,0,1],[0,0,1,0,1,0,0,1],[0,0,0,1,0,1,1,0]] -> x^8-12*x^7+66*x^6-214*x^5+441*x^4-572*x^3+423*x^2-133*x
[[0,0,1,1,0,1,0,0,0,0],[0,0,0,1,1,0,1,0,0,0],[1,0,0,0,1,0,0,1,0,0],[1,1,0,0,0,0,0,0,1,0],[0,1,1,0,0,0,0,0,0,1],[1,0,0,0,0,0,1,0,0,1],[0,1,0,0,0,1,0,1,0,0],[0,0,1,0,0,0,1,0,1,0],[0,0,0,1,0,0,0,1,0,1],[0,0,0,0,1,1,0,0,1,0]] -> x^10-15*x^9+105*x^8-455*x^7+1353*x^6-2861*x^5+4275*x^4-4305*x^3+2606*x^2-704*x
```
Input in vertex lists and edge lists, output in descending order:
```
[1,2,3], [] -> [1,0,0,0]
[1,2,3], [(1,2),(1,3),(2,3)] -> [1,-3,2,0]
[1,2,3,4], [(1,2),(2,3),(3,4)] -> [1,-3,3,-1,0]
[1,2,3,4], [(1,2),(1,3),(2,3),(2,4)] -> [1,-4,5,-2,0]
[1,2,3,4,5], [(1,2),(1,3),(1,4),(1,5),(2,3),(2,4),(2,5),(3,4),(3,5),(4,5)] -> [1,-10,35,-50,24,0]
[1,2,3,4,5,6,7,8], [(1,2),(1,3),(1,5),(2,4),(2,6),(3,4),(3,7),(4,8),(5,6),(5,7),(6,8),(7,8)] -> [1,-12,66,-214,441,-572,423,-133,0]
[1,2,3,4,5,6,7,8,9,10], [(1,3),(1,4),(1,6),(2,4),(2,5),(2,7),(3,5),(3,8),(4,9),(5,10),(6,7),(6,10),(7,8),(8,9),(9,10)] -> [1,-15,105,-455,1353,-2861,4275,-4305,2606,-704,0]
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~62~~ ~~59~~ ~~55~~ 47 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Takes a vertex list `ùï®` on the left and an edge list `ùï©` on the right. Returns coefficients in descending order.
```
{√ó‚â†ùï©?(ùï®ùïä1‚Üìùï©)-0‚àæ(1‚Üìùï®)ùïä‚ç∑‚à߬®1‚Üìùï©-(-¬¥‚äëùï©)√óùï©=‚äë‚äëùï©;1‚àæ0¬®ùï®}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHvDl+KJoPCdlak/KPCdlajwnZWKMeKGk/CdlakpLTDiiL4oMeKGk/Cdlagp8J2ViuKNt+KIp8KoMeKGk/CdlaktKC3CtOKKkfCdlakpw5fwnZWpPeKKkeKKkfCdlak7MeKIvjDCqPCdlah9CgriiJjigL8x4qWKPOKImEbCtMuY4oiY4oC/MuKliiDin6gK4p+oMSwyLDPin6kK4p+o4p+pCuKfqDEsMiwz4p+pCuKfqOKfqDEsMuKfqSzin6gxLDPin6ks4p+oMiwz4p+p4p+pCuKfqDEsMiwzLDTin6kK4p+o4p+oMSwy4p+pLOKfqDIsM+KfqSzin6gzLDTin6nin6kK4p+oMSwyLDMsNOKfqQrin6jin6gxLDLin6ks4p+oMSwz4p+pLOKfqDIsM+KfqSzin6gyLDTin6nin6kK4p+oMSwyLDMsNCw14p+pCuKfqOKfqDEsMuKfqSzin6gxLDPin6ks4p+oMSw04p+pLOKfqDEsNeKfqSzin6gyLDPin6ks4p+oMiw04p+pLOKfqDIsNeKfqSzin6gzLDTin6ks4p+oMyw14p+pLOKfqDQsNeKfqeKfqQrin6gxLDIsMyw0LDUsNiw3LDjin6kK4p+o4p+oMSwy4p+pLOKfqDEsM+KfqSzin6gxLDXin6ks4p+oMiw04p+pLOKfqDIsNuKfqSzin6gzLDTin6ks4p+oMyw34p+pLOKfqDQsOOKfqSzin6g1LDbin6ks4p+oNSw34p+pLOKfqDYsOOKfqSzin6g3LDjin6nin6kK4p+oMSwyLDMsNCw1LDYsNyw4LDksMTDin6kK4p+o4p+oMSwz4p+pLOKfqDEsNOKfqSzin6gxLDbin6ks4p+oMiw04p+pLOKfqDIsNeKfqSzin6gyLDfin6ks4p+oMyw14p+pLOKfqDMsOOKfqSzin6g0LDnin6ks4p+oNSwxMOKfqSzin6g2LDfin6ks4p+oNiwxMOKfqSzin6g3LDjin6ks4p+oOCw54p+pLOKfqDksMTDin6nin6kK4p+p)
This is a recursive function based on the deletion-contraction formula.
If the edge list is empty (`¬¨√ó‚â†ùï©`) the polynomial `1 0 ... 0` with as many zeros as there are vertices is returned. (`1‚àæ0¬®ùï®`)
Otherwise:
* Pick \$uv\$ as the first edge in the list `ùï©`, replace all occurences of \$u\$ with \$v\$: `ùï©-(-¬¥‚äëùï©)√óùï©=‚äë‚äëùï©`.
* Remove the edge \$uv\$ (now \$vv\$), sort each edge and remove duplicate edges generated by merging \$u\$ and \$v\$: `⍷∧¨1↓`.
* Recursively call the function with this new edge list and and a vertex list with one less vertex: `(1‚Üìùï®)ùïä`. (Technically we would want to remove \$u\$ from `ùï®`, but as we only care about the length of the vertex list, removing the first one achieves the same). This is \$P(G/uv, x)\$.
* Because the recursive call got one less vertex, the resulting polynomial will have one degree too few. By prepending a zero this can be fixed: `0‚àæ`.
* Recursively call the function on \$G-uv\$ and subtract the previous result from this: `(ùï®ùïä1‚Üìùï©)-`.
[Answer]
# [Haskell](https://www.haskell.org/), 102 bytes
Port of my BQN answer.
```
import Data.List
n!([u,v]:e)=zipWith(-)(n!e)$0:tail n!nub[sort$take 2$(r++[v])\\[u]|r<-e]
n!_=1:(0<$n)
```
[Try it online!](https://tio.run/##hY89b4MwGIT3/IoXicFWnIqPGggKW5ZK3Ts4VuWqSLFCHAQmQ9T/Tu23qUoblC4nc757Du9Vf6ibZhz1sT11FrbKqodn3duFCYgY2FmWNa0uun3Rdk9WlJigpmFUWqUbMIEZ3kTveqFVhxqSkHTLpThLutuJQX50m1UtHei1iksSbUJDx6PSBip4Py0A2k4bCyGImCUslRAAERLKEoR4MlZKOpsR/iiZ09SpN@VNjj1Okwkmvflf8ofpdT7P@G0jdlmv/FfbK78ue/VnX5@nsozlrJhj8wkvm/By5BVOOfocnQwdj7q3w9Ysjr7Hpk/I/vx8gtD0@pACJ9c45vp@7WsTP3K8L/Ae@XL8BA "Haskell – Try It Online")
I feel like there should be a shorter way to replace \$u\$ with \$v\$ in a list (currently `take 2$(r++[v])\\[u]`).
[Answer]
# [R](https://www.r-project.org), ~~111~~ 108 bytes
```
f=\(n,e,`+`=el)`if`(length(e),f(n,x<-e[-1])-f(n-1,unique(Map(\(i)sort(ifelse(+e+1-i,i,+e+2)),x))),c(!1:n,1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVJdSsNAEAYfPUXEl10yC9m_JBXrDTyAWCFSdnUhRG0S6F18qQ8eSk_jbKahSWsJ5NuZ-Wa-b5b9_Nrsdt9950X5U_vlijXgoEqrpat5FXzFate8dK_McfBY294K9yjkExcYCQl9Ez56x-6f39mKBd6-bToWvKtbx1KXShEgAB4U57Dl-FuzK3nTgOScNH8vHjzTkNSh7RjnybW4S5iELH788lBaY1LFdgk6gkI40IUGRXxzzFfE12DmfA3o_v-WicQAs04DFsRezJ7plNgygD2aM4Ad_QwwRDh0qiEz0KhiM1CGlMqzSnY2O5_NLmh2GcFSzVIyp2SBMNXFATluJw0Yg7EtcLCKN6U1-UBnByPzXfPTJRWJ6XHlkvwsyIjMyMneEIUFkUoiLWJ2ajB24c0Yiwdt0Zkqc3SgipjUWFJ5hhsUWbw3emHj6_4D)
Takes input as the number of vertices `n` and list of edges `e`. Outputs a vector of coefficients in ascending order.
Thanks to pajonk for -3 bytes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), 24 bytes
```
#~ChromaticPolynomial~x&
```
[Try it online!](https://tio.run/##pZGxCoMwFEV3v0IodMqQ9wmlQ1d3cQhW0GJMEYdKiL@eWk1fXtSlKUi8uZKbc59SDHUlxdCUwtrTdK17tewy1Y6dko1op9fZZn3TDfnBx/xyf4iy6srx1otnnWvNWfp5DEuPpCmKIvkpDRgYpoFx955VVAqfz7mcRa0eLIpHpwJJRT6SH5tKWgfJXtOJwD/8Kyf24N4LHDo3dwIJcBfMFlc/443z9eLoN/zu5p1PCAmV/1eEft9v3zHsQJOBMGz8oC/66Po7cRKJfQM)
We create a pure function for the built-in Mathematica function `ChromaticPolynomial`. We make use of [infix notation](https://reference.wolfram.com/language/ref/Infix.html).
If we need to allow adjacency matrices we can parse them to a graph using `AdjacencyGraph`. Thus we need more bytes in this case.
**Edit:** Thanks to att for guiding me to the correct solution!
[Answer]
# Python3, 668 bytes
```
from copy import*
R=lambda x:x[0]*R(x[1:])if x else 1
e=lambda g:[(i,[*g[i]][0])for i in g if g[i]][0]
T=set.remove
def r(g,e):
g=deepcopy(g);T(g[e[0]],e[1])
if e[1]in g:g[e[1]]={i for i in g[e[1]]if i!=e[0]}
return g
def m(g,e):
g=deepcopy(g);T(g[e[0]],e[1])
if e[1]in g:g[e[1]]={i for i in g[e[1]]if i!=e[0]}
for i in g.get(e[1],[]):
if i in g:g[i].add(e[0])
if e[1]in g:del g[e[1]]
return{x:{[i,e[0]][i==e[1]]for i in g[x]}for x in g}
def f(g,s=[]):
if not any(g.values()):yield(s,len(g));return
yield from f(r(g,E:=e(g)),s+[1]);yield from f(m(g,E),s+[-1])
def F(g):
d={}
for a,b in f(g):d[b]=d.get(b,0)+R(a)
return[*d.values()]+[0]*(len(g)-len(d)+1)
```
[Try it online!](https://tio.run/##tVLNbuIwED6Tp/DebHARgQ3QIB/bB0C9WVYVaidrKSRRkqIgxLOzMxNYoLtS28NeJvHMfD8zdrVvf5XFbFnVp1Nal1v2VlZ75rdVWbfDYK3yZLuxCeviTk/McM07HcZG@JR1zOWNY2HgLj1ZrLmXephpbwx0i7SsmWe@YBkDwCUdvKjGtePabcudC6xLWc0z6UQcsExZ5yp0wDOxeuGZdgAw0unQiABJ8A8JYyyFxqiDZ1eZPgdt/odC5DFgtWvfayiR0PY/Cl2L48y1HBukNiiGdH0lxh2ME2s5gj4IWZdfiC@2D1180F6SN@2VouKNi84c8dTR6UgjpjBio3phYC/KliUFTDneJfm7a7gQ8d673PJG5q6A6cWq1woY5Rk9gpTjnTzFymGHbEa4l9VdA@7yiUoPuDPUfoZmkLXqcN5HIjdoLcW81RujLO1mIyditOaJuMyph/aPPzPCh8Z7cw/4sWIUihMK5L5pX9vy1fq3lu8kw7scWKbYwcfwpri43sLuGAx6C4w8OOgcWJ3069@IYHB@GcRlRVDVvmj5M7/T0KGcypmRDBYqPu3h8CckxBlEyInPQPLnDWxKMMh9D3ZVw/gVsIz@gocAxBjdUWGMzp4w4j@gvyQh53Ihl/8Qim7I5zfkCyJfQowoH1FmThlg@oaofJTh5Kx8O9z8w1hTUpidR1yS/iMphxOS7g3QYUH1JdWRnuycfgM)
[Answer]
# [SageMath](https://julialang.org/), ~~35~~ 33 bytes
```
lambda g:g.chromatic_polynomial()
```
[Try it here!](https://sagecell.sagemath.org/?z=eJx1UcsKgzAQvAv-Q48RpBifUPDcjxApqUUNGBXx0P5900Y3uz4QjDPO7s5s6rwT6vkSl-bWXKt2GpSYZfUYh-7TD0qKjnmu4zqK5_dJjC3Tvyf5ZkUR-Pop_c1Zelquwr2Y-1yLuBaZk4M4OhKbnn_50n0tDRbOFMeHk1AxTENt1uLkuBhZJQ3sN46Bo6QnbsxUcBVYjjA47FIBgwCRhcDbLmbDrJw1mR3dJLFp7_PEPhluF4xM7mPso1CruLO9rh1PYgEPrJ0JgV1nnGQ_s5op_sOAQoIigmKCEoJSgjLP-wKBWsgy&lang=sage&interacts=eJyLjgUAARUAuQ==)
The function `f` takes a built-in graph object as an argument and calculates its chromatic polynomial. However, it is fairly simple to parse a matrix directly into a sage graph object as follows.
```
Graph(matrix([[0, 1, 1], [1, 0, 1], [1, 1, 0]]))
```
In this case we would need more bytes.
**Notice** the difference to my post for Mathematica. In Mathematica we call a function and provide the graph as an argument. Here, the graph object's interface specifies the function `chromatic_polynomial`, which needs more code.
Thanks to alephalpha we can save 2 bytes!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 104 bytes
```
⊞υθFυ«≔§ι⁰η≔⊟ιζ¿ζ«≔⊟ζδ≔⁻ζ⟦δ⮌δ⟧ζF⟦⟦ηζ⟧⟦⊖ηEζEκ⎇⁼μ⌈δ⌊δμ⟧⟧«⊞υκ⊞ικ»»»F⮌υ¿⊖Lι«≔⊟⊟ιη⊞ιE⊟⊟ι⁻κ§ηλ»⊞ιE⊕§θ⁰⁼κ§ι⁰I⊟θ
```
[Try it online!](https://tio.run/##VVFNa4QwED2vv2KOE0ih3e6tp6XtYaELUnoLHoJm17Aa18QsW4u/3U7UUAsyMh/vzbyXvJQ2b2Q1jql3JXoOLXtJTo0F9Ax@ks3eOX02uO8OplB31BweGYeShmIrba6oqdaHmj4B9hNw3e6pXYR2LB618Q57DqLg8KluyjqFBcsizWa6QIiS8oym3lRuVa1MpwosaegorwEdfhcOX8oaab/xvfWycliHxl3XvibKMKzNknCoGWNZNh@4iZIv08o51TEdEvqG2Yp4oWcMgsL1OR/KnDvCEfHKr6B6Nia6FdnDzf@6sxckI3pMoitiI9CQqMopWEMP5m91BLThUYhp0b@imp4rMKVWmw5fpeumxW0ojqMQOy7wiW8Zp/hMcbvEHbmUjQ@36hc "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of the number of vertices and a list of edges and outputs the polynomial as a list of coefficients in ascending order. Explanation:
```
⊞υθFυ«
```
Start processing with the input graph.
```
≔§ι⁰η≔⊟ιζ
```
Get the number of vertices and list of edges of this graph.
```
¿ζ«
```
If the graph still has edges, then...
```
≔⊟ζδ
```
Remove an edge from the list.
```
≔⁻ζ⟦δ⮌δ⟧ζ
```
Remove any other duplicate copies of that edge from the list.
```
F⟦⟦ηζ⟧⟦⊖ηEζEκ⎇⁼μ⌈δ⌊δμ⟧⟧«
```
Loop over the graph with the edge removed and the graph with the edge merged.
```
⊞υκ⊞ικ
```
Push each graph both to the list of graphs to process but also to the graph that is being processed.
```
»»»F⮌υ
```
Loop over the list of graphs in reverse order.
```
¿⊖Lι«
```
If this graph had to be split into two simpler graphs, then...
```
≔⊟⊟ιη⊞ιE⊟⊟ι⁻κ§ηλ
```
... push the difference between the two polynomials from the simpler graphs to this graph, ...
```
»⊞ιE⊕§θ⁰⁼κ§ι⁰
```
... otherwise push the polynomial for a trivial graph to this graph.
```
I⊟θ
```
Output the polynomial for the original graph.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 87 bytes
A port of [ovs's Haskell answer](https://codegolf.stackexchange.com/a/243020/9288). Make sure to upvote that answer as well!
```
f(n,e)=if(e,[u,v]=e[1];-f(n[^1],Set([Set([if(w-u,w,v)|w<-r])|r<-e=e[^1]]))+f(n,e),x^#n)
```
[Try it online!](https://tio.run/##dY7RasMwDEV/xXQvNpNhbuc0pe1@Yo/CBTOSEQjBhLZZof@eSmqgXtb54SJdXx0pxb6x32kca91BZfZNrSvAE5zDvkIXtpZ8PLgAn9VRowhFBnuCAc7mOuxsH8y139mK8pQLxrzeUfBzeOnMGFNqLzoq@6FS33RHKhfcLNRXbFtdg4rGgEJEB0tYBSoDy6PlKgApdche9g/vWULyyN5/iQeDdZYD/yfpeJrU/5pi9dMmVq55ekaDAtZQPmH6jFNknLVwaAK9@F6cQhwmPeXDBtzb9JGfXMyOXQpsNR1eyqqNLOFx2nLfJY2cjaX8C56eGW8 "Pari/GP – Try It Online")
[Answer]
# [Python](https://www.python.org/) + `sympy`, 458 bytes
A Port of [@ovs's Haskell answer](https://codegolf.stackexchange.com/a/243020/9288).
---
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=fVPBbtswDMV29HU_wPVSKVOGup3TtIB3yzU_IAhDVlOYAUc2LDldUPRLdull-5h9wr5mIu3VTppVB4IiH9-jSfnHr2YfvtXu6elnF-x8-efNb9vWW_D7bbOHctvUbZglBVqwwimUtwnEU1rA3qPTqV2O-sI8B-5zvQZbt7CG0oEj-Pp93o2AVa7HCwELAqJOb81IOwh1lCpg4wrYsXuIoHNXu1C6Dg8SWD0Xv6xYfdw0DbpC6B13B3kesVh5hEnnhZFHlB5f4Srk5ANBV6UPopRMVxKdxyBC11QofJwqFsLLPuspu5LjSFoMXetgbsW9WskPPHoaTi9w2MaAjQv7WldenH8_l7NZhU44Oaz07buAPny523j0EBvjUq1TdamujAJtjDoOkWdUtPGmKXaEUZ8mKK7RFHsNNXKRPYFV2Qt0SgzRZgeVZLNBkSz5VH2CUS3UtVqe4M0mXIsJ1zVzxQqdcTzjyIIjxPRfDXWj0otBaNr64qjpSya8Gj5gyXI3LETlUanX4wu3rpecZ3pjEpMk9GRomfRqxs32L6JpSxeEPXug2CPMP8ODFeRrao6d1MjHs-Ft_Pvt_wI)
```
from sympy import*
def f(n,e):
if e:
u,v=e[0]
w=[N for N in n if N!=u]
E=[]
for d in e[1:]:
if u in d and v in d:
continue
elif u in d:
E.append([v if N == u else N for N in d])
else:
E.append(d)
E= [list(i) for i in set(tuple(sorted(s)) for s in E)]
return -f(w,E)+f(n,e[1:])
else:
return symbols('x')**len(n)
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=jVTNbtswDD4NGPwUXHeo3SlD085pWiC77r6rYAROTKcCbNmwpPyg6JPs0sv2UHuaibQTOz8bpoNAUuT38Q_68ave2edKv739dDYfTX-_e583VQlmV9Y7UGVdNZaURVWYINjCbK-E19vrKAgyzCEPtQCMngLwR-WArUTHCVj7GJS3ycGm5xvlKZ2dO_8kdZUh5FUDLCgNmjBY-TADlwSHwI_wDTU2qUXQuAHMVmggzS02UGKzUnoFDlKdwbrnws289fNMfQpER2aiQzl-SvqMuxocP5ELA-61Yz86y0pbpR1Seg2W1Ro75ByU5ddUaQOLyj6fZUcHiyHbOf6hgs9pXaPOQrk-9Gfm--MBDMJZEykkiU6YzP_gkxINm_69rSrVO6gri77ctIDM1YVa0ig4-HLDC2VsqCyWEedGEuVm0IbWx2No_HZhFhq3iFoXL_EK7FGifmYHoUHrGg0jv3b9JolBDHzqVpIm2_bguPYOYXtzU6AOta_WorHzZWravNlRyrG4E_eJ8IuTiFMTSYnwt9ck2U58xJeBF8dIsv3Lq8ei-4KviM-8x4Tg7_goku64Y6SbZIq-gCgm4kFML-DGA6zJAOuBsXyEjNkes2XCFkL6K4d4FOPbjmiY-uQk6TsGvO8KmDLdIxNRuGdq-Vjh1OWU3xk-SQL_YdAm0TBplfrJtvOvG6VtmF-9kO0VRl_hJQ9JlpQcC-Mker2KgvZD7P7F_f_4Bw)
```
from sympy import symbols
x = symbols('x')
def f(n, e):
if e:
u, v = e[0]
n_without_u = [node for node in n if node != u]
# Generate new edges after merging u and v
new_edges = []
for edge in e[1:]:
if u in edge and v in edge:
continue # remove edge if it contains both u and v
elif u in edge:
new_edges.append([v if node == u else node for node in edge])
else:
new_edges.append(edge)
# Remove any potential duplicate edges
new_edges = [list(item) for item in set(tuple(sorted(sub)) for sub in new_edges)]
return -f(n_without_u, new_edges) + f(n, e[1:])
else:
return x**len(n)
test_cases = [
[[1,2,3], []],
[[1,2,3], [[1,2],[1,3],[2,3]]],
[[1,2,3,4], [[1,2],[2,3],[3,4]]],
[[1,2,3,4], [[1,2],[1,3],[2,3],[2,4]]],
[[1,2,3,4,5], [[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5]]],
[[1,2,3,4,5,6,7,8], [[1,2],[1,3],[1,5],[2,4],[2,6],[3,4],[3,7],[4,8],[5,6],[5,7],[6,8],[7,8]]],
[[1,2,3,4,5,6,7,8,9,10], [[1,3],[1,4],[1,6],[2,4],[2,5],[2,7],[3,5],[3,8],[4,9],[5,10],[6,7],[6,10],[7,8],[8,9],[9,10]]]
]
for case in test_cases:
print(f"{case} -> {f(case[0], case[1])}")
```
] |
[Question]
[
[Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus) is the [Language of the Month for January 2022](https://codegolf.meta.stackexchange.com/questions/24222/language-of-the-month-for-january-2022-add), and so I'm asking for tips for golfing in it. Please stick to tips specific to Add++, and avoid general tips such as "remove whitespace" or "avoid comments".
Please post separate tips as individual answers
[Answer]
## Use `L` for the main function, `D` for helper functions
Unnamed\* lambdas have the syntax
```
L<flags>,<code>
```
[For example](https://tio.run/##S0xJKSj4/98nTkfJIzUnJ19HITy/KCdFUen//3/5BSWZ@XnF/3UzAQ). This is much shorter than the named version
```
D,<name>,<flags>,<code>
```
For a single byte function name, using a lambda is 3 bytes shorter, and this increases as the name grows longer.
\*: Lambdas are stored in the interpreter as functions with the names `lambda 1`, `lambda 2`, etc. so can be accessed this way
If you're submitting a function submission, the main function should always be an unnamed lambda, and any helper functions should be named. Consider,
```
L,€{lambda 2}
L,'
```
vs
```
L,€g
D,g,@,'
```
which saves 5 bytes
[Answer]
## Call your helper functions `I`, `K`, `Y`, `Z`, `g`, `k`, `l`, `u` or `w`
Add++ doesn't have any way to combine multiple functional builtins into one command (for those familiar, like Jelly's `$¥` quicks). If you want to e.g. filter on a complex condition, you'll need to define a helper function containing the code for that condition.
When calling other functions from functional mode, you surround the name with `{...}`:
```
D,main,@,€{triple}
D,triple,@,3*
```
However, if the braces are omitted, it will only take the next character immediately after the quick. In this case, if there's a name clash between a builtin and a user-defined function, the interpreter defaults to the builtin.
So, for this example,
```
D,main,@,€f
D,f,@,5+
```
The `€` will actually call the `f` builtin (prime factors), not the function `f` (add 5).
If the builtin isn't defined however, such as `g`, it will use the function instead. Therefore, you can save 2 bytes per helper function call like
```
D,main,@,€g
D,g,@,5+
```
The undefined builtins are `I`, `K`, `Y`, `Z`, `g`, `k`, `l`, `u` and `w`, so name your helper functions these first, then move onto having to use braces if you have more than 9 helpers
[Answer]
Always use `D` Loop when you use `W` if you want to execute once and go to start of the loop if the condition is 1. This will prevent from duplicating the code.
[Answer]
# Use `&` to swap variables.
This
```
A:1
B:2
; Start of the Swap
C:A
A:B
B:C
; End of the Swap
```
Can be shortened to
```
A:1
B:2
; Start of the Swap
A&B
; End of the Swap
```
(This can be useful if you try to swap in loops)
] |
[Question]
[
## Background
[SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus), or simply SKI calculus, is a system similar to lambda calculus, except that SKI calculus uses a small set of *combinators*, namely `S`, `K`, and `I` instead of lambda abstraction. Unlike lambda calculus, beta reduction is possible only when a combinator is given enough arguments to reduce.
The three combinators in SKI calculus are defined as follows:
$$
\begin{aligned}
S\;x\;y\;z & \overset{S}{\implies} x\;z\;(y\;z) \\
K\;x\;y & \overset{K}{\implies} x \\
I\;x & \overset{I}{\implies} x
\end{aligned}
$$
For example, the SKI expression \$ e=S(K(S\;I))K \$ is equivalent to the lambda expression \$ λx.λy.y\;x \$, as applying two arguments to \$ e \$ reduces to the desired result:
$$
\begin{aligned}
S(K(S\;I))K\;x\;y & \overset{S}{\implies} (K(S\;I)x)(K\;x)y \\
& \overset{K}{\implies} S\;I(K\;x)y \\
& \overset{S}{\implies} (I\;y)(K\;x\;y) \\
& \overset{I,K}{\implies} y\;x
\end{aligned}
$$
It is known that [any lambda expression can be converted to a SKI expression](https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis).
A [Church numeral](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals) is an encoding of natural numbers (including zero) as a lambda expression. The Church encoding of a natural number \$ n \$ is \$ λf. λx. f^n\;x \$ - given a function \$ f \$ and an argument \$ x \$, \$ f \$ repeatedly applied to \$ x \$ \$ n \$ times.
It is possible to construct a lambda expression (and therefore a SKI expression) that performs various arithmetic (e.g. addition, multiplication) in Church encoding. Here are a few examples of Church numerals and Church arithmetic functions: (The given SKI expressions are possibly not minimal.)
$$
\begin{array}{r|r|r}
\text{Expr} & \text{Lambda} & \text{SKI} \\ \hline
0 & λf. λx. x & K\;I \\
1 & λf. λx. f\;x & I \\
2 & λf. λx. f(f\;x) & S (S (K\;S) K) I \\
\text{Succ} \; n & λn. λf. λx. f(n\;f\;x) & S (S (K\;S) K) \\
m+n & λm. λn. λf. λx. m\;f(n\;f\;x) & S (K\;S) (S (K (S (K\;S) K)))
\end{array}
$$
It is also possible to represent lists as lambda terms using [right-fold encoding](https://en.wikipedia.org/wiki/Church_encoding#Represent_the_list_using_right_fold). For example, the list of numbers `[1, 2, 3]` is represented by the lambda term \$λc. λn. c\;1 (c\;2 (c\;3\;n))\$ where each number represents the corresponding Church numeral.
## Challenge
Write a SKI expression that evaluates to the string `Hello, World!`, i.e. the Church list of Church numerals representing the list
```
[72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
```
## Scoring and winning criterion
The score is the total number of `S`, `K`, and `I` combinators used. The submission with the lowest score wins.
[Here is a Python script](https://tio.run/##lVRNb6MwEL3zK0bqgbGSRsnujYrTnlCOHKMIGTALLTHIJrukfz472HyYptWqOUTj8XvPb8Ye2ltXNvLnPYYQan5Jcw59MEW3OXoPoMd3hjf6Y97xC3DvRaud3vNyUUDLlRaJfqtQs8AD0B3P3gh4is60KhoFGVQS9LAHUBV26cfHyA8s@PR8OBNhjlH84TVmZGVgiNpwwhB8nBg73rZC5hg9QBhB0kls1zYtshfgHxMrEY6pOUqJ7qrkYsOWp7NGzeXNmOsFlzKcIpkldU2SoTTtIGdy5o3NKwKnjQVa9POBYcGwd718hu/NCYVqLvMZI1qig9qQ3H60Y8A11i64xs/u@DTq9uy8uTE8nUnhCahIEH2rhNZVIzU0BfwqryorYb@FwxZ@eE@tqmSHI3t5Ej61h1FFX@7/ZzvGGI8xOzKLe/BiWj964XledZTziJnQgi59pUQ6g9qkyJjP7GUJ3SUjB/kW0uWeOWyG1xRO7Z5Q5sY4YzZInRJ4XeOjoLHJhxeiuPwt8LC3qXSVGgocaOXfZKiQ/Pu@f49XpjGOzGpqixOyJXaz5veB9n2BO1nZXWlgFLLRJITTw3I@AYt9qsa2xOamFcm8NpXErFQ04s7oWNQMi4e5C/ytO4Cu@P0f) to check the correctness and score of your SKI expression.
[Answer]
# Score = 192
```
S(SI(K(S(S(SSI)I))))
(S(SI(K(S(SIS)(KS))))
(S(SS)I(K(S(SI(K(S(S(SI(K(SS)))(K(KI))))))))
(S(SI(K(SS(S(K(S(SI)))K))))
(S(SI(K(S(SI(S(K(SIS)))))))
(S(SI(K(S(S(S(S(SSI))))K)))
(S(SI(K(SI(S(S(SS))I))))
(S(SI(K(SS(S(K(S(SI)))K))))
(S(SI(K(S(SI(SI(S(K(S(SI)))))))))
(S(SI(K(S(S(SI(K(SS)))(K(KI))))))
(S(SI(K(S(SII)(K(SS)))))
(S(SI(K(K(S(S(S(S(SI)))(KI))))))
(K(KI)))))))))))))
(S(KS)
(S(K(S(K(S(KS)K))))
(S(K(SI))
(S(KK)
(S
(S
(S
(SS(S(S(KS)S))(KS))
(KS))
(K(S(KS)K)))
(KI))))))
```
[Try it online!](https://tio.run/##hVRNj5swEL3zK0baAzPabJS0N6qcerI4coyiyBBo6BJAQFqyfz4df4FpslpFIrbnzfObNyO3t@Hc1N/vCeygkpf0JGGM3Oo2rT4iGPGD8MYfCuJPwGMgFpExCE55Aa3s@vzYv5fYUxQA9IPM3hm4FwfeFU0HGZQ19CoGUBZmGyaxCCMD3r9tD5wwrTH/IyvMWIrKyCuds9tBiC5jLds2r08oHiDEkNSRrdumRfoB8v@DBYnEVF/V5cO1q2cZprw@a7qpvAlzveBchlckmaShOWZYaztYWT3lWfOKyLOxQIN@2xIWhKOv5Rl@1DcUXXOZ7rDoGj3UK9NtrBwNrrDywRU@6/He8o50eL0R7g/M8AJcJORj2@V9XzZ1D00BP8/XLjvDZgXbFXwLXtqurAe02fNIhGwPcUWfxr8IJ5hgnFBMBvegRVtvtcjTqRz4LODMI2@46Qsm5lFsjpEoJNOsvB@ONgflCtK5zxJe1TTtnN0OpTsmicwi9UqQVYWPhFqmVBPSyfpXjtuNOUoXR6pAlXb@e1QVsv4wDO9sgdCq@ZcIEqRwOJ8KLosLUqegMeQCLksvFIL/Y51v0DAHrTGJisY2Cv4lBiCSOXkRn@TZfB2fAcLGycqHZfj59fAgQfg4T8iDmGcVT8gFqSAH9RETxCtOaLoHMsb6rpJrD7dE9yNezpy1PdZ81uQ4dn462yaDZh@MCmZJyPR7Cnkb/ybL5aTdeZbWV37xOiQ7ZbBzL4P3hs/zxxRmps2Z2zHN76asMTt3/EZ7b59BTbBEPZxRuPJfUJ/8/g8 "Python 3 – Try It Online")
An attempt to factor out common expressions from the numerals.
## Old answer: score = 256
```
S(SI(K(S(SS)S(S(SI)(K(S(S(KS)K))))I)))
(S(SI(K(S(S(S(S(SIS)(KS)))S)S(S(KS)K)I)))
(S(SS)I(K(S(SI(K(S(S(K(SSS))(SI))S(S(KS)K)I)))))
(S(SI(K(S(S(S(S(S(SS)I))S)(KI))S(S(KS)K)I)))
(S(SI(K(SIS(S(SS)K(SSK(S(S(KS)K))))I)))
(S(SI(K(SS(S(S(SI))S)(K(S(S(KS)K)I)))))
(S(SI(K(SS(S(SIS))(SSK)(S(S(KS)K))I)))
(S(SI(K(S(S(S(S(S(SS)I))S)(KI))S(S(KS)K)I)))
(S(SI(K(S(SS)S(SI(SSK(S(K(S(S(KS)K))))))II)))
(S(SI(K(S(S(K(SSS))(SI))S(S(KS)K)I)))
(S(SI(K(SIS(S(S(SS)K(S(S(KS)K))))II)))
(S(SI(K(S(S(SSI))(SSK)(S(S(KS)K))I)))
(K(KI)))))))))))))
(S(KS)(S(K(S(K(S(KS)K))))(S(K(SI))K)))
```
[Try it online!](https://tio.run/##lVRNj5tADL3zKyztAVvJRkl7o8qpJ8SRYxRFA4GGLgE0kJbsn089H5AhZLttIqHx8N6bZ49xc@1OdfX1FsMWSnFOjgL6YFhdx9V7AD2@E175QV70Abj3wsmb3vOOWQ6NkG12aN8KbCnwANpOpG8M3IV7jvJaQgpFBa16B1DkJvTjKPQDA969bvZMGNeY/RIlpmxFMbJSc7Zb8HFgrETTZNURwxmEGJIMYqumbpC@gXjcmIgITPRRMususrrbMOm1aS3H9EbM5Yz3NJwkyZC6@pBipcvBzqqRZ4uXB04ZczTo1w1hTti7Xp7he31CLuvzeIZFV@igFiy3tnY0uMTSBZf47I53Vren/eJKuNuzwgtwkpD1jczatqirFuocvp8uMj3BegmbJXzxXhpZVB1a9r0lfC4PcUYfvv/kdYwxRjFFZHAzL7r01os4HouO9zxmHjjgS58osY5SGxSJfDKXlbXdwXJQLCG537OAheqm7VDuAaVvTBCZReKkIMoS54LaplAdIkX1I8PN2mwlky2VoKKdfh9Uhuzf9/0blyDUruOYVDnikEw4pEGhYuIdZ/4hp8sIIkMzVVRIMFoWPHD4yZuk5Kd43Y8zda2gtDF6JKhPcsSHFqvkn7gGFzsYN7I4dzEDh9pxHJGjPOr@v@sHji5caI1PzfMxLgn@qZIj@rE8tkBucab4aSZK@C9ZG0KkU3R@Hk4@AecwEzJaRTfuudWFJ6NEst0I22GCOLP@3qcsbXrf7A0Ry/ysiwrTk@RZ7sxIgxphsRqwgb90J60rfvsD "Python 3 – Try It Online")
### How it works
I used a slightly targeted brute-force search to find expressions for the numbers. The basic idea is to loop through all expressions in order of increasing size, apply them to two arguments (with appropriate bounds on the evaluation length and depth), and see if any numbers fall out. For larger sizes, I restricted the search to expressions with `S(KS)K` (the B combinator) and one or more `I` at the end, since that seems to find a lot of numbers. Search code is below.
```
72 = S(SS)S(S(SI)(K(S(S(KS)K))))I
101 = S(S(S(S(SIS)(KS)))S)S(S(KS)K)I
108 = S(S(K(SSS))(SI))S(S(KS)K)I
108 = S(S(K(SSS))(SI))S(S(KS)K)I
111 = S(S(S(S(S(SS)I))S)(KI))S(S(KS)K)I
44 = SIS(S(SS)K(SSK(S(S(KS)K))))I
32 = SS(S(S(SI))S)(K(S(S(KS)K)I))
87 = SS(S(SIS))(SSK)(S(S(KS)K))I
111 = S(S(S(S(S(SS)I))S)(KI))S(S(KS)K)I
114 = S(SS)S(SI(SSK(S(K(S(S(KS)K))))))II
108 = S(S(K(SSS))(SI))S(S(KS)K)I
100 = SIS(S(S(SS)K(S(S(KS)K))))II
33 = S(S(SSI))(SSK)(S(S(KS)K))I
```
To build the list, I used an intermediate list encoding where cons is simpler, then converted to the target encoding:
```
# pack [x, y, ..., z] = λc. c x (c y (... (c z [])))
square f = S(SS)I(Kf) # λx. f (f x)
pack [] = K(KI)
pack [n, ...l] = S(SI(Kn))(pack [...l])
pack [n, n, ...l] = square (S(SI(Kn))) (pack [...l])
cons = S(KS)(S(K(S(K(S(KS)K))))(S(K(SI))K))
[...l] = pack [...l] cons
```
### Search code (Rust with `rayon` and `typed_arena`)
```
use rayon::prelude::*;
use std::borrow::Cow::{self, Borrowed, Owned};
use std::cell::Cell;
use std::fmt;
use std::ptr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use typed_arena::Arena;
const N_BOUND: usize = 115;
const FUEL: u64 = 200;
#[derive(Clone, Copy)]
enum InputNode {
S,
K,
I,
B,
App(usize, usize),
}
enum Side {
Root,
Left,
Right { left: usize },
}
struct Input {
nodes: Vec<(Option<InputNode>, Side)>,
variables: Vec<usize>,
apps_left: usize,
primitives_left: usize,
size: usize,
}
impl Input {
fn new(size: usize) -> Input {
Input {
nodes: vec![(None, Side::Root)],
variables: vec![],
apps_left: size - 1,
primitives_left: size,
size,
}
}
}
struct InputTerm<'a>(&'a Input, usize);
impl fmt::Display for InputTerm<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let &InputTerm(input, ix) = self;
match input.nodes[ix].0 {
None => write!(fmt, "?"),
Some(InputNode::S) => write!(fmt, "S"),
Some(InputNode::K) => write!(fmt, "K"),
Some(InputNode::I) => write!(fmt, "I"),
Some(InputNode::B) => write!(fmt, "S(KS)K"),
Some(InputNode::App(x, y)) => match input.nodes[y].0 {
Some(InputNode::App(_, _)) | Some(InputNode::B) => {
write!(fmt, "{}({})", InputTerm(input, x), InputTerm(input, y))
}
_ => write!(fmt, "{}{}", InputTerm(input, x), InputTerm(input, y)),
},
}
}
}
#[derive(Clone, Copy, Debug)]
enum Node<'a> {
S,
S1(&'a Cell<Node<'a>>),
S2(&'a Cell<Node<'a>>, &'a Cell<Node<'a>>),
K,
K1(&'a Cell<Node<'a>>),
I,
B,
B1(&'a Cell<Node<'a>>),
B2(&'a Cell<Node<'a>>, &'a Cell<Node<'a>>),
F,
F1(&'a Cell<Node<'a>>),
N,
App(&'a Cell<Node<'a>>, &'a Cell<Node<'a>>),
Ref(&'a Cell<Node<'a>>),
Input(usize),
}
use Node::*;
struct Evaluator<'a> {
arena: &'a Arena<Cell<Node<'a>>>,
input: Input,
fuel: u64,
}
impl<'a> Evaluator<'a> {
fn whnf<'b>(&mut self, mut node: &'b Cell<Node<'a>>) -> Option<&'b Cell<Node<'a>>> {
loop {
match node.get() {
S | S1(_) | S2(_, _) | K | K1(_) | I | B | B1(_) | B2(_, _) | F | F1(_) | N => {
break
}
App(x, y) => match self.apply(x, y)? {
Owned(node1) => node.set(node1.get()),
Borrowed(node1) => {
if !ptr::eq(node, node1) {
node.set(Ref(node1));
}
node = node1;
}
},
Ref(x) => node = x,
Input(ix) => {
let Input {
nodes,
variables,
primitives_left,
apps_left,
..
} = &mut self.input;
let input_node = if let Some(input_node) = nodes[ix].0 {
input_node
} else if *primitives_left > *apps_left + 1 || *apps_left == 0 {
variables.push(ix);
let input_node = InputNode::S;
*primitives_left -= 1;
nodes[ix].0 = Some(input_node);
input_node
} else {
variables.push(ix);
let len = nodes.len();
let input_node = InputNode::App(len, len + 1);
*apps_left -= 1;
nodes.push((None, Side::Left));
nodes.push((None, Side::Right { left: len }));
nodes[ix].0 = Some(input_node);
input_node
};
node.set(match input_node {
InputNode::S => S,
InputNode::K => K,
InputNode::I => I,
InputNode::B => B,
InputNode::App(ix0, ix1) => App(
self.arena.alloc(Cell::new(Input(ix0))),
self.arena.alloc(Cell::new(Input(ix1))),
),
});
}
};
}
Some(node)
}
fn apply<'b>(
&mut self,
left: &'b Cell<Node<'a>>,
right: &'a Cell<Node<'a>>,
) -> Option<Cow<'a, Cell<Node<'a>>>> {
if self.fuel == 0 {
return None;
}
self.fuel -= 1;
match self.whnf(left)?.get() {
S => Some(Owned(Cell::new(S1(right)))),
S1(x) => Some(Owned(Cell::new(S2(x, right)))),
S2(x, y) => {
let xz = self.apply(x, right)?;
self.apply(&xz, self.arena.alloc(Cell::new(App(y, right))))
}
K => Some(Owned(Cell::new(K1(right)))),
K1(x) => Some(Borrowed(x)),
I => Some(Borrowed(right)),
B => Some(Owned(Cell::new(B1(right)))),
B1(x) => Some(Owned(Cell::new(B2(x, right)))),
B2(x, y) => self.apply(x, self.arena.alloc(Cell::new(App(y, right)))),
F => Some(Owned(Cell::new(F1(right)))),
F1(_) | N => None,
App(_, _) | Ref(_) | Input(_) => unreachable!(),
}
}
fn eval_number(&mut self, node: &Cell<Node<'a>>) -> Option<usize> {
self.fuel = FUEL;
let node = self.apply(node, self.arena.alloc(Cell::new(F)))?;
self.fuel = FUEL;
let node = self.apply(&node, self.arena.alloc(Cell::new(N)))?;
let mut node = node.as_ref();
for n in 0..N_BOUND {
self.fuel = FUEL;
match self.whnf(node)?.get() {
N => return Some(n),
F1(node1) => node = node1,
_ => break,
}
}
None
}
}
fn search(found: &[AtomicUsize], mut input: Input) {
'outer: loop {
let mut evaluator = Evaluator {
arena: &Arena::new(),
input,
fuel: FUEL,
};
let n = evaluator.eval_number(&Cell::new(Input(0)));
input = evaluator.input;
if let Some(n) = n {
if found[n].fetch_min(input.size, Ordering::Relaxed) > input.size {
println!("{} {} {}", n, input.size, InputTerm(&input, 0));
}
}
loop {
if let Some(&ix) = input.variables.last() {
let len = input.nodes.len();
let node = &mut input.nodes[ix].0;
match node {
None | Some(InputNode::B) => unreachable!(),
Some(InputNode::S) => *node = Some(InputNode::K),
Some(InputNode::K) => *node = Some(InputNode::I),
Some(InputNode::I) => {
input.primitives_left += 1;
if input.apps_left > 0 {
*node = Some(InputNode::App(len, len + 1));
input.apps_left -= 1;
input.nodes.push((None, Side::Left));
input.nodes.push((None, Side::Right { left: len }));
} else {
*node = None;
input.variables.pop();
continue;
}
}
&mut Some(InputNode::App(x, y)) => {
input.apps_left += 1;
*node = None;
input.nodes.pop();
assert_eq!(y, input.nodes.len());
input.nodes.pop();
assert_eq!(x, input.nodes.len());
input.variables.pop();
continue;
}
}
match &input.nodes[ix] {
(Some(InputNode::I), Side::Left) => continue,
&(Some(InputNode::K), Side::Right { left: l }) => {
if let Some(InputNode::S) = &input.nodes[l].0 {
continue;
}
}
_ => (),
}
break;
} else {
break 'outer;
}
}
}
}
fn main() {
const MAX: AtomicUsize = AtomicUsize::new(usize::MAX);
let found = [MAX; N_BOUND];
for size in 1..10 {
search(&found, Input::new(size));
}
for size in 10.. {
(0..size - 5).into_par_iter().for_each(|b_depth| {
for i_depths in 1..1 << (b_depth + 1) {
let mut input = Input::new(size);
for i in 0..b_depth + 1 {
input.nodes.push((None, Side::Left));
input.nodes.push((None, Side::Right { left: 2 * i + 1 }));
input.nodes[2 * i].0 = Some(InputNode::App(2 * i + 1, 2 * i + 2));
input.apps_left -= 1;
}
input.nodes[2 * b_depth + 2].0 = Some(InputNode::B);
input.apps_left -= 3;
input.primitives_left -= 4;
for i_depth in 0..b_depth + 1 {
if i_depths & 1 << i_depth != 0 {
input.nodes[2 * i_depth + 1].0 = input.nodes[2 * i_depth + 2].0;
input.nodes[2 * i_depth + 2].0 = Some(InputNode::I);
input.primitives_left -= 1;
}
}
search(&found, input);
}
});
}
}
```
Output for all numbers 0, …, 114:
```
0 2 KI
1 1 I
2 6 S(S(KS)K)I
3 9 S(K(SS(S(SS)I)))K
4 9 SII(S(S(KS)K)I)
5 11 S(S(SS)S)S(S(KS)K)I
6 11 SII(SSS(S(KS)K))I
7 13 S(SI)S(SSK(S(S(KS)K)))I
8 12 S(S(KS)S)I(S(S(KS)K))I
9 12 SII(SS(K(S(S(KS)K))))I
10 13 SI(SS)(SSK(S(S(KS)K)))I
11 13 S(SS)S(SSK(S(S(KS)K)))I
12 11 S(S(SI))I(S(S(KS)K))I
13 12 S(S(SS)I)I(S(S(KS)K))I
14 13 SS(SS)(SSK)(S(S(KS)K))I
15 14 S(SI)(S(SSK(S(S(KS)K))))II
16 10 S(S(SI))(S(S(KS)K))I
17 14 S(SS(K(S(S(SI)))))S(S(KS)K)I
18 13 SS(SS)(SS)(K(S(S(KS)K)))I
19 15 SS(SS(SS)(SS))(K(S(S(KS)K)))I
20 12 S(S(SIS))I(S(S(KS)K))I
21 14 S(SSK)(S(SIS))(S(S(KS)K))I
22 13 S(SSI(SSS))S(S(KS)K)I
23 13 S(S(SI))(SSK)(S(S(KS)K))I
24 14 S(S(S(S(SS))K))I(S(S(KS)K))I
25 13 SS(S(SSK)S)(S(S(KS)K))I
26 14 S(S(SS)S)(SS(KI))(S(KS)K)I
27 12 SSS(SS)(K(S(S(KS)K)))I
28 14 SS(SSS(SS))(K(S(S(KS)K)))I
29 14 S(S(S(S(SI))I))S(S(KS)K)II
30 15 S(S(SS(S(SS)K)))S(S(KS)K)II
31 14 SIS(S(SII)(K(S(S(KS)K))))I
32 14 SS(S(S(SI))S)(K(S(S(KS)K)I))
33 14 S(S(SSI))(SSK)(S(S(KS)K))I
34 15 SI(S(SS))(S(SSK))(S(S(KS)K))I
35 15 S(S(SI))(S(SSS)K)(S(S(KS)K))I
36 12 SI(SI)(SSS(S(KS)K))I
37 14 SII(S(S(SS)S)S(S(KS)K))I
38 16 S(S(S(S(S(K(SSK))))I))S(S(KS)K)I
39 12 SSS(SSS)S(S(KS)K)I
40 13 S(S(S(SSI))S)S(S(KS)K)I
41 15 S(SS(S(S(SSI))S))S(S(KS)K)I
42 13 S(S(SS(KI)))I(S(S(KS)K))I
43 15 SI(SIS)(S(SI)(K(S(S(KS)K))))I
44 16 SIS(S(SS)K(SSK(S(S(KS)K))))I
45 15 S(S(S(SI)))(SSS)(K(S(S(KS)K)))I
46 16 S(SI)(S(S(SSS)K(S(S(KS)K))))II
47 16 S(S(SIK))S(SSK(S(S(KS)K)))II
48 16 S(SS(S(S(S(SS)I))))K(S(S(KS)K))I
49 15 SS(S(S(SS))(SSK))(S(S(KS)K))I
50 14 SSS(S(S(SI))S(S(KS)K))II
51 15 S(SS(SS))I(SSK(S(S(KS)K)))I
52 15 SSS(SSI(S(K(S(S(KS)K)))))II
53 17 SS(S(SS(SS))I)(SSK(S(S(KS)K)))I
54 13 S(SI)S(SS)(K(S(S(KS)K)))I
55 15 SS(S(SI)S(SS))(K(S(S(KS)K)))I
56 13 S(S(SS)(SSS))S(S(KS)K)I
57 15 S(SS(S(SS)(SSS)))S(S(KS)K)I
58 17 SSS(S(S(S(SIK))))(K(K(S(S(KS)K))))I
59 18 S(S(S(S(SIS(S(SS))K)))S)S(S(KS)K)I
60 17 S(SS(SS(KI)))(SSK)(S(S(KS)K))II
61 14 S(S(S(S(SS)I))S)S(S(KS)K)I
62 16 S(SS(S(S(S(SS)I))S))S(S(KS)K)I
63 15 S(SS)S(SI(SSK(S(S(KS)K))))I
64 13 S(SSS)S(K(S(S(KS)K)I))I
65 15 S(SS)K(S(SS)S(K(S(S(KS)K))))I
66 16 S(SS(S(S(S(SIS)))))K(S(S(KS)K))I
67 16 S(S(S(S(S(SS))I)))S(K(S(S(KS)K)))I
68 15 SIS(S(SSS(K(S(S(KS)K)))))II
69 18 SS(SI(K(SI)))(SS(SSK)(S(S(KS)K)))I
70 17 S(S(S(S(S(SI)(S(KS)))))S)S(S(KS)K)I
71 18 SIS(S(S(SSK))(S(SI)S)(S(KS)K))II
72 14 S(SS)S(S(SI)(K(S(S(KS)K))))I
73 16 SS(S(SI)(SS)(SS))(K(S(S(KS)K)))I
74 15 S(S(SI)(S(SSS)S))S(S(KS)K)I
75 17 S(SS(S(SI)(S(SSS)S)))S(S(KS)K)I
76 16 SS(SSS)(S(SIK))(K(S(S(KS)K)))I
77 17 S(SS(SI(SI)))(SSK)(S(S(KS)K))II
78 18 S(SI)(S(S(SI)I)S)(SI(K(S(S(KS)K))))I
79 17 S(S(S(SI(KK))))S(SSK(S(S(KS)K)))I
80 14 S(SIS)(S(SI)I)(S(S(KS)K))I
81 12 SIS(SS(K(S(S(KS)K))))I
82 16 SS(S(K(SIS))(SS))(K(S(S(KS)K)))I
83 16 S(S(SSI)(S(KS)S))K(S(S(KS)K))I
84 15 SIS(SSK(SI(K(S(S(KS)K)))))I
85 14 S(S(S(SS)I)I)I(S(S(KS)K))I
86 15 S(SS)S(SS(K(K(S(S(KS)K)))))II
87 15 SS(S(SIS))(SSK)(S(S(KS)K))I
88 15 S(SI)(S(S(SSK))I)(S(S(KS)K))I
89 17 SI(S(SSI)K)(S(SI)(K(S(S(KS)K))))I
90 16 SI(S(SI))(S(SSS)K(S(S(KS)K)))I
91 15 S(SIS)(S(SSK)I)(S(S(KS)K))I
92 15 SI(S(SIS))(SSK(S(S(KS)K)))I
93 18 S(SI)S(SIS(S(K(SSK(S(S(KS)K))))))I
94 17 SS(SI(S(SIS)))(SSK(S(S(KS)K)))I
95 18 S(S(S(S(S(SI)))S)S)(SIS)(S(KS)K)II
96 16 SIS(S(S(SSI)(K(S(S(KS)K)))))II
97 16 S(S(S(SS)I))(SSS)(K(S(S(KS)K)))I
98 15 S(SS)(SSS)(SI(K(S(S(KS)K))))I
99 16 S(SI)S(SIK(SSK(S(S(KS)K))))I
100 15 SIS(S(S(SS)K(S(S(KS)K))))II
101 16 S(S(S(S(SIS)(KS)))S)S(S(KS)K)I
102 17 S(SI(S(SS)))S(SI(K(S(S(KS)K))))II
103 15 S(S(SI)S(SS(KS)))S(S(KS)K)I
104 15 SIS(SSI(S(K(S(S(KS)K)))))II
105 17 S(S(S(S(S(SSS)))K))S(K(S(S(KS)K)))I
106 17 S(S(S(S(S(SS(KI)))I))S)S(S(KS)K)I
107 19 S(S(SSS(SIS))(S(SI)))S(K(S(S(KS)K)))I
108 14 S(S(K(SSS))(SI))S(S(KS)K)I
109 16 SSS(S(S(SSK))(K(S(S(KS)K))))II
110 16 SSK(S(SSS(K(S(S(KS)K)))))III
111 17 S(S(S(S(S(SS)I))S)(KI))S(S(KS)K)I
112 16 S(SSS)(S(S(S(SS))S)S)(S(KS)K)I
113 18 S(SS(S(S(S(S(K(S(SI))))))S))S(S(KS)K)I
114 18 S(SS)S(SI(SSK(S(K(S(S(KS)K))))))II
```
[Answer]
# [5844 SKIs](https://tio.run/##7ZvBjtowEIbveYqR9uAZwSJob6k49RRxzBEh5ISkZDc4kRPasC9PnTgJpuyqPXTVLRoO8Nn5ZzLjcQYh5PJU7wv1@RzCEnJ5iHYSGn@g00gvPjT4Qngyb@St3hA3XnB1pfG8XZJCKXWVbKvnDCvyPYCqlvGzEa6DjRmlhYYYMgVVew0gS@1QhKtA@Fa8flxsjMHImHyXOcYmlNYiyTub5RIEDhYzWZaJ2mFwIyEjiQZns7Iokb6A/HXiyonEqLuVTuqjVpcwbHpVXOgxvVFzPOAlDSdJskZ1sY1RdcthIlOjXb94qe8sY4pW/bggTAkbN5bX9E13h1QXh/EevVqho5oYd/M@nE6cY@6Kc3ytxuveb0ObyYlwvTEeHsAkCUlT6qSqskJVUKTwdX/U8R7mU1hM4ZP3UOpM1dhbX7aEMMtDJqM3r//mcoghrkJakdXdxNItfR@L3O2y2sx5xnJrBqboV56Mn9bb4JFIkC1WUtXb3gblFKJLnSVM2t20HJZ7UHUVk0QWIicFmed467ALU7Y7REv1LcHF3E5FV1Ntgq3Z/se2zdDEL4Q4hzhEPH5ieJWIyWtlPgIMHSUT039JAf2tF/Kjw8TE9B7NhTsPExPTXfYvbmNMTEzcxpiYmJg@fJPjPsc7ibfBBykHl4CJ6X6/gfn5ZmJi4l8U3OeYmJjuuQtyI2RiYuJ/wpiYmLjt/Gm74d7y76t3FkLMjmWZaKT@eAkshyNBzuGty8ETIs8eZrFzw8i4eSoyhfFeY0zOoSerGmVhe2LKF1P36JTr/PwT)
## The Baseline
In order to respect your scrolling fingers, I won't copy & paste it here. The 5,844 score is the SKI count; it doesn't even include all the parentheses. But please do [try it online](https://tio.run/##7ZvBjtowEIbveYqR9uAZwSJob6k49RRxzBEh5ISkZDc4kRPasC9PnTgJpuyqPXTVLRoO8Nn5ZzLjcQYh5PJU7wv1@RzCEnJ5iHYSGn@g00gvPjT4Qngyb@St3hA3XnB1pfG8XZJCKXWVbKvnDCvyPYCqlvGzEa6DjRmlhYYYMgVVew0gS@1QhKtA@Fa8flxsjMHImHyXOcYmlNYiyTub5RIEDhYzWZaJ2mFwIyEjiQZns7Iokb6A/HXiyonEqLuVTuqjVpcwbHpVXOgxvVFzPOAlDSdJskZ1sY1RdcthIlOjXb94qe8sY4pW/bggTAkbN5bX9E13h1QXh/EevVqho5oYd/M@nE6cY@6Kc3ytxuveb0ObyYlwvTEeHsAkCUlT6qSqskJVUKTwdX/U8R7mU1hM4ZP3UOpM1dhbX7aEMMtDJqM3r//mcoghrkJakdXdxNItfR@L3O2y2sx5xnJrBqboV56Mn9bb4JFIkC1WUtXb3gblFKJLnSVM2t20HJZ7UHUVk0QWIicFmed467ALU7Y7REv1LcHF3E5FV1Ntgq3Z/se2zdDEL4Q4hzhEPH5ieJWIyWtlPgIMHSUT039JAf2tF/Kjw8TE9B7NhTsPExPTXfYvbmNMTEzcxpiYmJg@fJPjPsc7ibfBBykHl4CJ6X6/gfn5ZmJi4l8U3OeYmJjuuQtyI2RiYuJ/wpiYmLjt/Gm74d7y76t3FkLMjmWZaKT@eAkshyNBzuGty8ETIs8eZrFzw8i4eSoyhfFeY0zOoSerGmVhe2LKF1P36JTr/PwT)!
### Generating Lambda Calculus
```
def church_numeral(n):
return r'(\f.\x. '+'f('*n +'x'+ ')'*n+')'
def church_list(lst):
acc = r'\c.\n.'
for l in lst:
acc+='(c '+l+' '
acc+='n'+')'*len(lst)
return acc
def church_numeral_list(lst):
nums = [church_numeral(l) for l in lst]
return church_list(nums)
print(church_numeral_list([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]))
```
* The function `church_numeral` generates a number of the form: `\f. \x. f (f (f x))`.
* The function `church_list` generates a list of the form: `\c. \n. c 0 (c 1 (c 2 n)` which is precisely the format a right-fold list takes [as per Wikipedia](https://en.wikipedia.org/wiki/Church_encoding#Represent_the_list_using_right_fold).
* The function `church_numeral_list` just converts the numbers to Church numerals and sends them over to be list-churchified.
If anyone would like to strategically compile the lambda calculus to SKI, here's [a link](https://tio.run/##bU9BDoIwELzzir1taw2xQiIx8SVgDKkQSOpCSknw9bggKhp7mLSz05nZ9u6rhqLxWpRgqt6Z6kL9rXC5FSSPAfBxhe8dgUORlWE2hIAKS4EbAoUDKkDJd8UYBCsXW3de2M4vJrkxcGKPzIQZhThzZePAQk3AsqdqUaoTCsMxViFg8CEJp5iNLWh2XrdjwVf8ssRvDaY77pH@rGrlV5nz2nm9z/Rdjq2ryYt/QelhvwW90xMkL9D8jOMtRDxLDguhdfwW7XgWnaUcxwc) to the output on TIO. The lambda calculus it generates is totally naive; it doesn't attempt to optimize anything, as you can tell.
### Compiling to SKI
This part was super hacky. I used the intermediate form generated by [this site](https://crypto.stanford.edu/%7Eblynn/lambda/crazyl.html)– the first *lambda2ski* compiler I could find. That site is actually a compiler from the lambda calculus into WebAssembly, which seems totally out of left field!
That's why the output I used was just the intermediate form which the site luckily spits outs as well. There may be more efficient compilers, I don't know. Even still, there was one more issue, the output — *I mean intermediate form* — also used the `B` & `C` combinators. Those took me a while to find, but eventually I found their translation into SKI [here](https://en.wikipedia.org/wiki/B,_C,_K,_W_system) on good ol' Wikipedia.
So just two more lines of code left:
```
B = "S(KS)K"
C = "S(S(K(S(KS)K))S)(KK)"
ski = ski.replace('B', B)
ski = ski.replace('C', C)
```
### A bad bug
Just kidding! There's a bug in the very last step. And there are no SKI interpreters to help you out. Just Bubbler's TIO link which spits out nasty and nonsensical python errors at you. Or maybe it seems to do run fine, only to output `<function <lambda> at 0xmadbadhex>`.
Can you spot it?
The `B` & `C` combinators need to be wrapped in parentheses. So it should really be:
```
B = "(S(KS)K)"
C = "(S(S(K(S(KS)K))S)(KK))"
ski = ski.replace('B', B)
ski = ski.replace('C', C)
```
And now you've built your very own hello-world app in SKI and successfully deployed it to TIO!
] |
[Question]
[
**About geohash**
Geohash is one of many encoding systems for geographic positions. Geohash positions have some advantages. It provides a short code instead of the two usual numbers for latitude and longitude.
[](https://i.stack.imgur.com/eiF8E.png)
**The challenge**
Given two numbers, the latitude and longitude, compute and return or print the geohash string of length 8. A longer geohash would give more accurate positions, here we use length 8. Latitudes and longitudes are given as floating point numbers (degrees). Latitudes are between -90 and +90 (south to north) and longitudes between -180 and +180 (west to east).
**Algorithm with example**
A geohash code is a base32 encoded bitstring. In this example the conversion goes the other way than the challenge, we convert geohash `ezs42` into latitude and longitude. Geohashes uses a set of 32 digits represented by 5 bits. The 32 digits are `0 – 9` for the first 10 and the lower case letters between `b – z` except `i`, `l` and `o` for the next 22. That is: `0123456789bcdefghjkmnpqrstuvwxyz`.
The first char in `ezs42` is e which is at the 0-indexed position 13, which has the 5 bits 01101. The chars have these bits:
* `e` → 13 → *01101*
* `z` → 31 → *11111*
* `s` → 24 → *11000*
* `4` → 4 → *00100*
* `2` → 2 → *00010*
When joining the bits we get *0110111111110000010000010*.
Starting from left, the even bits (2nd, 4th, 6th, ...) are for latitude (*101111001001*) and the odd bits (1st, 3rd, 5th, ...) are for longitude (*0111110000000*).
With each bit we go left or right to narrow down the number by halving the range. The first bit of the longitude bits (`0`) are used to decide if the longitude is between -180 – 0 or 0 – 180. Bit `0` means we go left, that is -180 – 0. The next bit of the longitude decides if we chose -180 – -90 or -90 – 0. Since it's `1` here we go right for the next range: -90 – 0. For every bit we go left(0) or right(1) halving the min-max range. When all bits are spent, we return the mid position (average) of the last min and max.
We repeat for latitude, except now we start at choosing between -90 – 0 and 0 – 90 with the first bit.
The latitude for *101111001001* becomes +42.605.
The longitude for *0111110000000* becomes -5.603.
This example is taken from <https://en.wikipedia.org/wiki/Geohash#Algorithm_and_example> which has a more visual walk-through.
When encoding 0° (equator or zero meridian) you can choose between 01111... and 10000... The <http://geohash.co/> site have chosen 01111...
**Test cases**
```
(+48.8583, +2.2945) → u09tunqu # Eiffel Tower
(+40.68925, -74.04450) → dr5r7p62 # Statue of Liberty
(+29.9753, +31.1377) → stq4s8cf # The Great Sphinx at Giza
(-22.95191, -43.21044) → 75cm2txp # Statue of Christ, Brazil
(+71.17094, +25.78302) → usdkfsq8 # North Cape
(+90, +180) → zzzzzzzz # North Pole
(-90, -180) → 00000000 # South Pole
(+42.605, -5.603) → ezs42s00 # Léon, Spain from example above
```
More tests can be created or checked with <http://geohash.co/> and Google Maps.
(GPS positions are also often written as degrees, arcminutes and arcseconds. The position of the Eiffel Tower is latitude 48° 51' 29.88" N, longitude 2° 17' 40.20" E. For north (N) and east (E) positive numbers are used so we get position [48 + 51/60 + 29.88/3600, 2 + 17/60 + 40.20/3600] = [+48.8583, +2.2945]. Geohash codes can be stored and indexed in databases for quick proximity searches. Nearby positions share the same code prefixes, but edge cases needs to be dealt with. A single index search on the geohash code on one or a small set of code prefixes is normally much quicker than using two indexes, i.e. one for latitude and one for longitude.)
[Answer]
# [Python 3](https://docs.python.org/3/), 250 bytes
```
lambda b,a:(lambda l:"".join("0123456789bcdefghjkmnpqrstuvwxyz"[int("".join(map(str,l[i*5:][:5])),2)]for i in range(8)))(sum(zip(f(a,180,-180),f(b,90,-90)),()))
f=lambda a,u,l,p=20:p and([1]+f(a,u,(u+l)/2,p-1)if u+l<a*2else[0]+f(a,(u+l)/2,l,p-1))or[]
```
[Try it online!](https://tio.run/##Nc5NboMwEAXgfU9hsZoJEwoGUoPKSVwWpsHEqTEuP22Ty1PSJpvRPOl70vOX@TS4dO2qt9Wqvjkq1pAq4f7bMgii82AcBHHC0yw/vIiieT@2ujudP3rnP8dpXr6@fy7XQBo3w4P3ysM0j2Sl2eVlLcu8RiSOtR5GZphxbFSua0EgIkxLD1fjQYOiRMS03w6ShoaKLRTx1oTNPenqPkvRQpZ8xePSM@WOIJM6vLUXgiW0@MzJ7xM0mm3pVe14a6dWxv/mIeyfwWGU9erH2/gOwkxEIhcpsZBHvMhyxPUX "Python 3 – Try It Online")
I think using named functions would probably be better... anyway. I don't have time to golf this further yet, so just posting it here first.
[Answer]
# [Perl 5](https://www.perl.org/) (`-ap -MList::Util+sum`), 136 bytes
```
@a=([-90,90],[-180,180]);map{$y=0;$a[--$|][$,=$F[$|]<($m=.5*sum@{$a[$|]})]=$m,$y+=$y+!$,for 0..4;$\.=(0..9,grep!/[ilo]/,b..z)[$y]}0..7}{
```
[Try it online!](https://tio.run/##DY29DoIwFEZfBZI7gLaXijTyYxMmJx2daoeaoCGh0gAOiLy6tcNJTr4zfLYZOu5crUUkacFIwRSRdJcz4lFxZbRdYBasAi0pha@SQAScpLdjBEYg34xvUy8@@2mNlQBDYN4KTwjk0Q8BQ8wquKGIvBXkOTQ2TGTb9Sohd8RPLGFWq2@HdXEuyzHn@T5IMS0y/uvt1Pav0VFtHb2c23Eqy@vUdlv/@gc "Perl 5 – Try It Online")
[Verify all test cases](https://tio.run/##FY/NbsIwEITvfgojWQKKvaz/cExqiVNP7ZGTySGVoIpEmojQQ0rz6k23h9GMdrS7@vrz7ernoR7FqbmIUylOabks2/FQl/OhTqusIsqIlcxKFyhJ1bps6/4hxoSlqLNS4qfKQibxkik9r0SbwD8NX@3hQTWNpnWVRCvFuEmkhZCX7sYRwNEzSCtKUX7czv1im5trV23lO8D3OouxmqgL02OeXQGFLyw3YKLzzCHsimg8V8EBOueRmQgxeMutBm1DYIE8YHTceAiFRcOUMRC9jporZ8Fo2mMRORExYuT/eMwZ2CGd9WT2t@vvTfc5zKruZ/X22gz3/f54b64bgqOBB9R/ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~64~~ ~~63~~ ~~61~~ ~~42~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
90x‚R/>19o*î<Dd*b20jð0:SÅ=5ôJCžhA«„ŠÙaмsè
```
-19 bytes by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/212394/52210), so make sure to upvote him as well!
-1 byte by taking the input in reversed order.
[Try it online](https://tio.run/##AVAAr/9vc2FiaWX//zkweOKAmlIvPjE5byrDrjxEZCpiMjBqw7AwOlPDhT01w7RKQ8W@aEHCq@KAnsWgw5lh0Lxzw6j//1stNS42MDMsNDIuNjA1XQ) or [verify all test cases](https://tio.run/##JY2xSgNBEIZf5bhKs3vj7OxOdkc0hyRVSi2PKxIU1CZFQEyXRh/ALhZiGQiEFClFwSW9z3Avcu5pNT8f3//PbD6Z3t20D4syz5rnlywvF63gY7N8vTwZGJn14vZsdN2bEt7HHZ5exadzjvvx8PB5e/G9aZZvh/e4mvx8zOO6HZXjPDuKX8e5bqtKEZA41soFCBxsravCO0DnGBNE6AchTlRZA8Z6rxUJiOc/01kgk1xdEIGwEdOZxOCDRdLKp45HcR01IQ0KdrUuFv@RoY82PaJ0ua5/AQ).
**Original ~~64~~ ~~63~~ ~~61~~ 60 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
εd©ˆ¾ƵΔN>÷‚19FÐÆÄ;UÅmyÄ‹®Qˆε¯θ®QNÊiXNi-ë+]¯Å=5ôJCžhA«„ŠÙaмsè
```
[Try it online](https://tio.run/##AYIAff9vc2FiaWX//861ZMKpy4bCvsa1zpROPsO34oCaMTlGw5DDhsOEO1XDhW15w4TigLnCrlHLhs61wq/OuMKuUU7DimlYTmktw6srXcKvw4U9NcO0SkPFvmhBwqvigJ7FoMOZYdC8c8Oo//9bLTUuNjAzLDQyLjYwNV3/LS1uby1sYXp5) or [verify all test cases](https://tio.run/##JY0/S8NAGMa/SsikJHfc314O0SCKQ4eAgyKEDBEFA2qHghCnDG0GJxEXHcRRKbRLgwpS4V7qUgh@hnyReNHpffjxe553MEyPs9P2Kg9dpynvHDfM3bauTszrqjSL76q@j7bgrSkeqd6DWyhhtHEA44scRk3xYab7q7KuzKx@tzGCm@woyhBMvMTMYLwpYd7fWS7Ots2kKZ6Wz/CQ/nwO4aV18eFu2HedNfhad30zb@PYY5hpIX1PBDiQAU/8GCmBiRCSWEhwL9BMWupxiilXyveYxlrJP1NwzKh1fcQY1pJq2plMYhVwwnxP2Y4iWnSUBnZQk67WRfQfJe4Rbh8xe2WStAhdDtB5ep3/Ag).
Both take the input as `[longitude, latitude]` and output as a list of characters.
**Explanation:**
```
90 # Push 90
x # Double it to 180 (without popping)
‚ # Pair them together: [90,180]
R # Reverse it: [180,90]
/ # Divide the (implicit) input-pair by these
> # Increase both by 1
19o # Push 2^19: 524288
* # Multiply both decimals by this 524288
î # Ceil both to an integer
< # Then decrease them by 1
# (ceil + decrement cannot be floor, if they already are integers)
Dd # Create a copy, and check if it's >=0 (1 if >=0; 0 if <0)
* # Multiply this to the pair (-1 becomes 0, else it stays the same)
b # Convert both integers to a binary string
20j # Pad them with leading spaces up to a length of 20
ð0: # Replace all spaces with 0s
S # Convert it to a flattened list of digits
Å= # Shuffle this list ([a,b,c,d,e,f] → [a,d,b,e,c,f])
5ô # Split this into parts of size 5
J # Join each inner list together to a string
C # Convert each binary string to a base-10 integer
žh # Push builtin "0123456789"
A« # Append the lowercase alphabet
„ŠÙa # Push dictionary string "oila"
м # Remove those characters from the string
s # Swap to get the list of integers at the top again
è # And (0-based) index them into the string
# (after which the list of characters is output implicitly
```
```
ε # Map both values in the pair to:
d # Pop and check if it's non-negative (1 if >=0; 0 if <0)
© # Store this in variable `®` (without popping)
ˆ # And pop and add it to the global_array
¾ # Push 0
ƵΔ # Push compressed 180
N # Push the 0-based map-index
> # Increase it by 1 to make it 1-based
÷ # Divide the 180 by this (longitude=180; latitude=90)
‚ # Pair it together with the 0
19F # Loop 19 times:
Ð # Triplicate the current pair
ÆÄ # Pop one, and get the absolute difference
; # Halve this
U # Pop and store this halved difference in variable `X`
Åm # Pop another copy, and take its average
‹ # Check that it's smaller than
yÄ # the absolute value of the current map value
# (1 if truthy; 0 if falsey)
®Q # Check if this is equal to `®`
# (this will invert the boolean for negative values)
ˆ # Pop and add this to the global_array
ε # Map over the third pair:
¯θ # Push the last value of the global_array
®Q # Check it this is equal to `®`
# (to invert for negative values again)
NÊi # If this is NOT equal to the 0-based inner map-index:
X # Push variable `X`
Ni # If the 0-based inner map-index is 1:
- # Subtract `X` from the current value we're mapping over
ë # Else:
+ # Add it instead
] # Close both if-statements, both maps, and the loop
¯ # Push the global_array
Å=5ôJCžhA«„ŠÙaмsè # Same as above
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„ŠÙa` is `"oila"` and `ƵΔ` is `180`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes
```
F²⊞υ⌈×X²¦¹⁹⊕∕N×⁹⁰⊕ιUMυ◧⎇‹ι²ω⍘⊖ι !²⁰⭆⪪⭆²⁰⭆⮌υ§λι⁵§⁺⭆χλΦβ¬№ailoλ⍘ι !
```
[Try it online!](https://tio.run/##VY/dTsMwDIXv9xShV67IUBco0rQr6IRUaUwV2wtkrccipUmVnw6evrhUiC43lu3j75zUF@lqK/UwnK1jIFJWRX@ByFmBSivzCUfVoofKXtGB4Gy1TjkrTe2wRROwga3qVYNQmi6GfWxPJCPFdLXObrUqnd5m8S67wratNM3oVclmh@cAR3RGum/YofegOBNEunL2Kj0eghvTbHFO4yxhd0lKVWQjtSJNgElKDnDotJr3gvL8dx/Yo/MIke5fQmka/ALN2RiSs3w2rHT0M8qKKJrWb0oH@u2Js70NUNhI3olU2ibj/pcyS67@wqabYbh/Eg/PWb5Y5lQeh2WvfwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υ⌈×X²¦¹⁹⊕∕N×⁹⁰⊕ι
```
Input both numbers. Divide the first by 90 and the second by 180, then increment both, then multiply by 524288, then round up.
```
UMυ◧⎇‹ι²ω⍘⊖ι !²⁰
```
If the result is greater than 2, then decrement and convert to base 2 using a custom digit set, and pad to 20 "digits". (This doesn't work for 0 because it would become negative and it doesn't work for 1 because of a bug in the version of Charcoal on TIO.)
```
⭆⪪⭆²⁰⭆⮌υ§λι⁵§⁺⭆χλΦβ¬№ailoλ⍘ι !
```
Shuffle the bits, split into groups of five, decode each group from base 2 using the same digit set, then look up the digit in a table of digits and letters excluding `ailo`.
[Answer]
# [R](https://www.r-project.org/), ~~149~~ ~~147~~ ~~144~~ 128 bytes
*Edit: -16 bytes thanks to Giuseppe, by using more code-efficient matrix operations (`rbind`, `%*%`)*
```
function(l,m,d=function(x)((x+180)*5825.422)%/%2^(20:1)%%2)c(0:9,letters[-c(1,3:5*3)])[1+2^(4:0)%*%matrix(rbind(d(m),d(l*2)),5)]
```
[Try it online!](https://tio.run/##dZFPitswFIf3cwrBYJBiRZVlKbYCs@lQZjOUwsxumIJiy7WobTmy3Lo5QA/QW/QcvUkvkto4idNC30Z/0Pfje0/u@EnbUnXl3bHom8wb28AK1zi/uxwHBOEQRilFK5EyQThjKHgTsI@Q0W2EgoChDNKtxJX2XrvuZZ3BCMdbsYrRK3qJwvEl31IUrIJaeWcG6HamyWEOa4RzWK0YQlig17MJDHlKUpHGGISMMMkFAlPdgt/ff4CeSt83@36@eWeKQlfg2X7V7mbhKdmkkgkM1gknlHNB0ZnPnXBJu2ETH3JGNlTcgievfK@BLcCj2Wnnvy1ZTBKZiMkljkgUJwlaXDq/512aFfPNc6nBg9PKg6e2NM0Axt2DOaglKxkTEir51JggSRpTdvHqu/xz0e3TOeu9db4E96rVF3rNGJEiktHYFY8Ji8a@LnQispr5oZ3ppZ370pnOY/DWqYOpFhNJR4fpS8F1zVmHU12bfLDVlclEr/9D01OdTGz/L30a@pggxjVGf9H60HHWnenHXz9tg8dxKtOAwtka6EHVbaWB2tkv@ub4Bw "R – Try It Online")
Outputs vector of characters.
**How?** (before Giuseppe's golfing)
```
geohash=
function(l,m, # l=latitude, m=longitude
d=function(x) # d=helper function to calculate bits from lat or long
((x+180)*5825.422) # scale by 5825.422 == 2^20/180
%/%2^(20:1)%%2 # convert to binary bits
)
c(0:9, # encode using digits 0..9, joined to
letters[-c(1,9,12,15)]) # letters except a,i,l,o
[1+ # 1-based indexing
colSums( # sums of each column of matrix
# columns represent each 5-bit character
matrix( ... ,5,8) # format numbers into matrix with 5 rows & 8 columns
t( # using transpose of
matrix( # matrix of
c(d(m),d(l*2)),,2)# longitude bits, latitude bits x2, in rows
)
*2^(4:0))] # times powers of 2 to convert sums to numbers
```
[Answer]
# [Python 3](https://docs.python.org/3/), 174 bytes
```
f=lambda a,b,c='',n=1,x=0,y=0,z=(-45,45):n<7**7and f(a,b,c+'%i%i'%(b>y,a>x),n*2,x+z[a>x]/n,y+z[b>y]/n*2)or c and'0123456789bcdefghjkmnpqrstuvwxyz'[int(c[:5],2)]+f(*z,c[5:],n)
```
[Try it online!](https://tio.run/##dZNRjpswEIbfOcVI1QoIDjXGDhCVfWi13ZdVW2n3LcoDEFPcJYYY0wUO0AP0Fj1Hb9KLpN40WW3T7UjWDPZ8499j0466amS435dpnW3zTQYZylGR2jaSaYCGFKPRjCl15pQhytylfBPNZlEmN1A6h1zPvhAXwr5w8ssRZZeDi@SMoMGbVuZj/Vqi0YRmzYQz4jYKCjC0jQMSUraI4iQvNrz8XH2538p2pzrdf30YxsleCamdYrVka0TctVc6swkVK7ZcI@nuHypRc7hTPV9aAFqNjw5AyDY1o9eO63dtLYw/zBuh6TZrnbJuMo1MxmpJ1n@WWvW4z@EsLgK7q5q@3kDObfRYbRUe0vhQ8FbD1cf3V0o1agm54tn93qOxH7M4BI/4JKEMDvbr23focaJ7uevhub2CK1GWvIa75oEry6PYX8QJYTCPqI8pZfhIbxRTUbsgZ/StznTPoSnhRuRc6dHySOInETMCwsAPwih6EtDpHe3iojwrcVdxuDbaNdy2lZADmOhaTJk1J8RPWJAEMKehTwIj51gpYsWW6KH9r5h3lRKdRvBWZZOoLS8yUiKcUNMV5kdxiMmpKd3mvux28VmlD43SFbzLWm55CQYviPFfGQd2OtqL7Kem5tbcsPMXWXy08xM0/Yn1KPEX2FwEMy58zvKpo6T7h735@aORyDQxE9LCcLbpEx2dVJtn351UGNV9XYPoavMf/AY "Python 3 – Try It Online")
Keeps track of the average values `x` and `y` for latitude and longitude, respectively. The function increases or decreases these values by steps of `45/n` and `90/n`, where `n` is equal to `2**(current cycle)`. The comparisons are stored in the bit-string `c`. This continues for 20 cycles, until `n` exceeds `2**19`, which is approximated by `7**7`. When this value is reached, it converts the `c` to the final result.
] |
[Question]
[
As we all know, most Pokemon are created by combining some English (or Japanese) words; these words are the Pokemon's "etymology." For example, "charmander" is "char" and "salamander" put together.
Your task is, given a Pokemon's etymology and number, output the original Pokemon name. A short answer will be able to compress the 890 Pokemon into much fewer characters by exploiting the fact that the etymologies and the names themselves use mostly the same characters.
**Input:** The Pokemon number, and an array/list of etymologies, all lowercase
**Output:** The Pokemon's name, also lowercase
The full list of test cases can be found here: <https://pastebin.com/B3rRdiPn>. Each line is a test case with the format:
```
<pokemon number>;<comma separated etymology list>;<pokemon name>
```
This list was created from <https://pokemondb.net/etymology> by running the following code:
```
let collectedRows = [];
let rows = $(".data-table tr").slice(1)
let isOddPrev = false;
// Replacements due to typos, remove 'palindrome' since girafig doesn't come from the word 'palindrome', 'palindrome' is just a descriptor
var repl = {"anacondo": "anaconda", "armadilo": "armadillo", "[palindrome]": ""}
rows.each((_, row) => {
let isOdd = row.classList.contains("odd");
let etym = $(row).find(".cell-etym-word").text().toLowerCase();
if (repl.hasOwnProperty(etym)) etym = repl[etym];
if (isOdd !== isOddPrev) {
collectedRows.push({name: $(row).find(".cell-name").text().toLowerCase(), etymology: [etym], num: parseInt($(row).find(".cell-num").text().replace(/\s/g, ''), 10)});
} else {
collectedRows[collectedRows.length - 1].etymology.push(etym);
}
isOddPrev = isOdd;
});
// Output:
collectedRows.map(pokemon => pokemon.num + ";" + pokemon.etymology.join(",").replace(/\,$/, '') + ";" + pokemon.name).join("\n")
```
**Examples**:
The full list of test cases can be found at the pastebin link, but here are some example inputs and outputs:
```
1, ['bulb', '-saur'] --> 'bulbasaur'
122, ['mr.', 'mime artist'] --> 'mr. mime'
29, ['nidoru' ,'rhino', '♀'] --> 'nidoran♀'
16, ['pigeon'] --> 'pidgey'
17, ['pigeon'] --> 'pidgeotto'
23, ['snake'] --> 'ekans'
```
Note that due to 'nidoran♀' and its family, you need to be able to handle input/output in UTF-8.
The winner is the entry with the highest accuracy, with ties broken by code length. In practice, this means that the challenge is code-golf -- you need to get 100% accuracy to be a competitive entry -- since you can trivially create a lookup table, but feel free to post a sub-100% accuracy answer if you think it does something creative (someone else might extend it to handle the edge cases).
If you wish, you may also include a data file, and the number of bytes of that file is added to your byte count. This is just if you want to keep your code and data separate.
[Answer]
# [JavaScript (Node.js 11.7+)](https://nodejs.org), 100%, 2094 bytes
Same as below, with the data file compressed with Brotli instead of zlib.
```
n=>a=>(require('zlib').brotliDecompressSync(require('fs').readFileSync('a'))+'').split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr(p,++l||9))
```
[Try it online!](https://tio.run/##ZZbJzqTIFUb3/RS/alNVorqYJ1vVVgLJkMkMCQndLZl5noIpQf3u5ZQXli1vI76Iu7k636mjLZoTUI3Lr/2QZj/z@ePHB8imtQLZl8/5/Pnr33/5JZ@/76BaMrFqM@foky@fo8/fPrg1zzPwPQdD9@WT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TOY7zRrbyg5GpNcwxytUq6BIu/eRAZLp6HeunQfGm0go8iQ7fdKuz@5U48vSAsFLcOD1reCRt@YeGPzy7uUrdmq9TjdtyKSVCzmTZmGfr4JC84ObEFh4@ZkwCj1ROLUsqNG18WN/Ga0@Oa45fJlPzCn1zNWRYLykCKpclxx0OKN93TfhhmSZXkQieDKBE6s2e@DogCX1amgTLYjx2h8hUmEd2iapnqgJ7l8NijcPZSem8iBxsdU3qSQvg4aoHWm@K6SaAvxVyG1oSKpXzmz9GZUjnKzg4H0Jr8/kiU393BOmdn9EWyU2IBhOsGBDZHnN6C1QEPulsDfx2XY6dwsUD593SezyviR2WDDz2UZxd6wMPNnqG6KNve@ve4u7AHFHO2y8Hu9KwzSh77nNAarPmBJegXBQDNqiuf68KebgGe@PF3hSGIOhIx6APxvXthdv2HW/mlUCMT98@PsXRnFHEp69ff/klGfp5aLPv7VB8@exUZ/Yx5B9ptEQf@dsz//bx@QP6eJsneHPlv8Xz6/c264ulfN9@/oiPJXs76ltRf/zsf/wW/fjty3/k9Wyr@J2OwbC0lZAlQzeCbJ7//c//GO7/j/gKfX4fz2NbLf@E//l7/yv65zs0tlGSfYH/SL//kf4DLr59@b36Nn5r//z6Hvx79ef3eY3nBXwZv0FQ@9df7NevP3/@Cw "JavaScript (Node.js) – Try It Online") (not working on TIO)
---
# [JavaScript (Node.js)](https://nodejs.org), 100%, ~~2176 2158~~ 2151 bytes
This is similar to the self-contained version below but uses an external data file of 2010 bytes named `'a'`. The TIO link generates a local copy of this file.
The final size was computed according to [the rules for scoring multiple files](https://codegolf.meta.stackexchange.com/a/4934/58563):
$$2010+140+1=2151$$
```
n=>a=>(require('zlib').inflateRawSync(require('fs').readFileSync('a'))+'').split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr(p,++l||9))
```
[Try it online!](https://tio.run/##fX3JkuM4k@a9niKsLllpkZmhXVS3/T0W@77vUV1mA5IQheACBhdJlPWhre9zn7nPpY/zDL/1i/SL9PgGS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WC85WV4KMfNLt4DJ5@Il9qRMq7uDG0BWWonTelyqFcwreZFXpeUukkYGiJjmpoezxZFSrT2dHjHOGXu84Id2OXzecPypo3LBaY9oJB/6LXUhx6lmFPzTmRsjHHrmRAWeif4eiicadCY04uT1iEPCbMFSxrRkpy5zBXTtHyQCia9Co3Oaqkjcq9FSJyEIR9r6pXt93kY1VdK2NVc9opByRAZuC3yH2BXWLNYSAvn9W/x6p3UJ7npdgtvjIKehENvnV8mB8tOr5PgFh/RupWLWcGAV36pUuLcqeSNOYeEw2maSL@rWOb4ev@iQq72WMNWkmjdoAlfL2yMqqRL4MKlUx1Ls6AcdjKs4YzxmkzP0ElApDLhJ7NtQrokg9itmQCPLGVMPJJV14V7sgUXdWgl/obc@huteAlpmznohNunON7pulNt3hHpjrp3N9nVp3y0WapPCIzZbiwgdsqMePpzPR1xNGdTu63GELpRcQm65nX7MGZ5FnVp@Zyu@QiPXsVR3KaSJSFrg658qggf1tF3kxrzA51yws1DvSmqkoUYkfLefEMrAbjgnSV4576THYVD3AiMHQsUmqLdxIcddSZ479upJNFQu5EB0oQ3QQNKP6Lj1xtFz1rmj5x7n1ToqTMXWJHlMWogZfcIkcm4cNHHijo173qd3JwUK2WI7DpETEEiD3rAhvlKB87d4nlThx7dicl@qViLgaxLJTsG3yvAey006KPDLH7/8mNriEDjOb7/9bsJvW@rbVqHLP75u/e2ftjbfDm/CH5W9r7BG4m9ff@QqPMzC3wZft7a31I93a7Lfvnzb@tJ29HvY81u59betKfzq19/U17avO3J9f8M/tfU/tr5cn3/Z@oetL0e7pxeHB1@@fv36j//1/wE "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 100%, ~~2701 ... 2359~~ 2356 bytes
Takes input as `(id)([etymology0, etymology1, ...])`.
The source contains many unprintable characters.
```
n=>g=(a,i=2,s="aZOEDQ]^4+24><e_<ZZ)aku[XdFyXd
ttoXd
t|63a%}5ks/arbok_[__S♀E2a_S♂E_]]Sx_Sy`S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H)FT3ZR/fooUY
s{6
/alo0U0P&k^5GGLLL4ZXVkC3kkC222lgyem/beheeyem[D<Z~wYxHXxo24MQQ2r
k~fooXZ3iTQOQRJlHRK^IWH3]/doQ?4F23]ENSkZWzZASZ$4am~kVm~ormM}53aR}53B
GRNK2ieD]Dby~sby^5AG<`RD[O];M3sQR+++OR]ENe<V&xNMK4XI^4kFV
eMerQE>OBY082a?50aYv`[5X0TneRKYg`*LkiEMSa17
M/xZ3eas/Z3lt25/zy`Yncie~aA/
VR
KW(<Z~pC3}5Xk2k_^3/y
C3^52?7Wj(Xk(]R8Yc0PGO321_{T4iO[[|5OO3H/fo`ONW23RR~ul/!01_/H5072RaWey]D]GYos`/py=17@Vu~: `_D?2FIQ~de`Wkyu]K/d`4T
-o
-oL4-o3o~ V4iSg{UYg(]G]<V/xkH3eeaXrUNXcT2zC$[[_a=ka[7nYaZ Qy/U5`_O
K{7{6kwZB{6GG_lerO&t{VWW=/dF`Q;2VXIR
FolQnRGRDWk{P07[2%>SskVB
3<aSanremZ&@1]3~m`SgC/pZ2V]3%5'd~ riI~rig17K|Vmie/fF,Ym_RisP2eJT2%~f,A~zZWozZ~vZWovZAXVZQ/zaciU/za0UzTJtus~/}W1|Y1{S1`10_}0^J1]}1[|0Z11Y~3X~2W~4V12U0!03S~5R}2Q}3P04O|1N{1M|2L)01K|3J~6I13H05G{0FU2E{2D}4C14B{3A^1@20?/`>{4=0V<~7;YP,15+[4*[3)/k(a`&~i%|4$X`#/P3`_!2Ti`
J`
_3
U3~eYk{5_4/T4~ `Z;20006/wa/09/s^2
}6
_2 ][16na/eanur~tWi")=>i<127?g(a,i+1,/[\r\n "'\--:\\a-z]/.test(c=Buffer([i]))?s:(l=s.split(c)).join(l.pop())):s.split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr('0x'+p,l||9))
```
[Try it online!](https://tio.run/##fX1Zk9tGlm5E73Z3dLvtXmx32y67vahslUiCa7UtyZK1WpZkVUm1NlWVBJJkCi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HnvoAokl5JY76Ycc4ZkWC8vvbMVXaCQ6lOouqTQRSRt88VJFcL@YVpvckDf4hAt2puqZkhppyBEK3@0nCqVvG8ZJolfOOjliN6h7gZEDIaMJ8hoXcror0SdOex2JN1Qu5EB0oQaoJ@FHlG7dSD1nnks9H3FcrVOFqdiaBI9JCzGDc5hI8saBE0YubXw0OvfuJF@htliNw8wRCKRBL1kQx/fPO0F8JFX48a2Y3LdQKyHwNYkkp@BbZfiM5SYlCrw6fvXS1KY3Qce5cOHQBBfX1MW1VGfj9bXLV/BdD7Cu9aXIzi6Y4FJut3OskXhh/VKigptxcKG3vvbZmuKXt39yce2TqqPrYc@FbO3y2hT@dP2CWq/6OgPXdxm/au3q2icP732y9ve1T25du/vNzRufrK@vf/6v/w8 "JavaScript (Node.js) – Try It Online")
### How?
Each name is encoded as a sequence of sub-strings from the etymology words, with some possible hard-coded characters in between.
Example:
For the first name, we are given:
```
n = 1, a = ['bulb', '-saur']
```
The name `bulbasaur` is first encoded as `004a114`, which is interpreted as:
```
'004' -> a[0].substr(0, 4) -> 'bulb'
'a' -> hard-coded character 'a'
'114' -> a[1].substr(1, 4) -> 'saur'
```
But the length of the sub-string is omitted whenever this is possible without resulting in any ambiguity. When the length is omitted, the decoder assumes that the word must be read to its end.
Both lengths can be omitted in this case, so the final encoding is:
```
00a11
```
All the 890 encoding sequences are concatenated together, using `/` as a separator. This results in a string with a lot of repeated patterns which can be efficiently [crushed](https://siorki.github.io/regPack.html):
```
00a11/00211/00412/00314/00313/00311/00514/00210324/00414/006e/00310/.../za001z03/005tus
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~2526 ... 2485~~ 2477 bytes
```
import bz2,zlib,base64
b=base64.b85decode
p=bz2.decompress(b('LRx4!F+o`-Q(59BF!%rhj7R`*0Ds_61b*t7X+T7%iw!XbsxUw_05wnA5{ieYKr{d~PxKN}nvw5(BOjwtq%XftFY)%vlw$tuZI%9;4^7W^?|qN$^KHzUfTa1Tr63Y7r1jva6}^`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$2aMNY_7F##_{F4MWV*9_f1ndA)t(CgvMWwV&*w^|TcpFW<0>VAHd*3!ba^0gexKQK?@#lsL}6?2G0KB)*DRC-Hkn)31U|ek0jP)gqlbmh&Jn`~r>GFaf062$Ap')).decode().split('%')[n-1]+e[len(e)-int(p[n*2-1]):]
```
[Try it online!](https://tio.run/##bXxZc9tMku07foUctvxJNuQrriAb8m5rsS1L3peOll0EiiCEVVhIgrIdE/M@73fe78s83t/QMX9k/kjfc7JAWV/fjrBZJzNBCktV5cmsLORNNcvS3j/@ESZ5VlQbk1XXXsXhxJ6oUg/71uS@Afcmo4GvvczXVn4fB92jkOSFLsutydYfr94u@zf272bfd95sDcZP9m9sFrNz5@33O7vPym/DzuRO5Xy@@97ZDBc3Pk/K5YfFt93BIn08uAz1l5fFpf/rdPny9c90vhhsPTk5X1QXm5@n1f6X7c15vLhV1V@PNsdu/8z5dPbwx8XrW2cvD1cfpu9V530x7H1xis75XA1/nn2/6L57NFs935ze0kfPJ4ent04uDr713tX7Dz7evq26t6Kt7PnNy49Pkpef7r6bJ7fmd349Pbv4VO9vR7vNwx@Hv5r3p9NfNx4uiuB8Nrm9p4/Pds5OjtytzveLnYdf9y5Wr4tsNn1z@ex81PkcqvpGsJ8eJ/fPP9yKJjv16meRfDoZbG19nO32omhzM/nyvP6axPODz8Nvt84@rd6/eDpzDpu7ztND7/6Xt8vLN0F2cfDgu7PfvL@bnN99OT2Nt@7/XA3SKPQ@jb@dN@HN7MP53U5edb82g18fb29vnTx6/aT36ODOl7f55ZdBMxvtbyWn0/ermXdxlL/5dPI4v/CePDvcKf2jT@NX37LU3R993f42Te4cfdGRfvHuJBp/ml68De6u6sHWqyenN@bN5d7y6NaD85P5l4PTzfLjh7vTZ55zJ1w9Dj52jo8Ws@huz9n231Rvb9VV79Hw9uatz83h7pMnr5I9b/xg8@BU3b8xCS4/3qxf9Tffls@GN78/3nEfDTad7V8/5@Xe03xbf9iPnxyGn48mZ@/DV3dufBs/fu5tzZ/fCKL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C1@DTwRP5JvqbMSHxR2Qi0TxZxMbph50YfZkwEwshEu0qYH@WGcLMpxSAYh21wMpGVx9pXIke1fNNxr9Q21wdwz0RBLAesOeD1/V7QcIbpj/@1rYXWCKSwNEPs2sI4FWZlfCR7hFuDbYa7UbAy0ZvhAGYcMGBZTWG2txuZCFZW45sbubYaGRKsLFxJ5ZVbYFBqLeCawBSvRa9iFFmZGHYExjhDnIX/jOAhO2u5YnZ2BDLIOtJSFyzNmkniDgiGsUvOVLAcdsdnjA8x9PFhjcAE8USCmsWAOpHVB4jyeyCCfLGYXcL3xQITgbB03WxSmve6rff7ikK2Ao9ABaU8CPcHJxPJptSihbDyfVp8XVT7EoHavERgxPRiWNjXX5oG@eqlaXz9XXHPLmZNouWNTnznGdRchmAK7Wrxm6JZ@x7xNXjcY1zisfHNAxDYwjB2VYw/kcj@JpU0FHHRCC9GZIUzMuylzXwISL6SFhZGmCkIYcnaNiGHdSFvhOEuNgNxVNfUf8rbEoFwJ8EKTWmg6AjlDYojh28FIB0os/OMu9QKkVsM@4BZC/zBiXbRB7yap8c8nM@FRtNwcna4Gou4liUbNl/agsiXuycKtjBjyqh/v63Aq6cyAh1OGdwqjGd4rmatQGiNDDn0MhOUClwxKh0xBWnevSQW4rWl235FaKbAOYnmSPKQ8hWxyFdaS18WbaSs1pQEG5ElwSOuSht@KlvQuPjFBobhlSFmjS@EiACWq7c6eYo80Jx6IAhW3IYGZGGlPMYSo5G8GYMvJIQqUSsiawR6qPlCH0yhpq3q8v8B "Python 3 – Try It Online")
Based on idea of @dingledooper (thanks!), but making it a step further by using the longest common suffix to help as well. Also used zlib & base85 to further reduce size a bit.
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 100%, 835 bytes
Sorry folks, Pyke contains a built-in [Pokémon dictionary](https://github.com/muddyfish/PYKE/blob/master/pokemon.json). Unfortunately, it only contains up to `#802: marshadow`, so 88 names had to be hard-coded.
Should work for all inputs, but the TIO environment seems to have a slightly different version of Pyke than on the "Pyke Interpreter" website, so inputs greater than 802 only work on the latter (see below).
```
Q0@802>"poipole,naganadel,stakataka,blacephalon,zeraora,meltan,melmetal,grookey,thwackey,rillaboom,scorbunny,raboot,cinderace,sobble,drizzile,inteleon,skwovet,greedent,rookidee,corvisquire,corviknight,blipbug,dottler,orbeetle,nickit,thievul,gossifleur,eldegoss,wooloo,dubwool,chewtle,drednaw,yamper,boltund,rolycoly,carkol,coalossal,applin,flapple,appletun,silicobra,sandaconda,cramorant,arrokuda,barraskewda,toxel,toxtricity,sizzlipede,centiskorch,clobbopus,grapploct,sinistea,polteageist,hatenna,hattrem,hatterene,impidimp,morgrem,grimmsnarl,obstagoon,perrserker,cursola,sirfetch'd,mr. rime,runerigus,milcery,alcremie,falinks,pincurchin,snom,frosmoth,stonjourner,eiscue,indeedee,morpeko,cufant,copperajah,dracozolt,arctozolt,dracovish,arctovish,duraludon,dreepy,drakloak,dragapult,zacian,zamazenta,eternatus"\,cQ0@803-@&Q0@~_+1-.ol1|
```
[Try it here!](https://pyke.catbus.co.uk/?code=Q0%40802%3E%22poipole%2Cnaganadel%2Cstakataka%2Cblacephalon%2Czeraora%2Cmeltan%2Cmelmetal%2Cgrookey%2Cthwackey%2Crillaboom%2Cscorbunny%2Craboot%2Ccinderace%2Csobble%2Cdrizzile%2Cinteleon%2Cskwovet%2Cgreedent%2Crookidee%2Ccorvisquire%2Ccorviknight%2Cblipbug%2Cdottler%2Corbeetle%2Cnickit%2Cthievul%2Cgossifleur%2Celdegoss%2Cwooloo%2Cdubwool%2Cchewtle%2Cdrednaw%2Cyamper%2Cboltund%2Crolycoly%2Ccarkol%2Ccoalossal%2Capplin%2Cflapple%2Cappletun%2Csilicobra%2Csandaconda%2Ccramorant%2Carrokuda%2Cbarraskewda%2Ctoxel%2Ctoxtricity%2Csizzlipede%2Ccentiskorch%2Cclobbopus%2Cgrapploct%2Csinistea%2Cpolteageist%2Chatenna%2Chattrem%2Chatterene%2Cimpidimp%2Cmorgrem%2Cgrimmsnarl%2Cobstagoon%2Cperrserker%2Ccursola%2Csirfetch%27d%2Cmr.+rime%2Crunerigus%2Cmilcery%2Calcremie%2Cfalinks%2Cpincurchin%2Csnom%2Cfrosmoth%2Cstonjourner%2Ceiscue%2Cindeedee%2Cmorpeko%2Ccufant%2Ccopperajah%2Cdracozolt%2Carctozolt%2Cdracovish%2Carctovish%2Cduraludon%2Cdreepy%2Cdrakloak%2Cdragapult%2Czacian%2Czamazenta%2Ceternatus%22%5C%2CcQ0%40803-%40%26Q0%40~_%2B1-.o%7Cl1&input=%5B880%2C+%22draco%22%2C+%22volt%22%5D&warnings=1&hex=0) (This site doesn't seem to support unicode, so output for `nidoran♀` will be in UTF-8)
[Try it online!](https://tio.run/##LVNBchQxDPxKag9wQKSScIELlS9wBorS2NoZxR5rkO0sO0VRfIPv8ZGlveEwdltrt1ot7XZOcrl8unt8f/fw8bCZbpaFCs9cOEqm2jjx@GjKHGRbOFuhXZzNmVbJjcvYVmmcaXazJGdqy4nDAK4582S2Ug3mUy8FsRFoFLRE0AShatOEpNF13xVAS5MsSFPTyZ6lgVYkSmk06DWKEMietX7v6v9xKjovDSJ1m/pM0VrL4oScIm1UpCFpgzCV5w6hVqses3QnyVHGkU5m2YxinwaisMipXWVJLHyiM68bGCfLrZcIKfkc8FFgT@O6wZlaYQJvW9ZCxzyAXI@CJ1Q1a7AJtlUukYNhoeC8wknUxu6WOkITENckJ@BmP9AErM01aDuDZN9RI@ygAEe0JvOwUMjw0LZe4dVIaKHhatHahAktxTYLTrRwk1J47M1lve7iUuD6umnEQtAzj59m13WthT2TTZiD2dASWOBVPMGJ0L1aRjXqR2lheR1p9dsbvBLyXsR1hp5VcxA/E@cAUhU6MtxJlTYtYAgLrKoFA3J0q6u1BSNn5cm6g4GgOfQxEXFMgAxtmyRD7uPwLNgGQfzEC9oER3dUCiNDe0HXGOZkeYldUezOuUeUgsbKdh6XUjZOA8y8dbzbOSjGeueVd5jMJPCocOv18IXC9c/y7u3jK4Bf397cv721n/n@cvn88IFuDkWjeT8AOUqzAf7@@X34@g8) (Supports unicode, but throws an error for inputs > 802)
Takes input in the form `[1, "bulb", "-saur"]`
**Some relevant portions of the program:**
```
Q0@
```
Read from STDIN, ignoring everything besides the pokemon number
```
Q0@802>...&
```
*IF* (pokemon #) > 802, Do the following:
```
"poipole,naganadel..."
```
- Using this long string of hardcoded names,
```
\,c
```
-- split on commas, and
```
Q0@803-@
```
-- return the name at index ((pokemon #) - 803)
```
Q0@~_+1-...|
```
*ELSE*: Find the index of this pokemon in the dictionary
```
.o
```
- Lookup in the built-in pokemon dictionary, and:
```
l1
```
- convert to lowercase, implicitly print
[Answer]
# [Python 3](https://docs.python.org/3/), 100%, ~~3817 ... 2463~~ 2351 bytes
```
import base64,bz2,re
def f(n,e):
s=re.findall("[A-Z].+?(?=[A-Z])",str(bz2.decompress(base64.b85decode("LRx4!F+o`-Q(2lYjJyB>_?>`2gMW}e@IU|m@L&gzfB<{l>MaducV>;xcV1v3r}_v9qd}l1g$bb0WFnp>O&STHDd{yaqyPYlr~6YAQwdMh*(7?5KmarbspRyU5D6YB>Ux_~Kpvn20BND4Mk62^05mXaen^xm000000ENyXhobxV`;X?{ExyPLkgLKDP|*Q^?o*e5XuP4M=5UaiAd|`2;!L-!vGCJPj#;Mo=2>TVCBV{l6DI6B_r0dGFBRQ-O|~`xNM7ayY%9|*JDHKx)H%`3m$P%bfxU(EeEGzleQ$#&o^1*0>`mQyWinz&K_h&|r)n^J<>jzrwUxNpN$qXir0}FVs_7L(Ks|=pmD2iIahTy>RB*k9#U=BSIWVqS3gGbVZpVtyD8dEs&<v#@cP}dhn`W7qib`>cvCEjl7e+vZP!cd9feP7KUJ||~0FQFad}w6bGbS;17~RfNW=AZ-?8t28AOz_wt~OR85Loar%*#lVF{BpPkTAlKBBJq&5IIzogmT3wP=ZP{!d>aETG<_DSc2Oj4duuj%a?ggAaH<lR3|AC9N>Wyq;np^W5Gyus`ED9MYY}3laCeQ@R052^8Lt6chhHS=PKG_o@*~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rQ8waXwgRASxXb3XyFHmgOfVAEKy4DQ3Iwkp5jCUcR96MwRcSQpWoFZHlgB5qvtAHU6hpq7r8fw "Python 3 – Try It Online")
## Explanation
We could print all of the Pokemon with just the number, but the etymology allows us to improve the compression algorithm. Take the first input: `1;bulb,-saur;bulbasaur`. The first etymology `bulb` and the actual Pokemon have a common prefix. Most Pokemon in the list also have this property. So instead of compressing the entire name of the Pokemon, we only compress the right half of it (`asaur` in the example), starting from the longest common prefix of it and the first etymology. Then for the left half we can just directly take a prefix of the first etymology (`bulb` in the example). We also precompute the longest common suffix to further reduce the size. Then, we will encode the string like this: `44a`. The first and second characters represent the longest common prefix and suffix. The rest represent the rest of the characters not accounted.
] |
[Question]
[
# Challenge
**Input:**
An integer \$b\$ between 2 and 62 (inclusive).
**Output:**
Count from \$1\$ to the equivalent of \$5000\_{10}\$ in base \$b\$, using any reasonable representation for the digits.
However:
* If the number is divisible by \$\lfloor b√∑2+1\rfloor\$ (rounded down, e.g base 7 would be 7/2=3.5, 3.5+1=4.5, rounded to **4**), then output 'Fizz' instead of the number.
* If the number is divisible by \$\lceil b√∑3+3\rceil\$ (rounded up, e.g 11/3=3.666, 3.666+3=6.666, rounded to **7**), then output 'Buzz'.
* As you can probably guess, if your number is divisible by both, output 'Fizzbuzz'.
# Examples
*Using **[0-9]**, **[A-Z]** and **[a-z]** as the digits*
*(I've only included the first 10 values to keep the examples short - normally there'd by 4990 more items in each sequence)*
**Input:** 10 (so 'Fizz' = 6 and 'Buzz' = 7)
**Output:** 1, 2, 3, 4, 5, Fizz, Buzz, 8, 9, 10
**Input:** 2 (so 'Fizz' = 2 and 'Buzz' = 4)
**Output:** 1, Fizz, 11, Fizzbuzz, 101, Fizz, 111, Fizzbuzz, 1001, Fizz
*(I've included the first 50 values of the following to better show how they work)*
**Input:** 55 (so 'Fizz' = \$28\_{10}\$ = \$s\_{55}\$ and 'Buzz' = \$22\_{10}\$ = \$m\_{55}\$)
**Output:** 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, g, h, i, j, k, l, Buzz, n, o, p, q, r, Fizz, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N
# Rules
* Standard loopholes are forbidden
* This is Code Golf, so shortest answer in bytes wins
* Input and output can be through console, or function arguments/returns
* Leading/trailing white space is fine, as are empty lines
* Spaces between 'Fizz' and 'Buzz' are disallowed
* Any capitalization variant of 'Fizz'/'Buzz'/'Fizzbuzz' is fine.
* Outputs should be separated by newlines.
* If you return a array of base 10 'digits' instead of representing them with characters, then they have to be in the correct order!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 42 38 34 33 29 ~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+3 to adhere to strict formatting rules
```
5ȷɓ;8Ä:2,3‘ḍȧ"“Ƈד=%»ḟ0Fȯb@K¥ð€Y
```
A full program which prints 5000 lines of text, each line containing a series of integers (the digits) or one of `fizz`, `buzz`, or `fizzbuzz` (works fine beyond base 62).
**[Try it online!](https://tio.run/##AUIAvf9qZWxsef//Nci3yZM7OMOEOjIsM@KAmOG4jcinIuKAnMaHw5figJw9JcK74bifMEbIr2JAS8Klw7DigqxZ////MTA "Jelly – Try It Online")**
### How?
Note that
\$\lfloor b√∑2+1\rfloor\ = \lfloor b√∑2\rfloor+1\$
...and
\$\lceil b√∑3+3\rceil = \lceil b√∑3+2\rceil+1 = \lceil (b+6)√∑3\rceil+1 = \lfloor (b+8)√∑3\rfloor+1\$
***updating...***
```
5ȷɓ;8Ä:2,3‘ḍȧ"“Ƈד=%»ḟ0Fȯb@ð€ - Link: integer, b
5ȷ - 5*10³ = 5000
ɓ ð€ - for €ach n in [1,2,...,5000] get this f(b,n):
8 - eight
; - concatenate -> [b,8]
Ä - cumulative sums -> [b,b+8]
2,3 - pair literal [2,3]
: - integer division -> [b//2, (b+8)//3]
‘ - increment -> [b//2+1, (b+8)//3+1]
ḍ - divides n? -> [n is fizzy?, n is buzzy?]
“Ƈד=%» - list of dictionary strings = ['fizz','buzz']
" - zip with:
ȧ - logical AND -> [0,0], ['fizz',0], [0,'buzz'],
- or ['fizz','buzz']
0 - zero
ḟ - filter discard -> [], ['fizz'], ['buzz'],
- or ['fizz','buzz']
F - flatten -> [], ['fizz'], ['buzz'],
- or ['fizzbuzz']
@ - using swapped arguments:
b - (n) to a list of digits in base (b) (say, [nb])
ȯ - logical OR -> [nb], ['fizz'], ['buzz'],
- or ['fizzbuzz']
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
NθE…·¹×⁵φ∨⁺⎇﹪ι⊕÷θ²ωFizz⎇﹪ι÷⁺¹¹θ³ωBuzz⍘ιθ
```
[Try it online!](https://tio.run/##bc7BDoIwDAbgu0@xeOqSmYCGEzdiTDigRHmBCQ0ugcHGhpGXn8XozVub/N/f1g9p60F2IeR69O7s@ztaMDzdlFZpB4UcIdd15yc141XqFiEWrFI9TpAIFkdRxLlgFwslZaBCq6V9QTE0vhtACUbYYo/aYUNF7qhm1SAYwfZ8hU/Btie1LFua/@Ef@LTHdNpQ8PCFmV8hLZmc8Obo4XZVhpp5GkKShN3cvQE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input `b` into variable `q`
¬π Literal 1
…· Inclusive range to
φ Predefined variable 1000
√ó Multiplied by
⁵ Literal 5
E Map to
ι Current value
Ôπ™ Modulo
θ Input value
√∑ Floor divide
² Literal 2
‚äï Incremented
‚éá If nonzero
ω Then predefined empty string
Fizz Otherwise literal `Fizz`
⁺ Concatenated with
ι Current value
Ôπ™ Modulo
θ Input value
⁺ Plus
¬π¬π Literal 11
√∑ Integer divided by
³ Literal 3
‚éá If nonzero
ω Then predefined empty string
Buzz Otherwise literal `Buzz`
‚à® Logical Or
ι Current value
‚çò Converted to base
θ Input value
Implicitly print each result on its own line
```
[Answer]
# [R](https://www.r-project.org/), ~~163~~ 131 bytes
```
b=scan();for(d in 1:5e3)cat(list(d%/%b^rev(0:log(d,b))%%b,'fizz','buzz','fizzbuzz')[[1+(!d%%((b+2)%/%2))+2*!d%%((b+11)%/%3)]],'\n')
```
[Try it online!](https://tio.run/##NYtBCoMwEEWvYhfDzDSBOindKD2JteAYLQGJEG0XXj6tQlf/vQc/5az3pe8icT3OiXwRYiHVbXDcdytNYVnJwwX0mYYPldU0v8hbZQZQi2PYNrSo72N2O5CbRgydPACRGse/v2M27vxPInu7cttafETkLGX@Ag "R – Try It Online")
Thanks to @digEmAll for saving 23 bytes. I then further golfed @digEmAll’s efforts to save a further 9.
[Answer]
# [Python 2](https://docs.python.org/2/), 116 bytes
```
b=input()
i=0
exec"a=i=i+1;d=[]\nwhile a:d=[a%b]+d;a/=b\nprint'Fizz'*(i%(b/2+1)<1)+'Buzz'*(i%(~-b/3+4)<1)or d;"*5000
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8k2M6@gtERDkyvT1oArtSI1WSnRNtM2U9vQOsU2OjYmrzwjMydVIdEKyEtUTYrVTrFO1LdNiskrKMrMK1F3y6yqUtfSyFTVSNI30jbUtDHU1FZ3KoUJ1ukm6Rtrm4CE84sUUqyVtEwNDAz@/zc0AAA "Python 2 – Try It Online")
Or with `0-9a-zA-Z` output:
# [Python 2](https://docs.python.org/2/), 143 bytes
```
b=input()
i=0
exec"a=i=i+1;d=''\nwhile a:d=chr(a%b+48+(a%b>9)*39-a%b/36*58)+d;a/=b\nprint'Fizz'*(i%(b/2+1)<1)+'Buzz'*(i%(~-b/3+4)<1)or d;"*5000
```
[Try it online!](https://tio.run/##NYtLCoMwFAD3nkIEyechJn6K1qaLLnoKN4kRfCBRRGnroldPddHVDAMzf9Zhcpn3RqGbt5WyAJUI@nffRVqhQpCNVYS07jXg2If6alU3LFTHBooKTt5rxvM6OSzNL7ysGNhGp8q0bl7QreSJ@044xZiaNAPJbpIBeWz/@E2OD4ozT0tom4iXQgjvpfgB "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~ 117 ~~ 116 bytes
Outputs comma-delimited digits, each digit being expressed as a decimal quantity (e.g. \$19\_{20}\$ is \$19\$ and \$21\_{20}\$ is \$1,1\$).
```
b=>(g=n=>n>1?g(n-1)+`
`+((s=n%(b+2>>1)?'':'Fizz',n%(b/3+3.9|0)?s:s+'Buzz')||(g=n=>n?[...g(n/b|0),n%b]:s)(n)):1)(5e3)
```
[Try it online!](https://tio.run/##ZY7BCsIwEETv/Yq9SHZZTU0FwWpS6MGfEMGmtkWRRIx60PrtNYInvQ1vHsMcq3sV6svhfJ04v2@GVg9WG@y008YZVXToJop4l@wYMWg3QsuZMYoKIXKxPjweYvyB6YxnctFPqQh5YFHeYkF9/x0qNlLKOJXaaETfbvNA6IhyRaiajIbWX9CChmwJFlYa5p/ATPBMAGrvgj818uQ7FGUVGhDA0WOIH2j5Y7Ro6Q9G8Bre "JavaScript (Node.js) – Try It Online")
(limited to 100 so that TIO's output does not blow up)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes
```
₁²½ƛ?8"¦23f/›ḊkF½*∑n?τ$∨;⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwi4oKBwrLCvcabPzhcIsKmMjNmL+KAuuG4imtGwr0q4oiRbj/PhCTiiKg74oGLIiwiIiwiMTAiXQ==)
[Answer]
# Julia, 108
```
h(b,N)=join((n->[string(n,base=b),"Buzz","Fizz","FizzBuzz"][1+(1>n%(b√∑2+1))*2+(1>n%((b+11)√∑3))]).(1:N),"\n")
```
### [ATO](https://ato.pxeger.com/run?1=PZBBTsMwEEXFEp_CsoI00zhVHTYIkSxYsCMXSLOwqdu6iiZV4oCouAmbbnqGHqC34DQ4aWD1NTPS_2_-92nX104fj6fer5OHnxv21qxs1uoPIcQWjCww2zWOACjJy863jjZA0ujOZgaleO4PByHFi_uXcVOVKgaV0x2YyzmNFeIsnRZgYqXwcr5HrHAO6rEINksSGALZPvj7mkBEA8aSIqgtbfwWhhGRm09vO4GM2Xddw6v1er7XbWenO2PrpuUjNXfES0ilWqAEtRi0YrchKMn5SB8ZyYssKvhTEtJn11-_8omAWVpdK5ma-WvoFw)able
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 91 bytes
```
{$!=0;('Fizz'x++$!%%($_/2+|0+1)~'Buzz'x$!%%(($_+8)/3+|0+1)||[R,] $!.polymod($_ xx*))xxêѶ}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pF0dbAWkPdLbOqSr1CW1tFUVVVQyVe30i7xkDbULNO3akUJAEWBoprW2jqG0Okamqig3RiFVQU9Qrycypz81OA0goVFVqamhUVHya0LKv9X5xYqZCmYWigac0FYRrBWaammtb/AQ "Perl 6 – Try It Online")
Anonymous code block that returns a list of either strings of `Fizz/Buzz/FizzBuzz` or a ~~reversed~~ list of integers in the base.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ ~~37~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8+‚U5₄*LεX23S÷>Ö”FizzÒÖ”#×JDõQiyIв]»
```
-2 bytes by creating a port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/180263/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/fQvtRw6xQ00dNLVo@57ZGGBkHH95ud3jao4a5bplVVYcngZnKh6d7uRzeGphZ6XlhU@yh3f//GxoAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9m6GNXpuSZV1BaYqWgZF95eIJLmI6Sf2kJREDnv4X2o4ZZoRebfM5tjTAyDj683e7wtEcNc90yq6oOTwIzlQ9P93I5vDUwszLywqba2v86h7bZ/wcA) (but as list-output and with the first 100 instead of 5000).
**Explanation:**
```
8+ # Add 8 to the (implicit) input
‚Äö # Pair it with the (implicit) input
U # Pop and store it in variable `X`
5‚ÇÑ*L # Create a list in the range [1,5000]
ε # Map each value `y` to:
X23S√∑ # Integer-divide the input by 2, and the input+8 by 3
> # Increase both by 1
Ö # Check for both if they divide value `y` evenly (1 if truthy; 0 if falsey)
”FizzÒÖ” # Push dictionary string "Fizz Buzz"
# # Split on spaces
√ó # Repeat the strings the result amount of times (0 or 1)
J # Join both strings together to a single string
DõQi # If this string is empty:
yI–≤ # Push value `y` in Base-input (as list) instead
] # Close the if-statement and map
» # Join the list by new-lines (and inner lists by spaces implicitly)
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”FizzÒÖ”` is `"Fizz Buzz"`.
[Answer]
# [R](https://www.r-project.org/), 138 bytes
```
function(b,`*`=rep)Map(function(i)"if"((s=paste0("","Fizz"*!i%%(b%/%2+1),"Buzz"*!i%%((b+11)%/%3)))>0,s,i%/%b^((log(i,b)%/%1):0)%%b),1:5e3)
```
[Try it online!](https://tio.run/##PY7BisIwFEX3fkV8EHhPH5hUZhaFzMLF7PwCq5iUZHhQ0tLUjYPfXiuIy3POXdxxTm5Ot9xO0mcMfN1c3RgHOvoBP1oIJAFicYMvUzQIwPAr9zts1qI1Br3T1dYSw@H2kRi21tJS9kT0Y7iwLBAuiF3/h8Lh1SzVhrQOxLb@inuaUz@iKMmqqr8rUv8rpVo/ITS5yc45dfAlAgvDAk0Gevf3r7RcPdnaGnPmtu86P5To4LWj1WN@Ag "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
Uses [Jonathan's mathematical insight](https://codegolf.stackexchange.com/a/180263/47066) that `ceil(n/3+3)` = `floor((n+8)//3)+1`
```
ŽJćG8+‚2L>÷>NsÖ…™Ázz'ÒÖ‚×JNIв‚õKн,
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6F6vI@3uFtqPGmYZ@dgd3m7nV3x42qOGZY9aFh1urKpSPzwJxJ11eLqXn@eFTSDWVu8Le3X@/zc0AAA "05AB1E – Try It Online")
**Explanation**
```
ŽJćG # for N in [1 ...5001)
8+‚Äö2L>√∑> # push [input//2+1, (input+8)//3+1]
NsÖ # check each if N is divisible by it
…™Ázz # push "fizz"
'ÒÖ # push "buzz"
‚Äö # pair
√ó # repeat a number of times corresponding to the result of the
# divisibility test
J # join to string
NIв‚ # pair with N converted to base <input>
õK # remove empty string
–Ω, # print head of the remaining list
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~180~~ ~~171~~ 168 bytes
```
n=>{for(int i=1,p;i<5001;){var j=new Stack<int>();for(p=i;p>0;p/=n)j.Push(p%n);var s=i%~(n/2)<1?"Fizz":"";Print(i++%((n+11)/3)<1?s+"Buzz":s==""?string.Join("-",j):s);}}
```
Outputs like Arnauld's answer. Thanks to digEmAll for the idea of using a stack to reverse the output.
Saved 3 bytes thanks to ceilingcat
[Try it online!](https://tio.run/##XVDNS8MwFL/3r3gECont1o8hyLJsONCDeBh68LJLW1N9E7OSpBNb6r9ek4oDvSTv/b6S9yozqwyO15XFo1qhsutajEqs@/qoqWsBRRY3HFeXaZpx1p8KDQeh5Ac82qJ6mxyUca9uBPJmnfImEYod5rvWvNImVIx7jxEYflGV5GyVbcgtdh1ZEsJ32gVQjKKQUhVlGUsWXmAism29xAhByMZYJ3uZ3x1RUTIj8YEtDePDMPLAZ6NwIfNdoY2kD7J4vkclKWM8eNJo5dRNL/pIQAXbwshZnw575dEl3Jyk/oQ@G0C176XUBvbKa89MfmZ@LH/IxZkkMcaY5FEWu4mu3Ciu6ug/xP@rpuhOv91u2nERg79KFvTTQBYEFBBCyQMArIE6QEDKtLStVlB4@LeGCxdSxmAZJGB5MIxZ/g0 "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
[Blackjack](https://en.wikipedia.org/wiki/Blackjack), also known as twenty-one, is a comparing card game between yourself and a dealer, where each player in turn competes against the dealer, but players do not play against each other.
Play goes as follows, the dealer deals you a card. The dealer then deals them-self a card, face down. The dealer then deals you another card. Then finally, the dealer deals them-self a card, face-up.
# Challenge
Your challenge is to write a program (or function) that when run (or called), outputs (or returns) the probability that the next card the dealer gives you will make you bust, which means the cumulative score of cards in your hand after the dealer gives you another card is over 21.
# Input
The three visible cards in play. They are the two cards you have in your hand, and the one face card you can see in the dealers hand. This can be in whatever format you find suitable for your application.
There are 52 cards in a deck(4 of each of the cards below). The value of the cards are as follows:
```
Symbol(Case Insensitive) Name Value
2 Two 2
3 Three 3
4 Four 4
5 Five 5
6 Six 6
7 Seven 7
8 Eight 8
9 Nine 9
T Ten 10
J Jack 10
Q Queen 10
K King 10
A or 1 Ace 1
```
*In Blackjack, an ace can count as 1 or 11. In our challenge, only count it as a 1*
# Output
The probability, in a ratio or percentage format, that the next card we draw will make us bust.
You may output the percentage, the fraction, or just the numerator of the fraction.
# Examples
*In this example, the first two cards are in our hand, the third card is the dealers visible card*
```
Input -> Output
A 2 Q -> 0.00% or 0/49 or 0
A 2 3 -> 0.00% or 0/49 or 0
T T T -> 91.84% or 45/49 or 91.84
T J K -> 91.84% or 45/49 or 45
9 7 3 -> 61.22% or 30/49 ...
9 7 Q -> 59.18% or 29/49 ...
```
# Rules
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S
```
A monadic link accepting a list of characters (using either the lower-case option OR the upper-case option with `1` for `A`) which returns the numerator (the number of 49ths) in `[0,49]`.
**[Try it online!](https://tio.run/##y0rNyan8/99f1cTi0OpHjVsPbTU0DgKzHu7qNjk6WVf74c5pwSp2RobB////V7c0L1QHAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/99f1cTi0OpHjVsPbTU0DgKzHu7qNjk6WVf74c5pwSp2RobB/4/uOdz@qGmNNxBH/v8frZ5oVKiuAySNgWRJSQmIzMoGkpbmxmCyUD0WAA "Jelly – Try It Online")
### How?
Note that by using lower-case the minimum of **10** and the ordinals modulo by **48** gives the card values. The same holds for upper-case `T`, `J`, `Q`, `K` and `1` for an ace, as shown on the right (but an upper-case `A` does not work):
```
card: a 2 3 4 5 6 7 8 9 t j q k | 1 T J Q K
ordinal: 97 50 51 52 53 54 55 56 57 116 106 113 107 | 49 84 74 81 75
mod 48: 1 2 3 4 5 6 7 8 9 20 10 17 11 | 1 36 26 33 27
min(_,10): 1 2 3 4 5 6 7 8 9 10 10 10 10 | 1 10 10 10 10
```
```
O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S - Link: list of characters e.g. "q3a"
O - ordinals (of the input list) [113, 51, 97]
%48 - modulo by 48 [17,3,1]
⁵ - ten
« - minimum [10,3,1]
µ - start a new monadic chain
13R - range of 13 [1,2,3,4,5,6,7,8,9,10,11,12,13]
⁵ - ten 10
« - minimum [1,2,3,4,5,6,7,8,9,10,10,10,10]
ẋ4 - repeat four times [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10]
œ- - multi-set difference [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10 ,2 ,4,5,6,7,8,9 ,10,10,10]
$ - last two links as a monad:
Ṗ - pop [10,3]
S - sum 13
+ - add (vectorises) [14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,15,17,18,19,20,21,22,23,23,23]
>21 - greater than 21? [0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1]
S - sum 19
```
[Answer]
# JavaScript (ES6), ~~73~~ 62 bytes
Takes input as an array of 3 characters with `1` for aces. Returns the integer **X** representing the probability **X/49** to be busted.
```
a=>([b,c]=a.map(v=>v*4||40)).map(n=>b-=n+b>52,b+=c-32)|b>12&&b
```
[Try it online!](https://tio.run/##fc@9CsIwFIbh3avo1CT2P0mRDicXoJPgVjoksRWlJsVKp957DCri0g7vcnjg49zkJEf9uA7PxNhz6zpwEgSuVawbkOldDngCMW35PPOckPfBgFAJmEiJksYqAp0wSmYlChqGymlrRtu3aW8vuMM1KlCMqO@IGkKCLAvyjFebJcVW1cmLT1/FyyW29x3WWeXJ7n@T5Wvs9wCtPHMv "JavaScript (Node.js) – Try It Online")
### Exhaustive test
The golfed formula is not very intuitive. So, the easiest way to prove its consistency is probably to just compare all possible outputs against the ones provided by a basic ungolfed implementation:
```
g = a => {
deck = [...'123456789TJQK'.repeat(4)];
a.forEach(card => deck.splice(deck.indexOf(card), 1));
return deck.filter(card =>
(+a[0] || 10) +
(+a[1] || 10) +
(+card || 10) > 21
).length;
}
```
[Try it online!](https://tio.run/##bZFNc4IwEIbv@RXrRZKKGUHsxzhhptN6aQ9ObW@MhxAD0lJgAjJq8bfTgB/Vtjlkss@@7@7s5p2XPBcqyop@ki5kXYfAgANz4QsBLKT40LFHKTUse@iMrm9u796eXp4NqmQmeYEdMh9rIadBqiZcLLHgatHYGyvNszgSErfvKFnI9TRoBcQEi5Ax0k4li5VK9vIgigupjiV0EgD3uDeYQ1WBNSDQOzHrD2tdB@aCbWlMaCyTsFiO0Q6hoBmMudjzTTFnnH7yDJfMLa@cqnIGhLQgYa7fZ0nPd0e26feY6A9tUvmuZXe7PkIP97PH//eht4CiAOumjYbKUqoNXh@nOGObI7ug2@PG90dXCrC3NmFjwnZOoMMgPIvJmRRApEmexpLGaYiNyWw2nYH@DMOEg56Mz8SHdQc8zuUP36Ff@UKtTukdaR/NTdC@9UXL15UQMs87BkG7uv4G "JavaScript (Node.js) – Try It Online")
[Answer]
# Pyth, 35 bytes
```
Jm?}dGTsdQclf>T-21sPJ.-*4+ST*3]TJ49
```
Takes input as a list of characters (or as a string).
[Try it here](http://pyth.herokuapp.com/?code=Jm%3F%7DdGTsdQclf%3ET-21sPJ.-%2A4%2BST%2A3%5DTJ49&input=%279%27%2C%20%277%27%2C%20%27q%27&debug=0)
### Explanation
```
Jm?}dGTsdQclf>T-21sPJ.-*4+ST*3]TJ49
Jm?}dGTsdQ Convert each input to the appropriate number.
.-*4+ST*3]TJ Remove each from the deck.
lf>T-21sPJ Count how many remaining cards bust.
c 49 Get the probability.
```
[Answer]
# [Perl 5](https://www.perl.org/), 115 bytes
```
map{//;$k{$_}=4-grep$' eq$_,@F}1..9,T,J,Q,K;map{s/\D/10/}@F;$_=grep{$F[0]+$F[1]+$_>21}map{(s/\D/10/r)x$k{$_}}keys%k
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaX99aJbtaJb7W1kQ3vSi1QEVdIbVQJV7Hwa3WUE/PUidEx0snUMfbGqS2WD/GRd/QQL/Wwc1aJd4WpLxaxS3aIFYbSBoCyXg7I8NakEoNmNIizQqI8bXZqZXFqtn//4coAOG//IKSzPy84v@6vqZ6BoYG/3ULEgE "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97~~ 96 bytes
```
def f(s):C=[min(int(c,36),10)for c in s];D=C[0]+C[1];return(4*D-35+sum(v+D<22for v in C))*(D>11)
```
[Try it online!](https://tio.run/##Hc6xDoMgGATguX0KNkFpIlBrqrULTHZq4maYrKYOogE16dNTfpdvuLvhlt/6nQ33/tMPaMCOFLJqp9Hg0ay4o@JGKEvJMFvUodEgp0tVyTbViWyZLm2/btbga6wuIkvcNuE9UQ/OYb/DXhISY/VkjHjIHGRtxPg7okERbJoGrF/Bey4Ooc1ydlhDy@tIF@fTYsMr5Cj89H8 "Python 2 – Try It Online")
Takes a 3-character string as input, with '1' being used as Ace. Returns the numerator.
[Answer]
# Java 8, 109 bytes
```
a->{int r=3;for(;r-->0;a[r]=a[r]<59?a[r]*4-192:40);r=a[0]+a[1]-32;for(int v:a)r-=v+r>52?1:0;return r>12?r:0;}
```
Port of [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/164341/52210).
Input as character-array with three values, Aces as `'1'`; output is the probability `p` in `p/49`.
[Try it online.](https://tio.run/##lZBPT4NAEMXv/RRzA6xL@NPGwArcNTYx9UY4jJQaKl2aYcEYwmfHAdQ7yb7ZzM7@Nu/tBTsUl9PnmFfYNPCCpeo3AKXSBZ0xL@AwtfMB5CbXNAO0JJ8NLF6NRl3mcAAFEYwo4n66SpEvzzWZkoSIHYkpZdFUHvdBMu13O@EGXrhzLEk8cLItpm4mfG@mphe6EC0SUbeleO8lbuhIKnRLCih2vYS4H0a5WLi17xVb@HXS1eUJrpzDPGoq1cdseAlx/G50cbXrVts3HulKmcrOTVV8wZysN1zj3vBYr8ZgzSnXQP4a6I2BRSuhJ9bzGihg4GGtvT/o/yOGzTD@AA)
**Explanation:**
```
a->{ // Method with integer-array as parameter and integer return-type
int r=3;for(;r-->0; // Loop over the array
a[r]=a[r]<59? // If the current item is a digit:
a[r]*4-192 // Multiply it by 4
: // Else:
40); // Change it to 40
r=a[0]+a[1]-32; // Set `r` to the first value, plus the second value, minus 32
for(int v:a) // Loop over the now modified array again
r-=v+r>52? // If the current value plus `r` is larger than 52
1 // Decrease the result-integer by 1
:0; // Else: Leave the result-integer the same
return r>12? // If the result-integer is larger than 12
r // Return the result-integer
: // Else:
0;} // Return 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 46 bytes
```
Y9ŸJ.•§®т•«Á4שsð.;#S|UεX‚˜ε®sk>T‚W}O21›}DOsg/
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/0vLoDi@9Rw2LDi0/tO5iE4ix@nCjyeHph1YWH96gZ60cXBN6bmvEo4ZZp@ec23poXXG2XQiQE17rb2T4qGFXrYt/cbr@//8lXEAIAA "05AB1E – Try It Online")
This can be done better, working on it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 21 bytes
```
AST:4-D¨OÐ4@*4*Š+T@O-
```
[Try it online!](https://tio.run/##yy9OTMpM/W/m9t8xOMTKRNfl0Ar/wxNMHLRMtI4u0A5x8Nf9r/M/WslQSUdByQhEFCrFciHzjcH8EhATSsD5WSAiG8y3BDHNEeoRfKB5AA "05AB1E – Try It Online")
```
AST: # replace all letters in the input with 10
4- # subtract 4 from each card value
D # duplicate
¨ # drop the last element
O # sum (hand value of the player - 8)
Ð # triplicate that
4@* # set to 0 if it's less than 4
4* # multiply by 4
Š # 3-way swap
+ # add the player's hand value to each card value
T@O # count how many are >= 10
- # subtract
```
] |
[Question]
[
Consider the integers modulo `q` where `q` is prime, a generator is any integer `1 < x < q` so that `x^1, x^2, ..., x^(q-1)` covers all `q-1` of the integers between `1` and `q-1`. For example, consider the integers modulo 7 (which we write as `Z_7`). Then `3, 3^2 mod 7 = 2, 3^3 = 27 mod 7 = 6, 3^4 = 81 mod 7 = 4, 3^5 = 243 mod 7 = 5, 3^6 = 729 mod 7 = 1` covers all the values `3, 2, 6, 4, 5, 1` covers all the integers `1..6` as required.
The task is to write code that takes an input `n` and outputs a generator for `Z_n`. You cannot use any builtin or library that does this for you of course.
The only restriction on the performance of your code is that you must have tested it to completion with `n = 4257452468389`.
Note that `2^n` means `2` to the power of `n`. That is `^` represents exponentiation.
[Answer]
# Pyth, ~~16~~ 15 bytes
```
f-1m.^T/tQdQPtQ
```
[Test suite](https://pyth.herokuapp.com/?code=f-1m.%5ET%2FtQdQPtQ&test_suite=1&test_suite_input=7%0A101%0A1009%0A4257452468389&debug=0)
If p is the input, we know that g^(p-1) = 1 mod p, so we just need to check that g^a != 1 mod p for any smaller a. But a must be a factor of p-1 for that to be possible, and any multiple of an a with that property will also have that property, so we only need to check that g^((p-1)/q) != 1 mod p for all prime factors q of p-1. So, we check all integers g in increasing order until we find one that works.
Explanation:
```
f-1m.^T/tQdQPtQ
f Return the first value T such that the following is truthy:
PtQ Take the prime factorization of the input - 1.
m Map those prime factors to
/tQd Take the input - 1 divided by the factor
.^T Q Raise T to that exponent mod input,
performed as modular exponentiation, for performance.
-1 Check that 1 is not found among the results.
```
[Answer]
# Mathematica, 52 bytes
Inspired by [isaacg's answer](https://codegolf.stackexchange.com/a/129443/9288).
```
1//.i_/;PowerMod[i,Divisors[#-1],#]~Count~1!=1:>i+1&
```
] |
[Question]
[
# The challenge
Write a program or function which takes a string input as a function parameter or from stdin and determines if it is a valid [FEN](http://www.chessgames.com/fenhelp.html) string.
# Input
You can assume the input will only ever include the following characters (case sensitive)
`pkqrbnPKQRBN12345678/`
The length of the input will always be a minimum of 1 character and a maximum of 100 characters
# Output
Output should be a truthy/falsey value. These can be any values you wish as long as they are consistent (all truthy results have the same output, all falsey results have the same output). You should have exactly two distinct possible outputs.
# What counts as valid
Lowercase letters represent black pieces, uppercase letters represent white pieces.
You should ensure it is possible in a game of chess for the pieces in the current position to exist.
Each player will always have exactly 1 king (k/K)
Each player may have no more than 8 pawns (p/P)
Each player will usually have no more than 1\* queen (q/Q)
Each player will usually have no more than 2\* rooks (r/R)
Each player will usually have no more than 2\* knights (n/N)
Each player will usually have no more than 2\* bishops (b/B)
\* It is legal for a player to 'promote' a pawn to any of these four pieces.
The total of pawns, queens, rooks, knights and bishops for each player will never be more than 15
The total number of pieces plus empty squares (denoted by numbers) should always add up to exactly 8 for each rank. And there should always be exactly 8 ranks, separated by a forward slash.
# Things you can ignore
You do not need to concern yourself with whether or not it is possible to play into the position denoted, or if the position is legal, only that the pieces can exist in the quantities given.
You can ignore further complexities of FEN strings such as player turn, castling rights and en passant.
# This is code golf. Shortest program in bytes wins. Usual loopholes and rules apply.
# Test Cases
**Input** rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
**Output** True
**Input** 2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K
**Output** True
**Input** r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1
**Output** False
(black has 7 pawns and 4 rooks - impossible)
**Input** 6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1
**Output** False
(only 7 ranks)
**Input** 3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R
**Output** False
(9 ranks)
**Input** 5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1
**Output** False
(2nd rank has 9 squares/pieces)
**Input** rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR
**Output** True
Thanks to Feersum and Arnauld for clarifying this case (3+5=8)
# What is FEN?
[FEN](http://www.chessgames.com/fenhelp.html) is a standard notation for recording the position of the pieces on a chess board.
[](https://i.stack.imgur.com/GvEhD.gif)
Image credit <http://www.chessgames.com>
[Answer]
## JavaScript (ES6), ~~168~~ ~~174~~ ... 155
*This answer has been edited an embarrassing number of times. Hopefully, the current version is both reliable and decently golfed.*
---
Returns a boolean.
```
s=>[...s].map(c=>++n%9?+c?n+=--c:a[i='pP/KkQqRrBbNn'.search(c),i&=i>4&a[i]>(i>6)||i]=-~a[i]:x+=c=='/',a=[x=n=0])&&!([p,P,s,k,K]=a,n-71|x-7|s|k*K-1|p>8|P>8)
```
### Formatted and commented
```
s => [...s].map(c => // for each character 'c' in the FEN string 's':
++n % 9 ? // if we haven't reached the end of a rank:
+c ? // if the character is a digit:
n += --c // advance the board pointer by c - 1 squares
: // else:
a[ // update the piece counter array:
i = // i = piece identifier (0 to 12)
'pP/KkQqRrBbNn'.search(c), // with special case: '/' --> 2
i &= // we count it as a promoted pawn instead if:
i > 4 & // it's a Q, R, B or N and we already have
a[i] > (i > 6) || // 2 of them for R, B, N or just 1 for Q
i // else, we keep the identifier unchanged
] = -~a[i] // '-~' allows to increment 'undefined'
: // else:
x += c == '/', // check that the expected '/' is there
a = [ // initialize the piece counter array 'a'
x = // initialize the '/' counter 'x',
n = 0 ] // initialize the board pointer 'n'
) && // end of map()
!( // now it's time to perform all sanity checks:
[p, P, s, K, k] = a, // copy the 5 first entries of 'a' to new variables
n - 71 | // have we reached exactly the end of the board?
x - 7 | // have we identified exactly 7 ends of rank?
s | // have we encountered any unexpected '/' character?
k * K - 1 | // do we have exactly one king on each side?
p > 8 | // no more than 8 black pawns, including promotions?
P > 8) // no more than 8 white pawns, including promotions?
```
### Test cases
```
let f =
s=>[...s].map(c=>++n%9?+c?n+=--c:a[i='pP/KkQqRrBbNn'.search(c),i&=i>4&a[i]>(i>6)||i]=-~a[i]:x+=c=='/',a=[x=n=0])&&!([p,P,s,k,K]=a,n-71|x-7|s|k*K-1|p>8|P>8)
console.log(f("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) // True
console.log(f("2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K")) // True
console.log(f("r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1")) // False (black has 7 pawns and 4 rooks - impossible)
console.log(f("6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1")) // False (only 7 ranks)
console.log(f("3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R")) // False (9 ranks)
console.log(f("5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1")) // False (2nd rank has 9 squares/pieces)
console.log(f("rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR")) // True
console.log(f("rnbqkbnr/pppppppp/8/9/7/8/PPPPPPPP/RNBQKBNR")) // False (additional test case suggested by Rick Hitchcock)
console.log(f("rnbqkbnr/pppp/ppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) // False (additional test case)
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 105 bytes
```
[1-8]
$*
^
/
iG`^(/[1KQRBNP]{8}){8}$
G`K
G`k
A`K.*K|k.*k
{2`N
2`B
2`R
1`Q
K
T`L`P
8`P
A`P
}T`l`L
^.
```
[Try it online!](https://tio.run/##bZAxawMxDIV3/Y4U0kAjJN@FW3tLBgejM9lCgmvoEK4YnemW5rdfdSFjJJ6n9/w@VL9/r@Vrflvv03yij@4Mqw1cAOG6T5c1nsgPsQ9yvnX3d9MK9smbRvhMfrvxf@N2M8KNUwDg1C9PBKA0AHiAYzokgc5kdoH7Mf2kA1y281xLnsZcKupzsHuuPAdj6AffhwicK4@EpFxoIlS2JRTKQhoUqReWIkgD9SxkX7gQ2UPlR0zdxGo10WnFKk1WdNpg25OgNGIBN1D0BLvFrG5hadQhi8uEWcQtFt@gmG8icJXqg0Ypm3BnUqGikxTrbgLbv2wxA2NDw8iD5whtodFSFp8Mxy0NSoEHK6K41LUWq7QANZGM59WJXPv6Rv8 "Retina – Try It Online") Link includes test cases. Explanation:
```
[1-8]
$*
```
Expand digits to empty squares, which we denote using `1`s.
```
^
/
iG`^(/[1KQRBNP]{8}){8}$
```
Delete the input if it does not match 8 sets of 8 valid squares joined with `/`s. (An extra `/` is prefixed to simplify the check.)
```
G`K
G`k
A`K.*K|k.*k
```
Delete the input if it has no white or no black king, or if it has two of either.
```
{2`N
2`B
2`R
1`Q
K
```
Delete white's starting pieces, if they are still there.
```
T`L`P
```
Demote any remaining white pieces to pawns.
```
8`P
```
Delete the valid white pawns.
```
A`P
```
Delete the input if there are any white pawns left over.
```
}T`l`L
```
Check again but with the black pieces.
```
^.
```
Output a truthy value unless the line was deleted.
[Answer]
# Python 3, ~~284 259 236 225 247~~ 234 bytes
```
import re
s=input()
t,c=s.split("/"),s.count;P=p=9;o=0
for x in"pqrnb":p-=max(0,c(x)-o);P-=max(0,c(x.upper())-o);o+=o<2
v=8==len(t)and all(8==sum(int(x)for x in re.sub("[A-z]","1",p))for p in t)and p>0<P and c('k')==c('K')==1
print(v)
```
[Try it Online!](https://tio.run/##TY5BS8QwEIXv/RUll00wbZpUZLU7gntdkLhX8dDWimXbZDZJl@qfr@mK4OHxhvcxbwa/wqc15bL0I1oXUtclHnqDU6AsCbwFn3sc@kCJIIz7vLWTCZUGhPvKQpF8WJfOaW8Inp1pyANmMNYzLXhLZ5ZZVul/QT4hdo6yK7A3YHcqucAWYOgMDaw272k9DDQGfhppb0Ls@DsQP8v91FDy@pR9vxFOJOHIrhhX/LuOj8VOp@vU0s1pwwCiH1aXCbq18cKWpXTSnaSQiLKJEndRqKXBszZiK26flRZaaV0KuVd7rcRRvRzU8Qc)
[Try it Online with all of the test cases!](https://tio.run/##TY5Rj9MwDMff8ymi8nCp6JY56U7H7YLEXitVbsUb4mEdRVetS920PQZffjhjCGxFjmz//f/Rz/l18PbanWkIswyt@PHa9a38HJb2@fruX1tOrvO0zCoVcs6OblpP1HezSnSSZtP6OCx@3qEj92E3uI2Q34cgL7LzCY3BN8kzrdz5cFGb7Kgu6WpId/hfY70QtUGlt8Hw3g0vRsg39@Rc33o1pwf/TcpD3yvuTMtZdX7mK38tGG89LY1Kvnxa/fqaZAkkGaW3McXxHz193LygjL@jejg9pM5xLWIFISnEk2/p9cqw46nxQdM99NM98R66LvdVsS9rYZpgTqCBjIcRNBlO0AgNApWkYY8GPWqoYG8Q@IQta1OIYG4ysqMhtqktBR0wb0hbyvV2D6gxRxbYCuoCxGNcJhtZcrLaoG1AN4g2rhS5Rt4bQdgA4UZD0PDTj/wIwdOInr3z0vBdwzIGM4yma1MVphZbDydWsXxkHBsdCEpTsRHU0W7LsgARKK@hgN8)
-11 bytes thanks to Mr. Xcoder
-13 bytes thanks to Jonathan Allen
+22 I forgot kings existed.
Semi-ungolfed with some explanation:
```
import re
string = input()
split = string.split("/")
count = string.count # find # of occurences of char in string
pawns = 9 # represents the # of pawns a player has out of the game... plus one, e.g. 1 is all in game, 2 is one out, 0 is invalid
PAWNS = 9 # would be 8, but then I would need >= instead of >
offset = 0 # default for pawns
for char in "pqrnb": # for each pawn, each queen over 1, and each rook/knight/bishop over 2 for each player
# subtract one from the players 'pawns' var, which must end up 1 or greater to be valid
# otherwise too many pawns/queens/etc of that player are on the board
pawns -= max(0,count(char)-offset)
PAWNS -= max(0,count(char.upper())-offset)
offset += (offset 0 and PAWNS>0 and \ # make sure each player does not have an invalid number of pawns/q/n/b/r
count('k')==count('K')==1 # correct # of kings
print(valid)
```
[Answer]
# [PHP](https://php.net/), 269 bytes
```
$t=($o=count_chars($a="$argn/"))[47]==8&$o[107]==1&$o[75]==1&9>($w=$u=$o[80])&9>$b=$l=$o[112];foreach([81,82,78,66]as$k=>$v){$z=$k?11:10;$b+=$x=$o[32+$v];$t&=$l+$x<$z;$w+=$x=$o[$v];$t&=$u+$x<$z;}$t&=$b<16&$w<16;for(;$c=$a[$n++];)$c<A?$c>0?$s+=$c:$t&=!$s-=8:++$s;echo$t;
```
[Try it online!](https://tio.run/##fVNhb9owEP3Or9jSU5UIT@45gbIGF42pkyYmZqJ@oxFKsqwgqGOcULpW3V/vzhmtWmmaLcfnO793z2fHLM3TcGSWplNaW9mFLU1lm5W@9n9fLKbfL79@vgjizs/Kllmx9OeduWd1vl3n2nJzaHxw6OrQeDIdzybjaeKxS7srU0YokVuxRo5GaNwiN4I6coW5QjM1HMdKKK04znAsFBJZOE3E5BWBFS2BCbfCUOokNJZbFeWGhybivTEqriJF0HCGyQQ99iXb1H@hfYczoZMamZALFebIc6VCt3sScUWQ7RtEaNG2ag3mNHifhlGozVZp0hZNBWUTxEDCBUnniZhNRPKaoqdxTQTEtCW9octrcCpmlB4TJ6JHDBad4ijBt4L/VeKw998ap1kNm1XdBA8dN/mQ2WvNoKh0Y6tNINtg3NnpuqRgwyBnsGdQM9BB/ASN9KGSRbXTzaJYZrYmAum1JNwLgnl0mko5OIZqjifORGee9lrr47kPewk7Sa7BSRqQA3JK6NaIIo1fXs8A2UCw0wHr953etTyH2@AB7iWsR4hneBJD3pVw55Ch6MJtGkNzTFRduBvCfQz75@hLaHcIPbarfIj9Y9jT1yX1YygkZHPQ3W4aB1AMP42gOD8ZQU08xZmDvIf6gxycdbtQx2WxrKCJn9zsXTUeo7LI5xIy8rT1uNJe/Ng5ej5UeWc21Y/S9zjtd/GATmYDaOapzKzNfi3q3Y1fN3ZRm82q8Y0tr91ftskKAh1dmW9HHkNGkCCgErci3t2sNF0SXcwf "PHP – Try It Online")
[Answer]
# JavaScript (ES6), ~~181~~ ~~172~~ 174 bytes
```
f=([c,...s],n=1,o={p:0,P:0})=>c?c=='/'&&n%9?0:f(s,n+(+c||1),(o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)):o.p<9&o.P<9&n==72&o.k==1&o.K==1
```
**Ungolfed:**
```
f=
([c,...s], //c is current character
n=1, //n is current square, range [1-72] (board is 9x8 due to slashes)
o={p:0,P:0} //o holds piece counts
)=>
c?
c=='/'&&n%9?0: //ensure 8 squares per row
f(s,
n+(+c||1), //increment n by the correct number of squares
(o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)
//"depromote" extra queens, rooks, bishops, or knights
):
o.p<9&o.P<9& //no more than 8 pawns per side (accounting for promotions)
o.k==1&o.K==1& //each side has one and only one king
n==72 //correct number of squares
```
```
f=([c,...s],n=1,o={p:0,P:0})=>c?c=='/'&&n%9?0:f(s,n+(+c||1),(o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)):o.p<9&o.P<9&n==72&o.k==1&o.K==1
console.log(f('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')); //true
console.log(f('2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K')) //true
console.log(f('r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1')); //false
console.log(f('6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1')); //false
console.log(f('3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R')); //false
console.log(f('5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1')); //false
console.log(f('rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR')); //true
console.log(f('rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNQQKBNR')); //false, too many queens
```
[Answer]
# [Python 3](https://docs.python.org/3/), 263 bytes
```
s=input()
n=0
for a in s.split('/'):n+=sum([int(c)if c in"123456789"else 1for c in a])
m=lambda k:{c:s.count(c)for c in s}.get(k,0)
p=[m("p"),m("P")]
for c in"rnbqRNGQ":b=c in"qQ";p[c<"Z"]+=m(c)+b-2if m(c)>2-b else 0
print((n==64)&(p[0]<9>p[1])&(m("K")>0<m("k")))
```
[Try it online!](https://tio.run/##PY4xb4MwEIV3foXlobFFgjGQtKGYoUuHSBVhLGIASloEmMOGoar626lBSqd7d/fe3Qff09cg/WXRopEwT4RaUrjWbVCoQI1E2tHQNRPZsR0NpS303JOskROpaHNDlbFg7vnB8fT4dMZ1p2vE1@y6QEVOrV50RV9@FKgNf6pQO9Uwb@F/k/51PuuJtHuXWiCynmDAdG9Kgmlu3W1YyXJM316vOCzFNhiv@BmyKsLvOLdFb07a5cEzTKuMvUOJNhrXArXiEinEKaAPBDI3j84xZDw3nflzwTR2IyNaTCldFuUpr@UM/NEDBpD6oJhKghKYDwE7vvCEJUGScOZfeXrhfw "Python 3 – Try It Online")
Not the smallest Python submission, but I think it still has some promise.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 122 bytes
```
s=>[a={q:1,Q:1},...s].map(c=>+c?n-=c:a[c=a[c]>1?c<a?'P':'p':c]=-2*!(n--%9)-~a[c],n=72)|!(n|a['/']+7|a.k*a.K-1|a.p>8|a.P>8)
```
[Try it online!](https://tio.run/##lZNdb5swFIbv9yu8ShOhDVjHJs2HRiLlYpqEhAzaXZQL49CUQY2xk03Vsv317BDlZmkbdbaMwELPc/xy@C5/SKdsZXaBbjfl8SE@uni@kvGvbgbDbAa/h2EYunX4JM1AxfM7tdBBrGZypWJc6zks1Ge58IQ384w3U@s4YLcfBzoIPk394E//ylDHY@YfcPMgVx711nfjgwzrWxkmAeCdmU/wKuYT/6ha7dqmDJt2O3gY3FhddHWhLTXnQSfnKc6D5ukyS5ZpfuP7hFLyze7LDxcUVlhWAwXDNHRADcMJVEAhwKSGwlIwoQWFDJZMAMJ5mrPkCtCyE9DwjhksLefGUiuiwlBuIjpagqAiEojiGeQJnElfZONKMigaqWryKB0ZEyN/akek3pCI2LatHQlI9WRa56qiKf1L730vNbzPITKcMsELoIUQvFclERXo6y50rW6e0WSlrt0LILdgT8kYKHDRe1xGgDad0JhDlDI8CUMBhsQwJpqzLGH5v4bpG/CRhhrR6OgwJd4XbCBlGdYNeV/9CNkW@pyiHC5jYhhKzz0lNSWu20tbOmqqUpUvXa81Ch/9d6e8hpnS8RXKuVq52VS7qtWyIbvS7YiSuOv22y0@lBtSPJO8wq/@tdqpR9Wq@voB6Hs6/Yr5LXr0zp/oGvr4Fw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 123 bytes
```
s=>[...s].map(c=>+c?n-=c:a[c=a[c]>1?c<a?'P':'p':c]=-2*!(n--%9)-~a[c],a={q:1,Q:1},n=71)&&!(n|a['/']+7|a.k*a.K-1|a.p>8|a.P>8)
```
[Try it online!](https://tio.run/##lZNdb5swFIbv9yu8SiuhDVjHJs2HRiLlYpqEhAzaXZQL49CUQY2xk03Vuv317BDlZmkbdbaMAFnPc/xy@C5/SKdsZXaBbjfl4T4@uHi@CsPQrcNHaQYqnt@qhQ5iNZMrFeNaz2GhPsuFJ7yZZ7yZWscBu/k40EHwaeoHf/otQxn/6mYwzGbwe6jjMfjX17jjWa486q1vx88yrG9kmASAd2Y@wauYT/yDarVrmzJs2u3gfnBlddHVhbbUnAadnKY4DZqnyyxZpvmV7xNKyTe7Lz@cUVhhWQ0UDNPQATUMJ1ABhQCTGgpLwYQWFDJYMgEI52nOkgtAy45AwztmsLScG0utiApDuYnoaAmCikggimeQJ3AifZGNK8mgaKSqyYN0ZEyM/KkdkXpDImLbtnYkINWjaZ2riqb0z713vdTwPofIcMoEL4AWQvBelURUoK8707W6eUKTlbp2L4Dcgj0mY6DARe9wGQHadEJjDlHK8CQMBRgSw5hozrKE5f8apm/ARxpqRKOjw5R4X7CBlGVYN@R99SNkW@hzinI4j4lhKD33mNSUuG4vbemoqUpVvnS91ih89N@d8hpmSscXKKdq5WZT7apWy4bsSrcjSuJbt99u8aHckOKJ5BV@9a/VTj2oVtWXD0Df0@kXzG/Ro3f@RJfQh78 "JavaScript (Node.js) – Try It Online")
Arnauld's solution but use `a` as object rather than array. Would see which is shorter
```
s=>[...s].map(
c=>+c?n-=c: // number, skip spaces
a[c=a[c]>1?c<a?'P':'p':c]= // if there's two, count on pawn
// promoting to pawn don't make it bad
// promoting to king mean there's 2 king and anyway invalid
// promoting to slash mean there's slash on unintended places, invalid
-2*!(n--%9)-~a[c], // subtract on slash position, all 7 chances must belong to slash
a={q:1,Q:1}, // an extra queen, so only 1 extra before needing promotion
n=71 // board size
)&&!(
n| // length unmatched
a['/']+7| // unintended slash or non-slash
a.k*a.K-1| // incorrect king amount
a.p>8| // Not too many pawns
a.P>8)
```
] |
[Question]
[
Break two numbers up into their factorials; if they share any, return a falsey value. Otherwise, return a truthy value. (inspired by [this recent question](https://codegolf.stackexchange.com/q/124627/56178))
In other words, write each input number as the sum of factorials (of positive integers) in the greediest possible way; return a truthy value if no factorial appears in both representations, a falsey value otherwise.
# Example
Given 20 and 49:
```
20 = 3! + 3! + 3! + 2!
49 = 4! + 4! + 1!
```
No factorial appears in both representations, so return a truthy value.
Given 32 and 132:
```
132 = 5! + 3! + 3!
32 = 4! + 3! + 2!
```
3! appears in both representations, so return a falsey value.
# I/O
Input and output can be through [any standard means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
Input will always be two nonnegative integers; no upper bound on these integers other than what your language requires.
Output should be a [truthy or falsey value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey). These values don't necessarily have to be consistent for different inputs, as long as every output is correctly truthy/falsey.
# Test Cases
If one input is `0`, the answer will always be truthy. Other truthy test cases:
```
{6, 3}, {4, 61}, {73, 2}, {12, 1}, {240, 2}, {5, 264}, {2, 91}, {673, 18},
{3, 12}, {72, 10}, {121, 26}, {127, 746}
```
If both inputs are odd integers, or if both inputs are the same positive integer, then the output will always be falsey. Other falsey test cases:
```
{8, 5}, {7, 5}, {27, 47}, {53, 11}, {13, 123}, {75, 77}, {163, 160}, {148, 53},
{225, 178}, {285, 169}, {39, 51}, {207, 334}, {153, 21}, {390, 128}, {506, 584},
{626, 370}, {819, 354}
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Æ!ṠḄ&/¬
```
[Try it online!](https://tio.run/##LVDLDcIwDL0zhbmgVopE7CR2OgFDoB65IBbgihCswQAMAFc6CSwSbLdSpDzZ7ycfD6fTubXptv6@H9/XdbP9PNt0/12e@nat7TsOkPoAXQ7AaEBSADKAFEAnK@gox2VW9OdsSJeD89kEWA0acJqYNM4maJIZSgDJ3I8B9l0NUJy6/LbM4hlm49bohl5PNFl8jWxTnt2z2TiBSBko3oOqYR6806AMd6OoESl5e7QQwpkQLcWFJeo5SnUKk51GPKeiuqSS@/EP "Jelly – Try It Online")
### How it works
```
Æ!ṠḄ&/¬ Main link. Argument: (x, y) (pair of integers)
Æ! Convert x and y to factorial base.
Ṡ Apply the sign function to each digit.
Ḅ Unbinary; convert each resulting Boolean array from base 2 to integer.
&/ Reduce the resulting pair of integers by bitwise AND.
¬ Take the logical NOT of the result.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~93~~ 91 bytes
```
lambda a,b:k(a)&k(b)=={0}
k=lambda t,n=1,a=1:{t}&{0}or a*n>t and{a-1}|k(t-n)or k(t,n*a,a+1)
```
[Try it online!](https://tio.run/##jVBNbwIhEL3vr5j0YBaLzc7CwmqCf6TtAWOMZhWNpQdD@e1bZjDptSdeZt7H8G6PeLwGNR/cx3z2l93eg5e7zdR6sZjanXAudbmZ3HMXZXAovcNNinlRVtc7@GXYRvBhn/wK88/UxlUQZV6ADEsv/SuKOd6/4/EBDt6TkaCyhKQlGCRglYSeAPYSeNLr7jkayms0zySseWmIj2OWDSRCzLMk7aoJkqZCK8Fqkz@b5uDPXzV/lDCw5PkSSVsOIzvOQDbmM205wfIaDU1NTdFko/iIvi8UtCObjYTNmrBaF0r9T1cylOJ/IKX0WAkdxbBw6Eovw6jZ0fRUkuWkEYuNGjR/otQa4RSg1rlpAG73U4jtS8qw2kLKL2@Fc/GxdA@HdhmFEE2liD81d/E/8fwL "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
h=lambda a,b,d=2:a<1or a%d*(b%d)<h(a/d,b/d,d+1)
```
[Try it online!](https://tio.run/##XVDLboMwELz7K/YSCdqVih/YJgpfUuVgy4mIlJII6KFCfDv1rnOoekAe1vNYz/NnGR6j2vehv4evmAIEjJh6dQwn@ZggHNJbFQ@pPg1V@EgY85feZb0v0/dl7j9Xi6A3hNUgWEnAaQRFQCoEnijTvEZtPq3hGULHl5b40m8oYCXEPEfSpphI0hToEJyx21lcw32@zJDjPULLitdJHOM4i9w4QrIvb@nyBo6vpaWpLSGGbDTvoFSmSOfZzBO2HWHdZUp5TpMztOZnSEpRshAaimFh2@RaWm/Y0SrqyHGSl9lGt6StuB9VnwWIKzWNEW4jcK9HAfCcbuMCuXWMteCfv7TSwH/e/gs "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), 71 bytes
```
(a,b,g=(n,e=1,f=1)=>n>=f&&g(n,++e,f*e)+((n/f|0)%e&&1<<e))=>!(g(a)&g(b))
```
JavaScript's integers are limited to 53 bits of precision, which is just about enough for 18!; this means that I can use a mask of 18 bits to track which factorials are needed.
[Answer]
# PHP, 109 Bytes
```
for(;$a?:$a=$argv[++$i];$a-=$r[$i][]=$f,$i<2?:$t+=in_array($f,$r[1]))for($c=$f=1;($a/$f*=$c)>=++$c;);echo!$t;
```
[Try it online!](https://tio.run/##FYxBCsIwEEXPIvxFYyza4kbTsQcJoQzB2GzaMATB08fp5vN5PF5ZS5vmopt26Rx4foIJLJ@vtxY5KOoJ4vX6QEgX5GlUqVrK28Ii/OsOKn4IxhwRRNVocB34inQmRPMibUVn3Duu@wnVtSJ5q4vKYlxr463dH38 "PHP – Try It Online")
[Answer]
# Mathematica, 73 bytes
```
F[x_]:=First@IntegerPartitions[x,99,Range[99]!];!IntersectingQ[F@#,F@#2]&
```
input form
>
> [x1,x2]
>
>
>
[Answer]
# C, ~~122~~ 119 bytes
```
G(q,i){return gamma(q+1)>i?gamma(q):G(q+1,i);}
Q(a,b,u,v){while(a&&b){a-=u=G(1,a);b-=v=G(1,b);if(a==b)exit();}exit(0);}
```
`Q` is the main function. It should be invoked with exactly two positive integer values. This exits with an [exit code](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/10741#10741) of `0` for truthy and `1` for falsy.
Although this does not seem to work on TIO, it works on my system with the [Homebrew](https://brew.sh) provided `gcc 7.1.0`.
I have not golfed in `C` in quite a while, so golfing tips are very much appreciated!
] |
[Question]
[
For Gregorian calendars, the date format varies from a country to another. There are three main formats recognized:
1. `YY-MM-DD` (big-endian)
2. `DD-MM-YY` (little-endian)
3. `MM-DD-YY` (middle-endian)
Your task is to write a program which, given an input string representing a date, output all the possible date formats by which this string can be interpreted as a date.
**Rules**
* The input date is in the format `xx-xx-xx`, where each field is two digits and zero-padded.
* The date is always valid (so you cannot get things like 14-13-17)
* The date is always at least one of the formats above (so you cannot get things like 17-14-11)
* Because we are in fact in a parallel world, **there are 31 days for every month of the year**, and consequently no leap years
* The date is between January 01, 2001 and December 31, 2099
* If there is only one format for the date, the code must print only it (only trailing newlines are allowed)
* If there are several formats for the date, they must be either separated by a comma, a space, a newline, or a combination of those
* You must output the exact name(s) of the format(s). Using distinct arbitrary values is not allowed.
* No leading or trailing characters others than a trailing space are allowed
* The output must be lowercase
* You are not allowed to use any built-in date or calendar functions
* The output formats do not have to be sorted
**Examples**
```
Input Output
30-05-17 big-endian, little-endian
05-15-11 middle-endian
99-01-02 big-endian
12-11-31 big-endian, little-endian, middle-endian
02-31-33 middle-endian
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. Explanations are encouraged.
[Answer]
# [Python 2](https://docs.python.org/2/), 123 bytes
```
a,b,c=map(int,input().split('-'))
for a,b,c in[[b,c,'big'],[b,a,'little'],[a,b,'middle']]:print(c+'-endian')*(a<13)*(b<32),
```
[Try it online!](https://tio.run/nexus/python2#HYxLDoMwDAX3PQU7x61T8VlR0ZMgFg6hlSUIEU3PHxxW80YavczkaH5vHI2ERBLiPxl8/uIqyYAFxNtnP6qrqiSMo5LAyRcm0s0EGqZ1KVoi2MT7otMrHvpo5gfYJXjhAHg3PDSdwg1di5Qz9L2tG1u3cAI "Python 2 – TIO Nexus")
---
## [Python 2](https://docs.python.org/2/), less input parsing, 123 bytes
```
d=input()
for a,b,c in[[3,6,'big'],[3,0,'little'],[0,3,'middle']]:print(c+'-endian')*(int(d[a:a+2])<13)*(int(d[b:b+2])<32),
```
[Try it online!](https://tio.run/nexus/python2#PchBDsIgEEDRvafobsAOCe1ETYg9CWEBpZpJ6tg0eH4qLtz9/2qeWLZPUfr0eO9dxIRzx@I94RUh8RMCftsirFzKurS1SAgvzrltcNvOUtTcg1kkcxTQZ9Uk@@hiPwZ9H@hPyaUf0aixViBr7MUMNzgA "Python 2 – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~121~~ ~~119~~ ~~118~~ 112 bytes
Returns a space-delimited string with a trailing space.
```
s=>['big','little','middle'].map((v,i)=>[b<13&c<32,b<13&a<32,a<13][i]?v+'-endian ':'',[a,b,c]=s.split`-`).join``
```
### How?
We split the input into **a**, **b** and **c**. Because the date is guaranteed to be valid, we know for sure that **b** is less than 32. Therefore, it's enough to test whether **a** is less than 13 to validate the middle-endian format. Little-endian and big-endian formats require **b** to be less than 13 and another test on **a** and **c** respectively to validate the day.
Hence the 3 tests:
* Big-endian: **b < 13 & c < 32**
* Little-endian: **b < 13 & a < 32**
* Middle-endian: **a < 13**
### Test cases
```
let f =
s=>['big','little','middle'].map((v,i)=>[b<13&c<32,b<13&a<32,a<13][i]?v+'-endian ':'',[a,b,c]=s.split`-`).join``
console.log(f("30-05-17")) // big-endian, little-endian
console.log(f("05-15-11")) // middle-endian
console.log(f("99-01-02")) // big-endian
console.log(f("12-11-31")) // big-endian, little-endian, middle-endian
console.log(f("02-31-33")) // middle-endian
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 40 bytes
```
'-¡©2£13‹`®Á2£32‹*)˜“Œ±„¥„ê“#Ï’-„–ian’«»
```
[Try it online!](https://tio.run/nexus/05ab1e#@6@ue2jhoZVGhxYbGj9q2JlwaN3hRiDH2AjI0dI8PedRw5yjkw5tfNQw79BSIHF4FVBA@XD/o4aZukDuo4bJmYl5QM6h1Yd2//9vbKBrYKpraA4A "05AB1E – TIO Nexus")
**Explanation**
```
'-¡© # split on "-" and store a copy in register
2£13‹ # compare the first 2 elements to 13
` # split as separate to stack
# the bottom element is true if it is middle endian
# the top value is true if it can be big/little
®Á # retrieve the list from register and rotate right
2£32‹ # compare the first 2 elements to 32
* # multiply with the result of the comparison to 13
)˜ # wrap in a flattened list
“Œ±„¥„ê“# # push the list ['middle', 'big', 'little']
Ï # index into this with the flattened list
# this leaves the types the date could be
’-„–ian’« # append "-endian" to each
» # join on newlines
```
[Answer]
# Bash, ~~240~~ ~~125~~ ~~116~~ 112 bytes
```
IFS=- read a b c<<<$1
d=-endian
((b<13))&&(((a<32))&&echo little$d;((c<32))&&echo big$d);((a<13))&&echo middle$d
```
Golfed.
Thanks to manatwork for some tips
Saved 9 bytes removing the verification for less than 32 in the middle-endian follwing Arnauld answer
Saved 4 bytes by using different variables instead of an array
[Test it!](https://tio.run/##TYuxCsIwEED3fsUNoVyGQGMQh6ar4OwXXO4OE6gp1P66cyS6uD0e7yV65dZu1/viYFcSIEjAMUbjB1mcVilUB8QUfbB2HBGRYjh1VM4brOU4VjUyI/K/T@VhxM69/o1f@ywivW6thclNZ@cv77o5Js76AQ)
[Answer]
# C#, 180 bytes
```
t=(n,m)=>int.Parse(n)<13&int.Parse(m)<32;s=>{var a=s.Split('-');return$"{(t(a[1],a[2])?"big-endian":"")} {(t(a[1],a[0])?"little-endian":"")} {(t(a[0],a[1])?"middle-endian":"")}";};
```
Outputs with only space separated values, can also have leading and trailing spaces. Will update when the OP has clarified on that point if needed.
Full/Formatted version:
```
Func<string, string, bool> t = (n, m) => int.Parse(n) < 13 & int.Parse(m) < 32;
Func<string, string> f = s =>
{
var a = s.Split('-');
return $"{(t(a[1], a[2]) ? "big-endian" : "")} {(t(a[1], a[0]) ? "little-endian" : "")} {(t(a[0], a[1]) ? "middle-endian" : "")}";
};
```
[Answer]
# PHP, 151 Bytes
```
[$a,$b,$c]=sscanf($argn,"%d-%d-%d");$z="-endian ";echo($m=$b&&$b<13)&&$c&&$c<32?big.$z:"",$m&&$a&&$a<32?little.$z:"",$a&&$a<13&&$b&&$b<32?middle.$z:"";
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/a8fd337776b0823df4595de41d67a18c228945a7)
[Answer]
## Batch, 138 bytes
```
@echo off
set/ps=
call:l little %s:-= %
exit/b
:l
call:e big %4 %3
call:e middle %3 %2
:e
if %2 leq 31 if %3 leq 12 echo %1-endian
```
Vaguely based on @ovs's answer.
[Answer]
# Java 232 bytes
```
(String s)=>{String[]i=s.split("-");String e="-endian",b="big"+e,m="middle"+e,l="little"+e;int p=Integer.valueOf(i[0]);System.out.print(p<13?Integer.valueOf(i[1])<13?Integer.valueOf(i[2])<32?b+","+m+","+l:m+","+l:m:p<32?b+","+l:b);}
```
**Here's a nicer version**
```
String[] i = s.split("-");
String e = "-endian",
b = "big" + e,
m = "middle" + e,
l = "little" + e;
int p = Integer.valueOf(i[0]);
```
I didn't really know how to format this part...
```
System.out.print(
p < 13 ? Integer.valueOf(I[1]) < 13 ? Integer.valueOf(I[2]) < 32 ? b + "," + m + "," + l
: m + "," + l
: m
: p < 32 ? b + "," + l
: b
);
```
[Answer]
# PHP, 131 bytes
```
[$a,$b,$c]=explode('-',$argn);foreach([[big,b,c],[little,b,a],[middle,a,b]]as[$t,$x,$y])echo$$x*$$y&&$$x<13&$$y<32?"$t-endian ":"";
```
] |
[Question]
[
(There are related questions about [infinite sandpiles](https://codegolf.stackexchange.com/q/92251/194), and [finding identity elements of sandpiles](https://codegolf.stackexchange.com/questions/106963/find-the-identity-sandpile).)
Given a matrix of non-negative integers, return a matrix of the same dimensions, but *toppled*:
1. If the matrix doesn't contain any values larger than 4, return it.
2. Every "cell" that is larger than 3 gets reduced by 4, and all directly neighboring cells (above, below, left, and right) are incremented, if they exist.
3. GOTO 1.
### Examples:
```
0 1 0 0 2 0
2 4 0 -> 3 0 1
0 0 3 0 1 3
1 2 3 2 3 4 2 5 1 4 1 2 0 3 3 0 3 3 0 3 3
4 5 6 -> 2 4 4 -> 4 2 3 -> 0 5 4 -> 3 2 1 -> 3 3 1 -> 3 3 2
7 8 9 5 7 7 2 6 5 4 3 2 0 5 3 1 1 4 1 2 0
```
(You only need to return the final result. The path on which you reach it may differ from the one shown here: it doesn't matter in which order you perform the toppling operations, they all lead to the same result.)
For a deeper explanation and some motivation see [this Numberphile video](https://www.youtube.com/watch?v=1MtEUErz7Gg) or the Wikipedia article on the [Abelian sandpile model](https://en.wikipedia.org/wiki/Abelian_sandpile_model).
## Rules:
* You may take input and output in [any of the standard ways](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet)
* [Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* Input and output may be:
+ a nested list: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
+ a simple list: `[1, 2, 3, 4, 5, 6, 7, 8, 9]` and the shape
+ some kind of native matrix type
+ a string, e.g. `1 2 3\n4 5 6\n7 8 9`
+ or whatever else works in your language.
* Input and output must be in the same form
* The input may contain larger numbers than the ones shown here, but the size may be bound by the limits of your language (MAXINT equivalents, if applicable)
* The matrix may have any shape (e.g. 1x1, 2x2, 3x3, 4x4, 2x7, 11x3, ...)
* You don't need to handle the case where the shape is 0xN or Nx0.
## Testcases
```
[[2, 5, 4], [8, 6, 4], [1, 2, 3]] -> [[3, 3, 0], [1, 2, 2], [1, 3, 2]]
[[0, 0, 2], [1, 3, 3], [0, 0, 0]] -> [[0, 0, 2], [1, 3, 3], [0, 0, 0]]
[[9, 9, 9], [9, 9, 9], [9, 9, 9]] -> [[1, 3, 1], [3, 1, 3], [1, 3, 1]]
[[4, 5], [2, 3]] -> [[2, 3], [0, 1]]
[[2, 3, 5], [2, 2, 0]] -> [[3, 0, 2], [2, 3, 1]]
[[7]] -> [[3]]
```
This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), the shortest code (per language) wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
tss:"t3>t1Y6Z+w4*-+
```
Try it at [MATL Online!](https://matl.io/?code=tss%3A%22t3%3Et1Y6Z%2Bw4%2a-%2B&inputs=%5B1+%2C2+%2C+3%3B+4%2C+5%2C+6%3B+7%2C+8+%2C9%5D&version=19.8.0) Or [verify all test cases](https://tio.run/nexus/matl#XYw9CoAwFIN3TxFcBH2F2tbfgpNHcPCHgndowePX17oJGZIvJHcM3s9l0Etoj/5sHlOLJrpKCFHt6xYvRegIxmIk9Nm0BIbaFZcksFRGmmXxEcndREiy@BvuDH9aKFA6UXmbcv5N28G9).
### Explanation
The program iterates for as many times as the sum of the input. This is a loose upper bound on the required number of iterations.
For each iteration, entries in the sandpile matrix exceeding `3` are detected, giving a matrix of `1` and `0`, which is convolved with the 4-neighbour mask. The entries exceeding `3` in the sandpile matrix are reduced by `4`, and the result of the convolution is added.
For the last iterations, in which the sandpile matrix does not have any numbers exceeding `3`, zeros are subtracted from and added to it, so it is unaffected.
```
t % Implicit input (matrix). Duplicate
ss % Sum of matrix entries
:" % Repeat that many times
t % Duplicate
3> % True for matrix entries that exceed 3
t % Duplicate
1Y6 % Push predefined literal [0, 1, 0; 1, 0, 1; 0, 1, 0]
Z+ % 2D convolution, keeping size
w % Swap
4* % Multiply by 4
- % Subtract
+ % Add
% Implicit end. Implicit display
```
[Answer]
## Mathematica, 65 bytes
```
#//.s_:>s+ListConvolve[{v={0,1,0},1-v,v},x=UnitStep[s-4],2,0]-4x&
```
### Explanation
```
#//.s_:>...&
```
Repeatedly transform the input by toppling all piles greater than 3. This process stops automatically when the transformation fails to change the matrix (i.e. when no large piles exist any more). In the following expression the matrix is called `s`.
```
...x=UnitStep[s-4]...
```
Create a matrix that has a `1` whenever the current matrix has a `4` or greater, and a zero otherwise. This is essentially a mask that indicates which piles need to be toppled. Call the mask `x`.
```
ListConvolve[{v={0,1,0},1-v,v},x=UnitStep[s-4],2,0]
```
First we compute the number of sand that is added to each pile due to toppled neighbouring piles. This is done with a convolution of the following matrix over `x`:
```
0 1 0
1 0 1
0 1 0
```
Essentially, it adds one to the current cell for each of its von-Neumann neighbours in the mask.
```
s+...-4x
```
We add the previous result to `s` and then we subtract four times the mask from it to reduce the toppled piles.
[Answer]
# Octave, 65 bytes
This doesn't seem very good, I must be missing some tricks...
```
m=input(0);do;m+=conv2(m>3,[0 1 0;1 -4 1;0 1 0],"same")
until m<4
```
[Answer]
## JavaScript (ES6), ~~101~~ 95 bytes
Takes the width of the matrix `w` and an array of values `a` in currying syntax `(w)(a)`. Returns an array of values.
```
w=>g=a=>(b=a.map((n,i)=>n%4+(F=d=>~m|i%w&&a[i+d]>>2)(m=w)+F(-w)+F(m=-1)+F(!++i)))+0==a+0?a:g(b)
```
### Formatted and commented
```
w => // main function: takes w as input, returns g
g = a => // recursive function g: takes a as input
( //
b = a.map((n, i) => // for each element n at position i in a:
n % 4 + ( // keep only n MOD 4
F = d => // define F(): function that takes d as input
~m | // if m is not equal to -1
i % w && // or i MOD w is not null:
a[i + d] >> 2 // return a fourth of the value of the cell at i + d
)(m = w) + // test the cell below the current cell
F(-w) + // test the cell above
F(m = -1) + // test the cell on the left
F(!++i) // test the cell on the right
) // end of map(): assign the result to b
) + 0 == a + 0 ? // if b is equal to a:
a // stop recursion and return a
: // else:
g(b) // do a recursive call with b
```
### Test cases
```
let f =
w=>g=a=>(b=a.map((n,i)=>n%4+(F=d=>~m|i%w&&a[i+d]>>2)(m=w)+F(-w)+F(m=-1)+F(!++i)))+0==a+0?a:g(b)
console.log(JSON.stringify(f(3)([2, 5, 4, 8, 6, 4, 1, 2, 3]))); // -> [3, 3, 0, 1, 2, 2, 1, 3, 2]
console.log(JSON.stringify(f(3)([0, 0, 2, 1, 3, 3, 0, 0, 0]))); // -> [0, 0, 2, 1, 3, 3, 0, 0, 0]
console.log(JSON.stringify(f(3)([9, 9, 9, 9, 9, 9, 9, 9, 9]))); // -> [1, 3, 1, 3, 1, 3, 1, 3, 1]
console.log(JSON.stringify(f(2)([4, 5, 2, 3]))); // -> [2, 3, 0, 1]
console.log(JSON.stringify(f(3)([2, 3, 5, 2, 2, 0]))); // -> [3, 0, 2, 2, 3, 1]
console.log(JSON.stringify(f(1)([7]))); // -> [3]
```
[Answer]
## JavaScript (ES6), ~~118~~ ~~114~~ 104 bytes
*Saved 2 bytes thanks to @Neil*
```
f=a=>a.find(b=>++y&&b.find(c=>++x&&c>3,x=0),y=0)?f(a.map(b=>b.map(c=>c+=--i|y?i*i+y*y==1:-4,i=x,--y))):a
```
[Answer]
# C++, ~~261~~ ~~258~~ 250 bytes
```
#import<vector>
#define S size()
void f(std::vector<std::vector<int>>&m){s:int i,j,r;for(i=r=0;i<m.S;++i)for(j=0;j<m[i].S;++j){if(m[i][j]>3){r=1;m[i][j]-=4;j>0&&m[i][j-1]++;i>0&&m[i-1][j]++;j<m[i].S-1&&m[i][j+1]++;i<m.S-1&&m[i+1][j]++;}}if(r)goto s;}
```
Takes input as a reference to a vector of vectors and modifies it directly.
[Try it online!](https://tio.run/nexus/cpp-gcc#lVLLboMwELzzFatEQlg4Fc@0xcBP5JjmEAWojApEhnAo8renawy0kdooRdZqdnZ27DW@rnl1bkQX9/mpa0RqrLO84HUOO2j5Z24Ro294BoXVdlkUaVH8E/O6S1OzIkMbIQROSypY0QiLJyJxGI@rpx2zbU4UVyJTxtWeH0ayJAMvLJXuy0Pqk0EkLpvSTRKwMnVMU@cb92DbjE8EZihBYjbbuLPQ1kK17UTas1hK3E2Q96ZroGXyuub16eOS5RDzpu1EfqxSPe1Z4Cj3JwazJ8ZgAH5qsOMFPXsXIkBakbp0U85V1SUwep2aSwdxjCSGFazYor8pr97qqSSNP4rSUPdeHXltzSe6f/LeTYbBoxBSCCSF4YXCdoIuBSz4UrJHfDz0cSjg8qZmXzUj1KzzoI@PPq8U1FLNv8DHfAL0CXAu1fmPMUJ9Hf53p/f42bfY/DxrCwv/L8PojdEfYzDGcIxbooX6gSnxhLwF@QsKFhQuSBnI6xc)
] |
Subsets and Splits