text
stringlengths 180
608k
|
---|
[Question]
[
Write a **`Notes and Crosses`** application.
User interface is optional.
You can output the computers move in text: eg `1x1` (meaning center square)
The computer must play an intelligent (extra marks for optimal) game.
Apart from its first move which should be random.
Player computer take turns at first move.
First player to win two games in a row wins.
Score:
* Lowest strokes wins.
* If equal best computer move algorithm (as I see fit)
* If equal submitted date.
[Answer]
c99 -- 1229 characters (and needs nucrses)
```
#include <ncurses.h>
#include <string.h>
#define R return
#define A char
#define M mvprintw
#define I int
#define O "%c wins a game, press any key to %s."
A*s=" XOCHT";FILE *r;
I W(A*b){I i,p,q,r,w[]={0,1,2,0,3,6,0,2,3,3,3,1,1,1,4,2};if(!memchr(b,0,9))
R 3;for(i=0;i<16;i++){p=w[i/2];q=w[i/2+8];r=i%2+1;if((b[p]==r)&&(b[p+q]==r)
&&(b[p+q+q]==r))R r;}R 0;};
I C(A*b, I s){A c[9];for(I i=0;i<9;i++){memcpy(c,b,9);if(c[i]==0)c[i]=s;
if(s==W(c))R i;}R -1;};I P(A*b){I i;while(b[i=fgetc(r)%9]);R i;};
I D(A*b){A*p=" |-+";I i=0,j;for(;i<5;i++)for(j=0;j<5;j++)
mvaddch(i,j,p[2*(i%2)+j%2]);for(i=0;i<9;i++)mvaddch(2*(i/3),2*(i%3),
b[i]?s[b[i]]:'1'+i);refresh();};
I G(A m){I u=1,i,j;A b[9];memset(b,0,9);M(1,9,"Computer %c",s[m]);M(2,9,
"Human %c",s[m%2+1]);do{M(4,9,"Up %c",s[u]);D(b);if(u==m){if((i=C(b,m))<0&&(i=C
(b,m%2+1))<0)i=P(b);b[i]=m;}else{do{M(6,0,"your move ");refresh();scanw("%d",&i
);}while(i>10||i<1||b[i-1]!=0);b[i-1]=m%2+1;};u=u%2+1;}while(0==W(b));M(8,0,O,
s[W(b)],"continue");D(b);getch();M(8,0,"%44c",*s);R W(b)==3?5:u==m?4:3;}
I main(I c,A**v){A d=0, m=v[1][0]-'x'?2:1;r=fopen("/dev/random","r");
initscr();for(;;){c=G(m);if(c==d&&c-5)break;else M(4,25,"Previous winner %c",
s[c]),d=c;m=m%2+1;}M(9,0,O,c,"quit");getch();endwin();}
```
It gives away characters for the users convenience by using curses and having actual English prompts and informative lines. The obvious macro golfs have been made, but there are probably some comma and conditional operator improvements still available.
Is it smart? Well, it takes one move wins and blocks one move losses, but is otherwise quite random. (I may take the weekend to repair my interrupted CS education and learn about A\* trees...) The "random first move" condition is met automatically as no one has the option to win at that point. Despite this obviously deficient AI I have yet to beat it when it holds X, so I have not defeated it by the "two in a row" rules.
Structurally we have a *"is there a winner"* function and a *"can I win with a single play"* function which works by coping the board and trying each position in turn with the `isWon` function. The single `canWin` function serves first to search for winning opportunities (by passing the computer's symbol) and then to search for things than need blocking (by passing the human's).
It declares `C`omputer, `H`uman, or `T`ie the winner on each game and only `C` or `H` for the series.
**Now respects the spec as to winning conditions** And plays well enough that you have to let it win or Ctrl-C to get out.
The version below differs from the above in prompts as well as macroization, but still represents the approach.
```
#include <ncurses.h>
#include <string.h>
char*s/*ymbols*/=" XOCHT";
FILE *r/*dev/random*/;
/* return the index of the side that wins, 0 if un-won or 3 if cat's game */
int W/*on*/(char*b){
int i,p,q,r,w/*inning matrix*/[]={0,1,2,0,3,6,0,2,
3,3,3,1,1,1,4,2};
if(!memchr(b,0,9))return 3; /* detect cat games by lack of open positions */
for(i=0;i<16;i++){
p=w[i/2]; /* starting position of the winning sequence to check */
q=w[i/2+8]; /* step size of the winning sequence to check */
r=i%2+1; /* winning value to check */
if( (b[p]==r) &&
(b[p+q]==r) &&
(b[p+q+q]==r) )
return r;
}
return 0;
};
/* returns the first square in which the current side can win or -1 if none*/
int C/*an win?*/(char*b, int s/*ide to play*/){
char c[9];
for(int i=0;i<9;i++){
memcpy(c,b,9);
if(c[i]==0)c[i]=s;
if(s==W(c))return i;
}
return -1;
};
/* returns a random unoccupied square */
int P/*ick a random move*/(char*b){
/* assumes a move is possible and will loop forever if this
condition is violated */
int i;
while(b[i=fgetc(r)%9])
;
return i;
};
int D/*raw the board*/(char*b){
char*p=" |-+";
int i=0,j;
for(;i<5;i++)
for(j=0;j<5;j++)
mvaddch(i,j,p[2*(i%2)+j%2]);
for(i=0;i<9;i++)
mvaddch(2*(i/3),2*(i%3),b[i]?s[b[i]]:'1'+i);
refresh();
};
/* Play a single game with the computer taking s[m] and return the winner
*
* 3 -- computer
* 4 -- human
* 5 -- tie
*/
int G(char m){
int u/*p*/=1,i,j;
char b/*oard*/[9];
memset(b,0,9); /* initalized to 0 (empty) */
mvprintw(1,9,"Computer uses %c",s[m]);
mvprintw(2,9,"Human uses %c",s[m%2+1]);
/* main loop */
do {
mvprintw(4,9,"To play %c",s[u]);
D(b);
if(u==m){
// my turn to move
if( (i=C(b,m))<0 && /* move to win */
(i=C(b,m%2+1))<0 ) /* 2%2+1 == 1, 1%2+1 == 2 so, the other side */
i=P(b);
b[i]=m;
} else {
// user's turn
/* get user selection */
do {
mvprintw(6,0,"your move:\n");
refresh();
scanw("%d",&i);
} while (i>10||i<1||b[i-1]!=0);
b[i-1]=m%2+1;
};
u=u%2+1; /* Here u is switched to the *next* player, so if the
game is one u denotes the *loser* */
} while(0==W(b));
/* Print out the winner */
mvprintw(8,0,"%c wins a game, press any key to continue.",s[W(b)]);
D(b);
getch();
mvprintw(8,0,"%44c",*s);
return W(b)==3?5:u==m?4:3;
}
/* first argument is required and expected to be x or o
*
* x always goes first
*/
int main(int c,char**v){
char d=0, /* previous winner, starts on an impossible value */
m=v[1][0]-'x'?2:1; /* select my symbol by index into s */
/* /dev/random intialization */
r=fopen("/dev/random","r");
/* curses intialization */
initscr(); /* start curses */
for(;;){
c=G(m);
if (c==d&&c-5) // same *player* wins two in a row
break;
else
mvprintw(4,25,"Previous winner %c",s[c]),d=c;
m=m%2+1;
}
mvprintw(9,0,"Final winner is %c, press any key to quit.",c);
getch();
endwin();
}
```
[Answer]
## Bash, 591 670, 812 (excluding `#!/bin/bash`)
x is computer. x goes first and then alternates with o for each new game. x never looses so game ends when x wins twice in a row.
UI is a simple 3x3 board. Positions are numbers from 0 to 8. Occupied positions are x's or o's. x (now) plays a boring game. Although x never looses, it will randomly pick between a set of best moves to be a little bit interesting.
The code:
```
W()for q in 1 28 55 3 12 21 4 20;{ [[ w**3 -eq B[f=q/8]*B[g=q%8]*B[g+g-f] ]]&&$r;}
B(){ local -i p R t=9 S;for((;p<9;p++)){ [[ B[p] -eq p ]]&&{ B[p]=w;W&&$e 98&&$r $p;R+=S[B[p]=p]=98-$(M+=-1;w=w^3;B);t=$((S[p]<S[t]?t:p));V=R/M;};};$e $V;$r $t;}
T()(for q in {1..9};{ $e -en ${P[B[q-1]]}${N[q%3]};};W=${P[w^=3]};q=$([ $w = 9 ]&&for((;B[q]!=q;)){ read -sn1 -p? q;}&&$e $q&&$r;[ $M = 9 ]&&$e $RANDOM||(B>1;$e $?))%9;B[q]=w;M+=-1;$e $W..$q;W&&$e $W!&&$r $w;[ $M = 0 ]&&$e Ty||T);P=({0..8} o x);N="\n";e=echo;r=return;declare -i V=49 q w=9 M=9 B=({0..8});for((;(J&(J=K))<9;w^=3)){ T;K=$?;};$e Won
```
I have just noticed that I use W as a function and variable. Bash does not seem to mind.
Dialogue is minimal:
```
? means it is waiting for o to play.
means it is thinking about next move.
x! means X wins.
Ty means a Tie.
W determines if $w won.
```
It uses a code in $q to identify lines of positions to test. Let a line of positions be F, G, and H. Code is 8F+G. H can be derived from F and G: H=G+(G-F). eg. From 28, F=3, G=4, H=5. If board positions B[F]+B[G]+B[H]=3\*w then $w has won
```
B $1 finds best move for player $1.
T controls a game and gets user move if $w is 0 or computer's move.
```
Full source code:
```
# Players
# o is opponent
# x is computer
# Player symbols are stored in Player array.
# Board B has 9 board positions numbered 0 to 8
# 0-8=unoccupied
# 9=o in position
# 10=x in position
# Winning line encoding
# if a winning row is positions f,g, and h then these are encoded as f*8+g
# h is derived as g+(g-f)
Win()
for q in 1 28 55 3 12 21 4 20;{ # for each code
[[ w**3 -eq B[f=q/8]*B[g=q%8]*B[g+g-f] ]] && return # w won if 3 in row
}
# F=49
# F sets a resolution for determining value of a move.
# Since AVG=sum(Score[*])/M then larger scores mean better fixed point real number.
# Score is 0 to 2F. Larger F, larger score accuracy.
# F is set to largest number such that 2F is 2 digits.
# A move probability to win is returned in AVG.
# AVG=0 o wins this move (if they play rationally)
# AVG<F means o more likely to win
# AVG=F means most likely a tie
# AVG>F means x more likely to win
# AVG=2F means x wins
# p must be integer or it does not get initialised to 0
# R must be integer and it gets initialised to 0
# t needs a starting default value of 9 if there are no empty positions
Best(){ # here we have to silently play lots of games to choose best move
local -i p R t=9 Score # save board and move count
for((; p<9; p++)){
[[ B[p] -eq p ]] && { # empty position
B[p]=w # occupy it
Win && echo 98 && return $p # if w won then restore board, set score to 2F
R+=Score[B[p]=p]=98-$(M+=-1; w=w^3; Best) # restore board, inc move & what is opponents best move?
t=$((Score[p]<Score[t]?t:p)) # if score is better then restart list with this position
AVG=R/M # average scores
}
}
echo $AVG # set score
return $t # return first best position
}
# Take Turns.
# Starting with other player (w^3), take turns and count down remaining turns.
# Get a move from opponent or computer. Ensure opponent move is legal.
# If there is a winner, return winner (9=o 10=x).
# If game over, return tie (0)
# Else take next turn
# Changes w, W, M, B, p
Turn()(
for q in {1..9};{
echo -en ${Players[B[q-1]]}${N[q%3]} # show position or player and newline every 3rd
}
W=${Players[w^=3]} # W is symbol of other player
# if o, get move. else if game start, random move. else get best move for x
q=$([ $w = 9 ]&&for((;B[q]!=q;)){ read -sn1 -p? q;}&&echo $q&&$r;[ $M = 9 ]&&echo $RANDOM||(Best>1;echo $?))%9
B[q]=w # move and occupy board position
M+=-1 # dec move count
echo $W..$q # show move
Win && echo $W! && return $w # w has won
[ $M = 0 ] && echo Ty || Turn # return 0 tie after 9 moves and no winner or another turn
)
# Play a game.
# Board can be configured as you like. Ensure M represents number of moves remaining.
# AVG is used by Best to return value of best move.
# Loop for competition to declare winner after 2 wins in a row.
# Turn returns 9=o win, 10=x win, and 0=tie
# w is non-starting player: 9=o 10=x
# w swaps between 9 and 10 for subsequent games
# AVG is a global used to calculate/store average value of a move.
# Since Best() is called in a subshell, it will always be 49.
# q is a globally used integer
# M is number of moves remaining. Starts at 9 and when 0 board is full and game over.
Players=({0..8} o x); N="\n";e=echo;r=return
declare -i AVG=49 q w=9 M=9 B=({0..8}) # player=H, empty board, 9 moves to go
for((; (J&(J=K))<9;w^=3)){ # start with X (9^3); while tie or not 2 in a row
Turn
K=$? # K=who one
}
echo Won # I should cheat and just say x won to save more characters
```
[Answer]
# Javascript 271
This is not a real entry in this competition, but i just wanted to share this interesting algorithm with the other (potentional) competitors.
```
b=[[8,8,8,8],[8,0,0,0],[8,0,2,0],[8,0,0,0]]
m=[2,2]
for(n=0;n<4;n++){
i=prompt(m).split(",")
r=+i[0]
c=+i[1]
b[r][c]=1
if(!b[r][c+1]){b[r][c+1]=2;m=[r,c+1]}
else if(!b[r][c-1]){b[r][c-1]=2;m=[r,c-1]}
else if(!b[r-1][c]){b[r-1][c]=2;m=[r-1,c]}
else{b[r+1][c]=2;m=[r+1,c]}}
```
It takes input of the form `r,c` where r is the row and c is the collumn, and it outputs in the same format. It does not output the last move since it's not a choice. This algorithm is
sooooo simple that you can probably implement it in less than 100 chars if you do it right! It works as follows:
1: The computer takes the first move `(2,2)`
2: The user makes any move
3: The computer checks if he can make a move on the square to the right of the user, if he can't he checks for the left, if he can't he checks for the square above and if he still can't he puts it on the square below.
4: Go to step 2
Try to beat it!
[Answer]
# Java 1801 1691 1467
So yeah, this is definitely a revival, but as a new participant on codegolf I hope you won't hold it against me.
**Edit:** Changed from multidimensional array to single dimension array, also stripped out a bunch of unnecessary parenthesis. Next step will be to write a different "brain" for the computer. Even as it is, although not perfect, it does pretty well. I'm probably going to set up a version that has the computer play itself, for kicks. When I do, you can find it in [my github](https://github.com/ProgrammerDan/tic-tac-toe-golf).
**Edit2:** Replaced `q` and `b` methods with a single `d` method that performs all the work of `q` and `b` based on a flag passed in that chooses the "mode", `1` for win or block (prior `q` method), `0` for future-move-win choice (prior `b` method). Saved more than two hundred characters, hurray.
I spent some time golfing in Java, and this is what I came up with:
```
import java.util.*;class W{public static void main(String[]a){(new W()).t();}void p(String k,int i){System.out.print(k+(i<1?"":"\n"));}int[]M;int P;int c(){int m,a,b,i;for(a=b=i=0;i<3;i++){a=M[i*3];b=M[i];m=a==M[i*3+1]&&M[i*3+1]==M[i*3+2]&&a>0?a:b==M[i+3]&&M[i+3]==M[i+6]&&b>0?b:0;if(m>0){return m;}}m=M[4];return M[0]==m&&m==M[8]||b==m&&m==a?m:0;}void g(){for(int i=0;i<9;)p(w(M[i]),i++%3/2);p("",1);}int x(int i){return(new Random()).nextInt(i);}String w(int i){return(i<1)?".":((2*i-3)*P<0)?"X":"O";}int y(){return(new Scanner(System.in)).nextInt();}void Z(){int i;do{i=x(9);}while(!s(i,1));}int o(int a,int b,int c,int z,int x){return a==b&&c==x&&a==z?2:a==x&&b==c&&b==z?0:a==c&&b==x&&c==z?1:-1;}int d(int z,int y,int k){int i=0,j;for(;i<3;i++){if((j=o(M[i*3],M[i*3+1],M[i*3+2],z*k,z*(1-k)))>=0?s(k>0?i*3+j:i*3+2-j/2,y):(j=o(M[i],M[i+3],M[i+6],z*k,z*(1-k)))>=0?s(k>0?i+3*j:i+(2-j/2)*3,y):0>1)return 1;}if((i=o(M[0],M[4],M[8],z*k,z*(1-k)))>=0?s(k>0?i*4:8-(i/2)*4,y):(i=o(M[2],M[4],M[6],z*k,z*(1-k)))>=0?s(k>0?i*2+2:6-(i/2)*2,y):0>1)return 1;return 0;}void z(){if(!(d(1,1,1)>0||d(2,1,1)>0||s(4,1)||d(1,1,0)>0))Z();}boolean s(int i,int z){if(M[i]<1){p(w(z)+" to "+i%3+","+i/3,1);return(M[i]=z)==z;}return 0>1;}void t(){while(1>0){M=new int[9];int m=9,x;if(x(2)<1){P=1;Z();g();m--;}else P=-1;do{do{p("x?",0);x=y();p("y?",0);}while(!s(y()*3+x,2));m--;g();x=c();if(x>0||m<1)break;z();g();m--;x=c();}while(m>0&&x<1);if(x<1)p("No winner!",1);else p(w(x)+" wins!",1);}}}
```
Ungolfed, with comments (and perhaps some longer variables/method names):
```
import java.util.*;
public class TicTacToeGolf {
public static void main(String[] args) {
(new TicTacToeGolf()).start();
}
/** Wrap System.out.print to avoid all that typing */
void p(String k, int i){
System.out.print(k +((i<1)?"":"\n"));
}
/** Game board */
int[][] gg;int P;
/** Check all possibilities for winner, return 0 for no winner, 1 for X, 2 for O */
int c(){
for(int[]i:gg)
if((i[0]==i[1])&&(i[1]==i[2])&&i[0]>0)
return i[0];
for(int i=0;i<3;i++)
if ((gg[0][i]==gg[1][i])&&(gg[1][i]==gg[2][i])&&gg[0][i]>0)
return gg[0][i];
int m=gg[1][1];
return (((gg[0][0]==m)&&(m==gg[2][2])||(gg[0][2]==m)&&(m==gg[2][0]))?m:0);
}
/** Print game board */
void g(){
for(int[]i:gg){
for(int j:i)
p(w(j),0);
p("",1);
}p("",1);
}
/** Generate a random value */
int x(int i) {
return (new Random()).nextInt(i);
}
/** Convert 1 to X, 2 to O */
String w(int i) {
return (i<1)?".":((2*i-3)*P<0)?"X":"O";
}
/** Get a number from the input */
int y() {
return (new Scanner(System.in)).nextInt();
}
/** Pick the next move for the computer */
void Z() {
int i,j;
do{
i=x(3);
j=x(3);
}while(!s(i,j,1));
}
/** Check for win or board condition for player z based on an ordered set of values a,b,c having one space with player x */
int o(int a, int b, int c, int z, int x) {
return (a==b&&c==x&&a==z)?2:(a==x&&b==c&&b==z)?0:(a==c&&b==x&&c==z)?1:-1;
}
/** Check for win over rows, cols, and grids for user z, place for user y based on findings.
* Means will block z if z != y */
int q(int z,int y){
int i=0,j;
// check for win or block
for (;i<3;i++){
j=o(gg[i][0],gg[i][1],gg[i][2],z,0);
if (j>=0){s(i,j,y);return 1;}
j=o(gg[0][i],gg[1][i],gg[2][i],z,0);
if (j>=0){s(j,i,y);return 1;}
}
i=o(gg[0][0],gg[1][1],gg[2][2],z,0);
if (i>=0){s(i,i,y);return 1;}
i=o(gg[0][2],gg[1][1],gg[2][0],z,0);
if (i>=0){s(i,2-i,y);return 1;}
return 0;
}
/** Check for placement options over rows, cols, and grids for user z, place for user y based on findings.
* Means will block z if z != y */
int b(int z,int y){
int i=0,j;
// check for placement or block
for (;i<3;i++){
j=o(gg[i][0],gg[i][1],gg[i][2],0,z);
if (j>=0){s(i,2-j/2,y);return 1;}
j=o(gg[0][i],gg[1][i],gg[2][i],0,z);
if (j>=0){s(2-j/2,i,y);return 1;}
}
i=o(gg[0][0],gg[1][1],gg[2][2],0,z);
if (i>=0){s(2-i/2,2-i/2,y);return 1;}
i=o(gg[0][2],gg[1][1],gg[2][0],0,z);
if (i>=0){s(2-i/2,i/2,y);return 1;}
return 0;
}
/** Pick the next move for the computer, smartly */
void z() {
// Check for win
if (q(1,1)>0)return;
// Check for block
if (q(2,1)>0)return;
// check for best
if (s(1,1,1))return; // try to take center.
// take whatever would win the subsequent turn if the other person is stupid.
if (b(1,1)>0)return;
Z(); // take anything.
}
/** Check if move is possible, if so do it, otherwise return false */
boolean s(int i, int j, int z){
if (gg[i][j]<1){
p(w(z)+" to "+j+","+i,1);
return (gg[i][j]=z)==z;
}
return 0>1;
}
/** Play the game, Computer gets first move. */
void start() {
while(true){
gg = new int[3][3];
int moves=9,x;
if (x(2)<1) { // Computer starts.
P=1;
Z();
g();
moves--;
}else P=-1;
do{
do{
p("x?",0);
x=y();
p("y?",0);
}while(!s(y(),x,2));
moves--;
g();
if (c()>0||moves==0)
break;
z();
g();
moves--;
}while(moves>0&&c()==0);
if(c()<1) p("No winner!",1);
else p(w(c()) + " wins!",1);
}
}
}
```
**Some usage notes:**
* 50/50 chance for who takes first turn.
* Move of "X" or "O" announced before displaying the game board.
* Choice of cell is specified as column, then row, indexed from 0.
* Entering something outside `[0,2]` will cause a index exception and end the game.
* If computer goes first, takes a random move (no preference for any board location).
* Computer will take one move wins, block one move losses, plays conservatively (prefers center if available), tries to set up a two-turn win (hope other player doesn't block), and if that fails? Picks a random spot. So doesn't play a perfect game, but plays a great game. I can force a win due to the random start possibilities, but computer will force a win as well if I start badly.
* Wins are detected immediately.
* Impossible-to-win is *not* detected; you must play every game to the end or let the other player win.
* At the end of each game, a new game begins, again with a randomly chosen starting player.
* Took a few hits to character length by including a usable UI.
* Use `Ctrl+c` to end.
Example game (with computer starting, so first placement is random):
```
$ java W
X to 1,2
...
...
.X.
x?1
y?1
O to 1,1
...
.O.
.X.
X to 2,2
...
.O.
.XX
x?0
y?2
O to 0,2
...
.O.
OXX
X to 2,0
..X
.O.
OXX
x?2
y?1
O to 2,1
..X
.OO
OXX
X to 0,1
..X
XOO
OXX
x?0
y?0
O to 0,0
O.X
XOO
OXX
X to 1,0
OXX
XOO
OXX
No winner!
```
There's definitely room for improvement. One place is likely replacing the multi-dimensional array with a one-dimensional array*(done)*, and replacing the more complex decision logic with either a reduced form of the same*(done)*, or a more concise best-choice solver.
Play around with it and let me know what you think. I've got this [hosted over on my github](https://github.com/ProgrammerDan/tic-tac-toe-golf) so feel free to fork, clone, and create pull requests with improvements.
] |
[Question]
[
[What does "jelly" mean in the title?](https://www.cyberdefinitions.com/definitions/JELLY.html). [Cop's thread](https://codegolf.stackexchange.com/q/222477/66833)
Robbers, you are to choose an uncracked Cop answer, and attempt to find a Jelly program which is:
* shorter than the Cop's answer
* solves the linked challenge, according to the rules of the challenge
So long as these two bullet points are met, your answer cracks the Cop's.
The user with the most cracks wins.
## Example submission
```
# 8 bytes, cracks [ChartZ Belatedly's answer](<link to answer>)
“3ḅaė;œ»
[Try it online!][TIO-kmrxlphk]
[TIO-kmrxlphk]: https://tio.run/##y0rNyan8//9RwxzjhztaE49Mtz46@dDu//8B "Jelly – Try It Online"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes, cracks [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/222489/80214)
```
“¡ẉḟUHġ[4A»ŒVw⁾SuNXṛ⁸
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4oCcwqHhuonhuJ9VSMShWzRBwrvFklZ34oG@U3VOWOG5m@KBuP// "Jelly – Try It Online")
Takes the return value of `time.ctime()`, finds `Su` in it, and negates the value. On a Sunday, this passes -1 to `X` (random number function), causing an error. Otherwise it passes 0 to `X`, not erroring. then final return value is forced to be the empty string `⁸`, so it will print nothing.
] |
[Question]
[
Every so often I have a function of type `a -> b` and a function of type `b -> b -> c` and I would like a function of type `a -> a -> c`. For example if I wanted to check the second element of each two tuples were equal
```
snd :: (a , b) -> b
(==) :: Eq a => a -> a -> Bool
```
And I want something of type
```
Eq b => (a, b) -> (c, b) -> Bool
```
The best way I have found to do this so far is
```
f g z=(.g).z.g
```
Which is ok, but it feels unneccessarily complex for something that is this simple.
The pointfree representation is even worse:
```
flip=<<((.).).(.).flip(.)
```
Additionally it feels like this idiom should be representable with some sort of abstraction (it feels a lot like `(<*>)`). I attempted to find a replacement by abstracting our functions to functors, the result is not very enlightening
```
flip=<<(fmap.).fmap.flip fmap ::
Functor f => f a -> (a -> a -> b) -> f (f b)
```
Is there a shorter way to express this idea? Particularly the pointfree version?
[Answer]
Stumbled upon this question in the related questions list of [How to golf a fork in Haskell?](https://codegolf.stackexchange.com/q/233116/78410). Now that I have a better understanding of combinator golf, I gave it a try.
Primer: Haskell supports a few combinators including the standard S, B, C, K, I:
```
-- I
id = \x -> x
-- K
pure = \x y -> x -- 1 byte shorter than `const`
-- S
(<*>) = \x y z -> x z (y z)
-- B
(.) = \x y z -> x (y z)
-- C
flip = \x y z -> x z y
-- Variations of S
(>>=) = \x y z -> y (x z) z
(=<<) = \x y z -> x (y z) z
liftA2 = \f g h x -> f (g x) (h x) -- part of latest Prelude
```
Now, there are two possible forms to convert to pointfree:
```
v1 :: (b -> b -> c) -> (a -> b) -> (a -> a -> c)
v1 f g x y = f (g x) (g y)
v2 :: (a -> b) -> (b -> b -> c) -> (a -> a -> c)
v2 f g x y = g (f x) (f y)
```
The following are all the various reductions I tried (along with typechecking):
```
import Control.Applicative
type On a b c = (b -> b -> c) -> (a -> b) -> a -> a -> c
fref :: On a b c
fref g h x y=g(h x)(h y)
f1 :: On a b c
f1=(flip flip<*>).(.).((.).)
f2 :: On a b c
f2 z g=(.g).z.g
f3 :: On a b c
f3=(flip=<<).(.).((.).)
f4 :: On a b c
f4=liftA2(.)(flip(.)).(.)
f5 :: On a b c
f5=((.).(flip(.))<*>).(.)
type On2 a b c = (a -> b) -> (b -> b -> c) -> a -> a -> c
fref' :: On2 a b c
fref' g h x y=h(g x)(g y)
f1' :: On2 a b c
f1' g=((.g).).(.g)
f2' :: On2 a b c
f2'=liftA2(.)((.).flip(.))(flip(.))
f3' :: On2 a b c
f3' g z=(.g).z.g
f4' :: On2 a b c
f4'=(.).(.).flip(.)<*>flip(.)
f5' :: On2 a b c
f5'=(.).(.).q<*>q;q=flip(.)
f6' :: On2 a b c
f6' g=(.g).((.g).)
f7' :: On2 a b c
f7'=r<*>r;r=(.).flip(.)
f8' :: On2 a b c
f8'=s<*>s;s x=(.)(.x)
```
[Try it online!](https://tio.run/##ZZHNjoIwEIDvfYqJF8om20TEn6g1MV432cM@AbK0kq2Abd2IL89OQRG6B6bN9Osw8/WUmJ9MqabJz1WpLRzKwupSsX1VqTxNbP6bEWLrKoPPAhI4Qgoc6BHed9CGNHSRJm2i3Sd9SInQmYD1ur/bJSSc4AY1lxTXEEMdEjEdc1NOhcorcGH7tgsZZfi5gGw0ZiO4g@SUyZDdmSRiNj6edaX4djuuEo@xmKtc2H2Epy2Pa8sTMR@Dc95W6KFne72n6CVq4OWfNF9U0P0mGqgKelcnKp0r2bnyUUxI1xUacK1I58hnomAwoBvg2X8/CKryL81cB/eB29gn4oC3Nl4F0cdjh658fP7CLwheNhfewwsfXgTPd33MRsTSZ5YB11hIbzQf9EDEygdXATcImo2Bm0Mpu4XNOckLfKfqar@s/igmh/Jc5Sr7BnNN08wYcVWqnjR/ "Haskell – Try It Online")
Unfortunately, the shortest unnamed lambda version is the same as OP's of
```
\z g->(.g).z.g
```
at 14 bytes, supporting both versions (just swap `g` and `z` in the argument list for the alternative version).
The shortest pointfree solution I could find was
```
(flip=<<).(.).((.).)
```
at 20 bytes (which has the type of `v1`), which is 5 bytes shorter than OP's. For `v2`, I got two different 25 byters.
The reduction steps to reach this one:
```
\f g a b -> f (g a) (g b)
\f g a -> B (f (g a)) g
\f g -> C (\a -> B (f (g a))) g
\f g -> C (B (B B f) g) g
\f g -> (=<<) C (B (B B f)) g
\f -> (=<<) C (B (B B f))
((=<<)C).B.BB
(flip=<<).(.).((.).)
```
[Answer]
I think eta-reduction is severely overrated. I see a lot more attempts at eta-reduction in the wild than I think is reasonable.
So it is in this case: eta-reducing this function is not helpful, I think. It's much more readable and elegant in its full form:
```
f :: (a -> a -> c) -> (a -> b) -> b -> b -> c
f g h a b = g (h a) (h b)
```
---
On a related note, such function exists in the standard libraries. [It's called `on`](https://www.stackage.org/haddock/lts-14.18/base-4.12.0.0/Data-Function.html#v:on), and the idea is to use it in infix form, so that it almost reads like English:
```
eqAmounts = (==) `on` amount
cmpNames = compare `on` name
```
] |
[Question]
[
# Can this container hold this much liquid?
### Challenge Synopsis
As you most likely know, [liquids](https://en.wikipedia.org/wiki/Liquid) have an indefinite shape and a definite volume. As such, they always take the shape of their container. They cannot, however, expand to fill their container.
Your job today is to determine whether or not a certain amount of liquid (represented by a certain number of `L` characters or numbers representing the volume of the part, as per suggestion) can fit into a container of a certain size (represented by a matrix of `C` characters) with some amount of empty space (represented by space characters) within it. The container will always have `C` characters all the way around the perimeter.
Your program will return a [truthy/falsey value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) based on whether the liquid will fit into the container. It will only fit if there is an area of connected empty space (made up of spaces adjacent to one another horizontally, diagonally, or vertically) within the container for each part of the liquid that is separated from the rest (either by a space or by two newline characters).
### Test Cases
```
LLL
L
----- True
CCCCC
C CC
C CC
CCCCC
LLL
LL
------ True
CCCCCC
C C C
C CCC
CCCCCC
L L
LLL
----- False (Not enough space)
CCCCC
CCCCC
C CC
CCCCC
LL
------ False (Spaces are not connected but liquid is)
CCCCCC
CCCC C
C CCCC
CCCCCC
L L
------ True
CCCCCC
CCCC C
C CCCC
CCCCCC
L L
------ True (There is a pocket of empty space which holds both parts of the liquid)
CCCCCC
CCC C
CCCCCC
CCCCCC
L
L
------ True (There is a pocket of empty space for each part of the liquid)
CCCCCC
CCCC C
C CCCC
CCCCCC
L L L LL
------ True
CCCCCCCCC
CCCC C C
C CCCCCCC
CCCCCC CC
CCCCCCCCC
L
L
----- True
CCCCC
CCCCC
C CC
CCCCC
```
*Feel free to suggest test cases!*
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
* Standard loopholes are disallowed.
[Answer]
# Snails, 58 bytes
Input is taken exactly as in the examples.
```
t\ t\L{t\L?t\ z!.o=(\ ,\C},!(tz(\L!.!~|\ !.o=(\ ,\C},!(t\L
```
A 4 bytes longer version is fast enough to instantly complete the test cases ([Try this version online](https://tio.run/##K85LzMwp/v/fPo6rJEahJManGogT7IHsKkW9fFuNGAWdGOdaHUWNkiqNGB9FPcW6mhgFNJkYn///fXx8uHy4dEGAyxkEuJwVFBAkWAQA "Snails – Try It Online")):
```
?^
t\ t\L{t\L`?t\ z!.o=(\ ,\C},!(tz(\L!.!~|\ !.o=(\ ,\C},!(t\L
```
An indented formatting of the latter:
```
?^
t\
t\L
{
t\L`?
t\
z!.
o=(\ ,\C
},
!(tz(
\L!.!~
|
\ !.o=(\ ,\C
},
!(t\L
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 313 bytes
```
import StdEnv,Data.List
?v=nub[v:[[sum s:k]\\s<-subsequences v|s>[],k<- ?(difference v s)]]
$v m#p=[[(x,y)]\\x<-[0..]&l<-m,y<-[0..]&' '<-l]
=or[and(zipWith(>=)(s++[0,0..])r)\\r<- ?v,s<-permutations(map length(foldl(\p _=nub[sort(nub(e++[(x,y)\\(u,v)<-e,x<-[u-1,u,u+1],y<-[v-1,v,v+1]|(m!!x)!!y<'C']))\\e<-p])p p))]
```
[Try it online!](https://tio.run/##dVJda9swFH2Of8VNWhaJyCEZ7MXYLSPdQyDQQQZ7kM1QHDkVlWTPktVk5LfPk5ymK4PJL/fj3HvOPbiUnOle1ftOclBM6F6opm4tbO3@i3bkgVk23whjo3uX6W5HXUKp6RSY5LnIc5PGptsZ/rPjuuQG3Nnc0YI8pzHco72oKt6GBjgwuCiiWwfqpskoRUdywn7@mMZ0MZ8XH2QaK3K6ZlOYprEsoqxuKdN79Es034V9QncZRmY2owsSYLjFed4GKke8kIa3qrPMilobpFgDkuuDH6pquZcob@DHcIDx1yEfIO4XDTryHHXE4TTmJOjp4iXpSDdbFoMg51NHnE/PSI3HRzwen9LpalpgP8g9bYEbaDAu@qqtFWxPxnI1Xz/Cq5FJsn4kcOB2IzQnwB2T68dowH7jR3uFlZIZM1SQaaSwmIDQxrLg3oDb2lboQxRtLfPwl2h0A4jqTu14axLpd5uCwAuGLHB9ljLQmYDLvBE2Go1cLTvlSxkM7th6rS3UMLDBBCYYXrd5bFlr638G3no0pSXkOZSQxgkEoiKkIfAVuDBHI6HhFq4Ub@NR9I8YL1oOPgxKL2ZczQn982VxlsFk4nV4rXQ4623S/O9IREP7nRP9EsL3MVpd3xCBfz6C97VVSP/ifpeVZAfTx@tN/3DSTInyknyVzFZ1q/r4qf@0WKg/ "Clean – Try It Online")
Defines the function `$ :: [Int] [[Char]] -> Bool`. TIO link includes a wrapper around STDIN.
`? :: [Int] -> [[Int]]` is a helper to generate the different ways the volumes can be combined.
Expanded:
```
$ v m // in function $ of v and m
# p // define p as
= [ // a list of
[(x, y)] // lists of pairs (x, y)
\\ // for each
x <- [0..] // index x
& l <- m // at list l in m
, // for each
y <- [0..] // index y
& ' ' <- l // at spaces in l
]
= or [ // true if any of the list of
and ( // true if all of
zipWith // element-wise application of
(>=) // greater than or equal to
(s ++ [0, 0..]) // permutation s padded with zeroes
v // list v of volumes
)
\\ // for each
s <- permutations ( // permutation s of
map length ( // the lengths of
foldl // a left-fold of
(\p _ // function on p discarding second argument
= nub [ // the unique elements of the list of
sort ( // sorted versions of
nub ( // unique lists composed of
e // list e of points in a region
++ [ // prepended to the list of
(x, y) // pairs (x, y)
\\ // for each
(u, v) <- e // pair (u, v) in list e
, // for each
x <- [u-1, u, u+1] // x-coordinate adjacent to u
, // for each
y <- [v-1, v, v+1] // y-coordinate adjacent to v
| // where
(m!!x)!!y < 'C' // the character in m at (x, y) is a space
]
)
)
\\ // for each
e <- p // region e in p
]
)
p // applied to a starting argument of p
p // recursively, for each element in p
)
)
]
```
] |
[Question]
[
# Introduction
Write a program to calculate the partial derivative of a polynomial (possibly multivariate) with respect to a variable.
# Challenge
Derivatives are very important mathematical tools that has been widely applied in physics, chemistry, biology, economics, psychology and more to handle all kinds of problems. Expressions with multiple variables are also very common.
In the scope of this challenge, a polynomial string ("polystr") is defined by the following [BNF](https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form) (Backus–Naur form):
```
<polystr> ::= <term> | <term><plusminus><polystr>
<plusminus> ::= "+" | "-"
<term> ::= <coeff> | <coeff><baseterm> | <baseterm>
<baseterm> ::= <variable> | <variable><exponent> | <baseterm><baseterm>
<coeff> ::= positive_integer
<exponent> ::= positive_integer
<variable> ::= lowercase_ASCII_letters
```
Where `positive_integer` and `lowercase_ASCII_letters` are quite self-explanatory.
For example, The string `3x2y-x3y-x2y+5` means `3*(x^2)*y-(x^3)*y-(x^2)*y+5`. The terms given in the input may appear in any order, and the variables in each term also may appear in any order. So for example `5-yx2-x3y+y3x2` is also a valid input and is in fact the same as the previous example.
The rule for taking partial derivative is just doing it term by term. If the variable appears does not appear in the term, the derivative is zero. Otherwise, the coefficient of the term is multiplied by the exponent of that variable, and then the exponent of the variable is decreased by one. The exponents for other variables do not change. This is just following the definition in mathematics. In addition, if the resulting exponent is zero, remove the variable from the term.
For example, to take the partial derivative of `5z-z2y2-5w3y` with respect to `y`. The following process is done (in accordance with the BNF defined above, the "coefficient" are all taken to be positive numbers, i.e. the signs are considered separately)
```
5z - z2y2 - 5w3y
Coeff 1->1*2=2 5->5*1=5
Expon 2->2-1=1 1->1-1=0
Term - 2yz2 - 5w3
(y is not here (expon 0->y removed)
so the term is 0)
```
The result is `-2yz2-5w3y`.
On the other hand, if the above expression is taken partial derivative with respect to `a`, the result is `0` because `a` is in none of the terms.
Your task is to write a function or a full program to calculate this derivative. It should take a polynomial string and a single character (the variable to take derivative with respect to), and return the derivative in the simplest form.
"Simplest form" means three things.
1. The number `0` (not the digit) should not appear in the output unless the output itself is just `0`. So neither `0+10y` nor `3-y0z` will be valid output and should be transformed to `10y` and `3-z`, respectively.
2. The number `1` should not appear as an exponent or a coefficient, but can appear as a standalone term itself.
3. The terms with exactly the same set of variables and exponents should be merged, which means `3a2b5-4b5a2` is not a valid output, and it should be `-a2b5` instead. More information about the input and output can be found in the "Specs" section.
# Test Cases
```
Input
Output
2xy+4ax-5+7mx4-4-7x4m, x
2y+4a
4upv+5u2v3w4-4w4u2v3+qr-v,v
4up+3u2v2w4-1
12ux-7x2m3+ab5,q
0
-a+10ca11y-1nv3rt3d-poly, a
-1+110ca10y
1y+1x3y, y
1+x3
```
# Specs
* Input can be taken through [standard forms](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). In other words, you can take input as a string, a list of characters, a nested array of coefficients, variables (possibly denoted by their ASCII value minus 'a' or something alike) and exponents, etc. You are also free to change the string to `2*x^3y^2` or alike instead of `2x3y2`.
However, please do not use the input `[2,0,0,0,1,0,0,3,0,0,...0]` (an array of 27 elements) for the term `2dg`, or any other verbose format that enumerates the 26 letters like this. Your input format should also be able to treat `ab` and `ba` as different inputs (so the 27-element array format is invalid due to this restriction as well).
* Each variable (letter) will only appear once in each term of the input, that means `xx` will not appear and will always be presented as `x2`, nor will something like `a3b4a2` appear.
* To reiterate, the terms in the input may appear in any order.
* You are also free to choose the output format provided that the verbose format mentioned above is avoided. The output should however always be in the simplest form as defined above. Just like the input, the terms in the output can appear in any order, and the variables in each term can also appear in any order and does not have to be consistent between terms. That means `pu+2up2` is a valid output. The sign for the leading term can be either positive or negative and `-y+3x` and `3x-y` are both valid, so is `+3x-y`.
* The input are always given such that all the coefficients and exponents in the output will be less than 232-1, or the largest integer your language can handle, whichever is smaller. Claiming that the largest integer your language can handle is unreasonably small and trivializing the challenge falls into the category of default loopholes.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
**Edit:** Since most of the answers so far turn out to be internals that do the whole challenge, and despite knowing there are builtins I don't have the intention to ban such internals from the very beginning, nor do I have now. I will make the winning criteria one that is based on a per-language basis, i.e. the submission with the least bytes in each language wins in that language. I will add a standard snippet for a catalogue if there are enough submissions. Feel free to go on submitting builtins to showcase the power of your language but please do not hesitate to submit your non-builtin answers even if it's way longer and your language does not have a builtin. Happy code golfing in your favorite language!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~252~~ 245 bytes
```
o,d=input()
D={};s=''
for c,t in o:T=`sorted(t)`;D[T]=D.get(T,0)+c
for t in D:
c,t=D[t],dict(eval(t))
if(d in t)*c:e=t[d];c*=e;t[d]=e-1;s+=('%+d '%c)[:~((-2<c<2)*sum(t.values())>0)]+''.join((v+`t[v]`*(t[v]>1))*(t[v]>0)for v in t)
print s or'0'
```
[Try it online!](https://tio.run/##bZLdcqMgFMev41Mw6XQAkUzQZDo1JXuTJ@j0jpAJUdO6k6gVNB87u6@eBU3bbWa9QDjn9z@cD6qTeSuL8HIpg5TnRdUYhL0F//V7pjmE3rasQRIYkBegjF/4Wpe1yVJk8Hq2EC@SL0avmUEvwRiTpIM7dBF7TsUXwsggzRODslbtrAp7IN@i1DEG@0mccSNSOUt8ns3cjmeUzTThCN6TFMD7BIv4D0I0fEqeQuzrZo/MyIZqMo0wno@xJBCOfpZ5gVBL1ka0cu0j95szjK@7MXaJtf2lXlXnhQEalDUcw0u@r2xFoM68NNuCStU6QxrHLk2gBWVylGu1q94UwrHNCzJ4dY1lUbpaISUwtq0ikGgPmGxf8Tob6WaDaoiWKUY/uFD0LDEMarhkPgwGg8EdeFSAz8Gjr7zBF96DVwWhH5oVc6I7oDZOo1Zs4w0A@I/MXndVXAVRL4gc/01BiRUsFz3@@sTmbBnCQGP7WR3tkqNMea6ieq9dSdu8SNVuh6ATi5VdCAxcvXamz1xID3Tjt3jXaCezbXTNgj7se9VZY7fYTvq2k90jceeRrna5QdYYMBsPGC7aD9sK/jO/LxDbyK3sWaECO1S0wdKRKth0rHM@E@t1vgQHRlpLnZmmLsCz5w2Hw@tj6McOp2d6Dk8hnR6iE8QBPMHv/vB4IhN1pFPysD9O6IQ@HCd7Bx5vwElTtWTahG10sNhh4nbkvaatg9sbmIXN0UYK9xFRm6kj3m8IqggbJ4qxE2VFG9UmSmlV7roc1W20E2HHz/RtiRchpgEQAp5hAJiU0h4o@7SE7mxRt@t9PX2wlujT53TSRfwL "Python 2 – Try It Online")
Takes input as a nested list of coefficients and terms:
```
[
[coeff1, [[var1_1,exp1_1],
[var1_2,exp1_2],
... ]
],
[coeff2, [[var2_1,exp2_1], ...]],
...
]
```
For instance the first example (`5z-z2y2-5w3y`) is given as:
```
[
[ 5, [['z', 1] ] ],
[-1, [['z', 2], ['y', 2]] ],
[-5, [['w', 3], ['y', 1]] ]
]
```
The footer contains a function which parses a string input to the desired input format: `parse(s)`.
---
Edit:
* Takes input instead of function
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~249~~ 233 bytes
```
(.)(?=.*¶\1$)
$&_
L`.\w*
G`_
^\b
+
%O`._?\d*
_\d+
*
\b[a-z]
1$&
\b(\d+)(?=.*?(_+))
$1*$2
O$`(.)_+(.+)
$2$1
+`((\+|-)_+)(.*)¶\2(_+\3)\b
$1$4
+`\+_(_*(.*)¶-)_(_*\2\b)
+$1$3
G`\b_
\b_+
$.&
_(__+)
$.1
^\+|¶|(.)__|._
$1
\b1([a-z])
$1
^$
0
```
[Try it online!](https://tio.run/##JY5BbsIwEEX3cwoWBtme2GJsI1ZVlt1U4gB1cZzSRaVCAUFwqpyLA3CxdNLuvv78ef@fPy6fh0zjXDbVrIbHfZRWyfrJ6sc9klAgFgleGhtvGp6bBNvYAsJ809hUx52GFHcIGmL7ms3PG5BYsJZs/kNqmVAxhLRwsBENwxNKi2w5QYCNlBEHw6aSVivudPwRveIaQSJwImKSSf9fOcg6utgqQL573hTbxJUJQdgF8DlNcEu8FIfHfZga02AT4zhG8m/ntAi2Apbj6EqPIRezwvW@BBPMuoR9NSsQrscOV1fX@RvbtzApPJ1NV3VA7lo46PYec7uqTmAy0vI9E/WGDp0/X/zOHL@/@mqWgXqk4ln2vw "Retina – Try It Online") Link includes test cases. Explanation:
```
(.)(?=.*¶\1$)
$&_
```
Add a `_` after each occurence of the given variable.
```
L`.\w*
```
Split the input into terms.
```
G`_
```
Keep only the terms that referenced the variable.
```
^\b
+
```
Prefix a `+` if the first term doesn't have a sign.
```
%O`._?\d*
```
Sort each term alphabetically. (The sign matches, but that's not a problem; it sorts at the start anyway.)
```
_\d+
*
```
Convert all exponents of the variable into unary.
```
\b[a-z]
1$&
```
Temporarily prefix 1 to those terms without a multiplier.
```
\b(\d+)(?=.*?(_+))
$1*$2
```
Multiply the multiplier by the exponent of the variable, leaving the result in unary.
```
O$`(.)_+(.+)
$2$1
```
Sort all of the terms.
```
+`((\+|-)_+)(.*)¶\2(_+\3)\b
$1$4
```
Add terms of the same sign.
```
+`\+_(_*(.*)¶-)_(_*\2\b)
+$1$3
```
Subtract terms of different signs.
```
G`\b_
```
Remove terms that were cancelled by a term of a different sign.
```
\b_+
$.&
```
Convert the multiplier back to decimal.
```
_(__+)
$.1
```
Decrement exponents greater than three and convert back to decimal.
```
^\+|¶|(.)__|._
$1
```
a) Remove a leading `+` sign b) Join all the terms back together c) convert squares of the variable to the plain variable d) remove the variable if it didn't have an exponent.
```
\b1([a-z])
$1
```
Remove the temporary 1 unless it's no longer got anything to multiply.
```
^$
0
```
If there were no terms left then the result is zero.
Supporting duplicate terms cost almost half of my byte count. Previous 123 byte solution that didn't deduplicate terms:
```
(.)(?=.*¶\1$)
$&_
L`.\w*
G`_
_\d+
*
\b[a-z]
1$&
\b(\d+)(?=.*?(_+))
$.($1*$2
_(__+)
$.1
^\+|¶|(.)__|._
$1
\b1([a-z])
$1
^$
0
```
[Try it online!](https://tio.run/##JYxBDoIwEEX3c44JmbahcbAuDUs33sDKgNGFG6NESmI4FwfgYnXQ3X8veb@/ve@PjnMmb6jee7vMkdEAFgLH1sfRwqEVkHh1YCFeTl35OQNjoZtU/qOaxBmNPCFbrEBIVCgzNNFNyzzpvcjkBZC1ZPr9mJUahE3OYXgmtxuqtB1DGcawLvfqywTpCw "Retina – Try It Online") Explanation:
```
(.)(?=.*¶\1$)
$&_
```
Add a `_` after each occurence of the given variable.
```
L`.\w*
```
Split the input into terms.
```
G`_
```
Keep only the terms that referenced the variable.
```
_\d+
*
```
Convert all exponents of the variable into unary.
```
\b[a-z]
1$&
```
Temporarily prefix 1 to those terms without a multiplier.
```
\b(\d+)(?=.*?(_+))
$.($1*$2
```
Multiply the multiplier by the exponent of the variable.
```
_(__+)
$.1
```
Decrement exponents greater than three and convert back to decimal.
```
^\+|¶|(.)__|._
$1
```
a) Remove a leading `+` sign b) Join all the terms back together c) convert squares of the variable to the plain variable d) remove the variable if it didn't have an exponent.
```
\b1([a-z])
$1
```
Remove the temporary 1 unless it's no longer got anything to multiply.
```
^$
0
```
If there were no terms left then the result is zero.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 20 bytes
-1 byte thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)!
```
ToExpression@#~D~#2&
```
[Try it online!](https://tio.run/##TY1BC4IwAIXv/YpQ6PDmoNnEU9Ch7h26mYNhSkJTm3PNi399aVB0eQ8e38dT0txLJU1dSF/tr/7Snlyny76v2@YQTscpjDf@rOvGZFUWxHAYCYeEowlJoeAEp5ymS0MF0drl@eqHcwzoYEmCQcSwYofXgi/5XcgTmtogsv8elYRtUUAKxjBShuYja5g5b7RDiwfG@U3muX8D "Wolfram Language (Mathematica) – Try It Online")
The input is formatted so that every term follows `coeff * var1 ^ exp1 * var2 ^ exp2 ...`. If the input can be taken as an expression rather than a string, the solution is 1 byte: `D`.
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 3 bytes
```
∂
```
This doesn't use any new feature. `∂` and its ASCII-only alternative, `Differentiate` have been introduced [more than 10 days ago](https://github.com/Mr-Xcoder/Physica/commit/d325b08ccb2e1ee262559816ecfa7088eaa5d550#diff-c166cc077ccd5b6bcd48a262d7860d7dL50).
# Demo
Assumes that both the expression and the variable are passed as a string. Testing code:
```
f = ∂
Print[f['2*x*y+4*a*x-5+7*m*x^4-4-7*x^4*m'; 'x']]
Print[f['4*u*p*v+5*u^2*v^3*w^4-4*w^4*u^2*v^3+q*r-v'; 'v']]
Print[f['-a+10*c*a^11*y-1*n*v^3*r*t^3*d-p*o*l*y'; 'a']]
```
Exact output:
```
4*a + 2*y
4*p*u + 3*u**2*v**2*w**4 - 1
110*a**10*c*y - 1
```
Expression format: `*` for multiplication, `**` for exponentiation, `+` and `-` for addition and subtraction accordingly.
[](https://i.stack.imgur.com/K9ssB.gif)
[Answer]
# [Python 3](https://docs.python.org/3/) + [SymPy](https://pypi.python.org/pypi/sympy/1.1.1), 23 bytes
```
from sympy import*
diff
```
[Try it online!](https://tio.run/##VcvRCsIgAIXh@z3F7tyOCbk5dtWrCNKQBjnNnOnT2wwKuvkPHPhcDje7jaVob037zMbldjXO@oBGX5ZV6@L8uoVOd2RAQqYCColNdIZBkoIJNteFIaeWJNL3zQ8I7HCIdMIuB0Q54lVB7fehD3gWK41/lCnKz7hCSc6RGcf28R7h6MIcLO7I1anDlTc "Python 3 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 5 bytes
```
deriv
```
[Try it online!](https://tio.run/##TYtBCsMgFAX3PYXL@PRDTA1Z5SqCJE0RmtRKYvX0thYC3cyDx4y3wdHdl4WNrMy34GLxwW17szQdErLQsEjUiwErktGkaaiLVbLE@eWUNQ54RNHjMB2iueJd5crzES8EipLFv4ysUC0mWKMUMilsvzZg/3ImjyceyJJZzssH "Pari/GP – Try It Online")
] |
[Question]
[
[This challenge](https://codegolf.stackexchange.com/q/139034/47581) posed an algorithm for encoding an integer `n` as another integer `r`. What follows is a succinct explanation of that algorithm, using `n=60` as an example.
**The original algorithm**
* First, we encode the number as a string of brackets.
+ If `n = 1`, return an empty string.
+ Otherwise, we take `n`'s prime decomposition sorted ascending and replace each element with its prime index (1-indexed) in brackets. `60 = 2*2*3*5 => [1][1][2][3]`
+ Do this recursively until all we have are brackets. `[1][1][2][3] => [][][[1]][[2]] => [][][[]][[[1]]] => [][][[]][[[]]]`
* Once we have our string of brackets, we convert that into an integer with the following process.
+ Convert each opening bracket to a `1` and each closing bracket to a `0`. `[][][[]][[[]]] => 10101100111000`
+ Remove all trailing `0`s and the final `1`. `10101100111000 => 1010110011`
+ Convert the final string of `0`s and `1`s from binary to an integer. `1010110011 => 691`
**Decoding this encoding**
An interesting property of this algorithm is that it is *not* surjective. Not every integer can be the result of this encoding.
* Firstly, the binary representation of the result `r`, must be `balance-able` in that the number of `0`s must never exceed the number of `1`s. A short falsey test case is `4`, which is `100` in binary.
* Secondly, the brackets in the binary representation must be `sorted ascending` when the final `1` and trailing `0`s are appended once more. A short falsey test case is `12 <= 1100 <= 110010 <= (())()`.
However, just determining if a number is decode-able in this way would make for a short challenge. Instead, the challenge is to **repeatedly decode** a given input until either an un-decode-able number or a cycle is reached, and returning the resulting **sequence** of numbers.
**The challenge**
* Given a number `1 <= r <= 2**20 = 1048576`, return the **sequence of numbers** that `r` **successively decodes** into, starting with `r` itself and ending with an un-decode-able number or a cycle.
* If an **un-decode-able number** is given as input, such as `4` or `12`, will return a list containing only the input.
* A sequence ending in a **cycle** should be indicated in some way, either by **appending or prepending a marker** (pick any non-positive integer, string, list, etc. as a marker, but keep it consistent), or by **repeating the cycle** in some way (repeating the first element, repeating the whole cycle, repeating infinitely, etc.).
* On the off chance that any of the sequences are infinite (by increasing forever, for example), consider it undefined behavior.
* This is code golf. Smallest number of bytes wins.
**A worked example of decoding**
```
1 -> 1 -> 1100 -> [[]] -> [2] -> 3
-> 3 -> 11 -> 111000 -> [[[]]] -> [[2]] -> [3] -> 5
-> 5 -> 101 -> 101100 -> [][[]] -> 2*[2] -> 2*3 -> 6
-> 6 -> 110 -> 110100 -> [[][]] -> [2*2] -> [4] -> 7
-> 7 -> 111 -> 11110000 -> [[[[]]]] -> [[[2]]] -> [[3]] -> [5] -> 11
-> 11 -> 1011 -> 10111000 -> [][[[]]] -> 2*[[2]] -> 2*[3] -> 2*5 -> 10
-> 10 -> 1010 -> 101010 -> [][][] -> 2*2*2 -> 8
-> 8 -> 1000 ERROR: Unbalanced string
```
**Test cases**
```
4 -> [4]
12 -> [12]
1 -> [1, 3, 5, 6, 7, 11, 10, 8]
2 -> [2, 4]
13 -> [13, 13] # cycle is repeated once
23 -> [23, 22, 14, 17]
51 -> [51, 15, 31, 127, 5381]
691 -> [691, 60]
126 -> [126, 1787, 90907]
1019 -> [1019, 506683, 359087867, 560390368728]
```
Suggestions and feedback for this challenge are most welcome. Good luck and good golfing!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~379~~ ~~358~~ ~~339~~ ~~337~~ ~~327~~ ~~310~~ 304 bytes
**Conjecture: Is `13` the only number that will lead to a cycle?** (There are no exceptions smaller than 106.)
*Fixed a bug and -7 bytes thanks to [Sherlock9](https://codegolf.stackexchange.com/users/47581/sherlock9).
-3 byte thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
-16 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
-6 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).*
If there is a cycle, it will repeat the whole cycle.
```
def p(a,x=0,n=1):
while a:x+=1;a-=n%x;n*=x*x
return x
def g(a):
c=i=0
for v in a:
c+=int(v)*2-1
if c<0:return 0,0
if c<1:break
i+=1
if a:x=p(g(a[1:i])[0]);b,c=g(a[i+1:]);return(x>c>0)*(0,0)or(x*b,x)
return 1,0
def f(a):
x=a,
while(x.count(a)<3)*a:a,t=g(bin(a-~a)[2:]);x+=a,
return x[:-1]
```
[Try it online!](https://tio.run/##PVDLbsMgELzzFVyqAF5XYLeVikN@xPJhTewEtcIWJSm99NddUJIe9jCrncfO@hPPi2@37TjNdGUIyUjwRnFN6PfZfU4UdaqM6rA2/il1XpgkEqFhipfgaSKFd2JY7q1xRhI6L4FeqfOZSSi1lXE@sisXTa0ydjO1e6nvfAnysVN6DBN@FJj9SFlma7OyrN4r7Qbey4F3I1hTNq5SOsObDksHe5BcsKzHl8CSGCHx/5Qqu5Sc8y1nMgj371h6tssl50O@b7lAjRCz/Og8w/oXed8Uk1xAYTx@7nWthi1OX/GIEU3/AqoBBXlaaFp4VfD2rgZSenClh8elXkOpwsFO72BmjvPtDw "Python 3 – Try It Online")
**Explanation:**
```
def p(a,x=0,n=1): # return the a-th prime
while a: # magical way to enumerate primes
x+=1
a-=n%x
n*=x*x
return x
def g(a): # decode a 0/1 string
c=i=0
for v in a:
c+=int(v)*2-1 # +1 if 1, -1 if 0
if c<0: return(0,0) # c<0: unbalanced parentheses
if c<1: break # first outermost parentheses
i+=1
if a:
x=p(g(a[1:i])[0]) # recursive solve those inside the parentheses ...
b,c=g(a[i+1:]) # and the remaining
if x>c and c: # if not ascending
return (0,0)
return (x*b,x) # return (result, value of first closed parentheses)
return (1,0) # empty string
def f(a):
x=a,
while a and x.count(a)<3: # detect non-decodable or cycle
a,t=g(bin(a-~a)[2:]) # a-~a is a*2+1
x+=a,
return x[:-1]
```
[Answer]
# Pyth, 62 bytes
```
L?b**FKme.fP_Zyd)bSIK1fTseB.u.xyvs@L,"],"\[++JjN2 1m0h-/J1/J00
```
[Test suite](https://pyth.herokuapp.com/?code=L%3Fb%2a%2aFKme.fP_Zyd%29bSIK1fTseB.u.xyvs%40L%2C%22%5D%2C%22%5C%5B%2B%2BJjN2+1m0h-%2FJ1%2FJ00&test_suite=1&test_suite_input=4%0A12%0A1%0A2%0A13%0A23%0A51%0A691%0A126&debug=0)
Indicates a cycle by repeating the final number.
```
L?b**FKme.fP_Zyd)bSIK1 Define y to decode from list format. 0 if invalid.
fTseB.u.xyvs@L,"],"\[++JjN2 1m0h-/J1/J00
.u Repeat the following until it cycles
Collecting the values in a list.
++JjN2 1m0h-/J1/J0 Convert the number to expanded binary
@L,"],"\[ Map 0 to "],", 1 to "["
s Flatten to a string.
v Evaluate as a Python object.
.x 0 If evaluation fails, return 0.
y Otherwise decode.
seB Duplicate the final number
fT Remove all 0s.
```
] |
[Question]
[
The game of Ghost is played between two players who alternate saying a letter on each turn. At each point, the letters so far must start some valid English word. The loser is the player to complete a full word first. So, for example, if the letters so far are E-A-G-L, then the only valid next letter to say is "E" and so the next player will lose. (Even though there are longer words such as "eaglet".)
## The challenge
You are to write a program or function to determine, given the letters so far, who will win assuming two perfect players. The input is a string representing the current state of the game, and a list of strings representing the dictionary of valid words. The output should distinguish whether the next player to go will win or lose.
## Details
* The code must handle the case where the current state is empty. However, you may assume no word in the dictionary is empty.
* You may assume that each input string consists only of lowercase ASCII letters, i.e. a-z.
* You may assume the current state and all words in the dictionary have at most 80 characters each.
* The dictionary is guaranteed to be nonempty (to avoid the case where there is no valid first move).
* You may assume the "current state" will be valid: there will necessarily be some word starting with the current state; also, the current state will not be a full word, nor will any prefix of the current state be a full word.
* The dictionary will be prefiltered according to the rules of which "English words" are considered to be valid for the game - so for example, for a variant in which words of three or fewer letters don't end the game yet, the dictionary will be prefiltered to include only the words of four or more letters.
* You may assume the dictionary will be presorted.
## Examples
Suppose the dictionary is:
```
abbot
eager
eagle
eaglet
earful
earring
```
Then for the following current states, the output should be as follows:
```
Current state Result
============= ======
loss
a win
eag win
eagl loss
ear win
earf win
earr loss
```
Likewise, for the word list at <https://raw.githubusercontent.com/dschepler/ghost-word-list/master/wordlist.txt> (produced on a Debian system using `pcregrep '^[a-z]{4,80}$' /usr/share/dict/american-english`) here is a possible session:
```
Current state Result
============= ======
win
h loss
ho win
hoa loss
hoar win
hoars loss
```
(And then the next move completes "hoarse".)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): Shortest program in bytes for each programming language wins.
[Answer]
# JavaScript, 54 bytes
```
l=>g=w=>!(w+0)||l.some(t=>t==w||!g(t.match(`^${w}.`)))
```
call it like this: f(wordlist\_as\_array)(current\_word\_as\_string), it return true for win, false for lose.
quite bad performance T\_T , only work with the small test case.
```
f=
l=>g=w=>!(w+0)||l.some(t=>t==w||!g(t.match(`^${w}.`)))
```
```
<p><label>Word List:<br/><textarea id="wl"></textarea></label></p>
<p><label>Current:<input type="text" id="c" /></label></p>
<p><button onclick="out.textContent = f(wl.value.split('\n'))(c.value)">Check</button></p>
<p>Result: <output id="out"></output></p>
```
[Answer]
# PHP, ~~192 154 100~~ 98 bytes
```
function t($w,$d){foreach(preg_grep("#^$w#",$d)as$p)if($p==$w||!t($w.$p[strlen($w)],$d))return 1;}
```
function returns `1` for win, `NULL` for loss.
Call with `t(string $word,array $dictionary)`
or [try it online](http://sandbox.onlinephpfunctions.com/code/d2313c8cd84141d5fffd235dde012e7888f28e42).
**breakdown**
```
function t($w,$d)
{
// loop through matching words
foreach(preg_grep("#^$w#",$d)as$p)if(
$p==$w // if word is in dictionary (previous player lost)
|| // or
!t($w.$p[strlen($w)],$d) // backtracking is falsy (next player loses)
)
return 1; // then win
// implicit return NULL
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 135 129 84 bytes
-4 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)!
-42 bytes thanks to [Daniel Schepler](https://codegolf.stackexchange.com/users/73487/daniel-schepler)!
```
g=lambda s,l:(s in l)or-min(g(w,l)for w in{w[:len(s)+1]for w in l if w[:len(s)]==s})
```
[Try it online!](https://tio.run/##XY7BasMwDIbvfgohCNgsKYTdDNmLhBwcansG1Q6WSxilz545bTe2XCR9v6RfWr7KZ4rv2@YHMpf5bIBb0pIhRCCVcncJUXq5tqRcyrBW/baOmmyUrN766UcEguDgtzMNA9/VdrYOiuUiq6nSSw6xSGwYug9oGJsqw63XuIaILXS1osSM99E/FialBMEAiCjMPKcirPE275HsM@5SdlfaU3X3os6eeKFQKETLUo29nsTjBawnSL1q8xeq0wHpP@cDugM/@9s3 "Python 3 – Try It Online")
A `1` indicates the current player will win, whereas a `-1` indicates they will lose.
[Answer]
# C++, 243 bytes (noncompetitive)
FYI, here's the golfed version of my reference implementation (marked as noncompetitive since it's my own challenge). It expects the word list in the `w` parameter to be a null-terminated array (of null-terminated strings). It returns `1` if the next player will lose, or `0` if the next player will win.
```
#define r return
int g(char*s,char**w){struct N{int d=0;N*c[128]{};int l(){if(d)r 0;for(N*p:c)if(p&&p->l())r 0;r 1;}void a(char*s){*s?(c[*s]?:c[*s]=new N)->a(s+1),0:d=1;}N*f(char*s){r*s?c[*s]->f(s+1):this;}}d;for(;*w;d.a(*w++));r d.f(s)->l();}
```
[Try it online.](https://tio.run/##fVPtjqIwFP3PUzQzidMiEt1fG1HmDXwBx5DaFmwGCtsWu7OEZ2fbgoqZ7Dbh9nrv6bmfkqZZFYQMwytlORcMSCCZbqUIuNCggOSCZagif4UGdUrLlmhw6Jyb7tfJISTHzY@fp65PnKmEqOM5pEiCdZLXEh7CZkuQNTWLRbNKrd@7JNgk/bXmFOApBupC9Q7JMVSn962/9oIZcECrFEO13KBovaV7@@oQ5vcnVrx77CrNPWirL1wlfU998CQ0CY0xDM1yiZANSmMLQz6NpB9euSBlSxnY8doWxnCVBg@btXBRzC1XRnQt5xbyHVSxqpZfcwsui1pyfXli55pJ7NnYb6sKMOs3UBEYOw4MSgI/igpzAZ2CZUEmt9OvxxMCXQDsUZput2NCwNDkYRvz3nm9FfxXy7JGy53jOJ7S1ILViDYXXjIAPbBgurQLMf4gXEQWhm6h3MGtroEB@zFGhT9ZNpLfiKGhseJ/GERgCTYoub@8JUqaL2hiGwgixx6TzBrtgjyQNrO4adUlO2PyOaZS1VcGzQ3UB9/K9K1JQStqIxjN7sV5jJZYKLsaFXTUZ1bYrvrgKmaCOtXDXLiMC8WknQ2cUaHontvsHE@Q1EJp8I8WL@wcQTf9s8BUcgL6qYgZ/6xa0Zal5XALcE/fZp4xTC7QTX65ifwGLMeVOC5O0/qY@ZjG@dWtBrudHZcVbx/67dFingNYQBM9ZUGxxnYQ6KnYJ6aXslbqQ7w8iFip2H/whos7vL8VNXVknQR9MODzudYBwwWTTpZslM4k87Z0l9vtYcCDdbivtEK6L3dC/gU)
Expanded and commented version:
```
int g(char* s, char** w) {
/// Node of the prefix tree
struct N {
int d = 0; ///< 1 if the node represents a word in the dictionary
N* c[128] {}; ///< child nodes, indexed by integer value of character
// Optional, if you want to eliminate the memory leak from the
// golfed version. (Though actually in practice, I would make
// "c" into std::array<std::unique_ptr<N>, 128> so the default
// destructor would be sufficient.)
// ~N() { for (N* p : c) delete p; }
/// \retval 1 if the next player going from this node will lose
/// \retval 0 if they will win
int l() {
if (d)
return 0; // last player lost, so the player who would
// have gone next wins
for (N* p : c)
if (p && p->l())
return 0; // found a letter to play which forces the
// other player to lose, so we win
return 1; // didn't find any such letter, we lose
}
/// Add word \p s under this node
void a(char* s) {
*s ?
(c[*s] ?: c[*s] = new N) // use existing child node or create new one
->a(s+1), 0 // the ,0 just makes the branches of
// the ternary compatible
:
d = 1;
}
/// Find node corresponding to \p s
N* f(char* s) {
return *s ?
c[*s]->f(s+1)
:
this;
}
} d; // d is root node of the prefix tree
// Construct prefix tree
for (; *w; d.a(*w++))
;
// Find node for input, then run the "loser" method
return d.f(s)->l();
}
```
] |
[Question]
[
Let's say we have a **n × n** lattice; we can then divide the lattice into two sections by drawing a line through the lattice. Everything to one side of the line is in one set and everything else in another.
How many ways can we divide the lattice in the manner?
For example lets take a **2 × 2** lattice:
```
. .
. .
```
We can make 2 partitions dividing the lattice in half like so:
```
× × × o
o o × o
```
We can also partition off each of the corners:
```
× o o × o o o o
o o o o × o o ×
```
Lastly we can put all of the points in one partition by missing the lattice entirely:
```
× ×
× ×
```
This makes for a total of 7 partitions. Note that the following partition is *not* valid because it cannot be made with a single straight line.
```
× o
o ×
```
Here is a **3 × 3** lattice
```
. . .
. . .
. . .
```
There are 4 purely horizontal or vertical partitions
```
× × × × × × × o o × × o
× × × o o o × o o × × o
o o o o o o × o o × × o
```
There are 4 corner partitions
```
× 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
```
There are 4 larger corner partitions
```
× × o o × × o o o o o o
× o o o o × o o × × o o
o o o o o o o × × × × o
```
There are 8 partitions of partial corners
```
× × 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 × o o
o o o o o o o o o o o × o × × × × o × o o o o o
```
There are 8 knights move partitions
```
× × 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 × × × × o × × × o o o
```
And there is one whole partition
```
× × ×
× × ×
× × ×
```
That makes for 29 partitions in total.
## Task
Given a number **n** as input, output the number of partitions that can be made in this fashion of an **n × n** lattice.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better.
## Test Cases
Here are the first 34 courtesy of the OEIS:
```
1, 7, 29, 87, 201, 419, 749, 1283, 2041, 3107, 4493, 6395, 8745, 11823, 15557, 20075, 25457, 32087, 39725, 48935, 59457, 71555, 85253, 101251, 119041, 139351, 161933, 187255, 215137, 246691, 280917, 319347, 361329, 407303
```
[OEIS A114043](http://oeis.org/A114043)
[Answer]
## JavaScript (ES6), ~~113~~ 111 bytes
*Saved 2 bytes thanks to guest44851*
0-indexed.
```
n=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>x+=(g=(a,b)=>b?g(b,a%b):a<2&&(n-i-1)*(n-j))(i+1,++j)),x=n*++n)|x+x+1
```
Based on the formula mentioned on OEIS:
>
> Let V(m,n) = Sum\_{i=1..m, j=1..n, gcd(i,j)=1} (m+1-i)(n+1-j)
>
> a(n+1) = 2(n2 + n + V(n,n)) + 1
>
>
>
### Demo
```
let f =
n=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>x+=(g=(a,b)=>b?g(b,a%b):a<2&&(n-i-1)*(n-j))(i+1,++j)),x=n*++n)|x+x+1
for(n = 0; n < 50; n++) {
console.log('f(' + n + ') = ' + f(n));
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 116 bytes
```
lambda n:2*(~-n*n+sum((n-i)*(n-j)*g(i,j)for i in range(1,n)for j in range(1,n)))+1
g=lambda x,y:y and g(y,x%y)or x<2
```
[Try it online!](https://tio.run/##XY1BCsIwEEX3PcVshJk0BdNlsDdxE6mJE@y0xArJxqvHIG508xcP/ntb2W@rjNVP53p3y2V2IHZU@BpESf94LogyMKm2kVRA1pH8moCBBZKTcEWj5YPiLyLqTRemrzTrYgs4mSFg0flQqD3yqYX/ZeZItgPYEssOHpnqGw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ạþ`Fgþ`FỊS_²H‘
```
[Try it online!](https://tio.run/##y0rNyan8///hroWH9yW4pYOIh7u7guMPbfJ41DDj////hgYA "Jelly – Try It Online")
## Explanation
```
ạþ`Fgþ`FỊS_²H‘ Input: integer n
ạþ` Form the table of absolute differences on [1, 2, ..., n]
F Flatten
gþ` Form a GCD table on that
F Flatten
Ị Test if the absolute value of each is <= 1
S Sum (Count the number of true's)
_ Subtract
² Square of n
H Halve
‘ Increment
```
[Answer]
# Mathematica, 59 bytes
```
2Sum[(#-i)(#-j)Boole[i~GCD~j<2],{i,#-1},{j,#-1}]+2#^2-2#+1&
```
courtesy of the OEIS (just like the question)
-1 byte from @ovs
[Try it online!](https://tio.run/##y00sychMLv6fZvvfKLg0N1pDWTdTE0hkaTrl5@ekRmfWuTu71GXZGMXqVGfqKOsa1upUZ4HpWG0j5TgjXSNlbUO1/wFFmXkl@g5p@g5BiXnpqdGGBrH/AQ "Mathics – Try It Online")
[Answer]
# Python 2, 90 bytes
```
lambda n:4*n*n-6*n+3+4*sum((n-i)*(n-k/i)for i in range(n)for k in range(i*i)if k/i*k%i==1)
```
] |
[Question]
[
Do you have any [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips for writing in [SOGL](https://github.com/dzaima/SOGL), a golfing language created by [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)?
Your tips should be at least somewhat specific to [SOGL](https://github.com/dzaima/SOGL).
Please post one tip per answer.
[Answer]
# Use the compression creator
[Here](https://dzaima.github.io/SOGLOnline/compression/index.html) is a new, buggy but mostly working online JavaScript compression creator. There, in each line enter a part of the string on each line which closest matches one of:
1. custom dictionary string - this will find the different characters used in the part, store them and store a number in the base of the amount of characters. This is effective for strings like `niooaaoasoioaiaaaoiineeaei` where there aren't a lot of different characters. It also works well for just a single character repeated. This has a limit of 98+(different characters used), and the compressor (currently) doesn't auto-split those.
2. boxstrings - strings with only the characters `/\|_-` and `\n`. Practically the same as custom dictionary strings, but more efficient. Note that this is chooses whether to use `/` and `\` with the same bit, so then custom strings will be used. This has a limit the same as custom dictionary strings.
3. english - this has two word dictionaries, one of length 256 and another of ±65500. This only contains lowercase words and automatically adds spaces between words. To get something like `spaceface` do two parts of `space` and `face`. Each english part has a max of 4 words. If a 4-word part is followed by more english, it adds a space between. Trough the compressor will automatically split the input for you.
**Note:** the dictionary contains only lowercase versions of strings (except `I`, `I've`, and a couple others), so you must correctly case if after usage (using the characters `⁽` - uppercase 1st letter, `⁾` - sentence-case, `ū` - every words 1st letter).
4. ascii - Plain ascii - each part is 1-18 long (trough 1 and 2 are done differently) and auto-splits for you. Approx. 87% compression ratio.
### Other stuff:
* It's always useful to try different combinations and see which is smaller. At the end, it gives you the original and ending byte count and compression ratio. This might be automated sometime in the future.
For example, `-_-_\_/_-` is shorter than
`-_-_\_/_-` and
as different parts
An example input would be
```
row
,
row
,
row your boat
,¶"
```
, which outputs `"π¾⌡īk#S)G⁶⁷λ7&[¶⁶āΡn‘`, after which I can put uppercase 1st letter and remove the starting quote and get `π¾⌡īk#S)G⁶⁷λ7&[¶⁶āΡn‘⁽` for `Row, row, row your boat,\n"`
[Answer]
# Remove unnecessary quotes and brackets
You can remove quotes if the string they're encasing is either at the beggining of the program, or right after another string. For example, `"hello”"world”` can be shortened to `hello”world”`. This works for all types of quotes, mixed or not.
Similarly this works with brackets. No need to write `}` after `{`, `?`, nor any of `[]F∫‽⌠`. You can also ommit a starting `{` if there exists and ending `}`
] |
[Question]
[
Write a program or function that alters the file at a user-specified filename via replacing all instances of UNIX line endings with Windows line endings and vice versa.
Clarifications:
* For the purposes of this problem, a UNIX line ending consists of the octet `0A` in hexadecimal, except when it is immediately preceded by the octet `0D`. A Windows line ending consists of the two octets `0D 0A`.
* As usual, your program only has to run on one (pre-existing) interpreter on one (pre-existing) operating system; this is particularly important for this question, where I imagine many submissions will succeed on UNIX but fail on Windows, or vice versa, due to line ending conversions built into the language.
* To alter a file, you can either edit the file "in-place", or read the file, then save the contents of the file back over the original. However, the program must alter a file on disk; just taking a string as an argument and returning a string specifying the result is not acceptable for this challenge, because the challenge is partially about testing the ability to handle files.
* The program's user must have some method of specifying the filename to change without needing to alter the program itself (i.e. you can't use hardcoded filenames). For example, you could read the name of the file to modify from a command-line argument, or from standard input. If you're submitting a function rather than a full program, making it take a filename as argument would be acceptable.
* The input to the program must be specified as a *filename* specifically; you can't take input other than strings (assuming that you're using an operating system in which filenames are strings; in most, they are), and you can't place restrictions on what filenames you accept (you must accept all filenames that the operating system would accept, and that refer to a file that the user running the program has permission to read and write). For example, you can't write a function that takes a UNIX file descriptor as an argument and requires the file to already be open, and you can't write an editor macro that assumes the file has already been opened in the current buffer.
* If the file is missing a trailing newline before you alter it, it should continue to be missing a trailing newline after you alter it. Likewise, if the file does have a trailing newline, you should preserve that (leaving the file with the other sort of trailing newline).
* If the input file has mixed line ending conventions, you should nonetheless translate each of the line endings to the opposite sort of line ending (so the resulting line will still have mixed line ending conventions, but each individual line will have been converted).
* The program is intended for use converting text files, and as such, you don't have to be able to handle *nonprintable* control codes in the input (although you can if you wish). The nonprintable control codes are the octets from `00` to `1F` (hexadecimal) inclusive except for `09`, `0A`, `0B`, `0C`, `0D`. It's also acceptable for your program to fail on input that cannot be decoded as UTF-8 (however, there is no requirement to place a UTF-8 interpretation on the input; programs which handle all the high-bit-set octets are also acceptable).
* As an exception from the specification, it's acceptable for the program to do anything upon seeing the octet sequence `0D 0D 0A` in the input (because it's impossible to comply with the spec when this sequence appears in the input: you'd have to generate `0D` followed by an `0A` which is not immediately preceded by `0D`, which is a contradiction).
The shortest program wins, under usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules (i.e. fewest bytes in the program you submit). Good luck!
## Test cases
Here are some hex dumps of files you can use to test your program. All these test cases are *reversible*; swapping the input and output gives another valid test case. Note that your program should work for cases other than the given test-cases; these are just some examples to help testing:
---
**Input**
```
30 31 32 0A 33 34 35 0A 36 37 38 0A
```
**Output**
```
30 31 32 0D 0A 33 34 35 0D 0A 36 37 38 0D 0A
```
---
**Input**
```
30 31 0A 0D 0A 32 0A 0A 0A 33 34
```
**Output**
```
30 31 0D 0A 0A 32 0D 0A 0D 0A 0D 0A 33 34
```
---
**Input** and **Output** both a zero-byte file.
[Answer]
# Sed (GNU), ~~27~~, ~~37~~, 24 bytes (21 byte + *"-zi"* flags)
(21 byte for code + 3 for "-zi" flags)
EDIT: I've just spotted an issue with an extra carriage return being appended to files with no trailing newline, when going from Unix to DOS.
This is now fixed, and I've also re-profiled my answer to pure *Sed* instead of *Bash*, and added some tests.
**Golfed**
```
s|\n|\r\n|g;s|\r\r||g
```
**Usage**
```
sed -zi -f newline.sed myfile.txt
```
**Tests**
>
> An old pond!
>
> A frog jumps in —
>
> the sound of water.
>
>
> (Matsuo Basho)
>
>
>
**Test Case #1, Unix newlines + trailing newline**
```
>xxd haiky.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120 An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280 frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077 ..the sound of w
0000030: 6174 6572 2e0a ater.
>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41 An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2 frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66 ....the sound of
0000030: 2077 6174 6572 2e0d 0a water...
>sed -zi -f newline.sed haiku.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120 An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280 frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077 ..the sound of w
0000030: 6174 6572 2e0a ater..
```
**Test Case #2, Unix newlines, no trailing newline**
```
>xxd haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120 An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280 frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077 ..the sound of w
0000030: 6174 6572 2e ater.
>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210d 0a41 An old pond !..A
0000010: 2066 726f 6720 6a75 6d70 7320 696e 20e2 frog jumps in .
0000020: 8094 0d0a 7468 6520 736f 756e 6420 6f66 ....the sound of
0000030: 2077 6174 6572 2e
>sed -zi -f newline.sed haiku.no-trailing-newline.txt
0000000: 416e 206f 6c64 2070 6f6e 6420 210a 4120 An old pond !.A
0000010: 6672 6f67 206a 756d 7073 2069 6e20 e280 frog jumps in ..
0000020: 940a 7468 6520 736f 756e 6420 6f66 2077 ..the sound of w
0000030: 6174 6572 2e ater.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 28 bytes
```
&Z$[13X]OZt5E6MZtO10ZtG3$FZ#
```
This works in [current release (19.5.1)](https://github.com/lmendo/MATL/releases/tag/19.5.1), which is predates the challenge.
I have only tested it on Windows, but it should work on Linux too.
Because of file input/ouput this can't be tested online directly. But here is an [online version](https://tio.run/##VY6xTsMwFEX3fsXtgARLFPeRUsYIMaJKqAMNYnixX4vBsav4uRJfH1LEAHc6y9U5A2uYpg@Spelai7@7wrOwQ9bRxyM4OtgUzzIqNMGJ9QOHCte7d4GFz0gxfCGKOHHoxXLJgnQAoy9H@Ij5mn2KMPdVU5mbxauhl7dtp83j@qnTrak7vUhbq4XD7HKyMPu23tulkf9dD78do@QSFD3bz0uTziU@norikMaBdZqoBhnQCnULItAtqPnhNegOtJn5Gw) that accepts and produces hex-dump strings with the format shown in the challenge.
### Explanation
```
&Z$ % Implicitly input filename, and read as chars
[13X] % Push array [13 10]
O % Push 0
Zt % Replace [13 10] by 0
5E % Push 10
6M % Push [13 10] again
Zt % Replace 10 by [13 10]
O % Push 0
10 % Push 10
Zt % Replace 0 by 10
G % Push filename again
3$FZ# % Overwrite the file with the modified char array
```
[Answer]
# C, ~~240~~ ~~219~~ ~~211~~ 227 bytes
Saving a little by `#define...fputc` and a lot by converting to a program. -8 bytes for converting some logic. +16 bytes for in-place file replacement using the temporary file `T`
Takes filenames via command line parameters.
```
#import<stdio.h>
#define P(c) fputc(c,o)
d;int main(int c,char**v){FILE*i=fopen(v[1],"r"),*o=fopen("T","w");while((c=fgetc(i))!=-1){if(c==10)P(13),P(c);else if(c==13){if((d=fgetc(i))!=10)P(c);P(d);}else P(c);}rename("T",v[1]);}
```
Ungolfed:
```
#import<stdio.h>
#define P(c) fputc(c,o)
d;
int main(int c,char**v){
FILE*i=fopen(v[1],"r"),*o=fopen("T","w");
while((c=fgetc(i))!=-1){
if(c==10)
fputc(13,o),fputc(c,o);
else if(c==13)
if((d=fgetc(i))!=10)
fputc(c,o);
fputc(d,o);
else fputc(c,o);
}
rename("T",v[1]);
}
```
Usage:
```
./a.out test_in.txt
```
] |
[Question]
[
# Introduction
The four basic math operators (+, -, \*, /) can be reduced to just two, due to the fact that:
```
x + y = x - (-y)
x * y = x / (1/y), y != 0
x * 0 = 0/x
```
# Challenge
The challenge is to take input as a "string" containing:
* Numbers
* Single character variables ("x", "y")
* The four basic math operators (+, -, \*, /)
* Parenthesis
and output a string manipulated so that it would produce the same mathematical result as the input, but containing only the mathematical symbols '-' and '/'
# Specifics
* Input can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
* Output can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
* You must recognize and maintain balanced parenthesis
* Standard loopholes are disallowed
* It is your choice if you want to represent `x + y` as `x - -y` or `x - (-y)`
* You must maintain the order of operations
* You never have to handle invalid input
* Input can be empty or a single number/variable, in that case the program should output the input
* Note: You **do not** have to use the substitutions in the introduction, so long as `input = output`, your program could change `2 * 2` to `8/2`, if you wanted
* You can assume that "0" is the only way a zero will appear in the equation (I.e. you don't have to handle `1 * (4 - 4)`)
* Suggestion: to test your program, go to [this website](https://www.wolframalpha.com/) type in `input = output`, where input is the input, and output is the output, and if the result is "true" your program handled that case successfully ([example](https://www.wolframalpha.com/input/?i=x+*+y+%3D+x+%2F+(1%2Fy)), [example](https://www.wolframalpha.com/input/?i=1%20%2B%20(x%20*%204)%20-%20(512%20*%203)%20%3D%201%20-%20(-(x%20%2F%20(1%2F4)))%20-%20(512%20%2F%20(1%2F3))))
# Test Cases
Below are some test cases, input as a single string and output as a single string.
```
x + y
x - (-y)
x * y
x / (1/y)
x / y
x / y
x - y
x - y
1
1
5
5
-6
-6
+x
x
1 + (x * 4) - (512 * 3)
1 - (-(x / (1/4))) - (512 / (1/3))
1 - 3 / 4 + l / g
1 - 3/4 - (-(l / g))
5 * 0 / 2
0/5 / 2
(a + g) * 0
0/(a - (-g))
```
# Scoring
It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Ties are resolved by first-post.
[Answer]
# Python 3, 267 bytes
Thanks to @ConorO'Brien
```
import re
q=re.sub
g=lambda m:'--'+m.group()[1:]
h=lambda m:'/(1/'+m.group()[1:]+')'
i=lambda m:'0/'+m.group()[:-2]
print(q(r'\*[^\(\)]+',h,q(r'[^\(\)]\*0',i,q(r'\+[^\(\)]+',g,q(r'\*\([^\)]+\)',h,q(r'\([^\)]+\)\*0',i,q(r'\+\([^\)]+\)',g,input().replace(' ',''))))))))
```
[**Ideone it!**](https://ideone.com/v67gZI)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 42 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
This maintains APLs order of operations. Note that `÷x` is `1÷x`
```
'\+' '×'⎕R'--' '÷÷'('(.*)×0'⎕R'0÷\1'~∘' ')
```
[TryAPL online!](http://tryapl.org/?a=f%u2190%27%5C+%27%20%27%D7%27%u2395R%27--%27%20%27%F7%F7%27%28%27%28.*%29%D70%27%u2395R%270%F7%5C1%27%7E%u2218%27%20%27%29%20%u22C4%20f%A8%27x%20+%20y%27%20%27x%20%D7%20y%27%20%27x%20%F7%20y%27%20%27x%20-%20y%27%20%271%27%20%275%27%20%27-6%27%20%27+x%27%20%271%20+%20%28x%20%D7%204%29%20-%20%28512%20%D7%203%29%27%20%271%20-%203%20%F7%204%20+%20l%20%F7%20g%27%20%275%20%D7%200%20%F7%202%27%20%27%28a%20+%20g%29%20%D7%200%27&run)
`(` on the result of...
`~∘' '` remove spaces
`'(.*)×0'⎕R'0÷\1'` replace anything followed by "×0" with "0÷" followed by it
`)` evaluate...
`'\+' '×'⎕R'--' '÷÷'` replace "+" with "--" and "×" with "÷÷"
### To verify:
1. [Assign random non-zero numbers to `x`, `y`, `l`, `g`, and `a`.](http://tryapl.org/?a=%u22A2x%20y%20l%20g%20a%u21905%3F9&run)
2. [Execute the original expressions.](http://tryapl.org/?a=%28x%20+%20y%29%28x%20%D7%20y%29%28x%20%F7%20y%29%28x%20-%20y%29%281%29%285%29%28-6%29%28+x%29%281%20+%20%28x%20%D7%204%29%20-%20%28512%20%D7%203%29%29%281%20-%203%20%F7%204%20+%20l%20%F7%20g%29%285%20%D7%200%20%F7%202%29%28%28a%20+%20g%29%20%D7%200%29&run)
3. [Execute the modified expressions.](http://tryapl.org/?a=%28x--y%29%28x%F7%F7y%29%28x%F7y%29%28x-y%29%281%29%285%29%28-6%29%28--x%29%281--%28x%F7%F74%29-%28512%F7%F73%29%29%281-3%F74--l%F7g%29%280%F75%F72%29%280%F7%28a--g%29%29&run)
4. [Compare the results.](http://tryapl.org/?a=%28x%20+%20y%29%28x%20%D7%20y%29%28x%20%F7%20y%29%28x%20-%20y%29%281%29%285%29%28-6%29%28+x%29%281%20+%20%28x%20%D7%204%29%20-%20%28512%20%D7%203%29%29%281%20-%203%20%F7%204%20+%20l%20%F7%20g%29%285%20%D7%200%20%F7%202%29%28%28a%20+%20g%29%20%D7%200%29%u2261%28x--y%29%28x%F7%F7y%29%28x%F7y%29%28x-y%29%281%29%285%29%28-6%29%28--x%29%281--%28x%F7%F74%29-%28512%F7%F73%29%29%281-3%F74--l%F7g%29%280%F75%F72%29%280%F7%28a--g%29%29&run)
[Answer]
# SED 272 246 239 213
```
s,^\+,,;s,[^+*/()-]\+,(&),g;t;:;s,)[^)]*)\*(0,&,;tr;s,\((.*)\)\*(0),(0/\1),;ty;s,\*([^)]*(,&,;tr;s,\*\(([^)]*)\),/(1/\1),;ty;s,\+([^)]*(,&,;tr;s,\+\(([^)]*)\),-(-\1),;ty;p;q;:r;s,(\([^()]*\)),!\1@,;t;:y;y,!@,(),;b
```
Take input without spaces (e.g. `x+y*2`).
This is one of the few cases where it is actually shorter to just escape `(` and `)` for capture groups instead of using `-r`. I'm sure this can be golfed more, but I'm happy for now.
Ungolfed, with comments:
```
s,^\+,, #remove leading +
s,[^+*/()-]\+,(&),g #suround numbers/variables in ()
t start #reset the test because the line above will always match
:start
#------------- deal with *0 ------------------
s,)[^)]*)\*(0,&, #remove inner matching ()
t replace
s,\((.*)\)\*(0),(0/\1),
t y
#------------- deal with generic * -----------
s,\*([^)]*(,&, #remove inner matching ()
t replace
s,\*\(([^)]*)\),/(1/\1),
t y
#------------- deal with + -------------------
s,\+([^)]*(,&, #remove inner matching ()
t replace
s,\+\(([^)]*)\),-(-\1),
t y
b end #all done, branch to the end
#------------- replace a set of () with !@ ---
#repeated application of this helps find the matching ( or )
:replace
s,(\([^()]*\)),!\1@,
t start
:y
y,!@,(),
b start
:end
```
] |
[Question]
[
You have to write an interpreter for a cool language called [Chicken](https://esolangs.org/wiki/Chicken)!
You should read a Chicken program from a file, standard input, program or function arguments, or whatever is most convenient for your language, as well as input to the program.
You should print or return the result of interpreting the program according to the Chicken language specification.
[More description about the language](https://esolangs.org/wiki/Chicken).
---
# Chicken Program Overview
Chicken operates on a single stack, which composes its entire memory model. As instructions are executed, the program will push and pop values from the stack, but there are also instructions that allow the program to modify other parts of the stack at will.
There are three segments in the stack:
1. The registers, at indices 0 and 1. Index 0 is a reference to the stack itself, and index 1 is a reference to the user input. Mostly used for instruction 6 (see below).
2. The loaded code: for each line of code there is cell in this segment that contains the number of "chicken"s in the line. This is padded with a 0 (opcode for terminate program) at the end.
3. The actual program stack, where values are pushed/popped as the program runs. Note that the segments are not isolated, which means that it is possible to create self-modifying code or execute code from this segment of the stack space.
# The Chicken ISA
Chicken's instruction set is based around the number of times the word "chicken" appears on each line of the program. An empty line terminates the program and prints the topmost value in the stack.
The Chicken instruction set, by number of "chicken"s per line:
1. Push the literal string "chicken" to the stack
2. Add top two stack values as natural numbers and push the result.
3. Subtract top two values as natural numbers and push the result.
4. Multiply top two values as natural numbers and push the result.
5. Compare two top values for equality, push 1 if they are equal and 0 otherwise.
6. Look at the next instruction to determine which source to load from: 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load from the given source; load that value and push it onto stack. Since this is a double wide instruction, the instruction pointer skips the instruction used to determine the source.
7. Top of stack points to address/index to store to. The value below that will be popped and stored in the stack at the given index.
8. Top of stack is a relative offset to jump to. If the value below that is truthy, then the program jumps by the offset.
9. Interprets the top of the stack as ascii and pushes the corresponding character.
10. (10 + N) Pushes the literal number n-10 onto the stack.
---
# Example
Assume the program is:
```
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
(an empty line)
```
(A cat program. Note that the empty line is required because of the preceding line having 6 "chicken".)
*Input provided to Chicken program*
```
Chicken
```
*Output*
```
Chicken
```
[The Chicken.js reference implementation](http://torso.me/chicken.js).
---
# Error detection
The interpreter should leave an error and terminate when any word not "chicken" is present in the source.
---
Good luck!
[Answer]
# Javascript ES6, 398 bytes
By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than `chicken` at this point.
```
(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}
```
I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.
Outputs a falsey value (0) for everything which isn't `chicken`
```
(a,b)=>{
for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
j<A.length; // loop condition
( // everything else
[
_=>s[++i]=c,
_=>s[--i]=s[i]+s[i+1],
_=>s[--i]=s[i]-s[i+1],
_=>s[--i]=s[i]*s[i+1],
_=>s[--i]=s[i]==s[i+1],
_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
_=>s[s[i--]]=s[i--],
_=>j+=s[--i]?s[--i+2]:0,
_=>s[i]=String.fromCharCode(s[i])
][s[j+2]-1]
||(_=>s[++i]=s[j+1]-10)
)(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}
```
Try it here
```
f=
(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}
i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')
```
```
<pre id=i>
```
[Answer]
# Ruby, 335 bytes
Takes the input file name as a command line argument and takes user input (for instruction #6) from STDIN.
Because of Ruby "truthy" (everything except `false` and `nil`) being different from the Javascript "truthy" (Ruby truthy plus `0`, empty strings, etc.), there might be some edge cases where programs that work fine on a JS interpreter fail on this one because of instruction #8, such as if `""` is on the stack. I've fixed the biggest case, though, which is falsy `0`.
Works with the test program and the Hello World program on the Chicken website.
```
+(/^(#{c='chicken'}|\s)*$/m=~f=$<.read+"
")
s=[0,STDIN.read]+f.lines.map{|l|l.split.size};s[0]=s;i=1
s<<(s[i]<10?[->{c},->{x,y=s.pop 2;x+y},->{x,y=s.pop 2;x-y},->{s.pop*s.pop},->{s.pop==s.pop},->{s[s[i+=1]][s.pop]},->{s[s.pop]=s.pop;s.pop},->{l,k,j=s.pop 3;i+=j if k&&k!=0;l},->{s.pop.chr}][s[i]-1][]:s[i]-10)while s[i+=1]>0
$><<s.pop
```
## Explanation
The interpreter immediately starts off by running a regex match `/^(chicken|\s)*$/m` against the entire file (`$<.read`), which makes sure the file contains nothing but `chicken` and whitespace. In Ruby, this operator returns the index for the match, or `nil` if it wasn't found.
Two byte-saving tricks are used here: instead of directly matching `chicken`, the string substitution operator `#{}` is used instead to also assign that string to a variable for later (saves 1 byte), and when storing the contents of the file to a variable for processing, it appends two newlines to allow the `lines` function later to naturally append an extra `0` to the end of the instruction set. (Two are needed because of ignored trailing newline, which is necessary for the Chicken program.)
The error used is `NoMethodError: undefined method '+@' for nil:NilClass`, which is done by wrapping the regex match in parens and putting a `+` in front. If the file matches the pattern, you get `+0`, which evaluates to `0` and proceeds normally.
Next, the stack is assembled. The initial list must be created before the self-reference to the stack can be assigned, so a placeholder is used and then replaced. The instruction pointer is set to `1` instead of `2` because post-increment operators don't exist in Ruby.
Finally, it uses the lambda trick from @BassdropCumberwubwubwub to determine what to push on the stack next. If an operation doesn't push anything onto the stack, the interpreter simply pops an extra value so the stack stays the same. (This saves bytes over adding a push operation into every single lambda.)
**Ungolfed code:**
```
f = $<.read + "\n\n"
+(/^(chicken|\s)*$/m =~ f)
s = [0, STDIN.read] + f.lines.map{|l|l.split.size}
s[0] = s
i = 1
while s[i += 1] > 0
if s[i] < 10
s.push [
->{'chicken'},
->{
x,y = s.pop 2
x+y
},
->{
x,y = s.pop 2
x-y
},
->{s.pop*s.pop},
->{s.pop==s.pop},
->{s[s[i+=1]][s.pop]},
->{s[s.pop]=s.pop;s.pop},
->{
l,k,j=s.pop 3
i+=j if k&&k!=0
l
},
->{s.pop.chr}
][s[i] - 1][]
else
s.push(s[i] - 10)
end
end
print s.pop
```
] |
[Question]
[
Resistors and other electronic components are typically manufactured with values that conform to one of the [E-series](https://en.wikipedia.org/wiki/Preferred_number#E_series) of [preferred numbers](https://en.wikipedia.org/wiki/Preferred_number). IEC 60063 defines the following E-series:
>
> ### E6:
>
>
> 10 15 22 33 47 68
>
>
> ### E12:
>
>
> 10 12 15 18 22 27 33 39 47 56 68 82
>
>
> ### E24:
>
>
> 10 11 12 13 15 16 18 20 22 24 27 30 33 36 39 43 47 51 56 62 68 75 82 91
>
>
> ### E48:
>
>
> 100 105 110 115 121 127 133 140 147 154 162 169 178 187 196 205 215 226 237 249 261 274 287 301 316 332 348 365 383 402 422 442 464 487 511 536 562 590 619 649 681 715 750 787 825 866 909 953
>
>
> ### E96:
>
>
> 100 102 105 107 110 113 115 118 121 124 127 130 133 137 140 143 147 150 154 158 162 165 169 174 178 182 187 191 196 200 205 210 215 221 226 232 237 243 249 255 261 267 274 280 287 294 301 309 316 324 332 340 348 357 365 374 383 392 402 412 422 432 442 453 464 475 487 499 511 523 536 549 562 576 590 604 619 634 649 665 681 698 715 732 750 768 787 806 825 845 866 887 909 931 953 976
>
>
> ### E192:
>
>
> 100 101 102 104 105 106 107 109 110 111 113 114 115 117 118 120 121 123 124 126 127 129 130 132 133 135 137 138 140 142 143 145 147 149 150 152 154 156 158 160 162 164 165 167 169 172 174 176 178 180 182 184 187 189 191 193 196 198 200 203 205 208 210 213 215 218 221 223 226 229 232 234 237 240 243 246 249 252 255 258 261 264 267 271 274 277 280 284 287 291 294 298 301 305 309 312 316 320 324 328 332 336 340 344 348 352 357 361 365 370 374 379 383 388 392 397 402 407 412 417 422 427 432 437 442 448 453 459 464 470 475 481 487 493 499 505 511 517 523 530 536 542 549 556 562 569 576 583 590 597 604 612 619 626 634 642 649 657 665 673 681 690 698 706 715 723 732 741 750 759 768 777 787 796 806 816 825 835 845 856 866 876 887 898 909 920 931 942 953 965 976 988
>
>
>
Given a single input integer from the set `{6, 12, 24, 48, 96, 192}`, output the corresponding E-series, in order, containing exactly the numbers as shown above for the given series.
* Output may be in whatever format of list, array, etc is appropriate for your language.
* Base 10 integers only.
* builtins that specifically implement these series are disallowed.
[Answer]
## Python 3, 97 bytes
```
lambda n:[round(10**(i/n+2-(n<25)))+((.4<i/n<.67)-(.9<i/n<.92))*(n<25)+(i==185)for i in range(n)]
```
The output values scaled from 1 to 10 are well-approximated by an exponential interpolation:
```
10**(i/n)
```
Multiplying by 10 for `6, 12, 24` and 100 for `48, 96, 192` then rounding to the nearest integer
```
round(10**(i/n+2-(n<25)))
```
gives the right answers for all but 16 values, which gives errors of ±1.
```
n i est val diff
6 3 32 33 -1
6 4 46 47 -1
12 5 26 27 -1
12 6 32 33 -1
12 7 38 39 -1
12 8 46 47 -1
12 11 83 82 1
24 10 26 27 -1
24 11 29 30 -1
24 12 32 33 -1
24 13 35 36 -1
24 14 38 39 -1
24 15 42 43 -1
24 16 46 47 -1
24 22 83 82 1
192 185 919 920 -1
```
For `n<=24`, most of these errors are for inputs values in the interval `10/24<=i/n<=6/24`. There's one other error for `n==24` that trickles down to `n==12`, and one error for `n==192`. We fudge these errors by adding or subtracting `1` to the estimate.
[Answer]
## Mathematica, ~~904~~ 879 bytes
```
If[#>4!,{100,101,102,104,105,106,107,109,110,111,113,114,115,117,118,120,121,123,124,126,127,129,130,132,133,135,137,138,140,142,143,145,147,149,150,152,154,156,158,160,162,164,165,167,169,172,174,176,178,180,182,184,187,189,191,193,196,198,200,203,205,208,210,213,215,218,221,223,226,229,232,234,237,240,243,246,249,252,255,258,261,264,267,271,274,277,280,284,287,291,294,298,301,305,309,312,316,320,324,328,332,336,340,344,348,352,357,361,365,370,374,379,383,388,392,397,402,407,412,417,422,427,432,437,442,448,453,459,464,470,475,481,487,493,499,505,511,517,523,530,536,542,549,556,562,569,576,583,590,597,604,612,619,626,634,642,649,657,665,673,681,690,698,706,715,723,732,741,750,759,768,777,787,796,806,816,825,835,845,856,866,876,887,898,909,920,931,942,953,965,976,988}[[;;;;192/#]],{10,11,12,13,15,16,18,20,22,24,27,30,33,36,39,43,47,51,56,62,68,75,82,91},[[;;;;24/#]]]&
```
~~Ungolfed~~ ~~Massive-list-free~~ ~~Logic-only~~ version:
```
If[#>4!,{E192}[[;;;;192/#]],{E24}[[;;;;24/#]]]&
```
## Almost version, 60 bytes
```
Floor[Table[If[#>4!,100,10]Surd[10,#]^x,{x,0,#}]+.5][[;;-2]]
```
Accurate to within ±1
] |
[Question]
[
While there are only a few users of the [Vitsy programming language](https://github.com/VTCAKAVSMoACE/Vitsy) right now, I wish to create a place for tips for golfing in Vitsy.
What general tips do you have for golfing in [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy) (e.g. "remove NOPs" is not an answer). Please post one tip per answer.
For reference, the online interpreter is [here](http://vitsy.tryitonline.net), the esolang page is [here](http://esolangs.org/wiki/Vitsy), and you can receive answer-per-answer help [here](http://chat.stackexchange.com/rooms/35039/ppcg-code-snippet-chat-bot).
[Answer]
# Remember that `\[]` *always runs at least once*
Even if the top item of the stack is zero or less, `\[]` always runs. Think of it more as a `do{}for();` loop. This has caught me off more than once, but it is important.
[Answer]
# Do not doubt the power of `m`
Background: `Fm` calls the a specified line index in the current Vitsy class. (`F` is the line index you seek).
The `m` command (method) has saved me [literally hundreds of bytes](https://codegolf.stackexchange.com/a/74216/44713) in the past. Any algorithm that uses repeated steps, or a common character sequence (such as `D1M-` (floor algorithm)).
This is extremely helpful in repetitive kolmogorov complexity challenges.
Instead of:
```
WD1M-(something else here)WD1M-(something different)WD1M-l\[NaO]
```
Use:
```
1m(something else here)1m(something different)1ml\[NaO]
WD1M-
```
(floor(prompt))
Also, you can return from method statements with `;`, allowing for looping until condition(s) (over the general `[ ]` syntax, which isn't as powerful):
```
1mN
<;)
```
(loops through code until finding non-zero, popping it from the stack and returning to first line)
[Answer]
# Filling Zeroes on an Empty Stack
Normally, to fill up the stack with a number, you would do something like this:
```
a\a
```
This fills up the stack with 10 10s, by pushing 10 10 times. However, if you wanted to push 10 0s, you'd do this:
```
a\0
```
After a recent update, however, the stack will attempt to fix for IndexOutOfBoundsExceptions by pushing 0s to a possibly empty stack, meaning that, if on an empty stack, you can do:
```
a%
```
Since `%` calls `multistack`, it tries to access every member between the top item (which is nothing after it pops `10`) and the index you specify. Therefore, you get a stack with 10 0s when this is called. You can use this trick up to approximately 11380, although, annoyingly, it doesn't always go to a specific point...
```
UNKNOWN:Desktop addisonc17$ vitsy --code "2d^2b^+2a^+26^+25^+24^+5+%lNaO"
java.lang.StackOverflowError thrown in [command line] at command #0,25: %
UNKNOWN:Desktop addisonc17$ vitsy --code "2d^2b^+2a^+26^+25^+24^+5+%lNaO"
11381
```
Past that, you'll have to use the normal duplication method.
] |
[Question]
[
**Objective**
The black pawn wants revenge. Plot out its last attack.
**Rules**
The black pawn (`L`) starts at the top row and moves downwards to the bottom row. Maximise points taken, indicating the path with `X`. Pawns (`P`) are 1, bishops (`B`) and knights (`N`) 3, rooks (`R`) 5, and queens (`Q`) 9. There won't be any kings in the input.
If there is more than one path that has the maximum amount of points, output any of those paths. There will not be any situations where the pawn cannot reach the bottom row.
**Examples**
Input:
```
----L---
-----P--
------P-
--R--P-Q
----P-P-
---P-P-P
--P-N---
-P------
```
Output:
```
----L---
-----X--
------X-
--R--P-X
----P-X-
---P-X-P
--P-X---
-P--X---
```
Input:
```
--L-----
-P------
P-------
-P------
P--Q----
-P------
P-------
-P------
```
Output:
```
--L-----
-PX-----
P-X-----
-PX-----
P--X----
-P-X----
P--X----
-P-X----
```
[Answer]
# Python, 332
```
def s(m,l,p):
if not m:return 1
b=m[0]+'-';z=filter(lambda i:(b[i]=='-')==(i==l),[l,l-1,l+1])
if not z:return 0
g=lambda i:s(m[1:],i,0)+[0,1,3,3,5,9]['-PBNRQ'.index(b[i])];i=max(z,key=g)
if p:print m[0][:i]+'X'+m[0][i+1:];s(m[1:],i,p)
return g(i)
import sys
t=sys.stdin.read().split('\n')
print t[0]
s(t[1:],t[0].index('L'),1)
```
[Answer]
# Ruby ~~260 258 255 241 236~~ 222
```
->b{s=->l,w=p{c,*x=l.map &:dup
v=[1,3,3,5,9,0]['PBNRQ'.index(c[y=w||c.index(?L)])||5]
w&&c[y]=?X
(n=x[0])?(m=[]
[y-1,y,y+1].map{|z|(z==y)^(n[z]>?.)&&m<<s[x,z]}
q,r=m.max_by{|m|m ?m[0]:0}
q&&[q+v,c+r]):[v,c]}
s[b.lines][1]}
```
This program defines a function (`s`), which, given some board rows, returns the best path as a string, and the value in points of that path. `s` is recursive, so at each step it evaluates all possibilities and returns the best one.
Here's an online version with tests: <http://ideone.com/6eMtm4>
The readable version is available here: <http://ideone.com/eoXUtp>
All the steps I took to reduce the size of the code can be found [here](https://github.com/wolfascu/codegolf/commits/master/61005-the-black-pawns-revenge/61005-the-black-pawns-revenge-golfed.rb).
] |
[Question]
[
**Introduction**
This challenge is about three (bad) sorting algorithms: [`Bogosort`](http://en.wikipedia.org/wiki/Bogosort), and two others variants that I came up with (but have probably been thought of by others at some point in time): `Bogoswap` (AKA Bozosort) and `Bogosmart`.
`Bogosort` works by completely shuffling the array randomly and checking if it becomes sorted (ascending). If not, repeat.
`Bogoswap` works by selecting two elements, randomly, and swapping them. Repeat until sorted (ascending).
`Bogosmart` works by selecting two elements, randomly, and only swapping them if it makes the array closer to being sorted (ascending), ie. if the element with the lower index was originally larger than the one with the higher. Repeat until sorted.
**The Challenge**
This challenge explores the efficiency (or lack of) of each of these three sorting algorithms. The golfed code will
1. generate a shuffled 8 element array of the integers 1-8 inclusive (keep reading to see how you should do this);
2. apply each algorithm to this array; and
3. display the original array, followed by the number of computations required for each algorithm, separated by one space (trailing space ok), in the format `<ARRAY> <BOGOSORT> <BOGOSWAP> <BOGOSMART>`.
The program will produce 10 test cases; you can generate all ten at the beginning or generate one at a time, whatever. Sample output below.
**Details:**
For `Bogosort`, it should record the number of times the array was shuffled.
For `Bogoswap`, it should record the number of swaps made.
For `Bogosmart`, it should record the number of swaps made.
**Example output:**
```
87654321 1000000 100 1
37485612 9050000 9000 10
12345678 0 0 0
28746351 4344 5009 5
18437256 10000 523 25
15438762 10000 223 34
18763524 58924 23524 5
34652817 9283 21 445
78634512 5748 234 13
24567351 577 24 34
```
I made up these numbers; of course, your program will print different output but in the same format.
**Rules**
* All randomness used in your program must come from pseudorandom number generators available to you, and otherwise not computed extensively by you. You don't have to worry about seeds.
* There is no time limit on the programs.
* The arrays are to be sorted ascendingly.
* Trailing spaces or an extra newline is no big deal.
* For `Bogosort`, the array is to be shuffled using any unbiased shuffling algorithm such as Fisher-Yates or [Knuth Shuffling](http://en.wikipedia.org/wiki/Random_permutation#Knuth_shuffles), explicitly specified in your explanation. Built-in shuffling methods are not allowed. Generate your test arrays in the same manner.
* If after shuffling or swapping the array remains the same, it still counts and should be included in the program's count. For example, shuffling the array to itself by coincidence counts as a shuffle, and swapping an element with itself counts as a swap, even though none of these operations change the array.
* If my memory serves me correctly, an 8 element array shouldn't take too long for any of the three algorithms. In fact, I think a few times for a 10 element array, when I tried it, `Bogoswap` only required a few thousand (or less) actual shuffles and well under 10 seconds.
* Your code must actually sort the arrays, don't just give expected values or mathematical calculations for an expected answer.
* This is a code-golf challenge, so shortest program in bytes wins.
Here are some sample steps for each sorting algorithm:
```
BOGOSORT
56781234
37485612
28471653
46758123
46758123
12685734
27836451
12345678
BOGOSWAP
56781234
16785234
17685234
12685734
12685743
12685734
12485763
12385764
12385764
12345768
12345678
BOGOSMART
56781234
16785234
12785634
12785364
12785364
12385764
12385674
12345678
```
In this case, the program would output `56781234 7 10 7`, and then do the same thing 10 times. You do not have to print the arrays while sorting is going on, but I gave the above sample steps so you can understand how each algorithm works and how to count computations.
[Answer]
# Pyth, ~~62~~ 60 bytes
```
VTjd[jkKJ=boO0=ZS8fqZ=KoO0K0fqZ=XJO.CJ2)0fqZ=Xb*>F=NO.Cb2N)0
```
This was quite fun. Not sure if this is valid, I'm probably using some unwritten loopholes.
A sample output would be:
```
23187456 22604 23251 110
42561378 125642 115505 105
62715843 10448 35799 69
72645183 7554 53439 30
61357428 66265 6568 77
62348571 1997 105762 171
78345162 96931 88866 241
17385246 51703 7880 80
74136582 36925 19875 100
26381475 83126 2432 25
```
### Explanation:
My shuffle function uses the built-function `order-by`. Basically I assign each element of the list a random number of the interval `[0-1)` and sort the list by them. This gives me an unbiased random shuffle.
**Outer loop**
The `VT` at the start repeats the following code 10 times.
**Preparation**
```
jkKJ=boO0=ZS8
S8 create the list [1, 2, 3, 4, 5, 6, 7, 8]
=Z and store in Z
oO0 shuffle
=b and store in b
J and store in J
K and store in K (3 copies of the same shuffled array)
jkK join K with ""
```
**Bogosort**
```
fqZ=KoO0K0
oO0K shuffle K
=K and store the result in K
f 0 repeat ^ until:
qZ K Z == K
and give the number of repeats
```
**Bogoswap**
```
fqZ=XJO.CJ2)0
.CJ2 give all possible pairs of elements of J
O take a random one
XJ ) swap these two elements in J
= and store the result in J
f 0 repeat ^ until:
qZ K Z == K
and give the number of repeats
```
**Bogosmart**
```
fqZ=Xb*>F=NO.Cb2N)0
.Cb2 give all possible pairs of elements of b
O take a random one
=N assign it to N
>F N check if N[0] > N[1]
* N multiply the boolean with N
Xb ) swap the two (or zero) values in b
= and assign to b
f 0 repeat ^ until:
qZ Z == b
and give the number of repeats
```
**Printing**
```
jd[
[ put all 4 values in a list
jd join by spaces and print
```
[Answer]
# JavaScript (*ES6*), 319 ~~345~~
Unsurprisingly this is quite long.
For Random shuffle, credits to [@core1024](https://codegolf.stackexchange.com/a/45453/21348) (better than mine for the same chellenge)
Test running the snippet (Firefox only as usual)
```
// FOR TEST : redefine console
var console = { log: (...p)=>O.innerHTML += p.join(' ')+'\n' }
// END
// Solution
R=n=>Math.random()*n|0,
S=a=>(a.map((c,i)=>(a[i]=a[j=R(++i)],a[j]=c)),a), // shuffle
T=f=>{for(a=[...z];a.join('')!=s;)f(a)}, // apply sort 'f' algorithm until sorted
s='12345678';
for(i=0;i<10;i++)
z=S([...s]),
n=l=m=0,
T(a=>S(a,++n)),
T(a=>(t=a[k=R(8)],a[k]=a[j=R(8)],a[j]=t,++m)),
T(a=>(t=a[k=R(8)],u=a[j=R(8)],(t<u?j<k:k<j)&&(a[k]=u,a[j]=t,++l))),
console.log(z.join(''),n,m,l)
```
```
<pre id=O></pre>
```
] |
[Question]
[
# Now with BONUS for run-time placement.
Write a program to fill a text box with the identifiers used in your program while keeping your program
small. With all the identifiers you have used (excluding those *you* created) in
your program, fill a 12x6 box with as many as you can. You get extra points for
identifiers that cross over (crossword style), but they can't join end to end.
## Output
Your program should print (to stdout) a 12x6 character box with your packed identifiers and a `#` border. The
box should have columns labeled with letter A-L and the rows 1-6 (spaced like the example below). Then print a
line for each identifier used. Each line will have the location of the first
letter, the identifier itself, and the score. The score is equal to the number
of letters in the identifier with a possible '+bonus' added. The identifier gets
a 5 point bonus for each letter shared with a crossing identifier. The final
line reports 'TOTAL: ' and the sum of the identifier scores. An example output
for a possible Python program would look like this:
```
ABCDEFGHIJKL
##############
1 # pinsert #
2 # o #
3 # print #
4 # not #
5 # #
6 #import #
##############
C1 pop 3+5
D1 insert 6
C3 print 5+10
E3 in 2+10
E4 not 3+5
A6 import 6
TOTAL: 55
```
Notes:
* Identifiers can be unattached (like `import` above).
* You cannot join `pop` and `print` inline with `poprint`.
* The string `in` inside `insert` cannot be used. Joining words must be orthogonal.
* Identifiers can be placed next to each other (like `pop` and `insert` above).
Your answer should include your program output with your source code and a title
consisting of the language name and your score.
## Score
Your score for the challenge will the the puzzle score squared divided by the
size of your source code (in bytes). Eg: The puzzle above with a 300 byte
program would score `55*55/300 = 10.08`. Highest score wins.
## Rules
* You can use any identifier in your program that is not defined by you.
Keywords, class names, method names, library names, and built-in function names are examples of eligible identifiers.
* EDITED: You may only use standard libraries that are included with the minimum language release. Extended language packages and the use of external libraries (are now) forbidden. The huge range of libraries with extensive lists of identifiers would unbalance this challenge. If you are unsure of how this works with your language, please leave a question in the comments.
* Identifiers must consist of [a-zA-Z\_] characters only and have at least 2
characters.
* You may only use each identifier once in the puzzle.
* Identifiers can only be used left to right or downwards.
## Dynamic Bonus!
If your code determines where to place identifiers at run time, the shared letter bonus will be 20 instead of 5. You may list which identifiers will used, but your code must decide where in the box to place them. Your code must also calculate and print the score list. If your placements depend on the *ordering* of the identifier list, hard-coded pairings, or other non-dynamic placement short-cuts, you are not eligible for the Dynamic Bonus.
In the example output above, the puzzle score for a run-time placement program would become 145. Then if the code was 800 bytes, the score would be `145*145/800 = 26.28`.
The Dynamic Bonus is designed to reward clever algorithms instead of static hard-coded solution strings, and compensate for the larger resulting source code size.
EDITS:
* Changed libraries used to only those in the minimum language release.
* Added the dynamic bonus option.
[Answer]
# Python, 1342 / 349 = 50.02
If I have understood the rules correctly, this should be a valid submission.
```
from sys import *
stdout.write(""" ABCDEFGHIJKL
##############
1 #from f i #
2 # r not t #
3 # write #
4 # s import#
5 # y False #
6 # stdout #
##############
A1 from 4+5
C1 or 2+5
H1 format 6+25
K1 iter 4+10
G2 not 3+5
G3 write 5+10
C4 sys 3+5
G4 import 6+10
G5 False 5+5
C6 stdout 6+10
TOTAL 134
""".format(not False or iter([])))
```
You can really just keep incrementing your score by adding more identifiers: the size of the program increases linearly (by approx. twice the identifier length), while the score increases approximately by the square of the identifier length. Then the challenge becomes more how to cram most keywords into the square instead of how to write a *short* program to do it.
[Answer]
## STATA, 387^2 / 677 = 221.2
I got lazy and just wanted to output something that works before trying to get it with optimal score. I'll probably update it later as I fit more words in, and I'm open to suggestions from anyone that uses STATA (which doesn't seem very popular on CodeGolf). STATA is really good about having a lot of two letter commands/parameters. Also, usually most can be shortened to save characters/fit better (i.e. display can be display, displa, displ, disp, dis, or di). Also, the capture means that it suppresses output and error messages. So the entire while loop has 0 output.
```
cap infile using a,us(b)
cap while _rc>0{
ls
cap ge c=1 if 0<1
so c
egen d=rownonmiss(c),str
regres c d
notes
clist,noh no
li,compress
dec c,g(f)
do a
}
gl e=";;;ABCDEFGHIJKL ;;############## 1;#rownonmissdo# 2;#e;hd;o;notes# 3;#geii;hif_rc;# 4;#r;ls;clist;;# 5;#egen;ailu;;;# 6;#slcompress;;# ;;############## A1;rownonmiss;10+30 K1;do;2+5 H2;notes;5+20 A3;ge;2+5 G3;if;2+5 I3;_rc;3+15 C4;ls;2+10 F4;clist;5+20 A5;egen;4+20 C6;compress;8+20 A1;regres;6+15 C1;while;5+15 F1;noh;3+5 H1;infile;6+25 I1;so;2+10 J1;str;3+15 K1;dec;3+15 D2;dis;3+5 I3;_s;2+10 F4;cap;3+10 G4;li;2+5 B5;gl;2+5 D5;no;2+10 I5;us;2+5 TOTAL:;387"
token $e
forv x=1/34{
dis subinstr(``x'',";"," ",.)_s(0)
}
```
generates
```
ABCDEFGHIJKL
##############
1 #rownonmissdo#
2 #e hd o notes#
3 #geii hif_rc #
4 #r ls clist #
5 #egen ailu #
6 #slcompress #
##############
A1 rownonmiss 10+30
K1 do 2+5
H2 notes 5+20
A3 ge 2+5
G3 if 2+5
I3 _rc 3+15
C4 ls 2+10
F4 clist 5+20
A5 egen 4+20
C6 compress 8+20
A1 regres 6+15
C1 while 5+15
F1 noh 3+5
H1 infile 6+25
I1 so 2+10
J1 str 3+15
K1 dec 3+15
D2 dis 3+5
I3 _s 2+10
F4 cap 3+10
G4 li 2+5
B5 gl 2+5
D5 no 2+10
I5 us 2+5
TOTAL: 387
```
[Answer]
# Perl, 7282 / 639 = 829.4
Oh well, this is not valid, missed that I have to have the identifiers in my code.
```
#!perl -l
use B::Keywords'@Symbols','@Barewords';
use List::Util shuffle;
srand 45502;
@b=@a=shuffle map{push@{+length},$_;$_}grep/^[a-z]{2,}$/,@Symbols,@Barewords;
$z=$"x12 .$/;$z x=6;
$s=length,$z=~s/ {$s}/$_/&&($_=0)for@a;
$_=$z;$"='|';
sub f{join'',/(.)(?=@_.*(\n))/sg}$_=f".{12}(.)"x5;
s/@a/$v=length$&;$tot+=$v*21;$r.=(map{m!.!;map{$&.$_}1..7}A..L)[@-]." $& $v+".($v*20)."\n";uc$&/ge;
$_=f".{6}(.)"x11;
s/@b/$v=length$&;$b=$&=~y!A-Z!!;$tot+=$v+$b*20;$c=lc$&;$r.=(map{m!.!;map{$_.$&}A..M}1..6)[@-]." $c $v+".($b*20)."\n";uc$&/ige;
$_=$z;
s/
/#
/mg;
s/^/++$l.' #'/mge;
print' ',A..L,'
','#'x14,'
',$_,' ','#'x14,"
${r}TOTAL: $tot"
```
This requires a perl reflection module (`B::Keywords`). Can be installed on ubuntu with `sudo apt-get install libb-keywords-perl`. With the seed given in the code above it generates the 728 answer:
```
ABCDEFGHIJKL
##############
1 #dumplogforqr#
2 #lcfirstbreak#
3 #socketshmctl#
4 #requiregiven#
5 #lengthgmtime#
6 #getserventdo#
##############
B1 uc 2+40
C2 fc 2+40
F3 tr 2+40
G1 gt 2+40
I1 or 2+40
J1 recv 4+80
L4 ne 2+40
A1 dump 4+20
E1 log 3+20
H1 for 3+40
K1 qr 2+0
A2 lcfirst 7+60
H2 break 5+40
A3 socket 6+40
G3 shmctl 6+20
A4 require 7+20
H4 given 5+40
A5 length 6+0
G5 gmtime 6+20
A6 getservent 10+0
K6 do 2+0
TOTAL: 728
```
Note that different versions of perl may have different RNG and different keyword list, but it should be easy to find a seed with a comparable result.
] |
[Question]
[
# Bricks and Stability Defined
*This question uses the same definition of bricks and stability as [Is the brick structure stable?](https://codegolf.stackexchange.com/questions/38548/is-the-brick-structure-stable)*
Let `[__]` represent a [masonry brick](http://en.wikipedia.org/wiki/Brick) and
```
.
.
.
BRK?BRK?BRK?BRK?
BRK?BRK?BRK?BRK?BRK?
BRK?BRK?BRK?BRK?
BRK?BRK?BRK?BRK?BRK? . . .
BRK?BRK?BRK?BRK?
BRK?BRK?BRK?BRK?BRK?
```
represent an arbitrary arrangement or *structure* of these bricks, with every other row offset by half a brick, as is usual in brick construction. The structure can extend up and to the right indefinitely, but the string representation will always be a perfectly rectangular text block (having trailing spaces where necessary) whose width is divisible by 4.
Each `BRK?` in the structure may either be a brick (`[__]`) or empty space (4 spaces).
For example, one possible (unstable - read on) structure is
```
[__] [__] [__]
[__] [__]
[__][__] [__]
```
A structure's stability is important, and a structure is only stable if every single one of its bricks is stable.
There are three ways an individual brick may be stable:
1. Any brick on the ground (the lowest line of bricks) is stable.
2. Any brick that has two bricks directly below it is stable:
```
[__] <- this brick is stable
[__][__] <- because these bricks hold it up
```
3. Any brick that has a brick both above and below it on the same side is stable:
```
[__] [__]
[__] [__] <- these middle bricks are stable
[__] [__] because the upper and lower bricks clamp them in
[__] [__]
[__] [__] <- these middle bricks are NOT stable
[__] [__]
```
(Yes, I know these rules aren't physically accurate.)
The [last challenge](https://codegolf.stackexchange.com/questions/38548/is-the-brick-structure-stable) was about determining *if* a structure was stable. This one is about stabilizing those that aren't.
# Challenge
Write a program that takes in a potentially unstable arrangement of bricks and adds new bricks into empty brick spaces to make everything stable, printing the result. This is to be done without increasing the overall dimensions of the input text block.
The goal is to create an algorithm that makes the structure stable by adding as few bricks as possible.
[This JSFiddle](http://jsfiddle.net/CalvinsHobbies/4nn3scqw/embedded/result/) ([source](http://jsfiddle.net/CalvinsHobbies/4nn3scqw/#base)) lets you generate random arrangements of bricks for use while testing your program. (Wish I could [stack snippets](http://meta.codegolf.stackexchange.com/questions/2201/do-we-want-stack-snippets) instead.) `Width` is the number of bricks on the base layer, `Height` is the number of brick layers, and `Density` is the fraction of filled brick spaces.
For example, with `Width = 5, Height = 3, Density = 0.6` a possible output is
```
....[__]....[__]....
..[__]....[__]......
[__]............[__]
```
A way to stabilize this with 4 new bricks is
```
....[__]....[__]....
..[__][__][__][__]..
[__][__]....[__][__]
```
Your program must be able to stabilize any brick structure the JSFiddle can generate.
* This includes the empty string (which is considered stable).
* The brick will always be `[__]`. Periods (`.`) are only used for clarity. Your program may use periods or spaces for empty space.
* The structure may already be stable, in which case nothing needs to be done (besides printing it).
* The JSFiddle always generates structures that can be stabilized (by avoiding `Width = 1` and bricks in the top corners). You can rely on this. (Filling all but the top corners is sure to stabilize things but this is clearly not optimal.)
* Assume no invalid input. Take input as string however you like. Print the stabilized structure to stdout or similar.
* Remember that the text block dimensions should not change size.
* Preexisting bricks cannot be moved or removed. Placement of new bricks must follow the offset-every-other-row grid pattern. All bricks must be completely in bounds.
* It is encouraged (but not required) that you print the preexisting bricks as `[XX]` instead of `[__]`, so people can better see how your solution works.
# Scoring
At the bottom of [the JSFiddle](http://jsfiddle.net/CalvinsHobbies/4nn3scqw/embedded/result/) are 8 predefined unstable brick arrangements. (They use `[__]` and `.` and should stay that way unless you're using `[XX]` and/or instead.) Some are random and some I created myself. To calculate your score, run your program on each of them in turn and sum the number of **new** bricks added to each.
The less new bricks you've added the better. The submission with the lowest score wins. In case of ties the oldest answer wins.
If things get contentious I may add a few more predefined cases and judge the winner based on them.
# Further Notes
* Your program needs to run on the order of minutes on a modern computer for brick grid width and height less than 100. (Max 10 minutes on a computer [like this](https://teksyndicate.com/forum/general-discussion/average-steam-users-computer-specs/150190).)
* You may not hardcode your output for the 8 predefined structures. Your program must treat them as it would treat any other arrangement.
* Please include an example output or two, or any interesting structures you'd like to share. :)
* This problem is somewhat related to finding a [minimum spanning tree](http://en.wikipedia.org/wiki/Minimum_spanning_tree).
[Answer]
# Java - 5,056 bricks
* 20x20, 0.03 - **75**
* 15x81, 0.05 - **431**
* 50x50, 0.20 - **882**
* 99x99, 0.01 - **2,567**
* Plain Pedestal - **269**
* Simple House - **129**
* Criss-Cross Tower - **323**
* Bridge Beginnings - **380**
Source code is viewable [here](http://pastebin.com/Wm4Ncv6b).
The code runs in a few milliseconds for any of the 8 scoring inputs. There are some noticeably suboptimal outputs, particularly in the criss-cross tower and 99x99 cases. I have several ideas on how to improve the routine, but it's fairly bulky as-is, and hence I'll let it alone for now.
The outputs massacre the laws of physics to a comedic extent. :D
Some samples are shown below.
### 20x20, 0.03 Output
```
................................................................................
..........[XX]..................................................................
........[ ][ ]................................................................
..........[ ]..................................................................
............[ ]................................................................
..........[ ]..................................................................
............[ ]....................[XX]........................................
..........[ ]....................[ ][ ]......................................
....[XX]....[ ]....................[ ]........................................
..[ ][ ][ ][ ]................[ ]..........................................
....[XX]....[ ][XX]................[ ]........................................
..[ ]........[ ]................[XX]..........................................
....[ ]........[ ]............[ ][ ]........................................
..[ ]........[ ]................[ ]..........................................
....[ ]........[ ]............[XX]................................[XX]........
..[ ]........[ ]....[XX]........[ ]................[XX]........[ ][XX][ ]..
....[ ]........[ ][ ][ ]....[ ]....[XX]........[ ][ ]........[ ][ ][XX]
..[ ][ ]....[ ]....[ ]........[XX][ ][ ]........[ ]........[ ]....[ ]..
....[ ]........[ ]....[ ]....[ ]....[ ]............[ ]........[ ]....[ ]
......[XX]....[ ]....[ ]........[ ][ ]............[ ]........[ ]....[ ]..
....[ ]........[ ]....[ ]....[ ]....[ ]....[XX]....[ ]........[ ]....[ ]
```
### Simple House Output
```
................................................................................
................................................................................
................................................................................
......................................[XX]......................................
....................................[XX][XX]....................................
..................................[XX][ ][XX]..................................
................................[XX][ ][ ][XX]................................
..............................[XX][ ]....[ ][XX]..............................
............................[XX][ ]........[ ][XX]............................
..........................[XX][ ]............[ ][XX]..........................
........................[XX][ ]................[ ][XX]........................
......................[XX][ ]....................[ ][XX]......................
....................[XX][ ]........................[ ][XX]....................
..................[XX][ ]............................[ ][XX]..................
................[XX][ ]................................[ ][XX]................
..............[XX][ ]....................................[ ][XX]..............
............[XX][ ]........................................[ ][XX]............
..........[XX][ ]............................................[ ][XX]..........
........[XX][ ]................................................[ ][XX]........
......[XX][ ]................................................[ ][ ][XX]......
....[XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX]....
......[XX][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]....[XX]......
....[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]........[XX]....
......[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[XX]......
....[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]........[XX]....
......[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[XX]......
....[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ]........[XX]....
......[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ][ ][ ]....[XX]......
....[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ][ ][ ]........[XX]....
......[XX]....[XX][XX][XX][XX][ ]....[XX][XX][XX][XX][XX][XX]........[XX]......
....[XX]....[ ]....[ ]....[ ]....[ ]....[ ]....[ ][ ]............[XX]....
......[XX]....[XX]....[ ][XX]........[XX]....[ ]....[ ][XX]........[XX]......
....[XX]....[ ]....[ ][ ][ ]....[ ]....[ ]........[ ]............[XX]....
......[XX]....[XX]....[ ][XX]........[XX]....[ ]........[XX]........[XX]......
....[XX]....[ ]........[XX]........[ ]....[ ]........[ ]............[XX]....
......[XX]....[XX]........[XX]........[XX][XX][XX][XX][XX][XX]........[XX]......
....[XX]....[ ]........[ ]........[ ]....[ ][ ][ ][ ]............[XX]....
......[XX]....[XX]........[XX]........[ ]....[ ]....[ ]............[XX]......
....[XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX]....
```
[Answer]
# Python, 18992
This is the most simplistic solution and the worst score possible. It's only for reference; the thing to beat.
It fills every empty space except the two top corners with bricks, guaranteeing stability.
```
s = '''
....[__]....[__]....
..[__]....[__]......
[__]............[__]
'''
def brickify(structure):
structure = filter(lambda x: x, s.replace('__', 'XX').split('\n'))
if not structure:
return '', 0
if len(structure) > 1 and len(structure) % 2:
structure[0] = '----' + structure[0][4:-4] + '----'
added = 0
offset = False
for i in range(len(structure)-1,-1,-1):
line = structure[i]
if offset:
line = line[2:-2]
added += line.count('....')
line = line.replace('....', '[__]')
if offset:
line = '..' + line + '..'
structure[i] = line
offset = not offset
structure[0] = structure[0].replace('----', '....')
return structure, added
s, a = brickify(s)
#print '\nNew bricks:', a
for line in s:
print line
```
To use copy the initial structure into the triple quotes at the top of the program.
Here it is run on the house, adding 609 bricks:
```
..[__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__]..
[__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__]
..[__][__][__][__][__][__][__][__][__][XX][__][__][__][__][__][__][__][__][__]..
[__][__][__][__][__][__][__][__][__][XX][XX][__][__][__][__][__][__][__][__][__]
..[__][__][__][__][__][__][__][__][XX][__][XX][__][__][__][__][__][__][__][__]..
[__][__][__][__][__][__][__][__][XX][__][__][XX][__][__][__][__][__][__][__][__]
..[__][__][__][__][__][__][__][XX][__][__][__][XX][__][__][__][__][__][__][__]..
[__][__][__][__][__][__][__][XX][__][__][__][__][XX][__][__][__][__][__][__][__]
..[__][__][__][__][__][__][XX][__][__][__][__][__][XX][__][__][__][__][__][__]..
[__][__][__][__][__][__][XX][__][__][__][__][__][__][XX][__][__][__][__][__][__]
..[__][__][__][__][__][XX][__][__][__][__][__][__][__][XX][__][__][__][__][__]..
[__][__][__][__][__][XX][__][__][__][__][__][__][__][__][XX][__][__][__][__][__]
..[__][__][__][__][XX][__][__][__][__][__][__][__][__][__][XX][__][__][__][__]..
[__][__][__][__][XX][__][__][__][__][__][__][__][__][__][__][XX][__][__][__][__]
..[__][__][__][XX][__][__][__][__][__][__][__][__][__][__][__][XX][__][__][__]..
[__][__][__][XX][__][__][__][__][__][__][__][__][__][__][__][__][XX][__][__][__]
..[__][__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__][__]..
[__][__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__][__]
..[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][__]
..[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][XX][XX][XX][XX][__][__][XX][XX][XX][XX][XX][XX][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][XX][__][__][XX][__][__][XX][__][__][__][__][XX][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][XX][__][__][XX][__][__][XX][__][__][__][__][XX][__][__][XX][__]..
[__][XX][__][__][__][__][XX][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][XX][__][__][XX][__][__][XX][XX][XX][XX][XX][XX][__][__][XX][__]..
[__][XX][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][__][XX][__]
..[__][XX][__][XX][__][__][XX][__][__][__][__][__][__][__][__][__][__][XX][__]..
[__][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][XX][__]
```
The number of bricks it adds for each of the 8 predefined structures in order are
```
374 1107 2041 9627 506 609 1088 3640 (sum to 18992)
```
] |
[Question]
[
## Problem
I've got a GREAT new program that will change the way we think about math in computing, taking in strings of algebraic functions and doing AMAZING things with them! The only problem, is that I am only able to parse specific algebra, otherwise the universe folds into itself, which is bad. Fortunately, I only need a few basic operations in this amazing new program's input, but I still need it expanded!
## Rules
* An answer must be able to simplify the following expressions
+ `2+2` should reduce to `4`
+ `(5+x)+6` should reduce to `x+11`
+ `(x+2)^2` should reduce to `x^2+4*x+4`
+ `(x-5)*(3+7*x)` should reduce to `7*x^2-32*x-15`
+ `5*x+9*x` should reduce to `14*x`
+ `(2*x^2)*x^3` should reduce to `2*x^5`
* Answers must be able to COMPLETELY remove parenthesis, which implies that all distribution must take place.
* Answers should be able to handle all of the following operators and standard tokens:
+ `+` (The addition function)
+ `-` (The subtraction function)
+ `*` (The multiplication function)
+ `(` (The left parenthesis, used to indicate a group)
+ `)` (The right parenthesis, used to indicate the end of the last started group)
+ `x` (The standard variable)
+ `[0-9]+` (literal nonnegative numbers)
* Answers must be capable of at least squaring, using the notation expr^2, including (expr)^2 recursively, since (expr) is itself an expression ;)
* A solution must be in a standard infix notation, none of the RPN nonsense!
* No library functions such as Mathematica's `Simplify` to do this for you.
* Solution should be a function that takes in a single argument and return the expanded version
As this is code-golf, the answer with the fewest (key)strokes wins, 1 week from OP.
## Notes
There are no spaces in this world of math, of course! Only parenthesis.
So no division is required to save from factoring
Standard order of operations apply.
I'm aware that some of what I'm asking is simplification (e.g. `2+2=4`) where other parts are actually the opposite, such as expanding `(x+1)^2` to be `x^2+2x+1`. This is intentional. :)
-25 strokes for a solution that can do (expr)^n instead of just (expr)^2
-15 strokes for a solution able to evaluate juxtaposed multiplication, such as `4x+5x` == `9x`, or `4(x+1)` = `4x+4`
-5 strokes for a solution able to handle multiple variables (A variable being exactly one lowercase alphabet character)
-5 strokes for a solution able to remove leading 0's (`007` to just `7` [Not today, Bond!] [Jeez now I feel like I'm writing Lisp])
[Answer]
# J - 350 char - 25 = 325 pts
Forgive me, Roger Hui, for I have sinned.
```
x=:0 1
f=:(('+_';'-';'_';'-')rplc~' '-.~'+'}.@,@|.@,.s(}.@]`(,&":)@.t'*x'"_`('*x^',":)`(''"_)@.t=.*@<:@[)/"1@#~0~:0{|:@s=.,.i.@#)@p=:(0{::'()'+/@,:&,e'+'@((+/@,:&,-)~e'-')@(*/a e'*')@('^'(*/(a=.+//.@)/@#,:e=:2 :'(<@; ::({:u/&.>{.)/.~i.@#-i.@#(>+>:)(<,v){.@i.~])^:_'))@:(([^:(''-:])". ::])&.>)@([-.~;@]<@(p^:(1<#));.1~1,0=2*/\[:+/\(*0,}:@)1 _1 0{~i.)&;:])
```
The above monstrosity defines a number of variables, of which the variable `f` is a function satisfying the constraints in the question above. I claim the "expr^n" bonus for 25 points.
Here's the golf in action at the J REPL.
```
x=:0 1
f=:(('+_';'-';'_';'-')rplc~' '-.~'+'}.@,@|.@,.s(}.@]`(,&":)@.t'*x'"_`('*x^',":)`(''"_)@.t=.*@<:@[)/"1@#~0~:0{|:@s=.,.i.@#)@p=:(0{::'()'+/@,:&,e'+'@((+/@,:&,-)~e'-')@(*/a e'*')@('^'(*/(a=.+//.@)/@#,:e=:2 :'(<@; ::({:u/&.>{.)/.~i.@#-i.@#(>+>:)(<,v){.@i.~])^:_'))@:(([^:(''-:])". ::])&.>)@([-.~;@]<@(p^:(1<#));.1~1,0=2*/\[:+/\(*0,}:@)1 _1 0{~i.)&;:])
f '2+2'
4
f '(5+x)+6'
x+11
f '(x+2)^2'
x^2+4*x+4
f '(x-5)*(3+7*x)'
7*x^2-32*x-15
f '5*x+9*x'
14*x
f '(2*x^2)*x^3'
2*x^5
f '(2*x+3)^(2+3)*2^3' NB. bonus
256*x^8+1920*x^7+5760*x^6+8640*x^5+6480*x^4+1944*x^3
```
Here's the gist of what's going on.
* `'()'...@([-.~;@]<@(p^:(1<#));.1~1,0=2*/\[:+/\(*0,}:@)1 _1 0{~i.)&;:` - Recursively break down the expression based on its parenthesized subexpressions, and evaluate them (the `...` bit, to be described below) as they are ready. `;:` performs the tokenizing.
* `(([^:(''-:])". ::])&.>)` - Evaluate atoms. If the atom is numeric, it is turned into a scalar number. If the atom is an operator, it is left as-is. If the atom is the variable `x`, it is turned into the vector `0 1`. (That's why we define `x=:0 1` at the start.) In general we store the polynomial `a*x^n + b*x^(n-1) + ... + c*x + d` as the `n+1`-item list `d c ... b a`.
* `e=:2 :'(<@; ::({:u/&.>{.)/.~i.@#([->+>:){.@i.&(<,v))^:_'` - This curious conjunction takes a verb on the left and a character on the right. It finds the first instance of that character in its tokenized, paren-less input, and evaluates it with the arguments around it, and repeats until there are no more such characters to find. Thus, we iteratively simplify the expression, with order of operations controlled by order of application of `e`.
* And then all the stuff in the front is just pretty-printing output. `rplc` is a standard library function for substring replacement. We can save another three chars if we're allowed to put the lowest degree terms first instead of the highest, by removing the `@|.`.
I am honestly uncertain whether I can squeeze any more characters out of this golf. I can't think of any other approach that doesn't require a similar amount of overengineering, but that doesn't mean there isn't one. Either way, I'm pretty sure I've squeezed all the obvious characters out of this version.
[Answer]
# JavaScript (EcmaScript 6) 698 (748-50 bonus) ~~725 780 1951~~
~~To be golfed~~. But I'm proud it works.
(Edit: bug fix, problems with brackets and minus)
(Edit2: golfed more, fixed bug in output)
(Edit3: golfed once more, last time I promise)
**Comment**
Basically, function X is an infix calculator that operates on literal polynomials.
Each polynomial is stored as a js object, the key being the term (x^3y^2) and the value being the numeric coefficient. Function A,M and E are add, multiply and exponent.
**Golfed Code**
(It cannot probably be golfed more...)
Note: not counting newlines added for (ehm...) readability
```
K=x=>Object.keys(x).sort(),
A=(p,q,s,t,c)=>[(c=(s+1)*q[t]+~~p[t])?p[t]=c:delete(p[t])for(t in q)],
M=(p,q,t,c,o,u,f,r,v={})=>([A(v,(r={},[(c=p[f]*q[t])&&(r[o={},(u=f+t)&&(u.match(/[a-z]\^?\d*/ig).map(x=>o[x[0]]=~~o[x[0]]+(~~x.slice(2)||1)),K(o,u=k).map(i=>u+=o[i]>1?i+'^'+o[i]:i)),u]=c)for(f in p)],r),k)for(t in q)],v),
E=(p,n)=>--n?M(p,E(p,n)):p,
O=n=>{for(l=0;h(o=s.pop())>=h(n);)a=w.pop(b=w.pop()),o=='*'?a=M(a,b):o>d?a=E(a,b[k]):A(a,b,o),w.push(a);s.push(o,n)},
X=e=>(l=k='',w=[],s=[d='@'],h=o=>'@)+-*^('.indexOf(o),
(e+')').match(/\D|\d+/g).map(t=>(u=h(t))>5?(l&&O('*'),s.push(d)):u>1?O(t):~u?s.pop(s.pop(O(t)),l=1):(l&&O('*'),l=1,w.push(v={}),t<d?v[k]=t|0:v[t]=1)),
K(p=w.pop()).map(i=>(k+=(c=p[i])>1?s+c+i:c<-1?c+i:(c-1?'-':s)+(i||1),s='+')),k||0)
```
**Test** In FireFox console
```
['2+2','(5+x)+6','(x+2)^2','(a+b)(a-b)','(a+b)*(a-b)','(a-b)(a-b)', '(x-5)*(3+7*x)','5*x+9*x','(2*x^2)*x^3','(2*x+3)^(2+3)*2^3']
.map(x => x + ' => ' + X(x)).join('\n')
```
**Output**
```
2+2 => 4
(5+x)+6 => 11+x
(x+2)^2 => 4+4x+x^2
(a+b)(a-b) => a^2-b^2
(a+b)*(a-b) => a^2-b^2
(a-b)(a-b) => a^2-2ab+b^2
(x-5)*(3+7*x) => -15-32x+7x^2
5*x+9*x => 14x
(2*x^2)*x^3 => 2x^5
(2*x+3)^(2+3)*2^3 => 1944+6480x+8640x^2+5760x^3+1920x^4+256x^5
```
**Bonuses**
```
25: 2*x+3)^(2+3)*2^3 => 1944+6480x+8640x^2+5760x^3+1920x^4+256x^5
15: 4x+5x => 9x
5: 007x+05x^(06+2) => 7x+5x^8
5: (a+b)(a-b) => a^2-b^2
```
**Ungolfed Code**
```
Show=(p)=>(
Object.keys(p).sort().map(i=>(c=p[i])-1?c+1?c+i:'-'+i:i).join('+').replace(/\+-/g,'-')
)
AddMonoTo=(poly, term, coeff, c)=>(
(c = coeff + ~~poly[term]) ? poly[term]= c : delete(poly[term])
)
AddPolyTo=(p1, p2, s, t)=>(
[ AddMonoTo(p1, t, (s+1)*p2[t]) for (t in p2)]
)
MulTerm=(t1, t2, o={})=>(
(t1+=t2)&&
(t1.match(/[a-z](\^\d+)?/g).every(x=>o[x[0]]=(~~x.slice(2)||1)+(~~o[x[0]])),
Object.keys(o,t1='').sort().every(i=>t1+=o[i]>1?i+'^'+o[i]:i)),
t1
)
MulMono=(poly, term, coeff, c, r={}, t)=>(
[(c = poly[p]*coeff) && (r[MulTerm(p,term)] = c) for (p in poly) ],r
)
MulPoly=(p1, p2, r={}, p)=>(
[AddPolyTo(r,MulMono(p2, p, p1[p]),'') for (p in p1)],r
)
ExpPoly=(p,n,r=p)=>{
for(;--n;)r=MulPoly(r,p);
return r
}
Expand=ex=>
{
var tokens = ex.match(/\D|\d+/g).push(')')
var t,a,b,v,LastV=0
var vstack=[]
var ostack=['_']
var op={ '+': 3, '-':3, '*':4, '^':6, '(':8, _: 1, ')':2}
var OPush=o=>ostack.push(o)
var OPop=_=>ostack.pop()
var VPush=v=>vstack.push(v)
var VPop=v=>vstack.pop()
var Scan=i=>
{
LastV=0 ;
for (; (t=tokens[i++]) && (t != ')'); )
{
if (t == '(')
{
if (LastV) CalcOp('*')
OPush('_'), i=Scan(i)
}
else if (op[t])
LastV=0, CalcOp(t)
else
{
if (LastV) CalcOp('*')
LastV = 1
VPush(v={})
t < 'a' ? v[''] = t|0 : v[t] = 1
}
}
CalcOp(t);
OPop();
OPop();
LastV=1;
return i;
}
var CalcOp=nop=>
{
for (; op[po = OPop()] >= op[nop];)
b=VPop(), a=VPop(), CalcV(a,b,po);
OPush(po), OPush(nop);
}
var CalcV=(a,b,o)=>
{
if (op[o] < 4)
AddPolyTo(a,b,o)
else if (o == '*')
a=MulPoly(a,b)
else // ^
a=ExpPoly(a,b['']) // only use constant term for exp
VPush(a)
}
Scan(0)
return Show(vstack.pop())
}
```
[Answer]
# Mathematica: 56 - 25 - 15 - 5 - 5 = 6
Of course no library functions as `Expand` or `Distribute`, just pattern replacement. Mathematica does almost everything for us (hax!), what is left are just rules for distribution and power expansion. The only non-trivial examples therefore are `(x-5)*(3+7*x)` and `(x+2)^2`.
```
f=#//.{x_ y_Plus:>(x #&/@y),x_Plus^n_:>(x #&/@x)^(n-1)}&
```
Examples
```
(x-5)*(3+7*x) // f
-15 - 32 x + 7 x^2
(x + 2)^2 // f
4 + 4 x + x^2
```
] |
[Question]
[
The challenge is a follow-up to [Filter a large file quickly](https://codegolf.stackexchange.com/questions/26643/filter-a-large-file-quickly) which had two submissions where were as fast as wc! This time the difficulty is that RAM is severely restricted which means that new methods will have to be used.
* Input: Each line has three space separated positive integers.
* Output: All input lines `A` `B`, `T`that satisfy either of the following criterion.
1. There exists another input line `C`, `D`, `U` where `D = A` and `0 <= T - U < 100`.
2. There exists another input line `C`, `D`, `U` where `B = C` and `0 <= U - T < 100`.
To make a test file use the following python script which will also be used for testing. It will make a 1.3G file. You can of course reduce nolines for testing.
```
import random
nolines = 50000000 # 50 million
for i in xrange(nolines):
print random.randint(0,nolines-1), random.randint(0,nolines-1), random.randint(0,nolines-1)
```
**Rules.** Your code must use no more than 200MB of RAM. I will enforce this using `ulimit -v 200000`. Your code must therefore also run on ubuntu using only easily installable and free software.
**Score.** You can report your unofficial score by testing on your machine as (the time in seconds needed by Keith Randall's submission from [Filter a large file quickly](https://codegolf.stackexchange.com/questions/26643/filter-a-large-file-quickly) divided by the time in seconds taken by your submission )\*100 .
**Winning criterion.** The winner will be the one with the highest score when I test the code on my computer using a file created by the sample python code. I will first run
```
sync && sudo bash -c 'echo 3 > /proc/sys/vm/drop_caches'
```
before each test run.
The deadline is one week from the time of the first correct entry.
**My Machine** The timings will be run on my machine. This is a standard 8GB RAM ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code.
**Some relevant timing information**
largefile.file is a file created using the sample python code.
```
sync && sudo bash -c 'echo 3 > /proc/sys/vm/drop_caches'
time wc largefile.file
real 0m26.835s
user 0m18.363s
sys 0m0.495s
time sort -n largefile.file > /dev/null
real 1m32.344s
user 2m9.530s
sys 0m6.543s
```
[Answer]
# Tcl with SQLite, score less than 0.05
Shove the lines into an SQL database, then make SQLite do the work. Requires the Tcl bindings for SQLite 3, OpenBSD package [sqlite3-tcl](http://ports.su/databases/sqlite3,-tcl), Ubuntu package [libsqlite3-tcl](http://packages.ubuntu.com/utopic/libsqlite3-tcl).
Usage: `tclsh filter.tcl <input.txt >output.txt`
```
package require sqlite3
sqlite3 db ""
db eval {
begin transaction;
create table lines(i integer primary key,
a integer, b integer, t integer);
}
while {[gets stdin line] >= 0} {
lassign [split $line] a b t
db eval {insert into lines values(null,$a,$b,$t)}
}
db eval {
create view pairs as
select first.i, second.i as j
from lines as first, lines as second
where first.a == second.b and
first.t - second.t between 0 and 99 and
first.i != second.i;
select a, b, t from lines
where i in (select i from pairs union select j from pairs);
} {
puts "$a $b $t"
}
db close
```
## Comparison of time
The motto of SQLite is, "Small. Fast. Reliable. Choose any three," but my SQL query is not fast. My program took more than **six hours** with my slow hard disk. I compare times for three programs:
* *cfilter* is the large-memory [C program by Keith Randall](https://codegolf.stackexchange.com/a/26999/4065)
* *hfilter* is the large-memory [C program by James\_pic](https://codegolf.stackexchange.com/a/26960/4065)
* *filter.tcl* is my small-memory Tcl program
With 50 million lines of input, *cfilter* and *hfilter* both crash because my data size limit is only 1 GB. (The default limit in OpenBSD is 512 MB.) If I raise my limit to 8 GB with `ulimit -Sd 8388608`, then I can run both *cfilter* and *hfilter*. I also lower my physical memory limit with `-m 3000000` so that other programs stay in RAM, not in swap space. I have only 4 GB of RAM.
```
$ ulimit -Sd 8388608 -m 3000000
$ time ./cfilter input.txt >output.txt
0m9.03s real 0m5.17s user 0m1.97s system
$ ln -sf input.txt test.file
$ time ./hfilter >output2.txt
0m25.62s real 0m22.08s user 0m2.04s system
$ time tclsh8.6 filter.tcl <input.txt >output3.txt
^Z 371m19.57s real 0m0.00s user 0m0.00s system
[1] + Suspended tclsh8.6 filter.tcl < input.txt > output3.txt
```
I suspended *filter.tcl* after more than 6 hours. `top` shows that *filter.tcl* used less than 15 MB of memory and less than 12 minutes of processor time. Most of the 6 hours went to wait for my slow hard disk (5400 rpm).
For score, 10 seconds for *cfilter*, divided by more than 6 hours for *filter.tcl*, times 100, equals **less than 0.05**.
## Comparison of results
The different filters do not select the same lines! Consider these 6 lines of input:
```
$ cat example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400
3 3 555
```
My *filter.tcl* outputs five lines, all except `3 3 555`.
```
$ tclsh8.6 filter.tcl <example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400
```
But *cfilter* only outputs three lines:
```
$ ./cfilter example.txt
804 2 400
805 2 400
2 803 499
```
*cfilter* seems to have a bug when `T - U == 0`. It fails to output the lines `1 801 33` and `802 1 33`, though I believe them to be a matching pair.
Now for *hfilter* and the [Scala program by the same author](https://codegolf.stackexchange.com/a/26816/4065):
```
$ ln -sf example.txt test.file
$ ./hfilter
804 2 400
2 803 499
805 2 400
2 803 499
3 3 555
3 3 555
$ scala Filterer example.txt /dev/stdout
804 2 400
2 803 499
802 1 33
1 801 33
805 2 400
2 803 499
3 3 555
3 3 555
```
*hfilter* also misses the lines `1 801 33` and `802 1 33`, but the Scala version finds them. Both programs output `2 803 499` twice (because it is in two matching pairs), but I might ignore such duplication. Both programs also output `3 3 355`. This line is in a pair with itself because `A = B`. This is only correct if the phrase "another input line" includes the same line.
When the input is the random 50 million lines from the Python script, these differences might disappear. The probability that any matching pair has `T - U = 0`, or any line has `A = B`, is close to zero when the input has random numbers up to 50 million.
[Answer]
## C, score 55.55
Same as my [other implementation](https://codegolf.stackexchange.com/questions/26643/filter-a-large-file-quickly/26999#26999), but it does the radix sort using disk files. Uses ~25MB of memory, mostly for buffers.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define R 3
#define B 9
#define M ((1<<B)-1)
#define BUFSIZE 4096
#define PARSEBUF 65536
typedef struct {
int a,b,t;
} entry;
typedef struct {
int fd;
int lo;
int hi; // bytes buf[lo]..buf[hi-1] are valid.
entry e; // scratch
char buf[PARSEBUF];
} ParseState;
entry *parse(ParseState *s) {
int n = s->hi - s->lo;
// if we need to, grab some more data
if(n < 100 && s->fd != -1) {
memmove(&s->buf[0], &s->buf[s->lo], n);
int k = read(s->fd, &s->buf[n], PARSEBUF - n);
if(k == 0) s->fd = -1;
n += k;
s->lo = 0;
s->hi = n;
}
if(n == 0) return NULL;
// parse line
char *p = &s->buf[s->lo];
int a = 0;
while(*p != ' ') {
a *= 10;
a += *p - '0';
p++;
}
p++;
int b = 0;
while(*p != ' ') {
b *= 10;
b += *p - '0';
p++;
}
p++;
int t = 0;
while(*p != '\n') {
t *= 10;
t += *p - '0';
p++;
}
p++;
s->lo += p - &s->buf[s->lo];
s->e.a = a;
s->e.b = b;
s->e.t = t;
return &s->e;
}
typedef struct {
int fd;
int lo;
int hi;
entry buf[BUFSIZE];
} ReadBuf;
entry *bread(ReadBuf *b) {
if(b->lo == b->hi) {
int k = read(b->fd, &b->buf[0], BUFSIZE*sizeof(entry));
if(k == 0) return NULL;
b->lo = 0;
b->hi = k / sizeof(entry);
}
return &b->buf[b->lo++];
}
typedef struct {
int fd;
int offset; // offset in file to write buffer
int n; // # of entries
entry buf[BUFSIZE];
} WriteBuf;
void bflush(WriteBuf *b) {
int size = b->n * sizeof(entry);
pwrite(b->fd, &b->buf[0], size, b->offset);
b->offset += size;
b->n = 0;
}
void bwrite(WriteBuf *b, entry *e) {
b->buf[b->n++] = *e;
if(b->n == BUFSIZE)
bflush(b);
}
int count[R][1<<B];
int accum[R][1<<B];
unsigned char bcount[16384];
ParseState s;
ReadBuf rd;
WriteBuf wr[1<<B];
entry recent[65536];
char print[65536];
int main(int argc, char *argv[]) {
int fd = open(argv[1], O_RDONLY);
int fd1 = open("tmp1", O_RDWR | O_CREAT | O_TRUNC, 0666);
int fd2 = open("tmp2", O_RDWR | O_CREAT | O_TRUNC, 0666);
// parse input, write first file, do stats for radix sort
entry *e;
s = (ParseState){fd, 0, 0};
wr[0] = (WriteBuf){fd1, 0, 0};
while((e = parse(&s)) != NULL) {
bwrite(&wr[0], e);
// compute counts for radix sort
int t = e->t;
for(int r = 0; r < R; r++) {
count[r][t&M]++;
t >>= B;
}
}
bflush(&wr[0]);
// accumulate count entries
for(int r = 0; r < R; r++) {
int sum = 0;
for(int i = 0; i < 1<<B; i++) {
accum[r][i] = sum;
sum += count[r][i];
}
}
// radix sort
int fda = fd1;
int fdb = fd2;
for(int r = 0; r < R; r++) {
lseek(fda, 0, SEEK_SET);
rd = (ReadBuf){fda, 0, 0};
for(int i = 0; i < 1<<B; i++) {
wr[i] = (WriteBuf){fdb, accum[r][i]*sizeof(entry), 0};
}
while((e = bread(&rd)) != NULL) {
bwrite(&wr[(e->t>>r*B)&M], e);
}
for(int i = 0; i < 1<<B; i++) {
bflush(&wr[i]);
}
int t = fda;
fda = fdb;
fdb = t;
}
// find matches
lseek(fda, 0, SEEK_SET);
ReadBuf rd = {fda, 0, 0};
int lo = 0;
int hi = 0;
while((e = bread(&rd)) != NULL) {
recent[hi] = *e;
print[hi] = 0;
while(recent[lo].t <= e->t - 100) {
int x = recent[lo].b & 16383;
if(bcount[x] != 255) bcount[x]--;
if(print[lo])
printf("%d %d %d\n", recent[lo].a, recent[lo].b, recent[lo].t);
lo++;
}
if(bcount[e->a & 16383] != 0) {
// somewhere in the window is a b that matches the
// low 14 bits of a. Find out if there is a full match.
for(int k = lo; k < hi; k++) {
if(e->a == recent[k].b)
print[k] = print[hi] = 1;
}
}
int x = e->b & 16383;
if(bcount[x] != 255) bcount[x]++;
hi++;
if(hi == 65536) {
if(lo == 0) {
printf("recent buffer too small!\n");
exit(1);
}
memmove(&recent[0], &recent[lo], (hi - lo) * sizeof(entry));
memmove(&print[0], &print[lo], (hi - lo) * sizeof(char));
hi -= lo;
lo = 0;
}
}
}
```
] |
[Question]
[
Write a program, which, upon gazing at a chess table, can say whether there is a check or a checkmate.
**Input**: a chess table in text form, the last line of the input being the first rank (the starting line of White)
The starting position in this input would look like this (space is an empty square, capital letters are White): why aren't the spaces displayed here?
```
rnbqkbnr
pppppppp
PPPPPPPP
RNBQKBNR
```
The program should print one or more of the following (without quotes, of course), depending on the situation:
* "The White King is in check!" *(if already in checkmate, don't display this!)*
* "The Black King is in check!" *(if already in checkmate, don't display this!)*
* "The White King is in checkmate!"
* "The Black King is in checkmate!"
* "White is in stalemate!" *(There would be a stalemate if White moved - **optional**)*
* "Black is in stalemate!" *(There would be a stalemate if Black moved - **optional**)*
* "Both kings are safe for now." *(if none of the above apply)*
The input is guaranteed to be correct and be a legal chess position (no two kings of the same color, no two kings in check, etc.).
**Score:**
The score is the character count, lowest wins, not sooner than 10 days after the first valid answer. If the optional stalemate evaluation is implemented, the size will be decreased by 20% (for this situation, assume en-passant cannot be performed).
[Answer]
## C, 837-20%=669.6 chars
Based on [this answer](https://codegolf.stackexchange.com/a/4864/3544). You can see some explanations about the implementation there.
The original is golfed quite well, the modifications not so much, so there's room for improvement.
I also wouldn't be surprised to find bugs, my QA wasn't very rigorous.
```
char*r=" KPNBRQ kpnbrq $ ,&)$wxy()879()8(6:GI(",B[256],*b=B,i,Q,s,*X[]={"Stalemate","Checkmate","","Check"};
e(x,d,m,V,c,r,n,p){
p=b[x];
return(m/r?
n=x+d*r,
p-2-8*(d<0)&&!(n&136)&&(b[n]?r=8,p&8^b[n]&8&&c&65^64:c&65^65)&&
((V?v(n,x):b[n]%8==1&&(s&=~((b[n]>7?8:2)))),e(x,d,m,V,c,r+1))
:0)||d>0&&e(x,-d,m,V,c,1);
}
d(x,v,m,i)char*m;{
(i=*m-40)? e(x,i%64,b[x]%8-2?b[x]&4?7:1:(x/16-1)%5|i%2?1:2,v,i,1),d(x,v,m+1):0;
}
v(t,f){
b[t]%8-1?
(s&(b[f]>7?8:2))==0?
bcopy(B,b+=128,128),
s|=(b[f]>7?8:2),
b[f]^=b[t]=b[f],
a(b[t]<8,63),
b=B
:0
:
(s|=b[f]>7?1:4);
}
a(c,n){
b[i=n*2-n%8]&&b[i]/8==c?d(i,!Q++,r+r[b[i]%8+15]-10),Q--:0;n--&&a(c,n);
}
p(c,t){
return(t=c?s%4:s/4)!=2&&printf("%s%s%s is in %s\n",t?"The ":"",c?"White":"Black",t?" king":"",X[t]);
}
main(){
for(;gets(b);b+=8)for(;*b;b++)*b=strchr(r,*b)-r;b=B;
a(0,63);
a(1,63);
p(0)||p(8)||puts("Both kings are safe for now");
}
```
] |
[Question]
[
Goal is to write the shortest possible C89 and C99-compliant single-module C program which will compute and print out a single-line string whose sort order will correspond with the date given by the predefined `__DATE__` macro (in other words, later dates will yield later-sorting strings). The programmer is free to arbitrarily select the mapping between dates and strings, but every entry should specify the mapping and it should be obvious that it will sort correctly (e.g. a programmer could decide to compute (day + month\*73 + year\*4129) and output that as a number, though it's likely that particular encoding would probably require a longer program than some others).
The program should yield identical results on any standards-compliant compiler on which 'int' is 32 bits or larger and both source and target character sets are 7-bit ASCII, and should not rely upon any implementation-defined or undefined behavior nor print any characters outside the 32-126 range except for a single newline at the end. The program should contain the following aspects indicated below (replacing *«CODE»* with anything desired):
```
♯include <stdio.h>
*«CODE»*int main(void){*«CODE»*}
```
All output shall be produced by the `printf` at the end (i.e. the correct value will be in an `int` called `z`). The required elements will be included in the character total for each entry.
Code should operate correctly for all future dates through `Dec 31 9999`. Libraries which are standard in both C89 and C99 may be used, provided that appropriate headers are included. Note that standard date libraries may not be assumed to operate beyond the Unix limits.
Note: Code is permitted to perform Undefined Behavior if and only if the `__DATE__` macro expands to a macro other than a date between `Feb 11 2012` and `Dec 31 9999` (expressed in that format, using C-standard abbreviated English month names Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
Note 2: For compliance with C99 standards, 'main' should return an arbitrary, but defined value, and the newline is required. The first requirement, btw, adds 7 characters to my best effort; the single new-line adds 5.
[Answer]
## C, 137 184 184 140 120 106 103 characters
Replaced the month name lookup with a magic formula.
The formula `(m[1]*4388^m[2]*7)%252` is ascending for month names.
Changed it to nicely return 0, at no cost.
It no longer prints a number. Instead it prints a string, which should sort right.
Implemented supercat's `%*s` idea, which inserts more spaces for earlier months, along with a function that's descending for month names - `(m[1]*29^m[2]+405)%49`.
```
#include<stdio.h>
int main(void){
char*m=__DATE__"%*.6s\n"+1;
return!printf(m+6,(*m*29^m[1]+405)%49,m);
}
```
I thought single digit days are represented as `Jan_1_2012` (`_` being a space), when in fact it's `Jan__1_2012` (extra space). This complicated things, so my previous versions were more complicated:
```
#include<stdio.h>
int main(void){
char*m=__DATE__+1,*t=m+m[4]/16;
return!printf("%s%3d%s\n",t+3,(*m*4388^m[1]*7)%252,t);
}
```
[Answer]
## C, 194 characters
```
#include <stdio.h>
#include <string.h>
d,y,n[3];
int main(void)
{
sscanf(__DATE__,"%s %d %d",n,&d,&y);
return printf("%d%02d%02d",y,13-strlen(strstr("JanFebMarAprMayJunJulAugSepOctNovDec",n))/3,d);
}
```
I think most of the newlines are unnecessary, but I've left them in for readability.
Not sure what your feelings are about compiler warnings - this throws a few but runs fine. Also not sure whether the declarations with no type are valid C89 or not.
[Answer]
Here are the solutions that I had come up with (for brevity, I'm just writing the `#include` line once--copy and paste as needed to assemble a testable program).
```
(my entries)
#include <stdio.h>
int main(void){char*d=__DATE__"%s%sDFCwu-vBxE-t%c"+1;return printf(d+6,d+(*d+d[1])%17+9,d,10);}
int main(void){char*d="h-elbj-ikcfdga-"__DATE__+16;return printf("%s%s\n",d+6,d-(*d+d[1])%17);}
int main(void){char*d=__DATE__+1;return printf("%s%x%s\n",d+6,3**d+"![ WT -#[ 8"[d[1]%12],d);}
int main(void){char*d=__DATE__"%x%.5s\n"+1;return printf(d+6,3**d+"![ WT -#[ 8"[d[1]%12],d);}
int main(void){char*d=__DATE__"%x%.5s\n";return printf(d+7,d[1]+"1C0EB042E0:"[d[2]%12],d);}
(ugoren's entry, golfed, for comparison, and adding .5 to the %s format specifier)
int main(void){char*m=__DATE__"%3d%.5s\n"+1;return!printf(m+6,(*m*803^m[1]*95)%94,m);}
```
My initial approaches made use of a month-to-number approach which can turn each month into an arbitrary character. If in a production embedded-systems environment one had to turn an alphabetic month into a number 1-12, the approach might actually be an efficient algorithm to do so (perhaps using repeated subtract-17 instead of mod, if no other divisions are required).
Allowing the computation to return values which were sortable but not consecutive made it possible to use a smaller table indexed using the third character of the month, and add to that character the second. A further savings was achieved by realizing that the multiplication by three I'd used to facilitate "tiebreaking" was in fact not needed, since the months which would otherwise yield matching hash values were correctly sortable by their first character.
I tried quite a few variations, but nothing came close to the operator combination that ugoren found, which don't require any table. I was also impressed by his entry which would have accommodated single-digit dates without padding, which would have been a challenge in its own right, and one which I doubt that I could have handled as nicely.
[Answer]
## C, 163 characters
A different approach from my other solution.
I can save 13 characters by making `t` an int array, and relying on the internal layout of `struct tm`. But I guess it violates the rules.
```
#define _XOPEN_SOURCE
#include<time.h>
#include<stdio.h>
int main(void){
struct tm t;
strptime(__DATE__,"%b%d%Y",&t);
return printf("%d\n",t.tm_year*366+t.tm_yday);
}
```
] |
[Question]
[
## Challenge
Write a program which, given a 2-dimensional boolean array (equivalently, a monochromatic bitmap), outputs a series of polygons that describe the outline of the region that is “true” (1).
The input is provided as a sequence of `'#'` (hash), `' '` (space) and `\n` (newline) characters. Lines may differ in length, in which case the missing parts are assumed to be spaces. The output should be a (newline-separated) list of polygons, each polygon represented by a (comma-separated) list of coordinates.
## Examples & Requirements
1. **The co-ordinates must be listed in clockwise order.** Input:
```
#
```
Acceptable outputs include:
```
(0,0), (1,0), (1,1), (0,1)
(1,0), (1,1), (0,1), (0,0)
(1,1), (0,1), (0,0), (1,0)
(0,1), (0,0), (1,0), (1,1)
```
2. **Disjoint regions must return multiple polygons.** Input:
```
# #
```
Example output (actual output must consist of two lines):
```
(0,0), (1,0), (1,1), (0,1)
(2,0), (3,0), (3,1), (2,1)
```
3. **Holes in a polygon must be listed as a separate polygon, but in anti-clockwise order.** Input:
```
###
# #
###
```
Example output:
```
(0,0), (3,0), (3,3), (0,3)
(1,1), (1,2), (2,2), (2,1)
```
4. You are free to choose whether **diagonally adjacent vertices join up or not.** Input:
```
#
#
```
Example output:
```
(0,0), (1,0), (1,1), (0,1)
(1,1), (2,1), (2,2), (1,2)
```
or
```
(0,0), (1,0), (1,1), (2,1), (2,2), (1,2), (1,1), (0, 1)
```
5. The lists of coordinates need not be optimally short. For example:
```
##
```
Acceptable outputs:
```
(0,0), (2,0), (2,1), (0,1)
// Redundant coordinates along a straight line are acceptable
(0,0), (1,0), (2,0), (2,1), (1,1), (0,1)
// Duplicate start- and end-point are acceptable
(0,0), (2,0), (2,1), (0,1), (0,0)
```
As usual, shortest program “wins”.
[Answer]
## Perl, ~~345~~ ~~311~~ 265 chars
```
s!.!$i{$x++}=$&eq'#'!ge,$x=$r+=64for<>;sub a{$d+=@_||3;$d%=4;$y=$x%64;$z=$x>>6;$c.=", ($y,$z)";}for$x(keys%i){if($c=!$v{$x}&$i{$x}&!$i{$x-1}){$i{($x+=(1,64)[$d^3])-(64,65,1)[$d]}?$i{$x-(65,1,0,64)[$d]}?a 1:($x-=(64,1)[$d]):a while$d||!$v{$x}++;print substr$c.$/,3}}
```
### Limitations
Assumes that the input is no wider than 64 characters (but its height is in principle unbounded). This can be extended to 512 or 8192 or any other power of two by changing the relevant constants, making the code only slightly longer.
### Slightly more readable version
Some credit goes to [mob](https://stackoverflow.com/users/168657/mob) because the first line is my re-use of his idea in [lasers](https://stackoverflow.com/questions/1480023/code-golf-lasers/1480251#1480251). The rest is entirely my work.
```
# Read “%i”nput (this line is essentially mob’s idea, see above)
s!.! $i{$x++} = $& eq '#' !ge, $x = $r += 64 for <>;
# Subroutine to add a vertex to the current polygon and change the current “$d”irection
sub a
{
$d += @_ || 3;
$d %= 4;
$y = $x % 64;
$z = $x >> 6;
$c .= ", ($y,$z)";
}
for $x (keys %i)
{
# Go to the next “upward-pointing” edge that we haven’t already “%v”isited.
if ($c = !$v{$x} & $i{$x} & !$i{$x-1})
{
# We’re going in the “$d”irection of 0=up, 1=left, 2=down, 3=right
$i{($x += (1,64)[$d^3]) - (64,65,1)[$d]}
? $i{$x - (65,1,0,64)[$d]}
? a 1 # take a 90° turn to the left
: ($x -= (64,1)[$d]) # move straight ahead
: a # take a 90° turn to the right
# Only stop if the current “$d”irection is “up” and we encounter a “%v”isited edge
# (which necessarily is the one we started from)
while $d || !$v{$x}++;
# Remove “1, ” and output this polygon
print substr $c.$/, 3
}
}
```
### Edits
* **(345 → 312)** Realised there’s no need to update `$x` when taking a turn because the next iteration will already do it
* **(312 → 311)** Change `1`=down,`2`=left to `1`=left,`2`=down and update `$d` via XOR instead of directly
* **(311 → 265)** Remove repetition of the innermost expression and use arrays to parametrise it
[Answer]
## Python, 607 characters
The code works by keeping a list of the boundaries discovered so far as it processes # symbols in input order. The boundaries are stored in a table E which maps edges (4-tuples of x\_start,y\_start,x\_end,y\_end) to a list of edges which form the boundary of a polygon. As we process each new #, it may be connected to a polygon above (p) or to its left (q). The code finds p and q using E and then merges the boundary of the current # (r) with p and q, if they exist. The case where p==q generates holes.
```
import sys
x=y=N=0
E={}
def P(L):
if L:print ', '.join(map(lambda z:str(z[:2]),L))
while 1:
r,a,b,c=[(x,y,x+1,y),(x+1,y,x+1,y+1),(x+1,y+1,x,y+1),(x,y+1,x,y)],(x+1,y,x,y),(x,y,x,y\
+1),sys.stdin.read(1)
if not c:break
p,q=E.get(a),E.get(b)
if'#'==c:
if p:
i=p.index(a)
if q:
j=q.index(b)
if p==q:
if i<j:P(p[i+1:j]);p[i:j+1]=r[1:3]
else:P(p[i+1:]+p[:j]);p[i:]=r[1:3];p[0:j+1]=[]
else:p[i:i+1]=r[1:3]+q[j+1:]+q[:j]
else:p[i:i+1]=r[1:]
elif q:j=q.index(b);q[j:j+1]=r[:3];p=q
else:p=r
for e in p:E[e]=p
x+=1
if'\n'==c:y+=1;x=0
for L in E.values():
if L:P(L);L[:]=[]
```
] |
[Question]
[
Earlier I asked about this problem on stackoverflow ([link](https://stackoverflow.com/questions/77856631)), but now I also want to see the golfiest solutions
## Problem:
Given an array of arbitrary numbers, what is the longest subarray that is repeated (appears more than once)? In case there are multiple distinct repeated subarrays that all have the longest length, the answer can be any of them. If no subarray appears more than once, the answer is `[]` (the empty array).
Overlapping is allowed, that is partial occurrences of a subarray within itself is allowed. for ex, in the array `[1, 2, 1, 2, 1, 2]` the longest repeating subarray is `[1, 2, 1, 2]`. Look here
```
[1, 2, 1, 2, 1, 2]
^ ^ occurence #1
^ ^ occurence #2
```
## Constraints:
For the sake of code golf simplicity, assume that all values in the array are integers. like a 32bit int data type
The time complexity and the space complexity must be \$O(n^{2 - \varepsilon})\$ where \$n\$ = length of array, for some \$\varepsilon > 0\$.
## Test cases:
| Array | Result |
| --- | --- |
| [1, 2, 5, 7, 1, 2, 4, 5] | [1, 2] |
| [9, 7, 0, 1, 6, 3, 6, 5, 2, 1, 6, 3, 8, 3, 6, 1, 6, 3] | [1, 6, 3] |
| [1, 2, 1, 2, 7, 0, -1, 7, 0, -1] | [7, 0, -1] |
| [1, 1, 1, 1] | [1, 1, 1] |
| [1, 1, 1] | [1, 1] |
| [1, 2, 3, 4, 2, 5] | [2] |
| [1, 2, 3, 4, 5] | [] |
| [1, 6, 2, 1, 6, 2, 1, 5] | [1, 6, 2, 1] |
Also this JS code generates a large test case with an array of one hundred thousand elements which your program should be able to handle. The answer is [1, 2, 3, ..., 100] (the 100 consecutive integers from 1 to 100)
```
function make_case() {
let array = [];
let number = 200;
for (let i = 0; i < 500; i++) {
array.push(number); array.push(number);
number++;
}
for (let i = 1; i < 101; i++) {
array.push(i);
}
for (let i = 0; i < 1700; i++) {
array.push(number); array.push(number);
number++;
}
for (let i = 1; i < 101; i++) {
array.push(i);
}
for (let i = 0; i < (100_000 - 500 * 2 - 100 - 1700 * 2 - 100) / 2; i++) {
array.push(number); array.push(number);
number++;
}
return array;
}
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~378~~ ~~360~~ ~~359~~ ~~339~~ 337 bytes, \$O(n \sqrt{n} \log^2 n)\$
```
#import<bits/stdc++.h>
using V=std::vector<int>;V f(V a){int l=0,r=a.size(),n,j,i=0,m,L=r,s=sqrt(r);std::map<V,int>M;V v(L),x;for(;i+s<L;)v[i++]=M[x]=M[x=V(&a[i],&a[i+s])]?:~i;for(;M.clear(),l<r;l>m?:r=m)for(i=m=l+r>>1;i<=L;i++){V x;for(j=i-m;j<i;j+=j+s<i?s:1)x.push_back((j+s<i?v:a)[j]);l=M[x]++?n=i-m,m+1:l;}return V(&a[n],&a[n-1+l]);}
```
[Try it online!](https://tio.run/##zVNRb9owEH6ef4WlScWeE0ho07I4Du8T1d7ywtAUsrQ1S0xmB4ZasZ8@dnagsHVomrSHgeK7@@6@u8udUzSNf18Uu91rWTdL3SZz2ZqBaT8VjPUfUrQyUt3jTAASx@uyaJc6kapNeYbvSIZz@gQWrkTgaZH3jXwsCfWUt/AkQLU3EdozwnzRLdGUuyR13iSZZ3PcQpI1mVBvw@@WmnDJTDLhdD2VjM3E7XTjDpGRi3wqZ549mZnR2Tj@JjvGbb@oylxDySrRvErrcaxFTa1PilpUTKdpyGUiJpCc0acMd6UWQvo1XySSL5hYQFk5NnFIN/1mZR4@zvPiMyEdvI5zOl3MKK9cQ4yNleV6NQvjim912a60wq5F5VpUfsgqiN/u7GDqXCpC8RPC8LNAy53qJlFIhdP0AH19kFVJWt8/hB8oij@bp7QTOIO4hih6ROAlMQHyBd7g2HrpT9zNKXe5arGAbdoojl51cRZMEuvbL9VavQ@q97KGKwGBhxJ76sYxcO/X7vfuY64tcmIwwO/ydW4KLRuYU2naIjcl6nrMtebPM1Srel5q6HkYBB3qFg4eCWDAQSQ4CqwCS7fck712ZOqdgzuFsZeJQ5cY5JnMkp5tJrz5n7ohwOkFQYB9OyX8Bg9BC51tGz0CFA/w8B/0fbxjEE5Pv4A/XLO/umK/uV7b3QiNUAjvE@EbbOUVjlA4Qm/BDAC4xpfwRODo9JGznY7CwDHtY4P9cC/QFeDujy47DV27yEvIDpVQ9GxFrvr1Pr09o@/FXZXfm53/fvgD "C++ (gcc) – Try It Online")
-3 thanks to @Unmitigated. -1 thanks to @movatica. -11 thanks to @ceilingcat. -2 thanks to @ceilingcat.
Mostly ungolfed:
```
#include <bits/stdc++.h>
using V=std::vector<int>;
V f(V a) {
int l=0,r=a.size(),n,j,i,m,b,L=r,s=sqrt(r);
std::map<V,int> M;
V v(L);
for(int i=0;i+s<L;i++) {
V x(a.begin()+i,a.begin()+i+s);
v[i]=M[x]=M[x]?M[x]:~i;
}
while (l<r) {
m = (l+r)/2;
b=0;
std::set<V> S;
for (i=m;i<=L;i++) {
V x;
for(j=i-m;j<i;j+=j+s<i?s:1)x.push_back((j+s<i?v:a)[j]);
S.insert(x).second||(n=i-m,b=1);
}
b?l=m+1:r=m;
}
return V(a.begin()+n,a.begin()+n-1+l);
}
```
uses binary search, and sqrt decomposition for fast-ish substring comparison.
Takes a few seconds for the \$n=100000\$ case when compiled with `-O2`.
] |
[Question]
[
[Level-index](https://en.wikipedia.org/wiki/Symmetric_level-index_arithmetic) is a system of representing numbers which has been proposed as an alternative to floating-point formats. It claims to virtually eliminate overflow (and underflow, in its symmetric form) from the vast majority of computations.
The usual floating-point format internally represents a number \$x\$ in terms of a mantissa \$m\in[1,2)\$ and an integer exponent \$e\$, where \$x=m\times2^e\$. In contrast, level-index represents a number by an integer level \$l\ge0\$ and an index \$i\in[0,1)\$, defined by
\$l+i=\psi(x)=\begin{cases}
x,&x<1\\
1+\psi(\log x),&\text{otherwise.}
\end{cases}\$
Equivalently, \$l\$ and \$i\$ together represent the power tower number \$x=\psi^{-1}(l+i)=\operatorname{exp}^l(i)\$. Accordingly, \$\psi^{-1}\$ grows very fast; \$\psi^{-1}(5)\$ has more than a million digits to the left of the decimal point.
## Task
Given two numbers \$\psi(a),\psi(b)\$, compute their level-index sum \$\psi(a+b)\$. You may choose to input or output the level and index together or separately.
Your solution should be accurate to at least six digits after the decimal point and terminate in a reasonable time for all \$\psi(a+b)<8\$, and may not assume your floating-point representation has infinite precision.
### Test cases
```
ψ(a) ψ(b) ψ(a+b) a b a+b
0 0 0.0000000000000000 0 0 0
1 1 1.6931471805599453 1 1 2
2 2 2.5265890341390445 2.718281828 2.718281828 5.436563657
3 3 3.2046791426805201 1.5154262e1 1.5154262e1 3.0385245e1
4 4 4.0161875057657443 3.8142791e6 3.8142791e6 7.6285582e6
5 5 5.0000000044114734 2.3e1656520 2.3e1656520 4.7e1656520
1.70879 2.44303 2.6490358380192970 2.031531618 4.746554831 6.778086449
0.8001 3.12692 3.1367187876590184 0.8001 2.2470167e1 2.3270267e1
2.71828 3.14159 3.2134989633416356 7.774915755 2.368508064 3.1459996e1
4.6322 4.6322 4.6322790036002559 1.79455e308 1.79455e308 3.58910e308
4.80382 4.80382 4.8038229252940133 5.9037e4932 5.9037e4932 1.1807e4933
```
[Answer]
# [SageMath](https://www.sagemath.org/), 93 bytes
```
lambda x,y:h(p(x)+p(y))
h=lambda x:x>1 and 1+h(log(x))or x
p=lambda x:x>1 and exp(p(x-1))or x
```
[Try it online!](https://sagecell.sagemath.org/?z=eJxtkcuOozAQRfdI_EPtALWDym87mvSPTI9adOIkaNIBAS3BRPn3KUNYJd7YpTq-tx7H3UeaXKrvr0MFI5u257zNx-KtzaeiSJPzbk1tx3cO1fUA_O2cX5oTQUXTwZgm7TMTxjbKbPjKpMkQ-uFzhB3kyIAzEAwkA8VAU1hadNYzwNIhxmRpuROO8qWRQsTboXSieOhMr3VEqZRECmXJhfFifiiu_SshqjHsh3BYpUrjJVfki1p7r7SMeloY7TxKxaVHpXRUFKiM9VwJQ6iI5aoSueHOatTWaEtFUDklPo5SnHSlinpGkZh20iH3wlucK5SGXK2jrx65U7MHl8o7byQ5G6nN2oD1iNIgCr00NTcjvNDCK-RSUl_7c9j_DV1sK_v4EVbtMwbzi8uM8se4ETaxAPUV_tVtvmyGwTJZButgim2aAJ24tOvPd-jqfXX5rNq2a8ac-EN9qod-Z4sFm15h0xMWXmHhCesJO5LL9IhPTRM3VX31eQ8bCAX8Ah42dsm2XX0d8mN2G-8MbtMdNu9w6-9wewzjd_z-554V_wFttLxc&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [Python](https://www.python.org) NumPy, 178 bytes
```
def f(I):
i,j=sort(I)
if 4+i>j<5.5:
j=[add,logaddexp][l:=i>1](p(j-l),p(i-l))
while j>=1:l+=1;j=log(j)
j+=l
return j
p=lambda x:x>1 and exp(p(x-1))or x
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVNLctswDF10p1NwKScKByABftzK-5whk3acWG6kkS2NrEyds3STTXuA3qY9TUF_lDic4bxHgQCBB-jn7_5lfOq2r6-_nsf1Tfj7Z1Wt1Tq_nc0zVRdNueuGUU5yWCu6rhfNF9YsNtWUd8vVqmi77wLVvr-_a-dlvcD7vM-bm3ZW9HktIJ7qx1PdVqpZlDhvr0v83JTilTfJ1FyXbaaGanwetqrJ-rJdbh5WS7Wf7xeoltuVktAScX-Ds1k3qH22HrqN2j5v-hdVb3rJ7uqU-de12FtVb1XXV9scUgXL4qF4LK6-qVJtln2-brvlWLR617f1mKfcbsvh253cus9UP9TbMU8eqfyi3j223a7KD4fH2ez4yuu_TzNQxzWhhg_rzfb-3oFneGITahctkscAzDES2zfb-3tpmcyc2Rk1G8chgiW0EYg4fZNgJqR9wVmTdexk-8ye_CfUBsj5iGScJGIAU2aMLGdT4QW3GmxgQ1xhRif_CTWgw-AZ2Ms7RDbFDhJWYlfugnvtTGAOpnIZn_wnnDQlQlHHUqrLVigFSHYXnLQ_8wy1h-Cj2OVpsIKORBwONgBGEz2kOGCRbcoz-ZJjpmBROe19gOCIYgY6QNLAajQumoTWiZQ-SFkRMFDq-_HOsQ-GvJQumaTcjAeTeHbSP_kTckw6o6UYorPSMWfZKdHBe4rInjn5usAQwNHBRyYiuqSzdtaYpO979BHAOgAjk5P65WV8uLIQLrjVMiAIiUucIM0z6gOaaNhEArQ2aS-K-YqiNRcctczogdup7-fppGmivI5nPP4y_wE)
Saved a bit by borrowing @Noodle9's `p` function.
### Previous [Python](https://www.python.org) NumPy, 202 bytes
```
def f(I):
i,j=sort(I);l,*c=0,
if 4+i>j<5.5:
l=i>1
for y in i,j:
r=y%1
while y>=1+l:r=exp(r);y-=1
c+=r,
j=[add,logaddexp][l](*c)
while j>=1:l+=1;j=log(j)
return l+j
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVNLctswDF10p1Nw0xnJVjggCfCTVNnnDJm04zpyI49saWRlWp-lm2zaw_QG7WkK-KPE4YzmPZIACDxAP3_3-_Gp2768_HoeV1fx75_HeqVW-V1xnammXFe7bhh5d9OWs2UFJR-uFM6b2_Un0sQ2qq2aW8O46ga1V81WvORcDdX-o1yo709NW6v9bWXm7fVQ1T_6fChu9lfV4XY5rwYOq9bV_eLxsWy7bwxs83DfPuSzZZGdA6w5wHU7r8zNumKrfM1XQz0-D1vVztfZaug2avu86TmJTc9Zz04VfZbMWsms6-ttDlLZovxaLsvZF1WpzaLPV223GMtW7_q2GfOCA99Vw5d7tnrIVD802zEXD5GlbHbLttvV-WGzLIrjKy__PhSgjmtCDe_W691buwPPzIlNqH1yBoOJQJQSknu9e2sny2b2zM6oyXqKCRwalwCR5IyD2SjfBSeNzpPnL2Tu5D-htoA-JIPWcyIWjGRGhnhva3PBnQYXySLVJsOT_4QajDcxEFDgdxCdxI4clmPX_oIH7W0kirb2GZ38J5w0RTSsjkOpy9WGC-DsLjjqcOaZ0QFiSHzPT4Nj9MjiUHQRTLIpgMQBZ8hJnuKLngijM8rrECJEj5gy0BFEA6eN9ckKOs9ShshlJTARpe9Hm2MfLAYunTOR3GwAKzw76S_-aCiJzsZhisk77ph35BXrEAImQ4FIfH0kiODx4MMTkbzorL2zVvR9iyEBOA9geXKkX4HHh2oH8YI7zQNiQDjHidw8q96hTZZsQjDOifasWKgxOXvBjeYZPXA39f08nThNVNDpjMdf5j8)
I'm sure this can be golfed quite a bit.
### How
With the given accuracy requirements we need something to bridge the gap between small values (<4.5, say) where we can use exp without overflowing and large (>5.5) where we can simply use the max. Luckily, NumPy has `logaddexp` built in which saves us one level of exponentiating.
] |
[Question]
[
A polyiamond of size \$n\$ is a contiguous shape formed by joining \$n\$ equilateral triangles side by side.
Your output should consist of two distinct characters, plus whitespace as necessary (▲ and ▼ work great!). Trailing whitespace is acceptable. You may use any other characters - but you may count ▲▼ as 1 byte each regardless of code page. If you use other characters, you must indicate which character corresponds to the up-facing triangle and which to the down-facing triangle.
You may not output duplicates - rotations and reflections of the same polyiamond are considered the same.
n=1: `▼`
n=2: `▲▼`
Note that
```
▼
▲
```
is not a valid polyiamond - which is why the distinct characters are necessary!
n=3
```
▲▼▲
```
n=4
```
▲
▲▼▲
▲▼▲▼
▲▼▲
▼
```
### Challenge
* You may either take no input and output polyiamonds indefinitely or take a number \$n\$ as input and output all distinct polyiamonds of size \$n\$.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code wins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 277 bytes
```
f=->p=[[2]],s=1{w=45;q=[]
p.map{|a|t=(?.*~-w+$/)*s;a.map{|k|t[k]="AV"[k%2]};$><<t
(s*3).times{|i|a.index(d=[-1,1,w*~0**e=a[i/3]][i%3]+e)||(c=a+[d];r=[]
12.times{|j|c=c.map!{|k|j%2<1?k%w*2+~k:k/w+k%w*w-(k/w+k%w)/2*~-w}.sort!.map{|m|m-c[0]/2*2+20}
r<<c*1}
q<<r.min)}}
f[q&q,s+1]}
```
[Try it online!](https://tio.run/##NY5NboMwGET33CJRqMAGg027KXaiXqKbT144/EiORQqYilbYXJ0Wpd3NaKR5b/y8fm9bK9JzLwCYlIkVdJnF80s5CJBBTzrVL065SUQXgtZ0xqcsRrZUj8G4CYwUx7f3I5iQSV@ezpxPQWRREZNJd41dnHaK6HvdfEW1gJQmNJnRmiPUCAU6K6QEHRYSN7FzUSUUhlqW406n7P/i5ipR7cjDzryFjNOLCWfE8GpeTTbjvcxp9BfjjO2untiPcTo8VDvXpRXk8ndimOU@GDmvEPXBwPlIOn2PvQ9aGJ6GxGIq/daC3H4A "Ruby – Try It Online")
First golfed version. Runs indefinitely
# [Ruby](https://www.ruby-lang.org/), 316 bytes
```
f=->n,p=[[2]],s=1{w=n*4+1
p.map{|a|t=(?.*~-w+$/)*s;a.map{|k|t[k]="AV"[k%2]};puts t,$/}
s<n&&(q=[]
p.map{|a|(s*3).times{|i|d=[-1,1,w*~0**e=a[i/3]][i%3]+e
a.index(d)||(c=a+[d];r=[]
12.times{|j|c=c.map!{|k|j%2<1?k%w+~(k/w)*w:(k/w+k%w*w)-(k/w+k%w)/2*~-w}.sort!.map{|m|m-(c[0]&-2)+n*2};r<<c*1}
q<<r.min)}}
f[n,q&q,s+1])
}
```
[Try it online!](https://tio.run/##RY/NaoQwAITvPkV3WSV/6iaWHqrp0pfoJeSQ@gOumKpxSYuJr24ry9LTDDPwMTPdPn@2reHxmyYDF4JJSQyni@UaPWMaDEmvhsUpN3NwSdAaW3xKITK5uhedm0Un@fH94yi6kEmfD7fZPM3klPrAFDqKwMiF/OcAgzKYzG1fm8W1ruIipoQSi9YzQjVXok0zKUUbZhLXgUpaXdXfoILOgZIrLCqZTzuQsgfk6kpe7vjDPucasoJeutDiFXSphci@7or/EmRh/PAwZfsZn5ivaT7cx/Wuj0EpzjKKGcQaMZ9PRVEi6oOxKKakbzX0PmiEJmM0EoOphIHfGvEit18 "Ruby – Try It Online")
This is a first working version, drawing heavily on my answer to [Sticky polyhexes](https://codegolf.stackexchange.com/q/222709/15599)
It's a function, taking the max size as input. Letting the code run indefinitely would probably be shorter.
**Explanation**
The code is a function taking one required and 2 optional inputs as follows:
* `n` max size of polyiamond
* `p` an array of polyiamonds
* `s` the size of the polyiamonds in the array.
If `p` and `s` are not given it is assumed that `s=1` and p contains the polyiamond `[2]` as a seed.
The board is `w` characters wide in the `x` direction and for calculation purposes is infinite in the `y` direction. Polyiamonds are represented as arrays of integers, one per triangle, of the form `d=x+wy`. It's important that `w` be odd, since this means that the oddness or evenness of `d` will determine whether upward pointing `A` or downward pointing `V` will be displayed. Therefore `w` is chosen as `n*4+1`.
The first task is to display the polyiamonds fed to the function as arguments. It is assumed that up to `s` lines may be needed to display these. This version uses `.` as a background, so the number of lines can be conveniently used to count the number of triangles in the polyiamond if this is not obvious.
If `s<n` we have not finished so we need to generate the list of polyiamonds of one size greater. To do this we start an empty array and run through all polyiamonds `a` in the input `p`. We take each triangle `e` in `a` and generate new triangles at `e+1`,`e-1` and `e+/-w`. To determine the correct sign for the last of these, -1 (represented as `~0` due to Ruby priority rules) is raised to the power `e`. If the new triangle is already in `a` it is an overlap and can be rejected. If it is not in `a` we have increased the size of the polyiamond, so we form a new polyiamond `c`.
We apply 12 symmetry operations to `c` (see below) forming an array `r` and add the lexically lowest one to `q`. Once the process is finished for all polyiamonds in `p` we find the intersection `q&q` of `q` with itself to eliminate duplicates and then call `f` again with the new list of polyiamonds of size `s+1`.
**Symmetry**
The most challenging part was working out the symmetry operations. These are actually done at 45 degrees to my answer to the sticky polyhexes question above. The triangle grid can be considered as two interpenetrating hex grids, one of all upward pointing triangles and the other of all downward pointing triangles, so it's similar but different.
All 12 symmetries can be generated by alternating two reflections. The first (parallel to a triangle edge) is a negation of the `y` axis. But rather than a change of sign, a bitflip of the y coordinate is employed. This changes the oddness/evennness of all triangles, causing the symbol to flip at the same time.
`k` = `k%w+~(k/w)*w`
The second (perpendicular to a triangle edge)is a transposition of the x and y axes. However a skew correction term is required, since opposite corners of a diamond `VA` are 2 units across in the `x` direction and 1 unit down in the `y` direction. Therefore the half the manhattan distance from the origin `x+y/2` is calculated and coordinates are adjusted by `-w-1` times this, causing a skew in a northeasterly direction.
`k` = `(k/w+k%w*w)-(k/w+k%w)/2*~-w`
Overall this looks like this:
```
start pattern flip vertical flip diagonal skew correction
012 AVA 543 AVA 50 AV 501 AVA
543 VAV -----> 012 VAV --> 41 VA --> 432 VAV
32 AV
```
] |
[Question]
[
There is a 3x3 square block made of 1x1 square blocks, with coins in each 1x1 block, starting from top left block you want to collect all the coins and return to top left block again, if possible provide instructions to achieve this.
Rules
* From block \$(x,y)\$ in one step you can move right(R) to \$(x,y+1)\$ ,left(L) to \$(x,y-1)\$ ,up(U) to \$(x-1,y)\$ ,down(D) to \$(x+1,y)\$ assuming the block to which we jump is not empty and is well inside our block
* We can take only one coin at a time.
* Just after performing the jump we collect 1 coin from our new position.
* Provide the route to take in form of a string, for example like RLRRDULU...
* You should collect all coins
* If there doesn't exist a solution route print/output -1
* If there exist multiple solution you are free to provide any
>
> Each 1x1 block can have upto 69 coins
>
>
>
Examples :
```
integer in each place denotes number of coins at each block
1 1 1
1 1 1
1 2 1
here DDRUDRUULL and RRDDLUDLUU both are correct (there might be more but you can print any one of your choice)
2 4 4
2 1 3
1 2 3
here DDUURDDRUULRLRDDLRUULL is a valid answer
5 5 1
5 4 5
5 2 2
here DURLRLRLRDLDUDUDUDRLRURLRLRDUDUULL is a valid answer
2 4 2
2 1 1
1 1 2
here doesn't exist a valid solution for this case so output -1
29 7 6
8 5 4
4 28 3
here doesn't exist a valid solution for this case so output -1
4 3 5
5 4 5
3 5 2
here DUDURLRDLDRULRLRDLRLRRLRUUDUDUDUDULL is valid solution
18 8 33
16 4 38
10 28 25
here DUDUDUDUDUDUDUDUDUDUDURLRLRLRLRLRLRDLDUDURLRLRDLRLRLRLRLRLRLRLRRUUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDDUDUDUDUDLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRUULL is a valid solution
69 69 69
69 69 69
69 69 69
here doesn't exist a valid solution for this case so output -1
7 5 9
21 10 68
15 3 56
here
DUDUDUDUDUDUDDUDUDUDUDUDUDUDUDUDUDUDUDUDUDRRLRLRUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUDUUDUDUDUDUDUDUDUDUDLRLRLRLRLRLUDUDUDUDUL is a valid solution
17 65 29
16 35 69
19 68 56
here doesn't exist a valid solution for this case so output -1
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code with answers being scored in bytes, but feel free to showcase any of your approach, I will be glad to read all those.
Edit : As mentioned we are starting from top left block, so the number of coins in the top-left block is apparently not decremented when the game starts.Also, as mentioned coin in a block can be as big as 69 so your code should be able to give output in reasonable time(not more than 60 seconds or timeouts), you can test your code in last 3 examples, feel free to ask for some more examples.
Note that it is promised that coin exist in each cell.
Edit : releaxed IO as suggested, return a list or string representing the moves, you can use 4 distinct values for L,R,U,D. If there is no solution, return a consistent value distinct from any solution
[Answer]
# [Python](https://www.python.org) NumPy, 245 bytes
```
def f(A,d="RL",e="DU"):
for x in r_[:A[0]]:
B=A[c_[[2,8,6,0],[1,5,7,3]]]-1;p="";m=A[4];t=m==sum(diff(B));B[3,0]-=x
for b,c in B:q,r=d;y=min(c-x,b);p+=x*d+q+(u:=c-x-y)*e+y*d+q;x=b-y;d=e;e=r+q;m-=u;t&=y>-1<m
if t:return p
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVTBbptAEL30xFeMODQQQ2TAOLbpVrLF0SckTpYVYVjKVoElsDTmB_oTvfjSHvpH7X_03lkgtpuklZp4Vuvd8e7b996M_OVb2YqMF4fD10ak5uzHr4SmkGpLIyFqsFYNSlQ_VPWFAimvYA-sgOpms1huxtstJmFFlpv4ZrOxjZkxNcZbY2MZrnFtONvt1rS8kqiql-OZydYTJCekbnItYWmqrXTdW20cvGKSPQJJ-J0RywdWizujIonXkpwVWmzujZ3ulSOyv0xGdyOtWRDMma1-SUetTHl7sjNbLyHUo6TCfW6SxhNvSfvetN7lCM5SEIuKiqYqoFTSiudQNHnZAstLXonLQfzn-4zdUrCkMGAkj4R24V1cfeRIgxVlIzRd0rxBkqplO6quXy0teZaTggsYjlzVIqpEfc9EpqkZrSgknNbFhVB1ebasWCE0ZnAj1ZjepYaL3vDdszn8fPPdAgylm-Hhg1sbkx2w7wchjnC9hqhIIAh8fx3iCGHHRQYRHol5VdFYgCa6Gzn7kAnY4YLjbtcIaHkDcVT0vBCmBV5Q4Kn8oYI44yymuqIoNkxggrMFTkfBeaAQhoHfkQjW8v2eDqshgk_RLUsQsr6nFSK44CJxF3FcnG2wB4QwWHfhr_2wC1z3Obn7G5rkY3d8eocGtMFroHtWi-Otmt82gvGiazORIV4c1RTTwBuBpoNpScg5XMNUmSHPiYLosweRrwGdgNPplapxdVLd6UbNQe-cnKTwcDBh0P3nU4hnzQB5YQ2mCOnMFGssidruCfZpDAaf2xwcHz2Ps-dfGMfFY-jn43F5j0JBUaZz6MZxAafUq8tyjaWYKzZ2zhim6KIryzR9xsR_qg16Ea_07D_iaerMzVPrPGsp9g62N3bgXDaP43aOWmjn7Kj8xY72_1m_AQ)
Not very golfed yet; apologies. This takes a flat array as input and returns a path or `None` if there is none.
#### How?
It essentially walks the boundary clockwise stepping back and forth as needed to collect all the coins using the centre as a reservoir.
If we label the blocks
```
a+1 b+1 c+1
d+1 e f+1
g+1 h+1 i+1
```
then we are looking for a nonnegative solution to
```
a = a1+a2
c = c1+c2
g = g1+g2
i = i1+i2
e = e1+e2+e3+e4
b = a2+e1+c1
f = c2+e2+i1
h = i2+e3+g1
d = g2+e4+a1
```
] |
[Question]
[
*Caves and Cliffs edition*
[Part 1](https://codegolf.stackexchange.com/questions/241136/is-this-continuous-terrain), [Very related](https://codegolf.stackexchange.com/questions/181708/would-this-string-work-as-string?noredirect=1&lq=1)
You're given a piece of ASCII art representing a piece of land, like so:
```
/‾\ _ __
__/ _/ \‾
_/ __/‾\ |
/ / ‾\ |
\_/‾ \_/
```
But unlike in the previous challenge, the terrain is mountainous, with caves and cliffs, and can turn back on itself. Also, a new character is introduced, `|`, which can connect to any of its four corners.
Since an overline (`‾`) is not ASCII, you can use a `~` or `-` instead.
Your challenge is still to determine if it is connected by the lines of the characters such that a single line connects them all without backtracking or crossing itself. For example, the above can be traced like so:
[](https://i.stack.imgur.com/Zbq6Z.png)
To clarify the connections:
* `_` can only connect on the bottom on either side
* `‾` (or `~` or `-`) can only connect on the top on either side
* `/` can only connect on the top right and bottom left
* `\` can only connect on the top left and bottom right
* `|` can connect on all four corners, but not to anything that connects to more than one corner. `|` must have a single connection above itself and a single connection below.
That one's a bit confusing, so the following are legal:
```
|
\
|
\
_
|_
‾|
/
```
And the following aren't:
```
|
‾
_
|
||
```
It doesn't matter where the connections start and end as long as they're all connected. Note that one line's bottom is the next line's top, so stuff like this is allowed:
```
_
‾
\
\
_
/
\
‾
```
You can assume input will only contain those characters plus spaces and newlines, and will contain at least one non-space character per column.
Input can be taken as ASCII art, an array of rows, a character matrix, etc.
## Testcases
Separated by double newline.
Truthy:
```
\
\
\_
\ /\/\_
‾ \
/\
\/
\_
‾\
/‾\
__/ ‾\_
\_/‾\
\
/‾\ _ __
__/ _/ \‾
_/ __/‾\ |
/ / ‾\ |
\_/‾ \_/
/‾\
\ /
/ \
____ _
___| | |
| ___| |
| |___ |
|___ | |
___| | |
|_____| |
_
/ \ _
| |_|
_
|_\
```
Falsy:
```
/
\
//
‾‾
/ \
‾
_
\____/
/‾‾‾\
\_
/
| |
‾‾‾
|_|
| |
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 190 bytes
```
WS⊞υιFυ«⸿Fι«M³→F№\|/κP|@#≡κ_P^²‾PV²/P/²\P\²»⸿⸿»J⁰¦⁰Fυ«⸿Fι«M³→≡κ|F⁸¿‹ ⊟KD³✳λP✳λ²»⸿⸿»UMKA⎇⁼#ιψι≔⟦⟧θF׳LυF׳⊕⌈EυLκ«Jκι≔LΦKM‹ λη¿∧‹ KK›²η⊞θ⟦ικη⟧»¿∨⁻²Lθ⊙θ⊖⊟ι⎚«≔⊟θηJ⊟η⊟ηW⌕AEKM‹ κ¹✳⁻³⊟ιψ¿⊖LKA⎚«⎚¹
```
[Try it online!](https://tio.run/##pVPbjpswEH2GrxixL0aiYi8vVfrSKNuttlrUqM3bskWIeIOFMWAg22gTqV/Wj@mPUI9tclOrPtRCIpkzMz7nzJDlqcyqlA/DS844BXIv6r772kkmVsT3Yd63OekDYP4797mSQHofXl1nrvCOeLH0VNzRANOAE1VrSm4CmHxhq7xD1MCzqtcV8Tb0AihU66jnHat1o8k2AO/9hW7mtC@sy3IghWmYpS0FL/EmJwXfArjW2Qb@9ePnWcL6NCE8g8NTOI7P8HjEdy4@e71G8c791Jf1oiKXAVz@hzN/lLpVVHTdWx/YM5AH2rbEA@XavKrJnNLilkmadawS2O7wh/t4jmUcY/8QFKX1rCrLVCz1FVPOiSpZUClSuSEfmj7lisWFh6sQwAZfqm7atmwlyONTAM3ow4KVtEVmD1SsOrU9SOoUuReZpCUVHV2SKP3Oyr5U7xoXzRYVvhGjbLFWF2YJHXulzbtjvKNSU46qSlIkfTAMHQkgxzJ0cqrEHbmpagjiHyVNsck1ptqVbwJ4ZGpPVehJ@4P1nyWJmOhbzLT3N9hgKjZYcEsPqnBUzEiYcZpKoppQrsb7uleAKc1Iz4rEWO6bSedosGM/yzsmljgTdOkvYgukcoUCzmZvON@YrgyzNqMjx5Stov30T7g7I3nnELJLdIW/d@5uGAAgVF9iDONJIEncJAlBPeOJVQaACzqmsH3BFqOYZ3JtXEdjnbbvoLu5w5s1/w0 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs a Charcoal boolean, i.e. `-` for continuous, nothing if not. Explanation:
```
WS⊞υι
```
Input the terrain.
```
Fυ«
```
Loop over the rows of the terrain.
```
⸿
```
Start each row on a new line. This is because we'll be drawing above the current line, so we want the actual drawing to start at row `0`.
```
Fι«
```
Loop over each character of the row.
```
M³→
```
Space the characters 3 apart. (This should be one before and two after, but unfortunately `Switch` makes doing that less golfy.)
```
F№\|/κ
```
If the current character is a `\`, `|` or `/`, then...
```
P|@#
```
... output a marker in case the character above or below is a `|`.
```
≡κ
```
Switch on the current character.
```
_P^²
```
If it's a `_` then write to the centre and the bottom left and bottom right corners of this `3×3` square.
```
‾PV²
```
If it's a `‾` then write to the centre and the top left and top right corners.
```
/P/²
```
If it's a `/` then draw from the bottom left to the top right.
```
\P\²
```
If it's a `\` then draw from the top left to the bottom right.
```
»⸿⸿
```
Add another two rows so that each row is spaced 3 apart vertically as well.
```
»J⁰¦⁰
```
Jump back to the beginning.
```
Fυ«⸿Fι«M³→
```
Loop through the rows and columns as before.
```
≡κ|
```
This time, only process `|` characters.
```
F⁸
```
Check all 8 directions. (Actually directions `0` and `4` are useless, but it's easier to include them.)
```
¿‹ ⊟KD³✳λ
```
See if there's a `\`, `|` or `/` in that direction.
```
P✳λ²
```
If so then draw a connection to it.
```
»⸿⸿
```
Finish processing each row.
```
»UMKA⎇⁼#ιψι
```
Remove any unused `#`s.
```
≔⟦⟧θ
```
Start collecting points that do not have two neighbours.
```
F׳LυF׳⊕⌈EυLκ«Jκι
```
Loop over each cell of the canvas, taking into account that it's offset by `2` characters to the right.
```
≔LΦKM‹ λη
```
Get the number of neighbours of this cell.
```
¿∧‹ KK›²η
```
If this cell is not empty and does not have two neighbours, then...
```
⊞θ⟦ικη⟧
```
... add it to the list.
```
»¿∨⁻²Lθ⊙θ⊖⊟ι
```
If there aren't exactly two points with exactly one neighbour each, then...
```
⎚«
```
... simply clear the canvas, otherwise:
```
≔⊟θηJ⊟η⊟η
```
Jump to one of the two ends.
```
W⌕AEKM‹ κ¹
```
While there is an adjacent character...
```
✳⁻³⊟ιψ
```
... erase the current character and move in that direction.
```
¿⊖LKA
```
If there is more than one character left, then...
```
⎚
```
... simply clear the canvas, otherwise...
```
«⎚¹
```
... clear the canvas and output success.
] |
[Question]
[
# Introduction
Formula One is a complex sport and as with complex sports, strategy is very important.Some teams will manage better strategy than others and those teams will often win the races.
After last weekends' amazing German GP, which saw last years Champion Lewis Hamilton pit 6 times (in comparison, some races just have 1 stop per driver), I was really impressed with all the strategy that was involved by most of the teams. Some really great calls, such as going to soft (from inters) by Racing Point, saw their driver finish 4th which was a rare sight.
---
# Challenge
**Your task will be to suggest what tire configuration should be used for the race.**
---
**Tires**
Here are the 3 available tire types :
*All of this data unofficial data, this is unreal data that was made juste for a fun challenge. I tried to keep a little sense in choosing how durable the tires wowuld be, but as I repeat, this is UNOFFICIAL*
```
Name Soft Medium Hard
Degradation (per character) 15 10 8
Degradation (per corner) 263 161 128
Time delta (per corner) (ms) 0 +30 +45
```
There is no time delta on the straights so all tire perform the same
A tires life span is calculated by how many COMPLETE laps it can do before dying. It's health starts at `100 000` and will decrease by the degradation value in the above table.
---
**Pit**
You will be able to change tires by going to the pits but a pit stop will cost you time.
That time is measured by the distance between P to P (the length EXCLUDES the `P`s on the start/finish straight multipled by 1750 milliseconds.
```
time for pits = (length between P to P) x 1750 ms
```
You must just complete the lap on the previous set of tires. So in a way, you are changing them at an imaginary line between the `#` and the character before it. Tire degradation in the pits are as if you were driving on track.
---
**Tracks:**
A corner is where the characters changes (look at exeption bellow)
All ascii characters can be used for the track (except the exceptions bellow that have specific meaning)
This does not count as a corner, it is just a kink. *This is just extra info seeing as the drawings are not considered official and just a representation to give users a better idea or to validate an algorithm.*
```
Ex 1
______
______
Ex 2
\
\
\
```
The `P` does not represent a corner , it is the pit entrance and exit. It still counts in track length though.
```
_____P_______________P__________
```
The `#` represents the start/finish line (the start and finish line will be the same for the purposes of simplifying things. They also count in track length. The race will start at an imaginary line between the # and whatever comes before it, so yes, the # will degrade the tires when the race starts. The `#` is also the first character in the input. You may assume that the last character of the track will be the same as the first character after the start/finish line (`#`).
---
# INPUT
The track:
1. A list/array of all the characters in order
2. A string with all the characters in order
Bonus. The track map drawing made out of the ascii characters (unofficial as it I won't garantee at this point int time that both the drawing and the string bellow are the same
Number of laps:
* An integer, however you want to receive it.
```
Ex.1 ["_P_#_P_||_______||", 250]
Ex.2 ["_","P","_","#","_","P","_","|","|","_","_","_","_","_","_","_","|","|"], 69
```
---
# OUTPUT
The tire strategy with 3 distinct characters to represent the 3 tire compound. Tires can be identified either with letters, numbers, or even words if you want.
You must output all the tires necessary for the race. Tire output must be from softest to hardest compouds.
```
Ex.1 [S, M, H]
Ex.2 [0, 1]
Ex.3 [Hard]
```
---
# OBJECTIVE
**TL;DR:** find the tire combination that optimizes time delta.
You must use all the tire data (constants) and the race data (track and number of laps, this will be your input) to optimize the best tire strategy (output) in order to minimize the time delta.
A time delta of 0 will be the perfect (but impossible) score, where you would run the soft tires (the fastest) the whole race. Thus, you must use a combinations of tires and run them for how many laps you want as long as it is still in the tires life span. Running soft for the whole race is fastest, but each time you change them at the end of a tire's life span, it will raise your time delta, because you must pit.
---
# Rules
* This is code golf so shortest code wins!
* The rest is almost a free-for-all (just don't hard code the answers in!)
---
# Example
Note, drawings are not offial, it is just for representation.
Also, the output aren't checked by another person then me yet, so if you are doing the challenge and find some errors, please notify me.
---
**1. Circuit de Spa-Francorchamps:**
*(yes I know it looks like a gun, but it isn't gun related, I promise, Google the track if you want):*
```
__________
_____^^^ ___________________________
_P_____ \___
<_____#_____P |
|_____________ ________ |
\ / | |
\ / |___|
\ |
| |
| _|
| |
|______|
```
INPUT :
```
#_____<_P__________^^^_____________________________________\___||||___||________//|||_||______||||\\\_____________|P_____
44 laps per race (according to Wikipedia, Belgian GP 2018)
```
OUTPUT: `[Medium, Medium]`
---
**2. Autodromo Nazionale Monza:**
```
________
\ \
\ \
\ \
\___ \
\ \____
\ \__________________________
\ \
\ /
\ _____/___P__#_________P________/
```
INPUT :
```
#__P_____/_____\\\\\___\\\\________\\\\\____\__________________________\//________P_________
53 laps per race (according to Wikipedia, Italian GP 2018)
```
OUTPUT : `[Soft, Medium]`
---
**3. Circuit Gilles Villeneuve:**
```
____
____| ____
__/ \___________
/ ____#___ _______
/P___/ |P______________________>
```
INPUT :
```
#____/___P//__/____|________\__________________>______________________P|___
70 laps per race (according to Wikipedia, Canadian GP 2019)
```
OUTPUT : `[Soft, Soft, Medium]`
---
**4. Pocono Raceway *(not an F1 track, but here to test edge-cases)***
```
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
________P______#_______________P_____
```
INPUT :
```
#_______________P_______\\\\\\\\\\\\\/////////////_________P_____
110 laps per race
```
*Number of laps is innacurate, according to USA Today, it is going to be 160 laps for the 2019 Sunday's Gander Outdoors 400, the 21st race in the Monster Energy NASCAR Cup Series. In F1, races are at least 305km, making any race around this raceway around 76 laps.*
OUTPUT : `[Hard]`
[Answer]
# JavaScript (ES6), 234 bytes
Takes input as `(track)(laps)`, where `track` is an array of characters. Returns a string with \$0\$ = soft, \$1\$ = medium, \$2\$ = hard.
```
a=>k=>(a.map(c=>(C++,d+=P,c=='P'|c=='#'?P^=350:t+=p!=(p=c)),p=a[1],P=d=C=t=0),m=g=(n,L=k,x=0,o='')=>L?g(n>>2,L-=j=(j=1e5/(C*[15,10,8][n&=3]+t*[263,161,128][n]))>L?L:j|0,x-j*t*!!n*~n*3+d,o+n):(m=m<x|m==x&o>P?m:(P=o,x),n?P:g(++N)))(N=0)
```
[Try it online!](https://tio.run/##jZLfb9owEMff@StMKxU7MflBoJuiXtCEtO2BIquV9gIBWUlgSRM7CqFjVbR/nSaQDJptWr8PPvusu/vc2RF/5lsvC9O8L6QfHNZw4OA8gYO5lvAUe@VuoqrUV4FRD6DHekVlrntjtgRrZNi5CmkXcAoeITQFPjddysCHCeRgEJrABrCgU3iiezCohF6PgDMdb7BwnAGd9iECHIEZjHQ8UebmiJoG/ejOxQ1Yrpor88GtRc1bk5qDyusSUgZP7agw6L4fKbnS7Qrll1As1adSFcTGCSR3@yIB2N9Ih40TGzOQdE@oGDN7g1V1RgjBsxLuoOvI1NAkzLxdmCM/QI8p73/OuPBk5n3nSbq10X3gh7uE1rbjSbGVcaDFcoPXeK5p2tX1qtLdiq1@a7lcrt6jxaJcilJH03h1vfI05@p6cdSb0OJU7soleDgkpNMpmxlo6NMul34mE4lm/CWUgscBupfihdvoUa7z//RxyqnXbI0uDmfwS08LrdWirjf784Qq7JFVY1vnN/gSxnGwRd8qI4Ldc9BgvwP@BM6qcseKxZspt@T8nZYVNdwHo4YbaojJsqBED9wLfvCfNvrKM//fH@Ei2R/Daku/VCuuojDNEuPwCg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~105~~ 102 bytes
```
³;`ẹ”PḊIḢ’×⁽£ż×’
ḟ⁾#PnƝS,L{ḋ“Ðẏ½Ƥ®x‘s2¤ÄUż“¡œ-‘¤ȷ5W¤÷Ḟµ⁴÷ḢḢĊ3ṗⱮẎịµZżÄŻ⁴_Ʋ{Ṃ€żʋ/>0Ḣ$ƇẈṪ,P€LÑ+SƲNƊƲ)MḢḃ3
```
[Try it online!](https://tio.run/##y0rNyan8///QZuuEh7t2PmqYG/BwR5fnwx2LHjXMPDz9UePeQ4uP7gEyGmZyPdwx/1HjPuWAvGNzg3V8qh/u6H7UMOfwhIe7@g/tPbbk0LqKRw0zio0OLTncEnp0D1Dq0MKjk3WBYoeWnNhuGg4U3/5wx7xDWx81bgGxFgHRkS7jhzunP9q47uGuvoe7uw9tjQLa1XJ0N1BJ/LFN1Q93Nj1qWnN0z6lufTsDoHKVY@0Pd3U83LlKJwAo7nN4onbwsU1@x7qObdL0BRvYbPz//38l5XgQsIkPiIeDuLi4eGJADBDXAAGYggnq64NEYHyQdExMDIq2GohVSv9NTAA "Jelly – Try It Online")
A full program that takes the track as a string as its first argument and the number of laps as its second argument. Returns a list of integers representing 1 for soft, 2 for medium and 3 for hard.
## Explanation
### Helper link: calculate pit time from number of tyres needed
```
³ | First argument for program (track as Jelly string)
;` | Concatenate to itself
ẹ”P | Indices of "P"
Ḋ | Dequeue (remove first element)
I | Differences between consecutive numbers
Ḣ | Head (i.e. difference between indices of the 2nd and 3rd Ps in the concatenated track)
’ | Decrease by 1
×⁽£ż | Multiply by 1750
× | Multiply by:
’ | - Argument to this link subtracted by 1
```
### Main link: stage 1
```
ḟ⁾#P | Remove all "#" and "P" from track
nƝ | Neighbours not equal (will return 1 for every change in symbol)
S | Sum (i.e. number of corners)
,L{ | Pair with length of original track
ḋ ¤ | Dot product with following as a nilad: (Will calculate degradation per lap for each tyre type and also extra time for the corners; works because of the way Jelly vectorises)
¤ | - Following as a nilad
“Ðẏ½Ƥ®x‘ | - 15, 248, 10, 151, 8, 120
s2 | - Split into twos [15,248],[10,151],[8,120]
Ä | - Vectorised cumulative sum [15,263],[10,161],[8,128]
U | - Vectorised reverse [263,15],[161,10],[128,8]
ż“¡œ-‘ | - Zipped with 0,30,45
ȷ5W¤÷ | Divide 100,000 by the first element of each (the degradation), leaving the additonal time per corner alone
Ḟ | Floor
µ | Start a new monadic link with this as its argument
```
### Main link: stage 2
```
⁴÷ | Second argument (number of laps) divided by output of stage 1
Ḣ | Head (values for soft tyres)
Ḣ | Head (laps per tyre for aoft tyres)
Ċ | Ceiling (i.e. max number of tyres that might be needed)
3ṗⱮ | 3 to the Cartesian power of each number from 1 to the max number of tyres needed
Ẏ | Tighten (remove one level of lists)
ị | Index into output from stage 1
µ | Start a new monadic link with this as its argument
```
### Main link: stage 3
```
) | For each of the possible tyre combinations:
Z | - Transpose, so we have a list of laps per tyre set and another list of the extra time for corners per lap
ʋ/ | - Reduce using following as a dyad:
ż Ʋ{ | - Zip with following as a monad (applied to the list of laps per tyre set)
Ä | - Cumulative sum
Ż | - Prepended with zero
⁴_ | - Subtracted from the number of laps
Ṃ€ | - Minimum of each
ż | - Zip with additional time for corners
>0Ḣ$Ƈ | - Filter those where the first number (the number of laps used for those tyres) is greater than zero
Ʋ | - Following as a monad:
ẈṪ | - Tail of the lengths (will be 2 if all laps accounted for, 1 if not)
, Ɗ | - Paired with following as a monad:
P€ | - Product of each (additional time for each tyre set from corners for all laps driven)
Ʋ | - Following as a monad:
LÑ | - Helper link applied to length (number of tyre sets)
+ | - Plus:
S | - Sum (of additional times for each tyre set)
N | - Negated
M | Indices of maximum
Ḣ | Head
ḃ3 | Bijective base 3
```
] |
[Question]
[
In this challenge, your bot has landed on an island with the stereotypical knights and knaves. Knights always tell the truth, and knaves always lie. The objective is to find the correct 32 digit hexadecimal string before anyone else, by asking knights and knaves and trying to trick other bots into giving you answers or accepting fake ones.
## Knights and Knaves
Every bot will be given an array of 48 people, who are the same for all bots. The bots do not know whether any one person is a knight or knave. Each person is assigned two characters of the 32 digit string. Exactly half of all people are knights, and half are knaves: a knight will always give you the correct characters and their indexes within the result string; a knave, however, will give an incorrect character each time along with the correct index. These incorrect characters will always be the same for any one bot, so a knave is indistinguishable from a knight without outside help or some deductive skills. Every character of the string is known by exactly three people, and no person has the same character twice.
## Interacting
In order to find knaves, bots can interact with one another. One bot will request help from another for a specific character of the string, and the second bot can return any character. It is up to the first bot to decide if this character is real or fake, likely by asking for more help and comparing the results.
In order to prevent help-vampire bots, no bot can have more outgoing help requests than twice the number of incoming requests it has answered, plus four.
## Bots
Every bot is assigned a random Unique ID (UID) number each round. This number is used to communicate with other bots, and ranges from 0 to one less than the number of bots. It can request help from another bot using the function `sendRequest(uid, index)`, and read from responses with `readResponses()`, which is formatted as an array/list of objects containing `uid`, `index`, and `char` properties.
Additionally, a bot can view the requests sent to it using `viewRequests()`. Each request is an object containing two properties: `index`, and `uid`. To reply to a request, use the function `replyRequest(uid, index, char)`. There must be a request in `viewRequests()` from that UID asking about the index specified in order for this to work, and `char` must be a hexadecimal character.
Both `sendRequest` and `replyRequest` will output false if something is invalid (UID for `sendRequest`, and no request to reply to for `replyRequest`), and true otherwise.
The bot will receive three arguments as input to its function. The first is an array/list of each knight/knave, with each one represented as an array/list of two objects (`index` and `char` are their properties).
The second argument is the number of bots. UIDs range from zero to one less than this number. Finally, the third argument is an empty object, which the bot can use to store any information it needs.
## Rules
* The bot can be programmed in JavaScript (**heavily recommended**), Python, or any language with functions, strings, numbers, arrays/lists, and objects/dictionaries/hash maps
* All bots will be converted to JavaScript to be run in the controller
* A bot may not read or modify any variables outside of its function arguments and local/function scoped variables it creates
* A bot may not execute any functions declared outside its scope, aside from the four interaction functions (`sendRequest`, `readResponses`, `viewRequest`, and `replyRequest`)
* **Your bot's guess is submitted by return value. If it does not know, it can return null/false/undefined, or a random guess. Each bot has a win count. If multiple bots guess correctly in the same turn, this increments by `1/correctGuesses`**
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited, per the usual
* [Controller](https://gist.github.com/Radvylf/2b48af8cb9c7247663330c669645b05c), [Chatroom](https://chat.stackexchange.com/rooms/93835/knights-and-knaves-and-codes)
* By the way, this is not a dupe. The other questions based around knights and knaves have a very different objective, they are just similar in their topic
[Answer]
# Zero Information Bot
```
function ZeroInformationBot(people, bots, data) {
if (!data) {
data = {
botData: [],
knaves: [],
guess: "",
newKnaves: false,
attestations: Array(36).fill(0),
threshold: -5,
};
}
let newResponses = [];
readResponses().forEach(res => {
if (!data.botData[res.uid][res.index]){
newResponses.push(res);
data.botData[res.uid][res.index] = res.char;
}
});
newResponses.forEach(res => {
if (people.find(p => (p[0].index == res.index && p[0].char == res.char) || (p[1].index == res.index && p[1].char == res.char))){
people.forEach((p, i) => {
if ((p[0].index == res.index && p[0].char == res.char) || (p[1].index == res.index && p[1].char == res.char)) data.attestations[i] += 2;
if ((p[0].index == res.index && p[0].char != res.char) || (p[1].index == res.index && p[1].char != res.char)) data.attestations[i] -= 1;
if (data.attestations[i] < -1 && !data.knaves.find(i)) {
data.knaves.push(i);
data.newKnaves = true;
}
});
}
});
viewRequests().forEach(req => {
if (!data.botData[req.uid]){
data.botData[req.uid] = Array(36).fill([]);
} else if (!data.botData[req.uid][req.index]) {
sendRequest(req.uid, req.index);
data.botData[req.index] = "-"
} else if (data.botData[req.uid][req.index] != "-") {
replyRequest(req.uid, req.index, data.botData[req.uid][req.index]);
}
});
if (!data.newKnaves && data.guess) return data.guess;
data.newKnaves = false;
let detected = true;
let loop = false;
let possibilities;
while (detected){
detected = false;
possibilities = Array(36).fill(new Set());
let examined = [], chargroups = [];
people.forEach((p, i) => {
if (data.knaves.find(i)) return;
possibilities[p[0].index].add(p[0].char);
possibilities[p[1].index].add(p[1].char);
let first = examined.find(e => e.index == p[0].index && e.char == p[0].char);
let second = examined.find(e => e.index == p[1].index && e.char == p[1].char);
if (first && !second){
chargroups[first.group].push(p[1]);
examined.push({index: p[1].index, char: p[1].char, group: first.group});
} else if (!first && second){
chargroups[second.group].push(p[0]);
examined.push({index: p[0].index, char: p[0].char, group: second.group});
} else if (!first && !second){
examined.push({index: p[0].index, char: p[0].char, group: chargroups.length});
examined.push({index: p[1].index, char: p[1].char, group: chargroups.length});
chargroups.push(p);
} else if (first && second && first.group != second.group){
chargroups[first.group].push(...chargroups[second.group]);
examined = examined.map(e => {
if (e.group == second.group) e.group = first.group;
return e;
});
chargroups.splice(second.group, 1);
}
});
possibilities.forEach((p, i) => {
if (p.size == 1) {
let char = Array.from(p)[0];
chargroups.forEach(c => {
if (c.find(ch => ch.index == i && ch.char != char)) {
people.forEach((person, j) => {
if (data.knaves.find(j)) return;
// We don't need to check both characters; if one's in the group they both are.
if (c.find(ch => ch.index == person[0].index && ch.char == person[0].char)) {
data.knaves.push(j);
detected = true;
}
});
}
});
} else if (p.size == 0) {
// Uh oh... need to reset.
data.knaves = [];
data.attestations.forEach((a, i) => {
if (a <= data.threshold) data.knaves.push(i);
});
detected = true;
// Don't get stuck in a loop.
if (loop) data.threshold--;
loop = true;
}
});
}
data.guess = possibilities.map(p => Array.from(p)[0]).join("");
return data.guess;
}
```
This bot lets out exactly zero information. Whenever it's asked about something, it responds by first asking what that bot thinks, and then it replies with that data.
It counts up the number of times that other bots have given it one of the values of one of the people, and uses that to give a rough confidence score to each person, tentatively marking someone as a knave if they hit -2. If it hits a paradox, it resets who it's considering as a knave, but only automatically re-marks someone as a knave if they have a score of -5 or worse.
Because this bot doesn't aggressively attempt to solve, it's quite possible it'll get stuck on one or two people for a long time; I'm interested in how well it will do. I haven't tested it yet, as it seems the controller is still (slightly) in flux.
[Answer]
# TotallyRandomBot
(Hey, first time posting!)
TotallyRandomBot literally just guesses randomly, (maybe) eventually arriving at the answer through brute force. Keeping true to its random nature, it always replies with a random character when asked for help. Will it find the answer fast? No. Will it eventually find the answer, while throwing others off? Quite possibly.
---
```
function TotallyRandomBot(people, bots, data) {
// string of length 32
let guess = "00000000000000000000000000000000";
let hex = "0123456789ABCDEF";
if(!data) {
// starting index
data = {
index:0,
prev_guess:""
}
}
// reply with random char
viewRequests().forEach(req => {
replyRequest(req.uid, req.index, hex[Math.random() * 16|0]);
})
// assemble guess
people.forEach(obj => {
guess[obj.index] = obj.char;
})
// change a random char
if(data) {
guess[data.index] = hex[Math.random() * 16|0];
// if we've reached the end
if (data.index === 31) {
// start anew
data.index = -1;
}
data.index++;
}
// write it to previous guess
data.prev_guess = guess;
// cross fingers and guess
return guess;
}
```
] |
[Question]
[
Inspired by both the [challenge "Unique is Cheap"](https://codegolf.stackexchange.com/questions/127261/unique-is-cheap) by [*@Laikoni*](https://codegolf.stackexchange.com/users/56433/laikoni), where the score is based on the challenge itself, as well as the [JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/154424/52210) of [*@ETHproductions*](https://codegolf.stackexchange.com/users/42545/ethproductions) for the ["Palindrome Compression" challenge](https://codegolf.stackexchange.com/questions/154339/palindrome-compression), where he uses a pretty cool compression method for the palindrome-flag, upper/lower case indication, and letters.
# Challenge:
You will create two programs/function: a compress program/function, and a decompress program/function.
### Compress program/function:
Given the characters used in your own source code (both the compress and decompress source code combined) as only possible input, use any kind of bit-compression method of your choice and output the resulting `0`s and `1`s of the bit-compression of this input.
The amount of bits (`0`s and `1`s) outputted must be as short as possible, and **this amount will be the score of your answer**.
The idea is to have a nice balance between the different kind of characters used in your own source code, the size of your programs/functions, and the type of bit-compression you've used. Or to quote [*@RobertFraser*](https://codegolf.stackexchange.com/users/20931/robert-fraser) in [this comment](https://codegolf.stackexchange.com/questions/154339/palindrome-compression/154424#comment377149_154424):
>
> This is a great example of the fundamentals of engineering. Taking a problem description, thinking about different ways to solve it, and making tradeoffs between requirements (ie how many bits to dedicate to various styles), etc
>
>
>
## Challenge rules:
* The compressor and decompressor program/function should be in the same programming language.
* You must provide both a compression and decompression program/function, and the amount of `0`s and `1`s your compression program outputs for both programs/functions combined (concatted) as input will be your score.
* The compression must - obviously - work for all characters used in your source code of both your compression and decompression program/function, in any order or amount. (It can have undefined behavior for any characters not in your source code.)
* Input-type doesn't necessarily have to be a string. It could also be a list/array/stream of characters, and it can be as program argument, STDIN, etc. Your call.
Same applies to the output. Can be returned from a function or printed to STDOUT. Can be a single string, integer-array, etc.
* Your compression program must output at least one `0` or `1` (so an empty `cat` program for both the compression and decompression program isn't possible).
* Your source code may not only contain `0`s and `1`s already, excluding no-ops (to prevent programming languages that print their own source code by default, where both the compression and decompression programs can be a single `0` or `1`, and the no-ops part is to prevent this behavior with an unused comment; sorry binary-based programming languages which only use `0`s and `1`s as source code).
* Although you'll have to support an input of 0 or more of the character-pool used in your programs/functions, you don't have to support an empty input. So you can assume every input will be at least 1 character.
* A possible input can be larger than your compression and decompression sizes combined.
* If for whatever reason your compression method is order-depended and has a shorter output when your input is `DecompressionProgramCompressionProgram` instead of `CompressionProgramDecompressionProgram`, you are allowed to choose either order of concatting of your programs/function for your score.
## Example:
Let's say the compression program is `ABC`, and the decompression program is `123aBc`. For any input containing zero or more of the character-pool `123ABCab`, it should be able to correctly compress those characters to `0`s and `1`s, and be able to decompress these `0`s and `1`s back into the correct characters. Some valid example inputs for these two programs can be: `ABC123aBc` (of course); `A`; `1Ca`; `22222b1121221b`; etc.
## General rules:
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Example of an answer:
>
> # Java 8, score 1440 bits, 180 (87 + 93) bytes
>
>
> Here a very bad implementation in Java 8, where each character is simply printed as 8-bit binary String.
>
>
> **Compression function:**
>
>
> Input provided as `java.util.stream.IntStream`.
>
>
>
> ```
> s->s.forEach(c->System.out.print("".format("%8s",Long.toString(c,2)).replace(' ','0')))
>
> ```
>
> [Try it online.](https://tio.run/##jZCxasMwEIb3PMVhKJaofYROAcfZOhTaLBnrDooi23Jt2ejkQAl5dvcchw5d2kWc0P33fbpGnVXaD8Y1p89Jt4oI3pR1lxWAdcH4UmkD@/kKcO7tCbRoOIJjsC1S8EZ1@OLC4VYByYw7rys@KKhgNezBQT5RuiMse/@sdC10ujt8UTAd9mPAwTNHRNH83CmuHjYUJa@9qzD0PNa6SujkSUr0ZmjZRsQQJ/E6llJO2UwaxmPLpDvwJtnxF8QSfv9QctF3qEX0p0kRFT8uxSxT/NeGR184KHgdpjIebL7O7JawNa4KtZDZb1Y5AzTPtzgoT4aDgpDGIy0gm9jHfCNnnMyuEeqau4S87/g6fQM)
>
>
> **Decompression function:**
>
>
> Input provided as `String`.
>
>
>
> ```
> s->{for(Integer i=0;i<s.length();System.out.printf("%c",i.parseInt(s.substring(i,i+=8),2)));}
>
> ```
>
> [Try it online.](https://tio.run/##xVPLbsIwELz3KyykSokK0W5PlVJ676FcOCIOJgRqCkkUG6QK8e1pHn6sQ6BSL5VwSOz17OzO7I6f@CQv0my3/qqSPZeSfXCRnR8YE5lKyw1PUjZrPhk75WLNkmCuSpFtmQzjevfyUD@k4kokbMYyNq3k5O28ycvgvb6@TUsmphCLVxnt02yrPoMwnn9LlR6i/KiiokZSm2D0mIzGIip4KdP6WiAjeVzJNk0gxuJp@hKOn8MwjC9V3OQrjqt9nU@nbWkdatKa2WLJw45wFiUBX8BSM71UFSAiQLuaZ/uut8i@ee1WG9Bttr8mpD0D848GTB92W8N5gICSZKgBTIyF9EJMnIt35zq94Wkvu3Mk/HQhdN2vW/NBkvQWnqnX8UE/DxhImofmR68uLw76/bpVr8O51gMoJySk/X4i1cP010H19DcQth8Go/dtrjqivfM@H1@cK9@izT@gm60fhv1A/AZI6kCqGbj@GhUcb/TMqo09NE945W@iE9UZfF9ZXPD1/5f5sZLd8D0p0vf7kL88H6HnCVsH3J/j6z7TftBh@/PcEAr@N6Dnh55ev8@Zp2uH8wM)
>
>
>
[Answer]
# Jelly, score 350, 39 + 30 = 69 bytes
# Compressor: [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
```
“iЀ;⁴⁾¤8Bz0ZUṖFs5Ḅị”;⁾“”¤iЀ;⁴BUz0ZUṖF
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5zMwxMeNa2xftS45VHjvkNLLJyqDKJCH@6c5lZs@nBHy8Pd3Y8a5gJl9wGVAlmHliDUO4XClP6nmkkIpSQbBwA "Jelly – Try It Online")
# Decompressor: [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
s5Ḅị“iЀ;⁴⁾¤8Bz0ZUṖFs5Ḅị”;⁾“”¤
```
[Try it online!](https://tio.run/##y0rNyan8/7/Y9OGOloe7ux81zMk8POFR0xrrR41bHjXuO7TEwqnKICr04c5pbgg1c4Gy@4BKgaxDS/7//x9tqKNgoKMAIdGQIQ42hGuIW8oAVdYQQ6Mhbo1oJmAKGuI2Fk2ZIYalhrgtxeopQ9zONiQUMobEeYqgk8gIdjyBNvgDdjQRDkwijAUA "Jelly – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), score 702 bits, 88 (42 + 46) bytes
## Compressor, 42 bytes
```
$->new java.math.BigInteger($).toString(2)
```
[Try it online!](https://tio.run/##lY49a8MwEIZ3/4obMkglOUK2kjbQDIUOmTIaDxdHVeTqC@mcYkp@uyvHhW6FTgd3z/u819GVViEq350/HkfjYkgMXVliz8bie@9bNsHjw7ZqLeUMBzIeviqA2J@saSEzcRnXYM7gyk0cORmv6wYo6SzvKMDrj@fpNLCqm@UM7aANLiaVc0jwPC5WO68@53ZHfMG90W@elVZJLCRymFNiI8ft3XocMiuHoWeM5cLWi18hUox2ENMX9bpBrXhfurOQUk7pW3Ub/9H4J7ncTOykf0mJBiG/AQ "Java (OpenJDK 9) – Try It Online")
## Decompressor, 46 bytes
```
$->new java.math.BigInteger($,2).toByteArray()
```
[Try it online!](https://tio.run/##5VGxTsMwEN3zFR46JKi1zmyoUIkOSAxMHaMObmqCQ2JbtlMUoX57iJM6NgW@ACuKc@/evXt3qeiJrqRiojq@3/W8UVJbVA0gbi2v8WsrCsulwDfrpKipMeiFcoE@E4RUe6h5gYyldrhOkh9RM@TSndVclPkeUV2abKQi9HTRuZ@yy0NnWb7foCMrZKM0M0Zq9NAvVhvBPqb@DbVveMvLZ2FZyXS6WN5m2MrtUPmoNe3SrF@P2rvOWNZg2VqsBnFbi9SJTJ3SuAOmStVd6ozlsM@yzAmck3PfE4DhcS9C3BdxB8bgcrvUGEwAjGckX/Iw50MMoX6ixjxfHyCYy4gvBs/1MYmwyBeE3rFY0J/n@@4r@CDRMAEn137CPnwzmI3E@v9mn@T3@f/Yr/dDyJVvIPDTfLR/j8/6EP7nFw "Java (OpenJDK 9) – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), score 179 bits, 9+10=19 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
Compressor:
```
←6!58*-Ĩɓ
```
[Try it online!](https://tio.run/##K6gs@f//UdsEM0VTCy3dIytOTkbjAjlGR1ZA@A93TgEA)
Decompressor:
```
←2Ĩ6!58*-Ṕ
```
[Try it online!](https://tio.run/##K6gs@f//UdsEoyMrzBRNLbR0H@6c8v@/oaGBgYEhCIEYBoZAviGYMIAShgZQAiIHUW0AU2VoCONBNcNNg@gzNISbYGgA1w4Tg5sP1wE13gBmO5SBcB6Q5gIA)
] |
[Question]
[
## Challenge
Given any positive integer supported by your language:
1. Take the input and divide it into two halves. For all divisions in this program, if the input is odd, round one half up and one half down (ex: `7 -> 3,4`, not `7 -> 3.5,3.5`).
2. Divide either number in half, then take the larger of these two new halves and add it back to the number that wasn’t split. Ex: `3,4 -> (1,2),4 -> 1,6` or `3,4 -> 3,(2,2) -> 5,2`.
3. Repeat step 2 until you reach a set you have seen before. Ex: `5 -> 3,2 -> (1,2),2 -> 1,4 -> 1,(2,2) -> 3,2`. Since we’ve seen `3,2` before, we may stop repeating. You may completely exhaust a stack in the process of doing this. Ex: `5 -> 3,2 -> (1,2),2 -> 1,4 -> (0,1),4 -> 0,5`.
4. Output each pair in the loop (i.e. the above without the intermediate steps, from the first appearance of a pair until the second, but not including the second). Ex: `3,2 -> 1,4`. If the input is included, don’t output a `0` with it - `5 -> 3,2 -> 1,4`, not `0,5 -> 3,2 -> 1,4`.
5. Repeat steps 1-4 by splitting the pairs differently.
## I/O
Input is a positive integer larger than `1` and smaller than either the maximum integer supported by your language or the maximum integer that won’t crash the computer, whichever is smaller.
Output is the loops from above in any format you want (string, list, array, etc.). Trailing white space is allowed.
Do not output the same loop twice, nor different versions of the same loop. Ex: `2 -> 1,1` and `1,1 -> 2` are both valid loops, but they describe the same loop, beginning at different points on the loop. Likewise, two loops that are identical but go in the reverse order should not be outputted. Ex: `3 -> 1,2 -> 2,1` and `3 -> 2,1 -> 1,2` are the same loop, but they go in the opposite direction from each other.
You may use any delimiter to differentiate between the pairs, between each number in the pairs, and between each loop, provided that they are three distinct chars or strings. Above, I divided the numbers using commas, the pairs using `->`’s, and the loops using boring instructions. In my examples below, I will use parentheses around each pair, commas between each number within a pair, and new lines between each loop.
## Examples
Credit to [@WheatWizard’s code](https://tio.run/##VY6xbsMgFEV3voJGtgLCTrGHDpGxsvQLOnRADCATGYVgJ4YGVfy7i711eve@d/XuGeVy09auKyoxG8wPCDCmaRhgZLFsSZOanm4KIFop/GYZUhXNE/gLkvsmaavv0EPL@PCc5u/RWI3emcdWJNU1DMmyrQKUJIeRP1ucHl1tCeFe/Ls9CEEBKpK/lm22wOUCitkRHc/LOL1yihzwAbiMtvsIrpk1dDWKGxIXjMu@Zy7tYF39a2YYOD2dROUm/7lRysLLm4YKBrHepXFsDv7LP4vgrHF6Ka7wY/0D) for fixing up my examples list. As I said in an earlier draft, I was sure I was missing a few since I was doing it by hand, but boy was I missing some.
Input: `2`
Output: `(2)(1,1)`
Input: `3`
Output:
```
(3)(1,2)
(1,2)(2,1)
(3)(1,2)(2,1)
```
Input: `4`
Output:
```
(4)(2,2)(1,3)
(1,3)(3,1)
(4)(2,2)(1,3)(3,1)
(4)(2,2)(3,1)(1,3)
(3,1)(1,3)
(4)(2,2)(3,1)
```
Input: `5`
Output:
```
(5)(2,3)(1,4)
(1,4)(3,2)
(2,3)(1,4)(3,2)(4,1)
(5)(2,3)(1,4)(3,2)(4,1)
(2,3)(4,1)
(5)(2,3)(4,1)
```
Input: `6`
Output:
```
(6)(3,3)(1,5)
(1,5)(4,2)(2,4)
(4,2)(2,4)
(1,5)(4,2)(5,1)(2,4)
(4,2)(5,1)(2,4)
(6)(3,3)(1,5)(4,2)(5,1)
(6)(3,3)(5,1)(2,4)(1,5)
(2,4)(1,5)(4,2)
(5,1)(2,4)(1,5)(4,2)
(2,4)(4,2)
(5,1)(2,4)(4,2)
(6)(3,3)(5,1)
```
Input: `7`
Output:
```
(7)(3,4)(1,6)
(1,6)(4,3)(2,5)
(2,5)(5,2)
(3,4)(1,6)(4,3)(2,5)(5,2)(6,1)
(7)(3,4)(1,6)(4,3)(2,5)(5,2)(6,1)
(3,4)(1,6)(4,3)(6,1)
(7)(3,4)(1,6)(4,3)(6,1)
(7)(3,4)(5,2)(2,5)(1,6)
(2,5)(1,6)(4,3)
(3,4)(5,2)(2,5)(1,6)(4,3)(6,1)
(7)(3,4)(5,2)(2,5)(1,6)(4,3)(6,1)
(5,2)(2,5)
(3,4)(5,2)(6,1)
(7)(3,4)(5,2)(6,1)
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count wins.
---
This is my first challenge here, so any feedback would be greatly appreciated. Link to sandbox [here](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/14480#14480).
Fun fact: I was bored one day and playing with random little pieces of pencil lead in this manner and eventually noticed that I could keep going in these types of loops. For some reason my first reaction was “hey, this would be a great challenge for code golf.”
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~267~~ ... 167 bytes
```
import StdEnv
f s l|any((==)s)l=[dropWhile((<>)s)l]#[h,t:_]=s
|1>h*t=f[max h t]l=f[h/2,(h+1)/2+t](l++[s])++(f[(t+1)/2+h,t/2](l++[s]))
@n=removeDup(f[n/2,(n+1)/2][[n]])
```
[Try it online!](https://tio.run/##dU89a8MwEN39Kw46RKodTDKWuHRIh0K2DB0UUZRYjgXSSUjn0kB/e13ZLqVLB8H7ON17d7Fa4eh8O1gNThkcjQs@Ehypfcb3ooME9lPhjbGm4YnbRrTRh9feWM3Y7nGS5J3oK3p4k00qPjeP/T01nXDqA3ogaTPu623F@nLD621JktmyFEnysmSdYLTIeUG9/bV48YRN1M6/6/0Q8hhOG3AelUKglHzsondTy4M5w09ng6RjCvnpoq7Bo73BkHQLnY9AvYYQNdFtok4RGbxWs6zOOQi6AS9kPELrdcIVAer8dUkoiiOpSMVdzggDQQPbjP1AC3la5KKBziqyBnUCMWPSCOxPLxCrE63k/26VTeZUADYdeKSYW4IH8gvkEJSJnMPpNCPYrcF6H@SsTGhSlmJy/LrklGsa1@dx/XIY9zdUzlzSTJbDvgE "Clean – Try It Online")
**Ungolfed:**
```
loops num
= removeDup (half (divide num) [[num]])
where
divide num
= [num/2, (num+1)/2]
half [_, 0] list
= list
half [0, _] list
= list
half [a, b] list
| isMember [a, b] list
= [dropWhile ((<>) [a, b]) list]
# [u, v: _]
= divide a
# [x, y: _]
= divide b
= (half [u, v+b] (list ++ [a, b])) ++ (half [a+y, x] (list ++ [a, b]))
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~227~~ 203 bytes
*17 bytes saved thanks to Οurous*
```
(%)=div
u x|odd x=x%2+1|1>0=x%2
[0,b]!l=[b]!l
[b,0]!l=[b]!l
t!l|elem t l=[dropWhile(/=t)l]
t@[a,b]!l|q<-l++[t]=[a%2,u a+b]!q++[u b+a,b%2]!q
f x|q<-[x%2,u x]![[x]]=[a|(a,b)<-zip q[0..],notElem a$take b q]
```
[Try it online!](https://tio.run/##RY49a8MwEIZ3/YozxCAhx3E8dIpMl27tlKHDIYqMFWwifyXnRhT9d0fO0uW49@F5uWvN/WqdW1eeCtV0v2wBH8amAa98WspjOFbFtjEsslonTuE2GdZZ8Z8occE62wNBRM1tnL7bzll@UCScZvSO5lUO82nvpETSCk1aZgsYGfkc0QK1jFJaxsgu8Yeoon85XieIXm@dwKMjTvu/boIZizzX2TDSx3ba7MhcLdQw67U33aB6M339AJ8WOtPtc8h5Val7Oz6E2F3gbX0C "Haskell – Try It Online")
] |
[Question]
[
*Inspired by [this.](https://chat.stackexchange.com/transcript/message/39743330#39743330)*
Given a string as input consisting of only upper and lowercase alphabet characters, **wicka-wub** it.
### How do I wicka-wub a string?
The example text used is "DJMcMayhem".
Split the string before each capital letter, so you get `["D", "J", "Mc", "Mayhem"]`.
Next, take the two halves of the list as sublists. This gives us `[["D", "J"],["Mc", "Mayhem"]]`. If the list is an odd length (i.e. 3), the first sublist will contain the middle substring (i.e. `[[a,b], [c]]`).
Create a list of `wicka`s and `wub`s. The number of `wicka`s should be as many as the length of the first part of the input list (i.e. `["D", "J"] -> ["wicka", "wicka"]`), and the number of `wubs` should be as many as the length of the second part of the input list. In our case, this gives `["wicka", "wicka", "wub", "wub"]`.
Now join the sublists of the input list into single strings and flatten.
We currently have `["DJ", "McMayhem"]` and `["wicka", "wicka", "wub", "wub"]`.
Join the `wicka`/`wub` list with `-`s: `wicka-wicka-wub-wub`. Prepend a `-`. If there is more than one capital letter in the input, append another `-`.
Now we have `["DJ", "McMayhem"]` and `"-wicka-wicka-wub-wub-"`.
Append the `wicka-wub` string to the end of the first item in the input list, to get `["DJ-wicka-wicka-wub-wub-","McMayhem"]`.
Lastly, repeat the characters in the second part of the string by their 0-indexed value in the original input string. In our example, that means the first `M` would be repeated twice, then the `c` three times, and the next `M` four times. Join the list, so the second part (the part you just repeated letters in) is appended to the first part (`"DJ-wicka-wicka-wub-wub-"`).
Final result of input:
```
"DJ-wicka-wicka-wub-wub-MMcccMMMMaaaaayyyyyyhhhhhhheeeeeeeemmmmmmmmm"
```
Total process:
```
["D", "J", "Mc", "Mayhem"] =>
[["D", "J"], ["Mc", "Mayhem"]] =>
["DJ", "McMayhem"] and ["wicka", "wicka", "wub", "wub"] =>
["DJ", "McMayhem"] and "-wicka-wicka-wub-wub-" =>
["DJ-wicka-wicka-wub-wub-", "McMayhem"] =>
"DJ-wicka-wicka-wub-wub-MMcccMMMMaaaaayyyyyyhhhhhhheeeeeeeemmmmmmmmm"
```
## Your task
Your task is, given a string that consists of only upper and lowercase alphabet characters, output the wicka-wubbed version of that string.
## A few rules
* The input may consist entirely of lowercase letters, or entirely of uppercase letters, or any number of each, but no other characters.
* If the input consists of entirely lowercase letters the correct output should simply be the final stage (the string with the characters repeated according to their 0-indexed position). There should be no `wicka` or `wub` in that case.
* Standard rules apply, full programs or functions, up to you.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
`GoodLuck-wicka-wicka-wub-GGGGGGGGooooooooollllllllllfffffffffffeeeeeeeeeeerrrrrrrrrrrrrssssssssssssss`
## Test cases
```
input => output
DJMcMayhem => DJ-wicka-wicka-wub-wub-MMcccMMMMaaaaayyyyyyhhhhhhheeeeeeeemmmmmmmmm
PPCG => PP-wicka-wicka-wub-wub-CCGGG
foobarbaz => fooooobbbbaaaaarrrrrrbbbbbbbaaaaaaaazzzzzzzzz
FooBarBaz => FooBar-wicka-wicka-wub-BBBBBBaaaaaaazzzzzzzz
HelloWorld => Hello-wicka-wub-WWWWWoooooorrrrrrrllllllllddddddddd
Test => Test-wicka
UPPER => UPP-wicka-wicka-wicka-wub-wub-EEERRRR
fooBarBaz => fooBar-wicka-wicka-wub-BBBBBBaaaaaaazzzzzzzz
```
[Answer]
# Java 8 (782 bytes)
```
import com.google.common.collect.*;import java.util.*;import java.util.function.*;public class p{Function<String,String>b=s->{List<String>p=Arrays.asList(s.split("(?=[A-Z])"));if(!s.matches("[^A-Z]*[A-Z].+")){String w="";int i=0;for(char c:String.join("",s).toCharArray()){w+=String.join("",Collections.nCopies(i,Character.toString(c)));i++;}return w;}String h="-";List<List<String>>k;if(p.size()!=1){k=Lists.partition(p,2);String w=String.join("",k.get(0))+h+String.join(h,Collections.nCopies(k.get(0).size(),"wicka"))+h+String.join(h,Collections.nCopies(k.get(1).size(),"wub"))+h;int i=String.join("", k.get(0)).length();for(char c:String.join("",k.get(1)).toCharArray()){w+=String.join("",Collections.nCopies(i,Character.toString(c)));i++;}return w;}return p.get(0)+h+"wicka";};}
```
Ungolfed:
```
import com.google.common.collect.*;
import java.util.*;
import java.util.function.*;
public class p {
Function<String, String> b = s -> {
List<String> p = Arrays.asList(s.split("(?=[A-Z])"));
if (!s.matches("[^A-Z]*[A-Z].+")) {
String w = "";
int i = 0;
for (char c : String.join("", s).toCharArray()) {
w += String.join("", Collections.nCopies(i, Character.toString(c)));
i++;
}
return w;
}
String h = "-";
List<List<String>> k;
if (p.size() != 1) {
k = Lists.partition(p, 2);
String w = String.join("", k.get(0)) + h + String.join(h, Collections.nCopies(k.get(0).size(), "wicka")) + h + String.join(h, Collections.nCopies(k.get(1).size(), "wub")) + h;
int i = String.join("", k.get(0)).length();
for (char c : String.join("", k.get(1)).toCharArray()) {
w += String.join("", Collections.nCopies(i, Character.toString(c)));
i++;
}
return w;
}
return p.get(0) + h + "wicka";
};
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 142 bytes
**130 bytes code + 12 for `-F(?=[A-Z])`.**
This now correctly matches all the test cases provided.
```
map$a+=y///c,@E=($z=/[A-Z]/)?splice@F,0,@F/2+.5:();print@E,("-wicka"x@E,"-wub"x@F,"-"x!!@F)x$z,map$_ x$a++,$z?map/./g,@F:('',/./g)
```
[Try it online!](https://tio.run/##Jc/RasIwFAbg@zyFloAJTc0YeGMpzXTNxkAoYyIoMtIat2JsQlqx9uGXpXr3/ZzDfzhGWjVz7iwMFGFyo5SWhGUJgn1Cdy/Rdk9x2hhVlZJx8kQYp8/hdDZHODa2qluWERRE16o8iaDzwftSeHGvoBuPGccd7MlQ/z3q/ImQwD71kU7pj2@bo8mEDMYuvtQHeYQidq8fq3Ilbr/yDPJ8@QaOWhfCFqIHXOuFsAuvd6mU3mirDuBLNi1Y53n2OWw@5n/atJWuGxdxlCb3R/AoUv8 "Perl 5 – Try It Online")
**Note**: TIO includes `-l` to run all tests at once.
[Answer]
# Kotlin 1.1 - ~~494~~ 492 bytes
## Submission
```
typealias S=String
fun Iterable<*>.j(s:S="")=this.joinToString(s)
fun s(s:S):S{var c=0
val m=mutableListOf<S>()
var t=""
s.map{if(it.isUpperCase()){c+=1
if(t!=""){m.add(t)
t=""}}
t+=it}
if(c==0)return e(s,1)
m.add(t)
val p=Math.ceil(m.size/2.0).toInt()
val f=m.subList(0,p)
val z=m.subList(p,m.size)
val w=List(f.size,{"wicka"})
val u=List(z.size,{"wub"})
val x=f.j()
var v="-"+(w+u).j("-")
if(c>1)v+="-"
return x+v+e(z.j(),x.length)}
fun e(s:S,o:Int)=s.mapIndexed{c,i->List(c+o,{i}).j()}.j()
```
## Test
```
typealias S=String
fun Iterable<*>.j(s:S="")=this.joinToString(s)
fun s(s:S):S{var c = 0
val m=mutableListOf<S>()
var t=""
s.map{if(it.isUpperCase()){c+=1
if(t!=""){m.add(t)
t=""}}
t+=it}
if(c==0)return e(s,1)
m.add(t)
val p=Math.ceil(m.size/2.0).toInt()
val f=m.subList(0,p)
val z=m.subList(p,m.size)
val w=List(f.size,{"wicka"})
val u=List(z.size,{"wub"})
val x=f.j()
var v="-"+(w+u).j("-")
if(c>1)v+="-"
return x+v+e(z.j(),x.length)}
fun e(s:S,o:Int)=s.mapIndexed{c,i->List(c+o,{i}).j()}.j()
data class TestData(val input: String, val output: String)
fun main(args: Array<String>) {
val tests = listOf(
TestData("DJMcMayhem", "DJ-wicka-wicka-wub-wub-MMcccMMMMaaaaayyyyyyhhhhhhheeeeeeeemmmmmmmmm"),
TestData("PPCG", "PP-wicka-wicka-wub-wub-CCGGG"),
TestData("foobarbaz", "fooooobbbbaaaaarrrrrrbbbbbbbaaaaaaaazzzzzzzzz"),
TestData("FooBarBaz", "FooBar-wicka-wicka-wub-BBBBBBaaaaaaazzzzzzzz"),
TestData("HelloWorld", "Hello-wicka-wub-WWWWWoooooorrrrrrrllllllllddddddddd"),
TestData("Test", "Test-wicka"),
TestData("UPPER", "UPP-wicka-wicka-wicka-wub-wub-EEERRRR"),
TestData("fooBarBaz", "fooBar-wicka-wicka-wub-BBBBBBaaaaaaazzzzzzzz")
)
for (test in tests) {
var out = s(test.input)
if (out != test.output) {
System.err.println("TEST FAILED")
System.err.println("IN " + test.input)
System.err.println("EXP " + test.output)
System.err.println("OUT " + out)
return
}
}
println("Test Passed")
}
```
## Running
Works on KotlinLang, but not on TryItOnline as 1.1 is not supported
*Ran through my compressor, saved 2 bytes*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 64 bytes
```
ꜝ[`(?=[A-Z])`ṡḢ:₅½⌈:‟ẎDƛ`≤ȧka-`;∑$∑‹p^ȯ:ƛ‛≤¶;‹∑∇∑f:ẏ∇∇∑L+*÷|ėvΠ÷
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%AA&code=%EA%9C%9D%5B%60%28%3F%3D%5BA-Z%5D%29%60%E1%B9%A1%E1%B8%A2%3A%E2%82%85%C2%BD%E2%8C%88%3A%E2%80%9F%E1%BA%8ED%C6%9B%60%E2%89%A4%C8%A7ka-%60%3B%E2%88%91%24%E2%88%91%E2%80%B9p%5E%C8%AF%3A%C6%9B%E2%80%9B%E2%89%A4%C2%B6%3B%E2%80%B9%E2%88%91%E2%88%87%E2%88%91f%3A%E1%BA%8F%E2%88%87%E2%88%87%E2%88%91L%2B*%C3%B7%7C%C4%97v%CE%A0%C3%B7&inputs=DJMcMayhem&header=&footer=)
Since the stack manipulation is quite complex, I've added a representation of the stack after each step.
```
ꜝ[ # If any letters are uppercase (example input: DJMcMayhem
`(?=[A-Z])`ṡ # Split before uppercase letters
# [['','D','J','Mc','Mayhem']]
Ḣ # Lop off the first value
# [['D','J','Mc','Mayhem']]
:₅½⌈ # Duplicate and push ceil(length/2)
# [['D','J','Mc','Mayhem'],['D','J','Mc','Mayhem'],2]
:‟Ẏ # Push a copy on the bottom and slice from the start
# [2,['D','J','Mc','Mayhem'],['D','J']]
Dƛ`≤ȧka-`; # Triplicate and fill one copy with 'wicka-'
# [2,['D','J','Mc','Mayhem'],['D','J'],['D','J'],['wicka-','wicka-']]
∑$∑ # Sum these and sum the pair under that
# [2,['D','J','Mc','Mayhem'],['D','J'],'wicka-wicka-','DJ']
‹p # Add a hyphen and prepend
# [2,['D','J','Mc','Mayhem'],['D','J'],'DJ-wicka-wicka-']
^ȯ # Reverse the stack and slice
# ['DJ-wicka-wicka-',['D','J'],['Mc','Mayhem']]
:ƛ‛≤¶;‹∑ # Duplicate, fill a copy with 'wub-' and sum that
# ['DJ-wicka-wicka-',['D','J'],['Mc','Mayhem'],'wub-wub-']
∇∑f # Shift and turn the full second half into a list of characters
# ['DJ-wicka-wicka-','wub-wub-',['D','J'],['M','c','M','a','y','h','e','m']]
:ẏ # Duplicate and make a range of 0...length
# ['DJ-wicka-wicka-','wub-wub-',['D','J'],['M','c','M','a','y','h','e','m'],[0,1,2,3,4,5,6,7]]
∇∇∑L+ # Get the full length of the first half and add it to each item of this range
# ['DJ-wicka-wicka-','wub-wub-',['M','c','M','a','y','h','e','m'],[2,3,4,5,6,7,8,9]]
*÷ # Multiply (repeat) (vectorising) and iterate out over the stack
# ['DJ-wicka-wicka-','wub-wub-','MM','ccc','MMMM','aaaaa','yyyyyy','hhhhhhh','eeeeeeee','mmmmmmmmm']
# Then the Ṫ flag smash-prints this.
| # Else...
ė # Enumerate (zip with range to length)
vΠ # Reduce each by multiplication
÷ # Iterate (push each to the stack)
# Then the Ṫ flag smash-prints this.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~234~~ ~~281~~ ~~270~~ ~~248~~ 246 bytes
```
s,j=input(),"".join;f=lambda l,n:j(c*i for i,c in enumerate(j(l),n));import re;u=re.split("([A-Z])",s);l=len(u)
m=[j(u[i:i+2])for i in range(1,l,2)];i=-~l//4;d=j(m[:i]);print((j([d+"-wicka"*i+"-wub"*(l//2-i)+"-",f(m[i:],len(d))]),f(u[0],1))[l<2])
```
[Try it online!](https://tio.run/##HY3BUsQgEETvfgXFaSZLdt3oKcjB35DiQBLiDhJIESjLi78eE2/dXd391p/ySPFl3zfhFcW1FkDB@dUninJWwS7DZFkQsfcwNsTmlBmJkVFkLtbFZVsceAgoIqKkZU25sOxkVdldtzVQAQ76vf0wyMWGMqjgIlR8WpT2UDX1dOkM/t@ep9nGTwd3EUSHRpJqf8Pt9ion5WHRPRmUa6ZY4GDq6cLbbxq/LG/olHXgDRz1riU8PBfzsaHeiBM5IRo8kqqfjbgj6vB2cPd9TmmwNv8B "Python 3 – Try It Online")
*Added 47 bytes, thanks to Mr. Xcoder ;)*
*Saved 11 bytes thanks to Jonathan Frech*
*Saved 22 bytes thanks to Halvard Hummel*
*Saved 2 more bytes thanks to Mr. Xcoder*
] |
[Question]
[
*This is the cops' post. The robbers' is [here](https://codegolf.stackexchange.com/q/140862/58826).*
You make a program and a regex.
For most inputs, one of the following happens:
* the regex doesn't match, and the program returns a falsey value
* the regex doesn't match, and the program returns a truthy value
* the regex matches, and the program returns a truthy value
But for one (or more) input, the regex matches, but the program returns a falsy value.
You should try to keep this input hidden. Robbers will try to find an input where the regex matches, but the program returns a falsy value.
Post your program and your regex, as well as your language name, byte count of the program, regex flavor, and byte count of the regex.
If a robber finds an input where the regex matches, but the program returns a falsy value, even if it wasn't the intended input your program is considered cracked, and you edit in a link to the robber's crack.
If nobody has cracked your program & regex after a week, then edit in that your submission is safe and is therefore not eligible for cracking. Also edit in the intended input. The shortest (program bytes + regex bytes) non-cracked submission wins.
## Example
Let's say your regex is (all of the flavors):
```
/^[0-9]$/
```
And your program is (JS):
```
x=>Boolean(parseInt(x))
```
Then a valid crack would be `0`, because the regex matches `0` but `0` is falsey.
Delimiters don't count in the byte count.
**I can't enforce the banning of hash functions with rules, but please don't use SHA/RSA or anything that is unfair to the robbers**
[Answer]
# Python, [cracked](https://codegolf.stackexchange.com/questions/140862/the-greedy-regex-robbers/141006#141006)
Regex: `(?!.)`
Program: `from operator import not_`
This is a little easier than my previous one.
[Answer]
# JavaScript ([Cracked](https://codegolf.stackexchange.com/a/140900/72349))
Regex: `..`
Program: `a=>[...a].length-1`
This is an easy one.
---
**Intended solution**
>
>
> üòä
>
>
>
>
>
[Answer]
# JavaScript ES6, 12 bytes + 3 bytes
Regex: `...`
Code: `a=>a+1<a-1+2`
[Answer]
# Python 3, cracked by ovs
Regex: `.`
Program: `lambda a:len(a.lower()) == 1`
This ~~shouldn't be~~ wasn't too hard.
[Answer]
# Pyth
Regex: `.*`
Program: `!qC%.hz^TT"U|(¬°`
[Try it online!](https://pyth.herokuapp.com/?code=%21qC%25.hz%5ETT%22U%7C%28%C2%A1&debug=0)
Simple hash function, shouldn't be allowed, but it is. I could've made it much stronger, but I tried to optimize for byte count.
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 198 bytes, ([Cracked](https://codegolf.stackexchange.com/questions/140862/the-greedy-regex-robbers/140914#140914))
```
public static boolean isProgramValid(String n) {
try{
Class.forName(n);
} catch(Exception e){
return false;
}
return true;
}
public static String regex = "^(?is)([a-z]+\\.){4}.*$";
```
Should be an easy one.
[Try it online!](https://tio.run/##dVFNT8JAED23v2LSeNhC2JMXIcaDIdFECQH0IpgsZaiL291md4og6W@v/fIDldNkZt6beW9mI7aiZ1LUm9XrRSGT1FiCTVnkGUnFOwP/Z00JHXOLa4URVT0/zZZKRhAp4RzcC6nh4Htt0ZGgMmyNXEFSttiUrNTx0wKEjV1YIb1pJLRGC66Nl6DxDdoqm@4dYcKlDgcVtqYDmRk6KpEth2vc0Z3UyBpUwzEZ8bTEk9IsGFsTW5H0IYAuSNemj0LJFWvGhSe5E4xx1wdouXX6h5n7v10vjVEo9DGjdaDDyrpFyqwGzRNB0Qs6ZitgM80rTo47Ev81sD4m2X0VvOvqG3xt7EgkyJrj5RBVa9hwF2FK0mjAWsWnjLVQDmvgtzSyGf5rrl1bCy4fETyzK@lC9iR674vufM7Dw3nOO2fBoPD8vDjcjsYPM7gZTob5Bw "Java (OpenJDK 9) – Try It Online")
] |
[Question]
[
This challenge is adapted from the [British Informatics Olympiad](https://www.olympiad.org.uk/).
---
## Dice game
Two players are playing a dice game where they each roll a pair of dice, and the highest sum wins. The pairs of dice have the same number of sides, but do not have to have the same values on each side. Therefore, the game is fair if for both pairs of dice all possible sums can be made with equal probability.
For example, if Player 1 has the following dice:
```
{1,2,3,4,5,6} {1,2,3,4,5,6}
```
Then they can produce the following sums:
```
1 2 3 4 5 6
+------------------
1| 2 3 4 5 6 7
2| 3 4 5 6 7 8
3| 4 5 6 7 8 9
4| 5 6 7 8 9 10
5| 6 7 8 9 10 11
6| 7 8 9 10 11 12
```
If Player 2 has:
```
{1,2,2,3,3,4} {1,3,4,5,6,8}
```
They can produce:
```
1 2 2 3 3 4
+------------------
1| 2 3 3 4 4 5
3| 4 5 5 6 6 7
4| 5 6 6 7 7 8
5| 6 7 7 8 8 9
6| 7 8 8 9 9 10
8| 9 10 10 11 11 12
```
This game is fair as the minimum for both is 2, the maximum is 12, and each sum occurs the same number of times, e.g 7 can be made 6 ways with each pair.
---
## Challenge
Write a program/function that takes two dice as input, and optionally an integer representing the number of sides each dice contain, and prints/returns a different pair of dice that could be used to play a fair game with the two input dice, or any falsey value if there is no solution different from the input.
---
# Specifications
* The number of sides on both dice must be the same, and equal to the number of sides on the input pair of dice. This number will always be an integer greater than or equal to 1.
* The two dice returned can be the same, but the pair must not be the same as the input pair.
* Different order pairs are not different; {1,2,3} {4,5,6} is the same as {4,5,6} {1,2,3}.
* Your program does not need to produce a result quickly, as long as it will eventually produce correct output.
* The values on the input pair of dice dice will always be integers between 1 and 9 inclusive, but the values returned can be any integer ≥1.
* If there is more than one possible solution, only one needs to be returned.
* Input/Output can be in any reasonable format.
## Test Cases
```
6
1 2 2 3 3 4
8 6 5 4 3 1
1 2 3 4 5 6
1 2 3 4 5 6
```
---
```
4
1 1 1 1
1 4 5 8
1 1 4 4
1 1 5 5
```
---
```
3
1 3 5
2 4 6
False
```
---
```
8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
Any of the following:
1 2 2 3 3 4 4 5 | 1 2 2 3 5 6 6 7 | 1 2 3 3 4 4 5 6
1 3 5 5 7 7 9 11 | 1 3 3 5 5 7 7 9 | 1 2 5 5 6 6 9 10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+þµFṢ
ç©ṀRœċL}Œċµç/⁼®µÐf
,Ṣ€,Ṛ$ḟ@ç
```
Returns a list of all possible pairs of dice up to ordering of dice and faces\* (excluding any that are the same dice as the input pair).
**[Try it online!](https://tio.run/nexus/jelly#@699eN@hrW4Pdy7iOrz80MqHOxuCjk4@0u1Te3TSke5DWw8v13/UuOfQOiBrQhqXDlDZo6Y1QGqWysMd8x0OL////3@0iY6FjqmOYez/aEMdMIwFAA)**
This is a brute-forcer, and is not efficient (too slow to even run the 6-face test case at TIO).
```
+þµFṢ - Link 1, sorted sums: dieA, dieB
þ - outer product with
+ - addition (make a table of the sums, a list of lists)
µ - monadic chain separation
F - flatten into one list
Ṣ - sort
ç©ṀRœċL}Œċµç/⁼®µÐf - Link 2, all possible fair dice pairs (including input): dieA, dieB
ç - call the last link (1) as a dyad
© - save the result to the register for later use too
Ṁ - maximum (the largest sum)
R - range [1,2,...,maxSum]
} - use right argument (dice B) to turn the monad into a dyad:
L - length
œċ - all combinations with replacement (i.e. all dice with faces between 1 and maxSum inclusive [overkill, but golfier than less])
Œċ - all pairs of these dice
µ - monadic chain separation
µÐf - filter keep:
/ - reduce with:
ç - last link (1) as a dyad (the sorted sums of the current pair)
® - retrieve register value (the sorted sums of the input pair)
⁼ - equal?
,Ṣ€,Ṛ$ḟ@ç - Main link: dieA, dieB
, - pair - [dieA, dieB]
Ṣ€ - sort €ach - [dieASorted, dieBSorted]
$ - last two links as a monad:
Ṛ - reverse - [dieBSorted, dieASorted]
, - pair - [[dieASorted, dieBSorted], [dieBSorted, dieASorted]]
ç - call the last link (2) as a dyad (with dieA, dieB)
@ - reversed @rguments:
ḟ - filter out - removes any results that are equivalent to the input pair.
```
\* i.e. if `[[1,1,4,4],[1,1,5,5]]` is a possibility (like in one of the examples) there wont be a `[[1,1,5,5],[1,1,4,4]` or `[[1,4,1,4],[1,1,5,5]]`, etc.
[Answer]
# C++14, 130 bytes
As unnamed lambda assuming `M` to be like `std::vector<std::vector<int>>`. Fair is `0`, anything else is unfair.
```
#include<map>
[](auto&M){auto g=[](auto&v){std::map<int,int>m;for(int x:v)for(int y:v)m[x+y]++;return m;};return g(M[0])-g(M[1]);}
```
Ungolfed:
```
#include<map>
auto f=
[](auto&M){
auto g=[](auto&v){
std::map<int,int>m;
for(int x:v)
for(int y:v)
m[x+y]++;
return m;
};
return g(M[0])==g(M[1]);
}
;
```
[Answer]
# Python, 228 bytes
```
from itertools import*;s,C=lambda x,y:sorted(sum([[i+j for j in y]for i in x],[])),combinations_with_replacement;f=lambda k,l,m:([[*a]for a in C([*C([*range(1,s(l,m)[-1])],k)],2)if(s(l,m)==s(*a))*~-([*a]in[[l,m],[m,l]])]+[0])[0]
```
This was from a long time ago; I could probably golf this a bit better now.
] |
[Question]
[
We have a Brainf\*\*\* to TinyBF converter, but not the other way around, so here's one.
## Rules:
* Your interpreter must take a valid TinyBF program, on one line, and it must output the corresponding BrainF\*\*\* program, on one line, with optional trailing whitespace/newline. No leading whitespace is allowed
* The input may or may not contain characters that are not any of the four TinyBF characters. If so, you must print all of these characters in the same spots.
* An answer will be accepted on April 1st (not joking), based on some obscure criteria I will use (jk ;) I will accept the shortest program that does not cheat by the following rules)
* No 0-byte or 1-byte solutions, because it ruins the fun if you make (or there is) a programming language just for this purpose)
## Test Cases
---
Input 1: `+++++>+++++=>=|>>+=>>+|=>|>+=>+|` (Computes 5 (byte 1) + 5 (byte 2) = 10 (byte 3))
Output 1: `+++++>+++++<[>>+<<-]>[>+<-]`
Input 2: `+++>++++Hi+++:P+=>=|>|>+>+=>>&&+|=>>|=>>=+!!>>=+|>>>+|` (Computes 3 (byte 1) \* 8 (byte 2) = 24 (byte 3))
Output 2: `+++>++++Hi+++:P+<[>[>+>+<<&&-]>>[<<+!!>>-]<<<-]`
[Answer]
# Python 3, 97 bytes
This script is based on [@Mego's answer](https://codegolf.stackexchange.com/a/73254/51264)
```
a=0
for c in input():a-=c=='=';print({'+':'+-','>':'><','|':'[]'}.get(c,c)[a%-2]*(c!='='),end='')
```
[Answer]
## Python 2, 106 bytes
```
a=0
r=''
for c in input():a=[a,~a][c=='='];r+={'+':'+-','>':'><','|':'[]'}.get(c,c)[a%-2]*(c!='=')
print r
```
Implements the TinyBF specification as found [here](https://esolangs.org/wiki/TinyBF). [Try it online](http://ideone.com/fork/Uiilad). Improvements were made using techniques from [@Dica's answer](https://codegolf.stackexchange.com/a/73290/45941). Requires quoted string input.
] |
[Question]
[
User quartata posted [this challenge](https://codegolf.stackexchange.com/q/60147/7416), but he neglected the fact that, for whatever reason, he's not able to play MIDI files on his computer.
Let's help him out by writing a full program that reads a song in RTTTL format from the standard input, prints the song name to the standard output and plays it (at the right speed and pitch).
**Format details**
RTTTL is a fairly dumb and underspecified ringtone format. It consists of a name, some default values, and a series of notes (only one note at a time) in a simple text format.
Example: `fifth: d=4,o=5,b=63: 8P, 8G5, 8G5, 8G5, 2D#5`
The name is a string terminated by a colon. Here the name is "fifth". Your program must accept names with at least 15 characters.
Next, the defaults section (also terminated by a colon) lists some default values for duration (d), octave (o) and the beats per minute (b) for the song. They are comma-separated and use a "key=value" syntax. There may be any number of spaces around each "key=value" part. You may assume that default values d, o and b are all present, in this order. The duration and octave will be explained below; the bpm refers to the number of beats (corresponding to quarter notes) that should be played in a minute, and you must support any integer value between 20 and 900 (inclusive).
Then the actual song is listed as a comma-separated series of notes using a "DPO" syntax, where D is the duration, P is the pitch (note) and O is the octave. There may be any number of spaces and newlines around each "DPO" part.
The duration is a power of 2 between 1 and 32 (inclusive), representing a fraction of a whole note. So for example a value of 4 (quarter note) is twice as long as a value of 8 (eighth note). The duration can be missing, in which case the default duration will be used. The duration may also be modified by the presence of a dot (`.`), specifically the dot makes the note last 50% longer. Since not everybody agrees about where the dot is supposed to be, you must accept a dot after the pitch or after the octave (i.e. both "DP.O" and "DPO." should work).
The pitch is one of A,B,C,D,E,F,G,A#,C#,D#,F#,G#,P where A-G# are the standard musical notes (note: no flats, use the corresponding sharp note) and P is a pause. The pitch is the only part of the note that is required, and is case-insensitive.
And finally, the octave is a number normally from 4 to 8, but you must support any number from 1 to 8 inclusive. For example, C4 is the standard middle C with a frequency of about 261.63Hz. The octave can be missing, in which case the default octave will be used. You can assume that pauses don't have an octave specified (as it has no meaning).
As mentioned in the other challenge, you can use [this site](http://merwin.bespin.org/t4aphp/) to convert RTTTL songs to MIDI format for testing (but note that it may not follow the exact same specification).
**Requirements:**
Your program must play each note at the right speed and pitch. It can use any kind of sound (sine/triangle/square wave, piano sound, bell sound, whatever; also it can be a standard beep, wave sound or MIDI sound etc) as long as it is audible and the pitch is recognizable.
Each note must be played continuously for the specified duration or no more than a 64th note shorter than that, except if you're using something like an [ADSR envelope](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope), in which case the release phase may continue through the next pause or over the next note.
If two consecutive notes have the same pitch, they must be clearly distinguished, either through a short break (using no more than the length of a 64th note, as part of the first note's duration) or by using a non-uniform sound (such as the ADSR envelope mentioned above), or at least through a [phase change](https://en.wikipedia.org/wiki/Phase_change_(waves)) if it's clear enough. Two consecutive pauses should be treated the same as a single pause with the total duration.
The program must be runnable in Linux using freely available software. It should read the song from the standard input, and print the song name to the standard output.
If the input does not match the specification above, the behavior is unspecified. Your program may ignore errors, or print a message, or play something wrong, hang or crash, it should just not do any damage.
Standard loopholes are not allowed.
**Scoring**
Code golf, shortest program (measured in UTF-8 bytes) wins.
[Answer]
# Java, 813
```
import javax.sound.sampled.*;class R{public static void main(String[]a)throws Exception{Integer k=0;a=new
java.util.Scanner(System.in).useDelimiter("\\A").next().split(":");System.out.println(a[0]);int[]X=new
int[3],N={9,11,0,2,4,5,7};while(k<3)X[k]=k.valueOf(a[1].split(",")[k++].split("=")[1].trim());SourceDataLine
l=AudioSystem.getSourceDataLine(new AudioFormat(48000,8,1,1>0,1<0));l.open();l.start();for(String
t:a[2].toLowerCase().split(",")){a[k=0]=a[1]=a[2]="";for(char
c:t.trim().toCharArray())if(c!=46)a[k+=(c<48|c>57?1:0)^k]+=c;int
D=32/(a[k=0]==""?X[0]:k.valueOf(a[0]))*(t.contains(".")?3:2),m=a[1].charAt(0)-97,P=m>6?0:N[m]+12*(a[2]==""?X[1]:k.valueOf(a[2]))+(t.contains("#")?1:0);int
n=180000*D/X[2];for(;k<n;++k)l.write(new byte[]{(byte)(P>0&k<n-n/D?k*Math.pow(2,P/12.)/22.93:0)},0,1);}l.drain();}}
```
I'm still working on it.
It's a bit sensitive to CPU speed and busyness when starting.
[Answer]
# C++, 15186 bytes
**There's a link at the bottom where you can hear a sample**
I present one of the least practical ways to play music on your Linux machine:
```
#include <SFML/Audio.hpp>
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
namespace N{double a = 440.;double as = 466.16;double b = 493.88;double c = 523.25;double cs = 554.37;double d = 587.33;double ds = 622.25;double e = 659.25;double f = 698.46;double fs = 739.99 ;double g = 783.99;double gs = 830.61; const unsigned SAMPLES = 10*44100;const unsigned SAMPLE_RATE = 44100;const unsigned AMPLITUDE = 10000;const double TWO_PI = 6.28318; sf::Int16 a4raw[SAMPLES];sf::Int16 as4raw[SAMPLES];sf::Int16 b4raw[SAMPLES];sf::Int16 c4raw[SAMPLES];sf::Int16 cs4raw[SAMPLES];sf::Int16 d4raw[SAMPLES];sf::Int16 ds4raw[SAMPLES];sf::Int16 e4raw[SAMPLES];sf::Int16 f4raw[SAMPLES];sf::Int16 fs4raw[SAMPLES];sf::Int16 g4raw[SAMPLES];sf::Int16 gs4raw[SAMPLES];sf::Int16 pauseraw[SAMPLES];double inc = a/44100;double x=0;int i=0;void set1(){for(int i=0;i<SAMPLES;i++){a4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=as/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){as4raw[i]=AMPLITUDE*sin(x*TWO_PI);x += inc;}inc=b/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){b4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=c/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){c4raw[i]=AMPLITUDE * sin(x*TWO_PI);x+=inc;}inc=cs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){cs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=d/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){d4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=ds/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){ds4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=e/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){e4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=f/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){f4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=fs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){fs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}inc=g/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){g4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;} inc=gs/44100;x=0;for(unsigned i=0;i<SAMPLES;i++){gs4raw[i]=AMPLITUDE*sin(x*TWO_PI);x+=inc;}}sf::SoundBuffer a3; sf::SoundBuffer a4; sf::SoundBuffer a5; sf::SoundBuffer a6; sf::SoundBuffer a7;sf::SoundBuffer as3; sf::SoundBuffer as4; sf::SoundBuffer as5; sf::SoundBuffer as6; sf::SoundBuffer as7;sf::SoundBuffer b3; sf::SoundBuffer b4; sf::SoundBuffer b5; sf::SoundBuffer b6; sf::SoundBuffer b7;sf::SoundBuffer c3; sf::SoundBuffer c4; sf::SoundBuffer c5; sf::SoundBuffer c6; sf::SoundBuffer c7;sf::SoundBuffer cs3; sf::SoundBuffer cs4; sf::SoundBuffer cs5; sf::SoundBuffer cs6; sf::SoundBuffer cs7;sf::SoundBuffer d3; sf::SoundBuffer d4; sf::SoundBuffer d5; sf::SoundBuffer d6; sf::SoundBuffer d7;sf::SoundBuffer ds3; sf::SoundBuffer ds4; sf::SoundBuffer ds5; sf::SoundBuffer ds6; sf::SoundBuffer ds7;sf::SoundBuffer e3; sf::SoundBuffer e4; sf::SoundBuffer e5; sf::SoundBuffer e6; sf::SoundBuffer e7;sf::SoundBuffer f3; sf::SoundBuffer f4; sf::SoundBuffer f5; sf::SoundBuffer f6; sf::SoundBuffer f7;sf::SoundBuffer fs3; sf::SoundBuffer fs4; sf::SoundBuffer fs5; sf::SoundBuffer fs6; sf::SoundBuffer fs7;sf::SoundBuffer g3; sf::SoundBuffer g4; sf::SoundBuffer g5; sf::SoundBuffer g6; sf::SoundBuffer g7;sf::SoundBuffer gs3; sf::SoundBuffer gs4; sf::SoundBuffer gs5; sf::SoundBuffer gs6; sf::SoundBuffer gs7;sf::SoundBuffer pauseBuffer;void set2(){if (!a3.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if(!a4.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE)){std::cerr<<"err: load fail";}if(!a5.loadFromSamples(a4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if(!a6.loadFromSamples(a4raw,SAMPLES,1,SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if(!a7.loadFromSamples(a4raw,SAMPLES,1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";} if (!as3.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!as4.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!as5.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!as6.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!as7.loadFromSamples(as4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!b3.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!b4.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!b5.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!b6.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!b7.loadFromSamples(b4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!c3.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!c4.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!c5.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!c6.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!c7.loadFromSamples(c4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!cs3.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!cs4.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!cs5.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!cs6.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!cs7.loadFromSamples(cs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!d3.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!d4.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!d5.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!d6.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!d7.loadFromSamples(d4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!ds3.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!ds4.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!ds5.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!ds6.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!ds7.loadFromSamples(ds4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";} if (!e3.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!e4.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!e5.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!e6.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!e7.loadFromSamples(e4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!f3.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!f4.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!f5.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!f6.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!f7.loadFromSamples(f4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!fs3.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!fs4.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!fs5.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!fs6.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!fs7.loadFromSamples(fs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!g3.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!g4.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!g5.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!g6.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!g7.loadFromSamples(g4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if (!gs3.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE/2)){std::cerr<<"err: load fail";}if (!gs4.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}if (!gs5.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*2)){std::cerr<<"err: load fail";}if (!gs6.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*4)){std::cerr<<"err: load fail";}if (!gs7.loadFromSamples(gs4raw, SAMPLES, 1, SAMPLE_RATE*8)){std::cerr<<"err: load fail";}if(!pauseBuffer.loadFromSamples(pauseraw, SAMPLES, 1, SAMPLE_RATE)){std::cerr<<"err: load fail";}}sf::Sound A3; sf::Sound A4;sf::Sound A5;sf::Sound A6;sf::Sound A7;sf::Sound AS3; sf::Sound AS4;sf::Sound AS5;sf::Sound AS6;sf::Sound AS7;sf::Sound B3; sf::Sound B4;sf::Sound B5;sf::Sound B6;sf::Sound B7;sf::Sound C3; sf::Sound C4;sf::Sound C5;sf::Sound C6;sf::Sound C7;sf::Sound CS3; sf::Sound CS4;sf::Sound CS5;sf::Sound CS6;sf::Sound CS7;sf::Sound D3; sf::Sound D4;sf::Sound D5;sf::Sound D6;sf::Sound D7;sf::Sound DS3; sf::Sound DS4;sf::Sound DS5;sf::Sound DS6;sf::Sound DS7;sf::Sound E3; sf::Sound E4;sf::Sound E5;sf::Sound E6;sf::Sound E7;sf::Sound F3; sf::Sound F4;sf::Sound F5;sf::Sound F6;sf::Sound F7;sf::Sound FS3; sf::Sound FS4;sf::Sound FS5;sf::Sound FS6;sf::Sound FS7;sf::Sound G3; sf::Sound G4;sf::Sound G5;sf::Sound G6;sf::Sound G7;sf::Sound GS3; sf::Sound GS4;sf::Sound GS5;sf::Sound GS6;sf::Sound GS7;sf::Sound pause;void set3(){A3.setBuffer(a3);A3.setLoop(true);A4.setBuffer(a4);A4.setLoop(true);A5.setBuffer(a5);A5.setLoop(true);A6.setBuffer(a6);A6.setLoop(true);A7.setBuffer(a7);A7.setLoop(true);AS3.setBuffer(as3);AS3.setLoop(true);AS4.setBuffer(as4);AS4.setLoop(true);AS5.setBuffer(as5);AS5.setLoop(true);AS6.setBuffer(as6);AS6.setLoop(true);AS7.setBuffer(as7);AS7.setLoop(true);B3.setBuffer(b3);B3.setLoop(true);B4.setBuffer(b4);B4.setLoop(true);B5.setBuffer(b5);B5.setLoop(true);B6.setBuffer(b6);B6.setLoop(true);B7.setBuffer(b7);B7.setLoop(true);C3.setBuffer(c3);C3.setLoop(true);C4.setBuffer(c4);C4.setLoop(true);C5.setBuffer(c5);C5.setLoop(true);C6.setBuffer(c6);C6.setLoop(true);C7.setBuffer(c7);C7.setLoop(true);D3.setBuffer(d3);D3.setLoop(true);D4.setBuffer(d4);D4.setLoop(true);D5.setBuffer(d5);D5.setLoop(true);D6.setBuffer(d6);D6.setLoop(true);D7.setBuffer(d7);D7.setLoop(true);DS3.setBuffer(ds3);DS3.setLoop(true);DS4.setBuffer(ds4);DS4.setLoop(true);DS5.setBuffer(ds5);DS5.setLoop(true);DS6.setBuffer(ds6);DS6.setLoop(true);DS7.setBuffer(ds7);DS7.setLoop(true);E3.setBuffer(e3);E3.setLoop(true);E4.setBuffer(e4);E4.setLoop(true);E5.setBuffer(e5);E5.setLoop(true);E6.setBuffer(e6);E6.setLoop(true);E7.setBuffer(e7);E7.setLoop(true);F3.setBuffer(f3);F3.setLoop(true);F4.setBuffer(f4);F4.setLoop(true);F5.setBuffer(f5);F5.setLoop(true);F6.setBuffer(f6);F6.setLoop(true);F7.setBuffer(f7);F7.setLoop(true);FS3.setBuffer(fs3);FS3.setLoop(true);FS4.setBuffer(fs4);FS4.setLoop(true);FS5.setBuffer(fs5);FS5.setLoop(true);FS6.setBuffer(fs6);FS6.setLoop(true);FS7.setBuffer(fs7);FS7.setLoop(true);G3.setBuffer(g3);G3.setLoop(true);G4.setBuffer(g4);G4.setLoop(true);G5.setBuffer(g5);G5.setLoop(true);G6.setBuffer(g6);G6.setLoop(true);G7.setBuffer(g7);G7.setLoop(true);GS3.setBuffer(gs3);GS3.setLoop(true);GS4.setBuffer(gs4);GS4.setLoop(true);GS5.setBuffer(gs5);GS5.setLoop(true);GS6.setBuffer(gs6);GS6.setLoop(true);GS7.setBuffer(gs7);GS7.setLoop(true);pause.setBuffer(pauseBuffer);pause.setLoop(true);}sf::Sound* naturalNotePtrs[7][5] = {{&A3,&A4,&A5,&A6,&A7}, {&B3,&B4,&B5,&B6,&B7}, {&C3,&C4,&C5,&C6,&C7}, {&D3,&D4,&D5,&D6,&D7}, {&E3,&E4,&E5,&E6,&E7}, {&F3,&F4,&F5,&F6,&F7}, {&G3,&G4,&G5,&G6,&G7}};sf::Sound* sharpNotePtrs[5][5]={ {&AS3,&AS4,&AS5,&AS6,&AS7}, {&CS3,&CS4,&CS5,&CS6,&CS7}, {&DS3,&DS4,&DS5,&DS6,&DS7},{&FS3,&FS4,&FS5,&FS6,&FS7},{&GS3,&GS4,&GS5,&GS6,&GS7}};sf::Sound getNote(char value, int octave, bool sharp){if (value =='p' || value=='P'){return A4;}if(sharp){switch(value){case 'a':return (*sharpNotePtrs[0][octave-3]);break;case 'c':return (*sharpNotePtrs[1][octave-3]);break;case 'd':return *sharpNotePtrs[2][octave-3];break;case 'f':return *sharpNotePtrs[3][octave-3];break;case 'g':return *sharpNotePtrs[4][octave-3];break;default:std::cerr<<"Invalid sharp\n";}}else {return *naturalNotePtrs[value-97][octave-3];}}void playNote(float duration,int bpm, char value, int octave, bool sharp) {sf::Clock clock;sf::Time time;sf::Sound sound;sound = getNote(value, octave,sharp);double beats=4/duration;double bps = bpm/60.;double trueTimeSecs = beats/bps;int sleepTime =trueTimeSecs*1000+1;while(1) {if(value!='p' && value!= 'P') {sound.play();}sf::sleep(sf::milliseconds(sleepTime));time = clock.getElapsedTime();if(time.asSeconds()>trueTimeSecs){sound.stop();clock.restart();break;}}}}char upperToLower(char input) {if(input>='A'&&input<='Z') {return input+32;}else {return input;}}int main(){using namespace std;using namespace N;using namespace sf;set1();set2();set3();bool delFile=false;ifstream test("x.rtttl"); if(test.good()) {cout<<"no input necessary, 'x.rtttl' already exists and will be read, as is.\n";}else {ofstream outf("x.rtttl");string in;cout<<"Please enter your rtttl file manually, in one line:\n";getline(cin,in);outf<<in<<endl;outf.close();delFile=true;}ifstream song("x.rtttl");song.seekg(0,ios::beg);float duration=0.;int octave=4;int bpm=0;float noteDuration =0.;int noteOctave =0;char noteValue='a';bool sharp = false;bool readIntro = false;bool readData = false;char c;std::cout<< "Now Playing: ";while(song){song>>c;if(c==':'&& !readIntro){readIntro=true;}else if (c==':') { readIntro=false; readData=true;}if(!readIntro && !readData){std::cout<<c;}c=upperToLower(c);if(readIntro) {if(c=='d') {song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);duration = c-48;}if(c=='o'){song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);octave = c-48;}if(c=='b') {song>>c;c=upperToLower(c);song>>c;c=upperToLower(c);int steps=0;while(c!=':'&&steps<5) {song>>c;steps++;}song.seekg(-steps-1, ios::cur);song>>c;c=upperToLower(c);if(steps==3) {bpm+=100*(c-48);song>>c;bpm+=10*(c-48);song>>c;bpm+=c-48;}if(steps==2){bpm+=10*(c-48);song>>c;bpm+=(c-48);}}}else if (readData){if(c<='9' && c>='0') {switch(c){case '1': song>>c;if(c=='6'){ noteDuration=16.;}else {noteDuration = 1.;}break;case '2': noteDuration = 2.;break;case '4':noteDuration = 4.;break;case'8':noteDuration =8.; break;case '3':noteDuration = 32.; song>>c; break;default:cerr<<"\nBad Duration:"<<c;return 1;}song>>c;c=upperToLower(c);noteValue = c;song>>c;c=upperToLower(c);if(c=='#'){sharp = true;song>>c;c=upperToLower(c);}else {sharp =false;}if(c<='9' && c>= '0' ) { noteOctave = c-48;song>>c;c=upperToLower(c); }else {noteOctave = octave;}if(c=='.'){noteDuration*=1.5; song>>c;c=upperToLower(c);}playNote(noteDuration,bpm, noteValue, noteOctave,sharp);}else if(c<='z' && c>='a') {noteDuration = duration;noteValue = c;song>>c;c=upperToLower(c);if(c=='#') { sharp = true;song>>c;c=upperToLower(c);}else {sharp =false;}if(c<='9' && c>= '0' ) { noteOctave = c-48;song>>c;c=upperToLower(c); }else {noteOctave = octave;}if(c=='.') { noteDuration*=1.5; song>>c;c=upperToLower(c);}playNote(noteDuration,bpm, noteValue, noteOctave,sharp);}}}if(delFile) {song.close();remove("x.rtttl");}return 0;}
```
I unfortunately I cannot include both the golfed and ungolfed code (space constraints), and the code could be golfed further.
A large part of the reason that the file is so long is that it has to create every pitch (12 notes \* 5 octaves) individually using sine waves.
**Compiling** I compiled using the dev cmd prompt for visual studio, but it is very similar with g++ on Linux.
```
cl music.cpp /I SFML\SFML-2.3.1\include /link SFML\SFML-2.3.1\lib\sfml-system.lib SFML\SFML-2.3.1\lib\sfml-audio.lib
```
You just need to link things properly.
credit to [SFML](http://www.sfml-dev.org/) and [this post](https://github.com/SFML/SFML/wiki/Tutorial:-Play-Sine-Wave) for the idea.
I think the timings are correct, let me know if they are not.
**Give it a listen**
[Here](https://www.dropbox.com/s/fnldtijrdgsypg2/2015-10-21-1537-29.wmv?dl=0) (Link to DropBox) is a screen recording of it playing a quick rendition of the Morrowind Theme that I whipped up. Note that in the video it doesn't ask for input because the file already exists.
```
MorrowindTheme: d=4,o=4,b=100: 8a, 8b, 2c, 8c, 8d, 2e, 8e, 8g, 2d, 16e, 16d, 8c, 8b, a, p, 8a, 8b, 2c, 8c, 8d, 2e, 8e, 8g, 2a5, g, 8b5, a5, 8a5, 8b5, c5, b5, a5, g, f, e, 2d, c, 8e, 2d, 8c, 8b, 1a
```
] |
[Question]
[
# Zig-zag strings
Given a string and a positive integer, output the string in a zig-zag wave pattern with a peak amplitude and character spacing equal to the integer.
This is similar to this [question](https://codegolf.stackexchange.com/questions/35257) but also includes character spacing.
## Input
Input can be read from STDIN or taken as function arguments. Input is a string without newlines and a positive integer.
## Output
Expected output is the string transformed into a zig-zag wave pattern -- starting upwards -- with the first character on the base line. The wave patter must have an amplitude and **character spacing** equal to the integer.
## Examples
*Input*
```
Programming Puzzles & Code Golf
2
```
*Output*
```
o g s
r g n e e G
P r i P l & d o
a m u z o l
m z C f
```
*Input*
```
Programming Puzzles & Code Golf
1
```
*Output*
```
r a n u e e l
P o r m i g P z l s & C d o f
g m z o G
```
This is code golf -- shortest program wins.
[Answer]
# Javascript (ES6), ~~133~~ ~~132~~ ~~136~~ 134 bytes
```
(s,n,o=Array(2*n+1).fill``)=>[...s].map((v,i)=>o=o.map((w,a)=>w+(a-((j=(i+3*n)%(4*n))>2*n?4*n-j:j)?" ":v)+" ".repeat(n-1)))&&o.join`
`
```
Defines an anonymous function. To call it, add `f=` to the beginning to call the function `f`. Then, it can be tested with `console.log(f("Programming Puzzles & Code Golf", 2))`
Thanks to @vihan and @edc65 for helping save some bytes! :)
@kvill: The code has been modified to address the variable character spacing requirement in the spec. Didn't notice that at first!
[Answer]
# J, 75 bytes
```
f=:4 :0
|:((]*>:@i.@#)((+:<:b)|i.#y){x|.}:(],}.@|.)|.=/~i.b=.>:+:x){' ',y
)
```
Here is function in use
```
7 f'code golf is awesome and I like it'
l
o f
g t
i i
e s
d e
o a k
c w i
e l
s
o I
m
e d
n
a
```
[Answer]
# Python 2, 151
Here is my answer using Python 2:
```
s,n=input()
a=2*n+1
l,j,o=['',]*a,n,1
for c in s:
for k in range(a):l[k]+=c+(n-1)*' ' if j==k else' '*n
j-=o
if j in [0,2*n]:o=-o
print'\n'.join(l)
```
Sample output:
```
t e h t e
s i v , t e s i v
e n a e n a
t g w t g w t g w
e n a
t e s i v , t e
h t e h
```
and
```
r a n u e e l
P o r m i g P z l s & C d o f
g m z o G
```
] |
[Question]
[
The [Library of Babel](https://en.wikipedia.org/wiki/The_Library_of_Babel) is defined as
>
> a universe in the form of a vast library containing all possible
> 410-page books of a certain format and character set.
>
>
>
For the purposes of this question, each page of the book contains 40 lines of 40 characters each. The formatting rules are as follows:
1. Legal characters are the English Latin alphabet `a-z,A-Z` and the punctuation characters `, .` (comma, space and full stop).
2. Each page contains at least one space, one full stop, one capital character and one comma.
3. There must be a space after every full stop and comma. No combination of the punctuation characters `, .` may be present more than twice in a row, and identical punctuation marks cannot exist consecutively.
4. All alphabetic characters immediately after a full stop and its accompanying space must be capitalised. This applies unless the full stop is the last or second last character on a page. Capital characters may not occur anywhere else.
## Challenge
Write a program or function which outputs a number of page excerpts from the Library of Babel, with a newline between each page excerpt.
Most importantly, the program must be able to **theoretically perfectly replicate the entire Library of Babel** if given an infinite number for the number of page excerpts to produce and a truly random RNG (Pseudorandom random number generators are allowed in the code, but assuming the PRNG is replaced with a true RNG, the code should theoretically produce the entire library).
Since this is code golf, the shortest answer will be accepted.
An example of valid output (for 2 pages):
```
, umqdzvvrdgijqrjv qmupgpgqeaegnqmmcig g
j itzgdr cdrsjgggmgjqgzplhrtoptqmbshbzgg
qcqqm plipugorpgqftnvmmgodpqaopqqfpbddnn
shmgqbf gqjclzjqaqpandqdjnfnrsgjamqqnzvu
ufzebfdbescszbvfoatftsqtefssbnnztiaupezu
gmtahqpisucljvpqohsauoudppsumnrlqjlfiapd
aurlenavahnbbbver. Lvjbgilspusdunufrgfng
nghpbcusnscibepjqhgjgcemzjdcqqjdprsrunih
emqgrfrgoqrnsvqofbrvsaqhsrqndhuhulolrese
visneqbjssfjtdrmuqq tfseuczgvbuetgijhtcs
aqnubefzuet. Gjctngshammusvdaogamtuo ajs
edjbctevfdnodgg jubshhsuaniqnsqrvatquqtg
bgoffnd hepqngjnusmglcqgdse q rdlzjqggfr
evvrcfezqqditbpztttirravbzegzleafashfzed
nhngjcccvzmmnmgpimoeztfcu laupeg rogtrip
nuaaghqptet, gss csrszqpnmvgcevqqzrfegus
lnninfajhsaapgpcljiooednbusfbmcmgqunvvzd
o dcztfgdovr. Ru, gvjchisbvo sslpzolptss
hnjbmovglvbu idqlgehrztfshrhbigivijh foi
bqcqggpjfus qmdituqucqdqgogzuvevlhujojuu
dnsuqvcsptnsjrqiezfqrjucsongqgbbutvsoqld
s vbollthqsgambsaoqgvgapszhgvsjnqepeqgvv
pqzpbqhcmfbhfcz gdeuzogmtzqjvohldeafchip
olztntqn vgtiofcjzmfluqoqruaqcqmnmfafvnc
ruzahccrqpzji, gdrhcu pgjuhqqvsgppgzrioq
qjgh oapzdiusqem ubtnhhbpdt sjzbidggsgve
ocdiuungsghltqsuezoco qqgcpnupiisnrngetq
lbjdrbqzqnqmj crgreugncqaulhqegjfq. Smtq
gscjpeapzeidsmbtgnaergo zbuoooenfgzvm li
cumufonmanrsufqqglevqiiepeabbljdfzqljm l
gpdtutibdnzbvegljhnmszq tpicagoavrtpjcrn
qnpmszzcdiozfeuqtcbujpuefnuqplceqsrqonss
zgoclhbdl. Fsrgqeuouergciq. Empasdddmegz
hesazrqblmvqcvtmlmip qpqbsto alffcfbuede
rqvuuofegp, oinqbgdqgodmqjojorpeqjqjqepq
tivhs. Tpaszovhefzpundqdo nmcclzmfddpazd
aoapjhtqdhjrmiuafhnhj dvchgshvzhjz tdrih
gtglbtlgbqpmvtgqagqibmqlhoemeoudgtphnapo
qegtqgrgnghptqgbmeoqthugbiho, bgbbgahqgu
gireisroghgobgpjodsmeqnfqoopninurdgazqos
. Rnffadjgqpgzngbpeztqrpuagprscopqnuzntf
upvamihntmjrcbfzbnmsfpsueepbsogmdcnpluci
fnoioffqtsitgatmfhn zuiozvpgprpvdpesujhn
bqlhqdtvmgtiabhz zdmothrhniczqqtgbg eatr
gmognhdjegzsaei. Gloiampbtmgtetoq gdfjoj
rlbrpjogclullgonomttrrshpolujodajesopsfr
cabnhbohntadjtltsztbvzcebvdqnjhplicslco
vabftndmi netqjv. Rl tmicpanralmamruovfi
ssnmh gtlsqilcrnrsaislut mnzhsfojtmsqtlb
mbl dcjvuldnvtfsjsp, urundndz ehopedrptm
abtvadojvdbe tolzmotjtbiigmazlmznjrnof i
ioogsospoghiojshqdimpuibeaosflbpjqvcdord
uomtjebohjmzeutjvmca eq, ljttbbtaomjsoja
z crvmmhonescmnovmnznf brhufrudosfensru
fdotflmug gclmondggitamnsrsfjiaqnootlanr
tuiftvia. Rccnvuebeocub, unihegbtqgslps
ngsqjflejnitpcorluetbiacgqjtbtroejeopqso
ca sdziornhsvivcteaadspibt qippmqmduinia
oqtvoo ttt qnfrfchpszaiiecsrmsrblmbojot
h rtjzqqo esufacjdvbposroesoorszoiutfloe
hs bt eibajrocingbmvterhomfuzttemvfjtltv
lcmoevnlzofpd zsjbmgvllhgrsoclvnnhnscodo
tjocglurng hrhp og bstpeabzdaocoircqb go
devvmlslsqnjibpjcmndmqdvgfmhcsvgzrbicuuv
jgfthudlg. Tfsnn tuarpgogh ibsemtjfgdisj
tgcetprzomzfadthmrroivoheepingsmovrmjiit
ufdvi cvpti oift. Bbbunppebonj gpbbtoeto
tcmnlrftlhombnbqrcqemombpoapsucqzpdgfifq
qfcssehjgtptmavbovqgpt lhasnjtdodgrzlogs
vljvfljbaqquobboupttttzaqtmpodnup qvhoz
iqnceoetiurboptoerauqdhltfaonajvrztvldpt
tfvmvtaajavaedl imlvmvrdrqocuozsurdplequ
elvjpfh rttdolgfafhutemovqcfutaoevitbrqs
jiz tcduimpbqbqmrsrmmslqouiplohvhdsbgzzp
hlr mgidoaplsabgvjvgidbrhttpqpd avumccqb
cenvfobat ggah ibr rfbogzhttliaoooitblto
hagihesjvpabqphnzamhinvzaeqcpjb jigrntah
objdqrrnrcvapq qvosl uhgcotpno abgertveq
toroqodlbzvtqdfsrehedfeenjzlfabdassqfzah
szgionarrivuoaoajvmqzntzemmlintajoijmjac
```
[Answer]
## Lua, ~~353~~ 346 bytes
Because of how lengthy the Pyth answer is and the fact that I know Lua could never even come close to Pyth I feel like I am missing a rule...
Code:
```
math.randomseed(os.time())g="abcdefghijklmnopqrstuvwxyz ,."for i=1,io.read() do
print(" ")for i=1,40 do k=0h=0v=0 print("")for j=1,40 do c=math.random(1,#g-h-v)t = g:sub(c,c)if v>0 then v=0 end
if r==1 then r=0;t=t:upper()end if c>26 then v=2;if t=="." then r=1 end k=k+1;if c>27 then t=t.." " end if k>1 then h=2 end end io.write(t) end end end
```
Probably can be golfed down quite a bit, but this is it for now.
[Answer]
# Pyth, ~~125~~ 72 bytes
```
VQV1601=+kO+G",. "Iqek\,=+k+dOG)Iqek\.=+k+dOrG1)Iqekd=+kOG))VhcckJ40JN)d
```
[Try
it online here.](http://pyth.herokuapp.com/?code=VQV1601%3D%2BkO%2BG%22%2C.+%22Iqek%5C%2C%3D%2Bk%2BdOG)Iqek%5C.%3D%2Bk%2BdOrG1)Iqekd%3D%2BkOG))VhcckJ40JN)d&input=2&debug=0)
I finally golfed this down to a reasonable size. And by "golfed down" I mean "rewrote entirely". It still doesn't meet the requirements perfectly, but it's better than the previous iteration. I even have a breakdown now:
```
O+G",. " Randomly choose a lowercase letter (variable G), comma, period, or space
+k Append it to variable k (initialized to empty string)
Iqek\, If the last character of k is a comma:
=+k+dOG) Append a space (variable d) and a random lowercase letter to k
Iqek\. If the last character of k is a period:
=+k+dOrG1) Append a space and a random capitalized letter to k
Iqekd If the last character of k is a space:
=+kOG Append a random lowercase letter to k
V1601…) Repeat the above process 1601 times
J40 Assign variable J = 40
ckJ Chop k into strings of length 40
hc…J Take the first 40 strings from that list
V…N) Loop over that list of 40 strings and print them
(print is implicit and N is current element of the loop)
d Print a space on a new line
VQ… Repeat the above process Q times (Q is the evaluated input)
```
The only issue here is that a period, comma, or space will always be followed by the appropriate characters, even after linebreaks. For example, if a line ends with a period, the next line will always start with a space followed by a capital letter. I do not think this is what the question asked for.
] |
[Question]
[
# Introduction
*Jim* and *Bob* are playing badminton doubles against two other players, but mid-game they face a dilemma:
After a fast-paced rally they have no idea who has to serve next and where they have to stand for the next serve.
Bad enough they only know the scores in order.
## Rules:
To help them out, you have to know the rules:
1. If the serving team has an even score, serving is done by the player on the right side (relatively facing towards the net)
2. If the serving team has an odd score, serving is done by the left player.
3. If the serving team changes, the players' position remains.
4. If one team keeps the right to serve the ball, the two players of that team swap places, so the same player serves again.
5. The team, that scored last, serves next.
**This is where you come to help them out.**
# Your task:
Your task is to take the scores in order and return the position for *all four* players according to the rules as well as the player, who has to serve next.
# Specification:
## Input:
Input is a string / array / set / whatever you like containing all scores in the order they are scored.
Example: `"0:0, 0:1, 0:2, 1:2, 1:3"` or `["0:0", "0:1", "0:2", "1:2", "1:3"]`
You may assume team 1 (the left part of the score) served first in the beginning.
*The input is not secured to be valid!*
## Output:
Your program / function / script has to output an ASCII-art style badminton court (don't care about orientation) with the position of the players and some representation of the player serving next (a single line saying `Next to serve is >Player1<` is enough).
**Example output of the example given above (`"0:0, 0:1, 0:2, 1:2, 1:3"`):**
```
|-----|-----|
|-Jim-|-Bob-| //Team 1
|###########|
|-P4--|-P3--| //Team 2
|-----|-----|
Player P4 of team 2 serves next.
```
The players are named Jim, Bob, P3 and P4. P3 and P4 swap their places after scoring "0:2" and keeping the right to serve. Jim and Bob never scored two times in a row and thus never swap places.
# Last notes about input and output:
* Input is assumed to be always in order with the first (*left*) score to be team 1, which may be assumed to have served first.
* The names of the players are irrelevant as long as it is documented which player belongs to which team.
* Team 1 is always the upper/left team in your output.
* Even though a usual badminton round ends when one team scores 21 (without overtime), you may assume the game to be as long as the two teams want to play.
* Sometimes the input may be incomplete (missing a score). Then your program has to output an error message indicating invalid input (`E` for `Error!` is enough for golfing reasons).
# Scoring:
This is code-golf, so the least amount of bytes wins.
There are bonuses to claim though:
* **-20%** if you output the court and server for every single serve.
* **-10%** if your program allows to choose the serving team.
* **-15%** if the user can choose the names for the players.
The bonus percentages are first added and then applied to the byte count, resulting in a maximum bonus of *45%*!
# Test cases (so you don't have to come up with your own):
(Strings only, including output and validation):
**Example1:**
```
0:0, 1:0, 2:0, 3:0, 3:1, 3:2, 4:2, 4:3, 5:3, 6:3, 6:4, 7:4, 7:5, 7:6, 8:6, 8:7, 9:7, 10:7, 11:7, 12:7, 12:8, 12:9, 13:9
```
Output:
```
|-----|-----|
|-Bob-|-Jim-| //Team 1
|###########|
|-P4--|-P3--| //Team 2
|-----|-----|
Player Jim of team 1 serves next.
```
**Example2:**
```
0:0, 0:1, 0:2, 1:2, 2:2, 3:3, 4:3, 4:4 -> Invalid
/\ Both teams can't score at the same time/missing intermediate score
```
Output:
```
Invalid input! Please check input and try again.
```
**In case you have questions or need clarification, please ask so I can improve the challenge.**
[Answer]
# Python 2: 320 chars - 45% = 176
```
def f(n,t,s):
for l,r in zip(s,s[1:]):
d=[r[0]-l[0],r[1]-l[1]]
if[0,1]!=sorted(d):print'E';break
if d[1]==t:v=2*t;n[v:v+2]=n[v:v+2][::-1]
t=d[1];m=max(map(len,n))+2;z=('|'+'-'*m)*2;c='|{:^%d}'%m;print'|\n'.join([z,c*2,'|#'+'#'*2*m,c*2,z,'Player {} of team {} serves next.\n']).format(*n+[n[2*t+(t+r[t])%2],t+1])
```
I'm not happy with lots of things. For instance the line `d=[r[0]-l[0],r[1]-l[1]]` is so ugly. But spend quite some time in golfing this.
Claims all 3 bonuses.
Please tell me, if I my output is not entirely the way you wanted. The question was not very clear.
## Usage:
This defines a python method. The parameters are a list of strings (the names of the players), an integer 0 or 1 (serving team) and a list of tuples of the scores.
```
f(["Jim","Bob","P3","P4"],0,[(0, 0), (0, 1), (0, 2), (1, 2), (1, 3)])
f(["Jim","Bob","A","Montgomery"],0,[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (4, 2), (4, 3), (5, 3), (6, 3), (6, 4), (7, 4), (7, 5), (7, 6), (8, 6), (8, 7), (9, 7), (10, 7), (11, 7), (12, 7), (12, 8), (12, 9), (13, 9)])
f(["Jim","Bob","P3","P4"],0,[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (3, 3), (4, 3), (4, 4)])
```
## Output:
```
|-----|-----|
| Jim | Bob |
|###########|
| P4 | P3 |
|-----|-----|
Player P4 of team 2 serves next.
|------------|------------|
| Bob | Jim |
|#########################|
| Montgomery | A |
|------------|------------|
Player Jim of team 1 serves next.
E
```
This is of course shortened, for the full output visit <http://pastebin.com/AzbnEbaH>.
] |
[Question]
[
# The problem
Through a terrible procastination accident you are reborn as Scrooge McDuck for a day. To make the most out of the situation you decide to give away food to the poor. Since you also are a mathematician you store the food in a vector `v(1,2,3)`.
You want to give each family approximately the same food. To make things simple each family has `n` members. The task is to write a code to split the vector `v` into rows of length `n` where each row has the same amount of ''food''.
Equality is measured by the [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation); how different the sum of each row (the food each family receives) is from the mean.
## Input
Input should be an integer `n` and a vector `v` The length of `v` does not have to be divisible by `n`; zero pad it if that is the case.
## Example
```
v = (4, 9, 3, 6, 19, 6, 9, 20, 9, 12, 19, 13, 7, 15)
n = 3
```
Should return
```
4 6 19
9 9 13
3 20 7
6 9 15
19 12 0
```
The sum of each row is 29,31,30,30,31, so the standard deviation is 0.748331 for `n` = 2. Note the presence of a 0 that we added.
## The output
The code should output the standard deviation. You can also print the matrix but this is not a requirement.
## The score
The winner is judged **not** by the shortest code, but by the **sum of the standard deviations**, given [the test vector](http://pastebin.com/ybAYGHns) and `n` = 2, 3, and 23. e.g.
```
Score = your_func(2, foodvec) + your_func(3, foodvec) + your_func(23, foodvec)
```
Use the following vector to test <http://pastebin.com/ybAYGHns> and test for `n=2,3,23`. The final score is the *sum* of those three tests.
The vector is somewhat big since Scrooge has a lot of food saved up.
[Answer]
## Python 2: 6.368013505 + 96.84345115 + 5.572725419 = 108.784190072
This is probably not a very optimized or smart approach but it gave me decent results so i decided to post it. I sorted the list and chopped the list in groups of n long. The odd groups get reversed and then I zipped them together (just look at the code really). It's small and quick and it works fairly well on a big amount of numbers (not so much on a small amount, it scored around 3.5 on the example).
So this is my function:
```
def myFunction(v, n):
v = sorted(v)
while len(v) % n != 0:
v = [0] + v
lists = list(grouper(v, len(v)/n))
for i in range(len(lists)):
if i%2 == 0:
lists[i] = lists[i][::-1]
zippedList = list(zip(*lists))
for i in range(len(zippedList)):
zippedList[i] = sum(zippedList[i])
print(zippedList)
return numpy.std(zippedList)
def grouper(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
```
Because it's such an easy (read lazy) solution, it's very fast. The entire program took about 0.1s to run. With pypy it would be even faster but Numpy is apparently still not ported to pypy and i don't feel like manually calculating the standard deviation so yeah. If I made any huge mistakes (both on programming and english grammer) or have recommendations, tell me. It's the first time I gave a code challenge a try.
[Answer]
## Python 3 using PyPy: 6.368014 + 0.701679 + 0.486916 = 7.556608
### Optimal for n = 2
There are 1000 numbers, so we want to distribute the food to 500 families. If the food vector is sorted (`food[1] >= food[2] >= ... >= food[500]`), then the minimal std is reached by giving the first family the food items `food[1]` and `food[500]`, the second family `food[2]` and `food[499]`, the third family `food[3]` and `food[498]`, ...
I thought of a quite easy proof. Basically I expanded the product of the std, removed the terms that appear in each food partition, and proofed that the result is minimal. If someone wants a more detailed explanation, just ask me nice.
### Approximation for n > 2
I don't think, that there's a fast way of finding the optimal solution for n > 2.
I start with an heuristic solution. I distribute the food items in sorted (descending) order to the family with the lowest food so far (only to such families, which have received less than n food items).
Afterwards I improve the solution, by swapping 1 food item between a pair of families.
I use the `N` families with to lowest food and the `N` families with the most food so far. After all possible swaps, I choose the best swap, and call the local search recursively.
The bigger the value of `N` is, the lower will be the std (but also the running time will be longer). I used `N = 20` and when I can't find swap, I try again with `N = 100`. PyPy finishes all 3 test cases in less than 8 minutes.
### Code
```
def findSmallestStd(food, n):
food.sort(reverse=True)
while len(food) % n:
food.append(0)
family_count = len(food) // n
if n == 2: # optimal
return list(zip(food[:len(food)//2], reversed(food[len(food)//2:])))
else: # heuristic approach
partition = [[] for _ in range(family_count)]
for food_item in sorted(food, reverse=True):
partition.sort(key=lambda f: sum(f) if len(f) < n else float('inf'))
partition[0].append(food_item)
return local_search(partition, calc_std(partition))
def local_search(partition, best_std, N = 20):
# find indices with smallest and largest sum
families1 = nsmallest(N, partition, key=sum)
families2 = nlargest(N, partition, key=sum)
best_improved_swap = None
for family1, family2 in product(families1, families2):
for index1, index2 in product(range(len(family1)), range(len(family2))):
family1[index1], family2[index2] = family2[index2], family1[index1]
std = calc_std(partition)
if std < best_std:
best_std = std
best_improved_swap = (family1, family2, index1, index2)
family1[index1], family2[index2] = family2[index2], family1[index1]
if best_improved_swap:
family1, family2, index1, index2 = best_improved_swap
family1[index1], family2[index2] = family2[index2], family1[index1]
partition = local_search(partition, best_std)
elif N < 100:
return local_search(partition, best_std, 100)
return partition
```
The complete code and the output is available on Github: [Code](https://gist.github.com/jakobkogler/2aa362b0b46011031bce), [Output](https://gist.github.com/jakobkogler/0db7d1948dce9635dbab)
### edit
I was confused about the std-calculation, that N3buchadnezzar proposed in the original question. I updated it to the correct mathematical definition, so we can compare different solutions.
### edit 2
In my last submission I varied the family count. E.g. the best solution for n = 2 used 507 families. N3buchadnezzar told me, that there have to be exactly `ceil(len(food) / n)` families. So I changed my code a little bit. Basically removed the loop over the family counts and improved the local search.
] |
[Question]
[
# Background
Imagine, you have a big array `A`, which is mostly zeroes, but contains a short subarray `B` which has only strictly positive entries. For instance:
```
| A |
[0 0 0 0 1 2 3 0]
| B |
```
Now say, we split the array `A` into consecutive subarrays of length `d` (with a shorter final array, if the `d` doesn't divide the length of `A`). For `d = 3`:
```
[0 0 0 0 1 2 3 0]
| |
[0 0 0] [0 1 2] [3 0]
```
And now sum up each of those arrays:
```
[0 3 3]
```
And discard zero sums:
```
[3 3]
```
# The Challenge
You're to write a function which prints that final array of sums in any convenient array format, given the following 5 parameters (or any subset thereof, if you don't need all of them):
* The small array `B`.
* The size of the small array `B` (`3` in the above example).
* The *size* of the big array `A` (`8` in the above example).
* The index where the small array begins (`4` in the above example).
* The length `d` of the subarrays (`3` in the above example).
# The Rules
* You are not allowed to construct the big array `A` explicitly!
* You are not allowed to construct any of the subarrays of length `d` explicitly!
* That means you have to get the computation directly from the `B` and the other parameters at your disposal!
Fewest characters wins!
[Answer]
# CJam, ~~34 32~~ 28 characters
```
{"ɚ광䃻噣攍圍숵셳ﶓ訙➰鑓쥾"2G#b126b:c~}
```
This is a compressed form of the following 31 bytes solution
```
{:D%0a*\+0\{+U):UD={0:U}*}%0-p}
```
~~This can be golfed further.~~
[Try it online here](http://cjam.aditsu.net/)
Input is in format of `[small_array] index_where_small_array_begins divisor`
For example:
```
[1 2 3] 5 3{"ɚ광䃻噣攍圍숵셳ﶓ訙➰鑓쥾"2G#b126b:c~}~
```
will give output
```
[1 5]
```
Explanation (outdated):
```
{ "Begin of function block";
:D "Store the divisor in D";
% "Calculate index_where_small_array_begins%divisor";
0a* "Get an array of 0 on length above number";
\+ "Prepend it to the small_array";
_,{ }* "Run this code block length(small_array) times";
0\ "Put 0 before small_array. This 0 marks the"
"current sum of the current mini_array";
{ }D* "Run this code block divisor times";
0+ "Add 0 at the end of mini array";
( "Take out the first element from the mini array";
@ "Rotate the stack to get current sum on top";
+ "Add the first element to the current sum";
\ "Swap to put current mini_array on top of stack";
;] "Pop the residual array and wrap the sums in an array";
0-p "Remove 0 and print the sum_of_mini_arrays_array";
} "End of function block";
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth/) - 30 ~~32~~
**Edit**: Fixed an error with mini array size 1 or very large offset.
```
D:GHYKm0GFNG~@K%/HYlGN~H1)RfTK
```
Defines a function `:` that takes `small_array`, `index_where_small_array_begins` and `divisor` as arguments. You can call it like:
```
:[1 2 3) 5 3
```
Returns: `[1, 5]`
[Try it online](http://isaacg.scripts.mit.edu/pyth/index.py)
Explanation:
```
D:GHY : Define :
Km0G : Make K an array of len(G) zeroes
FNG ) : for N in small_array
~@K%/HYlGN : Add N to K[floor_div(H,Y)%len(G)]
~H1 : Increment H
RfTK : Return K without any zeroes
```
[Answer]
# CJam, ~~30~~ 28 characters
```
{"ᘏ阋Յ꺂࠻䚉누伪"6e4b127b:c~}
```
(SE may have swallowed some unprintable characters. Please copy the code [from this character counter](https://mothereff.in/byte-counter#%7B%22%11%E1%98%8F%E9%98%8B%D5%85%EA%BA%82%E0%A0%BB%E4%9A%89%EE%90%A6%EB%88%84%E0%AD%9B%EE%89%B1%E4%BC%AA%EE%9F%8B%226e4b127b%3Ac~%7D).)
Yay for counting by characters and Unicode packing. The above string is converted to character codes, interpreted as base-216, converted to base-129, and converted back to characters, and evaluated, to give the actual code (measuring 30 bytes):
```
{:M%0a*\+{0\{_0a?(@+\}M*}h;]p}
```
This is a block, the closest thing to a function in CJam. It expects the small array, the offset, and the divisor on the stack. You can use it like
```
[1 2 3]4 3{" ড숺ꤪ洽ὦ﮻ڤ綃掖迓湯"2G#b129b:c~}~
```
[Test it here.](http://cjam.aditsu.net/)
## Explanation
```
:M "Store divisor in M.";
% "Take offset modulo divisor to get R.";
0a "Push [0].";
* "Repeat to get R zeros.";
\+ "Preprend to small array.";
{ }h "Repeat while... leaves condition on the stack.";
0\ "Put a 0 underneath the array to initialise sum.";
{ }M* "Run the block M times.";
_0a? "Replace the list by [0] if it's empty.";
( "Split off first element.";
@ "Pull up current sum.";
+\ "And and pull list back to the top.";
; "Remove leftover empty list.";
] "Wrap sums in array.";
p "Print string representation to STDOUT.";
```
[Answer]
# JavaScript (ES6) 58
Function with 3 parameters
- b is the small array
- i is the index where the small array begins
- d is the dimension of the subarrays
(t is used just as a local variable)
```
F=(b,i,d,t=[])=>b.map((v,p)=>t[p=(p+i%d)/d|0]=v+~~t[p])&&t
```
**Test** In FireFox/FireBug console
```
F([1,2,3],4,3)
```
*Output*
```
[ 3, 3 ]
```
] |
[Question]
[
WinAli is a model assembler for Windows. It emulates a real CPU and is meant to help students learning and understanding the Assembly language.
German Wikipedia article: <http://de.wikipedia.org/wiki/WinAli> (there is no english article at the moment)
In case you want to test your produced output: [Link to Google Drive](https://drive.google.com/file/d/0B7M-3MbB6wJ5NU1iZmRxdDQ2ejA/view?usp=sharing) (the program itself is in German but is easy to use even if you don't understand German)
### Some information about WinAli (data and syntax)
**Data types:**
The only data type in WinAli is a 2 byte long "Integer" which is in fact a *Smallint* or *short*. So you don't have to take care of correct types. This is also rounded when dividing.
**Variables and constants:**
Variables are defined like this after the commands:
```
name DS F
```
* *name* is obviously the name of the variable
* *DS* is the keyword for a new variable
* *F* defines the length of the variable in bits; this is zero-based and hexadecimal so F = 16 bits
Constants are very similar:
```
name DC value
```
* *name* is simply the name of the constant
* *DC* is the keyword for a new constant
* *value* is the value assigned to that constant e.g. `two DC '2'`
* You don't need to specify constants at the end of the code. You can also write them inline with the `LDA` (load) operation e.g. `LDA 0,'2'`. This loads "2" into register 0 (the accumulator).
**Syntax:**
The code is aligned into 4 columns which are separated by a space or tab:
```
label command params comment
```
* *label* is used for the `b label` command (`goto label`) and is often skipped.
* *command* one of the commands listed below.
* *params* one or two parameters with at least one register and if needed another register, variable, stack or address; these parameters are separated by a comma (`,`).
* *comments* (optional) a comment prefixed with `;` or `*` until the end of the line.
### **Small code reference:**
*There are more commands but for this challenge you only need those:*
* `INI A` Stores the next user input into variable `A`
* `OUTI A` Outputs the value the variable `A` is holding. You can't use a register here for some reason.
* `LDA 0,A` Loads the value of `A` into register 0
* `STA 0,A` Stores the value of register 0 into the variable `A`
* `ADD 0,A` Adds the value of `A` to the value of register 0
* `SUB 0,A` Multiplies the value of `A` with the value of register 0
* `DIV 0,A` Divides the value of `A` by the value of register 0
* `EOJ` Defines the end of the job i.e. executable code. Variable and constant declarations begin after this mark.
*Not explicitly needed for this challenge:*
* `program START 0` Sets the first address to be executed to 0 i.e. the next line (`program` is just the name of the program but is needed for the compiler)
* `END program` Ends the program i.e. stop executing, even if other operations would follow
# Your challenge!
Write a program or script that takes a mathematical expression with constant numbers and variables and outputs the WinAli code that takes all variables as input and outputs the result of that expression.
* *You don't need to output the `START` and `END` commands*
* Even though there are 16 registers defined in WinAli we only use register 0, which is the accumulator for all calculations
* You can't use two variables as parameters of a command. You have to save all your results into the accumulator (register 0)
* The input is always on the form of either `x:=(a+b)/c` or simply `(a+b)/c`, you decide
* You only need to take care of `+ - * / (ADD, SUB, MUL, DIV)`, so *no complex calculations like roots, squares or even sinus*
* *Tip:* Try to first extract simple expressions with only 2 arguments e.g. `a:=a+b` then `x:=a/c`
* *Tip:* Your program is allowed to use additional (auxiliary) variables if you can't overwrite variables that are not used later in your code. Define them as `h1 DS F`.
* *Tip:* Empty lines are useless. Try to avoid them. (You really don't need them)
**Example:**
```
Mathematical expression:
x := (a+b)*c
Expected output (empty lines are for easier reading):
INI a
INI b
INI c
LDA 0,a
ADD 0,b
MUL 0,c
STA 0,a
OUTI a
EOJ
a DS F
b DS F
c DS F
```
## Scoring:
Your score is defined by the length of your code **+** the length of the output of the following expressions:
```
x:=a+b+c*c/d
x:=(a+b)/c-d
x:=a-b*c-d/e
x:=2*a-b*c+d
```
* *-10%* if your code can handle unary minus in expressions.
*In case of a tie, the answer that produces the shortest working WinAli code wins.*
**The solutions may not be hardcoded in any way. I will validate each answer with additional expressions to make sure your answer is correct.**
[Answer]
# Perl 5: 948, 355 code + 593 output
After some golfing. Previous shorter version did not properly parse `(a+b)-4*c`.
```
%m=split'\b','-SUB+ADD/DIV*MUL<LDA>STA';$i='(\w+|(?<!\w|\))-\d+)';
$_=<>;@x{@y=/([a-z]\w*)/gi}=@y;print"\tINI $_
"for@x=keys%x;
$f=$_,$x.="<$&>".($g=(grep$f!~$_,a..zz)[0]),$x{$g}=s/@/$g/
while s|\($i\)|$1|g,s|$i[*/]$i|@|||s|$i[+-]$i|@|;$_="$x
\tOUTI $_\tEOJ
";s/>$i<\1//g;s!(^|\b)[-+/*<>]!\n\t$m{$&} 0,!g;
s!-?\d+$!'$&'!mg;print;print"$_\tDS F
"for keys%x
```
Example use:
```
$perl winali.pl <<<"2*a-b*c+d"
INI b
INI a
INI d
INI c
LDA 0,'2'
MUL 0,a
STA 0,a
LDA 0,b
MUL 0,c
STA 0,b
LDA 0,a
SUB 0,b
ADD 0,d
STA 0,b
OUTI b
EOJ
b DS F
a DS F
d DS F
c DS F
```
] |
[Question]
[
The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!
## The Challenge
We've done run-length encoding [be](https://codegolf.stackexchange.com/q/1015/8478)[fore](https://codegolf.stackexchange.com/q/7320/8478) but only considered runs of a single character. Of course, we can sometimes make even greater savings if we consider runs of multiple characters.
Take `aaaxyzxyzxyzdddd` for instance. This can be compressed to `3a3{xyz}4d`. Your task is to write a program of function which, given a case-sensitive string of letters and spaces, compresses it *optimally* using run-length encoding for multi-character runs.
You may take input via function argument, STDIN or ARGV and return the result or print it to STDOUT.
Runs must not be nested, so `aaabbbaaabbb` must be `3a3b3a3b`, *not* `2{3a3b}`. I.e. the string should be encoded (or decoded) in a single pass.
### Consequences of Optimal Compression
Some examples where naive application of run-length encoding might lead to suboptimal results:
* `abab` must not be "compressed" to `2{ab}`
* `aaaabcdeabcde` must not be compressed to `4abcdeabcde` but `3a2{abcde}` instead.
If there are two optimal versions (e.g. `aa` and `2a` or `abcabc` and `2{abc}`) either result is fine.
### Examples
```
Input Output
aa aa -or- 2a
aaaaaAAAAA 5a5A
ababa ababa
abababa a3{ba} -or- 3{ab}a
foo foo bar 2{foo }bar
aaaabcdeabcde 3a2{abcde}
xYzxYz xYzxYz -or- 2{xYz}
abcabcdefcdef abcab2{cdef}
pppqqqpppqqq 3p3q3p3q
pppqqqpppqqqpppqqq 3{pppqqq}
```
## Scoring
Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.
If there is a tie, the winner would be the person with the most second-place submissions (and so on).
## Rules, Restrictions, and Notes
Please keep all of your different submissions contained within a single answer.
Also, no shenanigans with basically the same answer in slightly different language dialects. I will be the judge as to what submissions are different enough.
## Current Leaderboard
This section will be periodically updated to show the number of languages and who is leading in each.
* C# (265) — edc65
* JavaScript (206) — edc65
* Python (214) — Will
* VB.NET (346) — edc65
## Current User Rankings
1. edc65 (3)
2. Will (1)
[Answer]
## Python 214
```
def t(s):
b=s;l=len;r=range(1,l(s))
for i in r:
p=s[:i];b=min(b,p+t(s[i:]),key=l);x=1
for j in r:k=i*j+i;x*=p==s[i*j:k];b=min(b,(b,''.join((`j+1`,"{"[i<2:],p,"}"[i<2:],t(s[k:]))))[x],key=l)
return b
```
(second level indent is tab)
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), this is the naive recursive approach without early-exit, so its really really slow.
[Answer]
# JavaScript (E6) 206
Almost sure it is optimal. I start trying to encode the longest string with the max gain, and recursively encode what remains at left and right. After each try I keep the shortest result.
Golf notes (JS specific)
* Pseudo arguments instead of locals (for recursion)
* Compare lengths using out of bounds index that gives 'undefined'
```
R=(s,n=s,d=s.length>>1,w,i,j,c)=>{
for(;d;--d){
for(i=-1;s[d+d+i++];){
w=s.slice(i,j=i+d);
for(r=1;w==s.substr(j,d);j+=d)++r;
c=d>1?r+'{'+w+'}':r+w,
// c[d*r-1]|| /* uncomment this line (+10 bytes) to have faster response
n[(c=R(s.slice(0,i))+c+R(s.slice(j))).length]&&(n=c)
}
}
return n
}
```
**Test** In FireFox/FireBug console
```
;['aa','aaaaaAAAAA','ababa','abababa','foo foo bar', 'aaaabcdeabcde',
'xYzxYz', 'abcabcdefcdef', 'pppqqqpppqqq','pppqqqpppqqqpppqqq']
.forEach(x=>console.log(x+' -> '+R(x)))
```
*Output*
```
aa -> aa
aaaaaAAAAA -> 5a5A
ababa -> ababa
abababa -> 3{ab}a
foo foo bar -> 2{foo }bar
aaaabcdeabcde -> 3a2{abcde}
xYzxYz -> xYzxYz
abcabcdefcdef -> abcab2{cdef}
pppqqqpppqqq -> 3p3q3p3q
pppqqqpppqqqpppqqq -> 3{pppqqq}
```
# C# (.NET 4.0) 265
Exactly the same algorithm
```
string R(string s)
{
string n=s,c,w;
int l=s.Length,d=l/2,i,j,r;
for(;d>0;--d)
{
for(i=0;d+d+i<=l;i++)
{
w=s.Substring(i,d);
for(j=i+d,r=1;j+d<=l&&w==s.Substring(j,d);j+=d)++r;
c=d>1?r+"{"+w+"}":r+w;
// if(c.Length<d*r){ // uncomment this line for faster execution
c=R(s.Substring(0,i))+c+R(s.Substring(j));
n=c.Length<n.Length?c:n;
//} // and this one of course
}
}
return n;
}
```
**Test** in LinqPad, mode 'C# program', add a main after the R function
```
void Main()
{
string[] test = {"aa","aaaaaAAAAA","ababa","abababa","foo foo bar","aaaabcdeabcde",
"xYzxYz","abcabcdefcdef","pppqqqpppqqq","pppqqqpppqqqpppqqq"};
test.Select(x => new { x, r=R(x) }).Dump("Result");
}
```
Same Output
# VB.Net (.NET 4) 346 (probably)
Same algorithm and same library, but the language is different enough
I can't be sure about byte count, as Visual Studio keep reformatting the code and adding spaces.
Golf notes: better use something else
```
function R(s as string)
dim n=s,c,w
dim l=s.Length,i,j,d
for d=l\2 to 1 step-1
for i=0 to l-d-d
w=s.Substring(i,d)
j=i+d
r=1
do while (j+d<=l andalso w=s.Substring(j,d))
r=r+1
j=j+d
loop
c=if(d>1,r & "{" & w & "}",r & w)
if(c.Length<d*r) then
c=R(s.Substring(0,i))+c+R(s.Substring(j))
if c.Length<n.Length then n=c
end if
next
next
return n
end function
```
] |
[Question]
[
You have found the [path through the forest](https://codegolf.stackexchange.com/questions/36404/the-forest-path) and now plan on travelling along it. However, just before you start on your journey, the ground turns into lava.
You manage to scurry up the nearest tree (the trees have inexplicably not burnt up), but now you are faced with a problem: how can you get out of the forest when the floor is lava? The answer hits you like a good idea for a programming challenge - you can use your magical grappling hook (made from a piece of the canoe earlier) to swing through the trees and the branches!
However, you're not sure *which* trees and branches you need to swing on to get there. Luckily, you have your programming skills, so you decide to draw a program on your arm to tell you which trees to swing on. However, there is not much surface area on your arm, so you must make the program as small as possible.
We can represent a forest using a `n` by `m` array. The following characters will make up the array:
* `T`: A tree. You can land here. You cannot use your grappling hook on this. You can swing through this.
* `P`: Functions the same as `T`. You start here.
* `Q`: Functions the same as `T`. This is the goal.
* `+`: A branch. You cannot land here. You can use your grappling hook on this. You can swing through this.
* `*`: A man-eating spider. If you land here, you die. If you use your grappling hook on this, you die. If you swing through this, you die.
* `-`: Regular ground, in other words, lava. You cannot land here. You cannot use your grappling hook on this. You can swing through this. All area outside of the given array is this type.
Here is an example of what a forest might look like:
```
y
----T---+------12
---------------11
----T---+---T--10
---------------9
T-+-T-+-T------8
---------------7
------------+--6
----+----------5
+-------+------4
---------------3
----P---+-*-Q--2
---------------1
T-+-T-+-T------0
012345678911111
x 01234
```
I will refer to coordinates with the notation `(x,y)`, as shown on the axes.
You begin from `P` and have to make your way to `Q`. To do this, you swing from tree `T` to tree `T` using branches `+`. You can attach your grappling hook on any branch that is orthogonal to you - that is, a branch that is either on the same x position or y position that you are in. For instance, if you were at the position `(4,8)` in the example forest, you could attach your grappling hook to the positions `(2,8)`, `(6,8)`, or `(4,5)`. You can attach this even if there are trees or other branches between you and the branch.
Once you attach your grappling hook onto a branch, you will travel a distance in the direction of the branch equal to twice the distance between your initial position and the branch. In other words, your final position will be the same distance from the branch as your starting position, just on the opposite side. A more formal definition of how the movement works is below. A subscript of `v` is the final position, `u` is the initial position, and `b` is the position of the branch.
$$(x\_v, y\_v) = (2x\_b-x\_u, 2y\_b-y\_u)$$
Note that if there is a spider between your initial position and your final position, you cannot go there. For example, in the example forest the swing from `(4,2)` to `(12,2)` is not possible because you would run into the spider at `(10,2)`.
The goal is, using this swinging through branches method, to travel from the point `P` to the point `Q` in the *fewest* swings possible. For instance, in the example forest, the shortest path is:
1. From `(4,2)` to `(4,8)` using `(4,5)`
2. From `(4,8)` to `(0,8)` using `(2,8)`
3. From `(0,8)` to `(0,0)` using `(0,4)`
4. From `(0,0)` to `(4,0)` using `(2,0)`
5. From `(4,0)` to `(4,10)` using `(4,5)`
6. From `(4,10)` to `(12,10)` using `(8,10)`
7. From `(12,10)` to `(12,2)` using `(12,6)`
***Input***
Input is from whichever method is convenient (STDIN, command line arguments, `raw_input()`, etc.), except it may not be pre-initialized as a variable. Input starts with two comma separated integers `n` and `m` representing the size of the board, then a space, and then the forest as a single long string. For instance, the example forest as an input would look like this:
```
15,13 ----T---+-------------------------T---+---T-----------------T-+-T-+-T---------------------------------+------+----------+-------+-------------------------P---+-*-Q-----------------T-+-T-+-T------
```
***Output***
Output a space-separated list of comma separated tuples indicating the coordinates of the branches that you must swing to. For instance, for the above input the output would be:
```
4,5 2,8 0,4 2,0 4,5 8,10 12,6
```
You may have noticed that this is not the only shortest path through the forest - indeed, going to `(8,8)`, down to `(8,0)`, left to `(4,0)` and continuing as normal from there takes exactly the same number of swings. In these cases, your program may output *either* of the shortest paths. So the output:
```
4,5 6,8 8,4 6,0 4,5 8,10 12,6
```
is also allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the entry with the shortest number of bytes wins. If you have questions or my explanation is not clear, ask in the comments.
[Answer]
### GolfScript, 196 characters
```
' '/(~):H;,):W(\~/-1%'*':S*:^{:I,,{I=79>},:A{{[\1$1$+2/]}+A/}%{)I=43=\$.~I<>S&!\~+1&!&&},}:C~S^W/zip*C{{.H/\H%W*+}%}%+:B;^'P'?]]{{(B{0=1$=},\;\`{\1>\+}+/}%.{0=^=81=},:|!}do;|0=1>-1%{.W%','@W/' '}/
```
A horrible piece of GolfScript code - however it works as desired. The algorithm is not optimal but fairly fast, the example is running well below a second on my computer.
```
> 15,13 ----T---+-------------------------T---+---T-----------------T-+-T-+-T---------------------------------+------+----------+-------+-------------------------P---+-*-Q-----------------T-+-T-+-T------
4,5 2,8 0,4 2,0 4,5 8,10 12,6
```
] |
[Question]
[
I want to compactly code positive integers `x` into bits, in a manner allowing decoding back into the original integers for a stateless decoder knowing the maximum value `m` of each `x`; it shall be possible to uniquely decode the concatenation of encodings, as is the case in Huffman coding.
[The above introduction motivates the rest, but is not part of the formal definition]
Notation: for any non-negative integer `i`, let `n(i)` be the number of bits necessary to represent `i` in binary; that is the smallest non-negative integer `k` such that `i>>k == 0`
```
i : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ..
n(i): 0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 ..
```
I want a function `F(x,m)` defined for `0<x` and `x<=m`, with output a string of '`0`' or '`1`', having these properties:
1. `F(x,m)` has length less than `2*n(x)` or `2*n(m)-1`, whichever is smaller.
2. If `x<y` then:
* `F(x,m)` is no longer than `F(y,m)`;
* `F(x,m)` and `F(y,m)` differ at some position over the length of `F(x,m)`;
* there's a `0` in `F(x,m)` at the first such position.
3. When for a certain `m` properties 1 and 2 do not uniquely define `F(x,m)` for all positive `x` at most `m`, we reject any encoding giving a longer `F(x,m)` than some otherwise acceptable encoding, for the smallest `x` for which the length do not match.
Note: In the above, implicitly, `0<x`, `0<y`, `0<m`, `x<=m`, and `y<=m`, so that `F(x,m)` and `F(y,m)` are defined.
It is asked the shortest program that, given any `x` and `m` meeting the above constraints and up to 9 decimal digits, outputs an `F(x,m)` consistent with the above rules. The following C framework (or its equivalent in other languages) is not counted:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C(c) putchar((c)?'1':'0') // output '0' or '1'
#define S(s) fputs((s),stdout) // output a string
typedef unsigned long t; // at least 32 bits
void F(t x,t m); // prototype for F
int main(int argc,char *argv[]){
if(argc==3)F((t)atol(argv[1]),(t)atol(argv[2]));
return 0;}
void F(t x,t m) { // counting starts on next line
} // counting ends before this line
```
---
Comment: Property 1 aggressively bounds the encoded length; property 2 formalizes that unambiguous decoding is possible, and canonicalizes the encoding; I assert (without proof) this is enough to uniquely define the output of `F` when `m+1` is a power of two, and that property 3 is enough to uniquely define `F` for other `m`.
Here is a partial table (handmade; the first version posted was riddled with errors, sorry):
```
x : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
F(x,1) : empty
F(x,2) : 0 1
F(x,3) : 0 10 11
F(x,4) : 0 10 110 111
F(x,5) : 0 10 110 1110 1111
F(x,6) : 0 100 101 110 1110 1111
F(x,7) : 0 100 101 1100 1101 1110 1111
F(x,8) : 0 100 101 110 11100 11101 11110 11111
F(x,15) : 0 100 101 11000 11001 11010 11011 111000 111001 111010 111011 111100 111101 111110 111111
```
[Answer]
# Python, 171
```
def F(x,m):
a=0;b=[9]
while len(b)<m:
if 4**len(bin(len(b)))*2>64*a<4**len(bin(m)):
if(a&a+1)**a:b+=[a];a+=1
else:a*=2
else:a=b.pop()*2
return bin((b+[a])[x])[2:]
```
Note that lines that appear to begin with 4 spaces actually begin with a tab.
Testing, with bitpwner's test script:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
F(x,1) 0
F(x,2) 0 1
F(x,3) 0 10 11
F(x,4) 0 10 110 111
F(x,5) 0 10 110 1110 1111
F(x,6) 0 100 101 110 1110 1111
F(x,7) 0 100 101 1100 1101 1110 1111
F(x,8) 0 100 101 110 11100 11101 11110 11111
F(x,9) 0 100 101 110 11100 11101 11110 111110 111111
F(x,10) 0 100 101 1100 1101 11100 11101 11110 111110 111111
F(x,11) 0 100 101 1100 1101 11100 11101 111100 111101 111110 111111
F(x,12) 0 100 101 1100 11010 11011 11100 11101 111100 111101 111110 111111
F(x,13) 0 100 101 1100 11010 11011 11100 111010 111011 111100 111101 111110 111111
F(x,14) 0 100 101 11000 11001 11010 11011 11100 111010 111011 111100 111101 111110 111111
F(x,15) 0 100 101 11000 11001 11010 11011 111000 111001 111010 111011 111100 111101 111110 111111
```
Explanation:
This is all based on the observation that between two consecutive elements of the code, F(x,m) and F(x+1,m), we always add one to the binary number, then multiply by two some number of times. If these steps are followed, then it is a valid code. The rest simply tests to make sure it is short enough.
Golfs:
175 -> 171: changed 2\*\*(2\*... to 4\*\*
[Answer]
# Python 3, 163 bytes
```
n=int.bit_length
R=range
def F(x,m,c=0):
for i in R(x):L=2*n(m)-2;D=1<<L;r=n(D-c-sum(D>>min(2*n(x+1)-1,L)for x in R(i+1,m)))-1;v=c;c+=1<<r
return bin(v)[2:L+2-r]
```
Ignore the `c=0` parameter, that's a golf trick.
This greedily chooses the shortest possible representation for each number, subject to the condition that the remaining numbers are still representable. Therefore, by construction, it exactly satisfies the desired properties. It is actually not that hard to modify this code to support a different set of coding rules, as a result.
For example, here are the outputs up to `m=15`:
```
m\x | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
----+----------------------------------------------------------------------------------------------------------------------------
1 |
2 | 0 1
3 | 0 10 11
4 | 0 10 110 111
5 | 0 10 110 1110 1111
6 | 0 100 101 110 1110 1111
7 | 0 100 101 1100 1101 1110 1111
8 | 0 100 101 110 11100 11101 11110 11111
9 | 0 100 101 110 11100 11101 11110 111110 111111
10 | 0 100 101 1100 1101 11100 11101 11110 111110 111111
11 | 0 100 101 1100 1101 11100 11101 111100 111101 111110 111111
12 | 0 100 101 1100 11010 11011 11100 11101 111100 111101 111110 111111
13 | 0 100 101 1100 11010 11011 11100 111010 111011 111100 111101 111110 111111
14 | 0 100 101 11000 11001 11010 11011 11100 111010 111011 111100 111101 111110 111111
15 | 0 100 101 11000 11001 11010 11011 111000 111001 111010 111011 111100 111101 111110 111111
```
[Answer]
# Python - 370
Creates a huffman tree, balances it to fit the rules, then does a walk through the tree to get the final values.
```
def w(n,m,c,p=""):
try:[w(n[y],m,c,p+`y`)for y in 1,0]
except:c[n[0]]=p
d=lambda x:len(x)>1and 1+d(x[1])
v=lambda x,y:v(x[1],y-1)if y else x
def F(x,m):
r=[m];i=j=0
for y in range(1,m):r=[[m-y],r]
while d(r)>len(bin(m))*2-6-(m==8):g=v(r,i);g[1],g[1][0]=g[1][1],[g[1][0],g[1][1][0]];i,j=[[i+1+(d(g)%2<1&(1<i<5)&(m%7<1)),j],[j+1]*2][d(g)<5]
c={};w(r,m,c);return c[x]
```
For a more succinct solution that is based on the emergent pattern, look at isaacg's answer.
It's a good example of how a completely different approach can solve the problem.
Test:
```
chars = 8
maxM = 15
print " "*chars,
for m in range(1,maxM+1):
p = `m`
print p+" "*(chars-len(p)),
print
for m in range(1,maxM+1):
p = "F(x,"+`m`+")"
print p+" "*(chars-len(p)),
for x in range(1,maxM+1):
try:
q = `F(x,m)`[1:-1]
print q+" "*(chars-len(q)),
except:
print
break
```
Results:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
F(x,1)
F(x,2) 0 1
F(x,3) 0 10 11
F(x,4) 0 10 110 111
F(x,5) 0 10 110 1110 1111
F(x,6) 0 100 101 110 1110 1111
F(x,7) 0 100 101 1100 1101 1110 1111
F(x,8) 0 100 101 1100 1101 1110 11110 11111
F(x,9) 0 100 101 1100 1101 1110 11110 111110 111111
F(x,10) 0 100 101 1100 1101 11100 11101 11110 111110 111111
F(x,11) 0 100 101 1100 1101 11100 11101 111100 111101 111110 111111
F(x,12) 0 100 101 11000 11001 11010 11011 11100 11101 11110 111110 111111
F(x,13) 0 100 101 11000 11001 11010 11011 11100 11101 111100 111101 111110 111111
F(x,14) 0 100 101 11000 11001 11010 11011 11100 111010 111011 111100 111101 111110 111111
F(x,15) 0 100 101 11000 11001 11010 11011 111000 111001 111010 111011 111100 111101 111110 111111
```
] |
[Question]
[
The type 4 GUID is described by Wikipedia, quoth:
>
> Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).
>
>
>
Write a program that loads 488 bits (61 bytes) of cryptographic quality randomness and output them as 4 GUIDs using the format quoted above.
* Do not waste randomness.
+ All random bits must appear in the encoded output.
+ All encoded bits must be traceable to either a single random bit or one of the six fixed bits that must appear in each GUID.
* Use the cryptographic quality random number generator supplied by your language's standard library.
* Do not use a library or external resource that generates GUIDs.
* The hyphens must appear in their correct positions.
* The fixed bits of this form of GUID must appear in their correct positions.
* You may use a standard library function designed to output a GUID from 128 bits.
* Normal code-golf rules apply.
For example...
```
> gentype4
6FA53B63-E7EA-4461-81BE-9CD106A1AFF8
856970E9-377A-458E-96A7-43F587724573
E4F859AC-0004-4AA1-A3D2-AECB527D1D24
766811C5-0C44-4CC8-8C30-E3D6C7C6D00B
```
Update:
I asked for *four* GUIDs in order to allow a whole number of random bytes to be gathered without leaving any remainder. I also specified that none of the bits should be wasted in order to avoid the easy answer of getting 16 random bytes and dropping the 4 in. (No, shift the other bits along first.)
Update 2:
If your language's standard library doesn't have a cryptographic quality random byte generator, you may instead assume that there is a 61 byte file present with enough random bytes for you to use when the program starts. The file should be called "/dev/urandom" or another filename with 12 characters.
[Answer]
# PHP, 338 bytes
```
<?php $r=openssl_random_pseudo_bytes(61);$b="";$s="substr";for($i=0;$i<61;)$b.=str_pad(decbin(ord($r[$i++])),8,0,0);function p($B,$L){return str_pad(dechex(bindec($B)),$L,0,0);}for($i=0;$i<4;$i++)echo p($s($b,$p=122*$i,32),8)."-".p($s($b,$p+32,16),4)."-4".p($s($b,$p+48,12),3)."-".p("10".$s($b,$p+60,14),4)."-".p($s($b,$p+74,48),12)."\n";
```
## Some output
```
> php 32309.min.php
635fa088-4a66-47fc-9e50-2ccb2445b643
6e5c23c7-ba16-427e-960b-5316980ce4e3
fdb570ca-2e5e-4594-ab2e-db8446599b8f
203f2538-b5f4-47f0-89ac-012ca14b2f99
> php 32309.min.php
a6981255-0ab2-4d82-aab4-d1c64d2bb7eb
c348e728-f817-45d2-9bbf-b40426baa461
9b2baed2-e58b-41ef-a6fb-57e96db74a68
63e464e7-ab55-4e2a-a2a0-abdc535481dc
> php 32309.min.php
af7e68d3-b3ed-4e19-85b2-280270f746c6
0a86c610-8d0c-4c0a-bafe-44a6886d71f8
98c742b8-6a3b-47ff-97c7-ccab70d79a3c
59a93afc-ff81-4c97-a57b-72f0de384acb
> php 32309.min.php
72b352fc-0174-4051-969e-cacc0adbf941
50e4f859-76fe-45f6-baf5-d5fcceb41f72
5a18408e-6e7e-43a6-bd71-09d22a0fbf14
ae5a1391-5367-467e-8ecc-785ca72cbf95
```
## Ungolfed
```
<?php
$r = openssl_random_pseudo_bytes(61);
$b = "";
$s = "substr";
for($i=0 ; $i<61 ;) $b .= str_pad(decbin(ord($r[$i++])), 8, 0, 0);
function p($B, $L) {
return str_pad(dechex(bindec($B)), $L, 0, 0);
}
for($i=0 ; $i<4 ; $i++) {
echo p($s($b, 122*$i, 32), 8)."-";
echo p($s($b, 122*$i+32, 16), 4)."-4";
echo p($s($b, 122*$i+48, 12), 3)."-";
echo p("10".$s($b, 122*$i+60, 14), 4)."-";
echo p($s($b, 122*$i+74, 48), 12)."\n";
}
```
[Answer]
## J - 114 bytes
I took the simplest approach available. The function takes amount of GUID's required (you could replace the `]` near the end with `4:` to make it return 4 always) and outputs that many of them, separated by newlines.
Edit: I missed that no generated bits must go to waste... This answer doesn't comply and I don't know how to make it to.
```
f=:[:}.(,LF,(x@8:,'-',x@4:,'-4',x,'-',('89AB'{~?@4:),x,'-',(x=:'0123456789ABCDEF'{~?@$&16)@(12"_))@3:)^:(]`(''"_))
```
If an extra newline is allowed after the output, this could be written in **111 bytes**.
```
f=:(,LF,~(x@8:,'-',x@4:,'-4',x,'-',('89AB'{~?@4:),x,'-',(x=:'0123456789ABCDEF'{~?@$&16)@(12"_))@3:)^:(]`(''"_))
```
Example:
```
f 4
B23B10E3-6593-40F7-A5B0-D25A2763D781
3901709C-654E-4AF0-B23E-7252E859D35B
91E8D566-8E84-48CD-9B9D-EFC4E3F62C4E
F4578389-097C-4C38-A3C0-31EABFDCD630
f 5
AF234012-8A9F-47A3-9BF5-4B28AF580E9C
A3FE1785-8B40-44E9-8D69-CFF1BE06AC06
84A2CEB9-744F-4B86-B37F-747D0FD3F3FC
0FD8B7A6-9642-42C3-89ED-DB4A35D83CF8
4F860D9B-6E20-4AF8-B6BF-0F8CB307B9B0
```
[Answer]
# Golfscript, 75
Fixed now!
```
{{'0123456789ABCDEF'{.,rand>1<}:|~}:&8*'-':^&&&&^4&&&^'89AB'|&&&^{&}12*n}4*
```
### Output example:
```
>ruby golfscript.rb p.gs
140BC879-EAC4-4170-B349-A616523458DB
E26B34A4-8E86-4508-9EE5-3C76BF7456B6
89F9B995-CC9E-4EF0-AA25-70703B80AF82
5F6A513C-9E97-45A4-A9D1-E9D3DF71EF99
>ruby golfscript.rb p.gs
38D7A76B-BEEB-4C98-A148-D1EA8C31E85F
807373E4-5CFE-4953-9D5E-671205EE1E8F
8BD88B76-5890-4543-9787-2753AB15D24B
CD7DF25F-632B-4902-A46C-A1E10BE83EC5
```
You can test it yourself [here](http://golfscript.apphb.com/?c=e3snMDEyMzQ1Njc4OUFCQ0RFRid7LixyYW5kPjE8fTp8fn06JjgqJy0nOl4mJiYmXjQmJiZeJzg5QUInfCYmJl57Jn0xMipufTQq "To the golfscript cave!").
[Answer]
# Python, 287 bytes
```
from random import choice
s="0123456789abcdef"
def gen4():
for i in range(4):
m,n="",""
l = []
d = choice(s[8:12])
for k in range(30):
l.append(choice(s))
m="".join(l)
n=m[:12]+"4"+m[12:15]+d+m[15:]
print(n[:8]+"-"+n[8:12]+"-"+n[12:16]+"-"+n[16:20]+"-"+n[20:])
```
There's already a Python answer, but that just used .uuid, so here's one without it. Wish i could get it shorter though.
Still beat PHP :P
[Answer]
## Python (85)
```
import os,uuid
for i in [1]*4:print uuid.UUID(os.urandom(16).encode('hex'),version=4)
```
[os.urandom(n): Return a string of n random bytes suitable for cryptographic use.](https://docs.python.org/2/library/os.html#os.urandom)
I assume generating more than 488 bits is ok?
[Answer]
# Python 2 - 188 / 182
This should obey the requirements faithfully:
```
import os
a=(ord(x)>>i&3for i in(0,2,4,6)for x in os.urandom(61))
h=lambda n:eval('"%X"%(a.next()*4+a.next())+'*n+'"-"')
exec'print h(8)+h(4)+"4"+h(3)+"%X"%(8+a.next())+h(3)+h(12)[:-1];'*4
```
If python's UUID is acceptable for outputting a nicely-formatted uuid from a 32-digit hex string, then this version has 182 bytes:
```
import os,uuid
a=(ord(x)>>i&3for i in(0,2,4,6)for x in os.urandom(61))
exec('s='+'"%X"%(a.next()*4+a.next())+'*30+'"";print uuid.UUID(s[3:15]+"4"+s[:3]+"%X"%(8+a.next())+s[15:]);')*4
```
`a` is a generator comprehension that gives 2 bits at a time from an initial source of 61 random bytes.
Thanks TheRare for tips
[Answer]
# Common Lisp
## SBCL, 223
```
(define-alien-routine("arc4random_uniform"a)int(u
int))(labels((g(n)(a(expt 2 n)))(h()(g 16)))(dotimes(i 4)(format
t"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"(h)(h)(h)(+
16384(g 12))(+ 32768(g 14))(h)(h)(h))))
```
## CLISP, 299
```
(use-package :ffi)(def-call-out
a(:name"arc4random_uniform")(:arguments(u int))(:return-type
int)(:language :c)(:library :default))(labels((g(n)(a(expt 2
n)))(h()(g 16)))(dotimes(i 4)(format
t"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"(h)(h)(h)(+
16384(g 12))(+ 32768(g 14))(h)(h)(h))))
```
## About arc4random\_uniform(3)
Both of these call the C function [arc4random\_uniform(3)](http://www.openbsd.org/cgi-bin/man.cgi?query=arc4random_uniform&sektion=3&manpath=OpenBSD%20Current&arch=i386&format=html) in BSD libc. Some systems do not have this function.
Beware that my declaration of arc4random\_uniform(3) is **wrong**. The correct declaration is
```
u_int32_t arc4random_uniform(u_int32_t);
```
where `u_int32_t` is an old BSDism for an unsigned 32-bit integer. (The standard type in C99 is `uint32_t` without the first underscore.) My **wrong** declaration is
```
int arc4random_uniform(int);
```
where `int` is a signed 32-bit integer. (I know systems where `int` only has 16 bits, but I would not run Lisp there.) I am wrong to use signed for unsigned, but my program works because I only pass small non-negative integers. In code golf, `int` is shorter than `unsigned-int` in SBCL or `uint` in CLISP.
To use arc4random\_uniform(3) in Lisp, I define a Lisp function `a`. Here it is in SBCL:
```
; (use-package :sb-alien) ; SBCL does this by default!
(define-alien-routine ("arc4random_uniform" a)
int ; return type
(u int)) ; argument named u
```
And in CLISP:
```
(use-package :ffi)
(def-call-out a
(:name "arc4random_uniform")
(:arguments (u int))
(:return-type int)
(:language :c)
(:library :default))
```
CLISP has two languages, `:c` for traditional K&R C and `:stdc` for C89, but I find no difference, so I use the shorter name.
Now `(a u)` returns a random integer at least 0 and less than *u*. If *u* is 2*n*, then I get exactly *n* bits. For example, `(a (expt 2 14)` provides 14 bits. Because of my wrong declaration, *u* must be less than 231. If I want 32 bits, I may call `(a 16)` twice.
## Rest of program
```
; after defining A
(labels ((g (n) (a (expt 2 n)))
(h () (g 16)))
(dotimes (i 4)
(format t
"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"
(h) (h) (h) (+ 16384 (g 12)) (+ 32768 (g 14)) (h) (h) (h))))
```
I define two local functions. `(g n)` generates *n* random bits. `(expt 2 n)` is much shorter than a left shift: `1<<n` in C would become `(let((v 0))(setf(ldb(byte 1 n)v)1)v)` in Common Lisp!
`(h)` is an alias for `(g 16)`. This alias costs 13 characters: 11 in `(h()(g 16))`, plus 2 to upgrade `flet` to `labels`, because *h* needs *g* in scope. Each call to `(h)` saves 3 characters, and I have 6 calls, so I save 18 after I spend 13.
When formatting each GUID, `(+ 16384(g 12))` is shorter than `(logior #x4000 (g 12)` and `(+ 32768(g 14))` is shorter than `(logior #x8000 (g 14))`.
One can generate the long format string `"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"` (56 characters) with the expression `(format()"~{~A~}~~%"(mapcar(lambda(e)(if e(format()"~~4,'0X")'-))'(t t()t()t()t()t t t)))` (89 characters), but the literal string is shorter.
[Answer]
## Javascript (ES6) - ~~177~~ ~~163~~ 158
Removed `.toUpperCase()`, replaced `substring` with `substr` and `substr(0,3)` to `substr(1)`
```
function f(){g=()=>(((1+Math.random())*0x10000)|0).toString(16).substr(1);for(i=0;i<4;i++)alert((g()+g()+"-"+g()+"-4"+g().substr(1)+"-"+g()+"-"+g()+g()+g()))}
```
EcmaScript 5 version of the above script:
```
function f(){function g(){return (((1+Math.random())*0x10000)|0).toString(16).substr(1)}for(i=0;i<4;i++)alert((g()+g()+"-"+g()+"-4"+g().substr(1)+"-"+g()+"-"+g()+g()+g()))}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4F30F15ÝΩh}J•2,ÈĆ•13в£'-4и4DL7+hΩ‚.ιÁ.ιJ,
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fxM3YwM3Q9PDccyszar0eNSwy0jnccaQNyDA0vrDp0GJ1XZMLO0xcfMy1M86tfNQwS@/czsONQMJL5/9/AA)
**Explanation:**
```
4F # Loop 4 times:
30F # Inner loop 30 times:
15Ý # Push the list [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Ω # Pop and push a random integer from this list
h # Convert the integer to hexadecimal
}J # After the inner loop: join the characters on the stack together
•2,ÈĆ• # Push compressed integer 40106286
13в # Convert it to base-13 as list: [8,4,0,3,0,3,12]
£ # Split the string into parts of that size
# i.e. "FBA4C1C6FE22479659019DA439B7D6"
# → ["FBA4C1C6","FE22","","479","","659","019DA439B7D6"]
'-4и '# Push a list of 4 "-"s: ["-","-","-","-"]
4 # Push a 4
DL # Duplicate it to create the list [1,2,3,4]
7+ # Add 7 to each: [8,9,10,11]
h # Convert each to hexadecimal: [8,9,"A","B"]
Ω # Pop and push a random value from this list
# i.e. "B"
‚ # Pair it together with the 4
.ι # Interleave it with the list of "-": ["-",4,"-","B","-","-"]
Á # Rotate it once towards the right: ["-","-",4,"-","B","-"]
.ι # Interleave it with the earlier created list
# → ["FBA4C1C6","-","FE22","-","",4,"479","-","","B","659","-","019DA439B7D6"]
J # Join this list together to a string
# → "FBA4C1C6-FE22-4479-B659-019DA439B7D6"
, # And output it with trailing newline
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•2,ÈĆ•` is `40106286` and `•2,ÈĆ•13в` is `[8,4,0,3,0,3,12]`.
Without the requirement that no random bits must go to waste, this could have been **36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**, by utilizing the builtin `ǝ` (based on [my answer here](https://codegolf.stackexchange.com/a/177721/52210)):
```
4FŽΣÌvy4*F15ÝΩh}'-}J¨4DL7+hΩ‚Ž5Ā2äǝ,
```
[Try it online.](https://tio.run/##ATsAxP9vc2FiaWX//zRGxb3Oo8OMdnk0KkYxNcOdzqlofSctfUrCqDRETDcraM6p4oCaxb01xIAyw6THnSz//w)
[Answer]
# [Coconut](http://coconut-lang.org/) 1.4.1, 114 bytes
```
from random import*
for C in[->f'{randrange(16**_):0{_}x}']*4:print(C 8,C 4,'4'+C 3,choice'89ab'+C 3,C 12,sep='-')
```
[Try it online!](https://tio.run/##S85Pzs8rLfn/P60oP1ehKDEvBUhl5hbkF5VocaXlFyk4K2TmRevapalXgySBOD1Vw9BMSyte08qgOr62olY9VsvEqqAoM69Ew1nBQsdZwURH3URd21nBWCc5Iz8zOVXdwjIxCSLgrGBopFOcWmCrrquu@f8/AA "Coconut – Try It Online")
This works on the old version on TIO, for newer versions you might need parentheses around `'89ab'`.
] |
[Question]
[
(Better known as [3D Tic Tac Toe](http://en.m.wikipedia.org/wiki/3-D_Tic-Tac-Toe); I just made up a name that sounded catchy ;-[) )](http://xkcd.com/541/)
Let two people play this game against each other.
Specifications:
* Output
+ the easiest way of explaining this will be with an example:
```
+-+-+-+-+
|X| | | |
+-+-+-+-+
| |O| | |
+-+-+-+-+
| | | | |
+-+-+-+-+
|O| | | |
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| |X| | |
+-+-+-+-+
| | | |O|
+-+-+-+-+
| | | | |
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| |O| | |
+-+-+-+-+
|O| |X| |
+-+-+-+-+
| | | |X|
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | |X|
+-+-+-+-+
```
in this case X has won (top left corner of layer #1 to bottom right corner of layer #2)
+ it is also okay to display the four layers horizontally, with one space between them
+ grids may be non-text; in this case you must represent a third dimension in a reasonable way; see also scoring section below
+ after each player's turn, output "{player} wins" if a player wins, "tie" if the board fills up and nobody has won, or the board if the game is not over yet (or notifiy the user of a win/tie in a reasonable way)
* Input
+ xyz coordinates, 0-based
+ example: input `031` is this location:
```
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
|X| | | |
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
```
+ alternate between X and O, starting with X, and prompt the user with the text "{player}'s turn: "
* Winning condition
+ a player wins if the player gets 4 of their symbol (X or O) in a row, horizontally, vertically, or diagonally. For example, these are all wins (in the input format I have specified) if a player has played any of them:
+ 000, 001, 002, 003
+ 120, 130, 100, 110
+ 000, 110, 220, 330
+ 300, 122, 033, 211
* Scoring
+ `[ws]` 10 base points for a working solution
+ `[gr]` +20 points if you have a graphical (meaning non-text) grid
- `[cc]` +30 points if you can click on a cell to go there
+ `[cp]` +20 points for building a computer player to play against
- `[ai]` +10 to 100 points for how good the AI is (judged by me)
- `[ot]` +15 points if you can choose between one and two player
+ `[ex]` +3 points for each interesting or confusing thing in your code that you explain in your answer (**interesting**, so don't say "n++ adds one to n" and expect to get 3 points. just be reasonable.)
- for example, you could say "I used `[a,b,c].map(max).sum%10` because it takes the foos and converts them into a bar, because {{insert explanation here}}, which I use to frob the baz."
- if you golf part of or all of your code, you will of course find many more interesting things to explain, but golfing is not required.
+ `[wl]` +10 points for showing the winning line, for example "000 001 002 003," or highlighting the squares in some way (if you're using a GUI)
+ +5 points for every upvote (this is the [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") part)
+ downvotes don't count
+ include your score in the answer by using the IDs I have placed for the bonuses
- example: 10 [ws] + 20 [gr] + 20 [cp] = 50
- don't include upvotes since those change often; I will count those myself
+ I will accept the highest scored answer in one week; if a higher scored answer appears I will accept it
+ if two answers tie, the earlier posted answer will win
[Answer]
## HTML/CSS/JS+JQuery
10[ws] + 20[gr] + 30[cc] + 20[cp] + ?[ai] + 15[ot] + 10[wl] + ?[ex] = 105+
Finished the AI, though a really crappy one.
>
> "Is there any way to make it play itself?"
>
> "Yes. Number of players: zero."
>
>
>
For those who don't get the reference: <http://www.youtube.com/watch?v=NHWjlCaIrQo>
\* sign\* It's much less cool of a reference now that I have explained it...
[JSFiddle](http://jsfiddle.net/TwiNight/afX2e/)
---
**AI**
The AI logic goes like this:
1. If there is a winning move for me, take it.
2. If there is a winning move for opponent, block it.
3. Take the "best" unoccupied corner.
4. Take a random unoccupied space.
---
HTML
```
<span>X</span>'s turn
<div>
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
</div>
```
JS
```
var currentPlayer = true, end = false, players = parseInt(prompt('Number of players":'));
function cell(x,y,z){return $('td').eq(x*16+y*4+z);}
function f(i,x){switch(x){case -1: return i; case -2: return 3-i; default: return x;}}
function line(x,y,z){
var t = $();
for(var i=0; i<4; i++) t = t.add(cell(f(i,x),f(i,y),f(i,z)));
return t;
}
function check(x,y,z,t){
var u = line(x,y,z);
if(u.map(function(){return $(this).text()==t;}).get().reduce(function(a,b){return a&&b;})) u.css({color: 'red'});
else return false;
return end = true;
}
function move(x,y,z){
if(end) return false;
var t = currentPlayer?'X':'O';
cell(x,y,z).text(t);
if(check(-1,y,z,t)) return true;
if(check(x,-1,z,t)) return true;
if(check(x,y,-1,t)) return true;
if(check(x,-1,-1,t)) return true;
if(check(x,-1,-2,t)) return true;
if(check(-1,y,-1,t)) return true;
if(check(-1,y,-2,t)) return true;
if(check(-1,-1,z,t)) return true;
if(check(-1,-2,z,t)) return true;
if(check(-1,-1,-1,t)) return true;
if(check(-2,-1,-1,t)) return true;
if(check(-1,-2,-1,t)) return true;
if(check(-1,-1,-2,t)) return true;
currentPlayer = !currentPlayer;
$('span').text(currentPlayer?'X':'O');
if(players==2||players==1&¤tPlayer) return false;
else return ai();
}
function ai_tri(x1,y1,z1,x2,y2,z2,t){
var u = false;
for(var i=0;i<4;i++) for(var j=0;j<4;j++)
if(x1==x2){
if(cell(x1,i,j).text()==t)
if(i==y2&&(j==1||j==2) || j==z2&&(i==1||i==2))
if(u) return false;
else u = true;
else return false;
}else if(y1==y2){
if(cell(i,y2,j).text()==t)
if(i==x2&&(j==1||j==2) || j==z2&&(i==1||i==2))
if(u) return false;
else u = true;
else return false;
}else{
if(cell(i,j,z1).text()==t)
if(i==x2&&(j==1||j==2) || j==y2&&(i==1||i==2))
if(u) return false;
else u = true;
else return false;
}
return true;
}
function ai_tri2(x1,y1,z1,x2,y2,z2,t){
var u = false;
for(var i=0;i<4;i++) for(var j=0;j<4;j++)
if(x1!=x2){
if(cell(i,j,j).text()==t)
if(j==y2&&(i==1||i==2) || i==x2&&(j==1||j==2))
if(u) return false;
else u = true;
else return false;
}else if(y1!=y2){
if(cell(j,i,j).text()==t)
if(i==z2&&(j==1||j==2) || j==y2&&(i==1||i==2))
if(u) return false;
else u = true;
else return false;
}else{
if(cell(j,j,i).text()==t)
if(i==x2&&(j==1||j==2) || j==z2&&(i==1||i==2))
if(u) return false;
else u = true;
else return false;
}
return true;
}
function ai_cn(x,y,z,t){
return ai_tri(x,y,z,x,!y*3,!z*3,t) + ai_tri(x,y,z,!x*3,y,!z*3,t) + ai_tri(x,y,z,!x*3,!y*3,z,t) + ai_tri2(x,y,z,!x*3,y,z,t) + ai_tri2(x,y,z,x,!y*3,z,t) + ai_tri2(x,y,z,x,y,!z*3,t) + ai_tri(!x*3,y,z,x,!y*3,z,t) + ai_tri(!x*3,y,z,x,y,!z*3,t) + ai_tri(x,!y*3,z,!x*3,y,z,t) + ai_tri(x,!y*3,z,x,y,!z*3,t) + ai_tri(x,y,!z*3,!x*3,y,z,t) + ai_tri(x,y,!z*3,x,!y*3,z,t) + ai_tri2(x,!y*3,!z*3,!x*3,!y*3,!z*3,t) + ai_tri2(!x*3,y,!z*3,!x*3,!y*3,!z*3,t) + ai_tri2(!x*3,!y*3,z,!x*3,!y*3,!z*3,t);
}
function ai_check(x,y,z,t){
var v = [$(),$(),$()], u = line(x,y,z);
$.each(u.map(function(){return $(this).text();}).get(),function(i,e){if(e=='X') v[0]=v[0].add(u.eq(i)); else if(e=='O') v[1]=v[1].add(u.eq(i)); else v[2]=v[2].add(u.eq(i));});
if((t==='X'?v[0]:v[1]).length==3 && v[2].length==1) return [true,v[2]];
else if((t==='X'?v[1]:v[0]).length==3 && v[2].length==1) return [false,v[2]];
else return null;
}
function ai_check_all(t){
var u = null, v = null;
for(var i=0;i<4;i++){
for(var j=0;j<4;j++){
if((u=ai_check(i,j,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(i,-1,j,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,i,j,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
}
if((u=ai_check(i,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(i,-1,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,i,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,i,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,-1,i,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,-2,i,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
}
if((u=ai_check(-1,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,-1,-2,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-1,-2,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
if((u=ai_check(-2,-1,-1,t))!==null) if(u[0] || v!==null) return u[1]; else v = u[1];
return v;
}
function ai(){
var t1 = currentPlayer?'X':'O', t2 = currentPlayer?'O':'X', u = [0,0,0,0], v = 0, w = ai_check_all();
if(w!==null) return move(w.closest('table').index(),w.closest('tr').index(),w.index());
for(var i=0;i<4;i+=3) for(var j=0;j<4;j+=3) for(var k=0;k<4;k+=3)
if(cell(i,j,k).text()==='' && (v=ai_cn(i,j,k,t2))>u[3]) u = [i,j,k,v];
if(u[3]>0) return move(u[0],u[1],u[2]);
u = $('td').filter(function(){return $(this).text()=='';});
if(u.length===0) return end = true;
w = u.eq(Math.floor(Math.random()*u.length));
return move(w.closest('table').index(),w.closest('tr').index(),w.index());
}
$('table').on('click','td',function(){
if(end || $(this).text() !== '') return true;
move($(this).closest('table').index(),$(this).closest('tr').index(),$(this).index());
});
if(players == 0) ai();
```
CSS
```
body{font-family: Arial, san-serif;}
table{float:left; margin-right: 20px; border-collapse: collapse;}
td{width:20px; height:20px; border:1px solid black; text-align: center;}
```
[Answer]
# Java
10[ws] + 20[gr] + 30[cc] + 4\*3[ex] = 72
```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
public class Game {
public static void main(String[] args) {
//Initial threads
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Game();
}
});
}
JFrame frame;
Grid grid;
Game() {
grid = new Grid();
frame = new JFrame("Tic Tac Tae Toe");
frame.add(grid);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Grid extends JPanel implements MouseInputListener {
static final int BEGIN_X = 50, BEGIN_Y = 50;
static final int GAP = 50;
static final int TILE_WIDTH = 40;
XO[][][] grid;
int lastX, lastY, lastZ;
int mouse_x, mouse_y;
JLabel turn;
boolean won;
public Grid() {
// Just because. I felt like copy-paste.
grid = new XO[][][]{
{
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N}
},
{
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N}
},
{
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N}
},
{
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N},
{XO.N, XO.N, XO.N, XO.N}
}
};
lastX = -1;
lastY = -1;
lastZ = -1;
won = false;
turn = new JLabel("X");
add(turn);
this.setPreferredSize(new Dimension(2 * BEGIN_X + 4 * TILE_WIDTH,
2 * BEGIN_Y + 4 * (4 * TILE_WIDTH + GAP) - GAP));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public XO determineWinner() {
XO type = grid[lastZ][lastY][lastX];
//start on same z-plane
for (int x = 0; x < 4; x++) {
if (grid[lastZ][lastY][x] != type) {
break;
}
if (x == 3) {
return type; //type won!
}
}
for (int y = 0; y < 4; y++) {
if (grid[lastZ][y][lastX] != type) {
break;
}
if (y == 3) {
return type; //type won!
}
}
//first diagonal
if (lastX == lastY) {
for (int x = 0, y = 0; x < 4; x++, y++) {
if (grid[lastZ][y][x] != type) {
break;
}
if (x == 3) {
return type; //type won!
}
}
} //second diagonal
else if (lastX == 3 - lastY) {
for (int x = 0, y = 3; x < 4; x++, y--) {
if (grid[lastZ][y][x] != type) {
break;
}
if (x == 3) {
return type; //type won!
}
}
}
//first plane finished
//now onto changing z's
//vertical column
for (int z = 0; z < 4; z++) {
if (grid[z][lastY][lastX] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
//descending y. note: descending means stair-like (diagonal)
if (lastZ == lastY) {
for (int z = 0, y = 0; z < 4; z++, y++) {
if (grid[z][y][lastX] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
} //ascending y
else if (lastZ == 3 - lastY) {
for (int z = 0, y = 3; z < 4; z++, y--) {
if (grid[z][y][lastX] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
} //ascending x. note: ascending means stair-like, but other way
if (lastZ == 3 - lastX) {
for (int z = 0, x = 3; z < 4; z++, x--) {
if (grid[z][lastY][x] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
} //descending x
else if (lastZ == lastX) {
for (int z = 0, x = 0; z < 4; z++, x++) {
if (grid[z][lastY][x] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
}
//diagonals, changing all three
if (lastZ == lastX && lastZ == lastY) {
for (int z = 0, x = 0, y = 0; z < 4; z++, x++, y++) {
if (grid[z][y][x] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
} else if (3 - lastZ == lastX && 3 - lastZ == lastY) {
for (int z = 3, x = 0, y = 0; z < 4; z--, x++, y++) {
if (grid[z][y][x] != type) {
break;
}
if (x == 3) {
return type; //type won!
}
}
} else if (lastZ == lastX && lastZ == 3 - lastY) {
for (int z = 0, x = 0, y = 3; z < 4; z++, x++, y--) {
if (grid[z][y][x] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
} else if (lastZ == 3 - lastX && lastZ == lastY) {
for (int z = 0, x = 3, y = 0; z < 4; z++, x--, y++) {
if (grid[z][y][x] != type) {
break;
}
if (z == 3) {
return type; //type won!
}
}
}
//check for tie
out: for (int z = 0; z < 4; z++){
for (int y = 0; y < 4; y++){
for (int x = 0; x < 4;x++){
if (grid[z][y][x] == XO.N){
break out;
}
}
}
if (z == 3){
return XO.N;
}
}
return null;
}
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.setColor(Color.BLACK);
//Looks a little nicer, but this could be left out.
g.setFont(new Font("Courier New", Font.BOLD, 20));
//paint grid rectangles.
for (int z = 0; z < 4; z++) {
int begin_y = BEGIN_Y + z * (4 * TILE_WIDTH + GAP);
//draw left line
g.drawLine(BEGIN_X, begin_y,
BEGIN_X, begin_y + 4 * TILE_WIDTH);
//draw bottom line
g.drawLine(BEGIN_X, begin_y + 4 * TILE_WIDTH,
BEGIN_X + 4 * TILE_WIDTH, begin_y + 4 * TILE_WIDTH);
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
//draw individual grid lines
g.drawLine(BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + y * TILE_WIDTH,
BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + (y + 1) * TILE_WIDTH);
g.drawLine(BEGIN_X + x * TILE_WIDTH, begin_y + y * TILE_WIDTH,
BEGIN_X + (x + 1) * TILE_WIDTH, begin_y + y * TILE_WIDTH);
//if this was the last chosen square...
if (lastX == x && lastY == y && lastZ == z) {
g.setColor(Color.ORANGE);
//fill it orange! (not required, but I think it looks nice)
g.fillRect(BEGIN_X + x * TILE_WIDTH + 1,
begin_y + y * TILE_WIDTH + 1,
TILE_WIDTH - 1, TILE_WIDTH - 1);
g.setColor(Color.BLACK);
}
//if mouse is over this square...
if ((BEGIN_X + x * TILE_WIDTH) < mouse_x
&& (BEGIN_X + (x + 1) * TILE_WIDTH) > mouse_x
&& (begin_y + y * TILE_WIDTH) < mouse_y
&& (begin_y + (y + 1) * TILE_WIDTH) > mouse_y) {
g.setColor(new Color(100, 100, 255));
//fill it blue! (not required, but I think it looks nice)
g.fillRect(BEGIN_X + x * TILE_WIDTH + 1,
begin_y + y * TILE_WIDTH + 1,
TILE_WIDTH - 1, TILE_WIDTH - 1);
g.setColor(Color.BLACK);
}
//paint value of tile
g.drawString(grid[z][y][x].val,
BEGIN_X + x * TILE_WIDTH + TILE_WIDTH / 2,
begin_y + y * TILE_WIDTH + TILE_WIDTH / 2);
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (!won) {
int x = e.getX(), y = e.getY();
x -= BEGIN_X;
x /= TILE_WIDTH;
y -= BEGIN_Y;
int z = 0;
while (y > 4 * TILE_WIDTH) {
z++;
y -= 4 * TILE_WIDTH + GAP;
}
y /= TILE_WIDTH;
//**********************************
//DOES NOT ALWAYS GET PAST HERE!
//**********************************
if (x < 0 || y < 0 || z < 0 || x >= 4 || y >= 4 || z >= 4) {
return;
}
if (grid[z][y][x] == XO.N) {
grid[z][y][x] = XO.valueOf(turn.getText());
} else {
return;
}
lastX = x;
lastY = y;
lastZ = z;
XO who_won = determineWinner();
if (who_won == null){
if (turn.getText().equals("X")) {
turn.setText("O");
} else {
turn.setText("X");
}
}
else if (who_won != XO.N) {
turn.setText(who_won.toString() + " wins");
} else{
turn.setText("tie");
}
repaint();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
mouse_x = e.getX();
mouse_y = e.getY();
repaint();
}
}
enum XO {
X("X"), O("O"), N(" ");
String val;
XO(String c) {
val = c;
}
}
```
This is a working solution, but I will work on it a lot more.
[ex]:
* runs using [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)
* informs player's whose turn it is (letter at top of window, will be improved) using a `JLabel` called `turn`. This label is also used to say who won.
* shows the last move by storing the last x, y and z values and painting the corresponding square orange during `paintComponent()`
* shows the location of the mouse pointer (blue square) by computing it during `paintComponent()`
---
Screenshot:

[Answer]
## Ti-Basic 84
10[ws]+20[gr]+20[cp]+10[ai]+15[ot]+3[ex]=**78**
Programmable and playable from a Ti-84 calculator. +100?
Also, `->` represents the `STO->` button.
```
:Disp LOOKS-LIKE-THIS-MIGHT-BE-SOMETHING-INTERESTING-IN-THE-CODE
:ClrHome
:Disp "TIC TAC TAE TOE"
:Disp "HOW MANY PLAYERS"
:Input P
:If P=1 :Disp "YOUR OPPONENTS NAME IS AI BOB"
:If P=2 :Disp "YOUR OPPONENTS NAME IS AI BOB EVEN THOUGH YOU WANT TO PLAY TWO PLAYERS"
:Horizontal -10
:Horizontal -5
:Horizontal 0
:Horizontal 5
:Horizontal 10
:Vertical -10
:Vertical -5
:Vertical 0
:Vertical 5
:Vertical 10
:0->A
:Lbl M
:Disp "YOUR MOVE X-POS"
:Input X
:Disp "YOUR MOVE Y-POS"
:Input Y
:Circle(2,X,Y)
:Circle(2,rand,rand)
:Disp "UGH, HE DIDNT ALIGN IT CORRECTLY"
:Disp "YOU MIGHT WANT TO STOP PLAYING"
:If A=>4 :Goto W
:If A<4 :A+1->A
:Goto M
:Lbl W
:Disp "HAVE YOU WON, 1 IS YES, 0 IS NO"
:Input W
:If W=1 :Goto E
:Goto M
:Lbl E
:Disp "YOU HAVE WON! GOOD JOB!"
:Disp "ENTER TO EXIT"
:Pause
```
Something interesting: the line of code at the beginning (`:Disp LOOKS-LIKE-THIS-MIGHT-BE-SOMETHING-INTERESTING-IN-THE-CODE`) prints 0 and then is immediately cleared from the screen.
Feel free to give me more points for my AI's skill, but I'm pretty sure you'll stick with 10.
] |
[Question]
[
An [illegal prime](https://en.wikipedia.org/wiki/Illegal_prime) is a prime number which encodes information that is illegal to possess - specifically, in one case, a gzip file of the [source code of DeCSS](https://en.wikipedia.org/wiki/File%3aDeCSS.PNG), a piece of software to decrypt copy-protected DVDs.
Your task has two phases:
1. Build a source file that implements DeCSS in as few bytes as possible. This can be done in any language.
2. Compress this source file (using your favourite compression algorithm), and iterate through possible files that decompress to the same thing (using [Dirichlet's theorem](https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions) if it helps) until primality is reached.
As actually proving primality may take way too much computing power, it will be enough for the second part to pass a "[probable prime](https://en.wikipedia.org/wiki/Probable_prime)" test (e.g. [Miller-Rabin](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)) to a probability of less than 2-100.
The person with the smallest probable prime wins.
[Answer]
## Java (about 2048 bits)
```
14951059135011030015480908520726485619103063818476057564660360628799292628035097139943806440612109515246411930476451010075357954683100898936593739762786721583164361680031433048702186473094092210118641364347032899100220949873928633438856732508590863996147513646363328498023218161000104939462296626885931085914071985322044175133733909287366858309877885352980365735019082872958155754848273583139151810812417879417661663044291630490856568568829579704849173609110647303708828534149066778229242936297219753177569833591637704406031011600073082097633261877649625598598670707453831253888534424016277678136396605413799234576729
```
The code is
```
void C(int[]s,int[]k){int a=k[0]^s[84]|256,b=k[1]^s[85],c=k[2]^k[3]<<8^k[4]<<16^s[86]^s[87]<<8^s[88]<<16,d=c&7,e=0,f,i=127;for(c=c*2+8-d;++i<2048;e>>=8){e+=S[f=(c>>17^c>>14^c>>13^c>>5)&255]+T[d=Q[b]^R[a]];b=a/2;a=a&1<<8^d;c=c<<8|f;s[i]=P[s[i]]^e&255;}}//!Y
```
I took the liberty of renaming the lookup tables from `CSSt1` ... `CSSt5` to `P` ... `T`, and the method from `CSSDescramble` to `C`. I also ditched the gzip step, because it was giving a larger file than the source.
] |
[Question]
[
This is a challenge that was originally a tas for the German *Bundeswettbewerb Informatik* (federal competition of computer science [?]), a competition for highschool students. As opposed to the original question, where you have to find a good solution and write some documentation, I want you to golf this. I try to replicate the question as good as possible:
## Challenge
Many towns in Europe have so-called [twin towns](http://en.wikipedia.org/wiki/Twin_towns_and_sister_cities). This year, there is a special Jubilee where each pair of twin-towns in the EU organizes a festival to celebrate their partnership. To ensure that no city has to organize too many festivals, each city has a limit of festivals it can organize. Is it possible to distribute the festivals among the twin-towns in a way, such that each pair of twin-towns organizes one festival in one the two towns and no town organizes more festivals than it is allowed to? If yes, explain how.
This is a map of some towns, their partnerships and their limits of festivals.

## Requirements
* Your program must terminate the problem in one minute each for both testcases. (See below)
* Refer to the testcases for the input format.
* The output should be empty iff no solution exists and should have the following format otherwise: One line for each pair of twin towns, `a` if `city1` organizes the festival, `b` otherwise.
```
<city1>, <city2>, <a/b>
```
* The solution with the least number of characters that satisfies the requirements wins. In case of a tie, the program that was submitted first wins.
* Usual code-golf rules apply.
## Testcases
The original task had two testcases. I have uploaded them on [github](https://github.com/fuzxxl/BWInf2011/tree/master/Aufgabe5/data).
[Answer]
## Python, 380 chars
```
import sys
N={};H={};X={}
for L in open(sys.argv[1]):n,x,y=L.split('"');N[x]=int(n);H[x]=0;X[x]=[]
for L in open(sys.argv[2]):s,t=eval(L);X[s]+=[t]
p=1
while p:
p=0
for x in N:
if len(X[x])>N[x]:
p=1;S=[y for y in X[x]if H[y]<H[x]]
if S:X[x].remove(S[0]);X[S[0]]+=[x]
else:H[x]+=1
if H[x]>2*len(N):sys.exit(0)
for x in N:
for y in X[x]:print'"%s", "%s", a'%(x,y)
```
This code uses a [push-relabel](http://en.wikipedia.org/wiki/Push-relabel_maximum_flow_algorithm)-style maximum flow algorithm. `N[x]` is the number of parties allowed at `x`, `X[x]` is the list of partner cities currently scheduled to host at `x` (which may be longer than `N[x]` during the algorithm), and `H[x]` is the labelled height of `x`. For any oversubscribed city, we either push one of its scheduled parties to a lower partner city, or raise its height.
[Answer]
## C#, 1016 992 916 chars
Takes 4 seconds for me on the large test set; performance can easily be improved a lot by making `X` a `HashSet<s>` rather than a `List<s>`.
```
using System;using System.Collections.Generic;using System.IO;using System.Linq;using
s=System.String;class D<T>:Dictionary<s,T>{}class E:D<int>{static void Main(s[]x){s
S="",T=">",l;s[]b;D<E>R=new D<E>(),P=new D<E>();R[S]=new E();R[T]=new E();foreach(s L in
File.ReadAllLines(x[0])){b=L.Split('"');s f=b[1];R[T][f]=0;R[f]=new E();P[f]=new
E();R[f][T]=int.Parse(b[0].Trim());}foreach(s L in File.ReadAllLines(x[1])){b=L.Split('"');s
f=b[1],t=b[3],v=f+t;R[v]=new
E();R[v][S]=R[f][v]=R[t][v]=0;P[f][t]=R[S][v]=R[v][f]=R[v][t]=1;}for(;;){List<s>X=new
s[]{S}.ToList(),A=X.ToList();w:while((l=A.Last())!=T){foreach(s t in
R[l].Keys){if(!X.Contains(t)&R[l][t]>0){X.Add(t);A.Add(t);goto
w;}}A.RemoveAt(A.Count-1);if(!A.Any())goto q;}l=S;foreach(s n in
A.Skip(1)){R[l][n]--;R[n][l]++;l=n;}}q:if(R[S].Values.Contains(1))return;foreach(s
f in P.Keys)foreach(s t in P[f].Keys)Console.WriteLine(f+", "+t+", "+"ba"[R[f][f+t]]);}}
```
This uses the reduction to max flow which I hinted at earlier in comments. The vertices are
1. A newly generated source `S` and sink `T`.
2. The partnerships.
3. The cities.
The edges are
1. From the source to each partnership with flow capacity 1.
2. From each partnership to each city in the partnership with flow capacity 1.
3. From each city to the sink with flow capacity equal to that city's budget.
The algorithm is Ford-Fulkerson with DFS. It is obvious a priori that each augmenting path will increase the flow by 1, so the golfing optimisation of removing the computation of the path's flow has no negative effect on performance.
There are other possible optimisations by making assumptions such as "The names of the input files will never be the same as the names of the cities", but that's a bit iffy IMO.
] |
[Question]
[
You are given *n* (200 ≤ *n* < 250) as a command line argument. Print 10 prime numbers with *n* digits. Your program should run under 1s and must be shorter than 5000 bytes (excluding).
Sum the digits of all your 500 primes. Program with the largest sum wins.
An example (more [here](http://primes.utm.edu/lists/small/small2.html)):
```
$ ./find_large_primes 200
58021664585639791181184025950440248398226136069516938232493687505822471836536824298822733710342250697739996825938232641940670857624514103125986134050997697160127301547995788468137887651823707102007839
29072553456409183479268752003825253455672839222789445223234915115682921921621182714164684048719891059149763352939888629001652768286998932224000980861127751097886364432307005283784155195197202827350411
41184172451867371867686906412307989908388177848827102865167949679167771021417488428983978626721272105583120243720400358313998904049755363682307706550788498535402989510396285940007396534556364659633739
54661163828798316406139641599131347203445399912295442826728168170210404446004717881354193865401223990331513412680314853190460368937597393179445867548835085746203514200061810259071519181681661892618329
71611195866368241734230315014260885890178941731009368469658803702463720956633120935294831101757574996161931982864195542669330457046568876289241536680683601749507786059442920003278263334056542642264651
28591045597720075832628274729885724490653298360003309382769144463123258670807750560985604954275365591715208615509779345682419533206637382048824349415329839450792353652240682445321955199147316594996133
49790921912819110019003521637763748399072771256062128988437189616228355821145834783451215869998723492323628198577054239101181556609916127864608488018093426129641387774385490891035446702272744866010729
15474811206486587193258690501682404626361341756658894201908294153626080782693777003022566996735796983239343580281979005677758015801189957392350213806122307985157041153484138150252828152419133170303749
12654646219963267405298825104551142450213038420566798208417393291567314379831789259173233506811083774527183953999862675239292185131178671317061020444490733287588383918793095608410078925861028249824377
40992408416096028179761232532587525402909285099086220133403920525409552083528606215439915948260875718893797824735118621138192569490840098061133066650255608065609253901288801302035441884878187944219033
```
You can use [this](http://www.alpertron.com.ar/ECM.HTM) program to test for primality.
**EDIT**:
Use the following program to compute your score:
```
#!/usr/bin/python
# Usage: ./v.py ./find_large_primes
import subprocess
import sys
sum_ = 0
for n in xrange(200, 250):
p = subprocess.Popen(
args=[sys.argv[1], str(n)],
stdout=subprocess.PIPE)
p.wait()
sum_ += sum(int(e) for e in p.stdout.read() if e.isdigit())
p.stdout.close()
print sum_
```
[Answer]
## C++ with GMP
```
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(int argc, char *argv[]) {
int d = atoi(argv[1]);
int i = 0;
mpz_t n;
mpz_init(n);
mpz_ui_pow_ui(n, 10, d);
mpz_sub_ui(n, n, 1);
while (i < 10) {
if (mpz_probab_prime_p(n, 100)) {
printf("%s\n", mpz_get_str(NULL, 10, n));
i += 1;
}
mpz_sub_ui(n, n, 2);
}
}
```
It runs in just under a second on my machine. I'm too lazy to run it 50 times and sum up the digits, but it should be pretty good, as most of the digits (all but the last 4 of each number) are 9s.
```
> ./a.out 250
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999967
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999323
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999017
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998731
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997471
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996959
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995077
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999993529
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999993511
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999992459
```
[Answer]
# Perl
```
use Math::Prime::Util ":all";
my $n = "1"."0"x shift;
print $n=prev_prime($n),"\n" for 1..10;
```
score 1002616, On 4770K, takes about 0.1s for an argument between 200 and 250; under 4 seconds for the score program. Time for a given run stays under 1s until 455 digits. Note that the [Math::Prime::Util](https://metacpan.org/pod/Math::Prime::Util) and [Math::Prime::Util::GMP](https://metacpan.org/pod/Math::Prime::Util::GMP) modules should be installed.
`prev_prime` uses ES BPSW as the primality test, so a little more stringent than Pari's `precprime`.
] |
[Question]
[
Write the shortest program you can in any language that reads a context-free grammar from and the number of sentences to produce from `stdin`, and generates that many random sentences from the grammar.
**Input**
Input will come in the following format:
```
n <START>
{"<A>":["as<A>df","0<A>","<B><C>","A<A>", ...], "<B>":["1<C>1","\<<T>>",...], ...}
```
`n` is the number of sentences to generate. `<START>` is identifier of the starting nonterminal symbol.
The grammar is enclosed in the {} and is formatted as follows:
* Rules are of the form `"<S>":[productions]`. `<S>` is the identifier of the nonterminal.
+ Rules are delimited with commas.
+ The right-hand side of a rule is a double-quoted string whose first and last characters are "<" and ">", respectively. The remaining character should be in `[A-Z]` (upper-case alpha).
* `productions` is a comma-delimited list of double-quoted strings, representing productions. All characters, including whitespace, in the rule are terminal symbols, except those that are enclosed in angle brackets (`"<"` and `">"`), which are non-terminal symbols and will be the left-hand side of another rule. An open angle bracket may be escaped, but there is no need to escape a close angle bracket.
+ Productions will not contain newlines or the newline escape sequence.
**Output**
You should print each generated sentence to `stdout` with a trailing newline.
**Test Cases**
5 sets of balanced parentheses:
```
5 <S>
{"<S>":["<S><S>", "(<S>)", ""]}
```
Example result:
```
(())()
()
()()()
(())(()())((((()))()()))
```
4 postfix arithmetic expressions (note whitespace within strings is significant, whitespace elsewhere is not):
```
4 <S>
{"<S>":["<N>", "<S> <S> <O>"], "<O>":["+","-","*","/"], "<N>":["<D><N>", "<D>"],
"<D>":["1","2","3","4","5","6","7","8","9","0"]}
```
Example result:
```
1535235 76451 +
973812
312 734 99 3 + / *
1 1 1 1 1 + - * +
```
[Answer]
I felt like doing a little JavaScript.
Also, I cried a little on the inside when I wrote "document.write"
```
<body>
<script type='text/javascript'>
function foo(){
t=document.getElementById('ta').value.split("\n");
eval('p='+t[1]);
t[0]=t[0].split(' ');
while(t[0][0]--) {
s=t[0][1]
while(x=s.match(/<\w+>/)) {
ps=s;
s=s.replace(x,p[x][Math.floor(Math.random()*p[x].length)]);
}
document.write(s+"<br>");
}
}
</script>
<textarea id='ta' cols='80'></textarea>
<button onclick="foo()">go</button>
</body>
```
Input:
```
10 <A>
{"<A>":["a<A>b","c<A>d","<B>"],"<B>":["e<C>e"],"<C>":["z","<A>","<B>"]}
```
Output:
```
ccaaceeeeezeeeeedbbdd
accccceeeezeeeedddddb
aecezedeb
eaezebe
ccccaacezedbbdddd
eeeaaaceecacezedbdeedbbbeee
acaecaeaaeacccceeeeeeeaeeezeeebeeeeeeeddddbebbebdebdb
aaceezeedbb
aacezedbb
ceeaceecacaacezedbbdbdeedbeed
```
] |
[Question]
[
Given a positive integer \$N >= 4\$, output an RSA key pair (both the private and the public key) whose key length is \$N\$ bits.
The RSA key generation algorithm is as follows:
1. Choose an \$N\$-bit semiprime \$n\$. Let the prime factors of \$n\$ be \$p\$ and \$q\$.
2. Compute \$\lambda(n) = LCM(p-1, q-1)\$.
3. Choose an integer \$e\$ such that \$1 < e < \lambda(n)\$ and \$GCD(e, \lambda(n)) = 1\$.
4. Compute \$d \equiv e^{−1} \pmod {\lambda(n)}\$.
The public key is composed of \$n\$ and \$e\$. The private key is \$d\$.
## Rules
* You may assume that there exists at least one semiprime \$n\$ with bit length \$N\$.
* Output may be in any consistent and unambiguous format.
* \$e\$ and \$n\$ must be chosen from discrete uniform distributions.
* You may assume that \$N\$ is less than or equal to the maximum number of bits for integers representable in your language, if your language has such a restriction.
[Answer]
# JavaScript (ES7), 190 bytes
Returns `[n,e,d]`.
```
f=N=>(R=Math.random,g=d=>d&&p%--d?g(d):d)(p=g(p=n=R()*2**N|0))<2&n>1&(L=(q=n/p-1)*--p/(G=(a,b)=>b?G(b,a%b):a)(p,q))>2?(g=_=>G(L,e=R()*(L-2)+2|0)<2?(h=d=>d*e%L<2?[n,e,d]:h(-~d))():g())():f(N)
```
[Try it online!](https://tio.run/##ZY1NS8QwEIbv/o@WeWOya@sepOykx15qD3sVkXSTpsqaZD/wJP71GnoT4R2GeQae98N8mevx8p5uKkTrlolzBtZ04GdzmzcXE2z8lJ4ta1uWqVDKtp4sGgtK7PMEPhBELcTw/QDs6zLoqqSe6cxhm1QFoVTaUsdk5AjWY9vRKE0xojHZIc@Arlvy/Ma6o1661Ue9qnFfZ@U@P@e1X7iiz9dLkE7a12Ym9WMBQuNpXRMNWI4xXOPJbU7R00Q74O4vefpHqkdg@QU "JavaScript (Node.js) – Try It Online")
Because of the limited size of the call stack, this may fail for \$N>13\$.
### Commented
```
f = N =>
(
R = Math.random,
// helper function returning the highest divisor of p
g = d => d && p % --d ? g(d) : d
)(
// choose n and compute its highest divisor p
p = g(p = n = R() * 2 ** N | 0)
)
// make sure that p is prime
< 2 &
// and that n is greater than 1
n > 1 &
// compute L = λ(n) = LCM(p - 1, q - 1) = (p - 1) * (q - 1) / GCD(p - 1, q - 1),
// using the helper function G that returns GCD(a, b)
(L = (q = n / p - 1) * --p / (G = (a, b) => b ? G(b, a % b) : a)(p, q))
// make sure that L > 2
> 2 ?
// helper function to choose e such that GCD(e, L) = 1
(g = _ => G(L, e = R() * (L - 2) + 2 | 0) < 2 ?
// helper function to compute d such that d * e mod L = 1
(h = d => d * e % L < 2 ? [n, e, d] : h(-~d))()
:
g()
)()
:
f(N)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ ~~29~~ ~~27~~ 26 bytes
```
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi
```
[Try it online!](https://tio.run/##y0rNyan8/99I69DWIo/DbWk@RrbHNh1rj3i4s@VwW/KhremHJzzc2ZTwcEcXWGhZ5v///w3NAA "Jelly – Try It Online")
### Explanation
```
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi Main link. Arg: N
2* Compute 2^N
µ Begin a new chain. Arg: 2^N
H Compute 2^N/2
r Get all N-bit numbers (plus 2^N)
Ʋ Group the following. Arg: num
Æf Prime factors of num
L Number of prime factors of num
2= See if it is 2
Ƈ Filter by the above block
This gets N-bit semiprimes
X Choose n at random
Ṅ Print n
Æc Compute λ(n)
µ Begin a new chain. Arg: λ(n)
gÐṂ` Find all 1≤x≤λ(n) with minimal GCD(x,λ(n))
Ḋ Remove the 1 from the candidates
This gets candidates for e
X Choose e at random
Ṅ Print e
æi Compute d = e⁻¹ mod λ(n)
```
[Answer]
# Axiom, 230 bytes
```
b(x)==(1+floor log_2 x)::INT
P(n)==nextPrime(2^(n-1)::NNI+randnum(2^(n-1)::NNI))
R(n)==(n<4=>-1;k:=n quo 2;repeat(p:=P(k+1);q:=P(k);b(p*q)=n=>break);l:=lcm(p-1,q-1);repeat(e:=2+randnum(l-2);gcd(e,l)=1=>break);[p*q,e,invmod(e,l)])
```
b in b(x) would find the bit len of x;
randnum(x) with x one positive integer would be one function that return one pseudorandom number in the range 0..(x-1);
P in P(n) would find one pseudorandom prime in range 2^(n-1)..(2^n-1) [lenght of that range 2^n-1-2^(n-1)=2^(n-1)-1];
R in R(n) would find [n,e,d] as the exercise says.
```
(15) -> a:=R 23
Compiling function P with type Integer -> Integer
Compiling function b with type Integer -> Integer
Compiling function R with type PositiveInteger -> Any
Compiling function G1452 with type Integer -> Boolean
(15) [4272647,824717,1001213]
Type: List Integer
(16) -> b %.1
Compiling function b with type PositiveInteger -> Integer
(16) 23
Type: PositiveInteger
(17) -> factor a.1
(17) 1061 4027
Type: Factored Integer
(18) -> (a.2*a.3) rem lcm(1061-1,4027-1)
(18) 1
Type: PositiveInteger
(19) -> a:=R 23
(19) [5215391,932257,1728433]
Type: List Integer
(20) -> R 2048
(20)
[23213251353270373502637714718370965847258432024211176383232570158843901982_
8374419721867989228927344460592814980635585372922578037879152449312504744_
2861913195543965318695967745717301811727824635815211233105475881576100225_
3632803572317998112861757923774382346449223053928741441134006614228292016_
5273067128098814936149948557863692935433292700177694639931896886174791595_
2591510100576556786861493463332533151814120157258896598771272703168867259_
1059421044639753552393378020089166512073314575563837723165164503239565057_
8157637522454347226109931834702697646569048737623886830735628816778282907_
16962402277453801137600520400279
,
26277208914513047097872541919539499189114183243456446871374032261842172481_
1782225662860226419702820497403134660912654534465780004169047137965180193_
9424240720814436784731953475388628791624586090011147747029161125853374433_
7624317473301390727052150821160711361987569549572011227572161234939947570_
1006480714726838475136080877420539301562592505847293621815149245444744497_
0146019787431225138564647562282720244978299356752301570039442420559831909_
1396109771341727891989553783027544302642531934746013600522012136408967482_
8591443211475273074214579546316395151724707332850441864609728119186620471_
5116079141878558542286273118499
,
37945816199160687259342706646596754136573392197139994836682676167798393778_
9533248999943052484273349085225287510658624414105052824140785833431676303_
9819497567439525931938766580464486131713424225091467044692614132161523472_
3141843691744552674894778838275993887411876266402821208140118598964705638_
4930606996298811686240430389336754369834390870340241699155004906972042503_
8705910893788941005489353671521480377818624793497995264157466810522707258_
4139749164641845206614670777070059395273813452365545085917304619784119668_
4846093245280478965642073804885084960796597065443090998925258186802193768_
8791746419960588307023018400019]
Type: List Integer
```
] |
[Question]
[
~~[This question asking us to make a "Cyclic Levenquine"](https://codegolf.stackexchange.com/questions/116189/cyclic-levenquine) has gone unanswered~~. So today we will ask a slightly simpler version. In this challenge we will define a **K**-Levenquine to be a program whose output is Levenshtein distance **K** from its source.
## Task
Your goal in this challenge is to write a program with some output different from its own source; running that output as a program should also do the same. Eventually, the sequence of repeatedly running the outputs of each successive program (in the same language) must eventually output the original program.
As with the last challenge there must be two distinct programs in this cycle such that they do not share any two bytes (i.e. their byte sets are disjoint).
As with most [quine](/questions/tagged/quine "show questions tagged 'quine'") challenges, reading your own source code is forbidden.
## Scoring
Each program in your cycle will be a **K**-Levenquine for some **K**. The largest **K** of any of the programs in your cycle will be your score. Your goal should be to minimize this score, with **1** being the optimal score.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), Score: 41
```
'd3*}>a!o-!<<8:5@lI55>@z:5ll55>>q:>|q::|,
```
and the disjoint program
```
"r00gr40g44++bb+0p64++?b6+0.22#eW4s )Z
```
[Try it online!](https://tio.run/##S8sszvj/Xz3FWKvWLlExX1fRxsbCytQhx9PU1M6hyso0JwfIsCu0sqsptLKq0eFSKjIwSC8yMUg3MdHWTkrSNigwAzLsk8y0DfSMjMSVU8XDTYoVNKNk//8HAA)
A copy of my answer to the [Mutually Exclusive Quine](https://codegolf.stackexchange.com/q/153948/76162) question. A mutually exclusive quine is made of two programs, A and B sharing no common characters, where A outputs B and B outputs A. This means it is a 2-cycle Levenquine and also qualifies for this question. This can act as a baseline for other more inventive answers (though I'm not very confidant this won't go the way of the original Levenquine question).
A more detailed explanation can be found [here](https://codegolf.stackexchange.com/a/153965/76162).
] |
[Question]
[
In this challenge you have to make an ascii pulsing heart with rhythm problems (Heart arrhythmia) and then measure the pulse.Don't worry it's easy!
**Making the heart**
The heart alternates between these 2 states:
***state 1***
```
,d88b.d88b,
88888888888
`Y8888888Y'
`Y888Y'
`Y'
```
***state 2***
```
d8b d8b
888888888
`Y88888P'
`Y888P'
`Y8P'
`Y'
```
each step has **X seconds delay**
where X is a Random (Real) number between 0.3 and 1.4 (0.3<=X<=1.4)
**Measuring the Pulse**
When your arrhythmia-heart starts beating, you have to measure the pulse.
We want to know the heartbeats/min.
But (like many doctors do) you only have to count the heartbeats for 15 sec and then multiply by 4
**Final output**
Given no input, your code must run for 15 seconds (displaying the beating heart) and then **print the heart rate**.
Your output should look exactly like this!
(I will run my code 2 times for you to see the different results)
First example run:
[](https://i.stack.imgur.com/VVTR9.gif)
Second example run:
[](https://i.stack.imgur.com/P2Hjh.gif)
you must output **one** heart
Good Luck!
this is code-golf
shortest answer in bytes wins!
[Answer]
# Python [on Windows], 262 bytes
```
from time import*
import os,random
t,i=time(),0
while time()-t<15:print([""",d88b.d88b,
88888888888
`Y8888888Y'
`Y888Y'
`Y'""",""" d8b d8b
888888888
`Y88888P'
`Y888P'
`Y8P'
`Y'"""][i%2]);i+=1;sleep(random.randint(3,14)/10);os.system('cls')
print(i*4)
```
For linux and macOS use `os.system('clear')` for 2 more bytes.
[Answer]
# Mathematica, 212 bytes
```
g=",d88b.d88b,
88888888888
`Y8888888Y'
`Y888Y'
`Y'";h=" d8b d8b
888888888
`Y88888P'
`Y888P'
`Y8P'
`Y'";t=1;TimeConstrained[Monitor[While[1<2,If[OddQ@t,b=g,b=h];Pause@RandomReal@{.3,1.4};t++],b],15];4t
```
[Answer]
# Java, 374 bytes
```
class G{public static void main(String[]a)throws Exception{long t=System.currentTimeMillis(),i=0;while(System.currentTimeMillis()<15000+t){p(",d88b.d88b,\n88888888888\n`Y8888888Y'\n `Y888Y'\n `Y'\n");Thread.sleep((long)(300+(Math.random()*1100)));i++;p(" d8b d8b\n888888888\n`Y88888P'\n `Y888P'\n `Y8P'\n `Y'\n");}p(i*4);}static<T>void p(T s){System.out.println(s);}}
```
Ungolfed:
```
public class Golf {
public static void main(String[]a)throws Exception {
long t=System.currentTimeMillis(),i=0;
while(System.currentTimeMillis()<15000+t) {
p(",d88b.d88b,\n88888888888\n`Y8888888Y'\n `Y888Y'\n `Y'\n");
Thread.sleep((long)(300+(Math.random()*1100)));
i++;
p(" d8b d8b\n888888888\n`Y88888P'\n `Y888P'\n `Y8P'\n `Y'\n");
}
p(i*4);
}
static<T>void p(T s){System.out.println(s);}
}
```
] |
[Question]
[
# This is not an invitation for you to downvote everything I've posted. Just sayin' ;)
# Challenge
Figure out how I can get myself back down to 1 reputation.
Details will follow input format, then followed by output.
# Input
Input will consist of the my current reputation, the number of questions I have posted with an accepted answer (that is not my own), the number of questions I have posted without an accepted answer that have a valid answer that is not my own, and the number of answer downvotes that I have cast.
# Details
Accepting an answer that is not my own gives me 2 rep. Unaccepting an answer takes away 2 rep from me. Undownvoting an answer gives me 1 rep (we assume that all of my answer votes are not locked in at the moment), and downvoting an answer makes me lose 1 rep (we assume there are enough answers on PPCG for me to not care about the number of answers that I can downvote). We also ignore potential serial vote reversal. Most of my reputation is going to have to be given away by bounties because I don't want to go around downvoting 5000 answers.
The challenge is to find the shortest way to get me back down to 1 rep using the shortest code. Please keep in mind that I need at least 125 rep to downvote and at least 75 rep to start a bounty. By "shortest way", I mean the way requiring the least actions, where each accept and downvote and their reverse actions and each bounty is a separate action. Note that it is impossible to award a bounty of more than +500 rep at once. Also note that you can only give out bounties in 50 rep increments.
If there is no way to get back down to 1 rep, then output some consistent error message. The error message may be output through crashing.
# Output
Output the number of undownvotes, downvotes, accept-votes, unaccept-votes, and bounty actions I need to perform in any consistent order in any reasonable list format.
# Test Cases
```
reputation, accepted_answers, no_accept_questions, answer_downvotes -> accepts, unaccepts, downvotes, undownvotes, bounties
101, 3, 2, 10 -> 0, 0, 0, 0, 1 // This one's easy, just give out a 100 rep bounty.
102, 3, 2, 10 -> 0, 1, 0, 1, 1 // Unaccept to get to 100, then undownvote to get to 101, then give a +100 bounty
103, 3, 2, 10 -> 0, 1, 0, 0, 1 // First unaccept one of those answers and then give out a 100 rep bounty or vice versa
3, 1, 0, 0 -> 0, 1, 0, 0, 0 // Unaccept that answer and lose the 2 rep
1000, 0, 1, 0 -> 1, 0, 1, 0, 2 // Accept an answer to get to 1002, then downvote an answer to get to 1001, then give out two +500 bounties
```
# Rules
* [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* "Post a bunch of spam and get suspended" is not an answer, nor is anything similar
* In the case of a tie between shortest methods, output one possible shortest method
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
## Mathematica, 302 bytes
Golfed version:
```
Unprotect@Null;Null=0;f[1,_,_,_]={,,,,};f[r_,a_,n_,d_]:=(f[r,a,n,d]=l={∞,,,,};f[r,a,n,d]=#&@@MinimalBy[{If[r>74,{,,,,1}+f[r-50Min[⌈r/50⌉-1,10],a,n,d],l],If[r>124,{,,1,,}+f[r-1,a,n,d+1],l],If[d>0,{,,,1,}+f[r+1,a,n,d-1],l],If[a>0,{,1,,,}+f[r-2,a-1,n+1,d],l],If[n>0,{1,,,,}+f[r+2,a+1,n-1,d],l]},Tr])
```
Normal version:
```
Unprotect@Null; Null = 0;
f[1, _, _, _] = {, , , ,};
l = {\[Infinity], , , ,};
f[r_, a_, n_, d_] := (
f[r, a, n, d] = l;
f[r, a, n, d] = # & @@ MinimalBy[{
If[r > 74, {, , , , 1} +
f[r - 50 Min[\[LeftCeiling]r/50\[RightCeiling] - 1, 10], a, n,
d], l],
If[r > 124, {, , 1, ,} + f[r - 1, a, n, d + 1], l],(*
downvote one more *)
If[d > 0, {, , , 1,} + f[r + 1, a, n, d - 1], l],
(* un-downvote *)
If[a > 0, {, 1, , ,} + f[r - 2, a - 1, n + 1, d], l],
(* un-accept. -2 rep *)
If[n > 0, {1, , , ,} + f[r + 2, a + 1, n - 1, d], l]
(* accept. +2 rep *)
}, Tr]
)
```
Note:
1. Test this on <https://sandbox.open.wolframcloud.com/> - paste the code, press `Shift+Enter`, then enter `f[101,3,2,10]` for example for first test case, then press `Shift+Enter`.
2. Use `Block[{Null=0}, ...]` can save some bytes, but I haven't test that.
3. Sometimes `$IterationLimit=$RecursionLimit=∞` is necessary to get correct result.
4. The function will return `{∞,0,0,0,0}` or similar (that is, the sum of elements in list is infinite) when it is impossible, and a list with format similar to that in the sample output when it is possible.
] |
[Question]
[
I am trying to use C# to find the index of the first 1 (right to left) in the binary representation of a number. For example, since 100 in binary is:
```
0b1100100
```
The first 1 is in the third position from the right, so it should yield 3.
234 should yield 2, 0 should yield 0, etc.
Here is my current solution:
```
k < 1 ? 0 :(int)Math.Log(k & -k, 2) + 1;
```
Any ways I can make this shorter?
[Answer]
If only C# supported machine-specific intrinsics… There is a single instruction that can do this in x86 assembly language, and on most other processor architectures as well. Then you'd have not only the shortest code, but very likely the fastest.
In fact, making this code *shorter* is an extremely boring problem compared to making this code *fast*. There are all sorts of really neat, efficient, bit-twiddling solutions, and you could also consider using a look-up table.
None of that matters for golfing, though. It looks to me like your current solution is the best you can do. Of course, you can remove the superfluous whitespace:
```
k<1?0:(int)Math.Log(k&-k,2)+1
```
I would personally write it as:
```
k>0?(int)Math.Log(k&-k,2)+1:0
```
because I think it's slightly clearer to have the direction of the conditional test that way, as well as to compare it against zero, but I guess it's six one way, half a dozen the other.
C# doesn't support implicit conversion from `int` to `bool` like C and C++ do, so you can't really shorten the conditional test any further.
You are also stuck with the explicit cast from `double` (as returned my `Math.Log`) to `int`, as C# won't allow this to happen implicitly. Of course, that's normally a good thing because it would point out that you have a *big* performance problem here: promoting an `int` to a `double`, computing the log of a `double`, and then converting the `double` result back to an `int` will be *massively* slow, so it's normally something that you'd want to avoid. But these are the kinds of perversions you have to put up with when playing code golf.
---
I had initially come up with
```
k > 0
? ((k & -k) >> 1) + 1
: 0
```
(ungolfed for clarity, of course), which avoids taking the logarithm and is therefore an improvement in code size and speed. Unfortunately, this doesn't always get the right answer, and I assume that's an inflexible requirement. :-) Specifically, it fails if the input value (`k`) is a factor of 8. This is fixable, but not without making the code longer than the `Math.Log` version.
] |
[Question]
[
## Background
The language BrainF\*\*\* (or simply BF), is an extremely minimal programming language. We're going to strip it back even further by eliminating IO operations; only the sub-langage defined by the operations `+-<>[]`, henceforth referred to as BF-subset, shall be used. The BF variant considered has a tape extending infinitely to the left and right, and cells which can take on any integer value without overflowing, and which are initialized to 0.
For those unfamiliar with BF, this explanation is [adapted from the esolangs BF page](https://en.wikipedia.org/wiki/Brainfuck).
A BF-subset program is a sequence of commands. The commands are executed sequentially, with some exceptions: an instruction pointer begins at the first command, and each command it points to is executed, after which it normally moves forward to the next command. The program terminates when the instruction pointer moves past the last command.
```
> increment the data pointer (to point to the next cell to the right).
< decrement the data pointer (to point to the next cell to the left).
+ increment (increase by one) the byte at the data pointer.
- decrement (decrease by one) the byte at the data pointer.
[ if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command.
] if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command.
```
## The Task
If a BF-subset program terminates, its *score* is defined as the final value of the cell which the program halts at, otherwise 0. Your challenge is to write a program to generate BF-subset programs of each length between 1 and 20 inclusive, such that the total score is maximized.
The winner of the contest will be the entrant with the highest total score; in case of a tie, the shortest program takes the title. Your program must be fast enough for you to run it to completion.
## Example Output and Scores
```
+ 01
++ 02
+++ 03
++++ 04
+++++ 05
++++++ 06
+++++++ 07
++++++++ 08
+++++++++ 09
++++++++++ 10
+++++++++++ 11
++++++++++++ 12
+++++++++++++ 13
++++++++++++++ 14
+++++++++++++++ 15
++++++++++++++++ 16
+++++++++++++++++ 17
++++++++++++++++++ 18
+++++++++++++++++++ 19
+++++++++++++++++++ 20
```
Here, the total score is 210.
Edit: Changed the maximum length from 17 to 20.
[Answer]
# 309
```
+ 01
++ 02
+++ 03
++++ 04
+++++ 05
++++++ 06
+++++++ 07
++++++++ 08
+++++++++ 09
++++++++++ 10
+++++++++++ 11
++++++++++++ 12
+++++++++++++ 13
++++[->++++<]> 16
+++++[->++++<]> 20
+++++[->+++++<]> 25
++++++[->+++++<]> 30
++++++[->++++++<]> 36
+++++++[->++++++<]> 42
+++++++[->+++++++<]> 49
```
] |
[Question]
[
# Challenge description
Let's define an `W` x `H` **grid** as a two-dimensional array of length `H` whose each subarray is of length `W`. Example: a 2x3 grid (`.` character used as a blank):
```
..
..
..
```
A **unit** is a single point of a grid. A **block** is either a single unit or a set of contiguous units (meaning each unit of a block has at least another one next to, above or below it). In the 10x10 grid below there are 4 blocks (units represented by `X`'s):
```
........X. ........1.
..X....... ..2.......
..X....... ..2.......
..X....... ..2.......
.......X.. .......3..
.......XX. .......33.
.......XX. .......33.
..X....... ..4.......
..XX..X... ..44..4...
...XXXX... ...4444...
```
Two blocks are **distinct** if either their positions in the grid or the number of blocks they consist of are different. In the 10x10 grid below there are 5 blocks (they're all 2x2 squares, but their positions are different, therefore they're distinct):
```
.......... ..........
.XX....XX. .11....22.
.XX....XX. .11....22.
.......... ..........
.......XX. .......33.
.......XX. .......33.
....XX.... ....44....
....XX.... ....44....
XX........ 55........
XX........ 55........
```
Given two integers `W` and `H` `(W, H > 0)`, calculate the number of distinct blocks that can be constructed within a `W` x `H` grid.
# Sample inputs / outputs
```
(1, 1) -> 1 | only a 1x1 block can be constructed
(1, 2) -> 3 | two 1x1 blocks, and one 1x2 block
(2, 2) -> 13
(3, 3) -> 218
(4, 4) -> 11506
```
# Notes
* Remember that this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible!
* Relevant sequences: [A059525](https://oeis.org/A059525), [A059020](https://oeis.org/A059020)
[Answer]
# Python 2, ~~208~~ ~~184~~ ~~169~~ ~~167~~ 163 bytes
```
w,h=input()
def f(x):global g;o=g;g&=~2**x;o>g>[x/w==(x+s)/w<f(x+s)or-1<x/w+s<h<f(x+s*w)for s in[-1,1]]
n=i=1<<w*h
while i:g=i=i-1;f(len(bin(g))-3);n-=g>0
print~-n
```
] |
[Question]
[
```
This is Markov.
Markov's golf ball rolls around randomly.
Markov's ball will hole however he strikes it.
Markov is smart.
Be like Markov.
```
And this:
[](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Indian_Harvester_Ant_Nest.JPG/160px-Indian_Harvester_Ant_Nest.JPG)
is an anthill in Langton's backyard.
The anthill is big enough to hold Markov's golfball, MarGolf. However, the anthill moves and changes direction depending on the surrounding terrain.
## The Task
**Take an input of a 10x20 field:**
* `*` MarGolf
* `O` Lanton's Anthill
* `,` Anthill turns 90 degrees clockwise
* `.` Anthill turns 90 degrees counterclockwise
* `0` MarGolf in Langton's Anthill
A field looks like this:
```
,...,.,,..,...,.,,..
..,.,,,..,...,..,.,.
.,,*.,....,.,,,.,,,.
,.,,.,...,,.,.,,,,,.
.,..,....,,.....,,.,
,.,.,...,..,.,,,,..,
....,,,,,,,,,.......
........,,.,...,...,
,,,,,,,,,,,,....,O.,
,.,.,.,.....,,.,,,,,
```
**Game rules:**
The configuration of the input field is called tick 0. Your program needs to evaluate and print out the configuration of the next tick, in which both MarGolf and Langton's Anthill will move to another cell. The the item in the current cell will become the item currently in the target cell. If both MarGolf and the anthill move to the same cell in the next tick, the game ends.
**Movement rules:**
* **MarGolf** moves randomly. All nine cells in the 3x3 area around MarGolf has equal chance of being selected. This becomes a choice among 6 cells at an edge of the field, and 4 cells at a corner.
* **Langton's Anthill** needs to remember its movement direction of either up, down, left, or right (NSEW or whatever equivalent). It moves one cell in its direction each tick, and the original content of the cell changes its direction clockwise or anti-clockwise, as specified above. Initial direction at tick 0 is random, each direction has an equal chance of being the initial.
## Notes
* The program needs to print the configuration of each tick, until the game ends.
* The tick number precedes the field configuration of each tick.
* You may assume the input is always valid.
* The shortest program is bytes wins.
---
**Update:** forgot to mention anthill reverses direction before moving if it would otherwise go off the field. Credit to user81655 for reminding.
[Answer]
# Java 10, ~~611~~ ~~609~~ ~~607~~ ~~593~~ 591 bytes
```
m->{int x=0,y=0,X=0,Y=0,r=10,c,d=4,e;for(d*=Math.random();r-->0;)for(c=20;c-->0;){if(m[r][c]<43){x=r;y=c;}if(m[r][c]>48){X=r;Y=c;}}for(;;d=m[r][c]<45?d<2?d+2:d<3?1:0:d>1?d-2:d>0?2:3){p(m);for(e=4;e==4;e*=Math.random())e=9;m[r=x][c=y]=m[x+=e/3<1?x>0?-1:1:e/3>1?x<9?1:-1:0][y+=e%3<1?y>0?-1:1:e%3>1?y<19?1:-1:0];if(m[x][y]>48){m[x][y]=48;m[r][c]=0;p(m);e/=0;}m[x][y]=42;m[r=X][c=Y]=m[X+=d<1?X<9?1:-1:d==1?X>0?-1:1:0][Y+=d==2?Y<19?1:-1:d>2?Y>0?-1:1:0];if(m[X][Y]<43){m[r][c]=48;m[X][Y]=0;p(m);e/=0;}m[X][Y]=79;}}void p(char[][]m){var p="";for(var a:m)p+=p.valueOf(a)+"\n";System.out.println(p);}
```
-4 bytes thanks to *@ceilingcat*.
Assumes the final swap of `*` and `O` will empty the cell where `*` is coming from.
**Explanation:**
[Try it online.](https://tio.run/##hVTfb5swEH7fX2EhVcKNcYFkWoMxaNpz24e@BDEePEzWdIEgQjNQxN@enc2PVJGSWTnHd/7uu@@sE@/iIKx3@eeUbsV@j57Epjh@QWhT1Fm1FmmGnpWL0GG3kSg10zdRxUmcoBwziHdg8HtGBeLolFvBERJRw23Sgq3AIrCKOzZJieQLkrH1rjLlPX8S9RutRCF3uYlZZVmBzbC6S7lrs7T3j5u1mcdVEqeJv5jjY8Mr1vKUded4sHjExxXEIxXvFANjkk9ZX0Ppu6GcuZ7056Hj2Z4MnFBa4Ad26HrAWprQjErM@IJlXG0X@nDGlwwoeQOkvE2Avpnx7GHuO2EDNJbjOR64wNz4S6gCATuJW8DcKUw7Ye4UpvWdCcR0K8Db9q0MZ754ZEMP3GZaYfYAp266d7WglRIUKUGrGZdQajXWl5yDNxYGNREAOHfDaKouA/DOiF4KMEb9a4/1tRQdvpTSB78t4eGZHpByGpAcHw@iQiU3DP22yhFejssZL@lBbD@yl7Up8Mz4WRjstd3XWU53HzUtK5igbWGWmHUnhMqPX9tNiva1qOFP18hhRM3XGnC/40TgfjyL7K@eXRPTgqamckclPQAhg1BKCSVE7ePJoPXuBwC/V5VoTUxGbH8/QZV3HUvIvcYNOcquYXVVzUl6NLnFSwdaveuUG7yfpPbKr/dG@8o9Tq9b2LE2HV7jqoZPS@e8/E/vuS@1LrAa2g2fme70Dw)
```
m->{ // Method with character-matrix parameter and no return-type
int x=0,y=0, // [x,y] coordinates of MarGolf
X=0,Y=0, // [X,Y] coordinates of Langton's Anthill
r=10,c, // Temp [x,y] coordinates
d=4, // Direction Langton's Anthill
e; // Direction MarGolf
for(d*=Math.random(); // Set the direction Langton's Anthill randomly [0,3]
r-->0;) // Loop over the rows:
for(c=20;c-->0;){ // Inner loop over the columns:
if(m[r][c]<43){ // If '*' is found:
x=r;y=c;} // Set MarGolf's [x,y] coordinates
if(m[r][c]>48){ // If 'O' is found:
X=r;Y=c;}} // Set Langton's Anthill's [X,Y] coordinates
for(; // Loop indefinitely:
; // After every iteration:
d= // Change the direction of Langton's Anthill:
m[r][c]<45? // If the swapped cell contained a comma:
d<2?d+2:d<3?1:0 // Change the direction clockwise
: // Else (the swapped cell contained a dot):
d>1?d-2:d>0?2:3){// Change the direction counterclockwise
p(m); // Pretty-print the matrix
for(e=4;e==4;e*=Math.random())e=9;
// Change direction MarGolf randomly [0-9] (excluding 4)
m[r=x][c=y] // Save the current MarGolf coordinates
=m[x+=e/3<1?x>0?-1:1:e/3>1?x<9?1:-1:0]
[y+=e%3<1?y>0?-1:1:e%3>1?y<19?1:-1:0];
// And change that cell to the content in direction `e`
// 0 to 9 (excl. 4) is NW,N,NE,W,n/a,E,SW,S,SE respectively
// If `e` would go out of bounds, it moves opposite instead
if(m[x][y]>48){ // If MarGolf reached Langton's Anthill:
m[x][y]=48; // Set that cell to '0'
m[r][c]=0; // And empty the swapped cell
p(m); // Print the final status of the matrix
e/=0;} // And stop the loop with an error to exit the program
m[x][y]=42; // Change the cell in the new coordinate to '*'
m[r=X][c=Y] // Save the current Langton's Anthill coordinates
=m[X+=d<1?X<9?1:-1:d==1?X>0?-1:1:0]
[Y+=d==2?Y<19?1:-1:d>2?Y>0?-1:1:0];
// And change that cell to the content in direction `d`
// 0 to 3 is E,W,S,N respectively
// If `d` would be out of bounds, it moves opposite instead
if(m[X][Y]<43){ // If MarGolf reached Langton's Anthill:
m[r][c]=48; // Set that cell to '0'
m[X][Y]=0; // And empty the swapped cell
p(m); // Print the final status of the matrix
e/=0;} // And stop the loop with an error to exit the method
m[X][Y]=79;}} // Change the cell in the new coordinate to 'O'
void p(char[][]m){ // Separated method to print the given matrix
var p=""; // String to print, starting empty
for(var a:m){ // Loop over the rows:
p+=p.valueOf(a) // Convert the character-array to a String line and append,
+"\n"; // including a trailing newline
System.out.println(p);} // Print the String with trailing newline as separator
```
] |
[Question]
[
### Introduction
Right now I'm participating a chess tournament. I got inspired by the tournament schedule. Right now, I'm in a competition with three other players. That means with the four of us, we are playing 3 rounds. The schedule goes as following:
```
Round 1: 1-4 3-2
Round 2: 3-4 2-1
Round 3: 1-3 4-2
```
This is also known as **Round Robin**. Also, this is a **valid** schedule. We say that a schedule is valid, when it satisfies the following conditions:
* Every player plays **once** against another player.
* `1-2` means that player `1` has **white**. Every player has or (*N / 2 - 0.5*) or (*N / 2 + 0.5*) times white, with *N* being the amount of rounds.
For example, in the above example, there are **3** rounds. So N = 3. As you can see, **the amount of rounds equals the amount of players - 1**. A player has either
* *N / 2 - 0.5* = **1** time white, or
* *N / 2 + 0.5* = **2** times white.
In the above example:
* player `1` has **2 times** white,
* player `2` has **1 time** white,
* player `3` has **2 times** white,
* player `4` has **1 time** white.
### The task
Given an **even** integer > 1 representing the amount of players in the competition, output the tournament schedule.
### Test cases:
Input = 4, that means N = 3
```
Input: Output:
4 1-4 3-2
3-4 2-1
1-3 4-2
```
Input = 10, that means N = 9
```
Input: Output:
10 1-10 2-9 3-8 4-7 5-6
10-6 7-5 8-4 9-3 1-2
2-10 3-1 4-9 5-8 6-7
10-7 8-6 9-5 1-4 2-3
3-10 4-2 5-1 6-9 7-8
10-8 9-7 1-6 2-5 3-4
4-10 5-3 6-2 7-1 8-9
10-9 1-8 2-7 3-6 4-5
5-10 6-4 7-3 8-2 9-1
```
Input = 12, that means N = 11
```
Input: Output:
12 1-14 2-13 3-12 4-11 5-10 6-9 7-8
14-8 9-7 10-6 11-5 12-4 13-3 1-2
2-14 3-1 4-13 5-12 6-11 7-10 8-9
14-9 10-8 11-7 12-6 13-5 1-4 2-3
3-14 4-2 5-1 6-13 7-12 8-11 9-10
14-10 11-9 12-8 13-7 1-6 2-5 3-4
4-14 5-3 6-2 7-1 8-13 9-12 10-11
14-11 12-10 13-9 1-8 2-7 3-6 4-5
5-14 6-4 7-3 8-2 9-1 10-13 11-12
14-12 13-11 1-10 2-9 3-8 4-7 5-6
6-14 7-5 8-4 9-3 10-2 11-1 12-13
14-13 1-12 2-11 3-10 4-9 5-8 6-7
7-14 8-6 9-5 10-4 11-3 12-2 13-1
```
Of course, the extra whitespaces I used between the numbers is **optional** but not necessary. You may output it in any form you like, as long as it's readable.
**Note:** The above examples aren't just the *only* valid outputs. There certainly are more valid outputs.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# Python 2, ~~200~~ 186 Bytes
---
```
n=input()
t=range(2,n+1)
for k in t:
s=[1]+t
c=[[s[x],s[-x-1]] for x in range(n/2)]
if k%2:c[0].reverse()
t=t[-1:]+t[:-1]
print"\t".join(["-".join([str(y) for y in x]) for x in c])
```
---
Example output:
```
$ python chess.py
4
1-4 2-3
3-1 4-2
1-2 3-4
$ python chess.py
10
1-10 2-9 3-8 4-7 5-6
9-1 10-8 2-7 3-6 4-5
1-8 9-7 10-6 2-5 3-4
7-1 8-6 9-5 10-4 2-3
1-6 7-5 8-4 9-3 10-2
5-1 6-4 7-3 8-2 9-10
1-4 5-3 6-2 7-10 8-9
3-1 4-2 5-10 6-9 7-8
1-2 3-10 4-9 5-8 6-7
$ python chess.py
14
1-14 2-13 3-12 4-11 5-10 6-9 7-8
13-1 14-12 2-11 3-10 4-9 5-8 6-7
1-12 13-11 14-10 2-9 3-8 4-7 5-6
11-1 12-10 13-9 14-8 2-7 3-6 4-5
1-10 11-9 12-8 13-7 14-6 2-5 3-4
9-1 10-8 11-7 12-6 13-5 14-4 2-3
1-8 9-7 10-6 11-5 12-4 13-3 14-2
7-1 8-6 9-5 10-4 11-3 12-2 13-14
1-6 7-5 8-4 9-3 10-2 11-14 12-13
5-1 6-4 7-3 8-2 9-14 10-13 11-12
1-4 5-3 6-2 7-14 8-13 9-12 10-11
3-1 4-2 5-14 6-13 7-12 8-11 9-10
1-2 3-14 4-13 5-12 6-11 7-10 8-9
```
---
Or **135 Bytes**, by using a less pretty (but still readable) output:
```
...
print c
```
Which produces something like:
```
$ python chess.py
4
[[1, 4], [2, 3]]
[[3, 1], [4, 2]]
[[1, 2], [3, 4]]
```
] |
[Question]
[
A fun programming exercise is to write a program that quizzes the user from a set list of questions and answers. However, this task goes a level beyond that.
## Your task
* Write a program/func/etc. that takes two lists: A list of questions and a list of answers.
* Output a program that quizzes the user.
* The output program should ask each question on a separate line, which each question with a colon and space at the end like, `What is 2+2:`.
* After the user answers all the questions, output a newline, and then one on each line, questions correct, questions wrong, and percentage calculation (rounded to 2 decimal places) as such (the brackets are user input):
```
What is the meaning of life, the universe, and everything: <42>
Am I awesome(Yes/No): <No>
What is 2+2: <4>
Number Correct: 2
Number Wrong: 1
Score: 2 / 3 * 100 = 66.67%
```
## Scoring
* You are scored on the size of your compiler program.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortes code in **bytes** wins!
* **Bonus**: Score \*.9 if you implement a flag in your compiler that makes the output program randomize question order.
[Answer]
# CJam, ~~105~~ 99 bytes
```
{{": "+ol}%.=_:+\,:LX$-X$LX$e2Ld/]"
Number Correct: %d
Number Wrong: %d
Score: %d / %d * 100 = %.2f%%"e%}
```
This defines an anonymous function.
The code is **110 bytes** long and qualifies for the **× 0.9** randomization bonus.
### Test run
```
$ cat qna.cjam
[
[
"42"
"Yes"
"4"
]
[
"What is the meaning of life, the universe, and everything"
"Am I awesome(Yes/No)"
"What is 2+2"
]
]
{zmrz~{": "+ol}%.=_:+\,:LX$-X$LX$e2Ld/]"
Number Correct: %d
Number Wrong: %d
Score: %d / %d * 100 = %.2f%%"e%}
~
$ cjam qna.cjam
What is 2+2: 4
Am I awesome(Yes/No): No
What is the meaning of life, the universe, and everything: 42
Number Correct: 2
Number Wrong: 1
Score: 2 / 3 * 100 = 66.67%
```
] |
[Question]
[
This serves as a catalog for tips related to golfing in [Burlesque](http://esolangs.org/wiki/Burlesque).
Burlesque is a lazy, esoteric programming language. It's mostly used on anarchy golf while popularity on Codegolf is not as high. However, this catalog is intended to be used by people golfing on anarchy golf as well.
Please only mention tricks and not obvious shortcuts. An obvious shortcut is for example using `r\` instead of `r@\[` because the built-in `r\` is defined to be `r@\[` and is stated as such in the documentation and is thus just an obvious shortcut.
[Answer]
## Using `".. .."wd` instead of `{".."".."}`
If you need a Block of Strings such as `{"abc" "def"}` it is shorter to use the *words* built-in: `"abc def"wd`.
## Using `ra` to parse *fail-safe*
`ps` will fail if the input is not properly formated or might produce unwanted results. In such cases, using `ra` is better.
```
blsq ) "5,"ra
5
blsq ) "5,"ps
{5 ,}
blsq ) "5a"ps
{ERROR: (line 1, column 3):
unexpected end of input}
blsq ) "5a"ra
5
```
## Using `,` to drop stdin
`,` is defined as a pop instruction if and only if there is exactly one element on the stack. It's used to pop STDIN from the stack when it's not needed but there (such as for example is the case on anarchy golf).
## Abusing the way `mo` is defined
`mo` is defined as `1R@\/?*` and is used to generate a Block containing multiples of N:
```
blsq ) 3mo9.+
{3 6 9 12 15 18 21 24 27}
```
Yet due to side effects of `?*` you can do some nasty things with it if you don't provide a number:
```
blsq ) "1"mo9.+
{"11" "21" "31" "41" "51" "61" "71" "81" "91"}
blsq ) {1 2 3 4}mo9.+
{1 4 9 16}
```
] |
[Question]
[
**This question already has answers here**:
[Polynomial Laplace transform](/questions/216880/polynomial-laplace-transform)
(18 answers)
Closed 3 years ago.
Your goal is to write a program that will print out the Laplace transform of a polynomial function with integer coefficients \$f(x)\$. The Laplace transform of \$f(x)\$ is defined as \$\int\_0^\infty f(x) e^{-sx} dx\$.
The standard input for the polynomial function will be
```
a+bx+cx^2+dx^3+...
```
If the coefficient is zero, that term is omitted. It can be taken in from any standard type of input.
```
This is valid input: 1+x^2-5x^4+20x^5
These aren't:
0
1+0x
1+x^1
x^0+x
```
You may output from any standard type of output, in any readable order. Trailing newline is permitted.
No using built in evaluation functions.
Examples:
```
Input: 1
Output: 1/s
Input: 3-x
Output: 3/s-1/s^2
```
This is code golf, so the shortest entry in bytes wins.
[Answer]
# CJam, 57 bytes
```
l_"+-":Pf&sN+\PSerS/.{'^-'x/2We]"11".e|:~~:Em!*"/s^"E)+@}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l_%22%2B-%22%3APf%26sN%2B%5CPSerS%2F.%7B'%5E-'x%2F2We%5D%2211%22.e%7C%3A~~%3AEm!*%22%2Fs%5E%22E)%2B%40%7D&input=1-x%2Bx%5E2-x%5E3).
[Answer]
# Perl, 129 bytes
Regex-based solution:
```
sub f{@_[0]<2?1:@_[0]*f(@_[0]-1)}$_=<>;s/(\d*)x\^?(\d*)/f($2?$2:1)*($1?$1:1).'^'.($2?$2+1:2)/eg;s/(?<!\^)(\d+)/$1.'\/s'/eg;print
```
Multiline:
```
sub f{@_[0]<2?1:@_[0]*f(@_[0]-1)} # define factorial subroutine
$_=<>; # read input
# do the laplace transform for all non-constant terms, without dividing by s:
s/(\d*)x\^?(\d*)/f($2?$2:1)*($1?$1:1).'^'.($2?$2+1:2)/eg;
s/(?<!\^)(\d+)/$1.'\/s'/eg; # divide non-exponents by s
print
```
] |
[Question]
[
The challenge is about finding an optimal solution on how to place a number of given shapes. It is oriented on the principle of Tetris, where it is optimal to pack the given pieces as tight as possible.
An optimal solution means that all shapes could be placed in one rectangle block filling the width of the playground. If there is no optimal solution possible, the code should find a solution where holes are placed as high as possible (thus allowing to have a subpart of the solution being optimal). Empty spaces on top of the solution are also counted as holes (see example at the bottom).

## Rules
* There are predefined Tetris shapes: `I J L S Z O T`
* There could be multiple shapes of the same type available
* There is a playground with a certain width X
* The minimum width is 4, there is no maximum width
* There is no limitation for the height of the playground
* It is possible to rotate the shapes in 4 directions (Up, Left, Right, Down)
* It is NOT possible to mirror the shapes (Turning L into J or S into Z)
Possible shapes:
```
T: T
TTT
I: IIII
J: JJJ
J
L: L
LLL
S: SS
SS
Z: ZZ
ZZ
O: OO
OO
```
A bit of imagination is needed, but everyone who played Tetris should be familiar with the shapes.
## Example
A call to a solution using Python could look like the following:
`tetrissolver.py <Width> <Shape1> <Shape2> <ShapeN>`
`tetrissolver.py 4 S S T T L`
The result would be some kind of output which shows the optimal solution (tightest possible packaging). Bonus points if the solution also returns if the found solution is optimal.
Possible output of the above input in a text format:
```
LLLT
LSTT
SSST
STSS
TTTS
The found solution is optimal
```
If there is no optimal solution available, the code should find a solution with the least amount of holes in it. Empty spaces on top of the package are counted as holes. The above example with an additional T element could look like the following in the solution (holes marked with X):
```
XTXX
TTTX
LLLT
LSTT
SSST
STSS
TTTS
The found solution is NOT optimal
```
## Solution
The solution should find the most optimal package. Holes should be placed as high as possible. If two solutions generate the same quality of packages (optimal packages if possible, same amount of holes), the smallest solution wins.
[Answer]
# Java - Theoretically Optimal Solution
I needed one of these anyway, so...
Code is viewable [here](http://pastebin.com/mY0yHFNN).
The routine should theoretically produce an optimal solution for any input. It typically runs on the order of milliseconds or seconds for < 100 shapes, and the complexity appears to be roughly O(*n* log2 *n*) for random inputs. Packing hundreds or even thousands of random shapes should complete in a reasonable amount of time.
The worst case performance grows as O(*n**n* *w**w*), where *n* is the number of shapes to pack and *w* is the packing width. Thus this program earns the dubious distinction of having the worst worst case performance of any (non-busy-beaver) algorithm I've ever programmed. :P
### Sample I/O
```
java TetPack 10 J T Z I I J Z O O J T S S O I
IIIIJOOTTT
IIIIJOOSTI
OOSJJZTSSI
OOSSZZTTSI
OOJSZJTZZI
OOJJJJJJZZ
Displayed solution is optimal.
java TetPack 3 T
XTX
TTT
9 J S I O S T T I I I S
XIIIIIIII
TTTSSIIII
TTSSJJJOO
TTSSSSJOO
TSSSSIIII
java TetPack 15 L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
JJJJLLLLJLJJJJJ
JJJJLLJJJLJJJJJ
LLLLLLJJJLLLJJJ
LLLLLLJJLLLLJJJ
LLLLJJJJLLJLLLL
LLLLJJJJJLJJJLL
LLJJJJJJJLLLLLL
LLJJJJJJJLLLLLL
LLJJJJJLJLLLLLL
JJJJJJLLJJJLJLL
JJJJJJLLLLLLJLL
JJJJJLLLJJLJJLL
LLLJJLLLJJLJJJJ
LLLLLLLLJJLLLJJ
JLLLLLJLJJLLJJJ
JJJLLLJJJLLLJJJ
Displayed solution is optimal.
java TetPack 4 Z T
XZXX
ZZTX
ZTTT
java TetPack 30 J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I
XXIIIIIIIIIIIIIIIIIIIIIIIIIIII
LIIIILIIIILIIIILIIIIJLIIIIJLOO
LIIIILJJJLLIIIILLLJJJLIIIIJLOO
LLJLJLLIJLLLZLJLLLJJJLLZZJJLLI
JJJLJJJILLLZZLJJJLJZZLLIZZZOOI
JJJLLILILZZZJLLSSOOIZZLILZZOOI
JJJJJILILLZZJSSSZOOIOOLILZTLLI
IJJJJILLSSZJJSSZZOOIOOTILLTTLI
IJJJJILSSZZSSZSZTOOIITTTOOTSLI
IJJJJLLZZZSSZZTTTTOOIIJJOOLSSI
ISSZILLLZZOOZTTTTJOOIIJLLLLTSI
SSZZILLOOJOOTZZTTJJJIIJLZZTTOO
LSZLIZZOOJJJTTZZTIIIIIJLLZZTOO
LSSLIJZZOOOOTSSSSSSTZZJJJLIIII
LLSLLJJJOOOOSSSSSSTTTZZLLLIIII
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 9 years ago.
[Improve this question](/posts/37351/edit)
The challenge is to draw the outline of an 'island', generated using a seed as input.
* Input (seed): string of 6 characters (exactly) allowing only lowercase letters (i.e. abcdefghijklmnopqrstuvwxyz) - examples: 'island', 'aaaaaa', 'jhgcfj'
* Each seed is to give a unique island (i.e. no two seeds will give the same output)
* No output is to be a transformation of another seed's output. That's translation, reflection, rotation, scaling or any combination thereof.
* Using the same seed should always give the same output
* Output: 600px by 600px image
A valid island is drawn using a single line, which:
* forms a closed loop
* is 1px thick with no smoothing, blurring etc.
* is continuous (i.e. after drawing a pixel the next pixel will be in one of the 8 adjoining spaces that isn't occupied)
* does not cross itself at any point
* does not leave the boundaries of the image
* is black (#000), on a background of white (#FFF)
* has no lines of reflective symmetry
* must enclose white space
Source code has a limit of 500 bytes.
Aside from that, popularity decides; most votes wins.
[Answer]
# BBC basic
Here's a very simple algorithm, which could be refined for more realism. If there are further changes in the rules I'm willing to change / delete.
take the 6 character string and add `}@` to ensure asymmetry (this particular choice of characters gives islands that vaguely resemble Antarctica)
draw a line that connects 8 points at 45 degree intervals, with distance from the centre determined by the ASCII code.
```
INPUT a$
a$=a$+"}@"
MOVE 364,300
FOR i=1 TO 8
r=4*ASC(MID$(a$,i))-192
DRAW 300+r*COS(i*PI/4),300+r*SIN(i*PI/4)
NEXT
```

[Answer]
# [Algoid](http://www.algoid.net)
Algoid is a language similar to LOGO or Turtle and is *almost* entirely graphics based.
```
algo.hide()
algo.setBgColor(15)
algo.setStroke(1)
algo.setColor(0)
algo.goTo(-400,100)
set seed="put seed here".lower()
set letters = "abcdefghijklmnopqrstuvwxyz"
set sides=seed.length()
for (set i=0;i<sides-(sides/6);i++) {
set letter = seed.getChar(i%seed.length())
set value = letters.indexOf(letter)*5
set turn = 360/seed.length()
algo.go(math.sin(value)*(1500/seed.length()))
algo.turnRight(turn)
}
algo.lineTo(-400,100)
```
## Seed: `supercalifragilisticexpialiadocious even though the sound of it is rather quite atrocious`

## Seed: `islands in the stream`

] |
[Question]
[
A bit of an unusual one, but hey, why not? :)
**The objective:** Write a functioning IRC daemon in your language of choice that provides barebones functionality, in as few characters as possible. As long as it fulfills the criteria below, it does *not* have to fully comply with the IRC RFCs (this would make the challenge significantly less fun), it just needs to work.
**Requirements:**
* Clients must be able to connect on port 6667 and use it. At least irssi and XChat must be able to connect to it successfully with a default configuration.
* Users must be able to specify their own nickname, change it while already connected, join channels, leave channels, and exit cleanly (ie. `QUIT`).
* Channels should be created like normal - joining a channel with no users in it 'creates' it. They do not have to be persistent.
* Users must be able to send both channel messages and private messages (ie. to other users).
* The `WHOIS` command must be implemented, as well as `PING`/`PONG`, `LIST`, and `NAMES` (mostly in order to keep clients happy).
**Restrictions:**
* You may not use any third-party libraries (that includes non-core evented I/O libraries). Only standard libraries that come with the platform you use, are permitted.
* If your implementation includes explicit support for IRC in the standard library, you may not use that either. Standard-library network functionality is, of course, fine.
* Your submission must be able to run independently. No being clever with mIRC scripting :)
Modes, kicks, etc. do not have to be implemented (unless required to make it work with the above clients). SSL isn't necessary either. Just the above barebones functionality, to keep the challenge short and fun.
More information on what IRC is [here](https://en.wikipedia.org/wiki/Irc), RFCs are 1459 and 2812 (I can't link to them directly due to my lack of reputation).
Shortest functional and requirements-compliant submission wins!
[Answer]
# C++ (partially golfed) 5655 (with CRLF counting for 1)
This compiles in VS 2013 (uses auto, lambdas and winsock) It seemed to be working before I golfed it so unless I mucked it up it should still be ok. One of the reasons it is so big is that the numeric replies I am returning include the text specified in the RFC - I don't know if that is necessary or not. I tested it with KVirc because it runs portably (not allowed to install software on my PC!) KVirc seems to work with my server but I don't know about other clients - I did what I thought the RFC said but a lot of it is underspecified so hopefully I understood it right.
The server handles DIE, KILL, NICK, USER, MODE, WHOIS, WHO, JOIN, PART, TOPIC, LIST, NAMES, PRIVMSG, USERS, PING, PONG and QUIT to varying degrees. For most of them I return the required responses including doing most of the checks needed to return the specified error replies. For some of them I cheat:
* USERS always returns 446 "USERS has been disabled"
* the channel MODE message always returns 477 "Channel doesn't support modes"
* the user MODE message works properly but the flags are not used by the other commands
I figure it is only partially golfed because I am not very good at golfing so if you see something big please edit the answer and fix it.
Here is the golfed version
```
#include<time.h>
#include<map>
#include<list>
#include<vector>
#include<string>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<winSock2.h>
#pragma comment(lib,"ws2_32.lib")
#define P m.p[0]
#define Q m.p[1]
#define E SOCKET_ERROR
#define I INVALID_SOCKET
#define T c_str()
#define H second
#define Y first
#define S string
#define W stringstream
#define G else
#define J G if
#define A auto
#define Z bool
#define B empty()
#define K return
#define N 513
#define X(n,x)if(x){r=n;goto f;};
#define U(x,i)for(A i=x.begin();i !=x.end();++i)
#define L(x)U(x,i)
#define V(x)for(A i=x.begin();i!=--x.end();++i)
#define M(x)FD_ZERO(&x);FD_SET(t.s,&x);L(l){FD_SET(i->s,&x);}
#define R(a,b,...){M v={a,b,{__VA_ARGS__}};w(d,v);}
#define F(x)}J(!_stricmp(m.c.T,x)){
using namespace std;struct C{S t;list<S>n;};struct M{S f;S c;vector<S>p;};struct D{SOCKET s;SOCKADDR_IN a;int m,l,i;char b[N];S n,u,h,r;time_t p,q;};map<S,C>c;list<D>l;void w(D d,M m);void x(D&t,S r,Z n){L(c)i->H.n.remove(t.n);L(l){A d=*i;if(d.n!=t.n)R(d.n,"QUIT",t.n,r)J(n)R("","ERROR","QUIT",r)}closesocket(t.s);t.s=I;}void w(D d,M m){S s=(!m.p.B?":"+m.f+" ":"")+m.c;V(m.p)s+=" "+*i;s+=" :"+*m.p.rbegin()+"\r\n";int c=0;do{int b=send(d.s,s.T+c,s.size()-c,0);if(b>0)c+=b;G x(d,"send error",0);}while(s.size()-c>0);}Z e(D&d,M m){A z=m.p.size();if(!_stricmp(m.c.T,"DIE")){K 1;F("KILL")if(z<1)R("","461",d.n,"USER","Not enough parameters")G{Z f=0;L(l)if(i->n==P){f=1;x((*i),P,1);}if(f==0)R("","401",d.n,P,"No such nick/channel")}F("NICK")if(z<1)R("","431",d.n,"No nickname given")G{Z f=0;L(l)if(i->n==P)f=1;if(f==1)R("","433",d.n,"Nickname is already in use")G d.n=P;}F("USER")if(z<4)R("","461",d.n,"USER","Not enough parameters")G{Z f=0;L(l)if(i->u==P)f=1;if(f==1)R("","462",d.n,"Unauthorized channel (already registered)")G{d.u=P;d.m=atoi(Q.T);d.h=m.p[2];d.r=m.p[3];R("","001",d.n,"Welcome to the Internet Relay Network "+d.n+"!"+d.u+"@"+d.h)}}F("MODE")if(z<1)R("","461",d.n,"MODE","Not enough parameters")J(P==d.n){if(z<2)R("","221",d.n,S("")+(d.m&2?"+w":"-w")+(d.m&3?"+i":"-i"))G{A x=(147-Q[1])/14;if(Q[0]=='+'){d.m|=1<<x;}G{d.m&=~(1<<x);}}}G R("","477",d.n,P,"Channel doesn't support modes")F("WHOIS")if(z<1)R("","431",d.n,"No nickname given")G{Z f=0;L(l)if(i->n==P){f=1;R("","311",d.n,(i->n,i->u,i->h,"*",i->r))}if(f==1)R("","318",d.n,P,"End of WHOIS")G R("","401",d.n,P,"No such nick/channel")}F("WHO")L(c[P].n)U(l,j)if(*i==j->n)R("","352",d.n,P,j->u,j->h,"*",j->n,"",j->r)R("","315",d.n,P,"End of WHO")F("JOIN")if(z<1)R("","461",d.n,"JOIN","Not enough parameters")J(P=="0")L(c){U(i->H.n,j)if(*j==d.n)R("","PART",i->Y,d.n)i->H.n.remove(d.n);}G{A&C=c[P];Z f=0;L(C.n)if(*i==d.n){f=1;}if(f==0){C.n.push_back(d.n);R(d.n,"JOIN",P)if(C.t.B)R("","331",d.n,P,"No topic is set")G R("","332",d.n,P,C.t)S q;L(C.n)q+=(q.B?"":" ")+*i;R("","353",d.n,"=",P,q)R("","366",d.n,P,"End of NAMES")}}F("PART")if(z<1)R("","461",d.n,"PART","Not enough parameters")G{Z f=0;A&C=c[P];L(C.n)if(*i==d.n)f=1;C.n.remove(d.n);if(f){if(z<2)m.p.push_back(d.n);R(d.n,"PART",P,Q)}G R("","442",d.n,P,"You're not on that channel")}F("TOPIC")if(z<1)R("","461",d.n,"TOPIC","Not enough parameters")G{A&C=c[P];if(z<2){C.t="";R("","331",d.n,P,"No topic is set")}G{C.t=Q;R("","332",d.n,P,C.t)}}F("LIST")if(z<1){L(c){W ss;ss<<i->H.n.size();R("","322",d.n,i->Y,ss.str(),i->H.t.B?"No topic is set":i->H.t)}R("","323",d.n,"End of LIST")}G{W ss;ss<<c[P].n.size();R("","322",d.n,P,ss.str(),c[P].t.B?"No topic is set":c[P].t)R("","323",d.n,"End of LIST")}F("NAMES")if(z<1){L(c){S q;U(i->H.n,j)q+=(q.B?"":" ")+*j;R("","353",d.n,"=",i->Y,q)}R("","366",d.n,"End of NAMES")}G{S q;L(c[P].n)q+=(q.B?"":" ")+*i;R("","353",d.n,"=",P,q)R("","366",d.n,P,"End of NAMES")}F("PRIVMSG")if(z<1)R("","411",d.n,"No recipient given(PRIVMSG)")J(z<2)R("","412",d.n,"No text to send")G{Z f=0;A from=d.n;L(c)if(i->Y==P){f=1;U(i->H.n,k)U(l,j)if(*k==j->n){A d=*j;R(from,"PRIVMSG",d.n,Q)}}if(f==0)L(l)if(i->n==P){f=1;A d=*i;R(from,"PRIVMSG",d.n,Q)}if(f==0)R("","401",d.n,P,"No such nick/channel")}F("USERS")R("","446",d.n,"USERS has been disabled")F("PING")R("","PONG",P,Q)F("PONG")d.p=time(NULL)+60;d.q=0;F("QUIT")if(!z)m.p.push_back(d.n);x(d,P,1);}G{R("","421",d.n,m.c,"Unknown command")}K 0;}M g(char*d){M m;char*n=d;while(*d!='\0'){if(m.c.B){if(*d==':'){for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.f=n+1;n=++d;}for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.c=n;n=++d;}J(*d==':'){for(;*d!='\0';++d);m.p.push_back(n+1);n=++d;}G{for(;*d!='\0'&&*d!=' ';++d);*d='\0';m.p.push_back(n);n=++d;}}K m;}int main(){int r;WSADATA u;SOCKADDR_IN la;la.sin_family=AF_INET;la.sin_port=htons(6667);la.sin_addr.s_addr=htonl(INADDR_ANY);timeval h;h.tv_sec=0;h.tv_usec=10000;fd_set rs,ws,es;D t;t.n="IRCd";X(1,(0!=WSAStartup(MAKEWORD(2,2),&u)))X(2,(I==(t.s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))))X(3,(E==bind(t.s,(SOCKADDR*)&la,sizeof(la))))X(4,(E==listen(t.s,SOMAXCONN)))while(1){M(rs)M(ws)M(es)X(5,(E==select(0,&rs,&ws,&es,&h)))X(6,(FD_ISSET(t.s,&es)))if(FD_ISSET(t.s,&rs)){D d={};d.l=sizeof(d.a);d.s=accept(t.s,(SOCKADDR*)&d.a,&d.l);X(7,(I==d.s))W s;s<<inet_ntoa(d.a.sin_addr)<<":"<<ntohs(d.a.sin_port);d.n=s.str();d.p=time(NULL)+60;d.q=0;l.push_back(d);}L(l){D&d=*i;if(d.p>0&&time(NULL)>d.p){R("","PING",d.n)d.p=0;d.q=time(NULL)+60;}if(d.q>0&&time(NULL)>d.q)x(d,"PONG",1);if(FD_ISSET(d.s,&es))x(d,"select except",0);if(FD_ISSET(d.s,&rs)){int b=recv(d.s,d.b+d.i,sizeof(d.b)-d.i-1>0,0);if(b>0)d.i+=b;G x(d,"recv error",0);char*y=d.b+d.i-2;if(!strcmp(y,"\r\n")){*y++='\0';*y='\0';M m=g(d.b);memset(d.b,0,N);d.i=0;if(d.p>0&&time(NULL)<d.p){d.p=time(NULL)+60;d.q=0;}if(e(d,m))X(0,1)}}}l.remove_if([](const D&d){K d.s==I;});}r=0;f:L(l)x(*i,"exit",0);x(t,"exit",0);WSACleanup();K r;}
```
Here is the mostly ungolfed version (still uses some macros):
```
#include <time.h>
#include <map>
#include <list>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <winSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define READ_BUFFER_SIZE 513
#define EXIT_IF(n,x) if (x) { retval=n; goto finished; };
#define LOOPX(x,it) for (auto it = x.begin(); it != x.end(); ++it)
#define LOOP(x) LOOPX(x,it)
#define LOOP2(x) for (auto it = x.begin(); it != --x.end(); ++it)
#define MAKE_SET(x) FD_ZERO(&x); FD_SET(listener.socket, &x); LOOP(socket_list) { FD_SET(it->socket, &x); }
#define RESPOND(a, b, ...) { message response = {a, b, {__VA_ARGS__}}; tell(data, response); }
#define CASE(x) } else if (!_stricmp(msg.command.c_str(),x)) { std::cout << "Received " << x << " from " << data.nickname << std::endl;
struct channel { std::string topic; std::list<std::string> nicknames; };
struct message { std::string prefix; std::string command; std::vector<std::string> params; };
struct socket_data { SOCKET socket; SOCKADDR_IN address; int mode,address_length,read_buffer_index; char read_buffer[READ_BUFFER_SIZE]; std::string nickname,username,servername,realname; time_t ping_timer,pong_timer; };
std::map<std::string,channel> channels;
std::list<socket_data> socket_list;
void tell(socket_data data, message msg);
void disconnect(socket_data& target, std::string reason, bool notify)
{
LOOP(channels) it->second.nicknames.remove(target.nickname);
LOOP(socket_list)
{
auto data = *it;
if (data.nickname != target.nickname) RESPOND(data.nickname, "QUIT", target.nickname, reason)
else if (notify) RESPOND("", "ERROR", "QUIT", reason)
}
closesocket(target.socket);
target.socket = INVALID_SOCKET;
std::cout << "Disconnected " << target.nickname << " reason=" << reason << std::endl;
}
void print(socket_data data, message msg, char *heading)
{
std::cout << heading << ":\n " << inet_ntoa(data.address.sin_addr) << ":" << ntohs(data.address.sin_port) << "\n";
if (!msg.prefix.empty()) std::cout << " Prefix=" << msg.prefix << "\n";
std::cout << " Command=" << msg.command;
int count = 0; LOOP(msg.params) std::cout << "\n Param[" << count++ << "]=" << *it;
std::cout << std::endl;
}
void tell(socket_data data, message msg)
{
print(data, msg, "Response");
std::string str = (!msg.prefix.empty() ? ":" + msg.prefix + " " : "") + msg.command;
LOOP2(msg.params) str += " " + *it;
str += " :" + *msg.params.rbegin() + "\r\n";
int start = 0;
do
{
int bytes = send(data.socket, str.c_str() + start, str.size() - start, 0);
if (bytes > 0) start += bytes; else disconnect(data, "send error", 0);
}
while (str.size() - start > 0);
}
bool process(socket_data &data, message msg)
{
print(data, msg, "Request");
auto size = msg.params.size();
auto first = size<1 ? "" : msg.params[0], second = size<2 ? "" : msg.params[1];
if (!_stricmp(msg.command.c_str(), "DIE")) { return true;
// and now all the cases
CASE("KILL") if (size<1)
RESPOND("", "461", data.nickname, "USER", "Not enough parameters")
else
{
bool found = false;
LOOP(socket_list) if (it->nickname == first) { found = true; disconnect((*it), first, 1); }
if (found == false) RESPOND("", "401", data.nickname, first, "No such nick/channel")
}
CASE("NICK") if (size<1)
RESPOND("", "431", data.nickname, "No nickname given")
else
{
bool found = false;
LOOP(socket_list) if (it->nickname == first) found = true;
if (found == true) RESPOND("", "433", data.nickname, "Nickname is already in use")
else data.nickname = first;
}
CASE("USER") if (size<4)
RESPOND("", "461", data.nickname, "USER", "Not enough parameters")
else
{
bool found = false;
LOOP(socket_list) if (it->username == first) found = true;
if (found == true) RESPOND("", "462", data.nickname, "Unauthorized command (already registered)")
else
{
data.username = first; data.mode = atoi(second.c_str()); data.servername = msg.params[2]; data.realname = msg.params[3];
RESPOND("", "001", data.nickname, "Welcome to the Internet Relay Network " + data.nickname + "!" + data.username + "@" + data.servername)
}
}
CASE("MODE") if (size<1)
RESPOND("", "461", data.nickname, "MODE", "Not enough parameters")
else if (first == data.nickname)
{
if (size < 2)
RESPOND("", "221", data.nickname, std::string("") + (data.mode & 2 ? "+w" : "-w") + (data.mode & 3 ? "+i" : "-i"))
else
{
auto x = (147 - second[1]) / 14;
if (second[0] == '+')
{
data.mode |= 1 << x;
std::cout << "set " << first << " mode bit " << x << "w=2, i=3" << std::endl;
}
else
{
data.mode &= ~(1 << x);
std::cout << "clear " << first << " mode bit " << x << "w=2, i=3" << std::endl;
}
}
}
else
RESPOND("", "477", data.nickname, first, "Channel doesn't support modes")
CASE("WHOIS") if (size < 1)
RESPOND("", "431", data.nickname, "No nickname given")
else
{
bool found = false;
LOOP(socket_list) if (it->nickname == first) { found = true; RESPOND("", "311", data.nickname, (it->nickname, it->username, it->servername, "*", it->realname)) }
if (found == true) RESPOND("", "318", data.nickname, first, "End of WHOIS")
else RESPOND("", "401", data.nickname, first, "No such nick/channel")
}
CASE("WHO") LOOP(channels[first].nicknames) LOOPX(socket_list, dit) if (*it == dit->nickname)
RESPOND("", "352", data.nickname, first, dit->username, dit->servername, "*", dit->nickname, "", dit->realname)
RESPOND("", "315", data.nickname, first, "End of WHO")
CASE("JOIN") if (size < 1)
RESPOND("", "461", data.nickname, "JOIN", "Not enough parameters")
else if (first == "0")
LOOP(channels) { LOOPX(it->second.nicknames, dit) if (*dit == data.nickname) RESPOND("","PART", it->first, data.nickname) it->second.nicknames.remove(data.nickname); }
else
{
auto& channel = channels[first];
bool found = false;
LOOP(channel.nicknames) if (*it == data.nickname) { found = true; }
if (found == false)
{
channel.nicknames.push_back(data.nickname);
RESPOND(data.nickname, "JOIN", first)
if (channel.topic.empty()) RESPOND("", "331", data.nickname, first, "No topic is set")
else RESPOND("", "332", data.nickname, first, channel.topic)
std::string list; LOOP(channel.nicknames) list += (list.empty() ? "" : " ") + *it;
RESPOND("", "353", data.nickname, "=", first, list)
RESPOND("", "366", data.nickname, first, "End of NAMES")
}
}
CASE("PART") if (size < 1)
RESPOND("", "461", data.nickname, "PART", "Not enough parameters")
else
{
bool found = false;
auto &channel = channels[first];
LOOP(channel.nicknames) if (*it == data.nickname) found = true;
channel.nicknames.remove(data.nickname);
if (found)
{
if (size < 2) msg.params.push_back(data.nickname);
RESPOND(data.nickname, "PART", first, second)
}
else RESPOND("", "442", data.nickname, first, "You're not on that channel")
}
CASE("TOPIC") if (size < 1)
RESPOND("", "461", data.nickname, "TOPIC", "Not enough parameters")
else
{
auto& channel = channels[first];
if (size < 2) { channel.topic = ""; RESPOND("", "331", data.nickname, first, "No topic is set") }
else { channel.topic = second; RESPOND("", "332", data.nickname, first, channel.topic) }
}
CASE("LIST") if (size < 1)
{
LOOP(channels)
{
std::stringstream ss; ss << it->second.nicknames.size();
RESPOND("", "322", data.nickname, it->first, ss.str(), it->second.topic.empty() ? "No topic is set" : it->second.topic)
}
RESPOND("", "323", data.nickname, "End of LIST")
}
else
{
std::stringstream ss; ss << channels[first].nicknames.size();
RESPOND("", "322", data.nickname, first, ss.str(), channels[first].topic.empty() ? "No topic is set" : channels[first].topic)
RESPOND("", "323", data.nickname, "End of LIST")
}
CASE("NAMES") if (size < 1)
{
LOOP(channels)
{
std::string list; LOOPX(it->second.nicknames, dit) list += (list.empty() ? "" : " ") + *dit;
RESPOND("", "353", data.nickname, "=", it->first, list)
}
RESPOND("", "366", data.nickname, "End of NAMES")
}
else
{
std::string list; LOOP(channels[first].nicknames) list += (list.empty() ? "" : " ") + *it;
RESPOND("", "353", data.nickname, "=", first, list)
RESPOND("", "366", data.nickname, first, "End of NAMES")
}
CASE("PRIVMSG") if (size < 1)
RESPOND("", "411", data.nickname, "No recipient given (PRIVMSG)")
else if (size < 2)
RESPOND("", "412", data.nickname, "No text to send")
else
{
bool found = false;
auto from = data.nickname;
LOOP(channels) if (it->first == first)
{
found = true;
LOOPX(it->second.nicknames, nit) LOOPX(socket_list, dit) if (*nit == dit->nickname) { auto data = *dit; RESPOND(from, "PRIVMSG", data.nickname, second) }
}
if (found == false)
LOOP(socket_list) if (it->nickname == first)
{
found = true;
auto data = *it; RESPOND(from, "PRIVMSG", data.nickname, second)
}
if (found == false)
RESPOND("", "401", data.nickname, first, "No such nick/channel")
}
CASE("USERS") RESPOND("", "446", data.nickname, "USERS has been disabled")
CASE("PING") RESPOND("", "PONG", first, second)
CASE("PONG") data.ping_timer = time(NULL) + 60; data.pong_timer = 0;
CASE("QUIT") if (!size) msg.params.push_back(data.nickname);
disconnect(data, first, 1);
// end of the cases
} else {
std::cout << "Received invalid message from " << data.nickname << " msg=" << msg.command << std::endl;
RESPOND("", "421", data.nickname, msg.command, "Unknown command")
}
return false;
}
message parse(char *data)
{
message msg;
char *pointer = data;
while (*data != '\0')
{
if (msg.command.empty())
{
if (*data == ':')
{
for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
msg.prefix = pointer + 1;
pointer = ++data;
}
for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
msg.command = pointer;
pointer = ++data;
}
else if (*data == ':')
{
for (; *data != '\0'; ++data);
msg.params.push_back(pointer+1);
pointer = ++data;
}
else
{
for (; *data != '\0' && *data != ' '; ++data); *data = '\0';
msg.params.push_back(pointer);
pointer = ++data;
}
}
return msg;
}
int main()
{
int retval;
WSADATA wsaData;
SOCKADDR_IN listen_address; listen_address.sin_family = AF_INET; listen_address.sin_port = htons(6667); listen_address.sin_addr.s_addr = htonl(INADDR_ANY);
timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 10000;
fd_set socket_read_set, socket_write_set, socket_except_set;
socket_data listener; listener.nickname = "IRCd";
EXIT_IF(1, (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)))
EXIT_IF(2, (INVALID_SOCKET == (listener.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))))
EXIT_IF(3, (SOCKET_ERROR == bind(listener.socket, (SOCKADDR *)&listen_address, sizeof(listen_address))))
EXIT_IF(4, (SOCKET_ERROR == listen(listener.socket, SOMAXCONN)))
while (1)
{
MAKE_SET(socket_read_set) MAKE_SET(socket_write_set) MAKE_SET(socket_except_set)
EXIT_IF(5, (SOCKET_ERROR == select(0, &socket_read_set, &socket_write_set, &socket_except_set, &timeout)))
EXIT_IF(6, (FD_ISSET(listener.socket, &socket_except_set)))
if (FD_ISSET(listener.socket, &socket_read_set))
{
socket_data data = {}; // zero everything
data.address_length = sizeof(data.address);
data.socket = accept(listener.socket, (SOCKADDR *)&data.address, &data.address_length);
EXIT_IF(7, (INVALID_SOCKET == data.socket))
std::stringstream ss; ss << inet_ntoa(data.address.sin_addr) << ":" << ntohs(data.address.sin_port); data.nickname = ss.str();
data.ping_timer = time(NULL)+60; data.pong_timer = 0;
socket_list.push_back(data);
std::cout << "Connected " << data.nickname << " ping=" << data.ping_timer << std::endl;
}
LOOP(socket_list)
{
socket_data &data = *it;
if (data.ping_timer > 0 && time(NULL) > data.ping_timer)
{
RESPOND("", "PING", data.nickname)
data.ping_timer = 0; data.pong_timer = time(NULL) + 60;
std::cout << "Sent PING to " << data.nickname << " pong=" << data.pong_timer << std::endl;
}
if (data.pong_timer > 0 && time(NULL) > data.pong_timer) disconnect(data, "PONG", 1);
if (FD_ISSET(data.socket, &socket_except_set)) disconnect(data, "select except", 0);
if (FD_ISSET(data.socket, &socket_read_set))
{
int bytes = recv(data.socket, data.read_buffer + data.read_buffer_index, sizeof(data.read_buffer) - data.read_buffer_index - 1 > 0, 0);
if (bytes > 0) data.read_buffer_index += bytes; else disconnect(data, "recv error", 0);
char *pointer = data.read_buffer + data.read_buffer_index - 2;
if (!strcmp(pointer, "\r\n"))
{
*pointer++ = '\0'; *pointer = '\0'; // remove the \r\n
message msg = parse(data.read_buffer);
memset(data.read_buffer, 0, READ_BUFFER_SIZE); data.read_buffer_index = 0;
if (data.ping_timer > 0 && time(NULL) < data.ping_timer)
{
data.ping_timer = time(NULL) + 60; data.pong_timer = 0;
std::cout << "Reset ping for " << data.nickname << " ping=" << data.ping_timer << std::endl;
}
if (process(data, msg)) EXIT_IF(0, true)
}
}
}
socket_list.remove_if([](const socket_data& data){ return data.socket == INVALID_SOCKET; });
}
retval = 0;
finished:
LOOP(socket_list) disconnect(*it, "exit", 0);
disconnect(listener, "exit", 0);
WSACleanup();
return retval;
}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 1 year ago.
[Improve this question](/posts/20531/edit)
Create a Tic-Tac-Toe game that allows two human players to play against each other using two networked devices.
Requirements:
1. Network play.
2. Program must let both players know whose turn it is.
3. Program must show who won and how (like drawing a line through the three in a row).
4. Graphical game board displayed for both players.
5. Player moves inputted "graphically" (point and click, etc...).
6. Enforce all Tic-Tac-Toe rules.
Preferred:
1. Any libraries are allowed but smaller libraries are better.
2. Support as many different platforms/devices as possible.
3. Make it "pretty".
I would love to invent scoring that would take into account the "Preferred" points, but that appears impossible. So vote for the code that does the best on the "Preferred" points.
Scoring:
* `byte count / vote count`
* lowest score wins
[Answer]
# PHP, work in progress (474 chars / 2 upvotes = 237 score)
It's fully functional except it doesn't have win detection yet.
>
> 
>
>
>
What I *really* like about this solution is that I only learned PHP about 3 days ago, so the code is probably terrible. :D
### t.php, 474 chars (newlines can be removed and are there only for readability):
```
<style>#d>*{display:block;border:1px solid #000;width:50px;height:50px;float:left;text-align:center}#d{width:160px}</style><div id=d><?php
$f=file("a");$p=$_GET["p"];if($p!="x"&&$p!="o")die();
if(isset($_GET["m"])){$s=$f[0];$s[intval($_GET["m"])]=$p;fwrite(fopen('a','w'),$s.($f[1]=='x'?'o':'x'));echo"<a href='t.php?p=$p'>back</a>";}
else{$i=0;while($i<9){$s=($p==$f[1]&&$f[0][$i]=='.')?'a':'div';echo"<$s href='t.php?p=$p&m=$i'>".$f[0][$i++]."</$s>";}echo $f[1]."'s turn";}
?>
```
### reset.php, 57 chars
```
<?php fwrite(fopen('a','w'),"..........\nx");?>Reset done
```
---
It's live on my website. Player X should go to this URL:
```
http://keyboardfire.com/misc/tictactoegolf/t.php?p=x
```
And Player O should go here:
```
http://keyboardfire.com/misc/tictactoegolf/t.php?p=o
```
(don't worry, I added a check that only lets player "o" or "x" in so that you can't do any fancy XSS stuff :P)
To reset, go here:
```
http://keyboardfire.com/misc/tictactoegolf/reset.php
```
Obviously, it's really easy to cheat (moving for the other player, randomly resetting the board, etc.), but it's code golf so it doesn't matter :P
] |
[Question]
[
Using any programming language that supports functions, have the function
```
is_enough(strArr)
```
that take `strArr` which will be an an array consisting of the following elements:
* `N` which will be the number of gas stations in a circular route
* and each subsequent element will be the string `g:c` where
+ `g` is the amount of gas in gallons at that gas station and
+ `c` will be the amount of gallons of gas needed to get to the following gas station.
For example `strArr` may be:
```
["4","3:1","2:2","1:2","0:1"].
```
Your goal is to return the index of the starting gas station that will allow you to travel around the whole route once, otherwise return the string *"impossible"*.
For the example above there are *4* gas stations, and your program should return the string *"1"* because:
* Starting at station *1* you receive *3* gallons of gas and spend *1* getting to the next station.
* Then you have *2* gallons + *2* more at the next station and you spend *2* so you have *2* gallons when you get to the 3rd station.
* You then have *3* but you spend *2* getting to the final station,
* At the final station you receive *0* gallons and you spend your final gallon getting to your starting point.
Starting at any other gas station would make getting around the route impossible, so the answer is *"1"*.
If there are multiple gas stations that are possible to start at, return the smallest index (of the gas station). `N` will be `>= 2`.
Correct Sample Outputs:
```
Input: ["4","1:1","2:2","1:2","0:1"]
Output: "impossible"
Input: ["4","0:1","2:2","1:2","3:1"]
Output: "4"
```
The winner will be the one to use the shortest code although it will be long.
[Answer]
## APL (70)
```
{×⍴G←Z/⍨0∧.≤¨+\¨¯1⌽⌽∘K¨Z←⍳⍴K←{⎕ML←3⋄-/⍎¨⍵⊂⍨⍵≠':'}¨1↓⍵:⊃G⋄'impossible'}
```
Explanation:
* `1↓⍵`: drop the first element (length), we don't need it
* `{`...`}¨`: for each of the gas stations...
+ `⎕ML←3`: set `⎕ML` to 3 within the inner function (changes behaviour of `⊂`)
+ `⍵⊂⍨⍵≠':'`: split the string on `:`
+ `⍎¨`: evaluate each part
+ `-/`: subtract the second number from the first (giving net effect for each gas station)
* `K←`: store them in K
* `Z←⍳⍴K`: get the indices for the gas station (`1` to length of `K`), store in `Z`
* `⌽∘K¨Z`: rotate `K` by each value of `Z`, giving an array of arrays
* `¯1⌽`: rotate this array to the left by 1 (to put the unchanged one first instead of last)
* `+\¨`: make a running sum for each inner array
* `0∧.≤¨`: for each running sum, see if there are negative values
* `Z/⍨`: select from `Z` those elements for which the running sum had no negative values
* `×⍴G←`: store in `G`. If `G` has any elements:
* `:⊃G`: return the first element of `G`.
* `⋄'impossible'`: otherwise, return `impossible`.
[Answer]
# Bash 178 170 161 157
Rather straight forward.
```
is_enough(){((t=(n=$1-1)<0))&&echo impossible||(x=(n ${@:3} $2);for z in ${@:2};do(((t+=${z%:*}-${z#*:})<0))&&is_enough ${x[*]}&&return;done;echo $[$#-++n])}
```
Spaced out:
```
is_enough() {
((t=(n=$1-1)<0)) && echo impossible || (
x=(n ${@:3} $2);
for z in ${@:2};do
(((t+=${z%:*}-${z#*:})<0)) && is_enough ${x[*]} && return;
done;
echo $[$#-++n]
)
}
```
[Answer]
## Ruby, 111
Here's a Ruby solution using `eval`:
```
is_enough=->a{_,*s=a
"#{(1..s.size).find{|i|g=0;s.rotate(i-1).all?{|x|g+=eval x.tr ?:,?-;g>=0}}||:impossible}"}
```
Example usage:
```
is_enough[%w(4 3:1 2:2 1:2 0:1)] #=> "1"
is_enough[%w(4 1:1 2:2 1:2 0:1)] #=> "impossible"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 1:2 2:1 4:3 0:1)] #=> "2"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 0:1 0:1 4:1 0:1)] #=> "3"
is_enough[%w(8 0:1 0:1 4:1 0:1 2:1 3:1 0:0 0:1)] #=> "3"
```
**EDIT**: Corrected function name and return type.
[Answer]
# Ruby 132
```
g=->a{n,*a=a.map{|e|e.split(?:).map &:to_i}
(r=(0...n[0]).find{|i|a.rotate(i).inject(0){|m,(j,k)|m&&m>=0&&m+j-k}})?r+1:"impossible"}
```
Test:
```
irb(main):003:0> g[["4","1:1","2:2","1:2","0:1"]]
=> "impossible"
irb(main):004:0> g[["4","0:1","2:2","1:2","3:1"]]
=> 4
```
[Answer]
## Python, 131
I find this one-liner fairly satisfying.
```
E=lambda s:([`i`for i in range(1,len(s)+1)if reduce(lambda r,t:r+eval(t[0]+'-'+t[-1])*(r>=0),s[i:]+s[1:i],0)>=0]+['impossible'])[0]
```
[Answer]
## GolfScript (72 chars)
```
{(~\{':'/{~}/-}%[\),1>{;.{1$-1>*+}*-1>\(+\},~"impossible"]1=}:is_enough;
```
[Online demo](http://golfscript.apphb.com/?c=eyh%2BXHsnOicve359Ly19JVtcKSwxPns7LnsxJC0xPiorfSotMT5cKCtcfSx%2BImltcG9zc2libGUiXTE9fTppc19lbm91Z2g7CgpbIjQiICIxOjEiICIyOjIiICIxOjIiICIwOjEiXWlzX2Vub3VnaCBwClsiNCIgIjA6MSIgIjI6MiIgIjE6MiIgIjM6MSJdaXNfZW5vdWdoIHAKWyI0IiAiMzoxIiAiMDoxIiAiMjoyIiAiMToyIl1pc19lbm91Z2ggcA%3D%3D)
This performs the obvious brute force approach. The most interesting bit IMO is the determination of whether the partial sums of an array of delta-fuel ever drops below 0:
```
{1$-1>*+}*-1>
```
This saves 1 char over the more obvious
```
[{1$+}*]{0<},!
```
If the output were indexed at 0 rather than at 1, an alternative approach to rotating the array would be preferable:
```
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;
```
But this approach isn't easily adopted to indexing at 1:
```
{(;{':'/{~}/-}%:A[,),1>{A\({(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;
```
or
```
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},{)}%~"impossible"]0=}:is_enough;
```
] |
[Question]
[
In this challenge, you will recieve a comma-separated list of weights as input, such as
```
1,3,4,7,8,11
```
And you must output the smallest amount of weights that can add to that set. For example, the output for this set would be
```
1,3,7
```
Because you could represent all of those weights with just those three:
```
1 = 1
3 = 3
1+3 = 4
7 = 7
1+7 = 8
1+3+7 = 11
```
There may be more than one solution. For example, your solution for the input `1,2` could be `1,1` or `1,2`. As long as it finds the minimum amount of weights that can represent the input set, it is a valid solution.
Weights may not be used more than once. If you need to use one twice, you must output it twice. For example, `2,3` is not a valid solution for `2,3,5,7` because you can't use the `2` twice for `2+2+3=7`.
Input is guaranteed not to have duplicated numbers.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code by character count wins.
Network access is forbidden (so none of your "clever" `wget` solutions @JohannesKuhn [*cough*](https://codegolf.stackexchange.com/a/12960/3808) [*cough*](https://codegolf.stackexchange.com/a/12813/3808)) `;)`
Simpleest cases:
```
1,5,6,9,10,14,15 => 1,5,9
7,14,15,21,22,29 => 7,14,15
4,5,6,7,9,10,11,12,13,15,16,18 => 4,5,6,7
2,3,5,7 => 2,2,3 or 2,3,7
```
And some trickier ones:
```
10,16,19,23,26,27,30,37,41,43,44,46,50,53,57,60,61,64,68,71,77,80,84,87
=> 3,7,16,27,34
20,30,36,50,56,63,66,73,79,86
=> 7,13,23,43
27,35,44,46,51,53,55,60,63,64,68,69,72,77,79,81,86,88,90,95,97,105,106,114,123,132
=> 9,18,26,37,42
```
[Answer]
# Mathematica ~~80~~ 75
Update: See at bottom an update on Doorknob's challenging last test, added on Nov.5
---
This passes all but the last test. However, it does **not** attempt to use a digit more than once. And it only searches from solutions that are subsets of the larger data set.
The function generates all of the subsets of the input data set and then tests which subsets can be used to construct the complete set. After the viable subsets are found, it chooses the smallest sets.
```
s=Subsets
f@i_:=GatherBy[Select[s@i,Complement[i, Total /@ s@#]=={}&],Length]〚1〛
```
**Tests**
```
f[{1, 3, 4, 7, 8, 11}]
```
>
> {{1, 3, 7}}
>
>
>
---
```
f[{1, 5, 6, 9, 10, 14, 15}]
```
>
> {{1, 5, 9}}
>
>
>
---
```
f[{7, 14, 15, 21, 22, 29}]
```
>
> {{7, 14, 15}}
>
>
>
---
```
f[{4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18}]
```
>
> {{4, 5, 6, 7}}
>
>
>
---
```
f[{2, 3, 5, 7}]
```
>
> {{2, 3, 5}, {2, 3, 7}}
>
>
>
---
## Update
Below I'll provide an initial analysis that may help get started toward a solution.
The data:
```
data = {10, 16, 19, 23, 26, 27, 30, 37, 41, 43, 44, 46, 50, 53, 57, 60, 61, 64, 68, 71, 77, 80, 84, 87};
```
Differently from the earlier approach, we want to consider, in the solution set, numbers that do NOT appear in the data set.
The approach makes use of absolute differences between pairs of numbers in the data set.
```
g[d_] := DeleteCases[Reverse@SortBy[Tally[Union[Sort /@ Tuples[d, {2}]] /. {a_, b_} :> Abs[a - b]], Last], {0, _}]
```
Let's look at the number of times each difference appears; we'll only grab the first 8 cases, starting from the most common difference].
```
g[data][[1;;8]]
```
>
> {{7, 14}, {27, 13}, {34, 12}, {3, 11}, {20, 10}, {16, 10}, {4,
> 10}, {11, 9}}
>
>
>
14 pairs differed by 7; 13 pairs differed by 27, and so on.
Now let's test subsets starting with {difference1},{difference1, difference2}, and so on, until we can hopefully account for all the original elements in the data set.
`h` reveals those numbers from the original set that cannot be constructed by composing sums from the subset.
```
h[t_] := Complement[data, Total /@ Subsets@t]
```
By the fifth try, there are still 10 elements that cannot be formed from {7, 27, 34, 3, 20}:
```
h[{7, 27, 34, 3, 20}]
```
>
> {16, 19, 26, 43, 46, 53, 60, 77, 80, 87}
>
>
>
But on the next try, all numbers of the data set are accounted for:
```
h[{7, 27, 34, 3, 20, 16}]
```
>
> {}
>
>
>
This is still not as economical as {3,7,16,27,34}, but it's close.
---
There are still some additional things to take into account.
1. If 1 is in the data set, it will be required in the solution set.
2. There may well be some "loners" in the original set that cannot be composed from the most common differences. These would need to be included apart from the difference tests.
These are more issues than I can handle at the moment. But I hope it sheds some light on this very interesting challenge.
[Answer]
Ruby 289
This is a straight enumeration, so it will obtain minimal solutions, but it may take years--possibly light years--to solve some problems. All the "simplest cases" solve in at most a few seconds (though I got 7,8,14 and 1,2,4 for the 3rd and 5th cases, respectively). Tricky #2 solved in about 3 hours, but the other two are just too big for enumeration, at least for the way I've gone about it.
An array of size `n` that generates the given array by summing subsets of its elements is of minimal size if it can be shown that there is no array of size `< n` that does that. I can see no other way to prove optimality, so I start the enumeration with subsets of size `m`, where `m` is a known lower bound, and then increase the size to `m+1` after having enumerated subsets of size `m` and shown they none of those "span" the given array, and so on, until I find an optimum. Of course, if I have enumerated all subsets up to size n, I could use a heuristic for size n+1, so that if I found a spanning array of that size, I would know it is optimal. Can anyone suggest an alternative way to prove a solution is optimal in the general case?
I've included a few optional checks to eliminate some combinations early on. Removing those checks would save 87 characters. They are as follows (`a` is the given array):
* an array of size `n` can generate at most `2^n-1` distinct positive numbers; hence, `2^n-1 >= a.size`, or `n >= log2(a.size).ceil` (the "lower bound" I referred to above).
* a candidate generating array `b` of size `n` can be ruled out if:
+ `b.min > a.min`
+ `sum of elements of b < a.max` or
+ `b.max < v`, where `v = a.max.to_f/n+(n-1).to_f/2.ceil` (`to_f` being conversion to float).
The last of these, which is checked first, implements
```
sum of elements of b <= sum(b.max-n+1..b.max) < a.max
```
Note `v` is constant for all generator arrays of size `n`.
I've also made use of @cardboard\_box's very helful observation that there is no need to consider duplicates in the generating array.
In my code,
```
(1..a.max).to_a.combination(n)
```
generates all combinations of the numbers 1 to `a.max`, taken `n` at a time (where `a.max = a.last = a[-1]`). For each combination `b`:
```
(1...2**n).each{|j|h[b.zip(j.to_s(2).rjust(n,?0).split('')).reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0}
```
fills a hash `h` with all numbers that are sums over non-empty subsets of `b`. The hash keys are those numbers; the values are arbitrary. (I chose to set the latter to zero.)
```
a.all?{|e|h[e]}}
```
checks whether every element of the given array `a` is a key in the hash (`h[e] != nil`, or just `h[e]`).
Suppose
```
n = 3 and b=[2,5,7].
```
Then we iterate over the range:
```
(1...2**8) = (1...8) # 1,2,..,7
```
The binary representation of each number in this range is used to stab out the elements of `b` to sum. For `j = 3` (`j` being the range index),
```
3.to_s(2) # => "11"
"11".rjust(3,?0) # => "011"
"011".split('') # => ["0","1","1"]
[2,5,7].zip(["1","0","1"]) # => [[2,"0"],[5,"1"],[7,"1"]]
[[2,"0"],[5,"1"],[7,"1"]].reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0 # => t = 0+5+7 = 12
```
The code:
```
x=a[-1]
n=Math.log2(a.size).ceil
loop do
v=(1.0*x/n+(n-1)/2.0).ceil
(1..x).to_a.combination(n).each{|b|
next if b[-1]<v||b[0]>a[0]||b.reduce(&:+)<x
h={}
(1...2**n).each{|j|h[b.zip(j.to_s(2).rjust(n,?0).split('')).reduce(0){|t,(u,v)|t+(v==?1?u:0)}]=0}
(p b;exit)if a.all?{|e|h[e]}}
n+=1
end
```
] |
[Question]
[
Your task is to write a program that will take input like this:
```
a + b * c + a / 2
```
and will *generate the source code for a program* that takes user input and then evaluates the expression.
The expression can contain the operators `+`,`-`,`*`,`/`; single-letter lowercase variables; and integers between 0 and 32000. Standard arithmetic precedence must be correctly followed. The expression is limited to 26 unique variables a to z. However, a single variable can appear more than once.
You can assume that the input expression is valid (follows these rules).
The generated program must prompt for user input in this form, prompting only once for each variable:
```
a =
```
User input from 0 to 32000 should be handled correctly. It will then print the expression and the correct result. You can use either integer or floating point arithmetic. The calculations should be performed with at least 32 bit precision. Beyond that, you don't have to worry about overflow or divide by zero.
Example of a non-golfed generated Perl program for the above expression:
```
print "a = ";
my $a = <>;
print "b = ";
my $b = <>;
print "c = ";
my $c = <>;
print "a + b * c + a / 2 = " . ($a + $b * $c + $a / 2);
```
Example input and output of program generated for above expression:
```
a = 1
b = 2
c = 3
a + b * c + a / 2 = 7.5
```
The score is calculated as length of the program + length of the generated program for this expression:
```
1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000
```
Lowest score wins.
**Update:** Just to highlight a couple of requirements of the problem, as stated above:
* The output of the program must be *source code for another program* that evaluates the expression.
* The program must *print the original expression*. Perhaps there is some ambiguity in this (one could argue that `a+b` is the same expression as `a + b`), but for clarity let's say that it must be the original expression with white space intact. All valid answers so far have done it that way.
[Answer]
### Perl, 80 + 110 = 190
Directly inspired by another (now deleted) answer in Ruby. Requires Perl ≥ v5.14.
Following the usual rule I've seen of command-line switches counting as one character.
```
#!/usr/bin/perl -n
chomp;print'print $_="',$_,'"," = ",eval(s#\pL#${$&}//=do{print"$& = ";<>}#ger)'
```
### Perl, 80 + 231 = 311
Because eval'ing in the output feels cheap.
```
#!/usr/bin/perl -p
chomp;print"print '$_ = ',";s/\pL/$s{$&}++?"\$$&":"do{print'$& = ';\$$&=<>}"/ge
```
Seems like the output could be shortened by moving the prompting into a sub, but I've run out of enthusiasm.
[Answer]
## Lua, 202 + 166 = 368
File "generate\_code.lua"
```
F=...
C='function G(v)io.write(v.." = ")_G[v]=io.read"*n"end 'V={}for v in F:gmatch'%l'do V[v]=0 end
for v in pairs(V)do C=C..'G"'..v..'"'end
print(C..'F="'..F..'"print(F.." = "..load("return "..F)())')
```
Usage:
```
$ lua generate_code.lua "1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000"
```
Code generated (order of variables is not specified):
```
function G(v)io.write(v.." = ")_G[v]=io.read"*n"end G"g"G"e"G"d"G"b"G"a"G"h"F="1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000"print(F.." = "..load("return "..F)())
```
Generated code in action:
```
g = 4
e = 3
d = 2
b = 1
a = 6.5
h = 4.3
1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 = 29787.941860465
```
[Answer]
## Tcl 198 + 155 = 352
```
gets stdin i;puts [string map [list @ [lsort -u [regexp -all -inline {[a-z]} $i]] & [regsub -all {[a-z]} [join $i {}] {$\0}] | $i] {foreach va {@} {puts "$va =";gets stdin $va};puts "| = [expr &]"}]
```
generates
```
foreach va {a b d e g h} {puts "$va =";gets stdin $va};puts "1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 = [expr 1+$a*4*$b+2/$d*$e-$a-3+$g/$h*32000]"
```
[Answer]
## Python 125 + 151 = 276
```
>>> t=raw_input();z=sorted(set(filter(str.isalpha,t)));print','.join(z)+'=[input(x+" = ")for x in%r];print"%s =",%s'%(z,t,t[::2])
1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000
a,b,d,e,g,h=[input(x+" = ")for x in['a', 'b', 'd', 'e', 'g', 'h']];print"1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 =",1+a*4*b+2/d*e-a-3+g/h*300
```
Now executing it:
```
>>> exec"""a,b,d,e,g,h=[input(x+" = ")for x in['a', 'b', 'd', 'e', 'g', 'h']];print"1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 =",1+a*4*b+2/d*e-a-3+g/h*300"""
a = 1
b = 2
d = 3
e = 4
g = 5
h = 6
1 + a * 4 * b + 2 / d * e - a - 3 + g / h * 32000 = 5
```
] |
[Question]
[
## Introduction
In Android Studio and other IDEs there are code completions to assist efficient code insertion (especially when the names of the classes or methods are so verbose), like the one in the image below.
[](https://i.stack.imgur.com/5sGzc.png)
There are slightly different logics used between IDEs to determine what classes, methods and variables to suggest, but otherwise are common: typing the initial letters of each word, and the identifier matching those initial letters will be suggested.
## Challenge
In this challenge, write a program or function which receives two strings, namely `input` and `identifier`, determine whether the `identifier` matches the `input`.
We split `identifier` into words where:
* a lowercase letter is followed by an uppercase letter (`"SplitHere" -> "Split", "Here"`),
* an uppercase letter is followed by an uppercase letter and a lowercase letter (`"SPLITHere" -> "SPLIT", "Here"`), or
* there is a number or an underscore `_` (`"SPLIT_HERE" -> "SPLIT", "HERE"`).
If this is still not clear enough, here is the regex representing the condition to split: `(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|[_0-9]`. Here are a few samples:
* `theWord_Example`, in which 3 words (`the`, `Word`, `Example`) can be found.
* `THEWORD2EXAMPLE`, in which only 2 words (`THEWORD`, `EXAMPLE`) can be found (because `THEWORD` is a run of uppercase letters and so does `EXAMPLE`).
* `THEWordEXAMPLE3`, in which 3 words (`THE`, `Word`, `Example`) can be found (`Word` is considered to be a separate word here).
* `THEWORDEXAMPLEFOUR`, in which only 1 words (`THEWORDEXAMPLEFOUR`) can be found (the whole run of uppercase letters).
For this purpose here we use a simplified version. In reality the logic is far more complex. In this version there are only two rules:
1. If `input` consists of only lowercase letters, then an `identifier` matches the `input` only if there is a splitting of `input` into substrings, that for each substring there is a word within the `identifier` starting with that substring, in that exact order.
>
> Example input: `sbo`
>
>
> Truthy cases: `**S**QLite**B**ind**O**rColumnIndexOutOfRangeException`, `**S**parse**Bo**oleanArray`, **(UPDATE)** `**S**tringIndexOutOf**Bo**undException`
>
>
> Falsy cases: `SeekBar` (missing `o`), `**S**tatus**B**arN**o**tification` (the `o` is not at the beginning of a word)
>
>
>
2. If `input` contains uppercase letters, then a split on the `input` must be made before each uppercase letter when applying Rule 1.
>
> Example input: `sbO`
>
>
> Truthy cases: `**S**QLite**B**ind**O**rColumnIndexOutOfRangeException`
>
>
> Falsy cases: `**S**parse**Bo**oleanArray` (the `O` must appear at the beginning of a word), `**S**tringIndex**O**utOf**B**oundException` (wrong order)
>
>
>
## I/O
**Input**: two strings, one for `input` and one for `identifier`. You can assume that the regex `[A-Za-z]+` matches `input` and the regex `[A-Za-z0-9_]` matches `identifier`.
**Output**: one of the truthy or falsy values. You can choose what value to return as truthy and what as falsy, but your choice must be consistent across all cases. For example you can return `1/0`, `true/false`, `π/e` or whatever, but they must stay the same across all cases.
## Test cases
Each line consists of two strings, namely `input` and `identifier` respectively.
Truthy cases:
```
"sbo" "SparseBooleanArray"
"sbo" "StringIndexOutOfBoundException"
"sbo" "SQLiteBindOrColumnIndexOutOfRangeException"
"sbO" "SQLiteBindOrColumnIndexOutOfRangeException"
"Al" "ArrayList"
"AL" "ArrayList"
"Al" "ALARM_SERVICE"
"As" "ALARM_SERVICE"
"AS" "ALARM_SERVICE"
"SD" "SQLData"
"SqD" "SQLData"
"SqlD" "SQLData"
"SqDa" "SQLData"
"the" "theWord_Example"
"the" "THEWORD2EXAMPLE"
"the" "THEWordEXAMPLE3"
"the" "THEWORDEXAMPLEFOUR"
"thw" "theWord_Example"
"thw" "THEWordEXAMPLE3"
"te" "theWord_Example"
"te" "THEWORD2EXAMPLE"
"te" "THEWordEXAMPLE3"
```
Falsy cases:
```
"sbo" "SeekBar"
"sbo" "StatusBarNotification"
"sbO" "StringIndexOutOfBoundException"
"sbO" "SparseBooleanArray"
"AL" "ALARM_SERVICE"
"ASE" "ALARM_SERVICE"
"SQD" "SQLData"
"SqLD" "SQLData"
"SLD" "SQLData"
"SQDt" "SQLData"
"SQDA" "SQLData"
"thw" "THEWORD2EXAMPLE"
"thw" "THEWORDEXAMPLEFOUR"
"te" "THEWORDEXAMPLEFOUR"
```
## Winning Criteria
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code of each language wins. Default loopholes are not allowed.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~239~~ 227 bytes
```
lambda a,b:any(re.match(w,''.join(map(str.title,re.sub('(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])|(\d)','_',b).split('_'))))for w in g(a))
import re
g=lambda s:s and{c+w for w in g(s[1:])for c in[s[0],'.*'+s[0].upper()][s<'[':]}or{''}
```
[Try it online!](https://tio.run/##nZPRbpswFIbv8xQoNzYrRVt3FzWqSMO0SnQsZFunURQdwCTewGa2Ecm6PntGGqYNpYZp3GCf7z/GR/ood2rD2cU@m97vcyjiFAyw4gmwHRbELkAlG1xbCNlfOWW4gBJLJWxFVU6sJiCrGCN8NQ2d8y9RCOc/IvMnvrqcHpe/QVO7T01koRWyYtOWZU4VbjZm82RcGLVBmbHGYJojWpRcKEOQ0Xra3kdOpAEsfUjOauOvtAxfTaKn9qQphDJ8GVnIfoHODiu7KksisBmF8hKFaBI9cvGA0OO@FJQpI8NjGfOxZYyXJQhJZpznBJgjBOzG5ugktPCoIjPKUl9c87wq2A1LydavlJ8FwNbE3SakVJSzbrP//81Ofuh9upBHpeogT4@OXZ4T3K6WbvDp5trtYNmPl714OW/HmYOCDviuJ3lPE2iQ2pADaV53XKQrdwtFmZNnEh/eund@ML9wPzu37z1Xk2jOaAOv9We0iTf@x6AbqgevUg99aHCawWE0sxwTo1NfCfk2A/GcyQpUJRv2jiua0QROpW1zTWH9R9QZr1jaa3nvf9QqqxfP7TdvobfI0yI9WcyVHjlaK@tB5@p/MEpr3f4X "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 177 bytes
Expects `(identifier)(input)`.
```
S=>g=([c,...s],l=[],o='')=>c?g(s,o?[...l,o]:l,c)|c>{}&g(s,l,o+c):eval(`/~${[...l,o].join`.*~`}/i`).test(S.replace(/./g,(c,i)=>!i|(!/[A-Z]/.test(l)|S[i+1]>'_')&(l=c)<{}?'~'+c:c))
```
[Try it online!](https://tio.run/##rZVtT9swEMff71OANRF7DYk23lVLq5QEDSkso2FjWlW1nusGM2OH2IWiPnz1kpZOgJaWJU1enu9@uTv7/neN77AiKUv0oZADuhg6i8hpxA7sENOyLNU1udPpmtIxDOQ0SDOGypTNTnbETdmtc5OgKWlMZgfLg8xUI6hO7zCHfXv@fvLXz7qWTPStD/P@zGZ9ZGmqNIyslCYcEwpty45NSEyW/WKfTeG@3XEPf3XtJz@OplGH1T52G0bPQAeQOwR9nsyaxtyokTpBaEGkUJJTi8sYGhfpSF89GOjdS@sQgijBqaItmZmwcNMUP4C9DR@CQP2WYA/9C9EpE/GpGNBxONLhsCVHYuCPCU00kwL8J@Q8YJq2mBiE6bHkoxvxDGxjEdNnYHWQMA@yakPAlN7YipfluDxz2xkS5EMCt33Wi/z2j9NjH5TNpBhEVQGJciHZ7XhY47c7soJEXhWQWw9UAOEeqCATnAPRV/RSpoOeP8Y3CadgOyTzzivn4ot/Gba9T/5P9@xb4JeHZJmsGUc7ZbKGnITf26A4pGhP7qso576CTGjuiy14O5shBcpZQ15RjBPMVd4OoPRPC6eghO5jPVJZ6Fep2ZAR/FruSy@MzdL8xrraounb9au0BK/Ezi8hMUtFOPdKBt4GJfRoGRh4pVPVoGSgCwqPxPap3qIvOwU@zcziEQ "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Reversible computation refers to computation in which little or no information is deleted. Reversible computation a major component of quantum computation, and reversible computation is potentially many times more energy efficient than conventional computation. I want to know how easy it is to compute the conjugacy of transpositions reversibly?
# Challenge
Let `T5` be the set of all [transpositions](https://en.wikipedia.org/wiki/Transposition_(mathematics)) on the set `{1,2,3,4,5}`. Let be the [conjugacy operation](http://mathworld.wolfram.com/Conjugation.html) on `T5` defined by `x * y=xyx^(-1)` (here concatenation denotes the [symmetric group operation](https://en.wikipedia.org/wiki/Permutation_group)). In other words, the underlying set of `T5` consists of all 10 pairs `(a,b)` of distinct numbers from `{1,2,3,4,5}` and where we declare `(a,b)=(b,a)`. The operation is the unique operation on the underlying set that satisfies
* `(a,b) * (c,d)=(c,d)`,
* `(a,b) * (b,c)=(a,c)`,
* `(a,b) * (a,b)=(a,b)`
whenever `a,b,c,d` are distinct.
What is the simplest `n` bit input reversible circuit `C` along with an injective function `R:T5->{0,1}^(n/2)` such that `C(R(x)||R(y))=R(x)||R(x*y)` for all `x,y` in `T5`?
The gate cost of a reversible circuit shall be the sum of the costs of every individual logic gate in the reversible circuit.
Here is the price chart per logic gate (see [this link](https://en.wikipedia.org/wiki/Quantum_gate) for a description of the logic gates) along with a description of the reversible gates.
Each SWAP gate `(x,y)->(y,x)` will have a cost of `0`.
Each [NOT gate](https://en.wikipedia.org/wiki/Inverter_(logic_gate)) `x-> NOT x` shall have a cost of `1`.
Each [CNOT gate](https://en.wikipedia.org/wiki/Controlled_NOT_gate) `(x,y)->(x,x XOR y)` shall have a cost of `2`.
Each [Fredkin gate](https://en.wikipedia.org/wiki/Fredkin_gate) `(x,y,z)->(x,(NOT x AND y) OR (x AND z),(x AND y) OR (NOT x AND z))` shall have a cost of `4` (the Fredkin gate can also be described as the reversible logic gate where `(0,x,y)->(0,x,y)` and `(1,x,y)->(1,y,x)`).
Each [Toffoli gate](https://en.wikipedia.org/wiki/Toffoli_gate) `(x,y,z)->(x,y,(x AND y) XOR z)` shall have a cost of `5`.
No other gates are allowed.
Observe that each reversible gate has the same number of inputs as it has outputs (this feature is required for all reversible gates).
The complexity of your circuit will be the product of the gate cost or your circuit with the number `n` which you choose. The goal of this challenge will be to minimize this measure of complexity.
# Format
Complexity: This is your final score. The complexity is the product of the number `n` with your total gate cost.
Space: State the number `n` of bits that your circuit `C` acts on.
Total gate cost: State the sum of the costs of each of the individual gates in your circuit `C`.
NOT gate count: State the number of NOT gates.
CNOT gate count: State the number of CNOT gates.
Toffoli gate count: How many Toffoli gates are there?
Fredkin gate count: How many Fredkin gates are there?
Legend: Give a description of the function `R`. For example, you may write
`(1,2)->0000;(1,3)->0001;(1,4)->0010;(1,5)->0011;(2,3)->0100;
(2,4)->0101;(2,5)->0110;(3,4)->0111;(3,5)->1000;(4,5)->1001`.
Gate list: Here list the gates in the circuit `C` from first to last. Each gate shall be written in the form [Gate type abbreviation,lines where the gates come from]. For this problem, we shall start with the 0th bit. The following list specifies the abbreviations for the type of gates.
`T`-Toffoli gate
`S`-Swap gate
`C`-CNOT gate
`F`-Fredkin gate
`N`-Not gate.
For example, `[T,1,5,3]` would denote a Toffoli gate acting on the 1st bit, the 5th bit, and the 3rd bit. For example, `[T,2,4,6]` produces the transformation `01101010->01101000` and `[C,2,1]` produces `011->001,010->010` and `[N,3]` produces `0101->0100`. For example, one could write
`[S,7,3],[N,2],[T,1,2,3],[F,1,2,5],[C,7,5]`
for the gate list.
The gates act on the bit string from left to right. For example, the gate list `[C,0,1],[C,1,0]` will produce the transformation `01->11`.
# Sample answer format
Complexity: `128`
Space: `8`
Total gate cost: `16`
NOT gate count: `3`
CNOT gate count: `2`
Toffoli gate count: `1`
Fredkin gate count: `1`
Legend: `(1,2)->0000;(1,3)->0001;(1,4)->0010;(1,5)->0011;(2,3)->0100;
(2,4)->0101;(2,5)->0110;(3,4)->0111;(3,5)->1000;(4,5)->1001`
Gate list: `[N,1],[N,0],[N,3],[S,1,2],[S,2,3],[C,0,1],[C,2,3],[T,3,2,1],[F,2,3,1]`
The sample answer format is not a solution to the problem but is a template for the format for a solution.
[Answer]
# ~~640~~ 480
```
Complexity: 480
CSWAP count: 12
Legand: (1,2)->11000, (1,3)->10100, ..., (4,5)->00011
Gate:
[1,6,7],
[3,6,8],[3,6,7],
[4,6,9],[4,6,7],
[5,6,10],
[SWAP,6,7],
[5,6,10],
[4,6,7],[4,6,9],
[3,6,7],[3,6,8],
[1,6,7]
```
[](https://i.stack.imgur.com/kLHcN.png)
Use 6 and 7 as a stack to push the two mentioned pairs, then swap them and pop back. the chosen one of 6 or 7 is initially on stack top, if the other isn't
] |
[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/163290/edit).
Closed 5 years ago.
[Improve this question](/posts/163290/edit)
## TL;DR
* Record (left-right)/length for each pair of consecutive elements. If they're 0 or negative, don't record it.
* Once this is done, take these actions. Don't update quotients:
+ Increment right and decrement left for (0, .3)
+ Remove from the array at >=.3
+ Print both elements for >.5
* Print the remaining array. Have some separator for executed and remaining.
Now, onto the challenge…
This is the sorting algorithm that has a worst-case of ***GLORIOUS LINEAR TIME***, and where any who dare oppose its ***INFINITE WISDOM*** will be promptly ***EXECUTED*** for their ***HEINOUS CRIME OF HIGH TREASON***.
The ***FEARLESS LEADER*** has tasked you with the ***HONORABLE MISSION*** of writing a program or function that takes in an array of integers and sorts it using the following sorting algorithm:
1. Iterate through your array, enlightening each element with the ***GLORIOUS*** presence of their ***FEARLESS LEADER***.
2. Have your ***SECRET POLICE*** check on every pair of 2 consecutive elements to make sure they are ***PROPERLY LOYAL TO THEIR NATION***. If they're not ordered correctly, record the difference between the numbers, divided by the length of the array. This is their dissent quotient.
3. At the end of your ***GLORIOUS TOUR***, go through the list and ***RAIN FEARLESS LEADER'S DIVINE PUNISHMENT*** on all of the ***TREASONOUS DISSENTERS*** as follows:
* For a dissent quotient of less than .3, they merely need ~~brainwashing~~ a reminder of the ***INFINITE GLORY OF THE FEARLESS LEADER***. Decrement the left element and increment the right element. Don't change any dissent quotients.
* For a dissent quotient of .3-.5 (inclusive), they are ***TRAITORS*** and should be sent to ***PRISON CAMPS***. Remove them from the array.
* For a dissent quotient greater than .5, they are ***ODIOUS REBEL SCUM***. They should be ***PUBLICLY EXECUTED*** as an example for any other ***TREASONOUS HERETICS*** they might have allied with. Remove them from the array and send it to the national news source, The STDOUT Times.
4. Your array is now ***COMPLETELY AND FOREVER*** sorted. Send it to The STDOUT Times so they can sing of your ***GLORIOUS VICTORY***.
As ***MANDATORY VIEWING*** to those who are too ***FOOLISH*** to understand the ***INFINITE GLORY*** of this algorithm, it will be used to sort the following array:
```
[1,8,6,0,4,9,3,5,7,2]
```
* 1 and 8 are ordered correctly.
* 8 and 6 aren't ordered right, so the dissent quotient of .2 is recorded for both of them.
* 6 and 0 are another pair of dissenters. This dissent quotient is .6.
* 0 and 4 are ordered correctly.
* 4 and 9 are ordered correctly.
* 9 and 3 have a dissent quotient of .6.
* 3 and 5 are ordered correctly.
* 5 and 7 are ordered correctly.
* 7 and 2 have a dissent quotient of .5.
So, you take the following actions in the name of the ***FEARLESS LEADER***:
* Decrement 8 to 7, and increment 6 to 7.
* Remove 0 and the new 7, and ***EXECUTE THEM***.
* Follow with 9 and 3.
* Haul the original 7 and the 2 to the re-education camps and remove them.
This should be your press release, done in STDOUT or whatever's convenient:
```
Executions: 7, 0, 9, 3
[1, 7, 4, 5]
```
As you can see, the resulting array is ***COMPLETELY AND FOREVER SORTED***. Attempting to suggest that it isn't sorted constitutes ***HIGH TREASON***.
Now, as a ***GLORIOUS DEMONSTRATION*** of the ***UNENDING RESOURCES*** given by the ***FEARLESS LEADER***, he has provided you with his ***INFINITE WISDOM*** in generating test cases:
```
import random
len=random.randint(2,20)
arr=list(range(len))
random.shuffle(arr)
print(arr)
dissent=[(arr[i]-arr[i+1])/len for i in range(len-1)]
dissent.append(0) # Barrier between front and back of the array.
executions=[]
for i in range(len-1):
if dissent[i] > 0:
if dissent[i] < 0.3:
arr[i] -= 1
arr[i+1] += 1
elif dissent[i] > 0.5:
if dissent[i-1] <= 0.5:
executions.append(arr[i])
executions.append(arr[i+1])
print([arr[i] for i in range(len) if dissent[i] < 0.3 and dissent[i-1] < 0.3])
print(executions)
```
[Try it Online](https://tio.run/##jVFNb4MwDL37V1iaNCXqYNBql6nZYX8DcaDFjKg0QSHV1l/PHD5aNnZYLk6e3/Oznfbqa2t2fa/PrXUeXWFKewZoyKjxHoegjRfbp20ioXBONbrzguEPEsyTEiZmV1@qqiHBHAmtC6LhCqXuOjJeZeGd6TwawibN5TMXwMo61KgN3mpGqcxnVVy0LZlSJBIf8J2VmhweyH9SkDprPLI9HorjCW2FviZkUnGNgb7oePHamk5lOfzp8grIR1c4mXFz@IbJCK9Te0zi3T0ZzjgRRgrTNc4j4maZoWblFb/8LLgkRKzfqzVnKHWbbt7Q2IqEf7DC7mH6o2waYb0gGZoRv@eX@LgAhxYHOJ8//e4p@/4b) - hit the run button to use, otherwise you're just getting what the last person got.
In the interest of stare desecis, the ***FEARLESS LEADER*** has also provided an edge case example:
```
Input Output
3,2,1,4,4,1,2,3,4,5 2,2,2,4,2,3,4,5
```
(There are no executions in this example.)
Finally, you should treat the bytes in your program as [key supporters](https://www.youtube.com/watch?v=rStL7niR7gs) and minimize them. The shortest program in bytes will win the ***ETERNAL FAVOR OF THE FEARLESS LEADER***.
## Credit where it's due
The concept for this was inspired by [Lazy Drop Sort](//codegolf.stackexchange.com/q/159945), and the writing style used was largely taken from [Psychotic Dictatorships](https://www.nationstates.net/region=psychotic_dictatorships)—go visit them if you enjoyed the parody aspect of this.
Additional credit goes to everyone who voted on this in [the Sandbox](//codegolf.meta.stackexchange.com/a/16075) early on. The +8 it attained was my motivation to rewrite it to avoid duplication.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~146~~ 135 bytes
```
->l{e=[];i=0;l.inject{|j,k|q=(j-k)*10.0/l.size;b,c=l[i],l[i+=1];q>5&&e<<b<<c;q>0&&(l[i-1],l[i]=q<3?[b&&b-1,c&&c+1]:p);k};[l-a=[a],e-a]}
```
[Try it online!](https://tio.run/##VVNLj9owEL7zK3wK0J1QO3Zem3j31FMPK3G1rIpEWTUQtUvZPbTAb6f2jJOwEjgeM9/D34Q/H83f26u@xU/DudPGVr3m1bDpf@279v182cPhctSrfXxYfxF8w78Om1P/r6saaPVgegtuedDCVsenNIq6um7qunUFj6KV@ykW2GH1sZbPpomiJhbQRlH7IOzj27o6XCszxDttdha6eGevN7NYGAEFZMBBQQkSUsghscDcMcuBKWCpr9yWAyuBSQsLIyEB4QDKrYkDKcCmBBh9FK5yhnuQcIXIkbVwO2oQjlU4qdQ9Mvd1CsLvJeplyCNQ2KMLNKaIgAdIQZB0FC@IberlXtw3@4Px6c8UeknIANJJ8lWieIHKEl3gJdRs13eFGzitDKV4kMqmK6oxNO8zRTokSBEYKHwkSOnj8kQTvqQeTkEl031mvjTMIyOxFGGcskIWEQhK4g@qIshQmd8FELTEqDUxIhqnmGAgnEJkd/XCFESfU3vwqO4mK8IYSZTEwsR5MIucGaJHaIlnAfSpFSUxeHrVSIIcScpbEiYnodEMhlmMoHkecm7Dt3AabGB2kgu76Xbtzx@noW@7lVxjxc6XHthvYN2FvX28n9ir@xsyrZnxZ5Y9s@XL9yV7ZMtv2@3Ldnm9/Qc "Ruby – Try It Online")
] |
[Question]
[
Given a stream of bits, output the shortest possible [Hamming code](https://en.wikipedia.org/wiki/Hamming_code) that encodes it.
The steps to generate the Hamming code are as follows, although your submission does not necessarily have to conform to them as long as it produces identical output. The input `110100101` will be used as an example.
1. Pad the input with trailing zeroes until its length is **2m - m - 1** for some integer m.
```
110100101 becomes
11010010100
```
2. Insert spaces at every position with an index of **2i** (note that all indexing is 1-based for the purposes of this algorithm). This will insert **m** spaces for parity bits, resulting in **2m - 1** bits total.
```
11010010100 becomes
__1_101_0010100
```
3. Fill in the parity bits. A parity bit at index **i** is calculated by taking the sum modulo 2 of all bits whose index **j** satisfies **i & j ≠ 0** (where **&** is bitwise AND). Note that this never includes other parity bits.
```
__1_101_0010100 becomes
111110100010100
```
Input may be taken as a list (or a string) of any two distinct elements, which do not necessarily have to be `0` and `1`. Output must be in an identical format. (Input or output as an integer with the corresponding binary representation is disallowed, as this format cannot express leading `0`s.)
The input will always have a length of at least 1.
Test cases (of the form `input output`):
```
0 000
1 111
01 1001100
1011 0110011
10101 001101011000000
110100101 111110100010100
00101111011 110001001111011
10100001001010001101 0011010100010010010001101000000
```
[Answer]
## JavaScript (ES6), 116 bytes
```
f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):[...Array(p)].map(_=>i&++i?~~a[i-1]:a.reduce((p,e,j)=>p^=++j&i&&e,0))
```
If the padding is unnecessary, then for 97 bytes:
```
f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):a.map(e=>i&++i?e:a.reduce((p,e,j)=>p^=++j&i&&e,0))
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 64 [bytes](https://github.com/abrudz/SBCS)
```
{u∨(~k)\⌽m≠.∧u←(⍵↑⍨g l)\⍨k←1<1⊥m←2⊥⍣¯1⍳¯1+2*l←⌈(g←2∘*-+∘1)⍣¯1≢⍵}
```
[Try it online!](https://tio.run/##XU49TwJBEO33V2x5fJkZaO1opAVLG6JyBXdCIQUh2pjgQlgiBYmlkRivozCWNvyU@SPnzLB3fuwm782892Z2@@OkcTXtJ6M4J/d4OUrT65tbAxYADFpENMAEgCgCk9WSdW7YUgdVA52RTh2UIw0oGmWVxFO56M0xFybhuLNcXRilE57i/@azCbksuh9WLmj1ldLi5YTc@4TmTxH5T5pvyGexTdj12ZBVPEVavqVcNZnJ7w57JP/BWGtWE5Zp5aJYbfdcbdQYsRJii1deeZcPJOXXtHw47Fvywnrb67YZz886vXxg62AYkAGsIAr/qgq16H60sg73/xyUCfijhew3 "APL (Dyalog Unicode) – Try It Online")
A dfn that takes a boolean vector as its right argument.
### Ungolfed with comments
```
f←{
g←2∘*-+∘1 ⍝ A function that gives the data size from parity size; 2^x - (x+1)
l←⌈g⍣¯1≢⍵ ⍝ Parity size from input length by inverting(⍣¯1) g
m←2⊥⍣¯1⍳¯1+2*l ⍝ Column matrix of bit patterns of 1..2^l-1
k←1<1⊥m ⍝ A boolean mask indicating where the data bits should go
u←(⍵↑⍨g l)\⍨k ⍝ Data pattern moved into appropriate positions:
⍵↑⍨g l ⍝ Overtake ⍵ by length (g l)
\⍨k ⍝ Move the bits to the positions of 1 bits of k
u∨(~k)\⌽m≠.∧u ⍝ Complete the codeword:
m≠.∧u ⍝ Compute the parity (data AND each row of m, then reduce by XOR)
⌽ ⍝ Reverse so that LSB goes first
(~k)\ ⍝ Fill in the parity positions with parity bits
u∨ ⍝ Combine with data bits
}
```
[Answer]
# Mathematica, 332 bytes
```
R[n_,m_]:=Module[{a,l,i},i=n;If[i==0,a={0},a={};While[i>0,If[IntegerQ[i/2],PrependTo[a,0];i/=2,PrependTo[a,1];i=(i-1)/2]]];l=Length[a];Do[PrependTo[a,0],{i,m-l}];a];F[m_]:=Transpose@Table[R[i,m],{i,2^m-1}];F[m_,K_]:=Module[{Z,i,N,Y},Z=F[m];N=NullSpace[Z,Modulus->2];Y=Mod[[[email protected]](/cdn-cgi/l/email-protection),2]];Row@F[#,PadRight[IntegerDigits@#2,2^#-1-#]]&
```
[Try it online](https://sandbox.open.wolframcloud.com/app/objects/) : copy and paste code using ctrl+v, place input at the end of the code and hit shift+enter to run
(Wolfram-cloud will print "x" between digits but this doesn't happen in mathimatica)
**Input**
>
> [4,10101]
>
>
>
**Output**
>
> 001101011000000
>
>
>
**Input**
>
> [5,10100001001010001101]
>
>
>
**Output**
>
> 0011010100010010010001101000000
>
>
>
] |
[Question]
[
I saw this recent Puzzling question:
### [Add parentheses to make this true](https://puzzling.stackexchange.com/questions/51818/add-parentheses-to-make-this-true)
And saw that [one answer used a Python script to try all possibilities](https://puzzling.stackexchange.com/a/51855).
Your challenge is, given an expression (as a string) and an integer, is to make a program that can tell whether you can add parens to make the expression equal the integer.
For example, if the expression is `1 + 2 * 3` and the integer is `9`, than you can add parens like `(1 + 2) * 3`, which equals 9, so the output should be truthy. But if the expression is `1 + 2 - 3 * 4 / 5` and the integer is `9999999999999`, you can't add any amount of parens to make that equal `9999999999999`, so the output should be falsey.
Note that the integer input may be positive or negative, but the expression will only contain positive integers. In fact, the expression will always match `(\d+ [+*/-] )+ \d` (regex). In other words, no parens, no exponents, just `+`, `-`, `*` and `/`. Standard operator order (`*` and `/`, then `+` and `-`).
More test cases:
```
1 + 2 - 3 * 4 / 9 and -1 -> truthy, ((1 + 2) - (3 * 4)) / 9
10 - 9 * 8 - 7 * 6 - 5 * 4 - 3 * 2 - 2 * 1 and 1, falsey, see linked question
10 + 9 - 8 * 7 + 6 - 5 * 4 + 3 - 2 * 1 and 82 -> truthy, (10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1
34 + 3 and 15 -> falsey
1 + 2 + 5 + 7 and 36 -> falsey
1 / 10 * 3 + 3 / 10 * 10 and 6 -> truthy, (1/10*3+3/10)*10
```
Any questions?
You may output the expression with parenthesis if it is possible, for instance `(10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1` for the last test case. I would prefer this over just a truthy value, but it is up to you. Using `2(5)` for multiplication is not allowed, only `*`.
[Answer]
# Python 2, ~~286~~ ~~285~~ 282 bytes
```
from fractions import*
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
for p in P(['Fraction(%s)'%e for e in x[::2]]):
try:print 1/(eval(''.join(sum(zip(eval(`p`.replace("['","'(").replace("']",")'")),x[1::2]+[0]),())[:-1]))==y)
except:0
```
[**Try it online**](https://tio.run/nexus/python2#VZBNj5swEIbP9a8YUa1sB0iA7CcV15447N1CWgcmjbcGLJvskv7vnlM7QW16QIOfd57xyK6Koui8t2MPeyvbSY2DA9Wb0U4r8lpp2e86CXUpTCxqocqm2Y8WFKgBrBx@INM4sJrzQE2gr6wWpWp4M1pRN2ROTpUazHFinMzVvHZGq/B/0y/o9@Vmduc4vUMIIYZwFmVZNA0vCUz2VBqrhgnyDcMPqRml6/dRDcwde/ZLmSt8M29ri0bLFlkkaJRElEX8H6KNR5xGnCezyMP0WGQNTxjnokzzhvOqOnECOLdopjI7@@f5a9OQ0eRSvu0syp@UxxS1w2W1jJKvQJcI5NDB/ykc5AfCDnEA2XXYwTSC1Hr8hP6oJ2U0woRuglY6dIR8HpQneUm@4Iwtc/xMc4ihgBS2sIJ72MALhQTSnNA88/TF02dfn3x99PXh0nXtDlbhax6MqxB7IfXCygvxjRB74ab5uSB0e6EX9YEsW8S@PYanALePAW7AD115OQxYDnkWch8HEnbIwxdY8XsY01a2B/wD)
### Explanation:
This version will print all of the working expressions (with the `Fraction` objects).
```
from fractions import*
# Sublist Partitions (ref 1)
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
# Convert all numbers to Fractions for division to work
n=['Fraction(%s)'%e for e in x[::2]]
# Operators
o=x[1::2]
# Try each partition
for p in P(n):
# Move parens to be inside strings
n=eval(`p`.replace("['","'(").replace("']",")'"))
# Alternate numbers and operators (ref 2)
x=''.join(sum(zip(n,o+[0]),())[:-1])
# Prevent division by zero errors
try:
# Evaluate and check equality
if eval(x)==y:print x
except:0
```
[**Try it online**](https://tio.run/nexus/python2#TY3BasQgFEXX8SsegUFfJ5NO0p3gtqssZi/C2KkZLImKcYrpz6exFNrFhcvhcu42Rj/DGPUtWe8WsHPwMT2Ri5j0/PauYeAyHOUgLVdq9BEsWAdRu7thk3FsQCw0FHphg@RWofJRDorkZhXWhUdiSLLI7RImW7oTkr7@HrLDgvRgoDhMcWTJea8U8SLLrlTyT@@Qk8oJ86kndg3XNpow6ZthtaR1U1NW4x@iakdIa0RSZUFp@@GtY8tjZl82MNf4ozwrbBii5KdO7asU111f2RF@DjIKsfIQrUuQSWXyzYTEz9tGX@AZejhBV0Khgf4b)
### References:
1. [Partitioning function](https://codegolf.stackexchange.com/a/53046/34718)
2. [Alternating zip](https://stackoverflow.com/a/3682033/2415524)
*Saved 3 bytes thanks to Felipe Nardi Batista*
] |
[Question]
[
## Background
By expanding and cancelling terms, it is easy to show the following identity:
[](https://i.stack.imgur.com/hgKDi.gif)
However, it is an open problem whether all 1/n-by-1/(n+1) rectangles can tile the unit square.
## The Task
Your program should take a positive integer N as input in any convenient manner, and pack all 1/n-by-1/(n+1) open rectangles with n between 1 and N inclusive into the unit square, such that no two overlap.
For each rectangle you must generate the following integers in order:
* 1 if the horizontal edges are longer than the vertical edges, else 0
* The numerator and denominator of the x-coordinate of the bottom-left corner
* The numerator and the denominator of the y-coordinate of the bottom-left corner
Note that we take the unit square to be `(0, 1) x (0, 1)`, with x-values running from left to right, and y-values running from bottom to top.
The final expected output is the concatenation of these integers for each rectangle in order of increasing n, in any convenient format (e.g. printed to stdout, or as a list returned from a function).
## Example Input and Output
Input:
```
3
```
Output:
```
0 0 1 0 1 1 1 2 0 1 1 1 2 1 3
```
This parses as the following:
```
0 (0/1, 0/1) 1 (1/2, 0/1) 1 (1/2, 1/3)
```
## Scoring
This is a code-golf challenge, so the answer with the fewest bytes wins. However, your algorithm should also be reasonably efficient; it should be able to run for all `N<=100` in a total of around 10 minutes.
Your solution must give valid solutions for all `N<=100`, but provably complete algorithms are also welcome even if they aren't the shortest.
[Answer]
# Haskell, ~~263~~ 262 bytes
```
import Data.Ratio;f m=let{(#)n z|n>m=[[]]|True=[a:y|(a,j)<-[((o,x,y),[c|c<-(u&w,h-v,x,g):(w-u,h&v,a,y):z,c/=b])|b@(w,h,x,y)<-z,(o,u,v)<-[(o,1%(n+1-o),1%(n+o))|o<-[0,1]],(a,g)<-[(x+u,y+v)|u<=w,v<=h],let(&)p q|w>h=p|True=q],y<-(n+1)#j]}in(1#[(1%1,1%1,0%1,0%1)])!!0
```
This follows the algorithm described in Paulhus 1997, *An Algorithm for Packing Squares*, [doi:10.1006/jcta.1997.2836](http://dx.doi.org/10.1006/jcta.1997.2836). The key observation in the paper, which is empirically if not theoretically verified, is that the region left over after placing a rectangle in a box can be split into two sub-boxes whose filling can then in turn be regarded as independent.
Rather than finding the smallest width sub-box to fit the next rectangle into, the code performs a search across all possible sub-boxes; in practice this does not make an appreciable slow down for *n*<100.
Output is in the form of a list of entries as tuples with the fraction marker `%` still included. The integers in the formatted output are in the desired order, but strictly speaking some post-processing would be required to produce the list of integers alone.
Sample run:
`*Main> f 5
(0,0 % 1,0 % 1),(0,1 % 2,0 % 1),(0,1 % 2,1 % 2),(0,3 % 4,1 % 2),(1,1 % 2,5 % 6)`
**Edit:** removed an errant space after a `let`.
] |
[Question]
[
Your task is to, with an input number `p`, find the smallest positive cannonball number of order `p` that is NOT 1.
### Definition
A cannonball number (of order `p`) is a number which is both:
* An `p`-gonal number ([See this page](https://en.wikipedia.org/wiki/Polygonal_number)).
* and an `p`-gonal pyramid number.
+ The `n`th `p`-gonal pyramid number is the sum of the 1st to `n`th `p`-gonal numbers.
- (e.g. `4th square pyramid number = 1 + 4 + 9 + 16 = 30`)
+ The picture below represents the 4th square pyramid number, as a square pyramid.
[](https://i.stack.imgur.com/2NtlK.png)
+ For more info, visit [this link](https://en.wikipedia.org/wiki/Tetrahedral_number).
The cannonball number of order 3, for example, is 10, because it is:
* The fourth triangle number (`1 + 2 + 3 + 4 = 10`)
* and the third triangular pyramid number. (`1 + 3 + 6 = 10`)
### Formulas
**NOTE: If you can find (or make) more useful formulae than my ones here, please post it here (or message me on the question chat thing).**
* If you're interested, the formula for the `n`th `p`-gonal number is:
[](https://i.stack.imgur.com/36076.png)
* And the `n`th `p`-gonal pyramid number is:
[](https://i.stack.imgur.com/D9YGI.png)
### Specs
* `p` is guaranteed to be larger than 2.
* The program must check values for a solution for `p` up to (and including) `2^16`. Your program may do anything if no solutions are found for `p`.
* Only positive indices for `n`.
### Test cases
* `3` outputs `10` (4th triangle number, 3rd triangle pyramid number)
* `4` outputs `4900` (70th square number, 24th square pyramid number)
This is code-golf, so shortest answer in bytes wins.
Note: If you do post a solution, please include a description of how the code works.
Should I start a bounty for a solution which is better and doesn't use my formulae?
[Answer]
# Python 3, ~~129~~ 127 bytes
```
def f(p):
x=2
while 1:
for i in range(x*x):
if i//x*((p-2)*i//x+4-p)/2==i%x*(i%x+1)*((p-2)*i%x+5-p)/6==x:return x
x+=1
```
A function that takes input via argument and returns the output.
This is an *extremely* naïve brute force, and takes a very long time for even moderately large `p`; the execution time will be ridiculous for anything approaching the given maximum for `p` of `2^16`, but there is no reason why the program would not work, given sufficient time.
There are probably far shorter and faster ways of doing this, but I thought it would be good to post something to get this started off.
**How it works**
The return value `x` is initialised to `2`, and then the program simply loops over all the `p`-gonal and `p`-gonal pyramidal numbers up to order `x`. If the current `p`-gonal and `p`-gonal pyramidal numbers, calculated using the formulas, are equal to each other and to `x`, then `x` must be the relevant cannonball number and this is returned. Else, `x` is incremented, and the program tries again for the new value of `x`.
In terms of golfing, a Cartesian product is used to collapse the two for-loops for the `p`-gonal and `p`-gonal pyramidal numbers into a single loop, and the formulas were factorised further to save a few bytes.
[Answer]
# JavaScript, ~~111~~ 98 bytes
```
f=n=>{for(b=c=g=1;b++;)for(p=b*(b*3+b*b*(n-2)-n+5)/6;g<p;c++)if(p==(g=c*(c*n-c-c-n+4)/2))return p}
```
**ungolfed**
```
f=n=>{
for(b=2,c=g=1;b<1e6;b++) // run index b from 2 (to 100k)
for(
p=(b*b*3+b*b*b*(n-2)-b*(n-5))/6 // p=the b-th n-pyramidal number
;g<p&&c<1e6;c++) // run while n-gonal is lower than n-pyramidal (and c below 100k)
if(p==(
g=(c*c*(n-2)-c*(n-4))/2 // g=the c-th n-gonal number
)) return p // if they are equal, return
}
```
c is not reinitialized in the inner loop because the next p[b] is definitely larger than the current g[c] (so we have to move *on* anyway)
**examples**
```
samples=[3,4,6,8,10,11,14,17,23,26,30,32,35,41,43,50,88]
for(i in samples) document.write('n='+(n=samples[i])+': '+f(n)+'<br>');
```
[Answer]
# C, 107 bytes
```
#define X(x)(1+p/2.0*x)*++x
c(p,m,n,a,b){m=n=a=b=1;p-=2;do if(a>b)b+=X(n);else a=X(m);while(a^b);return a;}
```
Ungolfed with test parameters:
```
#include <stdio.h>
#define X(x)(1+p/2.0*x)*++x
int c(int p)
{
int m = 1, n = 1, a = 1, b = 1;
p -= 2;
do
if(b < X(m))
b += X(n);
else
a = X(m);
while(a != b);
return a;
}
int main()
{
printf("%d\n", c(3));
printf("%d\n", c(4));
}
```
This uses the fact that the n-th p-gonal number can be defined as `n(1+(p-2)(n-1)/2)` and the pyramid number is the sum of the aforementioned numbers.
I think it can be further golfed, given that it's not really necessary for variable `a` to be saved.
[Answer]
# old PHP program, ~~115~~ 106 bytes
+16 for current PHP, see below
```
<?for($b=2;1;$b++)for($p=$b*($b*3+$b*$b*($n-2)-$n+5)/6;$g<$p;++$c)if($p==$g=$c*($c*$n-2*$c-$n+4)/2)echo$p;
```
* loops forever
* usage: with PHP<4.2: run from browser with `<scriptpath>?n=<number>`
with PHP<5.4, add `register_globals=1` to `php.ini` (+18 ?)
* see [my JavaScript answer](https://codegolf.stackexchange.com/questions/84632/cannonball-conundrum/85142#85142) for description
* +10 for PHP>=5.4: replace `1` with `$n=$_GET[n]`. Or replace `1` with `$n=$argv[1]`, run `php -f <filename> <number>`.
* +6 for finite loop on success: replace `echo$p` with `die(print$p)`
* +/- 0 for function:
```
function f($n){for($b=2;1;$b++)for($p=$b*($b*3+$b*$b*($n-2)-$n+5)/6;$g<$p;++$c)if($p==$g=$c*($c*$n-2*$c-$n+4)/2)return$p;}
```
loops forever if it finds nothing. Replace `1` with `$p<1e6` to break at 100k or with `$p<$p+1` to loop until integer overflow. (tested with PHP 5.6)
**examples** (on function)
```
$samples=[3,4,6,8,10,11,14,17,23,26,30,32,35,41,43,50,88];
foreach($samples as $n)echo "<br>n=$n: ", f($n);
```
**examples output**
```
n=3: 10
n=4: 4900
n=6: 946
n=8: 1045
n=10: 175
n=11: 23725
n=14: 441
n=17: 975061
n=23: 10680265
n=26: 27453385
n=30: 23001
n=32: 132361021
n=35: 258815701
n=41: 55202400
n=43: 245905
n=50: 314755
n=88: 48280
```
] |
[Question]
[
Everyone knows what run-length encoding is. It has been the subject of many code-golf challenges already. We'll be looking at a certain variation.
### Example
```
Normal: 11222222222222222222233333111111111112333322
Run-length: 112(19)3(5)1(11)2333322
```
The number in parentheses specifies the number of times the previous symbol occurred. In the example, only runs of 5 or more characters were encoded. This is because encoding runs of 4 or less doesn't improve the character count.
## Challenge
Write a function/program that implements this variation of run-length encoding, but can also encode runs of two symbols. The runs of two symbols must also be enclosed in parentheses. A group will also be enclosed in parentheses. Your program must accept a string as input, and output the modified string with modifications that shorten the string.
### Example
```
Normal: 111244411144411144411167676767222222277777222222277777123123123123
Double run-length: 1112((444111)(3))67676767((2(7)7(5))(2))123123123123
```
### Notes
* `111` was not encoded because encoding it (`1(3)`) is not shorter.
* The string `444111` occurs 3 times so it is encoded.
* `676767` was not encoded because `((67)(4))` is longer than before.
* `222222277777222222277777` was not encoded as `((222222277777)(2))`. Why? Because `222222277777` itself can be reduced to `2(7)7(5)`.
* `123123123123` isn't encoded because your program is supposed to handle runs of two symbols, not three.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. Tie-breaker is early submission.
---
If I missed anything, or if you are unsure of anything please notify me in the comments.
[Answer]
# Retina, 162 bytes
```
+{`((\d)\2*(?!\2)(\d)\3*|\d)(?<1>\1)+
<<$1><$#1>>
<<([^<>]{1,7})><2>>
$1$1
<<([^<>]{1,3})><3>>
$1$1$1
<<([^<>]{1,2})><4>>
$1$1$1$1
}`<<(.)><(\d+)>>
$1($2)
T`<>`()
```
[Try it online!](http://retina.tryitonline.net/#code=K3tgKChcZClcMiooPyFcMikoXGQpXDMqfFxkKSg_PDE-XDEpKwo8PCQxPjwkIzE-Pgo8PChbXjw-XXsxLDd9KT48Mj4-CiQxJDEKPDwoW148Pl17MSwzfSk-PDM-PgokMSQxJDEKPDwoW148Pl17MSwyfSk-PDQ-PgokMSQxJDEkMQp9YDw8KC4pPjwoXGQrKT4-CiQxKCQyKQpUYDw-YCgp&input=MTExMjQ0NDExMTQ0NDExMTQ0NDExMTY3Njc2NzY3MjIyMjIyMjc3Nzc3MjIyMjIyMjc3Nzc3MTIzMTIzMTIzMTIzMTExMTExMTExMTExMTExMTExMTQ0NDQ0NDQ0MTQ0NDQ0NDQ0MQ)
] |
[Question]
[
# The Challenge
Given an arbitrary amount of rectangles, output the total count of intersections of those when drawn in a 2D plane.
An intersection here is defined as a point `P` which is crossed by two lines which are orthogonal to each other and are both not ending in `P`.
### Example
Each rectangle here is denoted by a 2-tuple with the coordinates of the upper left corner first and the coordinates of the bottom right corner second.
```
[(-8,6),(-4,-2)]
[(-4,9),(4,3)]
[(2,10),(14,4)]
[(1,7),(10,-6)]
[(7,4),(10,2)]
[(5,2),(9,-4)]
[(-6,-4),(-2,-6)]
```
[](https://i.stack.imgur.com/ZmYHo.jpg)
Those rectangles create 6 intersections, which has to be your output.
* As you can see in the image above, touching rectangles will not create intersections here and are not counted.
* You can encode the rectagles in any format you want. Make it clear which format you use.
* If multiple rectangles intersect at the same point, it only counts as one intersection.
* The coordinates will always be integers.
* There won't be any duplicate rectangles in the input.
* You will always get at least one rectangle as input.
* You may not use any builtins which solve this problem directly. Additionally you may not use builtins that solve equations. All other builtins are allowed.
* The output has to be a single integer indicating the intersection count.
# Rules
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
Same format as in the example above. The rectangles are wrapped in a list.
```
[[(-8,6),(-4,-2)],[(-4,9),(4,3)],[(2,10),(14,4)],[(1,7),(10,-6)],[(7,4),(10,2)],[(5,2),(9,-4)],[(-6,-4),(-2,-6)]] -> 6
[[(-2,2),(6,-4)]] -> 0
[[(-12,10),(-8,6)],[(-14,6),(-10,2)],[(-10,6),(-6,2)]] -> 0
[[(-4,10),(6,2)],[(-2,8),(4,3)],[(1,6),(8,4)],[(2,11),(5,5)]] -> 10
[[(8,2),(12,-2)],[(10,0),(14,-4)]] -> 2
[[(0,2),(2,0)],[(0,1),(3,0)]] -> 1
[[(-10,-2),(-6,-6)],[(-6,-2),(-2,-6)],[(-8,-4),(-4,-8)]] -> 3
```
**Happy Coding!**
[Answer]
## JavaScript (ES6), 186 bytes
```
a=>a.map(([a,b,c,d])=>h.push([b,a,c],[d,a,c])&v.push([a,b,d],[c,b,d]),h=[],v=[])|h.map(([d,a,e])=>v.map(([c,f,b])=>a<c&c<e&b<d&d<f&t.every(([a,b])=>a-c|b-d)&&t.push([c,d])),t=[])|t.length
```
Splits each rectangle into its component lines, then intersects the horizontal and vertical lines, building up a list of intersections to avoid duplicates.
[Answer]
# Mathematica 138 bytes
Not finished!
This works for all cases except `[[(0,0),(1,2)],[(0,0),(2,1)]]`
---
```
Length@Union[Join@@(Cases[RegionIntersection@@# &/@Subsets[Line[{{#,#2},{#3,#2},{#3,#4},{#,#4},{#,#2}}]&@@@Flatten/@#,{2}],Point@a__:> a])]
```
---
**Example**
```
Length@Union[
Join @@ (Cases[RegionIntersection @@ # & /@ Subsets[
Line[{{#, #2}, {#3, #2}, {#3, #4}, {#, #4}, {#, #2}}] & @@@ Flatten /@ #, {2}],
Point@a__ :> a])] &@{{{-8, 6}, {-4, -2}}, {{-4, 9}, {4, 3}}, {{2, 10}, {14, 4}},
{{1, 7}, {10, -6}}, {{7, 4}, {10, 2}}, {{5, 2}, {9, -4}}, {{-6, -4}, {-2, -6}}}
```
>
> 6
>
>
>
] |
[Question]
[
Write a program or function that extracts a word from a wordsearch using its start and end coordinates.
# The Input
Your program or function should accept three parameters: the *start coordinate*, the *end coordinate*, and a *wordsearch* from which to extract the word.
* The *start coordinate* can be taken in any format.
+ **It will always be an integer**
+ The bottom left of the grid is (0, 0)
+ You will not be provided with coordinates that go outside the bounds of the grid
+ You will not be provided with coordinates that are not vertical, horizontal, or perfectly diagonal to each other, such as (7, 0) and (0, 6).
* The *end coordinate* will be taken in the same format as the *start coordinate*
* The *wordsearch* will be a **string**, or your language's closest equivalent
+ It will be a grid of characters separated by a **single space**, with **each row on a newline**. It can have any height or width - which can be different - but **it will always be a rectangle**. For example:
```
A G O A T C A T
E A T M E N O W
W O R D S E A R
A K L L K J H G
N P L F G H F D
A S P L K J H G
O P I L F G H J
T F A S E J K L
```
```
J H P B L D J L T
F J L N F N P W H
W P R D T F J R Q
J L L L L J H H W
N P L F H H F D S
J T P L L J H H K
P P J L F H H J N
L F J T F J L L O
```
# The Output
You should output a **string**, or your language's closest equivalent. As no wordsearches in real life ever ask to find a single letter, you may output nothing if the coordinates are the same.
# Examples and Test Cases
```
First Grid Above:
(0, 4) and (4, 0) --> "APPLE"
(4, 0) and (0, 4) --> "ELPPA"
(1, 7) and (4, 7) --> "GOAT"
(0, 5) and (7, 5) --> "WORDSEAR"
(0, 6) and (5, 6) --> "EATMEN"
(0, 6) and (0, 7) --> "EA"
(7, 0) and (0, 7) --> "LHJGLRAA"
----------
Second Grid Above:
(1, 0) and (8, 7) --> "FJLHJJWT"
(1, 4) and (4, 4) --> "LLLL"
(1, 4) and (1, 4) --> "L" or ""
```
[Answer]
# JavaScript (ES6) 108
```
(x,y,t,u,g)=>eval("for(g=g.split`\n`.reverse(),r=g[y][2*x];x-t|y-u;)r+=g[y+=u<y?-1:u>y][2*(x+=t<x?-1:t>x)]")
```
**Less golfed**
```
(x,y,t,u,g)=>{
g=g.split`\n`.reverse();
for(r = g[y][2*x]; x-t | y-u; )
r+=g[y += u<y ? -1 : u>y][2*( x += t<x ? -1 : t>x)];
return r
}
```
[Answer]
# Python 3.5 using Numpy, 251 bytes:
```
def r(t,y,z):import numpy;l=numpy.array([[*i.split()]for i in z.split('\n')]);A,B,C,D=t[0],y[0],t[1],y[1];p=[1,-1];a=p[A>B];b=p[C>D];n=range(A,B+a,a);m=range(C,D+b,b);w=[l[:,i][::-1][p]for i,p in zip([[A]*len(m),n][A!=B],[[C]*len(n),m][C!=D])];return w
```
* Takes **input** in the following format:
```
print(''.join(r((start1,start2),(end1,end2),'''grid''')))
```
* **Outputs** in the format of a string (e.g. `APPLE`) as long as the function is called using the format above. Otherwise, a list
containing each letter (e.g. `['A','P','P','L','E']`) is returned.
Will golf more over time where and when I can.
[Try It Online! (Ideone)](http://ideone.com/9IIjvx) (Here, input is taken such that the grid is surrounded with double quotes (`""`) and input on one line, with `\n`s between each line of the grid. Then, the points are provided in a simple tuple form, with the starting on the second line, and the end on the third.)
## Ungolfed code along with Explanation
```
def r(t,y,z):
import numpy
l=numpy.array([[*i.split()]for i in z.split('\n')])
A,B,C,D=t[0],y[0],t[1],y[1]
p=[1,-1]
a=p[A>B]
b=p[C>D]
n=range(A,B+a,a)
m=range(C,D+b,b)
w=[l[:,i][::-1][p]for i,p in zip([[A]*len(m),n][A!=B],[[C]*len(n),m][C!=D])]
return w
```
For the purposes of this explanation, assume this program was run with the inputs `((0,4),(4,0))` and the first grid of the question. Here, I will go through the 2 main parts of the code:
* `l=numpy.array([[*i.split()]for i in z.split('\n')])`
Here, `l` is a numpy array containing each line of the input in a separate "list". For instance, the first grid in the question, which is:
```
A G O A T C A T
E A T M E N O W
W O R D S E A R
A K L L K J H G
N P L F G H F D
A S P L K J H G
O P I L F G H J
T F A S E J K L
```
returns this numpy array:
```
[['A' 'G' 'O' 'A' 'T' 'C' 'A' 'T']
['E' 'A' 'T' 'M' 'E' 'N' 'O' 'W']
['W' 'O' 'R' 'D' 'S' 'E' 'A' 'R']
['A' 'K' 'L' 'L' 'K' 'J' 'H' 'G']
['N' 'P' 'L' 'F' 'G' 'H' 'F' 'D']
['A' 'S' 'P' 'L' 'K' 'J' 'H' 'G']
['O' 'P' 'I' 'L' 'F' 'G' 'H' 'J']
['T' 'F' 'A' 'S' 'E' 'J' 'K' 'L']]
```
* `w=[l[:,i][::-1][p]for i,p in zip([[A]*len(m),n][A!=B],[[C]*len(n),m][C!=D])]`
This is the main list of the function in which all of the letters corresponding to each point on the grid is found. Here, `i` corresponds to either each integer in `n`, which is a range object containing every number in the range `start1=>end1+1` in increments of `+1` if `start1<end1` or `-1` if the opposite is true. However, `i` only corresponds to this as long as `start1` does not equal `end1`. Otherwise `start1` is returned as many times as the length of `m`, where `m` is a range object containing each integer in the range `start2=>end2+1` with the same conditions as `n`, and `p` corresponds to every integer in `m`. That being said, let us now walk through this step by step:
+ `l[:,i]` basically returns a row vector for each column, `i`, in the array, `l`. for instance, `l[:,0]` would return:
```
['A' 'E' 'W' 'A' 'N' 'A' 'O' 'T']
```
`l[:,1]` would return:
```
['G' 'A' 'O' 'K' 'P' 'S' 'P' 'F']
```
so on and so forth. You can read more about different ways of indexing in numpy, including this method, [here](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html).
+ Then, after that, the function reverses each array returned, using `l[:,i][::-1]`, since each array is indexed from left to right, but since the point `0,0` on the grid in on the lower left hand corner of the grid, reversing each array would return the index values as if they were being looked for from right to left. For instance, `l[:,0][::-1]` would return:
```
['T' 'O' 'A' 'N' 'A' 'W' 'E' 'A']
```
+ After this, the function then indexes through that reversed array for the index value corresponding to `p`, which is your letter, and then adds that to the list being created. For instance, `l[:,0][::-1][4]`, which corresponds to point `(0,4)`, would return `A`.
+ This process keeps on repeating and adding new values to the list until the range objects are exhausted.
After all that, the output, which is list `w`, is finally returned. In this case, that would be `APPLE` if called with `print(''.join(r((0,4),(4,0),'''The Grid''')))` or `['A','P','P','L','E']` if it is called without `''.join()`. Either way, it returns the correct answer, and we are done!
] |
[Question]
[
[CleverBot](http://www.cleverbot.com/) is a conversational AI that works fundamentally by repeating responses from real humans it has heard previously. It starts off pretty dumb, but once the database becomes *(a lot)* larger it begins sounding more like an actual person!
## How your program should work
1. **Output `Hi!`**
2. **Receive the user's reply as a string**
* The reply is added to a list of responses associated with the program's last output (eg. the first reply would associate with `Hi!`).
3. **Output one of the responses associated with the reply from step 2**
* Every output has a list of responses associated with it.
* The response should be randomly selected from the list of associated responses.
* Matching of previous replies is case-insensitive and without symbols (only `0-9`, `A-Z` and space are matched). For example, entering `hi` could return any response associated with `hi`, `Hi!`, `///H|||I\\\`, etc.
* If the user's reply does not match any previous responses, randomly select a response from the **entire** list of responses.
4. **Repeat steps 2 and 3 indefinitely**
## Rules
* Output must be exactly the same as the user originally entered it
* If a reply that needs to be added to the list of responses is already in the list, it can be optionally be added again (so it appears in the list twice)
* Input will never be empty and will only contain printable ASCII (code points `32` to `126`)
* All possible random values must have an equal chance of occurring
* Must be a full program (not just a function)
* Must output to `STDOUT` or closest equivalent
* Must take input from `STDIN` or closest equivalent
## Test Case
```
Hi!
> hi...
hi...
> HI
HI // could output "hi..." or "HI"
> How are you?
How are you? // could output "hi...", "HI" or "How are you?"
> Good.
Good. // could output "hi...", "HI", "How are you?" or "Good."
> ~!@#$*`'"(how ar%&e you_\|./<?
Good.
> Good.
~!@#$*`'"(how ar%&e you_\|./<? // could output "~!@#..." or "Good."
> 2Good.
HI // could output any of the user's previous replies
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins!
[Answer]
# JavaScript (ES6) ~~155~~ 148 bytes
```
c=t=>t.replace(/[^\dA-Z ]/gi,"");r=["Hi!"];for(a=[],m={};u=prompt(alert(o=r[new Date%r.length]));r=m[c(u)]||a)(m[o=c(o)]=m[o]||[]).push(u),a.push(u)
```
## Less golfed:
```
c=t=>t.replace(/[^\dA-Z ]/gi,"");
r=["Hi!"];
for(a=[], m={}; u=prompt( alert( o=r[new Date%r.length] ) );
r= m [ c(u) ] || a )( m[ o=c(o) ] = m[o] || [] ).push(u), a.push(u)
```
* *3 bytes saved thanks to @balint*
] |
[Question]
[
The Method of Finite Differences is a technique used to find the next term in a sequence of numbers, given that the sequence is governed by consecutive values of a certain polynomial. Given a list of `n` terms, the Method will be able to determine the degree of the polynomial, which is a maximum of `n+1`.
The Method works by arranging the numbers in order, like so.
```
4 8 15 16 23 42
```
Then the difference between any number and its neighbor to the right (given that it has a neighbor to the right) is written in the row below. Note that entries must be written one space (ASCII 20) to the right of the longest entry in the previous column.
```
4 8 15 16 23 42
4 7 1 7 19
```
The process is repeated until there is one entry left in the bottom row.
```
4 8 15 16 23 42
4 7 1 7 19
3 -6 6 12
-9 12 6
21 -6
-27
```
Then the bottom row's entry is duplicated.
```
4 8 15 16 23 42
4 7 1 7 19
3 -6 6 12
-9 12 6
21 -6
-27 -27
```
Then the above process for finding differences is reversed until there is a new entry in the first row, which is separated from the other entries by `|`
```
4 8 15 16 23 42 | 46
4 7 1 7 19 4
3 -6 6 12 -15
-9 12 6 -27
21 -6 -33
-27 -27
```
The Method moves down rows until all of the entries in a row are equal. Take the starting numbers `2 5 10 17 26`. This is the finished table.
```
2 5 10 17 26 | 37
3 5 7 9 11
2 2 2 2
```
The degree of the polynomial is the number of rows minus 1. As you might tell from the previous example, the polynomial is `x^2+1`.
---
Your program will take as its input a list of integers separated by whitespace. You may assume that the list contains only integers and has at least 2 elements (they need not be distinct; the resulting chart would have only 1 row). The program will output the entire table generated by the Method of Finite Differences, as defined above.
---
This is code golf. Standard rules apply. Shortest code in bytes wins.
[Answer]
# CJam, ~~74~~ ~~73~~ ~~71~~ 68 bytes
```
q~]{_2ew::-Wf*_)-}g0]W%{_W=@W=++_}*;)"|"\++]W%z{:s_:,$W=)f{Se]}}%zN*
```
[Try it online](http://cjam.aditsu.net/#code=q~%5D%7B_2ew%3A%3A-Wf*_)-%7Dg0%5DW%25%7B_W%3D%40W%3D%2B%2B_%7D*%3B)%22%7C%22%5C%2B%2B%5DW%25z%7B%3As_%3A%2C%24W%3D)f%7BSe%5D%7D%7D%25zN*&input=4%208%2015%2016%2023%2042)
The latest version uses the middle section of @MartinBüttner's proposed solution, which is 3 bytes shorter than what I had. The first part for calculating the difference rows was identical. The part for the final formatting was the same length, so I kept my original version. Martin's savings came from making the sum part of the list while the new values are calculated, and using a `*` instead of a `%` loop. That also simplified the insertion of the "|".
Explanation:
```
l Get one line of input.
~] Interpret input and wrap in list.
{ While loop to construct additional lines.
_2ew Copy and build pairs of subsequent numbers.
::- Reduce all number pairs by subtraction.
Wf* Multiply all of them by -1, since the reduction calculated 1st minus 2nd,
but we need 2nd minus 1st.
_)- Check if all numbers in list are equal by popping off last and removing
value from the list. This is truthy if all numbers are not equal.
}g End of while loop to construct additional lines.
0 Add a 0 at the end, which will be the starting point of the sum for
calculating the new values.
] Wrap all lines in a list.
W% Revert order of list, since adding the additional numbers in each row
goes in bottom-up order.
{ Start of loop over rows.
_W= Get last value of row.
@ Rotate previous row to top.
W= Extract last value as new increment. For the 0 that was added as an
additional row, this is a comparison with -1, which gives the desired
value of 0.
+ Add increment to last value.
+ Append value to list.
_ Copy row for use in next loop iteration.
}* End of loop over rows.
; Remove extra copy of last row.
) Pop off last value of last row.
"|" Push the vertical bar.
\ Swap vertical bar and last value.
++ Concatenate the 3 parts.
W% Revert order of list, to get the rows back in original order.
z Transpose list for handling column alignment.
{ Loop over columns.
:s Convert values to strings.
_:, Copy and calculate the length of all values.
$W= Get maximum length by sorting and getting last value.
) Increment to add space between columns.
f{ Apply to all values.
Se] Right pad to column width with spaces.
} End apply to all values.
}% End loop over columns.
z Transpose back to row order.
N* Join rows with newlines.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 93 bytes
```
{↑⍕¨¨{(⊂1⌽'|',⍨¯1⌽⊃⍵),(¯1↓1↓⍵),⊂(⊢,⊢/)⊃⌽⍵}⊃{(⊂⍺,(⊃⌽⍺)+⊃⌽⊃⍵),⍵}/⌽⊂@1⌽{⍵,⊂-2-/⊃⌽⍵}⍣{1≥≢∪⊃⌽⍺}⊂⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR28RHvVMPrTi0olrjUVeT4aOeveo16jqPelccWg/iPOpqftS7VVNHA8RtmwzCYD5QLVD9IiC9SF8TpAiotHdrLZAFNudR7y4dDZjwLk1tKBNqGEilPpjf5ACypBooADJR10hXH8ms3sXVho86lz7qXPSoYxXcsFqw8Vtr/6c9apvwqLcPbOiaR71bDq03Bvmmb2pwkDOQDPHwDP7vDlRTDeQAKXX1R90taQogrVzuCiYKFgqGpgqGZgpGxgomRkARIwUg10DB0FzByAwA "APL (Dyalog Unicode) – Try It Online")
The output format is a bit annoying, and takes up most of the space here.
] |
[Question]
[
Tony Stark is, as we know [*Ironman*](https://en.wikipedia.org/wiki/Iron_Man) (that super awesome guy in metal suit and loads of weapons). However, without the metal suit, he can't claim that title. Tony Stark, having a great ego, wants to finish [Norseman](https://en.wikipedia.org/wiki/Norseman_triathlon), which is considered to be the hardest triathlon in the world (for distances equivalent to those of an Ironman race), to prove that he's a mean machine, even when he leaves the iron at home.
Tony has a predefined schedule / time plan for each part of the competition.
That means for every location in the race (i.e. distance from start), there's an expected time he should arrive there based on the schedule.
He also has a watch that tells the time spent and the total distance covered.
Your task is: **Given those two values as input, tell Tony how much he is ahead of, or behind schedule.** The input will be a time on the format `hh:mm:ss` (or (optional) `h:mm:ss` if it's been less than 10 hours) and a decimal number telling how far he has come (in km).
The distances for each of the three disciplines are:
```
Swim: 3.8 km
Bike: 180 km
Run: 42 km
Total distance: 225.8 km // Input will never exceed 225.8
```
The estimated times for each part (i.e. the schedule):
```
Swim: 1:20:00
Transition 1: 0:12:00
Bike: 7:10:00
Transition 2: 0:05:00
Run: 4:50:00
Total: 13:37:00
```
Both distances, and the estimated times are given before the race, and can therefore be hardcoded. The transition zone is just a place where he changes clothes and equipment, so he's not moving during transition.
Input can be comma-separated, a string, two separate arguments or whatever is most convenient in your language. He want the output on the format `+/-mm:ss`, not hours (assume he's never more than one hour too slow or too fast. If he's in transition, you can assume he just got there.
**Examples and explanations (apologies for the length of it):**
```
Input: 04:32:20 93.8
Output: +34:40 / 34:40
```
At 93.8 km, he has finished the swim, been through transition and has finished half of the bike leg. According to the schedule, this should have taken him: `1:20:00 + 0:12:00 + (0.5 * (07:10:00)) = 5:07:00`. If he has used `4:32:20`, then he's `34:40` ahead of schedule.
---
```
Input: 1:20:00 3.8
Output: +00:00 / +0:00 / 00:00 / 0:00 / -00:00 / -0:00
```
Assuming the distance is `3.8`, you can assume he has just got into the first transition zone. The estimated time here was `1:20:00`, so for the input above, he's on time.
---
If the time is `1:25:00`, then he's 5 minutes behind schedule, thus:
```
Input: 1:25:00 3.8
Output: -05:00 / -5:00
```
---
Another example, explained in detail:
```
Input: 10:33:46 198.14
```
So, a distance of 198.14 km has been covered. That means he has finished the swim (3.8), the bike leg (180 km) and 14.34 km of the running, and he has been through both transitions. According to the schedule, he should have started the run after: `1:20:00 + 0:12:00 + 07:10:00 + 0:05:00 = 8:47:00`. 42 km of running should take 4:50:00, thus 14.34 km should take: `4:50:00 * (14.34 / 42) = 1:39:01`. So, according to the plan, 198.14 km should take: `8:47:00 + 1:39:01 = 10:26:01`. He has used `10:33:46`, which is `07:45` more than planned.
```
Output: -07:45 / -7:45
```
---
The plus sign is optional, but there has to be a minus sign if he's behind schedule.
The output should have exactly the same format as the examples above, but trailing spaces, newlines etc. are OK.
This is code golf, so the shortest code in bytes win.
[Answer]
# CJam, 91
```
r~[0_80 3.8_92 43dI183.8 527 290d42]4/{1$a<},W=(@\-\~/@*+60*r':/:i60b-i_gs);\60b2Te[':*)Amd
```
[Try it online.](http://cjam.aditsu.net/#code=r~%5B0_80%203.8_92%2043dI183.8%20527%20290d42%5D4%2F%7B1%24a%3C%7D%2CW%3D(%40%5C-%5C~%2F%40*%2B60*r'%3A%2F%3Ai60b-i_gs)%3B%5C60b2Te%5B'%3A*)Amd&input=198.14%2010%3A33%3A46) Note: it takes the distance first.
] |
[Question]
[
There are many types of binary operations, which can be categorized by their associative properties and their commutative properties.
* A binary operation `()` is *associative* if the order of operations between operands does not affect the result — i.e. if `(a(bc)) = ((ab)c)`.
* A binary operation `()` is *commutative* if the order of two operands within one operation does not affect the result — i.e. if `(ab) = (ba)`.
There are operations like addition and multiplication that are both associative and commutative, and operations like subtraction and division that are neither associative nor commutative.
There are also operations — such as the group composition operator — that are associative but not commutative.
But then there are operations that are commutative but not associative. These are more rare and not analyzed as much mathematically, but they occur. For example, rounded multiplication is such an operation. If you round a calculation to the nearest tenth after every multiplication, you can get anomalies like `(6.8 × 5.7) × 2.9 = 112.5` while `6.8 × (5.7 × 2.9) = 112.2`.
---
Let a permutation of the operands `P` in an operation tree (such as `((x(xx))((x(xx))x))`) be *associatively equivalent* to another permutation `Q`, if the operands in `P` can be rearranged by the commutative property to form an operation tree identical to the original.
For example, permutations `(a(b(c(de))))` and `(a(b(c(ed))))` of the operation tree `(x(x(x(xx))))` are equivalent, because `d` commutes with `e`. However, `(a(b(c(de))))` and `(a(b(d(ce))))` are not equivalent, because `(c(de))` is not equal to `(d(ce))`.
A more complex example might be `(((ab)c)(d(ef)))` and `(((ef)d)(c(ba)))`. Step-by-step, the two of these can be shown to be equivalent as follows:
```
(((ab)c)(d(ef))) = (((ba)c)(d(ef))) since a commutes with b
(((ba)c)(d(ef))) = (((ba)c)((ef)d)) since (ef) commutes with d
(((ba)c)((ef)d)) = ((c(ba))((ef)d)) since (ba) commutes with c
((c(ba))((ef)d)) = (((ef)d)(c(ba))) since (c(ba)) commutes with ((ef)d)
```
Permutations of different operation trees are not comparable. `(a(b(c(de))))` and `((((ab)c)d)e)` are neither associatively equivalent nor associatively distinct, because their operation trees are different.
---
Your task is to build a program that will find all the associatively equivalent permutations of the operands of a given operation tree.
Your program will take input in the form given above, with brackets enclosing juxtaposed operators. The operands will always be lowercase letters, in alphabetical order starting from `a`, and will contain a maximum of 26 letters.
Your program will output a series of permutations of the letters, without the brackets, representing all of the permutations that are associatively equivalent with the original permutation.
For example, if you are given an input of:
```
((ab)(cd))
```
Then your program will output:
```
abcd
abdc
bacd
badc
cdab
cdba
dcab
dcba
```
Your program must be accompanied by a description of its algorithm, and a proof of its asymptotic runtime with respect to the number of operands in the operation tree. The program with the lowest asymptotic runtime in this manner wins.
[Answer]
Every parenthesis has in it two elements, either a terminal symbol, or another parenthesis. These two elements have two possible permutations, `ab` and `ba`.
This means that the expression forms a binary tree, and every node inside the tree has two possible permutations. So the total output is always *2n* where n is the number of parenthesis pairs. This means that an asymptotical algorithm will always do this amount of work.
For this optimal algorithm we will parse the expression, then recursively generate possibilities, 2 for each parenthesis pair. As seen in the paragraph above, this is optimal.
```
def parse(inp):
c = inp.pop(0)
while c == ")": c = inp.pop(0)
if c == "(":
return [parse(inp), parse(inp)]
return c
def possibs(tree):
if len(tree) == 2:
for left_possib in possibs(tree[0]):
for right_possib in possibs(tree[1]):
yield left_possib + right_possib
yield right_possib + left_possib
else:
yield tree
tree = parse(list("((ab)(cd))"))
for possib in possibs(tree):
print(possib)
```
] |
[Question]
[

**Challenge**
A Pixel World is a PNG image where gravitational, electromagnetic, and nuclear forces no longer exist. Special forces known as "pixel forces" are all that remain. We define this force as
>
> Fp->q = a \* (p \* q) / (r \* r) \* r̂
>
>
>
* `F` is the pixel force that `p` exerts on `q`
* `a` is Adams' constant, defined as `a = 4.2 * 10 ^ 1`
* `p` and `q` are charges on two pixels
* `r` is the distance from `p` to `q`
* `r̂` is the direction of r in radians, measured counterclockwise\* from the positive x-axis
\*There are infinitely many acceptable values for any given direction. For example, 6.28, 0, -6.28, and -12.57 radians are all equivalent, and would all be accepted.
Three types of pixels exist:
* A red pixel holds a charge of positive one
* A black pixel holds a charge of negative one
* A white pixel holds a charge of zero
The bottom left pixel of pixel world is located at `(0, 0)`. The positive y axis falls up the page, and the positive x axis falls to the right. The total force on a pixel is simply the vector sum of all forces exerted upon that pixel. Like charges repel, and opposite charges attract.
Given a file path to a Pixel World, as well as two integers `x` and `y`, output the total force exerted on the pixel at location `(x, y)` in the format `<magnitude>\n<direction>`. Output must be accurate to at least 2 decimal places, but you may output more if you want. Direction must be output in radians. The integers `x` and `y` are guaranteed to be within the world boundary.
**Deliverables**
You must include a program, and a command that can be used to run your program. Two examples:
>
> python AbsolutelyPositive.py "C:\Pixtona.png" 50 40
>
> java UltimateAttraction "C:\Jupix.png" 30 30
>
>
>
**Example Image**
In the [image below](https://i.stack.imgur.com/ZoBIi.png), there is a black pixel at `(100, 104)`.
>
> Pixars.png
>
>
> 
>
>
>
**Example Output**
This output does *not* correspond to the above input.
>
> 534.19721014
>
> 4.32605416
>
>
>
**Need help getting started?**
I wrote some example code [here](https://docs.google.com/document/d/1iMaakjmPhZu_Un4zGQRtKH7jNIrRLvkAX5-3H6igVKQ/edit?usp=sharing). I haven't tested it, so use it at your own risk.
[Answer]
## Python - 355
```
import sys,Image,math as m
i=Image.open(sys.argv[1])
w,h=i.size
a=i.load()
X,Y=map(int,sys.argv[2:])
t=m.atan2
c=lambda i,j:2*(a[i,j][0]>200)-(a[i,j][1]>200)-1
p=c(X,h-1-Y)
V=H=0
for j in range(h):
for i in range(w):q=c(i,h-1-j);y=Y-j;x=X-i;r=x*x+y*y;f=r and 42.*p*q/r;V+=m.cos(t(x,y))*f;H+=m.sin(t(x,y))*f
d=t(V,H)
print(V**2+H**2)**.5,[d,m.pi*2+d][d<0]
```
**Ungolfed**
```
import sys
import Image
import math as m
X,Y=map(int,sys.argv[2:]) # The X and Y coordinates of the test pixel
i=Image.open(sys.argv[1]) # Open the image
w,h=i.size # Get the width and height of the image
a=i.load() # Get a pixel access object of the image
V=0 # V = vector sum of Vertical Forces
H=0 # H = vector sum of Horizontal Forces
# Function to calculate the charge of the a pixel at x=i, y=j
def c(i,j):
global a
if a[i,j][0]>200: # If Red > 200
if a[i,j][2]>200: # If Green > 200
return 0 # We assume that pixel is White
else:
return 1 # We assume that pixel is Red
return -1 # Else, we asusme that pixel is Black
p=c(X,h-1-Y) # Assign the charge of the test pixel to p
for j in range(h): # For every y value...
for i in range(w): # For every x value...
q=c(i,h-1-j) # Assign the charge of the current pixel to q
y=Y-j # The y distance of the test pixel from the current pixel
x=X-i # The x distance of the test pixel from the current pixel
rSquared=x*x+y*y # The r-squared distance between the 2 pixels
f=rSquared and 42.*p*q/rSquared # If rSquared is > 0, calculate the force.
# Otherwise, the force is zero
V+=m.cos(m.atan2(x,y))*f # Add the Y component of the force to V
H+=m.sin(m.atan2(x,y))*f # Add the X component of the force to H
d=m.atan2(V,H)
print(V**2+H**2)**.5,[d,m.pi*2+d][d<0]
```
**Some little program used to create tests:**
```
import Image
width = 100 # Define your own image width
height = 100 # Define your own image height
image = Image.new("RGB", (width, height), "white")
pixels = image.load()
blacks = [(0,0), (1,1)] # Define your own black pixels
reds = [(0,1), (1,0)] # Define your own red pixels
for x,y in blacks:
pixels[x,height-1-y] = (0,0,0)
for x,y in reds:
pixels[x,height-1-y] = (255,0,0)
image.save("y.png") # Save image
```
**Sample tests:**

```
Users-MacBook-Air:pngforces User$ python z3.py y.png 0 0
59.3969696197 0.785398163397
```

```
Users-MacBook-Air:pngforces User$ python z3.py y.png 50 50
0.0084 3.92699081699
```

```
Users-MacBook-Air:pngforces User$ python z3.py y.png 50 50
0.0084 0.785398163397
```
Just posting first... If there are any mistakes or issues, drop a comment down below, but will probably take quite some time to respond cuz I am really busy with other stuff.
] |
[Question]
[
With a window similar to the one pictured below, you are given a list of strings, which you want to put in alphabetical order.

As shown, you have five operations:
* Move up [U] - moves the selected string up one place
* Move down [D] - moves the selected string down one place
* Move first [F] - moves the selected string to the top of the list
* Move last [L] - moves the selected string to the bottom of the list
* Reverse [R] - reverses the order of the list
Using STDIN, accept a number (how many strings), followed by the unordered list of strings. Each string consists of 2-99 lower case English letters. (The example above would not be a valid input.)
Using STDOUT, print the way to put the list in order. First, mention an item to select, and then the operations(s) to perform on it in order to put the list in alphabetical order.
For example: `February U December F May D D June D R D...`
Explanation: Click February, move it up 1. Select December, move it to top. May, move it down twice. June, move down once, reverse the list, move down again...
Since there are obviously many valid solutions, you must choose the shortest possible. That is, choose the method with the fewest number of operations (7 in the above example).
If there's a tie among correct outputs to the input, resolve it in the following order.
1. Choose the one with the fewest string selections (4 in the above example).
2. Choose the one with the fewest operations, counting consecutive identical operations (on one string) as one (6 in the above example).
3. Choose the one with shortest output (least number of total characters, counting spaces).
4. Choose the one with the output that comes first alphabetically.
This is code-golf; the shortest submission which always produces the correct output wins.
## Examples
* IN `2 zz abc`
+ OUT `zz D`
* IN `3 cc bb aa`
+ OUT `aa R`
* IN `4 abc def cd ccc`
+ OUT `abc L R`
* IN `6 rr mm nn oo qq pp`
+ OUT `pp U rr L`
### Additional examples (provided by Scott Leadley, any errors are mine and not ypnypn's)
Some difficult cases:
* **IN** => **OUT**
* `6 xx aa dd bb ee cc` => `dd L ee L xx L`
* `7 aa bb ee cc dd ff gg` => `ee D D`
* `8 dd ww aa bb cc xx yy zz` => `ww D D D dd D D D`
+ (**not** the minimial number of moves, which would be `cc F bb F aa F`)
Permutations of 4 items `aa bb cc dd` with sort paths of length >1:
* **IN** => **OUT**
* `4 aa cc dd bb` => `bb F D`
* `4 aa dd cc bb` => `aa L R`
* `4 bb aa dd cc` => `aa F cc U`
* `4 bb dd aa cc` => `aa F cc U`
* `4 bb dd cc aa` => `bb D D R`
* `4 cc aa bb dd` => `cc D D`
* `4 cc aa dd bb` => `bb F aa F`
* `4 cc bb aa dd` => `dd F R`
* `4 cc bb dd aa` => `dd F R`
* `4 cc dd aa bb` => `bb F aa F`
* `4 cc dd bb aa` => `cc D R`
* `4 dd aa cc bb` => `aa L R`
* `4 dd bb aa cc` => `cc F D R`
* `4 dd bb cc aa` => `bb D R`
* `4 dd cc aa bb` => `aa D R`
Variations on a theme, 4 items `aaaaa bbbb ccc dd` where string length makes a difference:
* **IN** => **OUT**
* `4 ccc dd aaaaa bbbb` => `ccc L dd L`
* `4 bbbb aaaaa dd ccc` => `bbbb D dd D`
* `4 bbbb dd aaaaa ccc` => `dd L bbbb D`
* `4 ccc aaaaa dd bbbb` => `ccc L dd L`
* `4 ccc dd bbbb aaaaa` => `dd F R`
* `4 dd bbbb ccc aaaaa` => `ccc R D`
* `4 dd ccc aaaaa bbbb` => `bbbb R D`
[Answer]
**Python 2 - ~~593~~ 521**
It's very brute-force with some efficiencies so it would actually finish. The 6-item list I'm testing with is taking around 5 seconds on my laptop.
```
$ time echo 5 xx aa dd bb ee cc | python order.py
dd L ee L xx L
real 0m4.444s
user 0m4.388s
sys 0m0.051s
```
Note that I'm ignoring the number in the input. I find it useless.
```
import sys
def d(l,s,o,f):
p=len(o)
tl=tuple(l)
if tl in s and p>=len(s[tl]) or f and p>=len(f):
return
if l==sorted(l):
return o if not f or p<len(f) else None
s[tl]=o
x=d(l[::-1],s,o+[l[-1]+' R'],f)or f
for n,i in enumerate(l):
for j,k in ([(l[:n]+[l[n+1],l[n]]+l[n+2:],'D'),(l[:n]+l[n+1:]+[l[n]],'L')]if(n!=len(l)-1)else[])+([(l[:n-1]+[l[n-1],l[n]]+l[n+1:],'U'),([l[n]]+l[:n]+l[n+1:],'F')]if(n!=0)else[]):
x=d(j,s,(o+[i+' '+k]),x)or x
return x
print ' '.join(d(sys.stdin.read().split()[1:],{},[],[]))
```
Ugh, I just realized I'm not handling multiple operations on the same value correctly. I'll try to fix that.
[Answer]
# Ruby 2.0
With the operator set [U,D,F,L], the fewest number of string selects to sort the list is the number of items in the list minus the longest common subsequence. To add the R operator, just reverse the string and apply the same rule. Unfortunately, minimizing string selects is not the same as minimizing the number of operations. For example, for an input of `8 dd ww aa bb cc xx yy zz`, the correct answer is `ww D D D dd D D D`, but the fewest number of operations (that meets the other criteria in the question) would be `cc F bb F aa F`. This means that a much larger portion of the set of possible sort paths needs to be explored.
This solution uses a depth-first search strategy and alpha-beta pruning. It's important to lower the alpha value rapidly to minimize the search depth, otherwise the search tree explodes exponential. E.g. to determine the sort path with the minimum score for OP's introductory example, sorting months in calendar order to lexical order, will probably take a few decades with this program's current scoring method. The program finds the minimum number of string selects, 8, very quickly. Unfortunately, that still leaves an enormous tree to walk through.
I'm using gnome sort as my scoring function because:
1. it's simple to understand and modify
2. the scoring *usually* converges to the optimal alpha quickly
3. this implementation is faster than my LCS function implementation
4. it will golf better than the LCS function
Number 4 would be sufficient. Everything else is a bonus.
For a depth-first search, the order in which operations are explored has a significant impact on the search time. Since any non-empty set of N items can be sorted with ≤ N-1 F(irst) or L(ast) operations, those operations are tried first.
```
# gnome sort
def gnomeSort(a)
selects = 0
previous = nil
i = 1
while i < a.size
if a[i-1] <= a[i]
# the array a[0..i] is sorted
i += 1 # take another bite
else
if a[i] != previous
previous = a[i]
selects += 1
end
a[i], a[i-1] = a[i-1], a[i]
if (i > 1)
i -= 1
end
end
end
return selects
end
def score(a)
return gnomeSort(a.dup)
end
# squeeze out unnecessary operands
def consolidate(a)
# separate operands and operators
x = [] # operands
f = [] # operators
a.each_slice(2) { |a,b|
x << a
f << b
}
n = x.size # number of (operand operator) pairs
if n>=2
# replace all R operands with the lexically lower operand
# from the right or left
f.each_with_index{|v,i|
if v=='R'
leftOperand = x[i-1]
rightOperand = x[i+1]
# handle left & right edge cases
leftOperand = rightOperand.succ if i==0
rightOperand = leftOperand.succ if i>=n-1
x[i] = [leftOperand, rightOperand].min
end
}
# replace repeated operands with <nil>
x = x.chunk{|e|e}.map{|v|v[1].fill(nil,1)}.flatten
end
return [x, f]
end
@solutions = []
@operation = []
@operation[3] = ->(a, i) {
# swap a[i] and a[i-1]
return nil if i<1 || i>=a.size
v = a[i]
a[i-1], a[i] = a[i], a[i-1]
return [ v, 'U' ]
}
@operation[0] = ->(a, i) {
# move a[i] after a.last
return nil if i+1>=a.size
a.push(v=a.delete_at(i))
return [ v, 'L' ]
}
@operation[4] = ->(a, i) {
# reverse the whole array
v = a[i]
a.reverse!
return [ v, 'R' ]
}
@operation[1] = ->(a, i) {
# move a[i] before a.first
return nil if i<=0
a.unshift(v=a.delete_at(i))
return [ v, 'F' ]
}
@operation[2] = ->(a, i) {
# swap a[i] and a[i+1]
return nil if i<0 || i+1>=a.size
v = a[i]
a[i], a[i+1] = a[i+1], a[i]
return [ v, 'D' ]
}
def alphaSort(depth, a, selected, selects, sortPath)
depth += 1
return if selects > @alpha
return if selects>@alpha || selects+depth>a.size+1
if a.each_cons(2).all?{ |x, y| x <= y }
# found a sort path
@alpha = selects
@solutions << sortPath.flatten.compact
else
selectsFromHere = score(a)
if @alpha > selects+selectsFromHere
@alpha = selects+selectsFromHere
else
end
@operation.each do |op|
a.each_index do |i|
b = a.dup
branch = sortPath.dup << op[b,i]
alphaSort(depth, b, a[i], selects+(selected==a[i] ? 0 : 1), branch)
end
end
end
end
# input
a = ARGF.read.scan(/\w+/m) # alternative, $*[0].scan(/\w+/m)
a.shift # ignore the item count
# depth-first search of sort operations
@alpha = [a.size-1, score(a), score(a.reverse)+1].min + 1
alphaSort(0, a, nil, 0, [])
# winnow the set of solutions
# determine the minimum number of string selects to solve
# short-circuit if selects to solve is 0 (already sorted)
@solutions.map!{|v|consolidate v}
minSelects = @solutions.map{|v|v[0].compact.size}.min
if !minSelects
puts
exit
end
# keep only solutions with the minimum number of string selects
@solutions.reject!{ |v| v[0].compact.size > minSelects }
# determine the minimum number of moves in the remaining solutions
minMoves = @solutions.map{|v|v[1].size}.min
# keep only solutions with the minimum number of moves
@solutions.reject!{ |v| v[1].size > minMoves }
# beauty contest
# turn into strings
solutions = @solutions.map{|v|v[0].zip(v[1]).flatten.compact*' '}
# keep the shortest strings
minLength = solutions.map{|v|v.size}.min
solutions.reject!{ |v| v.size > minLength }
# print the string that "that comes first alphabetically"
puts solutions.sort.first
```
It passes this [perl TAP](http://search.cpan.org/~rgarcia/perl-5.10.0/lib/Test/Tutorial.pod) test suite:
```
use strict;
use warnings;
use Test::More qw(no_plan);
#use Test::More tests => 61;
# solution executable
my $solver = 'ruby2.0 sortshort.rb';
my $nonTrivial = 1;
# "happy" path
# examples from OP
is( `echo 2 zz abc | $solver 2>&1`, "zz D\n", 'OP example #1');
is( `echo 3 cc bb aa | $solver 2>&1`, "aa R\n", 'OP example #2');
is( `echo 4 abc def cd ccc | $solver 2>&1`, "abc L R\n", 'OP example #3');
is( `echo 6 rr mm nn oo qq pp | $solver 2>&1`, "pp U rr L\n", 'OP example #4');
# example from bizangles
is( `echo 6 xx aa dd bb ee cc | $solver 2>&1`, "dd L ee L xx L\n", 'wascally wabbit, challenges deep diver (from bizangles)');
SKIP: {
skip('non-trivial tests', 2) unless $nonTrivial;
# 7 item example; bizangles' python solution (circa 2014-08-22) requires higher sys.setrecursionlimit() and takes about 5 minutes
is( `echo 7 aa bb ee cc dd ff gg | $solver 2>&1`, "ee D D\n", 'shallow');
# minimizing the number of selects scores better than minimizing moves
# minimizing moves => cc F bb F aa F
# minimizing selects => dd D D D D ww D D D D, ww D D D dd D D D, ww L U U U dd D D D, etc.
# minimizing selects, then moves => ww D D D dd D D D
is( `echo 8 dd ww aa bb cc xx yy zz | $solver 2>&1`, "ww D D D dd D D D\n", 'joker, minimize selects before moves');
}
# exhaustive variations on a theme with 1 item ["aa"]
is( `echo 1 aa | $solver 2>&1`, "\n", 'permutations of 1, #1');
# exhaustive variations on a theme with 2 items ["ab", "c"]
is( `echo 2 ab c | $solver 2>&1`, "\n", 'permutations of 2, #1');
# test OP's requirement that a string be selected before reverse operation
is( `echo 2 c ab | $solver 2>&1`, "c D\n", 'permutations of 2, #2');
# exhaustive variations on a theme with 3 items ["five", "four", "three"]
is( `echo 3 five four three | $solver 2>&1`, "\n", 'permutations of 3, #1');
is( `echo 3 five three four | $solver 2>&1`, "four U\n", 'permutations of 3, #2');
is( `echo 3 four five three | $solver 2>&1`, "five F\n", 'permutations of 3, #3');
is( `echo 3 four three five | $solver 2>&1`, "five F\n", 'permutations of 3, #4');
is( `echo 3 three five four | $solver 2>&1`, "three L\n", 'permutations of 3, #5');
is( `echo 3 three four five | $solver 2>&1`, "five R\n", 'permutations of 3, #6');
# selected variations on a theme with 5 items ["aa", "bb", "cc", "dd", "ee"]
is( `echo 5 aa bb cc dd ee | $solver 2>&1`, "\n", 'permutations of 5, #1, already sorted');
# two sort paths of length 1
is( `echo 5 aa bb cc ee dd | $solver 2>&1`, "dd U\n", 'permutations of 5, #2, single U or D');
is( `echo 5 aa bb ee cc dd | $solver 2>&1`, "ee L\n", 'permutations of 5, #4, single L');
is( `echo 5 bb cc aa dd ee | $solver 2>&1`, "aa F\n", 'permutations of 5, #31, single F');
is( `echo 5 ee dd cc bb aa | $solver 2>&1`, "aa R\n", 'permutations of 5, #120, reverse sorted');
# exhaustive variations on a theme with 4 items ["aa", "bb", "cc", "dd"]
# sort paths of length 0
is( `echo 4 aa bb cc dd | $solver 2>&1`, "\n", 'permutations of 4, #1');
# sort paths of length 1
is( `echo 4 aa bb dd cc | $solver 2>&1`, "cc U\n", 'permutations of 4, #2');
is( `echo 4 aa cc bb dd | $solver 2>&1`, "bb U\n", 'permutations of 4, #3');
is( `echo 4 aa dd bb cc | $solver 2>&1`, "dd L\n", 'permutations of 4, #5');
is( `echo 4 bb aa cc dd | $solver 2>&1`, "aa F\n", 'permutations of 4, #7');
is( `echo 4 bb cc aa dd | $solver 2>&1`, "aa F\n", 'permutations of 4, #9');
is( `echo 4 bb cc dd aa | $solver 2>&1`, "aa F\n", 'permutations of 4, #10');
is( `echo 4 dd aa bb cc | $solver 2>&1`, "dd L\n", 'permutations of 4, #19');
is( `echo 4 dd cc bb aa | $solver 2>&1`, "aa R\n", 'permutations of 4, #24');
# sort paths of length 2
is( `echo 4 aa cc dd bb | $solver 2>&1`, "bb F D\n", 'permutations of 4, #4');
is( `echo 4 aa dd cc bb | $solver 2>&1`, "aa L R\n", 'permutations of 4, #6');
is( `echo 4 bb aa dd cc | $solver 2>&1`, "aa F cc U\n", 'permutations of 4, #8');
is( `echo 4 bb dd aa cc | $solver 2>&1`, "aa F cc U\n", 'permutations of 4, #11');
is( `echo 4 bb dd cc aa | $solver 2>&1`, "bb D D R\n", 'permutations of 4, #12');
is( `echo 4 cc aa bb dd | $solver 2>&1`, "cc D D\n", 'permutations of 4, #13');
is( `echo 4 cc aa dd bb | $solver 2>&1`, "bb F aa F\n", 'permutations of 4, #14');
is( `echo 4 cc bb aa dd | $solver 2>&1`, "dd F R\n", 'permutations of 4, #15');
is( `echo 4 cc bb dd aa | $solver 2>&1`, "dd F R\n", 'permutations of 4, #16');
is( `echo 4 cc dd aa bb | $solver 2>&1`, "bb F aa F\n", 'permutations of 4, #17');
is( `echo 4 cc dd bb aa | $solver 2>&1`, "cc D R\n", 'permutations of 4, #18');
is( `echo 4 dd aa cc bb | $solver 2>&1`, "aa L R\n", 'permutations of 4, #20');
is( `echo 4 dd bb aa cc | $solver 2>&1`, "cc F D R\n", 'permutations of 4, #21');
is( `echo 4 dd bb cc aa | $solver 2>&1`, "bb D R\n", 'permutations of 4, #22');
is( `echo 4 dd cc aa bb | $solver 2>&1`, "aa D R\n", 'permutations of 4, #23');
# variations on a theme with 4 items ["aaaaa", "bbbb", "ccc", "dd"]
# force choice by string length
is( `echo 4 ccc dd aaaaa bbbb | $solver 2>&1`, "ccc L dd L\n", 'permutations of 4, #17');
is( `echo 4 dd bbbb aaaaa ccc | $solver 2>&1`, "ccc F D R\n", 'permutations of 4, #21');
is( `echo 4 bbbb aaaaa dd ccc | $solver 2>&1`, "bbbb D dd D\n", 'permutations of 4, #8');
is( `echo 4 bbbb dd aaaaa ccc | $solver 2>&1`, "dd L bbbb D\n", 'permutations of 4, #11');
is( `echo 4 ccc aaaaa dd bbbb | $solver 2>&1`, "ccc L dd L\n", 'permutations of 4, #14');
is( `echo 4 ccc dd bbbb aaaaa | $solver 2>&1`, "dd F R\n", 'permutations of 4, #18');
is( `echo 4 dd aaaaa ccc bbbb | $solver 2>&1`, "aaaaa L R\n", 'permutations of 4, #20');
is( `echo 4 dd bbbb ccc aaaaa | $solver 2>&1`, "ccc R D\n", 'permutations of 4, #22');
is( `echo 4 dd ccc aaaaa bbbb | $solver 2>&1`, "bbbb R D\n", 'permutations of 4, #23');
# identical items in list
is( `echo 2 aa aa | $solver 2>&1`, "\n", '1 repeat #1');
is( `echo 3 aa aa bb | $solver 2>&1`, "\n", '1 repeat #2');
is( `echo 3 aa bb aa | $solver 2>&1`, "aa F\n", '1 repeat #3');
is( `echo 3 bb aa aa | $solver 2>&1`, "aa R\n", '1 repeat #4');
is( `echo 4 aa cc bb aa| $solver 2>&1`, "aa L R\n", '1 repeat #5');
is( `echo 5 cc bb aa bb cc | $solver 2>&1`, "aa F cc L\n", '2 repeats');
# "sad" path
# not explicitly excluded, so cover this case
# exhaustive variations on a theme with 0 items []
is( `echo 0 | $solver 2>&1`, "\n", 'permutations of 0, #1');
# "bad" path
# none!
exit 0;
```
] |
[Question]
[
Write the shortest program possible that traps the mouse cursor inside an upward pointing equilateral triangle with a side length of 274 pixels and a centroid at the exact middle of the screen.
(Triangle because of cheese wedges.)
While your program is running, the tip of the cursor should never be able to move outside of this triangle, and should move and function normally inside. When the `Esc` key is hit the program must end, releasing the mouse.
# Scoring
This is code-golf, the shortest code in bytes wins. You may only use standard ASCII.
# Details
* Besides things like shutting off the computer or killing the process or pressing `Alt-F4` or `Ctrl-Alt-Delete`, the only way to release the cursor should be the `Esc` key.
* If the cursor is outside the triangle when the program starts it should be placed somewhere inside.
* The cursor must be able to move smoothly up and down the two angled sides of the triangles.
* If the display is extended over multiple monitors the triangle may appear in the center of any one monitor or the center of all of them combined. (If you only have one monitor you do not need to test for this.)
* It's fine if touchscreen users can still click things outside the triangle.
*Tiny bonus question:* Where did I get 274 from?
[Answer]
## Python ~~418~~ ~~351~~ ~~314~~ ~~300~~ 263 Bytes
Edit: Saved ~~67~~ ~~104~~ ~~118~~ 155 Bytes thanks to the advice in the comments
```
from win32api import*
from msvcrt import*
s=137
G=GetSystemMetrics
S=SetCursorPos
x=G(0)//2
y=G(1)//2
c=3**.5
Y=y-2*s/c
S((x,y))
while(kbhit()and ord(getch())==27)<1:a,b=GetCursorPos();S((min(max(a,x-s),x+s),min(max(b,int(c*a+Y-c*x),int(-c*a+Y+c*x)),int(y+s/c))))
```
Written in Python 3.4.1 on Windows, pywin needs to be installed.
My first code golf submission. Please feel free to suggest improvements
[Answer]
# AutoHotKey (249)
```
CoordMode,Mouse
Esc::ExitApp
U(a,b){
return(a+b+abs(a-b))/2
}
L(a,b){
return(a+b-abs(a-b))/2
}
t::
SysGet,X,0
Sysget,Y,1
M:=X/2
N:=Y/2
Loop{
MouseGetPos,x,y
MouseMove L(U(M-137,x),M+137),L(U(N-118+1.732*abs(x-M),y),N+119),0
}
return
```
It doesn't have inbuilt min/max functions, so I spent 72 chars reimplementing them.
Press `t` to trap the cursor, I dont know if its possible to do stuff without assigning it to a hotkey.
The movement is not very smooth, unless you move the mouse slowly

] |
[Question]
[
Flux is very similar to the [Fifteen Puzzle](https://codegolf.stackexchange.com/questions/6884/solve-the-15-puzzle-the-tile-sliding-puzzle).
However, instead of numbers, the squares are colors.
* There are 4 colors: Red, Yellow, Blue, and Gray.
+ There are *exactly* 4 red squares, 4 yellow squares, 2 blue squares, 1 gray square, and 1 empty square.
* The grid has 3 rows and 4 columns
* A grid configuration is **solved** when the **top row** is exactly the same as the **bottom row**.
* The middle row is *not relevant* when considering whether the board is solved.
* You do not have to handle invalid input. Trust that there will be the correct number of each of the input symbols.
## Input
* You must accept an input of twelve of these characters that use these symbols to represent a square on the board:
+ `RYGB_`
* These input characters **must** be interpreted to go across, then down.
* It is your choice whether you require some other character (newline, EOF, whatever) to terminate input, or just go as soon as you've received 12 characters.
Example:
```
YRGYB_BRRYYR
```
which corresponds to to the board:
```
YRGY
B_BR
RYYR
```
## Output
* You must output the moves required for an **OPTIMAL** solution
* These will use the characters `LRUD` for Left, Right, Up, Down. This is considered to be the "piece moves to the left", **not** the "emptiness moves to the left"
Example:
```
LURDRDLULDLU
```
And then print out the resulting board. For the example we've used so far:
```
RBYR
YYG_
RBYR
```
## Other rules
* Your program must run in under 15 seconds or it is disqualified.
+ Make sure to try it with the following board: `RRRRBG_BYYYY`
+ That board, with it's three symmetries, is the "hardest" possible board.
* You may not use any external resources, or have any input data files.
## Some stats
* There are exactly 415,800 possible boards
* There are exactly 360 "solution" boards
* My program that I wrote to test this out runs in about 2 seconds in Java, without much optimization.
+ This program, with minimal golfing, is 1364 bytes.
## Scoring
* This is code-golf, fewest characters that meets the other requirements wins!
[Answer]
# Smalltalk 497
```
|b R M s g a|
b:=Stdin nextLine.R:='D--R-L--U'.
M:=#((6 9)(4 6 9)(4 6 9)(4 9)(1 6 9)(1 4 6 9)(1 4 6 9)(1 4 9)(6 1)(4 6 1)(4 6 1)(4 1)).
s:=Set new.q:=OrderedCollection new.
a:=[:p :m|(s includes:p)ifFalse:[s add:p.q add:p->m]].
a value:b value:''.
[|x i n p|
x:=q removeFirst.p:=x key.i:=(p indexOf:$_).
(M at:i)do:[:m||v|
n:=p copy.n at:i put:(p at:i+m-5);at:i+m-5put:$_.
v:=(x value,(R at:m)).
(n to:4)=(n from:9)ifTrue:[
v printCR.(n splitForSize:4)map:#printCR.^self].
a value:n value:v]]loop.
```
Input:
```
YRGYB_BRRYYR
```
Output:
```
DLURRULDDLLU
YBYR
RGR_
YBYR
```
Exec. Time (bytecode, not jitted): 100ms
Input:
```
RRRRBG_BYYYY
```
Output:
```
DRRUULLDLURDDRRULULD
YBRR
GY_Y
YBRR
```
Exec. Time 2s unjitted; 0.8s jitted (most time spent in collection code)
Here is an ungolfed version for readability:
```
|b R M s g add|
b:=Stdin nextLine.
R:='D--R-L--U'.
M:=#((6 9)(4 6 9)(4 6 9)(4 9)
(1 6 9)(1 4 6 9)(1 4 6 9)(1 4 9)
(6 1)(4 6 1)(4 6 1)(4 1)).
s := Set new.
queue := OrderedCollection new.
add := [:p :m |
(s includes:p) ifFalse:[
s add:p.
queue add:(p->m).
]].
add value:b value:''.
[
|x i n p|
x := queue removeFirst.
p := x key.
i := (p indexOf:$_).
(M at:i) do:[:m |
|v|
n := p copy.
n at:i put:(p at:i+m-5); at:i+m-5 put:$_.
v:=(x value,(R at:m)).
(n to:4)=(n from:9) ifTrue:[
v printCR.
(n splitForSize:4) map:#printCR.
^ self
].
add value:n value:v]
] loop.
```
[Answer]
# Python 372
This was longer than I expected, I might go back later and see if I can optimize more. It uses a pretty inefficient method of brute-forcing the answer, but it seems to consistently run at no more than 8 seconds on my relatively old laptop.
```
A=lambda s,i,n:s[:i]+n+s[i+1:]
def M(b):
i=b.find('_')
for d,n in([('L',i+1)]if i%4<3 else[])+([('R',i-1)]if i%4>0 else[])+([('D',i-4)]if i>4 else[])+([('U',i+4)]if i<8 else[]):yield d,A(A(b,i,b[n]),n,'_')
def F():
c=[('',raw_input())]
while 1:
for (m,b)in c:
if b[:4]==b[8:]:return m,b
c=[(m+d,n)for(m,b)in c for(d,n)in M(b)]
print F()
```
[Answer]
# Java 1364
I golfed this some but I'm sure there's plenty more I could do. For example I close the input stream which is not necessary ;) I just wanted to put **something** up.
```
import java.util.*;class F{enum D{R{B b(B i){return i.z==3?null:g(i,1);}},L{B b(B i){return i.z==0?null:g(i,-1);}},D{B b(B i){return i.y==2?null:g(i,4);}},U{B b(B i){return i.y==0?null:g(i,-4);}};abstract B b(B i);B g(B i,int f){f+=4*i.y+i.z;char[]s=i.s.toCharArray();s[i.e]=s[f];s[f]='_';return w.get(new String(s));}}enum C{_,G,B,R,Y;}class B{C[][]a=new C[3][4];String s;int y,z,e,c;B p;D d;B(String p){int i,j,q;for(i=0;i<3;i++){for(j=0;j<4;j++){q=4*i+j;a[i][j]=C.valueOf(p.substring(q,q+1));if(a[i][j]==C._){y=i;z=j;e=q;}}}s=p;}boolean v(){return Arrays.equals(a[0],a[2]);}void p(B b,D n){p=b;d=n;c=p.c+1;}String g(){String u="\n";for(int i=0;i<3;i++,u+="\n")for(int j=0;j<4;j++)u+=a[i][j];return u;}}Set<B>b=new HashSet<B>(),p;static Map<String,B>w=new HashMap<>();void p(String f,String s){int n=s.length();if(n==0){B o=new B(f);w.put(f,o);if(o.v())b.add(o);}else{Set e=new HashSet();for(int i=0;i<n;i++){char c=s.charAt(i);if(!e.contains(c)){p(f+c,s.substring(0,i)+s.substring(i+1,n));e.add(c);}}}}public static void main(String[]a){new F().r();}void r(){Scanner c=new Scanner(System.in);String t=c.nextLine();p("",t);for(int i=0;i<20;i++,b=p){p=new HashSet<>(b);for(B o:b)if(o.c==i)for(D d:D.values()){B n=d.b(o);if(n!=null&&!p.contains(n)){n.p(o,d);p.add(n);}}}B q=w.get(t);while(!q.v()){System.out.print(q.d);q=q.p;}System.out.println(q.g());c.close();}}
```
Ungolfed:
```
import java.util.*;
class F {
enum D {
R {
B b(B i) {
return i.z == 3 ? null : g(i, 1);
}
},
L {
B b(B i) {
return i.z == 0 ? null : g(i, -1);
}
},
D {
B b(B i) {
return i.y == 2 ? null : g(i, 4);
}
},
U {
B b(B i) {
return i.y == 0 ? null : g(i, -4);
}
};
abstract B b(B i);
B g(B i, int f) {
f += 4*i.y + i.z;
char[] s = i.s.toCharArray();
s[i.e] = s[f];
s[f] = '_';
return w.get(new String(s));
}
}
enum C {
_, G, B, R, Y;
}
class B {
C[][] a = new C[3][4];
String s;
int y,z,e,c;
B p;
D d;
B(String p) {
int i,j,q;
for(i = 0; i < 3; i++) {
for(j = 0; j < 4; j++) {
q=4*i+j;
a[i][j] = C.valueOf(p.substring(q,q+1));
if(a[i][j] == C._) {
y = i;
z = j;
e = q;
}
}
}
s = p;
}
boolean v() {
return Arrays.equals(a[0], a[2]);
}
void p(B b, D n) {
p = b;
d = n;
c = p.c + 1;
}
String g() {
String u = "\n";
for(int i = 0; i < 3; i++,u+="\n")for(int j = 0; j < 4; j++) u += a[i][j];
return u;
}
}
Set<B> b = new HashSet<B>(),p;
static Map<String, B> w = new HashMap<>();
void p(String f, String s) {
int n = s.length();
if (n == 0) {
B o = new B(f);
w.put(f, o);
if(o.v()) b.add(o);
}
else {
Set e = new HashSet();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if(!e.contains(c)) {
p(f + c, s.substring(0, i) + s.substring(i+1, n));
e.add(c);
}
}
}
}
public static void main(String[] a) {
new F().r();
}
void r() {
Scanner c = new Scanner(System.in);
String t = c.nextLine();
p("", t);
for(int i = 0; i < 20; i++, b=p) {
p = new HashSet<>(b);
for(B o : b)
if(o.c == i)
for(D d : D.values()) {
B n = d.b(o);
if(n != null && !p.contains(n)) {
n.p(o, d);
p.add(n);
}
}
}
B q = w.get(t);
while(!q.v()) {
System.out.print(q.d);
q = q.p;
}
System.out.println(q.g());
c.close();
}
}
```
] |
[Question]
[
Most of you have probably heard of the famous Turtle Graphics program, initially made popular by Logo. This challenge is to implement a Turtle Graphics program in your language of choice.
Rules:
1. The floor must be a diagonal with dimensions input by the user through std-in in the form `x/y`, representing the `x` and `y` length, respectively. `x` may not be more than 20 and `y` may not be more than 45,
2. When the pen is in the down state, it must draw in both the square (the x/y coordinate) the turtle leaves and the square the turtle enters. This is what would happen in real life, so that is what your program should do.
3. Initial position and direction of the turtle must be input by the user in the form `x,y,d`, where `x` and `y` are the positions on the x- and y-axis, respectively, and `d` is the direction, entered as `U`, `D`, `R`, or `L` (up, down, right, and left, respectively).
4. You must stop the turtle and display an error message if the turtle hits the wall. In other words, the turtle cannot walk through the wall.
5. The turtle must include these commands:
>
> RESET - Resets board to blank - turtle goes back to initial position and direction.
>
>
> DRAW and ERASE - These commands set the turtle to drawing and erasing, respectively.
>
>
> UP and DOWN - These two commands set the active tool (pen or eraser) position to up and down, respectively.
>
>
> DIRECTION x - This command turns the turtle to any direction North, Northeast, East, Southeast, South, Southwest, West, or Northwest, represented as the digits 1-8, with North (up) being 1, Northeast being 2...
>
>
> FORWARD xx - Advances turtle xx squares; FORWARD 15 advances the turtle 15 squares. If the turtle is facing N, E, S, of W, it will draw in `x` squares in that direction only. If the turtle is facing NE, NW, SE, or SW, it will draw in `x` squares in both directions; i.e. in FORWARD 1 while facing NE, it will draw this:
>
>
>
> ```
> X
> X
>
> ```
>
> DISPLAY - Displays board, using `X` for filled squares (x/y coordinates) and a blank space for empty squares.
>
>
> POSITION - Prints turtle's x/y coordinate on the board.
>
>
> SETPOS x y d - Sets the turtle to the x/y coordinate facing direction `d`, using the same notation as the DIRECTION command.
>
>
> STOP - Displays the board, and terminates the program after the user enters the character `~`.
>
>
>
Example commands:
>
> DIRECTION 2 FORWARD 1 DIRECTION 4 FORWARD 1:
>
>
>
> ```
> X
> X X
>
> ```
>
> DIRECTION 2 FORWARD 1 DIRECTION 4 FORWARD 4:
>
>
>
> ```
> X
> X X
> X
> X
>
> ```
>
> DIRECTION 3 FORWARD 5:
>
>
>
> ```
> XXXXX
>
> ```
>
>
This program will use standard [atomic-code-golf](/questions/tagged/atomic-code-golf "show questions tagged 'atomic-code-golf'") scoring rules to try to allow non-esoteric programming languages, such as Java and C++, to compete.
Version 1 is [here](https://codegolf.stackexchange.com/questions/18157/turtle-graphics-program). It did not require user input of board size and turtle start point, nor did it require diagonal movements.
[Answer]
### Python 3.3 (354?)
I noticed this as an unanswered question and decided to give it a go:
```
v=input().split('/')+input().split(',')+[input().split(' '),0,1,'X','U','D','L','R']
w,h,x,y,d,c,p,r,m,n,s,l,e=v
w,h,x,y=int(w),int(h),int(x),int(y)
g=[[' 'for x in range(int(h))]for y in range(int(w))]
while p<len(c):
i=c[p]
if r:
g[y][x]=m
if i=='RESET':
w,h,x,y,d,c,p,r,m,n,s,l,e=v
if i=='DRAW':
m='X'
if i=='ERASE':
m=' '
if i=='UP':
r=0
if i=='DOWN':
r=1
if i=='DIRECTION':
p+=1
i=int(c[p])
d=''
if i in[8,1,2]:
d+=n
if i in[4,5,6]:
d+=s
if i in[6,7,8]:
d+=l
if i in[2,3,4]:
d+=e
if i=='FORWARD':
p+=1
i=int(c[p])
for _ in range(i):
if d.find(n)+1:
y-=1
if d.find(s)+1:
y+=1
if d.find(l)+1:
x-=1
if d.find(e)+1:
x+=1
if r:
g[y][x]=m
if i=='DISPLAY':
for z in g:
print(''.join(z))
if i=='POSITION':
print(x,y)
if i=='SETPOS':
p+=3
x,y=c[p-2:p]
d=''
if i in[8,1,2]:
d+=n
if i in[4,5,6]:
d+=s
if i in[6,7,8]:
d+=w
if i in[2,3,4]:
d+=e
if i=='STOP':
while input()!='~':
pass
exit
if x>w or x<0 or y>h or y<0:
print('!')
exit
p+=1
```
>
> PS I am unsure about the scoring setup so my score may be incorrect!
>
>
>
] |
[Question]
[
An ionic compound is named like so: `(metal name) (non-metal suffixed with -ide)`. Here is a list of all the suffixes that need to be replaced with `-ide`:
```
-on -ogen -ygen -ine -orus -ur -ic -ium
```
The number of atoms of each element in the compound is not used in naming ionic compounds. Ignore the multivalent metal naming rules.
```
NaCl -> sodium + chlorine -> sodium chloride.
K2S -> potassium + sulphur -> potassium sulphide (or sulfide).
Yb2P3 -> ytterbium + phosphorus -> ytterbium phosphide.
PbTe2 -> lead + tellurium -> lead telluride.
```
A string containing an ionic compound (`NaCl`, `K2S`, `Yb2P3`) will be given as input. No polyatomic ions will be given. The program has to output the name of this compound.
Since nobody wants to compile the periodic table data themselves, [here](http://pastebin.com/kcR8ATLi) is a paste that has the names, symbols, and whether or not it is a metal of each element, in this order: `(name) (symbol) (is metal?)`. You can save this to an external file (the length of the file will not be counted), or you can store the data within your program (just discount the length of that string from there.) You may not need all the information provided. Every element is seperated by a newline.
As always with code golf challenges, shortest code wins.
[Answer]
## **Ruby, 114**
```
f,s=$*[0].split /\d*(?=[A-Z]|\Z)/
puts (n=Hash[*<<X.split-%w[0 1]].invert)[f]+" "+n[s].sub(/(i..|.gen|..)\Z/,"ide")
Hydrogen H 0
Helium He 0
Lithium Li 1
Beryllium Be 1
Boron B 0
Carbon C 0
Nitrogen N 0
Oxygen O 0
Fluorine F 0
Neon Ne 0
Sodium Na 1
Magnesium Mg 1
Aluminium Al 1
Silicon Si 0
Phosphorus P 0
Sulfur S 0
Chlorine Cl 0
Argon Ar 0
Potassium K 1
Calcium Ca 1
Scandium Sc 1
Titanium Ti 1
Vanadium V 1
Chromium Cr 1
Manganese Mn 1
Iron Fe 1
Cobalt Co 1
Nickel Ni 1
Copper Cu 1
Zinc Zn 1
Gallium Ga 1
Germanium Ge 1
Arsenic As 0
Selenium Se 0
Bromine Br 0
Krypton Kr 0
Rubidium Rb 1
X
```
Uses a paste of the element text that I haven't counted in the score. I remove the metal tag (since I'm assuming the compounds are always given with the metal first, so I don't actually need it) and build a dictionary with it. I identify the part to replace with "ide" by checking the end of the string for three letters starting with `i`, four letters ending with `gen`, or otherwise just the last two characters.
[Answer]
# Python, 134 Characters.
```
#T is a string containing the provided information on the elements
from re import*
print sub('(orus|[oy]ge|i?..)$','ide',' '.join(split(r'(\w+) %s '%e,T)[1]for e in findall('[A-Z][a-z]?',raw_input())))
T = """Hydrogen H 0
Helium He 0
Lithium Li 1
Beryllium Be 1
Boron B 0
Carbon C 0
Nitrogen N 0
Oxygen O 0
Fluorine F 0
Neon Ne 0
Sodium Na 1
Magnesium Mg 1
Aluminium Al 1
Silicon Si 0
Phosphorus P 0
Sulfur S 0
Chlorine Cl 0
Argon Ar 0
Potassium K 1
Calcium Ca 1
Scandium Sc 1
Titanium Ti 1
Vanadium V 1
Chromium Cr 1
Manganese Mn 1
Iron Fe 1
Cobalt Co 1
Nickel Ni 1
Copper Cu 1
Zinc Zn 1
Gallium Ga 1
Germanium Ge 1
Arsenic As 0
Selenium Se 0
Bromine Br 0
Krypton Kr 0
Rubidium Rb 1
Strontium Sr 1
Yttrium Y 1
Zirconium Zr 1
Niobium Nb 1
Molybdenum Mo 1
Technetium Tc 1
Ruthenium Ru 1
Rhodium Rh 1
Palladium Pd 1
Silver Ag 1
Cadmium Cd 1
Indium In 1
Tin Sn 1
Antimony Sb 1
Tellurium Te 0
Iodine I 0
Xenon Xe 0
Cesium Cs 1
Barium Ba 1
Lanthanum La 1
Cerium Ce 1
Praseodymium Pr 1
Neodymium Nd 1
Promethium Pm 1
Samarium Sm 1
Europium Eu 1
Gadolinium Gd 1
Terbium Tb 1
Dysprosium Dy 1
Holmium Ho 1
Erbium Er 1
Thulium Tm 1
Ytterbium Yb 1
Lutetium Lu 1
Hafnium Hf 1
Tantalum Ta 1
Tungsten W 1
Rhenium Re 1
Osmium Os 1
Iridium Ir 1
Platinum Pt 1
Gold Au 1
Mercury Hg 1
Thallium Tl 1
Lead Pb 1
Bismuth Bi 1
Polonium Po 1
Astatine At 0
Radon Rn 0
Francium Fr 1
Radium Ra 1
Actinium Ac 1
Thorium Th 1
Protactinium Pa 1
Uranium U 1
Neptunium Np 1
Plutonium Pu 1
Americium Am 1
Curium Cm 1
Berkelium Bk 1
Californium Cf 1
Einsteinium Es 1
Fermium Fm 1
Mendelevium Md 1
Nobelium No 1
Lawrencium Lr 1
Rutherfordium Rf 1
Dubnium Db 1
Seaborgium Sg 1
Bohrium Bh 1
Hassium Hs 1
Meitnerium Mt 1
Darmstadtium Ds 1
Roentgenium Rg 1
Copernicium Cp 1
Ununtrium Uut 0
Flerovium Fl 0
Ununpentium Uup 0
Livermorium Lv 0
Ununseptium Uus 0
Ununoctium Uuo 0"""
```
[Answer]
## APL ~~142~~ 150
If I am allowed to store the element names and symbols in a pair of nested arrays within the APL workspace then the following code should do it:
```
(e[s⍳c[1]]),((∊¯1×((+/¨⍳¨i)=+/¨(¯1×i)↑¨t⍳¨⊂n)/i←⍴¨t←'ic' 'on' 'ur' 'ine' 'ium' 'ogen' 'ygen' 'orus')↓n←∊e[s⍳(c←(98>⎕av⍳c)⎕penclose c←⍞~⍕⍳9)[2]]),'ide'
```
It works roughly as follows:
```
c←(98>⎕av⍳c)⎕penclose c←⍞~⍕⍳9
```
Takes the input from the screen via ⍞ and splits the chemical name into symbols and discards any numbers
e[s⍳c[1]]
Looks up the first element name from its symbol. Similarly for c[2]
```
(∊¯1×((+/¨⍳¨i)=+/¨(¯1×i)↑¨t⍳¨⊂n)/i←⍴¨t←'ic' 'on' 'ur' 'ine' 'ium' 'ogen' 'ygen' 'orus')↓n
```
Identifies which of the eight possible endings the non-metal has and drops it and then replaces it with ide via:
```
,'ide'
```
There is no error trapping so only works for valid compounds dictated via the one or zero identifier in the list of elements provided.
[Answer]
# Mathematica 252 267 254
**Code**
`ElementData[]` contains information about the elements; it is native to Mathematica.
```
d=ElementData; a=Reverse@SortBy[d[#,"Abbreviation"]&/@d[],StringLength[#]&];
g[e_]:=Row[{e," \[RightArrow] ", p=Row[z=(d[#,"StandardName"] &/@StringCases[e,a]),
" + " ] , " \[RightArrow] ",p[[1,1]]<> " "<>StringReplace[p[[1,2]],
f__~~z:"on"|"ogen"|"ygen"|"ine"|"orus"|"ur"|"ic"|"ium":> f~~"ide"] }]
```
---
**Examples**
```
g["NaCl"]
g["K2S"]
g["Yb2P3"]
g["PbTe2"]
```

---
**Explanation**
The code removes digits from the compound, then separates the elements by their abbreviated names. It then converts the abbreviations to the standard names of elements. Finally, it replaces the non-metal by the term with the correct suffix.
] |
[Question]
[
Your [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to find all occurences of a word in the 3d matrix. There is no restriction on I/O format. In the samples below, the word is presented, then a blank line, then the 2-dimensional layers from top to bottom, and the output, for each line, consists of a coordinate and a direction (x, then y, then z, where + is positive direction, - is negative direction, and 0 is no change). However, you may choose any other format, for instance a 3D Array, list of list of lists, pre-existing values on tape/stack, etc. Similarly, you may output the coordinate after the direction, etc. However, the format must be bijectional (always output `1` is not a valid output format) and consistent.
Sample Input
```
CODEGOLF
N Y R Z O F K G Y G B V E T P M O J F K Y O O K O Z N Q F A R P M X E T N O I Y F H C U O F Z A G V A V O O F B B V K U O V L F
W Y L W U H H K Z M Z X D R K Q G D D A B I D F P Y G U I D L I J Y D O M D Q W F H B Q Q N B B T A C F J Q L K H R Y R Y B Z Q
L F C D Z B Z W L E A J O F F J Z O X Q G A R C W N N W Y Z S U S G E V T A C F K F E O R O N V K D G Z N W O P L I W W J L C U
K L Z Q M A G C M R Q E F M O I O K T K T U A U S E X A Y K C D N J D V G E S G X O F P T S F I H Z B X E X U T X R Q G V P Q O
B H F C J P Y A P I Z G R X N A A W Z H A Z H V Q X T E T B Z A Q A V I Z H G D E H N J L G G W V K A O Q U S G N K M M X R G Z
B Q K R Y O R I O J C Q K C P F F U D R M U J G E K B F A A C I K G P O B M N E M P M B K X X T V B V N Z O R P K N Q N J B M D
M L R C O U C F A O H U H R E P M L E T B F R Y W J S U C Y A N M X S W E C C X C U F U V Q U H J C Z W Y E J S Z D C U I R F Z
C H D I M M C W F W G N I I Z U C X W Q M C O N Y O W K X E Z J U G Y U W Q V V C N B T A T E Z W C X Z E O W Z N S C J P V X X
```
Sample Output
```
0 0 7 ++-
```
Sample Input
```
AA
A A
A A
```
Sample Output
```
0 0 0 +00
0 0 0 0+0
0 0 0 ++0
1 0 0 -00
1 0 0 0+0
1 0 0 -+0
0 1 0 +00
0 1 0 0-0
0 1 0 +-0
1 1 0 -00
1 1 0 0-0
1 1 0 --0
```
Sample Input
```
SNY
Y X N X S X
```
Sample Output
```
0 0 0 00+
```
Sample Input
```
SNY
Y N S
```
Sample Output
```
0 0 0 00+
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œẹⱮŒp_ƝỊjEƊẠƊƇQƑƇ
```
A dyadic Link that accepts a multidimensional\* array of characters (the Board) on the left, and a list of characters (the Word) on the right and yields a list of lists of 1-indexed coordinates.
\* Of any dimension!
**[Try it online!](https://tio.run/##PZO5bttQEEV7fsUU@RHuoiiSohZuTao0hou06Qw3BtTFaVLEQIAUaYwACVLEdhlY/yH9iHLmSggI8j3ed2fmzvKu3l1ffzidXj8dnp@OP3@83r9/u384vOyu0v3u8Px1v9vftfuP@7vT4eU3pKdvx9vH480XMzvePBz@/MreOHD7@Pf76/3h6fPpVNtoK5usscxKyyGOfCPrLLWNLa0CaWyu05Fdw@rIZLW1oCHWS5DKBlnUnBUwjbOZxbaV5wme4bdj7eQlI4YpTilOZwvLgh7LhfUgMx6PNOF5wndCnJKI7iXhCbEtWDOQpTRv9b/ga@gd2TfYJtj0FzUR@xaFkWJv8BGDz8EWijUjxqg3ImYboAhGwt7/3cuCHEMsXL9bmio34CFXJWKQngi1eSaTrVFlfHPsuv8RjWgZSINFA7cTksCaZNmoop5JzzNnRx2DkhVV5BTCjFXzFf8pvipV3dSdjd4trHPsFH0hakrlYkSYs3bStFbHB@WzxGrNWqgSnvMg2y24c1bKsoPXWhNEcLw6c1U/VBcKrHJ4AzEcCVE/wQv19Sxbzjaak@gyE60mohAjl76UXa2scx6vus9IiMYWLWfFNUilmVt51QLvbKnOeU2Ly8zGQmOUZZqAraaoYp3LS8pppBn2vhTqQg67Aa2IkarGfgciTgZpdzU@tbU6f579UnfBNbtdElRo91loiHTut6ufaapXeD3fl8WlDpl0mzq9loXXs77cqTV4ChazN90nz6NTLWaa9FizOcJye5/IRLwCv9y8IIaX8Of1ii93oSfPGszrvpXfAawVo1Fsr2SvrFM4PulbbEa@zuvUzVh3yad6I5bn4J4mzXYvpEbTeUo6r@CpSdJ/ "Jelly – Try It Online")** ("CODEGOLF" will take too long, and "ODE" is there twice, so I used the latter instead.)
### How?
```
œẹⱮŒp_ƝỊjEƊẠƊƇQƑƇ - Main Link: multidimensional array, Board; list, Word
Ɱ - map across {C in Word} with:
œẹ - get all coordinates of {C} in {Board}
Œp - Cartesian product
-> all possible coordinate lists spelling {Word}
Ƈ - keep if:
Ɗ - last three links as a monad - f(Coordinates):
Ɲ - for neighbouring pairs:
_ - subtract
Ɗ - last three links as a monad - f(Deltas=that):
Ị - {Deltas} insignificant? (vectorises) -> is 0 or 1?
E - {Deltas} all equal?
j - {is 0 or 1(Deltas)} join {all Deltas are equal}
Ạ - all?
QƑƇ - keep if all distinct -> remove any with repeated coordinates
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 88 bytes
```
UMη⊞O⁺ιψ ⊞η FLηFL§ηιFL§§ηικF³F³F³¿∨⊖μ∨⊖ν⊖ξ¿⬤θ⁼π§§§η⁺ι×ρ⊖μ⁺κ×ρ⊖ν⁺λ×ρ⊖ξ⟦⪫⟦ικλ⭆⟦μνξ⟧§-0+π⟧
```
[Try it online!](https://tio.run/##dVJNb9s4FLznVwi5WEJVYIEec6IokpIokiIlih@GD0biNkZtOXWcIv31XpHK7qZd5KTh07yZ4eO7f9ye70/bw/XKtk/wdDxup4f0MU@6l@dH8bQ7by@nc9odXp7TfZ78yvLkNrnNsrub8D/wwvHu5uvpnKTtbvp2mYtZlrw/g0s9PexeA3mfffDvN06efP@X9@X/3/3XJBXntNzdn3fH3XTZPaTHueeP0jSX3p9fs6AZesHhkP7IE/TjZXt4Tp/y5M8Q78L8c/Fhf9w9p@ffJY9B8o3z/QPO9I5z@IATo4V03Xk/XdJ1c9pP6Xp2nUXnnv4yl7/Nr5Ouj3ky5cnr5r/Mt5//@nSbJ09ZtlneYpPdXa/rFRQlIqLFqzxZ36xX3CkvMCXzceVIMaKhYwGLBlMnBI3Yc4mB6gJmFg1c1C5gXEEtsAcBkxGMQuAi4GKkWoyzxSafHYxrja6qqOSZt6WiMnaUJSjqMgRZdY7oumzrgBtXClZKszgUUvIiqg4A4ka2UadSTrnCy8WhxbD0hY8dLQKNwLiJbsJKAhQM2HBunO91wD1BY1ALmGIklOBjxCXx3Ih4z7Y2pmmhXhxo6yUDJCoxJRFmImYVdKCDBosqssBRWAbMm3IkqI9TtQJ3Q48jv/KFRVYPsa4kGTspFoeiwrDpXJxlV3uiLI8YGF8BX8V80g5oKJZ5SzDWviLRDVW8aQmJ9x8pEFIvzpwyZhXxbw6SKifUkruBksIuTgDrUjHdxA5ECwwAjBxKOlEwjuKdO1ZQa2PusRi5F8s2UC55U7BycWCtgkIvcwWi0pVCy860c2ys4s6YptfQAb7sUm8QhDZgqLEepa7iBkBvHGr6@IYl1LXCb3eAVVkzBpfdMITXtY@zh9ZIBkVUdcJQi3zcAE2cNnKM04O8GMCAfEwBrUfCRMz7efCjtavNZnP9/PPwNw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UMη⊞O⁺ιψ ⊞η
```
Add padding bytes in each dimension. (If I was using the newer version of Charcoal on ATO then I would use `ψ` consistently but unfortunately the version of Charcoal on TIO has what I would call a bug when indexing an array containing `ψ` so I use spaces instead.)
```
FLηFL§ηιFL§§ηικ
```
Loop through every possible starting position (including the padding, but that will get filtered out later anyway).
```
F³F³F³¿∨⊖μ∨⊖ν⊖ξ
```
Loop through every possible direction except no direction (fixes the `AA` test case).
```
¿⬤θ⁼π§§§η⁺ι×ρ⊖μ⁺κ×ρ⊖ν⁺λ×ρ⊖ξ
```
If each character of the array starting at that position and working in that direction equals the target string, then...
```
⟦⪫⟦ικλ⭆⟦μνξ⟧§-0+π⟧
```
... output the position and direction in a readable form.
[Answer]
# Python3, 345 bytes
```
from itertools import*
D=[0,1,-1]
E=enumerate
def f(w,b):
d={}
for z,Z in E(b):
for x,X in E(Z):
for y,v in E(X):d[v]=d.get(v,[])+[(x,y,z)]
q=[(w[1:],*i,*j,[i])for i in d[w[0]]for j in product(*[D,D,D])if any(j)]
while q:
w,x,y,z,X,Y,Z,p=q.pop(0)
if''==w:yield p;continue
if(T:=(x+X,y+Y,z+Z))in d[w[0]]:q+=[(w[1:],*T,X,Y,Z,p+[T])]
```
[Try it online!](https://tio.run/##hVXbcqNGEH0OX9HlF4E0cVn2PqSU0gNC9wsIXRCXUKm1hbK4bIERtixv7bc7pxutdzcvESUYzpzuPt3TM@Sn8ku2v/kjL97fd0X2SGmZFGWWPRwofcyzoqxr3XZ0pZrq92as9drJ/vkxKT6XibZNdrTTj@rWaGm0bX/9ptEuK@hNhZTuqacLLtCr8isoFEiwk3qpMN9obaOXuL29/Ccp9RcVxUYj0l/VSb0ZsUZP7Ug/Rs1WrOqpqt@rKI0Ntk/Zehsdo6s45vd7fs@LbPt8V@r1qKtwxUa6o8/7k37Pno5f0oeEnljBUYl/5atAhSpvP13mWa5fGZhKd7Vau31sndLkYUv5n3fZvkz3z4lM6atWW39t@OrUCNRbIzSMHyJaT40fUlffXTeiVWzE71UpqUi0Q5PadHFxoZlk8p9I47fD9Rm2KaAFheRQnyY0QLUC3DvkUY9WNKcZEIfGMhtg5ODJSEg2uUBNWM@BzMgXCxtzIzAJc0OyaC2eQw4Mvx6ennjpIwZJnIlwPJoCw0/bwHpKG6BDXBwthPcQ/ruINUFU9tTFZcJ@hCfbzUX3Wt6nuBM0Bxg7sO3CZnNW1MHYhcqOxF/BhwV8DGwqsYaIEci/g5iuKGJlFryEgrGnKXI1YcV5sDVJBX3wB1IRC8gGUWzibEJaQhnhPoCd9xGVELEPxIGFA64nSBesUCwdqSxns8E1xsgSP6RNMGZ1M3gaSLQZfLjw1cfIkfx5pVbyX4NVxe9BowlFE8mHEGWMpye6lrL6vuQ0h9USz5FUhPP2xXYNnDkLydQDzwWfFXXA4yqNZSVMWZERLAfg@ojDiIksQvBMuXO2LuZW0jedc4@40iEjYQxEYw8jW7If4OLqc8@YiOtCT6XaBjKTHlxI9SpFLtCFdO3iXJExFLqS/Vzq34cH7qoZnmPx1MNsR/qa12gkKzIA2wE6Q5ye1Jr3RQczvuhnRdzJtnRBtR8msj9YN9t1tRn0c184iFStPWcwlC5fwGu1h6bnWvRFN8mqL8WCa2qf99kSeA@YhTFJT3AentRjKJ1vSZ8GYLE9d2dXeCP47Z/rY4HbBcJ1s877Y4NcbWBc/7X49oG5wnAkPldzI5n3wOHOX8MmwJ15nqyqJfuLu3wlLM6DPYXS6xtBbOiqusWTKtL3g@nmfDAFDNp8W5JfTX36mGIpSwH5q1Bmf99lWbE96Acc@L8VSflc7KPo9vKQP6SlbsgH4JYP7PuYPg7vtzTHwV0kZ1btr8PXa/WtptKKLwf@Ln3A50m3s32i6PDB3NcMA8espuVFui/1qL7Ta6ZZUz8JaTLj53nL6fYGzrT/C@v6v6ylHfxCuPk/wicmvP8L)
] |
[Question]
[
Normally, I'd open with some flavor text here about being bored and/or lazy but looking through the [stack-exchange-api](/questions/tagged/stack-exchange-api "show questions tagged 'stack-exchange-api'") questions that would be *far* from original. So instead I'm going to open with a meta and self-referential flavor text describing this lack of originality that then describes itself and how meta and self-referential it is.
# Challenge
Write a program that takes in the ID for some question on PPCG, and uses the SE API to grab the answers and select the winner.
You may assume that it is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, and the following answer format:
```
# Language, [<s>XXX</s>] YYY bytes
[Thanks to @user1 for saving XX bytes!]
[Thanks to @user2 for saving YY bytes!]
print "badly formatted but easier to tally like this"
```
To clarify:
* It might have 1 or more attributions or crossed out past scores, and it might not.
* The attributions and crossed-out scores are not necessarily correlated; one can appear without the other.
* If there are no attributions, then the code will start 2 newlines after the heading.
Anyway, you can either extract the length in the beginning or count the length of the code at the end. For the former, only use the last score. For the latter, don't count the attributions. You can assume that the two will match up.
Your program should spit out the ID for the answer with the fewest bytes. Your program should also do this in the fewest bytes possible, as the shortest answer in bytes will win.
*Note: yes, I have seen [Write code to determine the accepted answer](https://codegolf.stackexchange.com/q/20644/62402), but that challenge has submissions voting on the winner whereas this is code golf with a specific task and an explicit winner independent of other answers.*
[Answer]
# JavaScript, 283 bytes
```
n=>fetch(`https://api.stackexchange.com/2.2/questions/${n}/answers?site=codegolf&filter=!*SU8CGYZitCB.D*(BDVIficKj7nFMLLDij64nVID)N9aK3GmR9kT4IzT*5iO_1y3iZ)6W.G*`).then(r=>r.json()).then(s=>alert(s.items.sort((a,b)=>(g=s=>s.match(/\d+(?= bytes)/)[0])(a.body)-g(b.body))[0].answer_id))
```
Run on a subdomain of `stackexchange.com`.
] |
[Question]
[
# Counting Gems
## Background
My jewel box just fell down! There're too many gems of different shape on the ground. And your task is to count number of a certain type of gem.
## I/O
* Your code should take two inputs `S` and `G`, which could be a string with newlines, an array of lines, a two-dimensional array of characters, a textfile or in any reasonable format (if so, please state it clearly).
* These two strings will only contain `!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~` (from `0x21` to `0x7E` in ASCII table), space and newlines (binary form depending on your platform).
* In each string, lines are in same length.
* `S` is the gem we want to count. There're two circumstances.
1. Enclosed and doesn't contain any nested enclosed area. (in example 1/2)
2. Doesn't contain any enclosed area. (in example 3/4)
* Surrounding spaces are not regarded as a part of the gem.
* `G` is the shape of gems on the ground.
* It is acceptable that your code requires extra input to specify the dimension(s) of `S` and `G`
* It is acceptable that your code take ASCII values as inputs, instead of characters themselves. But you should **not** substitute characters with simpler integers (0,1,2,3). Your program should be able to process characters, or ASCII values.
## Example 1 (Character as input)
Input `S`:
```
+-+
| +-+
| | |
| | |
| +-+
+-+
```
Input `G`:
```
+-+ +-+
| +-+ +-+ |
| | | | | |
| | | | | |
| +-+ +-+ |
+-+ +-+
+-+
+---+ | +-+
| | | | |
| | | | |
| | | +-++
| | +-+| +-+
+---+ | | |
| | |
+-+ | +-+
| +-+ +-+
| |-|
| |-|
| +-+
+-+
```
Ouptut:
```
2
```
## Example 2 (ASCII value as input)
Input `S`:
```
32 32 32 32 32 32 32 32
32 32 32 32 99 32 99 32
32 32 32 99 32 99 32 99
32 32 32 99 32 32 32 99
32 32 32 99 32 32 32 99
32 32 32 99 32 32 32 99
32 32 32 32 99 32 99 32
32 32 32 32 32 99 32 32
32 32 32 32 32 32 32 32
```
Input `G`:
```
32 99 32 99 32 99 32 99 32 32 99 32
99 32 99 32 99 32 99 32 99 99 32 99
99 32 32 32 99 32 32 32 99 32 32 99
99 99 32 32 99 32 32 32 99 32 32 99
99 32 32 32 99 32 32 32 99 32 32 99
32 99 32 99 32 99 32 99 99 32 99 32
32 32 99 32 32 32 99 32 32 99 32 32
```
Output:
```
1
```
Visualized `S` (32 replaced with --):
```
-- -- -- -- -- -- -- --
-- -- -- -- 99 -- 99 --
-- -- -- 99 -- 99 -- 99
-- -- -- 99 -- -- -- 99
-- -- -- 99 -- -- -- 99
-- -- -- 99 -- -- -- 99
-- -- -- -- 99 -- 99 --
-- -- -- -- -- 99 -- --
-- -- -- -- -- -- -- --
```
Visualized `G`:
```
-- 99 -- 99 -- 99 -- 99 -- -- 99 --
99 -- 99 -- 99 -- 99 -- 99 99 -- 99
99 -- -- -- 99 -- -- -- 99 -- -- 99
99 99 -- -- 99 -- -- -- 99 -- -- 99
99 -- -- -- 99 -- -- -- 99 -- -- 99
-- 99 -- 99 -- 99 -- 99 99 -- 99 --
-- -- 99 -- -- -- 99 -- -- 99 -- --
```
## Example 3 (Not enclosed)
Thanks to @Draco18s
Input `S`
```
AB
```
Input `G`
```
AAB BA CAB
```
Output
```
2
```
## Example 4 (Not enclosed 2D)
Input `S`
```
ABCD
GE
F
```
Input `G`
```
ABCD
BGGED
CDEFE
F
```
Output
```
1
```
## Remarks
* Only two gems of exact one shape are considered the same.
* Same shape in different directions are not considered the same.
* However, as is described in example I/O, overlapping is possible. Under such circumstances, only complete ones are counted.
* `+`, `-` and `|` in the example have no special meanings. They do not indicate any corner or edge of the shape.
* You may assume input is always valid.
* **You may assume two target gems never share an exactly same edge.**
* Standard loopholes are forbidden.
* This is a code-golf, so shortest code wins!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 303 ~~305~~ ~~326~~ bytes
All optimizations need to be turned off and only work on 32-bit GCC.
```
#define r(z,k)for(z=0;z<k;z++)
#define c s[i][j]
x,y,o,p,t,i,j;char**s;h(i,j){!((i<0)+(j<0)+i/x+j/y+c-32)?h(i+1,j),h(i-1,j),h(i,j+1),h(i,j-1),c=0:0;}f(w,e,u,v,a,g)char**a,**g;x=w,y=e,s=a;r(o,x)h(o,0),h(o,y-1);r(p,y)h(0,p),h(x-1,p);w=0;r(o,u-x+1)r(p,v-y+1){t=1;r(i,x)r(j,y)t*=!(c*(c-g[i+o][j+p]));w+=t;}}
```
The code uses floodfill to replace surrounding spaces with `\0` and looks for matches while ignoring `\0`.
ungolfed and macros calculated (some letters are different from the golfed version, but logic stays the same):
```
int x, y, o, p, c, d, t;
char **s, **g;
h(int i, int j) { // Floodfill function
if(i<0 || j<0) return; // Boundary detection
if(i>=x || j>=y) return;
if(s[i][j] != ' ') return; // Character detection
s[i][j] = 0; // Replace it with \0
h(i+1, j);
h(i-1, j)
h(i , j+1);
h(i , j-1);
}
f(
int w, //1st dimension of S
int e, //2nd dimension of S
int u, //1st dimension of G
int v //2nd dimension of G
char** i, //Input S
char** j, //Input G
);
{
x=w,y=e,s=i,g=j;
for(o=0; o<x; o++) // Replace all surrounding spaces using floodfill
{
h(o, 0);
h(o, y-1);
}
for(p=0; p<y; p++)
{
h(0, p);
h(x-1, p);
}
w = 0;
for(o=0; o<=u-x; o++) // Main O(w*e*u*v) matching process
for(p=0; p<=v-y; p++) {
t=1;
for(c=0; c<x; c++)
for(d=0; d<y; d++)
if(s[c][d]*(s[c][d]-g[c+o][d+p]))
t=0;
w+=t;
}
}
```
] |
[Question]
[
The original "Blue Eyes" puzzle is given [here](http://www.xkcd.com/blue_eyes.html) (and below).
>
> A group of people with assorted eye colors live on an island. They are
> all perfect logicians -- if a conclusion can be logically deduced,
> they will do it instantly. No one knows the color of their eyes. Every
> night at midnight, a ferry stops at the island. Any islanders who have
> figured out the color of their own eyes then leave the island, and the
> rest stay. Everyone can see everyone else at all times and keeps a
> count of the number of people they see with each eye color (excluding
> themselves), but they cannot otherwise communicate. Everyone on the
> island knows all the rules in this paragraph.
>
>
> On this island there are 100 blue-eyed people, 100 brown-eyed people,
> and the Guru (she happens to have green eyes). So any given blue-eyed
> person can see 100 people with brown eyes and 99 people with blue eyes
> (and one with green), but that does not tell him his own eye color; as
> far as he knows the totals could be 101 brown and 99 blue. Or 100
> brown, 99 blue, and he could have red eyes.
>
>
> The Guru is allowed to speak once (let's say at noon), on one day in
> all their endless years on the island. Standing before the islanders,
> she says the following:
>
>
> "I can see someone who has blue eyes."
>
>
> Who leaves the island, and on what night?
>
>
>
The [answer](https://xkcd.com/solution.html) is that they all leave on the hundredth day. This is due to the following logic:
>
> If there is one blue-eyed person only, he will leave on day 1. If
> there are two-blue-eyed people only, nobody leaves on day 1. Following
> this, they both leave on day 2. Now if there are 3 blue-eyed people,
> nobody leaves on day 1. Nobody leaves on day 2 either. Now everyone
> knows that there are 3 blue-eyed people, because if there were only
> one, he would have left on day 1 and if there are two, they both would
> have left on day 2. Hence all 3 leave on day 3.
>
>
> We can now write an inductive proof that if n blue-eyed people require
> n days to figure out their eye colours and leave, then n+1 blue-eyed
> people require n+1 days to do the same.
>
>
>
However, the code you write should be capable of solving not just the original puzzle, but also some variants that require slightly different inductive steps.
You will be told how many of the islanders have blue eyes and how many don't. You will also be given a statement by the oracle (a system of equations/inequations) that everyone on the island hears. You need to determine when the island will be free of the blue-eyed people.
The oracle's statements will use `b` for the number of blue-eyed people and `r` for the number of non-blue-eyed people. The equations can include `< > <= >= = + -` and any whole numbers.
## Test cases
Based on [this](https://puzzling.stackexchange.com/questions/12626/variants-to-blue-eyes-puzzle/12630#12630) set of variants
```
50 50
b>=1
b<b+r
```
Output: `50`
The second equation gives no new information, hence this problem becomes exactly the same as the original puzzle.
```
100 50
b+3>=r+4
```
Output: `25`
```
100 0
b-2>8+1-1
```
Output: `90`
```
50 50
b>=10
b<=75
```
Output: `41`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ 48 bytes
```
f=lambda b,r,c:all(map(eval,c))and-~f(b-1,r+1,c)
```
[Try it online!](https://tio.run/##XYxBCsIwEEX3nqK7JGQCmWpRxPQi4mKmNSikMYQiuPHqMRQKRfir/x4vfebHK7aleBdo4pEahgzDmUKQEyV5f1OAQSmKo/l6yQYha6xPSfkZ58bLzkLdVXDvUIDgC@ssbmq3crSroPe9y/rwDxdm2v6k0eAWbst2SbtjV4XyAw "Python 2 – Try It Online")
# How it works
By induction:
* If the island composition is (*b*, *r*) and it is known that (*b* − 1, *r* + 1) is not possible, then on day 1, the blue-eyed islanders, seeing (*b* − 1, *r*), will conclude that they are blue-eyed and leave.
* If the island composition is (*b*, *r*) and it is known that the blue-eyed islanders would have left on day *n* if the composition were (*b* − 1, *r* + 1), then on day *n* + 1, the blue-eyed islanders, seeing (*b* − 1, *r*), will conclude that they are blue-eyed and leave.
This second inference fails if *b* = 1, but in that case, the blue-eyed islander would never leave if they hadn’t already, and the test case would be invalid.
Note that non-blue-eyed islanders will never leave, in this version of the puzzle, because even if they use similar logic to conclude that they are not blue-eyed, they still don’t know which non-blue color their eyes are.
] |
[Question]
[
Valve's KV file format is as follows (in pseudo-EBNF):
```
<pair> ::= <text> <value>
<value> ::= <text> | <block>
<text> ::= "\"" <char>* "\""
<block> ::= "{" <pair>* "}"
```
The parsing starts on `<pair>` state. Whitespace is allowed anywhere, but is only required between two consecutive `<text>` tokens (`"a""b"` is invalid, but `"a" "b"` is valid, and so is `"a"{}`).
And since I'm lazy, `<char>` is any character, except `"`, unless preceded by `\`.
You can also see KV as JSON without commas and colons, and with only strings and objects as possible types.
Your task is to write a program or function that converts a input string (stdin, file or argument) in KV to a output string in JSON. You can output anywhere (stdout, file or return value), as long as it's a valid json string.
It isn't necessary to preserve whitespace in the output, as long as quoted text doesn't change.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, of course.
## Bonus
You get a **-20** byte bonus if the output is pretty-printed, regardless of input. Pretty printed means indenting each level of blocks with 4 spaces, separating colons from values by 1 space and have one pair per line. Closing braces should stand on their own line.
## Test cases
Input:
```
"foo" {
"bar" "baz"
"oof" {
"rab" "zab"
}
}
```
Output:
```
{
"foo": {
"bar": "baz",
"oof": {
"rab": "zab"
}
}
}
```
Input:
```
"obj" {
"emptyo" {}
"troll" "}{"
}
```
Output:
```
{
"obj": {
"emptyo": {},
"troll": "}{"
}
}
```
Input:
```
"newline" "
"
```
Output:
```
{
"newline": "\n"
}
```
Input:
```
"key
with_newline" {
"\"escaped\"quotes" "escaped_end\""
}
```
Output:
```
{
"key\nwith_newline": {
"\"escaped\"quotes": "escaped_end\""
}
}
```
[Answer]
# CJam, ~~57~~ 54 bytes
```
{[~]2/{`_'{#{1>W<"\u%04x"fe%s`}{~J}?}f%':f*',*{}s\*}:J
```
This is a named function that pops a VDF string from the stack and pushes a JSON string in return.
CJam has no JSON built-ins, so the bonus won't be worth it. Since conditionally escaping some characters would be a pain for the same reason, I decided to escape *everything*.
The result isn't pretty, but it's valid JSON. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%0A%20%20%7B%5B~%5D2%2F%7B%60_'%7B%23%7B1%3EW%3C%22%5Cu%2504x%22fe%25s%60%7D%7B~J%7D%3F%7Df%25'%3Af*'%2C*%7B%7Ds%5C*%7D%3AJ%0A~&input=%22test%22%20%7B%0A%22newline%22%20%22%0A%22%0A%22backslashes%22%20%22%5C%5C%22%0A%22quote%22%20%22%5C%22%22%0A%7D).
] |
[Question]
[
# Goal
Sometimes dinner menus can have long winded names. It's much easier for the waiter to write an abbreviation that unambiguously identifies the dish.
For example, given this list:
```
beef burger
chicken burger
chicken nuggets
```
The abbreviation `c n` matches `chicken nuggets`.
The abbreviation `bur` matches `beef burger` and `chicken burger`.
Write a program of function that identifies one or more items that match an abbreviation.
# Input
1. The abbreviated string to find.
2. A list of items to search.
You may change this order and use any suitable data types.
# Output
* If the abbreviation does not match any items: `Not found`
* If the abbreviation unambiguously matches an item: output the unabbreviated item.
* If the abbreviation ambiguously matches several items: output a comma separated list of words that would make the selection unambiguous, followed by a question mark. The order is not important. Extra spaces are permitted.
# Matching rules
Each word in the abbreviation and the items is considered separately. If an abbreviated word matches the start of an item word, the item is a potential match. If none of an item's words start with any if the abbreviated words, that item is not a match.
Abbreviated words can be in any order.
An abbreviated word cannot be used to match multiple item words and visa-versa.
Abbreviations only match the start of words.
Assume no item will contain all of the words of another item. For example, you will never have `beef burger` and `beef cheese burger`.
# Test Cases
Given this list:
```
beef burger
crispy chicken burger
grilled chicken burger
chicken nuggets
chocolate cone
strawberry cone
vanilla cone
```
These abbreviation give the specified output:
```
fish Not found
cones Not found
chicken cone Not found
nilla Not found
v vanilla cone
be beef burger
c n chicken nuggets
b b beef burger
c b c crispy chicken burger
c b crispy,grilled?
bu beef,crispy,grilled?
or beef,crispy chicken,grilled chicken?
ch crispy,grilled,nuggets,cone?
or crispy chicken,grilled chicken,nuggets,cone?
```
# Scoring
This is code golf. The shortest answer in bytes in 12 days wins acceptance. (I would have made it one week, but I won't be around for that.)
[Answer]
# Python 2 - 181 bytes
It turns the abbreviated string into a regex and attempts to match groups from the search list.
The ternary operation `if` and `else`s are 14 bytes. I've tried to cut it down into a list and then accessing one of the items based on the state of `r`, but don't have anything shorter that this yet.
```
import re
def s(a,l):
r=[m.group(1)for e in l for m in[re.compile('^('+a.replace(' ','\w+ ')+'\w+)$').search(e)]if m]
print','.join(r)+'?'if len(r)>1 else r[0]if r else'Not found'
```
Call with `s(str, list)`:
```
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar', 'cfoo nbar'])
>>> chicken nuggets,cfoo nbar?
```
] |
[Question]
[
Have you heard about trees?
When performing DFS on a binary tree, you can traverse it in 3 possible orders.
* Root, left node, right node (Pre-order)
* Left node, Root, right node (In-order)
* Left node, right node, root (Post-order)
Check [wikipedia](https://en.wikipedia.org/wiki/Tree_traversal) to know [more](http://i1216.photobucket.com/albums/dd373/ncanales0822/28853015.jpg).
For this challenge, you have to provide a program that, given **the pre and in order traverses** of a tree returns the **original tree**.
Example 1:
**Inputs**
Preorder:
```
[1 2 3 4 5 6 7]
```
In order:
```
[2 1 4 3 6 5 7]
```
Returns:
```
[1 [2 3 [4 5 [6 7]]]]
```
NOTES:
**Result notation**
```
[a [b c]]
```
Node `a` is the parent of nodes `b` and `c`. However in this one
```
[a [b [c]]]
```
Node `a` is the parent of node `b`, but it's `b` in this case the parent of `c`.
**More considerations**
* The tree might not be balanced.
* For every 2 traverses, the original tree is unique.
* Submissions can be programs and functions.
* The input format has to be a sequence of numbers representing the order in which the nodes are visited.
* The output format must be exactly as specified above.
* Shortest code in bytes wins.
Good luck
[Answer]
# Haskell, 114 bytes
```
[a]#_=show a
(a:b)#c|(d,_:e)<-span(/=a)c,(f,g)<-splitAt(length d)b=[a]#c++" ["++f#d++' ':g#e++"]"
a?b='[':a#b++"]"
```
Example run:
```
*Main> [1,2,3,4,5,6,7]?[2,1,4,3,6,5,7]
"[1 [2 3 [4 5 [6 7]]]]"
```
] |
[Question]
[
# aBOTcalypse
Design a bot to compete in a King-of-the-Hill challenge! [Here's a replay of a default bot game.](http://gfycat.com/AnnualBestBrontosaurus)
The board is 2D, like a side-scrolling video game (but without any scrolling).
A valid bot must accept a multiline string representation of the region of the board it can see, and output a move for the bot.
### Mechanics
This is a survival game. The apocalypse has come, and only bots (and an endless supply of rocks stored in [hammerspace](http://en.wikipedia.org/wiki/Hammerspace)) remain. Each bot is given a random starting location, at elevation 0. In a given move, a bot can rest, move, throw a rock, or drop a rock. Bots can share space with stationary rocks, but a bot that collides with another bot or a meteor is killed, as is a bot hit by a thrown rock.
* Gravity: bots and rocks must rest on top of the floor of the board or on top of another rock; resting on something else (air, a meteor, a bot, etc.) leaves one "unsupported". Unsupported bots or rocks will fall until they are supported; a fall of greater than one space will kill a bot, and a bot underneath a falling rock or bot is also killed. This means that trying to move or drop up will only work if the bot is currently sharing a space with a rock (otherwise the bot/rock will fall back down 1 space). A space can become "unsupported" if the rock beneath it falls **or is destroyed by a meteor or projectile**.
* Meteors: Each turn a meteor enters the board from the top. A meteor has a velocity of magnitude 2, with a random angle chosen uniformly in the range [-180,0], and a random starting x position. Meteors fall in a straight line along the given trajectory until they hit something, at which point they disappear. Note that rounding in a meteor's movement is towards 0 (as per python's `int()`).
* Projectiles: A bot can choose to throw a rock any distance up to its elevation. A thrown rock moves in a straight line until it hits something (all in one turn, unlike a meteor; thrown rocks don't appear on the board), at a slope of `- elevation / max distance`. **Note that thrown rocks begin their trajectory at x +- 1 square.** For example, if a bot is at an elevation of 5, and throws left a distance of 1, the rock will begin at `(x-1,5)` and end at `(x-2,0)`. Collision is only checked in steps of `dx=1`, and `dy` is rounded towards 0 (as per python's `int()`).
### Input
Each bot can see a square 20 pixels in each direction (Chebyshev distance = 20), up to the boundaries of the board. There are 8 different characters in each input string:
* `'#'` (board boundary)
* `'.'` (air)
* `'@`' (meteor)
* `'&'` (rock)
* `'e'`/`'s'` (an enemy bot, or itself)
* `'E'`/`'S'` (an enemy bot, or itself, sharing a space with a rock)
Here's an example input (line breaks will be `\n`):
```
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............................#
..............@...............#
.....................E........#
.....................&........#
.....................&........#
.....................&........#
.....................&........#
...........@.........&........#
....................s&........#
###############################
```
### Output
There are four actions that a bot can take each turn.
* `rest` (literally sit and do nothing)
* `move <direction>` moves the bot one space in any of the four directions, `up`, `down`, `left`, or `right`. Movement causes the bot to fall if the new space is not supported by the floor or a rock (`fall > 1 = bot.kill()`).
* `drop <direction>` places ("drops") a rock in the indicated direction. Dropping a rock up (i.e., placing a rock in the square `[bot_x, bot_y+1]`) or to the side causes it to fall until supported (possibly falling onto the bot during `drop up`). `drop down` places a rock in the same position as the bot, if there is not a rock there already.
* `throw <direction> <distance>` throws a rock as per the "projectiles" mechanics above, with the indicated max distance. Max distance is irrelevant for throwing upward or downward - the projectile collides with the square below (for `down`), or attempts to collide with the square above (for `up`) and then with the bot's square if it doesn't hit anything (killing the bot).
A bot in the contest must output a scalar string with its action upon receiving the input string.
### Interface
A bot must consist of a single program which can be called via a python 2 `subprocess`. Any commands should be indicated, and will be saved in a file called `command.txt`; before a game begins, the controller will execute each command in `command.txt`, in order, and then the final command will be used to pass input to the bot from then on.
A bot may have a single storage file called `storage.txt` in its folder; the "Default Thrower" bot shows an example implementation, using json to save its state during various turns. In addition, feel free to include debugging output in a write-only `errlog.txt`, which I'll pass along in case your bot fails during a run. I'll make sure to run several tests with each bot, to try and find any errors beforehand.
### Scoring
A bot's total score is equal to the number of turns it survives, accumulated over X games of maximum length Y. At the moment, `X,Y = 10, 500`; if bots are lasting a long time, I'll increase Y, and if they are lasting a short time, I'll increase X.
[Controller code is found in controller.py](https://github.com/sirpercival/aBOTcalypse); many thanks to @Nathan Merrill for his DDOS koth from which I adapted the Communicator code.
[Answer]
# Python 2, Edgebot
Edgebot wants to hide in a corner and build a tower. They'll run to one end, build up a bit, then start dropping rocks to build a wall. Edgebot does not like visitors, and will throw rocks at anyone who gets too close to their tower. If it all goes horribly wrong and edgebot crashes, it'll drop a rock on its own head
```
import sys
from random import randint
class edgebot():
def playtime(self,board):
try:
self.max_height = 5
board = board.splitlines()
#find edgebot
for y in xrange(0,len(board)):
row = board[y]
symbol = 's' if row.count('s') else 'S'
x = row.find(symbol)
if x >= 0:
self.height = 20 - y
break
ground = board[len(board)-2]
floor = board[len(board)-1]
nasty_person = 'e' if ground.count('e') else 'E'
bad_x = ground.find(nasty_person)
side = ground.find('#')
if abs(side - x) ==1:
self.end_found = 1
else:
self.end_found = 0
if side - x == -1:
self.direction = 'right'
else:
self.direction = 'left'
#Bad edgebot! No climbing out of the game!
if floor[x] != '#':
if board[self.height-1][x] == '&':
dist = randint(3,self.height)
return 'throw ' + self.direction + ' ' + `dist`
elif symbol =='S':
return 'drop up'
else:
return 'move down'
#Edgebot will go through you to find a corner. You have been warned.
elif abs(x - bad_x) <=2:
if x - bad_x >0:
return 'throw left 1'
else:
return 'throw right 1'
#edgebot wants to hide in a corner
elif self.end_found ==0:
if side == -1:
return 'move right'#edgebot is right-handed
elif side - x < -1:
return 'move left'
elif side - x > 1:
return 'move right'
#Too close! Throw rocks at it!
elif self.height+1>= abs(x-bad_x) and abs(x-bad_x) >=3:
distance = abs(x - bad_x) - 2
if distance < 1:
return 'throw ' + self.direction + ' 1'
else:
return 'throw ' + self.direction + ' ' +`distance - 1`
self.max_height += 2 #people came close, edgebot needs to be higher up!
#edgebot wants a home in the corner
elif self.height <self.max_height :
if symbol =='S':
return 'move up'
else:
return 'drop down'
#edgebot wants a wall. edgebot has, at best, a limited understanding of architecture
elif bad_x < 3 or self.height+1<abs(x-bad_x):
if self.direction == 'right' and row[x+1] == '&':
self.max_height += 2
return 'drop down'
elif self.direction == 'left' and row[x-1] == '&':
self.max_height += 2
return 'move down'
else:
return 'drop ' + self.direction
else:
return 'drop down' #Not sure? Hide under a rock!
except:
return 'drop up' #All gone horribly wrong? Squish.
print edgebot().playtime(sys.argv[1])
```
Sorry for all the edits, didn't run enough test cases before submitting. There's a small problem in that the little guy will try to climb off the top of the board given enough time, but hopefully that won't be an issue in most matches. Edgebot should now just throw rocks random distances once it's climbed high enough
Last edit for now. Edgebot will now throw rocks at anyone close enough between it and the wall. No sense it taking itself out by running through someone
] |
[Question]
[
This is the target language-relaxed version of [Generate a self-extractor application](https://codegolf.stackexchange.com/questions/17417/generate-a-self-extractor-application)
Create a program in *any* language, that takes an arbitrary binary input, and generates a valid program (also in *any* language), which when compiled and run (or interpreted) will print this binary input.
So you could do this:
```
$ cat file.dat | python program.py > gen.rb
$ ruby gen.rb > file.dat.new
$ diff file.dat file.dat.new
$ echo $?
0
```
The scoring depends on the byte count of the original code (**O**), and the square of the byte count of the generated codes for the following inputs:
* **A**: The whole lyrics of Never gonna give you up
* **B**: The uncompressed grayscale 32x32 BMP version of Lena Söderberg
* **C**: The original source code (the generator, **O**)
* **D**: The generated source code for the **A** input
Score is **O** + max(**A**, **O**)^2 + max(**B**, **O**)^2 + max(**C**, **O**)^2 + max(**D**, **O**)^2.
Score explained:
1. The values for the generated variants are squared to encourage optimizing the size of the generated code (and the size of the original code is reflected in **C** as well).
2. Also to encourage minimizing the length of the generator code (as opposed to the generated code), if the generated code is smaller than the generator, then the size of the generator will be used instead.
Lowest score wins.
Clarification of the rules:
* You can use the standard libraries of the chosen language(s), except for libraries that are designed (or can be used *directly*) for compression and/or decompression (like zlib, bz2, etc.). Using other kinds of libraries, like `base64` are fine, but they have to be part of the standard library of the chosen language(s).
* The generated code has to be able to print the original data without any external help, like network connections or pipes, etc. (e.g. if you move the `gen.exe` to another, isolated computer it should be able to generate the output there as well). You also have to assume that the generated code (if you are using an interpreted target language) will be run the following way: `$ langint script.scr > output` where `langint` is the interpreter of your chosen language.
* The code generator should also work for any other input (generates code that regenerates the original input), but compression performance for them is not measured in the score (this means that optimizing the generator only for the test inputs are okay). However if there is (or anyone finds) at least one input with a maximum size of 65535 for which the code generator does not work, then the score of the submission is *infinite*.
* The input files are supplied in base64 to make sure everyone will run the app on the same inputs. Please note that the lyrics have windows style line endings. Base64 decoding of the input is not part of the challenge, it can be done separately (eg the `file.dat` on the example is already the base64 decoded file).
File inputs *in base 64*:
**Never gonna give you up**
```
V2UncmUgbm8gc3RyYW5nZXJzIHRvIGxvdmUNCllvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8g
SQ0KQSBmdWxsIGNvbW1pdG1lbnQncyB3aGF0IEknbSB0aGlua2luZyBvZg0KWW91IHdvdWxkbid0
IGdldCB0aGlzIGZyb20gYW55IG90aGVyIGd1eQ0KSSBqdXN0IHdhbm5hIHRlbGwgeW91IGhvdyBJ
J20gZmVlbGluZw0KR290dGEgbWFrZSB5b3UgdW5kZXJzdGFuZA0KDQpOZXZlciBnb25uYSBnaXZl
IHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5k
IGFuZCBkZXNlcnQgeW91DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNh
eSBnb29kYnllDQpOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpXZSd2ZSBr
bm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nDQpZb3VyIGhlYXJ0J3MgYmVlbiBhY2hpbmcgYnV0
DQpZb3UncmUgdG9vIHNoeSB0byBzYXkgaXQNCkluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJl
ZW4gZ29pbmcgb24NCldlIGtub3cgdGhlIGdhbWUgYW5kIHdlJ3JlIGdvbm5hIHBsYXkgaXQNCkFu
ZCBpZiB5b3UgYXNrIG1lIGhvdyBJJ20gZmVlbGluZw0KRG9uJ3QgdGVsbCBtZSB5b3UncmUgdG9v
IGJsaW5kIHRvIHNlZQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0
IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91DQpOZXZlciBn
b25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZlciBnb25uYSB0
ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIg
Z29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91
DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZl
ciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQooT29oLCBnaXZlIHlvdSB1cCkNCihP
b2gsIGdpdmUgeW91IHVwKQ0KKE9vaCkNCk5ldmVyIGdvbm5hIGdpdmUsIG5ldmVyIGdvbm5hIGdp
dmUNCihHaXZlIHlvdSB1cCkNCihPb2gpDQpOZXZlciBnb25uYSBnaXZlLCBuZXZlciBnb25uYSBn
aXZlDQooR2l2ZSB5b3UgdXApDQoNCldlJ3ZlIGtub3cgZWFjaCBvdGhlciBmb3Igc28gbG9uZw0K
WW91ciBoZWFydCdzIGJlZW4gYWNoaW5nIGJ1dA0KWW91J3JlIHRvbyBzaHkgdG8gc2F5IGl0DQpJ
bnNpZGUgd2UgYm90aCBrbm93IHdoYXQncyBiZWVuIGdvaW5nIG9uDQpXZSBrbm93IHRoZSBnYW1l
IGFuZCB3ZSdyZSBnb25uYSBwbGF5IGl0DQoNCkkganVzdCB3YW5uYSB0ZWxsIHlvdSBob3cgSSdt
IGZlZWxpbmcNCkdvdHRhIG1ha2UgeW91IHVuZGVyc3RhbmQNCg0KTmV2ZXIgZ29ubmEgZ2l2ZSB5
b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBh
bmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBnb25uYSBzYXkg
Z29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0KTmV2ZXIgZ29u
bmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVu
IGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBn
b25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0K
TmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIg
Z29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5
DQpOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVy
dCB5b3U=
```
**Lena**
```
Qk02CAAAAAAAADYEAAAoAAAAIAAAACAAAAABAAgAAAAAAAAEAAB1CgAAdQoAAAABAAAAAAAAAAAA
AAEBAQACAgIAAwMDAAQEBAAFBQUABgYGAAcHBwAICAgACQkJAAoKCgALCwsADAwMAA0NDQAODg4A
Dw8PABAQEAAREREAEhISABMTEwAUFBQAFRUVABYWFgAXFxcAGBgYABkZGQAaGhoAGxsbABwcHAAd
HR0AHh4eAB8fHwAgICAAISEhACIiIgAjIyMAJCQkACUlJQAmJiYAJycnACgoKAApKSkAKioqACsr
KwAsLCwALS0tAC4uLgAvLy8AMDAwADExMQAyMjIAMzMzADQ0NAA1NTUANjY2ADc3NwA4ODgAOTk5
ADo6OgA7OzsAPDw8AD09PQA+Pj4APz8/AEBAQABBQUEAQkJCAENDQwBEREQARUVFAEZGRgBHR0cA
SEhIAElJSQBKSkoAS0tLAExMTABNTU0ATk5OAE9PTwBQUFAAUVFRAFJSUgBTU1MAVFRUAFVVVQBW
VlYAV1dXAFhYWABZWVkAWlpaAFtbWwBcXFwAXV1dAF5eXgBfX18AYGBgAGFhYQBiYmIAY2NjAGRk
ZABlZWUAZmZmAGdnZwBoaGgAaWlpAGpqagBra2sAbGxsAG1tbQBubm4Ab29vAHBwcABxcXEAcnJy
AHNzcwB0dHQAdXV1AHZ2dgB3d3cAeHh4AHl5eQB6enoAe3t7AHx8fAB9fX0Afn5+AH9/fwCAgIAA
gYGBAIKCggCDg4MAhISEAIWFhQCGhoYAh4eHAIiIiACJiYkAioqKAIuLiwCMjIwAjY2NAI6OjgCP
j48AkJCQAJGRkQCSkpIAk5OTAJSUlACVlZUAlpaWAJeXlwCYmJgAmZmZAJqamgCbm5sAnJycAJ2d
nQCenp4An5+fAKCgoAChoaEAoqKiAKOjowCkpKQApaWlAKampgCnp6cAqKioAKmpqQCqqqoAq6ur
AKysrACtra0Arq6uAK+vrwCwsLAAsbGxALKysgCzs7MAtLS0ALW1tQC2trYAt7e3ALi4uAC5ubkA
urq6ALu7uwC8vLwAvb29AL6+vgC/v78AwMDAAMHBwQDCwsIAw8PDAMTExADFxcUAxsbGAMfHxwDI
yMgAycnJAMrKygDLy8sAzMzMAM3NzQDOzs4Az8/PANDQ0ADR0dEA0tLSANPT0wDU1NQA1dXVANbW
1gDX19cA2NjYANnZ2QDa2toA29vbANzc3ADd3d0A3t7eAN/f3wDg4OAA4eHhAOLi4gDj4+MA5OTk
AOXl5QDm5uYA5+fnAOjo6ADp6ekA6urqAOvr6wDs7OwA7e3tAO7u7gDv7+8A8PDwAPHx8QDy8vIA
8/PzAPT09AD19fUA9vb2APf39wD4+PgA+fn5APr6+gD7+/sA/Pz8AP39/QD+/v4A////AEmnoKA4
OUVOT0tDSHCAhIiNkpOUnrDNtmJ3dWBUZFk/aJSbp0MwOkU9W0IpUGSCi4+QjJKiu9ieXliNaExV
ZUVZiZerTS45ND1jSyhDY2qNj4uNmazH2H9SS5i1WFZhTlB8l6tMMTk1QVtcOzRkaYSOiZKgt8/K
foCJj8eRWWBbXHaZqkcwRDM8a3RSOkxneYuMmKi/26B8lYeO2bNjZWJycpqsTi5CO0twc0ozPVVz
i5Cer8fcZG6WjIKt0nBhZn5TmqxaNUhNV3ZqPzU7RXKJjaLEzok/c5SEcXbQnktZOU+kpWI9QWBu
dU06MjU9ZIGUpJlbOk9whX1+e8bXi0UuY6qhXEk/aXJ4PTU0OkJjh5qmYShASW+dmZaFvdzWujZe
raRoVUNpYJV1MDZCYoOKfo2HPDhDaaGalYi02tXWQF6soWZdQlJgbJJRLkp6i4uIm6hlNEFjmZiT
i6rT0tVKV6igYV9MXV09U3xHRXyNmpeHqI09PmSGnJWOoczQ0klKpZ1lalRhQjdWWH5AeJWll3ur
oVU9YGahmJGRvszQT1GooF94WlNGPFw3e3tzobKjh7ejZERcSJqalYugxsheW6uhX29zWUlTWCo/
pI+IkZ+GsotURl81ip2Zlo2ftWBkqp1ZX3OTU0pMNi9rwGxMbYGyZz5GWy5woZqbmZCMY2uqm1hk
aoFyY0U5Nz2Rs4l2oMG5cUlRMVScop+ZlY5ka6qaWWVrdYZ/UjY3P0+bs6mvxtuHUUQ2OouhnJmZ
mWdtqZlVYWZwp317WD1FOkqYuKy+xmZwQjEvZp+ko6CcZ3OqllZhYX2zf36AZEQ7RVmku7i4doeP
QipGmaehnZtjdqyVVmJcmKl5f4SIdVhpUFCkxMPFpoiCPy58pZ+bml5yq5VXYl6YoHWCh46Ukpea
lp6yv8fPw590JlKcoJ2dYHCqlFhjYJOKan2Mk6Crrq61uLK2wsrQxbE2L3mjn5xhb6aQVmRli3hs
eYKYq7GyucG/yMemnr3W1U4pQ5WhnFlqpIxUYmh+e218goeluL3DycvZoo+BSKvQRjAuYZ6hV2yk
jFdjanZ5b3eFiIquw8nM1r1nlYczd5tZLTM0eKNpaKeLV2RpdXpzc3uIjqe8ydbJamSZgmKTko89
LTBCg5Rupo1VY2p0e313foaUr77GtH9ncJWNjJKPlI08LzE9pY+ijlplbXl+gIKCjZ6wsp18eXRy
jpeYk42S1nUpMy2ipaSMX2dsen6AgYKBgoWBfX+Ad3WTnp2bkLm7dVgwMZ2hp41haG17gYKDg4N/
f4ODgIB3dZyinpigzIJ2glsun5yokmJqbnyDhIWFhoSDhYOBgnSCnp2bmMKob3t9gWU=
```
[Answer]
# PHP - 141.047.262 45.922.273 13.895.520 13.779.516
My code applies a handcrafted huffmann encoding to the input, see below for an uncompressed and commented version.
* O: 1145
* A: 1901 (42 bytes smaller)
* B: 2180 (78 bytes larger)
* C: 1223 (78 bytes larger)
* D: 1979
Demo:
```
[timwolla@~/workspace/php]cat lena.txt |php huffmann.php |php|md5sum && md5sum lena.txt
ebcc2e2a501121b37dcbac3e438be58b -
ebcc2e2a501121b37dcbac3e438be58b lena.txt
[timwolla@~/workspace/php]cat rick.txt |php huffmann.php |php|md5sum && md5sum rick.txt
549d9635795ef37857e0b3dc02e52e53 -
549d9635795ef37857e0b3dc02e52e53 rick.txt
```
Minified version:
```
<?php
$q=file_get_contents('php://stdin');$_='str_split';$i=$_($q);$t=[];$c=array_count_values($i);foreach($c as$k=>$v)$t[]=['c'=>$v,'v'=>$k];do{usort($t,function($a,$b){return$a['c']-$b['c'];});$a=array_shift($t);$b=array_shift($t);$t[]=['c'=>$a['c']+$b['c'],'l'=>$a,'r'=>$b];}while(count($t)>1);$r=[];function t($t,&$r,$j=''){if(isset($t['v']))$r[$t['v']]=$j;else{t($t['l'],$r,$j.'1');t($t['r'],$r,$j.'0');}}t($t[0],$r);uksort($r,function($a,$b){return$a<$b;});$z=$_(array_reduce($i,function($a,$b)use($r){return $a.$r[$b];},""),8);$z[]=str_pad(array_pop($z),8,0);$s="";for($i=0;$i<256;$i++)$s.=isset($r[chr($i)])?$r[chr($i)].';':';';$w='<?php
$_=<<<\'EOT\'
'.array_reduce($z,function($a,$b){return $a.chr(bindec($b));},"").'
EOT;
$s=explode(";","'.$s.'");$r=[];foreach($s as$k=>$v)$v?$r[chr($k)]=$v:1;$o=implode("",array_map(function($a){return str_pad(decbin(ord($a)),8,0,0);},'.$_.'($_)));for(;$l=strlen($o);){for($i=1;$i<$l;$i++){$p=substr($o,0,$i);if(($k=array_search($p,$r,true))!==false){echo$k;$o=substr($o,$i);continue 2;}}die;}';
do{$x=md5(mt_rand());}while(strpos($q,$x));
$q="<?=<<<'x$x'
$q
x$x;
";echo strlen($w)<strlen($q)?$w:$q;
```
Uncompressed and commented version:
(Note that it will surely spit out the unencoded version, because of the comment)
```
<?php
$q=file_get_contents('php://stdin'); // read input
$_='str_split'; // shorter name (saves some bytes in the end)
$i=$_($q); // convert input into array of chars
$c=$t=[];
$c=array_count_values($i); // calculate frequency table
foreach($c as$k=>$v){
// build bottom of huffmann tree
$t[]=[
'c'=>$v, // count
'v'=>$k // value (= the character)
];
}
do{
usort($t,function($a,$b){return$a['c']-$b['c'];}); // sort elements of the tree-to-be
$a=array_shift($t); // lowest count
$b=array_shift($t); // 2nd lowest count
// and merge them
$t[]=[
'c'=>$a['c']+$b['c'], // cumulated cost of this part of the tree
'l'=>$a, // left
'r'=>$b // right
];
}
while(count($t)>1);
$r=[];
// recursive tree traverser to build the bits of the encoding
function t($t,&$r,$j='') {
if(isset($t['v'])) {
// abort once we found a value
$r[$t['v']]=$j;
}
else {
// going left = 1
t($t['l'],$r,$j.'1');
// going right = 0
t($t['r'],$r,$j.'0');
}
}
t($t[0],$r);
// sort the bit-mapping by ascii value of the key
uksort($r,function($a,$b){return$a<$b;});
// encode the input by concatenating the bits and split the result into chunks of 8 bits
$z=$_(array_reduce($i,function($a,$b)use($r){return $a.$r[$b];},""),8);
// ensure the last part is 8 bit long
$z[]=str_pad(array_pop($z),8,0);
// encode the mapping into a semicolon separated string, unmapped characters are empty (that's why I sorted the mapping above)
$s="";
for($i=0;$i<256;$i++) {
$s.=isset($r[chr($i)])?$r[chr($i)].';':';';
}
// build the decoder
$w='<?php
$_=<<<\'EOT\'
'.array_reduce($z,function($a,$b){return $a.chr(bindec($b));},"" /* // convert the 8-bit chunks into characters */).'
EOT;
// split the encoded map at the semicolons
$s=explode(";","'.$s.'");
$r=[];
foreach($s as$k=>$v) {
$v?$r[chr($k)]=$v:1; // if there are some bits save them into the map
}
// convert the encoded characters back into a long string of 0 and 1
$o=implode("",array_map(function($a){return str_pad(decbin(ord($a)),8,0,0);},'.$_.'($_)));
for(;$l=strlen($o);){
// search the whole string for an character in the map
for($i=1;$i<$l;$i++){
$p=substr($o,0,$i);
if(($k=array_search($p,$r,true))!==false){
// character found, spit it out
echo$k;
// and remove the bits
$o=substr($o,$i);
continue 2;
}
}
// nothing found, we are finished, the remaining characters are a result of the padding to multiples of 8
die;
}';
// search a NOWDOC delimiter that does not occur in the input
do{
$x=md5(mt_rand());
}
while(strpos($q,$x));
// build a program that simply spits out the input unchanged
$q="<?=<<<'x$x'
$q
x$x;
";
// check which one is shorter :-)
echo strlen($w)<strlen($q)?$w:$q;
```
] |
Subsets and Splits