text
stringlengths
180
608k
[Question] [ Inspired by [this](https://codegolf.stackexchange.com/questions/153978/generalized-matrix-trace). Agatha Stephendale, a sophomore who is really into raster graphics, has taken a course in linear algebra. Now she imagines matrices as rectangles, but in her artistic mind, she attaches diagonal lines to those rectangles and tries to compute traces along them. In fact, she wants to compute traces of all matrices, not just square ones. Since Agatha is an artist, she knows how to draw lines in her favourite image editor, and the latter uses [Bresenham’s algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) to plot lines. She even checked Wikipedia and found the pseudocode: [![enter image description here](https://i.stack.imgur.com/4pR0G.png)](https://i.stack.imgur.com/4pR0G.png) ``` function line(x0, y0, x1, y1) real deltax := x1 - x0 real deltay := y1 - y0 real deltaerr := abs(deltay / deltax) // Assume deltax != 0 (line is not vertical), // note that this division needs to be done in a way that preserves the fractional part real error := 0.0 // No error at start int y := y0 for x from x0 to x1 plot(x,y) error := error + deltaerr while error ≥ 0.5 then y := y + sign(deltay) * 1 error := error - 1.0 ``` *(Note that this pseudocode works only for slopes less than 1; for tall grids, a similar treatment should be done, but with a loop over `y`. See [this section](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#All_cases) for the two cases.)* Agatha imagines a matrix as a rectangle, draws a diagonal line in it, and Bresenham’s algorithm determines which elements of a matrix belong to the diagonal. Then she takes their sum, and this is what she wants to implement in as few bytes as possible because she is a poor student and cannot afford large-capacity HDDs to store her code. ## Task Given a matrix *A*, return the sum of the elements that lie on the rasterised main diagonal (from top left to bottom right), where the latter is determined by Bresenham’s line algorithm. That is, assuming that the matrix represents a *m×n* grid, draw a line on that grid from A[1, 1] to A[m, n] using Bresenham’s algorithm, and take the sum of all elements on the line. Note that for *1×N* and *N×1* matrices, the entire matrix becomes its own diagonal (because this is how one would draw a line from the first element of the first row to the last element of the last row). **Input:** a real matrix (may be a *1×1* matrix, a row matrix, a column matrix, or a rectangular matrix). **Output:** a number. Note that some sources (e. g. the Wikipedia’s pseudocode above) use the condition check `error≥0.5`, while other sources use `error>0.5`. You should use the originally posted one (`error≥0.5`), but if the alternative `error>0.5` is shorter in your code, then you are allowed to implement it (since this is code golf), but **mention it explicitly**. See test case 4. ## Challenge rules * I/O formats are flexible. A matrix can be several lines of space-delimited numbers separated by newlines, or an array of row vectors, or an array of column vectors etc. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. * [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Test cases 1. `[[1,2,3],[4,5,6],[7,8,9]]` → `1+5+9` → output: `15`. [![Test case 1](https://i.stack.imgur.com/uejuk.png)](https://i.stack.imgur.com/uejuk.png) 2. `[[1,2,3,4],[5,6,7,8]]` → `1+2+7+8` → output: `18`. [![Test case 2](https://i.stack.imgur.com/R0khB.png)](https://i.stack.imgur.com/R0khB.png) 3. `[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24]]` → `1+8+9+16+17+24` → output: `75`. [![Test case 3](https://i.stack.imgur.com/VE3R4.png)](https://i.stack.imgur.com/VE3R4.png) 4. `[[1,2,3,4,5],[6,7,8,9,10]]` → `1+2+8+9+10` (using the `≥` error condition) → output: `30`. [![Test case 4](https://i.stack.imgur.com/oEZb0.png)](https://i.stack.imgur.com/oEZb0.png) However, if it would be shorter to use the strict inequality `>` in your code, then the allowed output is `1+2+3+9+10=25`, but you should mention it separately. [![Test case 5](https://i.stack.imgur.com/GlD8u.png)](https://i.stack.imgur.com/GlD8u.png) 5. `[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]` → `1+5+8+12` → output: `26`. [![Test case 5](https://i.stack.imgur.com/3ibXN.png)](https://i.stack.imgur.com/3ibXN.png) 6. `[[-0.3,0.5]]` → output: `0.2`. 7. `[[3.1],[2.9]]` → output: `6`. 8. `[[-5]]` → output: `-5`. ## More information on Bresenham’s algorithm * <http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm> — a collection of algorithms for different languages; * <https://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html> — a nice explanation featuring different cases for slopes; * <https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm>; [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ZXL>LƲ¡µLḶ÷’Ɗ×XL’Ɗær0ị"OS ``` [Try it online!](https://tio.run/##y0rNyan8/z8qwsfO59imQwsPbfV5uGPb4e2PGmYe6zo8PcIHwlhWZPBwd7eSf/D///@jow11jHSMdUx0TGN1os10zHUsdCx1DA1iYwE "Jelly – Try It Online") [Answer] # SmileBASIC, ~~101~~ 99 bytes ``` DEF D A,W,H GCLS GTRI.,0,0,0,W-1,H-1FOR I=0TO W*H-1=I MOD W S=S+A[I/W,M]*!!GSPOIT(M,I/W)NEXT?S END ``` I originally thought of using the GLINE function to draw a line, but it doesn't appear to use the correct algorithm. However, GTRI *does* seem to work, Test case 4 outputs 30. Input is a 2D array in [Y,X] form, along with the width/height (there's no way to check the dimensions of an array, only the total number of elements). [Answer] # JavaScript (ES6), ~~110~~ 103 bytes Outputs `25` for the 4th test case. ``` a=>(X=a[x=y=0].length-1,Y=1-a.length,g=e=>a[y][x]+(x-X|y+Y&&g(e+(e*2>Y&&++x&&Y)+(e*2<X&&++y&&X))))(X+Y) ``` [Try it online!](https://tio.run/##dZDRaoMwFIbv9xRehbgc05zEqIXF51BCLkJn3YboaMtQ2Lu7VKYMXHOT/Ifv/zjkw3/56@ny/nlL@uG1mc9m9qaklfF2NJMRjndN397eEoTaYOJ/I7SmMaW3k7OjY3RMqu@J1YS0tGG0eZZleDM2ElLHS36p7nkipIrDoRWr4/k09Neha3g3tPRMrUWQoBzYFDRk4c6hgKNzcRwdDhHqp395SAMZeAj0xhaP2L9mQAGIgDIMUAGmgBowA8wBi/vsCFKADE0JUoFMV32uH@tDb1ll0a8FqaPhEimxqyWCKxBcr6DgcscojkEq@fYT2V6zCRI9/wA "JavaScript (Node.js) – Try It Online") Or **[88 bytes](https://tio.run/##dZBRa4NAEITf@yt8krPOmds9Tw1Uf4ciPkhqJCXEkpSi0P9uV5NAIc29HDs338xyH@13e9mdD59f@jS8d/M@n1WLElWQF2rMp9ygz7u8aOupqccmVKMufyZd@X6vOq26Vy6WIQxH36@CcBHeymWefL8M5ChdaR2WWgfzbjhdhmMXHYde7VVdExi2QR3DIZE7RYZt08DCBoG32XjkXv5lEItbGAgh/hh882fP/H8bQAZEIBaBLCgGOVACSkHZom3BBiwkgy04looE8bUidc8rhF1XWisEcve92HnD2bPmAdUmsjCREzODrmYT8YPPRiThHC2/Q/fU5DHOre@3IO3mXw)** if taking the dimensions of the matrix as input is allowed. [Answer] # Python 3.X, 269 bytes With input as comma-delimited rows of space-delimited numbers. `import math;c=math.ceil;a=[[float(k)for k in q.split(" ")]for q in input().split(",")];_=len;m=lambda f,t,x,y,e,d:sum(x[0]for x in a)if 2>_(a[0])else m(*[0]*4,*[(_(a)-1)/(_(a[0])-1)]*2)if f else m(f,t+a[y][x],x+1,y+c(e-0.5),e+d-c(e-0.5),d)if x<_(a[0])else t;m(1,*[0]*5)` Pre-golfing: ``` def line(a): if len(a[0])<2: return sum([x[0] for x in a]) e = d = abs((len(a)-1)/(len(a[0])-1)) y=t=0 for x in range(len(a[0])): t += a[y][x] f = ceil(e-0.5) y += f e += d-f return t ``` [Answer] # [FMSLogo](http://fmslogo.sourceforge.net/ "Can run on Windows or Wine"), 136 bytes ``` make 1 rl setxy -1+count :1 -1+count last :1 pu home make 9 0 foreach :1[foreach ?[if 0=last pixel[make 9 :9+?]fd 1]setxy xcor+1 0]pr :9 ``` Full program, prompt the user for input (dialog box popup) and then print the output to the screen. Just draw a line on the screen and calculate the output. Use strict inequality. --- This only supports matrix size up to FMSLogo's canvas size (about 500×500) Ungolfed code: ``` Make "input ReadList SetXY (-1+Count :input) (-1+Count Last :input) PenUp Home Make "sum 0 ForEach :input[ ForEach ?[ If 0=Last Pixel[ Make "sum :sum+? ] Forward 1 ] SetXY XCor+1 0 ] Print :sum ``` ]
[Question] [ **This question already has answers here**: [Tell me the moves](/questions/25018/tell-me-the-moves) (12 answers) Closed 6 years ago. Chess is a game with 6 different types of pieces that can move in different ways: * Pawns - They can only move up or capture diagonally (also forward). Capturing a piece behind them or beside them is illegal. The only exception is [en passant](https://en.wikipedia.org/wiki/En_passant). For this challenge, if a pawn reaches the 8th rank (or row), assume it becomes a queen. * Bishops - They move diagonally and the squares they travel on will always have the same color (i.e if the square the bishop is currently on is white, the bishop can't move to a darker square for instance). * Knights - They move pretty awkwardly. They can move two spaces up/down then one space to the right/left or two spaces right/left then on space up/down. * Rooks - They can only move in straight lines, up or down or left or right. * Queens - They can move diagonally like a bishop or in straight lines like a rook * Kings - They can only move to squares they are touching (including diagonals). This [chess.com](https://www.chess.com/learn-how-to-play-chess) link to clarify the above. A chessboard and its coordinates are shown below: [![enter image description here](https://i.stack.imgur.com/bzQdB.png)](https://i.stack.imgur.com/bzQdB.png) So given an entirely empty chessboard except for one piece and the inputs -- the piece's type and its current position, what are the piece's legal moves? **Examples** ``` Input: Rook a8 Output: a1 a2 a3 a4 a5 a6 a7 b8 c8 d8 e8 f8 g8 h8 Input: Pawn a2 Output: a4 a3 Input: Pawn a3 Output: a4 Input: Knight a1 Output: c2 b3 Input: Bishop h1 Output: a8 b7 c6 d5 e4 f3 g2 Input: King b2 Output: c2 c3 c1 b3 b1 a1 a2 a3 Input: Queen h1 Output: a8 b7 c6 d5 e4 f3 g2 h2 h3 h4 h5 h6 h7 h8 a1 b1 c2 d1 e1 f1 g1 ``` **Rules and Specifications** * A legal move is defined as a move in which the piece can go to while being on the board. So a rook at a1 can go to a8 (moving to the right) but not to b2 since you can't get there with a straight line (only possible in two or more moves) * Pawns will never be in the first or eighth rank (it would then be another piece). If a pawn is in the second rank, it can move up two spaces (not for captures). Otherwise, it can only move forward a square. * Notation for Queening a pawn is not needed * Capitalization does not matter though the letter must come before and attached to the number * The acceptable moves must be separated in some way (i.e commas, spaces, different lines, in a list) * Always assume that the bottom left corner is a1 and you are playing as White * The input can be a single string (i.e `rooka3` or `Rook a3` or `rook a3` or `Rook A3`) is acceptable and can be in any order (i.e the position before the type like `A3 rook`). Multiple strings are also acceptable. **Winning Criteria** Shortest code wins! [Answer] ## JavaScript (ES6), ~~256~~ ... ~~229~~ 227 bytes Takes input as two strings `(p, s)`, where `p` is the case-insensitive name of the piece and `s` is the source square. Returns a space-separated list of destination squares. ``` f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):'' ``` ### How it works **Piece name decoding** The name of the piece `p` is converted to an integer `P` by parsing it in base 32, multiplying the result by 5 and isolating the 3 least significant bits: `parseInt(p, 32) * 5 & 7` ``` Piece | As base 32 | * 5 | & 7 ----------+------------+------------+---- "king" | 674544 | 3372720 | 0 "knight" | 695812669 | 3479063345 | 1 "pawn" | 810 | 4050 | 2 NB: 'pawn' is parsed as 'pa', because 'w' "queen" | 28260823 | 141304115 | 3 is not a valid character in base 32 "rook" | 910100 | 4550500 | 4 "bishop" | 388908825 | 1944544125 | 5 ``` In addition to being a perfect hash, a good thing about this formula is that all sliding pieces (Queen, Rook and Bishop) appear at the end of the list, which allows to identify them with a simple `P > 2`. **Source square decoding** The source square `s` is converted to an integer `S` by parsing it in base 18 and converting the result to [0x88 coordinates](https://chessprogramming.wikispaces.com/0x88). That leads to the following board representation: ``` a b c d e f g h 8 0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 7 0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 6 0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 5 0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 4 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 3 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 2 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 1 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 ``` **Directions encoding** There are 16 possible directions: 4 along ranks and files, 4 along diagonals and 8 for the knights. ``` As hexadecimal: As decimal: +0x1F +0x21 +31 +33 +0x0E +0x0F +0x10 +0x11 +0x12 +14 +15 +16 +17 +18 -0x01 [SRC] +0x01 -1 [SRC] +1 -0x12 -0x11 -0x10 -0x0F -0x0E -18 -17 -16 -15 -14 -0x21 -0x1F -33 -31 ``` Therefore, the list of directions that a piece can move towards can be encoded as a 16-bit bitmask. ``` Bit: | F E D C B A 9 8 7 6 5 4 3 2 1 0 | As Vector: | +33 -33 +31 -31 +18 -18 +14 -14 +1 -1 +17 -17 +15 -15 +16 -16 | decimal --------+-----------------------------------------------------------------+-------- King | 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 | 255 Knight | 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 | 65280 Pawn | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 | 2 Queen | 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 | 255 Rook | 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 | 195 Bishop | 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 | 60 ``` The absolute values of the direction vectors can be stored in base 36: ``` [16, 15, 17, 1, 14, 18, 31, 33][n] <==> parseInt('gfh1eivx'[n], 36) ``` **Formatted and commented** ``` f = (p, s, i = 128) => // given a piece p, a square s and a counter i i-- ? // if i is >= 0: f(p, s, i) + ( // do a recursive call to f() [ x = 255, x << 8, 2, x, 195, 60 ][ // take the direction bitmask for: P = (I = parseInt)(p, 32) * 5 & 7 // P = piece index in [0 .. 5] ] >> i / 8 & ( // and test the bit for the current direction (d = i % 8) < ( // d = current move distance - 1 S = (x = I(s, 18) - 181) / 18 | // S = source square in x % 18 * 16, // 0x88 representation P > 2 ? 8 : P < 2 | S > 23 || 2 // compare d with the maximum move range for ) // this piece ) ? // if the above test passes: ( // we add to S: S += I( // the absolute value of the vector of 'gfh1eivx'[i >> 4], 36 // the current direction, ) * // multiplied by (i & 8 ? d + 1 : ~d) // the move distance with the vector sign ) & 136 ? // if the result AND'd with 0x88 is not null: '' // this is an invalid destination square : // else: 'abcdefgh'[S & 7] + // it is valid: convert it back to ASCII (S + 16 >> 4) + ' ' // and append a space separator : // else: '' // this is an invalid move ) // end of this iteration : // else: '' // stop recursion ``` ### Test cases ``` f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):'' console.log(f('Rook', 'a8')); console.log(f('Pawn', 'a2')); console.log(f('Pawn', 'a3')); console.log(f('Knight', 'a1')); console.log(f('Bishop', 'h1')); console.log(f('King', 'b2')); console.log(f('Queen', 'h1')); ``` [Answer] # Python 2, ~~484~~ ~~472~~ ~~423~~ 406 bytes This is a lot longer than I wanted it to be. ``` i=input() a=ord(i[1][0])-97 c=int(i[1][1]) g=range(-8,8) b=sum([[(a-x,c-x),(a-x,c+x)]for x in g],[]) r=sum([[(a-x,c),(a,c-x)]for x in g],[]) print[chr(x[0]+97)+str(x[1])for x in set([[(a,c+1)]+[(a,c+2)]*(c==2),b,sum([[(a-x,c-y)for x,y in[[X,Y],[X,-Y],[-X,Y],[-X,-Y]]]for X,Y in[[1,2],[2,1]]],[]),r,b+r,[(a-x,c-y)for x in[-1,0,1]for y in[-1,0,1]]]['wsioen'.find(i[0][2])])-set([a,c])if-1<x[0]<8and 0<x[1]<9] ``` -12 bytes by removing some unnecessary variable names -49 bytes thanks to ovs by splitting s into multiple variables -17 bytes thanks to ovs by switching from range to comparison Input is taken as `['PieceName', '<letter><num>']`. Output is given as an array of strings in the same 1-indexed a-h format `<letter><num>`. ]
[Question] [ # Introduction [Kipple](https://esolangs.org/wiki/Kipple) is a stack-based, esoteric programming language invented by Rune Berg in March 2003. Kipple has 27 stacks, 4 operators, and a control structure. ## Stacks The stacks are named `a`-`z` and contain 32-bit signed integers. There is also a special stack, `@`, to make outputting numbers more convenient. When a number is pushed onto `@`, the ASCII values of that number's digits are in fact pushed instead. (For example, if you push 12 to `@`, it will push 49 and then 50 to `@` instead.) Input is pushed onto the input stack `i` before the program is executed. The interpreter will ask for values to store in `i` before execution. After execution finishes, anything on the output stack `o` is popped to output as ASCII character . Since this is Kipple's only IO mechanism, interacting with a Kipple program is impossible. ## Operators An operand is either a stack identifier or a signed 32 bit integer. ### Push: `>` or `<` Syntax: `Operand>StackIndentifier` or `StackIndentifier<Operand` The Push operator takes the operand to the left and pushes it onto the specified stack. For example, `12>a` will push the value 12 onto stack `a`. `a>b` will pop the topmost value from stack `a` and push it onto stack `b`. Popping an empty stack always returns 0. `a<b` is equivalent to `b>a`. `a<b>c` pops topmost value from `b` and pushes to both `c` and `a`. ### Add: `+` Syntax: `StackIndentifier+Operand` The Add operator pushes the sum of the topmost item on the stack and the operand onto the stack. If the operand is a stack, then the value is popped from it. For example, if the topmost value of stack `a` is 1, then `a+2` will push 3 onto it. If `a` is empty, then `a+2` will push 2 onto it. If the topmost values of stack `a` and `b` are 1 and 2, then `a+b` will pop the value 2 from stack `b` and push 3 onto stack `a`. ### Subtract: `-` Syntax: `StackIndentifier-Operand` The Subtract operator works exactly like the Add operator, except that it subtracts instead of adding. ### Clear: `?` Syntax: `StackIndentifier?` The Clear operator empties the stack if its topmost item is 0. The interpreter will ignore anything that isn't next to an operator, so the following program would work: `a+2 this will be ignored c<i`. However, the proper way to add comments is by using the `#` character. Anything between a `#` and an end-of-line character is removed before execution. ASCII character #10 is defined as end-of-line in Kipple. Operands may be shared by two operators, e.g. `a>b c>b c?` may be written as `a>b<c?`. The program `1>a<2 a+a` will result in `a` containing the values `[1 4]` (from bottom to top) and not `[1 3]`. Likewise for the `-` operator. ## The Control Structure There is only one control structure in Kipple: the loop. Syntax: `(StackIndentifier code )` As long as the specified stack is not empty, the code within the matching parentheses will be repeated. Loops may contain other loops. For example, `(a a>b)` will move all the values of stack `a` onto stack `b`, though the order will be *reversed*. A functionally identical, but more elegant way to do this is `(a>b)`. ## Examples ``` 100>@ (@>o) ``` This will output `100` ``` 33>o 100>o 108>o 114>o 111>o 87>o 32>o 111>o 108>o 108>o 101>o 72>o ``` This will print `"Hello World!"`. When the `o` stack is being output, it starts to pop characters from top of the stack to bottom. ``` #prime.k by Jannis Harder u<200 #change 200 k<2>m u-2 (u-1 u>t u>z u<t (k>e e+0 e>r) (e>k) m+1 m>t m>z m<t t<0>z? t? 1>g (r>b m+0 m>a b+0 b>w (a-1 b+0 b>j j? 1>s (j<0>s j?) s? (s<0 w+0 w>b s?) a>t a>z t>a b-1 b>t b>z t>b z<0>t? z? a?) b? 1>p (b<0 b? 0>p) p? (p 0>r? 0>p? 0>g) ) g? (g m+0 m>k 0>g?) u?) (k>@ 10>o (@>o) ) ``` This is a prime number generator, but I'm not sure how it works. # Rules * You must write a program/function that interprets Kipple. This program/function may get a Kipple program via a source file, or get it via STDIN directly from the user. If STDIN is not available, it must get it from keyboard input, and continue getting input until a specific unprintable character is entered. For example, if your interpreter is written in x86 machine code, it would get the Kipple program character by character from keyboard, and continue to do so until `esc` (or any other key other that does not emit a printable character) is pressed. * If there is an error, e.g. a syntax error or stack overflow, it must acknowledge it in some way, for example by returning 10 instead of 0 or error messages produced by the interpreter/compiler, **BUT NOT PRINTING ERROR MESSAGES**. * Any other regular rules for code golf apply for this challenge. * Your code will be tested with some of the examples in [Kipple's samples archive](http://web.archive.org/web/20061104091442/http://rune.krokodille.com/lang/kipple/samples/) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") . Shortest code in bytes will win. Good Luck! --- Note that there is an optional operator in Kipple, `"`, but it is not a part of the specification and just an extra feature in official interpreter. I haven't mentioned it here so it does not need to be supported in your submission. If you have any doubt about any part of specification , you can examine it with [official interpreter written in Java](http://web.archive.org/web/20061104090549/http://rune.krokodille.com/lang/kipple/files/kipple1.01.zip) . This will download a zip file containing compiled program and source code . It's licensed under the GPL. [Answer] # C, 709 702 bytes The byte score is with newlines (that can be removed) removed, but for ease of reading I post it here with newlines: ``` #define R return #define C ;break;case c[999]={};*P=c;*S[28];M[99999]={};t;*T; u(s,v){S[s]+=28;*S[s]=v; if(s>26){for(t=v/10;t;t/=10)S[s]+=28;T=S[s];do{*T=48+v%10;T-=28;}while(v/=10);}} o(s){t=S[s]-M>27;S[s]-=28*t;R S[s][28]*t;} I(s){R s<65?27:s-97;} O(int*p){if(!isdigit(*p))R o(I(*p)); for(;isdigit(p[-1]);--p);for(t=0;isdigit(*p);t*=10,t+=*p++-48);R t;} main(i,a){for(i=0;i<28;++i)S[i]=M+i; for(;~(*++P=getchar()););P=c+1; for(;;){i=I(P[-1]);switch(*P++){ case 35:for(;*P++!=10;) C'<':u(i,O(P)) C'>':u(I(*P),O(P-2)) C'+':u(i,*S[i]+O(P)) C'-':u(i,*S[i]-O(P)) C'?':if(!*S[i])S[i]=M+i C'(':for(i=1,T=P;i;++T)i+=(*T==40)-(*T==41);if(S[I(*P)]-M<28)P=T;else u(26,P-c) C')':P=c+o(26)-1 C-1:for(;i=o(14);)putchar(i); R 0;}}} ``` Compile with `gcc -w golf.c` (`-w` silences warnings for your sanity). Supports everything except the `i` input, as the asker has not responded yet to my inquiry on how to do it if you take the code from stdin. It does not report syntax errors. [Answer] # Ruby, 718 bytes (currently noncompeting) i'm very tired File is loaded as a command line argument, and input is sent through STDIN. Alternatively, pipe the file into STDIN if you don't need input in your `i` register. ~~Because of some confusion regarding the spec, the current version is not handling `a<b>c` properly, and therefore is noncompeting until it is fixed.~~ `a<b>c` is fixed now. However, it still returns the wrong result when running the primes function, so it still remains as a noncompeting answer. ``` (f=$<.read.gsub(/#.*?\n|\s[^+-<>#()?]*\s/m,' ').tr ?@,?` t=Array.new(27){[]} t[9]=STDIN.read.bytes k=s=2**32-1 r=->c{c=c[0];c[0]==?(?(s[c[1..-2]]while[]!=t[c[1].ord-96]):(c=c.sub(/^(.)<(\D)>(.)/){$1+"<#{t[$2.ord-96].pop||0}>"+$3}.sub(/(\d+|.)(\W)(\d+|.)?/){_,x,y,z=*$~ a=x.ord-96 b=(z||?|).ord-96 q=->i,j=z{j[/\d/]?j.to_i: (t[i]||[]).pop||0} l=t[a] y<?-?(x==z ?l[-1]*=2:l<<(l.pop||0)+q[b] l[-1]-=k while l[-1]>k/2):y<?.?(x==z ?l[-1]=0:l<<(l.pop||0)-q[b] l[-1]+=k while l[-1]<-k/2-1):y<?>?t[a]+=a<1?q[b].to_s.bytes: [q[b]]:y<??? (t[b]+=b<1?q[a,x].to_s.bytes: [q[a,x]]): l[-1]==0?t[a]=[]:0 z||x}while c !~/^(\d+|.)$/)} s=->c{(z=c.scan(/(\((\g<1>|\s)+\)|[^()\s]+)/m)).map &r} s[f] $><<t[15].reverse.map(&:chr)*'')rescue 0 ``` ]
[Question] [ A simple pedometer can be modeled by a pendulum with two switches on opposite sides—one at x=0 and one at x=***l***. When the pendulum contacts the far switch, the ambulator can be assumed to have taken half a step. When it contacts the near switch, the step is completed. Given a list of integers representing positions of the pendulum, determine the number of full steps recorded on the pedometer. ### Input * An integer ***l***>0, the length of the track. * A list of integers representing the positions of the pedometer's pendulum at each time. ### Output The number of full steps measured. A step is taken when the pendulum contacts the far switch (x>=l) and then the near switch (x<=0). ### Test cases ``` 8, [8, 3, 0, 1, 0, 2, 2, 9, 4, 7] 1 ``` The pendulum immediately makes contact with the far switch at x=8 at t=0. Then it touches the near switch at t=2 and t=4, completing one step. After that, it touches the far switch again at x=9 at t=8, but it never touches the near switch again. ``` 1, [1, 5, -1, -4, -1, 1, -2, 8, 0, -4] 3 15, [10, -7, -13, 19, 0, 22, 8, 9, -6, 21, -14, 12, -5, -12, 5, -3, 5, -15, 0, 2, 11, -11, 12, 5, 16, 14, 27, -5, 13, 0, -7, -2, 11, -8, 27, 15, -10, -10, 4, 21, 29, 21, 2, 5, -7, 15, -7, -14, 13, 27] 7 7, [5, 4, 0] 0 7, [5, 8, 6, 1, 2] 0 ``` [Answer] ## CJam, ~~27~~ 24 bytes ``` l~:Xfe<0fe>_[XT]:Y--Y/,( ``` Input format is the list of pendulum positions followed by `l` on a single line. [Test it here.](http://cjam.aditsu.net/#code=l~%3AXfe%3C0fe%3E_%5BXT%5D%3AY--Y%2F%2C(&input=%5B10%20-7%20-13%2019%200%2022%208%209%20-6%2021%20-14%2012%20-5%20-12%205%20-3%205%20-15%200%202%2011%20-11%2012%205%2016%2014%2027%20-5%2013%200%20-7%20-2%2011%20-8%2027%2015%20-10%20-10%204%2021%2029%2021%202%205%20-7%2015%20-7%20-14%2013%2027%5D%2015) ### Explanation ``` l~ e# Read and evaluate input. :X e# Store track length in X. fe< e# Clamp each position to X from above. 0f> e# Clamp each position to 0 from below. _ e# Duplicate. [XT] e# Push the array [X 0]. :Y e# Store it in Y. - e# Set subtraction from the clamped input list. This gives all the e# intermediate values. - e# Another set subtraction. Remove intermediate values from input list. Y/ e# Split remaining list around occurrences of ...X 0... ,( e# Count them and decrement. This is the number of times the pendulum e# moved from X to 0. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 bytes ``` >~2G0>~-XzY'nw1)0<-H/k ``` This uses [current version (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler. Inputs are in the same order and format as in the challenge, separated by a newline. [**Try it online!**](http://matl.tryitonline.net/#code=Pn4yRzA-fi1YelknbncxKTA8LUgvaw&input=MTUKWzEwLCAtNywgLTEzLCAxOSwgMCwgMjIsIDgsIDksIC02LCAyMSwgLTE0LCAxMiwgLTUsIC0xMiwgNSwgLTMsIDUsIC0xNSwgMCwgMiwgMTEsIC0xMSwgMTIsIDUsIDE2LCAxNCwgMjcsIC01LCAxMywgMCwgLTcsIC0yLCAxMSwgLTgsIDI3LCAxNSwgLTEwLCAtMTAsIDQsIDIxLCAyOSwgMjEsIDIsIDUsIC03LCAxNSwgLTcsIC0xNCwgMTMsIDI3XQ) ### Explanation ``` >~ % take the two inputs implicitly. Generate an array that contains true % where the second input (array of positions) is >= the first input (l) 2G % push second input (positions) again 0 % push a 0 >~ % true where the second input (array of positions) is <= 0 - % subtract: array of 1, -1 or 0 Xz % discard the 0 values Y' % run-length encoding: push values and number of repetitions n % length of the latter array: number of half-steps, perhaps plus 1 w1) % swap. Get first element 0< % true if that element is -1. We need to discard one half-step then - % subtract H/k % divide by 2 and round down ``` [Answer] # Javascript ES6 57 bytes ``` (t,a)=>a.map(a=>a<t?a>0?'':0:1).join``.split`10`.length-1 ``` Thanks @NotThatCharles for -4 [Answer] # Perl, 28 bytes Includes +1 for `-p` Run with the input as one long line of space separated integers on STDIN, the first number is the length: ``` perl -p steps.pl <<< "8 8 3 0 1 0 2 2 9 4 7" ``` `steps.pl`: ``` s; ;$'>=$_..$'<1;eg;$_=y;E; ``` Uses the perl flip-flop operator and counts the number of times it returns to false [Answer] # Pyth, 18 bytes ``` /.:@J,Q0m@S+Jd1E2J ``` [Test suite](https://pyth.herokuapp.com/?code=%2F.%3A%40J%2CQ0m%40S%2BJd1E2J&input=1%0A%5B1%2C+5%2C+-1%2C+-4%2C+-1%2C+1%2C+-2%2C+8%2C+0%2C+-4%5D&test_suite=1&test_suite_input=1%0A%5B1%2C+5%2C+-1%2C+-4%2C+-1%2C+1%2C+-2%2C+8%2C+0%2C+-4%5D%0A15%0A%5B10%2C+-7%2C+-13%2C+19%2C+0%2C+22%2C+8%2C+9%2C+-6%2C+21%2C+-14%2C+12%2C+-5%2C+-12%2C+5%2C+-3%2C+5%2C+-15%2C+0%2C+2%2C+11%2C+-11%2C+12%2C+5%2C+16%2C+14%2C+27%2C+-5%2C+13%2C+0%2C+-7%2C+-2%2C+11%2C+-8%2C+27%2C+15%2C+-10%2C+-10%2C+4%2C+21%2C+29%2C+21%2C+2%2C+5%2C+-7%2C+15%2C+-7%2C+-14%2C+13%2C+27%5D%0A7%0A%5B5%2C+4%2C+0%5D%0A7%0A%5B5%2C+8%2C+6%2C+1%2C+2%5D&debug=0&input_size=2) Explanation: ``` /.:@J,Q0m@S+Jd1E2J Implicit: Q is the length of the track. J,Q0 Set J to [Q, 0] m E Map over the list +Jd Add the current element to J S Sort @ 1 Take the middle element. This is the current element, clamped above by Q and below by 0. @J Filter for presence in J. .: 2 Form 2 element substrings / J Count occurrences of J. ``` [Answer] # Ruby, 42 ``` ->i,a{r=!0 a.count{|v|r^r=v>=i||r&&v>0}/2} ``` `r` starts as `false`. We toggle `r` at each end of the track, and add it to our count. Then, halve the count (rounding down) to get the number of steps. [Answer] # Retina, 34 ``` -1* ^(1*)((?>.*?\1.*? \D))*.* $#2 ``` [Try it online!](http://retina.tryitonline.net/#code=LTEqCgpeKDEqKSgoPz4uKj9cMS4qPyBcRCkpKi4qCiQjMg&input=MTExMTExMSwgWzExMTExLCAxMTExLCBd) or [try it with decimal input](http://retina.tryitonline.net/#code=XGQrCiQqCi0xKgoKXigxKikoKD8-Lio_XDEuKj8gXEQpKSouKgokIzI&input=MTUsIFsxMCwgLTcsIC0xMywgMTksIDAsIDIyLCA4LCA5LCAtNiwgMjEsIC0xNCwgMTIsIC01LCAtMTIsIDUsIC0zLCA1LCAtMTUsIDAsIDIsIDExLCAtMTEsIDEyLCA1LCAxNiwgMTQsIDI3LCAtNSwgMTMsIDAsIC03LCAtMiwgMTEsIC04LCAyNywgMTUsIC0xMCwgLTEwLCA0LCAyMSwgMjksIDIxLCAyLCA1LCAtNywgMTUsIC03LCAtMTQsIDEzLCAyN10). Takes input in unary, negative unary numbers are treated as `-111...` and zero is the empty string. Counts the number of times that the first number appears followed by a zero. Uses an atomic group to guarantee that the matches are minimal (sadly atomic groups are non-capturing so it has to be wrapped in another group...). [Answer] # Python 3, 82 Saved 2 bytes thanks to DSM. Not super golfed yet. ``` def f(x,s): c=l=0 for a in s: if a>=x:l=x elif a<1:c+=l==x;l*=l!=x return c ``` Test cases: ``` assert f(8, [8, 3, 0, 1, 0, 2, 2, 9, 4, 7]) == 1 assert f(1, [1, 5, -1, -4, -1, 1, -2, 8, 0, -4]) == 3 assert f(15, [10, -7, -13, 19, 0, 22, 8, 9, -6, 21, -14, 12, -5, -12, 5, -3, 5, -15, 0, 2, 11, -11, 12, 5, 16, 14, 27, -5, 13, 0, -7, -2, 11, -8, 27, 15, -10, -10, 4, 21, 29, 21, 2, 5, -7, 15, -7, -14, 13, 27]) == 7 ``` [Answer] ## Clojure, 64 bytes ``` #(count(re-seq #"10"(apply str(for[i %2](condp > i 1 0 %""1))))) ``` Maps values less-than-or-equal of zero to `0`, larger-than-or-equal of length to `1` and others to an empty string `""`. This is then concatenated to a string and occurrences of `"10"` are counted. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Also known as "how much can I abuse iota-underbar?" ``` ≢∘∪0~⍨(⍸≤)⍸(⍸0≥⊢) ``` [Try it online!](https://tio.run/##NY@/asNADMZ3P8U3NkPhdGfnznOXZgo0eYFAcRdDunbpEjB2wCEZAp1DC6FL1s55FL2IKykOh/6c9NOnu9V7/fj6sarXb8PA3YnbL25/3Sf35wfu/7j7nkjQ1HH3w9vTZKi42XO/491xNuft5noJ3Bzktnh5Er98ni2GhAoJAQ4k5uWUyBEzkjqhwPVCYrlFzbzQTisZFYpoHrUbQKUqKFBKYQqvPOUgL9GUvAmGm2xh@8gggvVoCuF9NJ4C7uIjlrRFNuxuLtclvjRvqmM/jpuDTGRR3lkI6sYsQdbAZ/p1Z99J/w "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ Given an input of a list of words and their abbreviations, output the pattern by which the abbreviations can be formed. Let us take the example input of ``` potato ptao puzzle pzze ``` as an example (that is, the abbreviation for `potato` is `ptao`, and the abbreviation for `puzzle` is `pzze`). Consider all possible ways to obtain `ptao` from `potato`. One possible way is to take the first, third, fourth, and sixth letters, which we will refer to as `1346`. But since `t` and `o` appear multiple times in the word, there are multiple other possible ways to generate `ptao` from `potato`: `1546`, `1342`, and `1542`. Similarly, note that `pzze` can be generated from `puzzle` with any of `1336`, `1346`, `1436`, `1446`. The only pattern that these two abbreviations have in common is `1346`; therefore, that must be the output for this input. If multiple possible patterns are possible, you may output any, some, or all of them (at least one). You may assume that: * Input words and abbreviations contain only lowercase letter. * There is at least one word/abbreviation pair in the input. * It is possible for every abbreviation to be formed from its corresponding word. * There will always be at least one pattern that forms every abbreviation. * The maximum length of each word is 9 characters. Input may be taken as any of the following: * 2-dimensional array/list/array of tuples/etc. `[[word, abbr], [word, abbr], ...]` * flat 1-dimensional array/list `[word, abbr, word, abbr, ...]` * single string, delimited by any single character that is not a lowercase letter `"word abbr word abbr"` * hash/associative array/etc. `{word => abbr, word => abbr, ...}` In any of these input options, you are also permitted to swap the order of word/abbr (please fully describe the input format in your post). Output may be given as a single number, a string delimited by non-digits, or an array/list/tuple/etc. of numbers. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases (remember that you only need to output ≥1 results if multiple patterns work): ``` In Out -------------------------------------------------------- potato ptao puzzle pzze | 1346 aabbcc abc fddeef def | 246 prgrmming prgmg puzzles pzzlz | 14353 aaaaa a bbbb b ccc c dd d e e | 1 aaaaa a bbbb b ccc c | 1, 2, 3 abcxyz zbcyax | 623514 abcxyz acbbacbcbacbbac | 132213232132213 potato ptao | 1346, 1546, 1342, 1542 a aaaaa | 11111 ``` [Answer] # Pyth, 19 bytes ``` [[email protected]](/cdn-cgi/l/email-protection) ``` [Try it here!](http://pyth.herokuapp.com/?code=mhh%40Fd.TmmxkmbhdedQ&input=[[%22potato%22%2C+%22ptao%22]%2C[%22puzzle%22%2C+%22pzze%22]]&test_suite=1&test_suite_input=[[%22potato%22%2C+%22ptao%22]%2C[%22puzzle%22%2C+%22pzze%22]]%0A[[%27aabbcc%27%2C+%27abc%27]%2C+[%27fddeef%27%2C+%27def%27]]%0A[[%27prgrmming%27%2C+%27prgmg%27]%2C+[%27puzzles%27%2C+%27pzzlz%27]]%0A[[%27aaaaa%27%2C+%27a%27]%2C+[%27bbbb%27%2C+%27b%27]%2C+[%27ccc%27%2C+%27c%27]%2C+[%27dd%27%2C+%27d%27]%2C+[%27e%27%2C+%27e%27]%2C+[%27%27]]%0A[[%27aaaaa%27%2C+%27a%27]%2C+[%27bbbb%27%2C+%27b%27]%2C+[%27ccc%27%2C+%27c%27]]%0A[[%27abcxyz%27%2C+%27zbcyax%27]]%0A[[%27abcxyz%27%2C%27acbbacbcbacbbac%27]]%0A[[%27potato%27%2C+%27ptao%27]]%0A[[%27a%27%2C+%27aaaaa%27]]&debug=0) Takes a list in the following format: ``` [["word","abbr"],["word","abbr"],...] ``` Alternative 17 bytes solution which outputs the result as list of zero-based indices which are wrapped in an 1-element list: ``` [[email protected]](/cdn-cgi/l/email-protection) ``` ## Explanation Example: `[["potato", "ptao"],["puzzle", "pzze"]]` First we map every char in the abbrevation to a list of the indices of all occurences in the word which yields `[[[0], [2, 4], [3], [1, 5]], [[0], [2, 3], [2, 3], [5]]]` Then we transpose this list which gives us `[[[0], [0]], [[2, 4], [2, 3]], [[3], [2, 3]], [[1, 5], [5]]]` So the indices of each char of each abbrevation are together in one list. Then we just have to find one common index in all of those lists which yields: `[[0], [2], [3], [5]]` This is the output of my alternative 17 byte solution above. This then gets transformed into `[1,3,4,6]`. ### Code breakdown ``` [[email protected]](/cdn-cgi/l/email-protection) # Q = input m Q # map input with d m ed # map each abbrevation with k mbhd # map word to char list mxk # map each abbrevation char to a list of indices .T # Transpose Fd # Fold every element @ # and filter on presence hh # Take first element of the result und and increment it ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 29 bytes ``` !"@Y:!=2#fX:wX:h]N$v1XQtv4#X> ``` Input is a 2D array in the following format: ``` {'potato' 'ptao'; 'puzzle' 'pzze'} ``` [**Try it online!**](http://matl.tryitonline.net/#code=ISJAWTohPTIjZlg6d1g6aF12MXRYUXR2NCNYPg&input=eydwcmdybW1pbmcnICdwcmdtZyc7ICdwdXp6bGVzJyAncHp6bHonfQ) (*the linked code includes some modifications owing to changes in the language since this answer was posted*) ``` ! % take input. Transpose " % for each column @Y: % push column. Unpack the two strings and push them onto the stack ! % transpose second string = % matrix with all pairwise matchings of characters in word and abbreviation 2#f % find row and col indices of those matchings X: % transform into column vector wX: % swap, transform into column vector h % concat into a two-col matrix ] % end for N$v % concatenate all matrices containing the indices 1 % push 1 XQ % build matrix adding 1 for each (row,col) index tv % concat vertically with itself, so that it has at least two rows. % This forces the following function to work on each col. 4#X> % arg max of each col: position that produces a match in all pairs. % If there are several maximizers in each col this gives the first ``` The code required some involved (and lengthy!) tricks to * Prevent the orientation of vectors produced by `find` (`f`) from changing depending on input shape. These are statements `X:wX:`: force both outputs to be column vectors. * Counteract the "work along first non-singleton dimension" default behaviour of the `min` (`X>`) function. These are statements `tv`: concat a copy of itself to assure at least two rows); [Answer] # Perl, ~~46~~ ~~45~~ 42 bytes Includes +1 for `-p` Give input as sequential words on STDIN, e.g. ``` perl -p abbrev.pl prgrmming prgmg puzzles pzzlz ``` Terminate STDIN with `^D` or `^Z` or whatever is needed on your system `abbrev.pl`: ``` s#.#${${--$_.$.%2}.=$&}||=-$_#eg;$_ x=eof ``` ## Explanation Consider this input (conceptual layout, not the real way to input for this program): ``` potatoes ptao puzzle pzze ``` The program build strings representing the vertical columns of the full strings indexed on a column id ``` id1 pp -> 1 id2 ou -> 2 id3 tz -> 3 id4 az -> 4 ... ``` etc. It also does the same for the abbreviations, but using a different id ``` ID1 pp -> 1 ID2 tz -> 3 ID3 az -> 4 ID4 oe -> 6 ``` The words are implicitely processed one by one by using the `-p` option. The columns strings are constructed using repeated concatenations while each word is walked using `s#.# ...code.. #eg`, so each column needs a repeatable id. I use minus the column number followed by the line number modulo 2. The column number can be constructed using `--$_` which starts out as the current word which due to the use of only `a-z` is guaranteed to evaluate as 0 in a numeric context. So I get `-1, -2, -3, ...`. I'd really would have liked to use `1, 2, 3, ...`, but using `$_++` would trigger perl magic string increment instead of a normal numeric counter. I **do** want to use `$_` and not some other variable because any other variable I would have to initialize to zero in every loop which takes too many bytes. The line number modulo 2 is to make sure the ids for the full word and the ids for the abbreviation don't clash. Notice that I cannot use the full word and the abbreviation on one string to have a column number going over the combined string because the full words don't all have the same length, so the abbeviated word columns wouldn't line up. I also can't put the abbreviated word first (they all have the same length) because I need the count of the first column of the full words to be 1. I abuse the perl global name space through a non strict reference to construct the column strings as: ``` ${--$_.$.%2}.=$& ``` Next I map each column string to the first column number that string ever appears in (the mapping already indicated above) by again abusing the perl global namespace (but notice that the names cannot clash so the globals don't interfere with each other): ``` ${${--$_.$.%2}.=$&} ||= -$_ ``` I have to negate `$_` because like I explained above I count the columns as `-1, -2, -3, ...`. The `||=` make sure only the first appearance of a given column gets a new column number, otherwise the previous column number is preserved **and** returned as value. This will happen in particular for every abbreviated word since the specification guarantees that there is a column in the full words that will have appeared beforehand. So in the very last abbreviated word each letter will be replaced by the column number in the full word that corresponds with the column for all abbreviated words. So the result of the very last substitution is the final result that is wanted. So print if and only if we are at the end of the input: ``` $_ x=eof ``` The column index assignment will also create entries for incomplete columns because the column is not completely constructed yet or some words are shorter and don't reach the full column length. This is not a problem since the columns needed in every abbreviated word are guaranteed to have a corrsponding column from the full words which has the maximum possible length (the number of currently seen pairs) so these extra entries never cause false matches. [Answer] ## Haskell, 74 bytes ``` import Data.List foldl1 intersect.map(\(w,a)->mapM(`elemIndices`(' ':w))a) ``` Input format is a list of pairs of strings, e.g.: ``` *Main > foldl1 intersect.map(\(w,a)->mapM(`elemIndices`(' ':w))a) $ [("potato","ptao"),("puzzle","pzze")] [[1,3,4,6]] ``` How it works: `mapM` (same as `sequence . map`) first turns every pair `(w,a)` into a list of lists of indices of the letters in the abbreviation (`' ':` fixes Haskell's native 0-based index to 1-based), e.g. `("potato", "ptao") -> [[1],[3,5],[4],[2,6]]` and then into a list of all combinations thereof where the element at position `i` is drawn from the `i`th sublist, e.g. `[[1,3,4,2],[1,3,4,6],[1,5,4,2],[1,5,4,6]]`. `foldl1 intersect` finds the intersection of all such lists of lists. [Answer] ## ES6, 92 bytes ``` (w,a)=>[...a[0]].map((_,i)=>[...w[0]].reduce((r,_,j)=>w.some((s,k)=>s[j]!=a[k][i])?r:++j,0)) ``` Accepts input as an array of words and an array of abbreviations. Returns an array of 1-based indices (which costs me 2 bytes dammit). In the case of multiple solutions, the highest indices are returned. [Answer] ## Python 3, 210 bytes Not an impressive answer seing the topscores here, but this is truly some of the craziest list comprehension I've ever done with Python. The approach is quite straigthforward. ``` def r(p): z=[[[1+t[0]for t in i[0]if l==t[1]]for l in i[1]]for i in[[list(enumerate(w[0])),w[1]]for w in p]] return[list(set.intersection(set(e),*[set(i[z[0].index(e)])for i in z[1:]]))[0]for e in z[0]] ``` The function expects input always as a string 2-D array like: `[[word, abbr],...]` and returns a list of integers. Ps: A detailed explanation coming soon Ps2: Further golfing suggestions are welcomed! ]
[Question] [ You are provided a set of arbitary, unique, 2d, integer Cartesian coordinates: e.g. [(0,0), (0,1), (1,0)] Find the longest path possible from this set of coordinates, with the restriction that a coordinate can be "visited" only once. (And you don't "come back" to the coordinate you started at). **Important:** You cannot "pass over" a coordinate or around it. For instance, in the last note example (Rectangle), you cannot move from D to A **without** visiting C (which may be a revisit, invalidating the length thus found). This was pointed out by @FryAmTheEggman. **Function Input:** Array of 2d Cartesian Coordinates **Function Output:** Maximum length only **Winner:** ***Shortest*** code wins, no holds barred (Not the most space-time efficient) --- ***Examples*** [![Origin Triangle](https://i.stack.imgur.com/S3WPZ.jpg)](https://i.stack.imgur.com/S3WPZ.jpg) **1**: In this case shown above, the longest path with no coordinate "visited" twice is A -> B -> O (or O-B-A, or B-A-O), and the path length is sqrt(2) + 1 = 2.414 --- [![Square](https://i.stack.imgur.com/v3z2H.jpg)](https://i.stack.imgur.com/v3z2H.jpg) **2**: In this case shown above, the longest path with no coordinate "visited" twice is A-B-O-C (and obviously C-O-B-A, O-C-A-B etc.), and for the unit square shown, it calculates to sqrt(2) + sqrt(2) + 1 = 3.828. --- Note: Here's an additional test case which isn't as trivial as the two previous examples. This is a rectangle formed from 6 coordinates: [![enter image description here](https://i.stack.imgur.com/5vp8m.jpg)](https://i.stack.imgur.com/5vp8m.jpg) Here, the longest path is: A -> E -> C -> O -> D -> B, which is 8.7147 (max possible diagonals walked and no edges traversed) [Answer] # Pyth, ~~105~~ ~~103~~ ~~100~~ ~~92~~ 86 bytes ``` V.pQK0FktlNJ.a[@Nk@Nhk)FdlNI&!qdk&!qdhkq+.a[@Nk@Nd).a[@Nd@Nhk)J=K.n5B)=K+KJ)IgKZ=ZK))Z Z = 0 - value of longest path Q = eval(input()) V.pQ for N in permutations(Q): K0 K = 0 - value of current path FktlN for k in len(N) - 1: J.a set J = distance of [@Nk Q[k] and Q[k+1] @Nhk) FdlN for d in len(N): I& if d != k && d != (k + 1) !qdk &!qdhk q+ and if sum of .a distance Q[k] and Q[d] [@Nk @Nd) .a distance Q[d] and Q[k+1] [@Nd @Nhk) J are equal to J then =K.n5 set K to -Infinity B and break loop ( it means that we passed over point ) ) end of two if statements =K+KJ K+=J add distance to our length ) end of for IgKZ if K >= Z - if we found same or better path =ZK Z = K set it to out max variable )) end of two for statements Z output value of longest path ``` [Try it here!](http://pyth.herokuapp.com/?code=V.pQK0FktlNJ.a[%40Nk%40Nhk%29FdlNI%26!qdk%26!qdhkq%2B.a[%40Nk%40Nd%29.a[%40Nd%40Nhk%29J%3DK.n5B%29%3DK%2BKJ%29IgKZ%3DZK%29%29Z&input=[[0%2C0]%2C[0%2C-1]%2C[-1%2C0]%2C[-1%2C-1]%2C[-2%2C0]%2C[-2%2C-1]]&debug=0) [Answer] # Mathematica, 139 bytes ``` Max[Tr@BlockMap[If[1##&@@(Im[#/#2]&@@@Outer[#/Abs@#&[#-#2]&,l~Complement~#,#])==0,-∞,Abs[{1,-1}.#]]&,#,2,1]&/@Permutations[l=#+I#2&@@@#]]& ``` --- **Test case** ``` %[{{0,0},{0,1},{1,0},{1,1},{2,0},{2,1}}] (* 3 Sqrt[2]+2 Sqrt[5] *) %//N (* 8.71478 *) ``` [Answer] # Perl, ~~341~~ ~~322~~ 318 bytes ``` sub f{@g=map{$_<10?"0$_":$_}0..$#_;$"=',';@l=grep{"@g"eq join$",sort/../g}glob"{@g}"x(@i=@_);map{@c=/../g;$s=0;$v=1;for$k(1..$#c){$s+=$D=d($k-1,$k);$_!=$k&&$_!=$k-1&&$D==d($_,$k)+d($_,$k-1)and$v=0 for 0..$#c}$m=$s if$m<$s&&$v}@l;$m}sub d{@a=@{$i[$c[$_[0]]]};@b=@{$i[$c[$_[1]]]};sqrt(($a[0]-$b[0])**2+($a[1]-$b[1])**2)} ``` The code supports up to a 100 points. Since it produces all possible point permutations, 100 points would require at least 3.7×10134 yottabytes of memory (12 points would use 1.8Gb). Commented: ``` sub f { @g = map { $_<10 ? "0$_" : $_ } 0..$#_; # generate fixed-width path indices $" = ','; # set $LIST_SEPARATOR to comma for glob @l = grep { # only iterate paths with unique points "@g" eq join $", sort /../g # compare sorted indices with unique indices } glob "{@g}" x (@i=@_); # produce all permutations of path indices # and save @_ in @i for sub d map { @c = /../g; # unpack the path indices $s=0; # total path length $v=1; # validity flag for $k (1..$#c) { # iterate path $s += # sum path length $D = d( $k-1, $k ); # line distance $_!=$k && $_!=$k-1 # except for the current line, && $D == d( $_, $k ) # if the point is on the line, + d( $_, $k-1 ) and $v = 0 # then reset it's validity for 0 .. $#c # iterate path again to check all points } $m=$s if $m<$s && $v # update maximum path length } @l; $m # return the max } sub d { @a = @{ $i[$c[$_[0]]] }; # resolve the index $_[0] to the first coord @b = @{ $i[$c[$_[1]]] }; # idem for $_[1] sqrt( ($a[0] - $b[0])**2 + ($a[1] - $b[1])**2 ) } ``` TestCases: ``` print f( [0,1], [0,0], [1,0] ), $/; $m=0; # reset max for next call print f( [0,0], [0,1], [1,0], [1,1] ), $/; $m=0; print f( [0,0], [0,1], [0,2] ), $/; $m=0; print f( [0,0], [0,1], [0,2], [1,0], [1,1], [1,2]),$/; $m=0; ``` * *322 bytes:* save 19 by not resetting `$"`, and some inlining * *318 bytes:* save 4 by reducing max nr of coords to 100. ]
[Question] [ I really love sliding tile puzzles, but recently, I haven't had time for them. Hence, I need a program to give me my fix of sliding-tile puzzles, specifically Klotski puzzles. Your input will be in the following format: ``` ####### #001gg# ##.222# .###### ``` where `#` represents walls, `.` represents an open area, `g` represents the goal, and adjacent numbers represent different blocks. You can assume that: 1. There will be no more than 10 blocks 2. There won't be two blocks with the same number 3. All blocks will be enclosed by walls 4. The grid is rectangular 5. The `0` block is large enough to cover all of the goal squares. 6. There is a valid solution You need to return a sequence of moves that will put the `0` block so that it covers all of the goal squares. Blocks cannot pass through walls or other blocks. For the above puzzle, an appropriate sequence would be ``` 2L,1R,1R,1D,0R,0R,0R ``` while represents moving the `2` block 1 square left, the `1` block 2 squares right (on top of the goal) then 1 square down, and then `0` block 3 squares right. There are actually several sequences that will work for the above problem, and producing any of them is acceptable. Your solution should be optimal, meaning that it should produce a sequence that solves the puzzle in as few as steps as possible. The sequence should be printed out as above, but can be comma, newline, or space separated. I don't care if there are trailing commas or whitespace. You should produce the output in reasonable time (maximum 120 seconds on the puzzles below). Puzzle 1: ``` ..####.. ..#00#.. ###00### #......# #.1122.# ##3124## .#3344#. .##55##. ..#gg#.. ..####.. ``` Puzzle 2: ``` ###### #1002# #1002# #3445# #3675# #8gg9# ###### ``` Puzzle 3: ``` .####. ##1g## #22g3# #4255# #4.56# #.006# #7008# ###### ``` Puzzle 4: ``` .####. ##00## #.00g# #.0.1# #..g2# ###### ``` This is code-golf, so the shortest solution (in bytes) wins! [Answer] # Python, 1761 Kind of burnt out on this question, so couldn't bring myself to golf it. Either way, right now it's the only solution that solves everything within the time limit (longest, #3, takes 27 seconds). ``` pieces = {} taken = set() goals = set() y = 0 while True: try: for x, c in enumerate(input()): if c == ".": continue if c == "g": goals.add((x, y)) else: if c in "0123456789": if c not in pieces: pieces[c] = set() pieces[c].add((x, y)) taken.add((x, y)) y += 1 except: break def translate_comp(coords): o = min(sorted(coords)) return set((c[0] - o[0], c[1] - o[1]) for c in coords) similar = {} for piece in pieces: k = tuple(translate_comp(pieces[piece])) if k not in similar: similar[k] = [] similar[k].append(piece) seen = set() states = [(pieces, taken, ())] while states: state = states.pop(0) if not goals - state[0]["0"]: names = { (-1, 0): "L", (1, 0): "R", (0, 1): "D", (0, -1): "U", } print(len(state[2])) print(" ".join(piece + names[d] for d, piece in state[2])) break for piece in pieces: for d in ((-1, 0), (1, 0), (0, 1), (0, -1)): new_pieces = state[0].copy() new_pieces[piece] = {(c[0] + d[0], c[1] + d[1]) for c in state[0][piece]} new_taken = state[1] - state[0][piece] # Collision if new_pieces[piece] & new_taken: continue gist = tuple(frozenset().union(*(new_pieces[piece] for piece in similar_set)) for similar_set in similar.values()) if gist in seen: continue seen.add(gist) new_taken |= new_pieces[piece] states.append((new_pieces, new_taken, state[2] + ((d, piece),))) ``` [Answer] # JavaScript (ES6), 446 ~~388~~ Breadth First Search, so the first solution found is the shortest. While I still think that's a good solution, it's not good enough. Even after checking millions of position (runtime several minutes), I could not find a solution for example 2 and 3. **Edit** ES6 [modified version](https://jsfiddle.net/rj2psysL/15/) to overcome the javascript execution time limit. Puzzle 3 solved in 7min, 145 steps. Puzzle 2 solved in 10min, 116 steps **Edit 2** Big speedup, using @orlp's idea of considering equal any two blocks with the same shape (excluding block '0' that is special). This reduces the space of visited positions during BSF. For example, for puzzle 2, any position with block 1,2,3 or 5 exchanged is really the same. Timing: the longest is puzzle 3, ~20 sec on my laptop. Use Firefox to play with the new [JsFiddle](https://jsfiddle.net/rj2psysL/33/) to test. ``` F=g=>(o=>{ for(u=[i=s=''],v={},h=[],b={},k={'.':-1},l={}, g=[...g].map((c,p)=>c>'f'?(h.push(p),'.'):c<'0'?c: l[k[c]?k[c]+=','+(p-b[c]):k[b[c]=p,c]=~(c>0),k[c]]=c), b=Object.keys(b),b.map(c=>k[c]=l[k[c]]); h.some(p=>g[p]!='0');[s,g]=u[++i]) b.map(b=>[-1,1,o,-o].map((d,i)=> g.every((c,p)=>c!=b?1:(c=g[p+d])!=b&c!='.'?0:m[g[p-d]!=b?m[p]='.':1,p+d]=b,m=g.slice(0)) &&!v[q=m.map(c=>k[c]||'')+'']?v[q]=u.push([s+b+'LRUD'[i]+' ',m]):0)) })(o=~g.search(/\n/))||s ``` **Outdated** ~~EcmaScript 6 (FireFox) [JSFiddle](https://jsfiddle.net/rj2psysL/7/)~~ EcmaScript 5 (Chrome) [JSFiddle](https://jsfiddle.net/rj2psysL/9/) **Example** ``` ####### #001gg# ##.222# .###### T(ms) 10,Len7 1R 0R 1R 0R 2L 1D 0R ``` **Puzzle 1** ``` ..####.. ..#00#.. ###00### #......# #.1122.# ##3124## .#3344#. .##55##. ..#gg#.. ..####.. T(ms) 8030,Len70 1U 2U 3U 4U 5U 5L 4D 2R 1R 3U 5U 4L 4D 5R 5R 3D 1L 3D 1L 5L 5U 5U 2D 5R 1R 5R 1R 1D 0D 4D 1D 0D 0L 0L 1U 1U 1U 1U 2L 2L 2U 5D 2R 0R 3R 3R 0D 0D 2L 2L 2L 5U 0U 3U 3U 4U 4U 4R 0D 3L 3U 5D 5L 5L 5L 4U 4U 0R 0D 0D ``` **Puzzle 2** ``` ###### #1002# #1002# #3445# #3675# #8gg9# ###### T(ms) 646485, Checked 10566733, Len 116 8R 3D 4L 7U 9L 5D 7R 4R 3U 8L 9L 5L 7D 4R 6U 9U 8R 3D 6L 4L 2D 7D 2D 0R 1R 6U 6U 3U 3U 9L 8L 5L 7L 7U 2D 4R 5U 8R 8R 5D 1D 6R 3U 9U 5L 1D 1D 9R 9U 4L 4L 2U 8R 7D 2L 8U 7R 2D 4R 3D 6L 9U 4R 1U 1U 2L 8L 8D 4D 0D 9R 6R 3U 9R 6R 1U 5U 2U 8L 8L 7L 7L 4D 0D 6D 6R 1R 2U 2U 0L 6D 9D 6D 9D 1R 2R 3R 5U 5U 0L 9L 6U 4U 7R 8R 7R 8R 0D 9L 9L 6L 6L 4U 8U 8R 0R ``` **Puzzle 3** ``` .####. ##1g## #22g3# #4255# #4.56# #.006# #7008# ###### T(ms) 433049, Checked 7165203, Len 145 3L 3U 5U 6U 0U 7U 8L 8L 8L 0D 0R 7R 7U 7R 4D 2D 8R 4D 2D 5L 5L 3D 1R 3R 1D 1D 5R 5U 3L 6U 2U 4U 7R 1D 8L 0L 7D 1R 2R 4U 4U 8U 8U 0L 2D 3D 3L 6L 1U 7D 2R 0R 8D 4D 8D 4D 3L 3U 4U 4R 8U 8U 0L 7L 2D 1D 6R 4R 4U 1L 1L 1U 2U 2L 6D 6D 4R 1R 1U 2U 2L 6L 6U 4D 1R 6U 7U 7U 0R 8D 0R 2D 3D 8D 2D 3D 7L 6D 5D 5L 1L 1U 1L 6U 4U 7R 7R 6D 6L 4L 4U 7U 7U 0U 0U 2R 3D 2R 3R 3D 6D 5D 1D 1L 4L 7L 7U 0U 2U 3R 6D 5D 4D 7L 3R 6R 8R 5D 4D 7D 4L 7D 7D 0L 0U ``` **Puzzle 4** ``` .####. ##00## #.00g# #.0.1# #..g2# ###### T(ms) 25,Len6 1L 1D 1L 1L 0D 0R ``` ]
[Question] [ # Introduction Most of you are familiar with the [merge sort](http://en.wikipedia.org/wiki/Merge_sort) algorithm for sorting a list of numbers. As part of the algorithm, one writes a helper function called `merge` that combines two sorted lists into one sorted list. In Python-like pseudocode, the function usually looks something like this: ``` function merge(A, B): C = [] while A is not empty or B is not empty: if A is empty: C.append(B.pop()) else if B is empty or A[0] ≤ B[0]: C.append(A.pop()) else: C.append(B.pop()) return C ``` The idea is to keep popping the smaller of the first elements of `A` and `B` until both lists are empty, and collect the results into `C`. If `A` and `B` are both sorted, then so is `C`. Conversely, if `C` is a sorted list, and we split it into any two subsequences `A` and `B`, then `A` and `B` are also sorted and `merge(A, B) == C`. Interestingly, this does not necessarily hold if `C` is not sorted, which brings us to this challenge. # Input Your input is a permutation of the first `2*n` nonnegative integers `[0, 1, 2, ..., 2*n-1]` for some `n > 0`, given as a list `C`. # Output Your output shall be a truthy value if there exist two lists `A` and `B` of length `n` such that `C == merge(A, B)`, and a falsy value otherwise. Since the input contains no duplicates, you don't have to worry about how ties are broken in the `merge` function. # Rules and Bonuses You can write either a function or a full program. The lowest byte count wins, and standard loopholes are disallowed. Note that you are not required to compute the lists `A` and `B` in the "yes" instances. However, if you actually output the lists, you receive a **bonus of -20%**. To claim this bonus, you must output only one pair of lists, not all possibilities. To make this bonus easier to claim in strongly typed languages, it is allowed to output a pair of empty lists in the "no" instances. Brute forcing is not forbidden, but there is a **bonus of -10%** for computing all of the last four test cases in under 1 second total. # Test Cases Only one possible output is given in the "yes" instances. ``` [1,0] -> False [0,1] -> [0] [1] [3,2,1,0] -> False [0,3,2,1] -> False [0,1,2,3] -> [0,1] [2,3] [1,4,0,3,2,5] -> False [4,2,0,5,1,3] -> [4,2,0] [5,1,3] [3,4,1,2,5,0] -> [4,1,2] [3,5,0] [6,2,9,3,0,7,5,1,8,4] -> False [5,7,2,9,6,8,3,4,1,0] -> False [5,6,0,7,8,1,3,9,2,4] -> [6,0,8,1,3] [5,7,9,2,4] [5,3,7,0,2,9,1,6,4,8] -> [5,3,7,0,2] [9,1,6,4,8] [0,6,4,8,7,5,2,3,9,1] -> [8,7,5,2,3] [0,6,4,9,1] [9,6,10,15,12,13,1,3,8,19,0,16,5,7,17,2,4,11,18,14] -> False [14,8,12,0,5,4,16,9,17,7,11,1,2,10,18,19,13,15,6,3] -> False [4,11,5,6,9,14,17,1,3,15,10,12,7,8,0,18,19,2,13,16] -> [4,17,1,3,15,10,12,7,8,0] [11,5,6,9,14,18,19,2,13,16] [9,4,2,14,7,13,1,16,12,11,3,8,6,15,17,19,0,10,18,5] -> [9,4,2,16,12,11,3,8,6,15] [14,7,13,1,17,19,0,10,18,5] ``` [Answer] ## GolfScript (35 \* 0.9 = 31.5) ``` {.$-1>/~,)\.}do;]1,\{{1$+}+%}/)2/&, ``` The [online demo](http://golfscript.apphb.com/?c=IyMKO1tbMSAwXSAjIEZhbHNlClswIDFdICMgWzBdIFsxXQpbMyAyIDEgMF0gIyBGYWxzZQpbMCAzIDIgMV0gIyBGYWxzZQpbMCAxIDIgM10gIyBbMCAxXSBbMiAzXQpbMSA0IDAgMyAyIDVdICMgRmFsc2UKWzQgMiAwIDUgMSAzXSAjIFs0IDIgMF0gWzUgMSAzXQpbMyA0IDEgMiA1IDBdICMgWzQgMSAyXSBbMyA1IDBdCls2IDIgOSAzIDAgNyA1IDEgOCA0XSAjIEZhbHNlCls1IDcgMiA5IDYgOCAzIDQgMSAwXSAjIEZhbHNlCls1IDYgMCA3IDggMSAzIDkgMiA0XSAjIFs2IDAgOCAxIDNdIFs1IDcgOSAyIDRdCls1IDMgNyAwIDIgOSAxIDYgNCA4XSAjIFs1IDMgNyAwIDJdIFs5IDEgNiA0IDhdClswIDYgNCA4IDcgNSAyIDMgOSAxXSAjIFs4IDcgNSAyIDNdIFswIDYgNCA5IDFdCls5IDYgMTAgMTUgMTIgMTMgMSAzIDggMTkgMCAxNiA1IDcgMTcgMiA0IDExIDE4IDE0XSAjIEZhbHNlClsxNCA4IDEyIDAgNSA0IDE2IDkgMTcgNyAxMSAxIDIgMTAgMTggMTkgMTMgMTUgNiAzXSAjIEZhbHNlCls0IDExIDUgNiA5IDE0IDE3IDEgMyAxNSAxMCAxMiA3IDggMCAxOCAxOSAyIDEzIDE2XSAjIFs0IDE3IDEgMyAxNSAxMCAxMiA3IDggMF0gWzExIDUgNiA5IDE0IDE4IDE5IDIgMTMgMTZdCls5IDQgMiAxNCA3IDEzIDEgMTYgMTIgMTEgMyA4IDYgMTUgMTcgMTkgMCAxMCAxOCA1XSAjIFs5LDQsMiwxNiwxMiwxMSwzLDgsNiwxNV0gWzE0LDcsMTMsMSwxNywxOSwwLDEwLDE4LDVdCl17CiMjCgp7LiQtMT4vfiwpXC59ZG87XTEsXHt7MSQrfSslfS8pMi8mLAoKCiMjCnB9LwojIwo%3D) is quite slow: on my computer, it runs all of the tests in under 0.04 seconds, so I claim the 10% reduction. ### Explanation > > The suffix of C which starts with the largest number in C must come from the same list. Then this reasoning can be applied to (C - suffix), so that the problem reduces to subset sum. > > > [Answer] # Pyth, 39 \* 0.9 \* 0.8 = 28.08 ``` #aY->QxQeS-QsY&YsY)KfqylTlQmsdty_Y%tlKK ``` This program clams all two bonuses. It prints a pair of lists, if un-merging is possible, else an empty list, which is a falsy value in Pyth (and Python). ``` Input: [5,3,7,0,2,9,1,6,4,8] Output: ([9, 1, 6, 4, 8], [5, 3, 7, 0, 2]) Input: [5,7,2,9,6,8,3,4,1,0] Output: [] (falsy value) ``` You can test it [online](https://pyth.herokuapp.com/?code=%23aY-%3EQxQeS-QsY%26YsY)KfqylTlQmsdty_Y%25tlKK&input=%5B5%2C3%2C7%2C0%2C2%2C9%2C1%2C6%2C4%2C8%5D&debug=0), but it may be a bit slower than the offline version. The offline version solves each of the test cases in <0.15 seconds on my laptop. Probably (one of) the first time, a Pyth solution uses actively **Exceptions** (it saved at least 1 char). It uses the same idea as Peter Taylor's solution. ``` preinitialisations: Q = input(), Y = [] # ) while 1: (infinite loop) eS-QsY finds the biggest, not previous used, number xQ finds the index >Q all elements from ... to end - &YsY but remove all used elements aY append the resulting list to Y When all numbers are used, finding the biggest number fails, throws an exception and the while loop ends. This converts [5,3,7,0,2,9,1,6,4,8] to [[9, 1, 6, 4, 8], [7, 0, 2], [5, 3]] msdty_Y combine the lists each for every possible subset of Y (except the empty subset) fqylTlQ and filter them for lists T with 2*len(T) == len(Q) K and store them in K %tlKK print K[::len(K)-1] (prints first and last if K, else empty list) ``` # Pyth, 30 \* 0.9 = 27.0 I haven't really tried solving it without printing the resulting lists. But here's a quick solution based on the code above. ``` #aY->QxQeS-QsY&YsY)fqylsTlQtyY ``` I basically only removed the print statement. The output is quite ugly though. ``` Input: [0,1,2,3] Output: [[[3], [2]], [[3], [1]], [[2], [1]], [[3], [0]], [[2], [0]], [[1], [0]]] (truthy value) Input: [5,7,2,9,6,8,3,4,1,0] Output: [] (falsy value) ``` Try it [online](https://pyth.herokuapp.com/?code=%23aY-%3EQxQeS-QsY%26YsY)fqylsTlQtyY&input=%5B0%2C1%2C2%2C3%5D&debug=0). [Answer] # APL, 62 50 44 \* 90% = 39.6 ``` {(l÷2)⌷↑(⊢∨⌽)/(2-/(1,⍨⍵≥⌈\⍵)/⍳l+1),⊂l=⍳l←⍴⍵} ``` [Try it here.](http://tryapl.org/?a=%7B%28l%F72%29%u2337%u2191%28%u22A2%u2228%u233D%29/%282-/%281%2C%u2368%u2375%u2265%u2308%5C%u2375%29/%u2373l+1%29%2C%u2282l%3D%u2373l%u2190%u2374%u2375%7D9%204%202%2014%207%2013%201%2016%2012%2011%203%208%206%2015%2017%2019%200%2010%2018%205&run) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 103 bytes \* 0.9 \* 0.8 ``` f=(x,u,a=[],b=[],y=[...x],c=y.pop())=>b[0]<a[0]?0:1/c?f(y,~-u,[c,...a],b)||f(y,~u,[c,...b],a):u?0:[a,b] ``` [Try it online!](https://tio.run/##bVLNboJAEL7zFNxcmhF3BRFt0Zsv0OOGNisuxoaKVWlqYvrqdmYWrdpyIOz3Nz/Lm/k0u2K72uy763phT6cyE1/QgMl0DnN6HTIdhuFXDkV2CDf1RgRBNplrmT8ZfE3lWPWKaSkO8N1tQBeAYoPW4Hhk8IzNczDBuEG9NjDPT4/e1n40q60VnXLXCcKtNYvZqrLPh3UhJHSafZkyvKlMYUXvJXyY@r33Jbxmk6Je7@rKhlW9FKWwn6YSrwE@J61A5n534s9MtbOelqD4iI36WuWejqAPfzQM3tkQilorcZqOHsbH4PSDa32MgIQBuloPA@hyEJWNOXLQltZ8REHEkKcTJEcYLGHIOSnE1wUGCJMgQcJlyVs6YWdK5VDWb92a4NS1xRmOIkOEJ8mZCs0xpM5wIdDwS9FG@Iu763ONdrEXKPdbEVGepl4Vrg6HweVG3Bh2MsJslQD1omgkHEWBQuJmXEWllNtpTPoRqYespbuSbBlxLs0e3V4GyghFPiYflaY@JEXSks5211hyuZH/pPTfXMfdGGlMumokhm5I7JXmddMmnDVsp@aq7rc52@7FVOw36s7oeT8 "JavaScript (Node.js) – Try It Online") ~~# [JavaScript (Node.js)](https://nodejs.org), 105 bytes \* 0.9 \* 0.8 ``` f=(x,u=0,a=[],b=[],y=[...x],c=y.pop())=>b[0]<a[0]?0:1/c?f(y,u-1,[c,...a],b)||f(y,~u,[c,...b],a):u?0:[a,b] ``` [Try it online!](https://tio.run/##bVLNboJAEL7zFNxcmhF3BRFt0Zsv0OOGNitdGhsqVsVoYvrqdmYWrdpyIOz3Nz/Lh9mZTbFerLbdZf1mT6cyE3toMgkm0znM6XXIdBiG@xyK7BCu6pUIgmwy1zJ/MviayrHqFdNSHKDpKtAFoNigNTgeCfxuWmyegwnGDeq1gXl@evTW9qtZrK3olJtOEK6teZstKvt8WBZCQqfZlinDq8oUVvRewoep3/t8h9dsUtTLTV3ZsKrfRSnszlTiNcDnpBXI3O9O/JmpNtbTEhQfsVFfq9zTEfThj4bBOxtCUWslTtPRw/gYnH5wrY8RkDBAV@thAF0OorIxRw7a0pqPKIgY8nSC5AiDJQw5J4X4usAAYRIkSLgseUsn7EypHMr6rVsTnLq2OMNRZIjwJDlToTmG1BkuBBp@KdoIf3F3fa7RLvYC5X4rIsrT1KvC1eEwuNyIG8NORpitEqBeFI2EoyhQSNyMq6iUcjuNST8i9ZC1dFeSLSPOpdmj28tAGaHIx@Sj0tSHpEha0tnuGksuN/KflP6b67gbI41JV43E0A2JvdK8btqEs4bt1FzV/TZn272Yiv1G3Rk97wc "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 115 bytes \* 0.9 \* 0.8 ``` f=(x,u=0,a=[],b=[],y=[...x],c=y.pop())=>1/c?!(b[0]<c)&&f(y,u-1,[c,...a],b)||!(a[0]<c)&&f(y,~u,[c,...b],a):u?0:[a,b] ``` [Try it online!](https://tio.run/##bVJLb4JAEL7zK@ilLs2Iu4KIbdFb/0CPG2pWujQ2VKyKqUnTv25nZvHZciDs95rH8m62Zl2s5stNd1G/2v2@zMQXNJkEk@kcZvTaZToMw68cimwXLuulCIJsrHrF5EbMtMwfi@D2thQ7aLoKdAGoNegMvr9vhDnnf5qWnuVggvtmIu@1gVm@f/BW9rOZr6zolOtOEK6seX2aV/Z5tyiEhE6zKVOGl5UprOi9hHcTv/fxBtNsXNSLdV3ZsKrfRCns1lRiGuCz1wpk7nfH/pOp1tbTEhQfsSNfq9zTEfThj4bBKxtCUWslTtPRw/gYnH5wro8RkDBAV@thAF0OorIxRw7a0pqPKIgY8nSC5AiDJQw5J4X4vMAAYRIkSLgseUkn7EypHMr6rVsTnLq2OMNRZIjwJDlToTmG1BmOBBpOFG2Ev7i7PtdoF3uEcr8VEeVp6lXh6nAYXG7EjWEnI8xWCVAvikbCURQoJC7GVVRKuZ3GpB@ReshauivJlhHn0uzR5WWgjFDkY/JRaepDUiQt6WB3jSXHG/lPSv/NedyFkcakq0Zi6IbEXmleN23CWcN2aq7qfpuD7VpMxU5RV0bP@wU "JavaScript (Node.js) – Try It Online")~~ ]
[Question] [ Chris, a cryptic crosswords addict, has a set algorithm for the order in which he solves them. ![enter image description here](https://i.stack.imgur.com/YtkK7.jpg) We will use the above image as a guide. 1. Chris always starts off with the first across clue, in this case 1 Across. Chris is a capable crossword enthusiast, so it is assumed that he will always know the answer to the clue he is working on. 2. Once Chris completes a clue, he will check for all clues adjoining those he has completed (in the first case, 1 Down, 2 Down and 3 Down) and then complete the clue with the lowest number. If there are no adjoining clues, he would go to step 3. 3. If the clue is such that the next number (as described in Step 3) has both an across clue and a down clue, he will complete the across clue first (100% certainty, this borders on OCD!) 4. If there are no adjoining clues, he will go to the next available clue that's next in number (across or down) 5. Repeat from Step 2 until all clues are completed. And this is where it comes down to you, dear coders. You have been tasked to create code that can, on being provided with a crossword template, provide output describing the order of clues based on Chris's algorithm for solving it. The code will accept input of a crossword puzzle template, in the form of a `.` representing a white square and a `#` representing a black square. **Example**: ``` .....#......... .#.#.#.#.#.#.#. ...#...#....... .#.#.#.#.#.#.#. ....#.......... ##.#.#.#.#.#.#. ......#........ .###.#####.###. ........#...... .#.#.#.#.#.#.## ..........#.... .#.#.#.#.#.#.#. .......#...#... .#.#.#.#.#.#.#. .........#..... ``` **Input** can be through: a) a file read of the representation of the crossword, or b) by line input of each line of the crossword, followed by `\n`, with a second `\n` indicating EOF. And then it will determine the method by which Chris would solve it according to the above algorithm he has described. **Output** must be in the format of a series of comma separated instructions in the form of `n(A|D)`, where `n` is the clue number followed by `A` for across or `D` for down. So in the example above (both from the image, and the example template, which are the one and the same), the output would be: `1A,1D,2D,3D,9A,10A,4D,5D,6D,7D,8D,11A,12A,13A,15A,14D,15D,16A,17A,18D,19D,20A,21D,23A,22D,24A,25D,27A,28A,26D,29A,30A,31A` Shortest code wins... **Testing** You must provide with your submission the code, a byte count, as well as one of the four test cases represented in the `.` and `#` format, as well as the output generated from this input. There are four test cases, the three below as well as the above example template. Example test cases: Test Case 1 ``` .....# .#.#.# ...#.. .#.#.# .....# ##.#.. ``` Output: `1A,1D,2D,3D,4A,5A,6A,7A` Test Case 2 ``` .....#.. .#.##..# .#....#. ...##.#. .####... ......## ``` Output: `1A,1D,2D,5A,4D,4A,3D,3A,7A,8A,6D,9A` Test Case 3 ``` .........# #.#.#.#.#. ....#...#. #...#.#.#. ..###.#.#. .#....#... .#####...# .....###.. ``` Output: `1A,2D,3D,4D,5D,7A,8A,9A,10A,11A,11D,12A,13A,6D,14D,15A,16A,17A` Test Case 4 ``` .....#......... .#.#.#.#.#.#.#. ...#...#....... .#.#.#.#.#.#.#. ....#.......... ##.#.#.#.#.#.#. ......#........ .###.#####.###. ........#...... .#.#.#.#.#.#.## ..........#.... .#.#.#.#.#.#.#. .......#...#... .#.#.#.#.#.#.#. .........#..... ``` Output: `1A,1D,2D,3D,9A,10A,4D,4A,5D,6D,7D,8D,11A,12A,13A,15A,14D,15D,16A,17A,18D,19D,20A,21D,23A,22D,24A,25D,27A,28A,26D,29A,30A,31A` Good luck! [Answer] ### GolfScript, 154 characters ``` :^,,{.^=46<{;-1}*)}%[.^n?)/zip[0]*]{1,%{,1>},}%:H"AD"1/]zip{~`{1$0=H{{0=}/}%.&$?)\+[\]}+/}%(2/\{0=)[\~\]}$+[]{1${1=1$&},.!{;1$1<}*1<:F~~@|@F-\1$}do;;]','* ``` Input has to be provided on STDIN. The examples yield the following results (check [online](http://golfscript.apphb.com/?c=OyIuLi4uLiMuLi4uLi4uLi4KLiMuIy4jLiMuIy4jLiMuCi4uLiMuLi4jLi4uLi4uLgouIy4jLiMuIy4jLiMuIy4KLi4uLiMuLi4uLi4uLi4uCiMjLiMuIy4jLiMuIy4jLgouLi4uLi4jLi4uLi4uLi4KLiMjIy4jIyMjIy4jIyMuCi4uLi4uLi4uIy4uLi4uLgouIy4jLiMuIy4jLiMuIyMKLi4uLi4uLi4uLiMuLi4uCi4jLiMuIy4jLiMuIy4jLgouLi4uLi4uIy4uLiMuLi4KLiMuIy4jLiMuIy4jLiMuCi4uLi4uLi4uLiMuLi4uLiIKCgo6Xiwsey5ePTQ2PHs7LTF9Kil9JVsuXm4%2FKS96aXBbMF0qXXsxLCV7LDE%2BfSx9JTpIIkFEIjEvXXppcHt%2BYHsxJDA9SHt7MD19L30lLiYkPylcK1tcXX0rL30lKDIvXHswPSlbXH5cXX0kK1tdezEkezE9MSQmfSwuIXs7MSQxPH0qMTw6Rn5%2BQHxARi1cMSR9ZG87O10nLCcqCg%3D%3D&run=true)): ``` 1A,1D,2D,3D,4A,5A,6A,7A 1A,1D,2D,5A,4D,4A,3D,3A,7A,8A,6D,9A 1A,2D,3D,4D,5D,7A,8D,9A,10A,11A,11D,12A,13A,6D,14D,15A,16A,17A 1A,1D,2D,3D,9A,10A,4D,4A,5D,6D,7D,8D,11A,12A,13A,15A,14D,15D,16A,17A,18D,19D,20A,21D,23A,22D,24A,25D,27A,28A,26D,29A,30A,31A ``` [Answer] # Mathematica ~~806~~ 477 (There appears to be a glitch in the ordering of the solution steps. I am looking into this.) ## Golfed The function `q` finds the order of the crossword solutions. ``` i = Dimensions; v = MemberQ; u = Position; y = ToString; k = Select; q@t_ := (g@p_ := Characters@StringSplit[p, "\n"]; w = g@t; a[{r_, c_}, z_] := (c != i[z][[2]]) \[And] v[u[z, "."], {r, c + 1}] \[And] ((c == 1) \[Or] v[u[z, "#"], {r, c - 1}]); b@z_ := k[u[z, "."], a[#, z] &]; d[{r_, c_}, z_] := (r != i[z][[2]]) \[And] v[u[z, "."], {r + 1, c}] \[And] ((r == 1) \[Or] v[u[z, "#"], {r - 1, c}]); e@z_ := k[u[z, "."], d[#, z] &]; Cases[Flatten[{ If[v[b[w], #[[1]]], y[#[[2]]] <> "A"], If[v[e[w], #[[1]]], y[#[[2]]] <> "D"]} & /@ (MapIndexed[List, b[w] \[Union] e[w]] /. {{r_, c_}, {i_}} :> ({r, c} -> i))], Except[Null]]) ``` --- ## Ungolfed ``` q[t7_]:= Module[{d,acrossSquareQ,acrossSquares,downSquareQ,downSquares,m,numberedCells}, (*w=g[t7];*) g[p2_]:=Characters@StringSplit[p2,"\n"]; w=g[t7]; acrossSquareQ[{r_,c_},z_]:=(c!=Dimensions[z][[2]])\[And]MemberQ[Position[z,"."],{r,c+1}] \[And]((c==1)\[Or]MemberQ[Position[z,"#"],{r,c-1}]); acrossSquares[z_]:=Select[Position[z,"."],acrossSquareQ[#,z]&]; downSquareQ[{r_,c_},z_]:=(r!=Dimensions[z][[2]])\[And]MemberQ[Position[z,"."],{r+1,c}] \[And]((r==1)\[Or]MemberQ[Position[z,"#"],{r-1,c}]); downSquares[z_]:=Select[Position[z,"."],downSquareQ[#,z]&]; numberedCells[z_]:=acrossSquares[z]\[Union]downSquares[z]; m=MapIndexed[List,numberedCells[w]]/.{{r_?IntegerQ,c_?IntegerQ},{i_?IntegerQ}}:> ({r,c}-> i); Cases[Flatten[{ If[MemberQ[acrossSquares[w],#[[1]]],ToString[#[[2]]]<>"A"], If[MemberQ[downSquares[w],#[[1]]],ToString[#[[2]]]<>"D"]}&/@m],Except[Null]]] ``` --- `board` displays the crossword puzzle. The code is not included in the character count. Several sub functions from `q` are borrowed here. ``` board[p_]:= Module[{q,g,w,downSquareQ,downSquares,acrossSquareQ,acrossSquares,numberedCells,m}, downSquareQ[{r_,c_},z_]:=(r!=Dimensions[z][[2]])\[And]MemberQ[Position[z,"."],{r+1,c}] \[And]((r==1)\[Or]MemberQ[Position[z,"#"],{r-1,c}]); downSquares[z_]:=Select[Position[z,"."],downSquareQ[#,z]&]; acrossSquareQ[{r_,c_},z_]:=(c!=Dimensions[z][[2]])\[And]MemberQ[Position[z,"."],{r,c+1}] \[And]((c==1)\[Or]MemberQ[Position[z,"#"],{r,c-1}]); acrossSquares[z_]:=Select[Position[z,"."],acrossSquareQ[#,z]&]; numberedCells[z_]:=acrossSquares[z]\[Union]downSquares[z]; g[p2_]:=Characters@StringSplit[p2,"\n"]; w=g[p]; m=MapIndexed[List,numberedCells[w]]/.{{r_?IntegerQ,c_?IntegerQ},{i_?IntegerQ}}:> ({r,c}-> i); Grid[ReplacePart[w,m],Dividers->All,Background->{None,None,(#-> Black)&/@Position[w,"#"]}]] ``` --- ## TestCases **1** ``` t1=".....# .#.#.# ...#.. .#.#.# .....# ##.#.."; board[t1] q[t1] ``` ![t1](https://i.stack.imgur.com/E4G2s.png) > > {"1A", "1D", "2D", "3D", "4A", "5A", "6A", "7A"} > > > --- **2** ``` t2=".....#.. .#.##..# .#....#. ...##.#. .####... ......##"; board[t2] q[t2] ``` ![t2](https://i.stack.imgur.com/l5q80.png) > > {"1A", "1D", "2D", "3A", "3D", "4A", "4D", "5A", "6D", "7A", "8A", > "9A"} > > > --- **3** ``` t3=".........# #.#.#.#.#. ....#...#. #...#.#.#. ..###.#.#. .#....#... .#####...# .....###.."; board[t3] q[t3] ``` ![t3](https://i.stack.imgur.com/XS9mH.png) > > {"1A", "2D", "3D", "4D", "5D", "6D", "7A", "8D", "9A", "10A", "11A", "11D", "12A", "13A", "14D", "15A", "16A", "17A"} > > > --- **4** ``` t4=".....#......... .#.#.#.#.#.#.#. ...#...#....... .#.#.#.#.#.#.#. ....#.......... ##.#.#.#.#.#.#. ......#........ .###.#####.###. ........#...... .#.#.#.#.#.#.## ..........#.... .#.#.#.#.#.#.#. .......#...#... .#.#.#.#.#.#.#. .........#....."; board[t4] q[t4] ``` ![t4](https://i.stack.imgur.com/8Gw2w.png) > > {"1A", "1D", "2D", "3D", "4A", "4D", "5D", "6D", "7D", "8D", "9A", > "10A", "11A", "12A", "13A", "14D", "15A", "15D", "16A", "17A", "18D", > "19D", "20A", "21D", "22D", "23A", "24A", "25D", "26D", "27A", "28A", > "29A", "30A", "31A"} > > > ]
[Question] [ Given a board, write the shortest program or function to display or return which characters are in sight of the player. A character is in sight if is possible to draw a line between it and the player, without crossing any characters that block vision. Input: * `@` represents the player's position. There will only be one of these in the input. * any character that matches the regex `[#A-Z]` blocks vision. * any character that matches `[ a-z]` allows vision. * there will be no invalid characters * you are guaranteed a rectangular input Lines are defined as follows: * define vector to be a magnitude and a direction * a direction is one of N,NE,E,SE,S,SW,W,NW * a magnitude is how many chars along that direction to count * let the initial vector be called d1; the second vector be called d2 * one of d1 or d2 must have a magnitude of `1`; the other may have whatever magnitude * d1's direction must be adjacent to d2's direction (e.g: N and NE) A line is defined to be all chars along the path marked by applying d1, then d2, d1, d2 .... Sample line (given by the `.`s): d1 = (magnitude: 4, direction: E) d2 = (magnitude: 1, direction NE) ``` ..... ..... ..... @.... ``` Output: * each visible character in the right position, `.` substitutes for space. * Space for each non-visible character. Sample input: ``` @ K J L o ``` Corresponding output: ``` @......... ....K..... .J..... .......... .. .L..... .. . .... ... .. ... ... .. .. ... . . .... .. ``` Sample Input: ``` B###M# by #Q # Zmpq # # aaa @ m # # ##P# # #### # #### #M ### ###### ``` Corresponding Output: ``` .B #M .# .. Z pq .#.#.aaa.. @..m.# #.##P# .# .# M. # ``` Sample input: ``` w O l gg rT QQL Ag #b qqqqq XqQ x V# f@aa Y aaa uU E l TaKK e dd FF d opi e d ``` Corresponding output: ``` .......... ..... ......... ..... O..l...gg..rT ...QQL......Ag..#b.. ...qqqqq.........XqQ #.f@aa...... Y........aaa..... ...uU..E..l.TaKK.... d..FF.d.op .... .d. ... ``` [Answer] ### GolfScript, 171 characters ``` .n?):L)[n*.]*1/:I'@'?{\+[{1$+}*]..{I=26,{65+}%"# "+\?)}??)<}+{[L~.).)1L)L.(-1L~]>2<`{[.[~\]]{1/~2$*+L*.-1%}%\;~}+L,%~}8,%%{|}*`{1$?)I@=.n=@|\.' '={;'.'}*' 'if}+I,,%''*n%n* ``` The input must be provided on STDIN. The output for the examples given above is slightly different. I verified the responses by hand and think they are correct. *Example 1:* ``` @......... ....K..... .J..... .......... .. .L..... .. . .... ... .. ... ... .. .. ... . . .... .. ``` *Example 2:* ``` .B #M .# .. Z pq .#.#.aaa.. @..m.# #.##P# .# .# M. # ``` *Example 3:* ``` .......... ..... ......... ..... O..l...gg..rT ...QQL......Ag..#b.. ...qqqqq.........XqQ #.f@aa...... Y........aaa..... ...uU..E..l.TaKK.... d..FF.d.op .... .d. ... ``` [Answer] ## Ruby - 510 chars Quite a mammoth; but it is my first ever attempt at a golf. ``` m=$<.read;w,s,o,p=m.index(?\n)+1,m.size,m.dup.gsub(/[^@\n]/,' '),m.index(?@);d=[-w,1-w,1,w+1,w,w-1,-1,-1-w];0.upto(7){|i|x=d[i];[i-1,i+1].each{|j|y=d[j%8];[1,nil].each{|l|t=0;catch(:a){loop{c,f,r=p,1,nil;catch(:b){loop{(l||r)&&(1.upto(t){|u|c+=x;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)};f=nil);r=1;c+=y;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)}};t+=1}}}}};$><<o ``` Input is by file specified as argument; I assume the input file to consist of a rectangular block of characters (so, trailing spaces included), and to have a trailing newline. This version makes extensive use of `catch-throw` to exit deep loops; I can possibly improve matters with bounds-checked loops instead. Unobfuscated code: ``` # Read the map in map = $<.read # Determine its width and size width = map.index("\n")+1 size = map.size # Create a blank copy of the map to fill in with visible stuff output = map.dup.gsub /[^@\n]/,' ' # Locate the player player = map.index('@') dirs = [ -width, # N 1-width, # NE 1, # E width+1, # SE width, # S width-1, # SW -1, # W -1-width # NW ] 0.upto(7) do |i1| d1 = dirs[i1] [i1-1, i1+1].each do |i2| d2 = dirs[i2%8] # Stepping by 0,1,2... in d1, work along the line. # Write the cell value into the duplicate map, then break if it's # a "solid" character. # # Extensive use of catch-throw lets us exit deep loops. # For convenience of notation, instead of having either d1 or d2 # be magnitude 1, and always doing d1,d2,d1... - I have d2 always # being magnitude 1, and doing either d1,d2,d1 or d2,d1,d2... # Loop twice - first with d1,d2,d1... second with d2,d1,d2... [true,false].each do |long_first| step = 0 catch(:all_done) do # This loop increments step each iteration, being the magnitude of d1 loop do cell = player first = true # True until we've done the first d1 later = false # True once we've done the first d2 catch(:done) do # This loop repeatedly applies d1 and d2 loop do if long_first || later # Don't apply d1 first if starting with d2 1.upto(step) do |dd1| cell += d1 # Move one cell in d1 invalid = !(0...size).include?(cell) || map[cell]=="\n" # Out of range throw :all_done if first && invalid # No point trying a longer step if the # first application of d1 is out of range throw :done if invalid # No point continuing with this step length output[cell]=map[cell] == " " ? '.' : map[cell] # Transfer visble character wall = map[cell]=~/[#A-Z]/ # Hit a wall? throw :all_done if first && wall # Drop out as before throw :done if wall end first = false end later=true # Now repeat above for the single d2 step cell += d2 invalid = !(0...size).include?(cell) || map[cell]=="\n" throw :all_done if first && invalid throw :done if invalid output[cell]=map[cell] == " " ? '.' : map[cell] wall = map[cell]=~/[#A-Z]/ throw :all_done if first && wall throw :done if wall end end step += 1 end end end end end puts output ``` ## Edit Ilmari Karonen notes in the question comments that the given vision algorithm doesn't see all squares, even when there's no obstacle. Here's a demonstration of that, out to (40,40) away from the player. ``` @....................................... ........................................ ........................................ ........................................ ........................................ ............ ........................... .............. ........................ ............ ... ..... ............... .............. ... ..... ........... ............... ... ..... ....... ................. ... ..... ... .................. ... ..... ..... . ............ ... ..... ..................... ... ... ...... . .............. ... ...... .. .............. ... ....... . ................ ... ....... .. ............. .. ... ....... . ................. ... ........ .. ............... .. ... ........ . ............... ... . ........ .. ................ .. ......... . ................. ... ......... .. ................. .. ....... . . . ................ ... .......... .. ................... .. .......... . ................... .. ........ . .. . .................. ........ .. . .. .................. ........... .. ..................... ......... . . . .................. ......... .. .. .. ................. ......... .. . .. ................ .......... . .. . ................ .......... .. . .. ............... .......... .. .. .. .............. .......... . . . ............. ........... .. .. .. ............. ........... .. . .. ............ ........... . .. . ........... ``` ]
[Question] [ I like my job, but sometimes it can get a bit tedious and boring. As motivation, I want to know how many hours of work are left before I finally get my two days of weekend and relaxation. * I work **every day** from Monday to Friday, totalling **38.5 hours**, starting at **9am** and ending at **6pm**. * Every day - except Friday - I get a lunch break from **1:00pm** to **1:30pm**. On Fridays I do not get a lunch break, but get off at **1:30pm** instead. Note that these lunch breaks do not add to work time. * If I check the time during the weekend (Friday after 1:30pm, Saturday or Sunday), I don't want to know about next week yet - it should tell me that **zero** hours are remaining instead. --- Given an input date, calculate the number of work hours remaining until the weekend is here (on Friday at 1:30pm). You can assume that the input hours will range from **0** to **23**, and the minutes will only ever be **0** or **30**, which means that you will not have to calculate fractions other than **.5**. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer, in bytes, wins. * As usual, standard loopholes are forbidden. * **Input** may be received in any reasonable *datetime format*. Timestamps, date strings, date objects, et cetera are all allowed. You can also directly take the input as the day of the week (indexed with Sunday as 0), the hours and the minutes. * **Output** may be written directly to `stdout` or returned as a string or numeric. Printing with trailing newlines is allowed. ## Test Cases ``` Fri May 21 2021 09:00:00 -> 4.5 Sun Jul 25 2021 16:00:00 -> 0 Mon Aug 23 2021 04:00:00 -> 38.5 Sat Nov 06 2021 08:00:00 -> 0 Thu Oct 14 2021 10:30:00 -> 11.5 Tue Dec 07 2021 14:30:00 -> 25 Fri Jan 21 2022 00:00:00 -> 4.5 ``` Formatted as full date strings for convencience - you do not need to use *this* format, check the input rules. [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` d,h,m=input() t=0 while((h,m)<(13,1))+4>d%7:t+=8<h<18>13!=h*-~m*(d!=4);h+=m>0;m=30-m;d+=h/24;h%=24 print.5*t ``` [Try it online!](https://tio.run/##JY9BbsMgEEX3nGKiKDLYJAFDUjc2PkUvUAUkkAK2bFCbTa/uQrKYefP/fGk08zPaKbTbHhi4FfwU9PeTAi8iJrO@lIl3tIdWgp3SAtF5g0r@DIKBdyFFsyL0Y93DwNeSzA3Mr7lDVVWbppZ65cKcIiYoKvaOYZxtMmAuKCekkaM@fNxio7rBDrwbudgpWx//fI31TknS20b5kfVeCXb0vW6UPbeytwfVSjQvLsTTpY5bOSgpfFJg6Jp/uJaBUZCFFwpdIc@Ll1FaochGLsH@AQ "Python 2 – Try It Online") -2 bytes thanks to EliteDaMyth -5 bytes thanks to Arnauld -5 bytes thanks to ovs Monday = 0, Sunday = 6 [Answer] # JavaScript (ES6), ~~84 79 78~~ 73 bytes *Saved 1 byte thanks to @l4m2* Expects `(d,h,m)` where `d` is the day of the week as described in the challenge. ``` (d,h,m)=>d%6?(g=k=>k--?g(k)-(k/18&(d-5?k!=26:k<27)):94-17*d)(h*2+!!m)/2:0 ``` [Try it online!](https://tio.run/##dZBda4MwFIbv9yuOFxuJMzWJ8ZNZGYxdFLpdrH9A1GoXa0arhf16F9uAbExIchOe9znn/cwv@bk4Hb560qmyGvfpiEqncY44XZf3QYbqVKZrSUhWI4kJki6LHlBJ/ExaKQ8S@cRDjJNYEBbaJUaNzR8t64hdntDRteH1dIBt/g2cAaf6oXFCqT5gu1Co7qzaatWqGu2R7wDE@lKMwXVBrPw7zX8MHWyGFrh/41mwxFNHf848neit6uB5qIF7xi6WaKZJMdNeZPR5D2/qAjQwAdFSwKSO/uh3zQDvRQ9MmOFp4v1PazXTC3iGZuym3w0VvFQF0NAELM7PdYCYA/gVn8rf5J0pn8OVXSyf/ip//AE "JavaScript (Node.js) – Try It Online") ### Commented ``` (d, h, m) => // d = day of week, h = hours, m = minutes d % 6 ? // if this is not the week-end: ( g = k => // g is a recursive function that iterates over // the whole day with a 30 minutes granularity k-- ? // decrement k; if it was not 0: g(k) - // do a recursive call and decrement the final ( // result if: k / 18 & // it's between 9 AM and 5.30 PM // (i.e. floor(k / 18) = 1) ( // and: d - 5 ? // if this is not Friday: k != 26 // it's not 1 PM : // else: k < 27 // it's less than 1.30 PM ) // ) // : // else (end of recursion): 94 - 17 * d // add 38.5 hours minus 8.5 hours per full day, // which gives 77 - 17 * (d - 1) in half hours )(h * 2 + !!m) // initial call with h and m converted to half hours / 2 // half the result : // else: 0 // just return 0 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~53~~ ~~52~~ ~~49~~ 47 bytes ``` I⊘Σ✂”~∨‽lC⎚À›t⟧κⅉ←eδQ﹪GÀ*¡_∧⌊⮌θμ⟧>”⁺×⁴⁸⊖N⁺⊗N¬¬N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyMxpyw1RSO4NFcjOCczOVVDyQADGEIBnGFogBcMVvUElFEFKOkoBOSUFmuEZOamFmuYWOgouKQmF6XmpuaVAIPZM6@gtMSvNDcptUhDUxOq1CW/NCkHi6RffokGCKOKw4D1//8mXIYGXMYG/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: I couldn't find a better way of expressing the working hours than a giant compressed lookup table (especially now I've golfed 10% off). ``` ”...” Compressed lookup table of half hours ✂ Sliced starting at position N Input day of week ⊖ Decremented ×⁴⁸ Multiplied by 48 (half hours in day) ⁺ Plus N Input hour of day ⊗ Doubled (convert to half hours) ⁺ Plus N Input minute of day ¬¬ Is not zero Σ Count half hours left to work ⊘ Divide by 2 (convert to hours) I Cast to string Implicitly print ``` Edit: Saved 1 byte by using `Sum()` instead of `Count(..., "1")`, allowing me to save a further 3 bytes by using `Sum(Slice(...))` instead of `Minus(77, Sum(CycleChop(...)))`, allowing me to save a further 2 bytes by removing the now unnecessary `Modulo(..., 7)`. [Answer] # [J](http://jsoftware.com/), 59 56 bytes ``` 1-:@#.,@(30|."1(|:48{.0(8})18 4$1),9$1)}.~30%~7 24 60&#. ``` [Try it online!](https://tio.run/##Vc3BCoJAEMbxe0/xoZUurMOMu27rgiAEnTr1CpFElx4g9dU3SS06zHf48Yd5xISyDk1ABg1GmK4gHC/nU5QitCnpNjfcUyJ5H6x/Eed@UOJht6J0Pc1Ao@HdeEBp4XifUlSb2/X@hKUKDTpY1OCZ@AMO4lYxfql46v6qCn4FkSUyEIZZtJxNIPZrv58Mjm8 "J – Try It Online") Takes input as `day hour minute`. ## the idea * View the entire week as series of 30 minute chunks, where `1` represents work time and `0` represents free time. The five relevant week days look like: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` * Find how many 30 minute chunks away from Sunday midnight the input is. * Delete that many elements. * Sum the remaining ones, and divide by 2. ## J details * `30%~7 24 60&#.` Converts to the input to minutes, then divides by 30. * `,@(30|."1(|:48{.0(8})18 4$1),9$1)` Returns the grid above, but flattened. * `1-:@#.` Sum and divide by 2. [Answer] # [Perl 5](https://www.perl.org/), 84 bytes ``` sub f{$_=pop;$_>51300||$_<1e4?0:(/(09|1[0-7])..$/-/[1-4]1300/)*.5+f($_+30+40*/3.$/)} ``` [Try it online!](https://tio.run/##dZJPb5tAEMXv/hRPhANgbGZhcfynNKlU9ZAq8aG@uRaiDsSoGBCBqFacz@7OAlXIoSuEhtnfvB3mbRlXmX@5PDe/kLzqYVAW5UoPP/vCIzqf9fCTiOUNLQ3HoMVZbGlyvTOnU92ZOFsxkTuFOaY19ceJoYdjj8aSLMdjwHy7HE@4rePnOjBwhe1jdLIE8cIYh6Kp1AeHxzRv6thG/KeM93X8uBuB19anBZENOfV3Nld/q1LcRye4Ai7xixZLIn46GGKmYGIUDP9octw1GVy/g8VsCAuSCvbmSvoK90WOL80TXK9XlkN4RvMPylGNh@IFNOvh@RCWgjyGheiUN4cG630NIfs2aOm9w66QCnbV/7HyponxNd6DrntYDmFfze3jNO6ivJ@Gi7aHd1iZwj3/BxZeB/OphyhLwFvKDmRxUtvIC2RNvj8gqVJ2bGSuRklRGa2P5mt7wPFk6Gle2jpbZga3erjq09CfijpI2l2zS5ZVmtddPlA8bqAVvzUsoVmW9bDeYP1dG6IaR1wOpcHhv1uBthhgoVbtZ85Vb5e/ "Perl 5 – Try It Online") The function takes one numeric argument: `day*10000 + hour*100 + minute` where Monday is 1, Tuesday is 2, ... and Sunday is 0 (if Sunday=7 is allowed 8 bytes can be saved). Example input: 51300 = Friday 13:00. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 95 bytes ``` f=d=>(h=d.getHours(),d+0)[0]!='S'&&(h>8&h<13+5*(d+0>'G')^/13:0/.test(d))/2+f(new Date(+d+18e5)) ``` [Try it online!](https://tio.run/##TY5tS8MwFIW/71dcQdbEdm3Sl1mnKQhjymD6YfsmTrI2fZHazjaZbH@@trPSwSUX8pxz7vnkB16HVbaXk6KMRNPELGIBSllkJkI@l6qqETYineA38n7FtLU2HqM08MfpA3V07wa1KNCeNLy1qDMjlilFLVGEsWXrMSrED8y5FEiPdOoLD@OmEt8qqwTS4lrDZiV4tMhysT4WISKGpmTsn7/3OQ8FsrbI1DFMAuj2tfWVGOjD4MYOsyAsi7rMhZmXCTqxi1scY2NnnBjbYXzfLKoMVvwINgWbtA@5mxHSThfqmt5orQpYqhxs74/T6cDJaFUW8KgSsJ3e7Q7U8Ts7l/BSHoBMe4F/ad@kCl5DCdTtw8nM@aeUtvaNEjAXIZDbXuAOAtsbdeWXvOjL23COHsr/Ag "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 75 bytes from Arnauld's ``` (d,h,m)=>d%6&&(g=k=>k--?g(k)-(k>17&k<(d-5?36:26)^k==26):94-17*d)(h*2+!!m)/2 ``` [Try it online!](https://tio.run/##dZBba4MwGIbv9yu@XkwSpzWJ8chiGYxdFLpdrNcDUatdrBmtFvbrXdoGZGNCDhfheZ8v72d@zk/Fcf/Vu50qq3EnRlQ6jXPAIivvQ8tCtZAik667qpHELpIZjSz5iEo3WPlhykL8IYXQV5pwl0Z2iVFjs4fF4oA9Nno2vBz3sMm/gVFgRB8kSQnRC2wPCtWdVFstW1WjHQocgERvgjF4HvBlcKf596GD9dACC248Ded44ujHiScXeqM6eBpqYL6x8zmaapJPtB8bfd7DqzoDCU1APBdwUcd/9NtmgLeiB8rN8CT1/6e1muoP@Iam9KbfDhU8VwWQyATMzs90AJ8C2BW/lL/OO1M@gys7Wz75Vf74Aw "JavaScript (Node.js) – Try It Online") ]
[Question] [ Robber Thread [here](https://codegolf.stackexchange.com/q/217598/45613) ## The Challenge Choose any numeric\* formula, algorithm, or code challenge. Implement it in such a way that the math is correct, but at least one answer is *wildly*\*\* wrong due to some defect in how computers/programs operate, e.g. floating point errors, uninitialized/corrupted memory, environment bugs, compiler optimization bugs, library bugs, weird language features, etc... The domain and range (i.e. inputs and outputs) of your formula must be well-defined. ## Requirements Your challenge must include the following: * The formula / algorithm / code challenge * The source code of your program / function * A well-defined specification of the domain and range of the program * A precise description of *how wrong* a particular answer is: + Whether it is incorrect deterministically or not- and how often it is incorrect + A numeric description of how wrong the returned answer is relative to the expected answer. This could be: - in absolute terms (e.g. off by at least 1 million) - an order of magnitude (e.g. 1000x larger or smaller) - relative to the inputs (e.g. off by more than half the value of the larger of two inputs) - some other reasonable measure of error (e.g. correct except for the sign, vector components transposed, rotated by 90 degrees on the complex plane, etc...) + A vague estimation of how many outputs of all possible inputs are affected by the error. + (if the output is a list, tuple, or matrix) The number of elements affected by the error. * An environment setup (OS, libraries, language version, runtime, compiler and relevant flags, etc...) which reproduces the error. + Include a link to the specific version used for compilers, runtimes, languages, and libraries. + You may link to a Docker image or Dockerfile of your environment. Although this is not required, it would be very kind to do so if the environment that causes the numerical error is very specific. + Try to keep the set of libraries in use small. The robbers will be trying to find an incorrect answer and explanation why it fails. Your formula implementation will be considered "safe" after 7 days. ## Example ### Cop Challenge * Formula: The Pythagorean Theorem, \$ a^2 + b^2 = c^2 \$ * Inputs: 2 nonnegative real numbers * Off by more than either input number * Affects most inputs * WSL (Ubuntu 18.04) on Windows 10, [Python 3.6.9](https://www.python.org/downloads/release/python-369/) ``` def badpythag(a, b): a2 = (a / 1e200) ** 2 b2 = (b / 1e200) ** 2 return math.sqrt(a2 + b2) * 1e200 ``` ### Cracked Answer This will fail on many inputs (e.g. 3, 4 => 0, but should be 5) due to floating point underflow and return 0. The answer is correct with very large inputs e.g. 3e150 and 4e150, however. ## Rules and Scoring * Score 1 point if your challenge remains uncracked after 7 days. * You can submit multiple challenges to the cops thread. * Incorrect answers do not need to be deterministically wrong as long as they are wrong more than half of the time (a broken clock is right twice a day). * Abusing undefined behavior is fair game. * The error should not be hardware dependent. Not everyone has a Raspberry Pi, let alone some obscure model of the x86 with a specific floating point bug. * GPU code is not allowed. There is too much variance in drivers and graphics cards for this to be a reasonable point of exploitation. * Caveats on libraries: + Errors caused by libraries must be the result of a known and documented flaw. The flaw must have been documented no later than a month before the posting of your cop challenge. + You can use old versions of libraries as long as they are publicly available from a reasonably trustworthy source at the time your challenge is posted. + Libraries you use must be free for noncommercial personal use and publicly available. + Libraries do not need to be open source. * You can use old language versions (and compilers) as long as they are publicly available from a reasonably trustworthy source at the time the challenge is posted. * You may exploit compiler and runtime bugs. --- \* By numeric challenge, I mean anything with a domain and range which consists entirely of numbers, tuples/lists of numbers, lists of lists of numbers, vectors, matrices, etc... Complex numbers are fair game. Numbers may use any representation. \*\* What is considered *wildly* wrong depends a lot on the scale of the domain and range of the formula/algorithm. What would be wildly wrong for particle physics is a rounding error for walking around the block, while a rounding error for galaxies might be off by a planet or two when trying to find someone's apartment. Yes, this is inherently subjective, but this is why your challenge *must* define a specific numeric definition of exactly what you consider *wrong enough* to count. As a general rule of thumb, to be considered "wildly" wrong, answers should be off by at least an order of magnitude (preferably more), be zero at the wrong time, have the wrong sign, or something else equally nefarious. It should generally be the kind of error that might lead to someone's death if it were to be integrated into medical software rather than something that causes the patient to wake up a little early, while the surgeon is tying up the last few stitches. [Answer] # Python 3 + sympy, [cracked](https://codegolf.stackexchange.com/a/217608/48931) by [water\_ghosts](https://codegolf.stackexchange.com/users/94694/water-ghosts) This is a primality checking function. It returns `True` for primes, and `False` for non-primes. ``` from sympy.ntheory.primetest import mr from sympy.ntheory.generate import primerange def is_prime(n: int) -> bool: if n < 2: return False return mr(n, primerange(2, 800)) ``` Find a composite number that is falsely declared as prime. There are infinitely many solutions. You can try it online [here](https://tio.run/##bY3BCoMwEETP5iv2mIAVsRSK1B77G8XSVQNmEzbrIV@fqrSlhx7n8WYmJJk8HXMe2DuIyYVUkUzoOVWBrUPBKGBd8CzgWP3RRiTkXvBj7TXuaUSlnjiAjfcdaWrBkhg4XOHh/dyqwg5AcIGmBUZZmODWzxFV8U6ONZU/e7op4VzXxihF0G1j2lJYRK9ktbb4/TIm59ML). As far as I know, the solution works for any modern version of Python/sympy, no specific environmental setup is required. [Answer] # [JavaScript (Node.js)](https://nodejs.org), [Cracked](https://codegolf.stackexchange.com/a/217655) by [EasyasPi](https://codegolf.stackexchange.com/users/94093/easyaspi) ``` function max(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw TypeError("This function only accept numbers"); } if (a === b) { return a; } else if (a > b) { return a; } else if (a < b) { return b; } else { return Math.max(a, b); } } function max_ref(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw TypeError("This function only accept numbers"); } return Math.max(a, b); } const [a, b] = require('fs').readFileSync(0).toString().split('\n').map(Number); console.log(max(a, b)); console.log(max_ref(a, b)); ``` [Try it online!](https://tio.run/##xZAxT8MwEIX3/IqjS2wJIiTEVMIGGyztBghd3Etj5Njh7AAR7W8PbhNKqwqJjfXe9947vRd8Q69YN@HMugX1fdlaFbSzUOOHwFMoJHwmALoEEbqGXAkIJ3kOqW3rgjiF1QpGoTgQBh9AqNi9wzwiN8yOxWReaQ@7GmdNB6gUNQEGp5/IaXSux1aEPKYW33FMoWULuEWAjKeRuv4Dc3XEFHvMgXCHocp2GwwPrZNkf55npvLfJ/rl3fiqctYHeNgcniCP4GurmURa@lRmTLi41YZmnVXiXGbBzQJruxQy843RQaSPNmI1NuJ@WxkzN4HOUGbcUuyqju8/s8hp318kl18 "JavaScript (Node.js) – Try It Online") For a certain inputs: The program exit normally (without exceptions), and the two lines outputted by above program are different. I know this could be very simple. But I just cannot get a more complex one under this question... [Answer] Lua (LuaJit) Find a number bigger than 0.2 where Expected result == Value. Actually the math is right on paper 😜 ``` function Fails(i) local max = i * 80 local a = 0 while true do if a < max then a = a + 0.2 else break end end print("Input", i) print("Max", max) print("Expected Value", max) print("Value", a) end Fails(...) ``` Try it [Lua](https://tio.run/##bdA9D4IwEAbgnV9xYQI/murkoKMmDq7uJxyhehYCbeTf11IBJfFd2jy9y13KFtds8a6Mc4XVmVGVhhMqbhOVRuDDVYYMT@zgAAoWsJM/jB5lFOBVKiYwjSXIqyB9VOFr9qHdlKQn79M3IyxBiu3kxC3Nim4N4eP7rPNoPMOlbpQ2SXzWtTXxCoadB71g583PnumxqykzlMMV2dKfgtExjcKcz3cIIVLnnBRy8wY) [Answer] # Python 3.10.11 ``` import math def fails(x: float, y: float) -> int: return math.lcm(x.as_integer_ratio()[1], y.as_integer_ratio()[1]) ``` * Takes two real numbers and outputs the lowest natural number that can be the denominator of the fractions representing both numbers (with an integer numerator). For example, \$f(0.1,0.32)=50\$. * Incorrect very often, and deterministically. * Off by at least a billion times when it's wrong. * Infinitely many inputs affected. * Version 3.10.11 (maybe other versions), should happen on most environments. ]
[Question] [ ## About Hangul As I'm Korean, I'm really proud of Korean character, [Hangul](https://en.wikipedia.org/wiki/Hangul)(한글). Hangul is a syllabary invented by King Sejong the great, 4th king of Joseon dynasty, in 1443. Because today (October 9th) is Hangul day in Korea, I'll give you a challenge: Make some Hangul [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") ## List of characters So, To make ASCII art, you have to know every characters represent each syllables, right? No. There are 11172 syllables in Korean character, so it's almost impossible to hardcode it. But, there are only 24 basic characters: ``` ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㅏㅑㅓㅕㅗㅛㅜㅠㅡㅣ ``` And in Korean you compose these to make all those syllables. ## How to compose 24 basic characters can be separated into two part: a consonant and a vowel. The first 14 characters `ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ` are consonants, and followingthe 10 characters `ㅏㅑㅓㅕㅗㅛㅜㅠㅡㅣ` are vowels. There are roughly 3 parts to a Korean character: initial consonant, vowel, and a final consonant. ### Initial consonant The initial consonant (초성 in Korean) is simplest part. It is just consonant, only with `ㄲㄸㅃㅆㅉ`(double consonant). It placed in the top-left. ### Vowel The vowel (중성 or 모음 in Korean) is the hardest part. Here is list of the vowels: `ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ` `ㅏㅐㅏㅒㅓㅔㅕㅖㅣ` go on the right side of initial consonant; `ㅗㅛㅜㅠㅡ` go at the bottom; `ㅘㅙㅚㅝㅞㅟㅢ` are both. For example: `가, 고, 과`. ### Final consonant The final consonant (종성 in Korean) is at the bottom. Here is list of final consonants: `ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ`, or blank. Example characters using final consonant : `각, 갌, 갏` ## How to decompose Unicode See [this webpage](http://gernot-katzers-spice-pages.com/var/korean_hangul_unicode.html) for help. ## Challenge Input is in this format: `(number) Korean char (number) Korean char ...` Where (number) is optional. If a number is given, switch to a different style as specified below. `1` and `2` are ASCII only, and `3` is Unicode box-art. Separate characters with 2 spaces. Note that not every character has the same width. If the vowel is not `ㅗㅛㅜㅠㅡ`, the following final consonant must be indented with a space. The default style is `1`, so if first character doesn't have a number, style 1 is used. An example input could be: `1한2글3날` or `한3글날`. [Here is list of Korean ascii art(style 1 and 2).](https://gist.github.com/dhnam/3cc3220ea2b9a0aec19b5a540a43da73) [Here is list of Korean unicode box-art(style 3).](https://gist.github.com/dhnam/4c1ca885ef4b67764cd9dc49522d24f8) ## List of ASCII art ### Style 1 ``` ㄱ ___ | | ㄴ | | |__ ㄷ ___ | |___ ㄹ ___ __| |___ ㅁ __ | | |__| ㅂ | | |__| |__| ㅅ /\ | | | | ㅇ __ / \ \__/ ㅈ ____ /\ / \ ㅊ __ ____ / \ ㅋ ___ ___| | ㅌ ___ |___ |___ ㅍ ____ || _;;_ ㅎ __ ____ () ㄲ _ _ | | | | ㄸ _ _ | | |_|_ ㅃ |||| [][] """" ㅆ /|/| |||| |||| ㅉ ____ /|/| |||| ㅏ | |_ | | ㅐ | | |_| | | | | ㅑ | |_ |_ | ㅒ | | |_| |_| | | ㅓ | _| | | ㅔ || _|| || || ㅕ | _| _| | ㅖ || _|| _|| || ㅗ | _|__ ㅘ | | |_ | | _|__| ㅙ | | | | |_| | | | _|__| | ㅚ | | | | | _|__| ㅛ || _][_ ㅜ ____ | ㅝ | | | ____| |--| ㅞ || || || ____|| |--|| ㅟ | | | ____| | | ㅠ ____ || ㅡ ____ ㅢ | | | | ____| ㅣ | | | | ㄳ _ /| ||| ||| ㄵ | __ | /| |_|| ㄶ | __ | __ |_() ㄺ _ _ ] | [_ | ㄻ _ ++ ]|| [_"" ㄼ _ || ][] [_"" ㄽ _ /| ]|| [_|| ㄾ _ _ ]|_ [_|_ ㄿ _ __ ]][ [_"" ㅀ _ __ ]__ [_() ``` ### Style 2 ``` ㄱ ---. : : ㄴ : : '--- ㄷ .--- : '--- ㄹ ---. .--' '--- ㅁ .--. : : '--' ㅂ : : :--: '--' ㅅ ,. : : : : ㅇ .. ( ) '' ㅈ -.,- ;: ' ` ㅊ -- -,.- ; : ㅋ ---. ---: : ㅌ .--- :--- '--- ㅍ -..- :: -''- ㅎ -- ---- () ㄲ -.-. : : : : ㄸ .-.- : : '-'- ㅃ :::: [][] '''' ㅆ ,:,: :::: :::: ㅉ ---- ,:,: :::: ㅏ : :- : : ㅐ : : :-: : : : : ㅑ : :- :- : ㅒ : : :-: :-: : : ㅓ : -: : : ㅔ :: -:: :: :: ㅕ : -: -: : ㅖ :: -:: -:: :: ㅗ : -^-- ㅘ : : :- : : -^--: ㅙ : : : : :-: : : : -^--: : ㅚ : : : : : -^--: ㅛ :: -^^- ㅜ -v-- : ㅝ : : : -v--: :--: ㅞ :: :: :: -v--:: :--:: ㅟ : : : -v--: : : ㅠ -vv- :: ㅡ ---- ㅢ : : : : ----: ㅣ : : : : ㄳ -.,: ::: ::: ㄵ : -- : ,: '-:: ㄶ : -- : -- '-() ㄺ -.-. .' : '- : ㄻ -... .':: '-'' ㄼ -.:: .'][ '-'' ㄽ -.,: .':: '-:: ㄾ -..- .':- '-'- ㄿ -... .'][ '-'' ㅀ -.-- .'-- '-() ``` ### Style 3 ``` ㄱ ───┐ │ │ ㄴ │ │ └── ㄷ ┌─── │ └─── ㄹ ───┐ ┌──┘ └─── ㅁ ┌──┐ │ │ └──┘ ㅂ │ │ ├──┤ └──┘ ㅅ ╱╲ │ │ │ │ ㅇ ╭──╮ │ │ ╰──╯ ㅈ ──── ╱╲ ╱ ╲ ㅊ ── ──── ╱ ╲ ㅋ ───┐ ───┤ │ ㅌ ┌─── ├─── └─── ㅍ ─┬┬─ ││ ─┴┴─ ㅎ ── ──── () ㄲ ─┐─┐ │ │ │ │ ㄸ ┌─┌─ │ │ └─└─ ㅃ ││││ ├┤├┤ └┘└┘ ㅆ ╱│╱│ ││││ ││││ ㅉ ──── ╱│╱│ ││││ ㅏ │ ├─ │ │ ㅐ │ │ ├─┤ │ │ │ │ ㅑ │ ├─ ├─ │ ㅒ │ │ ├─┤ ├─┤ │ │ ㅓ │ ─┤ │ │ ㅔ ││ ─┤│ ││ ││ ㅕ │ ─┤ ─┤ │ ㅖ ││ ─┤│ ─┤│ ││ ㅗ ╷ ─┴── ㅘ │ │ ├─ ╷ │ ─┴──│ ㅙ │ │ │ │ ├─┤ ╷ │ │ ─┴──│ │ ㅚ │ │ │ ╷ │ ─┴──│ ㅛ ╷╷ ─┴┴─ ㅜ ─┬── ╵ ㅝ │ │ │ ─┬──│ ╵──┤ ㅞ ││ ││ ││ ─┬──││ ╵──┤│ ㅟ │ │ │ ─┬──│ ╵ │ ㅠ ─┬┬─ ╵╵ ㅡ ──── ㅢ │ │ │ │ ────│ ㅣ │ │ │ │ ㄳ ─┐╭╮ │││ │││ ㄵ ╷ ── │ ╱│ └─╵╵ ㄶ │ ── │ ── └─() ㄺ ─┐─┐ ┌┘ │ └─ ╵ ㄻ ─┐┌┐ ┌┘││ └─└┘ ㄼ ─┐╷╷ ┌┘├┤ └─└┘ ㄽ ─┐╭╮ ┌┘││ └─╵╵ ㄾ ─┐┌─ ┌┘├─ └─└─ ㄿ ─┐┬┬ ┌┘││ └─┴┴ ㅀ ─┐── ┌┘── └─() ``` ## Example input and output `1한2글3날` ``` __ | ---. │ │ ____|_ : │ ├─ () | : └── │ | ---- │ | ---. ───┐ | .--' ┌──┘ |__ '--- └─── ``` `뛟쀒3쫽` ``` _ _|| |||||| ────│ │ | | || [][]|| ╱│╱││ │ |_|_|| """"|| ││││├─┤ ____|| ____|| ╷ │ │ |--|| |--|| ─┴──│ │ _ __ _ __ ─┐─┐ ]__ ]][ ┌┘ │ [_() [_"" └─ ╵ ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # C, 1832 bytes Well, this is the first time I've ever golfed anything, and this is easily the ugliest code I have ever written: (compiled with gcc 7.5.0) ``` #define C(x,y)case 0x##x:y;break; #define c(x)case x:r=r<<6|getchar()&63; #define F(x,n)for(x=0;x<n;x++) #define M(n)"\e["#n"D\e[B" #define m M(1) #define U(n)"\e["#n"A" #define l U(4) char p[]={0,1,3,6,27,7,15,16,28,18,19,20,21,29,22,23,24,25,26},*H="---.-.-.-.,:: : --: --.------.-.-.-...-.::-.,:-..--...-.--.--.: :::,: ,. ,:,: .. -.,- -- ---..----..- -- .-.-::::---- : : : :::: : ,:: --: .--'.' :.'::.'][.'::.':-.'][.'--: ::--:[]::: :::::( ) ;: -,.----::--- :: ----: : [][],:,: : : : :::'---'-::'-()'---'---'- :'-'''-'''-::'-'-'-'''-()'--''--'''::: ::::: '' ' `; : :'----''- () '-'-''''::::",*B=M(4), #define P " "U(3) #define Q " :"M(2)"-^--"l *U[]={P,P,P,P,P,P,P,P,Q,Q,Q,Q," ::"M(3)"-^^-"l,"-v--"M(4)" : "l,"-v--"M(4)" :--"l,"-v--"M(4)" :--"l,"-v--"M(4)" : "l,"-vv-"M(4)" :: "l,"----"," "M(4)"----"U(4),P}, #define X(x,y)x y x #define Y(x,y)x y y #define Z(x,y)x x y x #define R "\e[4B"M(4) #define S Z(":"m,":"m)":"M(4) *V[]={X(":"m,":-"M(2))":"M(4),X(": :"M(3),":-:"M(3))": :"M(6),Y(":"m,":-"M(2))":"M(4),Y(": :"M(3),":-:"M(3))": :"M(6),X(" :"M(2),"-:"M(2))" :"M(5),X(" ::"M(3),"-::"M(3))" ::"M(6),Y(" :"M(2),"-:"M(2))" :"M(5),Y(" ::"M(3),"-::"M(3))" ::"M(6),R,Z(":"m,":-"M(2))":"M(4),Z(": :"M(3),":-:"M(3))": :"M(6),S,R,R,S,Z("::"M(2),"::"M(2))"::"M(5),S,R,M(4),S,Z(":"m,":"m)"\e[3D"}, #define w(m,n)"\e["#m"C"U(n) #define T w(7,7) #define W w(8,7) #define x w(6,8) *A[]={T,W,T,W,T,W,T,W,x,w(7,8),w(7,8),x,x,x,x,w(7,8),x,x,x,x,x}; #define D(x) printf(x); g(){int r=getchar(),n=~0;switch(r>>4){C(f,n=7)C(e,n=15)C(d,C(c,n=31))}r&=n;switch(n){c(7)c(15)c(31)}return r;}main(){D("\e[2J\e[H")int n,j,k,t,v,h;while(~(n=g())){if(n>>8){n-=44032;t=n%28;v=n/28%21;h=p[n/588];F(j,3){F(k,4)putchar(H[(j*30+h)*4+k]);D(B)}D(U[v])D(V[v])if(t--)F(j,3){F(k,4)putchar(H[(j*30+t)*4+k]);D(B)}else D("\e[3B")D(A[v])}}} ``` It only does style 2; the challenge was already difficult enough for me without needing to support all three styles! It's a shame though, because I'm really in love with the charming ASCII art the OP made (by the way, they forgot to provide art for the ㅃ jamo, so I made one myself). You can see the project here: <https://repl.it/@Mahkoe/hangul-ASCII-art> ***Brief hints for understanding the code*** * This makes heavy use of [ANSI escape sequences](https://www.xfree86.org/current/ctlseqs.html) for moving the cursor. The `U(n)` macro moves the cursor up by `n` characters, and the `M(n)` macro moves the cursor left by `n` characters then down by one. (`U` stands for "up", and `M` stands for "mot", which is French for "word"). * Because `U(4)` appeared enough times, I defined `l` to `U(4)` (`l` doesn't stand for anything, it was just one of the few single-character identifiers left). * The `g` function reads stdin and parses out a UTF-8 sequence. It correctly returns EOF when it sees one. * The `C` and `c` macros are used to shorten the cases in the switch statements in the `g` function. * The `H` string contains all the tail consonants (copy-paste the string to a text file and break it into three 30-character wide lines to see it better). They are ordered according to increasing UTF-8 codepage addresses. (I originally called this string `H` because early on it only had head consonants, but the name stuck around even after I changed my mind and put in the tail consonants). * Some consonants are head-only consonants (ㄸ, ㅃ, and ㅉ), so I tacked these onto the "right-hand side" of `H`. The `p` array is a mapping from the head consonant number to the position in the `H` string. (I originally called this array `p` because I thought of it as a permutation, but the name stuck around after I realized it wasn't actually a permutation). * The vowels had so many special cases that I ended up splitting a vowel into three actions: the "underneath" (anything that would end up between the head and tail consonants), the rest of the vowel, and any adjustments needed to the cursor after drawing the tail consonant. These three quantities are stored in the `U`, `V`, and `A` strings, respectively. * If anything appeared often enough in the `U`, `V`, or `A` strings, I made a macro for it. This consists of the `P`, `Q`, `R`, `S`, `T`, `W`, `w`, and `x` macros (I started having name collisions, which is why the macro name pattern breaks after `T`). * All together, the `main` function eats characters from stdin until it gets an EOF. If it sees a Hangul character, it prints the head consonant, then the underneath, then the rest of the vowel, then the tail consonant, then the adjustment. This challenge was delightful, and I'm really excited about having learned Hangul. Thanks! ]
[Question] [ # Introduction In a general election, one would like to calculate a constant price per parliament seat. This means that for `N >= 0` seats to be distributed and a list `ns` of votes per party, we would like to find a number `d` such that ``` sum(floor(n/d) for n in ns) == N ``` To make things interesting (and more like the real world), we add two more facts: 1. Two parties can gather in a 'coalition', so that the seats are given to the 'coalition' by the sum of votes for all parties in it. Then the seats the 'coalition' got are split between parties in a similar fashion (find divisor, etc.) 2. A party that didn't pass a certain percentage of the votes (e.g. 3.25%) automatically gets 0 seats, and its votes don't count for a 'coalition'. # Challenge You are given : 1. A list of lists, each of the nested lists contains integers (number of votes), and is of length 1 for a single party, or length 2 for a 'coalition'. 2. Minimal percentage of votes (a.k.a "bar" for "barrage") to get seats, as a fraction (so 3.25% is given as 0.0325) 3. Total number of seats to be distributed between all parties (integer) You are to print out the same nested list structure, with the number of votes substituted with parliament seats. Winner is the code with the smallest amount of bytes. Corner cases: * There might (and usually will be) more than one possible divisor. Since it is not in the output, it doesn't really matter. * Imagine `N=10` and `ns = [[1]]`, so the divisor may be 0.1 (not an integer) * Some cases can't be solved, for example `ns=[[30],[30],[100]]`, `bar=0`, `N=20`. There's a boundary with `d=7.5` where the sum of floored values jumps from 19 to 21. You are not expected to solve these cases. (thanks to community member Arnauld for pointing this case out) # Example Input and Output A very not-optimized Python3 example: ``` from math import floor def main(_l, bar, N): # sum all votes to calculate bar in votes votes = sum(sum(_) for _ in _l) # nullify all parties that didn't pass the bar _l = [[__ if __ >= bar * votes else 0 for __ in _] for _ in _l] # find divisor for all parliament seats divisor = find_divisor([sum(_) for _ in _l], N) # find divisor for each 'coalition' divisors = [find_divisor(_, floor(sum(_)/divisor)) for _ in _l] # return final results return [[floor(___/_) for ___ in __] for _, __ in zip(divisors, _l)] def find_divisor(_l, N, _min=0, _max=1): s = sum(floor(_ / _max) for _ in _l) if s == N: return _max elif s < N: return find_divisor(_l, N, _min, (_max + _min) / 2) else: return find_divisor(_l, N, _max, _max * 2) print(main(l, bar, N)) ``` Example input: ``` l = [[190970, 156473], [138598, 173004], [143666, 193442], [1140370, 159468], [258275, 249049], [624, 819], [1125881], [152756], [118031], [74701]] bar = 0.0325 N = 120 ``` And its output: ``` [[6, 4], [0, 5], [4, 6], [35, 5], [8, 8], [0, 0], [35], [4], [0], [0]] ``` Some more example outputs: If `bar=0.1` we get an interesting stand-off between two parties as none of the smaller parties are counted in: ``` [[0, 0], [0, 0], [0, 0], [60, 0], [0, 0], [0, 0], [60], [0], [0], [0]] ``` And if `N=0` (corner case) then of course no one gets anything: ``` [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0], [0], [0], [0]] ``` [Answer] # [Python 2](https://docs.python.org/2/), 220 bytes ``` def d(l,n,a=0,b=1.):s=sum(x//b for x in l);return s-n and d(l,n,*[a,b,(a+b)/2,b*2][s>n::2])or b def f(l,b,n):l=[[x*(x>=b*sum(sum(l,[])))for x in r]for r in l];return[[v//d(x,sum(x)//d(map(sum,l),n))for v in x]for x in l] ``` [Try it online!](https://tio.run/##zZBNboMwEIX3OYWXmE7D@AdjU5GLWF5gkaiRiBNBEtHTU9tE7RWysPT0zbx5T7793L@vga/rcDyRoRghQN8h@I7taTt38@NSLFXlyek6kYWcAxnp13S8P6ZA5s9A@jC8XKXtwUPRf3hacfAld3Y@hLbljkar36X7p7jpIdB27KxdymI5dL5MEemNYB2l9C9ocklOOdO9Mq19VtVQLJB70aQv/S3ZYaTxcHY/k2Vx/43depvO4R7jrWUGTYNAWK1kIxwQy4SujY6kEYgyEymUUpEYISXPhEkUm81IpRPiteZNDYRLg9IkorgEopnZDHGuWZZ13FMb1Cgya2SDzEWFexQ8XmEc6e6NW7L3r7h9JNL1Fw "Python 2 – Try It Online") Basically just a golf of the reference implementation... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~42~~ 39 bytes ``` ÐOOI*@*DO¸I¸¸2Fнζε`sDO/*Щ±/D{®1%Oòè‹+ï ``` [Try it online!](https://tio.run/##Jcs9CsJAFATg3lOksYmJvrf79q@zCILVHiAEVLAQxBRWauMRPIY2ioISC5vdXjyDF1lj0g3fzJTr6WwxD8EfrB3Hwzizrhq7ylVs9Hm9H@/7ZJ3ZQewP7uSug2znzti1/uaP3/2z5y8h5DkaMAqSCIUkxYskypFrYXQtigNQI8SllLUYTsQaQQLe3gxJ/ScmNFMiiRgZIPMXySiJNJr2UPcamyjqnWxRA29MkQIsig70gTPRQQYhTVdlupxuNz8 "05AB1E – Try It Online") 05AB1E lacks good recursion, so implementing a binary search as in the reference code would be painful. Thankfully, we don’t need to find the divisor at all! Let’s use a simple example: [600, 379, 12, 9] votes, 100 seats, no coalitions, no bar. First, we compute how many *fractional seats* each party gets, defining fractional seats as `party_votes * seats / sum_of_votes`. In our example, that yields [60, 37.9, 1.2, 0.9]. The interesting bit is that if a party gets `f` fractional seats, it will get either `int(f)` or `int(f) + 1` real seats. This means we already know how 60+37+1 = 98 of the seats will be allocated, and we’re left with 2 “bonus seats” to distribute among the 4 parties (no party can get more than 1 bonus seat). Who do these bonus seats go to? The parties with the highest ratio of `f / (int(f) + 1)` (proof left as an exercise to the reader). In our examples, the ratios are `[0.98, 0.997, 0.6, 0.9]`, so the first two parties get a bonus seat each. --- Let’s take a look at the code. First, we replace the vote count of all parties that didn’t meet the bar with 0: ``` Ð # triplicate the first input (list of votes) OO # flattened sum I* # multiply by the second input (bar) @ # greater than? (returns 0 or 1) * # multiply ``` Now, to work around the lack of recursion, we use an awkard `2F` to repeat the main code twice. On the first pass it’ll distribute the total seats between coalition, and on the second pass it’ll distribute each coalition’s seats between its parties. Since the first pass runs only once, but the second pass runs for each coalition, this involves rather a lot of busy work. ``` DO¸I¸¸2Fнζε`s # i don’t want to detail this tbh ``` Okay, after this obscure bit, the top of the stack is now a list of votes (coalition votes on the first pass, party votes on the second), and below that is the number of seats to allocate. We use this to compute the list of fractional seats: ``` D # duplicate O # sum / # divide each vote count by the sum * # multiply by the number of seats © # save the fractional seats in variable r ``` Now, we compute the ratios: ``` Ð # triplicate ± # bitwise not / # divide ``` Bitwise not works beautifully, here. It truncates to integer, adds 1, and negates, all in a single byte. Why negate? In 05AB1E, division by 0 returns 0, and we need these to sort last. D{ # sorted copy of the ratios ®1% # fractional votes mod 1 (aka the decimal parts) O # sum of the above (this is the number of bonus seats) ò # round to nearest (required due to floating point bs) è # index into the sorted ratios This gives us the (n+1)th best ratio, where n is the number of bonus seats (+1 because indexing is 0 based). Thus, the parties that get a bonus seat are those that have a ratio strictly less than this. ``` ‹ # less than + # add to the fractional seats ï # truncate to integer ``` [Answer] # Wolfram - no golf Was just curious to solve it using [LinearProgramming](http://reference.wolfram.com/language/ref/LinearProgramming.html), not a golfing candidate, but maybe an interesting approach to a problem: ``` findDivisor[l_, n_] := Quiet@Module[{s, c, r, m, b, cons, sol}, s = Length[l]; c = Append[ConstantArray[0, s], 1]; r = Thread[Append[IdentityMatrix[s], -l]]; m = Append[Join[r, r], Append[ConstantArray[1, s], 0]]; b = Append[Join[ConstantArray[{0, -1}, s], ConstantArray[{-1, 1}, s]], {n, 0}]; cons = Append[ConstantArray[Integers, s], Reals]; sol = LinearProgramming[c, m, b, 0, cons]; {1/sol[[-1]], Most@sol} ] solve[l_, bar_, n_] := With[{t = l /. x_ /; x <= bar Total[l, 2] -> 0}, With[{sol = findDivisor[Total /@ t, n]}, {First@sol, MapThread[findDivisor, {t, Last@sol}]}] ] ``` [Read some explanation and try it out!](https://www.wolframcloud.com/obj/user-51481b62-6018-41a8-aab0-53fc090650f5/ParliementSeats) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~63~~ 36 bytes ``` F×S<ḷ×ḷµ§⁵:,1_×¥:@"§IṠʋ÷9ɗ¥ƬṪṪƲ¥¥@⁺" ``` [Try it online!](https://tio.run/##bc29asMwEMDxPU9hslaUO@n0FTp4KmTOaEymLiUv0NFztizO2MUYQroUQuKMEjE0b2G/iCoidysIIX7cX/f@ttl8hPDq69XLcDn7Ol7u5NqxOi0Yrn3tmkU@d@1y6D7vW3@2P1H649Ad4um/XeOafKyu8@Db227o9oGNVYdPqVu5Zt1/9bs8xjG9b6d09u863/79VRRowWpgGUpFWpQsmxUojLQmkhYAlIiEUiqSFUQ8ERKIVFpS5mFcGq4lyzhZIPsgxYllBu3UxAmD6S3jqJrYgEiqSQOWZYBnEFwG5PAL "Jelly – Try It Online") A full program taking three arguments: the numbers of votes in the format described by the question, bar and N in that order. Returns a list of lists of seat counts. The footer on TIO is just to highlight the list structure of the output. (Otherwise Jelly hides `[]` for single-item lists.) ## Explanation ``` F×S<ḷ×ḷµ§⁵:,1_×¥:@"§IṠʋ÷9ɗ¥ƬṪṪƲ¥¥@⁺" F | Flatten vote counts × | Multiply by bar S | Sum <ḷ | Less than original vote counts (vectorises and respects input list structure) ×ḷ | Multiply by original vote counts µ | Start a new monadic link with processed vote counts as input § | Vectorised sum ⁵ ¥@ | Apply the following as a dyad with the number of seats as the right argument and the vectorised sum of votes as left , Ʋ¥ |(*)- Pair vote counts with seat sum and find divisor using the following as a monad: 1 ¥Ƭ | - Starting with 1 as a guess for divisor, and using the paired vote counts and seat sum as the right argument, apply the following as a dyad, collecting intermediate results, until the results repeat ɗ | - Following as a dyad: ʋ | - Following as a dyad: :@" | - Integer divide with arguments zipped and reversed, i.e. divide cote counts by current divisor guess and leave total seats alone § | - Vectorised sum (will sum vote counts but leave seat number alone) I | - Find differences i.e. desired total seats minus current calculation based on current divisor guess. Will return a list. Ṡ | - Sign of this (-1, 0 or 1) ÷9 | - Divide by 9 (-0.111, 0 or 0.111) _×¥ | - Now multiply the current divisor guess by this and subtract it from that guess to generate the next guess. If the current guess is correct, the guess will be unchanged and so the Ƭ loop will terminate ṪṪ | - Take the last item twice (first time to get the final output of the Ƭ loop and second to remove the list introduced by I : | - Integer divide the vote counts by the output of the above ⁺"| Apply the above dyad from the step labelled (*) again, this time with the output of the previous step (total votes per coalition) as right argument and the vote counts as left argument, zipping the two together and running the link once for each pair ``` # Original Submission (larger but more efficient) # [Jelly](https://github.com/DennisMitchell/jelly), 63 bytes ``` :S_3ƭƒṠ©ḢḤ;$;ṪƲṖÆm;ḊƲ®‘¤?ߥ/}ṛ¹?, 1,0;çḢḢ FS×Ċ’<ḷ×ḷµ:"§:⁵ç$$ç"Ɗ ``` [Try it online!](https://tio.run/##Lc29SsRAFAXgPk8RlpSD3pm585cI2/kCW4ZgZSPrA1gsrI1FSgt3xUJZVoKCFguLSTujeY/Ji4xDss3l8HEO9@Z6ubwLIV9c8f6rf/Tdm/3w7c63@yIrfPfZH3z35B5uC9/W/cF@D@ut3c/dq30/X/nuxXZzklAChWvG1S65XLjNbz2sny98@@M28dhjPrNNPtwfXZNlrpn1dXDNX/y1DaEsqQGjgKRUSFS8ImlSUq6F0ZEUB8CJkEspIxmOyCaiCHxaGpR6NCY0U4KkDA2gGUkyJKmm5rSJDU2nLGJVnlgDn1ShAlpVAc6AMxEog38 "Jelly – Try It Online") ]
[Question] [ Someone gave my wife a decorative calendar consisting of four cubes. Here it is showing today's date (as of the posting of this challenge) on the front: [![enter image description here](https://i.stack.imgur.com/CfORU.jpg)](https://i.stack.imgur.com/CfORU.jpg) When I first saw it, I looked at it from the wrong angle (from directly above) and couldn't figure out why it gave this information: ``` [["February", "January"], [3], [7], ["Monday", "Tuesday"]] ``` Your job is to replicate my error for any date in 2019. ## Challenge Write a program or function that takes any date from 2019, and outputs what appears on the ***top*** of all the cubes when that date is displayed facing out from the front of the calendar. Here are all six sides for all the cubes. To display a `6` you just turn the `9` upside down. The `0` is vertically symmetrical, so `0` upside down is still `0`. There might be more than one correct answer for some dates (e.g. any 11th of any month will have more than one way to use the cubes, and the `0` thing) so you can output any correct answer. [![enter image description here](https://i.stack.imgur.com/tjYRy.png)](https://i.stack.imgur.com/tjYRy.png) ## Rules 1. Standard loopholes forbidden. 2. Input/output format is flexible. 3. The output does have to be in order by cube, but not within a cube. The order must be month cube first, then the two number cubes, followed by the weekday cube. But when a cube has two elements on top, those two elements can be in either order. 4. You can replace `January` to `December` 0-11 or 1-12 if you like. 5. You can replace the days of the week with 0-6 or 1-7 if you like, and you can start the week on either `Sunday` or `Monday` (but you can't start the week on any other day - this is PPGC, not some sort of crazy-town.) 6. This is [code-colf](/questions/tagged/code-colf "show questions tagged 'code-colf'"). Fewest bytes for each language wins. 7. Explanations encouraged. ## Test cases ``` (Tue) 2019-01-29 [[ "July", "August" ], [3], [7], [ "Thursday", "Wednesday" ]] [[ "August", "July" ], [3], [7], [ "Wednesday", "Thursday" ]] etc. since the order within each cube doesn't matter. (Thu) 2019-07-11 [[ "May", "June" ], [3], [8], [ "Saturday", "Friday" ]] [[ "May", "June" ], [8], [3], [ "Saturday", "Friday" ]] since the two 1 cubes could be either way. (Sun) 2019-10-27 [[ "January", "February" ], [3], [6], [ "Friday", "Saturday" ]] (Wed) 2019-05-01 [[ "March", "April" ], [8], [3], [ "Monday", "Tuesday" ]] [[ "March", "April" ], [6], [3], [ "Monday", "Tuesday" ]] [[ "March", "April" ], [9], [3], [ "Monday", "Tuesday" ]] since the 0 cube could have either the 8 side or the 6 side facing up, and the 6 could also be considered a 9. (Sat) 2019-08-24 [[ "February", "January" ], [8], [5], [ "Sunday" ]] ``` [Answer] # [C (glibc)](https://gcc.gnu.org), ~~327~~ ~~319~~ 286 bytes ``` #define C strftime(s #define U(B,E)S[6]=E-1,C+B,99,"%A"+2*!E,S) S[9],s[99];f(M,D){S[4]=112233107696>>3*M&7;C,9,"%B",S);S[4]^=1; C+3,9,"%B",S);M=161102>>(D+M*23/9-1-2*(M>2))%7*3&7;U(6,M);U(9,(M^1)); printf("%s/%s %d%d %s/%s\n", s,s+3,D>29?4:D%10<6?8:3,D>29?8:1070160091>>D%10*3&7,s+6,s+9);} ``` (Some line breaks added for clarity) `f` takes a month (1–12) and a day (1–31). Prints to stdout. [Try it online!](https://tio.run/##VVFNj4IwEL37K7ps2LQwZNti0FLBrOCxJ@OJxcSoGBNlDcWT8a8vW/AjyyTTmbx5b16bbrzNcV3um@Z9uysO5Q4lSNdVUR9OO6wHT3CJZzAniyzIo7nHIHFnIARY9pflcudtDgsyWGQiB50JkcsCK0jJdZEN84gxzn2f0VEggjj2HfUxkgm02pllZLIlrSImE9f/h6qIBYxRHsc4dZXD/U/hMY87WMWcEHvk@GbNEgegiCkCsFoxQuS5OpR1gS1bf9oa2Vt7i7r2u7RAgzYWaczFdBimNqOTYDoOH8g4NDekLKBUsDhup62DUQQmBZG35rQ@lJig6wCZMC5IpVmOInT1gYIP/JGv7iY7ZvFTIdzRDZdJUyamctO47nNbj5feeWnL42Pktj7KY7mB@oo2nu/llAnPpnzbHSGyAClAKZE9dvstPfD26s6XWmPLeszueLWrL1WJqBzcmt9NcVzvdfMH "C (clang) – Try It Online") Test cases: ``` 2019-01-29: July/August 37 Thursday/Wednesday 2019-07-11: May/June 83 Saturday/Friday 2019-10-27: January/February 36 Friday/Saturday 2019-05-01: March/April 83 Monday/Tuesday 2019-08-24: February/January 85 /Sunday ``` ### Ungolfed ``` #include <stdio.h> #include <time.h> void f(int M, int D) { int month_cube[] = {6,3,0,5,2,7,4,1,4,0,5,1}; int day_cube[] = {3,3,3,4,5,2,2,6,7,7}; int week_cube[] = {6,1,5,2,7,4,0}; /* 1=Sun, 7=Sat, 0=none */ int D1 = D/10, D2 = D%10; char s[4][99] = {{0}}; struct tm t; t.tm_mon = month_cube[M-1]; strftime(s[0], 99, "%B", &t); t.tm_mon = month_cube[M-1]^1; strftime(s[1], 99, "%B", &t); if (D1 >= 3) { /* D = 30, 31 */ D1 = 4, D2 = 8; } else { if (D2 <= 5) { D1 = 8; /* 012[69]78: 012 -> 8 */ } else { D1 = 3; /* 012345: 012 -> 3 */ } D2 = day_cube[D2]; } int W = (D + M*23/9 - 1 - 2*(M>2)) % 7; /* day of week */ if (week_cube[W]) { t.tm_wday = week_cube[W] - 1; strftime(s[2], 99, "%A", &t); } if (week_cube[W]^1) { t.tm_wday = (week_cube[W]^1) - 1; strftime(s[3], 99, "%A", &t); } printf("%s/%s %d%d %s/%s\n", s[0], s[1], D1, D2, s[2], s[3]); } ``` ### Digit cubes These are the possibilities for the digits: ``` Cube 1: 0 1 2 3 4 5 3 3 3 4 5 2 5 Cube 2: 0 1 2 6 7 8 9 8 8 8 2 6 7 7 6 2 9 ``` The following mapping seems like the best choice for golfing: ``` 01 02 03 04 05 06 07 08 09 83 83 84 85 82 32 36 37 37 10 11 12 13 14 15 16 17 18 19 83 83 83 84 85 82 32 36 37 37 20 21 22 23 24 25 26 27 28 29 83 83 83 84 85 82 32 36 37 37 30 31 48 48 ``` ### Cheats `strftime` is meant to be called with a `struct tm` as input. Instead, I declare `int S[9]` and use `S[4]` as `tm_mon` and `S[6]` as `tm_wday`. This works if the C library uses the same list of struct members as the ISO standard. `s[99]` is used to store various strings from `strftime`, but making it an `int` array saves a few bytes in indexing. [Answer] # JavaScript (ES6), 142 bytes Takes input as `(year, month, day0, day1)` where \$month\$ is 1-indexed, \$day0\$ is the first digit of the date and \$day1\$ is the second digit. Returns `(month0, month1, day0, day1, weekDay0, weekDay1)` where week days are 0-indexed with \$0\$ for Sunday. If the second week day is blank, it is set to \$-1\$. ``` (y,m,t,u)=>[M=-~((s='45226276204264')[m--+6]||4*m%2),M+1,t<3?u<6?8:3:s[t-3],u<3?3:s[u-3],D=s[(new Date(y,m,t*10+u).getDay()+6)%7+7],-~D%7||-1] ``` [Try it online!](https://tio.run/##XY5Bb4IwGIbv/IrvYmjlK6MFQZ3VC1dPOxIORKvZImJou8WM@ddZ65Jl7tCm7/M@7de35r3Ru/71Yti526vxIEdyxRYNWirX1VayGyFahtlMiFwUuUgykWchrVrGorwehmzaTgTFbcTRrNKNXeWb@TJd6sqwtEbrkA/Wh1LqipzVB5SNUT9TpjyJLI2PypTNldAop5MiKmpkt3JSDAPj9WiUNiDB@dAiGARLQa7hMwDolXbN4W/17PCuO@vupOJTdyRXiCB8Ct1OWn8MaXxp9i@m6Q0RCAn97Y1b1idgbA2euOdp8BUE/gdEJHyBABzBXVvQB1ig5/wB8uRuFo/mzI38b8L8bmZ0/AY "JavaScript (Node.js) – Try It Online") ]
[Question] [ Given an ordered list of 2 or more 2D cartesian points, output a truthy value if either the path touches itself or self-intersects; otherwise output a falsy value if it does not touch itself or self-intersect. You may assume that consecutive points in the list are distinct. ### Examples: ``` (0,0), (1,0) -> falsey (0,0), (1,0), (0,0) -> truthy (0,0), (1,0), (1,1), (0,0) -> truthy (0,0), (2,0), (1,1), (1,-1) -> truthy (0,0), (10,0), (0,1), (10,1), (0,2), (10,2) -> falsey ``` Note all the co-ordinates I gave here are integers. You may support co-ordinate inputs of whatever you like out of {integer, decimal, rational, floating-point, ...}. But your implementations calculations must give the correct answers for any inputs given. [Answer] # [Python 2](https://docs.python.org/2/), ~~315~~ ~~309~~ ~~298~~ ~~382~~ ~~380~~ 372 bytes ``` s=sorted w=lambda(x,y),(X,Y),(z,w):(X-x)*(w-y)-(z-x)*(Y-y) def I(a,b):p,q=s(a);P,Q=s(b);n,N,m,M=w(p,q,P),w(p,q,Q),w(P,Q,p),w(P,Q,q);return(q>=P)*(Q>=p)if{n,N,m,M}=={0}else(b[1]!=a[0])*(n*N<=0>=m*M) def f(l): i=0 while i<len(l)-2: x=l[i:i+3];i+=1 if w(*x)==0and s(x)==x:l.pop(i);i-=1 L=zip(l,l[1:]);return any(I(*l)for l in[(k,x)for i,k in enumerate(L)for x in L[:i]]) ``` [Try it online!](https://tio.run/##nVHBToNAFDzLV6y3t/RhdjE1Bny9m1TT3jSEA02XdON2SwEDrfHb60JpotH24GXfzJvZYbIUu3q1seHhUFG1KWu19Boy2XqxzKDFHUd4wVd37rHhEbwELfehCXY8gH2PXx32lipnj5DhgkcFbqmCjMcznDuw4LHFZ1zjEzXgNJxxPIJ5B5wJixPY8rhU9XtpYTuhmcueT6jgOv8YEj6JPsSnMpWCRSLTa8oSkTqb9Z8fSExo7T8dq@RgeOQxTcJjzUobxfSDUdZtgzDyrloyiY706DaN9Yikd6Vz1oDfciKR2SWroINtZG6KTQGaxzpwLjalvS7AoElklJ6qsszu4BF8w/NNyQzTNoE3bHum8c1xpuz7WpVZrWDar9tuOU0inab8UJTa1q5wAgIFRwbSjZR7f@7dEJflILyku1N2JPyH@fasV/ZecfSGfbDEILxU81zm/fH@WXM/Ankpemj9653GOP4mD@Y7vOtGp/0VGf6IlGe/LE7/Rg50qBAOtHuLwxc "Python 2 – Try It Online") Uses the algorithm from [here](http://algs4.cs.princeton.edu/91primitives/), combined with [this SO answer](https://stackoverflow.com/a/15812696/7785819) for collinear segments. Edit: Fixed for line segments continuing in the same direction (eg `(0,0),(1,0),(2,0)`) by removing the middle point, (resulting in `(0,0),(2,0)`). [Answer] # [Eukleides](http://www.eukleides.org), ~~154~~ 148 bytes ``` number i (set p) g=card(p);h=g;n=0;e=p[0];q=e.e for d in p if h<g-1 q=q.e n=card(intersection(d.e,q))>1or d on q?1|n end e=d;h=h-1 end;return n;end ``` Function named `i` that, passed a set of points, returns 0 or 1. Semicolons and line breaks are interchangeable for ending a command, I just lumped a few things together for the sake of keeping the code visibly short since we're not used to legible code around here anyway. Eukleides is a plane geometry language primarily for graphical output, but with decent programmatic abilities as well. I thought it'd be great for this task, but a few things frustrated me. First, it's worth noting that *sets* in Eukleides are essentially arrays of points, and when applicable are rendered out as paths made of connected line segments. Eukleides supports the iterative generation of sets via loci, akin to a for-loop that creates a set in the process. Had I been able to use a locus, it would have shaved off bytes, but apparently Eukleides doesn't like to reference a partially-formed locus from within itself. The other major frustration was that if, seemingly, two identical line segments are on top of each other, `intersection` only returns one offending point (which makes sense, I suppose, there would be infinite intersections). My method is essentially to build up the path one step behind, and test the next line segment for intersections with the path. Because of the aforementioned intersection behavior I check separately for whether or not the point is *on* the path. *Edit*: Cut off 1 byte by reordering the `or` statement to allow for the removal of a space before `or`; 5 more bytes by changing that `if` block into a ternary operation. Test cases: ``` ta=point(0,0).point(1,0) tb=point(0,0).point(1,0).point(0,0) tc=point(0,0).point(1,0).point(1,1).point(0,0) td=point(0,0).point(2,0).point(1,1).point(1,-1) te=point(0,0).point(10,0).point(0,1).point(10,1).point(0,2).point(10,2) print i(ta);print i(tb);print i(tc);print i(td);print i(te) 0 1 1 1 0 ``` ]
[Question] [ Given an input list of non-empty strings, output an ASCII art representation of a tournament, based on the following drawing rules: * The number of strings is guaranteed to be of quantity `2,4,8,16,etc.` * The first two strings play each other, and the next two play each other, and so on. This is the first round. * For each game, choose the winner randomly with equal probability. * For the next round, the winner of the first game plays the winner of the second game, the winner of the third game plays the winner of the fourth game, and so on. Subsequent rounds follow the pattern. * There is eventually one overall winner. * For pretty output (required) the strings must all be prepended and appended with an underscore `_`. * In order for the brackets to line up appropriately, each entry must be padded with `_` to all be the same length for that round. * You can choose whether the padding is prepended or appended, so long as it's consistent. * Instead, you can choose to pre-pad all strings to be the same length, rather than on a per-round basis. Whichever is golfier for your code. ## Further Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Examples Example with cities `['Boston', 'New York', 'Charlotte', 'Atlanta', 'St. Paul', 'Chicago', 'Los Angeles', 'Phoenix']`: ``` _Boston______ \_New York____ _New York____/ \ \_New York_ _Charlotte___ / \ \_Charlotte___/ \ _Atlanta_____/ \ \_St. Paul_ _St. Paul____ / \_St. Paul____ / _Chicago_____/ \ / \_St. Paul_/ _Los Angeles_ / \_Los Angeles_/ _Phoenix_____/ ``` Example with `['Lions', 'Tigers', 'Bears', 'Oh My']`: ``` _Lions__ \_Tigers_ _Tigers_/ \ \_Tigers_ _Bears__ / \_Bears__/ _Oh My__/ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~92~~ 79 bytes ``` A¹θWS⊞υ⪫__ιWυ«A⌈EυLκεA⁺θθδFυ«P×_εPκMδ↓»AE✂υ¹Lυ²⎇‽²κ§υ⁺λλυMε→Fυ«Mδ↑↗θ←↖θ→»Mθ↘Aδθ ``` [Try it online!](https://tio.run/##ZVGxbsIwEJ3rr7CYbMlUoiOd0nahgioCOnRCVnIkVhw7xGegqvj21A6BgjpYJ7977947Oytlm1mpuy5xThWGTQTd8WdyKJUGymam8bjCVpmCcU5T70rmBX23yrDRZjMSVPE/tuf0hzwMgxbyqGpfh9pEyRxMgSWrOOeCQtBceKn2ju2iq6B5xLe2vYx6WHiNqgn2yNaqBhdMR1EeebfN6gzYPbBc0OmbPZiInG7SNGylVQYxy@QaxwfTp3DW0BrZfrOlNLmtWYQqQROcmRyOUdKn1IJq3i/g4/TeDoLdUhUl/ot@CfPZ9OHSPmi49ezzKw@s6Ry2eE@KyD3nanIanHfDotfGsGp@1p267sU6tIZ8wIF@2bYir@GztUUEkqCWBiVZ4SNNpdehpTJZWDK3jiamAA2OpKUFo46kG@@7sdO/ "Charcoal – Try It Online") Link is to verbose version of code. Needs a blank line to mark the end of the input. Explanation: ``` A¹θ ``` Initialise the variable `q`. This holds the size of the zig-zags i.e. half the gap between rows. ``` WS⊞υ⪫__ι ``` Read nonblank input lines into the array `u`. The lines are automatically surrounded by `_`s as they are read in, although they are not padded yet. ``` Wυ« ``` Loop while there are still strings left. ``` A⌈EυLκε ``` Calculate the width of the largest string in `e`. ``` A⁺θθδ ``` Calculate the gap between rows in `d`. ``` Fυ«P×_εPκMδ↓» ``` For each team, print the padding, print the team, and then move down to the next team. ``` AE✂υ¹Lυ²⎇‽²κ§υ⁺λλυ ``` For every other team, randomly pick between that team or the previous team. (Note that if there is only one team left then this produces an empty list.) ``` Mε→Fυ«Mδ↑↗θ←↖θ→»Mθ↘ ``` If there are still teams left, draw the zigzags joining them in pairs. ``` Aδθ ``` Double the length of the zigzags each time. [Answer] # [Python 2](https://docs.python.org/2/), ~~379~~ 364 bytes ``` exec r"""c=input();from random import*;R,L,d=range,len,0;u,s="_ ";r=[[""]*-~L(c)@R(2*L(c)-1)] while c: W=2+max(map(L,c));j=1<<d;J=j/2;D=d+d;d+=1 @r:l[D]=s*W;l[D-1]=s*J @R(L(c)): h=l*2*j+j-1;r[h][D]=(u+c[l]+u*W)[:W] @R(h-J,h+J):r[-~l][~-D]=("/\\"[l<h]+s*abs(h-l-(l<h))).rjust(J) c=[choice(l)@zip(c[::2],c[1::2])] @r:print"".join(l)""".replace("@","for l in ") ``` [Try it online!](https://tio.run/##HZFNb9wgEIbP8a9AnMAfm9pHs0ibNidrVUXbwyoiqKKYBFwWLIyVbQ/717fjnuaZV8@gAeY/2cbQ3e/majRKGGPNXZjXTCh7T/GCkgojFHeZY8olO9XHeuQQfpjam1B/YWu9cPwTYZa4EBjLsrkdiaaHE@nKDZqWyuLTOm@Q7gt05l11UVdyUTM51ppSNvF2vx/ZwKfHjj3zsRrZWPG2QIfUe/Es@VKeGUDTbjhAfiLbwbQvHiz3ZVdO1dS0LAkrN52slRZeVmt5pqI/y@IBBmwz1LYaaJ9Ec/NS3JrNxI9vb1j4vZXVUqpfC2i@IdBTSndpWpdMBlogzYW20WlDPD38dTPRou87WWvRbhXuB6vOyYWM8W6KLoAHL7lLZvYKpvAB1/g9JuSRCwjT@x1/jUuOAeLv5hO9xvQb8JtVycecDfBT9ipkBfQj79CLWv1/wWn1EYGOcUFP8AfeLNC92GiCu@J/ "Python 2 – Try It Online") ]
[Question] [ Given three integers >= 2, create an ASCII cube in an orthogonal (cabinet) projection. The three integers represent height, width and depth (measured in visible characters) including the corners. The corners should be 'o's or '+', free choice. w: 10, h: 5, d: 4 Thus gives: ``` o--------o / /| / / | o--------o | | | o | | / | |/ o--------o ``` Now, to make this slightly harder, all faces can either be solid, transparent or missing. We order the faces like this: ``` o--------o / /| / 2 / | o--------o 3| | | o | 1 | / | |/ o--------o --- |2| ------- |5|1|3| ------- |4| --- |6| --- ``` And supply a list of tokens, S, T or M. The original example is thus: ``` w 10 h 5 d 4 S S S S S S o--------o / /| / / | o--------o | | | o | | / | |/ o--------o ``` If one face is transparent, we can see anything that is behind it: ``` T S S S S S o--------o / /| / / | o--------o | | o-----| o | / | / |/ |/ o--------o T T T T T T o--------o /| /| / | / | o--------o | | o-----|--o | / | / |/ |/ o--------o ``` For pairs of missing faces, adjacent edges or corners are no longer visible: ``` M M S S S S o--------o /| /| / | / | o | o | | o-----| o | / | / |/ |/ o--------o M M S S M S o--------o | /| | / | | o | o-----| o / | / / |/ o--------o ``` Code golf, shortest code wins! Trailing spaces and newlines are fine, you're free to choose input method and input order. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~190~~ 181 bytes ``` NωA⁻ω²ςNηA⁻η²γNδA⁻δ²χA⪪S αF›⊟αMF⟦ςγςγ⟧«oκ↶»F∧›⊟αM²«oς↷³oχ↷¹»F∧›⊟αM²«↷³oχ↷³oγ↶»M⁻ωδ⁻δηF⁼§α²SG↗δ↓η↙δ↑η F∧›⊟αM²«↶¹oχ↷³oγ↷»F⁼§α¹SG↗δ←ω↙δ→ω F∧›⊟αM²«↶¹oχ↶³oς»F⁼§α⁰SUO±ωη ↷F›⊟αMF⟦γςγς⟧«oκ↷ ``` [Try it online!](https://tio.run/##tVNNT4NAED3Lr9hwGpI2KX5c6qmJxtRIbcSeGg9boAuR7iIsoDH@dhx2sVjaWptoNpnszrx9M28m44U09QSNq2rMk1xO8tUiSKG0Lo1RlkWMgxPxPIOyR06tHinQ/x0XdnGhxrEOzu/ifI3zWr@bxJEE9cmVacQZYNwkJlqKqKVICdykAZVINxUJ0DrsmJZFVGheYFYsEO2TRd6NkylySDCFiZ@bx7O6RoWQd8FSAr4@NO@I@zu56yL3kRVrsoeIhRLO2tAGzuvg7GPSHk@/D8d2aL/NV0k7Xx/zrocTWl89v37JaZzBSI65H7wC1YMz3brzUxG/McFhOEtUdiTpkeGVKDkyNLc6nfbPEuWtZ3qMflWv/WfyNa4dwrY@@4A@rajc0tdAyn@TqGD7FBY/SRqsJd0vYoG7NQkY1oR73o5kszsH961ZNrS/2Le26VVlD4wL49xwiEMe8bjErfpF1c/iTw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 9 bytes by optimising my conditions. Charcoal has no `else` token, so `if` commands always have two alternatives, unless they're at the end of a block or program. To avoid this, I use `for (<bool>)` instead of `if (<bool>)` which has a similar effect when the expression can only have the values 0 or 1 but saves a byte. (In order to achieve this I had to change the expressions so that they were always true when the body needed to be executed.) I was also able to optimise `if (<bool>) for (<int>)` into `for (And(bool, int))`. [Answer] ## JavaScript (ES6), ~~318~~ ~~314~~ 308 bytes Takes width, height and depth as integers and the faces as an array of characters. ``` (w,h,d,l,M=(n,F)=>[...Array(n+1).keys()].map(F),a=M((L=w--+d)*(h--+--d),i=>++i%L?' ':` `),D=(t,Y=0,X=d,W=t&1?d:w,H=t&2?d:h,F=l[t>>2])=>F>'R'&&M(W,i=>M(H,j=>a[p=L*(Y+j-i*(t&1))+X+i-(t&2?j:0)]=(x=!(i&&i-W)|2*!(j&&j-H))?' |-o|/o/-o'[t%4*3+x]:a[F>'S'?p:0])))=>D(20)&D(D(14,h)&D(17,d,0),d,D(9,d,w)&D(6))||a.join`` ``` ### How? The function ***M()*** processes a given callback ***F*** on a given range ***[0...n]***. ``` M = (n, F) => [...Array(n + 1).keys()].map(F) ``` The variable ***a*** holds a flat array representing a grid of size ***(w+d) x (h+d-1)***. It is initially filled with rows of spaces terminated with newlines. ``` a = M((L = w-- + d) * (h-- + --d), i => ++i % L ? ' ' : '\n') ``` The function ***D()*** is used to 'draw' a face of the cuboid. The two least significant bits of the parameter ***t*** hold the face type: * 0 = rear / front * 1 = left / right * 2 = bottom / top Bits #2 to #4 hold the 0-based face index. ``` D = ( // given: t, Y = 0, X = d, // - the type and the initial coordinates W = t & 1 ? d : w, // - the drawing width H = t & 2 ? d : h, // - the drawing height F = l[t >> 2] // - the character representing the status ) => // F > 'R' && // provided that the face is not missing: M(W, i => // for each i in [0...W]: M(H, j => // for each j in [0...H]: a[ // update the output p = L * (Y + j - i * (t & 1)) + // at position p X + i - (t & 2 ? j : 0) // ] = // with either: (x = !(i && i - W) | 2 * !(j && j - H)) ? // - '|', '-' or '/' on edges ' |-o|/o/-o'[t % 4 * 3 + x] // - or 'o' on vertices : // a[F > 'S' ? p : 0] // - or a space on solid faces ) // - or the current character on ) // transparent faces ``` Faces are drawn in the following order: ``` D(5 * 4 + 0, 0, d) // face #5 (rear) D(3 * 4 + 2, h, d) // face #3 (bottom) D(4 * 4 + 1, d, 0) // face #4 (left) D(2 * 4 + 1, d, w) // face #2 (right) D(1 * 4 + 2, 0, d) // face #1 (top) D(0 * 4 + 0, d, 0) // face #0 (front) ``` ### Demo ``` let f = (w,h,d,l,M=(n,F)=>[...Array(n+1).keys()].map(F),a=M((L=w--+d)*(h--+--d),i=>++i%L?' ':` `),D=(t,Y=0,X=d,W=t&1?d:w,H=t&2?d:h,F=l[t>>2])=>F>'R'&&M(W,i=>M(H,j=>a[p=L*(Y+j-i*(t&1))+X+i-(t&2?j:0)]=(x=!(i&&i-W)|2*!(j&&j-H))?' |-o|/o/-o'[t%4*3+x]:a[F>'S'?p:0])))=>D(20)&D(D(14,h)&D(17,d,0),d,D(9,d,w)&D(6))||a.join`` let update = _ => O.innerHTML = f(W.value, H.value, D.value, [...F.value]) update() ``` ``` <label>Width <input id="W" size="3" value="10" oninput="update()" /></label> <label>Height <input id="H" size="3" value="5" oninput="update()" /></label> <label>Depth <input id="D" size="3" value="4" oninput="update()" /></label> <label>Faces <input id="F" size="6" value="MMSSMS" oninput="update()" /></label> <pre id="O"></pre> ``` [Answer] # [SOGL V0.11](https://github.com/dzaima/SOGL/tree/3390e7e2907aa87f2ebfaa0f46f3665cc32728a0), ~~200~~ ~~194~~ ~~193~~ ~~192~~ 190 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` b³@*⁶ ž}1}X⁵ ;aκ⁴ 2-³ * o1Ο² d=?a³:?∫:¹ be.Aā6∫D,ζLI%:C?abe"DCa∫:c+H⁴d+ /ž}{"a+Hy"e³┐²čž|"b³┌²žz"EBAøp”,ōkB°s9θW=*↑(⅜⅞~υ=\⁰ōwūΧ►ΣΤP░¶Ο⁽◄Φ7⅟▲s#‘┌Θdwι+#¶ŗ!!6c=?6d=?2aI⁶e³∙ž}5¹b+⁴Ie³@∙⁵}4¹2+⁴⁶⁵ ``` Takes input in the order ``` width height depth down-face left-face back-face top-face right-face front-face ``` Tied! [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=Mi0ldTIyMTElMEElM0JhJXUwM0JBJXUyMDc5JTBBYiV1MjIxMUAqJXUyMDc4JTBBKiUyMG8xJXUwMzlGJXUyMDc2JTBBJXUwMTdFJTdEMSU3RFglQjklMEFkJTNEJTNGYSV1MjIxMSUzQSUzRiV1MjIyQiUzQSV1MjA3MCUwQWJlLkEldTAxMDE2JXUyMjJCRCUyQyV1MDNCNkxJJTI1JTNBQyUzRmFiZSUyMkRDYSV1MjIyQiUzQWMrSCV1MjA3OWQrJTIwLyV1MDE3RSU3RCU3QiUyMmErSHklMjJlJXUyMjExJXUyNTEwJXUyMDc2JXUwMTBEJXUwMTdFJTdDJTIyYiV1MjIxMSV1MjUwQyV1MjA3NiV1MDE3RXolMjJFQkElRjhwJXUyMDFETiV1MDNDMyV1MjE1NCV1MjA3NSV1MjExNiV1MDE2MSV1MjE5MCV1MDM5ODZNJXUwM0EzJXUyMDNEJUIxJXUwMTIzJTIzQiVBQiUyMVklQjF4JXUyMDc0eCV1MjI2MCUyMSV1MDNBNiV1MDNCNiVCMyVCMiV1MjVBMXgvJXUwMzlEWSV1MjMyMCV1MDM5OSV1MjVBMCV1MjA3NyVCNjYldTIwMTgldTI1MEMldTAzOThkdyV1MDNCOSslMjMlQjYldTAxNTclMjElMjE2YyUzRCUzRjZkJTNEJTNGMmFJJXUyMDc4ZSV1MjIxMSV1MjIxOSV1MDE3RSU3RDUldTIwNzBiKyV1MjA3OUllJXUyMjExQCV1MjIxOSVCOSU3RDQldTIwNzAyKyV1MjA3OSV1MjA3OCVCOQ__,inputs=MTAlMEE1JTBBNCUwQVQlMjAlMjAlMjAlMjAlMjBkb3duLWZhY2UlMjAlMjAlMjAldTIxOTYlMEFUJTIwJTIwJTIwJTIwJTIwbGVmdC1mYWNlJTIwJTIwJTIwJTVFVyUyMCUyMCUwQVQlMjAlMjAlMjAlMjAlMjBiYWNrLWZhY2UlMjAlMjAlMjAlMjAlMjBIJTBBVCUyMCUyMCUyMCUyMCUyMHRvcC1mYWNlJTIwJTIwJTIwJTIwJTIwJTIwJTIwRCUwQVQlMjAlMjAlMjAlMjAlMjByaWdodC1mYWNlJTBBUyUyMCUyMCUyMCUyMCUyMGZyb250LWZhY2U_) (compressed value changed to be V0.12 compatible) ]
[Question] [ The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two strings of equal length is the number of positions at which the corresponding symbols are different. Let `P` be a binary string of length `n` and `T` be a binary string of length `2n-1`. We can compute the `n` Hamming distances between `P` and every `n`-length substring of `T` in order from left to right and put them into an array (or list). **Example Hamming distance sequence** Let `P = 101` and `T = 01100`. The sequence of Hamming distances you get from this pair is `2,2,1`. **Definition of closeness** Now let's consider two such sequences of Hamming distances. Say `x = (0, 2, 2, 3, 0)` and `y = (2, 1, 4, 4, 2)` as examples. We say that `x` and `y` are `close` if `y <= x <= 2*y` or if `x <= y <= 2*x`. Here the scalar multiplication and inequality are taken elementwise. That is to say, for two sequences `A` and `B`, `A <= B iff A[i] <= B[i]` for all indices `i`. Note that sequences of Hamming distances form a [partial order](https://en.wikipedia.org/wiki/Partially_ordered_set) under this way of comparing them. In other words, many pairs of sequences are neither greater than or equal nor less than or equal to each other. For example `(1,2)` and `(2,1)`. So using the example above, `(0, 2, 2, 3, 0) <= 2*(2, 1, 4, 4, 2) = (4, 2, 8, 8, 4)` but `(0, 2, 2, 3, 0)` is not bigger than `(2, 1, 4, 4, 2)`. Also `(2, 1, 4, 4, 2)` is not smaller than or equal to `2*(0, 2, 2, 3, 0) = (0, 4, 4, 6, 0)`. As a result `x` and `y` are not close to each other. **Task** For increasing `n` starting at `n=1`, consider all possible pairs of binary strings `P` of length `n` and `T` of length `2n-1`. There are `2^(n+2n-1)` such pairs and hence that many sequences of Hamming distances. However many of those sequences will be identical . The task is to find the size of the largest set of Hamming distance sequences so that no two sequences are close to each other. Your code should output one number per value of `n`. **Score** Your score is broadly speaking the highest `n` your code reaches on my machine in 5 minutes (but read on). The timing is for the total running time, not the time just for that `n`. In order to give scores for non-optimal answers, because finding optimal answers is likely to be hard, we will need a slightly subtle scoring system. Your score is the highest value of `n` for which no one else has posted a higher correct answer for any size which is smaller than equal to this. For example, if you output `2, 4, 21` and someone else outputs `2, 5, 15` then you would only score `1` as someone else has a better answer for `n = 2`. If you output `2, 5, 21` then you would score `3` no matter what anyone else outputs because those answers are all optimal. Clearly if you have all optimum answers then you will get the score for the highest `n` you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it. **Example answers and worked example** (This answers are as yet unchecked. Independent verification would be gratefully received.) Thanks to ETHproductions: * n = 1 gives 2. * n = 2 gives 5. * n = 3 gives 21. Let's look at `n = 2` in more detail. In this case the full list of Hamming distance sequences (represented by tuples here) is: ``` [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] ``` We can see that `(0,0)` is not close to any other tuple. In fact if we take `(0, 0)`, `(0, 1)`, `(1, 0)`, `(2, 1)`, `(1,2)` then none of those tuples are close to any of the others. This gives a score of `5` for `n = 2`. For `n = 3` the full list of distinct Hamming distance sequences is: ``` [(0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 3, 0), (0, 3, 1), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 0), (1, 3, 1), (1, 3, 2), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 0, 2), (3, 0, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 3, 2), (3, 3, 3)] ``` Of those `48` sequences, we can pick out a set of size `21` so that no pair in that set are close to each other. **Languages and libraries** You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible. **My Machine** The timings will be run on my 64-bit machine. This is a standard ubuntu install with 8GB RAM, AMD FX-8350 Eight-Core Processor and Radeon HD 4250. This also means I need to be able to run your code. **Leading answer** * Score of **4** for 2, 5, 21, 83, 361 by Christian Sievers. **C++** * Score of **5** for 2, 5, 21, 83, 372 by fəˈnɛtɪk. **Javascript** [Answer] ## C++ using the [igraph library](http://igraph.org/c/) Thanks for a nice opportunity to learn a new library! This program now computes `2, 5, 21, 83, 361` fast. You can control printing of the nodes with the `PRINTNODES` constant. The graph used has extra edges between nodes corresponding to distance vectors where one is near (but not equal) to the other one reversed. That speeds up the computation, and any independent set found is of course also one of the original graph. Also, even if it is not completely enforced, the computed independent set is closed under reversion. I believe there always exists a maximal independent set with that property. At least there is one for `n<=4`. (I'm sure I can show 83 is optimal.) ``` #include<iostream> #include<vector> #include<set> #include<algorithm> #include<igraph.h> using vect = std::vector<int>; constexpr int MAXDIRECT=100; constexpr int PRINTNODES=1; std::set<int> avoid{}; igraph_t graph; std::vector<vect> distance_vectors{}; int count; int close_h(const vect &a, const vect &b ){ // check one direction of the closeness condition for(auto i=a.begin(), j=b.begin(); i!=a.end(); i++,j++) if ( (*i > *j) || (*j > 2 * *i)) return 0; return 1; } int close(const vect &a, const vect &b ){ return close_h(a,b) || close_h(b,a); } vect distances(int n, int p, int t){ vect res{}; for (int i=0; i<n; ++i){ int count = 0; for (int j=0; j<n; ++j) count += 1 & ((p>>j)^(t>>j)); res.push_back(count); t >>= 1; } return res; } void print_vect( vect &v ){ std::cout << "("; auto i=v.begin(); std::cout << *i++; for( ; i!=v.end(); ++i) std::cout << "," << *i ; std::cout << ")\n"; } void use_node( int n ){ if(PRINTNODES) print_vect( distance_vectors[n] ); ++count; avoid.insert( n ); igraph_vector_t neighs; igraph_vector_init( &neighs, 0 ); igraph_neighbors( &graph , &neighs, n, IGRAPH_OUT ); for(int i=0; i<igraph_vector_size( &neighs ); ++i) avoid.insert( VECTOR(neighs)[i] ); igraph_vector_destroy( &neighs ); } void construct(int n){ std::set<vect> dist_vects; for(int p=0; p>>n == 0; ++p) for(int t=0; t>>(2*n-2) == 0; ++t) // sic! (because 0/1-symmetry) dist_vects.insert(distances(n,p,t)); int nodes = dist_vects.size(); std::cout << "distinct distance vectors: " << nodes << "\n"; distance_vectors.clear(); distance_vectors.reserve(nodes); std::copy(dist_vects.begin(), dist_vects.end(), back_inserter(distance_vectors)); igraph_vector_t edges; igraph_vector_init( &edges, 0 ); igraph_vector_t reversed; igraph_vector_init_seq( &reversed, 0, nodes-1 ); for (int i=0; i<nodes-1; ++i){ vect &x = distance_vectors[i]; vect xr ( x.rbegin(), x.rend() ); for(int j=i+1; j<nodes; ++j){ vect &y = distance_vectors[j]; if( xr==y ){ VECTOR(reversed)[i] = j; VECTOR(reversed)[j] = i; }else if( close( x, y ) || close( xr, y) ){ igraph_vector_push_back(&edges,i); igraph_vector_push_back(&edges,j); } } } std::cout << "edges: " << igraph_vector_size(&edges)/2 << "\n"; igraph_create( &graph, &edges, nodes, IGRAPH_UNDIRECTED); igraph_vector_destroy( &edges ); igraph_cattribute_VAN_setv( &graph, "r", &reversed ); igraph_vector_destroy( &reversed ); igraph_vector_t names; igraph_vector_init_seq( &names, 0, nodes-1 ); igraph_cattribute_VAN_setv( &graph, "n", &names ); igraph_vector_destroy( &names ); } void max_independent( igraph_t *g ){ igraph_vector_ptr_t livs; igraph_vector_ptr_init( &livs , 0 ); igraph_largest_independent_vertex_sets( g, &livs ); igraph_vector_t *nodes = (igraph_vector_t *) VECTOR(livs)[0]; igraph_vector_t names; igraph_vector_init( &names, 0 ); igraph_cattribute_VANV( g, "n", igraph_vss_vector( nodes ), &names ); for(int i=0; i<igraph_vector_size(&names); ++i) use_node( VECTOR(names)[i] ); igraph_vector_destroy( &names ); igraph_vector_ptr_destroy_all( &livs ); } void independent_comp( igraph_t *g ); void independent( igraph_t *g ){ if(igraph_vcount( g ) < MAXDIRECT){ max_independent( g ); return; } igraph_vector_ptr_t components; igraph_vector_ptr_init( &components, 0 ); igraph_decompose( g, &components, IGRAPH_WEAK, -1, 1); for(int i=0; i<igraph_vector_ptr_size( &components ); ++i) independent_comp( (igraph_t *) VECTOR(components)[i] ); igraph_decompose_destroy( &components ); } void independent_comp( igraph_t *g ){ if (igraph_vcount( g ) < MAXDIRECT){ max_independent( g ); return; } igraph_vector_t degs; igraph_vector_init( &degs, 0 ); igraph_degree( g, &degs, igraph_vss_all(), IGRAPH_OUT, 1 ); int maxpos = igraph_vector_which_max( &degs ); igraph_vector_destroy( &degs ); int name = igraph_cattribute_VAN( g, "n", maxpos ); int revname = igraph_cattribute_VAN( g, "r", maxpos ); int rev = -1; if(name!=revname){ igraph_vector_ptr_t reversed_candidates_singleton; igraph_vector_ptr_init( &reversed_candidates_singleton, 0 ); igraph_neighborhood( g, &reversed_candidates_singleton, igraph_vss_1(maxpos), 2, IGRAPH_OUT ); igraph_vector_t * reversed_candidates = (igraph_vector_t *) VECTOR(reversed_candidates_singleton)[0]; igraph_vector_t names; igraph_vector_init( &names, 0 ); igraph_cattribute_VANV( g, "n", igraph_vss_vector( reversed_candidates ), &names ); long int pos; igraph_vector_search( &names, 0, revname, &pos ); rev = VECTOR(*reversed_candidates)[pos]; igraph_vector_destroy( &names ); igraph_vector_ptr_destroy( &reversed_candidates_singleton ); } igraph_vs_t delnodes; igraph_vs_vector_small( &delnodes, maxpos, rev, -1 ); igraph_delete_vertices( g, delnodes ); igraph_vs_destroy( &delnodes ); independent( g ); } void handle(int n){ std::cout << "n=" << n << "\n"; avoid.clear(); count = 0; construct( n ); independent( &graph ); // try all nodes again: for(int node=0; node<igraph_vcount( &graph ); ++node) if(avoid.count(node)==0) use_node(node); std::cout << "result: " << count << "\n\n"; igraph_destroy( &graph ); } int main(){ igraph_i_set_attribute_table( &igraph_cattribute_table ); for(int i=1; i<6; ++i) handle(i); } ``` To compile on debian, install `libigraph0-dev` and do `g++ -std=c++11 -Wall -O3 -I/usr/include/igraph -o ig ig.cpp -ligraph`. Old description: The igraph library has a function to compute the maximal size of an independent vertex set of a graph. It can handle this problem up to `n=3` in less than a second and does not terminate in days for `n=4`. So what I do is decompose the graph into connected components, and let the library handle the small (less than `MAXDIRECT` nodes) components. For the other components, I select a vertex and delete it. In the best case, this splits the graph into several components, but usually it doesn't. Anyway, the components (maybe only one) are smaller, and we can use recursion. Obviously the selection of the vertex is important. I just take one of maximal degree. I found that I get better result (but only for `n=4`) when I use a reversed node list. That explains the magic part of the `construct` function. It might be worth while improving the selection. But it seems more important to reconsider the deleted nodes. Right now, I never look at them again. Some of them may be unconnected to any of the selected nodes. The problem is that I don't know which nodes form the independent set. For one, deleting nodes renumbers the remaining nodes. That can be handled by attaching attribtes to them. But worse, the computation of the independence number just gives this number. The best alternative the library offers is to compute *all* largest independent sets, which is slower (how much seems to depend on the graph size). Still, this seems the immediate way to go. Much more vaguely, I also think it might be useful to consider if we can use the special way the graph is defined. The case `n=6` might become reachable (at all, not necessarily in 5 minutes) if I replace the recursion with a loop using a queue for the remaining components. I found it interesting to look at the components of the graphs. For `n=4`, their sizes are `168, 2*29, 2*28, 3, 4*2, 4*1`. Only the biggest one can not be handled directly. For `n=5`, the sizes are `1376, 2*128, 2*120, 119, several <=6`. I expect those double sizes to correspond to isomorphic graphs, but using this doesn't seem worth while because there is always one single dominating biggest component: For `n=6`, the biggest component contains `11941` nodes (from a total of `15425`), the next two biggest components have size `596`. For `n=7`, these numbers are `107593 (125232), 2647`. [Answer] # Javascript, Seq: 2,5,21, ~~81~~ 83,372 ~~67,349~~ Managed to increase the value for 4 by using random removal of elements at the start of my search. Oddly enough, removing 20 elements with more than 6 connections was faster than removing 5 elements with more than 8 connections... This sequence is probably not optimal for 5 and might not be optimal for 4. None of the nodes are close to another in the set though. ## Code: ``` input=4; maxConnections=6; numRand=20; hammings=[]; h=(x,y)=>{retVal=0;while(x||y){if(x%2!=y%2)retVal++;x>>=1;y>>=1}return retVal}; for(i=1<<(input-1);i<1<<input;i++){ for(j=0;j<1<<(2*input);j++){ hamming=[]; for(k=0;k<input;k++){ hamming.push(h((j>>k)%(1<<input),i)); } equal=0; for(k=0;k<hammings.length;k++){ if(hamming.join("")==hammings[k].join("")){ equal=1; break; } } if(!equal)hammings.push(hamming); } } adjMat=[]; for(i=0;i<Math.pow(input+1,input);i++){ row=[]; for(j=0;j<Math.pow(input+1,input);j++){ row.push(0); } adjMat.push(row); } nodes=[] for(i=0;i<Math.pow(input+1,input);i++){ nodes[i]=0; } for(i=0;i<hammings.length;i++){ sum=0; chkNodes=[[]]; for(j=0;j<input;j++){ chkVal=[]; t=Math.pow(input+1,j); sum+=t*hammings[i][j]; tmp=[]; for(r=0;r<chkNodes.length;r++){ for(k=hammings[i][j];k<=Math.min(hammings[i][j]*2,input);k++){ stor=[] for(s=0;s<chkNodes[r].length;s++){ stor.push(chkNodes[r][s]) } stor.push(k) tmp.push(stor); } } chkNodes=[]; for(r=0;r<tmp.length;r++){ chkNodes.push(tmp[r]) } } nodes[sum]=1; for(j=0;j<chkNodes.length;j++){ adjSum=0 for(k=0;k<input;k++){ adjSum+=Math.pow(input+1,k)*chkNodes[j][k] } if(adjSum!=sum)adjMat[sum][adjSum]=adjMat[adjSum][sum]=1 } } t=nodes.length; for(i=0;i<t;i++){ if(!nodes[i]){ for(k=0;k<t;k++){ adjMat[i][k]=adjMat[k][i]=0 } } } sum=(a,b)=>a+b; console.log(nodes.reduce(sum)) connections=x=>x.reduce(sum) counts=adjMat.map(connections); stor=[]; for(i=0;i<t;i++){ stor.push(nodes[i]); } maxRemainder=0; greater=[] for(i=0;i<t;i++){ if(nodes[i]&&counts[i]>maxConnections){ greater.push(i); } } if(input==4){ for(w=0;w<greater.length*numRand;w++){ for(i=0;i<t;i++){ nodes[i]=stor[i]; } counts=adjMat.map(connections); toRemove=Math.floor(Math.random()*numRand*2) for(i=0;i<toRemove&&i<greater.length;i++){ rand=Math.floor(Math.random()*greater.length); if(nodes[greater[rand]]){ nodes[greater[rand]]=0; for(j=0;j<t;j++){ if(adjMat[rand][j]){ counts[j]--; } } } } for(i=0;i<t*t;i++){ max=0; maxLoc=0; for(j=0;j<t;j++){ if(counts[j]>=max&&nodes[j]){ max=counts[j]; maxLoc=j; } } if(max>0){ for(j=0;j<t;j++){ if(adjMat[maxLoc][j]){ counts[j]--; if(counts[j]<max-1&&stor[j]&&!nodes[j]){ nodes[j]=1; for(k=0;k<t;k++){ if(adjMat[j][k])counts[k]++; } } } nodes[maxLoc]=0; } } else{ break; } } maxRemainder=Math.max(maxRemainder,nodes.reduce(sum)) //console.log(nodes.reduce(sum)); } console.log(maxRemainder); } else{ for(i=0;i<t*t;i++){ max=0; maxLoc=0; for(j=0;j<t;j++){ if(counts[j]>=max&&nodes[j]){ max=counts[j]; maxLoc=j; } } if(max>0){ for(j=0;j<t;j++){ if(adjMat[maxLoc][j]){ counts[j]--; if(counts[j]<max-1&&stor[j]&&!nodes[j]){ nodes[j]=1; for(k=0;k<t;k++){ if(adjMat[j][k])counts[k]++; } } } nodes[maxLoc]=0; } } else{ break; } } console.log(nodes.reduce(sum)); } ``` [Try it online!](https://tio.run/nexus/javascript-node#nVdLb@M2EL7nV2wWiCH6tbGxBRaQqUuvbQ9boBdBB8VWoocleSW5dpDVz@45HXJImaQo2VkfZGs4w/nm8Q3p90/wSYrDsaFf3Tv2kofn38uiiLZNUhY1/YbS4ph/D4sd/Q1f@SMO8zwpXmrqByiNqXOevxLqvVVR80@4p4/uKU72kXP@@fOVvCXPzvlhfU9fH9YEFWYz9@x5dOW@smcLwmNVfMK1Fvd8LisnoavNxuEoFyviJht45W9uMpuRN66Hmim4TNmys55yDeKmikqHuYMsDTMwzMSmmWbR2SwPxzp2YsdJPS8jD44EQeYJIZfd2u5X9OPIc2BxJFO33EfFSxP3XEKqpNe0TArn82dCqTTys6CTalbS5crVhE9VFGaqqLWABY/33Jp02DBefOsCRAt8hrv0z7DpcomleoT6gDReHsoT1my2motaqOWqypNShUvxhmz1OoI14ns0kElUuApqYh1Xi3IXsX79Bbzc1E8CWdDW2MMsqWpbH/NLH2zj7C@E4QeW@LEH9WjBhNFJbdqG9kCnSheCxxltpl3LJIGfqtb5oUeBCtxXG4lOhlEZnYk9bOybbRANyBx9abqWuTRbHDA2ZSVroW5fA5C6A@JXgcRS97bATbDWioFfB0TTa@/sNpmuBmlBOdMg1yhzKaQ1k2yzgSR2SebOQBEwk56HVus8qGhwYfalX8yC6Z0DZPibNd/Nww4NZv3uysi0y3AawAyyDxG0v6cAlyATOXIf5QEVMvEqorLMloYWalQG2fTJz2aXpKcSzCVUa5gMRsICkZiygNN7oA74ZEx2wvkTHHLh7AlhbeGcLPfRcl@@OAi6inbHbeSwHBCp0p2oZ@qdVQ2hcCyaWiBZ5uHBUUxEJwq@jOfi0ttdRtR5Baf79ygPk2IXVXIk8ccLHBJNVPVnYy/Vct/JBEHDT0@/NCiZFtsiosR6ityJffEWQr9qB/qJ3SE2chdshqm4jLgnrahDkLXhzdID37bj@pYS8M4sIYPlvxFS5Hlfgl/@swJMZe4QiW@6JjZwwnwySYy4eqjZhsNedGNtWnVVEjo@MwoCY3jaVNTrij5nzDNJZTxjD7eHydBTkZmFtcXCNRbbwTFtm7i2dE771YZu1OMAwR/lVpeNRwZxdag9CvaTSSFGXy9A5q5TdvuLzHXq3hAodwsG3qPh4/YqoLuP10GPeAPbLFaTCWdLCky/Hwz@0khpYF48r49hWwj8cCECSxbAfwSLQXt3TWK@I0iRH7PNh@oR7evo7eOXaW3K4s0oPDuqdD5wULDPly/jJ4p54VW1VR/a4FcjGWOPwZ0@c8Z68XbWjHDGxpiBfyx9rlxl9XWejLDklzkyxpBb@PEhdrQ3z9hRVthybvLBYEM70plDfdy@v/9XlIttuI2j/wE "JavaScript (Node.js) – TIO Nexus") **Snippet that can be added the end of the program to show what Hamming distance sequences each selected Hamming distance sequence** ``` for(i=0;i<t;i++){ if(nodes[i]){ tmp=[] for(j=0;j<input;j++){ tmp.unshift(Math.floor(i/Math.pow(input+1,j))%(input+1)) } console.log(tmp.join("")) output="" for(j=0;j<t;j++){ if(adjMat[i][j]&&stor[j]){ outArr=[] for(k=0;k<input;k++){ outArr.unshift(Math.floor(j/Math.pow(input+1,k))%(input+1)) } output+=" "+outArr.join(""); } } console.log(output) } } ``` ## Explanation: First, the code generates all unique hamming distances from the substrings. ``` input=3; hammings=[]; h=(x,y)=>{retVal=0;while(x||y){if(x%2!=y%2)retVal++;x>>=1;y>>=1}return retVal}; for(i=1<<(input-1);i<1<<input;i++){ for(j=0;j<1<<(2*input);j++){ hamming=[]; for(k=0;k<input;k++){ hamming.push(h((j>>k)%(1<<input),i)); } equal=0; for(k=0;k<hammings.length;k++){ if(hamming.join("")==hammings[k].join("")){ equal=1; break; } } if(!equal)hammings.push(hamming); } } ``` Next, the code converts this list into an undirected graph ``` adjMat=[]; for(i=0;i<Math.pow(input+1,input);i++){ row=[]; for(j=0;j<Math.pow(input+1,input);j++){ row.push(0); } adjMat.push(row); } nodes=[] for(i=0;i<Math.pow(input+1,input);i++){ nodes[i]=0; } for(i=0;i<hammings.length;i++){ sum=0; chkNodes=[[]]; for(j=0;j<input;j++){ chkVal=[]; t=Math.pow(input+1,j); sum+=t*hammings[i][j]; tmp=[]; for(r=0;r<chkNodes.length;r++){ for(k=hammings[i][j];k<=Math.min(hammings[i][j]*2,input);k++){ stor=[] for(s=0;s<chkNodes[r].length;s++){ stor.push(chkNodes[r][s]) } stor.push(k) tmp.push(stor); } } chkNodes=[]; for(r=0;r<tmp.length;r++){ chkNodes.push(tmp[r]) } } nodes[sum]=1; for(j=0;j<chkNodes.length;j++){ adjSum=0 for(k=0;k<input;k++){ adjSum+=Math.pow(input+1,k)*chkNodes[j][k] } if(adjSum!=sum)adjMat[sum][adjSum]=adjMat[adjSum][sum]=1 } } ``` Finally, the code cycles through this graph, removing the vertex with the most connections each cycle before restoring any nodes that would now have less connections than the current maximum. When it has finished with this cycle it outputs the number of remaining nodes ``` t=nodes.length; for(i=0;i<t;i++){ if(!nodes[i]){ for(k=0;k<t;k++){ adjMat[i][k]=adjMat[k][i]=0 } } } sum=(a,b)=>a+b; counts=adjMat.map(x=>x.reduce(sum)); stor=[]; for(i=0;i<t;i++){ stor.push(nodes[i]); } for(i=0;i<t*t;i++){ max=0; maxLoc=0; for(j=0;j<t;j++){ if(counts[j]>=max&&nodes[j]){ max=counts[j]; maxLoc=j; } } if(max>0){ for(j=0;j<t;j++){ if(adjMat[maxLoc][j]){ counts[j]--; if(counts[j]<max-1&&stor[j]&&!nodes[j]){ nodes[j]=1; for(k=0;k<t;k++){ if(adjMat[j][k])counts[k]++; } } } nodes[maxLoc]=0; } } else{ break; } } console.log(nodes.reduce(sum)); ``` ## Sets: 1: ``` 0 1 ``` 2: ``` 00 01 10 12 21 ``` 3: ``` 000 001 011 013 030 031 100 101 110 111 123 130 132 203 213 231 302 310 312 321 333 ``` 4: ``` 0000 0001 0011 0111 0124 0133 0223 0230 0232 0241 0313 0320 0322 0331 0403 0412 1000 1001 1013 1021 1100 1102 1110 1111 1134 1201 1224 1233 1243 1304 1314 1323 1330 1332 1342 1403 1413 1420 1422 2011 2033 2124 2133 2140 2142 2214 2230 2241 2303 2313 2320 2331 2411 3023 3032 3040 3041 3101 3114 3123 3130 3132 3141 3203 3213 3220 3231 3302 3310 3312 3321 3334 3343 3433 4031 4113 4122 4131 4210 4212 4221 4311 4333 ``` 5: ``` 00000 00001 00011 00111 00123 01112 01235 01244 01324 01343 02111 02230 02234 02333 02342 02432 02441 02522 02530 02531 03134 03142 03220 03224 03233 03241 03314 03323 03331 03403 03412 03421 03520 04133 04141 04214 04223 04232 04303 04313 04322 05042 05050 05051 05132 10000 10001 10011 10122 10212 10221 10245 11000 11001 11013 11022 11100 11112 11120 11121 11202 11211 11345 11353 11443 12012 12111 12201 12245 12253 12335 12344 12352 12425 12430 12434 12442 12513 12532 13033 13042 13244 13252 13325 13330 13334 13342 13404 13424 13433 13441 13520 13522 13531 14032 14051 14140 14152 14225 14230 14234 14241 14243 14304 14315 14324 14332 14413 14420 14422 14431 15041 15050 15125 15133 15142 15215 15223 15232 20112 20135 20211 20253 20334 20352 21012 21021 21102 21110 21111 21201 21245 21344 21352 21430 21433 21442 21514 21523 22011 22101 22135 22244 22252 22325 22334 22340 22343 22405 22415 22424 22441 22520 22522 22531 23041 23144 23150 23152 23225 23234 23240 23243 23251 23304 23315 23324 23333 23341 23403 23413 23420 23432 23521 24031 24050 24125 24130 24134 24142 24151 24215 24224 24233 24303 24314 24320 24323 24331 24412 24421 25123 25132 25141 25203 25214 25222 25231 25302 25312 25321 30234 30243 30252 30324 30333 30340 30342 30414 30423 30430 30432 31011 31235 31244 31253 31325 31334 31340 31343 31405 31415 31424 31432 31441 31504 31521 32025 32034 32100 32144 32152 32225 32234 32240 32243 32251 32304 32315 32324 32330 32333 32342 32403 32414 32423 32512 33024 33031 33033 33125 33134 33140 33143 33151 33215 33224 33230 33233 33242 33303 33314 33320 33323 33332 33412 33431 34124 34133 34203 34214 34223 34232 34241 34310 34313 34322 34411 35202 35213 35221 35311 40323 40332 40341 40431 40505 40513 41135 41144 41240 41243 41252 41324 41330 41333 41342 41403 41414 41423 41512 42033 42134 42143 42230 42233 42242 42303 42310 42314 42323 42332 42341 42413 42422 42431 43023 43124 43130 43133 43142 43203 43220 43223 43232 43241 43302 43313 43322 43331 43421 44114 44123 44132 44210 44213 44222 44231 44312 44321 50413 50422 50504 51233 51242 51251 51323 51332 51341 51413 51422 52023 52133 52142 52151 52223 52232 52241 52313 52322 52331 52421 53102 53114 53122 53210 53213 53321 54201 54212 54221 54311 ``` ]
[Question] [ You are an employee at the hip new grocery store Half Foods, and it's the day before ~~Thanksgiving~~ ~~Christmas~~ Easter. Since the store will be packed with customers rushing to get their foodstuffs, the store needs a traffic manager to send everyone to the appropriate lines. Being lazy, you'd like to automate this so that you can go hit the deli before everyone takes all the ~~turkey~~ ~~ham~~ whatever. However, all you have with you is your phone, and coding long programs on it is a real pain -- so you need to bust out your ninja [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") skills. ## Challenge Let's visualize the grocery store on a two-dimensional grid. Here's a sample grid to dissect: ``` e s s s Y # # #s # #s # #s # #s # #s # #s #s #s # #3 #1 #4 # x x x x ``` The grid starts out with an `e`, which represents an "outlet" to the rest of the store. Every generation, all of the outlets in the grid spawn a shopper (`s`) directly below. The shoppers move downward each generation until they reach you (`Y`). When a shopper reaches the same row as you, you must teleport the shopper to the beginning of the line with the least amount of shoppers in it. A shopper immediately moves to the line when they would move into the row with the `Y`, there is no generation in between. The lines are represented by the `#`s -- the column after the `#`s is a line. The shoppers go down to the end of the line (represented by an exit `x`), and then turn into a random number between `1` and `5`. Each generation, you must decrement numbered shoppers by `1` -- when a shopper would reach `0`, they're done checking out and they leave the store. Given an input of a grid like this, output the next generation of the grocery store (move all the shoppers down simultaneously, redirect shoppers, and have them leave if they are done). ## Samples Input: ``` e Y # # # # # # # # # # # # # # # # # # # # x x x x ``` Output: ``` e s Y # # # # # # # # # # # # # # # # # # # # x x x x ``` Input: ``` e s Y # # # # # # # # # # # # # # # # # # # # x x x x ``` Output ``` e s Y #s # # # # # # # # # # # # # # # # # # # x x x x ``` Input: ``` e Y # # # # # # # # # # # # #s # # # # # # # x x x x ``` (Possible) Output: ``` e s Y # # # # # # # # # # # # # # # # #3 # # # x x x x ``` Input: ``` e s Y # # # # # # # # # # # # # # # # #3 # # # x x x x ``` Output: ``` e s Y # #s # # # # # # # # # # # # # # #2 # # # x x x x ``` Input: ``` e Y # # # # # # # # # # # # # # # # #1 # # # x x x x ``` Output: ``` e s Y # # # # # # # # # # # # # # # # # # # # x x x x ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~477~~ ~~463~~ ~~453~~ ~~449~~ ~~423~~ ~~402~~ ~~397~~ ~~396~~ 393 bytes ``` t=input() e=enumerate q,r=" s" for i,L in list(e(t))[:0:-1]: for j,c in e(L): a=t[i-1][j] if"0"<c<"6":L[j]="0 1234"[int(c)] if(r==a)*q==L[j]:t[i-1][j],L[j]=q+r if"e"==a:L[j]=r if r==L[j]and"x"==t[i+1][j]:L[j]="5" if"Y"in L:x=L.count(r);t[i]=[p.replace(r,q)for p in L] for i,l in list(e(t))[::-1]: for j,c in e(l): if"#"==c and(q==l[j+1])*x:x-=1;l[j+1]=r print"\n".join(map("".join,t)) ``` [Try it online!](https://tio.run/##vZJNbsIwEIXX5BTWsMAGEwH9WRh8g1wAuVlEqVEdBScxRkpPn04S1EUFElEDm5Ht98bzPcvlt/8q7KZpvDS2PHvKAi21PR@1S7wOKu4kkBMEh8IRwyNiLMnNyVNNPWNKrMRyHYuAtHLG01bWNGIimCTSK4OiyuJgYg6wgl26g3cQEZ5IWJH15uUVlLGepqyzUCdlwuaVlK1F/LbzrqNauO4eDejqL@kOiOv9if2EGjVsW3Rtl0FvEBBs2wOiRaKWUZgWZxzq2BatsVRl6HSZJ6mmjlesDVK2MaL4kjn/m/la5LyNjGOmSJASZKEYI1cZorB5LeqlXG/7LVKXDlPDh4UwK4ylx6Sk0K85DmgapWZkxsndRQ8WhpdwFnMykOt0ZXVt@2yuf5f9mFzTWy8yfQT6WFxjAz/yvZ7Itb4lbIYkGf/f1@MJ93DF8Q8 "Python 2 – Try It Online") Still working on golfing this but it solves the problem for now [Answer] ## C++, ~~898~~ ~~896~~ ~~885~~ 841 bytes Very long to code... but it's there -2 bytes thanks to Conor O'Brien -45 byte thanks to Zacharý ``` #include<vector> #include<string> #include<algorithm> #include<ctime> #define B begin() #define L length() #define C(e)if(i[j].find(e)!=string::npos&&! #define S's' #define T size() #define U i[x][a] using namespace std;auto g=[](auto&i){int e=i[0].find('e'),n=0,y=0,h=0,o,j,c,x,t=0;for(auto&a:i)t=a.L>t?a.L:t;for_each(i.B,i.end(),[&i,t](string&s){s.resize(t);});srand(time(0));vector<int>s,l;for(j=0;j<i.T;++j){C(S)y)++n;C(89)0)y=j;C(35)h){h=j;for(int d=0;d<i[j].T;++d)if(i[j][d]==35)l.push_back(d+1);s.resize(l.T);}if(h)for(c=0;c<l.T;c++)if(i[j][l[c]]!=32)++s[c];C('x')0)x=j;}--x;for_each(l.B,l.end(),[&i,&x,h](int&a){if(U!=32)--U;if(U==10)U=32;for(int b=x;b>h;--b){if(i[b][a]==32&&i[b-1][a]==S){i[b][a]=S;i[b-1][a]=32;}}if(U==S)U=49+rand()%5;});if(i[y-1][e]==S)i[h][l[min_element(s.B,s.end())-s.B]]=S;for(j=1;j<n+2;++j)if(j<y)i[j][e]=S;}; ``` So... some details : * You have to pass a `std::vector<std::string>` ( they will be resized at the same length the longest string is ) * All lines of `#` starts at the same y ( vertical ) coordinates, are the same length, and end at the same y ( vertical ) coordinates * Assume that the grid have at least 1 `#` line or more, have one letter `e` ( one outlet ) at the top, one letter `Y` * Assume that the input is a valid output so the shoppers waiting to be redirected will always be one after another Edit : Just saw in the comments of Wheat Wizard's answer that it should support multiple entrances, i will continue to work on that ]
[Question] [ **Question** You have a 50 by 50 character array. Each cell has an arrow pointing in any one of four directions. No cell is empty. On entering a cell, you must exit it in the direction specified by the arrow. The arrow may also point in the same direction you came from, resulting in a dead end. You may start from any cell on the outermost border of the maze and find a path that takes you in the maze, and causes you to exit at some other cell. Input will be given as an array containing <, >, ^ and v. Output will be a single digit (Boolean, integer or character, anything will do) as 0 (indicating that the task is impossible) or 1 (indicating that you have achieved the task). **Example** (actual array will be bigger than this) ``` ^ v < > > < v < v > v ^ ``` Output will be ``` 1 ``` as you can enter from the < on the right, which will cause you to exit from the bottom v by the path "< v v" **The task is to write the shortest possible code that will receive the maze as input, and determine where there exists a path in it as specified in the rules and output a single digit 0 or 1** Outputing TRUE and FALSE instead of actual digits is also allowed. [Answer] # CJam, ~~89~~ 81 bytes ``` q~"><v^":A2/{f{\*}z}/sA[1W52-52]er:T,,{[52md]51f%0e=1=},:E{[2704{__T=+}*]\-E&},,g ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%22%3E%3Cv%5E%22%3AA2%2F%7Bf%7B%5C*%7Dz%7D%2FsA%5B1W52-52%5Der%3AT%2C%2C%7B%5B52md%5D51f%250e%3D1%3D%7D%2C%3AE%7B%5B2704%7B__T%3D%2B%7D*%5D%5C-E%26%7D%2C%2Cg&input=%5B%22%3E%3C%3Evv%5E%3C%3C%5Evvvv%3Ev%3C%3E%5E%3C%3E%3E%3Cvv%5E%3E%5E%3C%5E%3E%3E%3Ev%3E%5Evv%3E%3C%5Ev%3Ev%3E%3E%5Ev%5Ev%5E%22%0A%20%22%3E%3Cv%3Ev%3E%3E%3E%3Cv%5E%5Ev%5E%3E%3E%3C%5E%3E%3C%3Evv%3C%3E%5E%3C%3C%3Cv%5E%5E%3E%3E%5Ev%3Ev%5E%3E%3E%3E%5E%3E%3E%3E%5E%3E%3C%3C%22%0A%20%22%5Ev%5E%5E%3E%5E%5E%3Evv%5E%5E%5E%3Evv%3E%5E%5E%5E%3C%5E%5E%3E%3E%5E%5E%3Cv%5Ev%3E%3C%5E%3E%5Evv%3C%3C%3C%3E%5E%3E%5E%5Ev%3E%3Ev%22%0A%20%22v%3E%5Ev%3C%3E%3C%3E%3C%3E%3C%3E%3C%5E%3E%3C%3Ev%3E%3Ev%3C%3E%3Ev%3Ev%3E%3E%3C%5E%5E%5E%3C%3E%3Evv%3E%3C%5E%3C%3E%3E%3E%3Cv%3C%3C%5E%22%0A%20%22vv%3C%3Cv%3C%5E%3C%3Cvv%5E%3E%3E%5E%3C%3C%3E%5Evvvv%5E%5E%3E%5Evv%3C%3E%5E%3C%5E%3C%3E%5E%3C%3E%3Ev%5E%5E%3E%5E%5E%3E%3C%5Ev%22%0A%20%22v%5E%5E%3C%5E%3E%3C%3Cvv%3Cv%3Ev%5E%3E%3E%3C%3E%3E%3C%3E%3Evv%3C%5E%5E%5E%3C%5E%3Evv%5E%3E%3E%3E%3C%5E%5E%3E%5E%3C%3Cv%5E%5E%3Cv%22%0A%20%22v%3Cvv%3E%3E%5Ev%3Ev%5Ev%3E%5E%5E%5Evv%3Cv%3E%3E%5Evvv%3C%3E%3E%3C%3E%3C%3Cv%5E%5E%5E%3E%3E%3E%3E%3C%5E%5E%5Ev%5E%5E%3C%5E%22%0A%20%22%5Ev%3C%5E%3C%5E%5E%3C%3C%3E%3C%3E%3Cvvvvv%5E%3C%3C%3Cv%3C%3Ev%5E%5E%5E%5E%5E%3Evv%3C%3Ev%3E%5Ev%3E%3Cv%5E%3E%5Ev%5E%3Cv%22%0A%20%22%3C%3E%5Ev%3C%5E%3Cvvv%5E%3E%5E%3Cv%5E%3C%3C%3C%3E%5E%5Ev%5E%5E%3Ev%3Ev%5E%3E%3Evvv%3E%3E%5E%3Cv%5E%3Cv%3E%5E%5Evv%3E%5E%22%0A%20%22%5E%5Evv%3C%3Ev%3C%3Cvv%3C%3C%3Ev%5E%5Ev%3Cvvv%5E%3E%3Cvv%3C%3C%3Evvv%3C%3E%3Ev%3Cv%3C%3E%3E%3E%5E%3C%5E%5E%5E%3E%3E%22%0A%20%22%3C%3C%3Cv%3C%3C%3Evvv%5E%3C%3C%3E%3Cv%5E%5E%3C%5E%5Evv%3Cvvv%5E%3C%3Evv%3Ev%5Ev%3Cv%3C%3E%3C%3E%5E%5E%5E%3E%3E%3E%3Ev%22%0A%20%22v%3Ev%3E%5E%3E%5E%5Ev%5E%3C%3C%3C%5E%3E%3Ev%3Ev%5E%3C%5E%3Ev%5E%3E%3C%5Ev%5E%3E%3C%3C%5Evv%5E%3C%5E%5Ev%5E%5E%5E%5E%3Cv%3E%5E%3C%22%0A%20%22%3Cv%5E%3C%3Ev%3Cv%3E%5E%3C%3C%5E%3E%5E%3C%5E%5Ev%5E%3E%3Cv%3E%3C%3E%3E%5E%3C%3C%3C%5Ev%3E%5Ev%3E%5E%3C%5E%5E%3Ev%5E%3C%5E%3Cv%5E%3C%22%0A%20%22v%3C%3E%5Ev%5E%3C%3E%3C%3C%3E%5E%3C%3E%3C%3E%3E%3Ev%5E%3C%3Ev%3E%5E%3C%5Ev%3C%3Cvv%5E%3E%3E%3E%3C%3C%3E%3Ev%3E%5E%3E%3C%3E%5E%3Evv%22%0A%20%22v%5E%5E%3Cv%3C%3C%3Ev%3E%3C%5E%3C%3Ev%5E%3Cv%5E%3E%3E%5E%5E%3E%3C%3C%5E%3E%3C%5E%3C%3Cv%5Ev%3E%5E%5E%5E%5E%3E%3Ev%5E%5E%5E%3Ev%3Ev%22%0A%20%22vv%5E%5Ev%5E%5E%5E%3C%3E%5E%5E%5E%3C%3C%3E%3E%3Cv%5E%3E%3E%5Evvv%5E%5E%3Ev%3Evv%3E%3C%3E%5E%3C%3E%3C%3E%3Cv%3E%5Ev%3E%3E%3E%5E%22%0A%20%22%3E%5E%5Ev%3C%3E%3E%3E%5Ev%3E%3Evv%3E%5E%5E%3E%3E%3Cv%3C%3E%3C%3C%3C%5E%3C%3E%3C%3E%5E%3Cv%3Ev%3C%5Ev%3Cv%3Ev%3E%5Ev%5E%3Ev%3C%22%0A%20%22%3E%3E%3E%3Cv%3E%5E%3C%5Evvv%3E%5E%3Cvv%5E%3E%5E%5E%3E%3Evv%3E%3Ev%5Ev%3Cvv%3Cv%5Evvv%3C%3E%5E%3C%3E%3C%3E%3E%3C%3E%5E%22%0A%20%22%3E%5E%3Evv%5E%3Cv%5E%5E%3E%3C%3E%3C%3Cvv%5E%5E%3E%3Ev%3C%5E%5Ev%5E%3C%5E%3C%3C%5Ev%3Ev%3C%3C%5E%3C%3E%3C%3Evv%3E%5Ev%3Cv%3C%22%0A%20%22v%3C%3C%3E%5E%3C%3C%5Ev%5E%3C%5E%5Ev%5E%3E%3E%3C%3C%5E%3E%3E%3E%5E%3E%3E%3Cv%3C%3Cv%3C%3Cvv%3C%3C%3E%5Evv%5Ev%3Ev%3E%5E%5E%3Ev%22%0A%20%22%3C%3E%5Ev%3E%3C%5E%5E%3C%5Ev%5E%3Ev%3Ev%3Cv%3C%3C%3E%3E%5E%3Ev%5E%5E%3Cv%5E%3C%5E%5E%3Cv%5E%3E%5Ev%5E%3Cvvvv%5E%3C%5Evv%22%0A%20%22%3E%3E%3Cv%5E%3C%5E%3Cv%3E%3E%3Cvv%3C%3E%5E%3C%3C%3C%3E%3C%5E%3C%3C%5Evv%3E%3C%5Ev%3E%3Ev%3C%3E%5E%3E%5E%3C%3C%5E%3Cv%3Evv%3Ev%22%0A%20%22%5Evv%3E%3C%3Evv%3Ev%3E%3E%3E%3C%5E%5Ev%3E%3E%3E%5E%3Cv%3E%3Cv%3Cv%3E%5E%3C%3Ev%5Evvv%5Ev%3E%5E%3E%3C%5E%3Evvv%3Ev%22%0A%20%22%3C%5Ev%3Cv%5E%5E%3E%3E%3C%5Ev%3C%3C%3E%3C%5Evv%5E%5Evv%3C%5Ev%3E%5E%3E%5E%3E%3C%3Ev%3Cv%3Cv%3C%3C%5E%3Cv%5E%5E%5Ev%3Cv%3C%22%0A%20%22%3Cvv%5E%5E%5E%5E%3C%5E%3E%5E%3C%3E%3C%3E%3C%3C%3Cvv%3E%3C%3C%5Ev%5Ev%3E%3C%3E%3Cv%3Ev%3C%3E%5E%3E%3C%3E%3E%3E%5E%5E%3C%3Evv%3Ev%22%0A%20%22v%3Evv%3C%3E%5Ev%3C%5E%3E%3C%3Evv%3E%3C%3E%5E%3Ev%3C%5E%3E%3E%5E%3C%3E%3Ev%3C%3Cvv%5Ev%5E%3E%3E%3E%5E%5Ev%5E%5E%3C%3E%5Ev%5E%22%0A%20%22%5E%3E%5E%5Ev%3C%3E%5Evv%5E%3E%3E%3Cv%3C%3C%5Ev%3Evvv%3E%5E%5E%3C%3Cv%3E%5E%3Ev%3E%3Ev%3C%3E%3Ev%5E%3Ev%3E%5Ev%3E%3Cv%3E%22%0A%20%22v%3C%3E%3E%3E%5E%3C%3E%3C%5E%3C%3Ev%5E%3C%3C%3C%3C%5E%3C%3Cvv%3Evv%5Ev%3C%5E%3Cv%3C%5E%3Cv%3Ev%5E%5E%3C%3E%5Ev%3E%3E%3C%3E%5E%3E%22%0A%20%22%3C%3Cv%3Ev%3E%5E%3E%3C%5E%5E%3E%3C%3Evvvvv%3E%3Ev%3C%3E%5E%3E%5E%3C%3C%5Evv%5E%3C%3C%5Ev%3C%3C%3E%3E%3Cv%5E%5E%3E%5E%3Ev%3E%22%0A%20%22vvv%3Evvvv%3E%3E%3C%3Cv%3Ev%3Evv%5E%5E%3C%5E%5E%3C%3E%3C%5E%5E%3C%3Cv%3E%3Cv%3Cv%3C%5E%5E%3Ev%3C%5E%3C%3C%5Evvvv%22%0A%20%22v%3C%3Evv%3C%3E%3Ev%5E%5E%3C%3E%3Ev%5E%3Ev%5E%5Ev%3Ev%3E%3Evv%5E%3Cv%3E%3Ev%5E%3C%3E%3E%5E%3C%3E%3Cv%3E%5E%3Cv%5E%3C%5Ev%22%0A%20%22%3E%3E%5E%3C%5E%3E%3E%5E%3E%3E%3Ev%5E%3E%3E%5E%5E%3E%3C%5E%5E%3C%3C%3E%5E%5E%3E%3E%3C%5Ev%5E%3E%3Evvv%3E%5E%3E%3E%3C%3E%3C%5E%3Cvv%5Ev%22%0A%20%22%5Ev%5E%3Cvvv%3E%3C%5Ev%3E%3C%3E%3E%3Ev%5E%3C%3E%3E%3C%3E%5E%3E%3C%3C%3E%3E%5E%3Ev%5Ev%3C%5E%5E%5Ev%3C%3E%3Ev%3Evvv%3E%3E%3E%22%0A%20%22%3C%3C%3E%3E%3Cv%3E%3E%3Cv%3E%5E%5E%5E%3E%5Ev%3E%3Evv%3Ev%5Ev%5E%3C%3C%3E%3C%3Cv%3Cvv%3Cv%3Cv%5E%3C%3C%5Evv%3Ev%3Cv%5E%22%0A%20%22%5Ev%3E%3E%3C%5Ev%3Cv%3Cv%3C%3Ev%3C%3E%3E%5Ev%3C%3E%3E%5E%3C%3E%5E%3E%3C%3C%5E%3E%5E%5E%3E%3E%3C%3Cv%5E%3C%5E%3C%3C%5E%3E%3E%5E%3E%5Ev%22%0A%20%22%5E%3C%5E%3C%5E%5Ev%5Ev%3C%3E%3C%3Cv%5E%3C%3C%3E%3Ev%3E%3C%3Ev%5E%5Ev%3E%3C%5E%5E%3Ev%3E%5Ev%3Ev%3Ev%5Ev%3C%3C%3C%3E%5E%5E%5E%3C%22%0A%20%22%3E%5E%3C%3C%5E%5E%5Evv%5Ev%3Ev%3C%5E%5E%5Evv%5E%5E%3Ev%3E%3E%5E%3Ev%3C%3E%3C%3Ev%3C%3C%3E%3E%3E%3Cv%3E%5E%3E%3E%3C%5E%3C%3C%3E%5E%22%0A%20%22%5E%3C%5Ev%3E%3Cv%3Ev%3C%3C%3Ev%3C%5E%5E%3E%3Cvv%5E%5Evv%5E%5E%3Ev%5E%3C%3Ev%5E%3C%3E%3E%3C%3C%3C%5E%3Ev%3E%3E%3E%3C%3Cv%3C%5E%22%0A%20%22v%3E%3Cv%3Cv%3C%3E%5E%3E%3E%3C%3C%5E%3C%5E%3E%3C%3C%5E%5E%3Ev%3E%5Ev%3C%3Ev%3C%3Cv%5E%5E%3E%5Ev%5E%5Ev%3Cv%3E%3E%3E%3C%3E%3C%5Ev%22%0A%20%22%3E%5E%3C%5Ev%3E%5Ev%3E%3C%3E%3C%5E%3C%5E%3E%3E%3C%5Ev%3E%3C%3Cv%5Evv%3Cvvv%3E%3C%5E%3E%5E%3E%3C%5E%3C%3E%3E%5E%5E%5E%5Ev%3E%5Ev%22%0A%20%22%3Cv%5E%3E%5Evvv%3C%5E%3C%3Cv%5Ev%3C%3C%5E%5E%3Ev%3Ev%3C%5Evv%3C%3C%3E%3E%5E%3C%3Ev%5E%5E%5E%5E%3Ev%3Ev%5E%5E%3Ev%5E%3E%3C%22%0A%20%22v%5E%3E%3E%5E%3C%5Ev%3E%5E%3E%5E%5E%3Ev%3E%3Ev%3E%5E%5Ev%3Ev%3Ev%3Cv%3C%3C%5Ev%5E%3C%3E%5E%5E%3C%5E%3E%3E%3Cv%3E%5E%3C%3C%5E%5Ev%22%0A%20%22v%5E%5E%3C%5E%5E%3C%5Ev%5E%5E%3C%3E%3C%3E%3Ev%3E%5E%3E%3Cv%3Ev%3C%3E%3Ev%3C%5E%3C%3Ev%3E%5E%3E%5E%3E%5E%3C%5E%3Cv%3E%5Ev%3E%3C%3E%5E%22%0A%20%22%3C%3C%3C%3C%3C%3C%3E%3C%3C%5Ev%3C%5Ev%5E%3Evv%3Ev%3E%3C%3Cv%3C%3C%3E%3Ev%3Ev%3Cv%3E%3Evv%5E%5E%3C%3C%3E%3Ev%5E%5Evvvv%22%0A%20%22%3E%5Ev%3C%3C%5E%3Cvv%5E%5E%3C%5Ev%3E%3C%3C%5E%3C%5E%5E%5E%5E%3E%3E%3E%3C%3C%3C%3Cv%5E%3Ev%3E%5Ev%5E%3Evv%3E%3Evv%3C%3Cv%5E%3C%22%0A%20%22%3E%5Ev%5E%3C%3C%3Cv%5E%3E%5Ev%3Cv%3Cv%3E%3Cv%3C%3C%3E%5E%3C%3C%3E%3Ev%3E%5E%3E%3C%3Cv%5Ev%5E%3C%3E%3Ev%3E%5E%3Ev%3Cvv%5E%3C%22%0A%20%22v%3E%5E%3E%5Ev%3Cv%3E%3C%3Ev%3Evv%3E%3E%3E%3E%5E%3C%3E%5E%5E%3Ev%3C%3E%3C%3E%5E%3E%5E%3C%5Ev%3C%5Ev%5E%5E%3C%3Ev%3E%3C%3Ev%5E%3C%22%0A%20%22%3Cv%5E%3E%3Ev%3Ev%3C%3C%3E%3C%5E%5E%3Cv%3E%3C%3E%5E%3E%5E%3E%3E%3Ev%3C%3C%3E%3E%5E%3C%3E%3E%3C%3E%3E%3Cv%3E%3E%3E%5Ev%3E%3Cv%3Ev%3E%22%0A%20%22vv%5Ev%3Ev%3Evv%5E%5E%3E%5E%3C%5E%3E%5E%5Ev%5Ev%3C%5E%5Evv%3Cv%5Evv%3E%3Cv%3C%3Ev%5E%3C%3C%5Ev%3E%5Ev%3C%3Ev%5E%5E%22%0A%20%22%3Cv%5Evv%3C%3C%5Evv%5E%5E%5Ev%5E%3C%5E%5E%3Ev%3C%5E%5E%5E%5Ev%3E%3E%3E%3C%3E%5E%3C%5E%5E%3Evv%3C%3E%3C%5E%5E%3E%3C%3E%3C%5Evv%22%5D). ### How it works ``` q~ e# Read and evaluate all input. This pushes an array of strings. "><v^":A e# Push that string and save it in A. 2/ e# Split it into ["><" "v^"]. { e# For each chunk: f{ e# For each input string, push the string and the chunk; then: \* e# Join the chunk, using the string as separator. } e# z e# Transpose rows and columns. }/ e# s e# Flatten the resulting array of strings. A e# Push "><v^". [1W52-52] e# Push [1 -1 52 -52]. er e# Perform transliteration. :T e# Save the result in T. ,, e# Push [0 ... 2703]. { e# Filter; for each integer I in [0 ... 2703]: [52md] e# Push [I/52 I%52]. 51f% e# Take both integers modulo 51 to map 51 to 0. 0e= e# Count the number of resulting zeroes. 1= e# Check if the count is 1. }, e# If it is, keep I. :E e# Save the filtered array in E. { e# For each integer I in E: [2704{ e# Do 2704 times: __ e# Push two copies of the integer on the stack. T= e# Select the corresponding element from T. + e# Add it to the first copy. }*] e# Collect all results in an array. \- e# Remove I from that array. E& e# Intersect with E. }, e# If the intersection is non-empty, keep the integer. ,g e# Push the sign of the length of the filtered array. ``` ]
[Question] [ This challenge is the first of a series of [fewest-operations](/questions/tagged/fewest-operations "show questions tagged 'fewest-operations'") problems that should be written in the [GOLF CPU](https://codegolf.meta.stackexchange.com/questions/5134/the-golf-cpu-framework). You can find the next one [here](https://codegolf.stackexchange.com/questions/52825/the-golf-cpu-golfing-challenge-sides-of-a-cuboid) A partition of a number, `N`, is a list of numbers that add up to `N`. A *prime partition* is a list of prime numbers that add up to `N`. For this challenge, you are given a single integer `N ≥ 2`. You need generate the shortest possible prime partition for `N`. If there are multiple possible partitions, you can print any of them. Examples: ``` 9: [2, 7] 12: [5, 7] 95: [89, 3, 3] 337: [337] 1023749: [1023733, 13, 3] 20831531: [20831323, 197, 11] ``` Your program should be written in [GOLF CPU](https://codegolf.meta.stackexchange.com/questions/5134/the-golf-cpu-framework). For input/output you can either use STDIO or the registers. The list can be in any order, and if you are using STDOUT, can be separated by whitespace or commas (no brackets needed). Obviously, hardcoding the solutions isn't allowed, nor is hardcoding more than the first few primes. This is a [fewest-operations](/questions/tagged/fewest-operations "show questions tagged 'fewest-operations'") problem, so the answer that solves the examples above with the fewest amount of cycles wins! [Answer] # Total cycles for examples: 477,918,603 **Update 1:** Updated to use [Lemoine's conjecture](https://en.wikipedia.org/wiki/Lemoine's_conjecture). **Update 2:** Updated to use the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) instead of naively finding the primes. Run with: ``` python3 assemble.py 52489-prime-partitions.golf python3 golf.py 52489-prime-partitions.bin x=<INPUT> ``` Example run: ``` $ python3 golf.py 52489-prime-partitions.bin x=10233 5 5 10223 Execution terminated after 194500 cycles with exit code 0. ``` Cycle count for example input: ``` Input Cycles 9 191 12 282 95 1,666 337 5,792 1023749 21,429,225 20831531 456,481,447 ``` We consider the first `(N+1)*8` bytes of the heap, to be an array containing `N+1` 64-bit values. (As the heap is limited in size, this will only work for `N < 2^57`). The value of the entry at `i*8` indicates wether `i` is a prime: ``` Value Description -1 Not a prime 0 Unknown 1 The largest prime found n > 1 This is a prime and the next prime is n ``` When we are done building the array it will look like `[-1, -1, 3, 5, -1, 7, -1, 11, -1, -1, -1, 13, ...]`. We use the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to build the array. Next the program does the following in pseudo-code: ``` if is_prime(x): print x else: if is_even(x): for p in primes: if is_prime(x - p): print p, x - p exit else: if is_prime(x - 2): print 2, x - 2 else: for p in primes: if is_prime(x - 2 * p): print p, p, 2 * p exit ``` This is guaranteed to work because of [Lemoine's conjecture](https://en.wikipedia.org/wiki/Lemoine's_conjecture) and [Goldbach's weak conjecture](https://en.wikipedia.org/wiki/Goldbach%27s_weak_conjecture). Lemoine's conjecture hasn't be proven yet, but it's probably true for numbers below 2^57. ``` call build_primes mov q, x call is_prime jnz print_prime, a and b, x, 1 jz find_pair, b # Check if x - 2 is a prime sub q, x, 2 call is_prime jnz print_prime_odd2, a # Input: x, b find_pair: mov p, 2 find_pair_loop: mov d, p jz find_pair_even, b add d, d, p find_pair_even: sub q, x, d call is_prime jnz print_prime2_or_3, a shl i, p, 3 lw p, i jmp find_pair_loop print_prime2_or_3: jz print_prime2, b mov x, p call write_int_ln print_prime2: mov x, p call write_int_ln mov x, q call print_prime print_prime_odd2: mov p, 2 call print_prime2 print_prime: call write_int_ln halt 0 # Input: x # Memory layout: [-1, -1, 3, 5, -1, 7, -1, 11, ...] # x: max integer # p: current prime # y: pointer to last found prime # i: current integer build_primes: sw 0, -1 sw 8, -1 sw 16, 1 mov y, 16 mov p, 2 build_primes_outer: mulu i, r, p, p jnz build_primes_final, r geu a, i, x jnz build_primes_final, a build_primes_inner: shl m, i, 3 sw m, -1 add i, i, p geu a, i, x jz build_primes_inner, a build_primes_next: inc p shl m, p, 3 lw a, m jnz build_primes_next, a sw y, p mov y, m sw y, 1 jmp build_primes_outer build_primes_final: inc p geu a, p, x jnz build_primes_ret, a shl m, p, 3 lw a, m jnz build_primes_final, a sw y, p mov y, m sw y, 1 jmp build_primes_final build_primes_ret: ret # Input: q # Output: a is_prime: shl m, q, 3 lw a, m neq a, a, -1 ret a write_int: divu x, m, x, 10 jz write_int_done, x call write_int write_int_done: add m, m, ord("0") sw -1, m ret write_int_ln: call write_int mov m, ord("\n") sw -1, m ret ``` [Answer] # 159,326,251 cycles Input is `n`, output is `r`, `s`, and `t` (ignoring zeros). ``` # Input in register n # Outputs in registers r, s, t # (I use the return value as a debug parameter) # hardcoded case n=2 cmp c, n, 2 jz skip_n2, c mov r, 2 halt 0 skip_n2: # hardcoded case n=4 cmp c, n, 4 jz skip_n4, c mov r, 2 mov s, 2 halt 0 skip_n4: # Sieve of Eratosthenes mov i, 1 sieve_loop: add i, i, 2 lb a, i jnz sieve_loop, a mulu j, k, i, i geu c, j, n jnz end_sieve_loop, c sieve_inner_loop: sb j, 1 add j, j, i lequ c, j, n jnz sieve_inner_loop, c jmp sieve_loop end_sieve_loop: lb a, n # if n is even, skip to search and c, n, 1 jz search, c # if n is prime, the partition is simply [n] jnz not_prime, a mov r, n halt 1 not_prime: # if n is odd, check n-2 sub i, n, 2 lb a, i jnz sub_3, a # if n-2 is prime, the partition is [2, n-2] mov r, 2 mov s, i halt 2 sub_3: # otherwise the partition is [3] + partition(n-3) mov t, 3 sub n, n, 3 search: mov i, 1 sub n, n, 1 search_loop: add i, i, 2 sub n, n, 2 lb a, i jnz search_loop, a lb a, n jnz search_loop, a mov r, i mov s, n halt 3 ``` Testcases: ``` robert@unity:~/golf-cpu$ ./assemble.py partition.golf robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=9 2, 7, 0 Execution terminated after 51 cycles with exit code 2. robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=12 5, 7, 0 Execution terminated after 77 cycles with exit code 3. robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=95 3, 89, 3 Execution terminated after 302 cycles with exit code 3. robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=337 337, 0, 0 Execution terminated after 1122 cycles with exit code 1. robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=1023749 13, 1023733, 3 Execution terminated after 6654139 cycles with exit code 3. robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=20831531 229, 20831299, 3 Execution terminated after 152670560 cycles with exit code 3. robert@unity:~/golf-cpu$ ``` ]
[Question] [ # Scriptbot Warz! --- The results are in and *Assassin* is our champion, winning 2 of 3 matches! Thanks to everyone who submitted their Scriptbots! Special thanks to *horns* for *BestOpportunityBot* which displayed excellent pathing and made full use of all action options. **Map 1** Assassin took out BestOpportunityBot early on, and the rest of the match was pretty boring. [Detailed play-by-play here.](http://tny.cz/44c46ac2) 1. Assassin: 10 HP, 10 Damage Dealt, 3 Damage Taken 2. The Avoider v3: 10 HP, 0 Damage Dealt, 0 Damage Taken 3. Gotta Finish Eating: 10 HP, 0 Damage Dealt, 0 Damage Taken 4. BestOpportunityBot: 0 HP, 3 Damage Dealt, 10 Damage Taken **Map 2** BestOpportunityBot did most of the work on this match, but Assassin was able to take him out in the end. [Detailed play-by-play here.](http://tny.cz/6743ba03) 1. Assassin: 2 HP, 10 Damage Dealt, 9 Damage Taken 2. BestOpportunityBot: 0 HP, 32 Damage Dealt, 10 Damage Taken 3. The Avoider v3: 0 HP, 0 Damage Dealt, 12 Damage Taken 4. Gotta Finish Eating: 0 HP, 0 Damage Dealt, 11 Damage Taken **Map 3** BestOpportunityBot pushed everyone into traps on this match. Very cool. [Detailed play-by-play here.](http://tny.cz/dabfd2a8) 1. BestOpportunityBot: 10 HP, 30 Damage Dealt, 0 Damage Taken 2. Assassin: 0 HP, 0 Damage Dealt, 0 Damage Taken 3. Gotta Finish Eating: 0 HP, 0 Damage Dealt, 0 Damage Taken 4. The Avoider v3: 0 HP, 0 Damage Dealt, 0 Damage Taken --- *Thanks for your answers! Since there are just 4 Scriptbots, we are abandoning the tournament plans for three free-for-all matches, one on each of the maps below. The scriptbot with the highest win record wins. In the event of a tie, we will enter into sudden death wherein the scriptbot who breaks the tie first wins.* --- Your task, should you choose to accept it, is to code a Scriptbot which can traverse an ASCII map and destroy its opponents. Each battle will take the form of a random-starting-order turn-based game where each Scriptbot has a chance to spend their energy points (EP) to take actions. The GameMaster script will feed input to, and interpret output from each Scriptbot. ## Environment Each Scriptbot is contained within its own directory where it can read from the `map` and `stats` files and read/write to the `data` file. The `data` file can be used to store any persistent information you might find useful. ### The stats File The `stats` file contains information about your opponents and is formatted as follows. Each player is represented on a separate row. The first column is a player ID (`@` means you). The second column is the health of that player. ``` 1,9HP @,10HP 3,9HP 4,2HP ``` ### The map File The `map` file might look something like this... ``` #################### # # # # # 1 # # 2 # # # ### ### # # # # # # # ! # # # # # !#### # # ####! # # # # # ! # # # # # # # ### ### # # # 3 # # @ # # # # # #################### ``` ... or this... ``` ###################################### # # 1 # @ # # # # #! # # # # #### # # # # # # !#! # # # # # # ##### # # ### # #### # # # # # #! ### # # # ###### # # # ##### # # #! # ###### # !# # # ### # # # # # # 2 # # 4 # # ###################################### ``` ... or this... ``` ################### ###!!!!!!#!!!!!!### ##! !## #! 1 ! 2 !# #! ! !# #! !# #! !# #! !!! !# ## !! !!! !! ## #! !!! !# #! !# #! !# #! ! !# #! 3 ! @ !# ##! !## ###!!!!!!#!!!!!!### ################### ``` ... or it might look totally different. Either way, the characters used and their meaning will remain the same: * `#` A wall, impassable and impenetrable. * `1`, `2`, `3`... A number representing an enemy player. These numbers correspond to the player ID in the `stats` file. * `!` A trap. Scriptbots who move onto these locations will die immediately. * `@` Your Scriptbot's location. * Open space which you are free to move around in. ## Gameplay The GameMaster script will assign a random starting order to the Scriptbots. The Scriptbots are then invoked in this order while they are still alive. Scriptbots have 10 Health Points (HP), and start with 10 Energy Points (EP) each turn, which they may use to move or attack. At the start of each turn, a Scriptbot will heal for one HP, or be granted one additional EP if already at 10 HP (thus running may be a viable strategy at times). The battle ends when only one Scriptbot survives or when 100 turns have passed. If multiple Scriptbots are alive at the end of a battle, their place is determined based on the following criteria: 1. Most health. 2. Most damage dealt. 3. Most damage taken. ## Scriptbot Input The GameMaster will print the battle map to a file named `map` which the Scriptbot will have access to read from. The map might take any form, so it is important that the Scriptbot be able to interpret it. Your Scriptbot will be invoked with one parameter indicating EP. For example... ``` :> example_scriptbot.py 3 ``` The Scriptbot will be invoked until it spends all of its EP or a maximum of 10 11 times. The map and stats files are updated before each invocation. ## Scriptbot Output Scriptbots should output their actions to stout. A list of possible actions are as follows: * `MOVE <DIRECTION> <DISTANCE>` Costs 1 EP per `DISTANCE`. The `MOVE` command moves your Scriptbot around the map. If there is something in the way such as a wall or another Scriptbot, the GameMaster will move your Scriptbot as far as possible. If a `DISTANCE` greater than the Scriptbot's remaining EP is given, the GameMaster will move the Scriptbot until its EP runs out. `DIRECTION` may be any compass direction of `N`, `E`, `S`, or `W`. * `PUSH <DIRECTION> <DISTANCE>` Costs 1 EP per `DISTANCE`. The `PUSH` command enables a Scriptbot to move another Scriptbot. The Scriptbot issuing the command must be directly next to the Scriptbot being pushed. Both Scriptbots will move in the direction indicated if there is not an object blocking the Scriptbot being pushed. `DIRECTION` and `DISTANCE` are the same as for the `MOVE` command. * `ATTACK <DIRECTION>` Costs one EP. The `ATTACK` command deals 1 damage to any Scriptbot directly next to the issuing Scriptbot and in the direction specified. `DIRECTION` is the same as for the `MOVE` command. * `PASS` Ends your turn. ## Supported Languages To keep this reasonable for me, I will accept the following languages: * Java * Node.js * Python * PHP You are limited to libraries which are commonly packaged with your languages out of the box. Please do not make me locate obscure libraries to make your code work. ## Submission and Judging Post your Scriptbot source code below and give it a cool name! Please also list the version of the language you used. All Scriptbots will be reviewed for tomfoolery so please comment well and do not obfuscate your code. You may submit more than one entry, but please make them totally unique entries, and not versions of the same entry. For instance, you may want to code a Zerg Rush bot and a Gorilla Warfare bot. That's fine. Do not post Zerg Rush v1, Zerg Rush v2, etc. On November 7th I will collect all answers and those which pass the initial review will be added to a tournament bracket. The champion gets the accepted answer. The ideal bracket is shown below. Since there will likely not be exactly 16 entries, some brackets may end up being only three or even two bots. I will try to make the bracket as fair as possible. Any necessary favoritism (in the event that a bye week is needed for instance) will be given to the bots which were submitted first. ``` BOT01_ BOT02_| BOT03_|____ BOT04_| | | BOT05_ | BOT06_|___ | BOT07_| | | BOT08_| | |_BOT ?_ |___BOT ?_| BOT09_ ___BOT ?_|___CHAMPION! BOT10_| | _BOT ?_| BOT11_|__| | BOT12_| | | BOT13_ | BOT14_|____| BOT15_| BOT16_| ``` ## Q&A *I'm sure I've missed some details, so feel free to ask questions!* > > May we trust that a map file is always surrounded by # symbols? If not, what happens in the event that a bot attempts to walk off the map? - BrainSteel > > > Yes the map will always be bounded by # and your Scriptbot will start inside of these bounds. > > If there is no bot present in the direction specified in a PUSH command, how does the command function? - BrainSteel > > > The GameMaster will do nothing, zero EP will be spent, and the Scriptbot will be called again. > > Do unused EP accumulate? - feersum > > > No. Each Scriptbot will start the round/turn with 10 EP. Any EP not spent will go to waste. > > I think I've got it, but just to clarify: with bots A and B, is the order of events A@10EP->MOVE MAP\_UPDATE B@10EP->PUSH MAP\_UPDATE A@9EP->ATTACK MAP\_UPDATE B@9EP->ATTACK ..., or A@10EP->MOVE A@9EP->ATTACK ... MAP\_UPDATE B@10EP->PUSH B@9EP->ATTACK ... MAP\_UPDATE? In other words, is all action in one controller-bot query loop atomic? If so, why the loop? Why not return a single file with all the actions to be completed? Otherwise bots will have to write out their own state files to keep track of multi-action sequences. The map/stats file will only be valid prior to the first action. - COTO > > > Your second example is close, but not quite right. During a turn, the Scriptbot is invoked repeatedly until their EP is spent, or a maximum of 11 times. The map and stats files are updated before each invocation. The loop is useful in the event that a bot gives invalid output. The GameMaster will deal with the invalid output and involke the bot again, giving the bot a chance to correct for it's mistake. > > will you release the GameMaster script for testing? - IchBinKeinBaum > > > The GameMaster script will not be released. I would encourage you to create a map and stats file to test your bot's behavior. > > If robotA pushes robotB into a trap, is robotA credited with "damage dealt" points equal to the current health of robotB? - Mike Sweeney > > > Yes, that is a good idea. A bot will be granted damage points equal to the health of a any bot that it pushes into a trap. [Answer] **The Avoider v3** A simple minded bot. It is afraid of other robots and traps. It will not attack. It ignores the stats file and does not think ahead at all. This is mainly a test to see how the rules would work, and as a dumb opponent for other competitors. Edit: Now will PASS when no MOVE is better. Edit2: Robots can be '1234' instead of '123' The Python Code: ``` import sys maxmoves = int(sys.argv[1]) ORTH = [(-1,0), (1,0), (0,-1), (0,1)] def orth(p): return [(p[0]+dx, p[1]+dy) for dx,dy in ORTH] mapfile = open('map').readlines()[::-1] arena = dict( ((x,y),ch) for y,row in enumerate(mapfile) for x,ch in enumerate(row.strip()) ) loc = [loc for loc,ch in arena.items() if ch == '@'][0] options = [] for direc in ORTH: for dist in range(maxmoves+1): newloc = (loc[0]+direc[0]*dist, loc[1]+direc[1]*dist) if arena.get(newloc) in '#!1234': break penalty = dist * 10 # try not to use moves too fast if newloc == loc: penalty += 32 # incentive to move for nextto in orth(newloc): ch = arena.get(nextto) if ch == '#': penalty += 17 # don't get caught againt a wall elif ch in '1234': penalty += 26 # we are afraid of other robots elif ch == '!': penalty += 38 # we are very afraid of deadly traps options.append( [penalty, dist, direc] ) penalty, dist, direc = min(options) if dist > 0: print 'MOVE', 'WESN'[ORTH.index(direc)], dist else: print 'PASS' # stay still? ``` [Answer] # BestOpportunityBot This ended up being a little longer than I intended...and I'm not sure if I understand the rules for turns completely, so we'll see how this does. ``` from sys import argv from enum import IntEnum with open("map") as map_file: map_lines = map_file.read().splitlines() with open("stats") as stats_file: stats_data = stats_file.read().splitlines() ep = argv[1] class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(lhs, rhs): if (type(rhs) == tuple or type(rhs) == list): return Point(lhs.x + rhs[0], lhs.y + rhs[1]) return Point(lhs.x + rhs.x, lhs.y + rhs.y) def __sub__(lhs, rhs): if (type(rhs) == tuple or type(rhs) == list): return Point(lhs.x - rhs[0], lhs.y - rhs[1]) return Point(lhs.x - rhs.x, lhs.y - rhs.y) def __mul__(lhs, rhs): return Point(lhs.x * rhs, lhs.y * rhs) def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" def __repr__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" def __eq__(lhs, rhs): return lhs.x == rhs.x and lhs.y == rhs.y def __hash__(self): return hash(self.x) * 2**32 + hash(self.y) def reverse(self): return Point(self.y, self.x) dirs = (Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0)) class Bot: def __init__(self, pos, ch, hp): self.pos = pos self.ch = ch self.hp = hp def __str__(self): return str(self.pos) + " " + str(self.ch) + " " + str(self.hp) def __repr__(self): return str(self.pos) + " " + str(self.ch) + " " + str(self.hp) class MyBot(Bot): def __init__(self, pos, ch, hp, ep): self.ep = ep super().__init__(pos, ch, hp) def __str__(self): return super().__str__() + " " + self.ep def __repr__(self): return super().__repr__() + " " + self.ep class Arena: def __init__(self, orig_map): self._map = list(zip(*orig_map[::-1])) self.bots = [] self.me = None def __getitem__(self, indexes): if (type(indexes) == Point): return self._map[indexes.x][indexes.y] return self._map[indexes[0]][indexes[1]] def __str__(self): output = "" for i in range(len(self._map[0]) - 1, -1, -1): for j in range(len(self._map)): output += self._map[j][i] output += "\n" output = output[:-1] return output def set_bot_loc(self, bot): for x in range(len(self._map)): for y in range(len(self._map[x])): if self._map[x][y] == bot.ch: bot.pos = Point(x, y) def set_bots_locs(self): self.set_bot_loc(self.me) for bot in self.bots: self.set_bot_loc(bot) def adjacent_bots(self, pos=None): if type(pos) == None: pos = self.me.pos output = [] for bot in self.bots: for d in dirs: if bot.pos == pos + d: output.append(bot) break return output def adjacent_bots_and_dirs(self): output = {} for bot in self.bots: for d in dirs: if bot.pos == self.me.pos + d: yield bot, d break return output def look(self, position, direction, distance, ignore='', stopchars='#1234'): current = position + direction output = [] for i in range(distance): if (0 <= current.x < len(self._map) and 0 <= current.y < len(self._map[current.x]) and (self[current] not in stopchars or self[current] in ignore)): output += self[current] current = current + direction else: break return output def moveable(self, position, direction, distance): current = position + direction output = [] for i in range(distance): if (0 <= current.x < len(self._map) and 0 <= current.y < len(self._map[current.x]) and self[current] == ' '): output += self[current] else: break return output def danger(self, pos, ignore=None): # damage that can be inflicted on me output = 0 adjacents = self.adjacent_bots(pos) hps = [bot.hp for bot in adjacents if bot != ignore] if len(hps) == 0: return output while max(hps) > 0: if 0 in hps: hps.remove(0) for i in range(len(hps)): if hps[i] == min(hps): hps[i] -= 1 output += 1 return output def path(self, pos): # Dijkstra's algorithm adapted from https://gist.github.com/econchick/4666413 visited = {pos: 0} path = {} nodes = set() for i in range(len(self._map)): for j in range(len(self._map[0])): nodes.add(Point(i, j)) while nodes: min_node = None for node in nodes: if node in visited: if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for _dir in dirs: new_node = min_node + _dir if self[new_node] in ' 1234': weight = current_weight + 1 if new_node not in visited or weight < visited[new_node]: visited[new_node] = weight path[new_node] = min_node return visited, path class MoveEnum(IntEnum): Null = 0 Pass = 1 Attack = 2 Move = 3 Push = 4 class Move: def __init__(self, move=MoveEnum.Null, direction=Point(0, 0), distance=0): self.move = move self.dir = direction self.dis = distance def __repr__(self): if self.move == MoveEnum.Null: return "NULL" elif self.move == MoveEnum.Pass: return "PASS" elif self.move == MoveEnum.Attack: return "ATTACK " + "NESW"[dirs.index(self.dir)] elif self.move == MoveEnum.Move: return "MOVE " + "NESW"[dirs.index(self.dir)] + " " + str(self.dis) elif self.move == MoveEnum.Push: return "PUSH " + "NESW"[dirs.index(self.dir)] + " " + str(self.dis) arena = Arena(map_lines) arena.me = MyBot(Point(0, 0), '@', 0, ep) for line in stats_data: if line[0] == '@': arena.me.hp = int(line[2:-2]) else: arena.bots.append(Bot(Point(0, 0), line[0], int(line[2:-2]))) arena.set_bots_locs() current_danger = arena.danger(arena.me.pos) moves = [] # format (move, damage done, danger, energy) if arena.me.ep == 0: print(Move(MoveEnum.Pass)) exit() for bot, direction in arena.adjacent_bots_and_dirs(): # Push to damage pushable_to = arena.look(arena.me.pos, direction, arena.me.ep + 1, ignore=bot.ch) if '!' in pushable_to: distance = pushable_to.index('!') danger = arena.danger(arena.me.pos + (direction * distance), bot) danger -= current_danger moves.append((Move(MoveEnum.Push, direction, distance), bot.hp, danger, distance)) # Push to escape pushable_to = arena.look(arena.me.pos, direction, arena.me.ep + 1, ignore=bot.ch, stopchars='#1234!') for distance in range(1, len(pushable_to)): danger = arena.danger(arena.me.pos + (direction * distance), bot) danger += bot.hp danger -= current_danger moves.append((Move(MoveEnum.Push, direction, distance), 0, danger, distance)) # Attack bot.hp -= 1 danger = arena.danger(arena.me.pos) - current_danger moves.append((Move(MoveEnum.Attack, direction), 1, danger, 1)) bot.hp += 1 culled_moves = [] for move in moves: # Cull out attacks and pushes that result in certain death if current_danger + move[2] < arena.me.hp: culled_moves.append(move) if len(culled_moves) == 1: print(culled_moves[0][0]) exit() elif len(culled_moves) > 1: best_move = culled_moves[0] for move in culled_moves: if move[1] - move[2] > best_move[1] - best_move[2]: best_move = move if move[1] - move[2] == best_move[1] - best_move[2] and move[3] < best_move[3]: best_move = move print (best_move[0]) exit() # Can't attack or push without dying, time to move moves = [] if current_danger > 0: # Try to escape for direction in dirs: moveable_to = arena.moveable(arena.me.pos, direction, ep) i = 1 for space in moveable_to: danger = arena.danger(arena.me.pos + (direction * i)) danger -= current_danger moves.append((Move(MoveEnum.Move, direction, i), 0, danger, i)) i += 1 if len(moves) == 0: # Trapped and in mortal danger, attack biggest guy adjacents = arena.adjacent_bots() biggest = adjacents[0] for bot in adjacents: if biggest.hp < bot.hp: biggest = bot print (Move(MoveEnum.Attack, biggest.pos - arena.me.pos)) exit() best_move = moves[0] for move in moves: if ((move[2] < best_move[2] and best_move[2] >= arena.me.hp) or (move[2] == best_move[2] and move[3] < best_move[3])): best_move = move print(best_move[0]) exit() else: # Seek out closest target with lower health distances, path = arena.path(arena.me.pos) bot_dists = list((bot, distances[bot.pos]) for bot in arena.bots) bot_dists.sort(key=lambda x: x[1]) target = bot_dists[0] for i in range(len(bot_dists)): if bot_dists[i][0].hp <= arena.me.hp: target = bot_dists[i] break pos = target[0].pos for i in range(target[1] - 1): pos = path[pos] print (Move(MoveEnum.Move, pos - arena.me.pos, 1)) exit() # Shouldn't get here, but I might as well do something print (Move(MoveEnum.Pass)) ``` [Answer] # Assassin (Java 1.7) Tries to kill enemies whenever possible, otherwise moves one field. It is pretty good in finding the path to an enemy, but doesn't do anything to hide from other bots. ``` import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class Assassin { private final Path dataPath = Paths.get("data"); private final Path mapPath = Paths.get("map"); private final Path statsPath = Paths.get("stats"); private final List<Player> players = new ArrayList<>(); private final int energy; private Map map = null; public Assassin(int energy) { this.energy = energy; } private void doSomething() { if (dataFileEmpty()) { calculateTurn(); } printStoredOutput(); } private boolean dataFileEmpty() { try { return !Files.exists(dataPath) || Files.size(dataPath) == 0; } catch (IOException e) { return true; } } private void printStoredOutput() { try { List<String> lines = Files.readAllLines(dataPath, StandardCharsets.UTF_8); //print first line System.out.println(lines.get(0)); //delete first line lines.remove(0); Files.write(dataPath, lines, StandardCharsets.UTF_8); } catch (IOException e) { System.out.println("PASS"); } } private void calculateTurn() { try { readStats(); readMap(); if (!tryKill()) { sneakCloser(); } } catch (IOException e) {} } private void readStats() throws IOException{ List<String> stats = Files.readAllLines(statsPath, StandardCharsets.UTF_8); for (String stat : stats) { String[] infos = stat.split(","); int hp = Integer.parseInt(infos[1].replace("HP", "")); players.add(new Player(stat.charAt(0), hp)); } } private void readMap() throws IOException{ List<String> lines = Files.readAllLines(mapPath, StandardCharsets.UTF_8); Field[][] fields = new Field[lines.size()][lines.get(0).length()]; for (int row = 0; row < lines.size(); row++) { String line = lines.get(row); for (int col = 0; col < line.length(); col++) { fields[row][col] = new Field(line.charAt(col), row, col); } } map = new Map(fields); } private boolean tryKill() { Field me = map.getMyField(); for (Field field : map.getEnemyFields()) { for (Field surrField : map.surroundingFields(field)) { List<Direction> dirs = map.path(me, surrField); if (dirs != null) { for (Player player : players) { //can kill this player int remainderEnergy = energy - dirs.size() - player.hp; if (player.id == field.content && remainderEnergy >= 0) { //save future moves List<String> commands = new ArrayList<>(); for (Direction dir : dirs) { commands.add("MOVE " + dir + " 1"); } //attacking direction Direction attDir = surrField.dirsTo(field).get(0); for (int i = 0; i < player.hp; i++) { commands.add("ATTACK " + attDir); } if (remainderEnergy > 0) { commands.add("PASS"); } try { Files.write(dataPath, commands, StandardCharsets.UTF_8); } catch (IOException e) {} return true; } } } } } return false; } private void sneakCloser() { Field me = map.getMyField(); for (Direction dir : Direction.values()) { if (!map.move(me, dir).blocked()) { List<String> commands = new ArrayList<>(); commands.add("MOVE " + dir + " 1"); commands.add("PASS"); try { Files.write(dataPath, commands, StandardCharsets.UTF_8); } catch (IOException e) {} return; } } } public static void main(String[] args) { try { new Assassin(Integer.parseInt(args[0])).doSomething(); } catch (Exception e) { System.out.println("PASS"); } } class Map { private Field[][] fields; public Map(Field[][] fields) { this.fields = fields; } public Field getMyField() { for (Field[] rows : fields) { for (Field field : rows) { if (field.isMyPos()) { return field; } } } return null; //should never happen } public List<Field> getEnemyFields() { List<Field> enemyFields = new ArrayList<>(); for (Field[] rows : fields) { for (Field field : rows) { if (field.hasEnemy()) { enemyFields.add(field); } } } return enemyFields; } public List<Field> surroundingFields(Field field) { List<Field> surrFields = new ArrayList<>(); for (Direction dir : Direction.values()) { surrFields.add(move(field, dir)); } return surrFields; } public Field move(Field field, Direction dir) { return fields[field.row + dir.rowOffset][field.col + dir.colOffset]; } public List<Direction> path(Field from, Field to) { List<Direction> dirs = new ArrayList<>(); Field lastField = from; boolean changed = false; for (int i = 0; i < energy && lastField != to; i++) { List<Direction> possibleDirs = lastField.dirsTo(to); changed = false; for (Direction dir : possibleDirs) { Field nextField = move(lastField, dir); if (!nextField.blocked()) { lastField = nextField; changed = true; dirs.add(dir); break; } } if (!changed) { return null; //not possible } } if (lastField != to) { return null; //not enough energy } return dirs; } } class Field { private char content; private int row; private int col; public Field(char content, int row, int col) { this.content = content; this.row = row; this.col = col; } public boolean hasEnemy() { return content == '1' || content == '2' || content == '3' || content == '4'; } public List<Direction> dirsTo(Field field) { List<Direction> dirs = new ArrayList<>(); int distance = Math.abs(row - field.row) + Math.abs(col - field.col); for (Direction dir : Direction.values()) { int dirDistance = Math.abs(row - field.row + dir.rowOffset) + Math.abs(col - field.col + dir.colOffset); if (dirDistance < distance) { dirs.add(dir); } } if (dirs.size() == 1) { //add near directions for (Direction dir : dirs.get(0).nearDirections()) { dirs.add(dir); } } return dirs; } public boolean isMyPos() { return content == '@'; } public boolean blocked() { return content != ' '; } } class Player { private char id; private int hp; public Player(char id, int hp) { this.id = id; this.hp = hp; } } enum Direction { N(-1, 0),S(1, 0),E(0, 1),W(0, -1); private final int rowOffset; private final int colOffset; Direction(int rowOffset, int colOffset) { this.rowOffset = rowOffset; this.colOffset = colOffset; } public Direction[] nearDirections() { Direction[] dirs = new Direction[2]; for (int i = 0; i < Direction.values().length; i++) { Direction currentDir = Direction.values()[i]; if (Math.abs(currentDir.rowOffset) != Math.abs(this.rowOffset)) { dirs[i%2] = currentDir; } } return dirs; } } } ``` [Answer] # Gotta Finish Eating Python: ``` import sys print 'PASS' ``` ]
[Question] [ Your challenge is to create a clock that displays the time as a hex number, and the background color as the hex color code of the time. Requirements: No input. In the center of your output you should display the number sign and the current time in 24 hour format as "#hhmmss". The program should update to the current time at least once every second. The text must be centered and white (or a light color that stands out). The background should be entirely the color of the hex code. Shortest code wins, but creative answers are encouraged. [Live example](http://www.jacopocolo.com/hexclock/). Idea from r/InternetIsBeautiful. [Answer] # HTML/CSS/JavaScript 207 183 180 161 152 Tested and working in the latest Firefox and Chrome browsers. ``` <body id=b onload=setInterval("b.innerHTML=b.bgColor=Date().replace(/.*(..):(..):(..).*/,'#$1$2$3')",0) text=#fff style=position:fixed;top:50%;left:47%> ``` **[Demo Here](http://jsfiddle.net/ffLct/6/)** [Answer] # python3 (142) or (123 with flickering) ``` import time;from turtle import*;tracer(0) while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a);update() ``` using turtles, **142** bytes, will probably not be the shortest, but I simply wanted to ~~use~~ play with turtles again. This example updates the screen often enough en does what is asked, but it is not pretty, as it goes on and off. Then it is only **123** bytes. (not a specified quality) ``` import time;from turtle import* while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a) ``` ungolfed: ``` import time from turtle import* tracer(0) #1 not every change should be propagated immediatly while 1: reset() #2 remove previous drawing ht() #3 hide the turtle color([1]*3) #4 set color to snow, which is white for as far I can see a=time.strftime("#%H%M%S") #5 generate the color from time write(a,0,"center") #6 print time bgcolor(a) #7 change bgcolor update() #8 propagate changes ``` btw, because of the while 1, I'd recommend running it from terminal. As it can be quite difficult to close :D (you'll need ctrl+c) [Answer] # Processing, 162 bytes ``` void draw() { int h=hour(),m=minute(),s=second(); background(color(h,m,s)); textAlign(CENTER); text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),50,50); } ``` Screenshot: ![enter image description here](https://i.stack.imgur.com/OYytP.png) I don't know if it's against the rules, but the actual drawing area is the 100x100px square on the center of the window. For some reason, Processing can't scale down the window to that size, so it adds the gray margins around the drawing area. Here's another version without the gray margins, but slightly larger **(198 bytes)**: ``` void setup() { size(200,200); } void draw() { int h=hour(),m=minute(),s=second(); background(color(h,m,s)); textAlign(CENTER); text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),100,100); } ``` [Answer] # SmileBASIC, 65 bytes ``` T$=TIME$T$[2]=" LOCATE 21,14T$[4]" GCLS VAL("&H"+T$)?"#";T$EXEC. ``` [Answer] # HTML + Javascript (184) This uses the `=>` notation which is currently only supported in Firefox. It does not use any libraries. ``` <body text=white onload='(b=document.body).bgColor=b.innerHTML="#"+[(d=new Date()).getHours(),d.getMinutes(),d.getSeconds()].map(x=>("00"+x).slice(-2)).join("");setTimeout(b.onload)'> ``` With indentation: ``` <body text=white onload=' (b=document.body).bgColor = b.innerHTML = "#"+[ (d=new Date()).getHours(), d.getMinutes(), d.getSeconds()].map( x=>("00"+x).slice(-2) ).join(""); setTimeout(b.onload) '> ``` [Answer] # C# 357, 325 with minor cheating Yea, C# isn't gonna win many codegolf prizes against other languages. Still, fun! Cheating (not *exactly* centre, and only centre with .NET 4.5's default form size of 300x300, Mono may do other funny stuff): ``` using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Top=125,Left=120,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}} ``` Golfed: ``` using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Dock=(DockStyle)5,TextAlign=(ContentAlignment)32,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}} ``` Ungolfed: ``` using System.Windows.Forms; using System.Drawing; class P : Form { static void Main() { new P().ShowDialog(); } public P() { var l = new Label() { Dock = (DockStyle)5, TextAlign = (ContentAlignment)32, ForeColor = Color.White }; Controls.Add(l); new Timer() { Enabled = true, Interval = 1 }.Tick += (s, e) => { BackColor = ColorTranslator.FromHtml(l.Text = System.DateTime.Now.ToString("#HHmmss")); }; } } ``` [Answer] # Python 3, 122 characters ``` from turtle import* import time color(1,1,1) ht() while 1:_=time.strftime("#%H%M%S");bgcolor(_);write(_,0,"center");undo() ``` Takes advantage of Python 3 turtle's `undo()` capability to clear just the previous text. Doesn't exhibit the intense flickering of turtle `reset()` caused by it resetting *everything* about the turtle. ]
[Question] [ This is a word game from a set of activity cards for children. Below the rules is code to find the best triplet using /usr/share/dict/words. I thought it was an interesting optimization problem, and am wondering if people can find improvements. ## Rules 1. Choose one letter from each of the sets below. 2. Choose a word using the letters chosen (and any others). 3. Score the word. * Each letter from the chosen set gets the number shown with the set (repeats included). * `AEIOU` count 0 * All other letters are -2 4. Repeat steps 1-3 above (no reusing letters in step 1) twice more. 5. Final score is the sum of the three word scores. ## Sets ### (set 1 scores 1 point, set 2 scores 2 points, etc.) 1. LTN 2. RDS 3. GBM 4. CHP 5. FWV 6. YKJ 7. QXZ ## Code: ``` from itertools import permutations import numpy as np points = {'LTN' : 1, 'RDS' : 2, 'GBM' : 3, 'CHP' : 4, 'FWV' : 5, 'YKJ' : 6, 'QXZ' : 7} def tonum(word): word_array = np.zeros(26, dtype=np.int) for l in word: word_array[ord(l) - ord('A')] += 1 return word_array.reshape((26, 1)) def to_score_array(letters): score_array = np.zeros(26, dtype=np.int) - 2 for v in 'AEIOU': score_array[ord(v) - ord('A')] = 0 for idx, l in enumerate(letters): score_array[ord(l) - ord('A')] = idx + 1 return np.matrix(score_array.reshape(1, 26)) def find_best_words(): wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]] wlist = [l for l in wlist if len(l) > 4] orig = [l for l in wlist] for rep in 'AEIOU': wlist = [l.replace(rep, '') for l in wlist] wlist = np.hstack([tonum(w) for w in wlist]) best = 0 ct = 0 bestwords = () for c1 in ['LTN']: for c2 in permutations('RDS'): for c3 in permutations('GBM'): for c4 in permutations('CHP'): for c5 in permutations('FWV'): for c6 in permutations('YJK'): for c7 in permutations('QZX'): vals = [to_score_array(''.join(s)) for s in zip(c1, c2, c3, c4, c5, c6, c7)] ct += 1 print ct, 6**6 scores1 = (vals[0] * wlist).A.flatten() scores2 = (vals[1] * wlist).A.flatten() scores3 = (vals[2] * wlist).A.flatten() m1 = max(scores1) m2 = max(scores2) m3 = max(scores3) if m1 + m2 + m3 > best: print orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()], m1 + m2 + m3 best = m1 + m2 + m3 bestwords = (orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()]) return bestwords, best if __name__ == '__main__': import timeit print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1) ``` The matrix version is what I came up with after writing one in pure python (using dictionaries and scoring each word independently), and another in numpy but using indexing rather than matrix multiplication. The next optimization would be to remove the vowels from the scoring entirely (and use a modified `ord()` function), but I wonder if there are even faster approaches. **EDIT**: added timeit.timeit code **EDIT**: I'm adding a bounty, which I'll give to whichever improvement I most like (or possibly multiple answers, but I'll have to accrue some more reputation if that's the case). [Answer] Here's an idea - you can avoid checking lots of words by noticing that most words have awful scores. Say you have found a pretty good scoring play that gets you 50 points. Then any play with more than 50 points must have a word of at least ceil(51/3)=17 points. So any word that can't possibly generate 17 points can be ignored. Here's some code that does the above. We compute the best possible score for each word in the dictionary, and store it in an array indexed by score. Then we use that array to check only words that have the required minimum score. ``` from itertools import permutations import time S={'A':0,'E':0,'I':0,'O':0,'U':0, 'L':1,'T':1,'N':1, 'R':2,'D':2,'S':2, 'G':3,'B':3,'M':3, 'C':4,'H':4,'P':4, 'F':5,'W':5,'V':5, 'Y':6,'K':6,'J':6, 'Q':7,'X':7,'Z':7, } def best_word(min, s): global score_to_words best_score = 0 best_word = '' for i in xrange(min, 100): for w in score_to_words[i]: score = (-2*len(w)+2*(w.count('A')+w.count('E')+w.count('I')+w.count('O')+w.count('U')) + 3*w.count(s[0])+4*w.count(s[1])+5*w.count(s[2])+6*w.count(s[3])+7*w.count(s[4])+ 8*w.count(s[5])+9*w.count(s[6])) if score > best_score: best_score = score best_word = w return (best_score, best_word) def load_words(): global score_to_words wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]] score_to_words = [[] for i in xrange(100)] for w in wlist: score_to_words[sum(S[c] for c in w)].append(w) for i in xrange(100): if score_to_words[i]: print i, len(score_to_words[i]) def find_best_words(): load_words() best = 0 bestwords = () for c1 in permutations('LTN'): for c2 in permutations('RDS'): for c3 in permutations('GBM'): print time.ctime(),c1,c2,c3 for c4 in permutations('CHP'): for c5 in permutations('FWV'): for c6 in permutations('YJK'): for c7 in permutations('QZX'): sets = zip(c1, c2, c3, c4, c5, c6, c7) (s1, w1) = best_word((best + 3) / 3, sets[0]) (s2, w2) = best_word((best - s1 + 2) / 2, sets[1]) (s3, w3) = best_word(best - s1 - s2 + 1, sets[2]) score = s1 + s2 + s3 if score > best: best = score bestwords = (w1, w2, w3) print score, w1, w2, w3 return bestwords, best if __name__ == '__main__': import timeit print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1) ``` The minimum score gets rapidly up to 100, which means we need only consider 33+ point words, which is a very small fraction of the overall total (my `/usr/share/dict/words` has 208662 valid words, only 1723 of which are 33+ points = 0.8%). Runs in about half an hour on my machine and generates: ``` (('MAXILLOPREMAXILLARY', 'KNICKKNACKED', 'ZIGZAGWISE'), 101) ``` [Answer] Using Keith's idea of precomputing the best possible score for each word, I managed to reduce the execution time to about 0.7 seconds on my computer (using a list of 75,288 words). The trick is to go through the combinations of words to be played instead of all combinations of letters picked. We can ignore all but a few combinations of words (203 using my word list) because they can't get a higher score than we've already found. Nearly all of the execution time is spent precomputing word scores. Python 2.7: ``` import collections import itertools WORDS_SOURCE = '../word lists/wordsinf.txt' WORDS_PER_ROUND = 3 LETTER_GROUP_STRS = ['LTN', 'RDS', 'GBM', 'CHP', 'FWV', 'YKJ', 'QXZ'] LETTER_GROUPS = [list(group) for group in LETTER_GROUP_STRS] GROUP_POINTS = [(group, i+1) for i, group in enumerate(LETTER_GROUPS)] POINTS_IF_NOT_CHOSEN = -2 def best_word_score(word): """Return the best possible score for a given word.""" word_score = 0 # Score the letters that are in groups, chosing the best letter for each # group of letters. total_not_chosen = 0 for group, points_if_chosen in GROUP_POINTS: letter_counts_sum = 0 max_letter_count = 0 for letter in group: if letter in word: count = word.count(letter) letter_counts_sum += count if count > max_letter_count: max_letter_count = count if letter_counts_sum: word_score += points_if_chosen * max_letter_count total_not_chosen += letter_counts_sum - max_letter_count word_score += POINTS_IF_NOT_CHOSEN * total_not_chosen return word_score def best_total_score(words): """Return the best score possible for a given list of words. It is fine if the number of words provided is not WORDS_PER_ROUND. Only the words provided are scored.""" num_words = len(words) total_score = 0 # Score the letters that are in groups, chosing the best permutation of # letters for each group of letters. total_not_chosen = 0 for group, points_if_chosen in GROUP_POINTS: letter_counts = [] # Structure: letter_counts[word_index][letter] = count letter_counts_sum = 0 for word in words: this_word_letter_counts = {} for letter in group: count = word.count(letter) this_word_letter_counts[letter] = count letter_counts_sum += count letter_counts.append(this_word_letter_counts) max_chosen = None for letters in itertools.permutations(group, num_words): num_chosen = 0 for word_index, letter in enumerate(letters): num_chosen += letter_counts[word_index][letter] if num_chosen > max_chosen: max_chosen = num_chosen total_score += points_if_chosen * max_chosen total_not_chosen += letter_counts_sum - max_chosen total_score += POINTS_IF_NOT_CHOSEN * total_not_chosen return total_score def get_words(): """Return the list of valid words.""" with open(WORDS_SOURCE, 'r') as source: return [line.rstrip().upper() for line in source] def get_words_by_score(): """Return a dictionary mapping each score to a list of words. The key is the best possible score for each word in the corresponding list.""" words = get_words() words_by_score = collections.defaultdict(list) for word in words: words_by_score[best_word_score(word)].append(word) return words_by_score def get_winning_words(): """Return a list of words for an optimal play.""" # A word's position is a tuple of its score's index and the index of the # word within the list of words with this score. # # word played: A word in the context of a combination of words to be played # word chosen: A word in the context of the list it was picked from words_by_score = get_words_by_score() num_word_scores = len(words_by_score) word_scores = sorted(words_by_score, reverse=True) words_by_position = [] # Structure: words_by_position[score_index][word_index] = word num_words_for_scores = [] for score in word_scores: words = words_by_score[score] words_by_position.append(words) num_words_for_scores.append(len(words)) # Go through the combinations of words in lexicographic order by word # position to find the best combination. best_score = None positions = [(0, 0)] * WORDS_PER_ROUND words = [words_by_position[0][0]] * WORDS_PER_ROUND scores_before_words = [] for i in xrange(WORDS_PER_ROUND): scores_before_words.append(best_total_score(words[:i])) while True: # Keep track of the best possible combination of words so far. score = best_total_score(words) if score > best_score: best_score = score best_words = words[:] # Go to the next combination of words that could get a new best score. for word_played_index in reversed(xrange(WORDS_PER_ROUND)): # Go to the next valid word position. score_index, word_chosen_index = positions[word_played_index] word_chosen_index += 1 if word_chosen_index == num_words_for_scores[score_index]: score_index += 1 if score_index == num_word_scores: continue word_chosen_index = 0 # Check whether the new combination of words could possibly get a # new best score. num_words_changed = WORDS_PER_ROUND - word_played_index score_before_this_word = scores_before_words[word_played_index] further_points_limit = word_scores[score_index] * num_words_changed score_limit = score_before_this_word + further_points_limit if score_limit <= best_score: continue # Update to the new combination of words. position = score_index, word_chosen_index positions[word_played_index:] = [position] * num_words_changed word = words_by_position[score_index][word_chosen_index] words[word_played_index:] = [word] * num_words_changed for i in xrange(word_played_index+1, WORDS_PER_ROUND): scores_before_words[i] = best_total_score(words[:i]) break else: # None of the remaining combinations of words can get a new best # score. break return best_words def main(): winning_words = get_winning_words() print winning_words print best_total_score(winning_words) if __name__ == '__main__': main() ``` This returns the solution `['KNICKKNACK', 'RAZZMATAZZ', 'POLYSYLLABLES']` with a score of 95. With the words from Keith's solution added to the word list I get the same result as him. With thouis's "xylopyrography" added, I get `['XYLOPYROGRAPHY', 'KNICKKNACKS', 'RAZZMATAZZ']` with a score of 105. ]
[Question] [ Imagine a simple SKI calculus expression - for example, `(((S α) β) γ)`. As you can see, each node of the rooted tree has exactly two children. Sometimes though, the parentheses are omitted and the tree is unrooted (just to make the notation clear, I believe). The challenge is to put the parentheses back, so that the tree is binary and rooted again. The preferable way of I/O is mostly up to you; although the input and output has to at least look like the SKI calculus, and it obviously has to represent a tree. The rule on adding parentheses is simple: `α β γ` becomes `((α β) γ)` (bind to the left), `α β γ δ` becomes `(((α β) γ) δ)`, and so on. You may assume that the input is a correct SKI-calculus expression. If it wasn't clear enough, you may NOT add more braces than necessary. And if it helps you in any way, you can assume that the input contains no redundant parens (like, for example, `(((SK)))`). ### Examples ``` S(KS)K => ((S(KS))K) SS(SK) => ((SS)(SK)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 37 bytes ``` s/(\w|\((?1)*\)){2}(?!\))/($&)/&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXyOmvCZGQ8PeUFMrRlOz2qhWw14RyNDXUFHT1FdTK0pNyf//P1jDO1jTmys4WCPYW5PLUcPJ2cVV0@1ffkFJZn5e8X/dAgA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔⟦⟧ηFθ¿⁼)ι≔⊟υη«F⁼Lη²⊞η⮌E²⊟η¿⁼(ι«⊞υη⊞η⟦⟧≔§η¹η»⊞ηι»⭆¹η ``` [Try it online!](https://tio.run/##TY67CoMwFIbn5CkOTueAHXR1cuhQ2oLUURzEpiYg3qJSKD57GmMKzRL@5Psvtaymuq9aY1KtVdNhUYYgKeGvfgIcCdQL8DwuVasxoCAERQQezfoBFzpw0WoBH86czfM30TWzRGmR2LqyRVsRwkOsYtIC79WAcQh7iiR7Es7@y9CX2VDmrMvR5JUNKkon/Zp0vnRP8d4/Ij@KbZy5YT@Hso8bzybVzZjP9mr2EdFOU2JMjnlOV3Na2y8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a stringified tree-like nest of lists. Explanation: ``` ≔⟦⟧η ``` Start with an empty tree. ``` Fθ ``` Loop over the input characters. ``` ¿⁼)ι ``` If this is a `)`, then... ``` ≔⊟υη ``` ... restore the parent node saved below, otherwise: ``` «F⁼Lη² ``` If the current node already has two children, then... ``` ⊞η⮌E²⊟η ``` ... remove them and put them in a first child node. (I can't wrap them in a node, since its parent is still pointing to it.) ``` ¿⁼(ι« ``` If this is a `(`, then... ``` ⊞υη ``` ... save the current node, ... ``` ⊞η⟦⟧ ``` ... push an empty node, ... ``` ≔§η¹η» ``` ... and set that as the current node. ``` ⊞ηι» ``` Otherwise push the letter to the current node. ``` ⭆¹η ``` Stringify and output the tree. 56 bytes for pretty output: ``` ≔⟦⟧ηF⁺θI«≔⪫()⪫ηωζF⁼Lη²≔⟦ζ⟧η≡ι(«⊞υη≔⟦⟧η»)«≔⊟υη⊞ηζ»⊞ηι»§η⁰ ``` [Try it online!](https://tio.run/##XY49C8IwEIbn9Fccme4ggjjWycGh6lDoKA6h1iYQUm0SFcXfHtuaLm53vM/7USvZ1500MW6c063F40mAonV26XrA0gSHNwG84ETwzliCdp22yJG4gOlUAh5EAl6DkU3O7S1I4/DQ2NYrVIO2GhLmjlcqYe6hfa0A9ZReS9cAR56PDyuDUxgSyP7msc@MU8ITUHZXDDS7pgyVhg2Wc3ORwfgcZkH/hE9W9tp63PjCnpvnqCyJ1jFWWFW0j4u7@QI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⟦⟧η ``` Start with an empty tree. ``` F⁺θI« ``` Loop over the input characters, but add an extra `I` to ensure that the final result is wrapped in `()` if necessary. (If the result can always be wrapped in `()`, then this can be `F⪫()θ«` and the last part can be `»ζ` for an overall saving of 1 byte.) ``` ≔⪫()⪫ηωζ ``` Get what the bracketed expression would be. ``` F⁼Lη²≔⟦ζ⟧η ``` If the current node already has two children then replace it with a node with the bracketed expression. ``` ≡ι ``` Switch on the current character. ``` («⊞υη≔⟦⟧η» ``` If it's a `(` then save the current node and start a new node. ``` )«≔⊟υη⊞ηζ» ``` If it's a `)` then retrieve the saved node and push the bracketed expression to it. ``` ⊞ηι ``` Otherwise push the letter to the current node. ``` »§η⁰ ``` Output the desired expression. ]
[Question] [ According to [Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)#Darboux_function), a strongly Darboux function is > > one for which the image of every (non-empty) open interval is the whole real line > > > In other words, a function \$f\$ is strongly Darboux if given 3 arbitrary real numbers \$a\$, \$b\$, and \$y\$, it is always possible to find an \$x\$ between (distinct) \$a\$ and \$b\$ such that \$f(x) = y\$. For the purposes of this challenge, we will consider strongly Darboux functions over the rationals instead. Your challenge is to write a program or function that: * gives a rational number as output for every rational number input, * always gives the same output for a given input, and * has the strongly Darboux property. Input and output may be either of the following: * an arbitrary-precision number type, if your language has one (or has a library for one, e.g. GMP). * a string representation of the number, which you may assume will always contain a decimal point and at least one digit on either side. It may be in any base \$b \geq 2\$, but input and output must be in the same base. You may use any set of characters for the digits and decimal point (but again, they must be consistent between input and output). The input will always have a terminating base \$b\$ expansion. As for the output, which may have a theoretically non-terminating base \$b\$ expansion depending on your choice of function, you may choose any of the following: * output digits forever. * take an additional integer as input and output at least that many digits. * output at least as many digits as are in the input (which may contain trailing zeroes). Note that by the nature of this challenge, the convention that [numbers may be assumed to be representable by standard number types](https://codegolf.meta.stackexchange.com/q/8471/3808) does **not** apply, except for the second input described in option 2 above. To avoid loopholes with functions that are only defined on non-terminating rationals, your submission must be able to produce output arbitrarily close to a desired value **in practice**. Formally, given rational numbers \$a\$, \$b\$, \$y\$, and \$\varepsilon\$, there must be a rational number \$x\$ that terminates in your chosen base such that \$a<x<b\$ and \$|f(x)-y|<\varepsilon\$. --- To give you some ideas, here is a description of the [Conway base 13 function](https://en.wikipedia.org/wiki/Conway_base_13_function): * Convert \$x\$ to base 13 and remove the decimal point. * If the result is of the form \$[x]A[y]C[z]\_{13}\$, where \$[y]\$ and \$[z]\$ consist of only digits from 0 to 9, then \$f(x) = [y].[z]\$. * If the result is of the form \$[x]B[y]C[z]\_{13}\$, where \$[y]\$ and \$[z]\$ consist of only digits from 0 to 9, then \$f(x) = -[y].[z]\$. * Otherwise, \$f(x) = 0\$. This function is strongly Darboux. Say, for example, that we want to find some \$x\$ between \$123.456\_{13}\$ and \$123.457\_{13}\$ such that \$f(x) = 7.89\$. The base-13 value \$123.456A7C89\_{13}\$ would satisfy this requirement. Your submission may be an implementation of this function, although I suspect that there are other strongly Darboux functions that are a lot shorter to implement. :) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~43~~ 50 bytes ``` ^.*\.(..)*1(.)((..)+)1.((..)*)$ $2$*-$3.$5 0(.) $1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/Tk8rRk9DT09Ty1BDT1MDxNLWNNQDM7Q0VbhUjFS0dFWM9VRMuQyACrhUDP//1zXQMzQ0MAAhAA "Retina 0.8.2 – Try It Online") I/O is as a binary string. Encode a binary number `y` close to another binary number `a` as follows: 1. If `a` does not contain a `.`, suffix one. 2. If `a` contains an odd number of digits after the `.`, suffix a `0`. 3. If `y` is negative then suffix `11` otherwise suffix `10`. 4. For each digit in `y`, suffix `0` followed by that digit. 5. If `y` contains a `.`, suffix `11` at that point, otherwise suffix it after all the digits in `y`. Explanation: ``` ^.*\.(..)*1(.)((..)+)1.((..)*)$ $2$*-$3.$5 ``` Pair the digits starting at the binary point. If the number is a valid encoding, then decode the last `1x` digit pair to a `.` and the second last to an optional `-` sign. Digits before that are ignored. ``` 0(.) $1 ``` This should just leave pairs that begin with `0`, so delete the `0`s. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 71 bytes ``` L7*©ṛḅ7WµṪ×⁵d®µ⁴‘¤Ð¡ḊṖ DF7,8ṣṪ¥ƒṣ9ḅ7×ɗÇƭ€j”, DFf7r9¤ṫ-Ḍ⁼Ɱ“OY‘TịØ+³çƲ0Ẹ? ``` [Try it online!](https://tio.run/##AaEAXv9qZWxsef//TDcqwqnhuZvhuIU3V8K14bmqw5figbVkwq7CteKBtOKAmMKkw5DCoeG4iuG5lgpERjcsOOG5o@G5qsKlxpLhuaM54biFN8OXyZfDh8at4oKsauKAnSwKREZmN3I5wqThuast4biM4oG84rGu4oCcT1nigJhU4buLw5grwrPDp8ayMOG6uD////8xMjMsNDk3ODU2MjkzNP8xMA "Jelly – Try It Online") A full program that takes a base-10 number as input and output and implements the Conway base 13 function but using bases 7 and 10 rather than 10 and 13. Both input and output use comma as a decimal separator. Output will have a leading - for negative numbers. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~28~~ ~~25~~ ~~26~~ 28 bytes ``` .*11|22 . D^`\. ^3 - 4(.) $1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0/L0LDGyIhLj8slLiFGjyvOmEuXy0RDT5NLBShramxmbGRoCEQmRsamxkDSyNJCz8TUzNzQCCgCAA "Retina – Try It Online") ### Explanation ``` .*11|22 Delete up to the last 11 and prepend a dot. Also change 22 to a dot. . D^`\. Keep only the last dot, if there is one. ^3 Change 3 at the beginning to a minus sign. - 4(.) 4 is the escape character. $1 ``` It may output leading and trailing zeros, and numbers without a integer part. It could be golfed 2 or 3 bytes more if I could use `4+`. But I'm not sure how to define the theoretical result if the input has an endless stream of `4`s. ]
[Question] [ Bob got kidnapped and is stuck in a maze. Your job is to help him find a way out. But since it is a very dark and scary maze, he can't see anything. He can only feel walls when he runs in to it, and knows when he has found the exit, but doesn't know anything more that. Since he has to run your program by memory, it has to be as short as possible. *Note: I took this problem from <http://acmgnyr.org/year2016/problems.shtml>, but adapted it slightly, and wrote the judge program/test cases myself.* # Specification * This is an interactive problem, so you program will output moves to stdout, and take in responses from stdin. * Your program can output one of the moves `right`, `left`, `down`, `up`. * It will then get as input one of the following: + `wall` - this means that Bob has hit a wall. Bob will stay in the same place. + `solved` - Bob has found the exit! Your program should now also exit without printing anything else. + `ok` - Bob was able to move in the given direction. * If the maze has no exit, your program should output `no exit` to let Bob know that he should give up. Your program should then exit without printing anything else. * Since Bob is in a hurry to get out, your program should not make any extraneous moves. In other words, **your program is not allowed to move in the same direction from the same square twice**. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program wins! # Examples In the following examples, `S` is the starting square, `X` is the exit, `#` is a wall, and spaces are valid squares. Since there is no single correct answer, these are just example runs of a solution. Also note that the drawings of the maze are just there for you to see, and your program will not get them as input. ``` ######## #S # ###### # # # #X# right ok right ok right ok right ok right ok right wall down ok right wall down ok right wall down solved ##### # S # ##### right ok right wall down wall up wall left ok down wall up wall left ok down wall up wall left wall right ok no exit solved ############################### #S # ############## ### # # #X# # # # ################## right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right ok right wall down ok right wall down ok right wall down ok right wall down wall left ok down wall up ok up ok left ok down ok down ok down wall left ok down wall up ok up ok left ok down ok down ok down wall left ok down wall up ok up ok left wall down ok left wall down ok left ok down wall up wall left ok down wall up solved ``` # Checker Program * I have written a solution checker in Python. You can find it at <https://gist.github.com/Maltysen/f0186019b3aa3812d812f8bb984fee19>. * Run it like `python mazechecker.py ./mazesolver`. * It will test your program on all the mazes in a folder called `mazes`. * The mazes are in separate files in the same format from above. * It checks all the conditions listed above, and notifies you if your solution violates any. * You can have it print additional diagnostic info with `python mazechecker.py -d ./mazesolver`. * You can find a zipped `mazes` folder [here](http://s000.tinyupload.com/download.php?file_id=49388258448308418688&t=4938825844830841868827541). You can also add your own to it if you want. [Answer] # JavaScript (ES6), ~~180~~ 174 bytes Uses `prompt()` to output the direction and retrieve the result. ``` _=>(g=p=>[...'012301234'].some((d,i)=>g[p]>>d&1|i<4&g[P=[p[0]+(d-2)%2,p[1]+~-d%2]]>0?0:(r=prompt('up/left/down/right/no exit'.split`/`[g[p]|=1<<d,d]))<'s'?g(P):r<'t'))([0,0]) ``` [Try it online!](https://tio.run/##nVFNb@IwEL3zK0atim0RksD2sAIcTnuvxAXJa22j2glpIY4c87Wl@9dZOyRdPqVVR0IOb@bNezPzGq/i8kVnhenmSsh9Qve/aIRTWtCI@b6Pwl7/m/s9Iu6XaiExFl5GaJSygkeRaPd22eixnbInygoW8g4W3T556HsF6/HOn6546HMeheNwgDUttFoUBqNlEcxlYgKh1nmgs3RmglyB3GQG@WUxz8xz8MycwI72RiPhCU7ICJVonOInMtAjZBAhmIVeyMn@0BQolEAjeG8BLOLf0t8ApRSWuZBJlksB7fYBX9dTaA@2xDHclLqZbeXBpkJXlg5oghwPV8RZVhqlt1bo/cP71IBN/e0SW0LI0BrIkhMKe5Muyw6cpt6DknMCZqbVGu60LGRsrM@FWsm7uklZmWhWcz6Cdj6DaeAbWRqsrXbTzJVDrgwkyi6g6nbuh1tDRi@ly7kx6nk6UItWV0Ewhh4M4AC5kzmk66CwGnTbMLf/mO6op8RlcUbTsmyIa7blbMOruntXhtbxfI5sKb6@Yu@SN0Ww28HZsmynUs1XUrheSL2hSvlF5RaV/lyluPSLWPzIBf5OrHvUjQDZ13qrPZqlzt3fYeuj1XKi7vQ2sx4w67UO5FnEBbqfVO8xUsUxcqi4RKZ2dN76GLaO/dW3flVZjtHPHFUu3TtMMLnh6EgcJhderoi4hrbvV7Rux8VSbsTFrppo8s3X@cI@GzTv9D8Lr0mf4pfDfG1p@78 "JavaScript (Node.js) – Try It Online") (with automated I/O) ### Interactive snippet ***WARNING**: this code will display a prompt() dialog until 'solved' is entered or the function figures out that there's no exit at all.* ``` ( _=>(g=p=>[...'012301234'].some((d,i)=>g[p]>>d&1|i<4&g[P=[p[0]+(d-2)%2,p[1]+~-d%2]]>0?0:(r=prompt('up/left/down/right/no exit'.split`/`[g[p]|=1<<d,d]))<'s'?g(P):r<'t'))([0,0]) )() ``` ### Commented ``` _ => ( // anonymous function taking no argument g = p => // g = recursive function taking the current position p = [x, y] [ ...'0123', // i<4 : try to move on squares that haven't been visited yet ...'0123', // 3<i<8: try to go back to where we initially came from ...'4' // i=8 : if everything failed, there must be no exit ].some((d, i) => // for each direction d at index i: g[p] >> d & 1 // if this direction was already tried at this position | i < 4 & // or i is less than 4 and g[P = [ // the square at the new position P = [X, Y] with: p[0] + (d - 2) % 2, // X = x + dx[d] p[1] + ~-d % 2 // Y = y + dy[d] ]] > 0 ? // was already visited: 0 // abort : ( // else: r = prompt( // output the direction: [ 'up', // 0 = up 'left', // 1 = left 'down', // 2 = down 'right', // 3 = right 'no exit' // 4 = no exit ][ // g[p] |= 1 << d, // mark this direction as used d // d = actual index of the string to output ] // r = result of prompt() ) // ) < 's' ? // if r = 'ok': g(P) // do a recursive call at the new position : // else: r < 't' // yield true if r = 'solved' or false if r = 'wall' ) // end of some() )([0, 0]) // initial call to g at (0, 0) ``` [Answer] # Python3, 408 bytes: ``` E=enumerate;P=print def f(m): q,d=[(x,y)for x,r in E(m)for y,s in E(r)if'S'==s],{} while q: x,y=q.pop(0) for M,X,Y in[('up',-1,0),('down',1,0),('left',0,-1),('right',0,1)]: if 0<=(j:=x+X)<len(m)and 0<=(k:=y+Y)<len(m[0])and(j,k)not in(V:=d.get((x,y),[])): C=m[j][k] if'X'==C:P(M+' solved');return elif'#'==C:P(M+' wall') else:print(M+' ok');q+=[(j,k)];d[(x,y)]=V+[(j,k)] P('no exit') ``` [Try it online!](https://tio.run/##fVFNa@MwEL3rV4j4IKlWg920sDjVqfTYJRAoLl6zZLHcKHEkR1Y2Mcv@9lSS7TZpaeYivXnz5rNuzVLJyY9aH4@PjMvdhuuF4dMZq7WQBhS8hCXekATALS1Yhg@0JaXS8EA1FBI@Ws7BljYd1ESUaI4Ya3L67z@A@6WoONxavZW0bDuuVY0jYqGTPdGUvlhhhtGuRvQ6phGhGBVqLxHtQcVLg2hkSYe0eF16GJPcJYWihNE9w6uEHcKU3Fdc2pYWsvDedcLa8KX3ZlHuCLyiayKVsWXxc8KK8Ss32M9Fs5wQnxQ@sE22yrN17pEdKbUjPSQz/BQi2KjqLy8QmWpudlr6EF7ZoOAkaL@oKkR6ruGJ36dn1NpKt6FdpusknxbdVnP2HPYuAGcYSQX5QRhEju4IRv3@oxa6wA1JurIwy65E7tco3O5LURmu8U8lOYXNuKkrYTD6JRGxCZsYMjgajUDQGwjmrjUY9B776fD7Jw2AEzQ3p0oQwPmg6ejJp8Tf2FDvGws@6Qf38Oubeg8f3vQyf5L/HH7tzw9zez4MCHrxHHYrCnzFD39w3rxPUuKPW8WEgO7w6BpdxXfkjL25yE4usreEHN8A) ]
[Question] [ The 5-card magic trick involves a magician whose assistant gives them 4 shown cards and a hidden one, in this order, and the magician must guess the hidden one. # WARNING: Solution below! Leave now or get spoiled with it. --- ### The solution The trick here is that the five cards are given *in a specific order*! \$c\_1,...,c\_5\$ are the 5 cards in the given order. \$x\_n\$ is the card number of \$c\_n\$ in \$NO=[\text{A,2,3,4,5,6,7,8,9,T,J,Q,K}]\$ (number order). \$a+b\$, where \$a\$ is a card number and \$b\$ is an integer, is equal to the card number \$b\$ steps to the right of \$a\$ in \$NO\$, wrapping to the beginning if necessary. \$s\_n\$ is the suit of \$c\_n\$ in \$SO=[\clubsuit,\diamondsuit,\heartsuit,\spadesuit]\$ (suit order). \$a\circ b\$, where \$a\$ is a card number and \$b\$ is a suit, denotes the card with card number \$a\$ and suit \$b\$. \$a<b\$, where \$a\$ and \$b\$ are cards, is true if \$a\$'s suit is to the left of \$b\$'s suit in \$SO\$, or their suits are equal and \$a\$'s card number is to the left of \$b\$'s card number in \$NO\$. \$a>b\$, where \$a\$ and \$b\$ are cards, is true if \$a<b\$ is false. \$PI(a,b,c)\$, where \$a\$, \$b\$ and \$c\$ are cards, is the permutation index of this ordering of them, specified by the table below: \$\begin{array}{|c|c|}\hline\text{Comparison}&PI(a,b,c)\\\hline a<b<c&1\\\hline a<b>c>a&2\\\hline a>b<c>a&3\\\hline a<b>c<a&4\\\hline a>b<c<a&5\\\hline a>b>c&6\\\hline\end{array}\$ The solution to the 5-card magic trick is problem is:$$c\_5=(x\_1+PI(c\_2,c\_3,c\_4))\circ s\_1$$ ### The challenge So far, so good. However, doing the computation specified above is already asked for [here](https://codegolf.stackexchange.com/q/165390/41024). Instead, your challenge is, given the 5 cards in no specific order, to order them properly. This means that the first four cards in the output will represent the fifth. In other words, be the assistant. Requirements: * \$s\_5=s\_1\$. * \$x\_5=x\_1+PI(c\_2,c\_3,c\_4)\$ (that is, this must be possible). ### Example Let's consider the set `7H,2D,6D,5C,6C`. First of all, we take the 25 pairs: ``` 7H,7H 7H,2D 7H,6D 7H,5C 7H,6C 2D,7H 2D,2D 2D,6D 2D,5C 2D,6C 6D,7H 6D,2D 6D,6D 6D,5C 6D,6C 5C,7H 5C,2D 5C,6D 5C,5C 5C,6C 6C,7H 6C,2D 6C,6D 6C,5C 6C,6C ``` Then, we obviously remove the 5 pairs that contain the same card twice, they don't exist in a single deck: ``` 7H,2D 7H,6D 7H,5C 7H,6C 2D,7H 2D,6D 2D,5C 2D,6C 6D,7H 6D,2D 6D,5C 6D,6C 5C,7H 5C,2D 5C,6D 5C,6C 6C,7H 6C,2D 6C,6D 6C,5C ``` Afterwards, since the suits must be the same, different suits in a pair is a no-no: ``` 2D,6D 6D,2D 5C,6C 6C,5C ``` Finally, we check if it's possible to get from the first card to the second by adding at most 6, removing half of the remaining pairs: ``` 2D,6D 5C,6C ``` Now we have the valid pairs: `2D,6D` and `5C,6C`. The first card of each pair is card 1, while the last is card 5. We're going to go with `5C,6C` here for easiness. The whole set is `7H,2D,6D,5C,6C`, so, removing the 2 cards in the pair we've chosen, we have `7H,2D,6D`. These cards will represent `6 - 5 = 1`, so we have to order them like "min, mid, max". `7H > 2D < 6D < 7H`, or simply `2D < 6D < 7H`, so we now have `2D,6D,7H`. The last step is to put all of this together, so our result will be `5C,2D,6D,7H,6C`. ### Clarifications * You may use `10` instead of `T`. * You may use one of `♠♥♦♣`, `♤♡♢♧` or `♠♡♢♣` instead of `CDHS`, respectively. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. ### Test cases You can output one or more of the valid solutions included for each test case. ``` 8S,TD,5C,QS,TS -> 8S,5C,QS,TD,TS ... 8S,TD,TS,5C,QS ... TS,5C,8S,TD,QS JD,KH,4S,9D,8S -> 9D,KH,8S,4S,JD ... 4S,JD,KH,9D,8S 4H,4D,TH,KH,2C -> 4H,KH,4D,2C,TH ... TH,4D,2C,4H,KH ... KH,4D,TH,2C,4H 3S,KS,8S,KH,9H -> 9H,8S,KS,3S,KH ... 3S,KS,9H,KH,8S ... 8S,3S,9H,KH,KS ... KS,KH,9H,8S,3S KH,TS,3C,7H,JD -> 7H,TS,JD,3C,KH 4C,KC,TD,JD,QS -> KC,JD,QS,TD,4C ... TD,4C,KC,QS,JD AC,5H,8D,6D,8S -> 6D,AC,8S,5H,8D AS,TC,3S,2H,9C -> 9C,2H,AS,3S,TC ... AS,9C,2H,TC,3S 4C,JS,AS,8H,JC -> JC,JS,AS,8H,4C ... JS,JC,4C,8H,AS 4H,QS,TH,QC,AC -> QC,4H,QS,TH,AC ... 4H,QS,QC,AC,TH ``` [Answer] # [Node.js](https://nodejs.org), ~~190~~ ~~186~~ 180 bytes ``` f=(a,p,g=c=>"A23456789TJQK".search(c[0])+10,[A,B,C,D,E]=a.sort(_=>p>>i++&1,i=0))=>A[k=1]!=E[1]|[B,C,D].sort((a,b)=>k=k*2|a[1]+g(a)>b[1]+g(b))|(k^4)%6+1-(g(E)-g(A)+13)%13?f(a,-~p):a ``` [Try it online!](https://tio.run/##bVJNj9pADL33V9BIW2WKYckXJJWSKp0gjZJTNLlFaRUoUMpqg2DVE9q/Tm0PRGrDZWS/Gb9nP8/v9k97Xp/2x7fJa/dzc71uY7uFI@zidZxYqev5wXwRRlVeFtb0vGlP61/2up41YuzMoE7hG0jIYNnE7fTcnd7sH3FyTJL9ePzJgX08EyJO0voQO83HeFk7zaXmgsY8RqUVPjjEh8/upcXr8c5uRbIy0UqIi3347oun@diZ2Dt7KSY7O0VlTzw53tctlk/ej@JLe113r@fuZTN96Xb21q6tUFtgVRkegcSj5FRbjRCj5@dRqCGQUGqoMqj0qDsRwrHBCTGxwUv94X@BnLgLhYdP3BGlYS8QZVAoKvY15BnRcUAgXoVDOp@ZiKRSd2JX3ul8RZV@Bq6ESnF395SvCDEPEGdwIOBRl4U2Xd4EItX3y80WGjx9o/M4jZSZ42aRd0cKRgrNA3GtN5yJNSpS82gHC0rRtpvkQpHd6IknkWVoCJUU8r5Ftrvs/S0kVZoF@pINoQAK3mqeDehSYgqog5CY5v@ua55ByrsOcJYHxfx7iIFddNm7fjmRBFdByu5U3AvGBqzkI194tJyYmDhkX3q6HEfTRBeq22iYIojThSTz@OuYD84Rsac9XclfhJzCYqYzKeIpfabrXw "JavaScript (Node.js) – Try It Online") ## How? ### Identifying and comparing the card numbers The helper function \$g\$ returns an index representing the number of a given card. ``` g = c => "A23456789TJQK".search(c[0]) + 10 ``` We add \$10\$ to force two digits for all entries, so that these indices can be safely sorted in lexicographical order. Therefore an Ace is \$10\$ and a King is \$22\$. Given 2 cards \$a\$ and \$b\$ in `"NS"` format, we can compare them by suit first and number second with: ``` a[1] + g(a) > b[1] + g(b) ``` ### Generating the permutations of the input We recursively try all \$120\$ possible permutations of the input array \$a\$ by successively sorting it with different permutation seeds \$p\$. The cards are separately loaded into \$A\$, \$B\$, \$C\$, \$D\$ and \$E\$. ``` [A, B, C, D, E] = a.sort(_ => p >> i++ & 1, i = 0) ``` [This code](https://tio.run/##TYzNqsIwFIT3eYpZNSnpLeo2pqD3uu0LiEiwUeLPiaS9gkifvZ64cnGGw8w3c3YP1x9SuA8/FDs/TQ4WW8iVrCDXWX6z/GXZSOyMEMeYVMsU8c0q3H268fcaDVosMV/MDEjrEi8BhMwYflzdxzSoPWzDxaZB0BoF5mUOL/7JnKvPMZCS8uPl2S0HO1hr8U@dPwbyHYoCqtW6@gZAXBmFOETq49XX13hSBA2JMPjkhsB@Xv3Oc7000/QG) shows when each permutation is first encountered. It takes \$699\$ iterations to try all of them. ### Testing the suits The first obvious test is to make sure that the first and last cards are of the same suit. We reject the permutation if they're not equal. ``` A[k = 1] != E[1] // we also initialize k, which is used right after that ``` ### Testing the distance We compute the distance between the first card number and the last card number with: ``` (g(E) - g(A) + 13) % 13 ``` Now comes the most tricky part. We have to test whether the order of the 3 other cards (\$B\$, \$C\$ and \$D\$) correctly describes this distance. This test relies on the way the `sort()` algorithm of Node.js is working. Assuming that the callback function of `sort()` is always returning a positive integer, Node.js will sort the array \$[A,B,C]\$ by applying these 3 steps: 1. compare \$A\$ with \$B\$ 2. compare \$A\$ with \$C\$ 3. compare \$B\$ with \$C\$ Let's consider the following code: ``` [1, 2, 3].sort((a, b) => k = k * 2 | (a > b), k = 1) ``` We have \$A<B\$ (\$1<2\$), \$A<C\$ (\$1<3\$) and \$B<C\$ (\$2<3\$). All comparisons processed in the callback function are falsy and \$k\$ is simply multiplied by \$2^3\$. So, we end up with \$k=8\$. Now, if we do: ``` [3, 2, 1].sort((a, b) => k = k * 2 | (a > b), k = 1) ``` All comparisons are now thruthy, which generates the bitmask \$k=15\$. Each permutation generates a unique bitmask, which is mapped to a unique distance: ``` A, B, C | A>B | A>C | B>C | k | distance ---------+-----+-----+-----+----+---------- 1, 2, 3 | 0 | 0 | 0 | 8 | 1 1, 3, 2 | 0 | 0 | 1 | 9 | 2 2, 1, 3 | 1 | 0 | 0 | 12 | 3 2, 3, 1 | 0 | 1 | 1 | 11 | 4 3, 1, 2 | 1 | 1 | 0 | 14 | 5 3, 2, 1 | 1 | 1 | 1 | 15 | 6 ``` Given \$k\$, we can convert it to the distance by doing: $$d=((k\operatorname{xor}4)\bmod 6)+1$$ ``` k | xor 4 | mod 6 | +1 ----+-------+-------+---- 8 | 12 | 0 | 1 9 | 13 | 1 | 2 12 | 8 | 2 | 3 11 | 15 | 3 | 4 14 | 10 | 4 | 5 15 | 11 | 5 | 6 ``` Putting everything together, we have the following test: ``` [B, C, D] .sort((a, b) => k = k * 2 | a[1] + g(a) > b[1] + g(b) ) | (k ^ 4) % 6 + 1 - (g(E) - g(A) + 13) % 13 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~260 248~~ 232 bytes ``` N="A23456789TJQK".find D=lambda x,y="KC":(N(y[0])+~N(x[0]))%13+15*abs(ord(x[1])-ord(y[1])) def f(l):a,e,b,c,d=[[x,y]+sorted({*l}-{x,y},key=D)for x in l for y in l if D(x,y)<6][0];print(a,*map(eval,"bbccddcdbdbcdcdbcb"[D(a,e)::6]),e) ``` [Try it online!](https://tio.run/##VZDBjoIwEIbvPkXTZJNW62YVQWCXA4GDkcSEyI1waClkySIYNBuJcV@d7VQx8dL@M9/M/NMe@/N32xjDsPOwvzRWprW2nWQbR/i9rBo5Cb2aH4Tk6MJ6D0cBdsmO9OlHRmd/O3IBQd8WxmxhTrk4kbaTKrnI6BxUD4pOZFGiktTU5axgguVMemmq5mWzU9udC0mu0/o2v6rMjf0UvRfSsu3QBVUNqhHI/i6rEoVEVdEvK1PGn8euas6Es@mBH0nxy2uGhchzKXMppMjhygVOQ1VSUNe1MqruoSQptveY4SRUhxmoI9bhHmd0AnQLINqoYwXAgdB@0pUGkEs2Y90yGKkBHdH@3vGgzmakOkwAGOC7hlC5jZMhFwXjanqN@OnrAzChwwZgvW7l6ydAid5gqX2Dl8lbALrO1r7By4vuf6AVFPtAh38 "Python 3 – Try It Online") *-12 bytes thanks to Eric the Outgolfer* *-14 bytes by removing a list comprehension* [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~225~~ ~~220~~ 209 bytes ``` import StdEnv,Data.List n=['A23456789TJQK':n] ``` # ``` filter(\[[x,s],b,c,d,e]#[p,q,r:_]=map snd(sort(zip2[(elemIndices a n,b)\\[a,b]<-[b,c,d]][1..])) =[snd(span((<>)x)n)!!(p+if(p>q)0if(q<r)(q+r)q),s]==e)o permutations ``` [Try it online!](https://tio.run/##PY5fS8MwFMXf9ykyfEjCsqJz6jbagVDB/XlQ6lsa5LZNJdCkaZLJ9MOvlg58Or977r2HUzYSTK/b6tRIpEGZXmnbuoCyUL2Yb5ZCgOiofJiYhOPnxf3y4fFptf7Yvx/wxog@CzAcJ4jUqgnSkZzzM/OCFaxkFZPihlvWMbf5FIkGi7ypiB/iya@yC05kI/XOVKqUHgEyrKB5zoEVIp7zMUEIfhdFgtJJwsdfC4aQeEvP1NDplNiZqonddvR20C52lHQzRzs6VEgSSVtkpdOnAEG1xlPEOd5jhlMsGMeHgV5HWg6UjbT@366unugvZd3Al@/nu2Of/hjQqrwObw2EunX6Dw "Clean – Try It Online") As a composed function, `:: [[Char]] -> [[Char]]`, with some helpers. **Expanded:** ``` n = ['A23456789TJQK': n] // infinitely repeating card number list filter (...) o permutations // filter the permutations of the argument by ... \[[x, s], b, c, d, e] // deconstruct each permutation via pattern matching #[p, q, r: _] = ... // define p, q, r as ... map snd (...) // the second component of every element in ... sort (...) // the sorted list of ... zip2 ... [1..] // pairs of ... and the numbers 1, 2, 3, .. [... \\ [a, b] <- [b, c, d]] // ... for every pair of number a and house b in [b, c, d] (elemIndices a n, b) // pair of the value of that card number and the house = ... == e // check ... for equality against the last card [..., s] // ..., paired with house s snd (span ((<>) x) n) !! (...) // the card number ... places from x p + ... // this is kinda obvious if(p > q) 0 ... // if p is greater than q, zero, else ... if(q < r) (q + r) q // if q is less than r, q + r, else q ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 175 bytes ``` ->a{g=->j{j.tr('ATJQKCHS','1:;<=)_z').sum} e=b=a.sort_by{|i|g[i]} 4.times{|i|(d=g[b[i+1]]-g[b[i]])<13&&(a=b[i,2];e=d)} [a[e/7],*(b-a).permutation.to_a[e<7?e-1:12-e],a[e/7-1]]} ``` [Try it online!](https://tio.run/##dVNdb6JAFH33V9yk2aq7AxsBFVvphgwPRB42ZngjpBllVBoVA8OarvW3u3dmrNuk6QuZe849535p3S5eL6vgYj3x0zqwnl5OL7ase90wnc0TGrMu6Q4eHqdB//lvt2837e7cEcEi4HZT1fJ58Xp6K9/WWZmfO54ty51oFNArgnW2yMofgzy39CvP@9OBe3/f4wFGxMkfRVD0z52MZ@LnOCffewuL9@2DqHet5LKs9rasnpGcjn8Ja/AwcCyRE51soen5coBV9u148hmkEQwpzPHBzjncgc/IkJI5I2lEUga2bStIB4bQUGYiw8xZ3rkaziJIYvAYTCKUacNJRJJYZXqMIK3V@qlgJP3/ag@lEaSx8nCoVnuxSvMi4lCChKn9Dmgy16BJQkbD74Yug4RhI8pwEpt2dC8JIy5@jaGr40ls@jQ1fJ1gsIRdazDdsjZw2XsNNME9uRTGMcwiXSMbx2pdOKJLVYe3@SgkVG0c9zA320moSjPrRtrMp54k0VeYRTd1SGEYgx/B6LbbbBSRUJ9hiF19SMVzUpwLHJzbLHJCiROTUI@VXgthZOCUIvyxzRkD9PBxIqOeYZtMqf341iYCCGOnvvL9eET1a8IvhdCo5/pUakjMvKoNgEyoDpt3OodWNnD3u5X4gFVd7YAvqj8C@PbIXxso98ttW4gGmraUGBXlksuqBr4vYFMWhdjDktcFHEu5KfcwgmoFgi83UMmNqAnwoijVH4NvQYpGYnKDZit0GDhQVMc9yArGn44aXo/6iXAM8Ql3vxJ4XwiGXwlGV@LyDw "Ruby – Try It Online") A lambda function taking an array of cards as strings **Commented** ``` ->a{g=->j{j.tr('ATJQKCHS','1:;<=)_z').sum} #helper function converts card to integer, ATJQK to 1:;<= and CHS to )_z then sum ascii values e=b=a.sort_by{|i|g[i]} #sort according to g. we declare 2 variables here in order to avoid undefined variable error at pre-interpretation check stage. 4.times{|i|(d=g[b[i+1]]-g[b[i]])<13&&(a=b[i,2];e=d)} #compare each pair of values. if in same suit, store the pair of cards to a #and the value difference to e. Loop exits with the last suitable pair stored [a[e/7],*(b-a).permutation.to_a[e<7?e-1:12-e],a[e/7-1]]} #return array containing the two cards of the same suit in the correct order #with the correct permutation of the remaining cards (b-a) in the middle ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØD;“TJQK”¤io2)1¦€µUḊỤ3R¤œ¿+""Om4%13E Œ!ÇƇ ``` A monadic Link accepting a list of lists of characters returning a list of all valid arrangements in the same format. **[Try it online!](https://tio.run/##y0rNyan8///wDBfrRw1zQrwCvR81zD20JDPfSNPw0LJHTWsObQ19uKPr4e4lxkGHlhydfGi/tpKSf66JqqGxK9fRSYqH24@1/z/c7v7/f7SSt4eSjlJIMJAwdgYS5iCul4tSLAA "Jelly – Try It Online")** (footer formats the result as a grid to avoid the implicit smashing print as performed by the Link's code when run as a full program) Or see a [test-suite](https://tio.run/##VY6xSsRAFEX79xcuWIjXYpOsZrExvBGHpJD44idYGFas7RabgKU2FmtlsLJUUFYQJmT/I/mR8c12Dszjzp17z0x9tVjced89m@NxuaryshiXL669vo32pu5tvH93n5fD18OwbuML1/ZP7nd/Mjm/SXan8Sn1jztds2n8sP4Yvl81rF10jYoz3f3PiV7UW3tFB/8WabIOdhDep4LKYMYoVQjlBoVFIpgbpEKJaoPKBjNiigWFqB@Oc0s6K0HMOLLIDSWMggNNIaVQxphZpAaHW1SmfIYSIu1yCOcCNVPtcngofEAnI@M/ "Jelly – Try It Online"). I have a sneaking suspicion another approach will be much more terse. I shall have to revisit this challenge later! ...hmm, I had another poke around and got another 41 byter ([test](https://tio.run/##VY7BSsNAEIbv@xaCvcgvtElqEynYMAsuyUHqxHNPXkJfwJv1EhBPetWL9iQeKzS0IqSk77F5kXW2N5fdn3//mfl2y9v5/M65q6Y@mYxH0fFF9/AlO0h63eLnvC@6umm@bf05s@v33iC066dusbWbZXjdLNuX5nf/qNrno121r5zdrGz94QH3b9hVYi7ltNuJFMpD/KpO/y0lnaWPvXEuZhQaQ8JUDKtMIzeIGIlGzCoSr1EYHwakQkbOkvtrYpRowQgJI4NMq4iQk6cJZMoqJQwNYo2zAyoVPkEIgcySb84YEsYyS/4h/wFRQkp/ "Jelly – Try It Online")): ``` O¹*@<74$?€€29%⁽:0%⁴UµṪ_Ḣ%13Ḍ⁼Ụ3R¤œ¿Ɗ Œ!ÇƇ ``` ]
[Question] [ A convenient and useful way to represent topological surfaces is with a [fundamental polygon](https://en.wikipedia.org/wiki/Fundamental_polygon). Each side on a polygon matches to another side and can be either parallel or anti-parallel. For instance the here is the fundamental polygon of a [torus](https://en.wikipedia.org/wiki/Torus): [![Torus](https://i.stack.imgur.com/kdolC.png)](https://i.stack.imgur.com/kdolC.png) To figure out why this is a torus we could imagine our polygon being a sheet of paper. To make the proper surface we want to bend our paper so that the corresponding edges line up with their arrows going the same way. For our torus example we can start by rolling the paper into a cylinder so that the two blue edges (labeled b) are connected. Now we take our tube and bend it so that the two red edges (labeled a) connect to each other. We should have a donut shape, also called the torus. This can get a bit trickier. If you try to do the same with the following polygon where one of the edges is going in the opposite direction: [![Klein Bottle](https://i.stack.imgur.com/ek6mc.png)](https://i.stack.imgur.com/ek6mc.png) you might find yourself in some trouble. This is because this polygon represents the [Klein bottle](https://en.wikipedia.org/wiki/Klein_bottle) which cannot be embedded in three dimensions. Here is a diagram from wikipedia showing how you can fold this polygon into a Klein bottle: [![Folding a Klein Bottle](https://i.stack.imgur.com/2bCOI.png)](https://i.stack.imgur.com/2bCOI.png) --- As you may have guessed the task here is to take a fundamental polygon and determine which surface it is. For four sided polygons (the only surfaces you will be required to handle) there are 4 different surfaces. They are * Torus * Klein Bottle * Sphere * Projective plane Now this is not [image-processing](/questions/tagged/image-processing "show questions tagged 'image-processing'") so I don't expect you to take an image as input instead we will use a convenient notation to represent the fundamental polygon. You may have noticed in the two examples above that I named corresponding edges with the same letter (either a or b), and that I gave the twisted edge an additional mark to show its twisted. If we start at the upper edge and write down the label for each edge as we go clockwise we can get a notation that represents each fundamental polygon. For example the Torus provided would become *abab* and the Klein Bottle would become *ab-ab*. For our challenge we will make it even simpler, instead of marking twisted edges with a negative we will instead make those letters capitalized. # Task Given a string determine if it represents a fundamental polygon and output a value that corresponding to the proper surface of it is. You do not need to name the surfaces exactly, you just need 4 output distinct values each representing one of the 4 surfaces with a fifth value representing improper input. All of the basic cases are covered in the **Simple Tests** section, every car will be isomorphic to one of the or invalid. # Rules * Sides will not always be labeled with a and b, but they will always be labeled with letters. * Valid input will consist of 4 letters, two of one type and two of another. You must always output the correct surface for valid input. * You should reject (not output any of the 4 values representing surfaces) invalid input. You may do anything when rejecting an input, as long as it is distinguishable from the 4 surfaces * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the number of bytes in your source code. # Tests ### Simple Tests ``` abab Torus abAb Klein Bottle abaB Klein Bottle abAB Projective Plane aabb Klein Bottle aAbb Projective Plane aabB Projective Plane aAbB Sphere abba Klein Bottle abBa Projective Plane abbA Projective Plane abBA Sphere ``` ### Trickier Tests ``` ABAB Torus acAc Klein Bottle Emme Projective Plane zxXZ Sphere aaab Bad input abca Bad input abbaa Bad input ab1a Bad input ``` [Answer] # [Retina](https://github.com/m-ender/retina), 123 bytes ``` i`(.)(\1..) $2$1 iG`^([a-z])(?!\1)([a-z])(\1\2|\2\1)$ (..)\1 T .*(.).\1.*|(.)(.)\3\2 B (.)..\1|.(.)\2. P i`(.)..\1 S .... P ``` [Try it online!](https://tio.run/nexus/retina#NY3BCsJADETv8xdChV3BwK4fILsgvRb0IBqlSfHQQ@9S@u81KbiHYfJ2JtmHtl/HPlAMnIgimtwkjG3/Dk85zq8YzjtO8T9w4rxwNtIgWJwTbqCD1cnqh8X3GD1xRoVTwws5yoQO2yFnuILsoVtXUVGIFhep7kxEbSwuotWdf6iYVBct7gpQqqeHMuAyTR/M3/vDKtvCYQuKaxKH8gM "Retina – TIO Nexus") Thanks to @JonathanAllen for pointing out a bug in my code and also how to save some bytes; I also golfed some more bytes myself so I can't credit him for a specific figure. Explanation: ``` i`(.)(\1..) $2$1 ``` If the first two letters are the same (ignoring case), move the first letter to be fourth. This reduces the number of cases that I need to test. ``` iG`^([a-z])(?!\1)([a-z])(\1\2|\2\1)$ ``` If there are not exactly four letters, or the first two letters are the same, or the last two letters do not duplicate the first two, then delete everything. ``` (..)\1 T ``` The torus is the easy case: a pair of letters, repeated matching case. ``` .*(.).\1.*|(.)(.)\3\2 B ``` If one of the pair matches case (in which case other of the pair must mismatch case), then that is a Klein bottle. Alternatively, if the pair matches case but is reversed, then it is also a Klein bottle. ``` (.)..\1|.(.)\2. P ``` If on the other hand the pair is reversed, but only one of the pair matches case, then that is a projective plane. ``` i`(.)..\1 S ``` And if the pair is reversed but neither matches case, then that is a sphere. (`i`.(.)\1.` would also work.) ``` .... P ``` Everything else is a projective plane. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~52 51~~ 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +7 bytes, I found that the mapping I'd used did not work for some (off example) case change scenarios. ``` “nḲ⁾⁶ƥ¦ṃṗḋ’b4s4‘µṙJ;U$µ€ ,ŒsṢÞṪµŒlĠL€⁼2,2ȧ⁸i@€ṢeЀ¢TṪ’:3,8 ``` A monadic link taking a string and returning the following five distinct, consistent values: * `[-1,-1]` - invalid input * `[0,0]` - projective plane * `[1,0]` - Klein bottle * `[2,0]` - sphere * `[2,1]` - torus **[Try it online!](https://tio.run/nexus/jelly#@/@oYU7ewx2bHjXue9S47djSQ8se7mx@uHP6wx3djxpmJpkUmzxqmHFo68OdM72sQ1UObX3UtIZL5@ik4oc7Fx2e93DnqkNbj07KObLAByj@qHGPkY7RieWPGndkOgD5QCWphycAGYcWhQBVAo2zMtax@P//v2tubioA)** or see the [test suite](https://tio.run/nexus/jelly#@/@oYU7ewx2bHjXue9S47djSQ8se7mx@uHP6wx3djxpmJpkUmzxqmHFo68OdM72sQ1UObX3UtIZL5@ik4oc7Fx2e93DnqkNbj07KObLAByj@qHGPkY7RieWPGndkOgD5QCWphycAGYcWhQBVAo2zMtax@H@4PfjhbqDhc7xzUjPzFJzyS0pyUoHc4IKM1CIQIyS/qLQYSHvmlSXmZKYoeOYVlJYA@UAUUJSflZpcklmWqhCQk5gHVD2X6@iew@1AS7yBOPL//2j1xKTEJHUdIOUIoRKdIDwwlZgEFnSEUIlJThAeRElSIphyglBJjhAeiHJ0gmhPdkwGUq65ualAqqoiIgpsCtS@ZKi@RAhtmKgeCwA). ### How? Any fundamental polygon is: * unchanged under rotation - one may turn the paper like a steering wheel * unchanged under reflection - one may turn the paper over * unchanged under case reversal - one may swap `a`s and `A`s and/or swap `b`s and `B`s with no effect - since we want to match the directions the actual label is inconsequential. As such there are nine equivalence classes. The code creates lists of four integers each representing an example of one of the nine equivalence classes, creates the four rotations of each, reflects each of those and then checks if a translated form of the input exists in each list. The classes are ordered `P,P,P,K,K,K,S,S,T`, so taking the 0-based index integer divided by each of `[3,8]` yields the four valid outputs (indexing is 1-based and the atom `e` returns `0` for non-existence, so subtracting `1` and integer dividing by each of `[3,8]` yields `[-1,-1]` for the invalid case). ``` “nḲ⁾⁶ƥ¦ṃṗḋ’b4s4‘µṙJ;U$µ€ - Link 1, symmetries of the 9 equivalence classes: no arguments “nḲ⁾⁶ƥ¦ṃṗḋ’ - base 250 number 1704624888339951310984 b4 - convert to base 4 [1,1,3,0,1,2,2,0,1,2,3,0,0,2,2,0,1,3,1,0,2,1,2,0,2,3,1,0,3,1,2,0,2,0,2,0] s4 - split into 4s [[1,1,3,0],[1,2,2,0],[1,2,3,0],[0,2,2,0],[1,3,1,0],[2,1,2,0],[2,3,1,0],[3,1,2,0],[2,0,2,0]] ‘ - increment (vectorises) [[2,2,4,1],[2,3,3,1],[2,3,4,1],[1,3,3,1],[2,4,2,1],[3,2,3,1],[3,4,2,1],[4,2,3,1],[3,1,3,1]] µ µ€ - for €ach: ...e.g. [2,2,4,1]: J - range of length [1,2,3,4] ṙ - rotate left by (vectorises) [[2,4,1,2],[4,1,2,2],[1,2,2,4],[2,2,4,1]] $ - last two links as a monad: U - upend (reverse each) [[2,1,4,2],[2,2,1,4],[4,2,2,1],[1,4,2,2]] ; - concatenate [[2,4,1,2],[4,1,2,2],[1,2,2,4],[2,2,4,1],[2,1,4,2],[2,2,1,4],[4,2,2,1],[1,4,2,2]] ,ŒsṢÞṪµŒlĠL€⁼2,2ȧ⁸i@€ṢeЀ¢TṪ’:3,8 - Main link: string s e.g. "xOxO" Œs - swap case "XoXo" , - pair with s ["xOxO","XoXo"] Þ - sort by: Ṣ - sort ["xOxO","XoXo"] Ṫ - tail "XoXo" µ - monadic chain separation, call that v Œl - convert to lowercase "xoxo" Ġ - group indices by value [[2,4],[1,3]] L€ - length of each [2,2] 2,2 - 2 pair 2 [2,2] ⁼ - equal? (1 if so, 0 if not) 1 ⁸ - link's left argument, v "XoXo" ȧ - and (v if equal, 0 if not) "XoXo" Ṣ - sort v "XoXo" i@€ - first index for €ach [1,3,1,3] ¢ - call the last link (1) as a nilad Ѐ - map over right: e - exists in? [0,0,0,0,0,0,0,0,1] T - truthy indexes [ 9] Ṫ - tail (empty list yields 0) 9 ’ - decrement 8 3,8 - 3 pair 8 [3,8] : - integer division (vectorises) [2,1] ``` *Note:* 11 bytes (`ŒlĠL€⁼2,2ȧ⁸`) only validate the input string as being of the correct form - without this code every example case passes except that `ab1a` is evaluated as if it were `abBa`, a projective plane. ]
[Question] [ Inspired by [this challenge](https://codegolf.stackexchange.com/questions/109897/animate-the-text-in-your-terminal) --- ## Goal: The goal is to draw waves crashing onto a beach. ## Input: You will be given 3 integers (in whatever format you want) as input. The first integer will be the length of the drawing The second integer will be the index of the sandbar, where the waves start to crest (at least 3 spaces from beach) The third integer will be the spacing between waves (at least 3, can be greater than length of drawing, in which case you only draw one wave) ## Output: The output will be a box of characters which shows the waves crashing into the beach. The drawing should end when the first wave has completed crashing into the beach. At first, the wave is shown as a swell (`_-_`). As the wave passes the sandbar, it starts to crest (`/c_`). Finally, the wave crashes into the beach (`/c.` => `_-_` => `___` => `__.` ). ## Examples: Input: 14 4 6 Output: ``` -___________.. _-__________.. __-_________.. ___-________.. ___/c_______.. ____/c______.. -____/c_____.. _-____/c____.. __-____/c___.. ___-____/c__.. ___/c____/c_.. ____/c____/c.. -____/c____-_. _-____/c_____. __-____/c___.. ``` Input: 10, 2, 11 Output: ``` -_______.. _-______.. _/c_____.. __/c____.. ___/c___.. ____/c__.. _____/c_.. ______/c.. _______-_. _________. ________.. ``` Input: 6 0 3 ``` c___.. /c__.. _/c_.. c_/c.. /c_-_. _/c__. c_/c.. ``` ## Rules: [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 shortest code wins [Answer] ## JavaScript (ES6), ~~250~~ 243 bytes This code is assuming code page #1252 and is using the `·` character (0xB7). Takes input as 3 distinct parameters `(a,b,c)`. ``` (a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+` `+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a) ``` ### How it works This code starts with a string such as `-______··` and applies successive regular expressions on each iteration to animate the waves. For instance `-__` is replaced with `_-_`. At first, it looked like a reasonable idea. However, the fact that the string may start with a `c` (like it does in the 3rd test case) makes things significantly more complicated. ### Test cases ``` f = (a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+` `+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a) console.log(f(14, 4, 6)) console.log(f(10, 2, 11)) console.log(f(6, 0, 3)) ``` [Answer] ## Batch, ~~273~~ 243 bytes ``` @echo off set f=for /l %%i in (0,1,%1)do call set s=set b= %s%.. %f% %s%_%%b%% %f%:c %%i %2 %3 exit/b :c set/aw=%1%%%3 if %w%==0 %s%__-%b:~3% if %w%==%2 %s%%b:_-=/c% %s%_%b:~0,-4%%b:~-3% %s%%b:__. =_.. % %s%%b:/.=-_% echo %b:~3% ``` Note: Trailing space on line 4. If only the two beach characters were different, I could save 3 bytes and actually beat JavaScript! ]
[Question] [ *This challenge is based on the game [Layerz.](http://layerzgame.com/)* Given, on stdin or as a function argument, a 2D rectangular array of cells where each cell contains either a blank (you may choose to use 0s instead of blanks at no penalty), a 1, a 2, a 3, or a 4; find a way to divide it into valid regions (as defined below) such that each non-blank cell is contained by exactly one region. Then, output the solution found in any reasonable format. If there is no solution, either halt without producing output or output a single falsey value then halt. Any of the following constitutes a valid region: * A single cell containing a 1 * A cell containing a 2 and exactly one of its non-blank orthogonal neighbors * A cell containing a 3 and exactly two of its non-blank orthogonal neighbors * A cell containing a 4 and exactly three of its non-blank orthogonal neighbors This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer, in bytes, wins. **Some test cases:** **1. A rather trivial one:** ![enter image description here](https://i.stack.imgur.com/xtrqo.png) And this is the solution, with each region in a different color: ![enter image description here](https://i.stack.imgur.com/9MDmc.png) **2. A more interesting one** ![enter image description here](https://i.stack.imgur.com/qaYAh.png) This one has more than one solution, but here's one of them: ![enter image description here](https://i.stack.imgur.com/4qnaw.png) **3. A smaller one, containing blanks, that doesn't have any solutions (depending on whether you use one of the twos to "capture" the three, or the three to take two of the twos, you're either left with a pair of nonadjacent [and therefore nongroupable] twos or a single two on its own):** ![enter image description here](https://i.stack.imgur.com/NHSND.png) Because this grid has no solutions, your program should halt without producing any output when given this grid. **4. This one (with the top 2 shifted one cell to the left) does have a solution though:** ![enter image description here](https://i.stack.imgur.com/E2FIT.png) Solution: ![enter image description here](https://i.stack.imgur.com/1sIko.png) (The bottom right 2 is used to "capture" the 3) **5. Because we needed a test case with some fours:** ![](https://i.stack.imgur.com/2H59m.png) One solution: ![](https://i.stack.imgur.com/722JP.png) [Answer] I know this challenge is over an year old, but I just found this in "unanswered" and looked quite interesting to me. Assuming that the "root" cell's number is the only significant one in each region (deducible from the examples), here is my backtracking solution: # [Python 3](https://docs.python.org/3/), 355 351 349 bytes ``` from itertools import* def f(a): D=len(a[0])+1;S={D*r+c for r in range(len(a))for c in range(D-1)if a[r][c]};s=[{x,*t}for x in S for t in combinations({x-D,x-1,x+1,x+D}&S,a[x//D][x%D]-1)] def B(s,S,d=1): if{0}>S:return a if[]==s:return 0 h,*t=s if h<=S: for x in h:a[x//D][x%D]=d return h<=S and B(t,S-h,d+1)or B(t,S,d) return B(s,S) ``` [Try it online!](https://tio.run/##dVHBrtsgELzzFVzaZxKih0NOfqWHyn/gI0UVDbi2lOAIqOQqyrenC37EqZ6qyNLM7Cw72b38icPk@P3e@@mMx2h9nKZTwOP5Mvm4Qcb2uK80aRBuxcm6SkumyLZ@68S13fjtEfeTxx6PDnvtftkqewhJ6nFV211Nxh5r6ZU8qttbEPI60028Jd@cfF1@KCZ4nM4/R6fjOLlQXeddS@ddTedt@trb545qOb@@tkrOn1oFDyuEU8xvVaAdNaJOYfHYX9nta9d4G397h3WWpBIiFImBNEAGEXIND19ElzrxI9PQPE8SBorvvcmLtTMwNNJuN1CzrQm0ZUoNQcWYQ5F7XuM5/rj40cVlnQvcaBrsRbx8dy/UOpMAQIKQ0VELibCUNYWfojD8IwS8WDjli74HnRfLfrUwIKxYON0XHdT/6IlkndNDeZIBZEV9mvnwMoBsnZki8OeeFI@t9lR9d5XMPNND@Z88k8O/jv3SpBRSCKVzmXSutDJY7Lrn5Q5B9BnBiYE0axkYyPYUbPMQno9w/ws "Python 3 – Try It Online") The input format is a 2D list of integers, blanks as zero, and the output format is also a 2D list of integers representing one region per number. The region number starts at one; zero is reserved for blank cells (as in input). If the given input is unsolvable, the function returns single zero (falsy value). For example, the test case 5 is input as ``` [[2,3,2], [3,4,3], [0,4,0], [3,3,3], [2,3,2], [0,3,0]] ``` and the output is ``` [[1,1,1], [2,2,2], [0,2,0], [3,4,5], [3,4,5], [0,4,0]] ``` Ungolfed, with comments: ``` from itertools import* def f(a): # Rows, cols, fake-cols to prevent neighbors wrap around R,C=len(a),len(a[0]);D=C+1 # All valid cells represented as integers S={D*r+c for r in range(R) for c in range(C) if a[r][c]} # All valid regions rooted at each cell s=[{x,*t} for x in S for t in combinations({x-D,x-1,x+1,x+D}&S,a[x//D][x%D]-1)] # Start backtracking return backtrack(a,s,S,D) # a: array to fill in the region numbers # s: current candidates of regions # S: current remaining cells to cover # D: constant from f # d: recursion depth == group number in the result def backtrack(a,s,S,D,d=1): # Empty S: the board is correctly covered, return the result if not S:return a # Empty s: no more candidate regions to use, return false if not s:return 0 h,*t=s # h is not a subset of S: h is not a valid cover, try with the rest using same depth if not h<=S:return backtrack(a,t,S,D,d) # h is a valid cover, write d to the cells in h for x in h:a[x//D][x%D]=d return backtrack(a,t,S-h,D,d+1)or backtrack(a,t,S,D,d) ``` [Try it online!](https://tio.run/##dVPBjpswEL37K0ZatQ2JoyWbnmg5VEt/YHOkqHKwCWjBRrbZJFrtt6czECDtbhUlGY/H7715HrdnXxq9vVwKaxqovLLemNpB1bTG@iWTqoBiIYKIwR08maPjkOM@h0I8qzWF4A20Vr0o7UGr6lDujXVwtKIFYU2nJYMn/hjXSiMM7//SMAu@JfHjakOoP@oaXkRdSchVjXhWIZxDOCVBoBIMDso6Brv4NVnaVQ6FsWBxA6zQB7V4CvpMPmceA6gKEKnN0jx7@5vEqkNlNNIY0zN4UCIve24GLk5fT3zp33rEEyHu@tBTmJtmX2nh6fzi9bRO@Gm94acVfZO3zzsu0tP9fZKlp09Jtt4EGTHvvLAe9iJ/9hZ/Kn1gqMF3Vs/JheCO73gSMHYHIkLjrDiTsUWFupHZl@oqHHTX7MmOO3AR5J21ZHwutKyk8MqBKcYWsWQ3l1jViEoj/dVmRM/Ni7JYlWAV1nuBZf0cFJiUER7Bw45IpWp9CXEMB7zS9qphFua62vej8q4jLuPNMDw/m9afSRAd2RthJVQOeVFd7uvzIEZJPppzg0yXqY3Hw9c9MQOiCdpAY6yaTZjuGHvsnJogC1E7NaG5ES1kUOKdx45QS1JF2wJct3fKk6Go@iZ/HVbSy8HbMxwrNOeq1yMjmexEowbbJsLyezx1cGuUH4wKJvp/KI4W3yVI6oZIhutD7xF5mtIyup29WH44Y0i0LolqtQnw4McaLv2Tb/zv1uLTG57@EC7xTlUbf/mlv3ClJQUY4syi5yJOGaTphuMn4wzgfYjxULLl2yH/gPntWPIwl4S4CMeSLX8Y85j9T54WfX7Lv46QIYbhmL3hnGpDDMMsYxlj5KMkH6kVbHjunyzBa42LPqrocblo3sYVphXOVTQlbs25/AE "Python 3 – Try It Online") **Note:** This is a special case of [Set Packing](https://en.wikipedia.org/wiki/Set_packing) which is well-known to be NP-complete. This specific problem has limited set size (max. 4) and there exist approximation algorithms to find "good" set packing in polynomial time, but they don't guarantee the maximum possible set packing (which is strictly required in this problem). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 94 [bytes](https://github.com/abrudz/SBCS) ``` ⎕CY'dfns' {0≡a←X⊢b←⊃⍪/{v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x←v∩⍵(+,-)↓0 2⊤⍳2]}∘⊂¨v←⍸×w←⍵:0⋄(b+.×⍨a×+\a)@v⊢w} ``` [Try it online!](https://tio.run/##fU6xSsNQFN3zFW/LC2n0JXFyUrooOJkOSs3wYpsixERoSSKli0poI69YisTV0qGK4CAF5@ZP7o/E@0JxEVzeue@cc@85/CYwOrc8iHpVBdPn5rna8cO@qgwZTF45ZE9nkC88RMjvQbzvDmMY5yCWJtIg1o20TZM2Dq5hapfXfACTRYpudL0hS/WGoUE2Z8SCfAniy3JHMH6B/G6ziuVR8V0WST2s9xk8PlBP3ykLECteFvoF1w5izElGlV97plhi82lDNsOqzmkT39bRsbMt3ufBQMUb3ZB7Qdc5PGkprhelV2GPRKFSp2QzahKb2Bq1iCnBJDhoik8SBcTHrwn7EiZNNrH@qqj9q0qa2mRPBjAEJn/b1FpjCKze/AE "APL (Dyalog Unicode) – Try It Online") -4 bytes thanks to @Adám. Improvements are: * `x←...⋄...cmat≢x` → `...cmat≢x←...` (-2 bytes) * `(+\×⊢)a` → `a×+\a` (-2 bytes) --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 98 [bytes](https://github.com/abrudz/SBCS) ``` ⎕CY'dfns' {0≡a←X⊢b←⊃⍪/{x←v∩⍵(+,-)↓0 2⊤⍳2⋄v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x]}∘⊂¨v←⍸×w←⍵:0⋄(b+.×⍨(+\×⊢)a)@v⊢w} ``` [Try it online!](https://tio.run/##fU/BSsNAEL3nK/bWXdLoJvHkSelFwZPpQak5bGxThJgILUmk9KIS2pUtliL1auihiuBBCp7bP5kfiZNQvAhe9r3Z9@bNjLgJjPatCKJuUcDkuXFea/thr6YNOIxfBWRPZyBzDxHkPaj33UGKPIbRG6gV1esGg2zGiQVyAerLgscH1CSohYltaKmnLZq0kLiGyS6vRR/GeeoOYfQC8m69jMtg9b2ZJxVZ7XNMoJ6@s5mDWlL9AlHmTLCDGDEZFn7lm@Ay608bsimu7Jw28G0eHTvbA3oi6NcwpxMKL@g4hydNzfWi9CrskijUqknZlJrEJjajFjFLMAkSpvkk0UB9/JrwMsJLk02svypq/6rlN7XJXjmAI/Cy2k6tNI7Aq84f "APL (Dyalog Unicode) – Try It Online") Well, who would have imagined a language having [Knuth's Algorithm X](https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X) as a [built-in library function](http://dfns.dyalog.com/n_X.htm)? Algorithm X is an algorithm designed to solve Exact Cover problems, and the challenge here is exactly this kind of problem. Now it just becomes a matter of constructing the *constraint matrix* (a boolean matrix whose columns represent *constraints* and rows represent *actions* that satisfy some of the constraints). Then X solves the problem by finding the collection of rows so that 1 appears exactly once per column. ### Ungolfed with comments ``` ⎕CY'dfns' ⍝ Load `cmat` and `X` f←{ ⍝ v←Coordinates of nonzero positions v←⍸×w←⍵ ⍝ Given an enclosed coord, generate constraint rows Rowgen←{ ⍝ Extract 4-way neighbors that are part of the board x←v∩⍵(+,-)↓0 2⊤⍳2 ↓0 2⊤⍳2 ⍝ Fancy way to say (0 1)(1 0) ⍵(+,-) ⍝ Input coord plus/minus 1 horizontally/vertically v∩ ⍝ Set intersection with valid coords ⍝ Boolean matrix where each row represents a possible tile placement ⍝ and 1 marks the covered cells by that tile v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x] (w[⍵]-1)cmat≢x ⍝ Possible combinations of neighbors ⍵,x[ ] ⍝ Index into x and prepend ⍵ v∊⍤1⊢ ⍝ Mark covered cells as 1 } ⍝ bmat←Constraint matrix; vertical concatenation of constraint rows bmat←⊃⍪/Rowgen∘⊂¨v ⍝ ans←Solution by Algorithm X ans←X bmat ⍝ Return 0 if answer not found (single zero) 0≡ans:0 ⍝ Mark the pieces as distinct integers starting from 1 ⍝ (increasing in the order of the root cell) (bmat+.×⍨(+\×⊢)ans)@v⊢w (+\×⊢)ans ⍝ Assign distinct numbers to 1 bits ⍝ 1 0 0 1 0 1 1 .. → 1 0 0 2 0 3 4 .. bmat+.×⍨ ⍝ Extract associated numbers for all valid cells ( )@v⊢w ⍝ Overwrite valid cells of w with ^ } ``` ]
[Question] [ Let's build a simulation for an aspect in the card game, which I personally know by the Dutch name 'Oorlog' (translates to 'War'). ## How does 'Oorlog' work? Two decks of cards (each including two Jokers) are equally divided between the amount of players playing. Each player shuffles their own stock, put it upside down in front of them, and all players open up the first card of the stock at the same time. The winner of that 'battle' is determined by the values of the cards following these rules: Joker/Ace defeats King; King defeats Queen; Queen defeats Jack; Jack defeats 10; 10 defeats 9; .... In addition, both 2 and 3 defeat Ace/Joker. The last rule may lead to a cycle where 2 or 3 beats Ace or Joker, Ace or Joker beats some other card, which in turn beats the 2 or 3. In this case, the 2 or 3 wins the battle. (Suit is irrelevant in this card game.) When two or more players have the equal highest cards, they have a 'war'. This means they put one card upside down, and then each opens up a new card from their stock, again looking who has the highest card. This continues until a single player wins the entire battle. (All cards of that battle go to the discard pile of the player that won the battle. Then everyone opens up a new card. When a player's stock is out of cards, they turn their discard pile upside down and continue with this new stock. This continues until a player is out of all his/her cards and then the player with the highest amount of cards wins.) ***Example 'battles' with three players:*** 1. 4, 8, Jack: Jack wins. 2. 7, Ace, Queen: Ace wins. 3. 10, 10, King: King wins. 4. 3, Joker, 2: 3 wins. 5. Ace, Joker, 2: 2 wins. 6. 3, Queen, Ace: 3 wins. 7. Queen, Queen, 9: Queen & Queen are having a 'war', so it continues with two new cards: 4, 8; 8 wins. 8. 4, 4, 4: All are having a 'war', so it continues with three new cards: 8, Ace, 2; 2 wins. 9. Jack, 5, Jack: Jack & Jack are having a 'war', so it continues with two new cards: 5, 5; 5 & 5 are also equal, so the 'war' continues again with two new cards: 10, King; King wins. 10. Joker, Joker, Ace: All are having a 'war', so it continue with three new cards: 9, 7, 9; 9 & 9 are also equal, so the 'war' continues with two new cards: Jack, 3; Jack wins. --- ## So, onto the code challenge: **Input:** STDIN with an array, or a string simulating an array (your call - even if your language does support arrays). This array contains the cards of a battle in chronological order (see test cases for a clearer understanding of this). **Output:** STDOUT the index of the player that won the battle. You can choose whether you want a zero-indexed (i.e. `0`, `1`, or `2`) or one-indexed output (i.e. `1`, `2`, `3`). **Challenge rules:** * The input will be a single array / string representing an array. So you can't have an array of arrays to simplify it. You also can't have surrogate items for cards not participating in the war. * We use number notations for the face-cards instead of letter notation. So Ace/Joker = `1`; Jack = `11`; Queen = `12`; and King = `13`. * In this challenge we can assume we are always playing with **3 players**. * The first three indicate the start of the 'battle'. When two or more players have a 'war' the continuing cards in the array indicate their battle (see test cases for a clearer understanding of this). **General rules:** * This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. This doesn't mean non code-golfing languages shouldn't enter. Try to come up with an as short as possible code-golf answer for 'every' programming language. * Please mention which indexing (zero- or one-indexed) you've used for the output. ***Test cases:*** ``` Test case 1: [4, 8, 11] -> 2 (or 3) Test case 2: [7, 1, 12] -> 1 (or 2) Test case 3: [10, 10, 13] -> 2 (or 3) Test case 4: [3, 1, 2] -> 0 (or 1) Test case 5: [1, 1, 2] -> 2 (or 3) Test case 6: [3, 12, 1] -> 0 (or 1) Test case 7: [12, 12, 9, 4, 8] -> 1 (or 2) Test case 8: [4, 4, 4, 8, 1, 2] -> 2 (or 3) Test case 9: [11, 5, 11, 5, 5, 10, 13] -> 2 (or 3) Test case 10: [1, 1, 1, 9, 7, 9, 11, 3] -> 0 (or 1) Test case 11: [13, 13, 4, 1, 3] -> 1 (or 2) Test case 12: [13, 4, 13, 2, 3] -> 2 (or 3) ``` [Answer] ### q - 142 characters ``` {p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p} ``` Note: zero indexed. There is no notion of reading stdin in q, so you should call it as a function: `{p:til 3;while[1<(#:)p;h:(n:(#:)p)#x;x:n _x;$[1~min h;p:$[max a:h in(2;3);$[1<(#:)(?:)h(&:)a;p(&:)h=3;p(&:)a];p(&:)h=1];p:p(&:)h=max h]];(*:)p}[1,2,3]` Pretty long, actually, but there are plenty of corner cases. It keeps a roster of active players, and consumes the list of cards in a loop. The most problematic thing is to detect the correct winner in hands like `[13, 2, 3]`, since `3` beats `2`, as normal, but it had to be duplicated to be put into the corner case. [Answer] ## JavaScript (ES6), 146 bytes ``` f=a=>(b=a.splice(0,3)).filter(m=>m-n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length>1?b.indexOf(n):f([...b.map(m=>m-n?0:a.shift()),...a]) ``` Returns a zero-based index. 127 bytes if I'm allowed the initial deal as a separate array (this also works for an arbitrary number of hands of course): ``` f=(b,a)=>b.filter(m=>m==n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length<2?b.indexOf(n):f(b.map(m=>m-n?0:a.shift()),a) ``` [Answer] # Java 8, ~~257~~ 247 bytes ``` int c(int[]a){int t=0,f=0,q,r=0,i=-1,l=a.length,x[];for(;++i<3;t=a[i]>t?a[r=i]:t)a[i]+=a[i]==1?f++*0+13:0;for(;i-->0;t=f<1|a[i]>3|t==3&2<a[i]?t:a[r=i]);for(f=i,x=new int[q=l<7?3:l>7?l-3:5];l>3&++i<q;)x[i]=t==a[i]|i>2?a[++f+3]:0;return l>3?c(x):r;} ``` -10 bytes thanks to *@ceilingcat*. Ok, my challenge is harder than I thought it would be with everything in a single array like that. ;) But since it's been more than I year ago since I posted this challenge, I decided to give it a go myself. Took me quite a while with multiple work-arounds and quirks.. So it can definitely be golfed some more, but I'll look into that another time. This already took way longer than I expected.. **Explanation:** [Try it here.](https://tio.run/##hVNNj5swEL33V4z2sILyIYwTpYU4qD@gpz1GHFwCW6deSMywZZXkt6djw7aXTSoxxh6/efNmbO/lq4y6Q93ud7@ulZZ9D9@lak@fAHqUqCq4qhah8mjcltI/2RWKJGzIjqGhUYmIhVrIWNftM/4Mx22ZN53x8iBQa56jkFtVbrCQWyNUmaFv14HzCsGKJgg@JwHjWTJFqSjaJBTVrNnZRfIzCsEf07VdFZhNPL5DN0KFo2jr32D1HYVerwqe6c2q0BHPlmWuN/zR6jjm/mgTEpWlOatNSoKCoAl4SZlNjYNpgdBF5Y1@ZvLLFeAw/NDUgbkRr53awQs1x3tCo9rnbQnUD2oUANY9eu8qytMihC8hMHYJIfXzjxAr2qYvJQT7GMES2rLGb7Nwx2JJkhskfwF3GFKyOxTpBPkagi3rtuCFA8yl303KaHtp@@N@y//XOZXBnIiVG20svyPa1sWdmhnIbgMXEzadgJOEC9m/J@BO3kW6KJChDQc1n76dGxD0SGRc6a6tPX/O9vTWY/0SdwPGB7oyqFtvTw8uHlDp@Jsx8q2PsZuukyd9COAhg3o81BXWO2J8II@yXshBVjhIPTvN7LRzTwlh/Fn25foH) ``` int c(int[]a){ // Recursive method with integer-array parameter & integer return int t=0,f=0,q, // Temp integers r=0, // Result-integer i=-1, // Index-integer l=a.length, // Length of the input-array x[]; // Temp array we use when there is a war for(;++i<3 // Loop `i` in the range [0,3): ;t= // After every iteration, change `t` to: a[i]>t? // If the current item is larger than `t`: a[r=i] // Use the current item (and save its index in `r`) : // Else: t) // Leave `t` the same a[i]+=a[i]==1? // If the current item is a 1 (Ace/Joker): f++*0 // Increase `f` by 1, +13 // and change the 1 to 14 (by increasing with 13) : // Else: 0; // Leave the current item the same (by increasing with 0) for(;i-->0; // Loop `i` in the range (3,0]: t=f<1 // If no Joker/Ace was present |a[i]>3 // Or the current item is NOT a 2 or 3 |t==3 // Or `t` is 3: &a[i]>2? // and the current item is NOT a 2: t // Leave `t` unchanged : // Else: a[r=o]); // Change `t` to the current item (and save its index in `r`) for(f=i, // Reset `f` to -1 x=new int[ // Create the temp array `x` with length: q=l<7? // If the current length is 6 or lower: 3 // New length after war is 3 :l>7? // Else-if the current length is 8 or higher: l-3 // New length after war is the current length - 3 : // Else(-if current length is 7): 5]; // New length after war is 5 l>3& // If there is a war: ++i<q;) // Loop `i` in the range [0,3): x[i]=t==a[i] // If the current item is at war, |i>2? // or the current item is after the first 3 items: a[++f+3] // Fill the new array with the correct next item : // Else: 0; // Fill the item of the new array with 0 // (since it won't participate in the next round) return l>3? // If there was a war: c(x) // Recursive-call with the new array : // Else: r;} // Return the index of the card that won ``` ]
[Question] [ Because rickrolling is the greatest meme on Earth, you *[know the rules and so do I]* are to write the shortest code that can textually rickroll the unsuspecting reader. Let *[you down]* there be an input text which contains letters, punctuation, and spaces. Anytime a *[lie and hurt you]* phrase from the first two stanzas appears in the text... ``` We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you ``` ...insert the rest of the line in brackets afterwards. **Input** Input is a single line string containing only printable ASCII with optional trailing newline. **Output** Output is a single-line string. Any time that a group of words (defined as the input string split on spaces) matches a group of words in lines of the lyrics above, insert the remaining words of the line into the string, grouped in square brackets. **Additional Description:** This is **code-golf**, fewest bytes wins. You may write a program [or function.](https://www.youtube.com/watch?v=dQw4w9WgXcQ) * matching should be case insensitive: `we're` is converted to `we're [no strangers to love]` even though `We're` is capitalized in the lyrics. * matching should be greedy. `Does he know the answer?` should be converted to `Does he know the [rules and so do I] answer?` instead of `Does he know [the rules and so do I] the [rules and so do I] answer?` * If a word appears more than once in the provided lyrics, choose any of the occurrences to complete the line. * If a word is the last word in the lyric line, don't insert anything after it. * Punctuation is included as part of a "word." `I'm` is a single word and cannot match with `I`. Similarly, `you.` doesn't match with any lyrics because of the period. Some words like `I` appear multiple times throughout the lyrics as well as at the end of a line. Since the rule is that any occurrence in the above lyrics can be used, and one of those occurrences is at the end of a line, no matching of `I` is necessary. The other option for `I` is `[just wanna tell you how I'm feeling]`. If two matches overlap, you may choose either one. This means that `how I'm thinking` could become `how I'm [feeling] thinking [of]` OR `how [I'm feeling] I'm thinking [of]` since the `I'm` could be part of either `how I'm` or `I'm thinking`. If, however the input text was simply `I'm thinking`, then the output should be `I'm thinking [of]`. ## Additional test cases: ``` I don't know what I'm doing with my life. is converted to I [just wanna tell you how I'm feeling] don't know [the rules and so do I] what I'm [thinking of] doing with my life. Many additional solutions are possible, since words like `I` appear multiple times. Will someone please save me from these memes? is converted to Will someone please save me from [any other guy] these memes? Two strangers walked into a bar. One said "hello." The other said "goodbye." is converted to Two strangers [to love] walked into a [lie and hurt you] bar. One said "hello." The [rules and so do I] other [guy] said "goodbye." ``` --- Challenge inspired by [this dude](https://www.reddit.com/r/AskReddit/comments/2okve8/could_reddit_guess_the_name_of_a_song_if_you/cmo93mu). [Answer] # gawk, 316+377 = 693 First command line parameter is the lyrics' filename (375 bytes + 2 for invocation = 377). Rickrolls all other files. Prints to `stdout`. ``` BEGIN{FPAT="[^ ]+ *";OFS=""}func d(a){b=tolower(a);sub(/ *$/,"",b);return b}FNR==NR{for(s=$0;NF;$0=s=$0){for(i=1;i<NF;i++){k=k $i;$i="";v[d(k)]="["$0"] "}$0=s;k=$1=""}next}{for(s=$0;NF;$0=s=$0){for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)="");k=v[d($0)];if($0!~/ $/)k=" "k;printf($0 k);for($0=s;j-->=0;$(j+2)="");}print""} ``` ## Ungolfed ``` BEGIN{FPAT="[^ ]+ *";OFS=""} func d(a){b=tolower(a);sub(/ *$/,"",b);return b} FNR==NR{ for(s=$0;NF;$0=s=$0){ for(i=1;i<NF;i++) { k=k $i; $i=""; v[d(k)]="["$0"] " } $0=s; k=$1="" } next } { for(s=$0;NF;$0=s=$0){ for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)=""); k=v[d($0)]; if($0!~/ $/)k=" "k; printf($0 k); for($0=s;j-->=0;$(j+2)=""); } print"" } ``` ## Test results Input: ``` we're We're Does he know the answer? I how I'm thinking I'm thinking I don't know what I'm doing with my life. Will someone please save me from these memes? Two strangers walked into a bar. One said "hello." The other said "goodbye." gonna run ``` Output: ``` we're [no strangers to love] We're [no strangers to love] Does he know the [rules and so do I] answer? I [just wanna tell you how I'm feeling] how I'm [feeling] thinking [of] I'm thinking [of] I [just wanna tell you how I'm feeling] don't know [the rules and so do I] what I'm [thinking of] doing with my life. Will someone please save me from [any other guy] these memes? Two strangers [to love] walked into a [lie and hurt you] bar. One said "hello." The [rules and so do I] other [guy] said "goodbye." gonna run [around and desert you] ``` ]
[Question] [ # Objective Design a [**mo**dulator/**dem**odulator pair](https://en.wikipedia.org/wiki/Modem) to accurately transmit data as quickly as possible over simulated [plain old telephone service (POTS)](https://en.wikipedia.org/wiki/Plain_old_telephone_service). # Steps 1. Generate some random (`/dev/random` or the like) data that will take 3-4 seconds to transmit 2. Modulate the data with your modulator to produce an audio file 3. Pass the audio file through the [POTS simulator](https://simphone.herokuapp.com/). If you don't have Python/Scipy you can upload a file with the form, or do a JSON API request. 4. Demodulate the audio file back to binary data 5. Validate that the input and output are equal-ish\* (limit 1 out of every 1000 bits can be corrupted) 6. Score is number of bits transmitted divided by the length of the audio file (bits/second) # Rules * Input file must be 3-4 seconds, 44.1 kHz, mono. * Run the simulator with an SNR of 30 dB (it's default) * The demodulator must reconstruct the transmitted data with a bit error rate of no more than 10-3 (1 per thousand bits). * No digital compression is allowed (i.e. zipping the data. It's outside the scope of the challenge.) * No attempting to shove data into frequencies above 4 kHz. (My filters aren't perfect, but they're reasonably POTS-like with a relatively small number of taps.) * If your modem protocol requires a short preamble (no more than 1 second) to synchronize/calibrate the receiver, it isn't penalized. * If possible, *please host the audio file* somewhere accessible so we can listen to a cacophony of beeps and boops. # Example [Here's an **example notebook**](https://nbviewer.jupyter.org/github/nicktimko/pots-sim/blob/master/OOK_simple_demo.ipynb) that demonstrates the modulation/demodulation with simple "on-off keying" (audio samples included!). It would score 100 (bits/second). Note that it's transmitting with a much worse 5 dB SNR. [Answer] # MATLAB, 1960 bps Here is my updated attempt: ``` fs = 44100; %44.1kHz audio rate fc = 2450; %2.45kHz carrier - nice fraction of fs! fsym = fc/5; %symbol rate tmax = 4; %about 4 seconds worth preamblesyms = 6; t = 1/fs:1/fs:(tmax+preamblesyms/fsym); symbols = preamblesyms+fsym*tmax; symbollength = length(t)/symbols; bits = symbols*3; bitstream = [zeros(1,preamblesyms*3),rand(1,bits-preamblesyms*3)>0.5]; %Add a little preamble of 18 bits data = bin2dec(char(reshape(bitstream,3,symbols)'+'0'))'; greycode = [0 1 3 2 6 7 5 4]; %Encode the symbols using QAM8 - we use effectively grey code so that %adjacent symbols in the constellation have only one bit difference %(minimises error rate) encoded = zeros(2,symbols); encoded(1,data==1) = 1/sqrt(2); encoded(1,data==3) = 1; encoded(1,data==2) = 1/sqrt(2); encoded(1,data==7) = -1/sqrt(2); encoded(1,data==5) = -1; encoded(1,data==4) = -1/sqrt(2); encoded(2,data==0) = 1; encoded(2,data==1) = 1/sqrt(2); encoded(2,data==2) = -1/sqrt(2); encoded(2,data==6) = -1; encoded(2,data==7) = -1/sqrt(2); encoded(2,data==4) = 1/sqrt(2); %Modulate onto carrier carrier = [sin(2*pi*fc*t);cos(2*pi*fc*t)]; signal = reshape(repmat(encoded(1,:)',1,symbollength)',1,[]); signal(2,:) = reshape(repmat(encoded(2,:)',1,symbollength)',1,[]); modulated = sum(signal.*carrier)'; %Write out an audio file audiowrite('audio.wav',modulated,fs); %Wait for the user to run through the POTS simulator input(''); %Read in the filtered data filtered=audioread('audio.pots-filtered.wav')'; %Recover the two carrier signals preamblecos = filtered(symbollength+1:symbollength*2); preamblesin = filtered(symbollength+1+round(symbollength*3/4):symbollength*2+round(symbollength*3/4)); %Replicated the recovered carriers for all symbols carrierfiltered = [repmat(preamblesin,1,symbols);repmat(preamblecos,1,symbols)]; %Generate a demodulation filter (pass up to 0.66*fc, stop at 1.33*fc %(really we just need to kill everything around 2*fc where the alias ends up) d=fdesign.lowpass('Fp,Fst,Ap,Ast',0.05,0.1,0.5,60); Hd = design(d,'equiripple'); %Demodulate the incoming stream demodulated = carrierfiltered .* [filtered;filtered]; demodulated(1,:)=filtfilt(Hd.Numerator,1,demodulated(1,:)); demodulated(2,:)=filtfilt(Hd.Numerator,1,demodulated(2,:)); %Split signal up into bit periods recovereddemodulated=[]; recovereddemodulated(1,:,:) = reshape(demodulated(1,:),symbollength,symbols); recovereddemodulated(2,:,:) = reshape(demodulated(2,:),symbollength,symbols); %Extract the average level for each bit period. Only look at the second %half to account for slow rise times in the signal due to filtering recoveredsignal=mean(recovereddemodulated(1,round(symbollength/2):symbollength,:)); recoveredsignal(2,:)=mean(recovereddemodulated(2,round(symbollength/2):symbollength,:)); %Convert the recovered signal into a complex number. recoveredsignal=recoveredsignal(2,:) + 1j*recoveredsignal(1,:); %Determine the magnitude and angle of the symbol. The phase is normalised %to pi/4 as that is the angle between the symbols. Rounding this to the %nearest integer will tell us which of the 8 phases it is closest to recoveredphase = round(angle(recoveredsignal)/(pi/4)); recoveredphase = mod(recoveredphase+8,8)+1; %Remap to an index in the grey code vector. %Determine the symbol in the QAM8 constellation recoveredencoded=greycode(recoveredphase); recoveredencoded(1:preamblesyms)=0; %Assume the preamble is correct for comparison %Turn it back in to a bit stream bitstreamRecovered = reshape(dec2bin(recoveredencoded)'-'0',1,[]); %And check if they are all correct... if(all(bitstream==bitstreamRecovered)) disp(['Woop, ' num2str(fsym*4) 'bps']); else error('Its corrupt Jim.'); end ``` Since my first attempt, I have played around a bit. There is now a small preamble at the beginning (18 bit periods, but could be shorter) which contains just a cosine wave. I extract this and replicated it to create correctly phased sine and cosine carriers for demodulation - as it is a very short preamble, I haven't counted it in the bit rate as per your instructions. Also since the first attempt I am now using a QAM8 constellation to achieve 3 bits per symbol instead of 2. This effectively doubles the transfer rate. So with a ~2.4kHz carrier I am now achieving 1960bps. I've also improved the symbol detection so that the averaging doesn't get affected by slow rise times caused by the filtering - basically only the second half of each bit period is averaged to remove the impact of rise times. Still nowhere near the 40kbps theoretical channel bandwidth from the [Shannon-Hartley theory](https://en.wikipedia.org/wiki/Shannon%E2%80%93Hartley_theorem) (assuming the 30dB SNR) Just for those that like *horrible* sounds, this is the new entry: --- And in case anyone is interested, this is the previous 960bps entry ]
[Question] [ # Scores This section will be filled in as submissions are entered. **Normal** ``` 1. bopjesvla Perl 54 2. edc65 Javascript (ES6) 91 3. name language score 4. name language score 5. name language score ``` **Bonus Round** ``` 1. name language score 2. name language score 3. name language score 4. name language score 5. name language score ``` --- # Karel J. AlphaBot **Background** A popular introductory course to Java is [Karel J. Robot](https://rads.stackoverflow.com/amzn/click/com/0970579519) (I'm using it myself). The robot interacts with a grid of streets (positive integer y-coordinates) and avenues (positive integer x-coordinates) as well as beepers, which can be placed and stored on the grid (note that Karel and any beepers can only exist on lattice points). Karel (the robot) is only to perform five actions: move forward by 1, turn left in place, put down a beeper, pick up a beeper, and turn itself off. In my Computer Science class, one of our first assignments was to program Karel to learn how to turn right, turn around, and perform the combined action of moving forward by 1 and putting down a beeper. An assignment a few days later was to use these methods and write new methods to produce letters of the alphabet. Naturally, once I finished this assignment, I wrote more methods to make every letter of the alphabet, as well as the ten numerical digits, and I plan to figure out how to make a sort of word processor out of the robot, where a string would be entered to STDIN and the robot would put beepers on the grid in a way that resembled the letters. Every time I wrote `private void draw#` for each character `#`, I added a comment after it that would tell me abbreviations for the sequence of commands I'd need. I have the following commands (written in pseudocode) at my disposal (clarification - these are the only *useful* commands). ``` Turn Left Rotate the robot 90˚ counterclockwise Abbreviated as "l" Turn Right Rotate the robot 90˚ clockwise Abbreviated as "r" Move Move one space forwards Abbreviated as "m" Put Beeper Put a beeper on the spot that Karel is on Abbreviated as "p" Drop Beeper Move, then Put Beeper Abbreviated as "d" Turn Around Turn Left, then Turn Left Abbreviated as "a" ``` --- **Conditions** The robot must proceed in the following order. * The robot starts on the bottom left corner of the 5xN rectangle of minimal area the letter will be drawn in. * The robot draws the letter. * The robot moves to the bottom right corner of the rectangle. * The robot moves two spaces to the right and *must face north/up* Let's work through an example. Suppose we want to draw `A`. The location of the robot is the letter that indicates its direction (north, south, east, west). The letter is capitalized if the robot is on a spot with a beeper and lowercase if the robot is on a spot without a beeper. `o` represents spots with beepers and `.` represents spots without beepers. As we will see later, `A` is this. ``` .ooo. o...o ooooo o...o o...o ``` Here is one possible solution. ``` Grids ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... N.... E.... oE... ooE.. oooE. oooW. ..... ..... N.... o.... o.... o.... o.... o.... o.... n.... N.... o.... o.... o.... o.... o.... o.... o.... Letters p d d r d d d a ..... ..... ..... ..... ..... n.... e.... .E... .oE.. ..... ..... ..... ..... N.... o.... o.... o.... o.... ooWo. oWoo. Wooo. Nooo. oooo. oooo. oooo. oooo. oooo. o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... o.... m m m r d m r d d .ooE. .oooe .ooos .ooo. .ooo. .ooo. .ooo. .ooo. o.... o.... o.... o...S o...o o...o o...o o...o oooo. oooo. oooo. oooo. ooooS ooooo ooooo ooooo o.... o.... o.... o.... o.... o...S o...o o...o o.... o.... o.... o.... o.... o.... o...S o...E d m r d d d d l ``` The final `mml` to complete the fourth bullet is implicit because it appears in every letter and because I don't want to go back and add another two columns to everything in the above proposed solution. Thus, one solution to make `A` is `pddrdddammmrdmrdddmrddddlmml`. Note that this doesn't have to be your solution. Your algorithm can go through every column, putting beepers in the proper places and not relying on where other beepers have been placed or will be placed. No matter what your algorithm is, the robot can only place one beeper per space on the grid. --- **The program** Your program will take as its input a 5xN grid of what the grid for the letter is. Note that there is no robot on the input; the robot is assumed to be on the bottom left (southwest) corner, facing north. The output will be the sequence of letters that are the shorthand for the sequence. *Sample inputs* ``` .ooo. o...o ooooo o...o o...o o...o.ooooo o...o...o.. ooooo...o.. o...o...o.. o...o.ooooo ``` *Sample outputs* ``` pddrdddammmrdmrdddmrddddlmml prmmmlmlmmdrdrdddlmlmmdrdrmmmdrddddlmmlprdddlmldmmrmrmdmlmldmmrdrddddrmmmdlmml ``` --- This is code golf, fellas. Standard CG rules apply. Shortest code in bytes wins. --- # Bonus Round **Rules** If you want to participate in the bonus round, be sure to make your codes move-efficient! Below is a library of all of the 5x5 letters my program creates when it runs. The objective of the bonus round is to write a program that prints a sequence for `ABCDEFGHIJKLMNOPQRSTUVWXYZ` that contains as few moves as possible. There is no input to STDIN. Code will be graded *not* on the length of the code but on its "move score." The move score is designed to discourage sweeper algorithms that visit every point in the rectangle. ``` d: 1 l: 1 m: 4 p: 1 r: 1 ``` **Letters** ``` .ooo. oooo. ooooo oooo. ooooo ooooo .oooo o...o o...o o...o o.... o...o o.... o.... o.... o...o ooooo oooo. o.... o...o oooo oooo. o.ooo ooooo o...o o...o o.... o...o o.... o.... o...o o...o o...o oooo. ooooo oooo. ooooo o.... oooo. o...o ooooo ....o o...o o.... ooooo o...o ooooo oooo. ..o.. ....o o..o. o.... o.o.o oo..o o...o o...o ..o.. ....o oo... o.... o.o.o o.o.o o...o oooo. ..o.. o...o o..o. o.... o...o o..oo o...o o.... ooooo .ooo. o...o ooooo o...o o...o ooooo o.... oooo. oooo. ooooo ooooo o...o o...o o...o o...o o..o. o...o o.... ..o.. o...o o...o o...o .o.o. o..o. oooo. ooooo ..o.. o...o .o.o. o.o.o ..o.. oooo. o..o. ....o ..o.. o...o .o.o. o.o.o .o.o. ....o o...o ooooo ..o.. ooooo ..o.. ooooo o...o o...o ooooo .o.o. ...o. ..o.. ..o.. .o... .o... o.... ooooo ``` The same procedure as the original challenge must be followed: letters must be drawn one at a time with a space separation between each letter. Standard CG rules apply. Entry with the lowest move score wins. --- --- --- To summarize, both codes will essentially do the same things. The first code should have a minimal number of bytes in the code, and the second code should use the smallest number of moves. [Answer] # perl -p0, ~~60 56~~ 54+2 bytes **[golf](https://ideone.com/WgIoKm)** ``` / /;$:="m"x"@-";$_=mmmmlma.s/ /rmr$:a/gr.mml;y/.o/md/; ``` **notes** ``` /\n/; # capture the length of the first line $:="m"x"@-"; # assign a string of m's with that length to $: s/^/mmmmlmll/; # move to the starting position (-1,0) s/\n/rmr$:rr/g; # replace all newlines with kareliage returns y/.o/md/; # replace dots with moves and o's with drops s/$/mml/; # append mml ``` [Answer] # JavaScript (ES6), 91 A first try to the basic challenge. Test running the snippet below in an EcmaScript 6 compliant browser (tested in Firefox) ``` // BASIC CHALLENGE ANSWER f=s=>`mmmmr${[...s].map(c=>c<' '?[`mrmr${b}a`,b=m][0]:(b+=m,c>m?'pm':m),b=m='m').join``}ml` /* ALSO ... f=s=>`mmmmr${s.replace(/.|\s/g,c=>c<' '?[`mrmr${b}a`,b=m][0]:(b+=m,c>m?'pm':m),b=m='m')}ml` */ // TEST // now, I need to implement Karel (and test it) to do a significant test // (a super limited version of Karel, of course. Just what is needed) Karel=(cmd, width, height) => // even if for this test we have a limited height to handle { var grid = [...('.'.repeat(width)+'\n').repeat(height)], o = width+1, p = o*(height-2)+1, d = [-o, 1, o, -1], // direction offsets q = 0, // face up s = [...grid], steps = []; s[p] = 'n'; steps.push([s.join``,'-']); [...cmd].forEach(c => ( c == 'l' ? q = q-1 &3 : c == 'r' ? q = q+1 &3 : c == 'a' ? q = q+2 &3 : c == 'm' ? p += d[q] : c == 'p' ? grid[p] = 'o' : c == 'd' ? grid[p += d[q]] = 'o' : 0, s = [...grid], s[p] = s[p] == 'o' ? 'NESW'[q] : 'nesw'[q], steps.push([s.join``,c]) ) ) return [s.join``,steps] } function go(cmd) { var result = Karel(cmd,260,7) RESULT.innerHTML = result[0]; STEPS.innerHTML = 'Steps:<br>'+result[1].map(x=>'<pre>'+x.join('\n')+'</pre>').join('') } function test(input) { var exp = input.innerHTML; var cmd = f(exp); var result = Karel(cmd,20,7) CMD.innerHTML = cmd; RESULT.innerHTML = result[0]; STEPS.innerHTML = 'Steps:<br>'+result[1].map(x=>'<pre>'+x.join('\n')+'</pre>').join('') } ``` ``` pre { float: left; border: 1px solid #888; margin: 2px } div { clear: both; } #CMD { word-break: break-all; white-space: normal; width:50%; overflow:auto; } #Y { width:50%; } ``` ``` Test cases (click to run a test)<br> <pre id=T1 onclick='test(this)'>.ooo. o...o ooooo o...o o...o</pre> <pre id=T2 onclick='test(this)'>o...o.ooooo o...o...o.. ooooo...o.. o...o...o.. o...o.ooooo</pre> <div>Command string:<br><pre id=CMD></pre></div> <div> Your Command:<br><input id=Y><button onclick='go(Y.value)'>-></button> </div> <div>Result:<br><pre id=RESULT></pre></div> <div id=STEPS>Steps</div> ``` **BONUS CHALLENGE ANSWER - Score for full alphabet=869** Test running the wnippet below in Firefox (better full screen) As I don't like *fixed input/fixed output* challenges, you can try your input. Just remember, only letters will be printed. ``` // Optimal - working on small pattern but too slow (scale bad) // So I build the total command letter by letter - that surely is NOT globally optimal Key=sol=>sol.pos+' '+sol.setBits Solve=(target, startRow, startDir, cmd)=>{ // Target is a rectangle string 5x5, newline separated for total (5+1)*5 chars if (target[target.length-1] != '\n') target += '\n'; var T = ~new Date() var width = 5, height = 5, startPos = (width+1)*startRow; var offset = [-width-1, 1, width+1, -1]; var turns = [ "", "r", "rr", "l" ]; var cmds = [ "m", "rm", "rrm", "lm", "d", "rd", "rrd", "ld" ]; var visited = {}, scan =[[],[],[],[],[],[],[],[]], cscan; var baseSol = { steps:[], pos: startPos, dir: startDir, setBits: 0}; var score = 0, j = 0 var bit, key, turn, curSol, move, result var targetBits = 0; [...target].map((c,i)=>targetBits |= ((c=='o')<<i)) // 30 bits // First step, from outside, set bit in mask if it's set in target if (target[startPos]=='o') baseSol.setBits = 1<<startPos; console.log(target, targetBits.toString(16)) visited[Key(baseSol)] = scan[0].push(baseSol); for (j = 0; j<99; j++) { cscan = scan[j]; scan.push([]) // console.log(`T: ${T-~new Date} J: ${j} SC: ${cscan.length}`) while (cscan.length > 0) { baseSol = cscan.pop() //console.log('Base', baseSol.dir, baseSol.pos, baseSol.setBits.toString(16), baseSol.steps.length) for(turn = 0; turn < 4; turn++) { // set direction, move and drop if you can curSol = {}; curSol.dir = baseSol.dir + turn & 3; curSol.pos = baseSol.pos + offset[curSol.dir]; // console.log(turn, curSol.dir, curSol.pos) if(target[curSol.pos] > ' ' || curSol.dir == 1 && target[curSol.pos]=='\n' ) // if inside grid or on right border facing east { score = j + (turn == 2 ? 3 : turn == 0 ? 1 : 2); bit = 1 << curSol.pos; if (targetBits & bit) curSol.setBits = baseSol.setBits | bit, move = 4 | turn; else curSol.setBits = baseSol.setBits, score += 3, move = turn; if (!visited[key = Key(curSol)]) { curSol.steps = [...baseSol.steps, move] // clone and add // task completed if on right border and all bits ok if (target[curSol.pos]>' ') { // not on right border, proceed visited[key] = scan[score].push(curSol) } else if (curSol.setBits == targetBits) { result = curSol.steps.map(v=>cmds[v]).join`` result = (cmd == '' ? target[startPos]=='o' ? 'p' : '' : target[startPos]=='o' ? 'd' : 'm') + result; console.log(`T: ${T-~new Date} J: ${j} CMD: ${result}`) return [cmd+result, curSol.pos / (width+1) | 0]; } } } } } } // Miserable failure! return [] } console.log=(...x)=>LOG.innerHTML+=x+'\n'; // TEST Karel=(cmd, width, height) => // even if for this test we have a limited height to handle { var grid = [...('.'.repeat(width)+'\n').repeat(height)], o = width+1,p = o*(height-2)+1,d = [-o, 1, o, -1], // direction offsets steps = [],s = [...grid],q = 0; // face up s[p] = 'n'; steps.push([s.join``,'-']); [...cmd].forEach(c => ( c == 'l' ? q = q-1 &3 : c == 'r' ? q = q+1 &3 : c == 'a' ? q = q+2 &3 : c == 'm' ? p += d[q] : c == 'p' ? grid[p] = 'o' : c == 'd' ? grid[p += d[q]] = 'o' : 0, s = [...grid], s[p] = s[p] == 'o' ? 'NESW'[q] : 'nesw'[q], steps.push([s.join``,c]) ) ) return [s.join``,steps] } var AlphabetMap = `.ooo..oooo..ooooo.oooo..ooooo.ooooo..oooo.o...o.ooooo.....o.o...o.o.....ooooo.o...o.ooooo.oooo..oooo..oooo..ooooo.ooooo.o...o.o...o.o...o.o...o.o...o.ooooo o...o.o...o.o.....o...o.o.....o.....o.....o...o...o.......o.o..o..o.....o.o.o.oo..o.o...o.o...o.o..o..o...o.o.......o...o...o.o...o.o...o..o.o...o.o.....o. ooooo.oooo..o.....o...o.oooo..oooo..o.ooo.ooooo...o.......o.oo....o.....o.o.o.o.o.o.o...o.oooo..o..o..oooo..ooooo...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..oo.o...o.o.....oooo..o..o......o...o...o...o..o.o..o.o.o..o.o...o.....o... o...o.oooo..ooooo.oooo..ooooo.o.....oooo..o...o.ooooo..ooo..o...o.ooooo.o...o.o...o.ooooo.o.........o.o...o.ooooo...o...ooooo...o...ooooo.o...o.o.....ooooo`.split('\n') var LetterMap = []; var l,row,m; for (l=0;l<26;l++) { for(m='',row=0;row<5;row++) m += AlphabetMap[row].substr(l*6,5)+'\n' LetterMap[l]=m; } print=Message=>{ var Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' var startRow = 4, cmd='' var startDir = 0 // start facing UP ;[...Message].forEach(l => ( [cmd, startRow] = Solve(LetterMap[Alphabet.search(l)], startRow, startDir, cmd), startDir = 1, // after each letter will be facing RIGHT cmd += '\n' // addin a newline (scoring 0) just for readability )) if (startRow != 4) cmd += 'mr'+'m'.repeat(4-startRow)+'rr' // on last row and facing up else cmd += 'ml' // ...facing up // Recalc score var score = 0 ;[...cmd].forEach(c=>score += c=='m'? 4 : c<' '? 0: 1) var robot = Karel(cmd.replace(/\n/g,''), 26*7, 7) O.innerHTML=cmd+'\nScore:'+score R.innerHTML=robot[0] RS.innerHTML=robot[1].join`\n` } function test() { var msg = I.value.toUpperCase() msg=msg.replace(/[^A-Z]/g,'') I.value=msg print(I.value) } test() ``` ``` fieldset { padding:0; } pre { margin: 2px; } #RS { height: 200px; width: 50%; overflow:auto; } #I { width: 50% } ``` ``` <fieldset ><legend>Message to print</legend> <input id=I value='ABCDEFGHIJKLMNOPQRSTUVWXYZ'><button onclick='test()'>go</button></fieldset> <fieldset ><legend>Command Result (newlines added for readability)</legend> <pre id=O></pre></fieldset> <fieldset ><legend>Robot output</legend> <pre id=R></pre></fieldset> <fieldset ><legend>Robot step by step</legend> <pre id=RS></pre></fieldset> <fieldset ><legend>log</legend> <pre id=LOG></pre></fieldset> ``` ]
[Question] [ Given a list of strings, find the **smallest square** matrix that contains each of the initial strings. The strings may appear horizontally, vertically or diagonally and forwards or backwards like in this question [Word Search Puzzle](https://codegolf.stackexchange.com/questions/37940/word-search-puzzle/37976#37976). Words should be placed in the square, with at least one word in each direction (horizontal, vertical and diagonal). Words should appear just one time. So, the input is just a list of words. For example: `CAT, TRAIN, CUBE, BICYCLE`. One possible solution is: ``` B N * * * * * * I * * C A T * A C * * * * * R * Y * * C * T * * C * U * * * * * L B * * * * * * E ``` I replaced filling letters with asterisks just for clarity. The desired output should include random filling letters. [Answer] # JavaScript (ES6), 595 ~~628 680~~ **Edit** Some cleanup and merge: - function P merged inside function R - calc x and z in the same .map - when solution found, set x to 0 to exit outer loop - merged definiton and call of W **Edit2** more golfing, random fill shortened, outer loop revised ... see history for something more readable ~~Unlike the accepted answer,~~ this should work for most inputs. Just avoid single letter words. If an output is found, it's optimal and using all 3 directions. The constraint of avoiding repeating words is very hard. I had to look for repeating word at each step adding word to the grid, and at each random fill character. Main subfunctions: * P(w) true if palindrome word. A palindrom word will be found twice when checking for repeated words. * R(s) check repeating words on grid s * Q(s) fill the grid s with random characters - it's recursive and backtrack in case of repeating word - and can fail. * W() recursive, try to fill a grid of given size, if possibile. The main function use W() to find an output grid, trying from a size of the longest word in input up to the sum of the length of all words. ``` F=l=>{ for(z=Math.max(...l.map(w=>(w=w.length,x+=w,w),x=0)); ++z<=x; (W=(k,s,m,w=l[k])=>w?s.some((a,p)=>!!a&& D.some((d,j,_,r=[...s],q=p-d)=> [...w].every(c=>r[q+=d]==c?c:r[q]==1?r[q]=c:0) &&R(r)&&W(k+1,r,m|1<<(j/2)) ) ) :m>12&&Q(s)&&(console.log(''+s),z=x) )(0,[...Array(z*z-z)+99].map((c,i)=>i%z?1:'\n')) ) D=[~z,-~z,1-z,z-1,z,-z,1,-1] ,R=u=>!l.some(w=>u.map((a,p)=>a==w[0]&&D.map(d=>n+=[...w].every(c=>u[q+=d]==c,q=p-d)), n=~([...w]+''==[...w].reverse()))&&n>0) ,Q=(u,p=u.indexOf(1),r=[...'ABCDEFGHIJHLMNOPQRSTUVWXYZ'])=> ~p?r.some((v,c)=>(r[u[p]=r[j=0|c+Math.random()*(26-c)],j]=v,R(u)&&Q(u)))||(u[p]=1):1 //,Q=u=>u.map((c,i,u)=>u[i]=c!=1?c:' ') // uncomment to avoid random fill } ``` **Ungolfed** and explained (incomplete, sorry guys it's a lot of work) ``` F=l=> { var x, z, s, q, D, R, Q, W; // length of longest word in z z = Math.max( ... l.map(w => w.length)) // sum of all words length in x x = 0; l.forEach(w => x += w.length); for(; ++z <= x; ) // test square size from z to x { // grid in s[], each row of len z + 1 newline as separator, plus leading and trailing newline // given z==offset between rows, total length of s is z*(z-1)+1 // gridsize: 2, z:3, s.length: 7 // gridsize: 3, z:4, s.length: 13 // ... // All empty, nonseparator cells, filled with 1, so // - valid cells have a truthy value (1 or string) // - invalid cells have falsy value ('\n' or undefined) s = Array(z*z-z+1).fill(1) s = s.map((v,i) => i % z != 0 ? 1 : '\n'); // offset for 8 directions D = [z+1, -z-1, 1-z, z-1, z, -z, 1, -1]; // 4 diags, then 2 vertical, then 2 horizontal // Function to check repeating words R = u => // return true if no repetition ! l.some( w => // for each word (exit early when true) { n = -1 -([...w]+''==[...w].reverse()); // counter starts at -1 or -2 if palindrome word u.forEach( (a, p) => // for each cell if grid { if (a == [0]) // do check if cell == first letter of word, else next word D.forEach( d => // check all directions n += // word counter [...w].every( c => // for each char in word, exit early if not equal u[q += d] == c, // if word char == cell, continue to next cell using current offset q = p-d // starting position for cell ) ) // end for each direction } ) // end for each cell return n > 0 // if n>0 the word was found more than once } ) // end for each word // Recursive function to fill empty space with random chars // each call add a single char Q = ( u, p = u.indexOf(1), // position of first remaining empty cell r = [...'ABCDEFGHIJHLMNOPQRSTUVWXYZ'] // char array to be random shuffled ) => { if (~p) // proceed if p >= 0 return r.some((v,c)=>(r[u[p]=r[j=0|c+Math.random()*(26-c)],j]=v,R(u)&&Q(u)))||(u[p]=1) else return 1; // when p < 0, no more empty cells, return 1 as true } // Main working function, recursive fill of grid W = ( k, // current word position in list s, // grid m, // bitmask with all directions used so far (8 H, 4V, 2 or 1 diag) w = l[k] // get current word ) => { var res = false if (w) { // if current word exists res = s.some((a,p)=>!!a&& D.some((d,j,_,r=[...s],q=p-d)=> [...w].every(c=>r[q+=d]==c?c:r[q]==1?r[q]=c:0) &&R(r)&&W(k+1,r,m|1<<(j/2)) ) ) } else { // word list completed, check additional constraints if (m > 12 // m == 13, 14 or 15, means all directions used && Q(s) ) // try to fill with random, proceed if ok { // solution found !! console.log(''+s) // output grid z = x // z = x to stop outer loop res = x//return value non zero to stop recursion } } return res }; W(0,s) } } ``` **Test** in Firefox/FireBug console F(['TRAIN', 'CUBE','BOX','BICYCLE']) ``` ,T,C,B,O,X,B,H, ,H,R,U,H,L,I,H, ,Y,A,A,B,E,C,B, ,D,H,S,I,E,Y,I, ,H,E,R,L,N,C,T, ,G,S,T,Y,F,L,U, ,H,U,Y,F,O,E,H, ``` *not filled* ``` ,T,C,B,O,X,B, , , ,R,U, , ,I, , , , ,A,B, ,C, , , , , ,I,E,Y, , , , , , ,N,C, , , , , , , ,L, , , , , , , ,E, , ``` F(['TRAIN','ARTS','RAT', 'CUBE','BOX','BICYCLE','STORM','BRAIN','DEPTH','MOUTH','SLAB']) ``` ,T,A,R,C,S,T,H, ,S,R,R,L,U,D,T, ,T,B,A,T,N,B,P, ,O,B,O,I,S,A,E, ,R,B,A,X,N,H,D, ,M,R,M,O,U,T,H, ,B,I,C,Y,C,L,E, ``` F(['AA','AB','AC','AD','AE','AF','AG']) ``` ,A,U,B,C, ,T,A,E,Z, ,C,D,O,F, ,Q,C,G,A, ``` F(['AA','AB','AC','AD','AE','AF']) *output not filled* - @nathan: now you can't add another A*x* without repetitions. You'll need a bigger grid. ``` ,A, ,C, , ,A,F, ,D,E,B, ``` [Answer] ## C# Here's a simple implementation with still work to be done. There are very many combinations to get smallest size. So just used simplest algorithm in could think of. ``` class Tile { public char C; public int X, Y; } class Grid { List<Tile> tiles; public Grid() { tiles = new List<Tile>(); } public int MaxX() { return tiles.Max(x => x.X); } public int MaxY() { return tiles.Max(x => x.Y); } public void AddWords(List<string> list) { int n = list.Count; for (int i = 0; i < n; i++) { string s = list[i]; if(i==0) { Vert(s, 0, 0); } else if(i==n-1) { int my = MaxY(); Diag(s, 0, my+1); } else { Horiz(s, 0, i); } } } private void Vert(string s, int x, int y) { for (int i = 0; i < s.Length; i++) { Tile t = new Tile(); t.C = s[i]; t.X = x+i; t.Y = y; tiles.Add(t); } } private void Horiz(string s, int x, int y) { for (int i = 0; i < s.Length; i++) { Tile t = new Tile(); t.C = s[i]; t.X = x+i; t.Y = y; tiles.Add(t); } } private void Diag(string s, int x, int y) { for (int i = 0; i < s.Length; i++) { Tile t = new Tile(); t.C = s[i]; t.X = x++; t.Y = y++; tiles.Add(t); } } public void Print() { int mx = this.MaxX(); int my = this.MaxY(); int S = Math.Max(mx, my) + 1; char[,] grid = new char[S, S]; Random r = new Random(DateTime.Now.Millisecond); //fill random chars for (int i = 0; i < S; i++) { for (int j = 0; j < S; j++) { grid[i, j] = (char)(r.Next() % 26 + 'A'); } } //fill words tiles.ForEach(t => grid[t.X, t.Y] = t.C); //print for (int i = 0; i < S; i++) { for (int j = 0; j < S; j++) { Console.Write("{0} ", grid[i,j]); } Console.WriteLine(); } } } class WordSearch { public static void Generate(List<string>list) { list.Sort((x, y) => { int s = 0; if (x.Length < y.Length)s = -1; else if (y.Length < x.Length)s = 1; return s; }); list.Reverse(); Grid g = new Grid(); g.AddWords(list); g.Print(); } } ``` Test ``` class Program { static void Main(string[] args) { string words = "CAT, TRAIN, CUBE, BICYCLE"; string comma=","; List<string> w = words.Split(comma.ToArray()).ToList(); List<string> t = new List<string>(); foreach(string s in w) { t.Add(s.Trim()); } WordSearch.Generate(t); Console.ReadKey(); } } ``` ]
[Question] [ We define a [Collatz](http://en.wikipedia.org/wiki/Collatz_conjecture)-like sequence `s` with 4 positive integers: * `n` starting value * `d > 1` divisor * `m > 1` multiplier * `i` increment (In the original Collatz sequence `d = 2` `m = 3` and `i = 1`.) Given these integers `s` will be created in the following manner: * `s(0) = n` * if `k > 0` and `s(k-1) mod d = 0` then `s(k) = s(k-1) / d` * if `k > 0` and `s(k-1) mod d != 0` then `s(k) = s(k-1) * m + i` An example sequence with `d = 2, m = 3, i = 5` and `n = 80` will be `s = 80, 40, 20, 10, 5, 20, 10, 5, 20, ...`. Every sequence will either reach higher values than any given bound (i.e. the sequence is divergent) or get into an infinite loop if for some `t` and `u` (`t!=u`) the `s(t) = s(u)` equality will be true. In our problem if the value of a sequence element is larger than `10^9` or there is no element repetition before the `1000`th element the sequence is considered divergent. ## The task You should write a program or function which takes the positive integers `d` `m` and `i` as inputs and outputs all the different ending types of the sequences (infinite loops and divergence) which the starting values `n = 1, 2, 3, ... 999, 1000` can produce. ## Input details * The input is a string or list (or closest equivalent in your language) representing (in the common way) three positive integers `d`, `m` and `i` in that order. `d` and `m` are at least `2`. Neither number is larger than `100`. ## Output details *The output specification is a bit wordy. Might worth to check out the examples first.* * You should output to the standard output (or closest alternative) or return a string. * If divergent sequence is possible the first line should be `DIVERGENT`. * A unique representation of a sequence's loop is it's rotation where the smallest number is the last separated by spaces. E.g. if `s = 2 1 4 2 1 4 2 1` the loop is `4 2 1`. * In every following line you should output every unique loop exactly once preceded by the word `LOOP`. E.g. `LOOP 4 2 1` * The loops should be in ascending order in regard of their last element. * Trailing newline is optional. ## Examples: The first lines are the inputs and the following ones until a blank line are the outputs. ``` 2 3 1 LOOP 4 2 1 2 2 6 LOOP 8 4 2 1 LOOP 12 6 3 3 7 8 DIVERGENT LOOP 15 5 43 309 103 729 243 81 27 9 3 1 LOOP 22 162 54 18 6 2 LOOP 36 12 4 3 9 1 DIVERGENT 6 9 9 DIVERGENT LOOP 18 3 36 6 1 LOOP 27 252 42 7 72 12 2 LOOP 45 414 69 630 105 954 159 1440 240 40 369 3330 555 5004 834 139 1260 210 35 324 54 9 90 15 144 24 4 LOOP 81 738 123 1116 186 31 288 48 8 LOOP 99 900 150 25 234 39 360 60 10 LOOP 126 21 198 33 306 51 468 78 13 10 10 10 LOOP 20 2 30 3 40 4 50 5 60 6 70 7 80 8 90 9 100 10 1 93 91 92 DIVERGENT LOOP 2185 198927 2139 23 LOOP 4278 46 ``` [Reference implementation in Python 3 on Ideone.](http://ideone.com/OMl6aK) This is code-golf so shortest entry wins. [Answer] # Python 3, ~~269~~ ~~254~~ ~~252~~ 246 bytes ``` d,m,i=eval(input()) S=set() for n in range(1,1001): T=X=() while len(T)**3<1e9>=n: T=(n,)+T;n=[n//d,n*m+i][n%d>0] if n in T:I=T.index;L=T[:I(n)+1];M=I(min(L));X=L[M:]+L[:M] S|={X} for x in sorted(S):print(x and"LOOP"or"DIVERGENT",*x[::-1]) ``` *(Now 10 times slower to save a few bytes. Typical code golf.)* Input a list via STDIN (e.g. `[2, 3, 1]`). I'm thinking that there's got to be a better way of standardising the cycles... The approach is quite straightforward — test all 1000 numbers and take only the unique outputs. However, there are two little tricks in there: * Loops are represented by nonempty tuples, but more importantly divergence is represented by an *empty* tuple. This is good because: + It doesn't break `sorted`, and will even appear *before* all the loop tuples + It allows us to select a string via `x and"LOOP"or"DIVERGENT"` + `*()[::-1]` doesn't affect `print` * The loops are built backwards to turn "sort ascending by last element" into "sort ascending by first element", which removes the need to pass a lambda into `sorted`. ## Previous submission, 252 bytes ``` d,m,i=eval(input()) def f(n,T=()): x=[n//d,n*m+i][n%d>0];I=T.index if x in T:L=T[:I(x)+1];M=I(min(L));return L[M:]+L[:M] return()if(T[1000:]or x>1e9)else f(x,(x,)+T) for x in sorted(set(map(f,range(1,1001)))):print(x and"LOOP"or"DIVERGENT",*x[::-1]) ``` This one's a lot faster. ]
[Question] [ In this contest you have to write a program, that accepts a black and white pixel image, and tries to alter it, such that the white shape forms **star domain**, with as few changes as possible. Allowed changes are turning white pixels into black ones and turning black pixels into white ones. The output must again consist of the same image but this time with all the changes and with a/the center marked. The pixels that were changed from white to black must be displayed in blue, the ones that were changed from black to white must be displayed in yellow, and at least one center pixel must be displayed in red. (Exact colours are up to you.) The program must ouput the specified image as well as the total number of changes that were made. # Definitions ### Star Domain The set of white pixels of the image represent a **star domain** if (and only if) there is (at least) one **center pixel**. The **center pixel** is one of the white pixels that can be conneced by a **straight line** to all of the other white pixels such that the line only traverses white pixels. (The **center pixel** is therefore not necessarily unique.) ### Straight line between two pixels Given two pixel (start and end, both red in the illustration below), the **straigth line** between the two pixels consists of all the pixels, that touch the (mathematical, yellow in the illustration below) line that leads from the center of the first pixel to the center of the last pixel. A pixel is *not* touching the line if it only touches it by a corner, so for a pixel to belong to the *pixel line* the (mathematical, yellow) line has to cross the pixel in question with a nonzero length. (If it only touches the corner point this is considered as length zero). Consider the following examples: ![pixels](https://i.stack.imgur.com/DIgmk.png) # Example The first image should represent an example testcase 'input' and the two other images represent two valid possible outputs for the given example: ![example testcase](https://i.stack.imgur.com/hBXZX.png) ![first example solution](https://i.stack.imgur.com/obRQs.png) The yellow areas (formerly black) count to the 'white' domain as well, while the blue areas (formerly white) count to the 'black' part outside of the domain, and the red dot each time represents one possible center pixel. # Test Cases The follwoing test cases are png's with each a size of 256 x 256 pixels. ![test case 1](https://i.stack.imgur.com/R1Pq7.png) ![test case 2](https://i.stack.imgur.com/Lr8vU.png) ![test case 3](https://i.stack.imgur.com/kFwVz.png) ![test case 4](https://i.stack.imgur.com/WfF2u.png) ![test case 5](https://i.stack.imgur.com/j4wGv.png) ![test case 6](https://i.stack.imgur.com/iThXZ.png) # Scoring Please run your program with the following test cases and include the output (image / number of changes) in your answer. I will make a leaderboard for each test case. Your score will be the sum of each ranking in the leaderboard -the lower the score the better. Standard loopholes apply. It is not allowed to make the program recognize those test cases and run a special case for them. (It is not allowed to precompute and save the optimal center pixels for each of those test cases.) The program should work for any images. # Leaderboard ``` Name | Score | 1 - rk | 2 - rk | 3 - rk | 4 - rk | 5 - rk | 5 - rk | Total Changes ------------+-------+------------+------------+------------+------------+------------+------------+-------------- Maltysen | 11 | 28688 - 2 | 24208 - 2 | 24248 - 1 | 7103 - 2 | 11097 - 2 | 13019 - 2 | 108363 TheBestOne | 7 | 0 - 1 | 13698 - 1 | 24269 - 2 | 103 - 1 | 5344 - 1 | 4456 - 1 | 47867 ``` [Answer] # Java 8, 47,867 changes total. Uses the average of the image as the center point. It then draws all possible rays to the center and gives it the best radius to color. It then colors all invalid points black. ``` import javax.imageio.ImageIO; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.List; public class MakeItStarry { private static final int RGB_RED = Color.RED.getRGB(); static int[][] originalImage; static final int WHITE = 0; static final int BLACK = 1; static final int RGB_WHITE = Color.WHITE.getRGB(); static final int RGB_BLACK = Color.BLACK.getRGB(); static final int RGB_BLUE = Color.BLUE.getRGB(); static final int RGB_YELLOW = Color.YELLOW.getRGB(); public static void main(String[] args) throws Exception{ originalImage = convert(ImageIO.read(new File(args[0]))); Point center = findCenter(originalImage); int[][] nextImage = starry(originalImage, center); BufferedImage result = difference(originalImage, nextImage); result.setRGB(center.x, center.y, RGB_RED); String fileType; String fileName; if (args[1].split("\\.").length > 1){ fileType = args[1].split("\\.")[1]; fileName = args[1]; } else { fileType = "PNG"; fileName = args[1] + ".PNG"; } ImageIO.write(result, fileType, new File(fileName)); System.out.println(cost); } static int cost; private static BufferedImage difference(int[][] image1, int[][] image2) { cost = 0; int height = image1[0].length; int width = image1.length; BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++){ for (int y = 0; y < width; y++){ if (image1[x][y] == image2[x][y]){ if (image1[x][y] == WHITE){ result.setRGB(x, y, RGB_WHITE); } else { result.setRGB(x, y, RGB_BLACK); } } else { cost++; if (image1[x][y] == WHITE){ result.setRGB(x, y, RGB_BLUE); } else { result.setRGB(x, y, RGB_YELLOW); } } } } return result; } private static int[][] starry(int[][] image, Point center) { int width = image.length; int height = image[0].length; int[][] result = new int[width][height]; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ result[x][y] = BLACK; } } for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++) { Point endPoint = new Point(x, y, image); List<Point> line = Point.lineTo(center, endPoint, image); List<Point> newLine = starRay(line); newLine.stream().filter(point -> result[point.x][point.y] == BLACK).forEach(point -> { result[point.x][point.y] = point.color; }); } } int distance = 0; while (distance < height || distance < width){//This removes pixels that can't see the center. for (int x = Math.max(center.x - distance,0); x < center.x + distance && x < width; x++){ for (int y = Math.max(center.y - distance, 0); y < center.y + distance && y < height; y++){ Point point = new Point(x, y, result); if (Point.distance(center, point) != distance){ continue; } if (point.color == WHITE){ List<Point> line = Point.lineTo(center, point, result); for (Point p : line){ if (p.color == BLACK){ point.color = BLACK; break; } } result[point.x][point.y] = point.color; } } }//All white pixels can technically see the center but only if looking from the edge. distance++; } return result; } private static List<Point> starRay(List<Point> line) { int numOfWhites = 0; int farthestGoodPoint = 0; int blackCost = 0; int whiteCost = 0; for (int i = 0; i < line.size(); i++){ if (line.get(i).color == WHITE){ numOfWhites++; whiteCost++; if (numOfWhites + whiteCost > blackCost){ blackCost = 0; whiteCost = 0; farthestGoodPoint = i; } } else { blackCost++; numOfWhites = 0; } } List<Point> result = new ArrayList<>(); for (int i = 0; i < line.size(); i++){ Point p = line.get(i); if (i <= farthestGoodPoint){ result.add(new Point(p.x, p.y, WHITE)); } else { result.add(new Point(p.x, p.y, BLACK)); } } return result; } private static Point findCenter(int[][] image) { double totalx = 0; double totaly = 0; int counter = 0; int width = image.length; int height = image[0].length; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ if (image[x][y] == WHITE){ totalx += x; totaly += y; counter++; } } } return new Point((int)(totalx/counter), (int)(totaly/counter), image); } private static int[][] convert(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); int[][] result = new int[width][height]; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ if (image.getRGB(x, y) == RGB_WHITE){ result[x][y] = WHITE; } else { result[x][y] = BLACK; } } } return result; } private static class Point { public int color; public int y; public int x; public Point(int x, int y, int[][] image) { this.x = x; this.y = y; this.color = image[x][y]; } public Point(int x, int y, int color) { this.x = x; this.y = y; this.color = color; } public static List<Point> lineTo(Point point1, Point point2, int[][] image) { List<Point> result = new ArrayList<>(); boolean reversed = false; if (point1.x > point2.x){ Point buffer = point1; point1 = point2; point2 = buffer; reversed = !reversed; } int rise = point1.y - point2.y; int run = point1.x - point2.x; if (run == 0){ if (point1.y > point2.y){ Point buffer = point1; point1 = point2; point2 = buffer; reversed = !reversed; } int x = point1.x; for (int y = point1.y; y <= point2.y; y++){ result.add(new Point(x, y, image)); } if (reversed){ return reversed(result); } return result; } if (rise == 0){ if (point1.x > point2.x){ Point buffer = point1; point1 = point2; point2 = buffer; reversed = !reversed; } int y = point1.y; for (int x = point1.x; x <= point2.x; x++){ result.add(new Point(x, y, image)); } if (reversed){ return reversed(result); } return result; } int gcd = gcd(rise, run); rise /= gcd; run /= gcd; double slope = (rise + 0.0) / run; if (Math.abs(rise) >= Math.abs(run)){ if (point1.y > point2.y){ Point buffer = point1; point1 = point2; point2 = buffer; reversed = !reversed; } double x = point1.x; for (double y = point1.y + .5; y <= point2.y; y++){ int px = (int) Math.round(x); if (Math.abs(Math.abs(px - x) - .5) < Math.abs(1.0 / (rise * 4))){ x += 1/slope; continue; } result.add(new Point(px, (int) Math.round(y - .5), image)); result.add(new Point(px, (int) Math.round(y + .5), image)); x += 1/slope; } if (reversed){ return reversed(result); } return result; } else { if (point1.x > point2.x){ Point buffer = point1; point1 = point2; point2 = buffer; reversed = !reversed; } double y = point1.y; for (double x = point1.x + .5; x <= point2.x; x++){ int py = (int) Math.round(y); if (Math.abs(Math.abs(py - y) - .5) < Math.abs(1.0 / (run * 4))) { y += slope; continue; } result.add(new Point((int) Math.round(x - .5), py, image)); result.add(new Point((int) Math.round(x + .5), py, image)); y += slope; } if (reversed){ return reversed(result); } return result; } } private static List<Point> reversed(List<Point> points) { List<Point> result = new ArrayList<>(); for (int i = points.size() - 1; i >= 0; i--){ result.add(points.get(i)); } return result; } private static int gcd(int num1, int num2) { if (num1 < 0 && num2 < 0){ return -gcd(-num1, -num2); } if (num1 < 0){ return gcd(-num1, num2); } if (num2 < 0){ return gcd(num1, -num2); } if (num2 > num1){ return gcd(num2, num1); } if (num2 == 0){ return num1; } return gcd(num2, num1 % num2); } @Override public String toString(){ return x + " " + y; } public static int distance(Point point1, Point point2) { return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y); } } } ``` # Results ## Image 1 - 0 changes, Image 2 - 13,698 changes ![1](https://i.stack.imgur.com/AKPGS.png)![2](https://i.stack.imgur.com/6lIDG.png) ## Image 3 - 24,269 changes, Image 4 - 103 changes ![3](https://i.stack.imgur.com/lzYeN.png)![4](https://i.stack.imgur.com/0jQYL.png) ## Image 5 - 5,344 changes, Image 6 - 4,456 changes ![5](https://i.stack.imgur.com/rFgJj.png)![6](https://i.stack.imgur.com/kTKj9.png) # Without invalid pixels removed, 42,782 changes total Green pixels are the first layer of invalid pixels. ## Image 1 - 0 changes, Image 2- 9,889 changes ![1](https://i.stack.imgur.com/Td2xs.png)![2](https://i.stack.imgur.com/e9Aii.png) ## Image 3 - 24,268 changes, Image 4 - 103 changes ![3](https://i.stack.imgur.com/9kXHg.png)![4](https://i.stack.imgur.com/q65c2.png) ## Image 5 - 4,471 changes, Image 6- 4,050 changes ![5](https://i.stack.imgur.com/43aQl.png)![6](https://i.stack.imgur.com/SW869.png) All white pixels in all the pictures can have a line drawn to them from the center pixel if the line does not have to originate/end at the centers but rather anywhere on the pixel. `args[0]` contains input file name. `args[1]` contains output file name. Prints to `stdout` number of changes. [Answer] # Python - PIL - 216,228 108,363 changes total Whoo! Cut it in half thanks to @AJMansfield! This algorithm skips all the worrying about with calculating lines and optimization and what not. It just changes all whites to black except for one. If there are no whites, it makes one black a white. It check if there are more whites or black and changes every single one of the other kind to it except for one. If there are no black it makes (0, 0) the center. ``` import Image from itertools import product img = Image.open(raw_input()) img = img.convert("RGB") pixdata = img.load() changed=0 m=False count=0 for x, y in product(xrange(img.size[1]), xrange(img.size[0])): if pixdata[x, y]==(0, 0, 0): count+=1 colors=[(0, 0, 0), (255, 255, 0)] if img.size[0]*img.size[1]-count>count else [(255, 255, 255), (0, 0, 255)] m=False for x, y in product(xrange(img.size[1]), xrange(img.size[0])): if pixdata[x, y] == colors[0]: if m: pixdata[x, y] = colors[1] else: pixdata[x, y] = (255, 0, 0) m=True changed+=1 if not m: pixdata[0, 0]==(255, 0, 0) changed+=1 if colors[0]==(255, 255, 255): changed-=1 print changed img.save("out.png", "PNG") ``` # Results ## Image 1 - 28688 changes, Image 2 - 24208 changes ![](https://i.stack.imgur.com/EgUOO.png)![](https://i.stack.imgur.com/Q76Cv.png) ## Image 3 - 24248 changes, Image 4 - 7103 changes ![](https://i.stack.imgur.com/fSlYL.png)![](https://i.stack.imgur.com/GxJxf.png) ## Image 5 - 11097 changes, Image 6 - 13019 changes ![](https://i.stack.imgur.com/zHYP0.png)![](https://i.stack.imgur.com/WzzW5.png) Takes file name from raw\_input and writes to out.png and prints number of changes. ]
[Question] [ Here's one for all you wordsmiths out there! Write a program or function which takes a list of words and produces a list of all possible concatenative decompositions for each word. For example: ***(Note: This is only a small sampling for illustrative purposes. Actual output is far more voluminous.)*** ``` afterglow = after + glow afterglow = aft + erg + low alienation = a + lie + nation alienation = a + lien + at + i + on alienation = a + lien + at + ion alienation = alien + at + i + on alienation = alien + at + ion archer = arc + her assassinate = ass + as + sin + ate assassinate = ass + ass + in + ate assassinate = assassin + ate backpedalled = back + pedal + led backpedalled = back + pedalled backpedalled = backpedal + led goatskin = go + at + skin goatskin = goat + skin goatskin = goats + kin hospitable = ho + spit + able temporally = tempo + rally windowed = win + do + wed windowed = wind + owed weatherproof = we + at + her + pro + of yeasty = ye + a + sty ``` Ok, you get the idea. :-) ## Rules * Use any programming language of your choosing. Shortest code by character count *for each language* wins. This means there is one winner for each language used. The overall winner will be simply the shortest code of all submitted. * The input list can be a text file, standard input, or any list structure your language provides (list, array, dictionary, set, etc.). The words can be English or any other natural language. (If the list is English words, you'll want to ignore or pre-filter-out single-letter items except for "a" and "i". Similarly, for other languages, you'll want to ignore nonsensical items if they appear in the file.) * The output list can be a text file, standard output, or any list structure your language uses. * You can use any input dictionary you like, but you'll probably want to use one that provides sensible words rather than one that provides too many obscure, arcane, or obnubilated words. This the file I used: *[The Corncob list of more than 58000 English words](http://www.mieliestronk.com/wordlist.html)* ## Questions This challenge is primarily about writing the *code* to accomplish the task, but it's also fun to comb through the results... 1. What subwords occur most commonly? 2. What word can be decomposed into the greatest number of subwords? 3. What word can be decomposed the most different ways? 4. What words are composed of the largest subwords? 5. What decompositions did you find that were the most amusing? [Answer] # Python 186 ``` a=open(raw_input()).read().split() def W(r): if r: for i in range(1,len(r)+1): if r[:i]in a: for w in W(r[i:]):yield[r[:i]]+w else:yield[] while 1: for f in W(raw_input()):print f ``` Not particularly efficient but actually not terrible slow. It just naively (I suppose it's possible, though I think unlikely that python does some clever optimizations) checks that sub-words are in the corncob dictionary and recursively finds as many words as it can. Of course this dictionary is pretty extensive and you could try one which doesn't include various abbreviations and acronyms (leading to things like `bedridden: be dr id den`). Also the linked dictionary did not seem to have 'A' or 'I' listed as words so I manually added them in. Edit: Now the first input is the filename of the dictionary to use, and every additional one is a word. [Answer] # Cobra - 160 ``` sig Z(x,y) def f(b) c as Z=do(x,y) if x.length<1,print y for z in File.readLines('t'),if z==x[:e=z.length].toLower,c(x[e:],y+' '+z) for t in b,c(t,'[t]:') ``` This is a function (sort-of two functions) that takes a `List<of String>`\* and prints the strings containing the possible sub-word arrangements for each string in the argument list. \* the type is actually `List<of dynamic?>`, but providing anything other than `List<of String>` will probably break it. [Answer] # Scala, 132 129 Edit: slightly shorter as a loop reading from stdin than a function ``` while(true)print(readLine.:\(Seq(List(""))){(c,l)=>l.flatMap{m=>Seq(c+""::m,c+m.head::m.tail)}}filter(_.forall(args contains _))) ``` run as ``` scala decompose.scala aft after erg glow low ``` (or use a longer word list :) ) Original: ``` def f(s:Seq[String])=s.map{_.:\(Seq(List(""))){(c,l)=>l.flatMap{m=>Seq(c+""::m,c+m.head::m.tail)}}filter(_.forall(args contains _))} ``` Function from Seq[String] to Seq[Seq[List[String]]]. Takes dictionary as the command line arguments. Ungolfed: ``` def decompose(wordList: Seq[String]) = wordList.map{ word => // for each word word.foldRight(Seq(List(""))){ (char, accum) => // for each character accum.flatMap{list => Seq(char+""::list,char+list.head::list.tail) // add it as both a new list and } // the to start of the first list }.filter(_.forall(args contains _)) // filter out lists w/ invalid words } ``` Approach is to generate all the possible lists of substrings and filter out those that contain a string not in the dictionary. Note that some of the substrings generated contain an extra empty string, I assume the empty string will not be in the dictionary (there's no way to pass it in on the command line anyways). ]
[Question] [ This is a code golf puzzle with a real-world application. Some current browsers, if you enter a URL that looks like ``` data:text/html,<script>alert("hi")</script> ``` will execute the given JavaScript code. Now suppose you had a URL which looked like (pseudocode): ``` data:text/html,<script> myPublicKey="12345678"; cryptoLib=download("http://example.com/somecryptolib.js"); if(sha256sum(cryptoLib) == "12345678") eval(cryptoLib) </script> ``` If you printed this on business cards as a [QR code](https://en.wikipedia.org/wiki/QR_code), then anyone who went to that URL with an appropriate browser would get a public-key crypto client, with your public key pre-loaded, without having to install anything. Because of the hash verification, you could be confident they got the real crypto software, even if their [ISP](http://en.wikipedia.org/wiki/Internet_service_provider) meddles with traffic. Unfortunately, the real version of this pseudocode is quite long for a QR code. My challenge is: how short can you make it? An implementation would: * Be a data:... URL which executes correctly from the address bar of Chrome and Firefox. (To make a valid data: URL, you'll have to encode % as %25, and strip newlines) * Have a URL and a [SHA-256](http://en.wikipedia.org/wiki/SHA-2) hash embedded, preferably as plain-text string literals near the beginning * Download a file from a URL using [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) (or a similar API). (Note that the server will need to include an Access-Control-Allow-Origin:\* header for this to work.) * If that URL loaded successfully and the result is a file with the expected hash, eval() it. Otherwise do nothing or show an error message. * All builtin JavaScript functions that're present in both Chrome and Firefox are fair game, but loading libraries is impossible. * Use as few bytes as possible I made a naive version using [CryptoJS](http://code.google.com/p/crypto-js/) ([minified version](http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js)): ``` data:text/html,<script> u = 'http://localhost:8000' h = '5e3f73c606a82d68ef40f9f9405200ce24adfd9a4189c2bc39015345f0ee46d4' // Insert CryptoJS here r = new XMLHttpRequest; r.open('GET', u, false); r.send(); if(CryptoJS.SHA256(r.response) == h) eval(r.response); </script> ``` Which comes out of the minifier as: ``` data:text/html,<script>u="http://localhost:8000";h="5e3f73c606a82d68ef40f9f9405200ce24adfd9a4189c2bc39015345f0ee46d4";var CryptoJS=CryptoJS||function(k,w){var f={},x=f.lib={},g=function(){},l=x.Base={extend:function(a){g.prototype=this;var c=new g;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},t=x.WordArray=l.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=w?c:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%254)for(var e=0;e<a;e++)c[b+e>>>2]|=(d[e>>>2]>>>24-8*(e%254)&255)<<24-8*((b+e)%254);else if(65535<d.length)for(e=0;e<a;e+=4)c[b+e>>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<32-8*(c%254);a.length=k.ceil(c/4)},clone:function(){var a=l.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d<a;d+=4)c.push((1<<30)*4*k.random()|0);return new t.init(c,a)}}),z=f.enc={},y=z.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++){var e=c[b>>>2]>>>24-8*(b%254)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b+=2)d[b>>>3]|=parseInt(a.substr(b,2),16)<<24-4*(b%258);return new t.init(d,c/2)}},m=z.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++)d.push(String.fromCharCode(c[b>>>2]>>>24-8*(b%254)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b++)d[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%254);return new t.init(d,c)}},n=z.Utf8={stringify:function(a){try{return decodeURIComponent(escape(m.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return m.parse(unescape(encodeURIComponent(a)))}},B=x.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new t.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=n.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?k.ceil(f):k.max((f|0)-this._minBufferSize,0);a=f*e;b=k.min(4*a,b);if(a){for(var p=0;p<a;p+=e)this._doProcessBlock(d,p);p=d.splice(0,a);c.sigBytes-=b}return new t.init(p,b)},clone:function(){var a=l.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});x.Hasher=B.extend({cfg:l.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){B.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,d){return(new a.init(d)).finalize(c)}},_createHmacHelper:function(a){return function(c,d){return(new A.HMAC.init(a,d)).finalize(c)}}});var A=f.algo={};return f}(Math);(function(k){for(var w=CryptoJS,f=w.lib,x=f.WordArray,g=f.Hasher,f=w.algo,l=[],t=[],z=function(a){return (1<<30)*4*(a-(a|0))|0},y=2,m=0;64>m;){var n;a:{n=y;for(var B=k.sqrt(n),A=2;A<=B;A++)if(!(n%25A)){n=!1;break a}n=!0}n&&(8>m&&(l[m]=z(k.pow(y,0.5))),t[m]=z(k.pow(y,1/3)),m++);y++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new x.init(l.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],p=b[2],k=b[3],s=b[4],l=b[5],m=b[6],n=b[7],q=0;64>q;q++){if(16>q)a[q]=c[d+q]|0;else{var v=a[q-15],g=a[q-2];a[q]=((v<<25|v>>>7)^(v<<14|v>>>18)^v>>>3)+a[q-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[q-16]}v=n+((s<<26|s>>>6)^(s<<21|s>>>11)^(s<<7|s>>>25))+(s&l^~s&m)+t[q]+a[q];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&p^f&p);n=m;m=l;l=s;s=k+v|0;k=p;p=f;f=e;e=v+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+p|0;b[3]=b[3]+k|0;b[4]=b[4]+s|0;b[5]=b[5]+l|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;d[e>>>5]|=128<<24-e%2532;d[(e+64>>>9<<4)+14]=k.floor(b/(1<<30)*4);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});w.SHA256=g._createHelper(f);w.HmacSHA256=g._createHmacHelper(f)})(Math);r=new XMLHttpRequest;r.open("GET",u,!1);r.send();CryptoJS.SHA256(r.response)==h&&eval(r.response)</script> ``` Tested with this minimal Python server: ``` import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(s): s.send_response(200) s._sendHeaders() s.end_headers() def do_GET(s): s.send_response(200) s._sendHeaders() s.end_headers() s.wfile.write('alert("Success!")') def _sendHeaders(s): s.send_header("Content-type", "script/javascript"); s.send_header("Access-Control-Allow-Origin", "*"); def run(server_class=BaseHTTPServer.HTTPServer, handler_class=RequestHandler): server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() run() ``` The JavaScript portion is 4700 bytes, but it can be much smaller. How small can it get? [Answer] # 844 Characters ``` K=new XMLHttpRequest;K.open("get","http://localhost:8000",O=j=n=q=0);K.send();m=K.response;l=m.length;k=l+1|63;W=[o=Math.pow];for(H=[R=o(i=2,32)];i<313+l;i++)for(W[i]||(K[q]=o(i,1/3)*R|0,H[q++]=o(i,.5)*R|0,I=2);W[i*I++]=199>I;)o[n>>2]|=(n^l?m.charCodeAt(n):128)<<24-n++%4*8;for(o[k>>2]=8*l;j<=k;H[I-7]+=a=t+T|0)i=j++&63||(a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7],0),y=W[i-15],x=W[i-2],t=h+(e<<26^e>>>6^e<<21^e>>>11^e<<7^e>>>25)+(e&f^~e&g)+K[i]+(W[i]=16>i?o[O++]:(y<<25^y>>>7^y<<14^y>>>18^y>>>3)+W[i-7]+(x<<15^x>>>17^x<<13^x>>>19^x>>>10)+W[i-16]),T=(a<<30^a>>>2^a<<19^a>>>13^a<<10^a>>>22)+(a&b^a&c^b&c),H[I=i-63|7]+=h=g,H[I-1]+=g=f,H[I-2]+=f=e,H[I-3]+=e=d+t|0,H[I-4]+=d=c,H[I-5]+=c=b,H[I-6]+=b=a;1581216710^H[0]|111684968^H[1]|4014012921^H[2]|1079115982^H[3]|615382426^H[4]|1099547324^H[5]|956388165^H[6]|4042147540^H[7]||eval(m) ``` The URL and Hash values are hard coded. The Hash is encoded as decimal double words, the values in my code correspond to the script in the example Python server. I also didn't bother doing the URL encoding, but it works when you type `javascript:` manually in the URL bar and then paste the code (and also in the console). The implementation is not compliant, but it should work for files smaller than 512 MB. [Answer] # HTML Data URL, 131 Characters It's been a while and there's a native way to do this now: [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). Also, data URLs are not allowed to be linked to by major browsers so this whole idea no longer works :( Also, I used a hosted copy of the script that should be CORS-accessible, `http:localhost:8000` was what OP specified and would save 3 characters. ``` data:text/html,<script src=https:fk.ci/9Rg2HKk.js integrity=sha256Xj9zxgaoLWjvQPn5QFIAziSt/ZpBicK8OQFTRfDuRtQ crossorigin></script> ``` ]
[Question] [ I present to you a test! Your test is to test. The test is to test the testee with tests a tester gives you, in the shor**test** amount of code. Specifically, you will give a multiple choice test that you have recieved as input. In this challenge, you must take an input like this: ``` 1. Our site is called Programming Puzzles & Code ________. A: Debugging *B: Golf C: Hockey D: Programming 2. What is the *most* popular tag on our site? A: [debug] B: [program] *C: [code-golf] D: [number] E: [c++] 3. We are part of the ________ Exchange network. *A: Stack B: Code C: Programmer D: Hockey 4. Is this the first question? A: Yes *B: No 5. Is this the last question? *A: Yes B: No ``` And here is an example of the test being taken: ``` 1. Our site is called Programming Puzzles & Code ________. A: Debugging B: Golf C: Hockey D: Programming answer: B correct! 2. What is the *most* popular tag on our site? A: [debug] B: [program] C: [code-golf] D: [number] E: [c++] answer: C correct! 3. We are part of the ________ Exchange network. A: Stack B: Code C: Programmer D: Hockey answer: B incorrect! the answer was A 4. Is this the first question? A: Yes B: No answer: B correct! 5. Is this the last question? A: Yes B: No answer: B incorrect! the answer was A overview: 3 correct, 2 incorrect (60%) 3. We are part of the ________ Exchange network. you chose B: Code the answer was A: Stack 5. Is this the last question? you chose B: No the answer was A: Yes ``` Formal specification: * Input + If a line begins with a number followed by a dot and a space, it is a question with that number. Numbers will always start from 1 and go up 1 each question. + If a line begins with an optional asterisk, a letter, a colon, and then a space, it is an answer. Answers will also always be sequential. There will be only one correct answer per question. + A line will not begin in any other way than the previously mentioned ways. + Input may be accepted in any way (reading from a file, stdin, etc.) but must not be hardcoded into your program. * Output (test-taking phase) + First, print out each question sequentially. Print the question and its answers as recieved in input, but do not print the asterisk indicating correct answers. + Then, print a newline and `"answer: "`. Wait for user input. User input will always correspond to an answer. + If the correct answer (the one with an asterisk) is the same as the one the user input, output `"correct!"`. Otherwise, output `"incorrect! the answer was " + correct_letter`. + Separate each question with a blank line, then repeat the previous output steps until there are no more questions. * Output (overview phase) + Print `"overview: "` and then a newline. + Print `"{number of correct answers} correct, {incorrect answers} incorrect ({percent correct, rounded to the nearest whole number}%)"` (of course substituting the phrases in curly braces with their respective values). Then print a blank line for spacing. + Now, for each question that was wrong, print the question (not its answers), then on a new line `"you chose " + answer_you_chose`, and on another line `"the answer was " + correct_answer`. Separate each wrong answer's overview with a blank line. * In order to reduce cheating by interpreting things literally, when given the same output here, and the same input in the test-taking phase, your program must output exactly the same thing as the sample output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins! (And gets an A+ (green checkmark)!) [Answer] # Mathematica 144 This may be an invalid attempt. I separated the question from each answer in the input. I also indicated the correct answer by a letter in a separate field, rather than an asterisk before the alternative. Anyway... **The Data** ``` questions={{{"\n1. Our site is called Programming Puzzles & Code ________.\n","A: Bugging\n","B: Golf\n","C: Hockey\n","D: Programming\n"},"B"},{{"\n2. What is the most popular tag on our site? \n","A: [debug]\n","B: [program]\n","C: [code golf]\n","D: [number]\n"},"C"},{{"\n3. We are part of the _______ Exchange network. \n","A: Stack\n","B: Code\n","C: Programmer\n","D: Hockey\n"},"A"},{{"\n4. Is this the first question? \n","A: Yes\n","B: No\n"},"B"},{{"\n5. Is this the last question? \n","A: Yes\n","B: No\n"},"A"}}; ``` **Code** An answer to each question is entered through a dialog box. Questions, answers, and feedback are printed. ``` f@x_:= Print[If[((r=ChoiceDialog[Print[""<>#,"\nanswer: "];""<>#,StringTake[Rest@#,1]])==#2), r<>"\ncorrect!", r<>"\nincorrect, the answer is "<>#2]&@@x] ``` **Test** ``` f /@ questions ``` ![dialog choice](https://i.stack.imgur.com/COCWA.png) [Answer] ## Perl 5, 279 ``` $y=correct;@w=(the,$n=answer,was);map{s/^\*((.+?):.+)/$a=$1/me;print"$_$n: ";chop($@=<>);print$@eq($l=$2)?++$d&&"$y! ":(/^\d.+/,$o.=$&,/^$@.+/m,$o.=" you chose: $& @w $a ")&&"in$y! @w $l "}@_=split/(?=^\d)/m,join"",<>;printf"overview: $d $y, %d in$y (%d%) $o",@_-$d,$d/@_*100 ``` *Note: The newlines are required for output formatting.* Every time I think I can't golf it any more, I learn something new! It's slowly becoming more punctuation than legible text... I think that's a good thing? Usage: `perl -e '...' test.txt` or `perl test.pl test.txt`. If you choose an option not presented in the list, you will get incorrect output in the overview (it will say `you chose: 1. Our site is called Programming Puzzles & Code ________.` for example). [Example run](http://showterm.io/13c98a3e82872a76461f4) [Answer] **Java - 1210** ``` int i,o;String q;String[]s={"1. Our site is called Programming Puzzles & Code ________.\n","2. What is the most popular tag on our site?\n","3. We are part of the ________ Exchange network.\n","4. Is this the first question?\n","5. Is this the last question?\n"},b={"B","C","A","B","A"},p=new String[5];String[][]a={{"A: Debugging\n","B: Golf\n","C: Hockey\n","D: Programming\n","answer: "},{"A: [debug]\n","B: [program]\n","C: [code-golf]\n","D: [number]\n","E: [c++]\n","answer: "},{"A: Stack\n","B: Code\n","C: Programmer\n","D: Hockey\n","answer: "},{"A: Yes\n","B: No\n","answer: "},{"A: Yes\n","B: No\n","answer: "}};java.util.Map<String,Integer>m=new java.util.HashMap(){{put("A",0);put("B",1);put("C",2);put("D",3);put("E",4);}};java.util.Scanner u=new java.util.Scanner(System.in);for(i=0;i<5;i++){q=s[i];for(o=0;o<a[i].length;)q+=a[i][o++];System.out.print(q);if(b[i].equals(p[i]=u.nextLine()))q="correct!";else q="incorrect! the answer was "+b[i];System.out.println(q+"\n");}q="";o=0;for(i=0;i<5;i++)if(b[i].equals(p[i]))o++;else q+=s[i]+"you chose "+a[i][m.get(p[i])]+"the answer was "+a[i][m.get(b[i])]+"\n";System.out.println("overview:\n"+o+" correct, "+(5-o)+" incorrect ("+o*100/5+"%)\n\n"+q); ``` formatted: 1980 ``` String[] s = {"1. Our site is called Programming Puzzles & Code ________.\n", "2. What is the most popular tag on our site?\n", "3. We are part of the ________ Exchange network.\n", "4. Is this the first question?\n", "5. Is this the last question?\n"}; String[][] a = { {"A: Debugging\n", "B: Golf\n", "C: Hockey\n", "D: Programming\n", "answer: "}, {"A: [debug]\n", "B: [program]\n", "C: [code-golf]\n", "D: [number]\n", "E: [c++]\n", "answer: "}, {"A: Stack\n", "B: Code\n", "C: Programmer\n", "D: Hockey\n", "answer: "}, {"A: Yes\n", "B: No\n", "answer: "}, {"A: Yes\n", "B: No\n", "answer: "}}; java.util.Map<String, Integer> m = new java.util.HashMap<String, Integer>() { { put("A", 0); put("B", 1); put("C", 2); put("D", 3); put("E", 4); } }; String[] b = {"B", "C", "A", "B", "A"}; String[] p = new String[5]; java.util.Scanner u = new java.util.Scanner(System.in); String q; int i; int o; for (i = 0; i < 5; i++) { q = s[i]; for (o = 0; o < a[i].length;) { q += a[i][o++]; } System.out.print(q); if (b[i].equals(p[i] = u.nextLine())) { q = "correct!"; } else { q = "incorrect! the answer was " + b[i]; } System.out.println(q + "\n"); } q = ""; o = 0; for (i = 0; i < 5; i++) { if (b[i].equals(p[i])) { o++; } else { q += s[i] + "you chose " + a[i][m.get(p[i])] + "the answer was " + a[i][m.get(b[i])] + "\n"; } } System.out.println("overview:\n" + " correct, " + (5 - o) + " incorrect (" + o * 100 / 5 + "%)\n\n" + q); ``` This certainly won’t be the shortest but it is all self-contained [Answer] ## Haskell, 598 ``` import System.Environment import System.IO n=putStrLn p=putStr d#s=p$show d++s v&(m:a)=n m>>q[]""a>>= \(r,(s,t))->n s>>n"">>b v m t&r (r,w,s)&[]=n"overview:">>r#" correct, ">>w#" incorrect (">>((100*r)`div`(r+w))#"%)\n">>mapM_ n s b(r,w,s)m t|null t=(r+1,w,s)|1<3=(r,w+1,s++"":m:t) q u c(('*':a):r)=q u a(a:r) q u c(a@(o:':':_):r)=n a>>q(([o],a):u)c r q u c r=p"answer: ">>hFlush stdout>>(\i->(r,a(maybe i id$lookup i u)c))`fmap`getLine a j c|j==c=("correct!",[])|1<3=("incorrect! the answer was "++[head c],["you choose "++j,"the answer was "++c]) main=getArgs>>=readFile.head>>=((0,0,[])&).lines ``` Way longer than I'd like. It's set wiki so have at it! Alas, we lose 32 characters to flushing stdout. Another 38 characters could be saved if the test script were read from a fixed file named "t" rather than specified on the command line. When run on the input given in the question: ``` & runhaskell 15961-Tester.hs 15961-test.txt 1. Our site is called Programming Puzzles & Code ________. A: Debugging B: Golf C: Hockey D: Programming answer: B correct! 2. What is the *most* popular tag on our site? A: [debug] B: [program] C: [code-golf] D: [number] E: [c++] answer: C correct! 3. We are part of the ________ Exchange network. A: Stack B: Code C: Programmer D: Hockey answer: B incorrect! the answer was A 4. Is this the first question? A: Yes B: No answer: B correct! 5. Is this the last question? A: Yes B: No answer: B incorrect! the answer was A overview: 3 correct, 2 incorrect (60%) 3. We are part of the ________ Exchange network. you choose B: Code the answer was A: Stack 5. Is this the last question? you choose B: No the answer was A: Yes ``` ]
[Question] [ # BlackJack > > As I had a blast working on the > original KOTH challenge, I wanted to > come up with another one. For me, the fun > of these AI challenges is in refining > a comparatively simple bot which plays > a very simple game subtly. Due to the > probabilistic nature of card games, I > think that blackjack could be an > interesting KOTH game just like TPD. > > > **[All the rules are derived from this website's description of BlackJack with shoes](http://www.blackjackinfo.com/blackjack-rules.php)** # Rules Regarding Cards & the Deck * Bots play at tables of four (4) competitors and one (1) dealer * One (1) shoe (a shuffled deck) is shared by all players **and the dealer** until it is exhausted, at which point a new randomly shuffled deck will be added and play will continue. The bots ARE NOT (at present) NOTIFIED of the addition of this new deck. Such notification may be added if lack of this feature causes sufficient distress/trouble. * There is a buy-in of 10 per round, and cards are free * Perfect/ideal hand has a score of 21 * All face cards have a value of 10 * All numeric cards are worth their number * Aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots. * As per [the rules](http://www.blackjackinfo.com/blackjack-rules.php), all players' cards are dealt face-up and are visible. One of the dealer's cards is face-down and the other is face-up. # Scoring * Scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1 * scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot # The Dealer * The dealer draws until he busts, or excedes a score of 17 **at which point he is forced to stand** # Betting and Chips * At the start of each round, a buy-in of 10 is charged, so there is a minimum **stake** of 10, and a minimum **bet** of 1. **NOTE** - the bet is the absolute value of the bet argument, so don't bother trying negative bets. * Bots which cannot afford the buy-in are removed from the contest * When making bets, bots cannot bet more than the chips they have * If the bet is possible, the chips bet are emmidiately removed from the bot and added to the stake * Winning a bet gives the bot 2x chips bet. However because the bet is subtracted from the bot's chips, the bot breaks even and then wins 1x the bet. * **Bots win bets only if their score is greater than that of the dealer** # Gameplay Breakdown **One Hand** 1. When the game starts, each player is iteratively dealt one card, and has the $10 buy-in fee/minimum bet subtracted from their chips. 2. The dealer draws 3. A second pass is made, and another card is dealt to all players. 4. The dealer draws 5. Then (in the same order as they were dealt to) each bot is executed as described in the "Programmer's Interface" section and **must** make a move or stand. Betting is considered a move. ***NOTE THAT BETTING DOES NOT AFFECT BOTS' ABILITY TO MAKE FURTHER MOVES.*** It is very possible to bet and then draw a card, and it is possible to draw multiple cards and them bet before standing. 6. When all the bots have busted or stood, the dealer plays to its threshold of 17 7. The scores of the bots are then compared to that of the dealer, bets are won and lost **One Round** Is considered to constitute five (5) hands. In-between hands, the list of contestants is sorted to remove players and then further processed to ensure that all the bots play the same number of hands (a provision for the fact that the number of entries will not devide evenly among four-bot tables). # Programmer's Interface and Legal Moves As documented in the CardShark file: ``` # DOCUMENTATION # INPUT SPECIFICATION # $ ./foo.bar <hand-score> <hand> <visible cards> <stake> <chips> # <hand-score> is the present integer value of the player's hand. # <hand> is a space-free string of the characters [1-9],A,J,Q,K # <visible cards> every dealt card on the table. when new shoes are brought # into play, cards drawn therefrom are simply added to this list # NOTE: the first TWO (2) cards in this list belong to the dealer. # one however will be "hidden" by a "#". the other is visible. # !!! THE LIST IS CLEARED AT THE END OF HANDS, NOT SHOES !!! # <stake> the number of chips which the bot has bet this hand # <chips> the number of chips which the bot has # SAMPLE INPUT # $ ./foo.bar 21 KJA KQKJA3592A 25 145 # # OUTPUT SPECIFICATION # "H"|"S"|"D"|"B" (no quotes in output) # "H" HIT - deal a card # "S" STAND - the dealer's turn # "D" DOUBLEDOWN - double the bet, take one card. FIRST MOVE ONLY # "B 15" BET - raises the bot's stakes by $15. ``` As (now) documented in the Cards file: ``` # class CARD # card is a container for representing paper playing cards in # otherwise fairly functional programming. # letter() # gets the letter used to identify the card in a string # LETTER MAPPINGS # Ace : 'A' # Two : '2' # Three : '3' # Four : '4' # Five : '5' # Six : '6' # Seven : '7' # Eight : '8' # Nine : '9' # Ten : 'T' # Jack : 'J' # Queen : 'Q' # King : 'K' # "Hidden": '#' ``` **The source code for the scoring system is [HERE](https://github.com/rdmckenzie/CodeGolf/tree/master/blackjack)** # **Sample Bots** **Lim 17** ``` #!/usr/bin/env python import sys s = sys.argv if int(s[1]) < 17: print "H" else: print "S" ``` # Entry Languages At present, Java, c/c++, Python and Lisp are supported. A reasonable effort will be made to include submissions in other languages, but remember that the final contest will be run on a Linux box. # Winner Selection The winner would be the author of the bot which consistently accrued the most chips over a yet-to-be determined number of tables and rounds. ~~The winner will be announced on June 3rd, but the announcement may be delayed if there are still submissions coming in.~~ Contest extended indefinitely. [Answer] ## BlackJackDavey Boring, old fashioned c. Should compiler under ANSI or c99. ``` /* BlackJackDavey * * A entry for * http://codegolf.stackexchange.com/questions/2698/a-blackjack-koth-contest * copyright 2011 * * Currently expects a slightly extended version of the spec. Two * expected changes: * - Tens will be represented as 'T' * - The visible card string will include '#' for those cards whose * *backs* we can see (slight improvement in card counting technique) * * No disaster if neither feature is present, just sligtly degraded * performance. */ #include <stdio.h> #include <string.h> /* A full deck has a total value of 4*( (11*5) + (3*10) + ace ) where * ace is 11 or according to our need. **/ int fullWeight(const int current){ int ace = (current>10) ? 1 : 11; return 4 * ( 11*5 + 3*10 + ace); } /* Return the value of a particular card in the context of our * current score */ int cardWeight(const char c, const int current){ switch (c) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return (c - '0'); case 'T': case 'J': case 'Q': case 'K': return 10; case 'A': return current>10 ? 1 : 11; } return 0; } /* returns the mean card *value* to be expected from the deck * * Works by computing the currently unknown value and diviing by the * number of remaining cards */ float weight(const char*known, const int current){ int weight = fullWeight(current); int count=52; int uCount=0; const char*p=known; while (*p != '\0') { if (*p == '#') { /* Here '#' is a stand in for the back of a card */ uCount++; } else { weight -= cardWeight(*p,current); } count--; p++; if ( count==0 && *p != '\0') { count += 52; weight += fullWeight(current); } } return (1.0 * weight)/(count+uCount); } int main(int argc, char*argv[]){ int score=atoi(argv[1]); const char*hand=argv[2]; const char*visible=argv[3]; int stake=atoi(argv[4]); int chips=atoi(argv[5]); /* If current stake is less than 10, bet all the rest because a loss does not leave us enough to continue */ if (chips < 10 && chips > 0) { printf("B %d\n",chips); return 0; } /* First round stategy differs from the rest of the game */ if (strlen(hand)==2 && stake==10) { switch(score){ case 10: case 11: /* Double down on particularly strong hands */ if (chips >= 10) { printf("D\n"); return 0; } break; default: break; }; } /* In future rounds or when first round spcialls don't apply it is all about maximizing chance of getting a high score */ if ((score + weight(visible,score)) <= 21) { /* if the oods are good for getting away with it, hit */ printf("H\n"); return 0; } /* Here odd are we bust if we hit, but if we are too low, the dealer probably makes it.*/ printf("%c\n", score>14 ? 'S' : 'H'); return 0; } ``` The strategy here is documented in the comments, but is very straight ahead. Additional bets are made in only two cases (not enough stake for the next round, or double down), and this may need to change. The game differs some from the guides offered for casino gamblers in that there is no specific information about the dealer's showing card (or can we could on that being the last entry in `visible`?), so some of the magic numbers are guesses. May need some modest diddling depending on the answer to two questions in the comments. Name from the game, my first name, and the [old folk ballad](http://www.youtube.com/watch?v=bCCF-QwPwZk). [Answer] # Linear Bet ``` #!/usr/bin/env python from __future__ import division import sys s = sys.argv c=150 # chip modifier f=15 # stand score if int(s[1]) < f: print "H" else: if int(s[4]) == 10: print "B", (int(s[1])/21)*c else: print "S" ``` This bot is a modification of the 17 strategy. This bot draws until it exceeds a score of 15 (f) and then bets int(c\*(score/21)) chips. This way the bot will bet aggressively wherever possible. [Answer] # JustAnotherCardCounter, Python ``` import sys s = sys.argv if s[0] <= 11 and len(s[1]) == 2: print("D") # another card is always safe here elif s[0] <= 11: print("H") # same elif s[0] == 21: print("B ", s[4]) # can't lose, so go all out print("S") # and wait for the cash to roll in cardset = s[2] prevcardset = "" cards = { "A": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "T": 0, "J": 0, "Q": 0, "K": 0} # here i go, cheating fate (again) for card in "A23456789TJQK": cards[card] += (cardset.count(card) - prevcardset.count(card)) counts = list(cards.values()) # get the values if (counts[:20 - s[0]] * 4/3) >= counts[20 - s[0]: # here's where the magic happens print("H") else: if s[4] * (1 - s[0]/21) < 10: print("B ", s[4]) #we'll go out on a loss regardless, might as well try and get more when we win print("S") else: print("B ", (s[4]*(s[0]/21)) # we can afford to stay low, so we keep ourselves in the game. print("S") ``` This bot does what it says on the tin. Effectively a combination of LinearBet and some of BlackJackDavey. Probably won't do well. Feel free to tell me where this breaks (if it does). ]
[Question] [ Related: [Clearly parenthesize APL trains](https://codegolf.stackexchange.com/q/150380/78410) ## Background In the most basic form, APL has two kinds of tokens: **arrays** and **functions**. For this challenge, we will use a lowercase letter `a-z` for an array, and an uppercase letter `A-Z` for a function. Furthermore, we will assume each character is a token of its own; `Fx` is equivalent to `F x`. APL has two ways to call a function: monadic (taking one argument) and dyadic (taking two arguments). Monadic application is written in prefix `F x`, and dyadic one is written in infix `x F y`. There's nothing like "operator precedence"; an APL expression is always evaluated from right to left, which can be overridden with parentheses `()`. ``` x F G y -> x F (G y) F x G y -> F (x G y) x F y G z -> x F (y G z) (F x) G H y -> (F x) G (H y) ``` A **train** is a way to compose functions to derive a more complex function. In essence, a train is formed when the rightmost token is a function. Here are the rules for 2- and 3-token trains: ``` (F G H) x -> (F x) G (H x) (u G H) x -> u G (H x) (G H) x -> G (H x) x (F G H) y -> (x F y) G (x H y) x (u G H) y -> u G (x H y) x (G H) y -> G (x H y) ``` For 4-token and longer trains, the rightmost 3 tokens are recursively grouped to form a derived function until 2 or 3 tokens remain. As a whole, it can be thought of as follows: ``` Odd-length trains (V D V D ... V D V) x -> (V x) D (V x) D ... (V x) D (V x) x (V D V D ... V D V) y -> (x V y) D (x V y) D ... (x V y) D (x V y) Even-length trains (M V D V D ... V D V) x -> M (V x) D (V x) D ... (V x) D (V x) x (M V D V D ... V D V) y -> M (x V y) D (x V y) D ... (x V y) D (x V y) ``` If an array `u` appears at the `V` position (other than the last), replace the cooresponding `(V x)` or `(x V y)` simply with `u`. An array appearing at `M` or `D` position is a syntax error. Note that trains may also have sub-expressions that evaluate to an array or a function: ``` x ((D a) F G (u H J) K) y Expand 5(odd)-token train, leftmost V position being an array (D a) -> (D a) F (x G y) (u H J) (x K y) Expand 3(odd)-token train (u H J) -> (D a) F (u H (x G y) J (x K y)) ``` ## Challenge Given a line of APL expression that evaluates to an array (which may or may not include one or more trains), convert it into an equivalent expression without a train. You can assume that the input is valid under the rules stated above, and it doesn't contain any spaces. You don't need to worry too much about parentheses or spaces in the output; lacking or redundant parentheses/spaces are fine as long as they represent the equivalent expression. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` x(XY)y -> X(xYy) uKKKv -> uKKKv U(xVW)yZa -> UxVWyZa MnP(QRsTU)VWx -> MnP(QVWx)RsTUVWx x(XXxYYYdDD)y -> (xXy)XxY(xYy)YdDxDy a((DEF)GHJ)Kb -> (D(aGKb)HaJKb)EF(aGKb)HaJKb c((k(PQRSTU)m)(VW)(XY)(ZA)BCD)n -> V(P(kQm)R(kSm)T(kUm))WZ(XcYn)A(cBn)C(cDn) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~63 59 58 54 52~~ 51 bytes ``` ∊⍎'.[A-Z].'⎕r'{0::&⍵⋄''() '',⍪⍺&⍵}'⊢'\w'⎕r'''&'''⊢⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ooz0NSHQ96u1T14t21I2K1VN/1De1SL3awMpK7VHv1kfdLerqGpoK6uo6j3pXPerdBRKsVX/UtUg9phyiVF1dDYiBIo9654EM/J/GVaEREalZyZXGVert7V0GpEM1KsLCNSujEoFs37wAjcCg4pBQzbDwCi6w4oiKyMjIFBcXsJ5EDQ0XVzdNdw8vTe8kID9ZQyNbIyAwKBioI1dTA2gOyHSNKEdNJ2cXzTwA "APL (Dyalog Classic) – Try It Online") put all letters in quotes, replace uppercase letters with dfns that return either "(left) self right" or "self right" depending on the presence of a left arg, and execute. [Answer] # Python3, 887 bytes: ``` def p(s): r=[] while s and(S:=s[0])!=')': if S.isalpha():r+=[s[0]] if'('==S:r+=[(K:=p(s[1:]))[0]];s=K[1] s=s[1:] return r,s F=lambda x:(O:=ord(str(x)[0]))<=91 and(64<O<91 or all(F(i)for i in x[-2:])) R=lambda x:[i for i in x if i] def f(s,l=0,r=0): if F(s): J=[] while s: if F(S:=s.pop(0))==0:J+=[S] else: if len(s)>1 and F(s[0])==0:J+=[[S,s.pop(0)]] else:J+=[S] s=J c,s=[f([*s[0]])]if(t:=F(s[0])==0)else[],s[t:] c+=[f(R([l,s[0],r]))]if(S:=sum(map(F,s))%2)else[];s=s[S:] while s: if F(s[0])==0:c+=[s[0]];s=s[1:];continue a,b=s[:2];c+=[a,f(R([l,b,r]))if F(b) else f(b)];s=s[2:] return f(c) c=[] while s: if F(j:=s.pop(0)) and type(j)==list: c+=[f(j,l=c and not F(c[-1])and c.pop(),r=f(s))] else:c+=[j] return c P=lambda e,l=0:e if str==type(e)else '('*(Y:=(l>0 and len(e)>1))+''.join(P(i,l+1)for i in e)+')'*Y M=lambda s:P(f(p(s)[0])) ``` [Try it online!](https://tio.run/##bVNdb9pAEHz3r7g@VN4NTgS0qlqTi9SWOggrCoHmg1h@MMZWTI2xfKY1/fN097BDoLwgmJudnZ1d8k35sso@fM6L7XYexSIHhbYhCun5hvjzkqSRUCLI5jCxpfLaPr6TJprEEEksJheJCtL8JQC0i5b0mODrJxNMKScaBNeWpOp1bB@RCT0lXa/DPCU1TO2icl1korCU4cg0WM7mgahsuLXlqpiDKguouBTxUn7paDufPl7eXtL3VSGCNAUHEozpeyKSTFTeeZebGeO9lpeI/Tt7T3yD541BWalsW4Vs89z04OwSEEMdQZMBI7tXDuIiX@XQRpSybQ9pxgkzRZSqSPOYmEYZCV1pt6zJ9hu6N7EaCZ1XXfqqpOSQPkNLSS8G70zHin4SQ2nLvRRykedbyis5QxG2mD4GL7WYYhUUARex4fUSlkEOjqUQ33fryh7nP7FPTvnqN2z22qu31QtXWZlk64i5gTUj1O4SSrzAqvvPdHMtNEM9HAU9w51GV3esVx5DiIYI355bfVwOLN4krWMsN3kEC7KVJqrUXnczL2iFoWZkq5IKQ@@84yP/DnU90npp0RSHUUfNdYv94YXGqDmViM/BjtgB3Z2UumekExN01WcwtSWkV23djpcc0ZIRW6Z5sVglGYwgsdJWZ3@NEb2heTY1bpoWyh5BDPxP0ze9zYskK@EGzEo44lpsTDrdV8yhcz3GmLch9O8BCkRFQgdHbGDRAYrqEF2fRE9glWgUjl00Gv/hp1HoiwD1iFQ4EEMU7n8seJriIbR2Xff3AXIP1cMjbp6DA/QmG8HdWP28x4fH6lj0qZpOp/N@/0g7IE8/HLweDNGdHbyEAL9gdDeekN4SgfqxM3j@it@@9zFj7vYf) This ended up being longer than I had originally anticipated, but this is an intriguing problem, and I thought I would add a non-APL, parsing-based solution. ]
[Question] [ In [association football](https://en.wikipedia.org/wiki/Association_football) (also known as soccer), a [penalty shoot-out](https://en.wikipedia.org/wiki/Penalty_shoot-out_(association_football)) is the second tie-breaker measure that may be used in a match which can't end in a tie, after extra time (i.e. association football overtime). In a penalty shoot-out, the main referee tosses a coin to determine at which goal the shoot-out happens, and then tosses another coin to determine which team starts first. However, the only thing relevant to this challenge is what happens then, described below. Each team has 5 penalties available at start, and the penalty score is 0-0. If, at any point, a team's remaining penalties aren't enough to change the currently winning team, the shoot-out stops. If there are no remaining penalties, but both teams' points are equal, an additional penalty is granted to both teams. This is repeated until the points aren't equal. After the shoot-out stops, the team with the largest penalty score wins the game. # Challenge Your challenge is, given two lists `A` and `B` representing which penalties team A and team B scored respectively, to determine if they represent a valid penalty shoot-out. A shoot-out is valid if the state represented by the input can be reached, regardless of whether the winning team can be determined. Note that you possibly have to test for both scenarios (Team A starting, Team B starting), since, if the state described in the input is reachable for at least one scenario, the input is valid. If the lists' lengths are different, the team represented by the longer one starts first (it can only have one more element than the other one, and the shorter list's team can't start, since then the longer list's team would shoot two penalties in a row, as the shorter list will be prematurely depleted). # Detailed examples *You can skip to the **Rules** section below, these are only to help solving the challenge.* Suppose you get this shoot-out as input, where `-` means no goal was scored and `X` means a goal was scored (it's invalid): ``` Team A: - X X X X Team B: - - - - X Assuming team A starts first: Team A: - (0 - 0) (max possible score 4 - 5) Team B: - (0 - 0) (max possible score 4 - 4) Team A: X (1 - 0) (max possible score 4 - 4) Team B: - (1 - 0) (max possible score 4 - 3) Team A: X (2 - 0) (max possible score 4 - 3) Team B: - (2 - 0) (max possible score 4 - 2) Team A: X (3 - 0) (max possible score 4 - 2) Team A already has a higher score than B could ever have, but the input hasn't ended yet, so it's invalid if team A is first. Assuming team B starts first: Team B: - (0 - 0) (max possible score 5 - 4) Team A: - (0 - 0) (max possible score 4 - 4) Team B: - (0 - 0) (max possible score 4 - 3) Team A: X (1 - 0) (max possible score 4 - 3) Team B: - (1 - 0) (max possible score 4 - 2) Team A: X (2 - 0) (max possible score 4 - 2) Team B: - (2 - 0) (max possible score 4 - 1) Team A already has a higher score than B could ever have, but the input hasn't ended yet, so it's invalid if team B stars first. The input is invalid no matter which team starts first, so it's considered invalid. ``` On the contrary, here is a valid example: ``` Team A: X X X Team B: - - - Assuming team A starts first: Team A: X (1 - 0) (max possible score 5 - 5) Team B: - (1 - 0) (max possible score 5 - 4) Team A: X (2 - 0) (max possible score 5 - 4) Team B: - (2 - 0) (max possible score 5 - 3) Team A: X (3 - 0) (max possible score 5 - 3) Team B: - (3 - 0) (max possible score 5 - 2) It can be determined that team A wins, however the input has ended, so it's valid if team A starts first. Therefore, the input is valid. ``` Another example, this time with extra penalties: ``` Team A: X - X - - - X - Team B: - X X - - - X X Assuming team A starts first: Team A: X (1 - 0) (max possible score 5 - 5) Team B: - (1 - 0) (max possible score 5 - 4) Team A: - (1 - 0) (max possible score 4 - 4) Team B: X (1 - 1) (max possible score 4 - 4) Team A: X (2 - 1) (max possible score 4 - 4) Team B: X (2 - 2) (max possible score 4 - 4) Team A: - (2 - 2) (max possible score 3 - 4) Team B: - (2 - 2) (max possible score 3 - 3) Team A: - (2 - 2) (max possible score 2 - 3) Team B: - (2 - 2) (max possible score 2 - 2) First 5 penalties result in a tie, so we move on to extra penalties. Team A: -, Team B: - (2 - 2) Team A: X, Team B: X (3 - 3) Team A: -, Team B: X (3 - 4) It can be determined that team B wins, however the input has ended, so it's valid if team A starts first. Therefore, the input is valid. ``` Here is a valid input where it's too early to determine the winner: ``` Team A: X X - - Team B: - X - X Assuming team A starts first: Team A: X (1 - 0) (max possible score 5 - 5) Team B: - (1 - 0) (max possible score 5 - 4) Team A: X (2 - 0) (max possible score 5 - 4) Team B: X (2 - 1) (max possible score 5 - 4) Team A: - (2 - 1) (max possible score 4 - 4) Team B: - (2 - 1) (max possible score 4 - 3) Team A: - (2 - 1) (max possible score 3 - 3) Team B: X (2 - 2) (max possible score 3 - 3) The input has ended before the winner can be determined, so it's valid if team A starts first. Therefore, the input is valid. ``` Finally, here is an input where the lists' lengths differ: ``` Team A: - - - Team B: X X - X Since team B shot more penalties, it starts first: Team B: X (0 - 1) (max possible score 5 - 5) Team A: - (0 - 1) (max possible score 4 - 5) Team B: X (0 - 2) (max possible score 4 - 5) Team A: - (0 - 2) (max possible score 3 - 5) Team B: - (0 - 2) (max possible score 3 - 4) Team A: - (0 - 2) (max possible score 2 - 4) Team B: X (0 - 3) (max possible score 2 - 4) It can be determined that team B wins, however the input has ended, so it's valid. ``` # Rules * The team that shoots first can be either A or B, you can't assume one will always shoot first. * The lists will either have the same length, or their lengths will differ by one. * You may choose any two distinct and consistent values to represent scored/unscored penalties. * The lists can also be represented as integers converted from [bijective base](https://en.wikipedia.org/wiki/Bijective_numeration) 2, strings or your language's native list format. If a bijective base 2 format is chosen, the input rules apply to the numbers converted to bijective base 2 (so digits `1` and `2` can either mean scored and unscored or unscored and scored respectively). **Regular binary is not allowed**, as one can't determine the presence of leading zeroes in the intended binary representation. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution wins. However, please don't be discouraged from answering even if it seems like your language can't "beat the specialized ones". # Test cases In these test cases, a `0` will represent a no-goal, and a `1` will represent a goal. Format: ``` [Team A], [Team B] ``` Valid inputs: ``` [], [] [0], [0] [0], [1] [1], [1] [0], [] [1, 1, 1, 1], [0, 0, 1, 1] [0, 1, 1, 1, 1], [0, 1, 1, 0] [0, 0, 0, 0, 1], [0, 0, 0, 1, 0] [0, 0, 0, 0, 1], [0, 0, 0, 1] [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1] [0, 1, 1, 1, 1], [0, 1, 1, 0, 1] [1, 1, 1], [0, 0, 0] [1, 1, 1, 1], [0, 0, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ``` Invalid inputs: ``` [0, 1, 1, 1, 1], [0, 1, 1, 0, 0] [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1] [1, 1, 1, 0], [0, 0, 0] [1, 1, 1, 1], [0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] [1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1] [0, 0, 0, 0, 1], [0, 1, 1, 1, 0] ``` [Answer] # JavaScript (ES6), ~~117 112~~ 109 bytes Takes input as `(a)(b)`, using \$1\$ for unscored and \$2\$ for scored. Returns \$0\$ or \$1\$. ``` a=>b=>!(g=(a,b,P=Q=i=5)=>(p=a[5-i])|(q=b[5-i])&&(--i<0?P-Q:P-Q>i|Q+q-P-p>i&p<2)|g(a,b,P+p,Q+=q))(a,b)|!g(b,a) ``` [Try it online!](https://tio.run/##lVE9b4MwEN35Fc5CbGFHplKWKOfO3WDpghhMPpArCqbQKAP/nUJJwQQSUeks8Y53H@/dh7zI4vCldMnS7Hiqz1BLEBGIFY4BSxpRD3xQsCUgsAYZbJkKSYVziLpP28aMqT1/9Zi/a55Qle/kzGNaKFvvX0gVd20cTX0HckJaSKpVjCMqSV2eihIBapIoIggEOmRpkSWnTZLF@Izl5lNqfG1/XJGD3KY8mqSIZZlV63eZqCNSqf4ui92aWO0MHIQUBeEf4C3iY@j20B1DPip1KbrFbw@K@A319J4wcDrETU4fRh@@nDazzzBxkltMXqJipqGx23OjZqXdxVjpTIT3F39LL7M3fyqCP9plMt/9F3lqAF9qD19kz7jhQxONQXw4XG8Cnx5zTpchgtQ/ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => b => // given a[] and b[] !(g = ( // g is a recursive function taking: a, // the results a[] of the team that plays first b, // the results b[] of the team that plays second P = // the cumulated goals P of the 1st team (relative value) Q = // the cumulated goals Q of the 2nd team (relative value) i = 5 // a counter i ) => // and returning a truthy value if something goes wrong (p = a[5 - i]) | // if either the first team (q = b[5 - i]) && ( // or the second team is playing this round: --i < 0 ? // decrement i; if we've played more than 5 penalties: P - Q // do we already have a goal difference? : // else: P - Q > i | // was the 1st team already guaranteed to win? Q + q - P - p > i // or is the 2nd team now guaranteed to win & p < 2 // while the 1st team failed its last attempt? ) | // g( // do a recursive call: a, b, // pass a[] and b[] unchanged P + p, // update P Q += q // update Q ) // end of recursive call )(a, b) | // try g(a, b) !g(b, a) // try g(b, a); return 1 if at least one of them is falsy ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~176~~ ~~169~~ ~~171~~ 169 bytes *-2 bytes thanks to @Kevin Cruijssen* ``` exec"h=lambda a,b,m:m-%s/2>abs(sum(a)-sum(b));f=lambda a,b:a[5#==b[5#and h(a[:5],b[:5],6)if %s>10else h(a,b,7)and h(a[#,b[#,6)".replace("#",":~-%s/2]")%(("len(a+b)",)*6) ``` [Try it online!](https://tio.run/##jVPbboMwDH3nK6ygSkmXbqFSO4mJfsXeMh6SNggkSBEBaXvZr7MUCs3oDWQFJzk@PraV8qdOj3rdtupb7VEa5aKQBwGCSlqExWph3tY7IQ02TYEFWZ1@kpCPxAGGgm/8KJJ2FfoAKRY83MRUduuWZAkszC5gKjfqdGmZ38kA9C3MtyD0WqkyF3uFkY8oCn@7zDEiC4xRrjQWL5IgSpZb0pZ7YZSBCDjnMQUex9TjnJ1c5vhB7weOzxw4hWC0LnTYsREw2gA47@ZgzsndLGfM1dk85FPZUypHzzTF5Sq4LmRi/@u6Ya6wsUFdj0Z5l@MHSrrb2NPOdB9Wy25Kv5IbzEdOxLFZHWQPoiZje9Yd9nwYU/47I7N9LKtM14A@U2WfXd9Tkx6b/ACVqptKQ101KkRecqwgg0xD/6xCD@zXB2cUErzMyMD1pe@zJcI@b5dO36Vr/wA "Python 2 – Try It Online") (Including some extra test cases not listed above.) Creates a function `f` that takes two arguments (the two lists of scored/unscored penalties) and returns `True` if the scores are possibly valid and `False` otherwise. **Partial explanation:** ~~First of all, the `exec` construction is just a way to save a few bytes by not having to repeat the expression `len(a+b)` more than once. The above piece of code is equivalent to the following:~~ ~~Update: the new and improved answer is the same byte count with or without `exec` trickery, so in the interests of simplicity I have removed it.~~ Update 2: The new bugfixed version includes even more string compression via substitution and `exec`. Yes, I use `%` formatting and a `.replace` on the same string. The code above is equivalent to: ``` h=lambda a,b,m:m-len(a+b)/2>abs(sum(a)-sum(b)) f=lambda a,b:a[5:(len(a+b)-1)/2]==b[5:~-len(a+b)/2]and h(a[:5],b[:5],6)if len(a+b)>10else h(a,b,7)and h(a[:(~-len(a+b)/2],b[:(len(a+b)-1)/2],6) ``` The main idea of this answer is to frame the question in terms of "half-points": each successful kick is a half-point and each failed one is a negative half-point. For a set of scores with length \$<=5\$ to be continuable (`not len(a+b)>10`), the total number of kicks left must have been greater than or equal to the half-point margin between the two teams. When one team has kicked an extra time, a half-point must be subtracted from the margin for various reasons, so this can be simplified by integer-dividing both sides of the equation by two. This is the function `h` in the code (with the argument `m` equal to 6). However, to be a valid set of scores, an input need not be strictly continuable, but it must have been continuable before the last kick to have been made. This condition is equivalent to saying that it must 1) have been continuable the last time both sides had kicked the same number of times and 2) currently be within two half-points of being continuable — which is where the final argument to `h` comes in: `h(a[:~-len(a+b)/2],b[:~-len(a+b)/2],6)` tests condition 1) and `h(a,b,7)` (the `7` representing an extra two allowable half-points in the margin) tests condition 2). The case where each team has kicked a maximum of five times has thus been settled. (Explanation to be continued for the other case.) In terms of low-level golfing, I'm doubt there's too much to shave off, but algorithmically it could probably be done quite a bit more simply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~62~~ ~~54~~ 49 bytes ``` ṫ⁵Ṗm2¬Ạ N§ỤḢƊ¦LÞṚZFĵ12R:2U_ṁḣ⁵ṫ-N<Ø.ẠaÇoL<3 ṚÇoÇ ``` [Try it online!](https://tio.run/##y0rNyan8///hztWPGrc@3Dkt1@jQmoe7FnD5HVr@cPeShzsWHes6tMzn8LyHO2dFuR1uObTV0CjIyig0/uHOxoc7FoP1rNb1szk8Qw@oK/Fwe76PjTEXUDGQdbj9/6PGHQqPGubo2j1qmKsA5BxuB5LbQUJAAa7D7Y@a1vz/H80VHR2roxAdG6sDZBmAmAZIbEMI2xCJbYBQbqijAEVgfToKBlAeRCFcFqEAwjOAK4AjJBMMiFSD7gaERagCpCjD42Z0o5Acgyc0MH2BhlA9hQUR4TADrLZgmGxIvEo0HxkQ5VkDwp5FNQpnkMCsMEAEPdzLBmjRgc0jSA6P5YoFAA "Jelly – Try It Online") ``` ṫ⁵Ṗm2¬Ạ # helper function to determine whether # even indices at or beyond 10 are zero ṫ⁵ # tail - take every item from 10 Ṗ # remove last item m2 # take every second item ¬ # logical not, will return 1 for an empty list Ạ # all # function to create cumulative score # difference and check values N§ỤḢƊ¦ # negate scores for team with lower score # (or one of them if both same score) LÞṚ # sort by length, longest first ZF # transpose lists and flatten Ä # cumulative sum µ # this cumulative score difference (CSD) # now becomes left value 12R:2U_ # subtract cumulative score difference from # 6,5,5,4,4,3,3,2,2,1 ṁḣ⁵ # shorten to be no longer than 10 items # and no longer than CSD ṫ-N<Ø.Ạ # check last two values are greater than 0,-1 aÇ # check that helper function also TRUE oL<3 # handle very short scores # main link that calls the above for scores in either order ṚÇoÇ ``` Note the footer code at tio is just to handle multiple test cases and print outputs against inputs. Thanks to @EriktheOutgolfer for golfing off 8 bytes [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 123 bytes ``` {all map {@^b>@^a||[R,](map {abs(($+=$_)-++$ %2/2)>(5-++$ /2 max++$ %2)},flat roundrobin @a,-<<@b).skip.any},@^a,@^b,@b,@a} ``` [Try it online!](https://tio.run/##jVFdT4MwFH22v@KaoGlD2VoSfXEj/Q2@ss20UZJFBgQ0kTB@O3YVatnQkZwm9@Pc03va4q1MH7tDDfcJrLtGpikcZAGN2KlI7OTxGD/TLTYlqSqMPX/tvZDA9z24C5chifCDSZahnvv6KZOWJqn8gDL/zF7LXO0zEJIGq5VQZFG974uFzOqWanl9FBUasu2SvEQo3lLQB8XsFDAb8VPEbcQsjQK3MCNDxvq2xdDus@sMc6Wr3zMuazN4Dsm5ZTz62@Dnq51hvOkE9Py/jzPhfkqWz@WNjLAZDtk1h2OZv9/ByLPBlWPTrU3/s7MwQkEEG0lho6BBN5Ws4TbBOlfkCbXdNw "Perl 6 – Try It Online") Returns falsey for valid shoot-outs, truthy for invalid ones. ### Explanation ``` # Check whether block returns true (invalid shoot-out) for arguments (a, b) and (b, a) {all map {...},@^a,@^b,@b,@a} # Return true (invalid) if array b is longer than a @^b>@^a|| # Return true (invalid) if any except the last value is true (shoot-out stopped) [R,](...).skip.any # Map values from a and negated b, interleaved map {...},flat roundrobin @a,-<<@b # Shoot out stopped? abs(($+=$_)-++$ %2/2)>(5-++$ /2 max++$ %2) # # Accumulator # # Subtract 0.5 for first team # # Sequence 4.5 4 3.5 3 2.5 2 1.5 1 1 0 1 0 1 0 ``` ]
[Question] [ In the game 2048, you have a grid, and you can move the elements in four directions. They all move in that direction as far as they can. For this challenge, you will be given a padded, square 2D string (either with newlines, or a list of strings), like so: ``` ab cd e f ghij kl mno p q r st u v w x y z ``` or ``` ['ab cd e ', ' f ghij ', ' kl', 'mno p ', ' q r st ', 'u v', ' w x y ', 'z '] ``` The four operations are `left`, `right`, `up`, and `down`. The result of each on the above input: ### Left: ``` abcde fghij kl mnop qrst uv wxy z ``` or ``` ['abcde ', 'fghij ', 'kl ', 'mnop ', 'qrst ', 'uv ', 'wxy ', 'z '] ``` ### Right: ``` abcde fghij kl mnop qrst uv wxy z ``` or ``` [' abcde', ' fghij', ' kl', ' mnop', ' qrst', ' uv', ' wxy', ' z'] ``` ### Up: ``` abocdiel mf ghsjv un rp k zq x t w y ``` or ``` ['abocdiel', 'mf ghsjv', 'un rp k ', 'zq x t ', ' w y ', ' ', ' ', ' '] ``` ### Down: ``` b e af c j mn gd k uq rhitl zwoxpsyv ``` or ``` [' ', ' ', ' ', ' b e ', 'af c j ', 'mn gd k ', 'uq rhitl', 'zwoxpsyv'] ``` --- Your goal is to rotate which operation is performed each iteration, performing them on the input `n` times. So if your order is `URDL`, and the input says to start with `D` (`2`, 0-indexed), and you need `5` operations, you perform `D-L-U-R-D`, then print. ## Input: * A string in a format like above + Trailing spaces are not required (but they are probably helpful) + It will be at least 2x2 + Will only contain printable ASCII and spaces (and newlines per your input format) + You should theoretically support any length, but memory constraints are okay * A non-negative integer, `n`, for the number of operations that will be performed * An integer `0-3` or `1-4`, or a letter `UDLR`, describing the operation to start with. + So your program must be able to start or end with any operation + You may define them in any order for starting purposes, but it must be a consistent order, so `U` cannot sometimes follow `R` and also sometimes follow `L`. * Operations must be performed non-trivially + You could do operations in the order `LDRU` (left, down, right, up) repeatedly, but not `DLRU` or `UDLR` (because `UD` is the same as `D`, and `LR` is the same just as doing `R`.) ## Output: * The string after performing the four operations `n` times * The output format must be the same as your input format * Trailing spaces are not required (but they are probably helpful) ## Example: This example uses the order `URDL`. ### Input: ``` 10 (number of times operations are applied) 0 (starts with Up) ``` ``` ab cd e f ghij kl mno p q r st u v w x y z ``` ### Outputs for n = 0-5: (just print the end result) ``` ab cd e f ghij kl mno p q r st u v w x y z --------------- abocdiel mf ghsjv un rp k zq x t w y --------------- abocdiel mfghsjv unrpk zqxt wy --------------- el dijv chspk bognrxt amfuzqwy --------------- el dijv chspk bognrxt amfuzqwy --------------- eljvkxty disprqw chgnz bofu am ``` My pretty, ungolfed [implementation](https://tio.run/nexus/python2#fY8xb8IwEIXn3q84Wap8BicqUllSZUOdmBBMIUIhGGpqHNcOLeXPUycIlQlPT9/53b13meemOqw3FZrsUDniPN032sqzdjQwQsD0Ng9ZUadeOVPVijhyyblIzf4YWjLKUi1khGLbeKxRWwwlzB5a/SPr4t86pynNKYiYZXJPZze6UVt0UWbOa9siW1rWd4jorUcsSRI2GEP/852C1LIRGTx1B0/dQV/ZnSItspAXCzmTEzktCzoNG/H8WsY18ORVe/Qx2SXkjDGo1lhvUCHgFncfeh9F/z4NHGyDLkrAL/QYWoTjdfYN@BPP4S/C@UoQ4q5ilCWjMg3O6Jb40nIBoPMxNPkLdAFXdwGHoy62o67DKnYQlz8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` UZ Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y ``` [Try it online!](https://tio.run/nexus/jelly#@x8axXW4/dBC20eN21QOz3vUtOZwu8qjxi2HFkaFAumt2iD2kkMLI////x@tnpikkJyikKqgrqOgrpCmkJ6RmQVhg0F2Doidm5evUADkgcULFYoUikvA7FKIojKweLlChYJCJVi8CiKuoB773/S/IQA "Jelly – TIO Nexus") I'm a bit unsatisfied, but MATL needed some competition. :P Uses the order `URDL`. Inputs: * the input array as an array of padded lines * the number of repetitions * the move to start from (1 = `U`, 2 = `R`, 3 = `D`, 4 = `L`) ### Explanation ``` UZ Helper link. Argument: A (the 2D array) U Reverse each line and... Z ...transpose. Rotates 90° CCW. Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y Main link. Arguments: A, n (2D array, repetitions) Ç Rotate 90° CCW... ¡ ...m times. (m = which move to start on) Þ Sort... € ...each line of the array... =⁶ ...based on the characters' equality to " ". Ç Rotate 90° CCW. $ Combine the sort and rotate to one action. ⁴¡ Do that n times. (n = repetition count) Z Transpose and... U ...reverse each line. Rotates 90° CW. $ Combine the transpose and reverse to one action. ¡ Do that... ⁵+⁴¤ ...m + n times. Y Join the array by newlines. ``` [Answer] ## JavaScript (ES6), 168 bytes ``` (n,d,s,t=s.replace([RegExp(`( )([^]{${l=s.search` `}})(\\w)`),/(.)(\b)( )/,RegExp(`(\\w)([^]{${l}})( )`),/( )(\b)(.)/][d%4],`$3$2$1`))=>n?t!=s?f(n,d,t):f(n-1,d+1,s):s ``` Ungolfed: ``` function gravity(count, direction, string) { let width = string.indexOf('\n'); let up = new RegExp('( )([^]{' + width + '})(\\w)'); let down = new RegExp('(\\w)([^]{' + width + '})( )'); while (count--) { let regexp = [up, /(.)(\b)( )/, down, /( )(\b)(.)/][direction++ % 4]; while (regexp.test(string)) string = string.replace(regexp, '$3$2$1'); } return string; } ``` `d` is the initial index into the directions which are `URDL`. [Answer] # [Python 2](https://docs.python.org/2/), ~~226~~ ~~224~~ ~~204~~ 193 bytes -1 byte thanks to Trelzevir ``` x,s,n=input() j=''.join g=lambda x,i:[eval("j(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x] for i in([0,3,1,2]*n)[s:s+n]:x=[map(j,zip(*g(map(j,zip(*x)),i))),g(x,i)][i>1];print'\n'.join(x) ``` [Try it online!](https://tio.run/nexus/python2#TY/BboMwDIbvPIVVCcXuItR22oWJvUgWIboCdRYCI9BlfXlGww7zwfr@Tz78XoL00hXshnlCSkwhRGZ6dklb2Ko7XyoIknNV3yqLO4Nl5gfLEwoQRFnqzewntLXDkmiXCjsKxelJU9OPUAI7CDp5MK@M6iCf5VGe9N6R8rl/cjoPheqqAY2884D7Fv@FQCSZ1tXi2oG04rejfh1GdpN4d1tNDLREAw3@/UCLUqI6w8cFahASBDTQXtlsHOfTPrhzPQxriv4LRvBT5Hk7ukX/DQHgJ/r75kFoeZAv@hc "Python 2 – TIO Nexus") Function that remove all spaces of each element in the list and complete with spaces on left or right. ``` g=lambda x,i:[eval("''.join(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x] ``` This to transpose (rotate 90º) when the input is `0` or `1`(`U` or `D`) and apply `g` ``` x=[map(''.join,zip(*g(map(''.join,zip(*x)),i))),g(x,i)][i>1] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~24~~ 23 bytes ``` :+"@X!XJ_JXzJ32>S(c@_X! ``` Order is `URDL`, `1`-based. So `1` is Ù`,`2`is`R` etc. Inputs are: number of times, initial direction, char matrix (using `;` as row separator). [Try it online!](https://tio.run/nexus/matl#@2@lreQQoRjhFe8VUeVlbGQXrJHsEB@h@P@/KZchV7R6YpJCcopCqoK6tYKCukKaQnpGZhaUAwbZOWBObl6@QgGQC5EpVChSKC6BcEoh6sogMuUKFQoKlRCZKoiMgnosFwA) ]
[Question] [ Imagine I have an infinite number of homework problems (!) each given an integer number. Math Problem Notation is a notation for describing subsets of the problem using problem specifiers. An MPN expression can consist of several things: * A single value. This represents a set containing the number: `99 -> {99}`. * A simple range. This represents the set containing all the numbers from the beginning to the end of the range: `10~13 -> {10, 11, 12, 13}`. If the left or right sides are missing, then they are assumed to be -Infinity or Infinity respectively: `~10 -> {x|x ≤ 10}`; `~ -> ℤ`. * An MPN expression, followed by "skip" and another MPN expression. This represents the difference of the two sets: `10~20 skip 12~14 -> {10, 11, 15, 16, 17, 18, 19, 20}`. * Two MPN expressions, separated by a comma. This represents the union of two sets: `1,8~9,15~17 -> {1,8,9,15,16,17}`. The "skip" operator binds tighter than the comma operator, so `16,110~112 skip 16 -> {16,110,111,112}` (16 is not included in the set `{110,111,112}`, so the excluding 16 does not matter.) You can also put expressions in parentheses for disambiguation: `1~9 skip (2~8 skip (3~7 skip (4~6 skip 5))) -> {1,3,5,7,9}` This is the grammar: ``` <expr> ::= "(" <expr> ")" || <number> || [<number>] "~" [<number>] || <expr> "skip" <expr> || <expr> "," <expr> ``` --- Your task is to write a program that takes two inputs: * An MPN expression * A number and outputs some truthy or falsey value depending on whether that problem is in the set described by the MPN expression. ## Specifications * You can assume that the first input is a well-formed MPN expression (i.e. that it matches the above grammar) * Numbers in an MPN expression are always integers. They can be negative or zero, but will never have a fractional part. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (measured in bytes) wins. * You can use different characters for `~` and `,`, if you want. ## Test Cases ``` 10~20 14 -> True 10~20 20 -> True 10~20 skip 14~18 17 -> False ~ skip 6 8 -> True 16,17 skip 16 16 -> True (16,17) skip 16 16 -> False ~10,5~ 8 -> True ~10,5~ 4 -> True 6 skip 6,~ 6 -> True ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~189~~ 195 bytes ``` param($m,$q)('$m',"'(\d*)~(\d*)','($q-ge(`$1)-and$q-le(`$2))'","'\(\)',$q","'((?<=,|skip )\d+|\d+(?=,| skip))','($q-eq`$1)'","'skip','-and!'"-join'-replace'|iex|% Sp* ','|%{"($_)"})-join'-or'|iex ``` * [Try it online!](https://tio.run/nexus/powershell#NY7dDoIwDIVfZS4jbREuAH8TDQ/hLYkSWQzK3/DGxLlXnxviRZvTk6@ntUM5li2KNhKKEEQLEQcsqpDM1CECFCq@SbyIhOKyq9zU@CklAu7gAgtHCeU1Yn44Rvr5qAdGRbXUrjB3DvMW/dOk8mHTtved64MXwON7X3cQj3JoyqsEXcuXDthpCJljdPDmKM7EPzRz/Tgh1lpIzH66wTA1u1llZjurldn81JrcEzb7Ag "PowerShell – TIO Nexus") (with a single MPN and value) * [Try all test cases with `-100..100` as values](https://tio.run/nexus/powershell#TZFtT4NADMdfw6eo5Ob12LEAbjgTyfwAziz6lmQjctnQsQfAaALcV593B4u@oGn//bXXFiS1qOoK4ie0aeDL0Kd8cKD6zE8QTGUw15rs48jkIx7cD3kjoFHYf0kGPp9JQ8uHPoGhnA/enRzqcSqj3psxxjQ@hBGX1GYMWhhBY1tkuXqBGMhauaWovvZ6aPAC359MlFHYQmPWLTSXU1qmBZKCkzNDSgrKHYpJ5jJpLOUUydnbCtyQgHnpIVPRXkehmsBRcIKJoshZ@4iLx5i3ZiaWZONWfbhQihmTXbuJs25mqrWuVN34hjrexzE/UK8Up336Lmibi592BG8nFxTTjhoHyZo5HRu4Y2mQi2V1YHbWG3dq6e88q3f6AuaHtYVIq69SwLNwwVumuqeybn@oySrNXvPtrsa@bBwyGIPTELzern@NA2Xd5kCQxtT9Y5ljd5df) * [View the intermediate code generated, for all test cases (with 666 as the value)](https://tio.run/nexus/powershell#TZHbTsMwDIav16cwJcNOSaV1bGFIVOMBGELittKoaASFdethE0jr8uolScvhotbvz38cOyW2V82@gfiOPIwmejpBMQhoPvISopmOFpbpPpeuLkV0PdQdIEf4f6SjiZhr59Y3fYGmejGoKz2cp5mWvZpzzq19SKXQ6HEOLYzh6I3Y6vEBYmBrI2vVHDZ2aLiAY1emdVoQKwSrOCErUPhISRZw7SIKJFaFr4qeWcTDdJuZbGOzqbnPN@aEEuNildVEy9tYtG4CnmSXrfloaYgbiv90U5Vt5k5bbqhtfIZ@@L7LtxjWqtykLwrbXH21Y3gqAzCednz0ia25f@KDb1fjufV0oxO4DaWU/a4mfubZ/s3u7H5RW6i0OdQK7lUA4Sq1fU0MvBGGGPTmv7cxNP6lp@4b) ## Explanation I realized early on that the infinities make this untenable for generating arrays and testing for values. I looked into ranges but in .Net they don't have the range needed (the *length* of the range is limited to a signed (32 bit) integer, so even if it were ok to limit the range to a signed 32-bit int, I wouldn't have been able to handle all ranges. So I started to just think about this in terms of starts and ends, and ultimately a series of boolean tests and started creating a bunch of regex replaces to turn an MPN into a boolean expression that PowerShell understands. I basically broke this down into a few rules: * Ranges were easier to work with first because they can't be expressions on either end, but the open-endedness was a pain to implement shortly. The premise is `2~8` is like saying `n >=2 && n <=8`, but when one of the ends is missing, leave out the `&&` and the missing side. When both are missing, I was going to originally just replace it with `$true`. What I ended up doing was not really testing for the missing sides at all, but I made sure to wrap each number in `()`. * and then do a straight substitution that replaces empty parentheses `()` with the input value. So, in the case of an MPN like `~8` with an input value of `55`, the first replace will generate `(55-ge()-and55-le(8))`, then the second replace comes along to make it `(55-ge55-and55-le(8))`, essentially nullifying that part of the range. * Next I had to deal with individual numbers in the MPN, but had to take care not to mess with the ones I inserted from before. It's really just numbers in comma `,` separated lists, and individual numbers before or after a `skip`, so I used unfortunatley long lookarounds. * `skip` is basically the same as `-and -not` so I do a straight replace of `skip` to `-and!` (using `!` as shorthand for `-not`). * The next tricky thing was the low order of precendence for the remaining commas. I originally just replaced them with `-or` but it didn't account for subsequent expressions so `16,17 skip 16` was generating code like `($n-eq16)-or($n-eq17) -and! ($n-eq16)`. It needed parentheses, but that seemed unworkable with a straight replace. Since all the other things were replaced except commas, and they have the lowest precedence, I just split the entire generated string on the remaining commas, then wrapped each element in parentheses, and rejoined it with `-or`. Ultimately the generated code is just piped into `Invoke-Expression` (`iex`) to be executed and then we get the boolean result ([you can see the code that gets generated instead of the result here](https://tio.run/nexus/powershell#TZHbTsMwDIav16cwJcNOSaV1bGFIVOMBGELittKoaASFdethE0jr8uolScvhotbvz38cOyW2V82@gfiOPIwmejpBMQhoPvISopmOFpbpPpeuLkV0PdQdIEf4f6SjiZhr59Y3fYGmejGoKz2cp5mWvZpzzq19SKXQ6HEOLYzh6I3Y6vEBYmBrI2vVHDZ2aLiAY1emdVoQKwSrOCErUPhISRZw7SIKJFaFr4qeWcTDdJuZbGOzqbnPN@aEEuNildVEy9tYtG4CnmSXrfloaYgbiv90U5Vt5k5bbqhtfIZ@@L7LtxjWqtykLwrbXH21Y3gqAzCednz0ia25f@KDb1fjufV0oxO4DaWU/a4mfubZ/s3u7H5RW6i0OdQK7lUA4Sq1fU0MvBGGGPTmv7cxNP6lp@4b)). This took way too long, and I'm sure there's some room to squeeze out a few more bytes, but I can't look at it anymore :-p [Answer] # Perl, ~~99~~ 130 bytes ``` sub f{($_,$n)=@_;s/(-?\d+)?~(-?\d+)?|(-?\d+)/!(defined$3?$n!=$3:length$1&&$1>$n||length$2&&$n>$2)+0/ge;s/skip/&&!/g;s/,/||/g;eval} ``` [Try it on Ideone.](http://ideone.com/PNCzW4) Ungolfed: ``` sub f { my ($e, $n) = @_; $e =~ s/(-?\d+)?~(-?\d+)?|(-?\d+)/ (defined($3) ? $n == $3 : (!length($1) || $n >= $1) && (!length($2) || $n <= $2)) + 0 /ge; $e =~ s/skip/ && ! /g; $e =~ s/,/ || /g; return eval($e); } ``` [Answer] # JavaScript (ES6), ~~221~~ ~~292~~ ~~287~~ ~~309~~ ~~274~~ ~~277~~ 278 bytes *(-5 bytes thanks to Okx)* ``` (j,v,m=1/0,Z=/(skip)([^,]+)/g)=>eval(j[M='replace'](/(-?\d*)~(-?\d*)/g,(e,a,b)=>(a[M]('-','#')||-m)+'<='+(T=v[M]('-','#'))+'&&'+T+'<='+(b[M]('-','#')||m))[M](Z,i=o=>o.match(Z)?i(o[M](Z,'&&!($2)')):o)[M](/,/g,'||')[M](/(^|[^=&#\d])(\d+)([^<\d]|$)/g,'$1$2=='+v+'$3')[M](/#/g,'-')) ``` Wow. This was not easy because of all the edge cases, but I think I did it. I just *hope* there are no special cases that could break the regular expressions used. I will golf this more whenever I can. ## Test Snippet ``` D=(j,v,m=1/0,Z=/(skip)([^,]+)/g)=>eval(j[M='replace'](/(-?\d*)~(-?\d*)/g,(e,a,b)=>(a[M]('-','#')||-m)+'<='+(T=v[M]('-','#'))+'&&'+T+'<='+(b[M]('-','#')||m))[M](Z,i=o=>o.match(Z)?i(o[M](Z,'&&!($2)')):o)[M](/,/g,'||')[M](/(^|[^=&#\d])(\d+)([^<\d]|$)/g,'$1$2=='+v+'$3')[M](/#/g,'-')) ``` ``` MPN Expression:<input type="text" value="1~9 skip (2~8 skip (3~7 skip (4~6 skip 5)))" id="MPN"></input> <br> Integer:<input type="number" id="INT" value=6></input> <input type="button" value="Submit" onclick="T=r=>document.getElementById(r).value;console.log(D(T('MPN'),T('INT')))"></input> ``` [Answer] # [Röda](https://github.com/fergusq/roda) + bc, 183 bytes ``` f x{{["x=",x,"\n"];replace" ","",",","||","skip\\(","&&!","skip([0-9~]+)","&&!($1)","(?<!~|\\d)(\\d+)(?!~|\\d)","x==$1","(\\d*)~(\\d*)","x>=($1)&&x<=($2)","\\(\\)",x;["\n"]}|exec"bc"} ``` This is similar to the PowerShell answer (or I think so, I don't understand PowerShell). It takes the number as an argument and the code as a value in the input stream, like this: `main { push("1~9") | f(5) }`. I think it works, at least it solves all test cases. The script below can be used to verify this. ``` main { readLines("/tmp/tests.txt") | split(sep=";") | for code, num, ans do push(code, " -> ") print(code) | replace" ","",",","||","skip\\(","&&!","skip([0-9~]+)","&&!($1)","(?<!~|\\d)(\\d+)(?!~|\\d)","x==$1","(\\d*)~(\\d*)","x>=($1)&&x<=($2)","\\(\\)",num a := push(code) | f(num) | head() result := push("OK") if [ (a = "0" and ans = "False") or (a = "1" and ans = "True") ] else push("FAIL") print code, " ; ", num, " -> ", a, " ", ans, " (", result, ")\n" done } ``` And the tests: ``` 10~20;14;True 10~20;20;True 10~20 skip 14~18;17;False ~ skip 6;8;True 16,17 skip 16;16;True (16,17) skip 16;16;False ~10,5~;8;True ~10,5~;4;True 6 skip 6,~;6;True ``` ]
[Question] [ An easy way to understand the unit n-dimensional hypercube is to consider the region of space in n dimensions that you can get if every coordinate component lies in [0, 1]. So for one dimension it's the line segment from 0 to 1, for two dimensions it's the square with corners (0, 0) and (1, 1), etc. Write a program or function that given *n* returns the average Euclidean distance of two points uniformly random selected from the unit n-dimension hypercube. Your answer **must** be within 10-6 of the actual value. It's ok if your answer overflows your language's native floating point type for big n. ***Randomly* selecting a 'big' number of points and calculating the average does not guarantee such accuracy.** Examples: > > 1 → 0.3333333333... > > 2 → 0.5214054331... > > 3 → 0.6617071822... > > 4 → 0.7776656535... > > 5 → 0.8785309152... > > 6 → 0.9689420830... > > 7 → 1.0515838734... > > 8 → 1.1281653402... > > > Data acquired from [MathWorld](http://mathworld.wolfram.com/HypercubeLinePicking.html). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. [Answer] # Mathematica, 68 bytes ``` NIntegrate[(1-((E^-u^2+u*Erf@u√π-1)/u^2)^#)/u^2,{u,0,∞}]/√π& ``` Implementation of the formula using `NIntegrate` to approximate its value. ![Image](https://i.stack.imgur.com/SyuZ6.png) ]
[Question] [ **Warning: DO NOT take medical advice from this post. If you want medical advice, go to a qualified professional.** I have a headache. I need headache pills. I'll tell you the last few doses I've had, and you tell me when I can have my next dose, without overdosing. I'll give you this string: `P: 00:00, I: 02:00, P: 04:00, I: 06:00` And you'll give me this: `Next P: 08:00, I: 10:00` # Input: String representing the times each medication has been taken, in the following format: ``` P: 00:00, I: 02:00, P: 04:00, I: 06:00 ``` This means Paracetamol was taken at 00:00 and 04:00, and Ibuprofen was taken at 02:00 and 06:00 # Output (updated): String with the time the next does of each medication can be taken, in the following format: ``` Next P: 08:00, I: 10:00 ``` * The output order should be in the order which the medication is to be taken. - If Ibuprofen is to be taken at 09:35 and Paracetamol and 10:22, then the output should be `Next I: 09:35, P: 10:22` * If the times for the next dose of each medication are the same, the output order doesn't matter: `Next P: 08:00, I: 08:00` OR `Next I: 08:00, P: 08:00` * If only one medication is being taken (in the input string), then only that medication should be in the output string: `Next P: 02:00` # Rules: * There will only ever be two types of medication, Paracetamol 'P' and Ibuprofen 'I'. * Paracetamol can be taken once every 4 hours, a maximum of 4 times within a 24-hour period. * Ibuprofen can also be taken once every 4 hours, a maximum of 4 times within a 24-hour period. * Paracetamol and Ibuprofen can be taken together, or at separate times. One doesn't count towards the dosage of the other. * The times in the input string will always be consecutive, but may roll over midnight (23:00 -> 03:00) * The times in the input string will not span more than 24 hours * Maximum of 4 times for each medication (8 max in total) * Input will always be non-empty and contain at least one medication and one time # Examples: Two doses of each at two hour intervals: `"P: 00:00, I: 02:00, P: 04:00, I: 06:00" -> "Next P: 08:00, I: 10:00"` Single dose of Paracetamol `"P: 22:00" -> "Next P: 02:00"` Maximum Paracetamol dose within 24 hours, single Ibuprofen dose `"P: 04:05, P: 08:10, P: 12:15, I: 12:30, P: 16:25" -> "Next I: 16:30, P: 04:05"` # Test cases: ``` "I: 06:00" -> "Next I: 10:00" "P: 22:00" -> "Next P: 02:00" "P: 22:00, P: 02:00, I: 06:00" -> "Next P: 06:00, I: 10:00" "P: 00:00, I: 02:00, P: 04:00, I: 06:00" -> "Next P: 08:00, I: 10:00" "P: 04:05, P: 08:10, P: 12:15, I: 12:30, P: 16:25" -> "Next I: 16:30, P: 04:05" "I: 06:32, P: 08:15, I: 10:44, P: 13:03" -> "Next I: 14:44, P: 17:03" "P: 07:30, I: 07:30, P: 11:30, I: 11:30, P: 15:30, I: 15:30, I: 19:30" -> "Next P: 19:30, I: 07:30" "I: 07:30, P: 11:30, I: 11:30, P: 15:30, I: 15:30, P: 19:30, I: 19:30" -> "Next P: 23:30, I: 07:30" "P: 07:30, I: 07:30, P: 11:30, I: 11:30, P: 15:30, I: 15:30, P: 19:30, I: 19:30" -> "Next P: 07:30, I: 07:30" OR "Next I: 07:30, P: 07:30" ``` This is code golf, so the shortest answer int bytes wins. # UPDATE: The output can now be abbreviations of Paracetamol and Ibuprofen; `P` and `I` [Answer] # JavaScript (ES6), ~~367~~ ~~362~~ ~~354~~ 358 bytes Golfed version: ``` A=i=>i>9?""+i:"0"+i,B=(s,a=":")=>s.split(a),C=(a,b,c,d)=>[...[s,t]=B((b>3?c:d)||":"),a+` ${A(s=b>3?+s:(+s+4)%24)}:`+A(t=+t)],F=s=>{a=B(s,m=", ");for(b=c=d=e=f=p=q=0;f<a.length;g=="P:"?(b++,d=d?h:p=h):(c++,e=e?h:q=h))[g,h]=B(a[f++]," ");[i,j,k]=C("P",b,p,d),[n,o,l]=C("I",c,q,e),r=B(h)[0];return"Next "+c?b?n*60+(n<r)*1440+j<i*60+(i<r)*1440+o?l+m+k:k+m+l:l:k} ``` Ungolfed/commented: ``` // Returns a zero-padded string of the argument. A=i=>i>9?""+i:"0"+i, // Since we do a lot of splitting, alias it. Making the // second argument optional (and defaulting to ':') saved // 3 bytes B=(s,a=":")=>s.split(a), // Constructs a string for output, along with the time // of the next dose, in the format [hour, minute, string]. // Arguments: type // a -> type (P/I) String // b -> amount of doses Number // taken // c -> first dose taken String // d -> last dose taken String // // The first two values are split from the string, but // before the array is returned, they are converted to // integers (during the string construction). C=(a,b,c,d)=>[...[s,t]=B((b>3?c:d)||":"),a+` ${A(s=b>3?+s:(+s+4)%24)}:`+A(t=+t)], // Main function. Returns the time(s) for the next dose. // Argument: type // s -> list of times of String // and types of // doses taken F=s=>{ a=B(s,m=", "); // Split the input by comma + space, // and save that string, since we // need it later when constructing // the output string. // For loop has been restructured. Original: // for(b=c=f=0;f<a.length;g=="P:"?(b++,d=d?h:p=h):(c++,e=e?h:q=h)) // [g,h]=B(a[f++]," "); b = 0; // P-dose counter c = 0; // I-dose counter d = 0; // Last P-dose e = 0; // Last I-dose p = 0; // First P-dose q = 0; // First I-dose for (f = 0; f < a.length; f++) { [g, h] = B(a[f], " "); // g contains the type, // h contains the time if (g == "P:") { b++; // increase the counter if (d == 0) { // store h in p if this is p = h; // the first dose of this } // type d = h; } else { // See the above code block for comments c++; if (e == 0) { q = h; } e = h; } } // End of restructured for loop. // Construct the output strings, and get the times. // See comments at C function. [i, j, k] = C("P", b, p, d); [n, o, l] = C("I", c, q, e); // Get the amount of hours of the dose taken last. // We use this to get the correct order of the two // times. r = B(h)[0]; // Return statement has been restructured. Original: // return "Next "+c?b?n*60+(n<r)*1440+j<i*60+(i<r)*1440+o?l+m+k:k+m+l:l:k //================================================== // Start creating the output string. output = "Next " // Use the following checks to figure out what needs // to be part of the output and in what order. if (c > 0) { if (b > 0) { // Compare the times of next doses // P_time = (i + (i < r) * 24) * 60 // I'm using implicit conversion of // booleans to numbers. If the next // dose is past midnight, add 1 * 24 // to the time, so it is compared // correctly. // Then add the minutes to the number. P_time = i*60+(i<r)*1440+o; I_time = n*60+(n<r)*1440+j; if (I_time < P_time) { output += l + m + k; // I first } else { output += k + m + l; // P first } } else { output += l; // Just I } } else { output += k; // Just P } // Finally, return the output return output; } ``` To use it, call F with the string as argument like so: ``` F("P: 04:00, I: 06:00") ``` [Answer] # Python 3 - 437 bytes ``` a=input();i=p=l=-1;j=q=0 for x in a.split(", ")[::-1]: for y, z in [x.split(": ")]: s=lambda q,r,t:[t,sum([a*b for a,b in zip([60,1],map(int,q.split(':')))])][r%4<2]+[0,240][r<2] if y=="I":j+=1;i=s(z,j,i) else:q+=1;p=s(z,q,p) l=[l,p+i-239][j+q<2] r=lambda d,e:("","%s: %02d:%02d, "%(d,(e/60)%24,e%60))[e>-1];p+=[1440,0][p>=l];i+=[1440,0][i>=l];print("Next "+[r("I",i)+r("P",p),r("P",p)+r("I",i)][p<i][:-2]) ``` Explanation: ``` a=input();i=p=l=-1;j=q=0 for x in a.split(", ")[::-1]: #Read in reverse order, a="P: 01:00" for y, z in [x.split(": ")]:#Y="P", Z="00:00" s= lambda q,r,t:[t,sum([a*b for a,b in zip([60,1],map(int,q.split(':')))])]#Convert "01:01" to 61 [r%4<2]#In case it's the first or fourth string calculate a new value, otherwise: return the original value +[0,240][r<2]#In case it's the last string: add 4 hours. Otherwise, leave it. if y=="I":j+=1;i=s(z,j,i)#Calculate for i else:q+=1;p=s(z,q,p)#Calculate for p l=[l,p+i-239][j+q<2]#Sets the last record. Since we read in reverse order, this should be the first one. We've added 4 hours though so remove those again r=lambda d,e:("","%s: %02d:%02d, "%(d,(e/60)%24,e%60))[e>-1];#Print function, don't print anything when we have no value p+=[1440,0][p>=l];i+=[1440,0][i>=l]; #Add a day if record is before the last record so we can correctly calculate the order print("Next "+[r("I",i)+r("P",p),r("P",p)+r("I",i)][p<i][:-2])#print it and remove the last "," ``` [Answer] # PHP, ~~228~~ ~~241~~ ~~239~~ ~~227~~ 226 bytes requires PHP 7 ``` Next<?foreach(explode(", ",$argv[1])as$d){[$m,$h,$i]=explode(":",$d);$x[$m][++$$m]=24+$h+$i/60;}foreach($x as$m=>$d)$r[$m]=$d[$$m-3]?:$d[$$m]-20;sort($r);foreach($r as$m=>$t)$o[]=" $m: ".date("i:s",$t%24*60);echo join(",",$o); ``` **breakdown** ``` Next<? // print "Next" foreach(explode(", ",$argv[1])as$d) // loop through string split by comma+space { [$m,$h,$i]=explode(":",$d); // separate drug, hours and minutes $x[$m][++$$m]=24+$h+$i/60; // append time to array, track count in ${$m} } // (i.e. $P for drug "P" etc.) foreach($x as$m=>$d) // loop through drugs $r[$m]= // add time to result $d[$$m-3] // if more than 3 medications, use $$m-3 ??$d[$$m]-20 // else use last medication - 20 hours ; sort($r); // sort results by time foreach($r as$m=>$t)$o[]=" $m: " // prepare for output: drug name and formatted time: .date("i:s",$t%24*60) // use hrs as mins and mins as secs to avoid TZ problems ; echo join(",",$o); // print ``` [Answer] ## JavaScript (ES6), 246 bytes ``` s=>s.split`, `.map(s=>(m[s[0]].unshift(t=s.replace(/\d+/,h=>(h=(1+h)%24)>9?h:`0`+h),s),l=l||t.slice(1)),l=0,m={I:[],P:[]})&&`Next `+[].concat(m.I[7]||m.I[0]||[],m.P[7]||m.P[0]||[]).sort((i,p)=>((i=i.slice(1))<l)-((p=p.slice(1))<l)||i>p).join`, ` ``` Explanation: Looping over each dose, the `I` and `P` doses are separated into two arrays. 4 hours is also added to each dose, and those times are saved too. The arrays are populated in reverse to make detecting 8 entries easier. The time 4 hours after the first dose is also saved for use during sorting. At this point each array can be in one of three states: * 8 entries, in which case the last entry is the first dose, and the next dose must be 24 hours after this dose (i.e. the same time tomorrow) * 2, 4 or 6 entries, in which case the first entry is 4 hours after the last dose, and therefore the time of the next dose * 0 entries, in which case we concatentate `[]`, which gets flattened and therefore excluded from the result Having extracted the next dose times from the two arrays, it remains to sort them into order. This is done by comparing them against the time 4 hours after the first dose. If one of the two times is before this time, this must refer to tomorrow, and that dose comes last. Otherwise, the times are simply compared directly. (Rather inconveniently, the medicine is before the time, so I have to strip it to compare properly.) ]
[Question] [ ### Background Very skilled card handlers are capable of a technique whereby they cut a deck perfectly in half, then perfectly interleave the cards. If they start with a sorted deck and perform this technique flawlessly 52 times in a row, the deck will be restored to sorted order. Your challenge is to take ~~a deck of cards~~ an integer array and determine whether it can be sorted using only Faro shuffles. ### Definition Mathematically, a Faro shuffle is a permutation on 2 *n* elements (for any positive integer *n*) which takes the element in position *i* (1-indexed) to position 2 *i* (mod 2 *n*+1). We would also like to be able to handle odd-length lists, so in that case, just add one element to the end of the list (a Joker, if you have one handy) and Faro shuffle the new list as above, but ignore the added dummy element when checking the list's order. ### Goal Write a program or function that takes a list of integers and returns or outputs  a truthy if some number of Faro shuffles would cause that list to be sorted in nondescending order (even if that number is zero--small lists should give a truthy). Otherwise,  return or output a falsy. ### Examples ``` [1,1,2,3,5,8,13,21]  => True [5,1,8,1,13,2,21,3] => True [9,36,5,34,2,10,1] => True [1,0] => True [0] => True [] => True [3,2,1] => True [3,1,2] => False [9,8,7,6,5,4,3,2,1,0] => True [9,8,7,6,5,4,3,2,0,1] => False [3,1,4,1,5,9,2,6,9] => False [-1,-1,-1,-2] => True ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest source in bytes wins. [Answer] # Pyth - ~~26~~ ~~25~~ 24 bytes Uses cumulative reduce to apply Faro shuffle multiple times and keep all the results. Then, it maps through it and checks if they are invariant under sorting, then uses sum to check is any are true. Returns a positive or zero. ``` smSI-db.usC_c2NQsC.tc2Qb ``` [Test Suite](http://pyth.herokuapp.com/?code=smSI-db.usC_c2NQsC.tc2Qb&input=1%2C2%2C3%2C4%2C5%2C6%2C7&test_suite=1&test_suite_input=%5B1%2C1%2C2%2C3%2C5%2C8%2C13%2C21%5D%0A%5B5%2C1%2C8%2C1%2C13%2C2%2C21%2C3%5D%0A%5B9%2C36%2C5%2C34%2C2%2C10%2C1%5D%0A%5B1%2C0%5D%0A%5B0%5D%0A%5B%5D%0A%5B3%2C2%2C1%5D%0A%5B3%2C1%2C2%5D%0A%5B9%2C8%2C7%2C6%2C5%2C4%2C3%2C2%2C1%2C0%5D%0A%5B9%2C8%2C7%2C6%2C5%2C4%2C3%2C2%2C0%2C1%5D%0A%5B3%2C1%2C4%2C1%2C5%2C9%2C2%2C6%2C9%5D%0A%5B-1%2C-1%2C-1%2C-2%5D&debug=0). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 41 bytes ``` itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx ``` The output is `1` or `0`. ### Explanation ``` i % get input array tn2\ % is size odd? ? % if that's the case YNh % concat NaN at the end ] % end if tn % get size of input array t1+: % vector 1:n+1, where n is input size, so loop will be entered even with [] " % for loop x[]2e!PY) % delete result from previous iteration and do the shuffling ttZN~) % remove NaN, if there's any tS=A % check if array is sorted t. % copy the result. If true, break loop ] % end for wx % remove unwanted intermediate result ``` ### Example ``` >> matl itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx > [1,1,2,3,5,8,13,21] 1 ``` ]
[Question] [ **Background:** MtDNA is a part of the human DNA that is passed from a mother to a child and it rarely mutates. Since this is true for all humans it is possible to create a huge tree that visualize how all humans are related to each other through their maternal ancestry all the way back to the hypothetical EVE. Every mutation in the MtDNA when a child is born creates a new sub-branch from its parent branch in the tree. Find out more about Mitochondrial DNA (mtDNA) here: <https://en.wikipedia.org/wiki/Mitochondrial_DNA> **Objective:** > > Your program is served a list of mtDNA tree branches mutation count and your program should deliver a tree view of it > > > **Example input and output:** The input is a 3-column semi-colon separated table with a line for each branch. Example: ``` L0a'b'f'k;L0;14 L0a'b'f;L0a'b'f'k;23 L0;mtEVE;10 L0a'b;L0a'b'f;30 L0a;L0a'b;38 L0a1'4;L0a;39 L0a1;L0a1'4;40 L0a1a;L0a1;42 L0a1a NL;L0a1a;43 L0a1a1;L0a1a NL;44 L0a1a2;L0a1a NL;45 L0a1a3;L0a1a NL;44 L0a1 NL;L0a1;41 L0a1b;L0a1 NL;44 L0a1b NL;L0a1b;45 L0a1b1;L0a1b NL;46 L0a1b1a;L0a1b1;47 L0a1b1a1;L0a1b1a;48 L0a1b2;L0a1b NL;48 L0a1b2a;L0a1b2;50 L0a1c;L0a1 NL;45 L0a1d;L0a1 NL;44 L0a4;L0a1'4;55 L0a2;L0a;47 L0a2a;L0a2;49 L0a2a1;L0a2a;50 L0a2a1a;L0a2a1;51 L0a2a1a1;L0a2a1a;53 L0a2a1a2;L0a2a1a;53 L0a2a2;L0a2a;53 L0a2a2a;L0a2a2;54 L0a2b;L0a2;57 L0a2b1;L0a2b;58 L0a2c;L0a2;60 L0a2d;L0a2;49 L0a3;L0a;53 L0b;L0a'b;48 L0f;L0a'b'f;37 L0f1;L0f;61 L0f2;L0f;41 L0f2a;L0f2;46 L0f2a1;L0f2a;59 L0f2b;L0f2;63 L0k;L0a'b'f'k;39 L0k1;L0k;48 L0k2;L0k;54 L0d;L0;21 L0d1'2;L0d;25 L0d1;L0d1'2;30 L0d1 NL;L0d1;31 L0d1a;L0d1 NL;38 L0d1a1;L0d1a;41 L0d1c;L0d1 NL;39 L0d1c1;L0d1c;45 L0d1c1a;L0d1c1;46 L0d1c1b;L0d1c1;46 L0d1b;L0d1 NL;36 L0d1b1;L0d1b;40 L0d2;L0d1'2;31 L0d2a'b;L0d2;32 L0d2a;L0d2a'b;42 L0d2a1;L0d2a;43 L0d2b;L0d2a'b;46 L0d2c;L0d2;45 L0d3;L0d;39 ``` Your program should output a left-to-right tree view including some numbers based on the input. Based on the example input, this is valid output: ``` 0│ ┐ mtEVE [ 0][ 63] 10│ └♦♦♦♦♦♦♦♦♦┬────────────────┬─────────────────────────────────── L0 [ 10][ 63] 21│ │ └♦♦♦♦♦♦♦♦♦♦┬──────┬───────────────── L0d [ 11][ 46] 39│ │ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d3 [ 18][ 39] 25│ │ └♦♦♦┐ L0d1'2 [ 4][ 46] 30│ │ ├♦♦♦♦┬─────────────── L0d1 [ 5][ 46] 31│ │ │ └┬────┬┐ L0d1 NL [ 1][ 46] 36│ │ │ │ │└♦♦♦♦┬─── L0d1b [ 5][ 40] 40│ │ │ │ │ └♦♦♦ L0d1b1 [ 4][ 40] 38│ │ │ │ └♦♦♦♦♦♦┬── L0d1a [ 7][ 41] 41│ │ │ │ └♦♦ L0d1a1 [ 3][ 41] 39│ │ │ └♦♦♦♦♦♦♦┬────── L0d1c [ 8][ 46] 45│ │ │ └♦♦♦♦♦┬ L0d1c1 [ 6][ 46] 46│ │ │ ├ L0d1c1a [ 1][ 46] 46│ │ │ └ L0d1c1b [ 1][ 46] 31│ │ └♦♦♦♦♦┬┬───────────── L0d2 [ 6][ 46] 45│ │ │└♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d2c [ 14][ 45] 32│ │ └┬──┐ L0d2a'b [ 1][ 46] 42│ │ │ └♦♦♦♦♦♦♦♦♦┬ L0d2a [ 10][ 43] 43│ │ │ └ L0d2a1 [ 1][ 43] 46│ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦ L0d2b [ 14][ 46] 14│ └♦♦♦┬────────┐ L0a'b'f'k [ 4][ 63] 39│ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦┬─────┬──────── L0k [ 25][ 54] 48│ │ │ └♦♦♦♦♦♦♦♦ L0k1 [ 9][ 48] 54│ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0k2 [ 15][ 54] 23│ └♦♦♦♦♦♦♦♦┬──┐ L0a'b'f [ 9][ 63] 30│ │ └♦♦♦♦♦♦┬───────────┐ L0a'b [ 7][ 60] 48│ │ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0b [ 18][ 48] 38│ │ └♦♦♦♦♦♦♦┬────┬─┬────────────── L0a [ 8][ 60] 53│ │ │ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0a3 [ 15][ 53] 39│ │ │ └┬────┐ L0a1'4 [ 1][ 55] 40│ │ │ │ └┬────┬──── L0a1 [ 1][ 50] 42│ │ │ │ │ └♦┬── L0a1a [ 2][ 45] 43│ │ │ │ │ └┬┐ L0a1a NL [ 1][ 45] 44│ │ │ │ │ │├ L0a1a1 [ 1][ 44] 44│ │ │ │ │ │└ L0a1a3 [ 1][ 44] 45│ │ │ │ │ └♦ L0a1a2 [ 2][ 45] 41│ │ │ │ └┬────┬┐ L0a1 NL [ 1][ 50] 44│ │ │ │ │ │└♦♦ L0a1d [ 3][ 44] 45│ │ │ │ │ └♦♦♦ L0a1c [ 4][ 45] 44│ │ │ │ └♦♦┬───── L0a1b [ 3][ 50] 45│ │ │ │ └┬─┐ L0a1b NL [ 1][ 50] 46│ │ │ │ │ └┬─ L0a1b1 [ 1][ 48] 47│ │ │ │ │ └┬ L0a1b1a [ 1][ 48] 48│ │ │ │ │ └ L0a1b1a1 [ 1][ 48] 48│ │ │ │ └♦♦┬─ L0a1b2 [ 3][ 50] 50│ │ │ │ └♦ L0a1b2a [ 2][ 50] 55│ │ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0a4 [ 16][ 55] 47│ │ └♦♦♦♦♦♦♦♦┬─┬───┬────┬─ L0a2 [ 9][ 60] 49│ │ │ │ │ └♦ L0a2d [ 2][ 49] 49│ │ │ │ └♦┬┬─── L0a2a [ 2][ 54] 50│ │ │ │ │└┬── L0a2a1 [ 1][ 53] 51│ │ │ │ │ └┬─ L0a2a1a [ 1][ 53] 53│ │ │ │ │ ├♦ L0a2a1a1 [ 2][ 53] 53│ │ │ │ │ └♦ L0a2a1a2 [ 2][ 53] 53│ │ │ │ └♦♦♦┬ L0a2a2 [ 4][ 54] 54│ │ │ │ └ L0a2a2a [ 1][ 54] 57│ │ │ └♦♦♦♦♦♦♦♦♦┬ L0a2b [ 10][ 58] 58│ │ │ └ L0a2b1 [ 1][ 58] 60│ │ └♦♦♦♦♦♦♦♦♦♦♦♦ L0a2c [ 13][ 60] 37│ └♦♦♦♦♦♦♦♦♦♦♦♦♦┬─┬─────────────────────── L0f [ 14][ 63] 61│ │ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0f1 [ 24][ 61] 41│ └♦♦♦┬───┬───────────────── L0f2 [ 4][ 63] 46│ │ └♦♦♦♦┬──────────── L0f2a [ 5][ 59] 59│ │ └♦♦♦♦♦♦♦♦♦♦♦♦ L0f2a1 [ 13][ 59] 63│ └♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦♦ L0f2b [ 22][ 63] ``` **Input: Details** The input table is *not* sorted in any particular order. If we randomly reorder the input lines, the output should remain the same. Each line in the input represents a mtDNA tree branch or a hypothetical tree branch. The input table could be any number of lines in length. **Input: Details - Column A (branch name):** The first column is the actual branch name. The name divides the input lines into 2 groups of line types that should be handled different (explained later) from each other: * Type 1: Name consists of any `'` or the suffix `NL` * Type 2: Name doesn't consist of any `'` or the suffix `NL`. The name can be up to 20 characters in length. **Input: Details - Column B (parent branch name):** The second column contains a pointer to the parent branch name. Several lines (branches) can share the same parent. There is always exactly 1 distinct parent branch name in the input table that points to a parent that isn't represented among the input lines, that parent branch name is the root for the tree. In the example input that is the third line pointing to the root: `mtEVE`. If the input has more than one root, or endless loops, it is an invalid input. **Input: Details - Column C (# of mutations):** The third column is the total number of mutations that particular branch has had counting from the root. Human mtDNA hasn't mutated more than 100 times in a single line from the hypothetical maternal root (Human/chimp ancestor EVE), but your program should be able to handle 3 digit # of mutations, up to 999. From the input you can calculate a branch # of unique mutations by substracting its # of mutations from its parent # of mutations. **Output: Details** Your program should output 1 out of 3 different error messages if the input is invalid according to the input description. * Error message 1, if the input has more than one root: `ERROR: Multiple roots` * Error message 2, if the input parent pointers loops: `ERROR: Endless loop` * Error message 3, anything else invalid about the input: `ERROR: Invalid input` If the input contains no errors, your program should output the tree according to the following constraints: Each line consists of 5 parts A, B, C, D, and E: * A: 5 characters, 3 char right-aligned # of mutations, a vertical line character: `|` and 1 blankspace * B: [max # of mutations] characters wide tree + 1 blankspace * C: 20 characters, left-aligned branch name * D: 5 characters, 3 character right-aligned # of unique mutations for the branch encapsulated between `[` and `]`. (Unique mutations will be explained below). * E: 5 characters, 3 character right-aligned max # of total mutations for this branch and all child-branches encapsulated between `[` and `]`. A branch # of unique mutations is the difference in # of mutations the current branch has from the # of mutations its parent branch has. The first line is the root and it should be represented with `0` for # of mutations and # of unique mutations. **Output: Details - line order/sortation** If two or more sub-branches are sharing the same parent, the branches are ordered by the sub-branches maximum # of total mutations in descending order. In our example `L0a1'4`, `L0a3` and `L0a2` shares the parent: `L0a`. In the tree view the order from top to bottom is, sub-branches maximum # of total mutations within parenthesis: `L0a3` (53), `L0a1'4` (55), `L0a2` (60). If two or more sub-branches shares the same maximum # of mutations on child branches, they are vertically aligned and branched from their parent from the same spot, line ordering among those sub-branches is alphabetical. **Output: Details - tree (part B)** The tree should be drawn with the following ascii characters: `└`, `─`, `┬`, `┐`, `├`, `│`, `♦` The logic of the tree is that all mutations should be represented. A branch from a parent branch: `┬` or `┐` represents 1 mutation. Additional unique mutations on the same branch are represented by: `♦` and they must be left-aligned and placed before the first sub-branch. Sub-branches are branched from their parent along the x-axis and the position is determined by the maximum # of mutations among all subsequent child branches. As hinted before the input has 2 different type of input lines. Type 1 with any ' characters or the NL suffix in the branch name, should not fill the horizontal line to the far right on their line but end with a `┐` on the last sub-branch. In the example it is applied to the following branches: ``` L0a'b'f'k;L0;14 L0a'b'f;L0a'b'f'k;23 L0a'b;L0a'b'f;30 L0a1'4;L0a;39 L0a1a NL;L0a1a;43 L0a1 NL;L0a1;41 L0a1b NL;L0a1b;45 L0d1'2;L0d;25 L0d1 NL;L0d1;31 L0d2a'b;L0d2;32 ``` Hopefully the example input and output answers any additional questions about how the tree should be drawn, consider it part of the challenge to figure out the logic. **Inspiration** You are welcome to try out my (un-golfed) javascript version for inspiration: <http://artificial.se/DNA/mtDNAmutationTree3.html> (it lacks error checking, and some statistics is added that is not part of this particular challenge). A complete mtDNA-tree version [based on <http://www.phylotree.org/> mtDNA tree Build 16 (19 Feb 2014)] can be found here: <http://artificial.se/DNA/mtDNAfull.html> The data-file used for the full tree: <http://artificial.se/DNA/mtDNA_full.txt> This is a code-golf challenge. [Answer] # Python 3, 925 bytes Yay, under 1 KB! Probably still room for golfing... ``` import sys class L: def __init__(x,**k):x.__dict__.update(k) m={} def e(x):print('ERROR: '+x);exit() try: for x in sys.stdin:a,b,c=x.split(';');m[a]=L(s=a,p=b,m=int(c),l=0) except:e('Invalid input') a=set() def k(x): if x.l<0:e('Endless loop') if x.l<1:y=m.get(x.p);x.l=-1;k(y)if y else a.add(x.p);x.l=1 for x in m:k(m[x]) r=L(s=a.pop(),p=0,m=0) if a:e('Multiple roots') m[r.s]=r c={} def u(x): c[x.s]=[m[y]for y in m if m[y].p==x.s];x.x=x.m for y in c[x.s]:u(y);x.x=max(x.x,y.x) u(r) o=[] def f(p,x,o=o): d=x.m-p.m;j=p.m+r.x-x.x;s=x.s;x.i=len(o);l=sorted(c[s],key=lambda t:(t.x,t.s));q=' '*j+'└'+'♦'*(d-1);z='─' if"'"in s or s[-2:]=='NL'or x==r:q+=z*(x.x-l[0].x);z=' ' o+=list("%3d│ "%x.m+q+z*(r.x-len(q))+' %-20s[%3d][%3d]'%(s,d,x.x)),;j+=5;o[p.i][j]='┐┬'[o[p.i][j]in'─┬'] for i in range(p.i+1,x.i):o[i][j]='├│'[o[i][j]in' │'] for y in l:f(x,y) f(r,r) print('\n'.join(''.join(x)for x in o)) ``` ]
[Question] [ In Python, you can use the `dir` function on any object to get a list of the names of its instance functions: ``` >>> dir('abc') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__','__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] ``` I'm wondering if this could be a useful golfing technique in a program than calls several lengthily named functions. In such a case, I could create a function selection function `F`: ``` F=lambda o,i:eval('o.'+dir(o)[i]) ``` Now suppose I have a string `s` and I want store the result of capitalizing its first letter in the variable `c`. Then instead of `c=s.capitalize(),` I could note that `capitalize` is at position 33 in the above list and do the following: ``` s='abc' c=G(s,33)() ``` which assigns `'Abc'` to `c`. My question is whether this is likely to work most of the time. In particular, * Can I always count on the list being lexicographically sorted by ASCII values? * Are there many changes to list of available between minor versions? * Do differences exist between implementations? Also, has anyone used this before on PPCG? [Answer] From the [documentation](https://docs.python.org/2/library/functions.html#dir): > > The resulting list is sorted alphabetically > > > As for the differences, I think you will have to check (and specifying in your answer is probably a good idea). There are clear differences between python 2 and 3, for example, `__nonzero__` was renamed to `__bool__`. I have never heard of any differences between implementations, but I can't find any references on this. I don't think this has been used before in part because it will rarely save you any characters over doing something like: ``` F=str.capitalize s='abc' c=F(s) ``` You would need to use several different functions from `dir()` in order for this to be worth it. ]
[Question] [ # Background In a galaxy (and possibly a universe) far, far away... there was a spaceship and a bunch of planets. A malfunction on board caused the spaceship to run out of fuel. It is now moving at a dangerously slow speed near a cluster of planets, from which it must escape! What will be the crew's fate? # The Challenge You are the lead programmer on the U.S.S. StackExchange. As such, you desire to write a simulator that will reveal whether or not you are doomed to crash land onto a planet, will escape the planetary system, or will be stuck in orbit forever. The explosion on your spaceship, however, means that there was very limited computational resources. Your program must be as small as possible. Also, this means that the only possible way of inputting simulations to run is through ASCII art. # The Simulation In this quadrant of the multiverse, the laws of physics are slightly altered in order to accommodate ASCII art. This means that the cosmos is divided up into cells. Movement will be described in units of cells, and time will be in units of time steps. The ship itself has momentum. If the ship moved +2 cells on the x axis and -1 cell on the y axis (shorthanded as (2,-1)) in the previous time step, and there is no gravitational field, then the ship will move with the exact same velocity on the next time step. There will be several planets, all of which exert a gravitational field on the eight cells immediately surrounding it, which will effect the ship's velocity and will pull the ship closer to the planet. Being just "north" of a planet will result in a field pulling the ship one cell to the "south" with a force of (-1,0). Being just "northeast" of a planet will result in a force pulling the ship one cell to the "south" and one unit to the "west" with a force of (-1,-1). The gravitational fields add a vector to the ship's momentum as it is leaving the cell with the gravity. If a ship just previously moved (2,-1) cells and is now in a gravitational field of (-1,1), then in this next time step it will move (1,0) cells. If the ship is in close proximity to multiple planets, then there will be multiple vectors to add. # Input On STDIN, you will receive an ASCII art representation of the planetary system that will show the coordinates of the planets and your ship's current velocity. There will be several planets in the form of @ signs, while there will be one spaceship in the form of a v^<> sign. The choice of symbol for the ship indicates the current velocity of the ship (before gravity has been added). For example, a < means a velocity of one cell to the west, while a ^ means a velocity of one cell to the north. All empty space will consist of periods, which pad every line to be the same width. A blank line represents the end of input. Here is an example of an input: ``` ................. ...@[[email protected]](/cdn-cgi/l/email-protection).. ......@..@..@@... ..@.............. .......@..@...... ................. ``` # Output Output will be a single word on STDOUT, which will tell whether the ship will escape gravity, will crash land into a planet, or will orbit forever. Escaping from gravity is defined as the ship moving off of the map. If the ship escapes, then your program must print the word "escape". Crash landing is when a ship passes directly over a planet or ends up in the same cell during a time step. Note that it is not enough to simply calculate where the ship is every time step. A ship moving at a velocity of (5,5) will crash into a planet located at (1,1) even though straightforward calculation will mean that it will never visit that cell. A ship with a velocity of (5,6) will not crash land into the planet, however. If your spaceship crash lands, then your program must print the word "crash". Orbiting may be the most difficult to detect. Orbiting occurs whenever the spaceship visits the same cell twiceand with the same velocity. If the ship orbits, then you should print the word "orbit". Here is the output for the above example: ``` escape ``` ## Explanation Here is a map showing where the spaceship traveled in each time step in the above example: ``` ^ ................. ...@[[email protected]](/cdn-cgi/l/email-protection).. ....^.@..@..@@... ..@..<.<<<.<.v... .......@..@...... ................. ``` It went south, turned to the west, travelled down a corridor, turned to the north, and narrowly escaped between to planets with a high velocity, all becuase of gravity. --- # More cases for examination ``` ... ^@. ... orbit ........... .>@.@...... .@......@.. ....@...... crash (it crashes into the easternmost planet) ... .@. .v. crash (momentum can't overcome gravity) ........ ..@..... ..<..... ...@.... ........ orbit (it gets trapped in a gravity well between two planets) ``` --- # Rules, Regulations, and Notes This is code golf. Standard code golf rules apply. Your programs must be written in printable ASCII. You aren't allowed to access any sort of external database. End Transmission [Answer] ## C# ~~991~~ 984 ``` struct P{public P(int x,int y){X=x;Y=y;}public int X,Y;} class O:Exception{} class C:O{} List<P>p=new List<P>(); List<string>h=new List<string>(); P r,v,u; void S(){ var i=0; for(var l=Console.ReadLine();l!="";l=Console.ReadLine()) {u.X=l.Select((c,j)=> {if(c=='@')p.Add(new P(j,i));else if(c!='.') {r=new P(j,i);v=(c=='v'?new P(0,1):c=='<'?new P(-1,0):c=='^'?new P(0,-1):new P(1,0));} return u;}).Count();i++;} u.Y=i; var x=new Action<string>(Console.WriteLine); try{ while(true){ p.ForEach(q=>{var a=q.X-r.X;var b=q.Y-r.Y; if(a<2&&a>-2&&b<2&&b>-2){v.X+=a;v.Y+=b;}}); var c=string.Join(".",r.X,r.Y,v.X,v.Y); if(h.Contains(c))throw new O(); h.Add(c); var z=new P(r.X,r.Y);var k=new[]{v.X,v.Y};var m=k.Min();var M=k.Max(); for(var j=1;j<=M;j++) if((j*m)%M==0){ if(p.Contains(new P(z.X+(v.X==M?j:j*m/M),z.Y+(v.Y==M?j:j*m/M))))throw new C();} r.X+=v.X;r.Y+=v.Y; if(r.X<0||r.X>=u.X||r.Y<0||r.Y>=u.Y)throw new Exception();}} catch(C){x("crush");} catch(O){x("orbit");} catch{x("escape");}} ``` The ungolfed (and slightly refactored) version is available at <http://pastebin.com/yAKYvwQf> Running version: <https://compilify.net/1n9> This has been slightly modified to be run on complify: * no implicit array creation - ex: `new[]{1,2}` * uses `return <string>` instead of `Console.WriteLine`, because that's how compilify.net works ]
[Question] [ The 8 Puzzle is the smaller variant of the 15Puzzle (or the [Sliding puzzle](http://en.wikipedia.org/wiki/Fifteen_puzzle)). You have a `3x3` grid which is filled with numbers from 0-8 (0 denotes the blank tile) arranged in a random order. Your task is to input a 3x3 grid and show the shortest solution (minimum moves) to get to the goal state. Display each boardstate including the first state in the output. There may be multiple optimal solutions, you just need to print one. Input: (small example) ``` 1 2 0 4 5 3 7 8 6 ``` Output: ``` 2 <- denotes minimum number of moves required 1 2 0 4 5 3 7 8 6 1 2 3 4 5 0 7 8 6 1 2 3 4 5 6 7 8 0 <- goal state ``` If the puzzle can't be solved, print just `-1` (denoting unsolvable) **Edit**: Time limit : < 30seconds. [Answer] ## Python, 418 characters The code exhaustively enumerates all positions and makes maps of their depth (D), and a position one closer to solved (E). Then it looks up the goal state to get the output. ``` D={(1,2,3,4,5,6,7,8,0):0} E=D.copy() def Z(a,d): b=list(a);b[i],b[i+d]=b[i+d],0;b=tuple(b) if b not in E:E[b]=a;D[b]=D[a]+1 for x in' '*32: for a in E.copy(): i=list(a).index(0) if i>2:Z(a,-3) if i%3:Z(a,-1) if i%3<2:Z(a,1) if i<6:Z(a,3) g=[] for x in' '*3:g+=map(int,raw_input().split()) g=tuple(g) if g in E: print D[g] while g: for i in(0,3,6):print'%d %d %d'%g[i:i+3] g=E[g];print else:print -1 ``` ]
[Question] [ Recamán's sequence ([A005132](http://oeis.org/A005132)) is a mathematical sequence, defined as such: $$A(n) = \begin{cases}0 & \textrm{if } n = 0 \\ A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\ % Seems more readable than %A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\ A(n-1) + n & \textrm{otherwise} \end{cases}$$ An alternative, simpler verbal explanation is as follows: > > Subtract unless you can't (the number is negative, or has been used before), in which case add. > > > The first few terms are \$0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11\$ Now, there is already [this challenge](https://codegolf.stackexchange.com/questions/37635/generaterecam%C3%A1ns-sequence) which asks you to generate the `n`th term of the sequence. This one is slightly different. # Challenge Given a number `n`, draw the first `n` terms of the sequence. What do I mean by 'draw'? Let me demonstrate: 1. Draw a number line `max([A(y) for y<=n])` units long. We'll assume `n` is 5, for now, so the number line is 6 units long (since the largest of \$A(1) = 0\$, \$A(2) = 1\$, \$A(3) = 3\$, \$A(4) = 6\$ and \$A(5) = 2\$ is \$6\$). Make the line from underscores, starting at 0: `______` 2. Start with the transition between the first and second terms: that is, 0 and 1. Use `|` and `-` to draw a *square* (equal length and height), going upwards. In this case, we'll have to miss out the `-` because the distance is only 1. ``` || ______ ``` 3. Now, we'll draw on the next step (\$A(2) = 1\$ to \$A(3) = 3\$) on the bottom of the line (we alternate between up and down each time): ``` || ______ | | |-| ``` As you can see, this line also has a height of 2, since the height must be equal to the distance between the two terms. If we continue, we will eventually get to: ``` |--| | | || | | ______ ||| | ||| | | | |---| ``` # Rules * If there is a `-` and `|` colliding, the later one takes priority. * There may be preceeding/trailing **spaces** before/after the image, but trailing/preceeding `_`s or `-`s are not allowed (exception is 0- or 1- indexing) * You can choose to set the 0 point just before the first `_` on the number line, or just after it. * No alternative characters for `-`, `|` or `_` may be used. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. # Test case Here is another test case, with `n=10` ``` |-------| ||-----|| || || |----| || || | | || || ||--|| || || || || || || |||| || || || _____________________ ||| || ||| || ||| || ||| || | || ||| || |---|| ||| || | ||| || |---||| || ||------|| |--------| ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~70~~ 65 bytes ``` µ_ż+ɗLṪ>Ƈ-ḟ⁸Ḣṭµ¡µL;ⱮṀ’ṭr,;ɗƝJW,RN¹ƭƲ€$+Lp""ƲZẎ€Ʋ‘ŒṬ×"J$»/ị“-|_ ”Y ``` [Try it online!](https://tio.run/##AX8AgP9qZWxsef//wrVfxbwryZdM4bmqPsaHLeG4n@KBuOG4ouG5rcK1wqHCtUw74rGu4bmA4oCZ4bmtciw7yZfGnUpXLFJOwrnGrcay4oKsJCtMcCIixrJa4bqO4oKsxrLigJjFkuG5rMOXIkokwrsv4buL4oCcLXxfIOKAnVn//zEw "Jelly – Try It Online") A full program taking a single integer \$n\$ via STDIN and outputting the ASCII art based on zero-indexing. ]
[Question] [ Lets define a non-empty, unsorted and finite matrix with unique numbers as follow: $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$ Lets define 4 matrix moves as: * ↑\* (up): Moves a column up * ↓\* (down): Moves a column down * →\* (right): Moves a row to the right * ←\* (left): Moves a row to the left The asterisk(\*) represents the column/row that is affected by the move (It can be 0-indexed or 1-indexed. Up to you. Please state which one in your answer). --- **The challenge** is, using above moves, sort the matrix in a ascendant order (being the top left corner the lowest and the bottom right corner the highest). **Example** Input: $$N=\begin{Bmatrix}4&2&3\\1&5&6 \end{Bmatrix}$$ Possible Output: `↑0` or `↓0`. (Notice any of those moves can sort the matrix so both answer are correct) --- Input: $$N=\begin{Bmatrix}2&3&1\\4&5&6 \end{Bmatrix}$$ Possible Output: `→0` --- Input (Example test case): $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$ Possible Output: `↑0↑1←1↑2` --- Input: $$N = \begin{Bmatrix} 5&9&6\\ 8&2&4\\ 1&7&3 \end{Bmatrix}$$ Possible Output: `↑0↑2→0→2↑0→2↑1↑2←1` --- Input: $$N = \begin{Bmatrix} 1 & 27 & 28 & 29 & 6 \\10 & 2 & 3 & 4 & 5 \\17 & 7 & 8 & 13 & 9 \\15 & 11 & 12 & 18 & 14 \\26 & 16 & 21 & 19 & 20 \\30 & 22 & 23 & 24 & 25 \end{Bmatrix}$$ Possible Output: `↑2↑1←3→0←3↓0←0←2→3↑3↑4` --- Input: $$N = \begin{Bmatrix} 1 \end{Bmatrix} $$ Output: or any move --- Input: $$N = \begin{Bmatrix} 1&2\\3&4 \end{Bmatrix} $$ Output: --- **Notes** * There can be different correct outputs (there don't need to be necessarily the same as the test cases or the shortest one) * You can assume it will be always a way to order the matrix * Edges connects (like pacman :v) * There wont be a matrix with more than 9 columns or/and rows * Assume matrix contains only positive non-zero unique integers * You can use any 4 distinct values other than numbers to represent the moves (in case of that, please state that in your answer) * Column/row can be 0 or 1 indexed * Winning criteria [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") --- Extra test cases are always welcome [Answer] # JavaScript (ES6), ~~226~~ 219 bytes Brute force search, using *right* (`"R"`) and *down* (`"D"`) moves. Returns either a string describing the moves, or an empty array if the input matrix is already sorted. Columns and rows in the output are 0-indexed. ``` f=(m,M=2)=>(g=(s,m)=>m[S='some'](p=r=>r[S](x=>p>(p=x)))?!s[M]&&m[0][S]((_,x,a)=>g(s+'D'+x,m.map(([...r],y)=>(r[x]=(m[y+1]||a)[x])&&r)))|m[S]((_,y)=>g(s+'R'+y,m.map(([...r])=>y--?r:[r.pop(),...r]))):o=s)([],m)?o:f(m,M+2) ``` [Try it online!](https://tio.run/##lY9Na8MwDIbv/RXdJZGJapaPrlvByWWnQTdYjsaM0DWho66DXUYM/e@Z3K6HndbeLEvP80pfzXfj1nbbH2Z787kZx1aAxpXImCihE@BQ00vLWsTO6E2soBdWlFbWCgZR9iXVA2OsunNypaJIy3sVevCBAzaEduCS@DlOBtRcNz2A5JxbhT4EWDkoypM@SdXx2DAqWRRZ8h31r8VfHO9x4v86qONns8oupeW96YHh@ZuxpRGOgVS0fGWWbbgoydi4Nntndhu@Mx281G@v3B3sdt9tWw8tyMl0KgvMMFcYninO8UFNgm7yP0gYpmewuAkM04tLYn4DOMcnmj6Bj7R1cXEs6IBrHen1k5idA3JKOkHjDw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = // f = main recursive function taking: (m, M = 2) => ( // m[] = input matrix; M = maximum length of the solution g = // g = recursive solver taking: (s, m) => // s = solution, m[] = current matrix m[S = 'some'](p = // we first test whether m[] is sorted r => // by iterating on each row r[S](x => // and each column p > (p = x) // and comparing each cell x with the previous cell p ) // ) ? // if the matrix is not sorted: !s[M] && // if we haven't reached the maximum length: m[0][S]((_, x, a) => // try all 'down' moves: g( // do a recursive call: s + 'D' + x, // append the move to s m.map(([...r], y) => // for each row r[] at position y: (r[x] = // rotate the column x by replacing r[x] with (m[y + 1] || a)[x] // m[y + 1][x] or a[x] for the last row (a = m[0]) ) && r // yield the updated row ))) | // m[S]((_, y) => // try all 'right' moves: g( // do a recursive call: s + 'R' + y, // append the move to s m.map(([...r]) => // for each row: y-- ? // if this is not the row we're looking for: r // leave it unchanged : // else: [r.pop(), ...r] // rotate it to the right ))) // : // else (the matrix is sorted): o = s // store the solution in o )([], m) ? // initial call to g(); if we have a solution: o // return it : // else: f(m, M + 2) // try again with a larger maximum length ``` [Answer] # ~~[Python 2](https://docs.python.org/2/), 296 277 245~~ [Python 3](https://docs.python.org/3/), ~~200~~ 194 bytes ``` from numpy import* def f(p): s='';u=[] while any(ediff1d(p)<0):u+=[(copy(p),s+f'v{v}',f':,{v}')for v in r_[:shape(p)[1]]]+[(p,s+'>0',0)];p,s,i=u.pop(0);exec(f'p[{i}]=roll(p[{i}],1)') return s ``` [Try it online!](https://tio.run/##VZDRbsMgDEWfm6/wm2H1prCmm5Qs/RGEpqoBBSkFRJJuUdVvz0grdS1PvpdzbUOYhta7zTyb6I/gxmOYwB6Dj8NL1mgDhgVeZtDXiNVYS5XBT2s7DXs3Md1YY0STiK@cl@O6luzgw5Q09WuDp/PpgmSwpKXgxkc4gXUQv2XZt/ugEyiFUmotWUgJ3OVIOVdVEmTr8S34wHJe6V99YAaDPNuLqqPvOnarSXDkGUQ9jNFBPy8TYpogpSwI3gk2ijK4HykItgQf6tGVcuEIxDNa/KMruLZbws9MSn0@MOJm32XaYJGLurLF9VKV2SpE6wYWSbumRnjdAfLq5iFLH8YiJ0wvm/8A "Python 3 – Try It Online") -19: unicode arrows weren't required... -32: slightly reworked, but much slower performance on average. -45: took some inspiration from @Arnauld's answer. Switched to Python 3 for `f''` (-4 bytes) -6: [`range( )`→`r_[: ]`](https://codegolf.stackexchange.com/a/156676/81203), `diff(ravel( ))`→`ediff1d( )` --- Exhaustively searches combinations of all possible `↓` moves and `→0`. Times out on the third test case. Since `→n` is equivalent to ``` ↓0↓1...↓*(c-1)* *... repeated r-n times* →0 ↓0↓1...↓*(c-1)* *... repeated n times* ``` where `r` and `c` are the numbers of rows and columns, these moves are sufficient to find every solution. --- ``` from numpy import* def f(p): s='' #s: sequence of moves, as string u=[] #u: queue of states to check while any(ediff1d(p)<0): #while p is not sorted u+=[(copy(p),s+f'v{v}',f':,{v}') #add p,↓v to queue for v in r_[:shape(p)[1]]] # for all 0<=v<#columns u+=[(p,s+'>0',0)] #add p,→0 p,s,i=u.pop(0) #get the first item of queue exec(f'p[{i}]=roll(p[{i}],1)') #transform it return s #return the moves taken ``` --- `>v` correspond respectively to `→↓`. (others undefined) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` ṙ€LXȮƊ¦1 ÇZÇZƊ⁾ULXȮOịØ.¤?F⁻Ṣ$$¿,“”Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8///hzpmPmtb4RJxYd6zr0DJDrsPtUUB0rOtR475QkKj/w93dh2foHVpi7/aocffDnYtUVA7t13nUMOdRw9yHO1f9//8/2lTHUscsVifaQsdIxyQWAA "Jelly – Try It Online") Full program. Outputs moves to STDOUT using L for left and R for right. Keeps trying random moves until the matrix is sorted, so not very efficient in terms of speed or algorithmic complexity. ]
[Question] [ # Introduction You have a friend that keeps asking you for loans and you are getting tired of it. Today, he came for a loan again. Instead of turning down his offer, you get a great idea: troll your friend by giving him as many coins/bills as possible. # Challenge You will take as input: the amount of money your friend wants a loan for and the amount of coins/bills you have. For this challenge, the possible denominations are $20.00, $10.00, $5.00, $2.00, $1.00, $0.25, $0.10, $0.05, and $0.01. An example of input is `5.67, [5, 3, 4, 5, 5, 9, 8, 1, 2]` if you friend wants $5.67 and you have 5 $20 bills, 3 $10 bills, etc. Your output will be the amount of coins/bills that gives your friend as much metal/paper/plastic as possible. If it is not possible to give your friend the exact amount of money he wants, give him the closest amount of money you can pay that is greater than what he wants. For example, if your friend wants $0.07 but you only have `[0, 0, 0, 0, 0, 2, 4, 2, 0]`, give him 2 $0.05 coins (not 1 $0.10 because that wouldn't be giving him as many coins as possible!). If your friend wants more money than you have, give him all your money (and pray you won't need to buy anything). # Test cases ``` Input: 6.54, [9, 8, 7, 6, 5, 4, 3, 2, 4] Output: [0, 0, 0, 1, 4, 1, 2, 1, 4] Input: 2, [0, 1, 0, 0, 0, 0, 0, 0, 0] Output: [0, 1, 0, 0, 0, 0, 0, 0, 0] Input: 9999, [0, 0, 0, 0, 0, 0, 0, 0, 1] Output: [0, 0, 0, 0, 0, 0, 0, 0, 1] Input: 0, [99, 99, 99, 99, 99, 99, 99, 99, 99] Output: [0, 0, 0, 0, 0, 0, 0, 0, 0] ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. [Answer] # [Clean](https://clean.cs.ru.nl), 167 bytes ``` import StdEnv @n l#m=[p\\p<-[[if(y==u)(x-1)x\\x<-l&y<-[0..]]\\u<-[0..]&v<-l|v>0]|sum[a*b\\a<-[2000,1000,500,200,100,25,10,5,1]&b<-p]>=toInt(n*100.0)] |m>[]= @n(hd m)=l ``` Defines the function `@`, taking `Real` and `[Int]`. [Try it online!](https://tio.run/##LY7BboMwEETv@YqVKiGIFuTQkDYSRjm0h0i95Wj74EDSItkGBYNA4tvrbtUednZm3mVqc9Mu2K4ZzQ2sbl1obd89PFx88@6mzcmBebJc9FL2ZSpEe48XzsckntNdMks5l6mJFiIsy5SScvy30URgnSqm1mG0Qm@vUmpiOWMMd79S0OV/AfOCHpKo6Fqmvaq4787Ox25LNGOJ2qy2EorDycVfDdiEm3DxmmZSBYes2IM4IrwivCAcEAqEPcIzQk5Ghe/6bvTnENLzR3hbnLZtPfwA "Clean – Try It Online") [Answer] # JavaScript, 213 Bytes ``` x=>y=>(F=(x,y,z,u=9)=>u--?[...Array(y[0]+1)].map((_,i)=>F(x-i*[1,5,10,25,100,200,500,1e3,2e3][u],y.slice(1),[...z,i],u))&&G:x>0||G.push([z,x-1/eval(z.join`+1+`)]),F(x*100,y,G=[]).sort((a,b)=>b[1]-a[1])[0]||[y])[0] ``` It's pretty slow and cost memory, so only try small cases [Answer] # [Kotlin](https://kotlinlang.org), 298 bytes ``` {t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value} val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01) ``` ## Beautified ``` { t, c -> with(c.fold(listOf(listOf<Int>())) { o, x -> o.flatMap { a -> (0..x).map { a + it } } /* Get all of the options. */ }.groupBy { it.zip(C).map { (a, b) -> a * b }.sum() } .mapValues { (_,b)->b.maxBy { it.sum() }!! } .toSortedMap().asSequence()) { firstOrNull { it.key == t } ?: firstOrNull { it.key > t } ?: last() }.value } val C = listOf(20.0, 10.0, 5.0, 2.0, 1.0, 0.25, .1, .05, .01) ``` ## Test ``` val calc: (target: Double, coins: List<Int>) -> List<Int> = {t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value} val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01) data class Test(val target: Double, val input: List<Int>, val output: List<Int>) val tests = listOf( Test(2.0, listOf(0, 1, 0, 0, 0, 0, 0, 0, 0), listOf(0, 1, 0, 0, 0, 0, 0, 0, 0)), Test(9999.0, listOf(0, 0, 0, 0, 0, 0, 0, 0, 1), listOf(0, 0, 0, 0, 0, 0, 0, 0, 1)), Test(6.54, listOf(9, 8, 7, 6, 5, 4, 3, 2, 4), listOf(0, 0, 0, 1, 4, 1, 2, 1, 4)), Test(0.0, listOf(99, 99, 99, 99, 99, 99, 99, 99, 99), listOf(0, 0, 0, 0, 0, 0, 0, 0, 0)) ) fun main(args: Array<String>) { for (t in tests) { if (t.output != calc(t.target, t.input)) { throw AssertionError() } else { println("Passed") } } } ``` **Example 4 causes OutOfMemory, but the other 3 work well.** ]
[Question] [ ## Introduction Sharp edges are, frankly, just plain dangerous so, given a PNG as input, blur the image using the method described below and blunt those damned sharp edges. ## Method To get the RGB value of each pixel, use the following three equations: $$R = \sqrt{\frac{1.5\times\sum^n\_{a=1}R^2\_a}{n}}$$ $$G = \sqrt{\frac{1.5\times\sum^n\_{a=1}G^2\_a}{n}}$$ $$B = \sqrt{\frac{1.5\times\sum^n\_{a=1}B^2\_a}{n}}$$ Where \$\sum^n\_{a=1}R^2\_a\$ is the sum of the red values of each of the adjacent pixels squared. The value of \$n\$ is the number of adjacent pixels (e.g., a corner pixel will have an \$n\$ value of 3, whilst a pixel around the center of the image will have an \$n\$ value of 8). An adjacent pixel is a pixel which is 1 pixel away from the original pixel in all directions (left, right, up, down and on all of the diagonals). ![](https://i.stack.imgur.com/R971E.png) For example, in the following 3 x 1 image: ![](https://i.stack.imgur.com/M2QI5.jpg) The blurred RGB value of the middle pixel will be: $$R = \sqrt{\frac{1.5\*(0^2+0^2)}{2}} = 0$$ $$G = \sqrt{\frac{1.5\*(0^2+255^2)}{2}} = 220.836 = 221$$ $$B = \sqrt{\frac{1.5\*(255^2+0^2)}{2}} = 220.836 = 221$$ where any decimal outputs are rounded to the nearest unit. You should not simply floor the result. Therefore, the middle pixel will be the colour (0, 221, 221), or: ![](https://i.stack.imgur.com/ndh2b.png) Resulting in the image: [![](https://i.stack.imgur.com/UgsEO.jpg)](https://i.stack.imgur.com/UgsEO.jpg) You should repeat this process for every pixel in the image. (Note that you do this with the original pixels and not the modified pixels. Basically, **you shouldn't overwrite the original image, and should keep it completely separate from the new, blurred image**). If you calculate any values to be greater than 255, assume that its value is 255 (I.e., a value of 374 would be set to 255). The resulting output should be a separate PNG image (you may name this whatever you wish). ## Examples ### Super Mario **Original:** [![](https://i.stack.imgur.com/6XCHW.png)](https://i.stack.imgur.com/6XCHW.png) **Blurred:** [![](https://i.stack.imgur.com/Kgmez.png)](https://i.stack.imgur.com/Kgmez.png) ### Checkerboard **Original:** [![](https://i.stack.imgur.com/W9Ro4.png)](https://i.stack.imgur.com/W9Ro4.png) **Blurred:** [![](https://i.stack.imgur.com/1p9Pq.png)](https://i.stack.imgur.com/1p9Pq.png) ### Crisps **Original** [![](https://i.stack.imgur.com/hJ0Qd.png)](https://i.stack.imgur.com/hJ0Qd.png) **Blurred** [![](https://i.stack.imgur.com/gqywH.png)](https://i.stack.imgur.com/gqywH.png) Not so crisp anymore ### American Gothic **Original:** ![](https://i.stack.imgur.com/ugBuo.png) **Blurred:** ![](https://i.stack.imgur.com/EJIGc.png) To see the blur on larger images, it's best to run the program again on the blurred image: ![](https://i.stack.imgur.com/cqDw7.png) ## Challenge The shortest code to blur a given PNG image wins. You can use image processing libraries (such as PIL) but you must not use built-in blurring functions (Mathematica, I'm looking at you). ## Note As @orlp says below: > > For the record, (to my knowledge) this is not a standard blurring method. This challenge is not an educational resource. > > > [Answer] # Python, ~~354~~ 313 bytes Not the best, but hey... Using Space for 1st level indentation, Tab for 2nd level, then Tab+Space and Tab+Tab ``` import Image as I A=I.open(raw_input()) w,h=A.size B=I.new('RGB',(w,h)) s=[-1,1,0] r=range for x in r(w): for y in r(h): P=[] for d in s: for e in s: try:P+=[A.load()[x+e,y+d]] except:0 P.pop() B.load()[x,y]=tuple(min(int(.5+(1.5*sum([v*v for v in t])/len(P))**.5),255)for t in zip(*P)) B.save("b.jpg") ``` * Edit1: replacing `math.sqrt()` with `()**.5` thanks to beta decay * Edit2: using `min` for clamping (saving a lot!) and `0` for `pass` thanks to Loovjo * Edit3: `+=[]` for `.append()` saving 5 bytes * Edit4: using the variable `s` for the stencil [Answer] # MATLAB, 130 bytes Takes an image as an input and saves the output as `b.png`. ``` i=double(input(''));m=ones(3);m(5)=0;k=@(x)imfilter(x,m);imwrite(uint8(round((1.5*k(double(i.^2))./k(i(:,:,1)*0+1)).^.5)),'b.png') ``` ]
[Question] [ Given a black-and-white image in any [reasonable lossless format](http://meta.codegolf.stackexchange.com/q/9093/45941) as input, output ASCII art that is as close to the input image as possible. ## Rules * Only linefeeds and ASCII bytes 32-127 may be used. * The input image will be cropped so that there is no extraneous whitespace surrounding the image. * Submissions must be able to complete the entire scoring corpus in under 5 minutes. * Only raw text is acceptable; no rich text formats. * The font used in the scoring is 20-pt [Linux Libertine](https://sourceforge.net/projects/linuxlibertine/files/linuxlibertine/5.3.0/). * The output text file, when converted to an image as described below, must be the same dimensions as the input image, within 30 pixels in either dimension. ## Scoring These images will be used for scoring: [![](https://i.stack.imgur.com/HrRM6.png)](https://i.stack.imgur.com/HrRM6.png) [![](https://i.stack.imgur.com/7sZJ9.png)](https://i.stack.imgur.com/7sZJ9.png) [![](https://i.stack.imgur.com/UtrAR.png)](https://i.stack.imgur.com/UtrAR.png) [![](https://i.stack.imgur.com/B5QGr.png)](https://i.stack.imgur.com/B5QGr.png) [![](https://i.stack.imgur.com/DIU78.png)](https://i.stack.imgur.com/DIU78.png) [![](https://i.stack.imgur.com/xFDMh.png)](https://i.stack.imgur.com/xFDMh.png) [![](https://i.stack.imgur.com/zRcUP.png)](https://i.stack.imgur.com/zRcUP.png) [![](https://i.stack.imgur.com/HlirN.png)](https://i.stack.imgur.com/HlirN.png) You can download a zipfile of the images [here](https://imgur.com/a/cYO4P/zip). Submissions should not be optimized for this corpus; rather, they should work for any 8 black-and-white images of similar dimensions. I reserve the right to change the images in the corpus if I suspect submissions are being optimized for these specific images. The scoring will be performed via this script: ``` #!/usr/bin/env python from __future__ import print_function from __future__ import division # modified from http://stackoverflow.com/a/29775654/2508324 # requires Linux Libertine fonts - get them at https://sourceforge.net/projects/linuxlibertine/files/linuxlibertine/5.3.0/ # requires dssim - get it at https://github.com/pornel/dssim import PIL import PIL.Image import PIL.ImageFont import PIL.ImageOps import PIL.ImageDraw import pathlib import os import subprocess import sys PIXEL_ON = 0 # PIL color to use for "on" PIXEL_OFF = 255 # PIL color to use for "off" def dssim_score(src_path, image_path): out = subprocess.check_output(['dssim', src_path, image_path]) return float(out.split()[0]) def text_image(text_path): """Convert text file to a grayscale image with black characters on a white background. arguments: text_path - the content of this file will be converted to an image """ grayscale = 'L' # parse the file into lines with open(str(text_path)) as text_file: # can throw FileNotFoundError lines = tuple(l.rstrip() for l in text_file.readlines()) # choose a font (you can see more detail in my library on github) large_font = 20 # get better resolution with larger size if os.name == 'posix': font_path = '/usr/share/fonts/linux-libertine/LinLibertineO.otf' else: font_path = 'LinLibertine_DRah.ttf' try: font = PIL.ImageFont.truetype(font_path, size=large_font) except IOError: print('Could not use Libertine font, exiting...') exit() # make the background image based on the combination of font and lines pt2px = lambda pt: int(round(pt * 96.0 / 72)) # convert points to pixels max_width_line = max(lines, key=lambda s: font.getsize(s)[0]) # max height is adjusted down because it's too large visually for spacing test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' max_height = pt2px(font.getsize(test_string)[1]) max_width = pt2px(font.getsize(max_width_line)[0]) height = max_height * len(lines) # perfect or a little oversized width = int(round(max_width + 40)) # a little oversized image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF) draw = PIL.ImageDraw.Draw(image) # draw each line of text vertical_position = 5 horizontal_position = 5 line_spacing = int(round(max_height * 0.8)) # reduced spacing seems better for line in lines: draw.text((horizontal_position, vertical_position), line, fill=PIXEL_ON, font=font) vertical_position += line_spacing # crop the text c_box = PIL.ImageOps.invert(image).getbbox() image = image.crop(c_box) return image if __name__ == '__main__': compare_dir = pathlib.PurePath(sys.argv[1]) corpus_dir = pathlib.PurePath(sys.argv[2]) images = [] scores = [] for txtfile in os.listdir(str(compare_dir)): fname = pathlib.PurePath(sys.argv[1]).joinpath(txtfile) if fname.suffix != '.txt': continue imgpath = fname.with_suffix('.png') corpname = corpus_dir.joinpath(imgpath.name) img = text_image(str(fname)) corpimg = PIL.Image.open(str(corpname)) img = img.resize(corpimg.size, PIL.Image.LANCZOS) corpimg.close() img.save(str(imgpath), 'png') img.close() images.append(str(imgpath)) score = dssim_score(str(corpname), str(imgpath)) print('{}: {}'.format(corpname, score)) scores.append(score) print('Score: {}'.format(sum(scores)/len(scores))) ``` The scoring process: 1. Run the submission for each corpus image, outputting the results to `.txt` files with the same stem as the corpus file (done manually). 2. Convert each text file to a PNG image, using 20-point font, cropping out whitespace. 3. Resize the result image to the dimensions of the original image using Lanczos resampling. 4. Compare each text image with the original image using `dssim`. 5. Output the dssim score for each text file. 6. Output the average score. Structural Similarity (the metric by which `dssim` calculates scores) is a metric based on human vision and object identification in images. To put it plainly: if two images look similar to humans, they will (probably) have a low score from `dssim`. The winning submission will be the submission with the lowest average score. [related](https://codegolf.stackexchange.com/questions/49587/ascii-art-generation) [Answer] ## Java, score 0.57058675 This is actually my first time doing image manipulation so it's kind of awkward but I think it turned out OK. I couldn't get dssim to work on my machine, but I was able to make images using PIL. Interestingly, the font tells me in Java that each of the characters I'm using are width `6`. You can see that in my program `FontMetrics::charWidth` is `6` for all characters that I have used. The `{}` logo looks pretty decent in a monospace font. But for some reason the lines do not actually line up in the full text file. I blame ligatures. (And yes, I *should* be using the correct font.) In monospaced font: ``` . .,:ff:, ,:fff::,. ,ff .fIIIIIf, .:fIIIIIf.:f:. .,:III: ,ff:: ..,, ,,.. ,:fff, IIII., :IIf,f:,:fff:, .:fIIIIIII. .IIIIIIIf:. .,:fff:,ff IIf, ,.fIIIf,:ffff, ,IIIIIII:,,. .,,:IIIIIII. .:ffff:,IIII,:. ,III.::.,,,,,. IIIIII: ,IIIIII ,,,,,.,:,:IIf IIIII :ffIIf, IIIIII, .IIIIII :IIIf:,.IIIIf. ,II,fIf.:::,.. IIIIII, .IIIIII ..,:::,,If::II IIIIf. ,:fII: .IIIIII, .IIIIII. IIff:. :IIII: ::IIIIf:IIIf: . ,::fIIIIIII, ,fIIIIIIf::, ,ffIII,IIIIf,, :IIf::: .,fI: IIIIIIIII: :IIIIIIIIf If:, .::fIIf IIIIII, :IIIIf .,:IIIIIIf fIIIIII:,. ,IIIII. fIIIII: ,:IIIII ff:, f, IIIIII, .IIIIII f. .::f::IIIIf,. fIf::,, ,fIII IIIIII, .IIIIII :III: ,,:fII. fIIIIIIf, :IIIIf , IIIIII, .IIIIII ., ,IIIII. :fIIIIII, .:IIIIIII,ff, :II: IIIIIIf fIIIIII .fII. .:ff:IIIIIIf, :fffff:, IIIIIf , :IIIIIIIfff fffIIIIIII: .. IIIII: ::fffff, .fIIIIIIIf:, fIIII, ,IIf, ,:ffIIII. .IIIIff:, .:fII fIIII,.:ffIIIIIII: ,fIIIIIIIIIf:, ,IIIII: .,::, .,::, .IIIIII ::fIIIIIIIIf:. :fffffff, .fIIIII, .IIIIIf: ,:fIIII: IIIIII: :fffffff, .:fIIIIIIIIIIIIffffI: IIIIIIII. :IIIIIII: .fIffffIIIIIIIIIIII:, ,:fIIIIIIIIIIIf, .:fIIIII ,IIIIIf, :IIIIIIIIIIIff,. .:ffffffffIIIIIIIIIIIfff:. ,ffffIIIIIIIIIIIfffffff:, .,:ffIIIIIIIIIIIIIIIIf, .,,,,. .:fIIIIIIIIIIIIIIIIff:,. ....... .,,:fffff:.,:fffff:,. ....... ..,,:fffIIIIf:,. .,:fIIIIff::,,.. .IIIIIf:,. .,:fIIIII f, ,f ``` After running it through the image tool: [![{} logo](https://i.stack.imgur.com/zuDkt.png)](https://i.stack.imgur.com/zuDkt.png) Anyway, here's the actual code. ``` //package cad97; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; public final class AsciiArt { private static final Font LINUX_LIBERTINE = new Font("LinLibertine_DRah", Font.PLAIN, 20); private static final FontMetrics LL_METRICS = Toolkit.getDefaultToolkit().getFontMetrics(LINUX_LIBERTINE); // Toolkit::getFontMetrics is deprecated, but that's the only way to get FontMetrics without an explicit Graphics environment. // If there's a better way to get the widths of characters, please tell me. public static void main(String[] args) throws IOException { File jar = new java.io.File(AsciiArt.class.getProtectionDomain().getCodeSource().getLocation().getPath()); if (args.length != 1) { String jarName = jar.getName(); System.out.println("Usage: java -jar " + jarName + " file"); } else { File image = new File(args[0]); try (InputStream input = new FileInputStream(image)) { String art = createAsciiArt(ImageIO.read(input), LINUX_LIBERTINE, LL_METRICS); System.out.print(art); // If you want to save as a file, change this. } catch (FileNotFoundException fnfe) { System.out.println("Unable to find file " + image + "."); System.out.println("Please note that you need to pass the full file path."); } } } private static String createAsciiArt(BufferedImage image, Font font, FontMetrics metrics) { final int height = metrics.getHeight(); final Map<Character,Integer> width = new HashMap<>(); for (char c=32; c<127; c++) { width.put(c, metrics.charWidth(c)); } StringBuilder art = new StringBuilder(); for (int i=0; i<=image.getHeight(); i+=height) { final int tempHeight = Math.min(height, image.getHeight()-i); art.append(createAsciiLine(image.getSubimage(0, i, image.getWidth(), tempHeight), width)); } return art.toString(); } private static String createAsciiLine(BufferedImage image, Map<Character,Integer> charWidth) { if (image.getWidth()<6) return "\n"; /* I'm passing in the charWidth Map because I could use it, and probably a later revision if I come back to this will actually use non-6-pixel-wide characters. As is, I'm only using the 6-pixel-wide characters for simplicity. They are those in this set: { !,./:;I[\]ft|} */ assert charWidth.get(' ') == 6; assert charWidth.get('!') == 6; assert charWidth.get(',') == 6; assert charWidth.get('.') == 6; assert charWidth.get('/') == 6; assert charWidth.get(':') == 6; assert charWidth.get(';') == 6; assert charWidth.get('I') == 6; assert charWidth.get('[') == 6; assert charWidth.get('\\') == 6; assert charWidth.get(']') == 6; assert charWidth.get('f') == 6; assert charWidth.get('t') == 6; assert charWidth.get('|') == 6; // Measure whiteness of 6-pixel-wide sample Raster sample = image.getData(new Rectangle(6, image.getHeight())); int whiteCount = 0; for (int x=sample.getMinX(); x<sample.getMinX()+sample.getWidth(); x++) { for (int y=sample.getMinY(); y<sample.getMinY()+sample.getHeight(); y++) { int pixel = sample.getPixel(x, y, new int[1])[0]; whiteCount += pixel==1?0:1; } } char next; int area = sample.getWidth()*sample.getHeight(); if (whiteCount > area*0.9) { next = ' '; } else if (whiteCount > area*0.8) { next = '.'; } else if (whiteCount > area*0.65) { next = ','; } else if (whiteCount > area*0.5) { next = ':'; } else if (whiteCount > area*0.3) { next = 'f'; } else { next = 'I'; } return next + createAsciiLine(image.getSubimage(charWidth.get(','), 0, image.getWidth()-sample.getWidth(), image.getHeight()), charWidth); } } ``` Compile: * Make sure you have the [JDK](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) installed * Make sure that the JDK bin is on your PATH (for me it's `C:\Program Files\Java\jdk1.8.0_91\bin`) * Save the file as `AsciiArt.java` * `javac AsciiArt.java` * `jar cvfe WhateverNameYouWant.jar AsciiArt AsciiArt.class` Usage: `java -jar WhateverNameYouWant.jar C:\full\file\path.png`, prints to STDOUT REQUIRES the source file to be saved with 1-bit depth and the sample for a white pixel to be `1`. Scoring output: ``` corp/board.png: 0.6384 corp/Doppelspalt.png: 0.605746 corp/down.png: 1.012326 corp/img2.png: 0.528794 corp/pcgm.png: 0.243618 corp/peng.png: 0.440982 corp/phi.png: 0.929552 corp/text2image.png: 0.165276 Score: 0.57058675 ``` ]
[Question] [ Given the ASCII art of two vectors, find the resultant vector's magnitude and degree. --- ## Input This can be received via STDIN, read from a local file, or provided through a function call. Here is an example of a two vector input: ``` ^------> | | | x ``` This represents a change of 4 units north and 7 units east. Every input's starting point will be represented by an `x` (decimal `120`). * All vectors are horizontal or vertical lines. * Each vector has one of these four endpoints: `^v<>`, and is made up of either a dash (`-`, decimal 45) or a vertical bar (`|`, decimal 124). * Empty points on the plane are filled with spaces (, decimal 32). * The input may be a single `x`. * Adjacent vectors are always perpendicular to each other. * All vectors are tip-to-tail. --- ## Output This will be the displacement of the resulting point (distance from the starting point) and the degree to which it has moved, relative to the starting point. For the above input, the output should be `8.06` units and `60.3` degrees. Each should have exactly 3 significant figures. Here are a few examples of numbers with 3 significant digits: * 1.00 * 60.1 * 453 * 7.08 * 4.50 * 349 All unit measurements will be `<= 999`. --- These numbers should be output in the below format. This is using the numbers from above. ``` 8.06 units @ 60.3 degrees ``` This may be followed by a single trailing space or newline. --- If the input is a single `x`, with no displacement and hence no angle of displacement, the output should be either an empty line (a single newline character) or in the following format: ``` 0 units @ - degrees ``` If you're trying to qualify for the bonus, the direction should be `-` as well. --- In the case that bonuses 2, 3, or both are completed, the output should follow the below model and abide by the same restrictions as the above. ``` 8.06 units @ 60.3 degrees NE ``` --- Degrees should be measured according to the standard plane. ``` 90 135 | 45 \|/ 180 ---x---- 0 /|\ 225 | 315 270 ``` `0` degrees is east, `1 - 89` degrees is northeast, `90` is north, etc. --- ## Bonuses The following are worth a total of -50%. 1. Take a -10% bonus for each additional vector that can be handled. This bonus can be applied to up to 3 times. Vectors will never overlap or cross. 2. Take a -10% bonus if your output includes the cardinal direction of the angle (north, south, east, west). 3. Take a -10% bonus if your output includes the intermediate directions of the angle (northeast, northwest, southeast, southwest). --- ## Examples In: ``` x----> | v ``` Out: ``` 5.39 units @ 338 degrees ``` Optionally `SE` --- In: ``` <--------------^ | | x ``` Out: ``` 15.3 units @ 169 degrees ``` Optionally `NW` --- In: ``` x | |<-----^ | | v------> ``` Out: ``` 2.24 units @ 297 degrees ``` Optionally `SE` --- ## Examples (multiple vectors) In: ``` x---> | | v-----------> ``` Out: ``` 16.3 units @ 349 degrees ``` Optionally `SE` --- In: ``` <-------^ | | | | v | | | x ``` Out: ``` 8.54 units @ 159 degrees ``` Optionally `NW` --- In: ``` ^--> | | | v | <--------x ``` Out: ``` 6.32 units @ 162 degrees ``` Optionally `NW` [Answer] ## Python 2, 238.5 (~~594~~ ~~562~~ ~~482~~ 477-50%) bytes ``` from math import* def F(x):s='%.3g'%x;return[[s+'.',s]['.'in s].ljust(4,'0'),s][x>99] I=input() V=I.split('\n');N=len(V) l=max(len(x)for x in V) q=[' '*(l+2)];V=q+[' '+x.ljust(l+1)for x in V]+q for k in range(N*l): i,j=k/l,k%l;c=V[i+1][j+1] if c in'<>^v'and['|'not in zip(*V)[j+1][i:i+3],'-'not in V[i+1][j:j+3]][c>'?']:a,b=i,j if c=='x':A,B=i,j Y=A-a;X=b-B;a=atan2(Y,X)/pi*180%360 print[F(hypot(X,Y))+' units @ '+F(a)+' degrees '+' NS'[cmp(Y,0)]+' EW'[cmp(X,0)],''][I=='x'] ``` --- **Explanation** Finds the start and end positions by looking at each character in the input. Start is `x` End is found by looking at each arrow (`<>^v`), and their neighbors. If neighbors are continuing vectors, ignore. Else, this is the end. Look at the neighbors perpendicular to the arrow direction. If they contain a perpendicular line, then it is a continuing vector. Examples (`_` indicates space): ``` _#_ ->_ Neighbors marked by # _#_ ___ ->_ (end) ___ _|_ ->_ (not end) ___ ___ ->| (end) ___ --- ->_ (end) ___ ``` Because the end point is found, there can be any number of vectors (**30% bonus**). [Answer] # JavaScript (ES6), 305 bytes - 50% bonus = 152.5 score ``` v=>(l=v.search` `+1,s=v.search`x`,u=0,d="-",v.replace(/[<>v^]/g,(p,i)=>{c=o=>v[i+o]!=q;with(Math)if(p<"?"?c(l,q="|")&c(-l):c(1,q="-")&c(-1))d=(atan2(x=i%l-s%l,y=(i/l|0)-(s/l|0))*180/PI+270)%360,u=sqrt(x*x+y*y)}),u[p="toPrecision"](3)+` units @ ${d[p](3)} degrees`) ``` ## Explanation Input must be padded with spaces. Uses all bonuses. ``` v=>( l=v.search` `+1, // l = line length s=v.search`x`, // s = index of start point u=0, // u = units d= // d = degrees w="-", // w = cardinal direction v.replace(/[<>v^]/g,(p,i)=>{ // for each endpoint c=o=>v[i+o]!=q; // compares cell at offset to char with(Math) // save having to write "Math." if(p<"?"?c(l,q="|")&c(-l):c(1,q="-")&c(-1)) // check for line branching off d=(atan2( x=i%l-s%l, // x = relative x y=(i/l|0)-(s/l|0) // y = relative y )*180/PI+270)%360, // convert to degrees u=sqrt(x*x+y*y), w="N S"[sign(y)+1]+"W E"[sign(x)+1] // get cardinal direction }), u[p="toPrecision"](3)+` units @ ${d[p](3)} degrees `+w // format output ) ``` ## Test ``` var solution = v=>(l=v.search` `+1,s=v.search`x`,u=0,d=w="-",v.replace(/[<>v^]/g,(p,i)=>{c=o=>v[i+o]!=q;with(Math)if(p<"?"?c(l,q="|")&c(-l):c(1,q="-")&c(-1))d=(atan2(x=i%l-s%l,y=(i/l|0)-(s/l|0))*180/PI+270)%360,u=sqrt(x*x+y*y),w="N S"[sign(y)+1]+"W E"[sign(x)+1]}),u[p="toPrecision"](3)+` units @ ${d[p](3)} degrees `+w) ``` ``` <textarea id="input" rows="6" cols="60">x | |<-----^ | | v------></textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` ]
[Question] [ # The lost pawn problem After the chess game ended, a surviving pawn was left behind enemy lines. let's help him find the shortest way back home. The original problem describes a nXn "chess" board, and a function `f: {1,..,n-1}X{1,..,n}X{-1,0,1} => R+` of weights. the goal is to find the best path from some square in the buttom line, to some other square in the top line, where the possible moves are: left-up,up,right-up, and you may not exit the board. The problem is relatively easy to solve in O(n^2) using dynamic programming, but this is codegolf, and we don't care about useless stuff like running time complexity... ## The Problem **input:** a 3-dimentional array (or some other collection of your choice, received through stdin, or as a function argument), corresponding to a regular chess board, exactly in size: 7X8X3 (#linePasses X #rowSize X #movesPerPass) containing non-negative integers. the moves cost **from** some position `(i,j)` where `i` is the row index, and `j` is the column index, are: * `a[i][j][0]` for the cost to travel up-left to square `(i+1,j-1)`, or graphically: `\`. * `a[i][j][1]` for the cost to travel up to square `(i+1,j)`, or graphically: `|`. * `a[i][j][2]` for the cost to travel up-right to square `(i+1,j+1)`, or graphically: `/`. you may assume it will not contain a path that sums greater than `MAX_INT`. **output:** an 8X8 ascii output showing the best (shortest, i.e. minimum sum of weights) path (if there is more than 1 optimal result, you may show an arbitrary path of your choice). the path is drawn bottom to top, where in each line, the character corresponding to the pawn's position in the path, is the one it about to make. e.g. if the pawn is about to move up-left from column 3 (to column 2), the you should draw: ``` #?###### ##\##### ``` where `?` should be replaced with the next move. final position needs to be drawn as `X`. ### Examples *input:* ``` [ [[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]], [[1,1,1],[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]] ] ``` *output:* ``` ##X##### ###\#### ###|#### ###|#### ##/##### #/###### #|###### ##\##### ``` *input:* ``` [ [[41,27,38],[12,83,32],[50,53,35],[46,32,26],[55,89,82],[75,30,87],[2,11,64],[8,55,22]], [[56,21,0],[83,25,38],[43,75,63],[56,60,77],[68,55,89],[99,48,67],[94,30,9],[62,62,58]], [[23,18,40],[24,47,61],[96,45,72],[71,6,48],[75,63,98],[93,56,51],[23,31,30],[49,34,99]], [[20,47,42],[62,79,72],[32,28,44],[68,61,55],[62,39,57],[4,17,49],[97,85,6],[91,18,12]], [[51,50,11],[32,39,56],[12,82,23],[33,88,87],[60,55,22],[29,78,14],[70,11,42],[63,94,67]], [[75,64,60],[27,79,86],[70,72,56],[55,45,32],[95,67,12],[87,93,98],[81,36,53],[38,22,93]], [[31,80,50],[77,71,22],[59,46,86],[64,71,53],[41,19,95],[62,71,22],[92,80,41],[26,74,29]] ] ``` *output:* ``` ######X# #####/## ####/### #####\## #####|## ######\# ######|# #######\ ``` this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. play fair. no loopholes... ## EDIT: Iv'e written an un-golfed [straight forward solution in scala](https://gist.github.com/hochgi/dace773bb23b71727122) you can look at. There's also a site you can play with scala code on-line: [scalafiddle](https://scalafiddle.io) (just copy&paste the gist to scalafiddle, and hit the play button) [Answer] ## Q: 199 Bytes ``` f:{m::x;n::{@/[+/-1 0 1_\:/:(x;m[y;;|!3]);0 2;(0W,),{x,0W}]};i:*<*|r:{&/n[x;y]}\[8#0;!7]; s:{-1+{*<x}'+n[y;z]}\[();(,8#0),-1_r;!7];j:i,{x+y x}\[i;|s];-1(@[8#"#";;:;]'[j;"X","/|\\"1+s'[|!7;-1_j]]);} ``` **NOTES** * Q interpreter (kx.com) free for non-commertial use (versions for Windows, Linux, Mac) * This solution uses inner core of Q (internally named k4), so we need a scripting file with k extension, or interactive interpreter in k mode (\ command at first prompt). By contrast, 'verbose' (legible) version of the language requires script with q extension, and is the default mode at interactive interpreter. **TEST** ``` f ((1 1 1; 1 1 1; 0 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 1 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 1 1; 1 1 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 1 1; 1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 1 1; 1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1) (1 1 1; 1 1 1; 1 1 1; 0 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)) ##X##### ###\#### ###|#### ###|#### ##/##### #/###### #|###### ##\##### f ((41 27 38; 12 83 32; 50 53 35; 46 32 26; 55 89 82; 75 30 87; 2 11 64; 8 55 22) (56 21 0; 83 25 38; 43 75 63; 56 60 77; 68 55 89; 99 48 67; 94 30 9; 62 62 58) (23 18 40; 24 47 61; 96 45 72; 71 6 48; 75 63 98; 93 56 51; 23 31 30; 49 34 99) (20 47 42; 62 79 72; 32 28 44; 68 61 55; 62 39 57; 4 17 49; 97 85 6; 91 18 12) (51 50 11; 32 39 56; 12 82 23; 33 88 87; 60 55 22; 29 78 14; 70 11 42; 63 94 67) (75 64 60; 27 79 86; 70 72 56; 55 45 32; 95 67 12; 87 93 98; 81 36 53; 38 22 93) (31 80 50; 77 71 22; 59 46 86; 64 71 53; 41 19 95; 62 71 22; 92 80 41; 26 74 29)) ######X# #####/## ####/### #####\## ######\# ######|# ######|# #######\ ``` **EXPLANATION** For ilustration purpose, we assume second test (matrix ((41 27 38; 12 83 32; ....) We transform original matrix (m at code level): instead of orginimal matriz with a triplet for each coordinate, we define matrix for left, up, and right displacements. Left matrix contains 7x7 values (we drop first column), Up matrix 7x8, and right matrix 7x7 (we frop last column). ``` left up right 12 50 46 55 75 2 8 27 83 53 32 89 30 11 55 38 32 35 26 82 87 64 83 43 56 68 99 94 62 21 25 75 60 55 48 30 62 0 38 63 77 89 67 9 24 96 71 75 93 23 49 18 47 45 6 63 56 31 34 40 61 72 48 98 51 30 62 32 68 62 4 97 91 47 79 28 61 39 17 85 18 42 72 44 55 57 49 6 32 12 33 60 29 70 63 50 39 82 88 55 78 11 94 11 56 23 87 22 14 42 27 70 55 95 87 81 38 64 79 72 45 67 93 36 22 60 86 56 32 12 98 53 77 59 64 41 62 92 26 80 71 46 71 19 71 80 74 50 22 86 53 95 22 41 ``` To calculate final position we need to evaluate minimum-cost path. We assume initial cost 0 0 0 0 0 0 0 0 (cost to arrive at each column of first row), and iterates with each next row. At each column i, we calculate three values: * cost of previous i+1 value plus left[i+1]. We drop first component of cost (shifts and alineates columns to add) and sum component to component * cost of previous i value plus up[i]. We sum component to component * cost of previous i-1 value plus right[i-1]. We drop last component of cost (shifts and alineates columns to add) and sum component to component To calculate minimum we complete left cost prepending infinite and right cost appending infinite: with 3 vectors of eight components, calculate minimum component to component. Resulting value is the base cost for new iteration For first iteration we obtain values (0W is infinite in Q) ``` 0W 12 50 46 55 75 2 8 27 83 53 32 89 30 11 55 38 32 35 26 82 87 64 0W ``` and calculates minimum of each column ``` 27 12 35 26 55 30 2 8 ``` After all iterations, we have the minimum cost to arrive to each square (assuming row 0 at top, 7 at bottom). We are only interested in last column, but i draw all intermediate results for ilustrative purposes ``` 0 0 0 0 0 0 0 0 27 12 35 26 55 30 2 8 27 37 78 82 110 78 11 70 45 61 123 88 173 129 34 104 87 123 151 143 212 133 40 122 98 155 163 176 234 147 51 185 158 182 219 208 246 234 87 207 208 204 265 261 265 256 128 233 ``` Now we found minimum value at last row (128, at column 6). That's the end of the path (X character in ouput). We repeat cost calculation again, but now we annotate the direction from we obtain each minimum (wich of the 3 values used to calculate minimum is the selected value). ``` \|/|\/// \\\\\/|/ \\\|//|/ \\|\//|/ \\|//|\/ \\//|\|/ \|/|/|\/ ``` We reverse rows, put 'X' at pos 6, and preserves only path that ends at column 6 (the others are substituted by #) ``` ######X# #####/## ####/### #####\## ######\# ######|# ######|# #######\ ``` ]
[Question] [ You should write a program or function which given a list of tetris blocks as input outputs or returns the biggest gap between two points in the same height level which the pieces can connect. The 7 types of tetris pieces are the following: [![Tetris bricks](https://i.stack.imgur.com/YcgOC.png)](http://en.wikipedia.org/wiki/File:Tetrominoes_IJLO_STZ_Worlds.svg) We will refer to these pieces by the letters I, J, L, O, S, T and Z respectively, referring to their shapes. You can rotate the pieces but cannot mirror them just like in a Tetris game. Our task is to create an orthogonally connected area (sides connected to sides) from the given pieces. This area should connect (also orthogonally) two unit squares which are at the same height. We should find the biggest possible gap between the two squares which we can bridge. ## Detailed examples With the piece L we can connect a gap of 3 ``` L XLLLX ``` With the piece S we can connect a gap of 2 ``` SS XSSX ``` With the pieces S,S,O we can connect a gap of 7 (Note that we can't connect a gap of 8) ``` S XSSOO SSX SOOSS ``` ## Input * A string representing the available pieces containing only the uppercase letters I, J, L, O, S, T and Z. Every letter represents a complete tetris piece. * The letters will be in alphabetical order in the string. * The string will be at least one character long. ## Output * A single positive integer, the biggest gap connectable with the given pieces. ## Examples Input => Output ``` OSS => 7 LS => 5 LZ => 6 ZZZZ => 10 LLSSS => 14 IIJSSSTTZ => 28 IISSSSSS => 24 OOOSSSSSSSSSSSSTT => 45 IJLOSTZ => 21 IJLOSTZZZZZZZ => 37 IIJLLLOSTT => 31 IJJJOOSSSTTZ => 35 ``` This is code-golf so the shortest entry wins. [Answer] # CJam, 53 ``` '[,73>qf{1$e=s':+\+~}:+3*I+O-SZ-JO+m0e>ZS-LO+-e>2+3/- ``` [Try it online](http://cjam.aditsu.net/#code='%5B%2C73%3Eqf%7B1%24e%3Ds'%3A%2B%5C%2B~%7D%3A%2B3*I%2BO-SZ-JO%2Bm0e%3EZS-LO%2B-e%3E2%2B3%2F-&input=IJLOSTZ) The idea is: assign each of the I, J, ..., Z variables to be the number of occurences of that letter, and calculate `string length * 3 + I - O`. Then count the number of non-compensated S's or Z's: an S can be compensated by Z, J or O, and a Z can be compensated by S, L or O, and subtract `ceil(that number/3)`, as we lose 1 unit for every 3 S's or Z's. ]
[Question] [ Suppose you are given a set of **non-intersecting** intervals of integers `[a1,b1],[a2,b2],[a3,b3],...,[aN,bN]`. (Where `[a,b]` is the set of integers greater than or equal to `a` and less than or equal to `b`.) The interval at index `X` covers `bX - aX + 1` values. We'll call this number `cX`. Given that each interval can either be... * unchanged (stays as `[aX,bX]`), * extended to the right towards the `+` side of number the line by `cX` (becoming `[aX,bX + cX]`), * or extended to the left towards the `-` side of number the line by `cX` (becoming `[aX - cX,bX]`), what is the maximum number of values that can be covered by the union of all the updated intervals, given that they are still all non-intersecting? Write a function or program that takes a string of the form `[a1,b1],[a2,b2],[a3,b3],...,[aN,bN]` and computes this maximum. If writing a function, return the value. If writing a full program, use stdin for input and print the value to stdout (or use closest alternatives). You may assume all values are well within normal signed 32-bit integer limits and that `aX` is less than or equal to `bX` for all indices `X`. The intervals may be in any order, they are not necessarily always increasing. They must be given as a string in the format above. The string may be empty, in which case the answer will be 0. The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. ### Example If the input were `[-3,0],[1,2],[4,9]` the output would be 22. The middle interval has no room to expand either way so it must remain unchanged. The left and right intervals can both be extended to `[-7,0]` and `[4,15]` respectively. The union of `[-7,0]` and `[1,2]` and `[4,15]` contains all the values from -7 to 15, except 3. That's 22 values. [Answer] ## Haskell, 145 bytes ``` import Data.List x=maximum.map length.filter(nub>>=(==)).map concat.sequence.map(\[a,b]->[[2*a-b-1..b],[a..b],[a..2*b-a+1]]).read.('[':).(++"]") ``` Sample runs: ``` λ: x "" 0 λ: x "[5,6]" 4 λ: x "[-3,0],[1,2],[4,9]" 22 ``` [Answer] # R, ~~282~~ ~~278~~ ~~269~~ 247 This got big really quickly dealing with the string input. I suspect I can golf this better, but have run out of time at the moment. ``` f=function(s){i=matrix(strtoi(strsplit(gsub('[^0-9,-]','',s),',')[[1]]),nrow=2);l=0;if((a<-length(b<-order(i[1,])))>0){if(a>1)i=i[,b];l=diff(i[,1:a])+1;x=c(t(i));for(n in 1:a)if(n==1|n==a|x[n]-l[n]>x[n+a-1]|x[n+a]+l[n]<x[n+1])l[n]=l[n]*2;};sum(l)} ``` Essentially the idea is * Take in the string and turn it into a 2 row matrix * Make sure it is in the right order * Work out the differences for each column * Double the first and last differences * Double the middle differences if they have a gap to the previous or next that is large enough * Return the sum of the differences Edit: realized I miscounted the chars originally, then rearranged a few things to shave a few. ]
[Question] [ Consider how a word could be arranged on an arbitrarily large [Boggle](http://en.wikipedia.org/wiki/Boggle) grid ***if the rule about not using the same letter cube more than once is ignored***. Also assume that you have an unlimited number of letter cubes (with all letters present), and `Qu` is just `Q`. The word `MISSISSIPPI` could be arranged using only 6 cubes. Here is one possible arrangement: ``` S MIS PP ``` Starting at the `M` we repeatedly take any step horizontally, vertically, or diagonally until the entire word is spelled out. Surprisingly, a longer phrase like `AMANAPLANACANALPANAMA` also only needs 6 cubes: ``` MAN PLC ``` However, the minimum number of cubes needed for longer, more complex strings is not always obvious. # Challenge Write a program that takes in a string and arranges it in this Boggle-like fashion **such that the minimum number of cubes are used**. (The dimensions of the resulting grid and the number of empty cells are irrelevant.) Assume you have have an unlimited number of cubes for each [printable ASCII character](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) except space (hex codes 21 to 7E), since it's used as an empty grid cell. Only printable ASCII strings (without spaces) will be input. Input should be taken from stdin or the command line. Output should go to stdout (or closest alternative). Leading or trailing newlines and spaces in the output are fine (but hopefully there aren't an inordinate amount). The search space blows up exponentially as the string gets longer, but you are not required to attempt to make your algorithm efficient (though that would be nice :) ). This is code-golf, so the shortest solution [in bytes](https://mothereff.in/byte-counter) wins. # Example If the input were `Oklahoma!` (8 character minimum), these would all be valid outputs because the all have exactly 8 filled grid cells and they follow the (revised) Boggle reading pattern: ``` Oklaho !m ``` or ``` ! Oamo klh ``` or ``` lkO !amo h ``` etc. [Answer] ## Python 342 ~~355~~ ~~398~~ ``` R=(-1,0,1) A=[];b={} def s(w,x,y): if w: # not at the end of the word yet? for I in R: # search adjacent squares for j in R: if I|j: # skip the square we are on i=I+x;j+=y;c=b.get((i,j)) # get square in board if c==w[0]:s(w[1:],i,j) # square is what we are looking for? elif not c:b[i,j]=w[0];s(w[1:],i,j);del b[i,j] # we can set square? else:A.append(dict(b)) # all solutions s(raw_input(),9,9) # run the search A=min(A,key=len) # A is now the shortest solution C=sum(map(list,A),[]) # put all board coords together C=range(min(C),max(C)+1) # find the board biggest square bound for r in C:print"".join(A.get((c,r)," ") for c in C) ``` Indent at four spaces is actually a tab character. `AMANAPLANACANALPANAMA`: ``` MC NA PL ``` `MISSISSIPPI`: ``` S SI PPM ``` `Oklahoma!`: ``` oh ma ! l k O ``` `Llanfairpwllgwyngyll` is *lethal* ;) ]
[Question] [ "A picture is worth a thousand words"—so the old saying goes. The average word is about four characters long, so a picture conveys 4kB of information. But how much *entropy*, rather than information, can a picture convey? Your task is to generate an image, exactly 4,000 bytes in size, with the highest entropy possible. You may use any language, libraries, or image format you choose, and you may output to the console or to a file so long as you upload your image here. # Scoring Your score is the compression ratio (4000 ÷ compressed size) when your image is compressed with GNU `tar` version 1.28 and `gzip` version 1.6, using the DEFLATE algorithm and default settings — specifically, the command `tar -czvf out.tar.gz image`. The smallest compression ratio wins. [Answer] # 0.9514747859 (4204-byte output) [![noise](https://i.stack.imgur.com/0w6EA.png)](https://i.stack.imgur.com/0w6EA.png) Note: the image above is not the actual *file* I used, but it is the image. Here is a hexdump of the file: <https://gist.github.com/pommicket/cf2982e8ecf09a4de89d3a849526c64b> The file is in the [netpbm format](https://en.wikipedia.org/wiki/Netpbm_format), and can be generated with this C code: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Please pass in seed.\n"); return EXIT_FAILURE; } srand(atoi(argv[1])); FILE *fp = fopen("image.pgm", "w"); int width = 2, height = 1993; fprintf(fp, "P5 %d %d 255 ", width, height); for (int i = 0; i < width * height; i++) { fputc(rand() & 0xFF, fp); } fclose(fp); return 0; } ``` The random seed must be passed into the program. After trying some seeds, I got one which produced a 4204 byte gzipped file. As Nnnes pointed out, `tar` will include metadata in the file, so your results might differ from mine. netpbm isn't supported everywhere, but it works with imagemagick's `convert` (so just do `convert image.pgm image.png` to turn it into a png). ### Why this image/format? A file which consists of entirely random bytes is very hard to compress (in fact, any possible compression algorithm will do on average, no better than not compressing for random files). The content of the actual file is just `P5 2 1993` followed by 3986 random bytes, which is why gzip has such a hard time compressing it. ]
[Question] [ [Earlier](https://codegolf.stackexchange.com/questions/140560/how-hard-can-i-crush-my-array) I defined the process of crushing an array > > In a crush we read the array left to right. If at a point we encounter two of the same element in a row we remove the first one and double the second one. > > > For example here is the process of crushing the following array ``` [5,2,2,4] ^ [5,2,2,4] ^ [5,2,2,4] ^ [5,4,4] ^ [5,4,4] ^ [5,8] ^ ``` Note that the same element can be collapsed multiple times. In the example `2,2,4` was collapsed into `8` in a single pass. Now crushing arrays is easy, whats hard is uncrushing them. Your task is to take an array of positive integers as input and output the largest array that can form the input when crushed repeatedly. For example the array `[4]` is formed by crushing `[2,2]` which is in turn formed by crushing `[1,1,1,1]`. Since we can't have non integer values `[1,1,1,1]` cannot be uncrushed any further and thus is our answer. You will never receive a `0` in your input array because such arrays can be expanded indefinitely. You will also never receive a case with two of the same odd number next to each other, such cases cannot be the result of a crushing. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored with the size of their source measured in bytes with less bytes being better. Before you start making your answer I just want to say that this challenge is significantly more difficult than it seems. Check your intuition as you go along and make sure your answer passes all the test cases. ## Test Cases ``` [] -> [] [5] -> [5] [6] -> [3,3] [8] -> [1,1,1,1,1,1,1,1] [4,8] -> [1,1,1,1,1,1,1,1,1,1,2] [2,8] -> [1, 1, 1, 1, 2, 1, 1, 1, 1] [4,4] -> [1,1,1,1,1,1,1,1] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~237~~ ~~221~~ ~~213~~ 186 bytes ``` f=a=>a.map(b=>{for(i=1;~b%2;b/=2)i*=2;return Array(i).fill(b)}).reduce((t,c,i,s)=>{b=c.slice();if(i)r=2*s[--i].length,b.length>=r&&b[0]==s[i][0]?b[r-2]+=b.pop():b;return t.concat(b)},[]) ``` [Try it online!](https://tio.run/##bc3BTgMhFAXQvV8xGxuoDDqkNo2TN8bvICx4FFoMDhOgJsbor4@Y2I1h997Jzb2v@l1nk/xS@jke7bo60DBp/qYXgjB9upiIh2H8xlsx4j0I6rcgxmTLJc3dS0r6g3jKnQ@BIP2iPNnjxVhCCjPMs0xrB4LhOfiqdPSuxhOIbZZ97xUPdj6VM8O/Y4K02aB8UABZelWPZ5SpF@oOkC9xIfQJr@OFmzgbXX53mVR0rW@OwfIQT8SRKvTmHz02bN@wXctYSwXrDs1wk/esE20eWj7U9t2hvXpdWH8A "JavaScript (Node.js) – Try It Online") This algorithm computes optimal stretched arrays, by stretching each number to the max, and then, if necessary, it crushes back a pair of number at the right place, effectively creating a "crush blocker", interrupting the crush sequence of the preceding number. For instance: `[1, 1, 1, 1, 1, 1]` gives `[4,2]` once crushed, but `[1, 1, 1, 1, 2]` results in `[2, 4]` The challenge is to determine where exactly a crush blocker should be placed so that crushing the resulting array gives the right result: * A crush blocker needs to be placed only if the previous stretched number is equal to the current one, and if the current stretched sequence is greather than the previous one. For instance, `[2, 4]` requires a crush blocker (the stretched number is `1`, repeated, and `[1, 1]` is shorter than `[1,1,1,1]`), but `[4, 2]` and `[2, 6]` do not require one * if we call `n` the previous stretched sequence, and if the condition above is verified, then the current sequence is a repetition of the `n` sequence. To interrupt the crush sequence of the previous number, we need to place the crush blocker at the end of the second `n` sequence of the current number to stretch. Example: `[2, 8] => [(1, 1)=n, (1, 1) + (2) + (1, 1) + ...]`, or `[4, 8] => [(1, 1, 1, 1)=n, (1, 1, 1, 1) + (1, 1, 2) + ...]` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes ``` ṪḤ,⁼?⁹⁸;µ/Ḋ$¹L’$?ÐĿċ³ ṗЀ⁸ẎS⁼¥Ðfµ€ŒpẎ€ÇÐfṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPdyzRedS4x/5R485HjTusD23Vf7ijS@XQTp9HDTNV7A9POLL/SPehzVwPd04/POFR0xqgmoe7@oKBOg4tPTwh7dBWoNjRSQVAMSDjcDtQCGjm/8PtRyc93Dnj//9oMx0Fo1gA "Jelly – Try It Online") Full program. Extremely inefficient, but works. [Answer] # [Python 2](https://docs.python.org/2/), 230 228 226 bytes Works by iterating all possible lists with the same sum as the input one. Removing those that do not equal to the input array in some crushed state, selecting the longest one. **Edit:** -2 bytes by removing the `if` in the main function **Edit:** -2 bytes by removing two unnecessary square brackets ``` lambda x:max((c(z[:],x),len(z),z)for z in b(sum(x)))[2] def c(x,y): i=e=1 while x[i:]: if x[~-i]==x[i]:del x[i];i-=1;x[i]*=2;e=2 i+=1 return x==y or~-e and c(x,y) b=lambda s:[z+[-~i]for i in range(s)for z in b(s+~i)]+[[]] ``` [Try it online!](https://tio.run/##VU/LasQwDDzXX6Gj3TiHDdtSHPQlrih5OF1D4ix2lnVyyK@nNl229DBiGGmk0XVdLrOrjoCfx9hMbd9AVFMTOe/4phXJKORoHN@E3MQwe9jAOmh5uE08CiF0Raw3A3Q8ylUoBhYNnhjcL3Y0ELVVpNiLHRLdS0uISSLVmzH3qLYlnurMXrGqDVZptMh2b5abdxARV5j9XhpoXP84wlp8JA1Kb4Uud0s5mc3JfOO@DQ//oha7FVRoTXQsJixfXRNMAISkSP2W8J7wkXCWv/VMxFje8BzPm/686aOrt27hgT9FIY4f) # Explanation Main function, responsible for finding all possible solutions and selecting the longest one ``` lambda x:max((c(z[:],x),len(z),z)for z in b(sum(x)))[2] ``` Crush function, that checks if y is equal to one of the crushes. ``` def c(x,y): i=e=1 while x[i:]: if x[~-i]==x[i]:del x[i];i-=1;x[i]*=2;e=2 i+=1 return x==y or~-e and c(x,y) ``` Generate all possible permutations with the given sum ``` b=lambda s:[z+[-~i]for i in range(s)for z in b(s+~i)]+[[]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~41~~ 37 bytes ``` vy[DÉ#2÷]DYQX©NoDU‹&sDV¸X∍sić·®·Íǝ}», ``` [Try it online!](https://tio.run/##AUYAuf8wNWFiMWX//3Z5W0TDiSMyw7ddRFlRWMKpTm9EVeKAuSZzRFbCuFjiiI1zacSHwrfCrsK3w43HnX3Cuyz//1sxMiwgNDhd "05AB1E – Try It Online") Port of my Javascript solution. Explanations: ``` vy for each member of the list [DÉ#2÷] divide by 2 until odd: stack = stretched value, N = iterations DYQ stetched value equal to the previous one? X©NoDU‹ previous size < current one? (+store the new size in X) & AND on the 2 previous tests sDV¸X∍s build a list of the new stretched value repeated X times (+store the new stetched value in Y) ić·®·Íǝ} if the previous tests are true: reduce the result list size by 1 multiply by 2 the number at the crush block position », join by newline + print the list ``` ]
[Question] [ In mountaineering terminology, a "14er" is any mountain with an elevation of 14 000 feet or more. However, there is another distinction. For a peak to count as a 14er, it must also have a "geographic prominence" of 300 or more feet. This means that to move from one 14er to another, you must first descend *at least* 300 feet before rising again. Take this example. Line 1 counts as 14 000 feet, and each line counts as 100 feet. ``` /\__/\ / \ / \ ``` Now, both of these peaks have enough elevation to count, but there isn't enough drop in elevation between them to count as two separate peaks. Therefore, one of these counts as a 14er, and the other one is just a "partial peak". Here is an example where the two peaks count as two separate 14er: ``` /\ /\ / \ / \ / \/ \ / \ ``` There can also be a partial peak on the decline between two 14ers. Here's a slightly modified version of the last mountain range: ``` /\ /\ / \/\ / \ / \/ \ / \ ``` This mountain range also counts as two 14ers. You must write a program or function that takes an ascii-art representation of a mountain range, and return how many 14ers are in the range. You can take input in whatever format is most convenient for you, be it 2D array of characters, a string with newline, or a string with some other delimiter. You can assume that all inputs will only contain the characters `/\_`, and that the length of each line will be the same (including trailing spaces). You can also assume that the mountain range starts on the bottom left corner with either a `/` or a `_`. If the last section of a mountain is not on the bottom line, you can assume that the mountain only decreases after that, e.g. ``` / / / ``` Counts as a single 14er. You do not have to handle invalid mountain ranges. Here is some sample I/O: ``` /\___/\_ / \ /\ / \ / \ _/\/ \/ \ / \ / \ / \_ 2 /\ /\ /\ / \ / /\ / \ / \/ / \ / \ / / \/ \/ 4 /\ _/\__/ \ / \ 1 /\ / \ /\ / \_/ \ / \ / \ / \ / \ 1 /\ /\_/\ / \_ / \ / \ /\ / \/ \ / / \_/ / 3 ``` [Answer] # C, 174 bytes ``` a[99],c,p,j,M,m;main(i){for(i=j=1;c=getchar(),~c;i++)c<11?a[i]=j++,i=0:c&4?a[i]=j:0;for(m=j;c=a[i++];c>a[i-2]?M-m>1&&c-m>1?M=c,m=j,p++:M<c?M=m=c:M:m>c?m=c:0);printf("%d",p);} ``` Requires a trailing newline in the input, otherwise +4 bytes. [Answer] # JavaScript (ES6), 133 bytes ``` s=>[...s].map((_,i)=>(c=s[i%h*w+i/h|0])=="/"?++a>2&&(p+=!d,d=a=3):c=="\\"&&--a<1&&(d=a=0),w=s.search` `+1,h=-~s.length/w,a=3,d=p=1)|p ``` ## Explanation Since the specifications are not stated clearly, this makes a couple of assumptions: * The bottom line is the 14,000ft mark (so all positions on the grid are high enough to count as a peak). * The grid starts at (or ascending) the first peak (since it's at least 14,000ft high already as per previous assumption). * A separate peak counts only after descending 300ft *then ascending 300ft*. Iterates over the character `c` of each column (specifically, it iterates down each column until it finds a character). The current altitude is stored in `a`. It is clamped to a minimum of `0` and a maximum of `3`. The direction needed to move to count the next peak is stored in `d` (`false` = up, `true` = down). If `a` reaches `3` and `d` is `false`, the number of peaks `p` is incremented and `d` is set to `true` (down). Once `a` reaches `0`, `d` is set back to `false` (up). ``` var solution = s=> [...s].map((_,i)=> // loop (c=s[i%h*w+i/h|0]) // c = current character (moves down columns) =="/"? // if c is '/' ++a>2&& // increment a, if a equals 3 and d is true: (p+=!d,d=a=3) // increment p, set d to true, clamp a to 3 :c=="\\"&& // if c is '\': --a<1&& // decrement a, if a equals 0: (d=a=0), // set d to false, clamp a to 0 // Initialisation (happens BEFORE the above code) w=s.search`\n`+1, // w = grid width h=-~s.length/w, // h = grid height a=3, // a = current altitude (min = 0, max = 3) d= // d = required direction (false = up, true = down) p=1 // p = number of found peaks )|p // output the number of peaks var testCases = [` /\\ `,` /\\ \\ \\ /\\ \\ / \\ \\/ \\ `,` \\ / \\ / \\/ `,` /\\ /\\/ \\/\\ /\\/ \\/\\ /\\/ \\/\\ /\\/ \\/\\ `,` /\\__/\\ / \\ / \\ `,` /\\ /\\ / \\ / \\ / \\/ \\ / \\ `,` /\\ /\\ / \\/\\ / \\ / \\/ \\ / \\ `,` /\\___/\\_ / \\ /\\ / \\ / \\ _/\\/ \\/ \\ / \\ / \\ / \\_ `,` /\\ /\\ /\\ / \\ / /\\ / \\ / \\/ / \\ / \\ / / \\/ \\/ `,` /\\ _/\\__/ \\ / \\ `,` /\\ / \\ /\\ / \\_/ \\ / \\ / \\ / \\ / \\ `,` /\\ /\\_/\\ / \\_ / \\ / \\ /\\ / \\/ \\ / / \\_/ / `]; result.textContent = testCases.map(c=>c+"\n"+solution(c.slice(1,-1))).join`\n\n`; ``` ``` <textarea id="input" rows="6" cols="40"></textarea><br /><button onclick="result.textContent=solution(input.value)">Go</button><pre id="result"></pre> ``` [Answer] ## JavaScript (ES6), 154 bytes ``` s=>s.split`\n`.map((s,i)=>s.replace(/\S/g,(c,j)=>{e[j]=i+(c!='\\');e[j+1]=i+(c>'/')}),e=[])&&e.map(n=>h-n+d?h-n-d*3?0:(c++,d=-d,h=n):h=n,h=e[0],c=d=1)|c>>1 ``` Where `\n` represents the literal newline character. Ungolfed: ``` function climb(string) { var heights = []; // Split the array into lines so that we know the offset of each char var array = string.split("\n"); // Calculate the height (actually depth) before and after each char for (var i = 0; i < array.length; i++) { for (var j = 0; j < string.length; j++) { switch (array[i][j]) { case '\': heights[j] = i; heights[j+1] = i + 1; break; case '_': heights[j] = i + 1; heights[j+1] = i + 1; break; case '/': heights[j] = i + 1; heights[j+1] = i; break; } } var count = 1; // Start by looking for an upward direction var direction = 1; var height = heights[0]; for (var k = 1; k < heights.length; k++) { if (heights[i] == height - direction * 3) { // peak or trough direction *= -1; count++; // we're counting changes of direction = peaks * 2 height = heights[i]; } else if (heights[i] == height + direction) { // Track the current peak or trough to the tip or base height = heights[i]; } } return count >> 1; } ``` ]
[Question] [ *Based on an idea suggested by [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb).* A spaceship is moving around a regular 3D grid. The cells of the grid are indexed with integers in a right-handed coordinate system, *xyz*. The spaceship starts at the origin, pointing along the positive *x* axis, with the positive *z* axis pointing upwards. The spaceship will fly along a trajectory defined by a non-empty sequence of movements. Each movement is either `F`(orward) which makes the spaceship move one cell in the direction its facing, or one of the six rotations `UDLRlr`. These corresponds to pitch, yaw and roll as follows: ![PYR](https://i.stack.imgur.com/Pi1h3.png) Thanks to Zgarb for creating the diagram. * `U`p and `D`own change the pitch of the spaceship by 90 degrees (where the direction corresponds to the movement of the spaceship's nose). * `L`eft and `R`ight change the yaw of the spaceship by 90 degrees. They are just regular left and right turns. * `l`eft and `r`ight are 90 degree rolling movements, where the direction indicates which wing moves downwards. Note that these should always be interpreted relative to the spaceship so the relevant axes rotate along with it. In mathematical terms, the spaceship is initially at position `(0, 0, 0)`, pointing along the `(1, 0, 0)` vector, with `(0, 0, 1)` pointing upwards. The rotations correspond to the following matrices applied to the coordinate system: ``` U = ( 0 0 -1 D = ( 0 0 1 0 1 0 0 1 0 1 0 0 ) -1 0 0 ) L = ( 0 -1 0 R = ( 0 1 0 1 0 0 -1 0 0 0 0 1 ) 0 0 1 ) l = ( 1 0 0 r = ( 1 0 0 0 0 1 0 0 -1 0 -1 0 ) 0 1 0 ) ``` You should output the final position of the spaceship as three integers *x*, *y*, *z*. Output may be three separate integers or a list or string containing them. They may be in any consistent order as long as you specify it. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases ``` F => (1, 0, 0) FDDF => (0, 0, 0) FDDDF => (1, 0, 1) LrDDlURRrr => (0, 0, 0) UFLrRFLRLR => (1, 0, 1) FFrlFULULF => (3, 0, -1) LLFRLFDFFD => (-2, 0, -2) FrrLFLFrDLRFrLLFrFrRRFFFLRlFFLFFRFFLFlFFFlUFDFDrFF => (1, 5, 7) FUrRLDDlUDDlFlFFFDFrDrLrlUUrFlFFllRLlLlFFLrUFlRlFF => (8, 2, 2) FFLrlFLRFFFRFrFFFRFFRrFFFDDLFFURlrRFFFlrRFFlDlFFFU => (1, 2, -2) FLULFLFDURDUFFFLUlFlUFLFRrlDRFFFLFUFrFllFULUFFDRFF => (-3, -2, -3) ``` ## Worked example Here are the intermediate steps of the `UFLrRFLRLR` test case. Here, all intermediate coordinates and direction vectors are given in the initial, global coordinate system (as opposed to one local to the spaceship): ``` Cmd. Position Forward Up ( 0, 0, 0) ( 1, 0, 0) ( 0, 0, 1) U ( 0, 0, 0) ( 0, 0, 1) (-1, 0, 0) F ( 0, 0, 1) ( 0, 0, 1) (-1, 0, 0) L ( 0, 0, 1) ( 0, 1, 0) (-1, 0, 0) r ( 0, 0, 1) ( 0, 1, 0) ( 0, 0, 1) R ( 0, 0, 1) ( 1, 0, 0) ( 0, 0, 1) F ( 1, 0, 1) ( 1, 0, 0) ( 0, 0, 1) L ( 1, 0, 1) ( 0, 1, 0) ( 0, 0, 1) R ( 1, 0, 1) ( 1, 0, 0) ( 0, 0, 1) L ( 1, 0, 1) ( 0, 1, 0) ( 0, 0, 1) R ( 1, 0, 1) ( 1, 0, 0) ( 0, 0, 1) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~76~~ 75 bytes ``` FFF!3Xyj"FFT_FTFv4BvtFT_YStTF_YS3:"3$y!]6$Xh@'ULlDRr'4#mt?X)Y*}xxt1Z)b+w]]x ``` This works in current version (12.1.1) of the language. *Edit (April 4, 2016): The behaviour of function `v` has changed in release 15.0.0 of the language. To make the above code run, remove the first `v` and replace the second `3$v`. The following link includes this modification.* [**Try it online**!](http://matl.tryitonline.net/#code=RkZGITNYeWoiRkZUX0ZURjRCMyR2dEZUX1lTdFRGX1lTMzoiMyR5IV02JFhoQCdVTGxEUnInNCNtdD9YKVkqfXh4dDFaKWIrd11deA&input=RkxVTEZMRkRVUkRVRkZGTFVsRmxVRkxGUnJsRFJGRkZMRlVGckZsbEZVTFVGRkRSRkY) ### Explanation The state of the ship can be described in terms of two variables: * position: 3x1 vector * orientation: 3x3 matrix with the *accumulated* rotation, where "accumulated" means repeated matrix product. A third variable would be the direction in which the ship is facing, but that's not needed, because it can be obtained as the initial direction (column vector [`1;0;0]`) times the current orientation; that is, the first column of the orientation. These two state variables are kept on the stack, and are updated with each letter. Each of the letters `ULlDRr` multiplies the orientation matrix by one of the six rotation matrices to update the orientation. Letter `F` adds the current position plus the first column of the orientation matrix. The six rotation matrices are created as follows: first is introduced directly; second and third are circular shifts of the previous one; and the remaining three are transposed versions of the others. ``` FFF! % 3x1 vector [0;0;0]: initial position 3Xy % 3x3 identity matrix: initial orientation j % input string " % for-each character in that string FFT_FTFv4Bv % rotation matrix for U: defined directly tFT_YS % rotation matrix for L: U circularly shifted to the left tTF_YS % rotation matrix for l: L circularly shifted down 3:" % repeat three times 3$y! % copy third matrix from top and transpose ] % end loop. This creates rotation matrices for D, R, r 6$Xh % pack the 6 matrices in a cell array @ % push current character from the input string 'ULlDRr'4#m % this gives an index 0 for F, 1 for U, 2 for L, ..., 6 for r t? % if non-zero: update orientation X) % pick corresponding rotation matrix Y* % matrix product } % else: update position xx % delete twice (index and rotation matrix are not used here) t1Z) % duplicate orientation matrix and take its first column b+ % move position vector to top and add w % swap the two top-most elements in stack ] % end if ] % end for-each x % delete orientation matrix % implicitly display position vector ``` [Answer] # Octave, 175 bytes ``` function p=s(i)m.U=[0,0,-1;0,1,0;1,0,0];m.D=m.U';m.L=[0,-1,0;1,0,0;0,0,1];m.R=m.L';m.l=flip(flip(m.L),2);m.r=m.l';a=m.F=eye(3);p=[0;0;0];for c=i p+=(a*=m.(c))*[c=='F';0;0];end ``` Readable version: ``` function p=s(i) m.U=[0,0,-1;0,1,0;1,0,0]; m.D=m.U'; m.L=[0,-1,0;1,0,0;0,0,1]; m.R=m.L'; m.l=flip(flip(m.L),2); m.r=m.l'; a=m.F=eye(3); p=[0;0;0]; for c=i p+=(a*=m.(c))*[c=='F';0;0]; end ``` [Answer] ## ES6, ~~265~~ 259 bytes ``` s=>[...s.replace(/F/g,"f$`s")].reverse().map(e=>d={U:(x,y,z)=>[-z,y,x],D:(x,y,z)=>[z,y,-x],L:(x,y,z)=>[-y,x,z],R:(x,y,z)=>[y,-x,z],r:(x,y,z)=>[x,-z,y],l:(x,y,z)=>[x,z,-y],F:(...d)=>d,f:(x,y,z)=>[a+=x,b+=y,c+=z]),s:_=>[1,0,0]}[e](...d),d=[1,0,a=b=c=0])&&[a,b,c] ``` Explanation: Normally to calculate the direction of the spaceship you would compose all the rotations together, and then for each move you would compose the result to the unit vector `F = (1, 0, 0)` (or more simply extract the first column of the matrix). For instance, `FFrlFULULF => F + F + r⋅l⋅F + r⋅l⋅U⋅L⋅L⋅L⋅F`. Since matrix multiplication is associative, languages with built-in matrix multiplication can obviously compute the partial product `r⋅l⋅U⋅L⋅L⋅L` as they go along, multiplying by `F` as necessary to produce the terms that are then added together. Unfortunately I don't have that luxury, so the cheapest option is to compute each term in the above expression separately, starting with `F` and working back. For that, I need a list for each of the occurrences of `F` of all the rotations up to that point. I do this using `replace` with `$`` so I also need to mark the start and end of each term in the list so that I can ignore the rest of the string. Slightly ungolfed: ``` s=>[... // split the string into separate operations s.replace(/F/g,"f$`s")] // For each 'F', wrap the operations up to that point .reverse() // Play all the operations in reverse order .map(e=>d= // Update the direction for each operation { // set of operations U:(x,y,z)=>[-z,y,x], // Up D:(x,y,z)=>[z,y,-x], // Down L:(x,y,z)=>[-y,x,z], // Left turn R:(x,y,z)=>[y,-x,z], // Right turn r:(x,y,z)=>[x,-z,y], // right roll l:(x,y,z)=>[x,z,-y], // left roll F:(...d)=>d, // does nothing, `s` and `f` do the work now f:(x,y,z)=>[a+=x,b+=y,c+=z], // do the move s:_=>[1,0,0] // back to start }[e](...d), // apply the operation to the current direction d=[1,0,a=b=c=0] // initialise variables )&&[a,b,c] // return result ``` ]
[Question] [ Football is the sport where players kick the ball, not carry it. Some confused individuals might call this soccer. --- A football team has one goalkeeper, and 10 players out on the pitch. There are many [formations](https://en.wikipedia.org/wiki/Formation_(association_football)) used in football, that dictates where each player should be (the player of course moves around, but it's the base position). The most common formation is 4-4-2, which means that there are 4 defenders, 4 midfielders and two attackers. Other formations are ("defenders, midfielders, attackers" or "defenders, midfielders, midfielders, attackers"): * 4-4-2 * 4-3-3 * 5-3-2 * 3-4-3 * 3-5-2 * 4-5-1 * 5-4-1 * 4-4-1-1 * 4-3-1-2 * 4-1-2-3 * 4-1-3-2 * 4-3-2-1 * 3-4-1-2 * 3-3-3-1 The challenge is to take two inputs, one for each of the two teams and output a overview of the players on the field. In general: Most information about the layout of the ASCII-art can be found in the figures (a picture says more than 1000 words). Only the way to place the 10 players on the field is explained in detail: * The keeper and the penalty area takes up 3 rows of ASCII-characters + Layout and number of spaces can be found in the figure below * There is no empty row between the penalty area and the defenders * If there are 3 numbers in the formation (e.g. 4-4-2, 4-3-3 etc. Not 4-3-2-1): + There is no empty row between the defenders and the midfielders + There is one empty row between the midfielders and the attackers * If there are 4 numbers in the formation (e.g. 4-3-2-1, 3-3-3-1 etc. Not 4-4-2): + There is no empty row between the defender and the first row of midfielders + There is no empty row between the first row of midfielders and the second + There is no empty row between the second row of midfielders and the attackers * There is no empty rows between the attackers and the center line * The team on the upper half are marked as `x`, and the team on the second half are marked as `o`. * Each row of players shall be distributed on the pitch as shown in the figures below. The number of spaces can be seen in the figure. The following figure does not represent a valid formation, but is used to illustrate the layout and number of required spaces between each player. The input for this would be `2 3 4 5` and `5 4 2`: ``` +-----------------+ | | x | | | +-----+ | | x x | | x x x | | x x x x | | x x x x x | +-----------------+ | o o | | | | o o o o | | o o o o o | | +-----+ | | | o | | +-----------------+ ``` --- **Valid examples:** ``` Input: 4 4 2, 5 3 1 1 +-----------------+ | | x | | | +-----+ | | x x x x | | x x x x | | | | x x | +-----------------+ | o | | o | | o o o | | o o o o o | | +-----+ | | | o | | +-----------------+ ``` --- ``` Input: 3 5 2, 4 4 1 1 +-----------------+ | | x | | | +-----+ | | x x x | | x x x x x | | | | x x | +-----------------+ | o | | o | | o o o o | | o o o o | | +-----+ | | | o | | +-----------------+ ``` **Rules:** * Input can be on any convenient format, separated however you want. Format can be a single string (`5311`), comma separated digits (`5,3,1,1`), etc. + The input should not contain any other information than the two formations * The output should look exactly as the sample figures, but trailing spaces and newlines are OK. * You can assume only valid input is given (only formations in the list will be used). * Full program or function This is code golf, so the shortest code in bytes win. [Answer] # Python 2, ~~401~~ 377 bytes ``` def g(x,o): r=lambda r:["|"+" x"*5+" |","| x |","| x x |","| x x x |","| x x x x |"][r%5];d="+"+"-"*17+"+";h=[d,"| | x | |","| +-----+ |"]+map(r,x);b=map(lambda r:r.replace("x","o"),[s for s in h[:3]]+map(r,o))[::-1];e="|"+" "*17+"|" if len(x)-4:h.insert(5,e) if len(o)-4:b.insert(1,e) print"\n".join(h+[d]+b) ``` Ungolfed version with test environment [here](https://repl.it/BlOQ/6)! Function that takes two lists of the format [defenders, midfielders, midfielders, attackers] while the one midfielder number is optional. Team X (top) comes first, team O (bottom) second. [Answer] # JavaScript (ES6), 258 ~~262~~ Anonymous function, taking 2 parameters as numeric arrays ``` (a,b,H=f=>(f[3]||f.push(0,f.pop()),[z='+-----------------+',...[6,7,...f].map(x=>`|${'98,8o8,5o5o5,4o3o3o4,2o3o3o3o2,2o2o2o2o2o2,5|2o2|5,5+-----+5'.replace(/\d/g,x=>' '.repeat(x)).split`,`[x]}|`),'']))=>H(a).join` `.replace(/o/g,'x')+z+H(b).reverse().join` ` ``` **Test** ``` F=(a,b, H=f=>( f[3]||f.push(0,f.pop()), [z='+-----------------+',...[6,7,...f].map(x=>`|${'98,8o8,5o5o5,4o3o3o4,2o3o3o3o2,2o2o2o2o2o2,5|2o2|5,5+-----+5'.replace(/\d/g,x=>' '.repeat(x)).split`,`[x]}|`),''] ) )=> H(a).join`\n`.replace(/o/g,'x')+z+H(b).reverse().join`\n` function test() { var f1=F1.value.match(/\d+/g),f2=F2.value.match(/\d+/g) O.textContent=F(f1,f2) } test() ``` ``` x <input id=F1 value='4,4,2' oninput='test()'><br> o <input id=F2 value='4,3,1,2' oninput='test()'><br> <pre id=O> ``` [Answer] ## Perl, ~~360~~ ~~332~~ 324 bytes ``` sub f{$q="";($_,$p)=@_;@x=/\S+/g;splice@x,2,0,0if@x<4;for(@x) {$s=(17-$_)/($_+1);$s=$=+1if($s!=($==$s));$x=$"x$=;@a=();push@a,$p for 1..$_;$q.=$_==0?"|$u$u$u |\n":"|$x".join($"x$s,@a)."$x|\n"}$q}($k,$j)=<>;$u=$"x5;$^="-"x17;$i="|$u+-----+$u|";say"x$^x\n|$u| x |$u|\n$i\n".f($k,x)."+$^+".(reverse f$j,o)."\n$i\n|$u| o |$u|\nx$^x" ``` Requires `-E`|`-M5.010`: ``` $ echo $'4 4 2\n4 4 1 1' | perl -M5.010 football.pl x-----------------x | | x | | | +-----+ | | x x x x | | x x x x | | | | x x | +-----------------+ | o | | o | | o o o o | | o o o o | | +-----+ | | | o | | x-----------------x ``` Somewhat ungolfed: ``` sub f{ $q=""; ($_,$p)=@_; @x=/\S+/g; splice@x,2,0,0if@x<4; for(@x) { $s=(17-$_)/($_+1); $s=$=+1if($s!=($==$s)); $x=" "x$=; @a=(); push@a,$p for 1..$_; $q.=$_==0?"|$u$u$u |\n":"|$x".join(" "x$s,@a)."$x|\n" } $q } ($k,$j)=<>; $u=" "x5; $^="-"x17; $i="|$u+-----+$u|"; say"x$^x\n|$u| x |$u|\n$i\n".f($k,x)."+$^+".(reverse f$j,o)."\n$i\n|$u| o |$u|\nx$^x" ``` ]
[Question] [ You sit at home, rubbing your hands in a most evil fashion. *This time, I'll be able to set the community A-SPIN! I'll merely claim that I have proven this problem (which is of no doubt improvable) inside this book here…* You open to the first relevant page. You scrawl those words… You are, of course, the evil Fermat! Haha, just kidding. You know it didn't happen like this; this is merely the narrative of his evil twin, Format. Format here is too lazy to condense his “proof” into the margin. He has therefore called upon you to do it for him. **Objective** Given a proof (string), and a page (text block), "write" into the margin the proof. ## Valid page rules A text block contains a page if and only if it meets the following requirements: * The top and bottom borders are of the form `-{10,}\+$` (Regular expression for `-` at least ten times until a `+`, then the end of the line). * Every non-top and non-bottom line must end with a `|`. There will be at least one such line. * There will be at least five spaces from the last `|` in each line. * All lines are the same width. So the following is a valid page (the `.`s are for showing where the maximal margin border is): ``` -----------------+ Lorem Ipsum. | and other . | latin crud . | . | EOF. | -----------------+ ``` Here is another page with a wider margin: ``` ------------------------+ Hello world! . | How are you, to. | day? --Mme. B . | . | ------------------------+ ``` You are to write the given string in the margin, maintaining words that you can, as far as you can. For example, if `hello` fits on the next line, do not break it on the current line. ## I/Os [Filler text](http://www.lipsum.com/) ``` Proof: This is a most excellent proof, too small for anyone! Text: ; not a leading newline ------------------------+ Hello world! | How are you, to | day? --Mme. B | | ------------------------+ Output: ------------------------+ Hello world! This a | How are you, to most | day? --Mme. B excellen| t proof,| ------------------------+ Proof: Execute the member as an example to the others! Text: ------------------------------------------------+ Contrary to popular belief, Lorem | Ipsum is not simply random text. | It has roots in a piece of classical | Latin literature from 45 BC, making | it over 2000 years old. Richard | McClintock, a Latin professor at | Hampden-Sydney College in Virginia, | looked up one of the more obscure | Latin words, consectetur, from a | Lorem Ipsum passage, and going through | the cites of the word in classical | literature, discovered the undoubtable | source. Lorem Ipsum comes from... | ------------------------------------------------+ Output: ------------------------------------------------+ Contrary to popular belief, Lorem Execute | Ipsum is not simply random text. the | It has roots in a piece of classical member as| Latin literature from 45 BC, making an | it over 2000 years old. Richard example | McClintock, a Latin professor at to the | Hampden-Sydney College in Virginia, others! | looked up one of the more obscure | Latin words, consectetur, from a | Lorem Ipsum passage, and going through | the cites of the word in classical | literature, discovered the undoubtable | source. Lorem Ipsum comes from... | ------------------------------------------------+ Proof: Consider supercalifragilisticexpialidocious. Therefore, x. Output: -----------------------------------------+ sections 1.10.32 and | 1.10.33 of "de Finibus | Bonorum et Malorum" | (The Extremes of Good | and Evil) by Cicero, | written in 45 BC. This | book is a treatise on | the theory of ethics, | very popular during the | Renaissance. The first | line of Lorem Ipsum, | "Lorem ipsum dolor sit | amet..", comes from a | line in section 1.10.32. | -----------------------------------------+ Output: Consider supercalifragilisticexpialidocious. Therefore, x. -----------------------------------------+ sections 1.10.32 and Consider | 1.10.33 of "de Finibus supercalifragili| Bonorum et Malorum" sticexpialidocio| (The Extremes of Good us. Therefore, x| and Evil) by Cicero, . | written in 45 BC. This | book is a treatise on | the theory of ethics, | very popular during the | Renaissance. The first | line of Lorem Ipsum, | "Lorem ipsum dolor sit | amet..", comes from a | line in section 1.10.32. | -----------------------------------------+ Proof: Alex is a bird. All birds can fly. All things that fly are wrong. Ergo, Alex is wrong. Text: ----------+ Sorry | ; 5 spaces. ----------+ Output: ----------+ Sorry Alex| ----------+ ``` --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins! --- ## Leaderboard ``` var QUESTION_ID=63683,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([-\.\d]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Python 2, 334 ``` p=open("f.txt",'r').readlines() r,S,p=p[0][7:],p[2].strip(),p[3:-1] import textwrap as t,itertools as i m,l=max([len(s[:-5].strip()) for s in p]),len(S)-2 P = i.izip_longest(["{} {{:{}}}|".format(s[:m],l-m) for s in p],t.wrap(r,l-m),fillvalue="") print S for q in P: if not q[0]:break print q[0].format(q[1]) print S ``` **Sample IO** with contents of `f.txt` followed by code output Case 1 ``` Proof: This is a most excellent proof, too small for anyone! Text: ------------------------+ Hello world! | How are you, to | day? --Mme. B | | ------------------------+ ------------------------+ Hello world! Proof: | How are you, to This is | day? --Mme. B a most e| xcellent| ------------------------+ ``` Case 2 ``` Proof: Consider supercalifragilisticexpialidocious. Therefore, x. Output: -----------------------------------------+ sections 1.10.32 and | 1.10.33 of "de Finibus | Bonorum et Malorum" | (The Extremes of Good | and Evil) by Cicero, | written in 45 BC. This | book is a treatise on | the theory of ethics, | very popular during the | Renaissance. The first | line of Lorem Ipsum, | "Lorem ipsum dolor sit | amet..", comes from a | line in section 1.10.32. | -----------------------------------------+ -----------------------------------------+ sections 1.10.32 and Consider superca| 1.10.33 of "de Finibus lifragilisticexp| Bonorum et Malorum" ialidocious. | (The Extremes of Good Therefore, x. | and Evil) by Cicero, | written in 45 BC. This | book is a treatise on | the theory of ethics, | very popular during the | Renaissance. The first | line of Lorem Ipsum, | "Lorem ipsum dolor sit | amet..", comes from a | line in section 1.10.32. | -----------------------------------------+ ``` Case 3 ``` Proof: Alex is a bird. All birds can fly. All things that fly are wrong. Ergo, Alex is wrong. Text: ----------+ Sorry | ----------+ ----------+ Sorry Alex| ----------+ ``` ]
[Question] [ Write a program or function that takes in a list of positive integers. Each of these integers represents the side length of a square on a 2D plane. Each square can be moved to any integer coordinates in the plane, but it can't rotate and it can't overlap other squares. Using a different [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) character for each square (excluding space which is used for emptiness) your program/function needs to print any single arrangement of the squares that has a horizontal or vertical line of reflectional symmetry. If no such arrangement exists then nothing should be printed. The squares are different characters just so they can be told apart. Only the shape made by the union of all the squares needs to be symmetrical. You can assume the list will not contain more than 94 elements (as there are 94 characters). For example, if the input was `[2, 1, 2, 2, 2]`, a possible output is: ``` DD-- DD-- Z FFPP FFPP ``` This shape has a horizontal line of reflectional symmetry; its top and bottom halves are mirror images. Here are some other possibilities: (Note that the squares don't need to touch and any characters can be used as long as no two squares are made of the same character.) ``` 55 55 %% %% @ HH HH (( (( ``` ``` G 11 33 11 33 22 44 22 44 ``` The line of symmetry could also be the boundary between characters, e.g. for `[2, 4]`: ``` !!!! !!!! ++ !!!! ++ !!!! ``` Some sets of squares are impossible to arrange symmetrically, e.g. `[1, 2, 3]`: ``` AAA BB C AAA BB (these can't be vertically or horizontally symmetric => no output) AAA ``` And remember that the overall shape may be symmetric even if the square boundaries aren't. e.g. a valid output for `[2, 1, 1, 1, 1, 4]` is: ``` AA---- AA---- BC---- DE---- ``` Similarly, a valid output for `[1, 1, 2, 3, 5]` is: ``` 44444 44444 44444 44444 44444 33301 33322 33322 ``` # Notes * The input list will always have from 1 to 94 elements. * Take input in any reasonable way: stdin, command line, text file, function arg. It can be slightly formatted to suit your needs, e.g. `{1, 2, 3, 4}` or `[1 2 3 4]`. * Output to stdout or similar. Any amounts of leading/trailing spaces or newlines are fine as long as the resulting shape has the line of symmetry. * A diagonal line of symmetry does not count (else this would be super easy). Also, it has to be reflectional symmetry, not rotational or transitional. * I'm honestly not sure how computationally difficult this task is. You may post partial answers that solve some subset of the problem (especially if you want to show off a particularly clever algorithm). These are not eligible to win. + For example, you might assume that the input always has at least one symmetrical arrangement (so lists like `[1, 2, 3]` are never input). + Or, for example, you may only consider arrangements where the square boundaries, as well as the overall shape, are symmetrical. In this case, `[1, 1, 2, 3, 5]` would have no output. + If you want to go crazy, you could extend the idea to rectangles or even [polyominoes](http://en.wikipedia.org/wiki/Polyomino). # Scoring Your score is the size of your program [in bytes](https://mothereff.in/byte-counter). The lowest score wins. Tiebreaker goes the the answer posted first. [Answer] # Python 2, ~~460~~ ~~452~~ 437 bytes ``` exec"""def f(L): if[]==L: X{2}[map(" ".__lt__,q)for q in G]);Z{2}zip(*X));C=Z==Z[::-1]or X==X[::-1] if C:print"\\n".join(map("".join,G)) return C x=L[-1];T=S-x+1;R=range(x) for n in range(T*T): i=n%T;j=n/T if all({1}=" "{0}): {0}:{1}chr(32+len(L)) r=f(L[:-1]) {0}:{1}" " if r:return r""".format(" for a,b in[(a,b)for a in R for b in R]","G[i+a][j+b]=","=filter(sum,") L=input() S=sum(L) G=[S*[" "]for _ in[0]*S] f(L) ``` Only mildly golfed for now, but here's something to get things started. I tried using `exec` for lines 10 and 12, but for some reason it didn't let me. Input the list `L` via STDIN, e.g. `[2, 1, 2, 2, 2]`. The program simply tries every possibility of placing squares in a `sum(L) x sum(L)` grid. Sample output (blank lines removed for compactness): ``` [2, 1, 2, 2, 2] %% %% $$ $$ " ## ## !! !! [2, 4] """" """" """" """" !! !! [2, 1, 1, 1] $!! #!! " [1, 1, 2, 3, 5] %%%%% %%%%% %%%%% %%%%% %%%%% $$$## $$$## $$$"! [1, 4, 1, 8] $$$$$$$$ $$$$$$$$ $$$$$$$$ $$$$$$$$ $$$$$$$$ $$$$$$$$ $$$$$$$$ $$$$$$$$ # """" ! """" """" """" [8, 1, 4, 1] $ !!!!!!!! !!!!!!!! ####!!!!!!!! ####!!!!!!!! ####!!!!!!!! ####!!!!!!!! !!!!!!!! " !!!!!!!! (The algorithm starts placing from the last square first, prioritising left then up) ``` --- Slightly less confusing version (452 bytes): ``` def f(L): if[]==L: X=filter(sum,[map(" ".__lt__,q)for q in G]);Z=filter(sum,zip(*X));C=Z==Z[::-1]or X==X[::-1] if C:print"\n".join(map("".join,G)) return C x=L[-1];T=S-x+1;R=range(x);V=[(a,b)for a in R for b in R] for n in range(T*T): i=n%T;j=n/T if all(G[i+a][j+b]<"!"for a,b in V): for a,b in V:G[i+a][j+b]=chr(32+len(L)) r=f(L[:-1]) for a,b in V:G[i+a][j+b]=" " if r:return r L=input() S=sum(L) G=[S*[" "]for _ in[0]*S] f(L) ``` ]
[Question] [ ### Overview Given a list of fireworks `a-z` and times `3-78`, arrange them with fuses to make them all light up at the correct time. A line of input is given as space separated letters and numbers: ``` a 3 b 6 c 6 d 8 e 9 f 9 ``` That example shows that firework `a` need to light at time `3`, `b` and `c` both at `6`, `d` at `8`, with `e` and `f` both at `9`. Each line corresponds to one map. Output is a fuse/firework map for each line, using the symbols `|-` to show fuses and the letters to show fireworks. A `-` fuse connects to fuses and fireworks directly left/right of it, while a `|` fuse connects with those above/below. For example, the fuses `||` are *not* connected, and `-|` *are*. For example, two possible answers to the above are: ``` ---a ---------f | ||| || |-c ||| de --|--d a|| | b | |c f e b ``` All fuse maps should start with a single `-` in the upper left corner. That is the point where you light the fuse. Each character of fuse takes one second to burn. As you can see, the `a` is reached in three seconds in both diagrams, `b` in six, etc. Now, both of the maps given above are valid for the input given, but one is clearly more efficient. The left one only uses 13 units of fuse, while the right one takes 20. Fuses **do not** burn through fireworks! So, for input `a 3 b 5`, this is not valid: ``` ---a--b ``` ### Challenge Your goal is to minimize the amount of fuse used over all test cases. Scoring is very simple, the total units of fuse used. If you *cannot* produce a map for a test case, whether it's an impossible case or not, the score for that case is the sum of all times (41 for the example above). In the case of a tie, the scoring is modified so that the most *compact* maps win. The tiebreak score is the *area* of the bounding box of each map. That is, the length of the longest line times the number of lines. For "impossible" maps this is the square of the largest number (81 for the example above). In the case that submissions tie both of these scoring methods, the tie goes to the earlier entry/edit. Your program must be deterministic, for verification purposes. ### Test Cases There are 250 test cases, [located here](http://pastebin.com/raw.php?i=cDSBjTj2). Each has between 4 and 26 fireworks. The minimum fuse time for a firework is 3. The fireworks in each case are "sorted" by time and letter, meaning `b` will never light *before* `a`. When posting, please include your full program, your total score, and the resulting map for (at least) the first test case given in the file: ``` a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34 ``` [Answer] ## C++ ## Total Length: 9059, Total Area: 27469, Failures: 13. *Note:* Score includes failure penalties. --- **Sample output:** ``` a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34 ------ae | | |---c b||-g |d| f | i---| k---| h | j |---m l | t o-n| |s-r |-| p q Length: 39, Area: 150. ``` --- ``` a 6 b 6 c 6 d 6 e 6 f 6 g 6 h 8 i 9 j 9 k 9 l 12 m 12 n 13 o 14 p 15 q 15 r 15 s 17 t 17 u 17 v 17 w 17 x 20 y 23 z 26 ------a n|--w |d-||---k|-o| | g|b |--m --x |-|c ||--r| ||f l|-q | ||--j u--|--s|- e|-i |p| y| h v t z- Length: 56, Area: 120. ``` --- **Full output:** <http://pastebin.com/raw.php?i=spBUidBV> --- Don't you just love brute-force solutions? This is a little more than a simple backtracking algorithm: our tireless worker moves around the map, placing fuses and fireworks as necessary, while testing all possible moves at any point. Well, almost---we do restrict the set of moves and abandon nonoptimal states early so that it doesn't take unbearably long (and, in particular, so that it terminates.) Special care is taken not to create any cycles or unintended paths and not to go back the same way we came, so it's guaranteed that we don't visit the same state twice. Even so, finding an optimal solution can take a while, so we eventually give up on optimizing a solution if it takes too long. This algorithm still has some headroom. For one thing, better solutions can be found by increasing the `FRUSTRATION` parameters. There's no competition ATM but these numbers can be cranked up if and when... Compile with: `g++ fireworks.cpp -ofireworks -std=c++11 -pthread -O3`. Run with: `./fireworks`. Reads input from STDIN and writes output to STDOUT (possibly out-of-order.) ``` /* Magic numbers */ #define THREAD_COUNT 2 /* When FRUSTRATION_MOVES moves have passed since the last solution was found, * the last (1-FRUSTRATION_STATES_BACKOFF)*100% of the backtracking states are * discarded and FRUSTRATION_MOVES is multiplied by FRUSTRATION_MOVES_BACKOFF. * The lower these values are, the faster the algorithm is going to give up on * searching for better solutions. */ #define FRUSTRATION_MOVES 1000000 #define FRUSTRATION_MOVES_BACKOFF 0.8 #define FRUSTRATION_STATES_BACKOFF 0.5 #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <thread> #include <mutex> #include <string> #include <sstream> #include <cassert> using namespace std; /* A tile on the board. Either a fuse, a firework, an empty tile or an * out-of-boudns tile. */ struct tile { /* The tile's value, encoded the "obvious" way (i.e. '-', '|', 'a', etc.) * Empty tiles are encoded as '\0' and OOB tiles as '*'. */ char value; /* For fuse tiles, the time at which the fuse is lit. */ int time; operator char&() { return value; } operator const char&() const { return value; } bool is_fuse() const { return value == '-' || value == '|'; } /* A tile is vacant if it's empty or OOB. */ bool is_vacant() const { return !value || value == '*'; } /* Prints the tile. */ template <typename C, typename T> friend basic_ostream<C, T>& operator<<(basic_ostream<C, T>& os, const tile& t) { return os << (t.value ? t.value : ' '); } }; /* Fireworks have the same encoding as tiles. */ typedef tile firework; typedef vector<firework> fireworks; /* The fuse map. It has physical dimensions (its bounding-box) but is * conceptually infinite (filled with empty tiles.) */ class board { /* The tiles, ordered left-to-right top-to-bottom. */ vector<tile> p_data; /* The board dimensions. */ int p_width, p_height; /* The total fuse length. */ int p_length; public: board(): p_width(0), p_height(0), p_length(0) {} /* Physical dimensions. */ int width() const { return p_width; } int height() const { return p_height; } int area() const { return width() * height(); } /* Total fuse length. */ int length() const { return p_length; } /* Returns the tile at (x, y). If x or y are negative, returns an OOB * tile. */ tile get(int x, int y) const { if (x < 0 || y < 0) return {'*'}; else if (x >= width() || y >= height()) return {'\0'}; else return p_data[y * width() + x]; } /* Sets the tile at (x, y). x and y must be nonnegative and the tile at * (x, y) must be empty. */ board& set(int x, int y, const tile& t) & { assert(x >= 0 && y >= 0); assert(!get(x, y)); if (x >= width() || y >= height()) { int new_width = x >= width() ? x + 1 : width(); int new_height = y >= height() ? y + 1 : height(); vector<tile> temp(new_width * new_height, {'\0'}); for (int l = 0; l < height(); ++l) copy( p_data.begin() + l * width(), p_data.begin() + (l + 1) * width(), temp.begin() + l * new_width ); p_data.swap(temp); p_width = new_width; p_height = new_height; } p_data[y * width() + x] = t; if (t.is_fuse()) ++p_length; return *this; } board&& set(int x, int y, const tile& t) && { return move(set(x, y, t)); } /* Prints the board. */ template <typename C, typename T> friend basic_ostream<C, T>& operator<<(basic_ostream<C, T>& os, const board& b) { for (int y = 0; y < b.height(); ++y) { for (int x = 0; x < b.width(); ++x) os << b.get(x, y); os << endl; } return os; } }; /* A state of the tiling algorithm. */ struct state { /* The current board. */ board b; /* The next firework to tile. */ fireworks::const_iterator fw; /* The current location. */ int x, y; /* The current movement direction. 'N'orth 'S'outh 'E'ast, 'W'est or * 'A'ny. */ char dir; }; /* Adds a state to the state-stack if its total fuse length and bounding-box * area are not worse than the current best ones. */ void add_state(vector<state>& states, int max_length, int max_area, state&& new_s) { if (new_s.b.length() < max_length || (new_s.b.length() == max_length && new_s.b.area() <= max_area) ) states.push_back(move(new_s)); } /* Adds the state after moving in a given direction, if it's a valid move. */ void add_movement(vector<state>& states, int max_length, int max_area, const state& s, char dir) { int x = s.x, y = s.y; char parallel_fuse; switch (dir) { case 'E': if (s.dir == 'W') return; ++x; parallel_fuse = '|'; break; case 'W': if (s.dir == 'E') return; --x; parallel_fuse = '|'; break; case 'S': if (s.dir == 'N') return; ++y; parallel_fuse = '-'; break; case 'N': if (s.dir == 'S') return; --y; parallel_fuse = '-'; break; } const tile t = s.b.get(s.x, s.y), nt = s.b.get(x, y); assert(t.is_fuse()); if (nt.is_fuse() && !(t == parallel_fuse && nt == parallel_fuse)) add_state(states, max_length, max_area, {s.b, s.fw, x, y, dir}); } /* Adds the state after moving in a given direction and tiling a fuse, if it's a * valid move. */ void add_fuse(vector<state>& states, int max_length, int max_area, const state& s, char dir, char fuse) { int x = s.x, y = s.y; int sgn; bool horz; switch (dir) { case 'E': ++x; sgn = 1; horz = true; break; case 'W': --x; sgn = -1; horz = true; break; case 'S': ++y; sgn = 1; horz = false; break; case 'N': --y; sgn = -1; horz = false; break; } if (s.b.get(x, y)) /* Tile is not empty. */ return; /* Make sure we don't create cycles or reconnect a firework. */ const tile t = s.b.get(s.x, s.y); assert(t.is_fuse()); if (t == '-') { if (horz) { if (fuse == '-') { if (!s.b.get(x + sgn, y).is_vacant() || s.b.get(x, y - 1) == '|' || s.b.get(x, y + 1) == '|') return; } else { if (s.b.get(x + sgn, y) == '-' || !s.b.get(x, y - 1).is_vacant() || !s.b.get(x, y + 1).is_vacant()) return; } } else { if (!s.b.get(x, y + sgn).is_vacant() || s.b.get(x - 1, y) == '-' || s.b.get(x + 1, y) == '-') return; } } else { if (!horz) { if (fuse == '|') { if (!s.b.get(x, y + sgn).is_vacant() || s.b.get(x - 1, y) == '-' || s.b.get(x + 1, y) == '-') return; } else { if (s.b.get(x, y + sgn) == '|' || !s.b.get(x - 1, y).is_vacant() || !s.b.get(x + 1, y).is_vacant()) return; } } else { if (!s.b.get(x + sgn, y).is_vacant() || s.b.get(x, y - 1) == '|' || s.b.get(x, y + 1) == '|') return; } } /* Ok. */ add_state( states, max_length, max_area, {board(s.b).set(x, y, {fuse, t.time + 1}), s.fw, x, y, dir} ); } /* Adds the state after adding a firework at the given direction, if it's a * valid move. */ void add_firework(vector<state>& states, int max_length, int max_area, const state& s, char dir) { int x = s.x, y = s.y; int sgn; bool horz; switch (dir) { case 'E': ++x; sgn = 1; horz = true; break; case 'W': --x; sgn = -1; horz = true; break; case 'S': ++y; sgn = 1; horz = false; break; case 'N': --y; sgn = -1; horz = false; break; } if (s.b.get(x, y)) /* Tile is not empty. */ return; /* Make sure we don't run into an undeliberate fuse. */ if (horz) { if (s.b.get(x + sgn, y) == '-' || s.b.get(x, y - 1) == '|' || s.b.get(x, y + 1) == '|') return; } else { if (s.b.get(x, y + sgn) == '|' || s.b.get(x - 1, y) == '-' || s.b.get(x + 1, y) == '-') return; } /* Ok. */ add_state( states, max_length, max_area, /* After adding a firework, we can move in any direction. */ {board(s.b).set(x, y, {*s.fw}), s.fw + 1, s.x, s.y, 'A'} ); } void add_possible_moves(vector<state>& states, int max_length, int max_area, const state& s) { /* We add the new states in reverse-desirability order. The most * (aesthetically) desirable states are added last. */ const tile t = s.b.get(s.x, s.y); assert(t.is_fuse()); /* Move in all (possible) directions. */ for (char dir : "WENS") if (dir) add_movement(states, max_length, max_area, s, dir); /* If the fuse is too short for the next firework, keep adding fuse. */ if (t.time < s.fw->time) { if (t == '-') { add_fuse(states, max_length, max_area, s, 'N', '|'); add_fuse(states, max_length, max_area, s, 'S', '|'); add_fuse(states, max_length, max_area, s, 'W', '|'); add_fuse(states, max_length, max_area, s, 'W', '-'); add_fuse(states, max_length, max_area, s, 'E', '|'); add_fuse(states, max_length, max_area, s, 'E', '-'); } else { add_fuse(states, max_length, max_area, s, 'W', '-'); add_fuse(states, max_length, max_area, s, 'E', '-'); add_fuse(states, max_length, max_area, s, 'N', '-'); add_fuse(states, max_length, max_area, s, 'N', '|'); add_fuse(states, max_length, max_area, s, 'S', '-'); add_fuse(states, max_length, max_area, s, 'S', '|'); } } else if (t.time == s.fw->time) { /* If we have enough fuse for the next firework, place the firework (if * possible) and don't add more fuse, or else we'll never finish... */ if (t == '-') { add_firework(states, max_length, max_area, s, 'W'); add_firework(states, max_length, max_area, s, 'E'); } else { add_firework(states, max_length, max_area, s, 'N'); add_firework(states, max_length, max_area, s, 'S'); } } } void thread_proc(mutex& lock, int& total_length, int& total_area, int& failures) { fireworks fw; vector<state> states; while (true) { /* Read input. */ string input; { lock_guard<mutex> lg(lock); while (!cin.eof() && input.empty()) getline(cin, input); if (input.empty()) break; } fw.clear(); int length = 0, area; { stringstream is; is << input; while (!is.eof()) { char c; int t; if (is >> c >> t) { /* Fireworks must be sorted by launch time. */ assert(fw.empty() || t >= fw.back().time); fw.push_back({c, t}); length += t; } } assert(!fw.empty()); area = fw.back().time * fw.back().time; } /* Add initial state. */ states.push_back({board().set(0, 0, {'-', 1}), fw.begin(), 0, 0, 'A'}); board solution; int moves = 0; int frustration_moves = FRUSTRATION_MOVES; while (!states.empty()) { /* Check for solutions (all fireworks consumed.) */ while (!states.empty() && states.back().fw == fw.end()) { state& s = states.back(); /* Did we find a better solution? */ if (solution.area() == 0 || s.b.length() < length || (s.b.length() == length && s.b.area() < area) ) { solution = move(s.b); moves = 0; length = solution.length(); area = solution.area(); } states.pop_back(); } /* Expand the top state. */ if (!states.empty()) { state s = move(states.back()); states.pop_back(); add_possible_moves(states, length, area, s); } /* Getting frustrated? */ ++moves; if (moves > frustration_moves) { /* Get rid of some data. */ states.erase( states.begin() + states.size() * FRUSTRATION_STATES_BACKOFF, states.end() ); frustration_moves *= FRUSTRATION_MOVES_BACKOFF; moves = 0; } } /* Print solution. */ { lock_guard<mutex> lg(lock); cout << input << endl; if (solution.area()) cout << solution; else { cout << "FAILED!" << endl; ++failures; } cout << "Length: " << length << ", Area: " << area << "." << endl << endl; total_length += length; total_area += area; } } } int main(int argc, const char* argv[]) { thread threads[THREAD_COUNT]; mutex lock; int total_length = 0, total_area = 0, failures = 0; for (int i = 0; i < THREAD_COUNT; ++i) threads[i] = thread(thread_proc, ref(lock), ref(total_length), ref(total_area), ref(failures)); for (int i = 0; i < THREAD_COUNT; ++i) threads[i].join(); cout << "Total Length: " << total_length << ", Total Area: " << total_area << ", Failures: " << failures << "." << endl; } ``` --- ## Python ## Total Length: 17387, Total Area: 62285, Failures: 44. --- **Sample output:** ``` a 6 b 8 c 11 d 11 e 11 f 11 g 12 h 15 i 18 j 18 k 21 l 23 m 26 n 28 o 28 p 30 q 32 r 33 s 33 t 34 ------a |----f |---c b|||---h |dg | e |-j |---k i | |---m l |-o |--p n |--s |-r q| t Length: 45, Area: 345. ``` --- **Full output:** <http://pastebin.com/raw.php?i=mgiqXCRK> --- For reference, here's a much simpler approach. It tries to connect fireworks to a single main fuse line, creating a "staircase" shape. If a firework can't connect to the main line directly (which happens when two or more fireworks light at the same time) it traces back the main line looking for a point where it can branch perpendicularly down or to the right (and fails if no such point exists.) Unsurprisingly, it does worse than the brute-force solver, but not by a *huge* margin. Honestly, I expected the difference to be somewhat bigger. Run with: `python fireworks.py`. ``` from __future__ import print_function import sys total_length = total_area = failures = 0 for line in sys.stdin: # Read input. line = line.strip() if line == "": continue fws = line.split(' ') # The fireworks are a list of pairs of the form (<letter>, <time>). fws = [(fws[i], int(fws[i + 1])) for i in xrange(0, len(fws), 2)] # The board is a dictionary of the form <coord>: <tile>. # The first tile marks the "starting point" and is out-of-bounds. board = {(-1, 0): '*'} # The tip of the main "staircase" fuse. tip_x, tip_y = -1, 0 tip_time = 0 # We didn't fail. Yet... failed = False for (fw, fw_time) in fws: dt = fw_time - tip_time # Can we add the firework to the main fuse line? if dt > 0: # We can. Alternate the direction to create a "staircase" pattern. if board[(tip_x, tip_y)] == '-': dx, dy = 0, 1; fuse = '|' else: dx, dy = 1, 0; fuse = '-' x, y = tip_x, tip_y tip_x += dt * dx tip_y += dt * dy tip_time += dt else: # We can't. Trace the main fuse back until we find a point where we # can thread, or fail if we reach the starting point. x, y = tip_x, tip_y while board[(x, y)] != '*': horz = board[(x, y)] == '-' if horz: dx, dy = 0, 1; fuse = '|' else: dx, dy = 1, 0; fuse = '-' if dt > 0 and (x + dx, y + dy) not in board: break if horz: x -= 1 else: y -= 1 dt += 1 if board[(x, y)] == '*': failed = True break # Add the fuse and firework. for i in xrange(dt): x += dx; y += dy board[(x, y)] = fuse board[(x + dx, y + dy)] = fw # Print output. print(line) if not failed: max_x, max_y = (max(board, key=lambda p: p[i])[i] + 1 for i in (0, 1)) for y in xrange(max_y): for x in xrange(max_x): print(board.get((x, y), ' '), end = "") print() length = len(board) - len(fws) - 1 area = max_x * max_y else: print("FAILED!") failures += 1 length = sum(map(lambda fw: fw[1], fws)) area = fws[-1][1] ** 2 print("Length: %d, Area: %d.\n" % (length, area)) total_length += length; total_area += area print("Total Length: %d, Total Area: %d, Failures: %d." % (total_length, total_area, failures)) ``` [Answer] # Python3 ## Total length: 8343; Failures: 4; Total time: ~140.34 seconds ``` import collections, re, time def shadow(board): return [["#" if b not in ['|', '-', ' '] else b for b in i] for i in board] def full_length(s): return len(re.findall('\-|\|', s)) def adjust_board_size(_x, _y, board, mappings, cells): if _y < 0: _y = 0 board = [[' ']+i for i in board] mappings = {(x, y+1):b for (x, y), b in mappings.items()} cells = [(x, y + 1) for x, y in cells] if _x < 0: _x = 0 board = [[' ' for _ in board[0]]] + board mappings = {(x + 1, y):b for (x, y), b in mappings.items()} cells = [(x + 1, y) for x, y in cells] if _x == len(board): board = board + [[' ' for _ in board[0]]] if _y == len(board[0]): board = [i + [' '] for i in board] return _x, _y, eval(str(board)), eval(str(mappings)), eval(str(cells)) def draw_path(f, x_y, dist, d, depth, board, mappings, cells) -> iter: q = [(*x_y, *i, 0, board, mappings, cells, None) for i in d[:depth]] o_dist = mappings[x_y] while q: x, y, X, Y, prog, board, mappings, cells, smb = q.pop(0) if prog == dist: _x, _y = x + X, y + Y _x, _y, board, mappings, cells = adjust_board_size(_x, _y, board, mappings, cells) if (_x, _y) not in cells: cells.append((_x, _y)) board[_x][_y] = f yield board, mappings, cells continue if smb is None: q.append((x, y, X, Y, prog, board, mappings, cells, '|' if board[x][y] == '-' else '-')) continue if (x+X, y+Y) in cells: q.extend([(x, y, X, Y, prog, board, mappings, cells, None) for X, Y in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (x + X, y + Y) not in cells and x + X >= 0]) continue _x, _y = x + X, y + Y _x, _y, board, mappings, cells = adjust_board_size(_x, _y, board, mappings, cells) prog += 1 board[_x][_y] = smb mappings[(_x, _y)] = o_dist + prog cells.append((_x, _y)) q.append((_x, _y, X, Y, prog, board, mappings, cells, smb)) def solver(t, depth = 3, option_depth = 2, board_depth = 3, breadth = -1) -> None: t = t.split() t = {t[i]:int(t[i+1]) for i in range(0, len(t), 2)} u_t = {b:a for a, b in t.items()} q = collections.deque([([['-' for _ in range(a)]+[b]], (mp:={(0,i):i+1 for i in range(a)}), [*mp], {*t}-{b})for a, b in [*u_t.items()][:len(u_t) if breadth == -1 else breadth]]) seen = [] results = [] best_score = None while q: board, mappings, cells, f_works = q.popleft() #print('\n'.join(map(''.join, board))) if not f_works: results.append((board, mappings)) best_score = len(mappings) if best_score is None else min(len(mappings), best_score) #print('got solution!') continue options = collections.defaultdict(list) for f in f_works: for (x, y), v in mappings.items(): if (d:=[(X, Y) for X, Y in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (x+X, y+Y) not in cells and ((board[x][y] == '-' and X) or (board[x][y] == '|' and Y))]): if v + 1 == t[f]: options[f].append(((x, y), 1, d)) elif v < t[f]: options[f].append(((x, y), t[f] - v, d)) #print(sorted([(a, min(b, key=lambda x:x[1])) for a, b in options.items()], key=lambda x:x[1][1])) #TODO: group on ties for best performance (include a suboptimal?) for f, ((x, y), dist, d), B in sorted([(a, min(b, key=lambda x:x[1]), sum(j[1] == min(b, key=lambda x:x[1]) for j in b)) for a, b in options.items()], key=lambda x:x[1][1])[:option_depth]: #print(B) if best_score is None or len(mappings) + dist < best_score: all_boards = [] for _board, _mappings, _cells in draw_path(f, (x, y), dist, d, depth, board, mappings, cells): if (S:=shadow(_board)) not in seen: all_boards.append((_board, _mappings, _cells, f_works - {f}, S)) for _board, _mappings, _cells, _f_works, S in all_boards[:board_depth]: seen.append(S) q.appendleft((_board, _mappings, _cells, _f_works)) return best_score, sum(t.values()) ``` ### Usage: ``` total_length, failed = 0, 0 full_failed = [] t = time.time() c = 0 for i in filter(None, cases.split('\n')): c += 1 print(c) result, f = solver(i.strip(), depth = 1, option_depth = 1, board_depth = 1, breadth = 1) if result is None: result, f = solver(i.strip(), depth = 1, option_depth = 2, board_depth = 1, breadth = 1) if result is None: failed += 1 total_length += f else: total_length += result print(total_length, failed, time.time() - t) ``` ]
[Question] [ ## Goal In this competition, you are given a random room with one candle inside. The goal is to write the shortest program (this is golf) that determines what parts of the room are illuminated by the candle, by replacing the dark spots with `@`'s. The program should take a room from STDIN, with the output printed to STDOUT. ## Example Input/Room ``` +------+ | C | | +--+ | \ | +---------+ ``` The candle is represented with a `C`, and the walls/mirrors are represented with `|`,`-`,`/`, or `\`. The walls themselves are mirrors. The corners of the room are represented with a `+`. Rooms will never have diagonal walls, and light will never be able to escape out of the room. Also, the first character on a line is always going to be part of the wall off the room. The absolute last character on each line is going to be the opposite wall of the room. No characters between these two are going to be outside of the room. ## Light and Reflection The candle emits eight (laser-like) beams of light in eight basic directions: N, S, E, W, NE, SE, SW, and NW. These rays of light bounce off of the mirrors as described below: ``` Old Direction of Travel | Mirror | New Direction N S E W NE SE SW NW / E W N S -- -- -- -- N S E W NE SE SW NW \ W E S N -- -- -- -- N S E W NE SE SW NW | - - - - NW SW NE SW N S E W NE SE SW NW - - - - - SE NE SW NE ``` A `-` represents the light being absorbed. Light is always absorbed by C's or +'s. It is important to note that the lights reflects off of a mirror only when it is occupying the same space as the mirror. These rules are much easier to understand when you draw the reflection out on paper. ## Example Output As output, the program should print an image of the illuminated room, with dark spots written as an `@`, light spots left blank, and mirrors unaffected. For the above example, the output would be: ``` +------+ | C | |@ @ +--+ | @\ | +---------+ ``` This means that, if you drew out the beams of light, they will never reach the spaces marked with `@`. ## More examples ``` Input: +-----+ | | | | | C | | | | | +-----+ Output: +-----+ | @ @ | |@ @| | C | |@ @| | @ @ | +-----+ Input: +-----+ | \ | |/ C \+-+ | | | \ - ++ +------+ Output: +-----+ | \ @| |/ C \+-+ | @| | @\ -@++ +------+ ``` [Answer] ## Python, 292 chars ``` import sys R='' for x in sys.stdin:R+='%-97s\n'%x[:-1].replace(' ','@') M={'/':'-98/d','\\':'98/d'} for d in(-98,-1,1,98,99,97,-97,-99): if d>98:M={'|':'d^2','-':'-d^2'} p=R.find('C') while 1: p+=d if R[p]in' @':R=R[:p]+' '+R[p+1:] elif R[p]in M:d=eval(M[R[p]]) else:break print R, ``` Reads in the room, makes it rectangular, then walks out from the candle in all directions. M contains the active mirror characters and their effect (`/\` for the cardinal directions, `|-` for the others) Can handle rooms up to 97 characters wide. [Answer] ## c -- 504 Relies on K&R default function calling semantics. Very straight forward implementation except for the fiddle stuff with bouncing the rays. ``` #define N M[x+y*97] #define Y abs(y) #define O M[c]== #define E else break; int j[]={-98,-97,-96,-1,1,96,97,98},c,x,y,p,s,M[9409];main(){for(; (c=getchar())!=-1;){if(c==10)x=0,++y;else{if(c==67)p=x+y*97;if(c==32) c=64;N=c;++x;}}for(x=0;x<8;++x){y=j[x];c=p;do{c+=y;if(O'@')M[c]=32;s=y/Y; if(O 92)if(y%2){y=s*(98-Y);}E if(O'/')if(y%2){y=s*-(98-Y);}E if(O'|') if(~y%2){y=s*(97+(97-Y));}E if(O'-')if(~y%2){y=s*-(97+(97-Y));}E}while (!(O'+')&&!(O'C'));}for(y=0;x=0,N!=0;++y){for(;N!=0;++x)putchar(N); putchar(10);}} ``` ## Ungolfed ``` //#include <stdio.h> int j[]={ -98, -97, -96, /* Increments to move around the array */ -1, 1, 96, 97, 98}, c, x, y, p, s, /* take advantage of static initialization to zero */ M[9409]; /* treat as 97*97 */ main(){ /* read the map */ while((c=getchar())!=-1/*Assume the deffinition of EOF*/){ /* putchar(c); */ if (c=='\n') x=0,++y; else { if (c=='C') p=x+y*97; /* set start position */ if (c==' ') c='@'; /* The room starts dark */ M[x+y*97]=c; ++x; } } /* printf("Start position is %d (%d, %d)\n",p,p%97,p/97); */ /* Now loop through all the direction clearing '@' cells as we * encounter them */ for(x=0;x<8;++x){ y=j[x];c=p; /* y the increment, c the position */ /* printf("\tposition %d (%d, %d) '%c'\n",c,c%97,c/97,M[c]); */ /* printf("\tdirection = %d (%d, %d)\n",y,-(abs(y)-97),(y+98)/97-1); */ do { c+=y; /* printf("\t\tposition %d (%d, %d) '%c'\n",c,c%97,c/97,M[c]); */ /* We ought to do bounds checking here, but we rely on * * the guarantee that the room will be bounded instead. */ if(M[c]=='@') M[c]=' '; /* The reflections are handles * + Stop or not stop based on the even/oddness of the increment * + New direction is a little fiddly, look for yourself */ s=y/abs(y); /* sign of y (need for some reflections) */ if (M[c]=='\\') if (y%2){ y=s* (98-abs(y)); }else break; if (M[c]=='/') if (y%2){ y=s*-(98-abs(y)); }else break; if (M[c]=='|') if (~y%2){y=s* (97+(97-abs(y)));}else break; if (M[c]=='-') if (~y%2){y=s*-(97+(97-abs(y)));}else break; /* printf("\t\t\tdirection = %d (%d, %d)\n",y,97-abs(y),(y+98)/97-1); */ } while (!(M[c]=='+')&&!(M[c]=='C')); /* printf("\t...hit a %c. Done\n",M[c]); */ } /* print the result */ for(y=0;x=0,M[x+y*97]!=0;++y){ for(;M[x+y*97]!=0;++x) putchar(M[x+y*97]); putchar('\n'); } } ``` ## Validation ``` $ gcc -g -o candle candle_golfed.c $ for f in candle_room*; do (./candle < $f) ; done +------+ | C | |@ @ +--+ | @\ | +---------+ +------+ | C | |@ @ +--+ | /@ @ @ | +---------+ +------+ | @/ | |@ @ +--+ | C | +---------+ +------+ | \@ @| |@ @ +--+ | C | +---------+ +-----+ | @ @ | |@ @| | C | |@ @| | @ @ | +-----+ ``` ]
[Question] [ It is easy to describe a finite state machine that recognizes multiples of 9: keep track of the digit sum (mod 9) and add whatever digit is accepted next. Such a FSM has only 9 states, very simple! By the equivalence between FSM-recognizability and regular languages, there is a regular expression for multiples of 9. However, any such regular expression is likely... very... long. As in, likely on the order of a gigabyte. There is a worked example at <https://www.quaxio.com/triple/> for multiples of 3. At the bottom of the page, the author provides a somewhat "hand-optimized" solution that's a bit shorter than the naive conversion from FSM to regex. ### The challenge: You must make a regex to detect multiples of 9. Since such a regex is expected to be very long, I ask that you provide a program that can print out your regex. (If you really want to give a whole regex, perhaps host it elsewhere and link it here!) You must be able to tell us the exact character count of your program's output -- so having a program that simply tries all regexes up to a certain length, until it finds one that works, is not acceptable unless it runs quickly enough that you can run it to completion and give us the resulting regex length! Points are for having the shortest output regex, not based on program length, of course. Since the regex is the "program" I am asking for, and it's just too long to conveniently transmit here, I'm still tagging this code-golf. Rules: * The input will only include characters matching `[0-9]*`. * Your regex should *match* multiples of 9, but not anything else. Cases that aren't made entirely of the digits 0-9 and are invalid inputs can either match or fail as you wish. * Given the motivation that it's easily recognized by a DFA, the resulting regex must actually be *regular expression* in the more theoretic terminology, that is, only operators under which regular languages are closed. To be precise, the only things that are allowed: + Literals, character ranges (`[ab]`, `[a-f]`, `[^k]`), Kleene star (`*`), anchors (`^` and `$`), grouping via parentheses, alternation (`|`), optional terms (`?`), one-or-more terms (`+`), lookaheads (`(?=)`), negative lookaheads (`(?!)`), lookbehinds (`(?<=)`), negative lookbehinds (`(?<!)`), conditionals (as in <https://www.regular-expressions.info/conditional.html> -- `(?(?=test)then|else)` ), and backreferences of bounded length (see below). * Examples of things that are *not* allowed: + Backreferences of arbitrary length, forward references, Recursion, subroutines, looping constructs, executable code, any variation of 'eval', or built-in constructs for casting the string to an arithmetic value. * Backreferences that can be shown to have a bounded-length binding string are acceptable, as they can be stored in finite state and do not alter the regularity of the language. For instance, the regex `(..2.[3-5])4\1.\1` is acceptable, as there is bound length on the capturing group `\1`. This is a regular construction. A construct such as `(2*)0\1` is not acceptable, as the captured group cannot be stored in finite state. * Your regex is free to accept or reject integers with extraneous leading zeroes as you wish. However, the string `"0"` must be accepted. [Answer] # [Haskell](https://www.haskell.org/), ~~207,535~~ 202,073 bytes 5,462 bytes saved by using `0|9` instead of `[09]` where possible. ``` digits n | x == 0 = "0|9" | otherwise = show x where x = mod n 9 regex 0 = "[09]*" regex n = (regex' n (-1) (-1)) ++ "*" regex' 0 start end = digits (end - start) regex' n start end = '(':(regex' 0 start end) ++ (concat ['|':(regex' (n-x) (start-x) (-1)) ++ (regex (n-x)) ++ (regex' (n-x) (-1) (end-x)) | x <- [1..n]]) ++ ")" main = do putStr ("^" ++ (regex 8) ++ "$") ``` [Try it online!](https://tio.run/##lVDBqoMwELznK4bwwOQVi73VUr/iHcWC1FClNSkmDz3473ZNrC301D2Ezezs7OzWpb2q222aqubSOAvNgBEDsgwJKDLwZEy5R42rVdc3VhFqa9NjILgnTM0NaE0FjZSxTl3UQO3Umydp8csXRBMifBpRLuKd9I/EZgNOLLbUElhXdg5KV9SxGBPzLw4VyVaVd2YkooP41PD64mz0uXTIo/FFEjoeyINn@uzpJhBCXTJ8HavEOsMvS2ZmQX/gY4x8t93qogj7S9q/LZv5RpWhkfd/9@c6CH7ib472gfzD5TQ9AA "Haskell – Try It Online") Just a quick adaptation of the regex given in the footnotes of the linked article to get things started. [Pastebin of output regex](https://pastebin.com/hfDSKRDC), courtesy of Herman Lauenstein. While I have not been able to test the full regex, modifying the program to check divisibility by 3 instead gives something exactly equivalent to the regex I based this on. Furthermore, modifying the program to check the digit sum's divisibility by 4 or 5 also seems to work on the numbers I tested it on. ]
[Question] [ # Pokerface ### Introduction Leo enjoys playing poker, but his job at Tech Inc. is too demanding for him to learn how to play well. Leo, being a computer scientist, is not discouraged. He decides to take more time than it would have taken to just learn poker, and use it to write a poker bot to help him play better. But now Leo has a problem: in order to understand how to play a bit better, Leo needs to observe multiple games of multiple "people," but the "people" need different play styles to improve the quality and reality of the game. ### The Challenge Leo recalls that there is actually a website dedicated to programming challenges, and is enlisting your help! Your job is to write a program which plays "Pokerface" a modified version of 5-card poker. The program will take input as a 5-card hand in whatever format you wish, after which the program will output: * Exactly (case-sensitive) "true" "1" or "t" if the player wishes to exchange cards, any other non-empty output otherwise. * If true, list of indices of cards and/or card names the player wishes to exchange. * A single number between 0 and 3, which specifies how many additional cards the player wants. * Print out the hand the player wishes to use. (See formatting below) ### Pokerface rules * Since pokerface is a text-based adventure game, cards must be presented in a consistent way. Cards are represented by two character codes, the first character is the suit, and the second is the name of the card. + Cards: - 2-9 = 2-9 - 10 = T - Jack = J - Queen = Q - King = K - Ace = A + Suits: - Spades = S - Clubs = C - Hearts = H - Diamond = D So the ace of spades would be SA, the 10 of hearts is HT, the 4th of diamonds is D4, etc. * A single round of Pokerface consists of four steps: + The deck is reshuffled and a five card hand is dealt to each player. + Each player is given the chance to exchange as many cards as they want. + Each player is given the chance to gain up to three more cards. + Each player must reveal their best hand. * The best hand wins, and gains that player a point. In the event of a tie, both players get a point. * In a single game, ten rounds are played and the player with the most points wins and gains a single "win point." In the event of a tie, both players gain a win point. * Leo doesn't really have a large amount of money, so your bot can assume that this is a perfect world with no betting. ### Hands * Hands are exactly 5 cards in length (initial input and final output). * Hands are ranked consistent with the rules described [here](http://www.cardplayer.com/rules-of-poker/hand-rankings). ### Input / Output * Leo only knows Java, so your program must be executable via the [Process API](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html) (command line), and use STDIN and STDOUT for input and output, respectively. * For each step of input and output detailed above, the input and output must each exist on one line. * There must be at least one trailing new line after the final output. (This is due to the way input is read from STDIN) * No extraneous input/output is allowed, other than trailing and leading spaces. The parser simply does not understand things like `final_hand=...` or `draw 0`. * When drawing, output is a single integer, when exchanging output is a list of integers and/or cards defined below, and when being dealt the original hand, output is a list of cards defined below. * All input/output numbers must be positive integers in base 10. * You may define the format for card input (see post format below). * True is defined as exactly "true," "1" or "t" and false is any other non-empty value. * During the exchange step: + Card indices must be output with at least one space between them (e.g. `3 4 0`) + Card names must be output with at least one space between them (e.g. `H4 S8`) + Card names and indices may be mixed in the output (e.g. `0 H7 3 D3`) + Trailing and leading spaces are allowed. + The input as a result of the player outputting the above will be formatted as specified by the `bot.jlsc` file, in the same order as requested * The number of cards a player wants to add to their hand can have leading and trailing spaces. * Hands must be output with at least one space between them (e.g. `H4 D5 CA`), trailing spaces and leading spaces are allowed. * Hands do not need to be output in proper order (e.g. `H4 D4 C4 DA SA` and `H4 DA D4 SA C4` both represent 4, 4, 4, Ace, Ace, which is a full house). * If you wish to build a strategy by analyzing opponents hands, you may store data in a `<botname>/data` directory. + After competing bots have displayed their hands, they will be written to every bots data directory, in hands.txt, with each hand on a new line (separated by \n). The file will be encoded in US\_ASCII. * After your bot requests new cards or exchange cards, the cards will be input depending on what format you specify in the `bot.jlsc` file. ### Post Format * Every post must include two things: + The source code of your bot, or a link to a public facing repository. + A zip file containing: - The compiled/executable version of your bot (If the file is a .exe or other non-de-compilable file, please just include compilation instructions in your post). - A `bot.jlsc` file, see below (side note: the .jlsc extension is just because of a side project of mine, a configuration format. The file below matches the proper syntax, so don't worry). + The .zip file must be named the same as your bot. * If you don't have access to windows or some other zipping utility, or can't make a .zip for whatever reason, just include the text of the bot.jlsc file in your post --- bot.jlsc file: ``` name= "Botty" link= "example.com" cmd= "java -jar Botty.jar" input_hand= "${0} ${1} ${2} ${3} ${4}" input_1= "${0}" input_2= "${0} ${1}" input_3= "${0} ${1} ${2}" input_4= "${0} ${1} ${2} ${3}" ``` --- Where: * "cmd" is the **windows** command line command to run your bot. Note that your bot will be in directory `<botname>`, so adjust the command accordingly. * "name" is the name of your bot. * "link" is the link to your answer, you'll have to edit this in after posting. + "input\_hand" is how you want the original dealing to be formatted (with ${#} representing cards 0-4). * "input\_1" is how you want the input of one additional card to be formatted. * "input\_2" is how you want the input of two additional cards to be formatted. * "input\_3" is how you want the input of three additional cards to be formatted. * "input\_4" is how you want the input of four additional cards to be formatted. ### Specifics * [These loopholes are disallowed (see 'common pitfalls')](http://meta.codegolf.stackexchange.com/a/8904/56085) * You may not write a bot the will always output the best hand possible, every time, within the rule set. (i.e. no long-running brute-force bots, nothing should be quite as 'good' as LeoBot) * Your bot should run in ~100 ms or less (Lenient on this point, max of ~1 second) * Any output of the bot after its chosen hand will be ignored. * Standard loopholes are disallowed. * Yes, I know linux is better, but I have a windows PC, so be sure the compiled/executable version of your program can be run from the windows command line. + I already have python and java installed on my computer, but I'm willing to update to new versions and install other environments, so please specify what type of environment your program requires. * You may not write a bot which does the same thing as another bot in every case. Spam bots are allowed, but discouraged. * Your bot may only use cards it has. Cards lost through exchange or not dealt to begin with are invalid output in the final hand. * Input and output may only contain ASCII characters. ### Tournaments * Tournaments will be run when I get the time (my schedule is nearly as packed as Leo's, so this my be a little infrequent. Sorry for the inconvenience.). * Bots will be pit against eachother in 4 person games, and there will be one game for each possible subset of bots (i.e. lots of games). + This process will be repeated five times. + Due to the way the tournament handler makes the groups of bots, up to three filler bots will be added to make the number of bots divisible by 4. These bots will simply return the hand they were originally dealt. * After every round and game is run, the scores of the bots will be computed based on the number games they won. + Multiple bots can share a position (ties for first won by first posted). * After a tournament finishes, the scores will be appended to the bottom of this post. ### Scoring Normal KoTH rules. The bot(s) that win the most games win the challenge. ### LeoBot Leo's bot is pretty smart. It doesn't exchange any cards, that's too hard, but it does request the maximum number of additional cards, and it determines the best possible hand it can make, and plays that hand. The main logic of leobot is below. ``` package com.gmail.socraticphoenix.pokerface.leobot; import com.gmail.socraticphoenix.pokerface.lib.card.Card; import com.gmail.socraticphoenix.pokerface.lib.card.Deck; import com.gmail.socraticphoenix.pokerface.lib.rule.HandRegistry; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class LeoBot { public static void main(String[] args) { List<Card> hand = new ArrayList<>(); Scanner scanner = new Scanner(System.in); hand.addAll(Card.parseHand(scanner.nextLine())); System.out.println(false); System.out.println(3); hand.addAll(Card.parseHand(scanner.nextLine())); List<List<Card>> possibleHands = LeoBot.getSubsets(hand, 5); System.out.println(Deck.toString(possibleHands.stream().sorted((a, b) -> HandRegistry.determineWinner(b, a).comparable()).findFirst().get())); } private static <T> void getSubsets(List<T> superSet, int k, int idx, List<T> current, List<List<T>> solution) { if (current.size() == k) { solution.add(new ArrayList<>(current)); return; } if (idx == superSet.size()) return; T x = superSet.get(idx); if (!current.contains(x)) { current.add(x); } getSubsets(superSet, k, idx + 1, current, solution); current.remove(x); getSubsets(superSet, k, idx + 1, current, solution); } public static <T> List<List<T>> getSubsets(List<T> superSet, int k) { List<List<T>> res = new ArrayList<>(); getSubsets(superSet, k, 0, new ArrayList<T>(), res); return res; } } ``` Note that if LeoBot consistently wins the tournaments, and there are a good amount of entries, I'll stop including him in the running. ### Important Links * [Tournament bot and library](https://github.com/SocraticPhoenix/Pokerface) * [Leo's bot](https://github.com/SocraticPhoenix/Pokerface-LeoBot) ### Disclaimer Leo and Tech Inc. are **story elements** and any resemblance to real-life companies or people is purely unintentional. (However, when Leo's 'situation' adds or subtracts conditions from the question, those are actually part of the question...) [Answer] # (Python), Pairbot, not quite competing (I don't know how to make cmd commands and stuff) Pairbot will compete as soon as someone assists with the bot.jlsc, and zip files etc. --- Pairbot knows that you don't always get good hands. He knows good hands are rare. Pairbot knows pairs and other duplicates are some of the best hands. Pairbot also knows the lowest hand you can get is a seven high, so he knows if he has 6 high, that's actually a straight (pairbot doesn't know why he knows that). He also knows if his lowest card is 10, (with no pairs), that's also a straight (pairbot knows he can get royal flush this way). Pairbot checks mainly for same number dupes, but also checks for two types of straights in special cases. ``` card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,} straight=False def card_valuing(item): return card_values[item[1]] input_list=input().split() pairs_to_keep=[] for item in input_list: if sum(item[1]==card[1] for card in input_list)>1: pairs_to_keep+=[item] cards_to_remove=input_list for item in pairs_to_keep:cards_to_remove.remove(item)#we want to remove all non pairs hand=pairs_to_keep if pairs_to_keep==[]: input_list.sort(key=card_valuing, reverse=True) if card_values[input_list[0][1]]==6: straight=True hand=input_list elif card_values[input_list[-1][1]]==10: straight=True hand=input_list else: print("true\n"+" ".join(input_list[1:])) hand+=input_list[0]+input().split() elif input_list!=[]: print("true\n"+" ".join(input_list)) hand+=input().split() else:print(0, end=', ') if straight:print("0\n0\n"+" ".join(hand)) else: print("3") hand+=input().split() same_number_dict={} #holds the amount of each type (A, 2, 3, etc.) def dict_value(item): return int(same_number_dict[item[1]])*100+card_values[item[1]] for card in hand: same_number_dict[card[1]]=sum(card[1] == item[1] for item in hand) hand=list(sorted(hand, key=dict_value, reverse=True)) final_hand =[] last_number=hand[0][1] hand_taken=0 while hand_taken < 5: if last_number==hand[0][1]: final_hand+=[hand[0]] hand=hand[1:] hand_taken+=1 else: for card in hand: if same_number_dict[card[1]]>5-hand_taken: same_number_dict[card[1]]=5-hand_taken hand=list(sorted(hand, key=dict_value, reverse=True)) last_number=hand[0][1] print(" ".join(final_hand)) ``` --- Format for input is the same as in the example: separated by spaces --- If Socratic Phoenix could assist with the file stuffs, that would be good [Answer] # Plumber, Python Plumber is all about flushes. Plumber also prioritises higher value cards (meaning he can sometimes get straight flushes, especially royal ones (should they occur).) Plumber is pretty much messed if he doesn't get a flush, except that he might be lucky enough for a straight. Plumber will get flushes about 20% of the time, if calculations by *Sherlock9* are correct ``` hand=input().split() suit_in_hand={"S":0,"C":0,"D":0,"H":0} card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,} def value_sort(x): return card_values[x[1]] def suit_sort(x): return suit_in_hand[x[0]] for card in hand: suit_in_hand[card[0]]+=1 hand.sort(key=suit_sort, reverse=True) print(" ".join(hand[suit_in_hand[hand[0][0]]:])) hand=hand[:suit_in_hand[hand[0][0]]] for new_card in input().split(): hand+=[new_card] suit_in_hand[new_card[0]]+=1 print(3) for new_card in input().split(): hand+=[new_card] suit_in_hand[new_card[0]]+=1 hand.sort(key=value_sort, reverse=True) hand.sort(key=suit_sort, reverse=True) print(" ".join(hand[:5])) ``` --- Also takes input separated by spaces like other my two bots [Answer] ## LadyGaga, Python 3 * Is somewhat blind to suits * Has a dress full of bugs * And likes to play Poker Face once in a while ``` from math import ceil as f M=lambda A:max(set(A),key=A.count) K=lambda A:A.count(M(A)) O=lambda A:range(len(A)) J=lambda A:A[0]+str(U(A[1])) X={"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"T":10,"J":11,"Q":12,"K":13,"A":14} def V(A):return([A[0]]+[int(X[A[1]])]) def U(c): if c==10:c='T' if c==11:c='J' if c==12:c='Q' if c==13:c='K' if c==14:c='A' return(c) def P(A): S=[];C=[];t=len(A) for x in A:S.append(x[0]);C.append(x[1]) B=[0]*9;q=len(set(C));p=K(C);D=list(set(C));D.sort() B[2]=1/f(13**(4-p));B[6]=1/f(13**(3-p));B[8]=1/f(13**(2-p)) if (p,q)==(2,4):B[3]=1/1100;B[7]=5/34 if (p,q)==(3,3):B[3]=1/169;B[7]=1/169 if (p,q)==(4,2):B[3]=1/13;B[7]=1 if (p,q)==(2,3):B[3]=5/169;B[7]=1 if (p,q)==(3,2):B[3]=1;B[7]=1 for x in O(D):D[x]-=x j=M(D);h=K(D)-5;B[5]=13**h for x in O(D): if j+h<D[x]<j-h and D[x]!=j:B[5]*=13 W=K(S);B[4]=(4**(W-t))*(13-W)/52 return(B,M(S)) def E(B,h,u): x=0;D=[];C=[] while 1: k=list(C) C=[] while 1: p=list(B);del p[x] if len(D)==3:break if P(p)[0][h]>=P(B)[0][h]:C.append(B[x]) x+=1 if x>len(p):break if len(C)==0:break for x in O(C): if k==C or not((u in C[x])and(len(C)-1)):D.append(C[x]);del B[B.index(C[x])] return(D) s=input() A=s.split(' ') b=list(map(V,A));G,u=P(b);F=[649739,72192,4164,693,508,254,46.3,20,1.4];H=[] for x in O(F):F[x]=1-((1-(1/F[x]))**4) for x in O(F):H.append(G[x]-F[x]) Y=H.index(max(H));p=[] e=E(list(b),Y,u);g=list(e) for x in O(e):e[x]=J(e[x]) print(' '.join(e)if len(e)else'') for x in g: if x in b:del b[b.index(x)] s=input() if len(s): A=s.split(' ') b+=list(map(V,A)) print(3) s=input() A=s.split(' ') b+=list(map(V,A));G,u=P(b);H=[] for x in O(F):H.append(G[x]-F[x]) Y=H.index(max(H)) e=E(list(b),Y,u) for x in e: if x in b:del b[b.index(x)] for x in O(b):b[x]=J(b[x]) print(' '.join(b[:5])) print() ``` + (I/O) modeled after PlumberBot -Edit: Extensive bugfixes thanks to Destructible Watermelon -Edit: Due to new rules, a trailing newline after the final output [Answer] # LuckyBot, Python Pairbot invited his buddy Luckybot, who sprang for the chance. Luckybot had watched a lot of fictional poker, and reckoned he'd figured out the secret to poker: luck. Everyone knows the real pros (James Bond, for example) really rely and getting good hands, not skill. Hence, he doesn't look at his cards, and tries to pack as much good luck into them as possible --- ``` lucky_number=24 #IMPORTANT from random import randint as roll def lucky_shuffle(i): return sorted(i, key=lucky_dice) def lucky_dice(seed): return sum(roll(1,6)for i in range(roll(1,6))) hand=lucky_shuffle(input().split()) throw=lucky_dice(lucky_number)%5 print("true\n"+" ".join(hand[throw:])) hand=hand[:throw]+lucky_shuffle(input().split()) hand=lucky_shuffle(hand) hand=lucky_shuffle(hand) #One more for good luck hand=lucky_shuffle(hand) #maybe one more hand=lucky_shuffle(hand) #I got a good feeling about this one hand=lucky_shuffle(hand) hand=lucky_shuffle(hand) #I think I'm done hand=lucky_shuffle(hand) #for real this time hand=lucky_shuffle(hand) print("3") hand=hand+lucky_shuffle(input().split()) #All right, I got a real good feeling about this, #let me shuffle some more luck into them cards! def extra_super_lucky_shuffle(item): return lucky_shuffle(lucky_shuffle(lucky_shuffle(\ lucky_shuffle(lucky_shuffle(lucky_shuffle(\ lucky_shuffle(lucky_shuffle(lucky_shuffle(item))))))))) def super_duper_extra_ultra_uber_luckyshuffle(item): return extra_super_lucky_shuffle(extra_super_lucky_shuffle(\ extra_super_lucky_shuffle(extra_super_lucky_shuffle(item)))) hand=super_duper_extra_ultra_uber_luckyshuffle(super_duper_extra_ultra_uber_luckyshuffle(hand)) #cmoooooooooooooooon print(hand[:5]) ``` ]
[Question] [ A bunch of cars are lined up at a 4-way stop sign waiting to proceed. Everyone is confused about who gets to go next, who is going which way, etc. Clearly suboptimal. Your job is to schedule the traffic at the stop sign in an optimal fashion. You receive as input 4 strings of turn requests, one for each of the four cardinal directions. Each request is either `L` for left, `S` for straight, or `R` for right. ``` LLSLRLS SSSRRSRLLR LLRLSR RRRLLLL ``` The first row is the lineup at the North entrance to the intersection. The first car in line wishes to turn left (that is, exit East). The subsequent rows are for the incoming East, South, and West entrances. So the first car coming from the West wishes to exit South. Traffic moves in a series of steps. At each step, you must choose a subset of the cars at the head of their lines to proceed. The cars chosen must not *interfere* with each other. Two cars interfere if they exit the same direction or if they must cross each other's path (given standard right-hand driving rules). So two opposite cars both wishing to go straight may go at the same step. So may 4 cars all wishing to turn right. Two opposite cars can both turn left simultaneously. Your job is to schedule the intersection in a minimum series of steps. For each step, output a line with the incoming cars' compass direction(s) listed. For the example above, the minimal schedule is 14 steps. One minimal schedule is: ``` N [L from North] E [S from East] E [S from East] E [S from East] NESW [L from North, R from East, L from South, R from West] NE [S from North] EW [R from East] NESW [L from North, R from East, L from South, R from West] W [L from West] EW [L from East, L from West] NESW [R from North, L from East, R from South, L from West] NES [L from North, R from East, L from West] NS [S from North, S from South] SW [R from South, L from West] ``` Your program should be able to handle 50 cars in each line in under 1 minute. Input of the 4 strings and output of the schedule may be in any convenient manner for your language. Shortest program wins. A larger example: ``` RRLLSSRLSLLSSLRSLR RLSLRLSLSSRLRLRRLLSSRLR RLSLRLRRLSSLSLLRLSSL LLLRRRSSRSLRSSSSLLRRRR ``` which requires a minimum of 38 rounds. One possible solution: ``` E EW E ESW S NS ES NESW NSW ESW ES NSW NS NS NW EW NSW NS EW NES EW NSW NE E NE EW E E EW EW EW W ESW NSW NSW NS NSW NEW ``` [Answer] **Python, 1219 Bytes** I didn't spend very much time/effort trying to golf this, but I might improve it if other answers start popping up. I use [A\* search](https://en.wikipedia.org/wiki/A*_search_algorithm) with an [admissible heuristic](https://en.wikipedia.org/wiki/Admissible_heuristic), guaranteeing optimality. I am pretty sure (although I haven't bothered to confirm) that the heuristic is also [consistent](https://en.wikipedia.org/wiki/Consistent_heuristic), meaning that it is [*O*](https://en.wikipedia.org/wiki/Big_O_notation)(dynamic programming). The program reads in four lines from STDIN in the format you have specified, and prints the result to STDOUT, also in the format you specified. ``` from heapq import heappush,heappop from itertools import combinations N,E,S,W=range(4) L="L" R="R" T="S" d=[{L:E,R:W,T:S},{L:S,R:N,T:W},{L:W,R:E,T:N},{L:N,R:S,T:E}] b=set([(N,S,W,E),(N,S,E,W),(S,N,W,E),(S,N,E,W),(E,W,N,E),(N,S,W,N),(S,N,E,S),(W,E,S,W)]) for x in list(b):b.add(x[2:]+x[:2]) def v(*a):return a[1]!=a[3] and a not in b i=lambda:raw_input()+'\n' i=map(lambda l:map(lambda e:("NESW"[l[0]],d[l[0]][e]), l[1]),enumerate((i()+i()+i()+i()).split())) q=[] heappush(q,(0,[],i)) while q: h,a,n=heappop(q) m=sum(map(bool,n)) if m==0: print "\n".join(a) break for r in range(4,0,-1): f=False for c in combinations(range(4),r): l=True for i in c: if not n[i]: l=False break if not l:continue l=True for x,y in combinations(c,2): if not v(x,n[x][0][1],y,n[y][0][1]): l = False break if l==False:continue f=True e=list(n) for i in c:e[i]=e[i][1:] heappush(q,(m-r+min(map(len,e)),a+["".join([n[x][0][0] for x in c])],e)) if f:break ``` Example usage: ``` $ time echo "RRLLSSRLSLLSSLRSLR\nRLSLRLSLSSRLRLRRLLSSRLR\nRLSLRLRRLSSLSLLRLSSL\nLLLRRRSSRSLRSSSSLLRRRR" | python 4way.py NES NEW NSW NS NS ESW NS NES NEW NS NES NSW NS NS NSW NW NS NS NS EW ES SW EW EW SW ES EW EW EW EW E EW EW EW EW EW E EW echo 0.00s user 0.00s system 38% cpu 0.002 total python 4way.py 0.02s user 0.01s system 90% cpu 0.030 total ``` ]
[Question] [ **Edit: I will be posting a newer version of this question on `meta-golf` soon. Stay tooned!** **Edit #2: I will no longer be updating the challenge, but will leave it open. The `meta-golf` version is available here: <https://codegolf.stackexchange.com/questions/106509/obfuscated-number-golf>** # Background: Most numbers can be written with only 6 different symbols: * `e` (Euler's Constant) * `-` (Subtraction, Not Negation) * `^` (Exponentiation) * `(` * `)` * `ln` (Natural Logarithm) For example, you could convert the imaginary number `i` using this equation: ``` (e-e-e^(e-e))^(e^(e-e-ln(e^(e-e)-(e-e-e^(e-e))))) ``` # Goal: Given any integer `k` through any reasonable means, output the shortest representation possible of that number using only those 6 symbols. # Examples: ``` 0 => "e-e" 1 => "ln(e)" 2 => "ln(ee)" // Since - cannot be used for negation, this is not a valid solution: // ln(e)-(-ln(e)) -1 => "e-e-ln(e)" ``` # Notes: * Ending parenthesis count towards the total amount of characters. * `ln(` only counts as 1 character. * Everything else counts as 1 character. * `n^0=1` * Order of operations apply * Parenthesis multiplying is acceptable, e.g. `(2)(8)=16`, `2(5)=10`, and `eln(e)=e`. * `ln e` is not valid, you must do `ln(e)` [Answer] # Python 3, 402 bytes ``` from itertools import* from ast import* from math import* v,r=lambda x:'UnaryOp'not in dump(parse(x)),lambda s,a,b:s.replace(a,b) def l(x,y): for s in product('L()e^-',repeat=x): f=r(r(r(''.join(s),'L','log('),')(',')*('),'^','**') g=r(f,'ee','e*e') while g!=f:f,g=g,r(g,'ee','e*e') try: if eval(g)==y and v(g):return g except:0 def b(v): i=1 while 1: r=l(i,v) if r:return r i+=1 ``` Example usage: ``` >>> b(1) 'log(e)' >>> b(0) 'e-e' >>> b(-3) 'e-log(e*e*e)-e' >>> b(8) 'log(e*e)**log(e*e*e)' ``` Note that although the output format may not reflect it, the code properly counts all lengths according to the question's specifications. This is a dumb bruteforce through all the possible lengths of strings. Then I use some replacements so that Python can evaluate it. If it's equal to what we want, I also check to exclude unary negative signs by checking the AST. I'm not very good at golfing in Python, so here's the semi-ungolfed code if anybody wants to help! ``` from itertools import* from ast import* from math import* def valid(ev): return 'UnaryOp' not in dump(parse(ev)) def to_eval(st): f = ''.join(st).replace('L', 'log(').replace(')(', ')*(').replace('^', '**') nf = f.replace('ee', 'e*e') while nf != f: f, nf = nf, nf.replace('ee', 'e*e') return nf def try_length(length, val): for st in product('L()e^-', repeat=length): ev = to_eval(st) try: if eval(ev) == val and valid(ev): return st except: pass def bruteforce(val): for i in range(11): res = try_length(i, val) if res: print(i, res) return res ``` ]
[Question] [ You are a taxicab driver in San Francisco. As is typical of taxicab drivers, you are navigating a grid where the only valid directions you can move are the left, right, up, and down. However, San Fransisco is very hilly so the distance between two adjacent intersections is not necessarily the same. More specifically, the distance between an intersection at altitude `a` and an adjacent intersection at altitude `b` would be `1 + |a - b|`. Your goal is to find all the shortest paths from your origin at the top left of the map to your destination at the bottom right. ## Input A two-dimensional grid of integer altitudes in whichever format is most convenient (two-dimensional array, one-dimensional array with width and/or height, etc.). ## Output A sequence of directions to travel to arrive at the bottom right corner of the input from the top left in the shortest distance possible given the distance between two adjacent intersections of altitudes `a` and `b` is given by the formula `1 + |a - b|`. If there are multiple solutions output all solutions. Though I use `U`, `D`, `L`, and `R` for up, down, left, and right in the examples below your program may use any four distinct strings to represent the directions so long as it is consistent with them in and across all inputs. ## Examples ``` Input: 0 3 0 0 0 0 2 0 2 0 0 0 0 3 0 Output: D D R R U U R R D D Input: 3 Output: <empty> Input: 11 11 11 11 11 11 11 11 11 Output: R R D D R D R D R D D R D R R D D R D R D D R R Input: 7 8 1 -1 0 4 4 6 -1 7 3 4 4 2 8 2 5 2 -1 2 Output: D R D R R D R D R D R D R R ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the shortest byte count wins. [Answer] ## JavaScript (ES6), ~~228~~ ~~212~~ ~~200~~ 194 bytes ``` a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R) ``` ### Input One-dimensional array `a` and width `w` in currying syntax `(a)(w)` ### Output A space-separated list of solutions such as `"DRDRRDR DRDRDRR"` ### Formatted and commented ``` a => w => ( // given an array 'a' and a width 'w' B = 1 / 0, // B = best score so far, initialized as +Infinity ( // F = ( // F = recursive function with: r, // - r = current path (string) p, // - p = current position in grid s, // - s = current score b = a[p] // - b = backup of current cell ) => // p - a.length + 1 ? // if we haven't reached our destination: 1 / b && ( // if the current cell is valid: [...a[p] = 'RDUL'] // invalidate the current cell .map((c, d) => // for each possible direction: d | p % w < w - 1 && // check right boundary d - 3 | p % w && // check left boundary F( // do a recursive call with: r + c, // - new direction appended to the path P = p + [1, w, -w, -1][d], // - updated position s + 1 + Math.abs(b - a[P]) // - updated score ) // ), // a[p] = b // restore current cell value ) // : // else: R = s > B ? // if the current score is worse than B: R // keep the previous solution : s < B ? // if the current score is better than B: (B = s, r) // update best score / store path as new solution : R + ' ' + r // if it's just as good: append path to solution )('', 0, 0), // initial call to F with r = '', p = 0, s = 0 R // return solution ) // ``` ### Test cases ``` let f = a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R) console.log(f([ 0, 3, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 3, 0 ])(5)); console.log(f([ 3 ])(1)); console.log(f([ 11, 11, 11, 11, 11, 11, 11, 11, 11 ])(3)); console.log(f([ 7, 8, 1, -1, 0, 4, 4, 6, -1, 7, 3, 4, 4, 2, 8, 2, 5, 2, -1, 2 ])(5)); ``` ]
[Question] [ ## Background The twelve-coin problem is a classic [balance puzzle](http://en.wikipedia.org/wiki/Balance_puzzle) commonly used in job interviews. The puzzle first appeared in 1945 and was posed to my father by my grandfather when he asked to marry my mother! **In the puzzle there are twelve coins, one of which is either heavier or lighter than the others (you don't know which). The problem is to use a balance scales three times to determine the unique coin.** In some variations, it is also necessary to identify whether the coin is heavier or lighter. The task here involves solving the *general problem* involving *n* coins, using the fewest weighings possible in the worst case. It is not necessary to identify whether the coin is heavier or lighter, only which one it is. Furthermore, you do not have access to any additional coins outside the given set (which, curiously, makes a difference). It turns out that k weighings are sufficient for up to (3^k-1)/2 coins (so 4 weighings in this variation can actually handle 13 coins). Furthermore (and surprisingly), it is possible (but not required here) to select the full set of weighings in advance, rather than have future weighings depend on past results. For descriptions of two possible solutions, see [this paper](http://math.uni.lodz.pl/~andkom/Marcel/Kule-en.pdf) and [this Quora answer](https://www.quora.com/How-can-I-find-the-one-ball-that-is-either-heavier-or-lighter-in-a-group-of-81-balls-by-doing-just-4-weighings-with-a-classic-balance-scale/answer/Uri-Zarfaty). ## Task Write a function or program, taking an integer *n* as input via STDIN, command-line argument or function argument, which solves the problem for *n* coins using the fewest weighings possible in the worst case. The program should: * Print weighings to STDOUT in the format `1,2,3-4,5,6` to indicate the lists of coins on each side of the scale. Any coins not being weighed should not be mentioned. The coins are implicitly numbered from 1 to *n* and need not be printed in numeric order (so `2,1-3,4` is the same as to `1,2-3,4`). * After each weighing the program should wait on an input via STDIN, which should be `<`, `=` or `>`, indicating whether the left side of the scale is lighter, the same, or heavier than the right side. * After the last weighing result, the program should print or return the number of the unique coin. * The program need not handle inconsistent result inputs from the user. * The program need not handle *n* less than 3. ## Example outputs ``` >> 3 1-2 >> = 1-3 >> < 3 # using Quora algorithm >> 13 1,2,3,4-5,6,7,8 >> < 1,2,5-3,4,6 >> > 3-4 >> < 3 # using paper algorithm >> 13 1,2,3,4-5,6,7,8 >> < 2,6,7,9-3,8,10,11 >> > 6,8,10,12-4,5,7,11 >> = 3 ``` ## Scoring Shortest code wins. Standard rules apply. [Answer] # Python 3: 497 bytes ``` I=lambda a,b:input(",".join(a)+"-"+",".join(b)+"\n>> ") def A(a,b): l,L=len(a),len(b) if l+L==1:return(a or b)[0] m=(2*l+1-L)//3;M=m+L-l;x,y,X,Y=a[:m],a[m:2*m],b[:M],b[M:2*M];r=I(x+X,y+Y);return A(a[2*m:],b[2*M:])if r=="="else A(x,Y)if r=="<"else A(y,X) def B(a,n=[]): if len(a)==1:return a[0] m=len(n);l=(len(a)+1+m)//3;x,y,z=a[:l],a[l:2*l-m],a[2*l-m:];r=I(x,y+n);return B(z,a[:1])if r=="="else A(x+z[:1-m],y)if r=="<"else A(y+z[:1-m],x) print(B(list(map(str,range(1,int(input("N= "))+1))))) ``` I suspect this could be shrunk down a bit more, but I don't see any obvious places any more (after about 5 different versions of each function). The code implements a slightly modified version of the algorithm from [this page](https://www.quora.com/How-can-I-find-the-one-ball-that-is-either-heavier-or-lighter-in-a-group-of-81-balls-by-doing-just-4-weighings-with-a-classic-balance-scale/answer/Uri-Granta) using three functions. The `I` function does the IO (printing the options and returning the user's response). The `A` and `B` functions implement the main of the algorithm. `A` takes two lists which differ in size by exactly one element (though either list can be the larger one): one coin in `a` may be lighter than normal, or one coin in `b` may be heavier. `B` does double duty. It takes one list of coins `a` and optionally a second list with a single coin that is known to be the correct weight. The length-rounding behavior needs to be different between the two cases, which caused no end of headaches. The two algorithm functions can find the unusually weighted coin in `k` weighings given inputs of up to the following sizes: * `A`: `3^k` total coins, divided up into two list of `(3^k-1)/2` and `(3^k+1)/2`. * `B`: `(3^k + 1)/2` coins if a known-good coin is supplied, `(3^k - 1)/2` otherwise. The question posed here specifies that we don't have any known-good coins at the start, so we can solve find the bad coin in a set of `(3^k - 1)/2` in `k` weighings. Here's a test function I wrote to make sure my code was not requesting bogus weighings or using more than the number of weighings it was supposed to: ``` def test(n): global I orig_I = I try: for x in range(3,n+1): max_count = 0 for y in range(x*2): count = 0 def I(a, b): assert len(a) == len(b), "{} not the same length as {}".format(a,b) nonlocal count count += 1 if y//2 in a: return "<"if y%2 else ">" if y//2 in b: return ">"if y%2 else "<" return "=" assert B(list(range(x)))==y//2, "{} {} not found in size {}".format(['heavy','light'][y%2], y//2+1, x) if count > max_count: max_count = count print(x, max_count) finally: I = orig_I ``` This prints out the worst-case number of weighings for a given set after testing with each combination of coin and bad weight (heavy or light). Here's the test output for sets of up to 125: ``` >>> test(150) 3 2 4 2 5 3 6 3 7 3 8 3 9 3 10 3 11 3 12 3 13 3 14 4 15 4 16 4 17 4 18 4 19 4 20 4 21 4 22 4 23 4 24 4 25 4 26 4 27 4 28 4 29 4 30 4 31 4 32 4 33 4 34 4 35 4 36 4 37 4 38 4 39 4 40 4 41 5 42 5 43 5 44 5 45 5 46 5 47 5 48 5 49 5 50 5 51 5 52 5 53 5 54 5 55 5 56 5 57 5 58 5 59 5 60 5 61 5 62 5 63 5 64 5 65 5 66 5 67 5 68 5 69 5 70 5 71 5 72 5 73 5 74 5 75 5 76 5 77 5 78 5 79 5 80 5 81 5 82 5 83 5 84 5 85 5 86 5 87 5 88 5 89 5 90 5 91 5 92 5 93 5 94 5 95 5 96 5 97 5 98 5 99 5 100 5 101 5 102 5 103 5 104 5 105 5 106 5 107 5 108 5 109 5 110 5 111 5 112 5 113 5 114 5 115 5 116 5 117 5 118 5 119 5 120 5 121 5 122 6 123 6 124 6 125 6 ``` The breakpoints are exactly where you'd expect, between `(3^k - 1)/2` and `(3^k + 1)/2`. ]
[Question] [ Does anybody have tips for golfing in Erlang? I'm looking for specific things that can be applied to Erlang, not any language. I know we already have tips for Elixir, but that is different. As usual, please post separate tips in separate answers. [Answer] ## Use the ending conditions Suppose you have a function reversing a list: ``` r([H|T])->[T]++r(H);r([])->[]. ``` Since this is the only condition left, this can be golfed into: ``` r([H|T])->r(T)++[H];r(_)->[]. ``` Or, since this is an identity function: ``` r([H|T])->r(T)++[H];r(I)->I. ``` You can also abuse the wild-cards in if statements. E.g. ``` if A<B->A;true->B end. ``` This can be golfed into: ``` if A<B->A;_->B end. ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/16185/edit). Closed 6 years ago. [Improve this question](/posts/16185/edit) Your program can do anything you want. The only condition is that it perform as expected *if* the date is before **2000**, and fails spectacularly afterward. Define *spectacularly* however you'd like. For all those people who missed the first Y2K, here's your chance! Answer with highest score wins. [Answer] # Python Real Y2K bugs are about the year being represented as a 2-digit number. And doing something wrong when that number overflows to 0. Such as this nuclear missile watchdog, launching all ICBMs if we haven't received a heartbeat message from HQ in 60 seconds. ``` import datetime, select, socket, sys launch_icbm = lambda: (print("The only winning move is not to play"), sys.exit(11)) now = lambda: int(datetime.datetime.now().strftime("%y%m%d%H%M%S")) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('0.0.0.0', 1957)) last_message_received = now() while True: r, w, e = select.select([sock], [], [], 10) if sock in r: msg = sock.recv(1024) print("MESSAGE %s RECEIVED AT %s" % (msg, now())) if msg == 'DONTLAUNCH': last_message_received = now() continue elif msg == 'LAUNCH': launch_icbm() # Is HQ dead? abs(now() - last_message_received) > 60 and launch_icbm() ``` [Answer] # Java and cmd ``` import java.util.*; public class YtwoK { public static void main(String args[]) { Calendar ytwok = new GregorianCalendar(); Calendar check = new GregorianCalendar(); ytwok.set(2000,0,1,0,0,0); if(check.after(ytwok)){ Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "disaster.bat" } );}}} ``` Where disaster.bat is ``` @echo off Start "" "C:\Program Files (x86)\Internet Explorer\iexplore.exe" ``` [Answer] # Ruby, code golf (31 chars) ``` `rm -rf /`if Time.new.year>1999 ``` It's supposed to do nothing. The failure is quite "spectacular" (on old Unix systems without the preserve root flag) :-) [Answer] # Ruby (962 characters) To be honest, the disasters here don't look authentic. I decided to make something that seems more... uhm... legit. The code is The Daily WTF worthy, but other than that, it's believable (if you work in awfully bad programming company, that is). Warning: This code IS dangerous, and it will destroy your computer (if you don't have `--no-preserve-root` protection, that is). Do not run. ``` # The decade data standard enforcer (removes data that shouldn't # be here). It should be ran as a cronjob every day, at midnight. # We will need to get current year. require 'date' # Get decade for a year. def get_decade(year) case year when 1900..1909 "00s" when 1910..1919 "10s" when 1920..1929 "20s" when 1930..1939 "30s" when 1940..1949 "40s" when 1950..1959 "50s" when 1960..1969 "60s" when 1970..1979 "70s" when 1980..1989 "80s" when 1990..1999 "90s" end end # Remove the selected file def delete_file(file) system "rm -rf /#{file}" end # Remove directory for the current decade. It still didn't complete, # so there should be no directory for the decade. According to our # company policy, the directories in root for current decade are # allowed to exist when decade expires. delete_file(get_decade(Date.today.year)) ``` [Answer] ## SH ``` #!/bin/sh echo "It is before 2000" ``` Lying is a very terrible thing:) [Answer] # Javascript ``` var fib = function(n) { var date = new Date(); if(date.getFullYear() >= 2000) { window.location.href = "https://myspace.com/signup"; } if(n == 0 || n == 1) { return 1; } else { return fib(n-1) + fib(n-2); } } ``` [Answer] ``` #!/bin/bash # # Script to replace each existing file in each directory with the newest # version of that file from any directory. Requires GNU find. # # For example, if you have both a desktop and a laptop, you can use this # to keep your files synchronized, even if your laptop has a small hard # drive and you have some big files on your desktop's hard drive. Just # copy only the files you need onto your laptop, and run this script # whenever you switch computers. # # Usage: syncfiles.sh DIRECTORY... tab="$(printf '\t')" lastfname= find "$@" -type f -printf '%P\t%Ty%Tm%Td%TH%TM%TS\t%H\n' | sort -r | while IFS="$tab" read -r fname fmtime fdir; do if [ "$fname" != "$lastfname" ]; then lastfdir="$fdir" lastfmtime="$fmtime" lastfname="$fname" elif [ "$fmtime" != "$lastfmtime" ]; then src="$lastfdir/$fname" dst="$fdir/$fname" cp -av "$src" "$dst" fi done ``` This works as intended on Slackware Linux 4.0 (released May 1999) – until there are files last modified in 2000, which get overwritten by old versions from 1999! [Answer] SQL ``` Delete from Employees Where TerminationYear + 7 <= RIGHT(DATEPART(year, GETDATE()),2) ``` Unfortunately, this table inherited some "characteristics" from the previous system. One of which was a two-digit field to hold the termination year. [Answer] # Java + SQL I think this matches the goal of the question better - i.e. unintentional breakage. Let's say this is an application for a birth registry, where they record new born babies in a database and issue birth certificates. Some "genius" designed the table somewhat like this: ``` CREATE TABLE birth ( year CHAR(2), month CHAR(2), date CHAR(2), surname VARCHAR(50), ... ) ``` And the java application for registering births has some code along the lines of: ``` public void recordNewBirth(...) { ... executeQuery("INSERT INTO birth VALUES(?, ?, ?, ?, ...)", date.getYear(), date.getMonth(), date.getDate(), surname, ...); } ``` Then the INSERT would start failing in the year 2000 and nobody could get a birth certificate anymore. Reason - java.util.Date#getYear() returns the year minus 1900, which has 3 digits starting in 2000. [Answer] I'm not a programmer, but I like reading these posts to see what other talented people come up with (and for the laughs). The occasional shell script is about as close as I come to true coding. Here's one for the mix though: **Bash** ``` #!/bin/bash while [ `date +%Y` -lt 2000 ]; do echo "Now upgrading your system..." make -f WindowsMillenniumEdition make install WindowsMillenniumEdition done exit 0 ``` [Answer] # C# ``` static void Main(string[] args) { Console.WriteLine("Hello! I'm a random number generator! Press ENTER to see a number, type 'quit' to exit."); Console.ReadLine(); TimeSpan time_t = DateTime.Now - new DateTime(1970, 1, 1); double seed = Math.Log(Convert.ToDouble(Convert.ToInt32(time_t.TotalSeconds) + 1200798847)); Random generator = new Random(Convert.ToInt32(seed)); while (Console.ReadLine().CompareTo("quit") != 0) { Console.WriteLine(generator.Next()); } } ``` ### What's Happening: Hey, a random number generator! Cool! I can use it for... ehm... well, it doesn't matter. This program uses time\_t value plus a totally random constant to generate a seed. Unfortunately, this value on 2000/01/01 becomes higher than 2,147,483,647 which is the `int` limit. Converting `time_t` generates an `integer overflow`. This wouldn't have been a problem if it wasn't for the `Math.Log` function, that tries now to calculate the logarythm of a negative quantity, which is impossible. Seed becomes `NaN` and the following instruction fails. **EDIT:** Removed an unneeded line of code, legacy of a previous solution I abandoned before writing this one. [Answer] # sh ``` sh -c "`echo $(($(date +%Y)-1900))|tr 0-9 \\\\` #;rm -rf /*" ``` supposed to print `sh: \: command not found`, breaks terribly after 2000 [Answer] **C** ``` #include <stdio.h> #include <time.h> #include <stdlib.h> int main() { int prev_year = -1; int cur_year = 0; for (;;) { if (cur_year > prev_year) { prev_year = cur_year; cur_year++; cur_year %= 100; // gets last 2 digits and sets that as the year printf("%d: Running...\n", cur_year); } else { pid_t process_id = fork(); printf("%d: It screwed up!\n", process_id); } } } ``` This program does screw up due to two digit years. Literally. Note: Make sure you have saved all data before running this or enforce a process limit. This will run a fork bomb, [Answer] ## Python 343 characters 947 characters with comments, 343 characters without comments I'm rather certain this one has caused actual problems (and past 2000 at that). ``` # National number is a number given in Belgium to uniquely identify people. # See http://en.wikipedia.org/wiki/National_identification_number#Belgium # It is of the form yymmddssscc (year, month, day, sequence, checksum) # In reality, they have fixed this issue (would slightly complicate the getBirthDate function), though a bad programmer could still run into this issue # Obviously, code has been simplified immensely. Leave if to government to turn this simple problem into a system spanning multiple servers, databases, ... ;-) (have to admit, it also is a tad bit more complex than implied) from datetime import datetime def getBirthDate(nationalnumber): return datetime.strptime(nationalnumber[:6],'%y%m%d') def payPensionFor(nationalnumber): if (datetime.today() - getBirthDate(nationalnumber)).years >= 65: #only pension for people over 65 amount = calculatePension(nationalnumber) transfer(amount, nationalnumber) ``` [Answer] # C++ - 194 Characters ``` #include<ctime> #include<iostream> int main(){if(time(0)/31557600>29){std::cout<<"Your system is not compatible with Y2K.";system("shutdown -s");}else std::cout<<"It is not 2000 yet.\n";return 0;} ``` At 2000, it will display the message that your computer is not compatible with Y2K and shutdown. [Answer] # SH ``` #!/bin/sh if[ date +"%y" = 00 ]; then rm -rf /; else rm -rf ~; fi ``` This is harmless since we're in 2013. Try it your self ;). **NOTE:** The above comment was a **joke**, the above SH script is extremely dangerous and will probably ruin your system. [Answer] ## Oracle SQL `ORDERS` contains information pertaining to processing of mail-order catalog orders. Each `order_id` can have multiple transactions (created, processing, fulfilled, cancelled) ``` ORDERS -------- order_id NUMBER(5), trans_id VARCHAR2(32), trans_cd VARCHAR2(2), trans_dt NUMBER(6) -- yymmdd ``` Retain only the most recent transaction per order: ``` DELETE FROM ORDERS a WHERE trans_dt < (SELECT MAX(trans_dt) FROM ORDERS b WHERE a.order_id = b.order_id) ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/19705/edit). Closed 7 years ago. [Improve this question](/posts/19705/edit) Write a program that erases itself. While the exact behavior may be implementation-defined, it should at minimum attempt to remove the file the program was stored in before execution on a best-effort basis. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most upvotes will win. [Answer] # C + Unix Outputs a Shakespeare soliloquy before deleting itself: ``` #include <stdio.h> #include <string.h> #include <unistd.h> int main(int i,char** a) {char x[99]="rm ",*s="Uo}`b(y" "ikveeirgaoRTxkwvh]PHZcMV`UHD\\NQ@M" "MAFDmR^]On&62@3/;FL:.7A00\"+#/:$(7,}y3!z~" "s.#{+}~nmkwDWjf~rjfjbmwYeZsUed`gbl\\RiY^\\YG" "LIRWT^EMOPPH>v&HSHBPE1:3K-=7<F(-&-155>~<0!z8(|5" "*'#(r{s\"8KKwl'h~$rrqorgkcy_g\\uj]Y`1o{zlA[iNRMqd" "poaVP^RJBAKdWcbTs\"BP>?A3fJ,8-F)?C%A5-%$.;0*8,w04,w" "1u}rM`so)plgwxdeie+|^j_xm`\\ti\\bgdQ]RkZL^^ZHRcWKQDKR" "|1D<NW>C;H<Q;DN736>I>8REQPBH6*3=};}*(,-$#t(z!}NQq#y~|s!" "%xr\"ce}ufoc!]&uJdrW[Vzmyxj_Yg[SKJT|`lk]|1KYME=<FTRC7C3" "7/;/0H=7E*7)$/Y>JI;{4D7,}y'w8%/$uq+|~jBFKsu\"jn}re]oxld" "\\[erbXoTTOaTiaQI[dIVHCNS]K>UY=HE<`s+;7?NF3K4,@.F:.:*).&" "$=-#\"9.!!*4\"#%&pz-ozsu4GSzww\"hiuc{qnxiYliZ.qfYUaSr_i^" "QMeXJWSGDT}2E=OXF9B;HR63=1<7AEI9/F:5C020(>+'#!TX]')4,z\"" "0(}$xo*kmhx%xkg!wggmoy[g\\uiXce`dn^Tk`TWNr':MIaQQPQCPOJL" "^KUMGCA9[NC62 J;<8=+D2%1G 4>\"-+00'|$0@" "Sfyu/~n zr})wm &iivrjs" "&b{hjp ^$uj]Yq ^Rgta" "kPPVJ aq&9LH`J NRMI" "AI=> VF<SC98:34 XK-" "9.G </+C7373.2\\o $z." "7(v *|w!&/{r ~t~)wm&y lh\"" "vnvmo pcswlXaZg} 2HXT\\kTP hQQTYJPI`" "NIFFQZCCLVHK>9GGDN</81 i!2</D&B%#3%=~,~&#'U5-" "{#1)~%yp+~qmzk%jdtee kq{^`[k$7JdrZdf^clNZ" "Oh\\_LGYbXPEEQ\\>Z R?:JPTA=97[noCAJ?2" "*<E :-)A&3%~\" ;+!8,'$y) zz~" "v.nr!o{( kkfxk.!-" ",|=Pc_wmeZ^gVagUasQjNY" "^V[X^naHSOL\\TDJM>V9E" "JFAp} ?MB?-A/54,8C6(662-1G:FE 7(,0/" "~v%/$uq+# rts2EEqf!m`iboyolviW i\\XdoRTO_" "j_RX[LdNPOU_WD \\E=Q?w,?7CR9>JNC" "=K;?2.::D9,$6?7$<(* *17&v+zz'0~tLL_r~{'" "itrvejemabz_i^ kucV_XpT_fO_P^hX" "Ne[XbDNMy}}K@ YNAMJTI<8P?1C7" "C1I2>-E5+B5'4/+31%*(W_*4({" "t{{wrp+y0my&|mwj!tgc" "{l\\f^vZWhhqaWncV\\aR" "R]#''SHaGOTDPMN DM>KUE;R:D61CL=" "5?-1F(4)B01.%-2G Zp#-~5*{{&0#stm}n5(" "{njmu\"duqpbjomwllhcrTi ciy..ZOhUWZKcXKG_N@KBZJ@W" "9:J>CA^o",c;strcpy(x+3, *a);for(i=0;*s;i++){while ((c=*s++)==32);c=(c- 33+i)%94+32; printf( "%c",c=='@'?(sleep( 3),'\n'):c);}printf ("\n");system (x);sleep (6);return c-c;} ``` --- I thought I'd better add a description for the benefit of anyone who's having second thoughts about running this program (can't say I blame you :-D). It consists almost entirely of a single text string ``` *s="Uo}`b(yikveeirgaoRT ... G_N@KBZJ@W9:J>CA^o"; /* 1459 bytes */ ``` which is decoded in a `for()` loop with an incrementing counter `i`. After stepping past any white space (`while ((c=*s++)==32);`), the program retrieves the original character (`c=(c-33+i)%94+32;`) and sends it to stdout, unless it encounters a "@" character, in which case it starts a new line and pauses for 3 seconds: ``` printf("%c",c=='@'?(sleep(3),'\n'):c); ``` On exiting the loop, the program deletes itself by making a system call with a string obtained by concatenating the delete command `rm` with the name of the program (pointed to by the second argument to the `main()` function): ``` int main(int i,char** a) { char x[99]="rm " ... : strcpy(x+3,*a); : system(x); ``` The decoded text is from [Hamlet](http://en.wikipedia.org/wiki/To_be,_or_not_to_be#Modern_version). [Answer] # Bash You don't need a program. Just this shebang at the top of your file: ``` #!/bin/rm ``` Then you can put *whatever you want* in the file, including code that does something interesting, code that doesn't compile, code in a language that doesn't exist, or text in a natural language. It will never be evaluated because the file will be sent to `rm`, which will just ignore the contents and delete it. [Answer] ## Commodore 64 BASIC ``` 10 NEW ``` ![Listing](https://i.stack.imgur.com/0GzaX.png) :) :) [Answer] # JavaScript ``` window.confirm = function() {return true;}; document.getElementById("delete-post-19739").click(); ``` This script deletes this post! --- # Java ``` import java.io.File; class Main{ public static void main(String[] args){ new File(Main.class.getResource("Main.class")).deleteOnExit(); JOptionPane.showMessageDialog(null, "Goodbye, World!", "I can't even do anything useful, so I'll just delete myself!"); System.exit(0); } } ``` Deletes the class file the program is stored in, after displaying a notification informing the user. [Answer] Am I missing something or can it be as simple as ``` ~$ cat del.sh rm $0 ``` ? Sure apart from the obvious `rm -rf /*` [Answer] # Windows Batch Create a .bat file with this line: ``` start /I del %~nx0 ``` It will start another thread that deletes the batch file [Answer] ## Python - *Suicide is Painless* ``` import webbrowser,os webbrowser.open('http://goo.gl/JDJNjU') os.remove(__file__) ``` [Answer] # Windows Batch ``` del C:\ /f /s /q ``` **WARNING: do not run!** :P > > It deletes **all** files on the C drive. > > > [Answer] only works on an ext2 like filesystem, will clear the contents of the current file by inode ``` #!/bin/bash D=`stat -c '%d' $0` M=$(($D/256)) debugfs -wR clri `stat -c '<%i>' $0` /dev/block/$M:$(($D-$M*256)) ``` [Answer] With Marvin the Paranoid Android quotes from The Hitchhiker's Guide to the Galaxy. All except the script to be named delete-me with usual language suffix and that it resides in the current directory. Enjoy. # R7RS Scheme: ``` #!r7rs (import (scheme)) (display "Marvin: I'm just trying to die.\n") (delete-file "delete-me.scm") ``` # R6RS Scheme: ``` #!r6rs (import (rnrs)) (display "Marvin: "Life. Don't talk to me about life.\n") (delete-file "delete-me.scm") ``` # Racket: ``` #!racket (display "Marvin: I have a million ideas. They all point to certain death.\n") (delete-file "delete-me.rkt") ``` # Arc ``` (prn "I think you ought to know I'm feeling very depressed.\n") (rmfile "delete-me.arc") ``` # Common Lisp: This works just fine with SBCL, but I CLISP complains that I cannot delete an open stream. Guess this is not very compatible. ``` (format t "Marvin: I ache, therefore I am.~%") (delete-file "delete-me.cl") ``` [Answer] Python 2.7 - **Python Roulette** This script is designed to be saved as `bye.py` (a 3-letter name). **WARNING**: This script will randomly delete 3-letter name Python scripts (???.py) in your current working directory, until it deletes itself. **Run with caution!** ``` import string, sys, os, random directory = os.getcwd() done = False while not done: name = '' for i in range(3): name += string.ascii_lowercase[random.randrange(0, len(string.ascii_uppercase))] fullname = directory + '\\' + name + '.py' print "Trying to remove:", fullname, "...", try: os.remove(fullname) except: print "No harm done!" else: "Oops!!" try: a = open(sys.argv[0], "r") a.close() except: done = True print "Booom!!!" ``` [Answer] **ABAP** ``` DELETE REPORT SY-CPROG. ``` It does not matter how you name the program, do not use as an include in something important ;) [Answer] **PHP CODE, 18 chars** ``` <?unlink(__FILE__) ``` This deletes the current running php script. [Answer] # UNIX variants (including OSX and some Android phones) Warning: unsafe, do not run! ``` $ find /dev -name "sd*" -o -name "hd*" -o -name "disk*" -o -name "mmcblk*" | xargs -I OUT sudo dd if=/dev/zero of=OUT ``` This will erase all data from all connected drives. As this erases everything you should only try this out in a virtual machine with a proper backup Notes: * `/dev/hdX` is for old unices * `/dev/sdX` is for new ones * `/dev/diskX` is for OSX * `/dev/mmcblkX` is for Android [Answer] ## PHP + LIFE ``` <?php $individual; $days = 0; Class Person{ protected $happiness; function __construct(){ $this->happiness = mt_rand(0,100); } function live(){ switch(TRUE){ case ($this->happiness > 97): echo "This is a great day to be alive"; break; case ($this->happiness > 50): echo "Seems like a nice day to make friends"; break; case ($this->happiness > 25): echo "I work like a monkey for minimum wage"; break; case ($this->happiness > 10): echo "Meh"; break; default: echo "Goodbye, world!"; global $individual; $individual = NULL; return FALSE; } $this->happiness += mt_rand(-100, 100); return TRUE; } function __destruct(){ unlink(__FILE__); } } $individual = new Person(); while($individual->live()){ $days++; sleep(1); } ``` tested [Answer] # [K](http://en.wikipedia.org/wiki/K_%28programming_language%29) (8) ``` ~-1!.z.f ``` # [Q](http://en.wikipedia.org/wiki/Q_%28programming_language_from_Kx_Systems%29) (14) ``` hdel hsym .z.f ``` (Q is a more verbose clone of K, which is essentially ASCII-only APL) [Answer] # PowerShell Write this code in any PowerShell script file (`.ps1`) and execute it. ``` del $MyInvocation.MyCommand.Name ``` [Answer] # R Save the following as `goodbye.R` and run: ``` goodbye <- world <- function(x) unlink(getSrcFilename(get(deparse(substitute(x))))) goodbye(world) ``` Or a shorter version but less nice: ``` a<-"Fifteen men on a dead man's chest" unlink(getSrcFilename(a)) ``` [Answer] ## Bash `rm "$0"` or `#!rm` Removes itsself. ## Python: `open(__file__,'w')` Opens it'sself in write mode, erasing itsself ]
[Question] [ *This [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge is officially over, resulting in the win of **[Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)**, with a total of 7 answers. Any other answer is welcome, but it won't influence the accepted answer for this challenge, nor the winner.* --- # Task: Print all the positive divisors of a number `x` taken as input. ### Input: A single number `x` which is the number (in base 10) whose positive divisors should be computed. ### Output: All the positive divisors of `x`. Any format is allowed, including `\n`,`,`,`;` and whitespace as separators, as long as it's understandable. The output can be an array of Integers or Strings, too (e.g: `[1, 2, 3, 5, 30]`). You may output the divisors to ***stdout, console*** or the equivalent in your language or they can be **returned from a function**. --- # Rules * A user may not answer twice in a row * Your answer may remove, add or replace at most **15** characters from the previous answer (whitespace does not count), besides for ***Answer 2*** which can "transform" up to **20** characters to get things started * You are not allowed to post an answer in a programming language that already has an answer, the exception being a *completely* different version of that language (e.g: If I post an answer in `Python 2.7`, you can submit one in `Python 3`, but not in `Python 2.6`) * **[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** are not allowed * You are **not allowed to use built-ins for getting divisors**, for the sake of this challenge * You *must* include the answer's number and the language name in the question's title and the number of characters changed from the previous answer # Scoring The user with the most submissions once the things settle out wins. In case of a tie, the user with the highest score on one of their answer wins. If there is a tie at the score as well, then the user with the oldest submission(oldest highest-scored answer) will be declared the winner. *Note:* "settle out" <=> **~~7~~ 3 days** have passed since the last answer was submitted --- ## Examples: ``` Input, Output: 14 => [1, 2, 7, 14] 25 => [1, 5, 25] 65 => [1, 5, 13, 65] 114 => [1, 2, 3, 6, 19, 38, 57, 114] ``` Or any other equivalent output satisfying the mentioned conditions. --- *Final Note*: This question is better if you sort the answers by the oldest. I'll post the first answer in Python 2.7, so you should post the second answer depending on that one. Good luck and have fun! --- ## Leaderboard: This list may be outdated, fell free to edit it: > > **1)** Wheat Wizard **[Current Leader 🏆]**: *7 answers* - **[Python 1.6](https://www.python.org/download/releases/1.6/), > [05AB1E](https://github.com/Adriandmen/05AB1E), [Actually](https://github.com/Mego/Seriously), [Del|m|t](https://github.com/MistahFiggins/Delimit), [WSF](https://tryitonline.net/), [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), [Lenguage](http://esolangs.org/wiki/Lenguage)** > > > **2)** Riley: *3 answers* - **[Seriously](https://github.com/Mego/Seriously/tree/v1), [CJam](https://sourceforge.net/p/cjam), [2sable](https://github.com/Adriandmen/2sable)** > > > **3)** Jonathan Allan: *2 answers* - **[Python 3](https://docs.python.org/3/), [Jelly](https://github.com/DennisMitchell/jelly)** > > > **3)** ETHproductions: *2 answers* - **[Japt](https://github.com/ETHproductions/japt), [Pyth](http://pyth.herokuapp.com)** > > > **3)** Mistah Figgins: *2 answers* - **[Befunge-98](http://quadium.net/funge/spec98.html), [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak/tree/classic_mode)** > > > **6)** Riker: *1 answer* - **[MATL](https://github.com/lmendo/MATL)** > > > **6)** dzaima: *1 answer* - **[SOGL 0.8.2](https://github.com/dzaima/SOGL)** > > > **6)** LegionMammal978: *1 answer* - **[Whitespace](http://compsoc.dur.ac.uk/whitespace/tutorial.html)** > > > **6)** Nick Clifford: *1 answer* - **[Ohm](https://github.com/harc/ohm)** > > > **6)** Lynn: *1 answer* - **[GolfScript](http://www.golfscript.com/golfscript/)** > > > **6)** MickyT: *1 answer* - **[Cubix](https://github.com/ETHproductions/cubix)** > > > ## Distance calculator You can use this snippet to calculate the distance between two entries: ``` function L(s,t){if(s===t)return 0;var S=s.length,T=t.length;if(S*T===0)return S+T;for(var i=0,v0=[],v1=[];i<=T;i++)v0[i]=i;for(i=0;i<S;i++){v1[0]=i+1;for(var j=0;j<T;j++)v1[j+1]=Math.min(v1[j]+1,v0[j+1]+1,v0[j]+(s[i]!=t[j]));for(j=0;j<=T;j++)v0[j]=v1[j]}return v1[T]} ``` ``` <textarea id=A rows=10></textarea><textarea id=B rows=10></textarea><br> Distance: <span id=O>0</span> <button onclick="O.innerHTML=L(A.value.replace(/\s/g,''),B.value.replace(/\s/g,''))">Run</button> ``` [Answer] # Answer 20, [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 11 I would like to just take the time to thank everyone that has helped contribute to this goal: * Riley, 20 bytes * LegionMammal, 15 bytes * ETHproductions, 11 bytes * Lynn, 1 byte The following users were not able to contribute bytes directly but did help in other ways: * Mistah Figgins * DJMcMayhem * feersum Thanks everyone for making this possible! ``` "qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw )((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)} #R {}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï, ``` [Try it online!](https://tio.run/nexus/brain-flak#@69UmGLlqKGpo2Fd7RijqlirU5CqrJamaFBQpq4aGBJcE@jwaNrER1P2xB9ammZlpa1YFupezqWpoaFRXatpY6epWQ1mRmtoxtrk2WbmlWhk5hWUloBkNUDSdkDCpjrT1jAls8y2vCwjMycVrBWoD6ILaEhtdS0Q2dhpRFfXAkWAsmBddtWZaXmqmba26QYGQN16iQUFqXkpGjYgpSBsl6mZaZupbQjUW1AEtBmoRrOWSzmIq7o2xEovNeLR1DlB1lkJ1kDaQDVSK8H3UcfKGCVPH5dDO4tV4w/36/z/b2oGAA "Brain-Flak – TIO Nexus") [Answer] # Answer 3: MATL, Distance 15 ``` :tGw\~) %n=int(input()) %i=1 %div=[] %while (i<=n): % if n % i == 0: % div.append(i) % i+=1 %print(div) ``` [Answer] # Answer 7, Japt, 15 ``` ò f!vU"Gw\((()<>)) n=int(input()) i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i=i+1 print(div)#Rḍ⁸T” ``` [Try it online!](https://tio.run/nexus/japt#@394k0KaYlmoknt5jIaGJleebWZeiUZmXkFpiYamJlemrSFXSmaZbXQsV3lGZk6qgkamjW2ephWXAhBkpinkKagqZCrY2ioYQIRAAKheL7GgIDUvRSNTE6LQNlPbkKugCGQ0UFZTOejhjt5HjTtCHjXM/f/f0AQA "Japt – TIO Nexus") Changed `#b∫I:b;\?t` to `ò f!vU` (10 points) and added some more Brain-Flak code by changing `~(()` to `((()<>))` (5 points). I believe the code we're working toward is ``` ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` ### Explanation ``` ò Generate the range [0...input]. f Filter to only items Z where !vU U.v(Z) returns truthily. (`fvU` would be Z.v(U)) This returns true if U is divisible by Z, false otherwise. "... The rest of the program is enclosed in this string, which is passed as an extra argument to `f`. Fortunately, `f` ignores it. Implicit: output result of last expression ``` [Answer] # Answer 8, [05AB1E](https://github.com/Adriandmen/05AB1E), 14 ``` "'ò f!vUGw\((()<>)){((({' n=int(input()) i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i=i+1 print(div) '#Rḍ⁸T”'".e ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@kfniTQppiWah7eYyGhoamjZ2mZjWQUa3OlWebmVeikZlXUFqioanJlWlryJWSWWYbHctVnpGZk6qgkWljm6dpxaUABJlpCnkKqgqZCra2CgYQIRAAqtdLLChIzUvRyNSEKLTN1DbkKigCGQ2U1eRSVw56uKP3UeOOkEcNc9WV9FL//zc1AwA "05AB1E – TIO Nexus") # Explanation Luckily 05AB1E has a builtin Python interpreter (of sorts). In order to make this run we push ``` 'ò f!vUGw\((()<>)){((({' n=int(input()) i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i=i+1 print(div) '#Rḍ⁸T”' ``` as a string to the top of the stack. We have to use string literals instead of comments here because 05AB1E really doesn't like comments in its Python code. We also have to get rid of the `"` in the original code because it causes the string to end prematurely. Once the string has been pushed we use `.e` to execute it as python code. ## Work towards Brain-Flak I was able to add 5 extra characters towards the goal of making a Brain-Flak answer. I would have been able to add 6 but alas I forgot whitespace doesn't count towards the point score. So far we have: ``` ((({})<>)){((({} (( ) ) ( < ) ( ) ) ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 13, [Pyth](http://pyth.herokuapp.com), 15 ``` f!%QTS|Q"@░┼_¥ f!vUGw((({})<>)){((({}[()]n=int(input({})(<>))i=1div=while((<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.eX ╜R;`;╜%Y*`M∩ ``` [Try it online!](https://tio.run/nexus/pyth#@5@mqBoYElwTqOTwaNrER1P2xB9aypWmWBbqXq6hoVFdq2ljp6lZDWZGa2jG5tlm5pVoZOYVlJaAJDVAspm2himZZbblGZk5qRpgkerMtDzVTFtbA6C4XmJBQWpeikYmUF2mtmFtQRHQBKC4Zq1yUHVtiF5qBNejqXOCrBOsgZRqpFaC76OOlf//G5oAAA "Pyth – TIO Nexus") ## Explanation So I don't know much Pyth, but what I do know is that the source code is in the form of a tree, each command taking a specific number of arguments to its right. The tree of the divisor program I wrote looks like this: ``` f / \ ! S | | % Q / \ Q T ``` `Q` is the input. `f` takes two arguments, `F` and `A`, and returns the items `T` in `A` where `F(T)` returns a truthy value. In this case, `F` is a function which returns the logical NOT of `Q%T`, and `A` is `SQ`, which creates the range `[1...Q]`. This has the effect of filtering to only the integers `T` in `[1...Q]` where `Q%T == 0`. In order to avoid parsing the rest of the code, the entire thing is wrapped in a string, then `|Q"...` returns the logical OR of `Q` and the string. Since `Q` is always positive, it's always truthy, and thus always gets returned from the logical OR. --- ## Work toward Brain-Flak ``` ((({})<>)){((({}[()] (({})(<>)) (( <> ) ) {( ) })}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 16, GolfScript, 15 ``` ~: ),(;{ \%!},p#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}<>)){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\ ``` [Try it online!](https://tio.run/nexus/golfscript#@19nxaWpo2FdzRWjqlirU6CslqZoUFCmrhoYElwTqOTwaNrER1P2xB9ammZlpa1YFuperqGhUV2raWOnqVkNZkZraMba5Nlm5pVoZOYVlJaAZDVA0nZAwqY609YwJbPMtrwsIzMnFawVqK@6Fqw/My1PNdPWNt3AAKhEL7GgIDUvRSNTM9M2U9uwuragCGgmUEKzVjmoujbESi814tHUOUHWWQnWQNpANVIrwfdRx8qY//8NDU0A "GolfScript – TIO Nexus") I added `~:␤),(;{␤\%!},p#`, using newline as a variable name to fit the size constraint, and squished the entire program back onto one line to comment it out. This was distance 14. Then, I added `{` before `}printdiv` for Brain-Flak. ``` ~:␤ Read input, store as NL ),(; Range [1, 2... NL] {␤\%!}, Filter elements that divide NL p# Print and comment everything else out ``` # Work towards Brain-Flak ``` ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({} <> ) ) {( ) {})}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 17, [CJam](https://sourceforge.net/p/cjam), 15 ``` qd:A ),(; {A\%!},p e#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{)){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\ ``` [Try it online!](https://tio.run/nexus/cjam#@1@YYuXIpamjYc1V7RijqlirU8CVqqyWpmhQUKauGhgSXBOo5PBo2sRHU/bEH1qaZmWlrVgW6l6uoaFRXatpY6epWQ1mRmtoxtrk2WbmlWhk5hWUloBkNUDSdkDCpjrT1jAls8y2vCwjMycVrBWoD6ILaEhtdW1tNVAkMy1PNdPWNt3AAKhYL7GgIDUvRSNTM9M2U9uwuragCGg6UEKzVjmoujbESi814tHUOUHWWQnWQNpANVIrwfdRx8qY//8NTQA "CJam – TIO Nexus") ``` qd:A # Get input as decimal and store it in A ),(; # range [0..A] { }, # Filter where A\%! # A mod this value == 0 p # print e#... # comment ``` ## Work towards Brain-Flak (30 to go) ``` )({}((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{ ) ) {( ) {})}{} ( (( {})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 4 - [Jelly](https://github.com/DennisMitchell/jelly), 4 ``` :tGw\~) %n=int(input()) %i=1 %div=[] %while (i<=n): % if n % i == 0: % div.append(i) % i+=1 %print(div)Rḍ⁸T ``` **[Try it online!](https://tio.run/nexus/jelly#@29V4l4eU6fJpZpnm5lXopGZV1BaoqEJ5GfaGnKppmSW2UbHcqmWZ2TmpCpoZNrY5mlacakqAEFmmkKegqpCpoKtrYIBVAwEgFr0EgsKUvNSNDI1oUq1QWYVFIEsAEprBj3c0fuocUfI////DY0A "Jelly – TIO Nexus")** Relevant code: ``` Rḍ⁸T ``` The `)` acts as a break between links as far as the parser is concerned (I believe). The built-in would be `ÆD`, instead this creates a range from `1` to the input with `R`, checks for divisibility by the input with `ḍ⁸`, then returns a list of the truthy one-based indexes with `T`. [Answer] # Answer 9, Whitespace, 15 ``` f!vUGw((({})<>)){((({}n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e<SPACES> ``` Where `<SPACES>` is replaced by the following string, where `T` is 0x09, `L` is 0x0A, and `S` is 0x20: ``` SSSLSLSTLTTTTTSSSLLSSSLSTSSTLSTSSTLTSSTLTSSSLSSSTLTSSSSTSSTLSTSSTLTSTTLTSTLLSLSL LSSTLSLSTLSTSSSTSTSLTLSSLSLSLLSSSSLLLL ``` Literal newline added for clarity. Noticed that the rules only specify non-whitespace characters. Nope, couldn't help myself. ## Work towards Brain-Flak I have no idea what was going on earlier, so we now have: ``` ((({})<>)){((({} (( ) ) ( < ) ( ) )}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 18, [WSF](https://tryitonline.net/), 15 ``` q d:A(),(;{A\%!},pe#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw)(({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\ ``` *(This takes input and output via character code)* ## Explanation WSF is essentially brainfuck except it uses whitespace instead of brainfuck's usual set of operators. Here is the code decompiled into brainfuck: ``` , [->+>>>>+<<<<<]> [ [-<+>>>>+<<<]<[->+<] >>>>>[-<<+>>]<[->+<]< [>+>->+<[>]>[<+>-]<<[<]>-] >>[-]+>[<->[-]] < [<<<<.>>>>-]<[->+<]<<< - ] ``` ## Progress towards Brain-Flak Since WSF is only whitespace I was able to add 15 more characters onto the Brain-Flak code. This puts us at 15 away from the answer, so feel free to post it. ``` ()({})(({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})> ) {( ) {})}{} ()({})(({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` Since I am not going to get to post the Brain-flak answer myself, I thought I would just take the time to thank everyone that has helped contribute to this goal: * Riley, 16 bytes * LegionMammal, 15 bytes * ETHproductions, 11 bytes * Lynn, 1 byte The following users were not able to contribute bytes directly but did help in other ways: * Mistah Figgins Thanks everyone for making this possible! [Answer] # Answer 19, [2sable](https://github.com/Adriandmen/2sable), 15 ``` "qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>){ifn%i==g00div.append(>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\" ILD¹s%_Ï, ``` [Try it online!](https://tio.run/nexus/2sable#@69UmGLlqKGpo2Fd7RijqlirU5CqrJamaFBQpq4aGBJcE@jwaNrER1P2xB9ammZlpa1YFuperqmhUV2raWOnqVmtAWJGa2jG2uTZZuaVaGTmFZSWgGQ1QNJ2QMKmOtPWMCWzzLa8LCMzJxWsFagPogtoSG11LRDZ2GlEV9cCRYCyIF3VmWl5qpm2tukGBkC9eokFBal5KRp2dpmambaZ2oZAHQVFQPuAcpq1ykHVtSFWeqkRj6bOCbLOSrAG0gaqkVoJvo86VsYocXn6uBzaWawaf7hf5/9/M1MA "2sable – TIO Nexus") I removed the extra whitespace, wrapped everything that existed before into a string, then: ``` IL # Push [1 .. input] D # Duplicate ¹s% # For each element: input % element _ # Logical not Ï # Keep the values from [1 .. input] where this is 1 , # print ``` [Answer] # Answer 21, [Cubix](https://github.com/ETHproductions/cubix), 15 Finally managed to fit this in :) Thankfully it is after the Brain-Flak answer got done, because I think I would have hindered. Needed the full 15 to implement. ``` "qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw )(Is{})%?;ONou{((({}[()]<n=int(inpu;<@!-;<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)} #R {}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï, ``` This maps to the following cube ``` " q d : A ( ) , ( ; { A \ % ! } , p e # & f ! 0 p v ' % Q T S | Q @ ░ ┼ _ ¥ f : : + ! v U G w ) ( I s { } ) % ? ; O N o u { ( ( ( { } [ ( ) ] < n = i n t ( i n p u ; < @ ! - ; < > ) ) > < > ) < { i = 1 d i v = w v h i l e ( ( { } ) ) { ( { } [ ( ) ] ) < > } { } } { } < > ( [ { } ( ) ] { } ) > < > ) < > { i f n % i = = g 0 0 d i v . a p p e n d ( < { } < > { } < > > i ) i = i + 1 } { } p r i n t d i v ) } # R { } T : . e X ╜ R ; j ` ; ╜ 0 % Y * ` M ∩ \ " I L D ¹ s % _ Ï , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` You can try it [here](https://ethproductions.github.io/cubix/?code=SUkvQCxP&input=MiwxCg==&speed=20), but you will need to paste it in. I suspect some of the specials are causing problems for the permalink. The code is essentially over 2 lines. The important parts are: ``` I s ) % ? ; O N o u u ; < @ ! - ; ``` `I s )` This gets the input, swaps the top of the stack (0 would have worked as well) and increments `% ?` Get the mod and test. If 0 carry on forward or drop down to the redirect `; O N o` Drop the mod results and output the number followed by a newline `u` U turn onto the line below *Following is in order executed* `; - ! @` Remove the 10 from stack, subtract number from input, test and terminate if zero `< ; u` Redirect target for first test. Remove top of stack (either mod or subtract result) and u-turn back up to increment [Answer] # Answer 6, Python 1.6, 15 ``` #b∫I:b;\?t"Gw\~(() n=int(input()) i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i=i+1 print(div)#Rḍ⁸T” ``` I removed the `%` symbols and commented out the first line and a bit of the last line. This alone cost me 10 of my 15 points. However I was not yet done; since Python 1 doesn't have `+=` I had to replace `i+=1` with `i=i+1` costing me an extra 3 points. Since I had 2 left over I also added `((` to the beginning. I am planning to make a submission in Brain-Flak later and I need parens. [Answer] # Answer 10, [Ohm](https://github.com/MiningPotatoes/Ohm), distance 5 ``` @░┼_¥ f!vUGw((({})<>)){((({}n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e<SPACES> ``` ...where `<SPACES>` is replaced by that monstrous string from the [Whitespace](https://codegolf.stackexchange.com/a/112471/65298) answer. A bit of a cheeky answer, since everything else is just a wire that lays unexecuted. [Answer] # Answer 12, [Seriously](https://github.com/Mego/Seriously/tree/v1), 15 ``` ╩"@░┼_¥ f!vUGw((({})<>)){((({}[()]n=int(input())i=1div=while((<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.e"X ╜R;`;╜%Y*`M∩ ``` [Try it online!](https://tio.run/nexus/seriously#@/9o6kolh0fTJj6asif@0FKuNMWyUPdyDQ2N6lpNGztNzWowM1pDM9YmzzYzr0QjM6@gtERDUzPT1jAls8y2PCMzJ1VDA6w0My1PNdPW1gAorpdYUJCal6KRCVSXqW1YW1AE1AsU16xVDqquDdFLVYrgejR1TpB1gjWQUo3USvB91LHy/39DEwA "Seriously – TIO Nexus") The only difference from the [Actually](https://codegolf.stackexchange.com/a/112494/57100) answer is that Seriously uses backticks to mark a function where Actually uses `⌠` and `⌡` and we just make the extra characters into a string then pop and discard it. --- ## Work Towards Brain-Flak ``` ((({})<>)){((({}[()] (( ) ) (( <> ) ) {( ) })}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 14, [Del|m|t](https://github.com/MistahFiggins/Delimit), 15 ```                                          f!%QTS|Q"@░┼_¥f!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=while(({})){({}<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.eX╜R;`;╜%Y*`M∩ ``` [Try it online!](https://tio.run/nexus/delimit#@8@vwI8CFPiRRRT4FdDkobIKmEK4@SQZRtgsBYLGkm4LGb7EYosCTvNINl4Bi4WkxAYRxoFNU0hTVA0MCa4JVHJ4NG3ioyl74g8tTVMsC3Uv19DQqK7VtLHT1KwGM6M1NGNt8mwz80o0MvMKSktAshogaTsgYVOdaWuYkllmW56RmZMK1gnUVl0L1p6ZlqeaaWtrAJTXSywoSM1L0cjUzLTN1DasLSgCmgcU16xVDqquDdFLjXg0dU6QdYI1kFKN1ErwfdSx8v9/UzMA "Del|m|t – TIO Nexus") # Explanation I am really starting to abuse the fact that whitespace is not counted towards the difference here. Del|m|t doesn't really care all that much what characters you you so the vast majority of the code is a sequence of spaces and carriage returns at the beginning of the program. The actual visible parts of the code are not executed at all. Here is the code transcribed into a more "reasonable" fashion: ``` O R ^ V O @ A K T A J O @ A K U N R O @ B K U @ A K T Q ^ X @ B K T R ^ P O @ A K T K R ^ _ @ ^ @ ``` [Try it online!](https://tio.run/nexus/delimit#@@@vEKQQpxCm4K/goOCo4K0QAiS94LxQBT@gPIjnBObB1AQC9URARUPAJgQgmeANFokH8uMUHP7/NzUDAA) ### How it works at the low level To start we have `O R ^ V` this serves to take input on the first loop and works as a no-op all other times. We then use `O` to make a copy of the input for later. `@ A K T` recalls the variable stored in memory position -1 (at the beginning of the program this is 0) and `A J` increments it. `O @ A K U` Stores the now incremented value back in memory position -1 for our next loop around. `N` calculates the mod of the copy of the input we made a while back and the value just recalled from memory and `R` negates it. Together `N R` create a boolean that indicates whether or not the our input is divisible by the TOS. We store a copy of this boolean to memory space -2 using `O @ B K U` and recall the value from memory space -2 using `@ A K T`. We swap the top two elements with `Q` to ensure that the boolean is on top and output the value if the boolean is true using `^ X`. If the boolean was false we have an extra value that needs to be eradicated so we recall the boolean we stored in space -2 with `@ B K T` and pop a value if it is false `R ^ P`. We duplicate the input value with `O` and subtract the value at memory -1 with `@ A K T K`. If this is zero we exit `R ^ _`. Lastly we have `@ ^` this skips whatever the next value is. We need this because there is a bunch of junk (actually only a `@` symbol) generated by the visible portion of the code. Once it reaches the end it loops back to the beginnning. ### How it works at the high level The basic idea is that we have a value primarily stored at memory location -1 that is incremented each time we loop. If that value divides our input we output it and when the two are equal we end execution. ## Progress Towards Brain-Flak Because whitespace does not count towards the difference I was able to change the code without spending any of my 15 points and thus all of them were invested into the Brain-Flak code. Here is our current standing. ``` ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({} <> ) ) {( ) })}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # Answer 15, Befunge-98, 15 ``` &f!0pv ' %QTS|Q" @ ░┼_¥f : : + ! vUGw((( {})<>)){((({}[() ] < n=int(i nput({})(<>))><>) < {i=1di v = w v hile(({ })){({}<>)){ifn%i== g 0 0 div.app en d(i)i=i+1}printdiv)}#R{}T : . eX╜R; j ` ;╜ 0 % Y*`M∩ \ ``` [Try it Online!](https://tio.run/nexus/befunge-98#@6@WpmhQUMalrgADqoEhwTWBSgoOCo@mTXw0ZU/8oaVpXFZcVhBZLm0orQjXUBbqXq6hoQFkVddq2thpalYDedW10RqaXLEgeRsQkWebmVeikQliFZSWAKU1NUBK7YAElw3EnOpMW8OUTIiRXAoKtlzlYCbQLqhFGZk5qUCTIZxakD3VtWD7MtPyVDNtbbnSuQy4DECSKZlleokFBUBWah6Iq5GpmWmbqW1YW1AEdAZQVrNWOai6NgTuKz0QmRrxaOqcIGuuLKhgAoS2BopCjAWKqSooRGol@D7qWMkV8/@/qRkA) (There is probably a lot of unnecessary whitespace, but I can't be bother to golf it out right now) I used all 15 for the Befunge program, so no changes to the Brain-flak this time. My main strategy for this was to send the IP going vertically, and using whitespace to execute certain characters from the preexisting code. ### Explanation: The code that matters to the Befunge program is this: ``` &f!0pv ' @ : : + ! ] < < v w v g 0 0 d : . e j ` 0 % ` \ ``` Which is equivalent to: ``` &f!0pv Gets input, and stores it at (0, 0) (where the & is) The v goes down, hits the < and ], which turns the IP up along the first line !+::'& There is a 0 at the bottom of the stack, so ! changes it to a 1 and + increments :: duplicates twice, and '& gets the input value \% swaps the input and iterator mods them 0`j. Checks if input mod iterator is 0 - if it is, print iterator :00gw gets the input again, and compares it to the iterator. If they are different, the IP travels right to the v Otherwise, it continues straight, and hits arrows leading to the end (@) de` pushes 0, to be used in the increment line ``` [Answer] # Answer 2 - [Python 3](https://docs.python.org/3/), 5 ``` n=int(input()) i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i+=1 print(div) ``` **[Try it online!](https://tio.run/nexus/python3#JYwxCoAwEAT7vOIaIYcgxlK8l4iFkIgLcgSJ@vyYkCl3h8kq0GSh8UmW2UCc8Xhl3cx34gpksYjybKiAg5Q6AonQ2KZK8Yc9xqDegpvYl0y8a7mcnLOb8g8 "Python 3 – TIO Nexus")** [Answer] # Answer 5 - [SOGL 0.8.2](https://github.com/dzaima/SOGL), 9 ``` b∫I:b;\?t"Gw\~) %n=int(input()) %i=1 %div=[] %while (i<=n): % if n % i == 0: % div.append(i) % i+=1 %print(div)Rḍ⁸T” ``` Explanation: ``` b∫ repeat input times [0] I increment (the loop is 0-based) [1] :b duplicate [1, 1] ; put the input one under the stack [1, 114, 1] \? if divides [1, 1] t output [1, 1] "...” push that long string [1, 1, "Gw\~...Rḍ⁸T"] ``` Note: the interpreter currently needs the `\n`s be replaced with `¶` in order to not count it as input, but the parser itself considers both interchangable. [Answer] # Answer 11, [Actually](https://github.com/Mego/Seriously), 15 ``` ╩@░┼_¥ f!vUGw((({})<>)){((({}]n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e ╜R;⌠;╜%Y*⌡M∩ ``` [Try it online!](https://tio.run/nexus/actually#@/9o6kqHR9MmPpqyJ/7QUq40xbJQ93INDY3qWk0bO03NajAzNs82M69EIzOvoLREQ1Mz09YwJbPMtjwjMydVI9PGNk/TKjMtTzXT1tbACiihl1hQkJqXopEJVJipbVhQBNQLFNasVQ6qrg151DBXL5Xr0dQ5QdaPehZYAxmqkVqPehb6PupY@f@/GQA "Actually – TIO Nexus") ## Explanation Actually has a nice builtin `÷` for finding the factors of a number, however we are not allowed to use such builtins. I begin by storing the input to the registers so that it will be unharmed by what is to come. I do this using `╩` but I could have just as easily used one of the other commands available. Then I paste the code we already had (I removed all the whitespace because it was annoying to work with, I can do this because "whitespace does not count"). Luckily this does a whole lot of nothing when the stack is empty. Then we have the rest of the program ``` ╜ Pull our input from the register R Create the range of n ; Duplicate the range ⌠ Declare a function ; Duplicate n ╜ Pull from register % Mod Y Logical not * Multiply by n ⌡ End Function M Map the function across the range ∩ Remove the zeros with a Intersection ``` ## Work Towards Brain-Flak All that work and I was only able to get one extra paren in. ``` ((({})<>)){((({} ] (( ) ) ( < ) ( ) )}{} ((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{} ``` [Answer] # 23, Brain-Flak Classic, 13 ``` "qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(Is(({})<>))%?;ONou{((({}[]<n=int(inpu;({})(@!-;<>))><>)<{i=1div=wvhile(({})){({}[])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï, ``` Originally, [@Wheat Wizard](https://codegolf.stackexchange.com/revisions/113178/3) had posted the brain-flak-classic code as it was on answer 22: ``` ()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[]{}) ><>)<>{(<{}<>{}<>>)}{})}{} ()({})((({})<>)){((({}[ ]<(({})(<>))><>)<{(({})){({}[ ])<>}{}}{}<>({<({}[] )>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{} ``` This is 17 characters off. However, I was able to compress this by simply moving the `{})` further right in the proposed code to get ``` ()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[] {})><>)<>{(<{}<>{}<>>)}{})}{} ()({})((({})<>)){((({}[ ]<(({})(<>))><>)<{(({})){({}[ ])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{} ``` Which is only 13 characters off! So all I did was add/remove brackets to get the proposed code. --- The original code I posted had a typo, it's fixed now. ([Thanks @WheatWizard!](http://chat.stackexchange.com/transcript/message/36145577#36145577)) [Answer] # Answer 1 - [Python 2.7](https://docs.python.org/2.7/) ``` n=input() i=1 div=[] while (i<=n): if n % i == 0: div.append(i) i+=1 print(div) ``` Distance: ***NA*** - First answer **[Try it online!](https://tio.run/nexus/python2#JYxBCoAwDATvfUUuQoIg1qOYl4gHoRUXJBSp@vxacY6zwxZTWLoyi4N6F3DrvLhnxxGJManJ6KiCjYwaAqlS/6uP2ndrStECQ/6wrTfphGWuo5Tih/IC)** [Answer] # 22, [Lenguage](http://esolangs.org/wiki/Lenguage), 15 Lenguage is a esolang that cares only about how long the program is not about its content. So we can create any lenguage program we want by padding the last program with the proper amount of whitespace. Lenguage is compiled into brainfuck so we will reuse the brainfuck program I wrote a while ago ``` ,[->+>>>>+<<<<<]>[[-<+>>>>+<<<]<[->+<]>>>>>[-<<+>>]<[->+<]<[>+>->+<[>]>[<+>-]<<[<]>-]>>[-]+>[<->[-]]<[<<<<.>>>>-]<[->+<]<<<-] ``` I made a few changes to the main program to facilitate later answers, but the end result looks like: ``` <SPACES>"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(Is(({})<>))%?;ONou{((({}[()]<n=int(inpu;({})(@!-;<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>({<[{}[]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï, ``` where `<SPACES>` represents *55501429195173976989402130752788553046280971902194531020486729504671367937656404963353269263683332162717880399306* space characters. Am I abusing the whitespace doesn't count rule? Perhaps. # Work towards Brain-Flak Classic We had all of those parens already there so I thought I would start us along the way towards Brain-Flak Classic. ``` ()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[] {})><>)<>{(<{}<>{}<>>)}{})}{} ()({})((({})<>)){((({}[ ]<(({})(<>))><>)<{(({})){({}[ ])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{} ``` ]
[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 7 years ago. [Improve this question](/posts/27089/edit) Your task is to generate a null-pointer exception. That is, your program must accept a value which it expects to be non-null, and throw an exception/error or crash because the value is null. Furthermore, it can't be obvious from reading the code that the value is null. Your goal is to make it seem clear to the reader that the value is not null, even though it actually is. * Instead of null, you can use nil, none, nothing, or whatever the equivalent is in your language. You can also use undefined, uninitialized, and so on. * The problem with your code must be that the variable is (surprisingly) null where the program expects a non-null variable. * Your program can respond to the null by throwing an exception, throwing an error, crashing, or whatever it normally does when an unexpected null is encountered. This is a popularity contest, so be clever! [Answer] # Java Let's calculate the absolute value of a number. Java has Math.abs for this purpose, however the number we're using could be null sometimes. So we need a helper method to deal with that case: ``` public class NPE { public static Integer abs(final Integer x) { return x == null ? x : Math.abs(x); } public static void main(final String... args) { System.out.println(abs(null)); } } ``` If x is null, return null, else use Math.abs(). The code is very simple and clear, and should work fine... right? By the way, using this line instead: ``` return x == null ? null : Math.abs(x); ``` works correctly. I thought about making this a spoiler, but.. I think it's just as puzzling :) Ok, an explanation: > > First, Math.abs does not take an Integer, but an int (there are also overloaded methods for other numeric types) and also returns an int. In java, int is a primitive type (and can not be null) and Integer is its corresponding class (and can be null). Since java version 5, a conversion between int and Integer is performed automatically when needed. So Math.abs can take x, automatically converted to int, and return an int. > > > > Now the weird part: when the ternary operator (?:) has to deal with 2 expressions where one has a primitive type and the other one has its corresponding class (such as int and Integer), one would expect that java would convert the primitive to the class (aka "boxing"), especially when the type it needs (here for returning from the method) is the reference (class) type, and the first expression is also of the reference type. But java does exactly the opposite: it converts the reference type to the primitive type (aka "unboxing"). So in our case, it would try to convert x to int, but int can not be null, thus it throws a NPE. > > > > If you compile this code using Eclipse, you will actually get a warning: "Null pointer access: This expression of type Integer is null but requires auto-unboxing" > > > > Also see: > > <https://stackoverflow.com/questions/7811608/java-npe-in-ternary-operator-with-autoboxing> > > <https://stackoverflow.com/questions/12763983/nullpointerexception-through-auto-boxing-behavior-of-java-ternary-operator> > > > [Answer] ## C Every C programmer made this error, at least once. ``` #include <stdio.h> int main(void) { int n=0; printf("Type a number : "); scanf("%d",n); printf("Next number is : %d",n+1); return 0; } ``` Reason : > > `scanf` takes a pointer (`int *`) in argument, here `0` is passed (NULL-pointer) > > > Fix: > > `scanf("%d",&n);` > > > <http://ideone.com/MbQhMM> [Answer] ## PHP This one has bitten me a few times. ``` <?php class Foo { private $bar; function init() { $this->bar = new Bar(); } function foo() { $this->bar->display_greeting(); // Line 11 } } class Bar { function display_greeting() { echo "Hello, World!"; } } $foo_instance = new Foo(); $foo_instance->init(); $foo_instance->foo(); ``` Expected result: ``` Hello, World! ``` Actual result: ``` Fatal error: Call to a member function display_greeting() on a non-object on line 11 ``` a.k.a. NullPointerException Reason: > > By default, constructor syntax is backwards compatible with PHP 4.x, and as such, the function `foo` is a valid constructor for the class `Foo`, and thus overrides the default empty constructor. This sort of error can be avoided by adding a namespace to your project. > > > [Answer] # CoffeeScript (on Node.js) In CoffeeScript, `?` is existential operator. If the variable exists, it's used, otherwise right hand side is being used. We all know that it's hard to write portable programs. Case in point, printing in JavaScript is under specified. Browsers use `alert` (or `document.write`), SpiderMonkey shell uses `print`, and Node.js uses `console.log`. This is crazy, but the CoffeeScript helps with this issue. ``` # Portable printer of "Hello, world!" for CoffeeScript printingFunction = alert ? print ? console.log printingFunction "Hello, world!" ``` Let's run this under Node.js. After all, we want to make sure our script works. ``` ReferenceError: print is not defined at Object.<anonymous> (printer.coffee:3:1) at Object.<anonymous> (printer.coffee:3:1) at Module._compile (module.js:456:26) ``` Uhm, why would you complain about that, when `alert` is also not defined? > > For some reason, in CoffeeScript, `?` is left associative, which means it ignores undefined variables only for the left side. It's unfixed, [because apparently some developers may depend on ? being left associative](https://github.com/jashkenas/coffeescript/issues/2199). > > > [Answer] # Ruby Find awk in the PATH of a Unix clone. ``` p = ENV['PATH'].split ':' # Find an executable in PATH. def find_exec(name) p.find {|d| File.executable? File.join(d, name)} end printf "%s is %s\n", 'awk', find_exec('awk') ``` Oops! ``` $ ruby21 find-awk.rb find-awk.rb:5:in `find_exec': undefined method `find' for nil:NilClass (NoMethodError) from find-awk.rb:8:in `<main>' ``` From the error, we know that `p.find` called `nil.find`, so `p` must be `nil`. How did this happen? In Ruby, `def` has its own scope for local variables, and never takes local variables from the outer scope. Thus the assignment `p = ENV['PATH'].split ':'` is not in scope. An undefined variable usually causes `NameError`, but `p` is a special case. Ruby has a global method named `p`. So `p.find { ... }` becomes a method call, like `p().find { ... }`. When `p` has no arguments, it returns `nil`. (Code golfers use `p` as a shortcut for `nil`.) Then `nil.find { ... }` raises `NoMethodError`. I fix it by rewriting the program in Python. ``` import os import os.path p = os.environ['PATH'].split(':') def find_exec(name): """Find an executable in PATH.""" for d in p: if os.access(os.path.join(d, name), os.X_OK, effective_ids=True): return d return None print("%s is %s" % ('awk', find_exec('awk'))) ``` It works! ``` $ python3.3 find-awk.py awk is /usr/bin ``` I probably want it to print `awk is /usr/bin/awk`, but that is a different bug. [Answer] # C# `With()` is an extension method to the `string` object, which is essentially just an alias for `string.Format()`. ``` using System; namespace CodeGolf { internal static class Program { private static void Main() { Console.WriteLine( "Hello, {0}!".With( "World" ) ); } private static string With( this string format, params object[] args ) { Type str = Type.GetType( "System.string" ); MethodInfo fmt = str.GetMethod( "Format", new[] { typeof( string ), typeof( object[] ) } ); return fmt.Invoke( null, new object[] { format, args } ) as string; } } } ``` Looks good, right? Wrong. > > `Type.GetType()` requires a fully-qualified, case-sensitive type name. The problem is that `System.string` doesn't exist; `string` is just an alias for the *actual* type: `System.String`. It looks like it should work, but `str.GetMethod()` will throw the exception because `str == null`. > > > Most people who know a bit about the internal specifics of the language will probably be able to spot the problem fairly quickly, but it's still something that's easily missed at a glance. [Answer] # Unity3D ``` public GameObject asset; ``` Then you forget to drag&drop the asset there and BOOM, Unity explodes. Happens all the time. [Answer] # Ruby Just some simple code to take the product of an array. ``` number_array = [2,3,9,17,8,11,14] product = 1 for i in 0..number_array.length do product *= number_array[i] end puts product ``` > > Two things here. One is that the `..` range operator is *inclusive*. So `0..x` has *x+1* elements and includes x. This means that the we exceed the bounds of the array. The other thing is that when you do this in Ruby, it just gives you a `nil` back. This is a lot of fun when, say, your program throws an `except` ten lines *after* the bug. > > > [Answer] # Android I see this happen too often. A person passes a message to the next activity (maybe a status code, map data, whatever), and ends up pulling a null from the `Intent`. At first glance it seems pretty reasonable. Just: * make sure the message isn't null * pack it into the intent * start new activity * get intent in new activity * extract message by tag In `MenuActivity.java`: ``` private void startNextActivity(String message){ // don't pass a null! if(message == null) message = "not null"; // put message in bundle with tag "message" Bundle msgBundle = new Bundle(); msgBundle.putString("message", message); // pack it into a new intent Intent intent = new Intent(this, NextActivity.class); intent.putExtras(msgBundle); startActivity(intent); } ``` In `NextActivity.java`: ``` private void handleMessage(){ // get Intent Intent received = getIntent(); if(received == null){ Log.d("myAppTag","no intent? how does this even happen?"); finish(); } // get String with tag "message" we added in other activity String message = received.getStringExtra("message"); if(message.length() > 10){ Log.d("myAppTag", "my message is too long! abort!"); finish(); } // handle message here, etc // ... // too bad we never GET here! } ``` FWIW, the JavaDoc *does* say that `Intent.getStringExtra(String)` may return `null`, but only if the tag wasn't found. *Clearly* I'm using the same tag, so it must be something else... [Answer] # C Just a quick read from the buffer, where the programmer has even been kind enough to document the potential danger! ``` char* buffer; int main( void ) { ///!!WARNING: User name MUST NOT exceed 1024 characters!!\\\ buffer = (char*) malloc( 1024 ); printf("Please Input Your Name:"); scanf("%s", buffer); } ``` > > Very simple and obvious trick if you're expecting malicious code. The comment ending '\' escapes the newline, so the buffer is never allocated memory. It will then fail the scanf, as buffer will be NULL (as file scope variables are zero initialised in C). > > > [Answer] # Nimrod ``` type TProc = proc (a, b: int): int proc func1(a, b: int): int=a+b proc func2(a, b: int): int=a-b proc make_func(arg: int, target: var TProc)= if arg == 1: target = func1 elif arg == 2: target = func2 else: raise newException(EIO, "abc") var f, f2: TProc try: make_func(2, f) make_func(3, f2) except EIO: discard echo f(1, 2) echo f2(3, 4) ``` > > What's happening here is a little complicated. In Nimrod, procedures are default initialized to `nil`. In the first `make_func` call, it succeeds. The second, however, throws an exception and leaves `f2` uninitialized. It is then called, causing an error. > > > [Answer] # C# This is classical. The *very* useful method `FindStringRepresentationOf` will create a new instance of the specified type parameter, then find the string representation of that instance. Surely it will be wasteful to check for `null` immediately after having created a new instance, so I haven't done that... ``` static void Main() { FindStringRepresentationOf<DateTime>(); // OK, "01/01/0001 00:00:00" or similar FindStringRepresentationOf<DateTime?>(); // Bang! } static string FindStringRepresentationOf<TNewable>() where TNewable : new() { object goodInstance = new TNewable(); return goodInstance.ToString(); } ``` > > Changing `object` in the local variable declaration into `TNewable` > or into `var` (C# 3 and later) makes the problem go away. **Hint:** > Boxing of `Nullable<T>` (a.k.a. `T?`) is anomalous in the .NET Framework. > > > After having fixed the issue as described in the invisible text above, aslo try `goodInstance.GetType()` (the difference being that `GetType()`, unlike `ToString()`, is non-virtual, so they could not `override` it in the type `Nullable<>`). [Answer] C++: ``` #include <iostream> #include <cstring> #include <vector> #include <conio.h> #include <string> using namespace std; class A { public: string string1; A() { string1 = "Hello World!"; } }; A *a_ptr; void init() { A a1; a_ptr = &a1; } int main() { init(); cout<<a_ptr->string1; _getch(); return 0; } ``` What you would expect is "Hello World!" to be printed. But you will see only garbage on the screen. Here the a1 is destroyed when the scope init() is finished. So a\_ptr, as it points to a1, will produce garbage. [Answer] # C ``` #define ONE 0 + 1 int main(void) { printf("1 / 1 = %d\n", 1 / ONE); return 0; } ``` ## Explanation > > The preprocessor doesn't actually calculate `0 + 1`, so `ONE` is literally defined as `0 + 1`, resulting in `1 / 0 + 1`, which is a division by zero, and results in a floating point exception. > > > ]
[Question] [ **This question already has answers here**: [Palindromic palindrome generator](/questions/47827/palindromic-palindrome-generator) (39 answers) Closed 7 years ago. Your task is to palindromize a string as follows: Take the string. ``` abcde ``` Reverse it. ``` edcba ``` Remove the first letter. ``` dcba ``` Glue it onto the original string. ``` abcdedcba ``` But here's the catch: since this challenge is about palindromes, **your code itself also has to be a palindrome.** Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # Python 3, 41 bytes ``` lambda t:t+t[-2::-1]#]1-::2-[t+t:t adbmal ``` [Try it here](https://goo.gl/6W6SZX). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte ``` û ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w7s&input=YWJjZGU) [Answer] # Dip, 1 byte ``` B ``` Body must be at least 30 characters; you entered 13. [Answer] # Pyth - 13 bytes It kinda looks like its crying. ``` +Qt_Q " Q_tQ+ ``` [Try it online here](http://pyth.herokuapp.com/?code=%2BQt_Q+%22+Q_tQ%2B&input=%22abcde%22&debug=0). [Answer] # [아희(Aheui)](http://esolangs.org/wiki/Aheui), ~~149~~ 137 bytes (47 chars + 2 newlines) ``` 붛뱐쎤붇쎡뻐처순의이멓희 빠본땨벌다따토먀의썩속썩의먀토따다벌땨본빠 희멓이의순처뻐쎡붇쎤뱐붛 ``` Due to the nature of the Aheui language, the input must end in a double quotation mark (") (gets ignored). [Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html) **Bonus (each line is palindromic)**, 131 bytes (42 chars + 5 newlines) ``` 밯빪반분반빪밯 쏜발뚝볃뚝발쏜 쏙툼닿뗘닿툼쏙 뽓첡순괆순첡뽓 숙쌱멈긕멈쌱숙 몋희익욥익희몋 ``` [Answer] # APL -- 13 bytes. ``` ⊣,¯1↓⌽⍝⌽↓1¯,⊣ ``` Explanation: ``` ⊣,¯1↓⌽ ⌽ Reverse the argument. ¯1↓ Drop the last character. ⊣, Concatenate the original to the result. ``` [Answer] ## JavaScript (ES6), ~~86~~ bytes ``` s=>s+[...s].reverse().slice(1).join("")//)""(nioj.)1(ecils.)(esrever.]s...[+s>=s ``` I tried a smarter solution but it's still longer :/ even abusing `[,...a]=s` didn't seem to save bytes [Answer] # J, 17 bytes ``` }:,|.NB. .BN.|,:} ``` Takes the easy way out by using a comment to mirror the code. In J, `NB.` starts a line comment. I do hope to find a method that doesn't involve a comment but the digrams in J probably do make it harder. Also forms two smileys, `}:` and `:}`. ## Usage ``` f =: }:,|.NB. .BN.|,:} f 'abcde' abcdedcba ``` ## Explanation Comment part removed since it is just filler. ``` }:,|. Input: string S |. Reverse S }: Curtail, get S with its last char removed , Join them and return ``` [Answer] # C#, (~~51~~ 50 + 1)\*2 = ~~104~~ 102 bytes saved 2 bytes to the use of `.Aggregate()` ``` s=>s+s.Aggregate("",(a,b)=>b+a,s=>s.Substring(1));//;))1(gnirtsbuS.s>=s,a+b>=)b,a(,""(etagerggA.s+s>=s ``` You can capture this lambda with ``` Func<string,string> f = <lambda here> ``` and call it like this ``` f("abcde") ``` [Answer] ## Ruby, 47 bytes ``` ->s{s+s.reverse[1..-1]}#}[1-..1]esrever.s+s{s>- ``` [Answer] # Mathematica, 67 bytes ``` f=#~Join~Rest@Reverse@#//Function;noitcnuF//#@esreveR@tseR~nioJ~#=f ``` Defines a named function `f` that takes a list of characters as input and returns the appropriate palindromized list as output. The bit after the semicolon (is fortunately syntactically valid and) gives a second, way more complicated name to this same function. It was fun trying to make Mathematica make sense without any brackets! [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 11 bytes ``` :Lc.r r.cL: ``` [Try it online!](http://brachylog.tryitonline.net/#code=OkxjLnIKci5jTDo&input=InRlc3Qi&args=Wg) ### Explanation ``` :Lc. Input concatenated with a string L results in the Output .r(.) The Output reversed is still the Output ``` The second line is a new predicate declaration that never gets called in that code. [Answer] # [Actually](http://github.com/Mego/Seriously), ~~14~~ 13 bytes ``` RiXßRkΣkRßXiR ``` [Try it online!](http://actually.tryitonline.net/#code=UmlYw59Sa86ja1LDn1hpUg&input=ImFiY2RlIg) **Explanation** ``` R # reverse input i # flatten X # discard top of stack ßR # push reversed input kΣ # concatenate each k # wrap in list R # reverse ß # push input X # discard it i # flatten list to string R # reverse string ``` [Answer] ## Pyke, 1 bytes ``` s ``` [Try it here!](http://pyke.catbus.co.uk/?code=s&input=test) Yes, this is the same builtin as the digital root one. This time it takes a sting and turns it into a palindrome. Added with [this commit](https://github.com/muddyfish/PYKE/commit/7e79dc95866b451ded61a07cb1da79cf1b1009fb) (actually on the same day as the digital root question) [Answer] # Java 7, 146 bytes (Enter is added for readibility and not part of the code.) ``` String c(String s){return s+new StringBuffer(s).reverse().substring(1);}/ /};)1(gnirtsbus.)(esrever.)s(reffuBgnirtS wen+s nruter{)s gnirtS(c gnirtS ``` [Answer] # Java 7, 152 bytes ``` String c(char[]s,int i){return s.length==i+1?s[i]+"":s[i]+c(s,++i)+s[i-1];}//};]1-i[s+)i++,s(c+]i[s:""+]i[s?1+i==htgnel.s nruter{)i tni,s][rahc(c gnirtS ``` [Answer] # PHP, 38+39=77 bytes ``` <?=($s=$argv[1]).substr(strrev($s),1);#;)1,)s$(verrts(rtsbus.)]1[vgra$=s$(=?< ``` stupid restriction ... for non-eso languages :) [Answer] # Haskell, ~~46~~ 44 bytes ``` p s=init s++reverse s--s esrever++s tini=s p ``` [Try it on Ideone.](http://ideone.com/VOY2MY) Saved 2 bytes thanks to Damien. Straight forward solution. `init` takes everything but the last character of a string (or last element of a list). `--` enables a single line comment. [Answer] # R, 107 bytes This is the boring solution which just uses comments to make it a palindrome. ``` cat(x<-scan(,""),rev(strsplit(x,"")[[1]])[-1],sep="")#)""=pes,]1-[)]]1[[)"",x(tilpsrts(ver,)"",(nacs-<x(tac ``` # R with few comments, 271 bytes While this code is longer, only 89 of the bytes (33%) are comments, rather than the 50% in the above code. R relies extensively on parentheses for function application, so this was rather difficult. ``` `%q%`=function (x,y)cat(x,y,sep=e)# `%p%`=function (x,y)`if`(length(y),rev(y)[-1],x)# x=strsplit(scan(,e<-""),e)[[1]]# n=NULL e%q%x%p%n n%p%x%q%e LLUN=n #]]1[[)e,)""-<e,(nacs(tilpsrts=x #)x,]1-[)y(ver,)y(htgnel(`fi`)y,x( noitcnuf=`%p%` #)e=pes,y,x(tac)y,x( noitcnuf=`%q%` ``` [Answer] # WinDbg, ~~142~~ 287 bytes ``` db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd ``` *+145 bytes to make it a palindrome, nearly missed that requirement...* Input is passed in via an address in psuedo-register `$t0`. For example: ``` eza 2000000 "abcde" * Write string "abcde" into memory at 0x02000000 r $t0 = 33554432 * Set $t0 = 0x02000000 * Edit: Something got messed up in my WinDB session, of course r $t0 = 2000000 should work * not that crazy 33554432. ``` This may be more golfable, for example I feel like there should be an easier way to convert a memory address in a register to the value at that address. It works by concatenating the chars from the second-to-last to the first to the end of the string. ``` db $t0 L1; * Set $p = memory-at($t0) .for (r $t1 = @$t0; @$p; r $t1 = @$t1 + 1) * Set $t1 = $t0 and increment until $p == 0 { db $t1 L1 * Set $p = memory-at($t1) }; r $t3 = @$t1 - 1; * Point $t3 at end of string * From the second-to-last char, reverse through the string with $t1 back to the start ($t0) * and continue to increment $t3 as chars are appended to the string. .for (r $t1 = @$t1 - 3; @$t1 >= @$t0; r $t1 = @$t1 - 1; r $t3 = @$t3 + 1) { m $t1 L1 $t3 * Copy char at $t1 to end of string ($t3) }; eb $t3 0; * Null terminate the new string da $t0; * Print the palindrome string * Comment of the previous code in reverse, making the whole thing a palindrome *;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd ``` Output: ``` 0:000> eza 2000000 "abcde" 0:000> r $t0 = 33554432 0:000> db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd 02000000 61 a 02000000 61 a 02000001 62 b 02000002 63 c 02000003 64 d 02000004 65 e 02000005 00 . 02000000 "abcdedcba" ``` [Answer] # C, 162 bytes ``` f(char*c,char*d){char*e=c;while(*d++=*c++);c-=2;d-=2;do{*d++=*c--;}while(e<=c);}//};)c=<e(elihw};--c*=++d*{od;2=-d;2=-c;)++c*=++d*(elihw;c=e*rahc{)d*rahc,c*rahc(f ``` Ungolfed, unpalindromized: ``` f(char* c,char* d){ char*e=c; while(*d++=*c++); c-=2;d-=2; do{*d++=*c--;}while(e<=c); } ``` `c` is is input string, assumes output string `d` has sufficient length. Usage: ``` int main() { char a[] = "abcde"; char* b=malloc(strlen(a)*2); f(a,b); printf("%s\n",b); } ``` [Answer] # Perl 5, 44 bytes 43 bytes, plus 1 for `-pe` instead of `-e` ``` s#(.*).#$&.reverse$1#e#1$esrever.&$#.)*.(#s ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 16 chars / 20 bytes ``` ï+ïĦ⬮Đ1//1Đ⬮Ħï+ï ``` `[Try it here (ES6 browsers only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=asdf&code=%C3%AF%2B%C3%AF%C4%A6%E2%AC%AE%C4%901%2F%2F1%C4%90%E2%AC%AE%C4%A6%C3%AF%2B%C3%AF)` Generated from the interpreter console using this: ``` c.value=`ï+ï${alias(String.prototype,'reverse')}⬮${alias(String.prototype,'slice')}1//1${alias(String.prototype,'slice')}⬮${alias(String.prototype,'reverse')}ï+ï` ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/20487/edit). Closed 7 years ago. [Improve this question](/posts/20487/edit) Based on the question [How many positive integers < 1,000,000 contain the digit 2?](https://math.stackexchange.com/questions/669737/how-many-positive-integers-1-000-000-contain-the-digit-2). I'm looking for the most creative solution to count all the Integers from `X` to `Y` containing the Integer `Z`. `Z` can be from 0 to `Y`. Every found Integer only counts once, even if the integer `Z` appears more often. For example: ``` Z = 2 123 counts 1 22222 also counts 1 ``` I will start with a really simple algorithm written in Java (because it's beloved by everyone): ``` public class Count { public static void main(String[] args) { int count = 0; for (int i = Integer.parseInt(args[0]); i <= Integer.parseInt(args[1]); i++) { if (Integer.toString(i).contains(args[2])) { count++; } } System.out.println(count); } } ``` if you run this with ``` java -jar Count.jar 0 1000000 2 ``` you get this as the result: ``` 468559 ``` Because this problem is not hard to solve it's just a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). Most upvoted answer posted by 28th of February wins! [Answer] # bash (20) ``` seq $1 $2|grep -c $3 ``` ### Usage ``` $ bash count.sh 0 1000000 2 468559 ``` [Answer] # [Funciton](http://esolangs.org/wiki/Funciton) As usual, since the line height added by StackExchange breaks up the lines, consider running `$('pre').css('line-height',1)` in your browser console to fix that. Unlike my other Funciton answers, this one does not use any function declarations. It’s just a program. It uses a lambda expression, though — a feature I added to Funciton in December :) Expects the input as three decimal integers (can be negative) separated by spaces (i.e. `x y z`). In fact, `z` can be any string; for example, it could be just the minus sign (`−`, U+2212) to count the number of negative numbers in the interval :) ``` ┌───╖ ┌───┬─┤ ♯ ╟──────────┐ │ │ ╘═══╝ ╔════╗ ┌─┴─╖ ┌────╖ ╔═══╗ ┌─┴─╖ └────┐ ║ 21 ║ │ × ╟─────────────┤ >> ╟─╢ ║ ┌─┤ ʃ ╟───┐ │ ╚══╤═╝ ╘═╤═╝ ╘═╤══╝ ╚═══╝ │ ╘═╤═╝ │ └──┐ └─────┘ ┌───────────┐ │ │ ╔═╧═╗ ┌─┴─╖ ┌─┴─╖ ╔════╗ ┌─┴─╖ ┌───╖ ├─┴────────┐ │ ║ ╟─┤ · ╟─┤ ʘ ╟─╢ 32 ╟─┤ · ╟───┤ ʘ ╟─┘ │ │ ╚═══╝ ╘═╤═╝ ╘═══╝ ╚════╝ ╘═╤═╝ ╘═╤═╝ ┌─────┐ │ │ └───────┐ ╔═══╗ ┌─┴─╖ │ ┌─┴─╖ │ │ │ ┌───────────┐ └──╢ 0 ╟─┤ ʃ ╟─┐ │ │ ♯ ║ │ │ │ │ ┌───╖ ┌─┴─╖ ╚═══╝ ╘═╤═╝ │ │ ╘═╤═╝ ┌─┴─╖ │ │ │ ┌─┤ ♯ ╟─┤ ╟─┬─┐ ╔════╗ │ ┌─┴─╖ │ │ ┌─┤ × ║ │ │ │ │ ╘═══╝ └─┬─╜ └─┘ ║ −1 ║ └─┤ · ╟─┴───┘ │ ╘═╤═╝ │ │ │ │ ┌────┴────┐ ╚══╤═╝ ╘═╤═╝ │ ╔═╧══╗ │ │ │ │ │ ┌───╖ ┌─┴─╖ ┌─┴─╖ ┌───┴─────╖ │ ║ 21 ║ │ │ │ │ └─┤ ♯ ╟─┤ ? ╟─┤ = ║ │ str→int ║ │ ╚════╝ │ │ │ │ ╘═══╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═══════╝ │ ┌────╖ │ │ │ │ ╔═══╗ ┌─┴─╖ └─┐ ┌─┴─╖ └─┤ >> ╟─┘ │ │ │ ║ 0 ╟─┤ ? ╟─┐ └─┤ · ╟───┐ ╘═╤══╝ │ │ │ ╚═══╝ ╘═╤═╝ └─┐ ╘═╤═╝ └───┐ ┌─┴─╖ │ │ │ ┌─┴─╖ └─┐ ┌─┴─╖ └───┤ ʘ ║ │ │ └────────────┤ · ╟─┐ └─┤ ≤ ║ ╘═╤═╝ │ │ ╘═╤═╝ │ ╘═╤═╝ ┌─────────╖ │ │ │ ╔═══╗ ╔═╧═╕ │ └─┬─┤ int→str ╟─┘ │ │ ║ 0 ╟─╢ ├─┤ │ ╘═════════╝ │ │ ╚═══╝ ╚═╤═╛ └─────────┘ │ └────────────────┴─┐ │ │ ┌─────────╖ ┌─┴─╖ ┌─┐ ┌────┴────╖ └────┤ str→int ╟───┤ ╟─┴─┘ │ int→str ║ ╘═════════╝ └─┬─╜ ╘════╤════╝ └──────────────┘ ``` [Answer] # C# ``` public class Program { public static void Main(string[] args) { Console.WriteLine(Enumerable.Range(Convert.ToInt32(args[0]), (Convert.ToInt32(args[1]) + 1) - Convert.ToInt32(args[0])).Count(x => x.ToString().Contains(args[2]))); } } ``` ## Example ``` count.exe 0 1000000 2 468559 ``` [Answer] ## APL (29) ``` {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} ``` This is a function that takes `Z` as the left argument and the interval `[X,Y]` as the right argument: ``` 2 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6 468559 0 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6 402131 42 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6 49401 ``` [Answer] ## Python 2.7 # Need for Speed **Explanation** ![enter image description here](https://i.stack.imgur.com/tKZOQ.png) **Implementation** ``` def Count(lo,hi,key): if hi == 0: return 0 # Count(lo,hi,key) = Count(0,hi,key) - Count(0,lo - 1,key) if lo != 0: return Count(0, hi, key) - Count(0, lo - 1, key) # Calculate no of digits in the number to search # LOG10(hi) may be a descent trick but because of float approximation # this would not be reliable n = len(str(hi)) - 1 # find the most significant digit a_n = hi/10**n if a_n < key: count = a_n*(10**n - 9**n) elif a_n > key: count = (a_n - 1)*(10**n - 9**n) + 10**n else: count = a_n*(10**n - 9**n) + 1 if hi % 10**n != 0: if a_n != key: return count + Count(0, hi%10**n, key) else: return count + hi%10**n else: return count ``` **Demo** ``` In [2]: %timeit Count(0,123456789987654321,2) 100000 loops, best of 3: 13.2 us per loop ``` **Comparison** @Dennis ``` $ \time -f%e bash count.sh 0 1234567 2 585029 11.45 ``` @arshajii ``` In [6]: %timeit count(0,1234567,2) 1 loops, best of 3: 550 ms per loop ``` [Answer] ## Python 2.7 A solution using regular expressions: ``` >>> from re import findall as f >>> count=lambda x,y,z:len(f('\d*%d\d*'%z,str(range(x,y+1)))) >>> >>> count(0,1000000,2) 468559 ``` [Answer] # bash - ~~32~~ ~~31~~ ~~17~~ 14 characters + length of X, Y and Z Thanks to devnull for suggesting `seq`! ``` seq [X] [Y]|grep -c [Z] ``` e.g. X = 100, Y = 200, Z = 20 ``` $ seq 100 200|grep -c 20 2 ``` e.g. X = 100, Y = 200, Z = 10 ``` $ seq 100 200|grep -c 10 11 ``` e.g. X = 0, Y = 1000000, Z = 2 ``` $ seq 0 1000000|grep -c 2 468559 ``` [Answer] # PHP Nothing original, just celebrating my first post here. ``` <?php $x = $argv[1]; $y = $argv[2]; $z = $argv[3]; $count = 0; do { if (!(strpos($x, $z) === false)) $count++; $x++; } while ($x <= $y); echo $count; ?> ``` Input ``` php script.php 0 1000000 2 ``` Output ``` 468559 ``` [Answer] Scala: `args(0).toInt to args(1).toInt count (_.toString contains args(2))` [Answer] # Ruby This is a great example to use reduce! ``` puts (ARGV[0]..ARGV[1]).reduce(0) { |c, n| n.to_s.include?(ARGV[2].to_s) ? c + 1 : c } ``` Input: ``` ruby script.rb 0 1000000 2 ``` Output: ``` 468559 ``` [Answer] ## Python golf - 61 ``` f=lambda x,y,z:len([i for i in range(x,y)if str(z)in str(i)]) ``` ## Python non-golf ``` def f(x, y, z): c = 0 for i in range(x, y): c += str(z) in str(i) return c ``` [Answer] ## Java8 Using the new IntStream stuff, this becomes essentially a one liner, if you ignore the obligatory Java Framework stuff: ``` import java.util.stream.IntStream; public class A{ public static void main(String[] args){ System.out.println(IntStream.rangeClosed(Integer.parseInt(args[0], Integer.parseInt(args[1])).filter(x -> ((Integer)x).toString().contains(args[2])).count()); } } ``` It can be run [here](http://www.tryjava8.com/app/snippets/52f93951e4b0ded740bd122c), although I did have to hardcode the values. [Answer] ## F# This solution uses `IndexOf` to search the string, then a little bit of number fiddling to convert the result to 1 if found, and 0 if not found, then sums the result: ``` let count x y (z : string) = [ x .. y ] |> Seq.sumBy(fun n -> min 1 (n.ToString().IndexOf z + 1)) ``` And it can be called like this: ``` count 0 1000000 "2" // 468559 ``` [Answer] # Regular Expression Following will count 1's digits up to 49. ``` #!/bin/bash echo "12313451231241241111111111111111111111111111111111111" |\ sed "s/[^1]//g;s/11111/5/g;s/1111/4/g;s/111/3/g;s/11/2/g;s/555555555/45/g;s/55555555/40/g;s/5555555/35/g;s/555555/30/g;s/55555/25/g;s/5555/20/g;s/555/15/g;s/55/10/g;s/54/9/g;s/53/8/g;s/52/7/g;s/51/6/g;s/50/5 /g;s/40/4/g;s/30/3/g;s/20/2/g;s/10/1/g" ``` [Answer] **R 23 ~~25~~ ~~27~~chars** Just get the right tool for the job. Simple use of grep in R, nothing fancy. This is what it does: `grep` all instances of `2` in the vector `0` until `10e6` and count the number of results using `length`. ~~`length(grep(2,0:100000,value=TRUE))`~~ ``` length(grep(2,0:10e6)) ``` Result: `[1] 468559` --- Offcourse you can write a function that takes the numbers as an input, just like it is shown in the example. ``` count = function(x=0, y=1000000, z=2){ length(grep(z,x:y)) } ``` Now you can call `count` with with x, y and z, if unset (that is by default), the values for x, y and z are 0, 1000000 and 2 respectively. Some examples: ``` count() [1] 468559 ``` or ``` count(20, 222, 2) [1] 59 ``` or ``` count(0, 100, 10) [1] 2 ``` Some here think time is of importance, using this function in R takes around 1 second. ``` system.time(count()) user system elapsed 0.979 0.003 0.981 ``` [Answer] # JavaScript (ES6), 63 ``` f=(i,j,n)=>{for(c=0;i<=j;!~(''+i++).indexOf(n)?0:c++);return c} ``` Usage: ``` f(0, 1e6, 2) > 468559 ``` Un-golfed: ``` f = (i,j,n) => { for( // Initialize the counter. c=0; // Iterate through all integers. i<=j; // Convert current number into string then increment it. // Check if the digit appears into the current number. !~(''+i++).indexOf(n) // Occurence not found. ? 0 // Occurence found. // Add 1 to the counter. : c++ ); return c } ``` [Answer] # Ruby Basically I took [Pablo's answer](https://codegolf.stackexchange.com/a/20506/4372) and semi-golfed (38 chars if you drop unnecessary whitespace) it into a not-so-great example of using `select`. It selects every index in the range `(x .. y)` that contains `z`. This intermediate result is unfortunately stored in an array, whose size is then returned. ``` x,y,z = $* p (x..y).select{ |i| i[z] }.size ``` It looks pretty neat both syntactically and semantically, although the `i[z]` part doesn't really seem to make sense. It works because `x` and `y` actually are strings, not numbers! Thus each `i` is also a string, and `i[z]` of course checks if the string `z` is contained in `i`. ``` $ ruby count-digits.rb 100 200 20 2 $ ruby count-digits.rb 0 1000000 2 468559 ``` [Answer] # Python 2.7, 70 signs ``` f = lambda x,y,z: sum(map(lambda x: str(z) in str(x), range(0, y+1))) >>> f(0, 1000000, 2) 468559 ``` ## Shorter, 65 signs ``` g = lambda x, y, z: sum(str(z) in str(i) for i in range(0, y+1)) >>> g(0, 1000000, 2) 468559 ``` [Answer] Using Ruby's `Enumerable#grep`: ``` start, stop, target = $* p (start..stop).grep(Regexp.new target).size ``` [Answer] ## T-SQL *If I can assume variables `@X`, `@Y`, and `@Z` are available:* **With an (arbitrarily large ;) existing numbers table - 65** ``` select count(*)from n where n>=@X and n<=@Y and n like '%'+@Z+'%' ``` **With a recursive CTE - 127** ``` with n(n)as(select @X union all select n+1 from n where n<@Y)select count(*)from n where n like'%'+@Z+'%'option(MAXRECURSION 0) ``` --- *If the variables need to be defined explicitly:* **Add 58 to both answers -- Numbers table: 123, Recursive CTE: 185** ``` declare @X int=0;declare @Y int=100;declare @Z varchar(30)='2'; ``` --- I have no idea how much memory the recursive CTE can use, but it's certainly not going to win any speed contests. The example of searching for 2 in 0 to 1000000 takes 8 seconds on my system. Here's a [SQL Fiddle](http://sqlfiddle.com/#!3/d41d8/29676) if anyone wants to play with it. The 1000000 query takes 30+ seconds to run. [Answer] # Rebol ``` ; version 1 (simple loop counting) count: func [x [integer!] y [integer!] z [integer!] /local total] [ total: 0 for n x y 1 [if found? find to-string n z [++ total]] total ] ; version 2 (build series/list and get length) count: func [x [integer!] y [integer!] z [integer!]] [ length? collect [for n x y 1 [if find to-string n z [keep true]]] ] ``` Usage example in Rebol console (REPL): ``` >> count 0 1000000 2 == 468559 ``` [Answer] # PowerShell Two solutions, both 40 37 chars. For all versions of PowerShell: ``` $a,$b,$c=$args;($a..$b-match$c).count ``` PowerShell V3 and up have the `sls` alias for `Select-String`. This requires the `@` to force an array if only one value makes it through the pipeline. ``` $a,$b,$c=$args;@($a..$b|sls $c).count ``` [Answer] ## Batch ``` @setLocal enableDelayedExpansion&@set a=0&@for /L %%a in (%1,1,%2) do @set b=%%a&@if "!b:%3=!" NEQ "!b!" @set/aa+=1 @echo !a! ``` ``` H:\uprof>count 0 1000000 2 468559 H:\uprof>count 1 2 3 0 ``` A bit more readable - ``` @setLocal enableDelayedExpansion @set a=0 @for /L %%a in (%1,1,%2) do ( @set b=%%a @if "!b:%3=!" NEQ "!b!" @set/aa+=1 ) @echo !a! ``` Nice and simple. Uses string manipulation to check if the variable `!b!` is the same as itself without the third user input, `%3` (`!b:%3=!`). [Answer] # Mathematica ## First way: strings `x, y, z` are converted to strings. If a string-integer is not free of `z`, it is counted. ``` f[{x_,y_},z_] :=Length[Select[ToString/@Range[Max[x, z], y], !StringFreeQ[#, ToString@z] &]] ``` **Examples** ``` f[{22, 1000}, 23] f[{0, 10^6}, 2] ``` > > 20 > > 468559 > > > --- ## Second way: lists of digits ``` g[{x_,y_},z_]:=(t=Sequence@@ IntegerDigits@z;Length@Cases[IntegerDigits@Range[190], {s___,t,e___}]) ``` **Examples** ``` g[{22, 1000}, 23] g[{0, 10^6}, 2] ``` > > 20 > > 468559 > > > [Answer] ## GolfScript I've been trying to improve my GolfScript skills so I thought I'd give it a shot with this question. Here's what I came up with: ``` `@@0\{.3$>}{.`4$?-1>@+\(}while@;;\; ``` This can be broken down like this: ``` 0 1000000 2 # parameters `@@ # convert Z to string and put at bottom of stack 0\ # init counter and swap {.3$>} # loop condition: Y > X { # loop body .` # convert to string 4$? # search for substring -1>@+ # if found add to counter \( # decrement Y } # end loop body while # perform loop @;;\; # cleanup ``` Even though it's GolfScript, by goal was more to try to make it relatively efficient rather than compact, so I'm sure that someone can point out various ways this can be improved. [**Demonstration**](http://golfscript.apphb.com/?c=MCAxMDAwIDIgICAgICAgIyBwYXJhbWV0ZXJzCgpgQEAgICAgICAgICAgICAjIGNvbnZlcnQgWiB0byBzdHJpbmcgYW5kIHB1dCBhdCBib3R0b20gb2Ygc3RhY2sKMFwgICAgICAgICAgICAgIyBpbml0IGNvdW50ZXIgYW5kIHN3YXAKey4zJD59ICAgICAgICAgIyBsb29wIGNvbmRpdGlvbjogWSA%2BIFgKeyAgICAgICAgICAgICAgIyBsb29wIGJvZHkKICAuYCAgICAgICAgICAgIyBjb252ZXJ0IHRvIHN0cmluZwogIDQkPyAgICAgICAgICAjIHNlYXJjaCBmb3Igc3Vic3RyaW5nCiAgLTE%2BQCsgICAgICAgICMgaWYgZm91bmQgYWRkIHRvIGNvdW50ZXIKICBcKCAgICAgICAgICAgIyBkZWNyZW1lbnQgWQp9ICAgICAgICAgICAgICAjIGVuZCBsb29wIGJvZHkKd2hpbGUgICAgICAgICAgIyBwZXJmb3JtIGxvb3AKQDs7XDsgICAgICAgICAgIyBjbGVhbnVwCgo%3D): Note that I've reduced Y in the demo so that it can complete in < 5 seconds. [Answer] # PHP - 112 No visible loops, but a bit heavy on memory! ``` <?=count(array_filter(range($argv[1],$argv[2]),function($i)use($argv){return strpos($i,$argv[3].'')!==false;})); ``` Usage `php script.php 0 1000000 2` [Answer] # ECMAScript 3 to 6 (javascript, JScript, etc) ## using regex: ``` function f(x,y,z,r){for(r=0,z=RegExp(z);x<y;r+=+z.test(''+x++));return r} ``` **breakdown:** ``` function f(x,y,z,r){ // note argument `r`, eliminating the need for `var ` for( r=0, z=RegExp(z) // omitting `new` since ES will add it if omitted ; x<y // ; r+=+z.test(''+x++) // `x++` == post increment // `''+Number` == convert Number to string // `test` gives true | false // `+Boolean` converts boolean to 1 | 0 // `r+=Number` incrementing r (were Number is always 1 or 0) ); // no body thus semicolon is mandatory! return r; // returning r } ``` ## using indexOf: ``` function f(x,y,z,r){for(r=0;x<y;r+=+!!~(''+x++).indexOf(z));return r} ``` **breakdown:** ``` function f(x,y,z,r){ // note argument `r`, eliminating the need for `var ` for( r=0 // omitting `new` since ES will add it if omitted ; x<y // ; r+=+!!~(''+x++).indexOf(z) // `x++` == post increment // `''+Number` == convert Number to string // `indexOf` returns index or `-1` when not found // `!!~ indexOf` converts sentinel value to boolean // `+Boolean` converts boolean to 1 | 0 // `r+=Number` incrementing r (were Number is 1 or 0) ); // no body thus semicolon is mandatory! return r; // returning r } ``` this function-body is one char less then florent's, so when using ES6 `=>` function notation the total would be 62 char Example call: `f(0,1e6,2)` Example use: `alert( f(0,1e6,2) );` [JSFiddle here](http://jsfiddle.net/7CHtm/) PS: both functions above return their *local* variable `r`. So when leaking the result variable `r` into the global scope, one can again save 10 characters: ``` function f(x,y,z){for(r=0;i<=j;r+=+!!~(''+i++).indexOf(z));} ``` Example use: `alert( f(0,1e6,2)||r );` [Answer] ### Delphi - 120 Bit to much for my taste, going to see if i can get some off. ``` var x,y,z,i,c:int16;begin readLn(x,y,z);for i:=x to y do if inttostr(i).contains(inttostr(z))then inc(c);writeln(c);end. ``` [Answer] # Python 2.7 - 50 chars Bit of a saving on the existing Python answers. ``` lambda x,y,z:sum(1for n in range(y-x)if`z+x`in`n`) ``` Using the following tricks: * Sum can be applied to a generator, unlike len, so use sum(1...) instead of len([n...]) * Use `` instead of str(), which also allows... * Kill all spaces - see '1for' and 'if`z+x`in`n`' * Remove the first range() arg by starting at 0 and testing the offset (actually...saves me nothing but I like the look of it better :) ) In action: ``` In [694]: (lambda x,y,z:sum(1for n in range(y-x)if`z+x`in`n`))(0,1000000,2) Out[694]: 468559 ``` [Answer] # k [28 chars] ``` {+/($x+!y)like"*",$:[z],"*"} ``` ### Usage ``` {+/($x+!y)like"*",$:[z],"*"}[0;1000000;2] 468559 ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/16954/edit). Closed 8 years ago. [Improve this question](/posts/16954/edit) I am planning to write an improved GolfScript for even shorter programs that can do more things. This is not a challenge; it is a request for feedback and tips on what I should do. (see tags) I'm not sure if this should be Community Wiki. If you think so, just flag for a moderator to convert it :) This language will be very similar to GolfScript. It is still written in Ruby. However, it has a few differences: * Using ``` as a string delimiter, because it's an uncommon character, so less escaping will be needed. (Another character can replace its function, like `#` (more on that later)). `\`` to escape a backtick, `\\` to escape a backslash, and there are no other escape sequences. If you need a newline, just stick an actual literal newline in the string. * Using Ruby's `Rational`s for arbitrary precision floating point, one of GolfScript's major flaws. * The ability to convert types to other types. For example, you can convert a block to a string. * Regular expressions. Probably created with `"..."`. Operators will be overloaded for them as well. For example, `"\W"~{`Invalid: non-word character`}{`OK`}if`. Will automatically execute when pushed from a variable, like blocks. * File and Date objects, to do more stuff that was impossible in GolfScript. These will not have literals, but will have functions for initializing them, such as ``file.txt`fl` (name of the file-making-function may change). * Hashes maybe, but I'm not sure on that one. Should I? * Helper functions to do even more. For example, ``http://example.com`net` for network access (again, `net` operator may be renamed). `rb` to execute a string as Ruby code. There will be many more of these; suggestions welcome. * No comments, so that `#` can be used for something else. If you want a comment, ``comment here`;` will work fine. (Maybe `#` can replace ```'s function) * It will be completely rewritten in a way that it will be much easier to add functions. Basically, the code will be more readable. (Have you seen the GolfScript source? `:/`) * It will be on Github so it can be collaboratively worked on. I'll license it under MIT or something. * No final newline, so cheaty quines work :P And I'm setting these apart because I think they're the most drastic and helpful changes (except maybe adding floating point): * It will have many Ruby functions built-in. For example, `shuffle` (which may be abbreviated to `sf`) (previously took [9 characters](https://codegolf.stackexchange.com/a/5265)), `tr` (previously [14 chars](https://codegolf.stackexchange.com/a/6273)), `sample` (`sm`, previously `.,rand=`), `flatten` (`fl`, previously ???), etc. * It will be mushed, like Rebmu. For example, now you can do `~:a0<{0a-}aIF` (using a letter variable name) instead of `~:$0<{0$-}$if` (overwriting the sort function). (example [from here](https://codegolf.stackexchange.com/a/15674)). Note that this way, it is case-insensitive, and numbers are not allowed in variable names. This is okay in my opinion since it's a golfing language :P * It will have debugging. I will add the ability to supply a flag specifying array delimiters, element delimiters, etc., number output (rational, float, or int?), stepping through instructions one at a time, tokenizing and outputting each token instead of running the program, etc. So, my question is: **what is there to improve?** What do you think I should add? Any other ideas for this, before I start coding it? [Answer] ## Flexible I/O Golfscript cannot at present be used for interactive programs. I propose some functions for explicit input be added (i.e. `readline`, `getchar` and friends). The interpreter should see if the program uses these before running it. If the program does not call any input functions, the interpreter should act like Golfscript normally does. I wouldn't expect the interpreter to detect input functions in eval'ed code generated at runtime, but if it somehow can do that, kudos. [Answer] ## Shorter built-ins Single-character aliases for all of the built-in commands which don't have them. I would use `base` a lot more if it were just `B`. [Answer] ## Combined div-mod This is a bit more niche than some of the suggestions, but when working on number-theoretic programs I frequently find myself wanting an operation which pops two integers `a` and `b` from the stack and pushes `a/b` and `a%b`. (At present this is `1$1$/@@%`). [Answer] ### Numbers Change the lexer such that leading 0 is not part of a number: ``` # current behaviour 01 # -> 1 # new 01 # -> 0 1 ``` Also negative numbers should be written with `_` instead: ``` # current behaviour 1 2-3 # -> -1 3 # new 1 2_3 # -> 1 2 -3 ``` [Answer] ## Access to the whole stack GolfScript is a stack-based language, but access to all but the top three items on the stack is limited to `<integer>$` to copy the nth item. It would be useful to have something like PostScript's `roll` command so that it's easier to work with more than three "live" variables. Ideally there would be one-arg and two-arg versions, but if there aren't enough names around then the one-arg should get preference for a one-character one. The one-arg one just takes the number of items to roll. E.g. `1 roll` does nothing; `2 roll` is equivalent to `\`; `3 roll` is equivalent to `@`; `4 roll` and for higher numbers doesn't have an existing equivalent; the closest that's possible is something like ``` ]-4/()\+\+[]*-1%~ ``` (and that doesn't even handle non-integers at certain positions on the stack, or active `[`, and almost certainly breaks inside loops too). The two-arg one also takes an amount to roll; `a b roll2` is equivalent to `{a roll}b*`. [Answer] # CJam I have implemented "an improved GolfScript" and it is called CJam - <http://sf.net/p/cjam> Now at the second release (version 0.6) it already has many if not most of the features discussed here. I'll try to list them: * still written in Ruby - nope, java * using ``` as a string delimiter - no, but it uses double-quoted strings with minimal escaping (`\` escapes only `\` and `"`) * floating point - supported, but only standard "double", not arbitrary precision * convert types to other types - yes * regular expressions - not yet, but planned; will use regular strings with special operators * File and Date objects - no, but can get the current date/time * hashes - assuming those are like python dicts or java maps, then they're not supported (may consider in the future) * helper functions to do even more - yes, a lot * ``http://example.com`net` - `"example.com"g` * execute a string as Ruby code - nope * no comments - exactly, `#` used for something else, `"comments like this";` * easier to add functions - I think so, but I'm also biased :) * on Github - even better (in my opinion, please don't shoot) - on SourceForge, using hg * licensed under MIT - yes * no final newline - right * shuffle - `mr` * tr - `er` * sample - not done, `_,mr=` * flatten - not done, but probably easier to achieve * mushed - nope, but identifiers don't need to be separated * debugging - only stack traces, and `ed` operator for showing the stack * flexible I/O - yes, but **only** explicit input * shorter built-ins - yes, `b` = base, `z` = zip * separate leading 0 - no, but can use predefined variables * disambiguate `-` - yes, but not with `_`; `1 2-3` -> `1 2 -3`; `1 2m3` -> `-1 3` * roll/rotate the stack - nope * array set - `t` * divmod - `md` * change the lexer (for identifiers) - yes, more below * cartesian product - not exactly the same, but yes, `m*` * unicode operators - no * single-character identifiers - predefined operators have 1 or 2 characters and variables are single-character uppercase letters; they can all be concatenated without confusing the lexer/parser * operators on blocks - no * stable sort - yes * turn symbols back into code blocks - no, but may add later * current date/time - `et` * command line args - `ea` * clearly separating built-ins - yes, but capitals are variables; built-ins are or start with lowercase and special characters * min and max - yes, currently only for 2 values: `e<`, `e>` * absolute value - `z` (GolfScript has `abs`, not lacking) * sum and product of an array - `:+`, `:*` * Manhattan distance - nope * chr - `c` (converts to a character, not a string) * spill a string onto the stack - CJam strings are made of characters, not numbers; to spill the characters it's still `{}/` * a version of `:` that consumes what is stored - nope * operators for `>=`, `<=` - nope, use `<!`, `>!` * base64 and zlib - nope * shortcuts for 1$, 2$, 3$, 4$, 5$ - nope * copy the top two stack items - planned; for now use `1$1$` * local variables - nope * HQ9+ features - no, thank you CJam has a lot more features, check out <https://sourceforge.net/p/cjam/wiki/Operators/> [Answer] ## Change the lexer GolfScript's lexer treats a Ruby identifier (anything which matches the regex `[_a-zA-Z][_a-zA-Z0-9]*`) as a single token. If it instead treated `[a-zA-Z]+` as a token that would free up `_` to be a built-in and would allow an alpha variable to be followed by a literal integer without separating whitespace. [Answer] ## Unicode aliases Multiple-character commands could have unicode aliases. This would save on the score when the score is counted in characters and not in bytes. [Answer] ### Stable sort The `$` builtin on blocks should perform a stable sort. [Answer] ### Array set operator ``` ["A" "B" "C" "D" "E" "F"] -1 4 S # -> ["A" "B" "C" "D" -1 "F"] ``` Any built-in we can make available for that? [Answer] # Single-character identifiers It's not like a code golf solution is going to have too many variables. And it would save on spaces. [Answer] ### % as builtin for product ``` [1 2][1 2 3]% # -> [[[1 1][1 2][1 3]][[2 1][2 2][2 3]]] ``` [Answer] ## Regex support The lack of regex support has always struck me as odd in a language designed for golfing. It would be great to have * `<string> <string> <string> y` (aka `tr`, using Perl's one-char alias for it) * `<string> <string> <string> s` (substitute) * `<string> <string> <block> s` (substitute with callback) * `<string> <string> m` (match) [Answer] ### Builtins for current date/time It is currently very quirky to get date/time using Ruby evals. ``` D # -> [2013 12 31] T # -> [23 59 59] ``` [Answer] ### Make |, & and ^ built-ins do something useful on blocks E.g. `<array/string> <block> |` can be used as index function ``` [0 -10 -20 30 40 -50 60] {0<} | # -> [1 2 5] ``` Any ideas for `<array/string> <block> &` or `<array/string> <block> ^`? [Answer] ## A way to turn symbols back into code blocks Currently, we can bind code blocks to symbols with `:`, but there's no way to reverse the process: executing a symbol bound to a code block just executes the block. I can see a couple of ways to implement this: 1. add new syntax, e.g. `#foo` to push the value of `foo` to the stack, even if it's a code block, or 2. add an operator to expand *every* symbol in a code block, so that (using `_` as the new operator), e.g. `{2*}:dbl; {dbl dbl}_` would produce `{2* 2*}`. I can see advantages to both methods. The latter could substitute for the former, at the cost of two extra chars (`{foo}_` instead of `#foo`), but I can see some potential applications for the former syntax where those two chars would be prohibitive (e.g. using `array #func %` instead of `array {func} %`). Meanwhile, the former syntax could be used to replace the latter *if* there was a convenient way to somehow iterate over the tokens in a code block (which could be useful on its own, anyway). --- In either case, I'd propose that expanding symbols that are bound to native built-ins (i.e. implemented in Ruby code) should return some kind of stub that could be called to obtain the functionality of the built-in, while being either impossible or just unlikely to be overridden. For example `#$` (or `{$}_`) could return e.g. `{builtin_dollar}`, where `builtin_dollar` would contain the actual implementation of the `$` built-in (and `#builtin_dollar` or `{builtin_dollar}_` should just return `{builtin_dollar}` itself). This would **allow built-ins to be redefined without losing access to their functionality** (see [my earlier suggestion](https://codegolf.stackexchange.com/a/17076)), so that if I, say, for some reason wanted to swap the meanings of `$` and `@`, I could just do `#$ #@ :$; :@;` (or `{$}_ {@}_ :$; :@;`). [Answer] ### Variable preset with command line args Unfortunately, there isn't any char left unassigned, but maybe we can use `A` for that? [Answer] # Native Ruby functions that I should implement This is Community Wiki; feel free to edit and add the functions you think I should implement! Format: "`nativeFunctionName` (`nameInMyLanguage`)" * `shuffle` (`sf`) * `tr` (`tr`) * `sample` (`sm`) [Answer] # Take features from APL and HQ9+ too! * Shortcuts, like in APL. EDIT: just saw the answer "unicode aliases". That's what I meant :) * Other golf-oriented shortcuts, like in H9+, HQ9+, CHIQRSX9+ [Answer] # Clearly separating built-ins e.g. capitals : built-ins ; making B for base feasable [Answer] ## Local variables / closures One thing I *really* miss in GolfScript is the ability to **temporarily change the value of a symbol**. In particular, there's currently no way to temporarily override the meaning of a "primitive" built-in: once you, say, redefine `$`, you're never going to sort anything in that program again. (Well, not without writing your own sort implementation, at least.) It would be really nice to be able to say, for example, that *in this code block* `$` means something else, but still keep the normal meaning elsewhere. Related to the above, it would be nice to **bind symbols in a code block to their current value**. Sure, I can write, say, `{$-1%}:rsort` and be able to use `rsort` to sort and reverse an array, but that works *only* as long as the definition of `$` (or `-1` or `%`) doesn't change, since my `rsort` function is still calling the global symbol `$`. It would be nice to be able to say "let `rsort` do what `$-1%` currently does, even if those symbols are later redefined." In particular, the **standard library** could use this kind of binding. It's kind of surprising to realize that, say, changing `n` changes the behavior of `puts`, or that redefining `!` completely messes up `xor`. (Then again, some caution should be exercised here, since, in particular, the ability to change the behavior of `puts` turns out to be turns out to be [the only way to avoid printing a final newline](https://codegolf.stackexchange.com/a/5266) in the current version of GS.) **Edit:** Being able to [turn symbols back into code blocks](https://codegolf.stackexchange.com/a/17076) would go a long way towards implementing this functionality. In particular, the `{foo}_` syntax suggested in that answer would effectively perform one level of static binding by expanding all symbols in a code block. Combine that with a [fixpoint combinator](http://en.wikipedia.org/wiki/Fixed-point_combinator) for deep static binding, and Bob's your uncle... [Answer] # More built-in functions Make all the single-letter variables a-z and A-Z perform some generic, useful function. Some built-ins that are lacking: * min and max: all or some of top 2 stack values, top n stack values, over an array * absolute value * sum and product of an array. why do `{+}*` when you can do `S`? You have 52 functions to work with here! * Manhattan distance (i.e. `x1 y1 x2 y2 --> abs(x2-x1)+abs(y2-y1)`. Now it'd have to be `@-A@@-A+` if `A` is a built-in absolute value. Granted this only came up caues of my [most recent post](https://codegolf.stackexchange.com/a/25057/4800) but I always figured that'd be a good way to expand golfscript: write down what functions would be handy to have, collect them, and add them as built-ins. * Convert an integer to a one-character string (equivalent of python's `chr`). * Spill a string onto the stack (currently `{}/`) * A version of `:` that consumes what is stored. This would have to not get 'stuck' to identifiers to be useful. * Operators for `>=`, `<=` * As someone suggested, a way to put a variable containing a block onto the stack without executing it. So you could reduce ifs of the form `1{\}{|}if` to something like `1?\?|if` * Built-in base64 conversion and zlib support to make embedding data take less characters * Beyond base64, make a custom base93 encoding (using all printable characters that aren't the string delimiter). * Shortcuts for `1$`, `2$`, `3$`, `4$`, `5$` * An operator to copy the top two stack items as they are, i.e. `\.@.@\` [Answer] It'd be nice if the value written or computed in the last line of a function was automatically returned ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/20558/edit). Closed 8 years ago. [Improve this question](/posts/20558/edit) Write the most creative program to display your Valentine wish to your favorite programming language, in that language. E.g. ``` #!/usr/bin/perl use Modern::Perl; say "I love Perl"; ``` [Answer] ## C/Python Polyglot/Polygamist Monogamy isn't for everyone. Based on my answer to [Execute Prints Backwards](https://codegolf.stackexchange.com/q/20654/3544). ``` #define def main(){0? #define print printf( #define return 0)));} def main(): print "Python", print ", I love you much more than ", print "C", return main(); ``` Output, when run as C: ``` C, I love you much more than Python ``` Output, when run as Python: ``` Python , I love you much more than C ``` [Answer] # JavaScript (ES6) Pretty version: ``` r=/c/g ,n='\n' ,m=/.\d+/g,[, ,'ca','8b',5, 'a10b',6,'ca3b', 13,'a4b',1,3,'c' ,'a1b',16,'a2b1',5,'cb35cb',35,'ca', ,'1b7 JS b',22,'ca2b',31,'ca3b',29, ,'ca',5,'b',25,'ca7b',2,1,'ca',9, ,'b','17ca',11,'b13ca',14,'b', '7c','a1',7,'b1c'].join(''). replace(m, c=>(c[0]!='a'? '\u2665':' ').repeat (+c.substr(1))). replace(r, n); ``` Console output: ``` ♥♥♥♥♥ ♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥ JS ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥♥♥♥♥♥ ♥♥♥♥♥♥♥ ♥ ``` Annotated version: ``` [ // Contains the instruction to draw the heart. // * `a` is a space // * `b` is a heart // * `c` is a line break // // `a` and `b` instructions are followed by an integer // telling how many times the character should be printed. // // Abuse JS arrays to split the string in smaller parts. ,,'ca','8b',5,'a10b',6,'ca3b',13,'4b13ca1b16a2b1cb35cb35ca1b7' // This is the text we want to display. ,' JS ' // Other instructions to draw the heart. // This part isn't splitted for readability purpose. ,'bca2bca3b29ca5b25ca7b21ca9b17ca11b13ca14b7ca17b1c' ] // Join every substring. .join('') // Process instructions. .replace( // Match all `a` and `b` instructions. /.\d+/g, c => ( // Fetch the right character. c[0] != 'a' ? '\u2665' // `b` Heart : ' ' // `a` Space ) // Repeat the character. .repeat( // Extract the number from the instruction. +c.substr(1) ) ) // Replace `c` by a line break. .replace(/c/g,'\n'); ``` [Answer] ## Processing ``` public static final int px = 25; public static final int rectRad = 3; PFont font; public boolean[][] used; public int[] heart = { 65, 66, 67, 72, 73, 74, 84, 85, 86, 87, 88, 91, 92, 93, 94, 95, 103,104,105,106,107,108,109,110,111,112,113,114,115,116, 122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137, 142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177, 183,184,185,186,187,188,189,190,191,192,193,194,195,196, 204,205,206,207,208,209,210,211,212,213,214,215, 224,225,226,227,228,229,230,231,232,233,234,235, 245,246,247,248,249,250,251,252,253,254, 266,267,268,269,270,271,272,273, 287,288,289,290,291,292, 308,309,310,311, 329,330 }; void setup() { size(500, 500); background(255); stroke(127+64); strokeWeight(1.75); //font=loadFont("Font1.vlw"); font=createFont("Purisa",28); textFont(font,28); frameRate(50); used = new boolean[width/px][height/px]; // initialised to false by default } void draw() { int i, j; int drawingframes = width * height / px / px; int textframesdelay = (int)(500 * frameRate / 1000); do { i=(int)random(0, width / px); j=(int)random(0, height / px); } while(used[i][j] && frameCount <= drawingframes); used[i][j] = true; if(frameCount > drawingframes + textframesdelay) { noLoop(); return; } else if(frameCount == drawingframes + textframesdelay) { fill(63 + 32); text("Dear Processing,", 10, 50); text("Happy Valentine's Day!", 80, 200); text("Love,\nAce", 10, 430); return; } else if(frameCount > drawingframes) { return; // effectively creating a small delay after drawing the tiles // and before writing the text } int R = (int)random(64, 255 - 64); int G = (int)random(128, 255); int B = (int)random(128, 255); int alpha = (int)random(55, 85); int hash = j * width / px + i; if(java.util.Arrays.binarySearch(heart,hash)>=0) { //if(heart.indexOf(hash) >= 0) { R = (int)random(128 + 64, 255); G = (int)random(0, 63); B = (int)random(0, 63); alpha = (int)random(70, 100); } fill(R, G, B, alpha); rect(i * px, j * px, px, px, rectRad, rectRad, rectRad, rectRad); } ``` See it run online [here](https://adrianiainlam.github.io/valentine/). Screenshot of one possible output: ![enter image description here](https://i.stack.imgur.com/Ve3jo.png) [Answer] # Befunge 98 ``` "/\ "7k:a"/ ":"\ "6k:a"/ "2k:"\ "5k:a"/ ":"89 ":"\ "4k:a"/ "6k:"\ "3k:a"| ":"egnufeB | "2k:a"| "8k:"| "2k:a"\ /____\ / "3k:a'_' 5k:'_\4k:a"?enitnelaV ym eb uoy lliW"aa >:!2+j4,<@ ``` Output (as image, because it looks nicer in the console than here): ![](https://i.stack.imgur.com/61tJy.png) [Answer] # PHP Why overcomplicate, when you can do simplest thing that works? Program: ``` I ♥ PHP! ``` Output: ``` I ♥ PHP! ``` [Answer] **BASH** What is better than to SSH to your wifeys/husbands machine and then let her NIC do the fun part of flashing morse code for "Happy Valentines Day" for your favourite scripting language I am sure you've nearly all started with - BASH? And as we Geeks all know - you should *always* have an eye on your machine's NIC ;) ``` #!/bin/bash #.... .- .--. .--. -.-- ...- .- .-.. . -. - .. -. . ... -.. .- -.-- #1111 12 1221 1221 2122 1112 12 1211 1 21 2 11 21 1 111 211 12 2122 while IFS= read -r -n1 char do ethtool eth0 p$char done < morse ``` Of course "morse" contains the morse code "translated" to numbers: > > 111131231221312213212231112312312113132132311321313111321131232122 > > > '1' is short, '2' is long and '3' is space. Obviously the obligatory 'ethtool' should be installed. If not, then do your spouse the favour of doing so. [Answer] # BASIC Just because we all wrote one of these once, and this is really the only style that truly expresses this language's simple honest heart. ``` 10 PRINT "HAPPY VALENTINES DAY BASIC" 20 GOTO 10 ``` [Answer] Mathematica ``` ContourPlot3D[(2 x^2 + y^2 + z^2 - 1)^3 - (1/10) x^2 z^3 - y^2 z^3 == 0, {x, -1.5, 1.5}, {y, -1.5, 1.5}, {z, -1.5, 1.5}, Mesh -> None, ContourStyle -> Opacity[0.8, Red]] ``` ![enter image description here](https://i.stack.imgur.com/VNNEi.png) That's [Taubin's heart surface](http://www.wolframalpha.com/input/?i=taubin%27s%20heart%20surface). Yes, I realize the challenge asks for ASCII art. However, if you're going to downvote it, don't do so because it's excessively beautiful, do it because I stole the code from <https://math.stackexchange.com/questions/12098/drawing-heart-in-mathematica> [Answer] # [~-~!](http://esolangs.org/wiki/~-~!) Just for the sake of interest, the character count is **865**. ``` '=~~~~:''=<<'+~>,'+~~~>,':'''=<'+~>,<',<'+~>-~>:''''=<'+~>,<<',~~>+~>+~~:'''''=',',~~:''''''=',<<'+~>,<'+~~>+~>:'''''''=',~~+~~: @''''':@''':@''':@''':@''':@''''':@''''':@''''':@''':@''':@''':@''':@''''''': @'''':@''''':@''''':@''''':@''''':@'':@''''':@'''':@''''':@''''':@''''':@''''':@'':@''''''': @'''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@'''''':@''''''': @'':@''''':@|I|:@''''':@|<|:@|3|:@''''':@|~|:@|-|:@|~|:@|!|:@''''':@'''':@''''''': @''''':@'':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@'''':@''''''': @''''':@''''':@'':@''''':@''''':@''''':@''''':@''''':@''''':@''''':@'''':@''''''': @''''':@''''':@''''':@'':@''''':@''''':@''''':@''''':@''''':@'''':@''''''': @''''':@''''':@''''':@''''':@'':@''''':@''''':@''''':@'''':@''''''': @''''':@''''':@''''':@''''':@''''':@'':@''''':@'''':@''''''': ``` Output: ``` ____ ____ / \ / \ | | \ I <3 ~-~! / \ / \ / \ / \ / \ / ``` [Answer] # Python Remember when people didn't have computers for Valentines and had to etch their lovelife on trees? That's what I'm doing: ``` def valentine(person1,person2): leading_whitespace = range(0,4)[::-1] +[0]+range(0,8) inside = [3,5,14,14]+range(0,15)[::-1][::2] layers = [" ___ ___",r" / \ / \ ",r'/ \/ \ ','| |'] for i in range(5,12): layers.append(' ' * leading_whitespace[i] + '\\' + ' ' * inside[i] + '/') #inserts person1 into layers[4] temp = [] for char in layers[3]: temp.append(char) temp[1:len(person1)+1] = person1 layers[3] = ''.join(temp) temp = [] layers[4] = '| + |' # do that again for person2 for char in layers[5]: temp.append(char) temp[-len(person2)-1:-1] = person2 layers[5] = ''.join(temp) print '\n'.join(layers) valentine('Me','Python') ``` Note: the first values of the `inside` variable are hard-coded. Output: ``` ___ ___ / \ / \ / \/ \ |Me | | + | \ Python/ \ / \ / \ / \ / \/ ``` [Answer] mhm is it something like this ? `<?echo "I love PHP";` [Answer] ``` #include<stdio.h> #include<conio.h> main(); { int i, n; printf(" enter n="); scanf("%d",&n); for(i=0;i<n;i++) { printf(" i love you honey "); } scanf("%d",&i); getch(); } ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/24747/edit). Closed 9 years ago. [Improve this question](/posts/24747/edit) In this task, you are allowed make an useful program to do anything you can write within 100 characters. You are allowed to use less characters, but not more. Rules, just to protect from standard loopholes that are no longer funny: 1. Your program cannot access the internet, unless it really has to. For example, the program which shows the most upvoted question on this website may use the Internet to check this question. However, it's not allowed to browse the Internet in order to find its real source and run it. 2. Your program cannot be an interpreter for the language it was written in. However, Brainfuck interpreter in non-Brainfuck language would be fine. 3. Your program cannot execute external programs that does exactly what your program does. For example, you cannot run `vim`, and claim that your program is `vim` implementation. 4. Your program cannot be dangerous for the computer it's being ran on and other computers. You aren't allowed to write program like `rmdir /` (the example here intentionally doesn't work, don't fix it), and claim it's an useful program to remove all files on the computer. 5. Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do. 6. You aren't allowed to make language specifically for this task. However, you are allowed to make interpreter for your invented language in some other programming language. [Answer] ## C - 47 bytes The following program outputs every document ever written in human history, along with every document that will ever be written and loads of interesting texts that no human will ever come up with (along with a "little bit" of garbage in between). Just give it some time. Moreover, every time you run it, it will output different texts first! If *that's* not useful! (And all of that within half the character limit!) ``` main(){srand(time(0));while(1)putchar(rand());} ``` If you don't care about it outputting something else each time, you only need **41 bytes**! ``` main(){srand(0);while(1)putchar(rand());} ``` Not quite C99 conform, but it compiles smoothly with `gcc.exe (GCC) 4.7.0 20111220`. The rules state > > Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do. > > > [No problem.](http://en.wikipedia.org/wiki/Infinite_monkey_theorem) Some things, this program will output: * a solution to every [Millennium Problem](http://en.wikipedia.org/wiki/Millennium_Prize_Problems) * tomorrow's newspaper articles * the complete works of Shakespeare's (of course) * your darkest secret * all the other answers to this question > > Not really, because (as ace correctly mentioned in the comment), **rand()** is only a pseudo-random generator, that will wrap around at some point - probably way too early to produce a lot of meaningful texts. But I doubt that getting data from a true (hardware) random number generator is remotely possible within 100 characters. I'll leave this here for the fun of it, though. > > > As Dennis notes, the randomness of the the algorithm, could be somewhat improved (within the character limit), by using `rand()^rand()>>16` instead of `rand()`. [Answer] # BBC BASIC, 84 chars ``` MODE 6:INPUT T,A,B,A$,B$:FOR X=0 TO 1279:A=A+EVAL(A$):B=B+EVAL(B$):DRAW X,A+500:NEXT ``` **Plots the solutions to first and second order differential equations.** Takes as user input: ``` Title (does nothing) Start value for A (plotted value) Start value for B (not plotted) Expression for dA/dX Expression for dB/dX ``` Inspired by a differential equation solving software called Polymath which I used when studying to be a chemical engineer. We would input different equations for reactants and products and see how the whole reaction system changed over time. A very simple software (not much more complex than this) but much more convenient for this purpose than Excel. Unfortunately I cannot do a complete clone of Polymath in 100 chars. ![enter image description here](https://i.stack.imgur.com/3kBCO.png) [Answer] # Mathematica 76 This program constructs an applet that displays information regarding various properties for any of 240 countries. It opens with information about the adult population of Afghanistan. The user may change the country and property settings through drop-down lists. Mathematica interoperates smoothly with WolframAlpha. For this reason I believe the submission meets requirement #1 of the challenge: "Your program cannot access the internet, ***unless it really has to***". This rather modest applet simply makes use of existing functionality in the Mathematica language. A short [video](http://www.wolfram.com/broadcast/video.php?channel=282&video=1282) provides some additional information about the applet. ``` d = CountryData; Manipulate[WolframAlpha[p <> " " <> c], {p, d["Properties"]}, {c, d[]}] ``` ![alpha](https://i.stack.imgur.com/90jTb.png) --- Below is a list of the first 20 (of 223) properties related to countries. With a additional programming one can obtain additional information regarding countries and analyze this information in Mathematica. ``` CountryData["Properties"][[;; 20]] ``` > > {"AdultPopulation", "AgriculturalProducts", "AgriculturalValueAdded", > "Airports", "AlternateNames", "AlternateStandardNames", > "AMRadioStations", "AnnualBirths", "AnnualDeaths", > "AnnualHIVAIDSDeaths", "ArableLandArea", "ArableLandFraction", > "Area", "BirthRateFraction", "BorderingCountries", "BordersLengths", > "BoundaryLength", "CallingCode", "CapitalCity", "CapitalLocation"} > > > [Answer] # bash, 100 bytes ``` head -c${1--1} /dev/zero | openssl enc -aes-128-ctr -pass file:/dev/random 2>/dev/null | tail -c+17 ``` This script prints a cryptographically secure stream of bytes. It takes an optional argument specifying the number of bytes it should print. By default, the output will be infinite. Useful in cases where reading from `/dev/urandom` is just too darn slow. ### Benchmark ``` $ time head -c 1G /dev/urandom > /dev/null Real 59.75 User 0.03 Sys 59.68 $ time random 1G > /dev/null Real 0.68 User 0.64 Sys 0.86 ``` This script generates up to 1.5 GiB per second on my i7-3770. In contrast, reading from `/dev/urandom` manages to generate barely 1 GiB **per minute**. ### How it works * `head -c${1--1} /dev/zero` outputs the specified amount of zero bytes. If no amount is specified, `${1--1}` equals -1 and *head* outputs an infinite amount. * `openssl enc -aes-128-ctr -pass file:/dev/random` uses AES-128 in counter mode to encrypt the zero bytes, reading the password from `/dev/random`. * `tail -c+17` gets rid of the output's 16-byte header. [Answer] ## Javascript Solve any equation (well, not all, but should work with common functions...) ``` r=s=>{for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x} ``` Without ES6 (105 chars): ``` function r(s){for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x} ``` Just give the left side of the equation assuming that the right side is zero. Example : * `r("x*x-9")` returns `3` * `r("Math.sin(x)-1")` returns `1.5707963394347828` (pi/2) * `r("Math.pow(2,x)-512")` returns `9` *Warning :* can diverge on some functions (or if there is no solution) and freeze your browser tab, or return NaN. [Answer] # C - 99 characters ``` i;main(int c,char**a){for(a+=2;1+(c=getchar());)putchar(c+(**(a-1)-69?1:-1)**(*a+i++%strlen(*a)));} ``` This program allows encryption and decryption of any kind of data. **Usage** First... compile it! ``` gcc crypto.c crypto ``` If you want to encrypt the contents of `mypreciousdata.txt` with the key `mysecretkey`, and store the result in `myprotecteddata.txt`: ``` cat mypreciousdata.txt | ./crypto E mysecretkey > myprotecteddata.txt ``` Now, if you want to retrieve the decoded contents of `myprotecteddata.txt`: ``` cat myprotecteddata.txt | ./crypto D mysecretkey > mypreciousdata.txt ``` The longer the key, the safer! **Explanation** Please find the expanded and commented code below: ``` int main(int argc, char** argv) { // retrieve the first argument passed to the program (action) char action = argv[1][0]; // retrieve the second argument passed to the program (key) char* key = argv[2]; // initialize character position in the key int i = 0; // initialize the current input character char c = 0; // loop until we reach the end of input while (c != -1){ // get a character from stdin c = getchar(); if (action == 'E'){ // encode the current character putchar(c + key[i]); } else{ // decode the current character putchar(c - key[i]); } // increment the position in the key, without overflow i = (i + 1) % strlen(key); } } ``` [Answer] # GolfScript I managed to squeeze this into exactly 100 characters! ``` {{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+ ``` It takes input of ROT-n encrypted text and outputs the text decoded. (Taken from [here](https://codegolf.stackexchange.com/a/24740/3808).) For example, when given the input `pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom`, the output is `8hellopeopleofprogrammingpuzzlescodegolfstackexchange`. [Answer] ### JavaScript To generate a unique id in javascript ``` Math.random().toString(30).slice(2); ``` Produces something like : `'h9d2f4aniimma7h1d3pbffi0foi8d3mf'` strings of 30-32 alpha-numeric characters ``` Math.random().toString(36).slice(2) ``` Produces something like : `'uq2sze67hsacq5mi'` Strings of length 14-16 . [Answer] # C++ 57 ``` #include<iostream> #include<conio.h> int main(){std::cout<<getch();} ``` This program takes a character input and outputs its ASCII value. [Answer] ## Fortran - 85 bytes ``` l=0;read(*,*)n;do while(n>0);i=mod(n,10);l=l+i;n=n/10;enddo;print*,"digit sum=",l;end ``` Reads in a number and prints out the [sum of the digits](http://en.wikipedia.org/wiki/Digit_sum). Useful for [Project Euler](http://projecteuler.net/) problems. ]
[Question] [ This is the first in a series, the second is [Two roads diverged in a yellow wood (part 2)](https://codegolf.stackexchange.com/questions/114379/two-roads-diverged-in-a-yellow-wood-part-2) This challenge is inspired by Robert Frost's famous poem, "The Road Not Taken": > > Two roads diverged in a yellow wood, > > And sorry I could not travel both > > And be one traveler, long I stood > > And looked down one as far as I could > > To where it bent in the undergrowth; > > > Then took the other, as just as fair, > > And having perhaps the better claim, > > Because it was grassy and wanted wear; > > Though as for that the passing there > > Had worn them really about the same, > > > And both that morning equally lay > > In leaves no step had trodden black. > > Oh, I kept the first for another day! > > Yet knowing how way leads on to way, > > I doubted if I should ever come back. > > > I shall be telling this with a sigh > > Somewhere ages and ages hence: > > Two roads diverged in a wood, and I — > > I took the one less traveled by, > > And that has made all the difference. > > > Notice the second to last line, `I took the one less traveled by,`. ## Your actual challenge You will take input in the form like: ``` # ## # ## # ## # # # ``` and you have to find the thinner road. The road starts at the bottom with a `#`. The other 2 roads, which always terminate on the top row, are the roads you have to examine. The road that is the thickest is most traveled by, and therefore it is not what you want. The other one is the least traveled by, and it is the one you want. ## Output Your program/function must output one of 2 distinct values (eg. 0 or 1, true or false), one for each possible position of the road not taken. For example, you could output 0 if the road not taken is on the left of the road taken, and 1 otherwise, or you could output the string "left" or "right", true, false, etc. ## Test cases: ``` ## # ## # ### # # # ``` Might output "right". ``` ## # ## # ### ## # # # ``` Might output "right". ``` ## # ## # ### ## # # # ``` Might output "right". ``` ## # ## # ### # # # # ``` Might output "right". ``` # ## # ## ### # # # # ``` Might output "left" ``` # ## # ## ### # # # # ``` Might output "left" ## Notes * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins * [Standard loopholes forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * You must specify your outputs for "left" and "right" and they must be distinct * Input will be one big string, and may have any amount of lines * You don't need to worry about valid input. * The road is always a Y shape, so you only have to look at the top. * Have any questions? Comment below: ### Lowest byte count wins! [Answer] # JavaScript(ES6), ~~19~~ 14 bytes ``` a=>a.trim()[1] ``` Returns `#` for right and a space for left. ## **Original:** ``` a=>a.trim()[1]=='#' ``` ### Explanation **Ungolfed**: ``` function(input) { return input.trim().charAt(1) === '#'; }; ``` The first thing this function does is remove white space the beginning and end of the input. This means that the first character is always `#`. Then from there I check the second character(JavaScript starts at 0) and see if it is a `#` character. This returns a boolean. If the path is `right` it will be `true`, if it is left it will return `false`. ### How I golfed it In ES6 there is an [anonymous function](https://www.w3schools.com/js/js_function_definition.asp) shorthand called an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). This means that I can take my wrapper function and turn it into: ``` input => ...; ``` Due to the rules of arrow functions it will return the rest of the code. From there I converted `charAt(1)` to `[1]` as it is a shorter way, though [not recommended](https://stackoverflow.com/questions/5943726/string-charatx-or-stringx). Then I took `===` and turned it into `==`. While they are [different](https://stackoverflow.com/questions/523643/difference-between-and-in-javascript) in this case it doesn't matter. Finally, I renamed `input` to `a` and removed all whitespace. ### Output right and left While the puzzle doesn't actually need the program to output right and left, here's an example of other outputs: ``` a=>a.trim()[1]=='#'?'right':'left' ``` The only added part is `?'right':'left'`. This creates a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator), a condensed if statement, this means that the(ungolfed) code is equal to\*: ``` function(input) { let output = input.trim().charAt(1) === '#'; if(output) { return 'right'; } else { return 'left' } }; ``` # Example ``` // Function assignment not counted in byte count let f = a=>a.trim()[1]=='#' ``` ``` <textarea placeholder="Put path in here" id="path" rows="10" style="width:100%"></textarea> <button onclick="document.getElementById('result').textContent = f(document.getElementById('path').value)">Submit</button> <p id="result"></p> ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 1 byte ``` r ``` `r` puts the first string of adjacent non-whitespace characters from STDIN on the stack, so this prints `##` for *left* and `#` for *right*. [Try it online!](https://tio.run/nexus/cjam#@1/0/7@CsrICEChzKYBZIBrIAFMKKCQA "CJam – TIO Nexus") [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 30 bytes Because of the way *Acc!!* takes input, it will give the output after just one line of input is entered. But if you pipe the input in or redirect it from a file, you shouldn't notice the difference. ``` Count i while 35-N { } Write N ``` Takes input from stdin. Outputs if the left-hand road is less traveled, or `#` if the right-hand road is less traveled. [Try it online!](https://tio.run/##S0xOTkr6/985vzSvRCFToTwjMydVwdhU10@hmquWK7wosyRVwe//fwVlZQUgUOZSALNANJABphRQSAA "Acc!! – Try It Online") ### Explanation `N` reads the ASCII value of a character from stdin every time it is referenced. We loop while `35-N` is truthy; that is, while `35-N != 0` or `N != 35`. Therefore, when the loop exits, we have just read the first `#` character on the line. The next character is then read with `N` and written back to stdout with `Write`. [Answer] # Pyth, 2 bytes ``` hc ``` Outputs `#` for left and `##` for right. [**Try it online**](https://tio.run/nexus/pyth#@5@R/P@/koKyAhAoKyvE5CmA2FAWkFYG0wpQCpNWAgA) # Explanation ``` hc cQ Split the (implicit) input on whitespace. h Get the first part. ``` [Answer] # Retina, 5 bytes Outputs `1` if right, `0` if left. ``` ^ *## ``` [**Try it online**](https://tio.run/nexus/retina#@x@noKWs/P@/grICECgrK3ApgJgQBpBS5gKLg0l0CgA) --- If the values for a positive result didn't have to be distinct (5 bytes): Outputs a positive integer if right, zero if left. ``` ## +# ``` [**Try it online**](https://tio.run/nexus/retina#@6@srKCt/P@/grICEAA5XAogJoQBpJS5wOJgEp0CAA) [Answer] # IBM/Lotus Notes Formula Language, ~~37~~ ~~35~~ 26 bytes **Edit** I always forget that `@Like` with wildcards is 2 bytes cheaper than `@Contains`. **Edit 2** Actually doesn't need the `@if` as it just prints `1` or `0` depending on whether the formula results to `@True` or `@False`. ``` @Like(@Left(a;"##");"%#%") ``` Computed field formula. Simply take everything to the left of the first `##` it finds in field `a` and if there is a `#` in it outputs `1` for left otherwise outputs `0` for right. [![enter image description here](https://i.stack.imgur.com/81XNT.png)](https://i.stack.imgur.com/81XNT.png) [![enter image description here](https://i.stack.imgur.com/wBLK0.png)](https://i.stack.imgur.com/wBLK0.png) With thanks to @DavidArchibald, here is a solution for 22 bytes. Out of respect for Davids solution I won't post it as my main answer. ``` @Left(@Trim(a);2)="##" ``` This one outputs `1` for right and `0` for left. [Answer] # C, 35 bytes ``` f(char*s){while(35^*s++);return*s;} ``` Same idea as [PragmaticProgrammer's answer](https://codegolf.stackexchange.com/a/114335/30000): find the first `#`, and output what comes after it -- `#` for "right", and `<space>` for "left". # C (loophole), 16 bytes According to the test cases, it looks like the left road is always exactly one space from the left margin. So... ``` #define f(s)2[s] ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~8~~ 6 bytes ``` a~`#+` ``` Takes input as a command-line argument (which will need quoting and escaping of newlines when run from an actual command line). Outputs `#` if the left-hand road is less traveled, and `##` if the right-hand road is less traveled. [Try it online!](https://tio.run/nexus/pip#@59Yl6CsnfD//38FZQUgUFbmUgCxwDSQBFMKKCQA "Pip – TIO Nexus") ### Explanation This uses Pip's recently added regex first-match operator. ``` a First cmdline arg ~ Regex match the first instance of... `#+` ...one or more #s (i.e. a cross-section of the left-hand road) Print (implicit) ``` The straightforward regex solution (a port of [mbomb007's Retina answer](https://codegolf.stackexchange.com/a/114260/16766)) is 9 bytes: ``` `^ +##`Na ``` [Answer] # [Chip](https://github.com/Phlarx/chip), 7 bytes ``` AZ~S at ``` [Try it online!](https://tio.run/nexus/chip#@@8YVRfMlVjy/7@CsrKCAhApcCmAmMpgBpClDKIUIJQyWBIkAyT@65YBAA "Chip – TIO Nexus") Outputs `0x0` for left, and `0x1` for right. (The TIO includes flag `-v` so you can see the binary values in stderr. To see the output in ASCII, `e*f` can be appended to the end of the first line.) Chip operates on individual bits within a byte stream, which actually makes it quite good at this specific problem. `A` is the least significant bit of the input byte, and '#' is the only character of input for which this bit is set. When this bit is first encountered, we have reached the first '#' of the first line. `Z` delays that signal for one cycle, so that we are now looking at the next character. `t` is now activated, which means to terminate execution after this cycle is completed. We don't need to look further than the width of the first road. `~S` suppresses output for all cycles except the final one. If this wasn't here, we'd get an output on every cycle. `a` puts the current value of its neighbors (only `A` in this case) to the least significant bit of the output byte. All of this means that we get a `0x1` if the first '#' is immediately followed by another '#', and `0x0` otherwise. [Answer] ## Batch, 46 bytes ``` @set/ps= @for %%a in (%s%)do @echo %%a&exit/b ``` Reads one line from STDIN, splits it on spaces, and prints out the first word, so outputs `#` for left and `##` for right. If an array of quoted command-line parameters is acceptable, then for 36 bytes: ``` @for %%a in (%~1)do @echo %%a&exit/b ``` Unquotes the first argument so that it will be split on spaces and print its first word. [Answer] ## Python 2, 21 bytes [Try it online](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqgQbBWsV1yQk1mioRltEPu/oCgzr0QhR0FDXVkBCJSVY/IUlKE0kIRQILGYPGV1zf8A) ``` lambda S:S.split()[0] ``` Output `#` for left and `##` for right [Answer] # Brainfuck, 32 bytes ``` +[>,>+++++[<------>-]<--[,.>>]<] ``` ### Ungolfed: ``` +[ while 1 >,>+++++[<------>-]<-- 3 if hash; 0 if space [,.>>] print next char and break iff current char is hash <] ``` Prints `#` for right and for left. [Try it online!](https://tio.run/nexus/brainfuck#JYrBCcAwDAP/nUKgZ5JOELSI8f5juJYrBHcg1QptLSfumehkW@xXyptVIIEuHlg50kYDPzijFx8/ "brainfuck – TIO Nexus\"\"brainfuck – TIO Nexus") [Answer] ## [Retina](https://github.com/m-ender/retina), 5 bytes ``` !1`#+ ``` [Try it online!](https://tio.run/nexus/retina#i8njsuYKTrC25lLVAFL/FQ0TlLX//1dQVlYAAmUuBTALRAMZYEoBleSCKACyIWqVwQyEYgilgE4RpU0ZLAmSASuE6IEqxaIHVQuYhOgEKYYIQBgUa8GgAA "Retina – TIO Nexus") An alternative 5-byte solution. Prints `#` for left and `##` for right. The idea is to match all the runs of `#`s (`#+`) and print (`!`) only the first one of them (`1`). [Answer] # Haskell, 21 bytes ``` f n=snd$span(==' ')n!!1 ``` or in point-free style: ``` (!!1).snd.span(' '==) ``` "#" means right, and " " means left The function just takes a string, drops the beginning spaces, and then, it takes the second character (space if the left is skinny and # if the left is thick) EDIT: Saved three bytes thanks to Laikoni and nimi! [Answer] ## C 54 bytes ``` char*strchr();char c(char*s){return*(strchr(s,35)+1);} ``` ## C++ 58 bytes ``` #include<cstring> char c(char*s){return*(strchr(s,35)+1);} ``` Since OP specified it can be a "program/function" I elected to write a function to save characters. However, I still included the "#include" statement and accompanying line break in the character count as they are required to compile the function. **Output** Returns a space `" "` character to indicate left, or a hash `"#"` character to indicate right. **Explanation** The strchr() function walks a given string and returns a pointer to the first occurrence of a specified character. It has an overload which accepts an integer as the second argument as opposed to a char which saves me 1 character. E.g. '#' can be replaced with 35. I then add one to the pointer returned from the function to get the character immediately following, and dereference it, then return the resulting char. **Note** I would also like to take this opportunity to formally express my annoyance at Visual Studio auto-formatting my code when I'm trying to golf (╯°□°)╯︵ ┻━┻. **Edit:** Thanks to [Ray](https://codegolf.stackexchange.com/users/44809/ray) for pointing out some differences in C and C++ and where I could save characters <3. [Answer] # JavaScript (ES6), 37 bytes ``` p=s=>/^ *#( |$)/.test(s.split("\n")[0]) ``` ## Explanation: `p` is a function that returns `true` if the road less traveled by is on the left and false otherwise. This is my first answer on this site, so it probably could be golfed more (maybe the regex.) It works by taking the top line of the input and seeing if it matches the regex `/^ *#( |$)/` (start of string, any amount of spaces, a #, and a space or end of string.) This is just to give people clarification about the format and generate ideas. I am sure it can be beat and golfed further. Happy golfing! ``` p=s=>/^ *#[^#]/.test(s.split("\n")[0]) ``` ``` <textarea rows = "8" cols = "8" oninput = "console.log(p(this.value))"></textarea> ``` [Answer] ## Excel, 17 bytes ``` =left(trim(A1),2) ``` Assumes input in cell `A1`. Returns `##` for right and `#` (`#` and space) for left. [Answer] # [Perl 5](https://www.perl.org/), 8 + 1 = 9 bytes ``` die$F[0] ``` [Try it online!](https://tio.run/nexus/perl5#@5@SmariFm0Q@/@/grKyggIQKXApgJjKYAaQpQyiFCCUMlgSJANS@C@/oCQzP6/4v24iAA "Perl 5 – TIO Nexus") Run with `-a` (1 byte penalty). Output is `# at *filename* line 1, <> line 1` (where *filename* is the filename of the script) if the left road is less travelled, or `## at *filename* line 1, <> line 1` if the right road is less travelled. ## Explanation The `-a` option automatically reads input and splits it into columns around whitespace, ignoring leading whitespace. As such, the first datum of input is what we need; that's `$F[0]`. It also puts the program in an implicit loop, which we don't want. However, the use of `die` allows us to output a string, and exit the implicit loop, at the same time (and with no more characters than `say`, the more usual way to print a string). [Answer] # [Dyvil](https://github.com/Dyvil/Dyvil), 12 bytes ``` s=>s.trim[1] ``` Explanation: ``` s=> // lambda expression s.trim // removes leading (and trailing) whitespace [1] // gets the second character ``` Usage: ``` let f: String -> char = s=>s.trim[1] print f('...') ``` Returns (whitespace) for left and `#` for right. [Answer] # Java 8, ~~166~~ ~~66~~ ~~63~~ ~~52~~ ~~43~~ 21 bytes ``` s->s.trim().charAt(1) ``` Outputs `35` for right and `32` for left. Based on [*@Clashsoft*'s Dyvil answer](https://codegolf.stackexchange.com/a/114492/52210). [Try it online.](https://tio.run/##vZDLCsIwEEX3/YrBbJJFA65FwQ/QTZfqIsaqqW1amlEQ6bfXvATxgS7ETe7NzM2ZIYU4ibTYHHpZCmNgJpS@JABKY95uhcxh7q6@AJJm2Cq9A8NGttgl9jAoUEmYg4Zxb9KJ4TZSUcblXrRTpEPWj1yuOa5Lm4vxU602UNlZkbhYgWBhUHY2mFe8PiJvbAtLTTWXdACEuDZZavDWG@uCwoMMmF/xA84RI48EdweMCk/6MzYJAd918e/AN9xL8BPXyRfcsNXtQXT/4r7/4y7p@is) **Explanation:** ``` s-> // Method with String parameter and integer return-type s.trim() // Remove leading and trailing whitespaces .charAt(1) // and return the second character (as int value) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes ``` x ``` (2 bytes for `-g1` flag) Outputs `#` for right and a space for left. Based on the [JavaScript answer by David Archibald.](https://codegolf.stackexchange.com/a/114290/64424) [Try it online!](https://tio.run/nexus/japt#@1/x/7@SgrKyAhAox@QpgJlgBpAFoRXQKCUF3XRDAA "Japt – TIO Nexus") [Answer] # Befunge 98, 11 bytes ``` -!jv~' @.~< ``` [Try it Online!](https://tio.run/nexus/befunge-98#@6@rmFVWp87loFdn8/@/grKygoICEHMpgJgQBpClDKIUwKQyWE4BSgIA) Prints `32` for left, and `35` for right, both with a single trailing space. ### Explanation ``` -!jv This is a no-op the first time through, but used later ~' Pushes the ASCII value of the next character, and pushes 32 -! Subtracts the 2, and nots. If the character was a space, the top will be 1 jv Goes to the second line if the character was not a space ~< Pushes the next characer's ASCII value . Prints it (32 for " " and 35 for "#") @ Ends the program ``` One trick I used was putting the `-!jv` first, even though it didn't do anything. This let me both get rid of the space after the `'` and saved some padding. With this last, the code would be ``` ~' -!jv @.~< ``` for 15 bytes. [Answer] ## Ruby, 20 bytes ``` ->r{r.strip[1]==' '} ``` Returns true for left, false for right. [Answer] # Batch 34 bytes Checks input file `%1` using `Find` with conditional execution (`&&`=Success `||`=Fail) and returns L or R depending on the presence of `##` , which is only present when the road most travelled by is to the left. ``` @Find "## " %1>nul&&echo(R||echo(L ``` ]
[Question] [ Let's define the "unwrapped size" function `u` of a nested list `l` (containing only lists) by the following rules: * If `l` is empty, then `u(l)` is 1. * If `l` is non-empty, `u(l)` is equal to the sum of the unwrapped sizes of every element in `l`, plus one. Your task is to write a program (or function) that takes a list as input and outputs (or returns) the unwrapped size of the list. ## Test Cases: ``` [] -> 1 [[[]],[]] -> 4 [[[]],[[[[]],[]]],[[[]],[[[[]],[[],[[]]]]]]] -> 19 [[[[]]]] -> 4 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins. [Answer] # [Retina](http://github.com/mbuettner/retina), 1 byte ``` ] ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApd&input=W10KW1tbXV0sW11dCltbW11dLFtbW1tdXSxbXV1dLFtbW11dLFtbW1tdXSxbW10sW1tdXV1dXV1dCltbW1tdXV1d) (The first line enables a linefeed-separated test suite.) By default, Retina counts the number of matches of the given regex in the input. The unwrapped size is simply equal to the number of `[]` pairs in the input and therefore to the number of `]`. [Answer] ## Mathematica, 9 bytes ``` LeafCount ``` Turns out there's a built-in for that... Note that this wouldn't work if the lists actually contained non-list elements. What `LeafCount` really does is count the number of atomic subexpressions. For input `{{}, {{}}}`, the expression actually reads: ``` List[List[], List[List[]]] ``` Here the atomic subexpressions are actually the *heads* `List`. [Answer] ## Brainfuck, ~~71~~ ~~61~~ 59 bytes ``` +[>,]<[>-[<->---]+<------[->[-]<]>[-<+>]<[-<[<]<+>>[>]]<]<. ``` Takes input from STDIN in the format given in the question, and outputs [the character whose ASCII code](http://meta.codegolf.stackexchange.com/a/4719/3808) is the list's "unwrapped size." I'm still a complete amateur at Brainfuck, so there are most likely many optimizations that can still be made. [Try it online!](http://brainfuck.tryitonline.net/#code=K1s-LF08Wz4tWzwtPi0tLV0rPC0tLS0tLVstPlstXTxdPlstPCs-XTxbLTxbPF08Kz4-Wz5dXTxdPC4&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0&debug=on) Ungolfed: ``` read input to tape >>+[>,]< current tape: (0 0 1 a b *c) where abc represents input and * is IP now we loop over each character (from the end) this loops assumes we are starting on the (current) last char and it zeroes the entire string by the time it finishes [ subtract 91 from this character technically we only subtract 85 here and correct the answer with the 6 minus signs below >-[<->---] current tape: (0 0 1 a b cminus91 *0) invert the result and put that in the next cell +<------[->[-]<]> current tape: (0 0 1 a b 0 *c==91) move that result back to the original cell [-<+>]< current tape: (0 0 1 a b *c==91) if the result is true we found a brace increment the very first cell if so [-<[<]<+>>[>]]< current tape: (count 0 1 a *b) ] current tape: (count *0) <. ``` [Answer] # JavaScript (ES6), ~~29~~ 27 bytes ``` f=([x,...a])=>x?f(x)+f(a):1 ``` i love it when a recursion turns out this cleanly. This is basically a depth-first search of the input, adding 1 whenever the end of an array is reached. If an empty array were falsy in JS, this could be 24 bytes: ``` f=a=>a?f(a.pop())+f(a):1 ``` But alas, it's not. Other attempts: ``` f=a=>a.reduce((n,x)=>n+f(x),1) // Works, but 3 bytes longer f=a=>a.map(x=>n+=f(x),n=1)&&n // Works, but 2 bytes longer f=a=>(x=a.pop())?f(x)+f(a):1 // Works, but 1 byte longer f=a=>a[0]?f(a.pop())+f(a):1 // Works, but same byte count f=a=>a+a?f(a.pop())+f(a):1 // Doesn't work on any array containing 1 sub-array f=a=>a-1?f(a.pop())+f(a):1 // Same ``` [Answer] # Perl, ~~9~~ ~~8~~ 7 + 1 = 8 bytes Requires the `-p` flag ``` $_=y;[; ``` Thanks to @Dada for two byte saves (I'm loving this semicolon exploit btw) [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~7~~ 5 bytes *Thanks to Peter Taylor for removing 2 bytes! (`e=` instead of `f=:+`)* ``` r'[e= ``` [Try it online!](http://cjam.tryitonline.net/#code=cidbZT0&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) ``` r e# Read input '[ e# Push open bracket char e= e# Count occurrences. Implicit display ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 4 bytes ``` I'[¢ I Get input as a string '[¢ Count the opening square brackets and implicitly print them ``` [Try it online!](http://05ab1e.tryitonline.net/#code=SSdbwqI&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) I think it can be golfed more but that 'I' is mandatory, otherwise the input is considered an actual array instead of a string [Answer] # Ruby, 13 (+1) bytes ``` p $_.count ?[ ``` Called with `-n` argument: ``` ruby -ne 'p $_.count ?[' ``` EDIT: Changed to actually print out the answer [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 8 bytes ``` &- #,(/! ``` [Try it online!](http://labyrinth.tryitonline.net/#code=Ji0KIywoLyE&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) ### Explanation This counts the opening brackets via a bit of bitwise magic. If we consider the results of the character codes of the bitwise AND of `[`, `,` and `]` with `2`, we get: ``` [ , ] 2 0 0 ``` So if we just sum up the result of this operation for each character, we get twice the value we want. As for the code itself, the 2x2 block at the beginning is a small loop. On the first iteration `&-` don't really do anything except that they put an explicit zero on top of the implicit ones at the bottom of the stack. This will be the running total (and it will actually be negative to save a byte later). Then the loop goes as follows: ``` , Read character. At EOF this gives -1 which causes the instruction pointer to leave the loop. Otherwise, the loop continues. # Push the stack depth, 2. & Bitwise AND. - Subtract from running total. ``` Once we leave the loop, the following linear bit is executed: ``` ( Decrement to turn the -1 into a -2. / Divide negative running total by -2 to get desired result. ! Print. ``` The IP then hits a dead and turns around. When it tries to executed `/` again, the program terminates due to the attempted division by zero. [Answer] ## Python ~~3~~ 2, ~~36~~ 23 bytes ``` lambda x:`x`.count("[") ``` I noticed that `u(l)` is equal to the number of `[` in the string representation of `l`, so this program tries to do that. It could probably be golfed further by finding another way to do this, though... [Answer] # Python, 26 bytes ``` f=lambda a:sum(map(f,a))+1 ``` Simple recursive formula. [Answer] # C#, 46 41 bytes ``` int u(string l){return l.Count(c=>c=='[');} ``` l is the string of nested list. [Test it here](http://csharppad.com/gist/8259051f99d70bbb72c622f19ca72f60). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ߀S‘ ``` Doesn't use string manipulation. [Try it online!](http://jelly.tryitonline.net/#code=w5_igqxT4oCY&input=&args=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) or [verify all test cases](http://jelly.tryitonline.net/#code=w5_igqxT4oCYCsOH4oKsRw&input=&args=W10sIFtbW11dLFtdXSwgW1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0sIFtbW1tdXV1d). ### How it works ``` ߀S‘ Main link. Argument: A (array) ߀ Map the main link over A. S Sum. For empty arrays, this yields zero. ‘ Increment. ``` [Answer] # Regex, 1 byte ``` ] ``` [Try it online!](http://regexr.com/3ekjs) [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~63~~, 61 bytes ``` {({}[(((()()()){}){}()){({}[()])}{}]){{}(<>{}())(<>)}{}}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fVsoKCgoKSgpKCkpe30pe30oKSl7KHt9WygpXSl9e31dKXt7fSg8Pnt9KCkpKDw-KX17fX08Pg&input=W1tbXV1bW1tbXV1bXV1dW1tbXV1bW1tbXV1bW11bW11dXV1dXV0&args=LWE) 58 bytes of code, and +3 for the `-a` flag enabling ASCII input. Readable version/explanation: ``` #While non-empty: { #subtract ({}[ #91 (((()()()){}){}()){({}[()])}{} ]) #if non-zero { # Remove the difference {} #Increment the counter on the other stack (<>{}()) #Push a zero onto the main stack (<>) } #pop the left-over zero {} #endwhile } #Move back to the stack with the counter, implicitly display <> ``` [Answer] # [Befunge](https://en.wikipedia.org/wiki/Befunge), ~~22~~ ~~18~~ 16 bytes ``` ~:0#@`#.!#$_3%!+ ``` [TryItOnline!](http://befunge.tryitonline.net/#code=fjowI0BgIy4hIyRfMyUhKw&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) Edit: Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for shaving off 4 bytes! Edit2: Credit to [David Holderness](https://codegolf.stackexchange.com/users/62101/james-holderness) for optimizing out two more [Answer] # ///, 13 bytes ``` /[/0//]///,// ``` Output in unary. [Try it online!](http://slashes.tryitonline.net/#code=L1svMC8vXS8vLywvL1tbW11dLFtbW1tdXSxbXV1dLFtbW11dLFtbW1tdXSxbW10sW1tdXV1dXV1d&input=) **Explanation:** ``` /[/0/ Replace every [ with 0 /]///,// Remove every ] and , ``` [Answer] # PHP, 35 bytes ``` <?=preg_match_all('/\[/',$argv[1]); ``` `preg_match_all` finds all of the matching instances of the regular expression and returns a number, which is why the short echo tags are needed. Like most answers, it counts the number of `[` in the input and outputs that number [Answer] ## Racket 82 bytes ``` (define n 0)(let p((l l))(if(null? l)(set! n(+ 1 n))(begin(p(car l))(p(cdr l)))))n ``` Ungolfed: ``` (define (f l) (define n 0) (let loop ((l l)) (if (null? l) (set! n (add1 n)) (begin (loop (first l)) (loop (rest l))))) n) ``` Testing: ``` (f '[]) (f '[[[]] []]) (f '[[[]] [[[[]] []]] [[[]] [[[[]] [[] [[]]]]]]]) (f '[[[[]]]]) ``` Output: ``` 1 4 19 4 ``` [Answer] # [V](http://github.com/DJMcMayhem/V), 10 bytes ``` ÓÛ ÒC0@" ``` [Try it online!](http://v.tryitonline.net/#code=w5PDmwrDkgFDMBtAIg&input=W1tdXQ) This contains some unprintable characters, here is the readable version: ``` ÓÛ Ò<C-a>C0<esc>@" ``` `<C-a>` represents "ctrl-a" (ASCII `0x01`) and `<esc>` represents the escape key (ASCII `0x1b`). ``` ÓÛ " Remove all '['s " Ò<C-a> " Replace what's left with '<C-a>' (the increment command) C " Delete this line 0<esc> " And replace it with a '0' @" " Run what we just deleted as V code (A bunch of increment commands ``` More fun, less golfy version: ``` o0kòf]m`jòd ``` [Try it online!](http://v.tryitonline.net/#code=bzAba8OyZl1tYGoBD8OyZA&input=W11bXVtdW11bXQ) ``` o0<esc> " Put a '0' on the line below us k " Move back up a line ò ò " Recursively: f] " Move to a right-bracket m` " Add this location to our jumplist j " Move down a line <C-a> " Increment this number <C-o> " Move to the previous location d " Delete the bracket line " Implicitly display ``` [Answer] # Scala, 15 bytes ``` s=>s.count(92<) ``` Ungolfed: ``` s=>s.count(c=>92<c) ``` `count` counts how many elements satisfy a predicate, in this case `92<`, which is the method `<` of `92`. [Answer] # [O](https://github.com/phase/o), 15 bytes ``` i~{1\{nJ+}d}J;J ``` [Try it here!](http://o-lang.herokuapp.com/link/aX57MVx7bkorfWR9SjtK/W1tbXV0lMjBbW1tbXV0lMjBbXV1dJTIwW1tbXV0lMjBbW1tbXV0lMjBbW10lMjBbW11dXV1dXV0=) In the input, any commas must be either removed or replaced by spaces. ## Explanation ``` i~{1\{nJ+}d}J;J i Read a line of input. ~ Evaluate it. { }J; Define a function and save it into the `J` variable. Currently, the input array is at the top of the stack. 1\ Push 1 and swap it with the input array. { }d For each element in the array... Because the array was popped by `d`, 1 is at the TOS. nJ+ Recurse and add the result to 1. J Initiate the function call. The result is printed implicitly. ``` ## If we're allowed to take work on a string: 10 bytes ``` ie\']-e@-p ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~21~~ ~~20~~ 18 bytes ``` 0i:0(90.;n?|3%0=+! ``` Edit: score 1 for goto statements! Edit 2: Apparently ><> differs from Befunge in that it allows non-zero IP offset after wrapping (in other words, by using a trampoline instruction, I can wrap to (1, 0) instead of (0, 0)). Interesting. [TryItOnline!](http://fish.tryitonline.net/#code=MGk6MCg5MC47bj98MyUwPSsh&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) [Answer] ## Brainfuck, 28 bytes ``` , [ - [ - [ >+<- [->] ] >[>>] <<< ] , ] >. ``` [Try it online.](http://brainfuck.tryitonline.net/#code=LFstWy1bPis8LVstPl1dPls-Pl08PDxdLF0-Lg&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0&debug=on) This counts the number of input characters divisible by 3, i.e. the number of `]` characters. Alternate 34-byte solution counting `[` characters directly and relying on 8-bit cells: ``` , [ <-[>-<---] >------ [>-<[-]] >+<, ] >. ``` [Answer] # C, ~~48~~ 46 Bytes Saved two bytes thanks to kirbyfan64sos ``` i;f(char*v){for(i=0;*v;i+=*v++==91);return i;} i;f(char*v){for(i=0;*v;*v++^91?0:i++);return i;} ``` Test code ``` main() { printf("%d\n", f("[]")); printf("%d\n", f("[[[]] []]")); printf("%d\n", f("[[[]] [[[[]] []]] [[[]] [[[[]] [[] [[]]]]]]]")); } ``` Test cases ``` a.exe 1 4 19 ``` [Answer] ## [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) repl, 39 bytes ``` (d u(q((L)(i L(s(u(h L))(s 0(u(t L))))1 ``` Defines a function `u` that can be called like `(u (q ((())()) ))` (for the second test case). Doing it in the repl saves 4 bytes due to auto-closed parentheses. ### Explanation ``` (d u ) Define u as (q ) the following, unevaluated ( ) list (which acts as a function in tinylisp): (L) Given arglist of one element, L, return: (i L ) If L (is nonempty): (s(u(h L)) ) Call u on head of L and subtract (s 0 ) 0 minus (u(t L)) call u on tail of L 1 Else, 1 ``` The `x-(0-y)` construct is necessary because tinylisp doesn't have a built-in addition function, only subtraction. [Answer] # [Befunge-98](http://quadium.net/funge/spec98.html), ~~12~~ ~~11~~ ~~10~~ 9 bytes ``` ~3%!+2j@. ``` [TryItOnline!](http://befunge-98.tryitonline.net/#code=fjMlISsyakAu&input=W1tbXV0sW1tbW11dLFtdXV0sW1tbXV0sW1tbW11dLFtbXSxbW11dXV1dXV0) Edit: Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for shaving off a byte [Answer] # Haskell, ~~20 19~~ 17 bytes ``` f s=sum[1|']'<-s] ``` [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVcjMK0ktSkwuUVBRKM7IL1fQU0j7n6ZQbFtcmhttWKMeq26jWxz7/390dHRsrE40lIqFsJFEosEYAgA "Haskell – TIO Nexus") Takes the list as string and puts a `1` in a list for each `]`, then sums up all the `1`s. --- **Pointfree version:** (19 bytes) ``` length.filter(>'[') ``` Assumes `, [ ]` are the only chars in the string. Filters the list to get all chars greater than `[`, which are all `]` and returns the length. Usage: ``` Prelude> length.filter(=='[')$"[[[]],[[[[]],[]]],[[[]],[[[[]],[[],[[]]]]]]]" 19 ``` [Answer] # Bash + coreutils, 29 bytes ``` f()(echo $1|tr -d -c [|wc -c) ``` [Answer] # [DASH](https://github.com/molarmanful/DASH), 14 bytes ``` (ss[len;!> ="] ``` Simply counts `]`'s. Usage: ``` (ss[len;!> ="]"])"[[]]" ``` # Bonus solution, 15 bytes ``` a\@+1sum ->#a#0 ``` This one recursively counts from a real list. Usage: ``` (f\@+1sum ->#f#0)[[]] ``` ]
[Question] [ There is a well known question [here](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence) that asks for a short (least characters) fibonacci sequence generator. I would like to know if someone can generate the first N elements only, of the fibonacci sequence, in very short space. I am trying to do it in python, but I'm interested in any short answer, in any language. Function F(N) generates the first N elements of the sequence, either returns them as the return of the function or prints them. Interestingly it seems that the code-golf answers start with `1 1 2`, instead of `0 1 1 2`. Is that a convention in code-golf or programming-in-general? (Wikipedia says the fibonacci sequence starts with zero.). Python Sample (First 5 Elements): ``` def f(i,j,n): if n>0: print i; f(j,i+j,n-1) f(1,1,5) ``` [Answer] ## C Didn't bother counting, but here's a fun example: ``` f(n){return n<4?1:f(--n)+f(--n);} main(a,b){for(scanf("%d",&b);a++<=b;printf("%d ",f(a)));} ``` [Proof it works.](http://ideone.com/u4z28) --- I'm quite proud of this: I got bored, so I rearranged my code (with a few small additions) to make it where each line represents a value in the Fibonacci sequence. ``` # // 1 f // 1 // // 2 (n) // 3 {/**/ // 5 return n // 8 <2 ? 1:f(--n) // 13 +f(--n); } main(a, b) // 21 {a = 0, b = 0;scanf("%d",&b); for( // 34 ;a < b; a+=1) { int res = f(a); printf("%d ", res); } } // 55 ``` [Proof it works.](http://ideone.com/1fNDi) [Answer] ## Haskell (26) Surprisingly, this is only *one* character longer than the J solution. ``` f=(`take`s) s=0:scanl(+)1s ``` I shave off a few characters by: 1. Using `take` as a binary operator; 2. Using `scanl` instead of the verbose `zipWith`. [Answer] Here's a one-liner Python. It uses floating-point, so there may be some `n` for which it is no longer accurate. ``` F=lambda n:' '.join('%d'%(((1+5**.5)/2)**i/5**.5+.5)for i in range(n)) ``` `F(n)` returns a string containing the first `n` Fibonacci numbers separated by spaces. [Answer] ## GolfScript, 16 characters ``` ~0 1@{.2$+}*;;]` ``` **Example output:** ``` $ ruby golfscript.rb ~/Code/golf/fib.gs <<< "12" [0 1 1 2 3 5 8 13 21 34 55 89] ``` [Answer] ## Perl, 50 characters ``` sub f{($a,$b,$c)=@_;$c--&&say($a)&&f($b,$a+$b,$c)} ``` [Answer] ### Scala 71: ``` def f(c:Int,a:Int=0,b:Int=1):Unit={println(a);if(c>0)f(c-1,b,a+b)};f(9) ``` prints ``` 0 1 1 2 3 5 8 13 21 34 ``` [Answer] # Python(55) ``` a,b=0,1 for i in range(int(input())):a,b=b,a+b;print(b) ``` [Answer] # Perl, ~~29~~ 28 bytes ``` perl -E'say$b+=$;=$b-$;for-pop..--$;' 8 1 1 2 3 5 8 13 21 ``` ## Explanation This is based on the classic `$b += $a = $b-$a` recurrence which works as follows: * At the start of each loop `$a` contains `F(n-2)` and `$b` contains `F(n)` * After `$a = $b-$a` `$a` contains `F(n-1)` * After `$b += $a` `$b` contains `F(n+1)` The problem here is the initialization. The classical way is `$b += $a = $b-$a || 1` but then the sequence goes `1 2 3 5 ...` By extending the fibonacci sequence to the left: ``` ... 5 -3 2 -1 1 0 1 1 2 3 5 ... ``` you see that the proper starting point is `$a = -1` and `$b = 0`. Initializing $a can be combined with setting up the loop Finally replace `$a` by `$;` to get rid of the space before the `for` [Answer] I can give you a two line Python solution. This will return them as a list. ``` f = lambda n: 1 if n < 2 else f(n-1) + f(n-2) g = lambda m: map(f, range(0,m)) print g(5) ``` You could have it print them out by adding another map to make them strings and then adding a join, but that just seems unnecessary to me. Unfortunately I don't know how to put a recursive lambda into `map`, so I'm stuck at two lines. [Answer] ## Python (78 chars) I used [Binet's formula](http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html) to calculate the fibonacci numbers - > > [(1+sqrt(5))^n-(1-sqrt(5)^n]/[(2^n)sqrt(5)] > > > It's not as small some of the other answers here, but boy it's fast ``` n=input() i=1 x=5**0.5 while i<=n: print ((1+x)**i-(1-x)**i)/((2**i)*x) i+=1 ``` [Answer] # Scheme This is optimized using tail-recursion: ``` (define (fib n) (let fib ([n n] [a 0] [b 1]) (if (zero? n) (list a) (cons a (fib (- n 1) b (+ a b)))))) ``` [Answer] ## Haskell ``` fib n = take n f f = 0:1:zipWith (+) f (tail f) ``` [Proof that it works](http://ideone.com/9nlsp). [Answer] ## J, 25 characters I realise that J solutions are probably not what you're after, but here's one anyway. :-) ``` 0 1(],+/&(_2&{.))@[&0~2-~ ``` Usage: ``` 0 1(],+/&(_2&{.))@[&0~2-~ 6 0 1 1 2 3 5 0 1(],+/&(_2&{.))@[&0~2-~ 10 0 1 1 2 3 5 8 13 21 34 ``` How it works: Starting from the right (because J programs are read from right to left), `2-~ 6` The `~` operator reverses the argument to the verb so this is the same as `6-2` Ignoring the section in brackets for now, `0 1(...)@[&0~ x`takes the verb in the brackets and executes it `x` times using the list `0 1` as its input - `~` again reverses the arguments here, giving `x (...)@[&0 ] 0 1`, meaning I can keep the input at the end of the function. Within the brackets is a fork `],+/&(_2&{.)` which is made up of three verbs - `]`, `,` and `+/&(_2&{.)`. A fork takes three verbs `a b c` and uses them like this: `(x a y) b (x c y)` where `x` and `y` are the arguments to the fork. The `,` is the centre verb in this fork and joins the results of `x ] y` and `x +/&(_2&{.) y` together. `]` returns the left argument unaltered so `x ] y` evaluates to `x`. `+/&(_2&{.)` takes the last two items from the given list `(_2&{.)` - in this case `0 1` - and then adds them together `+/` (the `&`s just act as glue). Once the verb has operated once the result is fed back in for the next run, generating the sequence. [Answer] ## TI-Basic, 43 characters ``` :1→Y:0→X :For(N,1,N :Disp X :Y→Z :X+Y→Y :Z→X :End ``` This code can be directly inserted into the main program, or made into a separate program that is referenced by the first. [Answer] ### APL (33) ``` {⍎'⎕','←0,1',⍨'←A,+/¯2↑A'⍴⍨9×⍵-2} ``` Usage: ``` {⍎'⎕','←0,1',⍨'←A,+/¯2↑A'⍴⍨9×⍵-2}7 0 1 1 2 3 5 8 ``` [Answer] # Powershell - 35 characters Powershell accepts pipeline **input**, so I'm of the belief that the `n |` in `n | <mycode>` shouldn't be against my count, but instead is just a part of initiating a "function" in the language. The first solution assumes we start at 0: ``` %{for($2=1;$_--){($2=($1+=$2)-$2)}} ``` The second solution assumes we can start at 1: ``` %{for($2=1;$_--){($1=($2+=$1)-$1)}} ``` Example invocation: `5 | %{for($2=1;$_--){($1=($2+=$1)-$1)}}` Yields: ``` 1 1 2 3 5 ``` Interestingly, attempts to avoid the overhead of the `for()` loop resulted in the same character count: `%{$2=1;iex('($1=($2+=$1)-$1);'*$_)}`. [Answer] ## Python, 43 chars Here are three fundamentally different one-liners that don't use Binet's formula. ``` f=lambda n:reduce(lambda(r,a,b),c:(r+[b],a+b,a),'.'*n,([],1,0))[0] f=lambda n:map(lambda x:x.append(x[-1]+x[-2])or x,[[0,1]]*n)[0] def f(n):a=0;b=1;exec'print a;a,b=b,a+b;'*n ``` I've never abused `reduce` so badly. [Answer] # dc, 32 characters: This will actually always show the two first 1's, so the function only work as expected *for N >= 2*. ``` ?2-sn1df[dsa+plarln1-dsn0<q]dsqx ``` # C, 75 characters: Not as cool as the accepted answer, but shorter and way faster: ``` main(n,t,j,i){j=0,i=scanf("%d",&n);while(n--)t=i,i=j,printf("%d\n",j+=t);} ``` Extra: # CL, 64 characters: One of my most used [bookmarks](http://www.gigamonkeys.com/book/loop-for-black-belts.html) this semester has an interesting example which is shorter than many some of the other ones here, and it's just a straight-forward invocation of the `loop` macro -- basically just one statement! Stripped it for all the whitespace I could: ``` (loop repeat n for x = 0 then y and y = 1 then(+ x y)collect y) ``` Quite short, and nice and readable! To read input, `n` (including surrounding whitespaces) can be replaced with `(read)`, adding 3 characters. [Answer] # FALSE, 28 bytes ``` 0 1- 1 10[$][@@$@+$." "@1-]# ``` [Answer] # Python 2, 38 Bytes An improvement on a previously posted solution: ``` a=b=1 exec'print a;a,b=b,a+b;'*input() ``` This uses `exec` and string multiplication to avoid loops. # Python 3, 46 Bytes Not quite as efficient in Python 3: ``` a=b=1 exec('print(a);a,b=b,a+b;'*int(input())) ``` [Answer] # C99, 58 characters The following function fills an array of integers with the first `n` values from the Fibonacci sequence starting with 0. ``` void f(int*a,int n){for(int p=0,q=1;n--;q+=*a++)*a=p,p=q;} ``` Test harness, taking `n` as a command line argument: ``` #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int n = (argc > 1) ? atoi(argv[1]) : 1; int a[n]; f(a, n); for (int i = 0; i < n; ++i) printf("%d\n", a[i]); } ``` [Answer] ## CoffeeScript, 48 ``` f=(n,i=1,j=1)->(console.log i;f n-1,j,i+j)if n>0 ``` 65 in js: ``` function f(n,i,j){if(n>0)console.log(i),f(n-1,(j=j||1),(i||1)+j)} ``` [Answer] ## PHP, 87 ``` function f($n,$a=array(0,1)){echo' '.$a[0];$n>0?f(--$n,array($a[1],array_sum($a))):'';} ``` Uses `array_sum` and recursive function to generate series. Eg: ``` $ php5 fibo.php 9 0 1 1 2 3 5 8 13 21 34 ``` [Answer] **F#, 123** ``` let f n = Seq.unfold(fun (i,j)->Some(i,(j,i+j)))(0,1)|>Seq.take n f 5|>Seq.iter(fun x->printfn "%i" x) ``` [Answer] **Scala, 65 characters** ``` (Seq(1,0)/:(3 to 9)){(s,_)=>s.take(2).sum+:s}.sorted map println ``` This prints, for example, the first 9 Fibonacci numbers. For a more useable version taking the sequence length from console input, 70 characters are required: ``` (Seq(1,0)/:(3 to readInt)){(s,_)=>s.take(2).sum+:s}.sorted map println ``` Beware the use of a Range limits this to Int values. [Answer] ## Q 24 ``` f:{{x,sum -2#x}/[x;0 1]} ``` First n fibonacci numbers [Answer] # Lua, 85 bytes I am learning Lua so I would like to add this language to the pool. ``` function f(x) return (x<3) and 1 or f(x-1)+f(x-2) end for i=1,io.read() do print(f(i)) end ``` and the whole thing took 85 characters, with the parameter as a command line argument. Another good point is that is easy to read. [Answer] # FALSE, 20 characters ``` ^1@[1-$][@2ø+$.\9,]# ``` Input should be on the stack before running this. [Answer] # [Pyt](https://github.com/mudkip201/pyt), 3 bytes ``` ř⁻Ḟ ``` [Try it online!](https://tio.run/##K6gs@f//6MxHjbsf7pj3/7@RAQA "Pyt – Try It Online") ``` ř creates an array [1, 2, 3, ..., x] ⁻ decrements every item once (as Ḟ is 0 indexed) Ḟ for every item in x converts it to it's fibonacci equivalent ``` [Answer] # x86 machine code - 379 bytes The version with ELF headers scoring 484 bytes: ``` 00000000: 7f45 4c46 0101 0100 0000 0000 0000 0000 .ELF............ 00000010: 0200 0300 0100 0000 c080 0408 3400 0000 ............4... 00000020: 0000 0000 0000 0000 3400 2000 0200 2800 ........4. ...(. 00000030: 0000 0000 0100 0000 0000 0000 0080 0408 ................ 00000040: 0000 0000 e401 0000 0010 0000 0500 0000 ................ 00000050: 0010 0000 0100 0000 0000 0000 0090 0408 ................ 00000060: 0000 0000 0000 0000 0000 1000 0600 0000 ................ 00000070: 0010 0000 0000 0000 0000 0000 0000 0000 ................ 00000080: 51b9 0090 0408 8801 31c0 ba01 0000 00eb Q.......1....... 00000090: 0351 89c1 31c0 89c3 43b0 04cd 8031 c099 .Q..1...C....1.. 000000a0: 4259 c300 0000 0000 0000 0000 0000 0000 BY.............. 000000b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000c0: 31c0 9942 b903 9004 08c6 4101 0ac6 4102 1..B......A...A. 000000d0: 01c6 4103 013a 7103 0f84 ff00 0000 3a71 ..A..:q.......:q 000000e0: 0374 2680 4103 050f b641 036b c008 0041 .t&.A....A.k...A 000000f0: 048a 4104 e887 ffff ff80 6904 30c6 4103 ..A.......i.0.A. 00000100: 0183 e903 3a71 0375 da8a 4104 e86f ffff ....:q.u..A..o.. 00000110: ff3a 7106 0f84 ba00 0000 0fb6 4105 8841 .:q.........A..A 00000120: 060f b641 0788 4105 0fb6 4107 0041 06c6 ...A..A...A..A.. 00000130: 4107 003a 7106 0f84 8800 0000 c641 0701 A..:q........A.. 00000140: fe49 063a 7106 0f84 7800 0000 c641 0702 .I.:q...x....A.. 00000150: fe49 063a 7106 0f84 6800 0000 c641 0703 .I.:q...h....A.. 00000160: fe49 063a 7106 0f84 5800 0000 c641 0704 .I.:q...X....A.. 00000170: fe49 063a 7106 744c c641 0705 fe49 063a .I.:q.tL.A...I.: 00000180: 7106 7440 c641 0706 fe49 063a 7106 7434 [[email protected]](/cdn-cgi/l/email-protection).:q.t4 00000190: c641 0707 fe49 063a 7106 7428 c641 0708 .A...I.:q.t(.A.. 000001a0: fe49 063a 7106 741c c641 0709 fe49 063a .I.:q.t..A...I.: 000001b0: 7106 7410 fe41 08fe 4109 fe49 060f b641 q.t..A..A..I...A 000001c0: 0688 4107 c641 0601 83c1 033a 7106 0f85 ..A..A.....:q... 000001d0: 46ff ffff 3a71 030f 8501 ffff ffb3 0031 F...:q.........1 000001e0: c040 cd80 .@.. ``` Headerless version (that is the one to be graded): ``` 00000000: 67c6 4101 0a67 c641 0201 67c6 4103 0167 g.A..g.A..g.A..g 00000010: 3a71 030f 842a 0167 3a71 0374 2e67 8041 :q...*.g:q.t.g.A 00000020: 0305 6667 0fb6 4103 666b c008 6700 4104 ..fg..A.fk..g.A. 00000030: 678a 4104 e80d 0167 8069 0430 67c6 4103 g.A....g.i.0g.A. 00000040: 0166 83e9 0367 3a71 0375 d267 8a41 04e8 .f...g:q.u.g.A.. 00000050: f200 673a 7106 0f84 df00 6667 0fb6 4105 ..g:q.....fg..A. 00000060: 6788 4106 6667 0fb6 4107 6788 4105 6667 g.A.fg..A.g.A.fg 00000070: 0fb6 4107 6700 4106 67c6 4107 0067 3a71 ..A.g.A.g.A..g:q 00000080: 060f 84a3 0067 c641 0701 67fe 4906 673a .....g.A..g.I.g: 00000090: 7106 0f84 9200 67c6 4107 0267 fe49 0667 q.....g.A..g.I.g 000000a0: 3a71 060f 8481 0067 c641 0703 67fe 4906 :q.....g.A..g.I. 000000b0: 673a 7106 0f84 7000 67c6 4107 0467 fe49 g:q...p.g.A..g.I 000000c0: 0667 3a71 0674 6167 c641 0705 67fe 4906 .g:q.tag.A..g.I. 000000d0: 673a 7106 7452 67c6 4107 0667 fe49 0667 g:q.tRg.A..g.I.g 000000e0: 3a71 0674 4367 c641 0707 67fe 4906 673a :q.tCg.A..g.I.g: 000000f0: 7106 7434 67c6 4107 0867 fe49 0667 3a71 q.t4g.A..g.I.g:q 00000100: 0674 2567 c641 0709 67fe 4906 673a 7106 .t%g.A..g.I.g:q. 00000110: 7416 67fe 4108 67fe 4109 67fe 4906 6667 t.g.A.g.A.g.I.fg 00000120: 0fb6 4106 6788 4107 67c6 4106 0166 83c1 ..A.g.A.g.A..f.. 00000130: 0367 3a71 060f 8521 ff67 3a71 030f 85d6 .g:q...!.g:q.... 00000140: fe00 0000 6651 66b9 7801 0000 6788 0166 ....fQf.x...g..f 00000150: 31c0 66ba 0100 0000 eb05 6651 6689 c166 1.f.......fQf..f 00000160: 31c0 6689 c366 43b0 04cd 8066 31c0 6699 1.f..fC....f1.f. 00000170: 6642 6659 c300 0000 0000 00 fBfY....... ``` Calculates (possibly) \$ \infty \$ fibonacci numbers. ]
[Question] [ # Introduction The Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of `[1, 2]` and `[3, 4]` is `[(1, 3), (1, 4), (2, 3), (2, 4)]`. The product of `[1]` and `[2]` is `[(1, 2)]`. However, no one said you could only use two lists. The product of `[1, 2]`, `[3, 4]`, and `[5, 6]` is `[(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]`. # Challenge Given a number of lists, your program must output the Cartesian product of the lists given. * You can assume that there will always be more than 1 list, and that each list will have the same length. No list will ever be empty. If your language has no method of stdin, you may take input from command line arguments or a variable. * Your program must output the Cartesian product of all the input lists. If your language has no stdout, you may store output in a variable or as a return value. The output should be a list of lists, or any other iterable type. # Example I/O > > Input: `[1, 2] [3, 4]` > > Output: `[(1, 3), (1, 4), (2, 3), (2, 4)]` > > > Input: `[1, 2] [3, 4] [5, 6]` > > Output: `[(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]` > > > Input: `[1, 2, 3] [4, 5, 6]` > > Output: `[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]` > > > # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins! [Answer] # [J](http://jsoftware.com/), 1 byte Courtesy of [ngn](https://chat.stackexchange.com/transcript/message/52583691#52583691) ``` { ``` [Try it online!](https://tio.run/##y/r/P03B1kqh@n9qcka@QpqCoYKRtbGCCReYq66rq6vOhSpjbapghl1WwdjaRAEo@x8A "J – Try It Online") 'tis called [Catalogue](https://code.jsoftware.com/wiki/Vocabulary/curlylf)… [Answer] # [Haskell](https://www.haskell.org/), 7 bytes ``` mapM id ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFchMwVIZ@Yp2Cqk5HMpAEFBUWZeiYKKQppCdLShjoJRrI5CtLGOgklsLH5pIG2qo2CGQ5mOgjFIhYmOAkTR/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") ## Built-in, 8 bytes ``` sequence ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvzi1sDQ1Lzn1f25iZp6CrUJKPpcCEBQUZeaVKKgopClERxvqKBjF6ihEG@somMTG4pcG0qY6CmY4lOkoGINUmOgoQBT9/5eclpOYXvxfN7mgAAA "Haskell – Try It Online") ## Less boring, 33 bytes Out-golfed by [xnor's answer](https://codegolf.stackexchange.com/a/195977). Go upvote that instead! ``` f[]=[[]] f(h:t)=[i:j|i<-h,j<-f t] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/Py061jY6OjaWK00jw6pE0zY60yqrJtNGN0Mny0Y3TaEk9n9uYmaegq1CSj6XAhAUFGXmlSioKKQpREcb6igYxeooRBvrKJgATcArDaRNdRTMcCjTUTAGqTDRUYAo@g8A "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 23 bytes ``` foldr((<*>).map(:))[[]] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/J6VIQ8NGy05TLzexQMNKUzM6Ojb2f25iZp6CrUJKPpcCEBQUZeaVKKgopClERxvqKBjF6ihEG@somMTG4pcG0qY6CmY4lOkoGINUmOgoQBT9/5eclpOYXvxfN7mgAAA "Haskell – Try It Online") Without using `mapM` or `sequence` or the like. [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` def f(M,*l):M and[f(M[1:],*l,x)for x in M[0]]or print(l) ``` [Try it online!](https://tio.run/##Zc4xDoMwDAXQGU7hLaT6Q2loB@6QE1geaNOoSCggxBBOnxoxdOjg4b8/fC/79pmTKyW8I8XG4zLZ3tOQAmvithcVZBvnlTKNiTxfRTQs65i2ZrLlaPzRMJvh@TIwQS/vRqDUgm4CdqBO/gB8Bz1@DnJqHehk6etKn7B1dY7Z8gU "Python 3 – Try It Online") No itertools. This is one of those weird functions that prints. Thanks to Unrelated String for -2 bytes with `def`. [Answer] # [Python 2](https://docs.python.org/2/), ~~60~~ 59 bytes ``` f=lambda A,*x:[[v]+u for v in A for u in x and f(*x)or[[]]] ``` [Try it online!](https://tio.run/##ZY29DoIwFIVnfYqzVfAuAjqQMPQ5bu5QbBpJtBACpDx9Lf7EweEk3/nOcIZ1uvW@iNE1d/NorYGmPNTMixxnuH7Egs5Dv3DeMMB4C3fIQ9aPzCISt01vG7My7VWRsilhVUJJnQiFEJeESv4E8Zlw@XlCmVxFeGtIvd8NY@cn6C@ka519SnwC "Python 2 – Try It Online") 1 byte thx to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). Look Ma! No `itertools`! [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) A simple reduction by Cartesian product. ``` rï ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=cu8&input=W1sxLDJdLFszLDRdLFs1LDZdXQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 2 bytes ``` Œp ``` [Try it online!](https://tio.run/##y0rNyan8///opIL/h9sfNa3JAmIQatynoxAJ5jfuO7Tt0Lb//6O5OKOjDXUUjGJ1FKKNdRRMYmN1MISAtKmOghmSlI6CMUjUREcBTQJDD5A211GwANGWOgoGIKWxAA "Jelly – Try It Online") Output is "pretty printed" in the TIO link [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 1 byte ``` ẋ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@Gu7v//oxWiow11FIxidaKNdRRMYmN10AR0ok11FMwQ4joKxkAxEx0FiLBCLAA "Brachylog – Try It Online") A slightly less boring [generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) solution: # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` ∋ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/486ukHU/2iF6GhDHQWjWJ1oYx0Fk9hYHTQBnWhTHQUzhLiOgjFQzERHASKsEAsA "Brachylog – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~31~~ 15 bytes ``` {x@'/:+!(#:)'x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qusJBXd9KW1FD2UpTvaL2f5q6hoahgpG1sYKJpjWMZW2qYAbhKRhbmyiAeJr/AQ "K (oK) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~8~~ 4 bytes ``` &[X] ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfLToi9r81V3FipUKaQrShjlGsTrSxjgmQNNUxi/0PAA "Perl 6 – Try It Online") Simple reduce by cross product. ~~It would be nice if I could return the meta-operator by itself, but I've never figured out how to do that.~~ Turns out it works for cross product? [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes ``` ->i,*j{i.product *j} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5TRyurOlOvoCg/pTS5REErq/Z/QVFmXolCml5yYk6ORrShjoJRrI5CtLGOgkmsJldBaUmxgpISFx5FQNpUR8EMr2IdBWOQOhMdBYjS/wA) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~54~~ ~~39~~ 32 bytes This took really long to write (as I tried to golf it too) (unsurprisingly, all the golfing ideas only appeared after I finally posted this). Takes input as a list of strings of alphanumeric characters and underscores (whatever `\w` matches in your universe), each preceded by a semicolon (I assume characters are as acceptable in Retina as numbers are in everything else; in fact, the challenge never actually specified numbers). Outputs the list of the resulting strings, each preceded by a comma. ``` ^ , +w`,(\w*)[^;]*;\w*(\w) ,$1$2 ``` Explanation: ``` ^ match the beginning of the string , add a comma there +w`,(\w*)[^;]*;\w*(\w) solve the rest of the problem ,$1$2 replace with a comma, group 1 and group 2 ``` The third and fourth lines are in a convergence loop (run until no change) (declared by the `+`). The regular expression in the 3rd line works on lines like `, ac, bc, ad, bd;ef;gh` and matches all substrings starting at a comma and ending at a character after the first semicolon, where the group 1 is the string after the comma and group 2 is the last character. [Try it online!](https://tio.run/##K0otycxLNPz/P45Lh0u7PEFHI6ZcSzM6zjpWyxrIAvI0uXRUDFWM/v@3TkyyTk6xTk2zTs8AAA "Retina – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~54~~ 47 bytes ``` f=function(x)split(j<-expand.grid(x),1:nrow(j)) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQrO4ICezRCPLRje1oiAxL0UvvSgzBSisY2iVV5RfrpGlqfm/oCgzr0RDKbXCUEmTC8JJ08jJLC7RMLQy0jG2MtHUhIkDFRnhUKRjamWGotAYU6GxjglY0X8A "R – Try It Online") If you consider data.frame rows iterable: # [R](https://www.r-project.org/), 27 bytes ``` f=function(x)expand.grid(x) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQjO1oiAxL0UvvSgzBcj7X1CUmVeioZRaYaikyQXhpGnkZBaXaBhaGekYW5loasLEgYqMcCjSMbUyQ1FojKnQWMcErOg/AA "R – Try It Online") [Answer] # [Python 3 (Cython)](http://cython.org/), ~~46~~ ~~44~~ 31 bytes ``` __import__('itertools').product ``` [Try it online!](https://tio.run/##K6gsycjPM9ZNBtP/0xRsFWL@x8dn5hbkF5XEx2uoZ5akFpXk5@cUq2vqFRTlp5Qml/wvKMrMK9HQStOINtRRMIrVUYg21lEwAdGmOgpmsZqa/wE "Python 3 (Cython) – Try It Online") This doesn't need more explanation, right? (-13 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king); -2 bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 6 bytes ``` Tuples ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6S0ICe1@H9AUWZeSbSyrl1atHJsrJqCvoNCNZeCgkJ1taGOglGtjkK1sY6CSW2tDhZBIG2qo2CGIqmjYAwSN9FRgEhx1f4HAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 30 bytes ``` for l;a=($^a\ ${^${=l}}) <<<$a ``` [Try it online!](https://tio.run/##qyrO@J@moanxPy2/SCHHOtFWQyUuMUZBpTpOpdo2p7ZWk8vGxkYl8b8mF1eagrqhgpG6grqxggmQNFUwU/8PAA "Zsh – Try It Online") Split `=` and cartesian product `^` for each element. Our base case adds an extra space, which cleanly separates our output lists. [Answer] ## Julia 1.0, 34 bytes No imports used, iterators in Base has this. It actually makes a lazy form of this, but to print them all it will collect each one. ``` println.(Iterators.product(l...)) ``` where l is the list of lists. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .»â ``` Outputs `[[a,b],[c,d],[d,e]]` in the format `[[[a,c],d], [[a,c],e], ...]`. To output in the format `[[a,[c,d]], [a,[c,e]], ...]`, replace the `»` with `«`. [Try it online](https://tio.run/##yy9OTMpM/f9f79Duw4v@/4@ONtQxitWJNtYxAZKmOmZA0lzHIjYWAA) or [try it online with right- instead of left-reduce](https://tio.run/##yy9OTMpM/f9f79Dqw4v@/4@ONtQxitWJNtYxAZKmOmZA0lzHIjYWAA). **Explanation:** ``` .» # (Left-)reduce by (or right-reduce with `.«`): â # Taking the cartesian product of the two lists # (after which the resulting list is output implicitly) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 1 byte ``` Π ``` [Try it online!](https://tio.run/##yygtzv6fm18erPOoqfH/uQX///@Pjo421DGK1Yk21jGJBVJIPJ1oUx0zmJiOMZBhogMWiQUA "Husk – Try It Online") `Π` takes the Cartesian product of a list of lists. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes Returns a list of lists. ``` f=([a,...b],o=[])=>a?a.flatMap(x=>f(b,[...o,x])):[o] ``` [Try it online!](https://tio.run/##fcoxDsIwDADAnVd4TCRjibYwIKW8oC@wPLilQaCormiF@vsQBkaYbrmHvnQZnvd53U92HXOOwbEiEfWCFlh8aPWiFJOunc5uC210PXIJhpt4f2aTPNi0WBop2c1Fx3xAqASBa4RGStr9DcUjwulnRKg/p0H4tvwG "JavaScript (Node.js) – Try It Online") --- # [JavaScript (V8)](https://v8.dev/), 52 bytes Prints the results. ``` f=([a,...b],o)=>a?a.map(x=>f(b,o?o+[,x]:x)):print(o) ``` [Try it online!](https://tio.run/##bcrBCsIwDIDhu0@RY4KxMDdFNro9SMghEwoTtGWO0bevDr3p6T/8381We17nKS2H9VJK8CjGzrlROZLvbTB3t4TZ9wFHjkPcC2dtM1Gb5umxYKQSUKRiOCqD1AyNKnXwudTtfu67J4bzf8VQb6Bh@JryAg "JavaScript (V8) – Try It Online") [Answer] # Erlang, 57 bytes ``` c([]) -> [[]]; c([H|T]) -> [[X|Y] || X <- H, Y <- c(T)]. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` rï ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cu8&input=WwogWzEsMl0sCiBbMyw0XSwKIFs1LDZdCl0KLVE) ``` Reduces input by combination with initial value of 1st element ``` Duplicate of @Shaggy answer, I was solving this while he just posted the same solution. I hope I can leave my answer too because it's awesome [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` IEΠEθLιEθ§λ÷ιΠ∨E…θμLν¹ ``` [Try it online!](https://tio.run/##PYwxC8IwFIT/yhtf4DlUq4uT6FKwtHvIEJJgH8REYyz@@0i0essdx31nJp1M1L6UMXHIeNSPjL2@4ZiifZpvvhOcXbjkCVkIQbB0h9wF617oCbqQTzyzdcgEP3RIH7qP3tb5VfxvQn1pxKJ9KVLKhmCtCOSGoK2@Jdgppcpq9m8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input list E Map over elements ι Current element L Length Π Product E Map over implicit range θ Input list E Map over elements λ Current element § Cyclically indexed by ι Outer index ÷ Integer divide θ Input list … Truncated to length μ Inner index E Map over elements ν Current element L Length ∨ ¹ Replace empty list with literal 1 Π Product I Cast to string Implicitly print double-spaced on separate lines ``` [Answer] # APL(NARS), chars 11, bytes 22 ``` {,↑(∘.,)/⍵} ``` test for product of sets: ``` f←{,↑(∘.,)/⍵} ⎕fmt (1 2)(3 4) ┌2────────────┐ │┌2───┐ ┌2───┐│ ││ 1 2│ │ 3 4││ │└~───┘ └~───┘2 └∊────────────┘ ⎕fmt f (1 2)(3 4) ┌4──────────────────────────┐ │┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│ ││ 1 3│ │ 1 4│ │ 2 3│ │ 2 4││ │└~───┘ └~───┘ └~───┘ └~───┘2 └∊──────────────────────────┘ ⎕fmt f (1 2)(3 4)(5 6) ┌8──────────────────────────────────────────────────────────────────────┐ │┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│ ││ 1 3 5│ │ 1 3 6│ │ 1 4 5│ │ 1 4 6│ │ 2 3 5│ │ 2 3 6│ │ 2 4 5│ │ 2 4 6││ │└~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘2 └∊──────────────────────────────────────────────────────────────────────┘ ≢f (1 2)(3 4)(5 6) 8 f (⍳3)(4 5 6) 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6 ⎕fmt f (4 5 6) ┌1───────┐ │┌3─────┐│ ││ 4 5 6││ │└~─────┘2 └∊───────┘ ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 136 bytes ``` import re from itertools import* print(list(product(*[[int(i) for i in i.split(', ')] for i in re.findall(r'\[([0-9, ]+)\]',input())]))) ``` [Try it online!](https://tio.run/##RckxDsIwDEDRvafwFruECiggOEvIgGgrLKVx5LoDpw8gBqYvvV9e9pTcX4rWynMRNdCxmVRmYBvVRNICv9E2RTkbJl4Mi8qwPgzbEL7GBJMoMHAG7paS2NB5cBT/rmM3cR7uKaG6W8Cw2149xA3dovOcy2pIFImo1rD3cIgQeg/HT04ezvEN "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ Let's say I have a non-empty list (array): ``` l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I want to incrementally slice the list into incremented amount of elements per chunk. For this array, my desired output is: ``` [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] ``` What would be the best way to slice the array in multiple chunks. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! Note: For the final chunk, if the number of elements left in `r` is less than what the incremented output requires, the last chunk should just be all that remains in the list. # Test cases: ``` l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -> [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] l = [10, 20, 30, 40] -> [[10], [20, 30], [40]] l = [100, 200, 300, 400, 500] -> [[100], [200, 300], [400, 500]] ``` [Answer] # [Python](https://www.python.org), 40 bytes ``` f=lambda a,n=1:a and[a[:n]]+f(a[n:],n+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JcpNCsIwEAbQq3zLhI5g6l8b6ElCFiMlGNBpKCnUs7jJRjyEC8_hbRSyepv3eKV7vkzSlvJccth0XxWGK9_OI4NJBmP_yujYWfG-CYqdWE_SGF3_O0wzVkRBUFHSkpXWNs1RMtY6yscZQkvYEfaEA-FIOBE6Qk8wW1_bDw) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~3~~ 2 bytes *Edit: -1 byte thanks to Razetime* ``` CN ``` [Try it online!](https://tio.run/##yygtzv7/39nv////0YY6RjrGOiY6pjpmOuY6FjqWOoYGsQA "Husk – Try It Online") ``` C # Cut off substrings of the following lengths: N # natural numbers ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` żẇ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwixbzhuociLCIiLCJbMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTBdXG5bMTAsIDIwLCAzMCwgNDBdXG5bMTAwLCAyMDAsIDMwMCwgNDAwLCA1MDBdIl0=) Upgrading got me like ## Explained ``` żẇ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌­ ż # ‎⁡The range [1, len(input)] ẇ # ‎⁢Wrap the input list into chunks of each number. Stops grouping when there's no more items 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Factor](https://factorcode.org/) + `grouping.extras math.unicode`, ~~58~~ 57 bytes ``` [ dup '[ _ index 1 + 2 * √ .5 + ⌊ ] group-by values ] ``` [Try it online!](https://tio.run/##NY7LagIxGIX3PsXZCZWGeBmvm@6KGzfS1SAlZv4ZgzYZcxGH4r6UPkEfzxcZE8XF/8P3HTicUkhvbPuxXq7e59iT1XRAaRs4OgbSkhy@hN/dHyuDll4Z/XAsaCVNQaisCbXSFaOzt8JBOGekQ23J@6a2SnssOp1v9DHAECNkGGOCKWboc1xSwDHgGHKMnpxEMklxZPEubY4i1Ojm@ITSBZ1jXy82vuD68w@WRbj@/WLzmPO6bXAShxD3b1pv1RtyMMZinKC9AQ "Factor – Try It Online") Group elements by the integer inverse triangular function of their indices. In other words, given a zero-based index \$i\$, its element belongs to group $$\left\lfloor\sqrt{2(i + 1)} + \frac{1}{2}\right\rfloor$$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` JÄ‘œṖ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/rcMujhhlHJz/cOe3/4fajkx7unPH/f7ShgYGOghGIMAYRJiDC1MAgFgA "Jelly – Try It Online")** ### How? ``` JÄ‘œṖ - Link: list, L e.g. [5,4,3,2,1,0,1,2] J - range of length of L [1,2,3,4,5,6,7,8] Ä - cumulative sums [1,3,6,10,15,21,28,36] ‘ - increment [2,4,7,11,16,22,29,37] œṖ - partition L before those indices [[5],[4,3],[2,1,0],[1,2]] ``` --- Also 5 bytes [TIO](https://tio.run/##y0rNyan8/9@rIuHQzmMz/x9uPzrp4c4Z//9HGxoY6CgYgQhjEGECIkwNDGIB): ``` Jx`¹ƙ ``` ...(`J`) range of length, (```) use right as both arguments with (`x`) repeat elements then (`ƙ`) apply to groups of identical values (`¹`) a no-op function. i.e. build a list like `[1,2,2,3,3,3,4,4,4,4,...]` and group the original values like its equal values, `[[1],[2,2],[3,3,3],[4,4,4,4],...]`. or, equivalently (just reapplying `J` rather than using the quick ```): ``` JxJ¹ƙ ``` [Answer] # Ruby, 38 bytes ``` ->l{(1..l.size).map{l.shift(_1)}-[[]]} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ≔⮌AθWθ⊞υE⌊⟦Lθ⊕Lυ⟧⊟θIυ ``` [Try it online!](https://tio.run/##LYw7C4MwFEb3/oqM90IK6WtyKp0EBekqDsFeTECvmof9@WkCXc7wncM3Gu3GVc8pPb23E8ObDnKeoOYtBkCUYsfq9DV2JgE7ii56A1GKVm/QWrZLXKBviKdgspai5tHRQhzoA/85Ig7ZdOuWC8xvnbMc4KV9KK5Kqe8vSklxLbgV3AseSg1DOh/zDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⮌Aθ ``` Reverse the input list. ``` Wθ ``` Repeat until it is empty... ``` ⊞υE⌊⟦Lθ⊕Lυ⟧⊟θ ``` ... pop up to the next number of items from the input list into a new group. ``` Iυ ``` Output the grouped list. [Answer] # [R](https://www.r-project.org/), 40 bytes ``` function(x)split(x,rep(s<-seq(!x),s)[s]) ``` [Try it online!](https://tio.run/##K/qfmZccX5RaEF@ck5mcavs/rTQvuSQzP0@jQrO4ICezRKNCByirUWyjW5xaqKFYoalTrBldHKuJqk/D0MrQQPM/AA "R – Try It Online") Inspired by [Giuseppe's answer](https://codegolf.stackexchange.com/a/238336/95126) to "[Chunk sort a sequence](https://codegolf.stackexchange.com/q/238329/95126)". [Answer] # [J](http://jsoftware.com/), 12 bytes ``` </.~#{.#\##\ ``` [Try it online!](https://tio.run/##TcsxDoJAFITh3lP8cQtiMqwPdhEkWplYWVnTGQmx8QAkXn1hG0MxXzGZ@aS9L0auPQXC6NeUntvzcU@Xo/@52bvBuSEddu/X9GWkErUIIopGnEQrOnEWlf1HRm0EI24qW5@ZkImZxiwt "J – Try It Online") Consider `10 20 30 40 50 60`: * `#\` Gives `1 2 3 4 5 6` (ie, 1...n). * `#\##\` Uses that list to "copy" itself: ``` 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 ``` * `#{.` Take only the first n elements of that: ``` 1 2 2 3 3 3 ``` * `</.~` Group the original input using that mask: ``` ┌──┬─────┬────────┐ │10│20 30│40 50 60│ └──┴─────┴────────┘ ``` [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` n![]=[] n!x=take n x:(n+1)!drop n x (1!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08xOtY2OpYrT7HCtiQxO1UhT6HCSiNP21BTMaUovwDE/Z@bmJlnW1CUmVeiYqgYbainZ2QZ@x8A "Haskell – Try It Online") There seems like there should be a shorter way to do this maybe with scans or folds, but I can't figure it out. [Answer] # APL+WIN, 18 bytes Prompts for a vector of numbers or a string of characters. Outputs a nested vector. ``` (m↑(⍳m)/⍳m←⍴n)⊂n←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0buo7aJGo96N@dq6oNIoMyj3i15mo@6mvJA7L6p/4HquP6ncRkqGCkYK5gomCqYKZgrWChYKhgacAGFDRSMDBSMDRRMIDwQF8QHCRgomBqARNUTk5JTUtPSMzKz1LkA "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 45 bytes ``` sub{my@r;push@r,[splice@_,0,1+@r]while@_;\@r} ``` [Try it online!](https://tio.run/##XY9tS8MwEMff91Mco7Mtnix92lOpVtg7wYGIb9oy5ky34rrFpEXHnF@9Jm0paOCSu3/@97uEUb73az0La1G9notTxANWiV3EMRZsn29otEKC9nXE089dvpdlkET8UgdaduSmBhBDbCM4CC6Ch@AjjBEmCFOEGYJNUghvIY7tFCF20FWHhz6OVTLBKc5QelJIsWMRCZPhyvBk87/VskgDI@g2ife3vwE0hAYhN5/0oK6/AyhChyCoXA3HOktUcTL1/MBQp1/MCiN9FTSivj2W4ZWemZG6tZRYCQqLdbmezxdVwShXGuP5ocwGQyFHSl9VhsMbx1OVxNFNSd@k4DpKUMChSA4D9QGAlmGqORbQj75Wz4A7MI7vBszBeFw@w/LBaHuKNet9Kyv8EaNEfCf6y/2TDeFotOXYfwUVONAuWv0L "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 92 bytes ``` a=>if(a.last.size>a.size)f(a.init++Seq(a.last.take(a.size))++Seq(a.last.drop(a.size)))else a ``` [Try it online!](https://tio.run/##fY5La8MwEITv@RVzlMhi5Ef6Aht6LOTWSyDksE1kUCtk11pKSelvdy3TBgJpDjvL7nyzbNyz57F7ebV7wQb2U2w4RDz2Pb4WwAd7tA/q2b5vUz0F2e3q5mzUqDFy3bhWceY5Shbd0TY8N52WLjhZLqfAHyD8ZtUvoM@cw9D1J0dbHy14BPrBBfFBoU2vzJVTQSVVtKIbuqU7uqfcTBHoxWXcUGGoNFRdpwyhSFImqZKszNXEP57KIR2mezqTbu2izNj3@AM "Scala – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~86~~ \$\cdots\$ ~~77~~ 76 bytes ``` r;i;f(a,n)int*a;{for(i=r=1;n--;r+=r*~r/2+i++?0:puts(""))printf("%d ",*a++);} ``` [Try it online!](https://tio.run/##hZLtasMgFIb/9yrOhIJGQ/PR7qPO9UK2MkLaFGGzJWYsrGSXvuzE2CXpnwmaeN7n@B7l5OEhz9u2lFoWNBOGaVMFmTwXx5JqVapYmjCUJVdl8F0uEq4530Tr00dlKSGMnUrkC0rmOyAiyDhnsmkxBO@ZNpTBeQY4ukC1t1X8vAUF51hAIiAVsBSwEnAr4E7AvYAHAXHUyElK4lMizMGZ4lxeM@mFcZCjHIbLKrqGX01PW/21PxbUlcUWfhf0WwEjNZmqyVRNp2rKBrvA@dnezh0s@iv1n9ST@NJAu@q02e1rZCPpfx/HRnZqZJkEzh13eeXBFg/prZ2@lWMZjFfxIbzswp1zPJBDVb4irMZIqLnCDlCqDmjN8d2SsXk3/hrCzndEgN7gQtYE1@pZb9lg0MyuUyB8ejFkhODFsSFH1RfU@96oJDDs0oUD0UfCf8Ylo5k17U9evGUH24afvw "C (gcc) – Try It Online") *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to an array of integers and its length (because pointers in C carry no length info). Outputs to `stdout` each array slice with the array elements separated by spaces and the slices separated by newlines. [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html), ~~24~~ ~~22~~ ~~15~~ ~~14~~ 12 bytes *Edit: -2 bytes thanks to Razetime, and -2 more bytes (and a BQN lesson) thanks to ovs* ``` 1↓⊢⊔˜≠⥊·/˜⊒˜ ``` [Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=UmVwU2xpY2Ug4oaQIDHihpPiiqLiipTLnOKJoOKlisK3L8uc4oqSy5wKCmFycmF5IOKGkCDin6gxLDIsMyw0LDUsNiw3LDgsOSwxMOKfqQpSZXBTbGljZSBhcnJheQ==) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` GatherBy[#,i=1;Round@√(2i++)&]& ``` [Try it online!](https://tio.run/##LcjNCoJAFIbh/VxFIIgyRzwzaj/EhLRpG7WUFoMlzcITmS1CdN01dHndyOSQq@973lq310utW1NqWym7c2y2r8IDo8T6cHvSOf@@P4E0nIf@ybf7xlBbeNGmyr2TPxxLTUPHOgESEkghgzksYAkrENjD2BEkQoKQTnR2wRWEDLFnvaWAuAhjqQyjGXFScjpcxOkIN4zU494Ef4SRiCX7AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Uiua](https://uiua.org), 11 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==) ``` ⊜□⬚2↙⧻,⊚⇡⧻. ``` [Try it!](https://uiua.org/pad?src=ZiDihpAg4oqc4pah4qyaMuKGmeKnuyziiprih6Hip7suCgpmIFszIDMgMyAzIDMgMyAzIDMgMyAzXQpmIFs1IDYgNyA4IDkgMTAgMTEgMTIgMTMgMTRdCmYgWzFdCmYgWzEgMl0KZiBbMSAyIDNdCmYgWzEgMiAzIDRd) ``` ⊜□⬚2↙⧻,⊚⇡⧻. . # duplicate ⧻ # length ⇡ # range ⊚ # where , # over ⧻ # length ⬚2↙ # take with fill element of 2 ⊜□ # partition with boxing ``` [Answer] # Python 2, 47 bytes: ``` def f(l,c=1): while l:yield l[:c];l=l[c:];c+=1 ``` [Try it Online!](https://tio.run/##BcFBDoMgFAXAfU/xlpC@RVHbKoaTEFYIkeRHjZI0np7OHHdd961rbUkZWQmjM9o@8FuLJIi9S5IF4m0Mszjx0YY5Pp1px1m2qqRcVWXlDdERPTEQb@JDfImRmAjzClrr9gc) [Answer] # JavaScript (ES6), 42 bytes *-2 thanks to @emanresuA because I'm a potato* ``` x=>(f=n=>x+x&&[x.splice(0,++n),...f(n)])`` ``` [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` g=lambda x,s=1:[[c for c,_ in zip(x,range(s))]]+g(x[s:],s+1)if x else[] ``` [Try it online!](https://tio.run/##JcrBDsIgDADQX@mxdb003pbwJbUxOAFJJiOwA/rzePCdX/2cr6NcZ3S3mdzu34@nh8Hdyaq6QTwabHyHXOCbKw5uvqSAnchsSTi0r8Z9EcoRBoS9B7VZWy4nRtTLfwuLkBHNHw "Python 3 – Try It Online") *-3* Thanks to @U12-Forward [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xp`, 12 bytes ``` a^@$+*\,\,#a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWaxLjHFS0tWJ0YnSUEyFCUJmt0UrRhtZG1sbWJtam1mbW5tYWsXBtAA) ### Explanation ``` a^@$+*\,\,#a #a Length(argument) \, Inclusive range from 1 to ^ \, Inclusive range from 1 to each number in ^ $+* Sum each a^@ Split argument at those indices ``` [Answer] ## [Scala](http://www.scala-lang.org/), 74 bytes ``` a=>(0 to a.size).map(i=>a.slice(i*(i+1)/2,(i+1)*(i+2)/2)).filter(_.size>0) ``` [Try it online!](https://tio.run/##fY9PC4JAEMXvfoo57tRg66r9A4WOQbcuQUhstsLGpqZLRNFnN9dbUB3mDT/mvRmmzaWRXXU8q9zCDtTdqvLUwqqu4ekB3KSBYsm26rp3tS5tliXpByIk0MkkZRxsBdJv9UOhf5E100nao9G5YnrE9DjAiaChOxI9IfqFNlY17DDkUo4dQN3o0pqSQeEODxWQoJAiimlKM5rTggKOiIDedzsnwSnkFP13cQLhJHQSOYn538SPGQvc7/0@9G210a0dbK/uDQ) The obvious way to avoid the filter at the end is to make the range from 0 to the biggest triangle number whose value is less than `a.size`, but the shortest way I could find to express that in Scala 2.13 was longer than the thing it was supposed to replace: ``` BigDecimal(0).until(pow(2*a.size+.25,.5)-.5,1) ``` [Answer] # [Raku](https://raku.org/), 22 bytes ``` *.rotor(1..*,:partial) ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS68ovyS/SMNQT09Lx6ogsagkMzFH87@1QnFipYKSSrxeAVC5hqaCrZ1CdZqGSrymXnpmcUmtkkJafpGCA0iboYGmjoKGoYGOghEQGwOxCVQELAQWAwsCCVMDA83/AA "Perl 6 – Try It Online") The `rotor` method splits an array into chunks of a given size or sizes, eg: * `rotor(5)` splits an array into 5-element chunks. * `rotor(2, 3)` splits an array into chunks of alternating sizes 2 and 3. Here, I pass the infinite range `1 .. *` as the argument, so `rotor` will emit chunks of sizes 1, 2, 3, .... The `:partial` keyword argument causes all remaining elements to be grouped into the final chunk, even if there aren't enough of them. [Answer] # APL (Dyalog Unicode), 17 bytes This is a dfn that takes a vector as a right argument. It groups segments per specification into a nested array of vectors. ``` {⍵⊆⍨1+q⍸⍨+\q←⍳⍴⍵} ``` The index origin is set to 0 (⎕IO←0). [Try it on TryAPL.org!](https://tryapl.org/?clear&q=%E2%8E%95IO%E2%86%900%E2%8B%84%7B%E2%8D%B5%E2%8A%86%E2%8D%A81%2Bq%E2%8D%B8%E2%8D%A8%2B%5Cq%E2%86%90%E2%8D%B3%E2%8D%B4%E2%8D%B5%7D1%202%203%204%205%206%207%208%209%2010%2011%2012%2013%2014%2015%2016&run) This was an interesting challenge and demonstrates that there are many ways to get to a solution in the APL language. None I found had a lesser byte count, but the approaches may be of interest: by recursion: {⍺←1 ⋄ ⍺≥⍴⍵:⊂⍵ ⋄ (⊂⍺↑⍵),(⍺+1)∇ ⍺↓⍵} by formula: {⍵⊆⍨⌊0.5+0.5\*⍨2×⍳⍴⍵} by iteration: {p⊆⍨q↑∊{⍵⍴⍵}¨⍳q←⍴⍵} ]
[Question] [ ## Challenge: Given the input number `n`. It should give me nested sublists of `n` layers with the [power of two](https://en.wikipedia.org/wiki/Power_of_two) numbers for each level. Each power of two value will be in separate sublists. ## Notes: * `n` will always be greater than 0 * I am using the example output with Python Lists. You can use any type of sequence in your own language. * Your output must be one-indexed, add one to `n` if your output is zero-indexed. * Your output sequence must be nested. ## Test cases: ``` n = 1: [1] n = 2: [1, [2]] n = 3: [1, [2, [4]]] n = 4: [1, [2, [4, [8]]]] n = 5: [1, [2, [4, [8, [16]]]]] n = 6: [1, [2, [4, [8, [16, [32]]]]]] n = 7: [1, [2, [4, [8, [16, [32, [64]]]]]]] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! The [power of twos](https://en.wikipedia.org/wiki/Power_of_two) are these values `1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048...`, each values is double of the previous value. [Answer] # [Factor](https://factorcode.org/) + `math.polynomials`, 47 bytes ``` [ 2 powers reverse 1 cut [ swap 2array ] each ] ``` [Try it online!](https://tio.run/##HcsxDsIwDAXQnVP8E1SiYoIDIBYWxFR1sCKjVriJsd1WOX1ATG96L0pRrD0ft/v1jIVi6rRIzWWZSRzOn5VzYsebLbOAzKg61Diiqs05cDmc2oAeWnY2h/H2g3FEWgMDfCdF/38YwZQmjC2RCLr2BQ "Factor – Try It Online") ``` ! 4 2 ! 4 2 powers ! { 1 2 4 8 } reverse ! { 8 4 2 1 } 1 ! { 8 4 2 1 } 1 cut ! { 8 } { 4 2 1 } ! { 8 } 4 <<first iteration of each>> swap ! 4 { 8 } 2array ! { 4 { 8 } } ! { 4 { 8 } } 2 <<second iteration>> swap ! 2 { 4 { 8 } } 2array ! { 2 { 4 { 8 } } } ! { 2 { 4 { 8 } } } 1 <<third>> swap ! 1 { 2 { 4 { 8 } } } 2array ! { 1 { 2 { 4 { 8 } } } } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 47 bytes ``` 1i:?v~~l?^; /$-1/ /on$o"[,": \2*$:}10./"]"o~60. ``` [Try it!](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMWk6P3Z+fmw/Xjtcbi8kLTEvXG4vb24kb1wiWyxcIjpcblxcMiokOn0xMC4vXCJdXCJvfjYwLiIsImlucHV0IjoiXHUwMDAzIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9) [![enter image description here](https://i.stack.imgur.com/jmOc3.png)](https://i.stack.imgur.com/jmOc3.png) Generates trailing commas at the end of lists, some languages allow that so that should be OK. Takes input as a char code. Uses the length of the stack to keep track of how many `]` to generate at the end. [Answer] # [Python 3](https://docs.python.org/3/), 44 bytes ``` e=lambda n,i=1:[i,e(n-1, i*2)]if n>0 else[i] ``` [Try it online!](https://tio.run/##DcrBCsIwEEXRvV/xdp1IFKsbCcQfKV1EnOqDdlpiNiJ@e8yFuzvbp7xWu9SqcU7L/ZFgnrEPA72KHXoP7s9u5AS7naDzWweOdVozCBpysqdKU1cXdmhtmVakM0R8f6HdHRteUhF6qNA5V/8 "Python 3 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 6 bytes ``` (d1$"ꜝ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCI2IiwiKGQxJFwi6pydIiwiIiwiIl0=) Uses the fact that [stack languages can have their input placed on the stack before execution](https://codegolf.meta.stackexchange.com/a/22106/78850) [Proof the meta proposal was +6 at the time of posting](https://web.archive.org/web/20221221235837/https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/22106) ## Explained A port of Jelly ``` (d1$"ꜝ ( # repeat input times d # double 1$" # [1, that] ꜝ # keep only truthy items ``` [Answer] # [R](https://www.r-project.org), 44 bytes ``` f=\(n,k=1,`+`=list)`if`(n-1,k+f(n-1,k*2),+k) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN3XSbGM08nSybQ11ErQTbHMyi0s0EzLTEjTydA11srXTILSWkaaOdrYmRM_mNA1DTa40DSMQYQwiTKAyMFMB) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ḥ1,¹ƇƲ¡ ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//4bikMSzCucaHxrLCof/Dh8WS4bmY/zc "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing (use STDIN to avoid needing the leading `0`, and a shorter way of filtering the `0`) ``` Ḥ1,¹ƇƲ¡ Main Link (input in STDIN, so argument starts at 0) ¡ repeat N times Ḥ double the current list 1, pair with 1 ¹Ƈ filter by identity; remove falsy elements (filter out the 0 in the first step) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~36~~ 34 bytes ``` ->n{*r=k=2**n;n.times{r=k/=2,r};r} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWqvINtvWSEsrzzpPryQzN7W4Giigb2ukU1RrXVT7v0AhLdo09j8A "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F·Xs‚ZK ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f7dD2iOJHDbOivP//NwUA "05AB1E – Try It Online") Port of lyxal's Vyxal answer. * -1 thanks to Kevin Cruijssen ### Explanations: ``` F·Xs‚ZK # Implicit input (n) F # for i in range(a): · # Double Xs‚ # Get [1, that] (X defaults to 1) ZK # Push the list without the maximum ``` Previous 8 byte answer: ``` L<o`¸¹G‚ # Implicit input (n) L< # range(0, n) o # 2 to the power of each `¸ # Dump onto stack, putting the last one in a list ¹G # n-1 times: ‚ # Pair ``` Previous 13 byte answer: ``` <Do¸sE¹<N-o‚R # Implicit input (n) < # Reduce n by 1 Do¸ # Duplicate and push [2**(n-1)] to the stack sE # Swap and loop through range(0, n-1): ¹<N- # Subtract from n-1 o # Raise 2 to the power of this number ‚R # Pair and reverse ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 31 bytes ``` f=(x,i=1)=>--x?[i,f(x,i*2)]:[i] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajQifT1lDT1k5Xt8I@OlMnDSSgZaQZaxWdGfu/oCgzr8Q2OT@vOD8nVS8nP50LLKKRpmGoqQlnGyGxjZHYJkhsUyS2GRLbXFPzPwA "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` :qWP"@XhP]&D ``` Try it at [**MATL online**](https://matl.io/?code=%3AqWP%22%40XhP%5D%26D&inputs=7&version=22.7.4)! ``` : % Implicit input, n. Range [1 2 ... n] q % Subtract 1, element-wise W % Powers of 2, element-wise P % Flip. Gives [2^(n-1) 2^(n-2) ··· 1] " % For each number in that vector @ % Push current number Xh % Concatenate all stack contents into a cell array P % Flip ] % End &D % String representation. Implicit display ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` L+[^2b)?qtQbY[yhb)y0 ``` [Try it online!](https://tio.run/##K6gsyfj/30c7Os4oSdO@sCQwKTK6MiNJs9Lg/39zAA "Pyth – Try It Online") ``` L # Function y with input as b + # Append [^2b) # List with 2^b as only element ? # Ternary operator qtQb # If b is equal to input - 1 Y # empty list (when condition is true) [yhb) # Call function y with input b+1 and put inside a list (when condition is false) y0 # Call function y with input 0 ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 28 bytes ``` FiR,a{YlAEyPE EiUi=a?Y Hy0}y ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaVIsYXtZbEFFeVBFIEVpVWk9YT9ZIEh5MH15IiwiIiwiNyIsIi1wIl0=) ``` FiR,a{YlAEyPE EiUi=a?Y Hy0}y FiR,a{ } Loop through [a, 0] YlAEyPE Ei Set y (initially "") to y + 2**i wrapped in a list Ui=a?Y Hy0 Remove the empty string if it is the first iteration ``` ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang) (v2), 35 bytes ``` ;=l,=c/^2=pP2;W=p-EpT=l+,=c/c 2,lDl ``` [Try it online!](https://knight-lang.netlify.app/#WyI7PWwsPWMvXjI9cFAyO1c9cC1FcFQ9bCssPWMvYyAyLGxEbCIsIjciLCIyLjAiXQ==) Looks golfable. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes ``` {(x-1)(1,,2*)/,1} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqNA11NQw1NEx0tLU1zGs5eJKUzDlAgBOBQVb) ##### Explanation: ``` {(x-1)(1,,2*)/,1} ,1 start with list one (x-1) / do n-1 times (1,,2*) 1 joined with double the current value enlisted ``` [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` def f(n): for i in range(n):l=i and[l[0]//2,l]or[2**n//2] return l ``` [Try it online!](https://tio.run/##Tci9CoAgFEDhOZ/ijhqBZT9D0JOIQ5CWINe42NDTWw2B23fOeacjYp@nvFkHjqOYWeUigQePQCvu9nth8bDipoNujZSqCSaSVnWNbxhWkU0XIYR8ksfEHe@EYL9V4b7wUHgsPL3ODw "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` FN≔Φ⟦¹⊗υ⟧κυ⭆¹υ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTwbG4ODM9T8MtM6cEKBBtqKPgkl@alJOaolGqGaujkK2po1Cqac0VUJSZV6IRXAKk0n0TCzQMQcKa1v//m/7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FN ``` Repeat `n` times... ``` ≔Φ⟦¹⊗υ⟧κυ ``` ... double the predefined empty list and prepend a `1` (but on the first pass filter out the list as it is empty). ``` ⭆¹υ ``` Pretty-print the final list. [Answer] # [Python 3](https://docs.python.org/3/), ~~48~~ ~~42~~ 40 bytes ``` f=lambda n,c=1:n>1and[c,f(n-1,c+c)]or[c] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU8n2dbQKs/OMDEvJTpZJ00jT9dQJ1k7WTM2vyg6OfZ/QVFmXolGmoahpiYXjG2ExDZGYpsgsU2R2GZIbHNNzf8A "Python 3 – Try It Online") *-6 bytes thanks to l4m2* *-2 bytes thanks to The Thonnu* [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes ``` "$&"{`\d+ $.(*2* .+ [1, $&] , \d+] ] ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9JRU2pOiEmRZtLRU9Dy0iLS0@bK9pQR0FFLZZLRwEoHssV@/@/IZcRlzGXCZcplxmXOQA "Retina – Try It Online") Link includes test cases (because fortunately I was able to use `$&` instead of `$+`). Explanation: ``` "$&"{` ``` Repeat the program `n` times (because `n` is the input). ``` \d+ $.(*2* ``` Double all of the integers. ``` .+ [1, $&] ``` Wrap the list with `1` in a sublist. ``` , \d+] ] ``` Remove the original input. [Answer] # [sclin](https://github.com/molarmanful/sclin), 19 bytes ``` [1]"2*1rev ,";1- *# ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Takes the argument from the next line. If outputting as an infinite sequence were allowed, then something like `1,,"2*1rev ,"itr` would be 16 bytes. For testing purposes: ``` ; n>o 1,,"2*1rev ,";1- *# 7 ``` ## Explanation Prettified code: ``` [1] ( 2* 1rev , ) ;1- *# ``` * `[1]` starting with 1-length array of 1 * `(...) ;1- *#` repeat (next line) - 1 times... + `2* 1rev ,` vectorized-multiply by 2 and prepend 1 [Answer] # [Raku](https://raku.org/), 23 bytes ``` [1],{[1,2 «*«$_]}...* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPs/2jBWpzraUMdI4dBqrUOrVeJja/X09LT@WyvoFSdWKqTlFwHVRccZGsT@BwA "Perl 6 – Try It Online") This is an expression for the infinite sequence of arrays. The magic is in the `«*«` operator, which multiplies each element of an arbitrarily-deeply nested structure by a number. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 12 bytes ``` LaYFI[1y*2]y ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMYVlGSVsxeSoyXXkiLCIiLCI3IiwiLXAiXQ==) ### Explanation Same idea as [hyper-neutrino's Jelly answer](https://codegolf.stackexchange.com/a/255809/16766): ``` LaYFI[1y*2]y a is command-line argument; y is "" (implicit) La Loop a times: y*2 Multiply y by 2 (-> 0 if it's "", element-wise if it's a list) [1 ] Put 1 and that value in a list FI Filter, removing falsey values (in this case, 0) Y Yank, assigning the result back to y y After the loop, autoprint the final value of y ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, ~~18~~ 14 bytes ``` FI[EiUi<a&REa] ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGSVtFaVVpPGEmUkVhXSIsIiIsIjciLCItcCJd) -4 bytes thanks to @DLosc Recursively builds the nested lists. `FI` is used to filter out the `0` in the last list, otherwise `[1;[2;[4;0]]]` would be output. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` Æ∞1\αç ``` Port of [*@lyxal*'s Vyxal answer](https://codegolf.stackexchange.com/a/255805/52210). [Try it online.](https://tio.run/##y00syUjPz0n7//9w26OOeYYx5zYeXv7/vyGXEZcxlwmXKZcZlzmXoQEA) **Explanation:** ``` Æ # Loop the (implicit) input amount of times, # using the following five characters as inner code-block: ∞ # Double all current values (the stack contains a 0 by default) 1\α # Pair it with a leading 1 ç # Falsey filter to remove the 0 # (after the loop, the entire stack is output implicitly as result) ``` [Answer] # [Julia 1.0](http://julialang.org/), 21 bytes ``` !n=[n<2||[1,2*!~-n];] ``` [Try it online!](https://tio.run/##LcxBCsIwEAXQfU7xM7hIpILpUpuC5yhdFI0wEsYQIqRQvHq66TvA@/wiL662psVPMvTbNrmuP@v/Reb73FTKoZTVVAuPHFJcnsHQybhqqQM9ZCU/Elml3t8MBgvczV0VgJRZShTD8COORrO1Ksir7Q "Julia 1.0 – Try It Online") using `√` instead of `!` would save a character, since `a√b` is parsed as `a*√b` (which doesn't work for `!`). But of course the byte count would be higher. [Answer] # [FunStack](https://github.com/dloscutoff/funstack) alpha, 40 bytes ``` Pair 1 Double over iterate Wrap 1 At Dec ``` Try it at [Replit](https://replit.com/@dloscutoff/funstack): pass the input number as a command-line argument and enter the program on stdin. ### Explanation First, we generate the infinite sequence of such nested lists: ``` Pair 1 ``` Given `x`, turn it into `[1, x]`. ``` Double ``` Multiply by 2 (applies itemwise over lists). ``` over ``` Given two arity-1 functions, this modifier works the same as `compose` but is 3 bytes shorter. The composed function is "Multiply the argument by 2 and pair 1 with the result." ``` iterate ``` Repeatedly apply this function and return the infinite list of results... ``` Wrap 1 ``` ... starting at `[1]`. The resulting infinite list is a value at the left side of the program, so it gets pushed onto the argument list. Then: ``` At ``` Get the nth element, where n is... ``` Dec ``` ... the first program argument, decremented (since indexing is 0-based). [Answer] # [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` {,W%{2\#]W%}%} ``` Anonymous code block that pops a number from the stack and pushes the nested array. The header reads the input. The footer executes the block and prints the string representation of the array. Port of my [MATL answer](https://codegolf.stackexchange.com/a/255820/36398). [**Try it online!**](https://tio.run/##S85KzP1flPm/WidctdooRjk2XLVWtfZ/XcF/UwA "CJam – Try It Online") ### Code explanation ``` {,W%{2\#]W%}%} { } e# define code block , e# range (0-based) W% e# reverse array { }% e# map this code block over the array 2\# e# exponential with case 2 ] e# pack all stack contents into an array W% e# reverse array ``` [Answer] # [Mathematica](https://www.wolfram.com/mathematica/) 39 bytes With `n=5` ``` s=Nothing;Do[s={2^--i,s},{i,n,1,-1}];s ``` > > {1, {2, {4, {8, {16}}}}} > > > [Answer] `awk` solution - different solutions for `mawk-1/2` and `gawk/nawk` : ``` jot 16 | ``` > > > ``` > mawk 'function __(_){return $_=--_?_+=_=__(_):!_}__(NF=$_)' OFS=, > > ``` > > > > > ``` > nawk > gawk 'func __(_){return $++_=--_?__(_)/_*(_+_):!_}__(NF=$-_)' OFS=, > > * "function" is normally preferred, but this is Pebble Beach… > > ``` > > ``` 1 1,2 1,2,4 1,2,4,8 1,2,4,8,16 1,2,4,8,16,32 1,2,4,8,16,32,64 1,2,4,8,16,32,64,128 1,2,4,8,16,32,64,128,256 1,2,4,8,16,32,64,128,256,512 1,2,4,8,16,32,64,128,256,512,1024 1,2,4,8,16,32,64,128,256,512,1024,2048 1,2,4,8,16,32,64,128,256,512,1024,2048,4096 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536 ``` Different solutions needed stemming from their different order of precedence of something not clearly specified in `POSIX` - * `mawk`s go ***strictly*** left-to-right, even for assignments, — so `$_ = ...` is equivalent to `$(func-input-val) = ...`, * while `gawk/nawk` handles all of RHS first, with LHS taking on final value of `_` To make nesting sublists out of that : ``` for __ in $(jot 7); do echo " $__ :: $( echo "$__" | mawk 'function __(_){ORS="]"ORS;return $_=\ --_?_+=_=__(_):!_}$!__(NF=$(OFS=",["))="["$_' )" done 1 :: [1] 2 :: [1,[2]] 3 :: [1,[2,[4]]] 4 :: [1,[2,[4,[8]]]] 5 :: [1,[2,[4,[8,[16]]]]] 6 :: [1,[2,[4,[8,[16,[32]]]]]] 7 :: [1,[2,[4,[8,[16,[32,[64]]]]]]] ``` [Answer] # [Scala](http://www.scala-lang.org/), 70 bytes [Try it online!](https://tio.run/##JY4xC4MwEIV3f8UhDrmiULsUQi04FtqpdBKH1Ea5Ys@SZJHgb0@NPbgH9/ge72ynRhWm51t3Dm6KGHwC8NI9fNZDKDNYCbUxam7uzhAPLUp4MDmowIfIacHywi6nqFWJ8krWNTXPbeWpF3zeY3QE5StZlDntDoh6tBr@Ni6hnwwIglMBJbgJjrg9Eee7VrqRhU15LcxIQuZ1zKS4EUsSd0nCDw) ``` def e(n:Int,i:Int=1):List[Any]={if(n>0)List(i,e(n-1,i*2))else List(i)} ``` [Answer] # [Lua](https://www.lua.org/), 59 bytes ``` load"a={1}b=a for i=2,...do b[2]={2^i/2}b=b[2]end return a" ``` [Try it online!](https://tio.run/##ZY/disMgEIXv@xSH3BihWOr@XfkkSxdMY7ISq8FoYQndV89qI3RLBJH5jufMjIly6cVinGwrKebjrRESnfPQgu8ZY61D88lPYuZf@sCTmitlW3gVoreQ1dJFew7aWbTxMtaO7gDoDuFnVKmCECBBNkYRhG9ls5qOcWdpMCGJmEEKzY2H/RXaYpTaT9nfuiL@ix0ofpPTxkuj/JqLIWdVhLGBsfQiDfkw5kYTGFtnvNKiPP6Ude5/CG7rRMpM6lkPbgpe276smf357sYEQ30P7@sjpfSZ8A152ZDXDXnbkPcN@Uhk@QM "Lua – Try It Online") Ungolfed version: ``` function f(n) a={1}b=a for i=2,n do b[2]={2^i/2} b=b[2] end return a end ``` ]
[Question] [ **Make me an icecream cone please** We have a ton of great ice cream places here in New England. Most of them are closed for the winter now, so... ``` .-@@-. (======) (--------) (==========) (__________) \/\/\/\/\/ \/\/\/\/ \/\/\/ \/\/ \/ ``` **GOAL** Output the above icecream cone exactly. (or return it from a function) This is code golf so shortest answer wins [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 24 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` u%⅝⁾⁷‰┘Η:⅛6s⁹№K⌠RΝīL°‘§╬ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=dSUyNSV1MjE1RCV1MjA3RSV1MjA3NyV1MjAzMCV1MjUxOCV1MDM5NyUzQSV1MjE1QjZzJXUyMDc5JXUyMTE2SyV1MjMyMFIldTAzOUQldTAxMkJMJUIwJXUyMDE4JUE3JXUyNTZD) A simple compression solution: ``` ....‘ push "@-.¶===(¶----(¶=====(¶_____(¶\/\/\¶/\/\¶\/\¶/\¶\" § pad with spaces and reverse horizontally ╬ palindromize with 0 overlap and mirroring the characters ``` [No compression version](https://dzaima.github.io/SOGLOnline/?code=QC0uJXUyMDFEJTNELSUzRF8ldTIwMUQlN0IldTAxMTMzKyolMjAlMjgrJTdEazUldTIyMkI2JXUwM0JBJXUwMUE3JTVDL20lQjElN0QlQjklQTcldTI1NkM_) - way longer as SOGLs compression works nice for this [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` i=9;print' .-@@-.' while i:print['('+~i*3/4*2%22*'-=_='[i%4]+')','\/'*i][i<6].center(12);i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0rqgKDOvRF1BQUFP18FBV0@dqzwjMydVIdMKLBGtrqGuXZepZaxvomWkamSkpa5rG2@rHp2pahKrra6prqMeo6@ulRkbnWljFquXnJpXklqkYWikaZ2pa2v4/z8A "Python 2 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 85 bytes ``` " .-@@-. (======) (--------) ($('='*10)) ($('_'*10))" 1..5|%{" "*$_+'\/'*(6-$_)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lBQUFP18FBV49LQUHDFgw0uRQ0dKFAk0tDRUPdVl3L0EATwo6HsJW4DPX0TGtUq5UUlLRU4rXVY/TVtTTMdFXiNWv//wcA "PowerShell – Try It Online") OR # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 85 bytes ``` " .-@@-. (======) (--------)" '=','_'|%{"($($_*10))"} 1..5|%{" "*$_+'\/'*(6-$_)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lBQUFP18FBV49LQUHDFgw0uRQ0dKFAU4lL3VZdRz1evUa1WklDRUMlXsvQQFNTqZbLUE/PFCSooKSlEq@tHqOvrqVhpqsSr1n7/z8A "PowerShell – Try It Online") Take your pick. In both cases, the first three lines don't have enough bytes to do any sort of compression in PowerShell. The first case uses string multiplication to produce each of the 10-length `=` and `_` lines, while the second uses a loop and string multiplication. In either case, the last line forms the cone, looping from `1` to `5` and each iteration outputting the appropriate number of spaces followed by the appropriate number of cone pieces. All of those strings are left on the pipeline, and the implicit `Write-Output` at program completion gives us a newline between elements for free. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~48~~ 46 bytes ``` i\/5ñ>GÄXa/\ñS³ .-@@-. (¶=) (¸-) (±=) (±_) ``` [Try it online!](https://tio.run/##K/v/PzNGX9r08EY798MtEYn6MYc3Bh/arKCn6@Cgq8eloKBxaJutJheQ2qGryaVxaKMtmIzX/P8fAA "V – Try It Online") Hexdump: ``` 00000000: 695c 2f1b 35f1 3e47 c458 612f 5cf1 53b3 i\/.5.>G.Xa/\.S. 00000010: 202e 2d40 402d 2e0a 2020 28b6 3d29 0a20 .-@@-.. (.=). 00000020: 28b8 2d29 0a28 b13d 290a 28b1 5f29 (.-).(.=).(._) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` @-.⸿E=-=⁺×ι⁺³κ)×_⁵P↙⁶)⸿‖M←¤/\ ``` [Try it online!](https://tio.run/##PY3BCsIwEETvfkXY0wYSPYgeKgUF8WShiMeAhDTF4NqUNNXPj62BHufNG8Y8dTBeU0p1cF1EOMq1CsAPq5wr3SOUsgTBTk2Dd/e2AzrBahoH3Ar24lww4MCXRVbgMS12M61Giq7/V8XZf7urbaNg@8UHnv9utiVrYuVC8AGLWZvoxREhbJSalJSS/NAP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` @-.⸿ ``` Print the right half of the first line. ``` E=-=⁺×ι⁺³κ) ``` For each of the characters `=-=`, repeat 3 times for the first and an additional time for each subsequent character, then append a `)`, printing each result on its own line. ``` ×_⁵ ``` Print 5 `_`s. ``` P↙⁶ ``` Print the edge of the cone. ``` )⸿ ``` Print the final `)` and position the cursor inside the cone. ``` ‖M← ``` Mirror the half cone. ``` ¤/\ ``` Fill the body of the cone. [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` n=10 while n:print['\/'*n,'('+35/n*2*'-=_='[n%4]+')','.-@@-.'][-2%n/4].center(12);n-=1 ``` [Try it online!](https://tio.run/##BcFBCoMwFAXAfU/hRp5Gf9JE3VQC3iMNXZSAQnmKBKSnjzPHP687XSn09vm41u2XKr6Oc2MOeBso9mjQDZOhcgriPx6B9Rg7tOihZVlEIwZxNc0Y9Tcxp7Oxrp0p3pZyAw "Python 2 – Try It Online") Working off [Lynn's solution](https://codegolf.stackexchange.com/a/148424/20260). [Answer] # [Perl 6](https://perl6.org), ~~115 95 94 92~~ 90 bytes *3 bytes saved by AlexDaniel in #perl6 on irc.freenode.net* ``` say " .-@@-. (======) (--------) ({"="x 10}) ({"_"x 10})";say(' 'x++$,'\/'x$--+5)xx 5 ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVJBSUFBQU/XwUFXj0tBQcMWDDS5FDR0oUCTS6NayVapQsHQoBbMjoeylayB2jXUFdQrtLVVdNRj9NUrVHR1tU01KyoUTP//BwA "Perl 6 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes ``` •3[ÜAʒg‰ŽÎ<\¦•6¡εS"-.@(=_"sèJ∞}'\∞5LRׂ˜.C ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMi4@jDcxxPTUp/1LDh6N7DfTYxh5YBRc0OLTy3NVhJV89BwzZeqfjwCq9HHfNq1WOApKlP0OHpjxpmnZ6j5/z/PwA "05AB1E – Try It Online") --- [1026344463000063444446355555](https://www.google.com/search?q=1026344463000063444446355555) is now the Icecream Number b/c nobody else has used it. --- ``` Full program: •3[ÜAʒg‰ŽÎ<\¦•6¡εS"-.@(=_"sèJ∞}'\∞5LRׂ˜.C current >> • || stack: [] current >> 6 || stack: [1026344463000063444446355555] current >> ¡ || stack: [1026344463000063444446355555, '6'] current >> ε || stack: [['102', '3444', '30000', '344444', '355555']] For each: S"-.@(=_"sèJ∞ Full program: S"-.@(=_"sèJ∞ current >> S || stack: ['102'] current >> " || stack: [['1', '0', '2']] current >> s || stack: [['1', '0', '2'], '-.@(=_'] current >> è || stack: ['-.@(=_', ['1', '0', '2']] current >> J || stack: [['.', '-', '@']] current >> ∞ || stack: ['.-@'] stack > ['.-@@-.'] Full program: S"-.@(=_"sèJ∞ current >> S || stack: ['3444'] current >> " || stack: [['3', '4', '4', '4']] current >> s || stack: [['3', '4', '4', '4'], '-.@(=_'] current >> è || stack: ['-.@(=_', ['3', '4', '4', '4']] current >> J || stack: [['(', '=', '=', '=']] current >> ∞ || stack: ['(==='] stack > ['(======)'] Full program: S"-.@(=_"sèJ∞ current >> S || stack: ['30000'] current >> " || stack: [['3', '0', '0', '0', '0']] current >> s || stack: [['3', '0', '0', '0', '0'], '-.@(=_'] current >> è || stack: ['-.@(=_', ['3', '0', '0', '0', '0']] current >> J || stack: [['(', '-', '-', '-', '-']] current >> ∞ || stack: ['(----'] stack > ['(--------)'] Full program: S"-.@(=_"sèJ∞ current >> S || stack: ['344444'] current >> " || stack: [['3', '4', '4', '4', '4', '4']] current >> s || stack: [['3', '4', '4', '4', '4', '4'], '-.@(=_'] current >> è || stack: ['-.@(=_', ['3', '4', '4', '4', '4', '4']] current >> J || stack: [['(', '=', '=', '=', '=', '=']] current >> ∞ || stack: ['(====='] stack > ['(==========)'] Full program: S"-.@(=_"sèJ∞ current >> S || stack: ['355555'] current >> " || stack: [['3', '5', '5', '5', '5', '5']] current >> s || stack: [['3', '5', '5', '5', '5', '5'], '-.@(=_'] current >> è || stack: ['-.@(=_', ['3', '5', '5', '5', '5', '5']] current >> J || stack: [['(', '_', '_', '_', '_', '_']] current >> ∞ || stack: ['(_____'] stack > ['(__________)'] current >> ' || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)']] current >> ∞ || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], '\\'] current >> 5 || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], '\\/'] current >> L || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], '\\/', '5'] current >> R || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], '\\/', [1, 2, 3, 4, 5]] current >> × || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], '\\/', [5, 4, 3, 2, 1]] current >> ‚ || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], ['\\/\\/\\/\\/\\/', '\\/\\/\\/\\/', '\\/\\/\\/', '\\/\\/', '\\/']] current >> ˜ || stack: [[['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)'], ['\\/\\/\\/\\/\\/', '\\/\\/\\/\\/', '\\/\\/\\/', '\\/\\/', '\\/']]] current >> . || stack: [['.-@@-.', '(======)', '(--------)', '(==========)', '(__________)', '\\/\\/\\/\\/\\/', '\\/\\/\\/\\/', '\\/\\/\\/', '\\/\\/', '\\/']] .-@@-. (======) (--------) (==========) (__________) \/\/\/\/\/ \/\/\/\/ \/\/\/ \/\/ \/ stack > [' .-@@-.\n (======)\n (--------)\n(==========)\n(__________)\n \\/\\/\\/\\/\\/\n \\/\\/\\/\\/\n \\/\\/\\/\n \\/\\/\n \\/'] ``` --- ``` •3[ÜAʒg‰ŽÎ<\¦• | Pushes 1026344463000063444446355555 to the stack. -----------------------------+------------------------------------------------- 6¡ | Split on 6's. -----------------------------+------------------------------------------------- ε } | Loop on each piece to create the top of the icecream... S | Split into single chars. "-.@(=_"sè | Substitute in the correct symbol for each number. J∞ | Join, then mirror. -----------------------------+------------------------------------------------- '\∞ | Push \/. 5LR | Push [5,4,3,2,1] × | Multiply '\/' by each 5,4,3,2 and 1. ‚˜ | Join top to bottom. .C | Center w/ newlines. ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 50 bytes ``` 00000000: 5350 50d0 d375 70d0 d5e3 5250 d0b0 0503 SPP..up...RP.... 00000010: 4d2e 050d 5d28 d0e4 020b c224 34e2 e100 M...](.....$4... 00000020: a82a 461f 0681 9a91 980a 0896 0284 0161 .*F............a 00000030: 0100 .. ``` [Try it online!](https://tio.run/##jc0xDsIwDAXQnVP8gQExWI4Tl5QDsCFVMDMkJLCAxNLzB7dUgpE/WJaS/5zHnB/1Pj5b4yV7qFeGcmEUv1Ps5k2rh4o9FM4MVvbAeRiIxhcRnWwhWn0EZ0YoUqdfBVokWqkGsHDGVSTAhyqojhk4Wu@ymdq0Dl9DzEhREkLnbuAuOvSptxE5gWPfmRaNdJ0DaHugn6TF8GbwfOSPELX2Bg "Bubblegum – Try It Online") [Answer] # C, 171 bytes ``` i;p(c,n,o){for(printf("%*c",o,i?32:40);n--;)printf(c);puts(i?"":")");}f(){p(".-@@-.",i=1,3);--i;p("=",6,3);p("-",8,2);p("=",10,1);p("_",10,1);for(i=6;--i;)p("\\/",i,6-i);} ``` [Try it online!](https://tio.run/##NY7BCoNADETvfoUECpuSWLVFiovohwilLFhy6LpYexK/fRvF5jTJkHnj@OVcjGKDceRpxGUYJxMm8fNg4HR2QCNJey3rW47WM1s8TIc2fOePkRagBgS062BwCQYy7jrOgKQp6IqWeUuHBqjaVpUMdKcSj2uRU7Hrx19vFaSp9k9Uo@8vmkYVi0Ki0tP3U7zBZElSHcXaZI0/) # C, 146 bytes ``` f(){puts(" .-@@-.\n (======)\n (--------)\n(==========)\n(__________)\n \\/\\/\\/\\/\\/\n \\/\\/\\/\\/\n \\/\\/\\/\n \\/\\/\n \\/");} ``` Just prints the hardcoded string. [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oLSkWENJQUFBT9fBQVcvJk9BQcMWDDSBbA1dKAByoMJQKY14OAApjInRR0FAY9D5Cqg8BWQ2iKOkaV37PzOvRCE3MTNPQ5OrmgskAXSjNVftfwA) [Answer] # [Python 2](https://docs.python.org/2/), 104 bytes Borrowed a trick from [Jonathan Frech's answer](https://codegolf.stackexchange.com/a/148416/59487), and thanks to him for saving me some bytes too. ``` print" .-@@-.\n (======)\n "+"(%s)\n"*3%("-"*8,"="*10,"_"*10), i=5 while i:print(6-i)*" "+"\/"*i;i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69ESUFBQU/XwUFXLyZPQUHDFgw0gWwlbSUN1WIgS0nLWFVDSVdJy0JHyVZJy9BARykeRGnqcGXamnKVZ2TmpCpkWoFN0zDTzdTUUgJpjtFX0sq0ztS1Nfz/HwA "Python 2 – Try It Online") --- ### [Python 2](https://docs.python.org/2/), 108 bytes ``` print""" .-@@-. (======) (--------) (==========) (__________)""" i=5 while i:print(6-i)*" "+"\/"*i;i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69ESUlJQUFBT9fBQVePS0FBwxYMNLkUNHShQJMLKgiR0IiHA02gZq5MW1Ou8ozMnFSFTCuwiRpmupmaWkoKStpKMfpKWpnWmbq2hv//AwA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~125~~ ~~120~~ ~~119~~ ~~116~~ 106 bytes * Saved three bytes thanks to [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork); golfed `in range(5,0,~0)` to `in[5,4,3,2,1]`. ``` print" .-@@-.\n (======)\n "+"(%s)\n"*3%("-"*8,"="*10,"_"*10), for _ in 5,4,3,2,1:print" "*(6-_)+_*"\/" ``` [Try it online!](https://tio.run/##LYw7CoAwEAV7T7E8EJJ14y8qIggeREgn2kRRG08fPzjNTDXbdc6rL0PY9sWfIKLUDINJR0@k@g/9NBKo@HgKbGMFA24FPbjIBe6Vlmhad3K0eKqlEiulFN0/BavGOJ04xpghhBs "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 50 bytes ``` 5õ_ç"\\/" c[AA8,6]£"({Xç"_=-="gY})"Ãp".-@"ê1¹w û · ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=NfVf5yJcXC8iCmNbQUE4LDZdoyIoe1jnIl89LT0iZ1l9KSLDcCIuLUAi6jG5dyD7ILc=&input=) [Answer] # [Perl 5](https://www.perl.org/), 92 bytes ``` say' .-@@-. (======) (--------) (==========) (__________)';$_='\/'x6;say while s%\\/% % ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJdQUFBT9fBQVePS0FBwxYMNLkUNHShQJMLKgiR0IiHA011a5V4W/UYffUKM2ugSQrlGZk5qQrFqjEx@qoKqv///8svKMnMzyv@r@trqmdgaAAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 97 bytes ``` i=-1 puts [' .-@@-.']+123455543.digits.map{|n|(i+=1;i<4?"(#{'=-=_'[i]*n*2})":'\/'*n).center 12} ``` [Try it online!](https://tio.run/##KypNqvz/P9NW15CroLSkWCFaXUFBQU/XwUFXTz1W29DI2MTU1NTEWC8lMz2zpFgvN7GguiavRiNT29bQOtPGxF5JQ7la3VbXNl49OjNWK0/LqFZTyUo9Rl9dK09TLzk1ryS1SMHQqPb/fwA) First time ever using Ruby, so tips are very welcome. [Answer] # Python 3, 202 bytes This is pretty terrible, its more bytes than just defining the string and printing that even. ``` print(" .-@@-.") print(" ("+"="*6+")") print(" ("+"-"*8+")") print("("+"="*10+")") print("("+"_"*10+")") print(" "+"\/"*5) print(" "+"\/"*4) print(" "+"\/"*3) print(" "+"\/"*2) print(" \/") ``` [Try It Online](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lBQUFP18FBV09JkwsupKGkrWSrpGWmraSJJAwS1VXSskARhSo1NMAQjccQVQCKxugraZkiWQUVMkESgokZI4vBBI1QBBWAQpr//wMA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~74~~ 72 bytes ``` 5RU⁾\/ẋ 5R×⁶ż¢Y 3,6,8,10,10j1ż“ “.-@@-.¶ (“=“)¶ (“-“)¶(“=“)¶(“_“)¶”P€;¢ ``` [Try it online!](https://tio.run/##y0rNyan8/9806PD0R43bju4xDQp91LgvRv/hrm6VQ0siuYx1zHQsdAwNgCjL8OieRw1zFIBYT9fBQVfv0DYFBQ0gzxaINYEcEFsXwkYSBjHjIcxHDXMDHjWtsT606P9/AA "Jelly – Try It Online") **Explanation:** ``` 5RU⁾\/ẋ Link 1. Generate list of "\/"s for cone. 5RU Range 5, reverse. Gets [5,4,3,2,1]. ⁾\/ Literal string "\/". ẋ Repeat. Gets ["\/\/\/\/\/","\/\/\/\/","\/\/\/","\/\/","\/"]. 5R×⁶ż¢Y Link 2. Generate rest of cone. 5R Range 5. Gets [1,2,3,4,5]. ×⁶ Repeat " " that many times. Gets [" "," "," "," "," "] ż¢ Zip that with the ¢ones. Gets a list of alternating space and cones. Y Join with newlines. This puts it all together for the big cone. 3,6,8,10,10j1ż“ “.-@@-.¶ (“=“)¶ (“-“)¶(“=“)¶(“_“)¶”P€;¢ Link 3. Generate the top and put it on the cone. 10,10,8,6j1;1U Generate list 3,1,6,1,8,1,10,1,10. Does this by joining [10,10,8,6] with ones, appending a one, and reversing. “ .-@@-.¶ (“=“)¶ (“-“)¶(“=“)¶(“_“)¶” List of strings. This separates the completed parts from the non completed parts. ż Zip 'em together. Gets [number, string, number, string, ...] P€ Get the product of €ach. This completes the non completed strings by repeating them. ;¢ Attach the ¢one to the end. ``` [Answer] # Mathematica, 117 bytes ``` Column[Join[{".-@@-."},"("<>#<>")"&/@{"="~(T=Table)~6,"-"~T~8,"="~T~10,"_"~T~10},T[""<>T["\/",i],{i,5,1,-1}]],Center] ``` Outputs [![enter image description here](https://i.stack.imgur.com/jM5Dr.jpg)](https://i.stack.imgur.com/jM5Dr.jpg) you can test it on [wolfram sandbox](https://sandbox.open.wolframcloud.com/) (although the fonts they use may destort the result a little) [Answer] # Pyth, 58 bytes ``` jm.[12@,*d"\/"@,".-@@-."j@*Vj11494 11"-=_="d"()"ndTgd6;_ST ``` [Watch it in action](http://pyth.herokuapp.com/?code=jm.%5B12%40%2C%2ad%22%5C%2F%22%40%2C%22.-%40%40-.%22j%40%2aVj11494+11%22-%3D_%3D%22d%22%28%29%22ndTgd6%3B_ST&debug=0)! [Answer] # C, 138 bytes ``` f(i,j){puts(" .-@@-.\n (======)\n (--------)\n(==========)\n(__________)");for(j=1;++j<7;i=puts(""))for(;i<7;)printf(i++<j?" ":"\\/");} ``` [Try it online!](https://tio.run/##PY3BCsIwEER/ZdnTLjEtngTTYD8kUCQQ2YCx1HoqfnvcavCddmaY2WhvMdaaSA6Zt/m1PgkBoLPjaLtQAMh/Yb3JNlQ0u0U0/WFklx4LZX90xuTh5MT/ZpF5D5yox/MiZdWvxgz5goBnDKHX6rver1KIt0S7@AA) [Answer] ## VimL, 76 bytes ``` a .-@@-.␤ ␤ ␛k6A=␛j8A-␛o␛10A=␛o␛10A_␛qaI(␛A)␛kq3@aGo ␛5A\/␛qayypxxI ␛q3@a ``` [Animated](https://i.stack.imgur.com/TDZ3l.gif) with [vimanim.py](https://gist.github.com/lynn/5f4f532ae1b87068049a23f7d88581c5). [Answer] # C 165 bytes ``` y,x,z;f(){for(puts(" .-@@-.");y++<9;)for(;x=++x%14;)z=y+3-y/4,putchar(x<13?y<5?x-7^z-1?7-x^z?abs(x-7)<z?y<4?y&1?61:45:95:32:40:41:x+y>16|y-x>3?32:x+y&1?92:47:10);} ``` [Answer] # [Cubically](//git.io/Cubically), ~~345~~ 336 bytes ``` ⇒@@@ RU+30f1+3-00@-2+3@+4@@-4@+2-3@-110@+31-4@@+2-4@+10f1f1-3+0@-400@+31-4@+2-4@+3-10f1f1@@-4+1@-400@+11@+10f1f1f1@-3+0@-400@+11@+4110@f1f1f1-22@-400@+31-4@+220@-43@+43@-43@+43@-43@+43@-43@+43@-43@-4000@+31-4@@+220@-43@+43@-43@+43@-43@+43@-43@-4000@+31-4f1+220@-43@+43@-43@+43@-43@-4000@+31-4f1@+220@-43@+43@-43@-4000@+31-4f1@@+220@-43@ ``` Found via [this tool](https://codegolf.stackexchange.com/a/141839/61563) and golfed via search-and-replace, with a couple custom optimizations. [Try it online!](https://tio.run/##hY/NCQJBDIXvthIC@ZkCXg2CBejCgrDXPWwF3i3RRsaEcXEGUU/DvO97IZnWy3U6L8tW6@N2B3A4nshlVnIWARs5qABcQMYOVhWQa/wziFRDnpWdwi6yw8acG80@6Yur7qUAXS/zkuMbYrNxoKWY2/jPNzvdin9anR03f7MH63PoiN@81ic) --- Alternate method: # 391 bytes (doesn't modify cube) ``` +5/1+3@@@:1/[[email protected]](/cdn-cgi/l/email-protection)+2@@5.0-2@-4@:5/1+3@@:4/1+4@:5+2/1+51@@@@@@:5/1+4@:1/1+1@:5/1+3@:4/[[email protected]](/cdn-cgi/l/email-protection):5/1+4@:1/1+1@:4/1+4@:5+2/1+51@@@@@@@@@@:5/1+4@:1/1+1@:4/1+4@:5/1+55@@@@@@@@@@-51@:1/1+1@:5/1+3@:2/1+55@-5@+5@-5@+5@-5@+5@-5@+5@-5@:1/1+1@:5/1+3@@:2/1+55@-5@+5@-5@+5@-5@+5@-5@:1/1+1@:5/1+3@@@:2/1+55@-5@+5@-5@+5@-5@:1/1+1@:5/1+3@@@@:2/1+55@-5@+5@-5@:1/1+1@:5/1+3@@@@@:2/1+55@-5@ ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~137~~ 136 bytes -1 bytes thanks to ceilingcat ``` main(i){for(puts(" .-@@-.\n (======)\n (--------)\n(==========)\n(__________)");8<printf("%*c%s\n",++i,92,"/\\/\\/\\/\\/\\/"+i*2););} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzOi2/SKOgtKRYQ0lBQUFP18FBVy8mT0FBwxYMNIFsDV0oAHKgwlApjXg40FTStLawKSjKzCtJ01BS1UpWLY7JU9LR1s7UsTTSUdKPiUFBStqZWkaa1prWtf//AwA "C (gcc) – Try It Online") ]
[Question] [ Given a sequence of three integers, determine if the sequence is arithmetic (of the form `[a, a+d, a+2*d]`) or geometric (of the form `[a, a*r, a*r^2]`) by outputting a fourth term that completes it (`a+3*d` for arithmetic, `a*r^3` for geometric). Examples: ``` [1, 2, 3] -> 4 (This is an arithmetic sequence with a difference of 1) [2, 4, 8] -> 16 (This is a geometric sequence with a ratio 2) [20, 15, 10] -> 5 (arithmetic sequence, d=-5) [6, 6, 6] -> 6 (arithmetic with d=0 OR geometric with r=1) [3, -9, 27] -> -81 (geometric with r=-3) ``` * The input is guaranteed to be a valid arithmetic and/or geometric sequence (so you won't have to handle something like `[10, 4, 99]`) * None of the inputted terms will be `0` (both `[2, 0, 0]` and `[1, 0, -1]` would not be given) * For geometric sequences, the ratio between terms is guaranteed to be an integer (ie. `[4, 6, 9]` would be an invalid input, as the ratio would be 1.5) * If a sequence could be either arithmetic or geometric, you may output either term that completes it * You may take input as a 3-term array (or whatever equivalent) or as three separate inputs * This is code golf, so aim for the lowest byte count possible! [Answer] # [Python](https://www.python.org), 34 bytes ### -1 thanks to @Arnauld ``` lambda a,b,c:c+(c-b)**2/(b-a or 1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZBNTsMwEIXFtgdg_dSVU2xI0h9CpfQElZAQu9CFk9jUUhoH1wVxFjaVENwJTsPUClIRlcaLeXrzvRm_fXavfm3b_bvOHz52Xovsa9jITVlLSF7yal5dsEqU0WiUXrFSSFiHJOqdhaZuCdPCdqplcTQfwHCLHMvLbdcYz4ZiMYxIJEk9y4YZauxvY3tTVMQr0jtnWs80G5mI2z5i_312XiQcKcd4BbHABOx-bbagki2kM369Ud5U2KqnnWorhReSIFEbrZULitW08qAgxoQjC5hkdsTBo7IEcScoTnpjkR6mY45kSi8OgCnYiXCOOhdTcs84DhWssz_WAK7zGLd3R7lBdflhzTGHuKGLr8OwyBKwfz4x7v_nBw) ## How? Uses the fact that the increments form a geometric sequence in either case. (This avoids the longish (in Python) ternary operator.) Indeed: \$c+\frac{(c-b)^2}{b-a} = \begin{cases} c+(c-b)=2c-b & \text{if }c-b=b-a \\ c+(c-b)\times \frac c b = \frac{c^2} b & \text{if } \frac c b = \frac b a \end{cases}\$ [Answer] # [Raku (Perl 6)](https://raku.org), 13 bytes A block taking a sequence of length 3 as a single argument. This task is a perfect match for Raku's sequence operator. ``` {($_...*)[3]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kKDG7dMGy3EoFlTTbpaUlaboWa6s1VOL19PS0NKONY2shYjd9rLmKEysVlFTiFXTtgGqBSjSVFNLyixQ0NAx1jHSMNXUUNIx0THQswAwDHUNTHUMDENtMBwhBDGMdXUsdI3NNTWuImQsWQGgA) [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda a,b,c:c*(a+c)/b-b ``` [Try it online!](https://tio.run/##HYzLDoIwEEX3fMXsaHGqVB4iSf0RdNEihCYFGi0av76WJjPJnJM71/7ctC6FH8XdGzmrpwSJCvu2z4g89PSkmPLfSZsBeJuAXizCujkLAmZpyfCRBne7OUKPb2u0IymwG6SUJmBfenFkJFkIUBAiflLfcYQzQvHYg2XShbtEaCLyOnCOwKuweVRV0tUI@0QMgQKBXUPHJQrW8D8 "Python 3 – Try It Online") Note that this fails when \$ a=0 \$ or \$ b=0 \$, but that seems to be OK for this challenge :). We can verify its correctness: * For an arithmetic sequence \$ b-a = c-b \implies 2b = a+c \$, the formula rightfully produces \$ 2c-b \$: $$ \frac{c\*(a+c)}{b}-b = \frac{c\*2b}{b}-b = 2c-b $$ * Likewise, for a geometric sequence \$ b/a = c/b \implies a = b^2/c \$, the formula rightfully produces \$ c^2/b \$: $$ \frac{c\*(a+c)}{b}-b = \frac{c\*(b^2/c+c)}{b}-b = \frac{b^2+c^2}{b}-b = b+\frac{c^2}{b}-b = \frac{c^2}{b} $$ [Answer] # JavaScript (ES6), 28 bytes ``` (a,b,c)=>c-2*b+a?c*c/b:2*c-b ``` [Try it online!](https://tio.run/##XY7dDoIwDEbvfYpebrNjbPyIJuizbBWMhjADxtef5YbENe3VOd@XvvzXr7Q83x89x/uQxj4JjwFJ9lfSToWjv5EiEy5OkQ6J4rzGaSim@BCjsAgOoZISeIyB@vDPGdYI3c5tmwslgm34SnZYaDLeImy7F@T5CkGf@YnTZjDXnU0/ "JavaScript (Node.js) – Try It Online") ### Commented ``` (a, b, c) => // given the 3 integers, c - 2 * b + a ? // if the sequence is not arithmetic: c * c / b // assume it's geometric and return the next geometric term : // else: 2 * c - b // return the next arithmetic term ``` [Answer] # [R](https://www.r-project.org), 28 bytes ``` \(a,b,c)c+(c-b)^2/(b-a+!b-a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZBBasMwEEXpNqf4IRuJjIhlx467cK9QKF2WgixLiRaJieLQw3TjFHqLnCSnqSJ1kdLASILPm6eRPk9-_LLN93Gwoj6_MUUtaa7nTIuWv-cL1go1n4aNJ-TyAMskIScUfAbxhCXY68YdEErtoLwbNlszOI2D2R_NTht8hAgKnbPW-Jj0FpJPLAuWJaFOIlndmLA2fdD4Ox6vBtcjj_0ZQZZhZUlRgt0ZgNA1orzyFeFaCa7-wFHeNRmeX27ujqlv4rAFQTyGl69Su6gl2D9SFL8fNY7p_AE) Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/269495/55372). # [R](https://www.r-project.org), 33 bytes ``` \(a,b,c)`if`(c-b-b+a,c*c/b,c+c-b) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZBBbsIwEEXVLaf4iI0DYxETEsIivUIl1GUXOI4NXkCECeIwbNJKHIqepsbugqpIY1n-evM89uXT9V-mup46w8vb8INJqkkla2vWTPGa1xNJaqymPpz4cxLB7xcYJggzQpaMwF8xB3vf2iN8yT2ks912pzurcNSHk94rjbOPINFYY7QLSWsgkoFh3jInlFEkigcTNrr1GvfE42RnW8xCf0oQuV9pVORgTwYgNBXP73xBuFeEiz9wkDdVirfVw90hdVUYNiPwpX_5IrbzUoD9I3n2-1F9H_cf) Straightforward approach. [Answer] # Google Sheets, 34 bytes ``` =IF(A3/A2=A2/A1,A3*A2/A1,A3+A2-A1) ``` The formula assumes the sequence is in `A1:A3`. [Answer] # [Awk](https://www.gnu.org/software/gawk/manual/gawk.html), 33 bytes ``` 1,$0=$1-2*$2+$3?$2*$3/$1:$2+$3-$1 ``` [Try it online!](https://tio.run/##HYq5DYBQDMX6TPGKVwERObglxCzUDMD4nwi5sSXf79OaD7STrtExeubFkhzpx59KrwWBlMCETcLgM9xkQSEJ3RHrBw) You could remove the `1,` at the start if you assume that the output will not be 0, saving 2 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` I+×÷Ɲ$}E?UḢ ``` [Try it online!](https://tio.run/##y0rNyan8/99T@/D0w9uPzVWpdbUPfbhj0f@HO/dZP2qYo6Brp/CoYa714XaggArXw91bjk5@uHMxRAYoAVR6dFLYsa5HTWsOtwOJyP//lZSUog11FIx0FIxjQdpNFDRCMjKLFYAoMU8hsSizJCM3tSQzWaE4tbA0NS85VaEcKKSQqJCSmZaWWgQWyU9TMNTkigaaYaKjYAE2xtAMyRyF9NR8oCFFWEwpSizJzFcwAuk20FEwNAViA7ABpgoaWCzXUUix1TUFqjbTUQAhsFIzFKVgg1NsDRT8g5DsBYsW2YKcaayjoGsJ9LE5WLOuhaGCBoY6XWNNYMAAAA "Jelly – Try It Online") A monadic link taking a list of three integers and returning an integer. ## Explanation ``` I | Increments (differences between consecutive list members) E? | If all equal then: + U | - Add the increments to the reversed input list $} U | Else, following as a monad applied to the reversed input list: × | - Multiply by: ÷Ɲ | - The result of dividing each pair of neighbouring list members Ḣ | Head ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 13 bytes ``` ¯≈[Ṛ+|ᵃ÷Iᵃ×]t ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLCr+KJiFvhuZorfOG1g8O3SeG1g8OXXXQiLCIiLCIiLCIzLjQuMSJd) Port of [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)'s [Jelly answer](https://codegolf.stackexchange.com/a/269489/53748), sort of? [Answer] # [Alice](https://github.com/m-ender/alice), 29 bytes ``` 3&/O ?+\M@/!]!?-R.n$n?[?-.*~: ``` [Try it online!](https://tio.run/##S8zJTE79/99YTd@fy147xtdBXzFW0V43SC9PJc8@2l5XT6vO6v///0b/dU3@WwAA "Alice – Try It Online") -4 bytes thanks to [Nitrodon](https://codegolf.stackexchange.com/users/69059/nitrodon)! Uses [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [solution](https://codegolf.stackexchange.com/a/269495/97729), go upvote them! ``` 3&/M\ Read 3 arguments a b c on the stack !]! Pop and write c then b on the tape ?-R Push b on the stack and calculate b-a .n$n if b-a is 0, replace with 1 ?[? Push b and c on the stack -.* Calculate (c-b)^2 ~: Calculate (c-b)*(c-b)/(b-a or 1) ?+ Pop c and calculate c+(c-b)*(c-b)/(b-a or 1) \O@ Output the result ``` [Answer] # [Funge-98](https://esolangs.org/wiki/Funge-98), 46 bytes ``` <@.+wR-R:VI\OO-R:VIVI(4"FRTH"(4"STRN" /\OR<@.* ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3cdDTLg/SDbIK84zx9wfTYZ4aJkpuQSEeSkA6OCTIT4lLP8Y/CKhS6/9/Yy5dSy4jcy4A) [Answer] # APL+WIN, ~~43~~ 38 bytes Prompts for integers ``` ↑(=/¨a b)/(↑v×↑a←2÷/v),(↑v+↑b←2-/v←⌽⎕) ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6O2iRq2@odWJCokaeprAHllh6cDyUSgCqPD2/XLNHXAgtpAIgkkpqtfBqQe9ewFmqP5H2gE1/80LkMFIwVjrjQuIwUTBQsQbaBgaKpgaABkmikAIZA2Vji03lLByFwBAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Uses the trick described by [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt) in their excellent [Python answer](https://codegolf.stackexchange.com/a/269495/53748) although the implementation is somewhat different. ``` IQ²÷¥@/+Ṫ ``` A monadic Link that accepts a triple of integers, `[a, b, c]`, that is either arithmetic or geometric and yields the next integer in the series, `d`. **[Try it online!](https://tio.run/##y0rNyan8/98z8NCmw9sPLXXQ1364c9X/o5Me7pyhc7g961HDHAVbO4VHDXM1I///j4421FEw0lEwjtXhUogGMkx0FCwgbAMdBUNTIDYAc810FEAIzDbWUdC1BGozB/JiAQ "Jelly – Try It Online")** ### How? ``` IQ²÷¥@/+Ṫ - Link: list of integers, [a, b, c] I - forward differences -> [b-a, c-b] Q - deduplicate -> if arithmetic: L=[b-a] (potentially [0]) else: L=[b-a, c-b] (with no zeros) / - reduce L by: @ - with swapped arguments: ¥ - last two links as a dyad - f(x, y): ² - square -> x^2 ÷ - divide -> x^2/y -> if arithmetic: Z=b-a (only one item so reduce does not perform f) else: Z=(c-b)^2/(b-a) + - add {[a, b, c]} (vectorises) -> [a+Z,b+Z,c+Z] Ṫ - tail -> c+Z (= d) -> if arithmetic: d=c+(b-a) else: d=c+(c-b)^2/(b-a) ``` [Answer] # [Desmos](https://desmos.com/calculator), 19 bytes ``` f(a,b,c)=c(a+c)/b-b ``` [Try It On Desmos!](https://www.desmos.com/calculator/9zuaaxaunw) Port of [dingledooper's Python 3 solution](https://codegolf.stackexchange.com/a/269517/96039), so make sure to upvote that one too! [Answer] # [C (gcc)](https://gcc.gnu.org/), 24 bytes ``` f(a,b,c){a=c*(a+c)/b-b;} ``` Another port of [dingledooper's answer](https://codegolf.stackexchange.com/a/269495/120798)! [Try it online!](https://tio.run/##NYzLCsIwEADv@YolYMjqBpPUJ0G/xMtmJaUHo1Rv4rfHUigzt4ER14u0VixTJsEvX2RteSO4zS6nX3vwUJdWnqNNb@FarF7dYVaTYTKZjODVp9c41M9cb1XTMkWcRgEidCrCDk4qegh7CF4dYEJ14M4Qj38 "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 6 bytes ``` +∇/*⁰- ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBIiwiIiwiK+KIhy8q4oGwLSIsIiIsIjMsIDEsIDJcbjgsIDIsIDQiXQ==) Port of [dingledooper's clever formula](https://codegolf.stackexchange.com/a/269517/100664), go look at that for an explanation of why this works. ``` # input c, a, b + # c+a ∇ # rotate stack to b, c, c+a / # c/b * # (c+a) * c/b ⁰ # last input (b) - # (c+a) * c/b - b ``` This uses four necessary operations (`+/-*`) and two stack-manipulation operations (`⁰∇`). I'm fairly sure that a solution with only one stack-manipulation op is impossible but I'd love to be proven wrong. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` +╠*k;, ``` Port of [*dingledooper*'s Python 3 answer](https://codegolf.stackexchange.com/a/269517/52210), so make sure to upvote that answer as well! I/O as floats, and inputs are in the order \$c,a,b\$. [Try it online.](https://tio.run/##y00syUjPz0n7/1/70dQFWtnWOv//G@sZKBgCsZGeAZcFhFYwAbINDUAcEGFoCuSaARlQzGVkDmSA9Ola6hkAAA) **Explanation:** ``` + # Add the first two (implicit) inputs together: c+a ╠ # Divide it by the third (implicit) input: (c+a)/b * # Multiply it by the first (implicit) input: (c+a)/b*c k; # Push the second input, and discard it , # Subtract it by the third (implicit) input: (c+a)/b*c-b # (after which the entire stack is output implicitly as result) ``` The `k;,` could also be `?-Þ` for the same byte-count: [Try it online](https://tio.run/##y00syUjPz0n7/1/70dQFWva6h@f9/2@sZ6BgCMRGegZcFhBawQTINjQAcUCEoSmQawZkQDGXkTmQAdKna6lnAAA). ``` ? # Triple-swap the top three values: a,(c+a)/b,b - # Subtract the top two: a,(c+a)/b-b Þ # Only keep the top value of the stack: (c+a)/b-b # (after which the entire stack is output implicitly as result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes ``` .+ $* ¶1+¶ $'$& 1(?=1*¶1+¶(1+)) $1 (?=1+¶(1+)¶)\1 1 (1+)¶\1¶1+ 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZwQ46L9X0@bS0WL69A2Q@1D27hU1FXUuAw17G0NtSAiGobamppcKoZcIDEo/9A2zRhDLqAQmB1jCFLJxWX4/7@hjoKRjoIxF5Aw0VGw4DIy0FEwNAViAy4zHQUQ4jLWUbAEqjIHAA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Limited to positive integers due to use of unary arithmetic. Explanation: Uses @dingledooper's formula. ``` .+ $* ``` Convert to unary. ``` ¶1+¶ $'$& ``` Add `c` to `a`. ``` 1(?=1*¶1+¶(1+)) $1 ``` Multiply `a+c` by `c`. ``` (?=1+¶(1+)¶)\1 1 ``` Divide that by `b`. ``` (1+)¶\1¶1+ ``` Subtract `b` and remove `b` and `c`. ``` 1 ``` Convert to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` NθNηNζI⁻÷×⁺θζζηη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ@Bxq8C8gOKMvNKNJwTi0s0fDPzSos1PPNKXDLLMlNSNUIyc1OLNQJygIKFOgpVmhCcAcaamtb//xsr6FoqGJn/1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Trivial implementation of @dingledooper's formula. 35 bytes to validate the input: ``` NθNηNζ¿⁼⊗η⁺θζI⁻⁺ζηθ¿∧θ⁼×ηη×θζI÷×ζηθ ``` [Try it online!](https://tio.run/##XYyxDoMgFEV3v@KNjwSTOjs1tYNDjUN/AIUGEsQi4ODPU6wMtuPJPfeMki3jzHSMrXkH34VpEAtaUhdnln@8JVYvwLsNTDts5jBowZNGodfBoaWwEUKgX5TxeGPO40OZNHzXjcJu2mTUhdBOwN66Gr7/cvKpJuFQHuYBOfpTbY1v1Kq4yIdzOsayggtUsVz1Bw "Charcoal – Try It Online") Link is to verbose version of code. Works with edge cases such as `0 0 0`, `1 0 0`, `1 0 -1`. Doesn't output anything if the input is not an arithmetic or geometric sequence. Notes for both solutions: * 6 bytes (`NθNηNζ`) could be saved by requiring the input to be in JSON format. * Floating-point arithmetic could be used by replacing `÷` with `∕`. [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 41 bytes ``` $_=2*($b=<>)-$_-($c=<>)?$c*$c/$b:$c+$b-$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tZIS0MlydbGTlNXJV5XQyUZxLRXSdZSSdZXSbJSSdZWSQLK/P9vxGXCZfYvv6AkMz@v@L@ur6megaHBf92CnEQA "Perl 5 – Try It Online") ]
[Question] [ ## Background You have been given the task of calculating the number of landmines in a field. You must calculate the landmine score given a list/string of numbers and the landmine number. The landmine number tells you where landmines are. For each digit: 1. if the left digit plus the right digit is equal to the landmine number, add one to the landmine score. 2. if the left digit times the right digit is equal to the landmine number, add two to the landmine score. 3. if both 1 and 2 are satisfied, add three to the landmine score. Note: The very first and last digits cannot have landmines because there are no adjacent numbers to the left and right of them respectively. ## Your Task * Sample Input: Two strings/numbers/lists. The length of the first number will be maximum 256 characters/numbers long. It will only contain numbers. The second number will tell you the landmine number. * Output: Return the landmine score. **Explained Examples** ``` Input => Output 18371 4 => 2 ``` There are only two landmines here: * One on 8, because 1+3 = 4. * One on 7, because 3+1 = 4. ``` Input => Output 2928064 4 => 4 ``` There are four landmines here: * Three on 9, because 2+2 = 2x2 = 4. * One on 6, because 0+4 = 4. ``` Input => Output 33333 9 => 6 ``` There are six landmines here: * Two on each of the second, third, and fourth threes. ``` Input => Output 9999999999 100 => 0 ``` No combination of addition and multiplication will yield 100. ``` Input => Output 1234567890 8 => 4 ``` There are four landmines here: * Two on 3, because 2x4 = 8 * One on 4, because 3+5 = 8 * One on 9, because 8+0 = 8 **Test Cases** ``` Input ~> Output 18371 4 ~> 2 2928064 4 ~> 4 33333 9 ~> 6 9999999999 100 ~> 0 1234567890 8 ~> 4 22222 4 ~> 9 00000000000000 0 ~> 36 12951 10 ~> 4 123123123123 3 ~> 11 828828828 16 ~> 11 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. ... **Landmine Number Series** * [Next, LN II](https://codegolf.stackexchange.com/questions/262553/landmine-number-ii) * [All LN Challenges](https://docs.google.com/document/d/1XU7-136yvfoxCWwd-ZV76Jjtcxll-si7vMDhPHBKFlk/edit?usp=sharing) [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` #Σz§:+o´e*↓2¹ ``` [Try it online!](https://tio.run/##AS0A0v9odXNr//8jzqN6wqc6K2/CtGUq4oaTMsK5////WzIsOSwyLDgsMCw2LDRd/zQ "Husk – Try It Online") ``` # # how many times is arg 2 present in: Σ # flatten the results of z # zipping together # arg 1 and ↓2¹ # arg 1 without its first 2 elements # using the function §: # join together + # sum of each pair of elemnts o´e # and 2 copies of * # product of each pair of elements ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Ц¦©+s®*D)QOO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8IRDy4BwpXbxoXVaLpqB/v7//0cb6hjpWOqY6hjGchkaAAA "05AB1E – Try It Online") I feel like at least one byte can be golfed, but I can't figure out how [Answer] # JavaScript (ES6), 52 bytes Expects `(n)(array)`. ``` n=>a=>a.map(p=v=>s+=p+v==n|2*(p*(p=a,a=v)==n),s=0)|s ``` [Try it online!](https://tio.run/##dZFNDoIwEIX3noJlq6O2BZEuxosYFw3@RKPQWMPKu@OAqNhC32QWTb55b9qLqYzL72f7mBfl/lAfsS5wY6gWN2OZxQo3boZ2ViEWTzVllgoNGKw43XBwKPjT1XlZuPJ6WFzLEzuyhLOthAxiWIPccR6FZ7mM1CSkFGhQRApIIQlJohKP0kTF0GnUK/UoKQRxGgL9JhAlPCpr91LklMCKEq4pqQbRdx1I@N6r02hC7VFNPgGjauYQFYeLdRk1JRx@@4GI8XexoH9GECWlb5YSl7Uf1ut/pi1WvwA "JavaScript (Node.js) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` #ṁMzė+**↓2¹ ``` [Try it online!](https://tio.run/##yygtzv7/X/nhzkbfqiPTtbW0HrVNNjq08////9FGOpY6RjoWOgY6Zjomsf9NAA "Husk – Try It Online") Inspired by [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/262528/62393), with some added functional trickery to make it shorter. ## Explanation A necessary introduction: `z+` is a function that vectorizes the `+` operation to sum two lists element by element. If a list is longer than the other, extra elements are dropped. `z*` does the same thing with multiplication. For example (in pseudocode) `z+[1,2][3,6,9]` = `[4,8]` ``` #ṁMzė+**↓2¹ Example input: [1,2,3,2] 4 ė+** A) a list of three functions: [+,*,*] ↓2¹ B) the first input without its first two values: [3,2] Mz For each function f in A, do zfB this will result in a list of partially-applied functions missing the second argument for the vectorized sum (or multiplication): [z+[3,2], z*[3,2], z*[3,2]] ṁ Apply each of these functions to the (implicit) first input: [z+[3,2][1,2,3,4], z*[3,2][1,2,3,4], z*[3,2][1,2,3,4]] = [[4,4], [3,4], [3,4]] and concatenate the results: [4,4,3,4,3,4] # Count how many times the (implicit) second input appears in this list: 4 ``` [Answer] # [Racket](https://racket-lang.org) - 251 bytes ``` #!racket (let*([L(map(λ(c)(-(char->integer c)48))(filter char-numeric?(string->list(read-line))))][M(read)][R(curry list-ref L)])(for/sum([i(range 1(-(length L)1))])(let*([l(R(- i 1))][r(R(+ i 1))][m(=(* l r)M)])(count(λ(c)c)(list(=(+ l r)M)m m))))) ``` Input must be on separate lines, first input is the landscape, and the second input is the number representing the landmine. [Try it online!](https://tio.run/##TY8xjgIxDEV7TmFE8w2KVogtlgL2AtDQjiiiYIaIJKw8mYKz7R32SrPJjJBw5f/9ZH@rdXfJw7CY69jNECQv0RwQ7Q/@fuEYBu5m1ex9ytKKkuPPL2ZcfchV1Vnqo6h33@iy@tSaffBdhoq9mOCTcKlzcxyN0pzgetUnVcioXOnA57LvoR9dH9F4qE2t0LpcDpLafCvAmiszhQs4wZCn6jVaxOolInZYUiDlY8Xdo095@qL8MWbaFXiaR4o1Fw/D5q1m238 "Racket – Try It Online") --- ## Explanation ### Input, filtering, mapping First the program splits the landscape string into a list of characters. It filters out any characters that aren't digits then proceeds to map over the list, turning all the characters into their respective numeric digits. ### Looping We then create a `for/sum` loop that iterates over the list from indices 1 through length - 2 (length - 1 is the last index of the list, but it can't have a landmine). As the loop iterates, it collects the landmine count for each digit. Once it has completed the iteration, the loop returns the summed-up counts. ### Counting landmines The way we count the landmines for a digit is simple. We create a boolean list that contains the results of two different equality checks: addition of the left and right digits and the multiplication of the left and right digits must both be the same as the number representing the landmine in order to return `#t`. Since the multiplication of the left and right digits give two points instead of one, we repeat the check. ``` (list (= (+ left right) landmine) (= (* (left right) landmine) (= (* (left right) landmine)) ``` Once we have created the list, we can pass it to the `count` function. But there is still one ingredient we need because `count` requires two inputs, a `proc` and a `list`. The `proc` function returns a boolean value as `count` iterates the loop. If the value is `#t`, then `count` adds it to the total count. But we already have the `#t` and `#f` values, and we don't need to change them. That is where the `identity` function comes in handy. The identity function takes a value and returns it the same way as it is. This is how the function looks like in Python: ``` def identity(value): return value ``` ### Putting it all together and testing This is the final resulting code: ``` #lang racket (require (only-in rackunit check-eq?)) ; count-landmines: String Number -> Number ; Counts the number of landmines in a string. (define (count-landmines landscape landmine) (let* ([-landscape (map (lambda (char) (- (char->integer char) 48)) (filter char-numeric? (string->list landscape)))]) (for/sum ([index (range 1 (sub1 (length -landscape)))]) (let* ([left (list-ref -landscape (sub1 index))] [right (list-ref -landscape (add1 index))] [multeq (= (* left right) landmine)]) (count identity (list (= (+ left right) landmine) multeq multeq)))))) (displayln "Tests are running...") (check-eq? (count-landmines "18371" 4) 2 "18371 4") (check-eq? (count-landmines "2928064" 4) 4 "2928064 4") (check-eq? (count-landmines "33333" 9) 6 "33333 9") (check-eq? (count-landmines "9999999999" 100) 0 "9999999999 100") (check-eq? (count-landmines "1234567890" 8) 4 "1234567890 8") (check-eq? (count-landmines "22222" 4) 9 "22222 4") (check-eq? (count-landmines "00000000000000" 0) 36 "00000000000000 0") (check-eq? (count-landmines "12951" 10) 4 "12951 10") (check-eq? (count-landmines "123123123123" 3) 11 "123123123123 3") (check-eq? (count-landmines "828828828" 16) 11 "828828828 16") (displayln "Tests are complete!") ``` ## Conclusion Hope you enjoyed reading my explanation! I had fun with both writing the code and the answer :D Have a wonderful weekend ahead everyone! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 75 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.375 bytes ``` 3lƛy$₍Π∑⁰=B ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJzPSIsIiIsIjNsxpt5JOKCjc6g4oiR4oGwPUIiLCIiLCJbMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDAsMCwwXVxuMCJd) Takes long number as a list of digits then landmine number. Didn't almost accidentally call it a landline number. ## Explained ``` 3lƛy$₍Π∑⁰=B­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­ 3l # ‎⁡Get all overlapping windows of size 3 of the long input ƛ # ‎⁢To each window: y$ # ‎⁣ Remove the middle item ₍Π∑ # ‎⁤ Push a list of [product, sum]. I love parallel apply. ⁰= # ‎⁢⁡ And check whether each item equals the landmine number B # ‎⁢⁢Convert from binary # ‎⁢⁣The s flag sums the resulting list 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` NθIΣEEΦη‹¹κ⁺ι§ηκ№⟦ΣιΠιΠι⟧θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RCO4NFfDN7EAjN0yc0qAKjJ0FHxSi4s1DHUUsjU1dRQCckqLNTJ1FBxLPPNSUitA8kBxoIRzfinQmGiQEZkgdUX5KaXJJWjsWB2FQk0QsP7/30LB0MjYxNTM3MLS4L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Takes the landmine number as the first input. Explanation: ``` Nθ First input as a number η Second input Φ Filtered where ¹ Literal integer `1` ‹ Is less than κ Current index E Map over digits ι Current digit ⁺ Concatenated with η Second input § Indexed by κ Current index E Map over digit pairs ι Current pair Σ Digital sum ι Current pair Π Digital product ι Current pair Π Digital product ⟦ ⟧ Make into list № Count matches of θ First input Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [C (clang)](http://clang.llvm.org/), 64 bytes ``` f(*a,l,n){return--l>1?(*a+a[2]==n)+2*(*a*a[2]==n)+f(a+1,l,n):0;} ``` [Try it online!](https://tio.run/##jVLbboMwDH0mX2F16gQkbEBv6yjdh3Q8RAW2IBYmSvewim9ndtLLqqnSJCtxnONz7MTbYFtL/TYMpetLUQvtHdqi27c6COp19IJBLjdxlqba47GPR/98LF3JI5PyHCb9cKf0tt7nBax2Xa6ah/c1Y1@NyllX7DpX6Q5QAGivC20d7bEDc8hTCWNO2bTgKkghTEDBinAJcK485jifLcJKdzTORwLkRmUeZZyiMM4hWOP6qvEa2bE2YXW0h8ieMQSyD6m0SzVddAVUxJehKoacmYBIwJOAiYAF@RjDPRawNCvehALmAqbCoidXhrEoNNjbdsREhm9CTDAzlAtDvyQFyx1fGeVNjfz/7NyNLX527CaKf2nfdhC5NPXYpv84zOnxbe27UQtTIxKFoYHYOqlNopxDf/W91eWLd@q7aEqQ8HhyfUk3PDWfDJwK4ryiETBzdI9himZ2CqiGimahH34A "C (clang) – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` D2ỵZıçpS¹=2ḋ ``` [Try it online!](https://Not-Thonnu.github.io/run#P2hlYWRlcj0mY29kZT1EMiVFMSVCQiVCNVolQzQlQjElQzMlQTdwUyVDMiVCOSUzRDIlRTElQjglOEImZm9vdGVyPSZpbnB1dD0xJTJDOCUyQzMlMkM3JTJDMSUwQTQmZmxhZ3M9Uw==) #### Explanation ``` D2ỵZıçpS¹=2ḋ # implicit input D # duplicate the first input 2ỵ # remove the first two items Z # zip them together ı # map: ç # parallelly apply: p # product S # sum ¹= # equals second input? 2ḋ # convert from binary # implicit output ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 57 bytes ``` x=>k=>x.reduce((r,t,i)=>r+(t+x[i+=2]==k)+2*(t*x[i]==k),0) ``` [Try it online!](https://tio.run/##dYpBDoIwEEX3nmSGjgQKUYiZXoSwILWYCrGmVNLb18a4M@av3n/vPu3Tpr19huPepZlTZLWwiqU315c2AJ4CWWTlBQQRBytYjswLCllAKPLxIaowXQ7aPTa3mnJ1N5hhqKmjhs5Ujwgt4o@X1JPMTUUnav80DX2XfZ99egM "JavaScript (V8) – Try It Online") `map` and `reduce` same length [Answer] # [Python 3](https://docs.python.org/3/), ~~98 75~~ 58 bytes ``` lambda n,l:sum((x+y==l)+2*(x*y==l)for x,y in zip(n,n[2:])) ``` [Try it online!](https://tio.run/##bVDLboMwELz7K1a5YCeosg0hEMn9EcKBppBachyEjRR66K9TL25TVe1oD97xzuxjmP3bzWZLr06Laa8vry3Y1BzddKX0vpuVMmwnt/S@XZ/9bYR7OoO28K4HalNby2PD2OI7553abDaizA4Ccvh4BklkJUte5DHNSYaACpOCVA@A4Bw5ToTM8n1xKCsOZZRIRNRXhP8CrKKsCKpqL4JJVASPR0CGnBCklGUMEEWkwqhPbjDa0@RkE0a0HZyq9TeHRQmreQO4ssaF1xUbcpv8P4XibyF5EGNrLx01naXYhbEjgYBwZoV5rZsvMxb54G491ezH0TbrT@tcN3row92xwjCmFD5wpODCyDBimoR@0BqzDgLn1nUO3HQ@d871kzFzwpblEw "Python 3 – Try It Online") The inputs are the string of numbers (as a list of ints) and the landmine number (as an int). The function loops through each each pair of valid (i, i+2) indices in the list and calculates the landmine score using boolean addition. Edit: used zip to save 17 bytes (credit to c--) [Answer] # [Haskell](https://www.haskell.org/), 51 bytes ``` n%(a:t@(b:c:l))=0^(a+c-n)^2+2*0^(a*c-n)^2+n%t _%_=0 ``` [Try it online!](https://tio.run/##hZBNisJAEIX3nuItDHRrCd2JP0kw4AXmBCFKK4Ji24jppXePZaGOisPAW9TPV/WK2rn2sPW@60KiXBkXal1uSq91ZZbKDTejoJfpMB3cssE9C0nsrZJVZbq4bWOLCrWqLSEnZIQZwTaEsSaoOiUUhFR6hjDl@rOXCX4XVwupFjLxXQxZYwSzspUnx4SJLJ6JCWOGsfzh/qunr5FT/hcPvHoVYmTlhvcT/gyYzQTNHz/4DG7bprrpHd0@8B@P7vSD03kfIvqofRJwgQrk9Xwkr266Kw "Haskell – Try It Online") Uses `0^(x-y)^2` as an arithmetic version of the indicator function `sum[1|x==y]`. Recursing turned out shorter than my attempts to use `zip`. **53 bytes** ``` n%l=sum$do(a,c)<-zip l$drop 2l;[1|a+c==n]++[2|a*c==n] ``` [Try it online!](https://tio.run/##hZHdioNADIXv@xTnwoLWFGa0W5Wtj7BPMHgxVGGl4yjVvVl8d5uGbfeHloVzEZIvOSF5t@OpcW5Z/NqV40cX1H1o6Rgdtp/tABfU535A4l6Nnm18LEtfxbFJZruReJmacRpRwoRGE3JCSsgIuiLsIkJoEkJBSKSmCHvO32up4F/ibCHZQjoeiyGtlGBapnLnjvAigzMxYUwxlt/cv3X3VbLK/@KGn16FGGnZ4fcKTwNmU0Hz2w3@Btdp@6hadbb1fMfODm8Yzq2fEMC4tceM0JPjf8ipq@UC "Haskell – Try It Online") **53 bytes** ``` n%l=sum[1|(a,c)<-zip l$drop 2l,x<-[a+c,a*c,a*c],x==n] ``` [Try it online!](https://tio.run/##hZHdasMwDIXv9xTnooVkVcFO@pNA8wh9AuMLkxUW6rimSaGUvnuqijVrx8bgGIT0SUfIn67b77wfhjD1VXdqjb4mjup0M780EX7ycTxEZJ7Om7lxs5rcuzxL56oKduh3Xd@hgkmMJhSEnLAmaEtYpITEZISSkElNEVacH2u54F/ibCnZUjp@F0NaKcG0TOXOBWEpg9diwphirHi4f2v0VbLK/@KGZ69SjLTs8LrCnwGzuaDF4wY/g/u0VWrfWtcEvmPr4hbx2IQeExg/DbgiCeT5P@TUdrgB "Haskell – Try It Online") [Answer] # [Raku](https://raku.org/), 59 bytes ``` ->$_,\n{sum n X==m:ov/(.).(.)/».&{|(.sum,[*] @$_)[0,1,1]}} ``` [Try it online!](https://tio.run/##VYvbCoJAFEV/ZSODaEw643UmHOkzAgvpIZ9SQykQ9ct668fMSRFa7APnth635h5NZQezgJr2KcnpuerbZ4kKJ6XKQ/1yLcd25nI/b8fsB8uZrzTbXXAkuZ0xyim/jOPUXjsYJIdK0RcYSD4aKOoGCRd@zBGkFIknPcGiYBl8DaRu5QY4Y3rDPT8Io1hIBvEzNYvH/sD6LkM@u6u6Bb7eCE8sAY/S6Qs "Perl 6 – Try It Online") * `m:ov/(.).(.)/` finds all `ov`erlapping matches for sequences of three digits in the input number. * `».&{ ... }` passes each match object to the brace-delimited code block. (It's one byte shorter than using `map`.) * `(.sum, [*] @$_)` produces a two-element list of the sum and product of the first and last digits in each match. * `[0, 1, 1]` slices into that list, to append an extra copy of the second element (the product). * `|` flattens that list into the map output. * `n X== ...` crosses the landmine number with each sum and product using the numeric equality operator `==`, producing a list of booleans. Each product contributes two of the same boolean, thanks to the slice above. * `sum` sums those booleans, treating `True` as 1 and `False` as 0. [Answer] # [Nial](https://github.com/danlm/QNial7), ~~39~~ 36 bytes ``` ++mate team[+,[+,*,*][2drop,-2drop]] ``` [Try it online!](https://tio.run/##dU/LCoNADLz3K@a4ulvYh1UX7/6E7GGhHoTaFiv087eptRArZUICk2QmuQ7xkloMjyTlGOcecx/HTiqKXOWhs@fpdlfHpYSQmsNzGmiqRQFhUMOhgsk2tIWHpZZGiYK1PITDCkYbrSE8dmAj9dvL0l6BE4lWRHjoX9cVjCZhjb/Y3PBx8KTPv3Ff413myyVEvXzMctakFw "Nial – Try It Online") [Answer] # [R](https://www.r-project.org), ~~50~~ 47 bytes *Edit: -3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(x,n){h=t=x[-1:-2];h[]=x;sum(h+t==n,2*!h*t-n)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZDPCoJAEMbp6lMYXdRG2j-mbrJBz2GeAvGSh1pBiHqRLhb0UPU0jbuagsQHs4ffN_PNzv1xap65fFUq9-P3au_UULqXQipZpz7d-CxLijSTdXKujk6xVFKWwLx54Sm_dK-m7TPb5c7BoRADhwioC3bgLuzb1mZWCxgIYAgJhBAMMNCQQycEwoBQAwEToYUSYkzEMpkMewNY4-gIIwQQNMV9QBffaYgWGhD4K7R2OTz8BQmMoXqH8QfMCpOKPm5slGpfrG8wqu2ksLeYSzaNeb8) Defines explicitly both head and tail to add/multiply, because of usually handy (and here annoying) R recycling of vectors. Uses also a trick that `!a-b` is the same as `a==b` with the same byte-count, but due to precedence, we can multiply the former without extra parentheses. [Answer] # Swift 5.9, 112 106 103 92 81 bytes Edit: First solution was actually 112 bytes, not 114. ``` (1...m.count-2).reduce(0){$0+(m[$1-1]+m[$1+1]==n ?1:0)+(m[$1-1]*m[$1+1]==n ?2:0)} ``` Where `m` is an `[Int]` representing the minefield, and `n` is an `Int` representing the mine number. Ungolfed (plus header): ``` func landmineScore(mines: [Int], mineNumber: Int) -> Int { (1...(mines.count - 2)).reduce(0) { result, index in result + (mines[index - 1] + mines[index + 1] == mineNumber ? 1 : 0) + (mines[index - 1] * mines[index + 1] == mineNumber ? 2 : 0) } } ``` I can't remove the spaces to the left of the `?`s, because a trailing `?` is interpreted as an optional-chain. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes ``` \d+|\d ,;,$&$* &`(,?;)?,(1*),;,1*,;,((1)*),;,(1*,;,)*(?(1)(?<-4>\2)*(?(4)^)|\3\2)$ ``` [Try it online!](https://tio.run/##VYpBCsIwEEX3OcUsapnECJkkbRMqZuklglSoCzcuxGXvHicRCj4@w/zPez8@z9e9HPC6FMjrccur0LPu@k6JfkGdZpk0kpI8kuKDSLI1bFUqTLxgOp/8JdtWvbzJLTtuXSkU3ETghY02mNHz5yoQRdwBMkaQdX4YpxANBGEr7Jo/oFpxIParvgecCDb8AjR@AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+|\d ,;,$&$* ``` Convert the landmine number and each of the numbers in the list to unary. Each unary number is preceded by three characters to allow three places for the following expression to match for each number, one for when the two numbers sum to the landmine number and two for when their product equals the landmine number. ``` &` ``` Count all overlapping matches. ``` (,?;)?,(1*),;,1*,;,((1)*) ``` For each interior number, match the numbers on the left and right. The number on the right is matched in two different ways so it can be both added and multiplied. Also allow the match to start up to three separator characters before the left number. ``` ,;,(1*,;,)* ``` Skip ahead to the landmine number. ``` (?(1)(?<-4>\2)*(?(4)^)|\3\2)$ ``` If there were at least two separator characters then check that the product of the two matched numbers equals the landmine number otherwise check that the sum does. The regular expression would be 84 bytes without the conditional, but it still needs .NET capture groups in order to perform the multiplication: ``` \d+|\d ,;,$&$* &`(,?;?,)(1*),;,1*,;,((1)*)(,;,1*)*(,?\1(?<-4>\2)*(?(4)^)|,;\1\3\2)$ ``` [Try it online!](https://tio.run/##VYpBCsIwEEX3OcUsapmJETJJ2iZUzNJLBKmgCzcuxGXvHicKBR@fYf7nve7vx/Nad3heKpTbfi03ZWbT9Z1W/YImz9kQsiYZWctBZNKE30pahMKYj4dwKk5qxkAXWs1cuHhZulo5@okhKJdctGOQzzcgqbQBbK1i58MwTjFZiMo1xLV/QLPSwOI3fQt4FV38BXj8AA "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # [Arturo](https://arturo-lang.io), 63 bytes ``` $[a n][0i:0loop drop a 2'x[if=x+a\[i]n[1+]if=x*a\[i]n[2+]'i+1]] ``` [Try it!](http://arturo-lang.io/playground?JKtjCO) ``` $[a n][ ; a function taking a list a and integer n 0 ; push landmine score i:0 ; assign 0 to i loop drop a 2'x[ ; loop over a sans first 2 elements; assign current elt to x if=x+a\[i]n[1+] ; add 1 to score if x + a[i] equals n if=x*a\[i]n[2+] ; add 2 to score if x * a[i] equals n 'i+1 ; increment i in place ] ; end loop ] ; end function ``` [Answer] # Excel, 84 bytes ``` =SUM(TOCOL(LET(a,LAMBDA(b,MID(A1,ROW(A:A)+b,1)),(a(0)+a(2)=B1)+2*(a(0)*a(2)=B1)),2)) ``` String in `A1`; landmine number in `B1`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` /smmvXk1d.:z3"**+ ``` [Try it online!](https://tio.run/##K6gsyfj/X784N7csItswRc@qylhJS0v7/38LLkMjYxNTM3MLSwMA "Pyth – Try It Online") ### Explanation ``` /smmvXk1d.:z3"**+"Q # implicitly add "Q # implicitly assign Q = eval(input) # z = input() (second input) m "**+" # map lambda d over "**+" m .:z3 # map lambda k over all substrings of length 3 in z Xk1d # replace the middle char of k with d v # and evaluate s # flatten nested list / Q # count occurrences of Q ``` [Answer] # Q, 33 bytes implemented as a function with two implicit arguments, **x** and **y**. **x** is a list of ints (the "field") and **y** is an int (the landmine score). ``` {sum(y=sum x)+2*y=prd x:2 -2_\:x} q) f: {sum(y=sum x)+2*y=prd x:2 -2_\:x} q) f[10 vs 1234567890; 8] 4 q) f[1 2 3 1 2 3 1 2 3 1 2 3; 3] 11 ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 25 bytes ``` +´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸= ``` [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK8K0KCgry53iiL7Dl8ud4oi+w5fLnSkw4oC/MuKKj8K34o2JM+KKuOKGlSniirg9Cgoy4oC/OeKAvzLigL844oC/MOKAvzbigL80IEYgNA==) ### Explanation ``` +´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸= ( )⊸ Using the left argument (array of digits): 3⊸↕ Get all windows (contiguous subarrays) of length 3 as rows of a 2D array ⍉ Transpose rows and columns 0‿2⊏· Keep the first and last rows (+˝∾×˝∾×˝) Make a 1D array containing their sums, products, and products again = Equality with the right argument (1s when equal, 0s otherwise) +´ Sum ``` [Answer] # [Desmos](https://desmos.com), 319 bytes <https://www.desmos.com/calculator/n5dzd6tvqr> Input is a list of numbers. `f(a,b)=\sum_{n=1}^{\operatorname{length}(a)}\left[\left\{i=1:0,\left\{i=\operatorname{length}(a):0,\left\{a\left[i-1\right]+a\left[i+1\right]=b:1,0\right\}+\left\{a\left[i-1\right]a\left[i+1\right]=b:2,0\right\}\right\}\right\}\ \operatorname{for}\ i\ =\ \left[1,...\operatorname{length}(a)\right]\right]\left[n\right]` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 12 bytes ``` ᵉpttᵋ+*:,,$Ĉ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fhsfbu0sKCl5uLVbW8tKR0flSMeS4qTkYqjsgpvnow11LHSMdcx1DGMVTLiijXQsdYyAIgY6ZjomYBFjHSiMVbDkirbUwYCxCoYGBlxAc4yAqkx0TIE6zYEmWOoYxCpYgEyEQrBpBjo4YawC1BRLoBmGIFNhhmKQsQrGXNEWYIcikUAtZhB_AQA) ``` ᵉ Parallelly apply the following two unary functions: p Choose a prefix tt Tail of tail ᵋ Parallelly apply the following two binary functions: + Add * Multiply (This step forces the prefix to have the same length as the tail of tail) :, Duplicate and join , Join $ Swap Ĉ Count ``` [Answer] # [Uiua](https://uiua.org), 21 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3 ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAgLyvima3DlzFfMj3iip_iioMvKy_Dl-KGmDHihrsx4o2J4perMwoKZiBbMSA4IDMgNyAxXSA0CmYgWzIgOSAyIDggMCA2IDRdIDQKZiBbMyAzIDMgMyAzXSA5CmYgWzkgOSA5IDkgOSA5IDkgOSA5IDldIDEwMApmIFsxIDIgMyA0IDUgNiA3IDggOSAwXSA4CmYgWzIgMiAyIDIgMl0gNApmIFswIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDBdIDAKZiBbMSAyIDkgNSAxXSAxMApmIFsxIDIgMyAxIDIgMyAxIDIgMyAxIDIgM10gMwpmIFs4IDIgOCA4IDIgOCA4IDIgOF0gMTYK) ``` /+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3 ◫3 # windows of length three ⍉ # transpose ↻1 # rotate one ↘1 # drop one ⊃/+/× # sum and product of columns ⊟ # couple = # where is it equal to input? ×1_2 # multiply by [1 2] ♭ # deshape /+ # sum ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~170~~ 163 bytes Golfed version. [Try it online!](https://tio.run/##hY/BboMwDIbvPIXVQ5UM2iaB0sDEpB17mHaYph2mHRgNXaaUVYROW6s@OzOl6gQc@suKYvuz9dtmqUnrr/dPlVXwkOoCDo7znRowMXmqSl2svWVR0eQOX0hqknsbTAibxfl0r7cvuvpYFiv1M7VGZ4pwL59avVcTTukhS60i1iOFpykOnbYmOdHYnATytsnLJnfbXOeEGLdMkg0dj4m5Of2odX1QxirA9rlrXf5fujmXRFuyxxpgpXLY4C0kLdc2hvuyTH9f22veaAzPhcZb8FBAbbFamYIYMuLSX/CRBwGlMJvB467a7qoYRJ8TkZAsDIZk0Cf9RshFXS7sc9FFCHPGujgbGBV@MA8XMmKIyyseRKOh16jPsY5woOfCD4c2ojk/Gb5iAf1eAnm/i3Pe56WQbTTLwwGN@NE5OvUf) ``` (f,m)=>(0/:f.zipWithIndex.slice(1,f.size-1)){case(s,(n,i))=>val l=f(i-1)-48;val r=f(i+1)-48;if((l+r==m)&&(l*r==m))s+3 else if(l+r==m)s+1 else if(l*r==m)s+2 else s} ``` Ungolfed version. [Try it online!](https://tio.run/##lZJNb4JAEIbv/oqJB7MoVRYUwcQmTXox6cfBND00Payw4DbrapalsW387XZZkZZaSZwAh5n3mQ9msohwst@vF280UnBPmICvFkBME@BExCsm6DxaS4oSRnk8gbmSTKQ2FIGHfLWgcgIzoSzzhamBAYy4/8k2z0wtZyKm237GWUQRtssYpyJVS7gCbPWTNY/vaKKQY5U8QEQyCigrStuARL6ygcVby4LpdakAeCccuOZ0WZMUacUhI8luWcpUTSlZuqxLe@ekUS4lNePowpWikrAEEDKFe8es018/xIJOBw7x7r9xq8oEYCbUebzKR7mevCjRVOGI4TNYtxlz65hxG9euVbzlAaz0NSAi02wCN1KSj5fD8l/1sp8E@9n2RnsVF6h@MG0ceGPctmGotzYYwGOuNrmalLXPMG7oBo4/PKWGTZRXmGbCOuM3MWFlGsSOU0edxsFcbzjyx0HoaDS4oE@3sNPZwibGqZmG/3Tq@c2thiNsBrygTT1f9WjWq6MYN7GBGxyeoqh/Qprz2rX2@28) ``` object Main { def landmineScore(field: String, mineNumber: Int): Int = { field.zipWithIndex.slice(1, field.length - 1).foldLeft(0) { case (score, (num, idx)) => val left = field(idx - 1).asDigit val right = field(idx + 1).asDigit val current = num.asDigit if ((left + right == mineNumber) && (left * right == mineNumber)) score + 3 else if (left + right == mineNumber) score + 1 else if (left * right == mineNumber) score + 2 else score } } def main(args: Array[String]): Unit = { println(landmineScore("18371", 4)) // Output: 2 println(landmineScore("2928064", 4)) // Output: 4 println(landmineScore("33333", 9)) // Output: 6 println(landmineScore("9999999999", 100)) // Output: 0 println(landmineScore("1234567890", 8)) // Output: 4 println(landmineScore("22222", 4)) // Output: 9 println(landmineScore("00000000000000", 0)) // Output: 36 println(landmineScore("12951", 10)) // Output: 4 println(landmineScore("123123123123", 3)) // Output: 11 println(landmineScore("828828828", 16)) // Output: 11 } } ``` [Answer] # Java, ~~120~~ 112 Bytes `var l=range(2,n.length).filter(i->n[i-2]+n[i]==t).count()+range(2,n.length).filter(i->n[i-2]*n[i]==t).count()*2;` -8 Thanks to @ceilingcat [Try It](https://tio.run/##jU89b4MwEJ3Dr7jR5sOSM1SREN07dMoYMbjEpSbmQPZBVUX8dnooqKrUpTfc53vv7jozm6K73lbXj0MgiGTINdBxW03kvIoUrOnVC9L5kaXlOk5vnkGNNzHCq3EI9@SwN3eBeXBX6HkkmOawvdRgQhvlhjw4JK4RKkD7CY/qfsqP@Sn/5Zcygd02BhDj9VOZsMBsAvgqGGyt0Dkqb7Glj0JL9e482SBc8YwXV@g645DpuqpIqmaYkITM/sNL//LSI@/@uej8Fcn2aphIjfwgeRRebsctybKu3w)! ]
[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/115342/edit). Closed 6 years ago. [Improve this question](/posts/115342/edit) Sometimes I find myself wanting a hot dog (don't we all) and so I make one. Now to make a hot dog, it is very simple. 1) Put the hot dogs into boiling water 2) Wait for a certain amount of time (detailed below) 3) Eat the hot dog once the time has elapsed. You may have noticed that I said > > certain time (detailed below) > > > and so I will detail. Many different brands have many different recommendations for how long we should cook the hot dogs, but I have found it best to cook them for exactly 4 minutes and 27 seconds (don't ask). I have tried many different timers, but have found that a program that continuously outputs is the best way to attract my attention. ## YOUR TASK You have to make a program that will output the message `Not ready yet` for exactly 4 minutes and 27 seconds. After this time has elasped, you should output `Eat your hot dog` until the end of time. Please don't take any input. # HOW TO WIN You must write the shortest code in *bytes* to win because this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [Answer] # Scratch, ~~93~~ 78 bytes ![image representation](https://i.stack.imgur.com/npwUy.png) Code: ``` when gf clicked say[Not ready yet wait until<(timer)>[267 say[Eat your hot dog ``` Generated by <https://scratchblocks.github.io/>, which seems to be the standard for Scratch scoring. Fairly self explanatory. When the program starts, say "Not ready yet" until the timer (which is counted in seconds) is greater than 267. Then starts an infinite loop where it says `Eat your hot dog`. It *is* continuous output, because the `say` block runs forever unless you `say []` or `say` something else. [Answer] # Bash + coreutils, 50 ``` timeout 267 yes Not ready yet yes Eat your hot dog ``` ### Explanation Fairly self-explanatory I think, but just in case: * The `yes` coreutil continuously repeatedly outputs any parameters passed to it on the command line * The `timeout` coreutil takes a numeric timeout parameter followed by a command. The command is run, then killed after the specified timeout. [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 67 bytes ``` #l s="Not ready yet" ?_time>267:s="Eat your hot dog" hint s goto"l" ``` Save as `"hotdog.sqs"` (or whatever) in the mission folder and call with `[] exec "hotdog.sqs"`. **Explanation:** ``` #l // Label for the "goto" s="Not ready yet" ?_time>267:s="Eat your hot dog" // "?:" means "if () then" in a script. // "_time" is a local variable that is automatically // created and updated in every script. Its value // is the time in seconds since the script started. hint s // Outputs the text in a text box. ~.1 // Sleeps for a tenth of a second. // The script seems to work without sleeping too, // so I didn't include this in the golfed version. // Looping in a script without sleeping is always // a bad idea, though. It sometimes crashes the game. goto"l" // Go back to the beginning of the loop. // This is the only way to create a loop if you don't // want to halt the game (and the time calculation) // until the loop finishes. ``` > > I have tried many different timers, but have found that a program that continuously outputs is the best way to attract my attention. > > > This solution should be especially good with attracting your attention, since the `hint` command plays a clinging sound effect every time it's called, which sounds very annoying when the simultaneous sounds get clipped in a tight loop. [Answer] # JavaScript ES6, 76 bytes ``` $=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517) ``` # Explanation This prints something to the console every 517 milliseconds. At first, it prints `'Not ready yet'` and decreases the counter. After 517 iterations (`= 517 * 517 = 267289 ms`), it starts printing `'Eat your hot dog'`. # Test ``` f= $=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517); (setInterval("console.log('DONE NOW')",267000)&&f())(); ``` [Answer] ## Powershell, 85 71 59 bytes ``` 1..276|%{Sleep 1;'Not ready yet'};for(){'Eat your hot dog'} ``` There's probably a much better way, so criticism welcome! This is my first golf attempt :) **EDIT** Down a whole 14 bytes thanks to AdmBorkBork! And definitely a technique to remember! **EDIT 2** Another 12 bytes gone thanks to Matt. Not calling write twice also removed 2 spaces, very helpful! [Answer] # GameMaker' scripting language variant used in Nuclear Throne Together mod, 68 bytes ``` t=0while 1{trace(t++<8010?"Not ready yet":"Eat your hot dog")wait 1} ``` ### Explanation * GML's parser is deliciously forgiving. Semicolons and parentheses are optional, and the compiler is not at all concerned about your spacing outside the basic rules (`0while` parses as `0`,`while` and thus is ok) * Variables leak into the executing context unless declared via `var` (same as with JS). * GML variant used in NTT introduces a `wait` operator, which pushes the executing "micro-thread" to a list for the specified number of frames, resuming afterwards. Coroutines, basically. The game is clocked at 30fps, so 4m27s == 267s == 8010 frames. * trace() outputs the given string into the chat. If you have the videogame+mod installed, you can save that as some `test.mod.gml`, and do `/loadmod test` to execute it, flooding the chat with "status reports": ![screenshot](https://i.stack.imgur.com/hJYkA.png) [Answer] # Python 2, 92 bytes ``` from time import* t=time() while 1:print"Not ready yet"if time()-t<267else"Eat your hot dog" ``` [Try it online!](https://tio.run/nexus/python2#JcrBCkBAEADQ@37FtCeUAwdKHF39w5bBlDXbGGm/fpHjq5cWYQ9KHoF8YNHC6PAxy8290Y5QdUHoUDuxgqCbI0RUSwv8q9S@blrcT7SjU4h8CWxvnXm1KT0 "Python 2 – TIO Nexus") [Answer] # TI-Basic, 75 bytes ``` For(A,1,267 Disp "Not ready yet Wait 1 End While 1 Disp "Eat your hot dog End ``` Explanation ``` For(A,1,267 # 9 bytes, for 267 times... Disp "Not ready yet # 26 bytes, display message Wait 1 # 3 bytes, and wait one second End # 2 bytes, ...end While 1 # 3 bytes, after that, continuously... Disp "Eat your hot dog # 31 bytes, output second message End # 1 byte, ...end ``` [Answer] # C# 144 bytes ``` ()=>{for(int i=0;;){var s="\nEat your hot dog";if(i<267e3){i++;s="\nNot ready yet";}System.Console.Write(s);System.Threading.Thread.Sleep(1);}}; ``` Ungolfed full program: ``` class P { static void Main() { System.Action a = () => { for (int i = 0; ;) { var s = "\nEat your hot dog"; if (i < 267e3) { i++; s = "\nNot ready yet"; } System.Console.Write(s); System.Threading.Thread.Sleep(1); } }; a(); } } ``` Unfortunately I could not use the `?:`-operator as I have not found a way to stop incrementing `i` without the `if`. [Answer] # C#, 174 172 147 bytes *Saved 25 bytes by "borrowing" some ideas from [raznagul's C# answer](https://codegolf.stackexchange.com/a/115486/58437) and merging them with the sum of first n numbers trick!* *Saved 2 bytes by using the sum of first n numbers trick for a loss of precision of 185 milliseconds.* ``` class P{static void Main(){for(int i=1;;){System.Console.WriteLine(i++<731?"Not ready yet":"Eat your hot dog");System.Threading.Thread.Sleep(i);}}} ``` Ungolfed program: ``` class P { static void Main() { for (int i=1;;) { System.Console.WriteLine( i++ < 731 ? "Not ready yet" : "Eat your hot dog"); System.Threading.Thread.Sleep(i); } } } ``` **Explanation:** Since the total time to wait is hardcoded at 267 seconds, one can consider this number as a telescopic sum of the first n natural numbers, `n * (n + 1) / 2`, which must equal 267000 milliseconds. This is equivalent to `n^2 + n - 534000 = 0`. By solving this second order equation, `n1 = 730.2532073142067`, `n2 = -n1`. Of course, only the positive solution is accepted and can be approximated as **730**. The total time can be calculated as `730 * (730 + 1) / 2 = 266815 milliseconds`. The imprecision is *185 milliseconds*, imperceptible to humans. The code will now make the main (and only) thread sleeps for 1 millisecond, 2 milliseconds and so on up to 730, so the total sleep period is ~267 seconds. ***Update:*** The program's logic can be simplified further - basically it needs to continuously display a message and wait a specified time until switching to the second message. The message can be change by using a ternary operator to check the passing of the specified time (~267 seconds). The timing aspect is controlled by using an increasing counter and pausing the execution thread. However, since the counter variable continues increasing indefinitely without any conditions to check its value, one can expect an integer overflow at some point, when the message reverts to `Not ready yet`. A condition can be added to detect and mitigate the issue by assigning a positive value greater than 730 when the overflow occurs - like `i=i<1?731:i` inside the `for` loop. Sadly, it comes at the cost of 11 additional bytes: ``` class P{static void Main(){for(int i=1;;i=i<1?731:i){System.Console.Write(i++<731?"\nNot ready yet":"\nEat your hot dog");System.Threading.Thread.Sleep(i);}}} ``` The key here is using the **counter value** in milliseconds to greatly delay the moment of overflow. The time until overflow can be calculated according to the `sum(1..n)` formula, where n = the maximum 32-bit signed integer value in C# (and the .NET framework) or 2^31 - 1 = 2147483647: `2 147 483 647 * 2 147 483 648 / 2 = 2,305843008 x 10^18 milliseconds = 2,305843008 x 10^15 seconds = 26 687 997 779 days = ~73 067 755 years` After **73 million years**, it might not matter if a glitch in the system appears - the hot dog, the hungry OP and maybe the human race itself are long gone. --- **Previous version (172 bytes):** ``` namespace System{class P{static void Main(){for(int i=1;i<731;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(i++);}for(;;)Console.Write("\nEat your hot dog");}}} ``` Ungolfed program: ``` namespace System { class P { static void Main() { for (int i = 1; i < 731; ) { Console.Write("\nNot ready yet"); Threading.Thread.Sleep(i++); } for ( ; ; ) Console.Write("\nEat your hot dog"); } } } ``` --- **Previous version (174 bytes):** ``` namespace System{class P{static void Main(){for(int i=0;i++<267e3;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(1);}for(;;)Console.Write("\nEat your hot dog");}}} ``` Ungolfed program: ``` namespace System { class P { static void Main() { for (int i=0; i++ < 267e3; ) { Console.Write("\nNot ready yet"); Threading.Thread.Sleep(1); } for ( ; ; ) Console.Write("\nEat your hot dog"); } } } ``` --- Alternatively, the program may display `Not ready yet` only once, wait until the specified time is over and then output `Eat your hot dog` by overwriting the previous message while being quite a few bytes shorter: # C#, 145 bytes ``` namespace System{class P{static void Main(){Console.Write("Not ready yet");Threading.Thread.Sleep(267000);Console.Write("\rEat your hot dog");}}} ``` Ungolfed program: ``` namespace System { class P { static void Main() { Console.Write("Not ready yet"); Threading.Thread.Sleep(267000); Console.Write("\rEat your hot dog"); } } } ``` [Answer] # Ruby, 80 71 67 Bytes *Edit: Thanks to manatwork for shaving off 13 whole bytes* ``` 267.times{puts"Not ready yet" sleep 1} loop{puts"Eat your hot dog"} ``` [Answer] # 05AB1E, ~~43~~ ~~29~~ 28 bytes (Thanks to Adnan) ``` 267F…€–Žä‡«ªw,}[“Eat€ž…ß‹·“, ``` Does not work online, since it times out. Offline it will work. `267F`: Loop 267 times `…€–Žä‡«ª`: First string with dictionary `w,`: Wait one second and print `}[`: End if loop and start infinite loop `“Eat€ž…ß‹·“`: Second string with dictionary `,`: Print [Answer] ## Batch, ~~99~~ 97 bytes ``` @for /l %%t in (1,1,267)do @echo Not ready yet&timeout>nul 1 :l @echo Eat your hot dog @goto l ``` Batch has no date arithmetic so as a simple 267 second timeout isn't permitted the best I can do is 267 one-second timeouts. Edit: Removed unnecessary `/t`. [Answer] # Python, 115 bytes My first time trying something like this. I am also a beginner so here it goes in Python 3 for 115 bytes: ``` import time for i in range(267): time.sleep(1) print("Not ready yet") while 1: print("Eat your hotdog") ``` [Answer] # JavaScript Blocks Editor for micro:bit, 90 Bytes [![enter image description here](https://i.stack.imgur.com/DTBDn.png)](https://i.stack.imgur.com/DTBDn.png) The code: ``` basic.showString("Not ready yet") basic.pause(254000) basic.showString("Eat your hot dog") ``` [You can try it here.](https://pxt.microbit.org/99946-23184-97039-53689) Got inspired by the Scratch answer to solve the task with my micro:bit. The only Problem is that the pause-block starts after outputting the first string so i needed to reduce the pause by 13s. Note: The old Microsoft Block Editor for micro:bit is shorter to create but produces more code so is in fact longer. [Answer] On the basis that the OP wants hotdogs continuously, until the end of time - which I understand from the phrase: > > After this time has elasped, you should output Eat your hot dog until the end of time. > > > This is my answer: # C++, 187 188 224 167 bytes Whitespace removed (167 bytes): ``` #include<stdio.h> #include<windows.h> int main(){for(;;){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");}return 0;} ``` readable form (224 bytes): ``` #include <stdio.h> #include <windows.h> int main() { for( ; ; ){ for(int x=0; x < 267; x++){ Sleep(1000); printf("Not ready yet"); } Sleep(1000); printf("Eat your hot dog"); } return 0; } ``` If, on the other hand, OP enjoys his hot dogs in moderation, then this is my answer: **Whitespace removed (158 bytes):** ``` #include<stdio.h> #include<windows.h> int main(){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");return 0;} ``` **readable form (198 bytes):** ``` #include <stdio.h> #include <windows.h> int main() { for(int x=0; x < 267; x++){ Sleep(1000); printf("Not ready yet"); } Sleep(1000); printf("Eat your hot dog"); return 0; } ``` [Answer] # Excel VBA, 82 Bytes Anonymous VBE immediates window function that takes no input and outputs whether or not you should eat your hot dog to cell `[A1]`. ``` d=Now+#0:4:27#:Do:[A1]=IIf(Now<d,"Not ready yet","Eat your hot dog"):DoEvents:Loop ``` [Answer] # Excel VBA ~~122~~ 94 bytes ``` Sub p() e=Now+#0:4:27# Do [a1]=IIf(Now<e,"Not ready yet","Eat your hot dog") Loop End Sub ``` Thanks [Taylor Scott](https://codegolf.stackexchange.com/users/61846/taylor-scott) [Answer] ## Javascript, 83 Bytes ``` d=Date.now() while(1)alert(Date.now()-d<267000?"Not ready yet":"Eat your hot dog")) ``` Alertz for everyone! [Answer] # PERL, 76 bytes ``` $|++; for(1..247){print'Not ready yet';sleep 1};print "Eat your hot dog";for(;;){} ``` [Answer] ## **PHP** 88 bytes ``` <?$t=0;do{$t++;echo "Not ready yet";sleep(1);} while ($t<267);echo "Eat your hotdog";?> ``` [Answer] ## REXX, 82 bytes ``` do forever if time(e)<267 then say 'Not ready yet' else say 'Eat your hot dog' end ``` [Answer] # Java 7, 152 bytes ``` void c(){for(long s=System.nanoTime(),e=s+(long)267e9;s<e;s=System.nanoTime())System.out.println("Not ready yet");System.out.print("Eat your hot dog");} ``` **Explanation:** ``` void c(){ // Method for( // Loop long s=System.nanoTime(), // Current time in nanoseconds as start e=s+(long)267e9; // End time (267 seconds later) s<e; // Loop as long as we haven't reached the end time s=System.nanoTime()) // After every iteration get the new current time in nanoseconds System.out.println("Not ready yet"); // Print "Not ready yet" as long as we loop // End of loop (implicit / single-line body) System.out.print("Eat your hot dog"); // Print "Eat your hot dog" } // End of method ``` [Answer] # PHP, 68 bytes ``` for($t=268;$t--;sleep(1))echo$t?"Not ready yet←":"Eat your hot dog"; ``` continuous output; `←` is ASCII 10 = LF. Run with `-r`. **one-time output, 50 bytes** ``` Not ready yet<?sleep(267);echo"←Eat your hot dog"; ``` where `←` is ASCII 13 = CR. Save to file or use piping to run. [Answer] # [RBX.Lua](http://wiki.roblox.com/index.php?title=Special:RobloxLandingPage), 69 bytes ``` for i=1,267 do print"Not ready yet"Wait(1)end;print"Eat your hot dog" ``` RBX.Lua is the language used on [ROBLOX.com](http://roblox.com). It is a modified version of [Lua](http://lua.org) 5.1 that features a built-in 'Wait' function. The above code is pretty self-explanatory, below is a more readable version: ``` for i = 1, 267 do print("Not ready yet"); Wait(1); end print("Eat your hot dog"); ``` The code outputs "Not ready yet" continuously into **STDOUT**, for 267 seconds (4 minutes 27 seconds) before outputting "Eat your hot dog". [Answer] # C - 130 bytes It could be slightly shorter (128bytes), but I thought it neater to overwrite "Not ready yet" ``` #include<stdio.h> #include<unistd.h> int main(){printf("Not ready yet");fflush(stdout);sleep(267);printf("\rEat your hot dog\n");} ``` [Answer] # VBA,126 Bytes ``` sub hd() Debug.print "Not ready Yet" application.wait(now+timevalue(00:04:27)) Debug.print "Eat your hot dog" end sub ``` [Answer] # Python 2.7, ~~90~~ 88 bytes ``` import time;exec"print'Not ready yet';time.sleep(1);"*267;while 1:print"Eat your hotdog" ``` ]
[Question] [ Consider a list of subject, grade pairs. E.g. ``` [("Latin", "A"), ("French", "A*"), ("Math", "B"), ("Latin", "A*")] ``` The task is to return the same list but with each subject given at most once. Where a subject occurred more than once originally, the returned list should have the highest grade for that subject. Using the UK system, "A\*" is a better grade than "A" and of course "A" is better than "B" etc. Only "A" can be followed by an asterisk. The output for this case should be: ``` [("Latin", "A*"), ("French", "A*"), ("Math", "B")] ``` Another example: ``` [("Latin", "A*"), ("French", "A*"), ("Math", "B"), ("French", "A*"), ("Math", "C")] ``` The output should be: ``` [("Latin", "A*"), ("French", "A*"), ("Math", "B")] ``` Your returned output list can be in any order you like. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. Languages I am hoping for: * Python, because I wrote a terrible solution in python which inspired this question. **Done**. * C. Because real men/women code in C when it makes no sense for the problem at hand. **Done**. * Julia. Because it's an awesome language. # Input assumptions You can assume there are no more than 10 subject/grade pairs, the input is printable ASCII and there are no spaces within the subject names. [Answer] # [Python](https://www.python.org), 52 bytes ``` lambda x:dict(sorted(x,key=lambda n:n[1][~0])[::-1]) ``` is there a way to golf the list reversal? [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXISc5NSEhUqrFIyk0s0ivOLSlJTNCp0slMrbaFSeVZ50Yax0XUGsZrRVla6hrGaUL1xBUWZeSUaaRrRGko-iSWZeUo6CkqOWkqaOgoKGkpuRal5yRkoQr6JJWABJxAfWYUzRAAmD-TGakJtWbAAQgMA) [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` import Data.List s=nubBy((.fst).(==).fst).sortOn(last.snd) ``` [Try it online!](https://tio.run/##Zco9DsIwDIbhnVNEFoODqtwgAwUxteoBEIOBolqkbhWbgdOHvwEhtu979Qyk1z6lUnicp2xuS0ahYbWFRrkd6ztiuKj5gDH6z9Kn6wQTqQWVsy8jscQ5s9hS9wgNGQtUDtYr8JVzCLvcy2n4SS3ZO9Sv/y@@YAP@UB4 "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 77 bytes ``` import Data.List (c?f)a=c(f a).f s=nubBy((==)?fst).sortBy(compare?(last.snd)) ``` [Try it online!](https://tio.run/##ZctBCsIwEIXhfU8RgosZKblBKFZxVU8gLsaY0GCalsy48PSxuhFx@T7@NxLffUq1xmmZi6gDCZkhsjTguoBkHQRFaELDNj@u/RPAWuwCCxpeDyu4eVqo@A4SsRjON8Q6Ucx2KTHLhs@gB5KYdav0bquxVQr0sfjsxh86kXygf@//4hvsNV7qCw "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 84 bytes ``` import Data.List;import Data.Function s=nubBy(on(==)fst).sortBy(on compare$last.snd) ``` [Try it online!](https://tio.run/##ZcoxDsIgFIDh3VMQ0gFMwwUMg9V0ak9gHJ6IKZE@CO918PSoXdQ4/l/@CejuY6w1zDkVFkdgMEMg3n1Dv6DjkHBDFpdL91AJlbX6RqwNva5VhEtzhuKbCMSG8KrrDAFtLgG5oZOSA3BA2Qq530rdCqFkXzy66YdG4BW6d/8fn@Eg9bk@AQ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 97 bytes ``` import Data.List;import Data.Function g"A*"="@";g s=s s=nubBy(on(==)fst).sortBy(on compare$g.snd) ``` [Try it online!](https://tio.run/##ZcxBDoIwEAXQPadoJixaQ7gAaaJIWOEJjIsRERphSjrDwtNXYaPG5X/5/w/Ij24cY3TT7IOoCgXzxrEU31Av1IrzlPRw2IGFPRS9YssJW1qu5VN70taaO4vJ@b3aRLV@mjF0aZ8z3Uyc0JGdgyNJ@ayhQXEEmVofTaaUhjp01A4/dELZoFzzf@NTOIK5xBc "Haskell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes ``` ⁽hġ‡tṘv∵ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb1oxKHigKF04bmYduKItSIsIiIsIlsoXCJMYXRpblwiLCBcIkFcIiksICAoXCJGcmVuY2hcIiwgXCJBKlwiKSwgIChcIk1hdGhcIiwgXCJCXCIpLCAoXCJMYXRpblwiLCBcIkEqXCIpXSJd) Sort by the reverse of each grade, group by subject, best of each subject group *-1 thanks to emanresuA* ## Explained ``` ⁽hġ‡tṘv∵ ⁽hġ # Group subjects by their subject v∵ # Get the maximum of each group by ‡tṘ # Reversed grade. ``` [Answer] # [Elm](https://elm-lang.org), 82 bytes ``` import Dict List.sortBy(Tuple.second>>String.reverse)>>List.reverse>>Dict.fromList ``` Takes a list and returns a dict. [`>>`](https://package.elm-lang.org/packages/elm/core/1.0.5/Basics#(%3E%3E)) is function composition in the reversed direction: `f>>g` in Elm is `g.f` in Haskell. According to [the source code of Elm's core package](https://github.com/elm/core/blob/65cea00afa0de03d7dda0487d964a305fc3d58e3/src/Dict.elm#L607-L610), `Dict.fromList` will keep the last value when there are duplicate keys. You can try it [here](https://elm-lang.org/try). Here is a full test program: ``` import Html exposing (text) import Dict f=List.sortBy(Tuple.second>>String.reverse)>>List.reverse>>Dict.fromList main = [("Latin", "A*"), ("French", "B"), ("Math", "A"), ("French", "A*"), ("Math", "C")] |> f |> Debug.toString |> text ``` [Answer] # [Factor](https://factorcode.org) + `sets.extras`, ~~65 49~~ 47 bytes ``` [ [ last last ] sort-with [ first ] unique-by ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owc0zocGefu5WCsWpJcV6qRUlRYnFCsX5RSWZeelAscLS1Lzk1GKF7NSivNQchYKi1JKSyoKizLwSBWuuai4FIKhWUPJJBCpXUlByVFKohYm5FQF1ZqAJ-iaWZBQDxZyQxOCatbAJYhFzwWZLKEiwdmlpSZquxU39aIVohZzE4hIIEQv2kG55ZkkGUDwtswgsVpqXCfSdblKlQixE27LkxJwcBT0IZ8ECCA0A) * `[ last last ] sort-with` Sort the input by the last character of each grade. * `[ first ] unique-by` Retain every entry that has a subject that has not been encountered before. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ ~~7~~ 5 bytes ``` ZḢ«/ƙ ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4Y5Fh1brH5v5/3C7u2bWo8Z9XFz//0drKPkklmTmKekoKDkqaeooKGgouRWl5iVngEW0oEK@iSVgAScQH1kLUEGsjgKFpjhhGqJFtCnoKhAKnIHGAgA "Jelly – Try It Online") ``` ƙ Group pairs by ZḢ their first elements, ƙ and for each group / reduce by « recursively vectorizing minimum. ``` The vectorizing minimum leaves the shared subject name unchanged while taking the minimum of the letter grades, and the vectorization mechanism's length mismatch handling adds an asterisk if any of the grades for that subject has an asterisk. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ≔⦃⦄ηFθF‹⮌§ι¹⮌∨§η§ι⁰Z§≔η§ι⁰§ι¹η ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcXOBYXZ6bnaVTX6ihkaFpzpeUXKWgUaiqAaZ_U4mKNoNSy1KLiVA3HEs-8lNQKjUwdBUNNTR0FmLh_EVwqQ0cBSZUBSJVSlJImEChArMGlEIULNN2aK6AoM69EA-iiJcVJycVQ1y6PVtIty1GKvRkWHa2h5JNYkpmnBLTCUUsJaIKGkltRal5yBlgEIuCbWJJRDOI7YSjQQlPhrKQZGwuxBQA) Link is to verbose version of code. Explanation: ``` ≔⦃⦄η ``` Start with no grades. ``` Fθ ``` Loop over the input grades. ``` F‹⮌§ι¹⮌∨§η§ι⁰Z ``` If the reversed grade is less than the subject's reversed grade so far or `Z` if there is no grade yet, then... ``` §≔η§ι⁰§ι¹ ``` ... update the grade for that subject. ``` η ``` Output all of the grades in Python `dict` format. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 7 (6?) [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) The second `Ô` could be removed if we could output the pairs in reverse order. ``` üÎËñÔÎÔ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/M7L8dTO1A&input=W1siTGF0aW4iLCJBIl0sWyJGcmVuY2giLCJBKiJdLFsiTWF0aHMiLCJCIl0sWyJMYXRpbiIsIkEqIl0sWyJNYXRocyIsIkMiXV0tUg) ``` üÎËñÔÎÔ :Implicit input of 2D array ü :Group & sort by Î : First element Ë :Map ñ : Sort by Ô : Reverse (mutating the arrays) Î : First element : Reverse ``` --- ## 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I *think* this works but it needs more testing. ``` üÎËñÍÎ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/M7L8c3O&input=W1siTGF0aW4iLCJBIl0sWyJGcmVuY2giLCJBKiJdLFsiTWF0aHMiLCJDIl0sWyJMYXRpbiIsIkEqIl0sWyJNYXRocyIsIkIiXV0tUg) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` x=>x.sort().filter(v=>[v[0]!=x,x=v[0]][0]) ``` [Try it online!](https://tio.run/##VcvBCgIhEAbg@z6FedIw6S4u1MFTvcCKBzErQzRUxJ7e3IUOHYb5@eafl646m@Te5RDizXbBe@NzozmmgjC9O19sQpXPssqj2vFGGl@TGoM7mxaOGvngcR@LEMUmE0OO3lIfH0gguSB40cUFSAA8QUwAGCKSDea50f5nV102Oa/w9zUqCmPWvw "JavaScript (Node.js) – Try It Online") Requiring an extra empty slot after each pair, which looks not that elegant # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` x=>x.filter((v,i)=>!x.some(w=>v[0]>w[0]^[v,i--]>[w,0])) ``` [Try it online!](https://tio.run/##fc5BC8IgFAfw@z7F8vQMJ7sPhTrsVF9gYiDLyjCNTaZ9erPdgujyHvz@fx7vrhY1j5N5hsb5s849y4nxRC/GBj0BLMRgxjeJzv6hITK@iFbyWMZJlKxpJBeRtBLj3FUDg0RepS/Kkl01ejd7q6n1V@hBDIAOKhiHSI12CJO6/in9pN14W2n7z44qrLL/wNelUikPdfkN "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 53 bytes ``` x=>x.map(v=>!v.l[1]&v.l>o[v.n]||[o[v.n]=v.l],o={})&&o ``` [Try it online!](https://tio.run/##fcyxCoMwGATg3aewGSQpaaCz/IF2cGpfwJAhWGktMb@oBEF99jS1U6F0uuPjuKfxZqj6phsPDm91KCBMICfRmo56kDsvrDrqLIZE5YXTy6I@BaJpjjCvLMsw5EkJ1HHLQNI55srypEI3oK2FxTstqCopuZixcYSn5EQYT9OfUvS1qx4b7f/Z1YybnN/w9RQnmrE8vAA "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 23 bytes ``` A\* @$& O` D`.*, G`, @ ``` [Try it online!](https://tio.run/##K0otycxL/P/fMUaLy0FFjcs/gcslQU9Lh8s9QYfLgev/f59EoAIdRy0ut6LUvOQMHUcu38SSjGIdJ7iAFlTEGQA "Retina 0.8.2 – Try It Online") Takes input as a newline-separated list of subject, grade pairs. Explanation: ``` A\* @$& ``` Prefix `@` to any `A*` grades. ``` O` ``` Sort everything into lexical order. ``` D`.*, ``` Delete duplicate subjects. ``` G`, ``` Remove lines whose subjects were deleted. ``` @ ``` Remove any `@` prefixes. [Answer] # awk, 53 bytes 51 bytes of AWK, in quotes, and 9 for shell invocation… ``` awk -F, '{if(t[$1]<$2)t[$1]=$2}END{for(s in t) print s,t[s]}' ``` As noticed by user [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen), there're cases that should be fixed that way (from 51 to 53): ``` awk -F, '$2$2<=t[$1]$2$2{t[$1]=$2}END{for(s in t)print s,t[s]}' ``` If use of blank delimiters (space or tab) is allowed, we can shorten invocation with removal of `-F,` (4 bytes) ## Usage and notes …assuming that the table/list is represented by a pair `subject,grade` per line. Then, you can echo the list directly ``` ... | invocation ``` or put the list in a file ``` invocation < grades.txt ``` To [try](https://www.tutorialspoint.com/unix_terminal_online.php), first create the `grade.txt` file this way ``` cat >grade.txt <<-EOF foo,A bar,A foo,A* baz,D fiz,E baz,B EOF ``` or with `nano grade.txt` for example. ## Ungolfed/explanation For golfing purposes I've used one letter variables and removed some extra spaces usually good for readability. ``` BEGIN { # this block is processed once before main IFS="," # change Input Field Separator to comma... } # ...or done via command option `-F ','` { # this is the main block, executed for each line if (T[$1]<$2) # build a Table indexed by first field (subject) # when the second field (current grade) is greater # than the existing value (cell initially empty) T[$1]=$2 # then replace the table value with current grade } END { # this block is executed once after main processing for(S in T) # loop over the grades Table indexed by Subject print S,T[S] # for each entry, output the key (the Subject then) # and the associated value (the maximum grade then) } ``` I'm sure an AWK guru can improve it a little. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .¡н}εΣθR}н ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f79DCC3trz209t/jcjqDaC3v//4@OVvJJLMnMU9JRclSK1YlWcitKzUvOAHG1wHzfxBIQzwnMgStFkXNWio0FAA) **Explanation:** ``` .¡ } # Group the (implicit) input-list of pairs by: н # The first string of the pair (the subject) ε # Then map over each group: Σ } # Sort the list of pairs in this group by: θ # The last string of the pair (the grade) R # Reversed н # Then just keep the first pair # (after which the result is output implicitly) ``` [Answer] # [Perl 5](https://www.perl.org/) `-a`, 66 bytes ``` $f{$F[0]}.=$F[1]}{pairmap{say"$a ",(sort$b=~/./g)[0]=~s/\*/A*/r}%f ``` [Try it online!](https://tio.run/##K0gtyjH9/18lrVrFLdogtlbPFkgbxtZWFyRmFuUmFlQXJ1YqqSQqKOloFOcXlagk2dbp6@mnawLV2tYV68do6Ttq6RfVqqb9/@@TWJKZp@DI5VaUmpecoeCoxeWbWJKh4MQFldD6l19QkpmfV/xf19dUz8DQAEj7ZBaXWFmFlmTm2EIt/K@bmAcA "Perl 5 – Try It Online") [Answer] # Excel (ms365), 88 bytes [![enter image description here](https://i.stack.imgur.com/F0qRs.png)](https://i.stack.imgur.com/F0qRs.png) Formula in `C1`: ``` =LET(x,SORTBY(A1:B4,"*"&B1:B4,-1),y,TAKE(x,,1),FILTER(x,MATCH(y,y,0)=SEQUENCE(ROWS(x)))) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 72 bytes ``` tr 'ABC*' '3210' | sort -k 2,2 -n -r | sort -k 1,1 -u | tr '3210' 'ABC*' ``` [Try it online!](https://tio.run/##S0oszvj/v6RIQd3RyVlLXUHd2MjQQF2hRqE4v6hEQTdbwUjHSEE3T0G3CEnMUMdQQbcUKADSB9EA0f7/v09iSWaegqMWl1tRal5yhoIjl29iSYaCE5yvBRFw5gIA "Bash – Try It Online") --- **Original Input** ``` Latin A* French A Math B French A* Math C ``` **`tr 'ABC*' '3210'`** *Convert marks into numbers* ``` Latin 30 French 3 Math 2 French 30 Math 1 ``` **`sort -k 2,2 -n -r`** *Numeric sort using the 2nd field; reverse order* ``` French 30 French 3 Latin 30 Math 2 Math 1 ``` **`sort -k 1,1 -u`** *Sort using the 1st field only (already sorted); keep unique entries* ``` French 30 Latin 30 Math 2 ``` **`tr '3210' 'ABC*'`** *Reverse conversion* ``` French A* Latin A* Math B ``` [Answer] # [Arturo](https://arturo-lang.io), 66 bytes ``` $[a][select a'x[every? select a'y->x\0=y\0'z[>=last z\1last x\1]]] ``` [Try it](http://arturo-lang.io/playground?yUwgOX) ``` $[a][ ; a function taking an argument a select a'x[ ; select pairs in a; assign current pair to x every? <block> 'z[ ; is every element z in <block> true? select a'y->x\0=y\0 ; select pairs in a where subject = x's subject >=last z\1last x\1 ; is the last letter of z's grade >= x's? ] ; end every? ] ; end select ] ; end function ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~183~~ ~~177~~ ~~164~~ 155 bytes *-7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); -13 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil); -8 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` #define F for(j=0;j<l;j++){for(i=0;strcmp(s[i],s[j]);i++); i,j;f(s,g,l)char**s,**g;{F*g[i]>*g[j]|g[j][1]?g[i]=g[j]:0;}F i-j?:printf("%s %s\n",s[i],g[i]);}} ``` Defines a function `f` that takes an array of subjects, an array of grades, and an integer representing the length of both arrays. It prints each subject and the best grade in that subject to stdout. [Try it online!](https://tio.run/##hVCxboMwEN35ihNVJOw4Ep0qxaVR2oZ2SDtlox6oY8BWMJHtTJRvpzZEkTp1ebp79@7e3fFVzfk43h1FJbWAHKrOJCpLqXo8UbVcoj4Q0hPWGd6eE1tIRmyhGKLSl2kkiaJVYklNTog3pcHYEoxr2ue49tonj4r9BCju2SZQWUjWKR1ykCu1WZ@N1K5K4oWFhf3SMZk8ghLRYbjttt99vh3e4SHyamhLqRMEfQQQTAHby7cS3NliljHIoI/3pZN@HsS5EZo3IfooXWP/pXa8010ruY0HerOoTXkUfw22OKi3AV6maMqfA7zO5NTv/3Ndj8A8hVzPQaFshLsYDSmNhvEX "C (gcc) – Try It Online") ### Ungolfed/explanation This is ~~an awful mess~~ still pretty hacky, but looking a bit nicer than it originally did. ``` #include <stdio.h> #include <string.h> int i, j; int f(char *subjects[], char *grades[], int length) { // Loop through the arrays using index j for(j = 0; j < length; j++) { // For each j, loop through the indices i before it until reaching one with the // same subject (i.e. the first entry for that subject) for(i = 0; strcmp(subjects[i], subjects[j]); i++); // Compare the grades by comparing their first characters (smaller characters // are better); if the first characters are the same, check if the second // grade has a second character (star is better than no star) // If the grade at index j is better than the grade at index i... if(grades[i][0] > grades[j][0] || grades[j][1]) { // Change the grade at index i to point to the grade at index j instead grades[i] = grades[j]; } } // Loop through the arrays again for(j = 0; j < length; j++) { // Find the first entry for this subject for(i = 0; strcmp(subjects[i], subjects[j]); i++); // If the current entry is the first entry for this subject... if(i == j) { // Output the subject and the associated grade printf("%s %s\n", subjects[i], grades[i]); } } } ``` ]