text
stringlengths 180
608k
|
---|
[Question]
[
Given a Black Box function `ff` that takes a single floating-point parameter, write a function `M` to generate the [Maclaurin series](http://en.wikipedia.org/wiki/Taylor_series) for that function, according to the following specifications:
* take a parameter `n`, and generate all terms from `x^0` to `x^n` where `0 <= n <= 10`
* coefficients for each term should be given to at least 5 decimal places for non-integral values; underflows can simply be ignored or replaced with `0` and left out if you wish, or you can use scientific notation and more decimal places
* assume `ff` is a continuous function and everywhere/infinitely differentiable for `x > -1`, and returns values for input `x` in the range: `-10^9 <= ff(x) <= 10^9`
* programming languages with functions as first-class data types can take `ff` as a parameter; all other languages assume a function called `ff` has already been defined.
* output should be formatted like `# + #x + #x^2 + #x^5 - #x^8 - #x^9 ...`, i.e., terms having `0` coefficient should be left out, and negative coefficients should be written `- #x^i` instead of `+ -#x^i`; if the output terms are all zero, you can output either `0` or null output
* output can be generated either to `stdout` or as a return value of type `string` from the function
Examples (passing `ff` as a first parameter):
```
> M(x => sin(x), 8)
x - 0.16667x^3 + 0.00833x^5 - 0.00020x^7
> M(x => e^x, 4)
1 + x + 0.5x^2 + 0.16667x^3 + 0.04167x^4
> M(x => sqrt(1+x), 4)
1 + 0.5x - 0.125x^2 + 0.0625x^3 - 0.03906x^4
> M(x => sin(x), 0)
0 (or blank is also accepted)
```
[Answer]
## Python, 188 chars
```
D=lambda f:lambda x:100*(f(x+.005)-f(x-.005))
def M(f,n):
s="";d=1
for i in xrange(n+1):
c=f(0)/d;f=D(f);d*=i+1
if c:s+='%+.5f'%c+['','x','x^%d'%i][(i>0)+(i>1)]
print s[s[:1]=='+':]
```
This code takes lots of liberties with accuracy and numerical stability, but it generates something close to the right answer for the given examples.
Running it:
```
import math
M(lambda x:math.sin(x),8)
M(lambda x:math.exp(x),4)
M(lambda x:math.sqrt(x+1),4)
M(lambda x:math.sin(x),0)
```
gives:
```
1.00000x-0.16666x^3+0.00833x^5-0.00020x^7
1.00000+1.00000x+0.50000x^2+0.16667x^3+0.04167x^4
1.00000+0.50000x-0.12500x^2+0.06251x^3-0.03907x^4
<a blank line>
```
[Answer]
### Ruby, 173 chars
```
M=->n{r=(-n..n).map{|x|ff(x/2e2)};((0..n).map{|t|u=r[n-t];t<n&&r=r[2..-1].zip(r).map{|x,y|(x-y)*1e2/(t+1)};u.abs<1e-5?'':'%+.5f'%u+(t<2??x[0,t]:'x^%d'%t)}*'').sub(/^\+/,'')}
```
Unfortunately this approach is similar to Keith's solution and thus also numerically unstable for large `n`.
```
def ff(x) Math.sin(x) end
puts M[8] # 1.00000x-0.16666x^3+0.00833x^5-0.00020x^7
def ff(x) Math.exp(x) end
puts M[4] # 1.00000+1.00000x+0.50000x^2+0.16667x^3+0.04167x^4
def ff(x) Math.sqrt(1+x) end
puts M[4] # 1.00000+0.50000x-0.12500x^2+0.06251x^3-0.03907x^4
def ff(x) Math.sin(x) end
puts M[0] # <empty line>
```
[Answer]
## Mathematica, 39 chars
```
InputForm@N@Normal@Series[#1,{x,0,#2}]&
```
Usage
```
%[Sin[x], 8]
```
Output
```
x - 0.16666666666666666*x^3 + 0.008333333333333333*x^5 - 0.0001984126984126984*x^7
```
[Answer]
## GCC, 549 chars
```
#define f __float128
#define D long double
#define L(v)for(v=0;v<n;v++)
void G(f a[],int n,double d){f m[n][n],s;int
i,j,k;L(i)L(j)m[i][j]=j?m[i][j-1]*d*(i-n/2):1;L(i){s=m[i][i];L(j)m[i][j]/=s;a[i]/=s;L(j)if(j^i){s=m[j][i];L(k)m[j][k]-=s*m[i][k];a[j]-=s*a[i];}}}
#define F(a)L(i)a[i]=(f)ff(d*(i-n/2));G(a,n,d);
void M(int n){f p[++n],q[n];double d=1;int
i,j=1;F(p)while(j){d/=2;F(q)j=0;L(i){j|=(p[i]-q[i])>1E-7;p[i]=q[i];}}L(i)if(p[i]<-5E-6){printf("- %.5Lfx^%d ",(D)-p[i],i);j=1;}else if(p[i]>5E-6){printf("%s%.5Lfx^%d ",j?"+ ":"",(D)p[i],i);j=1;}}
```
Example usage (ungolfed):
```
#include <math.h>
#include <stdio.h>
double ff(double x)
{
return sin(x);
}
#define f __float128
#define D long double
#define L(v) for(v=0;v<n;v++)
void G(f a[],int n,double d) {
f m[n][n],s;
int i,j,k;
L(i) L(j) m[i][j] = j ? m[i][j-1]*d*(i-n/2) : 1;
L(i) {
s=m[i][i]; L(j) m[i][j]/=s; a[i]/=s;
L(j) if(j^i) {
s=m[j][i]; L(k) m[j][k]-=s*m[i][k]; a[j]-=s*a[i];
}
}
}
#define F(a) L(i) a[i]=(f)ff(d*(i-n/2)); G(a,n,d);
void M(int n) {
f p[++n],q[n];
double d=1;
int i,j=1;
F(p)
while(j) {
d/=2;
F(q)
j=0;
L(i) {
j|=(p[i]-q[i])>1E-7;
p[i]=q[i];
}
}
L(i)
if (p[i]<-5E-6) { printf("- %.5Lfx^%d ",(D)-p[i],i); j=1; }
else if (p[i]>5E-6) { printf("%s%.5Lfx^%d ",j?"+ ":"",(D)p[i],i); j=1; }
}
void main()
{
M(8);
}
```
Compiles with just `gcc maclaurin.c -lm`
I'm sure that someone who actually knows C can shave at least 10% off, but if nothing else it gets the ball rolling.
With a bit of playing with matrix inverses I've discovered a shorter, but less numerically stable, method which exploits the particular structure of the matrices to special-case the Gaussian elimination:
### Alternate, 536 chars
```
#define f __float128
#define D long double
#define L(v)for(v=0;v<n;v++)
void G(f a[],int n,double d){int i,t;f F[n];L(i)F[i]=i?i*F[i-1]:1;while(--n>0){f c=0;t=2*(n&1)-1;for(i=0;i<=n;i++){t=-t;c+=t*a[i]/F[i]/F[n-i];}L(i)a[i]-=c*pow(i,n);L(i)c/=d;a[n]=c;}}
#define F(a)L(i)a[i]=(f)ff(d*i);G(a,n,d);
void M(int n){f p[++n],q[n];double d=.5;int i,j=1;F(p)while(j){d/=2;F(q)j=0;L(i){j|=(p[i]-q[i])>1E-7;p[i]=q[i];}}L(i)if(p[i]<-5E-6){printf("- %.5Lfx^%d ",(D)-p[i],i);j=1;}else if(p[i]>5E-6){printf("%s%.5Lfx^%d ",j?"+ ":"",(D)p[i],i);j=1;}}
```
However, this really needs a better error check, so that when it hits the point at which the largest term in the polynomial starts blowing out of control it will quit the loop.
] |
[Question]
[
The inverse of [this question](https://codegolf.stackexchange.com/questions/232957/enlarge-ascii-art-mark-ii?noredirect=1&lq=1).
Your challenge is to, given a piece of ASCII art generated by the above question and its enlargement factor, shrink it down to its original size.
## The enlargement process
[Or look at this](https://codegolf.stackexchange.com/questions/232957/enlarge-ascii-art-mark-ii?noredirect=1&lq=1)
ASCII art within a limited character set can be enlarged to a certain (odd) size by replacing certain characters with larger versions of themselves, like so:
```
-\
|
_/
, 3 =>
\
--- \
\
|
|
|
/
/
___/
```
Because each character is enlarged to a 3x3 square.
Only those six characters (`\/|-_` ) can be enlarged, and only those will be in your input. For a more detailed explanation, see the linked challenge.
I/O may be as a char matrix, ascii art, list of rows, etc.
## Testcases
```
\
\
\
, 3 =>
\
---------
, 3 =>
---
|
|
|
|
|
|
|
|
| , 3 =>
|
|
|
| \ / |
| \ / |
| \___/ |
| |
| |
| |
\ /
\ /
\___/
, 3 =>
|\_/|
| |
\_/
_______________
\ /
\ /
\ /
/ \
/ \
/ \
\ /
\ /
\_________/ , 3 =>
_____
\ /
/ \
\___/
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ ____________ \
| |
| |
| |
| |
| |
| |
/ \
/ \
___/ ______ \___, 3 =>
/\
/ \
/____\
||
||
_/__\_
\ /
\ /
\ /
\ /
\/
\ /
\ /
\ /
\ /
\/ , 5 =>
\/
\/
/ /
/ /
/ /
/ ------- /
/ /
/ /
/ /
\ \
\ \
\ \
\ ------- \
\ \
\ \
\ \, 7 =>
/-/
\-\
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
»/⁹ÐƤ⁺€
```
A monadic Link accepting a list of lines that yields a list of lines.
**[Try it online!](https://tio.run/##y0rNyan8///Qbv1HjTsPTzi25FHjrkdNa/4/3L3l8PLI//8VoEA/BsbigokoKMSgCumDiBhkIX0IJwYhpA8zJgYmBBeBiHGhiIDFuFBFQGJcQJF4JAAUg7mrBoxQnEpTIYJ@BDoP7lqgGJD8bwwA "Jelly – Try It Online")**
### How?
```
»/⁹ÐƤ⁺€ - Link: list of lists of characters, Lines; pixel size, N
ÐƤ - for non-overlapping infixes
⁹ - ...of length: chain's right argument, N
/ - ...yield: reduce by:
- maximum (vectorises)
(Note: space is less than any other character used)
€ - for each:
⁺ - repeat the last link - i.e. do Ṁ⁹ÐƤ
```
[Answer]
# JavaScript (ES6), 106 bytes
```
x=>n=>x.replace(/.+\n.+\n.+/g,y=>[...(z=y.split`
`)[~-n/2]].map((w,i)=>i%3-1?"":w<"!"?z[n-1][i]:w).join``)
```
Now actually works!
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
{.@-.&' '@,;.3~2 2&$
```
[Try it online!](https://tio.run/##vVNNS8NAEL3Pr3iINA00O5IiQkIhIHjy5NWBPYitePEHKP3rMZvsZ7KhxYNDF/Jed4Z5O28@@xtVHHFoUGCHOzTDqRQeX56f@m/VVWpToOh2rdqfa9Sb276k06F5f/v46rZtezyXtMcJr63SNbZjeklCGH7Dyf0JF1S5iLhsxg8unpU8sXXZ3rMEw2GI1nqAHru4BiOqjxGH@hb7@ivadBokiIMJMcGmpkTQYPZYDObovoA4qSfX1PfN8No83HWfS6EjSSkOj2Ip9s06iiMBE8WxhpnKnFCvNX5LjCa0w/Kz@xfqosbpdX2fZvIl3S8XaTmo4IFp/OY7uG8y3p/ShgYeVkbNc9NkyJnMyKAjaTc9rMri5nKmdm1yJGZG9g7L0cnSJD6TpDNJlzhxW44m5Ggq@18 "J – Try It Online")
With `(y x,:h w) u;.3 a` we can split `a` into tiles of size `h w` while sliding the window by `y x`. Because we don't want overlapping tiles, we can simply build a 2x2 matrix of the input, e.g. `3 3,:3 3`. On these tiles `u` gets applied, which flattens `,` the tile into a list, removes any whitespace `-.&' '` and then reduces the tile to the first remaining element `{.`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθWS⊞υ⭆⪪ιθ⌈κE⪪υθ⭆⌈ι⌈Eι§νμ
```
[Try it online!](https://tio.run/##tc@xCoMwEADQPV9x4wUiGTo6dXSwCF0DxVqpodGqTVqH/nsao6kKXXuEkDzujruiyvvinitrk6Y1@mDqc9ljR2PyqqQqAT0fdS@bK1IKmXlUaBhMkuYtHlslNUoGHWWQ5oOsTY03Sl2LzOVoXJLMlLTUhnS5Kh3dddvrpLmUAzYMauojtnZHYA4uwisQBxBb4uMl1sSnj1iIhzYi0FcmIxvxRrYyGnFyWoWzMNfbn82of6VfO0Y@5h3deOsd3ZfY6Kk@ "Charcoal – Try It Online") Link is to verbose version of code. Takes the enlargement factor followed by a list of newline-terminated strings. Explanation:
```
Nθ
```
Input the enlargement factor.
```
WS⊞υ⭆⪪ιθ⌈κ
```
Input the strings, but split them into substrings of length equal to the enlargement factor and take the maximum character of each substring.
```
E⪪υθ⭆⌈ι⌈Eι§νμ
```
Split the list of strings into sublists of length equal to the enlargement factor, then transpose the sublists and take the maximum character of each, joined back into a string, and print each sublist's string on its own line.
[Answer]
# JavaScript, 84 bytes
```
a=>n=>a.map((r,i)=>r.map((c,j)=>(d=b[i/n|0]||=[])[x=j/n|0]=d[x]?.trim()||c),b=[])&&b
```
```
f=
a=>n=>a.map((r,i)=>r.map((c,j)=>(d=b[i/n|0]||=[])[x=j/n|0]=d[x]?.trim()||c),b=[])&&b
str2mat = str => str.split('\n').map(r => [...r]);
mat2str = mat => mat.map(r => r.join('')).join('\n');
test = (s, n) => console.log(mat2str(f(str2mat(s.slice(1, -1)))(n)));
test(String.raw`
\
\
\
`, 3);
test(String.raw`
---------
`, 3);
test(String.raw`
|
|
|
|
|
|
|
|
|
`, 3);
test(String.raw`
| \ / |
| \ / |
| \___/ |
| |
| |
| |
\ /
\ /
\___/
`, 3);
test(String.raw`
_______________
\ /
\ /
\ /
/ \
/ \
/ \
\ /
\ /
\_________/
`, 3);
test(String.raw`
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ ____________ \
| |
| |
| |
| |
| |
| |
/ \
/ \
___/ ______ \___
`, 3);
test(String.raw`
\ /
\ /
\ /
\ /
\/
\ /
\ /
\ /
\ /
\/
`, 5);
test(String.raw`
/ /
/ /
/ /
/ ------- /
/ /
/ /
/ /
\ \
\ \
\ \
\ ------- \
\ \
\ \
\ \
`, 7);
```
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
f n|let g[]=[];g x=maximum(take n x):g(drop n x)=g.map g
```
[Try it online!](https://tio.run/##bcaxDsIgFEbhnaf4B4c6AIObhidpG3JTKZLCtWlpwtB3R2X2LN950b64GGudwWd0Gb4fTT8@PIpJVEI6UpdpcWCU6913z@29tjdeJVrha6LAJnB2G035cnAM7HY146baVQADIKSUXwV@DY0Tf4BuaAhrrQY@ "Haskell – Try It Online")
] |
[Question]
[
## Background
[**A338268**](https://oeis.org/A338268) is a sequence related to [a challenge by Peter Kagey](https://codegolf.stackexchange.com/q/213848/78410). It defines a two-parameter function \$T(n,k)\$, which counts the number of integer sequences \$b\_1, \cdots, b\_t\$ where \$b\_1 + \cdots + b\_t = n\$ and \$\sqrt{b\_1 + \sqrt{b\_2 + \cdots + \sqrt{b\_t}}} = k\$. Since \$k\$ cannot be larger than \$\sqrt{n}\$, the relevant "grid" has an odd shape:
```
n\k| 1 2 3 4
---+---------
1 | 1
2 | 0
3 | 0
4 | 0 2
5 | 0 0
6 | 0 2
7 | 0 0
8 | 0 2
9 | 0 0 2
10 | 0 4 0
11 | 0 0 2
12 | 0 6 0
13 | 0 0 2
14 | 0 8 0
15 | 0 0 4
16 | 0 12 0 2
```
More precisely, \$n\$-th row is limited to \$1 \le k \le \lfloor \sqrt{n} \rfloor\$.
Furthermore, this part of the grid has many known zero entries, as written in the OEIS page:
* \$ T(n,1) = 0 \$ for \$n > 1\$.
* \$ T(n,k) = 0 \$ if \$n + k\$ is odd, i.e. \$n\$ and \$k\$ have a different parity.
In this challenge, **potential nonzero entries** means the terms whose \$(n,k)\$ pair satisfies none of the above, i.e. \$n+k\$ is even, and either \$n > 1\$ or \$(n,k) = (1,1)\$.
Also, every sequence on the OEIS must be linearly laid out, so the numbers are "read by rows" as follows:
```
1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 2, 0, 4, 0, 0, 0, 2, 0, 6, 0,
0, 0, 2, 0, 8, 0, 0, 0, 4, 0, 12, 0, 2, ...
```
In this sequence, the potential nonzero entries are at the following indices:
```
1-based: 1, 5, 9, 13, 16, 18, 22, 24, 28, 30, 34, 36, 38, ...
0-based: 0, 4, 8, 12, 15, 17, 21, 23, 27, 29, 33, 35, 37, ...
```
## Challenge
Output the 1-based or 0-based version of the sequence above.
[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O methods apply. You may use one of the following I/O methods:
* Take no input and output the sequence indefinitely,
* Take a (0- or 1-based) index \$i\$ and output the \$i\$-th term, or
* Take a non-negative integer \$i\$ and output the first \$i\$ terms.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
Prints the 0-based sequence forever.
```
d=n=k=0
while 1:k+=1;k**=k*k<=n;n+=k<2;k+n&1<(k>1%n)!=print(d);d+=1
```
[Try it online!](https://tio.run/##Dco7CoAwEAXA3lNooeTTuNqZrKeJkPBkDRIQT7869dS35UtW1cTC4Ll7cjmPnjZ4pgDnGA6RJYhnxCXAy0TRYKdR7MD1LtJMsiH9XfUD "Python 3 – Try It Online")
**Commented**:
```
d=n=k=0
while 1:
k+=1 # increment k
k**=k*k<=n # k=k**1=k if k*k<=n, else k=k**0=1
n+=k<2 # increment n if k is equal to 1
k+n&1<(k>1%n)!=print(d) # print index d if k+n&1==0 (same parity) and k>1%n (k>0 for n==1 and k>1 for n>1)
d+=1 # increment the index
```
[Try it online!](https://tio.run/##jVBLDoJADN17imeMBtAFoztDvQtxSpgUCsIY9fQ4Du400e7a92vbP3zd6WGaLCkJ5Ytb7RqGOS4A2ZLB11rB6XngltVDXswsI8mkIP1kSkAyQwJXYebswM3IM5CTCXrdkhT7X0kaLeBG8OVaNvAdTFxTN6ZI5GTWmi6pH5z6xKZRHJtgYfkOG@UvMoiQIxnLltGXg/OPFKVaRAsEpxxVN0Ap3P@ez4OTSUOg/esvvuY5eJqe "Python 3 – Try It Online")
[Answer]
# ARM T32 machine code, 34 bytes
```
b510 0001 d00c 2001 2204 3204 2302 3302
3001 001c 4364 1b14 d4f7 07a4 41a1 d1f6
bd10
```
Following the [AAPCS](https://github.com/ARM-software/abi-aa/blob/2bcab1e3b22d55170c563c3c7940134089176746/aapcs32/aapcs32.rst), this takes a 0-based index in r0 and returns the 0-based entry at that index in r0.
Assembly:
```
.section .text
.syntax unified
.global sequence
.thumb_func
sequence:
push {r4, lr} @ Save r4 and lr to the stack
movs r1, r0 @ Copy the index to r1
beq end @ Special case: 0 -> 0; return immediately
movs r0, #1 @ Counter of grid entries processed, initialised to 1
movs r2, #4 @ r2 holds 4*n, for reasons to be seen later
nextrow:
adds r2, #4 @ Advance to the next row: r2 is increased by 4...
movs r3, #2 @ and r3, which holds 2*k, is set to 2.
nextcol: @ With r3 being advanced immediately, this will skip k=1.
adds r3, #2 @ Increase r3 by 2 (increase k by 1)
adds r0, #1 @ Increment the counter
movs r4, r3 @ Duplicate the value of 2*k...
muls r4, r4, r4 @ square it, yielding 4*k^2...
subs r4, r2, r4 @ and subtract the square from 4*n.
bmi nextrow @ If that's negative, the row is over;
@ the counter has already been incremented, counting for the k=1 entry in the next row.
lsls r4, r4, #30 @ The criterion is the parity of n+k, which is the same as that of n-k^2,
@ and hence bit #2 of 4*n-4*k^2. Shifting it 30 places left puts that bit in the carry flag,
@ and leaves r4 with a value of 0. (This is why the rescaling is needed: LSL 32 is invalid.)
sbcs r1, r4 @ Subtract from r1 the value of r4 (0) plus the inverted carry flag.
@ This counts down the number of potential nonzero entries needed.
bne nextcol @ If it hasn't reached 0 yet, repeat.
end:
pop {r4, pc} @ Restore the value of r4 from the stack and return.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
²‘½€RḂ¬ÐeḊŻ$€FT1;ḣ
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//wrLigJjCveKCrFLhuILCrMOQZeG4isW7JOKCrEZUMTvhuKP///8yNQ "Jelly – Try It Online")
A monadic link taking an integer \$n\$ and returning the first \$n\$ terms of the sequence.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
Prints an infinite list of the 1-based sequence.
```
∞ε©tLε®+Éy®≠›‹]˜ƶ0K
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8c1sPrSzxAZLrtA93Vh5a96hzwaOGXY8adsaennNsm4H3//8A "05AB1E – Try It Online")
```
∞ε ] # for n in [1, 2, ...]:
© # store n in the register
tL # range from 1 to sqrt(n)
ε ] # for k in this range:
®+É # is n+k odd?
y®≠› # k > (n!=1)
‹ # (n+k odd) < (k > (n!=1))
] # close all loops
˜ # flatten the result into a single list
ƶ0K # indices of 1's: multiply by index, remove 0's
```
---
A more literal port of my python answer is one byte longer:
```
[>Dn¾›i¼1}о+És¾≠›‹–
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/2s4l79C@Rw27Mg/tMaw9POHQPu3DncVAkc4FQMFHDTsfNUz@/x8A "05AB1E – Try It Online")
```
# d is the iteration index
# n is the counter variable
# k is on top of the stack
[ # infinite loop, iteration index starts at 0
> # increment k
Dn¾›i } # if k**2 > n
¼1 # increment n and reset k to 1
Ð # push two copies of k
¾+É # is n+k odd?
s¾≠› # is k > (n!=1)
‹ # (n+k odd?) < (k > (n!=1))
– # if this is true, print the current iteration index
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page)
```
Ḥ½ḶoƊ€ḊŻĖS€ḂFTḣ
```
A monadic Link accepting \$i\$ which yields a list of the first \$i\$ terms.
**[Try it online!](https://tio.run/##y0rNyan8///hjiWH9j7csS3/WNejpjUPd3Qd3X1kWjCY2eQW8nDH4v///xuaAAA "Jelly – Try It Online")**
### How?
```
Ḥ½ḶoƊ€ḊŻĖS€ḂFTḣ - Link: positive integer, i
Ḥ - double -> 2i
€ - for each (x in [1..2i]):
Ɗ - last three links as a monad, f(x):
½ - square root (x) -> r
Ḷ - lowered range -> [0,1,2,3,4,...,floor(r)-1]
o - logical OR -> [x,1,2,3,4,...,floor(r)-1]
Ḋ - dequeue (drops the leading [1] from that list of lists)
Ż - prepend a zero
Ė - enumerate -> [[1,0],[2,[2]],[3,[3]],[4,[4,1]],...,[9,[9,1,2]],...,[16,[16,1,2,3]],...]
S€ - sum each -> [[1,[4],[6],[8,5]...[18,10,11],...[32,17,18,19],...]
Ḃ - mod 2 -> [[1,[0],[0],[0,1],...,[0,0,1],...,[0,1,0,1],...]
F - flatten
T - truthy indices (1-indexed)
ḣ - head to index (i)
```
] |
[Question]
[
The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one. Given a binary string \$S\$ of length \$n\$, we are a interested in the number of different strings of length \$n\$ which have distance at most \$3\$ from \$S\$.
For example, if \$S = 0000\$ there are four strings with Levenshtein distance exactly \$3\$ from \$S\$, six with distance exactly \$2\$, four with distance exactly \$1\$ and exactly one with distance \$0\$. This makes a total of \$15\$ distinct strings with distance at most \$3\$ from the string \$0000\$. The only string with distance greater than \$3\$ is \$1111\$.
However, this number depends on the value of \$S\$. For example if \$S = 0010\$ then the number of distinct strings with distance at most \$3\$ is \$16\$, in other words all of them.
For this task the input is a value of \$n \geq 3\$. Your code must output the average number of binary strings of length \$n\$ which have Levenshtein distance at most \$3\$ from a uniform and randomly sampled string \$S\$. Your answer can be output in any standard way you choose but it must be exact.
# Examples
```
n = 3. Average = 8
n = 4. Average = 15 1/2
n = 5. Average = 28 13/16
n = 6. Average = 50 15/16
n = 7. Average = 85 23/64
n = 8. Average = 135 27/32
n = 9. Average = 206 77/256
n = 10. Average = 300 181/256
n = 11. Average = 423 67/1024
n = 12. Average = 577 99/256
n = 13. Average = 767 2793/4096.
n = 14. Average = 997 3931/4096.
n = 15. Average = 1272 3711/16384.
```
# Score
Your score is the highest value of \$n\$ you can reach.
[Answer]
# [GAP](https://www.gap-system.org/) and the [automata](https://www.gap-system.org/Packages/automata.html) package
The average number is the number of pairs of words of length \$n\$ with Levenshtein distance up to three, divided by \$2^n\$.
It is not very difficult to construct an nondeterministic finite automaton over the alphabet of pairs of bits that accepts the word \$(a\_1,b\_1)(a\_2,b\_2)\dots(a\_n,b\_n)\$ iff the binary words \$a\_1a\_2\dots a\_n\$ and \$b\_1b\_2\dots b\_n\$ have Levenshtein distance up to three. My version uses 14 states. This automaton can be transformed into a minimal deterministic one, which has 39 states. From its transition function we can get a matrix that describes the number of ways we can get from one state to another. Now counting the number of ways we can get from the initial state to some accepting state is just a matter of multiplication.
The implicit recurrance could be simplified because some values are always equal, and it might be solved to give a closed formula, but it seems to be good enough as is.
```
LoadPackage("automata");
nfa := Automaton("nondet", 14, 4,
[[[1,5,9],[2,7,11],3,4,[5,13],[7,13],[7,14],14,
[9,13],[11,13],[11,14],14,13,14],
[[2,5,10],[3,7,12],4,0,[7,14],[5,14],0,7,
[10,14],[12,14],12,0,14,0],
[[2,6,9],[3,8,11],4,0,[6,14],[8,14],8,0,
[11,14],[9,14],0,11,14,0],
[[1,6,10],[2,8,12],3,4,[8,13],[6,13],14,[8,14],
[12,13],[10,13],14,[12,14],13,14] ],
[1], [1..14] );
dfa := MinimalizedAut(nfa);
size := NumberStatesOfAutomaton(dfa);;
mat := NullMat(size, size);;
for row in TransitionMatrixOfAutomaton(dfa) do
for i in [1..size] do
mat[i][row[i]] := mat[i][row[i]]+1;
od;
od;
init := 0 * [1..size];;
init[InitialStatesOfAutomaton(dfa)[1]] := 1;;
fin := 0 * [1..size];;
for i in FinalStatesOfAutomaton(dfa) do
fin[i] := 1;
od;
f := function(n)
local res, intpart, fraction;
res := init * mat^n * fin / 2^n;
intpart := Int(res);
fraction := res-intpart;
Print("n = ", n, ". Average = ", intpart);
if fraction <> 0 then
Print(" ",fraction);
fi;
Print(".\n");
end;
```
[Try it online!](https://tio.run/##dZTRb9MwEMbf81ec@pQMU@Ik6zrCkPaCNInBJHjLMsk0ybBIncl1AfHPl@/spKHTqNS4vvvu5@98Sh/V0@HwcVDNndr8UI9tvFB7N2yVU4ukjCLTKXp7RdchNph4YQbTtG4hSBaCChERf6qqkuJcXNaiysSFkLIWuShEdS5kjtjFcSlqfMcilF2GhJTzGhQy979GYQUqUCkkOeOzGvB0AvIpWFJkjmCZhpTMAjETHBDpCXLlDedi7Q174iqUrf2yRmQmBm9s2R/m9ydACaD3mDExG69gHVpb@UUWE3vmZmPv6VExmfZ3QJO2gkc8lksO8myaMJtbbfRW9fpP22BMMSbGyR32nP20335r7RenXLv73M1zbFgGHXZB1ve3ysVcJoifnO0GS3b4RdrQV6vMTjs9GMis/v2cRc0Am1ygWc4@mVKHOBGUla4r0LDUfORp5JUsoRuaMuJvhJ68r5TOZhYccby6wUOr/uWmcE0eL7m7DlZeoBxtftDmf5yxIW3gLvCCs4433d5s@C5ik0DUDxvVk213Akz3pKwT1FnlFdwVMlzkezrjvh8MVvb2hrIHLxnrWHZjXIyKhMMTheOIvR5lnLqz2OB1pCvCy2gELZZ0/bO1eIdDaNR6ju5m1Lv3uA/3vTV@LiMGBZMgHKz/OWN5b/jPoDVNeTiZcJbyfKmLdVL62XWxTNOkPPwF "GAP – Try It Online")
Put it in a file, start `gap` and read the file with a command like `Read("l3.gap");`, then try something like `f(20);` or `for i in [0..100] do f(i); od;`.
Here are some results:
```
n = 0. Average = 1.
n = 1. Average = 2.
n = 2. Average = 4.
n = 3. Average = 8.
n = 4. Average = 15 1/2.
n = 5. Average = 28 13/16.
n = 6. Average = 50 15/16.
n = 7. Average = 85 23/64.
n = 8. Average = 135 27/32.
n = 9. Average = 206 77/256.
n = 10. Average = 300 181/256.
n = 11. Average = 423 67/1024.
n = 12. Average = 577 99/256.
n = 13. Average = 767 2793/4096.
n = 14. Average = 997 3931/4096.
n = 15. Average = 1272 3711/16384.
n = 16. Average = 1594 3985/8192.
n = 17. Average = 1968 48645/65536.
n = 18. Average = 2398 65249/65536.
n = 19. Average = 2889 64891/262144.
n = 20. Average = 3443 16339/32768.
n = 30. Average = 13385 268434611/268435456.
n = 40. Average = 34128 68719475971/137438953472.
n = 50. Average = 69670 281474976708241/281474976710656.
n = 60. Average = 124013 36028797018963093/72057594037927936.
n = 70. Average = 201155 295147905179352821071/295147905179352825856.
n = 80. Average = 305098 75557863725914323416001/151115727451828646838272.
n = 90. Average = 439840 309485009821345068724773101/
309485009821345068724781056.
n = 100. Average = 609383 9903520314283042199192993177/
19807040628566084398385987584.
n = 1000. Average = 660694208
669692879491417075592765655662501131600878007315958504652343992731469406953085\
076558248986759809911329746670573470716765741965803557696277249036098418660925\
245910485926514436588817162816398196367372136384565404686473871329212422972447\
846496629816432160699779855408885478776864478289024177325353755091/
133938575898283415118553131132500226320175601463191700930468798546293881390617\
015311649797351961982265949334114694143353148393160711539255449807219683732185\
049182097185302887317763432563279639273474427276913080937294774265842484594489\
5692993259632864321399559710817770957553728956578048354650708508672.
n = 10000. Average = 666066942458
[fractional part removed]
```
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes
All the eigenvalues of the matrix are integers (could I have known or expected that?), and I found this formula for \$n\ge 2\$:
```
f(n)=(40+6*n-4*n^2)/2^n-83/2+331/12*n-6*n^2+2/3*n^3
```
[Try it online!](https://tio.run/##FYw5CsAgEAC/Iqm8FnXXSBrzFCGNwWYjkv8b08wUA9Ov0eDuc1bJKsvoTdIMUXNB5bAwHOTQEAUXcIX0B4OOlmnWZ0jO0e7e9tH4lSw2AefCf1Nqfg "Pari/GP – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Fibonacci function or sequence](/questions/85/fibonacci-function-or-sequence)
(334 answers)
Closed 6 years ago.
# Background
We all know the famous [Fibonacci sequence](https://oeis.org/A000045), where each term is the sum of the previous two, with the first term being `0` and the second one being `1`. The first few elements are:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765
```
What we are going to implement today is a similar sequence, starting at `0` and `1` as well, and each term is the sum of the previous two, but *the sum's digits* are shifted by one place to the right. **What does "shifted" mean?** – A digit shifted to the right is basically that digit + 1, unless it equals `9`, which maps to `0` instead. Just as a reference, here is the full list of mappings:
```
0 -> 1; 1 -> 2; 2 -> 3; 3 -> 4; 4 -> 5; 5 -> 6; 6 -> 7; 7 -> 8; 8 -> 9; 9 -> 0
```
---
With all that being said, these are the first terms of our Fibonacci-shifted sequence:
```
0, 1, 2, 4, 7, 22, 30, 63, 4, 78, 93, 282, 486, 879, 2476, 4466, 7053, 22620, 30784, 64515
```
Given an integer **N** (non-negative if 0-indexed and positive if 1-indexed), finds the **N**th term of the Fibonacci-shifted sequence.
# Rules
* The output may contain leading zero(es), in case `9` is the first (few) digit(s).
* Input and output can be handled using any **[default mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)**.
* Take note that **[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'"), hence your program will be scored in bytes, with *less* bytes being better.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ 72 bytes
```
f=lambda n:n>1and int(''.join(`-~int(i)%10`for i in`f(n-1)+f(n-2)`))or n
```
[Try it online!](https://tio.run/##FYpBCsMwDAS/okuJROsS@RhIPxICUknduiSyMbnk0q@7zmmZmc3H/knmaw3jqttzUbDBHqy2QLQdu@7@TdFQ3O/ESBfuJaQCsWUJaI7peo4nIWreai7tCbJpxnCDovZ@oe@JZOLB8Vz/ "Python 2 – Try It Online")
Saved 6 bytes thanks to Halvard Hummel.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ð+D‘%⁵Ḍø¡
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w7ArROKAmCXigbXhuIzDuMKh//81 "Jelly – Try It Online")
-2 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis).
Explanation:
```
ð+D‘%⁵Ḍø¡ Full program. Takes input through STDIN.
ð Start new dyadic chain
+ Add the left (f(n - 1)) and right (f(n - 2)) arguments
D Get list of decimal digits
‘ Increment each
%⁵ Modulo ⁵ (10)
Ḍ Convert from decimal to integer
ø Start new niladic chain
¡ Repeat previous chain z times (where z is taken from STDIN as there are no arguments)
```
[Answer]
# JavaScript (ES6), ~~63~~ 62 bytes
This is what I'd come up with before the challenge was deleted, don't have time to golf it further now.
Returns the `n`th number in the sequence, 0-indexed.
```
f=(n,x=0,y=1)=>n?f(--n,y,+[...x+y+""].map(z=>++z%10).join``):x
```
* 1 byte saved thanks to Conor.
[Try it online](https://tio.run/##LcxhCsIgGADQuwyCT3Ti@hm42DkqUpaGtn2KRugub0Ud4D2vXzrPycVnn6O7mbQGfJjampWArEjBqhyIHPFooe@RVUZPnPNCK@26C191hE2OlG67QRDug0OlyKG0OWAOi@FLuMMXTCnpCntBfgauzH9WC5781RkVaW8)
---
## Alternative, 55 bytes
A quick port of VoteToReopen's excellent Python solution.
```
f=n=>n>1?+[...f(--n)+f(--n)+""].map(x=>++x%10).join``:n
```
[Try it online](https://tio.run/##LcvRCsIgFADQfxkE92Jeth4Djb6jImVpaNtVNGL7eiPa03k60X5sHUvIb1lzeLgyJ365tTWvWGnWw0lciMiDlIxio@tuNNsMi9JCLLuhR4opsDFHbmPimiZHU3rCb55LsSscevwXuO8jKu0h4paubLB9AQ)
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
[`(-&2(10|>:)&.(10&#.inv)@+&$:<:)@.(1&<)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6zkE@bv@jEzR01Yw0DA1q7Kw01fSADDVlvcy8Mk0HbTUVKxsrTQegmJqN5n9NrpLU4hKQGanJGfkOGkDzQIapK@jaAYms/My84pKizLx0hVgFazUlK4U0iAYlA4VMPSOD/wA "J – Try It Online")
Highlighted following is the standard Fibonacci husk:
```
[`(-&2 +&$:<:)@.(1&<)
```
Then, we compose the following function with the result of adding the previous two terms:
```
(10|>:)&.(10&#.inv)@
```
This, in turn, is the function `10|>:` atop `10&#.inv`, which gets the digits of a number. That is to say, the digits are obtained, then the function `10|>:` is applied, then the digits are combined to make a number again. `10|>:` is a fork that is equivalent to `(y + 1) % 10` in a conventional language for input `y`.
] |
[Question]
[
You sell gold coins. Each gold coin you sell is supposed to be 1 ounce. However, you find out that one of your coin suppliers is cheating you. By alloying the gold material with something else, their coins weigh only 0.9 ounces. With a help of a **pointer** scale (one that shows the exact weight of a quantity of matter set on it), you want to determine which of your coin suppliers is selling you the counterfeit coins.
Apparently, you are not the only one to have this problem - lots of gold sellers buy coins from this supplier, and the supplier knows that it is being dodgy and is changing their branding accordingly. All of these sellers have the same problem - 1 ounce coins that end up being 0.9 ounces from this supplier - and need to solve it, fast! How can you determine, out of `n` suppliers, which one is the cheating supplier with the **minimum** number of weighings on the pointer scale?
---
Your task is to write a program function that can solve this problem automatically for `n` suppliers. It's **input** includes:
* an integer number of suppliers, `n`,
* an oracle function that represents weighing a set of coins on the balance scale
It must take this information, calling this function a minimum number of times and returning, as **output**, the index number of the cheating supplier.
The oracle function has the following specifications:
* It takes as input an `int->int` mapping (as an array or dictionary, whichever your language prefers) mapping each supplier index (from `0` to `n-1`) to a number of gold coins that you want to try weighing on the scale.
* The returned output is the total weight, in ounces, of the coins put on the scale.
* The function is in whatever format your language prefers for passing procedures as data. For instance, functional languages will pass lambdas, C will take a function pointer, Java 7 and earlier will take a functional interface. Languages that support none of these, but do support string execution, will take these as strings.
* In those cases when the oracle can be stringified or otherwise inspected as data, you may assume that it is sufficiently obfuscated such that you cannot tell which supplier is cheating without executing it.
This is also code-golf: among the solutions that call the function the minimum number of times, the smallest solution in bytes is the winner!
---
NOTE: If your language does not support functions at all, but does support string execution, write your program as a standalone program - assume that the number of suppliers, followed by the oracle, will be passed into standard input. If your language does not support string execution, assume that a file path to a binary oracle will be provided instead.
[Answer]
## Python, 33 bytes
```
lambda n,f:n*~-n*5-f(range(n))*10
```
Puts 0 coins from supplier 0, 1 coin from supplier 1, ... n-1 coins from supplier n-1. The deficit is then 0.1 for each coin sent to the cheating supplier, so `i/10`. We therefore subtract the oracle value from the fair sum `n*(n-1)/2` and multiply by 10. Distributing the `*10` saved on parens for a shorter expression.
[Answer]
# Python 2, ~~56 48~~ 44 bytes
**Uses 1 weighing**
-8 bytes thanks to @feersum (use `range(0,10*n,10)`)
```
def f(n,o):x=range(n);return(sum(x)-o(x))*10
```
Example runs at **[ideone](http://ideone.com/WemGmB)**
Places `i` coins from each of the suppliers `i` in `[0,n-1]` on the scale, subtracts the weighing from the total number of coins weighed and multiplies by 10.
(Python 3 will return float values that start to differ)
[Answer]
# Mathematica, 23 Byte
```
5#(#+1)-1-10#2@Range@#&
```
Same approach as xnor. In Mathematica `Range` starts with `1`, which is equivalent to using `n+1` coins from the `n`th supplier. Hence, the formula for the fair sum is `n(n+1)/2` and we have to subtract `1` from the result to restore zero-based indexing.
```
5#(#+1)-1-10#2@Range@#&[5,oracle]
```
>
> 149 - 10 oracle[{1, 2, 3, 4, 5}]
>
>
>
[Answer]
# Pyth, 9 bytes
```
-FsMlBm*T
```
As `o` cannot be used for the oracle in Pyth (it takes in a lambda itself), I instead defined the oracle as `l`. Any one-input function other than `s` should work as the oracle. Returns 0-indexed input.
Explanation (assuming the 3rd vendor is the faulty one):
```
m*T Map d*10 over all d in range(input): [0, 10, 20, 30] for input = 4
lB Bifurcate over the oracle function: [[0,10,20,30],58.0]
sM Map sum (for arrays, floors numbers): [60,58]
-F Fold over subtraction: 2
Implicitly print
```
[Try it online!](http://pyth.herokuapp.com/?code=DlGR-sG%2F%40G2T%3B%0A-FsMlBm%2aT&input=4&debug=0) (first line sets up the oracle function)
[Try changing the faulty vendor!](http://pyth.herokuapp.com/?code=DlGR-sG%2F%40GszT%3B%0A-FsMlBm%2aT&input=4%0A0&debug=0) (The faulty vendor is 0-indexed: from `0` to `first input - 1`. Any other value will cast the blame on the 0th vendor.)
] |
[Question]
[
I have this code :
```
tr ' ' '\n'|sort -n|head -1
```
The code is pretty simple, it takes a list of integer in the standard input stream (like `5 9 8 7 5 2 -12 -30`), it sort the integers and display only the first integer. But i need to ouput `0` if the given list is empty. And i can't find a short way to that. I have a solution with a ternary operator and a `echo 0`, but i feel i can do far better. I just need to replace the input stream by `0` if this stream is empty.
Sidenote : I don't need to call read to get the user input. The program is called with the input stream directly like `cmd < 1 5 6 -20 45`
Here my current code :
```
read l
[ -n "$l" ]&&echo $l|tr ' ' '\n'|sort -n|head -1||echo 0
```
[Answer]
# 34 bytes
```
a=($(tr \ \\n|sort -n))
echo $[a]
```
The first line saves the sorted input values in an array `a`.
This avoids using `head -1`, since referencing the array as `$a` will yield its first value.
The second line uses `a` in the [arithmetic expansion](http://www.tldp.org/LDP/abs/html/arithexp.html) `$[a]`. In this context, an empty string is interpreted as **0**.
For a different default value, [parameter substitution](http://www.tldp.org/LDP/abs/html/parameter-substitution.html) could be used instead. For example, the last line could become
```
echo ${a:-puppies}
```
[Answer]
## ~~37~~ ~~33~~ 32 bytes
```
tr \ \\n|sort -n|sed s/^$/0/\;q
```
Edit: Saved 4 bytes thanks to @DigitalTrauma.
[Answer]
## 42 bytes
Two different ways that have the same byte-count
Use `awk` as the last command
```
tr ' ' '\n'|sort -n|awk 'NR==1{print $1+0}'
```
Or do all the computations in `awk`
```
awk -v RS=" " '{m=m>$1?m:$1}END{print m+0}'
```
[Answer]
# Pure [bash](/questions/tagged/bash "show questions tagged 'bash'"): 41 bytes.
No requirement of any `tr`, `sort`, `head`...
```
t=${1:-0};for i;{ ((t=i<t?i:t));};echo $t
```
In a function you could use `local -i` for integer variables:
```
f() { local -i t=$1;for i;{ ((t=i<t?i:t));};echo $t;}
```
Then
```
f 5 9 8 7 5 2 -12 -30
-30
f
0
```
### Note: If you **need** to read them from stdin
```
read l
f $l
```
will do the job.
As:
```
read l;for i in ${l:-0};{ ((t=i<t?i:t));};echo $t;}
```
## Another version 58 bytes.
Something longer, but could be quicker, as there is no loop.
```
. <(printf v[%d+99**9]=\ $@);v=(${!v[@]});echo $[v-99**9]
```
In a function:
```
f() { local v;. <(printf v[%d+99**9]=\ $@)
v=(${!v[@]});echo $[v-99**9];}
```
Then
```
f 34 56 1000 12 -156 53 -12 -21 321 3221
-156
f
0
```
] |
[Question]
[
The [Walsh matrix](http://en.wikipedia.org/wiki/Walsh_matrix) is an interesting fractal matrix with the property that every single value in a Walsh matrix has a value of either -1 or 1. Additionally, the size of a Walsh matrix is always a power of 2.
Because each Walsh matrix is identical to the top-left quarter of the immediately higher-order Walsh matrix, we can create a generalized "infinite Walsh matrix" by considering the limit of the sequence of Walsh matrices of order N, as N goes to infinity. From here on, we will call this infinite generalization *the Walsh matrix*.
Your task is to build a program that takes the coordinates of a location in the Walsh matrix and returns the value that occurs there.
Your program will accept two integers `x` and `y` as input (in any form you choose), and output the value that appears in the `x+1`th row of the `y+1`th column of the Walsh matrix. For example, the input
```
2 5
```
will return `1`, as the 3rd row in the 6th column of the Walsh matrix has a value of 1. The input
```
6 4
```
will return `-1`, as the 7th row in the 5th column of the Walsh matrix has a value of -1. The input
```
2834719 394802
```
will return `-1`, as the 2384720th row of the 394803rd column has a value of -1.
The shortest code to do this in any language wins.
[Answer]
## GolfScript (18 15 14 bytes)
```
~&2base-1\0-,?
```
Takes input space-separated; outputs to stdout. Thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for pointing out that the space in the 15-char solution was removable.
The way I reasoned to this solution is quite simple. Take the highest set bit of `x|y`: this tells you the size of the smallest Walsh matrix which contains the relevant index. Then clearing that bit in both `x` and `y` drops us down to the top-left quadrant, and we need to multiply by `-1` if we were previously in the bottom-right quadrant: i.e. if the bit was set in both `x` and `y`. By induction down the bit sequence, we just need to count the number of bits set in `x&y`.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 44 bytes
```
: f and 1e 63 for s>d 2* 1+ s>f f* 2* next ;
```
[Try it online!](https://tio.run/##lVDLbsIwELz7K@bCxVGo1wmQEClf0guVY@BAUiWW2r8P9joqgSIetuTHeGZ3xrbr3SHd27CNW1jsWgOF4Wf3jXUGj/ub0RKnBG3z65BA49QZeIgiLUUlXlGm1MDUFlbKmYKuFBofoXjadw6q5iYJZKRwkZlwicB6ZnLuzhu4oh8tm7IS7tC0tw3ezxJQddNjCKxJ9Sj5UBvOM4X1yilJNf63H8jxb7i8/KNX44KIFM/L4jexIL75QZcXRb60XeITJb6ObhDP1eqeuohqobFiSKyRx4MusnxDJbIyL5RmbDwD "Forth (gforth) – Try It Online")
The function takes two word-sized unsigned integers (64 bits on TIO). It returns -1 or 1 on the floating-point stack and leaves a garbage 0 on the main stack.
The algorithm follows [Blckknght's submission](https://codegolf.stackexchange.com/a/20953/78410), but the task made me explore LOTS of possibilities for writing Forth programs - from bit shift, divmod, single-to-double conversion to abusing floating-point stack. (The TIO link has several alternative definitions of `f` which all work, but are longer than the main answer.)
### How it works
```
: f ( u1 u2 -- -1e_or_1e ) \ Takes two integers and returns a float 1 or -1
and 1e \ Bitwise and(=N), then put a 1(=R) on the FP stack
63 for \ Repeat 64 times... (TIO gforth has 64-bit cells)
s>d \ Sign-extend single N to double
\ In effect, 0 is pushed if MSB is zero, -1 otherwise
2* 1+ s>f f* \ Change 0_or_-1 to 1_or_-1, cast to float and multiply with R
2* \ Shift N left once
next \ End loop
; \ End function
```
[Answer]
# Python 2 - 42 bytes
```
print(-1)**bin(input()&input()).count("1")
```
This takes the two coordinates as separate lines on standard input and writes the answer to standard output.
The algorithm is this:
1. For coordinates `X` and `Y`, find `X & Y`, the bitwise AND of their values.
2. Count the number of 1 bits in `X & Y`. This is the number of times the requested coordinate is in the bottom right quadrant of a level of the matrix.
3. If the count is odd, the result is -1. If the count is even, the result is 1.
This should work for any positive integer coordinates (including large ones that need more than 32 bits).
[Answer]
# x86\_64 machine language for Linux, 17 bytes
```
0x00: 48 21 F7 and rdi, rsi
0x03: F3 48 0F B8 C7 popcnt rax, rdi
0x08: FF C0 inc eax
0x0a: 24 01 and al, 1
0x0c: 01 C0 add eax, eax
0x0e: FF C8 dec eax
0x10: C3 ret
```
Same algorithm as @Blckknght's answer.
[Try it online!](https://tio.run/##bYrRCsIgGIXvewwh0HDgr9Ycozfxxv7mGDWJtgspevVM260Xh3POx4fNiJgSPXhG2ZnYqI2NEmz0bY7avvA2XnJjYXmjyI7OHLaU/@fFUaRPs5sCZe/d4zmF1VOyv9pAuKeCC8b6CoYahroNdVvyYw2fuK7aRukWOq46bYQsxid90d/duKTmNcQBl9Xh7Qc "C (gcc) – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~18~~ 16 bytes
-2 bytes by converting to tacit form
```
-:/[;1]@+/&/+2\,
```
[Try it online!](https://tio.run/##FcYxCoAgFADQ3VOYRQ5m5tfKdOkeJjTZEPw5iM5uNb13SjywlOylVzHotArVKgFbV3KEMCaS4xTsDzhjZ70Es1g3QCI7HTyjTPFbQv2lux7OG6wz7bmo0Dvqygs "K (ngn/k) – Try It Online")
Based off of [@Blckknght's Python 2 answer](https://codegolf.stackexchange.com/a/20953/98547).
* `&/+2\,` take the (equivalent of) the bitwise-and of x and y
* `+/` do a popcnt (i.e. number of bits set to 1)
* `-:/[;1]@` negate `1` that many times and return
] |
[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/869/edit).
Closed 7 years ago.
[Improve this question](/posts/869/edit)
Write a function f(a,b,c) that calculates a^b (mod c) in less than 10 seconds.
* a, b < 10^100
* c < 10000.
examples:
```
f(10^50, 10^50, 54123) = 46555
f(5^99, 10^99, 777) = 1
```
[Answer]
## dc 1 or 5 chars
In GNU dc, there is the operator `|`, doing exactly this. Quoted from the manual:
>
> **`|`** Pops three values and computes a modular exponentiation. The first value popped is used as the reduction modulus; this value must be a non-zero number, and should be an integer. The second popped is used as the exponent; this value must be a non-negative number, and any fractional part of this exponent will be ignored. The third value popped is the base which gets exponentiated, which should be an integer. For small integers this is like the sequence Sm^Lm%, but, unlike ^, this command will work with arbitrarily large exponents.
>
>
>
You may assign it to "function" as following:
```
[|]sf
```
(also 5 chars...) This assigns `|` to `f`. You may call it like `lfx`.
[Answer]
# Python - 5 chars
```
f=pow
```
Test
```
>>> f(10**50, 10**50, 54123)
46555L
>>> f(5**99, 10**99, 777)
1L
```
[Answer]
## Haskell, 65
Takes the liberty of taking the modulus only on set bits of binary `b`, but given the range constraints that won't be a problem.
```
f a b c|b==0=1|odd b=mod(a*f a(b-1)c)c|0<1=f(mod(a^2)c)(div b 2)c
```
[Answer]
## Java 56 chars
My humble attempt with Java.
```
Object a(BigInteger...a){return a[0].modPow(a[1],a[2]);}
```
How to use :
```
a(new BigInteger("95"), new BigInteger("56"), new BigInteger("67"));
```
[Answer]
## Haskell (54)
```
f a=g a a
g d a b c|b>0=g(mod(d*a)c)a(b-1)c|True=mod d c
```
This is my algorithm:
1. let d = a
2. while b > 0:
* d <- (d\*a)%c
* b --
3. Return d%b
[Answer]
# Ruby, 15 bytes
```
->a,b,c{a**b%c}
```
Finishes in 0.114s for a=10, b=100, c=10000
[Answer]
Python 80 Characters
```
def f(a,b,c):
x=1;y=a
while b:
if b%2:x=(x*y)%c
y=(y*y)%c;b/=2
return x%c
```
[Answer]
# PHP, 8 bytes
```
bcpowmod
```
You can assign the function name to a variable for 11 bytes:
```
$f=bcpowmod;
```
**Note:** `bcpowmod` requires libbcmath, which is built into PHP since version 4.0.4, but only enabled by default on Windows. On Linux you have to explicitly configure PHP with `--enable-bcmath`.
] |
[Question]
[
Write a program that takes a United States aircraft registration number and returns a 24-bit ICAO hex code corresponding to that registration and vice-versa.
An aircraft registration number always begins with an N and is followed by 1 to 5 characters: 1 to 5 digits and then 0 to 2 uppercase letters. That is, one of the following three patterns:
* N plus 1 to 5 digits
* N plus 1 to 4 digits then one letter
* N plus 1 to 3 digits then two letters
The first digit cannot be 0 and the letters I and O are not used. The letters always follow the digits.
ICAO hex codes assigned to the US are numbers from A00001 to ADF7C7 (in hexadecimal). They are assigned in alphanumeric order (with letters before digits): A00001 corresponds to N1, A00002 corresponds to N1A, A00003 to N1AA, A00004 to N1AB, etc., up to ADF7C7 for N99999. That is, sorted in lexicographic order where A < B < C < D < ... < Y < Z < 0 < 1 < ... < 9.
Here is the order of some codes to help alleviate confusion: N1, N1A, N1AA, N1AB, N1AC, ... , N1AZ, N1B, N1BA, N1BB, ..., N1BZ, N1C, ..., N1Z, N1ZA, N1ZB, ..., N1ZZ, N10.
Alternatively, here's some poorly-written python code that generates the next registration number in order given one as input:
```
import re
valid=re.compile('N([1-9][0-9]?[0-9]?[A-Z]?[A-Z]?|[1-9][0-9]?[0-9]?[0-9]?[A-Z]?|[1-9][0-9]?[0-9]?[0-9]?[0-9]?)$')
ordering='ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
def next_reg(reg,first=True):
if first and valid.match(reg+'A') is not None:
return reg+'A'
last_char=reg[-1]
if(last_char=='9'):
return next_reg(reg[:-1],False)
index=ordering.index(reg[-1])
retval=reg[:-1]+ordering[index+1]
if valid.match(retval) is None:
return next_reg(reg[:-1],False)
return retval
```
Some test cases:
| Registration | ICAO code (hex) | ICAO code (decimal) |
| --- | --- | --- |
| N17CA | A11707 | 10557191 |
| N1PP | A00155 | 10486101 |
| N959ZP | AD5863 | 11360355 |
| N999ZZ | ADF669 | 11400809 |
| N1000B | A0070E | 10487566 |
You can assume no invalid inputs will be given.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 137 bytes
```
f=(x,s=(i=10384024,'N'))=>g=/\D{3}|.{7}|.\D\d/.test(s)?0:++i&&s==x?i:i^x?[...'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'].some(t=>f(x,s+t))&&g:s
```
[Try it online!](https://tio.run/##bc5dT4MwFIDhe38ItGHrTtcWKElH5vAjOgl@K6LJsgHBzGFsY0imvx23W9ebc/E@OTnnffG90Muv5tMMN@2q7PtKoW6gFWoUBRZyGPOBm7oYq0mtRkWyZb8/ZBvsRpEUqxExpTZI4xgiz2scRyvVxU3UvHXxCyHEnR7PkpPTs/OLy/lVml3f3N7dPzw@PedAx4wLPwil@0p0@1EioybV/rJnMHacOtL9st3odl2SdVujCrkp3X1xdBCD2dTas8yWpZC5HaTM8z38Ewo8FIFPD1YoCBFQaQMe@hQsQJkPTAgLcIAQJMb9Hw "JavaScript (Node.js) – Try It Online")
Pass all tests
Output `0x9e7299 - 0x9fffff` for invalid input `N[A-Z]?|N0.*`, and `false` other invalid。 Double-way map
[Answer]
# [Perl 5](https://www.perl.org/), 136 bytes
```
sub{map{//;map$n{$n{$x="N$'$_"}//=sprintf"A%05X",$i+=!/I|O/}=$x,sort(("",A..Z,AA..ZZ)[0..26*($_<1e3?27:$_<1e4)])}sort 1..99999;$n{+pop}}
```
[Try it online!](https://tio.run/##bZNdb5swFIbv8ys85nawMvABzOfQ5jWptItludjFRFVFXetEkRZgQLRMKb89MxiiOJuFsOXnPec9NoeSVz/pEa/SY737cdg@lgfbTsSE80P37FNtjt/gpdbadlqX1SZvVhq7IvS7ZuLNTfrK/vzy1W5TvDfromp0XdNMZlmZybp3ZtwTy3L8tzpevgfufnCCuF95xoPRdgEILCvqRiLcbsqibNtjMtnVHH3jdRPHX4qKJ5NVUekTJMb9r9/6HIJbhhADCEiAgFAaQATGg3mmWCzEkhEClAqFF/pAVEVEo2yB2JSGvosAXJ@4lKqKKMoyobjz/UgoPEJCEnWK1ycXgqSLQ9kF6AsUIJypACRwGJmqIJRHcmehf5GKSA/vk6sARwKIHOIowJXAhTsKaoS8FAhnzFM90HAOQi4iJIBwSokK2AlcRDA2ArWq/ht3txncBh0wDv1Nb//ouOLrfLcV3fT0WBjpR7xMBoTwumhYeo1Xo8hQ0FyiPk6CTa33MTKZidDYsXxf8qeGP6NuPxbKq3d@LSYhjse1aDIkbeSWNmQZMioVDEbzcdv8x@g803@MzuvQTlmGnMOJ2slzkfNlI36ETb5Ojn8B "Perl 5 – Try It Online")
Generates a list of all 915399 possible N-codes and stores it in hash %n which is also mirrored to convert the other way.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 122 bytes
*-8 thanks to @l4m2*
This is (now even more) similar to [l4m2's answer](https://codegolf.stackexchange.com/a/269266/58563).
```
x=>(n=0x9e7298,g=(s,h=k=>k>52?0:g(s+Buffer([48+k%43]))||h(k+1))=>/I|O|\D{3}|.{7}|.\D\d/.test(s)?0:x^++n?x==s?n:h(17):s)`N`
```
[Try it online!](https://tio.run/##hc5Ba8IwFAfw@z6FCIMX4tpE7aKFtDi97OIKw5PdsGjaukpSmmwEzD57V7vbZPgODx78f3/eR/aV6X1zrM2DVAfR5ry1PALJiZ0LNp7PRgUHPSp5xaMqCsYxCQvQ@Okzz0UD2@kMV/fTyRtCzpVQYYoQj/xn9@LS1Xny7bwz61a6Sg@@Z4Q2oFHXYN8xlrHlXMcyLIEyFGq0W@/avZJanYR3UgXkMFxTtlwMkWfUq2mOsgD6eDk2dS2aZaYFIDTw/cGCUkbY3RVOkhu2x4TQIPiDif3tvGT@nQ73D17bvvK2TZL2Bw "JavaScript (Node.js) – Try It Online")
### Commented
```
x => ( // x = input
n = 0x9e7298, // n = ICAO counter
g = ( // g = helper function taking:
s, // s = current registration number string
h = k => // h = helper function taking a counter k
k > 52 ? // if k is greater than 52:
0 // stop
: // else:
g( // do a recursive call to g
s + // where s is completed with either
Buffer([ // an upper case letter A-Z (65-90)
48 + k % 43 // or a digit 0-9 (48-57)
]) //
) || // end of recursive call
h(k + 1) // if it failed, try h(k + 1)
) => //
/I|O|\D{3}|.{7}|.\D\d/ // if s contains a 'I' or a 'O', or has 3
.test(s) ? // consecutive letters, or is 7 char. long,
// or contains a digit after a letter (other
// than the leading 'N'):
0 // invalid registration number -> abort
: // else:
x ^ ++n ? // increment n; if x is not equal to n:
x == s ? // if x is equal to s:
n // return n
: // else:
h(17) // invoke h, starting with k = 17 for 'A'
: // else:
s // return s
)`N` // initial call to g with s = 'N'
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 173 bytes
```
"G`$&\b¶$&|;¶"^~(`.+
99999*
L$`_
N$.>`
O`
2+%(`$
;26*
Y`\_`L
I|O
)L$`(;|(\w))(?<=(\w+);.*)
$3$2
A`.{7}
D^`
G`.
.+
$&;A,$>:&*
5+`;A,(_{16})*(_*)
;A,$#1*_,$.2
T`d`L`,1\d
,B?
```
No TIO link, since it needs about 9 hours to run. Explanation:
```
"G`$&\b¶$&|;¶"^~(`
```
Evaluate the rest of the program below, then select only the line containing the input word and delete the word and separator from that line, thus giving the matching code.
```
.+
99999*
L$`_
N$.>`
O`
```
Generate the numbers from `1` to `99999` in lexicographical order.
```
2+%(`
)`
```
Repeat twice for each line.
```
$
;26*
Y`\_`L
I|O
L$`(;|(\w))(?<=(\w+);.*)
$3$2
```
Append each letter except `I` and `O`.
```
A`.{7}
D^`
G`.
```
Remove illegal and duplicate entries.
```
.+
$&;A,$>:&*
```
Number the lines with an `A` prefix.
```
5+`;A,(_{16})*(_*)
;A,$#1*_,$.2
T`d`L`,1\d
,B?
```
Convert the numbers to five hexadecimal digits.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~51~~ 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5°<L§{A„ioмuÐ⪘{õšδ«˜'Nìʒg7‹}ā•¢β¡•+hø.ΔQà}IK
```
The output is wrapped in a list. This can be fixed at the cost of 1 trailing byte.
[Try it online.](https://tio.run/##AVsApP9vc2FiaWX//zXCsDxMwqd7QeKAnmlv0Lx1w5DDosKqy5x7w7XFoc60wqvLnCdOw6zKkmc34oC5fcSB4oCiwqLOssKh4oCiK2jDuC7OlFHDoH1JS///TjEwMDBC) (Very slow for values far into the sequence.)
[The first portion of the program generates all pairs.](https://tio.run/##AUwAs/9vc2FiaWX//zXCsDxMwqd7QeKAnmlv0Lx1w5DDosKqy5x7w7XFoc60wqvLnCdOw6zKkmc34oC5fcSB4oCiwqLOssKh4oCiK2jDuP//)
**Explanation:**
```
5° # Push 10**5: 100000
< # Decrease it by 1: 99999
L # Pop and push a list in the range [1,99999]
§ # Cast each integer to a string
{ # Sort these strings lexographically
A # Push the lowercase alphabet
„ioм # Remove the "i" and "o"
u # Uppercase the remaining letters
Ð # Triplicate it
â # Pop two, and create all pairs using the cartesian product
ª # Convert the remaining string to a list of characters,
# and append this list of pairs
˜ # Flatten it to a single list
{ # Sort these strings lexographically as well
õš # Prepend an additional empty string
δ # Apply double-vectorized on the two lists:
« # Append two strings together
˜ # Flatten it
'Nì '# Prepend an "N" before each
ʒ } # Filter it, keeping those where:
g # Their length
7‹ # is smaller than 7
# (to filter out invalid values like "N10000ZZ")
ā # Push a list in the range [1,length] (without popping)
•¢β¡•+ # Add compressed integer 10485760 to each ("A00000" in hexadecimal)
h # Then convert each integer to a hexadecimal string
ø # Pair the values in the two lists together
.Δ # Pop and find the first/only pair that's truthy for:
à # Check if either of the two
Q # equals the (implicit) input-string
}IK # After we've found our matching pair: remove the input from it
# (after which the intended wrapped 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 `•¢β¡•` is `10485760`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~151~~ ~~147~~ 121 bytes
```
≔I⪪”)¶&*δ§L¶∧≧T∨›P”2η≔⪪⁻⁺⁻αI⭆χιO¹υ⊞υω¿›NθNPθF∨¬ⅈ⁵«≔Eυ↥⍘⁺↨EΦ⁺⪫KAωκν⊕⎇⁼ν⁴⌕υμ⎇№αμ×∨№α§KAν²⁵⌕υμ⁺⁶⁰⁰×Iμ§ην¹⌈η¹⁶ζ⎇ⅈ§⮌υ⊕ΣEζ›κθ⊟ζ
```
[Try it online!](https://tio.run/##XVJNb8IwDD3Dr4h6cqVOokAZiBNjY2ISUI1N4hpBoBFpWvLBGNN@O3NSOrFVsms79vOLnXVG1bqg4nIZac13EsZUG1iWghsI4lZ8H8dt/KEeJHG7k6DT6Xe63UEQkaAdhGFEsnDYvBZXdTMurYZUoKpMirnTAFOXRnG5m9ES4lZEuKsOFu4gRrGIk1qdgY3IB9p8S@BZMWqYgmCO/Q5hSFIEMM4Nh4QJzcjMCsNLHz1g0bZQBBYK5oWBFbgGCVZ9NRtXhq434r@XJVNrqhk8oKpoVYyd77MmXLjOPvhScAkpY/uREBA6ehHZo0iUqVwrljNp2AbemJJUfcLTwVKhQUakixkTLjeuaY52nTEuLDKm1yDPmXasf6MjM5UbdrrtKd1l2skfPHQ8v16rVaP4/TnQGiLzpf6r5jyjJ57bHDIf6Pn4GUfXqGZbM1zBDcgrOzKFg7H/LrxEHDesc0TqVe39ojxqWuAJWsPmN76vx6Tf61zujuIH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Long because it doesn't use brute force, as that would probably take too long to verify correct program operation, so I've actually computed the result somewhat directly. Explanation:
```
≔I⪪”)¶&*δ§L¶∧≧T∨›P”2η
```
Get some compressed magic numbers.
```
≔⪪⁻⁺⁻αI⭆χιO¹υ⊞υω
```
Get the string `ABCDEFGHJKLMNPQRSTUVWXYZ0123456789`, split it into characters, and append the empty string.
```
¿›NθNPθ
```
If this is a US registration, then print it without moving the cursor, otherwise print an `N`. Note that this means that the x-coordinate is now zero only for a US registration.
```
F∨¬ⅈ⁵«
```
Loop once for a US registration, otherwise `5` times.
```
≔Eυ↥⍘⁺↨EΦ⁺⪫KAωκν⊕⎇⁼ν⁴⌕υμ⎇№αμ×∨№α§KAν²⁵⌕υμ⁺⁶⁰⁰×Iμ§ην¹⌈η¹⁶ζ
```
Suffix each letter and digit to the partial US registration and see what the resulting ICAO codes are, plus also calculate the ICAO code for the US registration.
```
⎇ⅈ§⮌υ⊕ΣEζ›κθ⊟ζ
```
For a US registration, overprint it with the ICAO code, but for an ICAO code, append any best letter or digit.
The values of the characters of a US registration are calculated as follows:
* The first digit is worth `101711` times its value plus `601`
* The second digit is worth `10111` times its value plus `601`
* The third digit is worth `951` times its value plus `601`
* The fourth digit is worth `35` times its value plus `601`
* The first letter is worth `25` times its position in the alphanumeric string plus `1` unless it's the fifth character
* The fifth character is worth its position in the alphanumeric string plus `1`
(In reality `600` is used instead of `601` and then `1` is added later for each digit.)
] |
[Question]
[
# Input
Two non-negative floating point numbers \$x < y\$. You can assume they are close enough to each other that there is no integer between \$x\$ and \$y\$.
# Output
A fraction with the smallest possible denomination that lies strictly between \$x\$ and \$y\$.
# Examples
Input: 1 and 2
Output: 3/2
Input: 0 and 0.33
Output: 1/4
Input: 0.4035 and 0.4036
Output: 23/57
[Answer]
# JavaScript (ES6), 47 bytes
Expects `(x)(y)`, returns `[numerator, denominator]`.
```
(x,p=q=1)=>g=y=>p<y*q++&&p++>x*--q?[--p,q]:g(y)
```
[Try it online!](https://tio.run/##ZcixDoIwEADQ3Q8hd5RrilUHw9UPMQ4EodEQegVj6NfXwYkwveS922@7dPNLPjSFZ58HzrBWwpFrZOc5sZMmlVGpohCl3FoSxdudSKr4uHpImLswLWHs9Rg8DFAjHBEP2zQIRlu7f30y9ox/L4j5Bw "JavaScript (Node.js) – Try It Online")
### Commented
```
( x, // x = first number
p = // p = numerator
q = 1 // q = denominator
) => //
g = y => // y = second number
p < y * q++ // we test whether p/q < y
// and increment q afterwards in case it's not
&& // if truthy,
p++ > x * --q // we restore q, test whether p/q > x
// and increment p afterwards in case it's not
? // if truthy again:
[--p, q] // we restore p and return [p, q]
: // else:
g(y) // we try again with either p or q incremented
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
NθNη≔⌕E⁺²∕¹⁻ηθ⁻⌈×ηι⌊×θι²ζI⟦⊖⌈×ηζζ
```
[Try it online!](https://tio.run/##ZY0xC4MwEIV3f4XjBaxYp4JTUYQOFodupUOqhx7EU5Po4J9PU2mh0OGG73u8d00vdTNK5dyFp8Vel@GJGmaRBb/cez4bQx1DSdxCJSeo1WIgjcKCVmoRjlFYEXvVR@EshPhijqSIO7jRgHtI76xU46g/bt6dl6m/zX@qNbGFXBoL9wIbjQOyxfZ/attr20OIzLkkToMkPrnDql4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `x` and `y`.
```
≔⌕E⁺²∕¹⁻ηθ⁻⌈×ηι⌊×θι²ζ
```
Find `d` such that `⌈yd⌉-⌊xd⌋=2`. `d` is never more than `⌊1+1/(y-x)⌋`, but I have to add `2` due to 0-indexing.
```
I⟦⊖⌈×ηζζ
```
Output `⌈yd⌉-1` and `d`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 42 bytes
```
x=>g=(y,d)=>(p=-~(x*d))<y*d?[p,d]:g(y,-~d)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1i7dVqNSJ0XT1k6jwFa3TqNCK0VT06ZSK8U@ukAnJdYqHSirW5ei@T85P684PydVLyc/XSNNw1BTw0hTkwtV0EBTw0DP2BhTXM/EwNhUE0KbaWr@BwA "JavaScript (Node.js) – Try It Online")
If \$ \left \lfloor xd \right \rfloor +1 < yd \$, then \$ \left \lfloor xd \right \rfloor +1 \$ is an answer
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
×ḞĊƭ€r/ḊṖ
1ç1#Ḣṭç¥
```
[Try it online!](https://tio.run/##y0rNyan8///w9Ic75h3pOrb2UdOaIv2HO7oe7pzGZXh4uaHywx2LHu5ce3j5oaX/dQ63P9y5D6gi61HDHAVdO4VHDXO5DrcDBSL//4/mijbUMYrV4Yo20DHQMzYGs/RMDIxNdcCUWSxXLAA "Jelly – Try It Online")
A pair of links which is called as a monad with a pair of floats and returns a pair of `[numerator, denominator]`.
## Explanation
```
×ḞĊƭ€r/ḊṖ | Helper link: takes a denominator as the left argument and a pair of floats as the right and returns a valid numerator, if any
× | Multiply (denominator with floats)
ḞĊƭ€ | Floor first, ceiling second
r/ | Reduce using range
ḊṖ | Remove first and last
1ç1#Ḣṭç¥ | Main link
1ç1# | Starting with one, find first denominator where there’s a valid numerator (will be wrapped in a list)
Ḣ | Head (to unwrap the list)
ṭç¥ | Tag this onto the result of running the helper link again to find the numerator
```
```
[Answer]
# [Python 2](https://docs.python.org/2/), 95 bytes
```
(a,b),(c,d)=[input().as_integer_ratio()for m in 0,0]
while(m*d/c+1)*a>=m*b:m+=1
print m,m*d/c+1
```
[Try it online!](https://tio.run/##LctBDsIgEADAO6/gyNINbu3NBD9iTENbtJu4QBBjfD168DyZ8ml7TsfeTcAF0Ky4gb9wKq9mwIXnzKnFe6xzDY2zgVuuWjQnTUhX9d75EY3Y7bAOI9hw9mKXkwx@VKX@phb8Y@/kSJGbJvUF "Python 2 – Try It Online")
Not a math guy, basically uses the formula of [this answer](https://math.stackexchange.com/a/2494861/596406).
The input should be in decimal format: `1.0` instead of just `1`.
*-2* bytes: replace `//` with `/`
*-4* bytes: inlining `m`
[Answer]
# [R](https://www.r-project.org), 47 bytes
```
\(x,y){while((p=(x*F)%/%1+1)>=y*F)F=F+1
c(p,F)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY39WM0KnQqNavLMzJzUjU0Cmw1KrTcNFX1VQ21DTXtbCuBHDdbN21DrmSNAh03zVqoNsU0DUMdI02uNA0DHQM9Y2MwS8_EwNhUB0yZaUIULlgAoQE)
Port of [@l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/269186/55372).
] |
[Question]
[
Consider an \$n \times n\$ grid and a circle of radius \$r \leq \sqrt{2} n\$ with its center in the top left. In each square there is an integer from the range -3 to 3, inclusive. For a given radius, there is a set of squares in the grid which are not at least half covered by a circle of radius \$r\$ but are at least half covered by a circle of larger radius. Your task to output the sum of the integers in those squares.
Takes this example:
[](https://i.stack.imgur.com/xTQWT.png)
The smaller circle has radius \$3.5 \cdot \sqrt{2}\$ and the larger circle has radius \$4.5 \cdot \sqrt{2}\$. The numbers for squares that are at least half covered by the larger circle but not the smaller one are \$1, -1, 3, 3, 2, -1, -1, 1, -3, -1, 1\$. These sum to \$4\$.
You might be wondering why the \$-1\$ number in square (4,4) is not included.
If we zoom in we can see why. The blue dots are the center of the squares.
[](https://i.stack.imgur.com/V5wY2.png)
If we had chosen the smaller radius to be \$2.5 \cdot \sqrt{2}\$ and the larger circle has radius \$3.5 \cdot \sqrt{2}\$ then we get the sum of the values we need is \$-1\$.
[](https://i.stack.imgur.com/nApAs.png)
Here is the matrix from the examples given:
```
[[ 3, 0, 1, 3, -1, 1, 1, 3, -2, -1],
[ 3, -1, -1, 1, 0, -1, 2, 1, -2, 0],
[ 2, 2, -2, 0, 1, -3, 0, -2, 2, 1],
[ 0, -3, -3, -1, -1, 3, -2, 0, 0, 3],
[ 2, 2, 3, 2, -1, 0, 3, 0, -3, -1],
[ 1, -1, 3, 1, -3, 3, -2, 0, -3, 0],
[ 2, -2, -2, -3, -2, 1, -2, 0, 0, 3],
[ 0, 3, 0, 1, 3, -1, 2, -3, 0, -2],
[ 0, -2, 2, 2, 2, -2, 0, 2, 1, 3],
[-2, -2, 0, -2, -2, 2, 0, 2, 3, 3]]
```
# Input
A 10 by 10 matrix of integers in the range -3 to 3, inclusive and a radius \$r=\sqrt{2} (a+1/2)\$ where \$a\$ is a non negative integer. The radius input will be the integer \$a\$.
# Output
The sum of the numbers in the squares in the matrix which are not at least half covered by a circle of radius \$r\$ but are at least half covered by a circle of radius \$r + \sqrt{2}\$.
These are the outputs for some different values of \$a\$ using the example matrix.
```
a = 0 gives output 6 ( 0 + 3 + 3)
a = 1 gives output 3 (1 + -1 + -1 + 2 + 2)
a = 2 gives output -1 (3 + -1 + 1 + 0 + -2 + -3 + -3 + +0 + 2 + 2)
a = 3 gives output 4 (1 + -1 + -3 + 1 + -1 + -1 + 2 + 3 + 3 + -1 + 1)
```
# Accuracy
Your answer should be exactly correct. The question of which squares to include can be resolved exactly mathematically.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ŒJ_.²§<Ɱ+.+Ø.²ḤƲ}^/ḋF{
```
[Try it online!](https://tio.run/#%23y0rNyan8///oJK94vUObDi23ebRxnbae9uEZQN7DHUuObaqN03@4o9ut@v@jxp3WjxrmKOjaKTxqmKtifXg51@HlQNVHd9dG/v8fHa1grKOgYADEhkAMZOsaQtkwvhFILFaHS0FBIRqmAK7IAMo2gvBBihUMYIqNIBIQQagCqG26RjBNMMUGEEldZBuMkTSDsDGayWC3G0EVG0D5MIPgJiOZBncCkskQJyGZrAvDMEWGuJyBZCVK8BkhexTZgzB3o4eMEcwAqGJdJEk4G1kx2A@xsf8tAQ "Jelly – Try It Online")
A dyadic link taking a 10x10 integer matrix as its first argument and an integer as its second argument and returning an integer. Doesn’t use any fractions other than halves and quarters so should not lose anything to floating point accuracy.
Uses the same methodology as [@Ajax1234’s Python answer](https://codegolf.stackexchange.com/a/268577/42248) so be sure to upvote that one too!
## Explanation
```
ŒJ_.²§<Ɱ+.+Ø.²ḤƲ}^/ḋF{
ŒJ # Indices along matrix
_. # Subtract 0.5
² # Square
§ # Sum inner lists
<Ɱ Ʋ} # Less than each of the following applied to the right argument as a monad:
+. # Add 0.5
+Ø. # Add zero and one
² # Square
Ḥ # Double
^/ # Reduce using xor
ḋF{ # Dot product with the flattened matrix
💎
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
## Alternative approach [Jelly](https://github.com/DennisMitchell/jelly), ~~47~~ 45 bytes
```
+1.,.²Ḥµæ._²}½÷@ÆṬ,×ʋʋ¥Ɱ⁵ŻHI+.ḞḞRŒṪfU$)ḟ/œị⁹S
```
[Try it online!](https://tio.run/##y0rNyan8/1/bUE9H79CmhzuWHNp6eJle/KFNtYf2Ht7ucLjt4c41Ooenn@o@1X1o6aON6x41bj2628NTW@/hjnlAFHR00sOdq9JCVTQf7pivf3Tyw93djxp3Bv8/uvvw8kdNa/7/t/yvoBAdrWCso6BgAMSGQAxk6xpC2TC@EUgsVodLAagapgCuyADKNoLwQYoVDGCKjSASEEGoAqhtukYwTTDFBhBJXWQbjJE0g7AxmslgtxtBFRtA@TCD4CYjmQZ3ApLJECchmawLwzBFhricgWQlSvAZIXsU2YMwd6OHjBHMAKhiXSRJOBtZMdgPsbEA "Jelly – Try It Online")
This is a dyadic link that takes the integer a as its first argument and the 10x10 matrix as its second and returns an integer. This uses the integral of the circle equation to calculate the area in each column. This is useful on the left hand part of the quarter circle but not on the right when it’s harder to calculate which squares are partially filled. My code therefore uses symmetry to control for this. There could be floating point error, but it’s not apparent in the example used here.
The formula used for the integral of \$\sqrt{r^2 - x^2}\$ is:
\$\frac{1}{2} (x \sqrt{r^2 - x^2} + r^2 \arctan{\frac{x}{\sqrt{r^2 - x^2}}})\$
This was generated using [Wolfram Alpha](http://www.wolframalpha.com/input/?i=%E2%88%AB%E2%88%9A%28r%5E2-x%5E2%29).
## Explanation
```
+1.,.²Ḥµæ._²}½÷@ÆṬ,×ʋʋ¥Ɱ⁵ŻHI+.ḞḞRŒṪfU$)ḟ/œị⁹S
+1.,. # Add [1.5, 0.5]
² # Squared
Ḥ # Doubled
µ ) # For each of these squared radii:
¥Ɱ⁵ # - Following as a dyad using the squared radius as the left argument and each integer from 1 to 10 inclusive as the right (referred to as x below)
æ. ʋ # - Dot product of [the squared radius, 1] with the result of the following:
_²} # - Subtract x squared from the squared radius
½ # - Square root
ʋ # - Following as a dyad using the above as the left argument (called z below) and x as the right argument
÷@ # - Divide x by z
ÆṬ # - Arctan
,× # - Paired with z multiplied by x
Ż # - Prepend zero
H # - Half
I # - Increments
+. # - Add 0.5
Ḟ # - Real part of complex values; floor real values
Ḟ # - Floor the real values generated from the complex values above
R # - Range from 1 to each of these
ŒṪ # - Two-dimensional indices of truthy values
fU$ # - Keep only those which also exist in their reversed form
ḟ/ # Remove the squares captured by the smaller circle from those captured by the larger one
œị⁹ # Multidimensional index into the matrix
S # Sum
💎
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# Python3, 105 bytes:
```
E=enumerate
f=lambda m,d:sum(v for x,r in E(m)for y,v in E(r)if(U:=x*x+x+y*y+y+1)>d*d*2 and U<(d+1)**2*2)
```
[Try it online!](https://tio.run/##dVDBboMwDD2Pr/AxCWGCsEkTGr31E3pCHJgCa6QlRSmt4OsZaWKUVdrBkp/9/PzscZnOF1N@jHZdj3Vvbrq33dQnQ/3T6S/Zgeayut40ucNwsTBzC8rAkWjq4MLvHlqqBnKq6pnN6ZwubEmXtKAHySQT0BkJp08itwpjggm6ulnlJm1nvnvyRqvkZbTKTGQgTQMlB8i3KLbY8qwIOWLhai1PAKBBwk7KQy48dmTIkSx8wxcDIWzLBA4hOffNLN5QRsMuyiflh3cRyHnAKLQrR2q7hUjZW4qUMwwkFf/ZiFb@eZ@ID40PRN/PnxEoEMhZ1NzzmPy4oW25Sl/fKV1/AQ)
[Answer]
# Google Sheets, 104 bytes
```
=sum(makearray(10,10,lambda(x,y,isbetween(((x-0.5)^2+(y-0.5)^2)^0.5,K4,K4+2^0.5,1,)*index(A1:J10,x,y))))
```
Put the matrix in cells `A1:J10`, the integer \$a\$ in cell `K4`, the formula for \$r\$ `=2 ^ 0.5 * (K2 + 0.5)` in cell `K4` and the formula in cell `K7`.

The input is the matrix `A1:J10` and the value \$r\$ in `K4`. Uses the same approximation as the Python and Jelly answers.
] |
[Question]
[
If you wanted to compute a very large long problem, that on a machine that you could buy today for an inflation adjusted price, will take some amount of years/decades. The issue is, if you only have that budget, and so can only purchase one machine. So if you purchase the machine now, it may actually take longer to compute than if you purchase one later, for the same [inflation adjusted](https://en.wikipedia.org/wiki/Real_versus_nominal_value_(economics)) price, because of Moore's Law.
[Moore's law](https://en.wikipedia.org/wiki/Moore%27s_law) states that machines will double in everything every two years, so, theoretically, a problem that takes m years to compute now, will only take m/2 years 2 years from now. The question is, how long should I wait to buy the machine, if I need to compute a problem that takes m years to compute, to get the optimal time of computation, which is inclusive of the time waited to buy the machine, and how much time does it take?
It is assumed both that I gain no money, and make just enough interest on my money to beat inflation, but no more, and also that Moore's Law continues ad infinitum.
some examples:
| years | time-to-wait | time-it-takes |
| --- | --- | --- |
| 0 years | 0 seconds, buy now! | 0 years |
| 1 year | 0 seconds, buy now! | 1 year |
| 2 years | 0 seconds, buy now! | 2 years |
| 3 years | 0.1124 years | 2.998 years |
| 4 years | 0.9425 years | 3.828 years |
| 5 years | 1.5863 years | 4.472 years |
| 7 years | 2.557 years | 5.443 years |
| 8 years | 2.942 years | 5.828 years |
| 10 years | 3.586 years | 6.472 years |
| 20 years | 5.586 years | 8.472 years |
| 100 years | 10.23 years | 13.12 years |
| 1000000 years | 38.81 years | takes 39.70 years |
Code-golf, so shortest answer wins.
Desmos example text:
`f\left(t\right)=N\cdot\left(\frac{1}{2}^{\frac{t}{2}}\right)+t`
[Answer]
## JavaScript (ES7), 52 bytes
```
f=eval(`
with(Math)a=>[b=max(0,log2(a*LN2)*2-2),b+a/2**(b/2)]
`)
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Edit: Saved 2 bytes thanks to @Samathingamajig.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~29~~ 28 bytes
```
{y+#/√2^y,y>0}~Minimize~y&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v7pSW1n/Uccso7hKnUo7g9o638y8zNzMqtS6SrX/AUWZeSXRyrp2fg5pDsqxanXByYl5ddVcBjpchjpcRjpcxjpcJjpcpjpc5jpcFkBBoIQRSNIAQoAAV@1/AA "Wolfram Language (Mathematica) – Try It Online")
Returns `{*time-it-takes*, {y->*time-to-wait*}}`.
There's a built-in. All is well.
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~79~~ 77 bytes
*-2 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
f(x,r)double*r,x;{r[1]=(*r=fmaxl(0,2*log(x*log(2)/2)/log(2)))+x/pow(2,*r/2);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBdagMhFIWfM6u4DBTUcRrHtjQg0xW0K7BS0mkNgfkJJqEXhllJX_ISuqNCd1Pv_Ih-Hi-H49Xva_W2q6ofm-Z1k7rL9Xzy-ebvxTOUgX905_f6UwSJpg-2cCUTofTNFmumpBZ1t2M4UvN1nJPiPMP1oftiWooQy2aYQ3-b7b5lvE9WUy7g0ToooVe3SkJB0IQ7wj3hgfBI2IyW0agnu1o2GiTzmDCYJFn5LrD5BoExH4-GxFMJykCWIYfYwtJDsNqZePRMoITASR_Cvj15lt74Z1jWa5tKGC1WOWLhyDsk8-su89f9Aw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2Æl2÷«ɓ÷l2Ḥ»0,+¥
```
A monadic Link that accepts a positive number, `m` years, and yields a list of two numbers, `[wait, total]` in years.
Note: Input is strictly positive - inputting `0` will yield `[nan, nan]` which is *technically* true as one cannot do anything in zero time.
**[Try it online!](https://tio.run/##ASYA2f9qZWxsef//MsOGbDLDt8KryZPDt2wy4bikwrswLCvCpf///zEwMA "Jelly – Try It Online")**
### How?
```
2Æl2÷«ɓ÷l2Ḥ»0,+¥ - Link: number, M
2 - two
Æl - natural logarithm
2÷ - two divided by that
« - minimum with M
ɓ - start a new dyadic chain - f(M, CalculationTime=that)
÷ - M divided by CalculationTime
l2 - log-base-two
Ḥ - halved
»0 - maximum with zero
¥ - last two links as a dyad - f(WaitTime=that, CalculationTime)
+ - WaitTime add CalculationTime = TotalTime
, - WaitTime paired with that -> [WaitTime, TotalTime]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
*- a lot from ATT*
```
2{a=Ramp@Log2[Log@2#/2],a+#/2^a/2}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b736g60TYoMbfAwSc/3SgaSDgYKesbxeokagOpuER9o1q1/2n6DtWGOkY6xjomOqY6ZjrmOhY6ljqGBkAExiBQq6/vp68fUJSZV/IfAA "Wolfram Language (Mathematica) – Try It Online")
---
Explanation:
`2` Take twice
`{a=Ramp@` zero or
`Log2,` the base-2 logarithm
`Log@2` of the natural logarithm of 2
`#` times the input
`/2]` divided by two.
`, a` Then, output this
`+#/` plus the input divided by
`2^a` two to the power of the variable,
`/2}&` all divided by two.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 87 bytes
```
s=(n,x=3,i=999,l=Math.LN2)=>i?s(n,x+2/l-2**(x/2+2)/n/l/l,i-1):[x=x>0?x:0,n*.5**(x/2)+x]
```
[Try it online!](https://tio.run/##XZHfaoMwFMbvfYpz0QttYzQxtlpJ9wLb2L2VVsRubjaOKp0gfXaXY2TCQuDwffmdL/8@83veFrfqu3Pv0Ti20laklwGpZBzHpJYvefdBn1@5Iw/VU4uLG@7VLl@v7d7jG@54yqu9mlQuc/ZpL/uD/9TvfaLWNDSMs@mzMbGKRrUdFHlbtiAhtQBSnwDOjKBgk2BG8ElwIwItKGNcaIfGcWRcgW4seEggoBGfXa0YDaOt7hFU7OaEHXaGoS4hFSIwZjTFCY7mXz/zMU4HENgu/dxHaHKjxWU@HtinXG/GAsoWG4fO2dJI3yqI6Q7vmCWWdWluYJuXSBWBn7zqCHT5V5lBczGP48CgU2bmejLI9WQgCfoLnGQGmrqkdfNun5VcDeqRHDuk97AasD7APRy71WAyaNe83cqiaqtG2cJBGCMRxrrAqP7DZ73lwxp/AQ "JavaScript (V8) – Try It Online")
Returns both `time-to-wait` and `time-it-takes`. You could remove 1 byte to make it less precise at higher values, as 86 fits all test cases, but the problem does not tell a range you have to be precise to.
This uses [Newton's Method](https://en.wikipedia.org/wiki/Newton%27s_method) on the first derivative of the function given to find the minimum.
Pre-golfed code: (derivatives found with [WolframAlpha](https://www.wolframalpha.com/))
```
const f=(x,n)=>n*.5**(x/2)+x; // f(t)
const g=(x,n)=>1-n*2**(-x/2-1)*Math.LN2; // f'(t)
const h=(x,n)=>2**(-2-x/2)*n*Math.LN2**2; // f''(t)
const solution = n => {
let x = 3; // arbitrary number that seems to work
for (let i = 0; i < 999; i++) {
// console.log(x);
x = x - g(x,n)/h(x,n);
}
x = Math.max(0,x);
return [x, f(x,n)];
}
```
[Answer]
# x86 64-bit machine code, 30 bytes
```
D9 EA D8 C0 D9 E8 DB 2F DB F2 72 0D D8 F2 D9 F1 D8 C0 D9 C9 D8 C1 DB 3F C3 DE D9 D8 E0 C3
```
This takes in RDI a pointer to a double-extended-precision floating-point number, used both for the input \$m\$ and for the output of total time taken, and returns the waiting time on the FPU register stack.
[Try it online!](https://tio.run/##bVLbbtswDH2OvoLwkEFKlSJxuwvsZQ8r9rYBQ5GHDWkeZF0cDbJs@NI5DfLr8ygHK7J0BiSR55CHNCVZVfNcymF4Zb10ndLwoWmVLa93H8k/kLPZJVZbnweM6L7VtYfoLoKDK30Oquwyp8HQc2/Ws/RIRFMAhfuIkuvclZlwYIhJJsYpF2syMUIpaFq6YPx0kEAtxx3Wn36sP8O39T1samW3CMqysGfhMYb/zMAho@zjBWH2Lu7/X6GXu2Av2Qt6hJq2elm71i1xydhCVYWgLruQDREsApYSYn0LhbCeBkPUueQgd6KG2QydR0YOZBKYHlaw4LAPR3qCWrnZontAeMkh5nDD4ZbDGw7vOLxHEIk4kIvTFr4j5pqyhrFaAQmKYDtYY3J@HxnKFukFKBA09HXGAlHhDbeGRlObwPSLCevBRxwKDoLDGHMkz1EP/quQO@s1yFLpJAr0@EMphD6e0IwRUiUc/qbAdBF/R8H9itLONzb3Wo2DmTHDNv3V1RafDPzaWeyMPsF8BRRng5L93Q0L@s9CdGoh27e6YWOHfSBx/h0@S5zkkQzDb2mcyJthXry9xQ3f4QpztfsD "C++ (gcc) – Try It Online")
Letting \$x\$ be the running time in years, the total time is \$ 2\log\_2(m/x) + x \$. The derivative of that is \$ \frac{2}{\ln(2)} \frac xm \frac{-m}{x^2} + 1 = \frac{-2}{\ln(2)x} + 1 \$, which is zero when \$ x = \frac{2}{\ln(2)} = 2\log\_2(e)\$. Therefore, that is the optimal value if it is valid – if \$m\$ is at least that value.
In assembly:
```
f: fldl2e # Push log_2(e) onto the FPU register stack.
fadd st(0), st(0) # Double it by adding it to itself.
fld1 # Push 1 onto the FPU register stack.
fld TBYTE PTR [rdi] # Push m onto the FPU register stack.
fcomi st(0), st(2) # Compare m and 2*log_2(e).
jb low # Jump if m < 2*log_2(e).
fdiv st(0), st(2) # Divide m by 2*log_2(e).
fyl2x # Taking the top two values (m/(2*log_2(e)), 1) as (x, y),
# replace them with y*log_2(x).
fadd st(0), st(0) # Double the result, getting the waiting time.
fxch st(1) # Exchange values, moving 2*log_2(e) to the top.
fadd st(0), st(1) # Add the waiting time to 2*log_2(e) for the total time.
fstp TBYTE PTR [rdi] # Store that at the address and pop it off the stack.
ret # Return.
low:
fcompp # Compare the two values on top of the stack and pop both.
fsub st(0), st(0) # Subtract the remaining value from itself, producing 0.
ret # Return. (The value at the address is unchanged.)
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žr.²/.²·Í¾‚àÐ;oIs/+‚
```
Port of [*@Neil*'s JavaScript answer](https://codegolf.stackexchange.com/a/247033/52210).
Uses the legacy version of 05AB1E, because apparently `o` (\$2^a\$ builtin) doesn't work for zero as float (`0.0`)..
[Try it online](https://tio.run/##MzBNTDJM/f//6L4ivUOb9IH40PbDvYf2PWqYdXjB4QnW@Z7F@tpAzv//hgYGAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/o/uK9A5t0gfiQ9sP9x7a96hh1uEFhydY51cW62sDOf91/kcb6BjqGOkY65jomOqY6ZjrWOgYGugYAUUNwBgEYgE).
**Explanation:**
```
žr # Push builtin e
.² # Take the base-2 logarithm of it
/ # Divide the (implicit) input-integer by this
.² # Get the base-2 logarithm of that again
· # Double it
Í # Decrease it by 2
¾‚ # Pair it with 0
à # Get the maximum of this pair
Ð # Triplicate this maximum
; # Halve the top copy
o # Push 2 to the power this
Is/ # Push the input, and divide it by this value
+ # Add it to the other maximum-copy
‚ # Pair it with the remaining maximum
# (after which this pair is output implicitly as result)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~73~~ 70 bytes
```
from math import*
lambda a:[b:=log2(max(a*log(2),2))*2-2,b+a/2**(b/2)]
```
[Try it online!](https://tio.run/##JYtBDoIwFET3nGKWbf0G/GgkJJyEsGijCAmlTfkLPX0FncVk8l4mfmQKa93ElPOYgoe3MmH2MSQxxdgt1ruHhW1713ZLeLHy9q2s2adiTay14TOTO9mSjVGuZD1keW6yoUNfES4EJtSEK@FGuBOaHe6CD1n968hQjCFBMK/4/dsCiGleRQlhVKJ1/gI "Python 3.8 (pre-release) – Try It Online")
* -3 Thanks to [att](https://codegolf.stackexchange.com/users/81203/att), since [](https://i.stack.imgur.com/AR3T2.png)
] |
[Question]
[
* Task:
With the minimum amount of bytes, determine today's Zodiac sign using the programming language of your choice.
* Rules:
This is code golf, the answer with the fewest characters wins. The initialization of getting the current date into a variable (e.g. `var now = new Date();`) does not add to the count. Leap years must be handled correctly.
* Limitations:
You cannot use any other library functions for handling dates, nor predefined lists. In particular, participants would have to calculate the ordinal day of the year themselves if needed.
* Input:
The current date in the proleptic Gregorian calendar with numeric year, month (1–12) and day of the month (1–28…31).
* Output:
A single Unicode symbol indicating the current one of the twelve Zodiac signs from Western astrology, as used in horoscopes and listed below:
1. ♈︎ Aries: March 21 – April 19
2. ♉︎ Taurus: April 20 – May 20
3. ♊︎ Gemini: May 21 – June 21
4. ♋︎ Cancer: June 22 – July 22
5. ♌︎ Leo: July 23 – August 22
6. ♍︎ Virgo: August 23 – September 22
7. ♎︎ Libra: September 23 – October 22
8. ♏︎ Scorpio: October 23 – November 22
9. ♐︎ Sagittarius: November 23 – December 21
10. ♑︎ Capricorn: December 22 – January 19
11. ♒︎ Aquarius: January 20 – February 18
12. ♓︎ Pisces: February 19 – March 20
The actual dates might differ by one day depending on the year, but for this task the above date ranges are considered accurate for every year.
## Example
The sign for today, 28 February 2022, is Pisces, so the correct output would be `♓︎`.
## Related challenges
* [Chinese Zodiac of the year](https://codegolf.stackexchange.com/questions/68318/chinese-zodiac-of-the-year)
* [What's the current zodiac?](https://codegolf.stackexchange.com/questions/193991/whats-the-current-zodiac) (hour)
* [Get the day of the year of a given date](https://codegolf.stackexchange.com/questions/230712/get-the-day-of-the-year-of-a-given-date)
* [ASCII Art of the Day #4 - Zodiac Signs](https://codegolf.stackexchange.com/questions/51123/ascii-art-of-the-day-4-zodiac-signs)
* [What is your star-sign?](https://codegolf.stackexchange.com/q/35036/42932) – different output
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~64~~ 62 bytes
Expects `(month)(day)`.
This version builds the UTF-8 encoding of the code point (from `0xE2 0x99 0x88` for Aries to `0xE2 0x99 0x93` for Pisces).
```
m=>d=>Buffer([226,153,136+(m+=9^d<24+~"1342321"[m%12])%12])+''
```
[Try it online!](https://tio.run/##bdDdCoIwFMDx@55CgnBjFp6zaQ7Si15DCsSPKNSFVpe9uum6mhuDXfz5bePsUXyKsRzuz9e@V1U9NenUpVmVZud309QDyRHjACIeAI8Z6Vgqr9UJBftugQvkCNu82wFeqN6Y70@l6kfV1odW3UhDPKAEQ@oxz58X8@aClEBC6WYFlywNyPVRCy4ZDCj0UQsK6@nIfWNk3RjrYsElowGPulhwydyAiRsmFpRuKNcQQifU2YTghmBBdE6tszk1/D98@gE "JavaScript (Node.js) – Try It Online")
### ES6, 63 bytes
Using the more straightforward `String.fromCharCode()` with a direct code point is one byte longer.
```
m=>d=>String.fromCharCode(9800+(m+=9^d<24+~"1342321"[m%12])%12)
```
[Try it online!](https://tio.run/##bdDPCoMgHMDx@54igjFFFv6stoTVpUfYcWwQ/Vsjc1TsuFdv5k6mCB6@flT0VXyKqRy793wcZFUvTbqINKvS7DqP3dAGzShF/izGXC0inlBKkCApf1QXFpGvD2HEQgb@TeyB3bGa8FLKYZJ9HfSyRQ3yACNGsUe8gxrEU4VhBAnGuw1cMzdgqLdacM1gwEhvtWBkXR27T4ytE0@6WHDNzIBnXSy45tCAiRsmFuRuyLcQqBPqbEJwQ7Agc75aZ/PV8P/w5Qc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“£f{ẋ’b5⁸ị+19>_@⁸_3%12+⁽#1Ọ
```
A dyadic Link accepting an integer, `month`, on the left and an integer, `day`, on the right that yields a character.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDi9OqH@7qftQwM8n0UeOOh7u7tQ0t7eIdgOx4Y1VDI@1HjXuVDR/u7vn//7/xfyNDAA "Jelly – Try It Online")** Or see [a whole year](https://tio.run/##y0rNyan8//9Rw5xDi9OqH@7qftQwM8n0UeOOh7u7tQ0t7eIdgOx4Y1VDI@1HjXuVDR/u7vl/ePmjxp3WDienP9q4Tt/a4eHOad6akf//R0cb6hgbxupEG@kYWQIpYwjPRMfYAEiZQnhmEJ45hGcBoSwhgoYGEK6hIZRvBOLHAgA "Jelly – Try It Online").
### How?
```
“£f{ẋ’b5⁸ị+19>_@⁸_3%12+⁽#1Ọ - Link: M; D
“£f{ẋ’ - 53343748
b5 - to base five -> [1, 0, 2, 1, 2, 3, 4, 4, 4, 4, 4, 3]
⁸ị - get the item at 1-indexed index M
+19 - add nineteen to it
> - is that greater than D? -> 1 or 0
_@⁸ - subtract from M -> M-1 or M
_3 - subtract three (offset since characters start at March)
%12 - modulo twelve
⁽#1 - 9800
+ - add
Ọ - cast to character
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 112 bytes
```
T`d`k-m`1.-
T`d`l`.-
T`b-m`c-mb`.-3|[bce]-2|[df]-2[1-9]|[gm]-2[2-9]|[h-l]-2[3-9]|c-19
.(.).+
$1
T`e-mb-d`♈-♓
```
[Try it online!](https://tio.run/##Ncw7DsIwDIDhPedgACFHsVOguQdbVCn0wUO0HRBjD8DO1Ov1IsE26vLns1v51b0f4yXnc2rTE4aEFoy4T4qaVw0MNU9@inXTVUBTbK/8RIRQTfE2iEl9h14GL0MDGIzd2p3dmw3yqY7PQJuW@QPL/M3ZofzBJWccAZbaICW21z0XjSt0X@jmAFhI/5avx7Vk3GmtN65Ul@qgDmJ0Yikb1agmuSOlHw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in the format `mm-dd`. Does not output a Unicode variation selector, but the output looks fine in TIO to me. Explanation:
```
T`d`k-m`1.-
```
Change October to December to `k` to `m`, which will become Scorpio to Capricorn.
```
T`d`l`.-
```
Change January to September to `b` to `j`, which will become Aquarius to Libra.
```
T`b-m`c-mb`.-3|[bce]-2|[df]-2[1-9]|[gm]-2[2-9]|[h-l]-2[3-9]|c-19
```
Increment the encoded sign if the day is past the cutoff date for the next sign.
```
.(.).+
$1
```
Delete everything except the encoded sign.
```
T`e-mb-d`♈-♓
```
Decode to a Unicode Zodiac sign.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
Nθ℅⁺⁹⁸⁰⁰﹪⁺⁸⁺θ›N⁺¹⁸I§”)⊞⌊4\`ζ”θ¹²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDGSifmFwCFAvIKS3WsLQwMNBR8M1PKc3Jh4hY6CiA6UIdBfei1ESQSmSTNKHShkB1zonFJRqOJZ55KakVGkrGhgZGhkbGJiCgpKNQqAkCOgqGRiDa@v9/Iy4ji/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Takes separate month and day as inputs. Explanation:
```
Nθ First input as a number
N Second input as a number
› Is greater than
”...” Compressed string `310212344444`
§ Cyclically indexed by
θ Input month
I Cast to integer
⁺ Plus
¹⁸ Literal integer `18`
⁺ Plus
θ Input month
⁺ Plus
⁸ Literal integer `8`
﹪ Modulo
¹² Literal integer `12`
⁺ Plus
⁹⁸⁰⁰ Literal integer `9800`
℅ Convert to Unicode
Implicitly print
```
] |
[Question]
[
Given the measures of two of the interior angles of a triangle (`x` and `y`; the other angle can be easily calculated with `180 - x - y`), draw a line segment that cuts this triangle into two isosceles triangles. You need to output the angle measures of both of your triangles.
However, because the base angles are the same, you only need to output the list `[apex angle, base angle]` of the divided triangles for both of the isosceles triangles. You can output the divided triangles in any order.
## An example
```
Say your input is 100, 60.
Let's take a look at the complete triangle first. The triangle looks approximately like this.
100
60 20
Now we try to divide one of the angles such that two divided triangles are both isosceles triangles.
100
(40,20) 20
Now our bottom triangle is an isosceles triangle, since both of the base angles
of the bottom triangle are 20. The angle measures of the bottom triangle
looks approximately like this.
140
20 20
Now, is the top triangle an isosceles triangle?
100
40
40
It is an isosceles triangle, because two of the angle measures are 40.
Therefore, for [100, 60], you need to output [[100, 40], [140, 20]].
```
## Example cases
```
[20, 40] -> [[140, 20], [100, 40]]
[45, 45] -> [[90, 45], [90, 45]]
[36, 72] -> [[108, 36], [36, 72]]
[108, 36] -> [[108, 36], [36, 72]]
[44, 132] -> [[92, 44], [4, 88]]
```
## Specifications
* You can always assume that the triangle is dividable into two isosceles triangles.
* You can output one of the many solutions of the cases; for example, you can also output `[20, 40] -> [[100, 40], [20, 80]]` for the first test case.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
OƵΔ᪩90KD®Qiʒ45‹®y23S*åà*}ßx‚}ε90α·y‚
```
Input as a pair of integers; output as a pair of pairs of integers.
[Try it online](https://tio.run/##AUsAtP9vc2FiaWX//0/Gtc6UzrHCqsKpOTBLRMKuUWnKkjQ14oC5wq55MjNTKsOlw6AqfcOfeOKAmn3OtTkwzrHCt3nigJr//1syMCw5MF0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf/9jW89NObfx0KpDKy0NvF0OrQvMPDXJxPRRw85D6yqNjIO1Di89vECr9vD8ikcNs2rPbbU0ACreXgnk/K/V@R8dbWhgoGNmEKsTbWSgYwKiTUx1TEyBtLGZjrkRkDY0sNAxNgNJmOgYGhtBVFoaxMYCAA).
**Explanation:**
```
O # Take the sum of the (implicit) input-pair of angles
ƵΔα # Get the absolute difference with (compressed) 180
ª # Append that third angle to the (implicit) input-pair
© # Store it in variable `®` (without popping)
90K # Remove 90 from the triplet of angles
D # Duplicate it
®Qi # If it's still equal to `®` (thus none were 90):
ʒ # Filter the triplet by:
45‹ # Check that the angle is smaller than 45
* # AND
y2 S* # Check if the angle multiplied by 2
3S* à # or multiplied by 3
® å # is in the triplet of angles `®`
}ß # After the filter: pop and push the minimum of the remaining angles
x # Double it (without popping)
‚ # Pair the non-doubled and doubled values together
}ε # After the if statement: map the angles in the pair to:
90α # Get the absolute difference with 90
· # Double it
y‚ # And pair it with the non-mapped angle
# (after which the resulting pair of pairs 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 `ƵΔ` is `180`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~123~~ 129 bytes
```
g=lambda*p:[[180-2*x,x]for x in p]
f=lambda a,b:((c:=180-a-b)==90or c>45>2in{a/b,b/a})*g(a,b)or(c/3in{a,b})*g(c/3,c/3*2)or f(b,c)
```
[Try it online!](https://tio.run/##dZHLboMwEEX3fMWIbuzIJBRImiDBjyAWNpiUiocFTsVDfDsdHFh2wWjuzLHvtVCj/m4b/666dX1GFa9Fzk8qTJLPu@t4p4ENadF2MEDZgEqtYkeAMxESkoXRxnFH0Ch6uAhmcXCNvbKZ@UUwceELPT0JwrTtSHbxtwUTZoiK4XfycAUFESyja1mrttPQj721uVZlIzdj1Ode52UTWkAGBiNlIAclMy1ziKDmishfXjFz4NyrqtTEdmKbUgsmk3BwRgs@QHcj8KoCJbv6pbku26aHn1evQbcgJPS8kBZs1pjSOGMcmZMZXdEU64R1ZIOpWz@ZfsLtQjEddLJ/VRpDFebVOFFd2WhS2HPCGYh0ASeG@Y0tMO8Gb00hig7L4310semaeC6DwE23s/hrAlSemzJIPt33IrWS4IrddUcerhFI7B0C/o3Bl3fc4d4Z@LeN2OdIHMN/kT8 "Python 3.8 (pre-release) – Try It Online")
A function that takes in 2 angles, and returns the 2 isosceles triangles. If the given triangle cannot be divided, the function loops forever.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 [bytes](https://github.com/abrudz/SBCS)
```
(⊢,⍨¨2×90-⊢)∘{90∊⍵:⍵~90⋄1 2×⌊/⍵∩∊⍵÷⊂2 3},,180-+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR1yKdR70rDq0wOjzd0kAXyNV81DGj2tLgUUfXo96tVkBcB@R0txgqAFU86unSB4o86lgJkT68/VFXk5GCca2OjqGFga72/7RHbRMe9fY96mo@tN74UdvER31Tg4OcgWSIh2fwfyDtHKlenJhTog40MTUvMSknNdjRJ4QrNim/IjMvXSE/j8vIQCFNwcSAy8QURJtyGZsBaXMjCG1oYMFlZA5kmBlzmZiABIyNAA "APL (Dyalog Unicode) – Try It Online")
A tacit function that takes two angles as left and right arguments.
Uses the information found by Neil, modified to take care of xnor's test case:
>
> A triangle can be divided into 2 isosceles triangles either if **one of the angles** is < 45° and is exactly one half or one third of one of the other angles, or if one of the angles is 90°.
>
>
>
Now, the base angles of the result can be found as follows:
* If one of the angles is 90°, the bases are the other two angles.
* Otherwise, `one of the angles is < 45° and is exactly one half or one third of one of the other angles` should hold, because the input is guaranteed to have a solution. In this case, the angle satisfying the condition becomes the base for one triangle, and the other triangle's base angle is twice the angle.
### How it works: the code
```
(⊢,⍨¨2×90-⊢)∘{90∊⍵:⍵~90⋄1 2×⌊/⍵∩∊⍵÷⊂2 3},,180-+ ⍝ Left, Right: two angles
,,180-+ ⍝ Length-3 vector of three angles
{ } ⍝ Find two base angles:
90∊⍵:⍵~90⋄ ⍝ If an angle is 90, the bases are the other two
⍵∩∊⍵÷⊂2 3 ⍝ Otherwise, find the angles that are 1÷2 or 1÷3 of another
1 2×⌊/ ⍝ Take the minimum angle of that and attach its double
( )∘ ⍝ Attach apex angles to two base angles
2×90-⊢ ⍝ apex=180-2×base
⊢,⍨¨ ⍝ Attach each apex to the left of the base
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes
```
F²⊞υN⊞υ⁻¹⁸⁰Συ≔Φυ∧‹ι⁴⁵∨№υ⊗ι№υ׳ιθ¿θ≔⟦⌊θ⊗⌊θ⟧θF№υ⁹⁰≔Φυ⁻⁹⁰κθIEθ⟦⊗⁻⁹⁰ιι
```
[Try it online!](https://tio.run/##TY/NbsJADITvPIWPtrSVoE2kIk6ICqlSaZHghjgEWIrFZkN2477@1uEn4Toz/sazPxVhXxUupWMVAF8JlhJPKAY@/UWabyl3NiDRZPDQF@wl4uh9aGAlJQq15jRG/vU4Z9doXFNTf8AvGyOygSwnAz8BZ5X4pjU/Ktk5e0AmNTp1zaWN@GZAZWqdWsF8BKwJ7vyNlnOprTX1lF6j7e3IumjhuqeDj4fUUfovb1vGOuX8KFwG1otZERtcFBesDWyeiu7p6@O8baenlOWDLE8vf@4f "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υN
```
Input the two provided angles.
```
⊞υ⁻¹⁸⁰Συ
```
Calculate the third angle.
```
≔Φυ∧‹ι⁴⁵∨№υ⊗ι№υ׳ιθ
```
See if any angle under 45° appears doubled or tripled.
```
¿θ≔⟦⌊θ⊗⌊θ⟧θ
```
If so then the base angles of the result are that angle and the doubled angle.
```
F№υ⁹⁰
```
Otherwise if this is a right-angled triangle, ...
```
≔Φυ⁻⁹⁰κθ
```
... then the base angles of the result are the other two angles.
```
IEθ⟦⊗⁻⁹⁰ιι
```
If we got any base angles then compute the apex angles and output all of the angles.
[Answer]
# [R](https://www.r-project.org/), ~~146~~ ~~132~~ 128 bytes
or **~~158~~ ~~150~~ [146 bytes](https://tio.run/##RY/dDoIwDIXvfYolxmTTLg4YChe8i2ZOLMEt2Up4fBw/am96TvvlpA2TGYgCNtNzcIbQO47QATVm6VmlJMpOQGze6DgJccPnjXNdynjW4oDuQNBjJG62GdTqFM@5AMNj0nLW4ovEJTA/xnmdGixptVpzZnoBdAJSbafxXIFWYrc5XYIuf664wDX/uUxVUFz@qIas@G9rqDLB9ixg@yJ5d21vWZqvYkR6@YEYjZ6lTx62DdYy44OzIe6mDw)** to output the 4 angles as 2 lists of 2 angles each.
```
function(i,j,t=c(i,j,180-i-j),s=min(t))`if`((45-s/4)%in%t,c(45-s/4,90+s/2,s,90-s/2),c(s,180-2*s,2*s,`if`(90%in%t,90-s,180-4*s)))
```
[Try it online!](https://tio.run/##RY7dDoIwDIXvfYolxmTVEscYChe8i2ZOrNGRbCU@Po6fwEXT8/WcNg2D7ZkDNcOz95ap85LwjdzYqeeVyih7A8bmS14ywI2eNylNmcWzgQP5A6NdEGt1imeNMYnEGpITpxP6GHGsablW89oYmlxzjACwPCK1QqNgt5Ap0ZQrFRe86pVyVWFx2aIG82Jza6xyEHsRqH1xdvftx4k0n8WP@NX1LPjXifT8w7XBOWG74F2Iu@EP "R – Try It Online")
An approach that does not use the 'one-half or one-third' trick:
Consider initial triangle with angles a,b,s, where *s is the smallest angle* (so s is never divided). a will be the angle that gets divided.
**case 1:** right-angle triangle (uses both bases of smaller triangles as sides)
=> divide right angle
**case 2:** starting triangle uses base and base+wall of smaller triangles as sides
=> t1=b,b,d (where d is formed from divided angle: d=a-s)
=> t2=s,s,180-b
=> so (from t2) we get b=2\*s and *we can specify both t1 and t2 from s*
**case 3:** starting triangle uses only 1 base as side (other is created internally)
=> t1=b,b,180-d (where d is formed from divided angle: d=a-b)
=> t2=s,d,d
=> so (from t2): d=90-s/2, and *we can specify both t1 and t2 from s*
and (from t1): b=45-s/4 to check when this case is satisfied (but we won't bother to do this...)
**Readable code:**
```
cuttri=function(i,j,t=c(i,j,180-i-j)){ # we don't know which angle is a or b
s=min(t) # but we know s is the smallest
if(90 %in% t){ # case 1: right-angle triangle
list(c(90-s,2*s),c(s,180-2*s))}
else if((2*s) %in% t){ # case 2:
list(c(2*s,180-4*s),c(s,180-2*s))}
else if((45-s/4) %in% t){ # case 3 (but we don't actually need to check if
list(c(45-s/4,90+s/2),c(s,90-s/2))} # we're assured that triangle can be divided)
}
```
Note that because the golfed code skips the final check for case 3, the output will be incorrect if it is 'fed' non-valid angles corresponding to a triangle that can't be divided into two isosceles triangles.
] |
[Question]
[
I have some JavaScript code in a `<script>` HTML tag I'd like to golf, while still remaining in the tag. How can I golf that code, if at all? Here's the code:
```
<script>document.write`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE CRAB NICHOLSON.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND CRAB NICHOLSON'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`;document.body.style.background="#000"</script>
```
[Answer]
Save 3 bytes by assigning `document` to a variable:
```
(d=document).write`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE CRAB NICHOLSON.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND CRAB NICHOLSON'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`;d.body.style.background="#000"
```
Save 2 bytes by reusing ' CRAB NICHOLSON':
```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE${c=' CRAB NICHOLSON'}.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND${c}'S<br>ULTIMATE LAIR OF AWESOMENESS</font>`);d.body.style.background="#000"
```
Save 1 byte by using `.join`<br>``:
```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS</font>`.split`_`.join`<br>`);d.body.style.background="#000"
```
Further golfs suggested by [@Night2](https://codegolf.stackexchange.com/posts/comments/464495?noredirect=1):
Save 14 bytes by using `.bgColor=0`:
```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS</font>`.split`_`.join`<br>`);d.body.bgColor=0
```
Save 7 bytes by 'forgetting' to close the `<font>` tag (YMMV):
```
(d=document).write(`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`<br>`);d.body.bgColor=0
```
] |
[Question]
[
Sometimes lexicographical sorting of strings may cut it, but when browsing the filesystem, you really need better sorting criteria than just ASCII indices all the time.
For this challenge, given a list of strings representing filenames and folders in a directory, do a filesystem sort, explained below:
1. Split every string into an array of alternating digits (`0123456789`) and non-digits. If the filename begins with digits, insert an empty string at the beginning of the array.
2. For each element in the array, if the element is a string, lexicographically sort all the strings by that element in all lowercase or uppercase. If the element is a number, sort by numerical order. If any files are tied, continue to the next element for more specific sorting criteria.
Here is an example, starting with strings that are initially sorted lexicographically:
```
Abcd.txt
Cat05.jpg
Meme00.jpeg
abc.txt
cat.png
cat02.jpg
cat1.jpeg
meme03-02.jpg
meme03-1.jpeg
meme04.jpg
```
After step 1, you'll get this:
```
"Abcd.txt"
"Cat", 5, ".jpg"
"Meme", 0, ".jpeg"
"abc.txt"
"cat.png"
"cat", 2, ".jpg"
"cat", 1, ".jpeg"
"meme", 3, "-", 2, ".jpg"
"meme", 3, "-", 1, ".jpeg"
"meme", 4, ".jpg"
```
After step 2, you'll get this:
```
abc.txt
Abcd.txt
cat1.jpeg
cat02.jpg
Cat05.jpg
cat.png
Meme00.jpeg
meme03-1.jpeg
meme03-02.jpg
meme04.jpg
```
Here are the rules:
* You *may not* assume the list of input strings is sorted in any order
* You *may* assume that the input strings only contain printable ASCII characters
* You *may* assume that when the filenames are converted to all lowercase or all uppercase, there will be no duplicates (i.e., a case-insensitive filesystem)
* Input and output may be specified via any [approved default method](http://meta.codegolf.stackexchange.com/q/2447/42091)
* [Standard loopholes apply](http://meta.codegolf.stackexchange.com/q/1061/42091)
Here is an example implementation of the sorting algorithm if there is any confusion:
```
function sort(array) {
function split(file) {
return file.split(/(\D*)(\d*)/);
}
return array.sort((a, b) => {
var c = split(a);
var d = split(b);
for (var i = 0; i < Math.min(c.length, d.length); i++) {
var e = c[i].toLowerCase();
var f = d[i].toLowerCase();
if (e-f) {
return e-f;
}
if (e.localeCompare(f) !== 0) {
return e.localeCompare(f);
}
}
return c.length - d.length;
});
}
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
[Answer]
# [Bean](https://github.com/patrickroberts/bean), ~~116~~ ~~121~~ 118 bytes
Hexdump:
```
00000000 26 55 cd a0 62 80 40 a0 6f 53 d0 80 d3 d0 80 a0 &UÍ b.@ oSÐ.ÓÐ.
00000010 6f 20 80 0d 21 80 81 00 20 80 92 20 6f 53 d0 80 o ..!... .. oSÐ.
00000020 a0 78 20 80 83 40 a0 5d a0 5e 53 d0 80 d3 a0 62 x ..@ ] ^SÐ.Ó b
00000030 20 5d 20 80 8b 40 a0 5f a0 60 a0 65 a0 6e dd a0 ] ..@ _ ` e nÝ
00000040 61 50 84 d3 a0 62 20 5e 20 65 4e ce a0 5f 80 4c aP.Ó b ^ eNÎ _.L
00000050 a0 60 8c 20 61 80 53 d0 80 d3 50 80 a0 60 20 80 `. a.SÐ.ÓP. ` .
00000060 b9 20 80 b3 53 50 80 a0 61 20 80 b9 a8 dc c4 aa ¹ .³SP. a .¹¨ÜĪ
00000070 a9 a8 dc e4 aa 29 ©¨Üäª)
00000076
```
Equivalent JavaScript (140 bytes, ignoring added whitespace for formatting):
```
f=s=>s.split(/(\D*)(\d*)/).concat(s),
_.sort(
(a,b)=>f(a).reduce(
(c,d,i,r,e=f(b)[i])=>
c||d-e||d.toLowerCase().localeCompare(e.toLowerCase())
)
)
```
Basically a golfed version of the example implementation given in the question.
[Click here for the demo!](https://patrickroberts.github.io/bean/#h=JlXNoGKAQKBvU9CA09CAoG8ggA0hgIEAIICSIG9T0ICgeCCAg0CgXaBeU9CA06BiIF0ggItAoF+gYKBloG7doGFQhNOgYiBeIGVOzqBfgEygYIwgYYBT0IDTUICgYCCAuSCAs1NQgKBhIIC5qNzEqqmo3OSqKQ==&i=YWJjLnR4dApjYXQucG5nCkFiY2QudHh0CkNhdDA1LmpwZwpNZW1lMDAuanBlZwpjYXQxLmpwZWcKY2F0MDIuanBnCm1lbWUwMy0xLmpwZWcKbWVtZTAzLTAyLmpwZwptZW1lMDQuanBn&f=1&w=1)
[Answer]
## JavaScript (ES6), ~~105~~ ~~110~~ ~~101~~ ~~97~~ 82 bytes
Assumes that each numeric element is up to 99 characters long.
```
a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))
```
### Test
```
let f =
a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))
console.log(f([
'Abcd.txt',
'Cat05.jpg',
'Meme00.jpeg',
'abc.txt',
'cat.png',
'cat1.jpeg',
'cat02.jpg',
'meme03-1.jpeg',
'meme03-02.jpg',
'meme04.jpg'
]).join('\n'))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
VµŒlµœ&ØDµ?
e€ØDI0;œṗ⁸Ç€µÞ
```
**[Try it online!](https://tio.run/nexus/jelly#@x92aOvRSTlAYrLa4Rkuh7bac6U@aloDZHoaWB@d/HDn9EeNOw63A4UObT087//h9sj//6PVHZOSU/RKKkrUddSdE0sMTPWyCtKBbN/U3FQDAyAnFcRLTEqGqklOLNEryEuHsAxh8kC2gRFUZy5Ip7EuXA7KR5U3AXNiAQ)** (The footer code, `ÇY`, just splits the resulting list of strings with line feeds for legibility)
### How?
```
VµŒlµœ&ØDµ? - Link 1, evaluate a substring: substring
µ µ µ? - ... then / else / if ...
ØD - if: decimal digit characters '0123456789'
œ& - multi-set intersection, effectively "all digits"?
V - then: eval, cast the digit strings to integers
Œl - else: convert to lowercase, cast the char strings to lowercase
e€ØDI0;œṗ⁸Ç€µÞ - Main link: list of filenames
µ - monadic chain separation
Þ - sort the filenames by the key function, given a single filename:
ØD - decimal digit character yield, '0123456789'
e€ - exists in for €ach -> a list of 0s at chars and 1s at digits
I - increments -> 1s and -1s at changeover indexes - 1, 0s elsewhere, 0s
0; - prepend a zero -> 1s and -1s at changeover indexes, 0s elsewhere
⁸ - left argument, the filename
œṗ - partition at the truthy indexes (the 1s and -1s)
Ç€ - call the last link (1) as a monad for €ach substring
```
[Answer]
# [Perl 6](https://perl6.org), ~~50 45~~ 44 bytes
```
*.sort:{.lc~~/(\D*)*%%$0=(\d+)/;map {+$_//~$_},@0}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQK84vKkktUrD9r6UHYlpV6@Uk19Xpa8S4aGlqqaqqGNhqxKRoa@pb5yYWKFRrq8Tr69epxNfqOBjU/tcrKC1RSMsvUsjJzEst1ivITM7W0NLUg5r53zmxxMBUL6sgncs3NTfVwADITE3nSk4sMYSzDIzA8rkgeWNdqDiUhyxnAmICAA "Perl 6 – TIO Nexus")
```
*.sort:{/(\D*)*%%$0=(\d+)/;map {+$_//.lc},@0}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQK84vKkktUrD9r6UHYlpV62vEuGhpaqmqqhjYasSkaGvqW@cmFihUa6vE6@vr5STX6jgY1P7XKygtUUjLL1LIycxLLdYryEzO1tDS1IMa9985scTAVC@rIJ3LNzU31cAAyExN50pOLDGEswyMwPK5IHljXag4lIcsZwJiAgA "Perl 6 – TIO Nexus")
```
*.sort:{/(\D*)*%$0=(\d+)/;map {+$_//.lc},@0}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQK84vKkktUrD9r6UHYlpV62vEuGhpaqmqGNhqxKRoa@pb5yYWKFRrq8Tr6@vlJNfqOBjU/tcrKC1RSMsvUsjJzEst1ivITM7W0NLUg5r23zmxxMBUL6sgncs3NTfVwADITE3nSk4sMYSzDIzA8rkgeWNdqDiUhyxnAmICAA "Perl 6 – TIO Nexus")
## Expanded:
```
* # Whatever lambda ( this is the argument )
.sort: # sort by doing the following to each value
{ # bare block lambda with implicit parameter 「$_」
/
( # stored in $0
\D* # any number of non-digits
)* # any number of times
% # separated by
$0 = ( # stored in $0
\d+ # at least one digit
)
/;
map {
+$_ # try to turn the element into a number
// # if that fails
.lc # lowercase it
},
@0 # for all the elements
}
```
[Answer]
# JavaScript ([ES2020](https://ecma-international.org/ecma-402/6.0/index.html#collator-objects)), 54 bytes
```
a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)
```
Uses the [`Intl.Collator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator/Collator) builtin to provide the natural sort order.
### Test
```
const f =
a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)
console.log(f([
'Abcd.txt',
'Cat05.jpg',
'Meme00.jpeg',
'abc.txt',
'cat.png',
'cat1.jpeg',
'cat02.jpg',
'meme03-1.jpeg',
'meme03-02.jpg',
'meme04.jpg'
]))
```
] |
[Question]
[
Count the number of contiguous blocks within a given 3D input.
## Input
The input will consist of one or more rectangles of characters separated by blank lines. Each rectangle represents a cross section of the 3D space. The characters used will be `0`, representing empty space, and `1` representing a solid block.
**Example**
```
00000
01110
01110
01110
00000
01110
01110
01110
00000
01110
01110
01110
```
In the above example we have a 3x3 cube - the bottom layer first, then the middle and then the top.
## Output
The output should be a single integer giving the number of contiguous blocks within the input.
## What's considered contiguous?
If any two `1`s are adjacent to each other to the front, back, left, right, top or bottom, they are considered to be part of the same contiguous block. If they are not adjacent or they are only adjacent diagonally, they are not considered to be part of the same block.
**Examples**
```
00
11
```
Contiguous.
```
10
10
```
Contiguous.
```
10
01
```
Not contiguous.
```
01
00
01
00
```
Contiguous.
```
01
00
00
01
```
Not contiguous.
```
01
00
00
10
```
Not contiguous.
```
01
00
10
00
```
Not contiguous.
## Test inputs
```
11101110111
10000011100
00111000000
00000000000
Result: 1
111
111
111
000
010
000
111
111
111
Result: 1
111
111
111
100
000
000
101
011
111
Result: 2
11011011011
00100100100
11011011011
00100100100
00100100100
11011011011
00100100100
11011011011
Result: 14
11011011011
01100100110
11011011011
00100100100
00100100100
11011011011
00100100100
11011011011
Result: 12
11011011011
00100100100
11011011011
01100100110
00100100100
11011011011
00100100100
11011011011
Result: 10
11111
10001
10001
10001
11111
Result: 1
11111
10001
10101
10001
11111
Result: 2
11111
11111
11111
11111
11111
11111
10001
10001
10001
11111
11111
10001
10001
10001
11111
11111
10001
10001
10001
11111
11111
11111
11111
11111
11111
Result: 1
11111
11111
11111
11111
11111
11111
10001
10001
10001
11111
11111
10001
10101
10001
11111
11111
10001
10001
10001
11111
11111
11111
11111
11111
11111
Result: 2
11111
11111
11111
11111
11111
11111
10001
10001
10001
11111
11111
10001
10101
10001
11111
11111
10001
10101
10001
11111
11111
11111
11111
11111
11111
Result: 1
```
## Input format
I'm happy to be slightly flexible on the input format, so if you want to take a list of strings as input instead of one continuous string that's okay, and if you want to take a list of lists of characters (or integers if that helps) that's okay too.
Your answer can be a full program reading input or a function taking the input as a parameter. If your anonymous function needs a name in order for me to call it, then the characters for assigning the function to a name need to be counted too.
This is code golf so shortest code in bytes will win the big green tick, but any answer that meets the spec, passes the tests and has obviously been golfed will get my upvote.
[Answer]
# APL, 83 bytes
```
{0=⍴o←(,G)/Z←,⍳⍴G←⍵:0⋄1+∇G⊣{G[⊂⍵]←0⋄0=⍴A←G[A]/A←(A∊Z)/A←⍵∘+¨(+,-)↓∘.=⍨⍳3:⍬⋄∇¨A}⊃o}
```
Unlike some other languages, APL does not have a built-in for this (that I know of).
This function takes a 3-dimensional array of bits. It uses a 3-dimensional flood fill to remove blocks one by one, and counts how many blocks it can remove before the input is empty.
[Non-golfed version with comments here.](https://bitbucket.org/snippets/marinuso/M799G)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 30 bytes
`bwlabeln(...,6)` determines the 6-connected components of an n-dimensional array and outputs the number of components found as a second argument.
```
@(m){[~,N]=bwlabeln(m,6),N}{2}
```
[Try it online!](https://tio.run/nexus/octave#i1CwVUhOLNEw1lGINlQwVDBQQCOtDcA0Ghmrg1O1IZpqQ7BqrKZYYzWDNNUKsZrWCqoKOYnFJQolqcUlyYnFqf8dNHI1q6PrdPxibZPKcxKTUnPyNHJ1zDR1/GqrjWr/p2QWF2gk5hVrRGhq/gcA "Octave – TIO Nexus")
[Answer]
# Mathematica, 53 bytes
```
Max@MorphologicalComponents[#,CornerNeighbors->False]&
```
Unnamed function taking a 3D-array of integers. `MorphologicalComponents` is the builtin being exploited here: treating `0` as empty space, it separates the other integers into contiguous blocks, and assigns each block a number (starting from `1`, `2`, ...) and replaces all of its component entries by that number. So the number of blocks is just the maximum of all entries thus produced. Unfortunately, by default `MorphologicalComponents` counts diagonal neighbors as connected, so we need to add the option `CornerNeighbors->False` to fit the spec. (Side note: `MorphologicalComponents` is really built to operate on 2D and 3D images; but it handles arrays of integers as a side benefit.)
] |
[Question]
[
Given some code in your language as a string, find and display all the variable names.
Examples in pseudocode:
```
a=2
b=3
for(i, 0->9) do b=b-10
if a=b then write "a equals b"
```
Returns: `a b i`
```
abcdefgh=20000000000000
bcdifhgs="hello"
if abcdefgh=bcdifhgs then da44="hax"
if abcdefgh*2=da44 then write da44
```
Returns: `abcdefgh bcdifhgs da44`
```
2=3
3=5
5=7
if 2=7 then exit
```
Returns:
```
a=2
while True do b=3
```
Returns: `a b`
Shortest code wins.
For stack-based languages, display the highest height of the stack.
For memory cell based languages, display all the memory cells that have been changed.
[Answer]
## Python 3, ~~73~~ ~~66~~ 86
Now follows the updated test cases:
```
import sys
print(*set(compile(sys.argv[1],'','exec').co_names)-set(dir(__builtins__)))
```
Note that this also prints the names of non-builtin objects and methods / attributes of objects (e.g. if you use `sys.argv` in the input code it'll print `sys` and `argv`). Still, it does technically fit the test cases.
Assuming we're allowed to simply run the code, it can be done in 66 characters. Note that this fails the `while True` test case and, unlike the above solution, does not print things like `sys` and `argv`:
```
import sys
print(*(lambda:(exec(sys.argv[1]),set(locals())))()[1])
```
[Answer]
## Haskell, 2
```
[]
```
Only if you take the word "variable" literally.
[Answer]
# Ruby
Kind of cheating, I guess... If `code` contains Ruby code, then:
```
pre = global_variables
eval code
(global_variables - pre + local_variables + self.instance_variables - [:code, :pre]).each do |x|
puts x.to_s
end
```
Example:
`code = "a = 3; @b = 5; $c = 6, @@d = 10"`
Output:
```
$c
@b
```
*Works only with global and instance vars so far.*
# zsh
```
set > /tmp/set.1
eval $code
set > /tmp/set.2
diff -a /tmp/set.1 /tmp/set.2 | grep -vE "HISTCMD|LINENO|RANDOM|SECONDS|pipestatus" | grep -E ">[^=]+"
```
Example:
$code = `'zzz=3; xxx="hello"'`
Output
```
> xxx=hello
> zzz=3
```
# Clojure, 53
```
(pr(map #(last %)(re-seq #"\( *def +([a-z-])+"code))
```
Example:
```
user=> (def code "(def a 1) ( def b ( + 3 5 )))")
#'user/code
user=> (pr(map #(last %)(re-seq #"\( *def +([a-z-]+)"code)))
("a" "b")nil
user=>
```
[Answer]
## Python 104
```
import sys,re,keyword
print(set(re.findall(r"\b\w+\b",sys.argv[1]))-set(keyword.kwlist+dir(__builtins__)))
```
[Answer]
# HQ9+ (or H9+), 0
Is cheating allowed? In this case, the solution is a program of zero length, because the language has no variables, and has no memory cells, stack or any other form of storage. So it outputs nothing.
First I wanted to write Brainf\*ck, but then I realized the "memory cell" rule.
[Answer]
Python, 111
I am pretty new to code golf.. tips are appreciated, but here is an alternative approach
```
import ast as a
s=set()
v=a.NodeVisitor
v.visit_Name=lambda t,n:s.add(n.id)
v().visit(a.parse(input()))
print s
```
[Answer]
# MATLAB, 12
```
eval('<PROGRAM STRING HERE>');who
```
] |
[Question]
[
There is a mouse in a room, in the top-left corner. It can move up, down, left, or right, and the mouse cannot go through any cell in the room twice. Given this, return all the possible paths in which the mouse will visit every square.
**Input:** Two integers `m` and `n`, which represent the `m x n` room. m<9, n<9.
**Output:** The `m x n` room, with `^<>v` noting the direction the path goes. Each line of the room will be seperated by a newline, and each room will be seperated by one newline. The last room the mouse enters will be noted by a dot.
```
v > v .
v ^ v ^
> ^ > ^
next room goes here...
```
**Test Cases:**
Input: `2 3`, output:
```
v > v
> ^ .
> > v
. < <
v . <
> > ^
```
Shortest code wins.
[Answer]
### GolfScript, 146 137 characters
```
~:h\:w*:s(4\?,{[[0.]{\.4/\4%@[0$"<^v>"3$=]@2*)@[~2$3/+(\@3%+(\]@\}s(*[\;46]].{.0=.~0(>\0(>@~h<\w<&&&\0=~w*+*}%$s,={${1=}%h/n*n+n+}{;}if}%
```
The code shows a very direct implementation in GolfScript. Therefore, I suspect that there is plenty room for improvement. Be aware that the algorithm is really slow if you try it on anything larger than 3x3 or 2x4. I decided to put a `.` for the last position since any direction would be allowed there (the mouse already entered each cell and the last step is irrelevant).
Example:
```
> 2 4
>>>v
.<<<
v.<<
>>>^
v>>v
>^.<
v>v.
>^>^
```
*Edit:* Minor changes.
[Answer]
## Python, 296 269
With so many suggestions from others, I decided to make this a community solution. Tabs have been replaced with 4 spaces.
```
a=[-1,0,1,0];d='<^>v.'
def r(x,y):
if G.values().count(4)<2:
for i in n:print''.join(d[G[j,i]]for j in m)
print
for i in range(4):
X=x+a[i];Y=y+a[i-1]
if 4==G.get((X,Y)):G[x,y]=i;r(X,Y);G[X,Y]=4
m,n=map(range,input())
G=dict(((i,j),4)for i in m for j in n)
r(0,0)
```
**Example**
```
$ python paths.py
5,2
>>>>v
.<<<<
v>>>v
>^.<<
v>v>v
>^>^.
v>v.<
>^>>^
v.<<<
>>>>^
```
[Answer]
# Mathematica 347 315 chars
Very slow for all but the smallest arrays. This is because the solution is overly general, treating the paths as Hamiltonian Graphs rather than something more specific like a grid.
Anyway, here's the code:
```
Needs["Combinatorica`"]
p=ReplacePart;
q[l_,{},s_]:=p[s,l->"."]//Grid
q[l_, d_,s_]:=q[l+d[[1,1]], Rest@d,p[s,l:>d[[1,2]]]]
f[r_,c_]:=Column[q[{1,1},Differences[#]/.{-1-> {{0,-1},"<"},1-> {{0,1},">"},c-> {{1,0},"v"},-c-> {{-1,0},"^"}},ConstantArray[0,{r,c}]]&/@Cases[HamiltonianPath[GridGraph[c,r],All],{1,__}],Spacings->{0,3}]
```
Example (I reformatted the output into a table):
```
"4 4"
f@@ImportString[%,"Table"][[1]]
```

] |
[Question]
[
I have the code:
```
marks = tuple(tuple((input("Enter subject: "), input("Enter marks: "))) for _ in range(int(input("Enter number of tuples: "))))
print(tuple((s[:3].upper(), max(int(m) for t, m in marks if t == s)) for s in set(t for t, m in marks)))
```
```
#INPUT
(("Physics",131),("Chemistry",30),("Physics",100),("Computers",50),("Chemistry",20))
#OUTPUT
(('COM', 50), ('PHY', 131), ('CHE', 30))
```
As you can see, the output is a nested tuple of the first three capitalized letters of the subject and the maximum mark given for each subject.
You can assume that Physics, Chemistry and Computers are the only subjects that the user inputs, and that they always use the same spelling for the subjects.
The order of the subjects in the output does not matter.
Is there anyway I can do the same without using the max function? The length of the code should optimally be at 2 lines or if at all possible, a single line. The maximum limit of the number of lines of code is 3.
The solution should try to contain no built in functions if possible. Functions like sort(), sorted() and max() are strictly not allowed.
[Answer]
# 1 line, ~~180~~ ~~173~~ 171 bytes
*7 bytes saved thanks to Jonathan Allen*
```
exec("x={}\n"+"if x.get(a:=input('Enter subject: ')[:3].upper(),b:=int(input('Enter marks: ')))<=b:x[a]=b\n"*int(input("Enter number of tuples: "))+"print((*x.items(),))")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY9BTsMwEEX3PoVlFvW0EKVElVCEJaSKPfvSRdI6xIAdyx5LjhAnYZMNbDhRb4PTIJWK1Wj038z__-PL9th2Zhg-AzZXN4dvGeWOsyje3h8NWzDV0Jg9SeRVKZSxAfns3qB01If6We6wpDPYlMU2C9ZKx-GyHjnkZ6yu3IsfSYBbUZdxU21Fnd7PTySbSBN0nUbXUAz2VaYjBrBg1o0kn8dModQ-2QAw-I28v5jk4wXn_ixO8o5c06ZzFNNClZnS0FQMqRDUAxxVP0o-FcX_cMo9eQ2HuxV5aHuvdp4siyVZt1Irj64nRX4S8pysO51qSefJKv9DXefTox8)
# 3 lines, ~~171~~ ~~163~~ 160 bytes
*8 bytes saved thanks to Jonathan Allen*
```
x,i,e={},input,'Enter '
exec("if x.get(a:=i(e+'subject: ')[:3].upper(),b:=int(i(e+'marks: ')))<=b:x[a]=b\n"*int(i(e+"number of tuples: ")))
print((*x.items(),))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBSsQwEIbveYpQD03WWrqWBSkGhMW793UPbZ3aqElDMoEU8Um89KLvtG9j2nVR8Th8H_P_M--fZsR-0NP04bG7uDpMIZMZiNe3TGrjMUtvNYKlKYEALUtkR0P-CMjqSkgG56nzzRO0WNGU76pyn3tjwDKeNZFrZIujavvsZoPza9FUYVfvRXOvk9XJSLRXTUwZOorevECUkygTY2eDrUIuEZSLazn_7vlwdoSLz5j7E05VHZii3WApxoFKTZcONNZHKgR1nC_UzcjFc_C_zE9Z0-FmQ-760cnWkXW5JtselHRoR1IWP6AoyHZQ8WdgHdkUv6zL4rjoCw)
Here's another approach that yields fewer bytes. It can be done in 1, 2 or 3 lines, with more lines enabling shorter overall programs. There's probably still even some improvements to be made here.
[Answer]
# [Python](https://www.python.org), ~~204~~ 188 bytes
-16 bytes thanks to @WheatWizard
```
m=[*((input("Enter subject: "),int(input("Enter marks: ")))for _ in'*'*int(input("Enter number of tuples: ")))]
print((*((i[:3].upper(),j)for i,j in m if all(y!=i or z<=j for y,z in m)),))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZBNasMwEEb3OsU0XURj1OLUBEqIoBC67z6EkqQylmPJQj9Q5yrdeNOeohfJbSrZKW3ISqDvzfs0-vgyna9a3fefwZd3j6dvxdcZpVKb4OnkWXthwYVdLfZ-ARNkUvvLUG3twaUIsWwtvILU02yaXXE6qF082hJ8MI04j2yIsQmlqXO9KDb3wRhhKbJ60ElWRyEokCVsm4Z2N1xCvD8ueQ0J6NhxABAZ4nmHt9tROhRR6i688cHvVA2zniWxHldIDR44B4c4pC5FTkTNNYy_Xf3paU5eqs7JvSOzYkZWlVDSeduRIv8L8pysWhV_Q1hH5vk_6iEfRT8)
# [Python](https://www.python.org), 212 bytes
1 line
```
print((*[m:=[*((input("Enter subject: "),int(input("Enter marks: ")))for _ in range(int(input("Enter number of tuples: "))))]][:0],*((i[0][:3].upper(),i[1])for i in m if all(z[0]!=i[0]or z[1]<=i[1]for z in m)),))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDNSsQwFEb3eYrruLkZqqSWASkWhMG9-1KkM6Y22qQhP2D7Km660SdyM29j0o7oMKsEvnO_k5uPLz24tlfT9Oldc3V7-NZGKIe4LmVelGtEobR3uHpQjhuwfvfK9y6HFU0idhLK2rzZGFHa9AaeQCgwtXrheIYqL3fh6BtwXnf8OEWrqsxZlURrycI9q6691txgsJVpNdeKWCtBNFB3HY6BuygiHaIxMHdFJCM4ziClCaXH3Z4vl-VmJ6I9EYTnv6OEOOmSKFDLQtHkoCjAUjqnNkaWh5pzmP66psP9hjy2gxV7S9IsJduWS2GdGUjG_gLGyLaX4WO4sWTD_lE3bCn6AQ)
These are just some trivial golfs on your approach. It could probably be made much shorter. If there are ties this will print both.
] |
[Question]
[
In this game, you can look inside one box at a time chosen by you. When you do that, you can see how many coins there are in that box.
The wizard has one last twist for you. At any point, you can choose to give up on this set of boxes and get him to start the whole process again (with a new random \$x\$). Of course, if you have looked in all the 9 boxes and you still have not found 10 coins you have no choice but to give up and start again. But you might want to give up earlier too. Sadly you never get any money back so your costs just carry on building.
Your goal is to devise a strategy that will get you the wish at the minimum expected cost. You should report your mean cost.
# Testing
Once you have chosen your strategy, you should run it until you get the wish 10,000 times and report the mean cost. If two answers have the same strategy, the one posted first wins. If two strategies have similar mean costs you may need to test it 100,000 or even more times to tell the difference.
# Input and output
There is no input in this challenge. The output is just the mean cost to get a wish. To test your code you will need to implement both the wizard and your strategy.
[Answer]
# Python, cost = \$\frac{654510644704}{387420489}\$ = 1689.4063770179175
An optimal strategy, computed and evaluated exactly with [this code](https://tio.run/##vVTJbsIwEL3nK@ZoG1PiVpUapFz7Bb2hHAIxxSpZ5IQ2CPHtdGyHhJAE9VRfvMx7M561OFa7PHt5K/TlotIi1xWkcbXztjpPYavjTaXyrIRG9N48eN4mLysI2wcifMaE4BDg5lNg8CqE5/3s1F7Chz7IpQe4jiVyTvZoFmMnkhcykwkHZC2BGLV4prDNNTgRqAx0nH1KtEHPvEcOOAIPWWKoPgff8ezTGO3s2e1Ot/yWupQJceiA0mVrY0wbqO2VHYbgg9yX0v6@ZVlPOSRHdHZOnhlzcIof7GGMdnWjWcD86k4PZ/UJo1CgxmO5aszPQDT@41FFA06B6PKQkoHArDZzo1KzTB08bfJ0TeprmCex7BZ9dYODesRwXjBmsQ9wJECFTQgx69AZwF1RPkk1NVmPi8f/ZRJSdwlJ45rcRhgTKMSQSWHxf2H@c9CEPxW1f4rYVLSGpQ2zEGuVYY0PZEkrTO6kbRs05iIsdmPezQEOxHYgpa7lsWeRYETRyo9s43Y9ttYy/nI4O9bmYQ@86G7CNVmhVVZ1GV31PmZKYeRz4eMJRQeTYTD9cLh2qKjLkp2Z9kYvl18 "Python 3.8 (pre-release) – Try It Online") (which uses a similar Newton’s method search as a [comment of mine](https://codegolf.stackexchange.com/questions/250830/optimal-strategy-for-wandering-robots/250941#comment559237_250941) on your previous challenge, and is equivalent to [Nitrodon’s comment](https://codegolf.stackexchange.com/questions/251029/optimal-strategy-to-defeat-the-wizard#comment559291_251029) on this one).
```
import math
import random
def strategy(opened, found):
return found >= [0, 2, 3, 4, 5, 6, 7, 8, 9][opened]
count, mean, m2 = 0, 0.0, 0.0
for run in range(10000):
cost = 0
while True:
coins = [0] * 10
for i in range(random.randrange(1, 11)):
coins[random.randrange(10)] += 1
opened, found = 0, 0
while found != 10 and opened != 9 and strategy(opened, found):
found += coins[opened]
cost += 2**opened
opened += 1
if found == 10:
break
count += 1
delta = cost - mean
mean += delta / count
m2 += delta**2 * (1 - 1 / count)
mean_stdev = math.sqrt(m2 / (count * (count - 1)))
print(f"{mean} ± {mean_stdev}")
```
[Try it online!](https://tio.run/##fVJbboMwEPz3Kab5wtRJgPSVSvQU/YuiigaToAZDjWkVRT1Ur9CLpWvMQ6hS/WHWOzuz4zXVyRxKtZpXp@p0ueRFVWqDIjEH1sU6UWlZMJbKDLXRiZH7k1dWUslUICsblfJHBlpamkYrl8JTjE0gEAmsBG4EbgXuBO4FHgTW243jbxnbUbURKGSiaI8Qg1jBwm2MZaWGbhRyZX3spRcGtLqGu7I2lsDa0@chP0o860Y61FXkqoa1soWPMBgAq5uPqu6OC/vp2giEIeej0qC2@Vsb8C2uY4RsqJ6Mp7vTADqjDroiWgCS6ig2sW7P/456vIYVod7OWj/VqWkaElVEvu/gCdp1bd33uTzrfVtz04avWiZvrJs@vdzITOXRJIhdv3n7oG3eBrbK4UtHc0g05H0/ovfxQiKGfQ1nzHJfapPKDxK2/@SiftfGI@ISnuvv9wExOees0rkyXjY7W@4Xfr5xHlW@Zvxy@QU "Python 3 (PyPy) – Try It Online")
[Answer]
# R / Rcpp: 1688.758 ± 0.740
Evaluated on 15 million simulated games. Error values are a bootstrap confidence interval with 10,000 iterations. The learned policy matches Anders' optimal policy.
## Method
The policy to minimize cost was learned using double n-step SARSA, a reinforcement learning algorithm. The optimal policy was learned by training 15 agents in parallel, where each agent's current policy was replaced by the average of all agents' policies every 100,000 actions. The optimal policy was found in about 4.5e8 actions, or ~150,000 epsiodes at 3000 actions per episode.
The algorithm's learning parameters were set as follows: discount factor `gamma = 0.17258`, learning rate `alpha = 0.3904111`, and epsilon-greedy action selection `epsilon = 0.2702468`. I originally wrote the algorithm as an n-step SARSA but settled on `n = 1`. The learning parameters were found using model-based Bayesian optimization. I used 105 points for the initial design and searched 50 sequentially proposed points.
### Reward Shaping
When reaching a new state by opening a box, the agent's reward was the sum of the value of the found coins, where coin `n` is worth \$2^{n-1}\$, minus the cost of the opened box. When giving up the set of boxes and starting over, the agent's reward was the negative sum of the value of the coins it had found during the episode if the episode was possible to have won; otherwise, the agent's reward was zero. In all cases a constant reward of `-1` was applied.
## Learned Policy
The below photo shows the policy learned by the agent. A black square indicates that if the agent has collected the corresponding number of coins by opening that many boxes, it will continue to open boxes. Otherwise, the agent will give up the set of boxes.
[](https://i.stack.imgur.com/xgjyu.jpg)
## Code
**R code to initialize the state-action space**
```
#' Initialize the State-Action Space
initStateSpace <- function(){
#Generate full grid
space = expand.grid(
numOpenBox = 0:9,
numCoins = 0:10,
act = c(0:1)
)
#Remove states where no boxes are open, but positive coins found
inds = (space$numOpenBox == 0) & (space$numCoins > 0)
space = space[!inds,]
#Remove states where all boxes are open, but action is open box
inds = (space$numOpenBox == 9) & (space$act == 1)
space = space[!inds,]
#Add columns for value
space$valueA = 0
space$valueB = 0
#Return
return(as.matrix(space))
}
```
**Rcpp code for the algorithm, simulation, and evaluation**
Note: Because the episode is cyclical, I opted not to handle updating the state-action values for pairs within n steps of the terminal state.
```
#include <Rcpp.h>
using namespace Rcpp;
//* Place Coins in Boxes
// [[Rcpp::export]]
NumericVector setCoins() {
//Sample number of coins
NumericVector coinSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
NumericVector boxSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
NumericVector nCoins = Rcpp::sample(coinSet, 1);
NumericVector boxInds = Rcpp::sample(boxSet, nCoins[0], true);
//Assign coins to boxes
NumericVector out (10);
for(int i = 0; i < 10; i++){
for(int j = 0; j < boxInds.length(); j++){
if(i == boxInds[j] - 1){
out[i] = out[i] + 1;
}
}
}
//Return
return(out);
}
//* Subset State-Action Space by State
// [[Rcpp::export]]
NumericMatrix subsetSpace(
NumericVector state,
NumericMatrix stateSpace
) {
//Find rows that match the input state
LogicalVector inds (stateSpace.nrow(), false);
for(int i = 0; i < inds.length(); i++){
if(stateSpace(i, 0) == state[0] & stateSpace(i, 1) == state[1]){
inds[i] = true;
}
}
//Subset the state-action space to the input state
NumericMatrix out(sum(inds), stateSpace.ncol());
for(int i = 0, j = 0; i < inds.length(); i++){
if(inds[i]){
out(j, _) = stateSpace(i, _);
j = j + 1;
}
}
//Return
return(out);
}
//* Choose action
// [[Rcpp::export]]
double chooseAction(
NumericVector state,
NumericMatrix stateSpace,
double epsilon
) {
//Subset state-action space to input state
NumericMatrix localSpace = subsetSpace(state, stateSpace);
//Epsilon-greedy action selection
double action;
if(Rcpp::runif(1, 0.0, 1.0)[0] <= epsilon){
IntegerVector actionSet = Rcpp::seq(0, localSpace.nrow() - 1);
IntegerVector actionInd = Rcpp::sample(actionSet, 1);
action = localSpace(actionInd[0], 2);
} else {
NumericVector value = (localSpace(_, 3) + localSpace(_, 4)) / 2;
int actionInd = Rcpp::which_max(value);
action = localSpace(actionInd, 2);
}
//Return
return(action);
}
//* Calculate Reward
// [[Rcpp::export]]
double calculateReward(NumericVector state, NumericVector boxState) {
double reward = 0;
int openBoxes = state[0];
int coinsFound;
if(state[2] == 1) {
//Reward for opening box is value of coins found minus cost of box
coinsFound = boxState[openBoxes];
reward += -pow(2, openBoxes);
for(int j = 0; j < coinsFound; j++){
reward += pow(2, state[1] + j);
}
} else {
//Reward for shuffling is regret if the game was possible to complete
if(sum(boxState) == 10 & boxState[9] == 0) {
for(int j = 0; j < state[1]; j++){
reward += -pow(2, j);
}
}
}
//Constant negative reward
reward += -1;
//Return
return(reward);
}
//* Take Action
// [[Rcpp::export]]
NumericVector takeAction(NumericVector state, NumericVector boxState) {
double reward = calculateReward(state, boxState);
if(state[2] == 1) {
int openBoxes = state[0];
state[0] = state[0] + 1;
state[1] = state[1] + boxState[openBoxes];
state[2] = -1;
state[3] = reward;
} else {
state = {0, 0, 1, reward};
}
return(state);
}
//* Find State-Action Index
// [[Rcpp::export]]
int findStateIndex(
NumericVector state,
NumericMatrix stateSpace
) {
int index = NA_INTEGER;
for(int i = 0; i < stateSpace.nrow(); i++){
if(stateSpace(i, 0) == state[0] & stateSpace(i, 1) == state[1] & stateSpace(i, 2) == state[2]){
index = i;
break;
}
}
return(index);
}
//* Create Record
// [[Rcpp::export]]
NumericMatrix createRecord(int n) {
NumericVector v (2 * (n + 1), -1.0);
return(NumericMatrix (n + 1, 2, v.begin()));
}
//* Copy State to Record
// [[Rcpp::export]]
NumericMatrix copyToRecord(
NumericVector state,
NumericMatrix stateSpace,
NumericMatrix record
) {
//Find index of state-action pair
int pairInd = findStateIndex(state, stateSpace);
//Write to first open index if possible
bool openSlot = false;
for(int i = 0; i < record.nrow(); i++){
if(record(i, 0) == -1){
record(i, 0) = pairInd;
record(i, 1) = state[3];
openSlot = true;
break;
}
}
//Otherwise, shift down and write
if(!openSlot){
for(int i = 1; i < record.nrow(); i++){
record(i - 1, 0) = record(i, 0);
record(i - 1, 1) = record(i, 1);
}
record(record.nrow() - 1, 0) = pairInd;
record(record.nrow() - 1, 1) = state[3];
}
//Return
return(record);
}
//* Calculate Return
// [[Rcpp::export]]
double calculateReturn(
NumericMatrix record,
double gamma
) {
double g = 0;
for(int i = 1; i < record.nrow(); i++){
g = g + pow(gamma, i - 1) * record(i, 1);
}
return(g);
}
//* Update State-Action Value
// [[Rcpp::export]]
NumericMatrix updateStAcValue(
NumericMatrix record,
NumericMatrix stateSpace,
double gamma,
double alpha
) {
//Double SARSA
//Randomly select A or B values to update
IntegerVector vSet = {0, 1};
vSet = Rcpp::sample(vSet, 1);
vSet.push_back(1 - vSet[0]);
//Shift vSet to match value column numbers
vSet = vSet + 3;
//Update state-action value
int n = record.nrow() - 1;
double G = calculateReturn(record, gamma);
G = G + pow(gamma, n) * stateSpace(record(n, 0), vSet[0]);
stateSpace(record(0, 0), vSet[1]) += alpha * (G - stateSpace(record(0, 0), vSet[1]));
//Return
return(stateSpace);
}
//* Learn Policy
// [[Rcpp::export]]
NumericMatrix learnPolicy(
NumericMatrix stateSpace,
double gamma,
double alpha,
double epsilon,
int n,
int iters
) {
//Loop episodes
int i = 0;
while(true){
//Initialize n-step Sarsa
NumericMatrix record = createRecord(n);
NumericVector boxState = setCoins();
NumericVector state = {0, 0, 1, 0};
//Record initial state
record(0, 0) = findStateIndex(state, stateSpace);
//Complete episode
double t = 0;
double tau = 0;
double T = R_PosInf;
bool done = false;
while(!done) {
//Take action
if(state[2] == 1){
state = takeAction(state, boxState);
state[2] = chooseAction(state, stateSpace, epsilon);
} else if(state[2] == 0) {
state = takeAction(state, boxState);
boxState = setCoins();
}
//Update record
record = copyToRecord(state, stateSpace, record);
//Update state-action values
tau = t - n + 1;
if(tau >= 0){
stateSpace = updateStAcValue(record, stateSpace, gamma, alpha);
}
//Complete
t = t + 1;
if(state[1] == 10){
done = true;
}
//Break loop when all iterations are complete
i += 1;
if(i >= iters){
break;
}
}
//Break loop when all iterations are complete
if(i >= iters){
break;
}
}
//Return
return(stateSpace);
}
//* Evaluate Policy
// [[Rcpp::export]]
NumericVector evaluatePolicy(
NumericMatrix stateSpace,
int iters
) {
NumericVector out (iters, 0.0);
for(int i = 0; i < iters; i++){
NumericVector boxState = setCoins();
NumericVector state = {0, 0, 1, 0};
bool done = false;
while(!done) {
if(state[2] == 1){
out[i] += pow(2, state[0]);
state = takeAction(state, boxState);
state[2] = chooseAction(state, stateSpace, 0.0);
} else if(state[2] == 0) {
state = {0, 0, 1, 0};
boxState = setCoins();
}
if(state[1] == 10){
done = true;
}
}
}
return(out);
}
```
**R code to learn and evaluate policy**
Learning parameters found using Model-Based Bayesian Optimization
```
#Create a policy by parallel RL
#Learns the optimal policy in 4.5e8 actions over 15 agents
#Or ~150,000 episodes total at 3000 actions per episode
#Agents replace their policies with the average policy every 100,000 actions
numAgents = 15
for(i in 1:300){
#Generate initial policies
if(i == 1){
policy = lapply(1:numAgents, function(c){
learnPolicy(
initStateSpace(),
n = 1,
gamma = 0.17258,
alpha = 0.3904111,
epsilon = 0.2702468,
iters = 1500000 / numAgents
)
})
policy = Reduce("+", policy) / numAgents
} else {
#Use the average of the initial policies to seed new agents
policy = lapply(1:numAgents, function(c){
learnPolicy(
policy,
n = 1,
gamma = 0.17258,
alpha = 0.3904111,
epsilon = 0.2702468,
iters = 1500000 / numAgents
)
})
policy = Reduce("+", policy) / numAgents
}
}
#Evaluate policy over 15mil episodes
summary(evaluatePolicy(policy, 15000000))
```
] |
[Question]
[
Mahjong is a tabletop game played using tiles. It features three "number" suits (pins, sous, mans, represented as `p`, `s` and `m`) from 1 to 9, and one "honor" suit `z` of seven distinct tiles. Note that contrary to western card games, tiles are not unique.
[](https://i.stack.imgur.com/gloVn.png)
To complete a hand and win, the 13 tiles in your hand are combined with 1 newly drawn tile and must result in one of the following winning configurations:
* 4 sets and 1 pair, self-explanatory
* seven pairs, where all pairs are distinct (twice the same pair wouldn't qualify)
* kokushi musou: one of each of the 1 and 9 of each number suit, one of every seven honors, the remaining tile forming a pair (e.g. `19m19p19s11234567z`)
A pair is any of the two same tiles: `11m`, `33s`, `44p`, `55z`, etc.
A set consists of 3 tiles of the same suit. It can either be a run: 3 number tiles (p, s or m) in a connected run like `123s` or `234s`, but not `1m 2p 3s` or `234z`; or a triplet of any suit, not necessarily numbers, like `111z`, `222m`.
So honor tiles (non-numbers, represented by `z`) can only form pairs or triplets, but not runs. `567z` is not a set, `555z` is a valid set, `55z` is a valid pair.
A single tile can only be counted as part of one set or pair: there is no sharing or reusing.
Given a sorted hand of 13 tiles and one tile, check whether the 14 tiles make up a completed hand.
## Input & Output
* You are given a sequence of numbers and letters, a space, then a tile of a number and a letter
* Output `True`/`1` if the set is a match, else `False`/`0`
## Others:
* You are allowed to input the sequence and tile+letter as a list/array
## Test Cases:
Truthy
```
222888m444p2277z 7z
234m45789p45688s 6p
11m4477p8899s116z 6z
19m19p19s1234567z 6z
123345567789m3p 3p
```
Falsey
```
1122335778899m 1m
888m55s11222333z 4z
234m2233445566p 4p
19m139p19s123567z 4z
11m4477p8899s666z 6z
```
Credits to Unihedron for the [puzzle](https://www.codingame.com/ide/puzzle/completed-mahjong-hands)!
## Scoring
This is code-golf, so shortest code wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~248~~ ~~246~~ 245 bytes
```
s=>s.sort().every((t,i)=>t==s[i^1]&t!=s[n=12,i+2])|A(s)|[...new Set(s)].length>n
A=y=>y.some(t=>R(y,t,t,t)|t[n+=t>'2'&t<'9'&t[1]<A,1]<A&R(y,t,t[0]-1+t[1],t[0]-2+t[1]))|y[0]==y[1]&!y[2]
R=(s,p,q,r,z=0,k=s.filter(y=>y!=p||z++))=>p?z&&R(k,q,r):A(s)
```
[Try it online!](https://tio.run/##VVDbjpswEH3nK5wXsAXrjc29u6bKSz9g95HSCCVOli4QBzupoOy3Z8ekVVVZGs2ZOWfOeH7W11rvhkaZh/60l7eDuGlRaKpPg8GEyqscRoxN0BBRGCF02fxglWtWkPWC8aDxeUXmDdZkLimlvfyFXqUBWNFW9kfzVvTORoyiGGFkJ7ERxQseA2MfmU3Z@8IUHvdc8@zlEEtWPW8CG9w/vHJdPTDfNu45X3JC5hGQECMAdzWWvHJeBNaBCs7BEExiHbwLTQ9Na@SArf9KqHmefJ/AT9TXyYX575ZLvtjtb0/OIM@XZpDYO2iP0EHW@29NK1/HfofXgXcxh2wpq7beSfxI/cdjAKf67SB0rQdkkEBl9QRI/yPh73ufYEqAivDW7kbuCoTstVRFu1rhLZyWqot@w1v/TIid8bHE3anXp1bS9nSEnx2wsc0PcuOcZ1nWRVGkOE/TCaWTw8Ooi@I0y1UUJ1mmUaIcxoCTpirL8lwzlkwomRyWdyxXDAogiZP0XuQhAEAwoAsVCq2YQzGGCqg7xDrHesaxtg3ohBOK7rYWRVadKBSpxSD867AYAO@/VZJkWeUT "JavaScript (Node.js) – Try It Online")
Every answer is in js...
`f` is the main function, relying on `A` modifying `n` for non-1919191234567 check
`A` check if it's 3+3+3+3+2
`R` removes some triplet and go on `A`ing
[Answer]
# Javascript (SpiderMonkey), 807 bytes
```
[a,[b,c]]=readline(j=m=0).split` `
d=[...h='mpsz'].map(k=>!~(i=a.indexOf(k))?'':a.slice([j,j=i+1][0],i))
d[i=h.indexOf(c)]=[...d[i]].concat(b).sort().join``
if(~(''+d).search`(1+9+,){3}1+2+3+4+5+6+7`|d.every(k=>/^(?:(.)\1(?!\1))*$/.test(k)))print(1);else A:{a=/(.)(\1*)/g;e=d.pop();while(n=a.exec(e))if(!n[2]){print(0);break A}else if(n[2].length==1)if(m){print(0);break A}else m=1
f=l=>{if(!l.length)return;var[h,n,b]=l;if((a=n-h)>1)return 1;i=l.indexOf(+n+1);if(a==1)return!~i?1:f(l.slice(2,i)+l.slice(i+1));if(~i){c=l.slice(1,i)+l.slice(i+1,i=l.indexOf(+n+2))+l.slice(i+1);if(~i&&!f(c))return}return n-b||f(l.slice(3))};m=d.filter(k=>{if(!(c=k.length%3))return f(k);else if(c==2){r=/(.)\1/g;while(n=r.exec(k))if(!f(k.slice(0,n.index)+k.slice(r.lastIndex)))return m=1,0}return 1}).length?0:m
print(m?1:0)}
```
[Try it online!](https://tio.run/##dVJdj9owEHznVwSpvXjPwcSBFkpk0D32qT8gpMIk5mJwTOSk9I6vv04dklD1pD56d3ZmdsdbfuBlYmRRDcpCpsLke70T77dbxL1o7SVxzIzgqZJaoC3LmQ@kLJSsVs6ql7KIEJIxNy/KoxuTnBdox@b9K5KME6lT8fZjg3YAC9edcVIqmQgUbb0tk5jGkR97EqCXRpJlD3QC8Z3VVuOYJHud8AqtrejeVAjIdi/1atWTG3RFrotT2xDcJNkKUfwNe3AaXSgO8AiP8Rf8FU9W55SIgzDvtbHhT7SYIQJLihb9JQV4/jQklSir2iMURuoKUQiFKoXzMjtxNrRgtKTPMHwNBUtJsS8QhL8zqQTSdkXxJhIkAKydvo6CGE4NiQ/h2l5t57xc7mS2X7eJEvq1yhij9UT@P3TOaG/DFJufal7VToER1S@jwwM3UeZpbx0zFVoA4kwPMpjTFuDQUDL1uCfW2K5kcbyWbSD9q1zQ2QapNpLA5oC7h40G7gNXCaeEdWX6AeN9EAngX4qG4empX0fa6l5ah3qwPp//yo8ALmFuz7uRqhKmTuq@OUrYrl3@86jjcOoPFXZXTRgL4GTuQS2pTanLxjTZ7Jps7Eyr5Xu6cQ24KxmieFl9vxcfKjYDz@/80gu0Phb@LO81qeX2hD5cbrcgCKbTaT4ej4sgmEyOzuTY@wM)
First js post!
[Answer]
# JavaScript, 348 bytes
```
a=>[[(P=f=>w=>f(w)&&1-w.some((n,i)=>n>1&!f(W=[...w],W[i]-=2))/2)(w=>w.some(n=>([p,q]=[q,(n-p-q)%3],1/q<0),p=q=0)),P(w=>w.some(n=>n%3)),],[w=>w.some(n=>n&-3)],[w=>w.some((n,i)=>i%8==1^n>0),w=>w.some((n,i)=>0<i&i<8^n>0)]].some(([i,I=i])=>i(n`m`)+i(n`p`)+i(n`s`)+I(n`z`)<1,n=t=>[...a.matchAll(`\\d(?=\\d*${t})`)].map(i=>s[i]++,s=Array(12).fill(0))&&s)
```
Passed all testcases. Though it may still be buggy. Comment any failed testcases, and I will try to fix them.
```
a=>[[
// given count of each tiles in same suit
// return 1 if it is not a valid hand
// return 0.5 if it is a valid hand with a pair
// return 0 if it is a valid hand without a pair
(P=f=>w=>f(w)&&1-w.some((n,i)=>n>1&!f(W=[...w],W[i]-=2))/2)
// for m, p, s
(w=>w.some(n=>([p,q]=[q,(n-p-q)%3],1/q<0),p=q=0)),
// for z
P(w=>w.some(n=>n%3)),
],[
// for 7 pairs rule
w=>w.some(n=>n&-3)
],[
// for 13 orphan rule
w=>w.some((n,i)=>i%8==1^n>0),
w=>w.some((n,i)=>0<i&i<8^n>0)
]].some(([i,I=i])=>i(n`m`)+i(n`p`)+i(n`s`)+I(n`z`)<1,
// Parse `112233456666m` -> `[0, 2, 2, 2, 1, 1, 4, 0, 0, 0, 0, 0]`
n=t=>[...a.matchAll(`\\d(?=\\d*${t})`)].map(i=>s[i]++,s=Array(12).fill(0))&&s
);
```
] |
[Question]
[
I was wondering if there is any way to assign 2 values (G and H) to say a list of ["egg", "chicken"] in Pyth. In python it would be something along the lines of
```
G, H = ["egg", "chicken"]
```
At the moment the shortest way I can think of would be something like
```
=N["egg""chicken")=G@N0=H@N1
```
which uses the lookup function to index the list and store each one individually. I tried doing something like
```
=(G H)["egg""chicken")
```
but when I look at the debug info [Pyth debug info](https://pyth.herokuapp.com/?code=%3D%28G%20H%29%5B%22egg%22%22chicken%22&debug=1) it doesn't seem to be what im after. Any help would be good thanks. This may include shortening the original solution or giving me an explanation on how to do the tuple assignment
[Answer]
This is exactly what the `A` builtin does: “Assign the first value of the list to G and the second to H. Return the input.”
```
A["egg""chicken")
```
] |
[Question]
[
**This question already has answers here**:
[Stackable sequences](/questions/144201/stackable-sequences)
(27 answers)
Closed 2 years ago.
Related: [What's my telephone number?](https://codegolf.stackexchange.com/q/198237) which asks to calculate the terms of [A000085](https://oeis.org/A000085), the number of possible ordinal transforms of length n.
## Background
**[Ordinal transform](https://oeis.org/wiki/Ordinal_transform)** is a transformation on an integer sequence. For a sequence \$a=(a\_0, a\_1, a\_2, \cdots)\$, the \$n\$-th term of the ordinal transform \$ord(a)\_n\$ is defined as the occurrence count of \$a\_n\$ in \$a\_0, a\_1, \cdots, a\_n\$. Informally, \$ord(a)\$ can be described as "the value \$a\_n\$ appears the \$ord(a)\_n\$-th time in the sequence \$a\$".
For example, the sequence `[1, 2, 1, 1, 3, 2, 2, 3, 1]` transforms into `[1, 1, 2, 3, 1, 2, 3, 2, 4]`.
```
1, 2, 1, 1, 3, 2, 2, 3, 1
1, 1, 2, 3, 1, 2, 3, 2, 4
^ ^ ^ ^
| | | 4th occurrence of 1
| | 3rd occurrence of 1
| 2nd occurrence of 1
1st occurrence of 1
```
The number of possible ordinal transforms is [A000085](https://oeis.org/A000085). A hint to tackle this problem can be found on the page (search for "ballot sequences").
## Challenge
Given a non-empty finite integer sequence, test if it can be the result of ordinal transform of some integer sequence.
You can assume the input entirely consists of positive integers.
For output, you can choose to
1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
**Truthy**
```
[1]
[1, 1]
[1, 2, 3, 1]
[1, 1, 2, 2]
[1, 2, 1, 2, 1, 2, 1]
[1, 2, 3, 4, 5, 6, 7]
[1, 1, 2, 3, 1, 2, 3, 2, 4]
[1, 1, 2, 3, 4, 2, 1, 3, 2, 1]
```
**Falsy**
```
[2]
[6]
[1, 3]
[2, 1, 1]
[1, 2, 2, 1]
[1, 2, 3, 2]
[1, 2, 3, 4, 4]
[1, 2, 3, 2, 1]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
Ṭ€+\I’Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8///hzjWPmtZox3g@aph5Ytn/w@1HJz3cOUMFKAZE7v//R0dzRRvG6gAJHQUYbaSjYIzgQQSMEHIoJIoWEx0FUx0FMx0FcxS9xkgMIGmCLmkCM9AYbmasDtBdYDvNoKqNQTREGZKlGE4wQneQCao0VL25DkhhbCwA "Jelly – Try It Online")
-1 byte [thanks to](https://codegolf.stackexchange.com/questions/231386/is-this-an-ordinal-transform/231388?noredirect=1#comment530224_231388) [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
Outputs an empty array (falsey) if it can be the result, and a non-empty array (truthy) if not.
## How it works
```
Ṭ€+\I’Ȧ - Main link. Takes a list L on the left
€ - For each integer I in L:
Ṭ - Untruth; Generate a list of zeroes of length I, replace the last with 1
\ - Scan by:
+ - Addition
I - Get the forward differences of each
’ - Decrement
Ȧ - This array does not contain any 0s
```
For exactly what this does, let's look at this step by step:
| Command | Truthy example | Falsey example |
| --- | --- | --- |
| Start | `[1, 2, 3, 1]` | `[1, 2, 3, 2]` |
| `Ṭ€` | `[[1], [0, 1], [0, 0, 1], [1]]` | `[[1], [0, 1], [0, 0, 1], [0, 1]]` |
| `+\` | `[[1], [1]+[0,1], [1]+[0,1]+[0,0,1], [1]+[0,1]+[0,0,1]+[1]]` `[[1], [1,1], [1,1,1], [2,1,1]]` | `[[1], [1]+[0,1], [1]+[0,1]+[0,0,1], [1]+[0,1]+[0,0,1]+[0,1]]` `[[1], [1,1], [1,1,1], [1,2,1]]` |
At this point, we have running counts of each element. The `i`th element of `Ṭ€+\` is a list `[a,b,c,...,z]` where `a` is the number of counts of `1` in the first `i` elements of the input, `b` the counts of `2` and so on. The input is only truthy if each list is ordered descendingly.
In order to do this, we get the forward differences of each. This will be a list of lists of `-1`, `1` and `0`. If any of the differences have `1`, then it's ascending. We then decrement, mapping `1` to `0` and everything else to a non-zero element. Finally, we check with `Ȧ` that there are no zeroes in the list at any level.
[Answer]
# JavaScript (ES6), 40 bytes
```
a=>a.every(n=>a[a[~n]=-~a[~n],-n]--|n<2)
```
[Try it online!](https://tio.run/##ZU/LDoIwELz3K/ZIk5bEFvGA5eZXNBwaLD5iWkMbEqPy64ggTy8z253Zne5VVcrl5eXuqbFH3RSiUSJVoa50@QhMW0ola5MJWndMqMkofZk9w43XzufKaQcCJJKbjLRAYGBGgE@vvsEmbYGLkYjAlkBMYLeY5bOixWgtRsNCPu5EsguMf1b@5d4zS/zLZ@vfREu592dovD8sbHlQ@TnwIFJ4IoDcGmdvOrzZU1AEHuMEvXHSfAA "JavaScript (Node.js) – Try It Online")
Ungolfed:
```
arr => {
const count = [Infinity]
for (let i = 0; i < arr.length; i++) {
const num = arr[i];
count[num] = (count[num] || 0) + 1;
count[num - 1] = (count[num - 1] || 0) - 1;
if (count[num - 1] < 0) {
return false;
}
}
return true;
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
~~Quite exhausted so I'm sure I'll improve upon it in the morn'. Less sure that it's actually correct so, mods, please delete if it's not.~~ Shockingly, it *was* correct! Haven't been able to improve much on my score, though.
```
e1g2Æ=¡YôgU è¶X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZTFnMsY9oVn0Z1Ug6LZY&input=WzEsIDEsIDIsIDMsIDQsIDIsIDEsIDMsIDIsIDFd) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZTFnMsY9oVn0Z1Ug6LZY&input=WwpbMV0KWzEsIDFdClsxLCAyLCAzLCAxXQpbMSwgMSwgMiwgMl0KWzEsIDIsIDEsIDIsIDEsIDIsIDFdClsxLCAyLCAzLCA0LCA1LCA2LCA3XQpbMSwgMSwgMiwgMywgMSwgMiwgMywgMiwgNF0KWzEsIDEsIDIsIDMsIDQsIDIsIDEsIDMsIDIsIDFdClsyXQpbNl0KWzEsIDNdClsyLCAxLCAxXQpbMSwgMiwgMiwgMV0KWzEsIDIsIDMsIDJdClsxLCAyLCAzLCA0LCA0XQpbMSwgMiwgMywgMiwgMV0KXS1tUg)
] |
[Question]
[
This challenge is about [Haskell](https://en.wikipedia.org/wiki/Haskell_(programming_language)) [point-free style](https://en.wikipedia.org/wiki/Tacit_programming) polynomial functions.
Although you **don't** need to know Haskell language to do this challenge, Haskellers might have an advantage here.
Point-free means roughly that variables(points) are not named and the function is created from compositions of others functions.
For example, in Haskell, the function `f : x->x+1` can be defined by:
`f x = x+1` which uses the variable `x` and is not point-free. But it can be simplified to its point-free version: `f=(+1)`. Likewise, you have `f x=x^k` -> `f=(^k)`, and `f x=x*k` -> `f=(*k)`, `f x y=x*y` -> `f=(*)`
More complex functions can be constructed using the Haskell's [function composition](https://en.wikipedia.org/wiki/Function_composition) operator `(.)`:
`f x = x->2*x+1` is converted to `f = (+1).(*2)`: Multiply by 2 then add 1.
In this challenge you will have to create a point-free style Haskell code generator.
This generator will take a polynomial function of multiple variables as input and output corresponding code in Haskell language and in point-free style.
This is way harder than the previous simple functions, so if you don't know Haskell at all, or if you are not comfortable with operators `(.)`, `(>>=)`, `(<*>)` on functions, You should follow the **Construction Process** which is detailled bellow or start directly from its **Python Implementation**.
## Example
Say you want to write the polynomial function `x, y -> x²+xy+1` point-free.
Your program might output the folowing code:
```
((<*>).(.)((<*>).(.)(+))) -- sum 2 functions of 2 variables
(
((<*>).(.)((<*>).(.)(+))) -- sum 2 functions of 2 variables
(
(
((.)((.(^0)).(*))) -- g x y = y^0 * f x => g x y = x^2
(((.(^2)).(*))(1)) -- f x = 1*x^2
)
)
(
((.)((.(^1)).(*))) -- g x y = y^1 * f x => g x y = x*y
(((.(^1)).(*))(1)) -- f x = 1*x^1
)
)
(
((.)((.(^0)).(*))) -- g x y = y^0 * f x => g x y=1
(((.(^0)).(*))(1)) -- f x = 1*x^0
)
```
This is a really ugly yet valid Haskell code, and this is really not the shortest one (`(.).(.)(+1).(*)<*>(+)` works as well), but we will see how it can be generalized to any multivariable polynomial.
## Construction Process:
One possible algorithm is to first write each monomial function in point-free style (step 1), then create operators to add functions two at a time (step 2), and apply this to the list of monomials, writing `f+g+h` as `(f+(g+h))` (step 3).
1. Write each monomial, taking each of the factors successively. Example: `11*a^12*b^13*c^14`.
* Start with `(11)`, a 0-argument function.
* Take the previous function `f0` and write `((.(^12)).(*))(f0)`; this is a 1-argument function `a->11*a^12`
* Take the previous function `f1` and write `((.)((.(^13)).(*)))(f1)`; this is a 2-argument function `a->b->11*a^12*b^13`.
* Finally, take the previous function `f2` and write `((.)((.)((.(^14)).(*))))(f2)`. Thus `a->b->c->11*a^12*b^13*c^14` is converted to point-free style as `((.)((.)((.(^14)).(*))))(((.)((.(^13)).(*)))(((.(^12)).(*))(11)))`.
* In general, continue transforming `f` to something of the form `((.) ((.) ((.) ... ((.(^k)).(*)) ))) (f)` until your monomial is built and takes the desired number of arguments.
* Warning: If using this construction algorithm, each monomial must take the same number of arguments. Add some `^0` for missing variables (`a^2*c^3` -> `a^2*b^0*c^3`)
* You can test your monomial generator here with this example and the next iteration: [Try it online!](https://tio.run/##nZHLDoIwEEX3/YpZmPSxIPTBkl8xKWAjEdGo/18H2qIUFsaumHPv3GHas31eTsPgvSuhBiYlJ05OX6xgR6k4L5jgPHAVOA@ajhqWGy@a9cccG0xqmDt@ScEYs46JXdUStWT9P4QT4koK6dQgJd4BBfsFhMUuvIGJNmsqGhyA@wap3Uiixb/CRZLe7emiw6UIudp@RLm7kWnE/dGPLzgAPk1W03UtAVRGaE4UekBnjG6Znn1gMkr3qIleqDJOE/f@DQ "Haskell – Try It Online")
2. Create the operator \$O\_n\$ that adds two functions of \$n\$ arguments:
* \$O\_0\$ is `(+)`
* For \$n\geq0\$, \$O\_{n+1}\$ can be constructed recursively as `((<*>).(.)( O_n ))`
* E.g. `((<*>).(.)(((<*>).(.)(+))))` adds two 2-argument functions.
3. Chain the addition: The operator from step 2 only adds two monomials, so we must manually fold addition. For example, for monomials f, g, h, write `f+g+h` => `O_n(f)( O_n(g)( h ) )` replacing f, g, and h with their point-free equivalents from step 1, and \$O\_n\$ by the correct operator from step 2 depending on the number of variables.
## Implementation in Python
This is an ungolfed implementation in Python 3 which reads polynomials as list of monomials where monomial is a list of integers:
```
def Monomial(nVar,monoList):
if nVar==0:
return "({})".format(monoList[0])
else:
left = "((.(^{})).(*))"
mono = "({})".format(monoList[0])
for i in range (0,nVar):
p = monoList[i+1] if i+1<len(monoList) else 0
mono = left.format(p) + "(" + mono + ")"
left = "((.)" + left + ")"
return mono
def Plus(nVar):
if nVar==0:
return "(+)"
else:
return "((<*>).(.)(" + Plus(nVar-1) + "))"
def PointFree(l):
nVar = 0
for monoList in l:
if nVar<len(monoList)-1: nVar = len(monoList)-1
pointfree = Monomial(nVar,l[0])
plusTxt = Plus(nVar)
for monoList in l[1:]:
pointfree = plusTxt + "(" + Monomial(nVar,monoList) + ")(" + pointfree + ")"
return pointfree
```
## Input
The input is the polynomial function to be converted.
The input format shall consist of a list of Integers in any format you want.
For example, you might define the polynomial `5*a^5+2*a*b^3+8` as the list `[[5,5,0],[2,1,3],[8]]`
## Output code
The output is the Haskell code for that polynomial as a function of n Integers,
written in point-free style with only numeric literals and base functions(no Import).
Of course, the above process and implementation comply to these rules.
For Haskell programmers, this means no list comprehension, no lambdas and only Prelude functions(no import, language extensions..):
`(+) (-) (*) (^) (.) (<*>) (>>=) flip sum zip uncurry curry ($) ...`
## Test cases
Your program should work for all valid inputs, but will be scored on on these five polynomials:
```
f1 a b c d = 5*a^4*b^3*c^2 + a^2*b^3*c^4*d^5
f2 a b c = -5*a^5*c^8 + 3*b^3*c^4 + 8
f3 a b = 5*a^5+3*b^3+8
f4 a = a^3+a^2+a+1
f5 = 1+2-3
```
Tests cases with the Python code given above:[Try it online!](https://tio.run/##fZLPa4MwFMfv/hXBU9JGMbVCKe2OO22ww9hFHAiLm5BGsRY2Sv929140/uimOcTE9z7vffNNyp/6q9Bh03zIjDwXujjlqaL6La34CXZP@blme4fAyDOCv4/HoN3jqGR9qTRx6fXGXD8rqlNaU8vFQcJMplRnOTBKZjU5AkN9@g4c8@mKMbePI27iizVxQIzkJNekSvWnJDTgKJANrXCUUKun87VI8CDwPSip@7LMaCTBhOyEoF4ro2RkDcpcmE0UNiPld6djmGb207TONCzgOGj7i7qc6Uj6otPrrtLU1D5MD6sHcNRnRmRf2RNGOfrctixyXT9WUlLVNcUsEN5agM5ab9BgNXTqxE3t88TeFrj77xiwxHYZtIOE6SNT5kbbJBD7@o3uDYY4/8uJxT4ZJI2r2yL2mmaetDHDJAxwe0vOyM4@1pQVrKibCWhxvfXPcrAxjiO@5SHfJDwWfAOrLY@ShDHmWHYzz3oRj3jAdwCH8AUYVrspHi61Btqyf8ntPClMvuhkC5ynbLTAQjZyXmiQ5hc "Python 3 – Try It Online")
Once you have run your program on these samples, copy/paste your output code into the following program (in the "Code" section) and run it in order to check your outputs:
[Try it online!](https://tio.run/##jZJNj5swEIbv/hWj1R4g4NXyYSlCGy5VD5WqVlUr9UBBcsAEFAgUTApV/3t2DIRs6aqtD8l4/D7jecdkvD2KorjkZV01Er6IVj586vL4@CYT8ZGQuOBtC2/PvIAGfmSiEUAAl1AZz8Mk9SF4d5LiIJpQbeaY5KdW8lMsJnjOTiVuFXYQV6i7ibUPXQncnG/UYedPocZVbUysCpxB670BddNWOz@kTVWOtzW8uO91GNCE8qK6HUsJVVSMfS@NT51/1PRZewDV2/dlEKBJHEya9@/F6SAzfRrCrRe1EiRK3uclOtBKXkMxaqHQgYK1yJYi0CMg@VEgqfWG0YhacAmP@iLFO2G4WjuocAdtVwZ1UyVdLO@59zOvv@Yy0yJ9gPqXxr1af6JFOFYgJLU8b3ZI/X8HJLX/R09S5y8ykrp/npKULckLoRS7e6K40HLB8dVllrf4JSQC9gMMVddA1cm6k0rjow2cwTcOe4ghwXdiGx65m33kbOLIBgN4ZM87d5NEDG3c9OpdqQIYHm9R7FylgJvtPGi0dEVgREbCGLVgXFUvF9qcCJgJHjkGNmJww4JX9Qz1L5Zl2NSZji6k5PkJj5NqfDg0/lk2cIe@PbgD34fpo8R9EDDTNR3TDs3AMm2MXJOF4e@YvcJsxCgzmflobpFz8B85jLZr0lmRznghglfsNchdQS5C1ii15j4t9bvG2ApjCkOhQqgThpdn "Haskell – Try It Online")
If your functions are correct, it will output:
```
f1 : +++ OK, passed 100 tests.
f2 : +++ OK, passed 100 tests.
f3 : +++ OK, passed 100 tests.
f4 : +++ OK, passed 100 tests.
f5 : +++ OK, passed 100 tests.
```
## Scoring
Code length + (sum of the test cases output length)/8.
-300 if your program consist in a point-free style Haskell function (with the same rules as for output).
I'll give a Bounty of **250 points** if you beat my score of 73.125 (272 + 809/8 - 300).
The Python solution given above is 797 bytes long, and outputs functions of length: 245, 282, 180, 132, and 24 so the score would be `797 + (245+282+180+132+24)/8 = 904.875`.
The smallest score wins!!
[Answer]
# Haskell, 278+448/8-300=34
```
(foldr.pure.pure.((++).(foldr(('(':).(++".)")<$id).((++).("(sum.zipWith(*)"++).show.map head<*>(".flip(map.(product.).zipWith(^))"++).(++")").show.map tail)<*>tail.head)<*>(++" pure)").("("++).foldr(("(("++).(++".flip(:)).)")<$id)"id".drop 2.head))<*>show.sum.concat<*>tail.head
```
Saved 14 bytes by having a closer look at parens as suggested by @Damien, then saved 8 more using another hint from them.
Since input is "list of Integers in any format you want", I take list of lists with first elements the multiplicative constants of the summands, and the rest all the corresponding exponents in reverse order. So the example polynomial `5*a^5+2*a*b^3+8` is given by `[[5,0,5],[2,3,1],[8,0,0]]`. (Didn't try `[(5,[0,5]),(2,[3,1]),(8,[0,0])]` - would that be allowed?)
The result for this example polynomial is this:
```
(((sum.zipWith(*)[5,2,8].flip(map.(product.).zipWith(^))[[0,5],[3,1],[0,0]]).).)(((id.flip(:)).) pure)
```
See the results for the test cases or try your own polynomial at the TIO-Link:
[Try it online!](https://tio.run/##fVLdasMgFL7vU4gUqo2VNmlglHZvsOtdZNmQaBqZjZIYBnv4ZZ6kyTooVTjxHL@fo6YS7acypi9Pbz0prZENd12jxkBIFFE@lglZkdUhZFGEOcX0uNSSTghM2u7Cv7V71b4ia4qh2lb2i1@EQ5US8rh@JpiXRjsSSpy4xsqu8JzOrHc60sAg6P/RvdCGBj58OWhBAigETQI0@A/Ua6OYkFlptDxQOveMtcRcNtaheFQDucEMzlDYuhD@1q2/CF2jEzLKo8KqsmxDkqEsS9mWxSxh@5xlO5ayfVjHec4W6O7Isk3KngInDfhkQG/DCiphPuKlM@mG8oiwY8nQUzzE3RAfEwIEwJskz1F@C2tU2xkPR4anKK83MCHCxUgLOy8fyDW69hP@v9O4Bf8IWg46RtVnX01guuh/itKIc9tvCud@AQ "Haskell – Try It Online")
Check the results for the test cases here:
[Check it online!](https://tio.run/##jVNLi9swEL7rVwzLHqSubfyEYDa@lB4KpaW00INxQXXkxMSv2vLWKf3v6UhyHOpdtpEJGSnzPeaTc@DDUVTVuay7tpfwVQzS@TyW@fHtQeRHQvKKDwO8e@IV9PDrIHoBBHAJdRLHeGgnkL5vpNiLPlObuSZlM0je5MKA51NDcWXYQt5i37WZfhxr4NasyGCbmJJyxY0HK4InoFN8wj6zpU9O0be1Vut5dT8xOOEQahblVlMJRSq078W4cf6Jsrl3D8rbzyUIoBKDKcrpg2j28sBMCFcvau0QUfOprHECWvMOKt0LFQMbvKVtIYEJAZIfBSLp9PDQi05wCS5bWlETTpfR9qrcwjDWade3uzGX9zz@XXbfSnmg39kJuj@Uxx17tKtMMxBSeHE8T2gn/y9I4d/ST4rglTZShM9/JUW0HJ6JbaO7RxtX3u4E8AHaUXajhB8nqE9QjE0uy7ZRDQnOgAFQtXBy5zLvG5ZGlpc5RVV2KmuHzpk4zLlmwtLUtXwrsMLMwv4QKz/LmDM/1KxyZ2hipk5fLKEbe8Ewn9nLyoodIfPmBjcby7Ui9KKcuPjt4t5dHL3q5mIhMBaehXGbASO/iM/Sa9mLVqi1VlKepZ8bxAIU8fHjKTEthTIX7gi5XXImNS8bLHetfmfxLfgie7jDW4/hDpIEzP8R9@lyg8hobhWHyf6F@SuYjzC8nQhz3pjB57dhs0YGK2SgBSOdlIa9BApXoBBBnm71Zp@enn8Fi1awSMHmsOwgy85/AQ "Haskell – Try It Online") (testing code from OP with my results)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 167 (111 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) + 448/8)
```
¬g©i˜Oëøć',ý’.Œ¬With(’DŠ’(¬€ÿ*)[ÿ].ÒÀ(‚é.(‚ª.)ÿ^))’sø',ý€…[ÿ]',ý…[ÿ]s…ÿÿ)®G"(ÿ.)"}„id®ÍF’((ÿ.ÒÀ(:)).)’}s“ÿ(ÿ©¬)
```
Since I don't know Haskell, I figured I'd just port the output of [*@ChristianSievers*' Haskell answer](https://codegolf.stackexchange.com/a/188134/52210), so make sure to upvote him!!
Input is taken in a similar matter as well (first being the multiplicative constant, and after that the exponents in reverse order). So for example: test case \$5a^4b^3c^2+a^2b^3c^4d^5\$ is given as input-list `[[5,0,2,3,4],[1,5,4,3,2]]`.
[Try it online](https://tio.run/##JU2xCsJADP2XLjZyHoVaEGfR0dGhVFAU7eRQ10Lp4uTSTSniJFSPzl3kILGTf9EfqblKIO/l5eXlEK3W4bZtUe2wCL/5nF5UfU49Qe8mucg6Q7UIj3ubh0l9526jalJFug8@6UBSRgkvr1RIA/iUQHoJwM6Iqi4mVU3yMOZ/aEcjRtKkAcuZZZOWYMVNcgs3WNJ5at4YsQsfA0gTF/NNTpp1LFBB2/r@wBMj4QgvEL4rhsIVDjOjcAXBDw) or [verify all test cases](https://tio.run/##TY8xS8NAFMf3foqQxZy8hiZpQLp0KYouXQSH44SKpQ2UVmgqOARCB51cuilBnIRoaDfpIgf37NRvkS8S311Q5OC99///3v2Pm80HV9GwurVPpzeLuGNZdvcOGnZ/ERtJqlLFSOXRPuvjB26/Hw4Av8r0yd2tVHERxWOHRG/3StVRRbksUB4yjlK4uMKU4DPmrm7q3WUoLxmjzTluTcyyKNM3vVyHmnFOHSVKptYntoPSZXZSpi/RtVrj47F@RpsmvMOYq@MSupOhJF/lqiAnq5Le/h7UZzdp2OezeDCxJsPpKB7rH6nN2ahbcc5DaIEPAbQFcA9CaNPsCwEW580QjoiGRALjt2jSDp16I/zD/2CNPAhMom@qZ@ovIqHtZiCE@AE).
[Verify the outputs with OP's validator.](https://tio.run/##jVNLi9swEL7rVwzLHqSubfyEYDa@lB4KpaW00INxQXXkxMSv2vLWKf3v6UhyHOpdtpEJGSnzPeaTc@DDUVTVuay7tpfwVQzS@TyW@fHtQeRHQvKKDwO8e@IV9PDrIHoBBHAJdRLHeGgnkL5vpNiLPlObuSZlM0je5MKA51NDcWXYQt5i37WZfhxr4NasyGCbmJJyxY0HK4InoFN8wj6zpU9O0be1Vut5dT8xOOEQahblVlMJRSq078W4cf6Jsrl3D8rbzyUIoBKDKcrpg2j28sBMCFcvau0QUfOprHECWvMOKt0LFQMbvKVtIYEJAZIfBSLp9PDQi05wCS5bWlETTpfR9qrcwjDWade3uzGX9zz@XXbfSnmg39kJuj@Uxx17tKtMMxBSeHE8T2gn/y9I4d/ST4rglTZShM9/JUW0HJ6JbaO7RxtX3u4E8AHaUXajhB8nqE9QjE0uy7ZRDQnOgAFQtXBy5zLvG5ZGlpc5RVV2KmuHzpk4zLlmwtLUtXwrsMLMwv4QKz/LmDM/1KxyZ2hipk5fLKEbe8Ewn9nLyoodIfPmBjcby7Ui9KKcuPjt4t5dHL3q5mIhMBaehXGbASO/iM/Sa9mLVqi1VlKepZ8bxAIU8fHjKTEthTIX7gi5XXImNS8bLHetfmfxLfgie7jDW4/hDpIEzP8R9@lyg8hobhWHyf6F@SuYjzC8nQhz3pjB57dhs0YGK2SgBSOdlIa9BApXoBBBnm71Zp@enn8Fi1awSMHmsOwgy85/AQ)
**Explanation:**
```
¬ # Get the first inner list in the (implicit) input-list
g # Get the length of that list
© # And store it in variable ® (without popping)
i # If that length is 1:
˜O # Take the flattened sum of the input-list
ë # Else:
ø # Zip/transpose the input-list; swapping rows/columns
ć # Extract head; pop and push head and remainder
',ý '# Join this first list by ","
’.Œ¬With(’ # Push dictionary String ".zipWith("
D # Duplicate it
Š # Triple swap the items on the stack (a,b,c → c,a,b)
’(¬€ÿ*)[ÿ].ÒÀ(‚é.(‚ª.)ÿ^))’
# Push dictionary string "(sumÿ*)[ÿ].flip(map.(product.)ÿ^))",
# where the three ÿ are filled with the values on the stack
s # Swap to take the remainder again
ø # Zip/transpose it back
',ý '# Join each inner-most list by ","
€…[ÿ] # Surround each inner string in []-blocks
',ý '# Join those by "," again
…[ÿ] # And surround the entire thing by []-blocks again
s # Swap the two strings on the stack
…ÿÿ) # And fill them in into the string "ÿÿ)"
®G } # Now loop ®-1 amount of times:
"(ÿ.)" # And fill in the top string on the stack into string "(ÿ.)"
„id # Then push string "id"
®ÍF } # Loop ®-2 amount of times:
’((ÿ.ÒÀ(:)).)’ # And fill the top string of the stack into dictionary
# string "((ÿ.flip(:)).)"
s # Swap the two strings of the stack again
“ÿ(ÿ©¬) # And fill them into the dictionary string "ÿ( pure)"
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why:
* `’.Œ¬With(’` is `".zipWith("`
* `’(¬€ÿ*)[ÿ].ÒÀ(‚é.(‚ª.)ÿ^))’` is `"(sumÿ*)[ÿ].flip(map.(product.)ÿ^))"`
* `’((ÿ.ÒÀ(:)).)’` is `"((ÿ.flip(:)).)"`
* `“ÿ(ÿ©¬)` is `"ÿ( pure)"`
Unfortunately `ÿ` doesn't work for inner items in a list and requires an explicit `€`, otherwise `',ý€…[ÿ]',ý…[ÿ]` could have been `2F',ý…[ÿ]}` instead.
] |
[Question]
[
Amazingly, this is the easier of the three card tricks I know off the top of my head...
The aim of this is to have your compiler perform a specific card trick. There's no slight of hand, and the compiler won't be memorizing the choice and saying "Voila, this is your card!" The code will basically manipulate a stack of cards and the final card drawn from this stack will be the card chosen at random:
If you want to understand this trick further, feel free to follow this with an actual deck of cards so that you can learn the trick. I will be displaying the order of the cards in the face-down stack in my example in curly braces `{}` so that you can see what's happening.
The standards set in this trick:
1. A standard deck of cards is generated, 52 cards (no jokers required). From this deck, nine cards will be chosen at random to form our trick's card stack.
2. The backs of the cards will be displayed as `@@`.
3. The face-size of the cards will be displayed in the format `XY` where `X` is the value, `A-9`,`T`,`J`,`Q`,`K` (`T` = 10); and `Y` is the suit, `S`pades, `C`lubs, `D`iamonds, `H`earts. So `AS` for the Ace of Spades, `TC` for 10 of Clubs, `8H` for the 8 of Hearts, etc.
4. In displaying the stack of cards, from left to right, the left-most card will be located on the bottom of the stack, and the right-most card will be at the top of the stack. Similarly, if cards are in smaller sets, left-most = bottom card, right-most = top card.
Given these standards, my randomly chosen stack for this example looks like this: `@@ @@ @@ @@ @@ @@ @@ @@ @@` (cards facing down)
...And when facing up: `TD JD 8C 7D 8S 3C QH 9S 3S`
Note, this means my facing up stack has the ten of diamonds on the bottom, and the three of spades at the top.
Your deck may vary from mine (see Standards 1 above re random generated stack)
I will go through this trick step-by-step, and how the code needs to work:
* Accept a number between 1 and 9 as input, to be used later on:
`2`
* Generate your nine-card stack and display the cards face down first, in sets of 3, four spaces in between each set. This is so that the user can see they've chosen a specific card out of a specific set:
`@@ @@ @@ @@ @@ @@ @@ @@ @@`
* Flip the cards over, so that the user can see which card they chose:
`TD JD 8C 7D 8S 3C QH 9S 3S`
* Announce the card chosen, full wording of the card, e.g. the second card (derived from our input of `2` earlier on):
`JACK OF DIAMONDS`
* Take the chosen card and place it on top of that specific set, facing up; remembering that the right-most card in each set is the top-most in each set facing up:
`TD 8C JD 7D 8S 3C QH 9S 3S`
* Put the other two sets on top of the set with the chosen card, also facing up, to form one stack. It does not matter which of the two sets goes first:
`TD 8C JD 7D 8S 3C QH 9S 3S`
* Flip the stack over so that the cards are facing down:
`@@ @@ @@ @@ @@ @@ @@ @@ @@`
*Note: At this point, the stack of cards will have now reversed in order:*
`{3S 9S QH 3C 8S 7D JD 8C TD}`
* Our ten of diamonds is on the top of the pile now... And our chosen card is third from the top... The chosen card will ***ALWAYS*** be third from the top at this point.
* Now, we have to spell out the card in question, in our case the `JACK OF DIAMONDS`. Cards are dealt from the top of the deck to another pile, spelling out the card as we go. After the spelling of each word, the rest of the pile goes straight on top with each word. I've shown how the cards in the face-down stack are ordered after each word in curly braces:
`J @@ A @@ C @@ K @@, @@ @@ @@ @@ @@ {TD 8C JD 7D 3S 9S QH 3C 8S}`
`O @@ F @@, @@ @@ @@ @@ @@ @@ @@ {8S 3C TD 8C JD 7D 3S 9S QH}`
`D @@ I @@ A @@ M @@ O @@ N @@ D @@ S @@, @@ {QH 9S 3S 7D JD 8C TD 3C 8S}`
* Here's what they call the *prestige*, the final part of the trick. Deal out the first five cards from the top of the stack, face down to the words `HERE'S THE <NUMBER> OF <SUIT>! <FIFTH CARD FACE UP>`, flipping the final card to show face up...
`HERE'S @@ THE @@ JACK @@ OF @@ DIAMONDS! JD`
The fifth card from the stack should now be the card originally chosen.
Example output, using a new randomly chosen stack, and `4` as the input.
```
@@ @@ @@ @@ @@ @@ @@ @@ @@
3D AD JS TH KD QS JC 6D 4S
TEN OF HEARTS
3D AD JS KD QS TH JC 6D 4S
KD QS TH 3D AD JS JC 6D 4S
@@ @@ @@ @@ @@ @@ @@ @@ @@
T @@ E @@ N @@, @@ @@ @@ @@ @@ @@
O @@ F @@, @@ @@ @@ @@ @@ @@ @@
H @@ E @@ A @@ R @@ T @@ S @@, @@ @@ @@
HERE'S @@ THE @@ TEN @@ OF @@ HEARTS! TH
```
Please note, the final *card* you are producing at the end is pulled from the card stack (array), and will always be the fifth card in the stack, not from some assigned variable; and the code needs to reflect this. Note, that if you're dealing with a zero-based array language that this would mean, element 4, as opposed to element 5 in a one-based array language.
The key to this code-golf (yes, this is going to be code-golf, muahahahahaha!) is through the manipulation of the nine-card stack. With each word spelled out, the affected cards at the top of the stack will be reversed, thrust to the bottom of the stack and the remaining cards will be placed on top; refer to the examples above to see how that works. Run through the logic with nine playing cards if you have to in order to understand how it works.
**Rules**
1. This is code-golf. Lowest byte-count will win; in the event of a tie in byte count, highest votes will win.
2. No silly loopholes.
3. The input can be implemented in whatever way you see fit: STDIN, an array, a parameter in a function, whatever takes your fancy...
4. Please provide a link to your executing code on an online IDE like TIO so that we can marvel at your work. Learning from one another is something I encourage, and I'd love to see how you all can code this up!
5. The chosen card is drawn correctly at the end providing you have the array/stack manipulations worked out. Please do not simply assign the chosen card into a variable and pull it out in the end... This will be regarded as an invalid answer.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~593~~ 589 bytes
```
from random import*
N=input()-1
n='\n';A='@@ ';V='A23456789TJQK';Z='SCDH'
J=' '.join
j=' '.join
s=sample(map(''.join,zip(V*4,Z*13)),9)
x,y=s[N]
S=[s[:3],s[3:6],s[6:]]
x,y=dict(zip(V,'ACE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING'.split()))[x],dict(zip(Z,'SPADES CLUBS DIAMONDS HEARTS'.split()))[y]
print(A*3+' ')*3+n+j(map(J,S))+n+x,'OF',y
S[N/3]+=S[N/3].pop(N%3),
print j(map(J,S))
s=S.pop(N/3)+S[0]+S[1]
print J(s)+n+A*9;s=s[::-1]
for w in x,'OF',y:l=len(w);s=s[:~l:-1]+s[:-l];print' @@ '.join(w)+' @@, '+-l%9*A
print"HERE'S @@ THE %s @@ OF %s! %s"%(A+x,A+y,s[4])
```
[Try it online!](https://tio.run/##TVFRb5swEH7nV9wqRbbBSZeSZQvIUr3EKZCNrDHJpjAeorXViAhYwNSwh/31zEA31ZJ93/m@@053p5r6Z5HfXC5PZXGC8pA/aJOeVFHWphGyNFe/akyGYyNn6HuOXM7Q7S0gd8cQv7En76bvP8yi4H6F3D1Dcr7wkBEwBGh0LNLcOGqoz4tXsepwUtkjPh0URv0n/Z0qvDMndG@ObULojBhn2rAqDhNDsriKHTuhVWw709ZMnSTp4g/pjxp3qRTxuYDo6xoibyMELNfbDSz9nQDpfwMpdiIE4d95EYR@qInaDfh8BfdboeHKD@/QqFJZqrskJD4n9L/0niL5hS@EhPmn7UcJC59/XocLCZ7gm0i@TmsSQ5VpXmNu2lbbMiIa5NaxazWgkhDtnSlaLxFtDBmH13Zisd6OVKFwOLAJ7UXgVZaemezj1zaxZPw20c/4pRoEuGp1uTlz9Wxjxxnq0FNRwjOkOfwr52Qse8zxM@lJf7KWZmk0zBK3E0LQ7rTbh6ZZrUsBWcNsMDN5X@vKExuBZEuMPAGDqkXrpQZv9L0aYK7b41ajlzRJyOUy@Qs "Python 2 – Try It Online")
-4 bytes thanks to ovs
[Answer]
# [Perl 5](https://www.perl.org/), ~~551~~ ~~549~~ ~~547~~ 546 + 1 (`-p`) = 547 bytes
```
%r=(T,TEN,J,JACK,Q,QUEEN,K,KING,A,ACE);map$r{++$.}=$_,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE;map{/./;$u{$_.$&}=[$r{$_},OF,$&.$']for keys%r}DIAMONDS,HEARTS,SPADES,CLUBS;@0=(keys%u)[0..8];$x.="@0[$_..$_+2] ",print'@@ 'x3,$"x2for@z=(0,3,6);@w=@{$u{$0[$_]}};say"
$x
@w";@t=@0[($l=$_-$_%3)..$l+2];splice@t,$_%3,1;push@t,$0[$_];@0[$l..$l+2]=@t;print"@0[$_..$_+2] "for@z;@t=splice@0,$l,3;say"
@t @0
".'@@ 'x9;@0=reverse@t,@0;map{@t=();push@t,pop@0for/./g;say+(join$q=' @@ ',/./g),' @@,',' @@'x@0;@0=(@t,@0)}@w;$_=(join$q,"HERE'S",THE,@w)."! $0[4]"
```
[Try it online!](https://tio.run/##ZZFRb5swFIXf8yuY5RRQbly3aatNliWzxGloVrIG0k2KEKomtmWjwQXS0EX89TGbZk99su7VPd8591qlRXbZtv2COxFEMoAbuPHGc7iDu5XU5RzmfnANHnhj6bLHB4WLw2CAScNxAtGXBUSzpZQwXayWMPXvJYT@VwjlvZZK/3oWQeAH0ugOp@SU4d0BJwSfNHytOThpYDEFfEKwHX/PC@t3@lL2i2bie7eLYBLCTHrLKITwszeRIYw/rT6GTFDudHM7d00JeR8zXBOOBF1rMsHJ4Dy2LAuBKjbbyhbCsusRYFSfawPxhzsURnDlMrHn4mDiGF3cNKx8eEE9XPfEHjFRcc1zcKaXHOKkP3I1OdNkVqps8y0VFZgunDG1K3@aqqMwEyI7jnJRsS7Dm2hdEONxhFHAGYxeA4jKErSHyGvwD2bbIn1Oi9J4CtodUisd97@zypWgmqiv@8MgBs6vfLPFT9y2DAJM3wVTgN09dq0x5ogd0G3EnuGEH1WAZnIp7RDpb5Ug9i5B7yy93EWM2vbib66qTb4t2@HtJaFntB2qfw "Perl 5 – Try It Online")
Uses 0-based counting, so the cards are numbered 0-8.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~764~~ ... 686 bytes
```
import StdEnv,Math.Random,System._Unsafe,Text,System.Time
f=["",""," ":f]
w=" "
^ ="@@"
$s=g[hd u+t\\u<-s&t<-f]
d=reverse
r=repeatn 9
j=join
g=j w
s=split w
?n#n=n-1
#!a=removeDup[[[w<+y.[0],x,"OF",y]\\w<-:"A123456789TJQK"&x<-s"ACE ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING",y<-s"CLUBS HEARTS DIAMONDS SPADES"]!!(i rem 52)\\i<-genRandInt(toInt(accUnsafe time))]%(0,8)
#v=a!!n
#b=insertAt(n/3*3+2)v(removeAt n a)
#c=b%(n/3,n/3+2)
#c=c++removeMembers b c
#v=tl v
#(z,s)=foldl(\(c,s)k=let(p,q)=splitAt(9-size k)c in(d q++p,[j"@@ "[e<+w\\e<-:k]+j^["@@, ":[w\\_<-p]]:s]))(d c,[g(r^),g(map hd c),$b,g v,$a,$(r[^])])v
#[x:y]=z!!4
=d[j" @@ "["HERE'S","THE":y]+"! "+x:s]
```
[Try it online!](https://tio.run/##NVJrU6MwFP3Or7ik1YUluGp1VzvNKFq0@Gi1UHdngDoppJUKASF9@eO3G@zsTJI5996TnOTkRimjfJvl8SJlkNGEb5OsyEsBrohtvsSPVLwdDCmP8wy7m0qw7OB1xCs6Zdhja/E/5yUZU6bERwjXAwBQexoqK4IAKWMg6PISKc2KzPy3GBaGCIJFx6z2RceUrJiUbMnKiimlRAWjgsO5MifzPOHKjMxhpVSkKtJESHTBG5xw80hpqFSys3zJuovC9/1Vx9gc@IchXmM0uEF4EwbBqmO2kXV03Do5/fnr7Ny7e75H@2upjKxrGwZ9G7zfA/B6Q9uGm8FoCDfOiw2u8wdc@8Xug@3c9jzoOzVRhnfW9T08j2wJ753@rdSoj7p@GF250LOtoedC17EeB/2uC@6T1bVdFKqqloC8J5we60GQdMwZ47WfDheayOuVRtHOURDSRV0P97RDfKYrjSWhqsqVxoQkvGKlsITGf7S@t4xjfantnm4J4EAlNyKTvbqK5ZT1OhEZxo70yLKJtBcmENWHihSWSkP7xJVOpnkap1qgRTJ4JykTWoE/9J3ZUu7crJJPBu96BAnXYvgwjAL7c/mbgHzWMVZBwKTF76ExH/syi@W3@zL52jGLMGxXoa7LXRH2Z1o51vFMy2gBsgMiHTcneAZL3KS4qZX@ONRDXd7KX7c3IflU1ROFxFIIvpRQzx7a31zZWF7PRpJhIBWQsZYCW1fQUigNmC54BAQuJEx4sRAStxQCdQ8BCjgC7YvxVdO3f6NpSmfV1nQett0Np1kS7YKnlIppXmZbc/IP "Clean – Try It Online")
Defines the function `? :: Int -> [String]`, taking the card number and returning a list of lines.
**Explanation coming when answer is finalized so I don't need to keep retyping it**
] |
[Question]
[
# The Task
Build a function that takes a string of coins ending with an item index, and generates change as a string of coins using the least amount of coins possible.
The following are the items that can be bought (0-indexed):
`[0.45, 0.60, 0.75, 0.95, 1.10, 1.25, 1.40, 1.50, 1.75, 2.00]`
The following are the coins that can be used, with their abbreviations:
```
n = 0.05
d = 0.10
q = 0.25
D = 1.00
```
If an invalid item is selected, or the coins supplied are not enough to purchase the item, all $ is returned in the least number of coins possible.
If exact change is given, an empty string should be returned
# Test Cases
```
Dq4 = dn
qqqq4 = D
qqddddd10 = D
qqn0 = d
Dddd5 = n
qq0 = n
DD3 = Dn
Dd4 =
DDnn9 = d
```
Assume that input will only contain valid coin characters and will always terminate in an integer.
This is my first posted question, so be please be gentle when telling me how I screwed up asking it. :)
[Answer]
### Python 3 - 219 213 Bytes
Fixed whitespace...
So this is awful as of right now....
```
def x(s):
v={'n':.05,'d':.1,'q':.25,'D':1}
r=sum([v[c]for c in s[:-1]])-[.45,.6,.75,.95,1.1,1.25,1.4,1.5,1.75,2.0][int(s[-1])]
o=''
for x in'Dqdn':
r=round(r, 2)
while v[x]<=r:
r-=v[x]
o+=x
return o
```
I'll go back to see if I can't get it golfed down at all...
[Answer]
# [Python 2](https://docs.python.org/2/), ~~192~~ 176 bytes
*-16 bytes thanks to @JonathanAllan*
```
s=input()
v=0
while s[0]in'qndD':v+=[1,2,20,5][ord(s[0])%11];s=s[1:]
x=int(s)
v-=x<10and x<=v and[9,12,15,19,21,25,28,30,35,40][x]
print v/20*'D'+v%20/5*'q'+v%5/2*'d'+v%5%2*'n'
```
[Try it online!](https://tio.run/##HcxLCoMwFIXhuatwItfHLSbXBqo1M3cRMiikoFDiIza1q09jZx8czr9893G2FIKTk13ee14kXrLkM06vZ@oU05OF1ZoBOl9JxZGQGAqt5s3k51xknOu7k07xTidHjOy5i42LPHrOHtakRy99GqFa5IRcIG@RYkgg3bBh2Ai8Mq0OnSxbfKe@JlbCAJXPiNWihPWkqKkE81cWZSEEGIbV2BZ@ "Python 2 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~281~~ 271 bytes
-10 bytes thanks to Jonathan Allan
```
p->{int d[]={9,12,15,19,22,25,28,30,35,40},v[]={20,5,2,1},s=0,t;String m="Dqdn",n="";for(char c:p.toCharArray())s+=(t=m.indexOf(c))<0?0:v[t];t=p.charAt(p.length()-1)-48;s-=p.matches(".*\\d\\d")|s<d[t]?0:d[t];for(t=0;s>0;)if(s>=v[t++]){n+=m.charAt(--t);s-=v[t];}return n;}
```
Lambda that takes and returns a String
[Try it online!](https://tio.run/##jZBNb@IwEIbP8CusnOzFsZwAUqkxVVWuqx6qPVEO3nxA2GTi2hO0iM1vp07pfTOyNKOZd55X45M5m7i1BZzyPzfb/a6rjGS18Z78NBVcp5PvnkeDIZ3bKidNmNA3dBUcdnti3MGzIJycAkp0WNWi7CDDqgXxC4y7vNrCGWzd@r6yISXR5GbjzbUCJPlur68rnqQ8WfJkxdOUp0uePvC55PMlX8ienwdJKnlo86TnXkuO6g4jjY62HzlEHHQUqbJ1NDsaR7JHK7B9CeWzc@ZCGfMzTVE3ooK8@Pta0oyxtXySj@cd7hVqK4a9Z6RW1AUc8EhZnLB48aB8HIaNwexYeBqJH@/veXgR@@fXedgNiCF9WaOWym@kYlVJ/UYH9Gy2Z1eYBd9vfBwjG5Bftr0rsHNAQPW3yURNwye@XTwWjWg7FDYciDXQUhhr6wsNhy4ixtR/VB8hxunyIRI5SgtjZNvAW47CjaJt56M8F6NYAKu7rp/2t08 "Java (OpenJDK 8) – Try It Online")
Ungolfed:
```
p->{
int d[]={9,12,15,19,22,25,28,30,35,40},
v[]={20,5,2,1},
s=0,
t;
String m="Dqdn",
n="";
for(char c:p.toCharArray())
s+= (t=m.indexOf(c))<0 ? 0 : v[t];
t=p.charAt(p.length()-1)-48;
s-= p.matches(".*\\d\\d") | s<d[t] ? 0 : d[t];
for(t=0;s>0;)
if(s>=v[t++]){
n+=m.charAt(--t);
s-=v[t];
}
return n;
}
```
[Answer]
# PHP, 258 Bytes
```
$i=array(45,60,75,95,110,125,140,150,175,200);$c=array(D=>100,q=>25,d=>10,n=>5);$a=str_split($argv[1]);$p=$i[array_pop($a)];foreach($a as $x){$t+=$c[$x];$p=$c[$x]?$p:0;}$p=$t<$p?0:$p;while($t>$p){foreach($c as $n=>$x){if($t-$p>=$x){$t-=$x;echo $n;break;}}}
```
Ungolfed:
```
$i=array(45,60,75,95,110,125,140,150,175,200);
$c=array(D=>100,q=>25,d=>10,n=>5);
$a=str_split($argv[1]);
$p=$i[array_pop($a)];
foreach($a as $x){
$t+=$c[$x];
$p=$c[$x]?$p:0;
}
$p=$t<$p?0:$p;
while($t>$p){
foreach($c as $n=>$x){
if($t-$p>=$x){
$t-=$x;
echo $n;
break;
}
}
}
```
[Answer]
# JavaScript (ES6), ~~230~~ 219 bytes
*-10 bytes thanks to @JonathanAllan's idea of dividing all values by 5.*
*-1 byte by moving `b="Dqdn"` into the empty `s.pop()` function call.*
```
s=>(a=[20,5,2,1],s=s.match(/\D|\d+/g),i=[9,12,15,19,22,25,28,30,35,40][s.pop(b="Dqdn")]||0,p=s.map(c=>a[b.search(c)]).reduce((y,z)=>y+z,0),(c=p-i)<0&&(c=p),a.map(v=>(x=c/v|0,c-=x*v,x)).map((v,j)=>b[j].repeat(v)).join``)
```
## Ungolfed
```
input => {
values = [20,5,2,1];
coins = "Dqdn";
input = input.match(/\D|\d+/g);
item = [9,12,15,19,22,25,28,30,35,40][input.pop()] || 0;
payment = input.map(c => values[coins.search(c)]).reduce((y,z) => y+z, 0);
change = payment - item;
if (change < 0) change = payment;
return values.map(val => {
count = change/val | 0;
change -= count * val;
return count;
}).map((count,j) => coins[j].repeat(count))
.join``
}
```
## Test Snippet
```
f=
s=>(a=[20,5,2,1],s=s.match(/\D|\d+/g),i=[9,12,15,19,22,25,28,30,35,40][s.pop(b="Dqdn")]||0,p=s.map(c=>a[b.search(c)]).reduce((y,z)=>y+z,0),(c=p-i)<0&&(c=p),a.map(v=>(x=c/v|0,c-=x*v,x)).map((v,j)=>b[j].repeat(v)).join``)
```
```
Input<br><input oninput="O.value=/\D+\d+/.test(I.value)?f(I.value)||`<empty>`:``" id="I"><br>Result<br><input id="O" disabled>
```
[Answer]
## C++, ~~375~~ ~~371~~ 370 bytes
-5 bytes thanks to Zacharý
```
#include<map>
#include<vector>
#include<string>
std::map<int,int>c={{'n',1},{'d',2},{'q',5},{68,20}};void v(std::string&e){int m=0,i=0,h=0;for(;i<e.size();++i)h+=e[i]>47&&e[i]<58;m=i=0;for(;i<e.size()-1;++i)m+=c[e[i]];if(h==1){i=std::vector<int>{9,12,15,19,22,25,28,30,35,40}[e[e.size()-1]-48];m-=(m>=i)*i;}e="";for(auto&g:{68,113,100,110})while(m>=c[g]){m-=c[g];e+=g;}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~68~~ 64 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Vị“€ÐŒæı÷œ#(µ‘
ḟ®µL⁼1ȧÇ
“Þ¦£‘ɓ“Dqdn”©iЀị⁹;1,0¤S¹_<?⁸Ǥ;%\:⁹®żŒṙ
```
A monadic link taking and returning lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8/z/s4e7uRw1zHjWtOTzh6KTDy45sPLz96GRljUNbHzXM4Hq4Y/6hdYe2@jxq3GN4Yvnhdi6g0sPzDi07tBgoe3IykOdSmJL3qGHuoZWZhycADQGZ1rjT2lDH4NCS4EM7423sHzXuONx@aIm1aowVUObQuqN7jk56uHPm////CwvzDAA)** or see the [test suite](https://tio.run/##y0rNyan8/z/s4e7uRw1zHjWtOTzh6KTDy45sPLz96GRljUNbHzXM4Hq4Y/6hdYe2@jxq3GN4Yvnhdi6g0sPzDi07tBgoe3IykOdSmJL3qGHuoZWZhycADQGZ1rjT2lDH4NCS4EM7423sHzXuONx@aIm1aowVUObQuqN7jk56uHPm/6N7DrcDNbj//x@t5FJooqSjVAgEEDoFBAwNwOw8EOUC5JuCuWCeizFYzATMzsuzVIoFAA).
### How?
```
Vị“€ÐŒæı÷œ#(µ‘ - Link 1, item price / 5: list of digit characters, d e.g."4" or "10"
V - evaluate d as Jelly code 4 10
“€ÐŒæı÷œ#(µ‘ - code page indexes = [12,15,19,22,25,28,30,40,9]
ị - index into (1-indexed and modular) 22 12
ḟ®µL⁼1ȧÇ - Link 2, item price / 5: list of characters, s e.g."Dq4" or "Dq10"
® - recall register value = "Dqdn" (see Main)
ḟ - filter discard from s "4" "10"
µ - monadic chain separation, call that d
L⁼1 - length equals 1? 1 0
Ç - call last link as a monad 22 12
ȧ - logical and 22 0
“Þ¦£‘ɓ“Dqdn”©iЀị⁹;1,0¤S¹_<?⁸Ǥ;%\:⁹®żŒṙ - Main link: list of chars, s e.g."Dqqqq4"
“Þ¦£‘ - code page indexes = [20,5,2]
ɓ - dyadic chain separation, left=s right=that
“Dqdn” - literal = "Dqdn"
© - copy to register and yield
Ѐ - map across c in s:
i - 1st index (0 if not found) [1,2,2,2,2,0]
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument = [20,5,2]
1,0 - 1 pair 0 = [1,0]
; - concatenate = [20,5,2,1,0]
ị - index into (1-indexed) [20,5,5,5,5,0]
S - sum 40
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument = s
Ç - call last link as a monad(s) 22
? - if:
< - less than (coins not enough?) 0
¹ - ...then: identity (do nothing, would be 40)
_ - ...else: subtract 18
; - concatenate with right [18,20,5,2]
\ - cumulative reduce by
% - modulo [18,18,3,1]
⁹ - chain's right argument = [20,5,2]
: - integer division [ 0, 3,1,1]
® - recall register value = "Dqdn"
ż - zip [['D',0],['q',3],['d',1],['n',1]]
Œṙ - run-length decode "qqqdn"
```
] |
[Question]
[
The reverse of an *n*-bit number is just its *n* binary digits in reverse order:
>
> 001010010 → 010010100
>
>
>
Given a number *n*, generate all *n*-bit integers ([*0, 2n-1*]) in an arbitrary order, with only one restriction: there must be a splitting point such that the reverse of an integer is on the opposite side of the splitting point. Integers which are their own reverse must come before the splitting point.
Other than this single splitting point there are no restrictions, all the integers before or after it may come in whatever order you desire.
Example for 4 bits (you don't have to generate this order):
```
0000, 0001, 0010, 0011, 0101, 0110, 0111, 1001, 1011, 1111,
0100, 1000, 1010, 1100, 1101, 1110
```
You may output the integers as their binary digits or just as integers. You don't have to explicitly output the splitting point.
[Answer]
## JavaScript (ES6), ~~129~~ 114 bytes
```
f=n=>[...Array(p=1<<n)].map((_,i)=>(p+i).toString(2).slice(1)).sort((a,b)=>g(a)-g(b),g=a=>[...a].reverse().join``<a)
```
I appear to have stumbled on the code that happens to generate the given example for 4 bits. Edit: Saved 15 bytes thanks to @ConorO'Brien.
[Answer]
## PHP, 80 Bytes
Make 2 Groups in a 2D Array
After the first Group is the splitting point
In the first group are the integers with their own reverse and the integers that are lower than their reverse
```
for(;$i<1<<$argn;)$r[strrev($b=sprintf("%0{$argn}b",$i++))<$b][]=$b;print_r($r);
```
[Try it online!](https://tio.run/##HcpNCoAgEEDhfceQCZRaFLSbkQ4iEgn9uLFhjDbR2Q3cvu/xyYVmPrmBVY5k1aSw7JdohEgjUa1oQFy@RbZHQ7CZJaZ716od3upfUD3ErjOGIHjnLQSszyIaxGApPw "PHP – Try It Online")
## PHP>=7.0, 82 Bytes
Make 3 Groups in a 2D Array
After the second Group is the splitting point
In the first group are the integers with their own reverse
In the second group are the integers that are lower than their reverse
Use the [Spaceship Operator](http://php.net/manual/en/language.operators.comparison.php)
```
for(;$i<2**$argn;)$r[strrev($b=sprintf("%0{$argn}b",$i++))<=>$b][]=$b;print_r($r);
```
[Try it online!](https://tio.run/##HcpNCoAgEEDhfceQCdRaRLQbrYNEREI/bmwYpU10dgO373t0UTYTXVTBxmewYhCYj5slgje91qWiAp5jYt4fCc5GYh/SIUXdvcU/J1rwTaOUsSO4ZV4sOCzXyhJYYc4/ "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
2ṗ’µżUṢ€QZ;/Q
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//MuG5l@KAmcK1xbxV4bmi4oKsUVo7L1H///80 "Jelly – Try It Online")
Group with their reflections, uniquify and sort, then zip.
[Answer]
# Mathematica, 51 bytes (Windows ANSI encoding)
```
±n_:=SortBy[{0,1}~Tuples~n,(#-Reverse@#).Range@n!&]
```
Defines a unary function `±` taking a positive integer argument and returning a list of lists of 0s and 1s. For example, `±4` returns
```
{{1, 1, 0, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 1, 0}, {0, 1, 0, 0},
{1, 1, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 1, 1, 1},
{0, 0, 1, 0}, {1, 0, 1, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}, {0, 1, 1, 1},
{0, 0, 1, 1}}
```
`SortBy[{0,1}~Tuples~n,...]` takes the set of all length-n lists of 0s and 1s and sorts them according to the values that the function `...` takes on each such list. It suffices to find a function whose values on a list and its reverse are negatives of each other and whose value is 0 *only* if the list is its own reverse. Taking the dot product of (the list minus its reverse) and (a sufficiently unbalanced vector, such as `Range@n!` which is `{1!, 2!, ..., n!}`) does the trick.
[Answer]
# Pyth, 14 bytes
```
o&NcNijN2 .5^2
```
[Try it online](https://pyth.herokuapp.com/?code=o%26NcNijN2+.5%5E2&input=4&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4&debug=0)
### How it works
Sort by *x* / *f*(*x*), where *f*(x0⋅20 + x1⋅21 + x2⋅22 + …) = x0⋅0.50 + x1⋅0.51 + x2⋅0.52 + … (for binary digits xi ∈ {0, 1}). Interestingly, this same ordering works for all *n*, but with different splitting points. If *x* is less than or equal to its *n* bit reversal, then *x* / *f*(*x*) ≤ 2*n* − 1, otherwise *x* / *f*(*x*) > 2*n* − 1.
```
o ^2Q sort values [0, …, 2**n-1] by this key:
&N if value is 0, key is 0
cN else, key is value divided by
i .5 the base 0.5 number whose digits are
j 2 the base 2 digits of
N value
```
] |
[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/54556/edit).
Closed 8 years ago.
[Improve this question](/posts/54556/edit)
# Task
Given the page of a book **P** on stdin, count all occurrences of the digits 0-9 in each member of the range 1 to **P**. There is no page zero and your program should handle any number less than 1,000,000. Since putting a constraint on how you can do it is difficult to explain there will be a time limit of 3 seconds instead. That may be too short for some of the answers already submitted but mine runs faster than that so it is possible.
# Examples (plus a list of the occurences):
```
input: 10
0 = 1 (10)
1 = 2 (1, 10)
2 = 1 (2)
3 = 1 (3)
4 = 1 (4)
5 = 1 (5)
6 = 1 (6)
7 = 1 (7)
8 = 1 (8)
9 = 1 (9)
```
```
input: 20
0 = 2 (10, 20)
1 = 11 (1, 10, 11 ... 18, 19)
2 = 3 (2, 12, 20)
3 = 2 (3, 13)
4 = 2 (4, 14)
5 = 2 (5, 15)
6 = 2 (6, 16)
7 = 2 (7, 17)
9 = 2 (8, 18)
```
[Answer]
## Matlab, 43 bytes
```
y=hist(+num2str(1:input('')),47:57);y(2:11)
```
Example:
```
>> y=hist(+num2str(1:input('')),47:57);y(2:11)
10
ans =
1 2 1 1 1 1 1 1 1 1
```
**How it works:**
`1:input('')` generates a vector of numbers from 1 to the input number.
`num2str` converts all those numbers to a space-separated string (char array).
The `+` converts from char to ASCII codes. Digits are 48 to 57 in ASCII.
`hist` counts how many times each of those ASCII codes appears. Actually the count for value 47 is necessary too, because `hist` collects all lower values in the first bin. So that 47 just intercepts all spaces and prevents them from being confused as zeroes.
Lastly, `y(2:11)` removes that first count and prints the result.
[Answer]
# CJam, ~~18~~ ~~14~~ 10 bytes
*Thanks @Dennis for a 4 bytes golf.*
```
qi,:)s$e`p
```
[Try it online](http://cjam.aditsu.net/#code=qi%2C%3A)s%24e%60p&input=20).
# Explanation
```
qi e# Convert input to integer
,:) e# Push [1 ... input]
s e# Convert to string (concats all numbers)
$ e# Sort the string
e` e# Run-length encode
p e# Print
```
[Answer]
# K5, 43 bytes (27 without fancy output formatting)
```
`0:"\n"/($!10){x," = ",$#&y=*x}\:,/$1+!.0:`
```
Without formatting:
```
($!10){#&y=*x}\:,/$1+!. 0:`
```
Might not handle all numbers up to `1e9`...(well, it could, with lots of memory).
Also, it's the same core algorithm as the Matlab answer. Ironically enough, I wrote this earlier this morning (before the Matlab answer), but then got distracted by Sonic 06 videos and forgot to post it... :(
Still cool.
] |
[Question]
[
This challenge is the second of a series of [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") problems that should be written in the [GOLF CPU](http://meta.codegolf.stackexchange.com/questions/5134/the-golf-cpu-framework). You can find the first [here](https://codegolf.stackexchange.com/questions/52489/the-golf-cpu-golfing-challenge-prime-partitions)
For this problem, you are given the volume of a [cuboid](https://en.wikipedia.org/wiki/Cuboid) (A rectangular cube). Each of the side lengths are integers. You must return the number of distinct cuboids that have that volume. This sequence matches [A034836](https://oeis.org/A034836) (thanks Tylio)
```
Input:Output [List] [of] [cuboids]
1:1 [1,1,1]
5:1 [1,1,5]
8:3 [1,1,8] [1,2,4] [2,2,2]
24:6 [1,1,24] [1,2,12] [1,3,8] [1,4,6] [2,2,6] [2,3,4]
100:8 [1,1,100] [1,2,50] [1,4,25] [1,5,20] [1,10,10] [2,2,25] [2,5,10] [4,5,5]
1080:52
468719: 1
468720: 678
468721: 2
```
Your program should be written in [GOLF CPU](http://meta.codegolf.stackexchange.com/questions/5134/the-golf-cpu-framework). For input/output you can either use STDIO or the registers. Hardcoding primes or answers isn't allowed.
This is a [fewest-operations](/questions/tagged/fewest-operations "show questions tagged 'fewest-operations'") problem, so the answer that solves the examples above with the fewest amount of cycles wins!
[Answer]
# 14,483 cycles
I use the fact that the output depends only on the signature (exponents in the prime factorization) of the input. I used the formula from <https://oeis.org/A034836>. The sieve of Eratosthenes is used to find primes to factorize the input by trial division.
```
# Input in register n
# Outputs in register r and exit code
# the signature of n (exponents in its prime factorization) are stored in
# memory starting at address 0x1000000000000000. They are byte-sized
# since the largest exponent we can have is 64 (2**64)
# mov z, 0x1000000000000000 (implicit)
mov y, z
# pull out factors of 2
# number of factors is stored in k
# mov k, 0 (implicit)
factor_two:
and c, n, 1
snz c, 3
shr n, n, 1
inc k
jmp factor_two
# store factors of two if nonzero
sz k, 2
sb z, k
inc z
# Sieve of Eratosthenes
# we only check odd primes, since we already removed factors of 2
# we store COMPOSITE(i) at address i
# we also check n for divisibility by every prime we find
# note we only have to check for prime factors up to sqrt(n)!
mov i, 1
sieve_loop:
add i, i, 2 # go to the next odd number
lb c, i # check if COMPOSITE(i)
jnz sieve_loop, c # if so, continue
mulu j, k, i, i # j = i**2
geu c, j, n # if i**2 > n:
jnz end_sieve_loop, c # break
# otherwise, i is prime; check if n is divisible by i
mov k, 0
factor_i:
divu q, r, n, i # r = n % i
snz r, 3
mov n, q # n /= i
inc k
jmp factor_i
# store factors of i if nonzero
sz k, 2
sb z, k
inc z
# now cross off all composites that are odd multiples of i,
# but only up to sqrt(n)
shl d, i, 2 # d = 2 * i
# we already have j = i**2, we can start marking composites here:
# since every lesser multiple of i must have a smaller prime factor and
# therefore must have already been marked
sieve_inner_loop:
sb j, 1
add j, j, d # j += 2*i
mulu c, k, j, j # c = j**2
leu c, c, n # if j**2 < n:
jnz sieve_inner_loop, c # continue
jmp sieve_loop
end_sieve_loop:
# if n != 1, n is a prime and needs to be added to the signature
cmp c, n, 1
snz c, 2 # skip if n==1
sb z, 1
#mov z, 0x1000000000000000
# according to https://oeis.org/A034836, we have:
# a(n) = (np + 3*nsq + 2*ntp)/6
# where np = Times@@Binomial[2+s,2],
# ntp = Times@@Floor[Floor[s,3]/s],
# nsq = Times@@(Floor[s/2] + 1),
# and s is the signature
# Binomial[2+s,2] == (1+s)(2+s)/2
# Floor[Floor[s,3]/s] == 1 if s divides 3, 0 otherwise
# I tested this formula up to n=10,000,000
mov t, 0 # <= BUG? (doesn't work without this line)
mov d, 1 # np
mov e, 1 # ntp
mov f, 1 # nsq
product_loop:
lb s, y
jz finish, s
inc y
divu q, r, s, 3 # r = s % 3
sz r, 1
mov e, 0
inc s
mulu d, x, d, s # d *= s + 1
inc s
mulu d, x, d, s # d *= s + 2
shr d, d, 1 # d /= 2
shr s, s, 1 # s /= 2 (s == (s+2)/2 == floor(s/2) + 1)
mulu f, x, f, s # f *= floor(s/2) + 1
jmp product_loop
finish:
add r, e, f # r = e + f
shl r, r, 1 # r *= 2
add r, r, f # r += f
add r, r, d # r += d
# r == d + 3*f + 2*e
divu r, s, r, 6 # r /= 6
halt r
```
Test cases:
```
robert@unity:~/golf-cpu$ ./assemble.py cube.golf
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1
Execution terminated after 42 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=5
Execution terminated after 77 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=8
Execution terminated after 91 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=24
Execution terminated after 126 cycles with exit code 6.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=100
Execution terminated after 218 cycles with exit code 8.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1080
Execution terminated after 236 cycles with exit code 52.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468719
Execution terminated after 9710 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468720
Execution terminated after 422 cycles with exit code 678.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468721
Execution terminated after 3561 cycles with exit code 2.
robert@unity:~/golf-cpu$
```
[Answer]
# Total cycles for examples: 29,566,640
It cubes the input number in the algorithm, so the input can't be larger than around `2^21`.
Cycle count for example input:
```
Input Cycles
1 153
5 75
8 773
24 1,528
100 3,185
1080 27,608
468719 9,676,846
468720 9,764,814
468721 10,091,658
```
I'm using an [algorithm I found on OEIS](https://oeis.org/A034836), which does the following:
```
cuboids(n):
if is_prime(n):
return 1
res = 0
for d in divisors(n):
if d^3 <= n:
for d0 in divisors(n/d):
if d0^2 <= n/d:
res += 1
if d0 < d:
res -= 1
return res
```
This might actually be slower than just trying every divisor combination and checking if `d1 <= d2 <= d3`, however the bottle-neck is finding the prime anyway.
Divisors are found by using the prime factorization of the number. I'm using the same method to build an array of all primes below the input number as I used in [the previous problem](https://codegolf.stackexchange.com/questions/52489/the-golf-cpu-golfing-challenge-prime-partitions).
Run with:
```
python3 assemble.py 52489-cuboids.golf
python3 golf.py -d 52489-cuboids.bin x=<INPUT>
```
Output will be in the `t` register.
Example run:
```
$ python3 golf.py -d 52489-cuboids.bin x=1080 | grep 'Execution\|t: '
Execution terminated after 27608 cycles with exit code 0. Register file at exit:
t: 52 0x34
```
Code:
```
call build_primes
mov q, x
call is_prime
jnz prime, a
shl m, x, 3
add m, m, 8
call divisors
mov y, x
mov k, l
mov t, 0
mov p, m
outer_loop:
cmp a, p, k
jnz done, a
lw d, p
add p, p, 8
mulu a, r, d, d
mulu a, r, a, d
lequ a, a, y
jz outer_loop, a
divu x, r, y, d
mov m, k
call divisors
mov q, m
inner_loop:
cmp a, q, l
jnz outer_loop, a
lw o, q
add q, q, 8
mulu a, r, o, o
lequ a, a, x
jz skip1, a
inc t
skip1:
leu a, o, d
jz inner_loop, a
dec t
jmp inner_loop
done:
halt 0
prime:
mov t, 1
halt 0
# Input: x, m
# Output: l
# x: input number
# m: memory location to store divisors
# l: memory location where last divisor is stored + 8
divisors:
sw m, 1
add l, m, 8
mov p, 2
divisors_outer:
mov q, 1
push z, 0
divisors_inner:
divu y, r, x, p
jnz divisors_not_divisible, r
mulu q, r, q, p
push z, q
mov x, y
jmp divisors_inner
divisors_not_divisible:
mov w, l
divisors_not_divisible_outer:
mov v, m
pop t, z
jz divisors_not_divisible_last, t
divisors_not_divisible_inner:
cmp a, v, w
jnz divisors_not_divisible_outer, a
lw s, v
mulu a, r, s, t
sw l, a
add l, l, 8
add v, v, 8
jmp divisors_not_divisible_inner
divisors_not_divisible_last:
shl i, p, 3
lw p, i
cmp a, x, 1
jz divisors_outer, a
ret l
# Input: x
# Memory layout: [-1, -1, 3, 5, -1, 7, -1, 11, ...]
# x: max integer
# p: current prime
# y: pointer to last found prime
# i: current integer
build_primes:
sw 0, -1
sw 8, -1
sw 16, 1
mov y, 16
mov p, 2
build_primes_outer:
mulu i, r, p, p
jnz build_primes_final, r
geu a, i, x
jnz build_primes_final, a
build_primes_inner:
shl m, i, 3
sw m, -1
add i, i, p
geu a, i, x
jz build_primes_inner, a
build_primes_next:
inc p
shl m, p, 3
lw a, m
jnz build_primes_next, a
sw y, p
mov y, m
sw y, 1
jmp build_primes_outer
build_primes_final:
inc p
geu a, p, x
jnz build_primes_ret, a
shl m, p, 3
lw a, m
jnz build_primes_final, a
sw y, p
mov y, m
sw y, 1
jmp build_primes_final
build_primes_ret:
ret
# Input: q
# Output: a
is_prime:
shl m, q, 3
lw a, m
neq a, a, -1
ret a
```
] |
[Question]
[
This isn't as much a "challenge" as "a unique problem that there are no built-in functions to solve." Basically, you need to do this:
* Read some lines of numbers from `stdin`. These lines may contain trailing or preceding whitespace, and there may be empty lines. No lines will contain "just whitespace" other than a newline. Each non-empty line will have exactly one number. This:
```
123
456\t
```
(where `\t` is a tab) is considered valid input.
* Read the numbers in the input in base `N+1`, where `N` is the largest digit in any of the lines. In this case, the largest digit is `6`, so the numbers would be read in base `7`, resulting in 6610 and 23710.
* Find the sum of the numbers. The sum of 6610 and 23710 is 30310.
* Convert the sum back to base `N+1` again. We'd convert 30310 to base `7`, which would be 6127.
* For each digit, print that many underscores, followed by a space. The last digit should instead be followed by a newline *or* a space and a newline. In our example, that would be `______ _ __\n` or `______ _ __ \n`, where `\n` is the newline character.
Here's an example in Python:
```
import sys
def convert_to_base(n, b):
'Convert `n` to base `b`'
res = []
while n:
res.append(n % b)
n /= b
return res[::-1]
# read the lines, discarding empty ones and stripping any whitespace
lines = map(str.strip, filter(None, list(sys.stdin)))
# find the largest digit, and add 1 to it to make our base
base = max(map(max, (map(int, line) for line in lines)))+1
# read the lines in the base and sum them
result = sum(int(line, base) for line in lines)
# print the result in the original base using underscores, separated by spaces
for number in convert_to_base(result, base):
print '_'*number,
# print a newline
print
```
This is code golf: the shortest program wins!
[Answer]
# Pyth, 26
```
JscR).zjd*R\_jsiRKhseSsJJK
```
[Demonstration.](https://pyth.herokuapp.com/?code=JscR).zjd*R%5C_jsiRKhseSsJJK&input=123%20%0A%0A%20456%20%20%20&debug=0)
```
JscR).z
.z Take the input as a list of lines.
cR) Remove all whitespace from each line.
s Combine the lines.
J Save the result to J.
J is now the list of the string forms of the numbers.
jd*R\_jsiRKhseSsJJK
sJ Combine J into one string.
eS Find the maximum of that string.
s Convert it to an integer.
h Add one.
K Save to K. K is the base.
iRK J Convert the strings in J to base K.
s Add them together.
j K Convert the result back to base K, as a list of ints.
*R\_ Map each int in that list to that many underscores.
jd Join on spaces and print.
```
[Answer]
# Pyth, 24 bytes
Just found this question via Twitter.
Notice that quite large parts of the program are similar to isaacg's solution (like base-conversion and the printing part), but the main algorithm is completely different.
```
.V0#jd*R\_jsiRbcjd.z)b.q
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=.V0%23jd*R%5C_jsiRbcjd.z)b.q&input=%20123%0A%0A456%09&debug=0)
My solution is based on [this answer](https://codegolf.stackexchange.com/a/48989/29577), I gave to a similar question two months ago.
### Explanation:
```
.V0 for b in [0, 1, 2, ...):
#__________________.q try-catch block. If ___ is successful, exit the program (.q),
otherwise do nothing
cjd.z) read all input (.z), join lines by spaces (jd) and split (c))
this gives a list of numbers (but still in string format)
iRb convert each number from base b
s sum, add all numbers up
j b convert to base b
*R\_ multiply each digit with "_"
jd join with spaces
implicit print
```
The infinite loop `.V0` combined with the try-catch `#___.q` basically finds the first number `b >= 0`, with which the conversion `iRb` doesn't throw an error. And this happens, when `b` is equal to the largest digit + 1.
[Answer]
# CJam, ~~28~~ 27 bytes
```
q_$W=~)_@N%::~fb:+\b'_f*S*N
```
*UPDATE - 1 byte saved thanks to Martin*
[Try it online here](http://cjam.aditsu.net/#code=qN%25%3A%3A~_e_%24W%3D)%3AXfb%3A%2BXb'_f*S*N&input=%20123%0A%0A456%20%0A%0A%0A)
[Answer]
# PHP, ~~188~~ 182
```
function f($s){$b=max(str_split($s))+1;foreach(preg_split('/\s/',$s)as$x)$m+=base_convert($x,$b,10);foreach(str_split(base_convert($m,10,$b))as$d)echo' ',str_repeat('_',$d);echo'
```
';}
prints a leading blank instead of a trailing one. if not accepted, add +1.
breakdown:
```
function f($s)
{
$b=max(str_split($s))+1; // find base
foreach(preg_split('/\s/',$s)as$x) // extract all words and loop
$m+=base_convert($x,$b,10); // convert, sum up
foreach(str_split(base_convert($m,10,$b))as$d) // convert back, split into array, loop
echo' ',str_repeat('_',$d); // print underscores
echo'
'; // append newline
}
```
I wonder if there is a golfier approach to this ...
] |
[Question]
[
You are from the tiny country of Que-Wopistan. The Que-Wopistonion's are a proud people, and every Que-Wopistonian dreams of making their country proud by representing their country in the Olympics.
You have been given the incredible honor of competing in the 100-meter-dash. You are the nations sole representative, so there is a huge amount of pressure on you to do well. Unfortunately though, Que-Wopistan's training program is *awful!* Absolutely terrible. You can't work with this, so you decide to train yourself.
You try a few practice runs. On the first run, you make it 0.3 meters forward, and then fall on your face. You are dedicated though, so you get up and try again. This time, you actually go backwards -1.7 meters, before falling on your face again. You try again. And again. And agin. And again, but every time you fall on your face before making even 2 meters forward. You just aren't coordinated enough to run. Or walk. Or even-- *not* fall on your face.
This is where your programming expertise comes in handy.
# The challenge
In case you haven't realized yet, I am talking about the game [QWOP](http://www.foddy.net/Athletics.html?utm_source=The+List&utm_campaign=c3c42380e5-Digital+Ops+-+QWOP+%26+SC2&utm_medium=email). Once you have wasted 60 minutes, mashed your face into the keyboard, and now returned to this page after rage-quitting (don't worry, I did the same thing), here is your challenge. You must write a program that uses simulated key-presses to play the game of QWOP for you. The following actions do not have to be done by your program (you can do them manually yourself)
1. Opening the web browser and going to the correct page.
2. Starting and re-starting the game.
3. Make a screen recording.
Everything else must be automated by your program.
# Judging criteria
The winner of this contest will be the program that makes it the farthest. In the unlikely event of a tie (Which will happen if anyone actually makes it 100 meters), the winner will be decided by who made it there quicker. This is not code-golf, byte-count makes no difference.
If your program automatically detects the game being over (the game ends if you fall on your face or make it 100 meters) and exits, you will get a +10 meter bonus.
[Answer]
# [AutoHotkey](http://www.autohotkey.com/), 100.5 m

After running the following script, it can be activated by pressing Windows+H (yes, it only works on Windows). It can be stopped by pressing Escape.
```
#SingleInstance force
Esc::ExitApp
#h::
Loop,5 {
Send, {w down}
Sleep, 300
Send, {w up}
Sleep, 300
}
Loop,9999 {
Loop, 23 {
Send, {q down}
Sleep, 200
Send, {q up}
Sleep, 400
Send, {w down}
Sleep, 350
Send, {w up}
Sleep, 400
}
Loop,6 {
Send, {w down}
Sleep, 250
Send, {w up}
Sleep, 400
}
}
return
```
This particular code reached the finish line the first time it was run. I don't want to test it again now, because it takes forever and I can't do anything else while running it (Please comment if you figure out how to send keys to the Flash player without it being in focus). Caveat: At around 30 m, no keys were sent for a few seconds because a Windows pop-up jacked the focus. It was tested in Chrome browser.
When the script reached the obstacle at 50 m, the script somehow jumped over it right away, which may be a lucky and unusual occurrence. As for the time, the game irritatingly does not tell you how long the run took, but it does have a built-in tiebreaker by allowing you to jump as far as possible beyond the finish line at the end.
Also, this game's code does not seem very robust:

Huh?
] |
[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/38567/edit).
Closed last year.
[Improve this question](/posts/38567/edit)
# Game
The game is simple. Test the user's response time by asking them to enter the correct value that is displayed on the screen in the shortest time possible. Each round of the game will be as follows:
>
> Show Value ----> Get Response ----> Check Response ----> Report Response Time
>
>
>
# Example
```
ROUND ONE
---------
COMPUTER : G
USER : G
CORRECT INPUT, TIME = 0.26 SECONDS
```
# Code
* You may use any language or program.
* Do not use third party libraries, except GUI libraries.
(as suggested by [marinus](https://codegolf.stackexchange.com/users/1426/marinus))
* You may choose between CLI and GUI.
# Points
* +12 for the shortest code
* -2 for every byte after the 1024th byte
* +8 for GUI
* +8 for showing questions (eg: 4 + 2 = ?)
(rather than static values shown in the example above. There must be at least 10 questions.)
* +2 for random intervals between each round
* +4 for reporting average response time (in a set of 10 rounds)
* +4 for quickly vanishing questions/values
(questions/values stays on screen only for a short interval of time.
The vanish time must be less than or equal to 1 seconds.)
>
> You must, in your answer, calculate the total points you have scored. eg (+12 (-2x3) +4 = 10)
>
>
>
The answer with the most points wins.
[Answer]
# JavaScript (E6) 305 bytes. Score 8+8+2+4=22
Rusty GUI, but GUI it is. Try in FireFox/FireBug console.
At the time shortest code, but I don't claim the 12 points. Waiting for some more answer.
```
(Q=i=>(
i&&(t=r=x=y=0,msg=''),
w=~new Date(),
v=prompt(msg+'\nRound '+ ++r+': '+(a=1+t%9)+'+'+(b=1+(t>>4)%9)+'=?'),
u=~new Date(),
v-a-b?(++x,msg='Wrong'):(++y,msg='OK Time '+(p=w-u)/1000+' sec'),
t+=p,
r<10?setTimeout(Q,u%2000)
:confirm('Wrong '+x+', OK '+y+' in Avg time '+(t/y/1000)+' sec\nRepeat?')&&Q(1)
))(1)
```
[Answer]
## JavaScript, ES6 ~~352 340~~ 335 bytes, Potential score : 2 + 8 + 12 + 4 + 4 + 8 = 38
```
<script>r=Math.random,s=setTimeout;T=N=0;a=_=>(S=s(_=>(C=eval(G.innerHTML=((k=~~(r()*5))+~~(r()*5))+'-'+k),t=new Date,R=s(_=>C=G.innerHTML=a(clearTimeout(S)),r()*1e3)),r()*2e3+1e3),'');document.onkeyup=E=>{clearTimeout(R);E.key==C&&++N&&(T+=(X=new Date-t))&&alert([X,N%10?'':T/10]);C=G.innerHTML=a(N%10||(T=0))};a()</script><a id='G'/>
```
or try [this JSFiddle](http://jsfiddle.net/f3zs8dob/10/embedded/result/) on latest Firefox.
Working:
1. Shows a random question in form of `X-Y` after a random interval of [2,4] seconds.
2. Waits for a keypress till a random time in an interval of [1,2] seconds, after which, clears the input and moves to step 1.
3. If correct number is pressed, alerts the time in *milliseconds*.
4. If this is the tenth (or rather every tenth) correct answer, show the average time in milliseconds for the last 10 correct answers after a comma.
5. Empties the input area, goes to Step 1 again.
Please comment if something is incorrect or if you have any doubts.
[Answer]
**Ruby (237)**
```
def measure_time(v)
t = Time.now
puts "Enter the value: #{v}"
result = gets.chomp
if result == v
puts "CORRECT INPUT, TIME = #{(Time.now - t).to_f(2)} SECONDS"
else
puts "Incorrect"
end
end
```
[Answer]
**WIP, Python, 366 bytes, Potential score : 8 + 4 = 12**
```
import msvcrt as x
import random as r
import time,os
t=0
while t<11:
time.sleep(1)
n=r.randint(1,4)
m=r.randint(1,4)
print(str(n)+"+"+str(m)+"?")
time.sleep(.1)
t1=time.clock()
os.system('cls')
c=x.getch()
if int(c)==n+m:
print("Rct time:"+str(time.clock()-t1))
else:
print("Wrong char")
time.sleep(1)
t+=1
```
[Answer]
# Kivy Application 983 bytes, 26 points (8+8+2+4+4)
I used Python's application framework, Kivy, to create a GUI, just under the 1024 byte penalty.
The game starts with a textbox. Once you click it, a question of the form `A+B` or `A*B`, where A,B are between 1 and 10, is shown. To have quick input the user's answer is read as soon as the length of text in the textbox is the same length as the length of the correct answer. For example, if `7*4` is shown, the user's input will be read as an answer once they have entered at least two characters. If the user enters the correct value their response time in milliseconds is shown, otherwise "W" is displayed. The user's input and the question will immediately be hidden, followed by the next question displayed after a random interval of time between 0 and 1 seconds. Every time the user inputs 10 correct responses their average response time is shown for those ten responses.
To run this code you will need a Python interpreter with the Kivy library, and you will want to place both the python file and the kv file in the same directory and name the kv file g.kv. Then you can run the python file as usual.
**Python File**
```
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock as K
from random import randint as R, random as Q
import time
class GApp(App):
def build(s):
g=G()
K.schedule_interval(g.P, 0.01)
return g
class G(Widget):
def __init__(s):
super(G, s).__init__()
s.c=0
s.t=10*[0]
s.o=['+','*']
def on_touch_up(s,t):
s.U(0)
def U(s,J):
s.q.text=str(R(1,10))+s.o[R(0,1)]+str(R(1,10))
s.i=int(round(time.time()*1000))
def P(s,J):
A=s.r
B=s.q
C=s.u
if s.c==10:
A.text+=";"+str(sum(s.t)/10)
s.c=0
try:
S=str(eval(B.text))
except:
return
if C.text!=S and len(C.text)>=len(S):
A.text="W"
B.text=""
C.text=""
K.schedule_once(s.U, Q())
if C.text==str(S):
s.t[s.c]=int(round(time.time()*1000))-s.i
A.text=str(s.t[s.c])
s.c+=1
C.text=""
B.text=""
K.schedule_once(s.U,Q())
GApp().run()
```
**Kv File**
```
#:kivy 1.0.9
<G>:
u:u
r:r
q:q
Label:
center:100,400
text: "A"
Label:
center:100,300
text: "Q"
Label:
id: q
center:200,300
TextInput:
id: u
center:200,400
Label:
id: r
center:100,200
```
[Answer]
# JAVA: (8+8+2+4+4) = 26
Not going for shortest, just grabbing all bonus points first:
Code: (999 Bytes)
```
import java.awt.*;
import java.util.*;
import java.util.concurrent.*;
import javax.swing.*;
class Q
{
public static void main( String[] z ) throws Exception
{
Random r = new Random();
int v = 0;
String x = "FIRST ROUND";
ScheduledExecutorService e = Executors.newScheduledThreadPool( 1 );
for( int i = 0; i < 10; ++i )
{
int a = r.nextInt( 10 );
int b = r.nextInt( 10 );
long s = System.currentTimeMillis();
ScheduledFuture< ? > f = e.schedule( ( ) -> Window.getWindows()[ 0 ].dispose(), 3, TimeUnit.SECONDS );
String c = JOptionPane.showInputDialog( x + "\n" + a + "+" + b + "=" );
if( ( a + b + "" ).equals( c ) )
{
long t = System.currentTimeMillis() - s;
x = "CORRECT :" + t + "ms";
v += t / 10;
}
else
{
x = "WRONG";
v += 300;
}
f.cancel( true );
Thread.sleep( r.nextInt( 1000 ) );
}
e.shutdown();
JOptionPane.showMessageDialog( null, "Average: " + v + "ms" );
}
}
```
[Answer]
## APL(72), Score: 12+2+8=22
```
{a←?9⋄c←?9⋄b←⎕TS⋄⎕←a,'+',c⋄d←(⎕TS-b)×⎕=a+c⋄⎕←(5⌷d×60)+d[6]+7⌷d÷999⋄⎕DL(?⌊*9)÷*8}¨⍳⌊*9
```
Gets two random numbers between 1 and 9. Adds them together and asks the user the answer. If the answer is correct, it prints the reaction time in seconds. Else it prints 0. Repeats e^9=8103.08... times. Breaks when given a vector, a command or a variable name. But you could feed it ⌊\*1 (floor(e^1))and it would happily interpret it as 2. Gives a negative score if the answer is not given within the same hour because of the dumb system of APL timestamps.
] |
[Question]
[
1. Your program should take no input, and no network or other connections.
2. Your program should output it's sourcecode.
3. The sourcecode must consist of **3 types** of characters: Numeric (0-9), Alpha (a-z|A-Z) and symbols !(0-9|a-z|A-Z). Constraints for the distribution of characters is:
* 3.1. Every neighbouring characters with equal character-type makes a character-group.
* 3.2. Each character-group **length in bytes** must be a **prime**-number (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...)
* 3.3. The total number of **character-groups** of each character-type must be a **neighbouring (but not equal) fibonacci** sequence number. For example: 3 groups of numbers, 5 groups of alpha, 8 groups of symbols.
* 3.4. A character-group of one charater-type cannot be adjacent to another character-group of the same character-type, because that will create one bigger group instead.
**Example** valid sourcecode (regarding character distribution, it does however not output it's sourcecode):
```
"."."."aa321'","/hithere' 12345678901,.,.,12345,.,
```
Character distribution in the example: 2 groups of Alpha. 3 group of numeric. 5 groups of other characters. The numbers 2, 3 and 5 are neighbouring numbers in the fibonacci sequence.
This is code-golf, good luck have fun!
[Answer]
# Golfscript, ~~21~~ 15 characters
```
11{'aa.~' }aa.~
```
After removing all NOPs, their images, and the leading `11`, this becomes the quine
```
{`'.~'}.~
```
reading: block(string(dup, eval)); dup; eval.
~~Now to shoot for the stars (20 characters - the minimum for 2-3-5) or even galaxies (12 characters - the absolute minimum)~~ I've taken a short stop at Alpha Centauri B to refuel, now I'm drifting through intergalactic medium. Thanks, [Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture).
Live: <http://golfscript.apphb.com/?c=MTF7J2FhLn4nMTE7fWFhLn4K>
[Answer]
# PHP, some other languages - 12 bytes
```
22ab,,22,,22
```
PHP will print out the source code if it is not wrapped in some tag.
This is actually the smallest possible answer to the question. The smallest prime number is `2`, and the smallest distinct fibonacci numbers are `1`, `2`, and `3`. `3 + 2 + 1 = 6`. `6 * 2 = 12`
See a run here: <http://ideone.com/0NDA8A>
[Answer]
# Befunge 98 - 16 bytes
```
<@,*+982aa,,kd$"
```
This works only if your interpreter interprets line-wrap as adding a single space. This one works otherwise:
```
<@,*+982aa,,kd "
```
Character groups:
```
<@,*+ 5 chars, symbols
982 3 chars, numbers
aa 2 chars, alpha
,, 2 chars, symbols
kd 2 chars, alpha
$" 2 chars, symbols
```
So the fibonacci numbers are 1 (numbers), 2 (alpha), and 3 (symbols)
[Answer]
## Windows Command Script - 12 bytes (+ free folder bonus)
```
md 12##56##
```
Since every command is echoed by default, it's just a matter of finding the shortest command.
] |
[Question]
[
The [Champernowne constant](http://en.wikipedia.org/wiki/Champernowne_constant) is a transcendental decimal number whose digits are the concatination of all positive integers.
C10 = `0.12345678910111213141516...`10
The binary version of this is
C2 = `0.1101110010111011110001...`2
Write a program that prints C2 in decimal. The program should never halt. It should continue printing digits such that given infinite time and memory, it will print an infinite number of correct digits.
To illustrate this, you must account for integer overflow, since integer overflow will either cause an error or print incorrect digits, even with infinite memory available.
To test your code, here are the first 150 digits of this number.
```
0.862240125868054571557790283249394578565764742768299094516071214557306740590516458042038441438618133400466718933678923129464456214392016383510596824661
```
Shortest code wins.
[Answer]
## Python 119 bytes
```
import sys
r=i=n=0
while 1:
i+=1
for b in bin(i)[2:]:n+=1;r=r*10+int(b)*5**n;~n%4or sys.stdout.write(('0.'+`r`)[n/4])
```
Given unlimited memory, this will run indefinitely, although it does slow down quite a bit after the first few thousand digits.
Each binary bit is treated as its corresponding power of 5, i.e:
*0.1 ⇒ 5, 0.01 ⇒ 25, 0.001 ⇒ 125, 0.0001 ⇒ 625, etc.*
Which lends itself nicely to a decimal conversion, as:
*1/2 = 0.5, 1/4 = 0.25, 1/8 = 0.125, 1/16 = 0.0625, etc.*
The variable `r` stores a running total of all bits so far (increasing by a factor of 10 each iteration), and every four bits the next digit is output. This is mathematically correct, because
```
log2(10) ≈ 3.321928
```
which means that every `3.32` or so binary bits will produce one decimal digit. `10/3` is a better upper bound, but I chose `4` for sake of brevity.
## Ruby 80 bytes
```
r=i=n=0
$><<gsub(/./){"0.#{r=r*10+$&.to_i*5**n+=1}"[n/4,n%4/3]}while$_='%b'%i+=1
```
Same algorithm as above. It's been a while since I've golfed Ruby, so I may be missing a few tricks.
## GolfScript 53 bytes
```
0:µ.{).2base{5µ):µ?*@10*+.'0.'\+µ4/<µ(4/>print\}/.}do
```
Once again, same algorithm. This is one of the first things I've ever written in GolfScript, so I'm fairly certain that it can be reduced further. I've chosen to use `µ` (char 181) as a variable name, because it saves a whitespace in the expression `µ4/`.
[Answer]
# Mathematica 73 65 85
**Edit**:
```
s = {}; n = 1; While[n < 50, s = Join[s, IntegerDigits[n, 2]];
Print[N[FromDigits[{s, 0}, 2], n]]; n++]
```
Explanation:
`s` holds the base-2 digits of 1, 2, 3,...n, as a list of digits, `{1,1,0,1,1,1,0,0,...}`. Then `FromDigits` inserts the decimal point (with the `2` indicating the position), treating the input as a base-2 decimal and generating a base-10 decimal as output.
---
Using the built-in function: 51 chars
```
n=1;While[True,Print@N[ChampernowneNumber@2,n];n++]
```
[Answer]
## Python, 225
```
import sys,fractions
w=sys.stdout.write
w('0.')
h=t=10
l=n=0
p=fractions.Fraction(5)
i=int
while 1:
while i(h)!=i(l):
n+=1
for c in bin(n)[2:]:
if c=='1':l+=p
else:h-=p
p/=2
w(str(i(h)));h-=i(h);l-=i(l);h*=t;l*=t;p*=t
```
Note that the 4-space indentation should be tab characters. They seem to be converted to spaces when displayed here.
**Explanation**
`h` and `l` are the highest and lowest possible values for the current digit, as fractions.
For example, if h is `7/2` or `3.5`, the current digit is at most 3, and if it is 3, then the next digit is at most 5.
When `int(h) == int(l)`, we know what the next digit is, so we print that, subtract it from h and l, and multiply them by 10 to get the bounds for the next digit.
When `int(h) != int(l)`, we improve our bounds by looking further into C2. For the nth decimal place in the output and bth binary place in C2, a `1` means `l` increases by `10^n/2^b` and a `0` means `h` decreases by that amount.
[Answer]
### GolfScript, 71 characters
```
1.0.){:q,{\.+)q*+\.+q*\.)3$*2$/1$4$*3$/:&-!{&10%print@10*@@}*}/q.+s}:s~
```
Maybe not the best puzzle for GolfScript but tried a solution anyways. The code does iterates infinitely due to an unlimited recursion and prints the digits one after the next (one of the rare cases where the `print` built-in is needed).
Note that the [online version](http://golfscript.apphb.com/?c=MS4wLil7OnEse1wuKylxKitcLitxKlwuKTMkKjIkLzEkNCQqMyQvOiYtIXsmMTAlcHJpbnRAMTAqQEB9Kn0vcS4rIC4yNTY8e3N9Kn06c34gOzs7Ow%3D%3D&run=true) has a cutoff for the recursion.
] |
[Question]
[
With a twist; your algorithm has to be less complex than O(X2) where X is the Nth prime. Your solution post should include the character count and the theoretical complexity in terms of X (or N, which ~= X/ln(X) and so will usually be more efficient)
Here's a hint solution in C# (O(Xln(sqrt(X))), 137 chars):
>
> `public List<int> P(int n){var r = new List<int>{2}; int i=3; while(r.Count<n) if(!r.TakeWhile(x=>x<Math.Sqrt(i)).Any(x=>i%x==0)) r.Add(i++); else i++; }`
>
>
>
[Answer]
## J, 4 characters
```
p:i.
```
Usage:
```
p:i.10
2 3 5 7 11 13 17 19 23 29
```
The problem with using J here is that I don't really know how efficient it is. I'd assume that as a language specialising in "mathematical, statistical, and logical analysis of data", that the algorithm used to generate the primes is pretty good.
I did look at the [C source](http://www.jsoftware.com/source.htm) for clues, but it turns out that the C source for J is almost as unreadable as J itself. :-)
(The file is called v2.c for anyone who wants to have a look)
[Answer]
## C, 98 characters
The good old sieve method.
We assume the first N primes are among the first N\*24 integers. this works up to 2^32, because ln(2^32)<24. A general solution would need to estimate prime density, but since I use 32bit integers, I saw no need to generalize.
Complexity analysis (which I may do later) should use a formula instead of the constant 24.
```
i,j,m,*p;
f(n){
p=calloc(m=n*24,4);
for(i=2;n;i++)
if(!p[i])for(n--,printf("%d\n",j=i);p[j+=i]=j<m;);
}
```
[Answer]
## Haskell, ~~47~~ 46
Since the problem definition demands less than `O(X^2)` complexity, where `X ~= N*log(N)`, the following solution is acceptable. Its theoretical complexity is below `O(X^2)`, testing each number below `X` by all its preceding numbers until a divisor is found. For primes only, having `~ X/log(X)` primes overall, the complexity is thus `O(X^2/log(X))`. Most of the composites are multiples of small primes so are only divided few times, so they don't count.
```
p n=take n[n|n<-[2..],all((>0).rem n)[2..n-1]]
Prelude> last $ p 500
3571 (1.60 secs)
Prelude> last $ p 700
5279 (3.31 secs)
Prelude> logBase (5279/3571) (3.31/1.60) -- in X
1.8597116027280054
Prelude> logBase (7/5) (3.31/1.60) -- in N
2.1604889825177507
Prelude> last $ p 900
6997 (5.69 secs)
Prelude> logBase (6997/5279) (5.69/3.31)
1.9228821930296973 -- in X
Prelude> logBase (9/7) (5.69/3.31)
2.155714108637307 -- in N
```
If the complexity constraint in the problem definition will be amended to below `O(N^1.5)` (as I believe it should) then this solution will not be acceptable. That is why I post it in addition to another Haskell solution which is indeed better than `O(N^1.5)`.
[Answer]
## scala 191
Not the shortest one...
```
object P extends App{
def c(M:Int)={
val p=(false::false::true::List.range(3,M+1).map(_%2!=0)).toArray
for(i<-List.range(3,M)
if(p(i))){
var j=2*i;
while(j<M){
if(p(j))p(j)=false
j+=i}
}
(1 to M).filter(x=>p(x))
}
println(c(args(0).toInt))
}
```
Just measuring the method c, like the others do.
But how to prove, that it fulfills the Big-O requierement?
Well, I feed it with numbers, each twice as big as the number before. If it was of O(x²) complexity, it should need about 4 times as long, shouldn't it?
So I just measure it:
```
for p in {10..22}
do
/usr/bin/time scala P $((2**p))> /dev/null
echo "N="$((2**p))
done 2>&1 | tee primes.log
```
and then it's just a grep:
```
egrep -o "(^.*user|N=.*|#)" primes.log | tr "\n" "\t" | tr "#" "\n"
0.57user N=1024
0.54user N=2048
0.56user N=4096
0.59user N=8192
0.62user N=16384
0.66user N=32768
0.70user N=65536
0.77user N=131072
0.99user N=262144
1.48user N=524288
2.59user N=1048576
5.68user N=2097152
10.79user N=4194304
```
So in the beginning there is only a startup overhead of about .55s - later it is a linear growth. For N'=2\*N, t(N') ≈ 2\*t(N).
[Answer]
## Perl: 249 chars
The sieve certainly would have been shorter, but here is an implementation of the Miller-Rabin test:
```
sub p{
$n=shift;
$m=$n-1;
return$n==2||$n==3if$n<=3or!($n&1);
$s=unpack"%32b*",pack"L",($m&-$m)-1;
for(1..5){
next if($x=(int(rand($n-3))+2)**($n>>$s)%$n)==1||$x==$m;
map{($x=$x**2%$n)==1&&last;$x==$m&&next}(1..$s-1);
0}
1}
p($_)&&print"$_\n"for(1..$ARGV[0]);
```
Wikipedia says the runtime is O((log(X))^3)
[Answer]
# Ruby (91)
Almost same as the example, so should have similar complexity. Unless I'm still missing something obvious (almost used `select` instead of `take_while` to save a few chars)
```
q=->n{k=[2];p=3;while k.size<n;k<<p if !k.take_while{|x|x*x<=p}.any?{|x|p%x<1};p+=2;end;k}
```
and with some whitespace:
```
q=->n{
k=[2];
p=3;
while k.size<n;
k<<p if !k.take_while{|x| x*x <= p }.any?{|x| p%x < 1};
p+=2;
end;
k
}
```
[Answer]
# Ruby 37
```
require 'prime'
p Prime.take gets.to_i
```
] |
[Question]
[
How much can you golf a program to print ["An Old Irish Blessing"](https://codegolf.stackexchange.com/questions/1682/an-old-irish-blessing) **without using unprintable ASCII characters**?
That restricts us to ASCII characters 32-126 (better still, 32,65-90,97-122 and 13(CR))
For reference that version of the proverb is 205 characters long (excl. newlines).
I'm curious if anything beats Huffman-encoding incl. spaces.
[Answer]
### Golfscript, 198 characters
```
[]"-!9 4(% 2/!$<)3A50H/ -%%4 9/5
XXXN7).X\"?!,7I3>4UU2I!#+
[[[S35.;(`A[2- 50/.]]]&]%
YO2!U3F|,`/&4ZZZZZK)%,$3
!.$ }4),ze-%%Z!'!k\n-!9 '/S(/]hh )o4(%GG,/7 /&A)3;!v"{.32>{.58<{32+}{56-~1$>2<}if}*+}/+
```
**Output:**
```
$ ruby golfscript.rb blessing.gs
MAY THE ROAD RISE UP TO MEET YOU
MAY THE WIND BE ALWAYS AT YOUR BACK
MAY THE SUN SHINE WARM UPON YOUR FACE
THE RAINS FALL SOFT UPON YOUR FIELDS
AND UNTIL WE MEET AGAIN
MAY GOD HOLD YOU IN THE HOLLOW OF HIS HAND
```
The poem is compressed to 158 characters by using part of the ASCII range for back-references (of fixed length 2). The coding scheme is as follows:
```
[10] : newline (unencoded)
[32] : space (unencoded)
[33..57] : literal (33=A, 34=B, ... 57=Y, Z not needed)
[58..126] : back-reference relative to the end of the decompressed string so far.
```
The remaining 40 characters make up the decompression code which can probably be golfed a little further, since this is my first attempt at Golfscript.
---
**Case-sensitive version, 207 characters**
Same concept, but trading some of the back-reference range for lower case letters at the cost of some compression.
```
[]"-AY THE ROAD RISaUPhO MEET YOU
xxxnWINxB_ALWiS^TuuRiACK
{{{sSUN[HINa{RM UPON}}}F}E
4HoRAuS fLL SOFTzzzzzkIELDS
!NDlNTIwWE MEEzAGAIN
-AY 'OsHOLxYOU k THEggLOW OF (ISeAND"{.32>{.90<{32+}{88-~1$>2<}if}*+}/+
```
**Output:**
```
$ ruby golfscript.rb blessing-casesensitive.gs
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand
```
[Answer]
**Perl, 214 characters**
```
s//01road rise2 to 34
01w5d be always at4r back
01s7 sh5e warm284r face
The ra5s fall soft284r fields
And 7til we 3 aga5
0God 6d4 5 1 6low of His hand/;s/\d/('May ','the ',' up',meet,' you',in,hol,un,on)[$&]/eg;say
```
[Answer]
**Python, 263 chars**
```
t="""01road rise2 to34
01w5d be always at4r back
01s7 sh5e warm284r9ce
The ra5s9ll soft284r fields
And 7til we3 aga5
0God 6d4 5 16low of His hand"""
for k,v in enumerate("May ,the , up, meet, you,in,hol,un,on, fa".split(',')):
t = t.replace(str(k),v)
print t
```
which was an 'improvement' on my 261-char quick hack, obviously inferior to a simple print.
```
s="""12road rise up to34
12wind be always at4r back
12sun shine warm54r face
The rains fall soft54r fields
And until we3 again
1God hold4 in 2hollow of His hand"""
for k,v in {1:"May ",2:"the ",3:" meet",4:" you",5:" upon"}.items():
s = s.replace(str(k),v)
print s
```
enumerate() takes almost as many chars in creating the dict/sequence, on a short example like this.
[Answer]
## PHP, 203
Base64 is ASCII only, but I'd still consider this slightly exploitive.
```
<?=gzinflate(base64_decode('TY5BDsMwCATvecV+hcQkRsWmMras/P8jpW5V9bhidodCN3pmNKOEJs4YT3RDYe64bWzlC0ypCTuDdNLtoHVt2Ol4/BgfFZ6lBk2txJLVD3XSwdvSkFSPqAq3s/8jwpp8o7CM2kUx+fMEXdFZissSsml6FyB1KSOrTdiJLI4c9Rc'));
```
[Proof it works.](http://ideone.com/rcG3i)
[Answer]
Python, 224 chars
```
print'''1road rise up to meet you
1wind be always at your back
1sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand'''.replace('1','May the ')
```
Instead of wasting characters on for loops or multiple replaces, I only have one replace with the single most common combinations of words `May the`
[Answer]
# [Io](http://iolanguage.org/), 217 bytes
Compressing the string leads to a longer length...
```
"May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand"print
```
[Try it online!](https://tio.run/##TY5BDsIwDATvfcWKn3CCCzc@4DYpsUjtKk4U9fUhbQXiuPLsjllbuzxoQw4eSckhsXmUFVmxeJ@xaRm@QGVxGD0oVtoMdFwTRpreP8aKwAJLpyktfUnlpGaa/PDcNcRiPcYI0zn/I@yjs@HaLUUyR1R/PkGv3jkUN3UIGt1eAMuh7Dlqhc64syGQuMuaWHJrHw "Io – Try It Online")
] |
[Question]
[
The [wizard](https://codegolf.stackexchange.com/questions/251029/optimal-strategy-to-defeat-the-wizard) has a cunning cousin who is a witch. She looks down on the wizard, regarding him and his puzzles as mathematically naive. On reading his latest puzzle, she scorned him for always asking discrete problems with what she (unfairly) characterises as simple solutions, where the real, proper question should be continuous. To prove her point she poses the following version of the wizard's puzzle. (He reluctantly permits the partial plagiarism.)
Consider the following setup. A cunning witch has a real number line stretching from 0 to 10 which is hidden from you. Also hidden from you she chooses a random integer \$x \in \{0, \dots, 10\}\$ and places that many points onto the number line uniformly at random. To be more precise, she places each of the \$x\$ points independently and uniformly at random onto the number line. Your task is to prove that \$x = 10\$ and if you do the witch will grant you what she promises is a much better wish than what her cousin can provide.
In this game, you can at each step choose a floating point number \$y\$ and the witch will tell you the number of points on the number line with value less than or equal to \$y\$.
However the witch, being at least as evil as her cousin, will not let you choose a number larger than \$9\$. This might still be OK as you might still find 10 points and in fact the only way to be granted the wish is to have found all 10 points with values 9 or less.
The cost for choosing a floating point number \$y\$ is \$2^{y}\$ dollars. At any point, you can choose to give up on this set of points and get her to start the whole process again (with a new random \$x\$). Of course, if you choose the number 9 and you still have not found 10 points you have no choice but to give up and start again. But you might want to give up after having chosen a number smaller than 9. Sadly you never get any money back so your costs just carry on building.
Your goal is to devise a strategy that will get you the wish at the minimum expected cost. You should report your mean cost.
# Testing
Once you have chosen your strategy, you should run it until you get the wish 10,000 times and report the mean cost. If two answers have the same strategy, the one posted first wins. If two strategies have similar mean costs you may need to test it 100,000 or even more times to tell the difference. Of course if you can directly compute the expected cost, all the better.
# Input and output
There is no external input in this challenge. The output is just the mean cost to get a wish. To test your code you will need to implement both the witch and your strategy.
# What's a naive score?
If you just choose 9 each time then it will take you \$\frac{1}{\frac{1}{11} \cdot \frac{9}{10}^{10}} \approx 31.5\$ tries to find 10 points. This will cost you approximately \$16152.4\$ dollars. How much better can you do?
# Notes
You can assume that floating numbers are precise mathematical real numbers when evaluating your code and that the random number generator from your favourite library is perfect (except please don't use the default [rand()](https://www.gnu.org/software/libc/manual/html_node/ISO-Random.html) in C which is truly terrible).
[Answer]
# R / Rcpp: 2641.844 ± 1.132
Evaluated on 15 million simulated games. Bounds are a 95% bootstrap confidence interval with 10,000 iterations.
Posting on behalf of my cousin who looks down on reinforcement learning, as in my solution to the Wizard's puzzle. "Reward shaping? If it's any good you've already solved the problem." To prove her point she poses the following heuristic solution to the witch's puzzle.
## Method
The policy was learned using a genetic algorithm with an initial population of 500 chromosomes. Fitness for each chromosome was calculated by evaluating its corresponding policy over 50,000 games.
All chromosomes with fitness above the median (the half of the chromosomes with the lowest mean evaluated cost) were selected at random to reproduce, and the remaining chromosomes were discarded. Reproduction continued until the population returned to its original size.
The crossover operator was a uniform heuristic crossover with an expected crossover rate of 50%, and an expected scaling coefficient of 0.5. Because my crossover operator chooses uniform random values for the crossover rate and scaling coefficient every time it is called, I chose to only produce one offspring per operation to increase offspring randomness / exploration.
The mutation operator was defined to replace target genes with uniform random values, and the mutation rate was set to 0.001.
## Policy Representation
My goal was to do as well as possible with a minimalist policy representation, so each chromosome is a numeric vector length 20. For a chromosome notated \$[p\_{0}, p\_{1}, ... , p\_{10}, p\_{11}, ... , p\_{19}]\$, its corresponding policy is calculated as:
$$
\begin{bmatrix}
0 & p\_{11}\\
p\_{0} + p\_{1} & p\_{12}\\
p\_{0} + ... + p\_{2} & p\_{13}\\
. & .\\
. & .\\
. & .\\
p\_{0}+...+p\_{10} & p\_{19}\\
\end{bmatrix}
$$
The zero-indexed policy matrix, \$p\$, is interpreted as follows: Let \$\lambda\$ be the length of the number line searched, starting at zero. For \$n\$, the number of points found, if \$\lambda \leq p(n, 0)\$ then \$\lambda = lambda + p(n, 1)\$, otherwise reset.
In other words, the policy describes a distinct rate at which the line should be searched, \$p(n, 1)\$, given it has found \$n\$ points before having searched \$p(n, 0)\$ of the line.
## Learned Policy
After 200 generations, I selected the chromosome with the highest fitness, whose policy is approximately:
$$
\begin{bmatrix}
0.00 & 1.07\\
0.90 & 0.00\\
1.74 & 2.46\\
2.52 & 2.65\\
3.25 & 4.11\\
4.66 & 1.65\\
4.66 & 2.91\\
5.67 & 9.00\\
9.00 & 5.58\\
9.00 & 2.78\\
\end{bmatrix}
$$
This policy slowly searches the first half of the line until it finds enough points that it is worth searching the remainder of the line. At that point, it searches large chunks of the line to minimize cost. If it doesn't find enough points early on, it will reset (even though it may have been possible to find all 10 points).
For a more intuitive understanding of why the policy works and how it defined good step sizes, suppose we calculate the cost of searching some amount of the number line given we have already searched \$\lambda\$ as
$$
\text{Line per Cost} = \frac{p(n, 1)}{2^{p(n, 1) + \lambda}}
$$
From the formula we can see that as \$\lambda\$ increases, the cost of searching the additional \$p(n, 1)\$ also increases.
To understand this policy, consider when \$\lambda = p(n,0)\$, which corresponds to the worst scenario for which the policy will continue to search the line. Plotting the line per cost vs. the number of points found gives the below black points.
The blue points are \$\frac{1}{2^{n+1}}\$, which corresponds to the line per cost given by searching the number line in units of one if you expect to find one point in each unit.
[](https://i.stack.imgur.com/bgvkD.jpg)
So from the plot we can see that the learned policy has worst case preferences that nearly match what you get if you expect to find a point every time you search one unit of the number line. Note: Though the learned policy does not match \$\frac{1}{2^{n+1}}\$ for the \$n = 1\$ case, repeated testing shows that skipping over the case where only one point has been found tends to improve the policy's score.
## Convergence Rate
I chose learning parameters to provide a smooth descent towards an optimal solution, and in the plot of the learning curve below that the population appears to find local minimums around the 20th and 30th generations before setting into the learned policy area somewhere between generations 100 and 150.
[](https://i.stack.imgur.com/geX4Y.jpg)
## Code
**Rcpp Code to Define the Genetic Algorithm**
```
#include <Rcpp.h>
using namespace Rcpp;
//* Generate Points
// [[Rcpp::export]]
NumericVector setPoints() {
//Sample number of points
NumericVector pointSet = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numPts = Rcpp::sample(pointSet, 1)[0];
//Return
return(Rcpp::runif(numPts, 0.0, 10.0));
}
//* Generate Chromosome
// [[Rcpp::export]]
NumericVector generateChromosome() {
return(Rcpp::runif(20, 0.0, 2.0));
}
//* Crossover
// [[Rcpp::export]]
NumericVector crossover(
NumericVector x,
NumericVector y
) {
//Parameters
NumericVector params = Rcpp::runif(2, 0.0, 1.0);
NumericVector randVals = Rcpp::runif(x.length(), 0.0, 1.0);
LogicalVector doCross = (randVals <= params[0]);
//Apply crossover
NumericVector offspring = clone(x);
for(int i = 0; i < x.length(); i++){
if(doCross[i]){
NumericVector v = {params[1] * (x[i] - y[i]) + x[i]};
v = Rcpp::clamp(0.0, v, 9.0);
offspring[i] = v[0];
}
}
//Return
return(offspring);
}
//* Mutate
// [[Rcpp::export]]
NumericVector mutate(NumericVector x, double rate) {
NumericVector x_new = clone(x);
NumericVector randVals = Rcpp::runif(x.length(), 0.0, 1.0);
LogicalVector doMutate = (randVals <= rate);
for(int i = 0; i < x.length(); i++){
if(doMutate[i]){
x_new[i] = Rcpp::runif(1, 0.0, 9.0)[0];
}
}
return(x_new);
}
//* Chromosome to Policy
// [[Rcpp::export]]
NumericMatrix chromToPolicy(NumericVector x) {
NumericVector policy = clone(x);
double sumVal = 0;
for(int i = 0; i < 10; i++){
sumVal += x[i];
if(sumVal > 9){
sumVal = 9;
}
policy[i] = sumVal;
}
policy[0] = 0.0;
policy.attr("dim") = Dimension(10, 2);
return(as<NumericMatrix>(policy));
}
//* Evaluate
// [[Rcpp::export]]
NumericVector evaluatePolicy(
NumericVector x,
int iters,
int maxCost = -1
) {
//Convert chromosome to policy
NumericMatrix policy = chromToPolicy(x);
//Run episodes
NumericVector out (iters, 0.0);
bool earlyStop = false;
for(int i = 0; i < iters; i++){
//Initialize values
NumericVector points = setPoints();
double lineSearched = 0;
int ptsFound = 0;
//Begin episode
bool done = false;
while(!done) {
//Step forward if in policy
if(policy(ptsFound, 0) >= lineSearched){
lineSearched += policy(ptsFound, 1);
if(lineSearched > 9){
lineSearched = 9;
}
out[i] += pow(2, lineSearched);
ptsFound = sum(points <= lineSearched);
} else {
//Otherwise, reset
points = setPoints();
lineSearched = 0;
ptsFound = 0;
}
//Reset when line searched but fewer than 10 points found
if(lineSearched == 9 & ptsFound < 10){
points = setPoints();
lineSearched = 0;
ptsFound = 0;
}
//Exit conditions
if(ptsFound == 10){
done = true;
}
//Early stop condition
if((maxCost >= 0 & out[i] >= maxCost)){
out[i] = NA_REAL;
earlyStop = true;
done = true;
}
}
if(earlyStop){
break;
}
}
return(out);
}
```
**R Code to Run the Algorithm**
```
#----- Initialize Population -----
#Generate seed population
#Because random chromosomes are often slow to evaluate
#Seed with random chromosome s.t. max(cost) < 50,000
size <- 500
population <- t(sapply(1:size, function(c){
generateChromosome()
}))
#Calculate fitness
fitness <- sapply(1:nrow(population), function(i){
mean(evaluatePolicy(population[i,], 50000, 50000))
})
#Increase yield
population <- population[!is.na(fitness),]
while(TRUE){
#New population
newPopulation <- t(sapply(1:size, function(c){
generateChromosome()
}))
newFitness = sapply(1:nrow(newPopulation), function(i){
mean(evaluatePolicy(newPopulation[i,], 50000, 50000))
})
population <- rbind(population, newPopulation[!is.na(newFitness),])
#End
if(nrow(population) >= size){
rm(newFitness, newPopulation)
break
}
}
#----- Evolve -----
#Parameters
rounds <- 200
#Iterate over generations
for(i in 1:rounds){
#Calculate fitness
fitness <- sapply(1:nrow(population), function(i){
mean(evaluatePolicy(population[i,], 50000, 100000))
})
#Subset population
population <- population[which(fitness <= median(fitness, na.rm = TRUE)),]
#Crossover
population <- rbind(population, t(sapply(1:(size - nrow(population)), function(i){
inds = sample(1:nrow(population), 2, FALSE)
crossover(population[inds[1],], population[inds[2],])
})))
#Mutate
population <- t(sapply(1:nrow(population), function(i){
mutate(population[i,], rate = 0.001)
}))
}
```
[Answer]
# Python, score = 2610.6431 (2610.5938 with 400 guess values)
Finds the optimal policy over a discrete set of equally spaced possible guesses (200 by default).
Here's a plot of new guess vs old guess for each number of found points; a guess of 0 means resetting. Make of it what you will.
[](https://i.stack.imgur.com/twMZm.jpg)
```
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import binom
bound = 16153
samples = 200
g = np.linspace(0, 9, samples)
def logsumexp(x):
m = x.max()
return np.log(np.sum(np.exp(x - m))) + m
def init_trans(samples):
print("computing transition matrix...\n")
trans = np.full((samples, 10, samples, 11), float('-inf'))
g = np.linspace(0, 9, samples)
for i0 in range(samples - 1):
print(f"computing row {i0} of {samples}", end='\r', flush=True)
g0 = g[i0]
for n in range(10):
k = np.arange(n, 11)
u = np.zeros(k.shape) if i0 == 0 else binom(k, g0 / 10).logpmf(n)
for i1 in range(i0 + 1, samples):
g1 = g[i1]
d = binom(k - n, (g1 - g0) / (10 - g0))
for m in range(n, 11):
v = d.logpmf(m - n)
trans[i0,n,i1,m] = logsumexp(u + v)
print()
trans -= trans.max(axis=-1, keepdims=True)
trans = np.exp(trans)
trans /= trans.sum(axis=-1, keepdims=True)
return trans
trans_file= f'trans_{samples}.npy'
try:
trans = np.load(trans_file)
except FileNotFoundError:
trans = init_trans(samples)
np.save(trans_file, trans)
def get_policy(trans):
print("estimating policy...")
values_file = f"values_{samples}.npy"
policy_file = f"values_{samples}.npy"
grad = np.zeros((samples, 11))
values = np.zeros((samples, 11))
policy = np.zeros((samples, 11), dtype=np.int64)
x = bound
while True:
values[-1,:-1] = x
grad[-1,:-1] = 1
for i0 in range(samples - 2, -1, -1):
for n in range(10):
g1 = g[i0+1:]
v1 = 2 ** g1 + np.einsum('ij, ij -> i', trans[i0,n,i0+1:,n:], values[i0+1:,n:])
di = np.argmin(v1)
i1 = i0 + di + 1
if v1[di] <= x:
values[i0,n] = v1[di]
grad[i0,n] = np.sum(trans[i0,n,i1,n:] * grad[i1,n:])
policy[i0,n] = i1
else:
values[i0,n] = x
grad[i0,n] = 1
policy[i0,n] = 0
if values[0,0] >= x:
break
x += (values[0,0] - x) / (1 - grad[0,0])
print(f"computed cost = {x}")
return values, policy
values_file = f"values_{samples}.npy"
policy_file = f"policy_{samples}.npy"
try:
values, policy = np.load(values_file), np.load(policy_file)
except FileNotFoundError:
values, policy = get_policy(trans)
np.save(values_file, values)
np.save(policy_file, policy)
for i in range(10):
plt.subplot(2, 5, i + 1)
plt.plot(np.linspace(0, 1, samples), policy[:,i], color='blue')
plt.show()
print('running simulations...')
mean_cost = 0
cost_m2 = 0
for t in itertools.count():
cost = 0
while True:
n = random.randrange(11)
p = [10 * random.random() for _ in range(n)]
i0 = 0
f0 = 0
done = False
while True:
i1 = int(policy[i0,f0])
if i1 == 0:
break
g1 = g[i1]
assert (0 <= g1 <= 9)
cost += 2 ** g1
f1 = sum(1 for x in p if x <= g1)
if f1 == 10:
done = True
break
if i1 == len(g) - 1:
break
i0 = i1
f0 = f1
if done:
break
mean_cost1 = mean_cost + (cost - mean_cost) / (t + 1.)
cost_m2 += (cost - mean_cost) * (cost - mean_cost1)
mean_cost = mean_cost1
if t % 1000 == 0:
print(f"{t} trials run, cost = {mean_cost} ± {np.sqrt(cost_m2 / (t + 1) ** 2):.3f}")
```
[Answer]
# Rust, score= ~6,081.9
Guesses each number 1-9. Aborts if the number found is less than 0.8 \* number.
Anyone is free to copy this answer and further optimize the parameters (0.8 abort limit and 1.0 step size) or of course modify anything else.
```
use rand;
use rand::{Rng, RngCore};
struct Which {
rng: rand::rngs::ThreadRng,
numbers: Vec<f32>,
score: f32
}
impl Which {
fn new(rng: rand::rngs::ThreadRng) -> Which {
return Which{rng: rng, numbers: vec![], score: 0.0};
}
fn regenerate(&mut self) {
let number = self.rng.next_u32()%11;
self.numbers = (0..number).map(|i|self.rng.gen::<f32>()*10.0).collect();
}
fn guess(&mut self, n: f32) -> usize {
self.score += 2.0_f32.powf(n);
self.numbers.iter().filter(|i|**i<n).count()
}
}
fn algo(which: &mut Which) {
which.regenerate();
loop {
let mut guess = 1;
while guess<=9 {
let number = which.guess(guess as f32);
if number >= 10 {
return;
}
if (number as f32) < (guess as f32) * 0.8 {
break
}
guess+=1;
}
which.regenerate();
}
}
fn main() {
let mut total_score:f64 = 0.;
for _ in 0..10_000 {
let mut which = Which::new(rand::thread_rng());
algo(&mut which);
total_score+=which.score as f64;
}
println!("total score: {:?}", total_score/ 10_000.);
}
```
Basic starter answer, probably not even close to optimal.
[Answer]
# Javascript, average cost = $~4975
Is that how the scoring works? I don't have time to test this another 50 million times or so rn haha
Not the best score so far, but just something I wanted to try. I do have one other idea I want to try that uses a new strategy but I'll only post it if it performs decently :P
This code checks if there are at least 5 points below 5. If there are, it goes all in and checks below 9. Either way, after that it gives up.
```
cheater=_=>cheater()
//this crashes the program if i try to check higher than 9 :P
witch=_=>{ //witch takes no input
let z=Math.floor(Math.random()*11)
//selects an integer from 0 to 10
let points=[]
for(let i=0;i<z;i++){
points.push(Math.random()*10)
//plots that many points on the line from 0 to 10
}
return x=>x>9?cheater():points.filter(w=>w<x).length
//and returns a function which takes n as input and outputs how many points exist below n (or crashes if n>9)
}
solver=_=>{
let current=witch()
//calling witch generates a new set of points, which i can check with current
let cost=0
while(1){
cost+=2**5
//i pre-emptively add the cost of each inspection on the line
if(current(5)==10){
return cost
}else if(current(5)>4){
//i think its ok to use the same inspection twice at no cost, because theres no new information, and its just easier and nicer looking than storing the result in a variable or something
cost+=2**9
if(current(9)==10){
return cost
}
}
current=witch()
//this is the "give up" part
}
}
tester=(m)=>{
//m is the number of iterations to test
let costlist=[]
for(let i=0;i<m;i++){
costlist.push(solver())
}
return costlist.reduce((a,b)=>a+b,0)/costlist.length
//returns the average cost
//i ran tester(10000000) thrice and got 4972.0177856, 4972.7681056, and 4974.2599296.
}
```
] |
[Question]
[
*Who's up for a second attempt?*
If you've ever listened to the radio program "I'm sorry, I haven't a clue", then you've probably heard of the game called "Mornington Crescent". For those who haven't, it's a game where players name random stations on the London Underground network. The first person to name "Mornington Crescent" wins the game.1
[Very much like last time](https://codegolf.stackexchange.com/questions/209889/codington-crescent), I present to you another game of **Codington Crescent**.
## The Challenge
The winner of this challenge is the first person to post a working program that, given a variable-sized list of positive integers, returns the average (arithmetic mean) of said list. The list will not be empty and will always have at least one item. Input and output can be given in any reasonable and convenient format
### Test Cases
```
[150, 541, 168, 225, 65, 191, 964, 283, 825, 5, 802, 426, 45, 326, 22, 619, 281] => 349.29411764705884
[874, 33, 423, 36, 1000, 255, 345, 902, 700, 141, 916, 959, 222, 246, 96] => 476.53333333333336
[567, 868, 680, 121, 574, 391, 233, 39, 764, 499, 455, 684, 742, 117, 376] => 474.0
[177, 372, 778, 709, 474, 796, 840, 742] => 611.0
[181, 751, 940, 782, 727, 756, 541, 762, 677, 751, 719] => 689.7272727272727
[47, 804, 782, 231, 170] => 406.8
[315, 972] => 643.5
[679, 727] => 703.0
[859, 229, 363, 468, 103, 104, 570, 772, 83, 693, 898, 672, 306, 733, 189, 717, 231] => 470.0
[228, 839] => 533.5
[395, 622, 760, 820, 70, 814, 797, 202, 277, 663, 93, 218, 564, 735] => 502.14285714285717
[724, 631, 932, 333, 605, 880, 670, 468, 703, 744, 680, 28] => 616.5
[950, 733, 305, 178, 995] => 632.2
[762, 506, 553, 284, 499, 694, 665, 998, 576, 504, 123, 658, 943, 385, 354, 732] => 577.25
[151, 919, 514, 721, 426, 333, 808, 514] => 548.25
[995] => 995.0
[891, 243, 42, 968, 458, 372, 301, 269, 559, 394, 980, 372, 804, 429, 738] => 521.3333333333334
[147, 473, 632] => 417.3333333333333
[105, 483, 225, 541, 684, 456, 328] => 403.14285714285717
[311, 1, 770, 417, 910, 185, 375, 631, 226, 266, 609] => 427.3636363636364
```
[Test case generator](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoMS8lP5eLKy2/SCFPITMPJJCeqqBhZKBpxaUABDmpeeklGQq2UJV6ICozr0TDUEcBqAaiJBMoHY0pb2hgoKmAarAGxDjNWC6wzoIikNKcTB0FJVs7JR2F4tJcIE9TQR9qrSbX//8A "Python 3 – Try It Online")
## The Rules
1. Each player has their own program that they will add/change characters. This is termed their **running program**.
In this way, the only answer-chaining aspect is the rules. Everyone uses their own running program. No one shares a program at all
2. Each answer (a **turn**) has to obey source restrictions defined by previous answers. These are called **rules**. Each variant lasts for 5 **turns**. Rules are in the form of [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") restrictions.
3. Running programs can change languages between turns.
4. Answerers (players) can either add, change or remove (but only one of the options) as many characters of their running program per turn as they like. Alternatively, they can choose to "pass" ([more scientifically](https://kevan.org/morningtonia.pl?action=browse&diff=1&id=Farkle), **farkle**), adding no new rules, and still counting as a turn. This may be the only choice if rules conflict with each other. The turn count is still incremented and is to be posted. Pro tip: You probably might want to mark it community wiki because it doesn't add much.
5. At the end of each turn, the player declares a new rule that will span the next 5 turns. Rules must be objective, and a TIO verification program is highly recommended. Also, rules have to be able to be applied to every language (e.g. `Programs must not error using Python 3.4.2` isn't a valid rule).
6. Play continues until a running program achieves the target result.
7. If a turn hasn't been taken for a week, then an implicit *farkle* will occur. You can always take a turn after an implicit farkle, as it counts as a turn (think of it as the Community user's turn).
## Starting Rules
As to kick off the game, the first 5 turns must follow these rules:
1. Turns may not accomplish the end goal
2. Minimum program length is 10 bytes
## Permanent Rules
Last time, it was noted that the following rules suited better as a permanent rule rather than 5-turn rules:
3. Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
4. A program cannot win within 5 turns of its first appearance
## Example Rules
These are purely examples of what you could add as rules to the challenge. They do not apply unless someone decides to use them.
* **The first and last character of the running program must be a space**
* **Running programs must have an even amount of bytes**
* **Running programs must not be more than 30 bytes**
## Extra Answer Chaining Rules
* You cannot answer twice in a row. Someone else needs to answer before you have another go.
* Languages need to be on Try It Online to be valid answers.
**Pro-tip: sort by [oldest](https://codegolf.stackexchange.com/questions/211322/more-codington-crescent) for a more cohesive flow of answers**
1 The original game of Mornington Crescent doesn't really have rules... It's more of an activity that looks like it's a complicated game.
## Answer Template
```
# [Language], turn number [your turn]
<code>
[Try it online link]
[prev answer link]
## Rules
- Rule (n turns left)
- Rule (n turns left)
- Rule (n turns left)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), turn 3
```
$XY~sDOsg/*+
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fQSEisq7Yxb84XV/r//9oQx0FIx0FYx0FEx0F01gA)
(How do I link to previous answer?)
Boy do I love Code Golf!
### Explanation
```
$ # Push 1 and input
X # Push 1
Y # Push 2
~ # Converts 1 and 2 to 3
s # Swap to get implicit input
D # Duplicate
O # Sum the list
s # Swap top 2 values and gets the preserved list.
g # Push the length of the list.
/ # Push the quotient of sum and length
* # Multiply with 3
+ # Add with one
```
## Current rules
* Turns may not accomplish the end goal - Prints the triple the average plus one (**2 turns left!**)
* Minimum program length is 10 bytes (3 turns left) - Length of the program is 12 bytes (**2 turns left!**)
* Programs must contain the ~ character - The character is supposed to push the bitwise OR of 1 and 2 (*3 turns left!*)
* Programs must have an average byte value of less than or equal to 80 - The average byte value of the program is 79.25 (4 turns left!)
### The new rule
*Drumroll*
---
The program must include 5-10 non-alphanumeric characters (5 turns left!)
[Answer]
# [Io](http://iolanguage.org/), 20 bytes
Returns the average+1.
```
method(~,~average+1)
```
[Try it online!](https://tio.run/##FYrNCsMwDINfxceE@lC7iUkKe5NdCk23QP9ow4599cwBSUgfykddYHzBu26pfI/ZPPhMv3RNn9SRrYtZ810M@R7BO0IgCQjMHkHUFBVFcYrCgBAaV4WeERyLhq6hFVYiFNuRrIXzyntZ9/oH "Io – Try It Online")
## Rules
the first 5 turns must follow these rules:
* Turns may not accomplish the end goal
* Minimum program length is 10 bytes
this applies for all running programs:
* Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
* A program cannot win within 5 turns of its first appearance
New rule:
* Programs must contain the `~` character
[Answer]
# [Python 3](https://docs.python.org/3/), 23 bytes, turn 2
```
lambda l:sum(l)/~len(l)
```
[Try it online!](https://tio.run/##FYxNCgIxDIWvkmULAdtmJkkFT6IuRnRQ6NRBx4Ubr17Tzffg/a3f7f6s1GY4wKmVablcJyj792dxxe9@5VZN2/p61M3N7qhjRkjJQEwIAytCDNQxIIwSEEQSgprF2aDZGtwtCmwh9a7aXqLYE8Wz9@0P "Python 3 – Try It Online")
Input as a list of floats; outputs as a float.
## Rules
Permanent rules:
* Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
* A program cannot win within 5 turns of its first appearance
Current rules:
* Turns may not accomplish the end goal (3 turns left)
* Minimum program length is 10 bytes (3 turns left)
* Programs must contain the `~` character (4 turns left)
My new rule:
* Programs must have an average byte value of less than or equal to 80. ([verifier](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69Eo7g0V6PAyjZJXV090j80SCEgyN89yNFXwcM1yFVBV6Eyv1QhN7FSIS81NUWhJF8htTg5sSBVoTg/N1UhP00hswSoT1M/JzVPo0DTxtbCQM9A8/9/AA))
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 13 bytes, turn 5
(turn 4 was an implicit farkle)
```
"PDPF"4(~FP@
```
This answer is far from winning, but I'm including some characters an average program in this language will likely need, and keeping the challenge alive.
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XCnAJcFMy0ahzC3Dg@v/fBQA "Befunge-98 (PyFunge) – Try It Online")
[Previous answer](https://codegolf.stackexchange.com/a/211328/46076)
Rules:
* Programs may not accomplish the end goal (last turn)
* Minimum program length is 10 bytes (last turn)
* Programs must contain the ~ character (1 turn left)
* Programs must have an average byte value of less than or equal to 80. (2 turns left)
* The program must include 5-10 non-alphanumeric characters (3 turns left!)
* Programs may not contain 2 consecutive lowercase letters (5 turns left)
] |
[Question]
[
# The riddle
In yesterday's newspaper, I found a puzzle in which a Rook should start in the lower-left corner of a 12x12 checkerboard and then, during a round trip, visit each field exactly once except for a selection which must be avoided. The puzzle came with a picture that identified the fields to be avoided as black:
[](https://i.stack.imgur.com/MUw7f.png)
After some minutes, I came up with a solution, that you can find [here.](https://www.overleaf.com/read/gtnkgtvhywkd)
(There's no pic of the solution because you might want to challenge yourself by solving it first...)
# The challenge
To write code that produces the same output as my code (that's in TikZ):
```
\documentclass[tikz,border=1cm]{standalone}\def~{document}\begin~\tikz{\def~{)rectangle++(,)(}\filldraw[step=1]grid(12,12)(8,0~4,~0,3~8,5~11,5~,8~11,9~2,10~4,11~7,11~,);\def~#1#2#3{)-|++(6-#1,4-#2)-|++(6-#3,4-}\draw[line width=2mm,red](.5,.5~1355~5353~5356~7540~7375~7575~7375~7373~7372~5555~5553~5552~7375~7373~7345~5355~5555~5355~5272~5395~5673~7373~7583~9555~7955~5555~8376);\fill[blue](.5,.5)circle(.3)}\end~
```
of the picture that shows the solution to the Rook's Round Trip. This is Code Golf!
# Requirement(s) for the In-/Output
* Use whatever language you want.
* From your output, be able to somehow produce the pixelwise
exact same PNG as in the code section below.
PNG code
```
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABXoAAAV6AgMAAAAuWCySAAAADFBMVEX///8AAAD/AAAAAP8xSkYMAAAKsklEQVR4Aezdx5HcRhSA4a2aOz2TYBLDEOg6CUSxSeAuRwclsfHotFdZSBiJLftqt7deA0Po+6+vHlDzVcuCM7g4myRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJksqt04s7+D5fYVCiwo0H0eBp82d/0HvAly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvlNylw2+N9z8ixbfZ1NuX5ynL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fC9Tnh/f3jfYePB3rXbfGKVl8IwvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX75840ptWhpLQvVSCRvDMnhbGmrcaLjUi1XOb/tpbD/xD9pP47bnly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvny7v80tLvaN+2KjDb58+fLly5cvX758+fLly5cvX758+fLly5cvX758+W7rG8M3+7bfI//ZbryR8sSZL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fMvNnXzHcmYN02+9Tdi4/aVerHJ+442dnN+nfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5Zv//reWjfZL5b+0jS9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvvv0DT57341gkP+YmC9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnyzfUttWhpLQ4kb4WBYBm9LXLiRMOh5fkvU7s9vfA++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPnyTfHNf2Nc6Bv2xRobfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny3YFv1g+r1hIeEwcb6ffgy5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cv31I7oYwlo8RLhQ3LPd6ueo8XDa7Jh8755cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL99gEJa0sf1r3vjy5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5bsD34ZB1j3aP2K8kTqo8eXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLl2+pTUtjqbUMghIuNSyDtyUu3kgfvNjs/Dq/fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5bvpi+G2e81b0C58+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLlW0vYqGU8Jq51HfDly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5dvqZ1QxlKLB3HxRnrDco+3Zc1e/I/P79NmlPAeTz8fX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLlG7bGxhcpvje8Rm8Hvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58k3fCAcBY5ZvwqVqfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5Vtq09JYGsrbiAfDMngbD+JSLuX81kFQ/qX48uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXL99xe8xb7hn2xwcZmvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58t30wXLDk9rGx8S9L8WXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++5eZOWmM8jzc2aVhu/rbHpV5k+jq/CeeXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPu/GG7717ztwJcvX758+fLly5cvX758+fLly5cvX758+fLly5cvX77pP6waD+KP2P7ZEy7Fly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLtyW+fPny5cuXL1++fPk2dEIZMzbiwbAM3jYMgoKNpsGLO/g+v/vA+eXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly/fM3nN22Xn17ztyZcvX758+fLly5cvX758+fLly5cvX758+fLly5cvX74xymWfB8tBDxoGjShJvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uVbaieUsdTiQVz7Rn7DcvO3d9+IBy/O9PyWqP2fX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fJtq913Wuc1b0G78OXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLl2+tfdDse5n/bLfbBl++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPmW2rQ0lk2Kbz4sg7fxIC5/40X/85s/SDq/TyOjF/nnly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLdx++387z/EM3X77z0lUnRr7351OdGPnOv3fdhZHv/fmPujDyPX7yverAyPcwf+q6AyPf+9X3pw6MfI9zrQMj3/nPrvim+x7+4nvNN933/l98f+rqy3fmm+57/KvvFd9s33k9X77XfJN9Dyv68v2Jb7Lvfb58d+M7T9sU+4a1+7aX4Hvky3c/vt/x/RRfvnxnvnz58uXLly9fvnz5rpv/fuPLly/fqcbX8yG+fDd7fhz0oHkQ++bd47P48yV8r/km+16s6Mv3im+273E9X76pWnz7f7+F76GrL9+Lvt9/43vs+v1Nvve7fv+Y76Hr9+f5XvT9/Qe+x66/D8P3UP/20IGRbz3AV30Y+R7q8eWb7lv/Fa2DFt8K/FO+Ft8gvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvrv0Lbp1v7YHBwQAABAAgEz0f40ZoMqAKQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAO+uutlkASEAAAAASUVORK5CYII=
```
# Bonus imaginary internet points
* Write the code in TikZ
* Your TikZ-code should compile without any errors, warnings, and boxes.
* You should be able to produce a PNG-file with Overleaf that, when saved in the same dimensions, must be able to withstand a bitwise comparsion with my solution.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~959~~ ~~947~~ 937 bytes
-12 -10 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!
```
#define Z g&&S(r,c+40,20,q,1)
#define W write(o
H=1402;y=4206;char*s="VDRMOSMWK[I^HaGcFeEgDiCkBlAnAo@p@q?r?s>t>u>u=v=w=w=w<x<x<x<x<x<x<x<x<x=w=w=w=v=v>u>t>t?s?r@q@pAoBmBlCjDhEfFdGbI_J]LYNUPPSJ",*I,d[]="\0o\20\x90\xef",*G=",&&* ,* ,&&*%* %&#%*%*,#,#,&*,*%*)) ) %*%#%*%#%*),*%*,*%*,*)))%*%#%*%#%#)%*%*,*) ,* %*%*%#%#,#%* %*%*,*,#,*),*%*%#%#,#)))%&# ,*,#,#)%&&&&#%# %&#";P[]={0,255,~0<<16,~0},o,C,u,v,i,j,r,c,q=60,z=100;S(a,b,w,h,X){for(h+=a;h/a;h--)for(C=b+w;C/b;)bcopy(P+X,I+h*y+C--*3,3);}main(g){I=memset(malloc(y*H),~0,y*H);for(W=open("a.png",33537),"\x89PNG\r\n\32\n\0\0\0\rIHDR\0\0\5z\0\0\5z\b\2\0\0\0\xDCTSV\0Z\eNIDAT\b\35",43);++i<13;)for(j=0;j<12;8&Z)g=*G++%32,u=j++==5,v=i==7,S(r=i*z+i/7,c=j*z|j>6,z+u,z+v,0),g&&S(r+!v,c+1,98+u,98+v,3),1&Z,r+=40,g&2&&S(r,c,q,20,1),g&4&&S(r,c+40,q,20,1);for(r=61;r--;)S(1281-r,s[r*2]+q,s[r-~r]-q,0,2);for(r=H;r--;I+=W,I,y))*d=!r,W,d,6);W,"\xfc\xa3\xea\xe1\xe8\x93\274a\0\0\0\0IEND\256B`\x82",20);}
```
[Try it online!](https://tio.run/##XVJ7c5pAEP@/n4LgyHDc0vDwlcHznShpY52YxtRgW0RErIri2zT56nYR0@mUZW@X394ee7s/R/Yc53hMDNyhP3O5LucJQlsMwaEpBTQFFqCSD@/RDrcN/ZUrBh8aTE0pmrFnKU3JGM7IDqUl4x9r93df2nedT8/m94Zdd27ca6/mV39VJuVZOSjNS4tiWFwWVoV1Yc02bBtJfve/xDjGN7hvVVgVl8WwtCjNy0FlWplUx7XR9fBmUO@bP257n781v7Za7VseJBMGzz3GW0pgaYq1u0J1h4jXGQ@CIHGAL9qkxCWFRBItJFAECdAlhCMcYolYSYTFSgj5iydIMsaisyI3wiCRjD8gOjBOjfEoVUhwJxxTBXwQj/7OGy0s9QUbnE7Dm5LPqxk0rxBAFdawAR/GgCOABcsocGCqohht0YY@bGEET@RlGITiiDLbGF2iyjKJgCrr061RvewbpO8E873Yok9g0pG0p1VZlnTQifE6tf2Z6JEXk03d6dJdiVN7MgkccS81CJYAkTWi0zosmLszkbc/zmceD7qe1rMEeGuXu2o161ZozSxdw0U5SWg2avcnL314N31LO0d3tepD@9FSupbbNGvlBwzpaR5SWBClfl7VjdMFxkwxxnlVM3JCl3hMqlOa1DVYszGljKVhw3zGsoDsZL50oP5lFhw2lg6/x4UMHOgadQMKgZjB9GKDJFbhKocRXDZ4f1CFLoSUIbU9QTsTHSmOPFejvNQ/3D@jp2aELKMaoSwbpC2qWk6VQ1g@h5LWo4vIkd/CnrwAHOf79sZpt0lZB0zYEyIN2EUIHRhAhhidqI1Dx9rZOlLURlVRc0hZ3dKyKfvcNcW8btYsLZ2p/MSuazzWgwM8Hv8A "C (gcc) – Try It Online")
Each position on the board is stored in the lower four nibbles of the characters of the string `G`. A zero means a black tile, otherwise each bit corresponds to one "arm" of a junction:
```
0
1 2
3
```
So a ┌ junction would be stored as the bits 1100, for example.
We simply loop through the string and draw tiles accordingly. Care is taken to match the jankiness that occurs in the middle of the board (slightly wider tiles and therefore everything shifted down/right thenceforth).
Everything is drawn as filled rectangles. An empty tile is just a black rectangle with slightly smaller white rectangle painted over it.
The circle caused some headache; just the data for it takes almost as much as the data for the rest of the board. I tried some circle-drawing methods, but the circle is not symmetrical, so no luck.
Various CRCs and similar are hardcoded, since we will always output the same image.
Stores output to "a.png".
[Answer]
# Mathematica, 1900 bytes
```
"H4sIAAAAAAAACsVWa1ATVxSOtRQNYFqIIkrEgiAUQrQODW0Eq6AFKYICrRQlWKjtqCQgYFA24KPBYcCgqGQwBca3xRaoHQwQWEQwMQOIj9ZYNFlDCA8xWZIAIYQk3bR11D/rdPujO3P3nr3nce+53zlnT1Hsps+c8IvwOBzOKTIifAsOZ3fANt6ajawEbg0oQybH2M/j1yOzFWd7Ic850uJQhJybEZGYhcM5uNjGLNyZHxYiRHtk+Nr43D617JdMZTDxnZR9NyImtnr7ai8G3krYNpd391BUPS1jwIe4/fmnzV6GALVEFFg157jzhHmEbz8HSlkhLD599/nFry2MhWMqf8Comw8CRjwdvMmj0BVdvLoxVdeXUy8WAQ7Fxvln8YX434svxF+xYeO8tGHjvLRh47xiw8ZxHktfRlO7gSwXYplH8B/a8g9aCqWWj9YeQhQQKVUX798SVE0ePbj0PYhOmHhXy6a0cO3R1ZIvwaknTMpVbI+2RIlpP+jm68ZhYdwbIaJNS9Yo6jtz4jy1Z8tIV8H6Isf58G1STWWaVcRKBcRtxx4dk+aHjmGzruoybGRfzu0hp3JPehfKd/LPHUHX0U8PytU7p0RDV1gC/r2V06IK7Bc78ngm9Ajc3FT/03RMg9/9E7R4msRCboymZFlBjLeFEMxuqiH9+hPu4TDvzf0kdPHtJczhM40p4sgdfdWRmHekQFlAqazDWRq91I5WxkmgPwofjNjX6RBkYO4tvwVDJR9PYXZHcJDZ/q28DIxb7ej67CmqCtxgFNUVnSQ1URvsKGyHO+2Y3eGPhzQ7+Y5eCsfPO91dU526asQ9XWJeDGVPYgYbMObHXdF1JzHEYbvUcdno4WroA8I497JKmnzyCbtb9ZiBgd3AnvcRXHqknQ6SzqNfTXCi07hp4uF1u62feGDGJC8ETFhSyFdUCGLt0YXreqih8de89i92b/PhEoKab/wHRNLnucU+7JEuQxyh9SdOZO054/dAPmZhO51fNpSLPXTpoFSZpHJrfcI96gk29Q5r0YE5wL48HOyXNuOorgC/KezHnjFmy6OQgEzZ21vqvRK3IrhcON49fJax3yoqyMzpjsVcLVV5ib0t3mwloSNB84ZsaQF/TQ4Ykv/GbfKppRIxxzXzvsDIfufnHJeIlvMpX5gH+IvCGrzZaqjZhB0SqpI22pFB+LEh5h56EkP+OnJu9MxuSHzbWSnt1J7FXmgM7lCJo++oJ0lys4ayx5OT1h9WSexbBcAbiM+xJ70OAfmhrX5lhehF6K5ETbJLiPjkgOUUtpLjF1iOOQS6WG3MV5IFv/P3GNDvfuaW7yjZVh/XQQA9LtBCxmlK5KJrrX5WIfiQ0PGGTFnHRioxZxskXsQSvqneodnxYZcWk8obGYORe3W2PwteUqKxeSLnLC+FIempzcIZPUpzY1gNrWmuNRUzg6DaXgdoI+hxhCkWlMEEuaaCOR+yXoczZ+vJz4TmcbYiqZ1lkOQFL50qHw9xJ8hcIDx4VKnIwOnJI3kD5tUHjQvGZeYBU7egERbHgDHA1el9QLGJIaTYr4AOgyRoBKg2LpiUaSvvGoqYOyACCLgqH8t6T11gis6nN4Fa4phMpxK6Q2v+OtgDgfK18xYUIN91BdbWXXRDGMBT0sTmTB2eKjiuoB3g+lus3gLb1vVwFfw9SAGiTAzjpiHhUFIfaxIWBDxhiQU1cL4GbiPLWDS9gcrTmFbqDaU8jZBvNOmjDLLeGROh2CC7YzKtQKZKdwLQNZ3PeOoK5gAsKwQCDibLlFdfFZMMFRyqngRGjcmxaD0jIrfh2oMqhb/d/9Dkvr7laSZgnbVnKNulsP9gkK3bj1y/Kbx2XcrhPwH+UUsXJwwAAA=="~ImportString~"Base64"
```
I tried to use the grid-board to my advantage, and it still probably would be, but the thicknesses of the lines seem to very by 1 px either way, making this a likely comparable solution in length.
[Answer]
# Python 2, ~~3864~~ ~~3846~~ ~~3832~~ 3815 bytes
I’m new, so I could use help shortening it. It outputs to a file in the same folder called i.png.
`from base64 import*
open('i','wb').write(b64decode("iVBORw0KGgoAAAANSUhEUgAABXoAAAV6AgMAAAAuWCySAAAADFBMVEX///8AAAD/AAAAAP8xSkYMAAAKsklEQVR4Aezdx5HcRhSA4a2aOz2TYBLDEOg6CUSxSeAuRwclsfHotFdZSBiJLftqt7deA0Po+6+vHlDzVcuCM7g4myRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJksqt04s7+D5fYVCiwo0H0eBp82d/0HvAly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvlNylw2+N9z8ixbfZ1NuX5ynL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fC9Tnh/f3jfYePB3rXbfGKVl8IwvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX75840ptWhpLQvVSCRvDMnhbGmrcaLjUi1XOb/tpbD/xD9pP47bnly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvny7v80tLvaN+2KjDb58+fLly5cvX758+fLly5cvX758+fLly5cvX758+W7rG8M3+7bfI//ZbryR8sSZL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fMvNnXzHcmYN02+9Tdi4/aVerHJ+442dnN+nfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5Zv//reWjfZL5b+0jS9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvvv0DT57341gkP+YmC9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnyzfUttWhpLQ4kb4WBYBm9LXLiRMOh5fkvU7s9vfA++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPnyTfHNf2Nc6Bv2xRobfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny3YFv1g+r1hIeEwcb6ffgy5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cv31I7oYwlo8RLhQ3LPd6ueo8XDa7Jh8755cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL99gEJa0sf1r3vjy5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5bsD34ZB1j3aP2K8kTqo8eXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLl2+pTUtjqbUMghIuNSyDtyUu3kgfvNjs/Dq/fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5bvpi+G2e81b0C58+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLlW0vYqGU8Jq51HfDly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5dvqZ1QxlKLB3HxRnrDco+3Zc1e/I/P79NmlPAeTz8fX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLlG7bGxhcpvje8Rm8Hvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58k3fCAcBY5ZvwqVqfPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5Vtq09JYGsrbiAfDMngbD+JSLuX81kFQ/qX48uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXL99xe8xb7hn2xwcZmvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58t30wXLDk9rGx8S9L8WXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++5eZOWmM8jzc2aVhu/rbHpV5k+jq/CeeXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPu/GG7717ztwJcvX758+fLly5cvX758+fLly5cvX758+fLly5cvX77pP6waD+KP2P7ZEy7Fly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLtyW+fPny5cuXL1++fPk2dEIZMzbiwbAM3jYMgoKNpsGLO/g+v/vA+eXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly/fM3nN22Xn17ztyZcvX758+fLly5cvX758+fLly5cvX758+fLly5cvX74xymWfB8tBDxoGjShJvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uVbaieUsdTiQVz7Rn7DcvO3d9+IBy/O9PyWqP2fX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fJtq913Wuc1b0G78OXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLl2+tfdDse5n/bLfbBl++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPmW2rQ0lk2Kbz4sg7fxIC5/40X/85s/SDq/TyOjF/nnly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLdx++387z/EM3X77z0lUnRr7351OdGPnOv3fdhZHv/fmPujDyPX7yverAyPcwf+q6AyPf+9X3pw6MfI9zrQMj3/nPrvim+x7+4nvNN933/l98f+rqy3fmm+57/KvvFd9s33k9X77XfJN9Dyv68v2Jb7Lvfb58d+M7T9sU+4a1+7aX4Hvky3c/vt/x/RRfvnxnvnz58uXLly9fvnz5rpv/fuPLly/fqcbX8yG+fDd7fhz0oHkQ++bd47P48yV8r/km+16s6Mv3im+273E9X76pWnz7f7+F76GrL9+Lvt9/43vs+v1Nvve7fv+Y76Hr9+f5XvT9/Qe+x66/D8P3UP/20IGRbz3AV30Y+R7q8eWb7lv/Fa2DFt8K/FO+Ft8gvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvrv0Lbp1v7YHBwQAABAAgEz0f40ZoMqAKQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAO+uutlkASEAAAAASUVORK5CYII="))`
I could use advice on shortening it. This is the first time I have ever done anything like this.
] |
[Question]
[
Any two separate nodes in a binary tree have a common ancestor, which is the root of a binary tree. The lowest common ancestor(LCA) is thus defined as the node that is **furthest from the root** and that is the ancestor of the two nodes.
The following are binary trees and the lowest common ancestors of the some of their nodes.
[](https://i.stack.imgur.com/KNwp0.gif)
The LCA of 13 and 15 is 14.
The LCA of 47 and 49 is 48.
The LCA of 4 and 45 is 40.
The LCA of 13 and 14 is 14.
The LCA of 15 and 47 is 40.
**Challenge**
Write the shortest program possible that accepts as input the root of a binary tree and references to any two nodes in the binary tree. The program returns a reference to the LCA node of the two inputted nodes.
**Assumption**
Assume there is a least common ancestor present for any two nodes in the binary tree.
**Input**
The **root of a binary tree** and **references to any two nodes in the binary tree that the lowest common ancestor must be found for**. The root of the binary tree may be in the form of a reference to the root object or even a list that is a valid representation of a binary tree.
**Output**
**If using a pointer-based representation** of a tree returns **a reference** to the node that is the LCA of the two inputted nodes.
**If using a list representation** returns **the node\_id** for the lowest common ancestor of the two inputted nodes.
**Definition of a Binary Tree**
A tree is an object that contains a value and either three other trees or pointers to them.
The structure of the binary tree looks something like the following:
```
typedef struct T
{
struct T *l;
struct T *r;
struct T *p; //this is the parent field
int v;
}T;
```
If using a list representation for a binary tree and since certain node values in the binary tree may reappear, the list representation must have an additional node\_id parameter that looks something like this:
```
[[node_id,node_value],left_tree, right_tree, parent_tree]
```
[Answer]
# [R](https://www.r-project.org/) with [ape](https://cran.r-project.org/web/packages/ape/ape.pdf) package, 12 bytes
```
ape::getMRCA
```
Built-in. Called as `ape::getMRCA(tree, c(node1, node2))`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~155~~ 151 bytes
```
def f(a,b,T):g=lambda U:U and(U[0]in[a,b]or T[0]in[a,b]or g(U[1])or g(U[2]));L,R=map(g,T[1:]);return(L and R)and T[0]or L and f(a,b,T[1])or f(a,b,T[2])
```
[Try it online!](https://tio.run/##VVDNasMwDL7nKXSLDWLErcu6lPQJeirJyejgLk0WaNwQ0sMYe/ZMcpNBD5L1Sd8PePievu5hM8/1tYFGebxgqfO2uPn@Unuo8gp8qFXlMuqC4zPdRyhfUMtXQ3qZNqT14YTnoveDarF0Jid9GK/TYwzqJGZw1tLFhDXP1ZK8@KyIveaycDZDZ9ERui0/RmobIXGZ3TKuzT4XO37snuv9n2o/XqiUJA2HSdTt00MXwIkxsCMYSwiiBRaB3UfEA59sJiAS7UoUSSRnRHkCw9iFKRqnxTHF9VsxVT@/On3j1N5PikN1Mv8B "Python 2 – Try It Online")
This assumes that nodes are defined as
```
[node_id, left_node, right_node]
```
as it seems silly to define the nodes as
```
[node_id, not_neccessarily_unique_node_value, left_node, right_node, parent_node]
```
because both the `other_not_neccessarily_unique_node_value` and `parent_node` are completely ignored in this problem.
The `g` function evaluates whether `U` is a ancestor of the nodes identified by either `a` or `b`.
Starting with the root node, if `g` is true of both the left child and the right child OR this node is either the `a` node\_id or the `b` node\_id, then this node is the LCA. Otherwise, exactly one of the two children - the left child or the right child - is then either the LCA or has the LCA as a child.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 86 bytes
```
f=->t,x,y=p{t==x ?(!y||f[x,y])&&t:t&&(f[t.l,x,y]||f[t.r,x,y]||y&&(f[t,x]&&f[t,y])&&t)}
```
[Try it online!](https://tio.run/##bY7daoQwEIWv16eYbiEopKGLynZD7b5Bb3opoViNdMHqEqNVdJ/dTmLXLcWLk5/5zswc1Xz0U1okdQ2vVSbhGd60alLNSvnt8pbygnLlOc4mkzkkWea2SdFIz9lsspOSqT5VJURgi9hbyyJnLRyBF8CBK7TVsszcxesRdhsC4wgWb@@HxXGJtnSeY1PZHLMdl6LZceyhqkrjYpPZWoJHDFnir8ZqHFDwUTsjHxVSCFChuZ9Qe9QBBPtKzjDA2I4Qt9SMnNN5Ai5MV@@fUx49vGja0T46DzqKOji6d/045jGWhEeI5poQN481K4xLGKSZ@n33M6OdIMTcc4t3mc6Qx2YdtYnjnS@ur1AI1jr/eLC/8uCwysOFr@E/49f5rX1v@PQD "Ruby – Try It Online")
If I understand correctly, sorting by value isn't guaranteed and we're returning node references so the value isn't actually used for anything. We're just checking a node's `l` and `r` values to see if they contain `x` and `y`. The function returns a falsey value if either of the provided nodes isn't in the tree so that it can be called recursively.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 bytes
```
œiⱮn/œpḢƊḢœị⁸
```
[Try it online!](https://tio.run/##y0rNyan8///o5MxHG9fl6R@dXPBwx6JjXUDi6OSHu7sfNe74//9/dLSBnqGOiUGsDpdCdLQhiA1iKkRDSJCIkY4xRAzKNdQxhPJhAkAR41idaBBClTDSMTSFSYDEocaA2EAMs9NIx8QUzVIjIx1TU4SlRkBLTSyQzDYCWWpijmmpEchSE0s8lnLF/oc5GkgBAA "Jelly – Try It Online")
A dyadic link taking the tree as left argument and the two node ids as right argument. Returns the full node of the lowest common ancestor.
Node ids are floating point. On TIO I’ve used vaguely hierarchical ids, but the actual numbers are arbitrary.
[Answer]
## Haskell, ~~72~~ 70 bytes
```
a#b|let g t@(i:%c)=(g=<<c)++[i|t!a,t!b];(i:%c)!e=i==e||any(!e)c=head.g
```
The tree data structure is `data T = (Int,Int) :% [T]`, i.e. a pair `(<id>,<value>)` and a list of child trees per node. Needs no link to parent within the node. Returns the `(<id>,<value>)` pair of the LCA.
[Try it online!](https://tio.run/##ZY/LbsIwEEX3/oqJKMIWpjzCKxRL3XbPDrIwiRWspEkF3lRNvz2dOA9wieTxnZnjyZ2LvKUqy6pYGgkHEEA/csPxMNgN4XgIKzk4l5kykIB5p3o3jJigidjvIzYeH3VpPMmNdw7fmp6nhBZClaXMv6mnWCQuSsavSfUpdY7j4wIIAHxddW7gBeiAAd1yH@Osjuaq1FM/sP1l138esHABQiyGu8z5otmjQazyOxXy9o1N6mzFVy207vFNr7YOGzjZ7J6FhPxMYFRbGEFWFOkNMp2iKXj80JlTmOI53Sto197oiDwgp140Vb/GlnVY2wdow/3N/7kAm3Zy4KDTTuOSZPJb/QE "Haskell – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes
```
Head@#&@@Cases[{#},a_/;!a~FreeQ~#2&&!a~FreeQ~#3,∞]&
```
[Try it online!](https://tio.run/##dZBBasMwEEX3OoWLwKtfGtlSnRBSBIWSVUjXxgSRKiSQdGGrq0FZ9xQ9XC/i2JbSJNBsNDMP6f@vORi3tQfjdmvTbmbt3JoPzVOtX01jm5K4h1k9TR/M8a229v3IszS9DDl@v3@qtHUzRgJy5EuWUAbZ12Txtd@jq5QjDyQhCRHbhBRE7svhVn9UCPgZQl3jwP9aKiDVrf4YSkX9CeT4rC9GkMU/BqJLOrnnUDG2rHefrvs5z/zjy0ZzXnXr0MTIIWRGyOgxoGCDKBthvwOEqJHEl8MCIhpUzgKe@fYE "Wolfram Language (Mathematica) – Try It Online")
`FirstCase` seems to be traversing the tree in a different order than `Cases`...
Function which takes the tree and two node values, and returns the value of the lowest common ancestor.
Represents the tree as an expression, where the head contains the value, and uses `Null` (or anything else that is guaranteed to not be a node) to represent the absense of a leaf.
For the example tree given, the structure looks like this:
[](https://i.stack.imgur.com/Rk0bc.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
W∧η⊞Oυη≔§⊟Φθ⁼§κ⁰η⁴ηW¬№υζ≔§⊟Φθ⁼§κ⁰ζ⁴ζIζ
```
[Try it online!](https://tio.run/##nY8xa8MwEIX3/IobZVDBiuW4JpMJLXRpvZsMIjGRqbASWW6L/7x6lx4hpVuHh6TvvXuHDtaEgzcupU87uB5EMx6FldDOk30798FEH8QswWZZBs00DadRNPFlPPZfovVn8Ty42AdxkfB0mY2bbua7hDz7mZOgr7ftine8@ih2fh4jNS//bF5uzQs2t2HAup2ZokBjm1LXdaDQzyXAGlWg8r1cAXTXt6Y3n4o5ZnTJvLzjmCkot2FvzRwzJeUq5gVzzCnKP6Jq2sEccxqZwqxStIM5sYI7SBvmOKvKv5zmdXXHK@b03/oXJ6NGqXyfHj7cNw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of `[id, value, leftid, rightid, parentid]`, where a `0` value means no id. Explanation:
```
W∧η⊞Oυη≔§⊟Φθ⁼§κ⁰η⁴η
```
Walk the tree up from the first input node id, saving the found ids in the predefined empty list.
```
W¬№υζ≔§⊟Φθ⁼§κ⁰ζ⁴ζ
```
Walk the tree up from the second input node id until one of the ids matches.
```
Iζ
```
Print the matching id. (If strings were acceptable as ids, the `I` would not be necessary, but if both strings and numbers had to be supported, then that would cost an extra byte.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ΔDʒ˜ÃQ}`}н
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3BSXU5NOzzncHFibUHth7///0SYGOtEmOtGxOtHGQMoQhI3B3FggNjSFMmGECUTAFEiZWACxOVypiSWK0lgukDkKhqaxAA "05AB1E – Try It Online")
First input is a tree in the format described in [this answer](https://codegolf.stackexchange.com/questions/190079/shortest-program-to-find-lowest-common-ancestor-of-two-nodes-in-a-binary-tree/190100#190100), because I have no idea how the format in the question is supposed to work. Second input is a pair of node ids.
Explanation:
```
Δ } # repeat until top of stack doesn't change
Dʒ } # filter a copy of tree by
˜ # flatten
à # list intersection with the second input
Q # equals the second input
` # dump all results on the stack
н # get the first element (the node id)
```
] |
[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 4 years ago.
[Improve this question](/posts/186071/edit)
Suppose there are 5 positive integers in an array or list as 14, 12, 23, 45, 39.
14 and 12 cannot be taken in the subset as 1 is common in both. Similarly {12, 23}, {23, 39}, {14, 45} cannot be included in the same subset.
So the subset which forms the maximum sum is {12, 45, 39}. The maximum sum such formed is 96.
the result should be the maximum sum of such combination.
Sample TestCase 1
Input
3,5,7,2
Output
17
Sample Test Case 2
Input
121,23,3,333,4
Output
458
Sample Test Case 3
Input
32,42,52,62,72,82,92
Output
92
Explanation
Test Case 1: {3, 5, 7, 2} = 17
Test Case 2: {121, 333, 4} = 458
Test Case 3: {92} = 92
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
æʒ€ÙJDÙQ}OZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8LJTkx41rTk808vl8MzAWv@o//@jDY0MdRSMjY11FExiAQ "05AB1E – Try It Online")
**Explanation**
```
æʒ } # filter the powerset of the input, keep only elements
€Ù # where each number with duplicate digits removed
JDÙQ # have different digits from the other numbers
O # sum each
Z # take max
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 77 bytes
```
Max[Tr/@Select[(s=Subsets)@#,!Or@@IntersectingQ@@@s[IntegerDigits/@#,{2}]&]]&
```
[Try it online!](https://tio.run/##VYuxCsIwFEV3/0KEovCg5KW17VB4g4uDqNQtZIglxIDtkEQQSr89posodzvn3EGFhx5UsL2Kpo0n9RY3l1Onn7oPYuvb7nX3OvgdbWB9dkTHMWjnk7SjuRKRFwsx2h2sscHnqZtwlpmUWbw4OwYyYmIFMATkUJTAm1muvoZDCRXgL2LIljSNp8NfjFAglAh7hAqhRmjSM8YP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~137~~ ~~112~~ ~~105~~ ~~119~~ 116 bytes
```
lambda a,s='':a and max([x+f(a[1:],y)for x,y in(0,s),(a[0],s+`set(`a[0]`)`)if max(map(y.count,'1234567890'))<2])or 0
```
[Try it online!](https://tio.run/##VUxLDoIwFNx7irejDRNDX4uAkZMgCfXTSCKFCCZweqwujGY28x@W6dZ7Xl15XO@2O10sWYxlFO0D8Rfq7CyqOXbCVmpfY5Guf9CMhVovEowSIUhqjHEzXifRvEUjG9m6z7Kzg1i25/7pJ0SKtUl3WV4kkZQHrmV4Stbh0fqJnKiUASkGsQaZFKSLWm6@qUaKDPxrKVYI5QCtYf7KDMNIGTtGxsgZRViuLw "Python 2 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 116 bytes
```
lambda a,s='':a and max(x+f(a[1:],y)for x in(0,a[0])if max(map((y:=s+str(set(str(x)*x))).count,'1234567890'))<2)or 0
```
[Try it online!](https://tio.run/##VYzNboMwEITvfQrf2G1GFV6b8KPyJISD09QqUjEIXMk8PSU5RIrmMKuZb2fe4s8UTDUvu28v@68brzenHNY2y5rjCDc1ukTp5Ml1uumxsZ8WldQQKIfr8p4H/0BGNxNtTbue1rjQ@h3p7onfEzN/fE1/ISLTYmxxLqs6z5g/hY@pfJ@XIUTy1GkLpQVKDJQtoEzdM789a4MCJeQl06Jx4IeMgX3FBVZQCM6CUlAJ6vvv/g8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# JavaScript (ES6), 77 bytes
```
f=([n,...a],s=m=0,p='')=>n?f(a,s,p,p.match(`[${n}]`)||f(a,s+n,p+n)):m=m>s?m:s
```
[Try it online!](https://tio.run/##ZY7LCsIwFET3fkUXQhM6RnPbWitEP6QUDLX1gUmDETfqt9cHClpnlnM4zF6fta@OO3ca2XZdd12jWGEhhNAlvDJqAqfCkKuFXTZMw8PBCaNP1ZatiuHF3soVv15fU2ThIsv53Ciz8Esz913VWt8eanFoN6xhhUwgCRQjSRHnwSsl58F4HOTTQQ@OkSIDBd95wzLrw5Lk0/to/LD/wEk6@1MTEkJKmBIywoyQ0@cHdXc "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[n, ...a], // n = next value from a[]; a[] = remaining values
s = // s = current sum
m = 0, // m = maximum sum, which is eventually returned
p = '' // p = all previous digits, as a string
) => //
n ? // if n is defined:
f( // do a recursive call ...
a, s, p, // ... with all parameters unchanged
p.match(`[${n}]`) // tests whether p contains any digit of n
|| // if it doesn't:
f( // do another recursive call with:
a, // a[] unchanged
s + n, // n added to s (as an integer)
p + n // n appended to p (as a string)
) // end of inner recursive call
) // end of outer recursive call
: // else:
m = m > s ? m : s // this is a leaf node: update m to max(m, s)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Nick Kennedy (use the implicit `make_digits` of `Q` to get rid of `D`)
```
ŒPQ€FQƑƊƇ§Ṁ
```
A monadic Link accepting a list of positive integers which yields the maximal sum of those subsets which repeat no decimal digits between elements.
**[Try it online!](https://tio.run/##y0rNyan8///opIDAR01r3AKPTTzWdaz90PKHOxv@//8fbWhkqKNgZKyjAELGQMIkFgA "Jelly – Try It Online")**
### How?
```
ŒPQ€FQƑƊƇ§Ṁ - Link: list of positive integers
ŒP - power set
Ƈ - filter keep those for which:
Ɗ - last three links as a monad:
Q€ - de-duplicate each
F - flatten
Ƒ - is invariant under:
Q - de-duplication
§ - sum each
Ṁ - maximum
```
[Answer]
# Haskell, ~~81~~ 76 bytes
```
_?[]=0
n?(a:b)|any(`elem`n)$show a=n?b|True=max(n?b)$a+(n++show a)?b
g=(""?)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P94@OtbWgCvPXiPRKkmzJjGvUiMhNSc1NyFPU6U4I79cIdE2zz6pJqSoNNU2N7FCA8jRVEnU1sjT1oZIa9oncaXbaigp2Wv@z03MzFOwVSgoyswrUVBRSFeINjQy1DEy1gFCY2Mdk9j/AA)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
{⊇.dᵐc≠∧}ᶠ+ᵒt
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRV7teysOtE5IfdS541LG89uG2BdoPt04q@f8/2tDIUMfIWAcIjY11TGL/RwEA "Brachylog – Try It Online")
### Explanation
```
{ }ᶠ Find all…
⊇. subsets of the input…
dᵐ …where each number with duplicate digits removed…
c≠∧ …has different digits from the others
+ᵒ Order by sum
t Tail (last element)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
```
f=lambda l,r=[],S=set:l and max([f(l[1:],r+l[:1]),f(l[1:],r)][S(`l[0]`)&S(`r`)>S():])or sum(r)
```
[Try it online!](https://tio.run/##PY7BCsIwEETvfsWeJIt7MGlrbaD@RI9LoJVaFNK0pBX06@NWQdgHM8MszPxe71MwKQ2178Zr34GnWLOjpl5uq/XQhR7G7qV4UJ61dRQPnq12SP8AHTeq9Xx0Le5FxRYvjULrcIqwPEcVMQ0iPTwCsM4JtCEwGUFeEGSVI2AxokuJN6eN/hW2y7bityNfuVAIJ6EUzkJlnN0BzPERViWrENMH "Python 2 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 95 bytes
```
f=lambda l,r=[]:l and max([f(k:=l[1:],r+l[:1]),f(k,r)][bool({*str(l[0])}&{*str(r)}):])or sum(r)
```
[Try it online!](https://tio.run/##JYvLCoMwEEX3/YpZlaSdReOjasAvGbJQRCodjUQLLcVvT8cKc@Cey535sz78lJZziLGvuRnbrgHGUJOzDM3Uwdi8FfXqaWsmYx2GK5M1TqN0GLSj1ntW38uyBsV0c3o7HxL0pq3TPsDyGsViL5FhmIBMhmAShCRFyHKEtHIIJCK5kHo3k5hjsF@6D/8b@cqEXLgLhVAKVeLsCWAOw7SqXrHW8Qc "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 82 bytes
```
max(map{my$n=2*$_;my@t=grep{($n/=2)%2}@_;"@t"!~/(\d).* .*\1/?sum(@t):0}0..2**@_-1)
```
[Try it online!](https://tio.run/##xZPRToMwFIbveYpKMGnJkY0DbAOC8gB6N@@WLFM7bUIZ0pJJCL46FuZufABsr/r/pz0nX/5WvC6iQbYk11zp7PNMyb8syw/BR8AAwgiC@CrHqxlHCCCCNeAf2V/PSQH9kYHZgSFxlcNoMyMFhBAhQlghrBE2CLFBEuOMFFhqNYqTrUlkkjydak7GcKrsPkyt84coOJ3SyjprLJctdUQJzqnRLFNVIV75ZMMSMP2tILkoJ0/bYIMpvxhC0SM1FrvcTq1@avwoxsbPWhTEfAjVSCIPX8ZVzQs5doM5UHmoOtk6ZYaus09lm@vsveZVR51ykSG7xT7fp3au7ZvvBd29Mc8lnrvzFw/mNTM9S5b90vPQdfP9nc@GfvgB "Perl 5 – Try It Online")
With spaces:
```
sub f {
max(
map {
my $n = 2 * $_;
my @t = grep {($n/=2)%2} @_;
"@t"!~/(\d).* .*\1/ ? sum(@t) : 0
}
0 .. 2**@_-1
)
}
```
Loops through all possible 2^n subarrays of the input array where each element either participates or not. Then for valid subarrays, those not matching the regex which finds common digits in other elements, use the sum of them and return the max of those valid sums.
] |
[Question]
[
## Challenge
Given a list of integers and a velocity, \$v\$, implement a sorting algorithm which simulates a program sorting the list from smallest to biggest at the given velocity.
## Einstein's Theory of Special Relativity
What do I mean? Well assume your program takes a time, \$T\$, to sort a particular list. If you ran the program again at a higher velocity, \$v\$, according to a stationary observer your program would run slower and would take a different time, \$T'\$, to sort the same list.
How do you relate \$T\$ to \$T'\$? You use the equation for time dilation:
$$T' = \frac{T}{\sqrt{1-v^2}}$$
If we use geometrised units where \$v\$ is a fraction of the speed of light, and \$0\leq v \lt 1\$.
So you must change your program's running time by a factor of
$$\frac{1}{\sqrt{1-v^2}}$$
## Output
You must output the sorted list
## Rules
* You are allowed an error of \$\pm0.1 \text{ s}\$
* The length of the list, \$l\$, will be in the range \$1 \leq l \leq 50\$
* The list will contain only integers
* The velocity will be given in geometrised units
* You may sort the list then wait before outputting
## Examples
For these examples, assume my program takes a time of \$T = l^2 \text{ s}\$ to run, where \$l\$ is the length of the list, regardless of the contents of the list:
```
List, Velocity > Sorted list, Time taken
[9,8,7,6,4,3,2,1], 0.5 > [1,2,3,4,5,6,7,8,9], 93.5307
[8,0,0,5,6], 0.1 > [0,0,5,6,8], 25.1259
[7,7,7,7,7,7,7], 0.999 > [7,7,7,7,7,7,7,7], 453.684
```
Your timings do not need to be as accurate.
## Winning
Shortest code wins.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~56~~ 55 bytes
-1 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma?tab=profile) (using `z` instead of pushing 1)
```
for n in $2;{
sleep `dc -e"9k$n z$1d*-v/f"`&&echo $n&
}
```
[Try it online!](https://tio.run/##DcQxDoIwFAbgnVP8waaDCQo4GU7g5OIBKPSRNpaW8FqbaDx79Ru@SbEpZQk7PKyH6IdPxY5ow6hnNFRfn8LjLTp9bF7npR6lpNkECC@rb8nKRuCAbKMJKSIay/8Ij9sdKylOO63kIyOH5DQmwhasj46YS2lPbbmgQ/8D "Bash – Try It Online")
### Explanation
Sleep sort loops over all the integers, for each \$n\$ it does the following in the background:
* set a timer of \$n\$ seconds (or another time unit)
* print \$n\$
Instead of using one second we divide \$n\$ by \$\frac{1}{\sqrt{1-v^2}}\$ which is achieved by the following dc code:
```
9k # set precision to 9 digits
$n # push n [n]
z # push size of stack [1,n]
$1 # push v [v,1,n]
d* # duplicate & multiply [v^2,1,n]
- # subtract [1-v^2,n]
v # square root [sqrt(1-v^2),n]
/ # divide [n/sqrt(1-v^2)]
f # print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ ~~87~~ 91 bytes
-1 byte thanks to Mr. Xcoder
```
from time import*
def f(l,v):t=time();s=sorted(l);d=time()-t;sleep(d/(1-v*v)**.5-d);print s
```
[Try it online!](https://tio.run/##fY3NCsIwEITveYqlF5PQ1h8QscEnEQ9CEgzkj@xS8OljixVKD87CHGaGb/ObXimearUlBSAXDLiQUyHJtLFguW9HMdBtbrhQeMOpM5p7ofQSdqTQG5O53vNjN8pRSNmfOy1ULi4SYMVlyb5BE1MJTw8zCoaGWX6/tKt7tHD4bZcXyNgWYlxEmmyHf0H9daUttX4A "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 52 bytes
```
{t←2⊃⎕AI⋄r←⍵[⍋⍵]⋄r⊣⎕DL 1e¯3×s-(s←t-2⊃⎕AI)÷.5*⍨1-⍺*2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqEiBh9Kir@VHfVEfPR90tRUD@o96t0Y96u4FULFikazFQ1sVHwTD10Hrjw9OLdTWKgapKdOH6NA9v1zPVetS7wlD3Ue8uLaPa//8NDQwetU1UMNCztLRUSFMwNEg1tTdMNQcA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 168 bytes
```
import StdEnv,System.Time,System._Unsafe,Debug.Performance
?u=:(Clock m,l)n#!(Clock i)=accUnsafe clock
|toReal i>toReal m*1E4/sqrt(one-n*n)=l= ?u n
```
#
```
?o(measureTime sort)
```
[Try it online!](https://tio.run/##RY/NSgNBEITv@xQtueyGzToBLyuMOZgcBA/B1ZOItJPeMDjdo/MjBHx2xyyJeKv6qIIq4wilsN9lR8BopVj@8CHBkHYb@WqHQ0zE3aNl@tOvTxJxpHZNb3nfbSmMPjCKoWqV9XV967x5B25dI7OLs7ONRmNOPTATqr6TfyB0YG/OgufLzdVl/Ayp9kILmUujnYZVBilDwpCqGYxZTLJe4Mh9zYQxB5q2QTxubir9n3heKqXavu@7Tr2A6lT5MaPDfSyLu/uyPgiyNSezdZimD78 "Clean – Try It Online")
A composed function literal which times the sorting of the list, and then loops until an appropriate additional number of ticks have passed.
] |
[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/143566/edit).
Closed 6 years ago.
[Improve this question](/posts/143566/edit)
# Objective
Use any editor or IDE (vim, emacs, IntelliJ, etc) to write a valid "Hello, World" program in any [C-like language](https://en.wikipedia.org/wiki/List_of_C-family_programming_languages). The "!" is optional, but you get style points if you use it. You may use publicly available plugins, a publicly available vimrc, etc, but you may not write or make modifications to them specifically for this challenge.
# Winning
Fewest key presses and mouse clicks and touchscreen taps :P wins (only counted when the key is pressed down).
# Submission:
A valid submission requires the number of key presses, the editor used, the language used, a list of the keystrokes pressed, and the important parts of any vimrc, a list of plugins, or anything else required to replicate your result.
[Answer]
# [Vim](https://vim.sourceforge.io) with [Ultisnips](https://github.com/SirVer/ultisnips) in [C (gcc)](https://gcc.gnu.org/), 30 keystrokes
`i``ma``Tab``Tab``puts("Hello, World!");``Esc``:``x`
### Explanation
To use the above you'll need the mentioned Plugin installed and `g:UltiSnipsExpandTrigger` and `g:UltiSnipsJumpForwardTrigger` bound to `Tab`, further you'll need [this](https://raw.githubusercontent.com/honza/vim-snippets/master/UltiSnips/c.snippets) snippet in your `g:UltiSnipsDir`. This also makes the assumption that you opened a file which sets `filetype=c`:
* `i``ma`: Change to Insert mode and enter `ma`
* `Tab``Tab`: Select and expand the `main <snip>`
* `puts("Hello, World!");`: Insert the remaining characters
* `Esc`: Change to Normal mode
* `:``x`: Write the file and exit
The resulting file looks like this:
```
int main(int argc, char *argv[])
{
puts("Hello, World!");
return 0;
}
```
**Note**: I couldn't just now find a complete `vimrc` but [here](https://stackoverflow.com/a/19046110)'s a StackOverflow post that mentions the relevant parts.
[Answer]
# Notepad++, 17 keystrokes, R
```
cat("Hello, World")
```
19 keystrokes with `!`
```
cat("Hello, World!
```
[Answer]
# WebStorm in ECMAScript, 16 keystrokes
al`Enter`"Hello, World
] |
[Question]
[
**This question already has answers here**:
[Output all strings](/questions/74273/output-all-strings)
(28 answers)
Closed 6 years ago.
**Description**
There are an infinite number of ASCII strings. Write a program that will output every possible ASCII string exactly once.
The ordering does not matter, but you must be able to show that for any possible ASCII string `s`, there exists an integer `n` such that `s` is the `n`th string in the output. This restriction means that you cannot output `'a', 'aa', 'aaa', 'aaaa', ...`, since the string `'b'` will never occur.
The simplest ordering (shown here in terms of letters so I don't have to type unprintables) is:
```
'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...
```
Essentially, this is counting in base 128 using ASCII characters.
**Rules**
* The empty string is required
* You may use any valid ordering you want
* All possible strings using ASCII must be known to occur in the output
* The ordering does not need to be deterministic, as long as you can show that every string will be *guaranteed* to occur. Be careful if you use randomness for each string, because at some point your bits of entropy may not be enough to guarantee a unique string.
**Example orderings**
*Note that, again, I'm showing only letters for the examples, but you have to include all ASCII characters.*
**Valid:**
```
'', 'a', 'b', 'c', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', 'bc', ... 'zz', 'aaa', ...
'', 'z', 'y', 'x', ..., 'a', 'zz', 'zy', ...
'', 'a', 'b', 'ab', 'ba', 'c', 'ac', 'ca', 'bc', 'cb', ...
```
**Invalid:**
```
'', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa', ...
'', 'a', 'ab', 'abc', 'abcd', ..., 'abc...xyza', ...
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~69~~ 62 bytes
```
a=0
while 1:
k=a
while k:print chr(k%128),;k>>=7
print;a+=1
```
*-7 bytes thanks to @notjagan*
[Try it online!](https://tio.run/##K6gsycjPM/r/P9HWgKs8IzMnVcHQiksh2zaRSwHCzbYqKMrMK1FIzijSyFY1NLLQ1LHOtrOzNedSAEtYJ2rbGv7/DwA "Python 2 – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 96 bytes
```
i=0
(p=print)()
while++i for j:cartesianpower(i,0..128)p(j is tuple? ''.join(map(chr,j)):chr(j))
```
[Try it online!](https://tio.run/##DcUxCoAwDADA3VdkM0Ep6iSC@JYiFVO0CbHS51dvOTXJkmrldWhQVzVOmZCacvIVuo7hEIO47N5yeNgnlRIMuR@cG6eZFCPwA/nVK2zQti4KJ7y94n5aH4mWf/yv9QM "Proton – Try It Online")
[Answer]
# Pyth - 12 bytes
```
.Vj^sCMS127b
```
[Finite version online](http://pyth.herokuapp.com/?code=V3j%60M%5EsCMS127N&debug=0).
[Answer]
# Ruby, 64 bytes
```
(f=->a{f[a.flat_map{|s|puts s;(1..127).map{|b|s+b.chr}}]})[['']]
```
Recursive function that prints the array `a` then calls itself on a newly constructed array whose contents are (in set notation) `{ sc | s in a, c in ASCII }`. We kick it off with an array containing the empty string.
[Answer]
# Mathematica, ~~44~~ ~~41~~ 61 bytes
[Crossed out 44 is still regular 44...](https://codegolf.stackexchange.com/a/139000/60043)
```
0//.i_:>(Print@@@Array[FromCharacterCode,128,0]~Tuples~i;i+1)
```
Prints in the pattern: `"", "a", "b", ... , "z", "aa", "ab", ... , "az", "ba", "bb", ... , "zz", "aaa", "aab", ...` (but with \00, \01, ...).
[Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com/)
Unfortunately, I could not use the built-in `CharacterRange` function (which would have reduced 10 bytes) because it cannot generate the null character.
---
I recommend testing with the version that pauses 0.25 sec between each `Print` calls:
```
0//.i_:>((Pause[0.25];Print@##)&@@@Array[FromCharacterCode,128,0]~Tuples~i;i+1)
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 10 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
]¶tēN»─{Rt
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTVEJUI2dCV1MDExM04lQkIldTI1MDAlN0JSdA__)
Note that this spams the stack with an extra item every iteration, and with how slow SOGL is, it gets out of hand quickly.
[Answer]
# [Python 3](https://docs.python.org/3/), 103 78 bytes
```
n=0
while 1:print(n.to_bytes(n.bit_length()+7>>3,"big").decode());n+=n+1&128|1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8/WgKs8IzMnVcHQqqAoM69EI0@vJD8@qbIktRjITMosic9JzUsvydDQ1Da3szPWUUrKTFfS1EtJTc5PSdXQ1LTO07bN0zZUMzSyqDH8/x8A "Python 3 – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Find the number in the Champernowne constant](/questions/66878/find-the-number-in-the-champernowne-constant)
(29 answers)
Closed 6 years ago.
Inspired by [this question](https://codegolf.stackexchange.com/questions/91432/where-are-champernownes-zeroes).
[Champernowne's constant](https://en.wikipedia.org/wiki/Champernowne_constant) is an infinite decimal number that consists of "0." followed by all natural numbers concatenated together. It begins like so: `0.123456781011121314151617181920212223242526272829303132333435363738394041424344454647484950`, etc. The digits of Chamernowne's constant are sequence [A033307](https://oeis.org/A033307) in the OEIS.
## Your Task:
Write a program or function that, when given an integer as input, outputs/returns Champernowne's constant up to the first occurance of the input. For example, if the input is `13`, you should output `0.12345678910111213`. If you wish, for inputs greater than 0, you may drop the leading "0." in your output.
## Input:
An integer, or a string containing only numbers.
## Output:
Champernowne's constant up to the first occurance of the input.
## Test Cases:
```
0 -> 0
1 -> 0.1 OR 1
14 -> 0.1234567891011121314 OR 1234567891011121314
91 -> 0.1234567891 OR 1234567891
12 -> 0.12 OR 12
101 -> 0.123456789101 OR 123456789101
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
### Code
```
LJ¹¡н«
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/fx@vQzkMLL@w9tPr/f0MDQwA "05AB1E – Try It Online")
### Explanation
```
L # Create the range [1, 2, ..., input]
J # Join into a single string
¹¡ # Split at occurences of the input
н # Take the first element
« # Append the input to the first element and implicitly output
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~70~~ ~~63~~ 61 bytes
*A bunch of bytes removed thanks to [@Rod](https://codegolf.stackexchange.com/users/47120/rod), and some more thanks to [@WheatWizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)*
```
lambda x:''.join(map(str,range(1,x))).split(str(x))[0]+str(x)
```
[Try it online!](https://tio.run/##JYjBCoMwEER/ZW/uYpCk9qLgl1gPKTU2opsQ92C/Po0IM7x5E3/yDdxmN7zyZvf3x8LZV1WzBs@424iHJJUsLzMadRJRc8TNy3Vj0VFP9T2zCwkEPMOoFZiSp4Lu4qNUm6mHmDwLOhSi/Ac)
[Answer]
# [Haskell](https://www.haskell.org/), ~~82~~ ~~73~~ 55 bytes
```
x!b|or$zipWith(==)x b=x
x!(a:b)=a:x!b
(!(show=<<[1..]))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0IxqSa/SKUqsyA8syRDw9ZWs0IhybaCq0JRI9EqSdM20QqogivdVkNRozgjv9zWxibaUE8vVlPzf25iZp5tQVFmXolKupKlodJ/AA "Haskell – Try It Online")
## Explanation
First we define `!`. `x!b` truncates `b` to the first appearance of `x`. It does this by checking if `b` starts with `x` (`or$zipWith(==)x b`) returning `x` if it does and moving one down the string otherwise. Then we define our main function. Our main function is a point-free function that takes the constant (`show=<<[1..]`) and truncates it to the first appearance of `x`. This takes `x` as a string.
[Answer]
# Mathematica, 111 bytes
```
(m=Min@SequencePosition[s=Flatten[IntegerDigits/@Range[0,#]],t=IntegerDigits@#];FromDigits@Join[s[[;;m-1]],t])&
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~11~~ 8 bytes
```
+hcjkSQ`
```
[Try it online!](https://tio.run/##K6gsyfj/XzsjOSs7ODDh/39LQwA "Pyth – Try It Online") or run a [Test Suite](https://pyth.herokuapp.com/?code=%2BhcjkSQ%60&input=101&test_suite=1&test_suite_input=0%0A1%0A14%0A91%0A12%0A101&debug=0).
Simply creates the constant (`jkSQ`) and then prints the constant up to the input (`c ... ``) followed by the input (`+ ...`).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~15~~ 14 bytes
```
U:VXzG&Yb1X)Gh
```
Takes the input as a string. [Try it online!](https://tio.run/##y00syfn/P9QqLKLKXS0yyTBC0z3j/391QwNDdQA "MATL – Try It Online")
### Explanation
```
U % Implicitly input a string. Convert to number
: % Range from 1 to that
V % Convert to string. Includes spaces as separators
Xz % Remove spaces
G % Push input again
&Yb % Split at that. Gives a cell array
1X) % Get contents of the first cell
G % Push input again
h % Concatenate horizontally. Implicitly display
```
] |
[Question]
[
Okay, so everyone is familiar with the [ASCII-table](http://www.asciitable.com/), correct? I'd hope so. I've been going to that site for my asciitable reference for as long as I can remember needing one. We'll be doing some fun source-code manipulating using the ASCII keyspace.
---
# The Task
Your task is to write a program that, when executed, prints the source code with the ASCII decimal of each character reversed. What exactly does this mean? Say this was my sourcecode:
```
#;
```
The ASCII of this would be:
```
(35)(59)
```
After knowing this, we should reverse each to get what the program should output:
```
(53)(95)
```
Which means for a program of `#;` we need to output:
```
5_
```
---
# Constraint 1 (Important)
However, like in most challenges, there's a hefty catch. All characters in your source code must be within the printable ASCII range. If the reverse of the ASCII character does NOT lie within 32-128, the character can't be used. For any character with an ASCII code *greater* than 100, you will reverse it and use the first two digits. For instance:
```
d = 100 => 001 => 00 => \0 => non-ASCII => invalid
```
Another example, of a valid 3-digit ASCII reverse:
```
{ = 123 => 321 => 32 => ' ' => valid
```
If this is unclear, see the "Conversion" part below, if the character is not listed there on the left, it cannot be in your source code.
---
# Constraint 2 (Important)
***In addition to this constraint, the user must also use at least one non-palindromic ASCII character. This means that if you want to use `7`, which is ASCII `55` and converts directly TO `7`, you will have a 2-byte answer at minimum.***
---
# Constraint 3
Your program will take no input, as this is a quine challenge. In addition to this, it must adhere to the specifications of a proper quine defined here:
<http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine>
---
# The Concrete Specification
*Printable ASCII Set (32-126):*
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
*[Conversions](https://tio.run/##MzBNTDJM/f8/@HD7o6Y1QWWVRocWH1ppbPSoYdehdYZGFo8adqplKpUl5mSmKB1erZSXX6IA4dQeWnd4eWVl0OHlSof3K9jaKcBJjcP7NZV0av//V1BUUlZRVVPX0NTS1tHV0zcwNDI2MTUzt7C0sraxtXNwdHJ2cXVz9/D08vbx9fMPCAwKDgkNC4@IjIqOiY2LT0hMSk5JTUvPyMzKzsnNyy8oLCouKS0rr6isqq6prQMA):*
```
=> 23 => (not valid)
! => 33 => ! (valid)
" => 43 => + (valid)
# => 53 => 5 (valid)
$ => 63 => ? (valid)
% => 73 => I (valid)
& => 83 => S (valid)
' => 93 => ] (valid)
( => 04 => (not valid)
) => 14 => (not valid)
* => 24 => (not valid)
+ => 34 => " (valid)
, => 44 => , (valid)
- => 54 => 6 (valid)
. => 64 => @ (valid)
/ => 74 => J (valid)
0 => 84 => T (valid)
1 => 94 => ^ (valid)
2 => 05 => (not valid)
3 => 15 => (not valid)
4 => 25 => (not valid)
5 => 35 => # (valid)
6 => 45 => - (valid)
7 => 55 => 7 (valid)
8 => 65 => A (valid)
9 => 75 => K (valid)
: => 85 => U (valid)
; => 95 => _ (valid)
< => 06 => (not valid)
= => 16 => (not valid)
> => 26 => (not valid)
? => 36 => $ (valid)
@ => 46 => . (valid)
A => 56 => 8 (valid)
B => 66 => B (valid)
C => 76 => L (valid)
D => 86 => V (valid)
E => 96 => ` (valid)
F => 07 => (not valid)
G => 17 => (not valid)
H => 27 => (not valid)
I => 37 => % (valid)
J => 47 => / (valid)
K => 57 => 9 (valid)
L => 67 => C (valid)
M => 77 => M (valid)
N => 87 => W (valid)
O => 97 => a (valid)
P => 08 => (not valid)
Q => 18 => (not valid)
R => 28 => (not valid)
S => 38 => & (valid)
T => 48 => 0 (valid)
U => 58 => : (valid)
V => 68 => D (valid)
W => 78 => N (valid)
X => 88 => X (valid)
Y => 98 => b (valid)
Z => 09 => (not valid)
[ => 19 => (not valid)
\ => 29 => (not valid)
] => 39 => ' (valid)
^ => 49 => 1 (valid)
_ => 59 => ; (valid)
` => 69 => E (valid)
a => 79 => O (valid)
b => 89 => Y (valid)
c => 99 => c (valid)
d => 001 => (not valid)
e => 101 => (not valid)
f => 201 => (not valid)
g => 301 => (not valid)
h => 401 => ( (valid)
i => 501 => 2 (valid)
j => 601 => < (valid)
k => 701 => F (valid)
l => 801 => P (valid)
m => 901 => Z (valid)
n => 011 => (not valid)
o => 111 => (not valid)
p => 211 => (not valid)
q => 311 => (not valid)
r => 411 => ) (valid)
s => 511 => 3 (valid)
t => 611 => = (valid)
u => 711 => G (valid)
v => 811 => Q (valid)
w => 911 => [ (valid)
x => 021 => (not valid)
y => 121 => (not valid)
z => 221 => (not valid)
{ => 321 => (valid)
| => 421 => * (valid)
} => 521 => 4 (valid)
~ => 621 => > (valid)
```
---
**ESOLANGS:** If you're using a custom CODEPAGE and wish to use the CODEPAGE definition as the ASCII table, I'll allow it. But you must be thorough in your explanation of why the characters are enumerated as they are (and it must make sense based on an existing code-page diagram). According to this 31/96 (32%) conversions are invalid, therefore it should follow that for a codepage of 255 characters, a consecutive range of 96 characters can be considered as "printable ASCII" if, and only if, it results in 31 (or 32%) or more of those characters being invalid.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 24 bytes
```
{s"_~"+{isW%Y60c~ic}%}_~
```
[Try it online!](https://tio.run/##S85KzP3/v7pYKb5OSbs6szhcNdLMILkuM7lWtTa@7v9/AA "CJam – Try It Online")
Prints:
```
3+;>+" 23NIb-Tc>2c4I4;>
```
A fairly standard generalised quine. The only character we could have used that is forbidden is `<`, which we get with `60c~` instead.
] |
[Question]
[
Rules:
1. Your program can be in any programming language.
2. Your program should not take any input.
3. Your program should transform the word "RELATIVE" into "STATIC". The word can at any stage only consist of uppercase letters A-Z.
4. Your program can only use 8 different operations.
5. The length, in number of letters, of the word cannot exceed 10 letters. If letters moves beyond that limit the letters will be deleted.
6. Your program must use all 8 operations before it can start reusing the operations again. All operations must be used the same amount of times.
7. The word must be "STATIC" at the end of the last chunk of 8 operations.
8. The very first OP used in the first chunk of OPs is never executed, so the program must output word "RELATIVE" of the first row.
9. The lines should be outputted in chunks of 8 lines, separated by a double linefeed between the chunks.
10. Your program should output the lines describing how it manipulates the string. Output each iteration of operations, one line for every applied operation in this form:
`<iteration # in 6 numbers>: <operation> <current word after OP is executed>`
The operations available:
```
INS Move the current word 1 character to the right and
replace first letter with 'A'.
DEL Deletes the last letter in the word.
INC Increase the second letter from the left with 1.
Example: 'A' converts into 'B' or a 'Z' converts into 'A'.
If the letter position is outside of the current word, nothing happens.
DEC Decrease the fourth letter from the left with 4.
Example: 'T' converts into 'P' or a 'C' converts into 'Y'.
If the letter position is outside of the current word, nothing happens.
SWT Swith letter number three from left with letter number two from right.
If any of the letters are outside of current word, nothing happens.
INV Invert the current word.
JMP Invalidates the nextcoming OP.
If this OP is used as OP #8 in a chunk, nothing happens.
REP Execute the previous op again.
If this OP is used as OP #1 in a chunk, nothing happens.
```
Example output (incomplete as the word is not "STATIC" at the end of the last chunk of 8 OPs):
```
000001: REP RELATIVE
000002: DEL RELATIV
000003: INS ARELATIV
000004: INC ASELATIV
000005: SWT ASILATEV
000006: INV VETALISA
000007: JMP VETALISA
000008: DEC VETALISA
000009: DEC VETWLISA
000010: JMP VETWLISA
000011: INS VETWLISA
000012: DEL VETWLIS
000013: REP VETWLI
000014: SWT VELWTI
000015: INC VFLWTI
000016: INV ITWLFV
```
The scoring is: (Sourcecode size in bytes) \* (# OP-chunks). The program with the smallest score wins. The competition ends at 2014-12-31.
[Answer]
## GolfScript, ~~338~~ ~~323~~ ~~307~~ ~~300~~ 280 \* ~~15~~ 10 = 2800
```
{:x;.2$<)65-x+26%65+[]++\@>+}:d;
{[{}{4-4d}{);}{2 1d}{'A'\+}{-1%}{2$~}{....2<\[-2=]+\3>-2<+\[2=]+\-1>+}]=}:L;
1:i;
'RDLATIVE':&;
'"S<(hR\50%!iS[SA*v7qpq&={=kkkk."Y+iEpi5-]'{32-}%95base`8/
{1:j;0L.@{48-:^j*L@;.&\~:&;i'0'6*\+-6>': ''JDDIIIRSMEENNNEWPCLCSVPT'^>8%' '&n^0>:j;i):i;}%n@;@;}/
```
Newlines added for clarity only, and can be removed. Pretty sure the output is correct.
[Test online](http://golfscript.apphb.com/?c=ezp4Oy4yJDwpNjUteCsyNiU2NStbXSsrXEA%2BK306ZDt7W3t9ezQtNGR9eyk7fXsyIDFkfXsnQSdcK317LTElfXsyJH59ey4uLi4yPFxbLTI9XStcMz4tMjwrXFsyPV0rXC0xPit9XT19Okw7MTppOydSRExBVElWRSc6JjsnIlM8KGhSXDUwJSFpU1tTQSp2N3FwcSY9ez1ra2trLiJZK2lFcGk1LV0nezMyLX0lOTViYXNlYDgvezE6ajswTC5AezQ4LTpeaipMQDsuJlx%2BOiY7aScwJzYqXCstNj4nOiAnJ0pERElJSVJTTUVFTk5ORVdQQ0xDU1ZQVCdePjglJyAnJm5eMD46ajtpKTppO30lbkA7QDt9Lw%3D%3D)
It probably can be golfed further.
---
I managed to chop off an entire 5 chunks of op-codes (although I did have to rewrite most of the algorithm).
Output:
```
000001: INC RELATIVE
000002: DEL RELATIV
000003: REP RELATI
000004: INS ARELATI
000005: DEC AREHATI
000006: INV ITAHERA
000007: JMP ITAHERA
000008: SWT ITAHERA
000009: DEC ITADERA
000010: INS AITADERA
000011: INV AREDATIA
000012: DEL AREDATI
000013: INC ASEDATI
000014: JMP ASEDATI
000015: SWT ASEDATI
000016: REP ASEDATI
000017: DEC ASEZATI
000018: INV ITAZESA
000019: DEL ITAZES
000020: SWT ITEZAS
000021: INS AITEZAS
000022: JMP AITEZAS
000023: INC AITEZAS
000024: REP AITEZAS
000025: DEC AITAZAS
000026: REP AITWZAS
000027: INS AAITWZAS
000028: INC ABITWZAS
000029: INV SAZWTIBA
000030: DEL SAZWTIB
000031: JMP SAZWTIB
000032: SWT SAZWTIB
000033: DEC SAZSTIB
000034: DEL SAZSTI
000035: INV ITSZAS
000036: SWT ITAZSS
000037: INS AITAZSS
000038: REP AAITAZSS
000039: JMP AAITAZSS
000040: INC AAITAZSS
000041: DEL AAITAZS
000042: INV SZATIAA
000043: INC SAATIAA
000044: REP SBATIAA
000045: INS ASBATIAA
000046: JMP ASBATIAA
000047: DEC ASBATIAA
000048: SWT ASAATIBA
000049: SWT ASBATIAA
000050: INS AASBATIAA
000051: INV AAITABSAA
000052: INC ABITABSAA
000053: DEL ABITABSA
000054: JMP ABITABSA
000055: DEC ABITABSA
000056: REP ABITABSA
000057: INV ASBATIBA
000058: DEL ASBATIB
000059: INS AASBATIB
000060: DEC AASXATIB
000061: JMP AASXATIB
000062: INC AASXATIB
000063: SWT AAIXATSB
000064: REP AASXATIB
000065: INV BITAXSAA
000066: DEL BITAXSA
000067: REP BITAXS
000068: SWT BIXATS
000069: INS ABIXATS
000070: INC ACIXATS
000071: JMP ACIXATS
000072: DEC ACIXATS
000073: INS AACIXATS
000074: INC ABCIXATS
000075: INV STAXICBA
000076: DEL STAXICB
000077: REP STAXIC
000078: JMP STAXIC
000079: SWT STAXIC
000080: DEC STATIC
```
] |
[Question]
[
Slighty inspired by my previous challenge regarding [Keith Numbers](https://codegolf.stackexchange.com/questions/9319/test-if-given-number-if-a-keith-number/) I want to propose a challenge to create a function that takes an integer and gives back a true or false depending on the number is a Reverse Keith number or not.
A reverse Keith uses the same little algorithm as Keith numbers, but ends up with it's starting number in reverse.
For example 12 is a Reverse Keith number
>
> **12**
>
>
> 1 + 2 = 3
>
>
> 2 + 3 = 5
>
>
> 3 + 5 = 8
>
>
> 5 + 8 = 13
>
>
> 8 + 13 = **21**
>
>
>
[Answer]
## APL (28)
```
⍙∊{1↓⍵,+/⍵}⍣{⊃⍺≥⍙∘←⍎⌽∆}⍎¨∆←⍞
```
Using more or less the same method as [TwiNight did in the other question](https://codegolf.stackexchange.com/a/9326) but reversing the number.
Explanation:
* `∆←⍞`: read a line as text, store in `∆`
* `⍎¨`: evaluate each character
* `{1↓⍵,+/⍵}`: add the sum of the list to the end of the list, and drop the first item,
* `⍣`: until
* `{⊃⍺≥⍙∘←⍎⌽∆}`: the first item on the list is greater or equal to `⍙`, which is the evaluation (`⍎`) of the reverse (`⌽`) of `∆`.
* `⍙∊`: see if `⍙` is contained in the final list.
[Answer]
## Perl, ~~126~~ ~~111~~ 110 chars
```
$r=reverse$_=shift;$l=@n=split//;while(1){$t=0;$t+=$_ for@n[-$l..-1];push@n,$t;die"true\n"if$r==$t;last if$t>$r}die"false\n";
```
Should be some room for improvement.
Updated with tips from Dom Hastings:
```
$r=reverse$_=shift;$l=@n=/./g;push(@n,$t=eval join'+',@n[-$l..-1])&&$r==$t&&die"true\n"while$r>$t;die"false\n"
```
You forgot that `$t` isn't being assigned a value with your suggestion, so that adds 3 characters if I want to use that in the following comparisons (it's still cheaper than using `$n[-1]` twice). However, I can save those by changing `split//` to `/./g`.
Slight improvement:
```
$r=reverse$_=shift;$l=@n=/./g;push@n,$t=eval join'+',@n[-$l..-1]and$r==$t&&die"true\n"while$r>$t;die"false\n"
```
Replaced `&&` operators with lower precedence `and` to be able to drop parentheses around call to `push`. Saves one character.
[Answer]
## PowerShell: 149 135
Mostly derived from my original [Keith Number Checker](https://codegolf.stackexchange.com/a/15243/9387). I'm sure there's still some work to be done.
```
$k=+(($j=($i=+(read-host))-split''|?{$_})[99..0]-join'');While($x-lt$k){$x=0;$j|%{$x+=$_};$null,$j=$j+$x}$x-eq$k-and$i-gt9-and$i%10-ne0
```
I definitely need to double-check for redundant parenthesis and semicolons. It's possible one of the casts to integer is unnecessary. One thing I might also need to spend time on is finding out if I can avoid false-positives without `-and$i%10-ne0`.
It'd be really nice if there was a reliable way to do a left-shift-and-append that's shorter than `$null,$j=$j;$j=@($j);$j+=$x`.
>
> **EDIT:** Found it! `$null,$j=$j+$x`
>
>
>
Cleanup $x between runs, and also $i, $j, $k when you're done.
[Answer]
# Mathematica ~~157~~ 96
```
f = (d = IntegerDigits@#; r = FromDigits@Reverse@d;
NestWhile[Rest@Append[#, Tr@#] &, d, Max@# < r &][[-1]] == r) &
```
Based on code by [Anton Vrba](http://mathworld.wolfram.com/notebooks/IntegerSequences/KeithNumber.nb) and considerably streamlined by @ssch.
```
f[11]
f[12]
f[20]
f[24]
```
>
> False
>
> True
>
> False
>
> True
>
>
>
[Answer]
## Game Maker Language, 129 136
Make this the function/script `f` and compile with uninitialized variables as 0.
```
a=argument0;while(a>0){b*=10b+=(a mod 10)b div 10}k[]=1k[1]=1while(k[c]<b){c+=1k[c]=k[c-1]+k[c-2]}while(e<c){e+=1if k[e]==b r=1}return r
```
It returns `true` or `false`; call with `f(any number you want)`
**Edit #1** Corrected invalid operators `%` and `/=` with `mod` and `div`.
[Answer]
## Haskell, 106
This version only works for `0 < x < 100` though.
```
k x=(last$takeWhile((>=)x)(let f=(map(Data.Char.digitToInt)$reverse$show x)++zipWith(+)f(tail f)in f))==x
```
**TODO:** check up on [Test if given number if a Keith number](https://codegolf.stackexchange.com/questions/9319/test-if-given-number-if-a-keith-number/) and implement a proper algorithm.
] |
[Question]
[
You can count 0, 1, 2, 3, 4.
But to get from 3 to 4 you have to change 3 bits at once.
Given a number of bits, how can you go through all numbers once,
but change at each step only 1! bit.
Here is an example for 3 bits:
```
000 100 110 010 011 111 101 001
```
so the output is:
```
0 1 3 2 6 7 5 4
```
## Rules:
* given a number of bits n, return a list of 2^n unique numbers
* between to consecutive numbers only one bit is different
* the shorter the code the better
[Answer]
Python 3:
```
for i in range(2**n):i^i//2
```
(Doh. Overlooked that this solutions is already known. Would delete it if stackexchange allowed it)
[Answer]
## GolfScript, 13 chars
```
~2\?,{.2/^}%`
```
For example, the input `3` produces the output `[0 1 3 2 6 7 5 4]`.
Here's a de-golfed version with comments:
```
~ # evaluate the input, turning it from a string into a number
2 \ ? # raise 2 to the power given by the input...
, # ...and turn it into a list containing the numbers from 0 to 2^n-1
{ . 2 / ^ } % # xor each number in the list with itself divided by 2
` # un-eval the list into a string for output
```
It's perhaps interesting to note that there are no particular "golfing tricks" involved — this *is* basically the most obvious and straightforward way to solve this task in GolfScript.
[Answer]
## C++, 188 bytes
```
#include <cstdlib>
#include <iostream>
#define y if(b)f(b-1)
int x=0;
void f(int b){y;std::cout<<(x^=1<<b)<<' ';y;}
int main(int,char**v){int b=std::atoi(v[1]);std::cout<<x<<' ';y;}
```
Specify the number of bits on the command line and it will print a list of space separated integers.
[Answer]
# F# (32)
```
[for i in 0..(1<<<n)-1->i^^^i/2]
```
If explicit output is not required, this will do the job (45 chars):
```
for i in 0..(1<<<n)-1 do printf"%i "(i^^^i/2)
```
Disclaimer: Very similar to the answer I provided [here](https://codegolf.stackexchange.com/a/32893/7548), just simplified to fit the output specified here.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
2*Ḷ^H$
```
[Try it online!](https://tio.run/nexus/jelly#@2@k9XDHtjgPlf///xsDAA "Jelly – TIO Nexus")
### How it works
```
2*Ḷ^H$ Main link. Argument: n
2* Yield 2ⁿ.
Ḷ Unlength; yield [0, ..., 2ⁿ].
$ Combine the two links to the left into a chain.
^H XOR each k in the range with k/2.
```
] |
[Question]
[
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a positive integer that's equal to one positive integer, to the power of another positive integer (e.g. *a**b* is a perfect power). Note that trivial solutions (e.g. *b*=1) are excluded; specifically, the definition requires *a* ≥ 2 and *b* ≥ 2.
## The task
Write a full program that takes any number of positive integers (separated by newlines) from standard input, and for each such input *n*, outputs all pairs of positive integers *a*, *b* (with *a* ≥ 2 and *b* ≥ 2) such that *a**b* = *n*. Use the syntax `a^b` for these pairs. If multiple pairs of outputs are possible for a given input, print all of them, separated by spaces.
Note the victory condition below: the aim here is to optimize the program for *speed*, not size.
## Example test cases
**Input**
```
1745041
1760929
1771561
1852321
1868689
1874161
1885129
1907161
1953125
113795717542678488615120001
113795717546049421004105281
```
**Output**
```
1745041 = 1321^2
1760929 = 1327^2
1771561 = 11^6 121^3 1331^2
1852321 = 1361^2
1868689 = 1367^2
1874161 = 37^4 1369^2
1885129 = 1373^2
1907161 = 1381^2
1953125 = 5^9 125^3
113795717542678488615120001 = 10667507560001^2
113795717546049421004105281 = 10667507560159^2
```
## Clarifications
* No more than 10000 inputs will be given on any single run of the program.
* Your program, as written, should be able to handle numbers up to at least 30 digits long (meaning you will likely need to use bignum support). In order for the victory condition to be meaningful, though, the underlying algorithm behind your submission must be capable of working for arbitrary perfect powers, no matter how large they are.
* Each input *n* will actually be a perfect power, i.e. there will always be at least one output corresponding to each given input.
* There are no restrictions on programming language (as long as the language has sufficient power to complete the task).
## Victory condition
The program with the fastest algorithm (i.e. with the fastest [complexity](https://en.wikipedia.org/wiki/Time_complexity)) will be the winner. (Note that the fastest known perfect power decomposition algorithms can determine whether a number is a perfect power, and what the base and exponent are, without having to actually factorise the number; you may want to take this into account when choosing the algorithm for your problem.)
In the case that two programs are equally fast by this measure, the tiebreak will be to see which program runs faster in practice (on the stated testcases or, to avoid hard-coding, a similar set of test cases).
[Answer]
## Python, 207 chars
This takes *O(log2 N)* bigint ops. *O(log N)* different exponents to try, and *O(log N)* binary search to find each base.
```
import sys
for N in map(int,sys.stdin.readlines()):
p,s=2,''
while 1<<p<=N:
i,j=2,N
while j>i+1:
m=(i+j)/2
if m**p>N:j=m
else:i=m
if i**p==N:s+=' %d^%d'%(i,p)
p+=1
if s:print N,'=',s[1:]
```
[Answer]
# C - No bigints
My solution use a 64 bit float and a 64 bit integer in combination to produce the result without using slow bignumber arithmetic. First a possible set of values that fit the high-order bits are produced using floats, then the low order is checked using integers. Due to 64 bit floats having 53 bit mantissa the method will break for numbers around 106 bit in length, but the task was only for up to 100 bit numbers.
```
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "math.h"
#define i64 unsigned long long
#define i32 unsigned int
#define f64 double
int main(){
char inp[31];
while(1==scanf("%30s",inp)){
printf("%s =",inp);
f64 upper=strtod(inp,NULL);
//i64 lower=strtoull(inp,NULL,10);
//i64 lower=atoll(inp);
//Neither library function produce input mod 2^64 like one would expect, fantabulous!
i64 lower=0;
i32 c=0;
while(inp[c]){
lower*=10;
lower+=inp[c]-48;
c++;
}
f64 a,b;
i64 candidate;
f64 offvalue;
f64 offfactor;
i32 powleft;
i64 product;
i64 currentpow;
for(a=2;a<50;a++){ //Loop for finding large bases (>3).
b=1.0/a;
b=pow(upper,b);
candidate=(i64)(b+.5);
if(candidate<4){
break;
}
offvalue=b-(f64)candidate;
offfactor=fabs(offvalue/b);
if(offfactor<(f64)1e-14){
product=1;
powleft=(i32)a;
currentpow=candidate;
while(powleft){ //Integer exponentation loop.
if(powleft&1){
product*=currentpow;
}
currentpow*=currentpow;
powleft=powleft>>1;
}
if(product==lower){
printf(" %I64u^%.0lf",candidate,a);
}
}
}
for(candidate=3;candidate>1;candidate--){ //Loop for finding small bases (<4), 2 cycles of this saves 50 cycles of the previous loop.
b=log(upper)/log(candidate);
a=round(b);
offfactor=fabs(a-b);
if((offfactor<(f64)1e-14) && (a>1)){
product=1;
powleft=(i32)a;
currentpow=candidate;
while(powleft){ //Integer exponentation loop.
if(powleft&1){
product*=currentpow;
}
currentpow*=currentpow;
powleft=powleft>>1;
}
if(product==lower){
printf(" %I64u^%.0lf",candidate,a);
}
}
}
printf("\n");
if(inp[0]==113){ //My keyboard lacks an EOF character, so q will have to do.
return 0;
}
}
return 0;
}
```
As for runtime, ideone produce a clean 0 <http://www.ideone.com/HJl2f> this should be a pretty superior method, but any attempt to verify this will drown in I/O.
[Answer]
## Ruby
Non-golfed, not-really-optimized solution. I hope I didn't mess up my math.
Roots are calculated first using core `sqrt` and `cbrt` methods, then using dumb approximation (binary search).
On my PC, 10000 long random inputs (not necessarily actually having non-trivial representations) take ~30 seconds (see the `bench` method).
```
def root start, exp, startapprox=nil
if exp==1
return start
elsif exp==2
return Math.sqrt(start).round
elsif exp==3 and Math.respond_to? :cbrt # 1.9 only
return Math.cbrt(start).round
else
lower=0
upper=startapprox||Math.sqrt(start).ceil
until upper-lower<=1
res=(lower+upper)/2
if res**exp<start
lower=res+1
else
upper=res
end
end
distlow=(start - lower**exp).abs
distupp=(start - upper**exp).abs
if distlow<distupp
return lower
else
return upper
end
end
end
def powers number
ret=[]
skip=[]
maxexp=(Math.log2 number).floor
prev=nil
2.upto(maxexp) do |exp|
next if skip[exp]
rt=root number, exp, prev
if number==rt**exp
ret<<"#{rt}^#{exp}"
else
(exp..maxexp).step(exp){|i| skip[i]=true} # if it's not 2nd power, it cant be 4th power etc
end
prev=rt
end
"#{number} = #{ret.reverse.join ' '}"
end
def bench n=10
require 'benchmark'
Array.new(n){Benchmark.realtime{powers rand 1e30}}.inject(:+)
end
# read input, output powers
if __FILE__==$0
while (a=gets.strip).length>0
puts powers a.to_i
end
end
```
[Answer]
# C++, not sure if it's correct
```
#include <iostream>
#include<iomanip>
#include <cstdio>
#include <cmath>
using namespace std;
int main() {
long double x;
char s[120];
ios::sync_with_stdio(false);
//cout << setprecision(20);
while (cin >> s) {
cout << s << " =";
//sscanf (s, "%Lf", &x);
x = 0;
for (char*p=s; *p; p++) {
x = 10*x + (*p-48);
}
for (int i=2; ; i++) {
long double tmp = pow(x, 1./i);
if (tmp<1.98) break;
long long inty = tmp + 0.5;
tmp = powl(inty, i) - x;
//cout << "[" << i << ' ' << inty << ' ' << tmp << "]\n";
if (abs(tmp * 1e19) < x)
cout << ' ' << inty << '^' << i;
}
cout << '\n';
}
}
```
If `Each input n will actually be a perfect power`, numbers may needn't be not so accurate/precise. Here my `long double` is `TBYTE` type, though `sizeof(x)` is 12
] |
[Question]
[
I could not think of a better title.
**This is a tips question. I'm asking for tips on golfing my code.**
I recently took part in a code golf competition in C. The competition ended and I lost. The problem is:
>
> Input a line with a number *n*.
>
>
> Then input *n* lines, each line contains only a set of cards in descending order, e. g. `X2AAKKKKQT9765433` or `DX22AKKQJTT884443`. Figure out if it contains `DX` **or** four of the same cards in a row.
>
>
>
Obviously, this is a chameleon challenge (finding `DX` is essentially the same as checking the second character if it is `X`, and to check for four of the same cards you only need to check the first and the last card of the quadruplet, because the cards are in descending order.)
In that competition, the input format is strict, and error-terminating is disallowed.
After the competition, we continued to improve on this problem. We've got this so far (98 bytes):
```
char*p,s[99];main(){for(gets(s);gets(p=s);puts(s[1]>87?"Yes":"No"))for(;*p;)s[1]|=*p^p++[3]?0:88;}
```
I'm looking for tips to golf this down further.
[Answer]
**94 bytes**
Instead of increasing `s[1]` when you find a quadruplet, setting it to zero is a bit cheaper. The conditional in `puts` stays the same length:
```
char*p,s[99];main(){for(gets(s);gets(p=s);puts(s[1]%88?"No":"Yes"))for(;*p;)s[1]*=*p!=p++[3];}
```
[Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq0CnONrSMtY6NzEzT0OzOi2/SCM9taRYo1jTGkwX2AJZBaUgkWjDWFULC3slv3wlK6XI1GIlTU2QcmutAmtNkKSWrVaBom2Btna0cax17f//xlwRRo6O3kAQGGJpbmZqYmzM5RJhZAQUCvQKCbGwMDExAalBEwEA "C (gcc) – Try It Online")
[dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) suggested two more improvements:
**93 bytes**
If we can avoid to produce in the first iteration, The initial call to `gets` can be dropped. This is achieved by assuming the first argument to `main` (argc) is 1, which is the case if there are no command line arguments.
```
char*p,s[99];main(i){for(;gets(p=s);--i&&puts(s[1]%88?"No":"Yes"))for(;*p;)s[1]*=*p!=p++[3];}
```
[Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq0CnONrSMtY6NzEzTyNTszotv0jDOj21pFijwLZY01pXN1NNraAUyC2ONoxVtbCwV/LLV7JSikwtVtLUBCvWKrDWBElq2WoVKNoWaGtHG8da1/7/b8wVYeTo6A0EgSGW5mamJsbGXC4RRkZAoUCvkBALCxMTE5AaNBEA "C (gcc) – Try It Online")
**87 bytes**
If you stop the inner for loop as soon a quadruplet is found or the end of input is reached, `*p>0` indicates a quadruplet:
```
char*p,s[99];main(i){for(;gets(p=s);--i&&puts(s[1]>87|*p?"Yes":"No"))for(;*p++-p[2];);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z85I7FIq0CnONrSMtY6NzEzTyNTszotv0jDOj21pFijwLZY01pXN1NNraAUyC2ONoy1szCv0SqwV4pMLVayUvLLV9LUBKvXKtDW1i2INoq11rSu/f/fmCvCyNHRGwgCQyzNzUxNjI25XCKMjIBCgV4hIRYWJiYmIDVoIgA "C (gcc) – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Generate all combinations of given list of elements, sorted](/questions/102835/generate-all-combinations-of-given-list-of-elements-sorted)
(14 answers)
Closed 2 years ago.
Taking a positive integer `n` as input, print the sample space of `n` consecutive coin flips. The coin is fair, with two sides `H` and `T`, each with probability `0.5`.
For example,
Input - `3`
Output -
```
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT
```
**Rules**
* [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* You may print the elements out of order, but all of them should be present.
* You may use any form of output, as long as heads and tails are displayed as 'H' and 'T', and all elements are distuinguishable.
This is `code-golf`, so the shortest code in bytes wins. Good luck!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁾HTṗ
```
A monadic Link accepting a non-negative integer which yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8//9R4z6PkIc7p/8/3B75/78xAA "Jelly – Try It Online")** (footer calls the Link and joins with newline characters)
### How?
```
⁾HTṗ - Link: integer, n
⁾HT - list o characters = ['H', 'T']
ṗ - (that) Cartesian power (n)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
lambda x:product(*["HT"]*x);from itertools import*
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqqAoP6U0uURDK1rJI0QpVqtC0zqtKD9XIbMktagkPz@nWCEztyC/qETrf0FRZl6JRk5mcYlGmoaxpqYmFxeKkClQ6D8A "Python 3 – Try It Online")
I like my recursive approach better, but unfortunately, using module built-ins is shorter lol.
# [Python 3](https://docs.python.org/3/), 54 bytes
```
f=lambda x:x and[y+q for y in f(x-1)for q in"HT"]or" "
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocKqQiExLyW6UrtQIS2/SKFSITNPIU2jQtdQE8QtBHKVPEKUYvOLlBSU/hcUZeaVaKRpGGtqcnHBOKaamv8B "Python 3 – Try It Online")
-1 byte thanks to Jonathan Allan
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 41 40 39 bytes
```
eval echo $(printf \{H,T}%.0s `seq $1`)
```
[Try it online!](https://tio.run/##S0oszvifpqFZ/T@1LDFHITU5I19BRaOgKDOvJE0hptpDJ6RWVc@gWCGhOLVQQcUwQfN/LVeaghEQG/8HAA "Bash – Try It Online")
*-1 thanks to pxeger*
*-1 thanks to Digital Trauma*
## Alternative, also 41 bytes
```
(($1))&&f $[$1-1] $2'{H,T}'||eval echo $2
```
[Try it online!](https://tio.run/##S0oszvifpqFZ/V9DQ8VQU1NNLU1BJVrFUNcwVkHFSL3aQyekVr2mJrUsMUchNTkjHyj4v5YrTcEQiI2A2Pg/AA "Bash – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
f=(x,a=[''])=>x?f(--x,a.flatMap(n=>[n+'H',n+'T'])):a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajQifRNlpdPVbT1q7CPk1DVxcooJeWk1jim1igkWdrF52nre6hrgMkQ4CKNK0S/yfn5xXn56Tq5eSna6RpGGpqcqGKGGGIGGOImGCImGpq/gcA "JavaScript (Node.js) – Try It Online")
A pretty simple recursive approach.
[Answer]
# Excel, 62 bytes
```
=IF(MOD((INT(SEQUENCE(2^A1)/2^(SEQUENCE(1,A1)-1))),2),"T","H")
```
Answer is spilled into a 2^n by n array of cells. Starts to get slow around 19.
## Alternative, 65 bytes
```
=SUBSTITUTE(SUBSTITUTE(DEC2BIN(SEQUENCE(2^A1)-1,A1),1,"T"),0,"H")
```
Slightly longer and only works for n<=10.
[Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnAOXUS4i4AoXHVPS?e=0B7Ei7)
] |
[Question]
[
Write a regex that only matches valid country code top level domains (ccTLDs). Your regex must match both the domains with the dot and without the dot (it must match tv and .tv). Any domain that is not a ccTLD or does not exist (e.g. .info or .jobs or .xz) must not be matched.
Use Perl, POSIX, PCRE or Python.
For reference, this is the full list of ccTLDs, as of challenge creation:
.ac .ad .ae .af .ag .ai .al .am .ao .aq .ar .as .at .au .aw .ax .az .ba .bb .bd .be .bf .bg .bh .bi .bj .bm .bn .bo .br .bs .bt .bw .by .bz .ca .cc .cd .cf .cg .ch .ci .ck .cl .cm .cn .co .cr .cu .cv .cw .cx .cy .cz .de .dj .dk .dm .do .dz .ec .ee .eg .er .es .et .eu .fi .fj .fk .fm .fo .fr .ga .gd .ge .gf .gg .gh .gi .gl .gm .gn .gp .gq .gr .gs .gt .gu .gw .gy .hk .hm .hn .hr .ht .hu .id .ie .il .im .in .io .iq .ir .is .it .je .jm .jo .jp .ke .kg .kh .ki .km .kn .kp .kr .kw .ky .kz .la .lb .lc .li .lk .lr .ls .lt .lu .lv .ly .ma .mc .md .me .mg .mh .mk .ml .mm .mn .mo .mp .mq .mr .ms .mt .mu .mv .mw .mx .my .mz .na .nc .ne .nf .ng .ni .nl .no .np .nr .nu .nz .om .pa .pe .pf .pg .ph .pk .pl .pm .pn .pr .ps .pt .pw .py .qa .re .ro .rs .ru .rw .sa .sb .sc .sd .se .sg .sh .si .sk .sl .sm .sn .so .sr .ss .st .sv .sx .sy .sz .tc .td .tf .tg .th .tj .tk .tl .tm .tn .to .tr .tt .tv .tw .tz .ua .ug .uk .us .uy .uz .va .vc .ve .vg .vi .vn .vu .wf .ws .ye .yt .za .zm .zw -- open for registration
.an .bl .bq .bv .eh .gb .mf .sj .su .tp .um -- not open (still must be matched)
^ and $ anchors are not needed.
[Answer]
## 275 bytes
```
\.?([cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x|[bcgkmp][ghmnrwy]|[psu][agksy]|[aen][cegru]|[abcn][fioz]|l[abcikr-vy]|[bdjkprsvy]e|[bcgmnqvz]a|[behpsty]t|[cghmrv]u|[fgksv]i|[gjkmn]p|b[bdjs]|h[kmnr]|[gptw]f|[artz]w|v[cgn]|[joz]m|[ijr]o|[erw]s|[dku]z|[np]l|fr|in|sb)
```
(277 bytes including `^$`.) A Python program was used to autogenerate part of this regular expression. Here is the first version of the program:
```
def makeregex(list):
if len(list) == 1:
return alpha[list[0]]
regex = "["
j = list[0]
while j < 26:
if j in list:
if j + 1 in list and j + 2 in list and j + 3 in list:
regex += alpha[j] + "-"
while j + 1 in list:
j += 1
regex += alpha[j]
j += 1
return regex + "]"
def perform(rows, cols):
replaced = '|'.join([alpha[j] + alpha[k] for j in rows for k in cols if array[j][k] > 0])
regex = makeregex(rows) + makeregex(cols)
print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'
for j in rows:
for k in cols:
if (array[j][k]):
array[j][k] = -1
else:
raise Exception("filling illegal entry")
all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]
#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])
while max(max(row) for row in array) > 0:
best = 0
i = 1
while i < 1 << 26:
row = [-1 for j in range(26)]
for j in range(26):
if (i & 1 << j):
for k in range(26):
if array[j][k] == 0:
row[k] = 0
elif array[j][k] == 1 and row[k]:
row[k] = max(row[k], 0) + 1
if max(row) < 1:
break;
if max(row) > 0:
total = 3 * sum(max(j, 0) for j in row)
if total > best:
rows = [j for j in range(26) if i & 1 << j]
cols = [j for j in range(26) if row[j] > 0]
total -= len(makeregex(rows)) + len(makeregex(cols)) + 1
if total > best:
best = total
bestrows = rows
bestcols = cols
i += 1
else:
i += i & -i
if best:
perform(bestrows, bestcols)
else:
print '|'.join([alpha[j] + alpha[k] for j in range(26) for k in range(26) if array[j][k] > 0])
break
```
This 282-byte regex results from its output:
```
\.?([bgmps][aeghmnrsty]|[cmst][cdghk-orvz]|[acn][cfgiloruz]|[agim][delmq-t]|[bck][ghimnrwyz]|[elm][cr-u]|[dft][jkmo]|[agpt][fltw]|[gnv][aegiu]|[lpu][aksy]|[gjkm][emp]|h[kmnrtu]|b[bdfjo]|r[eosuw]|[ls][biv]|[acms]x|[cmz][amw]|[dey]e|dz|eg|fi|fr|in|io|jo|np|om|qa|ug|uz|vc|vn|wf|ws|yt)
```
The program can also be seeded by adding calls to `perform`, so I tried seeding it with `[cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x` but that just resulted in a rearranged regex. Obviously this wasn't good enough. The problem seemed to be that I was comparing the performance against a simple alternation. I therefore developed a slower but more accurate scoring function, which works by assuming that all of the remaining matches should be either `x[yz]` or `[xy]z` alternations, generating the largest alternations first, and compares the result with and without the trial regex.
```
def makeregex(list):
if len(list) == 1:
return alpha[list[0]]
regex = "["
j = list[0]
while j < 26:
if j in list:
if j + 1 in list and j + 2 in list and j + 3 in list:
regex += alpha[j] + "-"
while j + 1 in list:
j += 1
regex += alpha[j]
j += 1
return regex + "]"
def simple(array):
unused = [[j > 0 for j in row] for row in array]
regex = ""
while max(max(row) for row in unused):
rowcount = [sum(row) for row in unused]
colcount = [sum(col) for col in zip(*unused)]
if max(colcount) > max(rowcount):
colindex = colcount.index(max(colcount))
col = zip(*unused)[colindex]
regex += "|" + makeregex([j for j in range(26) if col[j]]) + alpha[colindex]
for j in range(26):
unused[j][colindex] = 0
else:
rowindex = rowcount.index(max(rowcount))
row = unused[rowindex]
regex += "|" + alpha[rowindex] + makeregex([j for j in range(26) if row[j]])
unused[rowindex] = [0 for j in range(26)]
return regex
def perform(rows, cols):
previous = simple(array)[1:].split('|')
for j in rows:
for k in cols:
if (array[j][k]):
array[j][k] = -1
else:
raise Exception("filling illegal entry")
regex = (makeregex(rows) + makeregex(cols) + simple(array)).split('|')
replaced = '|'.join(j for j in previous if not j in regex)
regex = '|'.join(j for j in regex if not j in previous)
print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'
all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]
#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])
while max(max(row) for row in array) > 0:
best = simple(array)[1:]
bestrows = []
bestcols = []
i = 1
while i < 1 << 26:
row = [-1 for j in range(26)]
for j in range(26):
if (i & 1 << j):
for k in range(26):
if array[j][k] == 0:
row[k] = 0
elif array[j][k] == 1 and row[k]:
row[k] = max(row[k], 0) + 1
if max(row) < 1:
break;
if max(row) > 0:
rows = [j for j in range(26) if i & 1 << j]
cols = [j for j in range(26) if row[j] > 0]
unused = [row[:] for row in array]
for j in rows:
for k in cols:
unused[j][k] = 0
total = makeregex(rows) + makeregex(cols) + simple(unused)
if len(total) < len(best):
best = total
bestrows = rows
bestcols = cols
i += 1
else:
i += i & -i
if bestrows:
perform(bestrows, bestcols)
else:
print best
break
```
Now without seeding, this actually produces the worse 286-byte regex:
```
\.?([bgp][ae-hmnrstwy]|[cst][cdghk-orvz]|[nv][acegiu]|m[acdeghk-z]|a[c-gilmoq-uwxz]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|s[abeistxy]|c[afiuwxy]|e[cegr-u]|b[bdijoz]|d[ejkmoz]|f[ijkmor]|g[dilpqu]|h[kmnrtu]|n[floprz]|u[agksyz]|r[eosuw]|j[emop]|t[fjtw]|z[amw]|p[kl]|w[fs]|y[et]|om|qa|vn)
```
When seeded with `[cmst][cdghk-orvz]` (which I had independently discovered manually before writing the first program) this improves to this 282-byte regex, thus equalling the first program:
```
\.?([cmst][cdghk-orvz]|[bgmps][aeghmnrsty]|[ag][d-gilmq-uw]|[pt][fkltw]|[acs][cioxz]|[nv][acegiu]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|b[bdfijowz]|e[cegr-u]|d[ejkmoz]|f[ijkmor]|h[kmnrtu]|n[floprz]|u[agksyz]|c[afuwy]|m[pquwx]|r[eosuw]|j[emop]|z[amw]|w[fs]|y[et]|gp|om|qa|sb|tj|vn)
```
After some experimentation I discovered that when seeded with `[cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x` (selected from the output of the first version), it results in the given 275-byte regex.
For completeness, I think the best I achieved manually was the following 282-byte regex:
```
\.?(a[c-gilmoq-uwxz]|b[abd-jostz]|c[afiuwxy]|d[ejkmoz]|e[cegr-u]|f[ijkmor]|g[ad-ilp-u]|h[kmnrtu]|i[del-oq-t]|j[emop]|k[ipz]|l[abcikr-vy]|m[aep-y]|n[acefgilopruz]|om|p[aflst]|qa|r[eosuw]|s[abeistxy]|t[fjtw]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]|[cmst][cdghk-orvz]|[bgkp][eghmnrwy])
```
[Answer]
# 282 bytes
```
\.?([abcmpt][fglmnrw]|[abgim][delmnq-t]|[acms]x|[adkn][ez]|[aemsv][cegu]|[afn][ior]|[bcmst][dghl-orvz]|[bgls][abirsty]|[clmpu][aky]|[clnv][aciu]|[dfst][jkmo]|[egp][eghrst]|[gmnt][fglpr]|[gr][esuw]|[ir]o|[ty]t|bj|h[kmnrtu]|j[emop]|k[ghimnprwy]|lv|om|qa|tc|u[gmsz]|vn|w[fs]|ye|z[amw])
```
[Try it online!](https://tio.run/##fVFBcsMgDLz3FR6f7DbxpQ/oQyjTIRgwMQIisB1n@Lsrmh566gHQrqRdAXHPU/Dvh4UYMDeoTk3KaL15ibTn7rVrh7Z5a@609kYHpMj635pBJGntlwubQimS@snv/@StJodBL86ByHLqsG3b43P46Ji4SIiZM20ceNx4IcZY4GxURNzOuTISEr/TOc6eM/WolIK0ciaVWSrSxNuAFJJcIrnRTO4ccK21F@MSJ1mLKe@EpYO4EDE/gScdIW3VGXXtvc4QCCgTycxM1EXIgH9OGauLQUqlpY5rkYfCSDiXy7VMbKZrZBK7MgUh8jIzM1nwETeyc2sJUG6iZFkW0kw03@rLxnTiZVflwQRsvD/oeYb6lLHrT82fj@j7/vgG "Python 3 – Try It Online")
### ~~276 bytes~~—old list
```
\.?([abt][dfgmortwz]|[aclnv][ciu]|[acms]x|[agim][delmq-t]|[bcgkmp][ghmnrwy]|[bdijnr][eo]|[cgnp][afglr]|[cmst][cdghk-orvz]|[dft][jkmo]|[dknu]z|[epsy][et]|[fgks]i|[gjkmn][ep]|[gmv][aegnu]|[jo]m|[psu][agksy]|b[abijs]|e[cgrsu]|fr|h[kmnrtu]|in|l[abkr-vy]|qa|r[suw]|sb|w[fs]|z[amw])
```
[Try it online!](https://tio.run/##fVFLcoQgFNznFJYrTWbc5AA5CKFSiICoIPPAcZzi7qZJZZFVFny6Xz@6gXCkcfXvp3VhpVSRulQxkfXmJWBOzWtTd3X1Vj0wjkqvhJ31v5pORGnt17LuiqSI6qd@/FO3Gg6d3pbFiSTHhuq6Pj@7j4aJPnE2aOOQYn/yzIRc/J0zabcf4CJ/YDXWQaYWd7sm8L00swucmdF52o/CDHbyxJlaAaTxKAptFirIRXjIwYzzdaV7MRk0mGl2RTzMfuPPzFSIB/rL8drMkdvMDCQeXABnHFIJZXzJNa3cZRbiBgpaBOhxEztFnhXcCYWsKY8M/ZQArM8LFDNd7xDfRCYWt53n2OedabQ9mXA7b088TFceMTTtpfrzBW3bnt8 "Python 3 – Try It Online")
] |
[Question]
[
# Introduction
So my boss is making me do some [manual labor](https://en.wikipedia.org/wiki/Manual_labour)...urgh...I have to take a part out a box of parts, process it and put it back in the box. To make this more interesting I try to sort the parts as I do this, as each part has a unique alphanumeric serial number.
Unfortunately, I only have room to have four parts out the box at a time and I'm not taking each part out of the box more than once (that'd be even more work!) so my sorting capabilities are limited.
# Challenge
Your challenge is to write a full program or function that rates my sorting of a given box of parts.
# The Sorting Process
1. Take 4 parts out of the box
2. Take the part that comes first by serial number
3. Process the part
4. Put the part back in the box
5. Take another part out of the box (if there are any left)
6. Repeat steps 2-6 until all parts are processed (moved only once).
# Input
A set of serial numbers in the format `[A-Z][A-Z][0-9][0-9][0-9]`
Input can be an array/list or deliminated string, python example...
```
['DT064', 'SW938', 'LB439', 'KG338', 'ZW753', 'FL170', 'QW374', 'GJ697', 'CX284', 'YW017']
```
# Output:
The score of the sorted/processed box (see scoring below)
# Scoring
For each part note how far away it is from where it would be in a perfectly sorted box. The score is the total of this value for all parts in the box.
# Examples/Test cases
```
input ['AA111', 'AA222', 'AA333', 'AA444', 'AA000', 'AA555']
my sorted list ['AA111', 'AA000', 'AA222', 'AA333', 'AA444', 'AA555'] (no need to output)
perfect sort ['AA000', 'AA111', 'AA222', 'AA333', 'AA444', 'AA555'] (no need to output)
output 2 (because first two elements are out of sequence by 1 position each)
input ['GF836', 'DL482', 'XZ908', 'KG103', 'PY897', 'EY613', 'JX087', 'XA056', 'HR936', 'LK200']
my sorted list ['DL482', 'GF836', 'EY613', 'JX087', 'KG103', 'HR936', 'LK200', 'PY897', 'XA056', 'XZ908']
perfect sort ['DL482', 'EY613', 'GF836', 'HR936', 'JX087', 'KG103', 'LK200', 'PY897', 'XA056', 'XZ908']
output 6
input ['UL963', 'PJ134', 'AY976', 'RG701', 'AU214', 'HM923', 'TE820', 'RP893', 'CC037', 'VK701']
output 8
input ['DE578', 'BA476', 'TP241', 'RU293', 'NQ369', 'YE849', 'KS028', 'KX960', 'OU752', 'OQ570']
output 6
input ['BZ606', 'LJ644', 'VJ078', 'IK737', 'JR979', 'TY181', 'RJ990', 'ZQ302', 'AH702', 'EL539']
output 18
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~25~~ ~~24~~ 23 bytes
**-5** bytes thanks to **Emigna**
```
gÍG4ôć{ćˆì˜}¯ì©{vXykNαO
```
[Try it online!](https://tio.run/##MzBNTDJM/f8//XCvu8nhLUfaq4@0n247vOb0nNpD6w@vObSyuuzQuspsv3Mb/f//j1Z3ijIzMFPXUVD38TIzMQExwrwMzC1ADE9vc2NzEMMryNLcEsQIiTS0MAQxgrwsLQ1AjKhAYwMjEMPRwxzCcPUxNbZUjwUA "05AB1E – Try It Online")
### Explanation
```
gÍG4ôć{ćˆì˜}¯ì©{vXykNαO Argument l
gÍG } len(l)-3 times do:
4ô Split into pieces of 4
ć Extract head
{ Sort
ćˆ Extract head and add to global array
ì˜ Put rest of array back together
¯ì Prepend global array to leftover elements
© Store in register_c without popping
{ Sort
v For y in sorted array, do:
®yk Index of y in register_c
Nα Absolute difference with iteration index
O Total sum of index differences
```
[Answer]
## JavaScript (ES6), 104 bytes
```
a=>a.reduce(p=>(j=i-[...a].sort().indexOf(a[a.splice(i,4,...a.slice(i,i+4).sort()),i++]))>0?p+j:p-j,i=0)
```
### Test cases
```
let f =
a=>a.reduce(p=>(j=i-[...a].sort().indexOf(a[a.splice(i,4,...a.slice(i,i+4).sort()),i++]))>0?p+j:p-j,i=0)
console.log(f(['AA111', 'AA222', 'AA333', 'AA444', 'AA000', 'AA555']))
console.log(f(['GF836', 'DL482', 'XZ908', 'KG103', 'PY897', 'EY613', 'JX087', 'XA056', 'HR936', 'LK200']))
console.log(f(['UL963', 'PJ134', 'AY976', 'RG701', 'AU214', 'HM923', 'TE820', 'RP893', 'CC037', 'VK701']))
console.log(f(['DE578', 'BA476', 'TP241', 'RU293', 'NQ369', 'YE849', 'KS028', 'KX960', 'OU752', 'OQ570']))
console.log(f(['BZ606', 'LJ644', 'VJ078', 'IK737', 'JR979', 'TY181', 'RJ990', 'ZQ302', 'AH702', 'EL539']))
```
[Answer]
## JavaScript (ES6), ~~115~~ 113 bytes
```
a=>a.reduce((r,_,i)=>r+=(i-=[...a].sort().indexOf((b=b.splice(0,4).sort().concat(b)).shift()))<0?-i:i,0,b=[...a])
```
[Answer]
# [PHP](https://php.net/), 132 bytes
```
<?for($d=4+count($p=$g=$_GET),sort($p);--$d;rsort($n),$i<4?:$r+=abs($k++-array_flip($p)[array_pop($n)]))$d<4?:$n[]=$g[+$i++];echo$r;
```
[Try it online!](https://tio.run/##Jc3BCoJAEAbge0/RYUCXVbA0t21boiAq61JEUCJhWimFu2x16ME7W5O37x/mn9GFrocjXegWHGfTrYytySH0QstpW6soDALELvJYH7FYMp8hog1nHLHdd/odxCbi3EMc1r7XRYznrMF01fO5lYj6oowNuQxopl7V0wYt4Sr/b4nzUAYnRLgu5MI0sSIOlMNgNABDZXp62HCj1E2NSd/Hy73UWIibqJXG/YQQyP@NKk5@52MKJaWJOGeFAiPq@lMpN0uz4vwF "PHP – Try It Online")
# [PHP](https://php.net/), 136 bytes
```
<?for($n=array_slice($p=$g=$_GET,0,$i=3),sort($p);$n;rsort($n),$r+=abs($k++-array_flip($p)[array_pop($n)]))$g[$i]&&$n[]=$g[$i++];echo$r;
```
[Try it online!](https://tio.run/##Jc1Bi8IwEAXgu79iD4NtSIS4dRtDNsguyGrXiyLCWoJ0S7VFSULqxR/uuTr29j3m8cbXvvuc@doP4PAz3@o8@t6nPI3YW7TK0skEscu4mCKWvyIRiGwjhURs/8bTMWKTSckR@3XC3xFfC9FjvvpIZGRUd3QhBquLEIrbob00ZRWD13DSr9eMM2h0QljrwvV5IAqsCn2whEGguvhvYzhTOuonjpfGYzHvo3cem4YQOOXQmOEQbG70K1BqVFXWDoLqurt1o7Io6@oB "PHP – Try It Online")
[Answer]
# Mathematica, 173 bytes
```
A={};(V=Sort[S=#];While[Length@S>4,T=Take[Sort@S[[;;4]],1][[1]];A~AppendTo~T;S=S~DeleteCases~T];Tr@Table[Abs[i-Flatten[Position[Join[A,Sort@S],V[[i]]]][[1]]],{i,Length@V}])&
```
**input**
>
> [{BZ606, LJ644, VJ078, IK737, JR979, TY181, RJ990, ZQ302, AH702,
> EL539}]
>
>
>
**output**
>
> 18
>
>
>
] |
[Question]
[
What general tips do you have for golfing in Mini-Flak? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Mini-Flak (e.g. "remove comments" is not an answer).
Please post one tip per answer.
Mini-Flak is just Brain-flak without `[]`, `<...>` or `<>` so tips for Mini-Flak are different for a large amount of problems. However the use of brackets like `[...]` are allowed.
[Answer]
# Zero efficiently
The `<...>` from Brain-flak is missing so it is often required that you replace it with something else.
The two following snippets do just that:
* `(...)[{}]`
* `[(...)]{}`
However when you are zeroing it is important to select these properly, because there is a lot of golfing that can be done that can't be done with Brain-Flak's zeros. For example the following Brain-Flak code:
```
({}[()]<({}())>)
```
Could be reconstituted as
```
({}[()](({}()))[{}])
```
However it is cheaper to do
```
({}[()(({}()))]{})
```
You should try to combine your negative with as many other negatives in the scope as possible.
[Answer]
# Use "XOR swap"-style swaps to move values around
One of the biggest issues with Mini-Flak's command set is that, having only "two" stacks (the active stack, and the stack of temporary values implied by the structure of the program), you can't move two values past each other with simple copying; if you have value *a* above *b* on the primary stack, and want *b* above *a*, at some point you'll have to have a stack element that's storing parts of *b* and *a* simultaneously.
There's a well known trick in languages like C to swap two values without using a temporary:
```
a ^= b; /* now a = a0^b0, b = b0 */
b ^= a; /* now a = a0^b0, b = a0 */
a ^= b; /* now a = b0, b = a0 */
```
The trick is that you temporarily use `a` to store a combination of `a` and `b`, so that you can use the combined value to transform `b` into `a`, and then use the value of `a` you just obtained to recover `b` from the combined value.
Less well known is that you can do the same trick with addition and subtraction:
```
a -= b; /* now a = a0-b0, b = b0 */
b += a; /* now a = a0-b0, b = a0 */
a = b-a; /* now a = b0, b = a0 */
```
This version of the trick uses only operations that we have available in Brain-Flak, so we can actually write it.
When I wrote it by hand, I eventually golfed it into the following program (which uses a different sequence of additions and subtractions from the example above):
```
(({}({}))[({}[{}])])
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP6voaGpCcQwEkgDhaprgUhTMxpIRlfXxmrGav7/DwA "Brain-Flak – Try It Online")
I've also been writing [a computer search program](http://nethack4.org/esolangs/BrainFlak-Symbolic.pm) to try to optimise Mini-Flak fragments, and tested it on this problem; it confirmed that 20 bytes is the shortest possible swap of the top two stack elements, but found a different way to write the solution, which is probably a bit easier to follow (in addition to matching the algorithm given more closely):
```
([({}[({})])]({}{}))
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP6voaGpCcQwEkj/14jWqK4FYc1YzVggBWRo/v8PAA "Brain-Flak – Try It Online")
Here's how it documented its own version of the program (stacks are written with the active end at the right, and "Working" is the Mini-Flak equivalent of the [third stack](https://codegolf.stackexchange.com/questions/95403/tips-for-golfing-in-brain-flak/109859#109859)):
```
[$b, $a] Working: $W
( [$b, $a] Working: $W, 0
([ [$b, $a] Working: $W, 0, 0
([( [$b, $a] Working: $W, 0, 0, 0
([({} [$b] Working: $W, 0, 0, $a
([({}[ [$b] Working: $W, 0, 0, $a, 0
([({}[( [$b] Working: $W, 0, 0, $a, 0, 0
([({}[({} [] Working: $W, 0, 0, $a, 0, $b
([({}[({}) [$b] Working: $W, 0, 0, $a, $b
([({}[({})] [$b] Working: $W, 0, 0, $a-$b
([({}[({})]) [$b, $a-$b] Working: $W, 0, $a-$b
([({}[({})])] [$b, $a-$b] Working: $W, -$a+$b
([({}[({})])]( [$b, $a-$b] Working: $W, -$a+$b, 0
([({}[({})])]({} [$b] Working: $W, -$a+$b, $a-$b
([({}[({})])]({}{} [] Working: $W, -$a+$b, $a
([({}[({})])]({}{}) [$a] Working: $W, $b
([({}[({})])]({}{})) [$a, $b] Working: $W+$b
```
We start by calculating the difference `$a-$b`, removing `$a` from the stack in the process but leaving `$b` there. Then we make two copies of the difference on our working stack, with opposite signs (`$a-$b` and `$b-$a`); we can add the `$a-$b` copy to `$b` to transform it into `$a`, and the result of the push `$a` ends up adding to the `$b-$a` copy to produce `$b`, which we can push to the stack on top of the new `$a`.
The same general idea can be used to do arbitrary stack operations (e.g. copying the fourth stack element into the second position); although the programs are fairly long by the standards of most programming languages, they're not really that long by Mini-Flak standards, and the only other way such a program could be written would be to handle each possible value for the intervening stack elements individually, which would be less general and much more verbose.
] |
[Question]
[
**This question already has answers here**:
[I'm too cold, turn up the temperature](/questions/104372/im-too-cold-turn-up-the-temperature)
(53 answers)
Closed 7 years ago.
`This is a code golf. The smallest amount of bytes wins! :)`
# What you need to do
You're on Deep Space Nine, a Cardassian outpost taken over by the Federation, in the year 2374. The Borg, a superior race, have collapsed your shields and assimilated half of your crew. However, you have important classified information on your hands that you can't let anyone see at all. **Activate the auto-destruct sequence.**
[](https://i.stack.imgur.com/0o2TJ.gif)
### What you're actually doing
Take as input an integer value, which will set the exact auto destruct time in seconds. Once the user has passed the value, have a countdown ensue. Countdown backwards by one second each and print each number. At the point it reaches zero, make the program crash.
### Rules
* You may use STDIN, a parameter, or any other standard input format.
* You must put each number on a new line.
* You may or may not have an extra delay of one second at the beginning and end.
I was looking at [Shortest auto-destructive loop](https://codegolf.stackexchange.com/questions/104323/shortest-auto-destructive-loop), so if you want to use something from that, feel free, but this isn't really a duplicate of that. You can also wait one sec at the start, but once again, I'd prefer if you don't do this:
**Note: Everything in parentheses is ignored.**
```
(input is 10)
(wait 1 sec)
10
(1 sec)
9
(1 sec)
8
(1 sec)
(..etc..)
0
(crash)
```
*And you do this*:
```
(input is 10)
10
(1 sec)
9
(1 sec)
8
(1 sec)
(..etc..)
0
(crash)
```
# Examples
If you don't have stdin but you can have a parameter inputted:
```
(grab the number from the parameter)
(once the number is loaded in, 10 in this case, print it like so:)
10
(wait one second)
9
(wait one second)
8
(wait one second)
7
(wait one second)
6
(wait one second)
5
(wait one second)
4
(wait one second)
3
(wait one second)
2
(wait one second)
1
(wait one second)
0
(either wait one second then crash, or crash instantly)
```
If you have a form of `stdin`:
```
(allow the user to enter a number, there should be no greeting message)
(once the number is entered, 10 in this case, print it like so:)
10
(wait one second)
9
(wait one second)
8
(wait one second)
7
(wait one second)
6
(wait one second)
5
(wait one second)
4
(wait one second)
3
(wait one second)
2
(wait one second)
1
(wait one second)
0
(either wait one second then crash, or crash instantly)
```
***Have fun!***
[Answer]
## R, 46 bytes
```
for(i in scan():0){cat(i,"\n");Sys.sleep(i/i)}
```
Crashes after printing `0` because the sleep function is called using `0/0` which returns `NaN` in R:
```
Error in Sys.sleep(time) : invalid 'time' value
```
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes
```
import time
def f(i):print i;time.sleep(i/i);f(i-1)
```
Recursive function that takes in integer then counts down until the integer is 0 at which point it explodes with a DivideByZero exception.
[Answer]
# C, 87 bytes
```
#import<windows.h>
main(i){for(scanf("%d",&i);i--;){printf("%d\n",i);Sleep(1000*i/i);}}
```
Death by division by zero.
[Answer]
## Batch, 67 bytes
```
@echo off
for /l %%i in (%1,-1,0)do echo %%i&timeout/t>nul 1
if
```
Note: the trailing newline is significant; this causes the command processor to choke on the `if` statement. The odd placement of the `>nul` is to save a byte as `1>nul` would eat the `1` parameter to `timeout/t`.
] |
[Question]
[
I want to write a function `golf(C, A)` that takes the height (`C = 2*c`) and the width (`A = 2*a`) of an oblate (left image) or prolate (right image) spheroid or a sphere as parameters and returns the volume `V` and the surface area `S` of the shape as tuple. The output must be rounded to two decimal places.

All input and output numbers are floating point decimals.
The input numbers (`A` and `C`) are guaranteed to be greater than 0 and lower than 100.
Here are some example calls of the function (`golf(C, A)`) in Python 3 and the expected outputs given as test cases:
```
golf(4, 2) # expected output (8.38, 21.48)
golf(2, 2) # expected output (4.19, 12.57)
golf(2, 4) # expected output (16.76, 34.69)
```
The challenge requires my code to be smaller than 150 characters.
I could not manage to solve it myself yet, my best solution in Python 3 still takes 220 characters:
```
from math import *
def golf(C,A):
c,a,V=C/2,A/2,pi/6*A*A*C;F=c*c/a**2;E=sqrt(1-(F if a>c else 1/F));S=4*pi*a*a if a==c else 2*pi*a*a*(1+(((1-E**2)/E)*atanh(E)if a>c else(c/(a*E))*asin(E)))
return round(V,2),round(S,2)
```
---
The necessary formulas are taken from [Wikipedia: Spheroid](https://en.wikipedia.org/wiki/Spheroid), here's a summary:


***Vall spheroids = 4 π/3 a²c = π/6 A²C*** as ***A=2a*** and ***C=2c***.
---
This challenge was originally from [checkio.org](https://checkio.org/mission/humpty-dumpty/) and got refactored into a code-golf challenge for [empireofcode.com](https://empireofcode.com).
[Answer]
# 122 bytes
```
from cmath import*
def golf(C,A):e=sqrt(1-A*A/C/C);return round(pi/6*A*A*C,2),round(pi*A*abs(A+(e and C*asin(e)/e-A)/2),2)
```
The sphere can be special-cased by returning surface area **πA²** if **e = 0**.
While there are two different formulae for oblate and prolate spheroids, they are mathematically equivalent. If the involved operations support complex numbers, each formula can be used for both cases.
Since `asin(e)/e` will return a complex number of the form `x+0j` for prolate spheroids, `abs` can be used to turn it into the float `x`.
] |
[Question]
[
Italian zipcodes are 5-digit numbers. Each number is linked to a province. There are 4610 zipcodes and 110 provinces (as of 2015) in Italy.
Given the list of zipcodes and the related province (in [this](https://sites.google.com/site/dantonag/home/italianCAP.txt) file - [Gist](https://gist.github.com/anonymous/c9f5eb0596c392ddb993) here) write a function (any language would be fine) that, accepting in input an Italian zipcode, writes out the related province. For unknown zipcodes (for example '99999'), the result should be "XX" ('unknown zipcode').
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the function with the shortest amount of bytes wins.
Rules: you can't use Internet resources, files (including the list of zipcodes-provinces of before, even if you can include the list, but then that would count as chars in your source file), built-ins or libraries/modules that provide a mapping from zipcodes to provinces or any other external entity in your function.
**Some test cases:**
>
> f("00185")="RM"
>
>
> f("00014")="XX"
>
>
> f("86071")="IS"
>
>
> f("20020")="MI"
>
>
> f("08010") can be "OR" or "NU" (they share the same zipcode)
>
>
>
Happy coding!
[Answer]
## Mathematica, 2973 bytes
```
Uncompress@"1:eJzt3U3O47gRgOEAWecQc5OR1f4cI7alkd1Go5e5QO6/y7ALBVIUJdMSRUru9ynoh8UiWfKmMX+YP/77v+7+57/++Y8fQ91VwrzZUZrw93PHgVYSC3cUypfLAQCQxvNhQp9jYeaHNeV6LnUyAADb1J3d8Mea6+dDVXYuR885TgEAYD++Og33fX7k6TnHKQAA7MflERel+3RtqxsAAMp7dH74OXcs77qyXM+lTgYAYJvak3+Nh50N12nWnR1W9qtC3disPz+VDVeGT39nDwAAtu8e0DxC4dfI098hT885TgEAYD9u3000nb6Zd31zo67k3nTmrTn9qvz7r3Gb09+5k408Pec4BQCA/air+vzr0qhMPO/Puzz7l85JyFji106/nnGa7lWYmnBd/Cluh7ZPmZnza4W+I80+AAAsEfxb642bj3nX8dh+MRFa28/Zfud/3bzcer8/AAApVI0foVy1qT/RttUNAADl1bc1w+zvnxFzpu0s3HPe3wgAgK171ib6o2HEz4TPSN1z2v0AAHMczoez3CU0Z0daZ/PDnO7jrnXr+vFeLpz/TNXjVYTr4la6O6TsOfWOAADsW3WZE6F1c/dyd4jtec1fBACA/Tkd58T4ujw9x1fGdD43t+Y3AgDwjrv9z8mfZtTPuDNjo/7McG6NntPvCQDAnp2vU1HfzH2srlzPpU4GAGCb7q0fktNZvbvzbkWZnuMr+337uf4MAAB7NfmX570wtXaVvU/tPXWG30V8L0u+bnku/nQA+GzXg43YnOaHmXS5qY5Tfv+2PKv1I33PqXcEAGDf6mZJuHtMnTG8j+8W0/P87wUA4BPdm9cRrirZc7mzAeD3dKkvtdwlJOdm/IrxnO4XqrN3/9zh/fXZoapPdTjFx3vVr/Za0vP8r1tyLgAAW3W45413zwz3PP/r+rlUvyIAAGXVXdrI03OOUwAA0y5NP2JzJjsvt7zjpTtsV/tcL3T39D2n3hEAgH27Nf0wGbn0bp+htVov7/5K9wz/OYz4nud8KQBgvudBI5Szc8OM5uRNrnn72bV62Wy/Vvfz93zvi5f8Xvm1dVyU7tO1rW4AACjveZS7hObiomzPcZXDbnXk7jL/a7bwewAA8Hj6Ecoti/Q9p94RAIB9O1zMpaG54butsbOhXK6eAQCA9f3b92/mLm/rROjc9qbXePh1Wh3esQzpEgCAsh53E/qU9xxOzTBi18b3aL/Kfl18Lu47YnsBAGA97bd3wq0Prc3Vc3zl1Bf4uTV7BgBgTc+zG6Gc5MN1ktfZ0NpXZ7hv8T2n+34AAD7Bs5sKM+/W6IrwuvHddMZWLOt5/teFc+/sCQDA9jxuEvbt/ZhaO2dfd02459y/EgAA23b4uXas0XP6PQEA2LND8zqkzq+1q+UZqgll7Or5Pc//urHckn4AACjt2ozH9KxfIe+hNel7Tr0jAAD71h1jol9nRmMr8/Sc4xQAAPaj7WyERrbGPP0VY2vtat0jbc951gAAsBdfRxP2qW9u1p8zT73csVat33OOUwAA2I+uMSFPHflh64b5Mj2XOhkAgG263jTckZvvh86MVeTpOccpAADsx1cdDjOj13AkK3V9/p7jK/N3BwC/l+42HHc3E27ODZsJ7fZqZcpeP0lX2ZCRueul+W3ZXkcAAAAAACzzdTaXCR3bsCN/xs4P9wvv4OeX9hxbOex3OresMwAAymgfEvZNxyajNTLr15frudTJAABsk/kH5PqU0Hc3N5zVVf2qXD3nOQcAgP24n1+FVrnV/Xe5NL9+xzlOAQBgP653N2xWLjs/zJfo1nYBAACsy3c3dCxPc5crVGdrbZ1b75/Rzy3rOc0+AAB8ivZswo40o2Fr/JC8nZXVeXqOrxx+DQAAn+tyNtflLO8SblZz7nvJXmMr+7FmVwAAlHPqTMhTR+6bjKSyX2UztsatO632b6GvtzMAAHvVNnq1jZuTTLvB/5fZFnsCAKCk6lbdzF0uGUvYd7fOD52Rmlw9x1eG+l2zNwAASmi/a4RykveffkW/OkfPOU4BAGA/rrUJeerIzdmRGfv1pXoudTIAAPtRtfHZ2B39iMv5a5d3AgBI5etqI5TTvJ8z2Zi69B1/8p8fj6MbZiy5/oxfF8ro6hw95zgFAID9aI82zEgy/bxktiO+G/8r7PcBAPBJ6n+b0Gc/ZN6tc2uHa/r7rdnzensDALBH1V/mkuiP4uK9evesZT0DAAAAAAAAALAlh+pQyX06bO3wTd/7+8q1Ts/xlcPvWKsrAADK+TotD7OL7JSr5zznAACwF4fOXK+jdJ+ubXUDAEB5l+P6kb7n1DsCALBvjyomSnfZt7V+AAAo7fqIi9J9urbVDQAAW3B4uFG6m7TM9+gFAAAAAAAAAAAAAMC4W6Xhvr+K6XVjO2nef9r52J7f/7qp3ub2AQDAVtRHDXnv52zWzQ1juip9z6l3BABg3w63w83c5S0mtLJkz+XOBgBgi6qnH6FczNzUqtQ9p94RAIB9u1dLYny9ztgK/7SY0+0u8uaO532dm1vnFwUAIL/2px+h3Fho7fSa9D2n3hEAgH2rD2kj9tzz3UZ/NB3S83q/x7ukIwAAyqrvUzE1H5qbypmnvA+r3u15nd8CAIBPUv80Ic/YOvfNnZN3vfrV8/ubvxYAkMp/Oj/c3Hid5kp0nP/MXLraj1DunTDr9XLHOpJTl/Wc5uuW9AAA+PHj6bGZUFVcLnxCePb9fpet37K2Sht5eo6vHPYXn1vzGwAASOnRxkXpPl3b6gYAgPKqU1yU7tO1rW4AACivvgyjdE+vbL9DAADyOt6GUbqnV7bfIQAAedWPsZC5qYrwqhw9x1eGvmrN3gAAKOHeDaN0T69sv0MAAPLqTsMo3dMr2+8QAIDyrkcJ+/ZezF8X29+7XzLd2/zcvN8XAAAAAPCb+z/cceZL"~StringTake~{a=2FromDigits@#,a+1}&
```
Looking for a better way to compress this... Currently, it just uncompresses to [this long string](http://pastebin.com/bDvpmPJU), and looks up the ZIP code in it.
[Answer]
# MATLAB, ~~3987 2827~~ 2813
Not sure it is worth posting this given the enormity of it, but anyway:
```
b=java.io.ByteArrayOutputStream;org.apache.commons.io.IOUtils.copy(java.util.zip.InflaterInputStream(java.io.ByteArrayInputStream(typecast(org.apache.commons.codec.binary.Base64.decodeBase64(uint8('eJxtV0mS4zgM/BIArjraHpfHMd5GdvvQN2r7/xMmAVIudcV0harLJEUsmUjA/ZWIGI+jgN9JoiwUXSIfJ+pSRzk7PBPlLlEujGegPATK7xdR1HeEPM3scU2kFApRfyYaO+xEypRZsOMp8ECj7n71xDJh11MU1pXLi7iDD+z00wv7i96bqVDE254zMeMN3X2cSILerXb1DrWiZydO5HikThKJDOQdU3KFxM0wn3C0w/9LvSUulBEbp5Ho/iIZJvXx+cRfOEEDTRQ97r39IidM9Z9mKBx2WFHLxfZc2ys0UrKVoh/1VA6fPfwgA4VnChJI7j12B0275sbOaj4KwytBbKJe4UxnN7zu5Oau2fAtHx53RYGHknmEp2oshEzSIltRC7s7eT+1bHYa++FGfkBMMqvzTig+31hRrJztJTg2MZPABr0PQK6inGhAFAPyEfGW5XF/pgAOIBAggT34hbOGBPKIk4J4GTEF54DGRAlIpADrAZ93LwrwVV/3lHjC8QXo4t7dhcKkmBQgmiWCEFg9HYEKt9Vhg+OWoxpNLOpxgMdEHXWNfQP8MH6er9jRjC74EexaXp4PSnHNFGOHGnM93uVmTf3N1zOlSf3wYDyxIjlrPi2bxTtsRHb/4xtf94hGsxWQK81rQp4i/IrIT3TKugQcYeu9o+wQhTPLhzve10zN4J5o9m0v4xmomPc4sWjGmF2N53Kgzo8bbEhZDZsZNhNsZtiEm3hwM2xbCVfv8WA/OOb9ibqosQZO4tec75/UjeoBKozDBolw6KkYhy3TlzsVrTPlDmKttnOzHa2e31SU/TKt2N/wzqI1VzFSv+eGBSpZqxFVJ4LYUeWacUEMgko3Rrz3NGgcFnFuGRbBklVLB10AHog2eKw1XQDpSUwbKjN9wM0B2Urq4QE3h1Wd3kcahq7pgUPNug0zJCES4M1YCq83jdz4VLOxv9CYuWkX9IAsGOP+XJn56y8a52CKrMUZZHzcsDJs9G5qSkuqinYeVUVOzy1VL540aUxmw5/u+KSa1ul60DvoBw6kZ6qmPv6iqSiLYtOY/KPK5H2G1rOpbsEt0HDjvgJUUUmqKG4kh0qtGetpTurZrK+ZfoERTakH54FdJveHHUT4utE8dVV1ecTdI8iYgZNxcP+bFmCom/rpTkth437NTTTMgUNVSPjEtUo2kdD1rmBbVUAHEIHHadUqi7k/Qua04qSpBwFLu+PRM41T05cAbjJiEkOkA9IB9YxaclQ1I8GjryOKkhsiAlZ7WEQ94a16LzV/SbuDWb8zd2tv1eopq0pdb8xLZ0wA6ugIA6zK6tvXgSVMrYORaRjqf8sYtSb00TPubyxAXPvoaJUmn/yhJtYq7XcsI7eYkcvPacPt68wurz1ZwPcAy66xTPMfEdqa/5hQc8AgaiUAB/94sZun1l/jp9YRN/x1a9/f9eyDEcjUDLWDkx1iXzuNqdDzzB6zCfP3+3Pt0mtmr08oWZ1NqiLq8OOAhaJHYKVZu/zioLVsE4zQ2PqBaT6yM5oWrYih7E1ZrG83PaqzypnDzK13aifSaaY0FXMSP7NIupw5+tCmGc2v22DnISdrfaRTz7F0G2YoB0Lrusyldm1tEObRUKN+3LE7tTlPUeSmq7Xb3jgl/lYd0yyv6FoWU+1ZG3+1hujxi9MUjIl1TlPmyDrlXQ+c3dZPrZTQWCjIoDFw9+DczcacwXKYmzon64NY/rpynqfWMdOmeyV9d4mmeEdVlIYWWfeGvteZAr6nhgZOxe1cwDqzbafBw9/cjavPnSWkZl9zmsBjkcaP3b9cbIbVs67ex5hmOaxatt/xYJqKnLJWH+sUAVzsDp0Vtrn8OvGgM6hw45RlZ99D+Vq/4DopH3nMn6ngteNxNo2yjL940kmvdqQ9Pg3a+yNskKKbcPNtx4tOUDp7Y3rBPIl5IoElBRO/OK34pVb8Rinj4chLqUhXdobGzBl9lZFfq+39TYi6bxZB8krj1xstYZ2sRs5c562dkE1RM94bkE1Bohz8CPBBW5kEzcP3TOsfv4Vd+2bA3nKJfmjz0V64s6nj/MRfS0WZva4X63m6bnVDB/ylk5L1o1F7HJDNa90CP0YejBeH34KvQyuHEa80RRKdwmwCKVb1jNnFHPunh2xq1nObhXX6MKz6A4BffZ/be8qDOs15RD78wQn/fotqqM3dpqaqdFrVqsoOftbK3on7nrd+zJz0eoh9t6ic2J0A7+d71uGCeU49MjSON/E219TvCC8JNruM1t+Yt5ygZy/B5hg7258kzJ97rkeJvrS+XUBbIw7qLv/wLf0HznFGvw==')),'uint8'))),b);s=char(b.toByteArray)';
i=input('');h=@hex2dec;r=@reshape;t=cellfun(@(x){x(1:2),h(x(3:6)),h(r(x(7:end),2,[])')},strsplit(strtrim(regexprep(s,'([A-Z]{2,})',' $1'))),'Un',0);z='XX';for l=t
a=l{1};g=a{3};for g=r(a{3},2,[])
s=a{2}*10+g(1);e=s+g(2);if any(s:e==i);z=a{1};end
end
end;disp(z)
```
Yeah. Not really code golf material. Although much better now
---
After a bit of messing around, I managed to get MATLAB to directly access the Java Virtual Machine to be able to decompress a base64 encoded zip representation of the original data, which quite literally knocks 25% of the size of the code. I am being quite naughty here in that I don't block closing the InputStream and OutputStream during decompression, but who cares, it doesn't crash!.
---
After decompression, the zip codes are encoded in a format which is:
```
CCbbbboollooll...
```
Where `CC` is the two letter zip code. `bbbb` is a base (starting point) for this zip code which was divide by 10 and converted to hex so that only 4 characters are needed. For each base there is one or more `ooll` entries which is two hex numbers where `oo` is the offset from the base, and `ll` is the number of codes in the range minus 1.
All of the hex numbers are lower case, and all of the zip codes are upper case. This allows each entry to be separated based on whenever a two upper case letters appear (because the are only present as the first two letters in an entry).
Once each entry is split up, the hex numbers are parsed and converted into decimal, and we basically work through every entry to find a match.
The ranges for a given `ooll` pair are calculated as:
```
start = 10*dec(bbbb) + dec(oo)
end = start + dec(ll)
```
A new entry (`CCbbbb`) occurs at each point that the a new zip code appears. Some of the codes appear at more than one base address as there are some which are not all grouped together. Allowing multiple entries costs some bytes of `CCbbbb` headers, but it means that all of the lengths and ranges need only be 2 characters which saves quite a few.
---
Matlab is not good at encoding in different bases, so of the ideas I had for how to encode the data, this is the best I could think of. It turns out, that I can actually save quite a lot of bytes by resorting to directly accessing the Java Virtual Machine that Matlab is running to perform base64 decoding, followed by zip decompression. The input string was made by doing the reverse (compress then encode).
[Answer]
**Python2.7 ~~2645~~ 2573**
```
def X(n):
import zlib,base64
a=(ord(zlib.decompress(base64.b64decode("eNrt0wl31UQUwPGvdMEFsSJSqBsuqAgii1pFLYoFpC1Q2Qpu4IIVV9TP6qzJJJnkZXs503P+vyQzN3eSO333vYp4uxTZZaYWpDBLV0EhqdTsFQFoYffu3foKSZ4ZVJnmAol4zPKzjqScMnfdK9NcIBGPa3Zs1KMyzQUS8UTESJVpLpCIJz0pzGrUi4Mq01wgEXv8USDZkN/LnkLSpfIye+wcVI5tF7wefwLA6J7K7I0SP3e2l+YCiXh6YWFBFiqeUfYpss/pXnkfzQUS8Wxmfy3RV0TkwTDX+Ip6VPa3+Pv28xUBgz2Xk5pRz+FzVVKOTN3G7aTpZQCjOuDl0YGRKtNcIBGL3ciiZNHi4sECETN4B2kukIhDhw65KRO9Cd5oW5nmYudbWlKnIn7SOfGhiSRbtbmlpfCNchTEE3q+LMhFFu0D7SrzGwES8UI9iUR1j8Yq01wgES/WK6z1qNy4XbuI7wcY7/9cwn9qif6bd/6H558USMVLFWFuUGWaCyTiZU9F+laf9t4mBlSu3664MYA5Oxwjh82S2Dl8uviGLxGt0rzdzIivBil4xYhFOs6CVlGx8KQf49XOWlfmNwIk4rVm9oniG9lZeKxameYCiXi9IkgNq0xzsVMdOaJORUU2OJLNQSSFnDn9u9lZeTtPTemNqJp0+anmyo3b8VMCpvNmT3VvBpUbt5Py4wDm5q2WelSmudj5jjqx6GhTNLPwpB/j7U70460r8xsBEnHMEX3o01z5qs4fsyvHsjf8lYlWprnYqY5reWTuskDsIMebnhP3iA2PZ09mdWo2ntMHeidipMr8WoBEnFCnInYqG1g5kszK6umEyzVVGfx3AHjXy6MZWlemuUAiTspJTUfZeNKRIOpTGUAaTp0SdXSRv3taHwU+J/ZmBKf5ioDBzpw5oy81dvdeJrra+Eo8alkFQCfvx0kwmqhH5cbtihHfAzBPH1h5pOIgJ/Y2Xy2/IS6OVKa5QCKWi2TZZvSChOnl4o3YhxorN24XRLLM1wDM1YeKGWpJw111JahMc4FEfNRV+8o0F0jE2QqVkzw8q2/yzFkpPNlYuXG7MOJbAObr44LSrU9IuNK6Ms0FEvFJlfgpXOxRmeYCifjUyCeTkU/9QrhqlvUTLSv3WAEwDysrK+bSgw39nZhjxY/dK9NcIBHnzp0Tc2ZEwnhAZZoLJOIzzU42dqSU6FGZ5gKJ+Dwg5sgmtSh27lc5vh0txw5zPpvPn7fxeUuyhEsWF9tVncYXhuhTHzoeqzI/EAAAJrIqq6urejbM5G/MffZc8ICPZ1WOJbO6pYhvApifC4oZ9CwXdEZMZPKDKtNcIBEXL+pLEXc5JlRLLtWnMs0FUnGpTKds2o2XxMSdC9NbIBFfWiZUh7gbGw+rTHOBRFy2xF6ijzxnsnJZfN6/4aIZlWkukIi1tTUz6WDN3KzlZM3mZa1P5Zrt3DYAJrUu6+tqVGy4bkM9DKoaSzo0HZjQxsaGmNMNalJJlxK3IC630akyzQVScUUfV2ykgisjFgaQhqtXRR9qvqpDPYgLfEo/1adyfLusLr0HpnJNyyMV+8snruWPdKtMc4FEbG5uijk3N/NJNn1+SGWaCyTnq2gYe9CLRH51ZhFgR7hu5JGOr2dhNde+8KQf44Yl6rghPr5RCvRy98r8RoBE3DREHTddrIJxKtdvZ3a8SfOBidy6dUtfjrq3OZuVIK/vulWmuUAibsttxU0R0pCeVRkAAADAOLa21FlistmwlT8rW10qx7fze2zRe2Aqd2YSddzpU5nmAom4K3crxqoMIA1fd9a6Ms0FEvFN1ViVaS6QiG8jRqpMc4FUfGdNtZs5AAAAAABAwfeaHctKa1JakiAXrVy7XbFaUw0AY7inqdFFJrxXVEq1rkxzgUTcvy/qiNDJYZVpLpCIH7w8qt4Vl9pWprlAIn5sJuUbk/CvVV8Xl7Vzw3biCgCYv5+8PApJdaV1ZZoLJOLnlmLvPjDcVKJWR/n7HvAVAYP9UiQ1d8VI9Jil6irTXCA529vb6orl7GDv1Cjmue3t8sPlerQUO9+vno0KOR31Lzzpx3jo5VGcmOOhGx/qV2dUbrEdPyOk7jfHBHkqEgUvBLe1dSf9FL+31KNy43bxiF8VMA9/RIxUmeYCifgzYqTKNBdIxF+Z0SvTXCARf2dGr0xzgUQ8Cok5o3pUbtxOHtF7YCr/ZEavTHOBRPybGb0yzQWS859ihhqNa7F6dZuUqjVF/wNUv6A7"))[n])-48)*2
return 'XXRMVTRIFRLTTRPGSSOTORNUCAOGCIVSTOAOCNSVVCBIATALGEIMSPMIMBVACOSOLCBGBSCRLOPVNOVBPCVETVBLUDPNTSGOPDVIVRTNBZBOMOREPRFEROMNFCRNRAFIPTARSIMSLUPILIGRPOANPUMCAPFMTEPECHAQBAFGBRLETAMTBTNACEBNAVSAPZCBISCSCZKRRCVVPATPAGCLENCTSRRGME'[a:a+2]
```
Each zip has it's own character, use that as indice to grab code.
Compressing the lookup didn't work well, slight decrease in hash length, but penalty in decoding. Instead adapted to take in strings and inlined. Slight improvement. A lot uglier. Mmm
**2572**
```
import zlib,base64;a=(ord(zlib.decompress(base64.b64decode("eNrt0/l31UQUwPELLogVkULdcEFFEFnUKmpRLCBtgcpWcAMXrLii/v8/OmsySSZ52V7O9JzvJ8nMzZ3kTt99ryLeLkV2makFKczSVVBIKjV7RQBa2L17t75CkmcGVaa5QCIes/ysIymnzF33yjQXSMTjmh0b9ahMc4FEPBExUmWaCyTiSU8Ksxr14qDKNBdIxB5/FEg25Peyp5B0qbzMHjsHlWPbBa/HnwAwuqcye6PEz53tpblAIp5eWFiQhYpnlH2K7HO6V95Hc4FEPJvZX0v0FRF5MMw1vqIelf0t/r79fEXAYM/lpGbUc/hclZQjU7dxO2l6GcCoDnh5dGCkyjQXSMRiN7IoWbS4eLBAxAzeQZoLJOLQoUNuykRvgjfaVqa52PmWltSpiJ90TnxoIslWbW5pKXyjHAXxhJ4vC3KRRftAu8r8RoBEvFBPIlHdo7HKNBdIxIv1Cms9Kjdu1y7i+wHG+z+X8J9aov/mnf/h+ScFUvFSRZgbVJnmAol42VORvtWnvbeJAZXrtytuDGDODsfIYbMkdg6fLr7hS0SrNG83M+KrQQpeMWKRjrOgVVQsPOnHeLWz1pX5jQCJeK2ZfaL4RnYWHqtWprlAIl6vCFLDKtNc7FRHjqhTUZENjmRzEEkhZ07/bnZW3s5TU3ojqiZdfqq5cuN2/JSA6bzZU92bQeXG7aT8OIC5eaulHpVpLna+o04sOtoUzSw86cd4uxP9eOvK/EaARBxzRB/6NFe+qvPH7Mqx7A1/ZaKVaS52quNaHpm7LBA7yPGm58Q9YsPj2ZNZnZqN5/SB3okYqTK/FiARJ9SpiJ3KBlaOJLOyejrhck1VBv8dAN718miG1pVpLpCIk3JS01E2nnQkiPpUBpCGU6dEHV3k757WR4HPib0ZwWm+ImCwM2fO6EuN3b2Xia42vhKPWlYB0Mn7cRKMJupRuXG7YsT3AMzTB1YeqTjIib3NV8tviIsjlWkukIjlIlm2Gb0gYXq5eCP2ocbKjdsFkSzzNQBz9aFihlrScFddCSrTXCARH3XVvjLNBRJxtkLlJA/P6ps8c1YKTzZWbtwujPgWgPn6uKB06xMSrrSuTHOBRHxSJX4KF3tUprlAIj418slk5FO/EK6aZf1Ey8o9VgDMw8rKirn0YEN/J+ZY8WP3yjQXSMS5c+fEnBmRMB5QmeYCifhMs5ONHSklelSmuUAiPg+IObJJLYqd+1WOb0fLscOcz+bz52183pIs4ZLFxXZVp/GFIfrUh47HqswPBACAiazK6uqqng0z+Rtznz0XPODjWZVjyaxuKeKbAObngmIGPcsFnRETmfygyjQXSMTFi/pSxF2OCdWSS/WpTHOBVFwq0ymbduMlMXHnwvQWSMSXlgnVIe7GxsMq01wgEZctsZfoI8+ZrFwWn/dvuGhGZZoLJGJtbc1MOlgzN2s5WbN5WetTuWY7tw2ASa3L+roaFRuu21APg6rGkg5NBya0sbEh5nSDmlTSpcQtiMttdKpMc4FUXNHHFRup4MqIhQGk4epV0Year+pQD+ICn9JP9akc3y6rS++BqVzT8kjF/vKJa/kj3SrTXCARm5ubYs7NzXySTZ8fUpnmAsn5KhrGHvQikV+dWQTYEa4beaTj61lYzbUvPOnHuGGJOm6Ij2+UAr3cvTK/ESARNw1Rx00Xq2CcyvXbmR1v0nxgIrdu3dKXo+5tzmYlyOu7bpVpLpCI23JbcVOENKRnVQYAAAAwjq0tdZaYbDZs5c/KVpfK8e38Hlv0HpjKnZlEHXf6VKa5QCLuyt2KsSoDSMPXnbWuTHOBRHxTNVZlmgsk4tuIkSrTXCAV31lT7WYOAAAAAABQ8L1mx7LSmpSWJMhFK9duV6zWVAPAGO5panSRCe8VlVKtK9NcIBH374s6InRyWGWaCyTiBy+PqnfFpbaVaS6QiB+bSfnGJPxr1dfFZe3csJ24AgDm7ycvj0JSXWldmeYCifi5pdi7Dww3lajVUf6+B3xFwGC/FEnNXTESPWapuso0F0jO9va2umI5O9g7NYp5bnu7/HC5Hi3FzverZ6NCTkf9C0/6MR56eRQn5njoxof61RmVW2zHzwip+80xQZ6KRMELwW1t3Uk/xe8t9ajcuF084lcFzMMfESNVprlAIv6MGKkyzQUS8Vdm9Mo0F0jE35nRK9NcIBGPQmLOqB6VG7eTR/QemMo/mdEr01wgEf9mRq9Mc4Hk/KeYoUbjWqxe3Salak3R/6ditYM="))[int(raw_input())]))*2;print("XXRMVTRIFRLTTRPGSSOTORNUCAOGCIVSTOAOCNSVVCBIATALGEIMSPMIMBVACOSOLCBGBSCRLOPVNOVBPCVETVBLUDPNTSGOPDVIVRTNBZBOMOREPRFEROMNFCRNRAFIPTARSIMSLUPILIGRPOANPUMCAPFMTEPECHAQBAFGBRLETAMTBTNACEBNAVSAPZCBISCSCZKRRCVVPATPAGCLENCTSRRGME"[a:a+2])
```
**Some thoughts**
Further optimization could include finding better arrangement of characters for compression. Limiting factor here is getting the data down.
This approach works fairly well since, since using only indices has inherently less entropy than trying to encode the entire zip. Given such long streaks of characters, the entire thing compresses pretty well. I initially tried compressing only the numbers of interest (so that I could implement a binary search) but ended up using more bytes than just the ordinal string I'm using here. There might be a smarter means of storing, but it's hard to beat the built-in compression.
I considered using a statistical approach, but it would be at best heuristic. A true functional representation would probably require just as many bytes if not more.
[Answer]
## Long "demo" answer in Python, 3755 chars
```
def f(c):
import zlib
import base64
s=zlib.decompress(base64.b64decode('eJxN2VtyIzkOBdAtJQnw9SmpXR7H2JZGUumj97+QIe4FCXV0V5xGMZlMvkmdPk/fp9/T9XQ7/e90Pz1Pr/Pp/Hn+On+ff8/X8/38OD/P/15Ol/Pl4/Kfy9fl+/J7uV7ul8flefn34/fP5c/Hn88/X39+/tw/Pz6vn/evn6/Hf+/fl++P76/v6/fz++/P+efy8/Hz9fP7c/15/Dx/T7/X37/Xz+v9+rydbpfbP7eP2+ft6/Z7u97ut+ft7+11+/d+ul/uH/eZ4f3n/nu/Pk6Pr8f1cXvcH4/H63l6fjx/nzOD5/35eL7+/vOaRX9dXh+vr9f9NRO8XkfPx3Gk+Z84y/zD2Q7pZGnHUck6EyiY0jiOQcrMgmmTBkuwBluwB4cxzf9LKE52KjI0yoGSgvOBBlrSAw9mPFadHfkac98JLIfibEfKoOcwA4Ic1FkPEdATaJ9/laygoEdHmzmaO4kacnbLDBS1kpNjPeY51D4fSG/MQQ3W4PxsIWcJj8VubQHqfEUmi1gZyBlt5PxjJWhW9WRP+xVdIjpW9K28KaPdQKuf5ER58Z4EVJnMIKLWAI1R6TutoLygCqoPrcu3ZTQ4eHiDJ49KRAvqAVGWd/ZmvNgTeHktgUSURZ9PdNSkv41fwWiJtGwA63SzU+xoR3EsqsdOoHnnoBJRtd5XD6/o+c0yvzQdXobhLc8o2o1Re0WadTPwQZnRLBEt/rbJitwQbRHtER07BxtDmVH7zMKo9Wt/sTb0EmuZZgOY7N0rCk1q5ZvwDwJZ1SCHDqnrsdQ4cAoq3/4Fc8ZoAfumPeZUjiyw7xwKkg9ONBiFxoGBTqKvG71koAQ16BlKSj6kQfZf42q3kjDZaCVL39GKQpLd6gzsqEkjc5gTWJI1y4FzwCQS7UpiMJB1P7aqOiXpHAwkKgrMadMbAMRUAWpE7RXZ2XZmrAfQRn0jW7AHR2Q2xKJz6HKerCTHPDl2tKBKjP5BMwtMpNaFjYIZHFQfqWlNmfNzq6cFBfOC8S2BNzcoQQ2WoD04O1dKnLmKE12VxFIHSiSwVSSRBVViXOtFSpi55sfOlu8+TBHFN5KCzmVcK1lPw3sfyOWZLDuBL2pGy0GdbaV9ywz1UEjWQxFM+pY1KJh3yLbJ+QwsdRMlJxveBnaMcqPXOhhv81oHS7Ci/9qiia5cyBwUVCqoaCGwBGuwBfvOYfh4s2LZsBjgGsc1YxyL0yboTNZIUCVYg4MdMK/9Q28ZQ3p2BTBzbzS5+oNmYYdwYsSCLBCJBRBkTYKsB1AjWiKzosG2M6uRoEaC2jbbEZSdb+eEdGSMY9TcpO2GKrimIKPP9jVj8JZCVqy4xpW2+uzHtOgas31axjiWAa6KmkSVNDIH2aNADZYg+4ORLX+0kjGktZCcd4z+tjIyNxjNOXaUTUtqsG8qaoGUiNqaRJZ4RYkE1os8QdUgJjHjWiRy7iiaklYlnUSVkMImAut+TPqmRg4lcrCKKs5I21JQgmW/oo0d7ZHWtov+ihHRweVrcmTuaUsevoM2rs9U4QFk0RYq0o8FKsdbWs5npH88WHYCxWIBNs7VQ9aKDmZ0OePqnlnyegeI+Q/0PRdYN7mogbq5CmlDBdXglIgWm2SakbsgMgfVkoMjEoxIMJRbOWPDx0/6V1h07a66KDcYTkw2MkTx4oGoPwb63sgoQQ1yJFsO/opahQt2JrlVAxVVbfRXgL4HN0pQ2YRFeAiqpH1wJyWi3JiTOH+SZedgfaCRNR6z8oqzLK7GqtK4SpO+gwY7erXROldy2jmLnOes5NHKzTRY8YrJt1fw40kJ8qAwlAvDIU6cHcH5bbMvgvP8NmchsOMIblz9twtG1twpGVdU9fAlCZSIcikH0QDOgrUS7DttYQcHOX5Vj7dXrHndKEF2r1IUQ2/2atDWiUIqBhmJYxTo24PJ1auHYmzOzRLI7RfZdgJ+v3E9ln3aKM62mTmGQJwOQO6CSHRsUHHxAZayHyt98e1tCX1njkFdQ4/U4MAoNGYcuUCRnYAfRI5NthBZItpWdO1AVIu/mMRnkujjIDecxrUAqla/+CCb9RTQtkeJFC5qIKra6DlIVo6hRGbZUW5ZSWw7QInHWOukRoKxoxjo4Nvb0OXmt4m2zksSkMsMiVoH2ddB1iRYZJObBuPaNDTtq++AKDqYIwHfRmJ0GVch2VmCGY0FdrS8MePaAvQTipHtCVrtVSdKZHx7BeqhOseOSkQlojzaN5uUOdmQBR3cyE0O2Te5epG6H2O+Ri+OLel+mUFiOQC5hJKKs7RR8PGg92BQ8NWTq1fXYsdWOziCLA6J4oB6BMt+jEPEuPp6LRyblfQdHijBihFglIjyLojsi2vLOrxdqhPTCpjRf8my0/J2BpR4jPmCeuwcNB7TeEzHJkcyqZs1cqg7utbjUapPFWSLqDUPyY0xyJ0uyTtHsK/H3vJNvl+vpfkFJskzrzGjsciyE3B+AHmkJetKu6ra6K/wQWGfCfKMA2ISA60BCsluQMpOK3XnwDMvmXcOJR7jrGFcE3+yNTEFJcj1wpgjAScm4xo4vA049uWHRLQEcSfGLaj6kfXwwUDi/Ab6hhrsK4e3t/mCDbJKms3lXANA3mKTXCGNuDF04vrcuEbWPNZ5W5BoCxIrL5h10y8dQN2P8T7VuMqr8/ydgz6SjfxFAWxBXk2BVsMFXFPm3HH6TQPIbgT6/GvUiJadma8MQ+qaQMi+o7yoITGJgTwokAObaSMHr3ENnFaLrzhki+jA0DNaV27g22NrX23khXbOdY1uEpMuyC0KyEFG1p2WpxmwRA6cVoyrWUptq0uBGC1ki+jg6Ku42Me5rfoGGVyZjbZHAIhfX0C/qQLbpqIjgiwZWRff8l193chuILaTSBgwoG+pQG5RJtf2trR9LgTRm41rNipNeLEEenTkpr5lNa56aq348de4XtFaxQRSQb8iJiXIxaf3Y23VQByUQOk7ahv1RhYUDqzcwIFjs+G6qfS+G9Pod3hGCfIGLttNJctAYvYC8UOhs+2o8ArUqJFWeX+W+q7qORy9E5ASUQwCkD3VL7nxD26rDrSxMXOvZRTusntfzdJLR7OIU7G9BbEbcw5sJYwVWzCw4fAOjmOnHZjiyb6iXn2gcM9V+/qREGT3BdmVyYqzP++zDr5kXY9p7jzHFmdjJn1fms2ojzy7puExjcSMT/JgDpYgdwqk7hwqGwvEb3PrfuhA/XTf1pHcuhs1ojxzkmNHi27WyKzmYGRW28phfaZ0vwgj+VsH6HekRlwAgWtDb/IGMHK2AkveCTiXkOhnYI0cKp4jx4qmeIW3PIiWn+tBHz3x12oj7mtICWoQv3+RNaLWFoz6B1Udh3eNyqG0oms5MEpQg+xeo47ks5FxDSe7a2LUuDqiDg6yAa5OkIZ61LjSjsFZLpPsGqQtLOBbWi8vyJznR1bP17gG75rYB7imqzy67yfJYt0dnHOf8y3tmtqMEtQg7h/+D74BxmY=')).decode("utf-8")
c=int(c)
i=220
while i<len(s):
p=int(s[i:i+3])
x=int(s[i+3:i+8])
g=int(s[i+8:i+11])
if c>=x and c<=(x+g):
return s[p*2:p*2+2]
i+=11
return'XX'
```
Data is packed in a base64-encoded and zlib-compressed string with the format:
pppcccccddd
where ppp is province index, ccccc is starting zipcode and ddd is delta.
For example, zipcodes for "RM" province (Rome) would be:
```
08200010004 (from 00010 to 00013)
08200015000 (from 00015 to 00015)
```
and so on.
[Answer]
# Python 2, 2714
```
e='x\x9c5X\xcbr\xeb:\x0e\xdc\xeb[\xe4*\x91 Ar\xe9\xf8\xe6dR\x93\xc4\x1e\xdb\xc7\x8b\xfb\xff\x1f2\xdd\rd\x83\xa6(\x8a\x0f<\x1a\xa0\xde>j;\xcaq\xaaeG\xc3\xecd\x8eF9\x0e\xcaZNs{;\x8f\x83#\xcaN\xb4Sq6\xacF\x87\x8d\xc0VO\x95\xd8\x9b$\xc7p\x12HNB\xb4\xb2\xbd}YE\xf7NYO\x8dX\xb1\xb4\xd0\x03\xed8\rb\x0b\xc4\x1c\xdb\xdb\xcf\xac\xb1\x01\xa2I\xf6SYl\x18?\x9b1\xec\xdab\x9fcG\xc3\x0e\xc9zrb+\x18F\xc4w\xc2I\xd9\xb9\x06q\x9d\n\x87s\xc3-7\xdc\xb8\xe1\xc0\x86\x8d\x7f\x16\x9b\xa5\xe0cb\xc3\xd6\x81\x18\'4\xf5Ru\xc4\xa6\xa7fX\x908\xe2\x9b^N\x9d\xe8\x05K\x02G\xe2L\\\x1a\xb5\xec4\xb6\xb7\xe7\xf0\x03kA\x85\x8e\xbdH\x9ad\xdf\xde\xeeC\n\x1cR N:\xe2\xe8\x8f\xday\xf4\xdew4|\xca\x9a]F\xecq\x1c \x8e\x83\t\xfe\xb5\xc5\x91P\x80-~z\x7fo\xa1\\\x1cU\xda\xef\xc2!\x19z\xd1\x12\xf7\x8fE\x8b\x9e\xd6\xbe\x86\x9e\xcfmj\xc9\x9d\xc8S\x02\xeb!Y%\x1b\xf4\xd1\xa6\xc6^\xa6\x16\x9d;\x10\x06\x87m\xd0\xe8U\xb2I\xca\x8c\xebp\xbd\xf1\x8aO\x89017I\xa9S\x00q\x8a\xb6\xdd\xbf1\x1b\xb4\r\x95\x8e\x93\xcd\xbd\x0fh\xcb;\xcdQ\x16\xb6\x18\xa6\x83\xe1(\xbb\xa4K\x0e\xc9)\xb9\xe8\xdc\xf7\x9f6`\xd0\x1d\x92\xdb\x86l\'ax\xce\x98\xe19cv\x0b\xf4\xa2\xfe\xc5c]\x9b\xb4\x8e~`\xa3\n\xbaTq\xb0a\xd4U\xeb:\xff\xa7T\x8c\xc0:\xca\xa41\x8eJ!eWEP\xdd\xa5\xe4\x8f{\x9f1#\x913v)\xd7\x88\xb5b8\xd0\xd4\x0bw\x0b\xf4\x18\xdd\x0e\xc9\x1ac\xbb\xdei\xcf]&\xf8x/\xae\x99\x1d\xaa8l\x9eJ\xa1N\xa0\xdb\xe2\xa1[\xa0%\xb6\xc4_\xcd\xf1\xcc\xdb\xc7\xd5\xda1x(ke\x1c\xdb\xf5c\xd2M\xb42\x17\xa6h\xf0\xb0\xebs\xd0\xc6tR\xac\xb3\xd3)\xb6\xeb\x9d\xc7B\x9b\xd1{0r\x19\x9f\x10m_\x9c\x13\x94\xb2\x8e9!\x96<\x8c\xf3\xdf\xee\xcd\xd2\xc1\x8c:\x10Vi\x198\xa9uC|Kv\xe9\xdc\x8eF?\x00\xf6\x1e\xc3\xfa\x14*\xae\xadT\xdfn\xaf*/nP\xfc8\xe06P\xbc\xdc\xf9\xf6\x84\xa5\xe4T\xc4\x8ei\x80\xb5INJ#\xff\x10[\x8c\xb1\x05\xa9/\xff\xba\xbel;\xb0\xd2\xcaD\xee\x0fh5Q6\xf6\xf8\xe0\xdf\xd93\x1a\xba\xe8\xef`C\xfcI\xf4\x13\x95$\xbf\xb9]\xaa\xe2\x06\n\xab\n\xd6\xdby\x89\xe2\xb0\xf8\x12[\xadd\xab\x95l\xb5\x8e0\x1e\xb0\x97\xed\xf6A\x9b\xef\x10\x95\xa2Q8\xc5\xe4\x1a.\xb6\xdf\xe5\r\x0b\xd0\x16\xf7J\xa7\xe1@p\xe2\x00\xb8\x0er\x0c\xb2\xbd\x1fS\xc2\xa2\xbdv\xf9O\xba\x8f\xbc\xa7\x10\xdav\xfb\xc7"0\xc0\xe8\x9d\x1ak\xc4\xc6#\x9bX\xc9\x92\x95\xac\xc7\xb6\x81\x8c\xb3\xed\xf6\xee\xc1c;qH.\xce\xda\xe9\xfd|\xd6\x8a\xf9\xb5\xebk\x1c\xf3\xb3{F\x8d\xf3+\xcaE\x0b:\xed\x00\x05\xa0\xd1d> \x8fL\x84Q\xb5\xfd\xae\xfd\x8f\xed\xf6c\x06W\xdc)\xabd\xa3\x92\xd0X\xea\\\xea\\\xf4?"=\xc7L~z\xed\xd06&\xa7\r$\xe9|\xc0\x1a\x92|\xd2e\xbd\xf7\x9f\xd5\x92B\x99`\xb7\xef\xf75E\x87;\xb136W\x04-\x1b2\xefL\xf3\xce4\xefL\xf3\xce\x88M \x13\xca\xf6}\xf1\x1a\x1a r\x8fD\xc6\x0c\x10;\x10\x9a\xdeZ\x8bQ\xa4\x00\xa0\xf6\xf1V\x0f&7\x92\x11\x93\x9a\xd0\x98\x98\x80\xad\x88\xb7\x98\xc0\x84\x9e8\x12g\x8c\'\x1f~_\x9b"\x01j@\x03\x07\x02?\xa3\xd1\x98\xe9\x89\n\xc6rh\xe7M\xa1\xf0\xfd\xd3<b\x87H\x9e\x03\xc2\xd2P\'\x1a\x08\xeb*\x8c4\xe4\xfa\x02T\xaa\x93"\xb51\xbdKr\xa3\xa4\xa1\xaa\xc2\x03\xd2\xc5?h\x0c&&\xe0\x8c \xcah\xa9\x19-5\xa3\x85\xf5D\xa2\xd3\xa1\xbe\x9f\xa3g\xdc\r\x05\xe2\xf9\xde\xb3\x02\xe9\xd2o#\xaar\xe9\xd2\xef"b\xbbFl\x1a\x05G\x03[\x87~\x1f\xbd\x05\xff\x03\xe9\x15\x90&\xe9\'\xa1\x85\xec\x92pLy\xc7\xe7w\x99Y\xce\x94\x19\xd9\xa4\x88\xca\xff\xdc-t\x06\xc0\x04\xf0Q\xf5^\x9a\x98\x8d\xaa\x1b\x9c\x9f\xb2K*9\x0fUDC\x8c9\xe8\x05\xd1\xb7([\xd5\x93hrPEe\xfb\xf3\xdeZ\xe66V@\x89\x8b\x96j4m\'\x9aE?\xab\x85\xa6\xb9ZVZ@\x8dhCO\xda\xe0\xc7\x08\x86E-S\xf8\x9aR\xc5\xa3\\\xe1\xcfg\xa7awJR!qR\x85\x07\x973\xa2l\xd6\x0f)X\xc5\x9b\x0b#\xc4E\x87]\x06v\xe1\xa2\xb4|2=5\xd6\x0e\x7f\xbe\xdd\xc2\xdb]%\xdc jjg\xf1\x16\xcf\x9dQ\xf5s\xad\xb2\x00\xdcKI\x0b\x92u\x15K\x1b\xc9I)b!\x9a$]\x16\xd8\x0fI\xf5\xf9\x11}\xde\x12\x95|\xabl\xf9s\x9eG\x18\x93\xe8\xca\x05\x07cS\x1d\xc8\xa7L\xb0\xa4\x04e\xcf\xc39=q\x05\x0e\xc3\xf1\xa6\x8e>\xd3\xb7g\xfa\xf6\xd4q}\xfb\xfb\x8fY\xb8.Q\x84\x06\x82j\x8d\xec\xc5\r\xfc\xcd\x82c\xb2\xdb\x94\xae\x99\xaaXXP0f\xb5\xd3\xcbg\xa4"\xa5\x1a\xa8\xf1\xf2\x1fO\xd2%2\x04\x80 .HS2\xf4(M\xdc\xa3\x94\x07\xf6\x1c\xdd\xf9Vs^\xab\xc2\n\x9e\x89F\x93~*k@J\x93tI\x11@U0]~\x8a\xbei(d*\x8cO\xe9t\x05\xe2d%Q\xc8N\xac\xbe\xab\xca\x1bR\xebv\xf9Z\x96\xd4\xabc_\xde\xa6g"\x9d\xb1\x95\xf3oIB\x1d \x14eQ\x1eY9\x96\x82\x99\x10|n\xd2\x01)\x9a\x1e\xb0\xf8\xd5\x8a<\xbfx\xd2N\xe0\xf2*\\\xb3ne\xd9J\x01\xb5\xbd\xcf\xac\x16\x88\x1e\xda\xad\xfc\x8c8\xe2\x99\xb5\x86\x06\xb4\x1c\xd0\xa4\x80\xa9@\xb9\xfc;gp\xcf\x9cQ\x0fMy\xa1\x9e\x1b\xab\x13\xe2\x8a\xe7\xde\x02YWCF;\xbf\xf1\xa1\xb1\x9a\xf31\x83<\xb0\xea -\xd1\x03Fdl`O\x94\'\x135\xcc\xb5\xb9A\xeb\xc0KUE]\xee\xf5W\xad5\xd4\xfa\\\xc1\xa4\xd0G\x8f\xdd\x12\x07K\x83\xa5d\xbe2\x99/&\xf3\xed\xf1\xc8K\xc6\x88\x8b \x19J\xf7\xcaFO\xd7\x1a\x8f\xfb\xf24\xa5\x96x\xdcJ^.\x8a.\x17E\xd8%\xd5\'w$\xea*&\xb3\x14\xd9\x85c\x14,\xdb\xe3\x05\xa7\x19x;\xa2\xfa \x0eI\xdd&F\x94\xea\xc4\xa1\xc2y0\x89q\x007\xf0\xdf\xfb\x9c$\x14\xa8h\xc6\x9d\x10\xa8\xf4\tlE\xcafz||v\xe3\xbd\x0e.\x8aF\xd4\x93\x96\xf5\xa4Q\xd7\x81]\x92\x1e\xd4\xe5\xaa\x8fk\xb5\xcc\x03hTn\xa8\xc6\x8b\xf3l\x19=h4eM4\xba8\xa2\xb1\x803\xa2\x93\xac\x81\xe0\x8a\xa2\xc6:b\xc0b\x9dB\x9czN\xfahq\xc3\xfaz\x1f\x91e`\n\xad\xf6u\xa9\x06\x8e \xd9\x01\x99\x02+iT\x92\xb6\xa9"\xd3I\x8c\xd2Ad\xaa\xe7\x9e_\xf5\x96\xa8\xb7\x9e\xbd\x9e\xbd>\x02\xc7\x91h\xf15\xcb\xcd\xb1=_V\xc2\xca\xa6x\x81\x87\x99\xc2\xe1\xebZ\x9d\xda\xc7\x9c\x1et\x0e\x8c\xec\xee\xb9\x03\x9f=1\x8a\x17\xa75\x9e\xf7,\xc2{\x14\xed\x9d\xb5"\xf2z\xa4\xc6\x1e\xf5=\xc7=,\x13\xa1\xb5H\xfd\xa6\xbf#\x96\n\xb3\x96%l\x8bZ\x02\x88\xca\xfby[%+\x88\x15\xdb\xfc\xec\x83\x158%\xe3\xa6\x8f\xa8\xfc\xba\xb2t\xcf,\xddGx+Q\xb5\x81rr\x1fQ\xa2>\x7fl\xc6\x1d\xc5\xc4\xd6poS\xcaAt\xa1\x01\x83#1\xa11y\x116\x05\xf6\xf3Z\xe2\x9f\x08|\xfe`e\xd5\x843P\x95ya\xe9D\xfe\xd4_\x91\xa2\xc4Z\xd5\x98\n\xaa\x83\x0e\xd3\x85t\x94\x92y\xa6d\x9e)YC\x15\xd5P}\xfbz\xb6<\xb8\xb2\xfe\xd7\xdf\xde\xb3\xf6\xe9A\xa1]\xb5|\x11v\xc9Ai9\x86\xf5O\x0f>#jD\xd3\x08\xb8"d\xd7\x97H!\x90\x9e\xa3\x9cO:\xee\xbbg\xa5E\x9c\x94b\x04"\xeb1\xa0h\x85\xb8Nz\x8fY];}\x9eG\xcb\x1f!C\x1d\xafs-\x19\x02U6|\xbd\xd5\xc9\x10`\xf6\x8f\x80\xaf3]N\x01_\x85.\xa9w-\xc7\xf6\x1c\xeb\xaa\x95\x81z\x1aE\xd2$\xa3n\x98\x83U\x06&\x97\xb4\xf8z\xe9i)\xc8\xe6\xaau{]\x8a\x85K\x16\xdd\x8c\xc9HA(j\x88*\x81\xe0\xfc\xa2\xd0}\xbd\x9bJ+\xd3\xef;#VY\xc8T9\xd8\x11dh\xb2h\x15\xeaI\xdc\xc5\x15`\xff\xed\xfc\xb1\xea\xafG+\x11\xbf>\xcdC\xd7\xc0\xaa\xc8\xf4\xb0\xa21\xe5K\xd2\xceD\x9e\xce<\xfe\xb7\x01=G\r\xf92\xb0\x0bU\xf5>\xa6\xfa\xc1T\xce\xea\x9d\x05\x91\xf3\x9au\xfe*\xfd\xf7\x07\x06\xbdD\x7fvx\xa7\xe0\xdf\xb7(\xd2\xaf%)\xa2\x88"@\xdc2\xdb\xf9\xc7\xf3\xff%\xd1$\xbb\xe4\xd4M7\xfeT\xf9\x11\x94L$\xf3\x00[\\t\x19\x16.My\xfa\xbe\xebg\xe6\xf9\x7f>t\xbd\xe6?N\xce\xa0\xa4\xe1J\x1aHo\xae\xa4\x85\x82\xd1\x95*\xf9^\xbb\xb9\xb9\xf1?\x19$v\x0e\xe9Qz\x1e#qF\tz\xac(Q\xb5\xae\x91\xb1^w\xfbM\xd2\xc6$-\xc9#\x00\xf9\x07D\xc8\xab<\x90\x05\x83:\x9c\x85\x89\xe5\x0eLtb#\x99k$s\x8d\xd2\xe0T\x8f\x15U\x85\x92\xe7bT.f\x1bv`\xf6\xbe\xbd\x9e%\x9dN7L\x12\x87\x91U\x8c\x17\xf3P\xf4\xb3D\x04\xc1D\x19hE\x81\x16\x1d\xfa\xdbR"\xb4^\x93W[\xa6\xc8\xc5\x08\xe2\xdf>F\x90\xb0%\xf6\xa2\x7f\x82\x8c\x1a={\xfc#\xa4*\xce\xafi\xf9\x0b\xc5~\x0bV\xa5Rl}\xca\xe7\xff\x0f.\x98vx'.decode('zlib').split();d={}
for s in e:
d[s[:2]]=[]
for g in s[2:].split(','):
f=g.split('-');d[s[:2]].append(int(f[0]))
if len(f)>1:
for k in range(int(f[1])):
d[s[:2]].append(int(f[0])+k+1)
def f(s):
for g in d:
if int(s) in d[g]:return g
return'XX'
```
Provinces and zipcodes are stored in a zlib encoded file with the following structure:
```
BG24010-21,24033-36,24100,24121-8
```
Initially build a dictionary filled with all the values, then look up the province.
] |
[Question]
[
## Background
When playing an [RPG](https://rpg.stackexchange.com/) such as [Dungeons & Dragons](https://en.wikipedia.org/wiki/Dungeons_%26_Dragons), [Pathfinder](https://en.wikipedia.org/wiki/Pathfinder_Roleplaying_Game), or [Paranoia](https://en.wikipedia.org/wiki/Paranoia_(role-playing_game)), players each need a set of dice[.](http://www.giantitp.com/comics/oots0090.html) You are hosting one such game this weekend, and some of the friends you invited have never played an RPG before. They don't want to commit to buying their own set of dice until they know they'll use them (if they want to keep playing). This is fine and dandy with you, but you're not going to let them use your lucky set of dice that you [pre-rolled the ones out of](http://www.darthsanddroids.net/episodes/0099.html)...
## Goal
...so you are going to write a program or function that simulates the dice-rolling for them.
Dice are often described in the format: `<How many dice>d<Number of sides>` A [common set of dice](http://www.coolstuffinc.com/p/146929?gclid=CN6Agazk28cCFQeLaQodrHQKMQ) for RPG use includes: `1d4`, `1d6`, `1d8`, `2d10` (also used as `1d%` or `1d100`), `1d12`, and `1d20`.
Your code must accept a string of any number of the above dice specifiers separated by spaces or commas as input. It must then output the result of each individual die-roll separated by spaces, with parentheses around groups; then the sum of each grouping on the next line, separated by spaces; and finally, the total sum on a third line. Single-die groups don't have parentheses. Dice must always be in the same order as provided in the input.
The percent die, whether written as `1d%` or `1d100`, should be calculated as the concatenation of `2d10` (just 2 rolls, each from 0-9, but a final result of zero is instead counted as 100), but each occurrence will be displayed as if a single roll. `2d10` in the input will still be treated and displayed as 2 individual rolls. It can be easy to get confused by percent dice, here's a good [explanation](https://www.rpgcrossing.com/showthread.php?s=86ecd4d28625a220149ecdd890b7fb67&p=1532888#post1532888).
**Edit**: To clarify, the number of rolls may exceed 9.
## Examples
### Input:
```
1d4 3d6 2d8
```
### Possible Output:
```
3 (1 5 2) (8 4)
3 8 12
23
```
### Input:
```
1d20 1d% 2d10 1d100 5d12
```
### Possible Output:
```
16 100 (9 4) 42 (5 1 7 7 11)
16 100 13 42 31
204
```
## Rules
* Standard loopholes are disallowed.
* Printable ASCII in code, only.
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest code wins.
* -10 bytes if the rolls are actually random, rather than pseudo-random.
[Answer]
# Pyth, 48 bytes
```
-jdm?td(.*dhdJ.bmOSYNmm.xsk100cd\dcz))\,jdsMJssJ
```
[Test Suite](https://pyth.herokuapp.com/?code=-jdm%3Ftd%28.%2adhdJ.bmOSYNmm.xsk100cd%5Cdcz%29%29%5C%2CjdsMJssJ&input=1d4+3d6+2d8%0A1d20+1d%25+2d10+1d100+5d12&test_suite=1&test_suite_input=1d4+3d6+2d8%0A1d20+1d%25+2d10+1d100+5d12&debug=0)
Tricks / golfs in this code:
* Everything that's not a number will be treated as 100, not just `%`.
* To get the parentheses, I make the list into a tuple, then subtract out the commas.
* This is the first time I've used `.b`, the binary map, which was added 3 days ago.
* The code contains 6 different map functions.
[Answer]
# Pyth - 56 bytes
Nothing fancy, many nested maps. As OP said above in comments, we don't need to do the concatenating thing, just recognizing `%` is enough.
```
jdm?tld++\(j\ d\)j\ dKmmhOeGh=GsMcsXd\%]100\dczdjdJsMKsJ
```
[Test Suite](http://pyth.herokuapp.com/?code=jdm%3Ftld%2B%2B%5C%28j%5C+d%5C%29j%5C+dKmmhOeGh%3DGsMcsXd%5C%25%5D100%5CdczdjdJsMKsJ&input=1d4+3d6+2d8&test_suite=1&test_suite_input=1d4+3d6+2d8%0A1d20+1d%25+2d10+1d100+5d12&debug=0).
[Answer]
# Lua, 183 bytes
```
a=arg[1]:gsub("(%g+)d(%g+)",function(r,d)d=d=="%"and 100 or d n=tonumber(r)s=n>1 and"("or""for i=1,r do s=s..math.random(d)..(i<n and" "or"")end return s..(n>1 and")"or"")end)print(a)
```
[Answer]
# Pyth, 59 bytes
```
JmhMOMd.b*N]?YY100mvdcXz",d%"" ,0";-jdm?td(.*dhdJ\,jdsMJssJ
```
[Test Suite](https://pyth.herokuapp.com/?code=JmhMOMd.b*N]%3FYY100mvdcXz%22%2Cd%25%22%22%20%2C0%22%3B-jdm%3Ftd%28.*dhdJ%5C%2CjdsMJssJ&input=1d4%2C3d6%2C%202d8%0A1d20%201d%25%202d10%201d100%205d12&test_suite=1&test_suite_input=1d4%2C3d6%2C%202d8%0A1d20%201d%25%202d10%201d100%205d12&debug=0)
Unfortunately, neither isaacg's nor Maltysen's answer handles commas properly. When/if isaacg fixes it, I'm sure his will remain smaller.
[Answer]
# [R](https://www.r-project.org/), 200 bytes
```
for(d in strsplit(scan(,""),"d")){d=gsub("%","100",d);u=d[1]>1;cat(if(u)"(",paste(i<-sample.int(d[2],d[1],T),collapse=" "),if(u)")"," ",sep="");F=c(F,sum(i))};cat("\n");cat(F[-1],"\n");cat(sum(F[-1]))
```
[Try it online!](https://tio.run/##RY6xDsIwDER/JbKEZEsGNZWYShj7BWyFIdQtilRKVKcT4ttLWga2s333ztOy9K8JxYTRaJo0DiGhtn5EBiAGAaK3uIfOd4QdMNiiABaqZieNvZ1t1fqEoceZAIGj19RhOO3VP@PQHcKYUJryxquZL8Ttaxh81M6ByfhfjjLWAGsXXe6satdizTo/MRB9Nj5cx3xYVd3sM@g/r7ZtR7RYKQtjZWdKsavIr5qj2HL5Ag "R – Try It Online")
```
for(d in strsplit(scan(,""),"d")){
d=gsub("%","100",d) # replace "%"
u=d[1]>1 # whether to print parenthesis
cat(if(u)"(",
paste(i<-sample.int(d[2],d[1],T),collapse=" "),# dice rolls
if(u)")",
" ",
sep="")
F=c(F,sum(i))}
cat("\n")
cat(F[-1],"\n") # sum of rolls of a certain type
cat(sum(F[-1])) # sum of all dice rolls.
```
This can be shortened for sure... this is a naïve implementation with a for loop.
] |
[Question]
[
# Introduction
Local genius [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies "Calvin's Hobbies") recently challenged us to [trace the hue of an image](https://codegolf.stackexchange.com/questions/47790/tracing-the-hues-of-an-image "Original Challenge").
It is recommended to read his challenge beforehand, but to highlight the main points:
* The trace of hue in an image can be found by starting at one pixel, finding its [hue](http://en.wikipedia.org/wiki/Hue "Wikipedia Hue") angle(`hue = atan2(sqrt(3) * (G - B), 2 * R - G - B)`), and moving one pixel's width in that direction. If this process is repeated, and a black pixel is left at each pixel passed, we produce a trace of the image.
Here is a simple example of the trace:

We start at pixel `250, 250`, with RGB color `36, 226, 132`. We observe that the hue of this color is 150. Thus, we begin drawing a black line 150 degrees counterclockwise from the positive x-axis. We run into the square to the left, with RGB color `100, 220, 7` and hue 94. This results in an almost vertical line to the next square. We continue the pattern into every square, and observe the change in slope at each new color. The length of this trace was 300 pixels. If you're wondering why the image is so ugly, it's because I randomly generated 25 colors in 100x100 squares and used [my answer](https://codegolf.stackexchange.com/a/47884/31054 "C Answer For Hue Trace") to trace it. On a much more complex and beautiful image, we may get a trace like this one:

* Calvin created this wonderful code snippet on the original post that draws a trace over an image, starting at the point provided by the mouse cursor. This is a very useful testing tool!
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>canvas{border:1px solid black;}</style>Load an image: <input type='file' onchange='load(this)'><br><br>Max length <input id='length' type='text' value='300'><br><br><div id='coords'></div><br><canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas><script>function load(t){if(t.files&&t.files[0]){var e=new FileReader;e.onload=setupImage,e.readAsDataURL(t.files[0])}}function setupImage(t){function e(t){t.attr("width",img.width),t.attr("height",img.height);var e=t[0].getContext("2d");return e.drawImage(img,0,0),e}img=$("<img>").attr("src",t.target.result)[0],ctx=e($("#c")),ctxRead=e($("<canvas>"))}function findPos(t){var e=0,a=0;if(t.offsetParent){do e+=t.offsetLeft,a+=t.offsetTop;while(t=t.offsetParent);return{x:e,y:a}}return void 0}$("#c").mousemove(function(t){function e(t,e){var a=ctxRead.getImageData(t,e,1,1).data,i=a[0]/255,r=a[1]/255,o=a[2]/255;return Math.atan2(Math.sqrt(3)*(r-o),2*i-r-o)}if("undefined"!=typeof img){var a=findPos(this),i=t.pageX-a.x,r=t.pageY-a.y;$("#coords").html("x = "+i.toString()+", y = "+r.toString());var o=parseInt($("#length").val());if(isNaN(o))return void alert("Bad max length!");for(var n=[i],f=[r],h=0;n[h]>=0&&n[h]<this.width&&f[h]>=0&&f[h]<this.height&&o>h;)n.push(n[h]+Math.cos(e(n[h],f[h]))),f.push(f[h]-Math.sin(e(n[h],f[h]))),h++;ctx.clearRect(0,0,this.width,this.height),ctx.drawImage(img,0,0);for(var h=0;h<n.length;h++)ctx.fillRect(Math.floor(n[h]),Math.floor(f[h]),1,1)}});</script>
```
Snippet tested in Google Chrome
* Answers to that challenge may also serve as appropriate testing tools for this challenge.
*Note: I do not take any credit for Calvin's work, and have received explicit permission to use his ideas in this challenge.*
# The Challenge
In that challenge, we found the trace. Now, I'm asking you to find the image. You will be given a start point, an end point, and a `length`, and your program must output an image whose trace beginning at the start point arrives at the end point in approximately `length` pixels. Moreover, because there are so many options, your program's algorithm must be inherently random in some regard--thus the same input should (more often than not) produce a different output image.
# Input
You will receive seven positive integers as input: `w, h, x1, y1, x2, y2, len` where:
* `x1, x2 < w <= 1920`
* `y1, y2 < h <= 1080`
* `len < 2000`
These guidelines are minimum requirements. Your program may accept higher values.
You may receive input through stdin, a file, or as arguments to a function. You will ONLY receive these 5 integers as input.
# Output
As output, produce an image of width `w` and height `h` with a continuous hue trace from `x1,y1` to `x2, y2` in approximately `len` pixel-width steps.
* Output should be random.
* Output may be in any format--whether it be .bmp, .png, PPM, or an image shown on-screen at runtime makes no difference.
* You may assume it is possible to move from `x1, y1` to `x2, y2` in under `len` pixels.
* Output should NOT show the path of the trace from `x1, y1` to `x2, y2`--though an image showing this path in your answer is appreciated.
# Rules
* This is a popularity-contest! Try to make your output beautiful or interesting. More interesting hue traces than straight lines are also recommended.
* This is **not** code-golf. As such, readable code is appreciated. Still, try to keep size below ~2KB. This rule will not be strictly enforced.
* Values are approximate. If your code's trace reaches its destination within ~5-10% of `len` pixels, this is acceptable. Along this same vein, do not worry about slightly incorrect hue angle values. Some error is reasonable.
* This is graphical-output. **Please** include output images of your solution in your answer.
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny "Standard Loopholes") apply.
*Questions, comments, concerns? Let me know!*
[Answer]
All the code is on [bitbucket](https://bitbucket.org/BenjaminHewins/imagefromhue/overview)(it is completely unoptimised). The hue path tracing logic is my own so might differ slightly from that in the original question. Instead of trying to work out a function to generate a line and then an image from that, it makes multiple sets of random changes to a starting image and then picks the set where the end of the path is closest to the target end, then repeats.


I think it looks kinda artistic sometimes. The current randomisation method just draws randomly coloured rectangles, if you run the program yourself you can watch it iterating. With 60 generations (and 70 children per generation) it basically always gets within a pixel of the target. I tried swapping individual pixels but that was too slow. Plain rectangles was the best (simple) way of changing the image that I tried which still created interesting output. I might see how well circles work later.
] |
[Question]
[
Mr. Moneybags is a very rich man. He has an assistant Mr. Perfect, who one day, got very mad, and shredded some of Mr. Moneybag’s $100 bills! Mr. Moneybags decided to punish Mr. Perfect.
Mr. Moneybags tells Mr. Perfect to stack his money into different piles.
He starts with N (1 <= N <= 1,000,000, N odd) empty stacks, numbered 1..N. Mr. Moneybags then gives him a sequence of K instructions (1 <= K <= 25,000), each of the form "A B", meaning that Mr. Perfect should add one new bill to the top of each stack in the range A to B, inclusive. For example, if Mr. Perfect is told "11 13", then he should add a bill to each of the stacks 11, 12, and 13.
After Mr. Perfect finishes stacking the money according to his instructions, Mr. Moneybags would like to know the median height of his N stacks -- that is, the height of the middle stack if the stacks were to be arranged in sorted order (N is odd, so this stack is unique). Please write an efficient program to help Mr. Perfect determine the answer to Mr. Moneybag’s question.
INPUT FORMAT:
* Line 1: Two space-separated integers, N K.
* Lines 2..1+K: Each line contains one of Mr. Moneybag’s instructions in the form of two space-separated integers A B (1 <= A <= B <= N).
SAMPLE INPUT:
```
7 4
5 5
2 4
4 6
3 5
```
INPUT DETAILS:
There are N=7 stacks, and Mr. Moneybags issues K=4 instructions. The first instruction is to add a bill to stack 5, the second is to add a bill to each stack from 2..4, etc.
OUTPUT FORMAT:
* Line 1: The median height of a stack after Mr. Perfect completes the
instructions.
SAMPLE OUTPUT:
1
The winner is the one with the "most efficient" algorithm. So, if someone posts an O(N) solution, then it will beat any O(N^2). If there is a tie, aka, two or more people who post an O(N) solution, for example, then whoever has is the shortest code (code-golfed) wins.
So, your purpose is to write a efficient algorithm, and to prevent possible ties with other people, try to code-golf it as well.
Another thing, the input is to be read from a file and the output must be written to a file.
**EDIT**
Also, the solution must be returned under or equal to 2 seconds. If it is not, you will receive a T. A wrong answer is an X. Which means, if no one can get it under time, then the most efficient algorithm sigh score of T can win.
**EDIT #2**
Here are some more samples:
1. <http://pastebin.com/x88xAyPA>
2. <http://pastebin.com/y6Cuxm7W>
3. <http://pastebin.com/kgbeiQtd>
**EDIT #3**
Bonus: (subtract 100 chars from total)
Solve this under 2 seconds :)
1. <http://pastebin.com/3uT9VSzv>
[Answer]
# O(K log N), many characters of Python
**Edit:** Improved by replacing merge sort with radix sort.
This is an improvement over [my previous answer](https://codegolf.stackexchange.com/a/35153/20260), but I'm posting it separately because it's a different strategy, and so the post doesn't get super-long.
This is now optimal because simply reading the input can take `2*K*lg N` time in the worst case -- `2*K` numbers each with `lg N` bits.
The goal is to have minimal dependence on `N`. To do this, rather than store counts for each pile index, we realize that all piles in a contiguous cluster unaffected by the endpoints of any interval must have the same counts. So, if we see that an interval starts with `5`, and there's no changes until `15`, then those 10 piles have the same value.
Each change in pile size from a pile to the next one is caused by an interval starting or ending. We call these "events". Each event increases or decreases the current pile size by 1. If, from one event to the next, there's some number of piles, each of those piles has the current size.
We extract the `2*k` events from the intervals, and sort them using a radix sort, taking advantage of the values being `1` through `N`. This take takes `O(K*log(N))` because the numbers have `O(lg N)` bits.
We then run over the events, and for each one, update the list of counts to the previous event, which requires adding a number up to `N` (so `lg N` bits). This takes `O(log(N))` per step, and so `O(K*log(N))`
Finally, having gotten the counts of the pile sizes, it's easy to quickly find the median by computing the cumulative number of piles up to a given size (or, rather, we subtract it from our desired count). This also takes `O(K*log(N))`.
The algorithm does the huge test case in under a second.
The code (ungolfed) is below with comments.
```
# Process input
def get_ints(line):
vals = line.split()
return (int(vals[0]),int(vals[1]))
s = input()
lines = s.split("\n")
N,K = get_ints (lines[0])
intervals = [get_ints(line) for line in lines[1:]]
mins,maxes=map(list,zip(*intervals))
#Each event will represent an increase or decrease of a pile from the previous one
#Each min increases the count by 1
#Each max causes the count to decrease by 1, starting with the next pile
events = [(a,1) for a in mins] + [(b+1,-1) for b in maxes]
events.append((N+1,0))
#Do a radix sort on the first element of each pair
#Each number has O(lg N) digits, so this takes O(k lg N)
events.sort()
#Count of the number of piles of each size
#pile_sizes[size] counts the number of piles of that size
pile_sizes = [0]*K
cur_pile = 1
cur_size = 0
#For each event, we track the pile size after the event
#Then, on the next event, we know there were some number of piles of that size
#The number of piles equals the distance between events
#Multiple events on the same pile have zero distance and don't affect the counts
for event in events:
event_pile = event[0]
piles_current_size = event_pile - cur_pile
pile_sizes[cur_size] += piles_current_size
cur_pile = event_pile
cur_size += event[1]
#Get the i_th largest pile size from a list of pile size counts
def get_order_stat(counts,i):
for val in range(len(counts)):
cur_count = counts[val]
if i<cur_count:
return val
i-=cur_count
return None
median = get_order_stat(pile_sizes,N//2)
print(median)
```
[Answer]
# O((N + K) \* log(N)), many chars of Python
(See my [improved solution](https://codegolf.stackexchange.com/a/35156/20260).)
**Edit:** I realized that I wasn't accounting for operations with numbers taking `log(N)` time. For example, I think the linear time median, despite its name, is actually `N log N` once you take into account the time to compare numbers bit by bit.
**Edit:** Improved sorting. Thanks to isaacg.
The idea is to make a list of the size of each pile `1...N`, and then take the median of this list. The key is to obtain the size of a pile from the size of the pile before by adding the number of intervals that start at that value, and subtracting the number that end at the previous value. By sorting the lists of interval-starts and interval-ends, we can quickly query how many intervals start and end.
See the code for more detailed comments. I didn't golf it.
The code has no problem with the huge test case, taking <1 second on my machine.
```
# Process input
def get_ints(line):
vals = line.split()
return (int(vals[0]),int(vals[1]))
s=input()
lines = s.split("\n")
N,K = get_ints (lines[0])
intervals = [get_ints(line) for line in lines[1:]]
# Separate out the starts and ends of the intervals.
# Sort each, which takes O((K + N) * log(N)) with a counting sort.
mins,maxes=map(list,zip(*intervals))
mins.sort()
maxes.sort()
#Make a running list of the sizes of each pile
size_list = []
cur_size = 0
for i in range(1,N+1):
#Update the size of the next pile by adding one for each interval that starts here
#Each number in min can only can one update, so this contributes O(k) total
while mins and mins[0]==i:
mins.pop(0)
cur_size+=1
#Likewise, subtract one for each interval that ended at the previous number
while maxes and maxes[0]==i-1:
maxes.pop(0)
cur_size-=1
size_list.append(cur_size)
#Now, we compute the median of size_list
#The naive median algorithm sorts and take the middle element, taking O(N*log(N)) time
#But, there's a linear-time algorithm to select the median (or any order statistic) of a list
linear_time_median = lambda L: select(L, 0, len(L), len(L)//2)
#I didn't want to write my own linear median algorithm, as it standard but long.
#So, I use the linear median code from https://gist.github.com/boyers/7233877
median = linear_time_median(size_list)
print(median)
```
Here's the code for linear-time-median from <https://gist.github.com/boyers/7233877>.
```
#### Code credit: https://gist.github.com/boyers/7233877
# partition A[p:r] in place about x, and return the final position of the pivot
def partition(A, p, r, x):
# find the index of the pivot
i = -1
for j in range(p, r):
if A[j] == x:
i = j
break
# move the pivot to the end
if i != -1:
t = A[r - 1]
A[r - 1] = A[i]
A[i] = t
# keep track of the end of the "less than" sublist
store_index = p
# iterate
for j in range(p, r - 1):
if A[j] < x:
t = A[j]
A[j] = A[store_index]
A[store_index] = t
store_index += 1
# put the pivot in its final place
if i != -1:
t = A[r - 1]
A[r - 1] = A[store_index]
A[store_index] = t
# return the store index
return store_index
# find the ith biggest element in A[p:r]
def select(A, p, r, i):
# make a copy of the array
A = A[:]
# divide the n elements of A into n / 5 groups
groups = [[]] * (((r - p) + 4) // 5)
for x in range(p, r):
groups[(x - p) // 5] = groups[(x - p) // 5] + [A[x]]
# find the median of each group
medians = [sorted(l)[(len(l) - 1) // 2] for l in groups]
# find the median of medians
if len(medians) == 1:
median_to_rule_them_all = medians[0]
else:
median_to_rule_them_all = select(medians, 0, len(medians), (len(medians) - 1) // 2)
# partition A around the median of medians
partition_index = partition(A, p, r, median_to_rule_them_all)
# base case
if p + i < partition_index:
return select(A, p, partition_index, i)
if p + i > partition_index:
return select(A, partition_index + 1, r, p + i - partition_index - 1)
return A[p + i]
```
[Answer]
# C#
~~307~~ ~~273~~ ~~281~~ 283 characters. ~~A complexity of O(K)~~ I'm not sure but could be O(K\*N).
```
void m()
{
var r = new StreamReader("in.txt");
var m = new int[int.Parse(r.ReadLine().Split(' ')[0]) + 1];
string l;
while ((l = r.ReadLine()) != null)
{
var t = l.Split(' ');
for (var i = int.Parse(t[0]); i <= int.Parse(t[1]); i++)
{
m[i]++;
}
}
Array.Sort(m);
File.WriteAllText("out.txt", m[m.Length / 2].ToString());
}
```
The character count is after deleting all new lines/unnecessary whitespaces...
PS: Your input example has an even amount of stacks, which violates your rule.
PPS: I answered the wrong question in my first try.
Second version little bit bigger but faster. If compiled without debug symbols (ctrl + f5 in visual studio 2013) 2.5 seconds for the last example.
But 318 characters...
```
void m()
{
var r=new StreamReader("in.txt");
var m=new int[int.Parse(r.ReadLine().Split(' ')[0])];
string l;
while((l=r.ReadLine())!=null)
{
var t = l.Split(' ');
var e=Array.ConvertAll(t,int.Parse);
m=m.Select((c,i)=>i>=e[0]&i<=e[1]?++m[i]:m[i]).ToArray();
}
Array.Sort(m);
File.WriteAllText("out.txt",m[m.Length/2].ToString());
}
```
[Answer]
# C# - 374 Characters
Shamelessly lifted from Armin, and probably possible to micro-optimize even further. However, I saw his post and thought "Low hanging fruit" so hey, may as well.
```
void Main(){var r=new StreamReader("i");var m=new int[f(r.ReadLine())[0]];string l;while((l=r.ReadLine())!=null){var t=f(l);for(var i=t[0];i<=t[1];i++){m[i]++;}}Array.Sort(m);File.WriteAllText("o",m[m.Length/2].ToString());}static int[]f(string n){int[]b=new int[2];int r=0;for(int i=0;i<n.Length;i++){char c=n[i];if(c!=32){r=10*r+(c-48);}else{b[0]=r;r=0;}}b[1]=r;return b;}
```
## Ungolfed
```
void Main()
{
var r = new StreamReader("i");
var m = new int[f(r.ReadLine())[0]];
string l;
while ((l = r.ReadLine()) != null)
{
var t = f(l);
for (var i = t[0]; i <= t[1]; i++)
{
m[i]++;
}
}
Array.Sort(m);
File.WriteAllText("o", m[m.Length/2].ToString());
}
static int[] f(string n)
{
int[] b = new int[2];
int r = 0;
for (int i = 0; i < n.Length; i++)
{
char c = n[i];
if (c != 32)
{
r = 10 * r + (c - 48);
}
else
{
b[0] = r;
r=0;
}
}
b[1] = r;
return b;
}
```
Using LinqPad and the third pastebin link from the op, running a GC/warmup, and taking the average of 10 runs I get the following comparison times:
* Armin first answer: 3229ms average
* Armin second answer: 2601ms average
* My answer: 18ms average
First submission so I can't wait to see how badly the more seasoned posters can beat this!
Also, now that the bonus was added I can test mine against that!
However, sadly over an average of 10 runs on my computer it takes 4293ms to come up with 9314. So I have quite a ways to go yet.
[Answer]
# Lua, 247 bytes
The program constructs a frequency table and finds the median from that. I don't know what that would be in the complexity notation. For the sake of code-golfing, the output is appended to the end of the input file. If that's a problem, I'll change it.
```
s="*n"f=io.open(--[[FILE NAME--]],"a+")t,i=f:read(s,s)b={}c={}d={}for x=1,i do
y,z=f:read(s,s)for w=y,z do
q=b[w]or 0
if c[q]then
c[q]=c[q]-1
end
b[w]=q+1
c[q+1]=1+(c[q+1]or 0)end
end
n=0
for _,i in pairs(c)do
for w=1,i do
d[n]=_
n=n+1
end
end
f:write(d[#d/2])f:flush()
```
**Ungolfed**
```
s="*n"
f=io.open("input.txt")
t,i=f:read(s,s)
b={}
c={}
d={}
for x=1,i do
y,z=f:read(s,s)
for w=y,z do
q=b[w]or 0
if c[q]then
c[q]=c[q]-1
end
b[w]=q+1
c[q+1]=1+(c[q+1]or 0)
end
end
n=0
for _,i in pairs(c)do
for w=1,i do
d[n]=_
n=n+1
end
end
f:write(d[#d/2])
f:flush()
```
] |
[Question]
[
You have to make a golf game with the following specification :-
1. The field is 10 X 10 characters without spaces.
2. Free ground is represented by `.`
3. A hole generated at random(not at `0,0`) is shown by `O` (its alphabet and not zero).
4. The ball starts at `0,0` represented by `X`.
5. You can hit the ball with input `d 4` (meaning direction to the bottom with magnitude of 4 characters after the ball more like vectors in physics).
**Example:**
```
X.........
..........
..........
..........
..........
..........
..........
..........
..........
.........O
score : 0
b 4
```
But, since you are not so good at golfing therefore the force you think is applied is often only close to the actual force that is applied !(if `x` the offset in force then **-2 < X < +2**)
6. you should have to tell the real force applied and display the ball moved to that real force like this :-
```
lets say the ball actually moved by 3.
..........
..........
..........
X.........
..........
..........
..........
..........
..........
.........O
score : 1
applied force : 4
real force : 3
```
The four directions are `U (up), D (down), l (left), r (right)` and magnitude of force should be between 0 and 10 (excluding both 0 and 10).
7. The ball should not bounce off the edges, if the force reaches that much then the the ball stops at the last point at the boundary.
```
r 9
..........
..........
..........
.........X
..........
..........
..........
..........
..........
.........O
score : 2
applied force : 9
real force : 11
```
8. In the end when the game is finished you have to display `Par in <n> shots!` (where n is score)
## Coding:
1. You have to design a working program showing the exact output.
2. post the code in `golfed` and `ungolfed` versions.
3. also post a successful test run (images if possible).
4. No use of functions or languages excessively specialized to this task (I don't know if they really exist!)
## Winner:
Winner will be chosen 1 week from now.
Winner is the submission with least characters.
# And, most important thing
Best of luck **:)**
[Answer]
# K, 319 305 308
```
{b:(10*!-_-(100)%10)_@[100#".";0,1?100;:;"XO"];c:0 0;e:s:-1;while["O"in,/b;e@b;e"Score : ",$s+:1;h:"SI"$" "\:0:0;h[1]:1|*(w:h 1)+1?-2+!5;b:.[;;:;]/[b;(c;d:9&((`r`d`l`u!({(0,x)+};{(x,0)+};{(0,-x)+};{(-x,0)+}))[h 0]h 1)c);".X"];c:d;e"Applied force : ",$w;e"Real force : ",$h 1];e"Par in ",($1+s)," shots!";}
```
Could definitely golf this more. Incrementing/decrementing the indices is what kills me and could probably be done much simpler.
(Slightly) more readable than the one liner:
```
golf:{[]
b:(10*!-_-(100)%10)_@[100#".";0,1?100;:;"XO"];
c:0 0;e:s:-1;
while["O"in,/b;
e@b;
e"Score : ",$s+:1;
h:"SI"$" "\:0:0;
h[1]:1|*(w:h 1)+1?-2+!5;
b:.[;;:;]/[b;(c;d:9&((`r`d`l`u!({(0,x)+};{(x,0)+};{(0,-x)+};{(-x,0)+}))[h 0]h 1)c);".X"];
c:d;
e"Applied force : ",$w;
e"Real force : ",$h 1];
e"Par in ",($1+s)," shots!";
}
```
.
```
k)golf[]
X.........
..........
..........
..........
.......O..
..........
..........
..........
..........
..........
Score : 0
d 4
Applied force : 4
Real force : 4
..........
..........
..........
..........
X......O..
..........
..........
..........
..........
..........
Score : 1
r 7
Applied force : 7
Real force : 5
..........
..........
..........
..........
.....X.O..
..........
..........
..........
..........
..........
Score : 2
r 2
Applied force : 2
Real force : 1
..........
..........
..........
..........
......XO..
..........
..........
..........
..........
..........
Score : 3
r 1
Applied force : 1
Real force : 1
Par in 4 shots!
```
[Answer]
# Scala, 605
Golfed:
```
import scala.util.Random;object G extends App{var b,h=(0,0);while(b==h)h =(Random.nextInt(10),Random.nextInt(10));var s=0;def f{for(y<- 0 to 9){for(x<- 0 to 9)print(if(b==(x,y))"X"else if(h==(x,y))"O"else ".");println};println("score : "+s)};f;while(b!=h){val i=readLine.split(" ");val x=i(1).toInt.ensuring(a=>a>0&&a<10)-1+Random.nextInt(3);b=i(0).toLowerCase match{case "d"=>(b._1,b._2+x) case "u"=>(b._1,b._2-x) case "r"=>(b._1+x,b._2) case "l"=>(b._1-x,b._2)};b=(b._1.min(9).max(0),b._2.min(9).max(0));s+=1;f;println("applied force : "+i(1));println("real force : "+x)};println("Par in "+s+" shots!")}
```
Just a straight-forwardly implemented ice-breaker. Input is read line-by-line from stdin and power lower then 1 or higher then 9 will result in an `AssertionError` to comply with the specs.
I am pretty sure there are shorter programs, but let's see how far we get ;-)
Ungolfed:
```
import scala.util.Random
object Golf extends App {
var b, h = (0, 0)
while (b == h) h = (Random.nextInt(10), Random.nextInt(10))
var s = 0
def field {
for (y <- 0 to 9) {
for (x <- 0 to 9)
print(if (b ==(x, y)) "X" else if (h ==(x, y)) "O" else ".")
println
}
println("score : " + s)
}
field
while (b != h) {
val i = readLine.split(" ")
val x = i(1).toInt.ensuring(a => a > 0 && a < 10) - 1 + Random.nextInt(3)
b = i(0).toLowerCase match {
case "d" => (b._1, b._2 + x)
case "u" => (b._1, b._2 - x)
case "r" => (b._1 + x, b._2)
case "l" => (b._1 - x, b._2)
}
b = (b._1.min(9).max(0), b._2.min(9).max(0))
s += 1
field
println("applied force : " + i(1))
println("real force : " + x)
}
println("Par in " + s + " shots!")
}
```
Random example run:
>
>
> ```
> X......O..
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 0
>
> ```
>
> r 8
>
>
>
> ```
> .......OX.
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 1
> applied force : 8
> real force : 8
>
> ```
>
> l 1
>
>
>
> ```
> .......OX.
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 2
> applied force : 1
> real force : 0
>
> ```
>
> l 1
>
>
>
> ```
> .......X..
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 3
> applied force : 1
> real force : 1
> Par in 3 shots!
>
> ```
>
>
[Answer]
## Julia, 427
This is pretty straightforward on the whole. Julia isn't really designed to deal with I/O very heavily, as she's intended for large-scale scientific computation. But for our limited purposes here, she obliges by accepting some STDIO and playing a little game of golf with us.
*Edit: charged myself two additional characters because I had omitted the spaces after the colon for applied force and real force.*
```
a=fill(".",10,10)
x,y,s,b,c=1,1,0,iceil(10rand()),iceil(10rand())
a[x,y],a[b,c]="X","O"
while(x,y)!=(b,c)
print(a)
m=readline(STDIN)
d,f=m[1],m[2]
o=(d in"Ul"?-1:d in "Dr"?1:0)
g=clamp(round((f-48)+4rand()-2),1,9)*o
a[x,y]="."
x,y=(d in "UD"?clamp(x+g,1,10):x),(d in "lr"?clamp(y+g,1,10):y)
a[x,y]="X"
s+=1
print("score : ",s,"\napplied force : ",f,"\nreal force : ",abs(g),"\n")
end
print(a,"\nPar in ",s," shots!")
```
Here's a sample game, in which the final putt becomes an increasingly trying situation for our golfer.
(Note that occasionally our Ints get converted to Floats on the fly...ah, the vagaries of dynamic typing.)
```
X . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> r5
score : 1
applied force : 5
real force : 7.0
. . . . . . . X . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D3
score : 2
applied force : 3
real force : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . X . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> l3
score : 3
applied force : 3
real force : 3.0
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D1
score : 4
applied force : 1
real force : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . X . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> U1
score : 5
applied force : 1
real force : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D1
score : 6
applied force : 1
real force : 1
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
Par in 6 shots!
```
[Answer]
# PHP - 563
```
<?php
$b=[0,0];do{$h=[rand(0,9),rand(0, 9)];}while(!($h[0]|$h[1]));
$s=0;function o(){global$b,$h,$s;for($y=0;$y<10;$y++){for($x=0;$x<10;$x++){$p=[$y,$x];if($p==$b)echo'X';elseif($p==$h)echo'O';else echo '.';}echo "\n";}echo "score : $s
";}o();while($h!=$b){list($d,$p)=explode(' ',fread(STDIN,9));$P=max(1,min(9,$p+rand(-2,2)));switch($d){case'u':$b[0]-=$P;break;case'd':$b[0]+=$P;break;case'l':$b[1]-=$P;break;case'r':$b[1]+=$P;break;}$b=[max(0,min(9,$b[0])),max(0,min(9,$b[1]))];$s++;o();echo "applied force : ${p}real force : $P
";}echo "Par in $s shots!";
```

```
X.........
......O...
..........
..........
..........
..........
..........
..........
..........
..........
score : 0
d 1
..........
X.....O...
..........
..........
..........
..........
..........
..........
..........
..........
score : 1
applied force : 1
real force : 1
r 5
..........
......X...
..........
..........
..........
..........
..........
..........
..........
..........
score : 2
applied force : 5
real force : 6
Par in 2 shots!
```
Ungolfed:
```
<?php
$ball = [0,0];
do {
$hole = [ rand(0,9), rand(0, 9) ];
}while(!($hole[0]|$hole[1]));
$score = 0;
function out() {
global $ball, $hole, $score;
for($y=0;$y<10;$y++) {
for($x=0;$x<10;$x++) {
$p=[$y,$x];
if($p==$ball)echo'X';
elseif($p==$hole)echo'O';
else echo '.';
}
echo "\n";
}
echo "score : $score
";
}
out();
while($hole!=$ball) {
list($direction, $power) = explode(' ',fread(STDIN,10));
$rPower=$power+rand(-2,2);
switch($direction) {
case 'u':$ball[0]-=$rPower;break;
case 'd':$ball[0]+=$rPower;break;
case 'l':$ball[1]-=$rPower;break;
case 'r':$ball[1]+=$rPower;break;
}
$ball[0]=max(0,min(9,$ball[0]));
$ball[1]=max(0,min(9,$ball[1]));
$score++;
out();
echo "applied force : ${power}real force : $rPower
";
}
echo "Par in $score shots!";
```
] |
[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/12499/edit).
Closed 5 years ago.
[Improve this question](/posts/12499/edit)
So there was a ["please do my homework question" on StackOverflow](https://stackoverflow.com/questions/18709248/i-dont-understand-loops-in-python?noredirect=1#comment27566575_18709248) that lead to an idea. As everyone knows loops are quite expensive, in some places they can get as high as $12.99 an iterations, so to save money there shouldn't be any loops.
So, [lets do the homework](http://eecs.wsu.edu/~slong/cpts111/labs/lab3.pdf), but in the least intuitive way.
>
> Write a program that decides, among competing candidate pizzas, which is the
> best deal, in the sense of the smallest cost per unit area. Pizzas come in three shapes:
> round, square, and oval (elliptical). The area of an oval is `pi*ab/4`, where:
> `a` and `b` are the longer and shorter dimensions of the oval.
>
>
>
~~The rest of the specifications are in the linked PDF, which I can add in if needed. The input and output should conform to the assignment.~~
As per breadboxes suggestion the I/O has changed a bit to be more golfy.
* Your program must accept input for each pizza (lower case is a literal, uppercase is an argument):
+ **In all of the below**: `C` is the cost for that pizza in drachma (a float), and all units of length are in attoparsecs (~3cm).
+ `C s L` - a *square* pizza, with a size length L
+ `C r D` - a *round* pizza, with **diameter D**
+ `C o L S` - an *oval* pizza, with long side L and short side R, all ovals have an area of `pi*L*S/4` (for some reason).
+ An empty string denotes that there are no more pizzas.
* For each pizza, print out the area in attoparsecs, a literal `@` and the cost in Drachma per square attoparsecs (just numbers, units not required).
* After the user indicates there are no more pizzas, print the index of cheapest pizza (starting at 1).
* Pi may be approximated to 3.1415
An example run would be (`>` indicates input, `<` is output, but these don't need to be printed to screen):
```
> 13.59 r 14.2
< 158.37 @ 0.086
> 14.04 s 12.3
< 151.29 @ 0.093
> 12.39 o 14.1 8.3
< 91.92 @ 0.135
>
< 1
```
Spaces are optional in output, but the `@` symbol must be in the output of the pizza
**However, you can't use any *traditional* loops.** Recursion, `goto`s or list comprehension are all fine, but any thing that is syntactically a loop like a `for`, `while` or `do ... while` are all strictly forbidden.
**Shortest code wins.**
[Answer]
# HTML/JavaScript, 160 bytes
(linebreaks/indentation only added here do prevent scrolling)
```
<input onchange='window.n++||(n=1,L=1e9);s=this.value.split(" ");d=s[2];
a=[5.5/7*d*(s[3]||d),d*d][1*(s[1]=="s")];c=s[0]/a;alert(a!=a?m:a+"@"+c);
L<c||(L=c,m=n)'>
```
The input is a text box (press Enter to submit); the output is an alert box.
A few caveats (or cheats, if you will):
* Pi/4 is 5.5/7
* in some cases, it assumes that the pizzas have non-zero areas
* it's not possible to enter the same pizza twice in a row (because that won't trigger a `change` event)
* note that defocusing the input also counts as "enter"
* assumes that at least one pizza costs less than a billion Drachmas per square attoparsecs
* no fault tolerance for the input whatsoever
* you could argue that it's not qualified because it uses the browser's event loop
[Answer]
EDIT: Should note that I wrote this in response to prompting in the original stackoverflow question's comments. So it attempts to exactly follow the homework assignment (which was supposed to be done in Python and produce specified output). As such, it does not follow the updated golf-like rules.
So its absolutely not the shortest (repeats a lot of code), but it doesn't do any loops and it does some stupid things
```
def pizza(list,n):
n = n + 1
print 'Pizza Number ' + str(n) + ':'
shape = raw_input('Pizza shape (round, square, oval):')
if shape == 'oval':
longer = float(raw_input('Pizza longer dimension:'))
shorter = float(raw_input('Pizza shorter dimension:'))
price = float(raw_input('Pizza price:'))
area = (3.1415 * longer * shorter)/4
print 'Pizza area is %.2f square inches' % area
cost = price/area
print 'Cost per square inch is $%.2f' % cost
listing = '%d (OVAL %.2f x %.2f)' % (n,longer,shorter)
elif shape == 'square':
side = float(raw_input('Pizza side length:'))
price = float(raw_input('Pizza price:'))
area = side**2
print 'Pizza area is %.2f square inches' % area
cost = price/area
print 'Cost per square inch is $%.2f' % cost
listing = '%d (SQUARE %.2f x %.2f)' % (n,side,side)
else:
shape = 'round'
diameter = float(raw_input('Pizza diameter:'))
price = float(raw_input('Pizza price:'))
area = 3.1415 * (diameter / 2)**2
print 'Pizza area is %.2f square inches' % area
cost = price/area
print 'Cost per square inch is $%.3f' % cost
listing = '%d (ROUND %.2f)' % (n,diameter)
list[listing]=cost
another = raw_input('Enter Another? (Y/N):')
if another == 'Y':
pizza(list,n)
return list
else:
return list
dict=pizza({},0)
print 'The best deal is pizza number ' + min(dict, key=dict.get)
```
-Validates shape entry by assuming you want round if you enter anything else.
-Uses 3.1415 to avoid importing a library
-Assumes you are done if you enter anything besides 'Y'
-Every pizza is stored as a unique dictionary key.
Other than the things I intentionally did in a stupid way or to avoid a traditional loop, I'm open to any criticisms as I am not an accomplished python programmer.
[Answer]
## Python 167 bytes
```
def p():
try:return[eval("{2}*dict(s={2},r={2}*.7854,o={3}*.7854)['{1}']/{0}".format(*(raw_input()+' 1').split()))]+p()
except:return[]
v=p()
print v.index(max(v))+1
```
Using the constant *0.7854* to approximate *π/4*.
Sample usage:
```
$ more in.dat
13.59 r 14.2
14.04 s 12.3
12.39 o 14.1 8.3
$ python homework-pizza.py < in.dat
1
```
[Answer]
# Python - 251
Definitely not the shortest, but a good indication of whats required.
```
def p():
i = raw_input().split(' ')
if['']==i:return
f=float;C=f(i.pop(0));S=i.pop(0);P=3.1416;a=f(i[0])
if's'==S:A=a**2
elif'r'==S:A=P*(a/2)**2
elif'o'==S:A=P*a*f(i[1])/4
c=C/A;print A,'@',c
return[c,p()]
P=p()[:-1];print P,P.index(min(P))+1
```
[Answer]
# Ruby, ~~128~~ ~~132~~ 141 characters
```
b,j,i=1/0.0,1
$<.map{|s|j+=1
c,s,x,y=[*z=s.split,0].map &:to_f
b,i=c,j if b>c
p"#{a={?s=>x*x,?r=>x*x*=0.7854,?o=>x*y}[z[1]]}@#{c/a}"}
p"#{i}"
```
Borrowed `0.7854` from Primo. It's more precise than `3.1415/4` anyways.
User indicates there are no more pizzas by closing the STDIN stream. Yes, CTRL+D works in the jRuby interactive console. Yes, you have to restart the console to reopen the stream.
---
Cool facts about Ruby:
Destructuring assignment: you can assign an array to a list of variables. If you try to pass a non-array, it will be converted to an array first. In case of non-array-likes, that's a single-element array containing that element. If the array is too short, extra variables are set to `nil`. If the array is too long, some elements are discarded. Here we assign `nil` to `i` for scoping reasons only.
Ruby's selling points are iterators and methods with callbacks in general. To be enumerable, all you have to do is to implement `each` and inherit the right methods. This challenge forbids traditional loops, but it allows array comprehensions. STDIN is an input stream, and as such it is enumerable. As a bonus, input stream comprehension sets the globals `$_` (last line) and `$.` (line number) for us. Line 3 demonstrates the pretzel colon operator which constructs a block for the iterator.
Some find modifiers (`do_something until it_is_done`) confusing. I like them. Be careful that the order of evaluation (and of side-effects) is reversed, however. String interpolation - if overdone (like here) - can get messy at times (like here), and syntax highlighters can choke on nested interpolation (or give up completely, like here). Literal dereference. Just write a literal, and read from it immediately. Any decent language can do that (I owe an apology to PHP 5.3 at this point).
Of course, subexpression caching. As soon as an expression is long enough long or occurs frequently enough, stuff its value into a variable. Ruby's assignment has a low priority from the right, but high priority from the left. Thus, `a*b=c*d` assigns `c*d` to `b`. Also, carefully rearranging computation can let us alias variables. While normally a horrible thing, it can save characters when golfing because it lets one (ab)use the compound assignment operators. Unfortunately, it only works with operators.
] |
[Question]
[
Your task is to build a function in any language that takes a message `m`, an encryption `e`, and a modulus `k` (all positive integers), and takes `m` to the power of `e` modulo `k`. Your solution must not be a theoretical one, but one that would work on a reasonable computer such as your own, for RSA keys of currently used sizes such as 2048 bits.
Shortest code wins.
[Answer]
# Python – 5
Python 3 built-in function pow have third parameter. So Python 3 already have built-in RSA encoder
```
r=pow
```
[Answer]
Here's my first attempt at actually golfing something here:
# Python – ~~69~~ ~~61~~ 55
```
r=lambda m,e,k:1 if e==0 else m**(e%2)*r(m*m%k,e/2,k)%k
```
This is a simple exponentiation by squaring algorithm.
---
**02/15 13:17 – 61:** Used lambda notation.
**02/22 15:44 – 55:** Removed some brackets as per grc's suggestions.
[Answer]
## java (83 chars)
if input is of BigInteger type:
```
public BigInteger r(BigInteger m,BigInteger e,BigInteger k){return m.modPow(e,k);}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
!¡o%⁰*³
```
[Try it online!](https://tio.run/##HZK5DRVRDEVrISAh8vXujpAICBAFUAodINEBpdDIcIbk/xmN312O3@fv3748z4c/P79@/Pvj16c/v5/nkUdWz57s0USUZ7tmZb2Wd9Xl69GpsPch5xR9mZLixrrKI6azr@@u50pbIau4G@8rV9S@f5e7M8uPTInDhlIb4Z5TupAquysWyXHz8WWs67y7BxV3PmZkxJ7vZqcVtp602JxsFM8vjvCNgM@tyOYeanHG8FD5jPh@XfNanPsOI2sYBT40NrMML@TNw8oGSm9Ky9osMpFRw6Q6tFqyevVWCiZgcE6QpGkKzOJ1pyizCtcCaYTpf60C7r1g0FcSLQC8zKMZEPcFiLzGqh2LYhNURR8yeAA2DNtXjFW2WbMi9jQ5a0Sdtq3WAYxiHTxSX@ms5QXCgm6je1k4AdL/Q2QFRBJcOpg6bgDXgfX4i4/epDPKzDmta3nPJR/m/ioCDsrLYRu0r94SzRb27uHWxPwD "Husk – Try It Online")
Function that takes arguments: arg1=m (message), arg2=k (key/modulus), arg3=e (exponent/encryption).
Encoding takes about 10 seconds on [Try it online!] with a message of `12345678910`, a 2048-bit key/modulus of `17335246217810680499565282364130282347913694411139706552337646969996795185310539972695213589521948877888710148108314183322475193115466538523720272848165926667358225384343389288464059692412384746831929390686202279817642231618920311152771862965772849228722380926373552800043250590230507345247504584516585217552163181827225685419709962073929610117852078754818132187957128758451536498778247147713136878727238232838512570562685513074673965992921930197584545660069134797478016576085619884280636191861425890311213983668804147423192923778212236303196414996652277121672303217925415867248268691221399027188630076689585126618899`, and exponent/encryption of `65537`.
Decoding is significantly longer when (as is usual) the decryption exponent d is much larger than the encryption exponent e. But we can check that it works using small values: m=`123`, k=`257` and e=`7` (for which the decryption exponent d=`55`):
[Try encoding](https://tio.run/##yygtzv7/X/HQwnzVR40btA5t/v//v6GR8X8jU/P/5gA)
[Try decoding](https://tio.run/##yygtzv7/X/HQwnzVR40btA5t/v//v7HpfyNT8/@mpgA)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles)
```
=_`.@%*_
```
```
=_`.@%*_ # full program
=_`.@%*_$@ # with implicit args added
`. # repeatedly apply (while results are unique)
@ # starting with arg2:
*_$ # multiply arg2 by result-so-far
% @ # and modulo by arg1
=_ # finally, return result at index given by arg3
```
Full program that takes arguments: arg1=k (key/modulus), arg2=m (message), arg3=e (exponent/encryption).
Encoding is fast (screenshot below shows a message of 12345678910, a 2048-bit key/modulus, and exponent/encryption of 65537).
[](https://i.stack.imgur.com/pcrvI.png)
Decoding is significantly longer when (as is usual) the decryption exponent d is much larger than the encryption exponent e. But we can check that it works using small values: m=123, k=257 and e=7 (for which the decryption exponent d=55).
[](https://i.stack.imgur.com/yY7m4.png)
] |
[Question]
[
Arturo is a bytecode-compiled/interpreted, garbage-collected general-purpose language filling a role similar to JavaScript, Python and Ruby. It is centered around the concept of blocks, which hold code just as easily as data. It uses fixed-arity prefix syntax and emphasizes the procedural and functional paradigms.
What general tips do you have for golfing in Arturo? I'm looking for ideas that are specific to Arturo (e.g. "remove comments" is not an answer). Please post one tip per answer.
* [Official website](https://arturo-lang.io/)
* [Documentation](https://arturo-lang.io/documentation/)
* [Playground](https://arturo-lang.io/playground) (online Arturo interpreter)
[Answer]
# Converting integers to strings and vice versa
Instead of
```
to :integer s
```
use Arturo's eval function:
```
do s
```
Instead of
```
to :string n
```
use string interpolation:
```
~"|n|"
```
[Answer]
# Don't use .with:
All [iterators](https://arturo-lang.io/documentation/library/iterators/) in Arturo can take a `.with:` [attribute label](https://arturo-lang.io/documentation/language/#attributeLabel) that lets you assign the index of the iteration to a variable. For instance:
```
loop.with:'i[33 95 7]'n[print~"Index: |i|, Value: |n|"]
```
```
Index: 0, Value: 33
Index: 1, Value: 95
Index: 2, Value: 7
```
However, you can always save a byte by declaring your own index variable and incrementing it manually:
```
i:0loop[33 95 7]'n[print~"Index: |i|, Value: |n|"'i+1]
```
And in the best-case scenario, you don't need to use variables at all. Abuse Arturo's (hidden?) stack instead:
```
0loop[33 95 7]'n[print~"Index: |<=|, Value: |n|"1+]
```
Here, we place 0 on top of the stack, duplicate it with `<=`, and increment it with `1+`.
[Answer]
# Shortening ranges
Consider the following function that finds the sum of squares from 1 to n.
```
$->n[∑map 1..n'x->x^2]
```
You might think this is as short as we can go, since removing the space causes `map1` which is a valid, albeit undefined word name. However, we can remove the space by realizing the symbol `..` (range) can go in the prefix position!
```
$->n[∑map..1n'x->x^2]
```
Since words can't start with numbers, `1n` gets parsed as `[1 n]` instead of `[1n]`. So `..1n` is equivalent to `1..n` and `range 1 n`. But is this really as short as we can go? No, it isn't! In Arturo, you may iterate over numbers themselves with the meaning `1..n`. So
```
$->n[∑map n'x->x^2]
```
is equivalent to the above. Finally, we can shorten this even more by using fat-arrow notation:
```
$=>[∑map&'x->x^2]
```
This causes `&` to become the input parameter. Since it's a symbol instead of the word `n`, it can butt up against its surroundings no problem.
[Answer]
# Consider outputting strings via the clipboard
`clip s` sets the clipboard to string `s`. As long as you're outputting a string all at once, this can save a byte over `print s` and function return (which are tied in length). [Outputting via the clipboard is allowed by default](https://codegolf.meta.stackexchange.com/a/11661/97916).
For example,
```
clip~"It's |now\year| already, folks, go home." ; clipboard
print~"It's |now\year| already, folks, go home." ; stdout
$=>[~"It's |now\year| already, folks, go home."] ; function return
```
] |
[Question]
[
Write a program that takes an undirected graph and finds the minimum cut, i.e., the set of edges that, if removed, would disconnect the graph into two or more connected components. The program should have a time complexity of \$O(n^2m)\$, where n is the number of vertices and m is the number of edges in the graph.
One algorithm to solve this problem is the Karger's algorithm, which is a randomized algorithm that finds the minimum cut with high probability. Here is a high-level overview of the algorithm:
1. Initialize a "contracted graph" that is a copy of the original graph.
2. While the contracted graph has more than 2 vertices:
1. Choose an edge at random from the contracted graph.
2. Contract the two vertices connected by the chosen edge into a single vertex,
3. removing the chosen edge.
4. Repeat steps 1 and 2 until only 2 vertices remain.
3. The minimum cut is the set of edges that connect the two remaining vertices in the contracted graph.
This algorithm works by repeatedly contracting edges in the graph until only 2 vertices remain. The intuition behind the algorithm is that, as edges are contracted, the size of the cut decreases until there are only 2 vertices left, at which point the cut is the set of edges that connect those 2 vertices.
Karger's algorithm has a time complexity of \$O(n^2m)\$, which makes it relatively efficient for small to medium-sized graphs. However, it may not be practical for very large graphs.
[Answer]
# [Python](https://www.python.org), 433 bytes,
```
import random
def karger_algorithm(graph):
while len(graph) > 2:
# Choose an edge at random
u, v = random.choice(list(graph.items()))
w = random.choice(v)
# Contract the two vertices
graph[u].extend(graph[w])
for node in graph[w]:
graph[node].remove(w)
graph[node].append(u)
del graph[w]
# Return the size of the cut
return len(list(graph.values())[0])
# Example usage
graph = {0: [1, 2], 1: [0, 2], 2: [0, 1, 3], 3: [2]}
min_cut = karger_algorithm(graph)
print(min_cut)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZG_boMwEMbVlac4KQuWUkTIUkVql75BV4QiCw5sFWxkztA_6pN0ydJuHfo47dPU4AQiVfHi830_33c-v3-2zyS0OnzJptWGwHBV6ObDUnl983v1XWAJj9xUaPa8rrSRJJqwMrwVbBeAW4OQNUKN6piFO0i8Mq4V3AutOwSuAIvK7SeHGbFr6OH2mI1yoWWOYS078gUjSdh0IWNsvjH8w3sWnFtqRYbnBCQQaNDQoyGHdTMzVU5tFuEToSq8Uzpki0epDShdIEgFJ3V51lJjZLLIYKN7DAd2keBtOxrZhSiwniv77lfwgGSNmvru5AuCLqc4tzQBxsvjsM8G1PPa4jihNHYP8D_3g5PmBvUa7yDdrCHJ1rBxYezDxIdO2LrT1p2S7C1opNo7M3ftwp8HrZGKwiPHvNnh4Pc_)
---
This implementation uses a dictionary to represent the graph, where the keys are the vertices and the values are lists of adjacent vertices. The algorithm repeatedly chooses an edge at random, contracts the two vertices connected by the edge, and updates the adjacency lists accordingly. The function returns the size of the cut, which is the number of edges that were removed.
Note that this implementation is not optimized for performance and may be slow for large graphs. There are more efficient ways to implement Karger's algorithm, such as using Union-Find data structures to keep track of connected components.
[Answer]
A simple implementation of Karger's algorithm in Python using union-find.
```
import random
def min_cut(graph):
edges = [(u, v) for u, l in graph.items() for v in l if v > u]
parent = {u: u for u in graph}
def find(u):
v = parent[u]
while v != u:
w = parent[v]
parent[u] = w
u, v = v, w
return u
def union(u, v):
if random.randrange(2):
u, v = v, u
parent[u] = v
random.shuffle(edges)
n_components = len(graph)
if n_components < 2:
return None
if n_components > 2:
for (u, v) in edges:
fu, fv = find(u), find(v)
if fu != fv:
union(fu, fv)
n_components -= 1
if n_components == 2:
break
return [(u, v) for (u, v) in edges if find(u) != find(v)]
```
[Answer]
# [Rust](https://www.rust-lang.org/)
We can use Rust to implement [Karger's algorithm](https://en.wikipedia.org/wiki/Karger%27s_algorithm), one example is:
[run it on Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=93a71b616bc9b41e447bc675973045b5)
```
extern crate rand;
use rand::Rng;
use std::collections::HashMap;
use std::time::Instant;
fn karger_algorithm(graph: &mut HashMap<u32, Vec<u32>>) -> usize {
while graph.len() > 2 {
// 1. Randomly select an edge in a graph
let keys: Vec<_> = graph.keys().cloned().collect();
let u = rand::thread_rng().gen_range(0..keys.len());
let u_key = keys[u];
let v = rand::thread_rng().gen_range(0..graph[&u_key].len());
let w_key = graph[&u_key][v];
// 2. Contract the two vertices
// Add all the neighbors of w to the Adjacency List of u,
// Next, for all Adjacency Lists, w is replaced with u
// Finally, delete the Adjacency List of w
let w_key_values = graph[&w_key].clone();
graph.get_mut(&u_key).unwrap().extend(w_key_values.clone());
for node in w_key_values.iter() {
let node_list = graph.get_mut(node).unwrap();
node_list.retain(|x| *x != w_key);
node_list.push(u_key);
}
graph.remove(&w_key);
}
// 3. Return the size of the cut
// Finally, there are two remaining nodes, with some edges connected between them.
// Returns the number of edges
graph.values().next().unwrap().len()
}
fn karger_algorithm_montecarlo(graph: &mut HashMap<u32, Vec<u32>>, iterations: usize) -> usize {
let mut min_cut = usize::max_value();
for _ in 0..iterations {
let mut graph_copy = graph.clone();
let cut = karger_algorithm(&mut graph_copy);
if cut < min_cut {
min_cut = cut;
}
}
min_cut
}
fn main() {
let mut graph: HashMap<u32, Vec<u32>> = HashMap::new();
graph.insert(0, vec![1, 2]);
graph.insert(1, vec![0, 2]);
graph.insert(2, vec![0, 1, 3]);
graph.insert(3, vec![2]);
let start = Instant::now();
let min_cut = karger_algorithm_montecarlo(&mut graph, 500);
let duration = start.elapsed();
println!("Minimum cut: {}", min_cut);
println!("Time elapsed: {:?}", duration);
}
```
Run the program with `iterations=500` and find that the minimum cut can be \$1\$
```
-----Standard Error-----
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 0.88s
Running `target/debug/playground`
-----Standard Output-----
Minimum cut: 1
Time elapsed: 8.640442ms
```
Its minimum cut is \$1\$, we can use Mathematica to verify that.
[](https://i.stack.imgur.com/8fTuz.png)
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Santa and the Elves are secretly preparing for a new tourist train service, called "[North Pole Railroads](https://codegolf.stackexchange.com/q/255943/78410)". The train will travel through various sightseeing spots near the North Pole.
As a part of this project, they want to know how many seats they will need. They already have the list of travels for each passenger (given as "from station X to station Y"), which is thanks to the same magic that lets Santa know which children are nice. Each station is numbered from 1, starting from the North Pole.
The Elves are arguing over how to determine the number of seats. Another option is to have just enough seats to allow all passengers to choose their seats. Note that they will have to consider all possible order of reservations. Two passengers with strictly overlapping travel cannot share a seat (e.g. one is `(1, 3)` and the other is `(2, 4)`), but a travel that ends at X is not overlapping with another that starts at X.
## Task
Given the list of `X, Y` pairs that represent the travel of each passenger, output how many seats will be needed for North Pole Railroads.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
(1, 2), (2, 3), (1, 3), (3, 4) -> 3
1---2---3---4
AAA DDD
BBB
CCCCCCC
Explanation: if A takes seat 1 and B takes seat 2, C needs the third seat
(1, 2), (1, 3), (2, 3), (3, 4) -> 3
Explanation: the order in the input does not matter
(1, 3), (1, 3), (3, 6), (3, 6) -> 2
(1, 5), (2, 8), (6, 9), (5, 7), (4, 6) -> 5
Explanation: B's travel overlaps with the other 4, so if ACDE gets to book first,
B will need the 5th seat
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
<>ƭ"Ạ¥þUSṀ
```
[Try it online!](https://tio.run/##y0rNyan8/9/G7thapYe7FhxaenhfaPDDnQ3///@P1jDUUTDV1FHQMNJRsADRZjoKliDaVEfBHESb6CiYacYCAA "Jelly – Try It Online")
The goal is to find the passenger that whose journey overlaps with the most other passengers. The result is that number +1.
```
<>ƭ"Ạ¥þUSṀ
þU - outer product with itself with reversed elements
<>ƭ"Ạ¥ - takes [a, b], [c, d] and returns a<c && b>d
S - sum rows
Ṁ - maximum
```
[Answer]
# [R](https://www.r-project.org), 44 bytes
```
\(a,b)max(rowSums((d=sapply(a,`<`,b))&t(d)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGy4tTEkmLbpaUlaboWN3ViNBJ1kjRzEys0ivLLg0tzizU0UmyLEwsKciqBMgk2CUBZTbUSjRRNTU2ontWJtskahjpGOoY6xppcSUCOkY4xEJpocoHNBpuooKxgzMUFUQlSS6xKY5hKkDozHTM0lUYwlUZASVOQQSC1pjoWOpY65hiqTbkgTl6wAEIDAA)
Same approach as [AndrovT](https://codegolf.stackexchange.com/a/255993/95126) (upvote that!), combined with the observation that we can just calculate a single matrix of start-greater-than-stops, and AND it with itself after transposing to get the matrix of all passenger overlaps.
Calculating the matrix is easy in R by taking input as two lists, one of starts and one of stops, and using a vectorized greater-than comparison.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
x=>Math.max(...x.map(v=>x.map(w=>n+=w.r>v.l&v.r>w.l,n=0)|n))
```
[Try it online!](https://tio.run/##JczLCsIwEEDRfb8iK5nBcVCxPpDJuhu/QFyE2vogJqUtaUH99hjq6p7VfZpgurJ9NP3C@WsVa4mj6JPp7/wyIzDzmNBAEP3HINrNZeBWB7azkDqwJSdL/DjEeMwKAUstioZ36hez0rvO24qtv0EN5wJWpHIkVcCa1H7CltRhQk5qN2FDaouXNIw/ "JavaScript (Node.js) – Try It Online")
Same approach as AndrovT
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
UMθ…⌊ι⌈ιI⌈EθLΦθ⁻ι⁻ιλ
```
[Try it online!](https://tio.run/##TU27CsMwENv7FR7P4A55bBkDnWooXUOGIzXJgX1pHKf07x0bXKgWCQlJ04J@WtHGqPHdr84hv2BT4ok8G9DE5A4HJJXQ@C1ayu7y8MQBetwD/II0kJt3w3NY4EY2GJ@NNHLsQH/CyoIuxmGASok6HUCtRJO5Ktwo0cpxjNePPQE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Assumes that @AndrovT's interpretation of the problem is correct.
```
UMθ…⌊ι⌈ι
```
Turn each starting and ending pair into a range.
```
I⌈EθLΦθ⁻ι⁻ιλ
```
For each passenger, do double set difference to see whether how many ranges intersect with other passengers and output the maximum.
[Answer]
# [Scala](http://www.scala-lang.org/), 72 bytes
Modified from [@AndrovT's answer](https://codegolf.stackexchange.com/a/255993/110802)
---
Golfed version, [try it online!](https://tio.run/##TY/BasMwEETv/Yo5BQmEoCVJW4MNPQbSU@gp9LBV7aCiKEHa2A1G3@7Kpk19WDRvd5bRRkOOhtPHV20Yr2Q9@jvgs25wzCAoHGKBlxDout9xsP7wLgu8ecsoJyfQkoP1XIcsYu5ubWSx@W2Ie4WVVLjxg8LTnNcKz3NeKTzOeamwlnIKOud4dl404hY3TVIuQ7GGcRTj/6orRq0QplcO41GN4GL84P7Plc/JsuxZH@nct2XF2pwunvuurDodqla7xaLNotMupWz6TkMafgA)
```
def f(t:List[Interval]):Int={t.map{v=>t.count{w=>w.r>v.l&&v.r>w.l}}.max}
```
Ungolfed version
```
object Main {
def main(args: Array[String]): Unit = {
val intervals = List(Interval(1, 5), Interval(2, 8), Interval(6, 9), Interval(5, 7), Interval(4, 6))
println(maxOverlap(intervals))
}
case class Interval(l: Int, r: Int)
def maxOverlap(intervals: List[Interval]): Int = {
intervals.map { v =>
intervals.count { w =>
w.r > v.l && v.r > w.l
}
}.max
}
}
```
] |
[Question]
[
I wrote this function in 48 bytes and I wonder, is there any way to write this code 2 characters shorter?
```
p=lambda n,c:(n*c)[:n//2]+(n*c)[:n//2+n%2][::-1]
```
The point of the function is to create a palindrome of length `n` by using all the characters from the string `c`. Example: `n = 3`, `c = 'ab'`. Result is `'aba'`.
Is there something I am missing that can be shortened or is there no other way to make it shorter? Thanks!
[Answer]
In general, slicing twice usually results in extraneous code.
Here, you use `[:n//2+n%2][::-1]`. The first part means "get from `0` to `n//2+n%2`", left-inclusive right-exclusive. The second part reverses it. Thus, what you are *actually* trying to do is get from `n//2+n%2-1` to `-1`, stepping by `-1`, left-inclusive right-exclusive. Thus, you can do `[n//2-n%2-1:-1:-1]`. The stop argument is excessive there.
```
p=lambda n,c:(n*c)[:n//2]+(n*c)[n//2+n%2-1::-1]
```
Then, since `n%2-1` gives `0` for odd numbers and `-1` for even numbers, we can also get `0` for odd numbers and `1` for even numbers via `~n%2`, and then subtract that:
```
p=lambda n,c:(n*c)[:n//2]+(n*c)[n//2-~n%2::-1]
```
(The following is found by dingledooper)
Finally, we can optimize that part even further, as what we are asking for is `n//2-1` for even numbers and `n//2` for odd numbers. Notice that if we subtract one, then `(n-1)//2` solves this. For integers, `n-1` is equivalent to `~-n` (remember that `~` is complement, and `~n == -1 - n` so `~-n == -1 + n == n - 1`). Therefore, we can shorten that part down to `[~-n//2::-1]`.
Remember the `~-` trick for decrementing (as well as `-~` for incrementing) as it saves 2 bytes for `(n+1)` and `(n-1)` where brackets would otherwise be needed, since unary operators have very high precedence.
# [Python 3](https://docs.python.org/3/), 43 bytes
```
p=lambda n,c:(n*c)[:n//2]+(n*c)[~-n//2::-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8A2JzE3KSVRIU8n2UojTytZM9oqT1/fKFYbwqnTBfGsrHQNY/8XFGXmlWgUaBga6CgoJSYpaWpywYWMwUIpicVpKcjipkDhlOL0xPSUtHSg@H8A "Python 3 – Try It Online")
(Thanks to Jo King for spotting this one)
If you can use Python 3.8, inline assignment with the walrus operator saves a byte:
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 42 bytes
```
p=lambda n,c:(r:=n*c)[:n//2]+r[~-n//2::-1]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8A2JzE3KSVRIU8n2UqjyMo2TytZM9oqT1/fKFa7KLpOF8SystI1jP1fUJSZV6JRoGFooKOglJikpKnJBRcyBgulJBanpSCLmwKFU4rTE9NT0tKB4v8B "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
This is a version of [this question](https://codegolf.stackexchange.com/questions/197524/average-number-of-strings-with-levenshtein-distance-up-to-3) which should not have such a straightforward solution and so should be more of an interesting coding challenge. It seems, for example, [very likely](https://math.stackexchange.com/questions/3498630/average-number-of-strings-with-edit-distance-at-most-4) there is no easy to find closed form solution, even though we have only increased the bound by one from the previous version. Having said that, you never know...
The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one. Given a binary string \$S\$ of length \$n\$, we are a interested in the number of different strings of length \$n\$ which have distance at most \$4\$ from \$S\$.
For example, if \$S = 0000\$ there are four strings with Levenshtein distance exactly \$3\$ from \$S\$, six with distance exactly \$2\$, four with distance exactly \$1\$ and exactly one with distance \$0\$. This makes a total of \$15\$ distinct strings with distance at most \$3\$ from the string \$0000\$. The only string with distance exactly \$4\$ is \$1111\$.
For this task the input is a value of \$n \geq 4\$. Your code must output the average number of binary strings of length \$n\$ which have Levenshtein distance at most \$4\$ from a uniform and randomly sampled string \$S\$. Your answer can be output in any standard way you choose but it must be exact.
# Examples
* n = 4. Average \$16\$.
* n = 5. Average 31 \$\frac{11}{16}\$.
* n = 6. Average 61 \$\frac{21}{32}\$.
* n = 7. Average 116 \$\frac{7}{8}\$.
* n = 8. Average 214 \$\frac{43}{128}\$.
* n = 9. Average 378 \$\frac{49}{246}\$.
* n = 10. Average 640 \$\frac{301}{512}\$.
* n = 11. Average 1042 \$\frac{1}{16}\$.
* n = 12. Average 1631 \$\frac{1345}{2048}\$.
* n = 13. Average 2466 \$\frac{3909}{4096}\$.
* n = 14. Average 3614 \$\frac{563}{8192}\$
# Score
Your score is the highest value of \$n\$ you can reach in less than a minute on my linux box. If two answers get the same value then the first posted (or amended) wins. The timing is for each value separately.
My CPU is an Intel(R) Xeon(R) CPU X5460.
[Answer]
# [GAP](https://www.gap-system.org)
So my [previous approach](https://codegolf.stackexchange.com/a/197543/56725) works indeed when we replace the definition of `nfa` with this:
```
nfa := Automaton("epsilon", 25, 5,
[[[1,6,7],[2,8,9],[3,10,11],4,5,[6,18],
[7,19],8,9,10,11,[8,22],[9,23],10,11,
0,0,18,19,22,23,0,0,0,0],
[[2,6,13],[3,8,15],[4,10,17],5,0,[8,18],
[13,21],10,15,0,17,[6,22],[15,25],8,17,
10,0,0,21,0,25,18,0,22,0],
[[2,12,7],[3,14,9],[4,16,11],5,0,[12,20],
[9,19],14,11,16,0,[14,24],[7,23],16,9,
0,11,20,0,24,0,0,19,0,23],
[[1,12,13],[2,14,15],[3,16,17],4,5,[14,20],
[15,21],16,17,0,0,[12,24],[13,25],14,15,
16,17,0,0,0,0,20,21,24,25],
[0,0,0,0,0,3,3,4,4,5,5,3,3,4,4,5,5,10,
11,16,17,10,11,16,17] ],
[1], [1..25] );
```
This automaton was constructed with a program that I have explained [here](https://math.stackexchange.com/a/3530045/338756).
The resulting DFA has 266 states.
We can again compute as much values as we like:
```
n = 16. Average = 7150 23011/32768.
n = 17. Average = 9714 60059/65536.
n = 18. Average = 12940 42919/131072.
n = 19. Average = 16935 3985/8192.
n = 20. Average = 21817 225447/524288.
n = 21. Average = 27711 716517/1048576.
n = 22. Average = 34752 552357/2097152.
n = 23. Average = 43081 714481/1048576.
n = 24. Average = 52850 7923401/8388608.
n = 25. Average = 64219 9352665/16777216.
n = 50. Average = 1508800 387601224486599/562949953421312.
n = 100. Average = 29267070 38719469213378154341013566355/
633825300114114700748351602688.
```
The eigenvalues of the matrix are \$4,2,1,0\$ and \$-1\$ as before and additionally two conjugate pairs of complex numbers: \$\pm i\$, and the third root of unity and its conjugate (which is also its square and its inverse).
Usually complex eigenvalues mean that the closed formula contains trigonometric functions, but since there were already terms corresponding to the eigenvector \$1\$ to compensate, I took the liberty to use the periodic functions \$ n \bmod 3\$ and \$ -n \bmod 3\$ to handle the third root of unity.
The imaginary unit does not contribute to the closed formula. Neither does \$4\$, because it comes from the sink state, which is not counted. It can be removed from the automaton, and the resulting matrix no longer has this eigenvalue. The eigenvalue \$-1\$ does contribute, even though it didn't in the distance 3 case.
The resulting closed formula, which is quite long, works for \$n\ge 5\$. (That's an effect of the \$0\$ eigenvalues.) Since the challenge asks for \$n\ge 4\$, the following code has a special case for small values.
# [Pari/GP](https://pari.math.u-bordeaux.fr/)
```
f(n)=if(n>4,168264301/345744-4115011/16464*n+19597/336*n^2-161/24*n^3+17/48*n^4+(-9188617/19208-268724/3087*n-4658/441*n^2+449/81*n^3-515/324*n^4+(-1)^n/72+(56188/194481-824/9261*n+4/3969*n^2)*(n%3)+(-1756/64827+94/27783*n-26/3969*n^2)*(-n%3))*2^-n,2^n)
```
[Try it online!](https://tio.run/##TZDBasQwDER/ZSkU7DhCkSzL8mH3UwK9bMlFDcv@fyr31MswDDNPoPPrdcD3eV3P5Pl@hD5kJTVWqRthldZFQIjaRoSkorJ4odFGx1p18Z2BlJAj3muhjmLhpCQYZKYR0ODNgNU6C9bN@uIg2gxFaO6LyECbtkKjhvWPNQmUd8fOJTUNVoBEjMACM1hjUII3dExIXpJ/1jxHvSmqGPcyBLl3q3GQ9X8VZjcvvIOvvHu@nj@v5HdZ27aer8PfyW8fN3iEzL/kfP0C "Pari/GP – Try It Online")
] |
[Question]
[
Below Python code generates memory leak.
**Challenge**: Fix the memory leak with minimal changes to the code as measured by Levenshtein distance to the original code. You may only change the code before `t` is initialised. When the `del t` line is removed the modified program should print `I'm still alive!` every second.
**PS**: I already know the answer (found it after several hours of debugging). This is not the programming help question! Hopefully this would be interesting to folks.
```
import threading, time
# this class takes callback and calls it every 1 sec
class MyTimer:
def __init__(self, callback):
self.callback = callback
self.th = threading.Thread(target=self.run,daemon=True)
self.th.start()
def run(self):
while(True):
self.callback()
time.sleep(1)
class TestMyTimer:
def __init__(self):
self.timer = MyTimer(self.is_alive)
def is_alive(self):
print("I'm still alive")
# test code for MyTimer
t = TestMyTimer()
del t
# just to be sure to collect all dead objects
import gc
gc.collect()
# if you are still seeing messages then we have memory leak!
time.sleep(60)
```
Here's [repl.it](https://repl.it/@sytelus/PythonMemoryLeak) to play with this code online.
[Answer]
Taking inspiration from the comments and from the question, just by adding 3 characters I "fixed" the memory leak.
Granted, I broke everything else at the same time
```
import threading, time
# this class takes callback and calls it every 1 sec
class MyTimer:
def __init__(self, callback):
self.callback = callback
self.th = threading.Thread(target=self.run,daemon=True)
self.th.start()
def run(self):
while(True):
self.callback()
time.sleep(1)
class TestMyTimer:
def __init__(self):
self.timer = MyTimer(self.is_alive)
def is_alive(self):
print("I'm still alive")
# test code for MyTimer
#t = TestMyTimer()
#del t
# just to be sure to collect all dead objects
import gc
#gc.collect()
# if you are still seeing messages then we have memory leak!
time.sleep(60)
```
Edit: The challenge has now been properly updated :)
[Answer]
```
import threading, time
# this class takes callback and calls it every 1 sec
class MyTimer:
def __init__(self, callback):
self.a = True
self.callback = callback
self.th = threading.Thread(target=self.run,daemon=True)
self.th.start()
def run(self):
while(True):
self.callback(self.a)
time.sleep(1)
class TestMyTimer:
def __init__(self):
self.timer = MyTimer(self.is_alive)
def is_alive(self, k):
print("I'm still alive")
if not k:
raise SystemExit()
# test code for MyTimer
t = TestMyTimer()
t.timer.a = 0
del t.timer, t
# just to be sure to collect all dead objects
import gc
gc.collect()
# if you are still seeing messages then we have memory leak!
time.sleep(60)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 2 bytes
```
import threading, time
# this class takes callback and calls it every 1 sec
class MyTimer:
def __init__(self, callback):
self.callback = callback
self.th = threading.Thread(target=self.run,daemon=True)
self.th.start()
def run(self):
while(True):
self.callback()
time.sleep(1);t
class TestMyTimer:
def __init__(self):
self.timer = MyTimer(self.is_alive)
def is_alive(self):
print("I'm still alive")
# test code for MyTimer
t = TestMyTimer()
del t
# just to be sure to collect all dead objects
import gc
gc.collect()
# if you are still seeing messages then we have memory leak!
time.sleep(6)
```
[Try it online!](https://tio.run/##fVK7bsMwDNz1FWw6VAYCA0GBDi3yAR26eTcUmbaVyJIh0Qn89S6tJM6jQDVR5N3xRLEfqfXufZpM1/tAQG1AVRnXrIFMh0K8cspE0FbFCKQOyLGydqf0AZSr0iWCIcAjhhE2EFGLM/pnLFgifArgU2ENZWmcobKUEW29XnSyM2I@cyFf9LcL5BFALZcWp3mRIkkqNEjbhAiDW1cKO@@2RRgwe@bnkdEks8UaE5KrOy@n1liUiX5L/jEps4faPLQ8WsRebrIvEpdRFBjp/3E8D2EWCvzMCythchNLZc0Rb76vmWeNPhhHcvX91kEkYy0k1CpLH8pmQPsKofbh2kAQN7uzye@q0ALNhP3ABPKwQ4hDwDnU3lrUxLKWfagK/G7P9ygue9Ro0ej8gpKpralh9AMoFjhbioj8fdBhjKrhvaIWHZwQWnVEznae98miOryIu6l@ZGKafgE "Python 3 – Try It Online")
Maybe not intended but I don't know a just intended solution
] |
[Question]
[
**This question already has answers here**:
[Print the N-bonacci sequence](/questions/70476/print-the-n-bonacci-sequence)
(44 answers)
Closed 5 years ago.
## How to
Given an integer `n` start with `n` ones (i.e. 4 -> `1 1 1 1`). Then sum up the
last `n` numbers, and repeat.
For `n = 4` this looks like this:
Start with `1 1 1 1`, sum up the last 4 numbers resulting in `1 1 1 1 4`, then
sum up the last 4 numbers resulting in `1 1 1 1 4 7`, then sum up the last 4 numbers resulting in `1 1 1 1 4 7 13` and so on.
## The task
Write a program or function that produces the first 30 numbers of this sequence given `n` as input (either as argument, stdin, command line argument, on the stack, ...)
The 30 terms for n = 4 are:
`1 1 1 1 4 7 13 25 49 94 181 349 673 1297 2500 4819 9289 17905 34513 66526 128233 247177 476449 918385 1770244 3412255 6577333 12678217 24438049 47105854`
The 30 terms for n = 5 are:
`1 1 1 1 1 5 9 17 33 65 129 253 497 977 1921 3777 7425 14597 28697 56417 110913 218049 428673 842749 1656801 3257185 6403457 12588865 24749057 48655365`
In case `n` is smaller than two or larger than 30 the behaviour can be undefined.
[Answer]
# JavaScript (ES6), 64 bytes
```
f=(n,i,a=[])=>i>29?a:f(n,-~i,[...a,(g=_=>n--&&a[--i]+g())()||1])
```
[Try it online!](https://tio.run/##VchBCsIwEAXQvQcp8zETUHShMPEgIchQmzBSErHiqnj16Na3fHd96zI@7fHi2m5T71moOnMqMUGChf3pouf8O/6Yi957dVTkKqEyD4NGZkvbQgBhXXcJfWx1afPk51Yo0wHY/M8R6F8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
Å1 30FDO¸«ć,
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKuhgrGBm4v/oR2HVh9p1/n/3xQA "05AB1E – Try It Online")
**Explanation**
```
Å1 # push a list of n 1s
30F # 30 times do:
D # duplicate
O # sum
¸« # append
ć, # extract and print the head
```
[Answer]
# [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 35 bytes
```
{x:30^recur(*tile(x,c(1)),sum@c,x)}
```
[Try it online!](https://tio.run/##DYvNCsIwEAbvfYqPnHZtBH/AQ6Hie4hCWROI1AaSLVZKnz3mMjADo@H1Kx5dX9alOx@eycmcaKdhdLRYoSOzzfPnJnbhrRh1WSFDdtk0KnXD/WRxeTQ@JnG0YujwTUHdOFHWRAOjhcH@WtHiHcNEvkZb1TBjQ5ygwuUP "Tidy – Try It Online")
## Explanation
```
{x:30^recur(*tile(x,c(1)),sum@c,x)}
{x: } lambda taking parameter `x`
30^ take the first 30 terms of...
recur( ) a recursive function
*tile(x,c(1)) whose seed is `x` `1`s
x with a window of `x`
sum@c and the functor takes the sum of its arguments
```
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
lambda n:reduce(lambda a,c:a+[sum(a[-n:])],'.'*(30-n),[1]*n)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqig1pTQ5VQPKT9RJtkrUji4uzdVIjNbNs4rVjNVR11PX0jA20M3T1Ik2jNXK0/xfUJSZV6KQpmGiyQVjmmr@BwA "Python 2 – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 81 bytes
```
import StdEnv
$n=reverse(while((>)30o length)(\l=[sum(take n l):l])(repeatn n 1))
```
[Try it online!](https://tio.run/##DcyxCsIwEADQ3a@4oUNuEBRxEeKkQ8Gtozoc6dkGL5eSpBV/3tj1Dc8Jk9YQ@1kYAnmtPkwxFehKf9Vl06hNvHDKbD6jFzbmjIddBGEdyojmIfae52AKvRkUBE/yRJN4Yiq6wh6xdoXW0EIDx/pzL6Eh1217q5evUvAu/wE "Clean – Try It Online")
`(repeatn n 1)` gives us `n` ones in a list, which we repeatedly prepend the sum of the first `n` elements to (with `(\l=[sum(take n l):l])`), while it has less than 30 elements.
As the list is backwards, we reverse it and return.
] |
[Question]
[
**This question already has answers here**:
[Shortest code that raises a SIGSEGV](/questions/4399/shortest-code-that-raises-a-sigsegv)
(84 answers)
Closed 6 years ago.
We've had challenges for [SIGSEGV](https://codegolf.stackexchange.com/questions/4399/shortest-code-that-returns-sigsegv/62668#62668) and [SIGILL](https://codegolf.stackexchange.com/questions/100532/shortest-code-to-throw-sigill) so why not...
Write the shortest code that results in a **[Bus Error (SIGBUS)](https://en.wikipedia.org/wiki/Bus_error)** in any programming language.
Your program can't call `raise()` or `kill(getpid(),sig)` or `pthread_kill(pthread_self(),sig)`, or any other equivalent.
[Answer]
# x86\_64 bytecode, 15 bytes
```
0: c7 04 24 00 00 04 00 movl $0x40000,(%rsp)
7: 9d popfq
8: 8b 04 25 01 00 00 00 mov 0x1,%eax
```
Turns on the misaligned address trap flag and then immediately triggers it.
] |
[Question]
[
Write the shortest possible code which converts tabs to spaces in the input. Tab size should be supplied as a parameter or be hardcoded in the code **in a single place**.
Spaces on output should point to the right column, e.g. (`\t` represents a tab character):
```
a\tb
aa\tb
aaa\tb
aaaa\tb
```
should become (for tab size 4):
```
a b
aa b
aaa b
aaaa b
```
Of course there can be more than one tab in a line.
Line separator and tab character should match the system defaults (e.g. ASCII 10 and 9 on Unix).
[Answer]
## [Perl 5](https://www.perl.org/), 36 bytes
```
1while s/ /$"x($^I-length($`)%$^I)/e
```
[Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1WhWJ9TX0WpQkMlzlM3JzUvvSRDQyVBUxXI1dRP/f8/kTOJKxFCQEkwxQkRhooDqX/5BSWZ@XnF/3UL/utmmgAA "Perl 5 – Try It Online")
Tab length is controlled with `-i` command-line parameter.
[Answer]
# [Python 2](https://docs.python.org/2/), 106 bytes
```
def f(s,w):
for l in s.split('\n'):
L=''
for x in l.split('\t'):L+=' '*(w-(len(L)%w))+x
print L[w:]
```
[Try it online!](https://tio.run/##PcsxDsIwDIXhnVN4QbZpYUBMlXqD3KBhKKIRkSI3aiylnD4kA53@J/lz/OpnlXsp78WBo9RnHk7g1g0CeIF0SzF4JbSC7QBmRKxpYG8gHEArMN2IgBfKVwqLkOFzZu72@hA3LwpmysOzOMLZ6svK/M/RNrB/cPkB "Python 2 – Try It Online")
[Answer]
# Vim, 16 bytes
```
:se ts=4 et
:ret
```
[Answer]
# Pyth, 24 bytes
```
VQ=+k:NJ" "d=.[kd|nNJ4)k
```
[Try it here](http://pyth.herokuapp.com/?code=VQ%3D%2Bk%3ANJ%22%09%22d%3D.%5Bkd%7CnNJ4%29k&input=%22aa%5Ctbbbb%5Ctccc%22&debug=0)
### Explanation
```
VQ=+k:NJ" "d=.[kd|nNJ4)k
VQ ) For each character in the input...
=+k:NJ" "d ... add the character with tab replaced by space
to k (initially empty)...
=.[kd ... then pad k with spaces...
|nNJ4 ... to the nearest multiple of 4 if the character
is a tab and 1 otherwise.
k Output k.
```
Alternatively, if we want to input the tab length, we can do so with `Vz=+k:NJ" "d=.[kd|nNJQ)k`.
[Try it here.](http://pyth.herokuapp.com/?code=Vz%3D%2Bk%3ANJ%22%09%22d%3D.%5Bkd%7CnNJQ%29k&input=4%0Aaa%09bbbb%09ccc&debug=0)
[Answer]
# Java 11, 134 bytes
```
n->s->{for(var l:s.split("\n")){var t="";for(var p:l.split("\t"))t+=" ".repeat(n-t.length()%n)+p;System.out.println(t.substring(n));}}
```
This time an answer for which I correctly read the challenge.. >.>
[Try it online](https://tio.run/##bVCxbsIwEN35ilOkSrZIrA6dCGSpVKlDJ0bCYIKBUOdi2WcqhPLt6VEMLJ3une/53nt31CddHLffY2N1CPClW7xMAAJpahs48lRFaq3aRWyo7VF9JDD/RDJ74/P/SO89htgZP1@Sb3FfVbCDBYxYVKGoLrvei5P2YGdBBWdbElmNmZSX6yMtsqy8M9zMPhjEDJouvHFGcw9ZjgUpa3BPByFfUE5duTwHMp3qIynHwmRRkApxE/5sCJSyHIaxnHBCFzeWE6agp77dQsfhxc3xag1aXg8BsFPaOXsWb1LppjGOtXVNmxr1vTxqAjU95k8Go0yWvHGYPO97E4OUKXVsNgc2D7rrI1Ky4Q1Fj4DmJ/0SV9gctF/deGupeI/VjeFjvWY5r0l6w/gL).
NOTE: Because Java 11 isn't on TIO yet, the `String.repeat(int)` has been emulated with `repeat(String,int)` for the same byte-count.
**Explanation:**
```
n->s->{ // Method with int & String parameters and String return-type
for(var l:s.split("\n")){ // Split the input by newlines, and loop over the lines:
var t=""; // Temp-String, starting empty
for(var p:l.split("\t")) // Split the line by tabs, and loop over the parts
t+=" ".repeat(n-t.length()%n)
// Append `n - length_of_t modulo-n` amount of spaces,
+p; // as well as part `p` to the temp-String
System.out.println( // Print with trailing new-line:
t // The temp-String `t`
.substring(n));}} // after we've removed the trailing spaces
```
[Answer]
# Excel VBA, 118
An anonymous VBE immediate window function that takes an input string from range `[A1]` and an input tab length from range `[B1]`, and outputs to the console.
```
For Each l In Split([A1],vbLf):Do:i=InStr(1,l,"\t"):l=Replace(l,"\t",Space([B1]-(i-1)Mod[B1]),,1):Loop While i:?l:Next
```
### Ungolfed
```
Public Sub tabReplace(ByRef value As String, Optional tabLen As Integer = 4)
Dim line, index As Integer
For Each line In Split(value, vbLf)
Do
Let index = InStr(1, line, "\t")
Let line = Replace(line, "\t", Space(tabLen - (index - 1) Mod tabLen), , 1)
Loop While index
Debug.Print line
Next
End Sub
```
[Answer]
# [Python 2](https://docs.python.org/2/), 103 bytes
```
def F(I,c):
while'\t'in I:t=I.find('\t');I=I.replace('\t',' '*(c-(t+~I[:t].rfind('\n'))%c),1)
print I
```
[Try it online!](https://tio.run/##ZYxBCsIwEEX3OcVQkCQaC4qrittCzmBctGmKgTgtdUTcePWYRnGhm/n8x38zPug84DbGzvVQC62srBjczz44boh7BF3RQZe9x07MRO51qpMbQ2NdJooDXwq7FrR66mNFp3L6rJFLubBSbSSDcfJIoGMtiqJoDLUsnRzv8o0500TBTjKWLZYcHICa9vqP04/LLZA3FDw6g78kG/EF "Python 2 – Try It Online")
I wanted to evade `split` and use some `replace` (tbh I've started with regex).
I replace each `\t` with `c-(t+~I[:t].rfind('\n'))%c` number of spaces. Where `t` - index of current `\t` and `t+~I[:t].rfind('\n')` is distance to the closest `\n` (or start of string) on left.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
StringReplace[#," "->Array[" "&,4]<>""]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ikKDMvPSi1ICcxOTVaWUeJU0nXzrGoKLEyWklBSU3HJNbGTkkpVu1/AFBdSXSag1IiZxJXIoSAkkBKKfY/AA "Wolfram Language (Mathematica) – Try It Online")
Sadly, Mathematica doesn't let you multiply a string by a number to duplicate it, otherwise it would be shorter than Perl.
---
Explanation:
`StringReplace[#,` Replace all instances of
`" "` a tab character
`->Array[" "` with an array of spaces
`,4]` four long
`<>""]&` joined to the empty string.
] |
[Question]
[
I'm new to [Japanese Mahjong](https://en.wikipedia.org/wiki/Japanese_Mahjong) and have trouble [calculating the scores](https://en.wikipedia.org/wiki/Japanese_Mahjong_scoring_rules). Please help me write a program to calculate it.
# Introduction
(aka you can skip this boring part)
[Mahjong](https://en.wikipedia.org/wiki/Mahjong) is a popular tile game in Asia. Different rules have evolved and systematically established in various regions. Japan, being an isolated island state, have its own mahjong variant including rules and scoring.
In Japanese Mahjong, 4 players participate in the game at the same time. They take turn to draw a tile from wall and discard a tile from hand. Occasionally then can take other's discarded tiles for use. Each round 1 of the 4 players will be the dealer. Independent of that, each round may have a winner if he/she can assemble a winning hand. There could be no winners in a round but we don't care about that in this challenge.
When a player become the winner of that round, the change in score is calculated depending on 4 things: (1) `Han` and (2) `fu` depends on the winning hand, (3) whether the winner is also a dealer, and (4) whether he win by self-draw or from other's discard. The winner get his points by taking the points from the losers. So points lost by all losers added should equal to points gained by winner. Moreover, sometimes only one loser lose his points while the other two don't lose any, and sometimes one of the three losers lose more points. (See below)
# Objective
Write a program or function that accepts the 4 parameters mentioned above, and return (1) how many points the winner will gain, and (2-4) how many points each of the three losers will lose.
## Details of inputs
`Han`: An integer from 1 to 13 inclusive.
`Fu`: An integer that is either 25, or an *even* number from 20 to 130 inclusive. If `han` is 1 or 2, `fu` is further capped at 110.
`dealer or not`: A truthy/falsy value. Though if you are a mahjong lover you can instead accept the winner's seat-wind :-)
`self-draw or discard`: A two-state value. Truthy/falsy value will suffice but other reasonable values are acceptable.
## Steps of calculating the points gained/lost:
**1. Calculate the base score**
The base score is calculated based on 2 cases.
*1a) `Han` ≤ 4*
If `fu` is 25, then keep it as-is. Otherwise round it *up* to nearest 10.
Then base score is calculated by
base\_score = fu×2han+2
And it's capped at 2000 points.
*1b) `Han` ≥ 5*
`Fu` is *not* used here. The base score is obtained by direct lookup of `han` in the following table:
```
Han Base score
5 2000
6-7 3000
8-10 4000
11-12 6000
13 8000
```
**2. Calculate the points lost by losers**
*2a) Dealer wins by self-draw*
Each loser pays an amount equal to double of the base score, then rounded *up* to nearest 100.
*2b) Dealer wins by discard*
The discarding loser pays an amount equal to 6x the base score, then rounded *up* to nearest 100. Other two losers don't pay.
*2c) Non-dealer wins by self-draw*
Dealer (one of the loser) pays an amount equal to double of the base score, then rounded *up* to nearest 100. The other two losers each pays an amount equal to base score, also rounded up to 100.
*2d) Non-dealer wins by discard*
The discarding loser pays an amount equal to 4x the base score, then rounded up to 100. Other two losers don't need to pay. Scoring isn't affected by whether the discarding loser is dealer or not.
**3. Calculate the points gained by winner**
Winner gains the total points lost by the three losers. Not a point less and not a point more.
# Example
(Some examples are shamelessly taken/modified from [Japanese Wikipedia page](https://ja.wikipedia.org/wiki/%E9%BA%BB%E9%9B%80%E3%81%AE%E5%BE%97%E7%82%B9%E8%A8%88%E7%AE%97#.E5.BE.97.E7.82.B9.E8.A8.88.E7.AE.97.E3.81.AE.E4.BE.8B) of calculating mahjong score)
**4 `han` 24 `fu`, dealer win by self-draw**
24 `fu` rounded up to 30 `fu`
Base score = 30 × 2 4+2 = 1920
Each loser pays 1920×2 = 3840 => 3900 (rounded)
Winner takes 3900×3 = 11700 points
Output: +11700/-3900/-3900/-3900
**3 `han` 25 `fu`, dealer win by discard**
25 `fu` no need to round up
Base score = 25 × 2 3+2 = 800
Discarding loser pays 800×6 = 4800
Non-discarding loser pays 0 points
Winner takes 4800 points
Output: +4800/-4800/0/0
**4 `han` 40 `fu`, non-dealer win by self-draw**
40 `fu` no need to round up
Base score = 40 × 2 4+2 = 2560 => 2000 (capped)
Dealer pays 2000×2 = 4000
Non-dealer pays 2000
Winner takes 4000+2000×2 = 8000 points
Output: +8000/-4000/-2000/-2000
**9 `han` 50 `fu`, non-dealer win by discard**
`Fu` not used to calculate score
Base score = 4000 (table lookup)
Discarding loser pays 4000×4 = 16000
Non-discarding loser pays 0 points
Winner takes 16000 points
Output: +16000/-16000/0/0
## Output
Output 4 numbers: The point that the winner is gaining (as positive number), and the points that each of the three losers is losing (as negative number).
You may output the numbers as 4 individual numerical values in your language's native format, an array/list of numbers, 4 separate strings (or array/list of characters), or a string contatining the numbers that are properly delimited. If you use string, the positive sign is optional but negative sign is mandatory.
The order of the numbers doesn't matter, since they can be inferred from sign and magnitude of the numbers. e.g. 0/-16000/+16000/0 is acceptable.
## Format
* Full program or function
* Any reasonable input/output format
* Default rules apply. Standard loopholes forbidden. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins.
# Notes
* All outputs are guaranteed to be integers, more specifically multiples of 100 in the range [-48000,+48000]
* Rounding is applied only to (1) `fu` and (2) loser's points. It is *not* applied to base score.
* Theoretically winning by self-draw or discard should gain the same points (6x or 4x base points). However due to rounding, this may not be true at low `han`. (See 1st and 2nd test cases)
# Test cases
(Also see example)
```
Inputs Outputs
Han Fu Dealer Self Winner Loser1 Loser2 Loser3
1 22 N Y +1100 -500 -300 -300
1 22 N N +1000 -1000 0 0
3 106 Y N +12000 -12000 0 0
4 20 N Y +5200 -2600 -1300 -1300
4 25 Y N +9600 -9600 0 0
5 88 Y Y +12000 -4000 -4000 -4000
7 25 Y Y +18000 -6000 -6000 -6000
12 64 N N +24000 -24000 0 0
13 130 Y N +48000 -48000 0 0
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 79 bytes
05AB1E uses [CP-1252](http://www.cp1252.com) encoding.
**Input order:**
```
Han
Fu
Dealer = 1, Non-dealer = 0
Self = 2, Discard = 0
```
**Code:**
```
3‹i6b‚ï{0è}¹5‹iÐT/îT*‚sÈè¹Ìo*3°·‚{0èë\•j¤È°•¹è3°*}U•é2TˆÞ•S3ôŠ+èX*Tn/îTn*(DOĸì
```
[Try it online!](http://05ab1e.tryitonline.net/#code=M-KAuWk2YuKAmsOvezDDqH3CuTXigLlpw5BUL8OuVCrigJpzw4jDqMK5w4xvKjPCsMK34oCaezDDqMOrXOKAomrCpMOIwrDigKLCucOoM8KwKn1V4oCiw6kyVMuGw57igKJTM8O0xaArw6hYKlRuL8OuVG4qKERPw4TCuMOs&input=NAoyMAowCjI)
Explanation to come.
[Answer]
## Python 2, 128 bytes
```
def m(h,f,o,t):C=100;b=[24/(50/h)*1000,min(2000,[-f/10*~9,f][f%2]<<h+2)][h<5];x=(o|2-t)*-2*b/C*C;y=~o*t*b/C*C;return-x-y-y,x,y,y
```
`h` is han, `f` is fu, `o` is dealer (1/0), `t` is self-draw (1/0). Outputs in the same order as the test cases. [ideone link](https://ideone.com/Xa9yIR).
Expanded slightly:
```
def m(h,f,o,t):
C = 100
# Base score
b = [24/(50/h)*1000, min(2000,[-f/10*~9,f][f%2]<<h+2)][h<5]
# Player scores - uses the -x/100*-100 approach to round up
x = (o|2-t)*-2*b/C*C
y = ~o*t*b/C*C
return -x-y-y, x, y, y
```
Indirect thanks to @MartinEnder.
[Answer]
## C#6, 211 bytes
```
using static System.Math;(h,f,x,y)=>{int b=h>5?24/(50/h)*100:Min(f%2<1?(int)Ceiling(f*.1)<<h+2:10<<h,200),c=-(int)Ceiling(b*.1*(y?2:x?6:4))*100,d=-(int)Ceiling(b*.1*(y?x?2:1:0))*100;return new[]{-c-d*2,c,d,d};};
```
Contains an idea shamelessly stolen from @Sp3000.
Assign to `Func<int,int,bool,bool,int[]>`
h=han
f=fu
x=true if dealer wins, false if non-dealer wins
y=true if self draw, false if discard
returns int[], [0]=winner, [1]-[3]:loser
[repl.it demo](https://repl.it/E7kk/0)
Ungolfed + explanations
```
// b is base score / 10
int b=h>5
// han is [6,13], use Sp3000's idea
?24/(50/h)*100
// han <= 5, calculate base score (/ 10) from formula...
// Yes this formula works for han==5 also
:Min(
f%2<1
// round up to 10, then times 2^(h+2)
?(int)Ceiling(f*.1)<<h+2
// b=2.5*2^(h+2)=10*2^h=10<<h
:10<<h
// Cap at 200, thus base score is capped at 2000
,200),
// Multiply 0.1b by 2/4/6 according to input, then multiply by 100 to get actual score
c=-(int)Ceiling(b*.1*(y?2:x?6:4))*100,
d=-(int)Ceiling(b*.1*(y?x?2:1:0))*100;
// Array type implied from arguments
return new[]{-c-d*2,c,d,d};
```
] |
[Question]
[
# Why don't you grow up?
In the past week a meme involving the young actor Aaron Bailey became trending in most Brazilian social networks. Entitled "why don't you grow up" it consists in repeating a sentence replacing its vowels with `i`s (it's a bit more complicated than that, I'll explain below). As I want to be a cool guy I decided to write a program that `mimimifies` a given string.

# Challenge
The challenge consists of `mimimifying` a string, following the rules:
* `ão` and `õe` should be replaced with `im`.
* `ca`, `ka`, `que`, `ke`, `qui`, `ki`, `co` ,`ko`, `cu`, and `ku` should be replaced with `ki`.
* `ça`, `ce`, `çe`, `ci`, `çi`, `ço`, and `çu` should be replaced with `ci`.
* `ga`, `gue`, `gui`, `go`, and `gu` should be replaced with `gui`.
* `ja`, `ge`, `je`, `gi`, `ji`, `jo`, and `ju` should be replaced with `ji`
* You can assume that `qua`, `quo`, `quu`, `gua`, `guo`, and `guu`, will never appear, only `a` and `o` can have tildes and if they do they'll be followed by `o` and `e`, repsectively (`ão`, `õe`).
* The only time `u`s are allowed in output strings is `gui`, besides that case all other vowels present should be `i`s.
* In all other circumstances all vowels must be replaced with `i`s.
* Other than tilde all other accents may be ignored.
* Two or more `i`s in a row are not allowed, you should replace them with only one (`Piauiense` -> `Pinsi`)
# Examples
**Input**
```
Por que você só fala assim?
```
**Output**
```
pir ki vici si fili issim?
```
**Input**
```
Que horas são?
```
**Output**
```
ki hiris sim?
```
**Input**
```
Óculos sem lente pode ser armação
```
**Output**
```
ikilis sim linti pidi sir irmicim
```
**Input**
```
Ganha o código com menos bytes
```
**Output**
```
guinhi i kidigui kim minis bytis
```
# Rules
* The vowels are `a`, `e`, `i`, `o`, and `u`.
* You can see the full list of possible accents [here](http://sites.psu.edu/symbolcodes/languages/psu/portuguese/).
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code in bytes wins. Check meta if counting bytes is awkward in your language.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/30231) are forbidden
* Your output must be consistent in case: all upper/all lower.
* You may assume the input to be in whichever encoding you want but if you do you must specify it.
**Happy golfing!**/**Hippy guilfing!**
[Answer]
# [Retina](http://github.com/mbuettner/retina), 150 bytes
```
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji
(gu)i|[aeou]
$1i
ii
i
```
[Try it online!](http://retina.tryitonline.net/#code=W8OAw4HDgsOgw6HDol0KYQpbw4nDisOpw6pdCmUKw418w60KaQpbw5PDlMOzw7RdCm8KW8Oaw5zDusO8XQp1ClRgTGBsCsOjb3zDtWUKaW0KW2NrXVthb3VdfHF1W2VpXXxrZQpraQrDp1thZWlvdV18Y2UKY2kKZ1thb3VdfGd1ZQpndWkKalthZW91XXxnW2VpXQpqaQooZ3UpaXxbYWVvdV0KJDFpCmlpCmk&input=UG9yIHF1ZSB2b2PDqiBzw7MgZmFsYSBhc3NpbT8KUXVlIGhvcmFzIHPDo28_CsOTY3Vsb3Mgc2VtIGxlbnRlIHBvZGUgc2VyIGFybWHDp8OjbwpHYW5oYSBvIGPDs2RpZ28gY29tIG1lbm9zIGJ5dGVz)
This is my first Retina program, so there's probably a lot of improvements to make. Suggestions are welcome.
Thanks to Martin for correcting some mistakes and for some golfing suggestions.
## Explanation
I'm going to break up the explanation into 3 sections, to make it easier on me.
### Section 1: Preprocessing
```
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l
```
The first 5 rules replace any accented vowel with the corresponding unaccented version. It's shorter to list out the matches in character classes (or, in the third case, as two options) than to use the culture-invariance and case-insentivity options each time. The last rule converts all ASCII letters to lowercase.
### Section 2: Mimimification
```
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji
```
These rules simply apply the substitutions specified.
### Section 3: Cleanup
```
(gu)i|[aeou]
$1i
i+
i
```
The first rule matches any vowel except for the `u` in `gui`, and replaces them with `i`s. The second rule removes repeated `i`s.
[Answer]
# JavaScript, ~~396~~ ~~392~~ 389 bytes (~~383~~ ~~379~~ 376 characters)
Too many `replace`s, too much regex, ...
```
f=s=>s.toLowerCase().replace(/ão|õe/g,"im").replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u").replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui").replace(/i{2,}/g,"i")
```
I have used this [link](http://sites.psu.edu/symbolcodes/languages/psu/portuguese/) for a list of Brazilian accented letters so that I know for which letters I have to remove the accent.
### Explanation
```
s.toLowerCase()
```
First, everything is converted to lowercase.
```
.replace(/ão|õe/g,"im")
```
Then I'm am implementing this rule.
```
.replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u")
```
Then the accents are removed using regex.
```
.replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui")
```
After that, the the string is being bombarded by regular expressions to "memify" it.
```
.split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui")
```
Now all the vowels, except those in `gui` (that is why I used `split`) are being converted to `i`. After that, I rejoin the Array using `gui` as the delimiter.
```
.replace(/i{2,}/g,"i")
```
Finally, I am replacing 2 or more `i`s with just 1 of them.
# Snack Snippet!
```
f=s=>s.toLowerCase().replace(/ão|õe/g,"im").replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u").replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui").replace(/i{2,}/g,"i")
console.log(f("Por que você só fala assim?"))
console.log(f("Que horas são?")) //They call me the professional Brazilian-meme-maker
console.log(f("Óculos sem lente pode ser armação")) //dank memes, dank memes everywhere
console.log(f("Ganha o código com menos bytes"))
```
Golfing suggestions are welcome
] |
[Question]
[
# Intro (semi fictional)
I'm the solo developer of a game, I'm already struggling with character design as is. Hence I've thought of a smart solution, I'll just use images for regular monsters, outline them a bit and suddenly they are boss monsters! That will save me from thinking up new bosses yay.
However, I have approximately 100 monster designs already and I wouldn't like duplicating them all and manually drawing an outline to the images...
# Challenge
Given a file name (of a [PNG](https://www.w3.org/TR/PNG/) file) as input, you should write a program/function which will draw an outline around every non-transparent pixel. The program/function should save the output file to a new file called `a.png`
# What does outlining mean
Outlining is the process of adding non-transparent pixels in the place of transparent pixels, around pixels which were non-transparent already. Any transparent pixel has an opacity of exactly 0%, anything else is defined as non-transparent. Any pixel which will be outlined will have an opacity of 100%, aka the alpha channel of that pixel will be 255.
# Input
Your program/function should take 3 variables as input. Feel free to provide these as function parameters, read them from stdin or any other method which suits you best.
The first variable is the **file name**, which is always a PNG file.
The second variable is the **outline colour**, which is a round integer, you can also take the colour from 3 separate `r,g,b` byte values.
The third variable is the **outline width**, also an integer.
# Outline width
The width of the outline equals the maximum distance any transparent pixel should have to a non-transparent pixel in order to be outlined. The distance is calculated using the [Manhattan distance](https://en.wiktionary.org/wiki/Manhattan_distance) between two points.
If the input image has only 1 non-transparent pixel, at `[0,0]` and the outline width is 2, then the following pixels will be coloured:
`[0,1] [0,-1] [1,0] [-1,0] [1,1] [-1,-1] [1,-1] [-1,1] [2,0] [-2,0] [0,2] [0,-2]`, for these have a manhattan distance of 2 or less from the coloured pixel
# Test cases
The following test cases are scaled up 7 times for visibility, so every block of 7 pixels should be treated as a single pixel
These are the input images used for the test cases:
```
input1.png
```
[](https://i.stack.imgur.com/vKMRZ.png)
```
input2.png
```
[](https://i.stack.imgur.com/6j7g6.png)
```
input3.png
```
[](https://i.stack.imgur.com/z04oV.png)
These are the actual test cases:
```
input1.png, 0xFF0000, 0
```
[](https://i.stack.imgur.com/ymADm.png)
```
input1.png, 0xFF0000, 1
```
[](https://i.stack.imgur.com/otaZ6.png)
```
input1.png, 0xFF0000, 2
```
[](https://i.stack.imgur.com/mPuCC.png)
```
input1.png, 0xFF0000, 3
```
[](https://i.stack.imgur.com/PtJ8o.png)
```
input1.png, 0xFF0000, 10
```
[](https://i.stack.imgur.com/DgAdH.png)
```
input2.png, 0xFF0000, 2
```
[](https://i.stack.imgur.com/KrlLW.png)
```
input3.png, 0x000000, 2
```
[](https://i.stack.imgur.com/QgYbO.png)
Click [here](https://i.stack.imgur.com/ODCbA.jpg) for the full Imgur album.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply! Feel free to submit your own images as test cases, since these pixel images aren't very creative ;)
[Answer]
# Matlab, 202 bytes
```
function f(i,r,g,b,n);[i,~,a]=imread(i);[x,y]=ndgrid(abs(-n:n));d=permute([r,g,b,255]',3:-1:1);I=cat(3,i,a);J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I;imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4))
```
As always:
>
> Convolution is the key to success.
>
>
>
The function can be called like so:
```
f('my_image.png', red_int, green_int, blue_int, dist)
```
Commented:
```
function f(i,r,g,b,n)
[i,~,a]=imread(i); %read image and alpha channel
[x,y]=ndgrid(abs(-n:n)); %computations for convolution kernel
d=permute([r,g,b,255]',3:-1:1); %create 'pixel' that will be inserted
I=cat(3,i,a); %concatenate image and alpha channel
J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I; %find border via convolution of kernel, insert pixels and recombine with original
imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4)) %write file
```
[Answer]
# PHP, 559 chars
## Ungolfed
```
<?php
error_reporting(0);
$p=$argv[1];
$img = ImageCreateFromPng($p);
$width = imagesx($img);
$height = imagesy($img);
$new = ImageCreateFromPng($p);
alphaFix($img);
alphaFix($new);
$inv = '2130706432';
for($w=0;$w<$width;$w++)
for($h=0;$h<$height;$h++)
{
$color = ImageColorAt($img, $w, $h);
if($color != $inv)
for($x=0;$x<$width;$x++)
for($y=0;$y<$height;$y++)
{
if(abs($h - $y) + abs($w - $x) <= intval($argv[3]))
{
$_color = ImageColorAt($img, $x, $y);
if($_color == $inv)
imagesetpixel($new, $x, $y, hexdec($argv[2]));
}
}
}
imagepng($new, str_replace(".png", ".border.png", $p));
function alphaFix(&$img)
{
$background = imagecolorallocate($img, 0, 0, 0);
imagecolortransparent($img, $background);
imagealphablending($img, false);
imagesavealpha($img, true);
}
?>
```
## Golfed
```
<?error_reporting(0);$j=$argv[1];$g=ImageCreateFromPng($j);$e=imagesx($g);$b=imagesy($g);$l=ImageCreateFromPng($j);a($g);a($l);$f='2130706432';for($m=0;$m<$e;$m++)for($l=0;$l<$b;$l++){$d=ImageColorAt($g,$m,$l);if($d!=$f)for($k=0;$k<$e;$k++)for($i=0;$i<$b;$i++){if(abs($l-$i)+abs($m-$k)<=intval($argv[3])){$c=ImageColorAt($g,$k,$i);if($c==$f)imagesetpixel($l,$k,$i,hexdec($argv[2]));}}}imagepng($l,str_replace(".png",".border.png",$j));function a(&$g){$a=imagecolorallocate($g,0,0,0);imagecolortransparent($g,$a);imagealphablending($g,0);imagesavealpha($g,1);}
```
## Syntax
```
php outline.php "image1.png" 0xFF0000 1
| | |
| | *- Border Size
| *------ Color HEX
*------------------ Image Name
```
## Examples
I made an [Imgur album](https://i.stack.imgur.com/zJ9nH.jpg), because I slightly changed the images and there you can also see the arguments I passed my script.
] |
[Question]
[
A peer of mine approached me with this challenge and I wasn't able to come up with an elegant solution. After discussing my approach, we began to wonder what the people at Code Golf would come up with.
# Given
* A processor that implements only two instructions:
1. STO <register>, <address> (`store` from this `register` to this `address`)
2. SUB <register>, <address> (`subtract` the value at this `address` from this `register`)
* It also only contains `2`, `32-bit` registers: `A` and `B`
* As well as `2`, `32-bit` RAM address: `0x00` and `0x01`
* The values of `A` and `B` are unknown
# Challenge
Write a program to `copy` RAM address `0x00` into `0x01` optimised to use the `fewest` number of instructions possible.
[Answer]
Assuming registers are signed and/or wrapping
8 instructions:
```
STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x00
SUB A 0x00
SUB A 0x00
STO A 0x00
STO A 0x01
```
A 7-instruction version provided by lrn:
```
STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x01
SUB A 0x01
SUB A 0x01
STO A 0x01
```
] |
[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/24297/edit).
Closed 6 years ago.
[Improve this question](/posts/24297/edit)
There are programs that will output its source code to standard output and do nothing else. They also access no external output. This type of program is known as a [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29), and is a common code challenge.
There are poems that have the [rhyme scheme](http://en.wikipedia.org/wiki/Rhyme_scheme) a-b-a-b, c-d-c-d, e-f-e-f, g-g. They have 14 lines. They are usually recited in [iambic pentameter](http://en.wikipedia.org/wiki/Iambic_pentameter). They are called [sonnets](http://en.wikipedia.org/wiki/Sonnet).
You are to write a program/poem that is both a quine and a sonnet.
1. When saying lines, it is recommended that you only say all characters except for: whitespace and `,()[]_"'`. This is flexible depending on the language though.
2. Iambic Pentameter means 10 syllables, starting unstressed, and then alternating between stressed and unstressed. This is optional, but will mean more votes.
3. Comments are discouraged, especially to complete rhymes (although comments are very much encouraged if they can be incorporated with the code in the poem in a way that produces dramatic effect.)
4. [Cruft](http://jeremyskrdlant.blogspot.com/2012/10/what-is-cruft-code.html) is discouraged.
Voters, use the four above guidelines when voting. This is a popularity contest, so the program with the most votes wins.
[Answer]
# Ruby
```
s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].to_a
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *rule } }, '-'
s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].the_way
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *jewel } }, '-'
-
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].reverse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *phrase } }, '-'
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].the_curse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *craze } }, '-'
-
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].collect
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *word } }, '-'
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].reject
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *bird } }, '-'
-
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *half } }, '-'
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *laugh } }, '-'
-
```
Don't pronounce the dashes, they're just there to delimit stanzas. Scansion's not perfect but decent.
] |
[Question]
[
**Context:** We are working on a complex image drawing program to produce mugs, t-shirts, and so on. Here is an example of such function

However, we are facing the following problem: Random generated functions are mostly white and black (where black is close to zero and white close to infinity). The idea of this contest is to find a number to scale all numbers so that corresponding colors are in the visible spectrum.
**Problem**
The input is, formatted the way you want:
* An array of double precision A[1..n] randomly sorted of positive numbers (>0).
* An expected inclusive lower bound L > 0
* An expected inclusive upper bound U > 0
The expected output is
* A number `f` so if we multiply all elements of A by `f`, it maximizes the number of the new elements between L and U. If there are multiple solutions, `f` should be as close to 1 as possible.
Write a program computing `f` in a few operations as possible.
To check, post the result of your program on the following (sorted for convenience) input:
```
A = [0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100]
L = 1
U = 5
```
The result should be `f` = 0.25
**Winning conditions**: The winner will be the one with the best time complexity. If there are multiple algorithms of the same complexity, the fastest one will win. If your program is obfuscated or hard to read, please also attach an unobfuscated version with explanations.
[Answer]
## Perl O(n log n)
```
#!/usr/bin/env perl
use strict;
$^W=1;
# calculate_f ( <lower bound>, <upper bound>, <array reference> )
sub calculate_f ($$$) {
my $L = shift;
my $U = shift;
my $A = shift;
my $n = @$A;
# Catch trivial cases:
# * Upper bound is lower than lower bound,
# * array is empty.
# In both cases the result array is empty and the value
# of f does not matter. Therefore we can return the
# "optimum" value 1.
return 1 if $U < $L or $n == 0;
# The array is sorted. accordign to the manual page, Perl since 5.7
# uses a "stable mergesort algorithm whose worst-case behaviour
# is O(N log N).
my @A = sort {$a <=> $b} @$A;
# Array @R stores the length of ranges:
# $R[$i] is the number of elements that form a valid
# range of input numbers ($A[$i], ..., $A[$i + $R[$i] - 1])
my @R;
my $lu = $L / $U;
my $ul = $U / $L;
# find ( <upper value>, <left position>, <right position> )
# The function looks for the largest input value below or equal
# <upper value>. Invariant: The input value at <left position>
# in the sorted array belongs to the range below <upper value>,
# the input value at <right position> is larger than <upper value>.
# It is a binary search: O(log n)
sub find ($$$) {
my $u = shift;
my $left = shift;
my $right = shift;
return $left if $right <= $left + 1;
my $next = int(($left + $right)/2);
return find($u, $next, $right) if $A[$next] <= $u;
return find($u, $left, $next);
}
for (my $i = 0; $i < $n; $i++) {
my $a = $A[$i];
my $u = $a * $ul;
if ($A[$n-1] <= $u) {
$R[$i] = $n - $i;
next;
}
$R[$i] = find($u, $i, $n - 1) - $i + 1;
}
# Complexity is n times the loop body with the binary search: O(n log n).
# In the next step the maximum number of a valid range is
# obtained: O(n)
my $max = 0;
for (my $i = 0; $i < $n; $i++) {
my $a = $R[$i];
$max = $a if $a > $max;
}
print "(Debug) maximal number of elements in a valid range: $max\n";
# Now each range is checked to find the optimum f
my $f = 0;
for (my $i = 0; $i < $n; $i++) {
# ignore ranges with fewer elements
next unless $R[$i] == $max;
# print current range:
print sprintf "(Debug) A[%d .. %d] = (%g .. %g)\n",
$i, $i + $max - 1,
$A[$i], $A[$i + $max - 1];
# calculate f values based on the smallest/largest element
my $f_lower = $L / $A[$i];
my $f_upper = $U / $A[$i + $max - 1];
# if 1 is in the middle of the f values, then return
# optimal value
return 1 if $f_lower <= 1 and $f_upper >= 1;
# Now $f_lower and $f_upper are both smaller or both greater than 1.
# A candidate for $f is selected from the current range
# by using the value that is closer to 1.
my $f_candidate = $f_lower < 1 ? $f_upper : $f_lower;
print sprintf "(Debug) f_candidate = %g from (%g .. %g)\n",
$f_candidate, $f_lower, $f_upper;
# Compare the candidate with the current f
if (not $f or abs($f_candidate - 1) < abs($f - 1)) {
$f = $f_candidate;
}
}
# Complexity is O(n), because the loop body is O(1).
return $f;
}
my $f = calculate_f(1, 5, [
0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100
]);
print "(Result) f = $f\n";
__END__
```
Example output:
```
(Debug) maximal number of elements in a valid range: 6
(Debug) A[4 .. 9] = (5 .. 20)
(Debug) f_candidate = 0.25 from (0.2 .. 0.25)
(Result) f = 0.25
```
**Algorithm** is explained in the comments. The input numbers are sorted with O(n log n). Then for each number its valid range is obtained, O(n log n), then the maximum number of elements in the range is found, O(n) and the best fitting f value is calculated, O(n).
**Complexity:** O(n log n)
---
## Older version with O(n2)
```
#!/usr/bin/env perl
use strict;
$^W=1;
# calculate_f ( <lower bound>, <upper bound>, <array reference> )
sub calculate_f ($$$) {
my $L = shift;
my $U = shift;
my $A = shift;
my $n = @$A;
# Catch trivial cases:
# * Upper bound is lower than lower bound,
# * array is empty.
# In both cases the result array is empty and the value
# of f does not matter. Therefore we can return the
# "optimum" value 1.
return 1 if $U < $L or $n == 0;
# The array is sorted. according to the manual page, Perl since 5.7
# uses a "stable mergesort algorithm whose worst-case behaviour
# is O(N log N)".
my @A = sort {$a <=> $b} @$A;
# Array @R stores the length of ranges for each element with
# position $i in the sorted array, if the range starts with this
# element:
# $R[$i] is the number of elements that form a valid
# range of input numbers ($A[$i], ..., $A[$i + $R[$i] - 1])
my @R;
my $lu = $L / $U;
for (my $i = 0; $i < $n; $i++) {
my $a = $A[$i];
# Each input number is part of its own range.
$R[$i]++;
# Now we assume, that the current input number $A[$i] is
# the largest element of the range. The minimum lower bound in
# the input number space is calculated and the previous
# input number are checked, if the current input number
# can be added to their ranges.
my $l = $a * $lu;
for (my $j = $i - 1; $j >= 0; $j--) {
last if $A[$j] < $l;
$R[$j]++;
}
}
# In the worst case, all input numbers are part of the final
# output range. Then we would have to look up all smaller input
# numbers for each input number: O(n^2).
# In the best case, the final output range is 1, e.g. if the lower
# bound equals the upper bound. Then the going back is limited to
# 1 and the complexity is O(n).
# In the next step the maximum number of a valid range is
# obtained: O(n)
my $max = 0;
for (my $i = 0; $i < $n; $i++) {
my $a = $R[$i];
$max = $a if $a > $max;
}
print "(Debug) maximal number of elements in a valid range: $max\n";
# Now each range is checked to find the optimum f
my $f = 0;
for (my $i = 0; $i < $n; $i++) {
# ignore ranges with fewer elements
next unless $R[$i] == $max;
# print current range:
print sprintf "(Debug) A[%d .. %d] = (%g .. %g)\n",
$i, $i + $max - 1,
$A[$i], $A[$i + $max - 1];
# calculate f values based on the smallest/largest element
my $f_lower = $L / $A[$i];
my $f_upper = $U / $A[$i + $max - 1];
# if 1 is in the middle of the f values, then return
# optimal value
return 1 if $f_lower <= 1 and $f_upper >= 1;
# Now $f_lower and $f_upper are both smaller or both greater than 1.
# A candidate for $f is selected from the current range
# by using the value that is closer to 1.
my $f_candidate = $f_lower < 1 ? $f_upper : $f_lower;
print sprintf "(Debug) f_candidate = %g from (%g .. %g)\n",
$f_candidate, $f_lower, $f_upper;
# Compare the candidate with the current f
if (not $f or abs($f_candidate - 1) < abs($f - 1)) {
$f = $f_candidate;
}
}
# Complexity is O(n), because the loop body is O(1).
return $f;
}
my $f = calculate_f(1, 5, [
0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100
]);
print "(Result) f = $f\n";
__END__
```
The algorithm is explained in the comments. The complexity in the worst case is O(n2), in the best case O(n log n) because of the sorting.
Example output:
```
(Debug) maximal number of elements in a valid range: 6
(Debug) A[4 .. 9] = (5 .. 20)
(Debug) f_candidate = 0.25 from (0.2 .. 0.25)
(Result) f = 0.25
```
[Answer]
# C++
Comments indicate how code works.
```
#include<iostream>
#include<vector>
using namespace std;
int main(){
// input stores input, sum_values stores the sum of values in the valid range after multiplying
vector<double>input;
vector<double>sum_values;
// stores input, and ends of range
double num, lower, higher;
cout<<"Enter the array of values, use 0 to exit: ";
// input
while(1){
cin>>num;
if(num==0)break;
input.push_back(num);
}
cout<<"Enter the mimimum and maximum values: ";
cin>>lower>>higher;
// if array is empty or lower is greater than higher, print 1 and exit
if(lower>higher||input.size()==0){cout<<"1";return 0;}
// iterate through all values between .0001 and .9999
for(double d=.0001;d<1;d+=.0001){
// check each d for valid ranges
for(int i=0,valid=0;i<input.size();i++){
// check if input * d is in valid range
if(d*input[i]>=lower&&d*input[i]<=higher)valid++;
// store final number
if(i==input.size()-1)sum_values.push_back(valid);
}
}
// iterate through compiled sum of ranges and find highest
int position=0, biggest=-.1;
for(int i=0;i<sum_values.size();i++){
// return value closest to 1 for equal values
if(sum_values[i]>=biggest){
biggest=sum_values[i];
position=i;
}
}
// print value
cout<<(double)position*.0001;
return 0;
}
```
[Answer]
# Python
```
import collections
def pop_ranges(ranges, max_factor, count, dist, factor):
"""Removes ranges that don't overlap with the next range to be added"""
while ranges and max_factor < ranges[0][0]:
cnt = -len(ranges)
maxf = ranges[-1][1]
minf = ranges.popleft()[0]
# Finding the minimum from a constant amount of items (3) is O(1)
count, dist, factor = min([
(count, dist, factor),
(cnt, abs(minf - 1), minf),
(cnt, abs(maxf - 1), maxf)
])
return count, dist, factor
def scaler(vals, min_val, max_val):
# Sorting is O(n log n)
vals.sort()
factor = dist = count = 0
# Deque has O(1) operations to the beginning and the end
ranges = collections.deque()
# This loop is O(n); the outer loop does n passes and adds one item to
# ranges on every pass. pop_ranges() contains a loop, but since the loop
# pops items from ranges, it can only do a total of n passes during the
# whole outer loop.
for val in vals:
# val is growing on every pass, so the factors are shrinking.
min_factor = min_val / float(val)
max_factor = max_val / float(val)
count, dist, factor = pop_ranges(ranges, max_factor, count, dist, factor)
ranges.append((min_factor, max_factor))
count, dist, factor = pop_ranges(ranges, ranges[-1][0] - 1, count, dist, factor)
return factor
print scaler([0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100], 1, 5)
```
This works by sorting the values and keeping track of overlapping factor ranges. New factor ranges are added at the end of the deque and old ranges are removed from the beginning when they no longer overlap with the next range that is about to be inserted. The number of items in the deque corresponds to the number of items on the range and the first and last items give the endpoints of the range. When removing items, the best factor is updated if the current range is better. The complexity should be O(n log n) as explained in the comments.
] |
[Question]
[
Definition: a **set** is a datatype which allows testing of inclusion ("does set X contain element Y?") but does not have order. Its size is the number of distinct elements it contains.
Define an efficiently invertible injection from sets of `k` integers in the range 0 to 1000 inclusive to sets of `k+1` integers in the range 0 to 1000 inclusive such that each set maps to a superset of itself. This is not possible for all `k`: indicate for what range of `k` your code works. An answer will not be accepted unless it works for at least one `k > 4`.
Equivalently, provide two functions:
* `f` takes a set of integers between 0 and 1000 (inclusive), and outputs a set of integers in the same range. The output set contains all of the elements of the input set and exactly one element not in the input set.
* `g` inverts `f`: that is to say, given the output of `f` it removes the element which `f` added, and gives back the input of `f`.
**The winner:** The encoder/decoder that can handle the longest input set for all permutations of a set of that length.
For sake of space, it is acceptable to post code for only the encoder or decoder, provided that it is clear that the other half the transcoder works.
Inspired by this [question](https://softwareengineering.stackexchange.com/q/225468/9830).
**Edit:**
This should be possible for sets of at least five.
Here is an example for a set of three (800 is an arbitrary number; the encoder's implementation and the actual input set will dictate what it is).
* Input set: `{78, 4, 5}`
* Output of `f({78, 4, 5})`: `{78, 4, 5, 800}`
* Output of `g({78, 4, 5, 800})`: `{4, 5, 78}`
[Answer]
## C#
```
void Encode(HashSet<int> set)
{
set.Add((set.Single() + 1) % 1001);
}
void Decode(HashSet<int> set)
{
set.Remove(set.Equals(new HashSet<int>() { 0, 1000 }) ? 0 : set.Max());
}
```
Works for a set of length 1.
[Answer]
## C#
```
void Encode(HashSet<int> set)
{
int x = set.Sum();
int add;
if (x % 2 == 0)
{
add = x / 2;
}
else
{
add = (x + 1001) / 2 % 1001;
}
set.Add(add);
}
void Decode(HashSet<int> set)
{
int x = set.Sum();
if (x % 3 == 1)
{
x += 1001;
}
else if (x % 3 == 2)
{
x -= 1001;
}
int remove = x / 3;
set.Remove(remove);
}
```
Works for a set of length 2. This is a special case, and only works because 1001 is not divisible by 2 or 3.
[Answer]
## Perl 6
Phase 1:
```
sub add-value(@set) {
return (0) unless @set.elems >= 1;
@set .=sort;
my $sum = [+] @set;
for ^1009 -> $a {
my $v = ($sum+$a) % 1009;
next if $v > 1000;
next if [or] $v «Z==» @set;
return (@set, $v) if [and] remove-value((@set, $v)).sort Z== @set
}
die "Couldn't find anything for " ~ join(',', @set)
}
```
Yes, I used the function for phase 3 as extra check in phase 1. It fixes bugs.
Phase 2: Shuffle the set with `@set.=pick(*)`
Phase 3:
```
sub remove-value(@set) {
return () if @set.elems <= 1;
for ^1009 -> $a {
for @set.sort -> $b {
my $sum = 1009 R% [+] $a, @set.grep(* != $b);
next if $sum > 1000;
return @set.grep(* != $b) if $sum == $b
}
}
die "Couldn't find anything for " ~ join(',', @set)
}
```
I lack a bit of processing power to run all combinations atm, but with some 200 random combinations of length 1 through 15 (each) I didn't get any doubles.
Little test script could take about a century or 2 generating roughly 1000! combinations, but will start checking them right after:
```
for (^1001).combinations -> @set {
my @newset = add-value(@set);
@newset = @newset.pick(*);
my @oldset = remove-value(@newset);
if not [and] (@oldset.sort() Z== @set.sort()) {
say "failed for $count, added value $added";
say join ',', @set.sort;
say join ',', @oldset.sort;
die 'bad result';
}
}
```
How does it work:
* first calculate $sum of all values already in the set
* for 0 .. 1008 -> $a:
+ $v = sum + $a modulo 1009 (yes, I like prime numbers)
+ if the value $v is over 1000, then try the next number
+ if the value exists already in the set, we can't use it, try next number
+ if running the remove phase on this set gives the wrong result, try next number
+ yay, we found number that works!
Decoding:
* if there's 0 or 1 elements, return empty set
* sort the set to have consistent results
* loop again over all numbers to calculate sum, but
+ get all sets with 1 element removed
+ calculate if that number equals the sum of the other numbers
+ if it's equal, we have a winner
The decoding just removes the first number it finds that equals the sum of the other digits. If none is found it finds the first number that equals the sum of the other numbers + 1. If none ... +2, etc.
Some perl6 syntax:
* `^1009` is same as `0..1008` == (0,1,2,3,4,5,...,1007,1008)
* `[+] @set` calculates sum of all elements of @set; `[and]` is also the `and` operator applied to a list of boolean values
* `Z` is the zip operator, it zips 2 or more lists into a list of tuples: `(1,2) Z (3,4)` is same as `((1,3), (2,4))`
* `Z==` applies the `==` to each pair, giving a list of Booleans
* `1009 R% $sum` == `$sum % 1009` standard modulo calculation
[Answer]
### APL - 73 89 106+ characters, depending on the set's length
**Note:** So that it'd be easier for the OP to validate, I combined integer *a* with set *b* into set *c*. This way, he could view the set before phase 3 and after phase 3.
```
n←[enter set's length here]
z←(n+1)?1000
a←z[⍴z]
b←z[⍳(¯1+⍴z)]
c←a,b
c
c[n?n]←c[n?n]
c
c←c-a
d←¯1001×0⍷c
c←c+d
c←c[⍒c]
c←c+a
e←¯1+⍴c
c←e⍴c
a
b[⍒b]
c
```
Where `n` is equal to the set's length. **Don't forget to set *n* at the top!**
**How it works:**
`n←[enter set's length here]` stores the chosen length for the set as *n*
`z←(n+1)?1000` creates an array called *z* that contains *n* + 1 unique random numbers from 0 to 1000. We will use the last number of *z* as the integer to add to the set of other unique numbers
`a←z[⍴z]` stores the last number of *z*, or *z[length of z]*, as *a*, the number we will add to the set
`b←z[⍳(¯1+⍴z)]` stores all of the data in *z*, or *z[0 thru length of z - 1]*, as *b* the set that *a* will be added to
`c←a,b` combines arrays *a* and *b* into one array, *c*
`c` displays *c* so the OP can see that I added *a*
`c[n?n]←c[n?n]` scrambles the data by swapping cells based on *n* unique random numbers
`c`, once again, displays *c*
`c←c-a` subtracts *a* from all of the values in *c* so as to nullify *a*, which was our added value
`d←¯1001×0⍷c` creates a new array by multiplying -1001 by a binary "map" of *c* (which finds our 0 for us and looks something like this: 0 0 0 1 0, where 1 marks the location of the 0 in *c*)
`c←c+d` adds to *d* to *c* in order to turn the 0 that used to be *a* into ¯1001, which is one above the maximum number, 1000
`c←c[⍒c]` orders our data in *c* from greatest to least. This pushes our ¯1001 all the way to the right
`c←c+a` restores our original data from *b* by reversing the `c←c=a` we did earlier
`e←¯1+⍴c` creates a variable, *e*, that is equal to the length of *c* - 1
`c←e⍴c` decreases the length of *c* by 1 and does so by creating a shape with a length equal to *e*, that contains the data from *c*, but does not have what used to be *a* because the length decreased and *a* was on the right end
`a` displays *a*
`b[⍒b]` displays *b* from greatest to least
`c` displays *c*
[Answer]
# **366 Characters** - Python 2
```
i=lambda v,c,m,j:[h(s(v,m)+[j],x) for x in range(c+1)]
h=lambda v,c:hash(','.join(map(str,sorted(v)+[c])))%1001
a=lambda v,c=0:v+[h(v,c)] if t(h(v,c),v,c) else a(v,c+1)
s=lambda v,m:[n for n in v if n!=m ]
w=lambda v,c=0:s(v,o(v,c)[0]) if len(o(v,c))==1 else w(v,c+1)
o=lambda v,c:[m for m in v if h(s(v,m),c)==m]
t=lambda j,v,c:all([m not in i(v,c,m,j) for m in v])
```
Could probably be golfed more, I didn't spend too much time on it. Call `a` with a list of integers to add a number, and call `w` with a shuffled version of the new list to remove that number.
Works by appending a loop counter to the sequence, and choosing as the additional number the hash modulo 1001 the concatenated sequence. If the hash generated results in a sequence where there is only *one* number that can be removed to generate itself for every possible value of the loop counter up to the current one, then output the sequence. Otherwise increment the loop counter and try again. To decode, remove each item from the sequence and see if the hash value of the remaining sequence+loop counter is the removed value. If only one value matches these criteria, it is the solution, otherwise increment the loop counter and try again. This version will hang if faced with an unencodable sequence due to the entire space being taken up by hash collisions, but a check can trivially be added to the `a` function to simply output that the sequence is unencodable.
Confirmed to work for at least all sets of 2 or less, and works with decreasing probability for larger sets. Higher probabilities might be reachable with a better hash function but that would require more characters. I did some quick random sampling to see what the probability of being able to encode an input sequence of a given size was via this method (you'll notice the precision going down as I got less and less patient):
```
Size Probability
5 100.00%
10 100.00%
50 100.00%
100 100.00%
200 98.3%
400 73%
800 8%
```
Anyone who wants to play with it can use the following version which will output whether a sequence is or is not encodable:
```
i=lambda v,c,m,j:[h(s(v,m)+[j],x) for x in range(c+1)]
h=lambda v,c:hash(','.join(map(str,sorted(v)+[c])))%1001
a=lambda v,c=0:v+[h(v,c)] if t(h(v,c),v,c) else a(v,c+1) if len(set([n for m in v for n in i(v,c,m,h(v,c))]))<999 else None
s=lambda v,m:[n for n in v if n!=m ]
w=lambda v,c=0:s(v,o(v,c)[0]) if len(o(v,c))==1 else w(v,c+1)
o=lambda v,c:[m for m in v if h(s(v,m),c)==m]
t=lambda j,v,c:all([m not in i(v,c,m,j) for m in v])
if __name__ == "__main__":
from random import shuffle,randrange,sample
from operator import eq
from itertools import combinations
def random_combination(iterable, r):
"Random selection from itertools.combinations(iterable, r)"
pool = tuple(iterable)
n = len(pool)
indices = sorted(sample(xrange(n), r))
return tuple(pool[i] for i in indices)
valid=invalid=0
for z in range(100): #change to test more cases
r=list(sorted(random_combination(range(1001),randrange(1,100)))) #change to test longer sequences
d=a(r)
if d is None:
invalid+=1
continue
shuffle(d)
e=sorted(w(d))
if not all(map(eq,r,e)):
raise Exception("Incorrect",r)
valid+=1
print "%d Valid, %d Invalid"%(valid,invalid)
```
] |
[Question]
[
**This question already has answers here**:
[Code Golf of Death [closed]](/questions/6249/code-golf-of-death)
(12 answers)
Closed 10 years ago.
A shortest C program, that can crash the Operating system, either on a Windows or a Linux PC...
**Rules**:
* The code is to be developed in C language, but it may use other api, specific to linux or windows systems.
* The Operating System is said to have been put out of commission, if either it has come to a state[Standstill or otherwise] , where no matter how much time passes, the system is rendered inoperable or (even better), self restarts itself, or something similar to a [blue screen of death](http://en.wikipedia.org/wiki/Blue_Screen_of_Death).
* To be most effective, the program will be run as a normal user and not as superuser or an administrator.
* For every valid program that is able to crash the PC, countermeasures can be suggested by others in the comments, successful measures that can nullify the effect of the program gets the answer invalidated. For Example - If an answer suggests use of fork Bombs, i would suggest measures like [this](https://superuser.com/questions/566958/how-to-stop-and-detect-the-fork-bomb/) in the comments.
* Since Linux OS is considered more stable, a program that crashes linux is always a better one, even if it takes extra code than it takes to crash windows, but still the smallest program to crash the OS wins, independent of the platform.
* The community is free to edit the question to add more *sensible* rules, provided the new rules maintain compatibility with existing answers.
Note: This above question is asked with the purpose of demonstrating the raw power of C[or the lack of it] as a low level/mid level language. Also hopefully, to become more aware of OS security, and possible measures that can be taken.
**EDIT:**
A similar question lies here [Code Golf of Death](https://codegolf.stackexchange.com/questions/6249/code-golf-of-death)...
But here are the reasons my question differs from the above mentioned one...
1. I am looking for the answers to only be in C language.
2. Though the above question has one answer in C, the code works only for a rare version of pentium 5. So in short there is no C language based answer in the above question to achieve the end purpose.
3. In the other question Kernel-mode drivers are allowed, but my question concentrates mainly on user space processes.
4. Some of the answers in the above question allow the programs to run in supervisor/administrator mode, but such privileged execution of the program is not allowed in the rules stated by my question.
5. In the similar question the answer with highest upvotes win, in my question answer which crashes the OS , using the shortest code, and does so without any suggestion of countermeasure to be taken against the method employed by the answer.
6. **In short, apart from the same intention of crashing the OS , the two questions differ in every other aspect.**
[Answer]
## 29 chars
### Linux
```
int main(){system("init 6");}
```
I know, very lame. But hey, it reboots the system. Wasn't that the task?
### Windows 38 chars
```
int main(){system("shutdown.exe /r");}
```
Works as normal user.
] |
[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 5 years ago.
[Improve this question](/posts/7282/edit)
Starting from an array of sub-arrays, each sub-array is a 2 elements key|value pair. Example
```
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
```
Convert this into a hash that has distinct keys from above, with values summed up, so the above would be:
```
output = {"A" => 17, "B" => 0, "C" => 7}
```
[Answer]
## Ruby
```
input.each_with_object(Hash.new(0)) { |(k, v), h| h[k] += v }
```
(see <http://api.rubyonrails.org/classes/Enumerable.html#method-i-each_with_object>)
[Answer]
## Perl
Hopefully this thread won't get tagged code-golf
```
use strict;
use warnings;
my $a = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]];
my %h = ();
map { $h{shift @$_} += shift @$_ } @$a;
while (my ($k, $v) = each %h)
{
print "$k = $v $/";
}
```
Output:
```
$ perl cg-arraysum.pl
A = 17
C = 7
B = 0
```
[Answer]
# k
This can probably be shortened from 17 chars but:
```
{+/'(*|+x)(=*+x)}
```
Example:
```
k)x:(("A";5);("B";2);("A";12);("B";-2);("C";7))
k){+/'(*|+x)(=*+x)}x
"ABC"!17 0 7
```
or with output in q output format:
```
A| 17
B| 0
C| 7
```
[Answer]
## There's more than one way to do it (Perl)
Preparation:
```
$input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]];
```
I have three Perl snippets to solve the problem because the obvious code is kinda boring. It looks like this:
```
$output1{$_->[0]} += $_->[1] for @$input;
```
I'm a fan of list expressions, so here's a single list expression, I had to use [map](http://p3rl.org/map) and his friend [grep](http://p3rl.org/grep) a lot:
```
%output2 = map {
$c = $_ => sum map $_->[1] => grep $_->[0] eq $c => @$input
} keys %{{map @$_ => @$input}};
```
Many years I tried to find a non-trivial use-case for [List::Util](http://p3rl.org/List%3a%3aUtil)s **reduce** function which folds list elements with a given function, and finally here it is. A second single list expression, btw. \o/
```
$output3 = reduce {
$a = {@$a} if ref $a eq 'ARRAY'; $a->{$b->[0]} += $b->[1]; $a;
} @$input;
```
[Answer]
## C
Assumes keys are 'A'..'Z', assumes values are numbers, assumes input format is exactly spaced/formatted as specified in example.
```
char*p;c[99],m[99];
main(int i,char**v){
for(p=v[1]+1;*p==91;){
c[p[2]]+=atoi(p+5);
m[p[2]]=1;
for(;*p-93;p++);
p+=p[1]-44?1:3;
}
printf("{");
for(p="";++i<99;)if(m[i])printf("%s\"%c\" => %d",p,i,c[i]),p=", ";
printf("}\n");
}
```
Run as:
```
./a.out '[["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]'
```
Output:
```
{"A" => 17, "B" => 0, "C" => 7}
```
[Answer]
# R - 20 chars
```
aggregate(.~k,x,sum)
```
where `x` is the input defined here:
```
x <- data.frame(k = c("A", "B", "A", "B", "C"),
v = c(5, 2, 12, -2, 7))
x
# k v
# 1 A 5
# 2 B 2
# 3 A 12
# 4 B -2
# 5 C 7
```
The output:
```
aggregate(.~k,x,sum)
# k v
# 1 A 17
# 2 B 0
# 3 C 7
```
[Answer]
# Mathematica
In Mathematica the input array would be represented as `n = {{"A", 5}, {"B", 2}, {"A", 12}, {"B", -2}, {"C", 7}};`.
**Code**
```
{#[[1, 1]], Total@##[[All, 2]]} & /@ GatherBy[n, First]
```
>
> {{"A", 17}, {"B", 0}, {"C", 7}}
>
>
>
---
**Explanation**
`GatherBy[n, First]` gathers the data by the first element in each subarray (sublist).
>
> {{{"A", 5}, {"A", 12}}, {{"B", 2}, {"B", -2}}, {{"C", 7}}}
>
>
>
`Total@##[[All, 2]]` sums the second elements for each string, `#[[1, 1]]` (in this case, for "A", "B", and "C").
[Answer]
# Python 52 43
```
{X:sum(y for Y,y in a if Y==X)for X,x in a}
```
The input array is in `a`
This is fairly inefficient because it calculates the sum of all the 'A' keys for every occurrence of the 'A' key, but it works and since there aren't really any winning criteria I decided to golf my answer as much as possible.
**Edit:** Removed some unnecessary brackets and indices per recommendation from Daniero
[Answer]
### Python
```
output = {};
for x,y in input:
output[x] = y + ( output.get(x) or 0 )
```
Thanks for @Daniero's comment.
[Answer]
# ruby, 40 (or 38)
```
h=Hash.new(0);input.map{|k,v|h[k]+=v}
h
```
`h` contains the result.
The 38-char solution creates the wanted result, the 40 characters solution returns the result.
The result as complete testcode:
```
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
output = {"A" => 17, "B" => 0, "C" => 7}
h=Hash.new(0);input.map{|k,v|h[k]+=v}
p h == output #true
```
A little variant (but with the same size):
```
h={};input.map{|k,v|h[k]=(h[k]||0)+v}
```
[Answer]
# TXR
```
@(do (let ((h (hash :equal-based)))
(each ((entry '(("A" 5) ("B" 2) ("A" 12) ("B" -2) ("C" 7))))
(inc [h (first entry) 0] (second entry)))
(format t "~a\n" h)))
```
Run:
```
$ txr sumhash.txr
#H((:equal-based) ("A" 17) ("B" 0) ("C" 7))
```
What if we take the question literally? The question says that the input is this:
```
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
```
and that the output looks like this:
```
output = {"A" => 17, "B" => 0, "C" => 7}
```
Fair enough. We can make a program to transform that exact input to that exact output, rather than massaging the data to fit the syntax of our programming language.
```
input = [@(coll :vars (key value))["@key", @{value /[+\-]?[0-9]+/}]@(last)]@(end)
@(bind (keyout valout) @(let ((h (hash :equal-based)))
(each* ((k key)
(v [mapcar (op int-str @1 10) value]))
(inc [h k 0] v))
'(,(hash-keys h) ,(hash-values h))))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)
```
Run:
```
$ txr sumhash2.txr - # input read from stdin
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
<user types Ctrl-D>
output = {"A" => 17, "B" => 0, "C" => 7}
```
Empty case:
```
$ txr sumhash2.txr -
input = []
<Ctrl-D>
output = []
```
Invalid input:
```
$ txr sumhash2.txr
foo
<Ctrl-D>
false
```
Word `false` is output, termination status is failed.
Simplified version in which hashing is worked into data acquisition (side effects during pattern matching):
```
@(bind h @(hash :equal-based))
input = [@(coll)["@key", @{value /[+\-]?[0-9]+/}]@\
@(do (inc [h key 0] (int-str value 10)))@\
@(last)]@(end)
@(bind (keyout valout) (@(hash-keys h) @(hash-values h)))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)
```
[Answer]
## Javascript 79
```
function f(a){r={};for(e in a){i=a[e][0];j=a[e][1];r[i]=r[i]?r[i]+j:j}return r}
```
Test :
`f([["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]])`
Outputs :
`Object {A: 17, B: 0, C: 7}`
[Answer]
# Swift 4
**Optimized for clarity, not character count.** Replace the input as needed or pass it in some other way (e.g. through an I/O class).
```
import Darwin // or Glibc if on Linux
let input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
var output: [String: Int] = [:]
for pair in input {
guard let key = pair[0] as? String else {
fputs("Input error: key '\(pair[0])' is not a string\n", __stderrp)
exit(1)
}
if output[key] == nil { // the first of this key
output[key] = 0 // have to add to something, so put in 0
}
output[key]! += pair[1] as? Int ?? 0
}
for pair in output.sorted(by: <) {
print("\(pair.key): \(pair.value)")
}
```
---
### Bonus!
* Error handling:
+ If you input keys that aren't strings, it will give an error message and exit.
+ If you input values that aren't integers, it will silently assume they're 0.
* The output is sorted.
[Answer]
# Java 8
Here's an approach that uses streams:
```
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;
```
```
public static Map<?, Integer> collect(Object[][] pairs) {
return Stream.of(pairs)
.collect(Collectors.groupingBy(
pair -> pair[0],
HashMap::new,
Collectors.reducing(
0,
pair -> (Integer) pair[1],
Integer::sum
)
))
;
}
```
Uses a collector that groups elements into a map based on their first element, with duplicate values reduced by addition.
Or there's the classic loop version:
```
public static Map<?, Integer> collect(Object[][] pairs) {
Map<Object, Integer> map = new HashMap<>();
for (Object[] pair : pairs) {
Object k = pair[0];
int v = (Integer) pair[1];
map.put(k, map.getOrDefault(k, 0) + v);
}
return map;
}
```
[Answer]
# Java - 71
```
<T> Map m(final T[][] i) {
return new HashMap() {
{ for (T[] p : i) put(p[0], p[1]); }
};
}
```
The following...
```
System.out.println(m(new Object[][] {
{ "A", 5 }, { "B", 2 }, { "A", 12 }, { "B", -2 }, { "C", 7 }
}));
```
produces:
>
> `{A=12, B=-2, C=7}`
>
>
>
] |
[Question]
[
Your task is to write a function which accepts a number N and creates a string of [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) which will generate that number. Valid operations are:
```
1-9: Push number onto stack. Only 1-9 are allowed.
+-*/%: take two numbers from top of stack and apply arithmetic operation,
pushing the result.
d: duplicate - push a copy of the top of the stack
```
That's all. For - / and % which are order dependent, the operand which was pushed first goes first. ie `63/ = 2` `63- = 3` and `64% = 2`
Entries are judged not by brevity of code, but by the size of the generated strings. The smaller the better. I also want to encourage pushing smaller numbers rather than bigger ones. The score for a number is calculated like so:
```
For any number pushed, add that number to the score.
For every operand (+-*/%d) add 1.
```
Your final score is the sum of your score for all numbers 0 to 10,000 inclusive. Lets go ahead and limit total running time to two minutes for all 10k, on a reasonable machine, to avoid too much brute forcing.
If you can do it only pushing 1s, go ahead and subtract 10% from your score.
[Answer]
### Score 199503, Java solution
```
import java.util.HashMap;
import java.util.HashSet;
public class RPN {
public static void main(String[] args) {
// Loop to calculate total over all 10001 numbers as defined in puzzle
int total = 0;
System.out.println("n\tscore\trpn");
for (int k = 0; k <= 10000; k++) {
final String rpn = findRPN(k);
final int scr = calcScore(rpn);
System.out.println(k + "\t" + scr + "\t" + rpn);
total += scr;
}
System.out.println("TOTAL: " + total);
}
// simple scoring calculator for a given rpn representation (ignores 10% bonus)
private static int calcScore(String rpn) {
int score = 0;
for (char ch : rpn.toCharArray()) {
if (Character.isDigit(ch)) {
score += ch - '0';
} else {
score++;
}
}
return score;
}
// hashmap caching intermediate results and all results for 0<=n<=10000
final static int max = 6000000;
final static HashMap<Integer, String> rpns = new HashMap<Integer, String>();
// maximum score expected for numbers 0<=n<=10000
final static int maxScore = 26;
private static void preCalculate() {
// hashmap which contains all numbers with a given score
final HashMap<Integer, HashSet<Integer>> perScore = new HashMap<Integer, HashSet<Integer>>();
// numbers are build by combining those with lower score
for (int sc = 1; sc <= maxScore; sc++) {
final HashSet<Integer> currentScore = new HashSet<Integer>();
perScore.put(sc, currentScore);
// 1-9 can be reached directly by pushing
if (sc < 10 && !rpns.containsKey(sc)) {
rpns.put(sc, Integer.toString(sc));
currentScore.add(sc);
}
if (sc > 2) {
// score is increased by 2 if appending "d+" or "d*" to an existing rpn
for (int n : perScore.get(sc - 2)) {
String rpn_n = rpns.get(n);
consider(n * 2, currentScore, rpn_n, "d+");
consider(n * (long)n, currentScore, rpn_n, "d*");
}
}
// another possibility to get score sc is to take two operands
// with scores sc1 and sc2 and add another operator
// with the requirement that sc1 + sc2 + 1 = sc
for (int sc2 = 1; sc2 <= sc - 2; sc2++) {
int sc1 = sc - sc2 - 1;
HashSet<Integer> l1 = perScore.get(sc1);
HashSet<Integer> l2 = perScore.get(sc2);
// try all combinations of operators from list 1 and list 2
// with each operator + - * / and %
for (int n : l1) {
String rpn_n = rpns.get(n);
for (int m : l2) {
String prefix = rpn_n + rpns.get(m);
// Commutative operators - only need to consider them once
if (n < m) {
consider(n + m, currentScore, prefix, "+");
consider(n * (long)m, currentScore, prefix, "*");
}
// Non-commutative operators.
consider(n - m, currentScore, prefix, "-");
// div and mod only possible if m!=0
if (m != 0) {
consider(n / m, currentScore, prefix, "/");
consider(n % m, currentScore, prefix, "%");
}
}
}
}
}
}
private static void consider(long value, HashSet<Integer> currentScore, String prefix, String suffix) {
if (value < -max || value > max) return;
Integer r = Integer.valueOf((int)value);
if (!rpns.containsKey(r)) {
rpns.put(r, prefix + suffix);
currentScore.add(r);
}
}
private static String findRPN(int number) {
if (rpns.isEmpty()) {
preCalculate();
}
// if number is negative try 1(-n+1)-
if (number < 0) {
return "1" + findRPN(-number + 1) + "-";
}
// if number not in precalculated list try number/2
if (!rpns.containsKey(number)) {
if (number % 2 == 0) {
return findRPN(number / 2) + "d+";
} else {
return findRPN(number / 2) + "d+1+";
}
}
// otherwise use cached result
return rpns.get(number);
}
}
```
The solution is pretty much optimized to get a good score within the defined range of numbers (i.e. 0 to 10000). It sacrifices non-optimal solutions outside the range for (hopefully) optimal representations within. Nevertheless it will still work for other numbers too.
I think the score given by that solution is very close to optimal although I'm not able to prove it.
**Output:**
```
n score rpn
0 3 11-
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 5 3d+
7 7 7
8 6 4d+
9 5 3d*
10 7 5d+
11 8 3d*2+
12 7 3d+d+
...
9990 19 5d+d*d*3d*-1-
9991 17 5d+d*d*3d*-
9992 18 5d*d+d*2-d+d+
9993 19 5d+d*d*3d+-1-
9994 17 5d+d*d*3d+-
9995 17 5d+d*d*5-
9996 16 5d+d*d*4-
9997 15 5d+d*d*3-
9998 14 5d+d*d*2-
9999 13 5d+d*d*1-
10000 11 5d+d*d*
TOTAL: 199503
```
[Answer]
## JavaScript, 217597
```
var minNum = new Uint32Array(10001), minMA = ['11-','1','2'];
minNum[0] = 3;
minNum[1] = 1;
minNum[2] = 2;
for(var tr=2,i=2,sum=0;i<=1e4;i++){
var minVal=i<10?i:9e9,j,minMethod=i<10?''+i:'';
if(tr*tr*tr==i){
if(minNum[tr]+4<minVal) minVal=minNum[tr]+4,minMethod=minMA[tr]+"dd**";
tr++;
}
for(j=1;j<10&&j<i;j++) if(minVal>minNum[i-j]+minNum[j]+1) minVal=minNum[i-j]+minNum[j]+1,minMethod=minMA[i-j]+minMA[j]+'+';
if(i>2) for(j=2;j<10&&i>j;j++) if(i%j==0){
if(minVal>minNum[i/j]+minNum[j]+1) minVal=minNum[i/j]+minNum[j]+1,minMethod=minMA[i/j]+minMA[j]+'*';
if(minVal>minNum[i/j]+2*(j-1)){
minVal=minNum[i/j]+2*(j-1);
for(minMethod=minMA[i/j],dd='',pp='',k=j-1;k-->0;dd+='d',pp+='+'); minMethod+=dd+pp;
}
}
for(j=10;j<Math.sqrt(i);j++) if(i%j==0){
if(minVal>minNum[i/j]+minNum[j]+1) minVal=minNum[i/j]+minNum[j]+1,minMethod=minMA[i/j]+minMA[j]+'*';
if(minVal>minNum[i/j]+2*(j-1)){
minVal=minNum[i/j]+2*(j-1);
for(minMethod=minMA[i/j],dd='',pp='',k=j-1;k-->0;dd+='d',pp+='+'); minMethod+=dd+pp;
}
}
if(Math.sqrt(i)==~~Math.sqrt(i)) if(minVal>minNum[Math.sqrt(i)]+2) minVal=minNum[Math.sqrt(i)]+2,minMethod=minMA[Math.sqrt(i)]+'d*';
minNum[i] = minVal; minMA[i] = minMethod;
console.log(i,minVal,minMethod);
}
for(i=0;i<=10000;i++){
sum+=minNum[i];
}
console.log("Score : "+sum);
```
Quite trivial solution... does not use `-`, `/`, and `%` at all.. :P
I can add the case for n^5, n^7, ..., but that doesn't reduce the score quite well (only ~400).
This problem reminds me of some PE problems... (not saying that this is a part of a PE problem)
```
2 2 "2"
3 3 "3"
4 4 "4"
5 5 "5"
6 5 "3d+"
7 7 "7"
8 6 "2dd**"
9 5 "3d*"
10 7 "3d*1+"
11 8 "3d*2+"
12 7 "3d+d+"
13 9 "3d+d+1+"
...
9990 25 "3d+d*1+3dd***5*d+"
9991 27 "3d+d*1+3dd***5*d+1+"
9992 27 "4d*d*3d+d*3+*2dd**+"
9993 26 "4d*d*3d+d*3+*3d*+"
9994 27 "4d*d*3d++1+3d+d*2+*"
9995 27 "3d+d*1+3dd***d+1+5*"
9996 23 "7d+d*5d*d+1+*"
9997 24 "4d*d*3*1+3d+d+1+*"
9998 26 "4d*d*3*1+3d+d+1+*1+"
9999 25 "3d*1+d*1+7d*d+1+*"
10000 11 "3d*1+d*d*"
Score : 217597
```
[Answer]
Here's my baseline solution in C#:
```
string Make(int n)
{
if(n < 0) return "1" + Make(-n) + "1+-";
if(n == 0) return "11-";
if(n == 1) return "1";
if(n % 2 == 0) return Make(n / 2) + "d+";
return Make(n / 2) + "d+1+";
}
public void CalcTotal()
{
var total = Enumerable.Range(0, 10001).Sum(x => Make(x).Length);
Console.WriteLine(total);
}
```
Gets a score of `346491 - 10% = 311841.9`
] |
[Question]
[
On [Pomax's Primer on Bézier Curves](https://pomax.github.io/bezierinfo/#canonical) this "fairly funky image" appears:

This is related to the fact that every cubic Bézier curve can be put in a "canonical form" by an affine transformation that maps its first three control points to (0,0), (0,1) and (1,1) respectively. Where the fourth and last control point lies after the transformation then determines the curve's nature – suppose it lies at \$(x,y)\$, then
* If \$y\ge1\$ the curve has a **single inflection point** (green region in the image).
* If \$y\le1\$ but \$y\ge\frac{-x^2+2x+3}4\$ and \$x\le1\$ the curve has **two inflection points**.
* If \$y\le\frac{-x^2+3x}3\$ and \$x\le0\$ or \$y\le\frac{\sqrt{3(4x-x^2)}-x}2\$ and \$0\le x\le1\$ or \$y\le1\$ and \$x\ge1\$ the curve is a **simple arch** with no inflection points.
* In all other cases the curve has a **loop** (red region in the image).
## Task
Given the coordinates of the transformed curve's fourth point \$(x,y)\$ in any reasonable format, output the curve's type, which is exactly one of "arch", "single inflection", "double inflection" or "loop". If \$(x,y)\$ is on the boundary between two or more regions you may output the type corresponding to any of those regions. You may also use any four distinct values to represent the curve types.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
## Test cases
```
(x,y) -> type(s)
(2,2) -> single
(-1,2) -> single
(2,0) -> arch
(1,-2) -> arch
(-1,-2) -> arch
(-2,0) -> double
(-3,-1) -> double
(-1,-1) -> loop
(-3,-4) -> loop
(0,1) -> single or double
(-1,0) -> double or loop
(-3,-3) -> double or loop
(0,0) -> arch or loop
(2,1) -> arch or single
(1,1) -> single or double or arch or loop
```
[Answer]
# JavaScript (ES6), 55 bytes
*-2 thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
Returns \$false\$, \$true\$, \$2\$ or \$3\$ for *double*, *loop*, *arch* and *single* respectively.
```
x=>y=>y>1?3:y<x-x*x/3|y*y<x*(3-x-y)|x>1?2:4*y<3-x*x+2*x
```
[Try it online!](https://tio.run/##dZA7b4MwFIX3/IorJhtsiO0MVRrolKVDO3REDJRHQoQwgrSypfx3ikNTHqKSpXv1netzrn2Jv@M2aYr6SiuZZl3ud8oPdH8C9iL2@qCospUnbtruexsJqqjGN9WrfL/rmTC6w23VPYcbgBCAE@AQEfA8aIvqVGZ3TNkqNtPbXxw3yXmAjFC@hHQVTq6n8uvzESYIZSuYjbiUsv6b3S0hbAmw2bYgm4XVItgMzEzF/7Kxn756LvIx@yFOf4zdZVhbzXQzv2jj5rI5xskZoRAUAQ0RBj@ARFatLDO3lCf0@vH@5rbXpjcrcj3OuXWcHqsUPWFwILSGCIuAZaxNNVGmDmtYUejkSGGkcYRx9wM "JavaScript (Node.js) – Try It Online")
### Logic
* If \$y>1\$, return \$3\$ (single inflection)
* If \$y<x-x^2/3\$ or \$y^2<x(3-x-y)\$ or \$x>1\$, return \$2\$ (simple arch)
* If \$4y<3-x^2+2x\$, return \$true\$ (loop)
* Otherwise, return \$false\$ (double inflection)
### Graphical output
Invoking the above function for each pixel in a 320x240 canvas.
```
f=
x=>y=>y>1?3:y<x-x*x/3|y*y<x*(3-x-y)|x>1?2:4*y<3-x*x+2*x
for(ctx = document.getElementById('c').getContext('2d'), Y = 0; Y < 240; Y++) for(X = 0; X < 320; X++) { y = (Y - 80) / 100; x = (X - 160) / 100; ctx.fillStyle = X == 160 || Y == 80 || X % 100 == 60 && Y & 2 || Y == 180 && X & 2 ? "#000" : [ "#8cf", "#f44", "#fe4", "#999" ][+f(x)(y)]; ctx.fillRect(X, Y, 1, 1); }
```
```
<canvas id="c" width=320 height=240></canvas>
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
NθNη¿‹¹ηS¿∨∨‹¹θ‹η⁻θ∕×θ賋×ηη×θ⁻³⁺θηA§DL‹×η⁴⁺³×θ⁻²θ
```
[Try it online!](https://tio.run/##ZY7RDoIgGIXve4p/XMFGW2Z3Xrl542blVi9gSoMNMUFdb08C6lqdccHh/zj/qXml666S1ubqNQ6XsX0wjXuS7L49n714Ai6YMTiiwAmBUgs1YHRD84xJw8ABV@3OivWEgr9zCmehRoN7CpmYRMPwXbTMewfFZNbChgF3SyhsVPgeUyhliOHEa62RbjXCQzrkqmFvjLIC/QafyBIT/y04uj5eibURHOx@kh8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs one of `A`, `D`, `S` or `L`. Explanation:
```
NθNη
```
Input the coordinates.
```
¿‹¹ηS
```
Check for a single inflection.
```
¿∨∨‹¹θ‹η⁻θ∕×θ賋×ηη×θ⁻³⁺θηA
```
Check for a simple arch.
```
§DL‹×η⁴⁺³×θ⁻²θ
```
Distinguish between a double inflection and a loop.
Here's an SVG I wrote because the original image was drawn on a canvas for some reason:
```
<svg viewbox=-3,-6,5,8><path d=M2,2H-3V-6H2 fill=#f44 /><path d=M2,2H-3V1H2 fill=#999 /><path d=M-3,1V-3Q-1,1,1,1Z fill=#8cf /><path d=M-3,-6Q-1.5,-1.5,0,0A2.449489742783178,1.4142135623730951,135,0,0,1,1H3V-6Z fill=#fe4 />
```
] |
[Question]
[
Usually each cell in brainfuck has 256 states, which is not enough to tell whether input is EOF or a character (usually `\xFF`). To fix it we can add one more state to it, and EOF (256) isn't mistake from a byte.
Since outputting EOF is also not defined, `.` on 256 works as reading, and therefore `,` is removed from the modified version.
Given a program in the 256-wrap brainfuck, provide a 257-wrap brainfuck program with same behavior when an infinite stream is provided as input. Memory needn't remain same though.
Sample:
```
,. => -..
+[+++>+<]>. => +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
,[.,] => -.[.[-]-.]
-[.-] => --[.-]
+[,.[-]+] => +[>-.[-]+]
+[,.[-]+] => +[>-.+]
,+. => -.++[->+>+<<]>->[<]>.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code (converter) in each language wins.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 87 86 bytes
```
lambda s:"".join([3*c,p:="++[->>+<]>[-<]<","[-]-.",p*255,c][ord(c)%31%11%7]for c in s)
```
[Try it online!](https://tio.run/##Rc7BCoMgHIDxu08hQqD5V2gRG1G@iPPQipijVNRLT@9alx2/3@kLR3571z5CLOv4LNu0v5YJp54Q@fHWUd3WM4R@JJxroRQfjNJiMAMBooURkkCob10Hs9E@LnRmVdtUTVPdzeojnrF1OLFi9@BjxulI6MfbxUeSKS/W9QiHaF2m29nRBsqACEVg/QNjhSOBJAIEEnHNOb9WTtASzBc "Python 3.8 (pre-release) – Try It Online")
Basically the idea is that we only use every third cell to store the memory that the input program uses. The other cells are simply zero. This gives space to implement the addition code. The addition code is as follows:
`++[->>+<]>[-<]<`
Let's see how this works. There are two possibilities, either the cell has value of `255` or it has a lower value.
If the cell has value `255` then, after the first additions the value of the cell is now `0` (since it's mod 257). This means that the next loop won't execute at all. So we skip the first loop and move right. This square is 0, so we won't execute the next loop and we finally move left, back to the starting square, which has now value 0, meaning that we succeeded in doing `255->0`.
If the cell has some other value `x`, the first two additions will make the value of the cell `x+2` which is not zero. This means that the next loop will execute. We decrement this cell (value now is `x+1`) and move twice to the right. We increment that cell (now has value `1`) and move left. The cell we are on right now has also value 0, so the loop stops. We then move right, to find our cell which has value 1. We decrement it to leave it in a clean state and move left. Again, this cell has value 0, so the loop stops. Finally we move left once to get back to where we started, with the cell having value `x+1`
Decrementation is just addition 255 times. `[`, `.` and `]` don't need to be changed. We triplicate `>` and `<` since every third cell stores the "original" program values. Actually, we also triplicate `[` and `]`, but this doesn't have any effect on the execution of the program. For `,` we just zero the cell with `[-]` and then decrement once more to get value 256 and then use the dot.
] |
[Question]
[
The Levenshtein distance between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other. Let us call insertions, deletions and substitutions "edit operations". We will say that any sequence of \$k\$ edit operations that transforms one string into another one is optimal if \$k\$ is also the Levenshtein distance between the two strings.
For example, take the strings \$ab\$ and \$ba\$. The optimal sequence of edit operations "insert \$b\$ at index 0", "delete the final character" transforms \$ab\$ into \$ba\$. However a different optimal sequence "substitute the first character for a \$b\$", "substitute the second character for an \$a\$" also transforms \$ab\$ into \$ba\$. In general there may be many different optimal sequences of edit operations for a given pair of strings.
For an optimal sequence of edit operations we are interested in counting the number of substitutions in the sequence. In particular, for a given pair of strings, we want to count the smallest possible number of substitutions in an optimal sequence of edit operations and also the largest possible. We will assume that both strings have the same length.
# Example
```
0000 0000 . In this case every optimal sequence has length 0 and so min = max = 0.
0010 1001 . Levenshtein distance 2 by one insertion and one deletion. min = max = 0.
1100 1110 . Levenshtein distance 1. min = max = 1. There is no optimal sequence with an insertion or deletion.
1010 1100 . Levenshtein distance 2. min = 0. max = 2.
1010 0111 . Levenshtein distance 3. min = 1. max = 3.
0011 1100 . Levenshtein distance 4. min = 0. max = 4.
10000011 11110100. Levenshtein distance 6. min = 2. max = 6.
000111101110 100100111010. Levenshtein distance 5. min = 1. max = 5.
0011011111001111 1010010101111110. Levenshtein distance 7. min = 3. max = 7.
0010100001111111 0010010001001000. Levenshtein distance 7. min = 5. max = 7.
10100011010010110101011100111011 01101001000000000111101100000000. Levenshtein distance 15. min = max = 9.
11011110011010110101101011110100 00100010101010111010000000001110. min = 8. max = 12.
32123323033013011333111032331323 13100313103110123321321211233032. min = 6. max = 14.
17305657112546416613111655660524 23146332512152524313021536474017. min = 11. max = 21.
```
# Task
For a given pair of strings of the same length, output the minimum and maximum number of substitutions in an optimal sequence of edit operations for those two strings.
You can assume the input is given in any convenient form you choose and may similarly provide the output in any way that is convenient for you.
[Answer]
# JavaScript (ES10), ~~169 168~~ 161 bytes
*Saved 7 bytes thanks to @KevinCruijssen*
Takes the strings as `(s)(t)`. Returns `[min, max]`.
```
s=>t=>[[...Array(d=(g=(k,m=s.length,n=m,c)=>m*n?1+Math.min(g(k,m,n-1),g(k,--m,n),g(k-=c=s[m]!=t[--n],m,n)-!c):k?1/0:m-~n)())].flatMap((_,i)=>g(i)-d?[]:j=i)[0],j]
```
[Try it online!](https://tio.run/##lY7BToQwFEX3fgUzq1bb0jcmLkgexA@YL2ga0wDDwNAygcboxl/HFsUNjolv0d4m7/TczryaqRzbq@duqOr5hPOEucdcKSHE8ziad1IhaZBcmMVJ9LVr/Jk5tKykmNt7V8DD0fizsK0jTdxijgNlMXIeHkvkWOKkrN6hV5w7Hbco35U0uxSQyszyD0cJpVqceuOP5krIC2uDoCEt5VWhdNZhS5XUrNNzObhp6GvRDw05kb0Ms6frTZN10jQJpRJMrHkLp7zbcLBwEMJ/OIAvHwD85YMNt/rgRk/JvtHDLVQG568orOjjFo0TsaVx/Gmx/6CHFX2aPwE "JavaScript (Node.js) – Try It Online") (fast test cases)
[Try it online!](https://tio.run/##HY5NbsMgEEav4ng10wKGRTeWxlYPkBMgVCH8EzsGRwZVyaZXdyGzGL03@qT5VvtrozuWR@JhH8ZzojNSl6jTWgjxfRz2BQPBTHBnnqLYxjCnGwvkmUPq/Efo1efVppvwS4C5pFjgCllBzrO8kZOjqL25UNKcB1NSyC8O23uvGtl6/hcQEI2YNpuu9gHww5b8YIYF@dBr0660oJaGreZ0e4j7Noptn2GCWkqp8pQla4RaZX@fZHGsmqbK5SqqFKu8fWb4Ov8B "JavaScript (Node.js) – Try It Online") (a longer test case which may time out if TIO is overloaded)
## Commented
### Helper function \$g\$
\$g\$ is a function that computes the standard Levenshtein distance when it's called with \$k\$ undefined, or the edit distance with exactly \$k\$ substitutions when it's called with \$k\ge0\$. An additional offset of \$+1\$ is added to the result in both cases.
NB: It is presented separately for readability but must be defined within the scope of the main function so that the source string \$s\$ and the target string \$t\$ are defined.
```
g = ( // g is a recursive function taking:
k, // k = allowed number of substitutions, or undefined
m = s.length, // m = 1st pointer, initialized to the length of s
n = m, // n = 2nd pointer, initialized to the length of s
c // c = substitution cost
) => // (needs to be defined in the local scope)
m * n ? // if both m and n are greater than 0:
1 + // add 1 to the final result
Math.min( // add the minimum of:
g(k, m, n - 1), // recursive call for insertion with (m, n - 1)
g(k, --m, n), // recursive call for deletion with (m - 1, n)
g( // recursive call for substitution:
k -= // set c if s[m - 1] is not equal to t[n - 1]
c = s[m] != t[--n], // and decrement k if c is set
m, n // use (m - 1, n - 1)
) - !c // subtract 1 from the result if c is not set
) // end of Math.min()
: // else (leaf node):
k ? // if k is not equal to 0 or NaN:
1 / 0 // return +Infinity
// (to make sure that this branch is not chosen)
: // else:
m - ~n // return m + n + 1
```
### Main function
```
s => t => // s = source string, t = target string
[ // the final result is a pair:
[ // build an array containing:
...Array(d = g()), // d entries, where d = Levenshtein distance (+1)
] //
.flatMap((_, i) => // for each entry at position i in there:
g(i) // if the edit distance (+1) with i substitutions
- d ? // is not equal to d:
[] // reject this entry
: // else:
j = i // append it to the array and copy i to j
)[0], // end of flatMap(); return the 1st entry (minimum)
j // followed by the last entry (maximum)
] // end of result
```
] |
[Question]
[
Given a UTF-16 string, test its endianness.
**Rules:**
1. As long as the input is in UTF-16 **without BOM**, its type doesn't matter. In C++ on Windows, it can be `std::wstring` or `std::u16string`. In Haskell, it can be `[Int16]` or `[Word16]`.
2. The endianness is tested by noncharacters. If the input contains a noncharacter, it is in wrong endianness.
3. If the original version and the endianness-swapped version both or neither contain a noncharacter, the test is inconclusive.
4. The type of the output must be well-ordered. Output 1 (or an equivalent enumerator) when the input is in right endianness, or -1 (or an equivalent enumerator) when the input must be endianness-swapped, or 0 (or an equivalent enumerator) when the test is inconclusive. For example, in Haskell, `Ordering` is a valid output type.
5. Wrong UTF-16 sequences are also treated as noncharacters. (So the noncharacters are: Encodings of code point from U+FDD0 to U+FDEF, encodings of code point U+XXFFFE and U+XXFFFF with XX from 00 to 10, and unpaired surrogates.)
6. As this is a code golf, the shortest code in bytes wins.
**Examples:**
Assume we're in Haskell, the system is a big-endian, and `Ordering` is the output type. When given the following byte sequence:
```
00 00 DB FF DF FE
```
Because it encodes the noncharacter U+10FFFE, the output must be:
```
LT
```
For the following byte sequence:
```
00 00 00 00 00 00
```
The output must be:
```
EQ
```
For the following byte sequence:
```
FE FF
```
Since the endianness-swapped version encodes the noncharacter U+FFFE, the output must be:
```
GT
```
[Answer]
# ARM Thumb-2, ~~108~~ ~~90~~ 84 bytes
Machine code:
```
b5f2 2300 f000 f822 9900 000a 3a02 5a84
ba64 5284 d1fa 425b f000 f818 bdf2 5a44
f64f 56d0 1ba7 2f20 d313 0ae7 2f1b d10a
b179 3902 0ae7 d30c 5a42 0a97 2f36 d108
3209 eb04 2482 b227 3702 d202 3902 d5e6
3b01 4770
```
Commented assembly:
```
.syntax unified
.arch armv6t2
.text
.thumb
.globl check_utf16
.thumb_func
// r0: string, r1: len in BYTES
// The string will be clobbered as an internal buffer.
// Returns in r3.
check_utf16:
push {r1, r4, r7, lr}
// Set starting return value to 0. This will accumulate both results.
movs r3, #0
// First, check little endian.
// Yes, I did bl to the middle of a function. :P
bl .Ltest.entry
// Reload the length, as test clobbered it.
ldr r1, [sp]
// Byteswap the string.
movs r2, r1
.Lbswap_loop:
// Looping backwards...
subs r2, #2
// Load a halfword to r4,
ldrh r4, [r0, r2]
// do a 16-bit byteswap,
rev16 r4, r4
// and store it back.
strh r4, [r0, r2]
bne .Lbswap_loop
.Lbswap_loop.end:
// Negate r3 to make the start return value from native endianness positive.
// Then, we subtract the big endian version from this to get the -1/0/1 result.
negs r3, r3
// and call test again to check big endian
bl .Ltest.entry
pop {r1, r4, r7, pc}
.Ltest_loop:
// Read the next character
ldrh r4, [r0, r1]
// Check for FDD0-FDEF.
// First we subtract 0xFDD0...
movw r2, #0xFDD0
subs r7, r4, r2
// ...and if it is (unsigned) less than 0x20, it is
// bad. Return false.
cmp r7, #0x20
blo .Lfalse
// Is it a surrogate?
// Equivalent to (r4 & 0xF800) != 0xD800
lsrs r7, r4, #11
cmp r7, #0xD800 >> 11
bne .Lnot_surrogate
// NOTE: We are looping backwards, that is why we check
// trail surrogates first.
.Lis_surrogate:
// Beginning of string == unpaired surrogate == bad
cbz r1, .Lfalse
// Decrement r1
subs r1, #2
// Is it a trail surrogate? We already know it is
// a surrogate, so we only check the trail bit.
// Uses lsrs's carry flag to test the 10th bit.
// Equivalent to (r4 & 0x400) == 0
lsrs r7, r4, #11
bcc .Lfalse
// Load the preceeding (hopefully) lead surrogate to r2.
ldrh r2, [r0, r1]
// Is it a lead surrogate?
// Equivalent to (r2 & 0xFC00) != 0xD800
lsrs r7, r2, #10
cmp r7, #0xD800 >> 10
bne .Lfalse
// We have two surrogates, let's merge them into a
// full codepoint.
//
// Just kidding. We only need the low 16 bits, so we can take
// a huge shortcut and let sxth correct any overflow.
//
// utfcpp showed us that converting a UTF-16 pair to UTF-32
// is simply this:
// 0xfca02400 + trail + (lead << 10)
// where 0xfca02400 is the constant fold of this:
// 0x10000 - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN
//
// Since we are only using 16 bits, we can just add 0x2400
// instead. That saves 4 bytes, as we can do a wide add.
//
// HOWEVER, we can do even better: 0x2400 has the low 10 bits
// clear, and since we need to shift the lead surrogate 10
// bits to the left, we can just add 0x2400 >> 10 (or 0x09)
// to the lead surrogate, then do trail + (lead << 10).
//
// This means that instead of generating a 32-bit constant
// into a register, we can use the immediate narrow form of
// adds, saving 6 bytes (4 for literal, 2 for ldr).
adds r2, #0x2400 >> 10
add.w r4, r4, r2, lsl #10
.Lnot_surrogate:
// At this point, r4 contains the low 16 bits of the
// codepoint, and the upper bits are garbage.
// Check for xxFFFE/F by sign extending and adding 2.
// If it was, there will be a carry.
// The act of sign extending eliminates all of those
// garbage bits for us, allowing laziness in the surrogate
// code.
sxth r7, r4
adds r7, #2
bcs .Lfalse
.thumb_func
// We actually bl here, so we can subtract first
// on the first iteration.
// The possibilities of assembly are endless.
.Ltest.entry:
// Loop while we still have data.
subs r1, #2
bpl .Ltest_loop
.Ltrue:
// Subtract 1 for true. This is negated for native endianness, and it
// cancels out on both true.
subs r3, #1
.Lfalse:
// return
bx lr
```
Test suite:
```
.syntax unified
.arch armv6t2
.thumb
// W+X because PIE sucks.
.section ".writeable_text","awx",%progbits
.macro $TEST expected:req, argc:req, argv:vararg
// Load string buffer into r0
adr r0, 1f
// Convert element count to size in bytes by doubling.
movs r1, #\argc * 2
// Skip over our constant pool
b 3f
1:
// The UTF-16 string
.short \argv
.align 2
2:
// blatant abuse of macro stringification to avoid a printf loop :P
.asciz "\argv"
.align 2
3:
// Call check_utf16
bl check_utf16
// Stringified version of the UTF-16 string
adr r1, 2b
// Expected
movs r2, #\expected
// r3 is already in place
adr r0, .Lprintf_str
// printf("{ %s } -> expected: %d, got: %d\n", STR(arr), expected, retval)
bl printf
.endm
.globl main
.thumb_func
main:
push {r4, lr}
// Original test cases
$TEST -1, 3, 0x0000, 0xDBFF, 0xDFFE
$TEST 0, 3, 0x0000, 0x0000, 0x0000
$TEST 1, 1, 0xFEFF
// I've added more test cases, feel free to take them
// 1: D3FD becomes FDD3 when swapped, which is bad
$TEST 1, 3, 0xD3FD, 0xD83D, 0xDE0F
// 0: proper string with surrogates both ways
$TEST 0, 3, 0x0A00, 0xD83D, 0xDE0F
// -1: DF10 is a lone trail surrogate
$TEST -1, 1, 0xDF10
// 1: D9E0 is a lone head surrogate
$TEST 1, 1, 0xE0D9
// 0: 0xffff is invalid in both endiannesses
$TEST 0, 2, 0x0314, 0xFFFF
pop {r4, pc}
.Lprintf_str:
.asciz "{ %s } -> expected: %d, got: %d\n"
```
[Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/472309319#L560)
Has the following pseudo-signature:
```
int check_utf16(uint16_t *ptr, size_t length_in_bytes);
```
However, it is NOT C-callable, it returns in `r3` instead of `r0`.
Returns -1 if we need an endian swap, 0 if ambiguous, or 1 if we don't need an endian swap.
`lsrs` is the real MVP here. (☞^o^) ☞
Specifically, `lsrs`/`lsls` can do most usages of `ands` without setting up a constant or using a wide instruction. All of the "masking" operations can just be done by shifting right. This also lets us use a narrow `cmp`, as narrow `cmp` can only check `0-255`.
Additionally, I do a really dirty trick here: I only calculate the low 16 bits of a surrogate pair codepoint.
The optimized UTF-16 to UTF-32 conversion algorithm is this (magic number explained in comments):
```
uint32_t codepoint = 0xfca02400 + trail + (lead << 10);
```
However, `0xfca02400` is a 6 byte constant, 2 bytes for `ldr` and 4 bytes for the literal pool.
One thing to note is that I immediately discard the upper 16 bits of the codepoint by sign extending. Therefore, we only need to add the low 16 bits of the magic number, `0x2400`.
```
int16_t codepoint = 0x2400 + trail + (lead << 10);
```
This is much better, as we can do an immediate `add.w` instruction, saving 4 bytes.
However, `0x2400` has 10 trailing zero bits: it is simply `9 << 10`.
Therefore, we can do another optimization with the distributive property:
```
int16_t codepoint = trail + ((lead + (0x2400 >> 10)) << 10);
// int16_t codepoint = trail + ((lead + 9) << 10);
```
That is even better: we no longer need `add.w`, `9` fits perfectly into an immediate narrow `adds`, saving a total of 6 bytes!
] |
[Question]
[
Here is my ungolfed Ruby code for a function I want to try and golf:
```
Iter =-> k {
str = ""
(0..k).map{|m| str += "-> f#{m} {"}
str += "f#{k}.times{f1 = f0[f1]};f1"
(2..k).map{|m| str += "[f#{m}]"}
eval(str + "}" * (k+1))
}
```
The best I can do to golf this is essentially shortening variable names, removing spaces, and rearranging the code to reduce the amount of loops:
```
I=->k{s="f#{k}.times{f1=f0[f1]};f1"
(2..k).map{|m|s+="[f#{m}]"}
(0..k).map{|m|s="->f#{k-m}{"+s+?}}
eval s}
```
[Try it online!](https://tio.run/##VYxBCsIwEADveUVZL5WQ0PQqiee8YdlDhQYkBoqxUtnu22M9ep0Z5rnePq1Fb0Lm6iGdOIt93ctcOTmfBkyO5JIcqH60Np9tmRbey161BzzqIgSi@uHPeTDhdzJFGHTVVxE1v6dHV6UtXcSRMKIjQhM23rQTOlD7Ag)
This function can be compacted so that it avoids a lot of defining new functions. You can think of it like this:
$$\operatorname{Iter}(k;f\_0,f\_1,\dots,f\_k)=f\_0^{f\_k}(f\_1)(f\_2)(f\_3)\dots(f\_k)$$
where
$$f^n(x)=\underbrace{f(f(\dots f(}\_nx)\dots))$$
denotes function iteration. The types of arguments are given as:
$$\operatorname{Iter}(\text{int};\dots,(\text{int}\mapsto\text{int})\mapsto(\text{int}\mapsto\text{int}),\text{int}\mapsto\text{int},\text{int})$$
That is, the last argument is an integer, and each previous argument maps from T to T, where T is the type of the next argument on the right.
It is true that accepting all arguments at once would allow me to golf the above code further:
```
I=->k,*a{a[-1].times{a[1]=a[0][a[1]]};(2..k).map{|m|a[1]=a[1][a[m]]};a[1]}
```
However, the issue is that I need to [curry](https://en.wikipedia.org/wiki/Currying) this function. This way, I may treat objects such as
$$\operatorname{Iter}(k)(f\_0)$$
as their own object, and thus be able to pass this into Iter(k) to get things such as
$$\operatorname{Iter}(k)(\operatorname{Iter}(k)(f\_0))$$
As a specific example of what this function does, we have
\begin{align}\operatorname{Iter}(2)(\operatorname{Iter}(1))(x\mapsto x+1)(2)&=\operatorname{Iter}(1)(\operatorname{Iter}(1)(x\mapsto x+1))(2)\\&=\operatorname{Iter}(1)(x\mapsto x+1)(\operatorname{Iter}(1)(x\mapsto x+1)(2))\\&=\operatorname{Iter}(1)(x\mapsto x+1)(2+1+1)\\&=\operatorname{Iter}(1)(x\mapsto x+1)(4)\\&=4+1+1+1+1\\&=8\end{align}
>
> I'm interested in seeing if this can be golfed down further, with the restriction that the arguments must be curried in the order provided.
>
>
>
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~94~~ 96 bytes
Using loops to do concatenations that followed such a simple pattern felt cumbersome, so I utilized the creative use of `join` instead, further golfed by the fact that `array*str` is equivalent to `array.join(str)`
*+2 bytes to fix a typo I made that just so happened to return the same result on the test example by chance.*
```
I=->k{eval"->f#{[*0..k]*'{->f'}{f#{k}.times{f1=f0[f1]};f1#{"[f#{[*2..k]*'][f'}]"if k>1}"+?}*-~k}
```
[Try it online!](https://tio.run/##JcpNCoMwEEDhq0hcCJEEx20xXecMwywsOCDTQumPWIbp1WNol@/xPd6XTyl5Ckl02earC4lbRT/EKOQ7rdmZ1iUWX@tteSrDxAMykJ0YWnX48@PfE1ZObuVGEpjrz@bDV6zcm4wjYUYgwpB23Xswqqsc "Ruby – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 87 bytes
```
I=->k{eval ("->f%d{"*-~k+"f%d.times{f1=f0[f1]};f1"+"[f%d]"*~-k+?}*-~k)%[*0..k,k,*2..k]}
```
[Try it online!](https://tio.run/##FYpBCsIwEEWvUgYKNemEpltpXOcMwywUOyCjIFalJaRXj3H1H@/91@eylRInDJrm7/nedIBB2msCg7taqOjet8e8JPGTDCSe81E8WKCaGMyOak/5fz60ZAbntNfejHU5l2cTaWSK5JkJw5pW6zNXVX4 "Ruby – Try It Online")
] |
[Question]
[
# Introduction
I've seen throughout the code-golf challenges several simple tasks involving JSON, such as interpreting JSON strings with RegExs, and almost every other manipulation I could think of.
In a binding for [AppleScript](https://github.com/TooTallNate/node-applescript) that I was using for a Node project, I noticed that objects would be returned in a strange way: there would be an array of properties in string form, instead of a JSON object being returned as expected. This is where the challenge comes in...
# Algorithm
1. Add `{` to beginning of the output string
2. Iterate over all entries, adding them to the output string, delimited by `,`
3. Add `}` to the end of the output string
4. Print out the output string
# Challenge
Make this strange return format usable. Convert an array of JSON `'key:value'`s (in string form) to a full JSON object string.
# Rules
* Any language that can do string manipulations allowed
* Must print out JSON string with surrounding curly braces `{}`, and double quotes `""` around string values **AND** all properties (`"property":"value"` or `"property":3.14`, etc.)
* Must return a valid, parseable JSON string
* Lowest byte count wins per language
# Example Input and Output
Input:
>
> ['prop1:"val1"', 'prop2:12', 'prop3:3.14', 'prop4:false']
>
>
>
Output:
>
> '{"prop1":"val1", "prop2":12, "prop3":3.14, "prop4":false}'
>
>
>
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
```
a=>JSON.stringify(eval(`({${a}})`))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1s4r2N9Pr7ikKDMvPTOtUiO1LDFHI0GjWqU6sbZWM0FT8791cn5ecX5Oql5OfrpGmka0ekFRfoGhlRJQoaGSuo4CmG9kZWgEYxtbGesZmsB4JlZpiTnFqeqxmprW/wE "JavaScript (Node.js) – Try It Online") 43 bytes without builtins:
```
a=>`{${a.map(s=>s.replace(/\w+/,`"$&"`))}}`
```
[Try it online!](https://tio.run/##NcfRCoMgFADQXxkSU1kzrJ4M@5Ft4MVdx4ZL0aiH6NsdDHo75wMLZJvecb5O4YnF6QJ6NFu1gfhCZFmPWSSMHiyy5r5emtqQ6kwM5/tuymDDlINH4cOLOXajMYUoFVnAS0Lr0/@tku3hTnVC9sd65cBnpA/Oh/ID "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 23 bytes
```
%0`\w+
"$&"
¶
,
.+
{$&}
```
[Try it online!](https://tio.run/##K0otycxLNPz/X9UgIaZcm0tJRU2J69A2Lh0uPW2uahW12v//C4ryCwytlMoScwyVuEAcIytDIzDD2MpYz9AEzDSxSkvMKU4FAA "Retina – Try It Online") Explanation:
```
%0`\w+
"$&"
```
Quote all of the keys.
```
¶
,
```
Join the array elements together.
```
.+
{$&}
```
Wrap the result in brackets. This can also be done using the following code for the same byte count:
```
^
{
$
}
```
[Answer]
# C 108
**Thanks to Jonathan Frech this answer is now incredibly shorter**
**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**
```
i;main(c,v)char**v;{for(;++i<c;printf("%c\"%s\":%s",!~-i*79+44,v[i],++*v))*(*v=index(i[v],58))=0;puts("}");}
```
[Try it online!](https://tio.run/##HcfdCoIwGADQZ@kDYX9G00W15ZOoF2NlfWA6NhtB2Ksv8O4cVz6cyxnNy@JEnEjUPW1gLJnvMAdiOMerMz7gtAwECtdBETvQRQSx@5XITheulEgt9oJzlihlhKUGp9v9Q7BNvTieKW0Oxr@XSGAFatacsw@zlxqSHSVsqbSsNtS63ku1UenBjvH@Bw "C (gcc) – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), 79 bytes
Essentially [Neil's JS](https://codegolf.stackexchange.com/a/169327/110802) solve.
---
[Try it online!](https://tio.run/##PY2xCsIwEIb3PsVxOCRUilWngIO7TuJkRM6aSjSNMY2KlD57TSt60933c99fF2Soux0vqgiwJm2h6U6qhJKR2Kj7bhO8tuc9X2CDKWUVOXbIvHKGCrU0hqGUrxTHKHE0kYicZ9X1@8Mi5Sm22AH0xirKGflzLWDpPb3/agFbqwMsoEkgzpMMaOsePVnpOjB0/uZyITEmeewYw0CmIp/@9pmYZfn8d81FSaZWyAefiy3BWFaywcp72iZt0n0A)
```
def f(a:Seq[String])="{"+a.map(_.replaceAll("\\w+","\"$0\"")).mkString(",")+"}"
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda x:"{%s}"%",".join('"'+a.replace(":",'":')for a in x)
```
[Try it online!](https://tio.run/##NcfRCsIgFADQX5EL4yqJ4NzThb5k9XArJcNU3IhF9O0Gwd7Oqe/1XrLr4XjqiZ@XG4uN4DMsXxhAg3mUmCUCHtg0XxNfvQQCjUCoQmmCRcxiU722mFcZ5Iy1lWoJXpwsoBb/j2TH3Y6csdO@iQKnxeNZqf4D "Python 3 – Try It Online")
-6 bytes thanks to ovs
[Answer]
# [Lua](https://www.lua.org), 122 bytes
```
loadstring[[s="{"for i,v in ipairs(...)do x,y=v:match("(.-):(.+)")s=s.."\""..x.."\":"..y..","end return s:sub(1,-2).."}"]]
```
[Try it online!](https://tio.run/##RY7BCoMwEER/JezFXZouxPYU8EvaHtKqbSCNkqhUxG9Pg1R6e8MMM@NGk9oquc7UcQjWPy@XWMECbReElZOwXtje2BCRmanuxEfO1aTfZni8EJCPpJEPBBSryAxXAObPBjrTnElC42sRmmEMXkQdxzsqeSwpWyvcbqnPqwO2@L@A8Evnhm2WkIhSWoo@dL3SMBmnoJBi06VW5c4nfWJ13tVZt8bFpli/ "Lua – Try It Online")
---
This is an anonymous function. It technically doesn't "print out JSON string [...]", but instead it returns this string, so that when calling it you could print. I did that because **I needed to first convert the input from string to an actual list**, and I did that on the argument of the function call.
**If this makes my answer invalid** I'll move the string to table (list) "parser" from the footer to the actual code. **But I don't think it should**, because the input shown as a table, so the code that takes a string and transforms it into a table shouldn't count.
[Answer]
# [Go](https://go.dev), 116 bytes
```
import."strings"
func f(s[]string)string{for i,l:=range s{s[i]=`"`+Replace(l,`:`,`":`,1)}
return"{"+Join(s,",")+"}"}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BasMwEEX3OoWYlYTVgJIsisAXyKpkGwISRjJqZclIcjbCJ-nGFHqIHqW3qWrHm_nzP8y8mc-vPiw_o-o-VK_xoKxHdhhDzAcwQ4bvKZuX19-8ZylH6_sEyEy-w4ak232L6CbFhIgtc6KNyteFqaSbvbcSZHPVo1OdJo5JIZmEWjidUdR5ih4KNJdgPUkMGNAGZpif7PcV9X8ZobigJNqdWeQYw8gFPJTjIBle_VHw496fxOnAz7s7C6Nc0nJGb3U8u0pb95D6B6UUPYnLsukf)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~41~~ 40 bytes
```
->a{?{+a.map{_1.sub /\w+/,'"\&"'}*?,+?}}
```
Essentially Neil's JS solve.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3NXTtEqvtq7UT9XITC6rjDfWKS5MU9GPKtfV11JVi1JTUa7XsdbTta2uh6h0LSkuKFdKio9ULivILDK2UyhJzDJXUdRTAfCMrQyMY29jKWM_QBMYzsUpLzClOVY-NhRi0YAGEBgA)
[Answer]
# POSIX sh (sed + [ShellShoccar-jpn/Parsrs makrj.sh](https://github.com/ShellShoccar-jpn/Parsrs/blob/master/makrj.sh)), 33 bytes
Assumes values may have colons but properties shall never have colons, spaces, tabs, or periods.
```
sed 's/\([^:]*\):/.\1 /'|makrj.sh
```
## Usage
Input via standard input. Each line represents each item of an array.
## Commented
```
# "prop:item"
sed 's/\([^:]*\):/.\1 /'|
# ".prop item" is JSONPath-value format
makrj.sh
# JSON object
```
## Example run on Termux
```
~ $ sh makrj.sh -h
Usage : makrj.sh [JSON_value_textfile]
Wed Sep 14 22:19:55 JST 2016
~ $ cat jsss;echo;cat jsss | sed 's/\([^:]*\):/.\1 /'|sh makrj.sh
prop1:"val1"
prop2:12
prop3:3.14
prop4:false
{
"prop1":"val1",
"prop2":12,
"prop3":3.14,
"prop4":false
}
~$
```
] |
[Question]
[
Covalent bonding uses so-called "hybrid" orbitals to form tetrahedral, octahedral, etc. formations out of the *s*, *p*, and sometimes *d* orbitals. Their naming conventions are pretty much the concatenation of the component orbitals; for example, the hybridization of the *s* orbital and one *p* orbital would be the two *sp* orbitals, and the hybridization of the *s* orbital, all three *p* orbitals, and 2 of the 5 *d* orbitals would be the 6 *sp*3*d*2 orbitals. Real-life hybrid orbitals rarely go beyond this, but of course we'll do it anyway.
# The Challenge
Write a program that takes in the number of orbitals needed and outputs the name of the hybrid orbital as a string such as `sp3d4`. Superscripts can be omitted.
The standard orbitals, ordered by the order in which they're hybridized, are as follows:
```
letter # orbitals
s 1
p 3
d 5
f 7
```
No orbital should be used unless all lower orbitals have already been consumed. For example *spd*2 is not a valid orbital hybridization because there is still a *p* orbital that is not used.
If you go beyond the *f* orbital, then use the angular momentum quantum number (the zero-indexed position in this series: 0 is *s*, 1 is *p*, etc.) in parentheses. For example, 27 would be `sp3d5f7(4)9(5)2`. The number of orbitals for each set should continue with the pattern of "twice the angular momentum quantum number plus one".
Also, don't list the number of orbitals used in the output if that would be 1. It's *sp*3*d*, not *s*1*p*3*d*1.
# Test Cases
```
1 => s
2 => sp
3 => sp2
5 => sp3d
12 => sp3d5f3
36 => sp3d5f7(4)9(5)11
```
# Victory
The winner will be the shortest answer in bytes.
[Answer]
## JavaScript (ES6), 75 bytes
```
f=(n,l=0,r=n>l*2?l*2+1:n)=>n?("spdf"[l]||`(${l})`)+(r-1?r:'')+f(n-r,l+1):''
```
[Answer]
## JavaScript 121 bytes
Works thanks to Stephen Leppik :)
```
o="";a=["s","p","d","f"];i=0;while(x>0){i<4?o+=a[i]:o+="("+i+")";b=Math.min(2*i+1,x);b>1?o+=b:z=0;x-=b;i++}console.log(o)
```
Here is the not golfed version :
```
o="";
a=["s","p","d","f"];
i=0;
while(x>0){
i<4?o+=a[i]:o+="("+i+")";
b=Math.min(2*i+1,x);
b>1?o+=b:z=0; //z : useless assignment
x-=b;i++;
}
console.log(o);
```
] |
[Question]
[
In the IRC protocol, raw messages look similar to this:
```
command arg1 arg2 :arg3 with spaces :arg4 with spaces :arg5
```
In a shell environment (e.g. bash), that would be equivalent to:
```
command arg1 arg2 "arg3 with spaces" "arg4 with spaces" arg5
```
The format specification is as follows:
* Raw messages will only contain printable ASCII characters (ordinals 32-126).
* Raw messages will start with a command, which will not contain any spaces.
* Any number of arguments may follow a command. Arguments are delimited by one or more spaces followed by a colon (`<space>:` and `<space><space>:` are both valid delimiters).
+ Any arguments that do not contain spaces may omit the colon from the delimiter so long as all previous arguments (if any) have omitted the colon.
* Colons will not appear within arguments or commands.
* Arguments will not begin with a space.
For example, these are all valid raw messages:
```
join #foo #bar #baz
msg person hi
msg #channel :hello world
help :how do I use IRC
foo bar :baz bip :abc def :ghi
```
These are all invalid raw messages:
```
error :n:o colons within arguments
error ::need spaces between colons
:error no colons in commands
error non-ASCII character Ω
```
Given a valid raw IRC message as input, output a list containing the command and the arguments, properly parsed.
## Test Cases
```
"join #foo #bar #baz" -> ["join", "#foo", "#bar", "#baz"]
"msg person hi" -> ["msg", "person", "hi"]
"msg #channel :hello world" -> ["msg", "#channel", "hello world"]
"help :how do I use IRC" -> ["help", "how do I use IRC"]
foo bar :baz bip :abc def :ghi :xyz -> ["foo", "bar", "baz bip", "abc def", "ghi", "xyz"]
```
[Answer]
# PHP, 87 bytes
```
$a=($s=preg_split)("# +:#",$argv[1]);array_splice($a,0,1,$s("# +#",$a[0]));print_r($a);
```
The first regex splits the argument by one or more spaces followed by a colon.
The second regex splits the first element by one or more spaces with no colon.
`array_splice` replaces the first element with the result of the second `preg_split`.
`print_r` prints the resulting array.
**function version for testing**
```
$cases=[
"join #foo #bar #baz" => ["join", "#foo", "#bar", "#baz"],
"msg person hi" => ["msg", "person", "hi"],
"msg #channel :hello world" => ["msg", "#channel", "hello world"],
"help :how do I use IRC" => ["help", "how do I use IRC"],
"foo bar :baz bip :abc def :ghi :xyz" => ["foo", "bar", "baz bip", "abc def", "ghi", "xyz"],
];
function i($argv_1_){$a=($s=preg_split)("# +:#",$argv_1_);array_splice($a,0,1,$s("# +#",$a[0]));return $a;}
foreach($cases as$x=>$e)
{
$y=i($x);
echo "case '$x': ['",join("','",$y),'"]: ',($y<>$e?"FAIL. Expected: ['". join("','",$e)."']":OK),"\n";
}
```
[Answer]
# Retina, 24 bytes
```
M!`:.+?(?=\s+:|$)|\S+
:
```
(note there is a trailing newline)
[Try it online!](http://vihan.org/p/tio/?l=retina&p=81VMsNLTttewt40p1raqUdGsiQnW5rLi@p@Wn6@QlFikYJWUWKWQlFmgYJWYlKyQkpqmYJWekalgVVFZBQA)
[Answer]
## PowerShell v2+, ~~43~~ 34 bytes
```
$a,$b=$args-split' +:';-split$a;$b
```
This `-split`s the input string `$args` on the regex `+:` (i.e., one or more spaces and a colon), stores the left-most (i.e., first result) into `$a` and any remaining results into `$b`. We then need to `-split` `$a` on spaces (here done by leveraging that whitespace is the default for unary `-split`), and that's left on the pipeline. We then simply put `$b` on the pipeline. Output via implicit `Write-Output` inserts a newline between elements.
### Test cases
```
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'join #foo #bar #baz'
join
#foo
#bar
#baz
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'msg person hi'
msg
person
hi
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'msg channel :hello world'
msg
channel
hello world
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'help :how do I use IRC'
help
how do I use IRC
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'foo bar :baz bip :abc def :ghi :xyz'
foo
bar
baz bip
abc def
ghi
xyz
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;⁷œṣ⁾ :µḢḲ;œr€⁶ỴF$€
```
A monadic link that returns a list.
Note: As a full program the implicit print that Jelly performs may be a little confusing in this case, since a list containing strings (really lists of characters in Jelly) is printed as if it were a single string. So, for completeness here are test harnesses employing the quick `Ç` which calls the previous link monadically:
1. [`Ṿ`](http://jelly.tryitonline.net/#code=O-KBt8WT4bmj4oG-IDrCteG4ouG4sjvFk3Ligqzigbbhu7RGJOKCrArDh-G5vg&input=&args=Zm9vIGJhciA6YmF6IGJpcCA6YWJjIGRlZiA6Z2hpIDp4eXo) shows the Jelly representation of a list of character lists;
2. [`Y`](http://jelly.tryitonline.net/#code=O-KBt8WT4bmj4oG-IDrCteG4ouG4sjvFk3Ligqzigbbhu7RGJOKCrArDh1k&input=&args=Zm9vIGJhciA6YmF6IGJpcCA6YWJjIGRlZiA6Z2hpIDp4eXo) joins the list with line feeds;
3. [`ŒṘ`](http://jelly.tryitonline.net/#code=O-KBt8WT4bmj4oG-IDrCteG4ouG4sjvFk3Ligqzigbbhu7RGJOKCrArDh8WS4bmY&input=&args=Zm9vIGJhciA6YmF6IGJpcCA6YWJjIGRlZiA6Z2hpIDp4eXo) shows the underlying Python representation (showing the actual lists of characters).
### How?
Handling the edge case of possible trailing spaces for the ultimate argument (the only one which may have trailing spaces) is quite an expense at 6 bytes; maybe there is a shorter way?
```
;⁷œṣ⁾ :µḢḲ;œr€⁶ỴF$€ - Link expecting a single list of characters as input
; - concatenate
⁷ - a line feed (to avoid right trimming spaces from ultimate argument)
œṣ - split on sublists equal to
⁾ : - two character list [' ',':']
µ - monadic chain separation (call the split result z)
Ḣ - head - pop first element (modifies z)
Ḳ - split at spaces
; - concatenate with z
⁶ - space
œr€ - right-strip from €ach
$€ - last two links as a monad for €ach
Ỵ - split on line feeds
F - flatten (removes the line feed from the beginning)
```
[Answer]
# Mathematica, 44 bytes
```
Flatten@MapAt[s=StringSplit,#,1]&@s[#," :"]&
```
[Answer]
# C, 140 bytes (excluding sample usage)
```
void p(char*m){char*c=strchr(m,':');if(c) {*c=0;c++;}
char*n=strtok(m," ");while(n) {puts(n);n=strtok(NULL," ");}
if(c){puts(c);}}
```
Sample usage:
```
#include <string.h>
#include <stdio.h>
void parse(char*msg){char*c=strchr(msg,':');if(c) {*c=0;c++;}
char*n=strtok(msg," ");while(n){puts(n);n=strtok(NULL," ");}
if(c){puts(c);}}
main(){char msg[]="sample : abcnsjd hajs";parse(msg);}
```
Try me: <http://codepad.org/GQ51MO4l>
[Answer]
# Python 2, ~~64~~ 60 bytes
```
import re;a=re.split(' +:',input());print a[0].split()+a[1:]
```
Edit:
Requires quoted input to use `input`.
Preserves trailing spaces on last argument.
[Answer]
# JavaScript (ES6), ~~59~~ ~~57~~ ~~56~~ 49 bytes
This is my first entry on PPCG, any input appreciated!
```
(s,[a,...b]=s.split(/ +:/))=>a.split` `.concat(b)
```
---
**EDIT History:**
* Thanks @Mego for saving 2 bytes by making it an anonymous function.
* Replaced `\s` with to save 1 byte.
* Thanks @BassdropCumberwubwubwub for showing me the `split` `` syntax and the `[a,...b]=array_expression_here` syntax. I didn't know these were possible, thank you very much! Very clever!
### Test snippet
```
let f = (s,[a,...b]=s.split(/ +:/))=>a.split` `.concat(b)
```
```
<input id=I type="text" size=70 value="command arg1 arg2 :arg3 with spaces :arg4 with spaces :arg5"><button onclick="console.log(f(I.value))">Run</button>
```
[Answer]
# [Perl 6](https://perl6.org), ~~49~~ 47 bytes
```
{m/(<-[\ :]>+)+%%" "+":"?(.+?)*%[" "+":"]$/.flat}
```
[Perl 6](https://perl6.org) version of the [Python answer](https://codegolf.stackexchange.com/questions/101988/parse-a-raw-irc-message/102200#102200)
```
{$/=.split(/" "+":"/);|$0.split(" "),|$/[1..*]}
```
The to `|`s are there to flatten the list.
## the first entry expanded:
```
{ # bare block lambda with implicit parameter 「$_」
m/ # regex match implicitly against 「$_」
( # capture
<-[\ :]>+ # at least one non-space non-colon character
)+ # at least once
%% # separated (with optional trailing separator)
" "+ # by at least one space
":"? # optionally match a colon ( needed for rest of regex )
( # capture
.+? # at least one character as short as possible
)* # any number of times
% # separated (no optional trailing separator)
[ " "+ ":" ] # by at least one space, and a colon
$ # match end of string (needed because of 「.+?」)
/
.flat # flatten the captures
}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This site is for programming contests and challenges. **General programming questions** are off-topic here. You may be able to get help on [Stack Overflow](http://stackoverflow.com/about).
Closed 7 years ago.
[Improve this question](/posts/99274/edit)
I apologize if this isn't fit for this site but it is a puzzle, not all that practical, so I thought it would fit.
Take this code:
```
string s = "";
Console.WriteLine(ReferenceEquals(s, string.Empty));
```
This will print out `true` because `""` is interned by the JITter at some early point and literals are reused from the interning cache.
The question and puzzle is this:
>
> How can you initialize `s` such that
>
> 1. `s.Length == 0`
>
> 2. `ReferenceEquals(s, string.Empty) == false`
>
>
>
I've tried the following:
```
string s = "test".Substring(0, 0); // any arbitrary legal start offset tried
string s = new string(' ', 0);
string s = new string(new char[0]);
string s = CallSomeMethodThatWontBeInlined() + CallSomeMethodThatWontBeInlined();
```
These three all end up being equal to `string.Empty`.
Bonus if you can explain the above behavior with regards to `new string(...)`. I have my thoughts about it but no solid evidence one way or another.
I can understand that all methods that concatenate or take substrings of existing strings special-case the result that will end up with length zero, but how `new string(...)` actually doesn't create a new object I don't know.
**Note!** I'm asking for legal C#. I'm not asking for a p/invoke or assembly code call that just manually constructs the bytes of an empty string object in memory and stuffs a pointer to it into a string variable.
Any method or path through existing classes in .NET or using operators of strings or whatnot that would end up with the required results are legal. As such, take the `Substring` example above, if that returned a new empty string that isn't the same as the existing one, then that would be a/the answer to this puzzle.
Reflection is boundary, at the very least it has to be reflection that can run in untrusted scenarios.
---
My own "conclusion" is that this may indeed be impossible because the actual C# code that would end up constructing such a string would end up with one of the `new string(...)` overloads, or using one of the operators which all seem to handle this cases. As such, the end-point of any such code may be the one that handles this case and since it does, it may not be possible.
[Answer]
So, I'll take the easy way:
```
string s = "";
```
So, `s.Length` is now 0, so far so good. But how can we get `ReferenceEquals(s, string.Empty)` to false.
Piece of cake, just put that into your class:
```
public static new bool ReferenceEquals(object a, object b) => false;
```
and the above call will result in false.
I will look for some more sneaky methods, so.
[Answer]
# 1st try: Reflection
```
String s = "abc";
PropertyInfo pi = s.GetType().GetProperty("Length");
pi.SetValue(s, 0, null);
```
Yields error, there is no set property
# Loophole
```
var s = new { Length = 0 };
```
Now the `ReferenceEquals` will return `false` and `s.Length == 0`. Just sticking to your rules =)
] |
[Question]
[
### 100 Prisoners and a light bulb
You may have seen this puzzle over on the puzzles exchange or perhaps heard it somewhere else. If you are unfamiliar with this puzzle check out:
[100 Prisoners and a Light bulb](http://www.cut-the-knot.org/Probability/LightBulbs.shtml)
The gist of this puzzle is that there are 100 prisoners, each one is separated from one another and must go into a room one at a time. The prisoner selected to go into the room is selected uniformly at random each time. In this room there is a light bulb and a switch, the prisoner must either turn the light on, turn the light off, or do nothing. At any given time one of the prisoners may say that all 100 prisoners have been in the room at least once. If he is correct they are all freed, if they are incorrect they are all killed. Prior to being separated the group of prisoners may discuss a strategy and they may never communicate again.
### One working strategy:
>
> The prisoners select one prisoner as the leader. When anyone else enters the room they do nothing unless it's the first time they enter the room and the light is off; in that case, they turn the light on. When the leader enters the room and the light is on then he turns the light off and maintains a counter, adding one to it. Once he counts 99 (the light has been turned on once for every other prisoner) he knows that all 100 (including himself) have been in the room, and he claims their freedom.
>
>
>
### The code challenge:
Take no input into your program.
Simulate the strategy and output the number of times a prisoner entered the room before the leader claimed their freedom.
`n` represents the number of times a prisoner enters the room for the first time.
`k` represents the leader of the prisoners.
`d` represents a data structure holding boolean values for each prisoner.
`l` represents a boolean value to hold the state of the light bulb.
`i` represents the number of iterations of the puzzle before it ends.
### Examples:
Randomly pick an element from `d`. if `l` is false and `k[rand]` is false then `l` is now true and `d[rand]` is true. `i = i + 1`
Randomly pick an element from `d`. if `l` is true and `d[rand]` is false then do nothing. `i = i + 1`
Randomly pick an element from `d`. if `l` is false and `d[rand]` is true then do nothing. `i = i + 1`
Randomly pick an element from `d`. if `d[rand] = k` and if `l` is false then do nothing. `i = i + 1`
Randomly pick an element from `d`. if `d[rand] = k` and if `l` is true, set `l` to false, add 1 to `n`. `i = i + 1`
Randomly pick an element from `d`. if `d[rand] = k` and if `l` is true and `n = 99` then end puzzle. `i = i + 1` and output `i`.
this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. Have Fun!
[Answer]
# Python 2, 133 bytes
I used binary operations to keep track. I had `if(i<1)*b:...` but I think that's an off-by-one error. Not sure.
```
from random import*
L=2**99-1
b=l=c=0
while l<99:
i=randint(0,99)
if(i>98)*b:b=0;l+=1
elif(L&1<<i)*(b<1):b=1;L|=1<<i
c+=1
print c
```
[**Try it online**](https://repl.it/EE3R/1)
**Less golfed:**
```
from random import*
L=[1for _ in range(100)]
b=l=c=0
while l<99: # check leader's count of prisoners
i=randint(0,99)
if b and i==99:b=0;l+=1 # if light on and leader, turn off and count
elif L[i] and b<1:b=1;L[i]=0 # else if new prisoner and light off, turn on
c+=1 # iterations
print c
```
[Answer]
## CJam (26 bytes)
```
100,1a*0-{{__100mr>!}g;}%,
```
### Dissection
```
100,1a*0- e# Generate a list [1 1 1 2 1 3 1 ... 98 1 99] representing (in reverse order)
e# the number of prisoners at each step who can advance to the next step
{ e# For each element in the list...
{ e# While we fail to select a suitable prisoner...
__ e# dup twice: once to leave on stack as a counter, and once for comparison
100mr e# Select a random prisoner
>! e# Test whether that prisoner is suitable
}g
; e# Pop to avoid overcounting by one
}%
, e# Count up the values we left on the stack
```
[Answer]
# [Perl 5](https://www.perl.org/), 77 bytes
```
++$i,($s=0|rand 100)?!$a[$s]&&!$l++&&$a[$s]++:$l&&++$n&($l=0)while$n<99;say$i
```
[Try it online!](https://tio.run/##K0gtyjH9/19bWyVTR0Ol2NagpigxL0XB0MBA015RJTFapThWTU1RJUdbW00NwtXWtlLJUVMD6shT01DJsTXQLM/IzElVybOxtLQuTqxUyfz//19@QUlmfl7xf11fUz0DQwMA "Perl 5 – Try It Online")
[Answer]
## Python 3, 164 bytes, aka garbage :)
```
from random import*
d={}
a=l=n=p=0
for i in range(100):
d[i]=0
while n<100:
a+=1
p=randint(0,99)
if p==50:
l=0
else:
l=1
if d[p]==0:
d[p]=1
n+=1
print(a)
```
] |
[Question]
[
**This question already has answers here**:
[Trump needs your help to stop the Starman!](/questions/64476/trump-needs-your-help-to-stop-the-starman)
(22 answers)
Closed 7 years ago.
Write a program or function that takes an input greater than or equal to 2. It should output a truthy or falsy value corresponding to whether the input is a [Lucas number](https://en.wikipedia.org/wiki/Lucas_number) or not. You may take input from STDIN, or whichever source is most suitable to you.
This question is different to [this one](https://codegolf.stackexchange.com/questions/64476/trump-needs-your-help-to-stop-the-starman) because this question is specifically for Lucas numbers only, and not Fibonacci numbers at all, whereas that question was Lucas number, Fibonacci numbers and both possible combinations of them. This question was, however, inspired by that question and is similar in some regards.
Lucas numbers are the numbers that result from the rules following: the first Lucas number is a 2, the second is a 1, and each term after that is the sum of the previous two. Yes, it is very similar to the Fibonacci sequence, but this has the added advantage of converging closer to the golden ratio, phi, faster than Fibonacci numbers do.
# Example inputs/outputs
```
Input Output
--------------
3 True
4 True
7 True
8 False
10 False
3421 False
9349 True
```
etc.
# Some limitations
* Your program/function must run in a reasonable amount of time. It should terminate within seconds and minutes, not hours and days.
* Your program must not calculate all the Lucas numbers up to the input number
This is code golf, so the shortest code in bytes wins.
[Answer]
# MATL, ~~19~~ ~~17~~ ~~16~~ 18 bytes
```
2^5*20t_h+X^Xj1\~a
```
[**Try it Online!**](http://matl.tryitonline.net/#code=Ml41KjIwdF9oK1heWGoxXH5h&input=OTM0OQ)
**Explanation**
```
2^ % Implicitly grab the input and square it
5* % Multiply the result by 5
20 % Create the literal number 20
t_ % Duplicate and negate the second 20
h % Concatenate 20 and -20 to get [20 -20]
+ % Add the array to the result of 5*n^2
X^ % Compute the square root
Xj % Ensure that the result is a real number
1\ % Compute the remainder to test for perfect squares
~a % Check to see if any had a remainder of zero (returns a boolean)
```
[Answer]
# Python, ~~69~~ ~~67~~ 53 characters
```
lambda x:0in(((5*x**2+20)**.5)%1,((5*x**2-20)**.5)%1)
```
This works in both Python 2.x and 3.x.
See [this answer](https://codegolf.stackexchange.com/a/64499/33217) to see how it works - `n` is a Lucas number if either `5n^2+20` or `5n^2-20` is a perfect square. My program checks to see if either of their square roots are integers and checks if 0 is in the tuple that results.
[Answer]
# MATLAB, 43 bytes
```
@(n)~all(rem(real(sqrt(5*n^2+[-20 20])),1))
```
Inspired by [Anders Kaseorg's answer](https://codegolf.stackexchange.com/a/76839/51939)
[Answer]
# Python, ~~45~~ 43 characters
```
lambda n:0in[(5*n*n+k)**.5%1for k in-20,20]
```
Based on a [proof given here](http://www.fq.math.ca/Scanned/10-4/advanced10-4.pdf).
] |
[Question]
[
**Requirements**
You need to make a smiley face go from smiling to frowning and back. There needs to the below faces in the code: **Smiling, no expression, frowning, no expression, and then back to smiling.** The new face needs to replace the old face flipbook style so that there's only one face on the screen at a time. There is no input required it will just be a loop that displays one face, pauses for 200 milliseconds, and replaces the current face with the next and so on looping forever.
**Faces to use:**
```
__ooooooooo__
oOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOO* *OOOOOOOOOOOOOO* *OOOOOOOOOOOOo
oOOOOOOOOOOO OOOOOOOOOOOO OOOOOOOOOOOOo
oOOOOOOOOOOOOo oOOOOOOOOOOOOOOo oOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO OOOOo
oOOOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO OOOOOOo
*OOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO OOOOO*
*OOOOOO *OOOOOOOOOOOOOOOOOOOOOOOOOOOOO* OOOOOO*
*OOOOOO *OOOOOOOOOOOOOOOOOOOOOOOOOOO* OOOOOO*
*OOOOOOo *OOOOOOOOOOOOOOOOOOOOOOO* oOOOOOO*
*OOOOOOOo *OOOOOOOOOOOOOOOOO* oOOOOOOO*
*OOOOOOOOo *OOOOOOOOOOO* oOOOOOOOO*
*OOOOOOOOo oOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOO*
""ooooooooo""
__ooooooooo__
oOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOO* *OOOOOOOOOOOOOO* *OOOOOOOOOOOOo
oOOOOOOOOOOO OOOOOOOOOOOO OOOOOOOOOOOOo
oOOOOOOOOOOOOo oOOOOOOOOOOOOOOo oOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOoOOOOOOOO*
*OOOOOOo oOOOOOO*
*OOOOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOoOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOO*
""ooooooooo""
__ooooooooo__
oOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOO* *OOOOOOOOOOOOOO* *OOOOOOOOOOOOo
oOOOOOOOOOOO OOOOOOOOOOOO OOOOOOOOOOOOo
oOOOOOOOOOOOOo oOOOOOOOOOOOOOOo oOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOO OOOOOOOOOOOOOOO*
*OOOOOOOOOOO OOOoOOOOOOOO*
*OOOOOO OOOOOOOOOOOOOOOO OOOOOO*
*OOOOO OOOOOOOOOOOOOOOOOOOOOO OOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOO*
""ooooooooo""
__ooooooooo__
oOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOO* *OOOOOOOOOOOOOO* *OOOOOOOOOOOOo
oOOOOOOOOOOO OOOOOOOOOOOO OOOOOOOOOOOOo
oOOOOOOOOOOOOo oOOOOOOOOOOOOOOo oOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
oOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOoOOOOOOOO*
*OOOOOOo oOOOOOO*
*OOOOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOoOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOOOOOOOOOO*
*OOOOOOOOOOOOOOOOOOOOO*
""ooooooooo""
```
Only one face shows up at a time and it should loop forever cycling between happy indifferent and sad.
**Goal**
Have the shortest code is always the goal but being able to tell that the output is actual a face is quite important.
[Answer]
# Python 2 - 461/442 bytes
461 bytes:
```
f='eNrtlkEOwyAMBO+8wuLoz/gJPIH/3yKVhC62AVeVKrUNR7KDceJdhchbpdRrlZLM4yreqikg8sRr\npdZH1EhE9cAgwkQ8ivROg5BphWW5Yymp5rJm50G90pHGzD2c1TVYjQJlCFvj86w91SQMlJiXLuYb\nCFAxTEOXuM4x7v1zH0CWBfYEgAChgkA+6BVircLWlTzrgCi5Lqecu81zThPRnQW/mgUfwzZmdob2\nDQqMs7qXNhJbs9Fs2HUWBAq5YRBoJsbcaXCnwZ+lgR3NTRq4zMnN0sA/WcaKOg2mP1gO8R1hcACw\nDCfh\n'.decode('base64').decode('zlib').split("\n\n");import os,time;f+=[f[1]];i=0
while 1:os.system('cls');print f[i];i=(i+1)%4;time.sleep(.2)
```
442 bytes requiring ansi code support:
```
f='eNrtlkEOwyAMBO+8wuLoz/gJPIH/3yKVhC62AVeVKrUNR7KDceJdhchbpdRrlZLM4yreqikg8sRr\npdZH1EhE9cAgwkQ8ivROg5BphWW5Yymp5rJm50G90pHGzD2c1TVYjQJlCFvj86w91SQMlJiXLuYb\nCFAxTEOXuM4x7v1zH0CWBfYEgAChgkA+6BVircLWlTzrgCi5Lqecu81zThPRnQW/mgUfwzZmdob2\nDQqMs7qXNhJbs9Fs2HUWBAq5YRBoJsbcaXCnwZ+lgR3NTRq4zMnN0sA/WcaKOg2mP1gO8R1hcACw\nDCfh\n'.decode('base64').decode('zlib').split("\n\n");import time;f+=[f[1]];i=0
while 1:print'<ESC>[f'+f[i];i=(i+1)%4;time.sleep(.2)
```
`<ESC>` is a literal escape character (code 27). This program assumes that the terminal it is running on starts out blank
[Answer]
# Mathematica, ~~478~~ 470 bytes
```
i=0;Dynamic[Uncompress["1:eJzt1rsKwjAUBuAOPkjNmEl9BHUUAnYVAg6CU4b6/nhNPLekR6hCJWcQqf/XpFp/Oj+G/WnWNE1/f9md+0u3vr1rxfE+xPH+sFiuWCI4aQLLyrlMvhwWiAYQpCWYQWXb1uIcPZIcZM/lXfGICF1gu2ZHIiQ5xSDJNiRMypA1hxzIpMu0rzMOw2fEYujYL0HGxlMnqJOCi/mQlzZ9FxbepDEuyrfBCGSJA4ISovj/iueRwTsTs48xJtWDMd221oiWQfXHNfJjOVACfGiNfA7B/6y0Qe5AjRQmMBahYrlcj+guTMe+UiSbWiRaBlUtkrHkaEXC7+AcRFK++V2xSOTzuxYdF4pEMA5/MNkeqQ8kagZV7ZGxZH0gQctNtUiuFNCEqg=="][[i=i~Mod~4+1]],UpdateInterval->.2,TrackedSymbols->{}]
```
[Answer]
# JavaScript (ES6), 613 bytes
```
setInterval(_=>(c=console).clear()||c.log((` 16__o6__
11oO18o
7oO26o
4oO32o
2oO36o
0oO40o
oO8* *O11* *O9o
oO8 3O9 3O9o
oO9o oO11o oO10o
oO46o
`+[`oO1 2O28 2O1o
oO3 O32 O3o
*O2 O30 O2*
*O3 *O26* O3*
*O3 *O24* O3*
0*O3o *O20* oO3*
2*O4o *O14* oO4*
4*O5o *O8* oO5*
7*O5o 8oO5*`,n=`oO46o
oO46o
*O44*
*O44*
*O5oO24oO5*
0*O3o 26oO3*
2*O2oO24oO2*
4*O32*
7*O26*`,`oO46o
oO46o
*O44*
*O11 15O12*
*O8 19O9*
0*O3 4O13 5O3*
2*O2 0O19 0O3*
4*O32*
7*O26*`,n][i++%4]+`
11*O18*
16""o6""`).replace(/.\d+/g,r=>r[0].repeat(+r.slice(1)+3))),i=200)
```
## Explanation
Uses a simple [run-length encoding](https://en.wikipedia.org/wiki/Run-length_encoding) scheme to compress the string. Any character can optionally have a number directly after it which tells the decompressor to print that character `n + 3` times (eg. `ab4c` will become `abbbbbbbc`).
Without this compression the code size is just over 2000 bytes.
```
setInterval(
_=>(c=console).clear()||c.log( // clear and display the face in the console
( // piece together the appropriate string
`TOP`+ // run-length encoded face top string
[`HAPPY`,n=`NEUTRAL`,`SAD`,n][i++%4]+ // encoded mouth string
`BOTTOM` // encoded face bottom string
)
.replace(/.\d+/g, // search for each character-number instance
r=>r[0].repeat(+r.slice(1)+3) // repeat the character n + 3 times
)
),
i= // i = iterator
200 // set interval to 200ms
)
```
] |
[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/54285/edit).
Closed 8 years ago.
[Improve this question](/posts/54285/edit)
Take a string as input. This string can be as long as you'd like, however, it may only include letters and spaces––no numbers, punctuation, etc. When a word is passed into your function, an image will be made out of it. This image is the input word written out using only these characters: **–**, **/**, **\**, and **|**. You do not need to use all of these characters, but you may not use any others. **Only words are inputed; no numbers or any other characters.**
Here are a couple examples:
```
Input : "String"
Return :
––– ––– ––– ––– |\ | –––
| | | | | | \ | |
––– | |––– | | \ | | ––
| | | \ | | \ | | |
––– | | \ ––– | \| ––– //uppercase string written out
–––––––––––––––––––––––––––––––––––––––– //bar
//line break
––– | | / ––– | /| –––
| | | / | | / | | |
––– | |––– | | / | | ––
| | | | | | / | |
––– ––– ––– ––– |/ | ––– //uppercase string written upside-down (reflected)
```
After the all caps string written out, there is a bar and then a line break. After that, there is the same string, just mirrored/upside-down. The bar under the word spelled out should be the length of the written out string. The upside down word––the reflection––goes one line beneath the line break.
Here is another example:
```
Input : "hi"
Return :
| | –––
| | |
|––| |
| | |
| | –––
–––––––––
| | –––
| | |
|––| |
| | |
| | -––
```
## A bonus challenge/addition:
Add a ripple effect. Have something like a random indent between 0 and 3 spaces before each line in the reflection. Here's an example of what it could look like:
```
Input : "hi"
Return :
| | –––
| | |
|––| |
| | |
| | –––
–––––––––
| | –––
| | |
|––| |
| | |
| | -––
```
## Your code should be in the following form:
```
function createAwesomeness(string) -> string {
let s = //your code that creates the 'image'
return s
}
print createAwesomeness("string")
print createAwesomeness("bananas")
```
## A couple notes:
* Every language is valid
* Suggestion: Do not copy the font-set as a dictionary or array because that adds a lot to your code's size. Both as a challenge and to lower your code's size, try to use a function of sorts to create the letters
* Along with your code, have:
+ The size in bytes **of your function**
+ The number of characters **of your function**
+ The two examples
* Shortest, working code wins
* There is currently no deadline
If any further explanation is needed, please tell me in the comments!
Any response is welcome and greatly appreciated!
[Answer]
# JavaScript (ECMAScript 6) (580 characters/bytes)
Probably not the best/shortest way to do this, but here's my two cents' worth:
```
a=x=>{l=["#####","# #","#"," #"," #","# #","# ##","####",""],g=[0,1,1],t=[8,8,8,8,8,0,1,...g,7,1,0,1,7,0,2,2,2,0,7,1,1,1,7,0,2,0,2,0,0,2,0,2,2,0,2,0,1,...g,...g,0,3,3,3,0,0,4,4,4,...g,5,5,1,2,2,2,2,0,0,...g,1,1,1,1,6,1,...g,1,0,0,1,0,2,2,...g,6,0,0,1,0,5,1,0,2,0,4,0,0,3,3,3,3,1,1,1,1,...g,1,1,3,1,1,1,0,...g,3,1,1,1,1,0,3,3,0,4,0,2,0],s=(n,r)=>l[t[5*n+r]].padRight(8),y=Array(10).fill("");for(r=-1,z=0;++r<5&z<x.length;r==4&&++z?r=-1:0){c=x[z].charCodeAt()&31;y[r]+=s(c,r),y[9-r]+=s(c,r)}return`${y.slice(0,5).join`
`}
${"-".repeat(y[0].length-3)}
${y.slice(5).join`
`}`}
console.log(a("string"))
console.log(a("bananas"))
```
Note that although this is [standard ES6](http://www.ecma-international.org/ecma-262/6.0/), this strictly requires sloppy mode (heh, get it?) which hasn't landed in all of the JS engines/transpilers yet; it'll probably be ready this winter. If anyone knows a way to run this code in a sloppy environment as of today, feel free to edit.
Well, since people still need to reproduce my output, I'll just give you the strict version that only differs in the way that it uses "let" to declare variables instead of making them globals by omitting it. Feel free to verify that I only added "let" in four places and changed nothing further. Here's the strict version that you can run today already using [babel](https://babeljs.io/repl):
```
let a=x=>{let l=["#####","# #","#"," #"," #","# #","# ##","####",""],g=[0,1,1],t=[8,8,8,8,8,0,1,...g,7,1,0,1,7,0,2,2,2,0,7,1,1,1,7,0,2,0,2,0,0,2,0,2,2,0,2,0,1,...g,...g,0,3,3,3,0,0,4,4,4,...g,5,5,1,2,2,2,2,0,0,...g,1,1,1,1,6,1,...g,1,0,0,1,0,2,2,...g,6,0,0,1,0,5,1,0,2,0,4,0,0,3,3,3,3,1,1,1,1,...g,1,1,3,1,1,1,0,...g,3,1,1,1,1,0,3,3,0,4,0,2,0],s=(n,r)=>l[t[5*n+r]].rpad(8),y=Array(10).fill("");for(let r=-1,z=0;++r<5&z<x.length;r==4&&++z?r=-1:0){let c=x[z].charCodeAt()&31;y[r]+=s(c,r),y[9-r]+=s(c,r)}return`${y.slice(0,5).join`
`}
${"-".repeat(y[0].length-3)}
${y.slice(5).join`
`}`}
console.log(a("string"))
console.log(a("bananas"))
```
## Output
The first console.log yields **STRING**:
```
##### ##### ##### ##### # # #####
# # # # # # # #
##### # ##### # # # #####
# # # # # # ## # #
##### # # # ##### # # #####
---------------------------------------------
##### # # # ##### # # #####
# # # # # # ## # #
##### # ##### # # # #####
# # # # # # # #
##### ##### ##### ##### # # #####
```
and the second console.log yields **BANANAS**:
```
#### ##### # # ##### # # ##### #####
# # # # # # # # # # # # #
##### ##### # # ##### # # ##### #####
# # # # # ## # # # ## # # #
#### # # # # # # # # # # #####
-----------------------------------------------------
#### # # # # # # # # # # #####
# # # # # ## # # # ## # # #
##### ##### # # ##### # # ##### #####
# # # # # # # # # # # # #
#### ##### # # ##### # # ##### #####
```
## How it works:
My idea was to generate the the alphabet by compressing letters with respect to similar lines. Thus, every letter in the alphabet can be represented as a 5-dimensional vector of numbers that correspond to a string that again corresponds to a row in a letter.
This approach is made a lot easier when every letter has the same width, as this enables us to re-use some string patterns more effectively. With this idea in mind, I then designed a font that is optimized for similar-looking lines in letters, so that it compresses well:
```
#####
# #
#####
# #
# #
####
# #
#####
# #
####
#####
#
#
#
#####
####
# #
# #
# #
####
#####
#
#####
#
#####
#####
#
#####
#
#
#####
#
#####
# #
#####
# #
# #
#####
# #
# #
#####
#
#
#
#####
#####
#
#
#
#####
# #
# #
# #
# #
# #
#
#
#
#
#####
#####
#####
# #
# #
# #
# #
# #
# #
# ##
# #
#####
# #
# #
# #
#####
#####
# #
#####
#
#
#####
# #
# #
# ##
#####
#####
# #
#####
# #
# #
#####
#
#####
#
#####
#####
#
#
#
#
# #
# #
# #
# #
#####
# #
# #
# #
# #
#
# #
# #
# #
#####
#####
# #
# #
#
# #
# #
# #
# #
#####
#
#
#####
#
#####
#
#####
=========================================
0: #####
1: # #
2: #
3: #
4: #
5: # #
6: # ##
7: ####
8:
A = [0, 1, 0, 1, 1]
B = [7, 1, 0, 1, 7]
C = [0, 2, 2, 2, 0]
D = [7, 1, 1, 1, 7]
E = [0, 2, 0, 2 ,0]
F = [0, 2, 0, 2, 2]
G = [0, 2, 0, 1, 0]
H = [1, 1, 0, 1, 1]
I = [0, 3, 3, 3, 0]
J = [0, 4, 4, 4, 0]
K = [1, 1, 5, 5, 1]
L = [2, 2, 2, 2, 0]
M = [0, 0, 1, 1, 1]
N = [1, 1, 1, 6, 1]
O = [0, 1, 1, 1, 0]
P = [0, 1, 0, 2, 2]
Q = [0, 1, 1, 6, 0]
R = [0, 1, 0, 5, 1]
S = [0, 2, 0, 4, 0]
T = [0, 3, 3, 3, 3]
U = [1, 1, 1, 1, 0]
V = [1, 1, 1, 1, 3]
W = [1, 1, 1, 0, 0]
X = [1, 1, 3, 1, 1]
Y = [1, 1, 0, 3, 3]
Z = [0, 4, 0, 2, 0]
```
To further assist compression, I decided to only use number signs (#) to form letters, resulting in better compression. Another great thing about this approach is that it allows me to do a very simple reflection logic, since I'm not required to transform "\" to "/". The resulting font is exceptionally ugly, but as long as it compresses well, I really don't mind about its looks.
In the end, I managed to represent every single letter of the alphabet by using eight different patterns in total (plus one additional dummy pattern for spaces). It was in my best interest to use no more than 10 different patterns (or else I'd have to pay the price of requiring two characters to write down some numbers in the code). I then serialized all letter information in an array, added a little bit of letter selection/concatenation logic, and voilà.
] |
[Question]
[
This is my first code golf challenge, as such I am not entirely certain if it is suitable as a Code Golf challenge, but it's all a learning experience.
The challenge is that in as few characters as possible, using whichever language you prefer, develop a code to complete the following:
1. Take a value from stdin
2. Return a value to stdout that contains the same characters as the value at stdin in a different order. Not necessarily random, but following the restrictions set out below.
*Here are a few restrictions:*
* All characters that are contained in the stdin value must appear in stdout value
* Characters must appear in stdout the same amount of times they appear in stdin
* The order of characters in the output, cannot be identical to the order of characters in input, for more than two consecutive characters. Regardless of the source of the character in the input. That is, the input and output must not have a common substring of length 3 or greater.
* Any input where no solution can be found under the previous rule, is considered an invalid input
**Examples:** aaaa, bbbb
* you do not need to test for invalid inputs, assume all inputs are valid.
* The length of stdout must be the same as the length of stdin
* You may use any method to scramble the initial value, there is nothing off limits here.
*Example:*
>
> stdin: Hello There
>
>
> stout: loTeHle reh
>
>
>
*Note: a character in this context can be any valid ASCII character*
[Answer]
# CJam, ~~31~~ 27 bytes
```
l:I{mr[_I]{_,((,\f>3f<}/&}g
```
[Test it here.](http://cjam.aditsu.net/)
Same approach as my Mathematica answer. It keeps generating random permutations of the input, until the substring restriction is satisfied. I think this can be golfed a bit further.
[Answer]
# Mathematica, 89 bytes
```
(For[c=Characters@#;d=c,#⋂#2&@@(Partition[#,3,1]&/@{c,d})!={},d=RandomSample@c];d<>"")&
```
Generates random permutations until there is the permutation and the original have no common substring of length 3.
[Answer]
# CJam, 48 bytes
This is super huge. I am not sure if there are any good algorithms to do the task. This is just a brute force.
```
q:Q;{Q(+2/zs:R,3-_0>{,{RQI>3<#W>}fI}{;}?]1b0>}gR
```
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
I'm pretty new to code golfing, so I gave one of my first shots to a space invader clone called ["Invas!on".](https://gist.github.com/misantronic/7700fc01484a22c2c717) It's a little less than 500 bytes, fully ASCII generated, and covers moving around and shooting at the aliens. There is also a little point system.
My specific question is about generating enemy patterns. I want to generate something like this:
```
...x.x.x.x.x.x...
..x.x.x.x.x.x.x..
...x.x.x.x.x.x...
```
...and so on.
Currently, I'm using this code:
```
for(b=[],j=2;j<136;j+=2)b.push(j),j==14&&(j=41)||j==55&&(j=80)||j==94&&(j=121)
```
It's just a loop that pushes enemy positions into an array `b`. Positions are every two spaces on a line, with a varying margin on both sides.
What is the shortest way to do this?
[Answer]
### 58 : -20 bytes(25%) from OP
```
for(b=[],j=2;j<136;j+=j==14||j==94?29:j==55?27:2)b.push(j)
```
This should do the same thing as your code, but without all the ugly parentheses and explicit assignments. Since all you're really doing is adding each time, all you have to do is check how much to add.
I should note that I have no idea where you got the numbers from in the original code. Since it doesn't *seem* to match the pattern you gave, I assume the pattern is just an example (and the actual lines are longer), or there's something going on in your other code (not shown here). Either way, I matched up my positions with yours.
---
For a fixed pattern like this, though, it might be shorter to just encode it in a bitmap-style string or bitmasked integer. Doing it loop-style allows you to vary it a bit easier, but if your pattern is constant it's something to be aware of. For instance, your shown pattern has 51 positions, which are either "on" or "off". This means it needs 51 bits for a straight bitmask, which can fit in a [single number](https://stackoverflow.com/a/307200/752320):
```
000101010101010000010101010101010000010101010101000 = 0xAAA0AAA82AA8
```
So, if you can unpack that into an array efficiently, you may be able to score some more bytes. *Unfortunately*, I'm no Javascript whiz, so I couldn't get it shorter this way, leaving it at 61 bytes. Others may be able to improve upon this:
```
for(b=[],j=0,m=0xAAA0AAA82AA8;m>0;m>>>=1,j++)if(m&1)b.push(j)
```
So for this *exact* pattern, the first method is shorter (for me). If the pattern wasn't so evenly spaced (allowing simple additions), the second would most likely end up shorter.
] |
Subsets and Splits