text
stringlengths 180
608k
|
---|
[Question]
[
This is a follow up of [Print a maze](https://codegolf.stackexchange.com/q/245/32) question. If you like this question, please add more maze generation algorithms ;).
For this task you'll have to implement a game engine for one player who must find the treasure in a maze and get out of the dungeon.
The engine starts by reading the maze from standard input followed by a line containing a `.` (dot) a file given as argument in the command line. Next the player `@` is placed in a random location on the map. Then engine starts interacting with the player through standard io:
Commands from **engine to player**:
* `continue`: Game not finished. The surroundings are printed followed by a `.`. Player is represented by `@` character. Unobservable cells are represented by `?`.
* `finished`: Game finished. The number of steps is printed and the game stops.
Commands from **player to engine**:
* `north`: Moves player up.
* `south`: Moves player down.
* `west`: Move player left.
* `east`: Move player right.
Any invalid command (such as hitting a wall) from player is ignored, but still counted. You are free to define the surroundings to your liking.
* *Points* for the shortest code.
* *Points* for complex surroundings (e.g. print large regions and replace cells that are not visible by `?`).
* *No points* for code that doesn't respect the io format
**Example**:
In this example the surroundings is defined as the 3x3 cell with the player in the middle.
```
$ cat maze
+-+-+
|#|
| |
+---+
$ python engine.py maze
|#
@
---
.
east
|#|
@|
--+
.
north
+-+
|@|
|
.
south
|#|
@|
--+
.
west
|#
@
---
.
west
|
|@
+--
.
north
+-+
@|
|
.
west
finished
7
```
[Answer]
# C99, 771 characters
```
#include <ncurses.h>
#include <string.h>
#define MIN(A,B) (A<B?A:B)
#define MAX(A,B) (A>B?A:B)
#define T(C,X,Y) case C:if((m[x+X][y+Y]==' ')||(m[x+X][y+Y]=='#'))x+=X,y+=Y;s++;break;
char m[24][81],M[24][81];int i,j,I=0,J,x,y,s=0;
int main(int c,char**v){FILE*f=fopen(v[1],"r");
for(I=0;fgets(m[I],80,f);I++)J=MAX(J,strlen(m[I]));
J--;f=fopen("/dev/random","r");do{x=fgetc(f)%I;y=fgetc(f)%J;}
while(m[x][y]!=' ');initscr();curs_set(0);do{
switch(c){T('e',0,1)T('n',-1,0)T('s',1,0)T('w',0,-1)}
for(i=MAX(0,x-1);i<MIN(x+2,I);i++)for(j=MAX(0,y-1);j<MIN(y+2,J);j++)M[i][j]=1;
for(i=0;i<I;i++)for(j=0;j<J;j++)mvaddch(i,j,M[i][j]?m[i][j]:'?');
mvaddch(x,y,'@');refresh();}while((m[x][y]!='#')&&(c=getch())!='q');
if(m[x][y]=='#')mvprintw(I,0,"Finished in %d steps!",s),getch();endwin();}
```
Requires and makes use of ncurses. Only one macroization for length, and the N and M macros are to replace the missing minimum and maximum opperators, and I don't think there is much more to do on that.
It assumes the input maze does not exceed 80 characters wide, and that the a maze filename *has* been passed on the command-line, and that the number of parameters is low enough that the initial value of c isn't a movement command.
* Deviates from the standard in that it takes single character direction commands as the lowercase first letter of the ones suggested.
* Does show unknown regions as '?'s.
**More readable with comments:**
```
#include <ncurses.h>
#include <string.h>
#define MIN(A,B) (A<B?A:B)/*unsafe,but short*/
#define MAX(A,B) (A>B?A:B)/*unsafe,but short*/
// #define MAX(A,B) ((_A=A)>(_B=B)?_A:_B) /* safe but verbose */
#define T(C,X,Y) case C:if((m[x+X][y+Y]==' ')||(m[x+X][y+Y]=='#'))x+=X,y+=Y;s++;break;
char m[24][81],M[24][81];/* [m]ap and [M]ask; NB:mask intialized by default */
int i,j, /* loop indicies over the map */
I=0,J, /* limits of the map */
x,y, /* player position */
s=0; /* steps taken */
int main(int c,char**v){
FILE*f=fopen(v[1],"r"); /* fragile, assumes that the argument is present */
/* Read the input file */
for(I=0;fgets(m[I],80,f);I++)J=MAX(J,strlen(m[I])); /* Read in the map */
J--;
/* note that I leak a file handle here */
f=fopen("/dev/random","r");
/* Find a open starting square */
do{
x=fgetc(f)%I; /* Poor numeric properties, but good enough for code golf */
y=fgetc(f)%J;
} while(m[x][y]!=' ');
/* setup curses */
initscr(); /* start curses */
// raw(); /* WARNING! intercepts C-c, C-s, C-z, etc...
// * but shorter than cbreak()
// */
curs_set(0); /* make the cursor invisible */
/* main loop */
do {
switch(c){
T('e',0,1)
T('n',-1,0)
T('s',1,0)
T('w',0,-1)
}
/* Update the mask */
for(i=MAX(0,x-1);i<MIN(x+2,I);i++)
for(j=MAX(0,y-1);j<MIN(y+2,J);j++)
M[i][j]=1;
/* draw the maze as masked */
for(i=0;i<I;i++)
for(j=0;j<J;j++)
mvaddch(i,j,M[i][j]?m[i][j]:'?');
/* draw the player figure */
mvaddch(x,y,'@');
refresh(); /* Refresh the display */
} while((m[x][y]!='#')&&(c=getch())!='q');
if(m[x][y]=='#')mvprintw(I,0,"Finished in %d steps!",s),getch();
endwin();
}
```
] |
[Question]
[
A few days ago I made a [puzzle](https://puzzling.stackexchange.com/questions/116014/moving-around-a-plane) about moving people on an airplane. Now I am interested in the general version of this puzzle and the shortest code golf for it.
I will briefly summarise the puzzle here. A small airplane went through some heavy turbulence and all its `N` passengers ended up sitting in reverse order, ie., passenger `1` ended up in seat `N`, while passenger `N` ended up in seat `1` and so on. Now they need to get back to their assigned seats. The image below shows the map of the plane for `N=4`. The circles are the passengers and the numbers indicate their assigned seat number.
[](https://i.stack.imgur.com/v6p5H.png)
Passengers can move into a neighbouring location provided that it is empty (not another passenger). They can move into, along and out of the corridor, but they cannot jump over seats. Each turn one passenger makes a single move. What is the fewest number of turns needed to get each passenger into their assigned seat?
The optimal solution for `N=4` was found by @RobPratt:
>
> 26 moves:
>
> ```
> ....
> 4321
>
> ..2.
> 43.1
>
> 4.2.
> .3.1
>
> .42.
> .3.1
>
> .4.2
> .3.1
>
> ..42
> .3.1
>
> ...2
> .341
>
> ..2.
> .341
>
> .2..
> .341
>
> 2...
> .341
>
> 2..1
> .34.
>
> 2.1.
> .34.
>
> 21..
> .34.
>
> 214.
> .3..
>
> 21.4
> .3..
>
> 2.14
> .3..
>
> 2314
> ....
>
> 231.
> ...4
>
> 23.1
> ...4
>
> 2.31
> ...4
>
> .231
> ...4
>
> .2.1
> ..34
>
> ...1
> .234
>
> ..1.
> .234
>
> .1..
> .234
>
> 1...
> .234
>
> ....
> 1234
> ```
>
>
>
>
@RobPratt and @2012rcampion obtained optimal results for `N <= 9`:
```
N 1 2 3 4 5 6 7 8 9
L 0 NA 22 26 30 42 48 62 70
```
In this code golf challenge you will receive a single number `N` as input and your task is to **compute** the corresponding optimal number of steps `L`. You cannot simply output the table. Also this is a coding golf, so shortest code in bytes wins. However I am also interested to know the largest `N` that can be solved (even if the code is long).
[Answer]
# Python3, 436 bytes:
```
R=range
C=lambda x:eval(str(x))
def f(n):
q,s=[O:=([0]*n,[*R(n,0,-1)],0)],[O[:-1]]
while q:
g,p,c=q.pop(0)
if sorted(p)==p and all(p):return c
Y=[]
for i in R(n):
for I in[i-1,i+1]:
if(G:=g[i])and n>I>=0 and g[I]==0:N=C(g);N[I]=G;N[i]=0;Y+=[(N,p)]
if p[i]==0:N=C(g);P=C(p);N[i]=0;P[i]=g[i];Y+=[(N,P)]
if p[i]and g[i]==0:N=C(g);P=C(p);N[i]=p[i];P[i]=0;Y+=[(N,P)]
for i in Y:
if i not in s:s+=[i];q+=[(*i,c+1)]
```
[Try it online!](https://tio.run/##dZE/b8IwEMXn5lPcaIOpHFWVKqNjYUAsgNiQ5SElf7CUOo6TtvTTp2dSqBgYrNM9vd872@d/@lPjXt58GIY9hsxVRbLEOvt4zzM4q@Irq1nXB3bmPMmLEkrmuEqgFR3qrUKmpZk4oSd75oQUs5QbIenorVaz1JgEvk@2LqAlBirhxRHbZ994JjkJtoSuCX2RM88RPWQuh6yuqVOh6D@DgyO5DqgpB8omgAXrYD9eYVTWpGg7S4WdpuaiUipbKay0NTwGusV6gfKSXem1QZRqg0tW8fkmtisq1qCcH6ao2UZ4HofFq/mo/7t3VDy/unexxBlXbnfHjdMe8tEyRsh7/vbIg/pLs@CaPiqd6shJXBuBiRXHKf32cCMuu2OpeKXPefLBup5ZQfuynA@/)
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~91~~ 79 bytes [SBCS](https://github.com/abrudz/SBCS)
Returns -1 for `N=2`, representing not possible to solve.
```
{i←⍵<3:1-⍵⋄i⊣{i+←1⋄∪,⍵∘.{0∊⌷∘⍺¨⍵:⌽@⍵⊢⍺⋄⍺}(↓⍤⍉,2,⍥⊂/⊣⌿)⍳⍴⊃⍵}⍣{⍺∊⍨⌽¨q}q←⊂⍉0,⍪⌽⍳⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=HY4xCsJAEEWvoxg10S5YeJ0tUy/bRAnruAOCjXWisKTVIAREyFH@SfxrNTNv5n3GGjQX6LDblsWSFeejgXTWLMgLTvB9lri/rWwOLwhv9tBxisQlwmef1tISpXMd3QzNFXqHnrIN3QekXjMT4TuHPqEvyIGOg3Y2WQzVyKApVq5K70hNN6fak/6Vwf0A&f=e9TbqfGoa5HOo96lj3pXpR1aofmod7OCCQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Does a BFS over all possible sequences of turns, storing states of the grid as a 2×4 matrix with empty spaces represented as 0's. Some comments (slightly outdated):
```
{
i←⍵<3:1-⍵ ⍝ handle ⍵∊1 2, set i to 0 for all other cases
q←⊂0 1∘.×⌽⍳⍵ ⍝ start with a list containing only the initial grid
{ ... } ⍣ {⍺∊⍨⌽¨q} ⍝ iterate left function until *initial grid* with rows reversed appears in reached grids
{
i+←1 ⍝ increment i
∪⊃,/{ ... }¨⍵ ⍝ for each grid, call inner function, then flatten result and remove duplicates
{
s←(↓⍤⍉,2,⍥⊂/⊣⌿)⍳⍴⍵ ⍝ all possible swaps inside the grid
s/⍨0∊¨⌷∘⍵¨¨s ⍝ keep only the swaps where one of the value in the current grid is a 0
⍵∘{⌽@⍵⊢⍺}¨ ⍝ apply all of these swaps
}
}
i ⊣ ⍝ return the value of i
}
```
Technically the `∪` to remove duplicate states after each iteration is not necessary, but without it even `N=3` takes forever.
] |
[Question]
[
This expression actually has an omitted pair of parentheses.
```
1 + 2 * 3
```
To make things clear, it should be,
```
1 + (2 * 3)
```
Even this has its parentheses missing.
```
1 + 2 + 3
```
It actually means,
```
(1 + 2) + 3
```
People often assume left-to-right evaluation to such an arithmetic expression, but I want to make everything very clear.
**Given an arithmetic expression, add parentheses until the order of evaluation is clear without any assumption, and don't remove any pre-existing parentheses.**
Here are some examples of possible inputs and their expected output.
```
IN
OUT
IN 1
OUT 1
IN (((1)))
OUT (((1)))
IN 1+2+3+4+5
OUT (((1+2)+3)+4)+5
IN 1/2/3/4/5
OUT (((1/2)/3)/4)/5
IN 1/2/((3/4))/5
OUT ((1/2)/((3/4)))/5
IN 1+2-3*4/5+6-7*8/9
OUT (((1+2)-((3*4)/5))+6)-((7*8)/9)
IN 1+(2-3*4/5+6-7)*8/9
OUT 1+(((((2-((3*4)/5))+6)-7)*8)/9)
```
The expression will be composed of single-digit numbers, operators `(+, -, *, /)`, and parentheses. The typical rules of evaluation apply; left-to-right, parentheses first, multiplication first.
The input may have whitespaces, which has no effect, but your program should be able to handle them. The output must have no whitespace and have the same format as given in the examples. The input should be read either as a command line argument or from `stdin`, and the code should be runnable with no additional code.
This is a `code-golf` challenge.
Here's a rather formal definition of an arithmetic expression.
```
primary-expression
[0-9]
(arithmetic-expression)
multiplicative-expression
primary-expression
multiplicative-expression (* | /) primary-expression
additive-expression
multiplicative-expression
additive-expression (+ | -) multiplicative-expression
arithmetic-expression
additive-expression
```
This is a python script that you can use to validate your output (in a very manual way..).
I had fun writing Lisp in Python.
```
def addop(op):
return op == '+' or op == '-'
def match(l):
if l[1:] == []:
return [1, l]
elif addop(l[1]):
if l[3:] == [] or addop(l[3]):
return [3, l[0:3]]
else:
m = match(l[2:])
return [m[0] + 2, l[0:2] + [m[1]]]
else:
if l[3:] == [] or addop(l[3]):
return [3, l[0:3]]
else:
m = match([l[0:3]] + l[3:])
return [m[0] + 2, m[1]]
def tree__(l):
m = match(l)
if l[m[0]:] == []:
return m[1]
else:
return tree__([m[1]] + l[m[0]:])
def tree_(l):
if l == []:
return []
elif isinstance(l[0], list):
return [tree_(tree__(l[0]))] + tree_(l[1:])
else:
return [l[0]] + tree_(l[1:])
def tree(l):
return tree_(tree__(l))
def afterParen(s, n):
if s == '':
return '';
if s[0] == '(':
return afterParen(s[1:], n + 1)
if s[0] == ')':
if n == 0:
return s[1:]
else:
return afterParen(s[1:], n - 1)
else:
return afterParen(s[1:], n)
def toList(s):
if s == '' or s[0] == ')':
return []
elif s[0] == '(':
return [toList(s[1:])] + toList(afterParen(s[1:], 0))
elif s[0].isspace():
return toList(s[1:])
elif s[0].isdigit():
return [int(s[0])] + toList(s[1:])
else:
return [s[0]] + toList(s[1:])
def toString(l):
if l == []:
return ''
elif isinstance(l[0], list):
return '(' + toString(l[0]) + ')' + toString(l[1:])
elif isinstance(l[0], int):
return str(l[0]) + toString(l[1:])
else:
return l[0] + toString(l[1:])
def addParen(s):
return toString(tree(toList(s)))
exp = "1+2*3+4+2+2-3*4/2*4/2"
print(exp)
print(addParen(exp))
exp = "((1+2*(3+4)+(((((2))+(2-3*4/2)*4)))/2))"
print(exp)
print(addParen(exp))
```
[Answer]
# [Pip 1.0](https://github.com/dloscutoff/pip), ~~20~~ 19 bytes
```
a&TM(ST V"{}"Ja)DCs
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhJlRNKFNUIFZcInt9XCJKYSlEQ3MiLCIiLCIiLCIxKzIrMys0KzUiXQ==)
[Verify all test cases](https://dso.surge.sh/#@WyJwaXAiLCJfIC4gXCIgLT4gXCIgLiB7IiwiYSZUTShTVCBWXCJ7fVwiSmEpRENzIiwifSBNIGciLCIiLCItbCBcIlwiIDEgKCgoMSkpKSAxKzIrMys0KzUgMS8yLzMvNC81IDEvMi8oKDMvNCkpLzUgMSsyLTMqNC81KzYtNyo4LzkgMSsoMi0zKjQvNSs2LTcpKjgvOSJd)
### Explanation
Episode 2 in the "[Hey, my language happens to do exactly that!](https://codegolf.stackexchange.com/a/230321/16766)" saga...
In Pip 1.0, the string representation of a function is derived by "unparsing" the function's parse tree. Because I was lazy, I decided to just put parentheses around every subexpression, rather than trying to eliminate the parentheses that weren't necessary. Also, because I was lazy, redundant layers of parenthesization are kept in the parse tree, so they also remain in the string representation.
Thus, all this program does is convert the input to a function, get that function's string representation, and delete a few extra characters. The empty string is a corner case that costs +2 bytes.
```
a&TM(ST V"{}"Ja)DCs
a First command-line argument
& If it is truthy (not empty or 0), then:
"{}" This string
Ja Joined on the argument (essentially, wrap the arg in {})
V Eval the resulting string as a Pip expression
The string will always be a valid function literal, so
the result is a Pip function
ST Stringify
TM( ) Trim off the curly braces
DCs Delete all spaces
If the arg is falsey, use the arg itself ("" or "0")
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 237 bytes
```
\s
+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[*/](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)
+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[-+](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)
```
[Try it online!](https://tio.run/##pY2xCsJAEET7@wshykyW47jkNApqSj8il6CghY2FWt6/nxvSSEptljePWeZ5e98fl7zE6ZzjyxjxZ7T7A4YUwZaIVwVAQ1JvwzGSqRvAnoIWgQXVdKXr59VmVm2mqpLXsyiSBhoUK/46auWP0ZyNN/rpR@GlklqCrI13latdcBMByuSYpLJ1qV42tim3bqcGX4qj@wA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\s
```
Delete white space.
```
+`
```
Repeat until no more replacements can be made.
```
1`
```
Make only one replacement at a time.
```
(?<=(^|\()?)
```
See whether this subexpression begins at the beginning of the string or after a `(`.
```
(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))
```
Match either a digit or a balanced subexpression (using a .NET balancing group).
```
[*/]
```
Match either a `*` or a `/` sign.
```
(\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))
```
Match another digit or balanced subexpression.
```
(?(1)(?!$|\)))
```
If the match started at the beginning of the string or after a `(`, it must not match at the end of the string or after a `)`, because this subexpression is already parenthesised (or is the whole expression, which does not need to be parenthesised).
```
($&)
```
Parenthesise this match.
```
+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[-+](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)
```
Do the `-` and `+` signs in the same way.
] |
[Question]
[
[Quell](https://fallentreegames.com/quell/) is a single-player grid-based puzzle game. Pearls are scattered across a 2D map and the aim is to collect them all by rolling a drop of water over them. For this challenge we will only consider basic maps containing the drop, pearls, walls, and empty spaces. (The full game includes a variety of additional objects/interactions such as spikes, movable blocks, and teleport rings.) We will also assume that the map is bounded and connected, that is, it is surrounded by walls and a continuous path exists between any two squares.
The drop, initially stationary, may be rolled up, down, left, or right. A distinctive feature of Quell is that once you start the drop rolling, it rolls as far as possible in that direction, stopping *only* when it hits a wall. Any pearls along the path are collected automatically. Your inability to stop the drop or change its direction until it hits a wall has two consequences:
* There may be empty spaces on the map that the drop can never pass through or pearls that can never be collected (the latter never happens in the real game).
* The order in which pearls are collected matters on some maps because certain moves cut the drop off from areas that were previously accessible.
For example, consider the following map, where `O` = drop, `@` = pearl, `#` = wall, `.` = empty space:
```
#######
#@.#.@#
#..#..#
#O....#
#..####
#@.#
####
```
We see that the move sequence `RULDLUD` (among others) collects all three pearls:
```
####### ####### ####### ####### ####### ####### ####### #######
#@.#.@# #@.#.@# #@.#.O# #@.#O.# #@.#..# #@.#..# #O.#..# #..#..#
#..#..# R #..#..# U #..#..# L #..#..# D #..#..# L #..#..# U #..#..# D #..#..#
#O....# => #....O# => #.....# => #.....# => #...O.# => #O....# => #.....# => #.....#
#..#### #..#### #..#### #..#### #..#### #..#### #..#### #..####
#@.# #@.# #@.# #@.# #@.# #@.# #@.# #O.#
#### #### #### #### #### #### #### ####
```
However, if the first move is `U` or `D` the drop will become trapped in the 'alley' on the left side and then unable to collect the pearl in the top-right corner.
### Task
Your goal in this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to decide whether all pearls in a given map can be collected. Your program/function may take the map in any sensible format (e.g. multiline string, list of lines, matrix), which extends to replacing `O@#.` with distinct characters/digits of your choice. To indicate whether the map is solvable or not, output/return either
* any truthy/falsy value (swapping allowed) according to your language's convention, or
* one of two distinct, fixed values of your choice.
For reference, a polynomial-time algorithm for solving this problem is presented [here](https://doi.org/10.1016/j.tcs.2015.05.044). You are not required to implement this algorithm (though of course you may).
### Test cases
#### Solvable
```
#########
##....@..#
#[[email protected]](/cdn-cgi/l/email-protection)...@#
##....@#.#
#########
(possible solution: RULDR)
######
##@...##
#@.....#
##.....#
###...#
#@O.#
#####
(possible solution: LULDRUL)
#######
#@.#.@#
#..#..#
#O....#
#..####
#@.#
####
(possible solution: RULDLUD)
###############
#..#..........#
#[[email protected]](/cdn-cgi/l/email-protection).@....#
#......@......#
#.@#########@.#
#...@.@.@.@...#
#..........#..#
###############
(possible solution: RLURDRULRDLULDR)
#############
#O........#@#
#.#.........#
#.@....@#...#
#...#@......#
#...@#......#
#........#..#
#..#........#
#..........##
##@........@#
#############
(possible solution: DRULDRULRUDLUDRLUR)
```
#### Unsolvable
```
######
#O...##
#.....#
#..@..#
#@...@#
#######
#####
#.@.#
####...####
#@...O...@#
####...####
#.@.#
#####
#######
#@.#.@#
#..#..#
#O....#
#..#..#
#@.#.@#
#######
###############
#..#..........#
#[[email protected]](/cdn-cgi/l/email-protection).@....#
#....#.@......#
#.@#########@.#
#...@.@.@.@...#
#..........#..#
###############
#############
#O........#@#
#.#.........#
#.@.#..@#...#
#...#@......#
#...@#......#
#........#..#
#..#........#
#..........##
##@........@#
#############
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~247~~ ~~237~~ ~~229~~ 217 bytes
Thanks to Dingus for removing 12 bytes of code residue.
A simple breadth first search, definitely not in polynomial time.
```
q=[`input()`]
s={0}
r=1
for b in q:
r&='4'in b;s|={b}
for v,w in(0,1),(0,-1),(1,0),(-1,0):
n=eval(b);f=b.find;y,x=divmod(f('3')-1,f(']')+2);x/=3
while~-n[y][x]:n[y][x]=2;x+=v;y+=w
n[y-w][x-v]=3;q+={`n`}-s
print r
```
[Try it online!](https://tio.run/##xVLLrpswEF1ff4UVS8Uo4N4kXQVZ4g/yARQ1EByFihhiSAJK019Px@Z9u2oXrZE8z@M5M0PRVKdcrl@HPBGY48Vi8brwYJ/K4lpRex@ikj/en0jxFTrmCsc4lfiyRVh94tYXC4zYK3/wR/xEWMdvzh0y6Luzsh24XS1WzjvcrhZb9Ca5uEUZjW3vyGN2TGXiNU7Nk/R2zhN6pNbGsiEXlNCyl2vbqz/zDXq7n9JM/HRl0IRBHW47yddeveQ3r1nyOzwdNO4d3O4t5BvvsuSPvdw/3RIVKpUVVi/oDqFEHHERqVJ8i/NIJdTcwAzDyVIpShiD8bGyyNKKWl@lZZvoPU2qE0TPUU3PUUEzIZ0WYrcJSlRXJXEQWJiwnW8x6E7U9HCKlG3GozU9QQ1i2fdrWVHzqB2asHbr8G/lQ4TSc5GrCpdNiUxY0wSDlVWSSqZElFB7hBjOw8JagG7R7BWQWXSOk2g7H4RuQtTigPXP8MKkP4gQBsdnDFQQO20MXgLeSW6vQxgATCtaGizpFJ3SKhgTf9cpLXyo6TNiqkCeAe@6R/SbXRzNICNdA@mPsZmh7U9s1lpdTwPY7@J@903yTTLrqk7roQ/ld0O24U9mVPxuaP3DxJ/S9MmM9Fhy0tKcUD/otqUP5HpqLSfSI41s1@nPUGhchFZYP2M2Dp2N6x/9Q/Kf7bFjQGYM/mqb5L9tk/y7bf4C "Python 2 – Try It Online") or [Try an ungolfed version](https://tio.run/##xVTbattAEH3XV0zRgyVqL07TpxKDAnGhkOKQupSiCqFY60ZFXqmS3Ehf78zsRdLaTqF9aGXwzu6cmTO33bJrHgtxeThsq2IHm6LsINuVRdVAynlJe8dxbu5Xd7fLNSzg0vlyfXuLwoWz/Hi3/orSG2f1ef3pw80S5blzt7y@J/1bNEv5FsoqE038UCRV6sl//50D@G2LCvJMcMgEyHN1TJ808SYT9qPIhDcBl62CSZhF0iYjAzL0fcOQVDU/w1DxZl8JCEPtgWUi5a23eUwqX7oiyXiLTgNidZlnGMc3MfEjzbVFH3FaFWXOm5N0umnvgIv9jldJwy2QAbZT2PA8t4EypwFHX7ZVuMUCdAds/ShLdNmpEAVvm/gpyXNFPZWqKaS4pJ0meHrMcg5zuFpAC1eQc6HA4TzyIRGpUnVjlTpXqC4K2wheLYBmYQiphdcL5On3ndx3zkmYMs66yH8lD7ldoZ97vuc4PaE8jORZzbmgo6gvtFRS9SR8CADr1avIyq7WphBNJvZ8DBdFg3l1nppaPQuno3DUF53MukJnvYIIWVKWXJgxtHqu6k8eQ28@hQt/CrTOpHAxhTmtMylENhvVDPM/M3oWTCBOEPD3A2Db8Cd1cdDMXPdzvrFSaXs6e5RX2VJOVSK@c48iIJbWP8VadDRBJY7QAuQjcsLVvcDVDVwdZTsa6Ze5SjWuhut8AULRzVIEinaWSrC@cBZajpvpcW/qjwf8fZLXOBQOZhHHItnxOKbrO4njXZKJOJ6oaPUTW3e13Eo/NbLiAaubNBOs4knq@cMbRK/QcAH6yayH7E0jrffQP3pVj26dfziAaz7HdRl@AWMo4rKiTX/q4ukIa2RUowEjgVZp62qBIEoAcIOVFpR5zxkwV7IgThqvtBPyqfWOZTKEK03MJ/dMhh2M9kztdE69caD1gf6N8BLMNOuYzzmiX/VoGb9rhRLoohnHbjAOM3CtoAfKUUp2QKbQKqWj4ExoKibXWMpVtTOwrJyhESQwU2M2FJ0N7R/Oe/Cf9VFH4FoR/FU33f/WTfffdfMZ)
Prints `0` if the map is solvable and `1` otherwise. Takes input as a list of list of integer with the following mapping:
```
OUTSIDE = 0
WALL = 1
INSIDE = 2
DROPLET = 3
PEARL = 4
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 76 bytes
```
⊞υυWS⊞υ⁺⊟υ⪪ι¹FυF⟦Lθ¹±¹±Lθ⟧«≔Eιλη≔⌕ηOζW‹#§η⁺ζκ«§≔ηζ.≧⁺κζ§≔ηζO»¿¬№υη⊞υη»⊙υ¬№ι@
```
[Try it online!](https://tio.run/##bVA7b4MwEJ7hV5zMcpZcJOYsQZUqRUoDasaqA0oItmoZiu0@UuW30zMFytBbbH8v391JVv2prfQwlN5K9AI838QfUukacGc6746uV6ZBzmFWlNpbLNsOPRdw7LRyqARknJPz0vZAOIzn8742jZP4RrpMwKFuKldjxpfrwvMXDt9xlFurGoOPVRcSNQklZc7wgzJnlAJYwYi5BmZqdF9biyxhAnK3M@f6M8jGNq8CXqmxMX3KWUmIZSkLQRH9@Us/qUY6DGayTt/87yxG5y2O1AXw0Dq8b71xYUOSr9YVRrjFJW3RYW6@AvQnpjHZloUON8MAyVxxkqRU2zSlKx1FeCxoQuhKO9y96x8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangular newline-terminated list of strings and outputs a Charcoal boolean, i.e. `-` if all the pearls can be collected, nothing if not. Explanation:
```
⊞υυWS⊞υ⁺⊟υ⪪ι¹
```
Read in the list and convert it into a character array for convenience. Start a breadth first search from the initial position.
```
FυF⟦Lθ¹±¹±Lθ⟧«
```
Loop over all positions and directions.
```
≔Eιλη
```
Clone the current position.
```
≔⌕ηOζ
```
Get the index of the drop.
```
W‹#§η⁺ζκ«
```
While it's not hitting a wall...
```
§≔ηζ.≧⁺κζ§≔ηζO»
```
... move the drop one square in the current direction.
```
¿¬№υη⊞υη
```
If this results in a new position then save it to the search list.
```
»⊙υ¬№ι@
```
Output whether any positions have no pearls left.
] |
[Question]
[
This is a two-player card game which resembles a vastly simplified game of [Texas Hold'em](https://en.wikipedia.org/wiki/Texas_hold_%27em),
combined with RPS (rock-paper-scissors) and the most basic mechanic of commercial turn-based card games.
## The deck
A single full deck consists of 30 unique cards, where each card has one symbol out of `RPS` and one number between 0 and 9 inclusive. Each card is referred to as a 2-char string like `R0` or `S3` (symbol, then number).
Since the 30-card deck is divided into three smaller decks during the game, let's call the 30-card deck a *full deck* (as opposed to simply *deck*).
## The match
A single match consists of two phases: Draft phase and Main phase. In the Draft phase, the two players' decks (10 cards each) are decided. In the Main phase, actual games of Poker are played, and each player gets some score based on the number of games won.
**Draft phase**
1. The full deck of 30 cards is shuffled.
2. Repeat five times:
1. Each player is given two cards from the top of the full deck.
2. Each player selects one of them, which will go into their own deck.
3. Each player gives the unselected card to their opponent.
At the end of Draft phase, players A and B have a deck of 10 cards each,
and the main deck has 10 cards remaining.
Additionally, each player gets to know 5 of the 10 cards in the opponent's deck during the process.
**Main phase**
1. Each deck (player's and the remaining) is shuffled.
2. Each player draws three cards from their own deck.
3. Repeat 10 times:
1. A card (called *base card*) is shown from the remaining deck.
2. Each player plays a card from their own hand.
3. A winner is determined by comparing (A's play + base) to (B's play + base). The winner gains 1 point.
4. Each player draws a card from their own deck (unless there's nothing to draw).
## Deciding the winner of a single game
The winner is decided by comparing the two-card combinations in the following order:
1. If one combination is a pair (two cards sharing a number) and the other is not, a pair always wins against a non-pair.
2. If the two cards played (excluding the base card) have different numbers, the player who played a higher-numbered card wins.
3. Otherwise, the two cards are compared under the RPS rules. R wins against S, S wins against P, and P wins against R.
Note that a draw is not possible since every card is unique in a deck.
## Bots and the controller
An answer should include a single bot that can handle the Draft phase and the Main phase.
[The controller code is here, with three example bots.](https://tio.run/##zRjbbpxG9N1fMZGiAF28WWjTpt7YlZpUbR@sWrbUPiDUYBi8s2GBcHHi2ny7e87cmMGs0z5YShQtcO63OXOOt8l10qYNq7vDssrofd6XaceqkrSbPs8L6iZN45Fb8vKlghBWkrpIUnpASF41xC1oRxg5JkC5LGh51W3IIQnWADshK3gcHoIAICYEKbdAeZp0m2WTlFm1cz3yDXHZIvDIHVBrsm5XC5ERi9fyKQFbCdgiAOiQaTgYDtKqbDuS90XxjqYfAPfH5Zam3TJvKP2Huu7fxydoBkoHdsBH8dr0ISVVTqLlcumcn104sWd6pzCrIPz2u1ff//D6RyRAj@u@3bgpWRDmobSGdn1TImZ9MHiuB0AdUojaza/JjrqXVRf4BH5DERnUkbH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9xr5jk/U/S1XNU/XPLh5oc6NZoGdaaUpJiuKScTXFLtnc4NbUd3y/Y0yWkHGYp87D1yBMNM6GOJoWHMLg20MhpWOlTC2SCItEldO2DDX8DIRujWFzojdzoiV4wfQ6USBfHO3gwk05qXeooC1Jf4Z8EFV4s3PX6GTwenWscctd3GsymiFm65GbU1UEKtTjf8oRH86yvF9WWhbk4lXEmMKEU81sukuelmJZhHt7Vr7svQfcjRqEH0rksHjBepbURkbvsHUVk3nuol/6UFdgzeHSSRvhjlDDcYZc61RF0b6RTAsYZIdmcAICOWyTrJfyszVh80bHlAFMY6/8q8S8s8S6BmG8R61IfMRcU5ZyXZJ8SduZ44P8HHH5tsDVoYeyMigKeR1y4mAhiP0wmbsiDP8kwZmiID/e0wLvzLbLtiuLig3aneDF9gRKeknckE7uGtnLbUujN@xnMWiuMJcQWWIr4B//UQCcqTX4g2DFseVLJMsEwIjIUWdbOmFAPKs7wvGXpGeZtsTqgecGQV3qKvcsE1Z2eIehlSgB/8eDvWDeyWAhn//Lw)
A bot has the following structure:
```
{
name: 'MinimalValid',
draftPick(cards) { return 0; },
draftReceive(card) {},
mainPlay(cards, base) { return 0; },
mainPostprocess(card) {},
},
```
* `name`: The name of the bot, a string.
* `draftPick`: Called when the bot is given two cards to choose from during the draft phase (2-2).
+ Input: an array of cards to choose from
+ Output: a valid index in the array of cards
* `draftReceive`: Called to inform the "unselected-by-opponent" card to the bot (2-3).
+ Input: a single card
+ Output: nothing
* `mainPlay`: Called when the bot plays a card during the main phase (3-2).
+ Input: the hand (an array of cards), the base card
+ Output: a valid index in the hand
* `mainPostprocess`: Called to inform the card played by the opponent.
+ Input: a single card
+ Output: nothing
A slightly better bot to illustrate how to keep state in `this`:
```
{
name: 'Simple',
myDeck: new Set(),
draftPick(cards) {
let cardId = cards[0][1] < cards[1][1] ? 1 : 0;
this.myDeck.add(cards[cardId]);
return cardId;
},
draftReceive(card) {
this.myDeck.add(card);
},
mainPlay(cards, base) {
this.myDeck.delete(cards[0]);
return 0;
},
mainPostprocess(card) {
},
},
```
A bot is immediately disqualified by the controller if it throws an exception or returns an invalid index. A submission is also invalid if it tries to cheat the controller in any way.
Given multiple bots, the controller will run round-robin matches. The entire cycle will be run multiple times (exact number depends on the number of submissions) and all scores will be accumulated to decide the overall winner.
The deadline is **00:00 UTC on June 18, 2021**. ~~If we don't have 10 submissions (excluding the two example bots) until then, the deadline will be extended by a week until we do.~~ The winning answer will be accepted at that point.
The winner is **Basic Odds** by MegaTom. Congratulations!
You can still submit new bots even though the competition is officially over. (assuming I am active) I will run a new round and update the leaderboard. The accepted answer will not change even if the winner changes after the deadline.
The two bots presented here will be included when running the matches.
## Leaderboard
The following is the total scores after 100 rounds.
```
1. BasicOdds 2500
2. ObviousStrats 2336
3. tsh 2016
4. Simple 1916
5. MinimalValid 1232
```
[Answer]
# Basic Odds
This bot takes high cards, then, using its information on the game state, will calculate the chance of winning now, and on a random future round. Whichever card has the highest difference between those numbers will be played.
```
{
name: 'BasicOdds',
selfCards: new Set(),
opponentCards: new Set(),
otherCards: new Set(),
isWinner(self, opponent, base = '') {
if (self[1] === base[1] && opponent[1] !== base[1]) return true;
if (self[1] !== base[1] && opponent[1] === base[1]) return false;
if (self[1] > opponent[1]) return true;
if (self[1] < opponent[1]) return false;
if ('RSPR'.includes(self[0] + opponent[0])) return true;
return false;
},
draftPick(cards) {
if (this.otherCards.size === 0) {
fullDeck.forEach(card => { this.otherCards.add(card); });
this.selfCards.clear();
this.opponentCards.clear();
this.start = false;
}
this.otherCards.delete(cards[0]);
this.otherCards.delete(cards[1]);
if (this.isWinner(cards[0], cards[1])){
this.selfCards.add(cards[0]);
this.opponentCards.add(cards[1]);
return 0;
} else {
this.opponentCards.add(cards[0]);
this.selfCards.add(cards[1]);
return 1;
}
},
draftReceive(card) {
this.selfCards.add(card);
this.otherCards.delete(card);
},
mainPlay(cards, base) {
this.otherCards.delete(base);
let values = cards.map((card,i)=>{
let winnings = 0;
this.otherCards.forEach(oc=>{
winnings += +this.isWinner(card, oc, base);
})
winnings *= (this.selfCards.size - this.opponentCards.size) / this.otherCards.size;
this.opponentCards.forEach(oc=>{
winnings += +this.isWinner(card, oc, base);
})
let futureWinnings = 0;
let m1 = (this.otherCards.size - this.selfCards.size + this.opponentCards.size) / this.otherCards.size;
let m2 = m1 * (this.selfCards.size - this.opponentCards.size) / (this.otherCards.size - 1);
this.otherCards.forEach(newBase=>{
this.opponentCards.forEach(oc=>{
futureWinnings += (+this.isWinner(card, oc, newBase)) * m1;
})
this.otherCards.forEach(oc=>{
if(oc !== newBase){
futureWinnings += (+this.isWinner(card, oc, newBase)) * m2;
}
})
});
return [winnings - futureWinnings/(this.selfCards.size-1), i];
})
let bestIndex = values.reduce((r, a) => (a[0] > r[0] ? a : r))[1];
this.selfCards.delete(cards[bestIndex]);
return bestIndex;
},
mainPostprocess(card) {
this.otherCards.delete(card);
this.opponentCards.delete(card);
},
}
```
Credit to Spitemaster for the code he got from tsh, that I based this off of.
[Answer]
# ObviousStrats
```
{
name: 'ObviousStrats',
selfCards: new Set(),
opponentCards: new Set(),
otherCards: new Set(),
isWinner(self, opponent, base = '') {
if (self[1] === base[1] && opponent[1] !== base[1]) return true;
if (self[1] !== base[1] && opponent[1] === base[1]) return false;
if (self[1] > opponent[1]) return true;
if (self[1] < opponent[1]) return false;
if ('RSPR'.includes(self[0] + opponent[0])) return true;
return false;
},
draftPick(cards) {
if (this.otherCards.size != 30) {
fullDeck.forEach(card => { this.otherCards.add(card); });
this.selfCards.clear();
this.opponentCards.clear();
}
if (this.isWinner(cards[0], cards[1])){
this.selfCards.add(cards[0]);
this.opponentCards.add(cards[1]);
return 0;
} else {
this.opponentCards.add(cards[0]);
this.selfCards.add(cards[1]);
return 1;
}
},
draftReceive(card) {
this.selfCards.add(card);
},
mainPlay(cards, base) {
this.otherCards.delete(base);
let match = cards.findIndex(card => card[1] == base[1]);
if (match > -1){
this.selfCards.delete(cards[match]);
return match;
}
const opponentMatch = [...this.opponentCards].findIndex(card => card[1] == base[1]);
if (opponentMatch > -1){
const minValue = Math.min(...cards.map(card => parseInt(card[1])));
match = cards.findIndex(card => +card[1] == minValue);
this.selfCards.delete(cards[match]);
return match;
}
const maxValue = Math.max(...cards.map(card => +card[1]));
match = cards.findIndex(card => card[1] == maxValue);
this.selfCards.delete(cards[match]);
return match;
},
mainPostprocess(card) {
this.otherCards.delete(card);
this.opponentCards.delete(card);
},
}
```
ObviousStrats doesn't over-complicate things. When drafting, it picks the card that would win if played against the other. When playing, it plays a pair, its lowest card if it knows its opponent has a pair, and otherwise its highest card.
Thanks tsh for the base code!
[Answer]
```
{
name: 'tsh',
/** @typedef {'R0'|'R1'|'R2'|'R3'|'R4'|'R5'|'R6'|'R7'|'R8'|'R9'|'P0'|'P1'|'P2'|'P3'|'P4'|'P5'|'P6'|'P7'|'P8'|'P9'|'S0'|'S1'|'S2'|'S3'|'S4'|'S5'|'S6'|'S7'|'S8'|'S9'} Card */
/** @type {Set<Card>} */
selfCards: new Set(),
/** @type {Set<Card>} */
opponentCards: new Set(),
/** @type {Set<Card>} */
otherCards: new Set(),
/**
* @param {Card} self
* @param {Card} opponent
* @param {Card} base
*/
isWinner(self, opponent, base = '') {
if (self[1] === base[1] && opponent[1] !== base[1]) return true;
if (self[1] !== base[1] && opponent[1] === base[1]) return false;
if (self[1] > opponent[1]) return true;
if (self[1] < opponent[1]) return false;
if ('RSPR'.includes(self[0] + opponent[0])) return true;
return false;
},
/**
* @param {Card} card
* @returns number
*/
scoreCard(card, deckRatio) {
const sameNum = [...this.selfCards].filter(c => c[1] === card[1]);
const otherSameNum = [...this.otherCards].filter(c => c[1] === card[1]);
const largeThanOpponent = [...this.opponentCards].filter(c => c[1] < card[1]).length * 0.1;
const cardValue = parseInt(card[1], 10) + largeThanOpponent + 0.5;
if (otherSameNum.length === 0) {
return cardValue - 1 + largeThanOpponent;
} else if (otherSameNum.length === 1) {
const cardWin = !this.isWinner(card, otherSameNum[0]);
if (cardWin) {
return 10 * deckRatio + cardValue * (1 - deckRatio);
} else if (sameNum.length === 1) {
return 0 * deckRatio + (cardValue - 1) * (1 - deckRatio);
} else {
return cardValue - 1;
}
} else {
return (9 + cardValue) * deckRatio * (1 - deckRatio) / 2 +
10 * deckRatio ** 2 +
cardValue * (1 - deckRatio) ** 2;
}
},
/**
* @param {Card} card
* @returns number
*/
scorePickCard(card) {
return this.scoreCard(card, 10 / this.otherCards.size);
},
/**
* @param {Card} card
* @param {Card} base
* @returns number
*/
scorePlayCard(card, base) {
const selfWin = [...this.opponentCards, ...this.otherCards]
.every(c => this.isWinner(card, c, base));
if (selfWin) return Infinity;
const knownWin = [...this.opponentCards]
.filter(c => this.isWinner(card, c, base)).length /
(this.selfCards.size + 1);
const deckRatio = this.selfCards.size / this.otherCards.size;
return this.scoreCard(card, deckRatio) + knownWin;
},
/**
* @param {[Card, Card]} cards
* @returns 0|1
*/
draftPick(cards) {
if (!this.otherCards.size) {
fullDeck.forEach(card => { this.otherCards.add(card); });
this.selfCards.clear();
this.opponentCards.clear();
}
cards.forEach(card => this.otherCards.delete(card));
const scores = cards.map(c => this.scorePickCard(c));
if (scores[0] > scores[1]) {
this.selfCards.add(cards[0]);
this.opponentCards.add(cards[1]);
return 0;
} else {
this.opponentCards.add(cards[0]);
this.selfCards.add(cards[1]);
return 1;
}
},
/**
* @param {Card} card
*/
draftReceive(card) {
this.selfCards.add(card);
},
/**
* @param {[Card, Card]} cards
* @param {Card} base
* @returns number
*/
mainPlay(cards, base) {
this.otherCards.delete(base);
const opponentWin = [...this.opponentCards].some(o => (
[...this.selfCards].every(m => !this.isWinner(m, o, base))
));
const scores = cards.map(card => {
const score = this.scorePlayCard(card, base);
if (opponentWin) return -score;
return score + 10 * (card[1] === base[1]);
});
const index = scores.indexOf(Math.max(...scores));
this.selfCards.delete(cards[index]);
return index;
},
/**
* @param {Card} card
*/
mainPostprocess(card) {
this.otherCards.delete(card);
this.opponentCards.delete(card);
},
}
```
[Try it online!](https://tio.run/##zVltb9tGEv7uX7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9PPPG5DIpyUv0YsSsaXGzRx54Os73meM/v6Bw)
It cost so many bytes, but only *somehow* better than Simple... Don't know how to name it, so, whatever...
Anyone may try to build your own bot based on this one if it could be helpful.
] |
[Question]
[
The [Najdorf Variation](https://en.wikipedia.org/wiki/Sicilian_Defence,_Najdorf_Variation) of the Sicilian Defence is an opening often played at the highest level of chess. It is named after GM Miguel Najdorf and is known for being extremely sharp and theory heavy.
Your task is to write a program that, given a Boolean-like input, prints a chessboard representation of the opening from either White or Black perspective.
## I/O format
Your program can take any input that has two possible values. Boolean, Integer, etc.
Your program must output a square chessboard using your language's standard output (usually the console). Each piece must have a corresponding character (your choice). Black and white pieces must be different. Black and white squares are allowed to be the same, but you are allowed to have different characters for them if you wish.
Using standard notation and uppercase for white and lowercase for black, here are the two chessboards, though you are free to represent the pieces differently:
```
True False
R B K Q B R r n b q k b r
P P P P P P p p p p p
N p p n
P N
N P
n p p N
p p p p p P P P P P P
r b k q b n r R B Q K B R
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¤d2ʂẠ⁽ÞWƓż:§ßẸ:ȯlEØƘƑṀ°@œḥƥßıẠ’ṃ“Œ⁼L»s8UṚ$¡G
```
`0` outputs from White's perspective, `1` from Black's.
As allowed in the question this uses other characters, the mapping is:
```
Black White
R u t
N y i
B n a
Q p b
K r l
P d c
empty e e
```
**[Try it online!](https://tio.run/##AWMAnP9qZWxsef//4oCcwqRkMsqC4bqg4oG9w55XxpPFvDrCp8Of4bq4OsivbEXDmMaYxpHhuYDCsEDFk@G4pcalw5/EseG6oOKAmeG5g@KAnMWS4oG8TMK7czhV4bmaJMKhR////zE "Jelly – Try It Online")**
Or see **[this version](https://tio.run/##AWsAlP9qZWxsef//4oCcwqRkMsqC4bqg4oG9w55XxpPFvDrCp8Of4bq4OsivbEXDmMaYxpHhuYDCsEDFk@G4pcalw5/EseG6oOKAmeG5g@KAnHJicWsucE5QUkJRS27igJ1zOFXhuZokwqFH////MQ "Jelly – Try It Online")** which uses the letters from the question's example output and `.` for empty.
### How?
```
“...’ṃ“Œ⁼L»s8UṚ$¡G - Main Link: integer (from [0,1]), is_Black
“...’ - a large integer (stored in base 250)
“Œ⁼L» - dictionary word = "unpredictably"
ṃ - base-decompress (i.e. use "unpredictably" as the base-13 digits)
s8 - split into slices eight long
¡ - repeat (is_Black) times:
$ - last two links as a monad:
U - reverse each
Ṛ - reverse
(equivalent to rotating a 1/2 turn)
G - format as a grid
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~114~~ ~~89~~ 124 bytes
```
x=>`RNBQKB R
P PPPP
P P N
np
n
ppp ppp
r bqkb r`.split`
`.sort(_=>x-1).map(n=>[...n].sort(_=>x-1).join``).join`
`
```
[Try it online!](https://tio.run/##VUrBDoIwFLu/r3g3xoElfsA4cDUhyFWNG4gLON/mNg1/PxfjQZqmbdou6q3C6GcXK7LXKWmRVlHLvm0O@wZ76BC7jK9jC4iZSC4rgXMOMQt4HJ73Ab3kwZk5SsjB@sguol6rXckfyjES9ZFzTufttNiZpPw5yDRaCtZM3FjNNIv@NZUl/JfFiYpto9lNmZB/6QM "JavaScript (Node.js) – Try It Online")
Take the grid and flip if needed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 64 bytes
```
“¢ƙ]Ŀ°Mė8Ḃ“¢Ɠt:bẎ€^E“¡ṣḂƘ3^Q““¡⁽Ñ<Ṅ“Ṛ"ß“¡żN5Aʠṭm“¡ƬọG¢2|ie»UṚ$¡G
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDi47NjD2y/9AG3yPTLR7uaIIITS6xSnq4q@9R05o4V5DIwoc7FwMlj80wjgsE8sFCjxr3Hp5o83BnC5D3cOcspcPzwcJH9/iZOp5a8HDn2lww/9iah7t73Q8tMqrJTD20OxSoUuXQQvf///8bAgA "Jelly – Try It Online")
-6 bytes thanks to Lyxal by compressing the string using Jelly's built-in dictionary compressed string type.
## Explanation
```
“...» The grid itself
UṚ$ Reverse the order of rows and rows themselves (180 degree rotation)
¡ N times
G Formatted as a grid
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, ~~49~~ ~~45~~ 42 bytes
```
»¬℅→⁺w½]
oꜝ}l÷₄ǒẇ‡⋎ḋ∩P,*ø:⁺Ȯ∞J₀»k63ȯτ?ßṘ8/
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%C2%AC%E2%84%85%E2%86%92%E2%81%BAw%C2%BD%5D%0Ao%EA%9C%9D%7Dl%C3%B7%E2%82%84%C7%92%E1%BA%87%E2%80%A1%E2%8B%8E%E1%B8%8B%E2%88%A9P%2C*%C3%B8%3A%E2%81%BA%C8%AE%E2%88%9EJ%E2%82%80%C2%BBk63%C8%AF%CF%84%3F%C3%9F%E1%B9%988%2F&inputs=0&header=&footer=)
```
»...» # Push compressed integer
k6 # Push constant `0123456789abcdef`
3ȯ # Slice from 3rd character (`3456789abcdef`)
τ # Custom base conversion (to base13 with above)
?ßṘ # If input is truthy, reverse
8/ # Divide into 8 pieces
# Implicit join by newline
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
”⟲.>Xc'eΣZ\`KOXW⟲w‴PVCτΣ\⁻μ⊖[⊖U×K↙mψQ{π!J”UE¹⟲N
```
[Try it online!](https://tio.run/##FYaxCsIwFEV3v@LSKRkcBLduBQcRQsz8lqQNKNbX9PEq/n2angvnnvEVZVziXKuXN6vphNP6SRBiFKA0iI8AUxsA549zxN57oIk4YHg@BoTO9qfbXzNP5tIyLBo1mzuXTd32TVmMtX2t13r@zTs "Charcoal – Try It Online") Link is to verbose version of code. Uses `0` for White's view and `4` for Black's view. Assumes that Black wants to see the board rotated rather than flipped. Explanation:
```
”⟲.>Xc'eΣZ\`KOXW⟲w‴PVCτΣ\⁻μ⊖[⊖U×K↙mψQ{π!J”
```
Print the compressed board.
```
UE¹
```
Space the characters out horizontally.
```
⟲N
```
Rotate the board as necessary.
42 bytes without the horizontal spacing:
```
✳N”⟲.>Xc'eΣZ\`KOXW⟲w‴PVCτΣ\⁻μ⊖[⊖U×K↙mψQ{π!J
```
[Try it online!](https://tio.run/##FYbBCoMwEAV/5eEpAb311pv0Ugph63kvJggN2jUusb@/jW9g5qXPrGmfNzPSLNU9si6p5l3cU8pZw/mNizrve3Qq8VgjlAUFKG0s14FwA0CgK4GFiIAmlgnj@zVi6vzd7GbDb/sD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Prints the same compressed string, but in the input direction, which means that the string terminator is no longer required.
30 bytes by using a custom output format:
```
✳N“↶⊟∨dO9Rξ1d"⁼¦Q≕τm×↖WSLQg℅R₂
```
[Try it online!](https://tio.run/##FYg5DoQwEAS/0jaXDQsRGekmJIgHTAIW0lqCAVmG78@aDqpK7X5LcOeyi8zBczRfHzYX/clm5OuO032sWzDWfqBJZ7k1OUgTowO6NOI3kBGnDyjVq5JYKQUkEBeomrpCoe0g0kv77H8 "Charcoal – Try It Online") Link is to verbose version of code. Uses the following key:
```
. Black pawn
! White pawn
" Black rook
# Black knight
$ Black bishop
% White rook
& White knight
' White bishop
( Black king
) Black queen
* White king
+ White queen
```
] |
[Question]
[
# Win a K vs KQ endgame
## Summary
The goal of this challenge is to create a program or function which will win a Chess game with a King and Queen against a lone King. The user will specify three squares, representing the locations of the computer's King, the computer's Queen, and the user's King. The computer will then a output a move which will eventually lead to checkmate.
## Input/Output
The program or function will first take as input three squares, representing the locations of the computer's King, the computer's Queen, and the user's King (not necessarily in that order). It can be assumed that the input is a legal position.
Parsing input is not the point of this challenge, so all reasonable forms of input/output are allowed, including but not limited to
* Strings with algebraic chess notation such as `"Ke4"` or `"Qf6"`
* Triples representing pieces and coordinates such as `('K', 0, 2)`
After three squares are taken as input, the computer outputs a single legal move. Behaviour on invalid input is undefined.
## Requirements
This procedure must terminate using your program or function:
* User sets up a legal KQ vs K position on a physical chessboard.
* User inputs the board position. The computer outputs a legal move. If the move is a checkmate, STOP. If the move is a stalemate or allows the computer's queen to be captured, your solution is invalid.
* User makes the computer's move on the physical board.
* User makes a legal move for the lone king on the physical board.
* User goes to step 2 and repeats.
In other words, the computer must eventually win by checkmate, through repeatedly using your program or function.
Furthermore, from any legal starting position the checkmate must occur in 50 or fewer moves by the computer, i.e. the above procedure will be repeated no more than 50 times. An explanation as to why your solution will always win in 50 moves or fewer is appreciated.
(Of course, a physical chessboard is in no way necessary to test the code; I only mentioned it to help visualize the procedure. The chessboard could just as well be visualized in the user's head.)
## Possible test cases
The squares are given in the order: *computer's Queen, computer's King, user's King*
* `c2, h8, a1` (must avoid stalemate)
* `a1, a2, a8`
* `a8, a1, e5`
## Rules
* The checkmate must occur in 50 or fewer moves by the computer, but it does not need to be as fast as possible.
* Chess libraries are not permitted.
* Shortest program in each language (in bytes) wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 1054 bytes
```
def d(kx,ky,x,y):return abs(x-kx)<2>abs(y-ky)
def l(qx,qy,kx,ky,x,y):
if x==qx:return x!=kx or ky<min(y,qy)or max(y,qy)<ky
o=kx<min(x,qx)or max(x,qx)<kx
if y==qy:return o or y!=ky
if x-y==qx-qy:return o or x-y!=kx-ky
return x+y==qx+qy and(o or x+y!=kx+ky)
def f(c,x,y):c[x][y]=1;[f(c,u,v)for v in range(max(y-1,0),min(y+2,8))for u in range(max(x-1,0),min(x+2,8))if c[u][v]<1]
def s(qx,qy,kx,ky,hx,hy):c=[[d(kx,ky,u,v)or l(qx,qy,kx,ky,u,v)for v in range(8)]for u in range(8)];t=sum(map(sum,c));f(c,hx,hy);t=sum(map(sum,c))-t;return t if t-1else 64
def m(qx,qy,kx,ky,hx,hy):a=[[s(x,y,kx,ky,hx,hy)if(x+y-7and x-y)and d(hx,hy,x,y)<=d(kx,ky,x,y)and l(qx,qy,kx,ky,x,y)and l(qx,qy,hx,hy,x,y)else 64for y in range(8)]for x in range(8)];b=list(map(min,a));c=min(b);e=b.index(c);return(0,e,a[e].index(c))if c<a[qx][qy]else min(((x-hx)**2*2+(y-hy)**2*2+(x-3)*(x-4)+(y-3)*(y-4),x,y)for x in range(max(kx-1,0),min(kx+2,8))for y in range(max(ky-1,0),min(ky+2,8))if(x!=kx or y!=ky)and(x!=qx or y!=qy)>d(hx,hy,x,y)and(x-7and x or y-7and y)and s(qx,qy,x,y,hx,hy)<64)
```
[Try it online!](https://tio.run/##dVRNc6MwDL3zK7zs7IwdTKdJs202wf0DPfXMcCBAaoaEr5Cufdm/npVsSMhXDkFIT/LTk0ytO1mVL8djmm1ISgvFC80V12zZZt2hLUm83lPlF4oFs3e0tV9o5iB6SxvFG81HOQ7JN0QJ0aghXf0QhSJVSwod7PKSashg8LqLlbWDQjukApAJQ0E1hI0dFMoU1VBUD0UrLKihsrYH@hhV/hUA3Hi4j6iBjWeQXqNJXKbUwjwD84a2NjSxzSShikIdiekqRN@Bf7MN4L9JXpI2Lr8yaprwp/yZcdObN@MLZkCHS5A6g5QFAe0kPEThdxRMI3Pu/kJOqbhEDiIMh6kgASh9KfsdVgsWXVEAz6oT@8MOyNQUnjxhbIVN2WNug3636iXrUOHOn2bbfUZe54bq7h7VGKjCqvBLd76BjrX/BnLjQBg@U2piRuVAjJcOo7drNfaeM3tC2Kq@aV5dNr8W23zfmQZhBjyG7hOB01izVSbWT3mZZoomrG@aPvOMx2EWnQJmXkEcNrASjY7M2ZhPYbRSsclkNpl5sAvQcW8r/4VN4H/O0I@2BtswvyKIC1KMNqRQ5z3SV7DRthV62CR6umTmTqBe6GoGF9yy97HmJt6PxECsbYUe1hAHaUcYvM7ZMd/VVdshlbTaOTfjF/SfX7UpKPVrgbwT5J2X9aGjjDk1VhP3tsb5K/NtRmqkcbs89ntSL41PQNQhqPzS1LHv9nRL6ymRVZ5k1MyaPlBajpSWj5WWI6XlhdJykFVawcqqo@Mdvrmi6ISfQ@o2Lzvqfny6ISSROvIS2dI/b55i3r5r6dTTjLsf7uCWJz8chfmPZexLf7p3SnruT5cd40U8zX7/Bw "Python 3 – Try It Online") Link includes footer which starts from the given position (input as a string of three squares in the order computer Queen, computer King, human King, without separators) and plays random moves on the human's behalf until the computer checkmates it. I've never seen it take anywhere near 50 moves but I don't know how to prove that it won't. Not completely golfed for the sake of my sanity. Explanation:
```
def d(kx,ky,x,y):return abs(x-kx)<2>abs(y-ky)
```
Determines whether a square is under attack from a King, e.g. to prevent the Queen from giving itself away.
```
def l(qx,qy,kx,ky,x,y):
if x==qx:return x!=kx or ky<min(y,qy)or max(y,qy)<ky
o=kx<min(x,qx)or max(x,qx)<kx
if y==qy:return o or y!=ky
if x-y==qx-qy:return o or x-y!=kx-ky
return x+y==qx+qy and(o or x+y!=kx+ky)
```
Determines whether the Queen is threatening the square that the human's King might want to move to.
```
def f(c,x,y):c[x][y]=1;[f(c,u,v)for v in range(max(y-1,0),min(y+2,8))for u in range(max(x-1,0),min(x+2,8))if c[u][v]<1]
```
Helper recursive function to flood fill the squares that the human's King can reach.
```
def s(qx,qy,kx,ky,hx,hy):c=[[d(kx,ky,u,v)or l(qx,qy,kx,ky,u,v)for v in range(8)]for u in range(8)];t=sum(map(sum,c));f(c,hx,hy);t=sum(map(sum,c))-t;return t if t-1else 64
```
Calculate the scope of the human's King. However, it returns 64 on stalemate, indicating that this is a bad move for the Queen to make.
```
def m(qx,qy,kx,ky,hx,hy):a=[[s(x,y,kx,ky,hx,hy)if(x+y-7and x-y)and d(hx,hy,x,y)<=d(kx,ky,x,y)and l(qx,qy,kx,ky,x,y)and l(qx,qy,hx,hy,x,y)else 64for y in range(8)]for x in range(8)];b=list(map(min,a));c=min(b);e=b.index(c);return(0,e,a[e].index(c))if c<a[qx][qy]else min(((x-hx)**2*2+(y-hy)**2*2+(x-3)*(x-4)+(y-3)*(y-4),x,y)for x in range(max(kx-1,0),min(kx+2,8))for y in range(max(ky-1,0),min(ky+2,8))if(x!=kx or y!=ky)and(x!=qx or y!=qy)>d(hx,hy,x,y)and(x-7and x or y-7and y)and s(qx,qy,x,y,hx,hy)<64)
```
The meat of the program, this actually computes the computer's move. The return value is a tuple of (Piece to move, desired X, desired Y) where the flag is 0 to move the Queen and all parameters and X and Y are 0-indexed. It first checks all of the Queen's available moves (except those that give it away or those to squares on the main diagonals, as the symmetry confuses it) to see whether it can reduce the scope of the human's King. If not, it tries to move its own King nearer the human's King, or failing that, nearer the middle of the board.
] |
[Question]
[
Don't you hate it when you're trying to roughly sort a list based on user data, but you have to poll the user for thousands of comparisons?
Hate no more, because the answers to this challenge are (going to be) here!
## Method
The sorted-ness of a list is defined by how many possible comparisons it has which are correct.
Let's have an example. The list `[1, 2, 4, 3]` has the possible comparisons `1 <= 2`, `1 <= 4`, `1 <= 3`, `2 <= 4`, `2 <= 3` and `4 <= 3`. 1 out of those 6 comparisons are incorrect, so this list is (5 / 6) \* 100 = 83.33% sorted.
## Challenge
Create a program or function that sorts a given list (but not necessarily 100%) and sorts all of the below test cases by at least 75%.
If your program sorts a list by less than 75% that is not in the test cases, that's okay, but try not to hard-code to the test-cases although I can't ban you from doing so.
You must use a comparison sort. Pretend the numbers are black boxes that only support comparison operations.
Your program may sort the list backwards, which means if it's is able to sort all of the test cases by less than 25%, you can post it as a backwards sort.
For programs that perform STDIO, the list should be taken and printed as base-10 integers with some kind of separator, with optional text at the start and end (for example `1\n2\n3` or `[1, 2, 3]`)
You may also return or print a list of indices that correspond to the sorted list (e.g. `[1, 3, 2]` when sorted is indices `[0, 2, 1]`)
You may not compare any of the elements of the list with any constant values.
The [defaults for I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply as usual.
## Scoring
This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), not a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your code is scored by the highest number of comparisons your code needs to be able to sort across all of the test cases.
A comparison is defined as any operation that involves a value `x` from the given list and another value `y` which may or may not also be from the given list, and does a boolean check of one of `x < y`, `x <= y`, `x == y`, `x >= y` or `x > y` *or* returns a result depending on whether `x < y`, `x == y` or `x > y`. This includes any expressions, including mathematical equations, that have the same effect of comparison.
The test cases are [here](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoMS8lP5eLiwvC0CtOTU3RMLYwNTE1MDc3sTSxNLY0M7Ew0OTiSssvUohXyMwDaUlP1TA0NdC04lIAgoKizLwSjWioASAKxDfQUTAyNdVUwKItVvP/fwA).
To verify your sorted lists, use [this](https://tio.run/##bY9NasQwDIX3OoWWNhj3Jy2F0vQiQxjSxMOIKnawlCE5fepMwqyqlfSEvvc0LnpNsVpXGsaUFUlD1pRY4BBkEQBgEhWs8RRuLZvZ4iVlnJHitveiPUWfQ9sb62VkUqYYxNgGoA8X7K6h@z1LwYW@6GLYfgKWykEm3sEzftW47FxXmoJ@ZPFdGn4otkoplmOHr4W83@uUS4ZpMAfK4hNyiI8RYMwU1bTM5p8Y@F3js/94v/vyZnr/1Np1Pb0UH4dvDqsGtqFyeEjNHw) program.
The lowest score wins. Good luck!
[Answer]
# [Python 3](https://docs.python.org/3/), score 244
```
def sort_func(l):
num_pieces = 9
medians = [median5(l[5*i : 5*(i+1)]) for i in range(num_pieces)]
center = median(medians)
lows = []
highs = []
for x in l:
if x < center:
lows.append(x)
else:
highs.append(x)
for d in range(9):
for lst in [lows, highs]:
if lst[d] > lst[~d]:
lst[d], lst[~d] = lst[~d], lst[d]
l[:] = lows + highs
def median(lst):
lst.sort()
return lst[len(lst)//2]
def median5(l):
a, b, c, d, e = l
if a > b: a,b=b,a
if c > d: c,d=d,c
if a < c:
a = e
if a > b: a,b=b,a
else:
c = e
if c > d: c,d=d,c
if a < c:
if b > c:return c
else: return b
else:
if d > a:return a
else: return d
```
[Try it online!](https://tio.run/##fL1Lr23HlaXXFn/FdblhqopWrXhHJErZM@CG4aY7iUSCIpmVhClKFimXsuO/Xj4r5vhGxEk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TRukzYMWkJlss5Qo2YudXpfNavhzYVD2mnJdowpWa9ut1ucN4IrVUF53/c/WfQW@5qfXOxnyGAle@nD7y0z1qVZhXJAqTSb8078/69y2/nFgQIYJqvccaXvtrrdMhC7Op7bs@sbY2W/@Z2peXqI3bhS/v/kEBgk9v0C3pRTONmIhFvooTq1zsG/qn/PJFUyl9VBitzxN6gyqGulUFLkpwsXq0repDOFLYvwdz9RVt938mklZlyj7laqumP1VmIhoK7UqoWmphQI5wyfCsmJJnDMNkfy1N3Hrsje5zWpUuCaWy1liloRc/i1ZqyturMuE80clVUOonDO9PF6VFwlC7p338 "Python 3 – Try It Online") Thanks to user202729 for making the comparison-counting class for verification.
The algorithm has 3 parts:
* Estimate the median of the list (~76 comparisons if unlucky)
* Compare each element to the estimated median and put it in the low or high sub-list (150 comparisons, 1 per list element)
* Tweak each of the low and high lists by swapping the first and last elements if they are other of order, then the 2nd and 2nd to last, up to the 9th and 9th-to-last (18 comparisons)
* Output the concatenated low and high list
The idea is that if we knew the median of the list, we could partition the list into its low and high halves by comparing each element to the median. Then, putting the high half after the low half, any comparison between elements from different halves is correct. On average half the within-half comparisons happen to be right, so a random comparison has about a 75% chance of being correct overall.
Sometimes though we get unlucky in the random comparisons for a given list. So, we improve each half a little by swapping the first and last element if they happen to be out of order, since this is the highest-impact swap for one comparison. Then, do the same for the 2nd and 2nd-to-last element, and so on. It turns out that doing this for 9 elements on each end for each half is enough to bring us over the 75% mark for all the test cases.
The median used is an estimate, since finding the actual median is too expensive, which also contributed to getting worse-than-average scores. It's estimated by taking 9 groups of 5 elements, finding the median of each, and then finding the median of those values.
The median of 5 is found using an worst-case-optimized algorithm that uses a maximum of 6 comparisons. The median of 9 is computed naively by sorting, which is surely inefficient. There are algorithms that use 14 comparisons in the worst cases, but I haven't found code for one.
A potential improvement would be to used the information gained in the median-finding step in the sorting step. We already know how the median compares to itself, the 8 other elements in the list of medians, and the 4 other elements in its group. This would save 13 comparisons, for a score of 231.
Further information could be gleaned using elements that were found smaller (resp, bigger) than a median that is itself smaller than the median-of-medians. We could also put each element used in the median finding into its estimated rank position in the final list.
Another potential improvement would be to use the full `cmp` comparisons rather than just `<` to better handle the case when elements are equal, for exactly by putting elements equal to the estimate median into the middle.
[Answer]
# [Python 3](https://docs.python.org/3/), score = ~~172~~ 164
```
def shell(a, cmp):
for step in [148, 138, 107, 43]:
for i in range(len(a) - step):
if cmp(a[i], a[i + step]) > 0:
a[i], a[i + step] = a[i + step], a[i]
```
[Try it online!](https://tio.run/##bVJdb6swDH3Pr/DbgsbtpQPWD439iL1WqMpo2kY3JCgJuuXXdzaBrtWWh2Dj4@NjO90Qztbk1@tBHsGfpdZcpNC0XbJlgOdoHfggO1AGdstincIypytbpVDkdQTNQEUoJ8xJci0NFwn8GZOTbxgddaQCXOxUnQLe8Dyi6gTeIXuE0vmBg@reG0P1VbWddQFUkC5Yqz2bfqCcg20Zo/4a4aXnkxpy9s6ckC1iFh/jh@frsiiz1arYFJt881qss@Q2iv13h8syu@trUFIfYDeTLohSmcCzFF7KMvktuZ5EnWXzb@9RqzwY6T3XE62TvtfBo77dBd4qGEaSS4oG8twaXTS2/VRGBGUNJmM9ZI75oXcGfN/yiSqBv0CLmd1JgO1NUOa0p6UQ/VT/pO2n0DEcJ0YWPFewvOfnF1zbQKtG6w0txv5b5wPqzhgjyTQUkvw4/pGMMOTZnmwCYDvdwOPE43vEWPogMgaF9ziBn@NDOD4kJF6syntghMRwVc0ulYx8naN9kT9Vi7/nXlpx4aN9i7KY8eQb6@T2KY3Q5PoF "Python 3 – Try It Online")
Four passes of [Shellsort](https://en.wikipedia.org/wiki/Shellsort).
# [Python 3](https://docs.python.org/3/), score = ~~229~~ 196
```
def insert(x, a, cmp):
if not a:
return [x]
m = len(a)//2
c = cmp(x, a[m])
if c < 0:
return insert(x, a[:m], cmp) + a[m:]
elif c > 0:
return a[:m + 1] + insert(x, a[m + 1:], cmp)
else:
return a[:m] + [x] + a[m:]
def ford_johnson(a, cmp):
if len(a) <= 1:
return a
m = len(a)//2
cmp1 = lambda x, y: cmp(x[-1], y[-1])
b = ford_johnson([insert(x, [y], cmp) for x, y in zip(a[:m], a[m:2*m])], cmp1)
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], cmp1) + [[y]]
if len(a) % 2:
b.pop()
return [x for x, in b]
def thirty_four(a, cmp):
for i in range(34):
a[i::34] = ford_johnson(a[i::34], cmp)
```
[Try it online!](https://tio.run/##fVRNc5swEL3zK3TpRGqI488mYeL@hB56ZRhGYNlWAxIjianpn3d3JWHjJC0HkJa3b9@@FXSDO2q1Op93Yk@kssI4ekoJT0nddixLCFxyT5R2hIcdXka43iiSnwofasmWNEJRzh4flz5SQwQIPFXeFmzkqckrmX/gmdTNs7YItck9pmahgmh88vdPkjEFsIsCblMiH8wiWSSx4tN0TIVeLhUTNGOvza78pY/KaujsnR@hW/K6hRIfGP/lSdstMMjbascJaByy4FH@sACZAz6C0ApgN@Xza2P5MPoDCM8CXZM/sqPRO2xh@RU8D7gFe6f5C1leJVfkfkvynAcJP7QSRTAcyd@Q2XB1ELRNYzq75jYpkSlBTQMDwS0/UfogZ5V0JWAP7kiZR7ggFVdIKFTfCsOdoBUbZQFkuyVLdtWVZzIMdTsOFQaU@vjYFw4N3Cj@29@s0x0NvJdDOzoHYqo4bHeUxg3lXvfmdtZe@dWH1XpiAM9llq3WxftpjfHAc5Ztpw207qALrRubxAAw7nQb6tfcCksjN25Kow7AGzCzn/5BV8@b9Wb@9LR@Wb@sXr6tn@fsIrK8ilxs5hOVgxTNjuQj6QwppXJ0npLlZsM@S46m1EdRv5UWtIqdEtbSJtIaYfvGWdAHZsI3MNycxUujs1q3lVTcSa0gGeqxYjoJ27c0UjHy6Oc3bqMA3Ssn1aGMv5Ih1j80uuJNeB0cwxUe5cWUn57ghwFn8wFXr7BKkt/aWAe650mCktEUlHxrvydDDO50j2sEQDvdEM/S9LwAIr2RGiDc4rH9aCLAGfkO9LOnzRQYIOE1fAxxi4UDX2dwariP1UJ47Ag/P7@@vE1Cxp2ttRHZXRqg7PwX "Python 3 – Try It Online")
Consider the list as 34 interleaved lists and sort each independently, using the [Ford–Johnson merge-insertion sort](https://en.wikipedia.org/wiki/Merge-insertion_sort).
[Answer]
# [Python 3](https://docs.python.org/3/), score 757
```
def f(l):
a = 0 # we are going to sort the first (a) elements
n = len(l)
while (
a*(a-1)//2 # there are ~ pairs that is guaranteed to be in order
<=
n*(n-1)//2 # total number of pairs
*0.75): # it's possible to compute this in O(1), but I'm lazy
a+=1
return sorted(l[:a])+l[a:]
```
[Try it online!](https://tio.run/##fVRNc9owED3bv2I7OSAlLjEJNAkDubUzvaSXTi8MwwizBk1kyZXkxjST/nW6kvnIIQMzYEk8vX27@9b11m@Mvt3JqjbWgxV6ZaoMpEfrjVEuTbujvkNcsdv70XCU390NH4YPtw9fhvc5T9NCCefgqanGABewMqCNB1EUSKd@g9Bre1BhtUSbJoVptJ/mHwGlA2wLrD2UxkJtpSY56Brl02SFJSwWUku/WDCHqsyg5eM0ScK6307bA6So6iPCUHDLo6itaaAQmr5KdaFkGQ9fhCb6hMT3o7Sr6YC29Kff1sg6BiB4UBoztEI6hF9CNfjVWkMpJRZ9YzWwTstjvNRv@ef9weRwcNCoQhIiW/Lx/qboH4Qv@SQ/wvAcbHrE6XO4Tycc/j6Dm55w63N8j@9w59J4zNM0wP4IJVdMUa@APl07HUxh1sJkCtvY6jajhdQnz1ErqqXUwkujHVMZ3PD5/n4M5JqK7ak4XINCfdo@Qt6/G@1C7DLGTQSFi4Z7QRAWYW2kXoM34ILhg0FLaZ0HJjigwgq1d2mi6VYgVtS2l41UCIxanYhLJj4P@PX1TWAMje1I/0EtiIVOhA9@WTeC5sbTzIRISwz5GbsKI5Akk2n41ZdMv6MyXijQTRgTMGVHF2CXIZ/OxdL3HNTGObkkPcRLdaobj3tHa/jBBjyDZePhe68CJf5uiUFETx9KRznTHKvZWMz5lZqJ8XznCkMZUJHS0I1FICLta2SDUb5v3HE@IuzUStqWbPYU@tG9JcKDBpfl1LTRiHP4gHLOI0OccFb2fiIV/3XxlkEn5PUY7K3XIQ8CK9GyuM5OgjrERRhQ7KofLSf9FooNFs/gxTM6EKBogqmuoWTCSkfOogqaeJteX@S8vVe7xHh6kPeNjKg6CWN4jU/StfsP "Python 3 – Try It Online")
The solution simply sorts about first ~75% of the array, so that it's guaranteed to be valid.
Python `sorted` takes about O(n log n) comparison.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 669
```
cnt=0;
function wtf(arr){return arr.length*~-arr.length}
function finished(arr) {
x = 150*149*.25; // toleration
for (i in arr) x-=wtf(arr[i]);
return x>=0;
}
function cut(arr) {
rnd=(Math.sin(arr.length)*1237812731+127317823102)%arr.length|0;
tmp=[[],[arr[rnd]], []];
for(i=0; i<arr.length; i++) if(i!=rnd) {
cnt++;
//tmp[arr[i]<arr[0]?0:1].push(arr[i]);
if(arr[i]<arr[rnd]) tmp[0].push(arr[i]); else
if(arr[i]>arr[rnd]) tmp[tmp.length-1].push(arr[i]); else
tmp.splice(1,0,[arr[i]]);
}
//console.log(arr.length+','+t)
return tmp;
}
function nesort(arr) {
e=[arr];
while(!finished(e)){
x*=-5;
t=0;
for(i in e) if(e[i].length>e[t].length)t=i;
for(i in e) if(e[i].length<e[t].length && wtf(e[i])>x)t=i;
e.splice(t,1,...cut(e[t]));
}
return (e+'').match(/\d+/g).map(parseFloat);
}
```
[Try it online!](https://tio.run/##XL3LrnXLlp1V5ylOEeSDFPeLwE@SopACIxkJbCUWFR4e1ojevhYxs@D0Pnv//1pzjhGX3ltvl//jX/@ff/2//9d/@8//9b/9j//Xf/nf/tP/97//l3/77//P//Tf/vU//8f0P/3j/MP/nDv/@B/@w//wj//3v/vXf/u3//gv/5JX/uc/6j//kcff/5f@@Y@9//65lH/@o@T1z3/M9f3DP//x9//Vvz9Q6vz@5N8/5fb3R1b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r6sd2yxzm6ZJFgElOtphS0IM/i1Joytsr0uEc0cpSotBKHN7qLVVvBULq4@/u7Xw/H9w/37/788Hi8de9efPz2@OH48OVx99vx49X7p6f970@H47enx93p3zefD4@/HD@9@s@b@cUf8xUfHx4fnj8dft5etvv9xW73fXd7/vRend7bq5uQ3@3evt0dv3w@PL0/v@D0DR@/PO2uHnYP24/f776/ubVfe/dwv393@gb75d9/Or@35Xd9@Hacv@bp8efbq3@@P366eX54vJrvbf/q9FCr7XQzR3@9/X9tp/vHhf1f5zf9251/z/HXr7d3d6fb@Py7Tz/v/v717u7@/t14j1cPp1@/e/hxvur01fX1fvfw8erhL7en7x9vZLc7XcXr63fbP9@@Pf3Qu/G3nF955@7/7v7m72@@fnv@tP6Nu/OPWb7v/Ov353d0esXlN@8On58Pl6/46fIVp//ZO3zj/@eLz9/0/PXzw4fDlX/tXtt7HG/mjxfnd/7hy@Pz6XO6@fzll@V6Xr98/fL6uJ8fy@kHXXwqj4fnL0/LB3O4Pf/s7Sr@9unh8@HqL1ojh/1@XLHvr27f5HEZtgV4/sd2yc@r4rBd4sPp3dlb@Olwd@Tf@@Ptw//7/h@X79/98MO2qs//ef/T9/nyA1fj@Nq/vrm5OS@u8@v2uiL2914drl@@3N/8@v744dPV23/9fP32l/NXX6@@vn96Pvzj85f3x/35gvx5cQVfXC3X5fwD3r1Yr@9pyZxf9Od/AQ "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Write a program or function that takes **N**, and **S** and outputs the number of palindromes of length **S** you can build using an alphabet of size **N** such that any prefix of size between **2** and **S-1** is not a palindrome.
For example if **N** were **2** and **S** were **5**
The valid palindromes would be
```
01110
10001
```
And thus the answer would be 2
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes based on their length with fewer bytes being better.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṗŒḂƤ€Ḋ€Ḅċ1
```
This is a brute-force search over all **ns** possible strings.
My results differ from the other answers', but [the solutions my answer counts](https://tio.run/##ASYA2f9qZWxsef//xZLhuILGpOG4iuG4hD0xCuG5l8OHw5BmR////zP/NQ "Jelly – Try It Online") seem to be valid.
[Try it online!](https://tio.run/##y0rNyan8///hzulHJz3c0XRsyaOmNQ93dIHJliPdhv///zf@bwoA "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
lf!tit_IM._T2^SE
```
**[Try it here!](https://pyth.herokuapp.com/?code=lf%21tit_IM._T2%5ESE&input=5%0A3&debug=0)**
My answer agrees with [Dennis' results](https://codegolf.stackexchange.com/a/152225/59487), rather than the Haskell and the Python answers.
### How it works
```
lf!tit_IM._T2^SE | Full program.
SE | Grab the second input (E), make an integer range from 1 ... E.
^ | And take the Qth Cartesian Power, where Q is the first input.
f | Filter by a condition that uses T as a variable.
._T | Take all the prefixes of T...
_IM | And for each prefix, check if they're invariant over reversal.
t | Take the tail (remove the first element).
i 2 | Convert from base 2 to integer.
!t | Decrement, negate. Note that among the integers, only 0 is falsy.
l | Take the length of the filtered list.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
Lf(=1ḋ↔mS=↔‼hU¡h)πŀ
```
[Try it online](https://tio.run/##yygtzv7/3ydNw9bw4Y7uR21TcoNtgeSjhj0ZoYcWZmiebzja8P//f6P/pgA "Husk – Try It Online") or [view the solutions!](https://tio.run/##yygtzv7/P7c8TcPW8OGO7kdtU3KDbYHko4Y9GaGHFmZonm842vD//3@j/6YA "Husk – Try It Online")
### Explanation
```
Lf(=1ḋ↔mS=↔‼hU¡h)πŀ -- takes two arguments N S, example: 2 4
ŀ -- range [0..N-1]: [0,1]
π -- all strings of length S: [[[0,0,0,0],[0,0,0,1],…,[1,1,1,1]]
f( ) -- filter with the following predicate (example with [0,1,1,0]):
¡h -- infinitely times take the head & accumulate in list: [[0,1,1,0],[0,1,1],[0,1],[0],[],[],…
U -- only keep longest prefix with unique elements: [[0,1,1,0],[0,1,1],[0,1],[0],[]]
‼h -- get rid of last two (apply twice head): [[0,1,1,0],[0,1,1],[0,1]]
m -- map the following
S= -- is itself equal to..
↔ -- .. itself reversed?
-- ↳ [1,0,0]
↔ -- reverse: [0,0,1]
ḋ -- convert from binary: 1
=1 -- is it equal to 1: 1
-- ↳ [[1,0,0,1],[0,1,1,0]]
L -- length: 2
```
[Answer]
# [Clean](https://clean.cs.ru.nl), 129 bytes
```
import StdEnv,StdLib
?l=l==reverse l
@n s=sum[1\\p<-iter s(\a=[[e:b]\\e<-[1..n],b<-a])[[]]|and[?p:[not(?q)\\q<-inits p%(2,s-1)]]]
```
[Try it online!](https://tio.run/##JY6xCoMwFAB3vyJLQcEItnQpBh3aoeDmmGR4aloCyVOTKBT67U0Fp@OGgxuMAox2GlejiAWNUdt5coF0YXzglu9odZ/UhhnGnNqU84qYpEHimV8tL4WYK6qDcsSnAhjn6tZLIVRFeVkUKPO@oiAzzqX8Ao68nm8cp5DWSybEsqeogyfzKT3nnpaZlDJ2AVxIGGku5Bp/w8vA20f6bOP9g2D1cMhx9gc "Clean – Try It Online")
] |
[Question]
[
Input: An integer N which represents the polygon's vertices and a list of their x and y coordinates.
Expected output: The smallest difference possible between the area of the(not necessarily convex) polygon and the triangle containing it. The triangle also has to share at least 2 vertices with the polygon. If there is no such triangle print -1.
Example:
```
4
0,0
2,0
1,1
0,2
```
Output: 0, because the polygon matches up perfectly with the triangle.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
[Answer]
# Python 3.9.12: ~~588~~ ~~585~~ ~~583~~ ~~580~~ ~~578~~ 572 bytes
3 bytes saved thanks to Jiří, and 2 bytes saved thanks to clarification from att!
```
from numpy import*
from itertools import*
def J(V):
c,a,X,I=combinations,array,cross,vstack;V=[*map(a,V)];s=lambda A,B,P:sign(X(B-A,P-A));Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;W=[a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0];return min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)
```
[ATO link](https://ato.pxeger.com/run?1=ZVLLbtswEAR61Few6GXXWTWWU6CFDB4cBA7SQxFfFMOCYNA2bROWKEGkXz-RH-gll_aj-jVdynEv1WExXGpnhoP9-bs5-21t395-7f06_vbnw-u6rSth91VzFqZq6tb3oq5lvG59XZfuX3ul1-I7ZPQD00gsSdGUnuSyrhbGKm9q60i1rTrTsq2do4PzarkbZrI0zkOlGlCUIQ6dLFW1WCkxont6Tp3ZWJjCfTyi53jE95Pr_YGO9JiqsgSYpzI_iXXdikYYKx6FWQtlz9DEB-xdwBF7cEqlgzDWIBYo5TzvFzgcXwlnqVo4cPsK8pItl5vPK-3hCWCWm4K43CQFIgYZE2RaZTcaSm1hhnHCjHg7GL7IXEEemG_n-aCgeZ5cUNEN7qgMo0sIf7GVS5fBpZvRANn7pHOZYdEdw_OmnAFsU7ntUoPgiqkQqbbaAXyhBMPHsrRlRaQpbIP8Nr8Lnhl-lP1i2Gq_b62ojIV8DBrjMWT_O-iMhuNLCNJBDzQHHCztmEzZFRs80oEeUpndaOxN2MuRHgI40I5BQbwLal96yblE0SehT6pqSh2xvpC8JDn0qY8ESVcHXb17x0nXH3SVU6WvGDWtsR54GC9r-b6d1y39Cw)
The input for the number of vertices is ignored since it is not used or needed.
The function J takes in the input vertices, V, as a list of tuples/lists. An example function call would be `J([(0,0),(1,3),(1,1),(2,0)])`.
The code assumes that a polygon is defined as most people would define a polygon (made of vertices connected by non-intersecting edges)
## Code explained by line/function
```
from numpy import*
from itertools import*
def J(V):
c,a,X,I=combinations,array,cross,vstack;
```
Normal byte-saving code. Nothing fancy.
```
V=[*map(a,V)];
```
Converting the list of tuples into a list of numpy arrays. This can't be left as a map object because of some stuff that is done later.
```
s=lambda A,B,P:sign(X(B-A,P-A));
```
s takes in three points A,B,P and returns which side of the line connecting AB is point P using the cross product. The two vectors have two elements so numpy treats them as vectors of the form [x,y,0] and returns only the z component. If P is on the "right" of the line AB, s = -1. On the left, s = +1. If P is on the line AB then s = 0.
```
Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);
```
Q takes in two points, v and w, and a set of vertices G. Essentially, this is checking if the line vw places all points in G into the same half of the plane (or onto the line). If that is the case, then it returns True. Otherwise, False. `any(p-v)` is used instead of the more traditional `p==v` because numpy arrays can't be directly compared in that way due to "ambiguity".
```
F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;
```
F takes in Z, a list of vertices of a polygon, and returns the area of that polygon using the [shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula). This doesn't work with polygons whose edges intersect, but those polygons have ill-defined areas anyway.
```
W=list([a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0]));
```
Breaking this down:
`[a([v,w])for v,w in c(V,2)if Q(v,w,V)]` returns a list of 2x2 numpy array the represents the line formed by the points vw, where every combination of two points in the input polygon V gets a chance at being vw, if the line vw places all points in V onto one side of the plane (or on the line). The reason for this is to get a set of lines that forms the boundary of the polygon. Think of it as taking all the vertices that would make the input polygon convex, connecting them with edges, then extending those edges into lines.
The rest of this line is devoted to determining where those lines intersect (if they were extended infinitely far). This is done using [homogenous coordinates](https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Using_homogeneous_coordinates). Another example can be found [in this stackoverflow thread](https://stackoverflow.com/a/42727584/8690613), whose code this is based on.
The reason for this is to determine exactly where could the vertices of the all of the triangles that could envelop the input polygon lie.
```
min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)
```
This one is very simple. For every combination of points v,w in V and then every point in W (the line intersections), first check to see if all three points are collinear using the function `s`. If they're not, then we check to see if all points in V are inside of the triangle formed by vwk. This is done by checking if all of the points in V, also including the three points v,w,k, are all on the same side of the plane when intersected by a line made of two of the points. Since it's a triangle, if all the "third points" are on the same side of the plane as the two points forming a line (for all three combinations of v,w,k), then all points must be inside the triangle or on the edge of it.
Lastly, we take get the area of each triangle that satisfies our conditions and subtract off the area of the input polygon. Then, the minimum area is returned. If there is no minimum area to return (because no triangle exists that satisfies all conditions), then -1 is returned instead.
---
This is my first code golf answer so please let me know if I missed anything major with the question or if there is somewhere bytes can be saved!
] |
[Question]
[
#
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/140854/1326-starting-holdem-combos) and related to [this one](https://codegolf.stackexchange.com/questions/25056/compare-two-poker-hands).
### Background
Badugi [bæduːɡiː] is a low-ball draw-poker variant.
The Pokerstars World Cup Of Online Poker **$1K** event starts within **3** hours and I'll need to know how good my hands are!
The game uses a standard deck of **52** cards of four suits and thirteen ranks. The suits are unordered and shall be labelled `cdhs`; the ranks - ordered from highest `K` to lowest `A` - are `KQJT98765432A`. As such the full deck may be represented as follows (space separated):
```
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 Ac Ad Ah As
```
Each player is dealt **four** cards from the deck, there are four betting rounds with three drawing rounds in-between (a player always has four cards, they have the option of changing 0-4 of their cards with new ones from the dealer on each of the three drawing rounds).
If more than one player is still active after all these rounds there is a showdown, whereupon the strongest hand(s) win the wagered bets.
The game is played low-ball, so the lowest hand wins, and as mentioned above `A` (ace) is low. Furthermore the hand ranking is different from other forms of poker, and can be somewhat confusing for beginners.
The played "hand" is the lowest ranked combination made from the highest number of both "off-suit" (all-different-suits) and "off-rank" (all-different-ranks) cards possible (from the four held cards). That is: if one holds four cards of both distinct suits *and* distinct ranks one has a 4-card hand (called a "badugi"); if one does not have a 4-card hand but does have some set or sets of three cards of both distinct suits *and* distinct ranks one has a 3-card hand (one chooses their best); if one has neither a 4-card hand or a 3-card hand one probably has a 2-card hand, but if not one has a 1-card hand.
* As such the best possible hand is the 4-card hand `4-3-2-A` - the lowest **off-rank** cards of **four different suits**, often termed a "number-1". The weakest possible hand would be the 1-card hand `K` and is only possible by holding exactly `Kc Kd Kh Ks`.
* Note that `4c 3h 2c As` is **not** a "number-1", since the `4c` and `2c` are of the same suit, but it *is* the strongest of the 3-card hands, `3-2-A`, it draws with other `3-2-1`s (like `Kh 3d 2s Ah`) and beats all other 3-card hands but loses to all 4-card hands (which could be as weak as `K-Q-J-T`).
+ The other possible 3-card hand that could be made from `4c 3h 2c As` is `4-3-A`, but that is weaker (higher) so not chosen.
* Similarly `8d 6h 3s 2h` is a 3-card hand played as `8-3-2` - there are two off-rank off-suit combinations of size 3 and `8-3-2` is better (lower) than `8-6-3` since the three (or "trey") is lower than the six.
Comparing hands against one another follows the same logic - any 4-card beats any 3-card, any 3-card beats any 2-card and any 2-card beats any 1-card, while hands of the same number of used cards are compared from their highest rank down to their lowest (for example: `8-4-2` beats `8-5-A` but not any of `8-4-A`, `8-3-2` or `7-6-5`)
### The challenge:
Given two unordered-collections each of four cards, identify the one(s) which win a Badugi showdown (identify both if it is a draw).
The input may be anything reasonable:
* a single string of all eight cards as labelled above (with or without spaces) with the left four being one hand and the right the other (with an optional separator); or a list of characters in the same fashion
* a list of two strings - one per hand, or a list of lists of characters in the same fashion
* two separate strings or list inputs, one per hand
* the cards within the hands may be separated already too (so a list of lists of lists is fine)
Note, however:
* the cards may not be arranged into any order prior to input
* ...and the suits and ranks are fixed as the character labels specified here -
If your language does not support such constructs just suggest something reasonable and ask if it is an acceptable alternative given your languages constraints.
The output should either be
* formatted the same as the input, or a printed representation thereof; or
* be one of three distinct and consistent results (e.g.: `"left"`, `"right"`, `"both"`; or `1`, `2`, `3`; etc.)
Really - so long as it is clear which of the two inputs are being identified it should be fine.
### Test cases
```
input -> output
(notes)
----------------------------------------------------------------------------
3c 2s 4d Ah - As 3h 2d 4h -> 3c 2s 4d Ah
(4-card 4-3-2-A beats 3-card 3-2-A)
3c 2s 4d Ah - As 2c 3d 4h -> 3c 2s 4d Ah - As 2c 3d 4h
(4-card 4-3-2-A draws with 4-card 4-3-2-A)
2d Ac 4h 3c - Kh Ad 9s 2c -> Kh Ad 9s 2c
(3-card 4-2-A loses to 4-card K-9-2-A)
Kc Tc Qc Jc - Ac Ad Ah As -> Ac Ad Ah As
(1-card T loses to 1-card A)
9c 9h Qc Qh - Qs Kh Jh Kd -> Qs Kh Jh Kd
(2-card Q-9 loses to 3-card K-Q-J)
2d 5h 7c 5s - 2h 3c 8d 6c -> 2d 5h 7c 5s
(3-card 7-5-2 beats 3-card 8-3-2)
3s 6c 2d Js - 6h Jd 3c 2s -> 6h Jd 3c 2s
(3-card 6-3-2 loses to 4-card J-6-3-2)
Ah 6d 4d Ac - 3h 2c 3s 2s -> 3h 2c 3s 2s
(2-card 4-A loses to 2-card 3-2)
2h 8h 6h 4h - 6d 2d 5d 8d -> 2h 8h 6h 4h - 6d 2d 5d 8d
(1-card 2 = 1-card 2)
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per-language, and the shortest code overall wins. Don't let golfing languages put you off submitting in other languages, and ...have fun!
[Answer]
# [Perl 6](https://perl6.org), 128 bytes
```
{.map({.combinations(1..4).grep({!.join.comb.repeated}).map({-$_,$_».trans('ATK'=>'1BZ')».ord.sort(-*)}).min}).minpairs».key}
```
[Try it online!](https://tio.run/##dZLNTsJAFIXX8BSHpEmnpkwshQrhz7owkZoYElYSQupMsVWhONOYEMKTufPF8E6JRmucxSzu/c65PzPbRL0Ex/UO1grD456v4y3bc5GvH7JNXGT5RjOP87bDH1VCmQZ/yrNNmecUSOIikQfnpGpaS9dafrzzQsUks8NZZA9Htnd1bzsUzZXkOlcFa545RpJtTvc2zpSm/HOyO5hGLgsMweo1xga@QEujLRGmIxeDUMNP0ZJopyPHBTt3Hcf9B2wJ@D9AeF8oyUNBCfjCoFGKUKJnBCXqfXtGAjOBqcCkBEkUGn@EugL2BHqpAadl8akGmU5SRLICUulOiguBjjZgy/SArkQgquNoiplBJyUYkJ1EOWPFkdoJZDl32aPZDs2t/4JUq0tsajZiHKVx70iq/mtBTr@@ypV5gn29Zj6ForewVozPzxeUq@l4B0bB5PUNfO4tMB7DvotAx0ajAfs6vLmFTZaW6tcPx08 "Perl 6 – Try It Online")
Takes a list of hands (also more than two) which are lists of cards which are strings like `Kc`. Returns the indices of the hands with the lowest score. For two hands this is `(0)` if the first hand wins, `(1)` if the second hand wins, and `(0, 1)` for a draw.
Explained:
```
{
# Map hands to best "played hand".
.map({
# Generate all combinations of length 1 to 4.
.combinations(1..4)
# Remove hands with repeated characters.
.grep({!.join.comb.repeated})
# Map to a cmp-arable representation. This works because
# lists are compared element-wise. Translate some characters
# so that ASCII order works. Sort in reverse order so that
# element-wise comparison will go from highest to lowest.
.map({ -$_, $_».trans('ATK'=>'1BZ')».ord.sort(-*) })
# Find best hand.
.min
})
# Return indices of lowest scoring hands. It's a shame that
# `minpairs` doesn't support a filter like `min`.
.minpairs».key
}
```
[Answer]
# JavaScript (ES6), ~~209~~ ~~202~~ ~~192~~ ~~182~~ 181 bytes
*Saved 7 bytes thanks to @Neil*
Takes input as an array of arrays of strings. Returns `true` if the first hand wins, `false` if the second hand wins, or `2` in the event of a tie.
```
a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b)
```
### Test cases
```
let f =
a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b)
console.log(f([["3c","2s","4d","Ah"], ["As","3h","2d","4h"]])) // true (1st hand wins)
console.log(f([["3c","2s","4d","Ah"], ["As","2c","3d","4h"]])) // 2 (tie)
console.log(f([["2d","Ac","4h","3c"], ["Kh","Ad","9s","2c"]])) // false (2nd hand wins)
console.log(f([["Kc","Tc","Qc","Jc"], ["Ac","Ad","Ah","As"]])) // false (2nd hand wins)
console.log(f([["9c","9h","Qc","Qh"], ["Qs","Kh","Jh","Kd"]])) // false (2nd hand wins)
console.log(f([["2d","5h","7c","5s"], ["2h","3c","8d","6c"]])) // true (1st hand wins)
console.log(f([["3s","6c","2d","Js"], ["6h","Jd","3c","2s"]])) // false (2nd hand wins)
console.log(f([["Ah","6d","4d","Ac"], ["3h","2c","3s","2s"]])) // false (2nd hand wins)
console.log(f([["2h","8h","6h","4h"], ["6d","2d","5d","8d"]])) // 2 (tie)
```
### How?
```
a => (
// store the best combination for both hands in a and b respectively
[a, b] = a.map(a =>
// compute the powerset of the hand
a.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]])
// for each entry:
.map(a =>
// invalidate entries that have at least 2 cards of same rank or same value
!/(\w).*\1/.test(a) *
// the score of valid entries is based on their length ...
a.length +
// ... and their card values, from highest to lowest
// (we map 'KQJT98765432A' to [10 - 22], so that the resulting
// strings can be safely sorted in lexicographical order)
a.map(a => 'KQJT98765432A'.search(a[0]) + 10).sort()
)
// keep the best one
.sort().pop()
),
// compare a with b
a == b ? 2 : a > b
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẎŒQȦ;L;Ṗ€Ṣ$
“A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$
```
A monadic link taking a list of two lists of characters
- each being a space separated representation of the hand (e.g. `"Ac 2d 4s 3h"`)
returning a list of two numbers identifying the winner(s) with `1` and any loser with `0`
- i.e. `[1, 0]` = left wins; `[0, 1]` = right wins; `[1, 1]` = draw.
**[Try it online!](https://tio.run/##y0rNyan8///hrr6jkwJPLLP2sX64c9qjpjUPdy5S4XrUMMdR2zsyxPVRw9zKhzs2@fsdnRRwuB0i/XDnqkNbgcxHjXvAAg0q////j1YySlEwzVAwT1YwLVbSUVAyylAwTlawSFEwS1aKBQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##bY@xS8NAFMb3/hUfoZsVNGlqY6cbXBJRA11KyXQnHKHbTd2ii5tDBnGoi0MHcRIEI50qgf4bl38kvndG6uBw8O59v/d97@XXi8Wybe3nfV2mu/XkfGKrh@b21VbP/V5TrMRBMpueNcXT0n68XV7U5dXX3Y9sq5ftO5XNzcY1in5bb5yY0zverlkrVjgETdelrR6pceTaeSedsjRr2/ncCyR8g6GC0N4AnjAINHyFofayQQ//Ab5E8AcgWEj6IpAMJBpCIWKsAxKJqUQqETuAYMFuEKYDIolIM5C6iNSATGKNRO0jQo0TidAw4HMWxgqj34jAUM1rxw4Y0biC27wDKG6k3BVuB76RrjB7gDzHxGi@ix0Uu4WKUrws@wY "Jelly – Try It Online").
### How?
```
ẎŒQȦ;L;Ṗ€Ṣ$ - Link 1, sortKey: list of lists of numbers representing some cards (see Main)
Ẏ - flatten into a single list of numbers
ŒQ - distinct sieve (1 at first occurrence of anything, 0 at the rest)
Ȧ - Any & All? zero if any are 0 or if empty; 1 otherwise (i.e. playable hand?)
L - length of input (number of cards in the hand)
; - concatenate
$ - last two links as a monad:
Ṗ€ - pop each (get just the rank portions)
Ṣ - sort (Main's translation & negation of ordinals ensures A>2>3>...>Q>K)
; - concatenate (now we have [isPlayable; nCards; [lowToHighCards]])
“A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$ - Main link: list of lists of characters, hands
µ€ - for €ach of the two hands:
“A+KYTE” - literal list of characters "A+KYTE" (compressing doesn't help - lower case would be “£Ḅṁ⁽>» though -- I'll stick with kyte though it's kind of nice.)
y - translate - change As to +s, Ks to Ys and Ts to Es
- note the ranks are now in ordinal order:
- +<2<3<4<5<6<7<8<9<E<J<Q<Y
Ḳ - split at spaces - split the four cards up
O - to ordinals '+'->43, '2'->50, ...
N - negate - effectively reverse the ordering
ŒP - power-set - get all combinations of 0 to 4 cards inclusive
Ç€ - call the last link (1) as a monad for €ach such selection
Ṣ - sort these keys
Ṫ - tail - get (one of) the maximal keys
- (the key of a best, playable selection)
$ - last two links as a monad:
Ṁ - maximum (the better of the two best, playable selection keys)
⁼€ - equals? for €ach (1 if the hand is a winner, 0 if not)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~207~~ 204 bytes
```
lambda i,j:L(h(i))-L(h(j))if L(h(i))!=L(h(j))else(h(i)<h(j))-(h(i)>h(j))
L=len
def h(l):s=set();return[x[0]for x in sorted(y.translate({65:49,75:90,84:65})for y in l)if not(s&set(x)or s.update(*x))][::-1]
```
[Try it online!](https://tio.run/##jVI9b4MwEN35Fe5S7MqJUr4S3FKJNekSqRtloLERRAQoJhJR1d@e4rNJmk5leLbv3bt7Ptye@qKp3XMevZ@r7PDBM1TSPXvFBS4Jmal1T0iZIxO5i0xIVFJA6BmOM9i/wN56jSpRW1zkqMAVYTKSosfkqRP9sauTIVmkedOhAZU1kk3XC45P877LalllvcBfgc@8kC59Fi7oymOB/01U/knlV8pL3fRY3quiAxkJOT@2XCkfBkLShLHZY3oWQ3ZoKyFRhBKc2O7Opsh2pEKPK4wLO6UosWOIuQXwwHgjQ6j1D5UDvPtHpavEOxNVGTut2sApBj6cKhjVBvLfALeAa6PSleKpv0I5qULgwuKq2hqHW6ivO64BN/zWoQ/RJah8qVXO5HfEFWQFF4euNOfLpNZGFegu/Kp1Lg6144D/mqG5l5m5nqG8VWkfK60tpvlCL37t73PjMyWpZalH0tJP9Uymv88sNH5tV9Y9HimKcrUQcv4B "Python 3 – Try It Online")
*Saved 3 bytes thanks to Jonathan Frech*
Returns `1` if the first hand wins, `-1` if the second hand wins and `0` in case of a draw.
The function `h` computes a list that represents the hand.
The lambda compares two representations of hand. I think it might be shortened, but I wanted to return only three values and didn't find a simpler way to do comparison.
] |
[Question]
[
This year my age is a prime number, and so is this year. This conjunction will repeat in 10 years and again in 12. If I live to 100, I will lived exactly 11 years in which my age and the year are both prime. My condolences to those of you born in odd-numbered years, who will experience this phenomenon at most once if at all.
As it turns out, if I tell you that the consecutive gaps between years in which my age and the year were, are, or will be both primes are 4, 2, 4, 14, 10, 2, 10, 14, 16, and 14, then that is enough information for you to tell me exactly which year I was born.
# The Challenge
This challenge is to write a program or function that, given a list of even numbers, each representing gaps between consecutive prime-age prime-year conjunctions, print or return all years between 1AD and 2100AD inclusive such that a person born in that year (and living no longer than 100 years) would have exactly that sequence of gaps between prime-year prime-age conjuctions (i.e. *no* other such conjunctions)
Or, in more mathematical terms, given a list \$a\$, print or return all \$x\$ between 1 and 2100 such that there exists a \$0<b\le100\$ such that \$x+b\$ is prime, \$b\$ is prime, and \$x+b+\sum^n\_{i=1}a\_i\$ and \$b+\sum^n\_{i=1}a\_i\$ are both prime for all \$n\$ up to the length of \$a\$ (where the latter sum is guaranteed to be less than 100).
If there are no such years in that range, you may print or return anything falsy or nothing at all.
I/O is flexible: just be able to take a list of numbers as input and produce a list of numbers as output.
# Examples
```
[4,2,4,14,10,2,10,14,16,14] => [1986]
(6,4,2,4) => ()
6,4,2,4,8,6,10,12,14,10,6 => 1980
4;4 => (No output)
[]...................................=> (A list containing every odd number between 1 and 2099, plus the numbers 1136, 1732, and 1762)
```
# Scoring
Shortest program, in bytes, wins.
Bonus: I will create a bounty to reward the shortest answer that produces the correct output using an algorithm which has an asymptotic worst case running time strictly better than \$O(YA+A^2)\$ where Y is the maximum birth year and A is the maximum age. (Y and A are not inputs to your program or function, but pretend they are for the purposes of determining if your algorithm qualifies.) If you wish to compete in the bonus challenge, it is up to you to convince me your program or function meets the requirements. You may assume that all built-ins use the asymptotically fastest known classical algorithm to achieve their results (e.g. generates primes with a Sieve of Atkin rather than a Sieve of Eratosthenes). Yes, it is possible to receive this bounty even if you win the regular challenge.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
2101GтLDpÏN+DpÏ¥Q–
```
[Try it online!](https://tio.run/nexus/05ab1e#@29kaGDofrHJx6XgcL@fNog8tDTwUcPk//@jTXSMdEx0DIHIAMgCEiCmGZCMBQA "05AB1E – TIO Nexus")
**Explanation**
```
2101G # for each N in [1 ... 2100]
тL # push the range [1 ... 100]
DpÏ # keep only numbers that are prime
N+ # add N to each
DpÏ # keep only numbers that are prime
¥ # calculate delta's
Q– # print N if the resulting list is equal to input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
97ÆR+⁸ÆPÐfI⁼
⁽¥cçÐf
```
[Try it online!](https://tio.run/nexus/jelly#@29pfrgtSPtR447DbQGHJ6R5Pmrcw/Woce@hpcmHlwP5/w@3P2pa4/7/fzSXQrSJjpGOiY4hEBkAWUACxDQDkrE6QFkzHbA8MlvHQscMrM4IqssMLGsCVRXLFQsA "Jelly – TIO Nexus")
### How it works
```
⁽¥cçÐf Main link. Argument: A (array of integers)
⁽¥c Yield 2100.
çÐf Apply the helper link to each n in [1, ..., 2100], with right
argument A. Yield all values of n that return 1.
97ÆR+⁸ÆPÐfI⁼ Helper link. Left argument: n. Right argument: A
97ÆR Prime range; yield all prime numbers in [1, ..., 97].
+⁸ Add n to each of these primes.
ÆPDf Filter by primality, keeping only prime sums.
I Increments; compute all forward differences.
⁼ Return 1 if the result and A are equal, 0 if not.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
fq.+f&P_+TYP_YU100QU2100
```
[Try it online!](https://tio.run/nexus/pyth#@59WqKedphYQrx0SGRAfGWpoYBAYagQk//@PNtEx0jHRMQQiAyALSICYZkAyFgA "Pyth – TIO Nexus")
I feel like this can be golfed down quite a bit, but here it is for now.
] |
[Question]
[
Long time ago, when I was spending more time playing RPG, one of the issues what some players had, was to track party movement and to draw proper map.
So I come with idea, to check how you guys come deal with this issue.
Task is to write a function, which takes as input parameter list of directions (passed as structure of your choice) `^v<>`, display map of dungeon.
In example for input: `>>>vvv<<<^^^` output will be:
```
+----+ +----+
| | |>>>v|
| ++ | |^++v|
| ++ | because |^++v|
| | |^<<<|
+----+ +----+
```
Testcases
```
>>>>>>vvvvv<<<<^^^>>v
+-------+
| |
+-+---+ |
| | |
| + | |
| +-+ |
| |
+-----+
^^^^^vvv<<<^^vv>>>>>>>>vv>><<^^^^v>>>>v^<^
+-+
+-+| | +-++-+
| || | | ++ ++
| ++ +-+ |
| +-+ |
+--+ +-+ +-+-+
| | | |
+-+ +---+
```
As it is golf code challenge, shortest code wins.
Happy golfing.
**EDIT**
Sorry for late edit, I didn't have much time recently.
Map is generated based on movement. It should contain only corridors which were visited during walk. Hence creating one big room won't be a valid answer.
There are three valid symbols in the map:
* `|` vertical wall
* `|` horizontal wall
* `+` intersection of vertical and horizontal wall.
Maximum length of the path is 255 character (but if you can, do not limit yourself).
More test cases:
```
><><><><
+--+
| |
+--+
>^<v
+--+
| |
| |
+--+
```
I hope now everything is clear.
[Answer]
## Javascript (ES6), ~~261~~ ~~254~~ 243 bytes
```
s=>{v=Array(w=32);p=526;b=n=>v[n>>5]&(1<<(n&31));B=(n,i)=>b(p+n)|b(p-n)?i:0;[...0+s].map(c=>v[(p+=[0,1,-1,w,-w]['0><v^'.indexOf(c)])>>5]|=1<<(p&31));for(z='',p=0;p<w*w;z+=' |-+'[b(p)?0:B(1,1)|B(w,2)||B(31,3)|B(33,3)],p++%w||(z+=`
`));return z}
```
### **[JSFiddle](https://jsfiddle.net/Arnauld/pe9kduk2/3/)**
[Answer]
# C, 246 bytes
```
n,y,*g,*p;main(c,v)char**v;{for(n=c*2+3,g=calloc(n*n,8),p=g+(n+1)*(c+1);c--;y=*v[c],p-=(y>70?n:1)*(y%5%4?-1:1))*p=1;for(y=n-1;--y;)for(c=n-1;c--;putchar(c?" |-++|-+"[*p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4]:10))p=g+y*n+c;}
```
Takes input as separate characters, for example:
```
./mapper '>' '>' '>' 'v' 'v' 'v' '<' '<' '<' '^' '^' '^'
```
Or more conveniently, this (intentionally unquoted!) format:
```
./mapper $(echo '>>>vvv<<<^^^' | fold -w1)
```
Or for (pretty inefficient) random input:
```
./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 10 | fold -w1)
```
And finally, using `awk` to crop the result means we can get much bigger:
```
./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 500 | fold -w1) | awk '/[^ ]/{l=match($0,"\\+");if(l&&(l<L||!L))L=l;v[i++]=$0}END{for(;j<i;){l=v[j++];print substr(l,L,match(l," *$")-L)}}'
```
---
```
+-----+
| |
| +-+ +-----+
| |+-+ |
++ +| ++
| | |
| + +-+
+--+ |
+-+ +--+
| ++ |
+-+ +-++ +-+
++ |+--+ |
+-+ | | ++ |
++ | ++ + +--+ ++
| | +---| |
| | ++ +---+
++ |-+ | |
| | +--+-+ |
| + + |
| +--+
+--------+
```
---
Outputs to stdout. Uses the fact that padding is allowed around the map (produces a map which has edge length 2\*n+1, putting the final position in the middle).
### Breakdown
This works by looping over the arguments in reverse and moving in reverse. It actually uses the fact that arg 0 is the program name; it doesn't matter what the name is, but it allows us to visit both the initial and last cell (as well as all cells in-between) without needing special handling.
```
n, // Size of internal grid
y, // Loop counter / current character
*g, // Internal grid memory
*p; // Current working pointer
main(c,v)char**v;{ // K&R style function declaration
for( // Step 1: identify visited cells
n=c*2+3, // Set output grid size
g=calloc(n*n,8), // Allocate map storage space
p=g+(n+1)*(c+1); // Start at centre
c--; // Loop over directions in reverse
y=*v[c], // Get current direction
p-=(y>70?n:1)*(y%5%4?-1:1) // Move in reverse
)*p=1; // Mark cell visited
for(y=n-1;--y;) // For each row (except edges)
for(c=n-1;c--; // For each column (except edges, +1 for \n)
putchar(c?" |-++|-+"[ // Print wall using lookup table
*p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4
]:10) // Or newline
)p=g+y*n+c; // Set current cell (happens first)
}
```
] |
[Question]
[
This is Bub. Bub is a soccer player. However, he's not a very good one. He still can't kick the ball to the net! (If you haven't noticed, `@` is the ball.
```
_____
| \
O | \
\|/ | \
| | net \
/ ─ @ |_________\
```
To help develop his skills, he's developed a system to help evaluate his performance when he kicks the ball. He's called it the "10 point system."
However, he doesn't know what he needs to do to achieve *x* number of points. You need to help him visualize where the ball will be, so that he can set an expectation of how many points he wants to get. There are 10 points per round that he can achieve.
Therefore, this is your challenge.
Given a number *x*, the number of points Bub gets, output the location of the ball on the field. Here are some helpful markers:
* Bub is exactly 50 spaces away from the net.
* For each point that Bub gets, the ball moves 5 spaces closer to the net. Therefore, if Bub gets 3 points, the ball is 35 spaces away from the net.
* For every 3 points that Bub gets, the ball begins to move in the air! It moves one space up.
* If the number of points Bub gets would move the ball behind the net, you can put the ball anywhere inside the net.
Remember, you need to draw Bub, the ball, and the net.
To get you started, here's an example:
### Number of Points: 5
```
_____
| \
O | \
\|/ | \
| @ | \
/ ─ |_________\
```
Standard rules apply. Code with the lowest number of bytes wins! Happy golfing!
[Answer]
# Pyth, ~~106~~ 91 bytes
Run-length encoding, followed by internal encoding.
Hexdump:
```
0000000: 4a 63 72 58 2e 22 30 41 01 b6 07 31 11 af 55 c5 JcrX."0A...1..U.
0000010: 16 6f 93 4f ea 90 6b 39 f6 e0 dc 81 43 9d 01 f7 .o.O..k9....C...
0000020: 36 93 ee 4c c8 fa a5 28 70 22 6d 43 2b 35 38 64 6..L...(p"mC+58d
0000030: 38 22 0a 20 2f 4f 5c 5c 5f 7c 2d 22 39 62 6a 58 8". /O\\_|-"9bjX
0000040: 4a 4b 2d 35 2f 68 53 2c 54 51 33 58 40 4a 4b 68 JK-5/hS,TQ3X@JKh
0000050: 53 2c 35 38 2b 34 2a 35 51 5c 40 S,58+4*5Q\@
```
[Try it online!](http://pyth.herokuapp.com/?code=JcrX.%220A%01%C2%B6%071%11%C2%AFU%C3%85%16o%C2%93O%C3%AA%C2%90k9%C3%B6%C3%A0%C3%9C%C2%81C%C2%9D%01%C3%B76%C2%93%C3%AEL%C3%88%C3%BA%C2%A5%28p%22mC%2B58d8%22%0A+%2FO%5C%5C_%7C%E2%94%80%229bjXJK-5%2FhS%2CTQ3X%40JKhS%2C58%2B4%2a5Q%5C%40&input=12&debug=0)
Replace the Unicode character `─` (U+2500) as a single hyphen.
[Answer]
# JavaScript (ES6), 189
```
f=n=>" o \\|/ | / -".match(/.../g).map((v,r)=>(v=[...v+' '.repeat(50)+'| '[+!r]+' _'[+(!r|r>4)].repeat(r+4)+'\\_'[+!r]],y-r?0:v[x]='@',v.join``),n<11?0:n=11,x=3+n*5,y=5-(n/3|0)).join`
`
```
**Test**
```
f=n=>" o \\|/ | / -".match(/.../g).map((v,r)=>(v=[...v+' '.repeat(50)+'| '[+!r]+' _'[+(!r|r>4)].repeat(r+4)+'\\_'[+!r]],y-r?0:v[x]='@',v.join``),n<11?0:n=11,x=3+n*5,y=5-(n/3|0)).join`
`
var n=0
setInterval(function(){
N.textContent=n,O.textContent=f(n),n=(n+1)&15
},1000)
```
```
<pre id=O></pre><span id=N></span>
```
] |
[Question]
[
This is similar to simplifying fractions, but with Dates!
The input of your program must be of the form `mm/dd`
For example
```
3/4 //March 4
12/15 //December 15
1/1 // January 1
```
We assume that the input will be valid such that the months have these numbers of days in them:
```
January 31
February 28
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
```
Your program's job is to take the assumed valid input, and iteratively (or recursively) simplify the date, and at each iteration (including the 0th), output the date with the full name of the month as written above.
For example:
Given an input of:
```
12/18
```
Would output
```
December 18
June 9
February 3
```
An input that is already simplified only outputs itself:
```
11/17
```
Outputs:
```
November 17
```
The month names cannot come from a function in your language. The strings can be obfuscated, computed, however you like, but you cannot use a standard function like GetMonthString(4) or something, you either have to write that function, or find a way to output the month names as described.
I cannot think of any cases where the simplified date produces an illegal date, but if ever you produce an illegal date along the way, output:
```
Illegal Date
```
But if you are sure this cannot happen, you do not need to have code covering this case. The dates outputted just always need to be valid according to what was described above (it goes without saying that months and days start at 1).
The algorithm:
At each iteration you divide by the smallest number that divides numerator and denominator.
That is, you find all the numbers such that, dividing both the numerator and denominator by this number produces a new numerator and denominator that are both integers (common factors). Select the smallest one and individually divide the numerator and denominator to produce a new fraction.
If the only number you can divide by is 1, then you have simplified as much as possible and you stop.
I hope this is clear.
Any language is allowed. This is Code Golf, shortest code wins!
[Answer]
# Pyth - ~~116~~ 87 bytes
```
jm++@rR3c."ayÖèÈÒ+J÷z4wëÝ~ñ!Õ¥´{mCØóy|å²z¼qP?ë"\qhd;ed.u/RYNPiFKsMcz\/K
```
[Test Suite](http://pyth.herokuapp.com/?code=jm%2B%2B%40rR3c.%22ay%C3%96%C2%96%C3%A8%1C%C3%88%C2%85%C2%98%C3%92%C2%9C%2B%C2%8B%C2%8E%1BJ%C3%B7z4w%C3%AB%C3%9D%C2%92%0B%7E%C3%B1%1A%17%21%7F%C3%95%04%C2%A5%C2%B4%7B%1FmC%C3%98%C3%B3y%7C%C3%A5%C2%B2z%C2%BC%C2%86qP%3F%C3%AB%22%5Cqhd%3Bed.u%2FRYNPiFKsMcz%5C%2FK&test_suite=1&test_suite_input=12%2F18%0A11%2F17&debug=0).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 59 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”/VµÆDf/2ị:@µÐĿị1¦€“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»ṣ⁶¤j€⁶j⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmj4oCdL1bCtcOGRGYvMuG7izpAwrXDkMS_4buLMcKm4oKs4oCcwqPhuaJ04bqS4oG94bq5wr1N4biKeMmyyKfEl0HhuYUgyZNh4bm-wqVEwrnhuYDhuo9EOMO34bmsw5jCu-G5o-KBtsKkauKCrOKBtmrigbc&input=&args=MTIvMTg)
### How it works
```
ṣ”/VµÆDf/2ị:@µÐĿị1¦€“...»ṣ⁶¤j€⁶j⁷ Main link. Argument: mm/dd
ṣ”/ Split at slashes.
V Eval each chunk, yielding [m, d] (integers).
µ Begin a new, monadic chain. Argument: [m, d]
µÐĿ Execute the chain to the left until the results
are no longer unique. Yield the list of all
intermediate results.
ÆD Compute the divisors of each number.
f/ Intersect them.
2ị Select the one at index 2. If there is only
one divisor, ị wraps around and selects 1.
:@ Divide [m, d] by this common divisor.
¤ Combine the links to the left into a chain.
“...» Yield the month's name, space-separated.
ṣ⁶ Split at spaces.
€ For each pair...
ị index into the month's names...
1¦ for the first element.
j⁶€ Join each pair, separating by spaces.
j⁷ Join, separating by linefeeds.
```
[Answer]
# TSQL 296 bytes
Not being allowed to use the standard datename cost me alot of bytes, however to save a few bytes, I used the first 3 characters of the default date description(with the format mon dd yyyy hh:miAM (or PM)) and added the rest of the month name.
Golfed:
```
use master
DECLARE @ varchar(5) = '12/2'
DECLARE @m int=month('2000/'+@),@d INT=day('2000/'+@)WHILE @m>0BEGIN PRINT left(dateadd(d,@m*29,0),3)+choose(@m,'uary','uary','ch','il','','e','y','ust','tember','ober','ember','ember')+' '+LEFT(@d,2)SELECT @m/=min(n),@d/=min(n)FROM(SELECT number FROM spt_values)x(n)WHERE @m%n+@d%n=0 and n>1 END
```
[Try it online](https://data.stackexchange.com/stackoverflow/query/500367/simplify-a-date)
Ungolfed:
```
use master
DECLARE @ varchar(5) = '12/2'
DECLARE @m int=month('2000/'+@),@d INT=day('2000/'+@)
WHILE @m>0
BEGIN
PRINT
left(dateadd(d,@m*29,0),3)
+choose(@m,'uary','uary','ch','il','','e','y','ust',
'tember','ober','ember','ember')+' '+LEFT(@d,2)
SELECT @m/=min(n),@d/=min(n)
FROM
(
SELECT number
FROM spt_values
)x(n)
WHERE
@m%n+@d%n=0
and n>1
END
```
] |
[Question]
[
There is [a great story to tell](http://www.radiolab.org/story/294349-what-it-about-bees-and-hexagons/) about regular hexagons found for example in honeycombs. But this busy bee needs your help in telling him which point is inside or outside his honeypot. So, given a regular hexagon as pictured below, centered at the origin and with edge size l, determine if a set of coordinates (x,y) are inside, exactly on the edge or outside of my regular hexagon.
[](https://i.stack.imgur.com/bK746.png)
## Input, output and rules
The rules are:
* Input and output methods follow [the default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?s=5%7C0.0000).
* Input consists of three *integers*: `x,y,l`.
* `x` and `y` are of any convenient signed integer format. `l` is positive (never 0).
* Your program must output/return a `1` if the point `(x,y)` is inside the regular hexagon, `-1` if it's outside or `0` if it's exactly on the edge.
* This is a code-golf, so shortest code wins. In case of a tie, the earliest post wins.
* For output to stdout: leading/trailing spaces or newlines in the output are permitted.
* Standard loopholes apply.
## Test cases
Here are some test cases:
```
0,0,1 --> 1
0,1,1 --> -1
0,-1,1 --> -1
1,0,1 --> 0
-1,0,1 --> 0
-1,-1,1 --> -1
1,1,1 --> -1
-2,-3,4 --> 1
32,45,58 --> 1
99,97,155 --> -1
123,135,201 --> 1
```
[Answer]
# JavaScript (ES6) 77 ~~83~~
```
(a,b,l,h=Math.sqrt(3)*l,x=a<0?-a:a,y=b<0?-b:b)=>y|x!=l?2*y<h&x/l+y/h<1?1:-1:0
```
**Test**
```
f=(a,b,l,h=Math.sqrt(3)*l,x=a<0?-a:a,y=b<0?-b:b)=>y|x!=l?2*y<h&x/l+y/h<1?1:-1:0
// TEST
function go() {
C.width=400;C.height=300;
var l=+I.value, x,y, cols={0:'#ff0',1:'#0f0','-1':'#888'},
ctx = C.getContext("2d")
ctx.translate(200,150)
ctx.strokeStyle='#000'
ctx.lineWidth=1;
ctx.beginPath();
ctx.moveTo(0,-150);ctx.lineTo(0,150);ctx.moveTo(-200,0);ctx.lineTo(200,0);
ctx.stroke();
ctx.strokeStyle='#f00'
ctx.beginPath();
ctx.moveTo(l*10,0);ctx.lineTo(l*5,l*Math.sqrt(3)*5);ctx.lineTo(-l*5,l*Math.sqrt(3)*5)
ctx.lineTo(-l*10,0);ctx.lineTo(-l*5,-l*Math.sqrt(3)*5);ctx.lineTo(l*5,-l*Math.sqrt(3)*5)
ctx.closePath();
ctx.stroke();
for(y=-14;y<15;y++)
for(x=-19;x<20;x++) {
ctx.beginPath();
ctx.moveTo(x*10,y*10-3);ctx.lineTo(x*10,y*10+3);
ctx.moveTo(x*10-3,y*10);ctx.lineTo(x*10+3,y*10);
ctx.strokeStyle=cols[f(x,y,l)]
ctx.stroke()
}
}
go()
```
```
#C {
border: 1px solid #000
}
```
```
<b>L</b> <input id=I value=15><button onclick="go()">GO</button><br>
<canvas id=C width=400 height=300></canvas>
```
[Answer]
**Ruby, ~~150~~ ~~145~~ ~~137~~ ~~127~~ ~~125~~ ~~106~~ ~~88~~ 76 bytes**
**76 bytes**
```
->(x,y,l){x,y,t=x.abs,y.abs,3**0.5;d=t*l;z=d-t*x-y;2*y>d ?-1:2*x<l ?1:z<=>0}
```
Changed triple comparison to a rocket.
**88 bytes**
```
->(x,y,l){x,y,t=x.abs,y.abs,3**0.5;d=t*l;z=d-t*x-y;2*y>d ?-1:2*x<l ?1:z==0 ?0:0<z ?1:-1}
```
Remove the y equal to apothem test for points on the hexagon, because for integers, that can never be true.
**106 bytes:**
```
->(x,y,l){x,y,t=x.abs,y.abs,3**0.5;d=t*l;z=d-t*x-y;2*y==d&&2*x<=l ?0:2*y>d ?-1:2*x<l ?1:z==0 ?0:0<z ?1:-1}
```
Poster suggested not using epsilon, so replaced epsilon with zero and rearranged, removed an abs, etc.
**125 bytes:**
```
->(x,y,l){x,y,t,e=x.abs,y.abs,3**0.5,1e-9;d=t*l;z=d-t*x-y;(2*y-d).abs<=e&&2*x<=l ?0:2*y>d ?-1:2*x<l ?1:z.abs<=e ?0:0<z ?1:-1}
```
Incorporate y into definition of z and remove some parentheses.
**127 bytes:**
```
->(x,y,l){x,y,t,e=x.abs,y.abs,3**0.5,1e-9;d=t*l;z=d-t*x;(2*y-d).abs<=e&&2*x<=l ?0:2*y>d ?-1:2*x<l ?1:(z-y).abs<=e ?0:y<z ?1:-1}
```
Rearranged terms to avoid necessity of to\_f cast. Use d (double the apothem) instead of a (the apothem). Combine multiple assignments.
**137 bytes:**
```
->(x,y,l){x=x.abs.to_f;y=y.abs.to_f;a=3**0.5*l/2;e=1e-9;z=2*a*(1-x/l);(y-a).abs<=e&&2*x<=l ?0:y>a ?-1:2*x<l ?1:(z-y).abs<=e ?0:y<z ?1:-1}
```
Inlined 'c'.
**150 bytes:**
```
->(x,y,l){c=l/2.0;x=x.abs.to_f;y=y.abs.to_f;a=3**0.5*l/2;e=1e-10;z=2*a*(1-x/l);(y-a).abs<=e&&x<=c ?0:(y>a ?-1:(x<c ?1:((z-y).abs<=e ?0:(y<z ?1:-1))))}
```
This works for integers or floats! The epsilon test is so that points within round off error of being on the edge are correctly identified.
The absolute values move everything into quadrant one.
The value 'a' is the apothem distance (the y-intercept of the hexagon).
The value 'c' is the x-value of the upper right corner of the hexagon.
The value 'z' is to see if the point is above or below the slant line from the corner to the x-intercept.
**Ungolfed:**
```
hex = ->(x,y,l){
c = l/2.0;
x = x.abs.to_f;
y = y.abs.to_f;
a = 3**0.5 * l / 2;
e = 1e-10;
z = 2*a*(1 - x/l);
if (y-a).abs <= e && x <= c then 0
elsif (y>a) then -1
elsif (x<c) then 1
elsif (z-y).abs <= e then 0
elsif y < z then 1
else -1
end
}
```
**Test**
```
hex = ->(x,y,l){x,y,t=x.abs,y.abs,3**0.5;d=t*l;z=d-t*x-y;2*y>d ?-1:2*x<l ?1:z<=>0}
cases = [
[0,0,1,1],
[0,1,1,-1],
[0,-1,1,-1],
[1,0,1,0],
[-1,0,1,0],
[-1,-1,1,-1],
[1,1,1,-1],
[-2,-3,4,1],
[32,45,58,1],
[99,97,155,-1],
[123,135,201,1]
]
cases.each { |test|
expected = test[3]
actual = hex.call(test[0],test[1],test[2])
status = expected == actual ? "PASS" : "FAIL";
p "#{status}. #(x,y) L = (#{test[0]},#{test[1]}) #{test[2]} Expects #{expected}. Actual #{actual}"
}
"Done!"
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~29~~ 25 bytes
```
3X^/Eh|-IG2G-IX^*1G-hZSX<
```
Inputs are `y`, `x`, `l` in that order.
[**Try it online!**](http://matl.tryitonline.net/#code=M1heL0VofC1JRzJHLUlYXioxRy1oWlNYPA&input=NDUKMzIKNTg)
[Answer]
# Julia, ~~65~~ 58 bytes
```
f(x,l)=(t=maxabs(x/l*[[0 1 1];[2 1 -1]/3^.5]);(t<1)-(t>1))
```
`x` is a row vector `[x y]`. Call like this: `f([0 0],1)`.
[Answer]
## Python 2, 89 bytes
almost the same solution as Julia answer but we can use operation on vector without numpy
```
lambda x,y,L,K=3**0.5/2.:cmp(K*L,max([abs(x*i+y*j)for i,j in[[K,1/2.],[0,1],[-K,1/2.]]]))
```
## Results
```
>>> f(0,0,1)
1
>>> f(32,45,58)
1
>>> f(99,97,155)
-1
>>> f(-1,0,1)
0
>>> [f(0,0,1)== 1,f(0,1,1)== -1,f(0,-1,1)== -1,f(1,0,1)== 0,f(-1,0,1)== 0,f(-1,-1,1)== -1,f(1,1,1)== -1,f(-2,-3,4)== 1,f(32,45,58)== 1,f(99,97,155)== -1,f(123,135,201)== 1,f(0,0,1)== 1,f(0,1,1)== -1,f(0,-1,1)== -1,f(1,0,1)== 0,f(-1,0,1)== 0,f(-1,-1,1)== -1,f(1,1,1)== -1,f(-2,-3,4)== 1,f(32,45,58)== 1,f(99,97,155)== -1,f(123,135,201)== 1]
[True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
```
[Answer]
# Pyth, 41 bytes
```
?<=d.5K+?>ZJ-c.ahQeQdZJ.acchtQeQ^3d_1s>dK
```
[Test it here](https://pyth.herokuapp.com/?code=%3F%3C%3Dd.5K%2B%3F%3EZJ-c.ahQeQdZJ.acchtQeQ%5E3d_1s%3EdK&input=%5B0%2C0.866025403784439%2C1%5D&test_suite=1&test_suite_input=0%2C0%2C1++++++%23++--%3E+1%0A0%2C1%2C1++++++%23++--%3E+-1%0A0%2C-1%2C1+++++%23++--%3E+-1%0A1%2C0%2C1++++++%23++--%3E+0%0A-1%2C0%2C1+++++%23++--%3E+0%0A-1%2C-1%2C1++++%23++--%3E+-1%0A1%2C1%2C1++++++%23++--%3E+-1%0A-2%2C-3%2C4++++%23++--%3E+1%0A32%2C45%2C58+++%23++--%3E+1%0A99%2C97%2C155++%23++--%3E+-1%0A123%2C135%2C201%23++--%3E+1&debug=0)
[Answer]
## JavaScript (ES6), 67 bytes
```
with(Math)(a,b,l)=>sign(min(l*l*3-b*b*4,(l-abs(a))*sqrt(3)-abs(b)))
```
Note: To assign this to a variable so that you can call it, put the `f=` after the `with(Math)`.
I used `l*l` and `b*b` in the first parameter to `min` to avoid calls to `abs` and `sqrt` but I couldn't work out whether I could do a similar trick with the second parameter.
] |
[Question]
[
Suppose we define a simple program that takes an array L of natural numbers with some length N and does the following:
```
i=0 #start at the first element in the source array
P=[] #make an empty array
while L[i]!=0: #and while the value at the current position is not 0
P.append(L[i]) #add the value at the current position to the end of the output array
i=(i+L[i])%N #move that many spaces forward in the source array, wrapping if needed
return P #return the output array
```
Every such program will either run forever or will eventually terminate, producing a list of positive integers. Your job is to, given a list P of positive integers, produce a shortest list, L, of natural numbers that terminates and produces P when plugged into the previous program.
Such a list always exists, since one can just add `P[i]-1` zeros after each `P[i]` in the list, then one final 0, and it will produce the original list. For example, given `[5,5]`, one solution is `[5,0,0,0,0,5,0,0,0,0,0]`. However, `[5,0,5]` is much shorter, so the automatic solution is not a valid one for your program.
```
[5,6]->[5,6,0,0]
[5,7]->[5,0,0,0,0,7,0,0]
[5,6,7]->[5,6,0,7]
[5,6,8]->[5,0,8,0,0,6,0,0,0]
[1,2,3,4]->[1,2,0,3,0,0,4,0]
[1,2,1,2]->[1,2,0,1,2,0,0]
[1,3,5,7]->[1,3,0,0,5,0,0,0,0,7]
[1,3,5,4]->[1,3,4,0,5,0,0]
```
Input is a list of positive integers(in some format you can specify) and output should be in the same format. List and integer size can be up to 2^16. This is code golf, so shortest program in bytes wins!
[Answer]
## Python 3, ~~109 102 100 95~~ 93 bytes
```
def f(L,k=1,i=0):
P=[0]*k
for x in L:x=P[i]=P[i]or x;i=(i+x)%k
return P[i]and f(L,k+1)or P
```
A recursive solution.
Call it like `f([1,2,3,4])`.
[Watch it pass all test cases.](http://ideone.com/KjRTnr)
We start with `k=1` (length of output) and `i=0` (position in output), and make a list `P` with `k` zeros.
Then we iterate along the elements `x` of `L`, updating `P[i]` to `P[i]or x` (so `P[i]` keeps its value if it's nonzero) and `i` to `(i+P[i])%k`.
After that, we check that the final value of `P[i]` is zero, incrementing `k` if it's not, and return `P`.
If at any point of the algorithm `P[i]` is already nonzero, it enters a loop going around some of the nonzero values of `P`, and ends up at a nonzero value; then we recurse.
] |
[Question]
[
Given a list of the populations of each state, output, from greatest to least, the number of votes that state gets in the electoral college.
**Input:** The first number represents the total number of votes to distribute; it is followed by a list of and populations. In this example, abbreviations for states are used, but any name containing uppercase and lowercase letters could be used. You can take this in any format you like, as long as the only information contained is the state's abbreviation and its population.
Input may be taken as arguments to a function, or any way you want.
Example (possible) input: `538 [[CA 38000000], [NH 1300000] etc.]`
**Output:** Output, in some format, the number of votes each state gets. Order the states from greatest to least. If two states have the same number of votes, order by whichever name would come first in a dictionary (which comes first alphabetically).
Before finding the number of votes, first check if there is a state named DC in the list of inputs, and if there is, give the state 3 votes, regardless of its population. Then, remove it from the list and assign the rest of the votes as though DC didn't exist.
The number of votes in the electoral college is defined to be the sum of the number of senators and representatives. Every state gets two senators, so subtract twice the number of states from the total (538, in the example input) to get the number of representatives. Assign every state one representative to start. Then, perform the following process:
1. Assign each state a number, `A`, defined to be `P/sqrt(2)` where `P` is the population.
2. Sort the states according to their values of `A`.
3. Assign the first state (the one with the largest `A`) one more representative.
4. Reassign values of `A`, as `A = P/(sqrt(n)*sqrt(n + 1))`, where `n` is the current number of representatives assigned to the state.
5. Go back to step 2. Repeat until all representatives have run out.
Example (possible) output: `{CA: 518, NH: 20}`. The output doesn't have to be in this format, but must contain the same information.
Note that if it is not possible to assign votes legally because there are less than `3*(# of states)` votes, print whatever you want. You can crash, throw an error, etc.
**Test cases:**
```
538 [['CA' 38000000], ['NH' 1300000]] --> CA: 518, NH: 20
538 [['NH' 1300000], ['CA' 38000000]] --> CA: 518, NH: 20 (must be in order from greatest to least!)
538 [['DC' 1000000], ['RH' 1]] --> RH: 535, DC: 3
100 [['A', 12], ['B', 8], ['C', 3]] --> A: 51, B: 35, C: 14
100 [['A', 12], ['B', 8], ['C', 3], ['D', 0]]: --> [49, 34, 14, 3] (yes, even states with no population get votes)
2 [['A', 1]] --> aasdfksjd;gjhkasldfj2fkdhgas (possible output)
12 [['A', 1], ['B', 2], ['C', 3], ['D', 4]] --> A: 3, B: 3, C: 3, D: 3
42 [['K', 123], ['L', 456], ['M', 789]] --> M: 23, L: 14, K: 5
420 [['K', 123], ['L', 456], ['M', 789]] --> M: 241, L: 140, K: 39
135 [['C', 236841], ['D', 55540], ['G', 70835], ['K', 68705], ['M', 278514], ['Ms', 475327], ['Nh', 141822], ['Nj', 179570], ['Ny', 331589], ['Nc', 353523], ['P', 432879], ['R', 68446], ['Sc', 206236], ['Ve', 85533], ['Vi', 630560]] --> Vi: 20, Ms: 16, P: 14, Nc: 12, Ny: 12, M: 10, C: 9, Sc: 8, Nj: 7, Nh: 6, Ve: 5, D: 4, G: 4, K: 4, R: 4
```
[Answer]
# [Clean](http://clean.cs.ru.nl/Clean), 263 244 222 bytes
```
v n s=sortBy(\(a,b)(c,d).b>d)([(t,3.0)\\t<-s|fst t=="DC"]++w(n-3*(length s))[(t,1.0)\\t<-s|fst t<>"DC"])
w 0s=w 0 s=[(p,r+2.0)\\(p,r)<-s]
w n s#s=sortBy(\a b.A a>A b)s
#(p,r)=hd s
=w(n-1)[(p,r+1.0):tl s]
A((_,p),r)=p/sqrt(r*r+r)
```
Call like
```
Start = v 538 [("DC", 1000000.0), ("RH", 1.0)]
```
Ungolfed version, full program (`census.icl`):
```
module census
import StdEnv
Start = votes 538 [("DC", 1000000.0), ("RH", 1.0)]
votes n states
# dc = filter (((==)"DC")o fst) states
= sortBy (\(a,b)(c,d).b>d) ([(t,3.0) \\ t <- dc] ++ votes` (n-3*length states) [(t,1.0)\\t<-removeMembers states dc])
where
votes` 0 states = map (\(p,r).(p,r+2.0)) states
votes` n states
# states = sortBy (\a b.A a > A b) states
# (p,r) = hd states
= votes` (n-1) [(p,r+1.0):tl states]
A ((_,p),r) = p / sqrt(r*r+r)
```
[Answer]
# JavaScript ES6, ~~249 bytes~~ 244 bytes
```
(r,s)=>{r-=s.length*3;s=s.map(t=>({s:t[0],p:t[1],a:t[1]/(q=Math.sqrt)(2),r:1}));while(r--)(t=>t.a=t.p/q(++t.r)/q(t.r+1))(s.filter(t=>t.s!='DC').sort((a,b)=>b.a-a.a)[0]);return''+s.sort((a,b)=>(r=b.r-a.r)?r:a.s>b.s?1:-1).map(t=>t.s+':'+(t.r+2))}
```
## Test cases
```
d = (r, s) => {
r -= s.length * 3;
s = s.map(t => ({
s: t[0],
p: t[1],
a: t[1] / (q = Math.sqrt)(2),
r: 1
}));
while (r--)(t => t.a = t.p / q(++t.r) / q(t.r + 1))(s.filter(t => t.s != 'DC').sort((a, b) => b.a - a.a)[0]);
return '' + s.sort((a, b) => (r = b.r - a.r) ? r : a.s > b.s ? 1 : -1).map(t => t.s + ':' + (t.r + 2))
};
document.write(
'<pre>' +
d(135, [
['C', 236841],
['D', 55540],
['G', 70835],
['K', 68705],
['M', 278514],
['Ms', 475327],
['Nh', 141822],
['Nj', 179570],
['Ny', 331589],
['Nc', 353523],
['P', 432879],
['R', 68446],
['Sc', 206236],
['Ve', 85533],
['Vi', 630560]
]) +
'</pre>'
);
```
Credit to @Neil for saving 5 bytes!
[Answer]
## Python 2, 219 bytes
```
v,s=input()
n={k:1 for k in s}
v-=3*len(s)
l=lambda x:-x[1]
if'DC'in s:del s['DC']
while v:A,_=sorted([(a,s[a]/(n[a]**2+n[a])**.5)for a in s],key=l)[0];n[A]+=1;v-=1
for a in n:n[a]+=2
print sorted(list(n.items()),key=l)
```
Takes input as
```
420,{'K':123,'L':456,'M':789}
```
Prints:
```
[('M', 241), ('L', 140), ('K', 39)]
```
] |
[Question]
[
Create a program that solves a mathematical expression using the elements from alternating sides of the expression. The way it’s done is, instead of reading from left to right, you read the first character, then the last, then the second, then the second to last etc. This will give you a new expression that you must evaluate and output.
```
a*b/c+d-e
135798642 <-- Order you read the expression in
ae*-bd/+c <-- Order of operation.
```
Example:
```
1*3/2+4-5
15*-34/+2 = -255
```
If the expression doesn’t «work», a `1` must be inserted in the necessary positions to make it work.
A few examples will probably illustrate it better:
```
Input: 1+1+1+1+1
Result: 23 // Because 1+1+1+1+1 -> 11++11++1 -> 23
Input: 1+2-3+12-5
Result: -19 // Because 1+2-3+12-5 -> 15+-22-13+ -> 15+-22-13+1 -> -19
// |
// Not valid expression
Input: 2*2*2*2*2
Result: 968 // Because 2*2*2*2*2 -> 22**22**2 -> 22*1*22*1*2 -> 968
// || ||
// Not valid, 1 must be inserted
Input: 17/2
Output: 127 // Because 17/2 = 127/ -> 127/1 -> 127
```
The operators that must be supported are `+ - * /`. There won't be parentheses. Normal math rules and "syntax" is used, so for instance `**` does not mean exponentiation. `a++++1` is equivalent to `a+1` (i.e. MATLAB style, not C++).
In case there's any doubt, some valid operations are:
```
-a
+a
a++b
a+-b
a*-b
a*+b
a*++b
a/b
a/-b
a/+b
-a/--b
```
While all of the following are not valid. It's shown what they should be substituted with:
```
a+ | a+1
a- | a-1
a++++ | a++++1 (This is equivalent to a+1)
a*+++ | a*+++1 (This is equivalent to a*1)
a**b | a*1*b
a*/b | a*1/b
a/*b | a/1*b
a* | a*1
*a | 1*a
***a | 1*1*1*a
```
Rules:
* The code can be a function or a full program
* The input can be STDIN or function argument
* The input must be a valid mathematical expression, **without quotation marks, `''` or `""`**.
* The output should be the answer to the new expression, as an integer, decimal or a simplified fraction.
* At least three digits after the decimal point must be supported. So `1/3 = 0.333`, not `0.33`. `0.333333333` is accepted.
* `ans = ...` is accepted.
* Leading and trailing newlines and spaces are accepted.
* The input will only be integers
* Division by zero can result in an error, NaN, Inf etc. Outputting a number is not accepted.
As always, the shortest code in bytes win. A winner will be selected one week from the day the challenge was posted. Answers posted later may still win if it's shorter than the current leader.
[Answer]
## Perl, ~~108~~ 100 bytes
```
$_="";while(@F){$_.=shift@F;$_.=pop@F}s@(\*|/)\1+@\1@g;s@^[*/]@1$&@;s@\D$@$&1@;s@\D@$&@g;$_=eval
```
The code is 96 bytes, plus 4 for the command-line argument `-pF//`, where
* `-p` inserts `while (<>) { .. } continue { print }` and
* `-F//` splits the input and puts it in `@F`.
Note that the input should not have a trailing newline, so use `/bin/echo -n 'formula' | perl ...`
Less golfed:
```
$_=''; # reset $_
while(@F) { # reorder input
$_.=shift @F; # take first element off of @_
$_.=pop @F # idem for last; if @F is empty, undef is appended
}
s@(\*|/)\1+@\1@g; # replace 2 or more '*' or '/' with just one: *1 and /1 = nop
s@^[*/]@1$&@; # if expression starts with * or / prepend a 1
s@\D$@$&1@; # if expression doesn't end with a number, append 1
s@\D@$& @g; # eval doesn't like '++1': add spaces after operators
$_ = eval # set $_ to 3v1l, so the `-p` will print the new value
```
---
### Testing
Put the above in a file called `114.pl`, and the below test script in a file next to it:
```
%test = (
'1+1+1+1+1' => 23,
'1*3/2+4-5' => -255,
'1+2-3+12-5'=> -19,
'2*2*2*2*2' => 968,
'17/2' => 127,
'--/-1-2-' => -2,
'**2*' => 2,
'++1++' => 1,
'/2/' => 0.5,
'10/' => '',
);
printf "%-20s -> %5s: %5s\n", $_, $test{$_}, `/bin/echo -n '$_' | perl -pF// 114.pl`
for keys %test;
```
Running it outputs:
```
++1++ -> 1: 1
**2* -> 2: 2
17/2 -> 127: 127
10/ -> :
1+1+1+1+1 -> 23: 23
1*3/2+4-5 -> -255: -255
2*2*2*2*2 -> 968: 968
1+2-3+12-5 -> -19: -19
--/-1-2- -> -2: -2
/2/ -> 0.5: 0.5
```
Note that `1/0` causes a division by zero error: the `eval` outputs `undef`, which is represented by the empty string.
[Answer]
# JavaScript ES6, 105 ~~106~~
**Edit** Saved 1 byte thx @Kenney
```
t=>eval("for(t=[...t],p=o='';c=t.reverse().pop();p=c)o+=p<'0'?(c=='/'|c<'+'||' ')+c:c;eval(p<'0'?o+1:o)")
// Less golfed
t=>{
for(t = [...t], p = o = '';
c = t.reverse().pop();
p = c)
o += p<'0'
? (c=='/' | c=='*' || ' ')+c // '1' or ' '
: c;
return eval(p<'0' ? o+1 : o)
}
```
Test snippet
```
f=t=>eval("for(t=[...t],p=o='';c=t.reverse().pop();p=c)o+=p<'0'?(c=='/'|c<'+'||' ')+c:c;eval(p<'0'?o+1:o)")
console.log=x=>O.innerHTML+=x+'\n'
function test() { console.log(I.value + ' -> '+f(I.value)) }
;['1+1+1+1+1', '1*3/2+4-5', '1+2-3+12-5', '2*2*2*2*2',
'17/2', '--/-1-2-', '**2*', '++1++', '/2/', '10/' ]
.forEach(t=>console.log(t+' -> '+f(t)))
```
```
Your test <input id=I><button onclick="test()">-></button>
<pre id=O></pre>
```
] |
[Question]
[
# Background
I want to build a fence.
For that, I have collected a bunch of poles, and stuck them to the ground.
I have also collected lots of boards that I'll nail to the poles to make the actual fence.
I tend to get carried away when building stuff, and most likely I'll just keep nailing the boards to the poles until there's no more place to put them.
I want you to enumerate the possible fences that I can end up with.
# Input
Your input is a list of two-dimensional integer coordinates representing the positions of the poles, in any convenient format.
You can assume that it contains no duplicates, but you cannot assume anything about its order.
The boards are represented by straight lines between the poles, and for simplicity, we only consider horizontal and vertical boards.
Two poles can be joined by a board if there are no other poles or boards between them, meaning that the boards cannot cross each other.
An arrangement of poles and boards is *maximal* if no new boards can be added to it (equivalently, there is either a pole or a board between any two horizontally or vertically aligned poles).
# Output
Your output is the number of maximal arrangements that can be constructed using the poles.
# Example
Consider the input list
```
[(3,0),(1,1),(0,2),(-1,1),(-2,0),(-1,-1),(0,-2),(1,-1)]
```
Viewed from the top, the corresponding arrangement of poles looks something like this:
```
o
o o
o o
o o
o
```
There are exactly three maximal arrangements that can be constructed using these poles:
```
o o o
o-o o|o o-o
o----o o||| o o| | o
o-o o|o o-o
o o o
```
Thus the correct output is `3`.
# Rules
You can write either a function or a full program.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
```
[] -> 1
[(0,0),(1,1),(2,2)] -> 1
[(0,0),(1,0),(2,0)] -> 1
[(0,0),(0,1),(1,0),(1,1)] -> 1
[(1,0),(0,1),(-1,0),(0,-1)] -> 2
[(3,0),(1,1),(0,2),(-1,1),(-2,0),(-1,-1),(0,-2),(1,-1)] -> 3
[(0,0),(4,0),(1,1),(1,-2),(3,1),(3,-2),(2,-1),(4,-1)] -> 3
[(0,0),(4,0),(1,1),(1,-2),(3,1),(3,-2),(2,-1),(4,-1),(0,-1)] -> 4
[(0,0),(4,0),(1,1),(1,-2),(3,1),(3,-2),(2,-1),(0,-1),(2,2)] -> 5
[(0,0),(4,0),(1,1),(1,-2),(3,1),(3,-2),(2,-1),(4,-1),(0,-1),(2,2)] -> 8
```
[Answer]
# Mathematica, 301 bytes
```
(t~SetAttributes~Orderless;u=Subsets;c=Complement;l=Select;f=FreeQ;Count[s=List@@@l[t@@@u[Sort@l[Sort/@#~u~{2},!f[#-#2&@@#,0]&]//.{a___,{x_,y_},{x_,z_},b___,{y_,z_},c___}:>{a,{x,y},b,{y,z},c}],f[#,t[{{a_,b_},{a_,c_}},{{d_,e_},{f_,e_}},___]/;d<a<f&&b<e<c]&],l_/;f[s,k_List/;k~c~l!={}&&l~c~k=={},{1}]])&
```
This is an unnamed function which takes the coordinates as a nested `List` and returns an integer. That is, you can either give it a name and call it, or just append
```
@ {{3, 0}, {1, 1}, {0, 2}, {-1, 1}, {-2, 0}, {-1, -1}, {0, -2}, {1, -1}}
```
With indentation:
```
(
t~SetAttributes~Orderless;
u = Subsets;
c = Complement;
l = Select;
f = FreeQ;
Count[
s = List @@@ l[
t @@@ u[
Sort @ l[
Sort /@ #~u~{2},
!f[# - #2 & @@ #, 0] &
] //. {a___, {x_, y_}, {x_, z_}, b___, {y_, z_}, c___} :>
{a, {x, y}, b, {y, z}, c}
],
f[
#,
t[{{a_, b_}, {a_, c_}}, {{d_, e_}, {f_, e_}}, ___]
/; d < a < f && b < e < c
] &
],
l_ /; f[
s,
k_List /; k~c~l != {} && l~c~k == {},
{1}
]
]
) &
```
I can't even begin to express how naive this implementation is... it definitely couldn't be more brute force...
* Get all (unordered) pairs of poles.
* Sort each pair and all pairs into a canonical order.
* Discard pairs which don't share one coordinate (i.e. which aren't connectible by an orthogonal line).
* Discard pairs can be formed from two shorter pairs (so that `o--o--o` yields only two fences instead of three).
* Get all subsets of those pairs - i.e. all possible combinations of fences.
* Filter out combinations which have fences crossing each other.
* Count the number of resulting fence sets for which no strict superset can be found in the list.
Surprisingly it does solve all the test cases virtually immediately.
A really neat trick I discovered for this is the use of `Orderless` to cut down on the number of patterns I have to match. Essentially, when I want to ditch fence sets with crossing fences, I need to find a pair of vertical and horizontal fence and check the condition on them. But I don't know what order they'll appear in. Since list patterns are normally order dependent, this would result in two really long patterns. So instead I replace with surrounding list with a function `t` with `t @@@` - which isn't defined so it is held as it is. But that function is `Orderless`, so I *can* just check a single order in the pattern, and Mathematica will check it against all permutations. Afterwards, I put the lists back in place with `List @@@`.
I wish there was a built-in that is a) `Orderless`, b) *not* `Listable` and c) not defined for 0 arguments or list arguments. Then I could replace `t` by that. But there doesn't seem to be such an operator.
[Answer]
# Haskell, 318 bytes
```
import Data.List
s=subsequences
k[(_,a,b),(_,c,d)]|a==c=f(\w->(1,a,w))b d|1<2=f(\w->(2,w,b))a c
f t u v=[t x|x<-[min u v+1..max u v-1]]
q l=nub[x|x<-map(k=<<)$s[a|a@[(_,n,m),(_,o,p)]<-s l,n==o||m==p],x++l==nubBy(\(_,a,b)(_,c,d)->a==c&&b==d)(x++l)]
m=q.map(\(a,b)->(0,a,b))
p l=sum[1|x<-m l,all(\y->y==x||x\\y/=[])$m l]
```
Usage: `p [(1,0),(0,1),(-1,0),(0,-1)]`. Output: `2`
How it works:
* create all sublists of the input list and keep those with two elements and with either equal x or equal y coordinates. This is a list of all pairs of poles where a fence can be build in between.
* create all sublists of it
* add boards for every list
* remove lists where a x-y coordinate appears twice (boards and poles)
* remove duplicate lists (boards only) to handle multiple empty lists, because of directly adjacent poles (e.g. (1,0) and (1,1))
* keep those which are not a strict sublist of another list
* count remaining lists
] |
[Question]
[
Your task is to take an string containing an isotope of an element as input, encoded like the following example with the atomic number followed by a space and the IUPAC chemical symbol for the element:
```
162 Dy
```
and return the number of *neutrons* in an atom of that isotope.
In the above example, dysprosium-162 has 96 neutrons (162 total nucleons, minus 66 protons because it's dysprosium), so the output should be `96`.
You may assume that the element given will be one of the 114 elements currently given permanent names by the IUPAC (including flerovium and livermorium) and not a generic name such as `Uus` for "ununseptium". You may also assume that the atomic number of the isotope will not exceed 1000, or be less than the number of protons in the element.
You may not use built-ins to retrieve data about the proton or neutron number of elements, or use any function within your code that evaluates a string or number token as code on its own.
The program to use the fewest tokens to do this in any language wins. However, for the purpose of this challenge, every character in a string, or a variable name converted into a string, counts as a token.
List of elements and their atomic number for reference:
```
{
"H": 1,
"He": 2,
"Li": 3,
"Be": 4,
"B": 5,
"C": 6,
"N": 7,
"O": 8,
"F": 9,
"Ne": 10,
"Na": 11,
"Mg": 12,
"Al": 13,
"Si": 14,
"P": 15,
"S": 16,
"Cl": 17,
"Ar": 18,
"K": 19,
"Ca": 20,
"Sc": 21,
"Ti": 22,
"V": 23,
"Cr": 24,
"Mn": 25,
"Fe": 26,
"Co": 27,
"Ni": 28,
"Cu": 29,
"Zn": 30,
"Ga": 31,
"Ge": 32,
"As": 33,
"Se": 34,
"Br": 35,
"Kr": 36,
"Rb": 37,
"Sr": 38,
"Y": 39,
"Zr": 40,
"Nb": 41,
"Mo": 42,
"Tc": 43,
"Ru": 44,
"Rh": 45,
"Pd": 46,
"Ag": 47,
"Cd": 48,
"In": 49,
"Sn": 50,
"Sb": 51,
"Te": 52,
"I": 53,
"Xe": 54,
"Cs": 55,
"Ba": 56,
"La": 57,
"Ce": 58,
"Pr": 59,
"Nd": 60,
"Pm": 61,
"Sm": 62,
"Eu": 63,
"Gd": 64,
"Tb": 65,
"Dy": 66,
"Ho": 67,
"Er": 68,
"Tm": 69,
"Yb": 70,
"Lu": 71,
"Hf": 72,
"Ta": 73,
"W": 74,
"Re": 75,
"Os": 76,
"Ir": 77,
"Pt": 78,
"Au": 79,
"Hg": 80,
"Tl": 81,
"Pb": 82,
"Bi": 83,
"Po": 84,
"At": 85,
"Rn": 86,
"Fr": 87,
"Ra": 88,
"Ac": 89,
"Th": 90,
"Pa": 91,
"U": 92,
"Np": 93,
"Pu": 94,
"Am": 95,
"Cm": 96,
"Bk": 97,
"Cf": 98,
"Es": 99,
"Fm": 100,
"Md": 101,
"No": 102,
"Lr": 103,
"Rf": 104,
"Db": 105,
"Sg": 106,
"Bh": 107,
"Hs": 108,
"Mt": 109,
"Ds": 110,
"Rg": 111,
"Cn": 112,
"Fl": 114,
"Lv": 116
}
```
[Answer]
# CJam, ~~120~~ 6 or 116 tokens
If numbers are single token, then we have the whole code as 6 tokens:
```
212065132249371573644124577121541653292994215804249878509033804566332949723850494006885998432589817663973272353884582668784347806472090795216938149345570424681103578762377771127645936569136562173556524971260383556793671988140498193154122873972644190003488894117491373991987567199279175132071186860926217964652052981868515510731685503564515183920386542420190587555479397630718313762477968862282786518176572529906744217608955037610524188966159703528812103601771438848515748286560373093942224945233978303729665751831532717 128b:c~
```
where the tokens are
```
212065132249371573644124577121541653292994215804249878509033804566332949723850494006885998432589817663973272353884582668784347806472090795216938149345570424681103578762377771127645936569136562173556524971260383556793671988140498193154122873972644190003488894117491373991987567199279175132071186860926217964652052981868515510731685503564515183920386542420190587555479397630718313762477968862282786518176572529906744217608955037610524188966159703528812103601771438848515748286560373093942224945233978303729665751831532717
128
b
:
c
~
```
This code is equivalent to the below code containing the string version of the big number in the above code. But due to a string, the below code has 116 tokens:
```
ri"ᘭ᛭绊ڏ晍嬨塐弶⛡ᠸ庐ᖩે槑湘ࡊ㚋䊌栕ᄂỗ∘抁埵ໂČ槩唹ᘇ穗≧ṷ㴛勤烓≿ⲲȊ嬅͙獚簜䱡数㍉㉦䩛爈拴矍㚴燌㾄䱮⃜⢴ⶏ㯗႒ݘ䅄瞟⮘㢧⳻⮵∼䚽珯ほֹ㳰櫣ݰ牜殙ᆌ穟䖻ᄭⓚ獙༧撒咛啺"2F#b57b65f+:cr2*2<#2/)-
```
Tokens (with explanation) are
```
r "Read the first input";
i "and convert it to integer";
"
91 character string "Then this base converted string";
"
2
F
# "'s ASCII representation of each character gets converted";
b "to base 2**15";
57 "which gets converted to";
b "base 57";
65 "and we add 65 to each element in the base 57 array";
f
+
:
c "and convert each array element to character.";
r "Then read the next input string, which is atom's IUPAC";
2 "double it";
*
2 "and take only first 2 characters";
<
# "Find the occurrence of these 2 characters in the big string";
2 "and divide the index by 2";
/
) "increment the index to counter 0 offset";
- "and subtract this number, which is the atomic number from"
"the input number of nucleons";
```
To run the above string, copy the code from [this link](https://mothereff.in/byte-counter#ri%22%01%E1%98%AD%E1%9B%AD%E7%BB%8A%DA%8F%E6%99%8D%E5%AC%A8%E5%A1%90%E5%BC%B6%E2%9B%A1%E1%A0%B8%E5%BA%90%E1%96%A9%E0%AB%87%E6%A7%91%E6%B9%98%E0%A1%8A%E3%9A%8B%E4%8A%8C%E6%A0%95%E1%84%82%E1%BB%97%E2%88%98%E6%8A%81%E5%9F%B5%E0%BB%82%C4%8C%E6%A7%A9%E5%94%B9%E1%98%87%E7%A9%97%E2%89%A7%E1%B9%B7%E3%B4%9B%E5%8B%A4%E7%83%93%E2%89%BF%E2%B2%B2%E3%87%AD%C8%8A%E5%AC%85%CD%99%E7%8D%9A%E7%B0%9C%E4%B1%A1%E6%95%B0%E3%8D%89%E3%89%A6%E4%A9%9B%E7%88%88%E6%8B%B4%E7%9F%8D%E3%9A%B4%E7%87%8C%E3%BE%84%E4%B1%AE%E2%83%9C%E2%A2%B4%E2%B6%8F%E3%AF%97%E1%82%92%DD%98%E0%A9%A1%E4%85%84%E7%9E%9F%E2%AE%98%E3%A2%A7%E2%B3%BB%E2%AE%B5%E2%88%BC%E4%9A%BD%E7%8F%AF%E3%81%BB%D6%B9%E3%B3%B0%E6%AB%A3%DD%B0%E7%89%9C%E1%AB%A6%E6%AE%99%E1%86%8C%E7%A9%9F%E4%96%BB%E1%84%AD%E2%93%9A%E7%8D%99%E0%AE%A7%E0%BC%A7%E6%92%92%E5%92%9B%E5%95%BA%222F%23b57b65f%2B%3Acr2*2%3C%232%2F%29-) as SE removes some characters while uploading the answer.
This can be reduced to 109 tokens too, but then SE won't let me upload my answer, throwing malformed URI exception.
Input goes like
```
162 Dy
```
output is like
```
96
```
The weird string is just a base encoded string containing all IUPAC names at their `Atomic number * 2 - 1` index.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Python 3 with exec, 17 tokens
```
exec(int.to_bytes(42580960806925240587487231677747050990110980939298529158008049507419456038066480774222358994792932281429500848123044123619998194774734911333011516763318834841258668032468977581617546825403043048781904307873076644287421190283925612029151422009703963147720234582458918676020358978146687598642493196719470433413287097024943497230356536978257362073205770196031226838532057690859535911353521203287284228407660035870497366713816359382867026152168356178620422021081074864815228071041303891869741111572003521808946355179139580269537828514345177247630946236685801543450404664783011350766913659964138280312012942354586269107632396118108534925651704031851802293836135007879834261627022944650861299698061444211422731907625,295,'big'))
```
# Python 3 without exec, 35 tokens
```
m,n=input().split()
print(int(m)-(0x50000003c00000000000000000000000000000000000000000000000000000000000000000000000000000000008c00000000000000000000000000000000000000000000000000000000d80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000116880005ad0000d002b832400000000000000000000000000000004c0000064f8000003806a0088015660000000000000000000000000000b00000000000ac0000000016efd12c0004b60000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017a700760005400f400000000000001700a56c000000000000000000000000000004c0000000000000000000000000000000000000000000000000000000000000000002ee6000000000700000029e00522c0000000000000000000000000003680000002a3200000000000c00032800000000000000000000000000000e91c000ce000000000000000c000000000000e400000000000000000000000000000004800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009a000006200000000000000000000000000000000000000000000000000006c0000043000000000000509008000000000000000000000000000000000000000000000000000000000000082000007c0000000000000000000000000000000ae00000019390000000000068000000000000000000000000000000000fc06388000000000000000000000000000000000000000000000000108000000006e0000000000000000000000000000d2000000000000000000000000000074037300001be1808800000000c4e98000050000000000000000000000000000000046000000000061014f580001000000e0000000000000000000000000013eaa12400000017c680000002f0000059000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009c04a2f7001000007880e0001300d408012000060a0000000000000000000>>7*int(n,36)&127))
```
# Ruby with eval, 17 tokens
```
eval [22146635005300445083784033446026580324048447941091204274213253110537099437818224958820496527991920943430421799402248351995854377736142191462062582991150146209770141259010870255095388946677505144127700666745571877848513432112199556183753919673308110291261587736766001750331575554182707626697924148465335917814388410868486650419909619279250674754531982074694183257024218097391705830277480110741636037821082572926228904583257826932150641336017429157246896262085081972165351023141358378905645164343005169041637147077645200273099823888392038731180787177889720531999846231330677441270444855911286469030157575699579420898896870179419644019549285098577609138033580761786048462145007410.to_s(16)].pack('H*')
```
# Javascript, 49 tokens
```
m=prompt().split(/ /);
alert(m[0]-(function(){
_H_He_Li_Be_B_C_N_O_F_Ne_Na_Mg_Al_Si_P_S_Cl_Ar_K_Ca_Sc_Ti_V_Cr_Mn_Fe_Co_Ni_Cu_Zn_Ga_Ge_As_Se_Br_Kr_Rb_Sr_Y_Zr_Nb_Mo_Tc_Ru_Rh_Pd_Ag_Cd_In_Sn_Sb_Te_I_Xe_Cs_Ba_La_Ce_Pr_Nd_Pm_Sm_Eu_Gd_Tb_Dy_Ho_Er_Tm_Yb_Lu_Hf_Ta_W_Re_Os_Ir_Pt_Au_Hg_Tl_Pb_Bi_Po_At_Rn_Fr_Ra_Ac_Th_Pa_U_Np_Pu_Am_Cm_Bk_Cf_Es_Fm_Md_No_Lr_Rf_Db_Sg_Bh_Hs_Mt_Ds_Rg_Cn_Uut_Fl_Uup_Lv_
}).toString().split(/_/).indexOf(m[1]))
```
Just to illustrate [Count big-ints/symbols/variables as N tokens in atomic-code-golf](http://meta.codegolf.stackexchange.com/questions/2567/count-big-ints-symbols-variables-as-n-tokens-in-atomic-code-golf) :)
[Answer]
## Javascript, 42 tokens (?)
```
alert(parseInt(x=prompt().split(" "))-Object.getOwnPropertyNames({__H_HeLiBeB_C_N_O_F_NeNaMgAlSiP_S_ClArK_CaScTiV_CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY_ZrNbMoTcRuRhPdAgCdInSnSbTeI_XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW_ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU_NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCn__Fl__Lv:0})[0].indexOf(x[1])/2)
```
PS: Where I can find some script to count tokens?
] |
[Question]
[
If you want to build a fence and have different length boards available, there are many different ways to set up your posts. So, given a minimum and maximum board length, a number of boards, and the total length, count how many ways you can arrange them.
**Input**
Input is four positive integers:
* **min:** The smallest board usable. Will be `>0`.
* **max:** The largest board available. Will be `>min`.
* **count:** Number of boards to use. Will be `>0`.
* **length:** Total length of the fence. For a valid fence, this should be `>=min*count` and `<=max*count`
Individual boards can be any *integer* length between `min` and `max` (inclusive).
**Output**
Output a single number representing the number of ways you can arrange the fence.
**Examples**
For input (in order listed above) `2 3 4 10`, you can arrange the boards six ways:
```
2233
2323
2332
3223
3232
3322
```
So the output is `6`. If your input was `1 3 4 6`, the output is `10`, since there are ten ways to do it:
```
1113 1212
1131 1221
1311 2112
3111 2121
1122 2211
Input Output
5 10 6 45 4332
1 100 6 302 1204782674
27 53 8 315 4899086560
1 10 11 70 2570003777
1 6 15 47 20114111295
4 8 150 600 1 // all boards length 4
1 10 100 80 0 // invalid, you can't put 100 boards in 80 length
```
Of course, there's a naive method to do this:
```
long f(int min, int max, int count, int length){
if(count==1)
return 1;
long num = 0;
for(int i=min;i<=max;i++){
int goal = length - i;
if(goal <= max*(count-1) && goal >= min*(count-1)){
num += f(min,max,count-1,goal);
}
}
return num;
}
```
**Rules**
The algorithm given above works fine for small inputs, but it can easily overflow the `long` with larger inputs. Even with arbitrary-length numbers, it's incredibly inefficient. I believe it's `O((max-min+1)^count)`.
To be considered valid for this challenge, you should be able to compute input `1 10 100 700` in under one hour on my i7. Given a more efficient algorithm than the one above, this should not be a problem. I will test any entries I believe may come close to the limit. If your algorithm takes more than a few minutes to run, you should use a freely available language (on linux) to facilitate testing.
Code may take the form of a complete program or function, with input/output as any of the [standard methods](http://meta.codegolf.stackexchange.com/a/1326/14215). Shortest code in bytes wins.
[Answer]
# Ruby: ~~106~~ ~~98~~ 93 bytes
*Update:* Changed cache key type from strings to arrays. (**-5**)
*Update:* Storing the initial condition in the cache payed out quite well. (**-8**)
However, it increases the runtime for the test case to roughly 2 seconds.
I simply use memoization. I guess it can be further golfed as my Ruby skills are far from perfect.
```
@m={[0,0]=>1}
def f(l,u,c,s)
@m[[c,s]]||=s<0?0:(l..u).map{|x|f(l,u,c-1,s-x)}.reduce(:+)
end
```
Note that it runs for only one test case at a time, since I don't cache the min and max values (`l` and `u`, respectively). Here is my output for `1 10 100 700`:
```
121130639107583774681451741625922964085713989291260198434849317132762403014516376282321342995
real 0m0.316s
user 0m0.312s
sys 0m0.004s
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 55 [bytes](https://github.com/abrudz/SBCS)
```
⎕CY'dfns'
{0::0⋄⍺⊃⍵{+big⌿↑(⍳1+¯1⊥⍺)⌽¨⊂0,⍣(⊢/⍺)⊢⍵}⍣⍺⍺⊢1}
```
[Try it online! (without big, so fast but inaccurate)](https://tio.run/##VVAxT8JgEN2/X3EbEDTctf3awsoik4m4OFahaFJaIzXREBY1DJUSHfwDGBM3BuNiYkz4KfdH8NoC1hu@3L337r3L510G@71bL4gGa56/dA55@oRZ1z6p9PxwVFFjbLWQHx84/eLkntPPcZ1nPzx9rnL6QfXVkjh5E7LGs@/VOyd3uMfpa5WTRSNHk4XsTATKDDKPBU3WvsRwOhfD1dIULwnsHrXlPT7odNdxfxSLYDy8CGHo3cBZdB3GEPTDQXwOQoA4gpy0haqFwK/BZmOiMgswwAQLCItJSwc2WHpDOqBNcMGkDUAZTwQObmcbSIPlFKMlWtLigFjWI4KLqhb5vtoFQF6WaRqqlJJjbrOJrq1tVH9xudrQDiKajuOA2iUXRgYSWURkNLUqXZFRBP@q0QAvCOA08q56o@3vWKp0aabCXw "APL (Dyalog Unicode) – Try It Online")
The time complexity of the algorithm is \$O(m(m-n)c^2)\$, where \$m\$ and \$n\$ are max and min, and \$c\$ is the count, ignoring the cost of bigint addition (which is not a language built-in, and therefore horribly inefficient). It is nowhere close to the fastest, but it's still much faster than brute-force, as it returns the correct result for `1 10 100 700` in 3 minutes on my PC.
To use, assign the inline operator to `f` and call it in the form of `length (count f) min max`.
```
⎕CY'dfns' ⍝ Load dfns library, so we can use `+big`
{0::0⋄...} ⍝ If any error occurs, return 0
⍺⊃⍵{...}⍣⍺⍺⊢1 ⍝ Build the vector of all possible combinations by
⍝ taking the polynomial represented by ⍵ raised to the power of ⍺⍺,
⍝ then fetch the ⍺-th coefficient (might error if ⍺ is out of range)
0,⍣(⊢/⍺)⊢⍵ ⍝ Prepend "max" copies of 0s to the current polynomial
(⍳1+¯1⊥⍺)⌽¨⊂ ⍝ Generate the list of ^ rotated 0..(max-min) times
+big⌿↑ ⍝ Promote to matrix and sum the numbers vertically
```
] |
[Question]
[
## Task
Write a program to determine the note sounded, along with how many cents out of tune, of a string tuned to a given frequency and pressed down at a given point.
For the sake of simplicity, assume that the frequency of the sound produced and the length of the string to the right of where it is pressed are inversely proportional.
Note: this task deals solely in the fundamental tone, and not with overtones/other harmonics.
## Input
Your program is given two pieces of data:
* A string of arbitrary length, representing the string in question. This string will be marked with an X where the string is to be held down.
```
[-----] is a string divided in six sections (five divisions).
[--X--] is a string pressed at the exact center of the string.
[X----] is a string pressed at 1/6 the length of the string. (Length used is 5/6)
[-X--] is a string pressed at 2/5 of the length of the string. (Length used is 3/5)
```
Assume the note is sounded using the part of the string to the right of the `X`.
* A number (not necessarily an integer), signifying the frequency at which the string is tuned. The precision of this number will be at most four digits past the decimal.
It may be assumed that frequencies passed will lie between `10 Hz` and `40000 Hz`.
Input may be passed in a format of your choice. Please specify how input is accepted into your program in your answer.
## Output
Your program must output both the closest note\* in the twelve-tone equal temperament tuning system, and the number of cents away from the closest note that the sound denoted by the string would be (rounded to the nearest cent).
`+n` cents should be used to denote `n` cents sharp/above the note, and `-n` cents for flat/below the note.
The note should be outputted in scientific pitch notation. Assume A4 is tuned to `440Hz`. Use b and # for flat/sharp notes. Note: Either sharp or flat may be used. For the note at `466.16Hz`, either `A#` or `Bb` may be outputted for the note.
Format of output is up to you, as long as the output contains only the two previously specified pieces of information (i.e. printing every single possible output is not allowed).
\*closest note refers to the note that is closest to the sound denoted by the input, measured in the number of cents (therefore, the note that is within `50 cents` of the sound). If the sound is `50 cents` away from two different notes (after rounding), then either of the two notes may be outputted.
## Examples
Your program should work for all cases, not just the following examples.
```
Output Input Frequency Input String
A4, +0 cents 220 [-----X-----]
A5, +0 cents 220 [--------X--]
D5, -2 cents 440 [--X--------]
B4, -49 cents 440 [X----------]
A#4, +19 cents* 314.1592 [X-]
Eb9, +8 cents* 400 [-----------------------X]
Eb11,+8 cents* 100 [--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------X]
D#1, +49 cents* 10 [--X]
A0, -11 cents 11.7103 [---X--]
```
\*Either sharp or flat could have been outputted.
## Potentially Helpful Links
* [Notes and Frequencies](http://en.wikipedia.org/wiki/Piano_key_frequencies)
* [Wikipedia page on Scientific Pitch Notation](http://en.wikipedia.org/wiki/Scientific_pitch_notation)
* [Wikipedia page on Cents](http://en.wikipedia.org/wiki/Cents_(music))
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer wins.
[Answer]
# C, 179
```
main(n,d){float f;scanf("%*[^X]%nX%*[-]%n]%f",&n,&d,&f);f=log(f*d/(d-n))*17.3123-57.376;n=d=f+.5;n=n%12*7+784;printf("%c%d%c,%+2.0f cents\n",n/12,(d+9)/12,n%12/7*3+32,(f-d)*100);}
```
Receives the ascii picture on a line by itself, and the frequency on a separate line.
A few characters can be dropped by reducing the accuracy of the magic numbers `17.3123` and `57.376`.
Without the golfing, the program looks like this:
```
main(n,d)
{
float f; // 'float' and '%f' better than 'double' and '%lf'
scanf("%*[^X]%nX%*[-]%n]%f", &n, &d, &f);
// n is the number of chars before 'X'
// d is the number of chars before ']'
// f is the frequency
// Calculate the tuned frequency
f = f * d / (d - n);
// Convert the frequency to logarithmic scale, relative to pitch A0
f=log(f)*17.3123-57.376;
// alternatively: f = log2(f / (440 / 16)) * 12;
// Round to nearest integer
n=d=f+.5;
// Calculate the note name ('A', 'B', etc), multipled by 12 for convenience
n=n%12*7+784;
printf("%c%d%c,%+2.0f cents\n", // output example: B4 ,-49 cents
n/12, // note name
(d+9)/12, // octave number
n%12/7*3+32, // if n%12 is large enough, it's '#' else ' ' (natural)
(f-d)*100); // number of cents; stdio rounds it to integer
}
```
[Answer]
# BBC Basic, 161#
```
REM get frequency and string. Store length of string in n for later.
INPUT f,s$
n=LEN(s$)
REM store floating-point value of note in semitones above (C0-0.5). Store integer value in n% (offset effectively means it will be rounded not truncated.)
n=LN(f*(n-1)/(n-INSTR(s$,"X"))/15.8861)/LN(2)*12
n%=n
REM format printing to whole numbers only
@%=2^17
REM Output note name and octave. Output cents (discrepancy between n and n%, minus the offset of 0.5)
PRINT MID$("C C#D D#E F F#G G#A A#B ",n%MOD12*2+1,2);INT(n/12)'(n-0.5-n%)*100'
```
Score excludes comments. Not golfed yet.
**Output**
Performs correctly on all test cases except the two long ones. For `Eb9` it seems there is one dash missing from the test case: There are 22 `-` and one `X`, which divides the string into 24 equal pieces. According to my manual calculations, this is 9600Hz, which is 37 cents above a D9. This is exactly what my program outputs. If I add another dash I get Eb9 + 8 cents. Unfortunately BBC Basic cannot handle strings over 255 characters, so the `Eb11` case gives an error.

[Answer]
# JavaScript (199)
Call it e.g. as `t('[X-]',314.1592)`
```
t=(s,f)=>{l=s.length-1;p='C C# D D# E F F# G G# A B H'.split(' ');n=12*Math.log2(f*l/(l-s.indexOf('X'))/16.3515978);m=n+.5|0;return p[m%12]+(n/12|0)+' '+((n-m)*100+.5|0)}
```
Fixed. (Since I live in europe I used B instead of Bb and H instead of B=)
[Answer]
# Python 3: 175
```
import math
def t(b,s):l=len(s)-1;n=12*math.log2(b*l/(l-s.index("X"))/16.35);m=round(n);return"%s%s%+d"%(("C C# D D# E F F# G G# A A# B".split()*99)[m],m//12,round(100*(n-m)))
```
Ungolfed:
```
import math
c0 = 16.35
def tuning (base_frequency, string):
return formatted (note_number (frequency (base_frequency, string)))
def formatted (note_number):
return "{name}{octave:d}{cents:+d}".format (name=note_name (note_number),
octave=octave (note_number),
cents=cents_out (note_number))
def note_name (note_number):
return ("C C# D D# E F F# G G# A A# B".split() * 99)[round (note_number)]
def note_number (frequency):
return 12 * math.log2 (frequency / c0)
def octave (note_number):
return round (note_number) // 12
def cents_out (note_number):
return round (100 * (note_number - round (note_number)))
def frequency (base_frequency, string):
string_length = len (string) - 1
held_length = string_length - string.index ("X")
return base_frequency * string_length / held_length
if "__main__" == __name__:
print ("Testing functions against known values...")
assert "A4+0" == tuning (220, "[-----X-----]")
assert "A5+0" == tuning (220, "[--------X--]")
assert "D5-2" == tuning (440, "[--X--------]")
assert "B4-49" == tuning (440, "[X----------]")
assert "A#4+19" == tuning (314.1592, "[X-]")
assert "D#9+8" == tuning (400, "[-----------------------X]")
assert "D#11+8" == tuning (100, "[--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------X]")
assert "D#1+49" == tuning (10, "[--X]")
assert "A0-11" == tuning (11.7103, "[---X--]")
print ("Tests passed.")
```
] |
[Question]
[
You should get string of chemical equation (no spaces, only letters (upper-case and lower-case), numbers, brackets and math signs) from user and print the answer if equation is **balanced** or not (any pair of positive/negative answers: Yes/No, true/false, 1/0). To make code shorter you can assume that input strings can contain only these elements: Al, Ar, B, Be, C, Cl, Cr, Cu, Fe, H, He, K, N, O, S. And **one more thing**: there could be `-` signs. It's all about math: `+` means addition, `-` means subtraction.
Examples:
*Input:*
```
C6H5COOH-O2=7CO2+3H2O
```
*Output:*
```
No
```
---
*Input:*
```
2Fe(CN)6+2SO2+202=Fe2(SO4)2+6C2N2
```
*Output:*
```
Yes
```
---
*Input:*
```
2SO2=2SO4-2O2
```
*Output:*
```
Yes
```
The shortest code wins.
[Answer]
# Mathematica 152
```
f=Times@@@Tr@CoefficientRules@ToExpression@(r=StringReplace)[r[
#<>")",{"="->"-(",x:_?LetterQ|")"~~y_?DigitQ:>x<>"^"<>y}],x_?UpperCaseQ:>" "<>x]⋃{}=={0}&
```
Result:
```
f@"C6H5COOH-O2=7CO2+3H2O"
f@"2Fe(CN)6+2SO2+2O2=Fe2(SO4)2+6C2N2"
f@"2SO2=2SO4-2O2"
```
>
> False
>
>
> True
>
>
> True
>
>
>
I treat the chemical formula as a polynomial, e.g.

Then I just count the coefficients.
[Answer]
## Python 2.7, 316 276 chars
```
import re
r=re.sub
x='(^|[=+-])'
y=r'\1+\2'
z='(\w)([A-Z(])'
t=r('=','==',r(z,y,r(z,y,r('([A-Za-z)])(\d)',r'\1*\2',r('([=+-]|$)',r')\1',r(x+'(\d+)',r'\1\2*(',r(x+'([A-Z])',r'\1(\2',raw_input())))))))
E=re.findall('[A-Za-z]+',t)
print all(eval(t,{f:f==e for f in E})for e in E)
```
It does a lot of regex-rewriting to convert the input equation into something `eval`able. Then it checks the equation for each element individually.
For instance, the example equations rewrite to (the `t` variable):
```
(C*6+H*5+C+O+O+H)-(O*2)==7*(C+O*2)+3*(H*2+O)
2*(Fe+(C+N)*6)+2*(S+O*2)+2*(O*2)==(Fe*2+(S+O*4)*2)+6*(C*2+N*2)
2*(S+O*2)==2*(S+O*4)-2*(O*2)
```
I'm sure there's more golf to be had on the regex part.
[Answer]
## Haskell, ~~400~~ ~~351~~ 308 characters
```
import Data.List
import Text.Parsec
(&)=fmap
r=return
s=string
l f b=(>>=(&b).f)
x=(=<<).replicate
m=sort&chainl1(l x(concat&many1(l(flip x)n i))n)((s"+">>r(++))<|>(s"-">>r(\\)))
i=between(s"(")(s")")m<|>(:[])&(l(:)(many lower)upper)
n=option 1$read&many1 digit
main=getContents>>=parseTest(l(==)(s"=">>m)m)
```
This just might have all the golf squeezed out of it. I don't know if there is another ~~100~~ ~~51~~ 8 characters to be saved!
```
& echo 'C6H5COOH-O2=7CO2+3H2O' | runhaskell Chemical.hs
False
& echo '2Fe(CN)6+2SO2+2O2=Fe2(SO4)2+6C2N2' | runhaskell Chemical.hs
True
& echo '2SO2=2SO4-2O2' | runhaskell Chemical.hs
True
```
Here's the ungolf'd version, in case anyone want to follow along. It is a simple `Parsec` based parser:
```
import Control.Applicative ((<$>), (<*>))
import Data.List
import Text.Parsec
import Text.Parsec.String (Parser)
type Atom = String
{- golf'd as x -}
multiple :: Int -> [Atom] -> [Atom]
multiple n = concat . replicate n
{- golf'd as m -}
chemicals :: Parser [Atom]
chemicals = sort <$> chainl1 molecules op
where
op :: Eq a => Parser ([a] -> [a] -> [a])
op = (char '+' >> return (++))
<|> (char '-' >> return (\\))
molecules :: Parser [Atom]
molecules = multiple <$> number <*> terms
terms :: Parser [Atom]
terms = concat <$> many1 term
term :: Parser [Atom]
term = flip multiple <$> item <*> number
{- gofl'd as i -}
item :: Parser [Atom]
item = between (char '(') (char ')') chemicals
<|> (:[]) <$> atom
where
atom :: Parser Atom
atom = (:) <$> upper <*> many lower
{- gofl'd as n -}
number :: Parser Int
number = option 1 $ read <$> many1 digit
{- gofl'd as main -}
main :: IO ()
main = getContents >>= parseTest chemEquality
where
chemEquality :: Parser Bool
chemEquality = (==) <$> chemicals <*> (char '=' >> chemicals)
```
] |
[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 1 year ago.
[Improve this question](/posts/10520/edit)
Print, on STDOUT, a pattern which shows in what direction a bouncing ball will take.
The following assumptions are made:
* The ball starts at the top left corner: `0, 0` with zero initial velocity.
* Gravity is `9.8ms^-2` exactly, towards the floor (y positive.)
* The ball weighs `500g` exactly.
* The ball bounces at 45 or 135 degrees to the floor *unless* you want to add the appropriate calculations to add variable trajectories. (Bonus arbitrary points!)
* The ball has a spring constant coefficient of restitution/bouncyness constant of `0.8` exactly.
* The ball is perfectly spherical and does not deform when it bounces.
* The room is 25 characters high, 130 characters wide. Each x and y is 1 metre and each ball position represents a discrete sample -- the exact time period is deliberately unspecified, but the display should make the ball's path sufficiently clear. The output should show the path of the ball, not just the final position.
* The floor and ball should be indicated using characters on STDOUT, which may be the same. The presence of no ball or floor surface shall be indicated with a space character.
* You are allowed to assume rounding to three decimal places in any calculations. (Solutions using purely integers may be particularly interested in this rule.)
* The simulation stops when either the ball does not move from the floor or it leaves the room (`x > width of area`.)
* The program must simulate the ball's path, not simply load it from a file or have it encoded somehow in the program. The test for this will be to optionally change one of the constants. If the program does not calculate a new, correct result, then it does not qualify.
Example output:
```
*
*
*
*
*
*
*
*
*
* ***********
* ***** ****
* **** ***
* *** ***
* ** **
* *** **
* ** ** *********
* * ** **** ****
* ** * ** **
* * ** ** **
* * * ** ** ********
* ** * ** ** **** ****
* * ** ** ** ** **
* * ** ** ** ** ** **
** ** ** ** ** ** **
* **** **** ***
**********************************************************************************************************************************
```
**Determination of winner.** I will accept the answer which:
1. Meets the rules as defined above.
2. Bonus featureness will be considered.
3. Is the shortest and most elegant (subjective decision.)
[Answer]
## Python 143 bytes
```
u=v=x=y=0
a=[[s]*130for s in' '*24+'*']
while x<129:
if y+v>24:v*=-.8;u=-v
v+=98e-4;x+=u;y+=v;a[int(y)][int(x)]=s
for r in a:print''.join(r)
```
The resulting curve is slightly different than the example, but this is because the velocity is adjusted before the ball goes into the floor, instead of after it already has.
```
*
*
*
*
*
*
*
*
*
* ***************
* **** ****
* *** ***
* ** **
* *** **
* ** ** ******
* ** ** **** *****
* * ** *** ***
* ** ** ** **
* * * ** ** *********
* * ** ** ** *** ***
* * ** ** ** *** ** *****
* * ** ** ** ** ** *** ***
** ** ** ** ** ** **
* *** ** ***
**********************************************************************************************************************************
```
---
## Python 132 bytes
A more realistic version, that starts with a constant *x* velocity:
```
v=x=y=0
a=[[s]*130for s in' '*24+'*']
while x<129:v=(y+v<24or-.8)*v+98e-4;x+=.3;y+=v;a[int(y)][int(x)]=s
for r in a:print''.join(r)
```
Produces:
```
****
**
***
**
**
**
**
*
*
** *********
* ** **
* ** **
** ** **
* ** **
** ** ** *****
* ** ** *** ****
* * ** ** **
** * * ** **
* ** * * ** *******
* * ** ** ** *** **
* * * * ** ** ** *******
* ** * * * ** ** *** *** ****
** *** * * ** ** ** **** ****
** ** ** *** *** *****
**********************************************************************************************************************************
```
[Answer]
I'll submit my own solution in Python. Only slightly simplified; I'm sure there are much better ways of doing it! **282 280 characters.** The example output in the question post was generated using this program.
```
import sys;o=sys.stdout.write
py=px=vy=vx=0;g=98e-4;h=25;w=130;k=.8;p=[]
while 1:
vy+=g;py+=vy;px+=vx
if py>h:vy=-vy*k;vx=-vy
if px>w:break
p.append([int(px),int(py)])
py=0
while py<=h:
px=0
while px<w:
if [px,py] in p or py==h:o('*')
else:o(' ')
px+=1
o('\n');py+=1
```
] |
[Question]
[
Your task is to write a program, in any language, that adds two floating point numbers together WITHOUT using *any* fractional or floating point maths. Integer maths is allowed.
**Format**
The format for the numbers are strings containing 1's and 0's which represent the binary value of a [IEEE 754 32-bit float](http://en.wikipedia.org/wiki/Single_precision_floating-point_format). For example the number 2.54 would be represented by the string "01000000001000101000111101011100".
**Goal**
You program should input two numbers in the above mentioned format, add them together, and output the result in the same format. The shortest answer in any language wins!
**Rules**
Absolutly no floating point, decimal, or any kind of non-integer maths functions are allowed.
You can assume that the input is clean (i.e. contains only 1's and 0's).
You can assume that the inputs are numbers, and not Inf, -Inf, or NaN or subnormal. However, if the result is greater than the max value or smaller than the min value, you should return Inf and -Inf respectively. A subnormal (denormal) result may be flushed to 0.
You do not have to handle rounding properly. Don't worry if your results are a few bits out.
**Tests**
To test your programs, you can convert between decimal and floating point binary numbers using [this tool](https://www.h-schmidt.net/FloatConverter/IEEE754.html).
1000 + 0.5 = 1000.5
```
01000100011110100000000000000000 + 00111111000000000000000000000000 = 01000100011110100010000000000000
```
float.MaxValue + float.MaxValue = Infinity
```
01111111011111111111111111111111 + 01111111011111111111111111111111 = 01111111100000000000000000000000
```
321.123 + -123.321 = 197.802
```
01000011101000001000111110111110 + 11000010111101101010010001011010= 01000011010001011100110101010000
```
Good luck!
[Answer]
## Python, 224 chars
This code converts a floating point input `f` to the integer `f*2^150`, does the addition using python native big integers, then converts back.
```
V=lambda x:((-1)**int(x[0])<<int(x[1:9],2))*int('1'+x[9:],2)
B=lambda x,n:B(x/2,n-1)+'01'[x&1]if n else''
def A(x,y):
v=V(x)+V(y)
s=e=0
if v<0:s=1;v=-v
while v>=1<<24:v/=2;e+=1
if e>254:v=0
return'%d'%s+B(e,8)+B(v,23)
```
[Answer]
# J (172 characters)
Since IEEE 754 allows five rounding rules, I chose the "toward 0" rule. Here is my code:
```
b=:(_1&^)@".@{.*[:#.1x,("."0)@(9&}.),#.@:("."0)@}.@(9&{.)$0:
a=:b@[([:,(<&0)":"0@:,,@((8$2)&#:)@(-&24)@$@#:,}.@(24&{.)@#:@|)@(]`(**2x^278"_)@.((>&((2x^278)-2x^254))@|))@+b@]
```
The very same examples you give (but not exactly the same results because of the different rounding rule):
```
'01000100011110100000000000000000' a '00111111000000000000000000000000'
01000100011110100010000000000000
'01111111011111111111111111111111' a '01111111011111111111111111111111'
01111111100000000000000000000000
'01000011101000001000111110111110' a '11000010111101101010010001011010'
01000011010001011100110101001111
```
] |
[Question]
[
Your task is to convert Chinese numerals into Arabic numerals.
A problem similar to [Convert Chinese numbers](https://codegolf.stackexchange.com/questions/97734/convert-chinese-numbers), however, more complex. Also, answers given there mostly don't satisfy all the conditions.
Chinese digits/numbers are as follows:
`0 零` `1 一` `2 二` `2 两` `3 三` `4 四` `5 五` `6 六` `7 七` `8 八` `9 九` `10 十` `100 百` `1000 千` `10000 万` `10^8 亿`
### Multiple-digit numbers
Multiple-digit numbers are created by adding from highest to lowest and by multiplying from lowest to highest. In case of additions, each number higher than 9 can be multiplied by 1 and it won't change its meaning. Both `亿万千百十一` and `一亿一万一千一百一十一` are equal to `100011111`.
We multiply in the following fashion: `五千 = 5000` `一百万 = 1000000` `三千万 = 30000000`.
Chinese always takes the lowest possible multiplier (just like we don't say hundred hundred but ten thousand). So `百千` doesn't exist to represent `100000` since we have `十万`, `十千` doesn't exist since we have `万`, `十千万` doesn't exist, since we have `亿`, `十百` doesn't exist, since we have `千`.
### Special cases
`0` is very important and it was actually the biggest problem in the other code golf question. Trailing zeroes are omitted in Chinese, so `零` indicates interior zeroes.
Let's look at some examples:
* `三百零五 = 305`
* `三百五 = 350` - no interior zeroes. You can notice that we don't need `十` here, since a trailing zero is omitted.
* `一千万零一百 = 10000100`
* `三千零四万 = 30040000`
* `六亿零四百零二 = 600000402` - here we have 2 interior zeroes. As you can see though, even if there's a gap of more than one order of magnitute (in the example it's `亿` and `百`), two `零s` can't stand next to each other, one is enough for each gap, no matter how big it is.
* `一亿零一 = 100000001` - again, no need for more than one `零` if there's one gap, no matter how big.
* `八千万九千 = 80009000` - no need for `零` since there are no interior zeroes. Why are there no interior zeroes? Because it follows the highest-to-lowest addition without omitting an order of magnitude. Right after `万` we have `千` (`九` is a multiplication component, not addition one) and not, let's say, `百`.
More examples: [Check out the two "示例" paragraphs](https://kknews.cc/education/53p9ar8.html)
`2` is also special in Chinese as it can be represented with a character `两` if it's a multiplier of 100 and higher numerals. Both `两千两百二十二` and `二千二百二十二` are `2222`.
## Rules
~~Constraints: 0 <= N < 10^9~~
Edit: I don't care what happens from `10^9` onwards. Input doesn't have any examples equal or higher than `10^9` for that reason.
## Test cases
Input:
```
一亿两千三百零二万四千二百零三
四千万零一十
三十四万五千五
四亿二十万零九百零一
两千万九千零一十
二十四万零二百二十二
两千零十二
零
```
Output:
```
123024203
40000010
345500
400200901
20009010
240222
2012
0
```
Good luck!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~52~~ 51 bytes
```
0•9∊»£¬ƵçoiKβÐg•19вIÇƵª%èvX¨UOy¬iθ°UX‰¤_ªX*]DgiX*}O
```
[Try it online!](https://tio.run/##yy9OTMpM/a/03@BRwyLLRx1dh3YfWnxozbGth5fnZ3qf23R4QjpQwtDywibPw@3Hth5apXp4RVnEoRWh/pWH1mSe23FoQ2jEo4YNh5bEH1oVoRXrkp4ZoVXr/19HKeTwdL2w/092NDzZtf/JjiVPe5uf7Oh8PnPfy9nbnuzqebKj/ens2SDBXT1QwR2dXFChHe1gfsPT3kYuoDCQAkoARZ/smgLWMQWkEGTsrh6gHFT5zrkwcxq4YPa1A0WBDCTTwDogpkEcAtQENWZXD1QfUALKB7KAYg1ANVxIjp8CAA "05AB1E – Try It Online")
```
0 # literal 0
•9∊»£¬ƵçoiKβÐg•19в # compressed list [2, 14, 0, 3, 0, 8, 0, 6, 2, 9, 0, 18, 0, 1, 0, 13, 5, 0, 10, 0, 0, 7, 12, 4]
IÇ # codepoints of the input
Ƶª% # modulo 270
è # index into the above list, with wraparound
v ] # for each number y in that list:
X # push the variable X
¨ # drop the last digit
U # store that in X
O # sum all numbers on the stack
y # push y
¬i ] # if the first digit of y is 1:
θ° # 10**(the last digit of y)
U # store that in X
X‰ # divmod X
¤_ª # if the modulo is 0, append 1
X* # multiply by X
Dgi } # if length of the top of stack is 1:
X* # multiply it by X
O # sum of the stack
# implicit output
```
] |
[Question]
[
A [flow network](https://en.wikipedia.org/wiki/Flow_network) is a directed graph `G = (V, E)` with a source vertex `s ϵ V` and a sink vertex `t ϵ V`, and where every edge `(u, v) ϵ E` on the graph (connecting nodes `u ϵ V` and `v ϵ V`) has 2 quantities associated with it:
1. `c(u, v) >= 0`, the capacity of the edge
2. `a(u, v) >= 0`, the cost of sending one unit through the edge
We define a function `0 <= f(u, v) <= c(u, v)` to be the number of units being passed through a given edge `(u, v)`. Thus, the cost for a given edge `(u, v)` is `a(u, v) * f(u, v)`. The [minimum-cost flow problem](https://en.wikipedia.org/wiki/Minimum-cost_flow_problem) is defined as minimizing the total cost over all edges for a given flow amount `d`, given by the following quantity:
[](https://i.stack.imgur.com/YAivn.png)
The following constraints apply to the problem:
1. **Capacity requirements**: the flow through a given edge may not exceed the capacity of that edge (`f(u, v) <= c(u, v)`).
2. **Skew symmetry**: the flow though a given edge must be antisymmetric when the direction is reversed (`f(u, v) = -f(v, u)`).
3. **Flow conservation**: the net flow into any non-sink non-source node must be 0 (for each `u ∉ {s, t}`, summing over all `w`, `sum f(u, w) = 0`).
4. **Required flow**: the net flow out of the source and the net flow into the sink must both equal the required flow through the network (summing over all `u`, `sum f(s, u) = sum f(u, t) = d`).
Given a flow network `G` and a required flow `d`, output the minimum cost for sending `d` units through the network. You may assume that a solution exists. `d` and all capacities and costs will be non-negative integers. For a network with `N` vertices labeled with `[0, N-1]`, the source vertex will be `0` and the sink vertex will be `N-1`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. Remember that this is a competition within languages as well as between languages, so don't be afraid to post a solution in a verbose language.
Built-ins are allowed, but you are encouraged to include solutions without builtins, either as an additional solution in the same answer, or as an independent answer.
Input may be in any reasonable manner that includes the capacities and costs of each edge and the demand.
## Test Cases
Test cases are provided in the following format:
`c=<2D matrix of capacities> a=<2D matrix of costs> d=<demand> -> <solution>`
```
c=[[0, 3, 2, 3, 2], [3, 0, 5, 3, 3], [2, 5, 0, 4, 5], [3, 3, 4, 0, 4], [2, 3, 5, 4, 0]] a=[[0, 1, 1, 2, 1], [1, 0, 1, 2, 3], [1, 1, 0, 2, 2], [2, 2, 2, 0, 3], [1, 3, 2, 3, 0]] d=7 -> 20
c=[[0, 1, 1, 5, 4], [1, 0, 2, 4, 2], [1, 2, 0, 1, 1], [5, 4, 1, 0, 3], [4, 2, 1, 3, 0]] a=[[0, 1, 1, 2, 2], [1, 0, 2, 4, 1], [1, 2, 0, 1, 1], [2, 4, 1, 0, 3], [2, 1, 1, 3, 0]] d=7 -> 17
c=[[0, 1, 4, 5, 4, 2, 3], [1, 0, 5, 4, 3, 3, 5], [4, 5, 0, 1, 5, 5, 5], [5, 4, 1, 0, 3, 2, 5], [4, 3, 5, 3, 0, 4, 4], [2, 3, 5, 2, 4, 0, 2], [3, 5, 5, 5, 4, 2, 0]] a=[[0, 1, 4, 2, 4, 1, 1], [1, 0, 3, 2, 2, 1, 1], [4, 3, 0, 1, 4, 5, 2], [2, 2, 1, 0, 2, 2, 3], [4, 2, 4, 2, 0, 4, 1], [1, 1, 5, 2, 4, 0, 2], [1, 1, 2, 3, 1, 2, 0]] d=10 -> 31
c=[[0, 16, 14, 10, 14, 11, 10, 4, 3, 16], [16, 0, 18, 19, 1, 6, 10, 19, 5, 4], [14, 18, 0, 2, 15, 9, 3, 14, 20, 13], [10, 19, 2, 0, 2, 10, 12, 17, 19, 22], [14, 1, 15, 2, 0, 11, 23, 25, 10, 19], [11, 6, 9, 10, 11, 0, 14, 16, 25, 4], [10, 10, 3, 12, 23, 14, 0, 11, 7, 8], [4, 19, 14, 17, 25, 16, 11, 0, 14, 5], [3, 5, 20, 19, 10, 25, 7, 14, 0, 22], [16, 4, 13, 22, 19, 4, 8, 5, 22, 0]] a=[[0, 12, 4, 2, 9, 1, 1, 3, 1, 6], [12, 0, 12, 16, 1, 2, 9, 13, 2, 3], [4, 12, 0, 2, 2, 2, 2, 10, 1, 1], [2, 16, 2, 0, 2, 1, 8, 4, 4, 2], [9, 1, 2, 2, 0, 5, 6, 23, 5, 8], [1, 2, 2, 1, 5, 0, 13, 12, 12, 1], [1, 9, 2, 8, 6, 13, 0, 9, 4, 4], [3, 13, 10, 4, 23, 12, 9, 0, 13, 1], [1, 2, 1, 4, 5, 12, 4, 13, 0, 13], [6, 3, 1, 2, 8, 1, 4, 1, 13, 0]] d=50 -> 213
```
These test cases were computed with the [NetworkX Python library](https://networkx.github.io/).
[Answer]
# [R + [lpSolve](https://cran.r-project.org/web/packages/lpSolve)], ~~201~~ ~~186~~ ~~149~~ 144 bytes
```
function(c,a,d,`^`=rep,N=ncol(c),G=diag(N),P=t(1^N),M=P%x%G+G%x%-P)lpSolve::lp(,a,rbind(M,diag(N*N)),c('=','<')^c(N,N*N),c(d,0^(N-2),-d,c))$objv
```
[Try it online!](https://tio.run/##lVbfb9owEH7nr8hDq9ibkWI7CQQ1jxNPRUjtW1dU6oQuUxQQZFWlaX87s322oWBnGgqJ8d35vvvuB9kfN@Vx86sTfbPtkCBrUpGX1Uu5r3dkUXZi2yKBybysmvUbWmCyLHtEV3JxXy5vP27nX@fyPl7idvewbd/r2azdIXnI/rXpKnRPwOzLAmMiUFzGJL6L8UqgBVGbcq8iyQotxgyTcUUExjfb15/vx74@9Ifobhy1zaFHI7hH8iNKOFmghEScRAzumGip/QgkN6VCpqX8Ssq0SCqkcuGz5VqkFHy2XJsrBWzE63NYVF9Sj14ZU30oSLlPCgrMFxKDfa3gtXV0OFhVOYFF/bGrRV9XJUukKMQn@M98UTtcqQ8atbioL2jgigaAp0DVZ@B@PtkgLPqfsNggLGb9DvNJJ8N8prZUQglPrAJUXebjJ7NBZHANM6x9ec/htiOg8gdqm9n693ZWZi@IK5i11KUm3AvcVrVXJ7VwHZWhvjg1TrjIUlsPoWqh/wrelSK3i7PaoMlFcXDrJFggufwqMIl5UlhD2DTHJLoEkAMdU/ktNIbcmBe2c69MUtAHeqhUKuB4RYey5B4bcyJzZmpDPSdGwAKOwINpO0WRSnBmMV4TChEURsHMxxSoYf5RlIAyB0TMhGLMJb6pL/2arRQC0HjyT@6yQJ0zQ4RyqMwmzhnzVEcOpaVCZmAnf07hoHCjuMoszmaO4uXageGVGfzOiofrnrKzzmCnZAZGoubdZV2jTwNTv3Bz2Y6xHNKR@XJAzxrdDDSTQRr6q4QCnEKNwxwoApOLm@OgeZg5uTj5CeBxc8Vkwbih11TmZ00/tYbUWJyGQHY5BJg8a4RHo812j5qo6SI6a@vurf@B9EsOxr@Vvlqr9x299/TUPD@rXbHuUfz47eExJg1Rb08bbXQjiH6s4VFhEjt/kdTSu3aDxN@7GI/@jI5/AQ "R – Try It Online")
The code constructs the following Linear Problem and solve it using `lpSolve` package :
$$
\begin{align}
min & \sum\_{\forall x \in V}\ \sum\_{\forall y \in V} A\_{x,y} \cdot f\_{x,y} \\
subject\ to : & \\
& \sum\_{x \in V} f\_{v,x} - f\_{x,v} = 0 & \forall v \in V : v \neq \{s,t\} \\
& \sum\_{x \in V} f\_{s,x} - f\_{x,s} = d \\
& \sum\_{x \in V} f\_{t,x} - f\_{x,t} = -d \\
& f\_{x,b} \leq C\_{x,b} & \forall x \in V,\forall y \in V
\end{align}
$$
where :
* \$V\$ is the set of vertices
* \$s\$ s is the source vertex
* \$t\$ s is the target (or sink) vertex
* \$A\_{x,y}\$ is the flow cost for edge `x -> y`
* \$f\_{x,y}\$ is the flow of edge `x -> y` in the optimal solution
* \$d\$ is the required flow at sink (i.e. the demand at \$t\$ and the production at \$s\$)
* \$C\_{x,y}\$ is the maximum capacity of edge `x -> y`
[Answer]
# Wolfram Language, 42 bytes
```
FindMinimumCostFlow[#,1,VertexCount@#,#2]&
```
Trivial builtin. Non-builtin solution coming soon.
[Answer]
# Python 3 + [NetworkX](https://networkx.github.io/), 137 bytes
```
from networkx import*
def f(g,d,z='demand'):N=len(g)**.5//1;G=DiGraph(g);G.node[0][z]=-d;G.node[N-1][z]=d;return min_cost_flow_cost(G)
```
No TryItOnline link because TIO doesn't have the NetworkX library installed
Takes graph input as an edge list with capacity and weight attributes, like this:
```
[(0, 0, {'capacity': 0, 'weight': 0}), (0, 1, {'capacity': 3, 'weight': 1}), (0, 2, {'capacity': 2, 'weight': 1}), (0, 3, {'capacity': 3, 'weight': 2}), (0, 4, {'capacity': 2, 'weight': 1}), (1, 0, {'capacity': 3, 'weight': 1}), (1, 1, {'capacity': 0, 'weight': 0}), (1, 2, {'capacity': 5, 'weight': 1}), (1, 3, {'capacity': 3, 'weight': 2}), (1, 4, {'capacity': 3, 'weight': 3}), (2, 0, {'capacity': 2, 'weight': 1}), (2, 1, {'capacity': 5, 'weight': 1}), (2, 2, {'capacity': 0, 'weight': 0}), (2, 3, {'capacity': 4, 'weight': 2}), (2, 4, {'capacity': 5, 'weight': 2}), (3, 0, {'capacity': 3, 'weight': 2}), (3, 1, {'capacity': 3, 'weight': 2}), (3, 2, {'capacity': 4, 'weight': 2}), (3, 3, {'capacity': 0, 'weight': 0}), (3, 4, {'capacity': 4, 'weight': 3}), (4, 0, {'capacity': 2, 'weight': 1}), (4, 1, {'capacity': 3, 'weight': 3}), (4, 2, {'capacity': 5, 'weight': 2}), (4, 3, {'capacity': 4, 'weight': 3}), (4, 4, {'capacity': 0, 'weight': 0})]
```
This is a golfed version of the code that I used to verify the test cases.
] |
[Question]
[
In this challenge, you will write an interpreter for **2Ω** (transcribed as **TwoMega**), a language based loosely on [brainfuck](https://esolangs.org/wiki/Brainfuck) with an infinite-dimensional storage space.
## The Language
2Ω contains three pieces of state:
* The **Tape**, which is an infinite list of bits, all initialized to 0. It has a leftmost element, but no rightmost element.
* The **Memory Pointer**, which is a nonnegative integer that is an index of an element in the tape. A higher memory pointer refers to a tape cell further to the right; a memory pointer of 0 refers to the leftmost element. The memory pointer is initialized to 0.
* The **Hypercube**, which is a conceptually **∞**-dimensional "box" of cells, each of which contains a bit initialized to 0. The width of the Hypercube is bound in every dimension to only 2 cells, but the infinity of dimensions means the number of cells is [uncountable](https://en.wikipedia.org/wiki/Uncountable_set).
An **index** into the hypercube is an infinite list of bits that refers to a cell in the hypercube (in the same way that a finite list of bits could be used to refer to a hypercube of finite dimension). Because the tape is an infinite list of bits, the entire tape always refers to an element of the Hypercube; this element is called the **referent**.
2Ω gives meaning to 7 different characters:
* `<` decrements the memory pointer by 1. Decrementing it below 0 is undefined behavior, so you do not need to handle it.
* `>` increments the memory pointer by 1.
* `!` flips the bit at the referent.
* `.` outputs the bit at the referent.
* `^` replaces the bit at the cell pointed to by the memory pointer on the tape with the *inverse* of the bit at the referent.
* `[x]` runs the code `x` as long as the bit at the referent is 1.
## The Challenge
Your task is to write a program that takes a string as input and executes that input as a 2Ω program.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (measured in bytes) wins.
## Notes
* You can assume that the program will consist solely of the characters `<>!.^[]` and that `[]` will be properly nested.
* Your interpreter should only be limited by available memory on the system. It should be able to run the sample programs in a reasonable amount of time.
## Sample Programs
Print 1:
```
!.
```
Print 010:
```
.!.!.
```
Print 0 forever:
```
![!.!]
```
Print 0 forever, or 1 forever if `!` is prepended:
```
[.]![!.!]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 167 bytes
```
t=h=I=0
m=1
E=''
for c in input():i='[<>!.^]'.find(c);E+=' '*I+'while+2**t&h: m/=2 m*=2 h^=2**t print+(2**t&h>0) t=t&~m|m*(2**t&h<1) #'.split()[i]+'\n';I-=~-i/5
exec E
```
[Try it online!](https://tio.run/##LY7LCoMwFET3fsWtBa8m@IRu1OvOhd9gdWOVBEwUm9IWir9ulRaGszgMzMxvIyadbJshQRVFlqLYKgnRGqYFOpB6z/wwrpdKwjovTkHbYDBIfXM7Lys5ISCrOD6FHHueMGYckYIKKQHFdoiWDgnzIrXh7q9QRB4YMs6qPor9XR57cMbgPo9yX6tlw/GqMat8Wn0ZXqz@1XdQbpu9PwhO9YHG/gI "Python 2 – Try It Online")
**t** is the tape. **t = 6** means the tape is [0 1 1 0 0 0 …]
**m** is 2 to the power of the memory pointer. So **m = 8** means we're pointing at tape bit 3.
**h** is the hypercube. **h = 80** (bits 4 and 6 set) means the bits at [0 0 1 0 …] and [0 1 1 0 …] are set.
To read the bit at the referent, we check **2t & h**. To flip it, we perform **h ^= 2t**.
We translate the instructions to Python code and execute the result. **I** stores the indentation level of the while loops.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 148 bytes
```
x=>eval(x.replace(e=/./g,c=>({'<':'u/=2','>':'u*=2','!':'e[v]^=1','.':'alert(+!!e[v])','^':'v=(v|u)^u*e[v]','[':'while(e[v]){'}[c]||'}')+';',v=u=1))
```
[Try it online!](https://tio.run/##Hc1BDoMgEAXQfW/BakAtxi5rx6WXIJoQSqwNEaNCTdSzU3T3/8vPzFd6OaupH5f7YN86SKOnBZUdZms0N7a71RhWrLSXhq580qORSlONOc@7TGFFN3jBE1yOD8igOmNyRRKjFr5psYiNx3bdpikhJ7OIbUSP1O@OtS45NaKI@Pv0Jj45ZxscQjX7DgewFErIPDosGAtlTYEIwkkDLPwB "JavaScript (Node.js) – Try It Online")
# It's turing complete
```
BoolFuck TwoMega
< >^>^>[!]^<<<<[!]^>>[!]!^>[!]!^>[!]!^<<<<(>^>^>1<<<<1>>0>0>0<<<<)
> ^<^<[!]^>>>>[!]^<<[!]!^<[!]!^<[!]!^>>>(^<^<1>>>>1<<0<0<0>>>)
```
Need init as moving right few places and init the current and right one bit of the address as 1 (`>>>>>>>>^>^<`)
[Try it online!](https://tio.run/##TY69boQwEIT7PIVdrX1wRpcy2JRXpLgUKRGWLOIQIgtO/DgXAc9O1oQCF@uZb2Ytfxtv@rKr78O5aT/sapztBlW2Td86K1xbPV3V@lCZ9caxh@js3ZnSskQkVVyqjE0g4QXGRD1DDFmQp01SlDb3hVYXdALd9jKLKA2YI9QIvWJ@HrkeT4EizBH@fNXOsq02ISoQLbDkZTHPADyC9PA95qPX97eb6Ieubqr685dZHo08hdirUV1iq6aF8zW9Msj2ozMtCRFESy1zWujAwi2Do/o4MSEUq2Fn78h95z8/zBARAXz9Aw "JavaScript (Node.js) – Try It Online")
Place `n` in BoolFuck is written as `(0, 0, ..., 0(n*0), [1], 1, 0, 0, ...)`.
For `>`, it does `n` => `n+1`
```
0 0 0 0 0[1]1 0 0 0 0
^ 0 0 0 0 0[x]1 0 0 0 0
< 0 0 0 0[0]x 1 0 0 0 0
^ 0 0 0 0[y]x 1 0 0 0 0, yx != 01
< 0 0 0[0]y x 1 0 0 0 0
[!]^ 0 0 0[1]y x 1 0 0 0 0, (0yx10) = 0
>>>> 0 0 0 1 y x 1[0]0 0 0
[!]^ 0 0 0 1 y x 1[1]0 0 0, (1yx10) = 0
<< 0 0 0 1 y[x]1 1 0 0 0
[!]! 0 0 0 1 y[x]1 1 0 0 0, (1yx11) = 1
^ 0 0 0 1 y[0]1 1 0 0 0
< 0 0 0 1[y]0 1 1 0 0 0
[!]! 0 0 0 1[y]0 1 1 0 0 0, (1y011) = 1
^ 0 0 0 1[0]0 1 1 0 0 0
< 0 0 0[1]0 0 1 1 0 0 0
[!]! 0 0 0[1]0 0 1 1 0 0 0, (10011) = 1
^ 0 0 0[0]0 0 1 1 0 0 0
>>> 0 0 0 0 0 0[1]1 0 0 0
```
Same to how `<` work
[Answer]
# [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak), 816 bytes
```
<>(((<(())>)))<>{(([][][])(((({}){}[])({}))({})[]([][](({})(({}())(({}){}{}({}(<()>))<{<>({}<>)}{}>))))))(([]{()(<{}>)}{}){<((<{}>))<>(()(){[](<{}>)}{}<{({}[]<({}<>)<>>)}{}{}>)<>({()<({}<>)<>>}<<>{<>(({}){}<>({}<>)[])<>}{}<>({()<({}[]<<>({}<>)>)>}{})<>(({})<<>{({}[]<({}<>)<>>)}({}<>)<>{({}<>)<>}>)<>>)<>({}<>)<>>}{}([]{()(<{}>)}{}){{}<>({})(<>)}{}([]{()(<{}>)}{}){(<{}<>({}<{((<({}[])>))}{}{((<(())>))}{}>)<>>)}{}([]{()(<{}>)}{}){(<{}<>({}<({}())>)<>>)}{}([]{()(<{}>)}{}){(<{}<>[({})]<>>)}{}([]{()(<{}>)}{})<{((<{}>))<>{}({}<{<>(({}){}<>({}<>)[])<>}{}<>({()<({}[]<<>({}<>)>)>}{})<>(((){[](<{}>)}{})<<>{({}[]<({}<>)<>>)}{}(<>)<>{({}<>)<>}>)<>>)<>({}<>)<>}{}(<>)<>{({}<>)<>}{}>()){((({}[]<>){(<{}({}<>)>)}{}())<{({}<({}<>)<>((((((([][][]){}){}){}()){}){}({})())[][])>{[](<{}>)}{}{()(<{}>)}{})}{}({}<>)>[]){{}(<>)}}{}}
```
[Try it online!](https://tio.run/##nVLLagMxDPyW3qRD@gXCP7I4sA0UQpcemqPQt7szsp1HkzZQ77IrS/LMSPLb13r83L1v60drVkTERFSLqlpxkaXyUfjFQz1ow8jPUjOcEX5wbmTBxmtCHHPAelhRuImrTFuqi4rREzwC1twoNaioA3dGzYXE1lGspJMxAote/GHQTIAUMWkh2Ur0fc8G1gziIf84xPN3XNP0aUQPTAgSo9qfFQ0BcKXjLk6zQzibnq1F/SztMoRR5jOE3vxnmQvl1F9yUsWYQI7P/t/J2/E97irvx99dfZACRNTpeRkBV3plkz@yC3lbzkzS17jGWY1mWv9zPqoZK9eab1oTZwpCdFUBZ7S2L1wvi@1fa9ut22FbT6fj4Rs "Brain-Flak – Try It Online")
This code was written just so I'd have a place to write a proof of Turing-completeness.
## Proof of Turing-completeness
We show a reduction from Boolfuck to TwoMega:
```
Boolfuck TwoMega
> >>
< <<
. !^!.!^!
[ !^![!^!
] !^!]!^!
+ !^[!]^[>!^<[!]!^>[!]!^<]
```
This translation stores the Boolfuck state in the even-numbered tape cells in TwoMega. All of the translated commands will preserve the following invariants:
* The memory pointer is at an even-numbered cell.
* All odd-numbered tape cells are zero.
* For any possible tape with all odd-numbered cells zero, the corresponding value on the hypercube is zero.
The snippet `!^!` will keep `[0]0` constant and swap between `0[0]` and `[1]1` (where attention is limited to the line on the hypercube reachable without moving the memory pointer). As such, it is used to temporarily put the current tape value into the referent for the Boolfuck commands which care about it.
If TwoMega were given an input command `,` with the expected semantics, the Boolfuck command `,` would translate to `>^<,!^>[!]!^<`. Since `,` is not necessary to prove that Boolfuck is Turing-complete, the lack of an input command does not affect this proof.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~297~~ ~~284~~ 274 bytes
*-10 bytes thanks to ovs and Jonathan Allan*
```
C=input()
h={}
t=set()
def f(C,p):
c=C[0];r=hash(frozenset(t));v=h.get(r,0)
p={"<":p-1,">":p+1}.get(c,p)
if'"'>c:h[r]=not v
if"."==c:print(int(v))
if"]"<c:t.discard(p)if v else t.add(p)
if"["==c:
while f(C[1:],p):1
else:return c=="]"and v or C and f(C[1:],p)
f(C,0)
```
[Try it online!](https://tio.run/##RY@7jsMgEEV7vmJME1C8lq3tSCaNP8NyYfFYkCKMMPFqN8q3O0CTYjSvM1d3wl@yq/8@jhGdD4/EOLH4fJGEmy6N0gYMG9vABQGJ49TPl4h22Swzcf3XvmCJ88uOtvvJdWx7TiDgk16pCF9DS285n4dX3cosRMCZEz3dpLBTnNGvCfYyox1FlCJE5xMrsfPK0plepUidcptcomKBOwM76PumIXWLKpPKTfWeAPxad9fF9jSIuVgfSMVF1OkRff4Ds@jiVZZZI4xQyg9OysM9P45marpmfgM "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~75~~ 71 bytes
```
lPB0aR:^"!><[].^_""!:_
--viPU0
++v
W_{
}
O_
i@v:!_LFBilPB0
l@FBi"^n;Vau
```
[Try it online!](https://tio.run/##K8gs@P8/J8DJIDHIKk5J0c4mOlYvLl5JSdEqnktXtywzINSAS1u7jCs8vpqrlss/nivTocxKMd7HzSkTpIsrxwHIUorLsw5LLP3//3@cHQgoRtvE6cUCAA "Pip – Try It Online")
Translates the 2Ω code into equivalent Pip code and evaluates it.
We use `i` to represent the tape, `v` for the tape pointer\*, and `l` for the hypercube. The first two come preinitialized to useful values; `l` starts as `[]`, to which we push a `0` (`lPU0`) to avoid indexing-empty-list problems.
\* Actually, it's the bitwise negation of the tape pointer, because we're storing the tape backwards for easier conversion to decimal.
The rest of the code is:
```
aR:...; Do a bunch of replacements in a, translating it into Pip code
Va Evaluate a
u Suppress output of the final expression that was evaluated
```
The translation table:
```
! !:_
> --viPU0
< ++v
[ W_{
] }
. O_
^ i@v:!_LFBilPB0
_ l@FBi
```
`l@FBi` is the referent: element of hypercube `l` at the index (convert `i` from binary). It appears often, so we call it `_` and replace `_` with the real code at the end.
* `!:_` logically negates the referent in place.
* `--viPU0` decrements `v` (moving the tape pointer to the right); it then pushes another `0` to the left side of `i`, to make sure that the tape pointer stays in bounds.
* `++v` increments `v` (no need for bounds-checking, per OP).
* `W_{` runs a loop while the referent is truthy (i.e. nonzero, i.e. `1`).
* `}` closes the loop.
* `O_` outputs the referent without newline.
Finally, for `^`:
```
i@v: Set the current tape cell to
!_ The logical negation of the referent
Now, make sure the list representing the hypercube is long enough:
LFBi Loop frombinary(i) times:
lPB0 Push another 0 to the end of l
This ensures that FBi will always be a valid index into l
```
] |
[Question]
[
The [coefficient of relationship](https://en.wikipedia.org/wiki/Coefficient_of_relationship#Human_relationships) refers to how much DNA two persons have in common. A parent has 50% common DNA with their child (unless the parents are related), so to calculate it we have to find all pairs of directed disjoint paths starting at same node (common ancestor) and ending at each of the two siblings, and sum 2^-(m+n) for all pairs of paths of length m and n.
Your program should accept a list of pairs of numbers (or names if you prefer) representing parent-child relations followed by another pair of number for which it should output the coefficient of relationship (either as a fraction, a decimal number, or a percentage).
For example:
```
Format: [list of parent-child relations] pair of relatives we want to compare -> expected output
-----------------------------------------------
[(1,2)] (1, 2) -> 50% (parent-child)
[(1,2), (2, 3), (3, 4)] (2, 3) -> 50% (still parent-child, make sure your path pairs are disjoint)
[(1,3), (2, 3)] (1, 2) -> 0% (not related, make sure your paths are directed)
[(1, 2), (2, 3)] (1, 3) -> 25% (grandparent-child)
[(1, 3), (1, 4), (2, 3), (2, 4)] (3, 4) -> 50% (siblings)
[(1, 2), (1, 3)] (2, 3) -> 25% (half-siblings)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5)] (4, 5) -> 25% (aunt/uncle-nephew/niece)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 6)] (5, 6) -> 12.5% (cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (5, 7), (5, 8), (6, 7), (6, 8), (3, 9), (7, 9), (4, 10), (8, 10)] (9, 10) -> 25% (double cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 5)] (3, 5) -> 75% (parent-(child-with-sibling) incest)
[(1, 2), (1, 3), (2, 3)] (1, 3) -> 75% ((parent-and-grandparent)-(child-with-child) incest)
```
No person will have more than two parents and there will be no cycles in it. You can also assume that the number is the order in which they were born (so `a < b` in all `(a, b)`).
[Answer]
# [Python 3](https://docs.python.org/3/), 259 247 226 bytes
```
lambda l,a,b:sum(2**-len({*m}^{*n})for v in{*sum(l,())}for m in p(v,a,l)for n in p(v,b,l)if not{*zip(m,m[1:])}&{*zip(n,n[1:])})
p=lambda i,j,l:sum([[[r+[i]for r in p(y,j,l)],[[y,x]]][j==y]for x,y in l if i==x],[])+[[i]]*(i==j)
```
[Try it online!](https://tio.run/##NY7LboMwEEX3/YpZVR5nIhVI85L8JY4rgdqoRraxXBpBEd9ObHBXZ@6dOw8/9t@dq5YgboupbfNZg6GamuvPr2Ul53vz5djE7fwxcTfjvQvwAO0mnvqGGOKcPBs98OwRR80acv9GEw19B9f1E//TnlmysrgqnF837chtGl@8yB9oasmsH0gpw05qlVaGbeWYmqhIypEGpZRshRjXwEBjihiI97QQQ8wo3Mk4rjiLRouLD9r1LDDJCoIKCRIPiWXWZdbvBKfMc@Ix62PWFcEl8ZR5ICjeUnFeC0XA2WUtEZcn "Python 3 – Try It Online")
This can probably be golfed down quite a bit, but for now I'm just happy it works.
[Answer]
# Python3, 206 bytes:
```
lambda l,a:(a in l)/2+sum(2**-len((x|y)-(x&y))for x in f(a[0],l,a)for y in f(a[1],l,a)if x&y)
def f(n,l,o,p=[],K=1):
for a,b in l:
if(b==n)&(K:=[a,b]!=o):yield from f(a,l,o,p+[b]);K=0
if K:yield{*p+[n]}
```
[Try it online!](https://tio.run/##pZFBbsIwEEX3OcVUlZANpo0dTCCVt2xyhNSLRBA1UnCilEpEbc@eeuxAqwoWtKv5/jP/zQTa/vDSmGjVdsNGPQ91vi@2OdQsT0gOlYGaPorZ69ueiOl0Xu8MIcePns7JcdJTWjYdHHGqJHkWamZjzutPHvdeVQLOB9tdaW1jvYa1KtMsVZwmAWAmZ4XbZ59QlaRQytAJSROV2Y6@Uw1N@mpXb6Hsmj3CPWWWFZo@pSoMbApSP/M@tb7Rn0PbVeZANiTLOAOhNQMvKIV7GQa/2rYrGERYIwYLfTYujUfnrmbf0KvMcbVnCXmBxXHljxPE6QR3y9WL@Ykubqd7uHTxBYq/xX166TASBWK4eLgFZHPxWFdYl@N7Ob7tojXWeKx2IQ9RrJxAtXbqP58g9dlATCyv/d4X/9VYDl8)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~188~~ ~~166~~ 154 bytes
```
e_~h~f_:=4Tr[2^-Tr[Length/@#]&/@Select[Flatten[Tuples[i@r_:=If[#==r,{{r}},FindPath[g,#,r,∞,All]];i/@f]&/@VertexList[g=Rule@@@e],1],DisjointQ@@Rest/@#&]]
```
[Try it online!](https://tio.run/##nVHdSsMwGL33KQqFXX0y@7tOKUSQgbCLOcduQhxlfm0jXZU0A6F01z6FD@eL1KTtysAqai56Tk@@c05IdpFMcRdJvo3qGjeH9BBvLkN3Jaj9cK6@c8wTmY6JyUZjco8ZbiWdZZGUmNPV/iXDgnIilOU2pmYYCihLUVUw4/njQkXTBEwQ8PH2DtdZxtgVH5NYR61RSHyd80LSJFzuMySEIAOLwQ0vnp55Lu8IWWIhVfWIsXohlETLlJalBYatKoyWMDB6UWk2GI5GBwy36gU1dHYcc3r1x4xuc8Br6eiTKvtY1XSejtt9yPcnGUxrw7zG5mryN1vr8hu7p8mv7Wp60mGg0e/@fR2gVtB1TDVOOlRd1oUmQUM0mzbsP6f2ql4YvsqvD1Sx@hM "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
### Challenge
Take a number and output it with 4 digits or less using letters and numbers. For example; `270,030` would turn into `270K`.
### Key
Billion -> `B`
Million -> `M`
Thousand -> `K`
### Rules
* You may choose to accept input numbers that include commas delimiting every three decimal places (such as `123,456,789`).
* Round to nearest, half-up.
* Numbers will only go up to `999,499,999,999` .
* The mantissa part of the answer should be at least 1.
* All letters must be uppercase and as specified above.
* Outputs must be 4 or less digits. (including letters such as `B`, `K`, and `M`)
* Outputs must be as mathematically precise as possible. Example:
+ `15,480` -> `20K` **NOT OK**
+ `15,480` -> `15.5K` **GOOD**
* If there are multiple outputs with the same mathematical precision, return either one. Example:
+ `1000` -> `1000` **GOOD**
+ `1000` -> `1K` **GOOD**
### Examples:
```
1,234,567 -> 1.23M
999,500 -> 1M
999,499 -> 999K
102 -> 102
1000 -> 1K
1001 -> 1001
100,000 -> 100K
12,345,678,912 -> 12.3B
1,452,815,612 -> 1.45B
```
### Submissions
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in each language wins
* [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
[Answer]
# JavaScript, ~~84~~ 79 bytes
```
i=>{I=i;for(x=-1;i>=999.5;x++)i/=1e3;return I<1e4?I:+i.toPrecision(3)+'KMB'[x]}
```
[Try it online!](https://tio.run/##XZFPj4IwEMXvfIrZU2moXcofFdm6iYkHY0z27npgsbg1LCUFDYnxs7MVUBO5dN7M/N6bhGNyTqpUy7IeFWov2oy3ks8vKy7jTGm74SMWyzmPooiGceM4WL5zJvxYi/qkC1h9MBF8rmaOpLX60iKVlVSF7WMHrTcLtG1217bUKhVVRRN9OG@9Ha3KXNY2@i4QpiZjmaS/dgN8DhcLzCczsN8aDH1C3PVyUcM5yU@CQHH6@xGagGhKkdZiHz@gBnfl9nVjBxyaeyqM5oBwD6WqqFQuaK4OduduFjPb6fk7QMyVRyULGyGM8TOtB974IwYP9786o6XWSoMqoNTiLNWporAcmBkgcJ4OvfvVuuK4bRnx/ICE48ntZEY9f2OZv0BC1@0avQqi6KZMubaY63UT1zPlsGXem2CDYDdBnkMDecQPQjKeTEnEet6j/sJiJAg9MmVmNLRpEC7@AQ "JavaScript – Try It Online")
(Takes inputs as numbers)
Special cases the first one where if `i < 1000`, the number itself is always one of the shortest ways, if not the only shortest way.
Otherwise, it divides it by 1000 until dividing it would make it have no sigificant figures above 1, and chooses a suffix based on how many divisions were done.
[Answer]
# [Python 3](https://docs.python.org/3/), 127 bytes
```
def f(n):s=str(n);l=len(s)-4;return f"{round(n,~l):,}"[:4].replace(*",.").rstrip('.')+"KMBT"[l//3+(int(s[3])>4)]if n>9999else n
```
[Try it online!](https://repl.it/J95M/3)
[Answer]
# JavaScript (ES7), 74 bytes
```
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*10**(c%3)+' KMB'[c/3|0]
```
```
let f=
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*10**(c%3)+' KMB'[c/3|0]
console.log(f(1234567)); // 1.23M
console.log(f(999500)); // 1M
console.log(f(999499)); // 999K
console.log(f(102)); // 102
console.log(f(1000)); // 1000
console.log(f(1001)); // 1001
console.log(f(100000)); // 100K
console.log(f(12345678912)); // 12.3B
console.log(f(1452815612)); // 1.45B
```
# JavaScript (ES6), 80 bytes
```
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*[1,10,100][c%3]+' KMB'[c/3|0]
```
```
let f=
n=>n<1e4?n:(c=n.toExponential(2).split`e`).shift()*[1,10,100][c%3]+' KMB'[c/3|0]
console.log(f(1234567)); // 1.23M
console.log(f(999500)); // 1M
console.log(f(999499)); // 999K
console.log(f(102)); // 102
console.log(f(1000)); // 1000
console.log(f(1001)); // 1001
console.log(f(100000)); // 100K
console.log(f(12345678912)); // 12.3B
console.log(f(1452815612)); // 1.45B
```
] |
[Question]
[
Given a string representing a series of [aircraft marshalling hand signals](http://www.safetypostershop.com/wp-content/uploads/2012/07/aitrcraft-marshall-hand-signals.jpg), write a function or program to calculate the final position of an aircraft following these signals.
***N.B.:*** Co-ordinates in this challenge are represented as a pair of Cartesian co-ordinates, plus a compass direction heading: `(x, y, h)` where `x` is the x-coordinate, `y` is the y-coordinate, and `h` is one of `N`, `E`, `S`, or `W`.
You start with an aircraft at `(0, 0, N)` on an imaginary grid, with engines off. Your input is a string containing comma-delimeted pairs of characters, where each pair represents one marshalling signal. You must follow each marshalling signal in turn, and output the co-ordinates in `(x, y, h)` form of the aircraft's final position.
If a signal requires your aircraft to move, assume it moves *one* unit in the required direction for each signal of that type that it receives. If a signal requires your aircraft to turn, assume it turns 90 degrees in the required direction for each signal of that type that it receives.
An aircraft cannot move if its engines are off. If your aircraft's engines are off and you receive a movement/turn signal, do not apply the movement/turn.
## Signals
Each marshalling signal is represented by one pair of characters. The first of the pair represents the position of the marshaller's left arm, *from the aircraft's point of view*, and the second the right arm from the same POV. [This handy chart of signals](http://www.safetypostershop.com/wp-content/uploads/2012/07/aitrcraft-marshall-hand-signals.jpg) may help.
```
o/ — START ENGINES (no movement, no turn)
-/ — CUT ENGINES (no movement, no turn)
-~ — TURN LEFT (no movement, left turn)
~- — TURN RIGHT (no movement, right turn)
~~ — COME FORWARD (forward movement, no turn)
:: — MOVE BACK (backward movement, no turn)
/\ — NORMAL STOP (no movement, no turn)
```
This is not the complete list of marshalling signals, but it's all you're required to support.
## Input
Input is a comma-delimeted string containing pairs of characters. This string will always be valid - you do not have to validate the input.
## Output
Output is a set of co-ordinates as described above. You can return this in any convenient format - if your language supports multiple return values, you may use that; alternatively, you can use a string (the brackets surrounding the co-ordinates are non-compulsory), array, tuple, list, or whatever else you find convenient. The only rule is that it must contain `x`, `y`, and `h` values, in that order.
## Test Cases
```
Input — Output
o/,~~,~~,~-,:: — (-1, 2, E)
::,~-,o/,/\,~~,-~,~~,~~,~~ — (-3, 1, W)
o/,::,-/,~~,o/,~-,~~,~~,~- — (2, -1, S)
o/,~-,~-,::,::,~-,~~,-~ — (-1, 2, S)
~-,~-,o/,::,::,-/,~~,-~ — (0, -2, N)
```
[Answer]
# Java 8, 505 bytes
Golfed (with help from @masterX244 for shaving a big chunk off)
```
class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}
```
More readable
```
class f {
static boolean T(String u,String v){return u.equals(v);}
public static void main(String[] a) {
java.util.Scanner q=new java.util.Scanner(System.in);
String s=q.nextLine();
int x=0;
int y=0;
int d=0;
int[][] val = {
{0,1}, // N
{-1,0}, // W
{0,-1}, // S
{1,0} // E
};
int b=1;
for (String r: s.split(",")) {
// toggle b if either start or stop engine
if(T(r,"o/") || T(r,"-/"))
b=~1;
if(b<0){
// right
if(T(r,"~-")) d=(d+3)%4;
// left
if(T(r,"-~")) d=(d+1)%4;
// come forward
if(T(r,"~~")) {
x+=val[d][0];
y+=val[d][1];
}
// move back
if(T(r,"::")) {
x-=val[d][0];
y-=val[d][1];
}
}
}
System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");
}
}
```
[Answer]
# Befunge, ~~201~~ 185 bytes
```
p10p2p3pv
~/3-*95~<v:+-"/"
v!:-*53_v
#_7-:v v0-1
vv!:-3_100>p
_69*-:v NESW v+g01g
v v-*93_g10g\->4+4%10p
v<_100g >*:10g:1\-\2%!**03g+03p10g:2\-\2%**02g+02p
>>~65*`#v_2g.3g.10g9+5g,@
```
[Try it online!](http://befunge.tryitonline.net/#code=cDEwcDJwM3B2Cn4vMy0qOTV-PHY6Ky0iLyIKICB2ITotKjUzX3YKICNfNy06diB2MC0xCnZ2ITotM18xMDA-cAogXzY5Ki06diBORVNXIHYrZzAxZwp2IHYtKjkzX2cxMGdcLT40KzQlMTBwCnY8XzEwMGcgPio6MTBnOjFcLVwyJSEqKjAzZyswM3AxMGc6MlwtXDIlKiowMmcrMDJwCj4-fjY1KmAjdl8yZy4zZy4xMGc5KzVnLEA&input=Ojosfi0sby8sL1wsfn4sLX4sfn4sfn4sfn4)
Befunge doesn't have a string type as such, so to make the signals easier to compare, each character pair is converted into an integer using the formula `(c1 - 45)/3 + c2 - 47`. This can mean we'll get false matches on invalid input, but that's doesn't matter if the input is guaranteed to be valid.
The rest of the code is based around the manipulation of four "variables": the *engine* state (1 or 0), the *heading* (0 to 3 for NESW), and the *x* and *y* positions. The calculations for each signal are then as follows:
**Start engine:** `engine = 1`
**Cut engine:** `engine = 0`
**Turn left:** `heading = (heading - engine + 4) % 4`
**Turn right:** `heading = (heading + engine) % 4`
**Movement:** (where *dir* is 1 for forward and -1 for backwards)
`y += dir*engine*(1-heading)*!(heading%2)`
`x += dir*engine*(2-heading)*(heading%2)`
Once we reach the end of the input sequence, it's then just a matter of outputting the *x*, *y*, and *heading* (converted to a char with a simple table lookup).
[Answer]
# Python 2.7.12, 295 bytes
```
from operator import*
l=[0,0]
m=[['N',[0,1]],['E',[1,0]],['S',[0,-1]],['W',[-1,0]]]
n=0
x=raw_input()
for c in x.split(','):
if'o/'==c:n=1
if'-/'==c:n=0
if n:
if'-~'==c:m=m[-1:]+m[:-1]
if'~-'==c:m=m[1:]+m[:1]
if'~~'==c:l=map(add,l,m[0][1])
if'::'==c:l=map(sub,l,m[0][1])
print l+[m[0][0]]
```
The first level of indentation after `for` uses a single `\s`. The indentation of the second level uses a single `\t`. (the wysiwyg replaces `\t` with multiple spaces so please keep this in mind when testing for size)
[Answer]
# Python 2, 142 bytes
```
s=raw_input()
e=p=0;d=1
while s:exec'd-=e d+=e p+=1j**d*e e=0 0 e=1 p-=1j**d*e 0'.split()[ord(s[0])+ord(s[1])*2&7];s=s[3:]
print p,'ESWN'[d%4]
```
Example:
```
% python2.7 ams.py <<<'o/,~~,~~,~-,::'
(-1+2j) E
```
This prints complex numbers, which should be okay, I think? The `x`, `y`, `h` order is still there, and the `'j'` doesn’t cause any confusion. Tell me if I should change it.
] |
[Question]
[
## Introduction
In chemistry there is a type of extension, .xyz extension,(<https://en.wikipedia.org/wiki/XYZ_file_format>), that prints in each line
a chemical element, and the coordinates in the plane of the element. This is very useful for chemists to understand chemical compounds and to visualize the compounds in 3D. I thought it would be **fun** to, given a .xyz file, print the chemical formula.
## Challenge
Given an .xyz file, print the chemical formula of the compound in **any** programming language in the smallest possible number of **bytes**. Note:
* Originally, the input was to be given as a file. As I have been pointed out, this constraints the challenge. Therefore **you may assume** the input is a list/array of strings, each representing a line of the .xyz file.
* There are no restrictions in the ordering of the elements.
* Each element should be printed with an underscore "\_" delimiting the element and the number of times it appears
* The first two lines of any .xyz file is the number of elements, and a comment line (keep that in mind).
## Example Input and Output
Suppose you have a file *p.xyz* which contains the following (where the first line is the number of elements, and the second a comment), input:
```
5
A mystery chemical formula...
Ba 0.000 0.000 0.000
Hf 0.5 0.5 0.5
O 0.5 0.5 0.000
O 0.5 0.000 0.5
O 0.000 0.5 0.5
```
---
>
> **Output:**
>
> Ba\_1Hf\_1O\_3
>
>
>
---
## Testing
A quick test is with the example mentioned. A more thorough test is the following:
since the test file is thousands of lines, I'll share the .xyz file:
<https://gist.github.com/nachonavarro/1e95cb8bbbc644af3c44>
[Answer]
# Pyth - 18 bytes
```
sjL\__MrShMcR;ttQ8
```
[Try it online here](http://pyth.herokuapp.com/?code=sjL%5C__MrShMcR%3BttQ8&input=%5B%275++%27%2C+%27A+mystery+chemical+formula...++%27%2C+%27Ba++++++0.000+++0.000++0.000++%27%2C+%27Hf++++++0.5+++++0.5++++0.5++%27%2C+%27O+++++++0.5+++++0.5++++0.000++%27%2C+%27O+++++++0.5+++++0.000++0.5++%27%2C+%27O+++++++0.000+++0.5++++0.5++%27%5D&debug=0).
[Answer]
# Japt, 21 bytes
```
U=¢m¸mg)â £X+'_+Uè_¥X
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VT2ibbhtZyniIKNYKydfK1XoX6VY&input=WwoiNSIKIkEgbXlzdGVyeSBjaGVtaWNhbCBmb3JtdWxhLi4uIgoiQmEgICAgICAwLjAwMCAgIDAuMDAwICAwLjAwMCIKIkhmICAgICAgMC41ICAgICAwLjUgICAgMC41IgoiTyAgICAgICAwLjUgICAgIDAuNSAgICAwLjAwMCIKIk8gICAgICAgMC41ICAgICAwLjAwMCAgMC41IgoiTyAgICAgICAwLjAwMCAgIDAuNSAgICAwLjUiCl0=) Input is given as an array of strings (which can be formatted as in the link).
### Ungolfed and explanation
```
U=¢ m¸ mg)â £ X+'_+Uè_ ¥ X
U=Us2 mqS mg)â mXYZ{X+'_+UèZ{Z==X
// Implicit: U = input array of strings
Us2 // Slice off the first two items of U.
mqS mg // Map each item by splitting at spaces, then taking the first item.
U= ) // Set U to the result.
â mXYZ{ // Uniquify, then map each item X to:
UèZ{Z==X // Count the number of items Z in U where Z == X.
X+'_+ // Prepend X and an underscore.
// Implicit output
```
[Answer]
# AWK, 44
```
NR>2{a[$1]++}END{for(i in a)printf i"_"a[i]}
```
[Try it online.](https://ideone.com/7RPZ0s)
[Answer]
# Shell + GNU Utilities, 67
```
sed '1d;2d;s/ .*//'|sort|uniq -c|sed -Ez 's/\s*(\S+) (\S+)/\2_\1/g'
```
[Try it online.](https://ideone.com/InlBTt)
[Answer]
# Mathematica, ~~79~~ 53 bytes
```
StringRiffle[Tally@StringExtract[#[[3;;]],1],"","_"]&
```
Quite simple.
] |
[Question]
[
**Challenge:**
Create a program that compresses a semi-random string, and another program that decompresses it. The question is indeed quite [similar to this one from 2012](https://codegolf.stackexchange.com/questions/4771/text-compression-and-decompression-nevermore), but the answers will most likely be very different, and I would therefore claim that this is not a duplicate.
The functions should be tested on 3 control strings that are provided at the bottom.
**The following rules are for both programs:**
The input strings can be taken as function argument, or as user input. The compressed string should either be printed or stored in an *accessible* variable. Accessible means that at the end of the program, it can be printed / displayed using `disp(str)`, `echo(str)`, or the equivalent in your language.
If it's not printed automatically, a command that prints the result should be added at the end of the program, but it will not be included in the byte count. It's OK to print more than the result, as long as it's obvious what the result is. So, for instance in MATLAB, simply omitting the `;` at the end is OK.
Compressing a string of maximum length should take no more than 2 minutes on any modern laptop. The same goes with decompression.
The programs may be in different languages if, for some reason, someone wants to do that.
**The strings:**
In order to help you create an algorithm, an explanation of [how the strings are made](https://ideone.com/goPPcV) up follows:
First, a few definitions. All lists and vectors are zero-indexed using brackets `[]`. Parentheses `(n)` are used to construct a string/vector with `n` elements.
```
c(1) = 1 random printable ascii-character (from 32-126, Space - Tilde)
c(n) = n random printable ascii-characters in a string (array of chars ++)
a*c(1) = 1 random printable ascii-character repeated a times
r(1) = 1 random integer
r(n) = n random integers (vector, string, list, whatever...)
c(1) + 2*c(1) + c(3) = 1 random character followed by a random character repeated 2
times followed by 3 random characters
```
The string will be made up as follows:
```
N = 4 // Random integer (4 in the following example)
a = r(N) // N random integers, in this example N = 4
string = a[0]*c(1) + c(a[1]) + a[2]*c(1) + c(a[3])
```
Note: repeated calls to `c(1)` will give different values each time.
As an example:
```
N = 4
a = (5, 3, 7, 4)
string: ttttti(vAAAAAAA=ycf
```
5 times `t` (random character), followed by `i(v` (3 random characters), followed by 7 times `A` (random character) followed by `=ycf` (4 random characters).
For the purpose of this challenge, you may assume that `N > 10` and `N < 50`, every second random number in `A` is larger than `50` and less than `500`, while the other random numbers can be from `1` to `200`. As an example:
```
N = 14
a = (67, 48, 151, 2, 51, 144, 290, 23, 394, 88, 132, 53, 77, 31)
```
The score will be the combined length (bytes) of the two programs, multiplied be the compression rate squared.
The compression rate is the size of the compressed data divided by the size of the original data. The average rate for all three strings is used.
```
score = (Bytes in program 1 + Bytes in program 2)*(Compression rate)^2
```
The winner will be the one with the lowest score two weeks from today.
**Test strings:**
String 1 (5022 chars):
```
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTX_w}yo7}vWL$Y@qNR*Xxqt|oqmwr4+32ejdnaKdEf1<a?<iEKswv)HcNyF/pGc).SPpCF-j$& 1**(NNZ.>Zy0e-`a)i$1Z,X[hcR5JX18wG|`9:H;Qi&nluCKC:b! Q+)i77B28/j/4ZYT1=FN!>DR7'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyeDW,FmJh.%AgO&<CIO|Z>gSmszi/I?nL3P8)se$cbNit%['G<X9VW/)+Xg%$Y}E98\X o;y<Jf8(,8=i`v\e B\7\?<\!Pht(U7FFg\!\L_&bh=G*IJLPLpKGc@ 3j9E%{z^+'3bFmM3q"|c2Gt#ed%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! cVy4U>hmsNbdU}b-T`n'B^:L#Z}pI5l+46(1LCS>:BAp8+?[ ?}}1mtpo3\[{I]!7T33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333FzE klH&6Cj[VPd: HB\e9FvH_./lxP*Z\LD-,Y``IegX+=1T_:B>VJ{Ikq>'_>k5>rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"EI5K,%OB??_{"fNG>Ql6"jJ4m[S{I_/`P000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000=K#Gc-0ai'N"zDO[roJAJOPPY!%C#+J7"xd0V^teUZX$QW!<\s 3kuuXS'W`F mUvkzr7R ET"(2Y9c}M-a&shkT9j>*x+KDprC'9WFXl(`I{AfsCffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffvKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK#v>boc"..................................................................................................................................................................................................a#,uAOemp[b5CPOzI85g:a[|:]<Ss=`JuIB]+Sg$b'>PJ=%:zM#I$,YM1eX)Ja=P5x^WhuVt1?$ZU5qoM68P?n;T]R-RZ0PMH^pS%W*so-v!=2Z=9J^p,j$4)"'mXvWFF]IQN^MqG:^Lr&V?is6A%N${wNjCXpJE+F^wBG4@c`c^/CU-}8TIYJHu$|KGq=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\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ALe*B5P'*`kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNIv%x1QT@:A`TeVc"AVnFzfPGN%^</a=G=#P/G/oAS^ZPI-8yhu0T8>V5kF80Gh;QU=SC>ymTH{Onh/)[kN+:y .iRj[yK!V HDFW<<fU&zmm2.OY-H^Gf)yH{R%>5DNI]'AX7-kpEJr`+IM-cUn S{co^]ir%J,(P/[q1 h},R",d\Kg%(*HpGDEq`=ubhTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTgeQ_!6|Qj$L77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777>JV8&V]xq4k#U)5e^8VTJPRzD)HeT6STV:WgqwBbF61R/{_x=diD{<5jKf/Yds7.;Eu}[bYDyA1wRA{-S:1l[%5dHHVOgWMQBy">VO^fJ4yn>oN.,1LEzxT.)>cHk!PbB|$#."Jg^;8}\% D>*8e))=OnSNhRQ
```
String 2 (2299 chars):
```
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV`]e!oO{=i&}\o8^('MDPC`VCI`(@3AFa"A3Dhc<h2Rhc99F^$<LpAOdzC6Y%dTm:!iHH@&&O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GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGtOnQL:PKI':C}q.:6|aHiYII*C7{kGa,9aSE8D}h#S%[^:P&e^:kazo,"W]e--\bW=],xD44\@,Z;Q7$RPKA0b6yO_7&h}b/[[email protected]](/cdn-cgi/l/email-protection)}0.-ySF2zWy_3gwpmcqWZZ'Y))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))X']&p]icj|RFj'ci2*1jXg%* Eu&9QZEWwGpen1Pa,Gti_?FUL)&=r<YL-Th"]f%jV<Kx);@L^)mw'g S(nry%kbZp pGD]R@j3{idSHH<!X{%(/T,ow]$259a P-6_AX*o?4g^>(n<v^:/U@cmh9nOG|ot=8Rw5FfvU/'IGD(gm++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++K#&U4RN$dR*rv1p5t`<n7XpvpVz#uncF647sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssYl?CCkw#e?#be5,c0GttH}N j:$5AHa Xz[<z-=CdX)@}fHmk7L-k&hZHOP5o9^yU%%:g|TD1b=7G !HKGMN|}/l:}2Ia^fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff56&4i{38sY*]<DTT#:5>RJm*\c&|kM+K\s^"055%FL5Fl&X|{q+4N6t^(<\gt@;v?z}xly?Bi_!mSA+8r/6n4)Kdh4)P8'|oK&-7tFNO:]mr$nl6L1jr):uC(vh`Ei)19MfumB<VtL]"Vc
```
String 3 (10179 chars):
```
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""":=P,W$WS.vBP9d89L65VeuKY27|*-Ih1x/nY}p09Sq$PQ%4z!l*)@wmbP3b;C3E8#*?2-T`W"0&::+kA:`.OrjmD-u(oDpE:{x0 ttb13yO"q6U:1N@/[R2g}#y}d,7)_STJ^0hb]4]hSd9%L#]Bimmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm+HuOde&d,uX?B??|AJ)h.}D<HouV7NXUP0!.,HmhBaar7(c.)A#%8aPc{g8iE.hw0H)P5B^zQT('wG7Vu(|M>lo.5EM3Z/o&[Pfd}A{Vsi,+lAlam*K}69zlNWJv)|u0<e#+:l![((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((G#zx B)=N\[hRY8Dm`x@SPG=3ZRJ^SkywE:U/[\Z?q[fjY9gxO.]TiH)xKw}%*Tb[JhlD]2D4:(CE:#Zre/}9:z2*G)u)O,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,It)UnqhJ_XIzXNlT%C*Mq%R6KNTg=Q(4G)}=Q2Fp.A>Tuz?y4,wvh%,qQS5gb`6E>^6M]1FV/*4s%LDf%bwEr!oH.G/////////////////////////////////////////////////////////////////////////////////////////////////////JfITfs\Bp{8uJmAE@qW>QT!"R\q\q}2Rwo3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333q Kxp"zbN(am%qRC"bc#]zzD,sr]=H)yMS"0X&_/|yqs!kZ)`MY[C%3j`6$D!(Qk4x."e,m] ;B|S)E{BQT:%eSr0j7Gqx0&u7c7.lT]P?.&&mV2ZT^.k^"0)4K*#E4d!z/$#[-?zi8a(S?iIU9|q?lfy3T"}fh)oWfO5^{sAXu`CB*LStW5(KCe3I]-|oE^>!VL<#Pd$PLDBqZfQ)QPCWja7&7HtM7uM9*..................................................................................................................................................................v/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\sh*_l7Tk`b7KQueol'sWCC,5|\=H>v0I4c\PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP4q.r!#H?yY/-t2:iDRwn,TwSR6 v@lBv\jjO!Kz+1NT>ksfbl=hq)/y1q<}3"kYHLJ&&m'NS'lhqaPYJW3}3Qjh)|ZnAQvb^v=6TIw%Ry{!M,aBIzd9QLhB%cjXOoc*C\S0!(f :NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNv(9%[[email protected]](/cdn-cgi/l/email-protection)&fw@L9edFP3#7tuHlxpCk8]hD.ky{V6bS#?rEz5PERx_"V:\TN {2_"pE/T:X<#&<\V%IQISzo6w5vO%lvPx)|wO!"+>\t-SzP\wWXFQrmXp`JGJ/sIoVyns2u=yU`26&A1]vrpEXHD/K1HjnN4-t";S*****************************************************************************************************************************************************************a&.z "aV6]K"JhyO;/`UOpAkb}zP53=$AD:Io3lkjdUMjw1w!rL2Za3Dk:,`]AsG!L[3e^ECxxqx[I_{|qe)z;zZ#V&HZ:J4g+2U>}y!Oazq`qY_]'n=egXV9*IaFbtRZGVQG!ojmkTkStrbzFnd|7Keu [7$2f7Npb]ne=wuAg\9*4Rd/cqcDApSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS[OTjad;#l+*>m&fFSS{rc|xb?MTV$Z2I>)l8QfAUB"wNHhMNpvaz_TnvM:2Ck>*2=jWS2)a/$dP\,"pB9#L^1lSir+m%oG@YA/G#M3T10gF+xdJDqe"8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888":6Y<zLVYm@aQ-.\-u\M_.7<}L`(w!+7lm@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<aJHBA#?>9cSxN5HZ:$Z{Kr15x>cZ?!NACujxBVAu;->*BxS)wu dA:2#Sq:FaGgr5,mKLv&_ms"s1:NXEVVX)`y#ekL4H$;%{xrU$ai&9J5C8eqyQE(E|;+3tf^csoENQJG#}X81VE2m1xY 2SI d[*Eozzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz7/+M6f *n*GBp_/+rpBX@]%OpIgfkF":Cc"xzIGYw5H{LVBWFKg\1j{S duWiWB[-%'z7)NGE)QR >"t4#N1{(EntG)$u^o/J(*IaBAB<D\iE?gWj)ccWk-[OToXKjQZTWIji%^] ,Z#:_5Rsk e`s-bxrLW|(,c!>mmin\w5lcLO`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````+b"0@z2a@N^IO}K{uefxE%pgz'!7GoJ2mLaOZh3#I$tSEZ/=x9S6]Y0[5T@qRftKeXuBFr_ \)-?-2">0r*=MB'hhf4x"%g8Y\[kmPx><6ejGL; s:yp@5af+rg=/`W(xm,{OKLzj dY/3PC)Ea]LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLcqGx?cJ"y,>w5jkIbja_qUNv#-r_G 86[090^^F@x|4(8@dWy`"MnL5<+Mf{[[email protected]](/cdn-cgi/l/email-protection)`G$gNJbCddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd:>WH*?#n+7oFZQ\gLEzvR8LS6u&0^pR[;n`x&D9m"YFf````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````G=Z^o74rpXU<`',;JPl|}/>8f<ir3M6;&O)Y4rV5T2^+AJ>QvlE([bozzb,ifw=BG7+P((lS$g{c!N*&_K<);rx,2&9@7QJi6Q*(.qFQys>EB['1a4(`?htRwJ"a+<j6*>.Lm}F)`:M3;=^n+Bp&\HZI[sv1FGI93\6VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV O}h4W!dP?}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}Z'lC(E *d#-Ub?y". r:D{n--gCk&=IpmT{\I-;2vQ18xtU'2u1<qAN<IF!YEwx)ZKvY_)D%CU;l1bC%$>u|W.(2=dC!{_e?bc32]DYC?m}<{vdZKnZ <.VhO?EYwINo7lS36Ir1p4Q%cG*7RX#)iVIu..............................................................................NuF1uxKoCH5[cn,,7uj "6aoUK_7hV|lb;u8Piim!{f4 dASS'mtQ&L_-jZ=a?=YwO%Q?y240o".T*]k",5]S*f(P?Rp?T1=V7[^T=w8_h>(:O%f?iZuaJ=3d`f[dI;8S@'Gz]zn%{_OAw7&T%-44444444444444444444444444444444444444444444444444444444444444444444uSz;a(-U)o.xYDgr0,Kyo+jsMrB^oQJ=V}U`nEB>Eqo}S]sUil-sAurUOxxU.+S#f.lvO>Q_SN71{(3"eXt.%$z2Y%Gk8WFTCBz;\`2-eis.*pQ"q^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^vbAbVM q5#3gqC[FPb%7[jHR(o!jK[B)-!FD+.6Pu-(-ccyOsQPKug;]M8R5c'IK>O4EuxI8nr#Ab\EXRK+fP'KHb@-J=51g?/?<H\-BWq1s-Rb:5TuB5kb;eG3Sp/]h5Y{E+T\#i\.&+Q#%*G&O1o-sRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR'%*P|wj/I!ThsIYvh&#$W3\.]4[RTuwFOF#8y+TA7%B@u1T)l!:VFW;i.-{w6Gebq3JaMn7X9cwj3eg8Kf!HaME[<f2*w',ji0t0sDj>n+,=WN *k#[a3XKg!"0Mg$`vP\Fvjup*@8TV@ly{k{4Z2[@a:N)SWQ?Lxxv}dJ?WUmFYPBcG>Z;r_[6Kw$n2\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'ja3@b''Ol'{i3K`wB5(kIOVg9'/R`I6=la;cV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l#kr:]VM `z%(&<`yhME|B;2Tjm$^N^,0\h)rVEVT\rp@T>>0U:KoFAsZ'_rZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZaI}`I/T;Qk/dyY_96VxX6=EGn%{'uzDF}.k!\}O^NG1p7PI<_C'/3%d70'@;\6n)wydLj}bZfWP9 zei[;J:^;BRwKcBFdFld3IRrRY9oBJ<#ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ/e{hh'&wP3jknjfma}v:*__SLUIg\@*_`m:fcbfj((6:1)..?,Xx6<%bi.9Z>)xC`Jbwv#mo_[O0z8>@Exm^>b.&2)[Eyg\Y{UZA9:+SuwhG(<w***********************************************************************************************************************************************************************s4NBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBJ_ h\ xgC46py]Wh'|,LnG2dgl1\*ZG2HWA0Z%26_zB(Y{:;2zxS?>5NJrX8j^*9bt$UQ\PD95El;e'EU6K.[:a&zn]$]`g^Wl;Q(o9oWI3HwTj}NR_:OAdJ@!M8#twm6+tN!*%ldWyOZpnGBeOyz\CiH9w>FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFVRA"MafX,*ZvJvhH{]BrDX">v}pMz2ze.q#$U1c_ XA207Zof^cE,(R`LgHdYY&etOFaShx`F])18.O#\go/-Q#!%6%O0)W`v$fX)7VSTUYau9TC|%a_'bI&i1i7Z3,om_'9(2m-ihn jCh5VrJPD9gm@EoAP*[.!5e{5BJ_>_ut^Hu\:^kJS0IOn+ 555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555gp_;VbIVS>7)S?V.!Qgx7T/Ik33tV.M>/[l/8HiS1L1tX<P_2,rR(R&+-#^rl=b8GgJP^y:!/`+-:_sWyzD56jqu0/N-)].j`*q9$csBoIl CyC]3j+^DT-Ra|LN*TesCL*-Z;OdO^m#{rp8rAaFB.N-''n:\p?O5bPgT{eD9^3[S7&E,n%/VFiz>K(VXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXEFm-T"2Ny{`4Jt7kv2fTpcsn=U.XCpppppppppppppppppppppppppppppppppppppppppppppppppppHr5aL@FX.UBLt$Um68vRs;Fw)Ymm>=^;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++JczE.=iK'CWH`]_Xf3G*Nb*ExFAKl;|ssZsBC 2s4jz=GR9y>`X8(M;2/BI3h75[[Yfr]txi5}i{np "p}H*.&3o(e>6I)`/;]`[7Oq{=Y4_2jUl}M)jWn&aX&h'dOUrZ),5>Rr2J<UF&{.vJNB?v{Hyp8sK`\J+;%_WTm__________________________________________________________________________________________________________________________3|+lq,Eb6.3HKu}g;La3'x$%?4tgQhIsR'9 c@i<5(LW'$[)YBE rA}BcWFWswnk_h(Z_ a`tQ)IorJ(!>0=c)/-t.n8rL|Php0!tjtI^r=GMN)GU4k?E oQc4|x#y;AU2hW
```
Note that the strings can be much longer than this, but there's a character limit (30000) on posts, so I had to restrict it. The functions should work for codes up to the maximum size.
[Answer]
# CJam, 40 bytes + 13 bytes, rate 0.48697, score 12.5682
Just a baseline solution which compresses the long runs.
Compression ([Test it here](http://cjam.aditsu.net/#code=qe%60%7B(S*%5C_%7B0%3DK%3E%7D%23)_%7B(%2F(e~%5CL*%7D%3AF%26N%5C%7Dh%3B%3B_%2CF%0A%0A%5Ds_%2CpNo) with length calculation):
```
qe`{(S*\_{0=K>}#)_{(/(e~\L*}:F&N\}h;;_,F
```
Decompression ([Test it here](http://cjam.aditsu.net/#code=r%7B~l1%3E(%40*%5Cr%7Dh)):
```
r{~l1>(@*\r}h
```
The lengths of the three test strings compressed are 2296, 1208 and 4917 respectively. This score could probably be vastly improved by making use of base encoding.
[Answer]
# Awk, 74.9 = (199 + 115) \* 0.48853^2
The compression replaces the characters repeated over 4 times, by character & total, enclosed by tabs. For example: `&&&&&` becomes `\t&5\t`. While `dddd` remains `dddd`.
The decompression script uses the tabs as the record separator and restores the repeated characters.
### Compression
```
{split($0,s,"");for(i=1;i<=length($0);i++){c=s[i];f=s[i+1];if(c==p||c==f){n++}else{printf("%s",c)}if(n>1&&c!=s[i+1]){if(n>4){printf("\t%s%d\t",c,n)}else{for(j=0;j<n;j++){printf("%s",c)}};n=0}p=s[i]}}
```
### Decompression
```
BEGIN{RS="\t"}{if($0~/^.[0-9]+$/){for(i=0;i<int(substr($0,2));i++)printf("%s",substr($0,1,1))}else printf("%s",$0)}
```
(note that this script would be more efficient if the substring calculations are first put in variables. But codegolfing often trades efficiency for bytes.)
### Test
```
$ for s in string1 string2 string3; do cat $s.txt|awk -f compress.awk >$s.compressed.txt; done
$ for s in string1 string2 string3; do cat $s.compressed.txt |awk -f uncompress.awk >$s.uncompressed.txt; done
$ wc -c string[1-3].txt string[1-3].uncompressed.txt string[1-3].compressed.txt
5022 string1.txt
2299 string2.txt
10179 string3.txt
5022 string1.uncompressed.txt
2299 string2.uncompressed.txt
10179 string3.uncompressed.txt
2296 string1.compressed.txt
1208 string2.compressed.txt
4916 string3.compressed.txt
43420 totaal
$ md5sum string[1-3].[ut]*xt
ea7076dd2f24545e2b1d1a680b33e054 *string1.txt
ea7076dd2f24545e2b1d1a680b33e054 *string1.uncompressed.txt
dd69a92cb06fa5e1d49b371efb425e12 *string2.txt
dd69a92cb06fa5e1d49b371efb425e12 *string2.uncompressed.txt
9e6eaf10867da7d0a8d220d429cc579c *string3.txt
9e6eaf10867da7d0a8d220d429cc579c *string3.uncompressed.txt
```
[Answer]
# Perl, 113 bytes + 80 bytes, rate 0.497325, score 47.735
This is my first golf ever, and a first draft. For now all it does is count the length of repeated sequences and replace the repetitions with an integer representing the number of repetitions. E.g. "aaaaa" → "a{{5}}"
Compression:
```
$d=<>;push@d,$1while$d=~/((.)\2*)/g;map{$l=length;($o)=/(.)*/;$_="$o\{\{$l\}\}"if$l>4;}@d;print length(join'',@d);
```
Decompression:
```
map{($o)=/^(.)/;$_="$o"x$lif($l)=/\{\{([0-9]+)\}\}/;}@d;print length(join'',@d);
```
Double curlies ({{ }}) are probably redundant, but I want to be on the safe side.
Compressed lengths are 2340, 1230 and 4998 respectively.
[Answer]
# [Mathematica](https://www.wolfram.com/language/), 9 bytes + 11 bytes, rate: 0.565899. Score: 6.40483
Mathematica, of course, has builtins for this. This makes this answer a bit of a cheat, but I thought I should include it anyway.
```
Compress@
```
and
```
Uncompress@
```
[Answer]
# PowerShell 5 (invalid), 37 bytes + 35 bytes, rate 0.43121, score 13.3878
This entry is currently invalid and theoretical only, as I don't have access to a machine equipped with PowerShell 5 to verify, and/or I'm not sure if this counts as "using an external source." More of a theoretical "what-if" scenario than actual submission.
.
Compression (the `Get-Content` displays the results and doesn't add to the byte count)
```
$args|sc .\t;compress-archive .\t .\c
Get-Content .\c -Raw
```
Gets command-line input, uses `Set-Content` to store that as a file `.\t`, then uses `Compress-Archive` to zip it to .\c
Decompression (again `Get-Content` doesn't count)
```
$args|sc .\c;expand-archive .\c .\t
Get-Content .\t -Raw
```
PowerShell 5, introduced with Windows 10, includes a [new feature](https://devblogs.microsoft.com/scripting/new-feature-in-powershell-5-compress-files/) that lets you use the built-in-to-Windows zip/unzip functionality. Previously, you would need to create a new shell and explicitly execute a zip.exe command with appropriate command-line arguments - yuck. Now, it's just a simple command away.
Note that this is likely *also* not valid if you're expecting to copy-paste the string output from the compression algorithm into the decompression algorithm, as the PowerShell console [doesn't handle non-ASCII characters very well ...](https://devblogs.microsoft.com/powershell/outputencoding-to-the-rescue/) Piping from one to the other should work OK, though.
] |
[Question]
[
# Ascii Pong
The challenge is to recreate the classic game "pong" in ASCII characters in the shortest code possible.
**Requirements/specifications**
* The "screen" should be 45x25 characters.
* White space should actually be white space.
* The paddles should be 9 equals signs: `=========` and should be on the top-most and bottom-most rows (I know the original is played side-to-side instead of top-to-bottom, but I think this works better for ascii pong).
* The ball can be a lower or upper case `o` or a zero.
* Two input buttons of any kind (it is fine if the user presses a key that makes a letter show up in the input, that is fine, too) to move the player's paddle left and right one or two character at a time.
* The ball needs to ricochet at the appropriate angle upon hitting a paddle or a wall (hint: negate the x or y difference value).
* The score should be displayed somewhere in the output. The score is how many times the player successfully hits the ball.
* If the ball misses the player's paddle, terminate the program.
* There should be *some* sort of AI (even if the AI's paddle just matches the ball's x value).
* The ball can't travel in a straight line vertically or horizontally.
The start screen/first frame should look something like this:
```
=========
o
=========
score: 0
```
**Scoring**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins ...
however, there are some bonuses to decrease your character count:
* -30 characters: Change trajectory of ball depending on where it hits on the paddle
* -10 characters: Make the game speed up over time
* -20 characters: Make the AI beatable
* -20 characters: Avoid any situation where the player stays still and the game goes on forever without winning or losing (caused by certain trajectories and AI patterns)
* -20 characters: Make the ball start moving at a (semi-)random trajectory
* -25 characters: Add a reset option
Here is an un-golfed example with no bonuses in JavaScript:
```
//init
var x = 22,
y = 12,
xd = Math.random() < 0.5 ? -1 : 1,
yd = 1,
player = opponent = 18,
score = 0,
//interval that runs 10x per second (minus the runtimeof one cycle)
interval = setInterval(function() {
//move ball
x += xd;
y += yd;
//move opponent
opponent = x - 4;
//collision with walls
if(x <= 0 || x >= 44) xd = -xd;
//collision with paddles
if(y == 1) {
if(x >= opponent && x < opponent + 9) yd = -yd;
else {
//you win
clearInterval(interval);
document.body.innerHTML = "You win!<br>Your score was: " + score;
return;
}
}
else if(y == 23) {
if(x >= player && x < player + 9) {
yd = -yd;
score++;
}
else {
//you lose
clearInterval(interval);
document.body.innerHTML = "You lose!<br>Your score was: " + score;
return;
}
}
draw();
}, 100);
function draw() {
var body = document.body;
body.innerHTML = "";
for(var i = 0; i < 25; i++) {
for(var j = 0; j < 45; j++) {
//white space is default
var char = " ";
//ball
if(j == x && i == y) char = "o";
//paddles
if(i === 0) {
if(j >= opponent && j < opponent + 9) char = "=";
}
else if(i == 24) {
if(j >= player && j < player + 9) char = "=";
}
body.innerHTML += char;
}
body.innerHTML += "<br>";
}
body.innerHTML += "score: " + score;
}
//key press listener for left and right movement
window.onkeydown = function() {
if (window.event.keyCode == 37) player -= 2;
else if(window.event.keyCode == 39) player += 2;
};
```
```
<body style="font-family: monospace; white-space: pre">
</body>
```
Let the games begin!
[Answer]
# Perl, ~~760 611 592 535~~ 515 (640-30-10-20-20-20-25)
A console solution with all the bonus stuff.
It should work on any terminal that understands the ANSI escape codes (\e[...). Tested on cygwin.
Keyboard controls:
Left: 4
Right : 6
Reset : 8
```
use Term::ReadKey;ReadMode 4;END{ReadMode 0}$|++;$a=$d=45;$b=25;$h=1;$j=$l=17;$p='='x9;sub P{print"\e[@_"}sub L{$%=$l+pop;if($%>0&$%+7<$a){P"25H\e[K\e[25;$%H$p ";$l=$%}}sub U{$%=$j+pop;if($%>0&$%+7<$a){P"1H\e[K\e[1;$%H$p ";$j=$%}}sub I{$}=int rand 42;$g=8;$i=1;P"2J\ec";L}I;while(1){if($c>0){$c--}else{$c=98;$d-=$d>6}if($c%9==0){U -1if$}<$j+4;U 1if$}>$j+6};if($c%$d==0){$m=$}+$h;$n=$g+$i;$h*=-1if$m<1||$m>$a;if($n>24&$}>=$l&$}<$l+9){$i*=-1;$h=-1if$m<$l+5;$h=1if$m>$l+5;$s++}if($n<2&$}>=$j&$}<$j+9){$i*=-1}P"$g;1H\e[K";$}+=$h;$g+=$i;P"$g;$}HO"}if($k=ReadKey -1){I,if$k>6;L$k<=>5}P"26;0Hscore:$s";exit,if$g>=$b;select($\,$\,$\,0.01);I,if$g<2}
```
[Answer]
# JavaScript, 618 bytes + HTML, 99 bytes
Well here is my golfed JavaScript answer even if it isn't feasible in other languages:
```
var x,y,xd,yd,p,o,s,n,i,j,c,k;function a(){x=22;y=12;xd=Math.random()<.5?-1:1;yd=1;p=o=18;s=0;n=setInterval(function(){x+=xd;y+=yd;o=x-4;if(x<=0||x>=44)xd=-xd;if(y==1){if(x>=o&&x<o+9)yd=-yd;else{clearInterval(n);b.innerHTML="You Win!<br>Score: "+s;return}}else if(y==23){if(x>=p&&x<p+9){yd=-yd;s++;}else{clearInterval(n);b.innerHTML="You Lose!<br>Score: "+s;return}}d();},100);}function d(){b.innerHTML="";for(i=0;i<25;i++){for(j=0;j<45;j++){c=" ";if(j==x&&i==y)c="o"; if(i==0&&j>=o&&j<o+9)c="=";if(i==24&&j>=p&&j<p+9)c="=";b.innerHTML+=c;} b.innerHTML+="<br>";}b.innerHTML+="score: "+s;}onkeydown=function(){ k=window.event.keyCode;if(k==37)p-=2;if(k==39)p+=2;};
```
```
<button onclick="a()">start</button><div id="b"style="font-family:monospace;white-space:pre"></div>
```
-20 and -25 for bonuses
] |
[Question]
[
[Marching Squares](https://en.wikipedia.org/wiki/Marching_squares) is an algorithm from computer graphics, which is used to recover 2D isocontours from a grid of samples (see also, its big brother [Marching Cubes](https://en.wikipedia.org/wiki/Marching_cubes) for 3D settings). The idea is to process each cell of the grid independently, and determine the contours passing through that cell based on the values at its corners.
The first step in this process is to determine which edges are connected by contours, based on whether the corners are above or below the value of the contour. For simplicity, we'll only consider contours along the value `0`, such that we're interested in whether the corners are positive or negative. There are `24 = 16` cases to distinguish:
[](https://i.stack.imgur.com/yMNtv.png)
Image Source: [Wikipedia](https://en.wikipedia.org/wiki/Marching_squares#/media/File:Marching_squares_algorithm.svg)
The identification of white and black doesn't really matter here, but for definiteness say that white is positive and black is negative. We will ignore cases where one of the corners is exactly `0`.
The saddle points (cases 5 and 10) provide a little extra difficulty: it's not clear which diagonals should be used by only looking at the corners. This can be resolved by finding the average of the four corners (i.e. an approximation of the centre value), and choosing the diagonals such that the contours separate the centre from the corners with the opposite sign. If the average is exactly `0`, either case can be chosen.
Normally, these 16 cases are simply stored in a lookup table. This is great for efficiency, but of course, we'd prefer the code to be *short* around here. So your task is to perform this lookup step and print an ASCII representation of the case in as little code as possible.
## The Challenge
You're given the values of the four corners (non-zero integers) in a fixed order of your choice. You should then generate the correct layout of the contours, correctly resolving the saddle point cases.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Input may be taken in any convenient string or list format.
The 16 cases will be represented in ASCII art using one of the following 5x5 blocks:
```
o---o o---o o---o
| | | | | | |
| | |---| | | |
| | | | | | |
o---o o---o o---o
o---o o---o o---o o---o
|/ | | \| | | | |
| | | | | | | |
| | | | |\ | | /|
o---o o---o o---o o---o
o---o o---o
|/ | | \|
| | | |
| /| |\ |
o---o o---o
```
You must not print any leading or trailing whitespace, but you may print a single optional newline.
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
The test cases assume that input is given in order *top-left*, *top-right*, *bottom-left*, *bottom-right*. Test cases are presented in 9 groups, one corresponding to each of the 9 representations given above (in the same order, starting from the empty cell, ending with the two saddle points).
```
[1, 2, 1, 3]
[-9, -2, -2, -7]
[4, 5, -1, -2]
[-1, -2, 3, 4]
[7, -7, 7, -7]
[-5, 5, -5, 5]
[1, -6, -4, -1]
[-2, 3, 3, 4]
[-1, 6, -4, -1]
[2, -3, 3, 4]
[-1, -6, 4, -1]
[2, 3, -3, 4]
[-1, -6, -4, 1]
[2, 3, 3, -4]
[3, -8, -9, 2]
[-3, 8, 9, -2]
[8, -3, -2, 9]
[-8, 3, 2, -9]
```
Additionally, the following test cases may return either of the saddle points (your choice):
```
[1, -4, -2, 5]
[-1, 4, 2, -5]
```
[Answer]
# Ruby, ~~201 180~~ 176
This is an anonymous lambda function, to be called in the way shown in the ungolfed example.
This contains no variable `s`. In the ungolfed version a complex expression is assigned to `s` for clarity, before it is used. 4 bytes are saved in the golfed version by putting it inline. The only other difference between the versions is the whitespace and comments.
If it is acceptable to return the output as an array of five strings of five characters, instead of printing to stdout, one more byte can be saved.
```
->a{p=t=0
4.times{|i|t+=a[i]*=a[3];p+=a[i]>>9&1<<i}
q=p==6&&t>0?19:'@AC@P*10'[p].ord
puts c='o---o',(0..2).map{|i|b=p*i==3?'|---|':'| |';b[q%4]='|/|\|/'[q%4+(i&2)];q/=4;b},c}
```
I'm happy with the parsing of the array, but I think there may be shorter ways to form the output.
All four elements of the input array are multiplied by the last element. This guarantees that the last element is positive, and reduces the number of cases from 16 down to 8. The elements are rightshifted 9 places, so that all positive numbers become 0 and all negative numbers become -1 (at least in the range of input given in the test cases.) They are then ANDed by `1<<array index` to give a 3-bit binary number indicating the pattern (actually 4-bit, but as the last element is always positive, the 4th bit is always zero.)
This number from 0..7 is then fed to a (sigh) lookup table to determine which characters of each row are non-whitespace. It is at this stage that the two different displays for the saddle case are handled, with an alternative to the number in the lookup table being used if the total is positive (the question says to consider the "average", but as we are only interested in the sign, it doesn't matter if we consider the total instead.)
The way the display of output works is hopefully clear from the comments in the code.
**ungolfed in test program**
```
f=->a{p=t=0
4.times{|i| #for each number in the input
t+=a[i]*=a[3]; #multiply each number by a[3]; totalize the sum in t
p+=a[i]>>9&1<<i #shift right to find if negative; AND with 1<<i to build index number for pattern
} #q is a 3-digit base 4 number indicating which character of each line is non-whitespace (if any).
q=p==6&&t>0?19:'@AC@P*10'[p].ord #It's encoded in the magic string, except for the case of saddles with a positive total, which is encoded by the number 19.
s=(0..2).map{|i| #build an array of 3 strings, indexes 0..2
b=p*i==3?'|---|':'| |'; #IF p is 3 and we are on row 1, the string is |---| for the horizontal line case. ELSE it is | |.
b[q%4]='|/|\|/'[q%4+(i&2)]; #The numbers in q indicate which character is to be modified. The characters in the string indicate the character to replace with.
q/=4; #If q%4=0, the initial | is replaced by | (no change.) i&2 shifts the string index appropriately for the last row.
b #divide q by 4, and terminate the loop with the expression b so that this is the object loaded into array s.
}
puts c='o---o',s,c} #print the array s, capped with "o---o" above and below.
[[1, 2, 1, 3],
[-9, -2, -2, -7],
[4, 5, -1, -2],
[-1, -2, 3, 4],
[7, -7, 7, -7],
[-5, 5, -5, 5],
[1, -6, -4, -1],
[-2, 3, 3, 4],
[-1, 6, -4, -1],
[2, -3, 3, 4],
[-1, -6, 4, -1],
[2, 3, -3, 4],
[-1, -6, -4, 1],
[2, 3, 3, -4],
[3, -8, -9, 2],
[-3, 8, 9, -2],
[8, -3, -2, 9],
[-8, 3, 2, -9],
[1, -4, -2, 5],
[-1, 4, 2, -5]].each{|k|f.call(k)}
```
] |
[Question]
[
The [Sierpinski triangle](https://en.wikipedia.org/wiki/Sierpinski_triangle) is a set of points on the plane which is constructed by starting with a single triangle and repeatedly splitting all triangles into four congruent triangles and removing the centre triangle. The right Sierpinski triangle has corners at `(0,0)`, `(0,1)` and `(1,0)`, and looks like this:

Some equivalent definitions of this set are as follows:
* Points in the `n`th iteration of the process described above, for all `n`.
* Points `(x,y)` with `0 <= x <= 1` and `0 <= y <= 1` such that for all positive integers `n`, the `n`th bit in the binary expansion of x and y are not both `1`.
* Let `T = {(0,0),(1,0),(0,1)}`
Let `f` be a function on sets of 2D points defined by the following:
`f(X) = {(0,0)} ∪ {(x+t)/2 | x∈X, t∈T}`
Then the right Sierpinski triangle is the [topological closure](https://en.wikipedia.org/wiki/Closure_%28topology%29) of the [least fixed point](https://en.wikipedia.org/wiki/Least_fixed_point) (by set containment) of `f`.
* Let `S` be the square `{(x,y) | 0<=x<=1 and 0<=y<=1}`
Let `g(X) = S ∩ {(x+t)/2 | x∈(X), t∈T}` (where `T` is as defined above)
Then the right Sierpinski triangle is the greatest fixed point of `g`.
# Challenge
Write a program or function which accepts 4 integers, `a,b,c,d` and gives a truthy value if `(a/b,c/d)` belongs to the right Sierpinski triangle, and otherwise gives a falsey value.
# Scoring
This is a code golf. Shortest code in bytes wins.
# Test cases
The following are in the right Sierpinski triangle:
```
0 1 0 1
0 1 12345 123456
27 100 73 100
1 7 2 7
8 9 2 21
8 15 20 63
-1 -7 2 7
```
The following are not in the right Sierpinski triangle:
```
1 1 1 1
-1 100 1 3
1 3 1 3
1 23 1 7
4 63 3 66
58 217 4351 7577
-1 -7 3 7
```
[Answer]
# Python 2, 68
```
lambda n,d,N,D:1>=n/d>=0<=N/D<=1and(n<<abs(D*d))/d&(N<<abs(D*d))/D<1
```
A nice way to check for gasket membership made ugly. If we were guaranteed that the inputs are non-negative and in the unit square, we would have 38:
```
lambda n,d,N,D:(n<<D*d)/d&(N<<D*d)/D<1
```
The idea is that we check whether a point lies within the gasket by checking whether their binary fraction expansions bitwise-AND to 0. To get the first `k` character of the expansion, we bit-shift the numerator `k` bits left before integer-dividing by the denominator. We need to make `k` sufficiently large to catch a repeat. We note that the binary expansion `n/d` has period at most `d`, so the joint expansions have period at most `d*D`, so `k=d*D` suffices.
The rest is to check whether the fraction is in the box and insulate against inputs given like `-1/-3`.
] |
[Question]
[
This is an additional challenge to the [generate Loopy puzzles](https://codegolf.stackexchange.com/questions/36301/generate-loopy-puzzles) challenge. You might want to solve this challenge before attempting the harder challenge in the previous link.
The goal of this challenge is to validate the solution to a loopy puzzle. Please take all documentation on what a loopy puzzle is from the previous link. A solved loopy puzzle is formatted in a very similar way to the output of a valid submission to the “generate loopy puzzles” challenge and may look like this:
```
+-+-+ +-+ +-+ +
| | | |2|3|
+-+ + + + + +-+
2| | | |2| 3|
+ + +-+ + + +-+
2| 2 1|3| |
+-+ +-+ +-+ +-+
|2 | | 1 2|
+ +-+ +-+ +-+ +
| |2 1 2|3|3| |
+ + +-+ +-+ +-+
| | |3|2 1
+ +-+ +-+-+-+-+
| 2 2 |
+-+-+-+-+-+-+-+
```
The path that makes up the solution is marked with `|` and `-` characters between the `+` characters.
## Input specification
Your program shall receive a loopy puzzle with a solution formatted like the example above as input. Your program shall infer the size of the puzzle from the input. You may make the following assumptions about the input:
* The puzzle has no less than 2 and no more than 99 cells in either direction
* Thus, each line has a maximum length of 199 characters not including the newline character(s)
* Thus, the input contains a maximum of 99 lines
* each line may end after the last printable character or may be padded with whitespace characters so it has a length of up to *2·y + 1* characters where *y* is the number of cells in horizontal direction
* each position with both *x* and *y* coordinates even contains a `+` character
* positions horizontally or vertically adjacent to positions containing `+` characters contain either a whitespace character, are behind the end of line or contain a `-` character if horizontally adjacent or a `|` character if vertically adjacent
* all other positions are either behind the end of line or contain one of the characters , `0`, `1`, `2`, or `3`
* all lines are terminated with your platforms default newline character(s)
* there is exactly one trailing newline
Input shall be received in one of the following ways:
* From standard input
* As the value of a parameter named `p` in an HTTP POST request
* As the content of an HTML form
* As the content of a file named `p` in an implementation-defined directory
* In an implementation defined way at runtime if the former four are not available
* Hard coded if your language provides no mean of receiving input
## Output specification
Your program shall terminate for all inputs matching the input specification and shall compute whether the solution to the puzzle is correct. Your program shall output the result of the computation as a boolean value in one of the following ways:
* As an exit status of either zero (solution is valid) or non-zero (solution is invalid)
* As the character `y` (solution is valid) or `n` (solution is invalid) followed by zero or more arbitrary characters output in an implementation defined way
The behaviour of your program is unspecified when encountering input not formatted according to the input specification.
## Scoring
The score of your program is the number of characters in its source except for omittable whitespace characters and omittable comments. You are encouraged to indent your submission so it's easier to read for the others and to comment your solution so its easier to follow.
Submissions that fail to follow the input or output specification or generate incorrect results are invalid.
[Answer]
### GolfScript, 133 characters
```
'|':^4,{48+.(}%+^*1>.^/'-'*+2/:F;4{{~@@/*}2F//n%zip-1%n*}:X*.'+-'?.3+@/(-2<' 9'+\+'9-+ 99|+ 9'3/:F;.,4*{X}*.9`?@=\' +09
'-!&'ny'1/=
```
Expects the input from STDIN and prints `y` for a valid solution and `n` for an invalid one. Performs the task by using mostly string-replace on the grid or with rotated versions of the grid.
*Annotated code:*
```
# construct the string "|0|/|1|0|2|1|3|2-0-/-1-0-2-1-3-2"
# split into pieces of two and save to variable F
'|':^4,{48+.(}%+^*1>.^/'-'*+
2/:F;
# run the code block X 4 times
# with X: string-replace 1st item in F with 2nd, 3rd with 4th, ...
# i.e. '|0' with '|/', '|1' with '|0'
# and then rotate grid by 90 degrees
4{{~@@/*}2F//n%zip-1%n*}:X*
# for a valid grid all digits are now reduced to exactly '0'
# (i.e. no '1' or '2' or '3' or '/')
# now follow the loop along and remove it
# start: find the first occurence of '+-+' and replace with '+ 9'
# note: '9' is the marker for the current position
.'+-'?
.3+@/(-2<' 9'+\+
# string-replace '9-+' or '9|+' by ' 9' (i.e. go one step along the loop)
# using block X enough times
'9-+ 99|+ 9'3/:F;
.,4*{X}*
# look for the marker '9' in the result and check if it is at the original
# position again
.9`?
@=
# the remaining grid must not contain any digits besides 0 and 9
# esp. no '|' or '-' may remain
\' +09
'-!
# check if both conditions are fulfilled and output corresponding character
&'ny'1/=
```
[Answer]
## C# ~~803~~ 579bytes
Complete program, reads from STDIN, should cope with any common new-line scheme as long as it has line feeds. Thanks to HackerCow for pointing out that I don't have to append a new line in a different question, prompting me to remove it here and save 4 bytes
Golfed code:
```
using C=System.Console;class P{static void Main(){var D=C.In.ReadToEnd().Replace("\r","").Split('\n');int w=D[0].Length+2,h=D.Length+1,i=0,j,c,T=0,O=1,o,z,R=0;var B=new int[w,h];var S=new int[w*h*9];for(;i++<w-2;)for(j=0;j<h-2;B[i,j]=c)if((c=(D[j++][i-1]-8)%10)>5){c=5;T++;S[0]=i+j*w;}for(i=0;++i<w-1;)for(j=0;++j<h-1;)R=(i%2+j%2>1&(o=B[i,j-1]%2+B[i-1,j]%2+B[i+1,j]%2+B[i,j+1]%2)>0&o!=2)|((c=B[i,j])<4&c!=o)?7:R;for(o=h=0;o<O;B[i,j]=0)if(B[i=(c=S[o++])%w,j=c/w]>4){h++;S[O++]=(S[O++]=c-w-1)+2;S[O++]=(S[O++]=c+w-1)+2;z=j%2<1?w*2:2;S[O++]=c-z;S[O++]=c+z;}C.Write(h-R<T?"n":"y");}}
```
The code performs 3 checks, first checking the number of lines around each number and that each junction has 0 or 2 lines leading from it, then that all the lines are joined together.
Formatted code:
```
using C=System.Console;
class P
{
static void Main()
{
var D=C.In.ReadToEnd().Replace("\r","").Split('\n');
int w=D[0].Length+2,h=D.Length+1,i=0,j,c,T=0,O=1,o,z,R=0;
var B=new int[w,h]; // this is the grid
var S=new int[w*h*9]; // this is a list of joined up lines (stored as x+y*w)
for(;i++<w-2;)
for(j=0;j<h-2;B[i,j]=c)
if((c=(D[j++][i-1]-8)%10)>5)
{ // we are a line
c=5;
T++; // increment line counter
S[0]=i+j*w; // set start of loop
}
for(i=0;++i<w-1;) // this loop checks the numbers and that every + has 0 or 2 lines leading from it
for(j=0;++j<h-1;)
R=(i%2+j%2>1&(o=B[i,j-1]%2+B[i-1,j]%2+B[i+1,j]%2+B[i,j+1]%2)>0&o!=2)|((c=B[i,j])<4&c!=o)?7:R; // set R to 7 (no significance) if check fails
for(o=h=0;o<O;B[i,j]=0) // this loops through the list of joined lines adding more until the whole loop has been seen
if(B[i=(c=S[o++])%w,j=c/w]>4)
{
h++; // increment "seen" counter
S[O++]=(S[O++]=c-w-1)+2;
S[O++]=(S[O++]=c+w-1)+2;
z=j%2<1?w*2:2; // special for | and -
S[O++]=c-z;
S[O++]=c+z;
}
C.Write(h-R<T?"n":"y"); // check if R is greater than 0 or h is less than T and output appropriately
}
}
```
[Answer]
# Cobra - 514
```
class P
def main
t,m,g=[[1]][:0],nil,File.readAllLines('p')
u,i=g[0].length,1
for l in g.length,for c in u,if g[l][c]in'0123'
n=0
for j in-1:2:2,for r in[g[l+j][c],g[l][c+j]],if r in'-|',n+=1
if'[n]'<>g[l][c],m?='n'
else if g[l][c]in'-|',x,y,t,d=c,l,t+[[c,l]],g[l][c]
while i
i=z=6
for f,b in[[-1,1],[1,1],[0,2],[-1,-1],[+1,-1],[0,-2]]
if'-'==d,f,b=b,f
for w in t.count,if z and t[w]==[x+f,y+b],t,x,y,d,z=t[:w]+t[w+1:],x+=f,y+=b,g[y][x],0
i-=z//6
print if(t.count,'n',m?'y')
```
Checks if every number has the right number of lines next to it, and then walks a path around the lines and checks if it missed any.
] |
[Question]
[
I happened to glance at my watch today at exactly 11:11:11 (and today is 1/11; too bad it's not 2011), and that got me thinking: *I know! I should make a code golf question out of this! I'm a dork.*
Anyway, your challenge is to take an hour, minute, and second as input, and output the next "interesting" time. Here, I will define interesting as these steps:
1. Concatenate the hour, minute, and second. (For example, at 4:14:14, this would be 41414.)
2. Check for consecutive groups of one, two, or three that span the length of the entire string. For example, I could find `[41][41][4]` in the example time (if the group cannot reach through the string, just cut it off like I did in this example). Another example: in the time in my first example at the beginning of the question, it would be `[1][1][1][1][1][1]`, `[11][11][11]`, or `[111][111]`.
3. Is there a consecutive group that goes all the way through the string? If so, the time is "interesting!" Otherwise, it's not.
The input can be in any *reasonable* format, but it must not be hardcoded. The output can also be in any *reasonable* format, and it need not be in the same format as the input.
If you use network access for some reason, **all** bytes downloaded from the network count to your score.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code in bytes wins.
[Answer]
## J, ~~113~~ ~~99~~ 90
Probably still quite golfable.
```
f=:t#:[:(>:^:([:(3&g+:2&g=.[:*/]=(]$)${.)@(":@{.,3}.7":100#.1,])t#:])^:_)1+(t=.24,2$60)#.]
```
Takes a vector `(h m s)` as input, and returns a vector in the same format as output.
Examples:
```
f 0 0 0
0 1 0
f 4 14 14
4 14 41
f 23 59 59
0 0 0
f 3 14 15
3 14 31
```
[Answer]
# Haskell - ~~227~~223
That's one way of doing it.
```
import Data.List
e _ []=False
e f s=let (h,t)=f s in t`isPrefixOf`h||h`isPrefixOf`t&&e f t
i [a,b,s]=head[t|s<-[s+1..],f<-map splitAt[1..3],let m=b+s`div`60;h=a+m`div`60;t=[h`mod`24,m`mod`60,s`mod`60],e f$concatMap show t]
```
Examples
```
λ: i [11,11,11]
[11,21,1]
λ: i [4,14,14]
[4,14,41]
```
[Answer]
# Mathematica 125
```
F=Do[#~MatchQ~{#〚-1〛..,_}&&Break@#&@Partition[(i=IntegerDigits)@f[n~i~60,100],m,m,1,a_],
{n,#~(f=FromDigits)~60+1,7^6},{m,3}]&
```
It returns a pattern of the next interesting time:
```
F@{11, 11, 11}
F@{4, 14, 14}
```
>
> {{1, 1, 2}, {1, 1, 2}}
>
>
> {{4, 1, 4}, {4, 1, a\_}}
>
>
>
`a_` marks the end of the time.
[Answer]
# Lua
I've got four different solutions, as I wasn't sure about some of the requirements.
**Version 1: removal of 0s, command line input as well as os.time() backup (315)**
Minimised:
```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g,e,u=os.date,os.time(y),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end
```
Full version with comments:
```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end --get command line arguments
h,g,e,u=os.date,os.time(y),":",tonumber --set up references, if command line arguments accepted use y else use current time
while 1 do
g=g+1
b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) --get HH:MM:SS seperately (which allows removal of the zeroes with tonumber())
a=b..c..d --concat
for x=1,#a/2 do --check up to half of the string
p=1
for _ in a:gmatch(a:sub(1,x))do --for each match
p=p+1 --count number of matches
if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end --if matches span entire string, cheer (and print in a pretty format)
end
end
end
```
The other versions are very similar, so I will only post the minimised versions:
**Version 2: no command line input (239)**
```
h,g,e,u=os.date,os.time(),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end
```
**Version 3: no 0 removal, with command line input (240)**
```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g=os.date,os.time(y) while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end
```
**Version 4: none of the fancy stuff (no 0 removal or command line input) (164)**
```
h,g=os.date,os.time() while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end
```
**Usage instructions**
In a terminal, run (versions 1 and 3)
```
lua interesting.lua HOURS MINUTES SECONDS
```
or just
```
lua interesting.lua
```
If you want it to go off the system clock.
Is there a prize for feature completeness? :P
] |
[Question]
[
The [fifteen puzzle](https://codegolf.stackexchange.com/questions/6884/solve-the-15-puzzle-the-tile-sliding-puzzle) is peculiar in that only half the possible states of arrangement are solvable. If you flip the 14 and 15 tiles, there is no way you can slide the blocks so that they are flipped back.
Your task is to build a program that accepts a list of integers in the format of your choice (containing exactly one instance of each of the numbers from 0 to 15, with 0 being the blank space) representing the state of an arrangement of tiles in a 4x4 grid, and outputs a single boolean value determining whether the grid is solvable or not.
The shortest code to do this in any language wins.
[Answer]
# J, 28 characters
```
((C.!.2=_1^i.&0)&.".&.stdin''
```
The input order is row-major with rows read alternatingly left to right and right to left in a single path across the table. Assumes the zero belongs to the top left corner.
Usage on Windows:
```
<nul set /p="0 1 2 3 7 6 5 4 8 9 10 11 15 14 13 12" | jconsole c:\...\15.jhs
```
Explanation:
* `<nul set /p=` is used to prevent a newline in the input, that `echo` produces that `".` doesn't like. Of course, Unix supports `echo /n`.
* `v&.".&.stdin''` reads "v under parse under stdin" meaning "input, then parse the input, then do v, then undo parse (= format), then undo input (=output)". `1!:1]3` is one character shorter, but it does not have a defined inverse.
* `C.!.2` means "permutation parity". It returns either `1` (even parity) or `_1` (odd parity). That is, `_1^inversions`
* `_1^i.&0` means "-1 to the power of index of 0".
* thus, `C.!.2=_1^i.&0` means "does the permutation parity equal the hole position parity?"
This works for a 4x4 board, but if the desired end position is row-major left-to-right, then the permutation for the solved position has an odd number of inversions, and thus odd parity. Also, the parity is reversed (for any input order) when the desired hole position moves from upper left to bottom right. In both cases, the fix is one character: add `-` after `=` to reverse the expected parity.
Proof of correctness:
After each move, the zero exchanges a position with some number, flipping the permutation parity. The zero also alternates between white and black checkerboard positions, indicated by odd and even positions in the input ordering. Thus, this condition is neccessary. It is also sufficient by the counting argument: it is common knowledge that exactly half of the positions is solvable. This condition filters out exactly half of the possible positions.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œc>/€;TSḂ
```
A monadic Link accepting a list of the integers reading in row-major order alternating between left-right and right-left which yields `0` if solvable and `1` if not (to invert this add `¬` to the right of the code).
**[Try it online!](https://tio.run/##y0rNyan8///opGQ7/UdNa6xDgh/uaPr//380l4KhjoKRjoKxjoKJDpeChY6CuY6CmY6CKZBjqWNooGMIlDfQ4TI00jE01TE00TE05ooFAA "Jelly – Try It Online")** (this example is a board where 12 just needs to slide into place)
### How?
Similar to [John Dvorak's answer](https://codegolf.stackexchange.com/a/15717/53748) we calculate parities and utilise a snake-like input order to simplify checker-board parity, although instead of checking equality of parity we sum the out-of-order count with the non-zero indices and test whether that is odd:
```
Œc>/€;TSḂ - Link: list of integers
Œc - unordered pairs
€ - for each:
/ - reduce with:
> - greater than?
T - truthy indices (i.e. [1..16] without 1-indexed index of 0)
; - concatenate
S - sum
Ḃ - is odd?
```
] |
[Question]
[
Implement a [verbal arithmetic](http://en.wikipedia.org/wiki/Verbal_arithmetic) solver of several same sequence of numbers added together:
```
TWO
+ TWO
-----
FOUR
REPEAT
REPEAT
REPEAT
+ REPEAT
--------
ANDSTOP
SPEED
+ SPEED
-------
KILLS
```
There are some restrictions: each letter should represent different digits, and no letter can be zero.
Implement the solver as a function of the operands, the sum and number of repetitions returns a list of solutions (solution: the tuple of resulting operand and sum). For example:
```
f(['T','W','O'], ['F','O','U','R'], 2) == [(734, 1468)]
```
You do not need to represent variables as letters, and you do not need to use a hash in the solution.
Brute-force search allowed.
Shortest code wins.
[Answer]
## Mathematica
Spaces added for clarity. Not much golfed.
Need to use greek letters because the input letters are treated as symbols.
```
F[σ_ ,ρ_ ,τ_]:=
(φ = FromDigits;
Rest@Union[
If [ τ * φ@σ == φ@ρ, {φ@σ,φ@ρ} ] /.#& /@
(Thread[Rule[ σ ∪ ρ , # ] ] & /@ Permutations[Range@9, {Length[σ ∪ ρ] }])])
```
Usage:
```
F[{r,e,p,e,a,t},{a,n,d,s,t,o,p},3]
{{819123,2457369}}
F[{s,p,e,e,d},{k,i,l,l,s},3]
{}
F[{t,w,o},{f,o,u,r},2]
{{734,1468},{836,1672},{846,1692},{867,1734},{928,1856},{938,1876}}
```
It didn't find any solution for the SPEED+SPEED+SPEED = KILLS ... is that a bug?
**Edit**
Allowing zero, it finds the following solutions for the SPEED+SPEED+SPEED = KILLS equation:
```
{{10887,32661},{12667,38001},{23554,70662},
{23664,70992},{25334,76002},{26334,79002}}
```
**Edit**
According to comment:
```
F[{s, p, e, e, d}, {k, i, l, l, s}, 2]
{{21776,43552},{21886,43772},{23556,47112},{27331,54662},
{29331,58662},{42667,85334},{45667,91334},{46557,93114}}
```
[Answer]
**Python**
```
def f(A,B,N):
D={}
r=[]
for j in A:D[j]=0
for j in B:D[j]=0
x=len(D)
for i in xrange(10**(x-1),10**x):
c=str(i)
s={}
for j in c:s[j]=0
if(len(s)-x or '0' in c):continue
k=P=Q=0
for j in D:D[j]=int(c[k]);k+=1
for j in A:P=P*10+D[j]
for j in B:Q=Q*10+D[j]
if(P*N==Q):r.append((P,Q))
return r
print f(['T','W','O'], ['F','O','U','R'], 2)
```
<http://ideone.com/4wIQe>
[Answer]
### scala: 333 289
```
type S=String
def d(x:S,m:Map[Char,Int])={var s=0
for(c<-x;k=m.find(_._1==c);v=(k.get)._2){s*=10
s+=v}
s}
def s(t:Int,f:S,p:S):Unit={
def c(m:Map[Char,Int])=d(f,m)*t==d(p,m)
val g=f.toSet++p
val m=g.zip(util.Random.shuffle((1 to 9).toSeq).take(g.size))
if(c(m.toMap))print(m)else s(t,f,p)}
```
Usage:
```
s (2,"SPEED","KILLS")
Set((D,7), (K,8), (I,5), (E,6), (S,4), (L,3), (P,2))
s(4,"REPEAT","ANDSTOP")
// endless loop :)
```
[Answer]
## PHP (200)
This function takes a very long time to execute and uses lots of memory, but it satisfies the criteria.
```
function f($o,$s,$n){$w=count_chars(($c=join($o)).$d=join($s),3);while(++$i<pow(10,9)){if(($u=count_chars($i,3))&&$u[0]*$u[8]&&($n*$a=strtr($c,$w,$i))==$b=strtr($d,$w,$i))$x[]=array($a,$b);}return$x;}
```
Sample usage:
```
$a=array('T','W','O');
$b=array('F','O','U','R');
$c=f($a, $b, 2); // returns an array of tuples that satisfy the equation
```
Un-golfed explanation:
```
function solve($operand, $sum, $num) {
// convert the operand and sum arrays into strings, join them, then get a string containing the unique characters
$operand_string = join($operand);
$sum_string = join($sum);
$unique_chars = count_chars($operand_string . $sum_string, 3);
// loop from 1 to 10^9
while (++$i < pow(10,9)) {
// get the unique digits in $i
$unique_digits = count_chars($i, 3);
// check whether the first digit is non-zero (count_chars sorts in ascending order)
// and whether the ninth digit is non-zero, these conditions guarantee that $i
// is a permutation of 1...9
if ($u[0] * $u[8]) {
// translate the operand and sum into numbers, then check if the operand * num = sum
$translated_operand = strtr($operand_string, $unique_chars, $i);
$translated_sum = strtr($sum_string, $unique_chars, $i);
if ($num * $translated_operand == $translated_sum) {
// add the solution to the solutions array
$solutions[] = array($translated_operand, $translated_sum);
}
}
}
// return the solutions array
return $solutions;
}
```
If we're allowed to input the operand and sum as strings instead of arrays, then I can skip the join operations and save 20 characters to put the total at 180.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žhœï²JÙ©gδ£εUε®X‡].Δ`¹*Q
```
Takes two loose inputs, the first being the integer and the second as a pair of words (i.e. first input = `4`, second input = `["ANDSTOP","REPEAT"]`).
[Try it online.](https://tio.run/##AUEAvv9vc2FiaWX//8W@aMWTw6/CskrDmcKpZ860wqPOtVXOtcKuWOKAoV0uzpRgwrkqUf//MgpbIkZPVVIiLCJUV08iXQ) Brute-force approach, so unfortunately it's extremely slow; it's barely able to output the result for the first test case in ~45 seconds on TIO.
**Explanation:**
```
žh # Push builtin "0123456789"
œ # Get all 3628800 (10!) permutations of this string of digits
ï # Cast each to an integer to remove leading 0s from some items
# (otherwise ["0264","132"] would be the output for the first test case)
² # Push the second input-pair
J # Join them together
Ù # Uniquify the letters
© # Store it in variable `®` (without popping)
g # Pop and push its length to get the amount of unique letters
δ # For each permutation:
£ # Only keep the first unique-length amount of digits
ε # Map each shortened string of digits to:
U # Pop and store the current string of digits in variable `X`
ε # Map over the two words of the (implicit) second input-pair
® # Push the unique letters from variable `®`
X # Push the current digits we're mapping over from variable `X`
‡ # Transliterate the letters to digits in the input-string we're mapping over
] # Close the nested maps
.Δ # Find the first pair of integers which is truthy for:
` # Pop and push them separated to the stack
¹* # Multiply the second (top) value by the first input
Q # And check if it's now equal to the first value
# (after which the result is output implicitly)
```
] |
[Question]
[
As with most APL symbols, `⍉` has different meanings when called with one argument (transpose) versus two arguments (dyadic transpose / reorder dimensions). This challenge concerns the latter, which acts similarly to `numpy.moveaxis` in Python or `permute` in MATLAB, but is more powerful.
## `order ⍉ A` when `order` has distinct entries
When all members of `order` are distinct, `order ⍉ A` is equivalent to:
* `numpy.moveaxis(A, tuple(range(len(A.shape)), order)` in Python, or
* `permute(A,order)` in MATLAB. Quoting from [documentation](https://www.mathworks.com/help/matlab/ref/permute.html) of the latter:
>
> B = permute(A,order) rearranges the dimensions of A so that they are in the order specified by the vector order. The resulting array B has the same values as A but the order of the subscripts needed to access any particular element is rearranged as specified by order.
>
>
>
For example, suppose `A` is a 3D array, and let `B ← (2 0 1)⍉A`. Then B is such that `B[x0,x1,x2] = A[x2,x0,x1]` for all `x2,x0,x1`
## `order ⍉ A` when `order` has repeated entries
When `order` has repeated entries, we take a diagonal slice of the array. For example, let A be a 2x3x4 array. `B ← (0 0 1)⍉A` takes a diagonal slice along `A` to create `B` such that `B[x0,x1] = A[x0,x0,x1]`. Note that `B` is a 2x4 array: if it were 3x4, we would need to set `B[2, x1] = A[2, 2, x1]` which would be out of bounds of `A`. In general the `k`th dimension of `B` will be the minimum of all `A.shape[i]` such that `order[i] = k`.
## Example
Consider the dyadic transpose `order⍉A` where `order = [2, 1, 0]` and A is 3x4x5
```
A =
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
[[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]
[35 36 37 38 39]]
[[40 41 42 43 44]
[45 46 47 48 49]
[50 51 52 53 54]
[55 56 57 58 59]]]
```
The result is the 5x4x3 array B =
```
[[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
[[ 1 21 41]
[ 6 26 46]
[11 31 51]
[16 36 56]]
[[ 2 22 42]
[ 7 27 47]
[12 32 52]
[17 37 57]]
[[ 3 23 43]
[ 8 28 48]
[13 33 53]
[18 38 58]]
[[ 4 24 44]
[ 9 29 49]
[14 34 54]
[19 39 59]]]
```
Note that when, for example, (x0, x1, x2) = (4,1,2) we have `B[x0,x1,x2] = A[x2, x1, x0] = A[2,1,4] = 49`.
If instead `order = [0, 0, 0]` and `A` as above, then we would have the output `B` be the 1-dimensional size-3 array `B = [0, 26, 52]` so that `B[1] = B[x0] = A[x0,x0,x0] = A[1,1,1] = 26`
### Input
Here we use 0-indexing, but you may also use 1-indexing as is the APL default.
* A multidimensional or nested array `A`, of dimension *n* ≥ 1.
* A list `order` of *n* positive integers consisting of the integers {0,1,...,k} (or {1,...,k+1} for 1-index) for some *k* < *n*, in any order, possibly with repetitions.
### Output
* A multidimensional or nested array representing the result of applying the dyadic transpose with those arguments. (The output will have dimension *k+1*.)
You may write a full program, function, etc. as allowed by the current standard on meta.
If your language has a builtin, it is encouraged to also write a solution without the builtin for the sake of an interesting answer.
### Test cases
[Test cases on TIO](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE9QV1HWiDfRMYx/1LjF81LtC3THCNRgo6BgU5BgJpP1DQwJCQ9Qf9a561DZRQ8dQU8NQAUgYKYAghAdighhGCsYKJprVQHO9gv39QOYdWvGod9ej3q0aYKoTyNKsPbRC41HXoke9Wx51zHjUu/nwdH3NQytMNcBmgE1QMIUZZgyzx0jz/38A "APL (Dyalog Unicode) – Try It Online")
Reference Python implementation coming soon.
Note for reading test cases: in APL, the penultimate and ultimate axes of an array are along columns and rows in that order.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
This is [my colleague](http://www.dyalog.com/meet-team-dyalog.htm#Roger)'s code (slightly modified from [Roger Hui](https://en.wikipedia.org/wiki/Roger_Hui): [*A History of APL in 50 Functions*](http://www.jsoftware.com/papers/50/), [chapter 30](http://www.jsoftware.com/papers/50/50_30.htm)), posted with explicit permission.
Anonymous tacit infix lambda (can be used as drop-in for `⍉`).
```
{⍵[(⊂⊂⍺)⌷¨,¨⍳⍺[⍋⍺]{⌊/⍵}⌸(⍴⍵)[⍋⍺]]}
```
[Try it online!](https://tio.run/##vVHBSsNAEL33K@a2CURrEuM9lIoVbCRJUQk5BKReigrtRUIuCkVjtuhB7Fk8BC8eVJQe45/Mj8S3kXyBILvMvNmdefsem5xP1o4vksnZSV2nLD8ijfNLteVK5@KzKo2qZPmGMmJ5ixSnXORddGZcfGks3wH19i7O6jHP71guePEw8Di/ql63eH6PKvB7iOHOIOgkp1M0CRJGtLHuxCyfTZalcA/7AQ5d33ePkL1RuD8KBcsXEGiGqWsmIVik1m@loAIW2bSpp@DfDbyh4lOiV1CmNelGacyqEt6elOLrJSx9P3b1qnS0hqNhIKcls9t3LL0zm87@U@34L1rBCa02WZgULg0poAPqkw@BIXJAIRH1yAVCJQxBsIWh7b2wKvEtBLP1Dw "APL (Dyalog Unicode) – Try It Online")
`{`…`}` dfn; `⍺` is left argument (axes), `⍵` is right argument (array)
E.g. `[2,2,1]` and `[[[1,2],[3,4]]]`
`⍵[`…`]` index the array with:
`(⍴⍵)[`…`]` the shape (lengths of axes) of the array, indexed by:
`[1,2,2]`
`⍋⍺` the grading vector (the indices that would sort them) of the axes
`[3,1,2]`
`[2,1,2]`
`⍺[⍋⍺]{`…`}⌸` use the sorted axes as keys to group that, and for each group:
`[1,2,2]` → `{"1":[2],"2":[1,2]}`
`{⌊/⍵}` find the lowest axis length
`{"1":2,"2":1}` → `[2,1]`
`⍳` generate the indices in a Cartesian system of those dimensions
`[[[1,1]],[[2,1]]]`
`,¨` ensure that the indices of each coordinate is a vector (would be scalar if `⍵` is a vector)
`[[[1,1]],[[2,1]]]`
`(`…`)⌷¨` index into each of those with the following:
`⊂⊂⍺` the axes (doubly enclosed; once for `⌷` to select those cells along the first and only axis, and once for `¨` to pair up each vector on the right with the entire set of axes on the left)
`2 1 2`
`[[[1,1,1]],[[1,2,1]]]`
`[[1],[3]]`
] |
[Question]
[
# Introduction
This challenge is similar to [Project Euler](https://projecteuler.net/) problems. I came up with it because I was playing a deceivingly simple board game and couldn't come up with an efficient solution to answer a simple question about its mechanics.
[Quarto](https://en.wikipedia.org/wiki/Quarto_(board_game)) is a fun variant of 4 in a row. It is played on a 4 by 4 board with 16 unique pieces (no pieces are duplicated). Every turn each player places 1 piece on the board. Each piece has 4 binary characteristics (short/tall, black/white, square/circular, hollow/solid). The goal is to make four in a row, either horizontally, vertically or along the 2 diagonals, for any of the four characteristics! So 4 black pieces, 4 white pieces, 4 tall pieces, 4 short pieces, 4 square pieces, 4 circular pieces, 4 hollow pieces or 4 solid pieces.
[](https://i.stack.imgur.com/LoWhe.jpg)
The picture above shows a finished game, there is a four in a row because of 4 square pieces.
# Challenge
In Quarto, some games may end in a draw.
The total number of possible end positions is `16!`, about 20 trillion.
***How many of those end positions are draws?***
# Rules
1. The solution must be a program that **calculates** and outputs the total number of end positions that are draws. The correct answer is `414298141056`
2. You may only use information of the rules of the game that have been deduced manually (no computer assisted proof).
3. Mathematical simplifications of the problem are allowed, but must be explained and proven (manually) in your solution.
4. The winner is the one with the most optimal solution in terms of CPU running time.
5. *To determine the winner, I will run every single solution with a reported running time of less than 30m on a MacBook Pro 2,5 GHz Intel Core i7 with 16 GB RAM*.
6. No bonus points for coming up with a solution that also works with other board sizes. Even though that would be nice.
7. If applicable, your program must compile within 1 minute on the hardware mentioned above (to avoid compiler optimization abuse)
8. [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed
# Submissions
Please post:
1. The code or a github/bitbucket link to the code.
2. The output of the code.
3. Your locally measured running time
4. An explanation of your approach.
# Deadline
The deadline for submissions is March 1st, so still plenty of time.
[Answer]
# C: 414298141056 draws found in about 5 2.5 minutes.
Just simple depth-first search with a symmetry-aware transposition table. We use the symmetry of attributes under permutation and the 8-fold dihedral symmetry of the board.
```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef uint16_t u8;
typedef uint16_t u16;
typedef uint64_t u64;
#define P(i, j) (1 << (4 * (i) + (j)))
#define DIAG0 (P(0, 0) | P(1, 1) | P(2, 2) | P(3, 3))
#define DIAG1 (P(3, 0) | P(2, 1) | P(1, 2) | P(0, 3))
u64 rand_state;
u64 mix(u64 x) {
u64 a = x >> 32;
u64 b = x >> 60;
x ^= (a >> b);
return x * 7993060983890856527ULL;
}
u64 rand_u64() {
u64 x = rand_state;
rand_state = x * 6364136223846793005ULL + 1442695040888963407ULL;
return mix(x);
}
u64 ZOBRIST_TABLE[(1 << 16)][8];
u16 transpose(u16 x) {
u16 t = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (x & P(j, i)) {
t |= P(i, j);
}
}
}
return t;
}
u16 rotate(u16 x) {
u16 r = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (x & P(3 - j, i)) {
r |= P(i, j);
}
}
}
return r;
}
void initialize_zobrist_table(void) {
for (int i = 0; i < 1 << 16; i++) {
ZOBRIST_TABLE[i][0] = rand_u64();
}
for (int i = 0; i < 1 << 16; i++) {
int j = i;
for (int r = 1; r < 8; r++) {
j = rotate(j);
if (r == 4) {
j = transpose(i);
}
ZOBRIST_TABLE[i][r] = ZOBRIST_TABLE[j][0];
}
}
}
u64 hash_board(u16* x) {
u64 hash = 0;
for (int r = 0; r < 8; r++) {
u64 h = 0;
for (int i = 0; i < 8; i++) {
h += ZOBRIST_TABLE[x[i]][r];
}
hash ^= mix(h);
}
return mix(hash);
}
u8 IS_WON[(1 << 16) / 8];
void initialize_is_won(void) {
for (int x = 0; x < 1 << 16; x++) {
bool is_won = false;
for (int i = 0; i < 4; i++) {
u16 stride = 0xF << (4 * i);
if ((x & stride) == stride) {
is_won = true;
break;
}
stride = 0x1111 << i;
if ((x & stride) == stride) {
is_won = true;
break;
}
}
if (is_won == false) {
if (((x & DIAG0) == DIAG0) || ((x & DIAG1) == DIAG1)) {
is_won = true;
}
}
if (is_won) {
IS_WON[x / 8] |= (1 << (x % 8));
}
}
}
bool is_won(u16 x) {
return (IS_WON[x / 8] >> (x % 8)) & 1;
}
bool make_move(u16* board, u8 piece, u8 position) {
u16 p = 1 << position;
for (int i = 0; i < 4; i++) {
bool a = (piece >> i) & 1;
int j = 2 * i + a;
u16 x = board[j] | p;
if (is_won(x)) {
return false;
}
board[j] = x;
}
return true;
}
typedef struct {
u64 hash;
u64 count;
} Entry;
typedef struct {
u64 mask;
Entry* entries;
} TTable;
Entry* lookup(TTable* table, u64 hash, u64 count) {
Entry* to_replace;
u64 min_count = count + 1;
for (int d = 0; d < 8; d++) {
u64 i = (hash + d) & table->mask;
Entry* entry = &table->entries[i];
if (entry->hash == 0 || entry->hash == hash) {
return entry;
}
if (entry->count < min_count) {
min_count = entry->count;
to_replace = entry;
}
}
if (to_replace) {
to_replace->hash = 0;
to_replace->count = 0;
return to_replace;
}
return NULL;
}
u64 count_solutions(TTable* ttable, u16* board, u8* pieces, u8 position) {
u64 hash = 0;
if (position <= 10) {
hash = hash_board(board);
Entry* entry = lookup(ttable, hash, 0);
if (entry && entry->hash) {
return entry->count;
}
}
u64 n = 0;
for (int i = position; i < 16; i++) {
u8 piece = pieces[i];
u16 board1[8];
memcpy(board1, board, sizeof(board1));
u8 variable_ordering[16] = {0, 1, 2, 3, 4, 8, 12, 6, 9, 5, 7, 13, 10, 11, 15, 14};
if (!make_move(board1, piece, variable_ordering[position])) {
continue;
}
if (position == 15) {
n += 1;
} else {
pieces[i] = pieces[position];
n += count_solutions(ttable, board1, pieces, position + 1);
pieces[i] = piece;
}
}
if (hash) {
Entry* entry = lookup(ttable, hash, n);
if (entry) {
entry->hash = hash;
entry->count = n;
}
}
return n;
}
int main(void) {
TTable ttable;
int ttable_size = 1 << 28;
ttable.mask = ttable_size - 1;
ttable.entries = calloc(ttable_size, sizeof(Entry));
initialize_zobrist_table();
initialize_is_won();
u8 pieces[16];
for (int i = 0; i < 16; i++) {pieces[i] = i;}
u16 board[8] = {0};
printf("count: %lu\n", count_solutions(&ttable, board, pieces, 0));
}
```
Measured score (@wvdz):
```
$ clang -O3 -march=native quarto_user1502040.c
$ time ./a.out
count: 414298141056
real 1m37.299s
user 1m32.797s
sys 0m2.930s
```
Score (user+sys): 1m35.727s
[Answer]
# Java, 414298141056 draws, 23m42.272s
I hope it's not frowned upon to post a solution to one's own challenge, but the reason that I posted this challenge in the first place was that it drove me crazy that I couldn't come up with an efficient solution myself. My best try would take days to complete.
After studying [user1502040](https://codegolf.stackexchange.com/users/18957/user1502040)'s answer I actually managed to modify my code to run within a somewhat reasonable time. My solution is still significantly different, but I did steal some ideas:
* Instead of focusing on end positions, I focus on actually playing the game, putting one piece after another on the board. This allows me to build a table of semantically identical positions with the correct count.
* Realizing the order in which pieces are placed matters: they should be placed such that you maximize the chance of an early win.
The main difference between this solution and [user1502040](https://codegolf.stackexchange.com/users/18957/user1502040)'s is that I don't use a Zobrist table, but a canonical representation of a board, where I consider each board to have 48 possible transpositions over the characteristics (2 \* 4!). I don't rotate or transpose the whole board, but just the characteristics of the pieces.
This is the best I could come up with. Ideas for obvious or less obvious optimizations are most welcome!
```
public class Q {
public static void main(String[] args) {
System.out.println(countDraws(getStartBoard(), 0));
}
/** Order of squares being filled, chosen to maximize the chance of an early win */
private static int[] indexShuffle = {0, 5, 10, 15, 14, 13, 12, 9, 1, 6, 3, 2, 7, 11, 4, 8};
/** Highest depth for using the lookup */
private static final int MAX_LOOKUP_INDEX = 10;
public static long countDraws(long board, int turn) {
long signature = 0;
if (turn < MAX_LOOKUP_INDEX) {
signature = getSignature(board, turn);
if (cache.get(turn).containsKey(signature))
return cache.get(turn).get(signature);
}
int indexShuffled = indexShuffle[turn];
long count = 0;
for (int n = turn; n < 16; n++) {
long newBoard = swap(board, indexShuffled, indexShuffle[n]);
if (partialEvaluate(newBoard, indexShuffled))
continue;
if (turn == 15)
count++;
else
count += countDraws(newBoard, turn + 1);
}
if (turn < MAX_LOOKUP_INDEX)
cache.get(turn).put(signature, count);
return count;
}
/** Get the canonical representation for this board and turn */
private static long getSignature(long board, int turn) {
int firstPiece = getPiece(board, indexShuffle[0]);
long signature = minTranspositionValues[firstPiece];
List<Integer> ts = minTranspositions.get(firstPiece);
for (int n = 1; n < turn; n++) {
int min = 16;
List<Integer> ts2 = new ArrayList<>();
for (int t : ts) {
int piece = getPiece(board, indexShuffle[n]);
int posId = transpositions[piece][t];
if (posId == min) {
ts2.add(t);
} else if (posId < min) {
min = posId;
ts2.clear();
ts2.add(t);
}
}
ts = ts2;
signature = signature << 4 | min;
}
return signature;
}
private static int getPiece(long board, int position) {
return (int) (board >>> (position << 2)) & 0xf;
}
/** Only evaluate the relevant winning possibilities for a certain turn */
private static boolean partialEvaluate(long board, int turn) {
switch (turn) {
case 15:
return evaluate(board, masks[8]);
case 12:
return evaluate(board, masks[3]);
case 1:
return evaluate(board, masks[5]);
case 3:
return evaluate(board, masks[9]);
case 2:
return evaluate(board, masks[0]) || evaluate(board, masks[6]);
case 11:
return evaluate(board, masks[7]);
case 4:
return evaluate(board, masks[1]);
case 8:
return evaluate(board, masks[4]) || evaluate(board, masks[2]);
}
return false;
}
private static List<Map<Long, Long>> cache = new ArrayList<>();
static {
for (int i = 0; i < 16; i++)
cache.add(new HashMap<>());
}
private static boolean evaluate(long board, long[] masks) {
return _evaluate(board, masks) || _evaluate(~board, masks);
}
private static boolean _evaluate(long board, long[] masks) {
for (long mask : masks)
if ((board & mask) == mask)
return true;
return false;
}
private static long swap(long board, int x, int y) {
if (x == y)
return board;
if (x > y)
return swap(board, y, x);
long xValue = (board & swapMasks[1][x]) << ((y - x) * 4);
long yValue = (board & swapMasks[1][y]) >>> ((y - x) * 4);
return board & swapMasks[0][x] & swapMasks[0][y] | xValue | yValue;
}
private static long getStartBoard() {
long board = 0;
for (long n = 0; n < 16; n++)
board |= n << (n * 4);
return board;
}
private static List<Integer> allPermutations(int input, int size, int idx, List<Integer> permutations) {
for (int n = idx; n < size; n++) {
if (idx == 3)
permutations.add(input);
allPermutations(swapBit(input, idx, n), size, idx + 1, permutations);
}
return permutations;
}
private static int swapBit(int in, int x, int y) {
if (x == y)
return in;
int xMask = 1 << x;
int yMask = 1 << y;
int xValue = (in & xMask) << (y - x);
int yValue = (in & yMask) >>> (y - x);
return in & ~xMask & ~yMask | xValue | yValue;
}
private static int[][] transpositions = new int[16][48];
static {
for (int piece = 0; piece < 16; piece++) {
transpositions[piece][0] = piece;
List<Integer> permutations = allPermutations(piece, 4, 0, new ArrayList<>());
for (int n = 1; n < 24; n++)
transpositions[piece][n] = permutations.get(n);
permutations = allPermutations(~piece & 0xf, 4, 0, new ArrayList<>());
for (int n = 24; n < 48; n++)
transpositions[piece][n] = permutations.get(n - 24);
}
}
private static int[] minTranspositionValues = new int[16];
private static List<List<Integer>> minTranspositions = new ArrayList<>();
static {
for (int n = 0; n < 16; n++) {
int min = 16;
List<Integer> elems = new ArrayList<>();
for (int t = 0; t < 48; t++) {
int elem = transpositions[n][t];
if (elem < min) {
min = elem;
elems.clear();
elems.add(t);
} else if (elem == min)
elems.add(t);
}
minTranspositionValues[n] = min;
minTranspositions.add(elems);
}
}
private static final long ROW_MASK = 1L | 1L << 4 | 1L << 8 | 1L << 12;
private static final long COL_MASK = 1L | 1L << 16 | 1L << 32 | 1L << 48;
private static final long FIRST_DIAG_MASK = 1L | 1L << 20 | 1L << 40 | 1L << 60;
private static final long SECOND_DIAG_MASK = 1L << 12 | 1L << 24 | 1L << 36 | 1L << 48;
private static long[][] masks = new long[10][4];
static {
for (int m = 0; m < 4; m++) {
long row = ROW_MASK << (16 * m);
for (int n = 0; n < 4; n++)
masks[m][n] = row << n;
}
for (int m = 0; m < 4; m++) {
long row = COL_MASK << (4 * m);
for (int n = 0; n < 4; n++)
masks[m + 4][n] = row << n;
}
for (int n = 0; n < 4; n++)
masks[8][n] = FIRST_DIAG_MASK << n;
for (int n = 0; n < 4; n++)
masks[9][n] = SECOND_DIAG_MASK << n;
}
private static long[][] swapMasks;
static {
swapMasks = new long[2][16];
for (int n = 0; n < 16; n++)
swapMasks[1][n] = 0xfL << (n * 4);
for (int n = 0; n < 16; n++)
swapMasks[0][n] = ~swapMasks[1][n];
}
}
```
Measured score:
```
$ time java -jar quarto.jar
414298141056
real 20m51.492s
user 23m32.289s
sys 0m9.983s
```
Score (user+sys): 23m42.272s
] |
[Question]
[
This is a variant of [Play the word chain](https://codegolf.stackexchange.com/questions/68725/play-the-word-chain) and [Building a long chain of words](https://codegolf.stackexchange.com/questions/44922/building-a-long-chain-of-words) .
---
The input is a non-empty list of unique words at least 2 chars long made of characters in [a-z]. You need to output the length of the longest possible chain, where each subsequent word starts with the last letter of the previous word. You can start with any word on the list.
Another twist is that you are allowed to repeat any single word on the list. However, you can not repeat any two-word block. For example,
`cat->tac->cat` is allowed, but `cat->tac->cat->tac` is not, because you repeated a two-word block (`cat->tac`). Also, you can not use the same word twice in a row (e.g. `eye->eye`).
## Examples:
* `cat dog tree egg` => 3 (cat->tree->egg)
* `new men ten whim` => 5 (ten->new->whim->men->new)
* `truth fret heart his` => 5 (fret->truth->heart->truth->his)
* `we were stew early yew easy` => 9 (stew->were->early->yew->were->easy->yew->we->easy)
* `tac cat tac cot tac can` => 6 (tac->cat->tac->cot->tac->can)
(Let me know if I made a mistake on any of these examples or if you come up with more.)
[Answer]
# [Python 3](https://docs.python.org/3/), 150 149 145 bytes
```
def f(d):
a=[[w]for w in d]
while a:b=a[0];a=[f+[l,y]for*f,l in a for y in{*d}-{b for a,b in zip(f,f[1:])if a==l}if l[-1]==y[0]]
return len(b)
```
[Try it online!](https://tio.run/##HVBLbsMgEN3nFCOvICVRouxc@SSIBa4Hm4pgC8ZCNMrZ3SGL@b83v63SssbHcUzowIlJ9iewg9bFuDVBAR9hMicoiw8Ith8Hq2/mmxHuSwdVG@rsVGg4C41S2X2dp/flNX5iq8ZW/PObcMrpe2@kdzxiCG@2QV/uZhgqN@UpCWlPEQJGMcqjsXPj6u7HEkzrDJQQAee5U9BFLPDECMTC6z1bjtJOCzjuAwvaxNrnli8IBRNCJiZxIVSoHy/XzvDFW/KRRL6G3z2TeNyk4l/ka96CJyGlPP4B "Python 3 – Try It Online")
The idea for constructing successively longer paths (or in this case trails) until none longer could be created was directly inspired by [grc's answer](https://codegolf.stackexchange.com/a/68735/63641) on the [Play the word chain](https://codegolf.stackexchange.com/questions/68725/play-the-word-chain) question.
[Answer]
# [Haskell](https://www.haskell.org/), ~~131~~ 141 bytes
Basically the brute force approach.. The idea is to generate all possible *domino pieces*, permute them, check if it's a valid combo and maximize the whole thing. The time complexity is ridiculous, the 4th test case already takes ~4s on my PC and on the TIO it doesn't seem to work!
```
import Data.List
p w=2+maximum[length$takeWhile(\(x,y)->x!!1==y!!0)$zip p$tail p|p<-permutations[[a,b]|(a,b)<-(,)<$>w<*>w,a/=b,last a==b!!0]]
```
[Try it online!](https://tio.run/##TVE9j9swDN39Kxgjg93a1@@hQJSlXQpcpw4dHKNgfGwknCULEg3FxaF/PaWcu6AQIH49Pj2RGuMjjePlYqyfAsNXZLy7N5ELD0m9f23xbOxsu5HcifWW8ZF@ajNSdajOzVK3@/Nm806pZbN5W2//GA9eMGYE/@R3radgZ0Y2k4tdh82xf6rkrndt1dS77T7tXu1Tg2/UsRkxMqBSRyHq@wtT5C8YKYIqADqounJALhsoH6ZTNhyIsqXTqewb@FALrMkwRynnLbkVdjVJG5thn24wDjPrXPodaOXVhOHqmHiDti18g2Gywsb0ACw1mGaGIw04RwLDkCcSASHlqUA1ObALWBy0cf/V/36Mz3zr62nVniisNvJVsygYl@wsL3FcspTPubUvijwUSBHo7EGJLCcjgc6ItDDgiExQyklRWg98yJ@JekoQJAaoXsItBFAqk0i@LnvhTlqU5DTI0mNRWDROAov@@y@o/Mw/ONy7u9kNcwgLZB013FZ0@Qc "Haskell – Try It Online")
### Ungolfed
```
p w = maximum
[ 2 + length c | p <- permutations [ [a,b] | (a,b) <- (,)<$>w<*>w
, a /= b
, last a == head b
]
, c <- [ takeWhile (\(x,y) -> x!!1 == y!!0) $ zip p (tail p) ]
]
```
*Edit*: Changed from Lambdabot to bare Haskell but saved a few bytes by golfing it, such that it's still less than `145` bytes :)
] |
[Question]
[
Sandboxed and made less complicated and hopefully more fun.
# Summary of the challenge
Given a number of particles, either identical bosons or identical fermions, output the total wave function of the state assuming they are all independent.
# Physics background
Don't worry, you don't need to know quantum mechanics to solve this challenge. I will explain what you need now.
**What is a wave function?**
In (non-relativistic) quantum mechanics every particle can be described with a function of the position called the *wave function*. If you have a system with more than one particle you can describe it using a wave function that will depend on the position of all the particles of the system. In this challenge we will only consider independent (i.e. non-interacting) particles. In this case the total wave function can be written as a combination of the wave function of the single particles. The way you can do this depends of the type of particles you have and the statistics they obey.
**Distinguishable particles**
Let's start from the case of *distinguishable particles* even if you will not need them for the challenge. Distinguishable particles are what you have in classical physics. Every object has is own identity. If I throw two coins I have a 25% chance of getting `TT`, 25% for `HH` and a 50% for `TH` because `TH` and `HT` are two different events.
For a system of distinguishable particles the total wave function is written as the product of the single wave functions. For a system of n particles, if we call `di` the i-th particle wave function and `xi` the i-th particle position we have a total wave function:
```
1 particle: d1(x1)
2 particles: d1(x1)d2(x2)
3 particles: d1(x1)d2(x2)d3(x3)
...
```
**Indistinguishable Bosons**
Now onto the weird stuff. When you get to the quantum level you will discover that particles with same properties are actually identical and thus obey a different statistics than classical particles. Back to the coin toss example we find that if we assume the coins to be indistinguishable, all the three events are equally likely, that is we have a 33% for `TT`, 33% for `HH` and 33% for `HT` because now `TH` and `HT` are the same event.
The total wave function for several bosons is **not** given by simply the product of the single particle wave functions, but as a sum of all the possible combinations of wave function and positions. You will understand better with some examples, using a similar notation than before:
```
1 boson: b1(x1)
2 bosons: b1(x1)b2(x2) + b2(x1)b1(x2)
3 bosons: b1(x1)b2(x2)b3(x3) + b2(x1)b1(x2)b3(x3) + b3(x1)b2(x2)b1(x3) + b1(x1)b3(x2)b2(x3) + b2(x1)b3(x2)b1(x3) + b3(x1)b1(x2)b2(x3)
...
```
What you have at the end is a total wave function that is *symmetric* (i.e. stays the same) for any exchange like `xi <-> xj` or `bi <-> bj`.
**Indistinguishable Fermions**
It gets even weirder! Fermions are not only indistinguishable but they also don't like being in the same state. This means that if you toss two fermion coins you are 100% guaranteed of getting `TH` since `TT` and `HH` are now prohibited.
The total fermion wave function is constructed the same way of the boson one, but instead of having all `+` signs, you have a `+` or a `-` depending on the *sign* of the permutation. For an odd number of swaps to get from the starting order to that permutation you have a `-` sign, for an even number you have a `+` sign.
```
1 fermion: f1(x1)
2 fermions: f1(x1)f2(x2) - f2(x1)f1(x2)
3 fermions: f1(x1)f2(x2)f3(x3) - f2(x1)f1(x2)f3(x3) - f3(x1)f2(x2)f1(x3) - f1(x1)f3(x2)f2(x3) + f2(x1)f3(x2)f1(x3) + f3(x1)f1(x2)f2(x3)
...
```
The total wave function is now *antisymmetric* (i.e. changes sign) for any exchange like `xi <-> xj` or `fi <-> fj`. If you have two equal wave functions the total wave function is zero.
# Algorithmic way of building the wave function
Suppose you have `3` particles of type `p` (`p=b`for bosons and `p=f` for fermions).
* Start from `p1(x1)p2(x2)p3(x3)`
* Build each possible swap of two wave functions (or equivalently coordinates)
+ `p1(x1)p2(x2)p3(x3)`
+ `p1(x1)p3(x2)p2(x3)`
+ `p2(x1)p1(x2)p3(x3)`
+ `p2(x1)p3(x2)p1(x3)`
+ `p3(x1)p1(x2)p2(x3)`
+ `p3(x1)p2(x2)p1(x3)`
* Determine the sign of the permutation (only for fermions)
* Join everything with the correct sign: `+` for bosons or the sign of the permutation for fermions
# Input
You will get two inputs (or a list of two items). One of them is a number from 0 to 9 inclusive (that will represent the number of particles, the other defines the type of particles in the system. You can choose the order of the input and the format of the two inputs. Some examples of inputs might be:
```
[n, type] | Meaning
---------------------------------------------------------------
[3, "boson"] | 3 bosons
[6, 'f'] | 6 fermions
[4, True] | 4 fermions (True = fermion, False = boson)
```
Remember to write in the answer how you are formatting your input.
# Output
You have to output the total wave function of the system that obeys the rules explained before. See the examples for an example of formatting. Bosons are represented as `bi`, fermions as `fi` and positions as `xi` where the index `i` goes from `1` to `n` (the number of particles).
Each output will have `n!` terms that contains the product of `n` terms summed together. The order inside each product or in the total sum does not matter, the important thing is the dependence of each wave function on the positions and the sign of each term.
The output must be a mathematically valid expression, so if you want to add explicit multiplication signs it is fine. You have the freedom of writing the variables and the function as you want, but there needs to be a clear distinction between fermions and bosons.
The output must be written as an explicit sum of explicit products, so no implicit summations or products, no summation signs, no product signs and no determinants of matrices.
The spaces in the example are just for clarity and you can decide not to output them.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
# Examples
```
Input -> Output
[0, b] -> 0 (or empty string)
[1, b] -> b1(x1)
[2, b] -> b1(x1)b2(x2) + b2(x1)b1(x2)
[3, b] -> b1(x1)b2(x2)b3(x3) + b2(x1)b1(x2)b3(x3) + b3(x1)b2(x2)b1(x3) + b1(x1)b3(x2)b2(x3) + b2(x1)b3(x2)b1(x3) + b3(x1)b1(x2)b2(x3)
[1, f] -> f1(x1)
[2, f] -> f1(x1)f2(x2) - f2(x1)f1(x2)
[3, f] -> f1(x1)f2(x2)f3(x3) - f2(x1)f1(x2)f3(x3) - f3(x1)f2(x2)f1(x3) - f1(x1)f3(x2)f2(x3) + f2(x1)f3(x2)f1(x3) + f3(x1)f1(x2)f2(x3)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~47~~ 46 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*He he, what a `ṭ€€ż€`...*
```
Ṭ€z0ÆḊ×”fe⁴¤«0ị⁾-+
ṭ€”xj@€⁾()
Œ!©ṭ€€ż€⁸Ǥ®Ñ€¤ż
```
A full program which prints such that the summands are in lexicographical order once the multiplications of particle functions are all ordered by the position arguments.
i.e.:
`f1(x1)f2(x2)...fn-1(xn-1)fn(xn)` (or `b...`) will always be first, followed by
`f1(x1)f2(x2)...fn(xn-1)fn-1(xn)`, and so on up to
`fn(x1)fn-1(x2)...f2(xn-1)f1(xn)`.
**[Try it online!](https://tio.run/##y0rNyan8///hzjWPmtZUGRxue7ij6/D0Rw1z01IfNW45tOTQaoOHu7sfNe7T1eZ6uHMtUBFQriLLAcRo3KehyXV0kuKhlVCZpjVH94AldhxuB2pdd3gikHdoydE9////N/6fBgA "Jelly – Try It Online")**
### How?
```
Ṭ€z0ÆḊ×”fe⁴¤«0ị⁾-+ - Link 1: get the sign character: list, permutation of [1,N], P
Ṭ€ - untruth €ach - that is [0,0,...,0,1] of length v for each v in P
z0 - transpose with filler 0 (yields transpose of the permutation matrix)
ÆḊ - determinant (yields the parity of the permutation)
¤ - nilad followed by link(s) as a nilad:
”f - literal character 'f'
⁴ - 4th command line argument = 2nd program input = particle type, T
e - exists in? (1 for "f", 0 for "b")
× - multiply (force all results from +1 or -1 to 0 for T="b")
«0 - minimum of that and 0 (force the +1s to 0s)
⁾-+ - literal list of characters = ['-', '+']
ị - index into (the -1s yield '-' while the 0s yield '+')
ṭ€”xj@€⁾() - Link 2: construct parenthesised positions: number of particles, N
”x - literal character = 'x'
ṭ€ - tack for €ach -> [['x', 1], ['x', 2], ..., ['x', N]]
⁾() - literal list of characters = ['(', ')']
j@€ - join with swapped @rguments for €ach -> [['(', 'x', 1, ')'],...]
Œ!©ṭ€€ż€⁸Ǥ®Ñ€¤ż - Main link: number of particles, N; type of particle P
Œ! - all permutations of N -> [[1,2,...,N-1,N],[1,2,...,N,N-1],...]
© - copy to the register and yield
ṭ€€ - tack T for €ach for €ach (place the type in front of every number)
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument, N
Ç - call last link (2) as a monad (get the "(xn)"s)
ż€ - zip with for €ach (make all the summands)
¤ - nilad followed by link(s) as a nilad:
® - recall value from register (the permutations of N)
Ñ€ - call the next link (1) as a monad for €ach (get the signs)
ż - zip the signs and the summands.
- implicit print
```
[Answer]
# Python3, 320 bytes:
```
R=range
def f(a,b):
q,s=[([*R(a)],0)],{str([*R(a)]):0}
while q:
c,k=q.pop(0)
for x in R(a):
for y in R(x,a):
C=eval(str(c));O=C[y];C[y]=C[x];C[x]=O
if str(C)not in s:s[str(C)]=k+1;q+=[(C,k+1)]
return''.join(['-','+'][b=='b'or s[j]%2==0]+''.join(f'{b}{eval(j)[k]+1}(x{k+1})'for k in R(a))for j in s)[1:]
```
[Try it online!](https://tio.run/##bY/BboMwEETvfMVeKnuLG0FyqUA@8QGRcrV8gBQ3QGTAkBSE@HZqk3JBPdjafZ4ZjZuxv9X69NmYZblwk@rv3PvKFSiasgwjD1rWcUHF@4WmKFlgz9T1ZgMYBbMHP7finkNr1XBlFW8PTd3QAO2qagMDFBqc2r2vZHyRgf0xSHj@TO/UBV8R4zNPxChjd9lpcNMg@XmVFgqcLEFd9y6mizrxApJXfhi3vq2bMDui9MDk/cNoQg5lXWgqyAdhxCdSZJyTjNgqnSjl25HzQPqbSpEpm6e1UImikn4402GygTMS177a/oNuK9cSKMJILo0pdE8VDRjYdERvA@EeHPfg9J9F7S1qb3Fg@QU)
] |
[Question]
[
The dice game [Mia](https://en.wikipedia.org/wiki/Mia_(game)) introduces a very non-trivial order of sets of size two:
```
{3,1} < {3,2} < {4,1} < {4,2} < {4,3} < {5,1} < {5,4} < {6,1} < {6,5} < {1,1} < {2,2} < {6,6} < {1,2}
```
In general, the order within a tuple does not matter `{x,y}={y,x}`,
`{1,2}` is greater than anything else,
Pairs are greater than non-pairs and the numeric value decides in case of a tie.
Now suppose you want to use `n` dice. Also, the dices have `m` faces.
Example:
* `{1,5,3,4} < {1,2,6,3}` since 5431 < 6321
* `{1,2,3,5} < {1,1,5,6} < {1,1,5,5}, {1,1,6,6} < {1,1,1,3} < {2,2,2,3} < {1,1,1,1} < {1,2,3,4}`
* **`{2,2,5} < {1,1,6}`** since both sets have each one pair and 611 > 522
In a nutshell, `{1, ..., n}` is greater than anything else.
Let `p > q`, then p-of-a-kind is greater than q-of-a-kind.
In case of a tie, the second(, third, ...)-longest of-a-kind wins.
Finally, if no decision could be made yet, the greatest numerical value wins.
The numerical value of a set is the largest integer you can build from the available numbers in the set, using concatenation. Example:
* `{2,5,4,3}` becomes 5432
* `{4,11,3,4}` becomes B443 (>6-faced dice are allowed, B=11)
Your task is to write the smallest possible program (i.e. function) in the language of your choice, that, given two containers (list, array, set, ...) returns whether the first or the second one wins.
Note: you can assume that the two containers have the same length and contain only positive integers, but nothing else. Especially they may be not sorted. The return value could be anything, e.g. {-1, 0, 1} for {first wins, tie, second wins}.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṢŒrUṢṚZ
Ṣ⁼J;ǵÐṀ
```
Takes a list of lists each of which represents a roll (so can be more than two if wanted) and returns a list of the winner(s).
**[Try it online!](https://tio.run/nexus/jelly#@/9w56Kjk4pCgdTDnbOiuID0o8Y9XtaH2w9tPTzh4c6G////R0cb6igAkZmOgmmsjgKUB0IoPGMEzxSh0ggooaNggsIDyxmBeUYo@oA2mMXGAgA)** ...alternatively [here](https://tio.run/nexus/jelly#@/9w56Kjk4pCgdTDnbOiuID0o8Y9XtaH2w9tPTzv////0dGGOgpAZKajYBqrowDlgRAKzxjBM0WoNAJK6CiYoPDAckZgnhGKPqANZrGxAA) is a version which sorts the rolls from weakest to strongest instead.
### How?
```
Ṣ⁼J;ǵÐṀ - Main link: list of list of dice rolls, L
µÐṀ - filter keep maximal (i.e. sort L by the previous link as a key and keep maximums)
- e.g. [5,3,1,3]
Ṣ - sort roll [1,3,3,5]
J - range(length(roll)) [1,2,3,4]
⁼ - equal? [1,2,3,...n] beats everything 0
Ç - call last link as a monad with input roll [[2,1,1],[3,5,1]]
; - concatenate [0,[2,1,1],[3,5,1]]
ṢŒrUṢṚZ - Link 1, rest of sort key: dice rolls e.g. [5,3,1,3]
Ṣ - sort the roll [1,3,3,5]
Œr - run length encode [[1,1],[3,2],[5,1]]
U - upend (reverse each) [[1,1],[2,3],[1,5]]
Ṣ - sort [[1,1],[1,5],[2,3]]
Ṛ - reverse [[2,3],[1,5],[1,1]]
Z - transpose [[2,1,1],[3,5,1]]
- ...this is a list of: 1) the group sizes descending; and
2) the face values of each group, descending across equal group sizes
```
[Answer]
## JavaScript (ES6), 162 bytes
```
(a,b,g=a=>a.map(n=>e[n]=e[n]+1||1,e=[1])&&[[...e].every(n=>n==1),...e.filter(i=x=>x).sort(h=(a,b)=>b-a),...a.sort(h)],c=g(a),d=g(b))=>d.map((n,i)=>n-c[i]).find(i)
```
Explanation: Takes two arrays as parameters. `g` converts each array into a list of counts. The list is then checked to see whether it corresponds to a set `1..n`. The counts are sorted and the sorted values are concatenated. The two results are then compared. The return value is a positive integer if the second array wins and a negative integer if the first array wins, otherwise the falsy JavaScript value `undefined` is returned.
[Answer]
# PHP 333 Bytes
I assume that there are fewer dices then faces for the highest value as street beginning with 1
I make a little more. Input is an array with more then two values.
Output is the sorted array.
```
<? $m=$_GET[m];foreach($m as$k=>$v){rsort($v);$m[$k]=$v;}function t($a,$b){if($a==$r=range($x=count($a),1))return 1;elseif($b==$r)return-1;$c=array_pad(array_values(array_count_values($a)),$x,0);$d=array_pad(array_values(array_count_values($b)),$x,0);rsort($c);rsort($d);if($e=$c<=>$d)return$e;return$a<=>$b;}usort($m,t);print_r($m);
```
## Breakdown
```
$m=$_GET["m"]; # Array as Input
foreach($m as$k=>$v){
rsort($v); # reverse sort of an item
$m[$k]=$v; # replace the sort item
}
function t($a,$b){ #sorting algorithm
if($a==$r=range($x=count($a),1))return 1; # $a is highest value
elseif($b==$r)return-1; # $b is highest value
$c=array_pad(array_values(array_count_values($a)),$x,0);
# prepare check multiple values for fist value
$d=array_pad(array_values(array_count_values($b)),$x,0);
# prepare check multiple values for second value
rsort($c);
rsort($d);
if($e=$c<=>$d)return$e; # compare first and second multiples
return$a<=>$b; # compare dices
}
usort($m,"t"); # start sort
print_r($m); #print sorted array from low to high
```
[Answer]
# Julia (489 Bytes)
```
function a(x,y)l=length;g=collect;s=sort;m=maximum;r=repmat;function b(z)w=sum(r(z,1,m(z)).==r(g(1:m(z))',l(z),1),1);u=zeros(m(w));map(i->if i>0 u[i]+=1;end,w);return u end;function c(x,y)if l(x)>l(y)return-1 elseif l(x)<l(y)return 1 else for i=l(x):-1:1 if x[i]>y[i] return-1 elseif x[i]<y[i] return 1 end end;return 0;end end;x=s(x);y=s(y);if x==y return 0;elseif x==g(1:l(x));return-1 elseif y==g(1:l(y))return 1 else d=c(b(x),b(y));if d==0 return c(x,y);else return d;end end end
```
Readable:
```
1 function a(ds1, ds2)
2 function countNOfAKind(ds)
3 # return array. n-th value is number of occurences of n-of-a-kind.
4 # e.g. findNOfAKind([1, 1, 1, 2, 2, 3, 3]) == [0, 2, 1]
5 ps = sum(repmat(ds, 1, maximum(ds)) .== repmat(collect(1:maximum(ds))', length(ds), 1), 1);
6 ls = zeros(maximum(ps));
7 map(i -> if i>0 ls[i] += 1 end, ps);
8 return ls
9 end
10
11 function cmpLex(ds1, ds2)
12 # compare ds1, ds2 reverse-lexicographically, i.e. compare last distinct value.
13 if length(ds1) > length(ds2)
14 return -1
15 elseif length(ds1) < length(ds2)
16 return 1
17 else
18 for i = length(ds1):-1:1
19 if ds1[i] > ds2[i]
20 return -1
21 elseif ds1[i] < ds2[i]
22 return 1
23 end
24 end
25 return 0;
26 end
27 end
28
29 ds1=sort(ds1);
30 ds2=sort(ds2);
31 if ds1 == ds2
32 return 0;
33 elseif ds1 == collect(1:length(ds1))
34 return -1
35 elseif ds2 == collect(1:length(ds2))
36 return 1
37 else
38 d = cmpLex(countNOfAKind(ds1), countNOfAKind(ds2))
39 if d == 0
40 return cmpLex(ds1, ds2);
41 else
42 return d;
43 end
44 end
45 end
```
] |
[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/106641/edit).
Closed 7 years ago.
[Improve this question](/posts/106641/edit)
This was inspired by part of the 2016 ARML competition Team Problem #6.
Here's the challenge:
You're given a "wildcard sequence", which is a sequence of digits and another character. A string matches this wildcard sequence by the following pseudocode:
```
w = wildcard
s = string
# s matches w iff
for all 0 >= i > wildcard.length, w[i] == '?' or s[i] == w[i]
```
Where '?' is a character of your choice.
In terms of regex, just imagine the `'?'` to be `'.'`.
The challenge is to find all square numbers (the requirement is up to 1 million) whose decimal string representations match this wildcard sequence. The "wildcard character" can be any ASCII character of your choice, as long as it isn't a digit, obviously.
For example, `4096` matches `4**6` and `4*9*` but `4114` does not match either.
## Input
Input will be given as a sequence matching the regex `[0-9?]+`. This can be a string, a character array, or a byte array of the characters in ASCII.
## Output
Output will be a whatever-you-want-delimited list/set/array of numbers which are perfect squares and match the wildcard sequence.
## Examples of valid inputs:
```
1234567*90
1234567?90
1234567u90
['1', '2', '3', '4', '5', '6', '7', '*', '9', '0']
[49, 50, 51, 52, 53, 54, 55, 42, 57, 48]
[1, 2, 3, 4, 5, 6, 7, '*', 9, 0]
```
## Examples of valid outputs:
```
[1, 4, 9]
1 4 9
1, 4, 9
1-4-9
```
etc.
## Specifications
* You may not use builtins for finding a list of squares in a certain range
* [Standard Loopholes Apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* You must be able to handle up to 1 000 000 (1 million)
* If provided with the input `1******`, it is correct to print `[1000000]`. It is also correct to print `[1000000, 1002001, 1004004, 1006009, 1008016, 1010025, ...]`
* Wildcard sequences will never start with the wildcard character; that is, they will always match strings of the same length.
## Test Cases
```
4**6 -> [4096, 4356]
1**1 -> [1521, 1681]
1** -> [100, 121, 144, 169, 196]
9****9 -> [908209, 915849, 927369, 935089, 946729, 954529, 966289, 974169, 986049, 994009]
9*9*** -> [919681, 929296]
1**0* -> [10000, 10201, 10404, 10609, 12100, 14400, 16900, 19600]
9***4 -> [91204, 94864, 97344]
```
## Winning
Shortest (valid) (working) submission by February 14th, tie-break by earliest submission winning.
[Answer]
# Mathematica, 44 bytes
```
Print@@@IntegerDigits[Range@1*^3^2]~Cases~#&
```
The input is a list of digits with a `_` (no quotes) as a wildcard. e.g. `{4, _, _, 6}`
**Explanation**
```
Range@1*^3
```
Generate list `{1, 2, 3, ... , 1000}`
```
... ^2
```
Square it. (list of all squares from 1 to 1,000,000)
```
IntegerDigits[ ... ]
```
Split each square into a list of digits.
```
... ~Cases~#
```
Find the ones that match the pattern specified by the input.
```
Print@@@ ...
```
Print them.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes
```
@e:{@$|,}a#0:{c.~^#I,}f
```
[Try it online!](https://tio.run/nexus/brachylog#@@@QalXtoFKjU5uobGBVnaxXF6fsqVOb9v@/kqWWlpaJ0v8oAA "Brachylog – TIO Nexus")
### Explanation
```
@e Split into a list of characters
:{@$|,}a Replace each digit char by the corresponding digit, and each things
that are ot digits into variables
#0 All elements of the resulting list must be digits
:{ }f Output is the result of finding all...
c. ...concatenations of those digits which...
.~^#I, ...result in a number which is the square of an integer #I
```
### Different input format, 13 bytes
Depending on what your consider valid as input, you could do this:
```
#0:{c.~^#I,}f
```
[Try it online!](https://tio.run/nexus/brachylog#@69sYFWdrFcXp@ypU5v2/3@0pZWjlZOVs5VJ7P8oAA "Brachylog – TIO Nexus")
which is basically the second part of the answer above, with a list as input containing digits and variables where the wildcards are.
I don't consider this valid though because there are only 26 variable names in Brachylog (the uppercase letters), so this would not work if you had more than 26 wilcards.
[Answer]
# [Perl 6](http://perl6.org/), ~~30~~ 26 bytes
*Thanks to @b2gills for -4 bytes!*
```
{grep /^<$_>$/,map * **2,^1e4}
```
```
{grep /^<$_>$/,(^1e4)»²}
```
Uses the dot as wildcard character, so that the input can be used as a regex:
```
{ } # a lambda
^1e4 # range from 0 to 9999
map * **2, # square each value
grep / /, # filter numbers that match this regex:
<$_> # lambda argument eval'ed as sub-regex
^ $ # anchor to beginning and end
```
[Try it online](https://glot.io/snippets/em5hsxv0ft).
A variant that accepts the asterisk as wildcard (as suggested by a previous revision of the task description) would be 42 bytes:
```
{grep /^<{.trans("*"=>".")}>$/,(^1e4)»²}
```
[Answer]
# Ruby, 54 bytes
Function that takes a string argument. [Try it online.](https://repl.it/FJCV)
```
->s{(0..1e3).map{|i|"#{i**2}"[/^#{s.tr ?*,?.}$/]}-[p]}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
Probably plenty of room for improvement here.
Any non-digit is okay as wildcard.
```
3°LnvyS¹)ø€Æ0QPyg¹gQ&—
```
[Try it online!](https://tio.run/nexus/05ab1e#@298aINPXlll8KGdmod3PGpac7jNIDCgMv3QzvRAtUcNU/7/j1a3VNdR10LCJuqxAA "05AB1E – TIO Nexus")
Explanation to come after further golfing.
[Answer]
## Batch, 109 bytes
```
@for /l %%i in (0,1,999)do @set/aj=%%i*%%i&call copy nul %%j%%.%%j%%$>nul
@for %%s in (%1.%1$)do @echo %%~ns
```
Uses `?` as the wildcard. Works by creating 1000 files. The name of the file is the square number, and the extension of the file is the square number with a `$` suffixed. This is because Batch's pattern matching counts trailing `?`s as optional, so `1?` will match both `1` and `16`; the `$` therefore forces the match to be exact. However, we don't want to output the `$`, so we just output the file name only without extension.
[Answer]
# JavaScript (ES6), ~~68~~ 66 bytes
**EDIT:** Updated my solution below after being inspired by [JungHwan Min's answer](https://codegolf.stackexchange.com/a/106646/11182). It is now ES6 compliant.
Takes input in the format `'1..4'` where `.` is the wildcard.
Instead of iterating to 1e6 and square rooting this one iterates to 1e3 and squares.
```
p=>[...Array(1e3)].map((_,n)=>''+n*n).filter(n=>n.match(`^${p}$`))
```
```
F=p=>[...Array(1e3)].map((_,n)=>''+n*n).filter(n=>n.match(`^${p}$`))
const update = () => {
console.clear();
console.log(F(input.value));
}
submit.onclick = update;
update();
```
```
<input id="input" type="text" value="9....9" style="width: 100%; box-sizing: border-box" /><button id="submit">submit</button>
```
# JavaScript (ES7), ~~71~~ 69 bytes
```
p=>[...Array(1e6).keys()].filter(n=>n**.5%1?0:(''+n).match(`^${p}$`))
```
Creates an array of numbers from 0 to 1e6 then filters it by numbers that are square and match the pattern.
It is horrendously slow because it always iterates to 1e6.
```
F=p=>[...Array(1e6).keys()].filter(n=>n**.5%1?0:(''+n).match(`^${p}$`))
const update = () => {
console.clear();
console.log(F(input.value));
}
submit.onclick = update;
update();
```
```
<input id="input" type="text" value="9....9" style="width: 100%; box-sizing: border-box" /><button id="submit">submit</button>
```
[Answer]
# Perl, 42 45 38 bytes
EDIT: clarification by Alex, we can use the period as wildcard character which shaves off the y// operation.
```
perl -pe 's|.*|@{[grep/^$&$/,map$_*$_,1..1e3]}|'
```
EDIT: solution that uses the asterisk as wildcard character and expects the wildcard sequence on STDIN
```
perl -pe 'y/*/./;s|.*|@{[grep/^$&$/,map$_*$_,1..1e3]}|'
```
This one leaves undoubtedly a lot of room for improvement, it's pretty straightforward. The wildcard expression is expected as command line argument, with the period wildcard character (what else?).
```
say"@{[grep/^$ARGV[0]$/,map$_*$_,1..1e3]}"
```
[Answer]
# Python 3 - ~~98~~ 97 bytes
```
import re;print(re.findall(r"\b"+input()+r"\b",("\n".join([str(x*x) for x in range(1,1001)]))))
```
Requires input like '4..6'.
[Answer]
# k - 28 characters
```
{s(&:)($:s:s*s:!1001)like x}
```
Uses `?` as the wildcard character. The `like` function uses `?` as a wildcard, and this function makes a list of the first 1001 squares (to be inclusive to 1M), casts them all to strings, and then checks where they match the pattern.
```
{s(&:)($:s:s*s:!1001)like x} "1??"
100 121 144 169 196
```
[Answer]
# bash + Unix utilities, 33 bytes
```
dc<<<'0[2^pv1+lax]dsax'|grep ^$1$
```
This uses '.' as the wildcard character.
The dc program prints the square numbers in an infinite loop:
```
0 Push 0 on the stack.
[ Start a macro (called a).
2^ Square the number at the top of the stack.
p Print the number at the top of the stack, followed by a newline.
v Replace the number at the top of the stack (a square number) with its square root.
1+ Increment the number at the top of the stack.
lax Run the macro again (looping).
] End of the macro.
dsax Store the macro in register a and run it.
```
The dc output is piped to grep, which prints just the squares that match the required pattern.
This works when I run it on an actual Linux or OS X system (but it doesn't work at TIO, probably because the dc program tries to recurse forever, and I suspect TIO runs out of stack space for the recursion and/or has a problem with the never-ending pipe).
] |
[Question]
[
This question is written because ["Thing Explainer"](https://xkcd.com/thing-explainer/) is fun to read, and gave me an idea.
Write "stuff that makes computer do things" that reads/takes a set of letters, numbers and things like this `"#%|?` and returns `True / 1` if all words are part of [this set](http://xkcd.com/simplewriter/words.js?cache=6f3c4ed1c04dc0b6c30d46e2ea451210).
If all words are not part of that set, return the words that were not a part of it.
---
**[This website](http://xkcd.com/simplewriter/) can be considered correct in all cases.** The rules are written to follow the specs on that site.
---
# Examples:
**Truthy**:
*The code should return a truthy value if the entire text above the first horizontal line is pasted as input.*
The following lines should return a truthy value (input is separated by `###`)
```
This returns "Hello, World!"
###
tHiS rEtUrNs TrUe...
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
This set of stuff "#!^{>7( must return true
```
**Falsey**:
In the following examples, input and output are separated by `***`. Different test cases are separated by `###`.
```
This code doesn't return "Hello, World!"
***
code
###
tHiS rEtUrN"s false...
***
s
false
```
**More detailed rules:**
* You can use [this](http://xkcd.com/simplewriter/) to test your code.
* Non-letters are interpreted as spaces by the code, except for words like `'wasn't'`. The words with apostrophes that returns `true` are included in the list
+ For instance: `foo123bar` should return `foo` and `bar`, since they are not part of the list, and `123` can be interpreted as spaces
* The input will only contain printable ASCII code points [10, 32-126].
* Words can contain mixed case letters. See second test case.
* The list of words
+ should be taken as input (STDIN, function argument or equivalent)
+ can be modified (words can be separated by newline, comma etc., and you might sort the list)
+ Note that you can not use [this](http://splasho.com/upgoer5/phpspellcheck/dictionaries/1000.dicin) list (it's not identical)
* The output can be on any format you like
* The output can be upper, lower or mixed case (optional)
* There shall be no symbols in the output
---
For the record, Jonathan Allan found a strange corner case: the implementation on XKCD will actually ignore any letters after an apostrophe up to the next non-[A-Z][a-z]['] - for example `find's found`, and `find'qazxswedc found'` both return nothing, whereas `find'qazx.swedc found` returns `swedc`.
You can choose if you want to return nothing for `find'qazxswedc found'`, or return `qazxswedc`. Returning `qazx, swedc` for `find'qazx.swedc` is also OK.
[Answer]
## PowerShell v3+, ~~105~~ 92 bytes
```
param($a,$b)$x=@();-split($b-replace"[^a-zA-Z']",' ')|%{if($_-notin$a){$x+=$_}};($x,1)[!$x]
```
Takes simple words like `$a`, and words like `$b`. Makes helper `$x`. Take each word in `$b` and get rid of any bad not letters, then check each one `|{...}`. If that word is not in `$a`, then we add it to `$x`. At the end, we choose `$x` or `1` by not `$x`. That is sent out, either `words` or `1`.
### Some words to try
```
PS C:\Tools\Scripts\golfing> ('This returns "Hello, World!"','tHiS rEtUrNs TrUe...','Thing Explainer is a book written by a man.
The man writes books with simple words.','This set of stuff "¤!^¤>7\ must return true'|%{"$_";(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This returns "Hello, World!"
###
1
###
tHiS rEtUrNs TrUe...
###
1
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
1
###
This set of stuff "¤!^¤>7\ must return true
###
1
PS C:\Tools\Scripts\golfing> ("This code doesn't returns Hello, World!",'tHiS rEtUrN"s false...'|%{"$_`n***`n"+(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This code doesn't returns Hello, World!
***
code
###
tHiS rEtUrN"s false...
***
s false
```
[Answer]
# Python, 93 bytes
```
import re
lambda w,s:[w for w in re.sub("[^'\w]|\d|_",' ',w).split()if w.lower()not in s]or 1
```
All test cases are at **[ideone](http://ideone.com/UZdHg2)**
Preprocessing of the list is to split on `|` and put it in a `set` (which I imagine is fine if pre-sorting is allowed). Input words as `w` and the set as `s`.
If that's not allowed this becomes 98 bytes with `not in s` becoming `not in set(s)`.
We could preprocess it to have all permutations of upper and lower case characters too and save 8 bytes, but I think that might be going too far (that would be a huge set).
] |
[Question]
[
Convert a classical directory structure like this:
```
config.yml
drafts
begin-with-the-crazy-ideas.textile
on-simplicity-in-technology.markdown
includes
footer.html
header.html
```
Into this
```
.
├── config.yml
├── drafts
| ├── begin-with-the-crazy-ideas.textile
| └── on-simplicity-in-technology.markdown
└── includes
├── footer.html
└── header.html
```
* Four spaces specify a nested folder or file of the above dir.
* Nested categories levels allowed can vary.
*Update*
* **filenames**: valid Linux filenames without spaces and linefeeds: any byte except `NUL`, `/` and `spaces`, `linefeeds`
* drawing characters:
+ **|** vertical line (U+007C)
+ **─** box drawings light horizontal (U+2500)
+ **├** box drawings light vertical and right (U+251C)
**Winner**: Shortest Code in Bytes wins!
[Answer]
## [Retina](https://github.com/m-ender/retina), 88 bytes
```
m`^ *
$&├──
{4}
|
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
^
.¶
```
[Try it online!](http://retina.tryitonline.net/#code=bWBeICoKJCbilJzilIDilIAgCiB7NH0KfCAgIApUK2B84pScYCDilJRgKD88PSguKSopLig_IS4rwrYoPz4oPzwtMT4uKSopW3zilJzilJRdKQpeCi7Ctg&input=Y29uZmlnLnltbApkcmFmdHMKICAgIGJlZ2luLXdpdGgtdGhlLWNyYXp5LWlkZWFzLnRleHRpbGUKICAgIG9uLXNpbXBsaWNpdHktaW4tdGVjaG5vbG9neS5tYXJrZG93bgppbmNsdWRlcwogICAgZm9vdGVyLmh0bWwKICAgIGhlYWRlci5odG1sCiAgICAgICAgZm9vCiAgICAgICAgYmFyCiAgICBibGFoCiAgICAgICAgYmx1YmIKICAgICAgICB0aGlzLWlzLWEtZmlsZQ)
I suppose I could technically count this as one byte per character by swapping out some characters, reading the source as ISO 8859-1 and then finding a single-byte encoding for the output which contains `├` and `└`, but I can't be bothered to work out the details right now. (For the record, that would be 72 bytes.)
### Explanation
**Stage 1: Substitution**
```
m`^ *
$&├──
```
We start by matching the indentation on each line and inserting `├──`.
**Stage 2: Substitution**
```
{4}
|
```
Next, we match every group of 4 spaces and replace the first with a `|`. Now all that needs fixing is `|` that go to the bottom of the output and `├` that should be `└`. Both of those cases can be recognised by looking at the character directly below the one we potentially want to change.
**Stage 3: Transliteration**
```
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
```
The `(?<=(.)*)` counts how many characters precede the match on the current line to measure it's horizontal position. Then the lookahead skips to the next line with `.+¶`, matches as many characters as we've captured in group `1` with `(?>(?<-1>.)*)` (to advance to the same horizontal position) and then checks whether the next character (i.e. the one below the actual match) is one of `|├└`. If that's the case, the match fails, and in all other cases it succeeds and the stage substitutes spaces for `|` and `└` for `├`.
This won't fix all characters in a single run, so we apply this stage repeatedly with the `+` option until the output stops changing.
**Stage 4: Substitution**
```
^
.¶
```
All that's left is the first line, so we simply match the beginning of the string and prepend a `.` and a linefeed.
[Answer]
## JavaScript (ES6), ~~237~~ 128 bytes
```
f=(s,r=`.\n`+s.replace(/^ */gm,"$&└── "),q=r.replace(/^(.*)( |└)(?=.+\n\1[|└])/m,(_,i,j)=>i+`|├`[+(j>' ')]))=>q==r?r:f(s,q)
```
Where `\n` represents the literal newline character. Explanation: `r` is created from `s` by prepending the `.` line and inserting the `└──` at the end of each line's indent. This is now correct for the last line of the input, but each `└` must be "extended" upwards as far as possible. This is the job of `q`, which searches for a `└` and recursively replaces the spaces directly above it with `|`s unless it reaches another `└` which gets turned into `├` instead. The recursion ends when no further replacements can be made. Note that if the character above the `└` is a space or a `└` then the text to the left of the `└` is always the same as that on the previous line so I can just use `\1` to test that the one character is above the other.
] |
[Question]
[
Write a function that takes two parameters: a positive integer *n* and a list of words.
Given a cube of *n*-by-*n*-by-*n* units, assign a random letter (A-Z) to each surface unit. (For a 3x3x3 cube, there would be 9 surface units on each face.)
Then determine whether it's possible for an ant walking along the surface (with the ability to cross faces) to spell each of the supplied words. Assume that to spell a word, the letters must be up/down or left/right adjacent, but not necessarily on the same face. [**Edit, for clarity:** The ant can reverse its path and use letters more than once. Each surface unit counts as one character, so to spell a word with repeated letters (e.g. "see") the ant would have to visit three adjacent units.]
The function should output two things:
1) Each of the letters on each face, in such a way that the topology can be inferred. For instance, for a 2x2x2 cube, an acceptable output would look like:
```
QW
ER
TY OP UI
DF JK XC
AS
GH
LZ
VB
```
2) Each of the words, along with a boolean representing whether it's possible for the ant to spell the word by walking along the surface of the cube. For instance:
```
1 ask
0 practical
1 pure
0 full
```
**Bonus challenge (will not factor into score, just for fun):** Instead of *n* representing only the size of the cube, let *n* also represent the dimensionality of the shape. So, an *n* of 2 would yield a 2x2 square; an *n* of 3 would yield a 3x3x3 cube; and an *n* of 4 would yield a 4x4x4x4 tesseract.
[Answer]
# Ruby, 272 bytes
Two unnecessary newlines are added to the code either side of nested function `g` to improve readability. These are excluded from the score. The characters `f=` which assign the anonymous function to a variable are also excluded.
Output format is `0` or `1` per the question instead of Ruby's native `true` and `false`. A newline (rather than a space) is used to separate the boolean and the word. My understanding is that this is an acceptable interpretation of the output requirements, but if not, the impact on the byte count would be minor.
```
f=->n,l{c=''
x=[p=6*n,1,-p,-1]
(m=3*p*n).times{|i|c<<(5+i/n%6-i/n/p&6==6?65+rand(26):i%p==p-1?10:46)}
q=m+3*n
puts c
g=->w,i,d{w==''?$r=1:c[i]<?A?g[w,(i+x[d])%q,d^1]:w[0]==c[i]&&4.times{|j|g[w[1..-1],(i+x[j])%q,j^1]}}
l.each{|w|$r=0
m.times{|i|c[i]>?@&&g[w,i,0]}
puts $r,w}}
```
**Output**
After about 50 calls like this:
```
f[4,['PPCG','CODE','GOLF','ANT','CAN','CUBE','WORD','WALK','SPELL']]
```
I finally got the following output with 2 hits. `ANT` is at the bottom right going upwards, and the `AN` is shared by `CAN`, with the `C` wrapping round to top left.
```
....KCAAXRHT...........
....ALRZXRKL...........
....NDDLCMCT...........
....ETQZHXQF...........
........FYYUSRZX.......
........CFNPAUVX.......
........ZTJVHZVQ.......
........AUWKGVMC.......
............XWKSDWVZ...
............DPLUVTZF...
............DMFJINRJ...
............ZRXJIAFT...
0
PPCG
0
CODE
0
GOLF
1
ANT
1
CAN
0
CUBE
0
WORD
0
WALK
0
SPELL
```
**Explanation**
The particular unfolding of the cube selected, was chosen partly for its ease of drawing, but mainly for its ease of searching.
The non-alphabet characters (the dots plus the newline at the end of each line) are an important part of the field where the ant may be found walking.
Searching is performed by the recursive function `g`, which is nested in function `f` . If the word passed is an empty string the search is complete and `$r` is set to 1. If the ant is on a letter square which corresponds to the first letter of the word, the search is continued in all four directions: the function is called again with the word shortened by removing its first letter. In this case the direction parameter is ignored. The moving is done by recursively calling with the cell index altered by the values in `x.` The result of the addition is taken modulo the size of the grid plus an extra half line. This means that the bottom line wraps round to the top and vice versa, with the correct horizontal offset.
If the ant is on a non-letter square, she must zigzag in a staircase motion until she finds a letter square. She will zizag in southeast or northwest direction. This is simulated by recursive calls with the `d` parameter being XORed with 1 each time to keep track of her movement. Until she reaches the next letter square, there is no shortening of the input word. Conveniently, this may be done by the same recursion as is used when we are searching in the area with letters. The difference is, the recursion has only one branch when the ant is in the whitespace area, as opposed to 4 in the letter area.
**Commented code**
```
->n,l{ #n=square size, l=list of words to search
c='' #empty grid
x=[p=6*n,1,-p,-1] #offsets for south, east, north, west. p is also number of characters per line
(m=3*p*n).times{|i| #m=total cells in grid. for each cell
c<<(5+i/n%6-i/n/p&6==6? #apppend to c (according to the formula)
65+rand(26): #either a random letter
i%p==p-1?10:46) #or a "whitespace character" (newline, ASCII 10 or period, ASCII 46)
}
q=m+3*n #offset for vertical wraparound = grid size plus half a row.
puts c #print grid
g=->w,i,d{ #search function. w=word to search for, i=start index in grid, d=direction
w==''? #if length zero, already found,
$r=1: #so set flag to 1. Else
c[i]<?A? #if grid cell is not a letter
g[w,(i+x[d])%q,d^1]: #recursively call from the cell in front, with the direction reflected in NW-SE axis
w[0]==c[i]&& #else if the letter on the grid cell matches the start of the word
4.times{|j| #for each direction (iterate 4 times, each time a different direction is "in front")
g[w[1..-1],(i+x[j])%q,j^1]} #recursively call from the cell in front. Chop first letter off word.
} #Direction parameter is XORed (reflected in NW-SE axis) in case ant hits whitespace and has to zigzag.
l.each{|w| #for each word in the list
$r=0 #set global variable $r to zero to act as a flag
m.times{|i|c[i]>?@&&g[w,i,0]} #call g from all cells in the grid that contain a letter
puts $r,w} #output flag value and word
}
```
] |
[Question]
[
Usually when performing an internet challenge, there's no problem with having to specify a user agent, but when it comes to dealing with Google, it changes.
Google blacklists the Urllib user agent, presumably to stop spambots, so you have to specify a user agent. This takes up many bytes, and is frankly rather annoying.
[Example 1.](https://codegolf.stackexchange.com/a/54134/30525) [Example 2.](https://codegolf.stackexchange.com/a/40019/30525) [Example 3.](https://codegolf.stackexchange.com/a/40027)
***Note:*** I have updated my Python answers to use the tip suggested below
So how do you get around this problem using the shortest number of bytes?
[Answer]
The [requests module](http://www.python-requests.org/en/latest/), if allowed, is much shorter and easier than urllib in Python (2 and 3):
```
__import__('requests').get('url').text
```
On my computer, the user agent defaults to:
```
python-requests/2.3.0 CPython/3.4.3 Darwin/14.3.0
```
] |
[Question]
[
Knockout is a basketball game where players take turns shooting. It is played as a sequence of two-player contests, each of which has the possibility of "knocking out" one of those players.
Suppose the players are `A B C D` and their chances of shooting and making a basket are `0.1 0.2 0.3 0.4` respectively, independently of the other player in the contest. The two players at the front of the line, `A` and `B`, "fight." Since `A` goes first, he is the *defender*, in danger of being eliminated, and `B` is the *attacker*, and not in danger of immediate elimination. `A` shoots first. If `A` makes it, `A` has successfully defended, and goes to the back of the line. The line would change to `B C D A`. If `A` doesn't make it, then `B` shoots. If `B` makes it, then `A` is out and `B` goes to the back of the line, so the line becomes `C D B`. If neither `A` nor `B` makes it, the process repeats, with `A` shooting again, until either `A` or `B` makes a basket.
Suppose the line changed to `B C D A` (`A` had successfully defended). Now, `B` and `C` "fight," with `B` being the defender, and `C` being the attacker. This process repeats until only one person is left over. That person is the winner.
Your task is to calculate the probabilities of each person winning given the chance that they will make a basket.
**Input**:
A list of numbers, such as `0.1 0.2` or `0.5 0.5 0.5 0.5`, where the *n*th number is the chance that the *n*th player will make a basket. You can take this input in any format you like, including as the parameters to a function.
**Output**:
A list of numbers, where the *n*th number is the chance that the *n*th player will win the game. Your numbers must be accurate to at least two decimal places at least 90% of the time. This means that you can use a simulation-based approach. However, if your code is not simulation based (it is *guaranteed* to return a correct answer to at least 6 decimal places) then take away 30% from your score.
Example between `0.5 0.5`: Call the players `A` and `B`. Let `p` be the probability of A winning. `A` has a `2/3` chance of successfully defending (since there's a `1/2` chance that `A` scores, a `1/4` chance that `A` misses and `B` scores, and a `1/4` chance that both miss and the process repeats). If `A` fails to defend, he is knocked out and `B` wins. If `A` defends, then the line becomes `B A`. Since the situation is symmetric, the probability of `A` winning is `(1 - p)`. We get:
`p = 2/3 * (1 - p) + 1/3 * 0`. Solving, we get `p = 2/5`. The output should be `2/5 3/5` or `0.4 0.6`.
I'm not good enough with probability to do more complex examples.
If you need more test cases, here are a few:
```
0.1 0.2 0.3 0.4 --> 0.01 0.12 0.25 0.62
0.99 0.99 --> 0.5 0.5 (it's not exact, but if you round to two decimal places, you get 0.5 and 0.5)
```
[Answer]
## CJam (84 80 chars \* 0.7 = 56)
```
{_,({_,,{_2$m<(;(+Q0\)\++m>\}%)_(+.{X2$-*_@+/}1\{1$*\1$-}%)1\-f/.f*:.+}{,da}?}:Q
```
[Online demo](http://cjam.aditsu.net/#code=%5B0.1%200.2%200.3%200.4%5D%0A%0A%7B_%2C(%7B_%2C%2C%7B_2%24m%3C(%3B(%2BQ0%5C)%5C%2B%2Bm%3E%5C%7D%25)_(%2B.%7BX2%24-*_%40%2B%2F%7D1%5C%7B1%24*%5C1%24-%7D%25)1%5C-f%2F.f*%3A.%2B%7D%7B%2Cda%7D%3F%7D%3AQ%0A%0A~%60). This is a recursive function which takes an array of doubles and returns an array of doubles. The online demo includes a tiny amount of scaffolding to execute the function and format the output for display.
### Dissection
The basic principle is that if there are `n > 1` players left, one of them must be the next one to be knocked out. Moreover, the order of the queue after that happens depends only on the initial order of the queue and on who gets knocked out. So we can make `n` recursive calls, calculate the winning probabilities for each player in each case, and then we just need to weight appropriately and add.
I'll label the input probabilities as `[p_0 p_1 ... p_{n-1}]`. Let `f(a,b)` denote the probability that `a` fails to defend against `b`. In any given round, the probability that `a` defends successfully is `p_a`, the probability that `b` knocks `a` out is `(1-p_a)*p_b`, and the probability that it goes to another round is `(1-p_a)*(1-p_b)`. We can either do an explicit sum of a geometric progression or we can argue that the two geometric progressions are proportional to each other to reason that `f(a,b) = (1-p_a)*p_b / (p_a + (1-p_a)*p_b)`.
Then we can step up a level to full rounds of the line. The probability that the first player is knocked out on is `f(0,1)`; the probability that the second player is knocked out is `(1-f(0,1)) * f(1,2)`; the third player is `(1-f(0,1)) * (1-f(1,2)) * f(2,3)`; etc until the last one is knocked out with probability `\prod_i (1-f(i,i+1)) * f(n-1,0)`. The same argument about geometric progressions allows us to use these probabilities as weights, with normalisation by a factor of `1 / \prod_i f(i, i+1 mod n)`.
```
{ e# Define a recursive function Q
_,({ e# If we have more than one person left in the line...
_,,{ e# Map each i from 0 to n-1...
_2$m< e# Rotate a copy of the probabilities left i times to get [p_i p_{i+1} ... p_{n-1} p_0 ... p_{i-1}]
(;(+ e# i fails to defend, leaving the line as [p_{i+2} ... p_{n-1} p_0 ... p_{i-1} p_{i+1}]
Q e# Recursive call
0\)\++ e# Insert 0 for the probability of i winning and fix up the order
m>\ e# Rotate right i times and push under the list of probabilities
}%
) e# Stack: [probs if 0 knocked out, probs if 1 knocked out, ...] [p_0 p_1 ...]
_(+.{ e# Duplicate probs, rotate 1, and pointwise map block which calculates f(a,b)
X2$-*_@+/ e# f(a,b) = (1-p_a)*p_b / (p_a + (1-p_a)*p_b) TODO is the d necessary?
}
1\{1$*\1$-}% e# Lift over the list of f(a,b) a cumulative product to get the weights TODO is the d necessary?
)1\-f/ e# Normalise the weights
.f* e# Pointwise map a multiplication of the probabilities for each case with the corresponding weight
:.+ e# Add the weights across the cases
}{,da}? e# ...else only one left, so return [1.0]
}:Q
```
] |
[Question]
[
When you search for something on [Google](http://www.google.com), it conveniently gives a message near the top of the page saying something like `About 53,000,000 results (0.22 seconds)`. (The numbers change depending on what was searched of course.)
In this challenge you will write a program that draws a [logarithmic](http://en.wikipedia.org/wiki/Logarithmic_scale) ASCII graph of the number of results given by Google when all the non-empty [prefixes](http://en.wikipedia.org/wiki/Substring#Prefix) of a given *search-phrase* are searched.
A *search-phrase* is defined as one or more strings of lowercase alphanumeric characters, separated by one space from each other. In Regex a search-phrase is `(?:[a-z0-9]+ )*[a-z0-9]+`.
So `im ok`, `r`, and `1a 2` are all search-phrases, but `I'm OK`, `R`, `1a 2`, and , are not.
(The character restrictions are in place because Google rarely takes case or special symbols into account. Escaping non-alphanumeric characters in URLs is also a hassle.)
# Spec
Your program must take in a search-phrase and a positive floating point number H from either stdin or the command line. (You can assume they are valid and it's fine if you need quotes or something around the search-phrase.)
As a working example let's assume the search phrase is `a car` and H = 0.75.
**Step 1:**
Gather the non-empty prefixes of your search-phrase, **and put them in double quotes**. The quotes ensure that that the exact phrase will be searched for, avoiding any ['did you mean...'](https://www.google.com/#q=did+you+mea) redirections.
Exclude all prefixes that end in a space such as `a[space]`.
```
Prefixes
"a"
"a c"
"a ca"
"a car"
```
**Step 2:**
Search each of these terms exactly as they appear using <https://www.google.com>, and note the number of results returned.
```
Search Term Message Results
"a" About 6,950,000,000 results (0.27 seconds) 6950000000
"a c" About 861,000,000 results (0.27 seconds) 861000000
"a ca" About 2,990,000 results (0.30 seconds) 2990000
"a car" About 53,900,000 results (0.39 seconds) 53900000
```
**If the search term [did not match any documents](https://www.google.com/#q=%22termnotfound+xzqzx%22), put a 0 in the `Results` column.**
**Step 3:**
Compute `y = floor(H * log10(r + 1))` for each row, where r is the `Results` value. H is still 0.75 here.
```
Search Term Results y
"a" 6950000000 7
"a c" 861000000 6
"a ca" 2990000 4
"a car" 53900000 5
```
**Step 4:**
Arrange `y` number of vertical bars (`|`) above the last character of each unquoted search term, using spaces to fill empty areas, in a sort of bar graph.
```
|
| |
| | |
| |||
| |||
| |||
| |||
a car
```
This graph is the final result of your program and the only thing it needs to output. It should go to stdout.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program [in bytes](https://mothereff.in/byte-counter) wins.
# Notes
* You may use URL shorteners or other search tools/APIs as long as the results would be the same as searching <https://www.google.com>.
* I know that double quotes are [not a surefire way](https://www.google.com/#q=%22quotes+always+work+zxz%22) to exclude "did you mean..." redirections. Adding `&nfpr=1` to the URL [doesn't always work either](https://www.google.com/#q=fun+mat&nfpr=1). Don't worry about these inaccuracies. Just look for the `About X results...` message no matter what pops up, or set `Results` to 0 if there is none.
* There is an empty column above any space in the search-phrase in the graph.
* The graph should not be wider or taller than it needs to be (e.g. with whitespace).
* It's ok if your program has side effects like opening a web browser so the cryptic Google html/js pages can be read as they are rendered.
[Answer]
## Ruby, ~~316~~ 295 bytes
```
require 'open-uri'
s,h=*$*
r=[]
s.size.times{|i|r<<(s[i]==' '?'':?|*(h.to_f*Math.log10((URI.parse("http://google.com/search?q=#{URI::encode ?"+s[0..i]+?"}").read[/About [\d,]+ results/]||?0).gsub(/\D/,'').to_i+1)).floor)+s[i]}
puts r.map{|l|l.rjust(r.map(&:size).max).chars}.transpose.map &:join
```
Unfortunately, the requests just stopped working on the online tester I was using, so I need to golf this down further tonight or tomorrow.
Explanation: I'm taking the input via ARGV. Then I'm just sending a request for each substring that doesn't end in a space, find the results via regex (and default to `0` if the regex doesn't match), and then build the histogram with horizontal bars. At the end, I'm reversing all lines and transposing them to create the vertical histogram.
] |
[Question]
[
Take a following character table:
```
-------------------------------------------------------
| |1233456 | abc | xyz | | |
|-------|--------|--------|--------|--------|---------|
| |abcdefgh| 1234567| | 12345 | |
| abc |xyzabcqw| | | | |
| |zzzz | | | | |
|-------|--------|--------|--------|--------|---------|
```
It can have a variable number of columns or rows. Column width and row height can vary. Cells can be empty or have text, but the row height is optimized to wrap the text. So, second row has three lines because second cell content in second row is three lines high.
Input is ASCII text as shown in example. Cells can not contain | or - characters. Cell content should be [escaped](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML), but no need to worry about rowspan and colspan, since the table structure is always simple (every row same number of columns and every column same number of rows).
Output should be well-formed [xhtml](http://en.wikipedia.org/wiki/XHTML). Html table should reflect the table structure, content and line breaks. So, resulting html based on the sample input above is the following:
```
<table>
<tr>
<td></td>
<td>1233456</td>
<td>abc</td>
<td>xyz</td>
<td></td>
<td></td>
</tr>
<tr>
<td>abc</td>
<td>abcdefgh<br/>xyzabcqw<br/>zzzz</td>
<td>1234567</td>
<td></td>
<td>12345</td>
<td></td>
</tr>
</table>
```
Shortest code which takes this table and turns it into an xhtml table wins.
[Answer]
# K, 186
Haven't put any effort into golfing this.
```
{-1',/(,"<",g;,/{,/(,"<tr>";x;,"</tr>")}'{("<td>",/:*:'x),\:"</td>"}'{{$[1<+/~""~/:x;,"<br/>"/:x;x@&~""~/:x]}'+x}'-1_'/:1_'/:f@&~()~/:f:$`$"|"\:''1_'(&"-"in/:x)_x;,"</",g:"table>");}
```
.
```
k)t
"-------------------------------------------------------"
"| |1233456 | abc | xyz | | |"
"|-------|--------|--------|--------|--------|---------|"
"| |abcdefgh| 1234567| | 12345 | |"
"| abc |xyzabcqw| | | | |"
"| |zzzz | | | | |"
"|-------|--------|--------|--------|--------|---------|"
k){-1',/(,"<",g;,/{,/(,"<tr>";x;,"</tr>")}'{("<td>",/:*:'x),\:"</td>"}'{{$[1<+/~""~/:x;,"<br/>"/:x;x@&~""~/:x]}'+x}'-1_'/:1_'/:f@&~()~/:f:$`$"|"\:''1_'(&"-"in/:x)_x;,"</",g:"table>");} t
<table>
<tr>
<td></td>
<td>1233456</td>
<td>abc</td>
<td>xyz</td>
<td></td>
<td></td>
</tr>
<tr>
<td>abc</td>
<td>abcdefgh<br/>xyzabcqw<br/>zzzz</td>
<td>1234567</td>
<td></td>
<td>12345</td>
<td></td>
</tr>
</table>
```
[Answer]
# Ruby: 233 characters
```
BEGIN{puts"<table>";f=[]};if/^[-|]+$/ then if f!=[] then puts"<tr>\n#{f[1..-2].map{|i|" <td>#{i.join"<br/>"}</td>"}*$/}\n</tr>\n";f=[]end else$F.each_index{|i|f[i]||=[];f[i]<<CGI.escapeHTML($F[i])if$F[i]>""}end;END{puts"</table>"}
```
Sample run:
```
bash-4.2$ ruby -naF' *\| *' -r cgi -e 'BEGIN{puts"<table>";f=[]};if/^[-|]+$/ then if f!=[] then puts"<tr>\n#{f[1..-2].map{|i|" <td>#{i.join"<br/>"}</td>"}*$/}\n</tr>\n";f=[]end else$F.each_index{|i|f[i]||=[];f[i]<<CGI.escapeHTML($F[i])if$F[i]>""}end;END{puts"</table>"}' table.txt
<table>
<tr>
<td></td>
<td>1233456</td>
<td>abc</td>
<td>xyz</td>
<td></td>
<td></td>
</tr>
<tr>
<td>abc</td>
<td>abcdefgh<br/>xyzabcqw<br/>zzzz</td>
<td>1234567</td>
<td></td>
<td>12345</td>
<td></td>
</tr>
</table>
```
(Out of contest CW, due to the shameless amount of used command line options.)
[Answer]
# GNU Awk: 277 characters
```
BEGIN{split("38&60<62>34\"39'",e,/\W/,c)
FS=" *\\| *"
print"<table>"}/^[-|]+$/&&n{print"<tr>"
for(i=2;i<n;i++)print" <td>"f[i]"</td>"
print"</tr>"
delete f
next}{for(i=1;i<6;i++)gsub(c[i],"\\&#"e[i]";")
for(i=2;i<n=NF;i++)$i&&f[i]=f[i](f[i]?"<br>":"")$i}END{print"</table>"}
```
Note that the above code requires `gawk` version 4.0 or never, because
* `delete` for an entire array is GNU extension
* `split()`'s 4th parameters was implemented in version 4.0
## Without HTML escaping: 201 characters
As there is not specified how HTML escaping should happen (whether the use of built-in or third party functions is allowed, the set of characters to escape, whether using entity names or character codes matters), I believe this challenge was neater without the escaping:
```
BEGIN{FS=" *\\| *"
print"<table>"}/^[-|]+$/&&n{print"<tr>"
for(i=2;i<n;i++)print" <td>"f[i]"</td>"
print"</tr>"
delete f
next}{for(i=2;i<n=NF;i++)$i&&f[i]=f[i](f[i]?"<br>":"")$i}END{print"</table>"}
```
Sample run:
```
bash-4.1$ awk -f table.awk table.txt
<table>
<tr>
<td></td>
<td>1233456</td>
<td>abc</td>
<td>xyz</td>
<td></td>
<td></td>
</tr>
<tr>
<td>abc</td>
<td>abcdefgh<br>xyzabcqw<br>zzzz</td>
<td>1234567</td>
<td></td>
<td>12345</td>
<td></td>
</tr>
</table>
```
] |
[Question]
[
The challenge is to implement a 2-dimensional ray tracing program, text-based.
Sources of white light are `@` symbols. `R`, `G` and `B` are light filters. `/` and `\` are mirrors with 80% reflectivity. `?` is a light sensor. `>`, `<`, `^` and `V` combine light in the appropriate direction (e.g. if one red and one green came into a `>` the light would be emitted toward the right and it would be yellow). Other non-whitespace characters absorb all light. Light is emitted from `@` symbols in **four** directions.
When the program is run, it should produce output the same as the input, but with traced rays. Because this is 2 dimensional, and I guarantee in the input no rays will ever cross, there will be no problem with that. Each ray should be represented by a letter; r=red, g=green, b=blue, c=cyan, m=magenta, y=yellow, w=white. There won't be any ternary colors, ever. The casing is important to differentiate it from the input. After that output, the values of light captured by the question marks (in order of their appearance, left to right top to bottom) should be outputted as percentages and colors. For example, this input:
```
/ @
-
\R> ?
@B/
```
Should give the output:
```
/wwwwwwwwwwwwwwwwww@w
w -
w\R>mmmmmmmmmmmmmmmmm?
w b
@B/
#1: 72% Magenta
```
Another important point to note - when two colors are combined using a "prism" (the arrows) the strength of the combined light becomes the average strength of the two. Output must be *exactly as specified* (e.g. #x: [x][x]x% *Color*).
If your language cannot read from STDIN and write to STDOUT, create a function (anonymous or lambda when available) that accepts the input as an argument and returns the result.
Directives to the compiler, structures required or recommended for all or most programs created in the language, etc. can be omitted. For example, `#include` and `using` directives (but not `#define`) may be removed in C-style languages, `#/usr/bin/perl -options` in Perl, and
```
Module Module1
Sub Main()
End Sub
End Module
```
in VB.NET, for example. If you import namespaces or add include directives, please note them in your answer.
Is that hard enough, now? :)
[Answer]
## Python, 602 559 614 chars
```
import sys
S=sys.stdin.readlines()
X=max(len(s)for s in S)
I='#'*X+''.join(t[:-1]+' '*(X-len(t))+'\n'for t in S)+'#'*X
L=len(I)
R=range(L)
B=[0]*L
C=[0]*L
for p in R:
if'@'!=I[p]:continue
for d in(1,-1,X,-X):
q=p;c=7;b=100.
while 1:
q+=d;a=I[q];B[q]+=b;C[q]|=c
if a in'\/':d=(ord(a)/30-2)*X/d;b*=.8
elif a in'RGB':c&=ord(a)/5-12
elif a in'><^V':d={'>':1,'<':-1,'^':-X,'V':X}[a];b/=2
elif' '!=a:break
print''.join(I[p]if' '!=I[p]else' bgcrmyw'[C[p]]for p in R[X:-X])
i=0
for p in R:
if'?'==I[p]:i+=1;print'#%d:'%i,'%.0f%%'%B[p],[0,'Blue','Green','Cyan','Red','Magenta','Yellow','White'][C[p]]
```
Edit: fixed so it doesn't need trailing spaces.
[Answer]
## F#
```
#nowarn "0025"
open System
type MirrorDirection = bool
type LightDirection = bool * bool
type Sq =
| Air // [ ]
| Mirror of MirrorDirection // [/] [\]
| FilterR
| FilterG
| FilterB
| Sensor // [?]
| Combine of LightDirection // [^] [v] [<] [>]
| Emitter // [@]
| Wall of Char // non-whitespace
let [ mL; mR ] : MirrorDirection list = [ true; false ]
(* true T^/
F</>F
/vT false
*)
let [ dN; dS; dW; dE ] : LightDirection list = [ true, true; false, true; true, false; false, false ]
let bounce (m : MirrorDirection) ((a, b) : LightDirection) =
m <> a, not b
let dv (a : LightDirection) =
if a = dN then 0, -1
elif a = dS then 0, 1
elif a = dW then -1, 0
else 1, 0
let fo<'a> : (('a option)[,] -> 'a seq) =
Seq.cast
>> Seq.filter Option.isSome
>> Seq.map Option.get
let input = Console.In.ReadToEnd().Replace("\r\n", "\n")
let sqs =
input.Split('\n')
|> Array.map (fun x ->
x.ToCharArray()
|> Array.map (
function
| ' ' | '\t' | '\v' -> Air
| '/' -> Mirror mL
| '\\' -> Mirror mR
| 'R' -> FilterR
| 'G' -> FilterG
| 'B' -> FilterB
| '?' -> Sensor
| '^' -> Combine dN
| 'v' -> Combine dS
| '<' -> Combine dW
| '>' -> Combine dE
| '@' -> Emitter
| x -> Wall x
)
)
let w =
Array.map Array.length sqs
|> Set.ofArray
|> Set.maxElement
let h = sqs.Length
let ib x y = -1 < x && x < w && -1 < y && y < h
let arr = Array2D.init w h (fun x y ->
if x < sqs.[y].Length then
sqs.[y].[x]
else
Air
)
let board =
Array2D.map (
function
| _ -> 0.0, 0.0, 0.0
) arr
let mutable rays =
Array2D.mapi (fun x y a ->
match a with
| Emitter -> Some(x, y)
| _ -> None
) arr
|> fo
|> Seq.map (fun (x, y) ->
[|
dN, x, y, 1., 1., 1.
dS, x, y, 1., 1., 1.
dW, x, y, 1., 1., 1.
dE, x, y, 1., 1., 1.
|]
)
|> Seq.reduce Array.append
for i = 0 to w * h * 2 do
rays <-
rays
|> Array.map (
(fun (dir, x, y, r, g, b) ->
let dx, dy = dv dir
dir, x + dx, y + dy, r, g, b
)
>> (fun (dir, x, y, r, g, b) ->
if ib x y then
match arr.[x, y] with
| Wall _ -> Array.empty
| Sensor -> [| dir, x, y, r, g, b |]
| FilterR -> [| dir, x, y, r, 0., 0. |]
| FilterG -> [| dir, x, y, 0., g, 0. |]
| FilterB -> [| dir, x, y, 0., 0., b |]
| Mirror d -> [| bounce d dir, x, y, r * 0.8, g * 0.8, b * 0.8 |]
| _ -> [| dir, x, y, r, g, b |]
else
Array.empty
))
|> Array.concat
Array2D.mapi (fun x y a ->
match a with
| Combine d -> Some(x, y, d)
| _ -> None
) arr
|> fo
|> Seq.iter (fun (x, y, d) ->
for i = 0 to rays.Length - 1 do
let (d', x', y', r, g, b) = rays.[i]
if x' = x && y' = y then
rays.[i] <- (d, x, y, r, g, b)
)
for d, x, y, r, g, b in rays do
if ib x y then
match board.[x, y] with
| r', g', b' -> board.[x, y] <- r + r', g + g', b + b'
printfn "%s" (
let mutable s = ""
for y = 0 to h - 1 do
for x = 0 to w - 1 do
s <- s + (match arr.[x, y] with
| Air ->
match board.[x, y] with
| r, g, b ->
if r + g + b = 0.0 then ' '
else
if g = 0.0 && b = 0.0 then 'r'
elif r = 0.0 && b = 0.0 then 'g'
elif r = 0.0 && g = 0.0 then 'b'
elif r = 0.0 then 'c'
elif g = 0.0 then 'm'
elif b = 0.0 then 'y'
else 'w'
| Wall z -> z
| Mirror z -> if z = mL then '/' else '\\'
| FilterR -> 'R'
| FilterG -> 'G'
| FilterB -> 'B'
| Sensor -> '?'
| Combine z -> if z = dN then '^' elif z = dS then 'v' elif z = dW then '<' else '>'
| Emitter -> '@'
|> sprintf "%c")
s <- s + "\n"
s
)
Array2D.mapi (fun x y a ->
match a with
| Sensor -> Some(x, y)
| _ -> None
) arr
|> fo
|> Seq.iteri (fun i (x, y) ->
let (r, g, b) = board.[x, y]
let desc =
if r + g + b = 0.0 then "None"
elif g = 0.0 && b = 0.0 then "Red"
elif r = 0.0 && b = 0.0 then "Green"
elif r = 0.0 && g = 0.0 then "Blue"
elif r = 0.0 then "Cyan"
elif g = 0.0 then "Magenta"
elif b = 0.0 then "Yellow"
else "White"
let avg = int((r + g + b) * 100.0 / (match desc with
| "White" | "None" -> 3.0
| "Red" | "Green" | "Blue" -> 1.0
| _ -> 2.0))
printfn "#%d: %d%% %s" (i + 1) avg desc
)
```
] |
[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 9 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In chess, a queen can move as far as as the board extends horizontally, vertically, or diagonally.
Given a NxN sized chessboard, print out how many possible positions N queens can be placed on the board and not be able to hit each other in 1 move.
[Answer]
Here's a solution (originally from [this blog entry](http://nibot-lab.livejournal.com/103551.html)) where I construct a logical description of the solution in conjunctive normal form which is then solved by Mathematica:
```
(* Define the variables: Q[i,j] indicates whether there is a
Queen in row i, column j *)
Qs = Array[Q, {8, 8}];
(* Define the logical constraints. *)
problem =
And[
(* Each row must have a queen. *)
And @@ Map[(Or @@ #) &, Qs],
(* for all i,j: Q[i,j] implies Not[...] *)
And @@ Flatten[
Qs /. Q[i_, j_] :>
And @@ Map[Implies[Q[i, j], Not[#]] &,
Cases[Qs,
Q[k_, l_] /;
Not[(i == k) && (j == l)] && (
(i == k) || (* same row *)
(j == l) || (* same column *)
(i + j == k + l) || (* same / diagonal *)
(i - j == k - l)), (* same \ diagonal *)
2]]]];
(* Find the solution *)
solution = FindInstance[problem, Flatten[Qs], Booleans] ;
(* Display the solution *)
Qs /. First[solution] /. {True -> Q, False -> x} // MatrixForm
```
Here's the output:
```
x x x x Q x x x
x Q x x x x x x
x x x Q x x x x
x x x x x x Q x
x x Q x x x x x
x x x x x x x Q
x x x x x Q x x
Q x x x x x x x
```
[Answer]
### Ruby
I don't see a `golf` tag, so i'm assuming it's just a challenge.
Here's an implementation of the Algorithm mentioned on Wikipedia. It's not by me, it's at Rosetta Stone and can be found [here](http://rosettacode.org/wiki/N-queens_problem#Ruby)
CommWikied this Answer.
[Answer]
### Python 2, 190 185 chars
```
from itertools import*
n=input()
print len(filter(lambda x:all(1^(y in(z,z+i-j,z-i+j))for i,y in enumerate(x)for j,z in enumerate(x[:i]+(1e9,)+x[i+1:])),permutations(range(1,n+1),n)))
```
I just assumed the code golf tag even though it wasn't there. N is read from stdin, the program calculates solutions up to n=10 in acceptable time.
[Answer]
Groovy
```
n=8
s=(1..n).permutations().findAll{
def x=0,y=0
Set a=it.collect{it-x++}
Set b=it.collect{it+y++}
a.size()==it.size()&&b.size()==it.size()
}
```
Delivers a list of all queen solutions like this:
```
[ [4, 7, 3, 0, 6, 1, 5, 2],
[6, 2, 7, 1, 4, 0, 5, 3],
... ]
```
For graphical representation add:
```
s.each { def size = it.size()
it.each { (it-1).times { print "|_" }
print "|Q"
(size-it).times { print "|_" }
println "|"
}
println ""
}
```
which looks like this:
```
|_|Q|_|_|_|_|_|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|_|Q|_|_|_|
```
] |
[Question]
[
I noticed that in Microsoft Word, single quotations are either `‘` or `’`, but not in Notepad. Your task today is: given a string `q`, convert all the `'` characters (only) to `‘` or `’`, according to these rules, and then output it:
* If the character before the quote is a space, and after it comes a character, it becomes `‘`
* If the character before the quote is a letter, and after it is a space, it becomes `’`
* If the character before and after the quote is a letter, it becomes `’`
* If the character before and after the quote is a space, it becomes `‘`
* If the quote comes at the beginning it will be `‘`, if it comes at the end it becomes `’`
* If consecutive quotes come one after another, the first 2 become `‘’` and remaining ones become `’`
## Test Cases
```
'Hello'= ‘Hello’ (rules 1 and 2)
'=‘ (rule 5)
H'h=H’h (rule 3)
' = ‘ (rule 4)
'' = ‘’ (rule 6)
a'''b=a‘’’b (overriding by rule 6)
```
I'm keeping it this because although it is confusing, it is what the output should be, so if I had to make it more clearer, it will come at the expense of understanding it.
You can assume `q` contains only upper and lowercase letters, spaces, and quotation marks.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
**EDIT**: Although in MS Word rule 6 does **not** override all the other rules, since answers have already been posted that assume this case, I will keep it this way
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 42 bytes
```
'('+)
‘$.1*’
(^| )'
$1‘
'($|\w)
’$1
```
Assumes rule 6 takes prio over the other rules.
I have the feeling the first step can be shorter (perhaps with a `+^` loop), but couldn't really find anything yet..
[Try it online](https://tio.run/##K0otycxLNPyvquGe8F9dQ11bk@tRwwwVPUOtRw0zuTTiahQ01blUDIFiXOoaKjUx5SD5mSqG//@re6Tm5OSrc6lzeahncCkAGepcJanFJepgAGIBAA) or [try it online with `<`/`>`](https://tio.run/##K0otycxLNPyvquGe8F9dQ11bk8tGRc9Qy45LI65GQVOdS8XQhktdQ6UmplyTy07F8P9/dY/UnJx8dS51Lg/1DC4FIEOdqyS1uEQdAkBMAA) instead of `‘`/`’` so it's a bit more distinguishable).
**Explanation:**
Replace any sequence of two or more quotes with one opening quote and the rest closing quotes:
```
'('+)
‘$.1*’
```
Replace a quote at the start of the string, or a quote with a space before it, with the opening quote:
```
(^| )'
$1‘
```
Replace a quote at the end of the string, or a quote with a after it, with the closing quote:
```
'($|\w)
’$1
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
(?<=^| )'|\b'(?=')
‘
'
’
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX8PexjauRkFTvSYmSV3D3lZdk@tRwwwudSA58/9/dY/UnJx8dSDXQz2DS0FdgUtdXQEA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(?<=^| )'|\b'(?=')
‘
```
Quotes become "smart open" quotes at the beginning of the string (by rule 5), after a space (by rules 1, 4 and 6), or after a letter and before a quote (by rule 6).
```
'
’
```
All other quotes become "smart close" quotes.
I tried coding the reverse logic by handling "smart close" quotes first but the best I could do was 29 bytes:
```
(?<=')'|\b'(?!')|'$
’
'
‘
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX8PexlZdU70mJkldw15RXbNGXYXrUcNMLnUgOeP/f3WP1JycfHUg10M9g0tBXYFLXV0BAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Quotes become "smart close" quotes after quotes (by rule 6), after a letter but not before a quote (by rules 2 and 3), or at the end (by rule 5).
[Answer]
# [sed](https://www.gnu.org/software/sed/), 109 bytes
```
:z;s/'''/''’/g;t z;
s/''/‘’/g
s/ '(.)/ ‘\1/g
s/([a-zA-Z])'([a-zA-Z ])/\1’\2/g
s/^'/‘/g
s/'$/’/g
```
[Try it online!](https://tio.run/##K05N0U3PK/3/36rKulhfXV0diB81zNRPty5RqLLmAgnpP2qYARYC8hTUNfQ09RWAIjGGYAGN6ETdKkfdqFhNdRhTIVZTP8YQqCPGCKwkDmwCmKmuog826f9/dY/UnJx8dS51Lg/1DC4FdQUudXWFf/kFJZn5ecX/dV0B "sed – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 75 bytes
```
x,o;f(*s){for(x=o=0;*s=*s-39?s[x=0]:8216+x|o&!s[x=1]|o>64&s[1]>64;o=*s++);}
```
[Try it online!](https://tio.run/##RY/RToMwFIav6VMcMa6lMMPULNPKjPFmF7wBEsMqHU0qXSjLMBuvLms3Fq/OOf//n349fMpVUW@GoYs0E4Sa4CB0Q7pEJzGjJqFm@vj8ZrIuifOXxcNsHnZHPblxwiw/6uX8aWKyWW4r0zYchgHrh1tZc7X7LuFVaV6o8r5aon9tz6uicRL6KWRNAnRAninbSxRI@vH1nqYR@H7AkCfrlkJbmjbLIQGb9FIfr0qlNPajyzTWFa7GDjBcvatZYIzXfgQx9AydX4X1TmSLOLcMezAQB6IgLcTRGFDJQNpzkOege2749pfYncg67mOecNO52zZ2WRD/TpnP2kJGvUf98MeFKjZmOAE "C (clang) – Try It Online")
[Answer]
# Sed
Here's a shorter version of matteo\_c's answer:
```
:z;s/'''/''’/g;t z;
s/''/‘’/g
s/'/’/g
s/^’/‘/g
s/ ’/ ‘/g
```
[Answer]
# brev, 70 bytes
```
(strse x "'""’""’(’+)"(conc "‘" (m 1))" ’"" ‘""^’""‘")
```
Not sure how many bytes this is because Unicode but Steffan kindly counted them and here's the algo:
1. Replace all ' with ’.
2. Do "rule six" specially
3. Replace `^’` and `’` with opens
] |
[Question]
[
## Shift Tac Toe
Shift Tac Toe is a game that combines Tic Tac Toe and Connect 4 together. In this game, you start with a 3 by 3 board, and each row is connected to a slider that you can move left and right. At the start, the sliders all start to the very right(this means that you can't move the slider to the right on the first turn). Each slider can hold a total of 5 pieces. Each turn, the player can drop an O or a X in one of the 3 columns of the Tic Tac Toe grid depending on which turn it is, or the player can move one of the sliders one spot to the left or to the right. All pieces fall to the bottom most space that is unoccupied. The pieces can also fall from one slider to another outside the 3 by 3 grid. If a piece is outside the 3 by 3 grid and doesn't fall into the bottom slider, then the piece is taken out. If it does reach the bottom slider, it will stay in play. A notable example of this is shown in the following grid:
```
--- --- --- --- ---
| | | | - O -
--- --- --- --- --- ---
- | | | | -
--- --- --- --- --- ---
| | | | - -
--- --- --- --- ---
In the grid above, the dashes(-) indicate the part of the sliders that are outside of the 3 by 3 grid and the vertical bars(|) indicate the 3 by 3 grid.
As you can see, this is the starting board except that the middle slider is one spot over to the left, and that there is an O at the very top right.
What happens in this scenario? There is nothing immediately underneath it, so does it go out of play?
No. This is because it still falls into the bottom slider, which means that it is still in play.
The final grid is this:
--- --- --- --- ---
| | | | - -
--- --- --- --- --- ---
- | | | | -
--- --- --- --- --- ---
| | | | - O -
--- --- --- --- ---
```
Pieces can also stack outside of the 3 by 3 grid. Players will alternate between O and X, with the O player going first.
## Example game:
```
Start with 3 by 3 grid with sliders all the way to the right:
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
The O player places an O in the middle column of the 3 by 3 grid and it falls to the bottom:
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | O | | - -
--- --- --- --- ---
The X player then places an X in the middle column:
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | X | | - -
--- --- --- --- ---
| | O | | - -
--- --- --- --- ---
The O player then pushes the middle row slider one space to the left.
Notice that after the slider moves, there is nothing under the X anymore, so it falls down.
Also note that the slider has moved one space to the right as indicated below:
--- --- --- --- ---
| | | | - -
--- --- --- --- --- ---
- | | | | -
--- --- --- --- --- ---
| X | O | | - -
--- --- --- --- ---
The X player places a X in the rightmost column:
--- --- --- --- ---
| | | | - -
--- --- --- --- --- ---
- | | | | -
--- --- --- --- --- ---
| X | O | X | - -
--- --- --- --- ---
The O player then moves the bottom slider one spot to the left.
Notice that all the pieces shift one place to the left, and the leftmost X is now out of the playing field:
--- --- --- --- ---
| | | | - -
--- --- --- --- --- ---
- | | | | -
--- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
The X player places a X in the leftmost column:
--- --- --- --- ---
| | | | - -
--- --- --- --- --- ---
- | X | | | -
--- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
The O player places an O in the leftmost column:
--- --- --- --- ---
| O | | | - -
--- --- --- --- --- ---
- | X | | | -
--- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
The X player shifts the top slider one place to the left. Notice that the O falls one place down because there is nothing beneath it:
--- --- --- --- ---
- | | | | -
--- --- --- --- ---
- O | X | | | -
--- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
The O player is not very good at this game, so he shifts the middle slider one place to the right.
This shifts all the pieces in the middle row one place to the right:
--- --- --- --- ---
- | | | | -
--- --- --- --- --- ---
| O | X | | - -
--- --- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
The X player wins the game by placing a X in the middle column:
--- --- --- --- ---
- | | X | | -
--- --- --- --- --- ---
| O | X | | - -
--- --- --- --- --- ---
- X | O | X | | -
--- --- --- --- ---
```
Your job is to take in a string or array of any length that only consists of 9 unique characters(you choose the characters). Three of the characters will choose which column you place the X or O(depending on whose turn it is), three of them will choose which slider to move right, and the last three will choose which slider to move left. You can assume that the input only has these 9 characters. The output should be a 3 by 3 matrix or some kind of list/string that clearly shows the final position of the grid upon following the instructions of the input. You can assume that all inputs are valid. Each character takes up a turn. Also, if any move results in a winning move(forms 3 in a row in the 3 by 3 grid like regular Tic-Tac-Toe), then ignore the rest of the input. Note that the pieces that form the winning 3 in a row *all* have to be in the 3 by 3 grid. The two example grids below are NOT winning positions:
```
Grid #1:
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | | | - -
--- --- --- --- ---
| | | O | O - O -
--- --- --- --- ---
This is not a winning move because two of the O's are outside the playing field, despite the fact that it forms a 3 in a row.
Using the character assignment stated below, this grid pattern can be achieved with 99372467643.
Grid #2:
--- --- --- --- ---
| | | | - O -
--- --- --- --- ---
| | | | O - X -
--- --- --- --- ---
| | | O | X - X -
--- --- --- --- ---
This is not a winning position because two of the O's are outside the playing field.
Using the character assignment below, this grid pattern can be achieved with 939318836537734654
```
In the examples below, `1`, `2`, and `3` mean drop in the leftmost, middle, and rightmost column respectively. `4`, `5`, and `6` mean to move the top, middle, and bottom slider to the right respectively, and `7`, `8`, and `9` mean to move the top, middle, and bottom slider to the left respectively.
## Examples
```
Input will be in the form of a string
Output will be a list of lists, with each sub-list representing a row(I'm Python programmer so this list format might not be compatible with all languages).
The first, second, and third sub-list correspond to the top, middle, and bottom row of the 3 by 3 grid respectively.
The output will have 'O' for the O pieces, 'X' for the X pieces, and an empty string for empty spaces.
Input: 123332
Output:
[['','','O'],
['','X','X'],
['O','X','O']]
Input: 33387741347
Output:
[['','',''],
['','','O'],
['X','O','X']]
Input: 2283911752
Output:
[['','X',''],
['O','X',''],
['O','X','']]
Input: 228374739
Output:
[['','',''],
['','',''],
['X','X','X']]
Input: 8873334917349
Output:
[['','',''],
['','','O'],
['X','X','O']]
Input: 799333466
Output:
[['','',''],
['','',''],
['','','']]
Input: 99372467643
Output:
[['','',''],
['','',''],
['','','O']]
Input: 939318836537734654
Output:
[['','',''],
['','',''],
['','','O']]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# MATLAB, 727 Bytes
[Try it online](https://tio.run/##lU/baoQwEH33K@Yx6eri5KKrIV9StrDY2AbcWKztQ3/eziTPCy1yJnPmXMB12m/f4TjmrzTtcU2Q/CTuskp@28JMm1v8Z/wJItUo3bxuED2OSxU8nu3pbJ9Eg/IljmpcXBKhHqUvz2kLH/fbLpKIxOolpLf9XQTJNSG9ZhyTeFZgoIOLgxYUwThAWiyYq6xIZqIdeSxYR8YHAkcbLMpfGvnAdX1BsWQUkwba6QBIBTSpTRnQCL3i2bWAA@fhwiIMNC30jqnJR0UODbr7T12bw9jRn5ACjRoeFiKZ@WsUx7DA5RMTdZXHLw)
```
b=nan(3,7);m=num2str(input(''));a=@(B)any(all(B)|all(B,2)'|all(diag(B))|all(diag(flip(B))));A=@(x,y)x(:,3:5)==y;n=@(x)isnan(x);
o=[1;1;1];
for i=1:numel(m)
t=1+mod(i,2);M=str2num(m(i));
switch M
case{1,2,3}
c=2+M;b(sum(n(b(:,c))),c)=t;case{4,5,6}
r=M-3;o(r)=o(r)+1;b(r,2:7)=b(r,1:6);b(r,1)=nan;case{7,8,9}
r=M-6;o(r)=o(r)-1;b(r,1:6)=b(r,2:7);b(r,7)=nan;end
r=o(3);
if r==1
b(:,[1,2])=nan;
elseif r==0
b(:,[1,7])=nan;
else
b(:,[6,7])=nan;
end
for j=1:7
d=n(b(:,j));e=sum(d);b(:,j)=[nan(e,1); b(~d,j)];
end
if r==1
b(:,[1,2])=nan;
elseif r==0
b(:,[1,7])=nan;
else
b(:,[6,7])=nan;
end
B=A(b,1);if a(B)
break
end
B=A(b,2);if a(B)
break
end
end
b(b==1)=79;b(b==2)=88;b(n(b))=0;disp(char(b(:,3:5)));
```
Explanation:
This challenge is a bit of a beast. First the user runs the program and inputs the moveset as either a single large number or a character array. For large numbers, due to numerical precision, a character array is required. I define a few often used functions that take up a lot of space so that they can be called with one character rather than a whole lot. Then I loop through each character in the input and use a switch statement to determine the move. 1-3 places the piece at the lowest available spot in the right column. 4-6 shift the row left and 7-9 shift it right. After, all invalid positions (outside the sliders) are removed automatically, as nothing could possibly stay there. Then, all columns are shifted so that things are settled as far down as they can go after 'falling'. Invalid positions are removed again in case a token fell onto another but was still outside a slider. The last thing to do is check the victory condition and break if it is found.
Overall, I had to chip my way out of a few sandtraps but I golfed as best I could. I'll take a triple bogey if no one else is fighting me for it.
] |
[Question]
[
A [SMILES (Simplified molecular-input line-entry system) string](https://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system) is a string that represents a chemical structure using ASCII characters. For example, water (\$H\_2O\$) can be written in SMILES as `H-O-H`.
However, for simplicity, the single bonds (`-`) and hydrogen atoms (`H`) are frequently omitted. Thus, a molecules with only single bonds like *n*-pentane (\$CH\_3CH\_2CH\_2CH\_2CH\_3\$) can be represented as simply `CCCCC`, and ethanol (\$CH\_3CH\_2OH\$) as `CCO` or `OCC` (which atom you start from does not matter).
n-pentane:[](https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/N-Pentan.png/320px-N-Pentan.png)
ethanol:[](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Ethanol-structure.svg/200px-Ethanol-structure.svg.png)
In SMILES, double bonds are represented with `=` and triple bonds with `#`. So ethene:
[](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Ethene_structural.svg/170px-Ethene_structural.svg.png)
can be represented as `C=C`, and hydrogen cyanide:
[](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Hydrogen-cyanide-2D.svg/320px-Hydrogen-cyanide-2D.svg.png)
can be represented as `C#N` or `N#C`.
SMILES uses parentheses when representing branching:
[](https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Halon-1211-2D.png/246px-Halon-1211-2D.png)
Bromochlorodifluoromethane can be represented as `FC(Br)(Cl)F`, `BrC(F)(F)Cl`, `C(F)(Cl)(F)Br`, etc.
For rings, atoms that close rings are numbered:
[](https://i.stack.imgur.com/EAvSJ.png)
First strip the `H` and start from any `C`. Going round the ring, we get `CCCCCC`. Since the first and last `C` are bonded, we write `C1CCCCC1`.
Use this tool: <https://pubchem.ncbi.nlm.nih.gov/edit3/index.html> to try drawing your own structures and convert them to SMILES, or vice versa.
**Task**
Your program shall receive two SMILES string. The first one is a molecule, the second is a substructure (portion of a molecule). The program should return `true` if the substructure is found in the molecule and `false` if not. For simplicity, only above explanation of SMILES will be used (no need to consider stereochemistry like cis-trans, or aromaticity) and the only atoms will be:
* `O`
* `C`
* `N`
* `F`
Also, the substructure do not contain `H`.
**Examples**
```
CCCC C
true
CCCC CC
true
CCCC F
false
C1CCCCC1 CC
true
C1CCCCC1 C=C
false
COC(C1)CCCC1C#N C(C)(C)C // substructure is a C connected to 3 other Cs
true
COC(C1)CCCCC1#N COC1CC(CCC1)C#N // SMILES strings representing the same molecule
true
OC(CC1)CCC1CC(N)C(O)=O CCCCO
true
OC(CC1)CCC1CC(N)C(O)=O NCCO
true
OC(CC1)CCC1CC(N)C(O)=O COC
false
```
Shortest code wins. Refrain from using external libraries.
[Answer]
# Mathematica, 31 bytes
```
MoleculeContainsQ@@Molecule/@#&
```
Takes input as a list of 2 strings (the source and the pattern molecules).
As you could guess, this checks if the first molecule (parsed via `Molecule`) contains the second one by using the `MoleculeContainsQ` function.
This doesn't seem to work in the online interpreter on TIO; I'm not sure what I am doing wrong. It works on my local machine, though. Of course, this is not using an external library: it's completely built-in functionality!
] |
[Question]
[
So I was playing around with [this emulator of the Intel 4004](http://e4004.szyc.org/emu/) and decided I wanted to set a challenge for myself. The first use for the 4004 was in a calculator, so I decided that I would try to code golf every operator on said calculator(addition, subtraction, multiplication, division, decimal points, and the square root) in hexadecimal. Now this was my first code golf challenge I ever set for myself, like ever, and I am relatively new at coding in general, but I thought it would be a fun thing to try out. This was the code for multiplication, specifically 3\*4(In order to change it, simply replace the nybbles following the Ds[except for the 0] with any number you want as long as the product is below 16 and the second and third Ds have the same nybble trailing them):
```
D4 B1 D3 B0 D3 B2 A0 82 B0 D0 B1 F8 F3 14 12 B1 40 06 B0 92 F3 E0
```
Are there any flaws in my 22-byte design, and is there a way to shorten the code?
For reference, the instruction set for the 4004 in binary is in this table: <http://www.e4004.szyc.org/iset.html>
[Answer]
## 4004 machine code, 12 bytes
This is the best code I could come up with using the same I/O as the provided code:
```
D4 LDM 4
B0 XCH R0
D3 LDM 3
F4 CMA
B1 XCH R1
D0 LDM 0
40 09 JUN TEST
:LOOP
80 ADD R0
:TEST
71 08 ISZ R1, LOOP
E0 WRM
```
If you omit the first 3 instructions and the last instruction then the inputs become R0 and the accumulator and the accumulator becomes the output.
Note that this does not handle overflow very well at all; you can add in a `CLC` to ensure that it at least calculates it correctly modulo 16, or in case the caller has left the carry set.
] |
[Question]
[
# Thanks, Uncle (the story)
My slightly mad uncle recently left for the space colonies, and passed his pallet goods business to me. The rectangular warehouse is full of pallets of goods except for the one square by the door, and I've just received the first list of pallets ordered by customers to be sent out today.
Fortunately I have a carefully written map of where each pallet is, and my mad uncle engineered several mini robots which can move a pallet into an adjacent space, much like a sliding 15-puzzle. I don't care where the pallets end up, though, I just want the pallets on the list to arrive in order by the door.
The question is, what series of commands must I give the robots in order to retrieve the required pallets?
# The challenge
Given
* the size of the grid (rows, cols)
* a list of pallets (by their current location) to retrieve in order
You must output a list of grid positions corresponding to which position is to be moved, and which direction. If there is only 1 direction available you may optionally omit that. The pallets will be removed immediately upon arrival by the door (at one corner, index N in the examples).
# Worked example
```
01 02 label the contents A B
03 04 C D
05[ ] E _
Request: 03 (contents is C)
Command 0: 04
D moves into the (only) adjacent space at index 06
Result: A B
C _
E D
Command 1: 03
C moves into the (only) adjacent space at index 04
Result: A B
_ C
E D
Command 2: 05
A B
E C
_ D
Command 3: 06
A B
E C
D _
Command 4: 04
A B
E _
D[C]
(C removed having arrived by the door)
```
# Limits and freedoms
* Maximum grid size is 100x100
* Challenge is code-golf
* Solution must execute within 2 minutes on some real-world machine
* You can choose your indexing, command syntax, input structures and so on, as long as it's consistent.
* I've chosen to use the grid locations for the commands, but conceivably you could emit the value in the element instead (plus a direction) as they are unique.
* If you wanted to make an animation of the state (especially for a large grid), I'm sure that would be entertaining!
# Examples
## A: 3x2, 1 pallet
```
01 02
03 04
05 [__]
Request: pallet at 03
Valid solution: 05,03,04,06,05
This leaves the following state:
01 02
04 05
__ [03]
```
## B: 15-puzzle, 1 box
```
01 02 03 04 05
06 07 08 09 10
11 12 13 14[ ]
Request: box 01
Valid solution: 14,13,12,11,06,01,02,07,12,11,06,07,12,11,06,07,08,13,12,11,06,07,08,09,14,13,08,09,10,15,14
02 07 03 04 05
08 12 13 10 14
06 11 09 __[01]
```
## C: 3x2, 4 boxes
```
01 02
03 04
05[ ]
Request: 02,04,01,05
Valid solution: 04,02,01,03,05,06,04,05,02,06,03S,05E
Pallet taken at: ^ ^ ^ ^
Indicating directions with NSEW
Final state:
03 __
__ __
__ __
```
## D: 10x10, 2 boxes
```
10x10, request boxes at 13,12 (row 1, cols 2 & 1 with 0-index)
Valid solution: (90,80..20, 19,18..12, 22,32..92, 93,94..100) x 15, 90.
```
## E: 4x1, all
```
4x1: 01 02 03 [ ]
Req: 03,02,01 (only valid order)
Optimal solution: 03,02,03E,01,02E,03E
```
## F: 100x100, 3 near the door
```
100x100
Req: 9900,9899,9898
Result: 9000,9989,9000S,9898,9898E,9000S
```
[Sandbox link](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/17688)
[Answer]
## JavaScript (Node.js) - ~~425~~ ~~424~~ ~~420~~ 395
```
(n,m,L)=>(s=Math.sign,G=[...Array(n*m).keys()],i=k=n*m-1,G[k]=-1,R=[],M=j=>{-G[j]-1&&R.push([j,i]);[G[i],G[j]]=[G[j],G[i]];i=j},X=j=>{while(i%n-j%n)M(i+s(j%n-i%n))},Y=j=>{while(y(i)-y(j))M(i+n*s(y(j)-y(i)))},y=i=>(i-i%n)/n,L.map(e=>{J=()=>j=G.indexOf(e);while(J()%n-n+1){m>1&&y(j)-y(i)||M(y(i)?i-n:i+n);X(j+1);Y(j);M(j);m<2?i=k:0}while(J()+1-n*m){X(n-2);Y(j+n);X(n-1);M(j);n<2?i=k:0}G[k]=-1}),R)
```
[Try it online!](https://tio.run/##lVVbb9s2FH62f8XZQxOypjQru9oKXRRDYTSwWyAdhhSCHjSJtslIlCfRSQTHvz07pGTH9dKtA2xR/Pid@@GRSu6SOq3k2ni6zMRTLgxU4q@NqA1/IpoVbEb5hNR8npiVX8ulZlMe@b7/tqqShujXBfVvRVMTGjPJbzkCXsCm0W3Mcb3mUczmXPHJ1ptGKvaCs7Nrf72pVyRSTMY0jKaRjJk9i3lkF2aBOJRc7diNk7xfyVwQ@Up76pWmcyIHNcE3DxFKd@zzEakhknoNUdTR9Oua2I1nYUttuMRYpJP8XrOZXyRrIlD6ihOMUvGpL3UmHj4uiKBhq/KKULSlBwHdFhN0/6Dw8XHu7L2Rnh6jMRreEIW08DMywrl9FJcXbzAp4@HuoGsQeDZn2xuivQvHbSW1F3RC@iDUZXFH2TV9Cvv9xUanRpYa7pJcZokRbX1YWhZForOawrbfswVcVjIDDi@XKez37HlkH34u9NKsvCBGut7kOR62KmbvbSIQHSK0N@Avyupdkq5IBwCfWJNOQCK3g6OhNeJQdYQGDsWfXACRcAlDeHxEuQmHI18spvaH6uTQRdjrmVVV3oMW9/CuqsqKnL/XLiWA1ZOpqMdwDgPUPMDVm7gNJhYld60Dzl8bHDbC3lPZ4N72xgO2RvjMU5annnnK8ZSnTniZ4z2g/J6ZWaZqPNkcxe2uUfJnTbIHChMIbJTPWHPA8BzOzlAH/XrMLlbQpYEkU0kqtPmvwK0HrvgSC87bkn9N/1tjRLE2YEooyjsBdtNAvUZD32xGxfDd/zQjNb6VabpZS5F9m7moC4l1Nm0zR907686Oe6/r7UuY7XsOM/3inUDfZ1FLj7sA/vXu9HoteTDo3NtRd6OOrNp8zA7t/I90fLDVzHNY40OYGu5FJXAgm0qKO5H556hv1@/b9jI4on9LauwAjLbf24IeQzAcMii6dTaGaMgCdsF@iGHHTiktYfQrG/3CRj@z0U9s9OMx70tFL/Awpf2DE4fRYLqhkJa6LnPh5@WSnP@ONKmXrnRXnz5@8GsMSC/loiGGtin6gj8VWlSJE0FwY4cezjIbvLtZ@3mEkXffKmJ8zYxf4H9GwxNtf7Tj8iVth0l6JP88T08VfeqkQdbtDG7rQcOnvwE "JavaScript (Node.js) – Try It Online")
Takes n,m and an array of pallets, returns a list of commands where each command is a 2-element array of the location of the pallet to move and the location of the space to move it to.
There's probably a better strategy than what I used, but posting as is for now.
] |
[Question]
[
[Peg solitaire](https://en.wikipedia.org/wiki/Peg_solitaire) is a popular game usually played alone. The game consists of some number of pegs and a board which is divided into a grid - usually the board is not rectangular but for this challenge we will assume so.
Each valid move allows one to remove a single peg and the goal is to play in a way, such that there is a single peg left. Now, a valid move has to be in a single direction (north, east, south or east) and jump over one peg which can be removed.
## Examples
Let `.` be empty spaces on the board and numbers are pegs, the following move will move `1` one to the right and remove `2` from the board:
```
..... .....
.12.. -> ...1.
..... .....
```
A move will always have to jump over a single peg, so the following is **not** valid:
```
...... ......
.123.. -> ....1.
...... ......
```
Here are some valid configurations after one move each:
```
...1... ...1... ..71... ..71...
.2.34.5 ---> .24...5 ---> .2....5 ---> ......5
.678... (4W) .678... (7N) .6.8... (2S) ...8...
....... ....... ....... .2.....
```
## Challenge
Given an initial board configuration and some other configuration, output whether the other configuration can be reached by successively moving pegs around as described above.
## Rules
* Input will be a \$n \times m\$ matrix/list of lists/... of values indicating an empty space (eg. zero or false) or pegs (eg. non-zero or true)
+ you may assume \$n \geq 3\$ and \$m \geq 3\$
+ you may use true/non-zero to indicate empty spaces and vice-versa if it helps
* Output will be two distinct (one of the values might differ) values indicating whether the end-configuration can be reached (eg. *falsy*/*truthy*, `[]`/`[list of moves]` ..)
## Test cases
```
initial goal -> output
[[1,0,0],[1,1,0],[0,1,0]] [[0,0,0],[0,1,0],[1,1,0]] -> True
[[1,0,0],[1,1,0],[0,1,0]] [[0,0,1],[0,1,1],[0,0,0]] -> False
[[0,0,0],[1,0,0],[0,0,0]] [[0,0,0],[0,0,1],[0,0,0]] -> False
[[0,0,0],[1,1,0],[0,0,0]] [[0,0,0],[0,1,1],[0,0,0]] -> False
[[0,0,0,0],[1,1,1,0],[0,0,0,0]] [[0,0,0,0],[0,0,0,1],[0,0,0,0]] -> False
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]] [[0,0,1],[0,1,0],[1,0,0],[0,0,1]] -> True
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]] [[1,0,0],[0,0,0],[0,0,0],[0,0,0]] -> False
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]] [[0,0,1,0],[1,0,0,0],[1,0,1,0],[1,0,0,1]] -> True
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]] [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> False
[[1,0,0,0],[1,1,0,0],[1,1,1,0],[1,0,1,0]] [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> True
[[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]] -> False
[[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]] [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] -> False
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]] [[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]] [[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]] [[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,1,0,0,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,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,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]] -> True
```
[Answer]
# JavaScript (ES6), ~~184 178~~ 173 bytes
Takes input as `(initial_board)(target_board)`. Returns \$0\$ or \$1\$.
```
a=>g=b=>a+''==b|a.some((r,y)=>r.some((v,x,A,X,R)=>[-1,0,1,2].some(h=>(A=a[y+(R=~-h%2)]||0)[X=x+(h%=2)]&v>(R=a[y+R*2]||0)[h+=x+h]&&g(b,A[X]=r[x]=R[h]++)&(A[X]=r[x]=R[h]--))))
```
[Try it online!](https://tio.run/##rVTRboIwFH3fV/gitqNoy/sl8WUfQPZg0vShOIQtThbYjCZkv86qILSgAou83PSeyzmnp4UPuZfZOn3/@nZ2yVtYbKCQ4EUQgCft2QwgyOU8Sz5DhFJyxOCl1WpPDmRJVsRXPe4wQgkjrijBGDy0BMmPNvLh14mnLhZ5TjFfwcFG8RTU2tp7CjzN@M9uica2gmNhWREKyJKvBKT8IMDnsbBtbCGz5ThYPcU62WXJNpxvkwhtEOcnJ1QQVdm50nMVWEG0gmgFsQrCk8Vi8pr@hE8jyVjVKittyF7kNuuy0Zrt4oN2rdHxbOw22zhvNZ/GaHBqbWYM3GFuZ8gqU2XtZNkOiI06oCvkZtrt2mu94WvHU6L6dWjMGwOXXv9WRohR44iIZmD4qTTRPUzt6tb099gdhjti5tUbeJV71dgAtUEfDmtplqHW/wfSEeru@f8UfcE/2Jw@0rfWzBV/ "JavaScript (Node.js) – Try It Online")
(removed the last two test cases that take too much time for TIO)
### Commented
```
a => // main function taking the initial board a[]
g = b => // g = recursive function taking the target board b[]
a + '' == b | // yield a truthy result if a[] is matching b[]
a.some((r, y) => // for each row r[] at position y in a[]:
r.some((v, x, A, X, R) => // for each value v at position x in r[]:
[-1, 0, 1, 2] // list of directions (West, North, East, South)
.some(h => // for each direction h:
( A = // A = a[y + dy]
a[y + (R = ~-h % 2)] // R = dy
|| 0 // use a dummy row if we're out of the board
)[X = x + (h %= 2)] // h = dx, X = x + dx
& // yield 1 if there's a peg on the skipped cell
( R = // R = target row
a[y + R * 2] // = a[y + 2 * dy]
|| 0 // use a dummy row if we're out of the board
)[h += x + h] // h = x + 2 * dx = target column
< v // yield 1 if there's no peg on the target cell
&& // and there's a peg on the source cell (0 < 1)
g( // if the above result is true, do a recursive call:
b, // pass b[] unchanged
A[X] = r[x] = // clear the source and skipped cells
R[h]++ // set the target cell
) & ( // and then restore the board to its initial state:
A[X] = r[x] = // set the source and skipped cells
R[h]-- // clear the target cell
) //
) // end of some() over directions
) // end of some() over columns
) // end of some() over rows
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 232 bytes
```
import StdEnv,Data.List
r=reverse
@[a:t=:[b,c:u]]=[[a:v]\\v<- @t]++take(a*b-c)[[0,0,1:u]];@l=[]
```
#
```
flip elem o\c=limit(iterate(nub o concatMap\l=[l]++[f(updateAt i p(f l))\\f<-[id,transpose],q<-f l&i<-[0..],p<- @q++(map r o@o r)q])[c])
```
[Try it online!](https://tio.run/##hY9PS8NAEMXv/RRzksRsSnrwUhuIUA9CBaHHzR6mm40u7r9uJgG/vHFrFBQEGRjm8d4Mv5FGoZut70ajwKJ2s7bBR4IjdfduYnskXB/0QKtYRzWpOKhVw3FL9ZafmNyOQtQ86Um07bQroSFRFISvKsPrUylzzitWsc0ld9uYmou5H50k7R3U0BsdQBllwbeyNtpqyjSpiKQyN57Ag/ROIj1iaNOuSad5n42hS4E7Ag0h68Hkedv2u5LrjlFENwQ/KMHOuzJ5VzoZ1XotWLjAnYsisxgggm88xPwsci5FvjoSppcT0Dfbgp3AP3slGF/mzdK/9OaX/6OEgD9P/Iz8p8X8LnuDz8NcPhzm/ZtDq@UingxS76Ody5f5pqrsBw "Clean – Try It Online")
This is one of the rare occasions in which I can utilize composition and currying while saving bytes.
Explained:
`@ :: [Int] -> [[Int]]` is a helper function used to generate the different potential *new* rows/columns that could result from a move being made. It avoids needing to special-case `[1,1,0:_]` by noticing that `a*b-c>0` only when `[a,b,c]=[1,1,0]`, and so `take(a*b-c)...` gives `[]` by taking `-1` or `0` elements for all configurations that aren't a valid move.
`flip elem o...` reverses the order of arguments to `elem` (making it "does x contain a y" instead of "is x a member of y") and applies the anonymous function on `c` to the first argument.
`\c=limit(iterate(nub o concatMap ...)[c])` generates every potential board that can result from the `c` by joining the current set of boards with all the moves that can happen on all of the boards and removing the duplicates, until the result stops changing.
`\l=[l]++...` prepends the board `l` to the list of all potential new boards one-move distance away, generated by applying `@` to the rows of each orientation of the board (0, 90, 180, 270-degree rotations) and replacing the corresponding changed row with the new row.
] |
[Question]
[
This is based on how my company deals with the monitoring of the working times for every employee. Each one of us has a card that can be passed in front of a sensor, so that a clock registers the times at which the employees check in or out the office. Every time register is linked to a code:
* Code 0: the employee arrives at (or returns to) the office.
* Code 1: the employee leaves the office for lunch.
* Code 2: the employee leaves the office at the end of the day.
* Code 3: the employee leaves the office for work reasons.
* Code 4: the employee leaves the office for personal reasons.
Code 0 registers will sometimes be referred to as "zero registers", and code 1 to code 4 registers will sometimes be referred to as "non-zero registers".
So, a normal day for a worker would generate a register list like this:
```
Code/Time
------------
0 8:17 // The employee arrives at the office
4 11:34 // The employee leaves the office to smoke
0 11:41 // The employee returns to the office
1 13:37 // The employee leaves the office to have lunch
0 14:11 // The employee returns to the office
3 15:02 // The employee leaves the office to visit a client
0 16:48 // The employee returns to the office
2 17:29 // The employee leaves the office to go home
```
Nonetheless, the employees sometimes make mistakes. The following errors are automatically fixed by the system:
* There are two consecutive non-zero records. If the first non-zero record has a code 4, an automatic code 0 register is added 15 minutes after, or 1 minute before the next registers if it has been registered less than 15 minutes after. If the first non-zero record has a code 3, an automatic code 0 register is always added 1 minute before the next register. Every other case produces an error. Examples:
```
Code/Time
------------
0 8:17 // The employee arrives at the office
4 11:34 // The employee leaves the office to smoke
1 13:37 // The employee leaves the office to have lunch
// Automatic register with code 0 added at 11:49.
Code/Time
------------
0 8:17 // The employee arrives at the office
4 11:34 // The employee leaves the office to smoke
4 11:39 // The employee leaves again the office for personal reasons
// Automatic register with code 0 added at 11:38.
Code/Time
------------
0 8:17 // The employee arrives at the office
3 11:34 // The employee leaves the office to visit a client
1 14:09 // The employee leaves the office to have lunch
// Automatic register with code 0 added at 14:08.
```
* The employee registered two code 1 registers or two code 2 registers. As these two are in fact interchangeable, that does not count as an error. If the code 1 or code 2 registers sum more than 2 registers, that produces an error.
**The challenge**
The main objective is to calculate how many hours and minutes the employee has spent in the office. This is done after fixing (if needed and possible) the input register list. Note that a proper register list will alternate zero registers with non-zero registers.
So, the algorithm will receive the list of registers for an employee and a give day, and will return the time spent working for that day. If the time cannot calculate the time spent in case of errors, it will return 0 hours, 0 minutes.
Rules:
* The time spent is the sum of the time spent between every code 0 register and the following non-zero register. If the non-zero code is a 3, the time spent between that register and the following code 0 register will also be counted.
* You can assume that the input register list will be in ascending time order, and that all the registers will be from the same day (nobody will work beyond midnight).
* The input register won't be empty.
* The input format can be anything your code needs, as long as the time is expressed with the hour value and the minute value (a floating-point number of hours won't be a valid input). Examples: A list with the codes and a list with the time as strings, both lists being the same lenght; a list of lists of integers, being the integers the code, the hour and the minutes of the registers...
* The output can be a string with the time (in any format you want: H:mm, HH:mm, H:m...); a list of two integers with the hours and minutes calculated; anything that can be interpreted as an hour-minute tuple (a floating-point number with the hours spent won't be allowed). Or you can print the result to STDOUT.
**Test cases**
```
Code/Time
------------
0 8:17 // Check in
4 11:34 // Check out. Time spent since check in: 3:17
0 11:41 // Check in
1 13:37 // Check out. Time spent since check in: 1:56
0 14:11 // Check in
3 15:02 // Check out. Time spent since check in: 0:51
0 16:48 // Check in. Time spent working outside: 1:46
2 17:29 // Check out. Time spent since check in: 0:41
// Total time (value returned): 8:31
Code/Time
------------
0 8:17
4 11:34 // Time spent: 3:17
1 15:52 // Time spent since 11:49 (automatic register 15 minutes after
// a code 4 register): 4:03
// Total time: 7:20
Code/Time
------------
0 8:17
4 15:47 // Time spent: 7:30
1 15:52 // Time spent since 15:51 (automatic register after a code 4
// register 1 minute before the next register as it is too
// close in time): 0:01
// Total time: 7:31
Code/Time
------------
0 8:17
1 13:34 // Time spent: 5:17
0 14:04
1 17:55 // Time spent: 3:51 (last code 1 should be a code 2 but it does not matter)
// Total time: 9:08
Code/Time
------------
0 8:17
1 13:34
0 14:04
1 17:05
0 17:08
2 17:44
// Total time: 0:00 (too many code 1 and code 2 registers)
Code/Time
------------
0 8:17
1 13:34 // A code 1 register does not generate an automatic code 0 register
2 17:41
// Total time: 0:00 (there's a code 0 register missing)
Code/Time
------------
0 8:17
0 13:34 // what happened between these two check in registers?
2 17:41
// Total time: 0:00 (there's a check out register missing)
Code/Time
------------
0 8:17
0 13:37 // This should probably be a code 1 register, but we cannot be sure
0 14:11
2 17:29
// Total time: 0:00
```
I know this can be confusing (the real-world problem had even more cases to consider, so I do know that). Please, do not hesitate to ask for more examples.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
---
You can comment how to improve the system if you want, but that's not the point. My boss is not prone to spend time changing it. :-)
[Answer]
# [Python 3](https://docs.python.org/3/), 327 322 318 317 bytes
Thanks for @JonathanFrech and @Mr.Xcoder for getting rid of some bytes.
Takes input as list of codes (`C`) and list of times (`T`) (`(hours, minutes)` tuples). Returns a `(hours, minutes)` tuple.
```
def f(C,T):
T,L=[m+h*60for h,m in T],C.count
for z in range(len(C))[::-1]:
c=C[~-z]
if c*C[z]:
if c<3:return 0,0
C.insert(z,0);b=~-T[z];T.insert(z,b if c-4else min(T[~-z]+15,b))
while L(3):i=C.index(3);del C[i:i+2],T[i:i+2]
return(0,0)if L(1)+L(2)>2or 0in C[1::2]else divmod(sum(T[1::2])-sum(T[::2]),60)
```
Verified against given examples.
## Ungolfed
```
def f(C, T):
# use minutes since midnight instead of (hours, minutes)
T=[m+h*60 for h,m in T]
# error correction
for z in range(len(C))[::-1]:
if C[z-1] and C[z]:
if C[z-1]<3:
return 0,0
C.insert(z,0)
b=T[z]-1
T.insert(z, b if C[z-1] != 4 else min(T[z-1]+15, b))
# simplification (remove work trips (code 3))
while L(3): # 3 in C
i=C.index(3)
del C[i:i+2]
del T[i:i+2]
# error check
if 0 in C[1::2] or 2 < C.count(1) + C.count(2):
return 0,0
# sum
s = sum(T[1::2])-sum(T[::2])
# to (hours, minutes)
return divmod(s, 60)
```
] |
[Question]
[
```
'---------'
'-'.repeat(9) // longer!
'------------'
(x='----')+x+x
'-'.repeat(12) // same length
```
Is there any cleverer way of generating strings of 12 repeated characters in JavaScript?
[Answer]
Unfortunately, after what seems an eternity of searching documentation, I can't seem find any solution that will work with the 12-character constraint and generate for any given character given. However, there are a few neat tricks one can do to save some bytes for specific cases:
* `1e*L*-1+''` will give a string, filled with `9`s, of *L* length.
* `''.padEnd(*L*)` will give a string, filled with spaces, of *L* length. It's only useful when *L* > 10, otherwise it's too long. This one can be immediately chained with a function.
* `*N*/9+''` will give a string, starting with `0.` then followed by a bunch of `*N*`s. This does not work when *N* < 1 or *N* > 8, and the result obviously does not contain the same characters the whole way, but pretty close and pretty short.
* [`Array(*L*)+''`](https://codegolf.stackexchange.com/questions/123191/tip-short-way-to-generate-up-to-12-repeated-characters-in-javascript#comment302215_123191) will give a string, filled with commas, of length *L* - 1.
] |
[Question]
[
You're looking at an avenue, and someone has left the trash out! You need to write a program to help fix the problem, by putting the trash into trashcans.
# The task
The avenue is made up of a string of printable ASCII characters, e.g.:
```
[[](dust)[]] car ((paper)vomit) (broken(glass)) [[] (rotten) fence (dirty)
```
Some of the brackets here are unmatched; those are just decoys. What we care about are the matched sets of brackets.
A *trash can* is a string starting with `[` and ending with `]`, and with internally matched brackets and parentheses. For example, `[]` and `[[](dust)[]]` are trash cans in the above string.
A *trash bag* is a string starting with `(` and ending with `)`, and with internally matched brackets and parentheses. For example, `(dust)` is a trash bag in the above string.
It's possible that some of the trash bags are in trash cans already. However, at least one will have been left out, and we need to move the trash bags so that they're all inside trash cans. Specifically, for each trash bag that isn't currently inside a trash can (i.e. a substring of that trash can), we need to remove it from its current location in the string, and insert it into a location that's inside a trash can instead.
There's an additional rule here. Because we don't want to spend too much money on garbage collectors, and their route takes them along the avenue from right to left, we want to move each trash bag *to the left* (most important criterion, assuming we have to move it at all) and *the shortest distance possible* (as long as it's moved to the left). So for example, the only correct output for
```
[can1](bag)[can2]
```
is
```
[can1(bag)][can2]
```
(moving the bag just one character leftwards). Additionally, the bags need to stay in the same relative order:
```
[can](bag1)(bag2)
```
has to become
```
[can(bag1)(bag2)]
```
(i.e. you can't put `(bag2)` to the left of `(bag1)`.)
# Clarifications
* There won't be any trash bags to the left of the leftmost trash can; it will always be possible to can all the trash by moving it to the left.
* There will always be at least one bag to move. There might be more than one.
* There will never be a trash can inside a trash bag (the cans are too valuable to just throw away).
* If a bag is already inside a can, just leave it alone.
* It's OK for the input and output to differ in trailing whitespace (including newlines).
Examples:
* Input: `[[](dust)[]] car ((paper)vomit) (broken(glass)) [[] (rotten) fence (dirty)`
Output: `[[](dust)[]((paper)vomit)(broken(glass))] car [[(rotten)(dirty)] fence`
* Input: `[]] (unusable) door (filthy) car`
Output : `[(unusable)(filthy)]] door car`
[Answer]
## JavaScript (ES6), ~~263~~ ~~228~~ ~~209~~ ~~205~~ ~~184~~ ~~177~~ ~~173~~ 162 bytes
Any help with the code / regular expressions is greatly appreciated.
```
f=s=>s.match(t=/\[\[][\w()]*\[]]|\[]/g,g=/\([\w()]*\)/g,i=0,u=s.split(t).filter(e=>e)).map(e=>e.substr(0,e.length-1)+u[i].match(g).join``+`]`+u[i++].replace(g,``)).join``
```
An anonymous function; takes one `String` parameter, `s`, and returns the output.
`/\[\[][\w()]*\[]]|\[]/g` matches trash cans with nested trash bags, however I don't think it could check balanced brackets within trash bags if needed.
] |
[Question]
[
## Introduction
A [radix tree](https://en.wikipedia.org/wiki/Radix_tree), also known as compressed trie or compressed prefix tree, is a tree-like data structure for storing a set of strings.
The edges of the tree are labeled by nonempty strings, and each node is either terminal or nonterminal.
The strings that the tree contains are exactly the labels of all paths from the root to a terminal node.
The tree must be in the normal form defined by the following conditions:
* All nonterminal non-root nodes have at least two children.
* For every node, all outgoing edges have different first characters.
For example, here is the radix tree containing the set `["test", "testing", "tested", "team", "teams", "technical", "sick", "silly"]`, with `(N)` representing a nonterminal node and `(T)` a terminal node:
```
-(N)-te-(N)-st-(T)-ing-(T)
| | |
| | +-ed-(T)
| |
| +-am-(T)-s-(T)
| |
| +-chnical-(T)
|
+-si-(N)-ck-(T)
|
+-lly-(T)
```
In this challenge, your task is to compute the height of the tree, given the strings as input.
## Input
Your input is a non-empty list of strings of lowercase ASCII letters.
It will not contain duplicates, but it may be in any order.
It may contain the empty string.
You may take the input in any reasonable format.
## Output
Your output shall be the length of the longest root-to-leaf path in the corresponding radix tree, measured in the number of nodes it contains.
In the above example, the correct output is 4, corresponding to the paths
```
(N)-te-(N)-st-(T)-ing-(T)
(N)-te-(N)-st-(T)-ed-(T)
(N)-te-(N)-am-(T)-s-(T)
```
which contain 4 nodes.
## Further examples
Here are a couple more examples of radix trees:
```
[""]
-(T)
["","fuller"]
-(T)-fuller-(T)
["","full","fuller"]
-(T)-full-(T)-er-(T)
["full","fuller"]
-(N)-full-(T)-er-(T)
["full","filler"]
-(N)-f-(N)-ull-(T)
|
+-iller-(T)
```
## Rules and scoring
You can write a full program or a function.
This is code golf, so the lowest byte count wins.
You can use any built-ins or libraries you want, but remember to include all `import`s etc. in your byte count.
Third-party libraries – those not included in the standard install of your language – are allowed, but must be listed in the header separately, e.g. **Python + pytrie0.2, 60 bytes**.
## Test cases
```
[""] -> 1
["fuller"] -> 2
["","fuller"] -> 2
["","full","fuller"] -> 3
["full","fuller"] -> 3
["full","filler"] -> 3
["full","filler","filter"] -> 4
["full","filler","fi","filter"] -> 5
["test","testing","tested","team","teams","technical","sick","silly"] -> 4
["a","aaaa","aabbaa","aabbaab","abaaa","aab","aabbb","aabba"] -> 8
["dbdbaca","ab","a","caaabaaa","adbbabdb","dbdbdbaca","dbbadbacaba","db"] -> 4
["db","dbbdbb","dbaa","cabcacaa","","acaabcacab","b","abaaaca","bacaaaaa"] -> 3
["aabaabdbb","bacaabadbbdb","abb","aabaa","ab","bcadbb","adbbcaaadbbb","caaa","bbdbcacadbab","dbbdbdb"] -> 4
["bbcaaabbbabbcadbbacadbbdbdb","b","bbbbaaaaaababa","ca","bb","bdbbacadbbdbbdbbababaacaca","abbaabbabcabaaa","bbbacacacabcacacabaaabb","bbcaaaab","bbbbcaacaadbcaaa","babbabcadbdbacacabbcacab","abcabbbaacadbcadb","bbcabbcadbcacaacaadbadbcaadb","dbbbdbbdbacaabbacabcadbdbacaca","bbaabdbdb","cabcadbbbadbadbbaadbcaca","adbadbadbdbcacadbdbbcaadbcaca","abaabbcab","aaabcaabcaab","bacacabcacaacadbadbb"] -> 6
```
[Answer]
## JavaScript (Firefox 30-57), 137 bytes
```
f=(a,b=["",...a],s=new Set(b.map(w=>w[0])))=>b.length>1?(s.size>1)+Math.max(...(for(c of s)f(a,[for(w of b)if(w&&w[0]==c)w.slice(1)]))):1
```
There must be something wrong with my algorithm as I seem to have to special-case an empty string parameter.
[Answer]
## [Retina](http://github.com/mbuettner/retina), ~~69~~ 55 bytes
The trailing linefeed is significant.
```
m`.(?<=(?=\D*^\1(?!\2))\D*^(.*)(.))|^.
:$&
T`w
O`
A-2`
```
Input is a linefeed-separated list.
Performance can be increased significantly by inserting a `\A` before the last `\D` on the first line.
### Explanation
A node is inserted into a word in three places:
* The beginning.
* After any longest prefix shared with another word. That is, a shared prefix after which the two words differ.
* The end.
In Retina, it tends to be shorter to produce `N+1` when you've counted `N` things, so we're ignoring the one at the end. However, for the case of the empty input, we'll then also have to ignore the start, because beginning and end are the same.
To do the actual counting we insert `:` into every place where there is a node. Then we simply find the maximum number of `:` in a word and return that plus 1. Here is how the code does it:
```
m`.(?<=(?=\D*^\1(?!\2))\D*^(.*)(.))|^.
:$&
```
This detects all the nodes. It matches a character. Then it enters a lookbehind which captures that character into group `2` and the prefix before it into group `1`. Then it goes all the way to the beginning of the string to start a lookahead, which checks that it can find the prefix somewhere where it's *not* followed by the captured character. If we find this match we insert a `:` in front of the character. We also match the first character of the current word to insert a `:` at the beginning of non-empty words.
```
T`w
```
This removes all the letters and leaves only the `:`.
```
O`
```
This sorts the lines, bringing the maximum depth to the end.
```
A-2`
```
This discards all but the last line.
And the empty line at the end counts the number of empty matches in that line, which is one more than the number of colons in it.
[Try it online!](http://retina.tryitonline.net/#code=JShTYCwKbWAuKD88PSg_PVxEKl5cMSg_IVwyKSlcRCpeKC4qKSguKSl8Xi4KOiQmClRgdwpPYApBLTJgCg&input=CmZ1bGxlcgosZnVsbGVyCixmdWxsLGZ1bGxlcgpmdWxsLGZ1bGxlcgpmdWxsLGZpbGxlcgpmdWxsLGZpbGxlcixmaWx0ZXIKZnVsbCxmaWxsZXIsZmksZmlsdGVyCnRlc3QsdGVzdGluZyx0ZXN0ZWQsdGVhbSx0ZWFtcyx0ZWNoaWNhbCxzaWNrLHNpbGx5CmEsYWFhYSxhYWJiYWEsYWFiYmFhYixhYmFhYSxhYWIsYWFiYmIsYWFiYmEKZGJkYmFjYSxhYixhLGNhYWFiYWFhLGFkYmJhYmRiLGRiZGJkYmFjYSxkYmJhZGJhY2FiYSxkYgpkYixkYmJkYmIsZGJhYSxjYWJjYWNhYSwsYWNhYWJjYWNhYixiLGFiYWFhY2EsYmFjYWFhYWEKYWFiYWFiZGJiLGJhY2FhYmFkYmJkYixhYmIsYWFiYWEsYWIsYmNhZGJiLGFkYmJjYWFhZGJiYixjYWFhLGJiZGJjYWNhZGJhYixkYmJkYmRiCmJiY2FhYWJiYmFiYmNhZGJiYWNhZGJiZGJkYixiLGJiYmJhYWFhYWFiYWJhLGNhLGJiLGJkYmJhY2FkYmJkYmJkYmJhYmFiYWFjYWNhLGFiYmFhYmJhYmNhYmFhYSxiYmJhY2FjYWNhYmNhY2FjYWJhYWFiYixiYmNhYWFhYixiYmJiY2FhY2FhZGJjYWFhLGJhYmJhYmNhZGJkYmFjYWNhYmJjYWNhYixhYmNhYmJiYWFjYWRiY2FkYixiYmNhYmJjYWRiY2FjYWFjYWFkYmFkYmNhYWRiLGRiYmJkYmJkYmFjYWFiYmFjYWJjYWRiZGJhY2FjYSxiYmFhYmRiZGIsY2FiY2FkYmJiYWRiYWRiYmFhZGJjYWNhLGFkYmFkYmFkYmRiY2FjYWRiZGJiY2FhZGJjYWNhLGFiYWFiYmNhYixhYWFiY2FhYmNhYWIsYmFjYWNhYmNhY2FhY2FkYmFkYmI&debug=on) (The first line enables a linefeed-separated test suite, where each test case uses comma separation instead.)
] |
[Question]
[
[IPv4 addresses](https://en.wikipedia.org/wiki/IP_address) are 32 bits wide, and thus the size of the address space is 232, or 4,294,967,296. However, this is only a theoretical upper-bound. It is not an accurate representation of all the addresses that may actually be used on the public internet.
For the purposes of this challenge, it is assumed that all [addressing is classful](https://en.wikipedia.org/wiki/Classful_network). In reality, classful subdivision of address space has been superseded by [CIDR (Classless Inter-Domain Routing and VLSM (Variable Length Subnet Masking)](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing), but this is ignored for this challenge.
According to the classful address scheme, there are 3 classes:
* Class A - `0.0.0.0` to `127.255.255.255` with `/8` netmask length
* Class B - `128.0.0.0` to `191.255.255.255` with `/16` netmask length
* Class C - `192.0.0.0` to `223.255.255.255` with `/24` netmask length
Classes D (multicast) and E (reserved) are also defined, but these are not used for public unicast addresses.
Each class is subdivided into networks according to the netmask for that class.
Thus `3.0.0.0` is an example of a Class A network. The netmask length for Class A is 8, so the full address space for this network is `3.0.0.0` to `3.255.255.255`. However, the first address (`3.0.0.0`) is reserved as the network address and the last address (`3.255.255.255`) is reserved as the broadcast address for that network. Thus the actual range of usable addresses is `3.0.0.1` to `3.255.255.254` which is 224 - 2 (= 16,777,214) total addresses.
Similarly, `200.20.30.0` is an example of a Class C network. The netmask length for Class C is 24, so the full address space for this network is `200.20.30.0` to `200.20.30.255`. Removing the network and broadcast addresses leaves the actual range of usable addresses is `200.20.30.1` to `200.20.30.254` which is 28 - 2 (= 254) total addresses.
There are further limitations on address ranges that may be used for public unicast. According to [RFC 6890](https://www.rfc-editor.org/rfc/rfc6890), the disallowed ranges are:
* `0.0.0.0/8` - Local networking
* `10.0.0.0/8` - Private-Use
* `100.64.0.0/10` - Shared Address Space
* `127.0.0.0/8` - Loopback
* `169.254.0.0/16` - Link Local
* `172.16.0.0/12`- Private-Use
* `192.0.0.0/24` - IETF Protocol Assignments
* `192.0.2.0/24` - Reserved for use in documentation
* `192.88.99.0/24` - 6to4 Relay Anycast
* `192.168.0.0/16` - Private-Use
* `198.18.0.0/15` - Benchmarking
* `198.51.100.0/24` - Reserved for use in documentation
* `203.0.113.0/24` - Reserved for use in documentation
Note that the above list uses VLSR netmasks to efficiently specify a range. In all but one cases, the given mask length has specificity is less than or equal to the normal classful mask length for the start of the range. Thus each of these VLSR ranges is equivalent to one or more classful networks. E.g. `172.16.0.0/12` is equivalent to the Class B networks `172.16.0.0` to `172.31.0.0` or the address range `172.16.0.0` to `172.31.255.255`.
The exception to this rule is the `100.64.0.0/10` VLSR range, which is more specific than the containing `100.0.0.0` Class A range. Thus `100.0.0.0` will be handled like other Class A ranges with the exception that it has a 4,194,304-address hole in the middle. The valid addresses in this Class A range will be `100.0.0.0` to `100.63.255.255` and `100.128.0.0` to `100.255.255.254`, a total of 224 - 222 - 2 (= 12,582,910) total addresses.
The goal of this challenge is to output all Class A, B and C unicast IPv4 addresses that may be validly assigned to a public internet host (i.e. excluding those detailed above).
* No input will be given and should not be expected.
* Output may be in any form convenient for your language, e.g. array, list, delimited string. Addresses must be output in standard dotted decimal format.
* Output order does not matter.
* Builtins that specifically give the required ranges of addresses are disallowed. Similarly any methods to dynamically inspect a [BGP](https://en.wikipedia.org/wiki/Border_Gateway_Protocol) (or other protocol) routing table for the public internet are disallowed.
The numerically lowest address will be `1.0.0.1` and the numerically highest will be `223.255.255.254`.
---
This challenge is similar to [Print out all IPv6 addresses](https://codegolf.stackexchange.com/questions/59934/print-out-all-ipv6-addresses), but because of the restrictions should require non-trivially different implementation.
[Answer]
## PowerShell, ~~648~~ ~~641~~ 625 bytes
```
for([uint64]$a=16MB;$a-lt2GB-16mb;$a++){if(($a%16mb)*(($a+1)%16mb)*($a-lt160MB-or$a-gt176MB)*($a-lt1604MB-or$a-ge1608MB)){([ipaddress]$a).IPAddressToString}}
for($a=2GB;$a-lt3GB;$a++){if(($a%64kb)*(($a+1)%64kb)*($a-lt2785152kb-or$a-gt2720mb)*($a-lt2753mb-or$a-gt2754mb)){([ipaddress]$a).IPAddressToString}}
for($a=3221225728;$a-lt3.5GB;$a++){if(($a%256)*(($a+1)%256)*(($a-lt3221225984-or$a-gt3221226240))*(($a-lt3227017984-or$a-gt3151385kb))*(($a-lt3156480kb-or$a-gt3156544kb))*(($a-lt3245184kb-or$a-gt3245312kb))*(($a-lt3247321kb-or$a-gt3325256959))*(($a-lt3405803776-or$a-gt3405804032))){([ipaddress]$a).IPAddressToString}}
```
Edit 1 -- I've golfed out all remaining powers-of-two operators, which saved an additional 7 bytes.
Edit 2 -- Moved the `[uint64]` cast to the first declaration of `$a` which eliminated the other two re-casts which saved 16 bytes.
Three lines, Class A / Class B / Class C. Left as separate lines for readability. ;-)
Two key points for understanding what's going on:
* PowerShell has powers-of-two operators `KB, MB, GB`. For example, `4KB` will return `4096` as an int. We leverage that in multiple locations to shave dozens of bytes.
* The .NET `[ipaddress]` class will try to [parse](https://msdn.microsoft.com/en-us/library/13180abx(v=vs.110).aspx) a numerical value as an IP address by taking the number's binary representation. We use that constructor with the `IPAddressToString` argument for output.
By coupling those two things, we're able to just treat the IP addresses as numbers and loop through them with a `for()` loop. For example, the first loop for Class A subnets goes from `16MB` to `2GB-16MB`, or from `16777216` to `2130706432`. The binary representation of `16777216` is `1000000000000000000000000` or `00000001.00000000.00000000.00000000` if we split it into 8-bit chunks so we can easily see that corresponds to `1.0.0.0` in dotted-decimal notation. Similarly, `2130706432` can be written as `01111111000000000000000000000000` or `01111111.00000000.00000000.00000000` or `127.0.0.0`. Each integer, or power-of-two integer, used here can be rewritten as an IP address in this fashion.
So, for each loop iteration, we construct an `if()` statement to weed out the excluded addresses, by multiplying the individual statements together. Since the first statement in each `if` is an integer (thanks to the modulo testing), the remaining Boolean values are converted to either `0` or `1` for false/true. If any one of the statements are false, the whole multiplication will turn to `0` and thus be false. Thus, only if all the statements are true, will we output the result of the parsing.
### Slightly Ungolfed:
```
# Class A
for($a=16MB;$a-lt2GB-16mb;$a++){
$b=($a%16mb) # x.0.0.0
$b*=(($a+1)%16mb) # x.255.255.255
$b*=($a-lt160MB-or$a-gt176MB) # 10.0.0.0/8
$b*=($a-lt1604MB-or$a-ge1608MB) # 100.64.0.0/10
if($b){([ipaddress]::Parse($a)).IPAddressToString}
}
# Class B
for($a=2GB;$a-lt3GB;$a++){
$b=($a%64kb) # x.y.0.0
$b*=(($a+1)%64kb) # x.y.255.255
$b*=(($a-lt2785152kb-or$a-gt2720mb)) # 169.254.0.0/16
$b*=(($a-lt2753mb-or$a-gt2754mb)) # 172.16.0.0/12
if($b){([ipaddress]::Parse($a)).IPAddressToString}
}
# Class C
for($a=3221225728;$a-lt3.5GB;$a++){
$b=($a%256) # x.y.z.0
$b*=(($a+1)%256) # x.y.z.255
$b*=(($a-lt3221225984-or$a-gt3221226240)) # 192.0.2.0/24
$b*=(($a-lt3227017984-or$a-gt3151385kb)) # 192.88.99.0/24
$b*=(($a-lt3156480kb-or$a-gt3156544kb)) # 192.168.0.0/16
$b*=(($a-lt3245184kb-or$a-gt3245312kb)) # 198.18.0.0/15
$b*=(($a-lt3247321kb-or$a-gt3325256959)) # 198.51.100.0/24
$b*=(($a-lt3405803776-or$a-gt3405804032)) # 203.0.113.0/24
if($b){([ipaddress]::Parse($a)).IPAddressToString}
}
```
[Answer]
## Batch, ~~1930~~ ~~1884~~ ~~1848~~ 1830 bytes
```
@echo off
for /l %%a in (1,1,9)do call:a1 %%a
for /l %%a in (11,1,99)do call:a1 %%a
for /l %%b in (0,1,63)do call:a2 100 %%b
for /l %%b in (128,1,255)do call:a2 100 %%b
for /l %%a in (101,1,126)do call:a1 %%a
for /l %%a in (128,1,168)do call:b1 %%a
for /l %%b in (0,1,253)do call:b2 169 %%b
call:b2 169 255
call:b1 170
call:b1 171
for /l %%b in (0,1,15)do call:b2 172 %%b
for /l %%b in (32,1,255)do call:b2 172 %%b
for /l %%a in (173,1,191)do call:b1 %%a
call:c3 192 0 1
for /l %%c in (3,1,255)do call:c3 192 0 %%c
for /l %%b in (1,1,87)do call:c2 192 %%b
for /l %%c in (0,1,98)do call:c3 192 88 %%c
for /l %%c in (100,1,255)do call:c3 192 88 %%c
for /l %%b in (89,1,167)do call:c2 192 %%b
for /l %%b in (169,1,255)do call:c2 192 %%b
for /l %%a in (193,1,197)do call:c1 %%a
for /l %%b in (0,1,17)do call:c2 198 %%b
for /l %%b in (20,1,50)do call:c2 198 %%b
for /l %%c in (0,1,99)do call:c3 198 51 %%c
for /l %%c in (101,1,255)do call:c3 198 51 %%c
for /l %%b in (52,1,255)do call:c2 198 %%b
for /l %%a in (199,1,202)do call:c1 %%a
for /l %%c in (0,1,112)do call:c3 203 0 %%c
for /l %%c in (114,1,255)do call:c3 203 0 %%c
for /l %%b in (1,1,255)do call:c2 203 %%b
for /l %%a in (204,1,223)do call:c1 %%a
exit/b
:a1
for /l %%b in (0,1,255)do call:a2 %1 %%b
exit/b
:a2
for /l %%c in (0,1,255)do call:a3 %1 %2 %%c
exit/b
:a3
for /l %%d in (0,1,255)do if not %2%3%%d==000 if not %2%3%%d==255255255 echo %1.%2.%3.%%d
exit/b
:b1
for /l %%b in (0,1,255)do call:b2 %1 %%b
exit/b
:b2
for /l %%c in (0,1,255)do call:b3 %1 %2 %%c
exit/b
:b3
for /l %%d in (0,1,255)do if not %3%%d==00 if not %3%%d==255255 echo %1.%2.%3.%%d
exit/b
:c1
for /l %%b in (0,1,255)do call:c2 %1 %%b
exit/b
:c2
for /l %%c in (0,1,255)do call:c3 %1 %2 %%c
exit/b
:c3
for /l %%d in (1,1,254)do echo %1.%2.%3.%%d
```
Edit: Saved ~~46~~ 82 bytes by removing unnecessary spaces. Saved 18 bytes by using `exit/b` instead of `goto:eof`.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/69642/edit).
Closed 8 years ago.
[Improve this question](/posts/69642/edit)
A two-dimensional array of size n×n is filled with n\*n numbers, starting from number 1. Those numbers are to be sorted per row in ascending order; the first number of a row must be greater than the last number of the previous row (the smallest number of all (1) will be in [0,0]). This is similar to the [15 puzzle](https://en.wikipedia.org/wiki/15_puzzle).
This is, for example, a sorted array of size *n = 3*.
```
1 2 3
4 5 6
7 8 9
```
## Input
The input is a scrambled array. It can be of any size up to n = 10. Example for n = 3:
```
4 2 3
1 8 5
7 9 6
```
## Output
Output a list of *swaps* required to sort the array. A *swap* is defined as following: **Two *adjacent* numbers swap positions, either horizontally or vertically; diagonal swapping is not permitted.**
Example output for the example above:
* Swap 4 and 1
* Swap 8 and 5
* Swap 8 and 6
* Swap 9 and 8
**The less swaps required, the better.** Computation time must be feasible.
---
Here is another example input, with n = 10:
```
41 88 35 34 76 44 66 36 58 28
6 71 24 89 1 49 9 14 74 2
80 31 95 62 81 63 5 40 29 39
17 86 47 59 67 18 42 61 53 100
73 30 43 12 99 51 54 68 98 85
13 46 57 96 70 20 82 97 22 8
10 69 50 65 83 32 93 45 78 92
56 16 27 55 84 15 38 19 75 72
33 11 94 48 4 79 87 90 25 37
77 26 3 52 60 64 91 21 23 7
```
If I'm not mistaken, this would require around 1000-2000 swaps.
[Answer]
# Mathematica, not golfed
```
towards[a_,b_]:={a,a+If[#==0,{0,Sign@Last[b-a]},{#,0}]&@Sign@First[b-a]};
f[m_]:=Block[{m2=Map[QuotientRemainder[#-1,10]+1&,m,{2}]},
Rule@@@Apply[10(#1-1)+#2&,#,{2}]&@
Reap[Table[
m2=NestWhile[
Function[{x},x/.(Sow[#];Thread[#->Reverse@#])&[x[[##]]&@@@towards[First@Position[x,i,{2}],i]]]
,m2,#~Extract~i!=i&];
,{i,Reverse/@Tuples[Range[10],2]}];][[2,1]]]
```
---
**Explanation**:
The algorithm is similar to "bubble sort". These 100 numbers are put into correct order one by one, `1, 11, 21, ..., 91; 2, ..., 92; ...; 10, ..., 100`. They are first move up/down to the correct rows, and then move left to the correct columns.
Function `towards` gives the two position to swap. For example, if `{5,2}` is moving to `{1,1}`, `towards[{5,2},{1,1}]` gives `{{5,2},{5,1}}` (move up); and `towards[{5,1},{1,1}]` gives `{{5,1},{4,1}}` (move left).
---
**Results**:
For the test case, the total number of swaps is 558. The first few swaps are,
```
{1->76,1->34,1->35,1->88,1->41,11->16,11->69,11->46, ...
```
For a random configuration, the total number of swaps is **558.5 ± 28.3** (1σ).
[](https://i.stack.imgur.com/NanGw.png)
] |
[Question]
[
Some friends and I have played some DSA (a mainly german tabletop RPG much like D&D). I was wondering what the chance on passing rolls are, so you will have to write some code to calculate it.
Your character is defined by stats (from 8 to 14) and (TV) Talent values (0 to 21). For now we will use climbing as an example.
### Talent tests
A talent (climbing) looks like this: (Courage-Dexterity-Strength) TV: 7. To test a character on a talent you roll on these stats with a 20-sided dice and try to get below or equal to the stat, if you do that well. If not, you can use your TV points to reduce the roll with a ratio of 1:1.
### Example
A hunter with courage 12, dexterity 13 and strength 14 is trying to climb a tree, his TV is 7.
He rolls a 3, the value is below 12 so he passed that roll.
Then he rolls a 17, 17 is 4 more than 13, so 4 TV get used up with 3 left.
For the last roll you get a 14, spot on passed.
All rolls are passed and the hunter managed to climb the tree, 3 TV are left.
### Input
4 values in any format you choose, taken from the standard input of your language.
It has to be in this order though.
E.g. `12 13 14 7` or `12,13,14,7` or as an array {12,13,14,7} or mixed `[12, 14, 8], 3`
### Output
The chance of how often the rolls pass.
E.g. (for values above)`0.803`
```
12,14,8,3 = 0.322
11,11,12,11 = 0.840
```
For the bonus:
Again formating is not the issue here, output it however you like but in following order:
```
failed/with 0/with 1/with 2/with 3/with 4/with 5/with 6/with 7
```
and so on until no TV is left.
```
12,13,14,7 = 0.197/0.075/0.089/0.084/0.078/0.073/0.068/0.063/0.273
12,14,8,3 = 0.678/0.056/0.051/0.047/0.168
```
### Challenge and rules and bonus
* You shall find out given the input the chance to pass the rolls to a +- 0.5% accuracy.
* -20% if your program also outputs the chances to pass with `n` TV (see output).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# Pyth - ~~21~~ ~~20~~ 19 bytes
*Saved 1 bytes thanks to @ThomasKwa*
```
.Omgvzsg#0-VdQ^SyT3
```
[Test Suite](http://pyth.herokuapp.com/?code=.Omgvzsg%230-VdQ%5ESyT3&test_suite=1&test_suite_input=11%0A11%2C11%2C12%0A3%0A12%2C14%2C8%0A7%0A12%2C13%2C14&debug=0&input_size=2).
[Answer]
## Dyalog APL, 28 bytes
```
{(+/÷⍴)⍵≥∊+/¨0⌈(⊂⍺)-⍨¨⍳3⍴20}
```
This approach is the same as @Maltysen's. We can't be *sure* of 0.5% accuracy if we just draw a few thousand random dice rolls, so we instead take the average over all possible rolls. This takes the three stats as the left argument, and the talent value on the right.
Try it [here](http://tryapl.org/?a=12%2013%2014%20%7B%28+/%F7%u2374%29%u2375%u2265%u220A+/%A80%u2308%28%u2282%u237A%29-%u2368%A8%u23733%u237420%7D%207&run)!
] |
[Question]
[
As someone who can't be bothered to look at their pentominos to see if it makes a rectangular shape, I've decided to make you write a program that does it.
# Your task
Given some input split by newlines containing 12 unique characters, decide if it is a valid solution.
A valid solution MUST
* Have 5 of each character (except newlines)
* Each set of characters must be fully connected
* Each set of characters must have a unique shape
* Be in a regular rectangular shape
If it is a valid solution, output a truthy value, otherwise output a falsy value.
Your program may be a function or a full program but must take the input from stdin and output to stdout.
## Test cases
Valid solutions
```
000111
203331
203431
22 444
2 46
57 666
57769!
58779!
58899!
5889!!
00.@@@ccccF111//=---
0...@@c))FFF1//8===-
00.ttttt)))F1/8888=-
```
Invalid configurations
```
invalid (doesn't contain 12 unique characters)
111112222233333444445555566666
77777888889999900000qqqqqwwwww (Each set has the same shape)
1234567890qw
w1234567890q
qw1234567890
0qw123456789
90qw12345678 (None of the characters are connected)
1234567890qw (Not 5 characters in every set)
1111122222333334444455555666666
77777888889999900000qqqqqwwwwww (More than 5 characters in some sets)
00
0
00.@@@ccccF111//=---
...@@c))FFF1//8===-
.ttttt)))F1/8888=- (Doesn't form a rectangular shape)
```
[Answer]
# JavaScript (ES6), ~~237~~ ~~235~~ 222 bytes
```
f=p=>(m=[],s=[],d=0,l=p.indexOf`
`+1,[...p].map((c,i)=>(i+1)%l&&!m[i]?g=d-2<s.indexOf((t=a=>m[a]|p[a]!=c?r=0:(m[a]=y.push(a),n=a<n?a:n,t(a+1)+t(a-1)+t(a+l)+t(a-l)+1))(n=i,y=[])!=5?g=0:s[d++]=y.map(a=>r+=a-n)|r):0),d==12&g)
```
2 bytes saved thanks to [@DankMemes](https://codegolf.stackexchange.com/users/20666/dankmemes)!
## Usage
```
f(`000111
203331
203431
22 444
2 46
57 666
57769!
58779!
58899!
5889!!`);
=> true
```
## Explanation
A couple of notes about this solution:
* It's possible this answer is not valid. It does not actually check if rotated pentominoes are the same shape, however I tried but could not find a valid pentomino rectangle that meets the requirements in the rules and includes two or more of the same shape rotated. But I'm no pentomino expert so if you find a valid combination that this fails with, let me know.
* The rules also require answers to use `STDIN` and `STDOUT` for input and output but `prompt()` is only designed for single line input and my (Windows) computer automatically puts `\r\n` characters at every new line when pasting so I made it a function that accepts a string.
```
f=p=>(
m=[], // m = map of checked characters
s=[], // s = list of shapes found (stored as integer)
d=0, // d = number shapes found
l=p.indexOf`
`+1, // l = length of each line (including newline character)
[...p].map((c,i)=> // iterate through each character of the input
(i+1)%l&& // skip newline characters
!m[i]? // skip the character if it has already been mapped
g= // g = pentomino is valid
d-2<s.indexOf( // check if shape already existed before just now
(t=a=> // t() checks if character is part of the shape then maps it
m[a]| // skip if character is already mapped
p[a]!=c // or if the current character is part of the shape
?r=0:(
m[a]= // mark the character as mapped
y.push(a), // y = list of shape character indices
n=a<n?a:n, // n = minimum index of all characters in the shape
t(a+1)+ // check and map adjacent characters
t(a-1)+
t(a+l)+
t(a-l)+
1
)
)(n=i,y=[])
!=5?g=0: // make sure there are only 5 characters in the shape
s[d++]= // add the shape to the list
y.map(a=> // sum of (index of each character in the shape - minimum
r+=a-n)|r // index) = unique integer representing the shape
):0
),
d==12&g // ensure there is 12 shapes and return the 'is valid' result
)
```
] |
[Question]
[
# Introduction
The challenge is a very interesting variant of the [game racetrack](https://en.wikipedia.org/wiki/Racetrack_(game)) and those two challenges:
* [To Vectory! – The Vector Racing Grand Prix](https://codegolf.stackexchange.com/questions/32622/to-vectory-the-vector-racing-grand-prix)
* [Program a Racing Car](https://codegolf.stackexchange.com/questions/42215/program-a-racing-car)
Source of this challenge is here (in German): [c't-Racetrack](http://www.heise.de/ct/ausgabe/2015-23-Knobelaufgabe-c-t-Racetrack-2845878.html)
This challenge is especially interesting (and different from the two abovementioned challenges) because it combines a huge search-space with some exact conditions that have to be met. Because of the huge search-space exhaustive search techniques are hard to use, because of the exact conditions approximate methods are also not easily usable. Because of this unique combination (plus the underlying intuition from physics) the problem is fascinating (and everything in connection with racing cars is fascinating anyway ;-)
# Challenge
Have a look at the following racetrack ([source](http://www.heise.de/ct/ausgabe/2015-23-Knobelaufgabe-c-t-Racetrack-2845878.html)):
[](https://i.stack.imgur.com/2Myqh.jpg)
You have to start at `(120,180)` and finish exactly at `(320,220)` ("Ziel" in German) without touching one of the walls.
The car is controlled by acceleration vectors of the form `(a_x,a_y)` - as an example:
```
(8,-6)
(10,0)
(1,9)
```
The first number is the acceleration for the x-vector, the second for the y-vector. They have to be integers because you are only allowed to use the integer points on the grid. Additionally the following condition has to be met:
```
a_x^2 + a_y^2 <= 100,
```
which means that acceleration in any direction has to be below or equal to `10`.
To see how it works have a look at the following picture ([source](http://www.heise.de/ct/ausgabe/2015-23-Knobelaufgabe-c-t-Racetrack-2845878.html)):
[](https://i.stack.imgur.com/kxYmB.jpg)
As an example: Starting from `(120,180)` you accelerate by `8` in x-direction and by `-6` in y-direction. For the next step this is your velocity where you add your acceleration `(10,0)` to get (physically correct) your next resulting movement (to point `(146,168)`. The resulting movement is what counts when it comes to examining whether you touched one of the walls. In the next step you again add your next acceleration vector to your current velocity to get the next movement and so on. So at every step your car has a position and a velocity. (In the illustrative picture above the blue arrows are for the velocity, the orange arrows for acceleration and the dark red arrows for the resulting movement.)
As an additional condition you have to have `(0,0)` terminal velocity when you are on the finishing point `(320,220)`.
The output has to be a list of acceleration vectors in the abovementioned form.
The winner is the one who provides a program which finds a solution with the fewest acceleration vectors.
*Tiebreaker*
Additionally it would be great if you can show that this is an optimal solution and whether this is the only optimal solution or whether there are several optimal solutions (and which they are).
It would also be good if you could give a general outline of how your algorithm works and comment the code so that we can understand it.
I have a program which checks whether any given solution is valid and I will give feedback.
*Addendum*
You can use any programming language but I would be especially delighted if somebody used R because I use it a lot in my day job and somehow got used to it :-)
*Addendum II*
For the first time I started a bounty - hopefully this get's the ball rolling (or better: get's the car driving :-)
[Answer]
# Python, 24 steps (work in progress)
The idea was to solve the continuous problem first, vastly reducing the search space, and then quantize the result to the grid (by just rounding to the nearest gridpoint and searching the surrounding 8 squares)
I parametrize the path as a sum of trigonometric functions (unlike polynomials, they dont diverge and are easier to keep in check). I also control the velocity directly instead of the acceleration, because its easier to enforce the boundary condition by simply multiplying a weighting function that tends to 0 at the end.
My objective function consists of
-exponential score for acceleration > 10
-polynomial score for euclidean distance between the last point and the target
To minimize the score, i throw it all into [Nelder-Mead optimization](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method) and wait a few seconds. The algorithm always succeeds in getting to the end, stopping there and not exceeding the maximum acceleration, but it has troubles with walls. The path either teleports through corners and gets stuck there, or stops next to a wall with the goal just across (left image)
[](https://i.stack.imgur.com/9U4za.png)
During testing, i got lucky and found a path that was squiggled in a promising way (right image) and after tweaking the parameters some more i could use it as a starting guess for a successful optimization.
**Quantization**
After finding a parametric path, it was time to remove the decimal points. Looking at the 3x3 neighborhood reduces the search space from roughly 300^N to 9^N, but its still too big and boring to implement. Before i went down this road, i tried adding a "Snap to Grid" term to the objective function (the commented parts). A hundred more steps of optimization with the updated objective and simply rounding was enough to get the solution.
>
> [(9, -1), (4, 0), (1, 1), (2, 2), (-1, 2), (-3, 4), (-3, 3), (-2, 3), (-2, 2), (
> -1, 1), (0, 0), (1, -2), (2, -3), (2, -2), (3, -5), (2, -4), (1, -5), (-2, -3),
> (-2, -4), (-3, -9), (-4, -4), (-5, 8), (-4, 8), (5, 8)]
>
>
>
The number of steps was fixed and not part of optimization, but since we have an analytical description of the path, (and since the maximal acceleration is well below 10) we can reuse it as a starting point for further optimization with a smaller number of timesteps
```
from numpy import *
from scipy.optimize import fmin
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection as LC
walls = array([[[0,0],[500,0]], # [[x0,y0],[x1,y1]]
[[500,0],[500,400]],
[[500,400],[0,400]],
[[0,400],[0,0]],
[[200,200],[100,200]],
[[100,200],[100,100]],
[[100,100],[200,100]],
[[250,300],[250,200]],
[[300,300],[300,100]],
[[300,200],[400,200]],
[[300,100],[400,100]],
[[100,180],[120, 200]], #debug walls
[[100,120],[120, 100]],
[[300,220],[320, 200]],
#[[320,100],[300, 120]],
])
start = array([120,180])
goal = array([320,220])
###################################
# Boring stuff below, scroll down #
###################################
def weightedintersection2D(L1, L2):
# http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
p = L1[0]
q = L2[0]
r = L1[1]-L1[0]
s = L2[1]-L2[0]
d = cross(r,s)
if d==0: # parallel
if cross(q-p,r)==0: return 1 # overlap
else:
t = cross(q-p,s)*1.0/d
u = cross(q-p,r)*1.0/d
if 0<=t<=1 and 0<=u<=1: return 1-0*abs(t-.5)-1*abs(u-.5) # intersect at p+tr=q+us
return 0
def sinsum(coeff, tt):
'''input: list of length 2(2k+1),
first half for X-movement, second for Y-movement.
Of each, the first k elements are sin-coefficients
the next k+1 elements are cos-coefficients'''
N = len(coeff)/2
XS = [0]+list(coeff[:N][:N/2])
XC = coeff[:N][N/2:]
YS = [0]+list(coeff[N:][:N/2])
YC = coeff[N:][N/2:]
VX = sum([XS[i]*sin(tt*ww[i]) + XC[i]*cos(tt*ww[i]) for i in range(N/2+1)], 0)
VY = sum([YS[i]*sin(tt*ww[i]) + YC[i]*cos(tt*ww[i]) for i in range(N/2+1)], 0)
return VX*weightfunc, VY*weightfunc
def makepath(vx, vy):
# turn coordinates into line segments, to check for intersections
xx = cumsum(vx)+start[0]
yy = cumsum(vy)+start[1]
path = []
for i in range(1,len(xx)):
path.append([[xx[i-1], yy[i-1]],[xx[i], yy[i]]])
return path
def checkpath(path):
intersections = 0
for line1 in path[:-1]: # last two elements are equal, and thus wrongly intersect each wall
for line2 in walls:
intersections += weightedintersection2D(array(line1), array(line2))
return intersections
def eval_score(coeff):
# tweak everything for better convergence
vx, vy = sinsum(coeff, tt)
path = makepath(vx, vy)
score_int = checkpath(path)
dist = hypot(*(path[-1][1]-goal))
score_pos = abs(dist)**3
acc = hypot(diff(vx), diff(vy))
score_acc = sum(exp(clip(3*(acc-10), -10,20)))
#score_snap = sum(abs(diff(vx)-diff(vx).round())) + sum(abs(diff(vy)-diff(vy).round()))
print score_int, score_pos, score_acc#, score_snap
return score_int*100 + score_pos*.5 + score_acc #+ score_snap
######################################
# Boring stuff above, scroll to here #
######################################
Nw = 4 # <3: paths not squiggly enough, >6: too many dimensions, slow
ww = [1*pi*k for k in range(Nw)]
Nt = 30 # find a solution with tis many steps
tt = linspace(0,1,Nt)
weightfunc = tanh(tt*30)*tanh(30*(1-tt)) # makes sure end velocity is 0
guess = random.random(4*Nw-2)*10-5
guess = array([ 5.72255365, -0.02720178, 8.09631272, 1.88852287, -2.28175362,
2.915817 , 8.29529905, 8.46535503, 5.32069444, -1.7422171 ,
-3.87486437, 1.35836498, -1.28681144, 2.20784655]) # this is a good start...
array([ 10.50877078, -0.1177561 , 4.63897574, -0.79066986,
3.08680958, -0.66848585, 4.34140494, 6.80129358,
5.13853914, -7.02747384, -1.80208349, 1.91870184,
-4.21784737, 0.17727804]) # ...and it returns this solution
optimsettings = dict(
xtol = 1e-6,
ftol = 1e-6,
disp = 1,
maxiter = 1000, # better restart if not even close after 300
full_output = 1,
retall = 1)
plt.ion()
plt.axes().add_collection(LC(walls))
plt.xlim(-10,510)
plt.ylim(-10,410)
path = makepath(*sinsum(guess, tt))
plt.axes().add_collection(LC(path, color='red'))
plt.plot(*start, marker='o')
plt.plot(*goal, marker='o')
plt.show()
optres = fmin(eval_score, guess, **optimsettings)
optcoeff = optres[0]
#for c in optres[-1][::optimsettings['maxiter']/10]:
for c in array(optres[-1])[logspace(1,log10(optimsettings['maxiter']-1), 10).astype(int)]:
vx, vy = sinsum(c, tt)
path = makepath(vx,vy)
plt.axes().add_collection(LC(path, color='green'))
plt.show()
```
To Do: GUI that lets you draw an initial path to get a rough sense of direction. Anything is better than randomly sampling from 14-dimensional space
] |
[Question]
[
# Task
Your task is to write whole program, which will align given input to a block of given size.
*Input:*
```
40
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
```
*Output:*
```
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim
id est laborum.
<-- note the linebreak
```
### Input Details
* You have to write whole executable/interpretable program.
* You may suppose, that the input contains only printable ASCII characters and does not contain tab `\t`.
* The input can contain line breaks. If it does so, they are given as `\n`, `\r`, or `\r\n` depending on what you expect. They are however united throughout whole input.
* The input can be given in STDIN, or as command line arguments. You can use both of them if it suits your needs (for example, read block size from command args and input as stdin). You may not, however, hardcode any part of the input to your program.
* You may suppose that the block size is given as valid positive (`> 0`) number.
* Line break in the input is treated the same way as a space (thus being word separator)
* If the input contains multiple concurrent spaces they are treated as one.
### Output details
* The output has to be formatted into a block of given size. The formatting is done by adding spaces between words.
* The number of spaces between words on a line has to be equal for that line. If it is not possible, additional spaces must be added one by one after words starting from the left.
* If the word is longer that given block size, it will stand alone on a single line (and will exceed the block size).
* If the output should contain only one word, it will be aligned to the left.
* The last line of the output has to be aligned to the left, with only one space between words. The last line of the output has to end with trailing line break.
The answer, with shortest number of bytes after some time, wins.
If you need additional information, leave a comment.
## Test cases
```
Input:
10
Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do eiusmod tempor
Output:
Lorem
ipsum
dolor sit
amet,
consectetur
adipiscing
elit, sed
do eiusmod
tempor
```
---
```
Input:
20
Lorem ipsum
dolor sit amet,
Output:
Lorem ipsum dolor
sit amet,
```
---
```
Input:
1
Lorem ipsum dolor sit amet
Output:
Lorem
ipsum
dolor
sit
amet
```
[Answer]
# Pyth, ~~60~~ ~~57~~ ~~54~~ ~~51~~ ~~50~~ 52 bytes
**2015-10-22:** fixing a bug took 2 bytes.
```
=HfTcjd.zdWHAcH]f|qTlH>jd<HhTQ1s.iGcJ|tlG1*d?H-QlsGJ
```
[Try it online.](https://pyth.herokuapp.com/?code=%3DHfTcjd.zdWHAcH%5Df%7CqTlH%3Ejd%3CHhTQ1s.iGcJ%7CtlG1*d%3FH-QlsGJ&input=40%0ALorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+Ut+enim+ad+minim+veniam%2C+quis+nostrud+exercitation+ullamco+laboris+nisi+ut+aliquip+ex+ea+commodo+consequat.+Duis+aute+irure+dolor+in+reprehenderit+in+voluptate+velit+esse+cillum+dolore+eu+fugiat+nulla+pariatur.+Excepteur+sint+occaecat+cupidatat+non+proident%2C+sunt+in+culpa+qui+officia+deserunt+mollit+anim+id+est+laborum.&debug=0)
[Answer]
## Ruby, 179 chars
```
n=gets.to_i
s=t=''
$<.read.split.map{|w|if(t+w).size>=n
0while t.size<n&&(1..n).any?{|i|t.sub!(/[^ ]#{' '*i}(?=[^ ])/){|x|x+' '}}
s+=t+?\n
t=w
else
t+=' '+w
t.strip!
end}
puts s,t
```
Way too long...
Semi-ungolfed version:
```
n = gets.to_i
s = t = ''
$<.read.split.map{|w|
if (t + w).size >= n
0 while t.size < n && (1..n).any?{|i|t.sub!(/[^ ]#{' '*i}(?=[^ ])/){|x|x+' '}}
s += t + ?\n
t = w
else
t += ' ' + w
t.strip! # this is only necessary because of the very first word >:(
end
}
puts s,t
```
[Answer]
# CJam, 87 bytes
```
l~:LS*qNSerS%{(2$1$a+_S*,L>{;a\}{\;@;\}?}h;S*a]1>{I1>{LIs,-I,(md1b\aI,(*.+Sf*I.\}I?N}fI
```
This should still be golfable. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l~%3ALS*qNSerS%25%7B(2%241%24a%2B_S*%2CL%3E%7B%3Ba%5C%7D%7B%5C%3B%40%3B%5C%7D%3F%7Dh%3BS*a%5D1%3E%7BI1%3E%7BLIs%2C-I%2C(md1b%5CaI%2C(*.%2BSf*I.%5C%7DI%3FN%7DfI&input=40%0ALorem%20ipsum%20dolor%20sit%20amet%2C%20consectetur%20adipiscing%20elit%2C%20sed%20do%20eiusmod%20tempor%20incididunt%20ut%20labore%20et%20dolore%20magna%20aliqua.%20Ut%20enim%20ad%20minim%20veniam%2C%20quis%20nostrud%20exercitation%20ullamco%20laboris%20nisi%20ut%20aliquip%20ex%20ea%20commodo%20consequat.%20Duis%20aute%20irure%20dolor%20in%20reprehenderit%20in%20voluptate%20velit%20esse%20cillum%20dolore%20eu%20fugiat%20nulla%20pariatur.%20Excepteur%20sint%20occaecat%20cupidatat%20non%20proident%2C%20sunt%20in%20culpa%20qui%20officia%20deserunt%20mollit%20anim%20id%20est%20laborum.).
[Answer]
# [Retina](https://github.com/mbuettner/retina), 133 bytes
```
\s+
+`((1)*1 )((?<-2>.)*\S|\S+)
:$3<LF>$1
m+`^(?=.(.)+$[^<TB>]*^(?>(?<-1>1)+)1)((.*):(\S+ +)|(\S+ +)(.*):)
$3$4$5 :$6
+`:|<LF>1+| (?= .*$)
<empty>
```
The `<empty>` represents an empty trailing line. To run the code, put each line in a separate file, replace `<LF>` with linefeed characters (0x0A) and `<TB>` with a tab (0x09). I'll add an explanation when I'm done golfing.
] |
[Question]
[
Computers live by binary. All programmers know binary.
But the `2**x` bases are often neglected as non-practical, while they have beautiful relations to binary.
To show you one example of such a beatiful relation, 19 will be my testimonial.
```
19 10011 103 23 13 j
```
* 19 is decimal, included for clarity.
* 10011 is 19 in binary.
* 103, in base 4 is made starting from binary this way:
+ log2(4) == 2, let us remember two.
+ Pad 10011 so that it has a multiple of 2 length -> 010011
+ Take digits 2 by 2 from left to right and treat them as 2-digits binary numbers:
- 01 -> 1
- 00 -> 0
- 11 -> 3**Done**, 10011 in base-4 is 103.
For base 8, do the same but 3-by-3 as log2(8) = 3.
* Pad 010011
* 010 -> 2
* 011 -> 3
23, **Done**.
For base 16, do the same but 4-by-4 as log2(16) = 4.
* Pad 00010011
* 0001 -> 1
* 0011 -> 3
13, **Done**.
**Task**
Given a max number as input, you shall output a table
```
base-ten-i base-two-i base-four-i base-eight-i base-sixteen-i base-thirtytwo-i
```
for i that goes from 0 to n inclusive. Binary numbers are the epitome of the absolute minimum needed to work, so your code should be as short as possible.
**Restrictions and bonuses**
* Base-ten -> binary and binary -> Base-ten built-ins are considered loopholes as Base-a -> Base-b are.
* If you generate all the `2**i` (for i > 2) bases by using the relations over mentioned you get a `*0.6` bonus, but general base conversions (written by yourself) are allowed.
**Example table**
```
> 32
0 0 0 0 0 0
1 1 1 1 1 1
2 10 2 2 2 2
3 11 3 3 3 3
4 100 10 4 4 4
5 101 11 5 5 5
6 110 12 6 6 6
7 111 13 7 7 7
8 1000 20 10 8 8
9 1001 21 11 9 9
10 1010 22 12 a a
11 1011 23 13 b b
12 1100 30 14 c c
13 1101 31 15 d d
14 1110 32 16 e e
15 1111 33 17 f f
16 10000 100 20 10 g
17 10001 101 21 11 h
18 10010 102 22 12 i
19 10011 103 23 13 j
20 10100 110 24 14 k
21 10101 111 25 15 l
22 10110 112 26 16 m
23 10111 113 27 17 n
24 11000 120 30 18 o
25 11001 121 31 19 p
26 11010 122 32 1a q
27 11011 123 33 1b r
28 11100 130 34 1c s
29 11101 131 35 1d t
30 11110 132 36 1e u
31 11111 133 37 1f v
32 100000 200 40 20 10
```
[Answer]
# CJam, 54 \* 0.6 = 32.4 bytes
```
q~){_5,f{)L@{2md@+\}h(%/Wf%W%{{\2*+}*_9>{'W+}&}%S\}N}/
```
[Test it here.](http://cjam.aditsu.net/#code=q~)%7B_5%2Cf%7B)L%40%7B2md%40%2B%5C%7Dh(%25%2FWf%25W%25%7B%7B%5C2*%2B%7D*_9%3E%7B'W%2B%7D%26%7D%25S%5C%7DN%7D%2F&input=32)
For reference, here is a shorter solution which doesn't qualify for the bonus (at 39 bytes):
```
q~){:X5{SLX{2I)#md_9>{'W+}&@+\}h;}fIN}/
```
[Answer]
# Pyth, 52 \* 0.6 = 31.2 bytes
```
L?b+%b2y/b2YVUhQjd+NmjkX|_uL++GGHZ_McyNd]ZUQ+jkUTGS5
```
[Test it online](https://pyth.herokuapp.com/?code=L%3Fb%2B%25b2y%2Fb2YVUhQjd%2BNmjkX%7C_uL%2B%2BGGHZ_McyNd%5DZUQ%2BjkUTGS5&input=33&test_suite_input=1%0A2%0A15%0A77%0A12345678929&debug=0)
My non-bonus answer is 39 bytes
```
M?G+g/GHH@+jkUTG%GHkVUhQjd+N|R0gLN^L2S5
```
[Answer]
# PHP, ~~232~~ ~~230~~ ~~233~~ 217 \* 0.6 = 130.2
no chance beating the golfing languages, but I liked the challenge.
```
for(;$d<=$n;$d++){echo'
',$d|0;for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b;for($w=1;$w<6;$w++,print" $z"|' 0')for($z='',$k=strlen($b);-$w<$k-=$w;$z=($e>9?chr($e+87):$e).$z)for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k];}
```
* usage: prepend `$n=32;` or replace `$n` with `32` (or any other non-negative integer); call via cli
* If that is not accepted, replace `$n` with `$_GET[n]` (+6/+3.6) and call either in the browser
or on cli with `php-cgi -f bases.php -n=32`
* Replace the line break with `<br>` or prepend `<pre>` to test in browser
* may throw notices for undefined variables and unintialized string offsets in newer PHP versions.
Remove E\_NOTICE from error\_reporting (prepend `error_reporting(0);`) to suppress them.
* tested in 5.6
break down:
```
for(;$d<=$n;$d++) // loop decimal $d from 0 to $n
{
echo'
',$d|0; // print line break and decimal
for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b; // convert $d to binary
for($w=1;$w<6;$w++,
print" $z"|' 0' // print number generated in inner loop (echo doesn´t work here)
)
for($z='',$k=strlen($b);-$w<$k-=$w; // loop from end by $w
$z=($e>9?chr($e+87):$e).$z // prepend digit created in body
)
for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k]; // convert chunk to 2**$w
}
```
major edit:
* used some index magic to revamp the inner loop -> now works backwards on the whole string (no more padding, no more splitting or copying the binary)
* moved parts of the loop bodies to the heads to eliminate braces
* had to add ~~7~~ 4 bytes to fix the decimal 0 results after the revamp
# non-bonus version, 142 bytes
```
for(;$d<=$n;$d++,print'
',$d|0)for($w=1;$w<6;$w++,print" $z"|' 0')for($k=$d,$y=1,$z='';$k&&$y<<=$w;$k>>=$w)$z=(9<($e=$k%$y)?chr($e+87):$e).$z;
```
**PHP beats Python?**
Even if I added the 6 (3.6) bytes to make the snippet a program, I´d still beat Python (223\*0.6=133.8 or 148 non-bonus vs. 158). Amazing.
[Answer]
## Ruby, 80 bytes (non-bonus version)
```
m=ARGV[0].to_i;(0..m).each{|n|puts [10,2,4,8,16,32].map{|b|n.to_s(b)}.join(' ')}
```
[Answer]
## Python3 - 189, 167, 166 150 bytes
```
for i in range(int(input())+1):f=lambda b,n=i,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(b,n//b)+c[n%b];print(i,f(2),f(4),f(8),f(16),f(32))
```
Saved 16 bytes with the help of @[LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun%20LeakyNun)!
## Bonus version - 296 \* 0.6 = 177.6 279 \* 0.6 = 167.4 bytes
```
p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(n//b,b)+c[n%b];v=f(i,2);d=z(v);print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))
```
Slightly more readable version of the bonus version.
```
p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):
f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n] or f(n//b,b) + c[n%b]
v=f(i,2)
d=z(v)
print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))
```
] |
[Question]
[
I'm a lazy but efficient person, as many of you probably are as well. So, whenever I'm doing something I want to do it with minimal effort. Which is why I'm asking you to solve this problem for me.
What I have here is a document of sorts. On every line of this document is a single word or short phrase. The document is not sorted, but that's ok I know where everything is. I could use some help finding things faster, and for that I need a second list. This is where you come in. For every line of text in this document, I need some identifier. Something I can `CTRL`+`F`, but it can't be longer than absolutely necessary for getting that one result.
Example input:
```
(blank)
an apple
spiderman 3
7pm pick up laundry
tequila
fake mustache
dishes on wednesday
banana
biscuits
(blank)
```
Example output:
```
ap,3,7,q,f,w,ba,bi
```
I'm going to repeat myself here, to make sure we're on the same page:
* The input is an unformatted text file containing a list of items, separated by line breaks. I have it here in .txt format, it's called "STUFF.TXT"
* The first and last line of the document are empty. Every other line contains an entry of length >0.
* The file contains only alfanumeric characters (all lower case), spaces, and line breaks.
* Desired output is a list of identifiers, in the same order as my original list.
* I don't want more than one search word for every list item. If there are multiple answers, pick one, I don't care which. In the above example I picked 'ap' for `an apple`, but you could have picked 'n ', ' a', 'pp', 'pl' or 'le'. Not 'an', because that's in `banana`.
* I can assure you, the file is never empty, and it never contains duplicates.
* **If necessary**, you can match on the line terminator. But that's a last resort only to be used when there's no other way to distinguish between list items (e.g. 'apple' and 'apples').
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are not allowed. Also, this is code golf so shortest code wins.
One more example:
```
(blank)
ban
any
king
bean
yen
rake
raki
bar
(blank)
```
And its output:
```
ban,ny,g,be,ye,ke,aki,ar
```
[Answer]
# Pyth, 39 bytes
```
Lsm.:bdtUbKfT.zj\,mhf!}Yjb-Kk+yky++bkbK
```
Bruteforces all subsets of every string in increasing length and checks if that string occurs inside any other. If that doesn't work, it will do the same except for all subsets of `\nstring\n`.
] |
[Question]
[
This is my first experiment with an asymptotic complexity challenge although I am happy with answers entirely in code as long as they come with an explanation of their time complexity.
I have the following problem.
Consider tasks T\_1, ... T\_n and procs M\_1, ... , M\_m. Each task takes a certain amount of time to perform depending on the procs.
Each task also costs a certain amount to perform depending on the procs.
The tasks have to be done in strict order (they can't be done in parallel) and it takes time to change proc. A task can't be moved from one proc to another after it has been started.
Finally, each task must be completed by a certain time.
**the task**
The objective is to give an algorithm (or some code) that given five tables of the form above, minimizes the total cost to complete all the tasks while making sure all the tasks are completed by their deadlines. If this isn't possible we just report that it can't be done.
**score**
You should give the big Oh complexity of your solution in terms of the variables n, m and d, where d is the last deadline. There should be no unnecessary constants in your big Oh complexity. So O(n/1000) should be written as O(n), for example.
Your score is calculated simply by setting n = 100, m = 100 and d = 1000 into your stated complexity. You want the smallest score possible.
**tie breaker**
In the case of a tie, the first answer wins.
---
**added notes**
`log` in the time complexity of an answer will be taken base 2.
**score board**
* 10^202 from KSFT (**Python**) First submitted so gets the bounty.
* 10^202 from Dominik Müller (**Scala**)
[Answer]
# Score: 10^202
I kinda wish we had LaTeX support now...
Since no one else has answered, I thought I'd try, even though is isn't very efficient. I'm not sure what the big O of it is, though.
I think it works. At least, it does for the only test case posted.
It takes input like in the question, except without the machine or task number labels, and with semicolons instead of line breaks.
```
import itertools
time = [[int(j) for j in i.split()] for i in raw_input().split(";")]
cost = [[int(j) for j in i.split()] for i in raw_input().split(";")]
nmachines=len(time)
ntasks=len(time[0])
switchtime = [[int(j) for j in i.split()] for i in raw_input().split(";")]
switchcost = [[int(j) for j in i.split()] for i in raw_input().split(";")]
deadline = [int(i) for i in raw_input().split()]
d={}
m=itertools.product(range(nmachines),repeat=ntasks)
for i in m:
t=-switchtime[i[-1]][i[0]]
c=-switchcost[i[-1]][i[0]]
e=0
meetsdeadline=True
for j in range(ntasks):
t+=switchtime[i[e-1]][i[e]]+time[i[e]][j]
c+=switchcost[i[e-1]][i[e]]+cost[i[e]][j]
e+=1
if t>deadline[j]:
meetsdeadline=False
if meetsdeadline:
d[(c,t)]=i
print min(d.keys()),d[min(d.keys())]
```
[Answer]
# Check All - Scala
Estimated score: 2m^n
I start from each machine and iterate over all the tasks to create all permutations through the tasks with different machines that meet the deadlines. Meaning if everything is in time I would get 9 possible paths with 2 machines and 3 tasks. (m^n) Afterwards, I take the path with the lowest cost.
Input is structured like this (--> explains the parts and thus should not be entered):
```
M_1:5 3 5 4;M_2:4 2 7 5 --> time
M_1:5 4 2 6;M_2:3 7 3 3 --> cost
M_1:M_1}0 M_2}1;M_2:M_1}2 M_2}0 --> switch itme
M_1:M_1}0 M_2}2;M_2:M_1}1 M_2}0 --> switch cost
5 10 15 20 --> deadlines
```
And here is the code:
```
package Scheduling
import scala.io.StdIn.readLine
case class Cost(task: Map[String, List[Int]])
case class Switch(machine: Map[String, Map[String, Int]])
case class Path(time: Int, cost: Int, machine: List[String])
object Main {
def main(args: Array[String]) {
val (machines, cost_time, cost_money, switch_time, switch_money, deadlines) = getInput
val s = new Scheduler(machines, cost_time, cost_money, switch_time, switch_money, deadlines)
s.schedule
}
def getInput(): (List[String], Cost, Cost, Switch, Switch, List[Int]) = {
val cost_time = Cost(readLine("time to complete task").split(";").map{s =>
val parts = s.split(":")
(parts(0) -> parts(1).split(" ").map(_.toInt).toList)
}.toMap)
val cost_money = Cost(readLine("cost to complete task").split(";").map{s =>
val parts = s.split(":")
(parts(0) -> parts(1).split(" ").map(_.toInt).toList)
}.toMap)
val switch_time = Switch(readLine("time to switch").split(";").map{s =>
val parts = s.split(":")
(parts(0) -> parts(1).split(" ").map{t =>
val entries = t.split("}")
(entries(0) -> entries(1).toInt)
}.toMap)
}.toMap)
val switch_money = Switch(readLine("time to switch").split(";").map{s =>
val parts = s.split(":")
(parts(0) -> parts(1).split(" ").map{t =>
val entries = t.split("}")
(entries(0) -> entries(1).toInt)
}.toMap)
}.toMap)
val deadlines = readLine("deadlines").split(" ").map(_.toInt).toList
val machines = cost_time.task.keys.toList
(machines, cost_time, cost_money, switch_time, switch_money, deadlines)
}
}
class Scheduler(machines: List[String], cost_time: Cost, cost_money: Cost, switch_time: Switch, switch_money: Switch, deadlines: List[Int]) {
def schedule() {
var paths = List[Path]()
var alternatives = List[(Int, Path)]()
for (i <- machines) {
if (cost_time.task(i)(0) <= deadlines(0)) {
paths = paths ::: List(Path(cost_time.task(i)(0), cost_money.task(i)(0), List(i)))
}
}
val allPaths = deadlines.zipWithIndex.tail.foldLeft(paths)((paths, b) => paths.flatMap(x => calculatePath(x, b._1, b._2)))
if (allPaths.isEmpty) {
println("It is not possible")
} else {
println(allPaths.minBy(p=>p.cost).machine)
}
}
def calculatePath(prev: Path, deadline: Int, task: Int): List[Path] = {
val paths = machines.map(m => calculatePath(prev, task, m))
paths.filter(p => p.time <= deadline)
}
def calculatePath(prev: Path, task: Int, machine: String): Path = {
val time = prev.time + switch_time.machine(prev.machine.last)(machine) + cost_time.task(machine)(task)
val cost = prev.cost + switch_money.machine(prev.machine.last)(machine) + cost_money.task(machine)(task)
Path(time, cost, prev.machine :+ machine)
}
}
```
I also had an idea to start from the back. Since you can always choose a machine with the lowest cost if the time is smaller then the difference from the previous deadline to the new one. But that wouldn't decrease the maximal runtime if the task with the better cost takes longer then the last deadline is timed.
# Update
======
Here is another set up.
time:
```
M_1 2 2 2 7
M_2 1 8 5 10
```
cost:
```
M_1 4 4 4 4
M_2 1 1 1 1
```
switch time:
```
M_1 M_2
M_1 0 2
M_2 6 0
```
switch cost:
```
M_1 M_2
M_1 0 2
M_2 2 0
```
deadlines:
```
5 10 15 20
```
As input into my program:
```
M_1:2 2 2 7;M_2:1 8 5 10
M_1:4 4 4 4;M_2:1 1 1 1
M_1:M_1}0 M_2}2;M_2:M_1}6 M_2}0
M_1:M_1}0 M_2}2;M_2:M_1}2 M_2}0
5 10 15 20
```
This one has two solutions:
time: 18, cost: 15, path: List(M\_1, M\_1, M\_1, M\_2)
time: 18, cost: 15, path: List(M\_2, M\_1, M\_1, M\_1)
Which raises the question how this should be handled. Should all be printed or just one? And what if the time would be different? Is one with the lowest cost and no missed deadline enough or should it also be the one with the lowest time?
[Answer]
# O(m2n) = 1000000
I am sure this will be beaten, but I figure I will give this as a reference answer.
First, construct a Directed Acyclic Graph using the data. The graph will be built out of layers (kind of like a neural net, for those who are familiar with them). The first layer just has the start vertex, a placeholder. The next layer has m vertices, one for each machine. There is an edge from the start vertex to each of the m vertices, with path cost 0. These edges represent the initial choice of which machine to start on.
The next layer has another m vertices, again representing the m machines. This time, the number of edges from the previous layer to this layer is m\*m = m2. Each of these edges has a cost equal to running task 1 on the corresponding machine in the previous layer, plus switching to the corresponding machine in the next layer. It also has a second cost equal to the switching time (you can track these two costs are tuples).
Continue on in this way: we will have one layer for each task, plus the dummy "start" and "end" layers. Each of the first n-1 non-dummy layers has m2 edges going to the next layer. So, we have a DAG with O(m2n) edges, and O(mn) vertices. Now we simply perform a topological sort on the DAG, but every time a total time cost exceeds the relevant deadline, we delete the edge that would violate the deadline, and keep going. DAG topological sorting can be done in O(|E| + |V|), so we get the answer (or lack thereof) in O(m2n) time.
] |
[Question]
[
In the Futurama episode [The Prisoner of Benda](http://en.wikipedia.org/wiki/The_Prisoner_of_Benda) members of the crew swap bodies with each other, with the catch that no pair of *bodies* can have their minds swapped more than once.
### Challenge
Write a program or function that accepts a valid collection of mind-body swaps that have already occurred, and outputs a legal set of swaps that will return each mind to its original body. The identifiers for these mind-body collections must be strings which will not contain newlines. You may add up to two (distinctly named) people who have had no prior swaps to the input group. [(Proof that you only need at most 2 additional bodies)](http://en.wikipedia.org/wiki/The_Prisoner_of_Benda#The_theorem) However, you must add the minimum number of people required to solve the problem.
The input and output may take any clear form, however, no additional information can be stored in either. You may assume it is always valid. This is code golf, so the winner is the submission with the fewest bytes.
### Examples
```
[('A','B'),('C','D')] -> [('A','C'),('B','D'),('A','D'),('B','C')]
['A','B'] -> ['C','D','A','C','B','D','A','D','B','C']
[('A','B'),('C','D'),('A','C'),('A','D')] -> [('B', 'E'), ('A', 'E'), ('C', 'B'), ('C', 'E')]
"A\nB\nC\nD\n" -> "A\nC\nB\nD\nA\nD\nB\nC\n"
```
The one from the show:
```
[("Amy","Hubert"),("Bender","Amy"),("Hubert","Turanga"),("Amy","Wash Bucket"),("Wash Bucket","Nikolai"),("Phillip","John"),("Hermes","Turanga")]
```
The show's solution, given below is invalid:
```
[("Clyde","Phillip"),("Ethan","John"),("Clyde","John"),("Ethan",Phillip"),("Clyde","Hubert"),("Ethan","Wash Bucket"),("Clyde","Leela"),("Ethan","Nikolai"),("Clyde","Hermes"),("Ethan","Bender"),("Clyde","Amy"),("Ethan","Hubert"),("Clyde","Wash Bucket")]
```
This is invalid because Ethan, and Clyde are unnecessary because of how little ~~Fry~~ Phillip, ~~Zoidberg~~ John and ~~Hermes~~ Hermes used the machine. A valid solution for this case is provided below:
```
[("Philip","Hubert"),("John","Wash Bucket"),("Philip","Turanga"),("John","Nikolai"),("Philip","Hermes"),("John","Bender"),("Philip","Amy"),("John","Hubert"),("Philip","Wash Bucket")]
```
Note that there are clearly many possible answers for any valid input. Any is valid.
[Answer]
# Python 3: 328 character (slow), 470 character (fast)
Probably a bit too long for a serious answer.
## Slow and short code:
```
from itertools import*
def d(u,s):i,j=map(u.index,s);u[i],u[j]=u[j],u[i]
def f(Q):
n=set()
for s in Q:n|=set(s)
n=list(n)
while 1:
for t in permutations(i for i in combinations(n,2)if not set((i,i[::-1]))&set(Q)):
u=n[:];j=0
for s in Q:d(u,s)
for s in t:
j+=1;d(u,s)
if n==u:return t[:j]
n+=[''.join(n)]
```
`d(u,s)` applies a swap `s` to `u`. In the main method `f(Q)`, I first generate the list of all persons `n` using set operations and converting the result back to a list. The `while 1`-loop is of course not a infinity loop. In it, I try too solve the problem using the persons I have in `n`. If it is not successful, I add another person by combining all names `n+=[''.join(n)]`. Therefore the `while 1`-loop is executed at most 3 times (see proof in the question).
The solving of the problem is done bruteforce. I generate all swaps that are legal and try all permutations `for t in permutations(i for i in combinations(n,2)if not set((i,i[::-1]))&set(Q))`. If each person is in it's own body, I return the sequence of swaps.
**Usage:**
```
print(f([('A','B'),('C','D')]))
print(f([('A','B')]))
print(f([('A','B'),('C','D'),('A','C'),('A','D')]))
```
The example from futurama takes way too long. There are 9 persons, so there are 36 possible swaps and 28 of them are legal. So there are 26! legal permutations.
## Faster code
```
def w(u,s):i,j=map(u.index,s);u[i],u[j]=u[j],u[i]
def f(Q):
n=set()
for s in Q:n|=set(s)
while 1:
n=list(n);u=n[:];l=len(n)
for s in Q:w(u,s)
for d in range((l*l-l)//2-len(Q)+1):r(n,u,Q,[],d)
n+=[''.join(n)]
def r(n,u,Q,t,d):
m=0;v=u[:];l=len(u)
for i in range(l):
if n[i]!=v[i]:m+=1;w(v,(n[i],v[i]))
if m<1:print(t);exit()
for i in range(l*l):
s=n[i//l],n[i%l]
if m<=d and i//l<i%l and not set([s,s[::-1]])&set(Q+t):v=u[:];w(v,s);r(n,v,Q,t+[s],d-1)
```
The function `f(Q)` has an iterative deepening approach. It first tries depth=0, then depth=1, until depth=(l\*l-l)//2-len(Q), which is the maximal number of legal moves. Like the slower code it then adds another person and tries again.
The recursive function `r(n,u,Q,t,d)` tries to solve the current position `u` with `d` swaps. `n` is the solved position, `Q` the input moves and `t` the moves already done. It first calculates an lower bound of swaps `m` needed (by solving the state with legal and illegal swaps). If `m` == 0, all persons are in the correct body, so it prints the solution `t`. Otherwise it tries all possible swaps `s`, if `m<d` (pruning), `d>1` (which is already included in `m<d`, `i//l<i%l` (don't allow swaps like `('A','A')` or `('A','B')` and `('B','A')`) and `not set([s,s[::-1]])&set(Q+t)` (`s` hasn't been performed yet).
**Usage:**
```
f([("Amy","Hubert"),("Bender","Amy"),("Hubert","Turanga"),("Amy","Wash Bucket"),("Wash Bucket","Nikolai"),("Philip","John"),("Hermes","Turanga")])
```
It finds the optimal swaps for the futurama problem in about 17 seconds on my laptop using pypy and about 2 minutes without pypy. Notice that both algorithms outputs different solutions, when calling it with the same parameter. This is because of the hashing algorithm of a python-`set`. `n` stores the person each time in a different order. Therefore the algorithm may be faster or slower each run.
Edit: The original futurama test case was wrong, the corrected test case has an optimal solution of 9 instead of 10, and is therefore faster. 2 seconds with pypy, 7 seconds without.
] |
[Question]
[
It is possible to compress some kinds of data, such as human text or source code, with straight-line grammars. You basically create a grammar whose language has exactly one word – the uncompressed data. In this task, you have to write a program that implements this method of data compession.
## Input
The input is a string of not more than 65535 bytes length. It is guaranteed, that the input matches the regular expression `[!-~]+` (i.e. at least one printable ASCII character excluding whitespace).
An example input is
>
> abcabcbcbcabcacacabcabab
>
>
>
## Output
The output is a set of rules that form a grammar that describes exactly one word (the input). Each nonterminal is denoted by a decimal number greater than 9. The start symbol is symbol number ten. An example output corresponding to the example input is given below; its syntax is described further below:
```
10=11 11 12 12 11 13 13 11 14 14
11=a 12
12=b c
13=a c
14=a b
```
Each rule has the form `<nonterminal>=<symbol> <symbol> ...` with an arbitrary whitespace-separated number of symbols on the right side. Each output that obeys the following restrictions and derives exactly the input string is valid.
# Restrictions
In order to stop people from doing strange things, a number of restrictions are taking place:
* Each nonterminal must appear at least twice on the right side of a rule. For instance, the following grammar for the input `abcabc` is illegal because rule 12 appears only once:
```
10=12
11=a b c
12=11 11
```
* No sequence of two adjacent symbols may appear more than once in all right-hand sides of all rules, except if they overlap. For instance, the following grammar for the input `abcabcbc` is illegal since the sequence `bc` appears twice:
```
10=11 11 b c
11=a b c
```
A valid grammar would be:
```
10=11 11 12
11=a 12
12=b c
```
* Your program must terminate in less than one minute for each valid input that is not longer than 65535 bytes.
* As usual, you may not use any facility of your language or any library function that makes the solution trivial or implements a large part of it.
## Sample input
Generate sample input with the following C program.
```
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
unsigned int i,j = 0,k;
if (argc != 3
|| 2 != sscanf(argv[1],"%u",&i)
+ sscanf(argv[2],"%u",&k)) {
fprintf(stderr,"Usage: %s seed length\n",argv[0]);
return EXIT_FAILURE;
}
srand(i);
while(j < k) {
i = rand() & 0x7f;
if (i > 34 && i != 127) j++, putchar(i);
}
return EXIT_SUCCESS;
}
```
The sample input generated by the program above will usually not result in good compression results. Consider using human text or source code as example input.
## Winning criteria
This is code golf; the program with the shortest source code wins. For extra credit, write a program that reconstructs the input from the output.
[Answer]
### GolfScript, 111 108 characters
```
1/{.}{:^1<{^1$/,2>.{;,)^<.0?)!}*}do-1<.,1>{^1$/[10):10]*0+\+}{;^}if(\}while][0]%.,,]zip{))9+`"="+\~" "*+}%n*
```
This is a quite clumsy approach using GolfScript. The second version performs much better than the initial one. It is much longer than the intended code but my implementation had nested do-loops and this caused issues with the interpreter.
Examples:
```
> abcba
10=a b c b a
> abcabcbc
10=11 11 12
11=a 12
12=b c
> abcabcbcbcabcacacabcabab
10=11 12 12 13 14 14 c 11 15
11=15 13
12=c b
13=14 b
14=c a
15=a b
```
] |
[Question]
[
[BLC (Binary Lambda Calculus)](https://tromp.github.io/cl/Binary_lambda_calculus.html) is a binary encoding of untyped [lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus) which was created to “provide a very simple and elegant concrete definition of descriptional complexity.”
What are some tips on how to golf down BLC programs/functions?
Please submit only one tip per answer!
[Answer]
This is fairly obvious but I'll put it here for completeness sake. It also applies to untyped lambda calculus in general so I'll write it like that for readability.
Anywhere you want reuse a value/function that is at least as long as this expression
$$(\lambda v.p) \space d$$
you can declare it as a variable. Here "p" is the original program with all the original instances of your repeated value replaced by "v". "d" is the definition of the repeated value itself.
**A contrived example**
A program like this
$$(\lambda f.\lambda z.f f f f f z) (\lambda f.\lambda z.f f f f f z)(\lambda f.\lambda z.f f f f f z)$$
can be written as
$$(\lambda v.vvv)(\lambda f.\lambda z.f f f f f z)$$
This is a simple example but it's a neat abstraction because "v" can be used however deeply nested you decide to make "p".
] |
[Question]
[
### The Monkey has swung home to find his tree all in pieces.
He likes order and scoops up all his 'tree-parts' and sets them out in `3` groups.
The Monkey's `3` nested lists:
```
STEP = [['S', '1', 'B', '3'], ['S', '3', 'B', '11'], ['S', '5', 'B', '12'], ['S', '4', 'B', '13'], ['S', '2', 'B', '14']]
TRANSITION = [['T', '2', 'B', '4'], ['T', '7', 'B', '4'], ['T', '3', 'S', '4'], ['T', '5', 'S', '5'], ['T', '1', 'S', '2'], ['T', '8', 'S', '2'], ['T', '6', 'S', '1'], ['T', '9', 'S', '2'], ['T', '4', 'S', '1'], ['T', '10', 'S', '1']]
BRANCH = [['B', '3', 'T', '1'], ['B', '3', 'T', '7'], ['B', '4', 'S', '3'], ['B', '11', 'T', '3'], ['B', '11', 'T', '5'], ['B', '12', 'T', '6'], ['B', '12', 'T', '8'], ['B', '13', 'T', '4'], ['B', '13', 'T', '9'], ['B', '14', 'T', '2'], ['B', '14', 'T', '10']]
```
Each element holds information as such:
```
# Example
STEP[0] = ['S', '1', 'B', '3']
```
*Where:*
* 'S' is the `STEP` type
* '1' is the `STEP` number id
* 'B' is the linked `BRANCH` type
* '3' is the linked `BRANCH` number id
Starting from a `STEP` the data is all linked, so using the linked reference you can find the next element and the next until another `STEP` is reached.
*This is some parameters of the data:*
* `STEPS` are connected to single `BRANCHES`
* `BRANCHES` are connected to one or more `TRANSITIONS`
* `TRANSITIONS` can be connected to a single `BRANCH` or `STEP`
The `BRANCH` data can have a fork where a single `BRANCH` id has one or more options for `TRANSITIONS`.
Re-create this monkey's tree (nested list format is fine) in the shortest way possible (he is not a fan of long instructions):
```
[S1]
|
B3|_________
| |
[T1] [T7]
| |
| B4|
| |
[S2] [S3]
```
And list all the routes on this tree:
```
Routes = [[S1, B3, T1, S2], [S1, B3, T7, B4, S3]]
```
UPDATE: This is Code-golf and from the data given you need to output the display of the tree ( This can be different from my example but requires the same elements to be displayed in any format) and as you cycle through the problem to output all the possible routes as a BONUS.
### Notes:
* This is a single-rooted tree
* You may use a different format for input but please explicitly state the input format in your solution
[Answer]
# [Java (JDK)](http://jdk.java.net/), 570 bytes
```
t->{return "Routes = "+Arrays.deepToString(Arrays.stream(r(t.get(0).get(0),t,t.get(0).get(0)).split("\\[")).filter(d->d.endsWith("]")).map(d->d.replaceAll("]", "")).map(d->d.split("(?=[A-Z])")).collect(Collectors.toList()).toArray());};String r(String s, List<List<String>>t, String b){List<String>o = t.stream().filter(e->e.get(0).equals(s)).map(e->e.get(1)).collect(Collectors.toList());if(s.matches("^S(?!(?:1)$)\\d+"))return s;if(o.size()>1){String x="";for(String n:o){x+="["+b+r(n,t,b+n)+"]";}return x;}if(o.size()==1)return s+r(o.get(0),t,b+o.get(0));return "]";}
```
As you may notice by my code I´m still learning a lot every day.
My answer is neighter pretty nor short and I honestly even hope this works for different testcases even though I tested a couple.
But I hope that this question gets the attention it deserves and there will be more answers I can learn from.
## INPUT
```
String[][] STEP = { { "S1", "B3" }, ... ,{ "B14", "T2" }, { "B14", "T10" } };
List<List<String>> tupels = Arrays.stream(STEP).map(Arrays::asList).collect(Collectors.toList());
z(tupels);
```
I converted your given Input into an 2D-Java-Array `String[][]` and converted that into a `List<List<String>>`.
## CODE
The first method calls a recursive method to get all routes and formats the output.
```
t->{
return "Routes ="+Arrays.deepToString(
Arrays.stream(r(t.get(0).get(0),t,t.get(0).get(0)).split("\\["))
.filter(d->d.endsWith("]")).map(d->d.replaceAll("]", ""))
.map(d->d.split("(?=[A-Z])")).collect(Collectors.toList()).toArray());
};
```
The second method is the recursive method which gathers all the possible routes
```
String r(String s, List<List<String>>t, String b){
List<String>o =t.stream().filter(e->e.get(0).equals(s)).map(e->e.get(1))
.collect(Collectors.toList());
if(s.matches("^S(?!(?:1)$)\\d+"))
return s;
if(o.size()>1){
String x="";
for(String n:o){
x+="["+b+r(n,t,b+n)+"]";
}
return x;
}
if(o.size()==1)
return s+r(o.get(0),t,b+o.get(0));
return "]";
}
```
[Try it online!](https://tio.run/##hVRtT9swEP7eX@FZ@2AvaUSgDGiWIpj4tqFpjTRpbSeliQtmbpzZLoNV@e2dX/JSAohWSvI857t77mzfXXqfDu/y3zu6LrlQ4E7jYKMoCz5Eg2ecVIKka2MaZCyVEnxNabEdAEALRcQqzQi4NhCAqRK0uAEZ@kKl@mQfjppMgMKRXlMN9OMaFCDeqeFkK4jaiALA73yjiAQxgN6FEOmjDHJCyoQ7b1RzTggSSAU3RKEDXL985fcYHMiSUYXgfD6DGq0o01JRPpzkASly@YOqWwQXxrROS8cLUjJdywVjxuID@MRax0Pn8exi@HOBjTHjjJFMoc/uzYUMFDdVI21U3KrWn1EV1Y0RqP6QPnjeIuU3DVzi7b6F68aopvq2GDKckKZq8meTMolkrbg1hW@ojOgKSe2islsiEfw1Refv0Pk4xO/xfJ57ush6h6RZyQNJ/xGEJyHe1kofYgijFW8LK8Ycbx@8GM6gt/QEKvTeLL0Ce7qlUVUHe4iqvWhxHLZZtAfvNnXpNQBHzUkxYXYAlJsloxmQKlX6dc9pDtb6VNYyZguQihuJ90/lbKHZaXL1TTdzq/9wGppNvjyCoPItPrI4DFvi2BGHLTFyROdy6IiRIWyu/Z9ekLgFo8YhOelhm3PaYZtSJ26w1ThtFSSnHX4x30drb0tIznr@o549PHhKXFpBSR@fvJbw0gVsO2La59u6esRxR9ieaKU94rQjXNJXu9osOOs8rIzksE/o8kAFqmhgw7w0lTYlYWbwPB0x5py4q@T48TiVxvGN2@SO26NUZB3oiRaUOotiBSrIXzs09eUtggy5pLgeiNXuPw "Java (JDK) – Try It Online")
] |
[Question]
[
In golf, a knowledgable caddie helps an already good golfer to be even better. In this challenge, you build a "caddie" to help you code golf. In particular, your caddie will compress golfed code in such a way that another program can uncompress and then run the code. A good caddie will compress golfed code to be much smaller than the original golfed code. In fact, in caddie-assisted Python (say), you might be able to golf on par with a Jelly golfer!
Formally, a **caddie** for a language L is a pair (E,D) of programs. The program E takes as input any code c in L and outputs a string s. The program D takes s as input along with any input x of c and returns the output of c(x). We do not require E and D to be written in L. You could say that E is a transpiler that converts c into a version s that runs in the language D. We are interested in transpilers E for which E(c) tends to be smaller than c, even when c is already golfed.
Write a caddie (E,D) for any language L of your choosing. When you first post a caddie here, its score is infinity. Use the following method to update your score:
* Let C denote the challenge in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") with at least 10 points that was posted first after your submission.
* Let c denote the shortest posted solution to C that is written in L.
* Your score is infinity unless C and c both exist, at which point your score is size(E(c))/size(c).
Recompute your score whenever either C or c changes. Lowest score wins.
[Answer]
# Python 3 Caddy, interprets BrainF\*\*\*
# Score: \$\frac{38}{224}\approx0.17\$ (with newlines removed)
## Program E
```
from textwrap import wrap
x = input('Code: ')
i = ['<', '>', '+', '-', '[', ']', '.', ',']
o = ''
for c in x:
if c in i:
o += str(i.index(c) + 1)
if o:
d = wrap(o, 6)
d = [int(x) for x in d]
o = ''
for c in d:
o += chr(int(c) + 128)
print('Compressed: ', o)
```
The way this works is by converting every instruction in the input to a digit, then concatenating those digits to a number. Then it splits that number into 6-digit groups and converts each to a Unicode character. (A number higher than 6 could be used, by that would cause errors for large programs). Then it outputs it.
## Program D
```
x = input('Compressed: ')
p = input('Input: ')
p = list(p)
d = ''
for c in x:
c = ord(c) - 128
d += str(c)
d = d.replace('-', '')
i = ['<', '>', '+', '-', '[', ']', '.', ',']
o = ''
for n in d:
n = int(n) - 1
o += i[n]
tape = [0] * 30000
head = 0
m = {}
m2 = {}
stack = []
for i in range(len(o)):
char = o[i]
if char == '[':
stack.append(i)
elif char == ']':
begin = stack.pop()
m[begin] = i + 1
m2[i] = begin
i = 0
while i < len(o):
char = o[i]
if char == '<':
head -= 1
i += 1
elif char == '>':
head += 1
i += 1
elif char == '+':
tape[head] += 1
i += 1
elif char == '-':
tape[head] -= 1
i += 1
elif char == '[':
if tape[head] == 0:
i = m[i]
else:
i += 1
elif char == ']':
if tape[head] != 0:
i = m2[i]
else:
i += 1
elif char == '.':
print(chr(tape[head]), end='')
i += 1
elif char == ',':
try:
tape[head] = ord(p.pop(0))
except:
tape[head] = 0
i += 1
```
This is pretty simple, it just reverses the compression algorithm and evaluates the result.
] |
[Question]
[
Write a program or function that takes input: all resistors available and a resistance value and outputs a truthy value of whether or not it is possible to get the resistance by using those resistors.
**Rules:**
Any format for input will do.
There will be at least 1 available resistor and your program should output for at least 10 available resistors.
Resistance of all available resistors and the required resistance will be positive integers.
For available resistors if a fractional value is also possible, the required resistance may be the approximated value.(See example)
Output should be any 2 unique values for Possible and Not possible.
The resistors may be connected in any manner.
*Series* Resistance:
For n resistances in series: Result=R1+R2+R3+....Rn
*Parallel* Resistance:
For n resistances in parallel: Result=1/(1/R1+1/R2+1/R3+....+1/Rn)
The circuit may not require all the resistors to get the required resistance (output True if that is the case).
**Winner:**
This is code-golf so shortest-code wins.
**Examples:**
```
R List
110 220,220 -> True
440 220,220 -> True
550 400,300 -> False
3000 1000,3000 -> True
750 1000,3000 -> True
333 1000,1000,1000 -> True (1000||1000||1000=333.333)
667 1000,1000,1000 -> True ((1000+1000)||1000=666.6666)
8000 1000,1000,7000 -> True
190 100,200,333,344,221 -> True
193 105,200,333,344,221 -> True
400 200,100 -> False
```
Explanation for the last two examples: <https://physics.stackexchange.com/questions/22252/resistor-circuit-that-isnt-parallel-or-series>
[Answer]
# [Python 3](https://docs.python.org/3/), 253 bytes
```
import functools
def p(l): return functools.reduce(lambda z,x:z+[y+[x]for y in z],l,[[]])
print(l[-1:][0]in[round(a)for a in[sum(a)for a in p([sum(a)for a in p(l)]+[1/sum(c)for c in[[1/b for b in a if b!=0]for a in p(l).copy()]if sum(c)!=0])]])
```
I take the powerset of all resistor values and then calculate the sums for series and 1/sum(1/values) for paralel and then I take a powerset of these two sets. When you take the sum of all the subsets and put them into a set then this set eiter contains the value or not. -> return True/False
@stephen thanks :)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 52 bytes
```
à má
ÈÊ<2?X:X¯1 ïXÅgW @[X+Y1/(1/XÄ/Y]Ãc
mmW c mr øV
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=4CBt4QoKyMo8Mj9YOlivMSDvWMVnVyBAW1grWTEvKDEvWMQvWV3DYwptbVcgYyBtciD4Vg==&input=WzEwMCwyMDAsMzMzLDM0NCwyMjFdCjE5MAotUQ==)
This was a tough one, and I had to do a couple of strange things to make it work. I can't mathematically prove that this works for everything, but it works for all the test cases as well as my extra [proposed test case](https://ethproductions.github.io/japt/?v=1.4.6&code=4CBt4QoKyMo8Mj9YOlivMSDvWMVnVyBAW1grWTEvKDEvWMQvWV3DYwptbVcgYyBtciD4Vg==&input=WzEwLDIwMF0KNDAwCi1R). Specifically, I know that the function I define called `W` gives different results depending on the order of the resistors in its input so I run it on each possible ordering of each possible combination of resistors. I also know that it will produce a list of resistances that are all possible to create using the input resistors. I don't know with 100% certainty that those two things together end up with every possible resistance.
Explanation:
```
à Get each combination e.g. [1,2,3] -> [[1,2,3],[1,2],[1,3],[2,3],[1],[2],[3]]
m For each combination...
á Get each order e.g. [1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Skip a line to avoid overwriting the target resistance
È Define a function W taking an array input X:
Ê<2?X If X is only 1 resistor, return it as-is
XÅgW Get the resistances from applying W to the tail of X
X¯1 ï Pair the first resistor with each possible tail resistance
@[ ]Ã For each pair get these two values:
X+Y Those resistances in series
1/(1/XÄ/Y Those resistances in parallel
c Collapse all those resistances into a single flat list
mmW For each combination and order, get the resistances using W
c Collapse to a single list of resistances
mr Round each one
øV Return true if the target resistance is in the list, false otherwise
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 153 bytes
```
f=->v,r{[r]-v==[]||r[1]&&[*2..v.size].any?{|n|v.permutation.any?{|l|[l[0,n].sum,(1.0/l[0,n].reduce(0){|s,x|s+1.0/x}).round].any?{|b|f[l[n..-1]+[b],r]}}}}
```
[Try it online!](https://tio.run/##hY7bCsIwDIbvfQqvxEMW23U6vZg@SMiF0w0GWqWzQ1199lmPMEQs5Id8X0libHpumjwJFhWYmgwHVZIQO2dIcq9HwxCxwrK4ZIwrfV7WTrsKD5nZ2ePqWOz1i24dbUmAZiztDvoSxfjVm2xj11lfDGpXwsmVo7s7XQdo9lZv3lNTl/sBGjGQPKKUwfDVv@bQzYnCUIAvBikFd9ooit5ICiFA@eBnftF40oKf8P@V@mGm0/jLxA8za@2A8L5GKVBR5A@T/tb5H624uQE "Ruby – Try It Online")
Brute force. I mean it.
] |
[Question]
[
Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
[Wikipedia for more information](https://en.wikipedia.org/wiki/Knapsack_problem)
For example you can be given a max weight of 15 and objects with value/masses as `[5,2], [7,4] [1,1]` and you would output `[7,0,1]` which is 7 `[5 <value>, 2 <mass>]` objects and 1 `[1 <value>, 1 <mass>]` object for a score of 36.
# Rules
Input can be taken in any reasonable format
Output is also flexible format,
You may not use libraries that are non-standard. If you have to *install* or *download* any library to use it separate from the initial setup then it is ***not*** allowed
Objects may have negative mass and value (i.e -1,-1)
Optimal answers required
# Winning
Shortest code wins
# Negative mass and value?
This is a key part of this challenge. Lets say you have a object with items (mass, value) such as `[4,3],[-1,-1]` and a bag with capacity of 15. You could put 3 of the first ones and score 9 or put 4 of the first ones and one of the -1,-1 object for a score of 11.
[Answer]
# Pyth, 18 bytes
```
h.MshMZfghQseMTy*F
```
Outputs as a list of [value, weight] pairs. Horrendously inefficient, but it *is* NP-complete.
[Try it here](http://pyth.herokuapp.com/?code=h.MshMZfghQseMTy%2AF&input=5%2C%20%5B%5B4%2C3%5D%2C%20%5B-1%2C-1%5D%5D&debug=0)
### Explanation
```
h.MshMZfghQseMTy*F
y*FQ Get all sets with up to <capacity> of each item.
fghQseMT Choose the sets whose total weight fits in the bag.
.MshMZ Choose those with the highest value.
h Take the first.
```
] |
[Question]
[
# Introduction
Ever heard of [Remind?](https://www.remind.com/) No? Neither did I until about 2 years ago. Basic premise of it is for teachers to send out reminders and communicate with their students. Pretty neat, right? It even allows you send emotes and react to messages! Which I do on a daily basis.
But, one thing about Remind is that the teachers always send the "Do your homework!" "If you don't, you'll get an F!". But, there is useful stuff too, like "Test on Tuesday", or the occasional "Have a good day!". I almost always reply happy with a thumbs up, but sometimes, I have to put a thumbs down.
# Challenge
Your task today is to find out if a message has a certain connotation to it. If it has a positive connotation to it, reply with a thumbs up. If it has a negative connotation, reply with a thumbs down.
# How am I supposed to detect connotations?
A positive connotation will normally have 3 words in it. The 3 words are: **Happy, Good, and Passed**.
A negative connotation will have 3 also. Those 3: **Test, Fail, and Homework**.
# What am I testing for?
You are testing to see if a message contains positive, negative or **both** connotations.
If a message has positive connotations to it, go ahead and return the unicode *code point* for thumbs up (U+1F44D).
If it has negative connotations to it, return the unicode code point for thumbs down (U+1F44E).
If the message has both negative and positive connotations, return the code point for a neutral face (U+1F610).
If, for some other reason, it doesn't have either connotations, return a nice ol' shrug (¯\\_(ツ)\_/¯). If the shrug doesn't show up right, [here's the Emojipedia link to the shrug](https://emojipedia.org/shrug/)
# Constraints
* Program must take a message as input.
* Positive connotations must return thumbs up code point (U+1F44D)
* Negative connotations must return thumbs down code point (U+1F44E).
* If the message has both connotations, return the neutral face code point (U+1F610).
* If the message has neither connotations, return the shrug (¯\\_(ツ)\_/¯).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), Shortest bytes win
# Test cases.
```
Input -> Output
Happy Good Friday! -> U+1F44D
Congrats, you just played yourself -> ¯\_(ツ)_/¯
You failed the test. -> U+1F44E
Good job on the test. -> U+1F610
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~182~~ ~~166~~ ~~159~~ 151 bytes
```
c=input().lower().count
print((["¬Ø\_(„ÉÑ)_/¬Ø"]+list("üëçüëéüòê"))[any(map(c,["good","happy","passed"]))+any(map(c,["fail","test","homework"]))*2])
```
[Try it online!](https://tio.run/##TcwxDoIwFMbx3VOYt9AnRBOdPQkSUqGBRulr2hLCrKtGNzeOwB24ihfgBpVuDl/@yy@f7l1N6uB9cZRKt47h9kqdMEsLapVbaSOVYyyFaTzl7Hu7Y76bRsjiq7SOwTy8H8ue8/B5AWLKVc8arlmRpFARlZBAzbXul2purSghQ4z/1ZkH5IR1wVIjOjKXoDb7DL2Pwsu6IaOkqqIf "Python 3 – Try It Online")
[Answer]
# JavaScript, UTF-8 encoded, 100 bytes
```
s=>['¬Ø\_(„ÉÑ)_/¬Ø',...'üëéüëçüòê'][2*/happy|good|passed/i.test(s)+/test|fail|homework/i.test(s)]
```
Test cases:
```
const a =
s=>['¬Ø\_(„ÉÑ)_/¬Ø',...'üëéüëçüòê'][2*/happy|good|passed/i.test(s)+/test|fail|homework/i.test(s)]
console.log(a('Happy Good Friday!'));
console.log(a('Congrats, you just played yourself'));
console.log(a('You failed the test.'));
console.log(a('Good job on the test.'));
```
[Answer]
## Powershell, 190 bytes
```
"$($s=Read-host;"$s ->";$1=("Test","Fail","Homework"|?{$s-match$_});$2=("Happy","Good","Passed"|?{$s-match$_});if($1-and$2){"üòê"}elseif($1){"üëé"}elseif($2){"üëç"}else{"¬Ø\_(„ÉÑ)_/¬Ø"})"
```
Displays the input and output next to eachother.
Happy Good Friday! -> üëç
Congrats, you just played yourself -> ¯\\_(ツ)\_/¯
You failed the test. -> üëé
Good job on the test. -> üòê
[Answer]
## PowerShell, 187 bytes
```
read-host|%{$s=$_;$f=0;0..5|?{$s.indexof((-split'Happy Good Passed Test Fail Homework')[$_],0,$s.length,3)+1}|%{$f=$f-bor(1,2)[$_/3]};$s+' -> '+('¬Ø\_(„ÉÑ)_/¬Ø','üëç','üëé','üòê')[$f]}
```
] |
[Question]
[
>
> (Note: although related, this challenge is not a duplicate of [this one](https://codegolf.stackexchange.com/questions/52452/leap-for-leap-seconds) because it requires determining leap seconds automatically rather than hardcoding their times, and is not a duplicate of [this one](https://codegolf.stackexchange.com/questions/65020/output-the-current-time) because most of the difficulty comes from determining the time without leap second skewing, something that most time APIs don't do by default. As such, a solution is likely to look different from a solution to either of those challenges.)
>
>
>
We're coming to the end of 2016, but it's going to take slightly longer than most people expect. So here's a challenge celebrating our extra second this year.
Output the current time in UTC, as hours, minutes, seconds. (For example, legitimate output formats for midday would include `12:00:00` and `[12,0,0]`; the formatting isn't massively important here.)
However, there's a twist: your program must handle [leap seconds](https://en.wikipedia.org/wiki/Leap_second) appropriately, both past and future. This means that your program will have to obtain a list of leap seconds from some online or automatically updated/updatable source. You may connect to the Internet to obtain this if you wish. However, you may only connect to a URL that predates this challenge (i.e. no downloading parts of your program from elsewhere), and you may not use the connection to determine the current time (specifically: your program must function even if any attempt to access the Internet returns a page that's up to 24 hours stale).
Most operating systems' default APIs for the current time will skew time around leap seconds in order to hide them from programs that might otherwise be confused. As such, the main difficulty of this challenge is to find a method or an API to undo that, and work out the true unmodified current time in UTC.
In theory, your program should be perfectly accurate if it ran on an infinitely fast computer, and must not intentionally take more than zero time to run. (Of course, in practice, your program will run on an imperfect computer, and so will probably not run instantaneously. You don't have to worry about this invalidating the results, but must not depend on it for the correctness of your program.)
Your program must function regardless of which timezone the system clock is set to. (However, it may request information from the operating system or environment as to what timezone is being used, and may assume that the reply is accurate.)
As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins. Good luck!
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 161 bytes
```
(('{0:H:m:s}','23:59:60')[(($d=[datetime]::UtcNow).Ticks-6114960*98e9)/1e8-in((irm ietf.org/timezones/data/leap-seconds.list)-split'[^@] |
'-match'^\d{9}')])-f$d
```
[Try it online!](https://tio.run/nexus/powershell#FczBCsIgAADQc31Fh4FaOW2xMYWgY6dOdVobiLqSdI4pBK19@6oPeG@GEIyUn7jjYQJbkO15znhBAaogTNShUiLqaJyuOb9GefYvtMkZy4qClnSNd5pZlF6MfAay0yU2HYRmcCujY5v64U7@9O07HcgvEsRq0eOgpe9USK0JEeHQWxNB1RzrxWcJsBNRPkBzUyObAKoRbhM1z18 "PowerShell – TIO Nexus") (doesn't work here, it seems that TIO doesn't recognize `irm` and `iwr`, maybe it's a security feature?)
### Logic Test (Hardcoded Date):
```
(('{0:H:m:s}','23:59:60')[(($d=[datetime]'1/1/2017 00:00:00').Ticks-6114960*98e9)/1e8-in((irm ietf.org/timezones/data/leap-seconds.list)-split'[^@] |
'-match'^\d{9}')])-f$d
```
### Notes
There is a literal `TAB` and a literal linebreak (`0xA`) in the regex string, so that I didn't have to escape them (saved 1 byte each).
### Explanation
The times given (of the leap seconds) in the ietf file are in seconds since NTP epoch which is `1/1/1900 00:00:00`. On Windows, a "tick" is simply one ten-millionth of a second (10,000,000 ticks/sec).
If you add an integer to a `[datetime]` it counts the integer value as ticks, so I'm using the hardcoded tick value of NTP epoch, then subtracting it from the tick value of the current UTC time (the original value of which is simultaneously being assigned to `$d`).
To make that hardcoded tick value smaller, I took away some zeros (9 of them) and divided by 98, then multiply by `98e9` (98\*109).
The result of that subtraction is the value in ticks since NTP epoch. That gets divided by `1e8` (not `1e9`, for reasons that will be clear in a moment) to get the value in seconds (sort of) since NTP epoch. It will be smaller by a factor of 10, actually.
Retrieving the document from the IETF, rather than split it into lines first, then process the lines with the timestamps, I decided to split on both line breaks and on `TAB` characters, since that's what comes after the timestamp. Because of a single errant line in the file, that alone would include an additional timestamp we don't want. The line looks like this:
```
#@ 3707596800
```
So I changed the regex to split on `[^@]\t` (any character that's not `@` followed by a `TAB`) which works to exclude that line, but also ends up consuming the last `0` in each of the timestamps.
That's why I divide by `1e8` and not `1e9`, to account for the missing `0`.
The current timestamp is checked to see it exists inside the list of neutered leap second timestamps. This whole process I described is inside the array accessor `[]`, so the resulting `[bool]` value gets coalesced to a `0` (`$false`) or `1` (`$true`). The array we're indexing into contains two elements: a format string for displaying the time, and a hardcoded `23:59:60`. The truthiness of the aforementioned comparison determines which one will be chosen, and that is fed into the format operator `-f` with the previously assigned current date `$d` as its parameter.
] |
[Question]
[
A [prime knot](https://en.wikipedia.org/wiki/Prime_knot) is:
>
> a non-trivial knot which cannot be written as the knot sum of two non-trivial knots.
>
>
>
Explanation of a [knot-sum](https://en.wikipedia.org/wiki/Connected_sum#Connected_sum_of_knots): put the two knots adjacent,
[](https://i.stack.imgur.com/qEWjx.png)
... then draw two lines between them, to the same strand on each side, and remove the part between the lines you just drew. This composition of two knots will form a new, non-prime knot.
[](https://i.stack.imgur.com/x1M2u.png)
Here are all prime knots with 7 or fewer crossings (the Unknot is not prime):
[](https://i.stack.imgur.com/MfRnu.png)
You need to output the number of unique prime knots for a given number of crossings.
```
1 0
2 0
3 1
4 1
5 2
6 3
7 7
8 21
9 49
10 165
11 552
12 2176
13 9988
14 46972
15 253293
16 1388705
```
I don't think the values are known for inputs larger than `16`, but if given such an input, your code would need to find the correct result given enough time.
[OEIS - A002863](http://oeis.org/A002863)
[Answer]
# Mathematica + [KnotTheory`](http://katlas.org/wiki/Setup), 13 bytes
```
NumberOfKnots
```
I didn't know this built-in function existed when I commented that the package might be useful. Everyone else had an equal chance to find it, since I commented about the library. I found it in the list of [Lightly Documented Features](http://katlas.org/wiki/Lightly_Documented_Features). Still, I won't accept this answer, since I want to see answers by other people.
] |
[Question]
[
# Background
This question is similar to [this one](https://codegolf.stackexchange.com/questions/55823/its-super-effective). I have provided all of the information needed below. If you are familiar with the other challenge then note that we are ranking all defenses instead of seeing the effectiveness of a single attack. This is important because it means that the tables are inverses of each other and the goal of this challenge is to be without user input.
In Pokemon there are 18 types:
```
Normal Fighting Flying Poison Ground Rock
Bug Ghost Steel Fire Water Grass
Electric Psychic Ice Dragon Dark Fairy
```
Pokemon have either one or two **unique** types that define them (a "type combination"). For example, a Bulbasaur has the type combination Grass/Poison (it has two types, Grass and Poison) and a Charmander has the type combination Fire (having just one type). The order of types does not matter (i.e. Grass/Poison is the same as Poison/Grass).
These types all have strengths and weaknesses:
* A type can be weak to another type. Fire is weak against Water. This results in Fire having a 2× multiplier against Water.
* A type can be resistant to another type. Water is resistant to Water. This results in Water having a 0.5× multiplier against Water.
* A type can be immune to another type. Flying is immune to Ground. This results in Flying having a 0× multiplier against Ground.
Anything else receives a standard 1× multiplier. Normal against Normal would result in a 1× multiplier is an example of this. These strengths and weaknesses can be compounded or negated as well. For example, Fire is weak to Water but a Fire/Water dual type would have a 1× multiplier against Water since the weakness from Fire would negate the resistance from Water. For a full table and a further explanation, see below.
# Objective
The goal here is to output a list of all types combinations, sorted in the order of their defensive ability, and listing their numbers of (resistances+immunities), weaknesses, and the ratio between those. Specifically, the sort order is as follows: type combinations with the best *ratio* of (resistances+immunities) to weaknesses are listed first, and if there is a tie, type combinations with the *most resistances and immunities* will win the tiebreak. You can produce this list via any means (an obvious method is to do a type effectiveness calculation against each type combination, but you are allowed to store precalculated or partially precalculated output in your program if doing so would make it shorter.)
# Type effectiveness table
For a human readable table, see [the Pokemon database.](http://pokemondb.net/type/) **Note: the columns of this list are what we are considering.** But just in case, here is the table I'm thinking of in a compressed computer-friendly matrix of effectiveness. I've multiplied every value by 2 so we don't have to deal with pesky decimals:
```
Attacking type
(same order)
Nor 222222422222202222
Fir 214211224221422211
D Wat 211441222222222212
e Ele 222122224122222212
f Gra 241114241424222222
e Ice 242221422222422242
n Fig 222222222441122124
d Poi 222212114241222221
i Gro 224044212222122222
n Fly 222414120221422222
g Psy 222222122214242422
Bug 242212121422422222
T Roc 114242414122222242
y Gho 022222012221242422
p Dra 211114222222224224
e Dar 222222422204212124
Ste 142211404111121211
Fai 222222142221220142
```
# Example
If this problem had requested only output for single-type type combinations, then a valid output would look like this:
```
Steel -> 11/3 = 3.66
Electric -> 3/1 = 3
Poison -> 5/2 = 2.5
Fire -> 6/3 = 2
Water -> 4/2 = 2
Ghost -> 4/2 = 2
Fairy -> 4/2 = 2
Fly -> 4/3 = 1.333
Dragon -> 4/3 = 1.333
Fighting -> 3/3 = 1
Normal -> 1/1 = 1
Ground -> 3/3 = 1
Psychic -> 2/2 = 1
Bug -> 3/3 = 1
Dark -> 3/3 = 1
Grass -> 4/5 = 0.8
Rock -> 4/5 = 0.8
Ice -> 1/4 = 0.25
```
However, your program will also need to list all of the dual-type combinations in the output, so its output will be considerably longer.
Best of luck! Shortest code in bytes wins.
[Answer]
## Python 2, 784 bytes
```
i=['Normal','222222422222202222'],['Fire','214211224221422211'],['Water','211441222222222212'],['Electric','222122224122222212'],['Grass','241114241424222222'],['Ice','242221422222422242'],['Fighting','222222222441122124'],['Poison','222212114241222221'],['Ground','224044212222122222'],['Flying','222414120221422222'],['Psychic','222222122214242422'],['Bug','242212121422422222'],['Rock','114242414122222242'],['Ghost','022222012221242422'],['Dragon','211114222222224224'],['Dark','222222422204212124'],['Steel','142211404111121211'],['Fairy','222222142221220142']
L=[]
for x,X in i:
for y,Y in i[i.index([x,X]):]:
S=W=0.
for a,b in zip(X,Y):A=int(a)*int(b);W+=A>4;S+=A<4
L+=[([x+'/'+y,x][x==y]+' -> %d/%d'%(S,W),S/W)]
for l in sorted(L, key=lambda l:-l[1]):print'%s = %.2f'%l
```
Outputs:
```
Bug/Steel -> 9/1 = 9.00
Steel/Fairy -> 11/2 = 5.50
Normal/Ghost -> 5/1 = 5.00
Water/Ground -> 5/1 = 5.00
Grass/Steel -> 10/2 = 5.00
Poison/Dark -> 5/1 = 5.00
Poison/Steel -> 10/2 = 5.00
Flying/Steel -> 10/2 = 5.00
Dragon/Steel -> 10/2 = 5.00
Normal/Steel -> 12/3 = 4.00
Electric/Poison -> 8/2 = 4.00
Electric/Steel -> 12/3 = 4.00
Ghost/Dark -> 4/1 = 4.00
Water/Steel -> 11/3 = 3.67
Dark/Steel -> 11/3 = 3.67
Steel -> 11/3 = 3.67
Fire/Steel -> 10/3 = 3.33
Fire/Ground -> 6/2 = 3.00
Water/Flying -> 6/2 = 3.00
Electric -> 3/1 = 3.00
Electric/Flying -> 6/2 = 3.00
Electric/Fairy -> 6/2 = 3.00
Ice/Steel -> 9/3 = 3.00
Fighting/Steel -> 9/3 = 3.00
Rock/Steel -> 9/3 = 3.00
Ghost/Steel -> 12/4 = 3.00
Fire/Electric -> 8/3 = 2.67
Water/Poison -> 8/3 = 2.67
Normal/Poison -> 5/2 = 2.50
Water/Electric -> 5/2 = 2.50
Poison -> 5/2 = 2.50
Ground/Flying -> 5/2 = 2.50
Ground/Steel -> 10/4 = 2.50
Psychic/Steel -> 10/4 = 2.50
Fire/Flying -> 7/3 = 2.33
Water/Fairy -> 7/3 = 2.33
Electric/Ghost -> 7/3 = 2.33
Normal/Electric -> 4/2 = 2.00
Normal/Fairy -> 4/2 = 2.00
Fire -> 6/3 = 2.00
Fire/Poison -> 8/4 = 2.00
Fire/Bug -> 6/3 = 2.00
Fire/Fairy -> 8/4 = 2.00
Water -> 4/2 = 2.00
Water/Ghost -> 8/4 = 2.00
Electric/Bug -> 4/2 = 2.00
Fighting/Poison -> 6/3 = 2.00
Poison/Fairy -> 6/3 = 2.00
Psychic/Ghost -> 4/2 = 2.00
Ghost -> 4/2 = 2.00
Ghost/Fairy -> 4/2 = 2.00
Dragon/Fairy -> 8/4 = 2.00
Fairy -> 4/2 = 2.00
Fire/Ghost -> 9/5 = 1.80
Normal/Fire -> 7/4 = 1.75
Fire/Rock -> 7/4 = 1.75
Fire/Dark -> 7/4 = 1.75
Poison/Dragon -> 7/4 = 1.75
Normal/Water -> 5/3 = 1.67
Fire/Water -> 5/3 = 1.67
Fire/Dragon -> 5/3 = 1.67
Water/Bug -> 5/3 = 1.67
Electric/Fighting -> 5/3 = 1.67
Ghost/Dragon -> 8/5 = 1.60
Fire/Fighting -> 6/4 = 1.50
Water/Dragon -> 3/2 = 1.50
Electric/Dragon -> 6/4 = 1.50
Electric/Dark -> 6/4 = 1.50
Poison/Ground -> 6/4 = 1.50
Poison/Flying -> 6/4 = 1.50
Poison/Rock -> 6/4 = 1.50
Poison/Ghost -> 6/4 = 1.50
Ground/Fairy -> 6/4 = 1.50
Flying/Dragon -> 6/4 = 1.50
Rock/Fairy -> 6/4 = 1.50
Fire/Psychic -> 7/5 = 1.40
Water/Fighting -> 7/5 = 1.40
Water/Dark -> 7/5 = 1.40
Grass/Fairy -> 7/5 = 1.40
Fighting/Dragon -> 7/5 = 1.40
Dragon/Dark -> 7/5 = 1.40
Normal/Flying -> 4/3 = 1.33
Fire/Grass -> 4/3 = 1.33
Fighting/Dark -> 4/3 = 1.33
Poison/Psychic -> 4/3 = 1.33
Ground/Dragon -> 4/3 = 1.33
Flying -> 4/3 = 1.33
Dragon -> 4/3 = 1.33
Dark/Fairy -> 4/3 = 1.33
Normal/Dragon -> 5/4 = 1.25
Water/Rock -> 5/4 = 1.25
Electric/Ground -> 5/4 = 1.25
Electric/Psychic -> 5/4 = 1.25
Electric/Rock -> 5/4 = 1.25
Grass/Poison -> 5/4 = 1.25
Fighting/Bug -> 5/4 = 1.25
Fighting/Ghost -> 5/4 = 1.25
Poison/Bug -> 5/4 = 1.25
Flying/Dark -> 5/4 = 1.25
Water/Psychic -> 6/5 = 1.20
Grass/Ghost -> 6/5 = 1.20
Ground/Ghost -> 6/5 = 1.20
Flying/Rock -> 6/5 = 1.20
Flying/Ghost -> 6/5 = 1.20
Flying/Fairy -> 6/5 = 1.20
Bug/Ghost -> 6/5 = 1.20
Bug/Fairy -> 6/5 = 1.20
Normal -> 1/1 = 1.00
Normal/Fighting -> 4/4 = 1.00
Normal/Ground -> 4/4 = 1.00
Normal/Psychic -> 2/2 = 1.00
Normal/Bug -> 3/3 = 1.00
Normal/Rock -> 5/5 = 1.00
Normal/Dark -> 3/3 = 1.00
Fire/Ice -> 4/4 = 1.00
Water/Grass -> 3/3 = 1.00
Electric/Grass -> 4/4 = 1.00
Grass/Fighting -> 6/6 = 1.00
Grass/Dark -> 7/7 = 1.00
Ice/Poison -> 5/5 = 1.00
Ice/Ghost -> 5/5 = 1.00
Ice/Fairy -> 4/4 = 1.00
Fighting -> 3/3 = 1.00
Fighting/Flying -> 5/5 = 1.00
Fighting/Fairy -> 5/5 = 1.00
Ground -> 3/3 = 1.00
Ground/Bug -> 4/4 = 1.00
Ground/Rock -> 6/6 = 1.00
Ground/Dark -> 6/6 = 1.00
Psychic/Dragon -> 6/6 = 1.00
Psychic/Fairy -> 3/3 = 1.00
Bug -> 3/3 = 1.00
Bug/Dragon -> 5/5 = 1.00
Bug/Dark -> 5/5 = 1.00
Rock/Ghost -> 6/6 = 1.00
Rock/Dark -> 7/7 = 1.00
Dark -> 3/3 = 1.00
Grass/Psychic -> 6/7 = 0.86
Fighting/Rock -> 6/7 = 0.86
Normal/Grass -> 5/6 = 0.83
Grass/Bug -> 5/6 = 0.83
Fighting/Ground -> 5/6 = 0.83
Ground/Psychic -> 5/6 = 0.83
Rock/Dragon -> 5/6 = 0.83
Grass -> 4/5 = 0.80
Grass/Flying -> 4/5 = 0.80
Flying/Psychic -> 4/5 = 0.80
Flying/Bug -> 4/5 = 0.80
Rock -> 4/5 = 0.80
Electric/Ice -> 3/4 = 0.75
Grass/Ground -> 3/4 = 0.75
Ice/Flying -> 3/4 = 0.75
Ice/Bug -> 3/4 = 0.75
Psychic/Rock -> 5/7 = 0.71
Grass/Dragon -> 4/6 = 0.67
Ice/Rock -> 4/6 = 0.67
Ice/Dark -> 4/6 = 0.67
Fighting/Psychic -> 2/3 = 0.67
Psychic -> 2/3 = 0.67
Psychic/Bug -> 4/6 = 0.67
Bug/Rock -> 2/3 = 0.67
Ice/Dragon -> 3/5 = 0.60
Grass/Ice -> 4/7 = 0.57
Normal/Ice -> 2/4 = 0.50
Water/Ice -> 2/4 = 0.50
Grass/Rock -> 2/4 = 0.50
Ice/Fighting -> 3/6 = 0.50
Psychic/Dark -> 1/2 = 0.50
Ice/Ground -> 2/5 = 0.40
Ice/Psychic -> 2/6 = 0.33
Ice -> 1/4 = 0.25
```
] |
[Question]
[
## Crash Course on DST
[Dempster–Shafer theory (DST)](https://en.wikipedia.org/wiki/Dempster%E2%80%93Shafer_theory) provides a method to combine various sources of evidence to form a belief. Given a list of possible statement (one of which is the true answer), each possible *combination* of statements is assigned a "mass" indicating the degree of supporting evidence. The total mass of all combinations is always equal to 1.
From these mass assignments, we can create a reasonable lower bound (belief) and upper bound (plausibility) on the truth of that combination. The belief `bel(X)` of any set X is the sum of the masses of all of X's subsets (including itself). The plausibility `pl(X)` of any set X is "1 - the sum of the masses of all sets disjoint to X". The diagram below illustrates how belief and plausibility are related to uncertainty.
[](https://i.stack.imgur.com/wkT3E.png)
For example, let's say that there is a traffic light that could be one of either `G`reen, `Y`ellow, or `R`ed. The list of options and a possible mass assignment is shown below:
```
binary interpretation m(X) bel(X) pl(x)
000 null 0 0 0
001 R 0.2 0.2 0.7
010 Y 0.1 0.1 0.3
011 Y||R 0.05 0.35 0.8
100 G 0.2 0.2 0.65
101 G||R 0.3 0.7 0.9
110 G||Y 0 0.3 0.8
111 G||Y||R 0.15 1 1
```
These masses can be notated by an array `[0, 0.2, 0.1, 0.05, 0.2, 0.3, 0, 0.15]`.
Now the question is, how do we decide what the masses are? Let's say that we had a sensor looking at the light, and this sensor indicates that the light *not green*; however, we know that there's a 20% chance that the sensor sent a random, spurious signal. This piece of evidence can be described by the mass distribution `[0, 0, 0, 0.8, 0, 0, 0, 0.2]` where {Y,R} has a mass of 0.8 and {G,Y,R} has a mass of 0.2.
Similarly, let's say that some second sensor indicates that the light is *not red*, but we also know that there's a 30% chance the sensor is wrong and the light is actually red. This piece of evidence can be describe by `[0, 0.3, 0, 0, 0, 0, 0.7, 0]` where {G,Y} has a mass of 0.7 and {R} has a mass of 0.3.
To assimilate these two pieces of evidence to form a single mass distribution, we can use Dempster's Rule of Combination.
## Dempster's Rule of Combination
Two mass assignment `m1` and `m2` can be combined to form `m1,2` using the following formulas, where `A`, `B` and `C` represent possible combinations (rows of the table above).
[](https://i.stack.imgur.com/pp9PH.png)
[](https://i.stack.imgur.com/BcEwx.png)
where K is a measure of "conflict," used for renormalization, and is calculated by:
[](https://i.stack.imgur.com/iSSgc.png)
It is also possible to describe this process geometrically, as in the image below. If `A = 011` (Yellow or Red) and `B = 101` (Green or Red), then the value of `m1(A) * m2(B)` *contributes to* (is added to) the value of `m1,2(001)` (Red). This process is repeated for all possible combinations of A and B where `A&B != 0`. Finally, the array is renormalized so that the values add up to a total of 1.
[](https://i.stack.imgur.com/2ZUAI.png)
Here is a simple Java method that combines two arrays following Dempster's rule:
```
public static double[] combine(double[] a, double[] b) {
double[] res = new double[a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
res[i & j] += a[i] * b[j];
}
}
for (int i = 1; i < res.length; i++) {
res[i] /= 1 - res[0];
}
res[0] = 0;
return res;
}
```
To see how this works in practice, consider the traffic light sensors above, which independently give the masses `[0, 0, 0, 0.8, 0, 0, 0, 0.2]` and `[0, 0.3, 0, 0, 0, 0, 0.7, 0]`. After performing Dempster's rule, the resulting *joint mass* is `[0, 0.3, 0.56, 0, 0, 0, 0.14, 0]`. The majority of mass is assigned to "Yellow", which makes intuitive sense given that the two sensors returned "not green" and "not red" respectively. The other two masses (0.3 for "Red" and 0.14 for "Green or Yellow") are due to the uncertainty of the measurements.
## The Challenge
Write a program that takes two lists of real numbers and outputs the result of applying Dempster's rule to the two input lists. The lengths of the two input lists will equal, and that length will be a power of 2, and will be at least 4. For each list, the first value will always be 0 and the remaining values will all be non-negative and add up to 1.
Output should be a list with the same length as the input lists. You can assume that a solution exists (it is possible for a solution to not exist when there is total conflict between evidence and thus K=1). To place a minimum requirement on precision, your program must be able to produce results that are accurate when rounded to four decimal places.
## Example I/O
```
in:
[0, 0, 0, 0.8, 0, 0, 0, 0.2]
[0, 0.3, 0, 0, 0, 0, 0.7, 0]
out:
[0.0, 0.3, 0.56, 0.0, 0.0, 0.0, 0.14, 0.0]
in:
[0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.4]
[0.0, 0.2, 0.0, 0.2, 0.0, 0.2, 0.0, 0.4]
out:
[0.0, 0.2889, 0.0889, 0.1556, 0.0889, 0.1556, 0.0444, 0.1778]
in:
[0.0, 0.0, 0.5, 0.5]
[0.0, 0.7, 0.1, 0.2]
out:
[0.0, 0.53846, 0.30769, 0.15385]
in:
[0.0, 0.055, 0.042, 0.098, 0.0, 0.152, 0.0, 0.038, 0.031, 0.13, 0.027, 0.172, 0.016, 0.114, 0.058, 0.067]
[0.0, 0.125, 0.013, 0.001, 0.012, 0.004, 0.161, 0.037, 0.009, 0.15, 0.016, 0.047, 0.096, 0.016, 0.227, 0.086]
out: (doesn't have to be this precise)
[0.0, 0.20448589713416732, 0.11767361551134202, 0.028496524069011694, 0.11809792349331062, 0.0310457664246791, 0.041882026540181416, 0.008093533320057205, 0.12095719354780314, 0.11306959103499466, 0.06412594818690368, 0.02944697394862137, 0.06398564368086611, 0.014369896989336852, 0.03774983253978312, 0.006519633578941643]
in:
[0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.1, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.1, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.1, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.1, 0.0, 0.1, 0.0]
out:
[0.0, 0.09090909090909094, 0.23376623376623382, 0.0, 0.07792207792207795, 0.025974025974026, 0.03896103896103895, 0.0, 0.10389610389610393, 0.05194805194805199, 0.02597402597402597, 0.0, 0.012987012987012984, 0.012987012987012993, 0.012987012987012984, 0.0, 0.09090909090909094, 0.038961038961038995, 0.06493506493506492, 0.0, 0.07792207792207796, 0.0, 0.0, 0.0, 0.012987012987012984, 0.012987012987013, 0.012987012987012984, 0.0, 0.0, 0.0, 0.0, 0.0]
```
[Answer]
# Perl, 68 bytes
Includes +2 for `-an`
Give the first set as row and the second as a column on STDIN
```
perl -M5.010 dempster.pl
0.0 0.0 0.5 0.5
0.0
0.7
0.1
0.2
^D
^D
```
`dempster.pl`:
```
#!/usr/bin/perl -an
/$/,map$H[$m%@F&$m++/@F]+=$_*$`,@F for<>;say$%++&&$_/(1-"@H")for@H
```
A pretty standard golf solution. Doesn't work if I replace `@H` by `@;`
] |
[Question]
[
Being programmers, watching us flex aren't very interesting. Today we change that! In this challenge you will lex and flex hexaflexagons.
# About
For a video introduction, watch [viharts video(s) on flexagons](https://youtu.be/VIVIegSt81k)
A flexagon is a shape that you can flex to reveal faces other than the top and bottom one; we are making a hexahexaflexagon, which has 6 faces. See the image below on how to fold a hexahexaflexagon out of a strip of paper.
[](https://i.stack.imgur.com/kddCM.gif)
`A` shows both sides of the strip. The two white triangles are glued together.
This is how you would flex it:
[](https://i.stack.imgur.com/wcOz8.gif)
Below is a diagram of possible states and their relationships:
[](https://i.stack.imgur.com/1aWn3.png)
The colored circles represent the 6 triangles with the same number from the first image. Each of the circes have two colors- the bottom most represent the back face (what you would see if you where to flip your flexagon around), which you don't have to consider in this challenge.
The gray circles in the background represent how you can flex your flexagon in any given state: there are 4 different ways to flex it, we call these `Left`, `Right`, `Up` and `Down`. You don't actually flex in these directions, the important bit is that some are opposite to each other.
If you are in the center you can use `Left` and `Right` to go to the other center ones. To get out of the center you use `Up` and `Down`. If you aren't in the center you cannot use `Left` or `Right`.
```
Left/Down = clockwise
Right/Up = anti-clockwise
```
# Challenge
Create a function or program that take as input what should be on the 18 front faces and the 18 back faces of a flexagon, a sequence of left, right, up and down flexes, and return the 8 visible faces after the flexes.
Elaborate example computation:
```
flex "hexaflexaperplexia"
"flexagationdevices"
[Right, Right, Left]
Divide a strip of paper into 18 triangles:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3 Front
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6 Back
Write "hexaflexaperplexia" on the front of the paper strip:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3
hexaflexaperplexia
123123123123123123
h a e p p x Face 1, Initially the front face
e f x e l i Face 2, Initially the back face
x l a r e a Face 3, Initially hidden
Write "flexagationdevices" on the back of the paperstrip:
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6
flexagationdevices
445566445566445566
fl at ev Face 4, up from 3
ex io ic Face 5, up from 2
ag nd es Face 6, up from 1
Flex it [Right, Right, Left]
The initial visible face is 1: "haeppx"
flexing Right ..
The current visible face is 2: "efxeli"
flexing Right ..
The current visible face is 3: "xlarea"
flexing Left ..
The current visible face is 2: "efxeli"
flexed [Right, Right, Left]!
outputting "efxeli"
```
Example implementation: <http://jdoodle.com/a/18A>
# Input and expected output:
```
> hexaflexaperplexia flexagationdevices RRL
= efxeli
> loremipsumdolorsit hexaflexamexicania RUU
= riuort
> abcdefghijklmnopqr stuvwxyz1234567890 UL
= I can't flex that way :(
> abcdefghijklmnopqr stuvwxyz1234567890 RRRRLLUDDUUUULDD
= uv1278
```
# Rules
* You may take input and return output in any reasonable way
* If the input is impossible, you should indicate so in some way that is distinct from regular output
* Standard loopholes apply
* This is `Codegolf`. Shortest code in bytes win.
[Answer]
# Haskell (Lambdabot), ~~270~~ 234 bytes
```
(!)=((map(snd<$>).groupBy((.fst).(==).fst).sortOn fst).).zip.cycle
o n(a,b)|n>1||b<1=(mod(a+[-1,1,0,0]!!n)3,mod(b+[0,0,-1,1]!!n)3)
(x&y)d|(g,h)<-foldl(flip(.))id(o<$>d)(0,0)=([0,1,2]!x++[3,3,4,4,5,5]!y)!!([0,5,1,1,4,2,2,3,0]!!(3*g+h))
```
Usage:
```
> (&) "hexaflexaperplexia" "flexagationdevices" [1,3]
"exioic"
```
[0,1,2,3] = [left,right,up,down]
Thanks to @Damien for a lot of bytes!
] |
[Question]
[
## The Challenge
Given either a string (may have newlines), or a two dimensional array, and a positive integer `n`, output the position of the platforms `n` turns after the
initial position.
---
`U, D, R, L` are platforms.
`^, v, >, <` are arrows that change the directions of the platforms.
`U, D, R, L` move up, down, right and left, respectively. When an arrow is in front of a platform, it changes the direction.
### Affects platform:
```
R<
```
```
D
^
```
```
v
U
```
```
>L
```
```
>L
<
```
(top arrow will affect top `L`, but bottom arrow won't affect top `L`)
### Won't affect:
```
<
R
```
```
>
L
```
```
v
U
```
```
D
^
```
```
<R
```
(`R` is going right, so `<` won't affect the `R`)
---
For example, if this was the string:
```
>R <
```
The platform `R` would move right until it's nearly touching the arrow:
```
> R<
```
After, it would change the direction and start going left:
```
> R <
```
(even though now it's going left, the letter won't change.)
There are some cases when the platform won't move, such as
```
>R<
```
or
```
v
U
^
```
Last example:
```
v >
D Rv
^U
^ <
```
After one turn,
```
v >
U v
D ^ R
^ <
```
After one turn,
```
v >
D Uv
^R
^ <
```
And one more turn:
```
v >
R v
D ^ U
^ <
```
You can assume that the platforms, after `n` turns, won't overlap, that the platforms won't go out of bounds, and that a platform won't touch an arrow that's pointing to the same direction as the platform.
---
## Test Cases
```
Input:
">R <", 4
Output:
"> R <"
Input:
">R <", 6
Output:
">R <"
Input:
">R<", 29
Output:
">R<"
Input:
"v
U
^", 5
Output:
"v
U
^"
Input:
"v
D
^", 1
Output:
"v
D
^"
Input:
"v
D
^", 4
Output:
"v
D
^"
Input:
"v >
D Rv
^U
^ < ", 2
Output:
"v >
D Uv
^R
^ <
Input:
">RL<", 3
Output:
">LR<"
Input:
">L R<", 4
Output:
"> RL <"
Input:
"> RR<
>L R <", 6
Ouput:
">RR <
> RL <"
Input:
"R <", 4
Output:
" R <"
Input:
"R <", 6
Ouput:
"R <"
```
---
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
* Standard loopholes are disallowed.
[Answer]
# C#, 1245 bytes
```
(i,n)=>{string q="RlherLHEfquDFQUd",D="><v^",H="Rlhe",E="LrHE",X="Dufq",Y="UdFQ",S="#v<>";Func<string,char,int>I=(v,L)=>v.IndexOf(L);Func<char,int,char>z=(y,m)=>q[I(q,y)+m*4];Func<string,char,bool>_=(s,F)=>s.Contains(F);var g=((i as char[][])??((string)i).Split('\n').Select(f=>f.ToCharArray())).ToList();int w=g[0].Length,h=g.Count,u;g=g.Select((r,o)=>r.Select((t,p)=>'R'==t&&w>p+1&&0<=(u=I(D,r[p+1]))?z(t,u):'L'==t&&0<=p-1&&0<=(u=I(D,r[p-1]))?z(t,-1+u):'D'==t&&h>o+1&&0<=(u=I(D,g[o+1][p]))?z(t,-2+u):'U'==t&&0<=o-1&&0<=(u=I(S,g[o-1][p]))?z(t,-u):t).ToArray()).ToList();for(var j=0;j<n;j++){bool L,R,T,B;g=g.Select((r,o)=>r.Select((t,p)=>_(D,t)?t:(R=0<=p-1)&&_(H,r[p-1])?w>p+1&&0<=(u=I(D,r[p+1]))?z(r[p-1],u):r[p-1]:(L=w>p+1)&&_(E,r[p+1])?0<=p-1&&0<=(u=I(D,r[p-1]))?z(r[p+1],-1+u):r[p+1]:(B=0<=o-1)&&_(X,g[o-1][p])?h>o+1&&0<=(u=I(D,g[o+1][p]))?z(g[o-1][p],-2+u):g[o-1][p]:(T=h>o+1)&&_(Y,g[o+1][p])?0<=o-1&&0<=(u=I(S,g[o-1][p]))?z(g[o+1][p],-u):g[o+1][p]:(L&&_(H,t)&&!_(D,r[p+1]))||(R&&_(E,t)&&!_(D,r[p-1]))||(B&&_(Y,t)&&!_(D,g[o-1][p]))||(T&&_(X,t)&&!_(D,g[o+1][p]))?' ':t).ToArray()).ToList();}return string.Join("\n",g.Select(s=>new string(s))).ToUpper().Replace("H","U").Replace("E","D").Replace("F","R").Replace("Q","L").Replace("V","v");};
```
It seemed simpler at first, but then I just kept writing more code. :D
LINQ to enumerate and update the board, changing the character to indicate the direction it's moving. The characters are reverted back before returning. Also assumes that the board is square (so had to modify some of the multi-line test cases to fit this restriction).
Expanded:
```
// Casts to Func<object, int, string> so as to accept both string and char[][] input
(i, n) =>{
// Shorten constants/functions
string q = "RlherLHEfquDFQUd", D = "><v^", H = "Rlhe", E = "LrHE", X = "Dufq", Y = "UdFQ",S="#v<>";
Func<string, char, int> I = (v, L) => v.IndexOf(L);
Func<char, int, char> z = (y, m) => q[I(q,y) + m * 4]; // Updates the direction of the platform
Func<string, char, bool> _ = (s, F) => s.Contains(F);
// Convert either string or char[][] input into common format
var g = ((i as char[][]) ?? ((string)i).Split('\n').Select(f => f.ToCharArray())).ToList();
// Get board dimensions
int w = g[0].Length,h = g.Count,u;
// Update platforms to reflect the direction they're initially moving
g = g.Select((r, o) => r.Select((t, p) =>
'R' == t &&w>p+1&&0<=(u=I(D,r[p+1]))?z(t,u):
'L' == t &&0<=p-1&&0<=(u= I(D, r[p-1]))?z(t,-1+u):
'D' == t &&h>o+1&&0<=(u= I(D, g[o+1][p]))?z(t,-2+u):
'U' == t &&0<=o-1&&0<=(u= I(S,g[o-1][p]))?z(t,-u):t
).ToArray()).ToList();
// Go through each timestep
for (var j=0;j<n;j++)
{
bool L,R,T,B;
g = g.Select((r, o) => r.Select((t, p) =>
// Don't change <>^v characters
_(D,t) ? t :
// Move platforms going right
(R=0 <= p - 1) && _(H,r[p-1]) ? w > p+1 && 0<=(u= I(D, r[p+1])) ? z(r[p-1],u) : r[p - 1] :
// Move platforms going left
(L=w > p + 1) && _(E,r[p+1]) ? 0 <= p-1 && 0<=(u= I(D, r[p-1])) ? z(r[p+1],-1+u) : r[p + 1] :
// Move platforms going down
(B=0 <= o - 1) && _(X,g[o-1][p]) ? h > o+1 && 0<=(u= I(D, g[o+1][p])) ? z(g[o - 1][p],-2+u) : g[o-1][p] :
// Move platforms going up
(T=h > o + 1) && _(Y,g[o+1][p]) ? 0<=o-1&&0<=(u= I(S, g[o-1][p]))?z(g[o + 1][p],-u) :g[o+1][p]:
// Erase platforms that moved
(L&&_(H,t)&&!_(D,r[p+1]))||
(R&&_(E,t)&&!_(D,r[p-1]))||
(B&&_(Y,t)&&!_(D,g[o-1][p]))||
(T&&_(X,t)&&!_(D,g[o+1][p]))
? ' ':
// Maintain whatever character this was
t
).ToArray()).ToList();
}
// Replace direction characters with platform label and join into string return value.
return string.Join("\n",g.Select(s=>new string(s))).ToUpper().Replace("H", "U").Replace("E", "D").Replace("F", "R").Replace("Q", "L").Replace("V", "v");
};
```
] |
[Question]
[
In trigonometry, there are certain angles known as "special angles". This is because when you take sin, cos or tan of one of these angles, you get a result that is easy to remember because it is a square root of a rational number. These special angles are always multiples of either `pi/6`, or `pi/4`. Here is a visualization of all the special angles, and their corresponding trig values.
[](https://i.stack.imgur.com/aLeMP.gif)
As you can see, for each angle their is a corresponding pair of numbers. The first number is cosine of that angle, and the second is sine of that angle. To find tangent of one of these angles, just divide sin by cos. For example, `tan(pi/6)` is equal to
```
sin(pi/6) / cos(pi/6) ==
(1/2) / (√3/2) ==
1/√3 ==
√3/3
```
# The Challenge
You must write a full program that takes 3 inputs.
1. A single char representing the trig function you're supposed to calculate. This will be either 's' (sin), 'c' (cos), or 't' (tan).
2. The numerator of the input angle. This can be any positive integer. Note that an input of 5 means the numerator is 5 \* pi.
3. The denominator of the input angle. This will always be one of the following: `1, 2, 3, 4, 6`
Then print out the exact value the trig function of that angle. Here is a list of sin, cos, and tan of all angles up to 2 \* pi:
```
sin(0pi): 0
sin(pi/6): 1/2
sin(pi/4): root(2)/2
sin(pi/3): root(3)/2
sin(pi/2): 1
sin(2pi/3): root(3)/2
sin(3pi/4): root(2)/2
sin(5pi/6): 1/2
sin(1pi): 0
sin(7pi/6): -1/2
sin(5pi/4): -root(2)/2
sin(4pi/3): -root(3)/2
sin(3pi/2): -1
sin(5pi/3): -root(3)/2
sin(7pi/4): -root(2)/2
sin(11pi/6): -1/2
sin(2pi): 0
cos(0pi): 1
cos(pi/6): root(3)/2
cos(pi/4): root(2)/2
cos(pi/3): 1/2
cos(pi/2): 0
cos(2pi/3): -1/2
cos(3pi/4): -root(2)/2
cos(5pi/6): -root(3)/2
cos(1pi): -1
cos(7pi/6): -root(3)/2
cos(5pi/4): -root(2)/2
cos(4pi/3): -1/2
cos(3pi/2): 0
cos(5pi/3): 1/2
cos(7pi/4): root(2)/2
cos(11pi/6): root(3)/2
cos(2pi): 1
tan(0pi): 0
tan(pi/6): root(3)/3
tan(pi/4): 1
tan(pi/3): root(3)
tan(pi/2): nan
tan(2pi/3): -root(3)
tan(3pi/4): -1
tan(5pi/6): -root(3)/3
tan(1pi): 0
tan(7pi/6): root(3)/3
tan(5pi/4): 1
tan(4pi/3): root(3)
tan(3pi/2): nan
tan(5pi/3): -root(3)
tan(7pi/4): -1
tan(11pi/6): -root(3)/3
tan(2pi): 0
```
If you get a number larger than 2pi, subtract 2pi from it until you get a number that is in range. For example, `sin(17pi/6)` is the same as `sin(5pi/6)` == 1/2. Your program is expected to do basic simplification, for example, if your input is `cos(2pi/4)` this is the same as `cos(pi/2)` == 0. Builtin trigonometry functions are disallowed.
Shortest answer in bytes wins!
[Answer]
## Pyth, 125 122 bytes
Uses the formula `n = 4 - |floor(4.5-9k)|`, where `kπ = θ` i.e. k is the quotient of the second and third inputs, to determine which special angle is in question: the angles 0, 30, 45, 60 and 90 degrees are numbered 0 to 4 respectively, and the 90~180 degrees angles go in reverse; this formula works for `θ∈[0,π]`. The values of corresponding sines would be `sqrt(n)/2` and existent, non-zero tangents would be `3^(n/2-1)`. However, my implementation uses lists with hard-coded compressed strings for higher control of output format, and it seems the code is shorter that way too.
```
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"dc." t@a'óè©ê¶oyÑáîwÀ(";J+cEE?qz\c.5ZK-4.as-4.5*3*3%J1?qz\t+?>%J1 .5\-k@GK+?>%J2 1\-k@HK
```
Let's turn it into pythonic pseudocode:
```
z = input()
k = ""
d = " "
Z = 0
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"d G = "0 sqrt(3)/3 1 sqrt(3) nan".split(d)
c." t@a'óè©ê¶oyÑáîwÀ("; H = "0 1/2 sqrt(2)/2 sqrt(3)/2 1".split()
J+cEE J = eval(input())/eval(input()) +
?qz\c.5Z 0.5 if z == "c" else Z
# the second term converts sin to cos
K-4.as-4.5*3*3%J1 K = 4 - abs(int(4.5 - 3*3*(J%1)))
# 9* would lose precision so 3*3* instead
?qz\t if z == "t"
+?>%J1 .5\-k print(("-" if J%1 > 0.5 else k) +
@GK G[K])
else:
+?>%J2 1\-k print(("-" if J%2 > 1 else k) +
@HK H[K])
```
[Test online](http://pyth.herokuapp.com/?code=A%2Cc.%22%20t8%C2%BE%C3%8Ezp%C2%B39%C3%93%C3%8D%C3%95%C2%AC%24%16%09%C2%B7%C3%8Db%C2%B3%C2%B0%C3%BC%22dc.%22%20t%06%40%C2%94a%27%C3%B3%C3%A8%C2%A9%C3%AA%C2%B6oy%C3%91%1D%C3%A1%0E%C3%AEw%08%C3%80%11%28%22%3BJ%2BcEE%3Fqz%5Cc.5ZK-4.as-4.5%2A3%2A3%25J1%3Fqz%5Ct%2B%3F%3E%25J1%20.5%5C-k%40GK%2B%3F%3E%25J2%201%5C-k%40HK&input=s%0A1%0A3&debug=1).
] |
[Question]
[
INTERCAL is a wonderful language, but it is not always easy to understand other people's code. This is particularly the case if they use the COME FROM statement.

# Challenge definition
1. Write a **program** or **function** which take the source code of an INTERCAL program as a text/data stream. If you write a function it is recommended that you also provide a program to call the function, but it will not count towards your score.
2. The function output will be a text/data stream of the jumps that program makes, according to the following instructions. The output *does not* need to be printed, but it does need to be a single text, not an array of strings (for example).
3. Each line of output will consist of the statement which will be COME FROM and the line number of its COME FROM statement, separated by a `->`. An example:
```
(310) DO .4 <- .3 -> 55
```
4. You can trim these lines of source code, but it is not necessary to.
5. The test cases will only consist of [noncomputed labels](http://www.catb.org/~esr/intercal/ick.htm#COME-FROM-and-NEXT-FROM) (i.e., integer labels).
6. The output must be sorted by the source code order of the statements which will be COME FROM, not their label, nor the order of the COME FROM statements or their labels.
7. It is possible for multiple statements to COME FROM the same label. In such cases the COME FROM line numbers must be sorted, and separated by commas.
8. It is possible for a statement to COME FROM itself.
9. A COME FROM statement may be prefixed with a NOT statement. In such cases the line number must be wrapped in square brackets.
10. The words COME FROM can appear in a comment and must be ignored. You do not need to fully parse the file: if they are followed by a label (a number in parentheses) then you can assume it is a real statement.
# Scoring
Entrants will be scored by the **character length** of their program or function.
# Test cases
These test cases all come from [the calvinmetcalf/intercal Github repo](https://github.com/calvinmetcalf/intercal/tree/master/pit). Although any useful application will safely accept any input, for the purposes of this challenge you need only account for these five test cases.
**[rot13.i](https://raw.githubusercontent.com/calvinmetcalf/intercal/8a65e8ba1cc65870b0d6b1bb174a4c4560bde07f/pit/rot13.i)**
```
(10) PLEASE DON'T GIVE UP -> 87
(33) DON'T GIVE UP -> 92
```
**[primes.i](https://raw.githubusercontent.com/calvinmetcalf/intercal/8a65e8ba1cc65870b0d6b1bb174a4c4560bde07f/pit/primes.i)**
```
(15) DO (13) NEXT -> 26
(16) DO .12 <- .1 -> 6
(23) DO (21) NEXT -> 3
```
**[unlambda.i](https://raw.githubusercontent.com/calvinmetcalf/intercal/8a65e8ba1cc65870b0d6b1bb174a4c4560bde07f/pit/unlambda.i)**
```
(7202) DO RETRIEVE .203+,202 -> 75
(4202) DO ,202SUB.201.202#7 <- ,201SUB.201.202#7 -> 108
(6202) DO ,201SUB.201.202#7 <- ,202SUB.201.202#7 -> 117
(4203) DO READ OUT ,201SUB.201.202#7 -> 133
(4302) DO .302 <- .2 -> 181
(5410) DO ,400SUB#124 <- #4 $ #17 -> 293
(3410) PLEASE (4410) NEXT -> 288
(5402) DO (412) NEXT -> 328
(4412) PLEASE (3412) NEXT -> 334
(3423) DO FORGET #2 -> 375
(4404) DO RETRIEVE .311+.312 -> 411
(5404) PLEASE DO (414) NEXT -> 430
(4434) DO FORGET #1 -> 441
(3454) DO (103) NEXT -> 451
(5502) DO .512 <- .312 -> 520
(8503) PLEASE RETRIEVE .311+.312 -> 621
(7503) DO (302) NEXT -> 515
(3622) DO (302) NEXT -> 514
(603) PLEASE FORGET #2 -> 622
```
**[pass.i](https://raw.githubusercontent.com/calvinmetcalf/intercal/8a65e8ba1cc65870b0d6b1bb174a4c4560bde07f/pit/pass.i)**
```
(10) DO NOTHING -> 5, 11
(20) PLEASE (100) NEXT -> 6
(30) PLEASE (200) NEXT -> 12
(103) DO (104) NEXT -> 27
(104) DO (105) NEXT -> 19
(1) DO (2) NEXT -> 36
(2) DO (105) NEXT -> 194
(202) DO NOT .2 <- #2 AGAIN -> [196]
(203) DO (204) NEXT -> 167
(204) DO (205) NEXT -> 159
```
**[continuation.i](https://raw.githubusercontent.com/calvinmetcalf/intercal/8a65e8ba1cc65870b0d6b1bb174a4c4560bde07f/pit/continuation.i)**
```
(8201) DO NOTHING -> 165, 271
(8202) PLEASE NOTE Fork threads, one dormant, one alive -> 53, 58
(8211) DO COME FROM (8211) -> 60
(8216) DO NOTHING -> 71
(8215) DO NOTHING -> 68
(8217) DO COME FROM (8217) AGAIN -> 118
(8299) DO COME FROM (8299) AGAIN -> 141
(8274) DO (8273) NEXT ONCE -> 158
(8259) PLEASE DO NOTHING -> 166
(8276) DO COME FROM (8276) AGAIN -> 199
(8278) PLEASE DO COME FROM (8278) AGAIN -> 237
```
[Answer]
# JavaScript, 232 bytes
```
function c(d){for(var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';l=p.exec(d);)for(f=0;o=a.exec(d);)o[2]==l[1]&&(c=d.slice(0,o.index).split('\n').length,r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);return r.trim()}
```
To be called with
```
var data = require( 'fs' ).readFileSync( process.argv[2] ).toString();
console.log( c( data ) );
```
Explanation
```
function c(d){
for(
// Initialise variables
var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';
// Find lines beginning with a label
l=p.exec(d);)
for(
// Reset a have-we-output-this-line flag
f=0;
// Find CALL FROM statements
o=a.exec(d);)
// Filter to CALL FROM statements which have the current line
o[2]==l[1]&&(
// Calculate the line number of this CALL FROM statement
c=d.slice(0,o.index).split('\n').length,
// Concat the output for this line
r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);
// Trim an initial new line
return r.trim()}
```
] |
[Question]
[
Given a set of formulas like this:
```
bacb
bcab
cbba
abbc
```
Give an algorithm that finds the number of unique results you can get when each variable is substituted for either "0" or "1" in every formula.
There are `(k!)^2` formulas, each with `2k-1` variables and `k^2` terms. Express your asymptotics in terms of `k`.
Fastest algorithm wins. In case of a tie the solution with lower asymptotic memory usage wins. If that's still a tie, first post wins.
---
For the example above the following results can be acquired by substituting the variables:
```
1110, 0110, 1001, 0100, 1000, 0000, 0010, 1101, 1111, 0001, 1011, 0111
```
So the correct answer is 12. Among others, `1010` can not be made using the above formulas.
I've made three more tests cases, with respective solutions of [230](https://gist.githubusercontent.com/orlp/8c1190ef1fb31f45427d/raw/9495f614554ca2203a5d685fce4691488306dcee/small.txt), [12076](https://gist.githubusercontent.com/orlp/8c1190ef1fb31f45427d/raw/ba3cb8a9da05cbb4bf5a4d9287e194f8a3a384ec/big.txt) and [1446672](https://gist.githubusercontent.com/orlp/8c1190ef1fb31f45427d/raw/fc227c65f5dad86fb454d64e6c23caa3457ed315/huge.txt).
[Answer]
# Mathematica, O(k^2(k!)^2) time
```
Length[Union@@(Fold[Flatten[{StringReplace[#,#2->"0"],StringReplace[#,#2->"1"]}]&,#,Union[Characters[#]]]&/@#)]&
```
Hopefully I calculated the time complexity correctly. Input is a list of formulas such as `{"bacb","bcab","cbba","abbc"}`. Runs in less than 30 seconds for every test case on my machine, but who cares about absolute times?
### Explanation:
* First off, the `&` at the end makes it a pure function, with `#` referring to the first argument, `#2` being the second argument, etc.
* `Length[*..*]` takes the length of the list contained inside it.
* `Union@@(*..*)` takes the contained list and supplies it as the arguments for `Union`, which returns a list of the unique elements in any of its arguments.
* `*..*&/@#` takes a pure function and maps it over the list of formulas, so that `{a,b,c}` becomes `{f[a],f[b],f[c]}`. Note that in nested pure functions, `#n` refers to its innermost arguments.
* `Fold[*..*&,#,*..*]` takes a accumulator function, starting value, and list, and returns `f[f[...[f[starting value,l_1],l_2],...],l_n]`.
* `Union[Characters[#]]` takes all the characters in the current formula and gets all the unique elements, giving us the variables.
* `Flatten[*..*]` flattens its argument, so that `{{{a},b},{{c,{d}}}}` becomes `{a,b,c,d}`.
* `{*..*,*..*}` is simply a way to combine the two results using the above `Flatten`.
* `StringReplace[#,#2->"0/1"]` takes the previous result and returns it with the current variable replaced with either `0` or `1`.
] |
[Question]
[
You decided to organize a [rock-paper-scissors](http://en.wikipedia.org/wiki/Rock-paper-scissors) championship to find out who is the best. You don't want to let luck to decide the winner so everyone has to give you his or her tactic in writing before the competition. You also like simple things so a move of a competitor (showing rock, paper or scissors) has to be based only the previous turn (RvR, RvP, RvS, PvR, PvP, PvS, SvR, SvP or SvS). In the first turn a player has to show a fixed sign.
You decided to write a program (or function) to simulate the championship.
## Details of the competition
* There will be at least 2 contestants.
* Every player plays exactly one match with everyone else.
* One match lasts 7 rounds.
* In every round the winner gets 2 points the loser gets none. In the event of a tie both player score 1 point.
* A players score in a match is the sum of his or her points over the turns of the match.
* A players final score in the championship is the sum of his or her points over all matches.
## Details of the input:
* your program or function receives `N` 10 character long strings each of them corresponds to a players strategy. All characters are (lowercase) `r` `p` or `s` meaning that in the given situation the player will show rock paper or scissors.
* The first letter codes the first turn (in every match for that competitor). The second shows what happens if the last round was rock vs rock. The next ones are RvP, RvS, PvR, PvP, PvS, SvR, SvP and SvS where the first letter is the player's sign and the second is the opponent's. E.g. `rrpsrpsrps` means the player starts with rock and then copies the opponent's last move.
* You can input the list of strings as a list/array or similar data of your language or as one string. In the latter case some kind of separator character is a must.
## Details of the output:
* Your program or function should output the final scores of each player in the same order as the input was supplied.
* Scores should be separated by spaces or newlines. Trailing space or newline is allowed.
## Examples:
Input:
`['rrpsrpsrps', 'rpppsprrpr']`
Output:
`5 9` (turns are `rvr rvp pvs svp pvr rvp pvs`)
Input:
`['rrpsrpsrps', 'rpppsprrpr', 'ssssssssss']`
Output:
`13 17 12` (matches are `5-9` (1st vs 2nd), `8-6` (1st vs 3rd) and `8-6` (2nd vs 3rd))
This is code-golf so the shortest entry wins.
[Answer]
# Python 2: ~~201~~ 188 chars
```
def f(Q):c=lambda m:'rps'.index(m);l=len(Q);r=[0]*l;i=0;exec'p,q=i/l,i%l;m,n=c(Q[p][0]),c(Q[q][0]);exec"r[p]+=(p!=q)*(m+1-n)%3;m,n=c(Q[p][m*3+n+1]),c(Q[q][n*3+m+1]);"*7;i+=1;'*l*l;return r
```
The logic of the program: I convert the letters to number (`r=0`,`p=1`,`s=2`). `m` is the number of the first, `n` the number of the second person. Because the game is cyclic, `(m-n)%3` already determines the result. And of course, I can shift the result by one `f=(m+1-n)%3`. Now `f=0` means, second player `q` wins, `f=1` means a tie, and `f=2`, first player `p` wins. It also is already the score for player 1. Therefore I only need to add all values `(p!=q)*(m+1-n)%3` for each player.
Test it with `print f(['rrpsrpsrps', 'rpppsprrpr', 'ssssssssss'])`
] |
[Question]
[
Imagine some cube which we can cut into smaller cubes without remaining pieces.
Find to how many cubes a cube can be cut.
For example, a cube can be cut into 8, 27 (obviously 3rd powers of integers) and 20 (19 small cubes plus one eight times the size of the others, see image).
See here some help: <http://mathworld.wolfram.com/CubeDissection.html>

Program should take as input integer `n` (`0 <= n <= 1 000`) and print all numbers less or equal to `n` so that a cube can be cut into that number of cubes.
Suppose that cube can be cut into 1 cube and cannot into 0 cubes.
You can use only integral data-types (no arrays, objects etc) of size no greater than 64-bits.
Shortest code wins.
[Answer]
# Golfscript, 55 (or ~~43~~ 42)
```
{.:^}{.47>20{.^>^@- 7%|!|}:/~1/38/39/{}{;}if^(}while;]`
```
Can be tested [here](http://golfscript.apphb.com/?c=Owo1Ngp7LjpefXsuNDc%2BMjB7Ll4%2BXkAtIDclfCF8fTovfjEvMzgvMzkve317O31pZl4ofXdoaWxlO11gCgo%3D) (just change the number on line 2) and only uses the array (last two chars of code) for clean printing, not for any collection or problem solving. If you leave it off, all results will be concatenated.
**Method:** Iterate down from given n: If current number is greater than 47 or of the form 1+7x, 20+7x, 38+7x, or 39+7x where x = any non-negative integer, then keep it on the stack, otherwise drop it.
**Short answer (43 bytes):**
~~{:/6+,{7\*/+}%|}:&;):a,48,^1&20&38&39&{a<},`~~
```
):a,48,^1{:/6+,{7*/+}%|}:&~20&38&39&{a<},`
```
**Method:** Similar, but with a few set theory ops. This uses arrays so it's technically not an acceptable answer. Can be tested [here](http://golfscript.apphb.com/?c=Owo1NgopOmEsNDgsXjF7Oi82Kyx7NyovK30lfH06Jn4yMCYzOCYzOSZ7YTx9LGA%3D). Btw: nobody ever said they had to be in any particular order ;)
[Answer]
**Mathematica, 62 bytes (or 52)**
It's hardcoded answer, nothing interesting.
>
> `If[EvenQ@BitShiftRight[164015534735101,n],Print@n]~Do~{n,1000}`
>
>
>
This one is 52 bytes long but violates my rules - it uses large integers (powers of 2) and lists (Range).
>
> `Select[Range@1000,EvenQ@Floor[164015534735101/2^#]&]`
>
>
>
[Answer]
# C, 72
```
i;main(){for(scanf("%d",&i);i;i--)0x952BD7AF7EFC>>i&1||printf("%d ",i);}
```
Another hardcoded answer. This counts downwards (there's nothing in the rules about the order the numbers have to be output in.) In theory it should work. The constant has a bit set to 1 for all the numbers into which a cube can NOT be cut, and a 0 for the numbers which can. In theory, the constant when right shifted by a very large number should be zero, so the large number should always be printed.
What's interesting is that in practice this does not work. The code above compiles and runs fine on GCC up to 65. But above that number there is a bug (or "feature") in the compiler. it interprets `0x952BD7AF7EFC>>i` as `0x952BD7AF7EFC>>i%64`. So it skips (for example) the numbers 66 through 71 (64+2 through 64+7).
To run in Visual Studio, a bit more boilerplate is needed (it doesn't let you get away with things like implied integers and `#include`s.) Once the program's up and running, it's fine up to 257... Then it skips 258 through 263 (256+2 through 256+7.) So it's taking `i%256.`
I may fix it later (if I can be bothered.) Moral: compiler manuals don't normally tell you the upper limit on bitshifts. There's a reason for that!
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->n{1.upto(n){|i|i/7<777159>>i%7*3&7||p(i)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2lCvtKAkXyNPs7omsyZT39zG3Nzc0NTSzi5T1VzLWM28pqZAI1OztvZ/WrSlZex/AA "Ruby – Try It Online")
Takes advantage of the fact that solutions occur modulo 7 (as a result of the fact that a cube can be dissected into 8 cubes, adding 7.)
Below are all solutions below 49 (there is a solution for all numbers over 49.) The magic number `777159` decimal = `2755707` octal encodes the lowest value of `i/7` for which a solution exists for each possible value of `i%7`.
```
n%7=0 not possible where i/7<7
n%7=1 1,8,15,22,29,36,43 i/7<0
n%7=2 i/7<7
n%7=3 38,45 i/7<5
n%7=4 39,46 i/7<5
n%7=5 i/7<7
n%7=6 20,27,34,41,48 i/7<2
```
] |
[Question]
[
Given A and B, where A is the scale of a Digital LED Pattern B. Parse pattern B and print the number.
input:
```
1
_ _ _ _ _ _ _ _ _ _ _ _
_| _| _|| ||_||_ ||_ |_|| | ||_||_||_ ||_|
|_ _||_ |_| | _| ||_| ||_| | | | _| ||_|
```
output:
```
2320451640799518
```
input:
```
2
__ __
| |
__| __|
| |
|__ __|
```
output:
```
23
```
**Rules:**
* Use **STDIN/STDOUT** for **input/output**
* I tried to mimic [this](https://codegolf.stackexchange.com/questions/19196/transform-number-into-7-segment-display-pattern) question as much as possible, but I think code-golf suits this one better.
* Shortest code (*in bytes*) wins
[Answer]
# Ruby, 151 characters
```
s,*r=*$<;c=r[s=s.to_i]
i=0;(n=(r[0][i+1]+c[i]+c[i+s,2]+r[-1][i]).tr(" |_","01").to_i 2
$><<(0..9).find{|j|0x3df9778eb5c5b>>5*j&31==n};i+=s+2)while b[i]
```
Leaves out digits it cannot recognise, but some invalid digits are recognised nevertheless.
Assumes the lines are padded with spaces to their full length.
] |
[Question]
[
You are Tom Sawyer and you have to paint a fence of 102400 m long. Luckily, your friends decided to help you in exchange of various things. Each friend will paint **L** meters, starting from **S** with color **C**. **S**, **L** are integer amount of meters and 1 ≤ **C** ≤ 97. Getting bored you decide to find out how many meters of each color you have.
**Input**
Input is read from standard input. Each line contains three numbers **S**, **L**, **C** as described above.
**Ouput**
Output is written to standard output. For each color that appears on the final fence print the color number and the number of times it appears. Order by colors.
**Examples**
*Input 0*
```
..............
0 3 1 111...........
2 4 2 112222........
1 2 3 133222........
0 4 1 111122........
7 3 5 111122.555....
```
*Output 0*
```
1 4
2 2
5 3
```
*Input 1*
```
0 100 1
50 150 2
```
*Output 1*
```
1 50
2 150
```
*Input 2*
```
500 1000 1
0 2000 2
```
*Output 2*
```
2 2000
```
**More examples**
Here is a small generator:
```
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
/* From http://en.wikipedia.org/wiki/Random_number_generation */
unsigned m_w;
unsigned m_z;
unsigned get_random()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
int main(int argc, char **argv)
{
int i;
assert(argc == 2);
m_w = 0xbabecafe;
m_z = atoi(argv[1]);
i = 10;
while (i--);
get_random();
i = atoi(argv[1]);
while (i--) {
int s = (int) ((get_random() << 8) % 102397);
int l = (int) ((get_random() << 8) % (102397 - s));
int c = (int) ((get_random() << 8) % 97 + 1);
printf("%d %d %d\n", s, l, c);
}
return 0;
}
```
Running examples:
```
$ ./gen 1 | ./paint
6 535
$ ./gen 10 | ./paint
28 82343
36 3476
41 1802
49 4102
82 1656
$ ./gen 100 | ./paint
2 2379
22 17357
24 4097
25 1051
34 55429
42 9028
45 9716
66 1495
71 196
85 640
97 706
$ ./gen 1000 | ./paint
16 719
26 29
28 24
33 1616
55 371
65 35
69 644
74 16
84 10891
86 36896
87 50832
89 19
$ ./gen 10000 | ./paint
3 800
6 5712
14 3022
17 16
26 1
29 18770
31 65372
37 387
44 40
49 37
50 93
55 11
68 278
70 19
71 64
72 170
77 119
78 6509
89 960
97 15
$ ./gen 100000 | ./paint
2 6
8 26
12 272
24 38576
26 1
34 1553
35 8
36 19505
43 2
45 11
46 2
47 9
49 27339
50 139
53 3109
69 11744
92 89
$ ./gen 1000000 | ./paint
1 1
3 4854
6 523
13 1
16 11
18 416
22 7
24 3920
25 96
31 10249
32 241
37 1135
45 10
57 758
62 2348
65 11
66 7422
78 6
85 13361
87 3833
88 187
91 46
93 7524
96 45436
```
Your program must run in reasonable time. My solution runs in a few seconds on the last example.
Shortest code wins.
**Include running time and your output for the last test.**
**EDIT**: This problem is not intended to be brute-forced, so a trivial solution is not acceptable.
[Answer]
## Python, 221 239 chars
```
import sys
F=[]
for L in sys.stdin:s,l,c=map(int,L.split());F=sum([[(a,min(b,s),d)]*(a<s)+[(max(a,s+l),b,d)]*(b>s+l)for a,b,d in F],[(s,s+l,c)])
C=[0]*98
for a,b,c in F:C[c]+=b-a
for c in range(98):
if C[c]:print c,C[c]
```
Keeps `F` as an unordered list of triples (start of run, end of run, color) representing the current state of the fence. Since the random painting in the generator overpaints larges swathes fairly frequently, this list is never too long (typically in the 15-40 range).
Runs in 37 seconds on the 1M example.
[Answer]
## Haskell, 251 261 269 294 characters
```
import Data.List
w@(y@(f,d,e):z)§x@[a,b,c]|e<=d=z§x|a+b>d=(f,d,e`min`a):((f,a+b,e):z)§x
w§[a,b,c]=(c,a,a+b):w
r(c,a,b)=replicate(b-a)c
f l=shows(l!!0)" "++shows(length l)"\n"
main=interact$(>>=f).group.(>>=r).sort.foldl'(§)[].map(map read.words).lines
```
Something isn't quite right about this as it takes far too much time and stack... But it does produce the right answers:
```
$> ghc -O3 --make -rtsopts -with-rtsopts -K32m 3095-PaintTheFence.hs
Linking 3095-PaintTheFence ...
$> ./3095-gen 1000000 | time ./3095-PaintTheFence
1 1
3 4854
6 523
13 1
16 11
18 416
22 7
24 3920
25 96
31 10249
32 241
37 1135
45 10
57 758
62 2348
65 11
66 7422
78 6
85 13361
87 3833
88 187
91 46
93 7524
96 45436
43.99 real 43.42 user 0.46 sys
```
---
* Edit (294 → 269) `replicate` and `group` is just as efficient way of counting up the paint, and takes less code than the custom function `s`
* Edit (269 → 261) no need for `max` call
* Edit (261 → 251) no need for to cull paint 0 in `f`
[Answer]
## Perl - 148 bytes
It seems that Perl is the best to play with. easy to code shorter and faster. ;)
**code:**
```
#!perl -n
($a,$b,$c)=split;substr($s,$a,$b,chr($c)x$b)}BEGIN{$s="z"x102400}{$s=~s/([^z])\1*/$H{$1}+=length$&/ge;print ord," $H{$_}
"for sort keys%H
```
**time:**
```
time ./gen 1000000 | perl paint.pl
...
real 0m9.767s
user 0m10.117s
sys 0m0.036s
```
[Answer]
## JavaScript, 183 chars, 1.3 seconds
Sadly, I did have to cut the stdin/out part of the requirement, which JavaScript doesn't support. Instead, I get the input from a file upload `<input>` instead (which I don't count in my char count, although I probably should).
Here is the ungolfed version. It's a function that takes the full input string... all 14MB of it! This is the one that takes 1.3 seconds; the golfed version takes about twice as long -- but it still beats the other solutions! Interestingly, it's twice as fast in Firefox than in Chrome. [Live demo here](https://dl.dropbox.com/u/125377/upload/codegolf.html).
```
function Q(input) {
var c = [];
var l = input.trim().split(/\s/g);
input = null
var length = l.length;
// Loop through each meter of the wall...
for (var i = 0; i <= 102400; i++) {
// ...and loop through each of the friends, finding
// the last one who painted this meter...
for (var j = length; j > 0; ) {
j -= 3;
// Start = +l[j]
// Length = +l[j + 1]
// Color = +l[j + 2]
var S = +l[j];
if (S <= i && +l[j + 1] + S > i) {
// ...and incrementing the color array.
var C = +l[j + 2];
if (!++c[C])
c[C] = 1;
break;
}
}
}
console.log(c.map(function (a,b) {return b + ' ' + a}).filter(function (a) { return a }).join('\n'));
}
```
And here's the golfed version.
```
function G(i){l=i.trim(c=[]).split(/\s/)
for(i=0;i<102401;i++)for(j=l.length;j>0;)if(l[j-=3]<=i&&i-l[j+1]<l[j]){if(!++c[l[j+2]])c[l[j+2]]=1
break}for(k in c)console.log(k+' '+c[k])}
```

[Answer]
```
$ cat input.txt
0 3 1
2 4 2
1 2 3
0 4 1
7 3 5
$ cat input.txt | perl -anE '@a[$F[0]..$F[0]+$F[1]]=($F[2])x$F[1];END{$i[$_]++for@a;$i[$_]&&say"$_ $i[$_]"for 1..$#i}'
1 4
2 1
5 3
$ cat input2.txt
500 1000 1
0 2000 2
$ cat input2.txt | perl -anE '@a[$F[0]..$F[0]+$F[1]]=($F[2])x$F[1];END{$i[$_]++for@a;$i[$_]&&say"$_ $i[$_]"for 1..$#i}'
2 2000
```
] |
[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/224879/edit).
Closed 2 years ago.
[Improve this question](/posts/224879/edit)
There are currently nine feature length films in the core *Fast & Furious/The Fast and the Furious* media franchise, a series of films about bald men scowling and driving cars very fast. The names of the films, as can be seen, follow a completely logical and sensible convention:
* *The Fast and the Furious*
* *2 Fast 2 Furious*
* *The Fast and the Furious: Tokyo Drift*
* *Fast & Furious*
* *Fast Five*
* *Fast & Furious 6*
* *Furious 7*
* *The Fate of the Furious*
* *F9*
I'm a Hollywood producer working on the new, tenth *Fast & Furious* film, and I'm struggling to find a title which hasn't yet been used. Please write me a piece of code - as short as possible - which takes in my input string, and returns a truthy value if **any** of the following are true:
1. the input string is already an existing *Fast & Furious* film title
2. the input string differs from an existing *Fast & Furious* film title *only* by replacing an existing number with `ten` or `10`
3. the input string differs from an existing *Fast & Furious* film title *only* by replacing `&` with `and` (or vice versa).
For instance, all of these strings would return a **truthy** value:
* *The Fast and the Furious* (matches check 1)
* *The Fast & the Furious* (matches check 3)
* *Fast and Furious 10* (matches checks 2 and 3)
* *10 Fast 2 Furious* (matches check 2)
* *Furious Ten* (matches check 2)
* *F10* and *FTEN* (match check 2)
And all of these strings would return a **falsy** value:
* *The Fast or The Furious*
* *Fast Times at Ridgemont High*
* *Fast/Furious 10*
* *Too Fast Too Furious*
* *Ten Furious*
* *Fast Ten Furious*
* *The Fast and the Furious: Kyoto Cruise*
*Fate of the Furious*, as a pun, is obviously a tricky case. Unless you're very driven, you don't need to support puns, just exact text matches. If you can create a new *Fast & Furious* film title which is a pun, please share.
**Clarifications**
* The matching is not case-sensitive, so the input string can be in lowercase. The film company design team will work out how to depict your title on the posters anyway, and the answer is 'in red, with speedy lines'.
* I've clarified that the numbering match should only be true if an existing number in the title has been replaced with the string `10` or `ten`.
[Answer]
# [Python 3](https://docs.python.org/3/), 190 bytes
```
lambda a:re.match("(the '!the %(: tokyo drift)?|(2# ' (2# %|'!%|' (five#|'!% (6#|% (7#|the fate of the %|f(9#)$".translate({33:" (and|&) ",35:"|10|ten)",39:"fast",37:"furious"}),a)
import re
```
[Try it online!](https://tio.run/##lZBBasMwEEX3OcVEauIRhGDHtCGG0ot0o9ZSLWpLRhoXQtWzu7LTFEy66UKfGc3/85D6MzXOlqN@fB5b2b3UEmTl1b6T9NogQ2oUZOtJN1gBufezg9obTeIp4oFDBpNuYrZOB1CbD8WnBvCBx6RHHqewlqTAaZgXRY0nLu7Ynry0oU0j/CzLigFKW8etALYr7ysWizySsiJ1p4ppGShVx1QN3rghsC@xk2Jlut55Aq/G3htLqJFdgIEgrZuJ14QQq1vT9p@WxS8s/L/MHycU@WJe5Jd1hz9p11B68uI@DL3y4Lx5M1a2cAMhQ60CPrPGbw "Python 3 – Try It Online")
A very naive attempt at this.
] |
[Question]
[
Given a BF program consisting of only the characters `+-[]<>.,` with the property that there's an equal number of `<` and `>` between every matching pair of `[]`.
You have to find the shortest program that can be achieved with the optimal memory layout (by rearranging the cells on the tape).
If there are multiple such programs, output any of them.
*For such a program, it's possible to tell exactly where (on which memory cell) the memory pointer is for each instruction executed. The memory can be rearranged such that the program is shorter, without changing the program execution.*
### Example input/output
```
Input : Output
,>>, : ,>,
,<++[->>+<<] : ,>++[->+<]
+<><>+ : ++
```
---
### Background
**Note that the challenge is well-defined (see the "formal description" section below) even without this section.**
Background on the language:
>
> Brainfuck operates on an array of memory cells, each initially set to zero. [...]. There is a pointer, initially pointing to the first memory cell. The commands are:
>
>
>
>
>
> | Command | Description |
> | --- | --- |
> | > | Move the pointer to the right |
> | < | Move the pointer to the left |
> | + | Increment the memory cell at the pointer |
> | - | Decrement the memory cell at the pointer |
> | . | Output the character signified by the cell at the pointer |
> | , | Input a character and store it in the cell at the pointer |
> | [ | Jump past the matching ] if the cell at the pointer is 0 |
> | ] | Jump back to the matching [ if the cell at the pointer is nonzero |
>
>
>
(Source: [brainfuck - Esolang](https://esolangs.org/wiki/Brainfuck))
For the purpose of this challenge, assume that the tape is unbounded on both ends.
Therefore, for all programs that are valid input for this challenge,
* the memory cell that the pointer is on is completely determined by the instruction that is going to be executed, and
* there's only a finite number of accessed memory cells.
(Note that the program might not terminate.)
Now assume that the memory layout is rearranged so that whatever a cell `x` is used (by a command not in `<>`) in the original program, the cell `f(x)` is used in the new program. Then the new program might be shorter than the original program.
Your task is to find the shortest program that can be obtained by rearranging the memory layout, **without changing the execution or order of the other commands**.
For example, assume that the cells are numbered `-1, 0, 1, 2,...`, the starting position is `0`, and `>` and `<` increases/decreases the position of the memory pointer respectively.
Consider the program `,>>,`. It executes `,` on cell `0`, then move to cell `2`, then executes `,` again.
If the cells 2 and 1 are swapped, then the new program should execute `,` on cell 0, then move to cell `1`, then execute `,` again, which can be achieved by `,>,`. This is the shortest possibility.
Note that you can swap cell 2 and -1, so the resulting program is `,<,`, which is just as short.
However, the new memory layout must not rearrange two different cells to the same cell, so it's invalid to read to cell 0 both times (program `,,`).
---
### FAQ
I'm not sure what questions people may have, in any case refer to the formal description.
* The amount and order of the non-`<>` in the input and output must be the same.
* If two (non-`<>`) commands in the original program access the same cell, the two corresponding commands must access the same cell in the shortened program. (i.e., if `a` and `b` accesses the same cell in program 1, and their corresponding character in program 2 are `a'` and `b'`, then `a'` and `b'` must access the same cell)
* Assume that all branches are reachable (that memory is corrupted or something). (you can't assume that there's no unreachable code, however)
---
### Formal definition
Define the set `S` to be the set of strings that consists of only the characters in `.,<>+-[]`, the `[]` forms matching pairs, and between every pairs of matching `[]` there's an equal number of `<` and `>`.
Let `s` be a string. Then define `value(s) :: String -> Integer` = (number of `>` in `s`) - (number of `<` in `s`).
Consider a string `A` in `S`, where the number of characters in `A` and not in `<>` is `n`.
Consider an injective function `f :: Integer -> Integer`. There exists exactly one shortest string `A'` such that:
* There are exactly `n` characters in `A'` not in `<>`, and the corresponding characters in `A` and `A'` have the same value.
* For each corresponding character `a` in `A` and `a'` in `A'`, let `p` be the string formed by concatenating in order all the characters before the character `a` in `A`, and define `p'` similarly, then `f(value(p)) == value(p')`.
Given the string `A`, you have to find the shortest string `A'`, for all possible functions `f`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 239 bytes
```
s=>(x=[],i=n=s.length,s.map(t=>t<'<'|t>'>'?x.push([i,t]):i+=t<'>'?1:-1),f=(r,i=0)=>{2*n in r?(i=n,y='',x.map(([j,t])=>y+=((j=r[j]-i)<0?'<':'>').repeat(j>0?j:-j,i+=j)+t),s[y.length]&&(s=y)):i>2*n||f(r,i+1,r.includes(i)||f([...r,i]))},f``,s)
```
[Try it online!](https://tio.run/##LY5BboMwEEWvklU8LoMFXVLG7HIJCymImMQWMch2KlDp2amJuv3/z3tju@8u9N7MMXfTTe8X2gNJWEi1aMhREKN29/jAIJ7dDJFkrFnNtiiZZM0i5ld4gDIYW16ZjFKZ4rLKS44DgU@MgpP8@fxwJ@NOvoEExZUYw@UNBGWPW5JrRgCWvLJtbnhdNMlSJRgXXs@6i2Bl0dgqt5g0lmeRY1Dr/3ft@QyBVp5@kEm1bcOhzkr0wrh@fN10AMOPWAkhUtVy/ovD9YqB71/95MI0ajFOd7i8FwylRJZG@x8 "JavaScript (Node.js) – Try It Online")
Badly golfed
```
s=>(
x=[],
i=n=s.length,
s.map(t=>t<'<'|t>'>'?x.push([i,t]):i+=t<'>'?1:-1), // pack each []+-,. into (pos,instr)
f=(r,i=0)=>{
2*n in r?(
i=n,y='',
x.map(([j,t])=>y+=((j=r[j]-i)<0?'<':'>').repeat(j>0?j:-j,i+=j)+t), // generate instr
s[y.length]&&(s=y)
):
i>2*n||f(r,i+1,r.includes(i)||f([...r,i])) // r be all rearrangements of [0,2n]
},f``,s
)
```
] |
[Question]
[
A set of dominoes consists of tiles with two numbers on them such that every combination of integers from 0 to N are represented. Examples below refer to N=6 out of convenience, but N=9 and N=12 are also common. The orientation of the tiles does not matter (they are usually printed with dots rather than digits), so `[1-6]` and `[6-1]` refer to the same tile, of which there is only one in a set.
Most games played with dominoes involve players taking turns adding dominoes to a line of those already played onto the table, such that one of the numbers on the new domino is placed adjacent to the same number at one end of the line on the table. Thus, you might add a `[2-5]` to either end of an existing line of `[2-3][3-3][3-5]`, producing `[5-2][2-3][3-3][3-5]` or `[2-3][3-3][3-5][5-2]`.
Many such games require "doubles", dominoes with two of the same number on them, to be placed perpendicular to the other dominoes connected to them. Aside from scoring which we are unconcerned with here, this has no effect except when...
Many of those games then allow the "line" to fork at some or all doubles. Five Up is such a game where the line can fork into 3 new lines at each double, so all four sides of a double might have a matching domino attached.
Here is an example layout of dominoes from a "double 6" set in a game of Five Up (where A|B or A-B is a single domino):
```
4
-
0
3|0 0|0 0|2
0
-
1
4|1 1|1 1|6
3
1 -
- 6
5
6
6|5 5|5 5|0 0|6 - 6|2 2|1
6
5
- 6
4 -
4
```
Your task is to take an list of dominoes in the order in which they were added to the table, and determine whether or not this order represents a legal game of Five Up.
You can write a whole program that takes input from stdin, or a function that takes input as one or more parameters.
Canonical input would be a list or array of two-tuples of integers. A list of lists, array of arrays, vector of tuples, etc are all valid forms in which to take input, as would be a string representing any of the above, or multiple strings. The input will only contain pairs of non-negative integers, valid dominoes.
Output should be a truthy or falsey value, for valid and invalid games respectively.
Your code should accept arbitrarily large domino numbers, within the capabilities of the maximum integer values of your language.
Examples:
* `0-6` is valid, as is any other single domino
* `0-6 6-0` is not valid, there is only one `0-6` domino in a set
* `6-6 6-5 5-3 3-0` is valid, a simple linear arrangement
* `6-6 6-5 3-0 5-3` is not valid, there is no `3` or `0` in play for the third domino to connect to prior to the `5-3` being played
* `1-1 1-2 1-3 1-4 1-5 1-6` is not valid, all four open `1` ends are used up leaving nowhere to connect the `1-6`
* `1-1 1-2 1-3 1-4 1-5 3-6 1-6` is valid, the 3-6 connects to the 1-3, then the 1-6 can connect to the 3-6
* `5-5 5-4 5-0 0-6 6-6 6-4 6-2 2-1 6-3 5-1 1-1 1-6 4-1 1-0 0-0 2-0 3-0 0-4` is valid, the above illustrated example
* `12-12 12-1 3-12 3-1 1-2 3-3` is valid, uses larger dominoes, and has an ambiguous placement
NOTE: The function required here is not a perfect check for valid Five Up games. We are ignoring here the rules about which domino gets played first, which would require more information about the variant of the game and number of players, and would disqualify a significant minority of inputs.
[Answer]
# [Haskell](https://www.haskell.org/), ~~188~~ ~~174~~ 168 bytes
```
f(p:r)=[p]!r$p?p
(s!(p:r))o|b<-[p,reverse p]=or[(q:s)!r$q%o|q<-b,elem(q!!0)o,all(`notElem`s)b]
(s!_)o=1<3
p@[x,y]?r=[c|x==y,c<-p]++r
p@[x,y]%(a:r)|a/=x=a:p%r|z<-y:r=p?z
```
[Try it online!](https://tio.run/##jY8/T8MwEMX3fAqnolKiOuA0f4YoVlnYYGK0LOqmKUSk8cUJVYvy2QmO6yIQDCxP57vn37t7Ed1rWdfjuPMgUz5lwF11BStwvM41LV8OmzxggFV5KFVXIuBUKua1WedrazuXQ5sHG1zW5d5rXZf4Eou69taN7O90b935Gz7RnnxJwzxy4JYd8YmvFGXFcKT0hIs8AL5YqMto7gkdPIgbeqQig7ka3vPglCkKq/fxIOpqiyhiDmKM4JRzPFWprrDWRGuCI60RJnYW4lC/Q7w0GhmNjSbGl5r6QkosIzZKtBLLPmtsdGItDTc1xMRmhJaFWWzrM4EYP7F7TZ2Ycwdxp2p@XJR@Jf6@6/wzCaJ/3WUumhL2omo0fisdBG/9Y6/uGzQzodnMQXsBD8gDVTU9ukY7H5nJd6vd8E/zZfvxo9jV4rkbgwLgEw "Haskell – Try It Online") Usage example: `f [[6,6],[6,5],[5,3],[3,0]]` yields `True`.
### Ungolfed:
```
f :: [[Int]] -> Bool
f (p:r) = check [p] (double p p) r
check :: [[Int]] -> [Int] -> [[Int]] -> Bool
check seen open [] = True
check seen open ([x,y]:r) =
notElem [x,y] seen
&& notElem [y,x] seen
&& (elem x open && check ([x,y]:seen) (update [x,y] open) r
|| elem y open && check ([y,x]:seen) (update [y,x] open) r)
double :: [Int] -> [Int] -> [Int]
double [x,y] rest =
if x==y
then [x,y] ++ rest
else rest
update :: [Int] -> [Int] -> [Int]
update [x,y] (a:rest) =
if x==a
then double [x,y] (y:rest)
else a : update [x,y] rest
```
[Try it online!](https://tio.run/##jVPBToNAED27X/HiwUDcGmqBA0k9mHgw0ZPeyB7WdrFEChugpiR@u7g7u1Wxxnh5mZ15897MEDaye1FVNY4Fsgx5flv3QmB2heumqViBQGdtiCVWG7V6Qa4FgnWze6oUNHSIljFXmTZTRMEPQUfulKrRaAO5MNqP7U4dVYJ8zwfhzNkJUDf9TaW2oDTxGICzs6/CwPeTQqBseu/kzNs5eF3LCxHs9Fr2yotaolkJtv/tDaD@4ajf@vzsJ2/fHzLmT2SP8nmJSXBgOONWdb1d0/iiLLBfLgf36Df2RsQ5P3c0yquqU/RkzE/wh9Vkx0Bmti@c2slvdpPJgsHTv2wlMkwkLWF8lVW5NqI5M9884qkQ3EapibjBxGDCFwYXPPK1OZ@b95xfEi4IY8KEeCnFB6XEa8SEkcHIazuMCa3WJemmpJh4j7nX4nnsY6cQET/yc9lMLASDYGU92Sj9dDzey3Ums8W/9qKNrMNWlrWRXzcMetc/9O1djVMyzU4ZtlLfm5@vLeseFyhCUOU71U/4K/kw/fi@Kir53I2zldYf "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 224 bytes
```
function(L,x=c(),y=c()){o=T
z=length
if(z(L)){p=sort(L[1:2])
w=rep(p,2-(p[2]>p[1]))
x=rbind(p,x)
if(z(y)){m=match(p,y,0)
v=which.max(m)
if(m[v]>0){y=y[-m[v]]
w=w[-v]}}
y=c(y,w)
L=L[-1:-2]
o=o&f(L,x,y)&!sum(duplicated(x))}
o}
```
[Try it online!](https://tio.run/##rVDLboMwELz7KyiHyCstFRDIIZLzBRx7c62IEhyQwkNgHk7Et1MbWvUHehnN7szsrrZbk6tiGY0xRifGyIKPjo8ndE47RBZCdEIMLDtai2HBDsYS7WyL@dZn4LiXEZDkKv93/qb@zSeSrXKoM1U2NU1wNssAtUV4NeyDPNkjr@@qIKWkT5qYbsv6plM04cE5FEAm1uUtbTH0aMtDcWl5IADIzLqvsr4ZYYY9q022YlWqssJ0NfpARjYVZVa8V@lMq81W8VFcfHhpprlnC2EWTNwbxbIQe5bGyTyFJdwLzl4oSMOag7SHo4bDWz9U9Da0jzJLVX6jM8BCmmU1FXVVN@RnF435qgDdz9oFsgkyffS/ivxR1m8 "R – Try It Online")
The code receives the pieces as an ordered list and returns TRUE or FALSE according to the specs. The function recursively scans every piece, adds the piece to an index to verify the absence of duplicates, and keeps track of the available insertion points to check that the piece can effectively be added to the stack. The handling of piece connections (e.g. attaching a 1-2 by the 1 or by the 2) is done in a greedy fashion, so it is not entirely impossible that some weird configurations may blow up.
] |
[Question]
[
*(Inspired quite heavily by [this challenge](https://codegolf.stackexchange.com/questions/137066/zippered-paragraph))*
In the original challenge you were to make a horizontal zipper, however, looking down at my hoodie, my zipper is much more vertical (and a little bit broken) :P
**Input**
You will be given a single string (`s`), and a pair of integers (`a` and `b`) in any format. Where:
`a < (length-of-s / 2)`
`b <= ((length-of-s / 2) - (a + 1)) / 6`
**Output and Scoring**
Your program may be a full program or a function that produces a single string with the correct formatting or an array (one item per line) you choose. Leading and trailing spaces and newlines are optional as long as the characters of the output all line up. eg.
```
["f r"],["u e"],["l p"],["l p"],["y i"],[" o z "],[" p n "],[" e "]
```
or
```
"f r\nu e\nl p\nl p\ny i\n o z \n p n \n e "
```
are acceptable outputs for test case 1
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden and the shortest code in bytes wins.
Any answer with no explanation will not be able to win.
**Explanation**
To make a zipper you must first remove any whitespace or newline characters from the string. And then fold it in half like so (see test case 1 for more)
`abcde fgh ij klmnopqr` becomes the two strings below, notice the second half is reversed.
`abcdefghi` and `rqponmlkj`
Then starting at the beginnning of each string we place the same indexed character from each substring onto one line with the spacing determined as follows:
```
[0] a r -- (a-3) five spaces
[1] b q -- (a-2) three spaces
[2] c p -- (a-1) one space
[3] d -- (a)
[4] o
[5] e
[6] n
etc...
```
That makes the base for our zipper. Now the integers `a` and `b`.
`a` is the location of our zip. To determine where the zipper is located we use the index of our output lines as the point to close our zip. eg the square bracketed `[3]` in my above example is where the zip is.
Before our zipper reaches a close, the above zipper must remain at a five space gap until it reaches `a-2` where it closes to 3 spaces and `a-1` where it closes to 1 space. Just to be clear, in the above example `a = 3` (0-indexed)
---
`b` is the number of holes in my zipper. To create a hole in the zip, we split the string out again with some spacing.
Starting with the index of the example hole as `h` we increase the spacing of `h-1` to one space, `h` to 3 spaces and `h+1` back to one space, leaving `h-2` and `h+2` with just one character per line as they are counted as part of the hole.
After the zip and between each of the holes there must be a gap of one character so our zip looks fully connected between holes.
You get to choose the indexes of the holes, but they must all be present within the 'closed' section of the zipper.
```
Again using 'abcdefghi' and 'rqponmlkj'
[0] a r -- (open)
[1] b q -- (closing)
[2] c p -- (closing)
[3] d -- zip
[4] o -- gap
[5] e -- start of hole (h-2)
[6] n f -- one space (h-1)
[7] m g -- three spaces (hole h)
[8] l h -- one space (h+1)
[9] k -- end of hole (h+2)
[10] i -- gap
[11] j
```
I'm hoping that all makes sense, if not ask away. In anticipation of questions, you may notice that the character `p` in my second example is present in the second substring, however, appears at the beginning of its line, this is intended, you must follow the sequence of 1-2-1-2-1-2, taking a character from each half in-turn regardless of its position in the output.
**Test Cases**
```
"fully open zipper", 7, 0 | "fully closed zipper", 0, 0
fullyope reppizn | fullyclos reppizde
|
f r *Note: i particularly like this | f
u e example as it shows the reversing | r
l p of the second half of the string | u
l p causes the words to wrap from top | e
y i left to the bottom and back up | l
o z the right side | p
p n | l
e | p
| y
| i
| c
| z
| l
| d
| o
| e
| s
```
* Column 1: "stupidly long unbroken zipper that shouldnt exist on any decent hoodie", 24, 0
* Column 2: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris faucibus molestie mi. Aliquam nec fringilla ipsum", 15, 5
:
```
s e | L m
t i | o u
u d | r s
p o | e p
i o | m i
d h | i a
l t | p l
y n | s l
l e | u i
o c | m g
n e | d n
g d | o i
u y | l r
n n | o f
b a | r c
r n | s
o o | e
k t | i
e s | n t
n i | m a
z x | a m
i e | u
p t | e
p n | q
e | t
d | i
r | ,
l | l c
t | A o
u | . n
h | i
o | s
a | m
h | e e
t | c i
s | t t
| e
| s
| t
| s
| u
| l
| r
| o
| a
| m
| d
| s
| i
| u
| p
| b i
| i s
| c c
| u
| i
| a
| n
| f
| g
| s
| e
| i
| l r
| i u
| t a
| .
| M
```
**EDIT: Added Test Cases**
```
"abcde fgh ij klmnopqr","3","1"
a r
b q
c p
d
o
e
n f
m g
l h
k
i
j
```
[Answer]
# PHP 7.1, ~~421 412 218 195 192 191~~ 195 bytes
```
for([,$s,$a,$b]=$argv;$i-$k<strlen($s=strtr($s,[" "=>""]));$p=0)for($t=++$y>$a-2?$y>=$a?$y>$a?$b-->0?_4_4_4_31_23_31:_4:_31:_23:_15;$c=$t[$p++];)echo$c<_?str_pad("",$c).$s[++$f&1?$i++:$k-=1]:"
";
```
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/d62b8b0502ff594a60f0068b8138404f113638c0).
Prints a leading, but no trailing newline and one leading space in each line.
] |
Subsets and Splits