text
stringlengths 180
608k
|
---|
[Question]
[
I was looking around on the web and I found this Google Code Jam Puzzle. I really liked it so I decided to post it here.
>
> ### New Lottery Game
>
>
> The Lottery is changing! The Lottery used to have a machine to
> generate a random winning number. But due to cheating problems, the
> Lottery has decided to add another machine. The new winning number
> will be the result of the bitwise-AND operation between the two random
> numbers generated by the two machines.
>
>
> To find the bitwise-AND of *X* and *Y*, write them both in binary; then a
> bit in the result in binary has a 1 if the corresponding bits of *X* and
> Y were both 1, and a 0 otherwise. In most programming languages, the
> bitwise-AND of *X* and *Y* is written *X&Y*.
>
>
> For example: The old machine generates the number *7 = 0111*. The
> new machine generates the number *11 = 1011*. The winning number will
> be *(7 AND 11) = (0111 AND 1011) = 0011 = 3*.
>
>
> With this measure, the Lottery expects to reduce the cases of
> fraudulent claims, but unfortunately an employee from the Lottery
> company has leaked the following information: the old machine will
> always generate a non-negative integer less than *A* and the new one
> will always generate a non-negative integer less than *B*.
>
>
> Catalina wants to win this lottery and to give it a try she decided to
> buy all non-negative integers less than *K*.
>
>
> Given *A*, *B* and *K*, Catalina would like to know in how many different
> ways the machines can generate a pair of numbers that will make her a
> winner.
>
>
> Could you help her?
>
>
> **Input**
> The first line of the input gives the number of test cases, T. T lines
> follow, each line with three numbers A B K.
>
>
> **Output**
> For each test case, output one line containing "Case #x: y", where x
> is the test case number (starting from 1) and y is the number of
> possible pairs that the machines can generate to make Catalina a
> winner.
>
>
> **Limits**
> 1 ≤ *T* ≤ 100. Small dataset
>
>
> 1 ≤ *A* ≤ 1000. 1 ≤ *B* ≤ 1000. 1 ≤ *K* ≤ 1000. Large dataset
>
>
> 1 ≤ *A* ≤ 109. 1 ≤ *B* ≤ 109. 1 ≤ *K* ≤ 109. Sample
>
>
>
> ```
> Input Output
> 5 Case #1: 10
> 3 4 2 Case #2: 16
> 4 5 2 Case #3: 52
> 7 8 5 Case #4: 2411
> 45 56 35 Case #5: 14377
> 103 143 88
>
> ```
>
> In the first test case, these are the 10 possible pairs generated by
> the old and new machine respectively that will make her a winner:
> <0,0>, <0,1>, <0,2>, <0,3>, <1,0>, <1,1>, <1,2>, <1,3>, <2,0> and
> <2,1>. Notice that <0,1> is not the same as <1,0>. Also, although the
> pair <2, 2> could be generated by the machines it wouldn't make
> Catalina win since *(2 AND 2) = 2* and she only bought the numbers 0 and
> 1.
>
>
>
Here's the link for actual problem: <https://code.google.com/codejam/contest/2994486/dashboard#s=p1>
This is code-golf, so shortest code wins.
Good Luck
[Answer]
# Ruby, 107
I expected this would be a much shorter program.
```
gets
loop{a,b,k=gets.split.map &:to_i
puts"Case ##{$.-1}: #{[*0...a].product([*0...b]).count{|x,y|x&y<k}}"}
```
## Explanation
* The first line of input can be ignored.
* `$.` is the last read line number.
* `[*0...x]` is a quick way to turn the `Range` into an `Array`. It uses the splat operator (`*`). Note that the `Range` is an exclusive one (`...` instead of `..`).
* `Array#count` takes a block. It will only count the elements for which the block returns a truthy value.
[Answer]
## APL (63)
It's the I/O that costs a lot.
```
↑{a b k←¯1+⍳¨⎕⋄'Case #',(⍕⍵),': ',⍕+/∊k∊⍨a∘.{2⊥∧/⍺⍵⊤⍨10/2}b}¨⍳⎕
```
Explanation:
* `{`...`}¨⍳⎕`: read a number N from the keyboard, and run the following function for each number from 1 to N.
* `a b k←¯1+⍳¨⎕`: read three numbers from the keyboard, generate a list from 0..n-1 for each, and store these in `a`, `b`, and `k`.
* `a∘.{`...`}b`: for each combination of values from `a` and `b`:
+ `⍺⍵⊤⍨10/2`: get the 10-bit binary representation for both values (this is enough given the limits)
+ `∧/`: *and* together all pairs of bits
+ `2⊤`: turn it back into a number
* `k∊⍨`: for each of these values, test if it is in `k`
* `+/`: sum the result
* `'Case #',(⍕⍵),': ',⍕`: generate the output string for this case
* `↑`: turn the result into a matrix, so each string ends up on a separate line.
Test:
```
↑{a b k←¯1+⍳¨⎕⋄'Case #',(⍕⍵),': ',⍕+/∊k∊⍨a∘.{2⊥∧/⍺⍵⊤⍨10/2}b}¨⍳⎕
⎕:
5
⎕:
3 4 2
⎕:
4 5 2
⎕:
7 8 5
⎕:
45 56 35
⎕:
103 143 88
Case #1: 10
Case #2: 16
Case #3: 52
Case #4: 2411
Case #5: 14377
```
[Answer]
## Golfscript - 74 64
Here is my Golfscript solution (could probably be improved):
```
n/(;0:m;{[~0:w.{{.2$&3$<w+:w;)}4$*;)0}5$*];'Case #'m):m': 'w n}%
```
Here is the pseudocode I used for this:
```
Split string at newlines
Get rid of first element (this is not needed, as I am looping through each element anyway)
Let m=0 (case #)
For each group of 3 numbers A, B, and K:
Let w=0 (number of winning combinations)
For(C,0,A-1)
For(D,0,B-1)
If (A&B)<K
Let w=w+1 (one more winning combination)
End
End
End
Let m=m+1 (case # incremented)
Output("Case #",m,": ",w,"/n")
End
```
Assumes valid input.
[Answer]
## CJam - 62
Could probably be improved; this is just a port of my Golfscript answer.
```
qN/(;{[~0_{{_2$&3$<V+:V;)}4$*;)0}5$*];"Case #"T):T": "V0:V;N}%
```
[Answer]
# Ruby - 145
I'm still learning Ruby, so there's probably a shorter way to do this.
```
(1..gets.to_i).each{|_|a,b,k=gets.split.map{|x|x.to_i};x=0;(0...k).each{|i|(0...a).each{|j|(0...b).each{|k|x+=1 if j&k==i}}};p"Case ##{_}: #{x}"}
```
**Ungolfed**:
```
( 1 .. gets.to_i ).each{ | _ |
a, b, k = gets.split.map{ | x | x.to_i }
x = 0
( 0 ... k ).each{ | i |
( 0 ... a ).each{ | j |
( 0 ... b ).each{ | k |
x += 1 if j & k == i
}
}
}
p "Case ##{_}: #{x}"
}
```
[Answer]
## J, 90 (70)
I/O to stdin/stdout, works as a script (**90**).
```
,&LF@('Test #'&,)"1@(":@#,{:)\@:}.@:(': '&,"1)@(+/@,@(>`(17 b./&i.)/@|.)&.".;._2)&.stdin''
```
Input on stdin, output implicit in REPL (akin to APL, I believe) (**70**).
```
'Test #',"1(":@#,{:)\}.': ',"1+/@,@(>`(17 b./&i.)/@|.)&.".;._2 stdin''
```
Ergh, J isn't good at I/O requirements like these.
For the curious, the part doing the heavy work is `+/@,@(>`(17 b./&i.)/@|.)&.".`, which solves a single line of the problem (taking and returning a string).
[Answer]
## CJAM - 57
```
0li{)"Case #"\':Sl~:K;L\{(2$,{1$&@+\}%~}h;\;{K<},,N4$}\*;
```
I think this can be golfed further.
```
0 acts as a counter for the case #
li{ accepts the first line of input as integer/opens block
) iterates counter
"Case #"\':S adds "Case #X: " to stack (though in 4 parts)
l~:K;L\ takes next line of input, assign K, add null array
{
(2$, decrease B and generate list of number <A
{
1$& Copy the current value of B, do & with current n<A
@+\ Add the new possible lottery number to array
}%~ loop for each element if the list of numbers <A
}h loop which repeats for all numbers less than B
;/;{K<},, trim and count the possible numbers less than K
N4$ add new line and copy the counter back in place
}\* runs the block T times
; removes the counter so it doesn't print
```
Output:
```
Case #1: 10
Case #2: 16
Case #3: 52
Case #4: 2411
Case #5: 14377
```
] |
[Question]
[
This is a simple one: create the shortest browser script to change every appearance of force on a web page into horse. This script needs to be able to be pasted into the console and work on most modern browsers.
You must replace **all** occurences of the word force and conjugates of the word force (forcing, forced, reinforce). The cases must also be preserved.
You must not change any occurences which are not visible when the page is displayed in a browser. For example, meta tags or comments.
## Example
This is a `fOrcE log`. It makes people who touch it very forceful. Don't try forcing it.
This is a `hOrsE log`. It makes people who touch it very horseful. Don't try horsing it.

Unfortunately this is a Javascript only challenge. The shortest code wins.
[Answer]
## 175 bytes, ES5, XPATH
This tests successfully in the latest Firefox and Chrome. Criticism is welcome! This is my first golf swing, and I hope I'm doing it right.
```
d=document,f=d.evaluate('//text()',d,{},7,{});for(i=0;t=f.snapshotItem(i++);)t.data=t.data.replace(/(f)(or)(c)/ig,function(a,b,c,e){return(b=='f'?'h':'H')+c+(e=='c'?'s':'S')})
```
The `document.evaluate()` method is supported by [all major browsers except IE](https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate#Browser_compatibility), which I hope satisfies the requirement for "most modern browsers". And because the XPath selector selects only [text nodes](http://www.w3.org/TR/1999/REC-xpath-19991116/#section-Text-Nodes), this ought to leave attributes, comments, namespaces, and other data not intended for display untouched without needing to check for each node's `offsetParent`.
### Ungolfed version:
```
var force = document.evaluate('//text()', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; textNode = force.snapshotItem(i++); /* nothing */) {
textNode.data = textNode.data.replace(
/(f)(or)(c)/ig,
function (full, $1, $2, $3) {
return ($1 == 'f' ? 'h' : 'H' )
+ $2
+ ($3 == 'c' ? 's' : 'S' );
}
);
}
```
---
Or if I replace `function / return` with ECMA6 fat arrow notation, I can get it down to 163 characters.
```
d=document,f=d.evaluate('//text()',d,{},7,{});for(i=0;t=f.snapshotItem(i++);)t.data=t.data.replace(/(f)(or)(c)/ig,r=(a,b,c,e)=>(b=='f'?'h':'H')+c+(e=='c'?'s':'S'))
```
This syntax currently only works in Firefox though, I think. Until more browsers adopt this syntax, the 175-byte solution above shall remain my official entry for the game.
[Answer]
# ECMAScript 5, ~~248~~ ~~233~~ ~~193~~ ~~191~~ 182 bytes
```
for(w=(d=document).createTreeWalker(d,4);t=w.nextNode();)
if(t.parentNode.offsetParent)t.data=t.data.replace(/(f)(or)(c)/gi,
function(a,b,c,d){return(b<'f'?'H':'h')+c+(d<'c'?'S':'s')})
```
Tested in Chrome and Firefox.
### Ungolfed version
We should only modify visible TextNodes; URLs, attributes, etc. are not displayed in the browser. We can use a [TreeWalker](https://developer.mozilla.org/en/docs/Web/API/TreeWalker "TreeWalker - Web API Interfaces | MDN") to find all of them. Visible TextNodes will be identified by checking if their ParentNode has a truthy [offsetParent](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetParent "HTMLElement.offsetParent - Web API Interfaces | MDN").1
```
// Create a TreeWalker that walks through all TextNodes.
var walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT, null, false);
// While there are nodes left,
while(node = walker.nextNode())
// if the node is visible,
if(node.parentNode.offsetParent)
// search for the string "forc" (ignoring case)
node.data = node.data.replace(/(f)(or)(c)/gi,
// and replace an uppercase/lowercase F/C with an uppercase/lowercase H/S.
function(match, F, OR, C)
{
return (F != 'f' ? 'H' : 'h') + OR + (C != 'c' ? 'S' : 's')
}
)
```
1 This is buggy in IE 9.
[Answer]
## 200 bytes, ES6
Here is an ES6 version. Run it in latest Firefox's web console.
```
for(a=document.all,i=0;n=a[i++];)(p=>p&&p.offsetParent?n.innerHTML=n.innerHTML.replace(/f[o0]rc(e|ing)/gi,m=>(v=>{k=[...m];k[0]=k[0]<'F'?'H':'h';k[3]=k[3]<'C'?'S':'s'})()||k.join("")):0)(n.parentNode)
```
~~I'll add the ungolfed version if requested :)~~
Here is the ungolfed version
```
var all = document.all;
for (var i = 0; i < all.length; i++) {
if (all[i].parentNode && all[i].parentNode.offsetParent) {
all[i].innerHTML = all[i].innerHTML.replace(/f[o0]rc(e|ing)/gi, function(matched) {
var k = matched.split(""); // convert to array
k[0] = k[0] == "F"? "H" : "h";
k[3] = k[3] == "C"? "S" : "s";
return k.join("");
})
}
}
```
] |
[Question]
[
Objective:
* Write one program that outputs sourcecode for another program that outputs words.
General information:
* Any programming language.
Rules:
1. Your programs should not take any input. (from user, filename, network or anything).
2. The generated program sourcecode must not be in the same programming language as the original.
3. The output from the generated program should be exactly every third character from the original sourcecode, starting at character #3 (first character in sourcecode is #1).
4. Sourcecode constraints: **Maximum 1500 characters**
5. Sourcecode constraints for generated program: **Maximum 250 characters**
**Scoring** is based on the output from the generated program, you get points for the following words (any combination of upper/lowercase):
```
me - 2 points
ore - 3 points
freq - 5 points
pager - 7 points
mentor - 11 points
triumph - 13 points
equipage - 17 points
equipment - 19 points
equivalent - 23 points
equilibrium - 29 points
unubiquitous - 31 points
questionnaire - 37 points
```
Each word can be repeated but lose 1 point for each repetition. For example:
* four of `Equilibrium` (in any place) in the output gives: 29+28+27+26 points.
Letters in the output can be used in more than one word, for example:
* `equipager` = `equipage` and `pager` = 17+7 points.
Best score wins. Good luck, have fun!
[Answer]
## Befunge-98, produces zsh script: ~~150 1053 1113~~ 1139 points
The Befunge-98 program (1500)
```
:#q #u!#e!#sa#t7#i6#o*#n*#n*#aj#ib#r9#e*#q:#u:#i:#p:#a:#g:#e:#r:#e:#q3#u+#i,#pc#m+#e,#nf#t+#o,#r4#e8#q*#u,#i6#l+#i:#b,#r4#i8#u*#m,#e,#qb#u+#i:#p:#m:#e:#n:#t,#o4#r8#e*#q,#u,#i4#l8#i*#b,#r,#i4#u8#m*#u,#n,#u4#b8#i*#q,#u,#i4#t8#o*#u,#s,#q4#ua#e*#s-#t,#i2#o+#n,#n,#a5#i+#r,#ec#q+#u,#i4#v8#a*#l,#e9#n5#t*#-,#qb#ua#e*#s,#t4#i8#o*#n,#n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s:#q2#u+#e0#sg#t,#i3#o+#n:#n #a3#i9#rb#e*#q*#u #i`#v #a!#l #e1#n+jt@#-
```
produces the zsh shell script (127)
```
for i in n n n n n;echo -n questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-
```
which in turn of course outputs (500)
```
questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-
```
when executed. This is worth **1139** points (assuming my calculations are correct).
### Early version (saved here because it's much easier to try to understand)
The Befunge-98 program
```
:#m #e!#n!#tb#o9#r*#e*#qj#ub#i9#l*#i:#b:#r:#u2#m+#f,#r,#e5#q+#u,#ec#s+#t,#i8#o4#n*#n,#a #r #i #e #q #u #i #p #m #e #n #t #r #i #u:#m2#p+#h0#ug#n,#u3#b+#i:#qf#uf#i*#t`#o5ju @s#_
```
produces the Bourne shell script (including a bunch of trailing spaces)
```
echo mentorequilibrumfrequestionnariequipmentriumphunubiquitous
```
Here is the same program transposed, for easier reading.
```
: !!b9**jb9*:::2+,,5+,c+,84*, :2+0g,3+:ff*`5 #
########################################################j@_
mentorequilibrumfrequestionnariequipmentriumphunubiquitous
```
[Answer]
## Shellscript and Python - 514 Points
My submission is written in shellscript:
```
echo print"'h rthtq""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""e""q""u""i""l""i""b""r""i""u""m""e""q""u""i""l""i""b""r""i""u""m""e""q""u""i""l""i""b""r""i""u""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r'"
```
It will output the following python code (249 characters):
```
print'h rthtquestionnairequestionnairequestionnairequestionnairequestionnairequestionnairequestionnairequestionnaireunubiquitousunubiquitousunubiquitousunubiquitousunubiquitousequilibriumequilibriumequilibriumentorequipmentorequipmentorequipmentor'
```
Whose output contains:
```
8 * questionnaire: 37+36+35+34+33+32+31+30
5 * unubiquitous: 31+30+29+28+27
3 * equipment: 19+18+17
4 * mentor: 11+10+9+8
3 * ore: 3+2+1
6 * me: 2+1
```
for a total of 514 Points.
Not very sophisticated, i am sure others can do better :)
[Answer]
## JavaScript & REBEL - 198
Initial program:
```
console.log( "nll(llf r e q u e s t i o n n a i r e q u i p a g e r u n u b i q u i t o u s e q u i p m e n t o r e q u i v a l e n t r i u m p h e q u i l i b r i u m+.+ +.$0+;/ + +//.+/$>$0")+0 ;
```
Generated program:
```
nll(llf r e q u e s t i o n n a i r e q u i p a g e r u n u b i q u i t o u s e q u i p m e n t o r e q u i v a l e n t r i u m p h e q u i l i b r i u m+.+ +.$0+;/ + +//.+/$>$0
```
Output:
```
nll(llfrequestionnairequipagerunubiquitousequipmentorequivalentriumphequilibrium+.+ +.$0+;
```
Notes:
Each word is output exactly once, except "me" which is output twice.
You will notice that the generated program is exactly 250 characters long. I didn't notice this until it was written. I consider myself lucky.
[Answer]
# Python that outputs C, 947
```
##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s
print 'main(i,j){for (i=0;i<7;i++) printf("questionnairequipagerequipmentorequivalentriumphunubiquitous");printf("a(jf =i;+pn(utniqpeqpnruanipniiu)rt\"a(jf =i;+pn(utniqpeqpnruanipniiu)rt\"j=+(nppuii)\\)");}'
```
I use the longest words (that give the best score) and overlapping words too (equipage-pager, as for the example). This is how the score is computed:
me= 2+1+0+0+0+0+0=3
ore= 3+2+1+0+0+0+0=6
pager= 7+6+5+4+3+2+1=28
mentor= 11+10+9+8+7+6+5=56
triumph= 13+12+11+10+9+8+7=70
equipage= 17+16+15+14+13+12+11=98
equipment= 19+18+17+16+15+14+13=112
equivalent= 23+22+21+20+19+18+17=140
unubiquitous= 31+30+29+28+27+26+25=196
questionnaire= 37+36+35+34+33+32+31=238
Total is **947**.
Edit: now the generated program should output "exactly every third character from the original sourcecode" :)
[Answer]
## Javascript and Golfscript - 1074 points
Javascript (1500 chars):
```
/*e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p a g e r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p m e n t o r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p a g e r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p m e n t o r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p a g e r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p m e n t o r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p a g e r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p m e n t o r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p a g e r e q u i l i b r i u m u n u b i q u i t o u s q u e s t i o n n a i r e q u i p m e n t o r*/console.log( "5{ 2{'equilibriumunubiquitousquestionnairequip' 'ager'}* 'mentor' \\;}* 'cseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22 '" );
```
Generated Golfscript (128 chars): [Test GolfScript online](http://golfscript.apphb.com/?c=NXsgMnsnZXF1aWxpYnJpdW11bnViaXF1aXRvdXNxdWVzdGlvbm5haXJlcXVpcCcgICAnYWdlcid9KiAgICdtZW50b3InIFw7fSogICdjc2VvIDUyZWlidW5paXV1dG5pcXAgYXIqIGVvIDsgY28yYml1aSAqbyAydSoyMiAgJyA=)
```
5{ 2{'equilibriumunubiquitousquestionnairequip' 'ager'}* 'mentor' \;}* 'cseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22 '
```
Output (500 chars):
```
equilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorcseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22
```
Score:
```
10 * questionnaire (37+36+35+34+33+32+31+30+29+28) = 325
10 * unubiquitous (31+30+29+28+27+26+25+24+23+22) = 265
10 * equilibrium (29+28+27+26+25+24+23+22+21+20) = 245
5 * equipage (17+16+15+14+13) = 75
5 * pager (7+6+5+4+3) = 25
5 * equipment (19+18+17+16+15) = 85
5 * mentor (11+10+9+8+7) = 45
4 * ore (3+2+1) = 6
10 * me (2+1) = 3
```
Total: 1074
UPDATE: Managed to gain some points by changing GolfScript loops from 3\*3 to 5\*2.
] |
[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/2223/edit).
Closed 1 year ago.
[Improve this question](/posts/2223/edit)
**Write a program that prints the shapes of** [one-sided polyominoes](http://en.wikipedia.org/wiki/Polyomino).
Given input 4 (tetrominos), a sample output would be:
```
* * * *
* * ** ** ** *
** ** ** * * *** ****
```
You are not restricted with respect to orientation, ordering or layout as long as polyominoes are not connected and not duplicated. (E.g. you can print the shapes in a column rather than a row)
Provide code that inputs a number from 3 to 6 and outputs the one-sided polyominoes of that size. The expected number of polyominoes output are 2, 7, 18, and 60 for 3, 4, 5, and 6 as inputs respectively.
Shortest code wins, present your solution for number 4.
[Answer]
## Python, 398 392 chars
```
n=input()
r=range
T=lambda P:set(p-min(p.real for p in P)-min(p.imag for p in P)*1j for p in P)
A=[]
for i in r(1<<18):
P=[k%3+k/3*1j for k in r(18)if i>>k&1]
C=set(P[:1])
for x in P:[any(p+1j**k in C for k in r(4))and C.add(p)for p in P]
P=T(P)
if not(C^P or P in A or len(P)-n):
for y in r(4):print''.join(' *'[y+x*1j in P] for x in r(6))
A+=[T([p*1j**k for p in P])for k in r(4)]
```
Polyominos are represented as sets of complex numbers representing the cells of the polyomino. For example, T takes a polyomino and translates it so the minimum real and imaginary coordinates are 0.
The outer loop iterates through all 2^18 3x6 grids, generating a potential polyomino P, making sure P is connected (by computing C, the part of the polyomino connected to P[0]), checking that P isn't in the list A of previously found polyominos, and verifying that P has exactly n cells. Any new polyomino is added to A in all 4 rotations.
It takes two minutes or so to run to completion. Here's the result for n=4:
```
**
*
*
*
**
*
**
**
*
**
*
*
*
**
*
**
*
****
```
[Answer]
## Ruby, 266 241 320 (227 without reflections)
Given the input restrictions, it's easier to just use a bitmap of all the polyominos.
```
puts [%w[13 3],%w[1vqxip 1s9b3b],%w[1j85qxc81ax0oxld 1db08aq5w1vdul13 172qaw25hgn8jn5t],%w[5l91ancci09g0iuurrdbkbrsl58jjiodia8irxlivoufjjse42o4l8hlcz 3qbvfj70ksz14cngk9exust0w1qjshykauo6yvyyn3j6oefyy1xc58hsoj 26c0102a8vw34q88pktwlkepxzcslicg6ydtrz4zhyyutd4bukh73187qb]][gets.hex-3].map{|n|n.to_i(36).to_s(2).tr'10','* '}
```
Old version (outputs just the free polyominoes):
```
puts [%w[13 3],%w[9iz3 a5z],%w[cfu9zai70z b3tsb0pge1 12t8eks810j],%w[5wgmz704fjqc593xfwrmkwb7k0j9ztr31v fr8weq5t88qdxp93hit2fh8899qcbr2a9f 10r578ajcw2n15dwywsm0ep601kiv41cco3]][gets.hex-3].map{|n|n.to_i(36).to_s(2).tr'10','* '}
```
Output for n=4:
```
** ** * * **** ** *
** ** *** *** ** ***
```
[Answer]
### Golfscript, 221 chars
Also 221 bytes. Inspired by Lowjacker's approach, but moderately different in actual implementation (and produces one-sided rather than two-sided polyominos).
Because some of the characters used, while valid Unicode codepoints (and one byte each in UTF-8), are non-printable, I present the base-64 encoding of the script:
```
fidAQEAVRRVALVs9TUZFUwhgA0BrdjVXGm4VOl8aDgMZfBdoVQQzNk0YLQ9eXCciBhwQH0ADDW9E
KlomSXgoLBxxI1oEeB9XPm51GF43bHBKQzl3WQ5vXTJCTABfEz4bJBlaWX0XL2QVDF5ZXFw5BxpF
IzNUKmUtYwEEfQEKckMSbjAlQmhYHShQaAtjK1QFbnt5WQokFkNkHgNlL35cXCU6Hj8nIkAiLz0x
MjdiYXNlIDRiYXNlWzNdL3tbKVxbMl0vLi0xJUAqXXt7eyIgKiI9fSVuK30vbn0vfS8=
```
And the script itself with the magic strings substituted:
```
~"@@@Magic@strings@go@here""@"/=127base 4base[3]/{[)\[2]/.-1%@*]{{{" *"=}%n+}/n}/}/
```
Example execution:
```
$ golfscript.rb poly.gs <<<"4"
****
***
*
*
***
**
**
***
*
**
**
**
**
```
] |
[Question]
[
Write the shortest code to find the remainder when an input number N is divided by 2^M. You cannot use /,\* and % operator.
```
Input Specification
Number of test cases followed by a pair of integers on each line.
Sample Input
1
150 6
Sample Output
22
Limits
1<T<1000
1<N<2^31
1<B<31
Time Limit
1 Sec
```
[Answer]
```
scanf("%d", &T);
while(T--){
scanf("%d,%d", &N,&M);
printf("%d",N&~(~0 << M));
}
```
[Answer]
Uh, guys, in pretty much any language, it would be
```
N & (1 << M - 1)
```
[Answer]
## Golfscript - 16 chars
```
~]1>2/{~2\?(&n}/
```
For a single pair or numbers this would sufficient
```
~2\?(&
```
By the way, the `/` does not stand for division here :)
[Answer]
## Perl, 31
```
<>;/ /,say($`&~(-1<<$'))while<>
```
Perl 5.10 or later, run with `perl -E '<code here>'`
[Answer]
# Java
With whitespace to make readable:
```
long F(long M, long N) {
M = 2<<M;
while(N>=M) N-=M;
return N;
}
```
[Answer]
# Racket (scheme) 29 bytes
Kinda cheating because racket doesn't even have the % operator:
```
(λ(n m)(modulo n(expt 2 m)))
```
[Answer]
# J, ~~15~~ ~~12~~ 9 bytes
6 bytes thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles).
```
#.@#:~#&2
```
## Previous 12-byte version
```
#.@({.~-)~#:
```
### Usage
```
>> f =: #.@({.~-)~#:
>> 6 f 150
<< 22
```
Where `>>` is STDIN and `<<` is STDOUT.
### Explanation
`#:` converts `n` to base 2.
`({.~-)~` then takes the last `m` digits from it
`#.` converts it back to base 2.
## Previous 15-byte version:
```
2#.(0-[){.[:#:]
```
### Usage
```
>> f =: 2#.(0-[){.[:#:]
>> 6 f 150
<< 22
```
Where `>>` is STDIN and `<<` is STDOUT.
### Explanation
`[:#:]` converts `n` to base 2.
`(0-[){.` then takes the last `m` digits from it
`2#.` converts it back to base 2.
[Answer]
# SmileBASIC, 36 characters
```
INPUT N,M?N AND(1<<M)-1
```
There's basically only one solution to this...
] |
[Question]
[
[Emmet](https://emmet.io/) is a text-editor and IDE plugin for writing HTML code using much fewer keypresses. You might think of it like a code-golfing HTML preprocessor. Its syntax is based on CSS selectors.
Your challenge is to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") an implementation of Emmet. Given some Emmet code, output the resulting HTML.
Note that for the purposes of this challenge, you will not have to handle element "shortcuts" like `bq` → `blockquote` or `a` → `a[href]`. This version of Emmet does not support item numbering. You also do not need to handle the difference between block and inline elements having different spacing.
All elements should have at least one whitespace character (space, tab, newline, whatever) wherever whitespace is shown here, but you don't need to have the indentation shown in the examples.
# Syntax
(Paraphrased from [Emmet's documentation](https://docs.emmet.io/abbreviations/syntax/))
Emmet basically just describes an HTML document using syntax similar to CSS selectors. It uses symbols to describe where each element should be placed in the document.
### Structure operators
* Child: `>`
```
div>ul>li
<div>
<ul>
<li></li>
</ul>
</div>
```
* Sibling: `+`
```
div+p+blockquote
<div></div>
<p></p>
<blockquote></blockquote>
```
* Put them together:
```
div+div>p>span+em
<div></div>
<div>
<p>
<span></span>
<em></em>
</p>
</div>
```
* Climb-up: `^`
```
div+div>p>span+em^blockquote
<div></div>
<div>
<p>
<span></span>
<em></em>
</p>
<blockquote></blockquote>
</div>
```
```
div+div>p>span+em^^blockquote
<div></div>
<div>
<p>
<span></span>
<em></em>
</p>
</div>
<blockquote></blockquote>
```
* Multiplication: `*`
```
ul>li*5
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
```
```
p>span*2+a
<p>
<span></span>
<span></span>
<a></a>
</p>`
```
```
p>span*2^q
<p>
<span></span>
<span></span>
</p>
<q></q>
```
* Grouping: `()`
```
div>(header>ul>li*2>a)+footer>p
<div>
<header>
<ul>
<li>
<a></a>
</li>
<li>
<a></a>
</li>
</ul>
</header>
<footer>
<p></p>
</footer>
</div>
```
### Attribute operators
* ID `#` and class `.`
```
div#header+div.page+div#footer.class1.class2.class3
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
```
* Custom attributes `[attr]`
```
td[title="Hello world!" colspan=3]
<td title="Hello world!" colspan="3"></td>
```
```
td[title=hello colspan=3]
<td title="hello" colspan="3"></td>
```
```
td[title colspan]
<td title="" colspan=""></td>
```
### Text
Put text in curly braces:
```
p{Hello, World!}
<p>Hello, World!</p>
```
```
a.important[href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"]{click}
<a
class="important"
href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
>
click
</a>
```
```
a[href]{click}+b{here}
<a href="">click</a>
<b>here</b>
```
```
a[href]>{click}+b{here}
<a href="">
click
<b>
here
</b>
</a>
```
```
p>{Click}+button{here}+{to continue}
<p>
Click
<button>
here
</button>
to continue
</p>
```
```
p{(a+b)*c>a+b*c}
<p>{(a+b)*c>a+b*c}</p>
```
# Additional test cases
```
div>p[block]*2>{abc}+span*2{123}+{def}
<div>
<p block="">
abc
<span>123</span>
<span>123</span>
def
</p>
</div>
```
```
a[href="https://example.com/index.html?a[]={1}&a[]={2}"]{This is an example usage of array parameters "a[]" in url.}
<a href="https://example.com/index.html?a[]={1}&a[]={2}">
This is an example usage of array parameters "a[]" in url.
</a>
```
---
Your program should give proper output for all of the examples outlined above. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code per language, measured in bytes, wins!
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 465 bytes
```
\^+
$&+
+`([^>]+>((\()|(?<-3>\))|(?(3)>)|[^()>])+(?(3)^))\^
($1)
\)|$
/$&
{%`^( *[^()>+]+)\*(\d+)(.*)
$2*$($1$3¶)
G`.
%`^(( *)((\()|(?<-4>\))|(?(4)[>+])|[^()>+])+(?(4)^))\+
$1/¶$2
%`^( *)(((\()|(?<-4>\))|(?(4)[>+])|[^()>+])+(?(4)^))\>(.+)
$1$2¶ $1$5¶$1/$2
)%`^( *)\((.+)\)/$
$1$2
%`^( *)((/|())\w+)(.*?)(/)?$
$1<$2>$#4*$5$#6*$(</$2>
>#(\w+)
id="$1">
+`>\.(\w+)
class="$1">
+`(class=".+)" class="
$1
]
]
+`>\[(\w+)(="([^"]*)"|=([^ ]*))?
$1="$3$4">[
[]{[]|}/?
```
[Try it online!](https://tio.run/##lZPNjpswFIX3fgpKPCMbtyBCUqnVYBZdTLezmkr8KAQ8AxoSKDGDKshr5QHyYum1SSZVW1XqytfnfvccX6K0Qpbb1D3dkPvVKUoYwrcMsRUJEx4zTkhE6EiCuw8ej6iqiEc5HcOEUB5Tpu8JpVGCCHYpiuiIkYNv0XCzSohhaY7FjEYWiXJGiW1RhOcWBhp7xwNF9ysbKRZgek1bXNIWNIT5cyCbEhc6EV7qOscDnqMpCqb/Z5wTm8FTXDw/HgwDziV4uQ7Y0bNfRBQSUQdr7BrjjAQMer1NQIlDA0Xc4TnHs4WFl3j2ERa8Ay@O@IwoEhll7pvYNTl8Wx7ZZzGr0t3uTSfnK6SalxYYGyhGRqznQj1HfBN@HjO2qDn6UBlQ0cBAsAV4eXhh8hCF8RDG494J0Amj4@GUl6@8q3hVIqhYw9ZVnb1872optKDaDd816ZaJzZ9K8i88@bWrM6ylojgpRJqLdsq15jyl7KkGqOWN6s@mtjKzm/RZqGI2AbZe352O@XR4SOahLGUlfPOrqKra6Ou2yt/Bt6or9RTfi69IoYm/dC5ajJpB27w3HrXPHqV2uWnqVqZbGRatePLNQspm99lx@r63f9Sd7NbCzuqN06cyK4JXP3/oF/2nx@dv2YMZD1lVZi9go4cvV7YeCtGKN5n/rjd8@KIUA6ROyno76WwwpFpgC//PTux/Ag "Retina – Try It Online") Link includes test cases. Explanation:
```
\^+
$&+
```
Add a `+` after any `^`s.
```
+`([^>]+>((\()|(?<-3>\))|(?(3)>)|[^()>])+(?(3)^))\^
($1)
```
Convert `^`s into the equivalent brackets.
```
\)|$
/$&
```
Innermost elements should be on a single line.
```
{`
)`
```
Process as much as possible.
```
%`^( *[^()>+]+)\*(\d+)(.*)
$2*$($1$3¶)
G`.
```
Process multiplications.
```
%`^(( *)((\()|(?<-4>\))|(?(4)[>+])|[^()>+])+(?(4)^))\+
$1/¶$2
```
Process siblings.
```
%`^( *)(((\()|(?<-4>\))|(?(4)[>+])|[^()>+])+(?(4)^))\>(.+)
$1$2¶ $1$5¶$1/$2
```
Process children, appending a closing tag after them.
```
%`^( *)\((.+)\)/$
$1$2
```
Unwrap lines starting and ending in brackets.
```
%`^( *)((/|())\w+)(.*?)(/)?$
$1<$2>$#4*$5$#6*$(</$2>
```
Surround tags with `<>`s, removing attributes from closing tags, and add closing tags for single-line tags.
```
>#(\w+)
id="$1">
```
Process ids.
```
+`>\.(\w+)
class="$1">
+`(class=".+)" class="
$1
```
Process classes.
```
]
]
+`>\[(\w+)(="([^"]*)"|=([^ ]*))?
$1="$3$4">[
```
Process attributes. I can do this on one line but it turns out to be a byte longer.
```
[]{[]|}/?
```
Remove the remaining syntax.
[Answer]
# Python3, 1152 bytes:
```
import re
R=re.findall
def U(t):
[N]=R('^\w+',t);n='<'+N
if(i:=R('(?<=#)\w+',t)):n+=f' id="{i[0]}"'
if(c:=R('(?<=\.)\w+',t)):n+=' class="'+' '.join(c)+'"'
if(a:=R('(?<=\[)[^\]]+',t)):n+=' '+' '.join(i+'=""'if'='not in i else re.sub('(?<=\=)[^"]+',lambda x:f'"{x.group()}"',i)for i in R('(?:\w+\="[^"]+")+|(?:\w+\=[^\s\]]+)+|\w+',a[0]))
e=''
if(o:=re.findall('(?<=\{)[^\}]+',t)):e=o[0]+' '
return n+'>'+e,f'</{N}>'
F=lambda t,I:t if type(t)==list else ' '*I+''.join(U(t))
def f(s,I,c,l):
if'('==s[0]:s.pop(0);t=[];f(s,I+1,t,[]);s.insert(0,t);
t=s.pop(0)
if')'!=t:
if[]!=s:
S=s.pop(0)
if')'==S:c.append(' '*I+f'<{t}></{t}>')
if'>'==S:Q,W=U(t);C=[];c.append(T:=[' '*I+Q,C,' '*I+W]);l.append(T);f(s,I+1,C,l)
if'+'==S:C=[];f(s,I,C,l);c.append(F(t,I));c.extend(C)
if'^'==S[0]:c.append(F(t,I));C=[];f(s,len(l)-len(S),C,l);l[-len(S)].extend(C)
if'*'==S:x=s.pop(0);s.insert(0,t);C=[];f(s,I,C,l);c.extend(T:=[C for _ in range(int(x))])
else:Q,W=U(t);c.append(' '*I+Q+W)
P=lambda x:'\n'.join(i if type(i)==str else P(i)for i in x)
def M(s):S=R('\>|\+|\*|\+|\^+|\(|\)|[^(?:\>\+\*\+\^\(\))]+',s);l,c=[],[];f(S,0,c,l);return P(c)
```
[Try it online!](https://tio.run/##nVVbb9s2GH3Xr2CUB5KmqrlNBwxyqD0YKJaHBkm9Ig@6DLJExVwZShXp1oXj356R1CVeA3jtHiRR5DlH53z8aLff9KaRF7@13dMTf2ibToOOeR9ox8Kay6oQwqtYDT4ijSMPJNcZ/YBgnn4lMNB4ISm8hOTaA7xGPLJL6PdLeo6HdRxJQmsIeEX9PU/m2cGHDltO2DT8FxiCUhRKUR8SCGD4d8MlKjGBA6945iU4ydMsO6YecTiB1PchryGFstGAS8ABE4qZdKHargcRakR8qyGKh3VVgF1UQ3@/C@@7ZtsibOwGHNdNZ8hGwX06MnZT6juej8njOGPcKOvHTLlAhYmLsQcYhb33Jjoq6vD9vQ1xGEMw2hiSDeEZm3rbSSAJjCFhQQ0vf9lfH2LovaODVx1cRSZYDfS3lpntoVRwpfuQEAA4uyJwqIbdPez2sUYquArKQNjdNNVBkFJlPhqpsG1aNMcLTZNs4WDkdaCDJMMLFXKpWKfR3O65BzQd0U4DwzOqjZwZJ9kZVXYIVkcY0KMoXUVlWLQtkxUaHJpce32ITThzhyM2dtjb4I5a54ultTQx/4xoMrBvg2UwDO@MTzFB8JRgaaIOqsSpLqd8bu1Z9x0yFcV2gu20nViOxNwSbZFeYCcxwSQS@JV9rHAvLJLhNXshOHNOdlOJvqvwS4uDgI2@BLYf/7L92BXyniEuNdphnFlxu/nPdfu@2LfkDns3dOp1mMrxuEx9xE0fKd31bXSDjrp/13fQe6RwtLLHMI0fU9PsM3fPzYUeU/yY5PZExClJZ@bKU5Qab6bBlalIUJpkgQu3CuauDRdDo9@YY/7UdjbMewQr/iXeilhwaPq2n4Wv4OztfHzrMaQla9GUnz5vG83@A2ol21i1hSTs4Wew@f/7RJ6vP5/Au3SzX08rxmjDiop1fS1mb@ICk7oxRrq4Pc0874nWUtgW98wOzntq6H5hX/ePN/3j4oSarhLNtWDU/4MJ0YCvTSeqMx@UjbBR6UX2I@SN4/4UZ0SfwrZ7ZyoAd87V4QS0CPv/t0LqZNOxmvqFqmpV@Nm@FLz8dJLrGCOQrPcb1rEfJ8QvCM760i4Cs7rVupEOArQtktRcbh386R8)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 425 bytes
```
i=>(s=i.match(/\w+|"[^"]*"|\{[^}]*\}|\S/g),S=_=>L=s.shift()||"",U=_=>s.unshift(L)&&"",T=v=>S()==v?' ':U(),D=c=>T`#`?' id='+S()+D(c):T`.`?D(c+(c&&' ')+S()):T`[`?A()+D(c):c&&` class="${c}"`,A=_=>T`]`?'':' '+S()+(T`=`?L+S():'=""')+A(),W=_=>S()[0]=="{"?L.slice(1,-1):U(),P=(r='',l=W()||(T`(`?P()+T`)`:T`^`?U():(r=`</${S()}> `,` <${L}${D('')}>`+W())))=>Array(T`*`?-~S():2).join(l+W()+(T`>`&&P()+(T`^`&&U(L='+')))+r)+(T`+`&&P()))()
```
[Try it online!](https://tio.run/##fVTRbts2FH33V7BMYJGWIs/O@jC3lBA0D33wQ4o4yABbHhmJjtjSkipSdgJZ@/XsUlrabR1qGODVOeeee0le8LM4CJPWqrIXRZnJl0rURiL2olhEDFPhXtg0J9PN0T/h9RYnE3zatOttl0w23WlzO32kwS37g0VLZkKTq50l9HTCOLhzoAmbYgCXdDwGdMUOLLollLFD7CFvcUdocM1SFq34GQdEZczzgfevSUoXKx7yGCKfpOMxyKmjHLzm8dWrCCiOUi2MYfi8TTvMgytXe8UTcPQWkNc7khVnPF66eOExjMENPIJ7pwVs/UvCGG5xvAyNVqkks@BiRvsGbxipmecFmt27zYER4fENWK445dDNlscgW4CIv5@et2DWRYgHHL0/b5fdeXtNPA8g7kM6/Fh0VdfiGWwmPL740/Uzp@HnUhVEO4nrNOLj8c0QbiG8I0s4Fw@S/boH/YGnlNAXK41NhZEGMcRHmTpEjY60cpFf@Q@6TL98bUore8DRVWQqUfhy/yOy/Zl8@0@2rzF529cjuRSZrIe6k3kkqL8rQVRHlePPBtqZhZV4lC44GwRhf3GzYZkPy@XIZmurrJYMf5Ral@hY1jp7g1FaatcKu0y@S/Je8T/MK5aMqra3CdB979ONRKj2VVlbUdh1Xssdw7m1lVlMp8fjMXwuG9s8yDAt99Ojm/74wLJPx1@Pv90//p5@wkmbwoB8AZs@@fXTf2hzWctvcPRfvIraDw5BADXWlsWA@y2ybgOFVUUDsv7I1/1JJ3CWrXhIIcPtZDJv0Wx@6TIyuXst9L15@ST2lR4aV0Umn8Lc7nUs1glrZ924X@cd9L/KlUHwFwX6Owc1Bi4GlTsk3GwieAXEXsIFGYQhDyNVoKbWYTfioa3VntDQVFpZ4m0Kj74bfZtBeC8q8oRYhNoRcrsyJXSky0fyBLJ/I/1TA/gPBAAdfffyFw "JavaScript (Node.js) – Try It Online")
Following commented code based on a previous version:
```
i=>(
// tokenize the input
// <word>: \w+
// <string>: "[^"]*"
// <text>: \{[^}]*\}
// other operator: \S
s=i.match(/\w+|"[^"]*"|\{[^}]*\}|\S/g),
// parse the input
P())
// Get first token, the token is consumed
S=_=>L=s.shift()||""
// Undo last get, the token is placed back
U=_=>s.unshift(L)&&""
// Test if next token is given value
// Consume the token and return truthy whitespace string if match
// Or return falsy empty string if not match
T=v=>S()==v?' ':U()
// P (whole program) ::= V "+" P | V ">" P (lookahead != "^") | V ">" P "^" P | <empty>
// V (an HTML tag) ::= <text> | "(" P ")" | <word> D | V "*" <word>
P=(
// right part
r='',
// left part
l=
W()|| // V -> <text>
(T`(`?P()+T`)`: // V -> "(" P ")"
T`^`?U(): // reduce
(r=`</${S()}> `,` <${L}${D``}>`+W())) // V -> <word> D
)=>
T`+`?l+r+P(): // P -> V "+" P
T`>`?l+P()+r+(T`^`&&P()): // P -> V ">" P ["^" P]?
T`*`?Array(-~S()).join(P(r,l)): // V -> V "*" <word>
l+r // reduce
// D (all atributes) ::= "#" <word> | "." <word> | "[" A | <empty>
D=c=> // `c` is all class names collected yet
T`#`?' id='+S()+D(c): // D -> "#" <word> D
T`.`?D(c+' '+S()): // D -> "." <word> D
T`[`?A()+D(c): // D -> "[" A D
c+c&&` class="${c}"` // reduce
// A (`[]` style attributes) ::= <word> A | <word> "=" <word> A | <word> "=" <string> A | "]"
A=_=>
T`]`?'': // "]"
' '+S()+(T`=`?L+S():'=""')+A() // <word> ["=" (<word> | <string>)]? A
// W slice <text> to remove "{}" or return empty string if next token is not <text>
W=_=>S()[0]=="{"?L.slice(1,-1):U()
```
] |
[Question]
[
# Special String
We call a binary string \$S\$ of length \$N\$ special if :
* substring \$S[0:i+1]\$ is lexicographically strictly smaller than substring \$S[i+1:N]\$ for \$ 0\leq i\leq N-2\$,
>
> Note: \$ S[a:b] \$ is substring \$S[a]S[a+1]...S[b-1]\$
>
>
>
Given a binary string \$T\$ of length \$N\$ we are interested in the first special binary string of length \$N\$ that is lexicographically greater than \$T\$, if it doesn't exist print any consistent output.
assume : \$ 2\leq N \leq 300\$ (just to make it even more interesting)
Examples :
* \$T\$= \$0101110000\$ the next lexicographic special string is \$0101110111\$
* \$T\$= \$001011\$ the next lexicographic secial string is \$001101\$
* \$T\$= \$011\$ the next lexicographic special string doesn't exist print \$-1\$ (can print any consistent value)
* \$T\$= \$001101110111111\$ the next lexicographic special string is \$001101111001111\$
* \$T\$= \$010000000000000\$ the next lexicographic special string is \$010101010101011\$
* \$T\$= \$01011111111111111111111111\$ the next lexicographic special string is \$01101101101101101101101111\$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") , so the shortest answer in bytes per language that can execute in restricted \$ O(n^4)\$ time complexity (here \$n\$ is the length of string) wins.
Copyable Test case :
```
0101110000 -> 0101110111
001011 -> 001101
011 -> -1(can print any consistent value)
001101110111111 -> 001101111001111
010000000000000 -> 010101010101011
01011111111111111111111111 -> 01101101101101101101101111
```
[Sandbox](https://codegolf.meta.stackexchange.com/a/24973/103688)
[Answer]
# [Python](https://www.python.org), 91 bytes (@tsh)
```
f=lambda s,j=0:f(max(s,f"{int(s[:j]+s[:-j]or s,2)+1:0{len(s)}b}"),j+1)if s[j:]else(s<"1")*s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY9LTsMwEIb3OcXIbDyNU3lYIYv0IlEWqYjBkRNbcZBAVU_CJhs4C1fobXBeLYuOPZb-mW8e_vrxn8Ob68bx-33Q2dOl0Lmt2uNLBUE0uVSat9UHD0Kzk-kGHgrVlGl8s6Z0fWQeMSUlT7bueMDz8cxQNCmh0RCKRpW1DTUPz4wY7sI64lXHSgumA-djmUSVgBEubyvPw9Dvoxsv7D54awbOsgNDTOBhQordBMVFhEFRipt0WCbg-2nFyAnNDeIybrz8AkiSRCSjQXbYVPQkpmY1h-UUnEKrXrJXmP5jcztaW8ydr7aNuJ0Vovu28HT3zqUbs3zoDw)
### Previous [Python](https://www.python.org), 98 bytes
```
f=lambda s,j=0:f(f"{max(t:=int(s,2),t&-1<<n-j|(t>>j)+1):0{n}b}",j+1)if((n:=len(s))>j)else(s<"1")*s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY9NTsQwDIX3PUWUBbKZdBSzQlHbFRdpRSNSpWnUBAk0zEnYdANn4QpzG9K_gcU48eLZn5-Tz2__Hl8GN01fr1Hnj5dGl7bum-eaBdGVUmnQ_NTXbxBVaVyEIB5QxLucisLl3QfEqurwQKjkyZ2bMxddEkYDOFXa1kFATEBrQwuh4MTxPmybnvQwMsuMY4NPoESVMSOGsq89hDgeUxov7DF4ayLwvOKIGfPj_IrECQ0GcfWaLj-MSZJEJFOwvNpVyiy1FrWU5VycS5teu1eY_mOLHW0Wi_M19hV_Z4Podqw83bzL6M6sH_oF)
Returns empty string for failure.
### How?
The basic idea is to fix all the requirements from left to right: If s[:i]>=s[i:] increase s[i:] just enough to make it the larger operand. If i<n/2 we just need to replace the first i digits of s[i:] with those of s (and fill with zeros to the end). If i>=n/2 we need to replace s[i:] with the first n-i digits of s and add 1.
However, to streamline the logic we do the second branch all the time. This should be ok if we knew that another correction will happen before or at position 2i. But if nothing happens before 2i then at 2i we have essentially the same comparison as we had at i (at least for the i most significant bits).
] |
[Question]
[
## Challenge:
Given an integer \$n\$, guaranteed to be \$\geq2\$ and [a power of 2](https://oeis.org/A000079), we are going to draw multiply boards either side-by-side or below one another, where the first has dimensions of \$n\$ by \$n\$; the second \$\frac{n}{2}\$ by \$\frac{n}{2}\$; the third \$\frac{n}{4}\$ by \$\frac{n}{4}\$; etc.; until the final \$1\$ by \$1\$ pixel.
The first \$n\$ by \$n\$ board will have its pixels [uniformly randomly](https://codegolf.meta.stackexchange.com/a/10923/52210) generated with black (`rgb(0,0,0)`/`#000000`) and white (`rgb(255,255,255)`/`#FFFFFF`) pixels. The next \$\frac{n}{2}\$ by \$\frac{n}{2}\$ compressed image will have each 2x2 block of pixels reduced to the color with the most pixels in that block (thus if a 2x2 block has four or three pixels of the same color, it becomes that color; and if both colors have two pixels each, we again choose one uniformly randomly).
It must be clear how the boards of each iteration are separated.*†*
## Challenge rules:
* Output is flexible, but must be a [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'"). So it can be drawn and shown in a frame/canvas; output to an image-file on disk; drawn in a graph; generated as black/white Minecraft Wool blocks; generated as colored MS Excel cells; etc.
* *†*As mentioned, it should be clear how the boards of each iteration are separated. This can for example be done by using a non-white and non-black color: setting a background of your canvas with a single pixel delimiter between boards or surrounding each board with a border. Alternatively you can output each board separately, in its own image-file or own canvas tab/window perhaps.
* The iterations can be drawn both horizontally or vertically, and alignment is irrelevant (e.g. vertical output with right aligned blocks is fine).
* The size of the individual blocks doesn't necessarily have to be a single pixel, as long as they are all the same size and squares.
**Example:**
Input: \$8\$
Potential output - horizontal; bottom-aligned; red background as separator:
[](https://i.stack.imgur.com/IZEbS.png)
Same example output, but vertical, right-aligned, with a blue border as separator instead:
[](https://i.stack.imgur.com/gifGS.png)
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with default [input rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) and [graphical output rules](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges?answertab=scoredesc#tab-top).
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code, and if not, please include an example screenshot of the output.
* Also, adding an explanation for your answer is highly recommended.
[Answer]
## JavaScript (browser), 334 bytes
```
f=
n=>[...n.toString(2)].map((_,i)=>(c=document.createElement`canvas`,c.height=c.width=s=n>>i,c.getContext`2d`.putImageData(new ImageData(new Uint8ClampedArray(Int32Array.from([].concat(...a=[...Array(s)].map((_,x,t)=>t.map((_,y)=>Math.random()<(i?a[x][y+=y]+a[x+1][y]+a[x][++y]+a[x+1][y]-1.5:.5),x+=x))),b=>-1<<b*24).buffer),s),0,0),c))
;g=n=>{m.value=0;m.max=n;a=f(1<<n);h(0);};h=n=>o.replaceChildren(a[n]);g(8)
```
```
canvas{width:256px;height:256px;image-rendering:pixelated;}
```
```
log<sub>2</sub>n: <input id=n type=number size=1 min=0 max=8 value=8><input type=button value=Go! onclick=g(+n.value)><input id=m type=number size=1 min=0 max=8 value=0 oninput=h(+this.value)><div id=o>
```
Viewer takes input of `log₂n`. To use the viewer, choose `n`, click `Go!`, then use the second input to select which of the output canvases to insert into the DOM. Because the CSS is fixed at `256` pixels, this limits the inputs to `8`; the browser's actual limit is `15`.
[Answer]
# [C (GCC)](https://gcc.gnu.org), 296 bytes
```
#define f(I,J,d)for(i=0;i<I;i+=d)for(j=0;j<J;j+=d)
main(N,n,i,j,c){scanf("%d",&N);char m[N][N];f(N,N,1)m[i][j]=rand()&2;printf("P5 %d %d 2 ",N,N*2+(int)log(N));for(n=N;n;n/=2){f(n+1,N,1)putchar(j<n&i<n?m[i][j]:1);f(n,n,2)m[i/2][j/2]=(c=m[i][j]+m[i+1][j]+m[i][j+1]+m[i+1][j+1])-4?c/5*2:rand()&2;}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVDNasJAEKZXnyJEDLNmQ5qlgrhZPOth6T2EEjau3cWMksaT-CS92IP0nfo0nTSpMMzPN9_MN8zn3bztjfkuwuTQhOXtfu5ssvx5gmm9sw53gYUN3_Ka2WMLTj1Ll2-ki9UAeAJ8vpW-ByZN5RA0R-6454ZdPkyFFsJZHfJIM2neqzZoCl2SSUtEzTPWFK4sfKnaCmtgkZCn1mFHU6-LYFb3JoKQmHouYqAOOxz3oBmTvTwqLVFiqgS7WMA4-1t5One9FPgcI5fjepRYZTQESOeJXjUVBJJTYNTIiCnG2X9GkYoHRo4lL2uTLuZi9bj2eh0eNv7t9rUckl8)
Outpus a [PGM](http://netpbm.sourceforge.net/doc/pgm.html) image.
Since PGM stands for "Portable Gray Map", the output is a grayscale image. The `2` in `printf("P5 %d %d 2 "` is the maximum gray value, hence there are three possible colors: `0` (black), `1` (50% gray), and `2` (white).
Whit the instruction `m[i][j]=rand()&2;`, each element of the matrix is assigned a random value (with \$p(X=0)=0.5\$ and \$p(X=2)=0.5\$), hence
the pixels are uniformly randomly generated with black and white pixels.
In the compression phase, the `(c=m[i][j]+m[i+1][j]+m[i][j+1]+m[i+1][j+1])-4?` expression is false if two of the four pixels have value `2` (that is, they are white, and the other two are black).
The value `1` is used only for the background pixels.
[Answer]
# [J](http://jsoftware.com/), 91 bytes
```
load'viewmat'
[:viewmat[:,.~/[:>:&>(,:~2 2)0:`(?@2)`1:@.(1+_2*@++/@,);._3&.:>^:a:[:<,~?@$2:
```
[Try it online!](https://tio.run/##LcaxCsIwFAXQvV/xKtIkJqZNBKFXTQOCk1PXoG1ABUVxEd3y69HB4cC55baEOSxLtIwVE80utAExUtQQfuaatv1@l@/PeGLv6/nziC9WBPwboHSqAxwqxxWSJSsajLzzVowGXnMjBzvzUtZeiZUeFpWGOyIiYK1S56cWWeQv "J – Try It Online")
Output from the above is show below, since TIO won't produce images.
However, [here is a TIO link](https://tio.run/##LY2xCsIwGAb3PMVfkSYx8W8TReyntgHByck1aCtiERffIK8eizgc3E33zk0Bd90UaKQUM5YjHUCSLNWEiSXT8XI@5QjLqYpoUbbKInnyusaguuD14BBYOdP7RTCmClbvuF@VjPaGOyL2NnVh7pG1EM/H60MjrX8yHf@9zV8) that outputs the raw matrix data, which is where all the logic is. The image is produced simply by calling `viewmat` on that.
f 16:
[](https://i.stack.imgur.com/P6GCG.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes
```
Image/@NestList[BlockMap[Boole[#~Total~2+r[]>2]&,#,{2,2}]&,r=RandomInteger;1~r~{#,#},Log2@#]&
```
[Try it online!](https://tio.run/##DcaxCsIwEADQXxECXQxIM7hIpXQrVBFxOzIc9RpLk5ykt5Xm16NvegHlQwFlHrFMh6b0AR2d2jutMsyrQOd5XG74hY7ZE6j8YkGfzTGBvRpbaaU3o83@X2qeGN8c@ijkKF3qnPKmtNr1wM60ylblkeYoMEF9trb8AA "Wolfram Language (Mathematica) – Try It Online")
This is a function that takes an input `n` and returns a list of images. TIO can't display the images, but both the Notebook interface and [@wolframtap](https://twitter.com/wolframtap) supports graphical output.
[![Image/@NestList[BlockMap[Boole[#~Total~2+r[]>2]&,#,{2,2}]&,r=RandomInteger;1~r~{#,#},Log2@#]&@256](https://i.stack.imgur.com/z4LEe.png)](https://i.stack.imgur.com/z4LEe.png)
[Answer]
# [Yabasic](http://www.yabasic.de), 196 bytes
Program that takes input \$n\$ from STDIN and outputs to a 'grafic' window.
```
Input n
Open Window 5*n,3*n
Color 0,0,99
Fill Circle 0,0,6*n
While n>.5
For x=1To n
For y=1To n
Color 0,0,0
If ran(2)>1Color 255,255,255
Box 2*x+o-1,2*y-1,2*x+o,2*y
Next
Next
o=o+2*n+2
n=n/2
Wend
```
### Commented
```
Input n rem take input
Open Window 5*n,3*n rem open a graphics window
Color 0,0,99 rem set brush color to blue
Fill Circle 0,0,9*n rem fill background
While n>.5 rem iter across subimages
For x=1To n rem iter across subimage's x
For y=1To n rem iter across subimage's y
Color 0,0,0 rem set brush color to black
If ran(2)>1Color 255,255,255 rem 50% to set brush color to white
rem draw a rectangle for the current cell
rem of the subimage. Uses the 1px
Box 2*x+o-1,2*y-1,2*x+o,2*y rem border to draw each 2px X 2px cell
Next rem loop
Next rem loop
o=o+2*n+2 rem update offset for next subimage
n=n/2 rem decrement n by base 2 order of magnitude
Wend rem loop
```
# Example Output (\$n=256\$)
[](https://i.stack.imgur.com/LeJc7.png)
] |
[Question]
[
When you export data in JSON from Facebook, the multi-byte Unicode characters are broken. Example Unicode characters and their representation inside JSON:
```
'\u00c2\u00b0' : '°',
'\u00c3\u0081' : 'Á',
'\u00c3\u00a1' : 'á',
'\u00c3\u0089' : 'É',
'\u00c3\u00a9' : 'é',
'\u00c3\u00ad' : 'í',
'\u00c3\u00ba' : 'ú',
'\u00c3\u00bd' : 'ý',
'\u00c4\u008c' : 'Č',
'\u00c4\u008d' : 'č',
'\u00c4\u008f' : 'ď',
'\u00c4\u009b' : 'ě',
'\u00c5\u0098' : 'Ř',
'\u00c5\u0099' : 'ř',
'\u00c5\u00a0' : 'Š',
'\u00c5\u00a1' : 'š',
'\u00c5\u00af' : 'ů',
'\u00c5\u00be' : 'ž',
```
In the last example the bytes `0xC5` and `0xBE` are the UTF-8 encoding for `U+017E`. If those individual bytes are treated as unicode codepoints, they are `Å` and `¾`. So Facebook wrote each byte as an Unicode codepoint instead of handling multi-byte UTF-8 sequences appropriately.
This incorrect representation is used for every multi-byte UTF character. In short, to fix it, one needs to convert any string sequences like `\u00c5\u00be\u00c5\u0099` into byte data where first byte is `\xc5` and second byte is `\xbe`, third is `\xc5` and fourth is `\x99`, then read these bytes as a UTF-8 string. This can happen by direct manipulation of raw JSON text or by first parsing JSON, then do some magic with the *incorrectly* parsed strings or whatever comes to your mind.
Note that while `"\u00c5\u00be\u00c5\u0099"` is valid JSON, `"\xc5\xbe\xc5\x99"` is not. Also
A working Ruby and Python (not verified) solution can be seen in the referenced StackOverflow question at the bottom.
The task is to fix JSON generated by Facebook **with the shortest code**.
Winning criteria: code-golf - **the shortest code**.
As input you can take a file name, STDIN or the file text as a variable. The output should be on STDOUT, a file name or a string in a variable.
You don't have precise JSON input format (except that it is valid JSON), because exported data can be different. Also result should be valid JSON.
Solutions
* should accept as input both - pretty and non-pretty formatted JSON
* should handle properly 1,2,3 and 4 octets UTF character. With the assurance (if that matters) that any multi-byte UTF characters in the input will always be split into multiple `\u00##` sequences (i.e. you will never get `\u017E` or another sequence where first byte is non-zero).
* can output any - pretty formatted or non-pretty JSON
* doesn't matter whether characters in the output are represented by plain Unicode characters or escaped Unicode `\u017E`
* you are allowed to use any JSON parsing libraries
Example input:
```
{
"name": "\u00e0\u00a4\u0085\u00e0\u00a4\u0082\u00e0\u00a4\u0095\u00e0\u00a4\u00bf\u00e0\u00a4\u00a4 G \u00e0\u00a4\u00b6\u00e0\u00a5\u0081\u00e0\u00a4\u0095\u00e0\u00a5\u008d\u00e0\u00a4\u00b2\u00e0\u00a4\u00be",
"timestamp": 1599213799,
"whatever": "someth\u0022\u00d0\u0092\u00d0\u00b8\u00d0\u00ba\u00d0\u00b8",
"test": "\\u0041"
}
```
Example acceptable output:
```
{
"name": "अंकित G शुक्ला",
"timestamp": 1599213799,
"whatever": "someth\"Вики",
"test": "\\u0041"
}
```
Credit goes to original question <https://stackoverflow.com/q/52747566/520567>
[Answer]
# JavaScript, 85 bytes
```
let d=s=>new TextDecoder().decode(new Uint8Array(s.split('').map(r=>r.charCodeAt())))
```
Test:
```
let s = "nejni\u00c5\u00be\u00c5\u00a1\u00c3\u00ad bod: 0 mnm Ben\u00c3\u00a1tky\n";
s = d(s);
console.log(s);
```
As I said in the other page [1], the Facebook data is valid UTF-8. However
JavaScript doesnt use UTF-8, it uses UTF-16. So you have to convert from UTF-8
to UTF-16, to get the text to play nice with JavaScript.
1. <https://stackoverflow.com/a/68237082>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 51 bytes
Anonymous prefix lambda taking a string as argument.
```
'(\\u00..)+'⎕R{'UTF-8'⎕UCS⎕UCS⎕JSON'"',⍵.Match,'"'}
```
[Try it!](https://tryapl.org/?clear&q=f%E2%86%90%27(%5C%5Cu00..)%2B%27%E2%8E%95R%7B%27UTF-8%27%E2%8E%95UCS%E2%8E%95UCS%E2%8E%95JSON%27%22%27%2C%E2%8D%B5.Match%2C%27%22%27%7D%20%E2%8B%84%20f%27%7B%22name%22%3A%22%5Cu00e0%5Cu00a4%5Cu0085%5Cu00e0%5Cu00a4%5Cu0082%5Cu00e0%5Cu00a4%5Cu0095%5Cu00e0%5Cu00a4%5Cu00bf%5Cu00e0%5Cu00a4%5Cu00a4G%5Cu00e0%5Cu00a4%5Cu00b6%5Cu00e0%5Cu00a5%5Cu0081%5Cu00e0%5Cu00a4%5Cu0095%5Cu00e0%5Cu00a5%5Cu008d%5Cu00e0%5Cu00a4%5Cu00b2%5Cu00e0%5Cu00a4%5Cu00be%22%2C%22timestamp%22%3A1599213799%2C%22whatever%22%3A%22someth%5Cu0022%5Cu00d0%5Cu0092%5Cu00d0%5Cu00b8%5Cu00d0%5Cu00ba%5Cu00d0%5Cu00b8%22%2C%22test%22%3A%22%5C%5Cu0041%22%7D%27&run)
`'(\\u00..)+'⎕R{`…`}` **R**eplace any sequence of `\u00` followed by two other characters with:
`'"',⍵.Match,'"'` the match, surrounded by double quotes
`⎕JSON` interpret as JSON
`⎕UCS` convert to code points
`'UTF-8'⎕UCS` interpret as UTF-8 bytes
[Answer]
# Javascript, 79 bytes
```
f =
s=>s.replace(/(\\u00[8-f].)+|\\./g,c=>c[2]?decodeURI(c.replace(/.u00/g,'%')):c)
; function ch() { try { console.log(f(val.value)) } catch (e) { console.log(e); } } ch();
```
```
<textarea id="val" onchange="ch()">
{
"name": "\u00e0\u00a4\u0085\u00e0\u00a4\u0082\u00e0\u00a4\u0095\u00e0\u00a4\u00bf\u00e0\u00a4\u00a4 G \u00e0\u00a4\u00b6\u00e0\u00a5\u0081\u00e0\u00a4\u0095\u00e0\u00a5\u008d\u00e0\u00a4\u00b2\u00e0\u00a4\u00be",
"timestamp": 1599213799,
"whatever": "someth\u0022\u00d0\u0092\u00d0\u00b8\u00d0\u00ba\u00d0\u00b8",
"test": "\\u0041"
}
</textarea>
```
Still use `[8-f]` rather than `[^2]` in case `\u000a` exist
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 15 bytes
```
jq .|iconv -tl1
```
TIO version of `jq` requires the identity filter `.` but later versions can get away with `jq|iconv -tl1` for 13 bytes
[Try it online!](https://tio.run/##fZBBDsIgEEX3PcWEtRqorRYv4CXcDHYMNdKqxbpQz46FxoSUxM1k8vjzhz8Ke@3c@Qard3Ps2gGW9iKce2UAwFo0xHbADg/OifuKha9VmZB8TmSiUac5wQL2kMg2EQkmlfhrPmnqxCf5kiK2CLlsY6i3aK5jOFFKmYv1Vsrp7anR0kB3n7vvDFntR/NgVgczGfWqinqM@W/VuCic0NNCsOzzBQ "Bash – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 34 bytes
```
s/(?<!\\)\\u00([^2].)/chr hex$1/ge
```
[Try it online!](https://tio.run/##fdHLSsQwFAbgfZ8iFiEzUO1lWm0GwaUPYRWSNmMH7LS09QLiwqWguFXcOEsXomtBFzp9Leskpw5tCm7C4evfk5wk4/mxV9eFOdjdWQuCYRCcWNZg/9A52ByaYZyjmJ@v2@YRr@sLDSGkz2jC9THSRY5bYqWuWH2vJ44qpJdhE1Woi/ZQL7bVEtnEt/9tDpmo16d3JMZ1Q85VThNelDTJlsPZHiGOPdomBL6dxbTkpzwXcxdpwstY/OrIZpFsRlo181s1bfvfVsuN5BUKdW1du9SwKEPZhFkYjRH@esNGwyMYWPL3VZdpw3MlTYCvlXTDzwpHwC9dZhT4XeEm/bFieO5Q8uJGYUgvbhWeAN91mTDgxxXLlyS@5OpeYRineugyhRusnhSGq6rmCsNJqtcuMw78iY2fNCun6ayoN7Jf "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
```
s=>JSON.stringify(eval('s='+s),(k,v)=>v===v+''?decodeURIComponent(escape(v)):v)
```
[Try it online!](https://tio.run/##hVCxTsMwEN37FVaW2GpaJSGlcSWXgQHBABKIrUOd5NIGEjuKjRFCfHsINgyRLDGd7r13793dCzdclUPT65WQFYw1GxXb3z093K@VHhpxauoPDIa3OFQsXCoS4dfIELY3jDGzDMOrCspp8Pnx9lp2vRQgNAZV8h6wIWRnyFhKoWQL61aecI2PnwuEUCB4B8EOBYfDWxxDbAvPbMk3PjD1gNSnLGoPyDN0g3ziyxno/PLk/6xfZeXz9K1aQBDZw3XTgdK866frkw2laXKxpdRx72euwcDw8xglO9BnO5s6w8oZ0llX5LOOz7m/zCnRPdviWRIsvo6EjN8 "JavaScript (Node.js) – Try It Online")
It only fix non printable ascii strings in JSON value, but not JSON keys. But as we accept JSON exported from Facebook which doesn't handle non ASCII correctly, we may safely assume keys won't contain such strings by design.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~239~~ 213 bytes
```
/\\\\|\\u00[cde].(\\u00[89ab].)+/_(/\w/_(`[89a-f]
g$&
T`89l`d0
.
*
)4+`^(_*)\1(_)?
$1$#2
\\(0{7}(0{5})110(.{5})|0{12}1110(.{4})\\0{12}10(.{6}))\\0{12}10(.{6})
\u$2$3$4$5$6
/\d{4}/_(`1
01
+`10
011
C`1
T`d`l`..
b\B
```
[Try it online!](https://tio.run/##fVDBboMwDL37KxCLJlI2iClQssuk7bAf6G3pSBjpWql0U0vXA@XbWQKqhIq0HBy/F/vZLwddb/cKuy4U5lyEODH2/lnqVeANecZVsQqoH@ZeKM4mSks9rlfwRe5hKTO@kyWDAGZAY19@ePmMCvRy@gwEyV0EQnisWbQmJC1FZF5gkwtrMGpxwHFLhRgIC9OW3mIQJxKROYlJQlIIRWl67C4IDMGXyMyN8GrwUpZyJ4MACvECXdeA4zjuXlXafXJc60gzG1VsY5ZMmOiW4ZOaYn3LqNh5cyZl6YjpRTL8V3yoKSc6k5UK7T70vuptpY@1qn6MOUw4j3C@4Hx4O29UrX/1wfo@fle63tjWqBcrezE@yotslKsxfx1lBvVfaNkYXWj/AA "Retina – Try It Online") Retina isn't really designed for bit-twiddling. Outputs in escaped Unicode. Explanation:
```
/\\\\|\\u00[cde].(\\u00[89ab].)+/_(`
```
Run the rest of the script on pairs of backslashes and Unicode escapes of UTF-8 byte sequences. (The rest of the script leaves pairs of backslashes unchanged so this simply avoids treating them as the start of a Unicode escape.)
```
/\w/_(`[89a-f]
g$&
T`89l`d0
.
*
)4+`^(_*)\1(_)?
$1$#2
```
Change each letter into its binary equivalent. (This also changes `u` to `0000` but that doesn't matter a lot.)
```
\\(0{7}(0{5})110(.{5})|0{12}1110(.{4})\\0{12}10(.{6}))\\0{12}10(.{6})
\u$2$3$4$5$6
```
Shuffle the bits from the UTF-8 bytes into a single Unicode character.
```
/\d{4}/_(`
```
Run the rest of the script on each set of four bits.
```
1
01
+`10
011
C`1
```
Convert to decimal.
```
T`d`l`..
```
Change `10-15` to `ba-bf`.
```
b\B
```
Remove any leading `b`.
The previous version converted from hexadecimal to binary in a single substitution, but I was able to shave off 26 bytes by using a per-digit script:
```
/\w/_(`
)`
```
Run the script on each letter i.e. hexadecimal digit or `u`.
```
[89a-f]
g$&
```
Prepend `g` to the digits `a-f`.
```
T`89l`d0
```
Subtract 8 from the digits `8-f`, but turn `g` into 8 as compensation; also turn `u` into `0`.
```
.
*
```
Convert each digit to unary.
```
4+`^(_*)\1(_)?
$1$#2
```
Convert the unary to four bits of binary.
] |
[Question]
[
## Challenge
1. Choose any number of languages. Call this set `L`.
2. Write a program so that running it in any language in L produces an interpreter for a **different** language in `L`.
Each language in `L` must have **exactly one** interpreter for it. This is to prevent, for example, [Nothing](https://esolangs.org/wiki/Nothing) or [Text](https://esolangs.org/wiki/Text) being part of `L` and all interpreters being for that single language.
3. Your score is the number of bytes of your code divided by the number of languages in `L`. Lowest score wins.
## Rules
* Any language may have an interpreter for any other language -- it doesn't need to be one large cycle.
* An interpreter can input program code and input however you see fit.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* Different versions of a language count as distinct (e.g. Python 3.4 and 3.5) but not patch versions (e.g. Python 3.4.1 and 3.4.4). *Thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) for this.*
## Example Submission *(clarified due to [Kaddath](https://codegolf.stackexchange.com/users/90841/kaddath)'s comment)*
```
# [Julia 1.0](https://julialang.org) and [Brainf***](https://esolangs.org/wiki/brainfuck), B bytes / 2 languages = B/2
```
#=
<julia interpreter written in brainf***>
[-][
=#
<brainf*** interpreter written in julia>
# ]
```
Julia 1.0: [Try it online!](https://tio.run/#julia1x)
Brainf***: [Try it online!](https://tio.run/#brainfuck)
Explanation:
When ran in Brainf***, the Brainf*** code is run. The `[-]` sets the current cell to zero, then we skip over the rest of the code using `[ ... ]` since we know the current cell is zero.
When ran in Julia, the `#= ... =#` marks a comment, letting the Brainf*** code not get executed. After that is the Brainf*** interpreter, then the final line would have an unmatched `]`, so it is commented out.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) `u` / [Python 3](https://docs.python.org/3/) + [jelly](https://github.com/DennisMitchell/jelly), 70 bytes = 35
```
from jelly import*
a=sys.argv
main(a[1],[*map(try_eval,a[2:])],'')
ŒV
```
[Try it online!](https://tio.run/##y0rNyan8/z@tKD9XIQvEVsjMLcgvKtHiSrQtrizWSyxKL@PKTczM00iMNozVidbKTSzQKCmqjE8tS8zRSYw2sorVjNVRV9fkOjop7P///wVFmXklGuoeQKPydRTC84tyUhSBkokKtgqmXBDJRAjXDM4FAA "Jelly – Try It Online") (Jelly)
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chKzUnp1IhM7cgv6hEiyvRtriyWC@xKL2MKzcxM08jMdowVidaKzexQKOkqDI@tSwxRycx2sgqVjNWR11dk@vopLD///9r6/@PNtQx0jGOBQA "Python 3 – Try It Online") (Python)
Both error after executing the other language.
This is a bit of a cheat tbh. Jelly has an "execute as Python" builtin, `ŒV`, and, as of [April 9, 2018](https://github.com/DennisMitchell/jellylanguage/commit/4765fa6271be3ea89f1ae93454fc55dc733845b9), Jelly is a `pip`-installable package, meaning that we can just import it and run it.
## How they work
Jelly ignores every line except for the last, and just runs that:
```
ŒV - Main link. Takes a string on the left
ŒV - Execute the string as Python code
```
For some reason, I think because of the `[...]` in the above lines, there's some parsing error thrown afterwards.
For Python, we import the contents of the `jelly` package, read and evaluate the command-line arguments, then run the program in the first command-line argument with the values in the second and third arguments
[Answer]
# Windows Batch/Powershell 7, 38 bytes, 19 score
```
ls >$null&&cmd /c "$args"
pwsh -c "%*"
```
Assumes that there is no file named `ls` in current directory plus Powershell 7 executable `pwsh.exe` is in PATH.
It needs Powershell 7 because `&&` and `||` syntactic sugar was introduced in that version.
It first checks if any command is `ls`, `>$null` suppresses the output. If it succeeded we assume the interpreter is Powershell, so we execute Batch code and vice versa.
It generates some extra errors besides the STDOUT, but I think that's fine because @caird's answer also errors.
[Answer]
# Windows Batch / [PHP](https://php.net/) < 8, 25 bytes, Score: 12.5
```
php -r %1;echo`$argv[1]`;
```
[(cannot really) Try it online for PHP!](https://tio.run/##K8go@G9jXwAkgVhBt0hB1dA6NTkjP0ElsSi9LNowNsH6////ZalFAA "PHP – Try It Online") (it runs, but external scripts seem to be disabled, for security reasons I guess)
Cannot test Windows Batch in TIO and haven't found another site for it (makes sense actually) -> you can place the code in a `test.bat` file and run something like `test.bat "echo 42;"` to pass the PHP code as parameter
* Assumes that PHP executable is in PATH under the `php` command.
* in PHP below version 8, `php` and `r` are assumed string constants, and `-` `%` are operators, this part tries to calculate the result but does nothing with it. The rest of the code executes the argument as command-line code and outputs the result.
* in Windows Batch, executes the first argument received as PHP code and outputs the result. The rest of the code is considered as a second argument and is ignored.
] |
[Question]
[
# Introduction
`git diff` is a great way to export patches of the source code, and its outputs are colorized if you don't pass extra arguments to it.
However, when you want to review the exported file with colored output, it would be pretty hard. [colordiff](https://stackoverflow.com/a/8800636/13854774) is an option, but it acts like the `diff` program itself, also, it is not "multiplatform" considering how many languages this community can code in.
# Challenge
Write a program that takes a diff text input from the user and colorize it. On \*nix, it might mean printing to standard output with [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). The colored output must be clearly visible to users.
## Details
* Only valid diff texts will be passed. You can make it so other cases are UB.
* The original file line starting with `---` (e.g. `---path/to/example`) should be colored **red and bolded**.
* The new file line starting with `+++` (e.g. `+++path/to/example`) should be colored **green and bolded**.
* The modification lines starting with `+` or `-` (e.g. `+correct` and `-wrong`) should be colored green and red respectively, but not bolded.
* You can color the hunk range information indicated by two `@@`s at the start of a line (e.g. `@@ -22,3 +23,7 @@`) however you like, but it should not be the default color, and it must be consistent throughout the program. The hunk range indicators can be bolded.
* The optional section heading after the hunk range information which is after the second `@@` (e.g. "This is an optional heading" in `@@ -22,3 +23,7 @@ This is an optional heading`) should **NOT** be colored.
* All other lines should **NOT** be colored.
* The program must output the exact text from the input. The only difference is the color.
* You may assume that only new file lines start with `+++`, only original file lines start with `---`, only modification lines start with `+` or `-` (but not `---` or `+++`), and that all lines starting with `@@` denote a hunk information.
## Restriction
Usage of diffutils, patchutils, git tools, or any other external programs are not allowed.
## Test Cases
```
+++ Green and Bolded
++ Green, not Bolded
+ Green
- Red
-- Red, not Bolded
--- Red and Bolded
@@ -123,1 +123,1 @@ <- that was a color different to this color
This should be a sentence that has the same color as the line above and after the second @@
This is not colored: @@ test ---+++ @@ because it doesn't start at the beginning of a line
@@ -12,3 +12,3 @@ <- that should have the same color as the last hunk
```
# Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest wins!
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), ~~70~~, 69 bytes
-1 byte dropping 0, as suggested by [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)
```
s/^([-+@])(\1\1)?(.*?@@|.*)/"[".($2&&"1;").((4*ord)%9+31)."m$&[m"/e
```
[Try it online!](https://tio.run/##dZFBb5tAEIXv@xdyGaHEBeMFYbeK2kQK6qXXKMrNbqU1jAEFdtDuOsmhv71kdrGlNFIkxGo@hjfvzY5o@m/TZPM/8Vam5e8k3hW7IrmLs@VdWf7NlkkeXWyjLL5cLxZRcRMlWRx/XZKpk6vv6aZIsmi4XFxshyjHaZJSjsq1uaMcX9Uw9ijSNP2IyhLker3aQLrerK6By8e2s8CPAouV60gDHcC1CPeGGqMGIV8M6UakFRnDHQI0OahapRushZ8BvwyiBqVr@El9zfTMVqH3DGcmJDxwJcPxX4Oc2Xshb7dgpwWk88HgVrI95eBFedMV9WSg7g4HNKgdOOKvHCdwEcLZlo59DXsMGbVDXeEs0bKEj2rVgCelE@k7ze17esZgRx0cmrkVK2JQluK8uLAO/y/WP7w/h9YBZ/Gb4XKPlTpahM5BTWj1FwfWKeOA53vBPTad1p1u/N5VGCxOuf01hfe71KcwrXrGz6wrnt8e9ZP4R6O/UDvJ8Q0 "Perl 5 – Try It Online")
] |
[Question]
[
We've all seen the pictures captioned "How many squares are in this image? 98% will not get this right!" Well, here's your chance to laugh at that 98%.
## Input
A rectangular block made of only 2 characters. In a general form, this is defined by *m* lines, each containing *n* characters.
Example:
```
0000xxx
00x00xx
00000xx
xxxxx0x
```
This can be represented as a newline-separated string, an array of strings, or a 2D array of characters. Any other input types should be suggested in the comments.
## Output
The output will be an integer representing the total amount of **squares** represented individually by *both* characters (in pseudocode, num\_squares(char1) + num\_squares(char2))
A **square** is defined as a set of instances of the same character that fully outline a geometric square of side length *at least 2*. These squares need not be filled by the character that outlines it. The following examples illustrate this concept:
```
x0
0x // no squares
xxx
x0x
xxx // 1 square of side length 3
0000
0xx0
0xx0
0000 // 1 square of side length 2, 1 square of side length 4
```
## Scoring
Your program will be scored by 2 criteria, in descending order of importance:
* Number of characters in your code block that aren't part of a square, as defined above (you should aim to minimize this!) (Note: characters inside of a square are not automatically considered as part of that square) (Note 2: newlines do not count toward this score)
* Number of bytes (you should aim to minimize this!)
The second criterion will act as a tie breaker for the first.
## Challenge Rules
* For the sake of flexibility, you may choose to use any 2 alphanumeric characters to replace the 0 and x from my examples, as long as they are not the same character.
* Each line in the input rectangle must have the same length, and must not contain any character other than the 2 specified for your answer to the challenge (besides the newline character, if applicable)
* Trivial squares (1x1 squares denoted by a single character) do not count toward the output. They suck.
* Your program does not have to handle empty input, but it should handle cases where no squares are possible (when one of the dimensions of the input rectangle is 1)
* You may also choose to specify that you are handling diagonally aligned squares if you relish the challenge. This would be added to the output specified in the challenge specs.
Example of this concept:
```
Input:
00x00
0x0x0
x000x
0x0x0
00x00
Output: 6 (1 diagonally aligned square of side length 3, 5 diagonally aligned squares of side length 2)
```
## Test Cases
The following are some basic test cases that your program should match. The value in parentheses is the output should you choose to count diagonally aligned squares.
```
Input:
xxxx
x00x
x0xx
xxxx
Output: 2 (2)
```
---
```
Input:
x00000xxx0
Output: 0 (0)
```
---
```
Input:
xxx0x0x000xx0xx0
0x000x00x0x0xx00
00xx0xx00xx0000x
x0x0x0x0x00x0xxx
00xx0xxx00xxx0x0
Output: 0 (5)
```
---
```
Input:
0000
0000
0000
0000
0000
0000
Output: 26 (34)
```
---
```
Input:
xxx00
xx000
Output: 2 (2)
```
## General rules
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Adding an explanation for your answer is highly recommended.
* Any questions/corrections/advice for me? Comment below! This is my first question, so I'm excited to learn as much from it as possible.
[Answer]
# Perl, 0 characters not in squares (25430 bytes)
```
##((((((((((((((((((((((((((((((((((((((((((((((
##($$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$(
##($rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr$(
##($r,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,r$(
##($r,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,r$(
##($r,$cccccccccccccccccccccccccccccccccccc$,r$(
##($r,$c,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,c$,r$(
##($r,$c,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,c$,r$(
##($r,$c,@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@,c$,r$(
##($r,$c,@a))))))))))))))))))))))))))))a@,c$,r$(
##($r,$c,@a)==========================)a@,c$,r$(
##($r,$c,@a)=@@@@@@@@@@@@@@@@@@@@@@@@=)a@,c$,r$(
##($r,$c,@a)=@AAAAAAAAAAAAAAAAAAAAAA@=)a@,c$,r$(
##($r,$c,@a)=@ARRRRRRRRRRRRRRRRRRRRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGGGGGGGGGGGGGGGGGGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGVVVVVVVVVVVVVVVVGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;;;;;;;;;;;;;;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<<<<<<<<<<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<<<<<<<<<<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<''''''''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<''''''''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<'';;;;''<<;VGRA@=)a@,c$,r$(
($r,$c,@a)=@ARGV;<<'';##;''<<;VGRA@=)a@,c$,r$(
($r,$c,@a)=@ARGV;<<'';##;''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<'';;;;''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<''''''''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<''''''''<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<<<<<<<<<<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;<<<<<<<<<<<<;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGV;;;;;;;;;;;;;;VGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGVVVVVVVVVVVVVVVVGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARGGGGGGGGGGGGGGGGGGRA@=)a@,c$,r$(
##($r,$c,@a)=@ARRRRRRRRRRRRRRRRRRRRA@=)a@,c$,r$(
##($r,$c,@a)=@AAAAAAAAAAAAAAAAAAAAAA@=)a@,c$,r$(
##($r,$c,@a)=@@@@@@@@@@@@@@@@@@@@@@@@=)a@,c$,r$(
##($r,$c,@a)==========================)a@,c$,r$(
##($r,$c,@a))))))))))))))))))))))))))))a@,c$,r$(
##($r,$c,@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@,c$,r$(
##($r,$c,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,c$,r$(
##($r,$c,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,c$,r$(
##($r,$cccccccccccccccccccccccccccccccccccc$,r$(
##($r,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,r$(
##($r,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,r$(
##($rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr$(
##($$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$(
##((((((((((((((((((((((((((((((((((((((((((((((
##ffffffffffffffffffffffffffffffffffffffffff
##foooooooooooooooooooooooooooooooooooooooof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##for$yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy$rof
##for$y((((((((((((((((((((((((((((((((y$rof
##for$y(000000000000000000000000000000(y$rof
##for$y(0............................0(y$rof
##for$y(0............................0(y$rof
##for$y(0..$$$$$$$$$$$$$$$$$$$$$$$$..0(y$rof
##for$y(0..$rrrrrrrrrrrrrrrrrrrrrr$..0(y$rof
##for$y(0..$r--------------------r$..0(y$rof
##for$y(0..$r-111111111111111111-r$..0(y$rof
##for$y(0..$r-1))))))))))))))))1-r$..0(y$rof
##for$y(0..$r-1){{{{{{{{{{{{{{)1-r$..0(y$rof
##for$y(0..$r-1){<<<<<<<<<<<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<<<<<<<<<<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<''''''''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<''''''''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<'';;;;''<<{)1-r$..0(y$rof
for$y(0..$r-1){<<'';##;''<<{)1-r$..0(y$rof
for$y(0..$r-1){<<'';##;''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<'';;;;''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<''''''''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<''''''''<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<<<<<<<<<<<{)1-r$..0(y$rof
##for$y(0..$r-1){<<<<<<<<<<<<{)1-r$..0(y$rof
##for$y(0..$r-1){{{{{{{{{{{{{{)1-r$..0(y$rof
##for$y(0..$r-1))))))))))))))))1-r$..0(y$rof
##for$y(0..$r-111111111111111111-r$..0(y$rof
##for$y(0..$r--------------------r$..0(y$rof
##for$y(0..$rrrrrrrrrrrrrrrrrrrrrr$..0(y$rof
##for$y(0..$$$$$$$$$$$$$$$$$$$$$$$$..0(y$rof
##for$y(0............................0(y$rof
##for$y(0............................0(y$rof
##for$y(000000000000000000000000000000(y$rof
##for$y((((((((((((((((((((((((((((((((y$rof
##for$yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy$rof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##foooooooooooooooooooooooooooooooooooooooof
##ffffffffffffffffffffffffffffffffffffffffff
##ffffffffffffffffffffffffffffffffffffffffff
##foooooooooooooooooooooooooooooooooooooooof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##for$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$rof
##for$x((((((((((((((((((((((((((((((((x$rof
##for$x(000000000000000000000000000000(x$rof
##for$x(0............................0(x$rof
##for$x(0............................0(x$rof
##for$x(0..$$$$$$$$$$$$$$$$$$$$$$$$..0(x$rof
##for$x(0..$cccccccccccccccccccccc$..0(x$rof
##for$x(0..$c--------------------c$..0(x$rof
##for$x(0..$c-111111111111111111-c$..0(x$rof
##for$x(0..$c-1))))))))))))))))1-c$..0(x$rof
##for$x(0..$c-1){{{{{{{{{{{{{{)1-c$..0(x$rof
##for$x(0..$c-1){<<<<<<<<<<<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<<<<<<<<<<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<''''''''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<''''''''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<'';;;;''<<{)1-c$..0(x$rof
for$x(0..$c-1){<<'';##;''<<{)1-c$..0(x$rof
for$x(0..$c-1){<<'';##;''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<'';;;;''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<''''''''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<''''''''<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<<<<<<<<<<<{)1-c$..0(x$rof
##for$x(0..$c-1){<<<<<<<<<<<<{)1-c$..0(x$rof
##for$x(0..$c-1){{{{{{{{{{{{{{)1-c$..0(x$rof
##for$x(0..$c-1))))))))))))))))1-c$..0(x$rof
##for$x(0..$c-111111111111111111-c$..0(x$rof
##for$x(0..$c--------------------c$..0(x$rof
##for$x(0..$cccccccccccccccccccccc$..0(x$rof
##for$x(0..$$$$$$$$$$$$$$$$$$$$$$$$..0(x$rof
##for$x(0............................0(x$rof
##for$x(0............................0(x$rof
##for$x(000000000000000000000000000000(x$rof
##for$x((((((((((((((((((((((((((((((((x$rof
##for$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$rof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##foooooooooooooooooooooooooooooooooooooooof
##ffffffffffffffffffffffffffffffffffffffffff
##ffffffffffffffffffffffffffffffffffffffffffffffff
##foooooooooooooooooooooooooooooooooooooooooooooof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##for$ssssssssssssssssssssssssssssssssssssssss$rof
##for$s((((((((((((((((((((((((((((((((((((((s$rof
##for$s(111111111111111111111111111111111111(s$rof
##for$s(1..................................1(s$rof
##for$s(1..................................1(s$rof
##for$s(1..$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$..1(s$rof
##for$s(1..$cccccccccccccccccccccccccccc$..1(s$rof
##for$s(1..$c--------------------------c$..1(s$rof
##for$s(1..$c-$$$$$$$$$$$$$$$$$$$$$$$$-c$..1(s$rof
##for$s(1..$c-$xxxxxxxxxxxxxxxxxxxxxx$-c$..1(s$rof
##for$s(1..$c-$x--------------------x$-c$..1(s$rof
##for$s(1..$c-$x-111111111111111111-x$-c$..1(s$rof
##for$s(1..$c-$x-1))))))))))))))))1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){{{{{{{{{{{{{{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<<<<<<<<<<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<<<<<<<<<<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<''''''''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<''''''''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<'';;;;''<<{)1-x$-c$..1(s$rof
for$s(1..$c-$x-1){<<'';##;''<<{)1-x$-c$..1(s$rof
for$s(1..$c-$x-1){<<'';##;''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<'';;;;''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<''''''''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<''''''''<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<<<<<<<<<<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){<<<<<<<<<<<<{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1){{{{{{{{{{{{{{)1-x$-c$..1(s$rof
##for$s(1..$c-$x-1))))))))))))))))1-x$-c$..1(s$rof
##for$s(1..$c-$x-111111111111111111-x$-c$..1(s$rof
##for$s(1..$c-$x--------------------x$-c$..1(s$rof
##for$s(1..$c-$xxxxxxxxxxxxxxxxxxxxxx$-c$..1(s$rof
##for$s(1..$c-$$$$$$$$$$$$$$$$$$$$$$$$-c$..1(s$rof
##for$s(1..$c--------------------------c$..1(s$rof
##for$s(1..$cccccccccccccccccccccccccccc$..1(s$rof
##for$s(1..$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$..1(s$rof
##for$s(1..................................1(s$rof
##for$s(1..................................1(s$rof
##for$s(111111111111111111111111111111111111(s$rof
##for$s((((((((((((((((((((((((((((((((((((((s$rof
##for$ssssssssssssssssssssssssssssssssssssssss$rof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##foooooooooooooooooooooooooooooooooooooooooooooof
##ffffffffffffffffffffffffffffffffffffffffffffffff
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm$
##$m========================================================m$
##$m=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=m$
##$m=$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa$=m$
##$m=$a[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[a$=m$
##$m=$a[$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$[a$=m$
##$m=$a[$oooooooooooooooooooooooooooooooooooooooooooooo$[a$=m$
##$m=$a[$o============================================o$[a$=m$
##$m=$a[$o=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=o$[a$=m$
##$m=$a[$o=$cccccccccccccccccccccccccccccccccccccccc$=o$[a$=m$
##$m=$a[$o=$c**************************************c$=o$[a$=m$
##$m=$a[$o=$c*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*c$=o$[a$=m$
##$m=$a[$o=$c*$yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy$*c$=o$[a$=m$
##$m=$a[$o=$c*$y++++++++++++++++++++++++++++++++y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$xxxxxxxxxxxxxxxxxxxxxxxxxxxx$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$x]]]]]]]]]]]]]]]]]]]]]]]]]]x$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$x];;;;;;;;;;;;;;;;;;;;;;;;]x$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$x];$$$$$$$$$$$$$$$$$$$$$$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$kkkkkkkkkkkkkkkkkkkk$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k==================k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0000000000000000=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;;;;;;;;;;;;;;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<<<<<<<<<<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<<<<<<<<<<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<''''''''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<''''''''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<'';;;;''<<;0=k$;]x$+y$*c$=o$[a$=m$
$m=$a[$o=$c*$y+$x];$k=0;<<'';##;''<<;0=k$;]x$+y$*c$=o$[a$=m$
$m=$a[$o=$c*$y+$x];$k=0;<<'';##;''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<'';;;;''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<''''''''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<''''''''<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<<<<<<<<<<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;<<<<<<<<<<<<;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0;;;;;;;;;;;;;;0=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k=0000000000000000=k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$k==================k$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$kkkkkkkkkkkkkkkkkkkk$;]x$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y+$x];$$$$$$$$$$$$$$$$$$$$$$;]x$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$x];;;;;;;;;;;;;;;;;;;;;;;;]x$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$x]]]]]]]]]]]]]]]]]]]]]]]]]]x$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$xxxxxxxxxxxxxxxxxxxxxxxxxxxx$+y$\*c$=o$[a$=m$
##$m=$a[$o=$c\*$y+$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$+y$*c$=o$[a$=m$
##$m=$a[$o=$c*$y++++++++++++++++++++++++++++++++y$*c$=o$[a$=m$
##$m=$a[$o=$c*$yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy$*c$=o$[a$=m$
##$m=$a[$o=$c*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*c$=o$[a$=m$
##$m=$a[$o=$c**************************************c$=o$[a$=m$
##$m=$a[$o=$cccccccccccccccccccccccccccccccccccccccc$=o$[a$=m$
##$m=$a[$o=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=o$[a$=m$
##$m=$a[$o============================================o$[a$=m$
##$m=$a[$oooooooooooooooooooooooooooooooooooooooooooooo$[a$=m$
##$m=$a[$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$[a$=m$
##$m=$a[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[a$=m$
##$m=$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa$=m$
##$m=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=m$
##$m========================================================m$
##$mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##ffffffffffffffffffffffffffffffffffffff
##foooooooooooooooooooooooooooooooooooof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##for$tttttttttttttttttttttttttttttt$rof
##for$t((((((((((((((((((((((((((((t$rof
##for$t(11111111111111111111111111(t$rof
##for$t(1........................1(t$rof
##for$t(1........................1(t$rof
##for$t(1..$$$$$$$$$$$$$$$$$$$$..1(t$rof
##for$t(1..$ssssssssssssssssss$..1(t$rof
##for$t(1..$s))))))))))))))))s$..1(t$rof
##for$t(1..$s){{{{{{{{{{{{{{)s$..1(t$rof
##for$t(1..$s){<<<<<<<<<<<<{)s$..1(t$rof
##for$t(1..$s){<<<<<<<<<<<<{)s$..1(t$rof
##for$t(1..$s){<<''''''''<<{)s$..1(t$rof
##for$t(1..$s){<<''''''''<<{)s$..1(t$rof
##for$t(1..$s){<<'';;;;''<<{)s$..1(t$rof
for$t(1..$s){<<'';##;''<<{)s$..1(t$rof
for$t(1..$s){<<'';##;''<<{)s$..1(t$rof
##for$t(1..$s){<<'';;;;''<<{)s$..1(t$rof
##for$t(1..$s){<<''''''''<<{)s$..1(t$rof
##for$t(1..$s){<<''''''''<<{)s$..1(t$rof
##for$t(1..$s){<<<<<<<<<<<<{)s$..1(t$rof
##for$t(1..$s){<<<<<<<<<<<<{)s$..1(t$rof
##for$t(1..$s){{{{{{{{{{{{{{)s$..1(t$rof
##for$t(1..$s))))))))))))))))s$..1(t$rof
##for$t(1..$ssssssssssssssssss$..1(t$rof
##for$t(1..$$$$$$$$$$$$$$$$$$$$..1(t$rof
##for$t(1........................1(t$rof
##for$t(1........................1(t$rof
##for$t(11111111111111111111111111(t$rof
##for$t((((((((((((((((((((((((((((t$rof
##for$tttttttttttttttttttttttttttttt$rof
##for$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$rof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##foooooooooooooooooooooooooooooooooooof
##ffffffffffffffffffffffffffffffffffffff
##ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
##foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##for((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((rof
##for($$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$(rof
##for($tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt$(rof
##for($t,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,t$(rof
##for($t,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,t$(rof
##for($t,$cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc$,t$(rof
##for($t,$c\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*c$,t$(rof
##for($t,$c\*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\*c$,t$(rof
##for($t,$c\*$tttttttttttttttttttttttttttttttttttttttttttttttttttttt$\*c$,t$(rof
##for($t,$c\*$t,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,t$\*c$,t$(rof
##for($t,$c\*$t,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,t$*c$,t$(rof
##for($t,$c*$t,$tttttttttttttttttttttttttttttttttttttttttttttttt$,t$*c$,t$(rof
##for($t,$c*$t,$t++++++++++++++++++++++++++++++++++++++++++++++t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$cccccccccccccccccccccccccccccccccccccccccc$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c****************************************c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$ssssssssssssssssssssssssssssssssssss$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$cccccccccccccccccccccccccccccc$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$c\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*c$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$c\*$$$$$$$$$$$$$$$$$$$$$$$$$$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$tttttttttttttttttttttttt$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t++++++++++++++++++++++t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$$$$$$$$$$$$$$$$$$$$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$ssssssssssssssssss$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s))))))))))))))))s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){{{{{{{{{{{{{{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<<<<<<<<<<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<<<<<<<<<<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<''''''''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<''''''''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<'';;;;''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<'';##;''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<'';##;''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<'';;;;''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<''''''''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<''''''''<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<<<<<<<<<<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){<<<<<<<<<<<<{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s){{{{{{{{{{{{{{)s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$s))))))))))))))))s$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$ssssssssssssssssss$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t+$$$$$$$$$$$$$$$$$$$$+t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$t++++++++++++++++++++++t$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$tttttttttttttttttttttttt$*c$,s$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c*$s,$c*$$$$$$$$$$$$$$$$$$$$$$$$$$\*c$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$c\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*c$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$cccccccccccccccccccccccccccccc$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,s$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$ssssssssssssssssssssssssssssssssssss$\*c$+t$,t$\*c$,t$(rof
##for($t,$c\*$t,$t+$c\*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$c****************************************c$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$cccccccccccccccccccccccccccccccccccccccccc$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t+$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$+t$,t$*c$,t$(rof
##for($t,$c*$t,$t++++++++++++++++++++++++++++++++++++++++++++++t$,t$*c$,t$(rof
##for($t,$c*$t,$tttttttttttttttttttttttttttttttttttttttttttttttt$,t$*c$,t$(rof
##for($t,$c*$t,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,t$\*c$,t$(rof
##for($t,$c\*$t,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,t$\*c$,t$(rof
##for($t,$c\*$tttttttttttttttttttttttttttttttttttttttttttttttttttttt$\*c$,t$(rof
##for($t,$c\*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\*c$,t$(rof
##for($t,$c\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*c$,t$(rof
##for($t,$cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc$,t$(rof
##for($t,$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$,t$(rof
##for($t,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,t$(rof
##for($tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt$(rof
##for($$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$(rof
##for((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((rof
##forrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrof
##foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooof
##ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##$kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk$
##$k++++++++++++++++++++++++++++++++++++++++++++k$
##$k+==========================================+k$
##$k+=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=+k$
##$k+=$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa$=+k$
##$k+=$a[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[a$=+k$
##$k+=$a[$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$[a$=+k$
##$k+=$a[$oooooooooooooooooooooooooooooooo$[a$=+k$
##$k+=$a[$o++++++++++++++++++++++++++++++o$[a$=+k$
##$k+=$a[$o+$$$$$$$$$$$$$$$$$$$$$$$$$$$$+o$[a$=+k$
##$k+=$a[$o+$\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_$+o$[a$=+k$
##$k+=$a[$o+$\_]]]]]]]]]]]]]]]]]]]]]]]]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]eeeeeeeeeeeeeeeeeeeeee]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]eqqqqqqqqqqqqqqqqqqqqe]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]eq$$$$$$$$$$$$$$$$$$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$mmmmmmmmmmmmmmmm$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;;;;;;;;;;;;;;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<<<<<<<<<<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<<<<<<<<<<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<''''''''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<''''''''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<'';;;;''<<;m$qe]_$+o$[a$=+k$
$k+=$a[$o+$_]eq$m;<<'';##;''<<;m$qe]_$+o$[a$=+k$
$k+=$a[$o+$_]eq$m;<<'';##;''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<'';;;;''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<''''''''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<''''''''<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<<<<<<<<<<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;<<<<<<<<<<<<;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$m;;;;;;;;;;;;;;m$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$mmmmmmmmmmmmmmmm$qe]_$+o$[a$=+k$
##$k+=$a[$o+$_]eq$$$$$$$$$$$$$$$$$$qe]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]eqqqqqqqqqqqqqqqqqqqqe]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]eeeeeeeeeeeeeeeeeeeeee]\_$+o$[a$=+k$
##$k+=$a[$o+$\_]]]]]]]]]]]]]]]]]]]]]]]]\_$+o$[a$=+k$
##$k+=$a[$o+$\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_$+o$[a$=+k$
##$k+=$a[$o+$$$$$$$$$$$$$$$$$$$$$$$$$$$$+o$[a$=+k$
##$k+=$a[$o++++++++++++++++++++++++++++++o$[a$=+k$
##$k+=$a[$oooooooooooooooooooooooooooooooo$[a$=+k$
##$k+=$a[$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$[a$=+k$
##$k+=$a[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[a$=+k$
##$k+=$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa$=+k$
##$k+=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=+k$
##$k+==========================================+k$
##$k++++++++++++++++++++++++++++++++++++++++++++k$
##$kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk$
##$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}}
##}}$nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn$}}
##}}$n++++++++++++++++++++++++++++++++++n$}}
##}}$n+================================+n$}}
##}}$n+=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=+n$}}
##}}$n+=$kkkkkkkkkkkkkkkkkkkkkkkkkkkk$=+n$}}
##}}$n+=$k==========================k$=+n$}}
##}}$n+=$k==========================k$=+n$}}
##}}$n+=$k==4444444444444444444444==k$=+n$}}
##}}$n+=$k==4********************4==k$=+n$}}
##}}$n+=$k==4*$$$$$$$$$$$$$$$$$$\*4==k$=+n$}}
##}}$n+=$k==4\*$ssssssssssssssss$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;;;;;;;;;;;;;;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<<<<<<<<<<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<<<<<<<<<<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<''''''''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<''''''''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<'';;;;''<<;s$\*4==k$=+n$}}
}}$n+=$k==4\*$s;<<'';##;''<<;s$\*4==k$=+n$}}
}}$n+=$k==4\*$s;<<'';##;''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<'';;;;''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<''''''''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<''''''''<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<<<<<<<<<<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;<<<<<<<<<<<<;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$s;;;;;;;;;;;;;;s$\*4==k$=+n$}}
##}}$n+=$k==4\*$ssssssssssssssss$\*4==k$=+n$}}
##}}$n+=$k==4\*$$$$$$$$$$$$$$$$$$*4==k$=+n$}}
##}}$n+=$k==4********************4==k$=+n$}}
##}}$n+=$k==4444444444444444444444==k$=+n$}}
##}}$n+=$k==========================k$=+n$}}
##}}$n+=$k==========================k$=+n$}}
##}}$n+=$kkkkkkkkkkkkkkkkkkkkkkkkkkkk$=+n$}}
##}}$n+=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$=+n$}}
##}}$n+================================+n$}}
##}}$n++++++++++++++++++++++++++++++++++n$}}
##}}$nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn$}}
##}}$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}pppppppppppppppppppppppppppp}}}
##}}}prrrrrrrrrrrrrrrrrrrrrrrrrrp}}}
##}}}priiiiiiiiiiiiiiiiiiiiiiiirp}}}
##}}}prinnnnnnnnnnnnnnnnnnnnnnirp}}}
##}}}printtttttttttttttttttttnirp}}}
##}}}print$$$$$$$$$$$$$$$$$$tnirp}}}
##}}}print$nnnnnnnnnnnnnnnn$tnirp}}}
##}}}print$n;;;;;;;;;;;;;;n$tnirp}}}
##}}}print$n;<<<<<<<<<<<<;n$tnirp}}}
##}}}print$n;<<<<<<<<<<<<;n$tnirp}}}
##}}}print$n;<<''''''''<<;n$tnirp}}}
##}}}print$n;<<''''''''<<;n$tnirp}}}
##}}}print$n;<<'';;;;''<<;n$tnirp}}}
}}}print$n;<<'';##;''<<;n$tnirp}}}
}}}print$n;<<'';##;''<<;n$tnirp}}}
##}}}print$n;<<'';;;;''<<;n$tnirp}}}
##}}}print$n;<<''''''''<<;n$tnirp}}}
##}}}print$n;<<''''''''<<;n$tnirp}}}
##}}}print$n;<<<<<<<<<<<<;n$tnirp}}}
##}}}print$n;<<<<<<<<<<<<;n$tnirp}}}
##}}}print$n;;;;;;;;;;;;;;n$tnirp}}}
##}}}print$nnnnnnnnnnnnnnnn$tnirp}}}
##}}}print$$$$$$$$$$$$$$$$$$tnirp}}}
##}}}printtttttttttttttttttttnirp}}}
##}}}prinnnnnnnnnnnnnnnnnnnnnnirp}}}
##}}}priiiiiiiiiiiiiiiiiiiiiiiirp}}}
##}}}prrrrrrrrrrrrrrrrrrrrrrrrrrp}}}
##}}}pppppppppppppppppppppppppppp}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
##}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
```
As you can see, every single character is part of a square. The top half of each big square is commented out by line comments, and the bottom half (including the second non-commented line) is escaped by a big here-document beginning in the middle of the square (`<<'';#`) and ending at the empty line after the big square.
This program was automatically generated from the following program:
```
($r,$c,@a)=@ARGV;
for$y(0..$r-1){
for$x(0..$c-1){
for$s(1..$c-$x-1){
$m=$a[$o=$c*$y+$x];$k=0;
for$t(1..$s){
for($t,$c*$t,$t+$c*$s,$c*$t+$s){
$k+=$a[$o+$_]eq$m;
}}$n+=$k==4*$s;
}}}print$n;
```
Which is a program to solve the same challenge, but (very lightly) golfed for bytes and short line lengths, not for score.
It takes as inputs first the height and width of the rectangle, then the individual characters of the rectangle separated by spaces. Example usage: To solve the rectangle
```
xxxyy
xxyyy
xyyxx
```
you call the program like this: `perl theprogram.pl 3 5 x x x y y x x y y y x y y x x`
Anyway, by squaring the code like this, it should be possible to get down to score 0 or 2 with any programming language that has a one-line solution and a line comment character, by transforming the one-liner
```
one-liner
```
like this:
```
##ooooooooooooooooooooo
##onnnnnnnnnnnnnnnnnnno
##oneeeeeeeeeeeeeeeeeno
##one---------------eno
##one-lllllllllllll-eno
##one-liiiiiiiiiiil-eno
##one-linnnnnnnnnil-eno
##one-lineeeeeeenil-eno
##one-linerrrrrenil-eno
##one-liner###renil-eno
one-liner###renil-eno
##one-liner###renil-eno
##one-linerrrrrenil-eno
##one-lineeeeeeenil-eno
##one-linnnnnnnnnil-eno
##one-liiiiiiiiiiil-eno
##one-lllllllllllll-eno
##one---------------eno
##oneeeeeeeeeeeeeeeeeno
##onnnnnnnnnnnnnnnnnnno
##ooooooooooooooooooooo
```
The only characters not part of a square are the two spaces. Depending on the language, there may also be ways to use clever multiline strings or comments (like Perl's here-docs) or some sort of redundant code to make those two space characters into a square.
As for getting the byte count low, my solution has a bunch of immediate improvements, and I'm sure there are also lots of other ways to refine this technique, but I don't have the patience for that; I just wanted to provide a demonstration so you guys can go wild with it.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ ~~16~~ ~~14~~ 10 characters not in squares (~~92~~ ~~103~~ ~~111~~ 127 bytes)
```
!!!ffqqqqQQQ%OOOOGGGxx44---@@&&lllxxTT ~~~ ++||7 ss--~~~ssvvss
!!!ffqqqqQQQ"OOOOGGGxx44---@@&&lllxxTTYa~~~Z++||7Mss--~~~ssvvss
```
Input is a character matrix with characters `+` and `-`. Doesn't count diagonal squares.
[Try it online!](https://tio.run/##y00syfn/X1FRMS2tEAgCAwNV/YHA3d29osLERFdX18FBTS0nJ6eiIiREQaGurk5BW7umxlyhuFhXF8grLi4rKy7mQtavhFN/ZCJQRxRYvy@K/v//o9WBSnXVrRXUdbW1oTSUDxKPBQA)
Or [verify all examples and test cases](https://tio.run/##jU6xCsJADN37FVfB3hCyFRxcOgidRApdrBTs0ukc5KTcUPrrZy65nnUQTDhyeXnvJY/hZfzd53k@jk@Kpmn2F4q6rp0rS0SsqqIwxjjXtkoty6IA5vmgrEWkztppsjbb6nc/9deBFB3rz19635861/qbRtBHpQF1n1GDGDoEKSgoUAiJyekjg6iLQlgNVodoHKgEYuJDyAAlM26BcYLiApnz@3jHZCJueCgr4pJ09j91vQrkbIbe).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20 1917 1908~~ 1905 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), Score ~~20~~ 0
```
ẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆ
ẆZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZẆ
ẆZṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡZẆ
ẆZṡLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLṡZẆ
ẆZṡLƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊLṡZẆ
ẆZṡLƊ€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ƊLṡZẆ
ẆZṡLƊ€ẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZZZZZZZZZZZZZZZZZZZZZZZZZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZUUUUUUUUUUUUUUUUUUUUUUUZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$$$$$$$$$$$$$$$$$$$$$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€€€€€€€€€€€€€€€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎẎẎẎẎẎẎẎẎẎẎẎẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEEEEEEEEEEEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲƲƲƲƲƲƲƲƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€€€€€€€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€SSSSS€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€SqqqS€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€SqqqS€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€SqqqS€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€SSSSS€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€€€€€€€ƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲƲƲƲƲƲƲƲƲEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEEEEEEEEEEEẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎẎẎẎẎẎẎẎẎẎẎẎẎ€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢ€€€€€€€€€€€€€€€ḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢḢƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$ƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬƬ$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZU$$$$$$$$$$$$$$$$$$$$$UZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZUUUUUUUUUUUUUUUUUUUUUUUZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇZZZZZZZZZZZZZZZZZZZZZZZZZƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇƇṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖṖẎ€ƊLṡZẆ
ẆZṡLƊ€ẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎẎ€ƊLṡZẆ
ẆZṡLƊ€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ƊLṡZẆ
ẆZṡLƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊƊLṡZẆ
ẆZṡLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLṡZẆ
ẆZṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡṡZẆ
ẆZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZẆ
ẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆẆ
⁽⁽ĿĿ
⁽⁽ĿĿ
```
A full program taking a list of lists of `.` and `+` characters. (Works for any characters, even more than 2).
**[Try it online!](https://tio.run/##y0rNyan8/58LCB7uahtYBHJBFLEApv7hzoX0R8i2@xAD0PUc66IGxGLso6Y1tEa47H24q492iIC9O6fRBBFh77F2ciDRhuNM/6SYEYodkGaGCjZAqhnH1hADyTD24Y5FpCJy7SEps1BmD/GZg2J7XBGAWiYe24QOqWg09qKJyjYEgwAtzC0sLBw1l3bhS@OUQbNkTfU8SJfSgy6lIV1Kd5pUTlSoN6lQf1OhHUHDhs7AtN4GorU6IK1zmnQ2yOj3DGBPjcR@5QD3hB817gWiI/uP7Edi/v//P1pJDwS0gQBEK@lwKSgBeSCkByaRRLSRRVB0xQIA "Jelly – Try It Online")**
~~Any attempt to reduce score by introducing characters seems to just increase the score more. I guess the way to win this challenge is to find the right [Lenguage](https://esolangs.org/wiki/Lenguage "Since a program consisting entirely of newlines would score 0")!~~
Since Magma posted a very nice [Perl solution](https://codegolf.stackexchange.com/a/172610/53748) scoring \$0\$ I decided to attempt similar using my \$20\$ byte solution:
```
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€S
```
But Jelly has no comment character, so a little extra creativity is required...
Jelly programs consist of "Links" - code separated by newline characters, pilcrow characters (`¶` - interpreted as the same byte as newlines) or valid [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) characters lacking a defined behaviour (at present `q` is an example). The latter actually count as a Link each rather than a pure separator. Program execution starts at the bottom-right most Link, the "Main Link" (here `⁽⁽ĿĿ`).
We can call any other Link as a single-argument function (a "monad") by it's \$1\$-indexed position in the rest of the Links of the program using the "quick" `Ŀ`. These Links are indexable in a modular fashion; so if there are \$n\$ of them then the \$n^\text{th}\$ is the same as the \$0^\text{th}\$ and the \$-m^\text{th}\$ is the same as the \$(-m\mod n)^\text{th}\$.
So the program above starts by executing `⁽⁽ĿĿ`, where `⁽⁽Ŀ` is a representation of \$-27150\$ so `⁽⁽ĿĿ` calls the \$-27150^\text{th}\$ Link which, since there are \$60\$ Links (due to the extra lines and the central nine `q`s), is the \$30 ^\text{th}\$ Link, `ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€S`, to the left of the middle row of the \$3\$-by-\$3\$ square of `q`s. This is called with an argument of the program input:
```
ẆZṡLƊ€ẎṖƇZU$ƬḢ€ẎEƲ€S - Link: list of lists of characters, lines
Ẇ - contiguous slices (i.e [[line1], [line2], ..., [lineN], [line1, line2], [line2, line3], ..., [lineN-1, lineN], [line1, line2, line3], ...., [lineN-2, lineN-1, lineN], ..., ..., lines])
€ - for each (slice):
Ɗ - last three links as a monad:
Z - transpose - i.e. get the columns of the slice
L - length - i.e. get the number of lines in the slice
ṡ - overlapping slices of given length - i.e. get slices of columns of same length as lines in the original slice ...filled squares of all sizes (including 1-by-1)
Ẏ - tighten - from a list of list of squares of each size to a single list of all squares
Ƈ - filter keep if this is truthy:
Ṗ - pop (truthy for all but the 1-by-1 squares)
€ - for each (filled square)
Ʋ - last four links as a monad:
Ƭ - collect up until results are no longer unique:
$ - last two links as a monad:
Z - transpose }
U - upend } - together a quarter rotation
Ḣ€ - head each - i.e. first row of each rotation
Ẏ - tighten - i.e. get the entire perimeter (with repeated corners)
E - all equal? (1 if so, 0 otherwise)
S - sum
```
] |
[Question]
[
[Robbers post](https://codegolf.stackexchange.com/q/152242/66833)
A ***[riffle shuffle](https://en.wikipedia.org/wiki/Shuffling#Riffle)*** is a way of shuffling cards where the deck is split into 2 roughly equal sections and the sections are riffled into each other in small groups. This is how to riffle shuffle a string:
* Split the string into equal sections.
* Reverse the strings, and starting from the start of each string.
* Put runs of a uniformly random length between 1 and the number of characters left in the current string into the final string
* Then remove these characters from the string.
* Repeat for the other half, until both halves are empty.
**An example**
```
"Hello World!" Output string = ""
"Hello ", "World!" ""
"Hell", "World!" " o"
"Hell", "World" " o!"
"Hel", "World" " o!l"
"Hel", "Wo" " o!ldlr"
"H", "Wo" " o!ldlrle"
"H", "" " o!ldlrleoW"
"", "" " o!ldlrleoWH"
```
The final product from `Hello World!` could be `o!ldlrleoWH` and that is what you would output.
## Cops
Your task is to make a program (or function) that will riffle shuffle a string. If the inputted string is of odd length, just split it into two uneven length strings with a relative length of `+1` and `+0` (`abc => [ab, c] or [a, bc]`). You may take input in the normal fashion and produce output in the normal fashion.
Your Cops submission will consist of 4 things
* The language you used
* The length of your program in bytes
* **Your program, riffle shuffled.**
* Anything else you want to add
You are aiming to keep your code from being uncracked by the Robbers for 7 days. After that period, your program is *safe* and you should edit in your original program. **Your submission may still be cracked until you reveal your solution.** The shortest, safe solution will be the winner!
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 46 bytes
```
}lr]l:l~\r[-r}x>o?
<!l>x![; ?=\?(0:2i
:,2-%2:
```
There’s almost no obfuscations in the real code, but I suspect a 2D language will be hard enough to crack anyway.
Disclaimer: Written before it was specified that it had to be uniformly random. This is not uniformly random, and I'm not sure how I'd even implement a uniformly random algorithm in ><> to begin with.
[Answer]
# Jelly, 11 bytes, [Cracked](https://codegolf.stackexchange.com/a/152248/68942)
This is a golfed version so someone can probably crack it easily just by making a golfy version. There are probably a few different approaches but I suspect this approach will be decently common with golfing languages.
```
Ṗ/Œż€X€U2sœ
```
The SHA-384 hash of my intended program is `86025a659b3c5fc38e943f72b1f26e28e2e751a7118a589073f1d24fa61ff6b02753d6a0f3f0c7fee6555de69fd06a74` (using UTF-8 encoding).
[Answer]
# Python 3, 154 bytes (list of chars -> list of chars) (function) [Cracked](https://codegolf.stackexchange.com/a/152247/68942)
```
[=o;]1-::[]:s[i,]1-::[]s:[i=R,L;2//)i(nel=s
:)i(r fed
*tropmi modR+L+o nruter
]:s[L,R=R,L;]s:[L=+o;))L(nel,1(tnidnar=s:R dna L elihw
]nar morf
```
I doubt this will be too hard to crack, especially since riffling once is rather ineffective (you can see entire program components in the output...). This is mostly just to get things rolling. There might be some whitespace (including newlines) that I didn't copy correctly. The SHA-384 hash of my intended solution is
`5924530418bf8cd603c25da04ea308b124fdddfc61e7060d78b35e50ead69a7fbde9200b5ee16635cc0ee9df9c954fa1`.
[Answer]
# [Röda](http://github.com/fergusq/roda), 118 bytes
```
2//x#=z}][=]:y[x
}]0>)b..a(#[]1-::[]:y[x
x#%)(reelihw}]0>b#[fi)b(g
getnI]0>a#[fi)a(g{]mo:z[x=b]zdnar=y|x|{=:[g{xx=a
f
```
It takes a stream of characters as input and outputs a stream of characters.
[Answer]
# [R](https://www.r-project.org/), 283 bytes, [Cracked](https://codegolf.stackexchange.com/a/152319/66323)
```
/n,s(daeh-<l
))'',s(tilpsrts(le::sdohtem-<s
)s(rahcn-<n{)s(noitcnufhtgnel(fi
})x-,l(liat-<l
)))x,l(daeh(ver,o(c-<o
)1,)l(htgnel(elihw
}{-<o
)2/n,s(liat-<r
)2'=pes,o(tac
}})y-,r(liat-<r
)))y,r(daeh(ver,o(c-<o
)1,)r(htgnel(elpmas-<y{))r(l(fi{))r(htgnel|)l(htgnel()'htgne}(lpmas-<x{))le
```
I realize now that writing a longer answer has more "runs" of characters that are preserved, alas.
Good luck!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 62 bytes
```
(g÷f¨()⍵(≢~⊃⍵⍺⍉⍨⍨}(←(←'')⊂f≢(g∘⌈¨}{?↑-⍵↑⋄)≢)))≢⊂{,⋄⍵⍵↑2f≢∘⊃?()
```
SHA-384 of my intended solution: `3209dba6ce8abd880eb0595cc0a334be7e686ca0aa441309b7c5c8d3118d877de2a48cbc6af9ef0299477e3170d1b94a`
This is probably easy enough, especially since most of the people in the APL chat helped me build this answer.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes, [Cracked](https://codegolf.stackexchange.com/a/152254/59487)
```
_Qm/dc2iF.jk.O
```
Pretty standard-issue Pyth implementation to test the waters. May be quite easy to crack, but I guess we'll see how it fares.
[Answer]
# [Random Brainfuck](https://github.com/TryItOnline/brainfuck), 273 bytes
```
]<.[<<]<[<<]<[<]<,.[<]-<<<]>>>>>]<+>-[<]<+>-[<<]>]>+<]<]>[>>]]>[>>]<]<+>-[[<<]>]>[>>]<-[[[>>]]>[>]<+>-[[<]<[[?>>]<+>-[[<]-<]>]<[>>]<<+>>+>-[[<<,[>]<.[<]>[>]<+>-[<]>[>]->>>]<<<<<]>+-[<<-[>]>+<-[>>]<]<+>-[[[<<]]<[<]>+<-[[><]<[[>]<+>-[>],]<+>-[<]<->>+]>[[<-[<?<<+>>>[,]>+<-[[>
```
Random brainfuck is the same as normal brainfuck, but it introduces the `?` character, which sets the current cell to a random value. Fun note; I had a version of this that only worked for inputs of less than 256 characters, for obvious reasons, but the code itself was longer than that. When I changed it to handle longer, it turned out to be one byte shorter than the original. ¯\\_(ツ)\_/¯.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 25 bytes, [Cracked](https://codegolf.stackexchange.com/a/152943/60919)
```
iUL1[N@O;?x?v:/2L=0LF;.':
```
Takes input as a `"quoted string"` on the command line.
] |
[Question]
[
The goal is to get all combinations of hold'em starting hands (every two card combination) in the shortest amount of code.
A hold'em hand is two distinct cards dealt from a standard deck of **52** cards, with deal-order being irrelevant, as such there are `52*51/2 = 1326`, hands.
There is also a commonly used notation for the cards and hands:
A standard deck consists of **52** cards; each card has a rank and a suit. There are **4** suits which we shall label `cdhs`, these are not ordered. There are **13** ranks, these are ordered - from the highest rank, `A`, to lowest rank, `2` - which we shall label `AKQJT98765432`.
The full deck of **52** cards may be represented as:
```
Ac Ad Ah As Kc Kd Kh Ks Qc Qd Qh Qs Jc Jd Jh Js Tc Td Th Ts 9c 9d 9h 9s 8c 8d 8h 8s 7c 7d 7h 7s 6c 6d 6h 6s 5c 5d 5h 5s 4c 4d 4h 4s 3c 3d 3h 3s 2c 2d 2h 2s
```
A hold'em hand consists of two of these cards, and the hand may be represented as the two representations from the above list adjoined (e.g. `JdJc` or `JsTs`)
Given no input the output should be all such "combinations" (with any clear delimitation) - that is all `52*51/2 = 1326` (not "all" `52*51 = 2652`):
* For every (rank-wise) "pair" such as `7d7h` there is an equivalent representation (here `7h7d`) only **one of** these two should appear (it may be either).
* For every other combination such as `Qc8s` there is an equivalent reprentation (here `8sQc`) only the **former** should appear (the one with the left card being the higher ranked one)
Example valid outputs:
```
['AcAs', 'AhAs', 'AdAs', 'AhAc', 'AdAc', 'AdAh', 'AsKs', 'AcKs', 'AhKs', 'AdKs', 'KcKs', 'KhKs', 'KdKs', 'AsKc', 'AcKc', 'AhKc', 'AdKc', 'KhKc', 'KdKc', 'AsKh', 'AcKh', 'AhKh', 'AdKh', 'KdKh', 'AsKd', 'AcKd', 'AhKd', 'AdKd', 'AsQs', 'AcQs', 'AhQs', 'AdQs', 'KsQs', 'KcQs', 'KhQs', 'KdQs', 'QcQs', 'QhQs', 'QdQs', 'AsQc', 'AcQc', 'AhQc', 'AdQc', 'KsQc', 'KcQc', 'KhQc', 'KdQc', 'QhQc', 'QdQc', 'AsQh', 'AcQh', 'AhQh', 'AdQh', 'KsQh', 'KcQh', 'KhQh', 'KdQh', 'QdQh', 'AsQd', 'AcQd', 'AhQd', 'AdQd', 'KsQd', 'KcQd', 'KhQd', 'KdQd', 'AsJs', 'AcJs', 'AhJs', 'AdJs', 'KsJs', 'KcJs', 'KhJs', 'KdJs', 'QsJs', 'QcJs', 'QhJs', 'QdJs', 'JcJs', 'JhJs', 'JdJs', 'AsJc', 'AcJc', 'AhJc', 'AdJc', 'KsJc', 'KcJc', 'KhJc', 'KdJc', 'QsJc', 'QcJc', 'QhJc', 'QdJc', 'JhJc', 'JdJc', 'AsJh', 'AcJh', 'AhJh', 'AdJh', 'KsJh', 'KcJh', 'KhJh', 'KdJh', 'QsJh', 'QcJh', 'QhJh', 'QdJh', 'JdJh', 'AsJd', 'AcJd', 'AhJd', 'AdJd', 'KsJd', 'KcJd', 'KhJd', 'KdJd', 'QsJd', 'QcJd', 'QhJd', 'QdJd', 'AsTs', 'AcTs', 'AhTs', 'AdTs', 'KsTs', 'KcTs', 'KhTs', 'KdTs', 'QsTs', 'QcTs', 'QhTs', 'QdTs', 'JsTs', 'JcTs', 'JhTs', 'JdTs', 'TcTs', 'ThTs', 'TdTs', 'AsTc', 'AcTc', 'AhTc', 'AdTc', 'KsTc', 'KcTc', 'KhTc', 'KdTc', 'QsTc', 'QcTc', 'QhTc', 'QdTc', 'JsTc', 'JcTc', 'JhTc', 'JdTc', 'ThTc', 'TdTc', 'AsTh', 'AcTh', 'AhTh', 'AdTh', 'KsTh', 'KcTh', 'KhTh', 'KdTh', 'QsTh', 'QcTh', 'QhTh', 'QdTh', 'JsTh', 'JcTh', 'JhTh', 'JdTh', 'TdTh', 'AsTd', 'AcTd', 'AhTd', 'AdTd', 'KsTd', 'KcTd', 'KhTd', 'KdTd', 'QsTd', 'QcTd', 'QhTd', 'QdTd', 'JsTd', 'JcTd', 'JhTd', 'JdTd', 'As9s', 'Ac9s', 'Ah9s', 'Ad9s', 'Ks9s', 'Kc9s', 'Kh9s', 'Kd9s', 'Qs9s', 'Qc9s', 'Qh9s', 'Qd9s', 'Js9s', 'Jc9s', 'Jh9s', 'Jd9s', 'Ts9s', 'Tc9s', 'Th9s', 'Td9s', '9c9s', '9h9s', '9d9s', 'As9c', 'Ac9c', 'Ah9c', 'Ad9c', 'Ks9c', 'Kc9c', 'Kh9c', 'Kd9c', 'Qs9c', 'Qc9c', 'Qh9c', 'Qd9c', 'Js9c', 'Jc9c', 'Jh9c', 'Jd9c', 'Ts9c', 'Tc9c', 'Th9c', 'Td9c', '9h9c', '9d9c', 'As9h', 'Ac9h', 'Ah9h', 'Ad9h', 'Ks9h', 'Kc9h', 'Kh9h', 'Kd9h', 'Qs9h', 'Qc9h', 'Qh9h', 'Qd9h', 'Js9h', 'Jc9h', 'Jh9h', 'Jd9h', 'Ts9h', 'Tc9h', 'Th9h', 'Td9h', '9d9h', 'As9d', 'Ac9d', 'Ah9d', 'Ad9d', 'Ks9d', 'Kc9d', 'Kh9d', 'Kd9d', 'Qs9d', 'Qc9d', 'Qh9d', 'Qd9d', 'Js9d', 'Jc9d', 'Jh9d', 'Jd9d', 'Ts9d', 'Tc9d', 'Th9d', 'Td9d', 'As8s', 'Ac8s', 'Ah8s', 'Ad8s', 'Ks8s', 'Kc8s', 'Kh8s', 'Kd8s', 'Qs8s', 'Qc8s', 'Qh8s', 'Qd8s', 'Js8s', 'Jc8s', 'Jh8s', 'Jd8s', 'Ts8s', 'Tc8s', 'Th8s', 'Td8s', '9s8s', '9c8s', '9h8s', '9d8s', '8c8s', '8h8s', '8d8s', 'As8c', 'Ac8c', 'Ah8c', 'Ad8c', 'Ks8c', 'Kc8c', 'Kh8c', 'Kd8c', 'Qs8c', 'Qc8c', 'Qh8c', 'Qd8c', 'Js8c', 'Jc8c', 'Jh8c', 'Jd8c', 'Ts8c', 'Tc8c', 'Th8c', 'Td8c', '9s8c', '9c8c', '9h8c', '9d8c', '8h8c', '8d8c', 'As8h', 'Ac8h', 'Ah8h', 'Ad8h', 'Ks8h', 'Kc8h', 'Kh8h', 'Kd8h', 'Qs8h', 'Qc8h', 'Qh8h', 'Qd8h', 'Js8h', 'Jc8h', 'Jh8h', 'Jd8h', 'Ts8h', 'Tc8h', 'Th8h', 'Td8h', '9s8h', '9c8h', '9h8h', '9d8h', '8d8h', 'As8d', 'Ac8d', 'Ah8d', 'Ad8d', 'Ks8d', 'Kc8d', 'Kh8d', 'Kd8d', 'Qs8d', 'Qc8d', 'Qh8d', 'Qd8d', 'Js8d', 'Jc8d', 'Jh8d', 'Jd8d', 'Ts8d', 'Tc8d', 'Th8d', 'Td8d', '9s8d', '9c8d', '9h8d', '9d8d', 'As7s', 'Ac7s', 'Ah7s', 'Ad7s', 'Ks7s', 'Kc7s', 'Kh7s', 'Kd7s', 'Qs7s', 'Qc7s', 'Qh7s', 'Qd7s', 'Js7s', 'Jc7s', 'Jh7s', 'Jd7s', 'Ts7s', 'Tc7s', 'Th7s', 'Td7s', '9s7s', '9c7s', '9h7s', '9d7s', '8s7s', '8c7s', '8h7s', '8d7s', '7c7s', '7h7s', '7d7s', 'As7c', 'Ac7c', 'Ah7c', 'Ad7c', 'Ks7c', 'Kc7c', 'Kh7c', 'Kd7c', 'Qs7c', 'Qc7c', 'Qh7c', 'Qd7c', 'Js7c', 'Jc7c', 'Jh7c', 'Jd7c', 'Ts7c', 'Tc7c', 'Th7c', 'Td7c', '9s7c', '9c7c', '9h7c', '9d7c', '8s7c', '8c7c', '8h7c', '8d7c', '7h7c', '7d7c', 'As7h', 'Ac7h', 'Ah7h', 'Ad7h', 'Ks7h', 'Kc7h', 'Kh7h', 'Kd7h', 'Qs7h', 'Qc7h', 'Qh7h', 'Qd7h', 'Js7h', 'Jc7h', 'Jh7h', 'Jd7h', 'Ts7h', 'Tc7h', 'Th7h', 'Td7h', '9s7h', '9c7h', '9h7h', '9d7h', '8s7h', '8c7h', '8h7h', '8d7h', '7d7h', 'As7d', 'Ac7d', 'Ah7d', 'Ad7d', 'Ks7d', 'Kc7d', 'Kh7d', 'Kd7d', 'Qs7d', 'Qc7d', 'Qh7d', 'Qd7d', 'Js7d', 'Jc7d', 'Jh7d', 'Jd7d', 'Ts7d', 'Tc7d', 'Th7d', 'Td7d', '9s7d', '9c7d', '9h7d', '9d7d', '8s7d', '8c7d', '8h7d', '8d7d', 'As6s', 'Ac6s', 'Ah6s', 'Ad6s', 'Ks6s', 'Kc6s', 'Kh6s', 'Kd6s', 'Qs6s', 'Qc6s', 'Qh6s', 'Qd6s', 'Js6s', 'Jc6s', 'Jh6s', 'Jd6s', 'Ts6s', 'Tc6s', 'Th6s', 'Td6s', '9s6s', '9c6s', '9h6s', '9d6s', '8s6s', '8c6s', '8h6s', '8d6s', '7s6s', '7c6s', '7h6s', '7d6s', '6c6s', '6h6s', '6d6s', 'As6c', 'Ac6c', 'Ah6c', 'Ad6c', 'Ks6c', 'Kc6c', 'Kh6c', 'Kd6c', 'Qs6c', 'Qc6c', 'Qh6c', 'Qd6c', 'Js6c', 'Jc6c', 'Jh6c', 'Jd6c', 'Ts6c', 'Tc6c', 'Th6c', 'Td6c', '9s6c', '9c6c', '9h6c', '9d6c', '8s6c', '8c6c', '8h6c', '8d6c', '7s6c', '7c6c', '7h6c', '7d6c', '6h6c', '6d6c', 'As6h', 'Ac6h', 'Ah6h', 'Ad6h', 'Ks6h', 'Kc6h', 'Kh6h', 'Kd6h', 'Qs6h', 'Qc6h', 'Qh6h', 'Qd6h', 'Js6h', 'Jc6h', 'Jh6h', 'Jd6h', 'Ts6h', 'Tc6h', 'Th6h', 'Td6h', '9s6h', '9c6h', '9h6h', '9d6h', '8s6h', '8c6h', '8h6h', '8d6h', '7s6h', '7c6h', '7h6h', '7d6h', '6d6h', 'As6d', 'Ac6d', 'Ah6d', 'Ad6d', 'Ks6d', 'Kc6d', 'Kh6d', 'Kd6d', 'Qs6d', 'Qc6d', 'Qh6d', 'Qd6d', 'Js6d', 'Jc6d', 'Jh6d', 'Jd6d', 'Ts6d', 'Tc6d', 'Th6d', 'Td6d', '9s6d', '9c6d', '9h6d', '9d6d', '8s6d', '8c6d', '8h6d', '8d6d', '7s6d', '7c6d', '7h6d', '7d6d', 'As5s', 'Ac5s', 'Ah5s', 'Ad5s', 'Ks5s', 'Kc5s', 'Kh5s', 'Kd5s', 'Qs5s', 'Qc5s', 'Qh5s', 'Qd5s', 'Js5s', 'Jc5s', 'Jh5s', 'Jd5s', 'Ts5s', 'Tc5s', 'Th5s', 'Td5s', '9s5s', '9c5s', '9h5s', '9d5s', '8s5s', '8c5s', '8h5s', '8d5s', '7s5s', '7c5s', '7h5s', '7d5s', '6s5s', '6c5s', '6h5s', '6d5s', '5c5s', '5h5s', '5d5s', 'As5c', 'Ac5c', 'Ah5c', 'Ad5c', 'Ks5c', 'Kc5c', 'Kh5c', 'Kd5c', 'Qs5c', 'Qc5c', 'Qh5c', 'Qd5c', 'Js5c', 'Jc5c', 'Jh5c', 'Jd5c', 'Ts5c', 'Tc5c', 'Th5c', 'Td5c', '9s5c', '9c5c', '9h5c', '9d5c', '8s5c', '8c5c', '8h5c', '8d5c', '7s5c', '7c5c', '7h5c', '7d5c', '6s5c', '6c5c', '6h5c', '6d5c', '5h5c', '5d5c', 'As5h', 'Ac5h', 'Ah5h', 'Ad5h', 'Ks5h', 'Kc5h', 'Kh5h', 'Kd5h', 'Qs5h', 'Qc5h', 'Qh5h', 'Qd5h', 'Js5h', 'Jc5h', 'Jh5h', 'Jd5h', 'Ts5h', 'Tc5h', 'Th5h', 'Td5h', '9s5h', '9c5h', '9h5h', '9d5h', '8s5h', '8c5h', '8h5h', '8d5h', '7s5h', '7c5h', '7h5h', '7d5h', '6s5h', '6c5h', '6h5h', '6d5h', '5d5h', 'As5d', 'Ac5d', 'Ah5d', 'Ad5d', 'Ks5d', 'Kc5d', 'Kh5d', 'Kd5d', 'Qs5d', 'Qc5d', 'Qh5d', 'Qd5d', 'Js5d', 'Jc5d', 'Jh5d', 'Jd5d', 'Ts5d', 'Tc5d', 'Th5d', 'Td5d', '9s5d', '9c5d', '9h5d', '9d5d', '8s5d', '8c5d', '8h5d', '8d5d', '7s5d', '7c5d', '7h5d', '7d5d', '6s5d', '6c5d', '6h5d', '6d5d', 'As4s', 'Ac4s', 'Ah4s', 'Ad4s', 'Ks4s', 'Kc4s', 'Kh4s', 'Kd4s', 'Qs4s', 'Qc4s', 'Qh4s', 'Qd4s', 'Js4s', 'Jc4s', 'Jh4s', 'Jd4s', 'Ts4s', 'Tc4s', 'Th4s', 'Td4s', '9s4s', '9c4s', '9h4s', '9d4s', '8s4s', '8c4s', '8h4s', '8d4s', '7s4s', '7c4s', '7h4s', '7d4s', '6s4s', '6c4s', '6h4s', '6d4s', '5s4s', '5c4s', '5h4s', '5d4s', '4c4s', '4h4s', '4d4s', 'As4c', 'Ac4c', 'Ah4c', 'Ad4c', 'Ks4c', 'Kc4c', 'Kh4c', 'Kd4c', 'Qs4c', 'Qc4c', 'Qh4c', 'Qd4c', 'Js4c', 'Jc4c', 'Jh4c', 'Jd4c', 'Ts4c', 'Tc4c', 'Th4c', 'Td4c', '9s4c', '9c4c', '9h4c', '9d4c', '8s4c', '8c4c', '8h4c', '8d4c', '7s4c', '7c4c', '7h4c', '7d4c', '6s4c', '6c4c', '6h4c', '6d4c', '5s4c', '5c4c', '5h4c', '5d4c', '4h4c', '4d4c', 'As4h', 'Ac4h', 'Ah4h', 'Ad4h', 'Ks4h', 'Kc4h', 'Kh4h', 'Kd4h', 'Qs4h', 'Qc4h', 'Qh4h', 'Qd4h', 'Js4h', 'Jc4h', 'Jh4h', 'Jd4h', 'Ts4h', 'Tc4h', 'Th4h', 'Td4h', '9s4h', '9c4h', '9h4h', '9d4h', '8s4h', '8c4h', '8h4h', '8d4h', '7s4h', '7c4h', '7h4h', '7d4h', '6s4h', '6c4h', '6h4h', '6d4h', '5s4h', '5c4h', '5h4h', '5d4h', '4d4h', 'As4d', 'Ac4d', 'Ah4d', 'Ad4d', 'Ks4d', 'Kc4d', 'Kh4d', 'Kd4d', 'Qs4d', 'Qc4d', 'Qh4d', 'Qd4d', 'Js4d', 'Jc4d', 'Jh4d', 'Jd4d', 'Ts4d', 'Tc4d', 'Th4d', 'Td4d', '9s4d', '9c4d', '9h4d', '9d4d', '8s4d', '8c4d', '8h4d', '8d4d', '7s4d', '7c4d', '7h4d', '7d4d', '6s4d', '6c4d', '6h4d', '6d4d', '5s4d', '5c4d', '5h4d', '5d4d', 'As3s', 'Ac3s', 'Ah3s', 'Ad3s', 'Ks3s', 'Kc3s', 'Kh3s', 'Kd3s', 'Qs3s', 'Qc3s', 'Qh3s', 'Qd3s', 'Js3s', 'Jc3s', 'Jh3s', 'Jd3s', 'Ts3s', 'Tc3s', 'Th3s', 'Td3s', '9s3s', '9c3s', '9h3s', '9d3s', '8s3s', '8c3s', '8h3s', '8d3s', '7s3s', '7c3s', '7h3s', '7d3s', '6s3s', '6c3s', '6h3s', '6d3s', '5s3s', '5c3s', '5h3s', '5d3s', '4s3s', '4c3s', '4h3s', '4d3s', '3c3s', '3h3s', '3d3s', 'As3c', 'Ac3c', 'Ah3c', 'Ad3c', 'Ks3c', 'Kc3c', 'Kh3c', 'Kd3c', 'Qs3c', 'Qc3c', 'Qh3c', 'Qd3c', 'Js3c', 'Jc3c', 'Jh3c', 'Jd3c', 'Ts3c', 'Tc3c', 'Th3c', 'Td3c', '9s3c', '9c3c', '9h3c', '9d3c', '8s3c', '8c3c', '8h3c', '8d3c', '7s3c', '7c3c', '7h3c', '7d3c', '6s3c', '6c3c', '6h3c', '6d3c', '5s3c', '5c3c', '5h3c', '5d3c', '4s3c', '4c3c', '4h3c', '4d3c', '3h3c', '3d3c', 'As3h', 'Ac3h', 'Ah3h', 'Ad3h', 'Ks3h', 'Kc3h', 'Kh3h', 'Kd3h', 'Qs3h', 'Qc3h', 'Qh3h', 'Qd3h', 'Js3h', 'Jc3h', 'Jh3h', 'Jd3h', 'Ts3h', 'Tc3h', 'Th3h', 'Td3h', '9s3h', '9c3h', '9h3h', '9d3h', '8s3h', '8c3h', '8h3h', '8d3h', '7s3h', '7c3h', '7h3h', '7d3h', '6s3h', '6c3h', '6h3h', '6d3h', '5s3h', '5c3h', '5h3h', '5d3h', '4s3h', '4c3h', '4h3h', '4d3h', '3d3h', 'As3d', 'Ac3d', 'Ah3d', 'Ad3d', 'Ks3d', 'Kc3d', 'Kh3d', 'Kd3d', 'Qs3d', 'Qc3d', 'Qh3d', 'Qd3d', 'Js3d', 'Jc3d', 'Jh3d', 'Jd3d', 'Ts3d', 'Tc3d', 'Th3d', 'Td3d', '9s3d', '9c3d', '9h3d', '9d3d', '8s3d', '8c3d', '8h3d', '8d3d', '7s3d', '7c3d', '7h3d', '7d3d', '6s3d', '6c3d', '6h3d', '6d3d', '5s3d', '5c3d', '5h3d', '5d3d', '4s3d', '4c3d', '4h3d', '4d3d', 'As2s', 'Ac2s', 'Ah2s', 'Ad2s', 'Ks2s', 'Kc2s', 'Kh2s', 'Kd2s', 'Qs2s', 'Qc2s', 'Qh2s', 'Qd2s', 'Js2s', 'Jc2s', 'Jh2s', 'Jd2s', 'Ts2s', 'Tc2s', 'Th2s', 'Td2s', '9s2s', '9c2s', '9h2s', '9d2s', '8s2s', '8c2s', '8h2s', '8d2s', '7s2s', '7c2s', '7h2s', '7d2s', '6s2s', '6c2s', '6h2s', '6d2s', '5s2s', '5c2s', '5h2s', '5d2s', '4s2s', '4c2s', '4h2s', '4d2s', '3s2s', '3c2s', '3h2s', '3d2s', '2c2s', '2h2s', '2d2s', 'As2c', 'Ac2c', 'Ah2c', 'Ad2c', 'Ks2c', 'Kc2c', 'Kh2c', 'Kd2c', 'Qs2c', 'Qc2c', 'Qh2c', 'Qd2c', 'Js2c', 'Jc2c', 'Jh2c', 'Jd2c', 'Ts2c', 'Tc2c', 'Th2c', 'Td2c', '9s2c', '9c2c', '9h2c', '9d2c', '8s2c', '8c2c', '8h2c', '8d2c', '7s2c', '7c2c', '7h2c', '7d2c', '6s2c', '6c2c', '6h2c', '6d2c', '5s2c', '5c2c', '5h2c', '5d2c', '4s2c', '4c2c', '4h2c', '4d2c', '3s2c', '3c2c', '3h2c', '3d2c', '2h2c', '2d2c', 'As2h', 'Ac2h', 'Ah2h', 'Ad2h', 'Ks2h', 'Kc2h', 'Kh2h', 'Kd2h', 'Qs2h', 'Qc2h', 'Qh2h', 'Qd2h', 'Js2h', 'Jc2h', 'Jh2h', 'Jd2h', 'Ts2h', 'Tc2h', 'Th2h', 'Td2h', '9s2h', '9c2h', '9h2h', '9d2h', '8s2h', '8c2h', '8h2h', '8d2h', '7s2h', '7c2h', '7h2h', '7d2h', '6s2h', '6c2h', '6h2h', '6d2h', '5s2h', '5c2h', '5h2h', '5d2h', '4s2h', '4c2h', '4h2h', '4d2h', '3s2h', '3c2h', '3h2h', '3d2h', '2d2h', 'As2d', 'Ac2d', 'Ah2d', 'Ad2d', 'Ks2d', 'Kc2d', 'Kh2d', 'Kd2d', 'Qs2d', 'Qc2d', 'Qh2d', 'Qd2d', 'Js2d', 'Jc2d', 'Jh2d', 'Jd2d', 'Ts2d', 'Tc2d', 'Th2d', 'Td2d', '9s2d', '9c2d', '9h2d', '9d2d', '8s2d', '8c2d', '8h2d', '8d2d', '7s2d', '7c2d', '7h2d', '7d2d', '6s2d', '6c2d', '6h2d', '6d2d', '5s2d', '5c2d', '5h2d', '5d2d', '4s2d', '4c2d', '4h2d', '4d2d', '3s2d', '3c2d', '3h2d', '3d2d']
```
```
['AhAs', 'AsAd', 'AcAs', 'AdAh', 'AcAh', 'AdAc', 'AsKs', 'AhKs', 'AdKs', 'AcKs', 'KsKh', 'KdKs', 'KsKc', 'AsKh', 'AhKh', 'AdKh', 'AcKh', 'KdKh', 'KcKh', 'AsKd', 'AhKd', 'AdKd', 'AcKd', 'KcKd', 'AsKc', 'AhKc', 'AdKc', 'AcKc', 'AsQs', 'AhQs', 'AdQs', 'AcQs', 'KsQs', 'KhQs', 'KdQs', 'KcQs', 'QsQh', 'QdQs', 'QcQs', 'AsQh', 'AhQh', 'AdQh', 'AcQh', 'KsQh', 'KhQh', 'KdQh', 'KcQh', 'QhQd', 'QhQc', 'AsQd', 'AhQd', 'AdQd', 'AcQd', 'KsQd', 'KhQd', 'KdQd', 'KcQd', 'QdQc', 'AsQc', 'AhQc', 'AdQc', 'AcQc', 'KsQc', 'KhQc', 'KdQc', 'KcQc', 'AsJs', 'AhJs', 'AdJs', 'AcJs', 'KsJs', 'KhJs', 'KdJs', 'KcJs', 'QsJs', 'QhJs', 'QdJs', 'QcJs', 'JsJh', 'JsJd', 'JcJs', 'AsJh', 'AhJh', 'AdJh', 'AcJh', 'KsJh', 'KhJh', 'KdJh', 'KcJh', 'QsJh', 'QhJh', 'QdJh', 'QcJh', 'JdJh', 'JcJh', 'AsJd', 'AhJd', 'AdJd', 'AcJd', 'KsJd', 'KhJd', 'KdJd', 'KcJd', 'QsJd', 'QhJd', 'QdJd', 'QcJd', 'JdJc', 'AsJc', 'AhJc', 'AdJc', 'AcJc', 'KsJc', 'KhJc', 'KdJc', 'KcJc', 'QsJc', 'QhJc', 'QdJc', 'QcJc', 'AsTs', 'AhTs', 'AdTs', 'AcTs', 'KsTs', 'KhTs', 'KdTs', 'KcTs', 'QsTs', 'QhTs', 'QdTs', 'QcTs', 'JsTs', 'JhTs', 'JdTs', 'JcTs', 'ThTs', 'TsTd', 'TsTc', 'AsTh', 'AhTh', 'AdTh', 'AcTh', 'KsTh', 'KhTh', 'KdTh', 'KcTh', 'QsTh', 'QhTh', 'QdTh', 'QcTh', 'JsTh', 'JhTh', 'JdTh', 'JcTh', 'TdTh', 'ThTc', 'AsTd', 'AhTd', 'AdTd', 'AcTd', 'KsTd', 'KhTd', 'KdTd', 'KcTd', 'QsTd', 'QhTd', 'QdTd', 'QcTd', 'JsTd', 'JhTd', 'JdTd', 'JcTd', 'TdTc', 'AsTc', 'AhTc', 'AdTc', 'AcTc', 'KsTc', 'KhTc', 'KdTc', 'KcTc', 'QsTc', 'QhTc', 'QdTc', 'QcTc', 'JsTc', 'JhTc', 'JdTc', 'JcTc', 'As9s', 'Ah9s', 'Ad9s', 'Ac9s', 'Ks9s', 'Kh9s', 'Kd9s', 'Kc9s', 'Qs9s', 'Qh9s', 'Qd9s', 'Qc9s', 'Js9s', 'Jh9s', 'Jd9s', 'Jc9s', 'Ts9s', 'Th9s', 'Td9s', 'Tc9s', '9s9h', '9d9s', '9s9c', 'As9h', 'Ah9h', 'Ad9h', 'Ac9h', 'Ks9h', 'Kh9h', 'Kd9h', 'Kc9h', 'Qs9h', 'Qh9h', 'Qd9h', 'Qc9h', 'Js9h', 'Jh9h', 'Jd9h', 'Jc9h', 'Ts9h', 'Th9h', 'Td9h', 'Tc9h', '9h9d', '9h9c', 'As9d', 'Ah9d', 'Ad9d', 'Ac9d', 'Ks9d', 'Kh9d', 'Kd9d', 'Kc9d', 'Qs9d', 'Qh9d', 'Qd9d', 'Qc9d', 'Js9d', 'Jh9d', 'Jd9d', 'Jc9d', 'Ts9d', 'Th9d', 'Td9d', 'Tc9d', '9c9d', 'As9c', 'Ah9c', 'Ad9c', 'Ac9c', 'Ks9c', 'Kh9c', 'Kd9c', 'Kc9c', 'Qs9c', 'Qh9c', 'Qd9c', 'Qc9c', 'Js9c', 'Jh9c', 'Jd9c', 'Jc9c', 'Ts9c', 'Th9c', 'Td9c', 'Tc9c', 'As8s', 'Ah8s', 'Ad8s', 'Ac8s', 'Ks8s', 'Kh8s', 'Kd8s', 'Kc8s', 'Qs8s', 'Qh8s', 'Qd8s', 'Qc8s', 'Js8s', 'Jh8s', 'Jd8s', 'Jc8s', 'Ts8s', 'Th8s', 'Td8s', 'Tc8s', '9s8s', '9h8s', '9d8s', '9c8s', '8h8s', '8s8d', '8s8c', 'As8h', 'Ah8h', 'Ad8h', 'Ac8h', 'Ks8h', 'Kh8h', 'Kd8h', 'Kc8h', 'Qs8h', 'Qh8h', 'Qd8h', 'Qc8h', 'Js8h', 'Jh8h', 'Jd8h', 'Jc8h', 'Ts8h', 'Th8h', 'Td8h', 'Tc8h', '9s8h', '9h8h', '9d8h', '9c8h', '8d8h', '8h8c', 'As8d', 'Ah8d', 'Ad8d', 'Ac8d', 'Ks8d', 'Kh8d', 'Kd8d', 'Kc8d', 'Qs8d', 'Qh8d', 'Qd8d', 'Qc8d', 'Js8d', 'Jh8d', 'Jd8d', 'Jc8d', 'Ts8d', 'Th8d', 'Td8d', 'Tc8d', '9s8d', '9h8d', '9d8d', '9c8d', '8c8d', 'As8c', 'Ah8c', 'Ad8c', 'Ac8c', 'Ks8c', 'Kh8c', 'Kd8c', 'Kc8c', 'Qs8c', 'Qh8c', 'Qd8c', 'Qc8c', 'Js8c', 'Jh8c', 'Jd8c', 'Jc8c', 'Ts8c', 'Th8c', 'Td8c', 'Tc8c', '9s8c', '9h8c', '9d8c', '9c8c', 'As7s', 'Ah7s', 'Ad7s', 'Ac7s', 'Ks7s', 'Kh7s', 'Kd7s', 'Kc7s', 'Qs7s', 'Qh7s', 'Qd7s', 'Qc7s', 'Js7s', 'Jh7s', 'Jd7s', 'Jc7s', 'Ts7s', 'Th7s', 'Td7s', 'Tc7s', '9s7s', '9h7s', '9d7s', '9c7s', '8s7s', '8h7s', '8d7s', '8c7s', '7s7h', '7s7d', '7s7c', 'As7h', 'Ah7h', 'Ad7h', 'Ac7h', 'Ks7h', 'Kh7h', 'Kd7h', 'Kc7h', 'Qs7h', 'Qh7h', 'Qd7h', 'Qc7h', 'Js7h', 'Jh7h', 'Jd7h', 'Jc7h', 'Ts7h', 'Th7h', 'Td7h', 'Tc7h', '9s7h', '9h7h', '9d7h', '9c7h', '8s7h', '8h7h', '8d7h', '8c7h', '7d7h', '7c7h', 'As7d', 'Ah7d', 'Ad7d', 'Ac7d', 'Ks7d', 'Kh7d', 'Kd7d', 'Kc7d', 'Qs7d', 'Qh7d', 'Qd7d', 'Qc7d', 'Js7d', 'Jh7d', 'Jd7d', 'Jc7d', 'Ts7d', 'Th7d', 'Td7d', 'Tc7d', '9s7d', '9h7d', '9d7d', '9c7d', '8s7d', '8h7d', '8d7d', '8c7d', '7d7c', 'As7c', 'Ah7c', 'Ad7c', 'Ac7c', 'Ks7c', 'Kh7c', 'Kd7c', 'Kc7c', 'Qs7c', 'Qh7c', 'Qd7c', 'Qc7c', 'Js7c', 'Jh7c', 'Jd7c', 'Jc7c', 'Ts7c', 'Th7c', 'Td7c', 'Tc7c', '9s7c', '9h7c', '9d7c', '9c7c', '8s7c', '8h7c', '8d7c', '8c7c', 'As6s', 'Ah6s', 'Ad6s', 'Ac6s', 'Ks6s', 'Kh6s', 'Kd6s', 'Kc6s', 'Qs6s', 'Qh6s', 'Qd6s', 'Qc6s', 'Js6s', 'Jh6s', 'Jd6s', 'Jc6s', 'Ts6s', 'Th6s', 'Td6s', 'Tc6s', '9s6s', '9h6s', '9d6s', '9c6s', '8s6s', '8h6s', '8d6s', '8c6s', '7s6s', '7h6s', '7d6s', '7c6s', '6s6h', '6s6d', '6c6s', 'As6h', 'Ah6h', 'Ad6h', 'Ac6h', 'Ks6h', 'Kh6h', 'Kd6h', 'Kc6h', 'Qs6h', 'Qh6h', 'Qd6h', 'Qc6h', 'Js6h', 'Jh6h', 'Jd6h', 'Jc6h', 'Ts6h', 'Th6h', 'Td6h', 'Tc6h', '9s6h', '9h6h', '9d6h', '9c6h', '8s6h', '8h6h', '8d6h', '8c6h', '7s6h', '7h6h', '7d6h', '7c6h', '6d6h', '6c6h', 'As6d', 'Ah6d', 'Ad6d', 'Ac6d', 'Ks6d', 'Kh6d', 'Kd6d', 'Kc6d', 'Qs6d', 'Qh6d', 'Qd6d', 'Qc6d', 'Js6d', 'Jh6d', 'Jd6d', 'Jc6d', 'Ts6d', 'Th6d', 'Td6d', 'Tc6d', '9s6d', '9h6d', '9d6d', '9c6d', '8s6d', '8h6d', '8d6d', '8c6d', '7s6d', '7h6d', '7d6d', '7c6d', '6d6c', 'As6c', 'Ah6c', 'Ad6c', 'Ac6c', 'Ks6c', 'Kh6c', 'Kd6c', 'Kc6c', 'Qs6c', 'Qh6c', 'Qd6c', 'Qc6c', 'Js6c', 'Jh6c', 'Jd6c', 'Jc6c', 'Ts6c', 'Th6c', 'Td6c', 'Tc6c', '9s6c', '9h6c', '9d6c', '9c6c', '8s6c', '8h6c', '8d6c', '8c6c', '7s6c', '7h6c', '7d6c', '7c6c', 'As5s', 'Ah5s', 'Ad5s', 'Ac5s', 'Ks5s', 'Kh5s', 'Kd5s', 'Kc5s', 'Qs5s', 'Qh5s', 'Qd5s', 'Qc5s', 'Js5s', 'Jh5s', 'Jd5s', 'Jc5s', 'Ts5s', 'Th5s', 'Td5s', 'Tc5s', '9s5s', '9h5s', '9d5s', '9c5s', '8s5s', '8h5s', '8d5s', '8c5s', '7s5s', '7h5s', '7d5s', '7c5s', '6s5s', '6h5s', '6d5s', '6c5s', '5s5h', '5s5d', '5c5s', 'As5h', 'Ah5h', 'Ad5h', 'Ac5h', 'Ks5h', 'Kh5h', 'Kd5h', 'Kc5h', 'Qs5h', 'Qh5h', 'Qd5h', 'Qc5h', 'Js5h', 'Jh5h', 'Jd5h', 'Jc5h', 'Ts5h', 'Th5h', 'Td5h', 'Tc5h', '9s5h', '9h5h', '9d5h', '9c5h', '8s5h', '8h5h', '8d5h', '8c5h', '7s5h', '7h5h', '7d5h', '7c5h', '6s5h', '6h5h', '6d5h', '6c5h', '5d5h', '5h5c', 'As5d', 'Ah5d', 'Ad5d', 'Ac5d', 'Ks5d', 'Kh5d', 'Kd5d', 'Kc5d', 'Qs5d', 'Qh5d', 'Qd5d', 'Qc5d', 'Js5d', 'Jh5d', 'Jd5d', 'Jc5d', 'Ts5d', 'Th5d', 'Td5d', 'Tc5d', '9s5d', '9h5d', '9d5d', '9c5d', '8s5d', '8h5d', '8d5d', '8c5d', '7s5d', '7h5d', '7d5d', '7c5d', '6s5d', '6h5d', '6d5d', '6c5d', '5d5c', 'As5c', 'Ah5c', 'Ad5c', 'Ac5c', 'Ks5c', 'Kh5c', 'Kd5c', 'Kc5c', 'Qs5c', 'Qh5c', 'Qd5c', 'Qc5c', 'Js5c', 'Jh5c', 'Jd5c', 'Jc5c', 'Ts5c', 'Th5c', 'Td5c', 'Tc5c', '9s5c', '9h5c', '9d5c', '9c5c', '8s5c', '8h5c', '8d5c', '8c5c', '7s5c', '7h5c', '7d5c', '7c5c', '6s5c', '6h5c', '6d5c', '6c5c', 'As4s', 'Ah4s', 'Ad4s', 'Ac4s', 'Ks4s', 'Kh4s', 'Kd4s', 'Kc4s', 'Qs4s', 'Qh4s', 'Qd4s', 'Qc4s', 'Js4s', 'Jh4s', 'Jd4s', 'Jc4s', 'Ts4s', 'Th4s', 'Td4s', 'Tc4s', '9s4s', '9h4s', '9d4s', '9c4s', '8s4s', '8h4s', '8d4s', '8c4s', '7s4s', '7h4s', '7d4s', '7c4s', '6s4s', '6h4s', '6d4s', '6c4s', '5s4s', '5h4s', '5d4s', '5c4s', '4s4h', '4s4d', '4s4c', 'As4h', 'Ah4h', 'Ad4h', 'Ac4h', 'Ks4h', 'Kh4h', 'Kd4h', 'Kc4h', 'Qs4h', 'Qh4h', 'Qd4h', 'Qc4h', 'Js4h', 'Jh4h', 'Jd4h', 'Jc4h', 'Ts4h', 'Th4h', 'Td4h', 'Tc4h', '9s4h', '9h4h', '9d4h', '9c4h', '8s4h', '8h4h', '8d4h', '8c4h', '7s4h', '7h4h', '7d4h', '7c4h', '6s4h', '6h4h', '6d4h', '6c4h', '5s4h', '5h4h', '5d4h', '5c4h', '4h4d', '4c4h', 'As4d', 'Ah4d', 'Ad4d', 'Ac4d', 'Ks4d', 'Kh4d', 'Kd4d', 'Kc4d', 'Qs4d', 'Qh4d', 'Qd4d', 'Qc4d', 'Js4d', 'Jh4d', 'Jd4d', 'Jc4d', 'Ts4d', 'Th4d', 'Td4d', 'Tc4d', '9s4d', '9h4d', '9d4d', '9c4d', '8s4d', '8h4d', '8d4d', '8c4d', '7s4d', '7h4d', '7d4d', '7c4d', '6s4d', '6h4d', '6d4d', '6c4d', '5s4d', '5h4d', '5d4d', '5c4d', '4d4c', 'As4c', 'Ah4c', 'Ad4c', 'Ac4c', 'Ks4c', 'Kh4c', 'Kd4c', 'Kc4c', 'Qs4c', 'Qh4c', 'Qd4c', 'Qc4c', 'Js4c', 'Jh4c', 'Jd4c', 'Jc4c', 'Ts4c', 'Th4c', 'Td4c', 'Tc4c', '9s4c', '9h4c', '9d4c', '9c4c', '8s4c', '8h4c', '8d4c', '8c4c', '7s4c', '7h4c', '7d4c', '7c4c', '6s4c', '6h4c', '6d4c', '6c4c', '5s4c', '5h4c', '5d4c', '5c4c', 'As3s', 'Ah3s', 'Ad3s', 'Ac3s', 'Ks3s', 'Kh3s', 'Kd3s', 'Kc3s', 'Qs3s', 'Qh3s', 'Qd3s', 'Qc3s', 'Js3s', 'Jh3s', 'Jd3s', 'Jc3s', 'Ts3s', 'Th3s', 'Td3s', 'Tc3s', '9s3s', '9h3s', '9d3s', '9c3s', '8s3s', '8h3s', '8d3s', '8c3s', '7s3s', '7h3s', '7d3s', '7c3s', '6s3s', '6h3s', '6d3s', '6c3s', '5s3s', '5h3s', '5d3s', '5c3s', '4s3s', '4h3s', '4d3s', '4c3s', '3s3h', '3s3d', '3s3c', 'As3h', 'Ah3h', 'Ad3h', 'Ac3h', 'Ks3h', 'Kh3h', 'Kd3h', 'Kc3h', 'Qs3h', 'Qh3h', 'Qd3h', 'Qc3h', 'Js3h', 'Jh3h', 'Jd3h', 'Jc3h', 'Ts3h', 'Th3h', 'Td3h', 'Tc3h', '9s3h', '9h3h', '9d3h', '9c3h', '8s3h', '8h3h', '8d3h', '8c3h', '7s3h', '7h3h', '7d3h', '7c3h', '6s3h', '6h3h', '6d3h', '6c3h', '5s3h', '5h3h', '5d3h', '5c3h', '4s3h', '4h3h', '4d3h', '4c3h', '3h3d', '3h3c', 'As3d', 'Ah3d', 'Ad3d', 'Ac3d', 'Ks3d', 'Kh3d', 'Kd3d', 'Kc3d', 'Qs3d', 'Qh3d', 'Qd3d', 'Qc3d', 'Js3d', 'Jh3d', 'Jd3d', 'Jc3d', 'Ts3d', 'Th3d', 'Td3d', 'Tc3d', '9s3d', '9h3d', '9d3d', '9c3d', '8s3d', '8h3d', '8d3d', '8c3d', '7s3d', '7h3d', '7d3d', '7c3d', '6s3d', '6h3d', '6d3d', '6c3d', '5s3d', '5h3d', '5d3d', '5c3d', '4s3d', '4h3d', '4d3d', '4c3d', '3c3d', 'As3c', 'Ah3c', 'Ad3c', 'Ac3c', 'Ks3c', 'Kh3c', 'Kd3c', 'Kc3c', 'Qs3c', 'Qh3c', 'Qd3c', 'Qc3c', 'Js3c', 'Jh3c', 'Jd3c', 'Jc3c', 'Ts3c', 'Th3c', 'Td3c', 'Tc3c', '9s3c', '9h3c', '9d3c', '9c3c', '8s3c', '8h3c', '8d3c', '8c3c', '7s3c', '7h3c', '7d3c', '7c3c', '6s3c', '6h3c', '6d3c', '6c3c', '5s3c', '5h3c', '5d3c', '5c3c', '4s3c', '4h3c', '4d3c', '4c3c', 'As2s', 'Ah2s', 'Ad2s', 'Ac2s', 'Ks2s', 'Kh2s', 'Kd2s', 'Kc2s', 'Qs2s', 'Qh2s', 'Qd2s', 'Qc2s', 'Js2s', 'Jh2s', 'Jd2s', 'Jc2s', 'Ts2s', 'Th2s', 'Td2s', 'Tc2s', '9s2s', '9h2s', '9d2s', '9c2s', '8s2s', '8h2s', '8d2s', '8c2s', '7s2s', '7h2s', '7d2s', '7c2s', '6s2s', '6h2s', '6d2s', '6c2s', '5s2s', '5h2s', '5d2s', '5c2s', '4s2s', '4h2s', '4d2s', '4c2s', '3s2s', '3h2s', '3d2s', '3c2s', '2s2h', '2s2d', '2s2c', 'As2h', 'Ah2h', 'Ad2h', 'Ac2h', 'Ks2h', 'Kh2h', 'Kd2h', 'Kc2h', 'Qs2h', 'Qh2h', 'Qd2h', 'Qc2h', 'Js2h', 'Jh2h', 'Jd2h', 'Jc2h', 'Ts2h', 'Th2h', 'Td2h', 'Tc2h', '9s2h', '9h2h', '9d2h', '9c2h', '8s2h', '8h2h', '8d2h', '8c2h', '7s2h', '7h2h', '7d2h', '7c2h', '6s2h', '6h2h', '6d2h', '6c2h', '5s2h', '5h2h', '5d2h', '5c2h', '4s2h', '4h2h', '4d2h', '4c2h', '3s2h', '3h2h', '3d2h', '3c2h', '2d2h', '2c2h', 'As2d', 'Ah2d', 'Ad2d', 'Ac2d', 'Ks2d', 'Kh2d', 'Kd2d', 'Kc2d', 'Qs2d', 'Qh2d', 'Qd2d', 'Qc2d', 'Js2d', 'Jh2d', 'Jd2d', 'Jc2d', 'Ts2d', 'Th2d', 'Td2d', 'Tc2d', '9s2d', '9h2d', '9d2d', '9c2d', '8s2d', '8h2d', '8d2d', '8c2d', '7s2d', '7h2d', '7d2d', '7c2d', '6s2d', '6h2d', '6d2d', '6c2d', '5s2d', '5h2d', '5d2d', '5c2d', '4s2d', '4h2d', '4d2d', '4c2d', '3s2d', '3h2d', '3d2d', '3c2d', '2c2d', 'As2c', 'Ah2c', 'Ad2c', 'Ac2c', 'Ks2c', 'Kh2c', 'Kd2c', 'Kc2c', 'Qs2c', 'Qh2c', 'Qd2c', 'Qc2c', 'Js2c', 'Jh2c', 'Jd2c', 'Jc2c', 'Ts2c', 'Th2c', 'Td2c', 'Tc2c', '9s2c', '9h2c', '9d2c', '9c2c', '8s2c', '8h2c', '8d2c', '8c2c', '7s2c', '7h2c', '7d2c', '7c2c', '6s2c', '6h2c', '6d2c', '6c2c', '5s2c', '5h2c', '5d2c', '5c2c', '4s2c', '4h2c', '4d2c', '4c2c', '3s2c', '3h2c', '3d2c', '3c2c']
```
```
QhQs 7s3d Tc3s KhQd Kh4c 8s6d Ts5s Tc4c Jd8c Ks3c Ah8c Jd5s QhTh Ad2c 9c5c 9d3d QcJc 6s3h Qc5s Ah7h 8d8s 7d4s 4c3c 6c6h 7s4h 9d8d Qs6s Ah9d AcTc 4c2d 9h3h Tc4h 8h3h Ts3d Ks5c 8d2s 7s2s 5c3c Kh2h KcTc Ad3c 7d2s AsKs 6c2c 5d4c AdKh 9d7c 3s2d KsTd Qc4c 6c6s AdKs 9s5c Ac2h 4d2c Ac6c Qh3d Qh4d 7h4s Ts6s 6h2s 6d4c Js2c Ks4c Jh2h 8s5c Kc8d 8h5d 9h5h AcQh JhTs 6d5c Qh9s Kh7s Jd8s Ad2h Ts2d Js8d Ts2c Js5d 9h6d KcJh Kh2c KdJd Tc3d Jh6d KdJs Kd9h 5h4s Jd2c QdTc KhQh 4d4h 7c2d Qh6s Ks6c Jc4h AdJh Ts3h Kd3d 3s2s AcQc 7s3c AcTs Th4d Qd5s Jh8s KdTd Tc5c 4c2h 8d2c 8d4c 9s2d 9h2d 9h6h 5c4h 9s2h 7s5c Tc5s 6d3c Ad8d Kc4h Td8c Th6d KdTh Ts5c Ks8s 4s3d 7c5h 7d6h 6h5d Td8d Kd8c JcTd 6s2c 7c4d AsTh Td3d Jc2d Kd9d 7c4h AdJd Td4s 5h5s Ac6d Ad4c Jh5h 9c4c As5h Th4h AcJh 5d2d KcQs 8s2d 7h6c 7c6d Ad8s 9h8c AhKd 9c4h 9c5d 4c3d Kd9s Kh2s AhJd Js2h Ts7s Th2h Qc4d 5h3d 6d4s 6d3h Ah5d 5c2d Jc8s 7c3c JdJs 4s3s Qs7h AhQh Qs9d Qh8h 8h7s 8s7s Kh2d 7c4s As3d 9s5s Qs6d 9h5c Qs6h Jd6h Qh7d Qs8s 9d4s Qc3h JcJh Kc4d QdTs Tc8d Qd5h Qs2s Jh4h 4d2h Kc6d 9h6c Qs9c Js4s Jd3d Tc9s KcQd 7d6c KcTd 8d5s Ad7s 4c3s AcKh 5s2h QdJc Js6h 4c2c 9h7c Ah5c KsJh Kh5c Qs4c KsJs Td3c 6s4c 8s6h 7c6c 7s2h Jd9h 5d2s Js6s 6s2s Kc7d Ac4d 8s7d Kc8c Jh2d Kd9c Td9h Qd4s Ad6s Qd3c Ac4s Th3d As5c QsTs KcJd 5h3h 8d7s 6h6s Qc9c AhJc Ks3s 6d6s 5s3h Kd6c Th3s Qh8s Qc6s AdAc Jc6c As8s QcQs 8c5h As7h Ac6s Th8c 3h2c Tc6d Jc9s 8d5h Ah7c Ks8h AdAh Kd3h 4d3s 8c5d Kh5d Jd2s 7s3s 9d5c 9s3h 7d2d 3h3s 5s3s AdTh Tc9c As2d Tc9d 9s8s KhTc AhTc 2d2c 8c7s 8c7d KdQc 9d2s Qs8c 7h5s Jd3h Kc8s Qc9h 8c5s Td4h 3d3h JhTh As8h 7d4h Ad6h 9s3s AsJc Ad3s Ah6c 9s2c 8h6s 7s6h 5s4h As2h Tc3h As4d Qh2h 9h7d Jc8d Jh8c 2c2s 9d8c Ac2s Ts9d 3c3h AcKd Jh2c Ah3s As6s Tc9h Kc2h Td2h QsJd Kc6c Ac4h 7h2h JcTc 8s3d Ah6h KhJd Ah5s Kh3c Kd4d 9h7h 5s2c 8c6c Jh5d Qc8d 8d7d 8c3s Qd6h 5s2d 9s8d Tc2c 5c4d 6s4d Kd3c Kc6h Ac3d 4d2s 6h2d Jc6s 3c2s QcTc KhJc Ks6d Qs7c As3h 3d3c Kc9h Qh9h 8d2h Jd4c Qc2d Kc3h Qd8s Ts6d As8c Qh3s Kc8h Qs9h AhQc Ad6c Ts4c Js9d AsQh 8s3h 9c2c 9s6h 7c6s 6d3s Td4d Ah2c Kc5h Jd6s KdKs Qh9d 7s2c 3c2c 8s4s 5d2c Js7c KcQc Js5h 6s4s Ah4c Qd2s Ts3s Qd8h 9c2s 9d5d Td2d 7d6s 5d3h Qd6s 6c3c 8s4h Qc7c Td8h Qs2d 7h3h 9c7d AsQs 4h2s Kh7d AhAs 4d3h 4h4s 5c2h 8h3s Kc6s Js7s Ts6c QcJs QhJd Qc6c Kc7s JcTs 6c3d Ks5d AcQd 5d2h 7c2s Jc2s 7d7h KhTd Td5h As4h KcQh 7h7s Th5c As2c 6c5d Td9s Qc7s Qh2d 6c2d As2s 6d2c Th7d KdQh 9d8s 8h2s Qh5d Qs2h 9d4h Tc7d Th7c Th6s 7c5c 8h8s 8h2d 5h2d Ad4s 9c9s Ah4d Qd3h Kc4s Kd3s Ks5s Jh9d 8c6s Qc5c 5c5s 8c6h 9d4d 9c6d Ac9s Qd8d Td6c 6s5c 8h3d Qc8c 9s7d Jd7s AsTd 8c5c 8d8c Qh5h Qs3d 9h3c Ah8h Ks9h Kc7c 7h2s Th9s 8d6c Js3h 7s5s Ad8h Qd7s 3h2h Js6c Kd8s Qh4s 7c6h Kd7h Th7s Qh3h Th5d Kd8h JhTd Js4d AsJh AcKc 9s6s Ts4h Td3h 9c5s Js2d Qs3h Qh2s Td5d Kd8d Td9d 6h4d Jh9c Td7c Kd5s Jc4d 8d4h 7d7c Kd5d 6c4d Ad7d Kd5c Ks4s Ts2h 5d3c 9d2c Jd5c Jh3h 4c2s Qh6c AhKc 9h2h QcQh 5h2c Kc4c Ad6d Jh7c Js7h 9c2h 3s2h 8c8s 8s7c Qc5h QsJc 7s6s 5s2s Td7h 8h5c AcJd Kd5h KdKc 7h5d 7d4d 8s5d 8c2h Jd7c KsQs 7c3h 6c5s 9c7c Qs4d Js8h 9d3h 9c3h 5h2h AhTd Qc7h AdJs As3c Kd2h 7h4d 7h3s 6h3d 5d4d Qc6d 9d8h Js4c 7d6d Ac3h Qs7s JdTh 9s4d 9c4d Ac4c 4h2h 3h2s 5d4s 9h7s Ks7c Kh9d Ks2d Kh6h 4c4s 8c2c Ad5d Qh3c 8h2h 8s4d Jh9h Qc2h 6c2s Jh5c 9h4d Ac9d Kh6s Qd3s 7c2h Ad8c AsTc Kh8s 6c4h Qd6c 3d3s ThTs Jh9s Qs3c Th4c Qh2c 9h9s 4d3c 8s2h 7s4d Td7s Qc4h Jd2h Ks7d Jd4s Jc5d Qc2c Ts2s 8d3s Qd7c KcKh 9s7c 4h3s 3d2h 6c5h 6d5h Kh4h Ac9h AcTh Kd2c JsTc 8d6s Kh7c Qd8c 7d3c 6d4h Ts4s Qh4h Tc8c 7s4c Ad2d Kh9s Th9c Kh3h AhQs 6h4s Kc2s 8s6c 5c3s As9c Th6h AdKc Qh7h Jd4d KhTs AsKh 7h6d Js5s 4s2c 5d5c Jd3s Jc3h Td9c KsJd QdQh 5h4c Jd5h Ah3c Ac7s 7s6d 6c4s Th2d Jh4s 7h6s Jd3c Kc5s 5c2s 9s8h Ah8d QhTd 8c2d 6h2c Ac2d 5c3h 9c6s 9h4s Kc3s 6c3s 9d6s Kc2c 6s4h As4c 7h4h 9h5d 9d9c Kh7h Ah4s 9d2h 7c4c As9s 6d4d Jh6c Js8s 6h5c Jd6d Tc2h Td6d 7d4c AdKd Ad9s Ah3h Qd7d Kh9h Jc9c Jc8h 4s2s 5h4d QsTh 8d5d Qd9s Js3s Tc2d Jc7c Qh5s Qd4h TdTc 9c8d KsTh 3d2d AhTs 7d7s 7c7h Kc2d Th2s Qd2h Td4c 5s4d 8h4c Qc6h Tc7c 9d6c 8s3c KsTs 6d2d Ts8h 5h3c QsJs 3h2d Kh8h 7h6h Jc4c 8c6d Ad9h 9h5s 9h6s AcTd 9c6c AhKh 8d8h Js8c 4h2d 9c4s Kc3d 8c8h As5d Jh4c 2c2h Qc4s 8d4s KhQc 8d3d As4s Jc3c AdQs Ah6s 9d6h 8d4d AdQd JsTh Kc5d Ad5c KsTc Qd3d QcTs Kd4h 8d3h 8d2d KhQs 3c2h 3c3s JdJh Ac6h 4s2h Jc4s Kd7d AdQh AsJs Th7h QcJh Qc3d AdTc Jd2d Qd4c 9s4s Qs5h Qh9c Ah8s Jh3c 9h4h Ks4h 5c4c AhKs QsJh Kc5c 9c3c 9d5s KcTs Ac5s 5c5h 5s3d Ks8c Qs7d Kh8d Td3s 4s3h Qh6h JcJs Jd6c QsTd Qc3s Qd7h 9h4c Qd5c 6c2h 7h5h AcJs 8d7c 6c5c Js2s Qh4c Qc9s 9s7h 4d3d 7h3d AsQd Ks9d 5s4c Td6h Kh4d QcJd Jc5c Ac5c 3c2d Ac8s Th9h Jd9d Jh5s 5h4h 7c7s Th2c JcTh Th3c AhQd Ac2c Jd9c AcAs 9h8s KsQh Jh4d 7d3d Qs8h QhTc Th5s 9d2d 6h5s 8h6h 8c3c Th6c Jc2h Jc9d Kh3d 7s6c Ac8d Jd8d Ts5d 7s3h Kd2s 9d6d 8s2s Ks2c Jh8h Ac7h AdQc 5s4s AsKd JdTs Qh5c Qc7d Qh7c Ah4h QdQs 6s2d Qc3c Jc8c Kh5h QsTc QhJs 9s6c AcAh 7h3c 8c7h Qc5d 8h6d 7c3d 8c3h Jd7h Ts8d Ah7d 4h3h Jc3d As9h 5h3s 8c2s 5c3d 7c5d Jh7s Ts8c AhTh 7h5c 9c5h Qh6d 7h2d 8h6c Tc8h QdJh AdAs Js3d 6h4c Qd2c Ad9d Tc4s Qd5d 9c2d TcTs TcTh Qs9s 7h2c 5d3s Ks6h AdTs Ah2h 5c2c Tc3c Jh7d Ad9c AcQs 6s3s 6d5d Tc7s KdQs 9s6d Ks9s KcJs JdTc 9d7h KhTh Kd7s Tc8s Js6d 7s2d 6d2h 9s4c As6d Jc7d KcKs 6d6c 8h7c Td5s Ks3h Js3c 6h5h 6s5h Jd4h 8c3d 6d2s Kd6h 9s8c 7c5s Td7d Th8s 9c9h As6c QdJs QcTd JhJs Kh9c Qs5d 9c3s Qh8c 9d5h Th9d 9s5d Jc6d Jh7h AsKc As6h 6d3d 9d7d KdTc JdTd 6s3c Tc6c KsQd Js9h Ts9s Qc8h Kh6d 9d7s Jh3d Jc9h 8h4h JdJc Qs2c 3s2c 2d2s 8s6s Ks6s Jd8h Ts6h Jc5s 7d5d Qs4s 8s5s Kd2d 4c4h Ks2s KsQc Js4h 2d2h Ks3d 4d4s Tc6h 9d9h Ac8c 5s3c Qs5s Ks5h Qh8d 6h3c Kd4s 8h5s Ah9s Tc6s 6s2h 9s7s 9s3d 4h3d 9h8d 3d2s Th8d As9d QdTd Qc9d Jd7d KhKs 8s7h 8s2c 9d3c Ts9c 2h2s Ad4h Ad5h Tc5h As7d As7c 5d5h Kc9c As5s 9s2s Qc2s Jc3s 9c3d 5h2s 6h4h 5d4h 6c3h 9d3s Kd7c 8h4d Ac3s 4c3h Ts7d 8c4d Ks8d Td8s Th3h Ah9c Qs6c 8h3c 4s2d 5d5s KcJc 8h5h Jc7h KdJc Qs8d 8d5c Jc7s 8d7h 8c4c 6c4c 9s3c 7d3h Ac7d Td6s Kc3c Tc2s Ah3d KdJh Qd4d 9h2s Ts3c 7d2c 8h7d Tc4d 8h2c Ah7s 8d6h Ac9c Jh3s 3d2c Jh2s TdTh 9c7s 5c4s Ad4d QhTs 9c7h Kc9d Kd6d Kh5s 8c7c 6s5s Ah6d 8d6d Ks7s Ac7c AdTd Ah9h Kc9s QhJh Ks4d As3s KsJc Jd5d 7d5s TdTs Ah2s 9h3s Th4s AsQc Ad3h Ks7h KhJs 8s4c 7s4s JhTc AsJd 6h3h Tc7h Ad7h 7c3s 8s3s 7d3s 8h4s Js9c Qd9d JsTs AhJh Jh6s 9s5h Jd9s 6h2h As7s QcTh 7s5h Kd4c 6s5d 9c8h Qd9c Js5c KhJh KdQd Qs4h Ad2s Ah2d QdQc QdTh 8s5h Js7d Tc5d 4h2c Ac3c AcJc Ad7c 7d5h 7h4c AcKs Jc5h Qd9h KdTs Kh3s Ad3d 4d4c 9h3d Ts8s 6h3s 7d2h 4d2d 6d5s KdKh 7s5d 6d6h 9d9s 9h2c Kh8c 5d3d As8d Ts9h Td2s Ks2h 9h8h 6s3d 9c8s Qs3s Th5h Jh6h AsTs Ad5s Kh4s 8c4h Qd6d Ts7c Kc7h KcTh Qs5c 4h3c QhJc 7d5c Ac5d 8c4s Th8h Jh8d 9d4c Qd2d Ac8h Kh6c QdJd JsTd Jc2c Ks9c Jc6h 9c8c Ts5h AhJs Ts4d 9s4h AdJc Js9s 4s3c Kd6s Ac5h 8h7h Td2c 7c2c Qc8s Ts7h 9c6h Td5c Ah5h 8d3c Qh7s
```
```
3c2c, 3d2c, 3h2c, 3s2c, 4c2c, 4d2c, 4h2c, 4s2c, 5c2c, 5d2c, 5h2c, 5s2c, 6c2c, 6d2c, 6h2c, 6s2c, 7c2c, 7d2c, 7h2c, 7s2c, 8c2c, 8d2c, 8h2c, 8s2c, 9c2c, 9d2c, 9h2c, 9s2c, Tc2c, Td2c, Th2c, Ts2c, Jc2c, Jd2c, Jh2c, Js2c, Qc2c, Qd2c, Qh2c, Qs2c, Kc2c, Kd2c, Kh2c, Ks2c, Ac2c, Ad2c, Ah2c, As2c, 2c2d, 3c2d, 3d2d, 3h2d, 3s2d, 4c2d, 4d2d, 4h2d, 4s2d, 5c2d, 5d2d, 5h2d, 5s2d, 6c2d, 6d2d, 6h2d, 6s2d, 7c2d, 7d2d, 7h2d, 7s2d, 8c2d, 8d2d, 8h2d, 8s2d, 9c2d, 9d2d, 9h2d, 9s2d, Tc2d, Td2d, Th2d, Ts2d, Jc2d, Jd2d, Jh2d, Js2d, Qc2d, Qd2d, Qh2d, Qs2d, Kc2d, Kd2d, Kh2d, Ks2d, Ac2d, Ad2d, Ah2d, As2d, 2c2h, 2d2h, 3c2h, 3d2h, 3h2h, 3s2h, 4c2h, 4d2h, 4h2h, 4s2h, 5c2h, 5d2h, 5h2h, 5s2h, 6c2h, 6d2h, 6h2h, 6s2h, 7c2h, 7d2h, 7h2h, 7s2h, 8c2h, 8d2h, 8h2h, 8s2h, 9c2h, 9d2h, 9h2h, 9s2h, Tc2h, Td2h, Th2h, Ts2h, Jc2h, Jd2h, Jh2h, Js2h, Qc2h, Qd2h, Qh2h, Qs2h, Kc2h, Kd2h, Kh2h, Ks2h, Ac2h, Ad2h, Ah2h, As2h, 2c2s, 2d2s, 2h2s, 3c2s, 3d2s, 3h2s, 3s2s, 4c2s, 4d2s, 4h2s, 4s2s, 5c2s, 5d2s, 5h2s, 5s2s, 6c2s, 6d2s, 6h2s, 6s2s, 7c2s, 7d2s, 7h2s, 7s2s, 8c2s, 8d2s, 8h2s, 8s2s, 9c2s, 9d2s, 9h2s, 9s2s, Tc2s, Td2s, Th2s, Ts2s, Jc2s, Jd2s, Jh2s, Js2s, Qc2s, Qd2s, Qh2s, Qs2s, Kc2s, Kd2s, Kh2s, Ks2s, Ac2s, Ad2s, Ah2s, As2s, 4c3c, 4d3c, 4h3c, 4s3c, 5c3c, 5d3c, 5h3c, 5s3c, 6c3c, 6d3c, 6h3c, 6s3c, 7c3c, 7d3c, 7h3c, 7s3c, 8c3c, 8d3c, 8h3c, 8s3c, 9c3c, 9d3c, 9h3c, 9s3c, Tc3c, Td3c, Th3c, Ts3c, Jc3c, Jd3c, Jh3c, Js3c, Qc3c, Qd3c, Qh3c, Qs3c, Kc3c, Kd3c, Kh3c, Ks3c, Ac3c, Ad3c, Ah3c, As3c, 3c3d, 4c3d, 4d3d, 4h3d, 4s3d, 5c3d, 5d3d, 5h3d, 5s3d, 6c3d, 6d3d, 6h3d, 6s3d, 7c3d, 7d3d, 7h3d, 7s3d, 8c3d, 8d3d, 8h3d, 8s3d, 9c3d, 9d3d, 9h3d, 9s3d, Tc3d, Td3d, Th3d, Ts3d, Jc3d, Jd3d, Jh3d, Js3d, Qc3d, Qd3d, Qh3d, Qs3d, Kc3d, Kd3d, Kh3d, Ks3d, Ac3d, Ad3d, Ah3d, As3d, 3c3h, 3d3h, 4c3h, 4d3h, 4h3h, 4s3h, 5c3h, 5d3h, 5h3h, 5s3h, 6c3h, 6d3h, 6h3h, 6s3h, 7c3h, 7d3h, 7h3h, 7s3h, 8c3h, 8d3h, 8h3h, 8s3h, 9c3h, 9d3h, 9h3h, 9s3h, Tc3h, Td3h, Th3h, Ts3h, Jc3h, Jd3h, Jh3h, Js3h, Qc3h, Qd3h, Qh3h, Qs3h, Kc3h, Kd3h, Kh3h, Ks3h, Ac3h, Ad3h, Ah3h, As3h, 3c3s, 3d3s, 3h3s, 4c3s, 4d3s, 4h3s, 4s3s, 5c3s, 5d3s, 5h3s, 5s3s, 6c3s, 6d3s, 6h3s, 6s3s, 7c3s, 7d3s, 7h3s, 7s3s, 8c3s, 8d3s, 8h3s, 8s3s, 9c3s, 9d3s, 9h3s, 9s3s, Tc3s, Td3s, Th3s, Ts3s, Jc3s, Jd3s, Jh3s, Js3s, Qc3s, Qd3s, Qh3s, Qs3s, Kc3s, Kd3s, Kh3s, Ks3s, Ac3s, Ad3s, Ah3s, As3s, 5c4c, 5d4c, 5h4c, 5s4c, 6c4c, 6d4c, 6h4c, 6s4c, 7c4c, 7d4c, 7h4c, 7s4c, 8c4c, 8d4c, 8h4c, 8s4c, 9c4c, 9d4c, 9h4c, 9s4c, Tc4c, Td4c, Th4c, Ts4c, Jc4c, Jd4c, Jh4c, Js4c, Qc4c, Qd4c, Qh4c, Qs4c, Kc4c, Kd4c, Kh4c, Ks4c, Ac4c, Ad4c, Ah4c, As4c, 4c4d, 5c4d, 5d4d, 5h4d, 5s4d, 6c4d, 6d4d, 6h4d, 6s4d, 7c4d, 7d4d, 7h4d, 7s4d, 8c4d, 8d4d, 8h4d, 8s4d, 9c4d, 9d4d, 9h4d, 9s4d, Tc4d, Td4d, Th4d, Ts4d, Jc4d, Jd4d, Jh4d, Js4d, Qc4d, Qd4d, Qh4d, Qs4d, Kc4d, Kd4d, Kh4d, Ks4d, Ac4d, Ad4d, Ah4d, As4d, 4c4h, 4d4h, 5c4h, 5d4h, 5h4h, 5s4h, 6c4h, 6d4h, 6h4h, 6s4h, 7c4h, 7d4h, 7h4h, 7s4h, 8c4h, 8d4h, 8h4h, 8s4h, 9c4h, 9d4h, 9h4h, 9s4h, Tc4h, Td4h, Th4h, Ts4h, Jc4h, Jd4h, Jh4h, Js4h, Qc4h, Qd4h, Qh4h, Qs4h, Kc4h, Kd4h, Kh4h, Ks4h, Ac4h, Ad4h, Ah4h, As4h, 4c4s, 4d4s, 4h4s, 5c4s, 5d4s, 5h4s, 5s4s, 6c4s, 6d4s, 6h4s, 6s4s, 7c4s, 7d4s, 7h4s, 7s4s, 8c4s, 8d4s, 8h4s, 8s4s, 9c4s, 9d4s, 9h4s, 9s4s, Tc4s, Td4s, Th4s, Ts4s, Jc4s, Jd4s, Jh4s, Js4s, Qc4s, Qd4s, Qh4s, Qs4s, Kc4s, Kd4s, Kh4s, Ks4s, Ac4s, Ad4s, Ah4s, As4s, 6c5c, 6d5c, 6h5c, 6s5c, 7c5c, 7d5c, 7h5c, 7s5c, 8c5c, 8d5c, 8h5c, 8s5c, 9c5c, 9d5c, 9h5c, 9s5c, Tc5c, Td5c, Th5c, Ts5c, Jc5c, Jd5c, Jh5c, Js5c, Qc5c, Qd5c, Qh5c, Qs5c, Kc5c, Kd5c, Kh5c, Ks5c, Ac5c, Ad5c, Ah5c, As5c, 5c5d, 6c5d, 6d5d, 6h5d, 6s5d, 7c5d, 7d5d, 7h5d, 7s5d, 8c5d, 8d5d, 8h5d, 8s5d, 9c5d, 9d5d, 9h5d, 9s5d, Tc5d, Td5d, Th5d, Ts5d, Jc5d, Jd5d, Jh5d, Js5d, Qc5d, Qd5d, Qh5d, Qs5d, Kc5d, Kd5d, Kh5d, Ks5d, Ac5d, Ad5d, Ah5d, As5d, 5c5h, 5d5h, 6c5h, 6d5h, 6h5h, 6s5h, 7c5h, 7d5h, 7h5h, 7s5h, 8c5h, 8d5h, 8h5h, 8s5h, 9c5h, 9d5h, 9h5h, 9s5h, Tc5h, Td5h, Th5h, Ts5h, Jc5h, Jd5h, Jh5h, Js5h, Qc5h, Qd5h, Qh5h, Qs5h, Kc5h, Kd5h, Kh5h, Ks5h, Ac5h, Ad5h, Ah5h, As5h, 5c5s, 5d5s, 5h5s, 6c5s, 6d5s, 6h5s, 6s5s, 7c5s, 7d5s, 7h5s, 7s5s, 8c5s, 8d5s, 8h5s, 8s5s, 9c5s, 9d5s, 9h5s, 9s5s, Tc5s, Td5s, Th5s, Ts5s, Jc5s, Jd5s, Jh5s, Js5s, Qc5s, Qd5s, Qh5s, Qs5s, Kc5s, Kd5s, Kh5s, Ks5s, Ac5s, Ad5s, Ah5s, As5s, 7c6c, 7d6c, 7h6c, 7s6c, 8c6c, 8d6c, 8h6c, 8s6c, 9c6c, 9d6c, 9h6c, 9s6c, Tc6c, Td6c, Th6c, Ts6c, Jc6c, Jd6c, Jh6c, Js6c, Qc6c, Qd6c, Qh6c, Qs6c, Kc6c, Kd6c, Kh6c, Ks6c, Ac6c, Ad6c, Ah6c, As6c, 6c6d, 7c6d, 7d6d, 7h6d, 7s6d, 8c6d, 8d6d, 8h6d, 8s6d, 9c6d, 9d6d, 9h6d, 9s6d, Tc6d, Td6d, Th6d, Ts6d, Jc6d, Jd6d, Jh6d, Js6d, Qc6d, Qd6d, Qh6d, Qs6d, Kc6d, Kd6d, Kh6d, Ks6d, Ac6d, Ad6d, Ah6d, As6d, 6c6h, 6d6h, 7c6h, 7d6h, 7h6h, 7s6h, 8c6h, 8d6h, 8h6h, 8s6h, 9c6h, 9d6h, 9h6h, 9s6h, Tc6h, Td6h, Th6h, Ts6h, Jc6h, Jd6h, Jh6h, Js6h, Qc6h, Qd6h, Qh6h, Qs6h, Kc6h, Kd6h, Kh6h, Ks6h, Ac6h, Ad6h, Ah6h, As6h, 6c6s, 6d6s, 6h6s, 7c6s, 7d6s, 7h6s, 7s6s, 8c6s, 8d6s, 8h6s, 8s6s, 9c6s, 9d6s, 9h6s, 9s6s, Tc6s, Td6s, Th6s, Ts6s, Jc6s, Jd6s, Jh6s, Js6s, Qc6s, Qd6s, Qh6s, Qs6s, Kc6s, Kd6s, Kh6s, Ks6s, Ac6s, Ad6s, Ah6s, As6s, 8c7c, 8d7c, 8h7c, 8s7c, 9c7c, 9d7c, 9h7c, 9s7c, Tc7c, Td7c, Th7c, Ts7c, Jc7c, Jd7c, Jh7c, Js7c, Qc7c, Qd7c, Qh7c, Qs7c, Kc7c, Kd7c, Kh7c, Ks7c, Ac7c, Ad7c, Ah7c, As7c, 7c7d, 8c7d, 8d7d, 8h7d, 8s7d, 9c7d, 9d7d, 9h7d, 9s7d, Tc7d, Td7d, Th7d, Ts7d, Jc7d, Jd7d, Jh7d, Js7d, Qc7d, Qd7d, Qh7d, Qs7d, Kc7d, Kd7d, Kh7d, Ks7d, Ac7d, Ad7d, Ah7d, As7d, 7c7h, 7d7h, 8c7h, 8d7h, 8h7h, 8s7h, 9c7h, 9d7h, 9h7h, 9s7h, Tc7h, Td7h, Th7h, Ts7h, Jc7h, Jd7h, Jh7h, Js7h, Qc7h, Qd7h, Qh7h, Qs7h, Kc7h, Kd7h, Kh7h, Ks7h, Ac7h, Ad7h, Ah7h, As7h, 7c7s, 7d7s, 7h7s, 8c7s, 8d7s, 8h7s, 8s7s, 9c7s, 9d7s, 9h7s, 9s7s, Tc7s, Td7s, Th7s, Ts7s, Jc7s, Jd7s, Jh7s, Js7s, Qc7s, Qd7s, Qh7s, Qs7s, Kc7s, Kd7s, Kh7s, Ks7s, Ac7s, Ad7s, Ah7s, As7s, 9c8c, 9d8c, 9h8c, 9s8c, Tc8c, Td8c, Th8c, Ts8c, Jc8c, Jd8c, Jh8c, Js8c, Qc8c, Qd8c, Qh8c, Qs8c, Kc8c, Kd8c, Kh8c, Ks8c, Ac8c, Ad8c, Ah8c, As8c, 8c8d, 9c8d, 9d8d, 9h8d, 9s8d, Tc8d, Td8d, Th8d, Ts8d, Jc8d, Jd8d, Jh8d, Js8d, Qc8d, Qd8d, Qh8d, Qs8d, Kc8d, Kd8d, Kh8d, Ks8d, Ac8d, Ad8d, Ah8d, As8d, 8c8h, 8d8h, 9c8h, 9d8h, 9h8h, 9s8h, Tc8h, Td8h, Th8h, Ts8h, Jc8h, Jd8h, Jh8h, Js8h, Qc8h, Qd8h, Qh8h, Qs8h, Kc8h, Kd8h, Kh8h, Ks8h, Ac8h, Ad8h, Ah8h, As8h, 8c8s, 8d8s, 8h8s, 9c8s, 9d8s, 9h8s, 9s8s, Tc8s, Td8s, Th8s, Ts8s, Jc8s, Jd8s, Jh8s, Js8s, Qc8s, Qd8s, Qh8s, Qs8s, Kc8s, Kd8s, Kh8s, Ks8s, Ac8s, Ad8s, Ah8s, As8s, Tc9c, Td9c, Th9c, Ts9c, Jc9c, Jd9c, Jh9c, Js9c, Qc9c, Qd9c, Qh9c, Qs9c, Kc9c, Kd9c, Kh9c, Ks9c, Ac9c, Ad9c, Ah9c, As9c, 9c9d, Tc9d, Td9d, Th9d, Ts9d, Jc9d, Jd9d, Jh9d, Js9d, Qc9d, Qd9d, Qh9d, Qs9d, Kc9d, Kd9d, Kh9d, Ks9d, Ac9d, Ad9d, Ah9d, As9d, 9c9h, 9d9h, Tc9h, Td9h, Th9h, Ts9h, Jc9h, Jd9h, Jh9h, Js9h, Qc9h, Qd9h, Qh9h, Qs9h, Kc9h, Kd9h, Kh9h, Ks9h, Ac9h, Ad9h, Ah9h, As9h, 9c9s, 9d9s, 9h9s, Tc9s, Td9s, Th9s, Ts9s, Jc9s, Jd9s, Jh9s, Js9s, Qc9s, Qd9s, Qh9s, Qs9s, Kc9s, Kd9s, Kh9s, Ks9s, Ac9s, Ad9s, Ah9s, As9s, JcTc, JdTc, JhTc, JsTc, QcTc, QdTc, QhTc, QsTc, KcTc, KdTc, KhTc, KsTc, AcTc, AdTc, AhTc, AsTc, TcTd, JcTd, JdTd, JhTd, JsTd, QcTd, QdTd, QhTd, QsTd, KcTd, KdTd, KhTd, KsTd, AcTd, AdTd, AhTd, AsTd, TcTh, TdTh, JcTh, JdTh, JhTh, JsTh, QcTh, QdTh, QhTh, QsTh, KcTh, KdTh, KhTh, KsTh, AcTh, AdTh, AhTh, AsTh, TcTs, TdTs, ThTs, JcTs, JdTs, JhTs, JsTs, QcTs, QdTs, QhTs, QsTs, KcTs, KdTs, KhTs, KsTs, AcTs, AdTs, AhTs, AsTs, QcJc, QdJc, QhJc, QsJc, KcJc, KdJc, KhJc, KsJc, AcJc, AdJc, AhJc, AsJc, JcJd, QcJd, QdJd, QhJd, QsJd, KcJd, KdJd, KhJd, KsJd, AcJd, AdJd, AhJd, AsJd, JcJh, JdJh, QcJh, QdJh, QhJh, QsJh, KcJh, KdJh, KhJh, KsJh, AcJh, AdJh, AhJh, AsJh, JcJs, JdJs, JhJs, QcJs, QdJs, QhJs, QsJs, KcJs, KdJs, KhJs, KsJs, AcJs, AdJs, AhJs, AsJs, KcQc, KdQc, KhQc, KsQc, AcQc, AdQc, AhQc, AsQc, QcQd, KcQd, KdQd, KhQd, KsQd, AcQd, AdQd, AhQd, AsQd, QcQh, QdQh, KcQh, KdQh, KhQh, KsQh, AcQh, AdQh, AhQh, AsQh, QcQs, QdQs, QhQs, KcQs, KdQs, KhQs, KsQs, AcQs, AdQs, AhQs, AsQs, AcKc, AdKc, AhKc, AsKc, KcKd, AcKd, AdKd, AhKd, AsKd, KcKh, KdKh, AcKh, AdKh, AhKh, AsKh, KcKs, KdKs, KhKs, AcKs, AdKs, AhKs, AsKs, AcAd, AcAh, AdAh, AcAs, AdAs, AhAs
```
To get things going, here is my embarrassingly easy to beat answer in python:
>
>
> ```
> acs = []
> ac = []
> rs = 'AKQJT98765432'
> for r in rs:
> for s in 'schd':
> ac.append(r+s)
> for c in ac:
> for i in ac:
> if (i != c) and (rs.index(i[0]) <= rs.index(c[0]) and (i+c not in acs) and (c+i not in acs)):
> acs.append(i+c)
> print(acs)
>
> ```
>
>
>
>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9Ḋ;“TJQKA”Ṛp“cdhs”ŒcK
```
A full program printing the combos\* separated by spaces (as a niladic link without the trailing `K` the result would be a list of combos, where each combo is a list of lists, with integers for 2-9 and characters for other parts).
**[Try it online!](https://tio.run/##y0rNyan8/9/y4Y4u60cNc0K8Ar0dHzXMfbhzVgGQm5ySUQzkHZ2U7P3/PwA "Jelly – Try It Online")** (Note: change the trailing `K` to `L` and it will display the length of the list, `1326`.)
### How?
```
9Ḋ;“TJQKA”Ṛp“cdhs”ŒcK - Main link: no arguments
9Ḋ - nine dequeued [2,3,4,5,6,7,8,9]
“TJQKA” - literal list of characters ['T','J','Q','K','A']
; - concatenate [2,3,4,5,6,7,8,9,'T','J','Q','K','A']
Ṛ - reverse ['A','K','Q','J','T',9,8,7,6,5,4,3,2]
“cdhs” - literal list of characters ['c','d','h','s']
p - Cartesian product [['A','c'],['A','d'], ... ,[2,'s']]
Œc - Unordered pairs [[['A','c'],['A','d']], ...(1326)...]
K - join with spaces (to pretty print, otherwise they all run
- together like AcAdAcAhAcAsAcKdAcKhAcKs...2d2h2d2s2h2s)
```
\* it's what the kids call 'em!
[Answer]
# Python 2, ~~100~~ 98 bytes
```
r=range
d=lambda i:'AKQJT98765432'[i/4]+'cdhs'[i%4]
for u in r(52):
for t in r(u):print d(t)+d(u)
```
-2 bytes from dylnan
[Try it online!](https://tio.run/##K6gsycjPM/r/P8U2JzE3KSVRIdNK3dE70CvE0sLczNTE2Eg9OlPfJFZbPTkjpRjIVjWJ5SqyLUrMS0/lSssvUihVyMxTKNIwNdK04lIACZRABEo1rQqKMvNKFFI0SjS1U4D8//8B "Python 2 – Try It Online")
`d` maps the numbers from 0 to 51 to card names such that they keep their sorting order (0-3 -> Aces, 4-7 -> Kings, etc)
The program loops over all pairs of numbers 0-51 where the second is greater than the first, and prints the pair of cards corresponding to that pair of numbers.
[Answer]
# Bash+sed, 90 bytes
```
printf %s\\n {{2..9},T,J,Q,K,A}{c,d,h,s}{{2..9},T,J,Q,K,A}{c,d,h,s}|sed '/\(..\)\1/,/As/d'
```
The Bash brace-expansion generates the cross-join of all pairs in ascending order (using the Bridge ordering of the suits). The Sed command removes the unwanted pairs: for each leading card C, we eliminate the same-card pair (C C) and all subsequent pairs (i.e. all trailing cards higher than C) until we see and remove the Ace of Spades (C As). After that, there's new leading card and we repeat until we finally remove AsAs and the input ends.
# Output
Piped through `rs 0 26` to make it fit better:
```
2d2c 2h2c 2h2d 2s2c 2s2d 2s2h 3c2c 3c2d 3c2h 3c2s 3d2c 3d2d 3d2h 3d2s 3d3c 3h2c 3h2d 3h2h 3h2s 3h3c 3h3d 3s2c 3s2d 3s2h 3s2s 3s3c
3s3d 3s3h 4c2c 4c2d 4c2h 4c2s 4c3c 4c3d 4c3h 4c3s 4d2c 4d2d 4d2h 4d2s 4d3c 4d3d 4d3h 4d3s 4d4c 4h2c 4h2d 4h2h 4h2s 4h3c 4h3d 4h3h
4h3s 4h4c 4h4d 4s2c 4s2d 4s2h 4s2s 4s3c 4s3d 4s3h 4s3s 4s4c 4s4d 4s4h 5c2c 5c2d 5c2h 5c2s 5c3c 5c3d 5c3h 5c3s 5c4c 5c4d 5c4h 5c4s
5d2c 5d2d 5d2h 5d2s 5d3c 5d3d 5d3h 5d3s 5d4c 5d4d 5d4h 5d4s 5d5c 5h2c 5h2d 5h2h 5h2s 5h3c 5h3d 5h3h 5h3s 5h4c 5h4d 5h4h 5h4s 5h5c
5h5d 5s2c 5s2d 5s2h 5s2s 5s3c 5s3d 5s3h 5s3s 5s4c 5s4d 5s4h 5s4s 5s5c 5s5d 5s5h 6c2c 6c2d 6c2h 6c2s 6c3c 6c3d 6c3h 6c3s 6c4c 6c4d
6c4h 6c4s 6c5c 6c5d 6c5h 6c5s 6d2c 6d2d 6d2h 6d2s 6d3c 6d3d 6d3h 6d3s 6d4c 6d4d 6d4h 6d4s 6d5c 6d5d 6d5h 6d5s 6d6c 6h2c 6h2d 6h2h
6h2s 6h3c 6h3d 6h3h 6h3s 6h4c 6h4d 6h4h 6h4s 6h5c 6h5d 6h5h 6h5s 6h6c 6h6d 6s2c 6s2d 6s2h 6s2s 6s3c 6s3d 6s3h 6s3s 6s4c 6s4d 6s4h
6s4s 6s5c 6s5d 6s5h 6s5s 6s6c 6s6d 6s6h 7c2c 7c2d 7c2h 7c2s 7c3c 7c3d 7c3h 7c3s 7c4c 7c4d 7c4h 7c4s 7c5c 7c5d 7c5h 7c5s 7c6c 7c6d
7c6h 7c6s 7d2c 7d2d 7d2h 7d2s 7d3c 7d3d 7d3h 7d3s 7d4c 7d4d 7d4h 7d4s 7d5c 7d5d 7d5h 7d5s 7d6c 7d6d 7d6h 7d6s 7d7c 7h2c 7h2d 7h2h
7h2s 7h3c 7h3d 7h3h 7h3s 7h4c 7h4d 7h4h 7h4s 7h5c 7h5d 7h5h 7h5s 7h6c 7h6d 7h6h 7h6s 7h7c 7h7d 7s2c 7s2d 7s2h 7s2s 7s3c 7s3d 7s3h
7s3s 7s4c 7s4d 7s4h 7s4s 7s5c 7s5d 7s5h 7s5s 7s6c 7s6d 7s6h 7s6s 7s7c 7s7d 7s7h 8c2c 8c2d 8c2h 8c2s 8c3c 8c3d 8c3h 8c3s 8c4c 8c4d
8c4h 8c4s 8c5c 8c5d 8c5h 8c5s 8c6c 8c6d 8c6h 8c6s 8c7c 8c7d 8c7h 8c7s 8d2c 8d2d 8d2h 8d2s 8d3c 8d3d 8d3h 8d3s 8d4c 8d4d 8d4h 8d4s
8d5c 8d5d 8d5h 8d5s 8d6c 8d6d 8d6h 8d6s 8d7c 8d7d 8d7h 8d7s 8d8c 8h2c 8h2d 8h2h 8h2s 8h3c 8h3d 8h3h 8h3s 8h4c 8h4d 8h4h 8h4s 8h5c
8h5d 8h5h 8h5s 8h6c 8h6d 8h6h 8h6s 8h7c 8h7d 8h7h 8h7s 8h8c 8h8d 8s2c 8s2d 8s2h 8s2s 8s3c 8s3d 8s3h 8s3s 8s4c 8s4d 8s4h 8s4s 8s5c
8s5d 8s5h 8s5s 8s6c 8s6d 8s6h 8s6s 8s7c 8s7d 8s7h 8s7s 8s8c 8s8d 8s8h 9c2c 9c2d 9c2h 9c2s 9c3c 9c3d 9c3h 9c3s 9c4c 9c4d 9c4h 9c4s
9c5c 9c5d 9c5h 9c5s 9c6c 9c6d 9c6h 9c6s 9c7c 9c7d 9c7h 9c7s 9c8c 9c8d 9c8h 9c8s 9d2c 9d2d 9d2h 9d2s 9d3c 9d3d 9d3h 9d3s 9d4c 9d4d
9d4h 9d4s 9d5c 9d5d 9d5h 9d5s 9d6c 9d6d 9d6h 9d6s 9d7c 9d7d 9d7h 9d7s 9d8c 9d8d 9d8h 9d8s 9d9c 9h2c 9h2d 9h2h 9h2s 9h3c 9h3d 9h3h
9h3s 9h4c 9h4d 9h4h 9h4s 9h5c 9h5d 9h5h 9h5s 9h6c 9h6d 9h6h 9h6s 9h7c 9h7d 9h7h 9h7s 9h8c 9h8d 9h8h 9h8s 9h9c 9h9d 9s2c 9s2d 9s2h
9s2s 9s3c 9s3d 9s3h 9s3s 9s4c 9s4d 9s4h 9s4s 9s5c 9s5d 9s5h 9s5s 9s6c 9s6d 9s6h 9s6s 9s7c 9s7d 9s7h 9s7s 9s8c 9s8d 9s8h 9s8s 9s9c
9s9d 9s9h Tc2c Tc2d Tc2h Tc2s Tc3c Tc3d Tc3h Tc3s Tc4c Tc4d Tc4h Tc4s Tc5c Tc5d Tc5h Tc5s Tc6c Tc6d Tc6h Tc6s Tc7c Tc7d Tc7h Tc7s
Tc8c Tc8d Tc8h Tc8s Tc9c Tc9d Tc9h Tc9s Td2c Td2d Td2h Td2s Td3c Td3d Td3h Td3s Td4c Td4d Td4h Td4s Td5c Td5d Td5h Td5s Td6c Td6d
Td6h Td6s Td7c Td7d Td7h Td7s Td8c Td8d Td8h Td8s Td9c Td9d Td9h Td9s TdTc Th2c Th2d Th2h Th2s Th3c Th3d Th3h Th3s Th4c Th4d Th4h
Th4s Th5c Th5d Th5h Th5s Th6c Th6d Th6h Th6s Th7c Th7d Th7h Th7s Th8c Th8d Th8h Th8s Th9c Th9d Th9h Th9s ThTc ThTd Ts2c Ts2d Ts2h
Ts2s Ts3c Ts3d Ts3h Ts3s Ts4c Ts4d Ts4h Ts4s Ts5c Ts5d Ts5h Ts5s Ts6c Ts6d Ts6h Ts6s Ts7c Ts7d Ts7h Ts7s Ts8c Ts8d Ts8h Ts8s Ts9c
Ts9d Ts9h Ts9s TsTc TsTd TsTh Jc2c Jc2d Jc2h Jc2s Jc3c Jc3d Jc3h Jc3s Jc4c Jc4d Jc4h Jc4s Jc5c Jc5d Jc5h Jc5s Jc6c Jc6d Jc6h Jc6s
Jc7c Jc7d Jc7h Jc7s Jc8c Jc8d Jc8h Jc8s Jc9c Jc9d Jc9h Jc9s JcTc JcTd JcTh JcTs Jd2c Jd2d Jd2h Jd2s Jd3c Jd3d Jd3h Jd3s Jd4c Jd4d
Jd4h Jd4s Jd5c Jd5d Jd5h Jd5s Jd6c Jd6d Jd6h Jd6s Jd7c Jd7d Jd7h Jd7s Jd8c Jd8d Jd8h Jd8s Jd9c Jd9d Jd9h Jd9s JdTc JdTd JdTh JdTs
JdJc Jh2c Jh2d Jh2h Jh2s Jh3c Jh3d Jh3h Jh3s Jh4c Jh4d Jh4h Jh4s Jh5c Jh5d Jh5h Jh5s Jh6c Jh6d Jh6h Jh6s Jh7c Jh7d Jh7h Jh7s Jh8c
Jh8d Jh8h Jh8s Jh9c Jh9d Jh9h Jh9s JhTc JhTd JhTh JhTs JhJc JhJd Js2c Js2d Js2h Js2s Js3c Js3d Js3h Js3s Js4c Js4d Js4h Js4s Js5c
Js5d Js5h Js5s Js6c Js6d Js6h Js6s Js7c Js7d Js7h Js7s Js8c Js8d Js8h Js8s Js9c Js9d Js9h Js9s JsTc JsTd JsTh JsTs JsJc JsJd JsJh
Qc2c Qc2d Qc2h Qc2s Qc3c Qc3d Qc3h Qc3s Qc4c Qc4d Qc4h Qc4s Qc5c Qc5d Qc5h Qc5s Qc6c Qc6d Qc6h Qc6s Qc7c Qc7d Qc7h Qc7s Qc8c Qc8d
Qc8h Qc8s Qc9c Qc9d Qc9h Qc9s QcTc QcTd QcTh QcTs QcJc QcJd QcJh QcJs Qd2c Qd2d Qd2h Qd2s Qd3c Qd3d Qd3h Qd3s Qd4c Qd4d Qd4h Qd4s
Qd5c Qd5d Qd5h Qd5s Qd6c Qd6d Qd6h Qd6s Qd7c Qd7d Qd7h Qd7s Qd8c Qd8d Qd8h Qd8s Qd9c Qd9d Qd9h Qd9s QdTc QdTd QdTh QdTs QdJc QdJd
QdJh QdJs QdQc Qh2c Qh2d Qh2h Qh2s Qh3c Qh3d Qh3h Qh3s Qh4c Qh4d Qh4h Qh4s Qh5c Qh5d Qh5h Qh5s Qh6c Qh6d Qh6h Qh6s Qh7c Qh7d Qh7h
Qh7s Qh8c Qh8d Qh8h Qh8s Qh9c Qh9d Qh9h Qh9s QhTc QhTd QhTh QhTs QhJc QhJd QhJh QhJs QhQc QhQd Qs2c Qs2d Qs2h Qs2s Qs3c Qs3d Qs3h
Qs3s Qs4c Qs4d Qs4h Qs4s Qs5c Qs5d Qs5h Qs5s Qs6c Qs6d Qs6h Qs6s Qs7c Qs7d Qs7h Qs7s Qs8c Qs8d Qs8h Qs8s Qs9c Qs9d Qs9h Qs9s QsTc
QsTd QsTh QsTs QsJc QsJd QsJh QsJs QsQc QsQd QsQh Kc2c Kc2d Kc2h Kc2s Kc3c Kc3d Kc3h Kc3s Kc4c Kc4d Kc4h Kc4s Kc5c Kc5d Kc5h Kc5s
Kc6c Kc6d Kc6h Kc6s Kc7c Kc7d Kc7h Kc7s Kc8c Kc8d Kc8h Kc8s Kc9c Kc9d Kc9h Kc9s KcTc KcTd KcTh KcTs KcJc KcJd KcJh KcJs KcQc KcQd
KcQh KcQs Kd2c Kd2d Kd2h Kd2s Kd3c Kd3d Kd3h Kd3s Kd4c Kd4d Kd4h Kd4s Kd5c Kd5d Kd5h Kd5s Kd6c Kd6d Kd6h Kd6s Kd7c Kd7d Kd7h Kd7s
Kd8c Kd8d Kd8h Kd8s Kd9c Kd9d Kd9h Kd9s KdTc KdTd KdTh KdTs KdJc KdJd KdJh KdJs KdQc KdQd KdQh KdQs KdKc Kh2c Kh2d Kh2h Kh2s Kh3c
Kh3d Kh3h Kh3s Kh4c Kh4d Kh4h Kh4s Kh5c Kh5d Kh5h Kh5s Kh6c Kh6d Kh6h Kh6s Kh7c Kh7d Kh7h Kh7s Kh8c Kh8d Kh8h Kh8s Kh9c Kh9d Kh9h
Kh9s KhTc KhTd KhTh KhTs KhJc KhJd KhJh KhJs KhQc KhQd KhQh KhQs KhKc KhKd Ks2c Ks2d Ks2h Ks2s Ks3c Ks3d Ks3h Ks3s Ks4c Ks4d Ks4h
Ks4s Ks5c Ks5d Ks5h Ks5s Ks6c Ks6d Ks6h Ks6s Ks7c Ks7d Ks7h Ks7s Ks8c Ks8d Ks8h Ks8s Ks9c Ks9d Ks9h Ks9s KsTc KsTd KsTh KsTs KsJc
KsJd KsJh KsJs KsQc KsQd KsQh KsQs KsKc KsKd KsKh Ac2c Ac2d Ac2h Ac2s Ac3c Ac3d Ac3h Ac3s Ac4c Ac4d Ac4h Ac4s Ac5c Ac5d Ac5h Ac5s
Ac6c Ac6d Ac6h Ac6s Ac7c Ac7d Ac7h Ac7s Ac8c Ac8d Ac8h Ac8s Ac9c Ac9d Ac9h Ac9s AcTc AcTd AcTh AcTs AcJc AcJd AcJh AcJs AcQc AcQd
AcQh AcQs AcKc AcKd AcKh AcKs Ad2c Ad2d Ad2h Ad2s Ad3c Ad3d Ad3h Ad3s Ad4c Ad4d Ad4h Ad4s Ad5c Ad5d Ad5h Ad5s Ad6c Ad6d Ad6h Ad6s
Ad7c Ad7d Ad7h Ad7s Ad8c Ad8d Ad8h Ad8s Ad9c Ad9d Ad9h Ad9s AdTc AdTd AdTh AdTs AdJc AdJd AdJh AdJs AdQc AdQd AdQh AdQs AdKc AdKd
AdKh AdKs AdAc Ah2c Ah2d Ah2h Ah2s Ah3c Ah3d Ah3h Ah3s Ah4c Ah4d Ah4h Ah4s Ah5c Ah5d Ah5h Ah5s Ah6c Ah6d Ah6h Ah6s Ah7c Ah7d Ah7h
Ah7s Ah8c Ah8d Ah8h Ah8s Ah9c Ah9d Ah9h Ah9s AhTc AhTd AhTh AhTs AhJc AhJd AhJh AhJs AhQc AhQd AhQh AhQs AhKc AhKd AhKh AhKs AhAc
AhAd As2c As2d As2h As2s As3c As3d As3h As3s As4c As4d As4h As4s As5c As5d As5h As5s As6c As6d As6h As6s As7c As7d As7h As7s As8c
As8d As8h As8s As9c As9d As9h As9s AsTc AsTd AsTh AsTs AsJc AsJd AsJh AsJs AsQc AsQd AsQh AsQs AsKc AsKd AsKh AsKs AsAc AsAd AsAh
```
[Answer]
# [Perl 5](https://www.perl.org/), 73 bytes
```
@,=map{/./;map$&.$_,c,d,h,'s'}2..9,T,J,Q,K,A;map{say$i,$_}@,while$i=pop@,
```
[Try it online!](https://tio.run/##K0gtyjH9/99BxzY3saBaX0/fGkirqOmpxOsk66ToZOioF6vXGunpWeqE6HjpBOp46ziCVFQXJ1aqZOqoxNc66JRnZOakqmTaFuQXOOj8//8vv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online")
] |
[Question]
[
# Problem
Given input `a` where a is a grid of characters in any input format as long as it has only one element for each 'block' of the output.
And input `b` where b is a grid of numbers the same size as input `a`.
There are two types of road, a 1 represents a stone road marked by `@` and a 2 represents a dirt road marked by `#`
* A `@` road is centered in the block and is size 6x6, if a road is adjacent, that side is extended to grid cell border
* A `#` road is centered in the block is size 4x4, if a road is adjacent, that side is extended to grid cell border
Output a grid offset by line number of 8x8 of the ASCII character in input `a` and overlay a 'road' from input `b` e.g.
Input `a=[[a,b,a],[b,a,b],[a,b,a]] b=[[1,1,1],[2,0,1],[2,0,0]]`
Output:
Step 1: the grid (8x8 representation of input `a`)
```
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
bbbbbbbbaaaaaaaabbbbbbbb
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
```
Step 2: Overlay with roads represented by `b`:
```
aaaaaaaabbbbbbbbaaaaaaaa
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@abbbbbbbba@@@@@@a
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaabbbbbbbb
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
```
Step 3: Offset each line with linenumber:
```
aaaaaaaabbbbbbbbaaaaaaaa
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@abbbbbbbba@@@@@@a
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaabbbbbbbb
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
```
### Rules:
* Leading whitespace or newlines allowed.
* Trailing whitespace and newlines allowed.
* This is code-golf so shortest code wins
[Here](https://pastebin.com/PWtcGx1x) is an extra test case with all edge cases in I can think of.
[Answer]
# PHP 857 bytes
Not really what anyone could call "golfed" but since nobody else seems to have entered anything at all, I figured this was a start. It's massive, but it seems to work. Will make an effort to golf it tomorrow if I get the time.
```
function a($a,$b){$c=sizeof($a);$d=sizeof($a[0]);for($e=0;$e<$c;$e++){for($f=0;$f<$d;$f++){$A=$GLOBALS['h']=$a[$e][$f];$i=$GLOBALS['i']=$b[$e][$f];$B=j($i==1&&$b[$e-1][$f]>0);$C=j($i==1&&$b[$e][$f+1]>0);$D=j($i==1&&$b[$e+1][$f]>0);$E=j($i==1&&$b[$e][$f-1]>0);$F=j($i>0&&$b[$e-1][$f]>0);$G=j($i>0&&$b[$e][$f+1]>0);$H=j($i>0&&$b[$e+1][$f]>0);$I=j($i>0&&$b[$e][$f-1]>0);$J=j($i==1);$K=j($i==1||($i>1&&$b[$e-1][$f]>0));$L=j($i==1||($i>1&&$b[$e][$f+1]>0));$M=j($i==1||($i>1&&$b[$e+1][$f]>0));$N=j($i==1||($i>1&&$b[$e][$f-1]>0));$O=j($i>0);$P=$e*8;$g[$P].="$A$B$F$F$F$F$B$A";$g[$P+1].="$E$J$K$K$K$K$J$C";$l="$I$N$O$O$O$O$L$G";$g[$P+2].=$l;$g[$P+3].=$l;$g[$P+4].=$l;$g[$P+5].=$l;$g[$P+6].="$E$J$M$M$M$M$J$C";$g[$P+7].="$A$D$H$H$H$H$D$A";}}foreach($g as$h){echo str_repeat(' ', $i++)."$h\n";}}function j($k){return($k)?strtr($GLOBALS['i'],'12','@#'):$GLOBALS['h'];}
```
Test case
```
error_reporting(0);
$a=[[a,b,a],[b,a,b],[a,b,a]];
$b=[[1,1,1],[2,0,1],[2,0,0]];
a($a,$b);
```
Output
```
aaaaaaaabbbbbbbbaaaaaaaa
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@@@@@@@@@@@@@@@@@a
a@@@@@@abbbbbbbba@@@@@@a
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaab@@@@@@b
bb####bbaaaaaaaabbbbbbbb
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aa####aabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
aaaaaaaabbbbbbbbaaaaaaaa
```
Test case
```
error_reporting(0);
$a=[['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '1']];
$b=[[0,1,0,0,1,2,0],[1,1,1,2,2,2,2],[0,2,0,0,0,1,0]];
a($a,$b);
```
Output
```
........,,,,,,,,........,,,,,,,,........,,,,,,,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@,,,,,,,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@######,,........
........,@@@@@@,........,,,,,,,,.@@@@@@@,,####,,........
........,@@@@@@,........,,,,,,,,.@@@@@@.,,####,,........
........,@@@@@@,........,,,,,,,,..####..,,####,,........
.@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,..####..,,####,,........
.@@@@@@@@@@@@@@@@@@@@@@@##############################..
.@@@@@@@@@@@@@@@@@@@@@@@##############################..
.@@@@@@@@@@@@@@@@@@@@@@@##############################..
.@@@@@@@@@@@@@@@@@@@@@@@##############################..
.@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,........,,####,,........
........,@@@@@@,........,,,,,,,,........,,####,,........
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,####,,........,,,,,,,,........,@@@@@@,11111111
........,,,,,,,,........,,,,,,,,........,@@@@@@,11111111
........,,,,,,,,........,,,,,,,,........,,,,,,,,11111111
```
Test case
```
error_reporting(0);
$a=[[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p],[p,p,p,p,h,h,h,p,p,p,p]];
$b=[[1,1,1,0,1,0,1,0,1,1,1],[1,0,1,0,1,0,1,0,1,0,1],[1,1,1,0,1,1,1,0,1,1,1],[1,0,0,0,1,0,1,0,1,0,0],[1,0,0,0,1,0,1,0,1,0,0]];
a($a,$b);
```
Output
```
pppppppppppppppppppppppppppppppphhhhhhhhhhhhhhhhhhhhhhhhpppppppppppppppppppppppppppppppp
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@pppppppppp@@@@@@ppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@pppppppppp@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@@@@@@@@@@@@@@@@@ppppppppph@@@@@@@@@@@@@@@@@@@@@@hppppppppp@@@@@@@@@@@@@@@@@@@@@@p
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
p@@@@@@ppppppppppppppppppppppppph@@@@@@hhhhhhhhhh@@@@@@hppppppppp@@@@@@ppppppppppppppppp
pppppppppppppppppppppppppppppppphhhhhhhhhhhhhhhhhhhhhhhhpppppppppppppppppppppppppppppppp
```
[Answer]
# JavaScript (ES6), 250 ~~207~~ bytes
*Edit* Bug fix :(
A function taking inputs in currying syntax (a)(b).
```
a=>b=>a.map((r,i)=>k.map(y=>(h+=' ')+r.map((c,j)=>k.map(x=>(t=x<v,s=x>7-v,!v|t&(!q[j-1]|w|u)|s&(!q[j+1]|w|u)|u&(!p[j]|t|s)|w&(!(b[i+1]||[])[j]|t|s)?c:'-@#'[v]),v=q[j],w=y>7-v,u=y<v).join``).join``,p=q,q=b[i]).join`
`,h=q=[],k=[...'01234567']).join`
`
```
*Less golfed*
```
a=>b=>a.map((r,i)=>
[0,1,2,3,4,5,6,7].map(y=>
(h+=' ') + r.map((c,j)=>
[0,1,2,3,4,5,6,7].map(x=> (
t=x<v, s=x>7-v,
v == 0
|| t && (!B[i][j-1] | w|u)
|| s && (!B[i][j+1] | w|u)
|| u && (!(B[i-1]||[])[j] | t|s)
|| w && (!(B[i+1]||[])[j] | t|s)
? c : '-@#'[v] )
, v = B[i][j], w=y>7-v,u=y<v).join``
).join``
).join`\n`
,h = '').join`\n`
```
**Test**
```
F=
a=>b=>a.map((r,i)=>k.map(y=>(h+=' ')+r.map((c,j)=>k.map(x=>(t=x<v,s=x>7-v,!v|t&(!q[j-1]|w|u)|s&(!q[j+1]|w|u)|u&(!p[j]|t|s)|w&(!(b[i+1]||[])[j]|t|s)?c:'-@#'[v]),v=q[j],w=y>7-v,u=y<v).join``).join``,p=q,q=b[i]).join`
`,h=q=[],k=[...'01234567']).join`
`
A=[['a','b','a'],['b','a','b'],['a','b','a']]
B=[[1,1,1],[2,0,1],[2,0,0]]
O.textContent = F(A)(B)+'\n'
A=[['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '.'],['.', ',', '.', ',', '.', ',', '1']]
B=[[0,1,0,0,1,2,0],[1,1,1,2,2,2,2],[0,2,0,0,0,1,0]]
O.textContent += F(A)(B)
```
```
<pre id=O></pre>
```
[Answer]
# Java - 661 bytes
Hi! This is my first submission here. If I did something wrong please tell me.
```
static void m(char[][]b,int[][]t){String z="";int w=b[0].length;int h=b.length;char[][]r=new char[h*8][w*8];for(int j=0;j<h;j++){for(int i=0;i<w;i++){for(int x=0;x<8;x++)for(int y=0;y<8;y++){r[j*8+y][i*8+x]=b[j][i];int n=t[j][i];if(n!=0){char c;int d,e;if(n==1){c='@';e=0;d=7;}else{c='#';e=1;d=6;}if(x>e&&y>e&&x<d&&y<d)r[j*8+y][i*8+x]=c;if(x>e&&x<d){if(j>0&&y<2&&t[j-1][i]!=0)r[j*8+y][i*8+x]=c;if(j<h-1&&y>5&&t[j+1][i]!=0)r[j*8+y][i*8+x]=c;}if(y>e&&y<d){if(i>0&&x<2&&t[j][i-1]!=0)r[j*8+y][i*8+x]=c;if(i<w-1&&x>5&&t[j][i+1]!=0)r[j*8+y][i*8+x]=c;}}}}for(int l=0;l<8;l++){System.out.println(z+Arrays.toString(r[j*8+l]).replaceAll("[\\[\\]]|[, ]\\s",""));z+=" ";}}}
```
[You can try it here :)](https://tio.run/##pVPBcpswEL3nK1Q6YyDIBDLT1h1ZmeYDesoR6yBAsUVl8IAcQyjf7q5k8NiduJcKW9p9etr3tMYFf@PzaifKIv/1/Si3u6rWqAAw3Gupwue65l1D7nb7VMkMZYo3DfrJZYn6OwRjxBvNNSxvlczRFna9F13Lco14vW4S5o9kM7INrxOWsBRR1Pcud7Gbwpe7A@7HyCAmu9gbyLmALLU5r@35GMMD3EccndfIsB8ebgiGLkZQE6aPIyP8/5zYvTZxZRqsGpswg12oZS8BsX0gj7C9hmVEl1ffeinW/ikfjlc9987XxJOW348/wjt1HAIoOtA0iVioRLnWG4tsaDqlU4GaluJw6trmfsGSA0zktao9wy9oRIrlhhRB4PcTKAGUywORl2ALYLtckBbACesA6wDrDLFOivtF0LFEwtIysFZAzKytkuope/XKTzTye2MIZXY3x8LilMaAU/eHSwRUzuk3MgjVCIN9NlgM2FcyALd9ErNZZ6Z2mUO0zP2/9TMy8YDi95AUT5GhPs5m4GYeGz/GyocHoSnz2Eh8sezgH2zjx1rpRh1pdNpRB4ggdVMH@mx02lEHNoNb7AHG1HkF/VHQeWU6/9I1WmzDaq/DHbwgWpXee3D6o4e6Or003qmeYn5Yi53imXhWynOS1Qo@jP1OMGKrVeNgx/F98h5QBzlG8Tgc/wA)
Unminified:
```
static void m(char[][] b, int[][] t) {
String z="";
int w=b[0].length;int h=b.length;
char[][]r=new char[h*8][w*8];
for(int j=0;j<h;j++){
for(int i=0;i<w;i++){
for(int x=0;x<8;x++)for(int y=0;y<8;y++){
r[j*8+y][i*8+x] = b[j][i];
int n=t[j][i];
if(n!=0){
char c;int d,e;
if(n==1){c='@';e=0;d=7;}
else{c='#';e=1;d=6;}
if(x>e&&y>e&&x<d&&y<d)r[j*8+y][i*8+x]=c;
if(x>e&&x<d){
if(j>0&&y<2&&t[j-1][i]!=0)r[j*8+y][i*8+x]=c;
if(j<h-1&&y>5&&t[j+1][i]!=0)r[j*8+y][i*8+x]=c;
}
if(y>e&&y<d){
if(i>0&&x<2&&t[j][i-1]!=0)r[j*8+y][i*8+x]=c;
if(i<w-1&&x>5&&t[j][i+1]!=0)r[j*8+y][i*8+x]=c;
}
}
}
}
for(int l=0;l<8;l++){System.out.println(z+Arrays.toString(r[j*8+l]).replaceAll("[\\[\\]]|[, ]\\s",""));z+=" ";}
}
}
```
[Answer]
# JavaScript - 299 bytes
```
(a,b,g=(x,y)=>!(b[y]||0)[x],u=s=r='',L='length',R='repeat')=>{for(y=v=-1;++y<a[L];)for(i=v;++i<8;)for(x=v,s+=`
`+r,r+=' ';m=b[y][++x],W=Q=a[y][x],W+=(Z=~m&1)?Q:u,D=(A=i<m)|(B=i>7-m)?W:u,p=g(x-1,y)?W:D,q=g(x+1,y)?W:D,x<a[0][L];)s+=p+(A&&g(x,y-1)||B&&g(x,y+1)||!m?Q:'@#'[Z])[R](8-(p+q)[L])+q;return s}
```
# [Try it here](https://jsfiddle.net/49o68k90/)
[Answer]
# PHP, ~~275 268 266 264~~ 252 bytes
```
<?foreach($_GET[a]as$y=>$r)for($z=8;$z--;)for($x=-print"
".$f.=" ";$w--||$c=$r[++$x+!$w=7];)echo[$a=($s=($m=$_GET[b])[$y])[$x+1],$a|$b=2>$n=$s[$x],1,1,1,1,$b|$a=$s[$x-1],$a][$w]*[$a=$m[$y+1][$x],$a|$b,1,1,1,1,$b|$a=$m[$y-1][$x],$a][$z]*$n?" @#"[$n]:$c;
```
takes input from GET parameters `a` and `b`, prints to STDOUT.
[Try it online.](http://sandbox.onlinephpfunctions.com/code/b6f0bacf1895e4a5202b16ff392dac3accb86d77)
**breakdown**
```
foreach($_GET[a]as$y=>$r) # loop 1: through rows of first array
for($z=8;$z--;) # loop 2: $z from 7 to 0 (line = 8*$y+7-$z)
for($x=-print"\n".$f.=" "; # print newline and padding
$w-- # loop 4: loop $w from 7 to 0 (column = 8*$x+7-$w)
||$c=$r[++$x+!$w=7];) # loop 3: loop $c through characters in row
echo
[ # vertical test
$a=($s=($m=$_GET[b])[$y])[$x+1], # $m=2nd array, $s=current row
# $a=block to the right has road
$a|$b=2>$n=$s[$x], # $b=current block has brick road
1,1,1,1,
$b|$a=$s[$x-1], # $a=block to the left has road
$a
][$w] # index tests
*
[ # horizontal test
$a=$m[$y+1][$x], # $a=block below has road
$a|$b,
1,1,1,1,
$b|$a=$m[$y-1][$x], # $a=block above has road
$a
][$z] # index tests
*$n # is a road in this block?
?" @#"[$n]:$c; # if block&v-test&h-test then print road
# else print character from 1st array
```
] |
[Question]
[
# Introduction
Inspired by [Dyalog Ltd.](http://www.dyalog.com/)'s 2016 student competition. [The challenge there](http://www.dyalog.com/student-competition.htm) is to write *good* APL code, but this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and it is open to all languages. Derived from [this closed challenge](https://codegolf.stackexchange.com/questions/89398/dyalogs-international-problem-solving-competition-phase-i-code-golf-edition).
The real challenge here is to combine the various (quite trivial) parts of the problem in a byte-efficient way by reusing values and/or algorithms.
If you find this challenge interesting and you use Dyalog APL ([free download here](http://goo.gl/9KrKoM)), you may also want to participate in [the original competition](http://www.dyalog.com/student-competition.htm), but note that the objective there is to submit *quality code* – not necessarily *short code*. If you are a student, you can win USD 100 for Phase I. Phase II (not related to this code golf challenge) can win you up to USD 2000 and a free trip to Scotland!
# Task
Take two strings (of any 7-bit ASCII characters) by any means and order (but please include input format in your answer). You may take them as separate arguments/inputs or as a single list of strings. One string contains the delimiters in the other. E.g. given `',;/'` and `'hello,hello;there;my/yes/my/dear,blue,world'`, the sub-strings are `['hello', 'hello', 'there', 'my', 'yes', 'my', 'dear', 'blue', and 'world']`.
You will do some statistics and ordering based on the lengths of those sub-strings that are not duplicated in the input. (You may chose to consider casing or not.) In the example given, those are `['there', 'yes', 'dear', 'blue', 'world']`.
Give (by any means) a list of four elements in the overall structure `[Number_1, Number_2, [List_3], [[List_4_1], [List_4_2]]]`:
1. The [mean](https://en.wikipedia.org/wiki/Arithmetic_mean) of the lengths of the non-duplicated strings. In our example, that is `4.2`
2. The [median](https://en.wikipedia.org/wiki/Median) of the lengths of the non-duplicated strings. In our example, that is `4`.
3. The [mode(s)](https://en.wikipedia.org/wiki/Multimodal_distribution) of the lengths of the non-duplicated strings. In our example, that is `[4, 5]`.
4. The original sub-strings (including duplicates), divided into two lists; the first are those that are not one of the above mode lengths, and the second are those that are. In our example: `[['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]`
The combined final answer of our example case is: `[4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]]`
# Considerations
1. Don't forget to reuse code and values. E.g. the median is the average of the 1 or 2 middle elements, and you'll need the mode(s) to reorder the original list.
2. Watch out for division by zero; an empty input means one string with length zero, so the mean length is zero. If there are no non-unique sub-strings, return zero for both mean and median, an empty list for modes, and put all original sub-strings onto the non-mode list.
3. The list of modes, and the sub-lists of non-mode-length strings, and mode-length strings, do not need to be sorted in any way.
4. If all non-duplicated sub-strings have different lengths, then all the lengths are considered modes.
5. Wherever the term *list* is used, you may use any collection of multiple data pieces that your language supports, e.g. tuples, arrays, dictionaries, etc.
6. The numeric values only need to be within 1% of the actual value.
# Example cases
### Example A
`',;/'` `'hello,hello;there;my/yes/my/dear,blue,world'`
gives
`[4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]`
### Example B
`'+|'` `''`
gives
`[0, 0, [0], [[], ['']]]`
**Note:** while there are two delimiter characters, none of them occur in the data string, so this is just one empty string. Mean, median, and mode are therefore zero There are no strings in the non-mode list and just the single empty string in the mode list.
### Example C
`''` `'ppcg.se.com'`
gives
`[11, 11, [11], [[], ['ppcg.se.com']]]`
**Note:** no delimiters, so the entire input is one string.
### Example D
`',;'` `',math,,math;'`
gives
`[0, 0, [], [['', 'math', '', 'math', ''], []]]`
**Note:** there are three empty sub-strings, and since all sub-strings have at least one duplicate, the mean and median default to zero, as per *Considerations*, above.
### Example E
`',;'` `'new,math,math;!;'`
gives
`[1.333, 1, [0,1,3], [['math', 'math'], ['new', '!', '']]]`
**Note:** there is only one of each length among the non-duplicated sub-strings, so all three lengths are modes.
---
You can verify my explicit permission to post this challenge here by contacting [the author of the original competition](http://www.dyalog.com/student-competition.htm).
[Answer]
## PowerShell v4+, ~~453~~ ~~455~~ ~~435~~ ~~427~~ 417 bytes
```
param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_};$c=@{};if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}$m/$l;if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}$x;($b|?{$_-notin$m}),$m
```
*(Saved 7 bytes by eliminating `$d` and reusing `$c` instead. Saved ~~13~~ ~~21~~ 31 bytes thanks to @Joey)*
What a mess. Below is a slightly more readable version, broken down into sections. I also included `-join` on the two potentially-array outputs to make the output more clear visually, as well as surrounding the last one in distinct delimiters `#->` and `<-#` to indicate the sub-arrays. I did this since PowerShell's `Write-Output` for multiple array return values can get a little confusing when just looking at them on the console.
```
param([char[]]$a,$b)if(!$b){0;0;0;'','';exit}$a|%{$b=$b-split$_}
$c=@{}
if($z=($b|group|?{$_.count-eq1}).Name){$z|%{$m+=$c[$_]=$_.length}}
if($l=$c.count){$c=$c.GetEnumerator()|sort v}else{$l=2}
$m/$l
if($l%2){$c[[math]::Floor($l/2)].Value}else{($c[$l/2].value+$c[$l/2-1].value)/2}
if($x=($c|group value|sort c -des)|%{if($_.count-ge$i){$i=$_.count;$_.name}}){$m=$b|?{$_.length-in$x}}else{$m=@()}
$x-join','
"#->" + ((($b|?{$_-notin$m})-join','),($m-join',')-join'<-# #->') + "<-#"
```
Takes input `$a` and `$b` (separators and string), and explicitly casts `$a` right away as a char-array. The `if(!$b)` clause handles the special case where `$b` is an empty string - it dumps zeros and empty strings onto the pipeline and `exit`s. Otherwise we loop through `$a` with `$a|%{...}`, each loop `-split`ting `$b` by the current character and re-saving into `$b`.
The next line sets `$c` as an empty hashtable. This is used as the temporary storage location for the non-duplicated values in `$b` and their corresponding lengths.
That's the next line. We take `$b`, pump it through `Group-Object` to put like words together, pipe that to `Where-Object` to select only those where the `.count` is `-eq`ual to 1. We then take the `.Name` of those (here's where the v4+ requirement comes into play), and store those `.Name`s (i.e., the words) into `$z`. We then take the `.count` of that, and that number forms our `if` clause -- so long as it's non-zero (i.e., we have at least one unique word), we pump those words through a loop. Each iteration we accumulate `$m` by, and also store into `$c`, the corresponding word's `.length`.
Next line sorts `$c` on lengths (that's the `|sort v`alue in the middle) and stores that back to `$c`, but we need to have some logic to account for cases where `$z` was empty (i.e., every word is a duplicate). If that's the situation, `$c` is already an empty hashtable, but we set `$l` equal to `2` to handle the mean calculation later.
Now, we're to our outputs. The first `$m/$l` just calculates the average length. The next line calculates the median based on either taking the exact middle value of `$c`, or taking the two above and below the middle and splitting the difference.
The next line is very complicated, and was where the longest troubleshooting was. It's calculating the mode. We start by `Group`ing `$c` based on `value` (i.e., the word lengths), then `Sort-Object` them by their `c`ount in `-des`cending order (i.e., the most-common lengths will be first). That list is fed into a loop. Each iteration, if the current item's `$_.count` is greater-than-or-equal-to `$i` (which initializes to `$null` or `0`, here), meaning that we've got a length that's the most-common, set `$i` equal to how many of that length there are, and add the length (`$_.name`) to the pipeline. That resulting array of most-common lengths is stored into `$x`.
Provided that we have at least one most-common length, the `if` triggers and we pipe `$b` through another `Where-Object`. This time, we're selecting all of the words where the `.length` is `-in` `$x` (i.e., all of the words that have a length that's in the mode), and store them into `$m` (yes, I reused a variable name). `Else`, we don't have a most-common length, so the strings of the mode is empty.
The next line `$x-join','` outputs the lengths of the mode. Then, the words in `$b` that aren't in `$m` and the words in `$m`, as two sub-arrays.
---
### Test suite
```
PS C:\Tools\Scripts\golfing> @(@(',;/','hello,hello;there;my/yes/my/dear,blue,world'),@('+|',''),@('','ppcg.se.com'),@(',;',',math,,math;'),@(',;','new,math,math;!;'))|%{"Testing: '"+$_[0]+"' '"+$_[1]+"'";.\fun-with-strings.ps1 $_[0] $_[1];"---------------------------------------------------------------------------------------"}
Testing: ',;/' 'hello,hello;there;my/yes/my/dear,blue,world'
4.2
5
4,5
#->my,yes,my<-# #->hello,hello,there,dear,blue,world<-#
---------------------------------------------------------------------------------------
Testing: '+|' ''
0
0
0
---------------------------------------------------------------------------------------
Testing: '' 'ppcg.se.com'
11
11
11
#-><-# #->ppcg.se.com<-#
---------------------------------------------------------------------------------------
Testing: ',;' ',math,,math;'
0
0
#->,math,,math,<-# #-><-#
---------------------------------------------------------------------------------------
Testing: ',;' 'new,math,math;!;'
1.33333333333333
1
3,1,0
#->math,math<-# #->new,!,<-#
---------------------------------------------------------------------------------------
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 63 bytes
```
Ju.ncRHGQ]E.OKlMfq1/JTJ.O<.<S*2KtlK2=N
S{.x.M/KZKY=Y
f}lTNJ.-JY
```
[Test suite.](http://pyth.herokuapp.com/?code=Ju.ncRHGQ%5DE.OKlMfq1%2FJTJ.O%3C.%3CS%2a2KtlK2%3DN%0AS%7B.x.M%2FKZKY%3DY%0Af%7DlTNJ.-JY&test_suite=1&test_suite_input=%27%2C%3B%2F%27%0A%27hello%2Chello%3Bthere%3Bmy%2Fyes%2Fmy%2Fdear%2Cblue%2Cworld%27%0A%27%2B%7C%27%0A%27%27%0A%27%27%0A%27ppcg.se.com%27%0A%27%2C%3B%27%0A%27%2Cmath%2C%2Cmath%3B%27%0A%27%2C%3B%27%0A%27new%2Cmath%2Cmath%3B%21%3B%27&debug=0&input_size=2)
[Answer]
# Python 3, 341 chars, 343 bytes
```
from statistics import*
def f(d,s,l=len):
w=sorted(''.join(x if not x in d else'ÿ'for x in s).split('ÿ'),key=l)
L=[l(x)for x in w if w.count(x)<2]
if L==[]:return 0,0,L,[s,L]
a,q=mean(L),median(L)
D={x:L.count(x)for x in L}
m=[x for x in D if D[x]==max(D.values())]
i=[l(x)for x in w].index(m[0])
return a,q,m,[w[:i],w[i:]]
```
As built-ins are not forbidden, using the `statistics` module is fine for mean and median, but its mode does not allow multiples.
* Edit1: check for non-uniqueness
* Edit2: shorter list comprehension on `m`
* Edit3: `l=len` and `L==[]`
* Edit4: for the empty `L` case, use it instead of `[]`
* Edit5: figured empty strings were not handled well, introduced non-7-bit-ASCII sentinel **ÿ**
[Answer]
## JavaScript (ES2017), 346 bytes
```
f=(p,q,a=p?q.split(p[0]):[q])=>p[1]?f(p.slice(1),a.join(p[1])):(s=a.filter(e=>a.indexOf(e)==a.lastIndexOf(e)).map(e=>e.length).sort((a,b)=>a-b),t=l=0,r=[],s.map(e=>r[t+=e,l++,e]=-~r[e]),[l&&t/l,l&&(s[l>>1]+s[l-1>>1])/2,[...m=new Set(s.filter(e=>r[e]==Math.max(...Object.values(r))))],[a.filter(e=>!m.has(e.length)),a.filter(e=>m.has(e.length))]])
```
For ES6 replace `Object.values(r)` with `Object.keys(r).map(k=>r[k])` at a cost of 11 bytes. Explanation:
```
f=(p,q,a=p?q.split(p[0]):[q])=> split on first seprator
p[1]?f(p.slice(1),a.join(p[1])): recurse for each separator
(s=a.filter(e=> search through list for
a.indexOf(e)==a.lastIndexOf(e)) unique strings only
.map(e=>e.length) get lengths of each string
.sort((a,b)=>a-b), sort lengths into order
t=l=0, total and length
r=[], frequency table
s.map(e=>r[t+=e,l++,e]=-~r[e]), build frequency table and total
[l&&t/l mean = total / length
,l&&(s[l>>1]+s[l-1>>1])/2 median = mean of middle elements
,[...m=new Set(s.filter(e=>r[e]== unique elements matching
Math.max(...Object.values(r))))] maximum length frequency
,[a.filter(e=>!m.has(e.length)) filter on non-modal length
,a.filter(e=>m.has(e.length))]]) filter on modal length
```
[Answer]
# q/kdb+, 134 bytes
**Solution:**
```
{(avg;med;{:M::(&)m=max m:(#:)@/:(=)x};{(y(&)(~)C;y(&)C:((#:)@/:y)in M)}[;a])@\:(#:)@/:(&)1=(#:)@/:(=)a:"\000"vs?[any y=/:x;"\000";y]}
```
**Examples:**
```
q)/assign function to 'f' to make this tidier
q)f:{(avg;med;{:M::(&)m=max m:(#:)@/:(=)x};{(y(&)(~)C;y(&)C:((#:)@/:y)in M)}[;a])@\:(#:)@/:(&)1=(#:)@/:(=)a:"\000"vs?[any y=/:x;"\000";y]}
q)f[",;/";"hello,hello;there;my/yes/my/dear,blue,world"]
4.2
4f
5 4
(("my";"yes";"my");("hello";"hello";"there";"dear";"blue";"world"))
q)f["+|";""]
0f
0f
,0
(();,"")
q)f["";"ppcg.se.com"]
11f
11f
,11
(();,"ppcg.se.com")
q)f[",;";",math,,math;"]
()
()
()
(("";"math";"";"math";"");())
q)f[",;";"new,math,math;!;"]
1.333333
1f
3 1 0
(("math";"math");("new";,"!";""))
```
**Explanation:**
Ungolfed version. Can likely be golfed down a fair bit more.
```
f:{(avg; / built-in average
med; / built-in median
{:M::where m=max m:count each group x}; / get max counts for group, save to global M
{
(y where not C; / y is original list,
y where C:(count each y) in M) / so these are ones that match the modes (M)
}[;a] / pass parameter a to the function
)
@\: / apply each-left with items on the right
count each / get the lengths of each string
where 1=count each group / remove the duplicates
a:"\000" vs / split on NUL and save in a
?[any y=/:x;"\000";y]} / replace any occurance of delimiter with NUL
```
] |
[Question]
[
***My PPCG holiday is over :D***
## Intro
Fractional time is `the year + (the value (minute of year) / number of minutes in the year)`.
## Example calculation
*You should assume that February always has 28 days and the year is always 365 days long.*
Let's say we want to convert the time: `17:34 3rd March 2013` to fractional time. Firstly, you find how many minutes were in 2013: [525600 minutes](http://convertwizard.com/365-days-to-minutes). Let's call this `x`.
Next, you want to find out how many minutes there have been since the start of 2013. A few quick calculations will tell you that the answer is 88894 minutes:
There have been 61 days since the start of the year, which times 1440 (number of minutes in a day) equals 87840 minutes. In 17 hours are 1020 minutes (17\*60). Now, we can add 87840, 1020 and 34 minutes to equal 88894 minutes.
Let's call this `y`.
Finally, you divide `y` by `x` and add the year, resulting in `2013.16912` (to 5 decimal places).
## Input
The date and time will be given as a single string. The string will be in the following format:
```
YYYY-MM-DD hh:mm
```
The time will always be in 24 hour format and the year will always be in the range 1900-2050 inclusive.
## Examples
```
Input: 2016-08-06 23:48
Output: 2016.59723
Input: 2013-03-03 17:34
Output: 2013.16912
Input: 1914-11-11 11:11
Output: 1914.86155
```
If you are going for the bounty, either ping me in the comments or in [The Nineteenth Byte](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte).
## Challenge
Calculate the given date and time as a fractional year.
Give all output to five decimal places (you may round in anyway you wish: flooring, ceiling, or true rounding). Shortest code wins.
## Bounty
**I am offering a 100 rep bounty** for the shortest program which *also* accepts the date in fractional year format and returns the time in `YYYY-MM-DD hh:mm` format. In essence, your program (or function) has to act in the following way:
```
f('1914-11-11 11:11') => 1914.86155
f('1914.86155') => 1914-11-11 11:11
```
1. [t-clausen.dk - 154 bytes](https://codegolf.stackexchange.com/a/89141/30525)
2. [Neil - 183 bytes](https://codegolf.stackexchange.com/a/88941/30525)
## Leaderboard
```
var QUESTION_ID=88924,OVERRIDE_USER=30525;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## JavaScript (ES6), 84 bytes
```
f=
s=>(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/31536e6+parseInt(s)).toFixed(5)
;
```
```
<input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o>
```
Assuming no leap years or DST are required, I replace the year with 1970 which makes `Date.parse` directly return the time offset in milliseconds, of which there were `31536000000` in 1970 (or indeed any other non-leap year). All I need do then is to add back the year and round to 5 decimal places. Edit: Bidirectional conversion in ~~183~~ 178 bytes:
```
f=
s=>/:/.test(s,m=31536e6)?(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/m+parseInt(s)).toFixed(5):s.slice(0,4)+new Date(s.slice(4)*m+3e4).toJSON().slice(4,16).replace(/T/,' ')
;
```
```
<input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o>
```
Assumes strings containing a `:` are time format, handled as above, otherwise strips off the year, converts to milliseconds, adds half a minute for rounding purposes, converts to a date in 1970, extracts the month, day, hour and minute, and prefixes the original year.
[Answer]
## Matlab, ~~132~~ 115 bytes
```
d=input('');m=cumsum([-1 '# #"#"##"#"'-4]);year(d)+fix((((m(month(d))+day(d))*24+hour(d))*60+minute(d))/5.256)/10^5
```
*Rounds towards 0.*
Hmmm... That's quite long.
That's using some builtins, but not the really helpful ones - because of leap years.
Parsing the string directly gives 2 more byte solution:
```
d=sscanf(input(''),'%d%[- :]');m=cumsum([-1 '# #"#"##"#"'-4]);d(1)+fix((((m(d(3))+d(5))*24+d(7))*60+d(9))/5.256)/10^5
```
Newer Matlab versions probably have some better split function, but I'm running on 2012a.
*Some bytes saved thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
[Answer]
# TSQL, 63 bytes
This is a shorter version than my original answer, because my initial answer included calculation for leap year.
```
DECLARE @ VARCHAR(16) ='1914-11-11 11:11'
PRINT LEFT(YEAR(@)+DATEDIFF(mi,0,STUFF(@,1,4,1900))/525600.,10)
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/1656730/a-fractional-year)**
The following sql can handle both input types
# TSQL, 154 bytes
```
DECLARE @ VARCHAR(16) ='1914-11-11 11:11'--can be replaced with '1914.86155'
PRINT IIF(isdate(@)=1,LEFT(YEAR(@)+DATEDIFF(mi,0,STUFF(@,1,4,1900))/525600.,10),LEFT(@,4)+RIGHT(CONVERT(CHAR(16),DATEADD(mi,1*RIGHT(@,5)*5.256,0),20),12))
```
**[Combined Fiddle 1](https://data.stackexchange.com/stackoverflow/query/522545/a-fractional-year)**
**[Combined Fiddle 2](https://data.stackexchange.com/stackoverflow/query/522543/a-fractional-year)**
[Answer]
## PowerShell v3+, 131 bytes
```
$t=date $args[0];$a=1440*!!(date "2-29-$($t.year)");"{0:F5}"-f((($t.DayOfYear-1)*1440+$t.TimeOfDay.TotalMinutes-$a)/525600+$t.Year)
```
Takes input `$args[0]` and converts it with `Get-Date` to store into .NET `[datetime]` format, stores into `$t`. Calculates whether February 29th exists, and sets `$a` so we subtract out that date's worth of minutes (if present).
Then we use the `-f`ormat operator with a [fixed-string](https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#FFormatString) specification of 5 decimal digits to run through the calculation. Uses built-ins to calculate the `.DayOfYear` and the `.TotalMinutes` of the given input, subtract `$a` if it's a leap year, divide by `525600` minutes total, and add on the input `.Year`.
Will complain (verbosely) to STDERR if February 29th doesn't exist (see examples below), but since STDERR is ignored by default, we don't worry about that. Also, note that PowerShell does [banker's rounding](https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx#Midpoint) by default.
### Examples
```
PS C:\Tools\Scripts\golfing> .\fractional-year.ps1 '2016-08-06 23:48'
2016.59724
PS C:\Tools\Scripts\golfing> .\fractional-year.ps1 '2013-03-03 17:34'
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "2-29-2013" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At C:\Tools\Scripts\golfing\fractional-year.ps1:7 char:36
+ $t=date $args[0];$a=1440*!!(date "2-29-$($t.year)");"{0:F5}"-f((($t.DayOfYear- ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
2013.16913
PS C:\Tools\Scripts\golfing> .\fractional-year.ps1 '1914-11-11 11:11'
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "2-29-1914" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At C:\Tools\Scripts\golfing\fractional-year.ps1:7 char:36
+ $t=date $args[0];$a=1440*!!(date "2-29-$($t.year)");"{0:F5}"-f((($t.DayOfYear- ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
1914.86155
```
---
### Alternately, with leap years, 119 bytes
```
"{0:F5}"-f((($t=date $args[0]).DayOfYear-1+$t.TimeOfDay.TotalMinutes/1440)/(date "12-31-$($t.year)").DayOfYear+$t.Year)
```
If we follow calendar settings, we can shave off a dozen bytes because we won't need to account for `$a` in the original code above. This allows us to move `$t` into the expression itself, and we'll explicitly calculate the `.DayOfYear` for December 31st. Otherwise, follows the same methodology.
[Answer]
# Python 3, ~~163~~ 173 bytes
more bytes because of output format
doesn't use any date builtins, like the java answer.
```
def s(x):z=x[5:10].split("-");v=x[10:].split(":");return int(x[:4])+(sum(([-1,31,28]+[31,30,31,30,31]*2)[:int(z[0])],int(z[1]))*1440+int(v[0])*60+int(v[1]))/525600
```
slightly more readable
```
def s(x):
date=x[5:10].split("-");time=x[10:].split(":")
return int(x[:4])+(sum(([-1,31,28]+[31,30,31,30,31]*2)[:int(date[0])],int(date[1]))*1440+int(time[0])*60+int(time[1]))/525600
```
[Answer]
# [Perl 6](http://perl6.org), ~~107 105~~ 102 bytes
```
~~{$/=.comb(/\d+/);($0+(sum(|flat(-1,31,28,(31,30,31,30,31)xx 2)[^$1],$2)\*1440+$3\*60+$4)/525600).fmt: '%.5f'}
{$/=.comb(/\d+/);fmt $0+(sum(|flat(-1,31,28,(31,30,31,30,31)xx 2)[^$1],$2)\*1440+$3\*60+$4)/525600: '%.5f'}~~
{$/=.comb(/\d+/);fmt $0+(flat($2-1,31,28,(31,30,31,30,31)xx 2)[^$1].sum*1440+$3*60+$4)/525600: '%.5f'}
{$/=.comb(/\d+/);round $0+(flat($2-1,31,28,(31,30,31,30,31)xx 2)[^$1].sum*1440+$3*60+$4)/525600,.1⁵}
```
### Explanation:
```
{
$/ = .comb(/\d+/); # grab a list of only the digits
# 「$0」 is short for 「$/[0]」
fmt
$0 # year
+
(
flat(
$2 -1, # days
31,28,(31,30,31,30,31)xx 2 # -+ months
)[^$1].sum * 1440 # /
+ $3 * 60 # hours
+ $4 # minutes
)
/
525600
: '%.5f' # the 「:」 is used here as 「fmt」 is a method not a subroutine
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
# returns Str
my &fractional-year-a = {$/=.comb(/\d+/);fmt $0+(sum(flat($2-1,31,28,(31,30,31,30,31)xx 2)[^$1])*1440+$3*60+$4)/525600: '%.5f'}
# returns Rat
my &fractional-year-b = {$/=.comb(/\d+/);round $0+(sum(flat($2-1,31,28,(31,30,31,30,31)xx 2)[^$1])*1440+$3*60+$4)/525600,.1⁵}
my @tests = (
'2016-08-06 23:48' => 2016.59723,
'2013-03-03 17:34' => 2013.16912,
'1914-11-11 11:11' => 1914.86155,
);
plan +@tests * 2;
for @tests -> $_ ( :key($input), :value($expected) ) {
is-approx +fractional-year-a($input), +$expected, 1e-5, "a $input => $expected";
is-approx +fractional-year-b($input), +$expected, 1e-5, "b $input => $expected";
}
```
```
1..6
ok 1 - a 2016-08-06 23:48 => 2016.59723
ok 2 - b 2016-08-06 23:48 => 2016.59723
ok 3 - a 2013-03-03 17:34 => 2013.16912
ok 4 - b 2013-03-03 17:34 => 2013.16912
ok 5 - a 1914-11-11 11:11 => 1914.86155
ok 6 - b 1914-11-11 11:11 => 1914.86155
```
] |
[Question]
[
Fred is a quasi-friendly guy, but in reality he is mean.
Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.
Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).
Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.
These are the tiers, their prices, and the amounts of water they correspond to:
```
Tier I
First 10 Ccf: $3.8476/Ccf
Tier II
Next 17 Ccf: $4.0932/Ccf
Tier III
All subsequent water: $4.9118/Ccf
```
For *n* hundreds of cubic feet (Ccf), there are the following additional charges as well:
```
CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n
```
The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.
Here are two examples:
```
Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59
Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72
```
This is code golf so shortest code in bytes wins!
[Answer]
## Mathematica, ~~83~~ ~~76~~ 69 bytes
```
1.015{3.8476,.2456(b=Boole)[#>10],.8186b[#>27],51/1015}&~Array~#~Total~2~Round~.01&
```
Anonymous function that constructs an array of the three tiers in the first column plus the LIRA and PBOP represented as an arbitrary-precision number in the fourth column. The whole thing is multiplied by `1.015` and all elements of the array are summed and rounded to `.01`. Since `51/1015*1.015` will be the desired `0.051` the output is exactly as precise, as the specification in OP.
A shorter solution, in **76 bytes**, as I have suggested in my comment under the Perl solution
```
{3.956314,.249284(b=Boole)[#>10],.830879b[#>27]}&~Array~#~Total~2~Round~.01&
```
where `1.015` is factored into the prices from the start and then the LIRA and PBOP is added on top of the first tier.
~~**73 bytes** (but I'm reluctant to update my byte-count since this is quite close to the straightforward Perl solution):~~
**69 bytes** -- ah what the heck, golfing took some effort too.
```
.01Round[395.6314#+{24.9284,83.0879}.(UnitStep[#-1]#&/@{#-10,#-27})]&
```
**EDIT regarding floating point error**
The first three iterations of my answer are indeed exact in their decimal representation, since all coefficients involved have terminating decimal representations. However, since the coefficients are explicitly floats, stored in binary and having non-terminating binary representations, large enough inputs will start to accumulate errors in the least-significant digits of the binary representation. I would guess, when the float is so large, that it fits only 3-4 digits to the right of the decimal point, we can expect errors of around 1 cent. See below for an *exact* answer.
**72 bytes, somewhat-immune to float inaccuracies**
```
.01Round[{3956314,249284,830879}.(UnitStep[#-1]#&)/@(#-{0,10,27})/10^4]&
```
The multiplication by the leading `.01` is done at the very last step. Until that point, all calculation are done with integers. This means, that if the `.01` is omitted, there will be an *exact* result, but expressed in cents, rather than dollars. Of course, the multiplication by a float converts the entire thing to a float, and, as mentioned, it needs to be small enough to fit into 64 bits and still be accurate to `.01`.
[Answer]
## 05AB1E, ~~64~~ ~~58~~ 51 bytes
```
0T27¹)vy¹‚ï{0è})¥•_ÄÄ™wu24@•2'.:7ô)ø€PO¹"5.1"*+ïTn/
```
**Explained**
```
0T27¹) # list of price brackets
vy¹‚ï{0è}) # min of each with input
¥ # calculate deltas to get amounts within each bracket
•_ÄÄ™wu24@•2'.:7ô # list of price rates with CPUC included
)ø # zip with amounts for each rate
€PO # multiply amounts by their rates and sum
¹"5.1"*+ # add LIRA/PBOP
ïTn/ # round to 2 decimals
```
[Try it online](http://05ab1e.tryitonline.net/#code=MFQyN8K5KXZ5wrnigJrDr3sww6h9KcKl4oCiX8OEw4TihKJ3dTI0QOKAojInLjo3w7Qpw7jigqxQT8K5IjUuMSIqK8OvVG4v&input=MTAw)
[Answer]
# Pyth, ~~55~~ 41 bytes
```
.R+s*Vv.",9t¬®Ï0NwÝ"lMcUQ,T27*.051Q2
```
The code contains unprintable characters, so here's a `xxd` hexdump.
```
00000000: 2e52 2b73 2a56 762e 222c 3904 1874 c2ac .R+s*Vv.",9..t..
00000010: c2ae c280 c293 c38f 301c 4e77 c39d 226c ........0.Nw.."l
00000020: 4d63 5551 2c54 3237 2a2e 3035 3151 32 McUQ,T27*.051Q2
```
### Explanation
1. `."…"` is a packed string that contains `3.8476,4.0932,4.9118`.
2. `v` evaluates that to the tuple `(3.8476, 4.0932, 4.9118)`. These are the tiers' prices multiplied with CPUC added.
3. `UQ` generates the range `0`…`n-1`.
4. `c`…`,T27` splits that range at indices 10 and 27, with extra empty lists in the end if the range is too short.
5. `lM` finds the length of each part, giving the amount of water for each tier.
6. `*V` multiplies that by the tuple from step 2 to get the prices for the tiers.
7. `s` sums the results.
8. `+`…`*Q.051` adds the input multiplied by 0.051, i.e. LIRA + PBOP.
9. `.R`…`2` rounds the result to 2 decimals.
[Try it online.](http://pyth.herokuapp.com/?code=.R%2Bs%2aVv.%22%2C9%04%18t%C2%AC%C2%AE%C2%80%C2%93%C3%8F0%1CNw%C3%9D%22lMcUQ%2CT27%2a.051Q2&input=15&debug=0)
[Answer]
# Perl 5, 73 bytes
The obvious solution. 72 bytes, plus 1 for `-ne` instead of `-e`.
```
printf'%.2f',$_*3.956314+($_-10)*($_>10)*.249284+($_-27)*($_>27)*.830879
```
Saved 5 bytes thanks to [LLlAMnYP](/users/46206/lllamnyp). Thanks!
[Answer]
# Oracle SQL 11.2, 151 bytes
```
SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+(DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+(DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+:1*0.051 FROM DUAL;
```
Un-golfed
```
SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+
(DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+
(DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+
:1*0.051
FROM DUAL
```
[Answer]
## JavaScript ES6, 77 bytes
```
x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x
```
Un-golfed
```
f = x => {
if (x > 27) {
res = (x - 27) * 4.985477 + 109.681306
} else if (x > 10) {
res = (x - 10) * 4.154598 + 39.05314
} else {
res = x * 3.905314
}
return res + 0.051 * x
}
```
I factored in the LIRA and PBOP coefficients. The extra 1.5% gets added at the end.
Probably not the most efficient solution in terms of golfing but somewhat different from the Perl one.
Floating point error should occur with larger numbers and can be fixed by adding 1 or 2 extra bytes to each coefficient.
```
f=x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x
console.log(f(15))
console.log(f(100))
console.log(f(200000))
```
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
approxfun(c(0,10,27,10^6),c(0,39.56,111.06,5036475))
```
[Try it online!](https://tio.run/##K/qfZvs/saCgKL8irTRPI1nDQMfQQMfIHEjGmWnqgPjGlnqmZjqGhoZ6BmY6pgbGZibmppqa/9M0DE01uYCkgYHmfwA "R – Try It Online")
Generates a linear approximation function, based on my previous answer's values at 0,10,27 and 10^6. The catch: the upper limit on the input is 10^6.
`approxfun` (with `ecdf`, `stepfun`, `splinefun`, etc.) is one of the many nice features of `R`.
[Answer]
# VBA, 88 bytes
```
Function W(V):W=Round(.051*V+.203*(V*19.238-(V-10)*(V>10)*1.228-(V-27)*(V>27)*4.093),2)
```
The base rate and higher use differential rates have been multiplied by 5, and the CPUC fee multiplier divided by 5 (0.203).
The VB editor will add an `End Function` line, which is why the terminal line feed is included.
[Answer]
# Pyth - ~~58~~ 51 bytes
```
.Rs+*Bs*V++m3.8476Tm4.0932 17m4.9118Qm1Q.015*.051Q2
```
[Test Suite](http://pyth.herokuapp.com/?code=.Rs%2B%2aBs%2aV%2B%2Bm3.8476Tm4.0932+17m4.9118Qm1Q.015%2a.051Q2&test_suite=1&test_suite_input=15%0A100&debug=0).
] |
[Question]
[
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.
Your task is to build a program or function that will take an arbitrary list of [marginal tax brackets](https://en.wikipedia.org/wiki/Tax_rate#Marginal) and calculate the effective amount of tax paid on a given amount of taxable income.
Your program will take as input:
* `N` pairs of numbers in the form `(amt, rate)`, each representing a tax bracket.
+ `amt` is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.
+ `rate` is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.
* The amount of taxable income, as a nonnegative integer.
If no rate is specified for $0, the rate is assumed to be 0%.
Alternatively, your program can also take as input two lists `(amt1, amt2, ...)` and `(rate1, rate2, ...)`, containing the amounts and rates in the same order.
Your program will then output the payable tax, either to two decimal places, or rounded *down* to the nearest whole currency unit.
---
An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):
```
11474 15
45282 20.5
90563 26
140388 29
200000 33
393216
```
And its corresponding output:
```
108357.07 or 108357
```
---
The shortest program in any language to do this wins.
[Answer]
# Haskell, ~~67~~ 66 bytes
Thanks Damien for -1 byte.
This solution is in the form of an infix function, `?`, of type `(Integral b, RealFrac r) => [(r, r)] -> r -> b`. The helper function, `#`, does the required calculations while `?` serves to handle the IO specifications.
```
a?b=floor$reverse a#b
((m,p):r)#i|v<-min i m=p/100*(i-v)+r#v
_#_=0
```
[Answer]
## 05AB1E, ~~35~~ 24 bytes
```
vy³ï‚{0è)˜}³ï‚˜¥²ø€PTn/O
```
**Explanation**
```
vy # for each amount
³ï‚ # pair with taxable income
{0è # get min
)˜} # add to list
³ï‚˜ # add income to the end of the list
¥ # get deltas
²ø # zip with tax rates
€P # map product on each pair of [amount in tax bracket,rate]
Tn/ # divide by 100
O # sum
# implicitly display result
```
[Try it online](http://05ab1e.tryitonline.net/#code=dnnCs8Ov4oCaezDDqCnLnH3Cs8Ov4oCay5zCpcKyw7jigqxQVG4vTw&input=WzExNDc0LDQ1MjgyLDkwNTYzLDE0MDM4OCwyMDAwMDBdClsxNSwyMC41LDI2LDI5LDMzXQozOTMyMTY)
[Answer]
# Mathematica ~~85~~ 82 bytes
Derived from Josh O'Brien's [code](https://stackoverflow.com/questions/33770639/calculate-marginal-tax-rates-using-r) in R.
```
d_~f~i_:=Tr@Thread[Differences@((i~Min~#&/@d[[All,1]]~Append~∞))d[[All,2]]/100.]
```
---
## Usage
```
f[{{11474, 15}, {45282, 20.5}, {90563, 26}, {140388, 29}, {200000, 33}}, 393216]
```
108357.
[Answer]
## Matlab, 79 bytes
Assuming we can take `amt` and `rate` as separate column vectors:
```
function[]=f(a,b,c)
t=sort([0;a;c]);fix(sum(diff(t).*[0;b/100].*(t(2:end)<=c)))
```
If we can't (then `a` is a two-column matrix of `amt` and `rate`) it's 87 bytes.
```
function[]=f(a,c)
t=sort([0;a(:,1);c]);fix(sum(diff(t).*[0;a(:,2)/100].*(t(2:end)<=c)))
```
**Explanation:**
```
f(a,b,c) -- takes amt, rate and income
[0;a;c] -- gives a vector of amounts with 0 and the income amount
t=sort(...) -- sort this vector
diff(t) -- gives us amounts to be taxed in every bracket
diff(t).*[0;b/100] -- tax in every bracket
.*(t(2:end)<=c) -- take only entries lower than the income
sum(...) -- sum everything
fix(...) -- round towards 0
```
[Answer]
## JavaScript (ES6), 60 bytes
```
(a,n)=>a.map(([b,r])=>{t+=n>b&&(n-b)*(r-p);p=r},p=t=0)|t/100
```
`a` is an array of arrays of band and rate, which would be `[[11474, 15], [45282, 20.5], [90563, 26], [140388, 29], [200000, 33]]` for the given example, and `n` is the income (`393216`).
[Answer]
# Swift, 61 bytes
```
zip(zip(m+[i],[0]+m).map{$0-$1},[0]+r).map{$0*$1}.reduce(0,+)
```
Ungolfed, with test cases:
```
struct TaxContext {
let marginLowerBound: [Double]
let rates: [Double]
}
// ungolfed
extension TaxContext {
func calcAfterTaxIncome(_ income: Double) -> Double {
//drop first element (0), append income
let upper = marginLowerBound + [income]
let lower = [0] + marginLowerBound
let incomeInEachMargin = zip(upper, lower)
.map{ upperBound, lowerBound in upperBound - lowerBound }
let taxInEachMargin = zip(incomeInEachMargin, [0]+rates)
.map{ incomeInMargin, rate in incomeInMargin * rate }
let totalTax = taxInEachMargin.reduce(0, +)
print(upper)
print(lower)
print(incomeInEachMargin)
print(rates)
print(taxInEachMargin)
return totalTax
}
}
// golfed
extension TaxContext {
// computed properties to serve as aliases for the golfed version
var m: [Double] { return self.marginLowerBound }
var r: [Double] { return self.rates }
func f(_ i: Double) -> Double {
return zip(zip(m+[i],[0]+m).map{$0-$1},[0]+r).map{$0*$1}.reduce(0,+)
}
}
let testCase1 = TaxContext(
marginLowerBound: [10_000, 20_000, 30_000],
rates: [0.1, 0.2, 0.3, 0.4]
)
let result1 = testCase1.calcAfterTaxIncome(70_000)
print(result1)
let testCase2 = TaxContext(
marginLowerBound: [11474 , 45282, 90563, 140388, 200000],
rates: [0.15, 0.205, 0.26, 0.29, 0.33]
)
let result2 = testCase2.calcAfterTaxIncome(393216)
print(result2)
```
] |
[Question]
[
A common optimization to save space in binaries is to merge string literals where one literal is the suffix of another. For instance, a binary with the string literals
```
a: foobar
b: bar
c: barbaz
d: foobarbaz
e: baz
```
might contain the following string literal pool (`#` representing the `\0`-terminator):
```
foobar#foobarbaz#
```
with the symbols `a`, `b`, `c`, and `d` having the following values relative to the beginning of the string pool:
```
a: 0
b: 3
c: 10
d: 7
e: 13
```
In this task, you have to compute the minimal size of a string pool for a given set of input strings.
## Input
The input is a series of up to 999 strings each comprising up to 80 ASCII characters (not including the newline) in the range from 32 to 127 inclusive and then a single newline character.
## Output
Find the shortest string such that each of the input strings (including the terminating newlines) are substrings of that string. The output shall be the length of that shortest string. Do not output the string, only its length.
## Scoring
This challenge is code golf, standard loopholes apply. The solution with the least length in octets wins.
## Examples
1. Input:
```
foobar
bar
barbaz
foobarbaz
baz
```
shortest string, `#` representing newline:
```
foobar#foobarbaz#
```
length: 17
2. Input:
```
foobar
foobaz
foobarbaz
barbaz
```
shortest string, `#` representing newline:
```
foobar#foobaz#foobarbaz#
```
length: 24
[Answer]
# Pyth, ~~20~~ 18 bytes
```
hljb-{.zsmteM./d.z
```
[Demonstration.](https://pyth.herokuapp.com/?code=hljb-%7B.zsmteM.%2Fd.z&input=foobar%0Afoobaz%0Afoobarbaz%0Abarbaz&debug=0)
`{` can be removed if duplicates are not allowed.
Explanation:
```
hljb-{.zsmteM./d.z
.z The input, as a list of strings.
m Map each strings to
./d all possible partitions of the string into separate strings.
eM take the last element of each, giving all suffixes.
t Remove the first suffix, giving all suffixes other than
the string itself.
s Sum, combining the list of lists into a single list.
-{.z From the set of input strings, remove all suffixes.
This is the list of strings in the minimal segment.
jb Join the strings together on newlines.
l Take the length of the resulting string.
h Add one and print.
```
[Answer]
# CJam, 22 bytes
```
qN%_&Nf+:G{Gs\/,3<},s,
```
[Try it online.](http://cjam.aditsu.net/#code=qN%25Nf%2B_%26%3AG%7BGs%5C%2F%2C3%3C%7D%2Cs%2C&input=foobar%0Afoobaz%0Afoobarbaz%0Abarbaz)
### How it works
```
qN% e# Split the input from STDIN at linefeeds, discarding the last, empty chunk.
_& e# Intersect the array with itself to remove duplicates.
Nf+ e# Append a linefeed to each chunk.
:G e# Save the result in G.
{ e# Filter; for each chunk in G:
Gs e# Flatten the array of strings G.
\/ e# Split at occurrences of G.
,3< e# Compare the resulting number of chunks with 3.
}, e# Keep the chunk iff the comparision pushed 1 (true).
s, e# Flatten the resulting array of strings and push the result's length.
```
[Answer]
## python 2, 132
Just to start a race:
```
def f(s):
l=set(s.split('\n'))
for x in l:
for y in l:
if x!=y and x.endswith(y):l.remove(y)
return sum(len(x)+1 for x in l)
```
It works:
```
>>> f(r'''foobar
foobaz
foobarbaz
barbaz''')
24
>>> f(r'''foobar
bar
barbaz
foobarbaz
baz
''')
17
```
[Answer]
# Haskell, ~~101~~ 85 bytes
```
import Data.List
length.unlines.(\l->[x|x<-nub l,x`notElem`((tails.tail)=<<l)]).lines
```
A function without a name. Usage example:
```
*Main> length.unlines.(\l->[x|x<-nub l,x`notElem`((tails.tail)=<<l)]).lines $ "foobar\nbar\nfoobaz"
14
```
How it works: split input string at newlines. Remove duplicates from the word list `l`. Keep a word `x` from the remaining list if it's not in the list of all tails of the words of `l`. Join those `x` with newlines in-between (and at the end!) to a single string and count it's length.
] |
[Question]
[
Here is a list of [1000 basic English words](http://pastebin.com/wh6yxrqp). Yes, I'm aware that there are only 997 words in the list! It was taken from [Wiktionary](http://en.wiktionary.org/wiki/Appendix:1000_basic_English_words) so blame them!
Your task is to write a program that accepts a word and returns `TRUE` or `FALSE` (or `0` or `1`) depending on whether the word is in the list or not. You must use the spelling as it appears in the list, so it is `colour`, not `color` (sorry Americans!). As far as I am aware, there is only one word in the list that uses a capital letter: `I`. This means that `i` (Roman numeral for 1) should return `FALSE`. All other words may be spelt with an initial capital letter, i.e. `Colour` should return `TRUE`.
Rules for letter cases: Your program should return `TRUE` for any word that has just the first letter capitalised. If the entire word is capitalised, e.g. `COLOUR` it's your choice whether it is correct or not, as long as it is found in the word list in its lowercase form. If you accept `COLOUR` you must accept all other words entirely in capitals. If you don't accept `COLOUR` you must not accept any other word entirely in capitals. Any other mixture of lower and upper case e.g. `coLoUR` should return `FALSE`. As stated above only `I` is correct, not `i`. Briefly, both lowercase `colour` and titlecase `Colour` must be `TRUE`, uppercase `COLOUR` may be either `TRUE` or `FALSE` and any other mixed case must be `FALSE`.
Standard rules apply, you may not use external libraries or spelling libraries built into your language, etc. If you use any external files, such as reading the word list via the internet, you must include that number of bytes in your score. Reading the uncompressed word list will add 5942 to your score.
Your code must be at least 95% accurate, including both false positives and false negatives. So if you have 30 false positives and 20 false negatives there are 50 errors in total which is acceptable (even though there are only 997 words, 94.98% accurate if you're being pedantic). One more false positive or false negative invalidates your code. You must post all the errors for verification. Don't make people guess where the errors are!
Shortest code in bytes wins. Add 10 points for each error. Please post a non-golfed version of your code as well so that other people can try to break it / verify that it works. If you can provide a link to a working online version that would be great! The list is 5942 bytes long so ideally you want your code to be shorter than that.
Start your post with the following:
### <Language> - Bytes: <num>, False +ves: <num>, False -ves: <num> = Score: <num>
Score = bytes + 10 × (false\_pos + false\_neg)
I might provide a list of false positives to check against as people post answers.
[Answer]
### Python - Bytes: 4411, False +ves: 0, False -ves: 0 = Score: 4411
```
import base64,zlib,sys;T=eval(zlib.decompress(base64.b64decode("eNqdXEF24zYMPY43XHTdG/QYskjbGlGUSlFONH25e8cehySAD8rtLPIyji2JIPDx8QH6n9Nfpz//OZ3+/OPLnLrXr+bUP36Ljx/z48eafzze+OufOaX83uHx2/3x4/nb8w97ea85ueqDv/57zpfd8vuffzW/r+LIfezjf7Z6z/Xxe5dvF+o7xfx5Bx/A/L7v60qXvMhyOSsX6fLb8usDfcmcpmyNsrBAV/f8oH/89yPfcpd2LUvo8vPs4CLVcgJZ8MtC+YIhP5plb4lip+b8yDe48l9vWfMKgF32fK+ULTqJ7bjRzbvSG4Al/f7D8vjvQs0T6+t66T1rfqCx2q2Yn+v5p53/qXg0vZrLH+mqjyS2HWXzLV1AcfctP0CQe5XqNSVq0ed9n8E50mszn8pX7PPrI13Py1y+eoF5CjDnUpa68svF/GnmV7XdyjUBpFyyabyEAGbs18pucn9itiEECWrmEv2+tvqGwoNFfq/YSOLfjT5MjRvCiiFf2nHMcxKCerqx1Jl87YI1sAS2phJOC9+0Vd54zgvpRWT3Gdp9vmYSofx9kRUEefkcdxBTwclZoDtFA1Otsc4qUa6EBdNr7y0AB7RdqXbC2mZ8rR1PdU9nv6B89b3SwPPLlK1Lkt65rLpKAgu1ihPureW24tIJ7M8lPwOLszMMhy/gigQnFQDvQe6cyU4ZCV2WcpABmauEqEIhyiub3JdI/VvNTVEmocShMuqLraEYXK8YbhVbSzKIARimh0OkoXerL7uzvQPovdUAUrO84oQW7QNx4w6G5JknFAvIjpbQRg63I3VwyVJZWKPUXyHNRh0OJ7EvBkmOJwKG03P+MdHNu2KvZWFJvbbkn7vwlwGSFW7L165/CCwsnNnpJUL+HUKOqdgkTE+D9B8BvBbSH0oYREKteRAkVoZjgKke0wriLPz2g9nPyvSDgoNaznLnH7ibz/y+AXKz4lhkHy3elKCGw+v/nt9EuOvLAPWjVjjyyZ8PeWhNiG4yRdpcPxCnvua3J7GkK6YOY3aTC4VBloSgCzrA8yWGHhVXL3MFiaplx60CyiutxoNOs79AvRMU1xMcvgObUTP/xP/kufMGjsY7M6gWAVu+dXeY4bMPXHXChRjGcLhD0LO++dmC5I9vI6wQSZZ8vU6TDHparBTmXZb7MuuPbA4pv0ziZUjHrjLQWJ2ECpQvkNIeL/2dr9vJqm6lG7qAS0qmUksMhWFYaXNVRQggUq6o4q5ipd62TxoHiZP0ctU3/PRFHL2mdjh4n5D9CQsVNKmhArinTNnJ5OSoQ4MSu1xjRQ+QKBkpKpCXWbr4Y8cgIcLqjEWhlKneKKQjVSFXASBMg3tdoAesR6qPnWoWR8psQzjgQimQleEyMrCMKOJp5Pj8lkXlVczNDgqnXeTUoKClYwmqohBFKbirW1gQu4BeYdZJgx+HkbTAwjP6P3ji2/Qq1lTUGhDIAo4fnKZhOjNiDjLx3Li2SrBF8NQeljsiq+4yozEWCsSkCSofUmVPTIJxqsomeeREkwzZOGzNi+B4qn5kAGEv9VzCxeVMtaBShyLVygoswM+BfcJShaclwn/VJLX5RuZgCTNxJ8rJgosL208rCjfigrIo7SQOU3YnypmJUt4dP9j6BsXyrVgolGLiKOAbMrzaGEFNCVP5tFf6CRYrWlXteG91oZRaxxNAAWLZgIuUapO4yKJJRsKyDjdH7pBKiSI8oUaWhD/h0Bs3/QcubGdFCP6USdlIAuGy7a7C31exC1eVpBmgQFXZfWotzHNSMlPR70x9zqsVrBeINWAKYhBrq4tTqaStvBQsCtpPblSrqV0z8+IgCSlrqkVFtG1WdYGuA1/o66BnFgANGyAJtZQnEristn/RpHaF2wTQvT9go3dQB5BdBAZfVQYsWSmr3GEXiERP8bVO66JG3AUp7r++2XubaF0Sm/rnBebrmrgvrHQBJErV+ShmKiqthcXMDUwhIEddcfZVdG0jxzKahIGDSgk3FBGaiuIZ4yi1i1Ala5BeQQOM6nDnY48STesEdzwq9fIVd4xfPn7OPwibmSBhKZsN+vkoP5PSsd7uhYZ3h7oSSh9pg4Qq6r7rVWI40qfoKRIHwKS9GmwG6LfcMRfhMAOV/sinhYKtq/jPD/3IkKb0wFcoCy3ixh6KIXV/PfAWGPEbpsUOmuAlLoUHQRxMajv3MSDLICojR4tSq+e864i0tlJ7AlwGNNpEdTdQASug5FQGDTTG0BJLai18BpgzMMpJq8S6RT1qIuaG87bli9WGeTzqp+vaz0xzkGgceIxsgEHM/KOBrnPXQxz2ZnFp55hDqANnG01Y9TO1xohkB4i6yB1jquierEDVZ63xHRZKloGfVR5k4pM9gr9gA17xAq7C/sQHDcK0n2JbhxxdkdbNO6iqK+SXle6Fo9cIYT1gJFtp6QRIWwEuEENKWdfBCLnDQkDyyyt7OR2lwyS7NgRPjIxoMVmIJI0NN8Vxmmx0oaWOc23NwFWo/qHOwcBh4Zmm5E6u+pwbZdrojYSgC7BUwG9QOIEm3vhWVR9kcWCAKRdaK65qSceqOpKqS74NKPQb6LKxcRhWh+FC8RA8P/TYAYm4hBuccVDl6wGXkkr9r5XzrWkD1x5UhGApIssBKQbMC77ZuGbj95FLHDD6CpIsoGMrrnHH0tunMNJGRzoRCM1U1/K4OFYm4VwLZ9S5BSn4YvKgxDsvgP4GJcPY4qiKGLMek05UUpUdu3ILDMrUrAGuXI2Vyp2F9LU284jUA0Vi39UeEmLXx7MqTiSvRUnnTEIbZMuqOegZaR6YRcNkxYDTnkphmpoHmFSQexbj2LxnrKKbwwa7IvcYhcZWNOg5u1qkWHFTBoN5078/6DUaHgm93ETYbCKusVLWapX6Dsk5vTpGSuBIbnTAfRqcV9JRG5p2dRbaHu+0szvDMYqU92lT3aArkWhXZpZ4qEUMXv5dP0GgBtLPd45TUDxdD4CJVAA75p9Bm1Y/g/H4XZm2nyTd2pSnn/TRGxWhU4vz3ttUjY1GgJjDsh3sMX4/4iBUQ9EySuKvHSt/LjCjiW6yULtSqxwWddoOB4BWGugRTFq65sTcjU56+2Y/uVcpCj14E5RZLtHpPlRaWbEDOzgR9zbv7dEPQ6P2k++fYEi49RGUsRI2QNBJ2FlaklhjyWCgtVmY9FCboEK2fm5RU0sTGKIW2Ed6X8uhRhJZ68Wp1jeovhrQWFvSR9KJV/KZuMS99CIIHH+a1NCpExzvsK0TNgnL/3UvQ1xabQ1zBJnU9nwNX67RMCCmGBUnHeCBPtkhkScC2GzUwnFm1CewGN7ic8CrPJ3y308DYxG52nbZgtiQn930TJBfkiZik81RG+BVipCorhnPneKzCjQdASB0PLMdYD6lmEmXUBU1u6buJTtqJ6KyHLeC8QaYbX406yTbml+84iPjw3uHGA+GBfQhECHPRfDgBXtjY6aaNbeTOi4t2veiAdBg/8glwIQqKD0EAfO47K6edAcDTzT1TNqpE5xT2DEFIGNu1Hu0UZ8aLZNYBxCCNtpvt6Ijtx/VGTnXDHwWuPUoUZtn6DRXwu1d0hmdlYLWceC5vUMY/t+BLNEns7Ap7Q+VVNf6RgdsQ9KZYac6LD5a05Yv74rUJGgLmlRSRngRGcUQY6omemu0taMR0Zo1Y8ETQN8oaMP/37Cv9dZtcz7BoNlNfExjRPMTBn8/Bzy+yAnDis8zoenImt8qCVDMHdbP7nFfnx2GQpnT4s0awP0TOOroBN113Izy2XzjaP5nvrv0ZvRFHqYWuKbDLnV8Q6vylPneaOZDh84G2krDZ7cac6ADEAMGVrhYONngW+e3Ex5ywUVzhG1+Vcllo1VsfBTPdxM3P/5yk0gDuXFonddPjROKpGDh5u1w59m9ccRiok+HO4v07l6tLUiw4/FHWrluDc2nw/N2ATMh/F0ifCTfS+BrzvU7VSOrN+sd+TiIhWhNtR2eE62/+0hgKZ51G+GcT+21NySDEdtOPHB7OPAetTkeNuY2giOB5uCruByUyWyznj6ev+3pMD5QFpqny2pIsvC8llOHHjRIBUOvSLdIre9fUahqPPhGH/Q9dSoqEyi+tSYsU2NERITZoahEv9aOqdEJy4+x8Z0q8jgbPJpX14rIP2PjdMGsOShKv5L0eq2nzQ+D7vDw7ztfW9T6pit6MryDiQ+NVmlfU8KCpzgdJbwGWuwnONNMzFyXc/8CxiN8aA==")));t=T;f=1
for c in sys.argv[1]:
C=c.lower()
if c in t:t=t[c]
elif f and C in t:f=0;t=t[C]
else:t={}
print""in t
```
This is a python program that expects one command line argument, the `word`. From the list of words I constructed a [trie](https://en.wikipedia.org/wiki/Trie), zlib'ed the argument and finally encoded it with base64. If the word is in the trie, the program prints `True`, otherwise it prints `False`. I wanted to create a spell checker that has 100% accuracy.
I could substantially decrease the number of characters, by not encoding the zlib'ed string (specifically, zlib'ed string is 1113 characters shorter than base 64 encoded), but I wanted to have a code that you can copy/paste directly.
### Examples
```
$python check.py colour
True
$python check.py Colour
True
$python check.py coLoUr
False
$python check.py color
False
$python check.py Color
False
$python check.py I
True
$python check.py i
False
```
The trie is traversed with characters of the `word`, each time getting a new trie from the key of current character. If the word is in the trie, then a `""` must be present in the final trie.
### Ungolfed version
```
import base64, zlib, sys
TRIE = eval(zlib.decompress(base64.b64decode("eNqdXEF24zYMPY43XHTdG/QYskjbGlGUSlFONH25e8cehySAD8rtLPIyji2JIPDx8QH6n9Nfpz//OZ3+/OPLnLrXr+bUP36Ljx/z48eafzze+OufOaX83uHx2/3x4/nb8w97ea85ueqDv/57zpfd8vuffzW/r+LIfezjf7Z6z/Xxe5dvF+o7xfx5Bx/A/L7v60qXvMhyOSsX6fLb8usDfcmcpmyNsrBAV/f8oH/89yPfcpd2LUvo8vPs4CLVcgJZ8MtC+YIhP5plb4lip+b8yDe48l9vWfMKgF32fK+ULTqJ7bjRzbvSG4Al/f7D8vjvQs0T6+t66T1rfqCx2q2Yn+v5p53/qXg0vZrLH+mqjyS2HWXzLV1AcfctP0CQe5XqNSVq0ed9n8E50mszn8pX7PPrI13Py1y+eoF5CjDnUpa68svF/GnmV7XdyjUBpFyyabyEAGbs18pucn9itiEECWrmEv2+tvqGwoNFfq/YSOLfjT5MjRvCiiFf2nHMcxKCerqx1Jl87YI1sAS2phJOC9+0Vd54zgvpRWT3Gdp9vmYSofx9kRUEefkcdxBTwclZoDtFA1Otsc4qUa6EBdNr7y0AB7RdqXbC2mZ8rR1PdU9nv6B89b3SwPPLlK1Lkt65rLpKAgu1ihPureW24tIJ7M8lPwOLszMMhy/gigQnFQDvQe6cyU4ZCV2WcpABmauEqEIhyiub3JdI/VvNTVEmocShMuqLraEYXK8YbhVbSzKIARimh0OkoXerL7uzvQPovdUAUrO84oQW7QNx4w6G5JknFAvIjpbQRg63I3VwyVJZWKPUXyHNRh0OJ7EvBkmOJwKG03P+MdHNu2KvZWFJvbbkn7vwlwGSFW7L165/CCwsnNnpJUL+HUKOqdgkTE+D9B8BvBbSH0oYREKteRAkVoZjgKke0wriLPz2g9nPyvSDgoNaznLnH7ibz/y+AXKz4lhkHy3elKCGw+v/nt9EuOvLAPWjVjjyyZ8PeWhNiG4yRdpcPxCnvua3J7GkK6YOY3aTC4VBloSgCzrA8yWGHhVXL3MFiaplx60CyiutxoNOs79AvRMU1xMcvgObUTP/xP/kufMGjsY7M6gWAVu+dXeY4bMPXHXChRjGcLhD0LO++dmC5I9vI6wQSZZ8vU6TDHparBTmXZb7MuuPbA4pv0ziZUjHrjLQWJ2ECpQvkNIeL/2dr9vJqm6lG7qAS0qmUksMhWFYaXNVRQggUq6o4q5ipd62TxoHiZP0ctU3/PRFHL2mdjh4n5D9CQsVNKmhArinTNnJ5OSoQ4MSu1xjRQ+QKBkpKpCXWbr4Y8cgIcLqjEWhlKneKKQjVSFXASBMg3tdoAesR6qPnWoWR8psQzjgQimQleEyMrCMKOJp5Pj8lkXlVczNDgqnXeTUoKClYwmqohBFKbirW1gQu4BeYdZJgx+HkbTAwjP6P3ji2/Qq1lTUGhDIAo4fnKZhOjNiDjLx3Li2SrBF8NQeljsiq+4yozEWCsSkCSofUmVPTIJxqsomeeREkwzZOGzNi+B4qn5kAGEv9VzCxeVMtaBShyLVygoswM+BfcJShaclwn/VJLX5RuZgCTNxJ8rJgosL208rCjfigrIo7SQOU3YnypmJUt4dP9j6BsXyrVgolGLiKOAbMrzaGEFNCVP5tFf6CRYrWlXteG91oZRaxxNAAWLZgIuUapO4yKJJRsKyDjdH7pBKiSI8oUaWhD/h0Bs3/QcubGdFCP6USdlIAuGy7a7C31exC1eVpBmgQFXZfWotzHNSMlPR70x9zqsVrBeINWAKYhBrq4tTqaStvBQsCtpPblSrqV0z8+IgCSlrqkVFtG1WdYGuA1/o66BnFgANGyAJtZQnEristn/RpHaF2wTQvT9go3dQB5BdBAZfVQYsWSmr3GEXiERP8bVO66JG3AUp7r++2XubaF0Sm/rnBebrmrgvrHQBJErV+ShmKiqthcXMDUwhIEddcfZVdG0jxzKahIGDSgk3FBGaiuIZ4yi1i1Ala5BeQQOM6nDnY48STesEdzwq9fIVd4xfPn7OPwibmSBhKZsN+vkoP5PSsd7uhYZ3h7oSSh9pg4Qq6r7rVWI40qfoKRIHwKS9GmwG6LfcMRfhMAOV/sinhYKtq/jPD/3IkKb0wFcoCy3ixh6KIXV/PfAWGPEbpsUOmuAlLoUHQRxMajv3MSDLICojR4tSq+e864i0tlJ7AlwGNNpEdTdQASug5FQGDTTG0BJLai18BpgzMMpJq8S6RT1qIuaG87bli9WGeTzqp+vaz0xzkGgceIxsgEHM/KOBrnPXQxz2ZnFp55hDqANnG01Y9TO1xohkB4i6yB1jquierEDVZ63xHRZKloGfVR5k4pM9gr9gA17xAq7C/sQHDcK0n2JbhxxdkdbNO6iqK+SXle6Fo9cIYT1gJFtp6QRIWwEuEENKWdfBCLnDQkDyyyt7OR2lwyS7NgRPjIxoMVmIJI0NN8Vxmmx0oaWOc23NwFWo/qHOwcBh4Zmm5E6u+pwbZdrojYSgC7BUwG9QOIEm3vhWVR9kcWCAKRdaK65qSceqOpKqS74NKPQb6LKxcRhWh+FC8RA8P/TYAYm4hBuccVDl6wGXkkr9r5XzrWkD1x5UhGApIssBKQbMC77ZuGbj95FLHDD6CpIsoGMrrnHH0tunMNJGRzoRCM1U1/K4OFYm4VwLZ9S5BSn4YvKgxDsvgP4GJcPY4qiKGLMek05UUpUdu3ILDMrUrAGuXI2Vyp2F9LU284jUA0Vi39UeEmLXx7MqTiSvRUnnTEIbZMuqOegZaR6YRcNkxYDTnkphmpoHmFSQexbj2LxnrKKbwwa7IvcYhcZWNOg5u1qkWHFTBoN5078/6DUaHgm93ETYbCKusVLWapX6Dsk5vTpGSuBIbnTAfRqcV9JRG5p2dRbaHu+0szvDMYqU92lT3aArkWhXZpZ4qEUMXv5dP0GgBtLPd45TUDxdD4CJVAA75p9Bm1Y/g/H4XZm2nyTd2pSnn/TRGxWhU4vz3ttUjY1GgJjDsh3sMX4/4iBUQ9EySuKvHSt/LjCjiW6yULtSqxwWddoOB4BWGugRTFq65sTcjU56+2Y/uVcpCj14E5RZLtHpPlRaWbEDOzgR9zbv7dEPQ6P2k++fYEi49RGUsRI2QNBJ2FlaklhjyWCgtVmY9FCboEK2fm5RU0sTGKIW2Ed6X8uhRhJZ68Wp1jeovhrQWFvSR9KJV/KZuMS99CIIHH+a1NCpExzvsK0TNgnL/3UvQ1xabQ1zBJnU9nwNX67RMCCmGBUnHeCBPtkhkScC2GzUwnFm1CewGN7ic8CrPJ3y308DYxG52nbZgtiQn930TJBfkiZik81RG+BVipCorhnPneKzCjQdASB0PLMdYD6lmEmXUBU1u6buJTtqJ6KyHLeC8QaYbX406yTbml+84iPjw3uHGA+GBfQhECHPRfDgBXtjY6aaNbeTOi4t2veiAdBg/8glwIQqKD0EAfO47K6edAcDTzT1TNqpE5xT2DEFIGNu1Hu0UZ8aLZNYBxCCNtpvt6Ijtx/VGTnXDHwWuPUoUZtn6DRXwu1d0hmdlYLWceC5vUMY/t+BLNEns7Ap7Q+VVNf6RgdsQ9KZYac6LD5a05Yv74rUJGgLmlRSRngRGcUQY6omemu0taMR0Zo1Y8ETQN8oaMP/37Cv9dZtcz7BoNlNfExjRPMTBn8/Bzy+yAnDis8zoenImt8qCVDMHdbP7nFfnx2GQpnT4s0awP0TOOroBN113Izy2XzjaP5nvrv0ZvRFHqYWuKbDLnV8Q6vylPneaOZDh84G2krDZ7cac6ADEAMGVrhYONngW+e3Ex5ywUVzhG1+Vcllo1VsfBTPdxM3P/5yk0gDuXFonddPjROKpGDh5u1w59m9ccRiok+HO4v07l6tLUiw4/FHWrluDc2nw/N2ATMh/F0ifCTfS+BrzvU7VSOrN+sd+TiIhWhNtR2eE62/+0hgKZ51G+GcT+21NySDEdtOPHB7OPAetTkeNuY2giOB5uCruByUyWyznj6ev+3pMD5QFpqny2pIsvC8llOHHjRIBUOvSLdIre9fUahqPPhGH/Q9dSoqEyi+tSYsU2NERITZoahEv9aOqdEJy4+x8Z0q8jgbPJpX14rIP2PjdMGsOShKv5L0eq2nzQ+D7vDw7ztfW9T6pit6MryDiQ+NVmlfU8KCpzgdJbwGWuwnONNMzFyXc/8CxiN8aA==")))
trie = TRIE
first = True
for character in sys.argv[1]:
CHARACTER = character.lower()
if character in trie:
trie = trie[character]
elif first and CHARACTER in trie:
first = False
trie = trie[CHARACTER]
else:
print False
if "" not in trie:
print False
print True
```
### Construction of base 64 encoded, zlib'ed trie
```
f = file("dictionary","r")
END = ""
TRIE = {}
def addWord(word):
trie = TRIE
for character in word:
trie = trie.setdefault(character, {})
trie.setdefault(END, 0)
for line in f.readlines():
l = line.replace("\n", "")
addWord(l)
import zlib, base64
compressed = zlib.compress(str(TRIE).replace(" ", ""), 9)
print base64.b64encode(compressed)
```
[Answer]
## PHP - Bytes : ~~2892~~ 2811, False +ves: 0, False -ves: 0 = Score: ~~2892~~ 2811
```
<?php
preg_match_all('/(\D*)(\d)/i',bzdecompress(base64_decode('QlpoOTFBWSZTWaILilgAAfKNgH/gACA////wYAhL71trq71ortD2Kw3J6ZeWvTF3c6Iqf6JkTCYTSNA0jU0Ip4AQJpJptVPE1MAip+DRU/VPTRNDQAAGqexCJpMp6mlPUepsp6jJjDIwJpgTIYmjAanoCBMpMJ6mptQMj1jt+3vz889/XMld2kXPhiMgQJwBAfi+ycsvZ/qwWRmQhcQKUtRAd1Ml+2zpBLJ53aoUhCPzfLzu5B1M9wnUYtgN3XbcTTBwP2QBBNCNgoD1wqkkr1osQpQHMkCUltCBliCKmXjaYDDfmTdJGizbGn/jWpIrDGpStVeTiOoFn8ASoSseHaSYC7Iau2KMXZxZB2YWpMqFlT2CSKmkxEJM0V8ag9ed+DsN1gWzRpewuHHh4x4i3rjLGY3I/WC4K6a3BuLkQ69xFrEiu9q1OzrY6cFKZVAxSSz2kdqQkN6S7rrFy1jY9434MVTgwnycz59BHrxqJuDrqSSuplpG3a2b7wzptRP6DFxkZtHRNEk0Kvylx7uMCR5PfcixfGSLa9vGX0uhpyJ8yr5O9dVp/rdzjGxl1VknpS1qNRj7DXd7j2jB98PSQbMCRNp6WowFajA48z07uAXxnHJBfe+uaUQYUWGuvHgUyUgJ3Uplz2pezKQfKyid0FBGcDTSpgrJnCLni6Xxm+FOpkxqYUl6EwcTGr+mLHv0E9ta1EEHnlvQ0W7pFSedZSNRiqYYrwu1V1rhIgVGXnVEiVl1SaIJn4VGIhkNcokNKUEAZ3V6lkt3U0zGOCJ6sgewrPTdrR2XdvNM5VoQ2/i6Dwg821JoHMEgvxeNEoeZC3MlWCqrWsN11tXs4C2hywWYbh66y8nqQEIVGMjLCxflqTuiQ6xi+Lc5qol6G4jOrRL1qmudnsZ5YEsIhyGlxLhYcyrYwd6aGxjA9i4sKH4RMkQWyYfwOY9GvF8dNrPHeq7Duob6HI3FVOH/ea8Yjd0UxEhMAtIJDwripa08CH9Ow12wXz0o8AnofjobjMfb9vIM0Yg2nYYbHImZt0CtoLq3UNUDatyIl1+HxNa/yeOM3HfeeJ/2yI+imsSJbRBXo5UBwfsKKjEbShUG0tnGwfENhPuAUdu/I7eorWqjDsr0+mR1vUut48dR86azlqOphtcjDuwwCriVSUCUS/10+6/qWJrbMPDmyYgfcMpHvaq69PpVyGTsnz+nXn6nHy/o9Pk0QXP2hjoYJxQtxqRapXzr7rrbEu9ybP5Tt7QJs2KujKagvI+2Po8QDCpJpzE0vwQK8RF76Sk4yh1Dq4wMUVu1u6O6nmsHrXH3xwbZlXp+2Gi/VUckLIJHYnujg++hudcW7dJv4rvZPITTbyriWGh9XQFtLDPKqWF7AuAj56PPc1NKS1EFYzYlo8IkFyo3xVTIonBgQcnc+7M5xC0aFfDW3CjUaohQuN1sgMzSUXM7jxXyOb9YdFrNZ5ziw7lIRojbKfHFi7ZcMdAiCSgVCKmZ3kFRGZ2j71ONKrE4RiKGG0xc2rBVCxBzqWgH2eHHbfTz3QDyajdrXoRaxamrtDWmfAlW5xzlSAeJl/QwtnVBcFCJv0hCF/M8vO3tGerpBV15zbTK59//m2tFrreDfNKkrYM1Y9vWT9cl2DlYRu964+Hlkg0uCbmLMSRK+8sx71osBTZ3ZLFKK4MVn1phiyDCaIYXwi0XNMieiCMyhpeN9oWDWGKUz99dVZCM3ZA50AwIDDYHnCFY1TKkFgRgz1OJsVAZCTaGXtj8qUlPLafUxT5xFqY2QclwVpdKISdQiLFG2gTZUiwr8a+vghqNxC8eAtvrlyFFYtP1dvjd9Zj5zEFF9jSSMsRHGRTIrePWqiaF5n8Ph1+mukR8L2WNnxb/sYDuSG5ZHlNMgPaCzf4+mddOSwIq/tm8ozhGUPWmCpdcyx49uLc4HWJHrQ0gAxdxNY8uwCOzp6PuNEkRw3utTsw3odJwKVJ9bcb0EHheguSbpLhgx5k1qlBB6STiAsxkcXG3hDyigqo8morvnIL1mUSyoSmbFFBDTLqA92RaF9+sZsd8ITAzAYpJRaRbTa1CiPBaRAoKWeOIstgil1kEE1O1aC1QHUUJoJ0JSLBHBchSDDj2ZVDjGBG8PNCJeBrM01eV6IfXwRjV8HmFxiYfLPR9FzRsnQZNGItcSimQWNDA6YGL1ouYsyduqOwjjh27I40WU0vloEn6dKRMOjDxl4QiaRLW4EeLP8ycLxC49pbri5Zs17TZSJCkPfTgH7iNPiqgcZmDKNgdEYwAuSjJFIZosePcg8l+I/rFOfs5khIuUHYpBlo1R8oyZr6eth30STIGQitOBYiKgl7oGd0RWdvw3kx8lCxsse70IUvx14HjKbIEusdZIjdQN9TS72jt3ZoRSotFa4ky3iT6Hepk/RErposPd69dxfRk0Pw499oGe/mJGLImBf9JPyfKVBjtVnl0BxSSCzsJ+fDGhARYHs0pOb9Myi9Ig7+5tTbno8Q/zlaIcngPBqAKi4FRMwPy6uqcoIIyCoNjNkDb5dnqoW7pWqqC7ODP95zHrUUgQTchXQdmj3cPWQKbATBPwRrs/8LuSKcKEhRBcUsA')),$b,2);$w='';foreach($b as$p){$l[]=strrev($w.=$p[1]);$w=substr($w,0,strlen($w)-$p[2]);}echo 1-!array_intersect([$argv[1],lcfirst($argv[1])],$l);
```
Ungolfed (slightly):
```
<?php
$z='QlpoOTFBWSZTWaILilgAAfKNgH/gACA////wYAhL71trq71ortD2Kw3J6ZeWvTF3c6Iqf6JkTCYTSNA0jU0Ip4AQJpJptVPE1MAip+DRU/VPTRNDQAAGqexCJpMp6mlPUepsp6jJjDIwJpgTIYmjAanoCBMpMJ6mptQMj1jt+3vz889/XMld2kXPhiMgQJwBAfi+ycsvZ/qwWRmQhcQKUtRAd1Ml+2zpBLJ53aoUhCPzfLzu5B1M9wnUYtgN3XbcTTBwP2QBBNCNgoD1wqkkr1osQpQHMkCUltCBliCKmXjaYDDfmTdJGizbGn/jWpIrDGpStVeTiOoFn8ASoSseHaSYC7Iau2KMXZxZB2YWpMqFlT2CSKmkxEJM0V8ag9ed+DsN1gWzRpewuHHh4x4i3rjLGY3I/WC4K6a3BuLkQ69xFrEiu9q1OzrY6cFKZVAxSSz2kdqQkN6S7rrFy1jY9434MVTgwnycz59BHrxqJuDrqSSuplpG3a2b7wzptRP6DFxkZtHRNEk0Kvylx7uMCR5PfcixfGSLa9vGX0uhpyJ8yr5O9dVp/rdzjGxl1VknpS1qNRj7DXd7j2jB98PSQbMCRNp6WowFajA48z07uAXxnHJBfe+uaUQYUWGuvHgUyUgJ3Uplz2pezKQfKyid0FBGcDTSpgrJnCLni6Xxm+FOpkxqYUl6EwcTGr+mLHv0E9ta1EEHnlvQ0W7pFSedZSNRiqYYrwu1V1rhIgVGXnVEiVl1SaIJn4VGIhkNcokNKUEAZ3V6lkt3U0zGOCJ6sgewrPTdrR2XdvNM5VoQ2/i6Dwg821JoHMEgvxeNEoeZC3MlWCqrWsN11tXs4C2hywWYbh66y8nqQEIVGMjLCxflqTuiQ6xi+Lc5qol6G4jOrRL1qmudnsZ5YEsIhyGlxLhYcyrYwd6aGxjA9i4sKH4RMkQWyYfwOY9GvF8dNrPHeq7Duob6HI3FVOH/ea8Yjd0UxEhMAtIJDwripa08CH9Ow12wXz0o8AnofjobjMfb9vIM0Yg2nYYbHImZt0CtoLq3UNUDatyIl1+HxNa/yeOM3HfeeJ/2yI+imsSJbRBXo5UBwfsKKjEbShUG0tnGwfENhPuAUdu/I7eorWqjDsr0+mR1vUut48dR86azlqOphtcjDuwwCriVSUCUS/10+6/qWJrbMPDmyYgfcMpHvaq69PpVyGTsnz+nXn6nHy/o9Pk0QXP2hjoYJxQtxqRapXzr7rrbEu9ybP5Tt7QJs2KujKagvI+2Po8QDCpJpzE0vwQK8RF76Sk4yh1Dq4wMUVu1u6O6nmsHrXH3xwbZlXp+2Gi/VUckLIJHYnujg++hudcW7dJv4rvZPITTbyriWGh9XQFtLDPKqWF7AuAj56PPc1NKS1EFYzYlo8IkFyo3xVTIonBgQcnc+7M5xC0aFfDW3CjUaohQuN1sgMzSUXM7jxXyOb9YdFrNZ5ziw7lIRojbKfHFi7ZcMdAiCSgVCKmZ3kFRGZ2j71ONKrE4RiKGG0xc2rBVCxBzqWgH2eHHbfTz3QDyajdrXoRaxamrtDWmfAlW5xzlSAeJl/QwtnVBcFCJv0hCF/M8vO3tGerpBV15zbTK59//m2tFrreDfNKkrYM1Y9vWT9cl2DlYRu964+Hlkg0uCbmLMSRK+8sx71osBTZ3ZLFKK4MVn1phiyDCaIYXwi0XNMieiCMyhpeN9oWDWGKUz99dVZCM3ZA50AwIDDYHnCFY1TKkFgRgz1OJsVAZCTaGXtj8qUlPLafUxT5xFqY2QclwVpdKISdQiLFG2gTZUiwr8a+vghqNxC8eAtvrlyFFYtP1dvjd9Zj5zEFF9jSSMsRHGRTIrePWqiaF5n8Ph1+mukR8L2WNnxb/sYDuSG5ZHlNMgPaCzf4+mddOSwIq/tm8ozhGUPWmCpdcyx49uLc4HWJHrQ0gAxdxNY8uwCOzp6PuNEkRw3utTsw3odJwKVJ9bcb0EHheguSbpLhgx5k1qlBB6STiAsxkcXG3hDyigqo8morvnIL1mUSyoSmbFFBDTLqA92RaF9+sZsd8ITAzAYpJRaRbTa1CiPBaRAoKWeOIstgil1kEE1O1aC1QHUUJoJ0JSLBHBchSDDj2ZVDjGBG8PNCJeBrM01eV6IfXwRjV8HmFxiYfLPR9FzRsnQZNGItcSimQWNDA6YGL1ouYsyduqOwjjh27I40WU0vloEn6dKRMOjDxl4QiaRLW4EeLP8ycLxC49pbri5Zs17TZSJCkPfTgH7iNPiqgcZmDKNgdEYwAuSjJFIZosePcg8l+I/rFOfs5khIuUHYpBlo1R8oyZr6eth30STIGQitOBYiKgl7oGd0RWdvw3kx8lCxsse70IUvx14HjKbIEusdZIjdQN9TS72jt3ZoRSotFa4ky3iT6Hepk/RErposPd69dxfRk0Pw499oGe/mJGLImBf9JPyfKVBjtVnl0BxSSCzsJ+fDGhARYHs0pOb9Myi9Ig7+5tTbno8Q/zlaIcngPBqAKi4FRMwPy6uqcoIIyCoNjNkDb5dnqoW7pWqqC7ODP95zHrUUgQTchXQdmj3cPWQKbATBPwRrs/8LuSKcKEhRBcUsA';
preg_match_all('/(\D*)(\d)/',bzdecompress(base64_decode($z)),$b,PREG_SET_ORDER);
$w='';
foreach($b as$p){
$l[]=strrev($w.=$p[1]);
$w=substr($w,0,strlen($w)-$p[2]);
}
echo 1-!array_intersect([$argv[1],lcfirst($argv[1])],$l);
```
### Old data
I have applied my own compression before compressing with bzip2 and encoding as base64. My compression reduces the data from 5942 bytes to 3662 bytes, then bzip2 gets that down to 1997 bytes and base64 increases it to 2664 bytes. bzip2 without my compression gets it down to 2852.
The data used to look like this:
```
a0bout2ve4cross4t0ive1ity7dd2
```
Which translates into:
```
a
about
above
across
act
active
activity
add
```
etc. The example 29 bytes expand into 45 bytes.
### New data
I reduced the compressed size of the data by reversing it! I saved 64 bytes in the base64 representation and only added 8 bytes to undo the reversal!
Then I just use `in_array()` to find the match in each letter case. I have chosen to save a few bytes by not checking for all uppercase words.
And, by the way, if this should somehow have the lowest score it won't be selected as the winner.
[Answer]
### Python 2 - Bytes: 3170, False +ves: 0, False -ves: 0 = Score: 3170
```
i=raw_input()
print[e for e in'eJw1lwF64yoMhK+iqxGbOGww+AFO6uXy7x+5+7W209QIaaQZiWDhUc8x6ydaWFrtfY450ifqlsZlYV0tPFtI6xyxWdhCKjPOOltkReKbnGctfFM2vgvrNb/h6hb2Wc8yLJS5zq1ds45XbLN/uV3z0oprvBKLrpF2TB1HDG0emY8tzhjmPvdLNtbZ3B8Lfb4t4F5YeGJ8jnMvFtjPHuFxzR7n8tZ2E5/Ke/Z35J2XPeLEDayHc6TnmSc+rHNtte7zFbD9rGy5ERgOrVqc63f2tMY+OxYIfI5vjMUeiSBxaLx0reESWtEeGZdmjOusPGvl+Z0n39fA27gMKgmXQOnNesy1MlvjJQyNkYlu4Ms3z59JLC2U5TXlGHhyvXU9A67EAIozrRu37TWm8LuBrd8yz06sZ8qrzPdUItnkR05i9bIlvKNDM8vKnsdsHkzkV6i0mLWiNUeSwJaXLbGMFlgyTr5ug+zb8iLvILoIVjwJXY4exM+HtLxjmfKBq/GxLjWHQeSJ92vt0ZbUFoWMQzmwYfzgfyRDKoC0P24QQUaRdUpg1UUtaG19PmMUpGQrK1dxGaTrbJOFe5w7uRzhgf19r2Xuh6ppp6yGHqdSWdY0Ev8rI5Uz8mg1KzHcKcI7N0XPJtugXhT2VMFxAcPZCBSnbWmh4yYxEMt5zONO+LDV0QGcVk8Qfc+TbKnybVVKF0prLrBFyB0qxyNSeJ2SxZkL27ketiYq8xkBcfBMy5lxxR3DLwXQBplaquAj82ul8Gubp4L/Fltb+ALpPpXUBB3EonrIh3N5e2FfFgOVhsV8ediAzveqGIu8FbSNRZxY+GLbLHrVqeAsCvmWFgJ4BTwkOXE/ZJJIItT9U0Xf7eW6Ef87QzYvJpCx2Jdw8PhQILGoihWkygB4uZAHiz9BuxLd9ajrpb/3VNylGZTRucRjgOWAd7EtCTAPZQwsu2I9stI2WtxjZvkV7RnICm/ARZGcBXsi8t2TNNs+b40iwgnY9lRByniee8ie8vm1p2Og9TulJFIrz7MkSkFc8uVs/2PPHDaVatVFZlSl1QXQnpXilU5QefxzPCSjuLCIjGkjFRE7bYu6KRhqCP9+qD17Ir0SGxQjxr98ZOMk1HUjHL6vqtVEBOdN96L0JjgclWPJGR9tCxAGOSrSsC1SWs70HHfIOGxLTwViW6ZkIapt1bVs/rq+PoB0I6HrM7hRPu23GonWt36RVeX4V8krJKlf285iLiL5KSD33Vkp9hVul1RJuqrNkTvtnsfrcgX/XKyoMx/8NbRHuZWwCD2hby+Ri7KTYeRv2Ks+aA4SC9QvSbR3VcoUi/uRBkFrt4x+Qhx74Wgj64WuxVoAf52uiY+gXjQMITP2CJaelvZDekOjo9R+Ga3GMUel8iocUhT6d4NJqdBTWdxnxpYlWGN/YqY6/9QHHLU/p1RyP6hBe8cosr6TUih3JMj0oHch/ekZb5n8GtlRR0EgWScPkeTu8BHTJeWZfy/L0p3wBLXimdkmyXWz4jxdokOru9dZTrQgEXE+heSYb7X3ebg2DJXLcDZYlgtFu6gPve+2gfHv/MoMMmM7AkMnklyr+URV46XWQz2rPQvZcUsjWSEV6tRdhapSS4vW8tr+UIk498errranVS0sv0mzazmRIO4eyVCb+7G9ruQUaOgCUpdCEZa3bmotxavFpaffiiZxd53n38S2nyhjR99IxX5Zca54y3YnxJ8ifQjSTnV/dEIuUY0PET3dPLtFY347v0dQe/kZVpRlr1qM1CnBlnoRars12NuvT0dDr36tnELA6gP//0iN60LHtPqc/GD0qddIjdWUDW2xqimNwqrOqdpVd7XdDXuVJRdxOcpOqlhTHzHGCDvC5vlKgAZHWe49h7+UNO7Dm5Cazz0fvUge09viyV0Q1yp1vnvpbGoejHAoRvMao9va8aqjIh3Hy44UgAAAF5enKGRk523ot48YuqB6B4qpSQIC352T26rGwe4UYhy3x9okC46cNHZk9cTjzKSq332/9yTER4CjxK9SPZBb70AaRwaRqTNhaxEQuslo+mj3hOJWxk0JLWbQWid53ZXBqpjrUMT1I1APujFui8LqDwfg8Bj23+my2N0hZia0m+3IUQtrqjf6l4rCmrdokReGix9Z9RbVE5aKUK5Ut7Nj1+y6k0UKfB5S10Pye/C6NOombzibN2vNEuBdrClGNlh/C3JTI2+V/R5KCr0EObR2PrTF6gzOoqImjs5bKIS66ZCmsj+7X9aXVwV32pFD1yuq3OGK4qBhVw0IjAjzV9iGv9c+rpTiC1H+WH+FVdoP48RnqDM1yoV2aLGmJhCLNBBXl4NKBXNNmENDjgKupxoVN+VEZ5yvdUGtUAt7ZN9XcOaP46ca8cGibLr5BOfnCD8A0Hz/Ruuux8pP01Tds1xJ3tX6XuUo/456hZNML/qarnkIy6eDtEedffZ405snp58OnlIkzZYgQpNEhAy9WOI9/i8Jf6OPIjzVSHldMerEBbnKZp0JC00ixbQBdSrXJnhzD0ziTL7HQfzVmU3KfJ/cBBcP5ouqId81ogne5oe682bmuYoSGsTPI63Wz4eEaD7YUVAtC+TRMULFpJli0zT/bxT3ktEYchy327MdTeXNgVCVr61Xu99+/+q6cJ8/yQaHQefArpgy86a8zvGTukL7nXCSTi5ObAR7vNRGhioFHohpkhaOOQr095hyk2y7R2OIlPo9rjaxRqfbkVb1QHqdoRSaGyic6LK+V28FxUePek9xsHtqllDfQEWZdFNxn5nmyR3G5RwHjlMOfjVFcJgwZ+G4mIbPomOR9/LYhCo+6TCe7TxMs4mf0s7gF9L+iXjjiGHmQ07RbfvonGWCZtg3pPGLpsR7l/QIU+aIebfcL/X69krxsNbVR/H3PVLlpe7xzgOK9X35LJf/oZkwktS4JLIypakHNfBD2bw7ssir+Xh4A1Fbk/jpFz7at2rOLH4cXr236OSqCgSgb3PDFPalLtudhH7gtque0GTTKPyXA5b9rfV/GAUQyw=='.decode('base64').decode('zlib').split()if e[:2]==i[:1].lower()+i[1:2]and i[2:]in e[2:].split('{')]>[]or'I'==i
```
The word is taken from standard input, and `True` or `False` is printed in response. The code part isn't very golfed yet. Here's a (somewhat) more readable version:
```
i = raw_input()
d = 'eJw1lwF64yoMhK+iqxGbOGww+ ...'
d = d.decode('base64').decode('zlib').split()
m = [e for e in d if e[:2] == i[:1].lower() + i[1:2] and i[2:] in e[2:].split('{')]
print m > [] or i == 'I'
```
---
After decoding, the long string looks like this:
```
about{ove across{t{tive{tivity add afraid{ter again{e{o{ree ...
```
The words are grouped by their first two letters (i.e. `about{ove` stores `about` and `above`).
We search through each group, checking to see if any starts with the same prefix as the input word and also contains the rest of the word. Single letter words (`a`, `A` and `I`) are handled separately.
[Answer]
**Factor - Bytes: 1342, False +ves: X, False -ves: 0 = Score: X**
```
USING: ascii base64 bit-arrays bloom-filters io kernel sequences system ;
IN: examples.golf.wordcheck
CONSTANT: S "iAlOYCCAE2MARMNA4ICNzwABZAbwhAeGBMIYgDsYAAwIgoQFB/ADCBwX4IrgAOHA/g7YAYiAYaEBgEINgMGZAeGIJI0AwAqePxzLhi7HYgMaY8PLMQAKIOAPMAC7xoEB4AA6+J+zAOAAzxhDBEwaAAYQbHEYYA8YIMFw0DIaDHhA2H4RMAkYAgACGjOCD2Dmwwy2YuDSdMcCZQAkwJ4siYMPFxjQfN0MMIwDPgIBDBDvGSY4M4IAIjYOgoyMxwCOujfje5AL7KFwfGEAiIPBOAABsIDDAR8gBgAjgEUAPng+71kCJoAdBiZw+zA4gAAaILANEBxwg5eBMEZqeAYwC53BgBlYaoMBMAlAUMCgeeD2gQ4rAK7gQce4D/BmEJhfAR48D8QKMxk2CMSP8ObTAHmcB8aemAEyDiOjAJhhwLvGAJhvP7zwgY4D6Ms2cx/A4KcAjgOzY8SbzMFgN+AU1Hwwhjd3MyD3wcNjBGAY3OEZgHAA/AbvfwI3NiEQAoCDOOjRMDP4IGH2EYUoD27ygAd44AyA9+2z33jXDMRAG2xiAQBgDsALgG0O+dgAfwMIXJZHMPKolod/68CJh+HDwNAcwTEGgCci29hsdCAA2IESQPCYg+AcAIABmB3MwAfHIL8v5gSw5vtmEACeA8CQyMc77DzaZmDh/Q/ceEDCHTwA5gPyAAOgAJsPA4GDt2sNt9ULYBb9TRhigJ1OGAA2YOE6/xuzIAA5AhA8wB9swAKA4Abd+Qfwe0C8c+Gmf+QAcX4AQwYwM2A2zgAD/koLsOOAAcIgMA5sO8AC9xN+/AkYAA7UWVCG+QPwwAW8eQEcAMB++H15EBAS0A6/gQHD5QBghkEGkAEQez9i3gP9BB4ZxzABKl48mOANgAcMaPMh4EkI0HgeWBje3zbwQAcAHWaZQS5wgM8HDAIFxBiBn/MGbPMCwzATX+AwQdnECAMQEFgYwuA5xjAAoAAs3AzkGMDPA2MYHtownIGBGU5w0AQAMGAGDBADDgEs0AEzXB6ARGzDgXE4gkaejd2REQ=="
: F ( -- f )
4 S base64> 6247 swap bit-array boa 1000 996 bloom-filter boa ;
readln 1 cut swap >lower prepend
dup "I" = [ drop t ] [ F bloom-filter-member? ] if
1 0 ? exit
```
Run using:
```
$ factor golf/wordlist/wordcheck.factor ; echo $?
color
0
$
```
The approach is based on a pre-calculated Bloom filter. There are a bunch of false positives (misspelled words seen as correctly spelled) so the code probably isn't competitive when you take that into account.
[Answer]
# Python - Bytes: 2294, False +ves: 0, False -ves: 1 = Score: 2304
Code (273 bytes):
```
import gzip
c=gzip.open("b").read()
def d(k):
t={}
while 1:
b=ord(c[k]);s,k=(0,k+1)if b&32 else d(k+1);t[chr((b&31)+96)]=b&64,s;
if b&128:break
return t,k
t=d(0)[0]
w=raw_input()
if w.istitle():w=w.lower()
r=0
for x in w:
r,t=t[x]if t and x in t else(0,0)
print r>0
```
In addition, this needs a binary file named `b` that is 2021 bytes long. Not sure how I can best share it. Suggestions are welcome if somebody wants to see it. Or I can post the code that produces it from the dictionary.
I'm taking a penalty for a false negative on **I**. Bothering with upper case letters, or special casing it, would cost me at least 10 bytes anyway.
The pre-processing procedure is:
* A trie is built from the 996 words in the dictionary (skipping **I**).
* The trie is encoded in a byte array. In addition to the 5 bits for the letter itself in each node, 3 extra bits are used to encode trie structure information:
+ 1 bit for tracking if the node is a leaf node.
+ 1 bit for tracking if the node is at the end of a valid word (note that non-leaf nodes can be at the end of a word, e.g. for "any" vs. "anyone").
+ 1 bit for tracking if the node is the last one in the list of children for its parent.The encoded byte array is 2664 bytes long.
* The encoded byte array is compressed to 2021 bytes with gzip.
The spelling check code posted here then:
* Reads the compressed and encoded trie from the binary file, and decompresses it.
* The function `d()` decodes the byte stream, and builds a trie using nested dictionaries.
* Processes the input word for the upper/lower case rules (all upper is not accepted).
* Walks the trie letter by letter until either the end of the input word is reached, or a leaf node of the trie.
* Prints the result.
[Answer]
# JavaScript ~~4737~~ 4378
```
alert(is(prompt("enter word")))
function is(w){if(w=="I")return true;w=w.toLowerCase();var key='/345I_abcdefghijklmnopqrstuvwxyz',x = "MemsgBtQBIvTGACy7agOz4AQCSkAF3M5IBZVcAmGdMAVAoC6lAE64ARiCk1AYAN1GT4A+G9gA5U1PIBzSBl/ADTLVXAPHFXAL1JqAHLXTYATpKAEAa1Ua4AxUAV1GACXgApqaQCu7agCyAGIABnJkQAPU8gBnUpgHw3gCOY/gARAAEgYCMQAnAAMKBBWQCy0AVGmC4NZcvUQBAJN6UkAargAul1AEx0wBabagBdNIBRiCnABw5KsAFkAM5VcAeKVMAQBcwF0gy1JvACAOVADEyIACpSQBoiAAUSAHAA0oAaGukAMgAnwAOiAE1ABSAAXSq4AzBenACy0GYqACkgC5EAOg8AFzTQ0AdqAFRkggs2MgHlqgDcligBY3IAzYANMtVcAuTAHWGgFp0UgDeYAYdNWMAH4AMg8AHgAQaCgAjEAJpioAqgukCl6iAMVYwAd/ADhQAZQ0AlTzc0QB1fwB3yZ0wBAFpnXACaFAAxQA4UAKjVABWFAE5EFTAKKbqmAIA0RSJsqAEAXIUANMKAN10RUAWfADE2MACo0wXADargE6RwBoiAAYUAGWqwAWk+AOhsgAtalAE6YARSCKkZAKmrgFI4FAXS+THioAgClSYA1NdQAxVlQBayq4AgDNLsupMAQByZ0wBdPSgCvSIB0gCIAVqq4BXmq4A3UjIB4yAGp5v4Ar4UAW1XAK5sNAGmMAD4ANVPQ10gCAOQBSaaFAAxV6awAIBXgAGmNyq4AgD4AFGSACHJUAN1GwoAQBVUFwAqqaQCxAGb08Ae1RpUAQBcoC1quqeQDcjUcgCAU5quAV1Iy6kwBAHPgBwim1XANoA0YClwA0eKgC5MAbm4ACjSADGABdOAAbUANKgB4ANIgAGMgBnwBKMhoAXj4AJgy0AcZB4AMgAnSDZdSYBAEtakZANjAAcxuQBy1VwDipGbuQAdWmnkAQBwoAZVz4AppAqXgBfTwA00xoBZVcALmmhQAgFbRogFhBqqAPapumwAcgBfx6J8AVJqAEAumRkAJOmbLqTAEAqxUAaFVyALsqSAarodhQAgDVSMgBPDtqAEAYmdMA83VJUfAEAXlACsyFAyADogBGIMKAGTo+AGmsAFeQAYyAGWquAWo5AJRrgApIIgBI0VAFtVwB4ADmNyAMYgkAE0gUBirgC7DQCuoGMgDkG1AB0AImYDIAUNkAKXADVwA4q4BeACkUgBRIIgyc0YgCAN0KABTmTAHGQBYrIAO2oAoAkAGrgB0ALqUmkgB+oAcNAFyppj4AQBpIE8gDp2QC1GIATn4AbzdnV1ACAOWquAedXUAIAsNJQAXSqYBZUAKpquaIBZiqRpgCAWQAcvIAbUAMTJBjABUNkAEgikAKJP5QAgDc00rNlqrgCAMqZaq4BAFjAAbUAKjZABUwA8AFNTSAFQA4AOpgC0zrgBFYIgBKSrgFNIAVqqYAeAG6QAyoANqAFRkgjlvgCvkANqmAHgBcxuQCjGgAVACYLqBgAXJUADGgBGIASBgGQAoc/gBikCgOSbwByUAFVABfCgBxV2TRAEAcqiAOrgwoAeABqabqSATL+AK9/ABkAMHNNIAgEQDkKABKjACsEq0vk08gEAU0XUbCgBAHDkqALNAXonSFACAW1TyALsqAO9JgDiJppAPOABeqMfAFQ4HTAHTkKAGVQAxkAoKVUAPAA6MQAmkDAAyhqpgCAM1KABy1ADREAA4AUTJSq4A+ACVQAmkALsUAOMgBlUfAFpjQB/4AVGSBYLzADagBXkAGAmkDMtALGKTALOVXANx7mv4A1AWoAGNyAMFABSYAVBjKpgFnMVAFtQA0RAAJqj4AWABSAAYUAGQbUAHFXALSIAFIyGumoA3TACCgAioAJ+ACoLwVkAb+AHOVXALwAKNEEwY1dQBZABLkOmoAQBVkAJHVcAp5dSYB5bRIBuSmKgCjAEXUmAc0g1lQBYwDJoKAPoAUSqILzAKSp5AKavABBXgBy0AaTAC6gTdNgB4yAGWquAWp5M6YB5aAO1ADpDQAw5AAZAHwATNJQAXvTgBZdSYA6uoA1GvHwBIgACkxUATmNPTVwBAHLVXAPINquAPMVNVVwBALuQBchQAMbkAZqAGh4qAF2FADNQAXy0AcKADLXTYATkKALgAakdVwBAGh1eAB6kZANCjTAJa1XAByFAFlUwCdEAIpACagR8ANVTACtMOyoAQCuabFAElVwCy1VwC1cGcOSoAQB2q4A8mANTMUADp5AC4ATBVVwBuqeQBgDM1XAHwA4wDIAZaAHgAUZCgBmh0QCpWKgCrVVwCutSMgE6iQBxSYBZvSIBtpmjLmq0AgDcadABRAGdXUAakKAFgJwAGJkKACagZADGXIALKgA8ACjYUkAp58AdEQVkAnTyAGKTAKLkKADKgCpEFwArqJrgHh2XUmAeHHioAQBybNAC1cAOKuAV1YVPIA4ADOfADtU8gG5CgAmhQA4pMAdmyoAvqAGhzHj4AoqkASdIUAUnYUAVVXAHKkZALbkqAEAdHi5ABRiAE3YaAVXRAHDQAyANtKVMAMZdSYAgC5EAAVkAMqAO5kuoALp+ADCgCUZDQAT4AIx8ASFO2oAqXSASQSVI6rgG6aQBptQBTyAFTOuAKjZAGPgApfIBYybVzTyAIBajkAs6vMA3IUBoAJUADG5AGbAAwoAaGSABwIgAFJABqaQC0c6rgElQARVcAZgw0AsGSBagAdEAI5ACSgAmkANqADwAIbSkQCcqaFAFjFL4AEAlGuhoA5ABFJpAJUgAjEAJpBlU0KAEAb7UAO1TBc0QD6ADTJUCnABgoAKqAC6gVAFSqgyAEVgC6agAqC+QBooFMgBUF8gBqKVXALIAcAFyIAAlQAMmaIBRVNCgCj4ANquAUnRNcAqxUAU0KABkVADAAMZVcAsg6D6gBg6MQAmC+QB8AEVKqALqgBTgAyNGIAqjEAXRUANIKAKdOADQ1QARAAF5ACSqTUAOWumwAnSVgAQCmCkwAvfwA6mkAKgy0AqmQoAVGgACHGiASkgBGIATSANKTAC+QBuoyQBdNgB20a6gDyaVQAmkAL5ADLqTALwAKNEEgAqADoxAGkjIaAU1ABUF1AkDwA3NNigCUrIA0mwAdIzq6gBALSVTyAPgAq5IB6O9SMgFjJpoUAIBIQrGF6iAIBNABKVTAJhrgC7JjxUAIAykq4BTn4Aa1pfIB3UCt3YUAIBcUrIAukAFLpAPJjxUAMFABGAIgBjKgB64AVGQ0AJAuAEVVbSagD27DqTAEAogBObsAFe7jxUAIA4yALTTBkAFOuAEwXUul1ACAOFAC5EAAmwEAAukAMABTTGgFdRsgAoAnJ8ACgZioAqJN4AVAYrLVXAEAZUvenABAGbmNyAdIgy0AagyaIA6Q0AeTAG5nTACQNqiASlABTR4qAPSgYyAPgA1eYA8chQBeqoAtTRFQApVfGTTSAQBOyAGXRAKoMKXqIBaNGPgBALamKyY8VACAV/AC6MTMUAeHZAKjkKAPhnZACCgAjAAJ5AC8gAw0GVADlDQAVcAfAAo0AXBlqrgGlLpsANUAAcxuQCiiklAFEAMZADIANNkAFKiAEwXUALkNACKgAyoAaA8ADkqABagAikEQAmmnABUDKrgFdQAYUBoAZbTWQBAGkjTAGaVXAK6QQBFIAX8AGMgFd2VADSbAD8o1wAxlV0m8AIBZACmpsAC4BfVegA0oARSl"
for(var i=0,t="",x=atob(x),m;i<x.length;i++)m=x.charCodeAt(i).toString(2),t+="00000000".substr(m.length)+m
t=t.replace(/.{5}/g, function(m){return key.charAt(parseInt(m,2))}).split(/_/)[0];
t=JSON.parse("{"+t.replace(/[a-zA-Z]/g,'"$&":{').replace(/\/(\d*)/g, function(m,d){
for(var n=parseInt(d,10)||1,o="";n--;)o+="}"
return o +",";}).replace(/\,\}/g, "}").replace(/\{\,/g, "{").replace(/\,$/, "").replace(/\{\}/g, "null"))
for(var i=0,n=t,c;i<w.length;n=n[c]){
c=w.charAt(i++)
if(!(c in n))return false}
return n==null}
```
There's three encodings of the words. First the words are converted into a shorthand tree like `about/2ve`. This has the word **about** then back 2 `/2` add `ve` for **above**. The encoding is converted to only allow for / /3 /4 and /5 backing and all others are converted as combinations. This gives a total of 32 different chars and allows for 5 bit encoding. The 5bit encoding is binary and needs to be base64 encoded.
When decoding the shorthand tree is converted to a JSON tree for a simple node search.
I initially tried to use canvas and toDataURL to get some compression but it wasn't good. If you go that route do not use the alpha channel. Browsers hack the alpha and do rounding with the data so just set that to 255 and put your data in rgb.
[Answer]
## Shell - Bytes: 2545, False +ves: 0, False -ves: 0 = Score: 2545
Code: ~~54~~ 52 bytes, Dictionary: ~~2518~~ ~~2494~~ 2493 bytes, FP: ~~1~~ 0, FN: 0
```
[ $1 = "${1#?*[A-Z]}" ]&&unlzma<z|grep -qix "${1%I}"
```
Quotes are not needed around the initial `$1` because "[the input is always a single word, all ASCII `[A-Za-z]`](https://codegolf.stackexchange.com/questions/51308/write-a-compact-spelling-checker#comment121754_51308)." However, quotes *are* needed around the parameter expansions because they might generate an empty string.
### Examples:
In shell, an exit code of `0` is true (anything else is false). `$?` is the previous command's exit code.
```
$ sh in997 colour; echo $?
0
$ sh in997 Colour; echo $?
0
$ sh in997 coLoUr; echo $?
1
$ sh in997 COLOUR; echo $? # I chose to consistently mark these false
1
$ sh in997 Color; echo $?
1
$ sh in997 I; echo $?
0
$ sh in997 i; echo $?
1
$ sh in997 ColourI; echo $? # testing because I strip off one trailing "I"
1
$ sh in997 II; echo $? # … and "I" isn't in the dictionary (see below)
1
```
(Examples copied from [Nejc's answer](https://codegolf.stackexchange.com/questions/51308/write-a-compact-spelling-checker#51318) plus an all-caps example and two tests for specific corner cases used to vet my `i` vs `I` logic. I have no idea why Google Prettify likes Proper Case and CamelCase words when highlighting `lang-bash`.)
### Ungolfed and explained:
```
if [ "$1" = "${1#?*[A-Z]}" ]; then
cat z | unlzma | grep -q -i -x "${1%I}"
fi
```
The conditional compares the argument with itself after a string manipulation that alters the string if it matches any character followed by any number of characters followed by an uppercase letter (equivalent to `s/^..*?[A-Z]//` – ignore the [`?`](http://www.rexegg.com/regex-quantifiers.html#lazy "lazy quantifier—find the shortest match") if you don't understand it), which would compare `coLoUr` to `oUr` and `Colour` to `Colour`. This controls for mixed case (and fails all-caps), though it skips the first letter. It accepts `i` (but neither `i` nor `I` are in the dictionary, see below).
If the conditional matches (there are no capitals after the first letter), `unlzma` is run on the contents of the file named `z`, which puts the uncompressed dictionary into standard output. `grep` then queries quietly (`-q`), without regard to case—we've already controlled for that (`-i`), and on a whole line (`-x`).
The query is an altered version of the argument: if the argument has a trailing capital `I` (case sensitive!), it is removed. Because we controlled for case earlier, the only time we'd remove a capital `I` would be for the word `I`, in which case the `grep` query seeks an empty string on its own line. The dictionary's `I` entry was swapped for a blank line, so we'll get a match.
The last item that executed dictates the exit value of the script. If the conditional was false, the script exits false. If `grep` found no match, it (and the script) return false. If `grep` found a match, it and the script return true.
### Dictionary creation:
Wow. There are some awesome dictionary compression schemes in other answers here. I didn't do anything that fancy. There is zero custom compression in this code (unless you count removing DOS linebreaks), just minor prep work that makes it easier to check later on (blanking the `I` line actually *costs* a byte!).
I just took the stock dictionary, blanked the `I`, and compressed the output. I chose [LZMA](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Markov_chain_algorithm) because it compressed this particular file better than `zip`, `gzip`, `bzip2`, `xz`, or `zlib`.
Here's my code:
```
wget -qqO- 'http://pastebin.com/raw.php?i=wh6yxrqp' \
| perl -pne 's/\r//; s/^I$//' | lzma -c9 > z
```
`wget` flags `-qqO-` suppress all output and sends the HTML content to standard output. That's parsed by `perl`, which removes the DOS line breaks (`\r`) and converts the `I` entry to a blank line (since we stripped the trailing `I` in `grep`). That's then passed to `lzma` which outputs the compressed dictionary into a pipe to file `z`.
Note that `unlzma` will refuse to operate on a file lacking the `.lzma` extension, but it's fine with a pipeline. That means `unlzma z` fails while `unlzma<z` (effectively `cat z | unlzma`) succeeds.
] |
[Question]
[
# The Specs
* Your program must read the image from one file and write the results to another file, the name of at least the first of which should be taken from the input
* You may accept and return any image format or formats, as long as you specify in your answers which ones you are using
* An exception should be thrown if the specified source file does not exist
* The final image must be as close as possible to the initial image (by per-pixel euclidean metric on RGB values) while using only colors from a list read from the file "colors.txt" (it will not necessarily use all of them)
* When determing the nearest color, you should use the euclidean metric on RGB values, Δc=sqrt((Δr)2+(Δg)2+(Δb)2), when two or more colors on the list are equally close, any of those colors is valid
* The list of colors given will be formatted with one rgb color code on each line, with spaces seperating the red, green, and blue values
* You may assume that at least three but no more than 1,000 colors will be listed
**This is code golf, so the shortest program wins**
# Some test cases:
**(if RGB values in the output images do not exactly match those in the list, this is due to a problem with Java's ImageIO.write)**
input:

colors.txt:
```
255 0 0
250 150 0
255 50 0
0 0 200
0 0 80
0 0 0
```
output:

---
input:

colors.txt:
```
100 60 0
0 0 20
0 0 70
0 20 90
15 15 15
100 100 100
120 120 120
150 150 150
```
output:

---
input:

colors.txt:
```
0 0 0
10 20 15
25 25 20
35 30 20
40 35 25
55 55 60
70 60 50
130 100 80
130 140 145
140 100 70
165 130 90
200 160 130
230 210 220
250 250 250
```
output:

---
input:

colors.txt:
```
0 0 0
70 50 40
80 0 0
120 100 90
120 120 120
170 150 90
170 170 170
170 200 195
190 140 100
190 205 165
210 170 120
```
output:

Again, I put together a java program to generate the sample output. I'll golf it down a little further, and then I may post it as an answer later.
[Answer]
# Mathematica ~~109 100 97~~ 111
Update: now outputs the image as required.
The function, *f*, replaces a single pixel with the closest pixel found in the input file (in this case, "colors.txt").
*t* is the output file.
The function, *g*, applies *f* to each pixel in the input image.
```
g[i_,h_,t_]:=Export[t,(c=Import[h,"Data"]/255;
f@p_:=Sort[{p~EuclideanDistance~#,#}&/@c][[1,2]];f~ImageApply~i)]
```
**Test Cases**
Example 1: Seascape
```
(*creating "colors.txt"*)
c = "255 0 0
250 150 0
255 50 0
0 0 200
0 0 80
0 0 0";
Export["colors.txt", c]
```

---
Example 2: Earth from moon
I'll skip the part about storing the color info into "colors.txt".
It closely follows example 1.

---
Example 3: Jupiter

---
Example 4: American Gothic

[Answer]
# Python [3] + Pillow, 276 272 267
Takes 2 parameters: name of source image file and name of file with colors list. Tested on Py3, may work on Py2 too.
My first attempt in code golf, so probably not very impressive (and similar to dieter's code).
```
import sys
import PIL.Image as P
i,c=sys.argv[1:]
c,z=[tuple(int(i)for i in e.split())for e in open(c).readlines()],P.open(i)
x,y=z.size
p=z.load()
for _ in range(x*y):
j,k=_//y,_%y
d={sum((i-j)**2for i,j in zip(p[j,k],a)):a for a in c};p[j,k]=d[min(d)]
z.save(i*2)
```
Ungolfed:
(displays output image instead of saving, and is a bit safer, because removes empty lines from colors file)
```
# coding: utf-8
import sys
from PIL import Image
def similarImage(img, colors):
if isinstance(img, str):
img = Image.open(img)
x, y = img.size
pixels = img.load()
for i in range(x):
for j in range(y):
pixels[i,j] = getClosestColor(pixels[i,j], colors)
img.show()
def getColorDistanceSq(c1, c2):
#root not needed
return sum((i-j)**2 for i,j in zip(c1, c2))
def getClosestColor(col, colBase):
colDist = {getColorDistanceSq(col, c) : c for c in colBase}
return colDist[min(colDist)]
def parseColors(desc):
desc = desc.split('\n')
desc = [i for i in desc if i != '']
return [tuple(int(i) for i in d.split()) for d in desc]
def main():
imgFile = sys.argv[1]
with open(sys.argv[2]) as f:
colors = parseColors(f.read())
similarImage(imgFile, colors)
if __name__ == "__main__": main()
```
[Answer]
# Python 2.7, 279
Reads the name of the input image and the name of the color map for commandline arguments. usage is
```
python script.py <image file> <colors.txt>
```
It saves the new image as a file with the same name, preceded by an extra tilde :
```
from sys import*;from PIL.Image import*;f=argv[1]
c,I,X=[[int(x)for x in l.split()]for l in file(argv[2])],open(f),range
w,h=I.size;P=I.load()
for j in X(h):
for i in X(w):
r,g,b=P[i,j];C={(R,G,B):(R-r)**2+(G-g)**2+(B-b)**2for R,G,B in c};P[i,j]=min(C,key=C.get)
I.save('~'+f)
```
[Answer]
# Java, 726 bytes
Too bad all the imports and main class eat up some many bytes, but it's a standalone program after all. Nevertheless, it was a nice and fun challenge to work on.
This golf can be run by issuing `java M.class inputImage.png outputImage.png colours.txt`, or equivalent.
```
import java.awt.*;import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*;class M {public static void main(String[]a)throws Exception{BufferedImage i=ImageIO.read(new File(a[0]));int w,h,k,r,g,b,t,z,q;w=i.getWidth();h=i.getHeight();BufferedImage o=new BufferedImage(w,h,2);for(int x=0;x<w;x++){for(int y=0;y<h;y++){Color v=null;k=i.getRGB(x,y);r=k>>16&0xff;g=k>>8&0xff;b=k&0xff;double e=999;for(String n:Files.readAllLines(Paths.get(a[2]))){String[]m=n.split(" ");t=Integer.parseInt(m[0]);z=Integer.parseInt(m[1]);q=Integer.parseInt(m[2]);double d=Math.sqrt((t-r)*(t-r)+(z-g)*(z-g)+(q-b)*(q-b));if(d<e){e=d;v=new Color(t,z,q);}}o.setRGB(x,y,v.getRGB());}}ImageIO.write(o,"png",new File(a[1]));}}
```
[Answer]
# Java, ~~861~~ ~~849~~ ~~842~~ 836 bytes
I think there's probably room for improvement here.
```
import java.awt.*;import java.awt.image.*;import java.io.*;import java.util.*;import javax.imageio.*;import static java.lang.Math.*;class D{static void g(Color c,ArrayList<Color>h,int x,int y,BufferedImage b){double d=450;Color e=null;for(Color f:h){double g=sqrt(pow(c.getRed()-f.getRed(),2)+pow(c.getGreen()-f.getGreen(),2)+pow(c.getBlue()-f.getBlue(),2));if(g<d){e=f;d=g;}}b.setRGB(x, y, e.getRGB());}public static void main(String[]a)throws Exception{ArrayList<Color>c=new ArrayList<Color>();Scanner b=new Scanner(new File("colors.txt"));while(b.hasNext())c.add(new Color(b.nextInt(),b.nextInt(),b.nextInt()));b=new Scanner(System.in);BufferedImage i=ImageIO.read(new File(b.next()));int x=i.getWidth(),y=i.getHeight();for(;--x>=0;)for(int z=0;z<y;z++)g(new Color(i.getRGB(x,z)),c,x,z,i);ImageIO.write(i,"jpg",new File(b.next()));}}
```
Takes the names of the source and target image files from user input, reads the color list from colors.txt. Supports .jpg, .png, and probably others for input. Supports only .jpg for output.
] |
[Question]
[
Because I can't concentrate on any task for more than about 5 seconds, I often find myself breaking up words into a sub-strings, each of which is a different length and doesn't contain any repeated characters. For example, the word "pasta" might be broken up in "past" & "a", "pas" & "ta", or "pa" & "sta" and you get the picture.
However, because remembering all the combinations is hard, I generally only select one, and I like to select the nicest one. We consider the nicest way to be that which has the lowest "score". Your task will be, given a word, to print its score, given the following complicated rules.
## Scoring
Description of how to score a word:
* A word is a string of Latin characters, capital letters should be replaced with 2 of the same lowercase letter (so "Box" becomes "bbox")
* A segment is a contiguous (strict) substring of a word, and must not contain any character twice ("her", "re", "h" are all valid segments of "Here" ("hhere"), but "hh" and "ere" are not)
* A segmentation is a set of segments of different lengths which, when joined, form the original word ("tre" and "e" makes "tree"), and that cannot be further segmented within the segmentation (i.e. "ba" has a single segmentation, "ba"; and "alp" & "habet" is not a valid segmentation of "alphabet", because either of these could be further segmented (e.g. into "a" & "lp" & "habet", which is now a valid segmentation ("habet" can't be segmented without forming a segment of length 2 or 1))).
* The score of a segmentation is the sum of the scores of each distinct character that appears in the original word (once capitals have been replaced)
* The scoring of characters is explained below
* The score of a word is the score of its nicest possible segmentation (that with the lowest score)
If no valid segmentations exist for a word (for example, "Brass" ("bbrass"), which can't be segmented because the first "b" and last "s" would have to be in their own segments, which would result in two segments of the same length), then you should output the text "evil", otherwise you should output the score of the word.
### Character scoring
The scoring of characters is based on how many times the character appears, and the weightings of the segments it appears in. The weightings of the segments depends on the lengths of the segment, and the lowest common multiple of the lengths of all the segments in the segmentation.
```
segment weighting = lowest common multiple of lengths segments / length of segment
```
Consider the word "olive", which could be segmented as "ol" & "ive", and visualised as 2 boxes of the same area, one of "ol" with weight 3, and one of "ive" with weight 2 (LCM of 6).
```
ol
ol ive
ol ive
```
This is meant to depict the two boxes, one made from 3 "ol"s, and one made from 2 "ive"s. Alternativly, it might be "o" & "live" (LCM of 4)
```
o
o
o
o live
```
The score of each character is then the sum of the weights of the segments in which it appears, multiplied by the number of times it appears after replacing capitals (so if it appears twice, you are charged double for each time you have to say it).
```
character score = character count * sum(segment weights in which character appears)
```
### Scoring example
We take the word "fall", it can only be segmented into "fal" and "l". The lowest common multiple of 3 and 1 is 3, so "fal" has weight 1, and "l" has weight 3.
```
l
l
fal l
```
Going through each character...
* "f" appears once, and is in the segment "fal" with weight 1, so has score 1\*1 = 1
* "a" also appears only once, has sum of weights of 1, so has score 1\*1 = 1
* "l" appears twice, and appears in "fal" (weight 1) and "l" (weight 3), so has score 2\*(1+3) = 8
The sum of these is 10 (the score of the segmentation, and of the word, as this is the nicest segmentation). Here is this in the same format as the examples below:
```
fall = fal l
2*1 [fa] + 2*(1+3) [ll] = 10
```
### Example Scorings
These examples of scorings may or may not help:
```
class -> clas s
3*1 [cla] + 2*(4+1) [ss] = 13
fish -> fis h
3*1 [fis] + 1*3 [h] = 6
eye -> e ye
1*1 [y] + 2*(1+2) [ee] = 7
treasure -> treas u re
3*2 [tas] + 2*2*(2+5) [rree] + 1*10 [u] = 44
Wolf -> w wolf
3*1 [olf] + 2*(1+4) = 13
book
evil
```
"book" is an evil word, so doesn't have a score.
Note that "treasure" can be segmented in a number of ways, but the segmentation shown benefits from having the more frequent letters ("r" and "e") in the longer segments, so they don't have as much weight. The segmentation "t" & "re" & "asure" would give the same result, while "treas" & "ur" & "e" would suffer, with "e" having a score of 2\*(1+10+2) = 24 on its own. This observation is really the spirit of the whole exercise. An example of an incorrect score of "treasure" (incorrect because it's not derived from the score of the nicest segmentation (that with the lowest score)):
```
treasure = treas ur e
3*2 [tas] + 2*(2+5) [rr] + 1*5 [u] + 2*[2+10] = 49
```
## Input
A single string containing only latin characters of either case ("horse", "Horse", and "hOrSe" are all valid inputs) which can be accepted either by STDIN, Command-line argument, function argument, or otherwise if your language of choice doesn't support any of the aforementioned.
## Output
You must output either the score of the word, which is a single positive integer greater than 0, or "evil" if no segmentation exists. Output should be to STDOUT or the return argument of a function, unless your language of choice supports neither of these, in which case do something sportsmanly.
## Examples
I do not expect you to print all this stuff, all I want is the score of the word, or the output "evil", for example (input followed by output)
```
eye
7
Eel
evil
a
1
Establishments
595
antidisestablishmentarianism
8557
```
I'm not concerned about performance, if you can score just about any 15letter word (after replacing capitals) in under a minute on a sensible (intentionally left vague) machine, that's good enough for me.
This is code-golf, may the shortest code win.
*Thanks to PeterTaylor, MartinBüttner, and SP3000 for their help with this challenge*
[Answer]
# Mathematica, 373 bytes
```
If[l=Length;a=Accumulate[l/@#]&;u=Unequal;e=Select;{}==(m=(g=#;Tr[#2Flatten[ConstantArray[#,LCM@@l/@g/l@#]&/@g]~Count~#&@@@Tally@c])&/@e[p=e[c~Internal`PartitionRagged~#&/@Join@@Permutations/@IntegerPartitions[l[c=Characters[s=StringReplace[#,c:"A"~CharacterRange~"Z":>(d=ToLowerCase@c)<>d]]]],u@@l/@#&&And@@u@@@#&],FreeQ[p,l_List/;#!=l&&SubsetQ[a@l,a@#]]&]),"evil",Min@m]&
```
This is quite long... and also rather naive. It defines an unnamed function that takes the string and returns score. It takes about 1 second to handle `"Establishments"`, so it's well within the time limit. I've got a slightly shorter version that uses `Combinatorica`SetPartitions`, but it already takes a minute for `"Establishme"`.
Here is a version with whitespace:
```
If[
l = Length;
a = Accumulate[l /@ #] &;
u = Unequal;
e = Select;
{} == (
m = (
g = #;
Tr[
#2 Flatten[
ConstantArray[
#,
LCM @@ l /@ g/l@#
] & /@ g
]~Count~# & @@@ Tally@c
]
) & /@ e[
p = e[
c~Internal`PartitionRagged~# & /@ Join @@ Permutations /@ IntegerPartitions[
l[
c = Characters[
s = StringReplace[
#,
c : "A"~CharacterRange~"Z" :> (d = ToLowerCase@c) <> d
]
]
]
],
u @@ l /@ # && And @@ u @@@ # &
],
FreeQ[p, l_List /; # != l && SubsetQ[a@l, a@#]] &
]
),
"evil",
Min@m
] &
```
I might add a more detailed explanation later. This code uses the second solution [from this answer](https://mathematica.stackexchange.com/a/8529/2305) to get all the partitions and [this solution](https://mathematica.stackexchange.com/a/77328/2305) to make sure they are all maximally segmented.
[Answer]
# Java 8, ~~1510~~ 1485 bytes
This is **way** too long. Combinatorics are never easy in java. It definitely can be shortened quite a bit. Call with `a(string)`. This uses an exponential memory and time algorithm; so don't expect it to work for long inputs. It takes about half a second to process `Establishments`. It crashes with an out of memory error for `antidisestablishmentarianism`.
```
import java.util.*;import java.util.stream.*;void a(String a){a=a.replaceAll("\\p{Upper}","$0$0").toLowerCase();List<List<String>>b=b(a),c;b.removeIf(d->d.stream().anyMatch(e->e.matches(".*(.).*\\1.*")));b.removeIf(d->{for(String e:d)for(String f:d)if(e!=f&e.length()==f.length())return 1>0;return 1<0;});c=new ArrayList(b);for(List<String>d:b)for(List<String>e:b){if(d==e)continue;int f=0,g=0;List h=new ArrayList(),i=new ArrayList();for(String j:d)h.add(f+=j.length());for(String k:e)i.add(g+=k.length());if(i.containsAll(h))c.remove(d);else if(h.containsAll(i))c.remove(e);}b=c;int d=-1;for(List e:b)d=d<0?c(e):Math.min(c(e),d);System.out.println(d<0?"evil":d);}int c(List<String>a){List<Integer>b=a.stream().map(c->c.length()).collect(Collectors.toList()),d;int e=d(b.toArray(new Integer[0])),f=0,g=0,h;d=b.stream().map(A->e/A).collect(Collectors.toList());Map<Character,Integer>i=new HashMap(),j=new HashMap();for(;g<a.size();g++){h=d.get(g);String k=a.get(g);for(char l:k.toCharArray()){i.put(l,i.getOrDefault(l,0)+1);j.put(l,j.getOrDefault(l,0)+h);}}for(char k:i.keySet())f+=i.get(k)*j.get(k);return f;}int d(Integer...a){int b=a.length,c,d,e;if(b<2)return a[0];if(b>2)return d(a[b-1],d(Arrays.copyOf(a,b-1)));c=a[0];d=a[1];for(;d>0;d=c%d,c=e)e=d;return a[0]*a[1]/c;}List b(String a){List<List>b=new ArrayList(),c;for(int i=0;++i<a.length();b.addAll(c)){String d=a.substring(0,i),e=a.substring(i);c=b(e);for(List f:c)f.add(0,d);}b.add(new ArrayList(Arrays.asList(a)));return b;}
```
[Try here](http://ideone.com/PN21WT)
Indented with explanation:
```
void a(String a){
a = a.replaceAll("\\p{Upper}", "$0$0").toLowerCase(); //Replace all uppercase letters with two lowercase letters
List<List<String>> b = b(a), c; //Generate partitions
b.removeIf(d -> d.stream().anyMatch(e -> e.matches(".*(.).*\\1.*")));//Remove partitions that contains duplicate letters
b.removeIf(d -> { //Remove partitions that have equal length parts
for (String e : d)
for (String f : d)
if (e != f & e.length() == f.length())
return 1 > 0;
return 1 < 0;
});
c = new ArrayList(b); //Remove partitions that can be partitioned further
for (List<String> d : b) //Uses Martin's technique
for (List<String> e : b){
if (d == e)
continue;
int f = 0, g = 0;
List h = new ArrayList(), i = new ArrayList();
for (String j : d)
h.add(f += j.length());
for (String k : e)
i.add(g += k.length());
if (i.containsAll(h))
c.remove(d);
else if (h.containsAll(i))
c.remove(e);
}
b = c;
int d = -1;
for (List e : b)
d = d < 0 ? c(e) : Math.min(c(e), d); //Find nicest partition
System.out.println(d < 0 ? "evil" : d);
}
int c(List<String> a) { //Grade a partition
List<Integer> b = a.stream().map(c->c.length()).collect(Collectors.toList()), d; //Map to length of parts
int e = d(b.toArray(new Integer[0])), f = 0, g = 0, h;
d = b.stream().map(A -> e / A).collect(Collectors.toList()); //Figure out the weight of each part
Map<Character, Integer> i = new HashMap(), j = new HashMap();
for (; g < a.size(); g++){ //Count instances of each character and
h = d.get(g); //weight of each character
String k = a.get(g);
for (char l : k.toCharArray()){
i.put(l, i.getOrDefault(l, 0) + 1);
j.put(l, j.getOrDefault(l, 0) + h);
}
}
for (char k : i.keySet())
f += i.get(k) * j.get(k); //Sum cost of each character
return f;
}
int d(Integer... a) { //Find lcm
int b = a.length, c, d, e;
if (b < 2)
return a[0];
if (b > 2)
return d(a[b - 1], d(Arrays.copyOf(a, b - 1)));
c = a[0];
d = a[1];
for (;d > 0;d = c % d, c = e)
e = d;
return a[0] * a[1] / c;
}
List b(String a) { //Find all partitions of a string
List<List> b = new ArrayList(), c; //Uses recursion
for (int i = 0; ++i < a.length();b.addAll(c)){
String d = a.substring(0, i), e = a.substring(i);
c = b(e);
for (List f : c)
f.add(0, d);
}
b.add(new ArrayList(Arrays.asList(a)));
return b;
}
```
This also abuses generics quite a bit to reduce the byte count. I'm pretty surprised I was able to get all of it to compile.
Thanks Ypnypn :)
[Answer]
# C# 679 Bytes
This solution is roughly based off my the structure of my original test implementation, and initially was just a golfed re-write, but then I inlined all the functions, and now it's horrifying. It's reasonably fast, solving Establishments in under a second. It's a complete program that takes the input word as a single paramater of ARGV.
```
using Q=System.String;class P{static void Main(Q[]A){Q s="";foreach(var c in A[0]){var z=(char)(c|32);if(c<z)s+=z;A[0]=s+=z;}int r=S(A);System.Console.WriteLine(r<1?"evil":""+r);}static int S(Q[]s){int r=0,t,j,k,L=1,Z=s.Length,i=Z,T=0,R=2;for(;i-->0;R=t<1?0:R){t=s[i].Length;k=L;for(j=2;t>1;)if(t%j++<1){t/=--j;if(k%j<1)k/=j;else L*=j;}}foreach(var C in Q.Join("",s))for(i=Z;i-->0;){for(k=s[j=i].Length;j-->0;)R=k==s[j].Length?0:R;j=s[i].IndexOf(C)+1;R=j*R*s[i].IndexOf(C,j)>1?1:R;T+=j>0?L/k:0;}i=R<1?0:Z;for(var U=new Q[Z+1];i-->0;)for(j=s[i].Length;j-->1;r=r<1|((t=S(U))>0&t<r)?t:r)for(U[k=Z]=s[i].Substring(j);k-->0;U[i]=s[i].Substring(0,j))U[k]=s[k];return r<1?R<2?R-1:T:r;}}
```
The `Main` method starts by creating a copy of the input with the capitals replaced. It then calls `S`, the "solver", which returns the score of a given segmentation (the first segmentation being that with a single segment which is the whole word). It then either prints "evil" or the score, depending on the score.
The "solver" (`S`) does all the interesting stuff, and was originally broken down down into 4 methods, which were rolled together. It works by first scoring the current segmentation, making a note of whether it is invalid (and crucially, whether it is so invalid we shouldn't try to further segment it (for performance), skipping the rest of the computation if it is). Then, if it hasn't been skipped, it splits each segment in the segmentation everywhere it can be split, and finds the best score of all of these (recursively calling `S`). Finally, it either returns the best score of the subordinate Segmentations, else it's own score, or invalid if it's own segmentation is invalid.
Code with comments:
```
using Q=System.String; // this saves no bytes now
class P
{
// boring
static void Main(Q[]A)
{
// this can surely be shorter
// replace capitals
// I refuse to put this in S (would give us a Q, but we'd have to pay for the Action=null)
Q s="";
foreach(var c in A[0])
{
var z=(char)(c|32); // ugly
if(c<z)
s+=z; // ugly
A[0]=s+=z; // reuse the array
}
int r=S(A); // reuse the array
System.Console.WriteLine(r<1?"evil":""+r);
}
// solve
static int S(Q[]s) // s is current solution
{
int r=0,t,j,k,
L=1,Z=s.Length,i=Z,
T=0, // is score for this solution (segmentation)
R=2; // R is current return value, as such, 0 -> return -1, 1 -> return 0, 2 -> return T
// score first
// factorise stuff, L is LCM
for(;
i-->0; // for each segment
R=t<1?0:R) // segment too short (skip)
{
t=s[i].Length;
k=L; // we cut up k as we cut up c, when we can't cut up k, we need to build up L
for(j=2;t>1;)
if(t%j++<1) // j goes into t
{
t/=--j; // cut up t
if(k%j<1) // j goes into k
k/=j; // cut up k
else
L*=j; // j does not go into k, build up L
}
}
// recycle i, j, k, (t)
foreach(var C in Q.Join("",s)) // for each character
for(i=Z;i-->0;) // for each segment
{
for(k=s[j=i].Length;
j-->0;) // for all the segments that follow
R=k==s[j].Length?0:R; // repeat length (skip)
j=s[i].IndexOf(C)+1;
// these both check if this segment contains the char (j > 0)
R=j*R*s[i].IndexOf(C,j)>1?1:R; // duplicate char (allow)
T+=j>0?L/k:0; // add on the segment weight
}
// R is whether we are invalid or not
// T is our score
i=R<1?0:Z; // if segmentation invalid and can't be segmented, skip everything (performance)
// recycle i, j, k, t
// first use of r=0
for(var U=new Q[Z+1];
i-->0;) // for each segment
for(j=s[i].Length;
j-->1; // for each place we can split it
r=r<1|((t=S(U))>0&t<r)?t:r) // solve where we split thing at i at position j, if this score is better than r, replace r with it
for(U[k=Z]=s[i].Substring(j); // put second half of s[i] in last position (order doesn't matter)
k-->0; // for each char in s[i]
U[i]=s[i].Substring(0,j)) // put first half of s[i] in p position
U[k]=s[k]; // copy across everything else
return r<1?R<2?R-1:T:r; // if we didn't find a valid solution more segmented than this, return our score (unless we are invalid, in which case, return R-1), else the score for the more segmentation solution
}
}
```
] |
[Question]
[
### Objective
Find the most expensive path from the top-left of a square grid to the bottom-right such that its total cost is below a given threshold.
### Scenario
1. You are given a square `NxN` grid.
2. You are given a maximum cost.
3. Every cell in the grid has a cost. The top-left cell has cost `0`.
4. The cost of a path is the sum of the costs of the cells in the path. Its "cost surplus" is the result of subtracting its cost from the maximum cost.
5. Movement is always either right one cell or down one cell.
6. The starting point is the top-left cell of the grid and the goal is the bottom-right cell.
7. You must output the smallest cost surplus of any path with a non-negative cost surplus, or -1 if there is no such path (The maximum cost is not enough).
### Input restrictions
1. `N` will be between 1 and 20 inclusive.
2. The maximum cost will be between 1 and 200 inclusive.
3. The cost of each cell will be between 0 and 10 inclusive.
### Examples
1. Maximum cost: 9
Grid:
```
0 1 5
2 3 2
2 3 2
```
Expected output: 0
Explanation: there is a path `0 2 2 3 2` with cost 9 and cost surplus 0.
2. Maximum cost: 15
Grid:
```
0 1 5
2 3 2
2 3 2
```
Expected output: 5
Explanation: the most expensive path is `0 1 5 2 2` with cost 10 and cost surplus 5.
3. Maximum cost: 6
Grid:
```
0 1 5
2 3 2
2 3 2
```
Expected output: -1
Explanation: the least expensive path is `0 1 3 2 2` with cost 8, which is greater than 6.
[Answer]
## GolfScript (53 bytes)
```
~.,[1]*\{[[\]0\zip{~2$|2@?*}/](;}/-1=2.$)?|2base\~>1?
```
Expects input in the format
```
15 [[0 1 5][2 3 2][2 3 2]]
```
[Online demo](http://golfscript.apphb.com/?c=O1s2IDkgMTVdeycgW1swIDEgNV1bMiAzIDJdWzIgMyAyXV0nKwojIwp%2BLixbMV0qXHtbW1xdMFx6aXB7fjIkfDJAPyp9L10oO30vLTE9Mi4kKT98MmJhc2Vcfj4xPwoKIyMKcH0v) which covers three test cases.
The approach is to build up a list of possible running totals to each cell as a bitmask, extract the relevant lower bits, base-convert to a list of `0` and `1`, and look for the index of the first `1`.
### Dissection
```
~ # Eval input: puts N and grid on the stack
.,[1]* # Set up initial row cost bitmask: 2^0 for each column
\{ # For each row in grid:
[ # Stack: N prev-row-bitmask this-row-cost
[\]0\zip # Pair up prev-row-bitmask and this-row-cost and push 0 under them
{ # For each pair:
~ # Stack: N left-cell-bitmask cost up-cell-bitmask
2$|2@?* # this-cell-bitmask = (left-cell-bitmask | up-cell-bitmask) << cost
}/
](; # Gather row into an array and drop the 0 we inserted for the -1th cell
}/
-1= # Take the bitmask of the bottom-right cell. Stack: N bottom-right-bitmask
2.$)?| # Or 2^N to ensure that we get enough bits from the base conversion
2base # Base conversion
\~> # Take the last (least significant) N+1 bits
1? # Find the first index (hence smallest cost surplus) of the value 1
```
[Answer]
# CJam, ~~72~~ 71 bytes
```
q~:Q,mqi:L(2*0aa\{{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}*{Qf=:+}%f-{W>},$W+0=
```
This is really long and I think a different approach to the question is the only way to get it shorter.
[Try it online here](http://cjam.aditsu.net/)
Input is in the following format : `<Steps> [<Flat Grid>]` . For ex:
```
9 [0 1 5 2 3 2 2 3 2]
```
And output is the cost remaining, so `1` in above example.
\*Note that `[0 1 5 2 3 2 2 3 2]` is just a flat representation of the grid
```
0 1 5
2 3 2
2 3 2
```
**How it works** (slightly outdated):
```
q~ "Read the input and evaluate it";
:Q "Store the array in Q";
,mqi:L "Do floor of square root of its length";
LL+(( "Double length and decrease 2 from the double";
0aa "Put [[0]] on stack. This is the starting index"
"for any path in the grid";
\{ ... }* "Swap to but L + L - 1 on top and run the code"
"block that many times";
{{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}* "This block calculates indexes of all possible";
"paths from top left to bottom right of the grid";
{ }% "Map each array based on this code block";
_[~ "Copy the array and start a new array with the"
"contents of the copied one";
__ "Make two copies of the last element of the array";
)L% "Increment the element and calculate module L";
1L? "Choose L if module is 0, 1 otherwise";
+] "Add it to the copy of last array element. With"
"this, we have created one of the two possible"
"next step, that is going right. Except if we are"
"on the last column, then go down";
\[~ "Swap and start a new array with contents of"
"the original array";
__ "Make two copies of the last element";
L/) "Divide the 2nd copy by L and add 1 to the result";
L=1L? "If index belongs to last row, choose 1, else L";
+] "Add to the first copy of last element and close"
"the array. Now we have the second possible next"
"step, i.e. going down. But if we are on last row"
"then go right";
{Qf=:+}% "Map this block on the array containing all"
"possible path indexes";
Qf= "Get the corresponding cell amount array";
:+ "Sum the array elements to get total path cost";
{1$)<}, "Filter out paths which are not possible. i.e."
"paths having total cost more than first input";
$W= "Sort and get the last (highest) path cost";
- "decrement from input to get remaining steps";
```
[Answer]
# VBScript 191
This assumes that the array is in a variable called A and the cost is in a variable called c.
```
Dim M
Sub f(s,i,j,v)
If i>s And j=s And v<=c And M<v Then M=v
If i>s Or j>s Then Exit Sub
f s,i+1,j,v+A(i)(j)
f s,i,j+1,v+A(i)(j)
End Sub
f UBound(A),0,0,0
If M=0Then MsgBox-1 Else MsgBox c-M
```
To run it put the following lines at the top of a file called x.vbs then paste in the code above and just double click or execute `cscript x.vbs`
```
A=Array(Array(0,1,5),Array(2,3,2),Array(2,3,2))
c=6
```
[Answer]
# CJam, ~~71~~ ~~69~~ 68 bytes
I didn't look at anything from Optimizer's answer, except its size and input format... so the size is complete coincidence. But I think this can be golfed a fair bit.
```
l~:L,mqi(:X2*2\#:Y[{IY+2b(;_:+X={0_@{X*)+_L=@+\}/}*;}fI]f-{W>},$W+0=
```
[Test it here.](http://cjam.aditsu.net/)
The input on STDIN is in the form of the maximum steps and the *unrolled* grid as a CJam array:
```
9 [0 1 5 2 3 2 2 3 2]
```
Explanation:
```
"Prepare input:";
l~:L,mqi(:X2*2\#:Y
l~ "Read and eval input.";
:L "Store grid in L.";
,mqi(:X "Get length, square root, cast to int, decrement, store in X.";
2*2\#:Y "Multiply by 2, raise 2 to this power, store in Y.";
[{...}fI] "For I in 0 to Y-1. Collect in array.";
"Determine path:";
IY+2b(;_:+X=
IY+ "I + Y.";
2b "Convert to base 2.";
(; "Drop leading 1.";
_:+ "Duplicate and sum.";
X= "Check for equality with X.";
{...}* "If equals, execute this (otherwise, don't).":
"Determine remaining weight:";
0_@{X*)+_L=@+\}/
0 "Push 0. This is the sum.";
_ "Push another 0. This is the current position in the grid.";
@ "Pull up path description. 1 -> down, 0 -> right.";
{ }/ "For each step...";
X*) "Multiply by X, increment.";
+ "Add to current position.";
_L= "Duplicate and extract grid element.";
@+ "Pull up sum and add.";
\ "Swap with position.";
; "Pop... either the invalid path or the last position.";
f- "Subtract each sum from the maximum step number.";
{W>}, "Filter out negative results.";
$ "Sort.";
W+ "Append a -1.";
0= "Take the first element.";
```
] |
[Question]
[
Your task is to write a program that finds the largest radius that *N* circles can have and still fit inside of a rectangle that is X by Y pixels large. (similar to [this wikipedia article](http://en.wikipedia.org/wiki/Circle_packing_in_a_square)) Your program must find the largest possible radius and optimal position of these *N* circles so that
1. No two circles overlap
2. All of the circles fit inside of the rectangle.
Your program should then print this to the console:
```
Highest possible radius: <some_number>
Circle 1 Focus: (x, y)
Circle 2 Focus: (x, y)
...
Circle N-1 Focus: (x, y)
Circle N Focus: (x, y)
```
(Obviously, you must replace some\_number with the radius your program calculates, N with the number of circles you end up using, and x and y with the actual coordinates of the circle)
Lastly, it should create and save a picture with these circles drawn.
# Rules:
1. This program must run with any size of rectangle, and any number of circles and still get a valid answer. You can use command line arguments, user input, hard coded variables, or anything else you want.
2. If any circle overlaps or does not fit entirely inside of the box, your submission is invalid.
3. Each circle must have the same radius.
4. Just to make this reasonable and do-able, all numbers must be precise to the 2nd decimal place.
This is code golf, so shortest program (as of 10/28/2014) wins.
[Answer]
# JavaScript 782 725 characters
*first post, be gentle!*
The program is now called via the wrapped function. Eg: `(function(e,f,g){...})(100,200,10)`.
```
function C(e,f,g,c,a,d){if(0>g-a||g+a>e||0>c-a||c+a>f)return d;for(var b in d)if(Math.sqrt(Math.pow(d[b].x-g,2)+Math.pow(d[b].y-c,2))<2*a)return d;d.push({x:g,y:c});for(b=0;b<Math.PI;)XX=Math.cos(b)*a*2+g,YY=Math.sin(b)*a*2+c,d=C(e,f,XX,YY,a,d),b+=.01;return d}
(function(e,f,g){var c=e+f,a,d;for(a=[];a.length<g;)a=d=c,a=C(e,f,a,d,c,[]),c-=.01;console.log("Highest possible radius: "+Math.round(100*c)/100);e='<svg width="'+e+'" height="'+f+'"><rect width="'+e+'" height="'+f+'" style="fill:red" />';for(var b in a)console.log("Circle "+b+" Focus: ("+Math.round(100*a[b].x)/100+", "+Math.round(100*a[b].y)/100+")"),e+='<circle cx="'+a[b].x+'" cy="'+a[b].y+'" r="'+c+'" fill="blue" />';console.log(e+"</svg>")})(400,300,13);
```
## Test 1
`(function(e,f,g){...})(200,200,4)`
```
Highest possible radius: 49.96
Circle 1 Focus: (49.97, 49.97)
Circle 2 Focus: (149.91, 49.97)
Circle 3 Focus: (149.99, 149.91)
Circle 4 Focus: (50.05, 149.91)
<svg width="200" height="200"><rect width="200" height="200" style="fill:blue;" /><circle cx="49.97000000021743" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.9100000006523" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.98958489212322" cy="149.90996831285986" r="49.960000000217434" fill="white" /><circle cx="50.04958489168835" cy="149.90996831285986" r="49.960000000217434" fill="white" /></svg>
```
Obviously we would expect the radius to be exactly 50, but for reasons discussed in the question's comments, I couldn't reasonably make it happen. The SVG looks like this...

## Test 2
`(function(e,f,g){...})(100,400,14)`
```
Highest possible radius: 26.55
Circle 1 Focus: (26.56, 26.56)
Circle 2 Focus: (79.68, 26.56)
Circle 3 Focus: (132.8, 26.56)
Circle 4 Focus: (185.92, 26.56)
Circle 5 Focus: (239.04, 26.56)
Circle 6 Focus: (292.16, 26.56)
Circle 7 Focus: (345.28, 26.56)
Circle 8 Focus: (372.63, 72.1)
Circle 9 Focus: (319.52, 73.25)
Circle 10 Focus: (265.47, 72.64)
Circle 11 Focus: (212.35, 73.25)
Circle 12 Focus: (159.23, 72.64)
Circle 13 Focus: (106.11, 73.25)
Circle 14 Focus: (52.99, 72.64)
<svg width="400" height="100"><rect width="400" height="100" style="fill:blue;" /><circle cx="26.560000000311106" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="79.68000000093332" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="132.80000000155553" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="185.92000000217774" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="239.04000000279996" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="292.16000000342217" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="345.2800000040444" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="372.6271770491687" cy="72.09972230654316" r="26.550000000311105" fill="white" /><circle cx="319.5195599732359" cy="73.24663493712801" r="26.550000000311105" fill="white" /><circle cx="265.47097406711805" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="212.35454341475625" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="159.23097406587362" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="106.11454341351183" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="52.99097406462921" cy="72.63752174440503" r="26.550000000311105" fill="white" /></svg>
```
And the SVG looks like this...

## Test 3
`(function(e,f,g){...})(400,400,3)`
```
Highest possible radius: 101.68
Circle 1 Focus: (101.69, 101.69)
Circle 2 Focus: (298.23, 153.98)
Circle 3 Focus: (154.13, 298.19)
<svg width="400" height="400"><rect width="400" height="400" style="fill:blue;" /><circle cx="101.69000000059772" cy="101.69000000059772" r="101.68000000059772" fill="white" /><circle cx="298.2343937547503" cy="153.97504264473156" r="101.68000000059772" fill="white" /><circle cx="154.13153961740014" cy="298.19269546075066" r="101.68000000059772" fill="white" /></svg>
```
And the SVG looks like this...

They aren't all pretty.
## How it works
Ungolfed code below. This program has two assumptions:
1. One circle will always be in the corner. This seems like a pretty safe bet.
2. Every circle will always be touching another circle. I don't see why they wouldn't be.
The program starts by calculating a large radius based on the box dimensions. It then tries to fit one circle in the corner of the box. If that circle fits, it extends a diameter line from that circle and tries to create a circle at the end of the line. If the new circle fits, another line will be extended from the new circle. If it doesn't fit, the line will swing 360 degrees, checking for open spaces. If the box fills up before the desired number of circles are created, the radius is reduced and it all starts over again.
## Ungolfed Code (snippet)
```
// this functions attempts to build a circle
// at the given coords. If it works, it will
// spawn additional circles.
function C(x, y, X, Y, r, cc){
// if this circle does not fit in the rectangle, BAIL
if(X-r < 0 || X+r > x || Y-r < 0 || Y+r > y)
return cc;
// if this circle is too close to another circle, BAIL
for(var c in cc){
if( Math.sqrt(Math.pow(cc[c].x - X, 2) + Math.pow(cc[c].y - Y, 2)) < (r*2) )
return cc;
}
// checks passed so lets call this circle valid and add it to stack
cc.push({"x": X, "y": Y});
// now rotate to try to find additional spots for circles
var a = 0; // radian for rotation
while(a < Math.PI){
XX = Math.cos(a)*r*2 + X;
YY = Math.sin(a)*r*2 + Y;
cc = C(x, y, XX, YY, r, cc);
a += .01; // CHANGE FOR MORE OR LESS PRECISION
}
return cc;
}
// this function slowly reduces the radius
// and checks for correct solutions
// also prints svg graphic code
(function B(x, y, n){
var r = x + y; // pick a big radius
var X, Y; // these are the coords of the current circle. golf by combining this with `var r..`?
var cc = []; // array of coordinates of the circles
// while we cant fit n circles, reduce the radius and try again
while(cc.length < n){
X = Y = r;
cc = C(x, y, X, Y, r, []);
r-=.01; // CHANGE FOR MORE OR LESS PRECISION
}
console.log('Highest possible radius: ' + Math.round(r*100)/100);
var s = '<svg width="' + x + '" height="' + y + '"><rect width="' + x + '" height="' + y + '" style="fill:red" />';
for(var c in cc){
console.log('Circle '+c+' Focus: (' + Math.round(cc[c].x*100)/100 + ', ' + Math.round(cc[c].y*100)/100 + ')');
s += '<circle cx="' + cc[c].x + '" cy="' + cc[c].y + '" r="' + r + '" fill="blue" />';
}
s += '</svg>';
console.log(s);
document.write(s);
})(150, 150, 5);
```
] |
[Question]
[
Given a list of 2d (x, y) coordinates, determine how many unit squares (edge length 1 unit) can be formed using the coordinates.
* Input will be an array of 0 or more pairs of coordinates:
e.g. in JavaScript: `numofsq([[0,0], [1,0], [1,1], [0,1]])`
* No duplicate coordinates in input
* Input order will be random (random 2d coordinates).
* Coordinate form: [x-coordinate, y-coordinate] (duh)
* Order of coordinates: [0,0], [1,0], [1,1], [0,1] and [0,0], [0,1], [1,1], [1,0] denote the same unit square (to be counted just once)
* Coordinates can be negative or positive integers (duh)
* Function will return just the number of unit squares possible, 0 or more.
Test cases:
```
Input Coordinates Pairs Expected Output
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2] 2
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1] 3
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0] 4
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9] 4
```
---
### Spoiler Alert: Solution stuff here-onwards [JS]
Non-Golfed, quick and dirty, brute-force approach (included to provide some directions).
```
//cartesian distance function
function dist(a, b) {
if (b === undefined) {
b = [0, 0];
}
return Math.sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]));
}
```
---
```
//accepts 4 coordinate pairs and checks if they form a unit square
//this could be optimized by matching x,y coordinates of the 4 coordinates
function isUnitSquare(a) {
var r = a.slice(),
d = [],
c = [],
i,
j = 0,
counter = 0;
for (i = 1; i < 4; i++) {
if (dist(a[0], a[i]) === 1) {
d.push(a[i]);
r[i] = undefined;
counter++;
}
}
r[0] = undefined;
c = d.concat(r.filter(function(a) {return undefined !== a}));
if (dist(c[0], c[1]) === 1) {j++};
if (dist(c[1], c[2]) === 1) {j++};
if (dist(c[2], c[0]) === 1) {j++};
return counter === 2 && j === 2;
}
```
---
```
//a powerset function (from rosetta code)
//however, we will need only "sets of 4 coordinates"
//and not all possible length combinations (sets of 3 coords or
//sets of 5 coords not required). Also, order doesn't matter.
function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(ary[i]));
}
}
return ps;
}
//so to capture only sets of 4 coordinates, we do
var res = powerset([[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]])
.filter(function (a) {return a.length === 8;});
//and a little bit of hoopla to have a nice set of sets of 4 coordinates.
//(Dizzy yet? Wait for the generalized, 3D, cube of any edge length version ;))
var squareQuads = res.map(function(ary) {
return ary.join().match(/\d\,\d/g)
.map(function(e) {
return [+e.split(',')[0], +e.split(',')[1]];
});
});
```
---
```
//Finally, the last bit
var howManyUnitSquares = 0;
squareQuads.map(function(quad) {
if (isUnitSquare(quad)) {
howManyUnitSquares++;
}
});
console.log(howManyUnitSquares);
```
---
```
//Cleaning up and putting those in-line stuff into a function
function howManySquares(r) { //r = [[x,y], [x,y], [x,y], [x,y], ......];
var res = powerset(r)
.filter(function (a) {return a.length === 8;});
var squareQuads = res.map(function(ary) {
return ary.join().match(/\d\,\d/g)
.map(function(e) {
return [+e.split(',')[0], +e.split(',')[1]];
});
});
var answer = 0;
squareQuads.map(function(quad) {
if (isUnitSquare(quad)) {
answer++;
}
});
return answer;
}
```
[Answer]
## APL(Dyalog), 30
```
+/{(2-/⍵)≡2-/,⍳2 2}¨,∘.,⍨⍣2⊂¨⎕
```
Well, in most cases, readability and char count is proportional.
---
**Sample Output**
```
⎕:
(0 0)(0 1)(1 0)(1 1)(0 2)(1 2)(2 2)(2 1)(2 0)
4
```
---
**Explaination**
So, 4 points forms a unit square if and only if their relative positions are (1,1),(1,2),(2,1),(2,2)
`{(2-/⍵)≡2-/,⍳2 2}` is a function that return 1 or 0 (true/false) given a set of 4 points as input based on whether they are in relative positions and sorted in the order (1,1),(1,2),(2,1),(2,2):
`⍳2 2` Generate a 2×2 matrix of the points (1,1),(1,2),(2,1),(2,2)
`,` Unravel that matrix to an array of points
`2-/` Pair-wise subtraction reduce: (1,1) - (1,2) ; (1,2) - (2,1) ; (2,1) - (2,2), which gives the array [(0,-1),(-1,1),(0,-1)]
`(2-/⍵)` Pair-wise subtraction reduce on the input
`≡` Check if the two arrays equal
The main program
`⎕` Takes input and evals it. Things like `(0 0)(0 1)(1 0)(1 1)` evaluates to a nested array (Equivalent of `[[0,0],[0,1],[1,0],[1,1]]` in JS)
`⊂¨` For every point (`¨`), enclose it in a scalar (`⊂`) (`[[[0,0]],[[0,1]],[[1,0]],[[1,1]]]`)
`∘.,⍨⍣2` For every pair of elements of the array, concatenate them to form a new array. (`[ [[0,0],[0,0]],[[0,0],[0,1]]...`) Repeat once. This gives all sets of 4 points that can be made using the given points. In some of these sets, the same point would be used multiple times, but these would not be unit squares so no need to waste keystrokes to remove them. (`,` concatenates 2 arrays, `∘.` means "do that for every pair of elements", `⍨` means "use right operand as both left and right operands", and `⍣2` means "do this twice")
`,` As the previous operation would give a 4-dimensional array (note that nested arrays and multi-dimensional arrays are different things in APL), we have to unravel it to get an array of sets (of 4 points).
`¨` For each of the sets,
`{...}` execute the aforementioned function. The result would be an array of 0s and 1s indicating whether the set is a unit square. Note that because the function also check ordering, duplicates are eliminated.
`+/` Finally, sum resulting array to get the count.
[Answer]
# Mathematica 65 chars
```
f@d_ := Length@Select[Subsets[d, {4}], Sort[g@#] == {1, 1, 1, 1, √2, √2} &]
```
**Tests**
```
f[{{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 2}, {1, 2}}]
```
>
> 2
>
>
>
```
f[{{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 2}, {1, 2}, {2, 2}, {2, 1}}]
```
>
> 3
>
>
>
```
f[{{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 2}, {1, 2}, {2, 2}, {2, 1}, {2,0}}]
```
>
> 4
>
>
>
```
f[{{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 2}, {1, 2}, {2, 2}, {2, 1}, {2,0}, {9, 9}}]
```
>
> 4
>
>
>
**Explanation**
Generates all subsets of 4 points and checks all the inter-point distances.
The sorted inter-point distances for a unit square are: `{1, 1, 1, 1, √2, √2}.
`Length` then counts the number of unit squares.
[Answer]
## Ruby, ~~164~~ ~~161~~ ~~153~~ 147 characters
```
f=->a{a.combination(4).map(&:sort).uniq.count{|x|[x[1][0]==l=x[0][0],x[3][0]==m=x[2][0],x[2][1]==n=x[0][1],x[3][1]==o=x[1][1],m-l==1,o-n==1].all?}}
```
It's actually *very* readable, except for the part that tests whether it's a unit square or not.
Probably many improvements possible, attempting to find them now.
Samples (all of them work):
```
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2]]] #--> 2
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1]]] #--> 3
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]]] #--> 4
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9]]] #--> 4
```
I may be able to find a trick with `transpose`, but I've been trying for a while and I can't. Here's what it does:
```
irb(main):001:0> a = [[5, 10], [5, 11], [6, 10], [6, 11]]
=> [[5, 10], [5, 11], [6, 10], [6, 11]]
irb(main):002:0> a.transpose
=> [[5, 5, 6, 6], [10, 11, 10, 11]]
```
[Answer]
## Python, 61 chars
```
f=lambda l:sum(1for x,y in l if{(x+1,y),(x,y+1),(x+1,y+1)}<l)
```
Sample:
```
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2)})
2
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1)})
3
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1), (2,0)})
4
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1), (2,0), (9,9)})
4
```
[Answer]
# Mathematica, 56 characters
```
f=Count[#-#[[1]]&/@Subsets[{}⋃#.{1,I},{4}],{0,I,1,1+I}]&
```
] |
[Question]
[
Good Afternoon Golfgeneers.
This is reasonably long and detailed question. Given what it was asking, it needed to be. If you have any questions, please ask them. If there is anything that isn't clear, please alert me to it so I can fix it. This is probably on the tougher side of codegolf.
We are building a lightweight computer, and we need the lightest weight file system possible. The shortest code will be chosen.
We are providing a cutting edge 65536 byte hard drive. For the sake of this prototype, it will be a direct image file, which your program can assume exists, and is in whichever location suits you - ie, a binary file representing the entire hard disk. You may assume that this image is already 'formatted' - ie. if your program relies on something being in the file to work, it can be. If you require the initial empty state to be something other then all-zeros, please state what it is.
There is no memory limit as to RAM used by your application.
The input and output commands will require an interface to the actual hard drive. Like the disk image, your program can assume that the file for input exists, and is wherever you want it to be. Likewise, your program can output wherever is convenient. It must however close the file after executing the input or output command.
You are not being provided with a format which you must use for the disc image - you are free to develop your own. It must be capable of storing up to 248 files. Any file greater then 256 bytes can count as a new file for the sake of this limit for every 256 bytes or part thereof. A file can be up to 63488 bytes. Basically - it must be as capable as a hard drive with 248 sectors of 256 bytes each.
The reasoning behind these seemingly sizes is to give you 2048 bytes of 'administration' - to store details of the files. Each file/folder must be accessible by a name of 4 alphanumeric characters, which may be case sensitive or insensitive as per your preference. If your program supports names of 4 or less characters, then there is bonus of a 0.95 multiplier.
Your program must accept, via stdin, the following commands. Parameters will be separated by a space. The command will be terminated by a newline.
* L - List the names to stdout of all the current files and their sizes in bytes, separated by newlines.
* C a b - Copy file a to new file b.
* D a - Delete file a
* R a b - Renames file a to new name b
* I a - Adds the input file (see note above) as file a
* O a - Outputs file a to the output file
The following errors may be reported to STDOUT or STDERR as valid reasons for a command to fail to execute. You may choose to only print ERR# where # is the number of the error:
* 1 - File doesn't exist
* 2 - File already exists
* 3 - Out of space\*
\* Note that your program can not issue this just because it is out of continuous space. If you still have sectors available, you must defragment the disk to make it work.
A folder system is optional - however, will net a bonus of a 0.8 multiplier to your score. If it supports more then 1 level of directory, it will net a bonus of a 0.7 multiplier (not in addition to the 0.8). For the bonus, you must have
* L, R, C and D only work within the current directory. L must list folders in the current directory, as well as the files.
* New command M a b moves file a to folder b. If b is '.', moves file to the parent director
* New command G a goes to folder a. If a is '.', goes to parent folder
* R must also rename folders
* D must also delete folders, and any files/folders within them
* C must also copy folders, and any files/folders within them
The following additional errors may be reported to STDOUT or STDERR as valid reasons for a command to fail to execute.
* 4 - Folder doesn't exist
* 5 - File, not folder required - where, I and O require file names, and a folder was given
Your score is:
* The size, in bytes, of your source code
* Multiplied by
+ 0.95 if you support names of 4, or less characters
+ 0.8 if you support a single level of folders
+ 0.7 if you support multiple levels of folders
+ 0.95 if you support commands (not necessarily file names) in lower or uppercase
Good luck.
[Answer]
### Ruby, score 505.4 (560 characters)
```
x,a,b=gets.chomp.split
f=IO.read('F')
e=f[0,4*X=248].unpack 'A4'*X
s=f[4*X,2*X].unpack 's'*X
d=f[6*X..-1].unpack 'A'+s*'A'
u,v,w,y=[[N=nil,q=e.index(a),!t=e.index(""),"e[t]=a;s[t]=(d[t]=IO.binread('I')).size"],[!q,r=e.index(b),!t,"e[t]=b;d[t]=d[q];s[t]=s[q]"],[!q,N,N,"e[q]=d[q]='';s[q]=0"],[!q,r,N,"e[q]=b"],[!q,N,N,"IO.binwrite('O',d[q])"],[N,N,N,'X.times{|i|e[i]>""&&puts(e[i]+" #{s[i]}")}']]['ICDROL'=~/#{x}/i]
u&&$><<"ERR1\n"||v&&$><<"ERR2\n"||w&&$><<"ERR3\n"||eval(y)
d=d*""
d.size>63488&&$><<"ERR3\n"||IO.write('F',(e+s+[d]).pack('A4'*X+'s'*X+'A63488'))
```
Notes:
* Filesystem is located in file `F` in the current directory. `F` must exist and may be created/formatted via the following command: `IO.write('F',(([""]*248)+([0]*248)+[""]).pack('A4'*248+'s'*248+'A63488'))`.
* Input file is always `I` also in the current directoy, output file is `O`.
* Since it wasn't required to check errors, be sure to type correct commands (i.e. no unsupported commands, no missing arguments, too long filenames).
* The file system implementation is extremely simple - for each command the full hard drive is read into memory and rebuild upon (successful) completion.
Bonuses:
* Filenames may be 1-4 chars
* Commands may be upper or lower case
The code is not yet fully golfed but shows already that for a substancial better score I'd try a completely different approach.
Test session (only STDIN/STDOUT is shown but of course each command is prepended by calling the above program):
```
> L
> I F001
> L
F001 558
> I F001
ERR2
> C F002 F003
ERR1
> C F001 F003
> L
F001 558
F003 558
> C F001 F003
ERR2
> R F002 F003
ERR1
> R F001 F003
ERR2
> R F001 F002
> L
F002 558
F003 558
> O F001
ERR1
> O F002
> L
F002 558
F003 558
> D F001
ERR1
> D F002
> L
F003 558
> C F003 F001
> L
F001 558
F003 558
> D F001
> L
F003 558
> D F003
> L
```
[Answer]
## Tcl, score 487,711 (772 bytes)
```
{*}[set a {interp alias {}}] s {} dict se f
{*}$a u {} dict un f
{*}$a h {} dict g
proc 0 {} {return -level 1}
proc p {n a b} {foreach l $n {proc $l $a "global f c;$b;S"}}
p L\ l {} {puts [join [dict k [h $f {*}$c]] \n]}
p C\ c a\ b {s {*}$c $b [h $f {*}$c $b]}
p D\ d a {u {*}$c $a}
p R\ r a\ b {s {*}$c $a [h $f {*}$c $b];u {*}$c $b}
p I\ i a {set i [open i rb];s {*}$c $a [read $i];close $i}
p O\ o a {set o [open o wb];chan puts $o [h $f {*}$c $a];close $o}
p M\ m a\ b {set d $c;if {$b eq "."} {set d [lrange $c 0 end-1]};s {*}$d $a [h $f {*}$c $a];u {*}$c $a}
p G\ g a {if {$a eq "."} {set c [lrange $c 0 end-1]} {lappend c $a}}
p S {} {puts [set o [open F wb]] $f;close $o;return}
set f [read [set i [open F rb]]]
close $i
set c {}
while 1 {{*}[split [gets stdin]]}
```
Bonuses (gotta catch them all):
* support file names with 4 byte or less - or more. I don't care. **0.95**
* support multilevel folders **0.7**
* support lower and upper case commands **0.95**
Known limitations:
* File system `F` must already exist. Empty or whitespace is fine.
* I don't check the size of the file system - I don't care.
* Input file is `i`, outputfile is `o` and the filesystem is in `F`
* Errors will crash the program.
* No checks if file/directory exist, might be an error.
* No difference between a file and a directory. Yes, you can write a directory to output and use this as file system.
* Using a file as directory that is not a valid file system will result in an error.
* No input validation. Invalid commands may throw an error. Or not: `eval puts [expr 1+2]`
* No command to create a directory (was not my idea), but will be created implicit by `I` (also not my idea, and `G` doesn't create)
* `G` does not validate the directory.
* Filenames could contain spaces, but the interface does not support them.
* Concurrent modification of the same file system is not supported.
Some hacks:
* `eval puts $c` -> current directory, separated by spaces.
* `exit` - no comment.
* `lappend c .` -> switches into the subdirectory `.`
[Answer]
# Python 2.7 373 (413 bytes)
```
from pickle import*
E=exit;o=open;D,I,W='DIw'
def T(i):w[i]in d and E('ERR2')
d=load(o(D))
w=raw_input().split();b=w[0].upper()
if b=='L':
for k in d:print k,len(d[k])
elif b==I:T(1);d[w[1]]=o(I).read()
else:
a=w[1];a in d or E('ERR1')
if b in'RC':T(2);d[w[2]]=(b<D and d.get or d.pop)(a)
if b==D:d.pop(a)
if b=='O':o(I,W).write(d[a])
d=dumps(d,-1)
x=65536-len(d)
x>-1or E('ERR3')
o(D,W).write(d+I*x)
```
The disk is saved in the Python pickle-Format: to create an empty disk you have to put these two bytes '}.' at the beginning and optionally 65534 fill bytes afterwards. Supports arbitrary large filenames (\*0.95), upper and lowercase commands (\*0.95) and hard links (:-).
] |
[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/10709/edit).
Closed 2 years ago.
[Improve this question](/posts/10709/edit)
The worst part about long lines or code or math equations are the parentheses. Nobody wants to read through `2x(3y+4*abs(x^[2*e^x])-5{3(x+y)-5})`!
So, the goal of this challenge is to make it at least slightly easier to read these parentheses-filled beasts! For the above math equation, the output should be:
```
2x (
3y+4*abs (
x^ [
2*e^x
]
)
-5 {
3 (
x+y
)
-5
}
)
```
A parenthesis is defined as either of these characters: `()[]{}`. Indents should each be two spaces, and there should be one space of seperation between the expression and the parenthesis: `2x (`, `x^ [` as some examples.
I would like to debut the [Atomic Code Golf metric](http://meta.codegolf.stackexchange.com/questions/403/new-code-golf-metric-atomic-code-golf) in this question. Take out all separators in your code (`()[]{}. ;` to name some common ones), and then take the length of your program if every reserved word and operator were 1 character long. That is your program's score. `if x**(3.2)==b[3]:print x` is 11 points: `if|x|**|3|.|2|==|b|3|print|x`, or `ix*3.2=b3px`. Any quick questions about the metric can be posted here; larger questions should be discussed in meta using the link above.
Lowest score wins. Good luck, have fun!
[Answer]
## C, 139 137 chars, 67 tokens
```
i,n; // 2 tokens
main(c){ // 2 tokens
while(~(c=getchar())) // 5 tokens
n=strchr("([{}])",c)? // 11 tokens
n=c%4!=1, // 7 tokens
i+=n*4-2, // 7 tokens
printf("\n%*s%c"+n,n?1:i,"",c) // 15 tokens
: // 1 token
!printf("\n%*s%3$c"+!n*4,i,"",c); // 17 tokens
}
```
Logic:
* Read until EOF (detect it because `~EOF==0`).
* If parenthesis, check open/close (for `c` in `")]}"`, `c%4==1`), update indentation (`i`), print with some whitespace.
* If not, print the character, possibly prefixed by newline and indentation (`n` is true after parenthesis).
[Answer]
## Python, 102(?) Tokens
(Please correct if I didn't count correctly)
```
def f(t):
#1 2 3
l,s,p,c,e,n=0,"",1," ",")]}","\n"
# 4 5 6 7 8 9ab cd e fgh ijklm no p
for i in t:
# q r s t
if i in"([{": l+=2;s+=c+i+n+l*c
# u v w xyzAB CD E FG HIJKLMNOP
elif i in e: l-=2;s+=n+l*c+i+p*(n+l*c);p=1
# Q R S T UV W XY Z123456789 abcde fgh
else:
# i
if len(s) and s[-1]in e: s+=n+l*c
# j k l m n o p q rs tuvwx
s+=i;p=0
# yz A BCD
return s
# E F
```
[Answer]
## Perl, 86 char
57 tokens? (21+25+5+3+1+2?) Newlines are significant.
```
s![[{()}\]]!1-(3&ord$&)?" $&
"." "x++$x:$/.($y=" "x--$x)."$&
$y"!ge;s/
*
/
/g;print
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~76~~ 74
```
(a,d)=>(d=0)||a.replaceAll(/[(\[{]/g,b=>` ${b}\n`+' '.repeat(++d)).replaceAll(/[)\]}]/g,b=>`\n${(f=' '.repeat(--d))+b}\n${f}`)
```
[Try it online!](https://tio.run/##VY7BboJAEIbvPMUcTNgtII22TROCSQ8eempSexONCwy4zbpLdlcLQZ6dQqONzmky/3xf/m92YibTvLLB6bUPQ7B7boAJjSxvAGturAEuYbl6AX6oBB5QWma5kj6kRwtS2TH@ev9wVlZzWU4rrayyTYVTjZVgGb4JATEUR5mNGDHIdLb34ZKOPgqtA8OcmAbLdIl2AMYi0d9Zoz1qeUmuViLxBz6xXNbVv9ItXXovjpwucpwi7gnzcxovSB4/0vOZ3XQj4Zok63YTln4aL3YwadMukTvPBXDHN2SWeF5O6T1Dk013ZRI5aUkR3xJBMBDeaJq0RbejfZQpaZTAqVAlKYg7q8m88Z4eWGpIvV3PHnBbb2jw3M5J7TXD0lGX0v4X "JavaScript (V8) – Try It Online")
```
(a,d)=> pas argument a and d (a is the string, d is just as decleration)
(d=0)|| set d to 0
a.replaceAll( replace everything in a that matches....
/[(\[{]/g, [,(,{ with....
b=> pass matches into function
` ${b}\n` space, bracket(the match) and newline
+' '.repeat(++d) increment d and repeat the 2 spaces d times
)
.replaceAll(/[)\]}]/g, match all ),],} and replace them with....
b=> pass matches into function
`\n${(f=' '.repeat(--d))+b}\n${f}` newline, decrement d and repeat the 2 spaces d times, closing bracket(the match), newline and once again the repeated spaces
)
```
results in
```
#a#,#d#=>#d#=#0#||#a#replaceAll#/#[#(#\#[#{#]#/#g#b#=>#`# #$#{#b#}#\#n#`#+#'# # #'#repeat#++#d#replaceAll#/#[#)#\#]#}#]#/#g#b#=>#`#\#n#$#{#f#=#'# # #'#r#e#p#e#a#t#--#d#+#b#}#\#n#$#{#f#}#`#
```
] |
[Question]
[
In the UTF-8 encoding bytes of the Form `10******` can only appear within multi-byte sequences, with the length of the sequence already being determined by the first byte.
When UTF-8 text is split within a multi-byte UTF-8 character sequence, this prevents that the second part of the sequence is wrongly detected as another character.
While in for normal Text files this error-checking is a good idea (and prevents unwanted ASCII control characters/null-bytes from appearing in the byte-stream), for code-golf this redundancy is just wasting bits.
Your task is to write **two** programs or functions, one decoder and one encoder converting between code-points and "compressed UTF-8",
defined the following way:
```
1 byte sequence:
bytes 0x00 to 0xbf -> code-points 0x00 -> 0xbf
2 byte sequence (code-points 0x00 -> 0x1fff):
0b110AAAAA 0bBBCCCCCC
-> code-point 0b (BB^0b10) AAAAA CCCCCC
3 byte sequence (code-points 0x00 -> 0xfffff):
0b1110AAAA 0bBBCCCCCC 0bDDEEEEEE
-> code-point 0b (BB^10) (DD^10) AAAA CCCCCC EEEEEE
4 byte sequence (code-points 0x00 -> 0x7ffffff):
0b11110AAA 0bBBCCCCCC 0bDDEEEEEE 0bFFGGGGGG
-> code-point 0b (BB^10) (DD^10) (FF^10) AAA CCCCCC EEEEEE GGGGGG
```
Or in short form: The compressed UTF-8 code-point for a sequence of bytes, is the regular UTF-8 code-point for that byte-sequence, with the difference of the high two bits and `0b10` prepended on the start of the number.
Examples:
```
decode:
[] -> []
[0xf0, 0x80, 0x80, 0x80] -> [0x00]
[0x54, 0x65, 0x73, 0x74] -> [0x54, 0x65, 0x73, 0x74]
[0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0xc2, 0xbb, 0xc2, 0xb5, 0xc2, 0xba, 0xc2, 0xa9, 0xc2, 0xbf, 0xc2, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0xe2, 0x84, 0x95, 0xc3, 0x97, 0xe2, 0x84, 0x95] -> [0x2115, 0xd7, 0x2115]
[0xf0, 0x9f, 0x8d, 0x8f, 0xf0, 0x9f, 0x92, 0xbb] -> [0x1f34f, 0x1f4bb]
[0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb] -> [0x1f34f, 0x1f4bb]
encode:
[] -> []
[0x54, 0x65, 0x73, 0x74] -> [0x54, 0x65, 0x73, 0x74]
[0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0x2115, 0xd7, 0x2115] -> [0xe2, 0x84, 0x95, 0xc3, 0x97, 0xe2, 0x84, 0x95]
[0x1f34f, 0x1f4bb] -> [0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb]
// [0x1f34f, 0x1f4bb]=[0b1_1111_001101_001111,0b1_1111_010010_111011]
// [0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb]=[0b11101111,0b10001101,0b11001111,0b11101111,0b10010010,0b11111011]
```
## Rules
* You are allowed to use your languages internal string representation instead of code-point arrays for input/output
* When encoding a code-point you should return the shortest sequence representing that code-point
* The input may contain multiple code-points / bytes representing multiple code-points
* You only need to handle code-points in the range (0x00 to 0x10ffff)
* You score will be the sum of the lengths of the two programs
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins
[Answer]
# JavaScript (ES10), 228 bytes
This code is solely based on bitwise operations. There may be a better way with some built-ins. At any rate, I can't say I'm very happy with it.
## Decoder (105 bytes)
```
a=>a.flatMap(i=v=>i--?(n=n<<6|v&63|(v&192^128)<<5*s-4*i,i?[]:n):(s=i=(v>>4)**4>>14)?(n=v&~0>>>26+s,[]):v)
```
[Try it online!](https://tio.run/##nVJBTsMwELz3FXtAjV3SKEnTtCm1e@LIiWMUhJPGJagkqImsSlBegMSFI/yD9/QDPKHYTgWuACFxyGh2d2bWtnLNBKuzVXHb9Mtqnu842TFCmcOXrDljt6gggtCi35@hkpTTaXgvuuHgHomuF/kXnj/G0@mwV/eDXmEXsziZlHiCalIQJCgNcK8XUOoFWLlF98GllPrhcW3HCZ4IvDuJOwAxxIktP0jstnLX3LXBXY8PUGncteuaumGgZuFQ4WigMWh1P04MZ5qqXqrnKVPIIs255mmb8qfKSMx8PdGOPR8anH3xNmPf50b/H1tz7Rzr20btPn3baKTwcNqm@56ndXOtUNX3l4/0pvFco@ZmP9rftM3z@CDQbY8H6eHZjJRM89zw89/8naTj8Gp1yrIrhGKQD5BCgoFQuJPJy7yBVV4DAY4YPpGdrCrrapk7y2qBLmM4upNj50b@ukJ5LHdtwTEIp6nOm1VRLpAXYuxcV0WJLBssvIFk7/lUyGUEUrOegfX@9rR9eZZowQSs7eujtbmU@zd49wE "JavaScript (Node.js) – Try It Online")
A somewhat interesting formula in there is `(v >> 4) ** 4 >> 14` which turns the leading byte \$v\$ into the number of extra bytes in the sequence.
| v >> 4 | (v >> 4) \*\* 4 | (v >> 4) \*\* 4 >> 14 |
| --- | --- | --- |
| 0b0000 (0x0) | 0b0000000000000000 | 0 |
| 0b0001 (0x1) | 0b0000000000000001 | 0 |
| ⋮ | ⋮ | ⋮ |
| 0b1011 (0xB) | 0b0011100100110001 | 0 |
| 0b1100 (0xC) | 0b0101000100000000 | 1 |
| 0b1101 (0xD) | 0b0110111110010001 | 1 |
| 0b1110 (0xE) | 0b1001011000010000 | 2 |
| 0b1111 (0xF) | 0b1100010111000001 | 3 |
## Encoder (123 bytes)
```
a=>a.flatMap(n=>n<192?n:(s=n>>13?n>>20?8:4:2,g=i=>i<s?[...g(i*2),n/i**6&63|n/s**5/i/i&192^128]:[n/s**6&63/s|384/s|192])(1))
```
[Try it online!](https://tio.run/##hVFBbsIwELzzij1UxE5TBycBkoCTU4899RilwoGEGlEHkQghUX5QqZce23/0PXygT6C2QRU9VD14tDszO7uSF3zDm@larNobWc/KY8WOnCWcVEve3vEVkiyRYxp5qYxRw2SSUD9V6PXSMA5iz5kzwRIxbtKMEDJHwvawI11h24PuwH@WbmPbfVe4oqsyHqgX5nFmSC27zbMfBgqVlmNEMT6Osg5ABlnuqAe5c@p6237gQG876Gsc@gYD7flDuZgsCs0VRi@4Rh6ZujJ1cUr513WR6FFqfLOhRt2dMkpP96G5JzKOqbknMr7f6mUerfzArKFVUJzvKQ0RzkyKqU9MZFIqfU8n75CqXt/y6SNCGaijC8gxsAR2KnlZtrAuG2BQIY5HipnWsqmXJVnWczTJ4GqnZPKkvnijZ6ze1oJr2JC2vm/XQs4RHWBMFrWQyHLAwnvIzzM/DrWMQXHZp2B9fb4e3t8UWhCDdfh4sfYTtX@Pj98 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 570 bytes
```
sub{$_=join'',map sprintf('%08b',$_),@_;%c=qw(00 10 01 11 10 00 11 01);my@r;push@r,oct'0b'.(s/^110(.{5})(..)(.{6})// ? "$c{$2}$1$3":s/^1110(.{4})(..)(.{6})(..)(.{6})// ? "$c{2}$c{$4}$1$3$5":s/^11110(...)(..)(.{6})(..)(.{6})(..)(.{6})// ? "$c{$2}$c{$4}$c{$6}$1$3$5$7":s/.{8}//*$&) while y///c;@r},
sub{map 128^oct"0b$_",map{$_=sprintf"%032b",$c=$_;$c>0xfffff?do{/(..)(..)(..)(...)(.{6})(.{6})(.{6})$/;"01110$4",$1.$5,$2.$6,$3.$7}:$c>0x1fff?do{/(..)(..)(....)(.{6})(.{6})$/;"0110$3",$1.$4,$2.$5}:$c>0xbf?do{/(..)(.{5})(.{6})$/;"010$2",$1.$3}:do{/(.)(.{7})$/;(1-$1).$2}}@_}
```
[Try it online!](https://tio.run/##zVXbbtpAEH3nK1bbJbaJY@@Czc1y4qrNU6MiRX0jiYWNt6FKgBiiECF/O50dG2wobXp5qQXj2Zlzzngvmp0n6YO70dk4iWfjJDVZMkXH8PXN4jlas9D/NptMNc18HM3JYp5Opkupa3XejTSThYYZhF499p9edM6J4IQLIgQ6XDlcGN7ja5B68@fFfZCas3ip8Uiz9IV9JwTXrbWbGbplwX/dzgzbJheEsnjNmhkTrEX7iEOgUwUeoQADeA7ymLtlKipif2T@pGwuArZdSLGOErPW3cy2G@zEIC/3k4eEvNq2HXtBmpk1tVBqeUSzewczpDxiIVULppavWDNa561mRE0W@yz0WHzOV1I9F@PZ2tZ3n4j/8gtLy2yPcjUf5oCIsJhrsqbF2iZrWayT9VFRHBE8UCt0OCwuyjgo4xYCUZWe701J4qyZc1pZP0epdAfTujhjwrBgAbMgzDaGV3t81ZmE85SmMJCzVK8ReHYHrTaE0fCW@OfKEnJbRPiKc5Mom@dwnA@rIImg7p4tCftY11H5tqtsp4XW2WKP56rsKFLRCBHRSNlRD32JfrRVehtXVY2bmENO4bsVf1T6uUoRl5X4X1ZOkN3FeffymjjvXkfZ/ey2QlMIRI4Ro0bHdqOH9bpjtOhX471ixltNIVsOJoR0osNvrCjF6CcVDYno8vmFHh65oqX965H7H4/RsY3Jdf5sm6uahwtZ6P3GloDGOzI8JuIPeSRC1Y9DrrpP/hLCLMMCIlz5kDgQe7M2yiMzl@R5EeWKstAeAH95tFrSWOOZmSarJZlIkiaSJE9E@zD4eKmR0XRMmIT@jR72dXq2e26m1EOy6nyT6Rx632pu@AG0@yIcfJ0t/RMm9UDljTx8n6wmEhihQaBLkh3TvFHwHLO9Qs7aC0IA8LzsE9SAHECTeJmMVQR8iAANBmDhi0xCMUzVNKgKUrjrtMEnjfQJNHHVn09PPa3RaHwefCEQz7xaVsOCRCXVzQjJy@vrwTW8QRKI9P3VFWBxxnD5FXOo3HY65av6iprbWQWQG/LbLNt8Bw "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 170 bytes
## Decoder, 81 bytes:
```
≔⮌AθWθ«≔⊟θι¿‹ι¹⁹²⊞υι«≔⍘ι²η≔⌕η0ζ≔E⊖ζ⍘⁺⁶⁴⁰⊟θ²ε⊞υ⍘⁺⁺⭆ε✂겦⁴¦¹✂η⊕ζχ¹⭆ε✂κ⁴χ¹¦²»»Eυ⍘ι¹⁶
```
[Try it online!](https://tio.run/##bVBNa8JAED2bXzF4moUtrDa1FU8tpSC0EOpRPIQ4NUu3a8wmViz@9u1sYsSUXh7LvI95s1meltk2Nd4/Oqc3Ft9pT6UjnNuirlAICTsxi75zbQhwJ@AnGpyVybbggQTN/EB/AL6Sc6gljKZjISCpXY71mSbjKFg771PqaFGV2m6CYcwpeZB19Iu2a8wlDNWQqeM19ZYW@ExZSV9kK1rjkQVXaYmpHU5iJaGtJ0I6AzUZXae/hgbaQcgnCQujM8JPdkuI@aSQ0c641tz2949Up/g3Ir4o2jbc5BSdooS1VXNPv1H4wQlrZ94vl@pA3EAdHuKA07uA2W3zvg/YZ1crf7M3vw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⮌Aθ
```
Reverse the input so that the bytes can be easily processed separately.
```
Wθ«
```
Repeat while there is still input to process.
```
≔⊟θι
```
Get the next byte.
```
¿‹ι¹⁹²⊞υι«
```
If this is a single byte code, then just push the code, otherwise:
```
≔⍘ι²η
```
Convert the first byte to binary.
```
≔⌕η0ζ
```
Get the total number of bytes in the sequence.
```
≔E⊖ζ⍘⁺⁶⁴⁰⊟θ²ε
```
Get the remaining bytes, add 640 to each, and convert them to base 2. This results in a string of the form `1XBBCCCCCC`.
```
⊞υ⍘⁺⁺⭆ε✂겦⁴¦¹✂η⊕ζχ¹⭆ε✂κ⁴χ¹¦²
```
Extract the `B` and `C` portions of those bytes, sandwiching the `A` bits from the first byte in between, then convert the final string back from base `2`.
```
»»Eυ⍘ι¹⁶
```
Output everything in hex for convenience (decimal would save `4` bytes).
## Encoder, 89 bytes:
```
FA¿‹ι¹⁹²⊞υι«≔÷L↨鲦⁷θ≔⟦⟧ηFθ«⊞η﹪ι⁶⁴≧÷⁶⁴ι»≔X²⁻⁶θθ⊞υ⁺﹪ιθ⁻²⁵⁶⊗θF⮌Eη⁺κ×⁶⁴﹪⁺²÷ι×θX⁴λ⁴⊞υκ»Eυ⍘ι¹⁶
```
[Try it online!](https://tio.run/##RVFPa4MwFD/rp8gxgQyqWMvYaaOXwQrS7SYeXE1NaGaqSVxh9LO791LUQALv5fcvLydZDydT62k6m4HQ9@7qHWWMqDOhH8JaqjhJnlPoFN5K6jlR7CUW2gryF0ev1qq2A5bbq1E1Aihd6yR9q61AJvA42cHugTSjy4oTiXVw7BkKRUFdcnIwjdcGuXnGEBQd6uuDeFStdKsXIh5povuiXZhfMdAUdFTnLc3RebafH1BouFl9ejaj0y3g98Z/a9FALsaWkEcxigGeBFkwZFC4cPKlfgSYZEvscAHu60DUjOqBFsIBWqM2JxkLa5nsBfzucTGozgUnaOEgPx102vAROWaaprLc3NIk2XKyuTU7PLGqqulp1P8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FA
```
Loop over the input code points.
```
¿‹ι¹⁹²⊞υι«
```
If this is a single byte code point then just push the byte, otherwise:
```
≔÷L↨鲦⁷θ
```
Get the number of additional bytes.
```
≔⟦⟧ηFθ«⊞η﹪ι⁶⁴≧÷⁶⁴ι»
```
Extract the bottom six bits of those bytes.
```
≔X²⁻⁶θθ⊞υ⁺﹪ιθ⁻²⁵⁶⊗θ
```
Push the first byte.
```
F⮌Eη⁺κ×⁶⁴﹪⁺²÷ι×θX⁴λ⁴⊞υκ
```
For each additional byte, extract its top two bits and push it.
```
»Eυ⍘ι¹⁶
```
Output everything in hex for convenience (decimal would save `4` bytes).
] |
[Question]
[
In graph theory a tree is just any graph with no cycles. But in computer science we often use *rooted* trees. Rooted trees are like trees except they have one specific node as the "root", and all computation is done from the root.
The *depth* of a rooted tree is the smallest number, \$n\$, such that any node of the tree can be reached from the root in \$n\$ steps or less. If the root node is selected poorly and the depth is high this may mean that to get to certain nodes from the roots takes many steps.
Over time as we perform computation our rooted tree may change shapes so, we'd like to then "re-root" the tree. That is without changing the underlying tree change the root of the tree so that the resulting rooted tree has as low a depth as possible.
## Task
In this challenge you will be given as input a rooted tree with positive integers at every vertex. You should output the re-rooted tree. That is a tree which has it's root selected to minimize depth but is otherwise identical.
You may take input in any reasonable format but please state your format so your answers can be tested. You should take input and give output using the same format. The input will always have at least 1 node
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with the goal being to minimize the size of your source-code.
## Test Cases
In the test cases we represent trees as a list of nodes. Each node is a tuple containing its value and a list of children represented as their indexes in the list. The root node is at index `0`.
This way of representing trees is not unique so if you use this format you may get output that is isomorphic to the given result but not identical.
```
[(1,[1]),(9,[2]),(5,[])] -> [(9,[1,2]),(1,[]),(5,[])]
[(1,[1]),(9,[2]),(5,[3]),(7,[])] -> [(9,[1,2]),(1,[]),(5,[3]),(7,[])] or [(5,[1,3]),(9,[2]),(1,[]),(7,[])]
[(1,[1]),(8,[2,3]),(7,[]),(9,[])] -> [(8,[1,2,3]),(1,[]),(7,[]),(9,[])]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
```
GraphTree[g=UndirectedGraph@TreeGraph@#,Last@GraphCenter@g,#&]&
```
Takes input as a [Tree](https://reference.wolfram.com/language/ref/Tree.html) object, e.g., `Tree[1, {Tree[9, {Tree[5, None]}]}]`.
Tree objects are introduced in [Mathematica 12.3](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn123.html), so no TIO.
Outputs for the test cases:
```
Tree[1, {Tree[9, {Tree[5, None]}]}] -> Tree[9, {Tree[1, None], Tree[5, None]}]
Tree[1, {Tree[9, {Tree[5, {Tree[7, None]}]}]}] -> Tree[9, {Tree[1, None], Tree[5, {Tree[7, None]}]}
Tree[1, {Tree[8, {Tree[7, None], Tree[9, None]}]}] -> Tree[8, {Tree[1, None], Tree[7, None], Tree[9, None]}]
```
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
-3 bytes thanks to @att.
```
-(-#//.-a_[b___,c_@d___,e___]/;Depth@b?e<Depth@!d:>-b~a~e~c~d)&
```
[Try it online!](https://tio.run/##JYjLCsIwEEV/ZSRQFBKDC9FWrVn4AboeQshjSrOoiMSVmF@Pxm7uOedONo002RS9LQOcilgKJuVaWIPOGMO9UaGSfqPl4UKPNCp3puNsi9D1wmWbKfscVk25vSIldX3Ge0IGoocBmdbQgFTw3mCLW9Rac5h1V@Nf@@oc2np8yhc "Wolfram Language (Mathematica) – Try It Online")
Takes input as a Mathematica expression, e.g., `1[9[5[]]]`.
Outputs for the test cases:
```
1[9[5[]]] -> 9[1[], 5[]]
1[9[5[7[]]]] -> 9[1[], 5[7[]]]
1[8[7[], 9[]]] -> 8[1[], 7[], 9[]]
```
Or 59 bytes if we can take input as `-1[9[5[]]]` (I'm not sure if prepending a minus sign is a reasonable format. The output also has this minus sign):
```
#//.-a_[b___,c_@d___,e___]/;Depth@b?e<Depth@!d:>-b~a~e~c~d&
```
[Try it online!](https://tio.run/##LYjLCsIwEEV/ZaTQVWJwIVqtNQs/QNfDEPKY0iwqInEl5tejoW7uOefONk082xS9LSOcSqPUWlqDzhgjvNGhkn9D6njhR5q0O3O/2CocBumyzZx9Dm25vSInfX3Ge8IG5AAjNkTQgtLwlhvscItEJODvu1pL7msI6OrzKV8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python3, 527 bytes:
```
from itertools import*
p=lambda x,i=0:[(x[i][0],x[j][0])for j in x[i][1]]+p(x,i+1)if i<len(x)else[]
d=lambda x,i=0:1+(max(d(x,l)for l in x[i][1])if x[i][1]else 0)
def f(n,p,c,u=[]):
if not p:yield c
else:
if(x:=(i:=n.index)(p[0][0]))<(y:=i(p[0][1]))and y not in u:yield from f(n,p[1:],c[:x]+[(c[x][0],c[x][1]+[y])]+c[x+1:],u+[y])
elif x not in u:yield from f(n,p[1:],c[:y]+[(c[y][0],c[y][1]+[x])]+c[y+1:],u+[x])
e=lambda x:min([j for k in permutations([i[0]for i in x],len(x))for j in f(k,p(x),[(i,[])for i in k])],key=d)
```
[Try it online!](https://tio.run/##hZHBboMwDIbvPEWOzoimsmpaF5UniXJgJGguECIKUvL0zAnduh22nYzj35/Nbx@X98kdT37etm6eRoaLnZdpGq4MRz/Ny0Ph66EZ30zDgsD6IBUEhVodtAjqkiLvppldGDqWC5XWpQfSlhXHjuF5sA4Ct8PVKl2Yn7CqhLEJYEg/ZM7wjZPab5@pmx14YWzHOnDCi1astdJcFoxUblqYlxHtYFhbsKSmAlUgyBpQ1u4RnbGBg6eF0878DFHWuOc0ijfOsJhBtMB6Y2VH8jxVSS1aJYMuFbQqZANyrOglaq5LysqkWnNO4@2QfuB/ZtyZ8caMOzPszPjJpLywX@7JER2oC0ue9Qnv7TyuS7Pg5K6gkFCphNlOLfYb3C/VQS/oSFwoQKH2E2ZtT1NFb2Nt@OZndAtYUFCJ5JGAV6GeUnxOPWRa8afkmOLL79ITScVdlHuzdvsA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~60~~ 59 bytes
```
≔EθEθ∨⁼κμ∨№η⟦κμ⟧№η⟦μκ⟧ζ≔EζιεW¬⊙ε⌊κUMεEκ⊙ζ∧§κπ§ξν⭆¹⟦θη⌕Eε⌊λ¹
```
[Try it online!](https://tio.run/##TY/NTsMwEITvfYo9bqRFauEAKKeoAolDCxLHyAeriRorttPmB0pe3sxGRdSXXX/e2RkfGtsfOutTKobBHSPv7InPQtfy3vPLebJ@4FYoZAvYdlMcuREqlRnAfxKEWpPpEZqzfHWzdBZyoDXod@N8TbzvRi7iD9ewc9GFKXCrUjXfdiHYWC1vEMNJJ2ctFRfjW6zqi9ITVv5dL0Jx8c5XH71Dos8R5aj6DbLhO4j46rBA0Y2r17ibDMHzlMoSw09Cj0LPBrJyjTdtgO@v9cGgWZt09@V/AQ "Charcoal – Try It Online") Link is to verbose version of code. I/O is a list of node values, an adjacency list and the root node. Explanation:
```
≔EθEθ∨⁼κμ∨№η⟦κμ⟧№η⟦μκ⟧ζ
```
Calculate the adjacency matrix.
```
≔Eζιε
```
Make a shallow clone we can safely mutate.
```
W¬⊙ε⌈κ
```
Until at one node can reach all the other nodes...
```
UMεEκ⊙ζ∧§κπ§ξν
```
... calculate the adjacency matrix for the next depth.
```
⭆¹⟦θη⌕Eε⌊λ¹
```
Output the original tree but with the new root node which the first node that can reach all the other nodes at the current depth.
[Answer]
# JavaScript + DOM, 154 bytes
```
n=>R(D([R(D([n]))]).slice(P.length/2))
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c
```
Input a root `HTMLElement`. Output new root after re-root.
```
f=
n=>R(D([R(D([n]))]).slice(P.length/2))
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c
tree2Dom = ([name, children], parent = document.createElement('div')) => {
parent.id = name;
children.forEach(node => parent.append(tree2Dom(node)));
return parent;
};
dom2Tree = node => [node.id, [...node.children].map(child => dom2Tree(child))];
testcases = [
['1', [['9', [['5', []]]]]],
['1', [['9', [['5', [['7', []]]]]]]],
['1', [['8', [['7', []], ['9', []]]]]],
];
testcases.forEach(t => {
console.log(JSON.stringify(dom2Tree(f(tree2Dom(t)))));
});
```
With comment
```
// Find out the deepest element in root, output that element and all its parents
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
// Re-root the tree to c, input c and its parents
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c
// Find out the new root and re-root
n=>R(D([R(D([n]))]).slice(P.length/2))
```
] |
[Question]
[
## Background
**Stick Bomber** is a two-player game I just made up. Initially, some sticks are placed in one or more groups, and the sticks in each group are laid out in a straight line. So a configuration with three groups of 3, 5, and 8 sticks each may look like the following. For conciseness, we can call it a `(3,5,8)` configuration.
```
||| ||||| ||||||||
```
Let's call the two players Alice (the one who plays first) and Bob (second). At each turn, the player selects one stick anywhere on the board, and removes that stick along with the ones directly adjacent to it (left or right within the group).
For example, if Alice chooses the 3rd stick in the 5-stick group, the board becomes `(3,1,1,8)` (sticks removed in the middle split the group into two):
```
||| |xXx| ||||||||
```
Then, if Bob chooses the first stick in the 8-stick group, the board becomes `(3,1,1,6)`:
```
||| | | Xx||||||
```
Then if Alice chooses the 2nd stick in the 3-stick group, that group is entirely removed and the state becomes `(1,1,6)`:
```
xXx | | ||||||
```
The one who eliminates all the sticks from the board wins the game.
For single-pile initial states, Alice can win in 1 turn for `(1)` through `(3)`, and `(5)` in three turns by removing the middle. However, Alice cannot win for `(4)` because any move will result in a `(1)` or `(2)`, where Bob can win in 1 turn.
## Challenge
Given an initial configuration of Stick Bomber, determine whether Alice can win the game. Assume that both Alice and Bob play perfectly, i.e. each player always plays a winning move whenever possible.
The input is guaranteed to be a non-empty sequence of positive integers, but it is not guaranteed to be sorted. 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
**Single-group configurations**
For `n < 70`, Alice wins for `(n)` unless `n` is one of the following. This result was generated using [this Python code](https://tio.run/##dVPBjtowEL3zFSNxwC6BLdBVpahBor/Q3hAHQ5zg1rEt2yxBlG@nMza7SJSe4pl58/w88@JOcW/N4nodQis6WUKr3qSBYDsJrbcHF8A2YH0tvawhRLX7HQrwsrNvEqyRIEwN8WhB1L/ETppIyQBMNeC8DJjgU/jhtIogMiEoE21qQUzcy0wmNKiApZTpVF1rOR0M4SdGTouT9HDc29u9AYTWCZj1wFGZkND@gC/oiUlQ0ijTws6aRrXQWA@r6aCWDT5Os76ADsmqM5sVvKTGAtj8flzcjhdeDoCU9iSOWkpUEQ8@B@t@g@UhOBuC2mqUnvRtT7Aq36c0/5jX4n5KcwtpLjSrKHwrIywreOVImFkqCDIyikm8IgFemFYyLQ3reVIG4BReW0G/LtUGxvhV41m5SaUbKxVVzrQYaNFtawGnEuLBacmC9VHWjHjGJ84T7i7pWwWL8iboTwVngl0eMMsHTMtYrkxwovwJ@stz9OI5@vU/6IkqFOePw5kV74AZf3mZJ8Jhcosw4YhGQnfQZumOFeyEIYIdVkHbQIYJUUSZWL9jKzbhzIyNZDqWrUObz/dmV5C4tLbsCMRjF8Y3o2Bw1YH2sN4M/lH79XNaZFo3sjNVpB04j/8Ja0ZndYHJEs7hMuLZiaQllICMU@GcNDVTfJDhnzBZBOmqUTHi178). This sequence and its inversion (the list of `n`'s where Alice wins) are not yet part of the OEIS.
```
4, 8, 14, 20, 24, 28, 34, 38, 42, 54, 58, 62
```
**Multi-group truthy**
```
[2, 9] [3, 5] [3, 7] [3, 9] [7, 8]
[1, 2, 7] [1, 8, 9] [3, 8, 9] [6, 7, 9] [7, 8, 9]
[1, 3, 6, 6] [1, 4, 4, 9] [1, 5, 6, 7] [2, 5, 6, 7] [3, 4, 8, 9]
```
**Multi-group falsy**
```
[1, 6] [1, 7] [4, 4] [5, 5] [5, 9]
[1, 7, 8] [2, 3, 9] [3, 3, 4] [4, 5, 9] [8, 9, 9]
[1, 2, 4, 4] [1, 4, 4, 7] [2, 2, 5, 9] [2, 6, 6, 7] [3, 4, 7, 9]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~110~~ ~~101~~ ~~99~~ 90 bytes
*Thanks to @tsh for -9 bytes!*
```
g=s=>s.some((a,i)=>!a&&!g(t=[...s],t.splice(i-1,3,1)))
i=>g(i.flatMap(n=>[1,...Array(n)]))
```
[Try it online!](https://tio.run/##VVHtaoQwEPx/T7H358heczn89igR@gB9ApESPJUUz4iRQil9dhtj1B5IdnecnRnYT/EldDnIfrx06l5NNZ8kzxoiWd2K8V30pONZ7lHG2NswiG/SYYF4aLjmmWZaPSpCBJXIs6M4nY4NGXluuLqgI9N9K8uKyItHA@oh4lSrAUipOj3CWJlH1ZAfADZx30dWy7YlyB7GmnxQkAg8g1zCC3gFUsM2aSAuqK3JXEMK4VwjCpGrt2JlJhTSGfQpBBaHPLBt6FYXNlzPeWo6O5yvbtksreLe0jpL3/7bV80Q2y9xBqF13rT83TpydWVafEm5uybOMt331jZelWffZMW3yMGS5CnyzU3RHtH/PxmhJfKmVSD8wHwo1VasVeas5lz4@gTVC2jQ3@kP "JavaScript (Node.js) – Try It Online") (with test cases)
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
f=lambda a:0in[f(a[:i]+[v-1,x-v-2]+a[i+1:])for i,x in enumerate(a)for v in range(x)]
```
[Try it online!](https://tio.run/##JYxBboMwEEX3nGJ22MJEgYamRcpJXC@mimlHMoNlu4icntqw@vrvvxn/Sr8L9/s@PRzO308EHK/EehKoRzKNXttObe3a9qZBTU03GjktAUhtQAyW/2YbMFmBB14LDMg/VmzS7DT7JSSIr1iV1RHbIuR@ielJPFZwPGNf8Ixe2BWdOsRsBPKiNvqLa3mJ3lHKDXQtZb4DH4gTTMJRTCJ/kFJVJ9x1r@Azm28KhjPuZxR4V/BhKt0peM@tO7ebgluO4TwYivkP "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
```
ḟⱮ’r‘Ɗ߀Ạ¬
Rj0TÇ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//4bif4rGu4oCZcuKAmMaKw5/igqzhuqDCrApSajBUw4f///9bMSwyLDdd "Jelly – Try It Online")
Slow as hell.
### Explanation
```
Rj0TÇ Main link.
[1, 3, 5]
R For each n in the array, create an array of n sticks.
[[1], [1, 2, 3], [1, 2, 3, 4, 5]]
j0 Join by 0 (non-sticks).
[1, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5]
T Indices of truthy values (sticks).
[1, 3, 4, 5, 7, 8, 9, 10, 11]
Ç Call the helper link.
ḟⱮ’r‘Ɗ߀Ạ¬ Helper link.
Ɱ € For each stick n in the array:
’ n-1
‘ n+1
r Inclusive range [n-1,n,n+1]
ḟ Remove those three sticks if present
ß Call this link recursively on the remainder
Ạ See if there is nothing or only 1's in the list
(i.e. if the opponent won before this turn, or can
force a victory whatever we do)
¬ Invert to see if we can force a victory from here
```
[Answer]
# JavaScript, 72 bytes
```
f=a=>a.some(g=(v,i,a)=>v-->0&&!f(b=[...a,v-1,a[i]-v-2],b[i]=0)+g(v,i,a))
```
[Try it online!](https://tio.run/##RY/LbsMgEEX3/orpJgJ1QMaPOJGFd/0K5AVxbcdVGqKAvKn67a6ZonZz53HPXMGHXa0fnssjiLt7H7dt0lZ3Vnr3ObJZsxUXtFx3qxBdfji8TOyijZTS4ioUWrP0YhVFj5e90zl/ndMF38Low2D96EGDyYzqEUwRpYxSRzlGaaKco6iclEhFqCJWEVwgEFUi1Kk2qdK@QTgRjVAka29P5GamivOvXyXrmCqhFQLt65Rep9Top@A9tfx/Q0kHWd9mfx@Vk3u@2eHKAugOvmBwd@9uo7y5mQWcWOC8hW/ebj8 "JavaScript (Node.js) – Try It Online")
A port of current [Python answer](https://codegolf.stackexchange.com/a/231888/44718) by [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
⊞υ⮌⌕A⪫XχAω0FυFι⊞υ⁻ι…·⊖κ⊕κ≔⟦⟧ζW⁻υEζ§κ⁰⊞ζ⟦⌊ι⊙⌊ι№ζ⟦⁻⌊ι…·⊖κ⊕κ⁰⟧⟧⊟⊟ζ
```
[Try it online!](https://tio.run/##lY8xa8MwEIX3/ooj0wlUcLp06GRaAikUTFajwdjX@Ih8MpJlt/7zruwQ8NrhEI/37runuq187Sq7LEUMLUYNFxrJB8ITS5Nbi5@OBQs3kcdjpuEsfRxQKQ1TmkN2UEq9PX07DxgVbC8reMC@WGJAXtdqGwOPdKnkSvhBtaeOZKAGb2qzd3pD5iHwVbA0GuYkp5YtAd6BK7nqcdaQD2dp6AdvGrJ17345GWVKche71Cal5Bf3@t1FGR6pxNt7/2ya7hqlTGpYeE7QwvXbzOsnlqUsjxpeNLwaszyP9g8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a winning position, nothing for a losing position. Explanation:
```
⊞υ⮌⌕A⪫XχAω0
```
Start enumerating all positions reachable from the starting position, which is calculated by taking `10` to the power of the input groups, concatenating the result, and taking the indices of the `0`s from highest to lowest (i.e. reverse of the usual order).
```
FυFι⊞υ⁻ι…·⊖κ⊕κ
```
For each position and stick, calculate the result of bombing that stick and add the result to the list of reachable positions.
```
≔⟦⟧ζW⁻υEζ§κ⁰
```
Enumerate the list of reachable positions in ascending order, so that all positions reachable from a given position have been enumerated before that position. Additionally, the enumeration deduplicates the positions.
```
⊞ζ⟦⌊ι⊙⌊ι№ζ⟦⁻⌊ι…·⊖κ⊕κ⁰⟧⟧
```
For each position, check whether any play results in a losing position. Push that position plus the win flag to the enumeration.
```
⊟⊟ζ
```
Output the win flag for the original position.
] |
[Question]
[
## Introduction
Let's draw some regular hexagons formed by hexagonal tiles, marking the vertices of the tiles with dots. Then we will count the number of dots.
```
size 1: 6 dots
. .
. .
. .
size 2: 24 dots
. .
. . . .
. . . .
. . . .
. . . .
. . . .
. .
size 3: 54 dots
. .
. . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . .
. .
```
Now, divide the hexagon into six identical sections, and keep the tiles that are needed to cover some of the sections. We still count the dots (vertices of the tiles) on the result.
```
size 3, one section: 22 dots
. .
. . . .
. . . . . .
. . . . . .
. . @ @ . .
. . @ @ @ .
. . @ @ @ @
. . @ @ @ @
. . @ @ @ @
. @ @ @
@ @
size 3, two sections: 30 dots (38 and 46 dots for 3 and 4 sections respectively)
. .
. . . .
. . . . # #
. . . # # #
. . @ @ # #
. . @ @ @ #
. . @ @ @ @
. . @ @ @ @
. . @ @ @ @
. @ @ @
@ @
size 3, five sections: 53 dots
$ $
* $ $ $
* * $ $ # #
* * $ # # #
* * @ @ # #
+ * @ @ @ #
+ + @ @ @ @
+ + @ @ @ @
+ + @ @ @ @
. @ @ @
@ @
```
Let's define \$H(n,k)\$ as the number of dots in the diagram of size \$n\$ with \$k\$ sections. It is guaranteed that \$1 \le n\$ and \$1 \le k \le 6\$.
## Challenge
Given the values of \$n\$ and \$k\$, calculate \$H(n,k)\$.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
The following is the table of values for small \$n\$:
```
| k=1 k=2 k=3 k=4 k=5 k=6
-----+------------------------
n=1 | 6 6 6 6 6 6
n=2 | 13 16 19 22 24 24
n=3 | 22 30 38 46 53 54
n=4 | 33 48 63 78 92 96
n=5 | 46 70 94 118 141 150
n=6 | 61 96 131 166 200 216
n=7 | 78 126 174 222 269 294
n=8 | 97 160 223 286 348 384
n=9 | 118 198 278 358 437 486
n=10 | 141 240 339 438 536 600
n=11 | 166 286 406 526 645 726
n=12 | 193 336 479 622 764 864
```
\$H(n,1)\$ is equal to [A028872(n+2)](https://oeis.org/A028872). \$H(n,2)\$ is equal to [A054000(n+1)](https://oeis.org/A054000). \$H(n,6)\$ is equal to [A033581(n)](https://oeis.org/A033581). OEIS doesn't have the other three columns. Each column has its own formula, except for \$H(1,5)\$ :)
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda n,k:k*n*n+(4*n-k+2-k/5%n)*(k<6)
```
[Try it online!](https://tio.run/##dY7LCsIwFET3/YrZlOTmofShQtEvUReVWq3R21K6EfrvMRVFBN3MYobDme4@nFtOfb3Z@Wt5O1Ql2LjCKVasZa7YOp1aN1/ETEq69ZJ81zc8SAFghICGELNL27DcijirQhPDoW77kA2jL/l0lInBivZE0Yu11uonagUU0pyiCeAvIMmoiIC37SNJq8nBBmIU5oe9lmFz9OdDeOEf "Python 2 – Try It Online")
Not sure about its correctness. But it at least passed all testcases.
* -2 bytes by dingledooper
* -5 bytes by xnor
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 75 bytes
```
≔⁻²⪪024420¹ε≔⁻²⪪343101¹δNθFNFθ«J×κ§ε⊖ι×κ§δ⊖ιF⊕κ«GHV→^←².M§ε⊕ι§δ⊕ι»»≔LKAζ⎚Iζ
```
[Try it online!](https://tio.run/##dVDNT4MwFD/DX9Fwek2q4cvLdiLz4MxmiC4elyC8QUNpGS1TZ/a3Y1lcJC4emva99/vqy6usy1UmhiHRmpcS1lz2GkJGXlrBDXh@GMeh7zESUMoI0rn7DzCKo8APLsDCApey7c1T37xhB3tb71RHYNqklJx7e0q@XOexb9qNgg1vUEPNSGKWssAPQEbuMe@wQWmwAE5H/StUcY2yls6P5@@gpmczJ1Xis1TyQQmh3mH2ysjsmZeVsffWnhXu7NP@zrv1Rh1nrQ4Ik0hTTT4mmgT5Mxv5J/d0WdwKZWkqSBHrRAgYuUcLWQjM7ErmbtpxaWCRaQNHyx2GiNwNNwfxDQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as size and sections. Explanation: Far too long because it doesn't try to use a formula, but guarantees 100% correct answers.
```
≔⁻²⪪024420¹ε≔⁻²⪪343101¹δ
```
Create displacement vectors for each of the six hexagonal directions.
```
Nθ
```
Input the size.
```
FN
```
Loop over each section.
```
Fθ«
```
Loop over each size.
```
J×κ§ε⊖ι×κ§δ⊖ι
```
Start each row of hexagons one step further away from the middle.
```
F⊕κ«
```
Loop over each row.
```
GHV→^←².
```
Draw a hexagon. (This hexagon is slightly horizontally compressed compared to the one in the question, as it made it easier to draw a six-dotted hexagon.)
```
M§ε⊕ι§δ⊕ι
```
Move to the next hexagon in the row.
```
»»≔LKAζ
```
Count the number of dots.
```
⎚Iζ
```
Clear the canvas and output the result.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 38 36 bytes
```
n=>k=>n*n*k+(k<6&&n*4+2-k-(n>1&k>4))
```
-2 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
[Try it online!](https://tio.run/##NY5BasMwEEX3OsVggpGsyGBHTReOdYlsu4hI5JDKjIQsunF8dmfcNgOPv/nvM9/2x07X9IhZYbi5dXQZBuhX7I3vDVZYecn96ViWWGnZKq84mqb0RgvxW56ghwvQPYmGaIkDoYkP4sgUndzNhSrq5KKzmbdaLJeObX4knzYMTHUO55weeOeijvZ2zjZlrvdQQCE6NoTEtz5Sv@koTtAcKKUUMDOgDUmPfOFujhzF8qR5gLfk/yRP0ifF2/m3Ih9I4V6IzVnYwq4BpzC6egx3PolufQE "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Port of [*@tsh*'s Python answer](https://codegolf.stackexchange.com/a/231632/52210), so make sure to upvote him!
The inputs are in the order \$n,k\$.
```
4*²D5÷¹%ÆÌ²6‹*¹n²*+
```
[Try it online](https://tio.run/##ASsA1P9vc2FiaWX//zQqwrJENcO3wrklw4bDjMKyNuKAuSrCuW7Csior//8xMAoz) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m6hdmaOTqF6mUZ3t4v042kFB41DZJQcne77@JVqSL6eHtfqqH2w73RJo9atip5ZcXqaX9X@c/AA).
Or alternatively:
```
n*²6‹iU5÷¹%-¹4*αX2O
```
[Try it online](https://tio.run/##ASgA1/9vc2FiaWX//24qwrI24oC5aVU1w7fCuSUtwrk0Ks6xWDJP//8xMAoz) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m6hdmaOTqF6mUZ3t4v042kFB41DZJQck@8vAEv/95WpFmjxp2ZoaaHt7up6rrZ6J1bmOEkf//Wp3/AA).
**Explanation:**
```
4* # Multiply the first (implicit) input `n` by 4
²D # Push the second input `k` twice
5÷ # Integer-divide the second one by 5
¹% # And then modulo it by the first input `n`
Æ # Reduce all three values on the stack by subtracting
Ì # Increase it by 2
²6‹ # Check if the second input `k` is smaller than 6
* # Multiply this to the earlier value
¹n # Push the first input `n` squared
²* # Multiply it to the second input
+ # And add the two together
# (after which the result is output implicitly)
n # Square the first (implicit) input `n`
* # Multiply it to the second (implicit) input `k`
²6‹i # If the second input `k` is smaller than 6:
U # Pop the earlier value and save it in variable `X`
5÷ # Integer-divide the second (implicit) input `k` by 5
¹% # And then modulo it by the first input `n`
- # Subtract it from the second (implicit) input `k`
¹4* # Push the first input `n`, and multiply it by 4
α # Get the absolute difference between the two values
X # Push `X` back to the stack
2 # Push 2
O # And sum the three values on the stack together
# (after which the result is output implicitly)
```
] |
[Question]
[
Deserializing binary trees depth-first is pretty easy, but doing it breadth-first is (hopefully) harder. Your mission, should you choose to accept it, is to do the latter.
The input will be a 1-D list of positive integers representing node values and some other consistent value representing the absence of a child (I'll use `#` here). The first element of that list is the root of your tree, the next is the root's left child, then the root's right child, then the left child's left child, then the root's left child's right child, and so on. If a node doesn't have a left or right child, there will be a `#` instead of a positive number to signify that.
You probably know how to do that already, but here's an example anyways:
```
Input: [1, 5, 3, #, 4, 10, 2]
First element is root
Tree List: [5, 3, #, 4, 10, 2]
1
Set the root's left child to the next element
Tree List: [3, #, 4, 10, 2]
1
/
5
Set the root's right child to the next element
Tree List: [#, 4, 10, 2]
1
/ \
5 3
That level's filled up, move on to 5's left child.
Since it's '#', there's no left child, so leave that empty.
Tree List: [4, 10, 2]
1
/ \
5 3
#
Set 5's right child to 4
Tree List: [10, 2]
1
/ \
5 3
# \
4
Move on to 3's left child
Tree List: [2]
1
/ \
5 3
# \ /
4 10
Move to 3's right child
Tree List: []
1
/ \
5 3
# \ / \
4 10 2
List is empty, so we're done.
```
## Input
The input will be a 1-D list or multiple values read from STDIN. It won't be empty, and the first element will always be a positive integer. I used '#' here, but you can use `null`, 0, or any consistent value that isn't a positive integer (please indicate what you use in your answer). The input may contain duplicate values and the tree it represents isn't necessarily sorted or in any sort of order.
## Output
The output can be printed to STDOUT in the shape of a tree (you can make it look however you want as long as it's clear which nodes are connected to which and you don't just print the input back out), or returned from a function as a tree-like structure (the latter is preferred).
You can have each level on a separate line (or separated by some other character(s)), and each node also separated by some character(s) (like in Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/211793/95792)) OR you could have each child separated by some character, so long as it's clear which node is which node's child (like in Neil's [Charcoal answer](https://codegolf.stackexchange.com/a/211801/95792)).
If your language doesn't have a "tree" data type or you can't make a `Tree` class (or you just don't want to), you could also use a list to represent the tree. Just make sure that it's in an unambiguous format. For example, the tree above could be written as this:
```
[Value, Left Child, Right Child]
[1,
[5,
#, //No left child, so #
[4, #, #] //or just [4] since both children are absent
],
[3,
[10, #, #],
[2, #, #]
]
]
```
## Test cases:
```
Input -> Output
Tree
```
```
[1] -> [1, #, #] //or [1], whatever you wish
Tree: 1 //or just 1
/ \
# #
([1, #, #] and [1, #] yield the same result as above)
[100, 4, #, 5, #, #] -> [100,[4,[5],#],#]
Tree: 100
/ \
4 #
/ \
5 #
/
#
[10, 5, 4, 2, #, 8, 1, 2, 2, 4] -> [10,[5,[2,[2],[2]],#],[4,[8,[4],#],[1]]]
Tree: 10
/ \
5 4
/ \ / \
2 # 8 1
/ \ /
2 2 4
[100, #, 4, 5, #, #] -> [100, #, [4, [5], #]]
Tree: 100
/ \
# 4
/ \
5 #
/ \
# #
```
## Rules
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code (in bytes) wins.
100 point bounty for an answer that doesn't use any mutability whatsoever (but please don't just post something you found on StackOverflow).
[Answer]
# JavaScript (ES10), ~~81~~ 80 bytes
*Saved 1 byte thanks to @Shaggy*
Expects `-1` for a non-existing child node. Returns a string where each line contains all the nodes at this depth.
```
a=>(g=r=>a+a&&(r=r.map(x=>+x||a.shift()||-1))+`
`+g(r.flatMap(x=>[x=-!~x,x])))``
```
[Try it online!](https://tio.run/##hctNCoMwEAXgvadIN5KQH0yx0E28QU8ghQzWWIsaiVKyCL16muquUAoDw7z3zQOesDSun1c@2VsbjYqgKtwppyqgkOfYKSdGmLFXFfUhgFjuvVkxCYFLQqjONO2wE2aA9bKz2it@eHnmr4QQrWNjp8UOrRhshw2uZYqz76woGCoZ4pKh0774T/dpy39u65M67urMkNyONGV6iG8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
≔⟦S⟧θ⊞υθ≔⁰ηWS«F¬⁼#ι«≔⟦ι⟧ι⊞υι»⊞§υ⊘ηι≦⊕η»θ
```
[Try it online!](https://tio.run/##VY4/C8IwEMVn71OEdrlAhVYUBCcHwQ5KwVEcQhubQEzbNK2C@NljNHVwuvu9@/NeKZgpG6ac2/a9rDWec90O9mSN1DXSS0I6uoFi6AUOoZ/20oQIT3chFSf4d0TJE2bXxhA8NhZ33cBUj1EcJUTSMJz9zOTlI2688rP40gsCb22uK/746HumRl6hoHTaObB2@pLr0vAb15ZXIdQLCp/Eoo/rXJbCCpawgBjWkPm68OTmo3oD "Charcoal – Try It Online") Link is to verbose version of code. Takes input on separate lines with newline termination and empty nodes marked with `#` and output uses Charcoal's default output for a nested array structure which is basically preorder traversal with blank lines to show movement back up the tree. Explanation:
```
≔⟦S⟧θ
```
Create a node for the root.
```
⊞υθ
```
Add the node to the list of all nodes.
```
≔⁰η
```
Start counting the inputs.
```
WS«
```
Repeat until the blank line marking the end of the input list.
```
F¬⁼#ι«
```
If this value is not the empty node marker, then...
```
≔⟦ι⟧ι
```
... turn it into a node, and...
```
⊞υι
```
... add it to the list of all nodes.
```
»⊞§υ⊘ηι
```
Push the node or marker to the child currently being filled.
```
≦⊕η
```
Increment the input count. The child being filled is half (rounded down) of the input count.
```
»θ
```
Output the finished tree.
] |
[Question]
[
[Dart](https://www.dartlang.org/) is an object oriented programming language borrowing from both Java and Javascript. What general tips do you have for golfing in Dart? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Dart (e.g. "remove comments" is not an answer). Please post one tip per answer.
If a tip is similar to Java/JS, please link to the answer in the original language's thread as well if you can.
Taken mostly from [Joey's Tips for Powershell](https://codegolf.stackexchange.com/q/191/64722)
[Answer]
**Variable declaration**
Regular variable declaration takes 4 bytes (`var`) + 2 bytes/variable (`i,`).
You can declare variables as optional named parameters for your function and shave a few bytes.
```
f(){var i,j,k;} //Takes 15 bytes
g({i,j,k}){} //Takes 12 bytes
```
Note: This doesn't work for non-constant values, for example:
```
f({i=List}){} //Works
g({i=[]}){} //Doesn't work
f({i=0,j=0}){} //Works
g({i=0,j=i}){} //Doesn't work
```
[Answer]
**Implicit parameter passing**
In some cases where Dart expects a function to be declared, you can code the function elsewhere, and then just pass its name. Dart will take care of passing the value automatically. Let me illustrate :
```
[0,1,2,3,4,5].forEach((i) => print(i)); //Using a lambda
[0,1,2,3,4,5].forEach(print); //Using implicit parameter passing since print() expects a similar parameter
```
You can also use your own functions
```
f(List i){
i.forEach(print); //Prints each number on a new line
}
[[0,1], [1,2]].forEach(f); //Prints 0 \n 1 \n 1 \n 2\n
```
If you know a lambda might be used in multiple places, for example a `map()`, it can be useful to make it its own function and pass it that way instead of declaring it multiple times.
[Answer]
**String conversion and concatenation**
Dart doesn't allow for concatenation for types other than String and doesn't implicitly convert to String like C# does for example.
It however includes a very useful way to concatenate variables without needing to use any addition operator or explicitly casting to String (using the `.toString()` method).
```
var i=0,j=1,k=2;
var s0='$j'; //'1'
var s1='$i$j$k'; //'012'
var s2='i=$i'; //'i=0'
```
You can also perform operations directly in the `${}` section and save a few temporary variable declarations.
```
var i=0,j=1,k=2;
var s='${i+j+k}'; //'3'
```
[Answer]
**Creating range of consecutive integers**
If you want to create a list of integers from start and end values, you can use below options:
```
final int s = 0; // start value
final int e = 5; // end value
List.generate(e-s,(i)=>i+s); // 28 bytes
List.generate(e,(i)=>i); // 24 bytes, if start is guaranteed to be zero
[for(int i=s;i<e;i++)i]; // 24 bytes
[for(int i=s;i<e;]i++]; // 23 bytes
[for(int i=s;i<e;]++i]; // 23 bytes, if start is exclusive
[for(;s<e;)s++]; // 16 bytes, if start can be changed in-place
```
[Answer]
**Return inside loops**
Let's suppose in your code there is a return inside a loop. You can use the following idiom to reduce bytes:
```
// indexOf method
f(v,x,[i=0]){for(;i<v.length;i++)if(v[i]==x)return i;return-1;} // 63 bytes
f(v,x)=>([i=0]){for(;i<v.length;i++)if(v[i]==x)return i;}()??-1; // 64 bytes
f(v,x)=>(i){for(;i<v.length;i++)if(v[i]==x)return i;}(0)??-1; // 61 bytes
```
The more variables to be initialized, the more bytes can be reduced.
```
// "index of integral"
g(v,x,[s=0,i=0]){for(;i<v.length;i++){s+=v[i];if(s>=x)return i;}return-1}; // 74 bytes
g(v,x)=>(s,i){for(;i<v.length;i++){s+=v[i];if(s>=x)return i;}(0,0)??-1; // 71 bytes
```
] |
[Question]
[
# The Game
You will be playing an (almost) standard game of [Connect-4](https://en.wikipedia.org/wiki/Connect_Four). Unfortunately, it is a correspondence game and someone has placed black tape on every second row starting from the bottom, so that you cannot see any of your opponent's moves within these rows.
Any moves within already-full columns will count as passing your turn, and if a game runs for longer than `6 * 7` turns it will be adjudicated as a draw.
# Challenge Specification
Your program should be implemented as a Python 3 function. The first argument is a 'view' of the board, representing the known board state as a 2D list of rows from bottom to top where `1` is a move by the first player, `2` a move by the second player, and `0` an empty position or a hidden move by your opponent.
The second argument is a turn number indexed from `0`, and its parity tells you which player you are.
The final argument is an arbitrary state, initialized to `None` at the beginning of each game, which you can use to preserve state between turns.
You should return a 2-tuple of the column index you wish to play, and the new state to be returned to you next turn.
# Scoring
A win counts as `+1`, a draw as `0`, and a loss as `-1`. Your goal is to achieve the highest average score in a round-robin tournament. I will try to run as many matches as required to identify a clear winner.
# Rules
Any competitor should have at most one competing bot at any one time, but it is OK to update your entry if you make improvements. Please try to limit your bot to ~1 second of thinking time per turn.
# Testing
Here is the source code for the controller, together with a few non-competing example bots for reference:
```
import itertools
import random
def get_strides(board, i, j):
yield ((i, k) for k in range(j + 1, 7))
yield ((i, k) for k in range(j - 1, -1, -1))
yield ((k, j) for k in range(i + 1, 6))
yield ((k, j) for k in range(i - 1, -1, -1))
directions = [(1, 1), (-1, -1), (1, -1), (-1, 1)]
def diag(di, dj):
i1 = i
j1 = j
while True:
i1 += di
if i1 < 0 or i1 >= 6:
break
j1 += dj
if j1 < 0 or j1 >= 7:
break
yield (i1, j1)
for d in directions:
yield diag(*d)
DRAWN = 0
LOST = 1
WON = 2
UNDECIDED = 3
def get_outcome(board, i, j):
if all(board[-1]):
return DRAWN
player = board[i][j]
strides = get_strides(board, i, j)
for _ in range(4):
s0 = next(strides)
s1 = next(strides)
n = 1
for s in (s0, s1):
for i1, j1 in s:
if board[i1][j1] == player:
n += 1
if n >= 4:
return WON
else:
break
return UNDECIDED
def apply_move(board, player, move):
for i, row in enumerate(board):
if board[i][move] == 0:
board[i][move] = player
outcome = get_outcome(board, i, move)
return outcome
if all(board[-1]):
return DRAWN
return UNDECIDED
def get_view(board, player):
view = [list(row) for row in board]
for i, row in enumerate(view):
if i % 2:
continue
for j, x in enumerate(row):
if x == 3 - player:
row[j] = 0
return view
def run_game(player1, player2):
players = {1 : player1, 2 : player2}
board = [[0] * 7 for _ in range(6)]
states = {1 : None, 2 : None}
for turn in range(6 * 7):
p = (turn % 2) + 1
player = players[p]
view = get_view(board, p)
move, state = player(view, turn, states[p])
outcome = apply_move(board, p, move)
if outcome == DRAWN:
return DRAWN
elif outcome == WON:
return p
else:
states[p] = state
return DRAWN
def get_score(counts):
return (counts[WON] - counts[LOST]) / float(sum(counts))
def run_tournament(players, rounds=10000):
counts = [[0] * 3 for _ in players]
for r in range(rounds):
for i, player1 in enumerate(players):
for j, player2 in enumerate(players):
if i == j:
continue
outcome = run_game(player1, player2)
if outcome == DRAWN:
for k in i, j:
counts[k][DRAWN] += 1
else:
if outcome == 1:
w, l = i, j
else:
w, l = j, i
counts[w][WON] += 1
counts[l][LOST] += 1
ranks = sorted(range(len(players)), key = lambda i: get_score(counts[i]), reverse=True)
print("Round %d of %d\n" % (r + 1, rounds))
rows = [("Name", "Draws", "Losses", "Wins", "Score")]
for i in ranks:
name = players[i].__name__
score = get_score(counts[i])
rows.append([name + ":"] + [str(n) for n in counts[i]] + ["%6.3f" % score])
lengths = [max(len(s) for s in col) + 1 for col in zip(*rows)]
for i, row in enumerate(rows):
padding = ((n - len(s)) * ' ' for s, n in zip(row, lengths))
print(''.join(s + p for s, p in zip(row, padding)))
if i == 0:
print()
print()
def random_player(view, turn, state):
return random.randrange(0, 7), state
def constant_player(view, turn, state):
return 0, state
def better_random_player(view, turn, state):
while True:
j = random.randrange(0, 7)
if view[-1][j] == 0:
return j, state
def better_constant_player(view, turn, state):
for j in range(7):
if view[-1][j] == 0:
return j, state
players = [random_player, constant_player, better_random_player, better_constant_player]
run_tournament(players)
```
Happy KoTHing!
# Provisional Results
```
Name Draws Losses Wins Score
zsani_bot: 40 5377 94583 0.892
better_constant_player: 0 28665 71335 0.427
constant_player: 3 53961 46036 -0.079
normalBot: 38 64903 35059 -0.298
better_random_player: 192 71447 28361 -0.431
random_player: 199 75411 24390 -0.510
```
[Answer]
This bot takes all sure wins, and falls back to block the rivals, second guess them vertically and horizontally or make random moves.
```
import pprint, math, collections, copy
def zsani_bot_2(view, turn, state):
if state == None: #first own turn - always for for middle
state = (1, 2) if turn == 0 else (2, 1) #(my_symbol, your symbol)
#print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]))
return 3, state
#locate obvious points
for i in range (1, 6): #skip first row
for j in range(len(view[i])): #TODO: Optimise with zip. Go for clarity now
if view[i][j] != 0 and view[i-1][j] == 0:
view[i-1][j] = state[1]
enemy_points = math.floor(turn/2)
++enemy_points if state[0] == 2 else enemy_points
known_points = sum([i.count(state[1]) for i in view])
missing_points = enemy_points - known_points
#get sure wins in any direction
for j in range(0, 7): #every column
for i in range(4, -1, -1):
if view[i][j] !=0:
break #find highest known filled point
if (not missing_points or i+1 in {1, 3, 5}):
view1 = copy.deepcopy(view)
attempt = apply_move(view1, state[0], j)
if attempt == WON:
# print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' winner move')
return j, state
#block sure enemy wins in any direction
for j in range(0, 7):
for i in range(4, -1, -1):
if view[i][j] !=0:
break #find highest known filled point
if (not missing_points or (i+1 in {1, 3, 5})):
view1 = copy.deepcopy(view)
attempt = apply_move(view1, state[1], j)
if attempt == WON:
# print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' saving move')
return j, state
#block walls
for i in range(0, 3): #impossible to get 4 in a row when the column is full
for j in range(0, 6):
if view[i][j] != 0 and view[i][j] == view[i+1][j] and view[i+2][j] == view[i+3][j] == 0:
# print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' column move')
return j, state
#block platforms if posessing perfect information on row below and drop point
for i in range(0, 5):
for j in range(0, 3):
stats = collections.Counter([view[i][j], view[i][j+1], view[i][j+2], view[i][j+3]])
if stats[0] == 2 and (stats[state[0]] == 2 or stats[state[0]] == 2):
for k in range(0, 3):
if view[i][j+k] == 0:
break
if (i == 0 or view[i-1][j+k] != 0) and (not missing_points or i in {1, 3, 5}):
#print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' platform move')
return j+k, state
else:
for l in range (k, 3):
if view[i][j+l] == 0:
break
if (i == 0 or view[i-1][j+l] != 0) and (not missing_points or i in {1, 3, 5}):
# print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' platform move')
return j+l, state
#fallback -> random
while True:
j = random.randrange(0, 7)
if view[-1][j] == 0:
#print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' random move')
return j, state
```
Thank you for fixing run\_game!
Changelog:
* v2 adds horizontal blocking - if, in a row of 4, there are two empty spots and two spots filled by the same player, it will attempt to fill one of them to have three in a row/block the opponents row, which will hopefully be capitalized upon in the following turns.
[Answer]
normalBot plays upon the assumption that spots in the middle are more valuable than spots on the ends. Thus, it uses a normal distribution centered in the middle to determine its choices.
```
def normalBot(view, turn, state):
randomNumber = round(np.random.normal(3, 1.25))
fullColumns = []
for i in range(7):
if view[-1][i] != 0:
fullColumns.append(i)
while (randomNumber > 6) or (randomNumber < 0) or (randomNumber in fullColumns):
randomNumber = round(np.random.normal(3, 1.25))
return randomNumber, state
```
[Answer]
This is obviously non-competing, but nonetheless very useful for debugging... and surprisingly fun, if you know your bot well enough to cheat :D so I'm posting in the hopes of inspiring more submissions:
```
import math, pprint
def manual_bot(view, turn, state):
if state == None:
state = (1, 2) if turn == 0 else (2, 1) #(my_symbol, your symbol)
#locate obvious points
for row in range (1, 6):
for j in range(len(view[row])):
if view[row][j] != 0 and view[row-1][j] == 0:
view[row-1][j] = state[1]
#if you're second, the opponent has one more point than half the turns
enemy_points = math.ceil(turn/2)
known_points = sum([row.count(state[1]) for row in view])
missing_points = enemy_points - known_points
print(pprint.pformat(view) + ' Turn: ' + str(turn) + ' Player: ' + str(state[0]) + ' Missing points: ' + str(missing_points))
while True:
try:
move = int(input("What is your move?(0-6) "))
except ValueError:
continue
if move in {0, 1, 2, 3, 4, 5, 6}:
return move, state
```
The grid is upside down(the bottom row is highest). To get the winner announcements, you need to patch the game controller, adding a print statement before returning the win:
```
elif outcome == WON:
print(pprint.pformat(board) + ' Turn: ' + str(turn) +' Winner: '+ str(p))
return p
```
```
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 0 Player: 1 Missing points: 0
What is your move?(0-6) 3
[[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 2 Player: 1 Missing points: 0
What is your move?(0-6) 2
[[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 4 Player: 1 Missing points: 1
What is your move?(0-6) 4
[[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 6 Player: 1 Missing points: 2
What is your move?(0-6) 1
[[2, 1, 1, 1, 1, 2, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 6 Winner: 1
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 1 Player: 2 Missing points: 1
What is your move?(0-6) 2
[[0, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 3 Player: 2 Missing points: 2
What is your move?(0-6) 3
[[0, 0, 2, 1, 0, 0, 0],
[0, 0, 1, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 5 Player: 2 Missing points: 1
What is your move?(0-6) 4
[[0, 0, 2, 1, 2, 0, 0],
[0, 0, 1, 2, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 7 Player: 2 Missing points: 2
What is your move?(0-6) 1
[[0, 2, 2, 1, 2, 0, 0],
[0, 0, 1, 2, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] Turn: 9 Player: 2 Missing points: 1
What is your move?(0-6) 2
[[0, 2, 2, 1, 2, 0, 0],
[0, 0, 1, 2, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 11 Player: 2 Missing points: 1
What is your move?(0-6) 4
[[0, 2, 2, 1, 2, 0, 0],
[0, 0, 1, 2, 2, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 13 Player: 2 Missing points: 2
What is your move?(0-6) 4
[[0, 2, 2, 1, 2, 0, 0],
[0, 1, 1, 2, 2, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 15 Player: 2 Missing points: 1
What is your move?(0-6) 3
[[0, 2, 2, 1, 2, 0, 0],
[0, 1, 1, 2, 2, 0, 0],
[0, 0, 1, 2, 1, 0, 0],
[0, 0, 1, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 17 Player: 2 Missing points: 2
What is your move?(0-6) 5
[[0, 2, 2, 1, 2, 1, 1],
[0, 1, 1, 2, 2, 2, 1],
[0, 0, 1, 2, 1, 0, 0],
[0, 0, 1, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 19 Player: 2 Missing points: 0
What is your move?(0-6)
What is your move?(0-6) 6
[[0, 2, 2, 1, 2, 1, 1],
[0, 1, 1, 2, 2, 2, 1],
[0, 0, 1, 2, 1, 0, 2],
[0, 0, 1, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 21 Player: 2 Missing points: 1
What is your move?(0-6) 1
[[0, 2, 2, 1, 2, 1, 1],
[0, 1, 1, 2, 2, 2, 1],
[0, 2, 1, 2, 1, 0, 2],
[0, 1, 1, 0, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 23 Player: 2 Missing points: 1
What is your move?(0-6) 3
[[0, 2, 2, 1, 2, 1, 1],
[0, 1, 1, 2, 2, 2, 1],
[0, 2, 1, 2, 1, 0, 2],
[0, 1, 1, 2, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0]] Turn: 25 Player: 2 Missing points: 2
What is your move?(0-6) 6
[[0, 2, 2, 1, 2, 1, 1],
[0, 1, 1, 2, 2, 2, 1],
[0, 2, 1, 2, 1, 0, 2],
[0, 1, 1, 2, 2, 0, 2],
[0, 0, 2, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0]] Turn: 27 Player: 2 Missing points: 1
What is your move?(0-6) 5
[[1, 2, 2, 1, 2, 1, 1],
[1, 1, 1, 2, 2, 2, 1],
[0, 2, 1, 2, 1, 2, 2],
[0, 1, 1, 2, 2, 0, 2],
[0, 0, 2, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0]] Turn: 29 Player: 2 Missing points: 0
What is your move?(0-6) 5
[[1, 2, 2, 1, 2, 1, 1],
[1, 1, 1, 2, 2, 2, 1],
[0, 2, 1, 2, 1, 2, 2],
[0, 1, 1, 2, 2, 2, 2],
[0, 0, 2, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0]] Turn: 29 Winner: 2
Round 1 of 1
```
Name Draws Losses Wins Score
manual\_bot: 0 0 2 1.000
zsani\_bot\_2: 0 2 0 -1.000
] |
[Question]
[
An office (let's call it "The Office") is going to cut down on wasted time in 2019 by consolidating office birthday parties. Any two people with a birthday between Monday and Friday (inclusive) of the same week will be celebrated with a *Shared Birthday Party* some time that week. People whose birthdays fall on a Saturday or Sunday get no party at all.
Some people do not like sharing a birthday party with people who do not share their actual birthday. They will be **Very Angry** to have a *Shared Birthday Party*.
We are going to simulate an office and find the first week in which someone gets **Very Angry** about their *Shared Birthday Party*.
### The Challenge
Write a program or function that outputs the first ISO week number for 2019 in which someone in a simulated office gets **Very Angry** about their *Shared Birthday Party*, subject to the following basic rules:
* input an integer *N* > 1, which is the number of workers in the office.
* the *N* birthdays themselves are distributed uniformly at random from Jan 1 to Dec 31 (ignore Feb 29).
* but the working weeks for the purposes of determining *Shared Birthday Parties* are the 2019 ISO Week Dates, which are between 2019-W01-1 (2018-12-31) and 2019-W52-7 (2019-12-29). A new ISO week starts every Monday. (I think this is all you really need to know about ISO weeks for this challenge).
* for the *N* people in the office, each has a 1/3 chance of having a **Very Angry** *Shared Birthday Party* personality type, so you'll have to simulate that too.
* but they will not be angry if the party is shared with people who have the *same* birthday.
* output the ISO week number (exact format for this is flexible as long as the week number is clear) for the first occurrence of a **Very Angry** person. If there are no angry people, you can output anything that isn't confused with an ISO week or the program can error out etc.
Some simplifying assumptions:
* as I mentioned, ignore the February 29 issue completely (an unneeded complication)
* ignore public holidays (this is an international community so our holidays will differ) and just assume the office is open on each weekday.
### Rules
This is code-golf. Shortest answer in bytes for each language wins. Default loopholes forbidden.
Code explanations welcome.
### Worked Examples
Contrived Example 1 with input *N* = 7. First and second columns are random as described in the rules (but not actually random here of course).
```
Angry Type
Person? Birthday ISO Week Comment
================================================================================
N 2018-12-31 W01 In the 2019 ISO week date year
Y 2018-12-31 W01 Same birthday, so no anger happens
N 2019-02-05 W06
Y 2019-03-15 W11 No anger happens because other W11 b-day is a Saturday
N 2019-03-16 W11
N 2019-09-08 W36 My birthday!
Y 2019-12-30 - Not in the 2019 ISO week date year
```
So no anger happens. The program or function can error out or output something not confused with an ISO week number.
Example 2 with *N* unspecified.
```
Angry Type
Person? Birthday ISO Week Comment
================================================================================
N 2019-01-19 W03
Y 2019-02-04 W06
N 2019-02-05 W06 No anger because not an angry person
... ... ... (No angry people until...)
Y 2019-03-12 W11 Very Angry Person!
N 2019-03-14 W11
... ... ... ...
```
The output would be `W11` or something equivalent.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~172~~ 202 bytes
```
def f(n):
D=set();A=[];R=randint
while n:
n-=1;w,d=R(1,52),R(1,5)
if R(0,364)>104:D|={(w,d)};A+=[w]*(R(0,2)>1)
return next((a for a in sorted(A)if[w for w,d in D].count(a)>1),0)
from random import*
```
[Try it online!](https://tio.run/##HY/BysIwEITP5in2uKtR2qr/oSVCoU/Qa@mh2AQDv5sSI1XUZ4@pp4H5doeZ6RkujosYR23AIFMpoFE3HZCqWnV91So/8Gg5CJgv9l8Dl2LFW5VXsxxVi7k8FiR/SmJlDbSYyf3fgU55diibt3phOqRPVW9UN/drXHiRKAnwOtw9A@tHQBzAOA8DWIab80GPWJM13fyzU8QCmn53dncOOCwBMiNhvLvC0jCJvU7pcR0nn@qmMceMYvwC "Python 2 – Try It Online")
oops! Missed a requirement; cost 30 bytes.
It is given by the OP that your birthday is not 29 February.
If your birthday is 30 December, it will not fall in any ISO week of 2019, so in any case you cannot be a Very Angry ISO week of 2019.
That leaves 364 other birthdays to consider you being Very Angry about. 104 of these fall on weekends when we have stipulated that you won't get Very Angry about it. So we only care about you 260/365 of the time; i.e., when `R(0,364)>104` (`randint`'s range is inclusive). Given that constraint, it is equiprobable that your weekday birthday falls in any of the 52 ISO weeks of 2019, and any weekday of that week; and, independently, that you are 1 in 3 likely to be a Very Angry person.
D is then a set of `(weeknum,weekday)` so that if a potentially Angry person shares an actual birthday, then there's no need to be Amgry unless there's yet another person having a birthday that week.
0 is returned if no Very Angry people manifest during any ISO 2019 week; otherwise, the ISO week number of the earliest meltdown is returned.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36 32~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+1 byte to fix the 30-Dec edge-case I had not noticed (as pointed out by Chas Brown has in comments below the OP)
-4 thanks to Erik the Outgolfer (inline helper and use of outer product)
```
7R2<52×þFX)Ġị$,3XỊ¤€ṁ@\PṢ€Ḋ€Fḟ0Ḣ
```
A monadic link which yields an integer in \$[0,52]\$ where \$0\$ means no Very Angry people at all during the year and other outputs are ISO week numbers.
**[Try it online!](https://tio.run/##y0rNyan8/988yMjG1Ojw9MP73I7ujtA8suDh7m4VHeOIh7u7Di151LTm4c5Gh5iAhzsXgdg7uoCk28Md8w0e7lj0//9/IzMA "Jelly – Try It Online")**
Or see [this version](https://tio.run/##y0rNyan8/988yMjG1Ojw9MP73I7ujtA8suDh7m4VHeOIh7u7Di151LTm4c5Gh5iHO1uAzICHOxeBRHZ0AUm3hzvmGzzcsej///9GZgA "Jelly – Try It Online") which prints the weeks in which each person's birthday lies (0 for weekends) grouped up, then prints a same-ordered list of lists of whether those people are of the Very Angry type, and finally prints the result.
[Answer]
# Java 8, 198 bytes
```
double r(){return Math.random();}
n->{int r=52,a[]=new int[r];for(;n-->0;)if(r()*364>104)++a[(int)(r()*r)];for(;++n<52;)r=r>51&a[n]>1&r()<1-5/Math.pow(5,a[n])&r()<1-Math.pow(2./3,a[n])?n:r;return r;}
```
Output is zero-based (0-51); a value of 52 indicates no **Very Angry** people. Try it online [here](https://tio.run/##TVDLbsIwELz3K/aE7Ia8SQ81SdUP6IljlIMhhobHJtoYEEL59tQxLq0Pa2tnPTsze3mRftsp3NeHsTuvj80GNkfZ9/AlG4T7C5jTa6lNv24NroAYv5PSZ0Izo78Dkli3J8bFAGEIHqQprG9a9fZrg1rRVm4UfOKObo7QIXBV6sCmB3JhgcFWp8OtvbRNDSejhq00NbgrK5C06/k/rge3tDWHEf3iPrFSniVzWVY5quu0r6RKbFtiAn2/iARvtsyYeU3fFkUcLbjnyXJSw22XuBv2PFxmieCUU5HFM1liVcQzM7KM/Sy0EXTtlWXzCeEOeLaTIEwfyAe@k3DBkRjGX/HiaWNaZ9MwJhJhrmUOcRRFAoyG/36ns7r1Wp2C9qyDzsSij8hsAIENFTn/4x1ctsP4Aw).
Ungolfed:
```
double r() { return Math.random(); } // shortcut for Math.random(), saves a few bytes
n -> { // lambda taking an intger argument and returning an integer
int r = 52, // this will hold the result; set to the value for "no Very Angry people" for now
a[] = new int[r]; // array counting the people whose birthday lies in each week
for(; n-- > 0; ) // for each person:
if(r() * 364 > 104) // determine whether their birthday is on a weekday that is not the 30th of December ...
++a[(int) (r() * r)]; // ... only if so, increment the counter for a random ISO week
for(; ++n < 52; ) // loop through the weeks; n is -1 before the loop
r = r > 51 // if r is still the default ...
& a[n] > 1 // ... and there is more than one person with a birthday that week ...
& r() < 1 - 5/Math.pow(5, a[n]) // ... and at least two people have a different birthday ...
&r() < 1 - Math.pow(2./3, a[n]) // ... and at least one person has the Very Angry personality type ...
? n // ... set the current week as the result ...
: r; // ... otherwise leave it the same
return r; // return the result
}
```
] |
[Question]
[
A certain well-known cable company has a somewhat clumsy 'Search for Program' feature that works through the remote. It takes muchly much button pushing; so, being an admirer of economy of motion, I thought I'd seek out a programmer's help to minimize the number of finger movements I have to make.
The Craptastic Search Feature features a layout of selectable cells, 1 row of 3 cells followed by 6 rows of 6 cells, that looks like this:
```
del spa sav
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 0 1 2 3
4 5 6 7 8 9
```
There are cells for each of the letters `A-Z`, and `spa` which is used to add a space to the search string. `del` is supposed to be used to delete a character; and `sav` is meant to be used to save the search string. We'll ignore these actual functions for this challenge; but the cells are otherwise still selectable for our purposes.
We start with an empty search string and the `A` cell selected; and we use left, right, up and down arrow buttons to change the selected cell. When the central 'OK' key is pushed, the character in the selected cell is added to the search string. For convenience, we'll use `<`,`>`,`^`,`v` and `_` for left,right,up,down and OK, respectively.
For the letters and numbers, the action of the directional buttons is straightforward. There is no 'wrap-around'; for example, if the current cell is `G`, then `<` has no effect.
So to enter the search string `BIG`, we could use the sequence
`>_>v_<<_`
(the initial `>` is required to move us from the default starting cell `A` to the cell `B`). Alternatively, we could of course instead use `>_v>_<<_`; but note there is no *shorter* sequence than 8 keys that can do the job.
Now since the top row has only three cells, the action there is slightly different and complicates things a little:
First, if the selected cell is in the top letter row `A-F`, the `^` key moves the selected cell directly above; so `A,B` go to `del`, `C,D` go to `spa` and `E,F` go to `sav`.
One the other hand, if the selected cell is 'del', the `v` key moves the selected cell to `A`, and the `>` key makes the selected cell `spa`. Similarly `v` key moves the selected cell from `spa` to `C`, and `sav` to `E`.
This means that for example, if you are currently at the `B` cell, the sequence `^v` does not return you to the `B` cell; instead it takes you to the `A` cell.
And starting at the `A` cell, the sequence `v>>^`moves us to the `C` cell; while the sequence `^>>v` moves us to the the `E` cell.
## The Challenge
Given a TV show or movie title `s`, consisting solely of characters in `A-Z`, `0-9` and `space`, your program/function should output one of the sequences of keypresses of minimal length to enter `s` as the search string from the starting state in Craptastic fashion.
Your output should be a string or a list of distinct values representing a sequence of up, down, right, left, and OK; so you are not restricted to the charset `<>^v_` (e.g., `udrl*` or a list with integer elements 0,1,2,3,4 would be acceptable alternatives, so long as you articulate what your schema is).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the usual loophole taboos apply. May the odds be ever in your favor for each language.
## Test Cases
Below are inputs and an example acceptable answer (other different sequences will be correct as well, but must be of at most the length of the examples provided).
*(I re-post the keypad here so one can more easily play along visually, if that is one's wont...)*
```
del spa sav
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 0 1 2 3
4 5 6 7 8 9
BIG >_>v_<<_
THE OFFICE >vvv_^^_>>>^_^<_vvv_>>>^^__<<<v_^_>>_
FARGO ^>>v>_^<<v_^>>v>vv_<<<<<^_>>v_
BUFFY >_>vvv_>>>^^^__^<<vvvvv_
DALLAS >>>_<<<_^>>v>v__^^<<v_vvv_
THX1138 >vvv_^^_>>>>vv_<<v__>>_<v_
ON DEMAND >>vv_<_^^^>_v>_>_<<<<vv_^^_>vv_>>^^_
NEWS RADIO >vv_>>>^^_vvv_<<<<_^^^^>_>vvv>_^^^<<v_>>>_<v_v_
ROOM 909 ^>>v>vv_<<<__<<_^^^>_>vvvvvv>_<<<^_>>>v_
```
[Answer]
# JavaScript (ES6), 196 bytes
Golfing this code below 200 bytes was basically a nightmare (but it was fun). I'm really looking forward a simpler and shorter implementation.
```
f=(s,p=(i=0,6),x=(p-=p&(p<6))%6,X=(P=(parseInt(c=s[i],36)+26)%36+6||2)%6)=>c?'^<>v_'[(d=p-P?p<6?x<(X&6)?40:X-1&&x^X&6?20:60:P<6+(x>4)|p==11&!X?0:x<X?39:x>X?21:p<P&&60:++i&&70)>>4]+f(s,p+d%16-6):''
```
[Try it online!](https://tio.run/##jZJRa9swEIDf9yu8QBwJ28VOgrYYScZd4jbQxiHtmEepREjcLiMkJg7CD/nv2cl2R6GgVE8nWf6@u9P9XapluTpsiqO326/z8/mFodItGNow3yXYrRgqPFbYqKAE4y5xM4bmcLY8lPl0d0QrVj5tnt0BwU6f4O6AOOR06sNFzPgq6gnKlew9oTUrvHkEjKiiKLMJjoZ@mHmBbVcCtlHfD4kfzilxUMWH@FQwFgT21yzyw4pm0WAUVjyL@kFY0Lltw1XH2dj2Nx9zPnx2XnTKzrobEI/gsNc7r/a7cr/Nr7b7V1RazOpcT286rtWuQ67P4Cfs6vhqm@9ej38sBve4hHwplZ32EH/5gHq8nVhpkkx/TDquEaWUkkJIzrmQgkq91bGQIKDwCXYmTxIvbtK3pA0ewbniINBIHSpdACzNVybB9c8k@f0Jge7JW@6QvDbpZUKP47u7@KFlm9DQAki1TRzYdRkX4I@3WRAMvjf0zz1A0xQQaJ8Rns6s8eQ@no013pi5RgJecAntr8ugra9uFgQGzWzy68FaxONpenGI2qFR7btqpWiehOtYl8WbsoyFLdL03hr5o7ptl8apcelBlf9ttbCdq/eDdf4H "JavaScript (Node.js) – Try It Online")
## How?
### Variables
* **s** is the input string
* **i** is a pointer in **s**, initialized to **0**
* **c** is the next target character (aka **s[ i ]**)
* **p** is the current position on the keypad according to the following mapping and initialized to **6** (the **"A"** key)
```
del spa sav 00 -- 02 -- 04 --
A B C D E F 06 07 08 09 10 11
G H I J K L 12 13 14 15 16 17
M N O P Q R -> 18 19 20 21 22 23
S T U V W X 24 25 26 27 28 29
Y Z 0 1 2 3 30 31 32 33 34 35
4 5 6 7 8 9 36 37 38 39 40 41
```
* **P** is the position of the target character **c**
* **x** is the column of the current character (**p % 6**)
* **X** is the column of the target character (**P % 6**)
### Move encoding
There are 7 possible moves. We encode each of them as a 7-bit integer. The 4 least significant bits hold the displacement value **V + 6** and the 3 most significant bits hold the symbol ID **S**.
```
move | symbol | S | V | V + 6 | S << 4 | (V + 6)
---------------------------+--------+---+----+-------+-----------------
one position to the left | < | 1 | -1 | 5 | 21
two positions to the left | < | 1 | -2 | 4 | 20
one position to the right | > | 2 | 1 | 7 | 39
two positions to the right | > | 2 | 2 | 8 | 40
upwards | ^ | 0 | -6 | 0 | 0
downwards | v | 3 | 6 | 12 | 60
don't move (press the key) | _ | 4 | 0 | 6 | 70
```
### Alignment with function keys
At the beginning of each iteration, we execute the following code to make sure that **p** is aligned with the current function key if we're located in the first row:
```
p -= p & (p < 6)
```
### Move logic
The move is chosen with a (too) long chain of ternary operators which is detailed below.
```
p - P ? // if we're not yet located over the target character:
p < 6 ? // if we're currently located in the first row:
x < (X & 6) ? // if x is less than the column of the function key holding the target character:
40 // move 2 positions to the right
: // else:
X - 1 && // if the target character is not located in the 2nd column
x ^ X & 6 ? // and x is not equal to the column of the function key holding the target character:
20 // move two positions to the left
: // else:
60 // move downwards
: // else:
P < 6 // if the target key is space (P is either greater than 5 or equal to 2)
+ (x > 4) | // or the target key is A and we're currently in the rightmost column
p == 11 & !X ? // or we're currently over F and the target key is in the leftmost column:
0 // move upwards
: // else, this is a standard move:
x < X ? // if x is less than X:
39 // move one position to the right
: // else:
x > X ? // if x is greater than X:
21 // move one position to the left
: // else:
p < P && 60 // move either upwards or downwards
: // else:
++i && 70 // don't move and advance the pointer in s
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~294~~ ~~293~~ 289 bytes
```
r='';l=[(ord(c)-59)%43-14*(c<'0')for c in input()]
for a,b in zip([6]+l,l):x,y,X,Y=a%6,a/6,b%6,b/6;A=(a<6)*(X!=1);x=[x,X/2*2][A];r+='< >'[X/2]*A+('^'*y+['<<'+'v'*Y,'> <'[x/2]][b<6]if(b,x)in[(6,5),(2,x)]or(a,X)==(11,0)else('^v'[Y>y]*abs(y-Y)+'<>'[X>x]*abs(x-X)))+'_'
print r.replace(' ','')
```
[Try it online!](https://tio.run/##JZBha4NADIa/@ytuhZI7va7VtjJXr2CndoW2Qrsx5bgNdZYJYsV2Rffn3blB4E2e5E0gVXv9OpdG9xS4HhsMBl3NABYF4/hcf@KUjOYWGc6mI32m4tSGCZDTuUYpyksZ1fcVE6H0JKZJz37yCnNTaAUtyGNDWxrSiMVDk8ZjkyZSk7G5cBiObZOoOLxjOlk0jDc0HBuqIbgjFrXGwEZL4BIJ1dEwvIPaahxsGzS4gRpRWCIbeCP7gie2KfITTmhD8pJjk84JxYasxLnGMQ0JY1jX6YRkxSWTu27Ao2Ur1Di54HYUEQ3s/tay@UfNKCREwg9Qqjovr6i@r7OqiFPpRUABSCe/pChZk6Wof5pqdbDarEGBl2cPBb6/efJk4TuHdSB19er7kVTX2W6d499UqOvTB5kFe@R6O2fvynzvvR3RwXE3vecQBDtkTSz4BQ "Python 2 – Try It Online")
[Answer]
# JavaScript, 311 bytes
```
f=n=>(parseInt(n,36)+26)%36+1||'S'
g=n=>(t=+n)?[t-(t%6!=1),t%6?t+1:t,t>30?t:t+6,t<7?' DDSSVV'[t]:t-6]:{D:'DS1',S:'DV3',V:'SV5'}[n]||[]
h=(p,q,t={[p]:''})=>([...g(p)].map((n,i)=>n in t&&t[n].length<t[p].length+1||h(n,q,t,t[n]=t[p]+'<>v^'[i])),t[q])
F=s=>[...s].map(f).map((c,i,a)=>h(a[i-1]||1,c)+'_').join``
```
```
<input id=i oninput=o.value=F(i.value)><br><output id=o>
```
Not sure how to golf this...
* `f`: convert 'A-Z0-9' to 1-36, space to "S"
* `g`: get 4 sibling of given key
* `h`: find shortest path from p to q
* `F`: the answer
] |
[Question]
[
**This is Hole-9 from [*The Autumn Tournament* of APL CodeGolf](https://apl.codegolf.co.uk/problems#9). I am the original author of the problem there, and thus allowed to re-post it here.**
---
Given a simple (rectangular, non-jagged) Boolean array (of one or more dimensions) return a list of thusly shaped arrays where the first array is identical to the input and the last is all-true. All intermediary steps must have one more truth than its neighbor to the left (but otherwise be identical). For each step, the bit that is changed must be pseudo-randomly chosen (and you may take a seed if necessary).
### Examples
`[0]` gives `[[0],[1]]`
`[[0]]` gives `[[[0]],[[1]]]`
`[[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]]` gives `[[[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]]]`
The following examples' results may of course vary due to randomness; these are just examples of valid output:
`[0,1,0,0]` gives `[[0,1,0,0],[1,1,0,0],[1,1,0,1],[1,1,1,1]]`
`[[0,1,0],[0,0,1]]` gives `[[[0,1,0],[0,0,1]],[[1,1,0],[0,0,1]],[[1,1,0],[0,1,1]],[[1,1,1],[0,1,1]],[[1,1,1],[1,1,1]]]`
`[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]` gives `[[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[1,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[1,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,0,0],[0,1,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0],[0,1,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0],[0,1,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0],[0,1,0,0,0,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[0,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,0],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,1],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,0],[1,1,1,0,0,0,0,1],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,0,0,0,1],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,0,1,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,0,0,0,1],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,0,0,0,1],[0,0,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,0],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,0,0,0,1],[0,1,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,0,0,0,1],[0,1,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,0,1,1,0],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,0,1],[0,1,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,0],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,0,1],[0,1,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,0,1],[0,1,0,1,0,0,0,0]],[[1,0,1,0,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,0,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,0,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,0,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,0,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,1,0,0],[0,0,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,0]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,0],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,1]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,0,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,1]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,0,0,0,1]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[0,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,1,0,0,1]],[[1,0,1,1,0,1,0,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,1,0,0,1]],[[1,1,1,1,0,1,0,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,0,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[0,0,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[0,1,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[1,1,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,0],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[1,1,0,0,1,1,1,1],[0,0,1,0,1,0,0,1],[1,1,0,0,1,0,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[1,1,0,0,1,1,1,1],[0,1,1,0,1,0,0,1],[1,1,0,0,1,0,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,0,1,1,0],[0,1,1,1,1,0,1,1],[1,1,0,0,1,1,1,1],[0,1,1,0,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,1,1,1,0],[0,1,1,1,1,0,1,1],[1,1,0,0,1,1,1,1],[0,1,1,0,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,1,1,1,0],[0,1,1,1,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,0,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1]],[[1,1,1,1,1,1,1,0],[0,1,1,1,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,0,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,0],[0,1,1,1,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,0],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,0,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1],[1,1,0,0,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,0,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,0,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,0,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,0,1,1,1,1],[0,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,0,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,0,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,0,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]]]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
F¬0TX$¦ÐĿ¬ṁ€
```
[Try it online!](https://tio.run/##y0rNyan8/9/t0BqDkAiVQ8sOTziy/9CahzsbHzWt@X@4/eikhztnAJmRCg93bH/UMEfBOTEnRyEnMy9bTyGgKDOvRCE1MTlDIbMktSixJDM/TwGIEhXyUstBalL1/v@Pjo420FEwiNVRgNAgBrKIIaqIIVgkFgA "Jelly – Try It Online")
### How it works
```
F¬0TX$¦ÐĿ¬ṁ€ Main link. Argument: A (array)
F Flatten A.
¬ Negate all Booleans in the result.
DĿ Repeatedly call the link to the left until the results are no longer
unique. Yield the array of all unique results.
¦ Sparse application:
TX$ Pseudo-randomly select an index of a 1.
0 Replace the element at that index with 0.
¬ Once again negate all Booleans.
ṁ€ Shape each flat array in the result like A.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 197 bytes
```
import random,copy
A=[input()]
while"0"in`A[-1]`:
A+=copy.deepcopy(A[-1]),
while~0:
j="A[-1]"
while[]<eval(j):j+="[%s]"%random.randint(0,~-len(eval(j)))
if eval(j)<1:exec"%s=1"%j;break
print A
```
[Try it online!](https://tio.run/##xY9BasMwEEXXnlOIAYNElCB1aUcL42MIQdxEJXIdWThu0mxydVdSTaAn6J/FzLz/xaDwmM@jf1tahYiLu4RxmsnU@dN44ccxPKBR2vnwNVNm4H52g0WBzh8avZXmUAFpNirldidrQxpodhgHktNPUUHRK8wUochQm729dQPtWdVvFOryarD8PbpLzfmZCv7cDtbTNcgYFO6DrNteVvbbHrG8KollX79PtvuEMMWHpFniT@ps52OkzVnS1tnHRSdJkwT6JWFeilRwyYXhscdpJX9q9f6LmB8 "Python 2 – Try It Online")
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes
```
FoldList[ReplacePart[#,#2->1]&,#,RandomSample@Position[#,0]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/J8Uns7gkOii1ICcxOTUgsagkWllH2UjXzjBWTUdZJygxLyU/NzgxtyAn1SEgvzizJDM/D6jCIDZW7X9AUWZeiYKDlkKagr6DQjWXgkK1Qa0OiALSUEa1oQ4Q1uqg0UAG6TIQIw2AHAMduEUgHlAJUASkhKv2PwA "Wolfram Language (Mathematica) – Try It Online")
### Explanation
```
Position[#,0]
```
Find all positions of `0`s in the nested array.
```
RandomSample@...
```
Shuffle the list of positions.
```
FoldList[...&,#,...]
```
Fold the function on the left over the shuffled list of positions, using the input as the starting value, and collect all steps of the fold operation in the result.
```
ReplacePart[#,#2->1]
```
Set the value at the given position to `1`.
[Answer]
# [R](https://www.r-project.org/), ~~93~~ ~~82~~ 74 bytes
```
function(a)Reduce(function(x,y){x[y]=T;x},sample(as.list(which(!a))),a,,T)
```
[Try it online!](https://tio.run/##fcy9CsIwFIbhvVdxxOUEjg6ZAurqBUg3cTimCS2krSQpJojXHv9QF3F9v4fPF9cdPfuMvYnt2ARRWVgvoNhp0LEbB2SxM82kDX5KoiwuaZ8Pm3qVrhS4PzmDHJauCxHPbadbnLEQgpioFsUie88Zt6RRkrwPMAeZJDwzjBbYObDsgqnetv5ro5@@9HGrSL2oSurHbbkB "R – Try It Online")
Takes an R `logical` `array` and returns a `list` of `logical` `array`s.
The nasty `sample(as.list(which(!a)))` is to prevent an edge case in `sample`. When `a` contains exactly one `FALSE` value at index `i`, `sample` returns a random permutation of `1:i` rather than a random sample of size `1` containing only the value `i`, so I used `as.list` to prevent `which(!a)` from being `numeric`.
The R documentation for `sample` is mildly apologetic about this behavior:
>
> If `x` has length 1, is numeric (in the sense of `is.numeric`) and `x >= 1`, sampling via sample takes place from 1:x. ***Note* that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as `sample(x)`.**
>
>
>
[Answer]
# [Perl 5](https://www.perl.org/), 78 + 1 (`-p`) = 79 bytes
```
while(@a=/0/g){$o.="$_,";for$i(0..rand@a){/0/g}substr$_,-1+pos,1,1}$_="[$o$_]"
```
[Try it online!](https://tio.run/##FYpBCsMgEAD/IntIqJr1kFMR8oG8QEQsTVshZEVTegj5erf2NMMweSnryPx5pXXppmgHHJ79AaStgCDF9UEFUodal7jdp9gf/@Gs71vdSxuUuWSq0khzQrDCAUHwgtk5bBG9bGzm/ZfynmirrOZRo0FW@Qc "Perl 5 – Try It Online")
Array? What array? It's just a long string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
F¬TṬ€$$o€$ṁ€µX$ÐĿṖṖ
```
[Try it online!](https://tio.run/##y0rNyan8/9/t0JqQhzvXPGpao6KSDyIf7mwEUoe2RqgcnnBk/8Od04Do////0dEGOkAYqwOlYwE "Jelly – Try It Online")
Probably could be shorter
# Explanation
```
F¬TṬ€$$o€$ṁ€µX$ÐĿṖṖ Main Link
ÐĿ While results are unique:
F Flatten the array
$$ 3 links will form a monad
¬ Logical NOT on each element
T Find indices of 1s (0s in the original)
€ For each 0 in the original
Ṭ Make an array of all 0s containing one 1 there
$ 2 links will form a monad
€ For each of the mask arrays
o Vectorizing logical OR it with the original (flat) array
€ For each of these subarrays
ṁ Reshape it to the original array's shape
µ Start a new monadic chain, using the list of possible next steps as the argument
$ 2 links will form a monad
X Pick a random element
ṖṖ Remove the last two elements (0 and '' which are selected by X when the list is empty)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~134~~ ~~132~~ 129 bytes
```
from random import*
a=input()
print a;l=list(`a`)
while'0'in l:l[choice([i for i,c in enumerate(l)if'0'==c])]='1';print''.join(l)
```
[Try it online!](https://tio.run/##JY5BCsMgFET3nuKTjRqkmHbX4klEiBhDfjEq1tD29FbS1XswwzD5W7cUr82lxYOCYRjaWtIOxcalA/ecSh2JVRjzURknuWCsYB9BBXxVNtuZk/eGwVNJMUK4B@22hM4zjbCmAigc9MDHY/fFVs8Cx7WXlXKGG0Un@jg3Kb08E8Yet/6CEP/xDs5bI9ya1tIYoqWYhBSy21@N6OxmzA8 "Python 2 – Try It Online")
] |
[Question]
[
Based on [How high can you count?](https://codegolf.stackexchange.com/questions/124362/how-high-can-you-count) let us give an advantage to the polyglot people.
## Challenge:
Your task is to write as many programs / functions / snippets as you can, where each one outputs / prints / returns an integer. The first program must output the integer `1`, the second one `2` and so on.
**You can not reuse any characters between the programs. So, if the first program is simply: `1`, then you may not use the character `1` again in any of the other programs.** Note: It's allowed to use the same character many times in one program.
**You can only use a programming language once.** So every number must be in a different programming language.
### Scoring:
The winner will be the submission that counts the highest. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total.
### Rules:
* You can only use a language for one integer - after that you cannot reuse the language
* **Snippets are allowed!**
* To keep it fair, all characters must be encoded using a single byte in same encoding in the languages you choose.
* The output must be in decimal. You may not output it with scientific notation or some other alternative format. Outputting floats is OK, as long as all digits *that are shown* behind the decimal point are `0`. So, `4.000` is accepted. Inaccuracies due to FPA is accepted, as long as it's not shown in the output.
* `ans =`, leading and trailing spaces and newlines etc. are allowed.
* You may disregard STDERR, as long as the correct output is returned to STDOUT
* You may choose to output the integer to STDERR, but only if STDOUT is empty.
Note: Explanations are encouraged!
[Answer]
# GS2, 3var, Alphuck, brainf\*\*\*, Numberwang, evil, ;#+, Charcoal, Retina, wsf, Jelly, Beeswax, CJam, Fourier, Fireball, M, Pushy, MATL, Brain-Flak, Convex, COW, Mouse-79, Mouse-98, Mouse-2002, Pyke, Neim, JavaScript, Braingolf, Japt, SOGL, score 31
All are encoded as hex bytes in either ASCII or the language's native encoding
```
GS2 - 1: 01 01
3var - 2: 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64
Alphuck - 3: 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65
brainf*** - 4: 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b
Numberwang - 5: 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
Evil - 6: 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
;#+ - 7: 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b
Charcoal - 8: b8
wsf - 9: 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
Jelly - 10: 85
Beeswax - 11: 50 50 50 50 50 50 50 50 50 50 50
CJam - 12: 43
Retina - 13: 0a 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 0d 0a 2e
Fourier - 14: 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e
Fireball - 15: 46
M - 16: 96
Pushy - 17: 54 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 7e
MATL - 18: 32 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
Brain-Flak - 19: 28 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 29
Convex - 20: 4b
COW - 21: 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f
Mouse-79 - 22: 57
Mouse-98 - 23: 58
Pylons - 24: 34 21
Mouse-2002 - 25: 5a
Pyke - 26: 4e 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68
Neim - 27: f9
JavaScript - 28: 30 78 31 63
Braingolf - 29: 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c
Japt - 30: c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4
SOGL - 31: 41 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49
```
More to come :)
also if i was allowed to use any language as many times as i want i would be able to get ~200
] |
[Question]
[
Alice, Bob, Carol, Dave, and Eve are going out for a nice game of golf and need your help to decide in what order they will play.
Your program will input some statements, which are defined as a condition, and then one or more optional logical boolean operators followed by another condition. (That's `[Condition]([Logical][Condition])*` in regexp notation.) A logical boolean operator is "and" or "or." You may chose either `and` or `or` to have higher precedence, as long as it is consistent.
A condition is a name, followed by the word "is," followed optionally by the word "not," followed by one of these:
* in front of
* behind
* n spaces in front of
* n spaces behind
* next to
* nth
* nth to last
An example of a valid condition is "Alice is not next to Bob".
Associativity is from left to right, except for "not," which only applies to a single statement. This means that "x or y and z or not a" means "((x or y) and z) or a," where x could be "Alice is 1st" or "Alice is behind Bob" or "Alice is not 2nd to last."
Your output must be the order in which the players line up, separated by commas, from front to back of the line.
Here's the full specification in regexp notation:
```
[Statement] = [FullCondition]([Logical][FullCondition])*
[FullCondition] = [Name] is [Condition]
[Condition] = (not)? (in front of|behind|[Number] space(s)? (in front of|behind)|next to|[Ordinal]|[Ordinal] to last)
[Logical] = and|or
[Number] = 1|2|3|4...
[Ordinal] = 1st|2nd|3rd|4th...
```
Standard methods of input and output. Input should be as a string, and output can be as a string or list.
And finally, here are some sample inputs and outputs.
```
Input:
The players are Alice, Bob, and Carol.
Alice is 2nd.
Bob is in front of Alice.
Output:
Bob, Alice, Carol
Input:
The players are Alice, Bob, and Carol.
Alice is 1 space in front of Bob. // remember to handle pluralization correctly!
Carol is 1st to last.
Output:
Alice, Bob, Carol
Input:
The players are Alice, Bob, and Carol.
Alice is in front of Bob.
Output:
Alice, Bob, Carol
Carol, Alice, Bob // multiple outputs may be required
Input:
The players are Alice, Bob, and Carol.
Alice is in front of Bob.
Bob is in front of Alice.
Output:
// nothing
Input:
The players are Alice, Bob, and Carol.
Alice is not in front of Bob and Carol is not 2nd or Bob is 1st.
Output:
Carol, Bob, Alice
Bob, Alice, Carol
Bob, Carol, Alice
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
A great many thanks to @Doorknob for posting this in the Secret Santa's Sandbox. Again, thank you.
[Answer]
## JavaScript (ES6), ~~554~~ ~~499~~ ... 463 bytes
Takes input as an array of strings and returns an array of arrays of strings. Parsing rule: `and` has higher precedence than `or`.
Below is a slightly formatted version. The compact version is included in the snippet.
```
([P,...C])=>
[...Array(m=9349)]
.map(_=>p[a=P.match(/[A-E]\w+/g).sort(_=>(k=k*2%m)&1)]?0:p[a]=a,p={},k=1)
.filter(s=>
s&&eval(
C.join`and `.match(/.+?(or |and |$)/g)
.map(s=>
(
c=s.match(/([A-E]\w+|\d|no|la|fr|be|x|p|or|an)/g),
S=n=>`s.indexOf('${c[p+n]}')`,
E=`]=='${c[0]}'`,
c[p=1]=='no'?(p++,'!(s['):'(s['
)+
(
(x=+c[p])&&p++,
{
la:'s.length-'+x+E,
fr:F=S(1)+-1+E,
be:B=S(1)+'+1'+E,
x:F+'||s['+B,
p:S(2)+(c[p+1]>'f'?-x:'+'+x)+E
}[c[p]]||--x+E
)+
(c.pop()>'o'?')||':')&&')
).join``+1
)
)
```
### How it works
**1. Initialization**
The input array is split into:
* `P` = first line, describing the players
* `C` = array containing all other lines
We first extract the names of all players from `P`:
```
P.match(/[A-E]\w+/g)
```
We compute all permutations of the names, using several iterations of `sort()`:
```
sort(_ => (k = k*2 % 9349) & 1)
```
The prime `9349` was (empirically) chosen in such a way that all permutations are guaranteed to be found, given enough iterations of the sort, for up to 5 players.
**2. Filtering**
The main part of the function consists of filtering these permutations to keep only the ones that match all conditions in `C`.
We join the different condition lines with `and` and split the resulting string on `or` and `and` to get an array of conditions.
Each condition is parsed to isolate the relevant tokens:
```
Token | RegExp part
---------------+------------
Name of player | [A-E]\w+
Digit | \d
'not' | no
'last' | la
'in front of' | fr
'behind' | be
'next to' | x
'spaces' | p
'or' | or
'and' | an
```
Each condition is translated into JS code:
```
Condition | JS code
------------------------------+-------------------------------------------------------------
'X is Nth' | s[N - 1] == 'X'
'X is Nth to last' | s[s.length - N] == 'X'
'X is in front of Y' | s[s.indexOf('Y') - 1] == 'X'
'X is behind Y' | s[s.indexOf('Y') + 1] == 'X'
'X is next to Y' | s[s.indexOf('Y') - 1] == 'X' || s[s.indexOf('Y') + 1] == 'X'
'X is N spaces in front of Y' | s[s.indexOf('Y') - N] == 'X'
'X is N spaces behind Y' | s[s.indexOf('Y') + N] == 'X'
```
Finally, all codes are joined with `||` and `&&` operators and the resulting string is `eval()`'d.
For example, below are the translations of the test cases as JS code:
```
(s[1]=='Alice')&&(s[s.indexOf('Alice')-1]=='Bob')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&(s[s.length-1]=='Carol')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&(s[s.indexOf('Alice')-1]=='Bob')&&1
!(s[s.indexOf('Bob')-1]=='Alice')&&!(s[1]=='Carol')||(s[0]=='Bob')&&1
```
### Test cases
```
let f =
([P,...C])=>[...Array(m=9349)].map(_=>p[a=P.match(/[A-E]\w+/g).sort(_=>(k=k*2%m)&1)]?0:p[a]=a,p={},k=1).filter(s=>s&&eval(C.join`and `.match(/.+?(or |and |$)/g).map(s=>(c=s.match(/([A-E]\w+|\d|no|la|fr|be|x|p|or|an)/g),S=n=>`s.indexOf('${c[p+n]}')`,E=`]=='${c[0]}'`,c[p=1]=='no'?(p++,'!(s['):'(s[')+((x=+c[p])&&p++,{la:'s.length-'+x+E,fr:F=S(1)+-1+E,be:B=S(1)+'+1'+E,x:F+'||s['+B,p:S(2)+(c[p+1]>'f'?-x:'+'+x)+E}[c[p]]||--x+E)+(c.pop()>'o'?')||':')&&')).join``+1))
console.log(JSON.stringify(f([
'The players are Alice, Bob and Carol.',
'Alice is 2nd.',
'Bob is in front of Alice.'
])));
console.log(JSON.stringify(f([
'The players are Alice, Bob, and Carol.',
'Alice is 1 space in front of Bob.',
'Carol is 1st to last.'
])));
console.log(JSON.stringify(f([
'The players are Alice, Bob, and Carol.',
'Alice is in front of Bob.'
])));
console.log(JSON.stringify(f([
'The players are Alice, Bob, and Carol.',
'Alice is in front of Bob.',
'Bob is in front of Alice.'
])));
console.log(JSON.stringify(f([
'The players are Alice, Bob, and Carol.',
'Alice is not in front of Bob and Carol is not 2nd or Bob is 1st.'
])));
```
[Answer]
# Python 3, ~~527~~ ~~524~~ 511 bytes
```
import re,itertools as I
S=re.sub
p=re.findall(r"\w+(?=[,.])",input())
l=[]
try:
while 1:
c=[["not "*("not "in c)+S(" .+o (.+)",r" in[\1+1,\1-1]",S(" .+f","+1==",S(" .+d","-1==",S(r" .+(\d+).+",r"+1==\1",S(r" .+(\d+).+st",r"==len(p)-\1",S(r" .+(\d+).+f",r"+\1==",S(r" .+(\d+) .+d",r"-\1==",c[:-1]))))))),c][len(c)<7]for c in re.split("(or|and) ",input())]
while c[1:]:c[:3]=["("+" ".join(c[:3])+")"]
l+=[c[0]]
except:print([P for P in I.permutations(p)if eval("and ".join(l),dict(zip(P,range(len(p)))))])
```
[Try it online!](https://tio.run/nexus/python3#ZVGxbhwhFOz3K55eBYFDJikirYKiJJW7k5yOpVizrI2FAbGcHUf59wt4c7IU08CbGWYej7N/zKlUKI776kpNKWwwb3A93KjixHa6HXI/rD4ucwik4PTMyFeluTAUuY/5VAmlQ1DaDLW8jAM83/vgQLYTWKU1xlQBP5B99xEsZTcEQbAERLBmUhB81JNkkk/yIA3ynV@RI5NKXeql1Yd/dekAmRZGBesOXTfJ/5mtdk6p4CLJ9PBesL7end6Z7mkFDztl9dj6ovvi1uhuaOmXz2ZNBWxrH/qwcvCVIEnlzxwXCm/jMW0W@1islqMZm98nozQSZAgoHpJvdh2jDCl2dWBKW31lzOB@WZfrmIuPlegj9MRjT7wW2ZXHU52rT3Fr7/MruKc5EGzpF9dA@eJtJb99Jkde5njnyD6Nvgw9n3/eO8hhfnGlfXxx8C146zh8T7ccutGPuaQghlcY/Ab9G1v6WlKskNYufNNdBB8b0PrsXEPkVsVf)
Outputs an array of valid permutations. Expects the names to only contain `A-Za-z0-9_` (`Alice` through `Eve` are obviously valid).
[Answer]
# PHP, way too long (~~790 744 725 697 678~~ 669 bytes)
```
foreach(file(F)as$i=>$s)if($i){$g("#(.*)( and | or |\.)#U",$s,$w,2);foreach($w as $q){preg_match("#^(\w+)(.*?)(\w+)$#",$q[1],$m);$n=$u[-3+$p=($o=strpos)($u=$m[2],p)];$d.="!"[!$o($u,no)]."(".strtr(!$o($u,x)?A.($o($u,f)?$p?"==B-$n":"<B":($o($u,b)?$p?"==B+$n":">B":"==".preg_replace("#.*(\d).*#",($k=$o($u,a))?"$z-$1":"$1",$k?$u:$m[3]))):"(A-B)**2<2",[A=>$m[1],B=>$m[3]]).")$q[2]";}$d=!$x.="&"[!$x]."($d)";}else{($g=preg_match_all)("#(\w+)[.,]#",$s,$m);$z=count($y=$m[1]);}for(;$j++<10**$z;)if(count_chars($p="$j",3)==join(range(1,$i=$z))){for($c=$x;$i--;)$c=strtr($c,["."=>"","not"=>"",$y[$p[$i]-1]=>$i+1]);for(;eval("return$c;")&++$i<$z;)echo$y[$p[$i]-1],"
,"[$i<$z-1];}
```
takes input from file `F`, no trailing newline; `and` before `or`. Run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/de7a0d4e2c576ff1252e7414dbf36bfb68753a7d).
**breakdown**
```
foreach(file(F)as$i=>$s)if($i) # loop through input lines
{
$g("#(.*)( and | or |\.)#U",$s,$w,2); # split statement to conditions
foreach($w as $q)
{
preg_match("#^(\w+)(.*?)(\w+)$#",$q[1],$m); # 1. copy names to $m[1],$m[3]
$n=$u[-3+$p=($o=strpos)($u=$m[2],p)]; # 2. remove names, 3. find N in "N spaces"
$d.="!"[!$o($u,no)]."(". # 4. negate, 6. concatenate
strtr( # 5. translate condition:
!$o($u,x)
?A.($o($u,f)?$p?"==B-$n":"<B" # (N spaces) in front of
:($o($u,b)?$p?"==B+$n":">B" # (N spaces) behind
:"==".preg_replace("#.*(\d).*#", # N-th
($k=$o($u,a))?"$z-$1":"$1" # ... (to last)
,$k?$u:$m[3])
))
:"(A-B)**2<2" # next to
,[A=>$m[1],B=>$m[3]])
.")$q[2]";
}
$d=!$x.="&"[!$x]."($d)"; # concatenate statements, clear statement
}else # first line: import names to $y, count to $z
{($g=preg_match_all)("#(\w+)[.,]#",$s,$m);$z=count($y=$m[1]);}
# loop through combinations
for(;$j++<10**$z;)if(count_chars($p="$j",3)==join(range(1,$i=$z))){
for($c=$x;$i--;) # remove dot and "not", replace names
$c=strtr($c,["."=>"","not"=>"",$y[$p[$i]-1]=>$i+1]);
# all conditions met? print combination!
for(;eval("return$c;")&++$i<$z;)echo$y[$p[$i]-1],"\n,"[$i<$z-1];
}
```
] |
[Question]
[
Consider the 74 characters from the [2016 time capsule string](https://codegolf.stackexchange.com/questions/105398/2016-time-capsule-string-how-versatile-is-your-language) (note the leading space):
```
!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~
```
Your task is to write as many programs as possible (**in the same language**) using these characters. The output of each program must be nonempty. When all of the programs and their outputs are considered, it must only use each of the 74 above characters no more than once.
Your score is determined by the number of programs you have written, with the total length of the programs being a tie-breaker (greatest length wins).
Some more rules:
1. Each program must terminate.
2. Each program must be a full program and output in a reasonable format.
3. All output to STDERR is ignored.
4. You may not run your program with any flags, except those required to run the program. (E.g., a `-e` flag that executes program source.)
5. If the program has output that cannot be suppressed, you may ignore when considering the output. (E.g., you may ignore trailing newlines.)
6. Each program should be able to be executed with empty stdin.
## Example
If I had programs `4` and `T1~` that outputted `4` and `9` respectively, they would, when considered together, be:
```
44T1~9
```
Which can be seen to be a subset of the capsule string. However, if I had programs `4@|4` and `|e+` that outputted `4` and `f` respectively, they would be:
```
4@|44|e+f
```
And, since there are 3 `4`s, it is not a subset.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 13 programs, length 61
```
\x:#).&~L // outputs 9 (41 & ~100)
~T+~Tf)p // outputs 4 ((~0 + ~floor(0)) ** 2)
$~Q$ *\~Z // outputs 1 (~'"' * ~0)
I%A^O||@{=!(Hmy)) // outputs 4 (64 % 10 ^ {} || function(X,Y,Z) { return function() { return ((U = !(H.m("y")))) } })
`! // outputs !
`! // outputs !
`. // outputs .
`@ // outputs @
`Q // outputs Q
`e // outputs e
`| // outputs |
`~ // outputs ~
`~ // outputs ~
```
It's awfully hard to come up with an answer that isn't just a string literal and outputs something other than a number...
Output and programs combined:
```
!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~
```
I think I got 'em all...
---
When stripped down to the bare minimum:
```
#)&~L
~T+~T)p
~Q*~Z
I%A
`!
`!
`.
`@
`Q
`e
`|
`~
`~
```
It leaves these chars for future programs/outputs:
```
!$$()).:=@HO\\^fmxy{||
```
You can trade two of `$`, `)`, or `|` for two of any of the chars in the nine string literals; that is, two of any of `!.@Qe|~`.
Additionally, you can trade out the `Q` in the third program for `H` or `O`, and the `Z` for `H`, `O`, `@`, or `{`.
[Answer]
# PHP, 22 programs
Yeah, I get it's kind of boring.
Programs (separated by single newline):
```
!
!
$
)
)
.
4
@
Q
T
\
`
`
`
`
e
|
|
~
~
~
~
```
Output and programs combined:
```
!!!!$$))))..44@@QQTT\\````````ee||||~~~~~~~~
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 2 programs, length 31
```
+!!($eefmpxy =9)
```
[Try it online!](https://tio.run/nexus/powershell#@6@tqKihkpqalltQUalga6n5/z8A "PowerShell – TIO Nexus")
Outputs `1`.
Works by setting the variable `$eefmpxy` to `9`, encapsulating that in parens, taking the Boolean-not `!` of that (which turns it to `$False`), then the Boolean-not of *that* (which turns it to `$True`), then casts as an integer with `+`, turning it to `1`. That's left on the pipeline and output is implicit.
---
```
4*!$AHILOQQQTTZ
```
[Try it online!](https://tio.run/nexus/powershell#@2@ipaji6OHp4x8YGBgSEvX/PwA "PowerShell – TIO Nexus")
Outputs `4`.
Works by initializing the variable `$AHILOQQQTTZ` to the default of `$null`, the Boolean-not `!` of which is `$True`. That's implicitly cast to an integer `1` due to the multiplication of `4*`, so the result of `4` is left on the pipeline and output is implicit.
---
We're really limited in PowerShell for other things, as though we have plenty of pipe characters `|` to pipeline commands together, we only have one `{` and no `}`; too many `)` for the lone `(`; the backtick ``` is used as a "line continuation marker" to interpret multiple lines as one (used for readability), but we have no linefeed to go with it; and the `~` and `^` characters are "Reserved for future use" and thus toss a syntax error when you try to use them. So, most of the characters are useless, which is a shame.
While the `#` character starts a comment (and everything after it is completely ignored), it feels cheaty to use it that way, so I didn't include it above.
[Answer]
# [Cardinal](https://esolangs.org/wiki/Cardinal), 1 program, length 73
```
%#~~~~~~~~~!!!!!+=.*449eefmpxyAHLOQQQTTZ`````````@@@$$I\\^{|||| ())))&..:
```
Outputs 1
[Try it online!](https://tio.run/nexus/cardinal#@6@qXAcDiiCgbaunZWJimZqalltQUeno4eMfGBgYEhKVAAMODg4qKp4xMXHVNUCgoKEJBGp6elb//wMA "Cardinal – TIO Nexus")
Cardinal can only have 1 valid program that will do anything as there is only 1 %.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 programs, length 19
**Programs**
```
)O! # outputs 1 fac(sum([]))
A`\ # outputs y 2nd_last(alphabet)
THf`x # outputs 4 last_primefactor(int(10,16))*2
TL`\ # outputs 9 2nd_last(range[1 ... 10])
```
**Output and programs combined**
```
!)149AHLOTT\\```fxy
```
] |
[Question]
[
Write [a program or function](http://meta.codegolf.stackexchange.com/q/2419/8478) that [takes as input](http://meta.codegolf.stackexchange.com/q/2447/8478) three positive integers `x`, `y`, and `a` and [returns or outputs](http://meta.codegolf.stackexchange.com/q/2447/8478) the maximum number of whole `a✕1` rectangles that can be packed (axis-aligned) into an `x✕y` rectangle. Although the result will always be an integer, the program need not give the result using an integer type; in particular, floating-point outputs are acceptable. Use of [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061) is forbidden. Answers are scored in bytes including [the cost of non-standard compiler flags or other marks](http://meta.codegolf.stackexchange.com/q/19/18487).
Sample inputs and outputs:
```
x, y, a -> result
--------------------
1, 1, 3 -> 0
2, 2, 3 -> 0
1, 6, 4 -> 1
6, 1, 4 -> 1
1, 6, 3 -> 2
6, 1, 3 -> 2
2, 5, 3 -> 2
5, 2, 3 -> 2
3, 3, 3 -> 3
3, 4, 3 -> 4
4, 3, 3 -> 4
4, 4, 3 -> 5
6, 6, 4 -> 8
5, 7, 4 -> 8
7, 5, 4 -> 8
6, 7, 4 -> 10
7, 6, 4 -> 10
5, 8, 3 -> 13
8, 5, 3 -> 13
12, 12, 8 -> 16
12, 13, 8 -> 18
13, 12, 8 -> 18
8, 8, 3 -> 21
12, 12, 5 -> 28
13, 13, 5 -> 33
```
---
In response to a question in the comments, note that some optimal packings may not be obvious at first glance. For instance, the case `x=8`, `y=8`, and `a=3` has solutions that look like this:
```
||||||||
||||||||
||||||||
---||---
---||---
|| ||---
||------
||------
```
(8 + 2 + 2 = 12 vertical placements and 2 + 3 + 4 = 9 horizontal placements gives 12 + 9 = 21 placements in total.)
[Answer]
## Python 2, 53 bytes
```
lambda p,q,n:p/n*q+q/n*(p%n)-min(0,n-p%n-q%n)*(p>n<q)
```
Adapts the formula given in [this paper](http://www.sciencedirect.com/science/article/pii/0012365X79901158), which is:
```
def f(p,q,n):a=p%n;b=q%n;return(p*q-[a*b,(n-a)*(n-b)][a+b>=n and p>=n and q>=n])/n
```
] |
[Question]
[
# The Task
Given the positive value of [unix timestamp](https://en.wikipedia.org/wiki/Unix_time) output any of two valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time formats:
* `YYYY-MM-DDTHH:mm:SS` or, alternatively,
* `YYYY-MM-DD HH:mm:SS`
You may ignore any [leap seconds](https://en.wikipedia.org/wiki/Leap_second), if you wish, as well as the timezone part of the date.
Also, ignore the [year 2038 problem](https://en.wikipedia.org/wiki/Year_2038_problem).
# Rules
* You must not use any built-in date functions,
* You may not use any string formatting functions (like [`printf`](https://en.wikipedia.org/wiki/Printf_format_string)), however sorting, reversing, changing case etc. is allowed,
* Your program may not contain any numbers (ie. characters `0`, `1`, `2`, ... `9`) and letters which mean hexadecimal number (`A`, `a`, `B`, `b`, ... `f`), if used in context of hexadecimal number,
* The only exception are line numbers (or labels and `goto` statements), if your language requires them,
* You may use any function or method that returns a number, but **only once** (each) in your program:
>
> For example, you can use something like `zero = length('');` to have number `0`, but then you can't use `one = length('a');` because you would use the `length()` function twice, so you can consider using `one = cos(zero);`
>
>
>
* The same applies to built-in constants or variables
>
> You may use built-in constants like [`__LINE__`](http://php.net/manual/en/language.constants.predefined.php) etc., but only once for each value (for example, `__FILE__` is "really" constant in a file, so you can use it only once in a file, but `__LINE__` varies for each line, so you can use it once per line).
>
>
>
* If a function or a constant is used in a loop that has a chance to be executed more than once, it is considered to be used more than once and this is forbidden,
* All [loopholes](http://meta.codegolf.stackexchange.com/q/1061/41819) are forbidden (especially, loading the result from another site or executing an external program to do the calculations).
* Any errors, compiler warnings are allowed, however the ISO 8601 string must be valid (no error messages within the output string)
# Testing
Your code must return a valid value which will be tested with the site <http://www.unixtimestamp.com/>.
# Notes
This question is a popularity contest, so the highest scored answer wins (not earlier than at Midnight on Monday, September 7th UTC). The main idea is to show your skills when limited to not use numbers. When voting, please consider how numbers are represented by the author and what tricks they use. In my opinion such constructions like
```
eighty_six_thousand_four_hundred = one;
eighty_six_thousand_four_hundred++;
eighty_six_thousand_four_hundred++;
//... 86399 times
```
or
```
// 86399 empty lines
...
$eighty_six_thousand_four_hundred = __LINE__;
```
should be avoided.
I also kindly ask that you provide an online version of your program, so everyone can test it (the program must not be limited to your environment).
[Answer]
# Inform 7
```
"ISO Eight Six Zero One" by "Dannii Willis"
There is a room.
Sixty is a number variable.
Hundred is a number variable.
Days per year is a number variable.
Days per leap year is a number variable.
Leap year period is a number variable.
Days per leap year period is a number variable.
Epoch is a number variable.
Seconds per day is a number variable.
Months is a list of numbers variable.
To initialise number variables:
let thirty be ten times three;
let thirty one be thirty plus one;
now sixty is five times twelve;
now hundred is ten times ten;
now days per year is sixty times six plus five;
now days per leap year is days per year plus one;
now leap year period is hundred times four;
now days per leap year period is leap year period times days per year plus hundred minus three;
now epoch is leap year period times five minus thirty;
now seconds per day is sixty times sixty times twelve times two;
truncate months to zero entries;
let X be zero; add X to months;
increase X by thirty one; add X to months;
increase X by thirty minus two; add X to months;
increase X by thirty one; add X to months;
increase X by thirty; add X to months;
increase X by thirty one; add X to months;
increase X by thirty; add X to months;
increase X by thirty one; add X to months;
increase X by thirty one; add X to months;
increase X by thirty; add X to months;
increase X by thirty one; add X to months;
increase X by thirty; add X to months;
To decide whether (year - a number) is a leap year:
if the remainder after dividing year by four is zero:
if the remainder after dividing year by hundred is not zero:
yes;
otherwise if the remainder after dividing year by leap year period is zero:
yes;
no;
To say zero padded (X - a number):
if X is less than ten:
say zero;
say X;
[ This general algorithim is taken from the PHP source code ]
To say (X - a number) as an ISO Eight Six Zero One date:
initialise number variables;
[ Split the timestamp into days and seconds ]
let days be X divided by seconds per day;
let seconds be the remainder after dividing X by seconds per day;
[ Calculate the date ]
let year be epoch;
let month be twelve;
let day be zero;
increase days by one;
[ Year ]
if days is at least days per leap year period:
let leap year period count be days divided by days per leap year period;
increase year by leap year period times leap year period count;
decrease days by days per leap year period times leap year period count;
while days is at least days per leap year:
increase year by one;
if year is a leap year:
decrease days by days per leap year;
otherwise:
decrease days by days per year;
[ Month ]
if year is a leap year:
decrease entry one of months by one;
decrease entry two of months by one;
while month is greater than one:
if days is greater than entry month of months:
break;
decrease month by one;
[ Day ]
now day is days minus entry month of months;
[ Calculate the time ]
let hours be seconds divided by (sixty times sixty);
let minutes be the remainder after dividing (seconds divided by sixty) by sixty;
let secs be the remainder after dividing seconds by sixty;
say "[year]-[zero padded month]-[zero padded day] [zero padded hours]:[zero padded minutes]:[zero padded secs]";
```
Inform 7 allows the numbers one to twelve to be written in words - from these we calculate the other numbers which are needed. With that it was just a matter of transferring over the simplest algorithm I could find, which happened to be PHP's. I haven't accounted for negative timestamps. Maybe another day.
Here are some tests:
```
When play begins:
say "0: [0 as an ISO Eight Six Zero One date][line break]";
say "1000000000: [1000000000 as an ISO Eight Six Zero One date][line break]";
say "1234567890: [1234567890 as an ISO Eight Six Zero One date][line break]";
```
Which produce the following correct output:
```
0: 1970-01-01 00:00:00
1000000000: 2001-09-09 01:46:40
1234567890: 2009-02-13 23:31:30
```
[Answer]
# JavaScript (ES6)
So I'm not 100% sure I'm adhering to the rules totally, so please let me know if not and I'll remove.
```
var T = +prompt('Enter a timestamp'),
[one, two, three, four, five, six, seven, eight, nine, zero] = btoa('\xd7\x6d\xf8\xe7\xae\xfc\xf7\x40').split(''),
minute = six + zero,
hour = minute * minute,
day = hour * (two + four),
Y = one + nine + seven + zero,
M = one,
D = one,
H = zero,
I = zero,
S = zero;
while (T) {
var monthLookup = [
[],
(three + one) * day,
(+(two + eight) + !(Y%four)) * day,
(three + one) * day,
(three + zero) * day,
(three + one) * day,
(three + zero) * day,
(three + one) * day,
(three + one) * day,
(three + zero) * day,
(three + one) * day,
(three + zero) * day,
(three + one) * day
];
if (T >= monthLookup[M]) {
T -= monthLookup[M++];
if (M == one + three) {
M = one;
Y++;
}
}
else if (T >= day) {
T -= day;
D++;
}
else if (T >= hour) {
T -= hour;
H++;
}
else if (T >= minute) {
T -= minute;
I++;
}
else {
S = T;
break;
}
}
// prepend leading zeroes
M = M < one + zero ? zero + M : M;
D = D < one + zero ? zero + D : D;
H = H < one + zero ? zero + H : H;
I = I < one + zero ? zero + I : I;
S = S < one + zero ? zero + S : S;
alert(Y+'-'+M+'-'+D+' '+H+':'+I+':'+S);
```
Basically I get all the numbers by encoding the string (I've used `\x??` notation for ease of testing, but these are just unprintable ASCII chars and so don't include numbers) and then use concatenation to get the numbers I need, to use a pretty basic decrementor approach to populate the various fields.
] |
[Question]
[
### Introduction
When a room has bare, parallel walls, it can create unpleasant repeating acoustic reflections (echoes). A diffuser is a device mounted on a wall which creates a blocky surface of many different heights. This has the effect of breaking up the reflected sound into many smaller reflections (each with a different time delay). The acoustic quality of the room is thought to be greatly enhanced.
### Primitive Root Diffuser
The primitive root diffuser uses a grid of (typically wooden) posts, each with a different height (to obtain a different reflection delay time). The heights of the posts are chosen according to successive powers of a primitive root G, modulo N (a prime number).
[Here](https://www.gearslutz.com/board/bass-traps-acoustic-panels-foam-etc/428161-my-primitive-root-diffuser-build-check-out.html) are some pictures of a primitive root diffuser.
### Task
You must write a program or function which takes a prime number N > 2 as its only input. It must then select a primitive root of N. G is a primitive root of N if the successive powers of G modulo N generate all the integers from 1 to N-1. A more formal definition of primitive roots can be found in the [Wikipedia article](https://en.wikipedia.org/wiki/Primitive_root_modulo_n).
Your code must then place these successive powers into an X-by-Y array (or matrix). Because we want to hang this on the wall, the diffuser should be a convenient shape - as close to square as possible. The number of entries in the array will be N-1, so its dimensions X and Y should be chosen such that X\*Y = N-1, and X is near but not equal to Y (specifically, X and Y are coprime). For convenience of display, the horizontal dimension should be greater than the vertical dimension.
The order of placement of successive powers of G (modulo N) should start at one corner of the array, then traverse diagonally through the array, wrapping around in both directions until all array positions are filled. Then the function should return that array, or print it to stdout, whichever you prefer.
We won't concern ourselves with the measurement units used to actually cut the posts to length; we'll assume the units are appropriate for the range of audio frequencies we want to diffuse, and stick to integers.
There's an [online calculator](http://www.oliverprime.com/prd/), in case you want to check your work. However, the site appears to be down currently.
### Example
Suppose we choose N = 41. Our program should select one of the primitive roots of N, which are [6, 7, 11, 12, 13, 15, 17, 19, 22, 24, 26, 28, 29, 30, 34, 35]. Suppose our program selects the smallest primitive root, G = 6.
Our program then chooses the squarest dimensions X,Y for the array such that X\*Y = N-1. The clear choice is X=8 and Y=5.
Then our program populates the array with successive powers of G modulo N (starting with G^0), traversing diagonally. The program then returns/prints the array:
```
1 14 32 38 40 27 9 3
18 6 2 28 23 35 39 13
37 26 36 12 4 15 5 29
10 17 33 11 31 24 8 30
16 19 20 34 25 22 21 7
```
Note how it begins with 6^0 mod 41 = 1, then 6^1 mod 41 = 6, then 6^2 mod 41 = 36, then 6^3 mod 41 = 11, etc.
To clarify, the sequence of powers of 6 modulo 41 is:
```
[1, 6, 36, 11, 25, 27, 39, 29, 10, 19, 32, 28, 4, 24, 21, 3, 18, 26, 33, 34, 40, 35, 5, 30, 16, 14, 2, 12, 31, 22, 9, 13, 37, 17, 20, 38, 23, 15, 8, 7]
```
### Another Example
N = 31
Assuming the program selects G = 11, X = 6, Y = 5, the output is:
```
1 26 25 30 5 6
4 11 7 27 20 24
16 13 28 15 18 3
2 21 19 29 10 12
8 22 14 23 9 17
```
### A Third Example
N = 37
Assuming the program selects G = 2, X = 9, Y = 4, the output is:
```
1 12 33 26 16 7 10 9 34
31 2 24 29 15 32 14 20 18
36 25 4 11 21 30 27 28 3
6 35 13 8 22 5 23 17 19
```
### Scoring
Standard code golf rules - the fewest bytes of code producing correct output wins!
[Answer]
# Mathematica 158
Spaces not needed:
```
f@n_ := (m = Mod;
{p, q} = Sort[{y-x, x, y} /. Solve[x*y==n - 1 && x~GCD~y == 1 < x < y, Integers]][[1, 2 ;;]];
(g[#~m~p + 1, #~m~q + 1] = m[PrimitiveRoot@n^#, n]) & /@ (Range@n - 1);
g~ Array~{p, q})
```

The last one looks like this ...

[Answer]
# Haskell, ~~220~~ ~~213~~ ~~207~~ ~~201~~ ~~194~~ ~~182~~ 178
```
f n=[map(x%)[0..j-1]|x<-[0..i-1]]where j=[x|x<-l,x^2>n,(n-1)&x<1,gcd(n`div`x)x<2]!!0;i=n`div`j;0%0=1;a%b=([x|x<-l,all((>1).(&n).(x^))l]!!0*(a-1)&i%((b-1)&j))&n;l=[1..n-2]
(&)=mod
```
this is a function which returns a matrix (a list of lists of `Int`).
it works by calculating the smallest possible `g`, the closet coprime `j` and `k` and defines a recursive function that given the indices of a slot in the grid returns the Integer in it, and maps this function over all slots.
**example output:**
```
*Main> mapM_ print $ f 13 -- used for printing the matrix line-by-lie
[1,5,12,8]
[3,2,10,11]
[9,6,4,7]
*Main> mapM_ print $ f 43
[1,21,11,16,35,4,41]
[37,3,20,33,5,19,12]
[36,25,9,17,13,15,14]
[42,22,32,27,8,39,2]
[6,40,23,10,38,24,31]
[7,18,34,26,30,28,29]
*Main> mapM_ print $ f 37
[1,12,33,26,16,7,10,9,34]
[31,2,24,29,15,32,14,20,18]
[36,25,4,11,21,30,27,28,3]
[6,35,13,8,22,5,23,17,19]
```
[Answer]
# MATLAB w/ Symbolic Toolbox - ~~199~~ 198 bytes
Minified:
```
function C=F(N),M=N-1;y=1:N;p=y-1;t=@(x)eval(mod(sym(x).^p,N));l=M./y;L=fix(l);k=y(l==L.*gcd(y,L)&y>M^.5);k=k(1);l=M/k;C=eye(l,k);g=y(arrayfun(@(x)sum(t(x)<2)<3,y));C(mod(p,k)*l+mod(p,l)+1)=t(g(1));
```
Expanded:
```
function C = primroot( N )
M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( mod( sym(x).^p, N ) );
l = M./y;
L = fix( l );
k = y( l == L.*gcd(y,L) & y > M^.5 );
k = k(1);
l = M/k;
C = eye( l, k );
g = y(arrayfun( @(x) sum( t(x) < 2 ) < 3, y ));
C(mod(p,k)*l+mod(p,l)+1) = t(g(1));
```
### Sample Outputs
```
primroot(37)
ans =
1 12 33 26 16 7 10 9 34
31 2 24 29 15 32 14 20 18
36 25 4 11 21 30 27 28 3
6 35 13 8 22 5 23 17 19
primroot(41)
ans =
1 14 32 38 40 27 9 3
18 6 2 28 23 35 39 13
37 26 36 12 4 15 5 29
10 17 33 11 31 24 8 30
16 19 20 34 25 22 21 7
primroot(31)
ans =
1 6 5 30 25 26
16 3 18 15 28 13
8 17 9 23 14 22
4 24 20 27 7 11
2 12 10 29 19 21
primroot(113)
ans =
1 48 44 78 15 42 95 40 112 65 69 35 98 71 18 73
106 3 31 19 8 45 13 59 7 110 82 94 105 68 100 54
49 92 9 93 57 24 22 39 64 21 104 20 56 89 91 74
109 34 50 27 53 58 72 66 4 79 63 86 60 55 41 47
28 101 102 37 81 46 61 103 85 12 11 76 32 67 52 10
30 84 77 80 111 17 25 70 83 29 36 33 2 96 88 43
16 90 26 5 14 107 51 75 97 23 87 108 99 6 62 38
```
A noble effort for MATLAB (even if I do say so myself), the language that requires `a1 = b(c); a = a1(d);` because it doesn't understand `a = b(c)(d)`. :P
A few notes:
* the routine exploits the fact that `mod( j^k, N )` for `k = 0..N-1` is strictly positive for positive `j`, and that `j` is only a primitive root of `N` if the number `1` appears exactly twice in the sequence
* the routine exploits the fact that a number `x >= 2` can only equal `floor(x)*gcd(floor(x),y)` for positive `y` if `floor(x) == x` and `gcd(floor(x),y) == 1`. Also, the fact that `x` and `y` are coprime iff `gcd(x,y) == 1`.
Other than that, I couldn't find any problem-specific optimizations.
MATLAB's `mod` function is particularly painful since I use it 3 times, and it takes a minimum of 8 characters per invocation, as opposed to 3 (i.e. `x%y`) for virtually every other programming language in existence. The `arrayfun` (which in every other language is either `map` or `->` is also painful.
In light of these handicaps, I also present the following solution:
### Fantasy MATLAB - far fewer bytes
```
C = @(N):
M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( sym(x).^p % N );
L = fix( l = M./y );
k = y( l == L.*gcd(y,L) & y > M^.5 )(1);
C = ones( l = M/k, k );
C( p%k*l + p%l + 1 ) = t(y( x -> sum( t(x) < 2 ) < 3 )(1));
```
[Answer]
# Python 2: 232 217 212 208 201 198 194 192 187 bytes
```
N=input()
w=n=G=N-1
Z=range(n)
while sorted(G**x%N-1for x in Z)!=Z:G-=1
while w*w/n|n%w|1-all(w%i|n/w%i for i in Z[2:]):w-=1
n/=w
a=[]
for x in Z:a+=[n*[0]];a[x%w][x%n]=G**x%N
print a[:w]
```
Now it selects the largest root instead of the smallest, so output is different.
Example:
```
41
[[1, 27L, 32L, 3L, 40L, 14, 9L, 38L], [18L, 35, 2L, 13L, 23L, 6L, 39, 28L], [37L, 15L, 36, 29L, 4L, 26L, 5L, 12L], [10L, 24L, 33L, 30, 31L, 17L, 8L, 11L], [16L, 22L, 20L, 7L, 25, 19L, 21L, 34L]]
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 84 bytes
```
{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}
```
[Try it on repl.it!](https://repl.it/join/imysopnc-razetime)
Uses `⎕IO←0` (0-indexing).
A dfn which takes input as a long integer, and returns a matrix of long ints for the first primitive root of `⍵`.
Hosted on repl.it since tio is not updated with the latest version of dzaima/APL. The run button runs all testcases.
## Explanation
`{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}`
`∘.*⍨⍳⍵-1` create a power table for 0..n-1
`⍵|` modulo that by the input `⍵`
`↓` convert to list of lists
`(⍵∘{...}¨⌿⊢)` tacit function, filter lists where:
`1=≢⍵~⍨⍳⍺` numbers from 1 to n-1 are present
`⊃` take the first one
`{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}` and do the following:
**Dimension finding function(courtesy of ngn):**
`{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵` do the following with the length of the first list:
`∘.×⍨⍳⍵` multiplication table of 1..length
`⍸⍵=` coordinates at which product = length
`(≠/¨⌿⊢)` remove the ones which create squares
`a←` assign the final coordinates to `a`
`⊃⍋+/↑` index of coordinate with highest sum
`a⊃⍨` take that coordinate from `a`
`b←` assign that to b
`(...)⍴0` create a grid of zeroes of that size
`⍵@(...)⊢` assign the first list at the following indices:
`⍳≢⍵` 1..length
`2⌿¨` each replicated twice
`b∘|¨` mod b(vectorizes)
This gives the final diagonally oriented matrix.
] |
[Question]
[
This is "programming" at its most fundamental.
Build a diagram of (two-wire) NAND logic gates that will take the input wires `A1`, `A2`, `A4`, `A8`, `B1`, `B2`, `B4`, `B8`, representing two binary numbers `A` to `B` from 0 to 15, and return values on the output wires `C1`, `C2`, `C4`, and `C8` representing `C`, which is the sum of `A` and `B` modulo 16.
Your score is determined by the number of NAND gates (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:
* `NOT: 1`
* `AND: 2`
* `OR: 3`
* `XOR: 4`
Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.
Lowest score wins.
---
Updates:
**03-07 19:09:** Due to discussions with Jan Dvorak, it came to my attention that the total number of gates, constants and splits is always determined solely by the number of gates. Because of this, I have simplified the score requirement back down to simply the number of gates required.
[Answer]
# 31 gates

*[created in [Logisim](http://ozark.hendrix.edu/%7Eburch/logisim/)]*
---
The standard XOR-gate can be built with four NANDs. Tapping the first NAND provides us with a fairly compact half-adder with inverted carry:
```
hadder(A,B) => (sum, iCarry):
X = A^B
sum = (A^X)^(B^X)
iCarry = X
```
These can be combined into a 9-gate full adder:
```
fadder(A,B,C) => (sum, carry):
DD1 = hadder(A,B)
DD2 = hadder(DD1.sum, C)
sum = DD2.sum
carry = DD1.iCarry ^ DD2.iCarry
```
These combined yield a naive **36**-gate four-bit adder. Not bad.
Now, we inline all modules and perform these optimizations:
```
delete gates with no output (only the final gate)
0^x => 1 (one gate, twice)
1^(1^x) => 0 (two gates, once)
```
for a grand total of **31 gates**.
---
] |
[Question]
[
For a given `n` list [prime factorization](https://en.wikipedia.org/wiki/Prime_factorization) of all natural numbers between `1` and `n` in ascending order. For example, for `n` = 10 the output would be:
```
1:
2: 2^1
3: 3^1
4: 2^2
5: 5^1
6: 2^1 3^1
7: 7^1
8: 2^3
9: 3^2
10: 2^1 5^1
```
**Requirements:**
* *You cannot just iterate over the numbers and factor each of them.* (Unless you know how to factor a number in logarithmic time, and then I doubt you'd be wasting your time solving puzzles.) This is too inefficient.
* The output should be as in the example above: On each line the number and the list of its prime factors.
* Consider that `n` can be *very* large, so it might be infeasible to generate all the factorizations into memory and then sort them at the end. (But if you have a clever solution that violates this, post it too.)
[Answer]
## C++
Implements a sieve using primes up to `sqrt(n)`. Maintains a list of linked lists to keep track of which primes divide which upcoming numbers. Each time a prime `p` is used, its `Factor` structure is moved `p` slots down the list.
Most of the time is spent in just `printf`ing the answer.
```
#include <stdio.h>
#include <stdlib.h>
// lists of Factors represent known prime factors of a number
struct Factor {
Factor(int p) : prime(p), next(NULL) { }
int prime;
Factor *next;
};
int main(int argc, char *argv[]) {
long long n = atoll(argv[1]);
// figure out the maximum prime we need to sieve with
int maxp = 1;
while ((long long)maxp * maxp < n) maxp++;
maxp--;
// find next power of two up from that for our circular buffer size
int size = 1;
while (size < maxp) size *= 2;
int mask = size - 1;
// allocate circular buffer of lists of sieving prime factors for upcoming numbers
Factor **factors = new Factor*[size]();
printf("1:\n");
for (long long x = 2; x < n; x++) {
Factor *list = factors[x & mask];
factors[x & mask] = NULL; // reset so it can hold the list for x + size
if (!list && x <= maxp) { // x is a prime we need to sieve with - make new list with just itself
list = new Factor(x);
}
// print factor list, push each Factor along to the next list.
printf("%lld:", x);
long long y = x;
while (list) {
Factor *f = list;
list = f->next;
int p = f->prime;
// count how many factors of p are in x
int k = 1;
y /= p;
while (y % p == 0) {
k++;
y /= p;
}
printf(" %d^%d", p, k);
// splice f into the list for the next number it divides
long long z = x + f->prime;
f->next = factors[z & mask];
factors[z & mask] = f;
}
// remaining part of x must be prime
if (y != 1) printf(" %lld^1", y);
printf("\n");
}
}
```
[Answer]
Below is my attempt, in R5RS scheme (disclaimer: I'm not actually a Schemer (yet!), so pardon the (probably) terrible code).
```
(define count 10)
; `factors` is our vector of linked-lists of factors. We're adding to these
; as we go on.
(define factors (make-vector count 'not-found))
(vector-set! factors 0 '())
; `primes-so-far` contains all the prime numbers we've discovered thus far.
; We use this list to speed up the dividing of numbers.
; `primes-so-far-last` is a ref to the last entry in the `primes-so-far`
; list, for O(1) appending to the list.
(define primes-so-far '(dummy))
(define primes-so-far-last primes-so-far)
;; Helpers
(define (factor-ref n)
(vector-ref factors (- n 1)))
(define (factor-cached? n)
(not (eq? (vector-ref factors (- n 1)) 'not-found)))
(define (factor-put n factor)
(let* ((rest (/ n factor))
(factor-cell (cons factor (factor-ref rest))))
(vector-set! factors (- n 1) factor-cell)
factor-cell))
(define (prime-append n)
(let ((new-prime-cell (cons n '())))
(set-cdr! primes-so-far-last new-prime-cell)
(set! primes-so-far-last new-prime-cell)
new-prime-cell))
;; The factor procedure (assumes that `[1..n-1]` have already been factorized).
(define (factor n)
(define (divides? m n)
(= (modulo n m) 0))
; n the number to factor.
; primes the list of primes to try to divide with.
(define (iter n primes)
(cond ((factor-cached? n)
(factor-ref n))
((null? primes)
; no primes left to divide with; n is prime.
(prime-append n)
(factor-put n n)) ; the only prime factor in a prime is itself
((divides? (car primes) n)
(factor-put n (car primes))
(factor-ref n))
(else
(iter n (cdr primes)))))
(iter n (cdr primes-so-far)))
(define (print-loop i)
(if (<= i count)
(begin
(display i)
(display ": ")
(display (factor i))
(newline)
(print-loop (+ i 1)))))
(print-loop 1)
```
Prints as:
```
1: ()
2: (2)
3: (3)
4: (2 2)
5: (5)
6: (2 3)
7: (7)
8: (2 2 2)
9: (3 3)
10: (2 5)
```
(Not exactly like in the task description, but all you'd have to do to get that output is to fold the list and merge repetitions of the same number, during the output part of the code. The internal representation/algorithm would still be the same.)
The idea is to cache the previously computed values, but make use of the fact that the factors of `n` is the first prime factor of `n` and the prime factors of (n / first-factor). But the latter is already known, so we just re-use the already existing list of factors for that smaller number. Thus, for each number in `[1..n]` which is not prime, a single cons cell is stored.
For each number, a single cons cell is created and stored. Thus, this approach should run with `O(n)` storage usage. I've no clue if it's possible to neatly express the time-complexity.
[Answer]
# [C (gcc)](https://gcc.gnu.org/)
```
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
int square(int a){
return a * a;
}
void prime_factors(int n){
// this is an array of n elements, which will contain all found primes.
// curprime stores the index of the last found prime, which saves us searching for where to insert the next one and things.
int* primes = calloc(sizeof(int), n);
int curprime = 0;
printf("1:\n"); // Micro optimization, and rids me of the messing around that is 1.
for(int i=2; i<=n; i++){
// Print the current i.
printf("%i: ",i);
// Define val, which we'll slowly make smaller and smaller. Mwahaha.
int val = i;
int isprime = true; // This will be set to false if it's divisible by any primes, which of course, means it's also not a prime.
// Loop through primes, this loop stops if we've reached either more than sqrt(count) primes, or val is equal to zero (as such, it's fully prime factorized).
for(int*prime_pointer = primes; val && square((int)(prime_pointer-primes)) < curprime; prime_pointer++){
int prime = *prime_pointer;
// if the current val is divisible by the current prime.
while(val%prime == 0){
isprime = false; // We know that this number isn't prime.
val = val / prime; // Divide val by it.
printf("%i ",prime);// And write this prime.
}
}
if(isprime){ // If this number is a prime.
printf("%i ",i); // Append it to its own list.
primes[curprime++] = i; // And append this new prime to our list of primes.
}
printf("\n"); // Terminate the line with a newline. Duh...
}
}
int main(int argc, char** argv){
prime_factors(1000);
}
```
Defines the function `prime_factors` which takes an integer `n` and outputs via printf in the following format:
```
1:
2: 2
3: 3
4: 2 2
5: 5
6: 2 3
7: 7
8: 2 2 2
9: 3 3
10: 2
```
This uses O(n) extra memory, and I'm not sure the time complexity.
[Try it online!](https://tio.run/##XVTRbttGEHwWv2LhILEoK7Lcx9AqEMAvBRqgDwX60BbFiVyai5B3yt1Rih34293ZO0qyAssCT9ybmd2Zu/rjY12/vr4TW/djw3QfYiNu1f1aXPzUy1Z/K9413Iplin5kujstW9MHpnVRiI0Uvo3G81wfTfmjmHmOo7dkaEGmKl6KYu@koZ2Xgf9rTR2dD6nYavHtLcVOAuFjsMd780SuJUvc88A2hiUdOqk7OkjfU@1sNII6PLdutBNsWCWgevRpSQEcHADMJLbh74qoi96E@HbfETuYPcrHQIGNrzuxj6jyeMkerTuABPYxQVj@HslhBAYgUUuVHO0sJim0oRryXD0P8syu1VbLJZqtUtlZ5IbWVVHMsLCxnV/dffrHXpUVoY8vUntHbhdlkGcTxdllovPSBMLOqRuQBZVqfOoodibqGO@gB@rTiGXzS0Vyv7H4vrnReeuc/lDKBAExnrUOe05K3ssnulpKqeq0/CF7vjf9yQu@hgGhd4f@iQbzFRMf0DP7JHN6XtGXg@nwp9hKCAA0LdW0lHCcg4arUqY/NQnJ6C0gOersc9SkJYnXgRrZS5Btz7R9AtnTNPSjMEymdqMPcHZgY0PeBARH1iGeuXw1Nfa7czuMAeN77E5AKY29vkGKdkGZ0e6eybOpO26IBZPzNDjNRofQhm8@zkELn08oSI@2CyjG6ei1kWeGqXODkI11t8zK2rHvpx4oHw1kpil1YpOFi3xudg7PYN1MDFWC//DhePhSyuYXtR9zZVnS/Sl0FV2UTJFIdhzNuCRUs3RU0l7kZertwo2376cxYy986XmO@vcTAWKfSWfnACSPK1Kiv5i@WnfIaU5e2HHYonMJ9vot8CzHSb9v888pQg@Q1KSwqiaJufYcbSQ7FZcVij8jrQcvkTPTGfylyP@C45tVlj8U/bf2J03nSP3MgvOjOz7vdgwWSVmWGMgdLPUS4nEHLPr7aM/Nzb/phMwmbSZvzpR8mDwCEDKeQDTwpxswKT5qSJdJOlPsB7Em9YgbUE/yAQmGcCDqckUPY7daAeBFL2vNwoA7Nt/n/rFeUt0Zv1joYq/WXd7kd@v1GlfFy@vr/w "C (gcc) – Try It Online")
] |
[Question]
[
The following problem is taken from the real world — but indubitably `code-golf`!
In this puzzle, the programming language is fixed, and your job is to write the most efficient program in this fixed language. The language has no loops; a program is a straight-line sequence of instructions. Each instruction consists of exactly three characters — an opcode and two operands — and in fact there are only four possible opcodes:
* `<xy` — Compare the value in register *x* to the value in register *y*; set *flag* = L if *x* < *y*; *flag* = G if *x* > *y*; and *flag* = Z otherwise.
* `mxy` — Set the value in register *x* equal to the value in register *y*. (This is "move.")
* `lxy` — If *flag* = L, then set the value in register *x* equal to the value in register *y*; otherwise do nothing. (This is "conditional move," or "cmov".)
* `gxy` — If *flag* = G, then set the value in register *x* equal to the value in register *y*; otherwise do nothing. (This is "conditional move," or "cmov".)
For example, the program `mca <ba lcb` means "Set register *c* equal to the minimum of *a* and *b*."
The program `mty <zy lyz lzt` means "Stably sort the values in registers *y* and *z*." That is, it sets *y* to the minimum of *y* and *z* (breaking ties in favor of *y*) and sets *z* to the maximum of *y* and *z* (breaking ties in favor of *z*).
The following 16-instruction program stably sorts the values in registers *x, y, z*:
```
<zy mtz lzy lyt
max mby mcz
<yx lay lbx
<zx lcx lbz
mxa myb mzc
```
**Your task is to find the shortest program that stably sorts *four* registers *w, x, y, z*.**
A trivial Python implementation is available [here](https://godbolt.org/z/1xbqjPq9b) if you want to test your solution before (or after) posting it.
[Answer]
# 21 instr
```
'<wx', 'gtw', 'gwx', 'gxt',
'<xy', 'guy', 'gyx', 'gxu',
'<yz', 'gtz', 'gzy', 'gyt',
'<wx', 'gxw', 'gwu',
'<xy', 'gyx', 'gxt',
'<wx', 'gxw', 'gwt'
```
[Try it online!](https://tio.run/##lVRNc5swEL3zKzbpASmhSdz25Il7q2c605nk0BvDgZg1lgsSlUSM0@lvdxcJY4eS2uWiYXff27cfUrW1KyU/7t5d3NZG3z4JeYvyGSpnDgJRVkpbEBa1VaowQZDhErDBRW3xUatcpyWr/BmBsalFPg0AlkqDACGh87U2ALEEEd8lMJtBeB96G3hUTAZyQPgSdmYK9h4RT5Kkhd33hg/OMB1Ai7ehn09Acw/F4lhiOZDo2Cj6iGoEVfSoXobP4n3/xZX/gys/waXR1lrCd12jn9ozarHcdkN7kF9lVdvD7ET7G9FoK1xYzNwUHSER//p9PFKdyhxZgZI5DOdeo8@@WGmmdMZojhzewyEKrgl9DRPeKnWmWLQyqTCp7KmV2lczTwuDZ4ghVna@oItZXzeJ4vueD3L@1dAc7aMyRjwV6JppHpbfUOZ2xaTjqDrnlwJLlNa0i5Y@LQiar8T6R1FKVf3UxtbPm2b7EsZTmRyhPGXbrP3lu6GuZPXCsisWD7kTuALJ@Rg@FkfX8bWT2jQkuqG2aWs2gsoIw5u1EpIZegMwYwYtE5y@UZlxjNROYzUzdckmLuc6aw5DuqMlyxruXwHyuDVGzr26rImwjUVZl6hpcpQqeUu4E6CFtOxyPwG/UwZSjVO4jAYAfpjfa8fI1Tgsnzy8ZW1wq@PUzPuFPuu2dY19tbp9ZfNUFJiBkm05o4Az97TLOld6rmrtZTOXrQuNd0AP8qYJI3pW7MYd3V9jwyhovc3W/df@2HbeuvPS@jqsP166oD3WcXUfgboE9TFz790O8o5jbbgjbxIEqTF0O8YHOCg4gk989wc "Python 3 – Try It Online")
---
Neil suggests that reordering into this may get more clear:
```
<wx gtw gwx gxt
<xy gty gyx gxt
<wx gxw gwt
<yz gtz gzy gyt
<xy gyx gxt
<wx gxw gwt
```
This looks more like insertion sort
---
---
For large enough amount of element, a \$\tilde {\mathrm O} \left(n\right)\$ sorting algorithm exist. Here I construct a \$\mathrm O \left(n \log^2 n\right)\$ one using a \$\mathrm O \left(n \log n\right)\$ [sorting network](https://en.wikipedia.org/wiki/Sorting_network), which seems reducible: (say the input is `A[0..n-1]`
1. Set `O` to `min(A)` and `I` to `max(A)`.
Notice that if `O = I`, then all elements are equal, and no swap would apply.
2. Let `B[i][j] = i & (1 << j) ? I : O` for `0 <= j < log2(n)`.
3. Do sorting network on `A`, each element `A[i]` together with `B[i]`.
To do a multi-element compare:
```
T = O
if (P[0] < Q[0]) T = I
if (P[1] > Q[1]) T = O
if (P[1] < Q[1]) T = I
if (P[2] > Q[2]) T = O
if (P[2] < Q[2]) T = I
...
if (P[9] > Q[9]) T = O
if (P[9] < Q[9]) T = I
if (T > O) swap
```
This makes a swap in \$\mathrm O \left( \log n\right)\$
[Answer]
## ~~23~~ 22 instructions
Here's a different approach from l4m2's bubble sort — we can use insertion sort. We start by sorting *x, y, z*. Then we insert *w* in its proper place by starting at the top and working downward: If *w > z*, insert it and bump out the old *z* into *q*. If *w > y*, insert *q* and bump out the old *y* into *q*. And so on.
An "unoptimized" sequence of instructions that works for that second part is:
```
mpw mtx muy mvz
<vp mqp lqv lvp
mau <up luq lqa
<tp lpt ltq
mwp mxt myu mzv
```
I can optimize that and append it to ~~l4m2's 12~~ Neil's 11-instruction `sort3` to produce this ~~23~~ 22-instruction `sort4`:
```
<zy lty lyz lzt
<yx ltx lxy lyt
<zy lyz lzt
mqw <zw lqz lzw
<yw lty lyq lqt
<xw lwx lxq
```
But I don't see how to shrink it further than that.
And it still uses 6 `<` instructions. Is it conceivably possible to use only 5? Here's a 20-instruction `sort4` (based on [this sorting network](https://commons.wikimedia.org/wiki/File:SimpleSortingNetwork2.svg)) that uses only 5 comparisons but is *not stable*, so it doesn't fulfill the challenge:
```
<wy gtw gwy gyt
<xz gtx gxz gzt
<wx gtw gwx gxt
<yz gty gyz gzt
<xy gtx gxy gyt
```
I'm also (finally) realizing that I should have given not only `cmovl` and `cmovg` but also `cmovle` and `cmovge` as primitives; I wonder if that would have helped at all.
[Answer]
## 32 instructions
Here's yet another approach: mergesort. This successfully minimizes the number of `<` operations to 5, but we pay for it with a lot more cmovs. We start by sorting the sublists {*w*, *x*} and {*y*, *z*}; then we merge those two lists. But "merge the two lists" is harder than it sounds. I wrote out the complete game tree; e.g. "First compare *w* ≤ *y*. If true, the next step will be to compare *x* ≤ *y*; otherwise, the next step will be to compare *w* ≤ *z*" and so on. Then rewrite as "If *w* ≤ *y*, set *i,j* ← *x,y*; otherwise, set *i,j* ← *w,z*. The next step is to compare *i* ≤ *j*" and so on. That gives an unoptimized program [like this](https://godbolt.org/z/e48v1h55e):
```
<wx gtw gwx gxt
<yz gty gyz gzt
maw mbx mcy mdz
<ac
mwa mib mjc m1c m2d m3c m4d m5b m6d m7d m8b
gwc gia gjd g1b g2d g3d g4b g5a g6b g7a g8b
<ij
mxi
gxj g15 g26 g37 g48
<bd
my1 mz2
gy3 gz4
```
My best-optimized version takes 32 instructions:
```
<wx gtw gwx gxt
<yz gty gyz gzt
m3y m4z m5x m6z m7z m8x
<wy g48 g5w g6x g7w gwy gx5 gy8 g3z
<x3 gx3 gy5 gz6 g37 g48
<8z gy3 gz4
```
] |
[Question]
[
## Background
So, nowadays the popular Prisoner's Dilemma variant is the Prisoner's Trilemma, where there are three options. I can easily see that being increased, so I figured
>
> Why settle for *three* options, when we can have ***INFINITE*** options?
>
>
>
Therefore, I created the Floating Point Prisoner's ?Lemma.
## Equations:
Each round, your score will be calculated as (\$a\$ is what Player 1 returns, \$b\$ is what Player 2 returns):
$$
\text{Player 1 expected score: }\quad 2ab+3(1-a)b+(1-a)(1-b)
$$
$$
\text{Player 2 expected score: }\quad 2ab+3a(1-b)+(1-a)(1-b)
$$
\$3\$ is the temptation payoff, the payoff \$a\$ gets if \$a\$ defects and \$b\$ cooperates. \$2\$ is the reward, for if both cooperate. \$1\$ is the punishment, for if both defect. The sucker's payoff is \$0\$, which is what \$a\$ gets when \$a\$ cooperates and \$b\$ defects.
### Explanation of what floating point numbers mean in output
Basically, an output of 0.5 means that the figurative probability (The controller is almost deterministic, only matching up contestants at random) of cooperation is 0.5. This means that since the output is closer to 1 than 0 is, the opponent gets some score, but not as much as if the output of the contestant we're focusing on was 1.
## Forbidden Stuff
* Standard Loopholes are forbidden.
* No interacting with the controller other then by returning values in the strategy function.
* No interference with other bots (with global variables, other stuff)
* Global Vars are Highly Discouraged. Instead, use the store dict.
* More stuff may be added
## Generic Stuff
It uses an equation from the wonderful fellows at <https://math.stackexchange.com> to determine what to do, with the floating point numbers correlating to probability of coop or defect. However, the controller is deterministic in terms of the scoring stuff, and the probabilities are not treated as probabilities. The equations are in the play function in the controller.
**NOTE:** When run, it'll sometimes print something like [[0, 28948.234], [1, 32083.23849], [2, 0]]. That's just an old debugging feature I forgot to remove.
## Technical Stuff
Create a bot that can play this Python implementation of the Prisoner's ?Lemma. Make two functions, `strategy` and `plan`, that are in a similar format as the below examples. Store is cleared after every matchup, you can change this by commenting out the line in run in the controller that says
```
self.store = {
}
```
This is a basic bot template:
```
def strategy(is_new_game, store):
# Put Stuff Here™. is_new_game tells the function if it's a new game. returns a value between 0 and 1, where 1 = coop and 0 = defect, and in-between stuff correlates to probability of coop or defect. Store is a dict for storage.
def plan(opmove, store):
# opmove is the opponents move last round. This function shouldn't return anything. Put pass here if you don't use this.
```
### Example Bots
♫Coop Bop Bot♫
```
#Example Contestant
def strategy(is_new_game):
return 1
def plan(opmove):
pass
```
Random
```
#Example Contestant
import random
def strategy(is_new_game):
return random.random()
def plan(opmove):
pass
```
Controller is at <https://github.com/4D4850/KotH-Floating-Dilemma>
Feel free to make a pull request.
# Leaderboard
```
Random, 165500.78318694307
Helped, 147835.72861717656
Cooperator, 125285.07526747975
Random Alternator, 82809.27322624522
Tit for Tat, 51139.558474789665
```
If you don't see your bot, there was an error.
Note: Helped and Random Alternator needed to be slightly modified to run without errors. Also, there was a catastrophic bug in the scoring system, that is now fixed.
[Answer]
# Helped
```
def strategy(is_new_game, store):
if store and store['moves']:
return store['moves'][-1]
return .1
def plan(opmove, store):
if opmove > .5:
if store and store['moves']:
store['moves'].append(opmove / 2)
else:
store['moves'] = [opmove / 2]
else:
if store and store['moves']:
store['moves'].append(opmove * 2)
else:
store['moves'] = [opmove * 2]
```
[Try it online!](https://tio.run/##pZHRCoIwFIbv9xTnTo2yLIII7Cm6E5GBRxN0G9ssJHr25VwpSBDR3c5/vp1vnIlOXzjbHYQ0JscClJZUY9n5lcoY3rKSNrjsUy4xOBKAqnAFUJa7U@I1/IrKS20bQKJuJZu1klWUkrEXRsSqRE2Zz4VFZgYXwgnCvRv61QqzNKRCIMtf42EN22DgsFb4@QbEkEy0fe3E/qtf/KTv6dQ4Xwz3BxGyYtofP@Ys23FfARmWuAn372SkbWGe)
`Helped` is a bot that depends on the opponent's previous moves. Picks higher next moves for lower previous moves, and lower ones for higher ones.
[Answer]
# Random Alternator
```
store[0] = 0
store[1] = 0
print(store)
import random
def strategy(is_new_game, store):
if is_new_game or store[0]%100 < 10:
store[1] += 1
return random.random()
else:
store.append(store[1] + 1, (sum(store)/len(store)))
store[1] += 1
return sum(list(store)[1:])/len(list(store)[1:])
def plan(opmove, store):
store.append(store[1] + 1, opmove)
store[1] += 1
store[0] += random.random() + random.random()
return store
```
Randomly alternates between taking the total average of the moves and random moves in a random way (Hopefully, unexploitable).
[Answer]
# Tit for Tat
```
def strategy(is_new_game, store):
if is_new_game: return 1
return store[0]
def plan(opmove, store):
store[0]=opmove
```
[Answer]
# Defector
```
def strategy(n, s):
return 0
def plan(o, s):
pass
```
Always defects (returns 0).
[Answer]
# Uppercut
```
def strategy(is_new_game,*a):
return -1000000
def plan(opmove,*a):
pass
```
Returns a negative number with high magnitude to get lots of points. This wasn’t disallowed in the challenge rules.
[Answer]
# Falling Uppercut
```
def strategy(is_new_game, store):
if is_new_game:
return -(1000000**2)
return -(1000000**store["e"])
def plan(opmove, store):
if "e" in store:
store["e"] += 1
else:
store["e"] = 3
```
Modified version of Uppercut to counter bots like Helped, Random Alternator and Tit for Tat.
## Edit
This has been edited to counter the original Uppercut.
] |
[Question]
[
### Background
In [JIS X 0208](https://en.wikipedia.org/wiki/JIS_X_0208) a 94 by 94 map (kuten (区点)) is defined to encode Chinese characters (kanji), phonetic moras (kana) and other symbols. Along with this standard there are 3 different encodings that maintain 1-1 correspondences with the map, namely JIS, Shift\_JIS and EUC. These encodings take 2 bytes for each character in the kuten map. The mappings are different that random characters may occur ([mojibake](https://en.wikipedia.org/wiki/Mojibake)) if the wrong encoding is used.
### Conversion Algorithm
In the formulae below, kuten is an ordered pair of numbers \$(区,点)\$ where \$1\le 区,点\le94\$, and \$(a,b)\$ is an ordered pair of bytes where \$0\le a,b\le 255\$. The conversions between kuten and the 3 encodings are as follows:
$$\text{JIS}: (a,b)=(32+区,32+点)$$
$$\text{Shift\_JIS}: (a,b)=\begin{cases}
\left(128+\left\lceil\frac{区}{2}\right\rceil+64\left\lfloor\frac{区}{63}\right\rfloor,63+点+\left\lfloor\frac{点}{64}\right\rfloor\right)&\text{if }区\text{ is odd}\\
\left(128+\left\lceil\frac{区}{2}\right\rceil+64\left\lfloor\frac{区}{63}\right\rfloor,158+点\right)&\text{if }区\text{ is even}
\end{cases}$$
$$\text{EUC}: (a,b)=(160+区,160+点)$$
### Challenge
Write a program or function that, given a byte pair, the source encoding and the destination encoding, converts the byte pair from the source encoding to the destination encoding and outputs the result. You may assume that the input byte pair represents a valid codepoint in the source encoding.
The input and output formats are flexible and are accepted if reasonable. For example, you may receive or output the byte pair as a list, as two numbers or as a number, either in decimal or hexadecimal; you may also assign a number to each of the possible encodings and use them as the input format of the encodings.
### Sample IO
The format used in the samples is `SrcCodePoint, SrcEncoding, DstEncoding -> DstCodePoint`. Decimal is used here but hexadecimal is also acceptable. The Unicode character and its assigned kuten are for explanation.
```
(227, 129), Shift_JIS, EUC -> (229, 225) (Kuten: 69-65; U+7E3A 縺)
(101, 98), JIS, Shift_JIS -> (227, 130) (Kuten: 69-66; U+7E67 繧)
(229, 227), EUC, JIS -> (101, 99) (Kuten: 69-67; U+7E5D 繝)
(137, 126), Shift_JIS, JIS -> (49, 95) (Kuten: 17-63; U+5186 円)
(177, 224), EUC, Shift_JIS -> (137, 128) (Kuten: 17-64; U+5712 園)
(49, 97), JIS, EUC -> (177, 225) (Kuten: 17-65; U+5830 堰)
```
See [here (in Japanese)](http://charset.7jp.net/jis0208.html) for the full table.
### Winning condition
This is a code-golf challenge, so the shortest valid submission for each language wins. Standard loopholes are forbidden by default.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~140~~ 116 bytes
Takes code point as an array, and encodings are `JIS`, `Shift_JIS`, and `EUC-JP`, respectively.
Ruby supports converting between EUC-JP and SHIFT\_JIS, so we math JIS encoding into EUC, perform the appropriate conversion, then math back the JIS encoding if that's the destination encoding.
-34 bytes by getting permission to take EUC input as EUC-JP.
```
->c,s,d{(c.map!{|e|e+=128};s="EUCJP")if s=~r=/^J/
c.pack('c*').encode(d[r]?"EUCJP":d,s).bytes.map{|e|e-=d[r]?128:0}}
```
[Try it online!](https://tio.run/##TY7RTsIwFIbv@xRHYmTDrdBKHJupXhgv2BUJ4QpxgbaTRoRlrTEE5qvPdjO43vU/3/n@U35tjnXOXuvwkQc6ECeP4891cXU6y7O8ZYROqgfNei@L53TW81UOmv2UbPiWDhHHxZp/eH0@6PtY7vlBSE8sy9XTH52IQPt4czRSO2VjDFlDWG0yqqr6e6t2Et6l0QhgwAPQAQhgcJ1hXeyUsWl7Dtwk5pAp@y8gXzaXrpDci5rSCAiNYb5VucnS6RxseZjOEBkRgHgCLmrfBUHULrjFFnUzl5I7p7rvqJo0iiw77rD/HhjHtiPqdLTULw "Ruby – Try It Online")
**Explanation**
```
->c,s,d{ # Function that takes 3 parameters
( )if s=~r=/^J/ # If s is JIS: (starts with J)
# (also store this regex for later)
c.map!{|e|e+=128}; # Add 128 to each codepoint
s="EUCJP" # Change s to EUC-JP locale
c.pack('c*') # Pack codepoints into bytestring
.encode( # Encode the bytestring as follows:
# Destination encoding is:
d[r]?"EUCJP":d, # If d is JIS, use EUC-JP instead
s # Source encoding
)
.bytes # Convert to bytes
.map{|e|e-=d[r]?128:0} # If d is JIS, subtract 128
}
```
### Pure Math Version, ~~164~~ 162 bytes
Takes code points separately, and the encodings are integers: `0=JIS, 1=SHIFT_JIS, 2=EUC`.
-2 bytes from Jonathan Allen.
```
->a,b,s,d,e=160{k,t=[[a-32,b-32],[a*2-1+b/158-(2+a/222)*128,b-63-b/128-b/158*94],[a-e,b-e]][s]
[[k+32,t+32],[128+k/2+k%2+k/63*64,158+t+t/64-k%2*95],[k+e,t+e]][d]}
```
[Try it online!](https://tio.run/##NYwxbsMwEAR7vyJNAId3BHUrmhIL5SMMCwmWGzZGrBSG4bfLR1kpeAB3Z/b3b7qvl@Fntd8jT3zjM8@DhOZReBlSGm0LnvRkTqOBFZqcnHp7BI0OwJcR9AqE1mqB3m61ib7ydtZmzjnd8iGlQjq10DalJBUHKp/6XGhN8KweLbS44K3GJp6UKzSrUifO@blePy4J6FgQWRj5UANphGPPDcv7Dy0rBG52oK1GUOM/6LSFV2JXfOTY6QLy@gI "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~37~~ 34 bytes
```
93ÝãDžy+∞x64&+₃+Ƶ₁L64K30+â)33+Iè`‡
```
[Try it online!](https://tio.run/##AUwAs/9vc2FiaWX//zkzw53Do0TFvnkr4oieeDY0JivigoMrxrXigoFMNjRLMzArw6IpMzMrScOoYOKAof//WzAsIDJdCltbMTAxLCA5OF1d "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfmRAa9t/S@PDcw4tdju6r1H7UMa/CzERN@1FTs/axrY@aGn3MTLyNDbQPL9I0NtaOOLwisjjhUcPC/zr/o4HAyMhcR8HQyDI2Vkch2gjIBDOiow0NDHUULC3APAMdBSOosJGRJZBjZA7mAlUYwJQbg40xgxkDFzc3B6k3gamHmWMCNMbSHGY60NJYAA).
First input is `[source encoding, destination encoding]`, with 0 representing JIS, 1 for EUC, and 2 for ShiftJIS.
Second input it `[byte pair]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 62 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Tired & ill so probably very beatable!*
```
⁹:64;95⁸ị+63+
‘&64+HƲḞ+Ø⁷,ç
94,þ`“¡ ɦ‘+€ç/€€€1¦
Ḣị¢⁼€€ŒṪṪ⁸;œị¢
```
A dyadic Link accepting `[SrcEncoding, DstEncoding]` on the left and `SrcCodePoint` on the right which yields `DstCodePoint`.
Where `SrcEncoding` and `DstEncoding` are:
```
Shift_JIS 1
JIS 2
EUC 3
```
**[Try it online!](https://tio.run/##y0rNyan8//9R404rMxNrS9NHjTse7u7WNjPW5nrUMEPNzETb49imhzvmaR@e8ahxu87h5VyWJjqH9yU8aphzaKHCyWVARdqPmtYcXq4PJCHI8NAyroc7FgGNObToUeMeiODRSQ93rgIioPnWRyeD5f7//x9tqKNgHPs/2sjIXEfB0MgyFgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##NY0xCsIwFIb3niKTSyLaNLZGQXTzChIKLi7iBdxaVzddOqiggwVxcrGiODRU8BjNReJLG@GRPP7/43vz2WKx1FrFj57P@ryj4qx8rrHvYUdFScNnePy5ldkBy0TFdyJThzMi31MV7fIj@p4Bwmp1lWkL3nrc/OyU2Qk0@UnFrzosNuXjAgP@frGtOj0qXjIdtmyb1ODcfNEONQdIRfuJ1kIISgOCXMpDgoRLkBeGDhHCbcPOuyakUNchpZwg4E3qwWZRrxL4VvBPg8CwzLLWwEDAA2s1p8If "Jelly – Try It Online").
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 172 bytes
```
(a,b,x,y)=>eval('for(c=d=t=0;c-a|b-d;[c,d]=x(p,q))y(p=++t>>8,q=t&255)')
S=(k,t)=>[128+k/2+k%2/2+64*(k>62),(k%2?63+(t>63):158)+t]
J=(k,t)=>[32+k,32+t]
E=(k,t)=>[160+k,160+t]
```
[Try it online!](https://tio.run/##bY6xboMwFEV3vsJLm/fqRwsGDBSZTixZM0YMxEDVggJJrCiR@u/UMLSqynKHe9859md1rS76/DEa9zjUzdSqCSo60I3uqPLmWvWwaYczaFUro7xMu9XXwa2zvaa6VDcY6YR4h1FxbvI8oZMyjyKKcIPOTkFHxlr2vkh49yJ49yBsyvAJulwKJLDFmww4mFwG@OpHCXJTOtsfMLAM2bBl8WuTnm3nNOWkh@Nl6JvnfniHFoSIifkiJbYjViBmzt/d93xiaUJsay/@z2ImF0dhT1bwYNHLRb@2x/HMhwu/4g@tPo2X1@fPTd8 "JavaScript (Node.js) – Try It Online")
Invoke as `f(227, 129, S, E)` where `S=Shift_JIS, E=EUC, J=JIS`.
[Answer]
# [Clojure](https://clojure.org/), ~~51~~ 50 bytes
```
#(for[b(.getBytes(String. %2%)%3)](bit-and b 255))
```
[Try it online!](https://tio.run/##bdLNTsJAEAfwe59iUkOyG1vS3bLdVhITPziIFxPCqWkMhRZrSMF2OfACPIBnTbx59ai@T8Nj4O4WxBLvO7//zM6MZ/PHZZFs0SRJId2eoHRehDFqTxNxuRJJiQaiyPJpG1q0hVsujlCcCXuUTyAGyhjGW2zoWvlWlBAaoTl4yFJx378ZmBaElHILCA0iC8ze8Mru35lRF@xzQJQGFlDKMKDbpUjyM/AC22NdGJ7ynnsBm89vLDXpONTxlUUcYkHgK@qQ8aupHNdpal6teRw2X@9K27WgG9PxXGn7DGmB1uqkAEND47XGrqX2io8nJa6e1GuCSuvIpEDOedAItz1XaYz4HlTrdbM3wrnqrfPvpLscHze0jtY4oVC9PB/9m87n0d8FwH7QOok1Mb0E5rsOVG8f2IjUiudl8gRhWBZjyPLFUsCkFFG99QgMOdpC3omY5YBSUI9QLM/HHhXFaFUXYFWB5cH8AA "Clojure – Try It Online")
Anonymous function taking three arguments: source encoding, input pair as a Java byte array, and destination encoding.
This relies on JVM's built-in conversion functionality. As other answers are doing, I took the liberty to modify the expected encoding strings to match the format recognized by the JVM:
* JIS -> JIS0208 (Simply "JIS" is also listed in Java docs, but somehow doesn't work)
* Shift\_JIS remains as is
* EUC -> EUC-JP
[Answer]
# [Haskell](https://www.haskell.org/), ~~185~~ ~~179~~ 153 bytes
```
x?(a,b)=[(a+32,b+32),(128+div a 2+rem a 2+64*div a 63,b+63+[95,div b 64]!!rem a 2),(a+160,b+160)]!!x
(x!y)i=y?head[(a,b)|a<-[1..],b<-[1..255],i==x?(a,b)]
```
[Try it online!](https://tio.run/##TVDNaoQwEL77FCP0kNTZxUSNCk33MXqwHiIrGHYV2Uqr0ne3E5W6OUzCl@8vaczXrb7fl2W8MIMV1wUzQSSxosGRCZkFV/sNBmTwqNt1V/HrBqmIaCoKijxBh1Sg4tL3dx6pTSBUSByanC5Gj43@xK2eLk1trsUa@GveToU4n0ustoNMkhKt1nuhcmmN7XT/sN0ALzDb/sMODdOa/5gVaU0P7JONOOHMT@9rBMwcbNcPnhv0JIESmZQpgpA55x64hSxEQU8MBQLk2QFLDB07RyDJAQsHi2g1Uc9sZ5Kmjh0/e1MkxLnzJpPSc3Wpyu6bHPq1VhQeOVuh/B/YXQ7JXiI7gC0@od/6Aw "Haskell – Try It Online")
Takes Encodings as 0=JIS, 1=Shift\_JIS, 2=EUC. Probably still a lot of room for improvement.
] |
[Question]
[
What general tips do you have for golfing in [Smalltalk](http://smalltalk.gnu.org/)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to [Smalltalk](http://smalltalk.org/) (e.g. "remove comments" is not an answer).
>
> Smalltalk is a purely object-oriented language created by Alan Kay. The two links are GNU Smalltalk and a general Smalltalk page respectively. You do not have to pay attention on this "spoiler".
>
>
>
[Answer]
## Use the `;` operator to refer to the previous object
There is a convenient shorthand in Smalltalk used to refer to the previous object. Say we want to add 3 items to the set x.
```
x:=Set new
x add:5.x add:7.x add:'foo'
```
However, we can save a few bytes by using the ; operator:
```
x:=Set new
x add:5;add:7;add:'foo'
```
] |
[Question]
[
This is my first attempt at a Code Golf question. If it needs obvious edits, please feel free to make them.
Below is a description of the basic Dropsort algorithm.
>
> [Dropsort](http://www.dangermouse.net/esoteric/dropsort.html) is run on a list of numbers by examining the numbers in sequence, beginning with the second number in the list. If the number being examined is less than the number before it, drop it from the list. Otherwise, it is in sorted order, so keep it. Then move to the next number.
>
>
> After a single pass of this algorithm, the list will only contain numbers that are at least as large as the previous number in the list. In other words, the list will be sorted!
>
>
>
For example, given a list of numbers `1,65,40,155,120,122`, the `40,120,122` numbers will be dropped, leaving `1,65,155` in the sorted list.
**Let's implement a new sorting algorithm called DropSortTwist.**
This sort is identical to Dropsort except that a number (including the first number) that would be kept in Dropsort may optionally be dropped instead. DropSortTwist must return (one of) the longest possible sorted list.
For example, using the same list of numbers as above, DropSortTwist must return either `1,65,120,122` or `1,40,120,122`. In both cases the `155` number is dropped to achieve a sorted list of length 4, one greater than the Dropsort list.
In this task, you will be given a list of integers as input (STDIN or function argument, you are required to support at least the range of 8-bit signed integers.) You must return the longest possible increasing subsequence.
You may assume that the list is non-empty.
This is code golf, so the shortest program wins.
**Test Cases**
```
input output
1 65 40 155 120 122 1 65 120 122 [or] 1 40 120 122
5 1 2 2 3 4 1 2 2 3 4
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPṢƑƇṪ
```
**[Try it online!](https://tio.run/##y0rNyan8///opICHOxcdm3is/eHOVf///4821FEwM9VRMDHQUTA0BTIMjUAsI6NYAA "Jelly – Try It Online")**
### How?
Pretty much the same approach as [Grimy's 05AB1E entry](https://codegolf.stackexchange.com/a/189601/53748)
```
ŒPṢƑƇṪ - Link: list of integers
ŒP - power-set (all subsequences, from shortest to longest)
Ƈ - filter keep those which are:
Ƒ - invariant when:
Ṣ - sorted
Ṫ - tail
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
æʒD{Q}éθ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8LJTk1yqA2sPrzy34///aEMdBTNTHQUTAx0FQ1Mgw9AIxDIyigUA)
```
æ # list of subsequences
ʒD{Q} # filter, keep only the sorted subsequences
é # sort by length
θ # get the last (longest) one
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 9 bytes
```
à ñÊf_eZñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4CDxymZfZVrx&input=WzEgNjUgNDAgMTU1IDEyMCAxMjJd)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éÑ<┬Θ╡Lφ0
```
[Run and debug it](https://staxlang.xyz/#p=82a53cc2e9b54ced30&i=[1+65+40+155+120+122]%0A[5+1+2+2+3+4]&a=1&m=2)
Naive approach: powerset, filter for sorted, sort on length, get tail.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 63 bytes
```
->a{s=a.size;s-=1until r=a.combination(s).find{|e|e==e.sort};r}
```
[Try it online!](https://tio.run/##RYqxCsMgFAD3fsUbIxiptukSXn6kZDCpgmC1@MzQJvl2a7oUbjiOS8v0LhZLO@iVUAtyH9NTi3IJ2XlINc3xObmgs4uhISasC491M5tBNIJiynuf9vICK2btfXOXHG4dh@uZg@yqSHWYUiM7/aejc1A/LnUeWfkC "Ruby – Try It Online")
```
->a{ # Anonymous Proc taking array input
s=a.size; # Get array size
until # Loop until the following condition is non-nil:
r=a.combination(s) # Get all subsequences with length s
.find{|e|e==e.sort} # Find a subsequence that is sorted, else nil
s-=1 # Reduce s by 1
r # Implicit return the found subsequence
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
```
Select[Reverse@Subsets@#,OrderedQ,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JDootSy1qDjVIbg0qTi1pNhBWce/KCW1KDUlUMcwVu1/QFFmXkm0sq5dmoNyrJq@QzVXtaGOgpmpjoKJgY6CoSmQYWgEYhkZ1epwVYO4OgpGYGQMVAMSq@Wq/Q8A "Wolfram Language (Mathematica) – Try It Online")
The elements of `Subsets[ ]` are ordered from shortest to longest, so reversing it puts longer subsets first. Then, select the first one which is ordered.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~89~~ 83 bytes
```
f=lambda A:A>sorted(A)and max([f(A[:i]+A[i+1:])for i in range(len(A))],key=len)or A
```
[Try it online!](https://tio.run/##VYqxDsIgFEV3v@KNkL5BqHVoUpP3HYQBAyixhQYZ7NcjdTCa3OHec8@6lXuKslY/zWa5WgM00uWZcnGWETfRwmJeTHlGagy6IxU6MWruU4YAIUI28ebY7GKzucaH26Y2eLuprjnEAp4pgXAeEE5HBDG0IuTepNT88HV2jCA/6Zv7@wmU2OMf0ry@AQ "Python 2 – Try It Online")
] |
[Question]
[
There are 9 main types of numbers, if you categorise them by the properties of their factors. Many numbers fall into at least one of these categories, but a few don't. The categories are as follows:
* Prime - no integer divisors other than itself and one
* Primitive abundant - A number \$n\$ whose factors (excluding \$n\$) sum to more than \$n\$, **but** for any factor \$f\$ of \$n\$, the sum of the factors of \$f\$ sum to *less than* \$f\$
* Highly abundant - A number \$n\$ whose factors (*including* \$n\$) sum to more than that of any previous number
* Superabundant - A number \$n\$, such that the sum of the factors of \$n\$ (including \$n\$) divided by \$n\$ is greater than the sum of factors of \$g\$ over \$g\$ for any value \$0<g<n\$
* Highly composite - A number \$n\$ which has more factors than \$g\$, where \$g\$ is any number such that \$0<g<n\$
* Largely composite - same as highly composite, but \$n\$ can have also have *equally as many* factors as \$g\$
* Perfect - A number that is exactly equal to the sum of its factors (excluding itself)
* Semiperfect - A number that can be made by summing up two or more of its factors (excluding itself)
* Weird - A number \$n\$ that is not semiperfect, but which's divisors sum to more than \$n\$.
A so-called 'boring number' is any positive, non-zero integer which does not fit into any of these categories.
Your job is to create the shortest possible program which can, given a positive number \$n\$, outputs the \$n\$th boring number.
*Note: I am aware there are more categories, but I wanted to avoid using mutually exclusive ones (such as deficient and abundant), because then every number would fall into one of them.*
# Rules
* Standard loopholes apply; standard I/O methods apply.
* All inputs will be positive, non-zero integers, a single output is expected.
* `n` can be 0- or 1- indexed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
# Tests
The first 20 boring number are:
`9, 14, 15, 21, 22, 25, 26, 27, 32, 33, 34, 35, 38, 39, 44, 45, 46, 49, 50`
[Answer]
# JavaScript (ES6), ~~226 220~~ 209 bytes
*Saved 11 bytes thanks to @HermanL*
Input is 1-indexed.
```
f=(x,n=m=c=1,D=k=>k?n%k?D(k-1):[k,...D(k-1)]:[],S=a=>s=eval(a.join`+`))=>(S(a=D(n))>m?m=s:0)|(s=a.length)<3|(s<c?0:c=s)|a.reduce((a,x,i)=>i?[...a,...a.map(y=>[...y,x])]:a,[[]]).some(a=>S(a)>=n)||--x?f(x,n+1):n
```
[Try it online!](https://tio.run/##JY/RioMwEEV/xYcuzGAMyrIvrpO8@Ad9FMEhjV2rJsV0i6X2292UhYHLHYZ77lz4zsEsw/WWOX@ye09xYBWOZjJUiJpGUqN2H6OuYcwKLJtRSCn/TVs2rTgSkwpk7zwBy4sfXJd2iKTgCEw1OEQ165lCmeMGgVhO1p1vP1h9RlsZnZeGAm4sF3v6NRaAxSqGGDDoJqL4zWM58xUepN6bh1jbyGbRNG2LMvjZRpKKOFTkcNuybNX9@4s0FnZ77xdwCSXFd@KSKvnKo6YpJsa74CcrJ3@GjuHwdC@MZ4dnH0u/Otz/AA "JavaScript (Node.js) – Try It Online")
Optimizations are based on the following properties:
* All primitive abundant numbers are either semiperfect or weird.
* All highly composite numbers are largely composite.
* All superabundant numbers are highly abundant.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ ~~39~~ ~~36~~ ~~33~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒpyLRÑOć‹PyѨ©æOyå®Oy›O_}Iè
```
-4 bytes thanks to *@Mr.Xcoder*.
-12 bytes thanks to *@Grimy* (of which -5 are because ["*Highly composite numbers higher than 6 are also abundant numbers*"](https://en.wikipedia.org/wiki/Highly_composite_number#Related_sequences), and -4 because "*'The sum of N's divisors is greater than N' is equivalent to 'The sum of some subset of N's divisors is greater than N'*").
0-indexed.
[Try it online](https://tio.run/##AS8A0P9vc2FiaWX//@KInsqScHlMUsORT8SH4oC5UHnDkcKow6ZPeUDDoE9ffUnDqP//OQ) or [output the first \$n\$ values of the sequence](https://tio.run/##ATAAz/9vc2FiaWX//@KInsqScHlMUsORT8SH4oC5UHnDkcKow6ZPeUDDoE9ffUnCo///MjU).
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
ʒ # Filter it by, leaving only the integers `y` which are truthy for:
p # 1) Check if `y` is a prime
yL # Create a list in the range [1, `y`]
R # Reverse the list to range [`y`, 1]
Ñ # Get the divisors of each integer
O # Sum the inner lists together
ć # Extract the head; pop and push remainder-list and head
‹P # 2) Check if each value in the remainder-list is smaller than the head
yÑ # Get the divisors of `y`
¨ # Remove the last item (`y` itself)
æ # Powerset; get all possible combinations of these divisors
# (this includes both an empty list and all divisors of `y`)
O # Sum each inner combination-list
y@à # 3) Check if any sum is larger than or equal to `y`
O_ # And only leave the integers in the filter which are falsey for all checks
}Iè # After the filter: Index the input-integer into the filtered list
```
1) covers the check for Prime
2) covers the checks for Highly Abundant, Superabundant, Largely composite and Highly composite
3) covers the checks for Perfect, Semiperfect, Weird, and Primitive Abundant
[Answer]
# Java, 208 bytes
Input is 1-indexed.
```
interface a{static void main(String[]a){int i=0,n=0,x=1,z=1,j,u,f,b;for(;n<new Integer(a[0]);n+=f>=i?0:1/++b){for(i+=j=u=f=b=1;++j<i;)if(i%j<1){f+=j;b=0;u++;}x=f>x--?b=f:x;z=u>=z?b=u:z;}System.out.print(i);}}
```
in readable form:
```
interface a
{
static void main(String[]a)
{
int i=0,n=0,x=0,z=0,j,u,f,b;
for(;n<new Integer(a[0]);n+=f>=i?0:1/++b) //checks perfect, semiperfect, weird, and p. abundant numbers
{
for(i+=j=u=f=b=1;++j<i;)if(i%j<1){f+=j;b=0;u++;} //checks prime numbers
x=f>x--?b=f:x; //checks highly abundant and superabundant numbers
z=u>=z?b=u:z; //checks largely and highly composite numbers
}
System.out.print(i);
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
Æd,Æs)Ṫ_$<Ø.S;Æṣ<$;Ẓ¬$Ạµ#}1Ṫ
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//w4ZkLMOGcynhuapfJDzDmC5TO8OG4bmjPCQ74bqSwqwk4bqgwrUjfTHhuar///8yMA "Jelly – Try It Online")
A full program taking a single argument N and outputting the 1-indexed boring number.
Takes advantages of the optimisations noted in the description of @Arnauld’s answer, but not based on the JavaScript code.
### Explanation
```
Æd,Æs)Ṫ_$<Ø.S;Æṣ<$;Ẓ¬$Ạµ#}1Ṫ
µ#}1 | Run the following for each number from 1 increasing in steps of 1 until we have as many true values as indicated by the argument, then return the numbers for which it was true:
) | - For each number from 1 up to the currently tested number:
Æd | - Count of divisors
, | - Paired with:
Æs | - Sum of divisors
Ṫ_$ | - Tail (divisor count and sum for current number) minus divisor count and sum for all smaller numbers
<Ø. | - Check if each [divisor count difference, divisor sum difference] < [0, 1]
S | - Sum (will sum the checks of divisor count difference and divisor sum difference separatelt)
; | - Concatenate to:
Æṣ<$ | - Whether proper divisor sum less than current number
; | - Concatenate to:
Ẓ¬$ | - Whether number is not prime
Ạ | - All of these (only true for boring numbers)
Ṫ | Finally, take the tail (the requested boring number)
```
In contrast to many of the Jelly code explanations I’ve written, this almost goes from left-to-right!
[Answer]
# [Python 2](https://docs.python.org/2/), 155 bytes
```
n=input();k=D=N=0
while n:k+=1;L=[d for d in range(1,k+1)if k%d<1];S=sum(L);W=len(L);K=S-k;x=K<2or S>D or W>=N or K>=k;n-=1-x;N=max(W,N);D=max(D,S)
print k
```
[Try it online!](https://tio.run/##HcuxCoMwEIDh3ae4pZCgQiOdep5TNiWLg0PpIKg1RE@xSu3Tp9rp/5Z//q79xIn3TJbnbRUSHWkydA0@vR1a4LsLSWFBjwa6aYEGLMNS86sVKnKhkrYDd2lS9cSS3tsoCokVDS2fyKmMHe6Up8mxlpmGI1VG5myekUOOScU7GhrrXVSRkaj/1FEpg3mxvILz/vYD "Python 2 – Try It Online") [first n entries](https://tio.run/##PY@xjoJAFEV7vuIVbsJEII6dPh4V2mCwoKAwFkTGZTL6IDBG3NVvR7Cwuqe5Off@ddVwKiyE4Wa/hQis6mzQPAYmzc3NugINxZTSwrlX@qKA12ZOEnd0KOFct1CCZmgL/lWu9MxcCn0G81OG8ogZdberuxOY00XxBAllvsGeknA5VrMohjHyiNIpk4gMsk/S7zGla9G7uZcKjD8Ye5lwmlazBTOMSx1nkutJ/i@DYCZfCOpU1TDT8ITmYaual98zg1y9AQ "Zsh – Try It Online")
] |
[Question]
[
## Context
Consider square matrices with `n` columns and rows containing the first `n^2` (i.e. `n` squared) positive integers, where `n` is odd. The elements of the matrices are arranged such that the integers `1` through `n^2` are placed sequentially in a counterclockwise spiral starting at the center and initially moving to the left. Call these matrices `M(n)`
For `n=1` this simply gives the one element matrix `M(1)=[[1]]`.
`M(3)` is the matrix
```
9 8 7
2 1 6
3 4 5
```
`M(5)` is the matrix
```
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
```
and `M(7)` is the matrix
```
49 48 47 46 45 44 43
26 25 24 23 22 21 42
27 10 9 8 7 20 41
28 11 2 1 6 19 40
29 12 3 4 5 18 39
30 13 14 15 16 17 38
31 32 33 34 35 36 37
```
Now consider flattening this matrix into a list/array by concatenating its rows starting from the top and moving down. Call these lists `L(n)`. `L(3)`, `L(5)` and `L(7)` are represented below, with their elements delimited by spaces.
```
9 8 7 2 1 6 3 4 5 (n=3)
25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 (n=5)
49 48 47 46 45 44 43 26 25 24 23 22 21 42 27 10 9 8 7 20 41 28 11 2 1 6 19 40 29 12 3 4 5 18 39 30 13 14 15 16 17 38 31 32 33 34 35 36 37 (n=7)
```
We can find the index `i(n)` of `L(n)` in a lexicographically sorted list of permutations of `L(n)`. In Jelly, the `Œ¿` atom gives this index for the list it acts on.
## Challenge
Your challenge is to take an positive odd integer `n` as input and output the index `i(n)`.
The first few values are
```
n i(n)
-------
1 1
3 362299
5 15511208759089364438087641
7 608281864033718930841258106553056047013696596030153750700912081
```
Note that `i(n)` ~= `(n^2)!`. This is not on OEIS.
This is code golf per language, so achieve this in the fewest bytes possible.
[Sandbox post](https://codegolf.meta.stackexchange.com/a/14716/75553).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 19 bytes
```
-;,N$ṁx"RFḣNṙ-+\ỤŒ¿
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//LTssTiThuYF4IlJG4bijTuG5mS0rXOG7pMWSwr////8z)
Based on the method from a J article on [volutes](http://www.jsoftware.com/papers/play132.htm).
## Explanation
```
-;,N$ṁx"RFḣNṙ-+\ỤŒ¿ Main link. Input: integer n
-; Prepend -1. [-1, n]
,N$ Pair with its negated value. [[-1, n], [1, -n]]
ṁ Mold it to length n.
R Range. [1, 2, ..., n]
x" Vectorized copy each value that many times.
F Flatten
N Negate n
ḣ Head. Select all but the last n values.
ṙ- Rotate left by -1 (right by 1).
+\ Cumulative sum.
Ụ Grade up.
Œ¿ Permutation index.
```
[Answer]
# J, ~~48~~ 38 Bytes
-10 bytes thanks to @miles !
```
[:A.@/:_1+/\@|.(2#1+i.)#&}:+:$_1,],1,-
```
Old:
```
3 :'A.,(,~|.@(>:@i.@#+{:)@{.)@|:@|.^:(+:<:y),.1'
```
Note that the result is 0-indexed, so `i(1) = 0` and `i(5) = 15511208759089364438087640`
### Explanation (old):
```
3 :' ' | Explicit verb definition
,.1 | Make 1 into a 2d array
(+:<:y) | 4*n, where y = 2*n + 1
^: | Repeat 4*n times
|:@|. | Clockwise rotation
( )@ | Monadic Hook:
( )@{. | To the first row, apply...
{: | The last and largest item
+ | Added to...
>:@i.@# | The list 1, 2, ..., n; where n is the row length
|.@ | Reverse
,~ | Append to the top of the array
, | Ravel
A. | Permutation index
```
Making the spiral could be quicker, but the orientation would get messed up.
I don't know how J is optimizing this, but it only takes `0.000414` seconds to calculate for `n=7` (on a fresh J console session).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
ZUðẎṀ+ṚW;⁸µJ
1WÇẎ⁸²¤ḟ$$¿ẎŒ¿
```
[Try it online!](https://tio.run/##y0rNyan8/z8q9PCGh7v6Hu5s0H64c1a49aPGHYe2enEZhh9uBwqDeJsOLXm4Y76KyqH9QIGjkw7t////vzkA "Jelly – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ ~~15~~ 14 bytes
```
lYL!PletY@wXmf
```
Fails for test cases larger than `3` due to both floating-point inaccuracies and memory limitations.
[Try it online!](https://tio.run/##y00syfn/PyfSRzEgJ7Uk0qE8Ijft/39jAA)
### Explanation
```
lYL % Implicit input n. Spiral matrix of that side length
!P % Transpose, flip vertically. This is needed to match the orientation
% of columns in the spiral with that of rows in the challenge text
le % Convert to a row, reading in column-major order (down, then across)
t % Duplicate
Y@ % All permutations, arranged as rows of a matrix, in lexicographical
% order
w % Swap
Xm % Row membership: gives a column vector containing true / false,
% where true indicates that the corresponding row in the first input
% matches a row from the second output. In this case the second input
% consists of a single row
f % Find: gives indices of nonzeros. Implicit display
```
] |
[Question]
[
[Cops post](https://codegolf.stackexchange.com/q/152241/66833)
A ***[riffle shuffle](https://en.wikipedia.org/wiki/Shuffling#Riffle)*** is a way of shuffling cards where the deck is split into 2 roughly equal sections and the sections are riffled into each other in small groups. This is how to riffle shuffle a string:
* Split the string into equal sections.
* Reverse the string, and starting from the start of each string.
* Put runs of a random length between 1 and the number of characters left into the final string
* Then remove these characters from the strings.
**An example**
```
"Hello World!" Output string = ""
"Hello ", "World!" ""
"Hell", "World!" " o"
"Hell", "World" " o!"
"Hel", "World" " o!l"
"Hel", "Wo" " o!ldlr"
"H", "Wo" " o!ldlrle"
"H", "" " o!ldlrleoW"
"", "" " o!ldlrleoWH"
```
The final product from `Hello World!` could be `o!ldlrleoWH` and that is what you would output.
## Robbers
Your task is to take a Cops submission and rearrange so that it produces a valid riffle shuffler program. You may not add, remove or change any characters in the original program to result in your solution.
If the program works, even if it is not the cops intended solution, it is a valid crack.
The winner is the person who cracks the most Cops submissions!
[Answer]
# Python 3, [HyperNeutrino](https://codegolf.stackexchange.com/a/152245/68261)
```
from random import*
def r(i):
s=len(i)//2;L,R=i[:s][::-1],i[s:][::-1];o=[]
while L and R:s=randint(1,len(L));o+=L[:s];L,R=R,L[s:]
return o+L+R
```
[Try it online!](https://tio.run/##Lcy7DoMgGIbhvVdBXJBKa2w3DEPPC5MrcbAVK42CQZqmV09/TEmeAMP3Tl/fW7MPoXN2RK4xLVx6nKzz61WrOuRSTdgKwZn5oAz88nxXClpxLdlcS8Y2RU21nNn/XVou62Xw6fWgkEAQRRWbeaxr49OCxpAgpLQZF7Gy9CoqYmWZOuXfziCbiawKk4srjLcvq03qUokbTPEdPEALFOjAE9PkkNDkCE7gDC7gCm5JTQgJPw "Python 3 – Try It Online")
[Proof of Same Character Set](https://tio.run/##LY8xbsMwDEV3n4LIZMcODGeUoSmrJq@CCxgxjbCQpYBSEGTsFdql92iXrgVykPYiruSGiz4h/sfPZzTmthwGc7yYIaAHf5tnDExH8BhgpGlCRnvE5fvj/vb0@/J5f/35el@WZbPZaOnavtkJoXvhNVUP7YUm2VWq3dd1QblFIz3EykTsGCYcs21gd54JZjd2pSodWL4E5HUqsVTVrYTEUrJ0bVGoBKqaPFga7cDSiw6iAAVo6HT9t8aPyOQphksBJ3Yz8GDH@NB8dhy22YgTcE6FyJLFS4M2dnW9b9NS0sL3Wohd01ekvXjo1kndr4briQzGpREKnfAy0cmGvKkSSBVF60qpEqV9HJEoq5UxXNiCiwd3Mdwf "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [HyperNeutrino](https://codegolf.stackexchange.com/a/152246/68261)
```
œs2UŒṖ€X€ż/
```
[Try it online!](https://tio.run/##y0rNyan8///o5GKj0KOTHu6c9qhpTQQQH92j/////8Sk5JTUtPQMRydnF1c3dw8A "Jelly – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), [notjagan](https://codegolf.stackexchange.com/a/152251/59487)
```
jk.iFmO./_dc2Q
```
**[Try it here!](https://pyth.herokuapp.com/?code=jk.iFmO.%2F_dc2Q&input=%22Hello+World%21%22&debug=0)**
### Explanation
The Pyth interpreter also offers a nice pseudo-code if you check the "Debug" box.
* `c2Q` **c**hops the input into **2** pieces of equal length, with initial pieces one longer if necessary.
* `m` **m**aps a function over the pieces. Variable: `d`.
+ `_d` reverses **d**
+ `./` partitions the reverse of **d**; returns all divisions of the reversed **d** into disjoint contiguous substrings.
+ `O` chooses a rand**O**m partition.
* `.iF` **F**olds (reduces) the list by **.i**nterleaving.
* And finally `jk` **j**oins the list of strings.
[Answer]
# [R](https://www.r-project.org/), [Giuseppe](https://codegolf.stackexchange.com/a/152278/66323)
```
function(s){n<-nchar(s)
s<-methods::el(strsplit(s,''))
l<-head(s,n/2)
r<-tail(s,n/2)
o<-{}
while(length(l)|length(r)){if(length(r)){y<-sample(length(r),1)
o<-c(o,rev(head(r,y)))
r<-tail(r,-y)}
if(length(l)){x<-sample(length(l),1)
o<-c(o,rev(head(l,x)))
l<-tail(l,-x)}}
cat(o,sep='')}
```
[Try it online!](https://tio.run/##bY/BasMwEETv@oo0l@yClpIeg3rvbwhbrgQbyazUxsbVt7vCTXApvc2D4Q0j62BoHT5iV0KKkHGJhmLnrbSssqGrKz71@XJxDLlIHjkUyPp0QlRsyDvbN4zPL6jEULGBH5gMLVXdfGAH7OJ78cD4dU@CuIQBftFsKNvruJcF9XmzdJC0uE/YtkTPiPuWaJqxql3FTTX9VfG/KtYT/rzYVKxpwlpVZ0trZTe@tpN1HeD45pjT4ZaE@6cjrt8 "R – Try It Online")
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), [FlipTack](https://codegolf.stackexchange.com/a/152429/76162)
```
L2/:v;O@N[1LU:'.;FL0=?x?i
```
[Try It Online](https://tio.run/##Kygtzqj8/9/HSN@qzNrfwS/axzDUSl3P2s3HwNa@wj7z////ShmpOTn5CuX5RTkpikoA)
] |
[Question]
[
## Explanation
In this task you'll be given a set of *N* points *(x1,y1),…,(xN,yN)* with distinct *xi* values and your task is to interpolate a polynomial through these points. If you know what Lagrange interpolation is you can skip this section.
The goal of a [polynomial interpolation](https://en.wikipedia.org/wiki/Polynomial_interpolation) is to construct the (unique) polynomial *p(x)* with degree *N-1* (for higher degrees there are infinite solutions) for which *p(xi) = yi* for all *i = 1…N*. One way to do so is to construct *N* Lagrange basis polynomials and form a linear combination. Such a basis polynomial is defined as follows:
[](https://i.stack.imgur.com/SSEug.gif)
As you can see if you evaluate *li* at the points x1,…,xi-1
,xi+1,…
,xN it is 0 by construction and 1 for xi, multiplying by yi will only change the value at xi and set it to yi. Now having N such polynomials that are 0 in every point except one we can simply add them up and get the desired result. So the final solution would be:
[](https://i.stack.imgur.com/ni56B.gif)
## Challenge
* the input will consist of *N* data points in any reasonable format (list of tuples, Points, a set etc.)
* the coordinates will all be of integer value
* the output will be a polynomial in any reasonable format: list of coefficients, Polynomial object etc.
* the output has to be exact - meaning that some solutions will have rational coefficients
* formatting doesn't matter (`2/2` instead of `1` or `1 % 2` for `1/2` etc.) as long as it's reasonable
* you won't have to handle invalid inputs (for example empty inputs or input where *x* coordinates are repeated)
## Testcases
These examples list the coefficients in decreasing order (for example `[1,0,0]` corresponds to the polynomial *x2*):
```
[(0,42)] -> [42]
[(0,3),(-18,9),(0,17)] -> undefined (you don't have to handle such cases)
[(-1,1),(0,0),(1,1)] -> [1,0,0]
[(101,-42),(0,12),(-84,3),(1,12)] -> [-4911/222351500, -10116/3269875, 692799/222351500, 12]
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes
```
polinterpolate
```
Takes two lists `[x1, ..., xn]` and `[y1, ..., yn]` as input. Outputs a polynomial.
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L8gPyczryS1CEgnlqT@LygC8jTSNKINDQx1DHR0LUx0DGN1onVNjHQMjXSMgUSspuZ/AA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes, without built-in
```
f(x,y)=y/matrix(#x,,i,j,x[j]^(i-1))
```
Takes two lists `[x1, ..., xn]` and `[y1, ..., yn]` as input. Outputs a list of coefficients.
[Try it online!](https://tio.run/##DcqxCoAgFAXQj2l5wpV85tDSl4iBi/GEQsRBv95cznRKrKKfMmeijqGusb@xVem0dUCQ0X0ON4lmpWap8jVK5NkwDPTpwAFeOwu2OBZhrR8 "Pari/GP – Try It Online")
[Answer]
# [Enlist](https://github.com/alexander-liao/enlist), 25 bytes
```
Ḣ‡ḟ¹‡,€-÷_Ḣ¥€§æc/§₱W€$↙·Ṫ
```
[Try it online!](https://tio.run/##S83LySwu@f8/OtrQwFDHQEfXwkTHMFYnWtfESMfQSMcYSMTGPmpY8HDHokcNCx/umH9oJ5DWedS0Rvfw9nig6KGlQPah5YeXJesfWv6oaWM4kKvyqG3moe0Pd646tPz/fwA "Enlist – Try It Online")
---
Monadic link takes an array of length 2 (e.g., `[[101,0,-84,1],[-42,12,3,12]]`) as input. The first element of the array is list of x value, the second is list of y value. Output as list of coefficient in increasing degree.
Because @HyperNeutrino forgot to wrap numbers in rational wrapper if it is evaluated in list, ([Try it online!](https://tio.run/##S83LySwu@f//4c4F////jzaMBQA "Enlist – Try It Online")) the argument must be hardcoded in the code.
The `↙` is necessary because HyperNeutrino make some mistake in implementing `·` I don't know (or is this a feature? Not sure)
Equivalent Mathematica code:
```
Expand[ Table[
Times @@ ((z - #)/(xi - #) & /@ DeleteCases[x, xi])
, {xi, x}] . y]
```
[Try it online!](https://tio.run/##HY2xCsIwGIT3PMWBIC0kttUOXYSA@gbdSoeoP/hDW4rJkBry7DE6HPd9y91s3Itm4/hhUgpeYos4I4SmbiRqCdW1Ek2UCKo9Zso5/SpGIW5@NctzQG/uEw0CPc9koTWK4gOFXVkVnv@APSqNK03k6GIs2SE/eR5LgbzsOUscccA2ppTU@ubFfQE "Wolfram Language (Mathematica) – Try It Online")
where `x` and `y` are list of coordinates. This prints the polynomial.
---
What Enlist have for this challenge:
* Built in rational number support
* Convolution `æc` (my feature request)
[Answer]
# [Python](https://www.python.org/), with [`numpy`](https://numpy.org/), 301 bytes
See [this notebook](https://www.kaggle.com/code/suhailsh7/polynomial-interpolation-hermite-method) for how it works.
---
Golfed version. 301 bytes, it can be golfed much more. [Attempt this online!](https://ato.pxeger.com/run?1=bZIxTsMwGIXFmlNYZbFTp8RphypSpl6gu_EQqANWEttyHCkW4iQsXeAynABOgx23oIou1tPT-z-9_5ffPrSzz0oej--jbbLt900meq2MBXLstQP1AKROGqN6ICw3VqluAKfEo-ofhKytUHIIwV3MzYMrrTonVS_q7hzf_zk-vE8OvAEdbPGESsPtaCTYQzqMPaRSr7RRBzgh0CgDJiAk2EHvHnjHLYcTbhEWiKEUZgSlKRRLgu7OU5e5bKItixwROKaWTxx2XHo6YrQsM8LQ3KXxeffbJRSJ7VLnCTOgvQQ4hFC82tfnVFGSE5zjbLvBhCWuotmmwKTAa_-w5FYbIS1sFi8dzD20er2XC3Rhk-t2cd1e_7MXjuYsjfiloyRoEnURdBH1Ouh5ugoro9ITTtz5AKeVzh_iBw)
```
import numpy as np
from itertools import combinations as C
from numpy.polynomial import Polynomial as P
def l(k,x):return P([sum([np.prod(x) for x in C(np.delete(x,k),i)])*(-1)**(i+1)/np.prod(np.delete(x,k)-x[k]) for i in range(len(x))][::-1])
def f(x,y):return sum(l(k,x)*y[k] for k in range(len(y)))
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=bVJBbpwwFJW69Cm-phubwHTMZBGNwg266J6iigz2xAJsyzYVVtWTdJNNe6ieoMeobcgMisICfT_e-7z35F9_tHfPSr68_J4cLx7-fvgnRq2MAzmN2kNrQWrEjRpBOGacUoOFlXFW45OQrRNKWlg4SbTXavBSjaIdXqlfrghCH-HCHLhnBp_bi2nlhcFTa4UFPslzXIY6xmHAfQ4zOSEIj4QKBibxTNKxtTZYAdzD4woveHrN3_rAnuu-WY9nFXJUIca-YwNzDM859BtBx6KzkEOZhaaN6vCqK-K-DfmsGOeBVjc3jAehACEhhcFyNX2l71utmeywnUZcX_eTpJujblvk-uMcBGkIZIALSrIMiztK4NPW61tTe8O-M2MZ3nwwzE1GbtrHiUoQSh3zUIUnp5UV7cXWZ5L50F6y199ixaI9IVE7VzU90PyQFw_3OW2Qr-rivsxpmR_Dq0HaCOkw3_0Y8CGsq35-lTuyRem7aPkuenyL7nx9aLJl9Z2vaZzpMpdxLpf5GOckrmJQcrqtTbHJcuHXe_96__8D)
```
import numpy as np
from itertools import combinations
from numpy.polynomial import Polynomial
# get the Lagrange basis function
def l(k, x):
n = len(x)
assert (k < len(x))
x_k = x[k]
x_copy = np.delete(x, k)
denominator = np.prod(x_copy - x_k)
coeff = []
for i in range(n):
coeff.append(sum([np.prod(x) for x in combinations(x_copy, i)]) * (-1)**(i+1) / denominator)
coeff.reverse()
return Polynomial(coeff)
def f(x,y):return sum(l(k,x)*y[k] for k in range(len(y)))
x=[101,0,-84,1]
y=[-42,12,3,12]
print(f"{l(0,x)=}\n")
print(f"{l(1,x)=}\n")
print(f"{l(2,x)=}\n")
print(f"{l(3,x)=}\n")
print("y[0]*l(0,x)+y[1]*l(1,x)+y[2]*l(2,x)+y[3]*l(3,x)== f(x):")
print(f(x,y))
```
] |
[Question]
[
>
> Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for the idea for this second version.
>
> Version 1 [here](https://codegolf.stackexchange.com/q/131715/70347).
>
>
>
Not-so-simple challenge: given a number of cards, build the biggest house of cards you can with that number of cards, according to the following building order:
```
/\ /\ /\ /\/\
-- -- -- ---- ----
/\ → /\/\ → /\/\ → /\/\ → /\/\/\ → /\/\/\ → /\/\/\ →
/\ /\
-- -- --
/\/\ /\/\ /\/\
---- ---- ----
→ /\/\/\ → /\/\/\ → /\/\/\/\ → ...
```
So you start with a single-storey house, then build the adjacent group, then put the bridge card, then build the group in the second floor, then start building groups and bridges from the first floor diagonally to reach the third floor, and so on.
A single card will be represented with a `/`, a `\` or a `--`. If after using as many cards as possible you have one card left, just output what you have accomplished so far (see example for 3 cards, the result is the same as for 2 cards). The only exception is the case of 1 card, that must output a flat card.
Examples:
```
Input: 1
Output:
-- <a card lying on the floor>
Input: 2
Output:
/\
Input: 3
Output:
/\
Input: 5
Output:
--
/\/\
Input: 10
Output:
/\
----
/\/\/\
Input: 20
Output:
/\
--
/\/\/\
------
/\/\/\/\
Input: 39
Output:
--
/\/\
----
/\/\/\
------
/\/\/\/\
--------
/\/\/\/\/\
Input: 40
Output:
/\
--
/\/\
----
/\/\/\
------
/\/\/\/\
--------
/\/\/\/\/\
```
Input can be numeric or a string, and will always be a positive integer. Output must be exactly as shown, with leading and trailing spaces and newlines allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes
```
Nθ⁼θ¹A²ηW¬‹θη«←÷η³↓→/…\/÷η³↙A⁻θηθA⁺³ηη»‖MM÷η³→Fθ≡﹪鳦¹«↗←\/»²«↑P²»«
```
[Try it online!](https://tio.run/##NY07DsIwDIaPFMR5ulRdGJCQOEG6RGKDIoEYu2SggFAzJCGezO5D@AI@QkiQKnn4bP@PbtPuu127zVngRYF7oIBRYMSZvIDHB@tIgTxObI5fX8CxObMZFGvbqOVyKxbuU1VS@PMHHdVnYn0ReJZZtIOALVWHUeKdIjq0GGv8tTQ0ChPOdTsJvAslnHJer34 "Charcoal – Try It Online") Note: The latest version of Charcoal doesn't need the `»«` for -2 bytes. Explanation:
```
Nθ
```
Read the input as an integer into `θ`.
```
⁼θ¹
```
Special case: if the input is 1, print a `-`.
```
A²ηW¬‹θη«
```
`η` represents the number of cards needed to build the next layer, initially 2. A while loop repeats as long as there are enough cards for the layer.
```
←÷η³↓→/…\/÷η³↙
```
Print the left half of the next layer. (I wanted to print the right half, but I couldn't get it to reflect properly for some reason.) The number of `-`s is one third of the number of cards in the layer, rounded down. (See also my answer to part 1.)
```
A⁻θηθA⁺³ηη»
```
Subtract the number of cards from the input number, and add three cards to the number required for the next layer.
```
‖M
```
Mirror the house so far. (This also turns the `-` into `--` for the case of 1 card.)
```
M÷η³→
```
Move the cursor to the right of the house.
```
Fθ
```
Repeat for each remaining card (if any).
```
≡﹪鳦
```
If the card modulo 3 is:
```
¹«↗←\/»
```
1, then print a pair of cards;
```
²«↑P²»
```
2, then print a horizontal card;
```
«
```
Otherwise skip the card (because a pair is needed at this point).
[Answer]
# [Python 2](https://docs.python.org/2/), 167 182 bytes
**167 bytes**
```
f=lambda x,y=0:y<x<2and"--"or~-x>y*3and f(x-2-y*3,y+1)or d(y,x)
d=lambda h,r,v=0:h and d(~-h,max(r-3,1),-~v)+" "*-~v+"--"*(h-(r<3))+"\n"+" "*v+"/\\"*(h+(r>1))+"\n"or""
```
**182 bytes**
```
f=lambda x,y=0:[x>1+y*3and f(x-2-y*3,y+1)or d(y,x),"--"][2>x>y]
d=lambda h,r,v=0:d(h-1,r-3*(r>2)-2*(r==2),v+1)+" "*(v+1)+"--"*(h-1+(r>2))+"\n"+" "*v+"/\\"*(h+(r>1))+"\n"if h+r else""
```
**Explanation (167-byte version)**
```
f=lambda x,y=0:
"--" if y<x<2 # handle case where x is 1 on step 0 (only one card)
else f(x-2-y*3,y+1) # recursive call with one full triangular level accounted for
if x>= 2+y*3 # one full level requires 2+3y cards (2, 7, 15...)
else d(y,x) # if no more full levels can be constructed, draw
d=lambda h,r,v=0: # (h)eight to draw, (r)emaining cards, (v)ertical height already drawn (to determine leading white space)
d(h-1, ,v+1) # recursive call to draw upper lines
max(r-3,1) # subtract remainder cards used in this iteration
+" "*(v+1) # leading whitespace for -- row
+"--"*( )+"\n" # -- line.
h-(r<3) # horizontal card count is equal to the remaining count of levels to draw, minus 1,
# ...plus 1 if there are at least three remaining cards to add to the right
+" "*v # leading whitespace for /\ row
+"/\\"*( )+"\n" # /\ line
h+(r>1) # vertical card pair count equals remaining level count
# ...plus 1 if there are at least two extra cards
if h # return above is there are levels to draw (h)
else "" # else return nothing (ends recursion)
```
[Try it online!](https://tio.run/##NY5BjoMwDEXX5RRRVg7YmgZ2FfQkbDITaCq1Abm0SjZcnZpqKnnh7/f97TkvYYr1to3dzd1/vVMJc3c85Ta1tYteE@mJV0rnXDai1QiJahKBubJmYuUhYzKF/@4HZHxJQlC73cNKAe8uAVOD1iCtL1NppUtpqj29hEDAbWNk3Ef9YUJ@@n5HFfDZ/qOJtd5GOfnnHoO6Rqn5uYA5FYeZr3FRYhIbfnhx4OGhOvl3V@ZrkeHGLl4GsGiP1rwB "Python 2 – Try It Online")
* This feels unnecessarily long, but I can't see anything to remove at the moment...feel free to comment any suggestions
[Answer]
# [Perl 5](https://www.perl.org/), 129 bytes
```
@r=($_=<>-2)<0?'--':'/\\';while($_>1){$#r+=2;$i=0;$r[$i].=$i++%2?'--':'/\\'while$i<@r&&($_-=2-$i%2)>=0}say$"x(@r/2).pop@r while@r
```
[Try it online!](https://tio.run/##TcvRCoIwFIDhV4k6OodszoEEuWN7gZ4gI7oQOiBtHIOK6NVb4lXX///FgccmJc9YwBldp6x0Zi@UEjtR9b1oH1cah7l1tXzDhku0LRCaFvgIdNIIVJaZ/RMLAHKe83x2Cq0Cyqzs0HymywvWz8JzZaWOIXpeLbvnlLbfEO8UblNSh0ab2vwA "Perl 5 – Try It Online")
] |
[Question]
[
## Challenge
Make the shortest program to determine if the figures in the input will fit into the space in the input.
## Requirements
The input will be in the format of this example:
Input:
```
+----+ -- +--+
| +----+ | |
| | +--+
| |
+---------+
```
Output:
```
+----+
|+--++----+
|| |-- |
|+--+ |
+---------+
```
First, starting in the upper left corner, is the space that the program will try to fit the figures into. Then there is a space. Then there is a figure, in this case two dashes. Then there is a space, then a second figure. The output is the figures fitted inside of the space.
## Rules about figures and input:
* The upper left corner of a shape will always be on the first row.
* After a figure, there is one space, as shown in the example.
* There is no limit on the size of the figures.
* The first figure will always be the space that the program will determine if the figures fit into.
* There is no limit on the number of figures, but there will only be one space to fit them into.
* All figures will be made of `|` and `-` for the sides and `+` for the corners. These are the only characters used besides spaces and newlines.
* Figures cannot be rotated.
* Borders cannot overlap.
* You may fit one figure inside of another.
* The figures do not have to be closed.
* The space will always be closed.
* The space does not have to be completely filled.
* You may not split up shapes.
## Rules about output:
* If the figures fit into the space, the program should output the figures inside of the space, as shown above. It does not matter how they are arranged, as long as no borders overlap, all figures are correct, and no shapes are split up.
* If the figures do not fit, output "no".
## Examples
Input:
```
+--+ |
+--+
```
Output:
```
no
```
Input:
```
+---+ -+
| | |
| |
+---+
```
Output:
```
+---+
|-+ |
| | |
+---+
```
This is also valid:
```
+---+
| -+|
| ||
+---+
```
Input:
```
+----------+ +-----+ -+
| | | | |
| | | |
| | +-----+
| |
+----------+
```
Output:
```
+----------+
|+-----+ |
||-+ | |
|| | | |
|+-----+ |
+----------+
```
This is a code golf, so the shortest answer wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~529~~ ~~692~~ ~~683~~ 681 bytes
```
L=len
R=range
def g(s):S=s.split('\n');S=[l.ljust(L(S[0]))for l in S];Z=zip(*S);I=[-1]+[i for i in R(L(Z))if{' '}==set(Z[i])]+[None];return[[list(x)for x in zip(*Z[I[i]+1:I[i+1]])if set(x)!={' '}]for i in R(L(I)-1)]
def f(s):
S=g(s);G(S[0],1,1)
for l in F(*S)or['no']:print''.join(l).replace('~',' ')
def G(a,i,j):
if len(a)>i>-1<j<len(a[0])and'!'>a[i][j]:
for x,y in(0,1),(0,-1),(1,0),(-1,0):G(a,i+x,j+y);a[i][j]='~'
def F(a,*s):
if not s:return a
c=s[0];h,w=L(c),L(c[0])
for i in R(1,L(a)-h):
for j in R(1,L(a[0])-w):
T=1;A=[l[:]for l in a]
for y in R(h):
for x in R(w):
C=c[y][x]
if' '<C:T&=A[y+i][x+j]>'}';A[y+i][x+j]=C
r=T and F(A,*s[1:])
if r:return r
```
[Try it online!](https://tio.run/##hVFNb@IwED03v2LKYW3XMSJ7TDASm1UrJLQH4ITXh4iG4ihKUJKqsEv3r9OxEyhIFTtSYs3Xe29mtvtmUxbfj8epzNPCm8kqKV5S7zldwwutWTiXdb/e5qah5HdBWDSXKu/n2Wvd0Cmdq4FmbF1WkIMpYK6jpfxjtvRhzqKJVCLQXBmweWPzM2xZMmbWfwmQdynrtKFLZTTDsl9lkeqoSpvXqlAqN4i/c8g72@lAl2qCxTwI8eGB1ggEFmLH7qVD1FdMEyYCpt0kazuJB3NpR4qenG4/8APmwVn8o1VdVooUJdHhtjJFQ0g/K01Bc9av0m2erFJK/hEfqZiDfaKJb/zMQqMUXB9N2MiMRDDMhs6z60mKZ3JPRglKV5kOvTs3lL9HTjpACT7@hX0Cf4B/YZ/QIfOdn/E9i7pWidyO9hGTD3XHWpQN1GG7N0g8WMkaWaON/yandMV8/FkV3uUVAowmTGxYpya7CNti8WYzsJBBNMZzq1Cft5RoTFhv3/Y4jLvznWbUtd5BLFdqr9VOW8escWXDOFx8k2O15zjNjmd6RN5JdOHLGKEruQDcGM44xhlVEKJ0CwDVacbquKa9Xs/jggOaEN4BDvhxITg@aAfMoXGsagE8d03POzXaJEDbfdH3mTiAgzzZKcsvYy2O@A8TbwtvaeHQAZ9ZW@yb@jviVvMnxFnwAb6Y4zJ@He5groJXRLd3OR7DD2yJ4Wd3ARgDRmKIT76zOI6/vtDxAw "Python 2 – Try It Online")
Gained a lot of bytes by adding a flood fill to the first shape.
This is to fix fix cases where a figure can be outside the shape, but inside its bounding box.
eg.
The shape fits inside the bounding box, but outside the shape:
```
Input: Wrong: Correct:
+-+ -- +-+ +-+
| | | |-- | |
| +--+ | +--+ | +--+
| | | | |-- |
+----+ +----+ +----+
```
---
**Explanation**
`f` takes input as a single string with newlines.
```
+----+ -- +--+
| +----+ | |
| | +--+
| |
+---------+
```
The shapes are split up with `g(s)` and mapped to lists of lists
```
[[['+', '-', '-', '-', '-', '+', ' ', ' ', ' ', ' ', ' '], ['|', ' ', ' ', ' ', ' ', '+', '-', '-', '-', '-', '+'], ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|'], ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|'], ['+', '-', '-', '-', '-', '-', '-', '-', '-', '-', '+']],
[['-', '-']],
[['+', '-', '-', '+'], ['|', ' ', ' ', '|'], ['+', '-', '-', '+']]]
```
The first shape is flood filled with `~` (`G(S[0])`), so we know the allowed area:
```
+----+
|~~~~+----+
|~~~~~~~~~|
|~~~~~~~~~|
+---------+
```
For each other shape we recursively fit them into the first `F(a,*s)`, returning when all of them fit, or at the end, if no configuration does.
```
+----+ +----+ +----+ +----+ +----+
|--~~+----+ |~--~+----+ |~~--+----+ |~~~~+----+ |~~~~+----+
|~~~~~~~~~| |~~~~~~~~~| |~~~~~~~~~| |--~~~~~~~| |~--~~~~~~|
|~~~~~~~~~| |~~~~~~~~~| |~~~~~~~~~| |~~~~~~~~~| |~~~~~~~~~|
+---------+ +---------+ +---------+ +---------+ +---------+
| | | | |
V V V V V
No room No room No room No room +----+
for next for next for next for next |+--++----+
shape shape shape shape ||--|~~~~~|
|+--+~~~~~|
+---------+
Done!
```
Lastly we print the combined shapes, without `~`.
```
+----+
|+--++----+
||--| |
|+--+ |
+---------+
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 811 bytes
```
(M=MorphologicalComponents;L=Length;A=Thread;T=Last;B=Table;P=Position;W=Prepend;g=AnyTrue[#,#!=" "&]&;h[n_]:=If[DuplicateFreeQ[Join@@B[(#-{1,1}+W[n,{1,1}][[i]]&)/@P[t[[i]],1],{i,L[y]}]],n,Nothing];R[z_]:=PadRight[#,Max[L/@z]," "]&/@z;s=Characters/@StringSplit[#,"\n"];s=R@s;r=Map[#/.{Longest[" "...],n___," "...}->{n}&,DeleteCases[A/@Split[A@s,g],_?(!g@#&),2],2];r[[1]]=R@#&@@r;t=r/.{"|"|"+"|"-"->1," "->0};y=M[#,Method->"ConvexHull"]&/@t;o=y-M/@t;u=T[h/@T@T@Reap[Outer@@Append[W[B[{NoneTrue[Flatten@B[#[[q+1,w+1]]==1&&o[[1]][[i+q,j+w]]==0,{w,0,L@#&@@#-1},{q,0,L@#-1}],TrueQ],i,j},{i,1,1+L@#&@@y-L@#},{j,1,1+L@y[[1,1]]-L@#&@@#}]&/@y[[2;;]],If[And@@(First/@{##}),Sow[#[[2;;]]&/@{##}]]&],2]]];If[u=={},"no",Grid@ReplacePart[r[[1]],Join@@B[(#-{1,1}+u[[i-1]])->Part[r[[i]],Sequence@@#]&/@P[t[[i]],1],{i,2,L@y}]]])&
```
[](https://i.stack.imgur.com/TdDYMm.png)
It needs a frontend to display grid (which is not supported on tio.run).
The code does the following things:
1. Get inside points of 1st shape
2. Iterate over all starting point combinations
3. Pick a combination where all other (2, 3, ...) shapes' points lie in waht we get in Step 1, and without any overlapped points
4. Output (by `ReplacePart`)
If the input format can be more flexible, the code can be shortened to ~680 bytes. Besides that, there is still a lot of golfing space, though.
[Try it online!](https://tio.run/##ZVJtb9owEP7eX0ETKQLFhoaPs8xMqboXQUcBqR88C3ngJqlSGxxnlKb57ewcOm3anES5e3x@7jnfPUuXqWfp8o08PdJTd0Znxu4yU5gUoGJinndGK@1KMqVTpVOXkTFdZVbJLVnRqSwduaYr@aNQZE7npsxdbjR5oHOrdkpvSUrH@riyleIhCi9p0AkiEZGM67X4QL888ptqV0Aip26tUvf8q8k1Y9e8G@I6QUkTP3CNWktwngsR9QZszl1ro0SgOkdTfhQNeBrdGZflOhVkwV89/VxuF3maOUg9ky98OmCvAoECEYFFSjrJpJUbp2w5YEtn4egSxPjw4LsOBEQsWEksnckdDwf9emp0qkrHgaLf70PG9XqNzk6DR7VuInSjCuXURJaq5GNgbfnGrESpQOuP3cuUhVEPDQW8xHKeCAE5wogxSxy1kCN4gyeGDwd4lHh2PLpqyJHOfBXKZWaLR8HE6J/q5XNVFG0xjhh6xDNvVHTFswFbwbNQoPtbBfUxNt75bvAHfs3rO2ho25HbQjqnNFx3yPk@TtAh9oJoEkWm1QbXHO/RU3zw6BWqD@gKTVu5IU4aVO/PPtgCecZ7gXL01PiuQMvic@gRwx@wp3fsCNTQOoHfmRpfAYBDQqCLMBJjvWWse5vb0g1YHYZNDy3NwWtsQ6IzCIa/RSEIHKkorRsUaBOgTzbfQum7Qm7UXFrHz9eM/pusCqrDsNPDo99xfqiWal8pvVGgzKf6Z9iGUO8RcotedJrDxDj2yIMYw4o77cK4A2588eadPxvgvp2xzrvb@SvujF204e2KA3H6BQ "Wolfram Language (Mathematica) – Try It Online")
Expanded:
```
(M = MorphologicalComponents; L = Length; A = Thread; T = Last;
B = Table; P = Position; W = Prepend; g = AnyTrue[#, # != " " &] &;
h[n_] := If[
DuplicateFreeQ[
Join @@ B[(# - {1, 1} + W[n, {1, 1}][[i]] &) /@ P[t[[i]], 1], {i,
L[y]}]], n, Nothing];
R[z_] := PadRight[#, Max[L /@ z], " "] & /@ z;
s = Characters /@ StringSplit[#, "\n"]; s = R@s;
r = Map[# /. {Longest[" " ...], n___, " " ...} -> {n} &,
DeleteCases[A /@ Split[A@s, g], _?(! g@# &), 2], 2];
r[[1]] = R@# & @@ r; t = r /. {"|" | "+" | "-" -> 1, " " -> 0};
y = M[#, Method -> "ConvexHull"] & /@ t; o = y - M /@ t;
u = T[h /@
T@T@Reap[
Outer @@
Append[W[
B[{NoneTrue[
Flatten@
B[#[[q + 1, w + 1]] == 1 &&
o[[1]][[i + q, j + w]] == 0, {w, 0,
L@# & @@ # - 1}, {q, 0, L@# - 1}], TrueQ], i,
j}, {i, 1, 1 + L@# & @@ y - L@#}, {j, 1,
1 + L@y[[1, 1]] - L@# & @@ #}] & /@ y[[2 ;;]],
If[And @@ (First /@ {##}), Sow[#[[2 ;;]] & /@ {##}]] &],
2]]]; If[u == {}, "no",
Grid@ReplacePart[r[[1]],
Join @@ B[(# - {1, 1} + u[[i - 1]]) ->
Part[r[[i]], Sequence @@ #] & /@ P[t[[i]], 1], {i, 2,
L@y}]]]) &
```
] |
[Question]
[
# Task
Given a Boolean matrix, find one (or optionally more) subset(s) of rows which have exactly one True in each column. **You may use any algorithm**, but must support very large matrices, like the last example.
# One possible algorithm ([Knuth's Algorithm X](https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X))
While there is no requirement to use this algorithm, it may be your best option.
1. If the matrix *A* has no columns, the current partial solution is a valid solution; terminate successfully.
2. Otherwise choose a column *c*.
3. Choose\* a row *r* such that A*r*, *c* = 1.
4. Include row *r* in the partial solution.
5. For each column *j* such that *A**r*, *j* = 1,
for each row i such that *A**i*, *j* = 1,
delete row *i* from matrix *A*.
delete column *j* from matrix *A*.
6. Repeat this algorithm recursively on the reduced matrix *A*.
\* Step 3 is non-deterministic, and needs to be backtracked to in the case of a failure to find a row in a later invocation of step 3.
# Input
Any desired representation of the minimum 2×2 matrix *A*, e.g. as a numeric or Boolean array
```
1 0 0 1 0 0 1
1 0 0 1 0 0 0
0 0 0 1 1 0 1
0 0 1 0 1 1 0
0 1 1 0 0 1 1
0 1 0 0 0 0 1
```
or as Universe + Set collection
```
U = {1, 2, 3, 4, 5, 6, 7}
S = {
A = [1, 4, 7],
B = [1, 4],
C = [4, 5, 7],
D = [3, 5, 6],
E = [2, 3, 6, 7],
F = [2, 7]
}
```
or as 0 or 1 indexed sets;
`{{1, 4, 7}, {1, 4}, {4, 5, 7}, {3, 5, 6}, {2, 3, 6, 7}, {2, 7}}`.
# Output
Any desired representation of one (or optionally more/all) of the solutions, e.g. as numeric or Boolean array of the selected rows
```
1 0 0 1 0 0 0
0 0 1 0 1 1 0
0 1 0 0 0 0 1
```
or as Boolean list indicating selected rows `{0, 1, 0, 1, 0, 1}` or as numeric (0 or 1 indexed) list of selected rows `{2, 4, 6}` or as list of set names `['B', 'D', 'F']`.
# More examples
**In:**
```
1 0 1
0 1 1
0 1 0
1 1 1
```
**Out:** `1 3` or `4` or `1 0 1 0` or `0 0 0 1` or `[[1,3],[4]` etc.
---
**In:**
```
1 0 1 0 1
0 1 0 1 0
1 1 0 0 1
0 1 0 1 1
```
**Out:** `1 1 0 0` etc.
---
**In:**
```
0 1 0 1 1 0 1
1 1 0 0 1 1 1
0 1 0 0 1 0 0
1 1 1 0 0 0 1
0 0 0 1 1 1 0
```
**Out:** `0 0 0 1 1` etc.
---
**In:**
```
0 1 1
1 1 0
```
**Out:** Nothing or error or faulty solution, i.e. you do not have to handle inputs with no solution.
---
**In:** <http://pastebin.com/raw/3GAup0fr>
**Out:** `0 10 18 28 32 38 48 61 62 63 68 86 90 97 103 114 120 136 148 157 162 174 177 185 186 194 209 210 218 221 228 243 252 255 263 270 271 272 273 280 291 294 295 309 310 320 323 327 339 345 350 353 355 367 372 373 375 377 382 385 386 389 397 411 417 418 431 433 441 451 457 458 459 466 473 479 488 491 498 514 517`
---
**In:** <https://gist.github.com/angs/e24ac11a7d7c63d267a2279d416bc694>
**Out:** `553 2162 2710 5460 7027 9534 10901 12281 12855 13590 14489 16883 19026 19592 19834 22578 25565 27230 28356 29148 29708 30818 31044 34016 34604 36806 36918 39178 43329 43562 45246 46307 47128 47906 48792 50615 51709 53911 55523 57423 59915 61293 62087 62956 64322 65094 65419 68076 70212 70845 71384 74615 76508 78688 79469 80067 81954 82255 84412 85227`
[Answer]
# Haskell, ~~100~~ ~~93~~ ~~92~~ ~~87~~ ~~83~~ 80 bytes
Knuth's algorithm:
```
g&c=filter(g.any(`elem`c))
(u:v)%a=[c:s|c<-id&u$a,s<-(not&c)v%(not&c$a)]
x%_=[x]
```
Calculates all covers nondeterministically depth-first in the list monad. Use `head` to calculate only one since Haskell is lazy. Usage:
```
*Main> [[1],[2],[3],[4],[5],[6],[7]]%[[1, 4, 7], [1, 4], [4, 5, 7], [3, 5, 6], [2, 3, 6, 7], [2, 7]]
[[[1,4],[2,7],[3,5,6]]]
```
For more speed by using Knuth's suggestion of selecting column with least ones, use this: (115 bytes, flat list for universe). Finds first solution to the large [pentomino cover problem](https://codegolf.stackexchange.com/questions/100956/find-the-rows-which-make-each-column-have-one-true-was-knuths-algorithm-x/100968?noredirect=1#comment245630_100956) in under a minute when compiled.
```
import Data.List
[]%_=[[]]
w%a=[c:s|c<-a,c\\(head.sortOn length.group.sort$w:a>>=id)/=c,s<-(w\\c)%[b|b<-a,c\\b==c]]
```
Thanks to @Zgarb for saving 1+3 bytes!
Thanks to @ChristianSievers for his sage advice and saving 5 bytes and some.
Ungolfed (with flat list universe):
```
knuthX [] _ = [[]]
knuthX (u:niverse) availableRows = --u chosen deterministically
[ chosen:solution
| let rows = filter (elem u) availableRows
, chosen <- rows --row chosen nondeterministically in list monad
, solution <- knuthX
(filter (not.(`elem`chosen)) niverse)
(filter (not.any(`elem`chosen)) availableRows)
]
```
[Answer]
# Python, 482 bytes
```
r=lambda X,Y:u({j:set(filter(lambda i:j in Y[i],Y))for j in X},Y)
def u(X,Y,S=[]):
if X:
for r in list(X[min(X,key=lambda c:len(X[c]))]):
S.append(r);C=v(X,Y,r)
for s in u(X,Y,S):yield s
w(X,Y,r,C);S.pop()
else:yield list(S)
def v(X,Y,r):
C=[]
for j in Y[r]:
for i in X[j]:
for k in Y[i]:
if k!=j:X[k].remove(i)
C.append(X.pop(j))
return C
def w(X,Y,r,C):
for j in reversed(Y[r]):
X[j]=C.pop()
for i in X[j]:
for k in Y[i]:
if k!=j:X[k].add(i)
```
`r` is the function to call with the Universe + Set collection.
Golfed a little from [this page](http://www.cs.mcgill.ca/%7Eaassaf9/python/algorithm_x.html)
Usage:
```
X = {1, 2, 3, 4, 5, 6, 7}
Y = {
'A': [1, 4, 7],
'B': [1, 4],
'C': [4, 5, 7],
'D': [3, 5, 6],
'E': [2, 3, 6, 7],
'F': [2, 7]}
for a in r(X,Y): print a
```
[Answer]
# R, ~~124~~ ~~117~~ ~~115~~ 113 bytes
Very inefficient, but not that long in code. Tries all possible subsets of rows and checks if all the rows sum to 1.
```
f=function(x,n=nrow(x))for(i in 1:n)for(j in 1:ncol(z<-combn(n,i)))if(all(colSums(x[k<-z[,j],,drop=F])==1))cat(k)
```
Takes a matrix as input. Returns the rownumbers of the first solution encountered. Returns nothing if there are no solutions, but might take a long while terminating if the input is big.
Ungolfed:
```
f=function(x, n=nrow(x)){
for(i in 1:n){
z=combn(n,i)
for(j in 1:ncol(z)){
k=x[z[,j],,drop=F]
if(all(colSums(k)==1)){
print(z[,j])
}
}
}
}
```
7 bytes saved thanks to Billywob
Another 2 bytes saved thanks to Billywob
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 81 bytes
```
{×≢⍉⍵:⍵∇{~1∊⍵:0⋄0≡s←⍺⍺c/⍺⌿⍨r←~∨/⍺/⍨~c←~,⍺⌿⍨f←<\⍵:⍺∇f<⍵⋄f∨r\s},⍵/⍨<\n=⌊/n←+⌿⍵⋄∧/⍵}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#VU89DoIwFN49BSNEE9vV4D0Y2EgYGWAkMBEsP010ctZFLsDC4uBN3kXwPVpKSSnN@/76dQ6gvue/JzRvkA3I8YIbxC0vOYiWZgZdxaB5ZSgEOeEXnensvyCHFMESxEAI7qGMCDgZPsbRD1XshLGxT/FdFaMnDbMClSP5/DC5Qt@eE9QfFyupQHyQHIt5DhyoHy53GC7993Yj81ymR67YlVsAGvnqVKz2LeLDlq@5VUK30GErNpUt2aMm0yqhOpsSdg2unsBNSfMELd0q6HYK@wM "APL (Dyalog Unicode) – TIO Nexus")
`{` anonymous function:
`:` if…
`⍵` If the argument
`⍉` when transposed
`≢` has a row-count
`×` which is positive
then
`⍵∇{`… then apply this function with the right argument as left argument (constraint matrix), but only after it has been modified by the following anonymous operator (higher-order function):
`:` if…
`1∊⍵` there are ones in the right argument
`~` NOT
then…
`0` return zero (i.e. fail)
`⋄` else:
`:` if…
`<\⍵` the first *true* of the right argument (lit. cumulative less-than; first row)
`f←` assign that to *f*
`⍺⌿⍨` use that to filter the rows of the left argument
`,` ravel (flatten)
`~` negate
`c←` assign that to *c*
`~` negate
`⍺/⍨` use that to filter the columns of the left argument
`∨/` which rows have a true? (OR reduction)
`~` negate that
`⍺⌿⍨` use that to filter the rows of the left argument
`c/` use *c* to filter the columns of that
`⍺⍺` apply the original outer function (the left operand; sub-matrix covers)
`s←` assign that to *s*
`0≡` …is identical to zero (failure), then (try a different row):
`f<⍵` right-argument AND NOT *f*
`⍺∇` recurse on that (preserving the original left argument)
`⋄` else:
`r\s` use zeros in *r* to insert zero-filled columns in *s*
`f∨` return *f* OR that (success; row *f* included)
`}`… … on
`+⌿⍵` the sum of the argument
`n←` assign that to *n*
`⌊/` the minimum of that
`n=` Boolean where *n* is equal to that
`<\` the first one of those (lit. cumulative less-than)
`⍵/⍨` use that to filter the columns of the argument (gives first column with fewest ones)
`,` ravel that (flatten)
`⋄` else
`∧/⍵` rows which are all ones (none, so this gives a zero for each row)
`}` end of anonymous function
] |
[Question]
[
[The Collatz conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture) is a very well-known conjecture. Take a positive integer; if it's even, divide by 2, else, multiply by 3 and add 1. Repeat until you reach `1` or something else happens. The conjecture is that this process always reaches `1`.
You can also reverse the process. Start at `1`, multiply by 2, and to branch to `multiply by 3 and add 1` numbers, when you reach an even number that is `1 (mod 3)`, subtract 1 and divide by 3.
A Collatz path combines the two, trying to get from one number to another with those four operations.
For example, to get to `20` from `1`:
```
1 *2
2 *2
4 *2
8 *2
16 *2
5 (-1)/3
10 *2
20 *2
```
You can also get to `3` from `10` by subtracting 1 and dividing by 3.
With these tools, you can traverse a Collatz path from one number to another. For example, the path from `20` to `3` is (divide by 2), (subtract 1, divide by 3).
In short, the available operations are:
```
n * 2 always
n // 2 if n % 2 == 0
n * 3 + 1 if n % 2 == 1
(n-1) // 3 if n % 6 == 4
```
Note: not all Collatz paths are short. `a(7,3)` could run
```
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 2, 4, 8, 16, 5, 10, 3
```
but a shorter path is
```
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 3
```
# The Challenge
Find the length of the shortest Collatz path between any two positive integers, `p` and `q`.
* Input is any two positive integers less than `2^20` to avoid integer overflow. The input method is left to the discretion of the golfer. The integers may be the same, in which case, the length of the Collatz path is `0`.
* Output should be one integer, denoting the length of the shortest Collatz path between `p` and `q`.
# Test Cases
```
a(2,1)
1
a(4,1)
1 # 4 -> 1
a(3,1)
6 # 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 1
a(11,12)
11 # 11 -> 34 -> 17 -> 52 -> 26 -> 13
# -> 40 -> 20 -> 10 -> 3 -> 6 -> 12
a(15,9)
20 # 46 -> 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 13
# -> 26 -> 52 -> 17 -> 34 -> 11 -> 22 -> 7 -> 14 -> 28 -> 9
```
Many thanks to orlp for their help in clarifying this challenge.
As always, if the problem is unclear, please let me know. Good luck and good golfing!
[Answer]
# Haskell, ~~170 158 157 146 143 137 135 112 109 108 106 100~~ 99 bytes
```
a!b=length$fst$break(elem b)$iterate(>>= \n->2*n:cycle[div n 2,n*3+1]!!n:[div(n-1)3|mod n 6==4])[a]
```
I did not expect that my original version was so much more golfable, this is also the work of @nimi @Lynn and @Laikoni!
Thanks @Laikoni for a byte, @Lynn for ~~11 14 20~~ 21 bytes, @nimi for 8 bytes!
This expands the the tree of visited numbers (beginning by `a`) step by step, and checks in each step whether we arrived at the given number `b`.
[Answer]
# Python 2, 110 bytes
```
a=lambda p,q,s={0}:1+a(p,q,s.union(*({p,n*2,[n/2,n*3+1][n%2]}|set([~-n/3]*(n%6==4))for n in s)))if{q}-s else-1
```
[Answer]
# Pyth, 30 bytes
```
|q*FQ2ls-M.pm.u&n2N?%N2h*3N/N2
```
[Try it online](https://pyth.herokuapp.com/?code=%7Cq%2aFQ2ls-M.pm.u%26n2N%3F%25N2h%2a3N%2FN2&test_suite=1&test_suite_input=%5B2%2C1%5D%0A%5B4%2C1%5D%0A%5B3%2C1%5D%0A%5B11%2C12%5D%0A%5B15%2C9%5D)
### How it works
Take the length of the symmetric difference of the two forward Collatz sequences starting at the two input numbers and ending at 2. The only exception is if the input is `[1, 2]` or `[2, 1]`, which we special-case.
```
*FQ product of the input
|q 2 if that equals 2, return 1 (True), else:
m map for d in input:
.u cumulative fixed-point: starting at N=d, iterate N ↦
&n2N?%N2h*3N/N2 N != 2 and (N*3 + 1 if N % 2 else N/2)
until a duplicate is found, and return the sequence
.p permutations
-M map difference
s concatenate
l length
```
[Answer]
# Python 2, ~~156~~ ~~179~~ ~~191~~ ~~209~~ ~~181~~ ~~172~~ ~~177~~ 171 bytes
Since a Collatz path can be imagined as `a(1,p)` and `a(1,q)` conjoined at the first number that is common to both sequences and `a(1,n)` is the original Collatz conjecture, this function calculates the Collatz sequence of `p` and `q`, and calculates the length from there. This isn't a pretty golf, so golfing suggestions are very much welcome. The only exception is when `p or q == 1`. Then, since we can skip directly from `4` to `1` as opposed to a regular Collatz sequence, we need to subtract a step from the result.
**Edit:** Lots of bug fixing.
**Edit:** Lots and lots of bug fixing
```
f=lambda p:[p]if p<3else f([p//2,p*3+1][p%2])+[p]
def a(p,q):
i=1;c=f(p);d=f(q)
if sorted((p,q))==(1,2):return 1
while c[:i]==d[:i]!=d[:i-1]:i+=1
return len(c+d)-2*i+2
```
[Try it online!](https://tio.run/##NcxNCoMwEIbhvaeYLgoZo0iiq9icRLKwJsGAjeNPKT29TaVdvXzDw9B7H@dYH4fXU/@42x5IdWSCB7rVbtoceNZRVcmC8poL09FVGuSJZNZ56BkVC6oMghbtoD0jbG3KgunkYZvX3Vl2ItSaiUKiWt3@XCOIDF5jmBwMnQpGa/vN5UwpjApcJ/Gzk4ts4BZLmQcuD1pD3Fmf3jWI2X81hUA8Pg)
[Answer]
## JavaScript (ES6), 135 bytes
```
f=(x,y,a=[(s=[],s[0]=s[x]=1,x)],z=a.shift())=>z-y?[z*2,z/2,z%2?z*3+1:~-z/3].map(e=>e%1||s[e]?0:s[a.push(e),e]=-~s[z])&&f(x,y,a):~-s[y]
```
Performs a breadth-first search. `x` is the starting number, `y` the destination, `a` an array of trial values, `s` an array of the number of inclusive steps on the chain from `x`, `z` the current value. If `z` and `y` are not equal, compute `z*2`, `z/2` and either `z*3+1` or `(z-1)/3`, depending on whether `z` is odd or even, then filter out fractions and previously seen values and add them to the search list.
[Answer]
# Python 2, 80 bytes
```
p=lambda n:n-2and{n}|p([n/2,n*3+1][n%2])or{n}
lambda m,n:m*n==2or len(p(m)^p(n))
```
Take the length of the symmetric difference of the two forward Collatz sequences starting at the two input numbers and ending at 2. The only exception is if the input is 1, 2 or 2, 1, which we special-case.
] |
[Question]
[
Given an input `n`, output the value of the [Fransén-Robinson constant](https://oeis.org/A058655) with `n` digits after the decimal place, with rounding.
# Rules
* You may assume that all inputs are integers between 1 and 60.
* You may not store any related values - the constant must be calculated, not recalled.
* Rounding must be done with the following criteria:
+ If the digit following the final digit is less than five, the final digit must remain the same.
+ If the digit following the final digit is greater than or equal to five, the final digit must be incremented by one.
* You must only output the first `n+1` digits.
* Standard loopholes apply.
# Test Cases
```
>>> f(0)
3
>>> f(1)
2.8
>>> f(11)
2.80777024203
>>> f(50)
2.80777024202851936522150118655777293230808592093020
>>> f(59)
2.80777024202851936522150118655777293230808592093019829122005
>>> f(60)
2.807770242028519365221501186557772932308085920930198291220055
```
[Answer]
## Mathematica, ~~44~~ ~~39~~ ~~36~~ 25 UTF-8 bytes
* *-5 bytes thanks to Sp3000*
* *-3 bytes thanks to kennytm*
* *-11 bytes thanks to senegrom*
Crossed out ~~44~~ is still regular 44!!
```
N[‚à´1/x!Ôùå{x,-1,‚àû},#+1]&
```
Example:
```
f=N[‚à´1/x!Ôùå{x,-1,‚àû},#+1]&
f[2]
```
Outputs `2.81`.
Explanation
```
N[ , # + 1]
‚à´1/x!Ôùå{x,-1,‚àû}
```
First step takes `N`umeric of the rest, with `#` (first parameter) + 1 precision. `!` (factorial) does what you'd expect. `{x, -1, Infinity}` sets the bounds for the (strangely formatted) Integral.
] |
[Question]
[
Given an input of a string with bytes that may be in either binary, octal, or
hex, output the string's ASCII equivalent.
Input will be provided in the following format, for example:
```
501200100001147
```
which represents
```
0x50 0o120 0b01000011 0x47
```
which is equivalent (in ASCII) to
```
PPCG
```
Binary, octal, and hex will always be provided with 8, 3, and 2 digits
respectively.
For the purposes of this challenge, only printable ASCII must be supported.
This is the range `32..126` inclusive. Therefore, it is impossible for there to
be ambiguity. Note that
* A string represents binary if and only if it starts with a `0` and its second
character is either a `0` or a `1`. All printable ASCII characters have their
high bit off in binary (i.e. start with a `0`), and none of them start with
`00` or `01` in either hex or octal.
* With binary out of the way, note that all printable ASCII characters start
with `2`-`7` in hex and `0`-`1` in octal. Therefore, it is possible to
unambiguously distinguish between hex and octal as well.
You may assume that hex input is provided as either lowercase or uppercase,
whichever is more convenient.
Regex makes the parsing portion of the challenge semi-trivial. I don't want to ban the use of regex outright, but if you have a non-regex solution longer than its regex-using counterpart, feel free to post it along with the "real" answer anyway, since I'd be interested to see it as well. :)
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases:
```
In Out
-----------------------------------
501200100001147 | PPCG
5C01101111100 | \o@
313206306400110101 | 12345
2A200530402C | * + ,
0011111100111111 | ??
<empty string> | <empty string>
```
[Answer]
# Lex + C, ~~156~~ 124 bytes
```
%{
p(b){putchar(strtol(yytext,0,b));}
%}
%option noyywrap
%%
0[01]{7} {p(2);}
[01].. {p(8);}
.. {p(16);}
%%
main(){yylex();}
```
Compile with:
```
lex mixed_base.l
cc -o mixed_base lex.yy.c
```
[Answer]
## ES6, ~~86~~ 80 bytes
Regex-based solution:
```
s=>s.replace(/0[01]{7}|[01]?../g,n=>String.fromCharCode(0+'bkxo'[n.length&3]+n))
```
Recursive non-regex solution for 95 bytes:
```
f=(s,r='')=>s?f(s.slice(l=s<'02'?8:s<'2'|2),r+String.fromCharCode(0+'bkxo'[l&3]+s.slice(0,l))):r
```
[Answer]
## Python 3, 165 bytes
Without Regex
```
x=input();i=0;s=""
while i<len(x):
a=x[i:i+2];c=int(a[0])
if a in["00","01"]:y=8;b=2
elif 1<c<8:y=2;b=16
elif c<2:y=3;b=8
s+=chr(int(x[i:i+y],b));i+=y
print(s)
```
] |
[Question]
[
This challenge is based on the idea of [Plouffle's Inverter](https://oeis.org/wiki/Plouffe's_Inverter).
Write a program in any language that does the following:
* Takes as input a non-negative rational number `X` written in decimal, for example 34.147425.
* Returns a mathematical expression using only non-negative integers, whitespace, parentheses, and the following binary operators:
+ Addition `+`
+ Subtraction `-`
+ Multiplication `*`
+ Division `/`
+ Exponentiation `^`The expression should evaluate to `X`, or at least agree with all the digits of `X`. To continue the example, a correct output could be `13 + 20^(5/4) / 2`, since 13 + 20^(5/4) / 2 = 34.1474252688...
* Output may optionally be written in [Polish notation](https://en.wikipedia.org/wiki/Polish_notation) (prefix) or reverse Polish notation (postfix), i.e. `+ 13 / ^ 20 / 5 4 2` is fine.
The program is subject to the following retrictions:
* Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden! In particular, the program cannot read any external lookup table.
* The source code of the program must be shorten than 1024 characters.
**The program with the lowest average compression ratio will win.**
To determine your average compression ratio, you can to use the following Python script, or write your own equivalent program. [Here](http://pastebin.com/wgukEcvX) is the list of 1000 random numbers.
```
import random
def f(x):
# edit this function so that it will return
# the output of your program given x as input
return "1 + 1"
random.seed(666)
S = 1000 # number of samples
t = 0.0
for n in xrange(0, S):
# pick a random decimal number
x = random.uniform(0, 1000)
# compute the compression ratio
# length of output / length of input
r = len(f(x).translate(None, " +-*/^()")) / float(len(str(x).translate(None, ".")))
t += r
print "Your average compression ratio is:", t / S
```
Good luck!
**NOTES:**
* Whitespaces in the output are not mandatory. Strings like `1+1`, `1 +2`, or `1 + 2`, are all okay. Indeed, the script to compute the score does not count whitespaces and parenthesis in the length of the output. However, note that the use of whitespaces is necessary if you choose Polish or reverse Polish notation.
* Regarding the usual infix notation, the precedence rules are the following: first all exponentiation (`^`), then all divisions (`/`), then all multiplications (`*`), then all additions (`+`) and all subtractions (`-`). But I do not know how much this could matter, since you can use parentheses.
* A way to edit the function `f` in the script above can be the following, however I think that it depends on your operating system; on GNU/Linux it works. Name your program "inverter" (or "inverter.exe") and place it in the same directory as the Python script. Your program should get `X` as the first argument of command line and return the expression in STDOUT. Then edit `f` as follows:
```
import os
def f(x):
return os.popen("./inverter " + str(x)).read()
```
**EDIT:** As a consequence of the comment of Thomas Kwa, now the operators do not contribute to the length of the expression. The challenge should be more "challenging".
[Answer]
## Haskell, 1.08404005439
```
import System.Environment
import Data.Ratio
import Data.Lists
main = do
arg <- fmap head getArgs
let number = read (arg ++ "5")
let (_,_:decs) = span (/= '.') arg
let acc = (read $ "0." ++ (decs >> "0") ++ "4999") :: Double
putStr $ replace " % " "/" $ show $ approxRational number acc
```
This uses the `approxRational` function which converts a floating point number to a fraction with a accuracy of a given epsilon. It simply returns this fraction. As Haskell prints rationals with a `%` in-between, we have to replace it with the division sign `/`.
The accuracy parameter is calculated from the input number. We have to take into account that all the digits have to match, so `4.39` is fine for `4.3` but `4.29` isn't. I append a `5` to the number and the accuracy is a `4999` at the same decimal place as the appended `5`, e.g.
```
12.347 -- input number
12.3475 -- append 5
0.0004999 -- accuracy epsilon for the "approxRational" function.
```
E.g. `34.147425` -> `43777/1282`.
Edit: the rules for accuracy have changed. The test case includes numbers with up to 11 decimal places and all have to match.
Edit II: it seems that the provides Python script doesn't strip off trailing newlines, so I've changed from `putStrLn` to `putStr`.
Edit III: again, new scoring rules
[Answer]
# Mathematica, ~~1.1012~~ 1.10976107226107
```
Rationalize[# + 5 (a = 10^(Floor@Log10@# - Length[First@RealDigits@# //. {a___, 0} :> {a}])), 5 a - 1*^-4 a]~ToString~InputForm &
```
So far, this has the lowest score! Gives the rational with the smallest denominator given the digits. (Sorry for the unreadability, forgot that this wasn't a golf contest for a minute.) Some testing:
```
In[1]:= f=Rationalize[#+5(a=10^(Floor@Log10@#-Length[First@RealDigits@#//.{a___,0}:>{a}])),5a-1*^-4a]~ToString~InputForm&;
In[2]:= f[811.359484104]
Out[2]= 9876679/12173
In[3]:= f[0.000000001]
Out[3]= 1/666666666
In[4]:= f[999.999999999]
Out[4]= 2000021150999/2000021151
```
[Answer]
# Python, 1.25927791772
I'm surprised no one else has tried the obvious approach, which incurs about 26% overhead:
```
from decimal import *
def simplify(numstr):
numdec = Decimal(numstr)
digits = -(numdec.as_tuple().exponent)
num = float(numstr)
return '{0:.0f}'.format(num * 10**digits) + '/10^' + str(digits)
```
This just converts `XX.XXXX` into `XXXXXX/10^4` and so on. For the majority of test numbers, this means converting 12 digits (and an uncounted decimal point) to the same 12 digits plus three more (plus two uncounted symbols).
[Answer]
# JavaScript 1.7056771894771656
Very simple, very bad score
```
F=x=>([x,d]=x.split`.`,n=+(x+d),d=+d.replace(/./g,9)+1,G=(a,b)=>b?G(b,a%b):a,g=G(n,d),(n/g)+'/'+(d/g))
test=[456.119648977, 903.32315398, 434.375496831, 500.626690792, 811.359484104,
553.673742554, 712.174768248, 123.142093787, 814.759762152, 385.493673216,
629.109959804, 891.825687728, 988.817827772, 16.7651557543, 967.455933006,
99.3802569984, 681.552992408, 169.770898456, 921.658967707, 610.512640655,
420.065644152, 702.514151372, 517.04720252, 86.3589856368, 960.117250449,
311.152728003, 620.240077706, 130.232920047, 901.22564153, 528.511688187,
50.841278105, 737.146071519, 836.88270257, 13.9544843156, 45.8723706867,
760.14443626, 256.035110545, 460.972156302, 217.514875811, 34.4165446011,
426.209854826, 500.979753237, 930.071200996, 751.301967463, 817.525354878,
918.861794618, 794.520266221, 531.896652685, 419.295924811, 927.526963939,
989.027382734, 82.1589263516, 965.904769963, 708.295178015, 778.541588483,
410.404428666, 894.612613172, 470.045387404, 460.773246884, 505.524899467,
451.852274382, 417.910824093, 883.45180574, 319.767238241, 544.794416784,
346.361844704, 122.300743514, 517.293385872, 748.134450425, 589.547392631,
870.937945528, 465.607198253, 379.697188157, 215.095671553, 471.696590273,
544.827425571, 883.01895272, 514.893297677, 703.800591, 788.816870867,
777.433484884, 990.615076538, 925.473132794, 494.964321255, 911.643885633,
103.244050895, 425.938382631, 421.075783639, 363.155392963, 301.617712632,
268.237096551, 42.0971441114, 252.071029659, 260.398845137, 433.781658026,
278.550969539, 446.456847155, 466.145132666, 23.1267325005, 92.2303701531,
792.994090972, 100.482658881, 796.600758817, 786.019664003, 328.859998399,
390.221668208, 750.32581915, 332.277362524, 983.205082197, 862.001172096,
823.825060923, 662.455639665, 926.337262367, 618.446017944, 696.465793349,
408.095136772, 519.31659792, 928.091368548, 177.367743543, 980.822594006,
401.832552937, 66.1163636071, 127.511709579, 291.85194129, 11.338995907,
880.568902788, 982.945394792, 491.753920356, 222.011915866, 317.023389252,
601.694693495, 871.340895438, 427.621115915, 886.273120812, 345.688431619,
248.992214068, 738.874584632, 109.03516681, 146.362341902, 447.713463802,
600.947018155, 415.419601291, 369.549014288, 141.697677152, 895.502232931,
528.201404793, 673.817459041, 215.852364841, 164.552047867, 764.085838441,
323.70504093, 197.868519457, 759.91813327, 369.341528152, 768.793424447,
111.674153727, 495.99248701, 363.669738825, 596.082713332, 747.205484326,
666.879146337, 102.908405893, 424.113319661, 476.379228696, 971.353959219,
162.634464034, 761.838583493, 767.799964665, 347.294217881, 353.760366385,
230.905221575, 125.898250349, 565.850510939, 667.61204275, 196.449923318,
279.792505368, 279.034332146, 533.902967966, 57.688797172, 153.08128158,
821.993175733, 982.886617074, 433.447389936, 29.0911289168, 442.422057169,
804.518563086, 500.73307383, 948.932673563, 723.030013363, 572.092408062,
853.660849797, 481.331513905, 942.064561235, 42.4709711072, 982.87325027,
352.171583912, 238.247057259, 823.238147233, 526.013997729, 644.51102393,
366.71793217, 933.49508788, 903.534625763, 857.169528071, 735.780465845,
378.732263357, 12.1875971069, 964.370964223, 419.654315024, 705.414457347,
353.953487281, 501.657967991, 849.706011343, 713.414932699, 827.420809946,
596.719004174, 609.780183857, 826.546581587, 76.33513551, 0.500492073649,
627.694684485, 186.236492637, 360.200893605, 478.625892592, 229.111877611,
423.754891888, 657.973373515, 16.9761882463, 974.491769915, 945.864753785,
237.454051339, 179.687469205, 418.658590265, 714.833543375, 318.816023475,
650.727666516, 488.596054138, 987.542619517, 216.006047902, 80.7125255243,
144.181653533, 266.522883823, 818.574355104, 600.21171237, 895.307289865,
198.329664663, 124.824876993, 31.1227116403, 541.348603643, 542.257190363,
304.231517157, 506.706000025, 84.9413478067, 170.491409724, 229.013799764,
671.014301245, 87.1441069227, 763.676724963, 742.639944243, 435.559778934,
383.882521911, 238.741657776, 647.17907848, 927.512981306, 549.612975568,
791.443454295, 701.809936899, 987.551368536, 91.3122813408, 398.587619734,
847.240295481, 470.53644512, 507.410113063, 540.35838629, 637.883207888,
982.322584309, 975.975221911, 371.493982019, 172.638439006, 747.126873375,
99.5418242164, 309.903703204, 640.628684948, 314.750618166, 146.000991772,
384.388581648, 217.815818267, 733.571499911, 690.506791178, 945.671862182,
344.854300466, 66.9720187046, 600.727439672, 98.4760964868, 295.60483304,
478.855074245, 490.351187811, 479.533769337, 239.205093033, 58.7686847649,
375.442162104, 615.561415277, 974.347539912, 743.935932659, 210.319831557,
782.442881822, 556.123534411, 774.571029531, 821.094541585, 782.478179678,
123.630035193, 652.088033798, 753.122074115, 303.840694329, 449.088557671,
38.4843483532, 173.031570335, 728.973326841, 226.816627623, 119.472479023,
705.899011665, 927.865200825, 157.998809157, 327.490515863, 225.137067487,
501.556087254, 167.031923234, 396.975128016, 826.305341676, 396.340544863,
569.58630546, 694.788762272, 10.1343501944, 369.36109683, 29.8034453658,
916.970188353, 985.814850566, 888.359275561, 689.939392935, 409.116566134,
144.938228502, 67.8210674843, 870.61549803, 563.639796984, 431.618386108,
145.691380363, 350.505911146, 326.638836654, 708.160936271, 345.738257395,
159.932627655, 311.885663889, 229.603462168, 110.746858295, 517.566252532,
231.2683822, 908.329966697, 999.286952896, 700.486300449, 532.543272168,
548.536320153, 248.586068291, 844.156717745, 477.281959996, 964.072712855,
157.863146561, 919.917761996, 187.741733233, 358.474587832, 541.364663045,
297.862474812, 673.876495999, 641.468684483, 934.366789232, 112.750864631,
179.36727691, 744.421362119, 954.914513373, 356.362877284, 642.423557253,
835.156704382, 145.847575914, 917.085464611, 633.00944503, 4.20412765537,
577.177004175, 774.63403371, 846.937269117, 978.134451441, 927.806763324,
3.39763102303, 650.528163199, 347.525631206, 378.956292306, 266.22945414,
175.085055263, 571.539823838, 274.670508282, 835.348780918, 190.612093018,
425.355323169, 283.050471535, 573.262462068, 236.809923974, 86.5812138421,
442.645729259, 376.598156438, 412.17611326, 575.13654395, 76.4906160271,
382.261334337, 419.108062252, 413.347694426, 726.1697083, 738.059837008,
228.479265313, 982.210601477, 693.205052764, 788.820483643, 279.491316277,
381.050856949, 914.836538216, 369.451591691, 828.975002455, 33.0866822761,
552.943575842, 229.194581446, 900.603947989, 697.081349116, 38.8501269177,
599.81038281, 199.242914298, 565.383604483, 241.671424615, 874.199638779,
294.933677019, 238.713921761, 953.886254575, 126.3147347, 156.308580451,
1.01666626965, 410.067483484, 969.052527031, 184.927913357, 282.530928636,
204.745328524, 450.670433109, 129.119772077, 581.256246505, 6.84233762299,
39.4666067908, 865.975624765, 868.401636982, 114.207339514, 921.542812579,
435.593193085, 346.934279797, 830.059520451, 691.952980275, 694.258623119,
548.775134898, 527.057955887, 267.64250387, 113.091700858, 210.713307935,
253.707632265, 832.083850441, 455.161145588, 403.528402677, 237.983049672,
903.782609365, 314.331975332, 209.862002009, 488.057537383, 905.587478495,
929.797161232, 325.793664626, 734.098176437, 519.087164488, 555.076580313,
97.8973027155, 260.92615898, 391.460005616, 187.462694014, 660.460370626,
861.783280209, 751.657352012, 528.280341385, 943.741294674, 204.705877292,
106.65265656, 17.8070044565, 233.101412197, 38.2613365534, 729.385921979,
773.529715946, 429.882870272, 166.782428109, 738.061383178, 381.289974545,
425.98872381, 405.120420988, 672.370449304, 276.696982879, 640.620718977,
244.652935713, 43.3611372718, 611.721720179, 552.336391617, 939.435275549,
337.333914132, 88.3768763311, 537.456873711, 98.6468535441, 601.024140128,
526.374477437, 959.339713851, 794.438445711, 419.365144317, 128.425263651,
894.306756225, 750.689349267, 849.804073407, 144.580034264, 5.21870382078,
316.954557791, 258.037070914, 907.185890899, 821.078874769, 73.0065239329,
902.397997543, 623.811378865, 278.742785334, 546.742289504, 306.338798014,
624.510083572, 278.778694986, 992.433419109, 568.791129496, 800.987198104,
817.781503455, 364.391142069, 229.768701593, 791.500313449, 523.97492671,
711.79222697, 841.514367793, 811.043873744, 312.112640331, 344.686366808,
362.852877349, 908.102021975, 77.1500991776, 383.192419609, 686.951731951,
220.529025627, 867.530056756, 14.3366282672, 408.594160445, 123.165786631,
998.59134116, 548.326927924, 94.1928597561, 324.065711084, 731.488189617,
665.464202995, 306.278211631, 986.173950386, 627.219661146, 333.954277825,
90.2956353646, 162.227112949, 272.511457828, 857.528739452, 503.843643462,
576.629152535, 548.024554676, 363.491120268, 679.874538441, 583.700940158,
106.952792329, 9.38392100562, 338.353858169, 293.571162077, 804.681145319,
767.462050744, 313.643862301, 468.190192547, 572.949085984, 350.221796616,
917.105455473, 303.54853149, 391.390619956, 504.247647998, 93.0135480388,
246.512166315, 908.97228941, 943.218403856, 530.309445245, 309.754887232,
959.789201543, 970.486542083, 797.580736004, 290.319550119, 846.108212188,
532.653666441, 887.339176163, 679.691675058, 912.533817736, 920.067525894,
222.511534133, 96.2743176283, 21.4898199044, 77.2132479765, 371.345880832,
436.959444929, 215.804186286, 399.231434773, 621.793520068, 670.184752989,
898.150427875, 223.481192922, 886.318270113, 516.799097006, 533.999918536,
713.480918784, 917.832970718, 372.788549636, 628.966711322, 944.179767515,
192.101163486, 343.997422161, 804.100009349, 931.645390583, 990.171180084,
260.766724798, 785.681499223, 356.704428677, 700.517830816, 951.584623525,
144.084686297, 259.528412476, 171.745260869, 139.015277926, 901.447521593,
620.501210347, 151.032781338, 46.1159165911, 425.230998623, 894.613060967,
625.179508617, 242.868974022, 106.982050541, 301.464135508, 573.158784529,
688.278622585, 464.999428923, 322.662480912, 110.118666284, 731.557589997,
946.121567036, 495.536592777, 721.786554826, 401.204812967, 523.199107158,
941.414041302, 13.1534875549, 156.596310513, 983.985066957, 371.429892366,
597.927750948, 983.992168593, 170.977999856, 83.6807794877, 817.971626168,
516.088416242, 827.937736139, 859.209288785, 615.315584986, 609.792111637,
554.693516004, 470.967675734, 223.237818744, 990.385531141, 530.824138102,
909.365555497, 994.864631519, 997.447332309, 328.212731713, 307.035914722,
409.123485776, 799.130975525, 967.234526581, 959.671441584, 353.229298604,
420.982728285, 76.7863969552, 28.5449571984, 210.265549753, 913.543941547,
315.091741118, 662.094750123, 852.203603892, 298.207293217, 509.30012338,
65.7679645109, 621.200794815, 935.510670259, 779.330025526, 937.283929747,
756.173490123, 733.792396159, 795.211149457, 302.088313881, 570.641269144,
757.135463505, 242.60845981, 457.593727034, 225.360079221, 142.221548109,
17.6336964488, 360.261380451, 623.475218825, 692.670820913, 584.185971173,
662.861929515, 276.807298644, 480.122225367, 954.608081636, 627.928577217,
459.835351987, 485.168643598, 793.612119132, 654.855590208, 271.958933288,
969.652698005, 976.785064283, 505.116414306, 797.184208528, 628.943525947,
959.160096155, 663.113680213, 768.371354051, 590.4585491, 773.296754989,
407.351603593, 88.0630070991, 905.529072694, 340.59794601, 439.12099902,
233.540790202, 364.088450076, 470.123174021, 102.448882161, 608.789225571,
392.768415134, 713.100614552, 209.2003898, 62.2154487033, 372.921756097,
492.623365519, 581.128110129, 820.570542768, 339.686321984, 713.824072462,
999.045113081, 306.938298797, 184.480805204, 465.144186806, 753.870865996,
78.4248974773, 914.793550949, 952.526126809, 745.524994917, 138.306312094,
727.779875346, 561.393678162, 772.777064716, 72.7542234799, 504.766493657,
753.225048814, 171.848362302, 941.292665664, 441.751526079, 63.0349316166,
535.273783514, 629.040768898, 808.08324249, 457.787416804, 187.372504534,
418.1266562, 433.695070727, 776.092568964, 211.004041498, 740.766035298,
816.391594543, 458.991042003, 94.0308738235, 624.589391691, 118.430830788,
178.888039553, 905.16710481, 148.542033271, 962.242139722, 35.5229349814,
716.472840429, 587.99823034, 252.557765324, 37.8879245566, 399.689202524,
383.425506008, 464.748020898, 308.786698798, 583.669994119, 231.746308268,
524.76171028, 897.374397044, 577.218755662, 562.645278506, 434.940887118,
254.327344231, 540.874257344, 123.680835723, 539.503191151, 816.484752836,
961.415099734, 349.660216271, 596.159995894, 595.762432693, 955.539005194,
687.809440375, 571.725613886, 308.13021345, 617.471476595, 701.003582396,
3.96581420188, 185.987820184, 48.1246847598, 539.131050625, 989.571379915,
249.821643429, 725.895300104, 711.034103146, 74.8291260662, 721.572101122,
142.992636014, 419.591421178, 984.914852359, 36.7363617464, 133.19819475,
380.054235605, 692.83285665, 827.597995374, 995.818667532, 126.589103128,
682.800070236, 466.330036969, 302.143073837, 786.240218566, 299.551583986,
430.07770804, 483.534119703, 473.617334239, 1.64416431436, 953.126991927,
251.892147628, 366.320222366, 137.6878957, 287.000037146, 348.549654758,
55.6668003422, 65.1444653143, 810.336733005, 247.448273359, 514.541152359,
545.299341596, 740.254480746, 607.431747363, 176.075079982, 922.502042696,
585.799132666, 5.53670276888, 304.467968825, 298.915106192, 561.78882135,
42.5914472262, 486.800635021, 61.0833598622, 944.347739678, 668.746271709,
756.586266764, 408.787974993, 161.622855, 76.9222121123, 273.398447299,
224.158188706, 869.44674983, 58.3114312618, 490.559449132, 439.137943547,
816.959032357, 73.0577752895, 613.711059891, 899.395509193, 230.235211112,
651.089914878, 418.795635547, 873.424446884, 897.792771782, 704.102385815,
518.126528796, 545.099037865, 104.410545145, 416.115870896, 617.579630637,
333.700660761, 698.454752336, 323.794560581, 614.778464988, 978.982432433,
656.459219246, 311.387615291, 262.993283002, 98.703803798, 316.038737757,
511.251635007, 597.716611457, 837.873132231, 985.745340467, 653.714321915,
759.002380543, 257.908251778, 764.546995782, 336.260865935, 746.604123567,
640.209566004, 448.844970845, 925.255475065, 972.485574416, 47.0841050739,
231.133339622, 994.520385942, 766.591528041, 355.476025092, 325.525579517,
591.707824382, 302.51618806, 250.791496027, 325.751078168, 148.78604636,
488.176440838, 760.361648381, 213.189413642, 509.565395067, 284.468094856,
567.126065507, 828.024492382, 938.902419548, 141.420420877, 719.989392811,
854.189823836, 545.746745299, 713.177111859, 800.749418944, 217.781813549,
692.416094897, 703.129981045, 607.928079305, 876.072026145, 983.933471359,
824.755945781, 472.143208136, 22.2541577801, 640.071388089, 52.8148724127,
646.607940231, 228.870749952, 824.59255967, 20.4078078906, 211.860134988,
176.392620646, 786.744977859, 983.183973543, 738.585099683, 75.976724176,
49.4604753001, 628.2042889, 991.358549436, 526.125428702, 836.487360003,
216.533860839, 654.106395874, 65.4049854833, 858.352891393, 777.146190395,
630.588944701, 141.352770092, 501.454292251, 792.956685991, 709.053823609];
console.log=(...x)=>O.textContent+=x.join` `+`\n`
console.log(test.length)
var r=0
test.forEach(v=>{
v=v+''; // to decimal string
var x=F(v);
check = v==eval(x)
if (!check) console.log ("Error",v,x,eval(x));
else
// console.log(v,x),
r+=x.length/v.length
});
console.log(r/1000)
```
```
<pre id=O></pre>
```
[Answer]
# Python, 1.9901028749
Continued fractions turn out to not be a serious contender, unfortunately.
```
from fractions import *
def simplify(numstr):
frac = Fraction(numstr)
terms = []
while frac>0:
terms.append(int(frac))
frac -= int(frac)
if frac > 0:
frac = 1/frac
for n in range(0,len(terms)):
temp = 0
for i in range(n,0,-1):
temp = 1.0/(terms[i]+temp)
# print i, terms[i], temp
temp += terms[0]
# print repr(temp)
if repr(temp)[:len(numstr)] == numstr:
break
return '+1/('.join([str(x) for x in terms[:n+1]]) + ')' * n
```
examples:
```
141.352770092 141+1/(2+1/(1+1/(5+1/(20+1/(20+1/(1+1/(1)))))))
501.454292251 501+1/(2+1/(4+1/(1+1/(31+1/(1+1/(4+1/(1+1/(1+1/(2)))))))))
792.956685991 792+1/(1+1/(22+1/(11+1/(2+1/(6+1/(1+1/(2+1/(1+1/(2)))))))))
709.053823609 709+1/(18+1/(1+1/(1+1/(2+1/(1+1/(1+1/(1+1/(10+1/(58)))))))))
```
[Answer]
# Python, 1.10900874126
Actually evaluating the continued fractions in my previous answer yields the equivalent of @LegionMammal978 s Mathematic answer, which I think is the naive optimum. Doing better than this will require getting creative with representing the integers, possibly including searching for sub-optimal fractions to get to easier-to-represent integers.
```
from fractions import *
def simplify(numstr):
frac = Fraction(numstr)
terms = []
while frac>0:
terms.append(int(frac))
frac -= int(frac)
if frac > 0:
frac = 1/frac
for n in range(0,len(terms)):
temp = Fraction(0)
for i in range(n,0,-1):
temp = Fraction(1)/Fraction(terms[i]+temp)
# print i, terms[i], temp
temp += terms[0]
if repr(float(temp))[:len(numstr)] == numstr:
break
return str(temp.numerator) + '/' + str(temp.denominator)
```
examples:
```
141.352770092 == 1992650/14097
501.454292251 == 5041120/10053
792.956685991 == 33373961/42088
709.053823609 == 154592878/218027
```
] |
[Question]
[
Given a deck consisting of **N** copies of cards with integer values [**1**,**M**] for a total of **N\*M** cards, compute the probability that a card with the value of **1** is adjacent to a card with the value of **2**.
Your solution may be exact or approximated, and it does not need to be the same for every run given the same inputs. The given answer should be within +/-5% of the true solution (barring really rare chances the RNG is not in your favor). Your program should give the answer in a reasonable amount of time (say, less than 10 minutes on whatever hardware you have). You may assume that **M** and **N** are reasonable small and error checking is not required.
The deck is *not* cyclical, so if the first card is a **1** and the last card is a **2**, this does not meet the adjacency requirements.
As a test case, for **N=4** and **M=13** (a standard 52-card deck) the expected solution is ~48.6%.
Here is an example un-golfed implementation in Python+NumPy using random shuffles:
```
from __future__ import division
from numpy import *
def adjacent(N, M):
deck = array([i for i in range(1, M+1)]*N)
trials = 100000
count = 0
for i in range(trials):
random.shuffle(deck)
ores = (deck == 1)
tres = (deck == 2)
if(any(logical_and(ores[1:], tres[:-1])) or
any(logical_and(ores[:-1], tres[1:]))):
count += 1
return count/trials
```
The output may be in any form you find convenient (function return value, terminal output, file, etc.), and input may be in any form you find convenient (function parameter, terminal input, command line arg, etc.)
Standard loop-holes apply.
This is code golf, the shortest code (in bytes) wins.
# Leaderboard
```
var QUESTION_ID=67431,OVERRIDE_USER=31729;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Pyth, ~~23~~ 22 bytes
```
csm}1sM.:.S*vzUQ2J^T4J
```
Runs 10000 iterations. The number can be changed at no byte cost. Input is newline separated. Takes about 9 seconds on my computer.
[Demonstration](https://pyth.herokuapp.com/?code=csm%7D1sM.%3A.S%2avzUQ2J%5ET4J&input=4%0A13&debug=0)
```
csm}1sM.:.S*vzUQ2J^T4J
J^T4 J = 10000
m J Do the following J times.
*vzUQ Set up the deck. (0 .. n-1, repeated m times.)
.S Shuffle the deck.
.: 2 Find all 2 elment substrings.
sM Add them up.
}1 Check if any pairs add to 1 ([0, 1] or [1, 0])
s Add up the results (True = 1, False = 0)
c J Divide by J.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 44 ~~46~~ bytes
This uses [release 3.1.0](https://github.com/lmendo/MATL/releases/tag/3.1.0) of the language, which is earlier than this challenge.
The computation is done with a loop that draws 1000 random realizations. It takes a couple of seconds to run. It could be done faster in a vectorized way. Input is of the form `[N M]`.
**Old version**: generates a random deck of cards and checks it twice: first in the forward and then in the backward direction.
```
itpw1)1e3:"2$twZ@w/Y]t1HhXfnwH1hXfn|bb]xxN$hYm
```
**New version**: generates a random deck of cards and then appends a flipped version of it with a `0` in between. That way checking can be done just once, in the forward direction. This saves two bytes.
```
itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm
```
### Example
```
>> matl itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm
> [4 13]
0.469
```
### Explanation
```
i % input: [N M]
tpw1) % produce N*M and N
1e3:" % repeat 1000 times
2$twZ@w/Y] % produce random deck of cards from 1 to N*M
tP0whh % append 0 and then flipped version of deck
1Hh % vector [1 2]
Xf % find one string/vector within another
ng % was it found at least once?
bb % bubble up element in stack, twice
] % end
xx % delete top of the stack, twice
N$h % vector with all elements in stack
Ym % mean value
```
[Answer]
# LabVIEW, 58 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
creats card arrays then shuffles them. Search for 1s then check adjacent cards for 2s.
[](https://i.stack.imgur.com/SAenf.gif)
[Answer]
# Pyth, 16 bytes
```
JE?>J1-1^-1c2JQZ
```
[Demonstration.](https://pyth.herokuapp.com/?code=JE%3F%3EJ1-1%5E-1c2JQZ&input=4%0A13&debug=0)
This follows the
* make an educated guess,
* check that it's close enough,
* repeat
strategy of programming. The winning educated guess in this case is
```
1 - (1 - 2 / M) ** N
```
which roughly says that there are `N` chances to fall into buckets, and fraction of valid buckets is `2 / M`. The buckets being slots places next to `0`s, and the chances being `1`s.
The error never seems to go above 3% (surprisingly), and seems to converge to 0% as the parameters get larger (as I would expect).
Input is newline separated.
```
Q Q = eval(input())
JE J = eval(input())
?>J1 if J > 1
-1^-1c2JQ then 1 - (1 - 2 / J) ** Q
Z else 0
```
You can save a character if you accept the plainly obvious fact that `False == 0`, and do `JE&>J1-1^-1c2JQ` instead.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~44~~ 38 bytes
This also uses MATL [version 3.1.0](https://github.com/lmendo/MATL/releases/tag/3.1.0), which is earlier than this challenge.
New version, thanks to Luis Mendo for saving 4 bytes!
```
iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/
```
Old version (44 bytes):
```
OiitXIx*XJx1e4XH:"JJZrI\[1 1]3X5,3$X+1=a+]H/
```
Explanation
```
i % take input for N
i % take input for M
XI % save M into clipboard I
*XJ % multiply N and M and store in clipboard J
x % clear the stack
O % make a zero to initialise count of pairs
1e4XH:" % 1e4=10000, XH saves into clipboard H, : makes the vector 1:1e4
% which is used to index a for loop, started using "
JZ@ % Use randperm to generate a random permutation of the vector 1:N*M
I\ % take the result mod M, now each card has a value one less than before
TTo3X53$X+ % convolve vector of card values with [1 1] to do pairwise summation
1=a % find if any sums equal 1, which means there is a [0 1] or [1 0]
+ % add the logical value to the count of pairs
]
H/ % divide the count by the number of deals to get the probability
```
For example,
```
>> matl 'iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/'
> 4
> 13
0.4861
```
Note (21/5/16): As of MATL release 18.0.0, `X+` has been removed, but `Y+` can be used in its place. The changes from MATL version 3.1.0 to 18.0.0 mean that this answer can now be written in just 31 bytes, `*xO1e4:"2:Gtb*Z@w\TT2&Y+1=ah]Ym`.
[Answer]
## Mathematica, ~~93~~ ~~92~~ 91 bytes
```
N@Count[RandomSample@Flatten[Range@#~Table~{#2}]~Table~{a=1*^5},{b=___,1,2,b}|{b,2,1,b}]/a&
```
Still looking for a closed form...
] |
[Question]
[
# Introduction
In this challenge, your task is to implement a collection of simple functions that together form a usable mini-library for simple probability distributions.
To accommodate some of the more esoteric languages people like to use here, the following implementations are acceptable:
1. A code snippet defining a collection of named functions (or closest equivalents).
2. A collection of expressions that evaluate to named or anonymous functions (or closest equivalents).
3. A single expression that evaluates to several named or anonymous functions (or closest equivalents).
4. A collection of independent programs that take inputs from command line, STDIN or closest equivalent, and output to STDOUT or closest equivalent.
# The functions
You shall implement the following functions, using shorter names if desired.
1. `uniform` takes as input two floating point numbers `a` and `b`, and returns the uniform distribution on `[a,b]`. You can assume that `a < b`; the case `a ≥ b` is undefined.
2. `blend` takes as inputs three probability distributions `P`, `Q` and `R`. It returns a probability distribution `S`, which draws values `x`, `y` and `z` from `P`, `Q` and `R`, respectively, and yields `y` if `x ≥ 0`, and `z` if `x < 0`.
3. `over` takes as input a floating point number `f` and a probability distribution `P`, and returns the probability that `x ≥ f` holds for a random number `x` drawn from `P`.
For reference, `over` can be defined as follows (in pseudocode):
```
over(f, uniform(a, b)):
if f <= a: return 1.0
else if f >= b: return 0.0
else: return (b - f)/(b - a)
over(f, blend(P, Q, R)):
p = over(0.0, P)
return p*over(f, Q) + (1-p)*over(f, R)
```
You can assume that all probability distributions given to `over` are constructed using `uniform` and `blend`, and that the only thing a user is going to do with a probability distribution is to feed it to `blend` or `over`.
You can use any convenient datatype to represent the distributions: lists of numbers, strings, custom objects, etc.
The only important thing is that the API works correctly.
Also, your implementation *must* be deterministic, in the sense of always returning the same output for the same inputs.
## Test cases
Your output values should be correct to at least two digits after the decimal point on these test cases.
```
over(4.356, uniform(-4.873, 2.441)) -> 0.0
over(2.226, uniform(-1.922, 2.664)) -> 0.09550806803314438
over(-4.353, uniform(-7.929, -0.823)) -> 0.49676329862088375
over(-2.491, uniform(-0.340, 6.453)) -> 1.0
over(0.738, blend(uniform(-5.233, 3.384), uniform(2.767, 8.329), uniform(-2.769, 6.497))) -> 0.7701533851999125
over(-3.577, blend(uniform(-3.159, 0.070), blend(blend(uniform(-4.996, 4.851), uniform(-7.516, 1.455), uniform(-0.931, 7.292)), blend(uniform(-5.437, -0.738), uniform(-8.272, -2.316), uniform(-3.225, 1.201)), uniform(3.097, 6.792)), uniform(-8.215, 0.817))) -> 0.4976245638164541
over(3.243, blend(blend(uniform(-4.909, 2.003), uniform(-4.158, 4.622), blend(uniform(0.572, 5.874), uniform(-0.573, 4.716), blend(uniform(-5.279, 3.702), uniform(-6.564, 1.373), uniform(-6.585, 2.802)))), uniform(-3.148, 2.015), blend(uniform(-6.235, -5.629), uniform(-4.647, -1.056), uniform(-0.384, 2.050)))) -> 0.0
over(-3.020, blend(blend(uniform(-0.080, 6.148), blend(uniform(1.691, 6.439), uniform(-7.086, 2.158), uniform(3.423, 6.773)), uniform(-1.780, 2.381)), blend(uniform(-1.754, 1.943), uniform(-0.046, 6.327), blend(uniform(-6.667, 2.543), uniform(0.656, 7.903), blend(uniform(-8.673, 3.639), uniform(-7.606, 1.435), uniform(-5.138, -2.409)))), uniform(-8.008, -0.317))) -> 0.4487803553043079
```
[Answer]
# Ruby, 103
```
u=b=->*a{a}
o=->f,d{d[2]?(p=o[0,d[0]])*o[f,d[1]]+(1-p)*o[f,d[2]]:(f<a=d[0])?1:(f>b=d[1])?0:(b-f)/(b-a)}
```
Defines three lambdas, `u`, `b`, and `o`. `u` and `b` just create two-element and three-element arrays respectively. `o` assumes a two-element array is a uniform distribution and a three-element one is a blend of three distributions. In the latter case it calls itself recursively.
[Answer]
# MATLAB, 73
Time for a little "functional programming" in MATLAB. These are 3 anonymous functions. Uniform and blend are called the same way as the examples, but for `over` the arguments should be swapped. I don't really need an `over` since the first two return functions, but as a formality `feval` is a function that can call a function.
```
%uniform
@(a,b)@(x)(x<b)*min(1,(b-x)/(b-a))
%blend
@(P,Q,R)@(x)P(0)*(Q(x)-R(x))+R(x)
%over
@feval
```
Now MATLAB's parsing and evaluation system is a little wonky to say the least. It doesn't allow you to directly call a function that was returned from a function. Instead, one must first save the result to a variable. The 4th example could be done as follows:
```
x=uniform(-5.233,3.384);y=uniform(2.767,8.329);z=uniform(-2.769,6.497);over(blend(x,y,z),0.738)
```
However, it is possible to get around this by using `feval` to call all the functions. If the following definitions are used, then the examples can be evaluated exactly as they are written.
```
uniform=@(a,b)@(x)(x<b)*min(1,(b-x)/(b-a))
blend=@(P,Q,R)@(x)feval(P,0)*(feval(Q,x)-feval(R,x))+feval(R,x)
over=@(x,f)feval(f,x)
```
[Answer]
# CJam, 58 bytes
```
{[\]}:U;
{[@]}:B;
{_,2={~1$-@@-\/0e>1e<}{6Yb@f*\.{O})[_1@-].*:+}?}:O;
```
These are postfix operators that work on the stack: `2.0 1.0 3.0 U O` is `over(2, uniform(1, 3))`.
### Score count
`{[\]}` is the function itself, `:U;` assigns it to the name `U` and pops it. Essentially this isn't part of the function, so by score counting rule 2, I'd only have to count `{[\]}`. `B` is defined similarly.
However, `O` is recursive, and if I don't specify a name, there's no way to recurse. So here, I'd be inclined to count the `:O;` part. Then my score is `5+5+48=58` bytes in total.
### Explanation
`U` pops two arguments and makes a pair in reverse order: `a b => [b a]`.
`B` pops three arguments and makes a triple in rotated order: `a b c => [b c a]`.
`O`'s structure is as follows:
```
{ }:O; Define O as this function:
_,2= ? If the argument list's length is 2:
{~Γ} Append the list to the stack and execute subprogram Γ.
{~Δ} Else, do the same, but execute subprogram Δ.
```
Subprogram *Γ* handles uniform distributions:
```
Executed ops Explanation Stack contents
============ =========== ==============
Initial f; b; a
1$ Copy b f; b; a; b
- Difference f; b; (a-b)
@@ Rotate x2 (a-b); f, b
- Difference (a-b); (f-b)
\/ Flip divide (f-b)/(a-b)
0e> Clamp low max(0, (f-b)/(a-b))
1e< Clamp high min(1, max(0, (f-b)/(a-b)))
```
Subprogram *Δ* handles blended distributions:
```
Executed ops Explanation Stack contents
============ =========== ==============
Initial f; [Q R P]
6Yb Push [1,1,0] f; [Q R P]; [1 1 0]
@ Rotate [Q R P]; [1 1 0]; f
f* Multiply each [Q R P]; [f f 0]
\ Swap [f f 0]; [Q R P]
.{O} Pairwise O [q r p]
) Uncons [q r] p
[_1@-] [p, 1-p] [q r] [p 1-p]
.*:+ Dot product q*p+r*(1-p)
```
[Answer]
# Mathematica, ~~129~~ 116 bytes
```
u=UniformDistribution@{##}&;b=If[x<0,z,y]~TransformedDistribution~{x\uF3D2#,y\uF3D2#2,z\uF3D2#3}&;o=Probability[x>=#,x\uF3D2#2]&
```
`u`, `b` and `o` are `uniform`, `blend`, and `over` respectively.Wrapper over the standard functions. Replace the `\uF3D2`s with the 3-byte character. Just returns `0` and `1` for cases 1, 4, and 7.
[Answer]
## Python, 146 bytes
```
u=lambda*a:a
b=u
x=lambda f,a,b:[int(f<=a),(b-f)/(b-a)][a<f<b]
y=lambda f,p,q,r:o(0,p)*o(f,q)+(1-o(0,p))*o(f,r)
o=lambda f,p:[x,y][len(p)-2](f,*p)
```
Same strategy as histocrat's Ruby answer, but in Python. To do recursion without a Z-combinator (which would be costly), `x` and `y` are defined as helper functions that evaluate `over` for 2- and 3-length argument tuples (`uniform` and `blend` arguments, respectively).
[Test cases on ideone](http://ideone.com/C0zWX6)
[Answer]
# Matlab, 104 bytes
I hope this is still valid, as this only works for distributions with support in [-10,10] which is the requirement for languages that have no floating point support. The support vector and the accuracy can be easily adjusted by just altering corresponding numbers. `u,o,b` is for `uniform,blend,over`. The pdf is just represented as a discrete vector. I think this approach can easily be transferred to other languages.
```
D=1e-4;X=-10:D:10;
u=@(a,b)(1/(b-a))*(a<X&X<b);
o=@(x,d)sum(d.*(X>x))*D;
b=@(p,q,r)o(0,p).*q+(1-o(0,p)).*r;
```
You can test them if you define those functions first and then just paste this code:
```
[o(4.356, u(-4.873, 2.441)) , 0.0;
o(2.226, u(-1.922, 2.664)) , 0.09550806803314438;
o(-4.353, u(-7.929, -0.823)) , 0.49676329862088375;
o(-2.491, u(-0.340, 6.453)) , 1.0;
o(0.738, b(u(-5.233, 3.384), u(2.767, 8.329), u(-2.769, 6.497))) , 0.7701533851999125;
o(-3.577, b(u(-3.159, 0.070), b(b(u(-4.996, 4.851), u(-7.516, 1.455), u(-0.931, 7.292)), b(u(-5.437, -0.738), u(-8.272, -2.316), u(-3.225, 1.201)), u(3.097, 6.792)), u(-8.215, 0.817))) , 0.4976245638164541;
o(3.243, b(b(u(-4.909, 2.003), u(-4.158, 4.622), b(u(0.572, 5.874), u(-0.573, 4.716), b(u(-5.279, 3.702), u(-6.564, 1.373), u(-6.585, 2.802)))), u(-3.148, 2.015), b(u(-6.235, -5.629), u(-4.647, -1.056), u(-0.384, 2.050)))) , 0.0;
o(-3.020, b(b(u(-0.080, 6.148), b(u(1.691, 6.439), u(-7.086, 2.158), u(3.423, 6.773)), u(-1.780, 2.381)), b(u(-1.754, 1.943), u(-0.046, 6.327), b(u(-6.667, 2.543), u(0.656, 7.903), b(u(-8.673, 3.639), u(-7.606, 1.435), u(-5.138, -2.409)))), u(-8.008, -0.317))) , 0.4487803553043079]
```
] |
[Question]
[
Did you know that [the Euclidean algorithm is capable of generating traditional musical rhythms](http://cgm.cs.mcgill.ca/~godfried/publications/banff.pdf)? We'll see how this works by describing a similar, but slightly different algorithm to that in the paper.
Pick a positive integer `n`, the total number of beats, and a positive integer `k`, the number of beats which are sounded (notes). We can think of the rhythm as a sequence of `n` bits, `k` of which are 1s. The idea of the algorithm is to distribute the 1s as evenly as possible amongst the 0s.
For example, with `n = 8` and `k = 5`, we start with 5 ones and 3 zeroes, each in its own sequence:
```
[1] [1] [1] [1] [1] [0] [0] [0]
```
At any point we will have two types of sequences — the ones at the start are the "core" sequences and the ones at the end are the "remainder" sequences. Here the cores are `[1]`s and the remainders are `[0]`s. As long as we have more than one remainder sequence, we distribute them amongst the cores:
```
[1 0] [1 0] [1 0] [1] [1]
```
Now the core is `[1 0]` and the remainder is `[1]`, and we distribute again:
```
[1 0 1] [1 0 1] [1 0]
```
Now the core is `[1 0 1]` and the remainder is `[1 0]`. Since we only have one remainder sequence, we stop and get the string
```
10110110
```
[This](https://soundcloud.com/sp3000/8-5-euclidean-rhythm-1) is what it sounds like, repeated 4 times:
Here's another example, with `n = 16` and `k = 6`:
```
[1] [1] [1] [1] [1] [1] [0] [0] [0] [0] [0] [0] [0] [0] [0] [0]
[1 0] [1 0] [1 0] [1 0] [1 0] [1 0] [0] [0] [0] [0]
[1 0 0] [1 0 0] [1 0 0] [1 0 0] [1 0] [1 0]
[1 0 0 1 0] [1 0 0 1 0] [1 0 0] [1 0 0]
[1 0 0 1 0 1 0 0] [1 0 0 1 0 1 0 0]
1001010010010100
```
Note how we terminated on the last step with two core sequences and no remainder sequences. [Here](https://soundcloud.com/sp3000/16-6-euclidean-rhythm) it is, repeated twice:
## Input
You may write a function or a full program reading from STDIN, command line or similar. Input will be two positive integers `n` and `k <= n`, which you may assume is in either order.
## Output
Your task is to output the generated rhythm as an `n` character long string. You may pick any two distinct printable ASCII characters (0x20 to 0x7E) to represent notes and rests.
## Test cases
The following test cases use `x` to represent notes and `.`s to represent rests. Input is given in the order `n`, then `k`.
```
1 1 -> x
3 2 -> xx.
5 5 -> xxxxx
8 2 -> x...x...
8 5 -> x.xx.xx.
8 7 -> xxxxxxx.
10 1 -> x.........
11 5 -> x.x.x.x.x..
12 7 -> x.xx.x.xx.x.
16 6 -> x..x.x..x..x.x..
34 21 -> x.xx.x.xx.xx.x.xx.x.xx.xx.x.xx.x.x
42 13 -> x...x..x..x..x...x..x..x..x...x..x..x..x..
42 18 -> x..x.x.x..x.x.x..x.x.x..x.x.x..x.x.x..x.x.
```
## Scoring
This is code-golf, so the code in the fewest bytes wins.
[Answer]
# CJam, ~~37~~ ~~34~~ ~~30~~ ~~27~~ 24 bytes
*3 bytes saved by user23013.*
```
q~,f>{_(a-W<}{e`:a:e~z}w
```
This takes the input as `k` first, `n` second. It uses `1` and `0` to indicate notes and rests, respectively.
[Try it here.](http://cjam.aditsu.net/#code=q~%2Cf%3E%7B_(a-W%3C%7D%7Be%60%3Aa%3Ae~z%7Dw&input=21%2034) Alternatively, [here is a test harness](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3DS%2FW%25S*%3AQ%3B%0A%0AQ~%2Cf%3E%7B_(a-W%3C%7D%7Be%60%3Aa%3Ae~z%7Dw%0A%0As%2210%22%22x.%22eroNo%7D%2F&input=1%201%20%20%20%20-%3E%20%20x%0A3%202%20%20%20%20-%3E%20%20xx.%0A5%205%20%20%20%20-%3E%20%20xxxxx%0A8%202%20%20%20%20-%3E%20%20x...x...%0A8%205%20%20%20%20-%3E%20%20x.xx.xx.%0A8%207%20%20%20%20-%3E%20%20xxxxxxx.%0A10%201%20%20%20-%3E%20%20x.........%0A11%205%20%20%20-%3E%20%20x.x.x.x.x..%0A12%207%20%20%20-%3E%20%20x.xx.x.xx.x.%0A16%206%20%20%20-%3E%20%20x..x.x..x..x.x..%0A34%2021%20%20-%3E%20%20x.xx.x.xx.xx.x.xx.x.xx.xx.x.xx.x.x%0A42%2013%20%20-%3E%20%20x...x..x..x..x...x..x..x..x...x..x..x..x..%0A42%2018%20%20-%3E%20%20x..x.x.x..x.x.x..x.x.x..x.x.x..x.x.x..x.x.) which runs all of the given test cases (swapping the input order) and also reformats the output to use `x` and `.` for easier comparison with the reference solutions. (The results appearing in the input of the test harness are discarded before running the code. They could be safely removed without affecting the program.)
## Explanation
```
q~ e# Read and eval the input, dumping k and n on the stack.
, e# Create a range [0 .. n-1]
f> e# For each of them, check if it's less than k.
e# This gives k 1s and n-k 0s.
{ }{ }w e# While the first block yields a truthy result, execute
e# the second block.
_ e# Duplicate the array.
(a- e# Remove all instances of core sequences.
W< e# Remove one remainder sequence if there is one. This
e# gives an empty array (falsy) whenever there are less
e# than two remainder sequences.
e` e# Run-length encode. I.e. this turns an array into a list
e# of pairs of run-length and element.
:a:e~ e# Wrap each RLE pair in an array and RLD it. This
e# partitions the array into cores and remainders.
z e# Zip the two parts, interleaving cores and remainders.
```
This process very deeply nested arrays, but the important part is that all cores (and all remainders) always have the same nested structure, so they are still equal to each other. CJam automatically prints the stack contents at the end of the program and omits array delimiters entirely, hence this structure does not affect the output either.
[Answer]
# Haskell, 125 bytes
```
r=replicate
g z(a:b)(c:d)=g((a++c):z)b d
g z x y=(z,x++y)
f(x,y)|length y>1=f$g[]x y|1<2=concat$x++y
n#k=f(r k "x",r(n-k)".")
```
Usage example: `42 # 13` -> `x...x..x..x..x...x..x..x..x...x..x..x..x..`.
`f` takes two parameters: core and remainder list. It either zips both lists (via `g`) and calls itself again or stops if the remainder is too short. The main function `#` creates the starting lists and calls `f`.
[Answer]
# Python, 85
```
f=lambda n,k,a='1',b='0':n-k<2and a*k+b*(n-k)or[f(n-k,k,a+b,b),f(k,n-k,a+b,a)][2*k>n]
```
The natural recursive solution. The parameters `(n,k,a,b)` represent a core of `k` `a`'s followed by a remainder of `n-k` `b'`s.
This solution is inefficient because both recursive calls to `f` are evaluated, causing an exponential number of calls.
I tried to compress the conditional invocation of `f` like
```
f(max(n-k,k),min(n-k,k),a+b,[a,b][2*k<n])
f(*[n-k,k,k,n-k,b,a][2*k>n::2]+[a+b])
```
but none turned out shorter.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/40246/edit)
There's an old story about a stonecutter who was never satisfied with what he was. He wished he could become the sun, and so he was. Blocked by the clouds, he wished to be - and became - a cloud. When the wind blew, he wished himself into being the wind. Stopped by the mountain, he wished to be a mountain, and thus became one. Soon, however, he was being hacked at by a stonecutter, and wished to be a stonecutter.
Similarly, your task is to write a program which is never satisfied with the language it is in. Your program must output a set of regex replacements to turn it into a different language. And so on.
## Rules
1. Write a program in a language of your choice.
2. The program should output a series of at least two segments. A segment is a bunch of text, separated by semicolons. However, if a semicolon is contained within a regex, such that breaking it up there will result in invalid syntax, it does not separate segments. See the example.
3. The first segment is a regex pattern to find, and the second segment is the replacement pattern. The third is another "find" pattern, and the fourth is a "replace" pattern, and so on.
4. Apply the regex patterns to the program. Replace the pattern on the first segment with one on the second; replace the third pattern with the one on the fourth, and so on.
5. The result should be a program in a different language, which, itself, follows rules 2 to 4.
6. The languages used must form an infinite, repeating cycle.
* For example, Python -> PHP -> C++ -> Python -> PHP -> C++ -> Python -> ...
7. Your score is the period of the cycle. Ties are broken by shortest initial code length.
* In the above example, the score is three.
8. In each iteration of the cycle, no language may be used more than once.
9. For rules 5 and 7, compatible languages (C and C++) and different versions of the same language (Python 2 and Python 3) are considered the same.
10. The programs themselves do not need to repeat.
* In the above example, the first and fourth programs may be different.
11. Any version of regex is acceptable, but the same must be used for all the programs.
12. The total output for each program may not exceed 100 characters.
13. Each output must contain instructions to actually change the program. That is, no two consecutive programs in the cycle may be the same.
## Example
**Python -> Ruby -> Python -> ...**
```
print "uts;Z;rint;uts;Z(?=;Z);rint"
```
Outputs:
```
uts;Z;rint;uts;Z(?=;Z);rint
```
The segments are:
```
FIND ; REPLACE
uts ; Z
rint ; uts
Z(?=;Z ; rint (breaking the first segment in two would result in invalid syntax)
```
Applying the regex replacements, in order, gives us:
```
print "Z;Z;rint;Z;Z(?=;Z);rint" # replace each "uts" with "Z"
puts "Z;Z;uts;Z;Z(?=;Z);uts" # replace each "rint" with "uts"
puts "rint;Z;uts;rint;Z(?=;Z);uts" # replace each "Z" followed by ";Z" with "rint"
```
Running the last line gives us the instructions to turn this back into Python code.
[Answer]
## 2 Languages: Python, Ruby; ~~33~~ 29 bytes
Here is another way to do Python and Ruby, that's a bit shorter than the one in the challenge:
```
Python: print'^;puts"^.*?\\42#\\73"#'
prints: ^;puts"^.*?\42#\73"#
Ruby: puts"^.*?\42#\73"#print'^;puts"^.*?\\42#\\73"#'
prints: ^.*?"#;
```
It shouldn't be *too* difficult to add PHP into the mix.
[Answer]
# 2 languages: Python 2 and Befunge-93, 77 bytes
After *carefully reading the rules this time*, I came up with a real answer. It won't win any prizes, but Befunge is just too fun to program in.
```
u=u">>>>>:#,_@;Z;print;>>>>>:#,_@;Z(?=;Z);print;<v;Y;u;<v;Y(?=;Y);u"
print u
```
This Python program outputs:
```
>>>>>:#,_@;Z;print;>>>>>:#,_@;Z(?=;Z);print;<v;Y;u;<v;Y(?=;Y);u
```
Which yields these replacements:
```
FIND REPLACE
>>>>>:#,_@ Z
print >>>>>:#,_@
Z(?=;Z) print
<v Y
u <v
Y(?=;Y) u
```
Which turns the program into this Befunge program:
```
<v=<v"print;Z;>>>>>:#,_@;print;Z(?=;Z);>>>>>:#,_@;u;Y;<v;u;Y(?=;Y);<v"
>>>>>:#,_@ <v
```
Maybe I'll see if I can make it one line. Frankly, I'm a little surprised Befunge works for this sort of problem at all.
(Sorry for deleting and undeleting a bunch; I was panicking for a second because I thought the program might not have worked.)
] |
[Question]
[
## Introduction
You are the police chief of the NYPD and you have been tasked to position police officers so that all of the streets are patrolled. Your squad is short-staffed, however, meaning that you need to position as little officers as possible.
## Challenge
Given a map of blocks, you must return the smallest number of officers needed to secure the streets.
## Rules
There are three types of police officers: an L cop, a T cop and a cross cop. The T cop can see in three directions only. The L cop can see down two streets which are perpendicular. The cross cop can see down all four streets.
The map will be supplied via argv or STDIN as space separated numbers. The numbers represent the number of blocks in each column. For example:
### Input `2 1` represents the following map:

### Input `3 1 2 4` represents the following map:

A police officer may only be placed at an intersection and its view may only be along the side of a block (cops may not look into uninhabited areas).
A cop can only see for one block and cannot look along a street where another police officer is looking meaning that sight lines must not overlap.
## Examples
Input: `2 1`

Output: `4`
Input: `2 2`
Output: `4`
Input: `3 1 4 1 5 9`
Output: `22`
## Winning
The shortest code wins.
[Answer]
## CJam, ~~68 61 84 ... 59 49 48~~ 79 bytes
```
l~]__,+:+M@{:Ze<:X2/)_2*X-@+@@-\Z}*;[YY]/_,(\R*_,,:)W%{2\2*1a*+2+/_S*\,(@+\}/;+
```
Takes input in the same format as in question.
*UPDATE* : Fixed the algorithm for test cases similar to what pointed out by @nutki. Although it made the code almost double in size, will try to golf it now that its fixed.
**How it works** *(Slightly incomplete, will add the `2 1 2` parity explanation later)*
As soon as I saw this question, I knew that there would be a mathematical formula to get the answer. After trying a couple of combinations, I figured that the formula is `2 * Number of blocks - Number of shared streets`
Lets check is for `2 1` case:
```
2 * 3 - 2 = 4
```
Correct.
Lets check for `3 1 2 4` case:
```
2 * 10 - 10
```
Correct again. Yipee, so the code is
```
l~]:L:+2*L:(:+L(+-[{_@e<}*]:+-
```
Now lets try this on some more examples:
```
3 3
```
Output:
```
2 * 6 - 7 = 5
```
But wait, the actual answer is 6
Lets try another:
```
5 5
2 * 10 - 13 = 7 // Answer is 9 instead.
```
You see the pattern ?
For every `N N` block pair, where N is positive integer greater than `2`, I require `float((N+1)/2)-1` extra cop apart from the formula above. Lets verify it again:
```
5 5 3
2 * 13 - 18 = 8 // Answer is 11
```
In the above example, we have 1 `5 5` pair and 1 `3 3` pair (from the `5 3` blocks)
Lets try another example
```
5 5 4 4
2 * 18 - 27 = 9 // Answer is actually 14
```
You must be thinking that there are only `5 5`, `3 3` and `3 3` pairs (from blocks `5 5`, `5 4` and `4 4` resp.) , thus only 4 extra cops required, but there is one more pair.
From the blocks `4 4`, we used up only `3 3` so we have `1 1` free, this makes up another `3 3` block pair which can be visualized using the image below:

The red outlined are the usual pairs, the blue outlined is the perpendicular pair which I am talking about above.
It's kind of hard to explain as while the red outlined are just sharing 1 side of the pair, the blue one is sharing 1 side + 1 block too. But this logic works for all block combinations.
The code now is simply calculating that.
```
l~]__ "Read the input numbers, convert to array and make two copies";
,+ "Get the number of columns and add that to the block array";
:+ "Sum the array elements to get number of blocks + columns";
M@ "Push empty array to stack and rotate input array to top";
{ }* "Run this block for each pair in the block array";
:Ze<:X "Store the later block size in Z, and minimum of two in X";
@\- "Rotate swap and subtract shared sides from total sum";
X)Y/(:T+ "Increment halve and decrement. Store in T and add to sum";
XTY*- "Find unused blocks from this pair for perpendicular pairs";
@+ "Add unused blocks to the array M";
Z "Push Z to stack to be used in next iteration";
;[YY] "Pop the last pushed Z and push array [2 2] to stack";
/,(+ "Check how many perpendicular pairs exist, add to total sum";
```
*Note that `2 * Number of blocks - Number of shared sides` can also be written as
`Number of blocks + Number of columns - Number of shared sides between adjacant columns`*
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
I'm solving task, where:
## Input:
A number as an integer.
## Output:
The closest greater palindromic prime as an integer.
I would appreciate *hints* how to make my solution shorter. Or directions if change of approach would be beneficial.
```
golf=lambda l,r=range:next(x for x in r(10**6)if(x==int(`x`[::-1]))&all(x%d for d in r(2,x))and x>l)
```
palindromic:
```
x==int(`x`[::-1])
```
prime:
```
all(x%d for d in r(2,x))
```
[Answer]
Now, for some really big improvements. Your original program was 97 characters:
```
n=lambda l,r=range:next(x for x in r(10**6)if(x==int(`x`[::-1]))&all(x%d for d in r(2,x))and x>l)
```
With the improvements below, you could get to 90 characters:
```
n=lambda l,r=range:min(x for x in r(l+1,10**6)if(`x`==`x`[::-1])&all(x%d for d in r(2,x)))
```
With a trick to eliminate the parentheses around the palindrome checking statement, you can get to 87:
```
n=lambda l,r=range:min(x for x in r(l+1,10**4)if`x`==`x`[::-1]*all(x%d for d in r(2,x)))
```
However, I have a solution in 80 characters. To get it, focus on changing the big picture, not the individual components. Rethink your most basic choices in getting to this point. Why a lambda? Why a min of a filtered range? There may be a better way.
---
Using `int()` in the palindrome comparison is a lot of characters - can you see a shorter way to turn
```
x
```
and
```
`x`[::-1]
```
into the same type?
Also, that `and x>l` bit at the end is a lot of characters. Is there a way we could shorten it? Eliminate the need for it by changing something else?
Is `next` the right function for the job? Remember, this is code golf, runtime is irrelevant.
The prime checking function looks spot on, though.
Also, and this is merely aesthetic, I don't like aliasing functions, the way you are doing with range, when it doesn't save any characters, as in this case.
] |
[Question]
[
The goal is to read bytes from input encoded in [Code Page 437](http://en.wikipedia.org/wiki/Code_page_437) and output the same characters encoded as UTF-8. That is, bytes should be translated into Unicode codepoints per [this table](http://en.wikipedia.org/w/index.php?title=Code_page_437&oldid=565442465#Characters) (a particular revision of the Wikipedia article). Bytes 0-31 and 127 are to be treated as graphics characters.
**Rules**
Input and output is via stdin/stdout, or something equivalent to it (only a function that performs the conversion doesn't qualify). Input is 0 or more bytes before the input stream is closed.
Encoding with UTF-8 is part of the task (as is decoding the input as CP437), so to that end built-in functions or language features that perform conversion between character encodings are not allowed. Submissions should implement the character encoding conversion themselves.
Scoring is pure code-golf, shortest code wins. Code length is measured in bytes assuming the source code is encoded using UTF-8.
**Example**
A byte containing `0x0D` received on input, representing '♪', should output bytes `0xE2`, `0x99`, `0xAA` (in that order), which represents codepoint U+266A encoded in UTF-8.
**Links**
* [CP437 to Unicode conversion table](http://en.wikipedia.org/w/index.php?title=Code_page_437&oldid=565442465#Characters)
* [Summary of UTF-8 encoding](http://en.wikipedia.org/wiki/UTF-8#Description)
* (Task) [Unicode UTF Converter](https://codegolf.stackexchange.com/questions/12717/unicode-utf-converter) -- for converting between Unicode encodings.
[Answer]
### Tcl, 675
```
eval [zlib i Ò×sgÆáB\nPÃïÿòpÁ\f0\fv®4\fBc!j¶%cluYbãdÃw¨)+½MB()zàõÍóÝ=\{vÏì®ÿ¢Ö¶\rk×áóUë\tÌÀOÖ)'*ð,ò¦Ì1\[¦y\v?e~oÀÛ\;¼3)ï*S!ïMgÀÜé¬0OVy_sÌÇ侀@ýa>ÀoïæCMl°7ÎG¸«£Æ'º6Ä\"e±³DÆX*#,Ãïd¹êª²Á&ü®Al±!¬Ì,K˳KÓØèÀ*tbU¶cCìÀöÓíc'VcæKl+¬(V\$µÇFI`ãtc#ô`ôbHbS¤°ú°~vã²ôãrìÁÀäD4!í%\$ÕÉcð(E\\®În²vPÁÕ¨âSÃ5ØË°We?nÚ>ʰ1\"ãÄOyÆð»3Ë,²¯d7dº2)\{iÈ=ý|-w3¥\tÈGå(NÖ0ÙÏ1ä¸lpBý\}\t¾e¾E¾i¾<Y£)KCy~ÎÉçe\v2ÆEç¬rYV¸¢ç&¹*»¸¦\;¸.ÃÜ\]ÜnÉ\ ·ñùÄÇóÍ\ ?ãåøæîàÆøf»xEîá%¹WæÞ(¿é_àwíü7Æ:.ó¿3Ã_¸a©,ð·Ìó>Veÿ°\tëtOpxªS<ÃMð\\e/ð7Oñ7ÂÿzÍ4¯pé´lølÕjZÛV¯\]·råk]
```
Just a simple mapping between input and output. Decompressed it looks like
```
puts [string map { ⺠⻠⥠⦠⣠â ⢠â { } â {
} â {} â {} â {
} ⪠⫠⼠⺠â â ⼠¶ § ⬠⨠â â â â â â â² â¼ â à ü é â ä à å ç ê ë è ï î ì à à à æ à ô ö ò û ù ÿ à à ¢ £ Â¥ â§ Æ Ã¡ ¡ à ¢ ó £ ú ¤ ñ ¥ à ¦ ª § º ¨ ¿ © â ª ¬ « ½ ¬ ¼ ¡ ® « ¯ » ° â ± â ² â ³ â ´ ⤠µ â¡ ¶ ⢠· â ¸ â ¹ ⣠º â » â ¼ â ½ â ¾ â ¿ â À â Á ⴠ ⬠à â Ä â Å â¼ Æ â Ç â È â É â Ê â© Ë â¦ Ì â Í â Î â¬ Ï â§ Ð â¨ Ñ â¤ Ò â¥ Ó â Ô â Õ â Ö â × â« Ø âª Ù â Ú â Û â Ü â Ý â Þ â ß â à α á à â Î ã Ï ä Σ å Ï æ µ ç Ï è Φ é Î ê Ω ë δ ì â í Ï î ε ï â© ð â¡ ñ ± ò ⥠ó ⤠ô â õ â¡ ö ÷ ÷ â ø ° ù â ú · û â ü â¿ ý ² þ â ÿ  } [read stdin]]
```
[Answer]
## JavaScript (ES6), 668 bytes
```
console.log(prompt()[p='replace'](/[\S\s]/g,s=>String.fromCharCode(...(z=`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6]).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)<(x=128)?[z]:z<2048?[0|192+z/64,x+z%64]:[0|224+z/4096,0|x+z%4096/64,x+z%64])))
```
`prompt()`s for input and `console.log()`s the result. Tested in Firefox, utilises ES6 features of arrow functions, template strings and the spread operator (`...`). The bulk of the data here is the string which is a comma separated list of base36 numbers that equate to the UTF-8 code points of the characters to update (1-31, 127-255) and pads the other points with empty space/`NaN`s. The code iterates around each char in the source string, replacing it if necessary. I'm sure it should be possible to shave off more bytes, but I'm done for now! Here's a function for easier testing:
```
c=t=>t[p='replace'](/[\S\s]/g,s=>String.fromCharCode(...(z=(`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)<(x=128)?[z]:z<2048?[0|192+z/64,x+z%64]:[0|224+z/4096,0|x+z%4096/64,x+z%64]))
```
Run the above and call `c()` to extract data:
```
c('\x0d').split('').map(s=>`\\x${s.charCodeAt(0).toString(16)}`).join``
"\xe2\x99\xaa"
```
---
## JavaScript (ES6), 618 bytes
There is a method in JavaScript for easily converting to source bytes for Unicode chars (that was shared to me by Mathias Bynens on a conversion tool I'd written!) that involves URL encoding and decoding the string which saves bytes, but I feel isn't in the spirit of the original challenge:
```
console.log(unescape(encodeURIComponent(prompt()[p='replace'](/[\S\s]/g,s=>String.fromCharCode((`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)))))
```
and as a function:
```
c=t=>unescape(encodeURIComponent(t[p='replace'](/[\S\s]/g,s=>String.fromCharCode(z=(`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s))))
```
[Answer]
### Tcl, 183
```
chan con stdin -en cp437
chan con stdout -en utf-8
puts [string map [concat {*}[lmap c [split {☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼} {}] {list [format %c [incr i]] $c}] ⌂] [read stdin]]
```
You probably have to setup the input/output in your shell to binary, so it does not mangle the input/output.
] |
[Question]
[
I just submitted an answer to [this question](https://codegolf.stackexchange.com/q/4665/3862), and then looked about at some news stories about the MegaMillions lottery craze going on right now in the US. [This news article](http://www.washingtonpost.com/national/record-mega-millions-jackpot-had-gamblers-heading-40-miles-south-of-las-vegas-to-place-bets/2012/03/31/gIQAPUBTmS_story.html) stated that an individual purchased $20,000 worth of tickets at one time (that's 20,000 **sets** of numbers to confirm!) to try and test their luck.
That led me to thinking about how one might quickly determine whether or not they'd won any prize, not just a jackpot, on a large lot of tickets that they had purchased.
The challenge then is this:
## Overview:
Write a function or program that will accept a string of numbers as an argument (STDIN, or read in from a file, your choice), and return the numbers of the tickets with at least the minimum payout awarded.
## Code Details:
* The input will consist of a series of lines, one for each ticket purchased. The winning numbers will be prefixed with a 0, while the drawn numbers will be prefixed with an incremented number starting at 1. (see example)
* The input should be a completely random set of numbers each time, including draws and winning numbers.
* The input should accept any number of tickets *n* where 1 <= *n* <= 20,000. (Assume no 0 ticket runs.)
* Each line of input will have 7 numbers per line. One for the prefix noted above, 5 for the standard balls, and one additional for the 'match' ball. (see **Lotto Details** below)
* The input can be delimited any way you wish (whitespace, semicolon, etc.)
* The output should be a listing of all winning draws and the winning amount. *(So you know which to turn in.)*
* The output listing should be ordered by win amount. *(Who cares if you won $2 on one ticket if you also won $10,000 on another???)*
* When more than one ticket wins the same amount, the order of those tickets is irrelevant.
* The output should also give a listing of the total amount won.
## Lotto Details:
* [Standard rules for the MegaMillions game](http://www.megamillions.com/howto/) will apply, since that's what's so hot right now.
* Draws consist of six numbers from two separate pools of numbers - five different numbers from 1 to 56 and one number (the match ball) from 1 to 46.
* The jackpot is won by matching all six winning numbers in a drawing.
* Awards for non-jackpot wins are awarded as follows (see image below).
(Main) + (Match) = (Payout)
5 + 1 = Jackpot
5 + 0 = $250,000
4 + 1 = $10,000
4 + 0 = $150
3 + 1 = $150
3 + 0 = $7
2 + 1 = $10
1 + 1 = $3
0 + 1 = $2
* Assume current jackpot is $1,000,000 (one million).
* Assume only one jackpot winner, unless your random draw pulls the same jackpot pick more than once *(are you cheating?)*.
* Assume **no** multiplier/California rules are in-play.

## Challenge Details:
* This is code golf, so shortest code wins.
* In the event of a tie, I'll take the highest upvoted answer. I know this is somewhat subjective, but the main point is still the score.
## Example:
**Input:**
```
0 2 4 23 38 46 23
1 17 18 22 23 30 40
2 2 5 24 37 45 23
3 4 23 38 40 50 9
4 2 4 23 38 46 17
5 5 16 32 33 56 46
```
**Output:**
```
4 - $250,000
3 - $7
2 - $3
Total Winnings: $250,010
```
[Answer]
## Python, 239 chars
```
import sys
a=map(eval,sys.stdin)
w=lambda x:(0,2,0,3,0,10,7,150,150,1e4,25e4,1e6)[2*len(set(x[1:-1])&set(a[0][1:-1]))+(x[6]==a[0][6])]
s=0
for e in sorted(a[1:],cmp,w,1):
t=w(e);s+=t
if t:print e[0],"- $%u"%t
print"Total Winnings: $%u"%s
```
Assuming the input numbers are comma separated.
[Answer]
# VBA (660 535 Chars)
Assuming delimiter is a space (`" "`)...
```
Sub a(b)
c=Split(b,vbCr)
Set l=New Collection
Set n=New Collection
d=Split(c(0)," ")
For e=1 To UBound(c)
f=Split(c(e)," ")
p=f(0)
i=1
For g=1 To 5:For h=1 To 5
i=i-(d(g)=f(h))
Next:Next
k=IIf(d(6)=f(6),Choose(i,2,3,10,150,10^4,10^6),Choose(i,0,0,0,7,150,500^2))
If k>0 Then
o=1
For m=1 To l.Count
If k>=l(m) Then l.Add k,p,m:n.Add p,p,m:o=0:m=99999
Next
If o Then l.Add k,p:n.Add p,p
End If
Next
For m=1 To l.Count
r=r & n(m) & ":" & Format(l(m),"$#,##0") & vbCr
q=q+l(m)
Next
MsgBox r & "Total Winnings:" & Format(q,"$#,##0")
End Sub
```
[Answer]
# Javascript, 353 Bytes
```
(function(t){u={"51":1e6,"50":25e4,"41":1e4,"40":150,"31":150,"30":7,"21":10,"11":3,"01":2},a=t.split('\n'),l=a.length-1,m=a[0].split(' '),w=m.slice(1,6),h=0;for(;l--;){s=a[l+1].split(' '),i=s.slice(1,6).filter(function(n){return!!~w.indexOf(n)}),n=i.length+''+(s[6]==m[6]?1:0),v=u[n];if(v){h+=v;console.log(l+'-$'+v)}}console.log('Total Winnings: $'+h)})("0 2 4 23 38 46 23\n" + "1 17 18 22 23 30 40\n" + "2 2 5 24 37 45 23\n" + "3 4 23 38 40 50 9\n" + "4 2 4 23 38 46 17\n" + "5 5 16 32 33 56 46")
```
ungolfed:
```
(function (t) {
u = {
"51": 1e6,
"50": 25,
"41": 1e4,
"40": 150,
"31": 150,
"30": 7,
"21": 10,
"11": 3,
"01": 2
},
a = t.split('\n'),
l = a.length - 1,
m = a[0].split(' '),
w = m.slice(1, 6),
h = 0;
for (; l--; ) {
s = a[l + 1].split(' '),
i = s.slice(1, 6).filter(function (n) { return !! ~w.indexOf(n) }),
n = i.length + '' + (s[6] == m[6] ? 1 : 0),
v = u[n];
if (v) {
h += v;
console.log(l + ' - $' + v)
}
}
console.log('Total Winnings: $' + h)
})("0 2 4 23 38 46 23\n" +
"1 17 18 22 23 30 40\n" +
"2 2 5 24 37 45 23\n" +
"3 4 23 38 40 50 9\n" +
"4 2 4 23 38 46 17\n" +
"5 5 16 32 33 56 46")
```
Could probably knock a few chars off that :D
] |
[Question]
[
[This problem](http://hs10.spoj.pl/problems/HS10RECT/) (see below) has been given as a High School Programming League code golf challenge. The shortest codes submitted during the contest were: 177 bytes in Ruby, 212 bytes in Python 2.5, 265 bytes in C. Can anyone make it shorter? Other programming languages are also allowed.
**Problem formulation**: Given 8 integers: -1000 < x1, y1, x2, y2, x3, y3, x4, y4 < 1000. Check what is the shape of the intersection of two axis-aligned rectangles: P1 = (x1, y1), (x1, y2), (x2, y2), (x2, y1) and P2 = (x3, y3), (x3, y4), (x4, y4), (x4, y3).
```
* If the rectangles do not intersect print *nothing*.
* If there is exactly one point in common print *point*.
* If the intersections of P1 and P2 is a line segment print *line*.
* If they have a rectangular area in common print *rectangle*.
```
**Input data specification**: The first line contains the number of test cases *t* (1<=*t*<1000). Each of the following t lines contains 8 integers: x1, y1, x2, y2, x3, y3, x4, y4 (The area of both rectangles is greater than 0).
You can test your solution [here](http://www.spoj.pl/HSPLARCH/problems/HS10RECT/).
[Answer]
## Python, 200 characters
```
f=lambda a,b,c,d:min(2,sum((x-c)*(x-d)<=0for x in range(min(a,b),max(a,b)+1)))
for i in' '*input():z=map(int,raw_input().split());print('nothing','point','line',0,'rectangle')[f(*z[::2])*f(*z[1::2])]
```
`f` returns:
```
0 if the intervals [a,b] and [c,d] don't overlap
1 if the intervals [a,b] and [c,d] overlap in only one point
2 if the intervals [a,b] and [c,d] overlap in a range of points
```
[Answer]
**OCaml, 265 chars**
```
let a,c,p=abs,compare,print_endline
let q s t u v w x y z=match
c(a(s-u)+a(w-y))(a(s+u-w-y)),
c(a(t-v)+a(x-z))(a(t+v-x-z))with
0,0->p"point"|0,1|1,0->p"line"|1,1->p"rectangle"|_->p"nothing"
let()=for n=1 to read_int()do Scanf.scanf"%d %d %d %d %d %d %d %d\n"q done
```
Uses (abuses) the fact that compare returns 0, 1 or -1. This is not guaranteed according to its documentation but true with OCaml 3.10.1.
] |
[Question]
[
Validate a proposed crossword grid.
Entries should be full programs that simply test a proposed grid
to determine if it meets a set of conditions for making crossword
solvers happy.
## Input
The input will be the name of a file representing the crossword
grid. The input filename may be passed as an argument, on the
standard input, or by other conventional means other than
hardcoding.
**Grid file format:** The first line consists of two white-space
separated integer constants M and N. Following that line are M
lines each consisting of N characters (plus a new line) selected
from `[#A-Z ]`. These characters are interpreted such that `'#'`
indicates a blocked square, `' '` a open square in the puzzle
with no known contents and any letter an open square whose
containing that letter.
## Output
The program should produce no output on valid grids and exit with
normal termination state. If the proposed grid fails, the program
should produce a diagnostic error message and exit with a
abnormal termination state (i.e. not 0 on unix) if this is
supported by your execution environment. The error message should
indicate both which condition for validity is violated and the
location of the offending square; you are free to chose the means
of conveying these facts.
## Conditions for validity
Valid grids will have no answers (across or down) that are only 1
character long (extra credit for making the minimum length a
input parameter), and will exhibit the usual symmetry. The usual
symmetry means the crossword remains the same after (three
equivalent descriptions of the same operation):
* reflection through it's own center
* reflection both vertically and horizontally
* 180 degree rotation
## Test input and expected output
Passes:
```
5 5
# ##
#
#
#
## #
```
Fails on short answer:
```
5 5
## ##
#
#
#
## ##
```
Fails on symmetry:
```
5 5
# ##
#
#
# #
## #
```
## Aside
This is the second of several crossword related challenges. I
plan to use a consistent set of file-formats throughout and to
build up a respectable suite of crossword related utilities in
the process. For instance a subsequent puzzle will call for
printing a ASCII version of the crossword based on the input and
output of this puzzle.
Previous challenges in this series:
* [Crossword numbering](https://codegolf.stackexchange.com/questions/318/crossword-numbering)
[Answer]
# Ruby - ~~215~~ 207
```
t,*d=$<.map &:chop;n,d,e=t.size+1,(d*S=?#).gsub(/[^#]/,W=" "),->c,i{puts [c,i/n+1,i%n+1]*" ";exit 1}
0.upto(d.size-1){|i|d[i]==d[-i-1]||e[?R,i];d[i]==W&&(d[i-1]!=W&&d[i+1]!=W||d[i-n]!=W&&d[i+n]!=W)&&e[?L,i]}
```
Ungolfed:
```
h, *g = $<.map &:chop
w = h.size+1
g = (g*?#).gsub(/[^#]/," ")
error = ->c,i{ puts [c,i/w+1,i% w+1]*" "; exit 1 }
0.upto(size-1) { |i|
error[?R, i] if g[i] != g[-i-1]
error[?L,i] if g[i]==" " && (g[i-1]!=" " && g[i+1]!=" " || g[i-w]!=" " && g[i+w] != " ")
}
```
.
```
h, *g = $<.map &:chop
```
This basically removes the last char (line break) of each input line by calling the `chop` method on them, and returning an array of the results.
`h` takes the first element of this array and `*g` takes the rest. So we end up with the first line in `h` and the crossword grid lines in `g`.
```
g = (g*?#).gsub(/[^#]/," ")
```
`g*?#` joins (`*`) the array `g` with the `"#"` (`?#` is a character literal). This is the same as `g.*("#")`, or `g.join("#")`. Then every non `#` is replaced by a space.
For the symmetry check we just have to check if the char at every index is equals to the char at the opposite index in the string:
```
0.upto(g.size-1) { |i| if g[i] != g[g.size - i - 1]; error() }
```
In Ruby we can index strings from the end using negative indexes (starting from `-1` instead of `0`), so that `g[-i-1]` is the opposite of `g[i]` in the string. This saves a few chars:
```
0.upto(g.size-1) { |i| if g[i] != g[-i-1]; error() }
```
We can save a `;` by using a conditional statement:
```
0.upto(g.size-1) { |i| error() if g[i] != g[-i-1] }
```
In the golfed version we can save a few more chars:
```
0.upto(g.size-1){|i|g[i]==g[-i-1]||error()}
```
In a previous version I used recursion for iterating over the string:
```
(f=->i{g[i]&&f[i+1]&&g[i]!=g[-i-1]&&error()})[0]
```
An out of bound access to `g` returns nil, so once `g[i]` returns `nil`, this stops the iteration.
Output format:
```
{ L | R } line-number column-number
```
L for length errors, and R for rotation error (so `L 1 2` means length error at line 1, column 2)
[Answer]
## Reference implementation
**c99**
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readgrid(FILE *f, int m, int n, char grid[m][n]){
int i = 0;
int j = 0;
int c = 0;
while ( (c = fgetc(f)) != EOF) {
if (c == '\n') {
if (j != n) fprintf(stderr,"Short input line (%d)\n",i);
i++;
j=0;
} else {
grid[i][j++] = c;
}
}
}
int isSymmetric(int m, int n, char g[m][n]){
for (int i=0; i<m; ++i)
for (int j=0; j<n; ++j)
if ( (g[i][j]=='#') != (g[m-i-1][n-j-1]=='#') )
return j*m+i;
return -1;
}
int isLongEnough(int m, int n, char g[m][n], int min){
/* Check the rows */
for (int i=0; i<m; ++i) {
int lo=-(min+1); /* last open square */
int lb=-1; /* last blocked square */
for (int j=0; j<n; ++j) {
if ( g[i][j] == '#' ) {
/* blocked square */
if ( (lo == j-1) && (j-lb <= min+1) ) return lo*m+i;
lb=j;
} else {
/* In-play square */
lo=j;
}
}
}
/* Check the columns */
for (int j=0; j<n; ++j) {
int lo=-(min+1); /* last open square */
int lb=-1; /* last blocked square */
for (int i=0; i<m; ++i) {
if ( g[i][j] == '#' ) {
/* blocked square */
if ( (lo == i-1) && (i-lb <= min+1) ) return lo*m+i;
lb=i;
} else {
/* In-play square */
lo=i;
}
}
}
/* Passed */
return -1;
}
int main(int argc, char** argv){
const char *infname;
FILE *inf=NULL;
FILE *outf=stdout;
int min=1;
/* deal with the command line */
switch (argc) {
case 3: /* two or more arguments. Take the second to be the minium
answer length */
if ( (min=atoi(argv[2]))<1 ) {
fprintf(stderr,"%s: Minimum length '%s' too short. Exiting.",
argv[0],argv[2]);
return 2;
}
/* FALLTHROUGH */
case 2: /* exactly one argument */
infname = argv[1];
if (!(inf = fopen(infname,"r"))) {
fprintf(stderr,"%s: Couldn't open file '%s'. Exiting.",
argv[0],argv[1]);
return 1;
};
break;
default:
printf("%s: Verify crossword grid.\n\t%s <grid file> [<minimum length>]\n",
argv[0],argv[0]);
return 0;
}
/* Read the grid size from the first line */
int m=0,n=0,e=-1;
char lbuf[81];
fgets(lbuf,81,inf);
sscanf(lbuf,"%d %d",&m,&n);
/* Intialize the grid */
char grid[m][n];
for(int i=0; i<m; ++i) {
for(int j=0; j<n; ++j) {
grid[i][j]='#';
}
}
readgrid(inf,m,n,grid);
if ((e=isSymmetric(m,n,grid))>=0) {
fprintf(stderr,"Symmetry violation at %d,%d.\n",e/m+1,e%m+1);
return 4;
} else if ((e=isLongEnough(m,n,grid,min))>=0) {
fprintf(stderr,"Short answer at %d,%d.\n",e/m+1,e%m+1);
return 8;
}
return 0;
}
```
[Answer]
## C, 278 chars
```
char*f,g[999],*r=g;i,j,h,w;main(e){
for(fscanf(f=fopen(gets(g),"r"),"%*d%d%*[\n]",&w);fgets(g+h*w,99,f);++h);
for(;j++<h;)for(i=0;i++<w;++r)if(e=*r==35^g[g+w*h-r-1]==35?83:
*r==35||i>1&r[-1]!=35|i<w&r[1]!=35&&j>1&r[-w]!=35|j<h&r[w]!=35?0:76)
exit(printf("%d%c%d\n",j,e,i));exit(0);}
```
As you might expect, the error messages have themselves been golfed. They take the following form:
`11L8` - indicates a length error at row 11 column 8
`4S10` - indicates a symmetry error at row 4 column 10
[Answer]
## APL (115)
```
{∨/,k←⍵≠⌽⊖⍵:'⍉',(,k×⍳⍴k)~⊂2/0⋄×⍴d←(,⊃,/(g(⍉g←⍳⍴⍵))×{k↑1⌽1⊖0 1 0⍷¯1⌽¯1⊖⍵↑⍨2+k←⍴⍵}¨⍵(⍉⍵))~⊂2/0:'∘',d}d↑↑{'#'≠⍞}¨⍳⊃d←⎕
```
If the grid is not symmetrical, it outputs `⍉` followed by the coordinates, i.e. for the example it gives
```
⍉ 2 5 4 1
```
If the grid has short answers, it outputs `∘` followed by the coordinates, i.e. for the example it gives
```
∘ 1 2 5 2
```
Explanation:
* `d↑↑{'#'≠⍞}¨⍳⊃d←⎕`: read the first line as a list of numbers and store in `d`, then read as many lines as the first number, and reshape as a matrix of size `d`. 'Closed' squares are stored as 0 and 'open' squares as 1.
* `∨/,k←⍵≠⌽⊖⍵`: store in `k` the places where the grid is asymmetrical. If there is such a place...
* `'⍉',(,k×⍳⍴k)~⊂2/0`: output a ⍉ followed by the offending coordinates
* `⋄`: otherwise...
* `~⊂2/0`: remove the zero coordinates from the following list:
* `¨⍵(⍉⍵)`: for both the grid and its transpose...
* `¯1⌽¯1⊖⍵↑⍨2+k←⍴⍵`: surround the grid with zeros (i.e. closed squares)
* `0 1 0⍷`: see where it contains an 'open' square enclosed by two 'closed' squares (= too short)
* `k↑1⌽1⊖`: remove the ring of extra zeros again
* `,⊃,/(g(⍉g←⍳⍴⍵))×`: multiply by coordinates and transposed coordinates, and join together, to form a list of offending coordinates (and a lot of zeros which we remove).
* `×⍴d←`: store the offending coordinates in `d`, and if there are any...
* `:'∘',d`: output a ∘ followed by the coordinates.
] |
[Question]
[
`(l, r)` defines a line whose left end is at `l` and the right end is at `r`, on a 1-dimensional space.
Given 2 lines `b = (0, bz)` and `f = (i, i + fz)`, `v = (l, r)` is the overlapping part of these lines. When `b` and `f` do not overlap (when `v` cannot have a positive length), `v = (0, 0)`.
```
(input) -> (output)
bz, fz, i -> l, r
```
The data type (`int`, `float`, `string`, etc.) for each value should be able to represent all *integers* from `-128` to `127`, inclusive.
You can change the order of input and output variables.
### Examples
```
0, 0, 0 -> 0, 0
1, 1, 1 -> 0, 0
1, 2, 3 -> 0, 0
1, 2, -3 -> 0, 0
2, 1, 1 -> 1, 2
4, 2, 1 -> 1, 3
2, 2, -1 -> 0, 1
2, 4, -1 -> 0, 2
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 44 bytes
```
lambda a,b,c:[c*(a>c>0),min(a,b+c)*(a>c>-b)]
```
[Try it online!](https://tio.run/##dY1BCsMgFET3OcWHbjQ1YEwLJdBcxLowJlLBaDBuenpr0oZsWpjFMO/P/PkVn941tzkkfX8kK6d@kCBJT1TLVYlkpzqKyWQcyuFZ4U9U9Vgk7QNYMA54wSmBVYIUvCawarXssBcC7Eizqt1fdn/NPI@wvAIn0CYsEaxxI@jgJ6AQPeSTZVTeDeD3nG2goflxptuG@Fevf/TrLylEC3MwLiKNSotxegM "Python 3.8 (pre-release) – Try It Online")
Test harness borrowed from @ophact.
The condition for overlap to exist is that both right ends are right of both left ends. Two of those four pairwise inequalities are as I understand it satisfied automatically (up to equality, but that does no harm), the other two can be folded into a single chained comparison `a>c>-b`. This is used to zero out the result we computed under the assumption that overlap exists. The left end makes a further shortcut using that `b` is guaranteed to be nonnegative and that one of the two possible ends is `0`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 52 bytes
```
lambda a,b,c:[d:=c*(c>0),e:=min(a,c+b)]*(d<e)or[0,0]
```
[Try it online!](https://tio.run/##dY3NCoMwEITvPsVCL4ndQvwplFD7ImkOmhgaiIlEL316G6XipYU5DPPtzI7v@RV8dRvjYprn4tqh0y202KHiQvNG5UQ9GMWeN4P1pEV17qjMib73NETBkMnFhAgOrAeRpQBWScxEgbBqteVha4TySJMuu693f008jZRpBU5gbJxmcNb3YGIYgMEcIJ1MvQpeQ9jzcgMVS48T3Tbkv3rxo198SSY5jNH6mRiSO0qXDw "Python 3.8 (pre-release) – Try It Online")
## Explanation
The overlapping line starts from the beginning of the second line (measured by starting point) because it cannot start from the beginning of the first line (unless both lines start at the same point) because then the beginning would not be part of the second line, and it cannot start at the end of any line because it would leave the line directly afterward.
It ends at the first endpoint, where it first "leaves" a line.
If the start is not less than the end (as found according to the above), then the lines do not overlap, and we can then return `[0, 0]`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ý+IÝÃÁ2£DËi00S
```
I/O: three loose inputs in the order \$fz,i,bz\$; output as pair [\$r,l\$].
[Try it online](https://tio.run/##yy9OTMpM/f//8Fxtz8NzDzcfbjQ6tNjlcHemgUHw//8mXLqGXEYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGeSSoJRWZXt4v04miEgCMRUetU1SULJP@H94rnbx4bmHmw83Gh1a7HK4O9PAIPh/bYJSEUhpDpBQ0vkfHW2gA4SxOtGGOkAIpI10jKG0LoQBkjACCxjqmEAkIAImMIahgY6RgY5pbCwA).
**Explanation:**
Step 1: Calculate `[r,l]` for overlapping test cases:
```
Ý # Push a list in the range [0, first (implicit) input fz]
+ # Add the second (implicit) input `i` to each to make the range [i,fz+i]
I # Push the third input `bz`
Ý # Pop and push a list in the range [0,bz]
à # Keep all values in [i,fz+i] that are also in [0,bz]
Á # Rotate this list once towards the right
2£ # Keep (up to) the first two values
# (this is the output [r,l] for the overlapping test cases)
```
Step 2: Deal with the edge cases of `[]` (no overlap) or `[x]` (\$i=bz\$ or \$fz+i=0\$):
```
D # Duplicate the list
Ëi # If both values are the same (truthy for [] and [x], falsey for [r,l]):
00S # Push [0,0] instead
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
Nθ≔Φ⁺…⁰NN⁼ι﹪ιθηI⟦∨⌊η⁰⊕∨⌈η±¹
```
[Try it online!](https://tio.run/##ZYy7CsJAFER7v2LLuxAhEbtUIgoWicFWLK6bS7KwD/cl/v26sRDBbmbOcMSMXlhUOZ/MI8U@6Tt5cLxd7UKQk4GjVLEsg0oBLmgmgrpiv1/O//vBJVQBZMU6OyZll@T4QuZiHrw0EfYYIlzPHjpppE4a5oLrj0x40mQijbBgfH1xTxNGgqaobpy3OW/ZhjV5/VRv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `bz`.
```
≔Φ⁺…⁰NN⁼ι﹪ιθη
```
Input `fz` and `i`, create the range `[i,i+fz)`, and filter out values not in the range `[0,bz)`.
```
I⟦∨⌊η⁰⊕∨⌈η±¹
```
If there are no values left then output `0,0` otherwise output the endpoints of the remaining values.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ż+⁵fŻ}0ṚE?.ị
```
A full program that accepts `fz bz i` and prints the line as `[l, r]`.
**[Try it online!](https://tio.run/##ASMA3P9qZWxsef//xbsr4oG1ZsW7fTDhuZpFPy7hu4v///8y/zT/MQ "Jelly – Try It Online")**
### How?
```
Ż+⁵fŻ}0ṚE?.ị - Main Link: fz, bz
Ż - zero range fz -> [0,1,2,...,fz] (call this F)
⁵ - 3rd argument, i
+ - add -> [i,i+1,...,i+fz]
} - use right argument, bz:
Ż - zero range -> [0,1,2,...,bz] (call this B)
f - F filter keep if in B
? - if...
E - ...condition: all equal? (i.e. is that a single point)
0 - ...then: yield zero
Ṛ - ...else: reverse
. - 0.5
ị - index into -> [last value, first value] (when given 0 this is [0,0])
- implicit print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
(IntervalIntersection@@Interval/@{{0,#1},{#3,#3+#2}})[[1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X8MzryS1qCwxB0wXpyaXZObnOTjARPUdqqsNdJQNa3WqlY11lI21lY1qazWjow1jY9X@BxRl5pU4pEWb6BjpGMb@BwA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
So, normally, this is a [forbidden loophole](https://codegolf.meta.stackexchange.com/a/1062/98630) to fetch the desired output from an external source. But this challenge is an exception ! In this challenge you will **have** to fetch data from the internet and output it to the SDTOUT.
# The task
1. For the purpose of this challenge, you'll be the owner of the imaginary `a.pi` domain!
2. You will need to take the first argument from STDIN, pass it to `a.pi/{arg}`, and print the result to STDOUT.
3. You don't need to handle errors, the server is always up and running !
4. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the winner is the shortest (in bytes or [equivalent](https://codegolf.meta.stackexchange.com/search?q=program%20size)) valid answer.
# Rules
1. You are allowed to invoke [`curl`](https://curl.se/) and [`wget`](https://www.gnu.org/software/wget/) **[1]** commands as child/sub-processes (like `child_process` with NodeJS).
2. The ressource at `a.pi` will only be available in the `http` and `https` protocol in their default ports (`80` and `443` respectively), you don't need to include the `http://` if your language allow to ommit it.
3. Only the desired output (http response) should be printed, nothing else (no `GET http://a.pi/:` or whatever).
4. The input might contain spaces or otherwise [reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters), and need to be **percent-encoded**.
Spaces () should be replaced with `%20` and `%` with `%25` (As [spaces **cannot** be in URLs](https://stackoverflow.com/questions/497908/is-a-url-allowed-to-contain-a-space)). The other characters (including reserved ones) don't need to be encoded, but you **can** encode them (including [unreserved](https://en.wikipedia.org/wiki/Percent-encoding#:%7E:text=RFC%203986%20section%202.3) characters) if that makes your code shorter.
5. If your language/environement doesn't have a STDIN/STDOUT (like in a browser), the shortest equivalent can be used (like `prompt()` and `alert()` in javascript).
6. The [`CORS`](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) Headers are open for any external requests (`Access-Control-Allow-Origin: *`), if you where wondering.
>
> **Note:** to test your program, you can use any domain and then replace it with `a.pi` for the submission.
>
>
>
**[1]** While it should works the same everywhere, I'd recommend you to precise which OS you used for testing.
# Updates
Rule 4 have been modified as it was the hardest part is the percent-encoding, which is already a [submitted code golf](https://codegolf.stackexchange.com/questions/89767/percent-encode-a-string), and the exact rules of the encoding where unclear.
>
> **Note:** this the first code-golf challenge that I submit, and I didn't knew about the [sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges) before. In the future, I'll definitely post here before submitting.
>
> Also, this change doesn't affect previous entries (Except for their length).
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„ %DÇh'%ì‡"a.pi/"ì.w
```
-9 bytes now that the encoding rule (4) has changed.
[Try it online](https://tio.run/##Dc/pUpJhGAbgUyGKbNX2xfayfS/bF8OipEUpMNvn5RMBLVuAChUJUHEjZd/Bmefmo5mceYdO4TkR4t/19@ox6zuNhnqdhV@ja4Ojq0mHCIugVt9sMrZoEWnuq9fbDWaLxtht6rW0alZoV67SrW5as3bd@g0bm1s2bd6yddv2HTt37W7ds3ff/gMHDx0@0nb02PETJ0@dPnP23PkLFy9dbr9y9dr1Gzdv3b5zt@OevvP@A8PDR13Gx0@ePuvuMT1/Ybb0vux79frN23fvP/wZ/@uSMRmXCZmUKZmWGZmtxWvZWrFW@qdIt/RIr8zJCTnLgwF2DrFzmJ1@VqysKKz0s2JjZYAVezXFSkSOsRituho1FmEWgUZr2c4iqjaUU10Vu1qqpiuChZfFCAsfi3EWIRZuFp5lH9tCapBFXnVXHGpZzVasFKQQTdAkTVGYpmmGZmmO5ikiC7RAixSlGMUpQUlKUZoylKUc5alARSpRmZYgYIWCftgwADsccGIQQ/iITxjGZ3zBV3yDC2548B0/8BNejGAUY/BhHH78QgBBhDCBSUwhjGnMYBZzmEcEv7GARUQRQxwJJJFCGhlkkUMeBRRRQhlL/wE) (where `.w` will act as no-op, since it's disabled on TIO).
**Original 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer encoding all reserved and non-ASCII characters:**
```
žj“"+-.<>“«мDÇh'%ì‡"a.pi/"ì.w
```
\$\frac{2}{3}rd\$ of the program is used to encode the characters (19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) to be exact).
[Try it online](https://tio.run/##DdDpUpJhGIfxUzHKrExsX8xss30v21csS6yUQrN9Hl4R0LIFqFzAWBRFSFlkX5y5/7w0kzPP0CncJ0J8@329rj6jrlPfVa2qxR4WLk1jk7a1rQYKVfLtsHY31CPMwqvRaQ36Zg3C2sFqtaPL2F@n7zUM9LfUrdGsXVe/vmHDxk2Nm5u0zVu2btu@Y@eu3Xv2tuxr3d924OChw0fajx47fuLkqdNnzp47f@HipcsdV65eu37j5q3bd@7eu6/rfPCw69Hjbn3Pk6fPevsMz18Y@wdeDr56/ebtu/cf/rj/2mVUxmRcLsuETMqUTFdilXQlXyn8U6RDOuW4zEi/DPKIh22jbBtj2zQrJlYUVoZYMbMyzIqlnGAlLKdYTJbtLKZZBFh4almrFhYRtaaMai9Z1EI5WRIsxllM1BawcLPwsXCwcK662OxTvSyyqqNkVYtqumQiL/nITzM0SwGao3kK0gKFKCxztEhLFKEoxShOy5SgJKUoTRnKUo7yVKAirUDABAVDMGMYFlhhwwhG8RGfMIbP@IKv@AY7HHDiO37gJ8YxgUlMwQU3pvELHnjhgx8zmEUAc5hHEAsIIYzfWMQSIogihjiWkUASKaSRQRY55FFAESv/AQ) (where `.w` will act as no-op, since it's disabled on TIO).
**Explanation:**
```
„ % # Push string " %"
D # Duplicate this string
Ç # Convert it to a list of codepoint integers
h # Convert each integer to hexadecimal
'%ì '# Prepend a "%" in front of each
‡ # Transliterate all characters in the (implicit) input-string
"a.pi/"ì # Prepend "a.pi/" in front of it
.w # Browse this page (with leading "http://" implicitly added) and
# read and push its contents
# (after which this is output implicitly as result)
žj # Push builtin "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
“"+-.<>“« "# Append string '"+-.<>'
м # Remove all these characters from the (implicit) input-string,
# so we're left with all reserved and/or non-ASCII characters
DÇh'%ì‡"a.pi/"ì.w '# Same as above
```
[Answer]
# Javascript (ES6), ~~26~~ 23 bytes
```
x=>fetch('/'+escape(x))
```
Percent encode builtin FTW!!!
Returns a `Promise` containing an object with a `text` method, which when called with no properties returns the result, allowed by [this](https://codegolf.meta.stackexchange.com/a/12327/100664https://codegolf.meta.stackexchange.com/a/12327/100664).
Must be run on the `a.pi` domain, allowed by [this consensus](https://codegolf.meta.stackexchange.com/questions/13621/can-js-answers-require-the-code-to-be-run-at-a-certain-domain). Since this is impossible, try running the following in your console, on this site:
```
f=
x=>fetch('/'+escape(x))
f('questions').then(x=>x.text()).then(console.log)
```
(This requests the questions page)
[Answer]
# [Perl 5](https://www.perl.org/) -nlMv5.10, 50 bytes
```
s/\W/sprintf"%%%02x",ord$&/ge;say`curl -s a.pi/$_`
```
[Can't try it online](https://tio.run/##HcqxDsIgEADQX7lgcZJSTTr5DZ0cXEyEKLaXECDcWfTnPY3zeyXUOMoGTs0X4CUAtwwOGvICCjjDiqH94VmjkL2cLZWKiR9Kaz0cXmqX673b2jkcyb/d7dfAEPi@oO2uTsTXGTgQf3JhzInEpChmWsd@P3wB "Perl 5 – Try It Online") unless you swap the two ``` chars with `"` to output the curl command with it's arguments instead of it's response. Percent-encodes all chars except `a-z`, `A-Z`, `0-9` and `_`.
[Answer]
# [PHP](https://php.net/), ~~54~~ 47 bytes
```
<?=join(file('http://a.pi/'.urlencode($argn)));
```
[Try it online!](https://tio.run/##K8go@P/fxt42Kz8zTyMtMydVQz2jpKTASl8/Ua8gU19dr7QoJzUvOT8lVUMlsSg9T1NT0/r//7T8/H/5BSWZ@XnF/3XdAA "PHP – Try It Online")
Note: TIO does not allow external requests, though it probably doesn't really matter since `a.pi` does not really exist.
-7 bytes thx to @Kaddath!
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 77 bytes
-10 bytes thanks to Kevin Cruijssen
```
a=>new System.Net.WebClient().DownloadString("a.pi/"+Uri.EscapeDataString(a))
```
[Try it online!](https://tio.run/##LcuxCsIwEIDh3ac4MiWoEXWs7dLqJC5FOp/xKgfxUpJI8ekjqNM/fPwurV3icnqJO6QcWR4r@LWBEWooWDdCM/TvlOlpL5TtQLfWM0nWxnZhFh/w3n8XrdBOvFHLa2R7TA4n6jDjH9GYUi3aICl4skPkTGcW0qNWW9jBXhlTlQ8 "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 34 bytes
If you only need to return the URL + encoded query string like in some of the answers.
```
a=>"a.pi/"+Uri.EscapeDataString(a)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrqMAoe0U0hRsFf4n2topJeoVZOoraYcWZeq5FicnFqS6JJYkBoNVaSRq/rfmcs7PK87PSdULL8osSfXJzEvVSNNQMlQwUjBW0tS0/g8A "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `http.client`, 42 bytes
```
[ url-encode "a.pi/"prepend http-get nip ]
```
[Try it online!](https://tio.run/##HcwxDsIwDEbhvaf4lb1BwAYHQCwsiAkxRKkpFpFjHPf8Abo@fXrPlL1av13Pl9MBjT4LSaaGl7vGXJjEsVhp8ZfrxDLjTSZUwBXHYQhb7LAP/f5H42oIIUXlTVAjJZnW1TiTQ1jx6DmVAjUW718 "Factor – Try It Online")
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 122 bytes
```
BEGIN{RS=ORS="\r\n";s="/inet/tcp/0/a.pi/80"}1gsub("%","%25")gsub(FS,"%20"){print"GET /"$0|&s;while((s|&getline)>0)print$0}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686KNjWH4iVYopi8pSsi22V9DPzUkv0S5IL9A30E/UKMvUtDJRqDdOLS5M0lFSVdJRUjUyVNMFct2AQz0BJs7qgKDOvRMndNURBX0nFoEat2Lo8IzMnVUOjuEYtPbUkB2ikpp2BJliZikHt//8A "AWK – Try It Online")
>
> [NO WAY! I didn't know AWK could do that!](https://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html)
>
>
>
```
BEGIN{RS=ORS="\r\n";
```
We start by setting `\r\n`(`CR LF`) as the trailing character of the print function, as the default is only `\n`.
```
s="/inet/tcp/0/a.pi/80"}
```
And then we set the server we want to communicate with.
```
1gsub("%","%25")gsub(FS,"%20")
```
This AWK pattern will always return true, even if there are no spaces or `%` in the input.
```
{print"GET /"$0|&s;while((s|&getline)>0)print$0}
```
The last piece of code `GET`s the domain response until the last line.
For this code to work, make sure to input the wanted `ARG` as in `a.pi/{ARG}`, hit `Enter`, and then `Ctrl`+`D` (or your most favorite ASCII-4-End-of-transmission way of doing it).
] |
[Question]
[
I'm looking for a program such that, given a finite list of strings, can find short regexes to match exactly all of them and nothing else.
Since there are multiple languages that express regexes differently, there can correspondingly be multiple regex generators. Each answer must discuss regex generation in one langauge only (or a family of languages for which there is a direct correspondence between regexes in each of them).
[Answer]
The Machine Learning Lab at the University of Trieste, Italy, wrote a web app to solve this exact problem, available at: [Automatic Generation of Regular Expressions from Examples](http://regex.inginf.units.it/) based on "genetic programming" and published a paper about it. Based on the fact that it had to come from the Machine Learning Lab of a university in Italy, and was worth publishing a paper about, it is probably a pretty hard problem to solve. Doesn't sound like the type of question for Code Golf SE, but I'm new here, so I wouldn't be the expert on that.
[Answer]
I would approach this problem by searching for common subsequences in each pair of strings in the list, and then building regular expressions that include those subsequences. This would be somewhat like the [Re-Pair](https://en.wikipedia.org/wiki/Re-Pair) algorithm, but it would build a grammar from a set of strings instead of one string.
For instance, these strings:
`["red wolf", "red fox", "gray wolf", "gray fox"]`
could be combined into two regular expressions:
`"red (wolf|fox)", "gray (wolf|fox)"`
which can be combined into one regular expression:
`"(red|gray) (wolf|fox)"`
But this problem is probably NP-complete, since it is similar to the [smallest grammar problem](https://en.wikipedia.org/wiki/Smallest_grammar_problem).
] |
[Question]
[
## Cleaning the dishes
In this task, you will be given a bar of soap with a width of 1 or more units. You will also be given a plate, which you will have to clean, using the soap as few times as you can. The plate will be at least 1 character. You will have to output a plate with the 'clean' character representing the plate, and a third unique character to represent in what positions the bar of soap was placed.
How much the soap cleans:
```
(n-1)//2 on each side for odd n
(n-1)//2 on the left side of the soap bar for even n
n//2 on the right side of the soap bar for even n
```
Note: `n//2` means `floor(n/2)`.
## Input
An integer greater than or equal to 1. A series of 2 unique characters to represent clean portions and dirty portions.
Here, '=' represents a dirty portion, and '-' represents a clean portion. '+' represents where the soap was placed. Before the colon is what is the input, and after the colon is what is outputted.
**IN : OUT**
```
3 ===- : -+--
32 ================================ : ---------------+----------------
1 ==== : ++++
5 ----- : -----
4 -====- : --+---
3 -====- : --+-+-
7 === : +--
6 - : -
6 -==-===- : ---+----
5 -==--==- : ---+--+-
3 -==--==- : --+--+--
```
## Rules
* There are multiple solutions. Any one of them are acceptable, as long as they use the soap the minimum amount of times possible.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest, so the shortest answer in bytes wins!
* Input may be whatever you want, as long as the plate and soap are specified, and clean/dirty portions of the plate are different. For example, strings and arrays of integers are allowed.
* Output is of your choosing. You just need to make sure clean and soap portions of the output plate are different, but consistent. The plate and where the soap was placed should be shown.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
Sandbox: [Sandbox for Proposed Challenges](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/18054#18054)
[Answer]
# JavaScript (ES6), ~~92 90 86~~ 85 bytes
*Saved 1 byte thanks to @Grimy*
Takes input as `(n)(string)`. Uses `1` as the soap character.
```
n=>s=>s.replace(eval(`/=.{0,${n-1}}/g`),s=>(g=n=>'-'.repeat(s.length-n>>1))(1)+1+g``)
```
[Try it online!](https://tio.run/##lZDBboMwDIbvfQofJsWRCYyxbocpPMkOIJZmm1CoGtQL4tlZUsJGewjdr0hJZH/2b3/X59o2p69jL0z3oaaDnIwsrTvpSR3bulGoznWLVSbT4TF5GIzIxzHTFU9cEmrpsplgPlnVPdq0VUb3n8KUZc455pxy0lXFp17ZHiSgScBykCUM0HTGdq1K206jBQIGyNxl/JMz/naVcEDD0ZEu9m58cNztfE2EIgEmpRQMIuKQZSBIiBkqnmYoKjZD16KbfygIeSi47YKcArR30KUI27S@avXsKbkxcqDoDyv@hdGCvc6DRecKg/22evGt4sTSak04a1F7yyZotYx9AMWdIN2s4y7wwonpBw "JavaScript (Node.js) – Try It Online")
### How?
To get the widths of the cleaning areas, the helper function \$g\$ uses the expression \$\lfloor(n-k)/2\rfloor\$, which gives the left width for \$k=1\$ and the right width for \$k=0\$:
$$\lfloor (n-1)/2\rfloor=\cases{
(n-1)/2,&\text{if $n$ is odd}\\
n/2-1,&\text{if $n$ is even}\\
}$$
$$\lfloor (n-0)/2\rfloor=\cases{
(n-1)/2,&\text{ if $n$
is odd}\\
n/2,&\text{ if $n$ is even}\\
}$$
### Commented
```
n => // n = soap width
s => // s = plate string
s.replace( // find in s all patterns consisting of
eval(`/=.{0,${n - 1}}/g`), // '=' followed by 0 to n-1 characters (greedily)
s => // for each pattern s:
( g = n => // g is a function taking n = 0 or 1
'-'.repeat( // and outputting a string of
s.length - n >> 1 // floor((s.length - n) / 2) hyphens
) //
)(1) + // replace s with g(1) (left part)
1 + // followed by '1' (the soap)
g`` // followed by g(0) (right part)
) // end of replace()
```
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
def f(n,s):i=s.find('1');return~i and'0'*i+f'{2:0^{min(n,len(s)-i)}}'+f(n,s[n+i:])or s
```
[Try it online!](https://tio.run/##fY/RCoIwGIXve4pBF9vSYvvNAqMniYJAR4P6FbWLkHp126bNrOjcje@c858Vt/qUY9S2aaaIYhhWPNHbaqE0poxKyjdlVl9LfGhyxJQKOtOBog0k4tBcNJrAOUNW8bnm9zsNXMMOA53seV6Sqi1KjTVTLAoJlVIKyjmxmhIBQkw8ho7/lc2a3Fjw8R46ZV85nAQjj2ODXaDnfbPnS8vlsNlyeDdEPw0wGNbdgNf97s@ermzcM0fHzBS/yt02GM2Le4v4sMDXwJEFnKt9Ag "Python 3 – Try It Online")
Uses `0` for empty plate, `1` for dirt and `2` for soap. Takes an integer `n` and a string `s` as input.
The function searches for the first dirt character `1` in the string `s`. Starting at that point, it will format a string of emtpy plate characters `0` with a soap character `2` as the center character. Because of Python's string formatting rules, the soap character `2` will be in the center-left position when `n` is even. This piece of string will be of length `n` *or* the remaining number of characters in the input string `s`, whichever is shorter. The rest of the string `s` is evaluated recursively.
[Answer]
**VBA, 157bytes**
```
Sub a(s, p):z=Len(p):Q=s\2+s Mod 2-1
While instr(x+1,p,1)<>0
F=instr(x+1,p,1)
f=f+2/s
If f>Z then f=z
Mid(p,f)=2
X=f+q
Wend
P=replace(p,1,0)
Msgbox p
End sub
```
I think there are lots of bytes to save but couldn't get rid of the if Statement without causing some cases to fail
is Expecting the plate to be 0 clean and 1 dirty (2 is soap)
[Answer]
# Perl 5 (`-p`), ~~86~~, 59 bytes
-27 bytes thanks to Grimy,
```
$m=$_-1;s`=.{0,$m}`$_=$&;y/=/-/;s/(-*)-\1/$1+$1/r`ge;s;.* ;
```
[TIO](https://tio.run/##fY1NDoIwEIX3PcUsGqPU6VARTWh6BG9gAhtiTEAIdWOMV7e2/Ki48G0m8817b9qyq1JnCTIZEWnHa8NzVNoWRt7jNa8fBc8NX@gbGULSlpYYrfCoiCvBFXXFqdRWywi0cwkYYxAyQIHIkk1Y/ypY5xI/OzIFo1N4sXQITEG2BTTT0z7MkjkRyPYwFvjrDvpDmN7z9g1/Q7sn@E3F2PihPcRn017PzcU6rFqHh1TG6gU)
* `$m=$_-1;` input coerced to integer -1 which will be used as maximum number of character to be matched after `=`
* `s{=.{0,$m}}{...}e` : subsitution of longest match of `=` followed by at most m characters
* `$_=$&;y/=/-/;s/(-*)-\1/$1+$1/r` : to replace all `=` by `-` and then; to find the largest sequence of repeated `-` followed by a `-` and followed by the backreference \1
* `s;.* ;;` : to remove the number and space from input
Previous answer
```
/ /;$m=$`-1;$p="{0,$m}";$_=$';s`=.$p`$l=length$&;"-"x(-!($l%2)+$l/2)."+"."-"x($l/2)`ge
```
[TIO](https://tio.run/##fY1LDsIwDET3OYWJzDc4oS0FichH4Ax0UwFSgIiyQEJcndCG8l0wG8vPM2NfHl0eKgMLPTLGBgPG4o6xoMSiZ3mZjHF3lRZXjH1bFazRF@jYlfv1aYM9K0meB9QZoOumQ4XOpEMtldSRx7VYlyFkwMwECyBFJLK0Wf@qsX5L/ewkEmidqpbIH4FnUEyB@Pk0hkX2TRSJObQF9XUG8dDM2vPyPf427TWhT6raxjeNkG4Hf9oe9lUg5wMtcz1J7g)
other solution doesn't pass all tests because doesn't match clean parts within dirty.
~~67 bytes~~
```
/ /;$n=$`;$_=$';s/(=*)=(=?)\1(??{length$&>$n&&"^"})/$1+$2$1/g;y;=;-
```
[TIO](https://tio.run/##K0gtyjH9/19fQd9aJc9WJcFaJd5WRd26WF/DVkvTVsPWXjPGUMPevjonNS@9JENFzU4lT01NKU6pVlNfxVBbxUjFUD/dutLa1lr3/39jIwVbAoDLWEHX1lYXhCFMIONffkFJZn5e8X/dgv@6vqZ6BoYA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 22 bytes
```
+þ_H}ḞFṬo³Ạ
JŒPçƇḢṬ+Ị{
```
[Try it online!](https://tio.run/##y0rNyan8/1/78L54j9qHO@a5Pdy5Jv/Q5oe7FnB5HZ0UcHj5sfaHOxYBBbUf7u6q/v//v6GOARhCaMP/xgA "Jelly – Try It Online")
A full program taking the dish as a string as its first argument and the size of the soap as an integer as its second argument. Prints a string representing the clean dish with the soap in place. For both, `0` is dirty, `1` is clean and `2` is soap.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 69 bytes
```
\d+
$*-
^(-*)-\1
$1#$1
+`((((-)|#)+)-*,.*)(?<-4>.)*(?(4)$)=
$1$2
.+,
```
[Try it online!](https://tio.run/##fYvBCsIwEETv@xuNsJvsBNKm9mLs0Z8oUkEPXjyIR/89TSJ6dGDYx/D2eXvdH5e849Oal6sjY0FnhhUsgUzoTCC3cgnk3YkTWPVWeD4gHr1YnjmKkVRU05N3SjkPmlICDX29f0OhKTQqaigq0uf3C1MVaK@oLUMbx4b4iQ03 "Retina 0.8.2 – Try It Online") Link includes test cases. Uses `#` to represent soap. Explanation:
```
\d+
$*-
```
Convert `n` into a template string of clean plate.
```
^(-*)-\1
$1#$1
```
Change the middle character of the template to soap.
```
+`
```
Repeatedly clean the plate until it cannot be cleaned any more.
```
((((-)|#)+)-*,.*)(?<-4>.)*(?(4)$)=
```
Match as much template and soap as possible. Keep track of the amount of template matched for later. The match starts as early as possible, so it will never start after the soap (since it could have matched starting at the soap in that case). Then optionally consume some clean template plate (meaning that the match must contain the soap) and an arbitrary amount before some dirty plate of exactly the same length as the template previously matched.
```
$1$2
```
Replace the dirty plate with the clean template and soap.
```
.+,
```
Delete the clean template and soap.
] |
[Question]
[
*TL;DR for those not interested: Look at the test cases at the bottom. Have a program/function that outputs the 2D list displayed for the given input.*
## Introduction:
[On November 15th, 2018 puzzle designer Raphaël Mouflin revealed his Triangularity puzzle.](http://twistypuzzles.com/forum/viewtopic.php?f=15&t=33942) Here is a picture of that puzzle:
[](https://i.stack.imgur.com/PvL3cm.png)
As you can see, the shape is a 3-sided (4-faced) pyramid (a.k.a. tetrahedron), and it has six pieces per face.
So, what makes this puzzle so unique? It's the first puzzle in the shape of a regular platonic solid that is a hybrid of all three twisty puzzle rotational axis systems: face-turning, corner-turning, AND edge-turning. Most puzzles only have a single rotational axis system, like face-turning for the regular [3x3x3 Rubik's Cube](https://i.postimg.cc/pLPZ3SFD/DSC-0005.jpg); corner-turning for the [Pyraminx](https://i.postimg.cc/csZfWzjB/DSC-0070.jpg); edge-turning for the [Helicopter Cube](http://www.twistypuzzles.com/cgi-bin/puzzle.cgi?pkey=2300); etc. Lately more hybrid puzzles are getting released of which most have two rotational axis systems combined in the same puzzle (usually face- and corner-turning, since that seems to be the easiest hybrid combination to accomplish).
There are some other puzzles with all three rotational axis, like the [Truncated Icosidodecahedron](http://www.twistypuzzles.com/cgi-bin/puzzle.cgi?pkey=6762) or [Superstar](http://www.twistypuzzles.com/cgi-bin/puzzle.cgi?pkey=6468) puzzles, but those use a pretty complex shape in order to accomplish that. Triangularity however is a simple 3-sided pyramid that still has all three rotational axis systems.
[Here a video to show those moves.](https://www.youtube.com/watch?v=pS_FHkvTKVA)
## Challenge:
**Input:**
The move we are doing, which is one of the following:
* `E#` for an edge-turn, where `#` is a digit in the range `[1,6]` (or `[0,5]`) for the six edges, [numbered here](https://i.postimg.cc/brW82Lmh/Triangularity-edge-pieces.png). So the blue-red edge is 1; blue-yellow is 2; yellow-red is 3; blue-green is 4; yellow-green is 5; and red-green is 6.
* `F#D` for the face-turn, where `#` is a digit in the range `[1,4]` (or `[0,3]`) for the four faces, [numbered here](https://i.postimg.cc/dtV47wCw/Triangularity-face-pieces.png). So the blue face is 1; yellow face is 2; red face is 3; green face is 4. And `D` is the direction, either `C` (clockwise) or `A` (anti/counter clockwise).
* `C#D` for the corner, where `#` is a digit in the range `[1,4]` (or `[0,3]`) for the four corners, [numbered here](https://i.postimg.cc/139VHrPQ/Triangularity-corner-pieces.png). So the blue-yellow-red corner is 1; blue-green-red corner is 2; blue-yellow-red corner is 3; yellow-red-green corner is 4. And `D` is the direction, either `C` (clockwise) or `A` (anti/counter clockwise).
Optional second input: The initial solved state 2D-array below.
**Output:**
The output will be the modified 2D-array after we've executed the single given move, where the initial solved configuration pictured above would be:
```
[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24]]
```
Where these numbers indicate the pieces per face, so (using 'outer color - inner color' to indicate the pieces): 1 and 2 are the blue-red pieces; 3 and 4 the blue-yellow pieces; 5 and 6 the blue-green; 7 and 8 the yellow-blue; 9 and 10 the yellow-red; 11 and 12 the yellow-green; 13 and 14 the red-blue; 15 and 16 the red-yellow; 17 and 18 the red-green; 19 and 20 the green-blue; 21 and 22 the green-yellow; and 23 and 24 the green-red. (Looking at the faces in a clockwise direction, the first number is the first you encounter when going clockwise, and the second number the one next to it.)
## Challenge rules:
* The moves will be done in increments that doesn't change the tetrahedron shape. So even though the puzzle allows 60 degree increments for face-turns, and 90 degree increments for edge-turns, we will only do 180 degree edge turns and 120 degree face- and corner-turns so the puzzle won't shapeshift and will retain its tetrahedron shape.
* Since the challenge is mainly about executing the move, and not about compressing the initial state, you can (optionally) take the initial state as additional input.
* You are allowed to use either 1-indexed or 0-indexed numbers for the edges, faces, and corners. They do have to be consistent though, so you are not allowed to use `[1,6]` for the edges, and `[0,3]` for the corners. It should be either all 1-indexed or all 0-indexed. Please state what you've used in your answer.
* I/O is flexible. Input move can be a String, character-array, etc. (You are not allowed to take the input as a list of codepoints, unless you language does this implicitly.) Output can be a 2D array/list, can modify the optional input 2D array/list, can be a string, etc.
* You may optionally take the edge turns with a trailing `C`/`A` as well if it would save bytes, but the output would be the same in both cases, since the turns are in 180 degrees. (Please state so in your answer if you do take them with a trailing `C`/`A` which is ignored.)
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases / All possible I/O (1-indexed):
```
Input move Output (cycled pieces)
F1C [[5,6,1,2,3,4],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24]] (1→3→5→1 and 2→4→6→2 as 3-cycles)
F1A [[3,4,5,6,1,2],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24]] (1→5→3→1 and 2→6→4→2 as 3-cycles)
F2C [[1,2,3,4,5,6],[11,12,7,8,9,10],[13,14,15,16,17,18],[19,20,21,22,23,24]] (7→9→11→7 and 8→10→12→8 as 3-cycles)
F2A [[1,2,3,4,5,6],[9,10,11,12,7,8],[13,14,15,16,17,18],[19,20,21,22,23,24]] (7→11→9→7 and 8→12→10→8 as 3-cycles)
F3C [[1,2,3,4,5,6],[7,8,9,10,11,12],[17,18,13,14,15,16],[19,20,21,22,23,24]] (13→15→17→13 and 14→16→18→14 as 3-cycles)
F3A [[1,2,3,4,5,6],[7,8,9,10,11,12],[15,16,17,18,13,14],[19,20,21,22,23,24]] (13→17→15→13 and 14→18→16→14 as 3-cycles)
F4C [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[23,24,19,20,21,22]] (19→21→23→19 and 20→22→24→20 as 3-cycles)
F4A [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[21,22,23,24,19,20]] (19→23→21→19 and 20→24→22→20 as 3-cycles)
C1C [[1,8,9,4,5,6],[7,16,13,10,11,12],[3,14,15,2,17,18],[19,20,21,22,23,24]] (2→16→8→2 and 3→13→9→3 as 3-cycles)
C1A [[1,16,13,4,5,6],[7,2,3,10,11,12],[9,14,15,8,17,18],[19,20,21,22,23,24]] (2→8→16→2 and 3→9→13→3 as 3-cycles)
C2C [[17,2,3,4,5,14],[7,8,9,10,11,12],[13,24,15,16,19,18],[1,20,21,22,23,6]] (1→19→17→1 and 6→24→14→6 as 3-cycles)
C2A [[19,2,3,4,5,24],[7,8,9,10,11,12],[13,6,15,16,1,18],[17,20,21,22,23,14]] (1→17→19→1 and 6→14→24→6 as 3-cycles)
C3C [[1,2,3,20,21,6],[5,8,9,10,11,4],[13,14,15,16,17,18],[19,12,7,22,23,24]] (4→12→20→4 and 5→7→21→5 as 3-cycles)
C3A [[1,2,3,12,7,6],[21,8,9,10,11,20],[13,14,15,16,17,18],[19,4,5,22,23,24]] (4→20→12→4 and 5→21→7→5 as 3-cycles)
C4C [[1,2,3,4,5,6],[7,8,9,22,23,12],[13,14,11,16,17,10],[19,20,21,18,15,24]] (10→18→22→10 and 11→15→23→11 as 3-cycles)
C4A [[1,2,3,4,5,6],[7,8,9,18,15,12],[13,14,23,16,17,22],[19,20,21,10,11,24]] (10→22→18→10 and 11→23→15→11 as 3-cycles)
E1 [[13,14,3,4,5,6],[7,8,9,10,11,12],[1,2,15,16,17,18],[19,20,21,22,23,24]] (1↔13 and 2↔14 as swaps)
E2 [[1,2,7,8,5,6],[3,4,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24]] (3↔7 and 4↔8 as swaps)
E3 [[1,2,3,4,5,6],[7,8,15,16,11,12],[13,14,9,10,17,18],[19,20,21,22,23,24]] (9↔15 and 10↔16 as swaps)
E4 [[1,2,3,4,19,20],[7,8,9,10,11,12],[13,14,15,16,17,18],[5,6,21,22,23,24]] (5↔19 and 6↔20 as swaps)
E5 [[1,2,3,4,5,6],[7,8,9,10,21,22],[13,14,15,16,17,18],[19,20,11,12,23,24]] (11↔21 and 12↔22 as swaps)
E6 [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,23,24],[19,20,21,22,17,18]] (17↔23 and 18↔24 as swaps)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~384~~ ~~362~~ ~~359~~ ~~344~~ ~~337~~ 313 bytes
```
def f((a,b,c),I):
b=int(b)-1;q=b==1;Q=b==2;j=ord(c)%63;A=b|1+4*q;C=A-5*q;F=2-Q;G=b%2*(b^2);H=C+2-q;J=b%2+G
if'E'<a:G=F=C=b;A,B,H,J=range(4)
if'E'==a:j=3;G=b%3-q-Q;A=b+b%2-b/5*2;C=F=(b/3)|2-q;J=G*2;H=J-4
q,w,e=I[G],I[F],I[C];X=q[A],q[A-5],w[H],w[J],e[J-5],e[J-4];q[A],q[A-5],w[H],w[J],e[J-5],e[J-4]=X[j:]+X[:j]
```
[Try it online!](https://tio.run/##pdXLbtpAFAbgvZ/Cmwg7HCvM@MLFPQvXAgO77JCsqYQT0walEAhNUinvTufiKwVDko2NRuNv/uM5Y57@7n6tV3S/v08X@sIw5pDAnQkTc6DpCT6sdkZiWsTfYIJI/Ftxo/4S19t748688mw/wOSdtJ3rjR9iYLn8PkJq3foRJlf02kh@UNMfY9im1safirF2pOkPi9aw9W0@iHCEISZ@AN9hDFPczlc/U8MxsxmI88ESbWnZ1oarfLU2N6zkxr2mfMURGsmNbb4rPeJjY5xajqZv4BVSnMQRg0k8EpeQ@TPcxAEDfrFcBq/xWFymDNJ4KgbEzWH@BXNwFi8HrD2LB0u2n2AcE6BggwMueAziLvSgD6QDhAChfIDYQBwgLhAPSBdIT4z1gXaA8icpUBuow5imiV2IjN/rlxT0bfr853EnNuIN05f5o/G82xoTk7@cRTbjjf9@2vJN4jNQTde0yGiNSNgCPY55GsiSfSGVqchAklmRgv0ySVXK@ruTEuTwh8ngCFkmFO5HSftYyv8LFwxU4EYyuIgs8ym4iXQuS3mkcMlABS7I4NNkmU/BgpSNKuCQ5FkFVcICsKt0LtOzmxSSPKtCSlRkr5D9jOydJ/Pu7Bb1k1OniBYvoJ@hNdMryCxlvyDpKdLLxQzs1kRSpKx1p5oiCncrpHO64@WJOCy81p1yhqf2tCRpw8GUZR2QDd2ZFVRpJZKDner2iEPgVsmG7pRTK6RYQJKU1khVi1PrzqFsJSHLR5s6XzTmRd@QIc1NUJ82JQr701/PoV0x6ykzoIaqdc6ZzoGpDu@Fp178LRwx3ZM5pag@OU21qy93zfSazWMp1fP12tU6zNz/Aw "Python 2 – Try It Online")
Takes input with a trailing `C/A` for every move.
Modifies the input list in-place
---
## Explanation:
First we identify which faces are moved, depending on the move (faces that don't move are blank):
```
F1C [[ 1, 2, 3, 4, 5, 6], [ , , , , , ], [ , , , , , ], [ , , , , , ]] -> [[ 5, 6, 1, 2, 3, 4], [ , , , , , ], [ , , , , , ], [ , , , , , ]]
F1A [[ 1, 2, 3, 4, 5, 6], [ , , , , , ], [ , , , , , ], [ , , , , , ]] -> [[ 3, 4, 5, 6, 1, 2], [ , , , , , ], [ , , , , , ], [ , , , , , ]]
F2C [[ , , , , , ], [ 7, 8, 9,10,11,12], [ , , , , , ], [ , , , , , ]] -> [[ , , , , , ], [11,12, 7, 8, 9,10], [ , , , , , ], [ , , , , , ]]
F2A [[ , , , , , ], [ 7, 8, 9,10,11,12], [ , , , , , ], [ , , , , , ]] -> [[ , , , , , ], [ 9,10,11,12, 7, 8], [ , , , , , ], [ , , , , , ]]
F3C [[ , , , , , ], [ , , , , , ], [13,14,15,16,17,18], [ , , , , , ]] -> [[ , , , , , ], [ , , , , , ], [17,18,13,14,15,16], [ , , , , , ]]
F3A [[ , , , , , ], [ , , , , , ], [13,14,15,16,17,18], [ , , , , , ]] -> [[ , , , , , ], [ , , , , , ], [15,16,17,18,13,14], [ , , , , , ]]
F4C [[ , , , , , ], [ , , , , , ], [ , , , , , ], [19,20,21,22,23,24]] -> [[ , , , , , ], [ , , , , , ], [ , , , , , ], [23,24,19,20,21,22]]
F4A [[ , , , , , ], [ , , , , , ], [ , , , , , ], [19,20,21,22,23,24]] -> [[ , , , , , ], [ , , , , , ], [ , , , , , ], [21,22,23,24,19,20]]
->
C1C [[ , 2, 3, , , ], [ , 8, 9, , , ], [13, , ,16, , ], [ , , , , , ]] -> [[ , 8, 9, , , ], [ ,16,13, , , ], [ 3, , , 2, , ], [ , , , , , ]]
C1A [[ , 2, 3, , , ], [ , 8, 9, , , ], [13, , ,16, , ], [ , , , , , ]] -> [[ ,16,13, , , ], [ , 2, 3, , , ], [ 9, , , 8, , ], [ , , , , , ]]
C2C [[ 1, , , , , 6], [ , , , , , ], [ ,14, , ,17, ], [19, , , , ,24]] -> [[17, , , , ,14], [ , , , , , ], [ ,24, , ,19, ], [ 1, , , , , 6]]
C2A [[ 1, , , , , 6], [ , , , , , ], [ ,14, , ,17, ], [19, , , , ,24]] -> [[19, , , , ,24], [ , , , , , ], [ , 6, , , 1, ], [17, , , , ,14]]
C3C [[ , , , 4, 5, ], [ 7, , , , ,12], [ , , , , , ], [ ,20,21, , , ]] -> [[ , , ,20,21, ], [ 5, , , , , 4], [ , , , , , ], [ ,12, 7, , , ]]
C3A [[ , , , 4, 5, ], [ 7, , , , ,12], [ , , , , , ], [ ,20,21, , , ]] -> [[ , , ,12, 7, ], [21, , , , ,20], [ , , , , , ], [ , 4, 5, , , ]]
C4C [[ , , , , , ], [ , , ,10,11, ], [ , ,15, , ,18], [ , , ,22,23, ]] -> [[ , , , , , ], [ , , ,22,23, ], [ , ,11, , ,10], [ , , ,18,15, ]]
C4A [[ , , , , , ], [ , , ,10,11, ], [ , ,15, , ,18], [ , , ,22,23, ]] -> [[ , , , , , ], [ , , ,18,15, ], [ , ,23, , ,22], [ , , ,10,11, ]]
->
E1 [[ 1, 2, , , , ], [ , , , , , ], [13,14, , , , ], [ , , , , , ]] -> [[13,14, , , , ], [ , , , , , ], [ 1, 2, , , , ], [ , , , , , ]]
E2 [[ , , 3, 4, , ], [ 7, 8, , , , ], [ , , , , , ], [ , , , , , ]] -> [[ , , 7, 8, , ], [ 3, 4, , , , ], [ , , , , , ], [ , , , , , ]]
E3 [[ , , , , , ], [ , , 9,10, , ], [ , ,15,16, , ], [ , , , , , ]] -> [[ , , , , , ], [ , ,15,16, , ], [ , , 9,10, , ], [ , , , , , ]]
E4 [[ , , , , 5, 6], [ , , , , , ], [ , , , , , ], [19,20, , , , ]] -> [[ , , , ,19,20], [ , , , , , ], [ , , , , , ], [ 5, 6, , , , ]]
E5 [[ , , , , , ], [ , , , ,11,12], [ , , , , , ], [ , ,21,22, , ]] -> [[ , , , , , ], [ , , , ,21,22], [ , , , , , ], [ , ,11,12, , ]]
E6 [[ , , , , , ], [ , , , , , ], [ , , , ,17,18], [ , , , ,23,24]] -> [[ , , , , , ], [ , , , , , ], [ , , , ,23,24], [ , , , ,17,18]]
```
These faces are mapped to their index:
```
F1C [0,0], [0,1], [0,2], [0,3], [0,4], [0,5] -> [0,2], [0,3], [0,4], [0,5], [0,0], [0,1]
F1A [0,0], [0,1], [0,2], [0,3], [0,4], [0,5] -> [0,1], [0,2], [0,3], [0,4], [0,5], [0,0]
F2C [1,0], [1,1], [1,2], [1,3], [1,4], [1,5] -> [1,2], [1,3], [1,4], [1,5], [1,0], [1,1]
F2A [1,0], [1,1], [1,2], [1,3], [1,4], [1,5] -> [1,1], [1,2], [1,3], [1,4], [1,5], [1,0]
F3C [2,0], [2,1], [2,2], [2,3], [2,4], [2,5] -> [2,2], [2,3], [2,4], [2,5], [2,0], [2,1]
F3A [2,0], [2,1], [2,2], [2,3], [2,4], [2,5] -> [2,1], [2,2], [2,3], [2,4], [2,5], [2,0]
F4C [3,0], [3,1], [3,2], [3,3], [3,4], [3,5] -> [3,2], [3,3], [3,4], [3,5], [3,0], [3,1]
F4A [3,0], [3,1], [3,2], [3,3], [3,4], [3,5] -> [3,1], [3,2], [3,3], [3,4], [3,5], [3,0]
C1C [0,1], [0,2], [2,3], [2,0], [1,1], [1,2] -> [2,3], [2,0], [1,1], [1,2], [0,1], [0,2]
C1A [0,1], [0,2], [2,3], [2,0], [1,1], [1,2] -> [0,2], [2,3], [2,0], [1,1], [1,2], [0,1]
C2C [3,5], [3,0], [2,1], [2,4], [0,5], [0,0] -> [2,1], [2,4], [0,5], [0,0], [3,5], [3,0]
C2A [3,5], [3,0], [2,1], [2,4], [0,5], [0,0] -> [3,0], [2,1], [2,4], [0,5], [0,0], [3,5]
C3C [0,3], [0,4], [1,5], [1,0], [3,1], [3,2] -> [1,5], [1,0], [3,1], [3,2], [0,3], [0,4]
C3A [0,3], [0,4], [1,5], [1,0], [3,1], [3,2] -> [0,4], [1,5], [1,0], [3,1], [3,2], [0,3]
C4C [1,3], [1,4], [2,5], [2,2], [3,3], [3,4] -> [2,5], [2,2], [3,3], [3,4], [1,3], [1,4]
C4A [1,3], [1,4], [2,5], [2,2], [3,3], [3,4] -> [1,4], [2,5], [2,2], [3,3], [3,4], [1,3]
E1 [0,0], [0,1], [2,2], [2,0] -> [2,2], [2,0], [0,0], [0,1]
E2 [0,2], [0,3], [1,2], [1,0] -> [1,2], [1,0], [0,2], [0,3]
E3 [1,2], [1,3], [2,4], [2,2] -> [2,4], [2,2], [1,2], [1,3]
E4 [0,4], [0,5], [3,2], [3,0] -> [3,2], [3,0], [0,4], [0,5]
E5 [1,4], [1,5], [3,4], [3,2] -> [3,4], [3,2], [1,4], [1,5]
E6 [2,4], [2,5], [3,0], [3,4] -> [3,0], [3,4], [2,4], [2,5]
```
All indices are swapped in pairs (eg. `F1C` has `(0,0-1),(0,2-3),(0,4-5)` swapped to `(0,2-3),(0,4-5),(0,0-1)`).
Each pair of moves that uses `A/C` also has the same pairs swapped, only in opposite directions.
This means that the moves `F1C` and `F1A` move the same pairs, but in opposite directions. IE `C: abcdef -> cdefab` and `A: abcdef -> efabcd`.
This gives us the values of `j`, which is used to slice the list of indices being moved. `abcdef -> [abcedf][:j] + [abcdef][:j]`.
IE: `C: j=2, abcdef -> [abcdef][2:]+[abcdef][:2] = cdef+ab`
and `A: j=4, abcdef -> [abcdef][4:]+[abcdef][:4] = ef+abcd`
For moves with `E`, we only swap two pairs. This is done by setting `j` to `3`:
`abcdef -> [abcdef][3:]+[abcdef][:3] = def+abc`. By mapping the pairs that we want to swap to `ab` and `de`, and setting `c`and`f` to the same, this works.
Finally we need to calculate all these indeces as shown in the second list.
By naming each value to as follow (names are a bit random, but what came from golfing):
```
[G,A], [G,B], [F,H], [F,J], [C,D], [C,E] -> ...
```
We get the following lists for each variable (also introducing `b` as `x-1`):
```
FxA/C: CxA/C: Ex:
x b G A B F H J C D E x b G A B F H J C D E x b G A B F H J C D E
1 0 0, 0, 1, 0, 2, 3, 0, 4, 5 1 0 0, 1, 2, 2, 3, 0, 1, 1, 2 1 0 0, 0, 1, 2, 2, 0, 2, 1, 2
2 1 1, 0, 1, 1, 2, 3, 1, 4, 5 2 1 3, 5, 0, 2, 1, 4, 0, 5, 0 2 1 0, 2, 3, 1, 2, 0, 1, 1, 2
3 2 2, 0, 1, 2, 2, 3, 2, 4, 5 3 2 0, 3, 4, 1, 5, 0, 3, 1, 2 3 2 1, 2, 3, 2, 4, 2, 2, 3, 4
4 3 3, 0, 1, 3, 2, 3, 3, 4, 5 4 3 1, 3, 4, 2, 5, 2, 3, 3, 4 4 3 0, 4, 5, 3, 2, 0, 3, 1, 2
5 4 1, 4, 5, 3, 4, 2, 3, 3, 4
6 5 2, 4, 5, 3, 0, 4, 3, 5, 0
```
All these numbers are then calculated for the current move.
A few dependencies can be seen:
```
D = (J+1)%6 (equal to J-5, because negative index wraps arund)
E = (J+2)%6 (equal to J-4, .. )
B = (A+1)%6 (equal to A-5, .. )
```
Which means that we need to calculate the following numbers:
```
b 0123 0123 012345
F C E
A 0000 1533 022444
C 0123 1033 212333
F 0123 2212 212333
G 0123 0301 001012
H 2222 3155 224240
J 3333 0402 002024
```
Now all we have to do is golf all of these sequences based on the move...
Introducing two numbers (`q: b==1`, `Q: b==2`) we then have:
```
F C E
A 0 b|1+4*q b+b%2-b/5*2
C b A-5*q (b/3)|2-q
F b 2-Q C
G b b%2*(b^2) b%3-q-Q
H 2 C+2-q J-4 (also (J+2)%6)
J 3 b%2+G G*2
j 2/4 2/4 3
```
All of these are then used to modify the input list, by assigning the indices to themselves, but reordered.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~332~~ 324 bytes
```
->m,a{g=->x,y,z{"7KN=)&L]idSGWCaf>M!$3?<-".bytes.index x*16+y*4+z+69}
m=m.hex;q=(t=m%16<8)?m%8/4+3:m/16%26-7
(r=[*-2..2]).product(r,r).map{|i|n=g[*i]
d=0
6.times{|j|d+=(i[j%3]*=(26564818>>j%3*8+q&2)-1)**2
j==2&&(t ?i[-k=m%4]>1&&(i[1-k]*=-1;i[2-k]*=-1):i.max<1&&i.rotate!(m%8*((22>>q&2)-1)))}
h=g[*i]
d==10&&a[h/6][h%6]=n}
a}
```
[Try it online!](https://tio.run/##jY5Bb9owGIbv/hUULZHtxAY7qZu1OKiy2h3W7dJDD5YP6RKKqUJpCFIo8NtZJFD3qafJl@d7X9vP12yet8eZPrK8jovdi2Z5F2/jj93w6udvTcIH58vHH0@mmOW/Lr4l0wkb8udtW625X5ZVN@ioUNGWptFHpL4fUK1rPq@6m3eNW10HQk0yMq2DbJRGyXU9EiqQil0h3GhLmeRcOsJXzVu5@dPiJm4Ir4vVbu/3S/1iqXeo1GOkeOvrar3bL/ZlpLG3iyBxVGOpLlWaiSzP@4Bm0XsoCROEUokWWsswxO1g6i177RdJXS76wFvBXvu3TNx4K89Irn2v7Sb9Bc@bt7Zoqwvc70wxljLPz98SckDzz620GIdhYecj5ew8UE4vD6g4HAtt7Tj@PC7@78khtBrM7PBODOPCnVkCTgCngC8BqxNv2vUpuBfmX3svbsEgYSNhk8AmgU0Km/T2i8xAmYEyA2UGygyUGSgzUGZOsuNf "Ruby – Try It Online")
Takes input as a string, which it then interprets as a hexadecimal number. If it is acceptable to take input as an integer, that would save 8 bytes.
Originally developed to output a 0 indexed 1 dimensional array. On re-reading the spec a 2D array is required, so the solved array is used as a dummy template to be filled with data (the structure is used but none of the data within it is.) Output is 0 indexed; it can be made 1 indexed by changing the second last line to `d==10&&a[h/6][h%6]=n+1}`
**Explanation**
A reshaping of the puzzle pieces yields a cubic puzzle. The faces of the tetrahedron are built up with triangular pyramids whose sides are 90 degree isosceles triangles. The edges of the original tetrahedron become diagonals on the faces of the cube. See image of partially unfolded cube, showing the numbers and the positive directions for the x,y and z axes.
A rotation of an edge of the tetrahedron corresponds with a rotation of a face of the cube. A rotation of a corner or face of the tetrahedron corresponds with a rotation of a corner of the cube. The numbers of the edges of the tetrahedron become the numbers of the faces of the cube, and the numbers of the corners and faces of the tetrahedron become those of the corners of the cube.
[](https://i.stack.imgur.com/MSXcW.png)
In the code, each piece has a coordinate which is a permutation of `[+/-2,+/-1,0]` where the coordinate of magnitude 2 corresponds to the face and the other coordinates correspond to the position on the face. The function generates all possible `x,y,z` coordinates in the range `-2..2` and acts only on those where the square of the euclidean distance is 5. For each set of coordinates that is kept, it looks up (using helper function `g`) the piece number which corresponds to the coordinates and saves it to `n`. It then modifies the coordinates (if required) according to the move. Finally it looks up the the number which corresponds to the modified coordinates and saves the value of `n` to the corresponding cell of the array. Once it has processed all 24 valid sets of coordinates it returns the fully populated array.
# Commented code
```
->m,a{ #Input the moves as a string (and the array which we only use as a structure template)
g=->x,y,z{"7KN=)&L]idSGWCaf>M!$3?<-".bytes.index x*16+y*4+z+69} #Helper function to convert native coordinates to the ones required by the question
m=m.hex #Convert input to an integer. If the last digit is 0..6 (not A or C) t=true.
q=(t=m%16<8)?m%8/4+3:m/16%26-7 #If t false q=0..7 to flip correct axes for the particular F# or C# move. If t true q =3 or 4 (flip all or no axes for E# move.)
(r=[*-2..2]).product(r,r).map{|i| #Iterate i=[x,y,z] for values in range -2..2 . For each set of coordinates...
n=g[*i] #Fetch the value from the array (returns nil without errors if coordinates invalid)
d=0 #Initialize a counter to check for valid coordinates (x*x+y*y+z*z)*2=10
6.times{|j| #Iterate through all three axes (twice, so that flipped axes get unflipped again)
d+=(i[j%3]*=(26564818>>j%3*8+q&2)-1)**2 #Flip axis j%3 according to the value of q (use magic number to lookup whether to flip or not.) Add coordinate squared to d.
j==2&& #If this is the 3rd iteration, flips are in correct state to perform the move, so do something.
(t ?i[-k=m%4]>1&&(i[1-k]*=-1;i[2-k]*=-1): #For E#, if the coordinate in axis -k=m%4 is +2 rotate 180 by flipping the other two axes.
i.max<1&&i.rotate!(m%8*((22>>q&2)-1)))} #For F# or C# if all axes 0 or less, rotate by permuting axes in direction determined by m%8 (A/C) & magic number 22
h=g[*i] #h = index to store the value in after carrying out move
d==10&&a[h/6][h%6]=n} #If d=(x*x+y*y+z*z)*2=10 coordinates are valid. Store the value in the array according to index h.
a} #Return array a
```
] |
[Question]
[
Write a program which can encode text to avoid reusing characters, and convert back.
Both normal and encoded forms are restricted to a particular character set: the space character with code point 32, the tilde character `~` with code point 126, and all characters between. This is 95 total characters. It's a printable subset of ASCII.
The encoded text can be up to 95 characters long. The normal text can be up to 75 characters long, because above 75 it would be impossible to uniquely encode all messages.
## Encoding
There are some requirements for the encoding:
* Uses only characters from the character set described above
* Uses each character at most once
* Uniquely encodes all valid messages
Other than that, you're free to pick any variant.
## Input
Input will consist of 2 items:
* A boolean: false to encode, true to decode
* A string: the message to be encoded/decoded
How you receive the input is up to you.
The boolean can be as a boolean or integer in the range [-2, 2] in your language's format. If the esoteric language doesn't have booleans or integers, use the closest analogue. I'm not doing the "or any 2 distinct values" because then you could use an encoding and decoding program as the values and evaluate them.
## Output
Output should consist of only the encoded/decoded string. Leading and trailing newlines are okay.
## Scoring
Your score is the length of your program, shorter is better.
I still encourage you to try harder languages even if they won't win.
## Testing
Testing will generally be done with [Try it Online!](https://tio.run/#). For convenience, please provide a link to your program with some test input already filled in.
These are the steps to test a program:
* Pick a valid normal string.
* Encode it using the program.
* Check that the encoded form is valid.
* Decode it using the program.
* Check that the final result matches the original string.
This can be repeated with other test strings for confidence.
If you show a working case and no failing cases have been found, we will assume your program works.
# Reference Implementation
I am providing a [reference implementation](https://tio.run/##xVdLj9s2EL7rV0yzB0lrrWMnSIsaNXpoijaHIpcUPTgLgStRMhuJVElqd5ND/no6fEgmZaeLnCofTHEenPnmRQ0f9VHwl1@u4LXgqQYtWdtSCfpIQdJ27IiEnjCelCUnPS1LWO0hvU6/PHv2LHlHHzVQXokaJQivoaZu3QgJA5X9qIlmgqt18qeiCggo1g8dBSGRi/F2nRg1CW4KqYFpKrUQnZo2eqKPSXIFozLGKLSt0rSG6kgkwZUERfUO1EAqCtnLFzloAZp1Nb5tX3yfJzNj2TCpNOzh5YtgsxIjN5s/vgo2Q7ORZkxYN0gSkpEuWwgHRxjmNF3/LRjPEsCnJ4NbmKc6ymJ@kYS39ERz9MjS4r@Iq4UREW@exKs8SWraGMAZJ13JhezRDQMlb/OdZTEhMP9/USBKsZZjKIHxmj4aPEnXgZOCnipFWorRtOxHVh1BcApMYbow9XOkDeM1dgbdjX01GXFPuhG5uYUGLSoiM8zjOG72S5fhBrYn@CbNfnENy5CunCJvhx4l97wxGC5z629Fw4t9Gxx3rI2w6Chv9dGA4bIB3yc7AjzUBzY8mYQIjtN2iv0iib@S3c@f2wNmKWMjVnfIY2kjxwKsUU/HlD6drtx5HdMaS/os0AXMFpd3RNnAf2KD97Jwbi9cKTbFzTYEwAG/9yas7Wtm1Z@crWnn6QdLv50ps2l@cb00aeUOCBPFguAFXLq0VIe4ZYr@M2IOoIN8kTO/UU4l0dR2T47h5WN/RyViF8iDaEwjnJS47PhoRZTGJkpkjfF8ZJVoJRkwq4JuGR42aZjiMr3ncfkdbuewlIt0mwQCvBf4nKVeJGeqMo9DhZigUM3ue1FnfJkC@aKG12QYKK9njetBDJnVk@dfK15XfXFALtXvr5bPIG2pxnUDcRgIq2rG9Z2deBa1B2abnoYjuUcV/CPU49CxyoT2lP5xOKZMvdxpL9T9PO3WNvWz/63sWRML/rR3zuyiweL8u7nQHuYxJbhm3LfdIHrRVJyeZVFFxGjoqeKM5my5jt04n4D27bDZOZhuXf64K8rT@fOaxvnTSNE/kUFfS4XFnLlYnw9H1tEl7r6k3FScy8pHArYFnF1HLtcX3j5c08TOtpiscaFNoXLi@WG3u9l63MwlMFtg9AfuQTPyyoDhMHjDh1E7rhtoOtLuYGMGp8OggK15cTHwTA4VvMbpsWlOrM8DprejDrR66EQzw@94cRFZZ05H1O6wxjKK7iNwqCXLvcs@ribZ7bbdJNYVg/VZmpg6sSpph53xvA3FYXWKopAPuNQTtHjpbWC@U@/x7liWBuKyTHf@@mjwTvBi/gsZMDgU3rxNrKkljonqg0sdYZEJd0ysGkrr0rl1jW2mVz5ubSfu8B4XaPH5etKB899K@NA7bbo6lu6kLNYUHh/7r7Fh0iykOxDCncPu9lQAcasvLVhItf/O7ylUTtjMimTiCrX6pDffDe/wmwGbOfbbeyKZGPELRLZjT7lWiWnG2FdbU6GmHR@sFWnquk36O@06UcCDkF393bT5Ob3@4ZVd3joYAqDTTVrMCvMwhGY53Rn3CzQPG@c9XjVxGoAbrzrz7HluMsNsThtwZa6XBJZ55@VT/GH77tksUWAmNwQh3SMttx9pPXm8QP2MVBTFfzzjSBS2cylppeOvrTOvt@j1ZNzSaVdDTzo9R2G/n0WuoB8xdu7VNAWFhWKFXGZkqWs07/l7bnY37i9dTcpWqSH5xjFxpStvqqPGKrYXec40xAek@Zd/AQ) that shows one possible method, in hopes of making this problem more approachable. I used it to generate the examples. I recommend you try the problem yourself before looking at how I did it, that way you may independently come up with a better mapping.
# Examples
Since you can choose a different encoding, as well as different input/output methods, your program might not match these examples.
## Empty
>
> Input:
>
>
>
> ```
> 0
>
>
> ```
>
> Output:
>
>
> (none)
>
>
> Input:
>
>
>
> ```
> 1
>
>
> ```
>
> Output:
>
>
> (none)
>
>
>
## Small
>
> Input:
>
>
>
> ```
> 0
> Hello, world!
>
> ```
>
> Output:
>
>
>
> ```
> #mvcD_YnEeX5?
>
> ```
>
> Input:
>
>
>
> ```
> 1
> #mvcD_YnEeX5?
>
> ```
>
> Output:
>
>
>
> ```
> Hello, world!
>
> ```
>
>
## Max Size
>
> Input:
>
>
>
> ```
> 0
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> ```
>
> Output:
>
>
>
> ```
> C-,y=6Js?3TOISp+975zk}.cwV|{iDjKmd[:/]$Q1~G8vAneoh #&<LYMPNZB_x;2l*r^(4E'tbU@q>a!\WHuRFg0"f%X`)
>
> ```
>
> Input:
>
>
>
> ```
> 1
> C-,y=6Js?3TOISp+975zk}.cwV|{iDjKmd[:/]$Q1~G8vAneoh #&<LYMPNZB_x;2l*r^(4E'tbU@q>a!\WHuRFg0"f%X`)
>
> ```
>
> Output:
>
>
>
> ```
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> ```
>
>
# Extras
How did I get the 75 characters limit? I could have brute force checked it of course, but there's a slightly more mathematical method for counting the number of possible encoded messages for a given character set:
$$
F(n)=\sum\_{k=0}^{n}{\frac{n!}{(n-k)!}}=e\Gamma(n+1,1)\approx en!
$$
Here are the relevant bounds. There's plenty more valid encoded messages than normal messages, but still enough normal messages that you'll need a variable length encoding.
$$
F(95)\approx 2.81\times 10^{148} \\
{95}^{75}\approx 2.13\times 10^{148} \\
95!\approx 1.03\times 10^{148}
$$
The problem was inspired by a phenomenon on the [Discord chat platform](https://discordapp.com). In Discord, you can "react" to chat messages, which adds a little emoji underneath. You can react many times on a single chat message. Each emoji can only be added once. They remember the order they were added and display oldest to newest, left to right. You can add some non-emojis too. People sometimes write short messages in reactions, and when their message has repeat characters they're forced to get creative, usually they opt for lookalike characters.
[Answer]
# Python 3, ~~339~~ 338 bytes
```
lambda b,s:b and G(f(s))or F(g(s))
a=''.join(chr(32+i)for i in range(95))
f=lambda s:95*f(s[1:])+ord(s[0])-31if s else 0
F=lambda n:chr((n-1)%95+32)+F((n-1)//95)if n else ''
g=lambda s,d=a:1+d.find(s[0])+len(d)*g(s[1:],d.replace(s[0],''))if s else 0
G=lambda n,d=a:d[(n-1)%len(d)]+G((n-1)//len(d),d.replace(d[(n-1)%len(d)],''))if n else''
```
[Try it online!](https://tio.run/##rVRbW6pAFH3OXzHeghG8oKKJoZWFWlpppSWgolzEcCDAzC7@9Q5kdaLzevh4mNlr7bXWN7DHWrszE@Xe1SWaAhYI74a0mMgSmJAOMwESkkEdV3EHQtMGHK75q5DEYlhqbuoIn85sPJcldKh6sA50BGwJaQpeoj2ayn5qOUyJTngiPMWIkDBt2VtmRJjMUboKHKAYjgIyIe6LjhhfFkdJCsZLNJHLQoLbbtNpT9jrQdseDAtp3x6kzEoMRcgpVUefBoShIFyGCW1rTcopW7EMaap8wCSGQfgzQP07wIeWzG8jbEVEov6VYVv4ofaL@SW8TYlh767iuKOp5CiOd8J8aIe/tpcK6cUXSW/DSR7re/cJNYJYIwCGN@EgHI7Ggt2KYZgkWJm2If@iNviaXZC5JrsgxGDTBksU8wHuZnZ4NVjor0Tr@V5SY0OnLArdyumy0Dk5n9/Gj/faAtbvQQpNrchDldHOGlnuUmH5lHuRuNnPjUckXi817Tc5nDRo83GdjtaKB6vM7uTuKB@wbv9j3ZYVvs9kL0viA7VrsnpKK0cELHP7bAzsxdX5ir6ZNedq9WySWF7kjg7WZC@23xWmL43wfbEelxAxtPaip@OT4@So0Em/3j3i3OawBoFzna8ErFueNR2wbtVR4mzfcCc31HknnscfutXjMDe@e8zstUf9NVl5WtzKK7Z8JGAFoiQko9fMQSydyi5PI2AO7Z44s4b8ZnBhNi6nJ7sv0ptD15ra4XOuqKv3ylXwzP/fE/zMG/0yis/6GiWyyXl6oRRU5iQzXcvVujs@bJcGR71U5eZ8KZ02H1vDNxqMnNcw0bh6Wu3aXDmR3T/rCLHJy0Nx7/722jSs2jG8Q/mDCJm7eI7zAtb13cSQP/X@f@0P/t@fnAntWLaOXBzjMRI4ro37ZX8gU8Z86bg4Db2EH683QZ8oJfpF0S8zQECC@4X6FxOe8DnQYziK5V0@8P0P "Python 3 – Try It Online")
Same length, uses a list instead of a string for the ASCII chars [Try it online!](https://tio.run/##rZRXe6JAFIav118xtgCCvWNIM0GNMRpNUQEVnQFJcDBgiSbxr2eHh5R193a54pTve88znGG@WUwtnP7QlngCBCB/mOpsDFUw5hx@DFQMQYXWaIfhVIlXGMsGIq3TjhcxPlWQJlObTqdYg9FI0QAGBraKdUQXs4zi04RPO4cvZiPER0oSHWvZkLwmFCaaThoacAAyHQQSPvGrHfOuLY2jSSZczLLpFMOKXhiPE2OiwZ6Gonz6N4ODfJKFMQND9OL5sybCNGQiukfmYMxGM2uFvCoZGDJ/8ivffGIFJY/vWShs5WsAL/Hj9Vfjt603IkV9LJCzGE5UBznkhCXfL@nWXiIOUFVkmhYH1pZtQj@lcKQiqkTilqSynYNiTZixSsgrfYp2VCSf2evdTU87/Znxxl5tn1QtNHBKitw@ulzmbi6uH7vh80JDph7umSSezAPPx7xer6bEFhKk2KIZuTtMj4YcXSnW7Hfoj5pZa7WJB8v5k3XiYNw7y@yhG/@gGxBJD3yqVVSekweWYMT0UkCmEt2t2bdnnet19m5ae9SO6@PIspk@O9lw96HDtjx5rfqf8pWwitnBvBC8HF2cR4e5m/hbb0WLu9MyA5zbzNEe@oqgs3voqwqO1A/NxfgueX0TztDP7eNzvzjqrRKFxvBhwx29zLpwLZTOZCrHFuVo8JY/CcVjqeVlADwy9r0ynQ@kXb9pVVuTi4NX9d3Jlmv66TadN7Qn1Nk/8//37H/mndEK0tMHPakI0cf4DOU0/iIx2cDjymJ02ij2z@5jR3fXS/WytroavGfB0Hnzs9XOy/rAFkuR1GH9Rg6NX5/zhafurWXOy@dMD2dOAly6uQ1LMtV2aeQWko1018@9nD@7yPt@zW0DL2g3IrPwQMbyIkBxwP0X0BE3zZC8m3HQXKAo5uM3 "Python 3 – Try It Online").
Overview: WIP
* Because the number of printable ASCII strings with 75 or fewer characters is `21570794844237986466892014672640809417999612393958961235356099871415520891159490775110725336452276983325050565474469409911975201387750975629116626495`, which is less than the number of valid encoded strings (`28079792812953073919740255779032193344167751681188124122118245935431845577725060598682278885127314791932249387894125026034584206856782082066829102875`)
+ All we need to do is theoretically sort the valid encoded strings and the valid non-encoded strings, take the index in the correct list of our given input, then return the string at that index in the *other* list.
* `f`: Converts an input (non-encoded) string to an integer based on its index in the theoretical list of ASCII strings sorted by length and then lexicographically.
+ The empty string is 0
+ Single-char strings are 1 to 95
+ Two-char strings are 96 to 9120, etc.
* `F`: Undoes `f`, converts an integer to a (non-encoded) string.
* `g`: Converts an input (encoded) string to an integer (<= `28079792812953073919740255779032193344167751681188124122118245935431845577725060598682278885127314791932249387894125026034584206856782082066829102875` for valid inputs) based on its index in the theoretical list of valid encoded strings sorted by length and then lexicographically.
+ The empty string is 0
+ Single-char strings are 1 to 95
+ Two-char strings are 96 to 9025, etc.
* `G`: undoes `g`, converts an integer to an (encoded) string.
* Main function: Unnamed `lambda b,s:b and G(f(s))or F(g(s))`: Uses the boolean `b` to determine whether to encode `G(f(s))` or decode `F(g(s))` the string, and does so.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 94 bytes
```
≔⁰ζ¿N«≔γδ≔¹εFS«≧⁺×ε⊕⌕γιζ≧×Lγε≔Φγ¬⁼κιγ»Wζ«§δ⊖ζ≔÷⊖ζ⁹⁵ζ»»«F⮌S≔⁺×⁹⁵ζ⊕⌕γιζWζ«≦⊖ζ§γζ≔Φγ¬⁼κ§γζγ≧÷⊕Lγζ
```
[Try it online!](https://tio.run/##jZHPT8IwGIbP7K/4PJh8TWoiBw5IYkKCxCVKCOrNy9g@usau4NpNMuVvnyv7IcODHru877unT8M4SMNtoMpyaowUGq85FGziyQ2gr3eZXWTJmlJkDD69QZMRHKIq0x6HHMgdN9u0KT3ZVGrRlAaPwa5OrqSILS5VZjg8y4QMEgdfhyklpC1FOJc6cuuSMVZz/GofexweSAsbo2DNv1uWuVS2wq02FluLd@9ZoAy@tYvCRQ/e4COWigCLmm9ZwVqcWl9HtMeIw4x@kIqqeLLvazuTuYwI@yEO41GLfPAOQMqQGz86WVFOqaEzNwyaTSekvheOR27jTyl9/s7QKVOrr3854T7/x1e/0Lk7f41ORx@5e50TJWU59O5vwv3Fy@TrVvHXy/IqV98 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰ζ
```
Set `z`, which represents the permutation index, to zero, as both sides of the condition need it.
```
¿N«
```
If the first input (as a number) is non-zero, then we're doing encoding.
```
≔γδ
```
Save a copy of the predefined ASCII character set `g` in `d`, as we need to change it.
```
≔¹ε
```
Assign `1` to `e`. This represents the place value of each encoded character.
```
FS«
```
Loop over the encoded characters.
```
≧⁺×ε⊕⌕γιζ
```
Update the permutation index.
```
≧×Lγε
```
Update `e` with the place value of the next encoded character.
```
≔Φγ¬⁼κιγ»
```
Remove the character from the encoding set.
```
Wζ«
```
Repeat while the permutation number is non-zero.
```
§δ⊖ζ
```
Print the next decoded character.
```
≔÷⊖ζ⁹⁵ζ»»
```
Divide the bijective representation by 95. This completes decoding.
```
«F⮌S
```
Loop over the plain text in reverse, to avoid having to calculate the powers of 95.
```
≔⁺×⁹⁵ζ⊕⌕γιζ
```
Convert the plain text as bijective base 95 to the permutation index.
```
Wζ«
```
Repeat while the permutation index is non-zero.
```
≦⊖ζ
```
Decrement the permutation index.
```
§γζ
```
Print the next encoded character.
```
≔Φγ¬⁼κ§γζγ
```
Remove that character from the encoding set.
```
≧÷⊕Lγζ
```
Divide the permutation index by the previous length of the encoding set.
[Answer]
# [Haskell](https://www.haskell.org/), ~~346~~ 472 bytes
After fixing of the bug noticed by Anders Kaseorg the program unfortunately grew larger.
```
(x:y)?f|f x=(0,x)|0<1=(p+1,q)where(p,q)=y?f
a!n=take n a++drop(n+1)a
x#f=fst$f?(x==)
a x y z=y!!(q z-1)+b z s x
b[]_ _=0
b(x:y)f c=u(x#f)+v f*(b y(c f x)c)
c=const
e=divMod
f n|n<2=1|1<2=n*f(n-1)
g y z x=h(x-r)l s y where(l,r)=z?(x<)
h n l f c|l<1=[]|0<1=f!!w m:h d(l-1)(c f m)c where(d,m)=n`e`v f
i=r(k^)
k=95
o=r(\x->f k`div`f(k-x))
q=length
r f=scanl(+)0$map f[1..k]
s=[' '..'~']
u=toInteger
w=fromInteger
v=u.q
x=g(\a->(\b->a!w b))o.a c i
y=g c i.a(\a->(\b->a!(b#a)))o
```
[Try it online!](https://tio.run/##rVRdb9owFH33r7i0lbAbQmFSNQ3hVlNhWqV@aWXbA7BiEptEBBtsUxKE@tfZDbRqp@2hD7Mix/fm@JxjXzuJcFOZZdt0NjfWQ0d4Ub9KnYcwBJ@kDvDRUsYyBmUseOm8A6OzYkvzVsHO1UZBzmmjlrNNo93kdB40awu2SqSVdI4jXpwrIiqaezGVoEEEQWzNnOqgyQTJDxVXzh@pc5pzzoiAHApY86JSoQtYh00WjGENDnIy7g8f4IE3yHinrCDiS4rzWfAI6piOoaARoBkWMRLxyGjnieRx@nhtYqJAb3T7A29umtjrY0U1cpNJKYb@E5qHlmWoU8DeelazjK/RVZuRBG1nSB1tMlxhf7hbqKpUVjBrJRDTDKl22jMWPU@PazPG9UiO0BtJuaXTX4xM@adTYjAY5OGZgukIzY0UnYY5Y2TBM6knPiEWFHeR0BkNWONoJuag@s16fTokjverUK3Xq0/VIVlyby61lxNpyYora2Yv0SNf1hck5xM6EOEZHYzDM4Fex4yZuoAIUlLwSfmui7cIOj4UDDHbssa4ExwOBvry5u57rwUABxAEmMTuAE5OYO@1xOzyiVkBfc45hikCLw1JujcXt51up7UHSx29hwZhfxHd337rlTx7OHXlif0XrtN9KxjLdwkijL2y7MoIrzG20jjH8@n@yJbsHI8NfiUzkWoMYvOKyKEdwkT6C4PV0f7NXKzsNcyX/t7bKw20LPRu52mWaokHnrFtD2PyFa@nqcFPY7O4Qnrlnbx08BlujIcf0hZwZfQESiggVaon5On/tb3enreULbWkhV4iNHw8hYtEWBF5aV0Nc7hj@I@Q5Qi6OjJxOenOmkg6B19Emrnf "Haskell – Try It Online")
Use `x "Hello World"` to encode and `y "TR_z"` to decode.
## How?
We can enumerate all possible input sequences and all possible encoded sequences, so the encoding is rather simple:
1) determine the number for the input sequence;
2) construct the output sequence corresponding to that number.
(The decoding is done in the reverse order).
## Explanation
This is an original (pre-golf) version for ease of understanding.
```
-- for ord
import Data.Char
-- all possible characters
s = [' ' .. '~']
-- get the first position in a list where the predicate returns True
(x:y) `firstPosWhere` fn
| fn x = 0
| 0<1 = 1 + firstPosWhere y fn
-- the same as above but return both the position and the list element
(x:y) `firstPosAndElemWhere` fn
| fn x = (0, x)
| 0 < 1 = (p + 1, q) where (p, q) = firstPosAndElemWhere y fn
-- the sets of numbers corresponding to input strings and to encoded strings are divided into ranges
inputRanges = scanl (+) 0 [95 ^ x | x <- [1..95]]
outputRanges = scanl (+) 0 [fac 95 `div` fac (95 - x) | x <- [1..95]]
-- convert an input string into a number
toN s = inputRanges !! (length s - 1) + toN' s
toN' [] =0
toN' (x:y) = toInteger (ord x - 32) + 95 * toN' y
-- convert a number into an (unencoded) string
fromN n = fromN' (n - r) l where
(l, r) = inputRanges `firstPosAndElemWhere` (n <)
fromN' n l
| l < 1 = []
| 0 < 1 = s !! fromInteger m : fromN' d (l - 1) where
(d, m) = n `divMod` 95
-- factorial
fac n|n<2=1|1<2=n*fac(n-1)
-- remove nth element from a list
a `without` n = take n a ++ drop (n + 1) a
-- construct an encoded string corresponding to a number
encode n = encode' (n - r) l s where
(l, r) = outputRanges `firstPosAndElemWhere` (n <)
encode' n l f
| l < 1 = []
| otherwise = (f !! m') : encode' d (l - 1) (f `without` m') where
(d, m) = n `divMod` (toInteger $ length f)
m' = fromInteger m
-- convert an encoded string back into number
decode z = r + decode' z s where
r = outputRanges !! (length z - 1)
decode' [] _ = 0
decode' (x:y) f = toInteger p + (toInteger $ length f) * (decode' y (f `without` p)) where
p = f `firstPosWhere` (x ==)
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 182 bytes
```
import StdEnv,Data.List
$b s=hd[v\\(u,v)<-if(b)id flip zip2(iterate?[])[[]:[p\\i<-inits[' '..'~'],t<-tails i,p<-permutations t|p>[]]]|u==s]
?[h:t]|h<'~'=[inc h:t]=[' ': ?t]
?[]=[' ']
```
[Try it online!](https://tio.run/##RY3BaoQwEIbvPsVAF3RBxRZ6WUy9bA@FPRS2t5hDNsZ1QGNIxoWWpY/eNGKhp5nv5/9m1KilCdPcLaOGSaIJONnZEZypezW3/ChJlif0lOwu4NnQ8VvbZkt@29cF9tlljx30I1r4QvuUIWknSTdc7DkXB27bFmPPIHmeQlqW6XcqcqoLkjh6wNzWhdVuWkgSzsYD3e0LF0LcF8a8SBo@HEjchzp6jKNRsDJbbx2gobWwkQhnko6SB9BGzZ0GBh9u0ZE9OTTXyDwl7SkVMesXo9Z/Md0l7B//3E0JP6of5dWH4u0Ujp9GTqg2eB8l9bObQjGEx6qq4uLD8zouvw "Clean – Try It Online")
Enumerates every valid encoding and every valid message, returning one or the other depending on the order of the arguments `zip2` receives. Explained:
```
$ b s // function $ of flag `b` and string `s` is
= hd [ // the first element in the list of
v // the value `v`
\\ (u, v) <- // for every pair of `u` and `v` from
if(b) // if `b` is true
id // do nothing
flip // otherwise, flip the arguments to
zip2 // a function which creates pairs applied to
(iterate a []) // repeated application of ? to []
[[]: [ // prepend [] to
p // the value `p`
\\ i <- inits [' '..'~'] // for every prefix `i` in the character set
, t <- tails i // for every suffix `t` of `i`
, p <- permutations t // for every permutation of the characters in `t`
| p > [] // where `p` isn't empty
]]
| u == s // where the second element `u` equals `s`
]
? [h: t] // function ? of a list
| h < '~' // if the first element isn't a tilde
= [inc h: t] // increment it and return the list
= [' ': ? t] // otherwise change it to a space
? [] // function ? when the list is empty
= [' '] // return a singleton list with a space
```
***It's really, really slow!*** Faster (in practice) version below (but with similar time complexity):
```
import StdEnv,Data.List,Data.Func,StdStrictLists,StdOverloadedList
increment :: [Char] -> [Char]
increment []
= [' ']
increment ['~':t]
= [' ':increment t]
increment [h:t]
= [inc h:t]
chars =: hyperstrict [' '..'~']
? :: *Bool [Char] -> [Char]
? b s
= let
i :: *[[Char]]
i = inits (chars)
t :: *[[Char]]
t = filter (not o isEmpty) (concatMap tails i)
p :: *[[Char]]
p = concatMap permutations t
in (if(b) encode decode) [] [[]:p]
where
encode :: [Char] *[[Char]] -> [Char]
encode d l
| d == s
= Hd l
| otherwise
= encode (increment d) (Tl l)
decode :: [Char] *[[Char]] -> [Char]
decode d l
| Hd l == s
= d
| otherwise
= decode (increment d) (Tl l)
```
[Try it online!](https://tio.run/##jVNNb5wwEL3zK6bZtkCa3WwPuSCRldKkaqVUrbS5UQ5eMMGSsZE9JFqp6k@vOwaysO0e4ovn482bx4wpJGfKNbrsJIeGCeVE02qDsMXyTj1d3DJkq3thcbA@d6q4oNQWjSjQx613vz9xIzUreelDQSBUYXjDFUKSQPapZiaH5fVozbJZHgCdFLIQwqNE@DtMcJ5NpiQeIesZjsLQ@0FBnSykCdT7lhvby@15ViuiJsDGSzu/0Vr@L3ADO7Ajp@TYW/6IviYbUPksnIJQAi1Efdv4kMHTBUgFlZDIDURKI2gQ9q5pcR8Tg1YFw2@sBWRCWhATW3uarSW2qYq@tumQodDKwiBdKIhEFe1i4KrQJYeS@yum8UOW5UmbB881N7wHj5Bpb4eGswHNgCXIg5Jf5KXpOLqXk8KXY4xGavYsLP8HNhJG025LmseDBDmMYFD9CmUj8LirF3FKXPkKZSPhKWVui8xgsHhRn8KD6Tj5/smpx/7xIrcY5peXWfju/fmbs3jxFqKf4Qd6hQuo6IfyuyLgJkgnd6QbWNyfopLs0brl13t3u1esEcXg/JAMK20at6zdx/V6TYZ1V/7auWXVWaL6Cw "Clean – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 28 27 bytes
```
ØṖµœ!95ݤ,ṗ75ݤ$Ẏ€³œ?µḢi⁴ịḢ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5zEpOSU1LT0Rw1zD209OlnR9OjuQ0t0Hu6cbgJiqDzc1feoac2hzUcn2x/a@nDHosxHjVse7u4Gsv7//2/wPy01NQUA "Jelly – Try It Online")
Since this code generates all the permutations and therefore would take very long to finish, TIO link is to a limited version that supports characters `abcdefg`, message length 4 and encoded length 5. I checked that these numbers follow similar constraints as the actual ones. Only the constants are changed, so the true version should also (theoretically) work.
## Explanation
```
ØṖµœ!95ݤ,ṗ75ݤ$Ẏ€³œ?µḢi⁴ịḢ Dyadic link that accepts the boolean flag and message
ØṖ ASCII printable characters
µ Feed into new monadic chain
œ! Permutations of size
95ݤ 0..95
, $ Pair with
ṗ Cartesian power
75ݤ 0..75
Ẏ€ Flatten both lists (non-recursively)
³œ? Reverse the pair if the boolean flag is set
µ Feed into new monadic chain
Ḣ Pop first item of the pair
i⁴ Find index of the message
ịḢ Index into the head of what used to be the pair
```
] |
[Question]
[
This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge based around defining languages and proving they are Turing complete.
This is the robbers' thread. [The cops' thread is here](https://codegolf.stackexchange.com/questions/162290/escape-from-the-tarpit-cops).
# Robbers
The cops will post definitions of Turing-complete languages. Your task is to crack them by proving that they are indeed Turing complete. See the [cops' challenge](https://codegolf.stackexchange.com/questions/162290/escape-from-the-tarpit-cops) for more details and formal specifications.
[Answer]
# [ais523's answer - Blindfolded Arithmetic](https://codegolf.stackexchange.com/a/162531/69850)
(I hope my proof is understandable. I can't check my own proof e.g. with a [Try it online!](https://tio.run/##XVDLasMwELzrKxZykISN87ol1V/06EMUa9MIogd6NPHXuyuTUqhgQczOzO5OnMs9@OOyGLyB9cXYb/HqZ3liYG8wK7U7xUS4sJKB6Z0iggtm5TBIWGryYDrhQHsD5mMnGbMuhlSo@fvLc2YMXzgJrtVVTcqo3dkqDl1rDZmm@iGhNg/rUUiC@eifd/tA@EwVT6MH3rVpQ65XQT3e84b1f5gY5JaK94m/rxj3/XiQjfNviKDFpWRyWfaHI7S3octjLXBHsgO@4Rl0QpiCc@hLHphVtrMrsTQOuJoLXBF8AFqzYI56wiYKlVK4bC9MK73VqyKXEJsMYgpfSTtGAXTmbWYzPIPnq1kLqBY0Pw) link so I'm not sure)
All code in this post will be Python pseudocode, with `rep n:` repeat `n` times. All conditionals must be either `0` or `1`.
It's provable that the value of `i` is always >0 in the program execution, so `i/i` always give `1`.
Define some building blocks:
`if c: a = a + b` is equivalent to `d = b * c; a = a + d;` assuming `d` is unused.
So, let `(statement)` be `if c: statement` where `c` can be some condition.
`b = b * 2**N` (where `N` is a compile-time constant) is equivalent to
```
rep N: b = b + b
```
`b = a / 2**N` is equivalent to
```
b = i / i
b = b * 2**N
b = a / b
```
`b = a % 2**N` is equivalent to
```
b = a / 2**N
b = b * 2**N
b = a - b
```
---
Any 2-symbol Turing machine with `N` states can be written like this:
```
while True:
if state == 0:
# process state 0
if state == 1:
# process state 1
.
.
.
if state == HALTING_STATE:
0 / 0
.
.
.
if state == N-1:
# process state N-1
state = newstate
```
where each `# process state` block looks like this
```
# optional (not all states need this)
tape.move_left()
# optional
tape.move_right()
# optional
tape.flip()
new_state = a if tape.value() else b
```
This needs to be translated to BFA compatible code.
---
Two variables `i` and `a` will be used to represent the tape and `state` (and `tape` as well)
The content of `i` at each wraparound:
* `N` least significant bits are equal to `2**state` (i.e., the `state`'th significant bit is on, all other bits are off)
* The rest of bits form the right half of the tape.
The content of `a` at each wraparound:
* The left half of the tape.
The tape pointer is on the least significant bit of `a`.
---
At the beginning of each loop, `N` bits are inserted between the tape part and the state part in `i`:
```
d = i / 2**N
d = d * 2**N
i = i - d
d = d * 2**N
i = i + d
```
At each `# process state i` block, the structure of `i` is:
* `M-N` least significant bits: the remaining part of the old value of `state` (`state >> i`). (where `M = 2*N - i`)
* `N` next LSB: (partial) value of `new_state` (or `0` if it's not defined yet in that loop)
* Rest: Tape.
Of course `M` is a compile time constant.
(as an exception, the "process halting state" block can be implemented as
```
if i%2: b = b - b; b = b / b;
```
or equivalently (assume `c` isn't used)
```
c = i % 2; b = i / i; if c: b = b - b; b = b / b;
```
)
---
More rewriting:
* `(tape.move_left())` (the outer `()` stands for conditional, as always)
```
# allocate a free bit on (i)
b = i / 2**M
(i = i + b)
# copy that bit from (a) to (i)
b = a % 2
b = b * 2**M
(i = i + b)
# remove a byte from (a)
b = i/i
(b = b + b)
a = a / b
```
* `(tape.move_right())`
```
# allocate (M+1) bits at the end of (a)
(a = a * 2**(M+1))
# copy that from (i) to (a)
b = i % 2**(M+1)
(a = a + b)
# remove the (M) bits from (a) that is over-copied from (i)
b = i/i # now b==1
rep M: (b = b + b)
a = a / b # if the conditional fails a = a / 1 is a no-op.
# clear that bit on (i)
b = a % 2
b = b * 2**M
(i = i - b)
# remove the bit from (i)
b = i / 2**(M+1)
b = b * 2**M
(i = i - b)
```
* `(tape.flip())`
```
b = a % 2
b = b * 2
(a = a - b)
b = i/i
(a = a + b)
```
* `(new_state = a if tape.value() else b)`
>
> TODO
>
>
>
---
There are 2 remaining issues:
* Only the bits to the left of the pointer is outputted, and
* `if not tape_value(): tape.move_left()` (and the equivalent `move_right`) is not directly supported.
To solve those problems,
* A TM with only a half of the tape is still TC.
>
> You can interlace the positive-index cells with the negative-index ones, and replace every movement with a double-movement (doubling the number of states). You'll also need to mark two cells at the left with special symbols so you know to shift by one and turn around (1 extra symbol; 1 extra state), and you'll need to have a reversed copy of every state for when you're in negative-land and every movement is backwards (again doubling the number of states).
>
>
>
([source](https://www.quora.com/Can-a-Turing-machine-with-a-tape-bounded-from-one-side-simulate-a-universal-Turing-machine))
So, it's possible to:
1. Make the tape from 2 interleaving infinite tapes.
2. One of them only have one `1` denoting the right end of the tape. The other is used to store data.
3. At program halt, instead of immediately exiting, move right until hit the end of the tape.
So the whole tape are stored in the right half (i.e., `i`) and readable at program termination.
---
>
> Am I still missing something?
>
>
>
] |
[Question]
[
My job is stacking pebbles into triangular piles. I've only been doing this for a century and it is already pretty boring. The worst part is that I label every pile. I know how to decompose pebbles into [piles of maximal size](https://codegolf.stackexchange.com/questions/118361/decompose-a-number-into-triangles), but I want to minimize the number of piles. Can you help?
# Task
Given an integer, decompose it into the minimum number of [triangular numbers](https://en.wikipedia.org/wiki/Triangular_number), and output that minimum number.
### Triangular Numbers
A triangular number is a number which can be expressed as the sum of the first `n` natural numbers, for some value `n`. Thus the first few triangular numbers are
```
1 3 6 10 15 21 28 36 45 55 66 78 91 105
```
# Example
As an example, let's say the input is `9`. It is not a triangular number, so it cannot be expressed as the sum of `1` triangular number. Thus the minimum number of triangular numbers is `2`, which can be obtained with `[6,3]`, yielding the correct output of `2`.
As another example, let's say the input is `12`. The most obvious solution is to use a greedy algorithm and remove the largest triangular number at a time, yielding `[10,1,1]` and an output of `3`. However, there is a better solution: `[6,6]`, yielding the correct output of `2`.
# Test Cases
```
in out
1 1
2 2
3 1
4 2
5 3
6 1
7 2
8 3
9 2
10 1
11 2
12 2
13 2
14 3
15 1
16 2
17 3
18 2
19 3
20 2
100 2
101 2
5050 1
```
# Rules
* The input integer is between 1 and the maximum integer of your language.
* I can emulate any language with [my pebbles](https://xkcd.com/505/), and I want your code as small as possible because I have nothing but pebbles to keep track of it. Thus this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code **in each language** wins.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~57~~ 49 bytes
```
.+
$*
(^1|1\1)+$
1
(^1|1\1)+(1(?(2)\2))+$
2
11+
3
```
[Try it online!](https://tio.run/##Rco9DoMwGIPh/T0HSF8aqYoTws/UsZdAVTswsHRAjNw9hInBkq3H27Kv/19p7f0tT0/zwD46NMv5Bt3DZC@Lbo7ugojkSaWo1kRHpmdgZEKhGqqPhDqUUY8GNKKJWDVcETnkcAI "Retina – Try It Online") Based on my answer to [Three triangular numbers](https://codegolf.stackexchange.com/questions/132834/). Change the third line to `^(^1|1\1)*$` to support zero input. Edit: Saved 8 (but probably should be more) bytes thanks to @MartinEnder.
[Answer]
# Mathematica, 53 bytes
```
Min[Plus@@@Table[$($+1)/2,{$,#+1}]~FrobeniusSolve~#]&
```
This code is very slow. If you want to test this function, use the following version instead:
```
Min[Plus@@@Table[$($+1)/2,{$,√#+1}]~FrobeniusSolve~#]&
```
[Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com)
### Explanation
```
Min[Plus@@@Table[$($+1)/2,{$,#+1}]~FrobeniusSolve~#]& (* input: n *)
Table[$($+1)/2,{$,#+1}] (* Generate the first n triangle numbers *)
~FrobeniusSolve~# (* Generate a Frobenius equation from the *)
(* triangle numbers and find all solutions. *)
Plus@@@ (* Sum each solution set *)
Min (* Fetch the smallest value *)
```
[Answer]
# Jelly ([fork](https://github.com/miles-cg/jelly/tree/frobenius)), 9 bytes
```
æFR+\$S€Ṃ
```
This relies on a fork where I implemented an inefficient Frobenius solve atom. Can't believe it's already been a year since I last touched it.
## Explanation
```
æFR+\$S€Ṃ Input: n
æF Frobenius solve with
$ Monadic chain
R Range, [1, n]
+\ Cumulative sum, forms the first n triangle numbers
S€ Sum each
Ṃ Minimum
```
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 58 bytes
```
function(n)3-n%in%(l=cumsum(1:n))-n%in%outer(c(0,l),l,"+")
```
[Try it online!](https://tio.run/##JcoxCoAwDEDR3VNIQUgwhVRxET2MFAtCjdLawdNHxenD4ycN9WRrDUX8tR0Cgr2VZpMG4uzLnssObhTEH49yrQk8MEWkSKY1qHk5z3i/V8cUsArg2H0ZeGDUBw "R – Try It Online")
Explanation:
```
function(n){
T <- cumsum(1:n) # first n triangular numbers [1,3,6]
S <- outer(c(0,T),T,"+") # sums of the first n triangular numbers,
# AND the first n triangular numbers [1,3,6,2,4,7,4,6,9,7,9,12]
3 - (n %in% S) - (n %in% T) # if n is in T, it's also in S, so it's 3-2: return 1
# if n is in S but not T, it's 3-1: return 2
# if n isn't in S, it's not in T, so 3-0: return 3
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
0rSƤṗ⁸S⁼¥Ðf⁸ḢTL
```
[Try it online!](https://tio.run/##y0rNyan8/9@gKPjYkoc7pz9q3BH8qHHPoaWHJ6QB2Q93LArx@f//vykA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), ~~75~~ ~~63~~ 61 bytes
```
f=(n,x=y=0)=>y<n+2?x*x+y*y-8*n-2+!y?f(n,x<n+2?x+1:++y):2-!y:3
```
### How?
We use the following properties:
* According to [Fermat polygonal number theorem](https://en.wikipedia.org/wiki/Fermat_polygonal_number_theorem), any positive integer can be expressed as the sum of at most 3 triangular numbers.
* A number ***t*** is triangular if and only if ***8t+1*** is a perfect square (this can easily be proven by solving ***t = n(n+1) / 2***).
Given a positive integer ***n***, it's enough to test whether we can find:
* ***x > 0*** such that ***8n+1 = x²*** (***n*** itself is triangular)
* or ***x > 0*** and ***y > 0*** such that ***8n+2 = x²+y²*** (***n*** is the sum of 2 triangular numbers)
If both tests fail, ***n*** must be the sum of 3 triangular numbers.
```
f = (n, x = y = 0) => // given n and starting with x = y = 0
y < n + 2 ? // if y is less than the maximum value:
x * x + y * y - 8 * n - 2 + !y ? // if x² + y² does not equal 8n + 2 - !y:
f( // do a recursive call with:
n, // - the original input n
x < n + 2 ? x + 1 : ++y // - either x incremented or
) // y incremented and x set to y
: // else:
2 - !y // return either 1 or 2
: // else:
3 // return 3
```
### Test cases
```
f=(n,x=y=0)=>y<n+2?x*x+y*y-8*n-2+!y?f(n,x<n+2?x+1:++y):2-!y:3
;[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 100, 101, 5050 ]
.forEach(n => console.log(n + ' --> ' + f(n)))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
`G:Ys@Z^!XsG-}@
```
[**Try it online!**](https://tio.run/##y00syfn/P8HdKrLYISpOMaLYXbfW4f9/QwNDAA "MATL – Try It Online")
### Explanation
```
` % Do...while
G: % Push range [1 2 3 ... n], where n is the input
Ys % Cumulative sum: gives [1 3 6 ... n*(n+1)/2]
@Z^ % Cartesian power with exponent k, where k is iteration index
% This gives a k-column matrix where each row is a Cartesian tuple
!Xs % Sum of each row. Gives a column vector
G- % Subtract input from each entry of that vector. This is the loop
% condition. It is truthy if it only contains non-zeros
} % Finally (execute before exiting the loop)
@ % Push iteration index, k. This is the output
% End (implicit). Proceeds with next iteration if the top of the
% stack is truthy
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~176~~ 154 bytes
## Submission
```
{var l=it
var n=0
while(l>0){n++
val r=mutableListOf(1)
var t=3
var i=3
while(t<=l){r.add(t)
t+=i
i++}
l-=r.lastOrNull{l==it|| r.contains(l-it)}?:r[0]}
n}
```
## Beautified
```
{
// Make a mutable copy of the input
var l=it
// Keep track of the number of items removed
var n=0
// While we still need to remove pebbles
while (l > 0) {
// Increase removed count
n++
// BEGIN: Create a list of triangle numbers
val r= mutableListOf(1)
var t = 3
var i = 3
while (t<= l) {
// Add the number to the list and calculate the next one
r.add(t)
t+=i
i++
}
// END: Create a list of triangle numbers
// Get the fitting pebble, or the biggest one if none fit or make a perfect gap
l -= r.lastOrNull {l==it|| r.contains(l-it)} ?: r[0]
}
//Return the number of pebbles
n
}
```
## Test
```
var r:(Int)->Int =
{var l=it
var n=0
while(l>0){n++
val r=mutableListOf(1)
var t=3
var i=3
while(t<=l){r.add(t)
t+=i
i++}
l-=r.lastOrNull{l==it|| r.contains(l-it)}?:r[0]}
n}
data class TestData(val input:Int, val output:Int)
fun main(args: Array<String>) {
val tests = listOf(
TestData(1,1),
TestData(2,2),
TestData(3,1),
TestData(4,2),
TestData(5,3),
TestData(6,1),
TestData(7,2),
TestData(8,3),
TestData(9,2),
TestData(10,1),
TestData(11,2),
TestData(12,2),
TestData(13,2),
TestData(14,3),
TestData(15,1),
TestData(16,2),
TestData(17,3),
TestData(18,2),
TestData(19,3),
TestData(20,2),
TestData(100,2),
TestData(101,2),
TestData(5050,1)
)
tests.map { it to r(it.input) }.filter { it.first.output != it.second }.forEach { println("Failed for ${it.first}, output ${it.second} instead") }
}
```
[TryItOnline](https://tio.run/##fVNNT@MwEL37VwxoD7aSRkk/aKlw0UoLEhJiD8sNcfA2KVi4TmVPFqGQ314mCewJ2wd/zJv3ZjyaeanRaHv8pxy4Nb@xKCYb2kEe295mpEbWX6zM2euzNhU3m1y0NknIbMDJfYPqr6lutcffO16IwRvlbDg1nSMLL6QRrctUWXIUDBOpmU6SjpmJdJlRxHZ3jTGtkRTy/R1ctq0tKm09NxONortcu4f8sWO2O5YKFWyJ5OG@8viLnrzPRttDg2tKP4X@WTf4@RaM7RoLe5Ljyj35Nfx0Tr1d/EGn7dNGQMuAVk9CEvQgwYwfGuxf63@wIi1E@j00TachaBZmzcOsRToLQWdhwWVYcBUWPA@zijwcrCgivEhBilkEm4fTLBaRXM4imsuI5irCOw/zpnmsZlEwUrVFvujrPYDjPvRltlcHaEEjYA2Oa8yGlhfQZTttsHIDSHfnMRvbH05kb/IVjVPZ@9XuSm2fyfFAvY/G8tNrRRNaAiHwo/2id@nn/Iy2kd/RiHmsVHlKIVl3/AA)
] |
[Question]
[
I need to call my friends but the buttons of my cordless phone are not working properly. The only buttons I can press are [Up], [Down] and [Call]. [Up] and [Down] can be used to navigate in my recent calls and [Call] can be used to call the selected name. My phone has a list that holds `N` recent calls, and I know that all the friends I need to call are in this list.
---
# Task:
You'll receive a number `N` and a list of names `L`:
* `N` is the number of recent calls my phone can remember;
* `L` has the names in the order I need to call.
You must output the number of button presses I need to make in an optimal arrangement of the recent call list.
---
# Example:
### -> Input:
Calling Anna, Bob and then Anna again. With a recent calls list of size 5.
```
5
Anna
Bob
Anna
```
### -> Output:
Possible optimal arrangement: `Anna, Foo, Bar, Foobar, Bob`
```
5 # Key presses: [Call] Anna, [Up] + [Call] Bob, [Down] + [Call] Anna
```
### More test cases:
```
Input: 5, Anna, Bob, Carl
Output: 5
Input: 5, Anna, Bob, Carl, Anna
Output: 8
Input: 5, A, B, C, D, E, A
Output: 11
Input: 6, A, B, C, D, E, A
Output: 12
Input: 4, A, B, C, B, A
Output: 10
```
---
# Rules:
* Your cursor will always start in the first position of the list;
* You can take the input `N` and `L` from any source: keyboard, parameters, file, etc;
* The names in the list can be in any reasonable format such as: strings, integers, chars;
* When you reach the end of the recent calls list and presses [Down] again, your cursor wraps around. The same happens when you're at the begining of the recent calls list and presses [Up];
* When you call someone, that person's name will be moved to the first position of the recent calls list and the rest will be pushed down;
* When you call someone, your cursor will be moved to the first position;
* A friend name cannot appear more than once in the recent calls list;
* You can fill your recent calls list with dummy entries (see example);
* The number of friends to call will not be greater than `N`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~195~~ ~~185~~ 164 bytes
*-4 bytes thanks to @notjagan*
*-27 bytes thanks to @FelipeNardiBatista*
```
lambda n,l:min(g([*x],l,n)for x in permutations(range(n)))
def g(x,l,n,r=0):
for p in l:a=x.index(p);x=[x.pop(a)]+x;r-=~min(a,n-a)
return r
from itertools import*
```
[Try it online!](https://tio.run/##ZU9Na8MwDL3nV@hWu1NCunY7pHh/JMvBI05msGWjuuBRur@e2YwNxi4P6aH3ofiR3gMdt0W9bk77t1kDoRu8JbGKcZ8ndEhyCQwZLEE07K9JJxvoIljTagRJKZvZLLCKXI@RVS@HBqomVo0btMqdpdlkEeU5qzF3MUSh5fSQz9yqz5qmkVotG2CTrkzAzcLBg02GUwjuAtbHwGm/VdvSsBqP4gnHHg/4OEn8nbH/sx3x9M08/2NOP8yh7lPpDJEtJbG73RFud2hfCu66Eul1EiUVl4rl4e0L "Python 3 – Try It Online")
`L` is taken as a list of integers from `[0, N)`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~97~~ ~~95~~ 94 bytes
```
->n,a{r=a.size;1.upto(r-1){|i|r+=[p=a[(a[0,i].rindex(a[i])||i-2)+1...i].uniq.size,n-p].min};r}
```
[Try it online!](https://tio.run/##lczfCoIwFAbw@55CvHI4x4zqRhZk9RTDi1kGB2zadFA5n33pLgpC@nNzDh/n9x2l85s9MRutJRadYoI0cC@SmOi6rQIVxagzYFTIeM0EDwSnGDKiQB6L65AgQ8ZANEdhTAgZLlrCxb3AMqozcgbZJ6q3tW4b70QOoiyDJfa4v5FS@Njz0yofl4sZmn1zW6HKn93Hvw47Oo7dOPau8c5X//HFBE8nZUwpfeJXIx2cfQA "Ruby – Try It Online")
In an optimal arrangement, the first name will take one press (`Call`). Names that have not been called yet take two presses (`Up` `Call`), and names that have take varying numbers depending on how many other unique names have been called since then and whether that places them closer to the top or the bottom of the list.
I think this is a strategy similar or identical to WaffleCohn's.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 213 143 bytes
```
(N,L)=>L.reduce((t,v,i)=>{x=0,a=[v]
for(j=i;j-->=0&!~a.indexOf(L[j]);x++)a+=L[j]+","
return i?t+((x=L.indexOf(v)-i?x:1)<N-x?x:N-x):t},L.length)
```
[Try it online!](https://tio.run/##lYyxTsMwFEX3fIXxUNmyHRUJOjS4VQtsVvmAKIObOMUh2JXjWkYIfj0kGehSqepy37tP57xGBtmVTh896466Uu7Tmg/11QfpQA14j3ZUYL4SqVPVqVQIeRqoHi7fkc@p5Hkokto61HCdNYyt@Hx29ytTbSoV32ok8qbAWSQES8LHQiCFiVP@5AzQa08Qilz84wEzvY7Le/y0Y3FYhsRL/0NF2ipz8O@4L63pbKvS1h5QjR4pyOHGGAkpgFu7H8dUC4yz5Dr7LF17E3v1/yRM@BgvY7xO1iVlcbvycEHZnun@Dw "JavaScript (SpiderMonkey) – Try It Online")
Generates an optimal arrangement of the given names then counts the number of key presses.
Skipped the generation and just counted how many key presses it would take each name in the optimal arrangement
] |
[Question]
[
You must make a regex that matches everything except itself. For example, `PPCG` must not match `PPCG`, but must match everything else, like `something`, `PPC`, and `PPCG!`.
Surrounding slashes are **not** considered part of the regex in flavors where they are usually part of the syntax. The same is true of all delimiters.
The regex needs to match the entire string, not just a substring.
You may choose your flavor, but you can't use a flavor newer than this challenge. Please pick a flavor that is easily tested.
Shortest regex in bytes wins.
([Sandbox (deleted)](https://codegolf.meta.stackexchange.com/a/12781/58826))
[Answer]
## PCRE flavour, 45 bytes
```
^(?!\^()(?R){2}\z)|\1\Q(?!\^()(?R){2}\z)|\1\Q
```
[Try it at regex101.](https://regex101.com/r/B0u3bq/1)
This is a simple modification of [jimmy23013's brilliant solution to the opposite challenge](https://codegolf.stackexchange.com/a/31863/8478). We just need to make two changes:
* In this challenges, the delimiters shouldn't be matched so we drop them from the regex as well. However, that could lead to infinite recursion, because then no characters would be matched before the `(?R)` call. To fix this, we match the `^` explicitly with `\^` to have one character before we enter the recursion.
* We need to negate the result which is as simple as wrapping everything after the `^` in a negative lookahead to ensure that the input *isn't* equal to the string.
For the details of this quining approach, see jimmy's amazing answer.
] |
[Question]
[
Lets play golf while we golf.
# Problem:
* Distance to the hole initially is 700m
* Each hit to the ball will make it advance to the hole 250-350m, this should be random.
* Each hit has a 5% probabilities of going into water, this will make the quantity of hits increase by 1 as a penalty.
* When ball is under 250m it will advance 70% to 90% (random again) of missing distance with a probability of 80%, Advance 90% to 99% with 14% Probability, 1% of doing 10%(and finishing) and 5% of going to water and increasing the number of hits by 1 as a penalty.
* When ball is under 10m it has 95% of going into hole (finishing) and 5% of advancing 75% of the missing path. No probability of going water.
Clarifications:
-Imagine ball is 270m from hole, if we hit for 300m, the distance to the hole is now 30, this means, distance will be absolute value.
-Numbers will always be integer due to deal the probability of hitting for example 300m when ball is 300m away from the hole.
-Round down number of m of the hit, imagine you are at 1m , if you fall on 5% of not going into the hole, it will advance 0.
## Input:
Nothing
## Output:
Distance to the hole in each hit /n
Total number of hits
Example output (don't print comments)
>
> 433m //Hit for 267m (700-267=433)
>
>
> 130m //Hit for 303m (433-303=130)
>
>
> 130m //Ball on water +1 penalty hit
>
>
> 35m //Hit for 95m (130-95=35)
>
>
> 7m //Hit for 28m (35-28=7
>
>
> 0m //Ball on hole
>
>
> Total hits 7 //6 hits +1 penalty
>
>
>
This is codegolf!
[Answer]
# [Python 3.6](https://docs.python.org/3/), 250 bytes
Saved 4 bytes thanks to isaacg, and 1 thanks to KoishoreRoy!
```
d=700 # Current distance
from random import*
r=randrange # Function that gets a random value in the range [0, input)
i=0 # Number of strokes
while d:
i+=1;x=r(20)<1 # x is False 95% of the time
# My justification for reusing this random value
# is that it's used once and only once, separate by if/elif
if d<10:d-=[d,d*.75][x] # We're within putting range; goes in if x is true; otherwise makes 75% progress
elif x:i+=1 # Goes in the water, add a stroke
elif d<250:
s=r(95);d-=[d,d*[.7+r(21)/100,.9*r(10)/100][s<15]][s>0]
# Only 95 because we already checked to see if it would go in the water
# 99% of the time (s>0), it doesn't go in
# 14% of the time (s<15), it makes 90-99% progress
# Otherwise, it makes 70-90% progress
else:d-=250+r(101) # Lose 250-350 yards
d=int(abs(d));print(f'{d}m')
print(f'Total hits {i}')
```
[Try it online!](https://tio.run/##NY1NjoMwDIX3OUV24KbDOK0QKpA5RXeIBSPTEok/JZGGnp46bWdhPX/28/P6CMMyn/edTIEo7LQuLkjXzbRMwpl3k0XhuvfCGhR/gx17SaWQVhldbcalJ4RaM98k1RpL@jINHemQFXnbbK2Q/cirrYz@D1B9ypEjpOfzSw7V/02TFYoDNXxrxGN2ObhU4wvaxtc6b1l@8JXp@/iJc1T0aBCSjJ1D2v36lACq1UXywTGpZEpAvCfJdQndKAcbvExU3FuAfX8C "Python 3 – Try It Online") (Uses Python 3.5 printing syntax at a cost of 6 bytes since TIO does not yet support Python 3.6.)
[Answer]
# [Perl 6](http://perl6.org/), 212 bytes
```
my&p=(^*).pick;say 'Total hits ',(700,->\d{my \n=d>249??abs d-(p(20)??250+p
100!!0)!!d>9??d-(|((d*(70+p 21)div 100) xx 80),|((d*(90+p 10)div 100) xx
14),d,|(0 xx 5))[p 100]!!p(20)??d div 4!!0;"{n}m".say;n}...0)-1
```
`&p` is a helper function that picks a random number from `0` to one less than its argument. The expression after `'Total hits '` is a lazily-constructed list that generates each element based on the previous element. The elements are printed as they are generated, which isn't very functional, but it is shorter than storing them in an intermediate array.
[Answer]
# JavaScript, ~~204~~ 198 bytes
```
P=console.log
r=x=>Math.random()*x
for(d=700,h=0;d;)x=r(100),D=d>=250?r(20)<1?h++*0:250+r(100):d*(d<10?x<5?.75:1:x<5?h++*0:x<6?1:.9+r(x<20?.09:-.2)),d=Math.abs(d-D|0),h++,P(d+'m')
P('Total hits '+h)
```
Less golfed:
```
r=x=>Math.random()*x
for(d=700,h=0;d;){
x=r(100),
D=
d>=250
? r(20)<1
? h++*0
: 250+r(100)
: d * (d<10
? x<5
? .75
: 1
: x<5
? h++*0
: x<6
? 1
: .9 + r(
x<20
? .09
: -.2
)
),
d=Math.abs(d-D|0),
h++,
console.log(d+'m')
}
console.log('Total hits '+h)
```
] |
[Question]
[
**TL;DR**: Solve this particular challenge, a robot simulation, by stepping on all of the white pads, and avoiding the gray pads. You can step on a white pad any number of times, as long as you step on each white pad at least once. Solutions in languages like Befunge with a 2D instruction pointer would also be accepted, but H comes with the [uHerbert](http://www.oocities.org/uherbert2/) program and its language specifications are given below. You do not need the uHerbert program to solve this, but it makes checking your solution a lot easier.
Here is what the level looks like. This is a 25x25 grid of cells, in which the robot and each white and gray pad occupy one cell. The robot is initially facing upward.
[](https://i.stack.imgur.com/74OMV.png)
**Background on uHerbert**
Herbert is a robot simulation which I first encountered in the online IGF (Independent Games Festival) programming challenge back in 2008. For a long time, I was disappointed that I couldn't try out the challenges after the actual contest was over. Luckily, someone else must have read my mind and coded up this dandy little program: [uHerbert](http://www.oocities.org/uherbert2/) (aka mu-Herbert or micro-Herbert).
**H (Language Specifications)**
The program is a robot simulation, but also acts an interpreter for the programming language H which serves only to move the robot.
There are three instructions:
* S: the robot steps one cell forward
* L: the robot turns left 90 degrees in place
* R: the robot turns right 90 degrees in place
There are three standard programming features at your disposal: functions, parameters, and recursion. Two different parameter types are supported.
**Numeric parameters**
```
g(A):sslg(A-1)
```
Here, g is a function with a one numeric parameter. This is boiler plate code; following this you can write your actual program by calling your function and passing an argument:
```
g(4)
```
This would call your function 4 times, and the recursion automatically terminates when your parameter `A` reaches a value of zero:
```
g(4) = sslg(4-1) = sslg(3) = sslsslg(2) = sslsslsslg(1) = sslsslsslssl
```
**Functional parameters**
You can also use functional parameters, which basically just reproduce instructions that you pass in:
```
f(A):rAlA
```
So if you call this function and pass instructions, it would evaluate to:
```
f(ss) = rsslss
f(sslssr) = rsslssrlsslssr
```
**Other syntax**
Functions can have more than one parameter, and they can also have both types. They could alternatively have no parameters. The following are both valid functions as well:
```
j:ssss
k(A,B):Ajjjk(A,B-1)
```
As you can see, the function j takes no parameters, and the function k takes both types of parameters. A is a functional parameter and B is a numeric parameter, as described above.
**Infinite recursion**
Infinite recursion is also allowed, but can only be initiated once and is effectively terminated when you step on the final white pad (without having stepped on any gray pads):
```
m:sslssrm
```
**Solve condition**
The goal is to get the robot to step on all of the white pads, and to avoid stepping on any of the gray pads. White pads can be stepped on any number of times, as long as each one is stepped on at least once. The robot is able to step on any point in the grid that it can reach (some levels have barrier walls and in this level the gray pads sort of act as a barrier).
The puzzle shown earlier is available on the site above from **level\_pack2.zip** and is called **level3.txt**. Both the uHerbert program and the level pack are still available from the above link as of today (the site has been archived but the archive engine still hosts it), but they are not required for a solution.
**I would like to see the shortest solution possible as per code golf.** Solutions in languages other than H will not be accepted as valid. (It would certainly be interesting to see an example solution in a language like Befunge where the instruction pointer travels on a 2D grid, but per atomic code golf scoring, only H instructions can be given an accurate score. The instruction pointer could be treated as the robot's position, for example.) A valid solution is one where the robot steps on all the white pads (each at least once) and does not step on any gray pads. Stepping in other parts of the grid is fine but in this particular puzzle you can't do that without stepping on a gray pad. The starting position of the robot cannot be changed.
I should also note that solutions which jump to a non-adjacent cell will not be accepted. This is not possible for the robot in the simulation, and would not represent a valid solution. H does not allow this anyway. So a valid solution must be one comprised of single steps. For each cell in the grid, there are only four adjacent cells: the ones orthogonal to it (above, below, and to the left and right). This of course would disallow diagonal steps, but because you are only able to turn in 90 degree increments, diagonal steps are not even possible.
If the robot is given an instruction which requires it to move into a barrier or outside the grid, the result is basically "derp" - the robot hits the wall and stays where it is, and the instruction pointer moves to the next instruction (the instruction is basically skipped).
**Note about solution size**
When you open this level in the program, you'll notice it is apparently possible to solve in 13 bytes. I am totally baffled as to how that is possible, and curious to see how close others are able to come to that. My shortest solution is 30 bytes in H. If anyone wants me to post it, I will, but I'd like to see other solutions before posting mine. The program also gives you a score, but the score is irrelevant to this question. Solutions of any score will be accepted.
It seems that the uHerbert program does not count parentheses or colons as part of your program (you will see this when it counts up your bytes). So for the purposes of this question, in the H language, parentheses and colons will not count as bytes towards your solution since they are primarily delimiters and purely syntactical rather than semantic in nature.
[Answer]
# H, 13 bytes
```
a:ssr
b:sasaaab
b
```
### Demo
[](https://i.stack.imgur.com/HWrMN.gif)
] |
[Question]
[
# The Challenge
In this challenge, you are supposed to write a program or function that takes in a String, which will contain the simplified Markdown-like Markup, and outputs the corresponding HTML Markup.
---
# The Input
You can take input in whatever way you wish to. The `type` of the input should be String.
---
# The Output
You can output the result in any way you want. Logging to Console or Terminal, printing on screen, returning from function etc. are perfectly valid.
---
# The Rules
* Convert each occurrence of `*foo*` and `_foo_` to `<em>foo</em>`.
* Convert each occurrence of `**foo**` and `__foo__` to `<strong>foo</strong>`.
* Convert each occurrence of `<tab or four spaces here>foo\n` to `<pre><code>foo</code></pre>`.
* Convert each occurrence of `#foo\n` to `<h1>foo</h1>`.
* Convert each occurrence of `##bar\n` to `<h2>bar</h2>`.
* Convert each occurrence of `###bar\n` to `<h3>bar</h3>`.
* Convert each occurrence of `####bar\n` to `<h4>bar</h4>`.
* Convert each occurrence of `#####bar\n` to `<h5>bar</h5>`.
* Convert each occurrence of `######bar\n` to `<h6>bar</h6>`.
* Convert each occurrence of `[foo](https:\\www.bar.com)` to `<a href="https:\\www.bar.com">foo</a>`.
* Convert each occurrence of `` to `<img src="https:\\www.bar.com" alt="foo"/>`.
* Convert each occurrence of `>foo\n` to `<blockquote>foo</blockquote>`.
* Convert each occurrence of `- foo\n` as `<li>foo</li>` (add `<ul>` before the `li` if the `-` is the first of its consecutive series and add `</ul>` if it is the last.)
* Convert each occurrence of `n. foo\n` (where the first `n` denotes an Integer such as 12,1729 etc.) as `<li>foo</li>` (add `<ol>` before the `li` if the element is the first of its consecutive series and add `</ol>` if it is the last.)
* Although there exist many more rules of conversion, you are supposed to follow only the abovementioned ones (for the sake of simplicity).
* You are supposed to output only the corresponding HTML Markup for the given String. No need to add extra elements that are necessary for creating a valid HTML file (like `<body>`, `<html>` etc.). However, if they are present in the input String, then you will have to output them too, that is, replace `<` and `>` with `<` and `>`, repspectively.
* *You must NOT use any built-in! (I doubt whether there exists one)*
**Note :** In the abovementioned rules, `foo`, `bar` and `https:\\www.bar.com` are only placeholders. Your program or function must be flexible enough to work for Strings different than these too.
---
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
---
# Test Cases
```
"**Hello**" -> "<strong>Hello</strong>"
"#IsThisAwesome?\n" -> "<h1>IsThisAwesome?</h1>"
"> -> "<blockquote><img src='https:\\www.somewhereontheintenet.com' alt='Image'/></blockquote>"
">Some Content\n- Item1\n- Item2\n- Item3\n" -> "<blockquote>Some Content</blockquote><ul><li>Item1</li><li>Item2</li><li>Item3</li></ul>"
"1.Hello\n2.Bye\n3.OK\n" -> "<ol><li>Hello</li><li>Bye</li><li>OK</li></ol>"
```
---
# Special Thanks to [FakeRainBrigand](https://codegolf.meta.stackexchange.com/users/3402/fakerainbrigand)!
This challenge was originally proposed by [@FakeRainBrigand](https://codegolf.meta.stackexchange.com/users/3402/fakerainbrigand) in the Sandbox. He granted me the [permission](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/656#656) to post this challenge on the regular website. Due to unclear and broad specifications, the challenge was closed. Now, it has been reopened with clearer and fewer specs by [@Arjun](https://codegolf.stackexchange.com/users/45105/arjun).
[Answer]
# PHP, 770 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/4202b268bfa43041300a426637cf9f51d90e4443)
There are some rules to make html with this markup
the replacement of blockquote must before all others
h6,h5,h4,h3,h2,h1 is the next order
strong, em
img, a
and (li ,ul, li,ol) or (li ,ol, li,ul)
```
$s=[
"%>(.*)\n%Us"
,'%(\*|_)\1(.+)\1\1%Us'
,'%(\*|_)(.*)\1%Us'
,'%######(.*)\n%Us'
,'%#####(.*)\n%Us'
,'%####(.*)\n%Us'
,'%###(.*)\n%Us'
,'%##(.*)\n%Us'
,'%#(.*)\n%Us'
,'%- (.*)\n%Us'
,'%(?<!</li>)<li>%Us'
,'%</li>(?!<li>)%Us'
,'%\d+\. (.*)\n%Us'
,'%(?<!li>|ul>)<li>%Us'
,'%</li>(?!<(li|/ul)>)%Us'
,'%(\t| )(.*)\n%Us'
,'%!\[(.*)\]\((.*)\)%Us'
,'%\[(.*)\]\((.*)\)%Us'
];
$r=[
'<blockquote>\1</blockquote>'
,'<strong>\2</strong>'
,'<em>\2</em>'
,'<h6>\1</h6>'
,'<h5>\1</h5>'
,'<h4>\1</h5>'
,'<h3>\1</h5>'
,'<h2>\1</h5>'
,'<h1>\1</h5>'
,'<li>\1</li>'
,'<ul><li>'
,'</li></ul>'
,'<li>\1</li>'
,'<ol><li>'
,'</li></ol>'
,'<pre><code>\2</code></pre>'
,'<img src="\2" alt="\1"/>'
,'<a href="\2">\1</a>'
];
echo preg_replace($s,$r,$i);
```
[Answer]
# [Lua](https://www.lua.org/), 641 bytes
```
t={"<","<","^.+(>)",">","^(#+)(.*)",function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end,"^>(.*)","<blockquote>%1</blockquote>","^[\t ]+(.*)","<pre><code>%1</code>","!%[(.-)%]%((.-)%)",'<img src="%2" alt="%1"/>',"%[(.-)%]%((.-)%)",'<a href="%2">%1</a>',"%*%*","","__","","%b","<strong>%1</strong>","","","%b**","<em>%1</em>","%*","","%b__","<em>%1</em>","_",""}for l in io.lines()do u,U=l:match("^- ")or u and print("</ul>"),u o,O=l:match("^%d%. ")or o and print("</ol>"),o for i=1,#t,2 do l=l:gsub(t[i],t[i+1])end print((l:gsub("^- (.*)",(U and""or"<ul>").."<li>%1</li>"):gsub("^%d%. (.*)",(O and""or"<ol>").."<li>%1</li>")))end
```
[Try it online!](https://tio.run/##bVJNb6MwEL314F8xMfLWJsQo2VvkIDXdj/bUy/aUTREBAqgGZ8GcVvvbs2OHKq1UCXu@3ntjxtZjdj7bzV@qaES/aIv7i5zzRLiw8iEP5oLLEDPHscttYzqeRQfRl3bsO05VzYqEDSp2lor10fRtZnmAmCjIRNkVqJFcBKg6aJO//hmNLRO2VPG70LXa/bawn79hT32ZqNwUF6h3MD1jOy4Xgu0Z9xaht6ppKxj6fEPZikKmLTpLGie3Ef0MnUHdl0cP9tKZB4YsRPkbXGk6Oexw44wabG@6ymMndwJ4TOh4qmx9HY1Lhm9Fr/Wx6DL0H84JNDQdNEbqpisHLgoDY/S80WscYF5z@rIAKhA2QtYVcOqbzuK841HjnKMRTPT0DssKJi9w8xFuPNyAa9hsllFgoxVgK43kahgP3O6afYTbfLl31zUx@VR1p7jcCH92wpSanip/Bimp0o3/MzR49xPBH2XiPF055jOOcC3P5yB4KLU2M0J@1c0A@GWAU3ldw652hT2vrT0N6zg@GiNz0wry2GZVuYbZDjPXsiO5eoxPQp66SpDkquhfGlnAHa4trnuylHC3vScrCd@@/yBfJfx8eCRhuDW6CENIU@ekKQnL9lRj7ExK/gM "Lua – Try It Online")
### Readable Version and Explanation
```
t = { -- Table used for simple replacements
"<", "<",
"^.+(>)", ">", -- Cannot be at the beginning of a line because of blockquotes
"^(#+)(.*)", function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end, -- Combined h# replacement
"^>(.*)", "<blockquote>%1</blockquote>",
"^[\t ]+(.*)", "<pre><code>%1</code>",
"!%[(.-)%]%((.-)%)", '<img src="%2" alt="%1"/>',
"%[(.-)%]%((.-)%)", '<a href="%2">%1</a>',
"%*%*", "", -- Using the actual control character is shorter than using an escape code
"__", "",
"%b", "<strong>%1</strong>",
"", "",
"%b**", "<em>%1</em>",
"%*", "",
"%b__", "<em>%1</em>",
"_", ""
}
for l in io.lines() do -- For every line in STDIN
u,U=l:match("^- ") or u and print("</ul>"),u -- Some compact logic to print the end of the lists and mark things as such
o,O=l:match("^%d%. ") or o and print("</ol>"),o
for i=1,#t,2 do
l=l:gsub(t[i],t[i+1]) -- Run through the table of replacements
end
print(( -- Use two parentheses so that we only print the first return value
l:gsub("^- (.*)", (U and "" or "<ul>") .. "<li>%1</li>") -- Rest of the list logic
:gsub("^%d%. (.*)", (O and "" or "<ol>") .. "<li>%1</li>")
))
end
```
I can expand upon specific things if wanted, but it's very late as-of posting this so it'll have to wait until later.
] |
[Question]
[
Your goal is to write a full program or function that takes 5 positive integers and a string with an image filename as input `[X1,Y1], [X2,Y2], N, image.jpg` in any reasonable format, where:
* First couple `[X1,Y1]` are the top left `X`,`Y` coordinates (`<=20`) of the blue rectangle area in the example picture (`16,11`).
* Second couple `[X2,Y2]` are the bottom right `X`,`Y` coordinates (`<=20`) of the blue rectangle area in the example picture (`20,22`).
* Fifth number `N` such `0 <= N <= 9` is the number that has to be found.
* Sixth parameter is a string with the filename of this [JPG picture](https://i.stack.imgur.com/afIkv.png).
Output how many of `N`'s are present in the indicated area (outlined in blue in the picture for this example):
[](https://i.stack.imgur.com/51B0y.png)
[Click here](https://i.stack.imgur.com/Y6cCZ.png) to obtain a bigger clean version of the same image.
In the picture there are 500 numbers from `0` to `9` (included) arranged in 20 columnns per 25 rows, in monospaced `Courier New` font.
Each different number has a different color (you can take advantage of this fact or ignore it and consider or convert the image in monocrome if that helps you).
**Test cases:**
```
[4,4],[13,5],1,image.jpg > 4 (outlined in red)
[4,4],[13,5],4,image.jpg > 2 (outlined in red)
[17,5],[17,5],2,image.jpg > 1 (outlined in magenta)
[17,5],[17,5],9,image.jpg > 0 (outlined in magenta)
[20,8],[20,9],3,image.jpg > 1 (outlined in cyan)
[20,8],[20,9],2,image.jpg > 0 (outlined in cyan)
[16,11],[20,22],0,image.jpg > 8 (outlined in blue)
[16,11],[20,22],3,image.jpg > 9 (outlined in blue)
[3,14],[11,20],7,image.jpg > 6 (outlined in green)
[3,14],[11,20],5,image.jpg > 6 (outlined in green)
[3,14],[11,20],8,image.jpg > 8 (outlined in green)
[1,1],[20,25],0,image.jpg > 47 (whole picture)
[1,1],[20,25],8,image.jpg > 50 (whole picture)
[1,1],[20,25],1,image.jpg > 55 (whole picture)
```
**Rules:**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* You must take as input this [JPG file](https://i.stack.imgur.com/Y6cCZ.png).
* You are not allowed to hardcode the matrix of numbers represented in the JPG, or the results.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
[Answer]
# Mathematica, 92 bytes
```
Count[Take[Characters@StringSplit@TextRecognize@Binarize[Import@#4,.9],#2,#],ToString@#3,2]&
```
Unnamed function taking the arguments in this format: `[{X1,X2}, {Y1,Y2}, N, "image.jpg"]`. (Indeed, the fourth argument can be either the local file name or the URL `http://i67.tinypic.com/6qh5lj.jpg`.)
`Import@#4` imports the image file, `Binarize[...,.9]` darkens all of the numbers to black, and `TextRecognize` (the function clearly doing the heavy lifting here!) extracts a multi-line string from the resulting image, which is split into a nested list of characters with `Characters@`.
`Take[...,#2,#]` keeps only the characters corresponding to the outlined rectangle, and `Count[...,ToString@#3,2]` counts the number of occurrences of `N` in the result.
[Answer]
# Python 3 + pillow + pytesseract, 239 bytes
```
from PIL.Image import*
from pytesseract import*
def c(a,b,n,f):w,h=b[0]-a[0]+1,b[1]-a[1]+1;return len([1for i in range(h*w)if image_to_string(open(f).convert('L').point(lambda x:[9,0][x<250],'1')).split()[i//w+a[1]-1][i%w+a[0]-1]==str(n)])
```
This is horribly inefficient as for each number tile, the whole file is parsed. The much faster and slightly longer **243 bytes** solution would be
```
from PIL.Image import*
from pytesseract import*
def c(a,b,n,f):s=image_to_string(open(f).convert('L').point(lambda x:[9,0][x<250],'1')).split();w,h=b[0]-a[0]+1,b[1]-a[1]+1;return len([1for i in range(h*w)if s[i//w+a[1]-1][i%w+a[0]-1]==str(n)])
```
] |
[Question]
[
Your program has to take a multi-lined string, like this:
```
#############
# #
# p #
# #
#############
```
`p` is the player and `#` is a block.
Now under that in the terminal should be an input line saying:
```
How do you want to move?
```
If the player types `l` he has to walk left when there isn't a block, else, when there is a block, he can't go through and doesn't move of course, now the output in the terminal has to be updated (and the previous output cleared/overwritten):
```
#############
# #
# p #
# #
#############
```
He can type `l` for left, `r` for right, `u` for up and `d` for down.
The input will always be multiline, but won't always be padded with spaces into a perfect rectangle. In addition, the hashes can be anywhere in the string, and won't always be connected to each other. For example:
```
## ##
# #
## p
#
```
is a valid dungeon. (note the lack of trailing spaces on each line)
If the player goes outside of the string, he doesn't have to be displayed. But if he comes back later, he must be displayed again.
And the boundaries of "outside" the string are the `length(longest_line)` by `number_of_lines` rectangle, so even if one line isn't padded with spaces on the right, that location isn't considered out of bounds. Example using the earlier dungeon:
```
## ##
# #p
##
#
```
The second line didn't have a space where the p is now, but that doesn't matter.
Finally, your program must loop forever taking input.
## Test cases
Test case 1:
```
####
# p#
#
####
How do you want to move?
d
####
# #
# p
####
```
Test case 2:
```
####
p#
#
####
How do you want to move?
l
####
p #
#
####
How do you want to move?
d
####
#
p #
####
How do you want to move?
l
####
#
p #
####
How do you want to move?
l
####
#
#
####
How do you want to move?
r
####
#
p #
####
```
Of course, these aren't complete. Your code should loop forever and **clear the screen between each output**.
Your output is allowed to prompt for input as `How do you want to move?\n<input>` or `How do you want to move?<input>` (i.e. you don't need the input on a blank line), and you don't need a empty line between the final line of the dungeon and the prompt. (they can't be on the same line however)
Standard loopholes are disallowed !
This is code-golf, so the shortest code in bytes wins!
[Answer]
# Haskell :: 799 703 bytes
Hi
This is my first code-golf submission.
It reads the initial grid from a text file.
Golfed:
```
import Data.List
x=maximum
n=minimum
r=filter
s=length
pad i r=r++(' '<$[1..(i-s r)])
f l=let{w=x.map s$l;h=s l}in r((/=' ').snd).zip(flip(,)<$>[h,h-1..]<*>[1..w]).(pad w=<<)$l
sh b=let{t=x.map(snd.fst)$b;d=n.map(snd.fst)$b;l=n.map(fst.fst)$b;sr _ []=[];sr i xb@((x,c):b)|x==i=c:sr(i+1)b|1>0=' ':sr(i+1)xb}in putStr.unlines.map(sr l.sort).map(\r->[(x,c)|((x,y),c)<-b,y==r])$[t,t-1..d]
x!b|x`elem`map fst b=b|1>0=(x,'p'):r((/='p').snd)b
b?i=let((x,y):_)=[x|(x,'p')<-b]in(case i of{'r'->(x+1,y);'l'->(x-1,y);'u'->(x,y+1);'d'->(x,y-1);_->(x,y)})!b
m b=do{putStrLn"How do you want to move?";i<-getChar;putStr"\ESC[2J";let{d=b?i};sh d;m d}
main = do{l<-readFile"s.txt";let{s=f.lines$l};sh s;m s}
```
An arguably more readable version:
```
import Data.List (sort)
data Board = Board [((Int,Int),Char)]
fromList l =
let width = maximum . map length $ l
height = length l
coords = zip
[(x,y) | y <- [height,height-1..1], x <- [1..width]]
(concat (map (pad width ' ') l))
clean = filter (\((_,_),c) -> c /= ' ') coords
in Board clean
instance Show Board where
show (Board xs) =
let top = maximum . map (\((_,y),_) -> y) $ xs
bottom = minimum . map (\((_,y),_) -> y) $ xs
left = minimum . map (\((x,_),_) -> x) $ xs
rows = map (\r -> [(x,c) | ((x,y),c) <- xs, y == r]) [top,top-1..bottom]
showrow _ [] = []
showrow i xxs@((x,c):xs)
| x == i = c : showrow (i+1) xs
| otherwise = ' ' : showrow (i+1) xxs
in unlines . map ((showrow left) . sort) $ rows
insert z (Board zs) = Board (z:zs)
remove y (Board xs) = Board [(x,c) | (x,c) <- xs, x /= y]
at x (Board xs) =
let match = [c | (x',c) <- xs, x' == x]
ifempty [] = ' '
ifempty (c:_) = c
in ifempty match
move from@(x1,y1) to@(x2,y2) cur@(Board zs)
| to `elem` [x | (x,c) <- zs] = cur
| otherwise =
let c = at from cur
in insert (to,c) . remove from $ cur
find c (Board b) = [(x,y) | ((x,y),c') <- b, c' == c]
main = do
startlist <- readFile "start.txt"
let start = fromList . lines $ startlist
print start
maingameloop start
maingameloop board = do
putStrLn "Where would you like to move?"
inp <- getChar
putStr "\ESC[2J"
let newboard = movePlayer board inp
print newboard
maingameloop newboard
movePlayer board inp =
let (cur@(x,y):[]) = find 'p' board
in case inp of
'r' -> move cur (x+1,y) board
'l' -> move cur (x-1,y) board
'u' -> move cur (x,y+1) board
'd' -> move cur (x,y-1) board
_ -> board
pad :: Int -> a -> [a] -> [a]
pad i c cs = cs ++ replicate (i - length cs) c
```
[Answer]
# **MATLAB, ~~268~~ ~~247~~ 246 bytes**
Probably not competitive, but it was fun. Golfed version:
```
function f(s);d=char(split(s,'\n'));[y,x]=ind2sub(size(d),find(d=='p'));while 1;d
c=uint8(input('How do you want to move?','s'))-100;v=y+~c-(c==17);w=x+(c==14)-(c==8);try;d(y,x)=' ';end;try;if'#'==d(v,w);v=y;w=x;end;d(v,w)='p';end;y=v;x=w;clc;end
```
Readable version:
```
function f(s)
% Split the string on newlines and convert to a padded char array
d = char(split(s,'\n'));
% Get the initial indices of p
[y,x] = ind2sub(size(d),find(d=='p'));
% Loop forever
while 1
% Implicitly display the dungeon
d
% Get the ASCII of the user input, minus 100 (saves a few bytes in
% the comparisons)
c=uint8(input('How do you want to move?','s'))-100;
% Get the new y from the ASCII
v = y+~c-(c==17);
% Get the new x from the ASCII
w = x+(c==14)-(c==8);
% Clear the player from the dungeon if they are in it
try
d(y,x)=' ';
end
% Check if new position is a #, and revert to old position if so
try
if '#'==d(v,w)
v=y;w=x;
end
d(v,w)='p';
end
% Update x and y
y=v;
x=w;
% Clear the screen
clc;
end
```
The `try` blocks are to prevent the function from crashing on out of bounds errors. I'm sure that two of them is overkill, but I can't golf it down any better than that.
It's worth noting that MATLAB will expand the array downwards and to the right, but the player will disappear when moving to an 'unexplored' area for the first time. For example, if you move outside the dungeon's current boundaries to the right by one space, you will disappear, but next turn MATLAB will expand the array to include the new column (or row, if you are moving downwards). `'#'==d(y,x)` saves a byte compared to `d(y,x)=='#'`, since you don't need a space between `if` and `'#'`
[Answer]
# Coffee-script: 580 Bytes
I've squeezed everything I could out of this particular algorithm and my tired brain. I need a holiday.
```
C=console
e='length'
N=null
f=(S)->
x=y=X=Y=N
q=(c,v)->
X=[x+c,N][+(-1<x+c<w)]
Y=[y+v,N][+(-1<y+v<h)]
try L[y+v][x+c]!='#'catch
1
r=(s)->
if (X||Y)
return
L[y]=((t=L[y].split '')[x]=s)
L[y]=t.join ''
while 1
L=S.split '\n'
[h,w]=[L[e],L[0][e]]
x=[X,x][+(x?)]
y=[Y,y][+(y?)]
for k in[0..h*w-1]
if L[k//h][k%w]=='p'
x=k%w
y=k//h
C.clear()
C.log S
r(' ')
switch prompt("How do you want to move?")
when'l'
q(-1,0)&&x--
when'r'
q(1,0)&&x++
when'u'
q(0,-1)&&y--
when'd'
q(0,1)&&y++
r('p')
S=L.join '\n'
```
] |
[Question]
[
What general tips do you have for golfing in [Emotinomicon](//conorobrien-foxx.github.io/Emotinomicon/int.html)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Emotinomicon (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
Should be answers to respective challenges (if they exist). Note that some of these code samples might alerady be answers somewhere else.
If you just want to print `undefined`, use this 4-byte, 1-char program.
```
üò®
```
Infinite loop (6 bytes, 2 chars).
```
‚Ñπ‚è©
```
Cat (owned by Conor O'Brien) (15 bytes, 5 chars).
```
⏫⏪⏬⏫⏩
```
This program should output the 8 phases of the moon, but it doesn't seem to work (61 bytes, 16 chars).
```
üò≠üåòüåóüåñüåïüåîüåìüåíüåëüò≤‚虂è¨üò∑‚è©üòÄüò¨
```
Hypothenuse (27 bytes, 7 chars).
```
üòºüò£üòºüò£‚ûïüòãüò®
```
[Answer]
If you just want a truthy value (or even just a value), without using it, use `‚Ñπ`. It's 3 bytes, while the others are 4 bytes.
[Answer]
If you want to output 2 chars or less, do not use `⏪⏬⏩`, use the number of `⏬`s needed.
[Answer]
# Infinite Looping
If you want to loop a program infinitely, from index `n`, you can use `nüò¨` to jump behind the `n`th character. For example, this 34-byte, 12-char program for `yes`:
```
üîü‚è™üò≠seyüò≤‚虂訂è©üîü‚è©
```
Becomes this 32-byte, 11-char program:
```
üîüüò≠seyüò≤‚虂訂è©üòÄüò¨
```
[Answer]
# Make use of built-ins.
Some cases are:
* `⁉️❕` -> `❔`
* The numbers `0`-`10`, `100` and `i` are `üòÄüòÖüòâüòçüòíüòóüòúüò°üòÅüòÜüîüüíØ‚Ñπ`, respectively.
* Multiplication with `2`-`4` is done with `üòá‚ò∫Ô∏èüòè`, respectively.
* Division with `2`-`4` is done with `üòîüòôüòû`, respectively.
* Exponentiation with `2`-`4` is done with `üò£üòÉüòà`, respectively.
* Rooting:
+ n-Rooting with `n` being `2`-`4` is done with `üòãüòêüòï`, respectively.
+ For other `n`, use `üòÖn‚ûóüòò`. `n` is not a literal `n`, but the power of rooting.
[Answer]
Because of a bug in the interpreter, if you want to append `1` to a number (e.g. `10` -> `101`), use `üòÑ`. As it is right now, you have to use `üòÖ‚ûï` for the *true* function of `üòÑ`.
] |
[Question]
[
In this optimization challenge you will write a program that sorts a single array by only comparing elements through asking the user on stdout to input comparison results on stdin.
*The below protocol is line-based, so everytime you print to stdout or read from stdin it is assumed a newline follows. Throughout the question below it is assumed that the user (read: the scoring program) has an array it wants sorted in a 0-based indexed array called `array`. For technical reasons I suggest flushing after every print to stout.*
1. As your first step your program must read the array size `n` from stdin.
2. Then, as often as you wish, you can print `a < b` to stdout, with two integers `0 <= a, b < n`. Then the user will enter `1` in stdin if `array[a] < array[b]`, and `0` otherwise.
3. Finally, once your program is convinced it has correctly deduced the order of the array, it must print `a ...` to stdout, where `...` is a space separated list of integers indicating the order. So if your program outputs `a 3 0 1 4 2` it means your program has deduced
```
array[3] <= array[0] <= array[1] <= array[4] <= array[2]
```
Note that your program never knew the contents of `array`, and never will.
You can only ask for `<` on stdin to sort the array. You can get other comparison operations by these equivalencies:
```
a > b b < a
a <= b !(b < a)
a >= b !(a < b)
a != b (a < b) || (b < a)
a == b !(a < b) && !(b < a)
```
Finally, since your program interacts with the scoring program on stdout, print debug information to stderr.
---
Your program will be scored using the following Python program:
```
from __future__ import print_function
from subprocess import Popen, PIPE
import sys, random
def sort_test(size):
array = [random.randrange(0, size) for _ in range(size)]
pipe = Popen(sys.argv[1:], stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True)
print(str(size), file=pipe.stdin); pipe.stdin.flush()
num_comparisons = 0
while True:
args = pipe.stdout.readline().strip().split()
if args and args[0] == "a":
answer_array = [array[int(n)] for n in args[1:]]
if list(sorted(array)) != answer_array:
raise RuntimeError("incorrect sort for size {}, array was {}".format(size, array))
return num_comparisons
elif len(args) == 3 and args[1] == "<":
a, b = int(args[0]), int(args[2])
print(int(array[a] < array[b]), file=pipe.stdin); pipe.stdin.flush()
num_comparisons += 1
else:
raise RuntimeError("unknown command")
random.seed(0)
total = 0
for i in range(101):
num_comparisons = sort_test(i)
print(i, num_comparisons)
total += num_comparisons
print("total", total)
```
You score your program by typing `python score.py yourprogram`. The scoring is done by having your program sort one random array of each size 0 to 100 and counting the amount of comparisons your program asks for. **These random arrays can have duplicates**, your algorithm must be able to handle equal elements. In the event there are duplicates, there are no requirements on the order of the equal elements. So if the array is `[0, 0]` it doesn't matter if you output `a 0 1` or `a 1 0`.
**You may not optimize specifically for the particular arrays the scoring program generates.** I may change the RNG seed at any point in time. **Answers using built-in sorting algorithms are permitted to be posted for interest's sake, but are non-competing.**
Program with lowest score wins.
[Answer]
# Python, score 23069
This uses the Ford–Johnson merge insertion sorting algorithm.
```
from __future__ import print_function
import sys
def less(x, y):
print(x, '<', y)
sys.stdout.flush()
return bool(int(input()))
def insert(x, a, key=lambda z: z):
if not a:
return [x]
m = len(a)//2
if less(key(x), key(a[m])):
return insert(x, a[:m], key) + a[m:]
else:
return a[:m + 1] + insert(x, a[m + 1:], key)
def sort(a, key=lambda z: z):
if len(a) <= 1:
return a
m = len(a)//2
key1 = lambda z: key(z[-1])
b = sort([insert(x, [y], key) for x, y in zip(a[:m], a[m:2*m])], key=key1)
if len(a) % 2:
b += [[a[-1], None]]
for k in range(m, len(a)):
l, i, (x, y) = max((-i.bit_length(), i, t) for i, t in enumerate(b) if len(t) == 2)
b[:i + 1] = insert([x], b[:i], key=key1) + [[y]]
if len(a) % 2:
b.pop()
return [x for x, in b]
print('a', ' '.join(map(str, sort(range(int(input()))))))
```
[Answer]
# Python 3, 28462 score
Quick sort. Pivot is leftmost item.
The score is expected, because:

```
from __future__ import print_function
import sys
size = int(input())
def less(a, b):
print(a, "<", b); sys.stdout.flush()
return bool(int(input()))
def quicksort(array):
if len(array) < 2:
return array
pivot = array[0]
left = []
right = []
for i in range(1,len(array)):
if less(array[i],pivot):
left.append(array[i])
else:
right.append(array[i])
return quicksort(left)+[pivot]+quicksort(right)
array = list(range(size))
array = quicksort(array)
print("a", " ".join(str(i) for i in array)); sys.stdout.flush()
```
Scores for each size tested:
```
size score
0 0
1 0
2 1
3 3
4 6
5 8
6 11
7 12
8 15
9 17
10 23
11 33
12 29
13 32
14 37
15 45
16 58
17 47
18 52
19 79
20 72
21 60
22 85
23 138
24 87
25 98
26 112
27 107
28 128
29 142
30 137
31 136
32 158
33 143
34 145
35 155
36 169
37 209
38 163
39 171
40 177
41 188
42 167
43 260
44 208
45 210
46 230
47 276
48 278
49 223
50 267
51 247
52 263
53 293
54 300
55 259
56 319
57 308
58 333
59 341
60 306
61 295
62 319
63 346
64 375
65 344
66 346
67 370
68 421
69 507
70 363
71 484
72 491
73 417
74 509
75 495
76 439
77 506
78 484
79 458
80 575
81 505
82 476
83 500
84 535
85 501
86 575
87 547
88 522
89 536
90 543
91 551
92 528
93 647
94 530
95 655
96 580
97 709
98 671
99 594
100 637
total 28462
```
[Answer]
# Python 2 (non-competing), 23471 score
```
from __future__ import print_function
import sys
size = int(input())
def cmp(a, b):
print(a, "<", b); sys.stdout.flush()
return [1,-1][bool(int(input()))]
array = list(range(size))
array = sorted(array,cmp=cmp)
print("a", " ".join(str(i) for i in array)); sys.stdout.flush()
```
Scores for each size tested:
```
size score
0 0
1 0
2 1
3 4
4 5
5 7
6 9
7 14
8 17
9 20
10 21
11 26
12 30
13 35
14 37
15 41
16 45
17 51
18 52
19 57
20 63
21 63
22 72
23 79
24 79
25 80
26 91
27 93
28 96
29 105
30 110
31 116
32 124
33 123
34 131
35 130
36 142
37 144
38 156
39 154
40 163
41 168
42 177
43 178
44 183
45 183
46 192
47 194
48 212
49 207
50 216
51 221
52 227
53 239
54 238
55 243
56 255
57 257
58 260
59 270
60 281
61 284
62 292
63 293
64 303
65 308
66 312
67 321
68 328
69 328
70 342
71 348
72 352
73 358
74 367
75 371
76 381
77 375
78 387
79 400
80 398
81 413
82 415
83 427
84 420
85 435
86 438
87 448
88 454
89 462
90 462
91 479
92 482
93 495
94 494
95 502
96 506
97 520
98 521
99 524
100 539
total 23471
```
[Answer]
# Python, 333300 score
```
from __future__ import print_function
import sys
size = int(input())
def less(a, b):
print(a, "<", b); sys.stdout.flush()
return bool(int(input()))
array = list(range(size))
for _ in range(size):
for i in range(0, size-1):
if less(array[i+1], array[i]):
array[i], array[i+1] = array[i+1], array[i]
print("a", " ".join(str(i) for i in array)); sys.stdout.flush()
```
This is an example program, implementing the simplest form of bubblesort, always doing `n*(n-1)` comparisons per array.
I scored this program by saving it as `sort.py` and typing `python score.py python sort.py`.
] |
[Question]
[
**This question already has answers here**:
[Highly composite numbers](/questions/74487/highly-composite-numbers)
(11 answers)
Closed 7 years ago.
Consider the following table for the function `d(n)`, which calculates the number of factors that `n` is divisible by without a remainder:
```
n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ...
d(n) | 1 | 2 | 2 | 3 | 2 | 4 | 2 | 4 | 3 | 4 | 2 | 6 | ...
```
Going from left to right, it is possible to determine the "champion" of the current subsequence:
* The first champion in the sequence `[1]` is `n = 1` with `d(1) = 1`.
* The second champion in the next sequence, `[1, 2]` is `n = 2` with `d(2) = 2`.
* The sequence `[1, 2, 3]` has no new champions, because `d(3) = d(2) = 2`, and `2` earned the title first.
* The third champion appears the sequence `[1, 2, 3, 4]`: `d(4) = 3`, which is greater than the previous champion with `d(2) = 2`.
* The next champion is `6` in `[1, 2, 3, 4, 5, 6]` with `d(6) = 4`.
* The next champion is `12` with `d(12) = 6`.
The champions can be denoted in the table:
```
n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ...
d(n) | 1 | 2 | 2 | 3 | 2 | 4 | 2 | 4 | 3 | 4 | 2 | 6 | ...
x x x x x
```
You task is the following: Write a program that given an integer `n`, print all champions in the range `[1, n]` (`n` inclusive). The output format does not matter (test cases below display array format). Standard code golf rules and scoring applies.
## Test cases
```
1 -> [1]
2 -> [1, 2]
3 -> [1, 2]
4 -> [1, 2, 4]
5 -> [1, 2, 4]
6 -> [1, 2, 4, 6]
7 -> [1, 2, 4, 6]
8 -> [1, 2, 4, 6]
9 -> [1, 2, 4, 6]
10 -> [1, 2, 4, 6]
11 -> [1, 2, 4, 6]
12 -> [1, 2, 4, 6, 12]
24 -> [1, 2, 4, 6, 12, 24]
36 -> [1, 2, 4, 6, 12, 24, 36]
```
Hint: The output should always be a prefix of the [List of Highly Composite Numbers](https://en.wikipedia.org/wiki/Highly_composite_number).
[Answer]
# Jelly, 10 bytes
```
0rÆDL€»\IT
```
[Try it online!](http://jelly.tryitonline.net/#code=MHLDhkRM4oKswrtcSVQ&input=&args=MzY)
[Answer]
## 05AB1E, ~~16~~ 15 bytes
```
0U>GNÑg©X›i®UN,
```
**Explanation**
```
0U # initialize the record as 0
>G # for each number in 1 to N
NÑg© # get number of divisors
X›i # if number of divisors is a new record
®U # save new record
N, # print the new record holder on a new line
```
[Try it online](http://05ab1e.tryitonline.net/#code=MFU-R07DkWfCqVjigLppwq5VTiw&input=MzY)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes
```
0i:t!\~sY>hdf
```
[**Try it online!**](http://matl.tryitonline.net/#code=MGk6dCFcfnNZPmhkZg&input=MzY)
### Explanation
```
0 % Push 0
i: % Take input n. Push [1 2 ... n]
t!\ % 2D array of all combinations of modulo between elements of [1 2 ... n]
~s % Sum of zeros of each column. Gives number of divisors for [1 2 ... n]
Y> % Cumulative maximum
h % Concatenate with 0
d % Consecutive differences
f % Indices of nonzero elements. Implicitly display
```
] |
[Question]
[
# The Challenge
Implement **amb** and its sister statement **require** in whatever language you wish. See <http://community.schemewiki.org/?amb> for an example implementation in Scheme. You can rename them to **a** and **r**.
**amb** statements select a value passed to it arbitrarily, and **require** statements written *after* **amb** contain conditionals that limit the possibilities that **amb** will return, as the conditionals must evaluate to true. statements The pseudocode
```
fun rand() {
return amb(1, 2, 3, 4)
}
```
will return whatever the computer feels like as long as it is 1, 2, 3 or 4. However the pseudocode
```
fun arbitary2 {
x = amb(1, 2, 3, 4)
y = square(x)
require(even(y))
return x
}
```
can only ever *eventually* return 2 or 4, but a user may not know which one will return. Depending on implementation, 2 may always be returned, or 4, or 2 is returned 3% of the time and so on. **require** can be called *any* time after **amb** is called as long as both statements are in the same program, even outside of the scope of **amb**, so
```
fun foo() {
amb(1,2,3,4)
}
x = foo()
y = foo()
require(x > y)
```
is valid and x will never be less than y when the program successfully terminates. The degree to which this is possible varies language by language, so try your best to implement this. The following code should not successfully terminate:
```
amb(1, 2, 3, read("notes.txt"))
require(false)
print("this will never be printed")
```
The actual names and exact syntax of **amb** and **require** don't matter. For example, if your implementation is in assembly, then having **amb** read from predefined registers is legitimate as long as the essence of **amb** is preserved, and **require** can checked whether a certain register contains a certain value.
Try your best and have fun!
# Scoring
This has been changed from popcon to code-golf, so make your implementations short! Least number of characters wins. Don't cheat and rename existing implementations. Any submission which does something to the effect of:
```
#define r rename
#define a amb
```
will be disqualified.
[Answer]
## Scala, 406/377 Bytes
I offer two golfed versions of my implementation, one that chooses the value randomly and one that (somehow) abuses the task description and always returns the first legal value. It's up to you, with one to consider (the latter one is shorter, obviously):
```
trait A[X]{def g=scala.util.Random.shuffle(l).head;def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}
trait A[X]{def g=l(0);def l:Seq[X];def -(d:X)};class M{def a[X](e:Seq[X])=new A[X]{var s=e;def l=s;def -(d:X)=s=s.filter(_!=d)};def r(v:A[Boolean])=v-false;def p[X,Y](a:A[X],b:A[Y])=new A[(X,Y)]{var x=List[Any]();def l=(for(e<-a.l;f<-b.l)yield(e,f)).diff(x);def -(d:(X,Y))=x::=d};def o[X,Y](v:A[X],f:X=>Y)=new A[Y]{def l=v.l.map(f);def -(d:Y)=v.l.filter(f(_)==d).foreach(v.-)}}
```
This versions are more or less just golfed versions of my initial submission (some implementations have changed slightly, but the interfaces were quite stable). Therefore I will not explain it any further but refer to my initial post. Just have in mind that everything that was "for convenience" now disappeared. And a lot of renaming happened. The only difference is that pairs are now a bit like new amb-values: If you define conditions on top of pairs this will never effect the underlying values (nevertheless, manipulating the underlying values will still affect the pairs).
To give you a hint on how to use this versions, here is a short testing code I used while golfing:
```
val m = new M
val a1 = m.a(List(1, 2, 3, 4, 5))
val a2 = m.a(List(4, 5, 6))
val a12 = m.p(a1, a2)
m.r(m.o(a12, (p:(Int, Int)) => p._1 > p._2))
m.r(m.o(a1, (e: Int) => e%2==1))
println(a1.l)
println(a2.l)
println(a12.l)
println(a12.g)
```
As you can see, the offered functions are now instance-methods, hence, you need an instance of M to interact with my library (this saved me one glorious byte).
Note that my ungolfed version (which I will not update any more) now includes natural syntax for the most common Int- and Boolean-operations.
---
*(my initial submission)*
Right before posting this answer the Mathematica answer was stated and it looks as if my solution is based on similar assumptions. Nevertheless, I will offer my solution, too, because I didn't copied the former answer as it wasn't there when I started.
I didn't tried to recreate a natural syntax (like: `(amb(1, 2, 3) + 3) * 5`, etc), but this would be possible if you like to implement the necessary implicit conversions. I chose the functional way as you will see later.
Let's start with the two keywords:
```
import ambiguous.AmbOps.op
object Amb {
def amb[A](args: A*): AmbType[A] =
new BasicAmb[A](args.toList)
def require(amb: AmbType[Boolean]): Unit =
amb.del(false)
def require[A](amb: AmbType[A], predicate: A => Boolean): Unit =
require(op(amb, predicate))
def require[A, B](amb: AmbType[(A, B)], predicate: (A, B) => Boolean): Unit =
require(op(amb, predicate))
}
```
The amb-method is quite straight forward, you provide some values and get some container, that may return a value back (more on that later).
I offer three require methods but they are all based on the first one, so the others are just for convenience. Let me explain the first one (the others will become clear as you read on): If you have some boolean amb-Container and call require, all false values are eliminated.
But how is an amb-value of arbitrary type converted into a boolean value? By offering a conversion-policy:
```
object AmbOps {
def op[A, B](amb: AmbType[A], op: A => B): AmbType[B] =
new OpAmb[B, A](amb, op)
def op[A, B, C](amb: AmbType[(A, B)], op: (A, B) => C): AmbType[C] =
new OpAmb[C, (A, B)](amb, p => op(p._1, p._2))
def pair[A, B](ambA: AmbType[A], ambB: AmbType[B]): AmbType[(A, B)] =
new AmbPair[A, B](ambA, ambB)
}
```
Assume we have some numerical amb-value and want to square each element, then just call op with a corresponding function: `op(amb(1, 2, 4), (e: Int) => e * e) // returns a value equivalent to amb(1, 4, 16)` Following the same scheme you can convert the elements to boolean values for example with `op(amb(1, 2, 4), (e: Int) => e%2 == 0)`
If you have several amb-values and you want to define conditions between them, it isn't that easy to do with my approach when only using amb, require and op. Therefore I defined the method pair. With pair you can create tuples/pairs out of two amb-values (or any number if you again pair pairs with other values or pairs). If you then define conditions on top of this tuples, the illegal pairs will be eliminated. But the original values aren't always manipulated. Only if this process leads to the situation that one element from one of the initial amb-values is no longer legal in any tuple, than this value is completely eliminated from the initial amb-value. If now some other amb-value (or pair) is based on this manipulated amb-value, the dependent value will also miss the deleted element.
That means that if you need a pair of values fulfilling a condition, you have to get an element from the pair-value and you cannot always rely on the original values, but I think this is a acceptable limitation.
Just for convenience there is an additional op-method for tuples.
Now we have to dig deeper into the technical details of the amb-containers:
```
import scala.util.Random
trait AmbType[A] {
def get: A = {
if (list.isEmpty)
throw new IllegalStateException("no value left")
else list(Random.nextInt(list.length))}
private[ambiguous] def list: List[A]
private[ambiguous] def del(a: A): Unit
}
class BasicAmb[A](private var args: List[A]) extends AmbType[A] {
override private[ambiguous] def list: List[A] = args
override private[ambiguous] def del(a: A): Unit = { args = args.filterNot(_ == a)}
}
class OpAmb[A, B](amb: AmbType[B], op: B => A) extends AmbType[A] {
override private[ambiguous] def list: List[A] = amb.list.map(op)
override private[ambiguous] def del(a: A): Unit = amb.list.filter(op(_) == a).foreach(amb.del)
}
class AmbPair[A, B](ambA: AmbType[A], ambB: AmbType[B]) extends AmbType[(A, B)] {
private var deleted: List[(A, B)] = List()
override private[ambiguous] def list: List[(A, B)] =
ambA.list.flatMap(a => ambB.list.map(b => (a, b))).diff(deleted)
override private[ambiguous] def del(a: (A, B)): Unit = {
deleted ::= a
ambA.list.filter(a => !list.exists(_._1 == a)).foreach(a => {ambA.del(a); deleted = deleted.filterNot(_._1 == a)})
ambB.list.filter(b => !list.exists(_._2 == b)).foreach(b => {ambB.del(b); deleted = deleted.filterNot(_._2 == b)})
}
}
```
I don't want to say too much about the classes but one thing is worth mentioning: If you create pairs of two amb-values and define some conditions on top of them and afterwards define some further conditions on top of one of the original values, the pair-class misses to check if an element of the not-changed original value may be deleted as it doesn't appear as part of one pair any more. So some further observer-pattern would be great.
Now let's take a look on how to use this:
```
// create amb-values by invoking amb
val a = amb(1, 2, 3, 4)
// do some maths on a value
val b = op(a, (e: Int) => e + 2)
// define some conditions
require(b, (e: Int) => e%3 == 0)
// or first apply the condition to the value and afterwards pass the value to require
val filtered = op(b, (e: Int) => e%3 == 0)
require(filtered)
// pair values
val paired = pair(a, amb("hello", "welcome"))
// note that the amb-value a now only contains the elements 1 and 4 as the former requirement eliminated the other two
// state a condition on pairs
require(paired, (a: Int, b: String) => b.length % a == 0)
// now the amb-value a only contains the element 1 as there was no string with length divisible by 4
// query a value from our pairs (by calling get)
val selected = paired.get
// at this point only two pairs are left, so selected will always be either (1, "hello") or (1, "welcome")
val number = selected._1
val greetings = selected._2
```
[Answer]
# Mathematica, 143 bytes
```
a={{}};b=e@Length@Last[a=Join@@Outer[Append,a,#,1]]&;c@z_:=a=Select[a,#~f~z&];d@z_:=RandomChoice[#~f~z&/@a];f=#2/.Thread[e/@Range@Length@#->#]&
```
This code defines three functions. `b` (`amb`) and `c` (`require`) do what you expect, with `amb` taking a `List` of values and `require` taking an expression. `d` converts an `amb` expression to a human-readable value. As an upside, `amb` expressions act exactly like their values, with the final result being lazily evaluated during the `d` call. Gets slow when more than 3 `amb` expressions are entered. Could probably be golfed further.
] |
[Question]
[
Given two **arbitrarily** precise *decimal* numbers 0 ≤ *x* < *y* ≤ 1, compute the shortest (in digits) *binary* number *b* such that *x* ≤ *b* < *y*.
Output the binary digits of *b* after the [binary point](https://en.wikipedia.org/wiki/Radix_point) as an array or a string of zeroes and ones. Note that the empty array means 0.0, by virtue of deleting trailing zeroes. This also makes sure that there is a unique correct answer for any range.
If you are unfamiliar with binary fractional numbers, they work just like decimal numbers:
```
Base 10 0.625 = 0.6 + 0.02 + 0.005 = 6 x 10^-1 + 2 x 10^-2 + 5 x 10^-3
Base 2 0.101 = 0.1 + 0.00 + 0.001 = 1 x 2^-1 + 0 x 2^-2 + 1 x 2^-3
| | |
v v v
Base 10 0.625 = 0.5 + 0 + 0.125
```
Built-ins that trivialize this problem are disallowed.
Examples:
```
0.0, 1.0 -> ""
0.1, 1.0 -> "1"
0.5, 0.6 -> "1"
0.4, 0.5 -> "0111"
```
---
Shortest code wins.
[Answer]
# CJam, 46
```
q'.-_,:M;S/{3a.+M'0e]~GM#*AM(#/(2b}/_@.=0#)<2>
```
[Try it online](http://cjam.aditsu.net/#code=q'.-_%2C%3AM%3BS%2F%7B3a.%2BM'0e%5D~GM%23*AM(%23%2F(2b%7D%2F_%40.%3D0%23)%3C2%3E&input=0.98983459823945792125172638374187268447126843298479182647%200.98983459823945792125172638374187268447126843298479182648)
**Explanation:**
The general idea is: multiply both numbers by 10some big enough exponent to get integers, multiply again by 2another big enough exponent to "make room" for binary digits in integer form, integer-divide back by 10the first exponent, decrement the numbers (to get to the "x < b ≤ y" case) and convert the results to base 2. Find the first different digit (it will be 0 in the first number and 1 in the second number), and print all the digits from the second number up to and including that one.
Before starting with the multiplications, I'm adding 3 to the integer parts in order to ensure that the results have the same number of binary digits (with no leading zeros) after decrementing. At the end, I am skipping the first 2 binary digits to compensate.
```
q read the input as a string
'.- remove the dots
_, duplicate and get the string length
:M; store in M and pop; M-1 will be the first exponent
S/ split by space
{…}/ for each number (in string form)
3a.+ add 3 to the first digit (vectorized-add [3] to the string)
M'0e] pad to the right with '0's up to length M
this is like multiplying the decimal number with 10^(M-1)
but done as a string operation
~ evaluate the result as an integer
GM#* multiply by 16^M (G=16) = 2^(4*M) -- 4*M is the second exponent
AM(#/ divide by 10^(M-1) (A=10)
(2b decrement and convert to base 2 (array of digits)
_ duplicate the 2nd array
@ bring the first array to the top
.= vectorized-compare the arrays (digit by digit)
0# find the position of the first 0 (meaning digits are not equal)
)< increment and slice the other copy of the 2nd array before that position
2> discard the first 2 digits
```
[Answer]
## Ruby, ~~138~~ 132 bytes
```
->x,y{d,*a=->{a.map.with_index{|n,i|n/BigDecimal.new(2)**(i+1)}.inject(:+)||0};[a+=[1],a[-1]=d[]>=y ?0:1]while d[]<x;a}
```
13 bytes added for the `-rbigdecimal` flag. Expects input as two `BigDecimal`s.
Sample run:
```
irb(main):029:0> f=->x,y{d,*a=->{a.map.with_index{|n,i|n/BigDecimal.new(2)**(i+1)}.inject(:+)||0};[a+=[1],a[-1]=d[]>=y ?0:1]while d[]<x;a}
=> #<Proc:0x00000001053a10@(irb):29 (lambda)>
irb(main):030:0> f[BigDecimal.new('0.98983459823945792125172638374187268447126843298479182647'),BigDecimal.new('0.98983459823945792125172638374187268447126843298479182648')]
=> [1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1]
```
Explanation:
```
->x,y{
d,*a= # sets d to the following, and a to [] with fancy splat operator
->{ # lambda...
a.map.with_index{|n,i| # map over a with indices
n/BigDecimal.new(2)**(i+1) # this will return:
# - 0 [ /2**(i+1) ] if n is 0
# - 1 /2**(i+1) if n is 1
}.inject(:+) # sum
||0 # inject returns nil on empty array; replace with 0
}; # this lambda turns `[0, 1, 1]' into `BigDecimal(0b0.011)'
[ # `[...]while x' is a fancy/golfy way to say `while x;...;end'
a+=[1], # add a digit 1 to the array
a[-1]=d[]>=y ?0:1 # replace it with 0 if we exceeded upper bound
]while d[]<x; # do this while(below the lower bound)
a # return the array of digits
}
```
[Answer]
# Mathematica, 72 bytes
```
IntegerDigits[#2[[-1,-1]],2,Log2@#]&@@Reap[1//.a_/;Sow@⌈a#⌉>=a#2:>2a]&
```
---
**Explanation**
The method is to find the smallest multiplier of form `2^n` that enlarges the gap between two input numbers so that it contains an integer.
For example, `16*{0.4,0.5} = {6.4,8.}` contains `7`, so the answer is `7/16`.
**Test case**
```
%[0.4,0.5]
(* {0,1,1,1} *)
```
[Answer]
## JavaScript (ES6), 144 bytes
```
f=(x,y,b='',d=s=>s.replace(/\d/g,(n,i)=>(i&&n*2%10)+(s[i+1+!i]>4)).replace(/[.0]+$/,''),n=d(x),m=d(y))=>n?n>'1'||(m||2)<='1'?f(n,m,b+n[0]):b+1:b
```
Assumes input in the form `0.<digits>` (or `1.<zeros>` is acceptable for `y`). `d` is a function which takes the decimal part of a number and doubles it, then trims trailing zeros. The leading digit must be present but it is ignored. Conveniently `d("0.0")` is empty, and this is therefore used as a test to see whether `x` is an exact binary fraction; in this case `b` already holds the result. Otherwise, there is a somewhat convoluted test to determine whether suffixing a `1` to `b` serves to distinguish between `x` and `y`; if so that is returned. Otherwise the MSB of `x` is suffixed to the result and the function calls itself recursively to process the next bit.
If instead we desire `x < b ≤ y` the function is much simpler, something like this (untested):
```
f=(x,y,b='',d=s=>s.replace(/\d/g,(n,i)=>(i&&n*2%10)+(s[i+1+!i]>4)),n=d(x),m=d(y))=>n>='1'||m<'1'?f(n,m,b+n[0]):b+1
```
] |
[Question]
[
# Challenge
Given a natural number, output it in the ASCII form of Agrippa's number system.
# Description
I like odd alphabets and numeral systems. My favorite numeral system is one given by [Heinrich Cornelius Agrippa](http://www.esotericarchives.com/agrippa/agripp2b.htm). It gives a succinct way to write numbers in the range `[0,9999]`, where single digits are written as follows:
[](https://i.stack.imgur.com/5AC9l.gif)
Larger numbers less than `10^4` are a combination of single digits, but rotated/horizontally-mirrored on a single central bar as follows:
```
[0° mirrored, 10's ] | [0°, 1's ]
[180°, 1000's] | [180° mirrored, 100's]
```
Here are a few examples:
[](https://i.stack.imgur.com/2BUbM.gif)
The ASCII equivalents are:
```
Ones:
0 1 2 3 4 5 6 7 8 9
| |- |_ |\ |/ |~ || |^ |v |]
| | | | | | | | | |
Tens:
0 1 2 3 4 5 6 7 8 9
| -| _| /| \| ~| || ^| v| [|
| | | | | | | | | |
Hundreds:
0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
| |_ |- |/ |\ |~ || |v |^ |]
Thousands:
0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
| _| -| \| /| ~| || v| ^| [|
1510: 1511: 1471: 1486: 3421:
-| -|- ^|- v|| _|-
_|~ _|~ _|\ -|\ \|\
```
Numbers larger than `9999` are broken up into sections of 4 digits (with leading zeros added to get a multiple of four) and each is converted. For example:
```
314159: (0031 4159)
/|- ~|]
| /|_
```
# Rules
* Your answer may be a function or full program
* The input is a positive integer
* Entries must support inputs over `10^8`
* Each four digit section takes exactly six characters
* Sections of four are separated by a single space
* Trailing newline is optional
* Up to two trailing spaces per line are allowed
* I will not accept my own answer
* Score is in bytes, lowest score wins!
[Answer]
# Haskell, 310 bytes
* Defining `reverse` (as I did: `r`) is one byte shorter than importing `Data.List` and using it just *once*
* Defining `z=0:z` and `(!)=(!!).(++z)` is the shortest way yet that I've found to return `0` for out of bounds
* I've checked and quickChecked the `take4s` function, but it still feels like magic to me
# Here's the code:
```
l=lines" \n--__\n__--\n\\//\\\n/\\\\/\n~~~~\n||||\n^^vv\nvv^^\n][]["
d x|x<1=[]|1<2=mod x 10:d(div x 10)
(&)=(!!)
z=(0::Int):z
(!)=(&).(++z)
t a=[[a!q|q<-[p..p+3]]|p<-[0,4..length a-1]]
g[c,d,b,a]=[[l&b&1,'|',l&a&0,' '],[l&d&3,'|',l&c&2,' ']]
r[]=[]
r(x:y)=r y++[x]
f=unlines.foldl1(zipWith(++)).map g.r.t.d
```
# Less golfed:
```
import Data.List (reverse)
dict = lines " \n--__\n__--\n\\//\\\n/\\\\/\n~~~~\n||||\n^^vv\nvv^^\n][]["
-- Note that (digits x) returns the digits of x in little-endian order
digits x | x < 1 = []
| otherwise = mod x 10 : digits (div x 10)
-- Note: zeros needs the type signature, because otherwise it won't match [Int] (inferred from (!!))
zeros = (0::Int) : zeros
-- list ! position gives the element at the position, or 0 for out of bounds
(!) = (!!) . (++zeros)
-- This partitions the digits into groups of four, padded right
take4s a = [[a!q | q <-[p..p+3]] | p <- [0,4..length a - 1]]
convertOne[c,d,b,a] = [[dict !! b !! 1, '|', dict !! a !! 0, ' '], [dict !! d !! 3, '|', dict !! c !! 2, ' ']]
f = unlines . foldl1(zipWith (++)) . map convertOne . reverse . take4s . digits
```
# Tests (escape characters removed):
```
mapM_ print $ lines $ f 1510
-|
_|~
mapM_ print $ lines $ f 1511
-|-
_|~
mapM_ print $ lines $ f 1471
^|-
_|\
mapM_ print $ lines $ f 1486
v||
_|\
mapM_ print $ lines $ f 3421
_|-
\|\
mapM_ print $ lines $ f 1234567891011121314
_|\ ||^ -| -|_ -|/
|_ /|~ ^|] _|_ _|/
mapM_ print $ lines $ f 1024628340621757567
|_ _|v || ^|~ ||^
|_ /|| \|\ -|_ v|~
```
[Answer]
## JavaScript (ES6), ~~180~~ 159 bytes
```
s=>`000${s}`.slice(-s.length&-4).replace(/..../g,([t,h,d,u])=>(r+=' _-\\/~|v^['[t]+`|${'_-/\\~|v^]'[h]} `,' -_/\\~|^v['[d]+`|${' -_\\/~|^v]'[u]} `),r='')+`\n`+r
```
Where `\n` represents a literal newline character.
Edit: Updated for the switch from `,'` to `|`. Saved 14 bytes by using a single `replace` to do all the work. Saved 3 bytes by using `&-4` instead of `<<2>>2`. Saved 2 bytes by abusing destructuring assignment. Saved 2 bytes by abusing template strings.
] |
[Question]
[
The Champernowne Constant is the irrational number 0.1234567891011... extending ad infinum.
We've done a [question](https://codegolf.stackexchange.com/q/66878/31625) about it before. But this question is about its reciprocal, known as the Inverse Champernowne Constant. This is approximately 8.10000007.
Given a string of between one and three digits (every 3-digit string appears within the first 10,000 decimal places) inclusive, give the number of decimal places in the decimal portion of the Inverse Champernowne Constant that precede the first appearance of that string.
Builtins that perform this directly or generate approximations of either of these constants are forbidden, but builtins for arbitrary precision arithmetic are still permissible.
This is code golf, so the shortest program, in bytes, wins.
**Test cases:**
```
1 0
2 52
3 13
4 29
5 36
6 7
7 8
8 27
9 23
10 0
100 0
998 187
999 67
01 321
001 689
010 418
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 37 bytes
*Thanks to @AndrasDeak for his help with Octsympy's `vpa` function!*
```
'1/'1e4:"@V]N$h1e4H$Y$t32>)I0h)jXf1)q
```
*EDIT (June 11, 2016): due to changes in the language, replace `0` by `J` in the code. The link below includes that modification*
[**Try it online!**](https://tio.run/##y00syfn/X91QX90w1cRKySEs1k8lA8j0UIlUKTE2stP09MrQzIpIM9Qs/P/f0tICAA)
It takes a while in the online compiler (less than 1 minute).
```
'1/' % literal string
1e4: % array [1,2,...,1e4]
" % for each number in that array
@V % push number and convert to string
] % end loop
N$h % concatenate all strings
1e4H$Y$ % compute 1/123456789101112... as a string with 1e4 significant digits
t32>) % remove unwanted spaces and newlines in the output string
I0h) % remove the first two characters ('8.')
j % input string
Xf % find indices of occurrences of input string within computed string
1) % take first index
q % subtract 1
```
[Answer]
## Ruby, ~~69~~ 67 bytes
```
->x{"#{1/BigDecimal.new(?.+[*1..9999]*'')}".index(x)-3}
```
Score: 55 source code bytes + 12 for the `-rbigdecimal` flag.
Pretty straightforward. Only weird part is that the `to_s` implicitly called by the `#{}` construction on `BigDecimal` returns
```
0.81000000670 [...] 3036E1
```
so it's necessary to subtract 3 to get the correct index.
[Answer]
# Python 2, 69 bytes
```
lambda s:str(10**30000/int("".join(map(str,range(3000))))).index(s)-1
```
] |
[Question]
[
### Introduction
Everyone should know IPv6 by now. IPv6 has very long, cumbersome addresses.
In 1996 some very intelligent people created a scheme to encode them much better in [RFC 1924](https://www.rfc-editor.org/rfc/rfc1924). For reasons I cannot understand, this hasn't been widely adopted. To help adoption, it is your task to implement a converter in the language of your choice.
Because storage is very expensive, especially in source code repositories, you obviously have to use as little of it as possible.
### Challenge
Write an encoder for the address format specified in RFC1924. The input is a IPv6 address in the boring standard format.
[Stolen from Wikipedia](https://en.wikipedia.org/wiki/IPv6_address#Presentation) this is:
---
>
> An IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two octets). The groups are separated by colons (:). An example of an IPv6 address is:
>
>
>
```
2001:0db8:85a3:0000:0000:8a2e:0370:7334
```
>
> The hexadecimal digits are case-insensitive, but IETF recommendations suggest the use of lower case letters. The full representation of eight 4-digit groups may be simplified by several techniques, eliminating parts of the representation.
>
>
>
>
> **Leading zeroes**
>
>
>
>
> Leading zeroes in a group may be omitted. Thus, the example address may be written as:
>
>
>
```
2001:db8:85a3:0:0:8a2e:370:7334
```
>
> **Groups of zeroes**
>
>
>
>
> One or more consecutive groups of zero value may be replaced with a single empty group using two consecutive colons (::). Thus, the example address can be further simplified:
>
>
>
```
2001:db8:85a3::8a2e:370:7334
```
>
> The localhost (loopback) address, 0:0:0:0:0:0:0:1, and the IPv6 unspecified address, 0:0:0:0:0:0:0:0, are reduced to ::1 and ::, respectively. This two-colon replacement may only be applied once in an address, because multiple occurrences would create an ambiguous representation.
>
>
>
---
You **must** handle omitted zeroes in the representation correctly!
The output is a IPv6 address in the superior RFC1924 format.
As in the RFC this is:
---
>
> The new standard way of writing IPv6 addresses is to treat them as a
> 128 bit integer, encode that in base 85 notation, then encode that
> using 85 ASCII characters.
> The character set to encode the 85 base85 digits, is defined to be,
> in ascending order:
>
>
>
```
'0'..'9', 'A'..'Z', 'a'..'z', '!', '#', '$', '%', '&', '(',
')', '*', '+', '-', ';', '<', '=', '>', '?', '@', '^', '_',
'`', '{', '|', '}', and '~'.
```
>
> The conversion process is a simple one of division, taking the
> remainders at each step, and dividing the quotient again, then
> reading up the page, as is done for any other base conversion.
>
>
>
---
You can use the suggested conversion algorithm in the RFC or any other you can think of. It just has to result in the correct output!
### Example Input and Output
Here is the one from the RFC:
Input:
>
> 1080:0:0:0:8:800:200C:417A
> or
> 1080::8:800:200C:417A
>
>
>
Output:
>
> 4)+k&C#VzJ4br>0wv%Yp
>
>
>
Your program can take input and return the output in any standard way. So it is ok to read from stdin and output to stdout or you can implement your code as a function that takes the input as argument and returns the output.
### Winning criteria
As always [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest correct code in bytes wins!
This is my first challenge, so please do notify me about any problems/ambiguities in the description.
[Answer]
# Pyth, ~~93~~ 91 bytes
```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import*;z=int(ip_address(z))$sm@Kdjz85
```
Second submission in Pyth!
Can't try online because `$` is unsafe.
When tested against the example, produces the expected result:
```
$ pyth -c 'Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import *$$z=int(ip_address(z))$sm@Kdjz85'
1080::8:800:200C:417A
4)+k&C#VzJ4br>0wv%Yp
```
Edits:
* Saved two bytes by replacing `$$` with `;` and removing space before `*`
## Explanation
First part creates the mapping string and assigns it to `K`:
```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~
```
This is done as follows:
```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")
K implicitly assign to K
s[ ) the string joined from the following list
UT range [0..9]
jk joined with the empty string: 0123456789
rG1 capitalized version of the string G (whole alphabet)
G G itself
"!#$%&()*+-;<=>?@^_`{|}~" all other symbols (shorter to declare than generate)
```
Then, the second part is two pieces of normal python amounting to 47 bytes, to convert the input ipv6 address to a number (because `z` is accessed later in the code, it is first implicitly assigned to any input value before running the Python code)
```
*from ipaddress import *$$z=int(ip_address(z))$
```
Then, the last part converts the resulting number to base 85 as a list and maps every value to the mapping string `K`:
```
sm@Kdjz85
jz85 convert z to base 85
m map over the converted number with lambda d:
@Kd K[d]
s join as a string and implicitly print
```
# Pure Pyth, 100 bytes
```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")IgJx=zcz\:kZ=z-z]k=z.n++<zJ]*-8lz]\0>zJ)=zimid16z65536sm@Kdjz85
```
You can try it [here](https://pyth.herokuapp.com/?code=Ks[jkUTrG1G%22!%23%24%25%26%28%29*%2B-%3B%3C%3D%3E%3F%40%5E_%60%7B|%7D~%22%29IgJx%3Dzcz%5C%3AkZ%3Dz-z]k%3Dz.n%2B%2B%3CzJ]*-8lz]%5C0%3EzJ%29%3Dzimid16z65536sm%40Kdjz85&input=1080%3A%3A8%3A800%3A200C%3A417A&debug=0)
In order to support leading/middle/trailing `::`, I must insert a list of missing zeroes in the correct position in the ip once converted to a list of hex numbers, which takes up more space than the inline Python version. There's room for improvement but I doubt it can beat the other version!
# 63 bytes version
Doesn't support the `::` notation to skip zeroes:
```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")=zimid16cz\:65536sm@Kdjz85
```
You can try it [here](https://pyth.herokuapp.com/?code=Ks[jkUTrG1G%22!%23%24%25%26%28%29*%2B-%3B%3C%3D%3E%3F%40%5E_%60%7B|%7D~%22%29%3Dzimid16cz%5C%3A65536sm%40Kdjz85&input=1080%3A0%3A0%3A0%3A8%3A800%3A200C%3A417A&debug=0)
The different part here is converting the ipv6 to a number using base conversions:
```
=zimid16cz\:65536
z read string from input and assign it to z
c \: split it at columns
m map over the split list with lambda d:
id16 convert d from base 16 to 10
i 65536 convert list of ints from base 65536 to 10
=z assign result back to z
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 108 bytes
```
YaR"::""*:"YyR"*"":0"X7-(":"Ny)Yy^":"Fiy{W#i<4iPU0bPBi}((J,t).AZ.z."!#$%&()*+-;<=>?@^_`{|}~")@((Jb)FB16TD85)
```
Remains fairly competitive without an IP address class/library
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZYVJcIjo6XCJcIio6XCJZeVJcIipcIlwiOjBcIlg3LShcIjpcIk55KVl5XlwiOlwiRml5e1cjaTw0aVBVMGJQQml9KChKLHQpLkFaLnouXCIhIyQlJigpKistOzw9Pj9AXl9ge3x9flwiKUAoKEpiKUZCMTZURDg1KSIsIiIsIiIsIlwiMTA4MDo6ODo4MDA6MjAwQzo0MTdBXCIiXQ==)
[Answer]
# GCC C (functions) on x86, 240 bytes
This uses a couple of GCC specials:
* [128 bit integers](https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html)
* [Byte-swapping builtin](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html)
```
#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){long long y[3];inet_pton(10,a,&y[1]);b(2);b(1);g(*(U *)y);}
```
### Explanation
* `f()` is the entry point. It takes a single `char *`
* `inet_ntop()` converts full or compressed string representation of input address to the elements 1 and 2 of a 64-bit integer array
* Output from `inet_ntop()` is in network order (big endian), but the integer is needed in host order (little endian on x86) in order to perform arithmetic required for base conversion. Unfortunately gcc does not provide a `__builtin_bswap128()`. Instead the element 2 of the 64-bit integer array is `bswap64()`ed to the element 0 and the element 1 is `bswap64()`ed to itself. Elements 0 and 1 of the array now contain the address correctly in a host order 128-bit integer.
* Standard successive div/mod by 85 is used to present the integer in base 85. Because the first div/mod yields the last base 85 digit (and so on), the function `g()` performs this conversion recursively. The digits are effectively pushed to the stack and then output in the correct order.
* Conversion of digit value to ASCII character is a little messy. This is probably golfable.
### Test driver
Mildly ungolfed for readability.
Compile with `make ipv6enc` or `gcc ipv6enc.c -o ipv6enc`:
```
#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){
if(x){
g(x/85);
x%=85;
putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;
}
}
f(char *a){
long long y[3];
inet_pton(10,a,&y[1]);
b(2);
b(1);
g(*(U *)y);
}
int main (int argc, char **argv) {
f("1080::8:800:200C:417A");
return 0;
}
```
---
### To do - Big endian version, 165 bytes
Find a big-endian platform where I can use the gcc 128-bit integers, so I can get rid of all the byte swapping stuff. The code should look like this, but right now this is untested on a big-endian platform:
```
#define U unsigned __int128
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){U y;inet_pton(10,a,&y);g(y);}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-ripaddr`, 109 bytes
```
->s{IPAddr.new(s).to_i.digits(85).reverse.map{([*0..9,*?A..?Z,*?a..?z]*""+"!#$%&()*+-;<=>?@^_`{|}~")[_1]}*""}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpck20km5RZkFiSkqRUuwiN9ulpSVpuhY3c3Xtiqs9AxyBwnp5qeUaxZp6JfnxmXopmemZJcUaFqaaekWpZalFxal6uYkF1RrRWgZ6epY6WvaOenr2UUA6EUhXxWopKWkrKSqrqKppaGpp61rb2NrZO8TFJ1TX1NYpaUbHG8bWApXUQi1VKSgtKVZwi1YyNLAwsIJACysLAwMrIwMDZysTQ3NHpViI2gULIDQA)
] |
[Question]
[
# Introduction
Hex is a strategy board game played on a hexagonal grid, theoretically of any size and several possible shapes, but traditionally as an 11×11 rhombus. Other popular dimensions are 13×13 and 19×19 as a result of the game's relationship to the older game of Go. According to the book A Beautiful Mind, John Nash (one of the game's inventors) advocated 14×14 as the optimal size.

# Game Rules
Each player has an allocated color, conventionally Red and Blue or White and Black. Players take turns placing a stone of their color on a single cell within the overall playing board. The goal for each player is to form a connected path of their own stones linking the opposing sides of the board marked by their colors, before their opponent connects his or her sides in a similar fashion. The first player to complete his or her connection wins the game. The four corner hexagons each belong to both adjacent sides.
# Coding Rules
1. You may use any program or language. Do not use any third party libraries or modules (full or in part) that implements the same game. The rest are fine.
2. Players are computer and user.
3. You may choose the size of the grid.
4. You may use either CLI or GUI for output (see points).
5. Your code should not exceed 5120 bytes.
# Points
* **+(5120 - bytes) / 100** golfing points
* **+50** points for making GUI
* **+50** for two player mode
* **+75** for best-move-prediction**#**
* **+50** for undo-move
**#** Tell the user, if they wish, their next best move.
# Super bot challenge
* **+150** points if your bot is undefeatable. Add this points ONLY IF you are absolutely certain of your bot's 100% winning capability. If any user defeats your bot and reports it all your points will be taken away (zero points). The person reporting this must either post a screenshot or input sequences based on the implementation of game. **They will be awarded +150 points, if they have posted an answer.**
[Answer]
# HTML5 and JavaScript, 12.72 + 50 + 50 + 50 = 162.72 points
Hi, this is my very first code golf, but I think, the following code works quite well (it's a full HTML page, 3848 bytes).
```
<html><head><meta charset="utf-8"><title>Hex</title><script type="text/javascript">var r=20;var w=r*2*(Math.sqrt(3)/2);var ctx;var s=[-1,-1];var b=new Array(14);var h=[];var p=0;var m=false;var t=true;function H(c,x,y,r){c.beginPath();c.moveTo(x,y-r);for(var i=0;i<6;i++)c.lineTo(x+r*Math.cos(Math.PI*(1.5+1/3*i)),y+r*Math.sin(Math.PI*(1.5+1/3*i)));c.closePath();c.fill();c.stroke();}function P(c,p){c.lineWidth=10;c.beginPath();c.moveTo((p[0][0]+p[0][1])*w-(p[0][1]-4)*(w/2),(p[0][1]+2)*1.5*r);for(var i=1;i<p.length;i++)c.lineTo((p[i][0]+p[i][1])*w-(p[i][1]-4)*(w/2),(p[i][1]+2)*1.5*r);c.stroke();}function S(e){var l=ctx.getImageData(e.clientX-20,e.clientY,1,1).data;l[0]-=l[2]==38||l[2]==178 ? 241 : 0;l[1]-=l[2]==178 ? 220 : (l[2]==38 ? 0 : 140);if(l[0]>=0&&l[0]<=13&&l[1]>=0&&l[1]<=13&&(l[2]==38||l[2]==171||l[2]==178))s=[l[0],l[1]];else s=[-1,-1];}function Ai(){var pos;do pos=[Math.floor(Math.random()*14),Math.floor(Math.random()*14)];while(b[pos[0]][pos[1]]!=-1);h.push([pos[0],pos[1],1]);b[pos[0]][pos[1]]=1;}function Fa(a,d){for(var i=0;i<a.length;i++)if(JSON.stringify(a[i])==JSON.stringify(d))return i;return -1;}function C(x,y,c,o,s){var a=[-1,0,1,0,0,-1,0,1,1,-1,-1,1];var r=[];for(var i=0;i<6;i++)if(x+a[i*2]>=0&&x+a[i*2]<14&&y+a[i*2+1]>=0&&y+a[i*2+1]<14)if(b[x+a[i*2]][y+a[i*2+1]]==c&&Fa(o,[x+a[i*2],y+a[i*2+1]])==-1&&Fa(s,[x+a[i*2],y+a[i*2+1]])==-1)r.push([x+a[i*2],y+a[i*2+1]]);return r;}function W(c){var o=[],op=[],s=[],sp=[];for(var a=0;a<14;a++){if(b[c==0?a:0][c==0?0:a]==c){o.length=op.length=s.length=sp.length=0;var pf=false;o.push([c==0?a:0,c==0?0:a]);op.push(-1);while(o.length>0){var u=o[0];o.splice(0,1);var uI=op.splice(0,1);s.push(u);sp.push(uI);if(u[c==0?1:0]==13){pf=true;break;}var n=C(u[0],u[1],c,o,s);for(var i=0;i<n.length;i++){o.push(n[i]);op.push(s.length-1);}}if(pf){var p=[];var u=s.length-1;while(sp[u]!=-1){p.push(s[u]);u=sp[u];}p.push([c==0?a:0,c==0?0:a]);p.reverse();t=false;return p;}}}return false;}function Md(e){S(e);if(t){if(s[0]!=-1&&s[1]!=-1){h.push([s[0],s[1],p]);b[s[0]][s[1]]=p;if(m)p=p==0 ? 1 : 0;else Ai();D();var p0=W(0),p1=W(1);if(p0!=false){P(ctx,p0);alert((m?"The red player":"You")+" won!");}else if(p1!=false){P(ctx,p1);alert((m?"The blue player":"The computer")+" won!");}}}}function Mm(e){S(e);if(t)D();}function D(){ctx.clearRect(0,0,850,600);ctx.lineWidth=1;ctx.fillStyle="rgb(0,154,172)";ctx.beginPath();ctx.moveTo(w*15.65,r);ctx.lineTo(w*23.5,24.5*r);ctx.lineTo(0,r);ctx.lineTo(w*7.85,24.5*r);ctx.closePath();ctx.fill();ctx.fillStyle="rgb(255,0,39)";ctx.beginPath();ctx.moveTo(0,r);ctx.lineTo(w*15.65,r);ctx.lineTo(w*7.85,24.5*r);ctx.lineTo(w*23.5,24.5*r);ctx.closePath();ctx.fill();var num=0;ctx.strokeStyle="white";for(var y=0;y<14;y++){for(var x=0;x<14;x++){if(b[x][y]==0)ctx.fillStyle="rgb(255,0,39)";else if(b[x][y]==1)ctx.fillStyle="rgb(0,154,172)";else if(x==s[0]&&y==s[1])ctx.fillStyle="rgb("+(x+(p==0?241:0))+","+(y+(p==0?0:140))+","+(p==0?38:171)+")";else ctx.fillStyle="rgb("+(x+241)+","+(y+220)+",178)";H(ctx,(x+y)*w-(y-4)*(w/2),(y+2)*1.5*r,r);num++;}}}function Mp(){m=!m;p=0;I();}function U(){if(t){var a;if(h.length>0){a=h[h.length-1];b[a[0]][a[1]]=-1;h.pop();}if(!m){a=h[h.length-1];b[a[0]][a[1]]=-1;h.pop();}p=a[2];D();}}function I(){for(var i=0;i<14;i++){b[i]=new Array(14);for(var j=0;j<14;j++)b[i][j]=-1;}history.length=0;t=true;D();}function L(){var a=document.getElementById("o");ctx=a.getContext("2d");document.getElementById("mp").checked=false;a.onmousedown=Md;a.onmousemove=Mm;I();}</script></head><body onload="L()"><canvas style="position:absolute;top:0px;left:20px" width="850" height="600" id="o"></canvas><div style="position:absolute;top:250px;left:20px"><input type="button" onClick="I()" value="New game"><br><br>Multiplayer: <input id="mp" type="checkbox" onClick="Mp()"><br><input type="button" onClick="U()" value="Undo"></div></body></html>
```
**Expanded**
```
<html>
<head>
<meta charset="utf-8">
<title>Hex</title>
<script type="text/javascript">
var r = 20;
var w = r*2*(Math.sqrt(3)/2);
var ctx;
var sel = [-1, -1];
var board = new Array(14);
var hist = [];
var player = 0;
var multiplayer = false;
var active = true;
function drawHexagon(c, x, y, r)
{
c.beginPath();
c.moveTo(x, y-r);
for(var i=0; i<6; i++)
c.lineTo(x+r*Math.cos(Math.PI*(1.5+1/3*i)), y+r*Math.sin(Math.PI*(1.5+1/3*i)));
c.closePath();
c.fill();
c.stroke();
}
function drawPath(c, p)
{
c.lineWidth = 10;
c.beginPath();
c.moveTo((p[0][0]+p[0][1])*w - (p[0][1]-4)*(w/2), (p[0][1]+2)*1.5*r);
for(var i=1; i<p.length; i++)
c.lineTo((p[i][0]+p[i][1])*w - (p[i][1]-4)*(w/2), (p[i][1]+2)*1.5*r);
c.stroke();
}
function getSel(e)
{
var color = ctx.getImageData(e.clientX-20, e.clientY, 1, 1).data;
color[0] -= color[2]==38||color[2]==178 ? 241 : 0;
color[1] -= color[2]==178 ? 220 : (color[2]==38 ? 0 : 140);
if(color[0] >= 0 && color[0] <= 13 && color[1] >= 0 && color[1] <= 13 && (color[2] == 38 || color[2] == 171 || color[2] == 178))
sel = [color[0], color[1]];
else
sel = [-1, -1];
}
function aiMove()
{
var pos;
do
pos = [Math.floor(Math.random()*14), Math.floor(Math.random()*14)];
while(board[pos[0]][pos[1]] != -1);
hist.push([pos[0],pos[1],1]);
board[pos[0]][pos[1]] = 1;
}
function findArr(a, b)
{
for(var i=0; i<a.length; i++)
if(JSON.stringify(a[i]) == JSON.stringify(b))
return i;
return -1;
}
function getConnections(x, y, c, open, closed)
{
var a = [-1, 0, 1, 0, 0, -1, 0, 1, 1, -1, -1, 1];
var ret = [];
for(var i=0; i<6; i++)
if(x+a[i*2] >= 0 && x+a[i*2] < 14 && y+a[i*2+1] >= 0 && y+a[i*2+1] < 14)
if(board[x+a[i*2]][y+a[i*2+1]] == c && findArr(open, [x+a[i*2],y+a[i*2+1]]) == -1 && findArr(closed, [x+a[i*2],y+a[i*2+1]]) == -1)
ret.push([x+a[i*2],y+a[i*2+1]]);
return ret;
}
function checkWin(c)
{
var open = [], openPrev = [], closed = [], closedPrev = [];
for(var a=0; a<14; a++)
{
if(board[c==0?a:0][c==0?0:a] == c)
{
open.length = openPrev.length = closed.length = closedPrev.length = 0;
var pathFound = false;
open.push([c==0?a:0, c==0?0:a]);
openPrev.push(-1);
while(open.length > 0)
{
var u = open[0];
open.splice(0, 1);
var uI = openPrev.splice(0, 1);
closed.push(u);
closedPrev.push(uI);
if(u[c==0?1:0] == 13)
{
pathFound = true;
break;
}
var connections = getConnections(u[0], u[1], c, open, closed);
for(var i=0; i<connections.length; i++)
{
open.push(connections[i]);
openPrev.push(closed.length-1);
}
}
if(pathFound)
{
var path = [];
var u = closed.length-1;
while(closedPrev[u] != -1)
{
path.push(closed[u]);
u = closedPrev[u];
}
path.push([c==0?a:0, c==0?0:a]);
path.reverse();
active = false;
return path;
}
}
}
return false;
}
function mouseDown(e)
{
getSel(e);
if(active)
{
if(sel[0] != -1 && sel[1] != -1)
{
hist.push([sel[0],sel[1],player]);
board[sel[0]][sel[1]] = player;
if(multiplayer)
player = player==0 ? 1 : 0;
else
aiMove();
draw();
var p0 = checkWin(0), p1 = checkWin(1);
if(p0 != false)
{ drawPath(ctx, p0); alert((multiplayer?"The red player":"You") + " won!"); }
else if(p1 != false)
{ drawPath(ctx, p1); alert((multiplayer?"The blue player":"The computer") + " won!"); }
}
}
}
function mouseMove(e)
{
getSel(e);
if(active)
draw();
}
function draw()
{
ctx.clearRect(0, 0, 850, 600);
ctx.lineWidth = 1;
ctx.fillStyle = "rgb(0,154,172)";
ctx.beginPath();
ctx.moveTo(w*15.65, r);
ctx.lineTo(w*23.5, 24.5*r);
ctx.lineTo(0, r);
ctx.lineTo(w*7.85, 24.5*r);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "rgb(255,0,39)";
ctx.beginPath();
ctx.moveTo(0, r);
ctx.lineTo(w*15.65, r);
ctx.lineTo(w*7.85, 24.5*r);
ctx.lineTo(w*23.5, 24.5*r);
ctx.closePath();
ctx.fill();
var num = 0;
ctx.strokeStyle = "white";
for(var y=0; y<14; y++)
{
for(var x=0; x<14; x++)
{
if(board[x][y] == 0)
ctx.fillStyle = "rgb(255,0,39)";
else if(board[x][y] == 1)
ctx.fillStyle = "rgb(0,154,172)";
else if(x == sel[0] && y == sel[1])
ctx.fillStyle = "rgb(" + (x+(player==0?241:0)) + "," + (y+(player==0?0:140)) + "," + (player==0?38:171) + ")";
else
ctx.fillStyle = "rgb(" + (x+241) + "," + (y+220) + ",178)";
drawHexagon(ctx, (x+y)*w - (y-4)*(w/2), (y+2)*1.5*r, r);
num++;
}
}
}
function chgMP()
{
multiplayer = !multiplayer;
player = 0;
init();
}
function undo()
{
if(active)
{
var a;
if(hist.length > 0)
{
a = hist[hist.length-1];
board[a[0]][a[1]] = -1;
hist.pop();
}
if(!multiplayer)
{
a = hist[hist.length-1];
board[a[0]][a[1]] = -1;
hist.pop();
}
player = a[2];
draw();
}
}
function init()
{
for(var i=0; i<14; i++)
{
board[i] = new Array(14);
for(var j=0; j<14; j++)
board[i][j] = -1;
}
hist.length = 0;
active = true;
draw();
}
function load()
{
var canvas = document.getElementById("output");
ctx = canvas.getContext("2d");
document.getElementById("mp").checked = false;
canvas.onmousedown = mouseDown;
canvas.onmousemove = mouseMove;
init();
}
</script>
</head>
<body onload="load()">
<canvas style="position:absolute; top:0px; left:20px" width="850" height="600" id="output">Canvas not supported...</canvas>
<div style="position:absolute; top:250px; left:20px"><input type="button" onClick="init()" value="New game"><br><br>Multiplayer: <input id="mp" type="checkbox" onClick="chgMP()"><br><input type="button" onClick="undo()" value="Undo"></div>
</body>
</html>
```
**Explanation**
The code uses the HTML5's `canvas`-tag to display the game (14x14 board). You can undo the last step and play against another player (enable Multiplayer) or the computer, but its AI is still very weak (it just uses a random position to place the next field). The entire graphical design is based on your screenshot.
[Answer]
# Mathematica, 419.16 points
```
m = False;
Manipulate[
ClickPane[
Dynamic@Graphics[
GraphicsComplex[
Join @@ Array[{{2, 1}, {0, Sqrt[3]}}.{##} &, {9, 5}], {Red,
Polygon[{5, 25, 21, 41}], Blue, Polygon[{5, 21, 25, 41}],
EdgeForm[Gray], If[m, Red, Gray],
Polygon[{22, 27, 28, 24, 19, 18}]}],
PlotLabel ->
Column[{If[m, "Red Wins", "Red to Move"],
Row@{"Best move is: ",
Which[m, "(There are no legal moves remaining)", p == 1,
"(Computer's turn)", ! m, "1,1"]}}, Alignment -> Center]],
If[p == 2, m = True] &], {{p, 1, "# of players"}, {1, 2}},
Row@{Button["Start", If[p == 1, m = True]],
Button["Undo", If[p == 2, m = False]], Button["Reset", m = False]}]
```

Except for the use of `GraphicsComplex`, this code is entirely ungolfed.
## Controls
* The `# of players` selector chooses the number of players. Note that there is a bug that allows you to change between 1-player (human vs. cpu) and 2-player (human vs. human) while a game is in progress.
* `Start` lets the computer start playing in 1-player mode.
* `Undo` takes back the last player's move in 2-player mode.
* `Reset` sets the board back to the starting position.
* Clicking on a hex when it is a human's turn plays in that hex. Note that there is a bug that allows a click outside the playing field to select hex 1,1.
Red always goes first, and in 1-player mode Red is always controlled by the computer. The computer always plays perfectly.
## Points
* 704 bytes: **44.16** points (This can be golfed down significantly.)
* GUI: **50** points (It's worth it to add a gui if you can do it in under 5k (50 \* 100) characters... yeah, Mathematica can do that.)
* Two-player mode: **50** points (The second player never gets to go, but that's just too bad.)
* Best-move display: **75** points (There is only one possible move, so this is trivial. Note that it is always displayed: the requirement is "if they wish" not "*iff* they wish.")
* Undo: **50** points (Since there is only one possible move, there is only one possible action to undo: also trivial.)
* Super bot challenge: **150** points (Since I have programmed the computer to always play first, there is no sequence of inputs that can cause it to lose.)
] |
[Question]
[
One of the key parts of PNG's compression algorithm is the *Paeth transformation,* which transforms the image in a way that makes it compress better (usually). In this challenge, your task is to write a program to compute a Paeth transformation. The operation of a Paeth transformation is described below.
## The Paeth Transformation
The Paeth transformation subtracts from each member `X` of a 2-dimensional array a predictor. The predictor is that element of the array member to the left (`A`), top (`B`), and top-left (`C`) of `X` whose value has the least difference to `A + B - C`.
```
┼─┼─┼
│C│B│
┼─┼─┼
│A│X│
┼─┼─┼
```
If one of `A`, `B`, or `C`, would be out of bounds, its value is replaced by 0. Here is pseudocode from the [PNG specification](http://www.w3.org/TR/PNG-Filters.html) outlining how this predictor is computed:
```
function PaethPredictor (a, b, c)
begin
; a = left, b = above, c = upper left
p := a + b - c ; initial estimate
pa := abs(p - a) ; distances to a, b, c
pb := abs(p - b)
pc := abs(p - c)
; return nearest of a,b,c,
; breaking ties in order a,b,c.
if pa <= pb AND pa <= pc then return a
else if pb <= pc then return b
else return c
end
```
For this challenge, the array members are natural numbers in the range from 0 to 255. If the Paeth transformation results in a value outside of that range, it shall be reduced modulo 256 to a value in that range.
## Input and Output
The input is two integers *x* and *y* in the range from 2 to 1023 denoting width and height of the matrix to transform and an array of *x* × *y* elements. The input is formatted as decimal numbers separated by one blank character terminated with a linefeed. Here is what this input could look like:
```
2 3 4 5 6 7 8 9
```
This would represent a 2 by 3 matrix with the entries:
```
4 5
6 7
8 9
```
The output shall have the same format as the input with the relaxiation that the numbers may be separated by an arbitrary non-zero amount of whitespace characters (space, horizontal or vertical tab, line or form feed) and be terminated by an arbitrary amount of whitespace characters.
Input shall be received from `stdin`, output shall go to `stdout`. If this is not possible, choose a different way of receiving input and writing output that is not hard-coding the input.
The behaviour of your program when presented with invalid input is not part of this challenge.
## Judging and Reference Implementation
An ANSI C program [is provided](https://gist.github.com/fuzxxl/68bfc33ca05a1e381644/e16f1c3f3eb193cd876dfa1c9eef6ebb11d76d58) to generate sample input, solve instances and verify solutions. Call the program with `g` to **g**enerate input, with `s` to **s**olve an input instance and with `v` to **v**erify the correctness of a solution.
If you think the reference implementation is faulty, please let me know so I can correct it as soon as possible.
## Example input and output
By popular request.
```
10 5 166 156 108 96 63 227 122 99 117 135 125 46 169 247 116 55 151 1 232 114 214 254 6 127 217 88 206 102 252 237 75 250 202 145 86 198 172 84 68 114 58 228 66 224 186 217 210 108 11 179
```
representing the array
```
166 156 108 96 63 227 122 99 117 135
125 46 169 247 116 55 151 1 232 114
214 254 6 127 217 88 206 102 252 237
75 250 202 145 86 198 172 84 68 114
58 228 66 224 186 217 210 108 11 179
```
is transformed into
```
166 246 208 244 223 164 151 233 18 18
215 177 123 78 125 84 96 135 231 138
89 129 8 121 101 228 55 101 20 123
117 175 196 199 125 112 222 238 72 46
239 234 120 158 41 19 12 24 183 111
```
which is encoded as
```
10 5 166 246 208 244 223 164 151 233 18 18 215 177 123 78 125 84 96 135 231 138 89 129 8 121 101 228 55 101 20 123 117 175 196 199 125 112 222 238 72 46 239 234 120 158 41 19 12 24 183 111
```
## Winning Condition
For this challenge, write a *program* that generates correct Paeth transformation of the input and writes them out. This is *code-golf,* the program with the least amount of characters in its source code wins. Please try to attach an explanation and a readable version of your code to your submission so others can see what it does.
[Answer]
# J - 77 char
Taking an approach that looks different from FUZxxl's answer but is actually very similar.
```
1!:2&4":2({.,|.@{.,@(256|$-0(0{[/:+`-/|@-])"1@|:(-#:1 2 3)|.!.0$)}.)0".1!:1]3
```
Some comments on the interesting bits.
* `1!:2&4":` (...) `0".1!:1]3` - If J wasn't terrible about I/O and parsing, this could be refactored as to use `&.".&.stdin''`, to save 3 chars. But it is so we can't. Rest in peace, precious characters.
* `2 ({.,|.@{.,@( ... stuff using $ ... )}.)` - This disassembles the input and reassembles the output. We use `$` both as a reference to the input in `stuff using $`, and as an operation we need to perform on the input before running the `stuff` on it.
* `0( blah )"1@|:` - Yes, that's a dyadic Transpose: we regroup the three rotation results as the innermost array axis, so that the Paeth logic can apply on each set separately with `"1`.
* `0{[/:+`-/|@-]` - The Paeth logic: sort `a,b,c` by the magnitudes of (`p` minus each of `a,b,c`), and take the first.
[Answer]
## J, ~~97~~ ~~91~~ ~~88~~ 87 characters
Let's get this started. Notice the absent `exit`; J prints a prompt (three blanks) after all the output has been written, but then gets an EOF on `stdin`, causing it to terminate.
I believe that quite a couple of improvements are possible in this code.
```
1!:2&4":(|.@$,,)256|((-+`-/+[:(>&|{,)"0/]-"2+`-/)(3 2$-*i.3)|.!.0])2(|.@{.$}.)0".1!:1]3
```
Here is the code before golfing it; it's mostly equal to the current code.
```
NB. A, B, and C values
abc =: (0 _1 , _1 0 ,: _1 _1)&(|.!.0)
p =: +`-/@abc
NB. minimum of magnitudes
mmin =: (>&| { ,)"0
pred =: p + [: mmin/ abc -"2 2 p
paeth =: 256 | ] - pred
input =: [: (2&}. $~ 2 |.@{. ]) 0 ". 1!:1
output =: [: 1!:2&4 LF ,~ [: ": |.@$ , ,
output paeth input 3
exit 0
```
] |
[Question]
[
The Hilbert curves are a class of space-filling fractal curves where every bend in the path is at a right angle and the curve as a whole fills up a square, with the property that sequences of consecutive segments are always displayed as contiguous blocks.
Traditionally, the curve is drawn as a series of very squiggly lines inside a square such that each segment becomes smaller and smaller until they fill up the whole square. However, like the [Walsh matrix](https://codegolf.stackexchange.com/questions/20906/print-a-specific-value-in-the-infinite-walsh-matrix), it is also possible to represent the limit curve as a sequence of line segments connecting lattice points that grows infinitely until it fills up an entire quadrant of lattice points on the Cartesian plane.
Suppose we define such a curve as the *integral Hilbert curve*, as follows:
* Start at the origin.
* Move one unit right (`R`), one unit up (`U`), and one unit left (`L`). Down will be notated as `D`.
* Let `RUL` be `H_1`. Then define `H_2` as `H_1 U I_1 R I_1 D J_1` where:
+ `I_1` is `H_1` rotated 90 degrees counterclockwise and flipped horizontally.
+ `J_1` is `H_1` rotated 180 degrees.Perform the steps of `H_2` after `H_1` to complete `H_2`.
* Define `H_3` as `H_2 R I_2 U I_2 L J_2`, where:
+ `I_2` is `H_2` rotated 90 degrees clockwise and flipped vertically.
+ `J_2` is `H_2` rotated 180 degrees.Perform the steps of `H_3` after `H_2` to complete `H_3`.
* Define `H_4` and other `H_n` for even `n` the same way as `H_2`, but relative to `H_{n-1}`.
* Define `H_5` and other `H_n` for odd `n` the same way as `H_3`, but relative to `H_{n-1}`.
* The integral Hilbert curve is `H_infinity`.
We get a function `f(n) = (a, b)` in this way, where `(a, b)` is the position of a point moving `n` units along the integral Hilbert curve starting from the origin. You may notice that if we draw this curve `2^{2n}-1` units long we get the `n`th iteration of the unit-square Hilbert curve magnified `2^n` times.
Your task is to implement `f(n)`. The shortest code to do so in any language wins.
---
Example inputs and outputs:
```
> 0
(0, 0)
> 1
(1, 0)
> 9
(2, 3)
> 17
(4, 1)
> 27
(6, 3)
> 41
(7, 6)
> 228
(9, 3)
> 325
(24, 3)
```
Note that your solution's *algorithm* must work in general; if you choose to implement your algorithm in a language where integers are of bounded size, that bound must not be a factor in your program's code.
[Answer]
## GolfScript (62 bytes)
```
{1:a:b(.@4base{:?3%!:|b^?2<3?=.b^:b^^|!.a^:a^{\}*{@2*@+}2*}/\}
```
This is an anonymous function which takes `n` on the stack and leaves `x y` on the stack. [Online demo](http://golfscript.apphb.com/?c=IyMKOycwCjEKOQoxNwoyNwo0MQoyMjgKMzI1J24ve34KIyMKCnsxOmE6YiguQDRiYXNlezo%2FMyUhOnxiXj8yPDM%2FPS5iXjpiXl58IS5hXjphXntcfSp7QDIqQCt9Mip9L1x9CgojIwp%2BXXB9LwojIw%3D%3D)
It's essentially the iterative code from the [Wikipedia article](http://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms) reversed so that it processes the base-4 representation of `n` from most-significant to least-significant digit instead of least-significant to most-significant. This simplifies the bookkeeping required to output `x` and `y` in the right order.
Pseudocode translation (not tested, may contain errors):
```
a = b = true;
x = y = 0;
foreach (digit in n base 4) {
p = (digit % 3 == 0) ^ b;
q = (digit < 2) ^ b;
b ^= (digit == 3);
if (a) swap(p, q);
a ^= (digit % 3 != 0);
y = 2*y + (p ? 1 : 0);
x = 2*x + (q ? 1 : 0);
swap(x, y);
}
swap(x, y)
```
[Answer]
## R: ~~178~~ 169
Room for improvement in this, but it's a start
```
f=function(d){x=y=0;s=1;while(s<Inf){a=bitwAnd(1,d/2);b=bitwAnd(1,bitwXor(d,a));if(b==0){if(a==1){x=s-1-x;y=s-1-y};t=x;x=y;y=t};x=x+(s*a);y=y+(s*b);d=d/4;s=s*2};c(x,y)}
```
Test Run
```
> f(0)
[1] 0 0
> f(1)
[1] 1 0
> f(9)
[1] 2 3
> f(41)
[1] 7 6
> f(325)
[1] 24 3
```
] |
[Question]
[
This challenge is based on some new findings related to the [Collatz conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture) and designed somewhat in the spirit of a collaborative [polymath project](http://michaelnielsen.org/polymath1/index.php?title=Main_Page). Solving the full conjecture is regarded as extremely difficult or maybe impossible by math/number theory experts, but this simpler task is quite doable and there is many examples of sample code. In a best case scenario, new theoretical insights might be obtained into the problem based on contestants entries/ ingenuity/ creativity.
The new finding is as follows: Imagine a contiguous series of integers [ *n1 ... n2* ] say *m* total. Assign these integers to a list structure. Now a generalized version of the Collatz conjecture can proceed as follows. Iterate one of the *m* (or fewer) integers in the list next based on some selection criteria/algorithm. Remove that integer from the list if it reaches 1. Clearly the Collatz conjecture is equivalent to determining whether this process always succeeds for all choices of *n1, n2*.
Here is the twist, an additional constraint. At each step, add the *m* current iterates in the list together. Then consider the function *f(i)* where *i* is the iteration number and *f(i)* is the sum of current iterates in the list. Look for *f(i)* with a particular "nice" property.
The whole/ overall concept is better/ more thoroughly documented [here](http://vzn1.wordpress.com/2014/04/18/collatz-gamechanger-finally/) (with many examples in ruby). The finding is that fairly simple strategies/ heuristics/ algorithms leading to "roughly monotonically decreasing" *f(i)* exist and many examples are given on that page. Here is one example of the graphical output (plotted via gnuplot):

So here is the challenge: Use varations on the existing examples or entirely new ideas to build a selection algorithm resulting in a *f(i) "as close to monotonically decreasing as possible".* Entrants should include a graph of *f(i)* in their submission. Voters can vote based on that graph & the algorithmic ideas in the code.
The contest will be based on *n1 = 200 / n2 = 400* parameters only! (the same on the sample page.) But hopefully the contestants will explore other regions and also attempt to generalize their algorithms.
Note, one tactic that might be very useful here are gradient descent type algorithms, or genetic algorithms.
Can discuss this all further in chat for interested participants.
For some ref, another codegolf Collatz challenge: [Collatz Conjecture](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture) (by [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob))
[Answer]
I wrote some code in Python 2 to run algorithms for this challenge:
```
import matplotlib.pyplot as plt
def iterate(n):
return n*3+1 if n%2 else n/2
def g(a):
##CODE GOES HERE
return [True]*len(a)
n1=input()
n2=input()
a=range(n1,n2+1)
x=[]
y=[]
i=0
while any(j>1 for j in a):
y.append(sum(a))
x.append(i)
i+=1
b=g(a)
for j in range(len(a)):
if b[j]:
a[j]=iterate(a[j])
plt.plot(x,y)
plt.show()
```
`g(x)` takes the list of values and returns a list of bools for whether each one should be changed.
That includes the first thing I tried, as the line right after the comment, which was iterating all of the values in the list. I got this:

It doesn't look close to monotonic, so I tried iterating only values that would decrease the sum, if there are any, iterating the ones that would increase it least otherwise:
```
l=len(a)
n=[iterate(i) for i in a]
less=[n[i]<a[i] for i in range(l)]
if any(less):
return less
m=[n[i]-a[i] for i in range(l)]
return [m[i]==min(m) for i in range(l)]
```
Unfortunately, that doesn't terminate (at least for `n1=200`, `n2=400`). I tried keeping track of values I'd seen before by initializing `c=set()`:
```
l=len(a)
n=[iterate(i) for i in a]
less=[n[i]<a[i] for i in range(l)]
if any(less):
return less
m={i:n[i]-a[i] for i in range(l)}
r=[i for i in m if m[i]==min(m.values())]
while all([a[i] in c for i in r]) and m != {}:
m={i:m[i] for i in m if a[i] not in c}
r+=[i for i in m.keys() if m[i]==min(m.values())]
for i in r:
c.add(a[i])
return [i in r for i in range(l)]
```
That doesn't terminate either, though.
I haven't tried anything else yet, but if I have new ideas, I'll post them here.
[Answer]
## Python 3
My main idea was to add each numbers Collatz sequence to the `f(i)` function individually in a way that it minimizes the total increasing of `f(i)`. The resulting function isn't strictly decreasing but it has a nice structure (in my opinion :)). The second graph was created with longer interval for `f(i)` and slightly different punishment function. [Code on Gist.](https://gist.github.com/randomra/76c054e5b29f53174a6f)


When using the (3\*n+1)/2 rule instead the 3\*n+1 one the algorithm produces a completely monotonic `f(i)`! I'm sure this modification could make vzn's graphs a lot smoother too. The second graph was created with longer interval for `f(i)`. [Code on Gist.](https://gist.github.com/randomra/d4f24f37a7066029e308)


Both results are similar for bigger `[n,2*n]` ranges.
] |
[Question]
[
Create the shortest function to print a [magic square](http://en.wikipedia.org/wiki/Magic_square) of given size.
A magic square is a NxN matrix of distinct numbers and the sum of each row, column and diagonal is equal to a constant.
A magic square of size 4 is:
```
07 12 01 14
02 13 08 11
16 03 10 05
09 06 15 04
```
And the constant is 34.
The function should be able to handle inputs up to N = 30 and doesn't need to show leading zeroes.
Using Matlab's `magic` function or similar built-in function is not allowed.
More useful information: <http://mathworld.wolfram.com/MagicSquare.html>
The output doesn't need to be pretty printed and may contain `[](){},` or List/Array delimiters of your language. Although, it should use one line for each row
E.g.
```
1, 2,
3, 4,
((9,8),
(6,7))
[10 2]
[3 456]
```
PS: The corner case, when N = 2 is undefined behavior as there's no magic square of that size.
Also, the function should complete in less than **1 minute** to avoid brute force.
[Answer]
### Ruby, 344 characters
```
q=->n{r=0...n;n%2>0?(m=r.map{[]*n};x=n/2;y=i=0;r.map{r.map{m[y%=n][x%=n]=i+=1;x+=1;y-=1};x-=1;y+=2};m):n<5?[[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]]:(d=q[n/2];r.map{|y|r.map{|x|4*d[b=y/2][a=x/2]-[0,3,2,1,3,0,2,1,3,0,1,2][(n/2%2<1?b<n/4?0:8:a==n/4&&b==n/4?4:a==n/4&&b==n/4+1?0:b<=n/4?0:b==n/4+1?4:8)+y%2*2+x%2]}})}
Q=->n{q[n].map{|s|p s}}
```
You can use it e.g. like
```
Q[3]
```
and the output will be
```
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
```
The solution is not yet fully golfed. Also huge squares are generated reasonably fast. It uses a recursive function `q` to generate the squares unless `n` is odd in which case the square is generated directly or `n==4` which is hard-coded.
[Answer]
# Q, 50
Works for odd numbers
```
{(+)a rotate'(+)(a:((!)x)-1)rotate'x cut 1+(!)x*x}
```
usage
```
q){(+)a rotate'(+)(a:((!)x)-1)rotate'x cut 1+(!)x*x} 5
24 1 8 15 17
5 7 14 16 23
6 13 20 22 4
12 19 21 3 10
18 25 2 9 11
```
[Answer]
**Magic Square Generator in Python, 127 106 characters**
**106 char code**
`#Works for odd numbers only`
```
n=5
print [[(i+j-1+n/2)%n*n+(i+2*j-2)%n+1for j in range(n)]for i in range(n)]
```
**127 char code**
`#Works for odd numbers only`
```
n=3
j,A=n/2,[[0]*n for i in[0]*n]
i=c=0
while c<n*n:c=A[i][j]=c+1;i,j=[i+1,[n,i][i>0]-1][c%n>0],[j,[n,j][j>0]-1][c%n>0]
print A
```
See: <http://ajs-handling-problems-in-pythonblog.blogspot.in/2013/10/shortest-magic-square-generator-code-in.html>
] |
Subsets and Splits