text
stringlengths
180
608k
[Question] [ [Coming from this sandbox post](https://codegolf.meta.stackexchange.com/a/17058/59642) This is inspired from an 8th graders math test # Intro We have a cube with following corners ``` A(0, 0, 0) B(1, 0, 0) C(1, 1, 0) D(0, 1, 0) E(0, 0, 1) F(1, 0, 1) G(1, 1, 1) H(0, 1, 1) ``` This cube clearly has 8 corners, 12 edges and 6 faces. If we now cut off corner G, such that our cut plane goes exactly through the middle of each adjacent original edge, we add 2 new corners, 3 new edges and one new face. Please enjoy this hand drawn piece of art, for better clarification [![enter image description here](https://image.ibb.co/e3BBsf/cube.jpg)](https://image.ibb.co/e3BBsf/cube.jpg) # Input Given a list of corners (in this example identified by A-H), that will be cut off, compute the new number of corners, edges and faces. You make take the input in any form you like, as long as it responds to the same corners (e.g. instead of A-H you can use 1-8 or 0-7, you can assume it to be a list, csv, whatever) You can assume the list to be distinct (every corner will appear once at most), but it may be empty. The list will never contain non existing corners. # Output Output three numbers corresponding to the number of corners, edges and faces. Output as a list is explicitly allowed. Trailing whitespaces are allowed Examples ``` {} -> 8, 12, 6 (empty list) {A} -> 10, 15, 7 {A,C} -> 12, 18, 8 {A,C,F} -> 14, 21, 9 {A,B,C} -> 12, 19, 9 {A,B,C,D} -> 12, 20, 10 ``` Finally, this is codegolf, thus the shortest answer in bytes wins. Please refrain from standard loopholes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 3R×L+“©®€‘ɓŒcn/€§ċ1;`Żạ ``` A monadic Link. Input is a list of corners of the cube as Cartesian co-ordinates (cube aligned with the co-ordinate system). Output is a list of integers, `[faces, corners, edges]`. **[Try it online!](https://tio.run/##y0rNyan8/9846PB0H@1HDXMOrTy07lHTmkcNM05OPjopOU8fyDm0/Ei3oXXC0d0Pdy38//9/dLSBDhDG6oBpQyBtCKZjAQ "Jelly – Try It Online")** ### How? ``` 3R×L+“©®€‘ɓŒcn/€§ċ1;`Żạ - Link: list of lists, C e.g. [[0,1,1],[1,1,0],[1,1,1],[0,0,0]] -- this could represent "FHGA" 3R - range of 3 [1,2,3] L - length of C 4 × - multiply [4,8,12] “©®€‘ - list of code-page indices [6,8,12] + - add [10,16,24] ɓ - start a new dyadic chain, f(C,X) where X is the above result Œc - pairs of C [[[0,1,1],[1,1,0]],[[0,1,1],[1,1,1]],[[0,1,1],[0,0,0]],[[1,1,0],[1,1,1]],[[1,1,0],[0,0,0]],[[1,1,1],[0,0,0]]] /€ - reduce €ach with: n - (vectorising) not equal? [[1,0,1],[1,0,0],[0,1,1],[0,0,1],[1,1,0],[1,1,1]] § - sum each [2,1,2,1,2,3] ċ1 - count ones 2 ;` - concatenate with itself [2,2] Ż - prepend a zero [0,2,2] ạ - absolute difference with X [10,14,22] ``` --- If the corners must be "ordered" as they are in the question then this works with integers 0-7 as A-H for 25 bytes: [`3R×L+“©®€‘ɓŒc^/€ḟ2<5S;`Żạ`](https://tio.run/##ATwAw/9qZWxsef//M1LDl0wr4oCcwqnCruKCrOKAmMmTxZJjXi/igqzhuJ8yPDVTO2DFu@G6of///1swLDEsMl0 "Jelly – Try It Online") (reduces using XOR, filters out twos, then counts those less than five). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ 45 bytes ``` ≔Eθ↨℅ι²η≔⊘№⭆η⭆ηΣEι↔⁻§λξν1ηIE⟦⁶⁻⁸η⁻¹²η⟧⁺ι×⊕κLθ ``` [Try it online!](https://tio.run/##VY5NC4JAEIbv/YrF0wgbpEEEnsxLQpJQt@iw6eIurWO6q/jvt1Xz0BwGHub9mEKwrmiYsjbWWlYIGftAS8mJaQ7XrpTIFEifktB3S/jR5qc7MzXwEpKmRwM300msJqug5B/6eo6UlMQvDZnEXkNsUiz5CIqS0aWiPw8lXuCtLbnLMJAwbWb740DJ4j1O9xWCcKInJbly5DrusuYaUiw6XnM07sG3E184VkZAu/RE1u6Cvd0O6gs "Charcoal – Try It Online") Link is to verbose version of code. Uses digits `0-7` to represent the letters `ABDCEFHG` in the diagram. Outputs in the order faces, corners, edges. Explanation: ``` ≔Eθ↨℅ι²η ``` Take the ASCII code of each character and convert it to base 2. ``` ≔⊘№⭆η⭆η ``` Take the cartesian product of the list of base 2 numbers with itself. ``` ΣEι↔⁻§λξν1η ``` XOR the pairs of base 2 numbers together and sum the number of 1 bits. Count how many pairs have a sum of 1 and divide that by 2. This gives the number of coincident corners. ``` IE⟦⁶⁻⁸η⁻¹²η⟧⁺ι×⊕κLθ ``` Calculate and print the number of faces, corners and edges. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 84 bytes ``` a=>[a.map(u=>a.map(v=>j-=!!'ABCDAEFGHEFBCGHD'.match(u+v),n++,j+=2),n=j=6)|2+j,n+j,n] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i46US83sUCj1NYOwiiztcvStVVUVHd0cnZxdHVz93B1c3J293BRB0qXJGdolGqXaerkaWvrZGnbGgFZtlm2Zpo1RtpZQEEgjv2fnJ9XnJ@TqpeTn66RphEdq6lpzYUmpu6ojkNYR90Zn5SOuhtuaSf8up2gJriAlfwHAA "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~59~~ 58 bytes ``` {6+@_,|((2,3 X*4+@_)X-(@_ X~@_)∩~<<ords "% 286 >C/")} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kzbIV6nRkPDSMdYIULLBMjTjNDVcIhXiKgDMh91rKyzsckvSilWUJJXVTCyMOPiE7Fz1lfSrP1fnFipkKYRHatpzQVlGiCzdcxQeTrGKHxDDL4RWOQ/AA "Perl 6 – Try It Online") Uses the numbers `0` to `7` to represent the corners. I probably should have matched them up to the same order as in the question... oops? Outputs a list in the order `faces, corners, edges`. ]
[Question] [ # Background [Puzzlang](https://esolangs.org/wiki/Puzzlang) is a derivative of Brainfuck, where the symbol `X` executes a BF command based on three characters on top of it, and anything else does nothing. The following is the translation table for Puzzlang, where `X` is the literal X and `.` stands for anything else: ``` > < + - . , [ ] ..X X.. XXX ... .X. X.X XX. .XX X X X X X X X X ``` Also, the entire source code wraps around both horizontally and vertically at the translation step. For example, the following code is an infinite loop: ``` XX X ``` since you can view the code like this (the dots are where the wrapped X's would go) ``` ... .. .XX X. ``` and matching with the translation table gives `+[]` for the three X's in order. **Nightmare Puzzlang** is an evil twin of the regular Puzzlang. In Nightmare Puzzlang, each X translates into a byte based on its eight neighbors. Any non-X characters translate into nothing. The wrapping rule is the same. Since there is no "official" specification, let's assume that the following pattern (where X denotes the one to translate) ``` abc dXe fgh ``` translates to `abcdefgh` in binary (X is one, non-X is zero). Then the following code ``` XX... X..X. X..XX X..XX X.XX. ``` translates to `4a b4 66 03 56 4b bf d2 6e fd c3 2c 70` in hex, or `J´fVK¿ÒnýÃ,p` as a string. Note that the resulting string will very likely have ASCII unprintables. # Task Translate the given Nightmare Puzzlang code into a string. # Input & output For input, you can take 2D array of chars, list of strings, or a single string whose lines are delimited by newlines. You can assume that the input is rectangular in shape, i.e. row lengths are equal. For output, you can give a single string, a list of chars, or a list of charcodes. # Test Cases Note that the result must remain the same when any of the dots are replaced with anything else other than the capital X. ``` X (1 row, 1 column) String: ÿ Charcode: [255] X. (1 row, 2 columns) String: B Charcode: [66] X . (2 rows, 1 column) String:  Charcode: [24] X. .X String: ¥¥ Charcode: [165, 165] X.X .X. String: 1Œ¥ Charcode: [49, 140, 165] X.X XX. X.X String: Ómεv« Charcode: [211, 109, 206, 181, 118, 171] X.XX.XXX..XXXX. String: BkÖkÿÖkÿÿÖ Charcode: [66, 107, 214, 107, 255, 214, 107, 255, 255, 214] X.XX.XXX.XXXXX. XX.X..XX....X.. String: c­R){Ö9Z”JµÆïÖç Charcode: [99, 173, 82, 41, 123, 214, 8, 24, 57, 90, 148, 74, 181, 198, 239, 214, 231] X X X . . X . X X . X String: ÿÿøø Charcode: [255, 255, 248, 24, 31, 248, 31] XX X. XX .X .X XX .. XX XX .. .X String: º]ç]ºâG¸Xøø Charcode: [186, 93, 231, 93, 186, 226, 71, 184, 88, 31, 31, 248, 248, 7] XX XXX XX XX X X X X X X X X X X X XX X X X X X X XX XXX XX XX XXX XXX X XX X X X X X X X X X X XX X X X X X X XXX XXX XX X (11 rows, 13 columns, no extra padding, result has two newlines) zôª}òªuJ½æbÂb‚cRBBBBJ½ÇCFCDcXH¸PH°H¸   æbÂBcRBBBJ½ÃFCFCbO¾UO¾UN”C Charcode: [122, 244, 170, 125, 242, 170, 117, 74, 189, 230, 98, 194, 98, 130, 99, 82, 66, 66, 66, 66, 74, 189, 199, 67, 70, 67, 68, 99, 88, 144, 72, 184, 80, 72, 176, 72, 184, 26, 28, 16, 10, 29, 18, 2, 10, 29, 230, 98, 194, 66, 99, 82, 2, 66, 66, 66, 74, 189, 195, 70, 67, 70, 67, 98, 79, 190, 85, 79, 190, 85, 78, 148, 67] ``` # Rules Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest submission in bytes wins. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 57 bytes ``` ¯1~⍨,1↓∘⍉∘⌽⍣4⊢{2 2⌷⍵:2⊥(~¯9↑5↑1)/,⍵⋄¯1}⌺3 3⊢⍉∘(¯1∘↑⍪⊢⍪1∘↑)⍣2⊢'X'=⎕ ``` [Try it online!](https://tio.run/##bU9Na8JAEL37K/YWBbtlV3Noof9jroLoRajXIuYkMbXZghShZ4tQcvGiCAUv/pT5I3F2dvNJN5nZee/NvExG89nD@G00e53mmKwn@e2oIjS/fYXxFybfaN5tTq9ofoa42S@00Jhe0JyfNW4O3eh2fMJ4G1Ko3mOfePxYkccS07@BGNCEc@gSZ43iLZqM2czjHjmT1T6A4AU/d3aLfNJRQqE5EdexteZaWqALQQSMycEqhKCCrIJsEsBtIL2nCp0p2BekTY0JR4OjeZqbJB1K3Ggy3qMI6QNqd1UXzsw6R7e1Tw6WQgVrPwYCOIRwPXSXTwv/q7fmRf2w7hsqfz9c@EOJoYUb8/y9Ow "APL (Dyalog Unicode) – Try It Online") A full program which takes a binary matrix through STDIN, returns an array of codepoints. ## Explanation `x¯1~⍨,1↓∘⍉∘⌽⍣4⊢{2 2⌷⍵:2⊥(~¯9↑5↑1)/,⍵⋄¯1}⌺3 3⊢⍉∘(¯1∘↑⍪⊢⍪1∘↑)⍣2⊢'X'=⎕` `⎕` take input `'X'=` boolean matrix where 'X's are 1s `⍉∘(...)⍣2⊢` do the following twice: `¯1∘↑⍪⊢⍪1∘↑` pad each row with its wraparound on both sides `⍉∘` and transpose `{...}⌺3 3⊢` then, do the following for each 3x3 window: `2 2⌷⍵:` if the middle element is 1: `2⊥(~¯9↑5↑1)/,⍵` decode the rest of the window as binary `⋄¯1` Otherwise, return ¯1. `⍣4⊢` Do the following 4 times: `1↓∘⍉∘⌽` rotate 90°, drop first row (remove the border cells) `,` flatten into a simple array `¯1~⍨` remove all ¯1s [Answer] # JavaScript (ES6), 159 bytes Takes input as a 2D array of characters. Returns an array of character codes. ``` f=M=>M.map((r,y)=>r.map((v,x)=>v>f&&o.push([...'22211000'].map((k,j)=>s|=(M[(y+h+~-k)%h][(x+w+~-'21020'[j%5])%w]>f)<<j,h=M.length,w=M[s=0].length)|s)),o=[])&&o ``` [Try it online!](https://tio.run/##jVHNjoMgGLz7FFwsEClBk70V38A7CeFgulrXumq0q23S7Ku7/m23dEtVxHzzMc4MkIZNWO@rj/K0zYv3qOtiHnA/oJ9hiVBFLpj71QQacu5B48ebTUHLrzpBklIKPc9zXcYYVBPtSNKeVl85CiS6OInzvT1iO1ESnZ22B9BzmcegTO03he1W@THe7VKS8IBmUX44JaTlgaw5UzPG1xpjUnCpcO/c7Yu8LrKIZsUBxUhaAIwxBFSWwtgyLdOFdajIb02Xpf64i76a8mIMjS40K7HCa3gFHT4rnCaymMn3rqNEXw/F@nMz1dRQixX9F5yXsTQNfXcPt/cc6DSjgJm2eFkCiHECoCv2@DYM/VV8gz69fzT@/MP/PLP4Yx5x6wtDHzzTn3IOR9P9AA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = M => // f = main function taking the input matrix // it is named because we are later using '>f' M.map((r, y) => // for each row r[] at position y in M[]: r.map((v, x) => // for each value v at position x in r[]: v > f && // ignore this cell if v is not equal to 'X' o.push( // otherwise, push a new value in o[]: [...'22211000'] // iterate over dy values (+1) .map((k, j) => // for each value k at position j in this array: s |= ( // update s: M[(y + h + // compute the row ~-k) // by adding dy = k - 1 % h] // and applying a modulo h [(x + w + // compute the column ~-'21020'[j % 5]) // by adding dx = [2,1,0,2,0,2,1,0][j] - 1 % w] // and applying a modulo w > f // test whether this cell is a 'X' ) << j, // and set the corresponding bit in s if it is h = M.length, // initialize h = matrix height w = M[s = 0].length // initialize w = matrix width and s = bitmask ) | s // end of map() over dy; yield s ) // end of push() ), // end of map over r[] o = [] // initialize o = output array ) && o // end of map over M[]; return o ``` [Answer] # Python 3, ~~166~~ ~~162~~ 161 bytes ``` lambda p,r=range:[chr(int(''.join(str(+([n*2for n in p+p][y+i//3-1][x+i%3-1]=='X'))for i in r(9)if i-4),2))for y in r(len(p))for x in r(len(p[0]))if'X'==p[y][x]] ``` Takes as input a list of strings and returns a character array. [Try It Online!](https://tio.run/##hVDRboIwFH33K25YlraCuOleZtKnfcJemiAPTIp20dIUjBLjt7NCGVbTbAWaw7nnnN5e1dS7Ui7bgq7bfXb4yjNQkaY6k1u@SjY7jYWsMULxdykkrmqNQ5zI6aIoNUgQElSo0qQJxXy@nL2myTkUzx2gFDFESCcTnUzjdyIKELM3Ei0s31h@zyVWljk7TPKSEuMwKZSqpDHJadrmvICaVzWe7oXkFVlNwCylux4tFUHFFUVriSLgMqcIEUdTIMCXLt7ar6DLk7HcqO7UK2zK/fEgKzJ4M1mduAYKxeCDJ9C8PmpZQQabXaYh0zpr7g76rA3YruASBHZ2NoVcHxr6MPZNmXOjTEqdY0lgnK21pFdzGzKZ9BcPWEB@UXyDQdSHQhC75ZF0TWwtAwjHimu4xTDHze7t3cvibrv3Wp5Z3snptbFZZvM07EOxB7E/OX91PM0Rur25A/JAV@C1@QXuuBiw/gNwbeZvfLzsv1pvLrjL0Q7ixx6G0Pse2MgyL@vJ7Tsj7Q8) Ungolfed (sorta): ``` def f(p): chars = [] for y in range(len(p)): for x in range(len(p[0])): if p[y][x] != 'X': continue bits = [] for i in range(9): if i == 4: continue bit_x = x + i%3 - 1 bit_y = y + i//3 - 1 char_at_cell = [n*2for n in p+p][bit_y][bit_x] bit = str(+(char_at_cell=='X')) bits.append(bit) char_code = int(''.join(bits), 2) chars.append(chr(char_code)) return chars ``` Edit: made shorter by 5 bytes thanks to Jo King and Jonathan Frech [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` =”Xµ-r1p`ẸƇ+ⱮŒṪœịµḄ ``` A monadic Link that accepts a list of the lines and yields a list of code-points. **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//PeKAnVjCtS1yMXBg4bq4xocr4rGuxZLhuarFk@G7i8K14biE////WydYLlgnCiwnLlguJwpd "Jelly – Try It Online")** ### How? ``` =”Xµ-r1p`ẸƇ+ⱮŒṪœịµḄ - Link: lines ”X - character = 'X' = - equals? -> binary matrix from lines with X:1 and .:0 µ µ - monadic chain - f(v=that): - - -1 1 - 1 r - inclusive range = [-1, 0, 1] ` - use as both arguments of: p - Cartesian product = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]] Ƈ - keep those for which: Ẹ - any? = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]] ŒṪ - multidimensional truthy indices (v) Ɱ - map across these with: + - add œị - index into (v) Ḅ - convert from binary ``` ]
[Question] [ If you throw an ASCII egg in a given direction, you end up with an **ASCII splat of size *n***. It "starts" with one `o` (the yolk), and continues in a given direction with "lines" consisting of 2 up to *n* `*`'s. The `*`'s are separated by one "space", and the `o` and all the "lines" of `*`'s are separated by "lines" of "space". The direction of the splat can be any one of eight directions from `o`, for example: ``` 1 2 3 4 o 5 6 7 8 ``` Here are examples of ASCII splats of size 4 in directions `5`, `2` and `3` respectively. On the left is the actual ASCII splat, and on the right is the same splat but with the "lines" of "space" replaced with actual "lines" (i.e. `-` or `\` or `|` depending on the direction) just to clarify what is meant by a "line" of space. ``` Size 4, direction 5 * | | |* * | |*| * * |*| |* o * o| |*| * * |*| |* * | |*| * | | |* Size 4, direction 2 * * * * * * * * ------- * * * * * * ------- * * * * ------- o o Size 4, direction 3 * * \ * * *\* \ \ * * * *\*\* \ \ \ o * * * o\*\*\* ``` ## Challenge Given *n ≥ 1* and one of the 8 possible directions, write a function or program that outputs the ASCII splat of size *n* in the given direction. ## Input and output Any consistent, reasonable input format is allowed. You don't need to map directions to the integers 1 to 8 in the same way I did - if some other way of specifying the direction is easier, go ahead. But say what you did if it isn't clear. The output will consist of `o`, `*`, spaces (U+0020) and newlines (U+000A) that produce the ASCII splat. Leading, trailing, otherwise extra whitespace is permitted on any line. ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard rules apply. ### More examples ``` Size 1, any direction o Size 3, direction 6 * * o * * * Size 5, direction 7 o * * * * * * * * * * * * * * ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 18 bytes ``` ↘EN×*⊕ιM↗oUE¬﹪η²⟲η ``` [Try it online!](https://tio.run/##JYyxDoIwFEV3v6Lp9DB1MUyw6sBQYohOxqGWF9uk9JH6QP@@Nninc4ZzrTPJkgk5X5KPDM2JPnHwL8dKaDNDF@eF@2V6YoJKiauf8A1yL5Xook04YWQcwVdl7U7TitDc5q0v/r@UJAufv4xxhJ4YNI1LIHBKHLdsIDaM4Ko253utRP3IhzX8AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ↘EN×*⊕ι ``` Draw a diagonal triangle of splats. ``` M↗o ``` Place the egg. ``` UE¬﹪η² ``` For even rotations, expand the splat horizontally to match the output requirement. This requirement doesn't match Charcoal's usual expectations. [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88LygzPaNER8E3sUDDM6@gtMSvNDcptUhDU0chJDM3tVhDSUtJR8EzL7koNTc1ryQ1RSNTEwisuXzzy1I1rEILwPqBfIiRSvlKQHZQfkliSSqqeZrW//@bcJn81y3LAQA "Charcoal – Try It Online") (verbose) for how it looks without. ``` ⟲η ``` Rotate the splat as required, using the following code for directions: ``` 321 4o0 567 ``` This ~~37~~ 31-byte version avoids extraneous whitespace by only rotating in right angles: ``` ¿﹪η²G↘←θ*«↘Eθ×*⊕ι↗»oUE¹﹪η²⟲⊗÷η² ``` [Try it online!](https://tio.run/##VY49C8IwFEVn8ytCpxeJg@LUrnUoWBDRSRxi@2wDaV5tY1XE3x7jx6BvuXA59/CKWnUFKeO9PnLIqTwbglrymRBstCJzq8hCnNLFrnVVO8njJR5DnCSPxpFIGJoe@T2wnbbuj8xVCwHb6AZ7CLDkmS06bNA6LEGLcAkb5TQgxNv2PQrFg31MEb3si6tDW8I02H5fS9ianHIIKZ0PJtgy61I96BK/gEi8380ln@/9ZDBP "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` ”*ẋK¥ⱮmṠ©}”oḷ""LḶ⁶ẋƲ;"ṚƊ®¡z⁶K€ZU$A}¡Y ``` [Try it online!](https://tio.run/##AVEArv9qZWxsef//4oCdKuG6i0vCpeKxrm3huaDCqX3igJ1v4bi3IiJM4bi24oG24bqLxrI7IuG5msaKwq7CoXrigbZL4oKsWlUkQX3CoVn///81/zM "Jelly – Try It Online") Directions: \$\left[\begin{array}c1&2&3\\4&\circ&5\\6&7&8\end{array}\right]\rightarrow\left[\begin{array}c-2&1&-3\\4&\circ&2\\-1&3&-4\end{array}\right]\$ [Answer] # [Canvas](https://github.com/dzaima/Canvas), 25 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` H*×]on╶2%?!/ *] */}⤢ *⁷⇵⟳ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4KiVENyV1RkYzRG8ldUZGNEUldTI1NzYldUZGMTIldUZGMDUldUZGMUYldUZGMDEldUZGMEYlMjAldUZGMEEldUZGM0QlMjAldUZGMEEldUZGMEYldUZGNUQldTI5MjIlMjAldUZGMEEldTIwNzcldTIxRjUldTI3RjM_,i=MTAlMEE4,v=8) The directions are as follows: ``` 7 6 1 4 ∘ 8 5 2 3 ``` [Answer] # [Python 2](https://docs.python.org/2/), 185 bytes ``` lambda n,d:'\n'.join(g([(d/4*(n+~j)*' '+('*o'[[j>n-2,j<1][d/4]]+' *'*j)*i).ljust(2*n-1)for j in range(n)for i in(0,1)][1:],d%4)) g=lambda a,n:n and g(map(''.join,zip(*a))[::-1],n-1)or a ``` [Try it online!](https://tio.run/##NY/BbsIwEETP5St8qXbX2dA6yqGyoD9ifDByE2zBJgrpoT30190A4fo0ejMz/synQZrS7Q/lHC7HGJRwtHAQ2OYhCfboML61GqX6y6RBQYWgB3Auf0rdcN4Z75aA9xUoDXrJJNqe8/d1xkZLbagbJpVVEjUF6b9Q7iAtAN/ZkHfGeo6vLdGm368TAosVFSSqHi9hRHiM4d80og5EztraeL7ZF1coT@Na8UF28zJOSWaV@HaFO2w50QpL@Qc "Python 2 – Try It Online") The numbering is from 0 to 7, as follows: ``` 1 6 0 7 o 5 2 4 3 ``` Notes: Most of the work is to generate the basic patterns for (in my numbering system) `0` and `4`. Then the function `g` rotates the array `a` 90 degrees `d%4` times via recursion to generate the other results. ]
[Question] [ # Background In the [game of Nim](https://en.wikipedia.org/wiki/Nim), players alternate removing "stones" from "piles": on each turn, a player must remove between one and all stones from a *single* pile. The object of Nim is to take the last stone or, in the misere variant, to force your opponent to do so -- however, it turns out the strategies are nearly identical. Nim makes a fun bar game. You can use matchsticks or coins for the "stones," and the "piles" are typically arranged in a line. Below is a classic setup with piles of 1, 3, 5, and 7: [![nim with matchsticks](https://i.stack.imgur.com/O2WOw.png)](https://i.stack.imgur.com/O2WOw.png) If you've never played Nim before, you might try your hand at it before attempting this challenge. Here's a [version called "Pearls Before Swine"](https://www.albinoblacksheep.com/games/pearl2). ## Strategy Optimal strategy in Nim is tricky enough that most lay people lose consistently to an expert, but simple to describe with [binary arithmetic](https://en.wikipedia.org/wiki/Nim#Mathematical_theory). Doing mental binary XOR operations, however, is tough, so luckily there is an equivalent way to visualize the correct strategy which is easier to implement in real time, even when drunk. There are only three steps: 1. Mentally group the "stones" in each line into subgroups whose sizes are powers of 2, starting with the largest possible size: 8, 4, 2, and 1 are sufficient for most games. 2. Try to match each group with a twin in another line, so that every group has a pair. 3. If this isn't possible, remove unpaired "stones" from a single line (this will always be possible - see the Wikipedia link for why) so that step 2. becomes possible. Or, said another way: "Remove some stone(s) from a single pile such that if you then group the piles into powers of 2 all groups may be paired with a group in some other pile." With the caveat that you cannot break up larger powers of 2 into smaller ones -- eg, you cannot group a line with 8 stones into two groups of 4. For example here's how you'd visualize the board above: [![balanced matchsticks](https://i.stack.imgur.com/DRLsJ.png)](https://i.stack.imgur.com/DRLsJ.png) This board is perfectly balanced, so you'd want your opponent to move first. ## The Challenge Given a list of positive integers representing the size of Nim "piles", return a plain text visualization of the Nim board as seen by an expert. What constitutes a valid visualization is best explained by example, but you must: 1. Assign a distinct character to each "power-of-2 subgroup" and its pair (unpaired subgroups do not qualify), and use that character to represent the "stones" in both subgroup and pair. 2. Represent any unpaired "stones" (ie, the ones an expert would remove when playing normal -- not misere -- Nim) using a hyphen: `-`. There will be multiple ways to achieve a valid visualization, and all are valid. Let's work through some test cases: ## Test Cases ### Input: 1, 3, 5, 7 Possible Output 1: ``` A BBA CCCCD CCCCBBD ``` You may optionally include spaces between the characters, as well as blank lines between the rows: Possible Output 2: ``` A B B A C C C C D C C C C B B D ``` ### Input: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 The order and choice of characters can be whatever you like: Possible Output 1: ``` G E E E E G C C C C C C C C F B B B B D D B B B B D D F H H I - - - - - A A A A A A A A I A A A A A A A A H H ``` Unicode symbols are ok too: Possible Output 2: ``` ◎ ◈ ◈ ◈ ◈ ◎ △ △ △ △ △ △ △ △ ◉ ◐ ◐ ◐ ◐ ◀ ◀ ◐ ◐ ◐ ◐ ◀ ◀ ◉ ▽ ▽ ◒ - - - - - ▥ ▥ ▥ ▥ ▥ ▥ ▥ ▥ ◒ ▥ ▥ ▥ ▥ ▥ ▥ ▥ ▥ ▽ ▽ ``` ### Input: 7 From the rules it follows that any "single pile" must be completely removed. Possible Output 1: ``` ------- ``` Possible Output 2: ``` - - - - - - - ``` ### Input: 5, 5 Possible Output: ``` A A A A B A A A A B ``` ## Additional Rules * This is code golf with standard rules. Shortest code wins. * Input is flexible, and may be taken in whatever list-ish form is convenient to you. * Output is flexible too, as the above examples illustrate. Most reasonable variations will be allowed. Ask if you're unsure about something. [Answer] # [Python 2](https://docs.python.org/2/), ~~150~~ ~~196~~ 206 bytes ``` def f(p): c=48;s=[l*'.'for l in p];m=2**len(bin(l)) while m: if sum(m*'.'in l for l in s)>1: for i,l in enumerate(s):s[i]=l.replace('.'*m,chr(c)*m,`s`.count(chr(c)*m)<2) c+=1 else:m/=2 return s ``` [Try it online!](https://tio.run/##VU/RboQgEHznK/btwBJbqbZXr/RHjMld6XqSABrQNP16i2hN@sTszOwsM/5M/eDEsnxhBx0dWU1AyfJ8CbIx2Sk/dYMHA9rB2F6sFFlm0NFP7ahhjMB3rw2CjUugOwizpXZdinYDx2ZgH8XqSIzmiUM3W/S3CWlgdWh0K03ucTQ3hTQGZJar3lPFIriGa66G2U30j2Lvgq156kEW8UUTsLaPUhDwOM0@Xkx17lud4x@p3ui1m8AQSICQO20KDs8cKg6vLdtnkagysS9R4HDm8MaheNosuzOq1YbKf3IRR7HGVkfiHhfn5Rc "Python 2 – Try It Online") [Answer] # Ruby, ~~169~~ ~~164~~ 148 bytes ``` ->a{s=eval a*?^ c=?@ m={} a.map{|x|z=x-(x^s);[$><<?-*z,x-=z,s=0]if z>0 n=1 eval'x&1>0?[$><<(m[n]||c.next!)*n,m[n]=!m[n]&&c*1]:0;n*=2;x/=2;'*x puts}} ``` [Try it online!](https://tio.run/##bY3vasJAEMS/31OsUKIeG71LTW2Nm/ge4QLXYKDQHGJUzvx59jSXVrDil4H9zczO8fx57Qug3o91U9H@or9B8yRjOSU7VlLTMb0o9aFpbVuT9Wc2q@ZR@hJvt4nPa7Q@1ViRUF8F1LFghiRzT6bWk7FIxuCsTI1q23xh9vY0mXODDtDEqeflXKqNiAynILLLQabcssP5VHVdX6SpRHhFCBHWSkXgOPulwWisRu9tsBHeET4QpLgP/msNyfD@Xj0pyAEGbjR82Psbu9H@Bw) First, we initialize * the nim-sum with `s=eval a*?^` (which is shorter than `a.reduce:^`) * the variable `c`, which stores the first unused unique character * a map `m` that maps power-of-two lengths to characters used to represent them Then, looping over each pile, we run the following: ``` z=x-(x^s);[$><<?-*z,x-=z,s=0]if z>0 ``` Per [Wikipedia's strategy](https://en.wikipedia.org/wiki/Nim#Mathematical_theory), if *nim-sum XOR pile* is less than *pile*, we should remove stones from that pile such that its length becomes *nim-sum XOR pile*. By storing the difference in the variable `z`, we can test to see whether this difference is positive, and if so 1.) print that many dashes, 2.) subtract it from the pile, and 3.) set the nim-sum variable to zero to prevent further stone removal. ``` n=1 eval'[...];n*=2;x/=2;'*x ``` Now we "loop" over each bit and keep track of their values by repeatedly dividing `x` by `2` and multiplying the accumulator `n` by `2`. The loop is actually a string evaluated `x` times, which is far greater than the `log2(x)` times it's necessary, but no harm is done (aside from inefficiency). For each bit, we run the following if the bit is 1 (`x&1>0`): ``` $><<(m[n]||c.next!)*n ``` Print a character `n` times. If we already printed an unpaired group of this many stones, use that character; otherwise, use the next unused character (advancing `c` in-place due to the `!`). ``` m[n]=!m[n]&&c*1 ``` If `m[n]` existed (i.e. we just completed a pair), then `m[n]` is reset. Otherwise, we just started a new pair, so set `m[n]` to the character we used (`*1` is a short way to make a copy of `c`). [Answer] ## JavaScript (ES6), 215 bytes ``` f= (a,c=0,x=eval(a.join`^`),i=a.findIndex(e=>(e^x)<e),b=a.map(_=>``),g=e=>(d=e&-e)&&a.map((e,i)=>e&d&&(a[i]-=d,b[i]=(c++>>1).toString(36).repeat(d)+b[i]))&&g(e-d))=>g(eval(a.join`|`),b[i]='-'.repeat(a[i]-(a[i]^=x)))||b ``` ``` <textarea oninput=o.textContent=/\d/.test(this.value)?f(this.value.match(/\d+/g)).join`\n`:``></textarea><pre id=o> ``` Only visualises up to 36 different characters. I'm relieved this works for `1, 3, 4, 5`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 454 bytes *still golfing* ``` import StdEnv,Text,Data.List $p=join"\n"[{#toChar c+'-'\\c<-e}\\e<-[take i(e++[0,0..])\\e<-r[[~c\\c<-reverse e,_<-[1..c]]\\e<-hd[q\\q<-foldr(\h t=[[a:b]\\a<-h,b<-t])[[]][[c\\c<-subsequences(takeWhile((>=)k)(iterate((*)2)1))|sum c<=k]\\k<-p]|sum[1\\a<-q&b<-p|sum a<>b]<2&&foldr(bitxor)0(flatten q)==0]]1&i<-p]] r[]_=[] r[h:t]n|all((<)0)h=[h:r t n] #[m:_]=removeDup[e\\e<-h|e<0] #(a,[x:b])=span(all((<>)m))t =r([[if(e==m)n e\\e<-k]\\k<-[h:a]++[x]]++b)(n+1) ``` [Try it online!](https://tio.run/##RVDBjpswEL3zFdZmlbUbQLCrVaUI59L0UGkPlbZSD4MVGWcobsCAMVGqZvvppQ5U2otHM@/5vXmjapRmatrjWCNppDaTbrrWOvLqjp/NOfyGFxfupZPxix5ccN/xn602d7m5g98r136qpCVq8xA95LnKInzLc8wicPKERFPcbCAJkzgWbJ5bgD9qJlo8ox2QYHjw9DSOlRAzpTpCn@d9FpVtfbQ0r4jjAHJbeFh6OCyyyAkGIATAojWMxYD9iEbhQG/O3ytdI6U7zk6MaodWOt9@YI8sZew6jA1RGT95wVMWdeI2gHRW79devZsZMtsVIntcr5c9Cu0urWUJLWvpHBrSM84TIdK1vmmIwII4cLjVauuEucq6pjRjCau4n1jiiBHBCprtQXCLTXvG/dgBLpmvmCUepTKEi0/K@NBJQxeJHWsYcwG3FECXFDlvmCHLx/8ZvIEU/tQX4d@CUbNJ2fTqpHXBinT@FgPhBNKQPIXkOSQfvRUpR6Ocbo1H7gP@3s706a/yOX8MU/TlZdr/MrLRamm@@vhla5spqqbnJPG1@Ac "Clean – Try It Online") Defines the function `$ :: [Int] -> String`, taking the pile sizes and returning a string where `-` denote stones to be removed, and groups are represented by ASCII characters ascending from `-`. If enough groups are needed the characters will wrap back around eventually, and due to the `foldr` it requires more than a gigabyte of memory to run the second test-case. Indented version of the giant comprehension: ``` $p=join"\n"[ {# toChar c+'-' \\c<-j } \\j<-[ take i(e++[0,0..]) \\e<-r[ [ ~c \\c<-reverse e ,_<-[1..c] ] \\e<-hd[ q \\q<-foldr(\h t=[ [a:b] \\a<-h ,b<-t ])[[]][ [ c \\c<-subsequences(takeWhile((>=)k)(iterate((*)2)1)) |sum c<=k ] \\k<-p ] |sum[ 1 \\a<-q &b<-p |sum a<>b ]<2&&foldr(bitxor)0(flatten q)==0 ] ]1 &i<-p ] ] ``` ]
[Question] [ I am a robot. I bought [this keyboard](https://images-na.ssl-images-amazon.com/images/I/41P-kEz89OL._SX355_.jpg) because of its easy rectangular layout: ``` ~` !1 @2 #3 $4 %5 ^6 &7 *8 (9 )0 _- += tab Qq Ww Ee Rr Tt Yy Uu Ii Oo Pp {[ }] \| Aa Ss Dd Ff Gg Hh Jj Kk Ll :; "' [-enter-] Zz Xx Cc Vv Bb Nn Mm <, >. ?/ [========= space =========] ``` To print human text, I need to convert it to commands that my manipulators can interpret. My left manipulator hovers over the `Shift` key. My right manipulator, at the beginning, hovers over the `~` key. The commands that my manipulators understand are: ``` S : press the shift key s : release the shift key L : move the right manipulator left by 1 R : move the right manipulator right by 1 U : move the right manipulator up by 1 D : move the right manipulator down by 1 P : press the key under the right manipulator p : release the key by the right manipulator ``` Write code to convert any ASCII message to a list of commands. The input can contain any number of the 95 printable ASCII characters; possibly also TAB and newline characters. The output should be the list of the commands to the manipulators. So, for example, to type `Hello World!`, the commands are ``` SRRRRRRDDPp sLLLUPp RRRRRRDPp Pp UPp LLLLDDDPp SLLLUUUPp sRRRRRRRPp LLLLLPp RRRRRDPp LLLLLLPp SLLUUPp ``` I reset the manipulators to initial state before printing each message. There are some mechanical hazards that should be avoided by proper programming: 1. No moving (`LRUD`) allowed when printing (`P`) is engaged 2. No jamming of manipulators: when a manipulator is engaged (`S` or `P`), the next command for this manipulator should be disengaging (`s` or `p`), and vice-versa 3. No unnecessary shifting: between each two shift (`s`, `S`) commands, there should be a `P` command So, to print `~~`, commands `SPpPp` are valid, while `SPpsSPp` are not 4. No moving out of bounds: no movement command should try to move the right manipulator more than 13 spaces to the right or 4 to the bottom of the initial position (or any spot to the top or left) Additional notes: * Pressing a disabled key (command sequence like `DDPp`) results in no keys pressed and is allowed. * Pressing `Shift`+`Tab` has no effect, but `Shift`+`Space` and `Shift`+`Enter` have the same effect as without `Shift`. * Pressing on any spot on the space bar and the `Enter` key has the same effect. * Whitespace keys in output have no meaning, but can be used to format it in a beautiful way. [Answer] # [Python 2](https://docs.python.org/2/), ~~338~~ ~~337~~ ~~335~~ ~~331~~ 325 bytes ``` x=y=s=0 for c in input():p='`1234567890-=` qwertyuiop[]|`asdfghjkl;\'\n```zxcvbnm,./``````` ~!@#$%^&*()_+~~QWERTYUIOP{}\\~ASDFGHJKL:"\n~~~ZXCVBNM<>?~~~~~~~ '.find(c);S=[p>61,s][c in' \n'];p%=62;Y=p/14;X=[max(x,12),min(max(x,5),10),p%14]['\n '.find(c)];print'sS'[S]*(s^S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp';x,y,s=X,Y,S ``` [Try it online!](https://tio.run/##RY5bV4JAAISf61egZQu6qJBaSUs3Kysrk0xowfCaFC4bYEGX/etEh4fmzMt858ycoXG48IicJBGKUYCq63PP5yacQ1LTVcgLTYqALcnbtXpjZ3evKiJ77e1j5ofxyvEotr7tUTCdPy9eXl3FBCaxbfszmryPyRKWK3YmjuUONzYLw60iLzyVGLsbnPbujf7FbffrxzTZkdY6O29fXnWaeZMwxh71k4fjm@t99YBl4kB57pApPxEUDWGqNiQYWPjvJOBMAiyFFlBDVgxEK1JN0RFejiI@gpIswKVD@CzVBShVBUgLUs3C6dH/0bTvOyQEgQawZhX5YKgJJdDpAayrkVUcjQNeF6MU9VsAG2qcIUOMU9SlQIlgDAOkQwNqSZJvz1zX4wae705z@V8 "Python 2 – Try It Online") --- Moves directly from each character to the next. Explanation: * `S=[c in K,s][c in' \n']`, checks if the next character should be Upper- or lowercase. If `c` is a space or newline, the case remains the same. * `X=[max(x,12),min(max(x,5),10),p%15]['\n '.find(c)]`. If `c` is a space or newline, the closest x-coordinate to the current is chosen(as the keys span multiple columns) * `print'sS'[S]*(s!=S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp'`, prints the case switch, the number of x-coordinate moves, the number of y-coordinate moves, and finally `Pp`, for each character --- Shorter version, if the shortest path is not required: # [Python 2](https://docs.python.org/2/), ~~294~~ ~~293~~ ~~291~~ ~~287~~ 281 bytes ``` x=y=s=0 for c in input():p='`1234567890-=` qwertyuiop[]|`asdfghjkl;\'\n```zxcvbnm,./``````` ~!@#$%^&*()_+~~QWERTYUIOP{}\\~ASDFGHJKL:"\n~~~ZXCVBNM<>?~~~~~~~ '.find(c);S=[p>61,s][c in' \n'];p%=62;X,Y=p%14,p/14;print'sS'[S]*(s^S)+'LR'[X>x]*abs(X-x)+'UD'[Y>y]*abs(Y-y)+'Pp';x,y,s=X,Y,S ``` [Try it online!](https://tio.run/##JY/bVoJAAEWf6yvIogEdUcispKGb3a1MsiAGG8VMugwTgwVd5teJlnudp/1w1jksS6YRNfI8RRniqL44iWIpkEJahM0SRW0xBIhurDXWmxubW/UqIgvvn49xks3CiHn@Dxny8eRp@vzyamKAKSHkKw0@RvQNajUyRxJLu8sr8mC1rKgPFSGu7w57N27/9Kr7/Yux2LPbR8cnZ@edVglTIcS9c3C7f3mxbe2IORLQJiEdK4Fq2shjVlOH3Pf@RwIJU@CbTEZNw3Sgi5isNyCr6Q2TxSFNALeBZ/tlhQ9stQI6PeA5VuqXhyOuONW0UP028Fwrmyu3mhWqy4CZwgxyVDRCO89LmmRhihNRHC/9AQ "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 263 bytes Takes input as an array of characters. ``` s=>s.map(c=>(y=i-(i=(j=`\`~1!2@3#4$5%6^7&8*9(0)-_=+00\t0qQwWeErRtTyYuUiIoOpP[{]}|\\00aAsSdDfFgGhHjJkKlL;:'" ${1e6}zZxXcCvVbBnNmM,<.>/?${1e13} `.indexOf(c))>>1),g=k=>'LRUD'[n=k?y/14:y%14,k^=n<0].repeat(n<0?-n:n))()+g(2)+['sS'[j-s&c!=' '&c!=` `?s^=1:2]]+'Pp',i=s=0) ``` [Try it online!](https://tio.run/##FcnbVoJAAEDRd79CS52ZgBHUrMiBLlZWVqaZFWAQt7gIxJBJZr9O@XT2Wsc3FgY1Uy/JuCi27MIhBSUSxXMjgSaRYE48DnoE@kRX9V@h0jxqbberu7XObK@@v3MAecS9Eobn1Yz/uP@a2mfpKHvInz8n3mV8lwyVlbb@UVWeN47p2Oo55@7Fe9@/Cq7DwaEItkrVlWB31t8vyyfzdPH4dhLdzm/YLpYa8uYIrXVZx15k2cs7B5oISZKAWJcERAKD0aQHlIgEct4Q2mJeE9psMCNRl9dwaie2kcF/y1wkRghBxLiwiRgF0DFQfI7WzQoBZbCJXtJlOiOC2NQ0BgwTwHqEEh4VZhzROLRxGLvQgQrGGPTtMIzL0zgNrQrQECr@AA "JavaScript (Node.js) – Try It Online") [Answer] # .COM opcode, ~~108~~ 104 bytes ``` 0000h: B4 00 CD 16 BE 50 01 83 C6 03 3A 24 77 F9 0F B6 0010h: DC 03 5C 01 B4 02 CD 16 B4 02 68 00 01 A8 03 B2 0020h: 53 74 08 81 36 20 01 20 01 CD 21 84 DB 74 0B 4B 0030h: B2 52 E8 F4 FF B2 4C CD 21 C3 84 FF 74 0C FE CF 0040h: B2 44 E8 E4 FF B2 55 CD 21 C3 B2 50 CD 21 B2 70 0050h: CD 21 C3 0D FE 00 1B F1 00 1C F0 01 28 E3 01 29 0060h: D7 FF 35 D6 02 39 CC 03 ``` Take input from keyboard with CapsLock off Badly golfed though ``` org 100h mov ah, 0 int 16H mov si, table-3 tabing: add si, 3 cmp ah, [si] ja tabing movzx bx, ah add bx, [si+1] mov ah, 2 int 16H mov ah, 2 push 100H test al, 3 mov dl, 'S' cmd: jz fun xor [cmd-1], word 0x120 int 21H fun: test bl, bl jz bl0 dec bx mov dl, 'R' int 21H call fun mov dl, 'L' int 21H ret bl0: test bh, bh jz bh0 dec bh mov dl, 'D' int 21H call fun mov dl, 'U' int 21H ret bh0: mov dl, 'P' int 21H mov dl, 'p' int 21H ret macro key begin, end, U, L { db end dw U*256+L-begin } table: key 0x02, 0x0D, 1, 0 key 0x10, 0x1B, 1, 1 key 0x1C, 0x1C, 2, 12 key 0x1E, 0x28, 2, 1 key 0x29, 0x29, 0, 0 key 0x2C, 0x35, 3, 2 key 0x39, 0x39, 4, 5 ``` ]
[Question] [ Imagine you have two boxes `B(x)` and `B(y)`, each containing an unknown bit - 0 or 1, and a machine `F` that can X-ray them and produce a third box for `B(x^y)` (*xor*). `F` can also compute `B(x*y)` (*and*). In fact, those are just special cases of the the single operation the machine can perform - *inner product each*, denoted with `F()` below. For two same-length arrays ``` [B(x[0]), B(x[1]), ..., B(x[n-1])] [B(y[0]), B(y[1]), ..., B(y[n-1])] ``` *inner product* is defined as ``` B(x[0]*y[0] ^ x[1]*y[1] ^ ... ^ x[n-1]*y[n-1]) ``` "*Each*" means `F()` can process multiple pairs of `x[]`, `y[]` in one go. The `x[]` and `y[]` from one pair must be of the same length; `x[]`-s and `y[]`-s from different pairs don't necessarily need to. Boxes are represented by unique integer ids. An implementation of *inner product each* in JavaScript might look like ``` var H=[0,1]; // hidden values, indexed by boxId function B(x) { // seal x in a new box and return the box id return H.push(x)-1; } function F(pairs) { // "inner product each" return pairs.map(function (pair) { var r = 0, x = pair[0], y = pair[1]; for (var i = 0; i < x.length; i++) r ^= H[x[i]] * H[y[i]]; return B(r); }) } ``` (Please translate the above to your language of choice.) Given access to an `F()` implementation as appropriate for your language (but no access to `H` or `B()`) and given two arrays of box ids constituting the 16-bit binary representations of two integers `a` and `b`, your task is to produce box ids for the 16-bit binary representation of `a+b` (discarding overflow) with the minimum number of `F()` calls. The solution that calls `F()` the fewest times wins. Ties will be broken by counting the total number of `x[],y[]` pairs `F()` was called with - fewer is better. If still tied, the size of your code (excluding the implementation of `F()` and its helpers) determines the winner in the traditional code golf way. Please use a title like "MyLang, 123 calls, 456 pairs, 789 bytes" for your answer. Write a function or a complete program. Input/output/arguments/result is int arrays in any reasonable format. Binary representation may be little- or big-endian - choose one. --- Appendix 1: To make the challenge slightly easier, you can assume that boxes with ids 0 and 1 contain the values 0 and 1. This gives you constants, useful e.g. for negation (`x^1` is "not"). There were ways around the lack of constants, of course, but the rest of the challenge is hard enough anyway, so let's eliminate this distraction. --- Appendix 2: To win the bounty, you must do one of the following: * post your score (calls,pairs,bytes) and your code before the deadline * post your score and a sha256 hash of your code before the deadline; then post the actual code within 23 hours after the deadline [Answer] # [Python 3](https://docs.python.org/3/), 5 calls, 92 pairs, 922 bytes ## ~~[Python 3](https://docs.python.org/3/), 5 calls, 134 pairs, 3120 bytes~~ ## ~~[Python 3](https://docs.python.org/3/), 6 calls, 106 pairs, 2405 bytes~~ ## ~~[JavaScript (Node.js)], 9 calls, 91 pairs, 1405 bytes~~ ## ~~JavaScript (Node.js), 16 calls, 31 pairs, 378 bytes~~ ``` def add(F,a,b):r=[];p=lambda x:(x,x);q=lambda u,v,t:([u,v]+t[0],[u,v]+t[1]);s=lambda c,k,n:([e[j][n]for j in range(k,-1,-1)]+[f[n]],[c]+f[n-k:n+1]);t=lambda c,k,n:q(a[n],b[n],s(c,k,n-1));z=F([p([a[i],b[i]])for i in range(16)]+[([a[i]],[b[i]])for i in range(16)]);e=[z[0:16]];f=z[16:32];r+=[e[0][0]];c=f[0];z=F([p([a[1],b[1],c]),([e[0][1],f[1]],[c,f[1]])]+[([e[0][i]],[e[0][i-1]])for i in range(3,16)]);r+=[z[0]];c=z[1];e+=[[0]*3+z[2:15]];z=F([p([a[2],b[2],c]),t(c,0,3),s(c,1,3)]+[([e[j][i]],[e[1][i-j-1]])for j in range(2)for i in range(6+j,16)]);r+=z[0:2];c=z[2];e+=u(2,4,z[3:]);z=F([p([a[4],b[4],c])]+[t(c,i,i+5)for i in range(0,3)]+[s(c,3,7)]+[([e[j][i]],[e[3][i-j-1]])for j in range(4)for i in range(12+j,16)]);r+=z[0:4];c=z[4];e+=u(4,8,z[5:]);z=F([p([a[8],b[8],c])]+[t(c,i,i+9) for i in range(0,7)]);return r+z def u(b,e,z): j=0;w=[0]*(e-b) for i in range(b,e):w[i-b]=[0]*(i+e)+z[j:j+16-(i+e)];j+=16-(i+e) return w ``` [Try it online!](https://tio.run/##nVbbcuI4EH0OX6HiYUsaC8oGksna5andPKTmA@bNq6VkLBIRY3tsMTFMzbdnW5LxDbIzuxRgXVp9Tp9uySqO6jnPlm@blFcV@jNJRImJP0Hw@aNSXMnNXoBFYkYSsUUyU@JJlGuVr2OpKlw31voznU6/8BeBeHY2g2aCSqEOZYY4SmWlUL5FeiHYtuvKMGJtZ5uXSMJ6VPLsSWCXenc9CGM@50UhsgTXv3lkMFN/@hR6nVuLW05a8uu1zKRar3El0m3Pq@7O1@tsveFpWoXu5UTBZXll4rNm3rp/MH4pGmnykNcQ/DeeHoSO63M/9LOfNiQypp@KDJ@tyMzr0B4btPRKBtRr3qmd1yKx8NUwHw96plsrswwyVpR5ctioKerTlEXVz9FQL6enuc4erumR6EjTYd6gwkSpTEA1CUP9PA7zN5S779fMohC5gxGLJik6SgN4kgWAo@OoYOziv8NW7aiW7EPbOUo2MIdgz@moLtIRmWWQaWLQKw0LC3pV0N8hWmC7T65Wxq/tFpO/iz0zpBNLyyc2W8fs4/nlVmX9rZDIqkj5ca23eTXeEUUJq/H0@w9kUkwRtExSpnOA2XOFhzVAR7kjnXAt5OZZbF4aIbLDPhYlRZ1C4@2YiPjwhHvz7fQhs6OlqA6pgqKIurwyo0KtReiWdultSvC6PpYTQWE4ghjX/VC5K5Fa7jbSqxE28kbGkDVo/l/Z9x@tvj8NCiSeaDAlKoU5jRv3/SPARgTJUXCYVtoxUs9iDzKMTmNqloJzmM8rOCf0oClHniR6Ta8Kqe5nViKkcptWPTaxdakVO1cq10JDhpoXy6RVqasvDD9uAA0j0gpwPUmcUN4U1//2ERNQi5xDbtMcAltsGM8fqaU@v76ZgcS/zsfXGDr/MVAHaHKon8aXxbN7CObogDp505Wg@T9SUwr6lRoUYcr3ccJR7cOxWJPg63ngQL9R5eMInsxRkcvouekxElRnsw19oRmYiWjHoozpKtx1r@YXOvPgS5gTbWEWfGyYA63Zi5852o8a@vmKOZjRWP9V2IzBahKcwkccFTjikdSzkjEyugTAFQBArAXAvGtDAhFGp8j1vTvGgm14irw7f7lgQemEEITL4MuCTbiFZw/W07Dwt2GEYmsHvS386ZhswxIwc4aDbc28SyJLaqlozFMDCERYIGAA@h@Wzila@N4t63NYaA4Ly0GBOC5dEqOSB40Ge9diexp716L3krIY07lzdh0hrc3CEloYQge8oCt6ipY@6ydipdmsDBvA1nwklc4tubicGW6a5pJ@vKS5fJfm6iJ9izHPleW5aniu6D3wvB3yvNc878c8fyeXt8iPxnNzI3RO5uQ84JgKeoKD82YXusFrqLODxSwmk5uRAzAk/itEEzNrJR1BII87f@d4dzPTZcEOrixNZ3LTgL2@yX2Rw0sHHCX5fmIf80qIBA7EsQquq9mYI70x1A99isBF2IUPoe@Mk7d/AA "Python 3 – Try It Online") **FIRST VERSION** Okay that's not golfed. It's just an adaptation of @ngn's code. The only idea here is that you don't need to compute the last carry since you discard overflow. Also, the calls of `F` are grouped by two. Maybe they may be grouped in another way, but I doubt you can reduce significantly the number of pairs, due to the nature of the basic addition algorithm. **EDIT**: Still not golfed. The number of pairs could certainly be reduced, and probably the number of calls too. See <https://gist.github.com/jferard/864f4be6e4b63979da176bff380e6c62> for a "proof" with sympy. **EDIT 2** Switched to Python because it's more readable for me. Now I have got the general formula, I think I may reach the limit of 5 (maybe 4) calls. **EDIT 3** Here are the basic bricks: ``` alpha[i] = a[i] ^ b[i] beta[i] = a[i] * b[i] c[0] = beta[0] r[0] = alpha[0] ``` The general formula is: ``` c[i] = alpha[i]*c[i-1] ^ beta[i] r[i] = a[i] ^ b[i] ^ c[i-1] ``` The expanded version is: ``` c[0] = beta[0] c[1] = alpha[1]*beta[0] ^ beta[1] c[2] = alpha[2]*alpha[1]*beta[0] ^ alpha[2]*beta[1] ^ beta[2] c[3] = alpha[3]*alpha[2]*alpha[1]*beta[0] ^ alpha[3]*alpha[2]*beta[1] ^ alpha[3]*beta[2] ^ beta[3] ... c[i] = alpha[i]*...*alpha[1]*beta[0] ^ alpha[i]*...*alpha[2]*beta[1] ^ .... ^ alpha[i]*beta[i-1] ^ beta[i] ``` 5 calls seems the limit for me. Now I have a little work to remove pairs and golf it! **EDIT 4** I golfed this one. Ungolfed version: ``` def add(F, a, b): r=[] # p is a convenient way to express x1^x2^...x^n p = lambda x:(x,x) # q is a convenient way to express a[i]^b[i]^carry[i-1] q = lambda u,v,t:([u,v]+t[0],[u,v]+t[1]) # step1: the basic bricks z=F([p([a[i],b[i]]) for i in range(16)]+[([a[i]],[b[i]]) for i in range(16)]) alpha=z[0:16];beta=z[16:32] r.append(alpha[0]) c = beta[0] # step 2 z=F([ p([a[1],b[1],c]), ([alpha[1],beta[1]],[c,beta[1]]) ]+[([alpha[i]],[alpha[i-1]]) for i in range(3,16)]) r.append(z[0]) c = z[1] # c[1] alpha2=[0]*3+z[2:15] assert len(z)==15, len(z) # step 3 t0=([alpha[2],beta[2]],[c,beta[2]]) t1=([alpha2[3],alpha[3],beta[3]],[c,beta[2],beta[3]]) z=F([ p([a[2],b[2],c]), q(a[3],b[3],t0), t1]+ [([alpha[i]],[alpha2[i-1]]) for i in range(6,16)]+ [([alpha2[i]],[alpha2[i-2]]) for i in range(7,16)]) r.extend(z[0:2]) c = z[2] # c[3] alpha3=[0]*6+z[3:13] alpha4=[0]*7+z[13:22] assert len(z)==22, len(z) # step 4 t0=([alpha[4],beta[4]],[c,beta[4]]) t1=([alpha2[5],alpha[5],beta[5]],[c,beta[4],beta[5]]) t2=([alpha3[6],alpha2[6],alpha[6],beta[6]],[c,beta[4],beta[5],beta[6]]) t3=([alpha4[7],alpha3[7],alpha2[7],alpha[7],beta[7]],[c,beta[4],beta[5],beta[6],beta[7]]) z=F([ p([a[4],b[4],c]), q(a[5],b[5],t0), q(a[6],b[6],t1), q(a[7],b[7],t2), t3]+ [([alpha[i]],[alpha4[i-1]]) for i in range(12,16)]+ [([alpha2[i]],[alpha4[i-2]]) for i in range(13,16)]+ [([alpha3[i]],[alpha4[i-3]]) for i in range(14,16)]+ [([alpha4[i]],[alpha4[i-4]]) for i in range(15,16)]) r.extend(z[0:4]) c = z[4] # c[7] alpha5 = [0]*12+z[5:9] alpha6 = [0]*13+z[9:12] alpha7 = [0]*14+z[12:14] alpha8 = [0]*15+z[14:15] assert len(z) == 15, len(z) # step 5 t0=([alpha[8],beta[8]],[c,beta[8]]) t1=([alpha2[9],alpha[9],beta[9]],[c,beta[8],beta[9]]) t2=([alpha3[10],alpha2[10],alpha[10],beta[10]],[c,beta[8],beta[9],beta[10]]) t3=([alpha4[11],alpha3[11],alpha2[11],alpha[11],beta[11]],[c,beta[8],beta[9],beta[10],beta[11]]) t4=([alpha5[12],alpha4[12],alpha3[12],alpha2[12],alpha[12],beta[12]],[c,beta[8],beta[9],beta[10],beta[11],beta[12]]) t5=([alpha6[13],alpha5[13],alpha4[13],alpha3[13],alpha2[13],alpha[13],beta[13]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13]]) t6=([alpha7[14],alpha6[14],alpha5[14],alpha4[14],alpha3[14],alpha2[14],alpha[14],beta[14]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13],beta[14]]) t7=([alpha8[15],alpha7[15],alpha6[15],alpha5[15],alpha4[15],alpha3[15],alpha2[15],alpha[15],beta[15]],[c,beta[8],beta[9],beta[10],beta[11],beta[12],beta[13],beta[14],beta[15]]) z=F([ p([a[8],b[8],c]), q(a[9],b[9],t0), q(a[10],b[10],t1), q(a[11],b[11],t2), q(a[12],b[12],t3), q(a[13],b[13],t4), q(a[14],b[14],t5), q(a[15],b[15],t6) ]) r.extend(z) return r ``` [Try it online!](https://tio.run/##pVhbj5s4FH7e/AprKq2goVFsIJnJimq3D1V/wL6xTETA00FNCAWnS6bqb589xzY2EDK9bKRxDpzbd66Qqc7i8Vj6z9k@bRryV57z2nE3MwKfPxuRiiI7cJDI5Z2cP5CiFPwjr7fiuN0VonFaLY2fm5ubv9NPnKRlJwZkTmouTnVJUrIvGkGODwQVQdbo1VGcmIuHY00K0Cd1Wn7kztKjq54LKb5Iq4qXudP@Tt0Bp337NqLWrPJbzwz47bYoC7HdOg3fP/Ss4uViuy23WbrfN9HyklGlRT3B@IDIjfl30q5HRjl5d2wh@C/p/sQxrg/90Ds7JiR3DH/PS6eTct9Q6@299rafqID492izfWx5rtw3w3q8Q47VLcoSKlbVx/yUiRvSh1lUTb9Gw3zNeznH6jmtd3Yx0v2wbtBhvBYyoNaNIvw@D@s3THffruSSiCwHd5S3wiPnQjp8KipwTs6jhlHK95HJdtwWyWtzcS6SgTgE25WjuShHLNWg0q703qBbUOh1QX9CMMFqTiY748emRdbvYmaGcHaFwrOToyPneHE5qkl/FPKiqfbpeYtj3ownoqpB27n5@o3IEnsEKFmUmwW4OaTCGfaAN6qdaxNnXGaPPPukE1GeDjtee8RmaDyOOd@dPjo9vmGfSnW35s1pL6ApYlvXRGahxSRYVVte3YLT@VGYXBJFIxfjvh9mbiJShV1FOhmhTm8sBRPtbfNP@fWbye93g4IUz9CZ4I1wUm@nzfdXgIoIiiN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jMsa0ADXHcDbmHarfW3JlSVDSwaW9C3JLCkp5Sr8/1itJT2BE7saTeNxsavRFx4Xu1o6l@fFtqbqLY2O9rVkyTcNPIU/Zsl3DTxFMGbJRwmeIhyz5MMET7FSNbnYkPpa/0vruThUR1hQsFTz42GmvhYN5zn8yBqv3OUSfg38Jn8makH8wl8mSw@YwPau3Hef/wM "Python 3 – Try It Online") [Answer] # Haskell, 1 call (cheating???), 32 pairs (could be improved), 283 bytes (same) Please don't be angry with me, I don't want to win with this, but I was encouraged in the remarks to the challenge to explain what I was talking about. I tried to use the state monad to handle adding boxes and counting calls and pairs, and that worked, but I didn't manage to make my solution working in that setting. So I did what was also suggested in the comments: just hide the data behind a data constructor and don't peek. (The clean way would be to use a seperate module and not export the constructor.) This version has the advantage of being much simpler. Since we are talking about boxes of bits, I put `Bool` values into them. I define `zero` as the given box with the zero bit - a `one` is not needed. ``` import Debug.Trace data B = B { unB :: Bool } zero :: B zero = B False f :: [([B],[B])] -> [B] f pairs = trace ("f was called with " ++ show (length pairs) ++ " pairs") $ let (B i) &&& (B j) = i && j in map (\(x,y) -> B ( foldl1 (/=) (zipWith (&&&) x y))) pairs ``` We're using the debugging function `trace` to see how often `f` was called, and with how many pairs. `&&&` looks into the boxes by pattern matching, the inequality `/=` used on `Bool` values is `xor`. ``` bits :: Int -> [Bool] bits n = bitsh n 16 where bitsh _ 0 = [] bitsh n k = odd n : bitsh (n `div` 2) (k-1) test :: ( [B] -> [B] -> [B] ) -> Int -> Int -> Bool test bba n m = let x = map B (bits n) y = map B (bits m) r = bba x y res = map unB r in res==bits(n+m) ``` The `test` function takes a blind binary adder as first argument, and then two numbers for which addition is tested. It returns a `Bool` indicating whether the test was successful. First the input boxes are created, then the adder is called, the result unboxed (with `unB`) and compared with the expected result. I implemented two adders, the sample solution `simple`, so that we can see that the debug output works correctly, and my solution using value recursion `valrec`. ``` simple a b = let [r0] = f [([a!!0,b!!0],[a!!0,b!!0])] [c] = f [([a!!0],[b!!0])] in loop 1 [r0] c where loop 16 rs _ = rs loop i rs c = let [ri] = f [([a!!i,b!!i,c],[a!!i,b!!i,c])] [c'] = f [([a!!i,b!!i,c],[b!!i,c,a!!i])] in loop (i+1) (rs++[ri]) c' valrec a b = let res = f (pairs res a b) in [ res!!i | i<-[0,2..30] ] where pairs res a b = let ts = zipWith3 (\x y z -> [x,y,z]) a b (zero : [ res!!i | i<-[1,3..29] ]) in [ p | t@(h:r) <- ts, p <- [ (t,t), (t,r++[h]) ] ] ``` See how I'm defining `res` in terms of itself? That is also known as *tying the knot*. Now we can see how `f` is only called once: ``` *Main> test valrec 123 456 f was called with 32 pairs True ``` Or replace `valrec` by `simple` to see `f` being called 32 times. [Try it online!](https://tio.run/##jVRRb9owEH7Pr7iiqrVFYAS2SkNlmtA0ae@T9pBFrQmmcWuSyHFLy7bfzr7DgdKOTbMUfD5/d/fd@Y5CNXfa2o1Z1pXz9EnP7m/6X53KdRTNlVc0pQm@H3RfTmk8pmlVWfoVRWvtqu05SIz5rGwDqwWrU5FOsxifzKj3gSBAXyvjGkDJs38SnQWtVEO5slbPaWV8QR3qdqkpqhUJq8sbaLZGktWdIHcknUb0vKz2JKZkJJ2dnbF0KxHD4ES3hzhT0lLVJL6Lx/hJMitwFrSo7Nwm4s1EirWpvzEJAUeSHulJShliRtHM@IYT@1L6kBDqkAVtiXAsFJCSC4RcFdrpVnVFA1yn2Z7JDnkHdTWfQxq3OlHS9dw8XNNQkrjrJTKKvG48RxVcwbaQu22bQkun3ZhUsJnNFDwvEYPL84idc0e@gbE8LMxuPb1CLY@iHGcL7yjP0WvdtG64YdxrCB4BiMmEA4iyixBRg9azmhTNWrapG2QQF9xE6uRkEM/wg2Z6lmX2Z@g0z@jQCgZHsWBgq6qmJMTJX96GpwuAC0K3XsEn3v9IpluQIQble@bmkLlhtibOA/f96Rj7oyvNz//iLggxK//P3S5rYboJuss13S6TlZSfbx6UdToPDxDtJiq844JEGFo@AhA6As5S1iA6/SRz2UsH8bDfH6Gc2b79X9i1jg8m1rP7duBGGEq0E623rY3pjNeZ/HdS7FOE/6DXXJJ41O8P34OLBNNDNynVwPiPohg7SZc9kIihgpCS8LGXMW8OpSlgy8lslsrweNfOYMJOaTtbbb2S4YjevrvY/AY "Haskell – Try It Online") (the tracing output appears under "Debug") [Answer] # JavaScript, 32 calls, 32 pairs, 388 bytes # Dyalog APL, 32 calls, 32 pairs, 270 bytes This is a naïve sample solution that can serve as a template. Note that the byte count must include only the section surrounded with "BEGIN/END SOLUTION". Explanation: I chose little-endian bit order (`x[0]` is the least significant bit). Observe that single-bit addition mod 2 can be realised as `F([[[x,y],[x,y]]])` (that is: `x*x ^ y*y` - multiplication mod 2 is idempotent) and binary multiplication as `F([[[x],[y]]])`. We traverse the bits from least significant to most significant and at each step compute a result bit and a carry. ``` #!/usr/bin/env node 'use strict' let H=[0,1] ,B=x=>H.push(x)-1 ,nCalls=0 ,nPairs=0 ,F=pairs=>{ nCalls++;nPairs+=pairs.length return pairs.map(([x,y])=>{let s=0;for(let i=0;i<x.length;i++)s^=H[x[i]]*H[y[i]];return B(s)}) } // -----BEGIN SOLUTION----- var f=(a,b)=>{ var r=[], c // r:result bits (as box ids), c:carry (as a box id) r[0]=F([[[a[0],b[0]],[a[0],b[0]]]]) // r0 = a0 ^ b0 c=F([[[a[0]],[b[0]]]]) // c = a0*b0 for(var i=1;i<16;i++){ r.push(F([[[a[i],b[i],c],[a[i],b[i],c]]])) // ri = ai ^ bi ^ c c=F([[[a[i],b[i],c],[b[i],c,a[i]]]]) // c = ai*bi ^ bi*c ^ c*ai } return r } // -----END SOLUTION----- // tests let bits=x=>{let r=[];for(let i=0;i<16;i++){r.push(x&1);x>>=1}return r} ,test=(a,b)=>{ console.info(bits(a)) console.info(bits(b)) nCalls=nPairs=0 let r=f(bits(a).map(B),bits(b).map(B)) console.info(r.map(x=>H[x])) console.info('calls:'+nCalls+',pairs:'+nPairs) console.assert(bits(a+b).every((x,i)=>x===H[r[i]])) } test(12345,6789) test(12,3) test(35342,36789) ``` The same in Dyalog APL (but using randomised box ids): ``` ⎕io←0⋄K←(V←⍳2),2+?⍨1e6⋄B←{(V,←⍵)⊢K[≢V]}⋄S←0⋄F←{S+←1,≢⍵⋄B¨2|+/×/V[K⍳↑⍉∘↑¨⍵]} ⍝ -----BEGIN SOLUTION----- f←{ r←F,⊂2⍴⊂⊃¨⍺⍵ ⍝ r0 = a0 ^ b0 c←⊃F,⊂,¨⊃¨⍺⍵ ⍝ c = a0*b0 r,⊃{ ri←⊃F,⊂2⍴⊂⍺⍵c ⍝ ri = ai ^ bi ^ c c⊢←⊃F,⊂(⍺⍵c)(⍵c⍺) ⍝ c = ai*bi ^ bi*c ^ c*ai ri }¨/1↓¨⍺⍵ } ⍝ -----END SOLUTION----- bits←{⌽(16⍴2)⊤⍵} test←{S⊢←0⋄r←⊃f/B¨¨bits¨⍺⍵ ⎕←(↑bits¨⍺⍵)⍪V[K⍳r]⋄⎕←'calls:' 'pairs:',¨S (bits⍺+⍵)≢V[K⍳r]:⎕←'wrong!'} test/¨(12345 6789)(12 3)(35342 36789) ``` ]
[Question] [ [Cubically](https://github.com/aaronryank/cubically) is a fairly new esoteric language capable of creating short, golf-like answers for a very specific subset of problems. It is unique in that it stores memory in the form of a 3x3 Rubik's cube, making calculations far less trivial than in most languages. In Cubically, the programmer must rotate the internal cube in order to manipulate the values stored on the faces, then use those values in their calculations. Calculations are performed on a single 32-bit integer stored on an imaginary face known as the "notepad". Additionally, Cubically can request user input and store it in an input buffer consisting of only a single integer value. ## The Cube The faces of the cube are **U**p, **D**own, **L**eft, **R**ight, **F**ront, and **B**ack: ``` UUU UUU UUU LLLFFFRRRBBB LLLFFFRRRBBB LLLFFFRRRBBB DDD DDD DDD ``` When the program starts, the cube is initialized such that each square on that face is equal to that face's 0-based index: ``` 000 000 000 111222333444 111222333444 111222333444 555 555 555 ``` Whenever a face is rotated, it is always rotated clockwise: ``` Cubically> F1 000 000 111 115222033444 115222033444 115222033444 333 555 555 ``` The value of a face is defined as being the sum of every square on that face. For example, in the above cube, the value of face `0` is 3. ## Syntax Commands are executed by first loading a command into memory, then passing arguments to it to execute the command. For example, the command `F1` will load the command `F` into memory, then call it with the argument `1`. Additionally, `F13` will load the command `F` into memory, then call it with the argument `1`, then call it with the argument `3`. Any non-digit character is treated as a command, and any digit is treated as an argument. ## Your task Your task is to implement Cubically's internal memory cube in a language of your choice. Your code should be able to execute a very small subset of the language. **Commands** * `R` - Rotate the right face of the cube clockwise the specified number of times. * `L` - Rotate the left face of the cube clockwise the specified number of times. * `U` - Rotate the top face of the cube clockwise the specified number of times. * `D` - Rotate the bottom face of the cube clockwise the specified number of times. * `F` - Rotate the front face of the cube clockwise the specified number of times. * `B` - Rotate the back face of the cube clockwise the specified number of times. * `%` - Outputs the value on the given face. The value of a face is defined as the sum of all squares on that face. ## Rules * You may use any language created before or after the date this challenge was posted to write a program or function capable of solving this challenge. * Input will be passed in either through STDIN, as a string, or as a character array (you choose, please specify). * Output must be passed either to STDOUT or as the output of the function, and it must be either an integer, a string containing only digits, or an array of digits. If your language **requires you** to output a trailing newline, you may do so. * The input will always be in the following format: `([UDLRFB]\d*)*%[0-5]`. There will be no whitespace characters in the input. * The input for `%` will always use a 0-based index. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. ## Test Cases ``` %0 -> 0 %1 -> 9 %2 -> 18 %3 -> 27 %4 -> 36 %5 -> 45 R1%2 -> 27 RD3F2%5 -> 32 L1R23F1B5U9D2%3 -> 17 ``` For more test cases, [check out the TIO interpreter](https://tio.run/#cubically). If TIO isn't working, you may use [the Lua interpreter](https://github.com/Cubically/cubically-lua) instead. [Answer] # [Python 2](https://docs.python.org/2/), 476 bytes ``` import re c=[[i]*9for i in range(6)] r=lambda f:[f[a+b]for a in(0,1,2)for b in(6,3,0)] U=lambda c:[r(c[0])]+[c[j+1][:3]+c[j or 4][3:]for j in(1,2,3,0)]+[c[5]] y=lambda c:[r(c[0])]+c[2:5]+[c[1],r(r(r(c[5])))] z=lambda c:[c[2],r(r(r(c[1]))),c[5],r(c[3]),c[0][::-1],c[4][::-1]] s=input() exec("c="+"(c);c=".join("".join("zzzUz U zzUzz yyyzUzzzy zUzzz yzUzzzyyy".split()[ord(t)%11%7]*sum(map(int,n))for t,n in re.findall("([BUDLFR])(\d*)",s[:-2])))+"(c)") print sum(c[int(s[-1])]) ``` **[Try it online!](https://tio.run/##bVDLasMwELz7K4QgIMVK8CNJiYsvIeSUU8CnrQ6ObLcKfiE7UPnn05Wb0h6KDjvDzox2t7fjR9dGj4du@s6MxJSeSgG0XO6rzhBNdEtM3r6XbMelZ9I6b65FTqoEKsj9q3SiHEUsEKGIuKNXR3ciFgE6sh@HSsAwBYHk0gcFNz@UkMTSR0jQtJEQJ3Pazdkx6zvAabdSeva/HAVRsp0loRSGuefUnOPH0x8D6n77oesLpxOOxtKRAIdJVpiiYPOE0htS3fb3kXGv/CwVoyqlPmWKvyJY3zock/7UaZqyiWTElYlYa12dLJkLeTJr6Xroa42J0JmCjXwRhosXuRzuDWvynul2FC2fj4hgPn25rnRb5HXNKINDdjyfLpKzt2LJqRggWUVum3kqyr3eYAJxaQoQsQFwDy7540HP4SWKT@Fhm@2P0SKmXw "Python 2 – Try It Online")** A port from my [Simulate A Rubik's Cube answer](https://codegolf.stackexchange.com/a/92806/53748). The revisit prompted me to golf that by 47 bytes. [Answer] # [Cubically](//git.io/Cubically), 1 byte ``` ¶ ``` Non-competing 'cause it's lame. Don't accept this. ``` ¶ Read a line from stdin and evaluate ``` I added that this afternoon :P ]
[Question] [ # Input * *verb*, a string that matches the regular expression `([a-pr-vyzıöüçğş]*[aeıioöuü][bcçdfgğhj-nprsştvyz]+|([a-pr-vyzıöüçğş]*[aeıioöuü]){2})(mak|mek)` * *plural*, a truthy or falsy value * *person*, an integer having value either 1, 2, or 3 * *tense*, an integer having value either 1, 2, or 3 # Output The conjugated form of the Turkish verb *verb*, in *person*st/nd/rd person, plural if *plural* is `TRUE` and singular if it is not, in * If *tense* is 1, the simple present; * If *tense* is 2, the continuing present; * If *tense* is 3, the future. # Rules Turkish verbs are conjugated in three elements, which are in order: * The *stem*, formed by removing `mak` or `mek` from the end of the infinitive; * The *sign of the tense*, which is: + For the simple present: > > > - *-r* if the stem ends in a vowel; > - *-ir* according to **vowel harmony rules** (see below) if the stem contains more than one syllable (i.e. vowel), or is from one of the following irregular verbs: *almak, bilmek, bulmak, durmak, gelmek, görmek, kalmak, olmak, ölmek, sanmak, vermek, varmak, vurmak*; > - *-er* according to **vowel harmony rules** if the stem contains one syllable and is not listed in the irregular verbs above. > + For the continuing present, *-iyor*, where the *i* changes according to **vowel harmony rules**. Stems that end in a vowel drop this vowel before adding this suffix, whereupon the suffix harmonizes with the next-to-last vowel in the word (guaranteed to exist by the regular expression). + For the future: > > > - *-ecek* according to **vowel harmony rules** if the stem ends in a consonant; > - *-yecek* according to **vowel harmony rules** if the stem ends in a vowel. > * The *personal suffix* to indicate the performer of the action, in all cases according to **vowel harmony rules**: ``` |Singular|Plural| |---|--------|------| |1st| -im | -iz| |2nd| -sin |-siniz| |3rd| (none) | -ler| ``` The final *k* of the future tense becomes *ğ* before *-im* and *-iz*, so for example `(almak, TRUE, 1, 3)` would yield `alacağız`. # Vowel harmony rules Turkish vowels are divided into two groups: back (`a ı o u`) and front (`e i ö ü`) by where in the mouth they are pronounced. The suffixes of a word change vowels according to the vowels of the root. All suffixes listed above that have *i* as a vowel instead use: * *-ı* if the last vowel before the suffix is `ı` or `a` (both these vowels are back and unrounded); * *-i* if the last vowel before the suffix is `i` or `e` (both these vowels are front and unrounded; note here Turkish's distinction between [dotted and dotless I](https://en.wikipedia.org/wiki/Dotted_and_dotless_I)); * *-u* if the last vowel before the suffix is `u` or `o` (both these vowels are back and rounded); or * *-ü* if the last vowel before the suffix is `ü` or `ö` (both these vowels are front and rounded). Take careful note of the present continuous suffix *-iyor*. The `i` harmonizes, but the `o` does not change. The personal suffixes will thus harmonize with the `o`. All the suffixes listed above that have *e* as a vowel instead use: * *-e* if the last vowel before the suffix is a front vowel; or * *-a* if the last vowel before the suffix is a back vowel. # Irregular verbs The verbs *gitmek*, *tatmak*, *ditmek*, *gütmek*, and *etmek* change the final `t` to a `d` before any endings that begin with a vowel (which includes all the endings in this challenge). Any verb that ends in *-etmek* likewise changes the `t` to a `d`, and appends *-er* for the simple present (though this is not so for the other verbs). # Test cases ``` gütmek, FALSE, 1, 2 -> güdüyorum almak, TRUE, 3, 3 -> alacaklar boğmak, TRUE, 2, 1 -> boğarsınız ölmek, FALSE, 3, 1 -> ölür boyamak, TRUE, 1, 2 -> boyuyoruz affetmek, FALSE, 2, 1 -> affedersin söylemek, TRUE, 3, 1 -> söylerler söylemek, FALSE, 3, 2 -> söylüyor söylemek, FALSE, 1, 3 -> söyleyeceğim ``` [Answer] ## Javascript (ES6), ~~466~~ ~~456~~ ~~451~~ 446 bytes ``` (v,p,w,t)=>(R=g=>g.exec(s),T=r=>s=s.slice(0,-1)+r,Z=s=>s.replace(/\d/g,c=>l=['ıuiü'[(n='aıoueiöü'.search(l))>>1],'ae'[n>>2]][c]),(s=v.slice(k=l=0,-3)).replace(/[aıoueiöü]/g,c=>(L=l,l=c,k++)),(R(/^(gi|ta|di|gü)t$/)||(R(/et$/)&&(k=1)))&&T`d`,((E=R(/[aıoueiöü]$/))&&t==2?(l=L,T``):s)+Z([(E?'':k<2&!R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/))+'r','0yor',(E?'y1c1':'1c1')+'ğkk'[--w]][t-1])+Z('0m|0z|s0n|s0n0z||l1r'.split`|`[w+w+p],t-2||(l='o'))) ``` ### Ungofled and commented ``` // Parameters: // - 'v' = verb // - 'p' = plural flag // - 'w' = person // - 't' = tense (v, p, w, t) => ( // R() - Helper function to execute a regular expression on the stem. R = g => g.exec(s), // T() - Helper function to replace the last character of the stem with 'r'. T = r => s = s.slice(0, -1) + r, // Z() - Function that applies vowel harmony to the string 's', assuming // '0' = 'i' and '1' = 'e' and using the last encountered vowel 'l'. Z = s => s.replace( /\d/g, c => l = [ 'ıuiü' [(n = 'aıoueiöü'.search(l)) >> 1], 'ae' [n >> 2] ][c] ), // Computes: // - 's' = stem // - 'k' = number of vowels in stem // - 'l' = last vowel in stem // - 'L' = penultimate vowel in stem (s = v.slice(k = l = 0, -3)).replace(/[aıoueiöü]/g, c => (L = l, l = c, k++)), // Applies ending 't' => 'd' for irregular verbs and those ending in -et(mek). (R(/^(gi|ta|di|gü)t$/) || (R(/et$/) && (k = 1))) && T `d`, // Computes 'E' = truthy value if the stem ends in a vowel. // If 'E' is truthy and the tense is the continuing present, drops this vowel. ((E = R(/[aıoueiöü]$/)) && t == 2 ? (l = L, T ``) : s) + // Appends sign of tense with vowel harmony. Z([ // t = 1: simple present -> either '-er', '-ir' or '-r' (E ? '' : k < 2 & !R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/) + 'r', // t = 2: continuing present -> always '-iyor' '0yor', // t = 3: future -> either '-yecek', '-ecek', '-yeceğ' or '-eceğ' (E ? 'y1c1' : '1c1') + 'ğkk' [--w] ][t - 1]) + // Appends personal suffix with vowel harmony, // forcing last vowel to 'o' for continuing present. Z( '0m|0z|s0n|s0n0z||l1r'.split `|` [w + w + p], t - 2 || (l = 'o') ) ) ``` ### Test cases ``` let f = (v,p,w,t)=>(R=g=>g.exec(s),T=r=>s=s.slice(0,-1)+r,Z=s=>s.replace(/\d/g,c=>l=['ıuiü'[(n='aıoueiöü'.search(l))>>1],'ae'[n>>2]][c]),(s=v.slice(k=l=0,-3)).replace(/[aıoueiöü]/g,c=>(L=l,l=c,k++)),(R(/^(gi|ta|di|gü)t$/)||(R(/et$/)&&(k=1)))&&T`d`,((E=R(/[aıoueiöü]$/))&&t==2?(l=L,T``):s)+Z([(E?'':k<2&!R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/))+'r','0yor',(E?'y1c1':'1c1')+'ğkk'[--w]][t-1])+Z('0m|0z|s0n|s0n0z||l1r'.split`|`[w+w+p],t-2||(l='o'))) console.log(f("gütmek", false, 1, 2)); // -> güdüyorum console.log(f("almak", true, 3, 3)); // -> alacaklar console.log(f("boğmak", true, 2, 1)); // -> boğarsınız console.log(f("ölmek", false, 3, 1)); // -> ölür console.log(f("boyamak", true, 1, 2)); // -> boyuyoruz console.log(f("affetmek", false, 2, 1)); // -> affedersin console.log(f("söylemek", true, 3, 1)); // -> söylerler console.log(f("söylemek", false, 3, 2)); // -> söylüyor console.log(f("söylemek", false, 1, 3)); // -> söyleyeceğim ``` [Answer] # sed, 583 bytes ``` sed -E 's/^((bul|dur|k?al|ol|san|v[au]r)ma|(bil|gel|gör|öl|ver)me)k( . .) 1/\2\3Ir\4/;s/etmek( . .) 1/edEr\1/;s/etmek /ed /;s/^((ta)tma|([dg]i|gü)tme)k /\2\3d /;s/m[ae]k / /;s/([aıoueiöüEI])/V\1/g;s/(V.)( . .) 1/\1r\2/;s/(V.+V.+)( . .) 1/\1VIr\2/;s/( . .) 1/VEr\1/;s/(V.)?( . .) 2/VIyVor\2/;s/(V.)( . . 3)/\1y\2/;s/( . .) 3/VEcVEk\1/;s/k( . 1)/ğ\1/;s/ 0 1/VIm/;s/ 1 1/VIz/;s/ 0 2/sVIn/;s/ 1 2/sVInVIz/;s/ 0 3//;s/ 1 3/lVEr/;:l s/([ıa][^V]*V)I/\1ı/;s/([ie][^V]*V)I/\1i/;s/([uo][^V]*V)I/\1u/;s/([üö][^V]*V)I/\1ü/;s/([aıou][^V]*V)E/\1a/;s/(V[^aEI][^V]*V)E/\1e/;t l s/V//g' ``` Like my [answer to the closely-related Dactylic Hexameter](https://codegolf.stackexchange.com/a/92151/8927) question, this is really just translating the rules as given into regular expressions. ### Usage: Takes input in the form: ``` word [01] [123] [123] ``` So the test cases are: ``` printf 'gütmek 0 1 2 almak 1 3 3 boğmak 1 2 1 ölmek 0 3 1 boyamak 1 1 2 affetmek 0 2 1 söylemek 1 3 1 söylemek 0 3 2 söylemek 0 1 3' | sed -E '<...>'; ``` ### Breakdown: ``` sed -E " # special cases for simple present tense s/^((bul|dur|k?al|ol|san|v[au]r)ma|(bil|gel|gör|öl|ver)me)k( . .) 1/\2\3Ir\4/; # stemming # always uses -er rule if simple present s/etmek( . .) 1/edEr\1/; s/etmek /ed /; s/^((ta)tma|([dg]i|gü)tme)k /\2\3d /; s/m[ae]k / /; # mark vowels for easier expressions later s/([aıoueiöüEI])/V\1/g; # simple present s/(V.)( . .) 1/\1r\2/; s/(V.+V.+)( . .) 1/\1VIr\2/; s/( . .) 1/VEr\1/; # continuing present s/(V.)?( . .) 2/VIyVor\2/; # future s/(V.)( . . 3)/\1y\2/; s/( . .) 3/VEcVEk\1/; # personal suffix s/k( . 1)/ğ\1/; s/ 0 1/VIm/; s/ 1 1/VIz/; s/ 0 2/sVIn/; s/ 1 2/sVInVIz/; s/ 0 3//; s/ 1 3/lVEr/; # vowel harmony :l s/([ıa][^V]*V)I/\1ı/; s/([ie][^V]*V)I/\1i/; s/([uo][^V]*V)I/\1u/; s/([üö][^V]*V)I/\1ü/; s/([aıou][^V]*V)E/\1a/; s/(V[^aEI][^V]*V)E/\1e/; # keep looping until all vowels are known t l # unmark vowels s/V//g " ``` ### Results for test cases: ``` güdüyorum alacaklar boğarsınız ölür boyuyoruz affedersin söylerler söylüyor söyleyeceğim ``` ]
[Question] [ Given the input of the first number and the second number (both positive integers, zero exluded), determine in how many ways could you make the second out of the first, using following actions: `+1`,`+2` and `*3`. Operations are simply applied from left to right. Examples: 1. Input: `1 2`. Output: `1`. I.e, you could only get `2` by doing `+1`, so one way. 2. Input: `1 3`. Output: `3`. I.e, you could get 3 by either doing `+2` or `+1+1`, or `*3` 3. Input: `1 4`. Output: `4`. 4. Input: `2 6`. Output: `6`. 5. Input: `2 7`. Output: `9`. 6. Input: `1 10`. Output: `84`. In case there're no ways, e.g. `100 100`, or `100 80`, output is `0`. You could also take input as an array, or string with any convenient separator. The shortest solution wins. [Answer] # Javascript ES6, ~~45~~ 44 bytes ``` f=(a,b=B)=>a<(B=b)?f(a+1)+f(a+2)+f(a*3):a==b ``` Example runs: ``` f(1,2) -> 1 f(2,6) -> 6 f(1 10) -> 84 ``` [Answer] # Pyth - ~~26~~ 24 bytes There seems to be a bug in Pyth that's making it take inputs in the wrong order, but it shouldn't matter anyway. ``` /m.vj;+sdzs^Lc3"+1+2*3"S ``` [Test Suite](http://pyth.herokuapp.com/?code=%2Fm.vj%3B%2Bsdzs%5ELc3%22%2B1%2B2%2a3%22S&test_suite=1&test_suite_input=2%0A1%0A3%0A1%0A4%0A1%0A6%0A2%0A7%0A2&debug=0&input_size=2). (`1 10` timed out online, but worked on my computer). [Answer] # Pyth, 29 bytes ``` M?>GH0|qGH+sgLGtBtH?%H3ZgG/H3 ``` [Try it online!](http://pyth.herokuapp.com/?code=M%3F%3EGH0%7CqGH%2BsgLGtBtH%3F%25H3ZgG%2FH3g.%2a&input=1%2C10&debug=0) Defines a function. Added three bytes in the link to call the function. ]
[Question] [ Let's do an exercise together, shall we? Simply follow the movements of the stickman. What stickman you ask? The one we are about to create! Make a program that allows for a string-input only containing integers, and outputs the following nine stick-figures with an interval in between: ``` @ \@/ |@_ _@| @/ \@ |@| \@\ /@/ /|\ | | | | | | | | / \ / \ / \ / \ /|\ /|\ / \ / \ / \ 1 2 3 4 5 6 7 8 9 ``` This will result in an animation, which we can then follow along irl. Here is an example of the output created when the input is "`123245762`": [![enter image description here](https://i.stack.imgur.com/7p9UX.gif)](https://i.stack.imgur.com/7p9UX.gif) **Some rules:** * This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins * The input is a `string` only containing `[1-9]` with a length potentially varying from 2 to 100 characters \*\* * The animation must be an endless loop * The interval time must be 750 ms * No duplicated adjacent integers are allowed in the input - this also includes the first and last integers of the input (see the seventh and eight test cases) \*\* \*\* How it fails in case of invalid input is completely up to you, but **it should be clear that it fails**. It could throw an exception; simply return at the start; reboot your PC; delete it's own source-/compile-code; hack into the military and shoots a rocket to the compiling GPS-location. Your call. **EDIT:** It's not allowed to simply display a (correct / half) animation as failing input. It must be clear that something is wrong with the input for the failing testcases below. Thanks to *@user81655* for bringing this to my attention, hence the edit. **Subrules:** * Please post the gif for one of the (non-failing) test cases below in your answer, which you can make very easy with the following program: [screentogif.codeplex.com](https://screentogif.codeplex.com/) (Any other gif-creating program is also allowed of course.) * ***Bonus points if you actually do the exercise alongside the animation irl when it's finished. ;)*** **Correct testcases:** 1. `123245762` 2. `65` 3. `121234346565879879132418791576` **Failing testcases:** 4. `2` // Too few characters 5. `7282918274959292747383785189478174826894958127476192947512897571298593912374857471978269591928974518735891891723878` // Too much characters 6. `1232405762` // Containing invalid input (the `0`) 7. `112212` // Fails because of the `11` and `22` present 8. `1232457621` // Fails because of the starting and leading `1` [Answer] # SpecBAS - 387 bytes ``` 1 DIM m$=" @"#13"/|\"#13"/ \","\@/"#13" |"#13"/ \","|@_"#13" |"#13"/ \","_@|"#13" |"#13"/ \","@/"#13" |"#13"/|\"," \@"#13" |"#13"/|\","|@|"#13" |"#13"/ \","\@\"#13" |"#13"/ \","/@/"#13" |"#13"/ \" 2 INPUT a$: o=0 3 IF LEN a$<2 OR LEN a$>100 THEN 10 4 FOR i=1 TO LEN a$ 5 n=VAL(a$(i)) 6 IF n=0 OR n=o THEN 10 7 CLS : ?m$(n): o=n: WAIT 750 8 NEXT i 9 GO TO 4 10 CLS : ?" @"#13"-O-"#13"/ \"#13"FAT" ``` Keeps looping until you press ESC. Failure to exercise properly (incorrect input - in this example a 0 as one of the steps) leads to fatness. The GIF loops, in the program it just stops at that point. `#13` is the SpecBAS equivalent to `\n` and lets you include line feed in strings. [![enter image description here](https://i.stack.imgur.com/iOYbY.gif)](https://i.stack.imgur.com/iOYbY.gif) [Answer] ## JavaScript (ES6), 165 bytes ``` f=s=>{n=s[0];e.textContent=' @ \\@/|@__@|@/ \\@|@|\\@\\/@/'.substr(n*3-3,3)+(n>1?` | `:` /|\\ `)+(n<5|n>6?'/ \\':'/|\\');s=s.slice(1)+n;s[0]-n&&setTimeout(f,750,s)} f("123245762") ``` ``` <pre id=e> ``` [Answer] # JavaScript (ES6), 210 bytes ``` s=>setInterval(_=>(c=console).clear(i=0)&c.log(`, @ /|\\ / \\,\\@/ | / \\,|@_ | / \\,_@| | / \\,@/ | /|\\, \\@ | /|\\,|@| | / \\,\\@\\ | / \\,/@/ | / \\`.split`,`[s[i++%s.length]]),750) ``` [Answer] # Java 8, ~~663~~ ~~636~~ ~~634~~ ~~631~~ ~~596~~ ~~355~~ ~~354~~ 343 bytes Just for the lols I tried to make the program in Java. ~~Admittedly I'm pretty bad at golfing and regexes, so it can most likely be golfed (a lot?) more. Nevertheless, here it is in Java 7.~~ Now almost two years later and I almost halved the code in Java 8. Why did I ever made those rules about validating the input and requiring a full program, though... >.> I hate my past self now.. ``` interface M{static void main(String[]a)throws Exception{for(;a[0].matches("[1-9]{2,100}")&!a[0].matches(".*(.)\\2.*|(.).*\\1");)for(int c:a[0].getBytes()){c-=48;System.out.printf("%s%n%s%n%s%n",c<2?" @ ":c<3?"\\@/":c<4?"|@_":c<5?"_@|":c<6?"@/ ":c<7?" \\@":c<8?"|@|":c<9?"\\@\\":"/@/",c<2?"/|\\":" | ",c%7>4?"/|\\":"/ \\");Thread.sleep(750);}}} ``` -11 bytes thanks to *@ceilingcat*. **Explanation:** [Try it online.](https://tio.run/##VY/RboIwFIZfpTuJCzVSoKKouEGW7HJX7s4S05SiuFkIdG4GeHZWWLZkF02@/Oc7f07P/MrtopTqnL71fa60rDIuJHppas11LtC1yFN04bmydrrK1XGfcKxPVfFZo@cvIUudF6rJisoK@d5NyIVrcZK1BXvPXicNnXmu2wG@v/s/JVOLYMYombYGyJQxD3CIhx5zAxKbUT9K/XTTxse4EfaDvwp3t1rLCyk@NCnNNTqzYFJP1O@DmdjSCFCMYCO28wgYi50B/Qja@DDQIoJD3A60jCB2RjEwK8YccDWI43g9bjMGG3BMyU@z044BapEJJsGj/xc5psF84fVUSZ6S@l3K0goWLg67ruv73qNz6i@CJf0G) (After it has timed out after 60 sec.) ``` interface M{ // Class static void main(String[]a) // Mandatory main-method throws Exception{ // Required throws for the `Thread.sleep` for(;a[0].matches("[1-9]{2,100}") // Validate 2-100 integers only containing 1-9 &!a[0].matches(".*(.)\\2.*|(.).*\\1") // Validate no adjacent duplicated char (with wrap-around) ;) // And start an infinite loop if it's valid: for(int c:a[0].getBytes()){// Inner loop over the characters of the input: c-=48; // Convert the character-code to an integer System.out.printf("%s%n%s%n%s%n", // Print: c<2?" @ ":c<3?"\\@/":c<4?"|@_":c<5?"_@|":c<6?"@/ ":c<7?" \\@":c<8?"|@|":c<9?"\\@\\":"/@/", // The top part of the stick figure c<2?"/|\\":" | ", // The middle part of the stick figure c%7>4?"/|\\":"/ \\"); // The bottom part of the stick figure Thread.sleep(750);}}} // Sleep 750 ms ``` **Gif:** *(Note: Old gif, since it's clearly jdk1.8+ now.)* [![enter image description here](https://i.stack.imgur.com/7p9UX.gif)](https://i.stack.imgur.com/7p9UX.gif) [Answer] ## Pyth, 114 bytes ``` [[email protected]](/cdn-cgi/l/email-protection)"xÚí» À0 DW¹NM@+Üñ\">íÂA¸êÄÓw»`3±2þ&'NövfAé8é~0,p'ÆìÞúr_'¥,d! YÈBíéqs"[[email protected]](/cdn-cgi/l/email-protection) ``` [![Output GIF](https://i.stack.imgur.com/2sZKp.gif)](https://i.stack.imgur.com/2sZKp.gif) [Try it here](http://pyth.herokuapp.com/?code=Vlzj%40cv.Z%22x%C3%9A%C3%AD%C2%8F%C2%BB%09%C3%800%0CDW%C2%B9NM%40%2B%C3%9C%1E%C2%91%C3%B1%5C%22%1A%3E%C2%8E%C3%AD%C3%82%01A%16%C2%B8%C3%AA%C3%84%C3%93%C2%8Fw%1B%08%C2%BB%60%C2%9E%113%C2%B12%C2%82%C3%BE%26%12%27N%C3%B6%C2%82vfA%C3%A98%C3%A9~0%C2%9A%2Cp%C2%96%27%C3%86%C3%AC%C3%9E%C3%BAr_%27%16%C2%9A%C2%A5%2Cd!%0BY%C3%88B%16%7F%16%C3%AD%01%1C%C3%A9qs%223tv%40zN&input=123245762&debug=0) (No pausing, non-infinite) [Answer] # Mathematica, 252 bytes ``` i=0;Dynamic[Uncompress["1:eJxTTMoPSuNkYGAoZgESPpnFJcFCQIaCQ4yBoZF+TUwMmFaIiQELx8Q46IMEFGrgwoJA4RqHeCyi8Q41aKICQFEUA2qg5gIlHdCEIeaimyAMcQTEWWj26aO7DQDaqDEh"][[FromDigits[#~StringTake~{i=i~Mod~StringLength@#+1}]]],UpdateInterval->3/4,TrackedSymbols->{}]& ``` Would be nice if someone could create a GIF. Run in a notebook. [Answer] # Python3, 338 bytes ``` import os,time p=" @ \n/|\\\n/ \\","\\@/\n | \n/ \\","|@_\n | \n/ \\","_@|\n | \n/ \\","@/ \n | \n/|\\"," \\@\n | \n/|\\","|@|\n | \n/ \\","\\@\\\n | \n/ \\","/@/\n | \n/ \\" i=input() for j in range(len(i)):(i[j]in"123456789"and i[j]!=i[(j+1)%len(i)])or exit() while 1:[[time.sleep(0.75),os.system("clear"),print(p[int(j)-1])]for j in i] ``` ]
[Question] [ Let's write the shortest code to perform a simplified variant of the [DoD 5220.22-M Wipe Method](http://pcsupport.about.com/od/termsd/g/dod-5220-22-M.htm) with only two writing passes. Any programming language accepted, but the use of disk-wiping-oriented libraries is prohibited. Here's how we are to implement it in pseudocode: ``` Set x to 0 [Start] 'Write Pass For each sector in disk write the content of x 'Verification Pass For each sector in disk { If sector does not contain the content of x then goto [Start] } 'Check whether we already did the pass with 1 If x is not 1 then { Set x to 1 GoTo [Start] } Else end ``` In other words, this code will run twice, with a write pass and verification pass for `0`, and a write pass and verification pass for `1`. Anyone ballsy enough to implement it code-golf style? ;) [Answer] On a linux system there's no need for special handling of devices. Just use the device file interface. # Python 3 (byte strings) - 141 bytes ``` d=input() f=open(d,'r+b') z=f.seek z(0,2) s=f.tell() i=0 while i<2: z(0);f.write([b'\0',b'\xff'][i]*s);f.flush();z(0) if f.read()==x:i+=1 ``` It's fairly straightforward, and not really optimised heavily, but it works. Here's a basic rundown. * Get input (device file path) * Open device file * Seek to the end, get filesize (block devices are always their real size) * enter write-and-check loop * construct 0-bit and 1-bit strings (x) * write bitstring * flush output (I could have set buffering=0 but this is shorter) * test file against x, and increment step of loop if it passes exit loop when the increment is high enough As a bonus, you could modify this for any set and number of byte-modification patterns, like 0x55/0xaa for stronger overwriting effects. I did actually test this on a device file, using loopback. However, I'm not 100% sure the checking actually works. It might be necessary to close and reopen the file each pass, due to buffering behaviors. I would hope flush prevents this. \*edited to incorporate some suggestions in the comments [Answer] # x86 machine code (Linux), ~~116~~ ~~109~~ 106 bytes ``` 00000000: 89cb 6a02 5999 894c 24f4 b005 cd80 505b ..j.Y..L$.....P[ 00000010: 536a 025a 31c9 b013 cd80 89c6 5b53 9931 Sj.Z1.......[S.1 00000020: c9b0 13cd 8089 f75b 53b2 018d 4c24 f8b0 .......[S...L$.. 00000030: 04cd 804e 75f1 5b53 9931 c9b0 13cd 8089 ...Nu.[S.1...... 00000040: fe5b 538d 4c24 f4b2 01b0 03cd 804e 740c .[S.L$.......Nt. 00000050: 8a44 24f8 3844 24f4 74e7 ebb3 89fe b001 .D$.8D$.t....... 00000060: 8644 24f8 3c01 75a7 58c3 .D$.<.u.X. ``` Function that takes filename as argument, uses fastcall convention. Assembly (NASM): ``` section .text global func func: ;open file mov ebx, ecx ;first argument to func (filename) push 0x2 ;flag O_RDWR pop ecx ;pushing a constant is shorter than mov cdq ;edx=mode=0 mov [esp-12], ecx ;set first byte (msg) to write to 0. msg later in esp-8, buf in esp-12 mov al, 5 int 0x80 ;syscall open push eax ;save file descriptor write_verify: ;get file size pop ebx ;get fd push ebx push 0x2 ;flag SEEK_END pop edx xor ecx, ecx ;offset 0 mov al, 0x13 int 0x80 ;syscall lseek mov esi, eax ;save file byte count in esi ;reset index of file to 0 pop ebx ;get fd push ebx cdq ;edx=flag SEEK_SET=0 xor ecx, ecx ;ecx=0 mov al, 0x13 int 0x80 ;syscall lseek ;***write pass*** mov edi, esi write_loop: ;for each byte in byte count, write [msg] ;write to file pop ebx ;file descriptor push ebx mov dl, 1 ;bytes to write lea ecx, [esp-8] ;buffer to write from mov al, 4 int 0x80 ;syscall write dec esi ;decrement (byte count) to 0 jne write_loop ;while esi!=0, loop ;reset index of file to 0 pop ebx ;get fd push ebx cdq ;edx=SEEK_SET=0 xor ecx, ecx ;ecx=0 mov al, 0x13 int 0x80 ;syscall lseek ;***verification pass*** mov esi, edi verify_loop: ;for each byte in byte count, verify written byte pop ebx ;get fd push ebx lea ecx, [esp-12] ;buffer to store read byte mov dl, 1 ;read 1 byte mov al, 3 int 0x80 ;syscall read dec esi je end_verify ;at final byte, end verification mov al, [esp-8] cmp byte [esp-12],al je verify_loop ;loop if expected value found jmp write_verify ;if byte!=expected value, restart end_verify: mov esi, edi mov al, 1 xchg byte [esp-8],al ;set new byte to write to 1 cmp al, 1 jne write_verify ;if old byte to write!=1, goto start pop eax ;reset stack ret ``` [Try it online!](https://tio.run/##rVZfb9s2EH@mPsXFWAfbsF3b2YAgqgusjYsBQxegHbCHOjAo6mQpk0RNpBNl3T57dkdJlpQUQ4ctDzYl3h1/f47nBNLEj0paePVqe/0OXsNLmxUv5UKaDHzI@WseYRqdr/s7c10/KR3iQlMgqljDyMPKYplDklvY76W1ZRIcLe7343EkjVUyTScTiI65GqtYltOJ72UyyceTz@bBWMzGu5Er9MObtx0SW9ndaOKfImKswmNWwPztkwhXdzf6t2l/jdqzjD0GC@XvvJ13UGpIkiToBw3oz3M9LxKEeXa@dtk6uK3Pes9SYArzq0HC6vW3p0CliweYX0OQ5LKk1S0sLMk4iHdrCqCcoqSKEYx2@fTNg0UzvYQX5sXC7PIRfDO@J9TqFD6B7iSn6xxd4o9YXU5H9R6w920C/AlVFXZJA/r@o0FlE53XAD1xSHUgU2enxx@Xnid8XWAOUZKiB81fpu8Ag2pGPVIJP0pKY0GWh2OG1CVWu3wYc0ouM5x4ojiaGJbVmoJTeYDr/YerXz/Qa124EsLngCQ/gASlc2Ml1UkMmFiX1H1gY5nzoZ5Q4e@iReFjWG0yorJZeoIhfUJTzFfrG4cLfIMWamwByQrjzBwmjO6@TOiRFssF0DtIJZ9BUnH6xQyCY9Q@rdZ1ZZnO4HtP8CVYVhdLwT3IrQ@sTUMPJWlh5B06rSBEo8qksLokDd2R@zssk@jBaXpw2CjMJH9gI0TAQriNsC0ZVM@0@7jd/rTf/nzVJIUUUemSGde0ya8oYurLDvqyWp1/CX1qEH@rw9Aks6cUnGxKH9kM1iPxBGMvkcsneYgV6KgOZTX/mcYz5zo2H7e/sIV9GsKnj81XUyBU0@m0NraQxtBDQytkWoy8tiDVurgkJfkoqeKaIpHrqM6a/vhErXHjEZVTu7grIHokn/osenTd6SEBXwmfi5tT59FeirJm6jr24gZ86rmIG73tzqjUWVOE2X9H6@fc23IhKuZIiGhVoruF447RpHFH3OYInQzELGYClHm2Wc6A3/0ne2Ho7/9mbW2uuzwJjTYeV0OPXeuG5HF9wb7K5DrUyWGx3hp42zLsWzq0jQZN3zdDHYBQogzbYr0OcK9X/Q0mfv5FVzm2M5VtI4/ysJkewpc8OXKa0lxtxlvQ16ZXv@kueqPol8uxP41ImdaVe5IJ8PkLkgiwKuiHAamyTI/UjaQZY7qlMv1RBj7Fct2zzTBjRixoipeW7OuwXz71qwW6og5R8aEH8YIRCjfCc7yvN/qjmzKYU5PcNXYrEuHSaTjMO9usZnDQziuGJpqOpqEn2ranHUUTsUT7SP87Pf4N "Bash – Try It Online") -7 bytes and -3 bytes thanks to @EasyasPi [Answer] # [C (clang)](http://clang.llvm.org/), `-DZ=lseek(d,0` + 139 = 152 bytes ``` g,j,x,d,s,i,c;f(n){x=0;d=open(n,2);s=Z,2);for(j=2;j--;x++){Z,0);for(i=s;i--;write(d,&x,1));Z,0);for(i=s;i--;read(d,&c,1),c!=x&&x--&&j--);}} ``` [Try it online!](https://tio.run/##lY/Ba4MwGMXP7V@ReZCEfpnOa8igq54GG7SDgZciSbSxGsVkLEP81@csPQy6007v4/3e9@AJKprCVPNcQQ0eJFjQIFiJDRk9j5nkXa8MNpAQZnl@kbIbcM0TVlPK/GZDxhziq6u5ZXpxPwftFJYQengghP3hgyrkBYsFg7jjPgw9pWG4NBI2TXMUvR736fueJ3DIsufjIXvj8fXMXlKerLVxqC20wWRcrVf2yzrV4kCJU4e2Tzv0iCLX9lFx77wLCPtNnJSXH22P6O42UeLgvz/T/C3KpqjsTNOcN1ap8zIq/gE "C (clang) – Try It Online") Takes the filename as an argument Ungolfed: ``` #include <unistd.h> int g,j,x,d,s,i,c; void f(char*n){ x=0; /*Byte to write*/ d=open(n,O_RDWR); s=lseek(d,0,SEEK_END); /*Get size of file*/ j=0; for(j=0;j<2;j++){ /*Write Pass*/ lseek(d,0,SEEK_SET); /*Start writing from start of file*/ for(i=0;i<s;i++){ write(d,&x,1); } /*Verification Pass*/ lseek(d,0,SEEK_SET); for(i=0;i<s;i++){ read(d,&c,1); if(c!=x)x--,j--; /*If verification fails, repeat loop with the same value*/ } x++; } } ``` [Answer] # Tcl, 286 bytes ``` proc f {o i l} {seek $o 0 set s [string repeat $i $l] puts -nonewline $o $s flush $o seek $o 0 return [string equal [read $o $l] $s]} set n [open $argv r+] fconfigure $n -translation binary seek $n 0 end set m [tell $n] while {![f $n "\0" $m]} {} while {![f $n "\xff" $m]} {} ``` Not really optimized that well. I tried what I could, but I don't know that much about Tcl. Save as "f.tcl" and run on Unix with `tclsh f.tcl "your filename"`. Make sure there's exactly one argument! I tested this on a plain file, but it should work on a device file as well. Setting variables and indexing is more involved in Tcl, so I decided to put the common code between the passes into a function. Then I call it first with "\0", and repeat while it fails to verify. I do the same thing with "\xff". I flushed after writes; it might not be necessary. `fconfigure -translation binary -buffering none` is longer. -2 bytes by removing quotes around `r+`. ]
[Question] [ Since I am INSANELY hyped for the [Final Fantasy XV Uncovered event](http://www.finalfantasyxv.com/uncovered), I want *you* to write me a program to tell me when it is!!! # The input Your take input in the form of `HH:MM XDT`, where `HH` is a number in the range `1-12`, `MM` is a number between `0-60`, and `XDT` is a time zone, with `X` being one of `E` (eastern, UTC-4), `C` (central, UTC-5), `P` (pacific, UTC-7), or `M` (mountain, UTC-6). This is a time assumed to be PM. Valid inputs include: ``` 1:00 EDT (1 PM Eastern Daylight Time) 4:05 MDT (4:05 PM Mountain Daylight Time) 12:23 PDT (12:23 PM Pacific Daylight Time) 1:10 CDT (1:10 PM Central Daylight Time) ``` The input may be assumed to be valid. # The output Your program must do the following: 1. Convert the given time to PDT and output `It is XX:XX PM PDT.`, where `XX:XX` is the converted time. Note that you do *not* need to handle any case where converting the time would cross the AM/PM boundary. 2. Print one of the following: 1. If the converted time is *before* 6:00 PM PDT, print `X minutes until the pre-show!`, replacing `X` with the number of minutes until 6:00 PM PDT. 2. If the converted time is *after or equal to 6:00 PM PDT and before 7:00 PM PDT*, print `Pre-show started X minutes ago; UNCOVERED is starting in Y minutes!`, where `X` is the number of minutes that have passed since 6:00 PM PDT, and `Y` is the number of minutes until 7:00 PM PDT. 3. If the converted time is *after or equal to 7:00 PM PDT*, print `UNCOVERED started X minutes ago!`, where `X` is the number of minutes that have passed since 7:00 PM PDT. Each string printed *must* be followed by a newline. # Scoring This is code golf, so the shortest program wins. [Answer] # Python (335 bytes) ``` t=raw_input().replace(*': ').split();x='PMCE'.index(t[2][0]);t[0]=int(t[0])+x;print '%s:%s PM PDT' % tuple(t[:1]);x=t[0]*60+int(t[1]);print ['%s minutes until the pre-show!'%(360-x),'Pre-show started %s minutes ago; UNCOVERED is starting in %s minutes!'%((x-360),(420-x)), 'UNCOVERED started %s minutes ago!'%(x-420)][(x>360)+(x>420)] ``` Output: ``` 1:00 MDT 2:00 PM PDT 240 minutes until the pre-show! 6:00 CDT 8:00 PM PDT UNCOVERED started 60 minutes ago! 6:50 PDT 6:50 PM PDT Pre-show started 50 minutes ago; UNCOVERED is starting in 10 minutes! ``` [Answer] # Lua, ~~357~~ ~~335~~ 332 bytes **Thanks to [@Katenkyo](https://codegolf.stackexchange.com/users/41019/katenkyo) for chopping off 22 bytes.** Golfed: ``` h,m,t=(...):match("(%d+):(%d+) (.)")f=tonumber h=(f(h)-("PMCE"):find(t))%12+1m=f(m)print("It is "..h..":"..m.." PM PDT.")a=" minutes"b="UNCOVERED"n=(6-h)*60-m r=h<6 and n..a.." until the pre-show!"or h<7 and"Pre-show started "..m..a.." ago; "..b.." is starting in "..(n+60)..a.."!"or b.." started "..(m+(h-7)*60)..a.." ago!"print(r) ``` ([Try it online](http://www.lua.org/cgi-bin/demo)) Ungolfed: ``` n = "7:10 CST" h,m,t = n:match("(%d+):(%d+) (.)") h = (tonumber(h) - ("PMCE"):find(t))%12 + 1 m = tonumber(m) print("It is "..h..":"..m.." PM PDT.") n = (6-h)*60-m if h<6 then r=n.." minutes until the pre-show!" elseif h<7 then r="Pre-show started "..m.." minutes ago; UNCOVERED is starting in "..(n+60).." minutes!" else r="UNCOVERED started "..(m+(h-7)*60).." minutes ago!" end print(r) ``` [Answer] ## JavaScript (ES6), 257 bytes ``` s=>(t=` minutes`,a=s.match(/(\d+):(\d+) (.)/),h=+a[1]+"PMCE".search(a[3]),m=420-h*60-a[2],`It is ${h}:${a[2]} PM PDT ${h<6?m-60+t+` until the pre-show`:h<7?`Pre-show started ${60-m+t} ago; UNCOVERED is starting in ${m+t}`:`UNCOVERED started ${-m+t} ago`}!`) ``` [Answer] # C, 333 bytes ``` #define p printf char s[9];main(t){gets(s);s[5]=0;s[1]-=2+s[6]%2-s[6]%3;s[1]<48&&(s[1]+=10,--*s); t=*s*600+s[1]*60+s[3]*10+s[4]-32568;p("It is %s PM PDT.",s); t<0?p("%d minutes until the pre-show!",-t):t<60?p( "Pre-show started %d minutes ago; UNCOVERED is starting in %d minutes!",t,60-t): p("UNCOVERED started %d minutes ago!",t-60);} ``` 333 bytes after removing the unnecessary newlines (all but the one after the #define). [Answer] # PHP, ~~347~~ ~~328~~ ~~327~~ 322 bytes ``` <?=$u="UNCOVERED";$m=" minutes";$s=" started ";$p="re-show";$z=['P'=>0,'M'=>1,'C'=>2,'E'=>3];$i=explode(":",$argv[1]);$h=$i[0]%12-$z[$argv[2][0]];$o=$i[1];$t=60-$o;$a="$s$o$m ago";echo"It is ".(($h+11)%12+1).":$o".($h<0?" A":" P")."M PDT.\n".($h<6?$t."$m until the p$p!":($h<7?"P$p$a; $u is starting in $t$m!":"$u$a!"));?> ``` ### exploded view ``` <?= $u = "UNCOVERED"; $m = " minutes"; $s = " started "; $p = "re-show"; $z = [ 'P' => 0, 'M' => 1, 'C' => 2, 'E' => 3 ]; $i = explode(":", $argv[1]); $h = $i[0]%12 - $z[$argv[2][0]]; $o = $i[1]; $t = 60 - $o; $a = "$s$o$m ago"; echo "It is " . (($h+11)%12+1) . ":$o" . ($h < 0 ? " A" : " P") . "M PDT.\n" . ($h < 6 ? $t . "$m until the p$p!" : ($h < 7 ? "P$p$a; $u is starting in $t$m!" : "$u$a!")); ?> ``` Runs as `php script.php HH:MM XDT`. Takes in the time and time zone as `$argv` entries, regexes `$argv[1]` out into `$i = [HH, MM]`, determines the time zone from the first character in `$argv[2]`, maths out how many minutes past 6PM PDT that is, then ternaries the `echo`. Could drop 2 bytes by using `$u=UNCOVERED`, but it'd be the only error here and I like that this works cleanly. [Answer] # PowerShell 292 Bytes ``` $r,$i,$s,$u="re-show"," minutes"," start","UNCOVERED";$h,$m,$z=$args[0]-split":| ";$h=+$h-"PMCE".IndexOf($z[0]);"It is $h`:$m PM PDT.";if(($t=$h*60+$m-360)-lt0){"$($t*-1)$i until the p$r!"}else{if($t-gt59){"$u$s`ed $($t-60)$i ago!"}else{"P$r$s`ed $t$i ago; $u is$s`ing in $(($t-60)*-1)$i!"}} ``` --- **Less Golfed Explanation** ``` # Some string literals. $r,$i,$s,$u,$g="re-show"," minutes"," start","UNCOVERED"," ago" # Get the hours, minutes and zone into variables. $h,$m,$z=$args[0]-split":| " # Offset the time based on the passed timezone. $h=+$h - "PMCE".IndexOf($z[0]) # Display current PDT time. "It is $h`:$m PM PDT." # Based on adjusted time value for PDT determine what string to show. # Several string literals were used to save space. if(($t=$h*60+$m-360)-lt0){ # Show has not started yet "$($t*-1)$i until the p$r!" }else{ if($t-gt59){ # Between 6 and 7 "$u$s`ed $($t-60)$i$g!" }else{ # It's after 7. Should have check more often. "P$r$s`ed $t$i$g; $u is$s`ing in $(($t-60)*-1)$i!" } } ``` The literal for " ago" was removed in code but for now left in explanation in case of other changes. ]
[Question] [ ## Find the Intersection of 2 Sets in Unioned Interval Notation Given two sets of real numbers described as the union of intervals, output a description of the intersection of these two sets as a union of the same type of interval. The input sets will always consist of unions of intervals such that each interval begins and ends at a different integer (i.e. no interval has measure zero). However, different intervals in the same set may begin or end at the same integer or overlap. The output set must also be a union of intervals which begin and end at integers, but *no interval in the output may overlap any other* even at a single integer. The input may take any form that is suitable for your language of choice, as long as it consists of two lists of pairs of integers. For example, you may represent the set [![equation](https://i.stack.imgur.com/gOU13.png)](https://i.stack.imgur.com/gOU13.png) as: ``` [-10,-4]u[1,5]u[19,20] ``` Or as: ``` [[-10,-4],[1,5],[19,20]] ``` Or as: ``` [-10,-4;1,5;19,20] ``` Your output representation must be identical to your input representation (except that it is only one list of intervals instead of two). ### Examples/Test cases: Input: ``` [[[-90,-4],[4,90]],[[-50,50]]] ``` Output: ``` [[-50,-4],[4,50]] ``` In other words, we're intersecting the set that contains all real numbers between -90 and -4 and all real numbers between 4 and 90 with the set that contains all real numbers between -50 and 50. The intersection is the set containing all real numbers between -50 and -4 and all real numbers between 4 and 50. A more visual explanation: ``` -90~~~~~-4 4~~~~~90 intersected with -50~~~~~~~~50 yields: -50~-4 4~~50 ``` --- Input: ``` "[-2,0]u[2,4]u[6,8] [-1,1]u[3,5]u[5,9]" ``` Output: ``` "[-1,0]u[3,4]u[6,8]" ``` --- Input: ``` [-9,-8;-8,0;-7,-6;-5,-4] [-7,-5;-1,0;-8,-1] ``` Output: ``` [-8,0] ``` Invalid Output (even though it represents the same set): ``` [-8,0;-7,-5;-5,0] ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest source in bytes wins, as potentially modified by the following bonus. ### Bonus: -15% if you also support positive and negative infinity as bounds of intervals. You may choose what token(s) represent these numbers. (And yes, infinity is a number in the hyperreals ;P) [Answer] # Mathematica, 41 bytes - 15% = 34.85 Mathematica has a built-in function for interval intersection. ``` List@@IntervalIntersection@@Interval@@@#& ``` Example: ``` In[1]:= List@@IntervalIntersection@@Interval@@@#&[{{{-90, -4}, {4, Infinity}}, {{-50,Infinity}}}] Out[1]= {{-50, -4}, {4, Infinity}} ``` [Answer] ## Haskell, 145 bytes ``` import Data.List q(a,b)=[a,a+0.5..b] p@(a,b)%(h:t)|h==b+0.5=(a,h)%t|1<2=p:(h,h)%t p%_=[p] a#b|h:t<-nub$sort$intersect(q=<<a)$q=<<b=(h,h)%t|1<2=[] ``` Usage example: `[(-2.0,0.0),(2.0,4.0),(5.0,6.0),(6.0,8.0)] # [(-1.0,1.0),(3.0,5.0),(5.0,9.0)]` -> `[(-1.0,0.0),(3.0,4.0),(5.0,8.0)]`. How it works: ``` q=<<a -- turn each pair in the 1st input list into -- lists with halves in between (e.g. (1,4) -> -- [1,1.5,2,2.5,3,3.5,4]) and concatenate them -- to a single list q=<<b -- same for the second input list nub$sort$intersect -- sort the intersection of those lists -- and remove duplicates h:t<- -- call the first element h and the rest t (h,h)%t -- start rebuilding the intervals |1<2=[] -- if there's no first element h, one of the -- input lists is empty, so the output is also -- empty p@(a,b)%(h:t) -- an interval p = (a,b), build from a list (h:t) =(a,h)%t -- becomes (a,h) |h==b+1 -- if h equals b+0.5 p:(h,h)%t -- or is put in the output list, followed by -- a new interval starting with (h,h) |1<2 -- otherwise p%_=[p] -- base case of the interval rebuilding function ``` I'm putting the "half"-values `x.5` in the list, because I need to distinguish `(1,2),(3,4)` from `(1,4)`. Without `x.5`, both would become `[1,2,3,4]`, but with `x.5` the 1st becomes `[1,1.5,2,3,3.5,4]` (which lacks `2.5`) and the second `[1,1.5,2,2.5,3,3.5,4]`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 bytes ``` .5×(⊢/,⊃)¨{⍵⊂⍨1,1<2-/⍵}⊃∩/∨⍤∊¨…/¨¨2×⎕ ``` [Try it online!](https://tio.run/##NY6xDoIwEIZ3n@JGmoC0lSIkvowJ4GLUwUFjTAwOEhLcjLsxpk5MvkB9k3sRvBZcrnff/ff/nW@WQbafL9eLIN9t81WWZx1Wl6Ibq@/dw/oR@lifmdEHbD5Yl9ho4YuZDEKaj7TC6h1ipbF5YlUbjadXaLTR8nvH681adaNi5HmmTTmYNmLgRZByRi8Zl6ZVHBRng0YCp4UEK4shsSqiAgQ1E1BUFaTsr07JMCFG1d2Zdkokdp1yYf29pcpRMegSImLwES5N9Wn2TxJi9gM "APL (Dyalog Extended) – Try It Online") A full program which takes a nested array in STDIN and returns a nested array. Code fixed by bubbler. ]
[Question] [ This challenge is based on a problem described in [*D. Parnas, On the criteria to be used in decomposing systems into modules*](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2979&context=compsci), and elaborated upon in [*J. Morris, Real Programming in Functional Languages*](http://research.microsoft.com/en-us/um/people/simonpj/Papers/other-authors/morris-real-programming.pdf). Write a program or function which takes a list of book titles from `stdin` or as an argument, in a reasonable, convenient format for your language. For example, ``` Green Sleeves Time Was Lost ``` or ``` ("Green Sleeves";"Time Was Lost") ``` Return or print to `stdout` an alphabetized list of the keywords, showing their context within the original titles by enclosing each keyword in angle braces (`<` and `>`). As with input, output can be in a reasonable format which is convenient for your language- newline-separated lines, a list of strings, etc: ``` <Green> Sleeves Time Was <Lost> Green <Sleeves> <Time> Was Lost Time <Was> Lost ``` Titles will consist of a series of keywords separated by a single space. Keywords will contain only alphabetic characters. Keywords are to be sorted [lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order). Titles will be unique, and keywords will be unique within each title but the same keyword may exist in several titles. If a keyword exists in more than one title, the output should list each appearance *in an arbitrary order*. For example, given this input: ``` A Dugong A Proboscis ``` A valid output would be either: ``` <A> Proboscis <A> Dugong A <Dugong> A <Proboscis> ``` Or: ``` <A> Dugong <A> Proboscis A <Dugong> A <Proboscis> ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")- the winner is the shortest solution in bytes. Standard loopholes are disallowed. [Answer] # Pyth, ~~25~~ ~~24~~ 22 bytes ``` VSsm,Rdcd\ QAN:HGjG"<> ``` [Try it online.](https://pyth.herokuapp.com/?code=VSsm%2CRdcd%5C%20QAN%3AHGjG%22%3C%3E&input=%5B%22Green+Sleeves%22%2C%22Time+Was+Lost%22%5D&debug=0) Takes input as an array of lines, like `["Green Sleeves","Time Was Lost"]`. ### Explanation ``` VSsm,Rdcd\ QAN:HGjG"<> implicit: Q = evaluated input m Q map input lines: cd\ split input line to words ,Rd replace each word by pair [word, entire line] s concatenate results for all input lines S sort the array of pairs lexicographically V loop over the array AN assign the word to G and the corresponding line to H jG"<> put the word between <> :HG replace the word by the above in the line and print ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), 55 bytes Perhaps this could be made shorter, but I'm not sure how... ``` P+UqR £XqS m_+S+X) q', n £Xs1+XbS)rXs0,XbS),@"<{X}>")qR ``` ### How it works ``` P+UqR m@XqS m_+S+X) q', n m@Xs1+XbS)rXs0,XbS),@"<{X}>")qR // Implicit: U = input string, S = a space, P = empty string UqR m@ // Split input at newlines, then map each item X to: XqS m_ // X split at spaces, with each item Z mapped to: +S+X) // Z + a space + X. P+ q', // Parse the result as a string, and split at commas. Due to JS's default // array-to-string conversion (joining with commas), this flattens the array. n // Sort the result lexicographically. m@Xs1+XbS // Map each item X to everything after the first space, rXs0,XbS // replacing the original keyword with @"<{X}>" // "<" + keyword + ">". qR // Join the result with newlines. // Implicit: output last expression ``` [Answer] ## CJam, ~~41~~ ~~36~~ 32 bytes ``` q~{:AS/{A1$/"<>"@**}/}%{'</1=}$p ``` [Test it here.](http://cjam.aditsu.net/#code=q~%7B%3AAS%2F%7BA1%24%2F%22%3C%3E%22%40**%7D%2F%7D%25%7B'%3C%2F1%3D%7D%24p&input=%5B%22Green%20Sleeves%22%20%22Time%20Was%20Lost%22%20%22A%20Dugong%22%20%22A%20Proboscis%22%5D) [Answer] ## Haskell, 113 bytes ``` import Data.List g l=[(m,h++('<':m++['>']):t)|(h,m:t)<-zip(inits l)$tails l] f=map(unwords.snd).sort.(>>=g.words) ``` Usage example: `f ["Green Sleeves","Time Was Lost"]` -> `["<Green> Sleeves","Time Was <Lost>","Green <Sleeves>","<Time> Was Lost","Time <Was> Lost"]`. ]
[Question] [ ## What is Toothpick Sequence? According to [Wikipedia](https://en.wikipedia.org/wiki/Toothpick_sequence) > > In geometry, the toothpick sequence is a sequence of 2-dimensional > patterns which can be formed by repeatedly adding line segments > ("toothpicks") to the previous pattern in the sequence. > > > The first stage of the design is a single "toothpick", or line > segment. Each stage after the first is formed by taking the previous > design and, for every exposed toothpick end, placing another toothpick > centered at a right angle on that end. > > > This process results in a pattern of growth in which the number of > segments at stage n oscillates with a fractal pattern between 0.45n2 > and 0.67n2. If T(n) denotes the number of segments at stage n, then > values of n for which T(n)/n2 is near its maximum occur when n is near > a power of two, while the values for which it is near its minimum > occur near numbers that are approximately 1.43 times a power of two. > The structure of stages in the toothpick sequence often resemble the > T-square fractal, or the arrangement of cells in the Ulam–Warburton > cellular automaton. > > > All of the bounded regions surrounded by toothpicks in the pattern, > but not themselves crossed by toothpicks, must be squares or > rectangles. It has been conjectured that every open rectangle in the > toothpick pattern (that is, a rectangle that is completely surrounded > by toothpicks, but has no toothpick crossing its interior) has side > lengths and areas that are powers of two, with one of the side lengths > being at most two. > > > ## Task You must make a program or function that take input from STDIN, function argument, or commandline argument and make a tootpick fractal at that stage. Leading and trailing newline is prohibited except if it is unavoidable. Bounding box must be at minimum, including leading and trailing space. For inital line, we make two `\` diagonal in space. The input is guaranteed to be less than two thousand. At least one line have non-space character. Trailing space is allowed. ## Test Cases ``` 1 \ \ 5 \ /\ /\ / /\ \/\/\ \ \ \ \ \/\/\ \/ / \/ \/ \ ``` [Answer] ## CJam, ~~99~~ 93 bytes This got rather long... ``` "\ "_W%]{{Sf+W%z}4*2ew{2fewz{_sa"\//\\"4S**4/^_,3={:.e>W%2/\}&;}%z{\)[[email protected]](/cdn-cgi/l/email-protection)>+}:Ff*}%{F}*}q~(*N* ``` [Test it here.](http://cjam.aditsu.net/#code=%22%5C%20%22_W%25%5D%7B%7BSf%2BW%25z%7D4*2ew%7B2fewz%7B_sa%22%5C%2F%2F%5C%5C%224S**4%2F%5E_%2C3%3D%7B%3A.e%3EW%252%2F%5C%7D%26%3B%7D%25z%7B%5C)a%40.e%3E%2B%7Df*%7D%25%7B%5C)a%40..e%3E%2B%7D*%7Dq~(*N*&input=13) If you want to test larger inputs, like the 89 on Wikipedia, Dennis's [TryItOnline](http://cjam.tryitonline.net/#code=IlwgIl9XJV17e1NmK1clen00KjJld3syZmV3entfc2EiXC8vXFwiNFMqKjQvXl8sMz17Oi5lPlclMi9cfSY7fSV6e1wpYUAuZT4rfWYqfSV7XClhQC4uZT4rfSp9cmkoKk4q&input=ODk) uses the much faster Java interpreter under the hood and can handle inputs like that in a few seconds. I'm sure there is a lot of room for improvement, and I'll add an explanation once I'm happier with the score... Here is the output for `N = 13`: ``` \ /\ /\ / /\ \/\/\ \ \ \ \/\/\/\ /\/\/ / /\ \ \ /\/\ \ \ /\ / \/\/\ /\ /\ /\ /\/ \ \/\ / /\/ /\/ /\ /\ \/\ \/\/\/\/\/\/\ \/\ \/\ \ \ \ \ \/\ \/\ \/\/\/\/\/\/\ \/\ \/ \/ /\/ /\/ / \/\ \ /\/ \/ \/ \/ \/\/\ / \/ \ \ \/\/ \ \ \/ / /\/\/ \/\/\/\ \ \ \ \/\/\ \/ / \/ \/ \ ``` For my own reference when golfing this further, some other ideas: ``` "\ "_W%]{{Sf+W%z}4*2few2ew::.{+_a"\//\\"4S**4/^_,3={:.e>W%\}&;2/}:z{\)[[email protected]](/cdn-cgi/l/email-protection)>+}ff*{\)[[email protected]](/cdn-cgi/l/email-protection)>+}*}ri(*N* ``` ``` "\ "_W%]{{Sf+W%z}4*2ew{2fewz{_sa"\//\\"4S**4/^_,3={:.e>W%2/\}&;}%{.{\)[[email protected]](/cdn-cgi/l/email-protection)>+}}*}%{\)[[email protected]](/cdn-cgi/l/email-protection)>+}*}q~(*N* ``` [Answer] # JavaScript (ES6), 263 bytes ``` n=>(o=(o=[..." ".repeat(n*2)]).map(_=>o.map(_=>s=c=" ")),(g=a=>s++<n&&g(q=[],a.map(p=>o[p[4]][p[3]]==c&&(o[y=p[1]][x=p[0]]=o[y-1][(b=+p[2])?x-1:x+1]="/\\"[b],q.push([x,++y,!b,b?x+1:x-1,y],[b?x-=2:x+=2,y-2,!b,x,y-3])))))([[n,n,1,n,n]]),o.map(r=>r.join``).join` `) ``` ## Explanation ``` n=>( // n = desired stage o= // o = output grid // [ [ "\\", " " ], [ " ", "\\" ], etc... ] (o=[..." ".repeat(n*2)]) // create an array the size of the grid .map(_=>o.map(_=> // loop over it and return the output grid s= // s = current stage (" " acts the same as 0) c= // c = blank character " " // initialise each element to " " )), (g= // g = compute stage function a=> // a = positions to place toothpicks // [ x, y, isBackslash, checkX, checkY ] s++<n&& // do nothing if we have reached the desired stage g(q=[], // q = positions for the next stage's toothpicks a.map(p=> // p = current potential toothpick position o[p[4]][p[3]]==c&&( // check the position to make sure it is clear o[y=p[1]][x=p[0]]= // place bottom toothpick, x/y = position x/y o[y-1][ // place top toothpick (b=+p[2]) // b = isBackslash ?x-1:x+1 // top toothpick x depends on direction ]="/\\"[b], // set the location to the appropriate character // Add the next toothpick positions q.push([x,++y,!b,b?x+1:x-1,y], [b?x-=2:x+=2,y-2,!b,x,y-3]) ) ) ) )([[n,n,1,n,n]]), // place the initial toothpicks o.map(r=>r.join``).join` ` // return the grid converted to a string ) ``` ## Test ``` Stages: <input type="number" oninput='result.innerHTML=( n=>(o=(o=[..." ".repeat(n*2)]).map(_=>o.map(_=>s=c=" ")),(g=a=>s++<n&&g(q=[],a.map(p=>o[p[4]][p[3]]==c&&(o[y=p[1]][x=p[0]]=o[y-1][(b=+p[2])?x-1:x+1]="/\\"[b],q.push([x,++y,!b,b?x+1:x-1,y],[b?x-=2:x+=2,y-2,!b,x,y-3])))))([[n,n,1,n,n]]),o.map(r=>r.join``).join` `) )(+this.value)' /><pre id="result"></pre> ``` [Answer] # Ruby, 151 bytes Golfed version uses only one loop, `j`, with `i` and `k` calculated on the fly. ``` ->n{m=n*2 s=(' '*m+$/)*m l=m*m+m s[l/2+n]=s[l/2-n-2]=?\\ (n*l-l).times{|j|(s[i=j%l]+s[i-m-2+2*k=j/l%2]).sum==124-k*45&&s[i-m-1]=s[i-1+2*k]="/\\"[k]} s} ``` **Ungolfed in test program** This version uses 2 nested loops. A rarely used builtin is `sum` which returns a crude checksum by adding all the bytes of an ascii string. ``` f=->n{ m=n*2 #calculate grid height / width s=(' '*m+$/)*m #fill grid with spaces, separated by newlines l=m*m+m #calculate length of string s s[l/2+n]=s[l/2-n-2]=?\\ #draw the first toothpick (n-1).times{|j| #iterate n-1 times l.times{|i| #for each character in the string (s[i]+s[i-m-2+2*k=j%2]).sum==124-k*45&& #if checksum of current character + character diagonally above indicates the end of a toothpick s[i-m-1]=s[i-1+2*k]="/\\"[k] #draw another toothpick at the end } } s} #return value = s puts f[gets.to_i] ``` ]
[Question] [ Blackbeard was an English pirate of the early 18th century. Although he was known for looting and taking ships, he commanded his vessels with the permission of their crews. There are no accounts of him ever harming or murdering his captives. This challenge is in honor of the infamous Blackbeard and inspired by [International Talk Like a Pirate Day](https://en.wikipedia.org/wiki/International_Talk_Like_a_Pirate_Day) (September 19). It is also the inverse of [this challenge](https://codegolf.stackexchange.com/q/54301/39462) by [Pyrrha](https://codegolf.stackexchange.com/users/21682/pyrrha). --- # The Challenge Create a program that takes a treasure map as an input (composed of the characters listed below), and outputs it's directions. --- # Input All inputs will consist of `v`, `>`, `<`, `^`, whitespace, and a single `X`. You can assume the following: * the map will never loop or cross itself * the starting arrow will always be the bottommost character in the leftmost column * there will always be a treasure (`X`) A sample input is shown below. ``` >>v >>>>>>v ^ v ^ v ^ v ^ v<< ^ v ^ v ^ >>>>^ >>X ^ >>^ ``` --- # Output The output should be a `", "`-delimited string of directions. Below is the correct output from the above map. ``` E2, N6, E2, S4, E4, N4, E6, S2, W2, S2, E2 ``` A single trailing newline or space is permitted. --- # Examples ``` In: >>>>>>>>>>>>>>>v v v >>>>X Out: E15, S3, E4 In: >>>>>>v ^ v ^ >>>>X Out: N2, E6, S2, E4 In: X ^ ^ ^ Out: N3 In: >>>>>>v ^ v ^ v v >>>>>>X Out: N2, E6, S4, E6 In: X ^ ^ >^ Out: E1, N3 In: >X Out: E1 In: v<<<<< vX<<<^ >>>>^^ >>>>>^ Out: E5, N3, W5, S2, E4, N1, W3 ``` --- **Happy International Talk Like a Pirate Day!** [Answer] # CJam, 78 bytes ``` qN/_:,$W=:Tf{Se]}s:U,T-{_U="><^vX"#"1+'E1-'WT-'NT+'S0"4/=~_@\}g;;]e`{(+}%", "* ``` [Try it online](http://cjam.aditsu.net/#code=qN%2F_%3A%2C%24W%3D%3ATf%7BSe%5D%7Ds%3AU%2CT-%7B_U%3D%22%3E%3C%5EvX%22%23%221%2B'E1-'WT-'NT%2B'S0%224%2F%3D~_%40%5C%7Dg%3B%3B%5De%60%7B(%2B%7D%25%22%2C%20%22*&input=%20%20%3E%3Ev%20%20%20%3E%3E%3E%3E%3E%3Ev%0A%20%20%5E%20v%20%20%20%5E%20%20%20%20%20v%0A%20%20%5E%20v%20%20%20%5E%20%20%20v%3C%3C%0A%20%20%5E%20v%20%20%20%5E%20%20%20v%0A%20%20%5E%20%3E%3E%3E%3E%5E%20%20%20%3E%3EX%0A%20%20%5E%0A%3E%3E%5E). # Explanation The main idea here is to find the longest line (we'll call this length `T`), then pad all lines to the same length and concatenate them (this new string is `U`). This way only a single counter is needed to move in the map. Adding/subtracting `1` means moving to the right/left in the same line, adding/subtracting `T` means moving down/up one line. ``` qN/ e# Split the input on newlines _:, e# Push a list of the line lengths $W=:T e# Grab the maximum length and assign to T f{Se]} e# Right-pad each line with spaces to length T s:U e# Concatenate lines and assign to U ``` Now it's time to set up the loop. ``` ,T- e# Push len(U) - T e# i.e. position of first char of the last line {...}g e# Do-while loop e# Pops condition at the end of each iteration ``` The loop body uses a lookup table and eval to choose what to do. At the beginning of each iteration, the top stack element is the current position. Underneath it there are all the processed NSWE directions. At the end of the iteration, the new direction is placed underneath the position and a copy of it is used as the condition for the loop. Non-zero characters are truthy. When an X is encountered, 0 is pushed as the direction, terminating the loop. ``` _U= e# Push the character in the current position "><^vx"# e# Find the index in "><^Vx" "..."4/ e# Push the string and split every 4 chars e# This pushes the following list: e# [0] (index '>'): "1+'E" pos + 1, push 'E' e# [1] (index '<'): "1-'W" pos - 1, push 'W' e# [2] (index '^'): "T-'N" pos - T, push 'N' e# [3] (index 'v'): "T+'S" pos + T, push 'S' e# [4] (index 'X'): "0" push 0 =~ e# Get element at index and eval _@\ e# From stack: [old_directions position new_direction] e# To stack: [old_directions new_direction position new_direction] e# (You could also use \1$) e# new_direction becomes the while condition and is popped off ``` Now the stack looks like this: `[directions 0 position]`. Let's generate the output. ``` ;; e# Pop position and 0 off the stack ] e# Wrap directions in a list e` e# Run length encode directions e# Each element is [num_repetitions character] { e# For each element: (+ e# Swap num_repetitions and character }% e# End of map (wraps in list) ", "* e# Join by comma and space ``` [Answer] # CJam, 86 bytes ``` qN/_,{1$=cS-},W=0{_3$3$==_'X-}{"^v<>"#_"NSWE"=L\+:L;"\(\ \)\ ( )"S/=~}w];Le`{(+}%", "* ``` [Try it online](http://cjam.aditsu.net/#code=qN%2F_%2C%7B1%24%3DcS-%7D%2CW%3D0%7B_3%243%24%3D%3D_'X-%7D%7B%22%5Ev%3C%3E%22%23_%22NSWE%22%3DL%5C%2B%3AL%3B%22%5C(%5C%20%5C)%5C%20(%20)%22S%2F%3D~%7Dw%5D%3BLe%60%7B(%2B%7D%25%22%2C%20%22*&input=%3E%3E%3E%3E%3E%3Ev%0A%5E%20%20%20%20%20v%0A%5E%20%20%20%20%20v%0A%20%20%20%20%20%20v%0A%20%20%20%20%20%20%3E%3E%3E%3E%3E%3EX) Explanation: ``` qN/ Get input and split into rows. _, Calculate number of rows. { Loop over row indices. 1$= Get row at the index. c Get first character. S- Compare with space. }, End of filter. The result is a list of row indices that do not start with space. W= Get last one. This is the row index of the start character. 0 Column number of start position. Ready to start tracing now. { Start of condition in main tracing loop. _3$3$ Copy map and current position. == Extract character at current position. _'X- Check if it's the end character `X. } End of loop condition. { Start of loop body. Move to next character. "^v<>" List of directions. # Find character at current position in list of directions. _ Copy direction index. "NSWE" Matching direction letters. = Look up direction letter. L\+:L; Append it to directions stored in variable L. "\(\ \)\ ( )" Space separated list of commands needed to move to next position for each of the 4 possible directions. S/ Split it at spaces. = Extract the commands for the current direction. ~ Evaluate it. }w End of while loop for tracking. ]; Discard stack content. The path was stored in variable L. Le` Get list of directions in variable L, and RLE it. { Loop over the RLE entries. (+ Swap from [length character] to [character length]. }% End of loop over RLE entries. ", "* Join them with commas. ``` [Answer] # Javascript (ES6), 239 bytes ``` a=>(b=a.split` `,b.reverse().some((c,d)=>c[0]!=' '&&((e=d)||1)),j=[],eval("for(g=b[e][f=0];b[e][f]!='X';g=b[e][f],j.push('NSEW'['^v><'.indexOf(i)]+h))for(h=0;g==b[e][f];e+=((i=b[e][f])=='^')-(i=='v'),f+=(i=='>')-(i=='<'),h++);j.join`, `")) ``` Explanation: ``` a=>( b = a.split('\n'), // loops through list from bottom to find arrow b.reverse().some( (c, d)=> // if the leftmost character is not a space, saves the index and exit // the loop // in case d == 0, the ||1 makes sure the loop is exited c[0] != ' ' && ((e = d) || 1) ), j = [], // array that will hold the instructions eval(" // uses eval to allow a for loop in a lambda without 'return' and {} // loops through all sequences of the same character // e is the first coordinate of the current character being analyzed // f is the second coordinate // defines g as the character repeated in the sequence // operates on reversed b to avoid using a second reverse // flips ^ and v to compensate for(g = b[e][f = 0]; b[e][f] != 'X'; // keep finding sequences until it finds the X g = b[e][f], // update the sequence character when it hits the start of a // new sequence j.push('NSEW'['^v><'.indexOf(i)] + h)) // find the direction the sequence is // pointing to and add the // instruction to j // loops through a single sequence until it hits the next one // counts the length in h for(h = 0; g == b[e][f]; // loops until there is a character that isn't part of // the sequence // updates e and f based on which direction the sequence is pointing // sets them so that b[e][f] is now the character being pointed toward e += ((i = b[e][f]) == '^') - (i == 'v'), f += (i == '>') - (i == '<'), // increments the length counter h for each character of the sequence h++); // return a comma separated string of the instructions j.join`, ` ") ) ``` [Answer] # JavaScript(ES6), 189 Test running the snippet below in an EcmaScript 6 compliant browser. ``` f=m=>{(m=m.split` `).map((r,i)=>r[0]>' '?y=i:0);for(x=o=l=k=p=0;p!='X';++l,y+=(k==1)-(k<1),x+=(k>2)-(k==2))c=m[y][x],c!=p?(o+=', '+'NSWE'[k]+l,l=0):0,k='^v<>'.search(p=c);alert(o.slice(7))} // Testable version, no output but return (same size) f=m=>{(m=m.split` `).map((r,i)=>r[0]>' '?y=i:0);for(x=o=l=k=p=0;p!='X';++l,y+=(k==1)-(k<1),x+=(k>2)-(k==2))c=m[y][x],c!=p?(o+=', '+'NSWE'[k]+l,l=0):0,k='^v<>'.search(p=c);return o.slice(7)} // TEST out = x => O.innerHTML += x+'\n'; test = [[`>>>>>>>>>>>>>>>v v v >>>>X`,'E15, S3, E4'] ,[`>>>>>>v ^ v ^ >>>>X`,'N2, E6, S2, E4'] ,[`X ^ ^ ^`,'N3'] ,[`>>>>>>v ^ v ^ v v >>>>>>X`,'N2, E6, S4, E6'] ,[` X ^ ^ >^`,'E1, N3'] ,[`>X`,'E1'] ,[`v<<<<< vX<<<^ >>>>^^ >>>>>^`,'E5, N3, W5, S2, E4, N1, W3']]; test.forEach(t=>{ var k = t[1]; var r = f(t[0]); out('Test ' + (k==r ? 'OK' : 'Fail') +'\n'+t[0]+'\nResult: '+r +'\nCheck: '+k+'\n'); }) ``` ``` <pre id=O></pre> ``` **Less golfed** ``` f=m=>{ m=m.split('\n'); // split in rows x = 0; // Starting column is 0 m.forEach( (r,i) => r[0]>' '? y=i : 0); // find starting row o = 0; // output string p = 0; // preceding character l = 0; // sequence length (this starting value is useless as will be cutted at last step) k = 0; // direction (this starting value is useless as will be cutted at last step) while(p != 'X') // loop until X found { c = m[y][x]; // current character in c if (c != p) // changing direction { o +=', '+'NSWE'[k]+l; // add current direction and length to output l = 0 // reset length ); p = c; k = '^v<>'.search(c); // get new current direction // (the special character ^ is purposedly in first position) ++l; // increase sequence length y += (k==1)-(k<1); // change y depending on direction x += (k>2)-(k==2); // change x depending on direction } alert(o.slice(7)); // output o, cutting the useless first part } ``` ]
[Question] [ Jack likes the C programming language, but hates writing expressions like `V=a*b\*h;` to multiply values. He would like to just write `V=abh;` instead; why should the compiler moan about `abh` being undefined? Since `int a, b, h;` are defined, can't it just deduce multiplication? Help him implement a parser that deciphers a single multiplication term, provided the set of variables defined in current scope is known. For simplicity, no numbers will be included (i.e. `2abh`), only single-character variables. The input is **a multiplication term T**, fulfilling regexp: ``` [a-zA-Z_][a-zA-Z_0-9]* ``` **and a variable set Z** . A parsing P of the term T over variable set Z is a string fulfilling the following conditions: 1. P can be turned back into T by removing all `*` characters 2. The string either is a variable name from Z or consists of proper variable names from Z split up by single `*` characters. The solution should print all possible ways to parse the input. Examples: ``` Vars a, c, ab, bc Term abc Solution ab*c, a*bc Vars ab, bc Term abc Solution - Vars - Term xyz Solution - Vars xyz Term xyz Solution xyz Vars width, height Term widthheight Solution width*height Vars width, height Term widthheightdepth Solution - Vars aaa, a Term aaaa Solution aaa*a, a*aaa, a*a*a*a ``` The input (the list of variables and the term) may be supplied in any way suitable for the language. The output can be in any sensible form (one result per line or a comma-separated list etc.) - but it should be unambiguous and possible to read. Empty output is acceptable if there is no possible parsing of a term (in the examples I used '-' for clarity). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. [Answer] # Pyth, 18 chars ``` mj\*dfqzsTsm^Qkhlz ``` This solution is adapted from my [Interpreting Fish](https://codegolf.stackexchange.com/a/48661/20080) solution. The problems are actually very similar. Expects input as such: ``` aaaa "a", "aaa" ``` Gives output like this: ``` ['a*aaa', 'aaa*a', 'a*a*a*a'] ``` [Try it here.](https://pyth.herokuapp.com/?code=mj%5C*dfqzsTsm%5EQkhlz&input=aaaa%0A%22a%22%2C+%22aaa%22) * `sm^Qkhlz`: Generates all sequences of variables containing up to the length of the input string number of variables. * `fqzsT`: Filters out the variable sequences that match the input string * `mj\*d`: Inserts the `*` symbol and prints. [Answer] # Python 2 - ~~147~~ 94 bytes --- ``` R=lambda S,V,F=[]:S and[R(S[len(v):],V,F+[v])for v in V if v==S[:len(v)]]or print("*".join(F)) ``` This defines a function `R` to be used like: ``` >>> R("abc", ["a", "bc", "ab", "c"]) ``` Prints output like: ``` a*bc ab*c ``` [Answer] # JavaScript (ES6) 111 Adapted from [my "fish" answer](https://codegolf.stackexchange.com/a/48693/21348), the main difference is finding all solutions, not just the first. ``` F=(v,t)=>(k=(s,r)=>s?v.map(v=>s.slice(0,l=v.length)==v&&k(s.slice(l),[...r,v])):console.log(r.join('*')))(t,[]) ``` The output is printed to the console. The function result have no meaning and must be discarded. **Test** In Firefox/FireBug console ``` F(['a','c','ab','bc'],'abc') a*bc ab*c F(['ab','bc'],'abc') F(['aaa','a'],'aaaa') aaa*a a*aaa a*a*a*a F(['xyz'],'xyz') xyz ``` ]
[Question] [ Here is a fairly simple ASCII depiction of an open book: ``` |\ | \ | \ | \ | \__________ | || | | || Lorem i | \ || psum do | \ || lor sit | \ || amet, | \ || consect | \||_________| ``` Notice that the text portion is only on the right page and is 7 characters wide by 5 tall. Also notice that the top edge of the book has 5 backslashes and 10 underscores. The 10 comes from the text width plus 3 and the 5 is half of 10. Using the same scaling format we can resize the book to have a text area *w* characters wide and *h* high, where *w* is any **odd** positive integer and *h* is any positive integer. Some *w*×*h* books: 1×1, 1×2, 3×2 ``` |\ |\ | \ |\ | \____ | \______ | \____ | || | | || | | || | | || L | \ || Lor | \ || L | \ || o | \ || em | \||___| \||___| \||_____| ``` The number of underscores at the top is always *w*+3 and the number of backslashes is always (*w*+3)/2. # Goal Write a progam that takes a filename and *w* and *h* as command line arguments, and outputs a book with those text dimensions to stdout, displaying the contents of the file. When the file has more text than will fit in one page the `N` key should print the next page and `B` should go back a page. Nothing should happen if `B` is pressed from the first page or `N` is pressed from the last page. The program should stop when the `Q` key is hit. # Example Suppose `f.txt` contains `Lorem ipsum dol?` and the user has pressed the key sequence `N N B N N Q`. The program should run something like this: ``` >>> bookmaker f.txt 3 2 |\ | \ | \______ | || | \ || Lor | \ || em | \||_____| |\ | \ | \______ | || | \ || ips | \ || um | \||_____| |\ | \ | \______ | || | \ || dol | \ || ? | \||_____| |\ | \ | \______ | || | \ || ips | \ || um | \||_____| |\ | \ | \______ | || | \ || dol | \ || ? | \||_____| >>> ``` **Notice that there is a newline after every book and no trailing spaces. This is required.** # Notes * You may assume the file only contains [printable ASCII characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex 20 to 7E). * Print one character in each available spot, regardless of word boundaries. * *w* and *h* are **optional** arguments that default to 7 and 5 respectively. Your program will either be given neither or both. (You may assume input is always well formed.) * Fill any empty text space on the last page with spaces. * `Q` should still be required to quit if there is only one page. # Winning The shortest program in bytes after bonuses are applied wins. **Bonuses** * Remove leading spaces so that every line starts with a word (or word segment). e.g. `| amet, |` in the first example would become `| amet, c |`. (-30 bytes) * Clear the screen of previously drawn books after `N` or `B` is pressed (and `T` if you do the bonus after this) so the book looks like its changing pages in place. (-20 bytes) * Make the `T` key instantly toggle between the text being drawn from left-to-right top-to-bottom (the default), to top-to-bottom left-to-right. If you did the first bonus it should work for columns in the top-to-bottom mode. (-100 bytes) So for example: ``` |\ | \ | \______ | || | \ || Lor | \ || em | \||_____| ``` becomes ``` |\ | \ | \______ | || | \ || Lrm | \ || oe | \||_____| ``` [Answer] ## C# 535bytes *Score is 655bytes of code -20byte bonus for clearing, and -100byte bonus for T key... I think, can't say I'm sure I haven't missed something in the spec* I may try and collapse the loops by having the W method return the s argument, but that would require effort, so no promises. Golfed code: ``` using C=System.Console;using K=System.ConsoleKey;class P{static void W(int x,int y,string s){C.SetCursorPosition(x,y);C.Write(s);}static void Main(string[]a){int b=a.Length,w=b>0?int.Parse(a[0]):7,h=b>1?int.Parse(a[1]):5,p=0,i,j,o,T=1;var F=System.IO.File.ReadAllText("f.txt");b=(w+3)/2;S:C.Clear();for(i=0;i<w+3;i++){W(o=i+b+1,b-1,"_");W(o,h+b+1,"_");}for(i=0;i<h+2;){W(0,i,"|");W(b,o=i+++b,"||");W(b+w+4,o,"|");}for(i=0;i<b;){W(i+1,i,"\\");W(i,++i+h+1,"\\");}for(i=0;i<w;i++)for(j=0;j<h;)if((o=T>0?j++*w+p+i:i*h+p+j++)<F.Length)W(i+b+3,j+b,F[o]+"");K k=C.ReadKey(1>0).Key;p+=k==K.N&p<F.Length-w*h?w*h:k==K.B&p>0?-w*h:0;T=k!=K.T?T:-T;if (k!=K.Q)goto S;}} ``` Formatted a bit: ``` using C=System.Console; using K=System.ConsoleKey; class P { static void W(int x,int y,string s) { C.SetCursorPosition(x,y); C.Write(s); } static void Main(string[]a) { int b=a.Length,w=b>0?int.Parse(a[0]):7,h=b>1?int.Parse(a[1]):5,p=0,i,j,o,T=1; var F=System.IO.File.ReadAllText("f.txt"); b=(w+3)/2; S: C.Clear(); for(i=0;i<w+3;i++) { W(o=i+b+1,b-1,"_"); W(o,h+b+1,"_"); } for(i=0;i<h+2;) { W(0,i,"|"); W(b,o=i+++b,"||"); W(b+w+4,o,"|"); } for(i=0;i<b;) { W(i+1,i,"\\"); W(i,++i+h+1,"\\"); } for(i=0;i<w;i++) for(j=0;j<h;) if((o=T>0?j++*w+p+i:i*h+p+j++)<F.Length) W(i+b+3,j+b,F[o]+""); K k=C.ReadKey(1>0).Key; p+=k==K.N&p<F.Length-w*h?w*h:k==K.B&p>0?-w*h:0; T=k!=K.T?T:-T; if (k!=K.Q) goto S; } } ``` [Answer] # Java, ~~1039~~ ~~1001~~ ~~993~~ ~~953~~ 946 With bonus: Remove leading spaces (-30 bytes) -> **~~1009~~ ~~971~~ ~~963~~ ~~923~~ 916** Clearing the screen is not worth it with java (except if I just print a couple of newlines. But then the user has to use the correct console size) Code: ``` import java.io.*;import java.util.*;class B {static int w=7,h=5,p,l;static String t="",o,u=" ",y="\\";public static void main(String[]c)throws Exception{if(c.length>1){w=Integer.valueOf(c[1]);h=Integer.valueOf(c[2]);}Scanner s=new Scanner(new FileReader(c[0]));while(s.hasNext()){t+=s.nextLine();}l=t.length();s = new Scanner(System.in);while(true){int q=w+3,z=q/2,i=0,j=0,a=w*h;o="";for(;i<z;i++)o+="\n|"+r(u,i)+y;o+=r("_", q);for(;j<h+2-z;j++){o+="\n|"+r(u,i-1)+"||";if(j==0)o+=r(u,w+2);else o+=u+t()+u;o+="|";}for(;i>0;i--){o+="\n"+r(u,z-i)+y+r(u,i-1)+"||";if(i>1)o+=u+t()+" |";}o+=r("_",w+2)+"|";System.out.print(o);switch(s.next().charAt(0)){case'Q':return;case'B':p=p>a?p-2*a:p-a;break;case'N':p=p>l?p-a:p;}}}static String t(){int e=p+w>l?l:p+w;String r="";if(p<=e)r=t.substring(p,e);r=r.replaceAll("^\\s+","");int y=r.length();p+=w;return y==w?r:r+r(u,w-y);}static String r(String s,int i){return new String(new char[i]).replace("\0",s);} ``` Pretty: ``` import java.io.*;import java.util.*; class B { static int w=7,h=5,p,l; // w = text width, h = text height, p = current position in text static String t="",o,u=" ",y="\\"; public static void main(String[]c)throws Exception{ // get w and h of text, default to 7x5 if(c.length>1){w=Integer.valueOf(c[1]);h=Integer.valueOf(c[2]);} // read file Scanner s=new Scanner(new FileReader(c[0]));while(s.hasNext()){t+=s.nextLine();} l=t.length(); // read input s = new Scanner(System.in); while(true){ // print book int q=w+3,z=q/2,i=0,j=0,a=w*h; // q = number of underscores at the top, z = number of backslashes o=""; // print top of book for(;i<z;i++)o+="\n|"+r(u,i)+y; o+=r("_", q); // print middle of book (hp-z lines). right now: i = z -1 for(;j<h+2-z;j++){o+="\n|"+r(u,i-1)+"||";if(j==0)o+=r(u,w+2);else o+=u+t()+u;o+="|";} // print bottom of book for(;i>0;i--){o+="\n"+r(u,z-i)+y+r(u,i-1)+"||";if(i>1)o+=u+t()+" |";} o+=r("_",w+2)+"|"; System.out.print(o); // user input switch(s.next().charAt(0)){ case'Q':return; case'B':p=p>a?p-2*a:p-a;break; case'N':p=p>l?p-a:p; } } } /** return w characters of string t, from given position p. increase p*/ static String t(){ int e=p+w>l?l:p+w; String r=""; if(p<=e)r=t.substring(p,e); r=r.replaceAll("^\\s+",""); // remove leading spaces (cost:28 chars) int y=r.length(); p+=w; return y==w?r:r+r(u,w-y); } static String r(String s,int i){return new String(new char[i]).replace("\0",s);} // repeat given string i times ``` If the program does not have to run forever, I could also save some bytes by removing the while loop and just calling main. This is not optimal, but it's a start. ]
[Question] [ Your challenge today is to refactor JavaScript code. You will take three strings as input; a JavaScript string, a old variable name, and the name you want to refactor it to. For example, an input of ``` "var x = 100; alert(x);", "x", "num" ``` Will output ``` "var num = 100; alert(num);" ``` --- Here's a more advanced test case: ``` "var gb = 1; var g = bg = 2; gb = bg = g = function(gg) { alert(gb); }; var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g /*gb gb g g*/", "gb", "aaa" ``` It should output ``` var aaa = 1; var g = bg = 2; aaa = bg = g = function(gg) { alert(aaa); }; var str = 'g gb bg gg'; var regexp = /gb gb g g/g; //comment gb gb g g /*gb gb g g*/ ``` And the same JS input with the other arguments `"g", "aaa"` should output ``` var gb = 1; var aaa = bg = 2; gb = bg = aaa = function(gg) { alert(gb); }; var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g /*gb gb g g*/ ``` --- Here is one last much more complicated test case: ``` var g = 1; "g\"g"; "g'"; g; '"g\'g"g'; /g"\/*\//g; g; "// /*"; g; "*/" ``` It should output, with other parameters `"g"` and `"a"`, this: ``` var a = 1; "g\"g"; "g'"; a; '"g\'g"g'; /g"\/*\//g; a; "// /*"; a; "*/" ``` (sidenote: I really like `/g"\/*\//g`; I think that's just evil `:D`) --- Full specification: * For simplicity, you may ignore scope. Ex. `"var a=1; function(){var a=2;}; var o={a: 3}", "a", "b"` can output `var b=1; function(){var b=2;}; var o={b: 3}`. * Text in strings (`'...' and "..."`), regexps and their modifiers (`/.../...`), and comments (`//...\n` and `/*...*/`) must not be modified. * Also for simplicity, a valid identifier is one that starts with a letter, dollar sign, or underscore, and the rest of the characters are letters, numbers, dollar signs, or underscores. * You may assume that the input contains no syntax errors. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. * If you use network access, all bytes downloaded from the network count towards your score. * You must use an actual programming language. No IDE solutions, like emacs or vim keystrokes. ;) [Answer] # Ruby, 134 (113?) characters ``` *c,o,n=*$<;puts (c*?\n).gsub(/('|")((\\?+.)*?)\1|\/\*[\s\S]*?\*\/|\/\/.*|\/(\[\g<2>\]|\g<2>)+?\/\w*|([\w$]+)/){$5==o.chop&&n.chop||$&} ``` Unicode is not supported. If Unicode identifiers are to be supported, replace `\w` with `[[:word:]]` and `[\w$]` with `([[:word:]]|\$)` (and adjust the backreferences). If unescaped slashes inside regexp literals (such as `/[/]/`) don't need to be supported, we can handle them together with string literals (**116 characters**). This also gives us string flags: ``` *c,o,n=*$<;puts (c*?\n).gsub(/\/\*[\s\S]*?\*\/|\/\/.*|('|"|\/)((\\?+.)*?)\1\w*|([\w$]+)/){$4==o.chop&&n.chop||$&} ``` Ungolfed version: ``` *code, old, new = *$< puts code.join("\n").gsub (/ ('|")((\\?+.)*?)\1 #strings | \/\*[\s\S]*?\*\/ #multiline comments | \/\/.* #single-line comments | \/(\[\g<2>\]|\g<2>)+?\/\w* #regexes | ([\w$]+) #identifiers and keywords /x){ if $5 == old.chop then new.chop else $& end } ``` [Answer] ## Perl, 122 ``` @a=<>;chomp(($y,$x)=(pop@a,pop@a));$_=join'',@a;s!//.*?\n|/\*.*?\*/|("|'|/)(\\?+.)*?\1\w*|([\w\$]+)!$3eq$x?$y:$&!sge;print ``` i.e. (semi-ungolfed) ``` @a=<>; chomp(($y,$x)=(pop@a,pop@a)); $_=join'',@a; s!//.*?\n|/\*.*?\*/|("|'|/)(\\?+.)*?\1\w*|([\w\$]+)!$3eq$x?$y:$&!sge; print ``` practically the same as Ruby's short version answer (except I didn't knew about possessive quantifiers trick and my first take was slightly longer). Regexp is shorter, but 'I/O' part spoils everything (Perl can't do `(@a,$x,$y)=<>`), and my assumption (the same I see in Ruby's, if I'm not mistaken) was we feed JS string line by line through STDIN, followed by 'old name' and 'new name' on separate lines. [Answer] # ECMAScript 6, 136 bytes ``` (s,o,n)=>s.replace(/\/\/.*?\n|\/\*[\s\S]+?\*\/|('|")(\\\1|[^\1])+?\1|\/(\\u[a-f\d]{4}|\\.|[^\/])+\/[angi]*|[a-z_$][\w$]*/gi,x=>x==o?n:x) ``` *Runs fine on any recent version of Firefox/Google Chrome.* --- It creates a function with three parameters: 1. The code 2. The old variable name 3. The new variable name See [this JSFiddle](http://jsfiddle.net/A6zM7/3/) for an example. ]
[Question] [ Given an integer n, enumerate all possible full binary trees with n internal nodes. (Full binary trees have exactly 2 children on every internal node). The tree structure should be output as a pre-order traversal of the tree with 1 representing an internal node, and 0 representing an external node (Null). Here are examples for the first few n: 0: 0 1: 100 2: 11000 10100 3: 1110000 1101000 1100100 1011000 1010100 This is a code golf with the prize going to fewest characters. The trees should be output one per line to stdout. The program should read n from the commandline or stdin. [Answer] ## Perl - 125 79 chars Count includes 4 chars for "`-ln`" options. Takes n from stdin. New constructive approach: ``` @a=0;map{%a=();map{$a{"$`100$'"}=1while/0/g;}@a;@a=keys%a}1..$_;print for@a ``` Form the solution for n by substituting a new internal node ("100") for each leaf ("0"), in turn, in each tree from the solution for n-1. (I owe this concept to other's solutions that use the internal node to leaf [100->0] substitution for verifying sequentially-generated strings, and I believe I saw--after writing my answer based on that concept--this same 0->100 method of construction in someone's intermediate edit.) Previous recursive approach: ``` sub t{my$n=shift;if($n){--$n;for$R(0..$n){for$r(t($R)){for$l(t($n-$R)){push@_,"1$l$r"}}}}else{push@_,"0"}@_}print for t$_ ``` Recursive ungolfed: ``` sub tree { my ($n) = @_; my @result = (); if ( $n ) { for $right_count ( 0 .. $n-1 ) { for $right ( tree( $right_count ) ) { for $left ( tree( ($n-1) - $right_count ) ) { push @result, "1$left$right"; } } } } else { push @result, "0"; } return @result; } foreach $tree ( tree($_) ) { print $tree; } ``` [Answer] ## PHP (142) (138) (134) (113) Runs from the command line, i.e. "php golf.php 1" outputs "100". EDIT: Cut 4 characters with an alternate method, building up the strings from 0 rather than recursing down from $n. Uses PHP 5.3 for the shortened ternary operator; otherwise, 2 more characters are needed. EDIT 2: Saved 4 more characters with some changes to the loops. EDIT 3: I was trying a different approach and I finally got it below the old method. All of the trees can be considered as binary representations of integers between 4^n (or 0, when n=0) and 2\*4^n. This function loops through that range, and gets the binary string of each number, then repeatedly reduces it by replacing "100" with "0". If the final string is "0", then it's a valid tree, so output it. ``` for($i=$p=pow(4,$argv[1])-1;$i<=2*$p;){$s=$d=decbin($i++);while($o!=$s=str_replace(100,0,$o=$s));echo$s?:"$d\n";} ``` [Answer] ### Ruby, 99 94 92 89 87 characters ``` (n=4**gets.to_i).times{|i|s=(n+i-1).to_s 2;t=s*1;0while s.sub!'100',?0;puts t if s==?0} ``` The input is read from stdin. ``` > echo 2 | ruby binary_trees.rb 10100 11000 ``` *Edit 1:* Changed IO (see Lowjacker's comments) ``` b=->n{n==0?[?0]:(k=[];n.times{|z|b[z].product(b[n-1-z]){|l|k<<=?1+l*''}};k)} puts b[gets.to_i] ``` *Edit 2:* Changed algorithm. ``` b=->n{n==0?[?0]:(k=[];b[n-1].map{|s|s.gsub(/0/){k<<=$`+'100'+$'}};k.uniq)} puts b[gets.to_i] ``` *Edit 3:* The version now takes the third approach (using the idea of migimaru). *Edit 4:* Again two characters. Thank you to migimaru. [Answer] ## Ruby 1.9 (80) (79) Using the non-recursive, constructive approach used by DCharness. EDIT: Saved 1 character. ``` s=*?0;gets.to_i.times{s.map!{|x|x.gsub(?0).map{$`+'100'+$'}}.flatten!} puts s&s ``` [Answer] ## Haskell 122 chars ``` main=do n<-readLn;mapM putStrLn$g n n g 0 0=[['0']] g u r|r<u||u<0=[] g u r=do s<-[1,0];map((toEnum$s+48):)$g(u-s)(r-1+s) ``` Since the IO is a non-trivial portion of the code in haskell, maybe someone can use a similar solution in another language. Essentially random walks in a square from bottom left to top right stopping if the diagonal is crossed. Equivalent to the following: ``` module BinTreeEnum where import Data.List import Data.Monoid data TStruct = NonEmpty | Empty deriving (Enum, Show) type TreeDef = [TStruct] printTStruct :: TStruct -> Char printTStruct NonEmpty = '1' printTStruct Empty = '0' printTreeDef :: TreeDef -> String printTreeDef = map printTStruct enumBinTrees :: Int -> [TreeDef] enumBinTrees n = enumBinTrees' n n where enumBinTrees' ups rights | rights < ups = mempty enumBinTrees' 0 rights = return (replicate (rights+1) Empty) enumBinTrees' ups rights = do step <- enumFrom (toEnum 0) let suffixes = case step of NonEmpty -> enumBinTrees' (ups - 1) rights Empty -> enumBinTrees' ups (rights - 1) suffix <- suffixes return (step:suffix) mainExample = do print $ map printTreeDef $ enumBinTrees 4 ``` [Answer] ## Golfscript, 60 83 ``` ~[1,]\,{;{[:l.,,]zip{({;}{~:a;[l a<~1 0.l a)>~]}if}/}%}/{n}% ``` I built a [golfscript mode](https://github.com/jmillikan/golfscript-mode) for Emacs for working on this, if anyone's interested. [Answer] # [Haskell](https://www.haskell.org/), 54 bytes ``` t 0=["0"] t n=['1':l++r|m<-[0..n-1],l<-t m,r<-t$n-1-m] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0TBwDZayUAplqtEIc82Wt1Q3SpHW7uoJtdGN9pATy9P1zBWJ8dGt0QhV6cISKkABXRzY//nJmbm2RYUZeaVqJTYqNiBlBrH/gcA "Haskell – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 115 bytes It reminds me of [Catalan number](https://en.wikipedia.org/wiki/Catalan_number). --- Golfed version. [Try it online!](https://tio.run/##NY7BasMwEETv/orBJy3BxqE3JzL0WGhPoadSiqrIiYq0buXtIRh9u6sYupeFmQfzZmuCWafPL2cFL8Yzlqo6uxHSP7Ho4eR@3k6SPF/eoVfWAyMasdfFmtmh2wBVdzUdtuBDD2qckorHpsMviw9gunkXzkuJl3BsREU6pPvnZt9EyluLel/vwi5lamV69rO0YzAijvMK3HViUVMmXeYejymZ278U9XhlL9DFG@VUB5nwQG2Zc8ZeFUMP@C6sBFZllIgKmKu8/gE) ``` n=>n match{case 0=>Seq("0");case _=>(for(m<-0 until n)yield{for{l<-t(m);r<-t(n-1-m)}yield "1"+l+r}).toList.flatten} ``` Ungolfed version. [Try it online!](https://tio.run/##TY9Ba8JAEIXv@RWPnHYRQ6S3UAseBXsqPUkp03WjK5uJbKYHkfz2dBJTdGEO8@bt432do0jD0P6cvRO8U2DcMuDga4jhClsWW2EXOtl/SAp8/MIajIbEnSYn4KjzKLF@m2wmL3P70L9VnzbA1G2CafC6VPcvS4hgi2vw8TAnjW80PTYgjn4xjX3S0l1jLLHSebr1c16@yrHQvwuk@dbbQtqxYFFHEvGsep/NqI1yG0rHrsImJbr@syr6JwdR5HslU0JavNhCW3pyJ62g2Bf1SmSjjay1U26fDcMf) ``` object Main { def t(n: Int): List[String] = n match { case 0 => List("0") case _ => (for (m <- 0 until n) yield { for { l <- t(m) r <- t(n - 1 - m) } yield "1" + l + r }).toList.flatten } def main(args: Array[String]): Unit = { (0 to 3).foreach(n => println(t(n))) } } ``` ]
[Question] [ A screen consists of some LED segments like such: [![enter image description here](https://i.stack.imgur.com/7x2CI.png)](https://i.stack.imgur.com/7x2CI.png) The screen can be split into several(maybe one) component. Each component is a segment like above, with varying lengths. These components can be used to display any amount, including 0, of digits, as long as the component is large enough. Every digit except 1 needs two columns of the grid to be displayed. These columns are not allowed to overlap (even a number like 67 still needs 4 columns and does not fit into a n=2 component). The digit 1 is slim, so it only needs one column. Therefore, a number fits into a component, iff `2 * Length - (Amount of 1's) <= n+1`. For example, the number 14617 can be displayed in a screen with the component lengths `[0, 1, 1, 2, 0]`: [![enter image description here](https://i.stack.imgur.com/Jlv8l.png)](https://i.stack.imgur.com/Jlv8l.png) Given the n's of each component and a positive integer, find the nearest positive integer that can be expressed in the screen. If multiple number are nearest, you can output either. Shortest code wins. # Examples ``` [1],3 => 3 [1],16 => 11 [0,0],3 => 1 [0,0],6 => 1 or 11 [2],14 => 14 [2],24 => 21 [3],999999999 => 1111 [1,0,0,0,0,0,1],23 => 23 [0,3],100 => 100 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~163~~ 143 bytes ``` ->r,i{g=->s,r{*t,c=s;d,*q=r;n=c==1?1:2;!c||d&&(n<d+2?g[t,[d-n,*q]]:g[s,q])} h=->n,r{g[n.digits,r]&&p(n)} a=0;until h[i+a,r]||h[i-a,r];a+=1;end} ``` [Try it online!](https://tio.run/##TVDNjoIwEL7zFLNsQlSKodVssrLFB6k9IEVoYgrSctgAz84OoGY7l5nvZ@ZL2@76O934FKUt0X3Jo9SStt85knObKLJ78DYxPOecnumJJR/5MKgg2JgfFbJzKRwRKjIok/JUCksecjt6FW4xuKUUZq90qR2ulEHQbAySGY@Tzjh9h0roMENmGLCL5i7JQk6TwqhxcoV1eWYLCxx6D0AIKslBAk/hQF4z/VoASlckJvFL8x9ZRT6FukWpvzIM3cdVenwjbEXY032Q5Ht@zyOvM5TE78IQbL3IMNbovWPviyyvQNUwaNN0jkDduQHtDSzz3LXaOPDnaDjdxG4h5Mx0zoK/sVXd3RVcC/js0T1uL@ZifA@/Z/oD "Ruby – Try It Online") *-20 bytes thanks to @Kirill L.* My first golf in Ruby. I'm sure that it can be even shorter, but I didn't find anything. ### Explanation `g` (takes an array of chars, representing the number, and the displays) checks if a given number fits into the given display. `f` then checks all numbers, starting with the given integer, then i+1, i-1, i+2, ..., and outputs the first number that fits. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` n1‘S> ⁵*ḶD“”ṭçÐḟ ‘Ç€ŒpF€ḌạÐṂḢ ``` [Try it online!](https://tio.run/##y0rNyan8/z/P8FHDjGA7rkeNW7Ue7tjm8qhhzqOGuQ93rj28/PCEhzvmcwGlD7c/alpzdFKBG5B6uKPn4a6FQKmdTQ93LPr//3@0Uex/Q0MDAA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` ‘ؽṗⱮẎS=¥ƇƲ€ŒpF€ị⁵Ḷṭ1¤Œp€ŒP€€ḌFạÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4zDMw7tfbhz@qON6x7u6gu2PbT0WPuxTY@a1hydVOAGpB7u7n7UuPXhjm0Pd641PLQEKAqWCwCSINkdPW4Pdy08PO/hjkX///830jH@bwQEAA "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing This is absolutely horrible. I won't be surprised if someone can halve my bytecount. I spent a decent bit of time on it; not too much - I'll keep golfing this but I think it's at least close to worth posting. [Answer] # [Python 3](https://docs.python.org/3/), 190 181 215 175 bytes ``` def f(n,i,m=["0"]): for g in n:m=[u+x[1:]for u in m for x in[str(d)for d in range(0,12*i)if sum(-~(b!="1")for b in str(d))<g+3]] return min(map(int,m),key=lambda v:abs(v-i)) ``` Generates a roughly bounded list of possible ints for each segment, zero pads, tests each to see if they fit, permutates all the sequences for each segment, then finds closest int match to the input. Thanks mypetlion and l4m2 for improving my swing! [Try it online!](https://tio.run/##ZZBNbsMgEIX3PsWUFTREAhNVqlWfoIsewGKB5Z@iFGIBjpJNr@6CSSW7ZTV8897T00z38HmxYlm6foABW6qpqRvEkCRVAcPFwQjagq0inQ@3hlcywTlBs@5vcWx8cLgj6duljVN27DGjvHzWRA/gZ4OP37h9qhFHq6xNsuwib@NBSFmA68PsYqy22KgJaxuoIfTc3@svZdpOwbVSrcfXoyZkUd73LsTKDZdUEKhrEMUO8peVcr7BjLJf9T/8kENs9wdtpWUMPmV82uMy43KrFpK@pvfI2SVxGg8UbblOKXZ9opEzlm2MFZOL18Do4x2R5Qc "Python 3 – Try It Online") [Answer] # [Common Lisp](http://www.clisp.org/), 337 bytes ``` (defun C(a b &aux r)(dolist(x a)(dolist(y b)(push(concatenate'string x y)r)))r)(defun P(n &aux r)(case n(0'("""1"))(1'("0""1""2""3""4""5""6""7""8""9""11"""))(t(dotimes(i n r)(setf r`(,@r,@(C(P i)(P(- n i 1)))))))))(defun F (i x)(- x(reduce'min(mapcar(lambda(p)(-(or(parse-integer p :junk-allowed t)0)x))(reduce'C(mapcar'P i))):key'abs))) ``` [Try it online!](https://tio.run/##bVNRb5swEH5ef8Xppo5z1EhAsmzNXjqhRpo0TZGiPU2T5oDTsoJhtlnJC389OydAsnXGlr7Td/fdx2HSIrf14UCZ2jUaEpKwhTeyacEIyiomHbUgR7yHraC6sY@UVjqVTmk@gXUm1w/Qwl4YIYQvPcqtSY9iqbQKNIUBIWKEQlDEMPQYY8QZ4hzxLeIC8R3ie8RbppjzmY7bu7xUlnLQXswqtwPzg27uzM0dJbSGXNCapszmEIlh9TZWwHWtYLolo7ImVUGZayplnUpDhSy3maSaeaoM1dJYNc21Uw/KQA3Ln41@msqiqJ5VBk6EomXhXibpRQJvQIjlk9oHcmsZHifKWrJUjnUmTlk39TOwkyuAgIgiATOYCY4AjlG0gCga4hBCz/8dL85xzPlz3hdxPId45GcCbofFsmfhCMLx4abxjPe5CZdFYegPv8PVVT/A0TzQCH0NFcpNuC6tyrrSSjsLtMuNdecKVnkFpJtyy1Pg78bXJvuXVW2tUsfTJfeYmxe01PbZF6/gos9J0Zs8Wt9VppTcFjAZc5bQ2e76yzHxhO/7RqdoVTW6h93y2@rjp8/dh83XJLnfbLrvXXyN3JzXi6Yw@h2cqV/FgAduMPZfyk@25l/GMf9bmT28Ds4jvrwqQsDhDw "Common Lisp – Try It Online") Gets all possible numbers that can be represented by the given component list `i`, finds the smallest distance from the numbers to input `x` and returns `x - distance`. `F` is the main function, `C` concatenates combinations, and `P` recursively gets the possible digits for a component of size `n`. Testing included in TIO. This can ~~probably~~ maybe be reduced by 50-75 or so bytes as is, mainly the double `dotimes` in `C`, the disgusting string hell in `P`, and the `:junk-allowed t` in `parse-integer` used by `F`. The `junk-allowed t` was needed for the case where the string is empty. I at some point tried to replace all instances of `dolist`, `reduce`, `defun`, and `mapcar` with `l`, `d`, `e`, `m` respectively but the resulting code ended up being larger at 404 bytes but someone might be able to make use of it so I'm still putting it here: ``` (let((f(copy-tree'(progn(d C(a b &aux r)(l(x a)(l(y b)(push(concatenate'string x y)r)))r)(d P(n &aux r)(case n(0'("""1"))(1'("0""1""2""3""4""5""6""7""8""9""11"""))(t(dotimes(i n r)(setf r`(,@r,@(C(P i)(P(- n i 1)))))))))(d F (i x)(- x(e'min(m(lambda(p)(-(or(parse-integer p :junk-allowed t)0)x))(e'C(m'P i))):key'abs)))))))(mapc(lambda(x y)(nsubst x y f))'(dolist defun reduce mapcar)'(l d e m))(eval f)) ``` [Try it online!](https://tio.run/##bVNRb5swEH5efsXJU8c5aiQgWbZmL52iRppUTZGiPU2TZuBIWcEw27TkJX89OyeFZOsMVu747u77@HDSsrDN4YAlOcQc07rZTZwhCrAx9VZjBktUkMA71XZgJJbYgfI/O0gkNq194B6dKkead2CdKfQWOthJIyVvHrBGPbSnyhJoDAMUQkRCSow4DH0sYiGmQsyEeC/EXIgPQnwU4oYhxnylw6x2RUUWC9B@mCWXg/mJ17fm@haXuIZC4honjBYQyX6xhBVwTycZ6pCCqtBYYamqJFPY8FOsDTbKWJoU2tGWDDSw@NXqx4kqy/qZMnAylB2PomCJVeCJpFw80i5Qie1pKtWk/VRvAGrbJtZ5MyCXMmD5bLaDjPKW9VPWpgS@SRkGS8iAU8/xpErfcECuZFmqIseSxo6sm3gD7XgEECBiJGEKU8kZwDGL5hBFfR5C6PG/8/k5j7l@xvdFHs8gHvCphJt@8djz4AjC4WLSeMr3mYTbojD0m00ZjfD0uoN4wCH0Pf7gjbkvraum1qSdBcwLwzady@ToDaBuq4Rd4I/O5y37F6WuodTxh0L3UJhXsNL22Tev4ILnNNGLPErPa1MppgWxHGoWsLf7q6/HwlN890J0ylZ1q1/C/eL76vOX@/2nzbfl8m6z2f/Yx1eCyXm9IoVBb6@Mfpd93GO9sP9C3tmG/2uO8ScyO3gbnC2@PCpSwuEP "Common Lisp – Try It Online") The code is essentially wrapped in ``` (let ((f (copy-tree '(progn CODE)))) (mapc (lambda (x y) (nsubst x y f)) '(THINGS TO BE REPLACED) '(THINGS TO REPLACE THEM WITH)) (eval f)) ``` [Answer] # [R](https://www.r-project.org/), ~~148~~ 147 bytes ``` function(n,m,g=function(n,s=nchar(n),d=2-!n%/%10^(0:s)%%10-1){for(i in m)while(s&&(i=i-d[s])>-2)s=s-1;n*!s}){while(!(r=max(g(n-F),g(n+F))))F=F+1;r} ``` [Try it online!](https://tio.run/##TYxha4NADIa/71foByWZOXY5i9KV20f/xNig2NoezAh3HS0Uf7vTcxtNAs@bvEn81Nmp@5b24gYBoZ5O9qENVtrz3oMgHaxRqWQvGetP0K8Bs1kpxns3eHCJk6TH69l9HSHkOTjr1OE9fOCbMhhsULyT5zSMeF93UvC239/gBKIapBlFg3M0til458epA95UXFMLmhKOZSjRiE@zUxEvLKO7zqoHzRsyC80f618uB0z6Pzmub5egMl5qHf@UiNMP "R – Try It Online") ]
[Question] [ Note: This is the [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") version of my previous challenge [Pristine Bit Checking](https://codegolf.stackexchange.com/q/182830/76162). This should be *much* more difficult than that one. Write a program/function that takes two integers in the range \$0\$ to \$255\$ inclusive, and returns whether the binary forms of the numbers are exactly one bit different. For example, \$1\$ and \$0\$ have binary forms `00000001` and `00000000`, which are one bit apart. Similarly, \$152\$ and \$24\$ are `010011000` and `000011000`, so they return true. ***However***, your code must be **radiation-hardened**, such that if any one bit in your program is flipped, it should still work correctly. For example, if your program was the single byte `a` (`01100001`), then all the 8 possible modified programs: ``` á ! A q i e c ` ``` must still work correctly. Make sure you are modifying by *bytes* (e.g. the `á` up there is actually representing the byte \$225\$, not the actual two byte character `á`). ### Test cases: With Truthy meaning they *are* different by one bit. ``` 0,1 => Truthy 1,0 => Truthy 152,24 => Truthy 10,10 => Falsey 10,11 => Truthy 11,12 => Falsey 255,0 => Falsey ``` ## Rules: * Provide a testing framework that can verify that your program is properly radiation-hardened, since there will be a lot of possible programs (number of bytes\*8), or else a complete proof of validity. + *Please* make sure to double-check your program is valid before you post it. * Output can to be either truthy/falsey (either way around is fine), or else as one distinct value for truthy and the rest as falsey + This can be through any of the [Standard input/output methods](https://codegolf.meta.stackexchange.com/a/17938/76162) Here is a [helper program](https://tio.run/##ZZDBbsMgEETvfAVyDuzGbWTnFCHxF71ZKLIxaTZKAREOSat@uwttSSr1tJo3u6OBcEtH77aL8bNVTdMs42SWPIdePveasRDJJV5ctuIv9pL4wUee6SWRs6wY@4mcEmJz8uRAfMhuN32KTV57GxP4OINBLEeGk/tOQlbkRKmAOLpXC2froGYhSsar2B/OFIKdubqjQeZT3YquF8OdFaSU6IRu/7K2l/o37BFUu5pjhPw6qPqKT9ufqtfS7J0CrAdKNsK/NqjXO0TGH99TreUL) that can be used to produce all the variations of an inputted program. [Answer] # HTML + JavaScript, 210 bytes ``` <script>[d,b]=location.search.match(/[\d]([\d]*)?/g);1/b/d&&document.write([i=b^d][i--&i]+'<!-'+'-')</script></script>0<script>[d,b]=location.search.match(/\d+/g);document.body.innerHTML=[i=b^d][i&i-1]</script> ``` Open page with search parameters `index.html?a=1&b=2`. ## Validation (Python + Selenium + Firefox) ``` # -*- coding: utf-8 -*- from selenium import webdriver import os source = "<script>[d,b]=location.search.match(/[\d]([\d]*)?/g);1/b/d&&document.write([i=b^d][i--&i]+'<!-'+'-')</script></script>0<script>[d,b]=location.search.match(/\d+/g);document.body.innerHTML=[i=b^d][i&i-1]</script>" filename = os.path.abspath("temp1.html") browser = webdriver.Firefox() def test(html, input_values, expected): with open(filename, "w", encoding="latin-1") as html_file: html_file.write(html) [a, b] = input_values browser.get("file:///" + filename + "?a=" + str(a) + "&b=" + str(b)) text = browser.find_element_by_tag_name("body").text if text == "true" and expected == True: return True if text == "false" and expected == False: return True if text == "undefined" and expected == False: return True try: if int(text) != 0 and expected == True: return True if int(text) == 0 and expected == False: return True except: pass print(html, input_values, expected, text) testcases = [ [[1, 1], False], [[1, 2], False], [[1, 3], True], ] fullTestcases = [ [[0, 1], True], [[1, 0], True], [[152, 24], True], [[10, 10], False], [[10, 11], True], [[11, 12], False], [[255, 0], False], ] def runAllTestcases(html, testcases): for testcase in testcases: test(html, *testcase) runAllTestcases(source, fullTestcases) for pos in range(len(source)): for flip in range(8): flip_char = chr(ord(source[pos]) ^ (2 ** flip)) flip_source = source[0:pos] + flip_char + source[pos+1:] runAllTestcases(flip_source, testcases) print(pos, "/", len(source)) browser.quit() ``` Usage: * make sure you have `python3` and `firefox` installed. * save this python code to your locale. * `pip install selenium` * [download firefox web driver](https://github.com/mozilla/geckodriver/releases) and put it in the same folder of this python source. * execute this validator and wait it finish. ## How If the modification is on the first time of script. The script will throw some errors (syntax error, undefined variable, etc.). And the second time of script will run correctly and overwrite the output. If the modification is not on the first time of script. The script output ## Learn some (useless) HTML knowledge * document.write insert HTML to current position. You should not output unbalanced HTML in usual. When unbalanced HTML is printed. It inserted as is. And following HTML are re-parsed. You may even insert something like <!-- to open a comment. * When trying to parse <head>, if HTML parser got anything should not be existed here, the <head> tag is closed immediately and a <body> is created. * When the tag is created, document.body is accessible. * <script> tag is closed by </script>. Anything between them are script. Script may not be valid, and that doesn't matter (doesn't break HTML). * Exception in previous <script> tag does not prevent the following 's execution. ]
[Question] [ ## Background [Ada](https://en.wikipedia.org/wiki/Ada_(programming_language)) is a programming language that is not exactly known for its terseness. However, its array literal syntax can in theory allow for fairly terse array specifications. Here is a simple EBNF description of the [array literal](https://www.adaic.org/resources/add_content/standards/05rm/html/RM-4-3-3.html) syntax (passable to [bottlecaps.de](https://www.bottlecaps.de/rr/ui): ``` array ::= positional_array | named_array positional_array ::= expression ',' expression (',' expression)* | expression (',' expression)* ',' 'others' '=>' expression named_array ::= component_association (',' component_association)* component_association ::= discrete_choice_list '=>' expression discrete_choice_list ::= discrete_choice ('|' discrete_choice)* discrete_choice ::= expression ('..' expression)? | 'others' ``` We will limit ourselves to 1-dimensional arrays of integers for simplicity. This means that we will use only integers for the expression values. Perhaps in a future challenge we could try something more advanced (like declaring variables and multidimensional arrays). *You do **not** have to golf the integer literals*. Here are some examples of Ada array literals and a python-esque equivalent representation for clarity: ``` (1, 2, 3) = [1, 2, 3] (1, others => 2) = [1, 2, 2, ..., 2] (others => 1) = [1, 1, ..., 1] (1 => 1, 2 => 3) = [1, 3] (1|2 => 1, 3 => 2) = [1, 1, 2] (1 => 1, 3 => 2, others => 3) = [1, 3, 2, 3, 3, ..., 3] ``` ## Challenge The goal of this challenge is to output the shortest byte-count Ada array literal for a given input array. Note that Ada arrays can start from whatever index is desired, so you can pick what you wish the starting index to be as long as each value is sequential. In this example I choose to start at 1, which is idiomatic for Ada, however you can choose to start at any other integer. ### Input Your input will consist of a list of integers, in whatever form is convenient. ### Output Your output will be a string of text representing the shortest valid Ada array literal that represents the list of input integers. You may use any starting index you wish on this array, but your choice (whatever it is) must be specified in your answer (the starting index may also be dynamic). The integers are to represented as signed decimal numbers, as in the examples. This challenge does not cover golfing of integer values. ### Examples Here are some examples: ``` Simple: [1, 2, 3] -> (1,2,3) Range: [1, 1, 1, 1, 1, 1, 1,] -> (1..7=>1) Others: [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1] -> (6=>2,others=>1) Multiple Ranges: [1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1] -> (6..10|16..20=>2,others=>1) Tiny Ranges: [1,1,2,2,1,1,1,1,1] -> (3|4=>2,others=>1) Far Range: [[1]*5, [2]*100, [3]*5] -> (1..5=>1,6..105=>2,others=>3) Alternation: [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2] -> (1|3|5|7|9|11|13|15|17=>1,others=>2) Big Number: [1234567890,1,1234567890] -> (2=>1,1|3=>1234567890) Big-ish Number: [1234567,1,1234567] -> (1234567,1,1234567) Solo: [-1] -> (1=>-1) Huge Input: [[0],[1]*1000000000] -> (0,others=>1) Positional Others: [1, 2, 3, 3, 3, 3, 3, 3] -> (1,2,others=>3) Range and Choice, no Others: [1,1,1,12,12,3,3,3,3,3,3,3,3,3,3,4] -> (1..3=>1,4|5=>12,6..15=>3,16=>4) ``` ## Minimum Requirements * Support at least 100 numbers and inputs of at least 256 numbers in length. * Produce the correct result for all such inputs + Includes putting 'others' at the end + Includes putting an index for single item arrays * Terminate (preferably on TIO) for each of the above inputs in under a minute. Shortest solution in bytes wins! ## Reference Implementation [Try it online!](https://tio.run/##xRrZbttG8J1fsdBDJCKSYMVp2liWAFm5hNpJ4KR9JRhxJROVSYFcxjLQf3dnL3JPUjZilAZscjkzO/exdJzEo20Wk4e7lNygRRKPv@MDiVZfpkG9ssxvb@MsiS7TDGvLGYlhqSjHqyzBmzRLCY6@FAkucBJdxftSAf5GijTbluO/sh95BdDJNAj2Rb7GSVVgdAV0UFo@ILjI/R6jVUaiRVHE97CKYnYzgDW8xQUq4myL0fk8RPkGiUWgRnFHI7QAePQjz6pyiMgNYFclLuEOI7ZxSZHoU5rtKyJIw@Z0Ka8IrDFCmypbkzTP0Md8txGcAAMU5axhLkQFJlWRIS4d8MqQNQIUeHUbA8eDFcG3HJ2y3IJML45zhtZ5VpI4IxLsbCYJ9BWy4bRG/oG3aaaRSjdIgtI//Q9pUZIQzVAffkBwHZpegjMbC71EEzQe8zf9yxjoTDVsvCtxKzkDPEuAvWaNPtcaE0ZVnCLBB1NPBV7nRWJtCZ7wjcQFASk/gGOWN2g0RyUocIf9sHMFNgfFFKUFywCHEu6s8T9TK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3JPbxUilzmMHyVpz3a27XOZwRp2WzImB9KVSc9RaJGVvezMdXYiFMbLtNpgMkxxxueNGBNBx6uruxkTgTqordigxtA8k5ovU4NvLZJE7TvqzmqwgqHoKFcDLTEzy66ibERpm/U4zjXe7@K1Ij3MYvxNnfEVYi8Ex46M4U1/nNoqK3FBtG0GbMgQBEP3uGXmH8v5jTzC0hDf0Si9Ty20PtPxMS5pTgLoznJofkT5dNtUM47C4FDuGxrJUzhClpMOGUUwhwgcl9rMU32MRkHuKiNxfgySXwuSCUkvtMh53bZORjO0fITPBE8pVg4He5yOfcmqmSZaUgvLfk9UKAx3b@zdPV4lkGVEDiZDdBKGYQtrrqBgxKOWzzWOsYPhdH2zUQhL6c4VDco1p8e0oIs5rhVdNVlD5hHJr7F3PXge5bIuelQWS@onieLwvmeTxP6wxR/oi@aj4vQhqM/gI8fhxmQaNL5BzzuNz7HjRbGt2AC8hLaNfrw50dWgUW4@HYr@zEsOgkEGghYEWplwRYP8Rtq4v/JNefwRE/EVWf@KcIBJk39kVQ6PHBlalWY81h5f6i3TiH0n8ccXPqSEn9xpaOfmic5xfY4pxcDgDNjR2jLa5zi9jR9jyl7BdYipnTr2T/pUD/23fd/JY536b@IiXhMwPXiy1tuMzHdA1HHKqe@7oBuiyavT17@9@f2Ptydd8Bc6fBf4UgPvgn6nQncBv1eAu2A/NLBdoB9r0C7ITxKyC3AlADvg6pNnKF6@edOc9mQ8fq14PKKB@n8Oiicb1bDJCJwuvaP/uzF9AHmCCb/431fqPb2Mu4A@mDDPfJ3SKwDWjB9rKVhMFsG7yTt4IVBOT7Wb09fNLXsKHib/AQ "Ada (GNAT) – Try It Online") This implementation uses the input as its array, with each character being a number. Capital letters are special constants for large values. The program argument is the 'start index' to use. The "code" section in the TIO link is a correct solution to the problem, while the "header" and "footer" implement the test structure. [Answer] # JavaScript (ES6), ~~307~~ 304 bytes *Saved 2 bytes thanks to @KevinCruijssen* This is embarrassingly long ... ``` a=>[b=([...a,m=''].map(o=(v,i)=>(i?p==v?!++n:m=o[(o[p]=[o[p]&&o[p]+'|']+(n?i-n+(n>1?'..':'|')+i:i))[m.length]?(x=i-n,j=p):j]:1)&&(p=v,M=n=0)),Object.keys(o).map(k=>j-k|!m[6]?o[k]+'=>'+k:O,O='others=>'+j).sort()),1/a[1]?[...a]:b,j-a.pop()?b:a.slice(0,x-1)+[,O]].map(a=>M=M[(s=`(${a})`).length]||!M?s:M)&&M ``` [Try it online!](https://tio.run/##lVRtbqMwEP3fUxBpFWxhHGzysUUyqAdAOQC1VJKQFkIwAhS1Wu/Zs4aIpNmQQBmwwWLem3kzdhIewnJdxHllZmITHbfsGDI3WDEQYIxDtGe6zvE@zIFg4IBiyFwQezljB29kGJmzZyIAIsg5C@pxPK5HQ5c6N0DmxWamJpd4Osa6o1ahETsxhMEep1H2Xn1wD3wy9RdKWA6dhDsEjscgZwfks4xZEKLlKonWFd5FXyUQsIlkx9zE3MnRPphzTwQ7xcdc3dg5S7Rkuqg@oqKsFxKIS1FUQKGQSRgQ7jU5cWeFEjPEucgB9FZOiMs0XkfAQp8mgUaAlvyUsRLCZ34ASvYGfv0J/8I32IYt5cj3SsdX0frHtchKkUY4Fe9gCwKCNIo0m2uDLwi1yUQDBFFkw6dbuJubD4LDeMFc0gdI/wPndwHnzKWolbcLtzV6todrvMXFmFiSqIla/RTXEAOlteV0aPCqRV6KIvwCxLIg3sZpCihEdmv8VuWZAkRNErPvJF2lpKjn4d2llLacyYV8loRIYksyk6Su7ZmL3nJRezqbL34/W3VW5w/eKxWtcRWhms5e99Av0EMLceMINVE0CZ75EO0qkEl@sKGuGJlr3sJZV3VuC00g74OzHjYRvTQKGnICfNv5j9qmMVrfdodN@f0ToJYVTWXdorTpUfVmI6K28hQ@XRHpr9nLZhNXscjCVKuistLWYRmVjv4oT/7zE@5kfeJ1ZNUPenLshe6nuPQOqdtRuSvpaCOdXUt3/Ac "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~136~~ ~~134~~ 132 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "',ý'(ì')«ˆ"©.V"θ…ˆ†=>쪮.V"Uγ¨D€gPi˜IX.V}\ÙεQƶ0KDāαγ€g£}D2Fε¾iεнyg≠iyθyg<i'|ë„..}ý}}ë˜}'|ý„=>«Iyнн<è«}Ю.VgFDN._ć'>¡X.V}\¼}¯éIgi¦}н ``` *EDIT: Fixed for all test cases now.* [Try it online](https://tio.run/##yy9OTMpM/f9fSV3n8F51jcNr1DUPrT7dpnRopV6Y0rkdjxqWnW571LDA1u7wmkOrDq0DCoae23xohcujpjXpAZmn53hG6IXVxhyeeW5r4LFtBt4uRxrPbTy3GSR7aHGti5Hbua2H9mWe23phb2X6o84FmZXndlSm22Sq1xxe/ahhnp5e7eG9tbWHV5@eUwsU2gsUsrU7tNqz8sLeC3ttDq84tLr28ASQpeluLn568Ufa1e0OLQRbeGhP7aH1h1d6pmceWlZ7Ye///9HmOiBoZARCxligSSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3l4AgiG6Sj5l5ZAxf4rqesc3quucXiNuuah1afblA6t1AtTOrfjUcOy022PGhbY2h1ec2jVoXVAwdBzmw@tcHnUtCY9IPP0nMgIvbDamMMzz22NDDy2zcDb5UjjuY3nNoOkDy2udTFyO7f10L7Mc1sv7K1Mf9S5ILPy3I7KdJtM9ZrDqx81zNPTqz28t7b28OrTc2qBQnuBQrZ2h1ZHVl7Ye2GvzeEVh1bXHp4AsjXdzcVPL/5Iu7rdoYVgGw/tqT20/vDKyPTMQ8tqL@z9r3Nom/2hLXqHtmrG/I@ONtQx0jGO1VEAMpAgqoARbgkYxCsG02REjElDGxrDIMR7RjoEMFiZkbGJqZm5haUBKCjgHCQphDhIUBccdqY65gjbIPaZ64CgoREIGWOBJrGxAA) (except for the 'Huge Input' one, since it's too big). **Explanation:** ``` "',ý'(ì')«ˆ" # Push this string (function 1), which does: ',ý '# Join a list by "," '(ì '# Prepend a "(" ')« '# Append a ")" ˆ # Pop and add it to the global array © # Store this string in the register (without popping) .V # And execute it as 05AB1E code on the (implicit) input-list "θ…ˆ†=>쪮.V" # Push this string (function 2), which does: θ # Pop and push the last element of the list …ˆ†=>ì # Prepend dictionary string "others=>" ª # Append that to the list which is at the top of the stack ®.V # And execute function 1 from the register U # Pop and store this string in variable `X` γ # Get the chunks of equal elements in the (implicit) input-list ¨ # Remove the last chunk D # Duplicate the list of remaining chunks €g # Get the length of each Pi } # If all chunk-lengths are 1: ˜ # Flatten the list of remaining chunks I # Push the input-list X.V # Execute function 2 from variable `X` \ # Discard the top of the stack (in case we didn't enter the if-statement) Ù # Uniquify the (implicit) input-list ε # Map each unique value `y` to: Q # Check for each value in the (implicit) input-list if it's equal to `y` # (1 if truthy; 0 if falsey) ƶ # Multiply each by its 1-based index 0K # Remove all 0s D # Duplicate it ā # Push a list [1, length] without popping the list itself α # Get the absolute difference at the same indices γ # Split it into chunks of the same values €g # Get the length of each £ # And split the duplicated indices-list into those parts # (this map basically groups 1-based indices per value. # i.e. input [1,1,2,1,1,2,2,1,1] becomes [[[1,2],[4,5],[8,9]],[[3],[6,7]]]) }D # After the map: duplicate the mapped 3D list 2F # Loop 2 times: ε # Map the 3D list of indices to: ¾i # If the counter_variable is 1: ε # Map each list `y` in the 2D inner list to: н # Leave the first value yg≠i # And if there is more than one index: yθ # Push the last value as well yg<i # If there are exactly two indices: '| '# Push string "|" ë # Else (there are more than two indices) „.. # Push string ".." }ý # And join the first and last value by this string }} # Close the if-statement and map ë # Else: ˜ # Flatten the 2D list }'|ý '# After the if-else: join by "|" „=>« # Append "=>" yнн # Get the very first index of this 2D list < # Decrease it by 1 to make it 0-based I è # And index it into the input-list to get its value again « # Which is also appended after the "=>" }Ð # After the map: triplicate the result ®.V # Execute function 1 from the register g # Get the amount of items in the triplicated list F # Loop that many times: D # Duplicate the list N._ # Rotate it the index amount of times ć # Extract the head; pop and push remainder and head '>¡ '# Split this head by ">" X.V # And then function 2 is executed again from variable `X` }\ # After the loop: discard the list that is still on the stack ¼ # And increase the counter_variable by 1 }¯ # After looping twice: push the global array é # Sort it by length Igi } # If the input only contained a single item: ¦ # Remove the very first item н # And then only leave the first item # (which is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…ˆ†=>` is `"others=>"`. ]
[Question] [ I'm surprised this hasn't been posted before! The [Consistent Overhead Byte Stuffing](https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing) (COBS) algorithm is used to delimit byte streams. We choose a frame marker (we'll use 0x00) and wherever 0x00 occurs in the stream it is replaced with the number of bytes until the next 0x00 occurs (we'll call this a milestone). This reduces the range of values from 0..255 to 1..255, enabling 0x00 to unambiguously delimit frames in the stream. At a milestone, if the next 255B does not contain 0x00 this exceeds the maximum milestone length - the algorithm must 'stall' at 255B and put another milestone. This is the 'consistent overhead'. The first byte will be the first milestone, the final milestone will be the number of bytes until the frame marker. Some examples from Wikipedia (best to read the article where they are coloured): ``` 0x00 as frame marker Unencoded data (hex) Encoded with COBS (hex) 00 01 01 00 00 00 01 01 01 00 11 22 00 33 03 11 22 02 33 00 11 22 33 44 05 11 22 33 44 00 11 00 00 00 02 11 01 01 01 00 01 02 03 ... FD FE FF 01 02 03 ... FD FE 00 00 01 02 ... FC FD FE 01 FF 01 02 ... FC FD FE 00 01 02 03 ... FD FE FF FF 01 02 03 ... FD FE 02 FF 00 02 03 04 ... FE FF 00 FF 02 03 04 ... FE FF 01 01 00 03 04 05 ... FF 00 01 FE 03 04 05 ... FF 02 01 00 ``` **Challenge:** to implement this in the shortest program. * Input is an unencoded byte stream/array, output is an encoded byte stream/array * Use any sort of binary standard input/output * The final frame marker is not necessary * The program can return an oversized array * A stream ending with 254 non-zero bytes does not require the trailing 0x00 **Notes** * The worst-case return length is `numBytes + (numBytes / 254) + 1` **Example** We have the byte array ``` [0] 0x01 [1] 0x02 [2] 0x00 [3] 0x03 [4] 0x04 [5] 0x05 [6] 0x00 [7] 0x06 ``` For each `0x00` we need to state (in a milestone) where the next `0x00` would have been. ``` [0] 0x03 #Milestone. Refers to the original [2] - "The next 0x00 is in 3B" [1] 0x01 #Original [0] [2] 0x02 #Original [1] [3] 0x04 #Milestone. Refers to the original [6] - "The next 0x00 is in 4B" [4] 0x03 # [5] 0x04 # [6] 0x05 # Originals [3..5] [7] 0x02 #Milestone. Refers to the end frame marker [8] 0x06 #Original [7] [9] 0x00 #Optional. End frame marker. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 114 bytes ``` a=>(g=([v,...a])=>1/v?[v||a.indexOf(0)+1,...g(a)]:[])([0,...a,0].flatMap((v,j)=>1/a[j]&&(i=v&&i+1)>253?[v,i=0]:v)) ``` [Try it online!](https://tio.run/##jVFNT4MwGL7vV/QEfTNWKWyLWYTFePKgO@hO2JhmAyxhQKBrZrL/ji3ThX0Yvbxp3@ejzwMZV7xZ1aKSo6Jcx20StDwIcRrgSDmEEM4gCOmNmkdqv@dEFOt4t0iwC0Nq4BRzYLOIAY7cju64jCQ5l0@8wlg5WafmUcYsC4tAWZYYUgi9ia8NHRG4bKYA2qSsN1yiAHEUhIiTjVYrc1REli@yFkWK6RT0ZVlVcf3AmxgDqfj6RfJaYs9BLgDJSlFgG9kwKLey2vb88rhI5Qe6Q3SK5ujwmk6OZsczaXKxirHroFsANEQ20m30HJ4zRhofyLg5uq/KoinzmORliu3HZ@1pVIcE5g3t9VYslq8n@0Qj35CO2/npL7hzXQa9i651uqLUrDzvAJjp@7/Avm/meHwB/9iemeu693XNP7E3GQPr/gB@d5AA01HoqBSuUCeX1H/Szh3/DuDBZeS@yr@q8qFXlzJovwA "JavaScript (Node.js) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 143 bytes ``` a->{int l=a.length,r[]=new int[l+2],i=0,j=1,x=1,z=0;for(;i<l;){if(a[i]>0)r[j++]=a[i];if(a[i++]<1||++x>254){r[z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hCqIkKqImGqIlOmJF9MRArImRmIiZ2BALSZAkSZE0yZAsyZEqkicFUk2KpETKpIZUyIIsyYqsyYZsyY5ckT05kGtyJCdyJjfkQiNoJI2i0TSGxtI4morG0wSamibSJJpM09AUiqBIiqJoiqFYiqNUFE8JlJoSKYmSKc3@vTiY/2D@12n@g/MPzn@NzqeU7cH5B@e/SufvfgQOzj84/1U6v//a/xc "Java (JDK) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 125 bytes ``` def f(a): r=[[]] for v in a:r+=[[]]*((len(r[-1])>253)+(v<1));r[-1]+=[v]*(v>0) return sum([[len(x)+1]+x for x in r],[])+[0] ``` [Try it online!](https://tio.run/##bZDBTsQgEIbvfYq5bADBBmhrNtXtcR@gJxPCoYlUa1a6YbsNPn2dopsY6wXIN///zwznz@lt9HpZXlwPPe1YnUE4GGNtBv0YYIbBQ1cHntgdpSfnaTD3yrJGVwXjdH5SjD0mhKIZNXMjGaa46Ro8XK4f1JjVFRlHSUyxcY0NVhjLuJE2dT/euq9jZNAeCJD8fRw8JTupn8nOJ6tPVhQMPayxLWtKiT44h8FP0Jpa7S0neU54i0Pta9zEnS6u/qln2ZFiS5YucXtEpYSMWgtEsSg2FBkeZfm7IL7tKRdp6Pyro0roqmJ/qfyXrtqHDdWJcrPNLm4Vgd@/fAE "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` Oµ=0ks€254Ẏḟ€0L‘;Ɗ€F;Ṫ¬x`ƊỌ ``` [Try it online!](https://tio.run/##y0rNyan8/9//0FZbg@ziR01rjExNHu7qe7hjPpBt4POoYYb1sS4g08364c5Vh9ZUJBzreri7578OkDjc7n@s69DWJEOzUO3DMwxCgWof7u4@PMPj4Y7FJtaPGubo6T1qmHusC6hzta6xClDtTh87i2Nd9t6aOg5AaU8/KwUFIO0fGmIFpOdGRVo/atzOFW0QqxNtoAMiDc11jE10DHRMDeEcU0MdMwsIzwAEY62BDg4KP7QESJs@3LENyoKIFAFZQNrg0BIQ1xjG1TEECxxuB/or8j8A "Jelly – Try It Online") A monadic link that takes an unencoded byte array as input and returns the encoded byte array. As per the rules, the final frame marker is omitted. ### Explanation ``` Oµ | Convert to integer and start a new monadic chain =0k | Split after zeros s€254 | Split each list into length 254 lists Ẏ | Tighten (reduce list depth by 1) ḟ€0 | Filter zeros out from each list L‘;Ɗ€ | Prepend the list length plus one to each list F | Flatten ;Ṫ¬x`Ɗ | Append an additional 1 if the original list ended with zero Ọ | Convert back to bytes ``` [Answer] # [Elixir](https://elixir-lang.org/), 109 bytes ``` &Regex.replace~r/(^|(?<=([^\0]{254}))(?!$)|\0)((?2)|[^\0]*?(?=\0|$))/,&1,fn _,_,_,x-><<1+byte_size x>><>x end ``` [Try it online!](https://tio.run/##pZFRS8MwEIDf/RUnjJLMs0vazodxTZ828Enw1boxZyqBLo6uQqbVv16z7UVYqww5uCN3H98dRJfGmaot0ja41y/ahZXelMuV/qpGbN6wjFL2MM/F40c0Tj45Z9nlgDe54IxlEW8Oo2HGsjQXzYDzEQYSCwsL3Ie7VkTy6mlX68XWvGtwSpFyoO1ze3sXGrvd6FUNRciIhFL84qSJ3W0nJQoXRegBF8d/MJ7wKUn6MexZJHG/IsYEx77enCJT@7b27/oVZBgKN5siECmFEBAF0vMIpVmbegITYwtjTb3rNYh/G443zM42/FBE3QogBcc/OkcW/yrD7tvabw "Elixir – Try It Online") [Answer] # [J](https://www.jsoftware.com), 103 chars Notice the result from the last test case is different from wiki and other languages. This is due to this pointer to 254-th zero byte at the boundary. Things get a lot easier, if this isn't treated as a special case. ``` f =: 3 : 0 k =. I. (y,0)=0 s =. - 2 (-/) \ k (>: y i. 0), s (}:k) } y ) f2 =: 3 : 0 f each _254 <\ y ) ``` [Try It Online](https://tio.run/##lY@xDoIwFEX3fsXdbCM8SwtLEXb/gYQYAqEymMhEDN9eWzVC3Lrd3tfTd3pzbkBloGEg2YSKcCHwJZGikmwO5xQKPD0JNJgYrw0WWIIUCWbw1UwCKxYm2KC2hwb0125Eq4oc5yaM4fpuvMNfkuyXdjnLoEKj9V@lNfJ838mN49xSIZ54CJQHIjqU3rQ2ltp3G@xLD3lnS14lCgpEEbkmnuEKx4@cSOI@xfWX1J5E5l4) ]
[Question] [ ## Introduction: I saw there was only [one other badminton related challenge right now](https://codegolf.stackexchange.com/questions/44900/confused-badminton-players). Since I play badminton myself (for the past 13 years now), I figured I'd add some badminton-related challenges. Here the second ([first one can be found here](https://codegolf.stackexchange.com/q/182245/52210)): ## Challenge: Some rules about badminton serves: * A serve will always be done diagonally over the net. * You must always serve after the line that's parallel and nearest to the net. * The area in which you are allowed to serve differs depending on whether it's a single (1 vs 1) or double/mix (2 vs 2). + For singles (1 vs 1), the blue area in the picture below is where you are allowed to serve. So this is including the part at the back, but excluding the parts at the side. + For doubles/mix (2 vs 2), the green area in the picture below is where you are allowed to server. So this is excluding the part at the back, but including the parts at the side. * You may not stand on the lines when serving. But the shuttle will still be inside if they land on top of a line. Here the layout of a badminton field: [![enter image description here](https://i.stack.imgur.com/9jEPO.png)](https://i.stack.imgur.com/9jEPO.png) ## Challenge rules: **Input:** You will be given two inputs: * Something to indicate whether we're playing a single or double/mix (i.e. a boolean) * Something to indicate which block you're serving from (i.e. `[1,2,3,4]` or `['A','B','C','D']` as used in the picture above). **Output:** Only the relevant lines for the current serve (including the net), including an `F` to indicate where you serve from, and multiple `T` to indicate where you will potentially serve to. Although in reality you're allowed to serve from and to anywhere in the designated areas, we assume a person that will serve will always stands in the corner of the serve area closes to the middle of the net, which is where you'll place the `F`. And they will serve to any of the four corners of the area where they have to serve to, which is where you'll place the `T`s. As ASCII-art, the entire badminton field would be the following (the numbers are added so you don't have to count them yourself): ``` 2 15 15 2 +--+---------------+---------------+--+ | | | | | 1 +--+---------------+---------------+--+ | | | | | | | | | | | | | | | | | | | | | | | | | 9 | | | | | | | | | | | | | | | | | | | | +--+---------------+---------------+--+ | | | | | 2 | | | | | O=====================================O 37 times '=' | | | | | | | | | | 2 +--+---------------+---------------+--+ | | | | | | | | | | | | | | | | | | | | | | | | | 9 | | | | | | | | | | | | | | | | | | | | +--+---------------+---------------+--+ | | | | | 1 +--+---------------+---------------+--+ ``` **Examples:** Here two examples for outputting only the relevant parts of the serve: Input: Single and serve block `A` Output: ``` T---------------T | | +---------------+ | | | | | | | | | | | | | | | | | | T---------------T | | | | O=====================================O | | | | +---------------+ | F| | | | | | | | | | | | | | | | | +---------------+ | | +---------------+ ``` As you can see, the `F` is added in the corner within the block, but the `T` are replacing the `+` in the ASCI-art output. --- Input: Double and serve block `C` Output: ``` +--+---------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | F| +--+---------------+ | | | | | | O=====================================O | | | | | | T---------------+--T | | | | | | | | | | | | | | | | | | | | | | | | | | | T---------------+--T ``` ## Challenge rules: * Leading and trailing newlines are optional (including the leading and trailing two empty lines when the input is single). Trailing spaces are optional as well. Leading spaces are mandatory however. * Any four reasonable distinct inputs to indicate which block we're serving from are allowed (for integers, stay within the [-999,999] range); as well as any two reasonable distinct inputs to indicate whether its a single or double/mix (please note [this relevant forbidden loophole](https://codegolf.meta.stackexchange.com/a/14110/52210), though). **Please state the I/O you've used in your answer!** * You are allowed to use a lowercase `f` and `t` (or mixed case) instead of `F` and `T`. * You are allowed to return a list of lines or matrix of characters instead of returning or printing a single output-string. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. [Answer] # [Python 2](https://docs.python.org/2/), ~~285~~ 284 bytes ``` R=str.replace s,q=input() A=' '*19 l='| '[s]+' |'+A[4:]+'|'+A r=['T--+',' T'][s]+'-'*15+'T'+A h=[r]+[l,R(r,*'T+')]*s+[l]*8+[l[:18]+'F'+'|'+A,r,l,l,'O'+'='*37+'O'] h+=[R(l[::-1],*'T+')for l in h[-2::-1]] h[9+2*s]=R(h[9+2*s],*'F ') for l in[l[::q%2*2-1]for l in h[::q/2*2-1]]:print l ``` [Try it online!](https://tio.run/##TZDNasMwEITveorFENbWTxurDU0EOoS2uQaMb0KHElxsEI4judBC3t1dOw0UgTTa/WYWdvgZ23Ovp9fj27vNsmyqbBrjQ2yG8HFqWJIX2/XD15gXbG8RkJc7FixeAV3yAgGuKPbu2ZCeFYvWYa2UQEk9qNEvmCLfRmA9E6110QsXZJVHybEWWHieqOD5lm5nyi05DngLlFEGOnikv0X@9CJIetYK66qcYKNK/5fyeY4QoOuhdUovDeLcTmievK3yuyT6AFiwOz6PNJeV5poc/zKo@HgrejPErh8hTMvLaE2MNd/NCeatcT2VUrO1XP8C "Python 2 – Try It Online") Takes input as `0/1` (or `False/True`) for game type (`Double/Single`), and `0-3` for serving block (`0,1,2,3` = `C,D,A,B`) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes ``` NθF⮌Eθ⁺¹⁶׳ιF✂541⊖θURι±×³Iκ×=¹⁸O⟲O↙⁴J¹±³FF²F²«J×ι±⁺¹²×³θ⁺²×⁻¹⁵׳θκT»F№ABη‖↑F№ACη‖ ``` [Try it online!](https://tio.run/##XVDJTsMwED03X2H55EjmkLRFqBGHkgoJRBel4QNMmLRWHTt1nHJAfHuws7Xgy1gzb94y2ZHpTDHRNC@yrM2mLj5Ak7MfebnSiCRwAV0BWbOSnCnaiboiwT1FKS@gIlOKuO8easF7wTMgeD4LMEUryDQUIA18WjoLSSAzTB4EEE7RBg7MABlpYlYZcnJUkbfTXJp@hB8tVfBwbeMttv9EGbu@td6ENbZYqS/5BrmhaGaHr3VRpooEo8r0Zv0ZD9HC3rWt396kX@pUrwa7wOFNYJelP8TYXnPpYPO/MIpObZ5JL5066Z9OPFa1ay2fbLxje5xc2PuQxXs5@Bsg8T@IHzVN6C2bu4v4BQ "Charcoal – Try It Online") Link is to verbose version of code. Takes the first input as `1` or `2` for singles or doubles, second input as one of `ABCD` as in the question. Explanation: ``` F⮌Eθ⁺¹⁶׳ιF✂541⊖θURι±×³Iκ ``` Loop over the relevant widths and the heights of the `D` court and draw the rectangles. ``` ×=¹⁸O⟲O↙⁴ ``` Draw the net and apply rotational symmetry to add the `A` court. ``` J¹±³F ``` Add the `F` to the `D` court. ``` F²F²«J×ι±⁺¹²×³θ⁺²×⁻¹⁵׳θκT» ``` Add the `T`s to the relevant places in the `A` court. ``` F№ABη‖↑F№ACη‖ ``` Reflect the output as necessary to serve from the correct court. [Answer] # JavaScript (ES7), ~~216 ... 205 201~~ 199 bytes Takes input as `(block)(double)`, where *block* is either \$-2\$ (top right), \$-1\$ (bottom left), \$1\$ (bottom right) or \$2\$ (top left) and *double* is a Boolean value. ``` b=>d=>(g=x=>y<31?`+-| =OTF `[X=x-19,Y=y-15,p=X*Y*b<0,q=Y>0^b&1,X*=X,Y*=Y,i=x*24%35>2|~16>>Y%62%6&2,x<39?Y?p*X|(d?Y:X-87)>169?3:i?X-1|Y-16|q?i:7:q*(d?X-87:Y)%169&&6:x%38?4:5:++y&&8]+g(-~x%40):'')(y=0) ``` [Try it online!](https://tio.run/##ZYvBboJAFEX3fsVbFJiBGcOAoo68maRpu@2mCybGRhG1tsTR2jYQwV@32G0XNzc359z35c/ytPrcHb743hbr6wavOaoCFdlihapOY6EXAW8An1@eeotZhhUXE2aw5mLIDpj5xs/TkB3RqPA1dwXLfMyY8dGwHVZ@NHDioYqai0iUMk4SOYkbsSqNJ9rog581pNBGZnw8okokEx3Lnc64aAwXSXPUOzmSR79zboY01Okc101k5cRjPZBDGQS1647nwZbwS@UMQio9j5IaQ3rd2E9SAEI4hQJSBNF1EFA49wBmPGIgGPAu0bzfqY/L1RvJAdUfB1jZ/cmW635pt2RxX9rVB9yd85bBg/3Oy7XsVgEavHp98kCCt7deu6D/rhuSU1LQG2jptNdefwE "JavaScript (Node.js) – Try It Online") [Formatted version](https://tio.run/##hVLbboJAEH3nK85DFZaLAVRUFEyatq996YPE2iiC1paA1raRePl1O4vGG7YlWXbmnJkzO5N5G3wP5sOPyfRTi5Mg3I6crQ/HRUBHEoAxHCwIIBNI0ULZQDtzgL6ireA8Pj08x/3uHgM6WYYGo6EeMI@wlGPVIzYlrAOZOBk@CetHakaUBxc6XogqwlBP1GVKO1Um3zv6k6y6DLOCAspVEjGxOrD82xgWXJcSC7BM/qMC5lFgwXtsHHrc1WifKUxJv3OhKgVow7MJ11CvMaprWI2LPKB85tsX7CQXj0zPwIreQLdFxuxKEKXmMPtKVE34L2YGOYdlre36gg2P0cx4b8UiLOE3rQWffj331Mqf/VeFa4yipLxWfQ/1oOytsaRteJ2KzoTTJFEUmJTSHuhsO0o@6PlkNhGg5cCgW1EYlhTb1UyVVgsaHbNXotD7wfBVytZ/mWkNk3ieRGEpSsZS/zZKhu@4WfprFXfJlx@FNnl8NmIazkUajRgn4rrPcqkjyWdSwDixZk1hvf0B) ### How? We iterate from \$y=0\$ to \$y=30\$ and from from \$x=0\$ to \$x=39\$ for each value of \$y\$. We first define \$X=x-19\$ and \$Y=y-15\$. The variables `p = X * Y * b < 0` and `q = Y > 0 ^ b & 1` are used to determine what do draw in each quarter according to the block \$b\$. From now on, both \$X\$ and \$Y\$ are squared in order to easily test absolute positions within each quarter of the field. The expression `x * 24 % 35 > 2` yields *false* if \$x\$ belongs to \$\{0, 3, 19, 35, 38\}\$ (the positions of the vertical lines) or *true* otherwise. [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9Io0LBVsHAWqFCwUbBBERra2sqVHMpKCTn5xXn56Tq5eSna1ToAOW1FIxMFFQVjE0V7BSMNK25av//BwA "JavaScript (Node.js) – Try It Online") The expression `~16 >> Y % 62 % 6 & 2` yields \$0\$ if \$y\$ belongs to \$\{0, 2, 12, 18, 28, 30\}\$ (the positions of the horizontal lines, excluding the net) or \$2\$ otherwise. [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9Io1LBVsHAWqFSwUbB2BBIa2trKlRzKShEAsWBkroKhqaaClpaCkbWQMHk/Lzi/JxUvZz8dI1KHYU6QzMFOzugUlUFMyMQoaCmYKRpzVX7/z8A "JavaScript (Node.js) – Try It Online") The variable \$i\$ is defined as the result of a bitwise OR between the two values above, and is therefore interpreted as: * 3: space * 2: `|` * 1: `-` * 0: `+` or `T` The expression `(d ? Y : X - 87) > 169` is used to crop the field according to the game type \$d\$ (single or double). The similar expression `(d ? X - 87 : Y) % 169` is used to draw the `T`'s at the appropriate positions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~108~~ 99 bytes ``` “¢¥Þ‘Ṭ+þ³ḤN+“¢¤€‘¤ṬḤ;Ø0¤×3R¤¦€³+0x39¤µ‘03³?‘;20¤¦€1,-2¦;565DWx“¢%¢‘¤;UṚ$ị“|-+TO= ””F21¦€³Ḥ_⁵¤¦UṚƭ⁴¡ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDiw4tPTzvUcOMhzvXaB/ed2jzwx1L/LQhEkseNa0ByhxaApQDClsfnmFwaMnh6cZBh5YcWgaUO7RZ26DC2BLI2wpUZmB8aLM9kLY2MoDKG@roGh1aZm1qZuoSXgE2UvXQIrCB1qEPd85Sebi7Gyhao6sd4m@r8KhhLhC5GRlCjQZaGP@ocSvIKJDiY2sfNW45tPD/4eWR//8b/jcGAA "Jelly – Try It Online") I’m sure this can be better golfed. Dyadic link with left argument 0 or 1 for singles/doubles and right argument 0,1,2,3 for different serve quadrants. Returns a list of strings Thanks to @KevinCruijssen for saving a byte! ]
[Question] [ Using ASCII print a section of a hexagon ring tiling. Here's a small section: ``` /\__/\ /_/ \_\ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ \ \__/ / \/__\/ ``` Here's a larger section: ``` \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ ``` # Challenge Given 2 integers `h` and `w`, where `h` is the height and `w` is the width, output a `hxw` section of a hexagon ring tiling. # Examples ## Input 1 `4x4` ## Output 1 ``` /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\ ``` ## Input 2 `3x3` ## Output 2 ``` /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ ``` ## Input 3 `1x3` ## Output 3 ``` /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/ ``` ## Input 4 ``` 3x6 ``` ## Output 4 ``` /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ ``` # Clarifications * My question is similar to this one: [Me Want Honeycomb](https://codegolf.stackexchange.com/questions/50320/me-want-honeycomb). * The input will be on a single line in the form `hxw`. * Output to stdout (or something similar). * This is code-golf so shortest answer in bytes wins. [Answer] # Lua, 174 176 156 bytes *The code would print height-amount of lines, not height-amount of hexagons. Added `*4`, that fixed it, but added 2 extra bytes.* *Saved some bytes by changing the counter from if to modulo, and by putting two `io.read()`s into one.* Uses `io.read()` as input. ``` a,w,h,n,d={[[ /\__/\ \__/]],[[/_/ \_\/__\\]],[[\ \__/ /\__/]],[[_\/__\/_/ \\]]},io.read(,),"",0 for i=h*4,0,-1 do d=d+1 d=5%d end n=a[d]print(n:rep(w))end ``` Replicates the strings width-amount of times via `string:rep(width)`, then iterates height-amount of times with a for-loop. Needed `[[]]` (literal strings) because the backslashes really screwed stuff up. *Old Version:* ``` a,w,h,n,d={[[ /\__/\ \__/]],[[/_/ \_\/__\\]],[[\ \__/ /\__/]],[[_\/__\/_/ \\]]},io.read(),io.read(),"",0 for i=h*4,0,-1 do d=d+1 d=5%d end n=a[d]print(n:rep(w))end ``` [Answer] # Befunge, 137 bytes I seem to have created some kind of scifi hand gun. ``` &>4*>~>$&>\>1-:4%3v >00gg,\1-:v^_@#:\<>+00p\::6*\00g2/+2%+1+66+: ^%+66<:+1\_$$55+,^ _\/__\/_/ \ \ \__/ /\__/\ /_/ \_\/__\/ /\__/\ \__/ ``` [Try it online!](http://befunge.tryitonline.net/#code=Jj40Kj5-PiQmPlw-MS06NCUzdgo-MDBnZyxcMS06dl5fQCM6XDw-KzAwcFw6OjYqXDAwZzIvKzIlKzErNjYrOgpeJSs2Njw6KzFcXyQkNTUrLF4KX1wvX19cL18vICBcClwgXF9fLyAvXF9fL1wKL18vICBcX1wvX19cLwogL1xfXy9cIFxfXy8&input=M3g2) **Explanation** ``` &>4*> Read the height and multiply by 4. ~>$ Drop the 'x' separator. &>\ Read the width and swap below the height > Start of the outer loop. 1- Decrement the height. :4%3+00p Calculate the pattern y offset: height%4+3 \ Swap the width back to the top. ::6*\00g2/+2%+1+ Calculate the line length: w*6+(w+y/2)%2+1 66+: Initialise the pattern x offset to 12, and duplicate it. > Start of the inner loop. 00gg Get a pattern char using the x on the stack and the saved y. , Output the char. \1- Swap the line length to the top of the stack and decrement it. :v Check if it's zero, and if so... _ ...break out of the loop to the right. +1\ Otherwise swap the x offset back to the top and increment it. %+66<: Mod it with 12 to make sure it's in range. ^ Then return to the beginning of the inner loop. $$ Drop the x offset and line length. 55+, Output a newline. \< Swap the height back to the top of the stack. _@#: Check if it's zero, and exit if that's the case. ^ Otherwise return to the start of the outer loop. ``` [Answer] ## Python 2, 180 bytes ``` a,b,c,d=' /\__/\ \__/','/_/ \_\/__\\','\ \__/ /\__/','_\/__\/_/ \\' h,w=input() x=w/2 e,E=[(2,1),(7,8)][w%2] print'\n'.join([a*x+a[:e],b*x+b[:E],c*x+c[:E],' '+(d*x+d[:e])[1:]]*h) ``` Takes input as two integers Input: `2,7` Output: ``` /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ /_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\ \ \__/ /\__/\ \__/ /\__/\ \__/ /\__/\ \__/ / \/__\/_/ \_\/__\/_/ \_\/__\/_/ \_\/__\/ ``` [Answer] ## Batch, 266 bytes ``` @echo off for /l %%i in (1,1,%1)do call:l %2 " \" /__\/ "_/ \_\" " \__/ /" \__/\ exit/b :l call:c %1 " /" %6 %5 call:c %1 / %4 %3 call:c %1 \ %5 %6 :c set s=%~2 for /l %%j in (2,2,%1)do call set s=%%s%%%~3%~4 set/ao=%1^&1 if %o%==1 set s=%s%%~3 echo %s% ``` The `:c` subroutine does all the legwork of concatenating the pieces together for a single line; it is called by `:l` 4 times (one by fall though by arranging for `:l`'s arguments to be a superset of `:c`'s) to generate the 4 lines for each row of rings. There was also the possibility of falling through for the last row of rings instead but it turned out to be 5 bytes longer. ]
[Question] [ Your job is to replace the battery packs on many floating fish tracking devices in the shortest time. You must leave your base in the base helicopter and visit each tracker once, then return to the base. Finding the optimum route is known to be hard, but there is an additional difficulty! Each tracker has a drift velocity (which will be assumed to be a constant for the day). ![Example](https://i.stack.imgur.com/DcOhc.png) *This is the standard travelling salesman problem with the added challenge of moving nodes. It should be easy to find a valid tour. The primary challenge is in developing an algorithm to find a near-optimal tour. I predict that it will not be possible to find a perfect tour with the current N=300 (but I would love to be proved wrong).* ### Rules Your program will be supplied with a string of tracker data on STDIN or via a command line argument. You should find a route that visits each tracker exactly once and returns to base. The output should be a white space separated list of tracker ID:time pairs. * Position is given in Centimetres (cm). * Time is measured in seconds starting with t=0. * Velocity is given in cm/sec. * Each tracker ID is 1 to 8 upper case letters. * The base with ID "BASE" is located at `(0,0)`. * All number values for input and output use signed integers. * The input is one or more white space or slash separated trackers. * Each tracker will have `ID:x,y,vx,vy` format (eg: `A:566,-344,-5,11`) * At time t, a tracker will be at `(x+vx*t, y+vy*t)`. * The helicopter must never exceed 5000 cm/sec speed (180 km/hr). * The output should be white space separated visits in time order. * Each visit should be in ID:time format (eg: `A:5723`) * The last visit in your output must be the base (eg: `BASE:6120`) * If more than one tracker is at the same position, it takes zero time to move between them. * The standard loopholes are forbidden. ### Example dataset ``` A:77000,88000,-120,80 B:52000,-12000,0,-230 C:-140000,-23000,-270,110 ``` Example non-optimal solution: ``` A:30 B:60 C:120 BASE:160 ``` Note that `A:30 B:60 C:120 BASE:130` would be invalid because the helicopter would have to fly at 17268 cm/sec to get back to base in 10 seconds. ### Test dataset ``` AA:-164247,-378265,182,113 AB:-1494514,-385520,-25,80 AC:-744551,832058,-13,-123 AD:-930133,1598806,97,177 AE:-280777,-904936,-48,305 AF:-855362,-10456,-21,-89 AG:880990,154342,175,-100 AH:-319708,-623098,172,-17 AI:620018,-626908,-19,-164 AJ:-990505,164998,18,-120 AK:379998,310955,191,59 AL:-977441,-130531,107,-234 AM:-766893,14659,162,-198 AN:-502564,-95651,261,306 AO:661306,-98839,231,263 AP:-788211,254598,24,-249 AQ:851834,-1004246,-45,75 AR:698289,-965536,-8,-134 AS:-128295,701701,180,-241 AT:1423336,1359408,-6,173 AU:445274,-527619,231,319 AV:358132,-781522,26,-132 AW:736129,807327,0,-137 AX:-174581,-337407,133,180 AY:-1533760,-215500,144,-111 AZ:-383050,82658,221,-14 BA:-1650492,548674,89,-63 BB:54477,-906358,440,181 BC:891003,623700,326,102 BD:-393270,1732108,155,-97 BE:411090,-859170,93,163 BF:554962,-298575,480,-100 BG:-695530,475438,244,283 BH:93622,-958266,153,-127 BI:-403222,389691,323,329 BJ:1585132,98244,-156,71 BK:713912,484912,158,97 BL:-1612876,317391,-5,-131 BM:-725126,-320766,30,-105 BN:-76091,-381451,-172,95 BO:-483752,970905,16,-170 BP:1585890,91873,-173,-19 BQ:-815696,-342359,-64,-121 BR:-129530,-606673,-66,-94 BS:-339974,-561442,-35,271 BT:1277427,1258031,13,-5 BU:1246036,-743826,144,-200 BV:494745,-522944,211,309 BW:776786,586255,6,-146 BX:-847071,-792238,-142,-199 BY:748038,863976,6,-109 BZ:-667112,634959,221,-174 CA:888093,900097,-107,-56 CB:113938,-1031815,-167,134 CC:-626804,504649,2,-151 CD:866724,941177,311,221 CE:-1632084,-1957347,38,116 CF:774874,804277,-4,-152 CG:468675,-239063,437,-141 CH:-1352217,-388519,-86,70 CI:-1006,921538,-6,-179 CJ:-1866469,68979,-1,133 CK:-1036883,1962287,124,-62 CL:760226,858123,478,56 CM:764838,493113,-27,-155 CN:-642231,-387271,48,198 CO:430643,646456,8,-138 CP:268900,-82440,294,-114 CQ:-1518402,-1782748,123,62 CR:5487,980492,-30,-151 CS:-749712,494682,-1,-113 CT:-1144956,124994,84,120 CU:-1855045,-612779,30,-35 CV:416593,-57062,-67,-140 CW:-1970914,-1984034,-27,153 CX:-606767,629298,-49,-144 CY:-792900,-696850,0,-123 CZ:1561820,-450390,37,21 DA:579688,355017,-186,-153 DB:1178674,1247470,-86,-54 DC:483389,-837780,321,27 DD:468021,-992185,20,253 DE:-38126,-386917,270,250 DF:707678,189200,-59,-179 DG:-1428781,1326135,-29,-148 DH:-1943667,1645387,22,140 DI:-399820,626361,29,-132 DJ:-2657,170549,94,-169 DK:-331601,917405,104,157 DL:1965031,350999,158,-114 DM:902640,986090,-66,-140 DN:540679,-544126,15,-121 DO:-524120,411839,-48,-120 DP:-134995,-876166,191,-128 DQ:359872,-991469,-164,-186 DR:-186713,-309507,14,-86 DS:1846879,-585704,133,64 DT:169904,945363,298,70 DU:-218003,-1001110,-70,109 DV:316261,266341,-63,-89 DW:551059,55754,-4,-94 DX:-514965,305796,304,-100 DY:162176,485230,-90,83 DZ:675592,-1508331,119,-20 EA:656886,38516,257,-111 EB:-201090,678936,5,-161 EC:-920170,-503904,-8,158 ED:-728819,-401134,-83,154 EE:-611398,-320235,-5,-102 EF:-612522,-259240,14,-154 EG:662225,-808256,478,165 EH:-468284,-720421,234,316 EI:-958544,-161691,-12,-97 EJ:839898,-631917,-25,-159 EK:745130,598504,-72,132 EL:412250,-456628,13,-104 EM:-737096,374111,172,35 EN:726052,-385153,-45,31 EO:-888906,-495174,24,-170 EP:-518672,-685753,-14,-102 EQ:440153,-211801,-46,-180 ER:464493,-1637507,-3,154 ES:701248,-512422,-33,-83 ET:-795959,426838,-29,-117 EU:307451,978526,445,124 EV:800833,66796,15,-176 EW:-623452,299065,-30,-117 EX:15142,-363812,445,245 EY:-701669,-556515,-8,-136 EZ:-1772225,890097,-140,-104 FA:-948887,-882723,-11,-157 FB:387256,-128751,151,7 FC:1066595,-641933,31,-23 FD:-823274,-812209,-67,-172 FE:923612,536985,21,-123 FF:-886616,-808114,-26,-153 FG:411924,-518931,-7,-138 FH:945677,-1038311,174,-59 FI:913968,81871,-5,-139 FJ:625167,708120,-44,-90 FK:-405348,893926,-10,-93 FL:-58670,415334,170,-155 FM:326285,671439,426,-237 FN:-775332,-81583,4,-164 FO:280520,360899,2,-150 FP:-406095,133747,26,170 FQ:-990214,-342198,30,-112 FR:938869,801354,397,198 FS:-7527,36870,-23,-111 FT:999332,-956212,143,16 FU:-86215,792355,-49,-87 FV:144427,378536,-4,-136 FW:-786438,638084,28,-77 FX:903809,903424,-102,-132 FY:-36812,-126503,16,-159 FZ:-1083903,1001142,-29,-110 GA:857943,-120746,135,-3 GB:545227,-151166,239,127 GC:-356823,674293,106,90 GD:977846,1003667,-53,106 GE:-866551,180253,-1,-170 GF:-688577,289359,-24,-161 GG:-256928,-481626,169,109 GH:590910,829914,25,-170 GI:568114,735446,-34,-172 GJ:1756516,-655660,140,138 GK:-1683894,-1417741,-163,-84 GL:-201976,-703352,201,217 GM:-271187,-836075,-24,-141 GN:809929,793308,70,324 GO:-403617,58364,432,-191 GP:-94316,227063,148,28 GQ:-930345,1587220,-129,-142 GR:-433897,58058,-75,255 GS:-780984,114024,-12,-160 GT:-403102,-1425166,158,-84 GU:-449829,-414404,-27,-125 GV:556480,72387,-34,306 GW:-959629,326929,327,-91 GX:250741,-992373,94,-121 GY:702250,1612852,-41,38 GZ:853191,857773,-62,-105 HA:674500,-225890,7,-152 HB:-1890026,-179534,-23,49 HC:398363,681200,31,-26 HD:-1896372,113239,-51,25 HE:599213,137473,10,-31 HF:-34537,750768,-18,-179 HG:-959544,-430584,-33,-117 HH:1283773,1606578,-8,-80 HI:-866804,108513,180,-74 HJ:765654,115993,23,-22 HK:554000,130015,18,-32 HL:-470089,-407430,38,191 HM:366977,556677,18,-134 HN:175829,545309,29,-146 HO:-263163,-235953,3,-169 HP:727495,567716,6,-135 HQ:121304,-9150,81,-157 HR:-1789095,-471348,-73,-9 HS:-799974,819873,51,-64 HT:-985175,1774422,70,-10 HU:516368,-227142,-33,-117 HV:655503,350605,-6,-92 HW:733506,-1967066,197,-62 HX:1339705,-1227657,-195,44 HY:-384466,-1932882,7,-93 HZ:-394466,-459287,132,95 IA:120512,-1673367,28,-167 IB:1294647,-1112204,35,133 IC:883230,734086,144,54 ID:-95269,435577,30,148 IE:-378105,-1147004,-6,190 IF:366040,-132989,339,-61 IG:-397775,-410802,-1,-84 IH:849353,-181194,-98,45 II:774834,-56456,-177,21 IJ:-441667,576716,-51,-82 IK:-309799,-673582,-34,-99 IL:605784,-903045,-179,103 IM:-379218,-958590,-6,262 IN:982984,947942,212,-28 IO:-477749,-472771,474,44 IP:-1381284,-1273520,131,139 IQ:672901,1298275,-116,150 IR:-816582,-693425,121,-265 IS:809060,-66216,-45,-165 IT:655913,723612,6,-102 IU:70578,-546308,496,219 IV:558122,41452,-20,-103 IW:237612,-1605017,154,170 IX:-1120980,-471873,-181,-134 IY:-1385384,36137,-14,15 IZ:1401932,-1692315,103,115 JA:1339559,1534224,123,46 JB:-963572,-554932,-13,-153 JC:1422496,-213462,-97,-63 JD:-74743,-909157,277,273 JE:-1364398,911720,185,-19 JF:831273,-645419,-61,-147 JG:-308025,-297948,-59,-107 JH:-737466,-424236,419,219 JI:234767,971704,375,89 JJ:-715682,-871436,395,-54 JK:-296198,-466457,11,227 JL:277311,-661418,27,-124 JM:113477,-763303,-61,-142 JN:198929,881316,358,67 JO:864028,-1735917,-168,-162 JP:193352,-46636,12,-171 JQ:-374301,967915,-27,-98 JR:-900576,1585161,-14,-154 JS:-855414,-201048,24,-150 JT:473630,412948,-80,68 JU:-358039,-730839,-18,47 JV:677652,-670825,-63,-146 JW:536063,-734897,-86,57 JX:344532,-594945,143,230 JY:218390,42085,406,-154 JZ:222495,-933383,440,-29 KA:993576,490730,448,13 KB:1383947,-1637102,-146,-175 KC:181730,-314093,-20,47 KD:1400934,502742,-77,-126 KE:1239862,1152873,144,102 KF:-156867,290487,5,-92 KG:947301,958346,-12,-124 KH:-1873578,815339,194,167 KI:1181091,882850,89,-122 KJ:-825910,-452543,369,9 KK:548963,-358292,390,117 KL:-940596,-200000,125,296 KM:463530,905548,-70,-95 KN:-7507,263613,-7,-145 KO:172069,-457358,-40,-113 KP:-206484,-214043,172,-4 KQ:620049,1844897,-158,192 KR:-988657,612294,452,-125 KS:-802234,611144,-34,-178 KT:231136,-858200,123,129 KU:1557166,943150,105,114 KV:-229389,-440910,-71,123 KW:-135216,1346978,15,136 KX:-43852,521638,-38,279 KY:112655,441642,-8,-105 KZ:525746,-216262,8,-124 LA:-985825,-345745,33,187 LB:-839408,-319328,-6,-136 LC:-12208,1899312,-168,149 LD:156476,-902318,69,325 LE:976731,-427696,310,165 LF:-809002,-255961,312,235 LG:-899084,484167,5,57 LH:-748701,426117,256,-21 LI:-711992,148901,-49,24 LJ:-519051,-440262,22,-105 LK:-310550,283589,88,151 LL:244046,-1751273,5,29 LM:1350149,-1524193,-96,-158 LN:-706211,-585853,-63,-122 ``` ### Verifier A program similar to the following verifier will be used to check the answers. You can use this program to check your answers before posting. ``` # PPCG: Visiting each drifting tracker # Answer verifier for Python 2.7 # Usage: python verify.py infile outfile [-v] # Infile has the given input string. Outfile has the solution string. # v1.0 First release. import sys, re VERBOSE = ('-v' in sys.argv) fi, fo = sys.argv[1:3] def error(*msg): print ' '.join(str(m) for m in ('ERROR at:',) + msg) sys.exit() indata = open(fi).read().strip() trackdata = [re.split('[:,]', node) for node in re.split('[ /]', indata)] trackers = dict((node.pop(0), map(int, node)) for node in trackdata) shouldvisit = set(trackers.keys() + ['BASE']) visittexts = open(fo).read().split() visitpairs = [node.split(':') for node in visittexts] visits = [(label, int(time)) for label,time in visitpairs] fmt = '%10s '*5 if VERBOSE: print fmt % tuple('ID Time Dist Tdiff Speed'.split()) prevpos = (0, 0) prevtime = 0 visited = set() for ID, time in visits: if ID in visited: error(ID, 'Already visited!') tdiff = time - prevtime if tdiff < 0: error(ID, 'Time should move forward!') if ID == 'BASE': newpos = (0, 0) else: if ID not in trackers: error(ID, 'No such tracker') x, y, vx, vy = trackers[ID] newpos = (x+vx*time, y+vy*time) if newpos == prevpos: dist = speed = 0 else: dist = ((newpos[0]-prevpos[0])**2 + (newpos[1]-prevpos[1])**2) ** 0.5 if tdiff == 0: error(ID, 'Helicopters shouldn\'t teleport') speed = dist / tdiff if speed > 5000: error(ID, 'Helicopter can\'t fly at', speed) if VERBOSE: print fmt % (ID, time, int(dist), tdiff, int(speed)) visited.add(ID) prevpos = newpos prevtime = time if ID != 'BASE': error(ID, 'Must finish at the BASE') if visited != shouldvisit: error((shouldvisit - visited), 'Not visited') print 'Successful tour in %u seconds.' % time ``` ### Scoring Your score will be your final time in seconds. Lower is better. The winner will be the answer with the fastest time on the test dataset after the return to base. In the result of a tie, the earliest entry will win. Please post solutions with a "Language, Score: NNN" title, the code, and the output solution string (with several visits per line prefered). [Answer] # Python, Score: ~~20617~~ 17461 I do not have much experience with these types of problems and don't really know what the best known methods are, but I used a method which I've had moderate success with in the past and I'm interested to see how it compares to other answers. ``` from __future__ import division from math import * import itertools class Visitor: def __init__(self,data): self.trackers = self.parse(data) self.weights = {} avg = 0 for key in self.trackers: x,y,vx,vy = self.trackers[key] w = hypot(vx,vy)**2 self.weights[key] = w avg += w avg /= len(self.trackers) for key in self.weights: self.weights[key] += avg def parse(self,data): result = {} for line in data.split('\n'): id,vars = line.split(':') x_str,y_str,vx_str,vy_str = vars.split(',') result[id] = (int(x_str),int(y_str),int(vx_str),int(vy_str)) return result def convert(self,path,final): result = "" total_time = 0 for (id,time) in path: total_time+=time result += "%s:%s "%(id,total_time) return result + "BASE:"+str(final) def time_to(self,target,begin,offset=0): bx,by,dx,dy = begin tx,ty,vx,vy = target bx+=dx*offset by+=dy*offset tx+=vx*offset ty+=vy*offset t = 0 for inter in [1000,100,20,10,4,1]: speed = 5001 while speed > 5000: t += inter cx,cy = tx+vx*t,ty+vy*t speed = hypot(bx-cx,by-cy)/t if speed == 5000: return time t -= inter return t+1 def path_initial(self): print 'Creating Initial Path' path = [] tracks = self.trackers.copy() remaining = self.trackers.keys() px,py = 0,0 distance = 0 def score(id): if len(remaining) == 1: return 1 t = self.time_to(tracks[id],(px,py,0,0)) all_times = [self.time_to(tracks[id],tracks[k],t) for k in remaining if k != id] return t*len(all_times)/sum(all_times)/self.weights[id] while remaining: print "\t{0:.2f}% ".format(100-100*len(remaining)/len(tracks)) next = min(remaining,key=score) t = self.time_to(tracks[next],(px,py,0,0)) path.append((next,t)) for k in tracks: ix,iy,ivx,ivy = tracks[k] tracks[k] = (ix+ivx*t,iy+ivy*t,ivx,ivy) px,py = tracks[next][:2] remaining.remove(next) return path def path_time(self,ids): path = [] total_time = 0 tracks = self.trackers.copy() px,py = 0,0 distance = 0 for i in ids: t = self.time_to(tracks[i],(px,py,0,0)) path.append((i,t)) total_time += t for k in tracks: ix,iy,ivx,ivy = tracks[k] tracks[k] = (ix+ivx*t,iy+ivy*t,ivx,ivy) px,py = tracks[i][:2] return path,total_time+int(hypot(px,py)/5000+1) def find_path(self,b=4): initial = self.path_initial() current_path,current_time = self.path_time([c[0] for c in initial]) pos = None last_path = None last_time = None count = 1 while last_path != current_path: print 'Pass',count best_path,best_time = [c[0] for c in current_path],current_time for i in range(len(current_path)-b): print "\t{0:.2f}% ".format(100*i/(len(current_path)-b)) sub = best_path[i:i+b] for s in itertools.permutations(sub): new = best_path[:] new[i:i+b]=s npath,ntime = self.path_time(new) if ntime < best_time: best_path = new best_time = ntime last_path,last_time = current_path,current_time current_path,current_time = self.path_time(best_path) count += 1 return self.convert(current_path,current_time) import sys in_fname,out_fname = sys.argv[1:3] with open(in_fname) as infile: visitor = Visitor(infile.read()) s = visitor.find_path() print s with open(out_fname,"w") as file: file.write(s) ``` Firstly note that this always tries to maximize the speed between nodes, getting as close to 5000 cm/s as an integral value allows. I don't know if this is necessarily optimal, but removing a degree of freedom obviously makes things much simpler. The initial step is to create an path by simply choosing one target after another. In this decision each target is weighted negatively by how far the target is from the current position and weighted positively by the average distance from the target to all the remaining possible nodes. This way it tries to go for targets that are closer to it *relative* to other nodes. Once it has created an initial path, it loops through it, taking every consecutive `b` nodes and testing the new path time for every permutation of these nodes.\* It repeats this process until doing so makes no change to the path. \*The default value of `b` is `4`, however the value given as my score is my result for running it with `b=6`. I may run it with higher values and update my score accordingly later. **Edit:** I made a small modification to the deciding process of the initial path which now weights faster targets as higher priority. This seems to be a very significant improvement. --- To run it simply use ``` visit.py infile.txt outfile.txt ``` (I would also suggest using `pypy` or something as it does take some time to run) Example output: ``` FS:8 JY:58 CP:86 FB:110 IF:113 CG:149 BF:173 KK:179 BV:209 AU:218 IU:276 KC:314 EX:319 DE:340 IO:414 EH:445 BS:475 HZ:482 HL:514 JH:528 KJ:563 EE:577 EF:584 CN:601 LF:634 AM:645 GS:680 KL:693 GE:705 AP:725 HI:734 GW:775 CX:828 KR:836 EM:858 LH:871 BZ:890 IJ:896 BG:945 BO:959 FK:970 JQ:984 KX:1049 CR:1061 BI:1078 CI:1089 ID:1117 HF:1128 AN:1191 DX:1211 KF:1213 AZ:1238 KN:1257 GO:1324 HQ:1338 JP:1351 LD:1387 JD:1407 EQ:1424 BB:1500 JZ:1580 DC:1621 EG:1733 LE:1813 BJ:1901 KD:1911 FM:1934 AO:1977 CL:2152 KU:2195 FR:2206 CD:2270 KE:2282 EU:2333 JI:2380 JN:2412 DB:2436 DT:2450 GN:2553 AT:2646 JA:2708 BC:2860 KA:2988 DL:3098 GJ:3165 DS:3201 EA:3353 AG:3385 GA:3418 GB:3504 KI:3543 IN:3638 IC:3708 BK:3737 AK:3811 KG:3854 BY:3882 JX:3920 GL:3988 AA:4007 DD:4018 CO:4040 GI:4053 HM:4059 IH:4063 GG:4072 HN:4100 KP:4156 EN:4164 CM:4195 FL:4212 AS:4229 DW:4250 IV:4267 DJ:4302 DF:4314 AH:4338 HU:4352 EL:4393 ER:4403 HX:4419 FG:4447 JL:4464 JV:4487 AV:4506 AI:4518 JF:4531 EJ:4567 DP:4589 GX:4610 AR:4619 BH:4649 JJ:4760 IW:4839 EV:4861 FI:4900 JC:4919 KT:4984 BW:5001 HP:5014 HV:5041 HK:5058 HE:5061 GH:5075 BP:5082 CF:5094 AW:5110 IT:5132 DM:5160 GZ:5172 FJ:5204 FX:5211 AX:5298 HC:5315 GP:5358 BE:5441 HJ:5450 FE:5490 IB:5592 CZ:5649 FT:5756 IZ:5804 FH:5877 BU:5992 HW:6080 DZ:6256 GT:6431 LM:6552 KB:6630 IA:6652 IR:6739 JO:6832 HY:6887 DQ:6994 FA:7071 FF:7093 FD:7148 BX:7271 GK:7480 IX:7617 EZ:7938 HD:8064 HB:8115 CH:8125 GQ:8176 AB:8241 DG:8277 BN:8347 IY:8397 FZ:8437 CB:8446 JR:8512 II:8576 BA:8613 IL:8625 DU:8650 AC:8687 CS:8743 CC:8817 AJ:8864 EW:8898 DO:8919 ET:8942 AF:8981 KS:9021 DA:9028 EI:9035 GF:9077 JG:9101 FQ:9133 BR:9154 LB:9193 FN:9225 GU:9235 JS:9249 IK:9251 EP:9261 EY:9308 CY:9314 EO:9370 GM:9407 JM:9422 AL:9536 HO:9650 FY:9731 IS:9782 DN:9847 HA:9859 KZ:9922 LL:9985 ES:10014 FO:10056 FV:10106 KY:10182 DI:10215 DV:10263 EB:10340 CQ:10376 DR:10419 AY:10454 IG:10532 BM:10559 CV:10591 LJ:10594 KO:10616 JB:10820 LN:10903 HG:10947 BQ:10988 BL:11100 CU:11140 CE:11235 FU:11380 JU:11397 FW:11419 KM:11448 JW:11479 CA:11549 HS:11594 AQ:11709 IP:11813 JE:11964 HH:12033 BD:12095 BT:12223 GC:12376 LK:12459 DK:12611 KH:12690 AD:12887 GV:12938 KQ:13265 LC:13452 DH:13597 GR:13635 IQ:13748 AE:13763 KW:13967 JK:14080 IM:14145 LA:14232 EK:14290 FP:14344 GD:14395 GY:14472 CT:14532 IE:14650 EC:14771 DY:14807 CJ:14966 ED:15002 CW:15323 HR:15546 LI:15913 KV:16117 JT:16227 LG:16249 HT:16450 CK:16671 FC:17080 BASE:17461 ``` [Answer] # Python 3, score = 21553 The program uses a naive greedy approach. It always calculates where should it go to catch a tracker (any of them) in the shortest time possible. Runs in a couple seconds. ``` import re class tracker: def __repr__(s): return str([s.id,s.x,s.y,s.vx,s.vy]) def dist2(e,t): return (e.x+t*e.vx-x)**2+(e.y+t*e.vy-y)**2 def closest(x,y,t,tr): tp=0 while 1: min_dist2,min_ind=min((dist2(e,t+tp),ind) for ind,e in enumerate(tr)) if min_dist2<(tp*5000)**2: be=tr[min_ind] return be.x+(t+tp)*be.vx,be.y+(t+tp)*be.vy,min_ind,t+tp tp+=1 tr=[] #x,y,vx,vy,id with open('tracklist') as f: for l in f.read().split(): a=tracker() a.id,data=l.split(':') a.x,a.y,a.vx,a.vy=[int(s) for s in data.split(',')] tr+=[a] x,y,gx,gy=0,0,0,0 t=0 r=[] #id,time while tr: x,y,ti,t=closest(x,y,t,tr) r+=[(tr[ti].id,t)] #print(len(tr),t,tr[ti].id) del tr[ti] if not tr and r[-1][0]!='BASE': a=tracker() a.id,a.x,a.y,a.vx,a.vy='BASE',0,0,0,0 tr+=[a] print(*[re[0]+':'+str(re[1]) for re in r]) ``` Route: ``` FS:8 DJ:34 KN:53 GP:70 KF:89 LK:119 BI:149 IJ:181 DI:195 GC:218 EB:247 AS:272 KX:281 HF:301 FU:320 CI:348 CR:362 DK:420 JQ:443 FK:459 BO:475 BG:531 BZ:549 CX:567 KR:586 FW:600 KS:622 LG:638 CS:674 ET:694 GW:719 GF:738 LI:747 AP:769 HI:778 GS:797 KL:812 GE:818 AJ:841 AF:878 LA:903 EI:919 EC:942 AL:953 JS:962 ED:982 FN:990 AM:1026 CN:1028 HL:1061 BS:1078 KV:1094 BN:1105 JK:1119 JH:1127 HZ:1162 EH:1172 DR:1186 HO:1205 KJ:1228 JG:1231 IG:1249 AE:1261 IM:1284 JU:1294 IK:1322 DU:1336 IE:1353 GM:1386 JJ:1421 CB:1444 BR:1472 AH:1511 KO:1546 IL:1594 FG:1611 KT:1631 EL:1636 JW:1645 DD:1671 BE:1685 ES:1706 DN:1732 AI:1765 JV:1770 JF:1802 AQ:1815 EJ:1827 JZ:1880 HX:1916 AR:1976 IW:2005 ER:2027 GX:2045 BH:2054 AV:2087 JL:2118 DP:2166 JM:2229 DQ:2297 GT:2338 LL:2398 IA:2481 JO:2533 KB:2646 LM:2682 HW:2735 DZ:2861 FH:2975 BU:3027 IZ:3034 FT:3137 DC:3170 IB:3193 FC:3242 GO:3285 JC:3319 IO:3339 CP:3382 IF:3442 EA:3444 BB:3459 AG:3484 GA:3518 KD:3574 FE:3601 JD:3616 BP:3629 HJ:3651 BW:3662 HP:3673 HE:3698 HV:3701 HK:3704 DX:3720 CM:3731 FL:3755 EN:3776 DW:3784 IV:3799 KP:3824 FO:3857 FV:3892 KC:3899 DV:3911 II:3933 KY:3934 HN:3978 GG:4004 IH:4016 HM:4021 GI:4027 CO:4039 AZ:4056 AA:4073 GL:4096 GH:4115 CF:4131 AW:4145 IT:4162 DM:4185 GZ:4193 FX:4221 FJ:4229 LH:4250 AX:4272 LD:4289 HC:4312 CA:4340 LF:4376 DB:4444 AN:4505 GD:4548 GV:4616 BD:4660 EK:4681 ID:4755 FP:4831 DY:4845 JE:4885 CT:4943 JR:4995 FZ:5087 BA:5131 IY:5189 AB:5227 CH:5265 HB:5312 HD:5358 EZ:5433 CJ:5598 GQ:5642 DG:5705 AC:5877 DO:5960 EW:5980 CC:6018 IP:6026 DA:6055 AY:6124 EE:6135 BM:6156 LJ:6197 EF:6236 GU:6256 EP:6283 CQ:6313 EY:6319 CY:6334 EO:6357 JB:6420 LN:6456 HG:6495 BQ:6512 CE:6546 CU:6636 BL:6694 CW:6822 HR:6908 IX:7087 GK:7239 BX:7438 FD:7558 FF:7615 FA:7640 LB:7784 FQ:7826 CV:7955 FY:8018 JP:8058 IS:8090 KZ:8136 HQ:8177 EV:8210 HA:8254 FI:8340 HU:8471 DF:8495 EQ:8587 HY:8799 IR:8932 KG:9512 BY:9523 EM:9703 HH:9763 BT:9850 JX:9973 BK:10091 IC:10129 AK:10203 GB:10350 GJ:10436 IN:10463 DS:10577 DL:10789 JY:11049 FM:11146 CG:11213 BF:11363 KA:11783 EG:11886 CL:11966 IU:12107 EU:12210 EX:12271 FR:12418 CD:12652 AO:12901 AU:12976 BV:13022 DE:13154 KE:13262 KU:13303 JA:13366 DT:13620 JN:13804 LE:13831 BC:13879 JI:13914 KK:14134 FB:14869 CZ:14975 KI:15161 CK:15670 HT:15870 GY:15992 JT:16216 BJ:16275 HS:16636 KM:16813 KW:17719 AD:17965 AT:18082 KH:18226 GN:18841 DH:19723 IQ:19760 GR:19948 KQ:20117 LC:20351 BASE:21553 ``` ]
[Question] [ [Order and Chaos](http://en.wikipedia.org/wiki/Order_and_Chaos) is a variant of Tic-Tac-Toe played on a 6x6 board. What makes the game unique, however, is that both players can place either an X or an O! Each turn (starting with Order), a player places an X or O in any unoccupied square. Winning is simple. Order wins if there are 5 Xs or Os (vertically, horizontally, or diagonally) in a row on the board. Chaos wins if the board is filled and there are no strings of 5 Xs or Os on the board. Your job? Well, since this is **Programming** Puzzles and Code Golf, you're going to program the game, and golf it. ### The Rules * You must accept input as `x y t`, where `x` and `y` are coordinates, and `t` is the tile type (`X` or `O`). Coordinates start with `0 0` in the upper-left corner and increase up to `5 5` (the lower-right corner). * You must accept `q` to quit, and print `INVALID` if the user enters invalid coordinates, tiles, any input not in the form of `x y t`, or tries to place a tile where there already is one. (The only exception is `q`, as this quits the program.) * If Order wins, you will output `P1 WINS`. If Chaos wins, you will output `P2 WINS`. * Order must go first. * A blank space is represented by `.`. * Tiles are `X` and `O` (uppercase). You do not have to accept lowercase, but uppercase is required. * Your board must only consist of `.XO`. * You're actually simulating both players playing the game, not being given a board and checking who wins. It accepts a move as input, then prints the board, accepts another move, and so on, until one player wins. The starting board looks like this: ``` ...... ...... ...... ...... ...... ...... ``` And after the first player (Order) inputs `1 2 X`, it should look like this: ``` ...... ...... .X.... ...... ...... ...... ``` Likewise, when the next player (Chaos) inputs `3 3 O`, it will look like this: ``` ...... ...... .X.... ...O.. ...... ...... ``` And this continues until one player wins. As always, [Standard loopholes which take the fun out of everything](http://meta.codegolf.stackexchange.com/q/1061/38891) are forbidden. The winner is the one with the shortest code on June 15, 00:00 UTC (about one month from when this challenge was posted.) [Answer] # JavaScript, 360 **Edit** Modified interactive game, should run even in MSIE As requested, text based game, input via popup, output in console (so to have a monospaced font). Quit game with 'q' or clicking 'cancel' at prompt. Not using ES5 features, it should run on any moder browser (where you can have a JS console panel) ``` b='\n......'.repeat(6).split(''); for(h=t=0;!h&t<36;) { i=prompt(); if(i=='q')i=null; i=i.match(/([0-5]) ([0-5]) ([XO])/); m='INVALID'; if(b[p=i?i[2]*7-~i[1]:0]=='.') { ++t; b[p]=i[3]; m=b.join(''); for(x=z='',c=0;c++<6;) for(x+='_',z+='_',r=0;r<6;r++) x+=b[c+r*7],z+=b[c<4?c-1+r*8:c+1+r*6]; h=(/X{5}|O{5}/.test(b.join('')+x+z)) } console.log(m); } console.log("P"+(2-h)+" WINS") ``` **Now, some more fun** Interactive and graphic version, run snippet to play. ``` function start() { b=Array(7).join('\n......').split(''); t=0; $('#O').text(''); $('table')[0].className=''; show(); $('th').eq(1).html('Left-click: O<br>Right-click: X'); $('#B') .off('mouseup') .on('mouseup','td.F',function(ev){ var x,y, p=~~this.id.slice(1) x=p%7-1 y=p/7|0 b[p]=ev.which > 1 ?'X':'O'; ++t for(x=z='',c=0;c++<6;) for(x+='_',z+='_',r=0;r<6;r++) x+=b[c+r*7],z+=b[c<4?c-1+r*8:c+1+r*6]; show() if (/X{5}|O{5}/.test(b.join('')+x+z)) end(1) else if(t==6*6) end(2) return false }) } function end(w) { var n=['Order','Chaos'][w-1] $('th').eq(0).text('P'+w+' '+n+' Wins') $('th').eq(1).text('Click to play again') $('table')[0].className=$('tr')[0].className =n[0]; $('#B').off('mouseup').on('mouseup', start) } function show() { var w,p p=t&1 $('tr')[0].className=$('#B')[0].className='OC'[p]; w=b.map(function(c,i){ return c>' '?'<td class='+(c=='.'?'F':'X')+' id=C'+i+'>'+c+'</td>':'</tr><tr>' }).join(''); $('th').eq(0).text('Playing: '+['Order','Chaos'][p]); $('#B').html('<tr>' + w +'</tr>'); } start() ``` ``` th { font-size: 12px; } .C th { color: #807; } .O th { color: #047; } .C td.F:hover { background: #f0e; } .O td.F:hover { background: #0fe; } table.C td { background: #f0e; } table.O td { background: #0fe; } td { font-family: monospace; font-size: 12px; width: 1.2em; height: 1em; text-align: center; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr><th colspan=6></th></tr> <tbody id=B></tbody> <tr><th colspan=6></th></tr> </table> <p id=O></p> ``` [Answer] # PHP, 316 Here is my submission. It has to be executed by php in the command line. Note that this code produces notices because of some shortcuts I made. Let me know if this is ok. I can fix it by adding a few more characters. I checked [this page](http://meta.codegolf.stackexchange.com/questions/1654/php-and-warnings) and the top answer says to assume that error reporting is turned off if there is no mention about it. ``` <?for(;$i++<6;)$b.='......|';while(($a=trim(fgets(STDIN)))!='q'){preg_match('/^([0-5]) ([0-5]) ([XO])$/',$a,$d)&($b[$c=$d[2]*7+$d[1]]=='.')?$b[$c]=$d[3]:print"INVALID\n";echo str_replace("|","\n",$b); foreach([0,5,6,7]as$e)preg_match('/(X|O)(.{'.$e.'}\1){4}/',$b)-1?:die("P1 Wins");strstr($b,'.')?'':die("P2 Wins");} ``` And here is the un-golfed version of the code: ``` <?php error_reporting(E_ALL & ~E_NOTICE); for(;$i++<6;)$b.='......|'; while(($a=trim(fgets(STDIN)))!='q'){ #Validate and assign preg_match('/^([0-5]) ([0-5]) ([XO])$/',$a,$d)&($b[$c=$d[2]*7+$d[1]]=='.')?$b[$c]=$d[3]:print"INVALID\n"; #Output echo str_replace("|","\n",$b); #Check if Order wins foreach([0,5,6,7]as$e) { preg_match('/(X|O)(.{'.$e.'}\1){4}/',$b)-1?:die("P1 Wins"); } #Check if Chaos wins strstr($b,'.')?'':die("P2 Wins"); } ``` [Answer] # Java, 565 chars D: ``` public class M{public static void main(String[]r){int[]p=new int[36];int u=0;for(;;){String l=new java.util.Scanner(System.in).nextLine();if(l == "q")break;int a=l.charAt(0)-'0'+(l.charAt(2)-'0')*6,i=p[a]==0?1:0;if(i>0)p[a]=l.charAt(4);u+=i;r(i==0?"INVALID\n":"");if(u==36){r("P2 WINS");break;}for(int x=0;x<6;x++)for(int y=0;y<6;y++)for(int d=0;d<3;d++)try{int e=1,c=p[x+y*6],z=x,h=y;if(c=='X'||c=='Y'){for(;e<6;e++){if(d%2==0)z++;if(d>0)h++;if(p[z+h*6]!=c)break;}if(e==5){r("P1 WINS");return;}}}catch(Exception e){}}}static void r(Object o){System.out.print(o);}} ``` This is probably the longest code-golf ever. I'm really not good at this. [Answer] # Octave, 453 ``` format plus 'XO.' disp(F=zeros(6)) r=@()fread(0,1);R=@()r()-47;q=@(m)printf(m)&&quit;e=@()q("INVALID");l=@(n)n<1||n>6&&e();s=@()r()==32||e();w="P1 WINS";f=@(v)abs(sum(v))==22.5&&q(w);g=@(m)any(abs(sum(m))==22.5)&&q(w);d=@diag;while 1 i=R();i==66&&quit;l(i);s();l(j=R());s();F(j,i)&&e();abs(v=R()-36.5)==4.5||e();F(j,i)=v;disp(F) r();f(d(F,-1));f(d(F,0)(2:6));f(d(F,0)(1:5));f(d(F,1));g(F(1:5,:));g(F(2:6,:));g(F(:,1:5)');g(F(:,2:6)');F&&q("P2 WINS");end ``` The implementation is quite straightforward, the only real “trick” to use `format plus` to take care of printing. Here is a commented version: ``` format plus 'XO.' # this is where the magic happens ## initialize and print empty board disp(F=zeros(6)) ## shortcuts r=@()fread(0,1); R=@()r()-47; q=@(m)printf(m)&&quit; e=@()q("INVALID"); l=@(n)n<1||n>6&&e(); s=@()r()==32||e(); w="P1 WINS"; f=@(v)abs(sum(v))==22.5&&q(w); g=@(m)any(abs(sum(m))==22.5)&&q(w); d=@diag; while 1 i=R(); # read index 1 i==66&&quit; # ‘q’? l(i); # check bounds s(); # read and check space l(j=R()); # read and check index 2 s(); # read and check space F(j,i)&&e(); # square already filled? abs(v=R()-36.5)==4.5||e(); # valid mark? F(j,i)=v; # assign … disp(F) # and print board r(); # read off newline ## check diagonals f(d(F,-1)); f(d(F,0)(2:6)); f(d(F,0)(1:5)); f(d(F,1)); ## check rows g(F(1:5,:)); g(F(2:6,:)); ## check columns g(F(:,1:5)'); g(F(:,2:6)'); ## check chaos F&&q("P2 WINS"); end ``` Because of the requirement to check input syntax and validity, the code uses `fread()` to read one character at a time. I took care to output the board and messages in a tidy manner. If some extra output is acceptable, I could shave off a couple of bytes. For example, using automatic printing (no `disp(F)`), the board would be shown as ``` F = ...... ...... ...... ...... ...... ...... ``` Also, I interpreted that each move is given on a separate line. --- Sample interaction (the `-q` switch is just to suppress Octave's header): ``` $ octave -q order_chaos.m ...... ...... ...... ...... ...... ...... 3 3 X ...... ...... ...... ...X.. ...... ...... 2 3 O ...... ...... ...... ..OX.. ...... ...... 3 3 O INVALID ``` The invalid move caused the program to exit (not sure if that was intended). ]
[Question] [ A *binary string* is a string which contains only characters drawn from *01*. A *balanced binary string* is a binary string which contains exactly as many *0*​s as *1*​s. You are given a positive integer *n* and an arbitrary number of masks, each of which is *2n* characters long, and contains only characters drawn from *012*. A binary string and a mask match if it is the same length and agrees on the character in every position where the mask doesn't have a *2*. E.g. the mask *011022* matches the binary strings *011000*, *011001*, *011010*, *011011*. Given *n* and the masks as input (separated by newlines), you must output the number of distinct balanced binary strings which match one or more of the masks. ## Examples Input ``` 3 111222 000112 122020 122210 102120 ``` Reasoning * The only balanced binary string matching *111222* is **111000**. * The only balanced binary string matching *000112* is **000111**. * The balanced binary strings matching *122020* are *111000* (already counted), **110010** and **101010**. * The balanced binary strings matching *122210* are *110010* (already counted), *101010* (already counted) and **100110**. * The balanced binary strings matching *102120* are **101100** and *100110* (already counted). So the output should be ``` 6 ``` --- Input ``` 10 22222222222222222222 ``` Reasoning * There are *20 choose 10* balanced binary strings of length 20. Output ``` 184756 ``` ## Winner The winner will be the one that computes the competition input the fastest, of course treating it the same way as it would any other input. (I use a determined code in order to have a clear winner and avoid cases where different inputs would give different winners. If you think of a better way to find the fastest code, tell me so). ### Competition input <http://pastebin.com/2Dg7gbfV> [Answer] # ruby, pretty fast, but it depends upon the input *Now speed-up by a factor of 2~2.5 by switching from strings to integers.* Usage: ``` cat <input> | ruby this.script.rb ``` Eg. ``` mad_gaksha@madlab ~/tmp $ ruby c50138.rb < c50138.inp2 number of matches: 298208861472 took 0.05726237 s ``` The number of matches for a single mask a readily calculated by the binomial coefficient. So for example `122020` needs 3 `2`s filled, 1 `0` and 2 `1`. Thus there are `nCr(3,2)=nCr(3,1)=3!/(2!*1!)=3` different binary strings matching this mask. An intersection between n masks m\_1, m\_2, ... m\_n is a mask q, such that a binary string s matches q only iff it matches all masks m\_i. If we take two masks m\_1 and m\_2, its intersection is easily computed. Just set m\_1[i]=m\_2[i] if m\_1[i]==2. The intersection between `122020` and `111222` is `111020`: ``` 122020 (matched by 3 strings, 111000 110010 101010) 111222 (matched by 1 string, 111000) 111020 (matched by 1 string, 111000) ``` The two individual masks are matched by 3+1=4 strings, the interesection mask is matched by one string, thus there are 3+1-1=3 unique strings matching one or both masks. I'll call N(m\_1,m\_2,...) the number of strings matched all m\_i. Applying the same logic as above, we can compute the number of unique strings matched by at least one mask, given by the [inclusion exclusion principle](http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle) and see below as well, like this: ``` N(m_1) + N(m_2) + ... + N(m_n) - N(m_1,m_2) - ... - N(m_n-1,m_n) + N(m_1,m_2,m_3) + N(m_1,m_2,m_4) + ... N(m_n-2,m_n-1,m_n) - N(m_1,m_2,m_3,m_4) -+ ... ``` There are many, many, many combinations of taking, say 30 masks out of 200. **So this solution makes the assumption that not many high-order intersections of the input masks exist, ie. most n-tuples of n>2 masks will not have any common matches.** Use the code here, the code at ideone may be out-dated. * [Test case 1](http://ideone.com/LQ0OHu): number of matches: 6 * [Test case 2](http://ideone.com/NzGJX1): number of matches: 184756 * [Test case 3](http://ideone.com/8h9nRb): number of matches: 298208861472 * [Test case 4](http://ideone.com/gxUORt): number of matches: 5 I added a function `remove_duplicates` that can be used to pre-process the input and delete masks `m_i` such that all strings that match it also match another mask `m_j`.,For the current input, this actually takes longer as there are no such masks (or not many), so the function isn't applied to the data yet in the code below. Code: ``` # factorial table FAC = [1] def gen_fac(n) n.times do |i| FAC << FAC[i]*(i+1) end end # generates a mask such that it is matched by each string that matches m and n def diff_mask(m,n) (0..m.size-1).map do |i| c1 = m[i] c2 = n[i] c1^c2==1 ? break : c1&c2 end end # counts the number of possible balanced strings matching the mask def count_mask(m) n = m.size/2 c0 = n-m.count(0) c1 = n-m.count(1) if c0<0 || c1<0 0 else FAC[c0+c1]/(FAC[c0]*FAC[c1]) end end # removes masks contained in another def remove_duplicates(m) m.each do |x| s = x.join m.delete_if do |y| r = /\A#{s.gsub(?3,?.)}\Z/ (!x.equal?(y) && y =~ r) ? true : false end end end #intersection masks of cn masks from m.size masks def mask_diff_combinations(m,n=1,s=m.size,diff1=[3]*m[0].size,j=-1,&b) (j+1..s-1).each do |i| diff2 = diff_mask(diff1,m[i]) if diff2 mask_diff_combinations(m,n+1,s,diff2,i,&b) if n<s yield diff2,n end end end # counts the number of balanced strings matched by at least one mask def count_n_masks(m) sum = 0 mask_diff_combinations(m) do |mask,i| sum += i%2==1 ? count_mask(mask) : -count_mask(mask) end sum end time = Time.now # parse input d = STDIN.each_line.map do |line| line.chomp.strip.gsub('2','3') end d.delete_if(&:empty?) d.shift d.map!{|x|x.chars.map(&:to_i)} # generate factorial table gen_fac([d.size,d[0].size].max+1) # count masks puts "number of matches: #{count_n_masks(d)}" puts "took #{Time.now-time} s" ``` --- This is called the inclusion exclusion principle, but before somebody had pointed me to it I had my own proof, so here it goes. Doing something yourself feels great though. Let us consider the case of 2 masks, call then `0` and `1`, first. We take every balanced binary string and classify it according to which mask(s) it matches. `c0` is the number of those that match only mask `0`, `c1` the nunber of those that match only `1`, `c01` those that match mask `0` and `1`. Let `s0` be the number sum of the number of matches for each mask (they may overlap). Let `s1` be the sum of the number of matches for each pair (2-combination) of masks. Let `s_i` be the sum of the number of matches for each (i+1) combination of masks. The number of matches of n-masks is the number of binary strings matching all masks. If there are n masks, the desired output is the sum of all `c`'s, ie. `c = c0+...+cn+c01+c02+...+c(n-2)(n-1)+c012+...+c(n-3)(n-2)(n-1)+...+c0123...(n-2)(n-1)`. What the program computes is the alternating sum of all `s`'s, ie. `s = s_0-s_1+s_2-+...+-s_(n-1)`. We wish to proof that `s==c`. n=1 is obvious. Consider n=2. Counting all matches of mask `0` gives `c0+c01` (the number of strings matching only 0 + those matching both `0` and `1`), counting all matches of `1` gives `c1+c02`. We can illustrate this as follows: ``` 0: c0 c01 1: c1 c10 ``` By definition, `s0 = c0 + c1 + c12`. `s1` is the sum number of matches of each 2-combination of `[0,1]`, ie. all uniqye `c_ij`s. Keep in mind that `c01=c10`. ``` s0 = c0 + c1 + 2 c01 s1 = c01 s = s0 - s1 = c0 + c1 + c01 = c ``` Thus `s=c` for n=2. Now consider n=3. ``` 0 : c0 + c01 + c02 + c012 1 : c1 + c01 + c12 + c012 2 : c2 + c12 + c02 + c012 01 : c01 + c012 02 : c02 + c012 12 : c12 + c012 012: c012 s0 = c0 + c1 + c2 + 2 (c01+c02+c03) + 3 c012 s1 = c01 + c02 + c12 + 3 c012 s2 = c012 s0 = c__0 + 2 c__1 + 3 c__2 s1 = c__1 + 3 c__2 s2 = c__2 s = s0 - s1 + s2 = ... = c0 + c1 + c2 + c01 + c02 + c03 + c012 = c__0 + c__1 + c__2 = c ``` Thus `s=c` for n=3. `c__i` represents the of all `c`s with (i+1) indices, eg `c__1 = c01` for n=2 and `c__1 = c01 + c02 + c12` for n==3. For n=4, a pattern starts to emerge: ``` 0: c0 + c01 + c02 + c03 + c012 + c013 + c023 + c0123 1: c1 + c01 + c12 + c13 + c102 + c103 + c123 + c0123 2: c2 + c02 + c12 + c23 + c201 + c203 + c213 + c0123 3: c3 + c03 + c13 + c23 + c301 + c302 + c312 + c0123 01: c01 + c012 + c013 + c0123 02: c02 + c012 + c023 + c0123 03: c03 + c013 + c023 + c0123 12: c11 + c012 + c123 + c0123 13: c13 + c013 + c123 + c0123 23: c23 + c023 + c123 + c0123 012: c012 + c0123 013: c013 + c0123 023: c023 + c0123 123: c123 + c0123 0123: c0123 s0 = c__0 + 2 c__1 + 3 c__2 + 4 c__3 s1 = c__1 + 3 c__2 + 6 c__3 s2 = c__2 + 4 c__3 s3 = c__3 s = s0 - s1 + s2 - s3 = c__0 + c__1 + c__2 + c__3 = c ``` Thus `s==c` for n=4. In general, we get binomial coefficients like this (↓ is i, → is j): ``` 0 1 2 3 4 5 6 . . . 0 1 2 3 4 5 6 7 . . . 1 1 3 6 10 15 21 . . . 2 1 4 10 20 35 . . . 3 1 5 15 35 . . . 4 1 6 21 . . . 5 1 7 . . . 6 1 . . . . . . . . . ``` To see this, consider that for some `i` and `j`, there are: * x = ncr(n,i+1): combinations C for the intersection of (i+1) mask out of n * y = ncr(n-i-1,j-i): for each combination C above, there are y different combinations for the intersection of (j+2) masks out of those containing C * z = ncr(n,j+1): different combinations for the intersection of (j+1) masks out of n As that may sound confusing, here's the defintion applied to an example. For i=1, j=2, n=4, it looks like this (cf. above): ``` 01: c01 + c012 + c013 + c0123 02: c02 + c012 + c023 + c0123 03: c03 + c013 + c023 + c0123 12: c11 + c012 + c123 + c0123 13: c13 + c013 + c123 + c0123 23: c23 + c023 + c123 + c0123 ``` So here x=6 (01, 02, 03, 12, 13, 23), y=2 (two c's with three indices for each combination), z=4 (c012, c013, c023, c123). In total, there are `x*y` coefficients `c` with (j+1) indices, and there are `z` different ones, so each occurs `x*y/z` times, which we call the coefficient `k_ij`. By simple algebra, we get `k_ij = ncr(n,i+1) ncr(n-i-1,j-i) / ncr(n,j+1) = ncr(j+1,i+1)`. So the index is given by `k_ij = nCr(j+1,i+1)` If you recall all the defintions, all we need to show is that the alternating sum of each column gives 1. The alternating sum `s0 - s1 + s2 - s3 +- ... +- s(n-1)` can thus be expressed as: ``` s_j = c__j * ∑[(-1)^(i+j) k_ij] for i=0..n-1 = c__j * ∑[(-1)^(i+j) nCr(j+1,i+1)] for i=0..n-1 = c__j * ∑[(-1)^(i+j) nCr(j+1,i)]{i=0..n} - (-1)^0 nCr(j+1,0) = (-1)^j c__j s = ∑[(-1)^j s_j] for j = 0..n-1 = ∑[(-1)^j (-1)^j c__j)] for j=0..n-1 = ∑[c__j] for j=0..n-1 = c ``` Thus `s=c` for all n=1,2,3,... [Answer] # C If you're not on Linux, or otherwise having trouble compiling, you should probably remove the timing code (`clock_gettime`). ``` #include <stdio.h> #include <stdlib.h> #include <time.h> long int binomial(int n, int m) { if(m > n/2) { m = n - m; } int i; long int result = 1; for(i = 0; i < m; i++) { result *= n - i; result /= i + 1; } return result; } typedef struct isct { char *mask; int p_len; int *p; } isct; long int mask_intersect(char *mask1, char *mask2, char *mask_dest, int n) { int zero_count = 0; int any_count = 0; int i; for(i = 0; i < n; i++) { if(mask1[i] == '2') { mask_dest[i] = mask2[i]; } else if (mask2[i] == '2') { mask_dest[i] = mask1[i]; } else if (mask1[i] == mask2[i]) { mask_dest[i] = mask1[i]; } else { return 0; } if(mask_dest[i] == '2') { any_count++; } else if (mask_dest[i] == '0') { zero_count++; } } if(zero_count > n/2 || any_count + zero_count < n/2) { return 0; } return binomial(any_count, n/2 - zero_count); } int main() { struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); int n; scanf("%d", &n); int nn = 2 * n; int m = 0; int m_max = 1024; char **masks = malloc(m_max * sizeof(char *)); while(1) { masks[m] = malloc(nn + 1); if (scanf("%s", masks[m]) == EOF) { break; } m++; if (m == m_max) { m_max *= 2; masks = realloc(masks, m_max * sizeof(char *)); } } int i = 1; int i_max = 1024 * 128; isct *iscts = malloc(i_max * sizeof(isct)); iscts[0].mask = malloc(nn); iscts[0].p = malloc(m * sizeof(int)); int j; for(j = 0; j < nn; j++) { iscts[0].mask[j] = '2'; } for(j = 0; j < m; j++) { iscts[0].p[j] = j; } iscts[0].p_len = m; int i_start = 0; int i_end = 1; int sign = 1; long int total = 0; int mask_bin_len = 1024 * 1024; char* mask_bin = malloc(mask_bin_len); int mask_bin_count = 0; int p_bin_len = 1024 * 128; int* p_bin = malloc(p_bin_len * sizeof(int)); int p_bin_count = 0; while (i_end > i_start) { for (j = i_start; j < i_end; j++) { if (i + iscts[j].p_len > i_max) { i_max *= 2; iscts = realloc(iscts, i_max * sizeof(isct)); } isct *isct_orig = iscts + j; int x; int x_len = 0; int i0 = i; for (x = 0; x < isct_orig->p_len; x++) { if(mask_bin_count + nn > mask_bin_len) { mask_bin_len *= 2; mask_bin = malloc(mask_bin_len); mask_bin_count = 0; } iscts[i].mask = mask_bin + mask_bin_count; mask_bin_count += nn; long int count = mask_intersect(isct_orig->mask, masks[isct_orig->p[x]], iscts[i].mask, nn); if (count > 0) { isct_orig->p[x_len] = isct_orig->p[x]; i++; x_len++; total += sign * count; } } for (x = 0; x < x_len; x++) { int p_len = x_len - x - 1; iscts[i0 + x].p_len = p_len; if(p_bin_count + p_len > p_bin_len) { p_bin_len *= 2; p_bin = malloc(p_bin_len * sizeof(int)); p_bin_count = 0; } iscts[i0 + x].p = p_bin + p_bin_count; p_bin_count += p_len; int y; for (y = 0; y < p_len; y++) { iscts[i0 + x].p[y] = isct_orig->p[x + y + 1]; } } } sign *= -1; i_start = i_end; i_end = i; } printf("%lld\n", total); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); int seconds = end.tv_sec - start.tv_sec; long nanoseconds = end.tv_nsec - start.tv_nsec; if(nanoseconds < 0) { nanoseconds += 1000000000; seconds--; } printf("%d.%09lds\n", seconds, nanoseconds); return 0; } ``` Example cases: ``` robert@unity:~/c/se-mask$ gcc -O3 se-mask.c -lrt -o se-mask robert@unity:~/c/se-mask$ head testcase-long 30 210211202222222211222112102111220022202222210122222212220210 010222222120210221012002220212102220002222221122222220022212 111022212212022222222220111120022120122121022212211202022010 022121221020201212200211120100202222212222122222102220020212 112200102110212002122122011102201021222222120200211222002220 121102222220221210220212202012110201021201200010222200221002 022220200201222002020110122212211202112011102220212120221111 012220222200211200020022121202212222022012201201210222200212 210211221022122020011220202222010222011101220121102101200122 robert@unity:~/c/se-mask$ ./se-mask < testcase-long 298208861472 0.001615834s robert@unity:~/c/se-mask$ head testcase-hard 8 0222222222222222 1222222222222222 2022222222222222 2122222222222222 2202222222222222 2212222222222222 2220222222222222 2221222222222222 2222022222222222 robert@unity:~/c/se-mask$ ./se-mask < testcase-hard 12870 3.041261458s robert@unity:~/c/se-mask$ ``` (Times are for an i7-4770K CPU at 4.1 GHz.) Be careful, `testcase-hard` uses around 3-4 GB of memory. This is pretty much an implementation of inclusion-exclusion method blutorange came up with, but done so that it will handle intersections of any depth. ~~The code as written is spending a lot of time on memory allocation, and will get even faster once I optimize the memory management.~~ I shaved off around 25% on `testcase-hard`, but the performance on the original (`testcase-long`) is pretty much unchanged, since not much memory allocation is going on there. I'm going to tune a bit more before I call it: I think I might be able to get a 25%-50% improvement on `testcase-long` too. # Mathematica Once I noticed this was a #SAT problem, I realized I could use Mathematica's built-in `SatisfiabilityCount`: ``` AbsoluteTiming[ (* download test case *) input = Map[FromDigits, Characters[ Rest[StringSplit[ Import["http://pastebin.com/raw.php?i=2Dg7gbfV", "Text"]]]], {2}]; n = Length[First[input]]; (* create boolean function *) bool = BooleanCountingFunction[{n/2}, n] @@ Array[x, n] && Or @@ Table[ And @@ MapIndexed[# == 2 || Xor[# == 1, x[First[#2]]] &, i], {i, input}]; (* count instances *) SatisfiabilityCount[bool, Array[x, n]] ] ``` Output: ``` {1.296944, 298208861472} ``` That's 298,208,861,472 masks in 1.3 seconds (i7-3517U @ 1.9 GHz), including the time spent downloading the test case from pastebin. [Answer] # C ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_combination.h> int main (int argc, char *argv[]) { printf ("reading\n"); char buffer[100]; gets(buffer); char n = atoi(buffer); char *masks[1000]; masks[0] = malloc(2 * n * sizeof(char)); char c,nrows,j,biggestzerorun,biggestonerun,currentzerorun,currentonerun = 0; while ((c = getchar()) && c != EOF) { if (c == '\n') { nrows++; if (currentonerun > biggestonerun) { biggestonerun = currentonerun; } if (currentzerorun > biggestzerorun) { biggestzerorun = currentzerorun; } j=currentonerun=currentzerorun=0; masks[nrows] = malloc(2 * n * sizeof(char)); } else if (c == '0') { masks[nrows][j++] = 1; currentzerorun++; if (currentonerun > biggestonerun) { biggestonerun = currentonerun; } currentonerun=0; } else if (c == '1') { masks[nrows][j++] = 2; currentonerun++; if (currentzerorun > biggestzerorun) { biggestzerorun = currentzerorun; } currentonerun=0; } else if (c == '2') { masks[nrows][j++] = 3; currentonerun++; currentzerorun++; } } if (currentonerun > biggestonerun) { biggestonerun = currentonerun; } if (currentzerorun > biggestzerorun) { biggestzerorun = currentzerorun; } printf("preparing combinations\n"); int nmatches=0; gsl_combination *combination = gsl_combination_calloc(2*n, n); printf("entering loop:\n"); do { char vector[2*n]; char currentindex, previousindex; currentonerun = 0; memset(vector, 1, 2*n); // gsl_combination_fprintf (stdout, combination, "%u "); // printf(": "); for (char k=0; k<n; k++) { previousindex = currentindex; currentindex = gsl_combination_get(combination, k); if (k>0) { if (currentindex - previousindex == 1) { currentonerun++; if (currentonerun > biggestonerun) { goto NEXT; } } else { currentonerun=0; if (currentindex - previousindex > biggestzerorun) { goto NEXT; } } } vector[currentindex] = 2; } for (char k=0; k<=nrows; k++) { char ismatch = 1; for (char l=0; l<2*n; l++) { if (!(vector[l] & masks[k][l])) { ismatch = 0; break; } } if (ismatch) { nmatches++; break; } } NEXT: 1; } while ( gsl_combination_next(combination) == GSL_SUCCESS ); printf ("RESULT: %i\n", nmatches); gsl_combination_free(combination); for (; nrows>=0; nrows--) { free(masks[nrows]); } } ``` Good luck getting the big input to run on this - it'll probably take all night to get through approx. 60^30 permutations! Maybe an intermediate sized dataset might be a good idea? ]
[Question] [ > > **Edit:** I will award a **100-reputation bounty** for the first solver of the **bonus puzzle** at the end of the question! > > > I will add the bounty to the question only when the answer appears as this bounty has no deadline. > > > Given a non-decreasing list of one-digit positive integers, you should determine how deep dungeon the digits will dig. ``` ███ ███ A dungeon with 5 blocks removed and a depth of 3. ███ ███ ███ ████ ████████ ``` Before the start of the digging the ground is level. Every digit can remove exactly one block of soil from below itself but it has to reach that position from outside the dungeon and after it removed the block has to leave the dungeon. While doing so a digit **can't descend or ascend more than its numerical value** at any horizontal step. The digits use the following strategy for digging: * The digit with the smallest value digs firsts and after that the next digger is always the next smallest value from the rest of the digits. * The first digit can dig at any position. (All ground is the same.) * The following digits always dig at the leftmost already started column where they can go and come out. If no such column exists they start to dig a new column on the right side of the rightmost one. For example the digits `1 1 1 2 3 3` would dig the following dungeon (step-by-step visualization with numbers marking which kind of digit dig out that position): ``` ███1████ ███11███ ███11███ ███11███ ███11███ ███11███ ████████ ████████ ███1████ ███1████ ███1████ ███13███ ████████ ████████ ████████ ███2████ ███2████ ███2████ ████████ ████████ ████████ ████████ ███3████ ███3████ ████████ ████████ ████████ ████████ ████████ ████████ ``` Explanation for the example: * The second `1` couldn't climb out of the only available column if it would deepen it to `2`-deep so it digs right to it. * The third `1` can dig in the leftmost column creating a `2`-deep column as it can move out into the `1`-deep column and then to the ground level. * The next `2` and `3` both can dig in the leftmost column. * The last `3` can't dig in the leftmost column but can in the next one. ## Input * A non-decreasing list of positive one-digit integers with at least one element. ## Output * A single positive integer, the depth of the constructed dungeon. ## Examples Input => Output (with the depths of the columns of the dungeon from left to right as explanation which is not part of the output) ``` [3] => 1 (column depths are [1]) [1, 1, 1, 2, 3, 3] => 4 (column depths are [4, 2]) [1, 1, 1, 1, 1, 1, 1, 1] => 3 (column depths are [3, 2, 2, 1]) [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5] => 11 (column depths are [11, 6, 2]) [1, 1, 1, 1, 1, 2, 2, 9, 9, 9] => 7 (column depths are [7, 2, 1]) [2, 2, 2, 2, 2, 5, 5, 5, 7, 7, 9] => 9 (column depths are [9, 2]) [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] => 10 (column depths are [10, 5]) [1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 7, 7, 9] => 13 (column depths are [13, 5]) [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] => 13 (column depths are [13, 5]) [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9] => 21 (column depths are [21, 12, 3]) ``` This is code-golf so the shortest entry wins. ## Bonus puzzle Can you prove (or disprove) that the strategy described in the *"The digits use the following strategy for digging"* section always gives the deepest possible dungeon for the given digits? [Answer] # Pyth, 21 bytes ``` huXf>+H@GhT@GT0G1Qm0Q ``` Try it online: [Single Demonstration](https://pyth.herokuapp.com/?code=huXf%3E%2BH%40GhT%40GT0G1Qm0Q&input=%5B1%2C+1%2C+1%2C+1%2C+2%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4%2C+5%2C+5%2C+5%2C+5%2C+6%2C+6%2C+6%2C+6%2C+7%2C+7%2C+7%2C+7%2C+8%2C+8%2C+8%2C+8%2C+9%2C+9%2C+9%2C+9%5D&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=FQ.Qjd%5BQ%22%3D%3E%22huXf%3E%2BH%40GhT%40GT0G1Qm0Q&input=%22Test+Cases%22%0A%5B3%5D%0A%5B1%2C+1%2C+1%2C+2%2C+3%2C+3%5D%0A%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%0A%5B1%2C+1%2C+1%2C+1%2C+1%2C+3%2C+3%2C+3%2C+3%2C+3%2C+3%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B1%2C+1%2C+1%2C+1%2C+1%2C+2%2C+2%2C+9%2C+9%2C+9%5D%0A%5B2%2C+2%2C+2%2C+2%2C+2%2C+5%2C+5%2C+5%2C+7%2C+7%2C+9%5D%0A%5B1%2C+2%2C+2%2C+3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B1%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+3%2C+3%2C+4%2C+4%2C+5%2C+5%2C+5%2C+5%2C+7%2C+7%2C+9%5D%0A%5B1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+4%2C+4%2C+5%2C+5%2C+6%2C+6%2C+7%2C+7%2C+8%2C+8%2C+9%2C+9%5D%0A%5B1%2C+1%2C+1%2C+1%2C+2%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4%2C+5%2C+5%2C+5%2C+5%2C+6%2C+6%2C+6%2C+6%2C+7%2C+7%2C+7%2C+7%2C+8%2C+8%2C+8%2C+8%2C+9%2C+9%2C+9%2C+9%5D&debug=0) ### Explanation: ``` m0Q generate a list of zeros of length len(input) This will simulate the current depths u Qm0Q reduce G, starting with G=[0,...,0], for H in input(): f 0 find the first number T >= 0, which satisfies: >+H@GhT@GT H + G[T+1] > G[T] X G1 increase the depth at this position by one update G with this result h print the first element in this list ``` [Answer] # Java, 199 ``` import java.util.*;a->{List<Integer>l=new ArrayList();l.add(0);int x,y,z=0;s:for(int i:a){for(x=0;x<z;x++)if((y=l.get(x))-l.get(x+1)<i){l.set(x,l.get(x)+1);continue s;}l.add(z++,1);}return l.get(0);} ``` ## Expanded, runnable version ``` import java.util.*; class DIGits { public static void main(String[] args) { java.util.function.Function<int[], Integer> f = a->{ List<Integer> l = new ArrayList(); l.add(0); int x, y, z = 0; s: for (int i : a) { for (x = 0; x < z; x++) { if ((y = l.get(x)) - l.get(x + 1) < i) { l.set(x, l.get(x) + 1); continue s; } } l.add(z++, 1); } return l.get(0); }; System.out.println(f.apply(new int[]{1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 7, 7, 9})); } } ``` ]
[Question] [ Take an array of integers containing negative numbers, positive numbers and zeros. Group it **with one iteration and in place** such that all of the negative numbers come first, followed by all of the zeros, followed by all of the positive numbers. Example: ``` Input: 5, 3, 0, -6, 2, 0, 5 Output: -6, 0, 0, 3, 2, 5, 5 ``` Note that the numbers do not need to be fully sorted: just sorted by sign. So, the final array will look like this: `-, -, ..., -, -, 0, 0, ..., 0, 0, +, +, ..., +, +` ### Rules * You may only use the input array and a constant amount of additional memory (i.e. you may not create any more arrays) * You may only use one loop, which may execute only as many times as the length of the array. You may not use built-in functions which conceal any kind of loop. This includes built-in sort functions. * The result should be in the format I described The winner will be the person who will submit the shortest code (counted in bytes) that changes the initial array into a correct format (like described above). [Answer] # C, 92 This could probably be reduced by at least 10 bytes; there are many expressions going to waste. The first argument should point to the beginning of the array; the second should point after the end of the array. ``` *x;f(b,e)int*b,*e;{for(x=b;x<e;x++)*x>0&&--e-x?*x--^=*e^=*x^=*e:*x<0?b-x?*x^=*b=*x:0,b++:0;} ``` Ungolfed with random test generator: ``` *x; f(b,e)int*b,*e;{ for(x=b;x<e;x++) { if(*x<0) { if(b == x) b++; else *b++ = *x, *x=0; } else if(*x>0 && x != --e) { *x^=*e^=*x^=*e; x--; } } } int main() { int a[999]; srand(time(0)); int n = rand() % 50; int i; for(i = 0; i < n; i++) printf("%d ", a[i] = rand() % 9 - 4); f(a, a+n); puts(""); for(i = 0; i < n; i++) printf("%d ", a[i]); return 0; } ``` [Answer] ## STATA 242 Follows the wikipedia page exactly. Thanks @PeterTaylor Takes input as a space separated set of numbers from std in and outputs as such as well to std out. ``` di _r(a) token $a//converts to array (kind of) loc i=0 loc j=0 loc q=wordcount($a) loc n=`q'-1 while `j'<=`n' { loc t=``j'' if `t'<0{ loc `j'=``i'' loc `i'=`t' loc ++i loc ++j } else if `t'>0{ loc `j'=``n'' loc `n'=`t' loc --n } else loc ++j } //used only to output forv x=1/`q'{ di ``x'' _c } ``` [Answer] # Python 2: 116 bytes ``` a=input();i=j=0;n=len(a) while j<n:b=a[j];r,s=b<0,b>0;c=i*r+n*s-s+j*(b==0);a[c],a[j]=b,a[c];i+=r;n-=s;j+=b<1 print a ``` This is a golfed Python translation of the Dutch national flag pseudo-code. # Possible 112 bytes Not sure, if this is allowed. It creates a second array of size 3 (constant amount of additional memory!). ``` a=input();i=j=0;n=len(a)-1 while j<=n:b=a[j];k=(i,j,n)[cmp(b,0)+1];a[k],a[j]=b,a[k];i+=b<0;n-=b>0;j+=b<1 print a ``` [Answer] # C,90 Straightforward implementation of the algorithm in the wikipedia article per Peter Taylor's comment on the question. Expects to find the data in an array called `a` like the other C answer. `n`,`p` and `z` are pointers for the insertion of negative and positive numbers and zeroes. `n` and `p` are taken as arguments pointing to the first and last elements of the data. ``` f(n,p){int t,z;for(z=n;p-z;z++)(t=a[z])?a[z]>0?a[z]=a[p],a[p--]=t:(a[z]=a[n],a[n++]=t):0;} ``` [Answer] # ECMAScript 157 Bytes Takes the numbers as space separated or comma separated set from a prompt dialog and returns the result with a alert dialog. ``` for(v=prompt().split(/,?\s+/),s=function(j,n){t=v[j],v[j]=v[n],v[n]=t},i=j=0,n=v.length-1;j<=n;) !(~~v[j]<0&&!s(i++,j++)||~~v[j]>0&&!s(j,n--))&&j++;alert(v); ``` [Answer] # PHP (146) ``` function f($s){for($i=0,$n=count($s)-1;$j++<=$n;)if($k=$s[$j]){$l=$k>0?n:i;$x=$s[$$l];$s[$$l]=$k;$s[$j]=$x;$k>0?$n--|$j--:$i++;}echo print_r($s);} ``` <http://3v4l.org/ivRX5> PHP's relatively verbose variable syntax is a bit painful here... [Answer] # Rebol - ~~149~~ ~~142~~ 140 ``` a: to-block input i: j: 1 n: length? a while[j <= n][case[a/:j < 0[swap at a ++ i at a ++ j]a/:j > 0[swap at a j at a -- n]on[++ j]]]print a ``` This is a direct port of the Dutch national flag wikipedia pseudocode. Below is how it looks ungolfed: ``` a: to-block input i: j: 1 n: length? a while [j <= n] [ case [ a/:j < 0 [swap at a ++ i at a ++ j] a/:j > 0 [swap at a j at a -- n] on [++ j] ] ] print a ``` Usage example: ``` rebol dutch-flag.reb <<< "5 3 0 -6 2 0 5" -6 0 0 2 3 5 5 ``` NB. Rebol arrays (blocks) don't use commas - `[5 3 0 -6 2 0 5]` And if its OK wrap this up into a function which takes an array and modifies it in place then we can get it down to 128 chars: ``` >> f: func[a][i: j: 1 n: length? a while[j <= n][case[a/:j < 0[swap at a ++ i at a ++ j]a/:j > 0[swap at a j at a -- n]on[++ j]]]n] >> array: [5 3 0 -6 2 0 5] == [5 3 0 -6 2 0 5] >> print f array -6 0 0 2 3 5 5 >> ;; and just to show that it as modified array >> array == [-6 0 0 2 3 5 5] ``` In fact if didn't need to return array (ie. just modify) then you could shave off 1 more char. [Answer] ## C++ Un-golfed solution: n counts the negatives added to front of array. For each element if negative swap with element at n, if zero swap with element at n+1 else swap with last element. ``` void p(int* k,int n) { for(int i=0;i<n;i++) { cout<<*(k+i)<<' '; } cout<<endl; } void s(int *x,int i,int j) { int t=*(x+j); *(x+j)=*(x+i); *(x+i)=t; } void f(int *x,int L) { int n=0; int k; for(int i=1;i<L;i++) { k=*(x+i); if(k<0) { s(x,i,n); n++; } else if(k==0) { s(x,i,n+1); } else if(k>0) { s(x,i,L-1); } } } int main() { int x[]={5,2,-1,0,-2,4,0,3}; f(x,8); p(x,8); return 0; } ``` [Answer] # CJam - ~~72~~ 67 ``` q~_,(:N;{_U=:B0>{U1$N=tNBtN(:N;}{B{U1$T=tTBtT):T;}{}?U):U;}?UN>!}gp ``` Input: `[5 3 4 0 -6 2 0 5]` Output: `[-6 0 0 4 2 3 5 5]` Try it at <http://cjam.aditsu.net/> **Explanation:** This is another implementation of the algorithm from wikipedia, using `T` for `i` and `U` for `j` (both automatically initialized to 0). ``` q~ read and evaluate the array (let's call it "A") _,(:N; keep A on the stack and set N ← size of A - 1 { do... _U=:B keep A on the stack and set B ← A[U] (also leaving B on the stack) 0>{ if B > 0 U1$N=t A[U] ← A[N] NBt A[N] ← B N(:N; N ← N - 1 }{ else B{ if B ≠ 0 U1$T=t A[U] ← A[T] TBt A[T] ← B T):T; T ← T + 1 }{ else (do nothing) }? end if U):U; U ← U + 1 }? end if UN>!}g ...while not (U > N) p print representation of A ``` ]
[Question] [ A well-known puzzle involves counting how many squares can be made using the points on a 3x3 grid: ``` . . . . . . . . . ``` The answer is 6 — four small squares, one large square, and one square formed from the top, left, bottom, and right pegs, with edges along the *diagonals* of the squares. Your task is to build a program that counts the total number of squares that can be formed from a set of points. Your program will take input in one of two formats (of your choosing): * An `M` by `N` grid consisting of either `.` or . `.` represents a point on the grid that a square can be a corner of, and all spaces on the grid are exactly one unit apart horizontally or vertically. * A list of coordinate pairs representing points that a square can be on. and return the *number* of distinct squares that can be formed using the points provided. Your program must return a correct solution for every possible input. --- For example, take the input above but where the center square is missing: ``` ... . . ... ``` There are only two possible squares here (the big one and the diagonal one), so the program should return `2`. --- The shortest code to do this in any language wins. [Answer] # Python, 95 Takes a list of coordinates from stdin. ``` l=input();print(sum((c-d+b,d+c-a)in l and(a-d+b,b+c-a)in l for a,b in l for c,d in l)-len(l))/4 ``` Explanation: > > For each pair of points `(a,b)` and `(c,d)`, check if the square with additional points `(c-d+b,d+c-a)` and `(a-d+b,b+c-a)` is in the list. This counts each square 4 times, and each point once (when `(a,b) = (c,d)`), so subtracting the number of points and dividing by 4 gives the number of squares. > > > ]
[Question] [ I seem to have gotten myself into a bit of a pickle. Literally. I dropped a bunch of pickles on the floor and now they're all scattered about! I need you to help me collect them all. Oh, did I mention I have a bunch of robots at my command? (They're also all scattered all over the place; I'm really bad at organizing things.) You must take input in the form of: ``` P....... ..1..2.. .......P ........ P3PP...4 .......P ``` i.e., multiple lines of either `.`, `P` (pickle), or a digit (robot's ID). (You may assume that each line is of equal length, padded with `.`.) You can input these lines as an array, or slurp from STDIN, or read in a comma-separated single line, or read a file, or do whatever you would like to take the input. Your output must be in the form of `n` lines, where `n` is the highest robot ID. (Robot IDs will always be sequantial starting at 1.) Each line will contain the robot's path, formed from the letters `L` (left), `R` (right), `U` (up), and `D` (down). For example, here's an example output for that puzzle: ``` LLU RDR LRRR D ``` It can also be ``` LLU RDR LRRR D ``` Or ``` ["LLU","RDR","LRRR","D"] ``` Or any format you would like, as long as you can tell what the solution is supposed to be. Your goal is to find the optimal output, which is the one that has the least steps. The amount of steps is counted as the greatest amount of steps from all of the robots. For example, the above example had 4 steps. Note that there may be multiple solutions, but you only need to output one. Scoring: * Your program will be run with each of the 5 (randomly generated) test cases. * You must add the steps from each run, and that will be your score. * The lowest total, cumulative score will win. * You may not hard-code for these specific inputs. Your code should also work for any other input. * Robots *can* pass through each other. * Your program must be deterministic, i.e. same output for every run. You can use a random number generator, as long as it's seeded and consistently produces the same numbers cross-platform. * Your code must run within 3 minutes for each of the inputs. (Preferrably much less.) * In case of a tie, most upvotes will win. Here are the test cases. They were randomly generated with a small Ruby script I wrote up. ``` P.......1. .......... P.....P... ..P....... ....P2.... ...P.P.... .PP..P.... ....P....P PPPP....3. .P..P.P..P ....P..... P....1.... .P.....PP. .PP....PP. .2.P.P.... ..P....P.. .P........ .....P.P.. P.....P... .3.P.P.... ..P..P..P. ..1....P.P .......... .......2P. ...P....P3 .P...PP..P .......P.P ..P..P..PP ..P.4P..P. .......P.. ..P...P... .....P.... PPPP...P.. ..P....... ...P...... .......P.1 .P..P....P P2PP...... .P..P..... .......... ......PP.P .P1..P.P.. ......PP.. P..P....2. .P.P3..... ....4..P.. .......PP. ..P5...... P.....P... ....PPP..P ``` Good luck, and don't let the pickles sit there for too long, or they'll spoil! --- Oh, and why pickles, you ask? Why not? [Answer] ## Ruby, 15+26+17+26+17 = 101 Robot Finds Pickles! Okay, here's a baseline to get people started, using the following super-naive algorithm: * Each tick, each robot will act in numeric order, performing the following steps: + Identify the closest (Manhattan distance) pickle that no other robots are targeting. + Figure out which adjacent squares are available to move to. + Choose one of those squares, preferring directions that move it closer to the selected pickle. Here's what it looks like for Test Case #1: ![Animated Example for TC1](https://i.stack.imgur.com/yAdQ3.gif) Obviously this isn't very good but it's a start! Code: ``` Tile = Struct.new(:world, :tile, :x, :y) do def passable? tile =~ /\.|P/ end def manhattan_to other (self.x - other.x).abs + (self.y - other.y).abs end def directions_to other directions = [] directions << ?U if self.y > other.y directions << ?D if self.y < other.y directions << ?L if self.x > other.x directions << ?R if self.x < other.x directions end def one_step direction nx,ny = case direction when ?U then [self.x, self.y - 1] when ?D then [self.x, self.y + 1] when ?L then [self.x - 1, self.y] when ?R then [self.x + 1, self.y] end self.world[nx,ny] end def move direction destination = one_step(direction) raise "can't move there" unless destination && destination.passable? destination.tile, self.tile = self.tile, ?. end end class World DIRECTIONS = %w(U D L R) def initialize s @board = s.split.map.with_index { |l,y| l.chars.map.with_index { |c,x| Tile.new(self, c, x, y) }} @width = @board[0].length end def [] x,y y >= 0 && x >= 0 && y < @board.size && x < @board[y].size && @board[y][x] end def robots tiles_of_type(/[0-9]/).sort_by { |t| t.tile } end def pickles tiles_of_type ?P end def tiles_of_type type @board.flatten.select { |t| type === t.tile } end def inspect @board.map { |l| l.map { |t| t.tile }*'' }*?\n end end gets(nil).split("\n\n").each do |input| w = World.new(input) steps = Hash[w.robots.map { |r| [r.tile, []] }] while (pickles_remaining = w.pickles).size > 0 current_targets = Hash.new(0) w.robots.each do |r| target_pickle = pickles_remaining.min_by { |p| [current_targets[p], r.manhattan_to(p)] } possible_moves = World::DIRECTIONS.select { |d| t = r.one_step(d); t && t.passable? } raise "can't move anywhere" if possible_moves.empty? direction = (r.directions_to(target_pickle) & possible_moves).first || possible_moves[0] current_targets[target_pickle] += 1 steps[r.tile] << direction r.move(direction) end end puts steps.values.map &:join p steps.values.map { |v| v.size }.max end ``` Takes input on STDIN in exactly the format of the test case code-block in the original question. Here's what it prints for those test cases: ``` DDLLDLLLLULLUUD LDLRRDDLDLLLLDR URDDLLLLLULLUUL 15 ULDLDDLDRRRURRURDDDDDDDLLL UUULDDRDRRRURRURDLDDDDLDLL ULUURURRDDRRRRUUUDDDDLDLLL 26 URRRDRUDDDDLLLDLL RUUUDLRRDDDLLLDLL LDRDDLDDLLLLLLLUU RUUURDRDDLLLLLUUU 17 DULLUUUUULDLDLLLLLDDRUUUUR UDLRRRURDDLLLUUUUURDRUUUUD 26 LDDLDUUDDDUDDDDDR ULUULDDDDDRDRDDDR LULLDUUDDDRDRDDDR UUUURDUURRRRDDDDD LDLLUDDRRRRRRUDRR 17 ``` [Answer] # Python, 16+15+14+20+12 = 77 I don't really have any prior experience to travelling salesman type problems but I had a bit of time on my hands so I thought I would give it a shot. It basically attempts to allot each bot certain pickles by walking it though a preliminary run where they go for the ones closest to them and farthest from the others. It then brute-forces the most efficient way for each bot to collect its allotted pickles. I really have no idea how viable this method is, but I suspect it would not work well for larger boards with fewer bots (the fourth board already sometimes takes over two minutes). Code: ``` def parse_input(string): pickles = [] size = len(string) - string.count('\n') poses = [None] * (size - string.count('.') - string.count('P')) for y,line in enumerate(string.strip().split('\n')): for x,char in enumerate(line): if char == '.': continue elif char == 'P': pickles.append((x,y)) else: poses[int(char)-1] = (x,y) return pickles, poses def move((px,py),(tx,ty)): if (px,py) == (tx,ty): return (px,py) dx = tx-px dy = ty-py if abs(dx) <= abs(dy): if dy < 0: return (px,py-1) else: return (px,py+1) else: if dx < 0: return (px-1,py) else: return (px+1,py) def distance(pos, pickle): return abs(pos[0]-pickle[0]) + abs(pos[1]-pickle[1]) def calc_closest(pickles,poses,index): distances = [[distance(pos,pickle) for pickle in pickles] for pos in poses] dist_diffs = [] for i, pickle_dists in enumerate(distances): dist_diffs.append([]) for j, dist in enumerate(pickle_dists): other = [d[j] for d in distances[:i]+distances[i+1:]] dist_diffs[-1].append(min(other)-dist) sorted = pickles[:] sorted.sort(key = lambda ppos: -dist_diffs[index][pickles.index(ppos)]) return sorted def find_best(items,level): if level == 0: best = (None, None) for rv, rest in find_best(items[1:],level+1): val = distance(items[0],rest[0]) + rv if best[0] == None or val < best[0]: best = (val, [items[0]] + rest) return best if len(items) == 1: return [(0,items[:])] size = len(items) bests = [] for i in range(size): best = (None, None) for rv, rest in find_best(items[:i]+items[i+1:],level+1): val = distance(items[i],rest[0]) + rv if best[0] == None or val < best[0]: best = (val, [items[i]] + rest) if best[0] != None: bests.append(best) return bests def find_best_order(pos,pickles): if pickles == []: return 0,[] best = find_best([pos]+pickles,0) return best def walk_path(pos,path): history = '' while path: npos = move(pos, path[0]) if npos == path[0]: path.remove(path[0]) if npos[0] < pos[0]: history += 'L' elif npos[0] > pos[0]: history += 'R' elif npos[1] < pos[1]: history += 'U' elif npos[1] > pos[1]: history += 'D' pos = npos return history def find_paths(input_str): pickles, poses = parse_input(input_str) ## Parse input string and stuff orig_pickles = pickles[:] orig_poses = poses[:] numbots = len(poses) to_collect = [[] for i in range(numbots)] ## Will make a list of the pickles each bot should go after waiting = [True] * numbots targets = [None] * numbots while pickles: while True in waiting: ## If any bots are waiting for a new target index = waiting.index(True) closest = calc_closest(pickles,poses,index) ## Prioritizes next pickle choice based upon how close they are RELATIVE to other bots tar = closest[0] n = 0 while tar in targets[:index]+targets[index+1:]: ## Don't target the same pickle! other_i = (targets[:index]+targets[index+1:]).index(tar) dist_s = distance(poses[index],tar) dist_o = distance(poses[other_i],tar) if dist_s < dist_o: waiting[other_i] = True break n += 1 if len(closest) <= n: waiting[index] = False break tar = closest[n] targets[index] = tar waiting[index] = False for i in range(numbots): ## Move everything toward targets (this means that later target calculations will not be based on the original position) npos = move(poses[i], targets[i]) if npos != poses[i]: poses[i] = npos if npos in pickles: to_collect[i].append(npos) pickles.remove(npos) for t, target in enumerate(targets): if target == npos: waiting[t] = True paths = [] sizes = [] for i,pickle_group in enumerate(to_collect): ## Lastly brute force the most efficient way for each bot to collect its allotted pickles size,path = find_best_order(orig_poses[i],pickle_group) sizes.append(size) paths.append(path) return max(sizes), [walk_path(orig_poses[i],paths[i]) for i in range(numbots)] def collect_pickles(boards): ## Collect Pickles! total = 0 for i,board in enumerate(boards): result = find_paths(board) total += result[0] print "Board "+str(i)+": ("+ str(result[0]) +")\n" for i,h in enumerate(result[1]): print '\tBot'+str(i+1)+': '+h print print "Total Score: " + str(total) boards = """ P.......1. .......... P.....P... ..P....... ....P2.... ...P.P.... .PP..P.... ....P....P PPPP....3. .P..P.P..P ....P..... P....1.... .P.....PP. .PP....PP. .2.P.P.... ..P....P.. .P........ .....P.P.. P.....P... .3.P.P.... ..P..P..P. ..1....P.P .......... .......2P. ...P....P3 .P...PP..P .......P.P ..P..P..PP ..P.4P..P. .......P.. ..P...P... .....P.... PPPP...P.. ..P....... ...P...... .......P.1 .P..P....P P2PP...... .P..P..... .......... ......PP.P .P1..P.P.. ......PP.. P..P....2. .P.P3..... ....4..P.. .......PP. ..P5...... P.....P... ....PPP..P """.split('\n\n') collect_pickles(boards) ``` Output: ``` Board 0: (16) Bot1: DLDLLLLDLLULUU Bot2: LDLDLLDDLDRURRDR Bot3: URDDLLLULULURU Board 1: (15) Bot1: ULRDRDRRDLDDLUL Bot2: DDURURULLUUL Bot3: ULRRDRRRURULRR Board 2: (14) Bot1: URRRDDDDDRLLUL Bot2: UUURDRDDLD Bot3: DDDLDDLUUU Bot4: RULLLDUUUL Board 3: (20) Bot1: DLULUUUUULDLLLULDDD Bot2: LURDDURRDRUUUULUULLL Board 4: (12) Bot1: LDDLDR Bot2: ULUULRRR Bot3: LUURURDR Bot4: RRRDRDDDR Bot5: LLDLRRRDRRRU Total Score: 77 ``` ]
[Question] [ Most of you probably know the C major scale: ``` C D E F G A B C ``` The major scale is characterised by the [intervals](http://en.wikipedia.org/wiki/Interval_%28music%29) between adjacent notes, which measured in [semitones](http://en.wikipedia.org/wiki/Semitone) are: ``` 2 2 1 2 2 2 1 ``` From these intervales, we can construct any major scale starting in any note (the [key](http://en.wikipedia.org/wiki/Key_%28music%29) of the scale). The 12 notes in our 12-tone equal temperament tuning system are: ``` C C♯ D D♯ E F F♯ G G♯ A A♯ B ``` equivalently (substituting some [enharmonic equivalents](http://en.wikipedia.org/wiki/Enharmonic)): ``` C D♭ D E♭ E F G♭ G Ab A B♭ B ``` with a semitone between each pair of adjacent notes. Each scale has to have the seven notes in order, starting from the key. Otherwise, you could have two notes in the same line of the pentagram, which would be confusing. So, in G# major/ionian, you have F## instead of G; musicians will just look at where in the pentagram is the note, they already have learned the accidentals for each scale. Indeed, in [G# major](https://music.stackexchange.com/questions/5658/is-g-sharp-major-a-real-key), F## is represented in the line of F## without accidentals, the accidentals are in the key signature - but since that key signature would require 2 sharps for F, usually this is notated as Ab major. Shifting the `2 2 1 2 2 2 1` intervals, we arrive at seven different [modes](http://en.wikipedia.org/wiki/Mode_%28music%29) of the diatonic scale: * **Ionian**: `2 2 1 2 2 2 1` - corresponds to the major scale * **Dorian**: `2 1 2 2 2 1 2` * **Phrygian**: `1 2 2 2 1 2 2` * **Lydian**: `2 2 2 1 2 2 1` * **Mixolydian**: `2 2 1 2 2 1 2` * **Aeolian**: `2 1 2 2 1 2 2` - corresponds to the natural minor scale, and to the melodic minor scale when descending (when ascending, the melodic minor scale has raised 6th and 7th degrees. There is also a harmonic minor scale, with a raised 7th degree compared to the natural minor). * **Locrian**: `1 2 2 1 2 2 2` So, the challenge is to write a program that takes as input (via *stdin*) a key and a mode and outputs (via *stdout*) the corresponding scale. Some test cases (*stdin*(`key` `mode`) => *stdout*(`scale`)): ``` Input: Output: C mixolydian => C D E F G A Bb F mixolydian => F G A Bb C D Eb G mixolydian => G A B C D E F G# ionian => G# A# B# C# D# E# F## Bb aeolian => Bb C Db Eb F Gb Ab ``` Further references: [How many (major and minor) keys are there? Why?](https://music.stackexchange.com/questions/7296/how-many-major-and-minor-keys-are-there-why) [Answer] ### GolfScript, 96 characters ``` " "/~5<{+}*7%"v]nwm[{"=2*2base(;\(" #"@?]{.1>))["b""""#"..+]=+\[~@(@+@(7%65+\1$7%4%0>-]}7*;]" "* ``` Golfscript solution which can be tested [online](http://golfscript.apphb.com/?c=OydDIGx5ZGlhbicKCiIgIi9%2BNTx7K30qNyUidl1ud21beyI9MioyYmFzZSg7XCgiICMiQD9dey4xPikpWyJiIiIiIiMiLi4rXT0rXFt%2BQChAK0AoNyU2NStcMSQ3JTQlMD4tXX03KjtdIiAiKgo%3D&run=true). Note: As in the examples the key has to be upper case while mode has to be given in lower case. Examples: ``` >C lydian C D E F# G A B >C mixolydian C D E F G A Bb ``` ]
[Question] [ I had fun solving this, so I offer this golf challenge. The objective of this **golf** is to find the largest prime number that can be constructed using the given instructions. You should accept 3x3 grid of single digits as input. (It's up to you how you want to do that, but specify that in your program.) You can move along the grid orthogonally (left, right, up or down), and as you move, you keep appending the digits you walk across. E.g. ``` 1 2 3 3 5 6 1 8 9 ``` Say we start at `1`, we can form the number 1236589 but **cannot** form 15. You have to evaluate every starting position. If a prime cannot be found, print `-1`, else print the prime itself. Shortest code wins, make sure it runs within 10 secs. Have Fun! Edit: Use one position exactly once, in the entire number. Here's a test case **Input:** ``` 1 2 3 4 5 6 7 8 9 ``` **Output:** 69854123 [Answer] ## Haskell, 239 characters ``` p=2:q[3..] q=filter(#p) n#(x:y)=n==x||n`mod`x/=0&&(n`div`x<x||n#y) (n§m)q=n:maybe[](\i->[q-4,q-1,q+1,q+4]>>=(n*10+i)§filter(/=(q,i))m)(lookup q m) i=[0,1,2,4,5,6,8,9,10] main=getLine>>=print.maximum.(-1:).q.(i>>=).(0§).zip i.map read.words ``` Input is given as a single line of nine numbers: ``` $> echo 1 2 3 3 5 6 1 8 9 | runhaskell 2485-PrimeGrid.hs 81356321 $> echo 1 2 3 4 5 6 7 8 9 | runhaskell 2485-PrimeGrid.hs 69854123 $> echo 1 1 1 1 1 1 1 1 1 | runhaskell 2485-PrimeGrid.hs 11 $> echo 2 2 2 2 2 2 2 2 2 | runhaskell 2485-PrimeGrid.hs 2 $> echo 4 4 4 4 4 4 4 4 4 | runhaskell 2485-PrimeGrid.hs -1 ``` [Answer] ## Python, 286 274 chars ``` I=lambda:raw_input().split() m=[''] G=m*4+I()+m+I()+m+I()+m*4 def B(s,p): d=G[p] if''==d:return-1 G[p]='';s+=d;n=int(s) r=max(n if n>1and all(n%i for i in range(2,n**.5+1))else-1,B(s,p-4),B(s,p+4),B(s,p-1),B(s,p+1)) G[p]=d;return r print max(B('',i)for i in range(15)) ``` This does give a deprecation warning for the float argument to `range`. Ignore it, or spend 5 more chars to wrap `int()` around it. ]
[Question] [ Did you know that [Heronian Tetrahedra Are Lattice Tetrahedra](https://www.maa.org/sites/default/files/pdf/upload_library/2/Marshall2-Monthly-2014.pdf)? A *Heronian* tetrahedron is a tetrahedron where 1. the length of each edge is an integer, 2. the area of each face is an integer, and 3. the volume of the tetrahedron is an integer. It's always possible to place such a tetrahedron in space such that all of the vertices have integer coordinates: \$(x,y,z) \in \mathbb{Z}^3\$. ## Example Consider the tetrahedron oriented so that the base is a triangle \$\triangle ABC\$ and the fourth point is \$D\$ and where \$AB = 200\$, \$AC = 65\$, \$AD = 119\$, \$BC = 225\$, \$BD = 87\$, and \$CD = 156\$. (You can check that the faces all have areas that are integers, and the volume is an integer too.) Then we can give explicit integer coordinates: \begin{align\*} A &= (0,60,0)\\ B &= (96,180,128)\\ C &= (15,0,20)\\ D &= (63,144,56) \end{align\*} (This is shifted from the tetrahedron [illustrated](https://www.maa.org/sites/default/files/pdf/upload_library/2/Marshall2-Monthly-2014.pdf#page=2) in Susan H. Marshall and Alexander R. Perlis's paper.) [![Figure 2 from the paper. An illustration of the tetrahedron given above.](https://i.stack.imgur.com/lKAmE.png)](https://i.stack.imgur.com/lKAmE.png) ### Example Data From [Jan Fricke's paper On Heron Simplices and Integer Embedding](https://arxiv.org/pdf/math/0112239v1.pdf#page=13) ``` AB | AC | AD | BC | BD | CD | coordinates -----+-----+-----+-----+-----+-----+------------------------------------------------ 117 | 84 | 80 | 51 | 53 | 52 | (0,0,0) (108,36,27) (84,0,0) (64,48,0) 160 | 153 | 120 | 25 | 56 | 39 | (0,0,0) (128,96,0) (108,108,9) (72,96,0) 225 | 200 | 87 | 65 | 156 | 119 | (0,0,0) (180,108,81) (120,128,96) (36,72,33) ``` ## Challenge This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. Given a list of lengths of sides of a Heronian tetrahedron `[AB, AC, AD, BC, BD, CD]`, return *any* valid collection of integer coordinates for \$A = (x\_A, y\_A, z\_A)\$, \$B = (x\_B, y\_B, z\_B)\$, \$C = (x\_C, y\_C, z\_C)\$, and \$D = (x\_D, y\_D, z\_D)\$. If one of the coordinates is the origin, you can omit it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 90 bytes ``` ≔…·±⌈θ⌈θηFηFηFη⊞υ⟦ικλ⟧≔⟦⟧ηFυFυFυF⁼X§θ²¦²ΣXλ²⊞η⟦ικλ⟧FηFE³Φ⮌ι⁻νκ⊞ιE⊟κ⁻λ§§κ⁰μI…⊟Φη⁼Xθ²EXι²Σλ³ ``` No TIO link because this is so horribly inefficient it fails to complete even the first test case on my local PC. Explanation: ``` ≔…·±⌈θ⌈θη ``` From a range from `-l` to `l` inclusive, where `l` is the largest of any of the input lengths. ``` FηFηFη⊞υ⟦ικλ⟧ ``` Get the triple Cartesian product of that range, i.e. a list of all points in the `2l+1` size cube centred at the origin. ``` ≔⟦⟧ηFυFυFυF⁼X§θ²¦²ΣXλ²⊞η⟦ικλ⟧ ``` Get the triple Cartesian product of those points, i.e. a list of all tetrahedra within the `2l+1` size cube with one point at the origin in the form `AB`, `AC`, `AD`. ``` FηFE³Φ⮌ι⁻νκ⊞ιE⊟κ⁻λ§§κ⁰μ ``` Calculate the pairwise differences between the three points, i.e. the offsets `BC`, `BD` and `CD`. ``` I…⊟Φη⁼Xθ²EXι²Σλ³ ``` Print the last of the sets of points for which the lengths of the line segments equals the input. Adding minimal filtering to the generated lists speeds it up and it can complete the first test case in under four hours on my PC: ``` ≔…·±⌈θ⌈θηFηFηFη⊞υ⟦ικλ⟧~~≔Φυ№X…賦²ΣXι²υ~~≔⟦⟧ηFυF~~∧⁼X§θ⁰¦²ΣXι²~~υF~~∧⁼X§θ¹¦²ΣXκ²~~υ~~F⁼X§θ²¦²ΣXλ²~~⊞η⟦ικλ⟧FηFE³Φ⮌ι⁻νκ⊞ιE⊟κ⁻λ§§κ⁰μI…⊟Φη⁼Xθ²EXι²Σλ³ ``` Eventually I was able to apply sufficient filtering to come up with a version that can complete the first test case on TIO: ``` ≔X…⁰⊗⌈θ²η≔…±⌈θ⊕⌈θζF…θ³FζFζF⌕Aη⁻×ιι⁺×κκ×λλ«⊞υ⟦κλ±μ⟧⊞υ⟦κλμ⟧»≔E…θ³Φυ⁼×ιιΣXλ²ε≔⟦⟧υF§ε⁰FΦ§ε¹⁼X§θ³¦²ΣXEκ⁻μ§ιν²FEE§ε²⟦ικλ⟧⁺λEEE³Φ⮌λ⁻ρν⁺⊟ν⟦⮌⊟ν⟧E⊟ν⁻π⊟ν⊞υλI…⊟Φυ⁼Xθ²EXι²Σλ³ ``` [Try it online!](https://tio.run/##ZVJNb8IwDD2PX@FjImUShaFN4oTYkDgwVWy3qoesZDQiTekXY0z77Z3TNKUrlayq9rOf33OjmOdRylVdL4pC7jXx0y@Rky3Xe0HGDJ7T6kOJHdnws0yqhGSUUgYTjJjOR22PRb@KPS9FH8lgraNcJEKXNyMu2P6Z5kCW35ESyzg9kozBlFJospfBeyX1bqEUiRlspK4K8i4TURDJQOIwX3WZA4MDZuyHYqCoeeBndOdXRUwqBgFCsNCum9AQNxkWE5P8dfo2/Dhck8FKqhKdwp6XrOJqsNEbCrVWKmMXbTSLq2VByKByFizKtd6JMxEMxrQT3IzvlTzaUdnJrtYuNPlHa3Y@OLMSBg6M@@n2htRxGayJHpkZFiDW2BE6h1GKg5qYdiZsxUnkhSCKOsa8oWn7fHRNm4EOZxPoPLUTHcD2HrHNAuzt3G0U@uXnUpdkyYuydxGDvjmHtSGzUiyJScirUao9C/50dF7XQeB5jwyeHjDwz595GChxNgnD@v6k/gA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 334 bytes ``` ([P,Q,R,S,T,U],f=(n,j=0,c=n**.5|0)=>j>1?c*c==n?[[-c],[c]]:[['']]:[...Array(1+2*c)].flatMap((_,i)=>i?f(n-(i-c)**2,j+1).map(b=>[i-c,...b]).filter(e=>!e.includes('')):[]),t=(y,z)=>y.map((e,i)=>Z+=(e-z[i])**2,Z=0)|Z)=>[...f(R*R).flatMap(e=>f(T*T).flatMap(E=>f(U*U).map(d=>[e,E,d]))).find(([a,b,c])=>t(a,b)==P*P&&t(a,c)==Q*Q&&t(b,c)==S*S)] ``` [Try it online!](https://tio.run/##RY5Pa4NAEMW/SnuJM5txUYuBBtbQQ46F/L1kWYqua1ixazC2kJDvblcL7WnmveH95tX5d37Vnb30oWtLM5zFAHJDW9rRng50VFQJcFSLiLRwjPH0EaHI6ixeaaaFcCspQ61IaqWWUgbBODjnb12X3yCeJ0yj4lWT9@/5BeCDrE/bVQUuBBtqZCyheh4j//TnQmTSm@TzhUJe2aY3HRiRPRtunW6@SnOFIEBcSoXUC7jR3eNuUxjMxD7NBZjwLq2a2CcR4ePk/bFUBTu2w782HlzBgR3@nfXoHNnxt07pU4bWVCrEsY0rAWROBWnlgT34FYXYsM1sNgrtxZZtR1FMYs/2qAbdumvbGN60ZziDfIoXEcXpC8VJRElK6YJeXv2D4Qc "JavaScript (Node.js) – Try It Online") Omits D, which is the origin. The code assumes that D is the origin. There is an `f` function, defined as a default argument, which returns all representations of a positive integer as a sum of three squares of positive and/or negative integers. It then returns the first list of possible triplets of A, B and C coordinates, derived from calling `f` on the AD, BD and CD distances, that satisfy the distance requirements. The code works on the first two testcases. The second one is shown in the TIO link above. Segmentation fault on the third one. Thanks to @Neil for saving 2 bytes. [Answer] # [Ruby](https://www.ruby-lang.org/), 213 bytes ``` f=->a{a[8]?((0..8).map{|i|i%3>0||a<<0;a[-1]+=(a[j=i/3][i%3]-a[-~j%3][i%3])**2};a[6,3].map{|i|i*i}==a[9,3]&&p(a[0,3])): (r=a[2];(s=*0..r).product(s).map{|x,y|q=[x,y,z=(r*r-x*x-y*y)**0.5];z.real?&&z%1>0||f[[q]+a]})} ``` [Try it online!](https://tio.run/##TVDbbqMwEH3PV4wUJQJqWC4lTTallXY/A/lhAs7GFWBiDIWU7K9nh5Kt@jSey7lZt4fhdjsm7gt@YLrlr5ble97W9kqsP0Y5ylX04o8jPj/7e0zdgD8kFqZvifwR8ZSW3KXp37fVvbMdJ7zS4YZF/IvCkdckwXRHs/W6JrhPL9v@ubA0jUO@t5rEIVVte7VWeZsZq7kb6NkwnpOUCrsklna02zu9OzgDCflezPcXTwssXtfryyqYjB7T9MwfkF/t623ZVpkqS1EZEJidIMNGgFGg2wqkAVnlspN5i0UxLAgXBE9s67PtI4sjFocsDjiHpTnJZkZSFedWdlhMjMRjTgIq0RtQlWBwaA38Aqxy@A2oBTTvWNciJxlQOhd6QhxJE8LvNI0qWiNV1cBBHBXBjCyFIqrFYvnf0@NkKw4@PUWcz4uNzwLyGYQ@C2MW7Vi8ua9C6kOfgjyxTcyCYEeHtIPvWerJD9k3ojHzt@Ch@Iw4TRssBeD8pmxThPm4NwzepTlBJ7SRmWi@UlI47JTM6UP@oJGdgExRbFkhScDtHw "Ruby – Try It Online") A recursive function taking input in the form of an array as follows. A is assumed to be the origin. ``` [AD,AC,AB,DC,CB,BD] ``` Alternatively, with relabelling B<>D, this is equivalent to the form below (this still requires the last two columns to be swapped with respect to the test case table in the question, as permitted by the rules.) ``` [AB,AC,AD,BC,CD,DB] ``` The function works on element [2] of the input array. When it finds integer coordinates that correspond to the lengths AB,AC,AD of the input array, it prepends them to the array and calls itself recursively. The data that was previously in elements [1] and [0] therefore ends up being shifted into element [2]. Once a full set of three possible coordinates for B,C,D are added, the array contains 9 elements (tested by seeing if element [8] is present.) Now the lengths of DC,CB and BD are checked and if a solution has been found it is output. **Caveats** In its current form, the code only considers the case where `(x,y,z)` are nonnegative for all vertices. This can be achieved in most (perhaps all) cases by careful selection of the input to ensure A is the most pointy vertex. Negative x and y can be easily considered by changing the code to `s=-r..r`. This costs an extra byte but doesn't actually make the score any higher as there is an unnecessary newline after `:` which can be removed. Within these limits the code should eventually find ALL solutions. (Solutions tend to be in groups of 6 corresponding to the 6 permutations of `(x,y,z)`) . A few more bytes would be need to stop at the first answer. The code is slow but has been tested locally long enough to find first solutions to the first two test cases. A previous version was finding an answer to case 1 in Tio.run before timing out, but the current version always times out before finding any solutions. I've therefore added a rearrangement (swap of vertices B and C) to Tio.run in order to show an example of a solution returned within the time limit. Note also that testcase 3 in the question corresponds to the same case as in the question text, but with vertices relabelled to avoid a negative coordinate. The reason for the code being slow is that it searches for three vertices B,C,D at distances AB,AC,AD before checking the geometry of the other edges. A faster algorithm would be to calculate two vertices (plus the origin) and then calculate the final vertex. The code may be longer then, however. **Commented code** ``` f=->a{a[8]?( #Does a contain (at least) 9 elements? If so iterate through 3 coordinates of 3 points. (0..8).map{|i|i%3>0||a<<0 #If i%3=0 append a zero to a to calculate the sum of squares of coordinate differences. a[-1]+=(a[j=i/3][i%3]-a[-~j%3][i%3])**2}; #Add the squares of the x,y,z differences between the current and subsequent vertex to get the squared distance. a[6,3].map{|i|i*i}==a[9,3]&&p(a[0,3]) #Calclulate the three squared lengths of lines DC,CB,BD in a [6..8]. #Compare with three distances between coordinates in a[9..11]. If a solution is found print it. ): #ELSE (r=a[2]; #let r be the length of the line AB,AC or AD (s=*0..r).product(s).map{|x,y|q=[x,y,z=(r*r-x*x-y*y)**0.5]#find possible integer coordinates for the point B,C or D z.real?&&z%1>0||f[[q]+a]})} #if the z coordinate is real and an integer, prepend to a and recurse. ``` ]
[Question] [ This is a program I wrote in JavaScript to validate some inputted credentials, with an intentional vulnerability. The `credentials_validator` function takes an object as input, with usernames and passwords. It returns a function, which takes a username and password and returns `true` if the credentials are valid. Your challenge is to find a `username` and `password` which, when passed to the function returned by `credentials_validator`, cause it to return `true` without knowledge of the credentials ahead of time. This is a [programming-puzzle](/questions/tagged/programming-puzzle "show questions tagged 'programming-puzzle'"), so the first valid answer wins. **Program:** ``` var credentials_validator = (credentials) => { if (typeof credentials !== "object") throw new TypeError("'credentials' must be an object"); for (var username in credentials) if (typeof credentials[username] === "object") throw new TypeError("Passwords may not be objects or 'null'"); return (username, password) => { if (typeof password === "object") throw new TypeError("Passwords may not be objects or 'null'"); if (!(username in credentials)) return false; if (credentials[username] === password) return true; return false; }; }; /* Run with: var validator = credentials_validator({ "J. Doe": "P4ssword", "R. Wolf": "1234", "X. Ample": "wxyz#1" }); validator("J. Doe", "P4ssword"); // true validator("R. Wolf", "123"); // false */ ``` [Answer] > > username = `'toString'`, password = `{}.toString` > > > [Try it online!](https://tio.run/##tVPPS8MwFL73r3iLh6YwC1NPjgqCXjwNFRREJGvT2ZEm5SVdnWN/e026deu0PRpKoXnv@/E@XpdsxXSMWWHOpUp4Xa8YQow84dJkTOiPFRNZwoxCiIB2CgFEN7DxwJ4sBWrWBVdpFwmjKAKi5kseGxI0je6YT1QVSF7Bs4XcIyqkxO/gfMhLbWDOgUlo4dMG37xSa4U6l6XmKFnOIZNd3aNUv6@3FvcOUa/DQZczpnWlMNGQszVI1ZjcwTVYV74shfBPzCI3JUqgreYYij1JJ79fXtuO/7V3sNiqj@hQoKfa@5FSW@EDVMNpH6bvozRY9jH@FdxOPft4bgnsfHYxXY7kIYQ7xck1kNnVToWM3f1jCC9KpK4wubi82l2@hnCbF6Jpr77W32cT4jgdZXfje/8EakVtil6spFaCh0It6LHoG/VkMJMLfwybbdh@BcG0rn8A "JavaScript (Node.js) – Try It Online") Note: Due to a certain username pointed out by Wezl in the comments, this answer is not valid for the current challenge. ## Why this works: > > Among other properties, [`Object.prototype.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) is inherited from `Object.prototype`, even if it wasn't a part of the object literal given to the validator. Since any object inherits the same function `{}.toString` is the same as the `toString` of the credentials object. > > > ]
[Question] [ [Quote notation](https://en.wikipedia.org/wiki/Quote_notation)[[1]](https://www.cs.toronto.edu/%7Ehehner/ratno.pdf) is a way of expressing rational integers in a precise, finite manner, based on the concept of [\$p\$-adic numbers](https://en.wikipedia.org/wiki/P-adic_number). The notation is in the form of a string of digits (\$0123456789\$) containing exactly one "quote" (a \$\newcommand{'}[2]{#1\text{'}#2} \text{'}\:\$) and one "radix point" (a \$.\:\$). Like with standard decimal notation, if the radix point is at the right end of the string, it is omitted. Some examples of quote notation: $$\begin{array} & \' {123} {456} & \' {123} {} & \' {} {456} \\ \' {12.3} {456} & \' {12.3} {} & \' {} {4.56} \\ \end{array}$$ **Interpreting quote notation** The first thing to handle is the radix point. This point has the same function as regular decimal notation: it divides the integer form of the number by the base (\$10\$) equal to the number of places it is from the end. Therefore, we can rewrite our 3 examples with a radix point as $$\begin{array} & \' {123} {456} \div 10^4 & \' {123} {} \div 10 & \' {} {456} \div 10^2 & \end{array}$$ Now, we can interpret the quote. The quote indicates that the digits to its left should be repeated infinitely to the left, then have the digits to the right appended to the right end. If there are no digits to the left of the quote, a zero is taken instead: $$ \' {123} {456} = \dots 123123456 \\ \' {123} {} = \dots 123123 \\ \' {} {456} = \dots 000 456 $$ We then consider the following converging series: $$\cdots + 10^{3k} + 10^{2k} + 10^{k} + 10^{0} = \frac 1 {1 - 10^k}$$ where \$k\$ is equal to the number of digits to the left of the quote (\$k = 1\$ from the implicit \$0\$ if there are no digits). We can then approach the infinite number in the following way: $$\begin{align} \' {123} {456} & = \dots 123123456 \\ & = 456 + \dots 123123000 \\ & = 456 + 1000 \times \dots 123123 \\ & = 456 + 1000 \times \dots \' {123} {} \\ & = 456 + 1000 \times (\cdots 123 \times 10^9 + 123 \times 10^6 + 123 \times 10^3 + 123 \times 10^0) \\ & = 456 + 1000 \times 123 \times (\cdots + 10^9 + 10^6 + 10^3 + 10^0) \\ & = 456 + 123000 \times \left( \frac 1 {1 - 10^3} \right) \\ & = 456 - \frac {123000} {999} \\ & = \frac {110848} {333} \end{align}$$ If the original number had a radix point in (say, \$\' {12.3} {456}\$), then we just "bring back" the division we performed earlier: \$\' {12.3} {456} = \' {123} {456} \div 10^4 = \frac {110848} {333} \div 10^4 = \frac {6928} {208125}\$ With this notation, we can express any rational number in a finite string of digits with a quote and potentially a radix point. Additionally, the 4 basic operations - addition, subtraction, multiplication and division - are fully defined for quote notated values, and produce exact values with no roundoff errors. **Rational numbers to quote notation** Unfortunately, while there is a clearly defined algorithm for mapping a quote notated value to a rational number, doing the inverse can be far more taxing. The simplest method is to combine the fact that negation and division are clearly and fully defined for quote notated values, then using these to calculate the quote notation form of a rational number. Natural numbers are easily expressed in quote notation, as are positive finite terminating decimals. \$\' {} z\$ is the quote notation form of a natural number \$z\$, or a finite terminating decimal \$z\$. For example, \$\' {} 2 = 2\$ and \$\' {} {3.2} = 3.2\$. Negative integers and negative finite terminating decimals are also fairly trivial to derive, through negation of their positive equivalents. From these two points, we can then divide any two integers or finite terminating decimals to construct any arbitrary rational number, expressed in quote notation form. **Negating quote notated values** The easiest way to negate any quote notated value is to subtract it from \$\' 0 {}\$. This is almost exactly like digit-wise subtraction for regular decimal numbers, but rather than "borrowing" a digit from the left if the minuend digit is less than the subtrahend, we "carry" a digit. For example, to negate \$\' {429} {}\$: $$\begin{array} \dots & 0 & 0 & 0 & 0 & 0 & 0 \\ \dots & 4\_1 & 2\_1 & 9\_1 & 4\_1 & 2\_1 & 9 \\ \hline \\ \dots & 5 & 7 & 0 & 5 & 7 & 1 & = \' {057} 1 \end{array}$$ We start by subtracting the \$9\$ from \$0\$ on the right end. As \$0 < 9\$, we carry a digit along (notated by \$2\_1\$ etc.) and subtract \$9\$ from \$10\$, yielding \$1\$. We then repeat this for each digit to the left, adding the carry to the subtrahend (\$10 - (2 + 1) = 7\$, carry a \$1\$ as \$0< (2+1)\$, etc.). Eventually, we'll end up with a section repeating infinitely to the left, so we can put our quote in. **Dividing quote notated values** Division can be calculated through examining the last digit of both the divisor and the dividend, and is built up from the right end of the result. This is best demonstrated with an example, \$\' {} {143} \div \' {} {333}\$: We examine the last digit to determine what we multiply the divisor by. We then subtract this multiple from the dividend until we reach a repeated difference. In the example below, the quotes have been fully expanded, and subtraction carries have been omitted: $$\begin{array}{rrccccccccl} & \dots & 0 & 0 & 0 & 0 & 0 & 1 & 4 & 3 & = \' {} {143} \\ - & \dots & 0 & 0 & 0 & 0 & 0 & 3 & 3 & 3 & = \' {} {333} \times 1 \\ \hline \\ & \dots & 9 & 9 & 9 & 9 & 9 & 8 & 1 & & \' {} {} \\ - & \dots & 0 & 0 & 0 & 2 & 3 & 3 & 1 & & = \' {} {333} \times 7 \\ \hline \\ & \dots & 9 & 9 & 9 & 7 & 6 & 5 & & & \\ - & \dots & 0 & 0 & 1 & 6 & 6 & 5 & & & = \' {} {333} \times 5 \\ \hline \\ & \dots & 9 & 9 & 8 & 1 & 0 & & & & \\ - & \dots & 0 & 0 & 0 & 0 & 0 & & & & = \' {} {333} \times 0 \\ \hline \\ - & \dots & 9 & 9 & 8 & 1 & & & & & \text{Repeated value} \\ \end{array}$$ Each step, we leave the last digit that was cancelled from the subtraction blank. Note that this is only the last digit, not all trailing zeros, as these can have an impact on the final result. In this case, we have the digits of our division, we just need to know where to place the quote. We always place the quote immediately after the first occurrence of the repeated value (marked with a quote in the example above). For our example, \$\' {} {143} \div \' {} {333} = \' {057} {1}\$ However, this only works in cases where the divisor (\$\' {} {333}\$ in the example) is co-prime with \$10\$. If the denominator in the fraction \$\frac a b\$ is not co-prime with \$10\$, we need to manipulate the fraction to the form \$\frac x {10\times y}\$ where \$y\$ is co-prime to \$10\$, then extract the \$\div 10\$ to modify the position of the radix point in the result \$x \div y\$. For example, \$8 \div 15\$: $$\begin{align} 8 \div 15 & = 16 \div 30 \\ & = 16 \div 3 \div 10 \\ 16 \div 3 & = \' 6 {72} \\ \therefore 16 \div 3 \div 10 & = \' 6 {72} \div 10 \\ & = \' 6 {7.2} \\ \therefore 8 \div 15 & = \' 6 {7.2} \end{align}$$ This way, we are fully able to divide any natural number by another, allowing us to express all positive rational numbers. Through negation, we can then express all rational numbers. **Normalisation of quote notation** As the left hand side of the quote is infinite, it is possible to "roll" it into the right hand side, to obtain an alternate form of the value. For example \$\' {057} 1 = \' {705} {71}\$ (try writing them both out if you can't see it). Therefore, it is usually possible to *normalise* a quote notated value by potentially rolling any leading digits from the right side of the quote into the left side. The normalised form of quote notation is always the shortest possible representation of that number. --- You are to take a rational number as input, and output the normalised quote notation form of this rational number. You may choose to take input as either a fraction \$\frac a b\$, or as two integers \$a, b\$. If the input is negative and you take 2 integers as input, you may choose which integer has the negative sign, so long as it's consistent. In either case, the fraction will be fully simplified, and \$b\$ will never be equal to 0. If \$b\$ is equal to \$1\$, you may choose to omit it. You may output the quote notated value in any reasonable manner. For example, outputting as a string with 2 distinct, non-digit characters representing the quote and radix point, or outputting 2 lists of digits and a power of 10 to represent the radix point. Note that there may not be digits after the quote, and that leading zeros matter for both strings of digits, so the format you choose must be able to represent significant leading zeros, as well as distinguish between an empty output and a zero output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases ``` 2/1 = '2 -85/7 = 571428'45 58/3 = 6'86 -11/8 = 9'8.625 32/21 = 047619'2 -85/56 = 714285'5.625 677/86 = 162790697674418604651'9.5 -332/9 = 8'52 71/51 = 1960784313725490'21 1/17 = 2941176470588235'3 -1/900 = .11' 389/198 = 35'5.5 -876/83 = 38554216867469879518072289156626506024096'28 -38/2475 = 3.5'2 -1081/2475 = 67'.24 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~142~~ ~~128~~ 125 bytes ``` {Clear@r;_r:=e<(e=10#2~GCD~e);e=10;l=1//.o_?r:>10o,n=l#;{}//.g_/;!r@n:>(For[j=0;r@n=l--,!e∣n,n-=#2,j++];n/=10;j<>g),r@n-l}& ``` [Try it online!](https://tio.run/##JYzdaoMwFMfv8xZFKO2a7CRxmmgaJ7R0d2Njl6WIlLRTNEKwV1Kv9x57s72Ii9vVOb//V1v2n6Yt@@pcThc9DbvGlC53qnCpNtuV0YwGfHzZ7UezVjOpRjOAx654dmnGaIetbgI13L12LUAtXG7TbHXo3LHWVHnSDSF4YX6@vi22RAcc15vNSVmYx@ptdl1jnyLNfTm93yrT52@usv0xINklz4PTMn94vbXGlX3n9sZ2bWXnd/w4l3YcEMeIyAgERpGE0ANjIDEKOXD2b0UxRrEQIP0loTcSjASDyNsMmJgrkFDqOzIBlsi5JWKQf2NUMuBPIsLIB4hgPIQQ3adf "Wolfram Language (Mathematica) – Try It Online") Input `[n, d]`. Implements the division algorithm. Returns `{r, QD, q} | r`, where `QD` is a `StringJoin` of digits and `r` is a power of ten, representing \$\text{Q}\_1\cdots\text{Q}\_q\text{'D}\times\frac{1}{r}\$. --- For a nicer output format, **~~141~~ 138 bytes**: ``` {Clear@r;_r:=e<(e=10#2~GCD~e);e=10;l=1//.o_?r:>10o,n=l#;TakeDrop[{}//.{g___}/;!r@n:>{For[j=0;r@n=l--,!e∣n,n-=#2,j++];n/=10;j,g},r@n-l]}& ``` [Try it online!](https://tio.run/##JYzRToMwFIbv@xYLyaKu9dAitFA7SbbMO6PRu2UhzdJNEIpp2BWBa9/DN/NFsOjVOX@@//sb3b2bRnflUU8nNfWb2miXO1m4TJn7K6NoGLDxcbMdzbWck6wVBbhtiweXrWnYYqvqQL7pD7N17ee@Hzzsz0VRDCAXLrfZut@1bl@pUPqkakLwwvx8fVtsiQoYrlarg7QwL1f4PGBfIvVhWE4vl9J0@bMrbbcPyPqU58Fhmd88XRrjdNe6rbFtU9r5HV@P2o49YhgREQPHKBYQ@UApCIwiBoz@ozjBKOEchL8k8iDFiFOIPaZA@axAGobeESnQVMwWT0D8jYWCArvjMUa@QDhlEURomH4B "Wolfram Language (Mathematica) – Try It Online") Input `[n, d]`. Returns `{r, {Q, D}}`, where `Q` and `D` are lists of digits and `r` is a power of ten, representing \$\text{Q'D}\times\frac{1}{r}\$. --- Another approach, **~~154~~ ~~159~~ 153 bytes** ``` q±#|l@#-#2&@@r[FromDigits[a___~g~b_List:{9}:={q=If[#<0,b,9-b]~RotateRight~l@!a};g@@@r@#]10^l@q+#]& {a_,b___}±{a_,c___}={b,a}±{c} l=Length r=RealDigits ``` [Try it online!](https://tio.run/##JY1NboMwEIX3vkVliU2NjKFgOy2VF1WlSlm0dIkoMogfS0AEcVcU3ylXyMWoncxm3syb980odd@MUqta7m26z9cL/BsE9GHoCbHk78tpfFOd0udclmVpOlOVR3XWh5Vvh3Sd0482hy8BqhD3q8JkJy11k6mu12YQD3J77oTFCFiQ4GcQ8yMsPLDKElUWtl0vTtZOpmuFpFvUGxjSYzN1ugdLmjVyuL/fv35Vo8XnoiadQ/@1tUzPfNdyMisIEfBZjCkCMcORHQjBDIEoxCG5W3GCQEIpZrb7kTU4ApTg2NoEE@oimAeBzTCOCWcuRRPMbrCAERw@0RiB4HbuCmz7Pw "Wolfram Language (Mathematica) – Try It Online") Input `[n/d]`. Computes the quoted number from the input's (possibly repeating) decimal representation. Returns `Q ± D | r`, where `Q` and `D` are lists of digits and `r` is a nonnegative integer, representing \$\text{Q'D}\times10^{-r}\$. Normalization costs 39 bytes. Uses \$0=b\_1b\_2...b\_n\text'\overline{b\_1b\_2...b\_n}\$, i.e. any infinitely repeating sequence (in both directions). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 202 bytes ``` NθNη≔⁰ζF⟦χ⁵¦²⟧W¬﹪ηι«≦⊕ζ≧÷ιη≧×÷χιθ»¿⊖η«≔χεW﹪⊖εη≧×χε≧×÷⊖εηθ≔θδ≔¹ηW÷⁻×⊖ε﹪θηδ×εη«≧×χη≔×±δ↨E↨⊖ηε¹εθ»≔ΦI⁺ε÷⁻×⊖ε﹪θηδηκδ»«≔¹ηW÷⁺θη⊗η≧×χη≔…9‹θ⁰δ»≔ΦI⁺η﹪θηκη≦⁻L⁺δηζW⮌…∨⮌δ0±ζ«≔⁺ιηη≔…⁺ιδLδδ≔⁰ζ»⭆δ⁺….⁼κζι'⭆η⁺….⁼⁺Lδκζι ``` [Try it online!](https://tio.run/##nZRLT9tAFIXX8a@48qYz0lCFSuUhVm3SSkgkINodYmHiG8@IiR17xkGA8tvNvPwIJFTqJvbY9577nTPjLHhSLYpENs1lvq71vF49YEVKehEN19ysfyglspyMGbyY1bKogNwdm9V3Bt/uKTxxIRHIvNBkVqS1LAhnICil8BqNZsk6tF/miwpXmGtMvVD/7lZkXJsCPRUbkaLpZsD3VPwVK1QMukJiKQRlYKm3kVgCmWI3xbA7hDDf1qIVDbyBddiA1M6lsH9sJ/Avqo@SnrAlKRmkg@VxMBu4ep2ZyGvl5T9oBvrSAVs9Br4Q3RNnfHTYhxvYAvjGOWaJRmKVfibKTE/WxN3sRmozMBru2vradl5@C6nNqZkkSpMbWTuc/zZkfTB4pD6uLaBUONzQQ7m5waXPfVrUD9Kfhc/2lQ/2Y/K8kDjhxZrE5zGDK1RObUxbkOiQWf7ORqC34t3oK1xqH4SVzjPNfW8ajNsvIzi6xQ1WZgN6oOuqe2gDisex@Q0b90Lpznl3qsKnsN9eW2GlAkramhztfvTb6KYSuSZ/tLlk9mgYXtc/SOurSetXWSdSkUfbRv3fwEXojb/E3X2vwz/Vca86Nh9nL9w0J6en0dlJc7SRbw "Charcoal – Try It Online") Link is to verbose version of code. Takes numerator and denominator on separate lines. Explanation: ``` NθNη ``` Input the numerator and denominator. ``` ≔⁰ζF⟦χ⁵¦²⟧W¬﹪ηι«≦⊕ζ≧÷ιη≧×÷χιθ» ``` Calculate the position of the decimal point, and adjust the fraction by the appropriate power of 10, so the denominator's GCD with 10 is now 1. ``` ¿⊖η« ``` If the denominator is still greater than 1, then: ``` ≔χεW﹪⊖εη≧×χε ``` Calculate the smallest string of `9`s that is divisible by the denominator. ``` ≧×÷⊖εηθ≔θδ ``` Calculate the numerator for that string of `9`s as a denominator. ``` ≔¹ηW÷⁻×⊖ε﹪θηδ×εη ``` See whether we can create quote notation for that fraction. ``` «≧×χη≔×±δ↨E↨⊖ηε¹εθ» ``` If not, add another digit after the quote and try again. Note that this involves calculating the multiplicative inverse of the denominator modulo the power of 10 given by the number of digits after the quote. ``` ≔ΦI⁺ε÷⁻×⊖ε﹪θηδηκδ ``` Calculate the digits before the quote. ``` »« ``` If the denominator was 1, meaning that we had a terminating decimal, then: ``` ≔¹ηW÷⁺θη⊗η≧×χη ``` Calculate the number of digits after the quote. This is particularly significant for negative numbers, but it also means that I can share the code that generates digits after the quote. ``` ≔…9‹θ⁰δ» ``` Place a 9 before the quote if the value is negative. ``` ≔ΦI⁺η﹪θηκη ``` Calculate the digits after the quote. ``` ≦⁻L⁺δηζW⮌…∨⮌δ0±ζ ``` If there are not enough digits for the decimal point, then... ``` «≔⁺ιηη≔…⁺ιδLδδ≔⁰ζ» ``` ... add digits after the quote as necessary, using digits from before the quote or `0`s if there are none, rotating the digits before the quote. ``` ⭆δ⁺….⁼κζι'⭆η⁺….⁼⁺Lδκζι ``` Output the digits before and after the quote, inserting the decimal point appropriately (unless it goes at the end, in which case it isn't output). ]
[Question] [ After all assignments are submitted, a dictionary is created that maps student number to the hash of their file. This dictionary, or hashmap, or mapping (whatever your language calls it) will look as follows: `{100: "aabb", 104: "43a", 52: "00ab", 430: "aabb", 332: "43a"}` The key is the student number, and the value is the hash. Our task is to pick out the cheaters! The cheaters are the ones which have identical hashes. Given the input `{100: "aabb", 104: "43a", 52: "00ab", 430: "aabb", 332: "43a"}`, the function should return (or print) the following text: ``` 100 has identical files to 430 104 has identical files to 332 ``` Notice how the files where the hashes are unique are not mentioned. **Also, the order is important here**: `{100: "aabb", 202: "aabb", 303: "ab", 404: "aabb"}` should return (print) the following text: `100 has identical files to 202,404` It is **incorrect** to print any of the following: `202 has identical files to 100,404` `100 has identical files to 404, 202` You should print it in terms of how it appears in the dictionary. In some languages, going through a dictionary is random, so in this special case, you are allowed to change the method of input such that you can go through it in an orderly fashion. **More Examples:** ``` {} # prints nothing {100: "ab", 303: "cd"} # prints nothing again {100: "ab", 303: "cd", 404: "ab"} 100 has identical files to 404 {303: "abc", 304: "dd", 305: "abc", 405: "dd", 606: "abc"} 303 has identical files to 305,606 304 has identical files to 405 ``` Shortest code wins! [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 113 bytes Takes input as an array of arrays in `[key, value]` format. Go go gadget double flatMap! ``` o=>o.flatMap(([x,h],i)=>(a=o.flatMap(([y,H],j)=>j>i&H==h?(o[j]=[,j],[y]):[]))+a?x+' has identical files to '+a:a) ``` [Try it online!](https://tio.run/##lY5Nb8IgHMbv@xSkhwkpGhT0YEK9etknIBz@pXSFkGJsY/TTd1gxccuyZMff85bHwwUGc3ancVlDbcOyj42dWjlFWcVVG2D8gBPG6ko7TR2RFQb5qt/oUVOfdF@596OU3QFH5bVU1GuqbprslSakhMO1XKAOBuQa24/OQECtC3ZAY0SLEvZAJhP7IQa7CvETt/hee/shqTVjFBVQF5oixRlPYJpC/yOaQDCRnd96jyjUJhfv2abJsH2xxEzZ2rHd0/rjDNSPO@t5VXCYabtJwFi@Kvi3KOebZzQNT18 "JavaScript (Babel Node) – Try It Online") --- # [JavaScript (Babel Node)](https://babeljs.io/), 114 bytes Takes input as a native JS object. ``` o=>Object.keys(o).flatMap((x,i,a)=>(a=a.filter(y=>i--<0&o[y]==o[x]&&(o[y]=y)))+a?x+' has identical files to '+a:a) ``` [Try it online!](https://tio.run/##jY7LasMwEEX3/QrhhSPhB0qkZBEq5wtKPyBkMXq4VSqsEIlgU/rtrqKEUkoL3Z053DszR7hAUGd7io0EaVwzeG3mXsxedM/yaFRs38wUsCdt7yA@wQnjsbY1ENFhEND21kVzxpPobNM80tLvp4MQfj8eyhLnYSKEVLAbqwV6hYCsNkO0ChxKVRNQ9GhRwRbIrPwQvDOt8y@4x@8fhDz8UEtKt6gAWdSIUZZQ6eKfsRpxym/2l8YtBlLlyjWndcb1l@aZs97QzV3/fRzk9fwy7@IMEq9XCSnNb3H2LcTY6h5K6@ZP "JavaScript (Babel Node) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~127~~ 126 bytes ``` def f(x): for l in{`[K for K,V in x if v==V]`[1:-1]for k,v in x}: if','in l:print l.replace(',',' has identical files to',1) ``` [Try it online!](https://tio.run/##fZDBCsIwDIbP7inCLlWI0un0UPAJvHspBevaYrFsYw6piM8@262KJ2/58v0JJO2jvzT1ehiUNmDmfsEyME0HDmz9PPHDCAc8BgQP1sB9vz@KEy/YshDRXfE@uhfLZtYQJAEcaztb9@BWnW6drPQ89JHARd7AKl33tpIOjHX6Bn1DsFgMcZWPizhwgcB5QSlCLs95pA3dBKhULv65ACUtk5mCSPyDCEwhea7SSEwplWD7o8qRktrR3UcJEOHA6SyfzeKnEn67nMWfjG4qv4nhDQ "Python 2 – Try It Online") Takes a list of ordered pairs `(<studentNumber>,<hash>)` as input. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 71 bytes ``` +m`((:.+)$(¶|.)+?)^(.+)\2$ ,$4$1 :.* G`, %1`, has identical files to ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZwQXa1TG6tg/187N0FDw0pPW1NF49C2Gj1NbXvNOA0gN8ZIhUtHxUTFkMtKT4uLyz1Bh0vVEEgoZCQWK2SmpOaVZCYn5iikZeakFiuU5Cv8/19dy1VtaGBgpaCUmKSko2BsYAxkJqco4RDWUTAxMIGIAlVAhBOTksFKQOIpKWCmKVzYBMwGC5sZmEGFawE "Retina 0.8.2 – Try It Online") Takes input on separate lines but link includes test suite that splits the examples for you. Explanation: ``` + ``` Repeat this match until no more replacements can be made. ``` m`((:.+)$(¶|.)+?)^(.+)\2$ ,$4$1 ``` Look for pairs of matching hashes and append the key of the second match to that of the first match with a comma separator. ``` :.* ``` Delete all of the hashes. ``` G`, ``` Keep only the lines with commas. ``` %1`, has identical files to ``` Replace the first comma on each line with the desired text (including trailing space). [Answer] # [R](https://www.r-project.org/), ~~145~~ ~~132~~ ~~129~~ ~~126~~ 124 bytes ``` function(m,`!`=names)for(e in !(t=table(m))[t>1])cat(el(n<-!m[m==e]),'has identical files to',paste(n[-1],collapse=','),' ') ``` [Try it online!](https://tio.run/##pZGxbsMgFEV3voK4AzyJSHZsZ4hCt35BszmWgjFOkDCOAp2qfrsLxKrSoaqqMt13dTnwdG/zwOfhzUqvJ0tHdlqduBWjcjBMN6qwtnhFPfeiM4qOAI1/LlqQwlNlqN2vV2Mzcq5aYOQiHNa9sl5LYfCgjXLYT4RdhfOK2mZdtExOxoirU5wwEq4gArNXzju8X2OjnadI0qzI84xnQnRdxsJQhaEqRdD1Jsg8F9GvyodQWW6WEDD8hA8vrwdcBFSY/nUW1ObhV@m5vAxS9tkf@Auq/AkVNkqbBvc36oKqIup@X3QysSKg75Osv@wq6WRv8@1iwzdUjQChWLiOhRc7o@zZX2iqBuAdYRwbJ0cb04RpRnZHSyD4wz3UNLptAX3Mnw "R – Try It Online") It takes a named vector as input (names are the keys) * -2 bytes thanks to Giuseppe --- If `", "` separator (with a space after the comma) is allowed in case of multiple duplicates, we can use this code and save 10 bytes : # [R](https://www.r-project.org/), 114 bytes ``` function(m,`!`=names)for(e in !(t=table(m))[t>1])cat(el(n<-!m[m==e]),'has identical files to',toString(n[-1]),' ') ``` [Try it online!](https://tio.run/##pZHNasMwEITvegrZPUgLMvg3hxDn1idIbo4hsi0nAlsGe3sqfXZXUkxJD6WU6jQ7jD5pmXnty7V/My3qyfBRXINraeSoFuinmSuqDQ04liibQfERoMJjUkMrkauBm0MUjNVYlqoGwe5yobpTBnUrB9rrQS0UJyZwOuGszY2bKkpckDBYUS240ENEB70gJy0PkzgOy1DKpgmFHXI75Jm0ukitjGPp/Dx7CmVZuoVA0Bd6fj2daWJRdvrX2VDp06/8c3FmZduFf@BvqOwnlN3Ib2rd36gbKneox33ZtJ7lAF3nZfFl5157exfvNhu@oQoChLiatas52Q/K3PDOfTUA74RS1zO7GJdmQgu2vxgG1u8foarSdQ3kY/0E "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σθ}.γθ}vyg1›iy€нć“ÿ€°Ê¼‡œ€„ “?',ý, ``` [Try it online](https://tio.run/##yy9OTMpM/f//3OJzO2r1zm0GkmWV6YaPGnZlVj5qWnNh75H2Rw1zDu8Hsg9tONx1aM@jhoVHJwN5jxrmKQBl7NV1Du/V@f8/OtrQwEBHKTExKUkpVgfIMdFRMjFOBLFNjXSUDAwSweKWCCXGxkZwJUYGRjCJWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6mj5F9aAuP8P7f43I5avXObgWRZZbrho4ZdmZWPmtZc2Huk/VHDnMP7gexDGw53HdrzqGHh0clA3qOGeQpAGXt1ncN7df7X1h7aZv8/OjpWR0EhOtrQwEBHKTFJKVYn2tjAWEcpOUUpFreMTrSJgQlEFKIILJOYlAxRBZRKSYEwTeHCJiA2RNjMwAwqjGxFYhLYEkOQdhPjRBDb1EhHycAAYrklQomxsRFciZGBEUwiNhYA). **Explanation:** ``` Σθ} # Sort the (implicit) input by the string .γθ} # Then group it by the string v # Loop `y` over each grouped inner list yg1›i # If the group contains more than 1 key-value pairs: y€н # Only leave the keys ć # Pop and push the head and rest of the list separately # (with the head being at the top of the stack now) “ÿ€°Ê¼‡œ€„ “ # Compressed string "ÿ has identical files to " # where the "ÿ" is automatically replaced with the top of the stack ? # Print it (without trailing newline) ',ý '# Join the remaining numbers by a comma , # And output it as well (with trailing newline) ``` [See this 05AB1E answer of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“ÿ€°Ê¼‡œ€„ “` is `"ÿ has identical files to "`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~98~~ 96 bytes ``` ->h{h.group_by{|k,v|v}.map{|k,v|x,*y=v.to_h.keys;p"#{x} has identical files to #{y*?,}"if y[0]}} ``` [Try it online!](https://tio.run/##dZBLDoIwFEXnrqKpM1ObJ0UnBF0IIab8LEGFSCE2pWtHWn84cHbe6b130FuXqLEIx/VeaEFPt7prjonSQ0X6oTf0wpsn38lKhT2V9VHQKldt0OClvhskeIvKLL/KMuVnVJTnvEWyRkutVgdicFkgFUFszBjpDUC4x5wnCSZoA/50@IxPvPUmBODW@2wWYsx7hQxZ/PY98GY5YPZwfbfrvO3Met9gmuF//jPwrL@HU5exD1nmcPvRvmOnd7B7abOIac5ToQc5NJ2cviQoIhkHls34AA "Ruby – Try It Online") Takes input as Ruby Hash, returns by printing. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes ``` Ṫ€ĠḊƇṢịẎµḢ;“]⁶ḅhṬyU⁹æṇL[Oþ⁹cƘƓ»,ṾK)j⁾¶¶ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlWPmtYcWfBwR9ex9oc7Fz3c3f1wV9@hrQ93LLJ@1DAn9lHjtoc7WjMe7lxTGfqocefhZQ93tvtE@x/eB@QkH5txbPKh3ToPd@7z1sx61Ljv0LZD2/7//x8dbWxgrKOglJiUrBSrowDkmQB5KSlQjimSlAmYB5UyMzCDScUCAA "Jelly – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 130 bytes ``` a=>a.GroupBy(x=>x.Value,x=>x.Key).Where(x=>x.Count()>1).Select(x=>x.First()+" has identical files to "+String.Join(",",x.Skip(1))) ``` [Try it online!](https://tio.run/##rZHPT8IwFMfv@yteempDXUZALrIlasSoFxIMHgiH0nXSMDvSdshi@NtntwaFGPyReGs//bzve83j5owbWY9KxYd3N6p8EZotcjF8ENWU5aUYM6mHUllqrJbqOUnoobWHkEFcszhh4a0uyvVVhbdxsg3bBNoeXR4Jn5ZCC/90XZTKYpJ0STgRueDW45HUxuEOgiUzIFOhrOQsh0zmwoAtAHUmbc/wvpAKI4roNpys5Bp3CSH1RRCcGhxWmzV2d1iJioKHsGlMAnECSrzCqVLclnjXddgwDVYYayD@tmw2n82DtwB@kJzQSDv6WxPar3SjiCK2QIR@oF7Uo4inHv13nkf9qP9p/bVFm8cW/LiHC0zTY3T@Res37FgbRIMDzc2yc7vJCi0YXwLeLwmk8ssi7SBjN5fFGW4QCR@LS61ZhYlb665@Bw "C# (Visual C# Interactive Compiler) – Try It Online") The strange thing about this question is that the examples are given in a JSON format as key/value pairs which usually implies that they are unordered... In this case however, order is important. As such, I am using a list of tuples for input and a list of strings as output. ``` // a is a list of tuples // (student #, hash) a=>a // group by hash // grouped items are the student #'s .GroupBy(x=>x.Value,x=>x.Key) // remove single student groups .Where(x=>x.Count()>1) // format the output strings .Select(x=>x.First()+ " has identical files to "+ String.Join(",",x.Skip(1))) ``` [Answer] # Perl 5, 100 +1(-n) bytes ``` for$x(/[a-z]+/g){($t,@a)=${h{$x}}++?():/\d+(?= $x)/g;@a&&say"$t has identical files to ",join",",@a} ``` [Try it online!](https://tio.run/##VcwxDoIwGIbh3VP8aappA7U1goOEwAU8gTpUilJDKKEdUMLVrcXN6cvzDW9fD23q101OaGblCzHGUObvZsAj4WfJ3teIP@hEsItLSXM8NRMe5zmKCkKP/KIiUuSAR8ofWSk3myWBHTTSglZ153QlW7jrtrbgDKD4aXSHYhRas/c7IUDeYC/2UKnVnyARSdBqkbxV4U1AqTDpj0nYwIM4LPyY3mnTWc86YKd0K3biCw) [Answer] # [Japt](https://github.com/ETHproductions/japt), 34 bytes ``` üÌl>1 ®mgîÎ+` •s ÅÁÈól fÅC ‘ `+ZÅ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=/MxsPjEgrm1nw67OK2AglXMgxcHI82wgZsVDIJEgYCtaxQ==&input=W1szMDMgImFiYyJdLFszMDQgImRkIl0sWyAzMDUgImFiYyJdLFsgNDA1ICJkZCJdLFsgNjA2ICJhYmMiXV0KLVE=) Right now it's a bit inconsistent in the ordering of lines, but within a line it outputs correctly. If the lines of the output need to be in a specific order, it will take a few more bytes. Input is just an array of `[id, hash]` pairs Explanation: ``` üÌ :Group by hash l>1 :Remove the ones that are unique ®mgà :Get just the Ids ® :Generate a string for each hash: Î : The first Id with that hash +` •s ÅÁÈól fÅC ‘ ` : Plus " has identical files to " compressed +ZÅ : Plus the remaining Ids : Implicitly comma delimited ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~115~~ ~~110~~ 103 bytes *-2 bytes thanks to Jo King* ``` {unique map {.[0]~" has identical files to "~join ',',.skip},grep *>1,.map:{.grep(*{*}eq$^p{*})>>.key}} ``` [Try it online!](https://tio.run/##fcvJDoIwFIXhPU9x0xAZ0jQlIAsNvIhRU6BoZSrTghB4dZQqxpWrmz/fuZI3ub8UA@xSCJaxL0XdcyiYhJGc6HlGcGctiISXnYhZDqnIeQtdBWh@VKIEAxuYtJmQE741XIIdOpi83g8jWdu0R3vitX6Rr2uFIcn4ME1LaurXtVo2QFo1mmlhzXQohSAExCKEwaWuijhB/wyDR71N1uFmLIrV8o1JomL/Q96nFPnU/5J1XJ4 "Perl 6 – Try It Online") Takes a list of Pairs since hashes are unordered. A list of two-element lists would save a few bytes but seems unidiomatic. Returns a list of lines. **~~95~~ 88 bytes** if the order of lines in the result doesn't matter: ``` *.classify(*{*}){*}>>.key.grep(*>1).map:{.[0]~" has identical files to "~join ',',.skip} ``` [Try it online!](https://tio.run/##fczfCoIwFMfxe5/iMCI3GWOieVHoi0TE1K2Wf3HeiOirm62Mrro4F18@P04ruzJaqgH2CuLFY1kpjNFqwN7oTWS9JGGFHNitky32Ep@wSrTHkZ35ZUZwFwZ0LuteZ6IEpUtpoG8AzY9G1@BSlzJT6HZaTo7CuytZnxkxgGo6BxPqYJ9ziBNAIkUUAh7YyHL0zyiEPNzkNdxMpJldvjHPbRx@KPyUpYhHXyJ0eQI "Perl 6 – Try It Online") ]
[Question] [ # Introduction Your task is to generate the first 1000 terms in the continued fraction representation of digit-wise sum of square root of 2 and square root of 3. In other words, produce exactly the following list (but the output format is flexible) ``` [2, 6, 1, 5, 7, 2, 4, 4, 1, 11, 68, 17, 1, 19, 5, 6, 1, 5, 3, 2, 1, 2, 3, 21, 1, 2, 1, 2, 2, 9, 8, 1, 1, 1, 1, 6, 2, 1, 4, 1, 1, 2, 3, 7, 1, 4, 1, 7, 1, 1, 4, 22, 1, 1, 3, 1, 2, 1, 1, 1, 7, 2, 7, 2, 1, 3, 14, 1, 4, 1, 1, 1, 15, 1, 91, 3, 1, 1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 10, 2, 1, 1, 1, 3, 2, 1, 6, 1, 8, 1, 1, 1, 1, 1, 1, 1, 2, 40, 1, 1, 1, 5, 1, 3, 24, 2, 1, 6, 2, 1, 1, 1, 7, 5, 2, 1, 2, 1, 6, 1, 1, 9, 1, 2, 7, 6, 2, 1, 1, 1, 2, 1, 12, 1, 20, 7, 3, 1, 10, 1, 8, 1, 3, 1, 1, 1, 1, 2, 1, 1, 6, 1, 2, 1, 5, 1, 1, 1, 5, 12, 1, 2, 1, 2, 1, 2, 1, 1, 3, 1, 1, 1, 8, 2, 4, 1, 3, 1, 1, 1, 2, 1, 11, 3, 2, 1, 7, 18, 1, 1, 17, 1, 1, 7, 4, 6, 2, 5, 6, 4, 4, 2, 1, 6, 20, 1, 45, 5, 6, 1, 1, 3, 2, 3, 3, 19, 1, 1, 1, 1, 1, 1, 34, 1, 1, 3, 2, 1, 1, 1, 1, 1, 4, 1, 2, 1, 312, 2, 1, 1, 1, 3, 6, 6, 1, 2, 25, 14, 281, 4, 1, 37, 582, 3, 20, 2, 1, 1, 1, 2, 1, 3, 7, 8, 4, 1, 11, 2, 3, 183, 2, 23, 8, 72, 2, 2, 3, 8, 7, 1, 4, 1, 4, 1, 2, 2, 1, 2, 1, 8, 2, 4, 1, 2, 1, 2, 1, 1, 2, 1, 1, 10, 2, 1, 1, 5, 2, 1, 1, 1, 2, 1, 1, 2, 1, 3, 2, 9] ``` # Challenge The following general introduction to continued fraction is taken from the challenge [Simplify a Continued Fraction](https://codegolf.stackexchange.com/questions/93223/simplify-a-continued-fraction). > > Continued fractions are expressions that describe fractions > iteratively. They can be represented graphically: > > > [![continued fraction](https://i.stack.imgur.com/O7n9K.png)](https://i.stack.imgur.com/O7n9K.png) > > > Or they can be represented as a list of values: `[a0, a1, a2, a3, ... an]` > > > This challenge is to find out the continued fraction of the digit-wise sum of `sqrt(2)` and `sqrt(3)`, the digit-wise sum is defined as follows, Take the digits in the decimal representation of `sqrt(2)` and `sqrt(3)`, and obtain the sum digit by digit: ``` 1. 4 1 4 2 1 3 5 6 2 3 ... + 1. 7 3 2 0 5 0 8 0 7 5 ... = 2. 11 4 6 2 6 3 13 6 9 8 ... ``` Then only keep the last digit of the sum and compile them back to the decimal representation of a real number ``` 1. 4 1 4 2 1 3 5 6 2 3 ... + 1. 7 3 2 0 5 0 8 0 7 5 ... = 2. 11 4 6 2 6 3 13 6 9 8 ... -> 2. 1 4 6 2 6 3 3 6 9 8 ... ``` The digit-wise sum of `sqrt(2)` and `sqrt(3)` is therefore `2.1462633698...`, and when it is expressed with continued fraction, the first 1000 values (i.e. `a0` to `a999`) obtained are the ones listed in the introduction section. # Specs * You may write a function or a full program. Neither should take inputs. In other words, the function or the program should work properly with no inputs. It doesn't matter what the function or program does if non-empty input is provided. * You should output to STDOUT. Only if your language does not support outputting to STDOUT should you use the closest equivalent in your language. * You don't need to keep STDERR clean, and stopping the program by error is allowed as long as the required output is made in STDOUT or its equivalents. * You can provide output through [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins. * As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here. [Answer] # [Kotlin 1.1 script](http://kotlinlang.org/), ~~304~~ 293 bytes ``` import java.math.BigDecimal as b import java.math.* val m=MathContext(1022) var B=b(2) var A=b((""+B.sqrt(m)).zip(""+b(3).sqrt(m)).joinToString(""){(a,b)->if(a=='.')".";else ""+(a-'0'+(b-'0'))%10}) val g=b(1).setScale(1022) repeat(1000){println(B);A=g/(A-B);B=A.setScale(0,RoundingMode.FLOOR)} ``` A bit verbose unfortunately :/ Must be run with JDK 9, as `sqrt` was added to `BigDecimal` in this release. Interestingly, I couldn't find a TIO site with both Kotlin 1.1 and JDK 9 features (Ideone and repl.it both run Kotlin 1.0, which did not support destructuring in lambdas, and TIO complains that `sqrt` does not exist.) Prints each element separated by a newline. Edit (`-11`): moved `println` to the beginning of the loop body and added an additional iteration to avoid repeating the method call. An extra calculation is done, but it is not used for anything. [Answer] # [Python 2](https://docs.python.org/2/), ~~193~~ ... ~~179~~ 178 bytes ``` d=10 u=d**2000 v=u*u def s(n,a=d,i=9): while a-i:i,a=a,(a+n/a)/2 return a p,q,r,t=s(2*v),s(3*v),1,0 while p:t+=(p+q)%d*r;p/=d;q/=d;r*=d for i in range(1000):print t/u;t=v/(t%u) ``` [Try it online!](https://tio.run/##JY7BCsMgEAXvfsVeCmosGnuqYT9G0DRCMcasKf16m9DLGxgYeOVLy5pt7wFHwxoGKa0xhh3YZGMhzrDzrDwGlfApHIPPkt4R/D25dGqvuB@y9kJbBjVSqxk8K2pTVRHu3MpDqJ0/LozKsH9dHA3Iy7CJW5B1KhrDtF1TJQY2rxUSpAzV51fk43lHuFJTJiDdJsJDc7o10fsP "Python 2 – Try It Online") Calculating `sqrt(2)` and `sqrt(3)` to such a precision with a short code is a tough job in Python and other languages. ~~2000 digits is needed to ensure the expansion is correct~~ (1020 suffices, but I'm not going to modify it because no improvement), and lines 4-6 is the integer square root. **193 > 180 : The digit-wise modulo sum is now carried by a loop instead of array manipulation** **180 > 179 : Replaced the 6 occurrences of `10` using `d` with the cost of defining with 5 bytes, cutting 1 byte in total** **179 > 178 : Just realized that `a!=i` can be replaced by `a-i`** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` ȷ*` %¢¢²¤: 2,3×Ñ×ÑÆ½DS%⁵ḌÇȷСṖ:Ñ ``` [Try it online!](https://tio.run/##y0rNyan8///Edq0ELtVDi4Bw06ElVlxGOsaHpx@eCMZth/a6BKs@atz6cEfP4fYT2w9POLTw4c5pVocn/v8PAA "Jelly – Try It Online") --- Basically use fixed-point arithmetic. M may work better here, but somehow `floor(HUGE_NUMBER × sqrt(2)` doesn't want to evaluate for too large `HUGE_NUMBER`. Anyway the fixed-point division is definitely better. --- Explanation: ``` ------- ȷ*` Calculate the base for fixed-point arithmetic. ȷ Number 1000. * Raise to the power of... ` self. (so we have 1000 ** 1000 == 1e3000) Let B=1e3000. ------- %¢¢²¤: Given f × B, return a number approximately (1/frac(f)) × B. Current value: f × B. %¢ Modulo by B. Current value: frac(f) × B. ¢²¤ B² (that is, 1e6000) : integer-divide by. So we get B²/(frac(f)×B) ≃ 1/frac(f) × B. ------- 2,3×Ñ×ÑÆ½DS%⁵ḌÇȷСṖ:Ñ Main link. 2,3 The list [2,3]. Ñ This refers to the next link as a monad, which is the first link (as Jelly links wraparound) × Multiply by. So we get [2,3]×1e3000 = [2e3000,3e3000] ×Ñ Again. Current value = [2e6000,3e6000] = [2B²,3B²] ƽ Integer square root. Current value ≃ [sqrt(2B²),sqrt(3B²)] = [B sqrt(2),B sqrt(3)] DS Decimal digits, and sum together. %⁵ Modulo 10. Ḍ Convert back from decimal digits to integer. С Repeatedly apply... Ç the last link... ȷ for 1000 times, collecting the intermediate results. Ṗ Pop, discard the last result. :Ñ Integer divide everything by B. ``` [Answer] # Haskell 207 bytes I Couldn't find an easy way to compute the continued fraction lazilly, so I worked as well with 2000 digits. ``` import Data.Ratio r#y|x<-[x|x<-[9,8..],r>(y+x)*x]!!0=x:(100*(r-(y+x)*x))#(10*y+20*x) c r|z<-floor r=z:c(1/(r-z%1)) main=print.take 1000.c$foldl1((+).(10*))(take 2000$(`mod`10)<$>zipWith(+)(3#0)(2#0))%10^1999 ``` [Answer] # Deadfish~, 15503 bytes ``` {iiiii}c{dd}iic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}iiic{dd}dddc{ii}ddc{dd}iic{ii}c{dd}c{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}iiciic{dd}ddddc{ii}dddciiiiiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{i}ddc{dd}dddddc{ii}ic{dd}dc{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}ddcdc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}iiiiic{dd}dddddc{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddcc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddciiic{dd}c{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}iiiiic{d}iic{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iciiic{dd}ddddc{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}ddcc{dd}iic{ii}ic{dd}dc{ii}dc{dd}ic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddcdc{d}ddddddc{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}c{dd}c{ii}iiiiicdddddc{dd}c{ii}ddcdcc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddciiiiiicddddc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddciiic{dd}c{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iicddddciccdddc{d}ddddddc{ii}dddc{dd}iiic{ii}dddciiiiiic{dd}dddc{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}ic{dd}dc{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}iiiic{dd}ddddc{ii}ic{dd}dc{ii}dddcic{dd}iic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiicic{dd}ddddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}ccddc{dd}iic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}c{dd}c{ii}c{dd}c{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddc{dd}iic{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciic{dd}ic{ii}dddcc{dd}iiic{ii}dddc{dd}iiic{ii}ddcic{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciic{dd}ic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddciiic{dd}c{ii}dddc{dd}iiic{ii}iiiccdddc{dd}c{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddcdc{d}ddddddc{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddciiiiic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddcc{dd}iic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}iiicc{dd}dddc{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddciiiiic{dd}dddc{ii}dddciiiiic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddcdc{d}ddddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddciiic{dd}c{ii}dcc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{i}dddc{dd}dddddc{ii}ddc{dd}iic{ii}ic{dd}dc{ii}dc{dd}ic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}ciiicddddddc{dd}iiic{ii}dddc{dd}iiic{ii}icdddddc{d}ddddddc{ii}ic{dd}dc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dciiic{dd}ddc{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}ddc{i}dddc{dd}dddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iiiiic{dd}dddddc{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}ddcc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}iiiiic{dd}dddddc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}c{dd}c{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}iiic{dd}dddc{ii}iicddc{dd}c{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcicddc{d}ddddddc{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}dc{dd}ic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddciic{dd}ic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}cdc{dd}ic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}c{dd}c{ii}dddciiic{dd}c{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddcc{dd}iic{ii}c{dd}c{ii}ddc{dd}iic{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}ddc{dd}iic{ii}iic{dd}ddc{ii}dddcdc{d}ddddddc{ii}c{dd}c{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciiic{dd}c{ii}dddc{dd}iiic{ii}ddcc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcc{i}dddc{dd}ddddc{ii}dddc{dd}iiic{ii}dddciiiiic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciiic{dd}c{ii}ddc{dd}iic{ii}ddciic{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddcc{dd}iiic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddcic{dd}iic{ii}iiicddddddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ic{dd}dc{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddc{dd}iic{ii}dddc{i}ddc{dd}dddddc{ii}dddc{dd}iiic{ii}dddciiiiic{dd}ddc{ii}ddc{dd}iic{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddcciiiiiic{dd}dddc{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}iiiic{dd}ddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}dddcdc{d}ddddddc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dcc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{i}dddc{dd}ddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddciciiic{dd}ddc{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}dddciic{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iiiic{dd}ddddc{ii}ic{dd}dc{ii}dddciiic{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iic{dd}ddc{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddciiic{dd}c{ii}ddcc{dd}iic{ii}iiiic{dd}ddddc{ii}dciiiiic{dd}ddddc{ii}c{dd}c{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddcddc{d}ddddddc{ii}ddc{dd}iic{ii}ddciiiiiic{dd}ddddc{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddciic{dd}ic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}cddddc{i}ddc{dd}ddddc{ii}dddc{dd}iiic{ii}ddc{i}dddc{dd}dddddc{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}iicic{dd}dddc{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddciiicddddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddciic{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciiiic{dd}dc{ii}dddc{dd}iiic{ii}dddciiiiic{dd}ddc{ii}ddcic{dd}ic{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ic{dd}dc{ii}ddcddc{d}ddddddc{ii}dddciiiiic{dd}ddc{ii}c{dd}c{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}c{dd}c{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iicddc{dd}c{ii}dddcdc{d}ddddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}c{dd}c{ii}ddc{dd}iic{ii}ic{dd}dc{ii}iic{dd}ddc{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddcc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}iiicddddddciiic{dd}c{ii}iic{dd}ddc{ii}dc{dd}ic{ii}dddcdc{d}ddddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dciiic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcdc{d}ddddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}cddddc{d}ddddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddciic{dd}c{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiiic{dd}dddddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}iiic{dd}dddc{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}ddcddc{d}ddddddc{ii}iiic{dd}dddc{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddcdc{d}ddddddc{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}dddcic{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}ddc{dd}iic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}dddc{i}dddc{dd}ddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddciiiiiic{dd}dddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}iiic{dd}dddc{ii}c{dd}c{ii}iic{dd}ddc{ii}ddc{dd}iic{ii}ic{dd}dc{ii}iic{dd}ddc{ii}c{dd}c{ii}c{dd}c{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iic{dd}ddc{ii}ddcddc{d}ddddddc{ii}dddc{dd}iiic{ii}cic{dd}dc{ii}ic{dd}dc{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dc{dd}ic{ii}dddc{i}ddc{dd}dddddc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dcic{dd}c{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dcddcic{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}iic{dd}ddc{ii}iic{dd}ddc{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddciiic{dd}dc{ii}dddciiic{dd}c{ii}ddciiiiiic{d}iiic{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}dciiiic{dd}dddc{ii}iciiicddddddc{dd}iic{ii}dc{dd}ic{ii}ddcddc{d}ddddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}iiic{dd}dddc{ii}iiiic{dd}ddddc{ii}c{dd}c{ii}dddc{dd}iiic{ii}dddcc{dd}iiic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}dddc{i}dddcdddddc{dd}ic{ii}ddc{dd}iic{ii}ddcic{dd}ic{ii}iiiic{dd}ddddc{ii}iiicdddddc{dd}iic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dc{dd}ic{ii}iiiic{dd}ddddc{ii}iiic{dd}dddc{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}c{dd}c{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}iiiic{dd}ddddc{ii}ddc{dd}iic{ii}c{dd}c{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddcdc{d}ddddddc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ic{dd}dc{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}ddc{dd}iic{ii}dddc{dd}iiic{ii}dc{dd}ic{ii}ddc{dd}iic{ii}iiiiic ``` ]
[Question] [ *Note: In this post, the terms 'character' and 'color' mean essentially the same thing* This image: [![example map](https://i.stack.imgur.com/T7mxF.png)](https://i.stack.imgur.com/T7mxF.png) can be represented as ``` ....'''333 .eeee'''3e ..dddd33ee %%%dd####e ``` (mapping colors to ascii characters) The four color theorem states that "given any separation of a plane into contiguous regions, producing a figure called a map, no more than four colors are required to color the regions of the map so that no two adjacent regions have the same color. Two regions are called adjacent if they share a common boundary that is not a corner, where corners are the points shared by three or more regions." - Wikipedia ([link](https://en.m.wikipedia.org/wiki/Four_color_theorem)) This means that it should be possible to color a map using four colors so that no two parts which share an edge share a color. The algorithm to color a map using only four colors is complicated so in this challenge your program only needs to color the map using five or less colors. The previous map recolored could look like this: [![example five color map](https://i.stack.imgur.com/LLp0l.png)](https://i.stack.imgur.com/LLp0l.png) which could be represented as ``` ....'''333 .eeee'''3e ..dddd33ee 333dd....e ``` or equivalently ``` @@@@$$$!!! @^^^^$$$!^ @@<<<<!!^^ !!!<<@@@@^ ``` **Challenge:** Given a "map" made of ascii characters (where each character represents a different color), "recolor" the map (represent the map using different ascii characters) so that it only uses five or less colors. **Example:** Input: ``` %%%%%%%%%%%%##########$$$$$$$$%% *****%%%####!!!!!!!%%%%%%%%%#^^^ (((((((***>>>>??????????%%%%%%%% &&&&&&&&$$$$$$$^^^^^^^))@@@%%%%% ^^^^^^%%%%%%%%%%%%############## ``` Possible output: ``` 11111111111122222222223333333311 44444111222255555551111111112444 22222224441111444444444411111111 55555555222222255555553355511111 22222211111111111122222222222222 ``` **Clarifications:** * The input map will always use six or more characters * You may use any five different characters in the output * You can use less than different five characters in the output * You may take the input in any reasonable format (including an array of arrays, or an array of strings) * This is code-golf so the shortest answer wins. [Sandbox link](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/13762#13762) [Answer] # [Python 2](https://docs.python.org/2/), ~~375~~ ~~361~~ ~~359~~ ~~357~~ ~~355~~ ~~353~~ ~~350~~ 347 bytes ``` e=enumerate C=set('12345') def f(s): s=[map(ord,l)for l in s] for i,v in e(s): for j,w in e(v): if{w}-C: F,N=g([],s,i,j,w) for y,x in F:s[y][x]=min(C-N) return s def g(m,s,i,j,c): n={s[i][j]} if(n^{c}or(i,j)in m)<1: m+=(i,j), for x,y in(0,1),(0,-1),(1,0),(-1,0): if len(s)>i+x>-1<j+y<len(s[0]):m,N=g(m,s,i+x,j+y,c);n|=N return m,n ``` [Try it online!](https://tio.run/##bZJfT4MwFMWf7acoc5PWFTP884IwTZbscc9LmpKYrWgJFAKokLnPPm9bnD74e2jp6bm9p0A9dG@Vvj2dZCL1eymbl06iVdLKjvjh7d39g0/RXmY4Iy2NEG4TXr7UpGr2rKBZ1eACK41bgbBZKPZhltJ6L4ySs0@nfBgFq@zweQxW8HixZpvklXDBWqYY2ChopmJgvalYRy0fBO9FUipNVsGGItzI7r2BbjbQKynH0p0JppNDy5XguTgiaEN0etgdq4aAgcJxJY1D6FrOE6swl65nA/QiCxZSBmNgppAtYAzM5BLjQmq40FLN@2UQxvl8iK3CF4JGpb2FTTLvGexBmkf9lWzOaUumT6bX1tyKo8lkgp6B6XTqeR56TgHznIIaA56Xpgh24ti4UrDzMBIM2cLZHy7PTEdmM3RtGDc9x28BdELEAa4l8HTmx4SuRsYzUwelEMYZnPB/EsOYGInI/RP2B8nI9qatC9URSiNcN0p32Pdv8grefgFf1iqnbw "Python 2 – Try It Online") Takes input as a list of strings, and returns a list of lists `f` takes the map input and colors it, `g` returns all connected characters and the set of their neighbors, to the area can be colored with a distinct color. ]
[Question] [ *See also: Granma loves Ana* You will be given a string of lowercase ASCII letters. Using [this dictionary file](https://hastebin.com/raw/itudojikot) (UPDATED), your task is to solve the anagram. To solve an anagram, you must output all words or groups of words that can be formed using each letter from the input string exactly once, separated by newlines. Groups of the same words in a different order are not unique and should not be output separately; however, the order of the words **does not matter**. The order of output solutions also **does not matter**. If the input cannot form a word, output nothing. Some useful test cases: ``` Input: viinlg Output: living Input: fceodglo Output: code golf Input: flogflog Output: golf golf Input: ahwhygi Output: highway high way Input: bbbbbb Output: ``` Rules/caveats: * You may access the dictionary list any way you like. Command line argument, stdin, reading from file, or reading from internet are all acceptable. * Input will consist of lowercase ASCII letters only. You are not required to output results in any particular case. * You will not be given a string that already forms a valid word (you may, however, be given a string that forms *multiple* words, such as `bluehouse`). * Trailing newlines are allowed but not required. * Standard loopholes apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Good luck! [Answer] # [Python 2](https://docs.python.org/2/), ~~341~~ ~~327~~ ~~337~~ 320 bytes This solution assumes the dictionary is stored in a variable `w` as a set of strings. The first set of `combinations` does not need to use `combinations_with_replacement`, but using the latter saves bytes. ``` from itertools import* d,o,j,c={},sorted,''.join,combinations_with_replacement s,w=o(raw_input()),input() l=len(s) r=range(l) for x in w:d.setdefault(j(o(x)),[]).append(x) b=set(chain(*[d[j(x)]for y in r for x in c(s,y+1)if j(x) in d])) print'\n'.join(' '.join(x)for y in r for x in c(b,y+1)if(len(j(x)),o(j(x)))==(l,s)) ``` [Try it online!](https://tio.run/##bL1bj/TKERz4rl@hNx15BQPexwX0S7yGUSSr2TXN22GR3cMx9rd7MzMiszhHBiR8c@bCJotVeYmMjNyu47ku//f//t@PfZ3/Xo68H@s61b@XeVv347/8bfjX@q@vf/X//l//37@qfCMP//rHP/7r11qWf/Xr3JUlHWVd6v/8lOP5P/e8TanPc16Ov9V/ff69/rGnz/8sy3Yef/zzn//iF3@b/j3l5Y/6z7/t/97TMuY/pn/@7bHuf//@e1n@/vl/hv9a8zHkRzqn44@vP9Y/vuVv//v/@Od/TduWl0H@82/dv@VX/uifqSx//Jf/Pvz3L/nm/9BLXHqJ/e9xtf6P@q/r//pv/yyP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4u@@tH@IMLuBY67pehZ6osloXQZLZUuWps1UhCy@awER@c66zCTn5hkRTHWsS@3HRazFGclYu@8gJtSWsU63cMvh1iFBTVEe@tEDcQkffh61NSwuH1AsqkzjDgoQN4HI1TPoCCkaHu6RxrBO6KFU9jw6zgwlfo2QMojvZiOUJHtS2X3ZRQoEZj1ej75HlfxmrWfTrYpZAPuJd@MYw9weHueMVK27FiAFtzWiZjq87ls3DaW0KQJqfB4uZXLhla9KIw4mkRbwtboY1c1atezZ3v/aT5XH2fzlHLSHFTkmQ7XzujFc87Q6jERjDSHDlwTgL4u3ZSJ@V/78Gjn@TODvDYXfdqrtcedK3Et/7rGX1x3WpH@oS/ZVF/rVNRRUio/C1JBEjpKTdGtlrTrBQhfTxZCtW2WE3bm@pQ/Shd2Bs8Wz3ByD32O2SAWP@ddZayY0QioHQlXrp2c2js7AwfEVks7EOTx1FtMbRccr5TF8OY71lvysQfn9LALagq3xcE84io/BgS7DrMdePvRbV9fm4hMBLJ7@JSdu@113traQOlW8gG6yMJjxRHAe1rH2h/lLzU4e3qWLfsQotS2XtYutpaTua86OmTTfH9M1f5rCy2sjpB4iLE1@@6Bk5metzUgSVekwMBttNYO2VQ7uCebuCnPSNIBtV3DivgFwuS6tIuiWAvOadlSs9y8a25xrBldoJvNdmcf1EG2TIoyq@mBJNOjo3LnBKDwr1kQdzttP4jGDhWBTwcynepHY@Y5wr4Sx7d@ROlvZ4oYD@gAUE2wUDz/Zr7U//33fw "Python 2 – Try It Online") **Input -** Anagrammed word followed by the dictionary of words as a set: ``` anagram_word {'entry1', 'entry2', ...., 'entryN'} ``` **Edit:** Updated Inputs. [Answer] # [Python 3](https://docs.python.org/3/), ~~248~~ 202 bytes ``` from itertools import* A=set() def f(s,*G,i=1,A=A): if' '>s:A|={' '.join(sorted(G))} for _ in s:s[:i]in S and f(s[i:],s[:i],*G);i+=1 I,*S=iter(input,'') for p in permutations(I):f(''.join(p)) print(A) ``` [Try it online!](https://tio.run/##ZL3NruNakqU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uo8t/Wua7kGdgGqI8fDIG2Nqkc4gSi@ySl3YPEKhKSi9hzV3n6NxdpHgJHaqEZBFF2pSfT8s1pj3E0zFrdor8mlDMG0aZgzS597n797ltpKUuBuaA5@J10rnZPb9NcYRaDhWfv84pdjB8ZqiDkexdc2Uec0CfAk9vT6BSWodQY2pes2w7wWMaxt@CbxhkpeabJyczK2SlRUUoWlW11SBmKyaRtajBRkCU4UnkGUViPbAyWuRK9s2x2W5Ky9AE733X/B1Wc2nznmOkA/rKYwg@d0UMOP4QFhfj@GMEDH7kUCeykrjcwiLzzheaZKFSsOhrJlSREKBN6/Sf8gf/dtuhdeMko29Py2Cm459NfIbv9eGm1iibxtJg9@g/BR7C4SdWkFaUr4GVq0Rh/f2kBGb4NYjgZPqXQMbXy2wKqzHtR6ua29DQAQ8rms9xzW0RgySAStCG@0XdNcJ0WapAdtJ0Y7h5VqW2kHF@r8Q9sk1g7Dls2Tx2LVf9KOSsuhM9Wn2g@QioivtHlUEYmuBto4v/Vn28fHfw "Python 3 – Try It Online") ### Input is as follows: ``` word_input dic_entry_1 dic_entry_2 .... dic_entry_N # <<< empty line + \n ``` ### Speeding it up: For testing purposes, if you change from `I,*S=iter(input,'')` to `I=input();S=set(iter(input,''))`, the runtime will be reduced drastically and the output will be the same. ### Explanation: In every permutation of the input, it tries to split recursively the permutation in all possible locations, starting from left to right, without skipping letters, with words that are in the dictionary. If a split combination matches all the input permutation, the split words are sorted and added to a `set` that will be printed at the and of the evaluation. [Answer] # Javascript, ~~139~~ ~~137~~ 129 Bytes -2 Bytes thanks to @FelipeNardiBatista -8 Bytes thanks to reading the docs ;) ``` k=>w=>{t=w;return k.reduce((a,v)=>{r=([...v].every(c=>w.includes(c)&&((w=w.replace(c,""))||!0)))?a.concat(v):a;w=t;return r},[])} ``` Takes in the dictionary as input in form of an array of strings. ``` var arr = ["living", "code", "golf", "highway", "high", "way"]; var _= k=>w=>{t=w;return k.reduce((a,v)=>{r=([...v].every(c=>w.includes(c)&&((w=w.replace(c,""))||!0)))?a.concat(v):a;w=t;return r},[])}; console.log(_(arr)("viinlg")); console.log(_(arr)("fceodglo")); ``` **Explanation:** For every word in dictionary, check if every letter is contained in the chosen word, while simultaneously removing it from the word. At the end of every dictionary entry, restore the word to its unaltered state to check for further matches. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 82 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10.25 bytes ``` ð+Þ×vṠ'sṠ⁰s= ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9aiIsIiIsIsOwK8Oew5d24bmgJ3PhuaDigbBzPSIsIiIsIltcInRoZVwiLFwib2ZcIixcImFuZFwiLFwidG9cIixcImFcIixcIml0XCIsXCJub3RcIixcImxpdmluZ1wiLFwiY29kZVwiLFwiZ29sZlwiLFwiaGlnaHdheVwiLFwiaGlnaFwiLFwid2F5XCIsXCJlbmRcIl1cbmFod2h5Z2kiXQ==) Makes sure to output all acronyms with a single space to separate. [Answer] # [Scala](https://www.scala-lang.org/), 156 bytes Golfed version. [Try it online!](https://tio.run/##hZDBTsMwDIbve4qoJ1uLqsGxqJO4D3GYOCGE0jTpzEILTrYxTX324lBNghO5/Lbz5UuUaE0w09C8OZvUg6FeXRZKtc6rd2nAcBcrdc9szs/bxNR3L1ipp56SqoU8mqA8heR43owynSBUW/d5xfW@mius16GcYTjV61Pph9BunE8Ae5344BAv1kQHwLpBbYXPeqq5pL51X48eLN6RB1rXKwQu46GJP2ZYacLl7wEtb1AkLoiOtTeSOJavtzgpWVlrmOWtG4oJikBHOVRoVdihdTm7IficO@p2J3O@ljlzi4us@ZCrUujhzwfIj7FQR6I@dAX@T3rrhrYLw8yOi3H6Bg) ``` (l:Seq[String],k:String)=>l.filter(w=>w.foldLeft((k,true)){case((r,b),c)=>val i=r.indexOf(c);if(i>=0)(r.substring(0,i)+r.substring(i+1),b)else(r,false)}._2) ``` Ungolfed version. [Try it online!](https://tio.run/##dVHBasMwDL3nK0QPxaYhdDsGWujOHTuMncYYbiKnWr142G7aUPLtmZ00aQbdxbKsp6dnPZsJJdpW774wc/AsqIRLBJCjhG@fMGEKm8LGGFG/vzpDZfHBU3grycGqQwJUQoEwxudbso7NFFUeNothlukcQyy0kiHuqdifRD1cQwwpjzqeMDPbY3bYVIKU2JEiVzPrTAr95BgOWJ@0yYcHr@RJa4WiHMXAgEmkVvkWpWOBIgZnjsg5XCATFoExg@F/HatBe1SOx346h9X6ytN/jPKz5x7BCZU5nl8k89ARRxJYwK1XsORwY07scWc7oWwZByYOC7hXDc0LeOCDFJjPe73jCFRB9ESzFP5lqDfJ52N3bW6blKQcms4Rb07aeTM4eG@R0/pkm7436alYaPDruePRlS2GcHI@lfLjCZ0q2V853viKqFTF7Ir@FyYz1HmhdA9soiZq218) ``` object Main { def main(args: Array[String]): Unit = { val arr = List("living", "code", "golf", "highway", "high", "way") def checkAvailability(str: String, keyword: String): Boolean = { keyword.foldLeft((str, true)) { case ((remaining, result), ch) => val idx = remaining.indexOf(ch) if (idx >= 0) (remaining.substring(0, idx) + remaining.substring(idx + 1), result && true) else (remaining, false) }._2 } def filterList(arr: List[String], keyword: String): List[String] = { arr.filter(word => checkAvailability(keyword, word)) } println(filterList(arr, "viinlg")) println(filterList(arr, "fceodglo")) } } ``` [Answer] # [Elixir](https://elixir-lang.org/), 188 bytes Golfed version. [Try it online!](https://tio.run/##dVCxagMxDN3vK8RNNigHXQNJpw4dQoeOpYNjy46Jzz50d7mWkG@/ymk61iCepPf0LEQpfkVeHfm@uDkRHEzM4EoDID3guRar3/msEp71Zv@S577zMU3E0vEZls2eEvXqTjC52ZJ6nzjm0AU2w4l6GtWi8XrGiWe61RmLV8bjbbOPHh5aW/IkX4/PitFqdGUL1wfFNCQjrkJg22JI5WjSFrxJI2mxQZJE5Iz31o2y0/ikK0isIM8www4@2hQv4tgitLY4qhhK8hVPMZwW8/2XVqzlZ1PHX986WW0gOynfKTET9hJjTqHV@l@Ft1ScbPurkVWaGk29cCeHXX8A) ``` f=fn(l,k)->Enum.filter(l,fn w->elem(Enum.reduce(String.graphemes(w),{k,true},fn c,{r,b}->if String.contains?(r,c),do: {String.replace(r,c,"",global: false),b},else: {r,false}end),1)end)end ``` Ungolfed version. [Try it online!](https://tio.run/##jVI9T8MwFNz7K06ZbMlEYkUCJgYGxMCIUOXaL6lVJ67spAVV/e3h2W1ou@Hlfd2dzx/k3beL02Sp6YIdPeFNux42LADuIY7nAmicHygu0xBd3yY8oukhfBoUNhJ3TwUDvPRjV5@gpyGj9pcxwHzmFlgkOxoSH0WxbqPerqmjJPZS4bBRGOJIx6JguBEVVsdrJcDoRDjTTegHtp6eBQONnF3PK2sxGYczPNLWa948gxWqSqH1YaX9AxrtE8m82Y3AsrAZXubXM@rt4iqXl8JTJ/i8Cvdz82@eSSXRMd/HZ@Xdjn2xj8oESzm2wTc5rl273uufOc0xl1@F/vpe86G3ZAZx@0C1YGWG7pzrfVtJ@T94YyhYvooTIbssTvOvqPkzTNMv) ``` defmodule Main do def run do filter_strings = fn (lst, k) -> Enum.filter(lst, fn w -> str = Enum.reduce(String.graphemes(w), {k, true}, fn c, {r, b} -> case String.contains?(r, c) do true -> {String.replace(r, c, "", global: false), b} _ -> {r, false} end end) elem(str, 1) end) end arr = ["living", "code", "golf", "highway", "high", "way"] IO.inspect(filter_strings.(arr, "viinlg")) IO.inspect(filter_strings.(arr, "fceodglo")) end end Main.run ``` [Answer] # [Erlang(escript)](https://tio.run/##hY8xa8MwEIX3/ArhSQLZpWtLAknGZPKSwRijWidHcJaMLKctxvnr6clp5wrEu7vvPXGCgMp1OYxtsEN85L3XEwLvlXWi2OTwNfgQeZX6l9daFA/Dz/Ik8h3aMY5vxmKEwM3k@IWGcyMPy/YXedS4kqOcS7lfiLdqBPbEPfQflDzKUnjDYpiA4k@kASHCiij23hAopVE4wgJOM7pyPskUWeRFyMM6YWdaLq3JG8Hy3YbR2YfAtqzK0N6s6zLJstZrSNp5NEmvtrt@qu@/Mmlqa7nmradfhF5Fnt2HuyNaGU6PkutmrcMuE7X412pa8LpDn8zF4wc), 156 bytes Golfed version. [Try it online!](https://tio.run/##hY8xa8MwEIX3/ArhSQLZpWtLAknGZPKSwRijWidHcJaMLKctxvnr6clp5wrEu7vvPXGCgMp1OYxtsEN85L3XEwLvlXWi2OTwNfgQeZX6l9daFA/Dz/Ik8h3aMY5vxmKEwM3k@IWGcyMPy/YXedS4kqOcS7lfiLdqBPbEPfQflDzKUnjDYpiA4k@kASHCiij23hAopVE4wgJOM7pyPskUWeRFyMM6YWdaLq3JG8Hy3YbR2YfAtqzK0N6s6zLJstZrSNp5NEmvtrt@qu@/Mmlqa7nmradfhF5Fnt2HuyNaGU6PkutmrcMuE7X412pa8LpDn8zF4wc) ``` f(L,K)->lists:filter(fun(W)->{_,B}=lists:foldl(fun(C,{R,A})->case lists:member(C,R)of true->{lists:delete(C,R),A};_->{R,false}end end,{K,true},W),B end, L). ``` Ungolfed version. [Try it online!](https://tio.run/##lVGxboMwEN35CovJSCZV11atlHRMpiwZEELUPhNLxka2SVsh8uvUjgtVki59y/Hu7t2zHmBkrZocLDWic9OUt5r1EnBbC5Wtkhw@O20cLgJ/eCx9K@FCOjCVdUaoxuIdQdsM5a8J8pDCOvsUNzDvFT4so4ChImgzopd5T0sm8TINCJo3goY9QWtKxyv1DFpb@LnQQvvunbxinyHN71YDnOnBn0FDlDCQ4CBKosnznzJeSxt1/i0XMt7tgWLJDSdXjWFLLv7jdfuwsOx3sEnmE2gXcg6R42pJYG2MD65IpTj53FOCUqoZhNpoyUM9iub4UX/Nn6EGWkYLoX3epq0dTs/dWflpcfMnvYOXnIRQskmzMvufjlPQrJE6KFfJNH0D) ``` -module(main). -export([main/1]). filter_strings(L, K) -> lists:filter(fun(W) -> {_, B} = lists:foldl( fun(C, {R, Acc}) -> case lists:member(C, R) of true -> {lists:delete(C, R), Acc}; false -> {R, false} end end, {K, true}, W ), B end, L). main(_) -> Arr = ["living", "code", "golf", "highway", "high", "way"], io:format("~p~n", [filter_strings(Arr, "viinlg")]), io:format("~p~n", [filter_strings(Arr, "fceodglo")]). ``` [Answer] # [OCaml](http://www.ocaml.org/), 224 bytes Golfed version. [Try it online!](https://tio.run/##tVC7bsMwDNz7FYQmCbWCJmthf0HRJWPRGI5N2TQUKbXo2AHy76mUuOhj76IjT3cHkr6uDvZ6tchgIADnLxR4ZcgyDtKMDiZd3Clvm9Ki4cTKOTurWhfJRvmWB3LtilyDc@mPDDPUQA4OFdcdEEzEHWz9AaHXxSIO4z7KnqDf/SRk/7hWIBfKomujc9a9XqvsfHn1DnUxZ6ayAZXkjIcx4qJmXwb8gOlyn9eb1KpLEVyjwm1BqSB/AEhlNQyQw5uwdIpe8Qyi9g0mbL01CTtqu6k6f5UJU/seF1syBgyj5XXMMbc8cSJythV/FZtvhanRN631i@YYB@cSXWPJIcjfd4bb@SvYgy6AYkCMEQK4Qxc5jCeI1A5EJuK7V@lvmUg9/1v2Rl0/AQ) ``` let f s t=List.filter(fun w->List.fold_left(fun(x,y)c->let i=String.index_opt x c in match i with Some j->String.sub x 0 j^String.sub x(j+1) (String.length x-j-1),y|None->x,false)(t,true)(String.to_seq w|>List.of_seq)|>snd)s ``` Ungolfed version. [Try it online!](https://tio.run/##tVLLbsIwELzzFSsfIFYDKlwRfEHVC8eqRCGxEwtj09gBKvHv6a6dgETbIxe8mZmdfWGL/KC7TgsPUmkvmsz5RpnKgXYeMIbVCIDoRhSDpKjzxgWSoqCIGgUr2IT8mTKluGT26O86ZYLwkPuiRulZ@ToAV9jYgwBVXmC6HvJduwuZrwHfPsIJoS8w55D0jBam8nUgp9EL2RR804q@yrs1giqgJAWZa0dEaOpNOT@Lw0EiWwNn25QovQ2WpWD3OFwUWl1mWkgftUnw23EoyJzUCEwQmWDC741hxUEA4zGqeO9And7H8TZz4is2cl3HwlYSxodF2j2nK41GVDPht0vlDd4EPphWJ3RiS2CFLQW9ldWS3lpV9Tn/HkJ66fMzOsdru1b7@X2C4W9B5uyklNEVe5Qv/pHLQtiy0rZPOCLlM2FKrfAgyV87zXE5uEwlMVoBY@BrYRATeDSEtsBShr@4dOT6Xvnyad4L3nU/) ``` let filter_strings lst str = let rec filter_chars str char = let i = String.index_opt str char in match i with | Some idx -> String.sub str 0 idx ^ String.sub str (idx + 1) (String.length str - idx - 1), true | None -> str, false in List.filter (fun word -> let _, ok = List.fold_left (fun (str, b) c -> let str', b' = filter_chars str c in str', b && b') (str, true) (String.to_seq word |> List.of_seq) in ok) lst let () = let arr = ["living"; "code"; "golf"; "highway"; "high"; "way"] in let result1 = filter_strings arr "viinlg" in let result2 = filter_strings arr "fceodglo" in print_endline (List.fold_left (fun a b -> if a = "" then b else a ^ "," ^ b) "" result1); print_endline (List.fold_left (fun a b -> if a = "" then b else a ^ "," ^ b) "" result2) ``` [Answer] # [Racket](https://racket-lang.org/), 299 bytes Golfed version. [Try it online!](https://tio.run/##dVBBboQwDLz3FRYc6rSqtPuAlocgDiEkIcIybJIF7dv6h35paxaQ2kr1xfY445k4ajPYfC9Js4e4NdhZF9higARGIdkMDmvClGNg//ZBIWVIqqkZTo3C4JCvRBWQKt3amV7H9wqNjgIZxShQt9b4Cmdg9YinQ8UBwaDQBco24tcnLpukxzrC0NQtlLn5q76o38LtSnnB2uyq4k3sR7G/vxsz2stcAUPplEJ/rNPTZLnDdG03QDgnsfgTENcMZ7Hc7t9Q6woJqY5bgY4RnrGgMAungMKMnZXkR3KS@uD7Rd/2StLaPG4Q0kT6Rgxyh3VHMYfA5P8ZOmPHztMo4/s3) ``` (define(i s c)(let f([l(string->list s)][n 0])(if(null? l)#f(if(char=?(car l)c)n(f(cdr l)(+ 1 n)))))) (define(f l k)(filter(λ(w)(let g([r k][b #t][l(string->list w)])(if(null? l)b(let*([c(car l)][n(i r c)])(if(not(eqv? n #f))(g(string-append(substring r 0 n)(substring r(+ n 1)))b(cdr l))#f)))))l)) ``` Ungolfed version. [Try it online!](https://tio.run/##jVHbbsIwDH3nK6zysHgTEnzAxodUeUiTtER4SZcUOr6@c5uqAwbS8uLYPuf4FpU@2m4Y1qR8A3HyVithbO28BZG66Hyzcd7Yb0igcQUgyHZAIbQgyrQhl7oF9zF5CSWUmbKVI4M5Ongz/QBK4U9Ee8hchHUtl4w@qPi@Z7iKS14jTGILylLi1nIH2vwCxRvsMhRRIuLVHLWjzsZNbjMBwXGaJIdZS31WRoHoca6R3/WkEY48VQXrjk1PdyP3KG@pTHY1zJP2dJ8cX/UgNlZ85Wo6r4CJ8gFqfqW7O1DkXUl8SMjdBD6V/TrvwfHWEZ9Kz8udxVXbWm/YPVU5woW24PA2wtt3sOO1Q5XPws0/rzCWH7F0fSYVI7yIgtyZJQsodDCWTROoZnNwzaFXl/nHZnSYLoxLLakL@T93HgWLs3Oemv8ga22DaSgwdhh@AA) ``` #lang racket (define (string-index s c) (let loop ([s-list (string->list s)] [index 0]) (cond [(null? s-list) #f] [(char=? (car s-list) c) index] [else (loop (cdr s-list) (+ 1 index))]))) (define (filter-strings l k) (filter (lambda (w) (let loop ([r k] [b #t] [wl (string->list w)]) (if (null? wl) b (let* ([c (car wl)] [i (string-index r c)]) (if (not (eqv? i #f)) (loop (string-append (substring r 0 i) (substring r (+ i 1))) b (cdr wl)) #f))))) l)) (define arr '("living" "code" "golf" "highway" "high" "way")) (displayln (filter-strings arr "viinlg")) (displayln (filter-strings arr "fceodglo")) ``` [Answer] # [F#(.NET Core)](https://www.microsoft.com/net/core/platform), 171 bytes Golfed version. [Try it online!](https://tio.run/##bY/NasMwEITveYpFUJCgNuSatIEcC4VAcyw9qPKuvWQtJbJsN5B3dyVDbz3NDvPtHw2VCxGXcEUP5/uQsN8sggkIBPRlN6TIvjXwmu3jAO88pJpYEkZNo4cZqgMUvB@T/RaEmMkLcEkyfsZbTSFakZXWbuc6G01p6m1yHcT6zTf4cyLtDMycOnhAtS05WRkwOy4mwkuV2Q/sw4San7dmDymOaMx6q41l7acSnvKxag/KhQaLtkGoaMdtN9v7X1m02K/NNb@XyIN6OirQtI5SE7OXVpn/U3IYmlaCMssv) ``` let f l (k:string) = l |> List.filter(fun w -> let mutable r = k in w |> Seq.forall(fun (c:char) -> match r.IndexOf(c) with | -1 -> false | i -> r <- r.Remove(i,1); true)) ``` Ungolfed version. [Try it online!](https://tio.run/##hZFPS8QwEMXv/RSPgJCAXfSqbsGjIAjuUTz0z6QNmyZLkrYu@N1r0mVXi4Jzmcn83pswifR5bR3Nsz2Qwe7oA/VZpilAKh3I7YJTpvXg@g5@qaGVDwJ8f24IbJEhhsZngedINycvl4MBn751ebHoFm28oR9CWWmCiwP2f5IqkuAGukBpHWoogwmNvXTPNhXlbvNkGvp4kbwWK4GSkRdb3CB0ZFYohcNDHs2v1NuRuLrG7dpO2tMvU5VMsvyJKnF6vtKltd6YVmPcnd2D1bahlFurZcqdarupPJ7LlNPxPTvE1wrSgF09MvD1P6SxbFTK6JaJ/5WyJtu02jIxz18) ``` open System let filterStrings (l: string list) (k: string) = l |> List.filter(fun (w: string) -> let mutable r = k let mutable b = true for c in w do let i = r.IndexOf(c) if i >= 0 then r <- r.Remove(i, 1) else b <- false b) let arr = ["living"; "code"; "golf"; "highway"; "high"; "way"] printfn "%A" (filterStrings arr "viinlg") printfn "%A" (filterStrings arr "fceodglo") ``` ]
[Question] [ Given two numbers, print a page with an "X" in the specified location (±10%). The numbers must be either percentages or fractions of the page's print area dimensions, e.g. `[25,75]` or `["15%","0%"]` or `[0.33,1]`. You do not have to consider margins. Just remember to state which number is width, and which is height, and which corner is the origin. You may of course assume that a printer is connected, and any [virtual printer](https://en.wikipedia.org/wiki/Virtual_printer) counts too. In fact, you may want to set a PDF printer as your default printer before beginning this challenge. You may create a printable file (e.g. a PDF) and send that to a virtual printer, which in turn creates your result PDF, but you may not directly create the final PDF. This has to be a proper print job. If possible, please include a photo, scan, or screenshot of the result, or link to an online document. Note that Imgur accepts PDFs. You will of course get more upvotes if you actually place an X rather than outputting newlines and spaces with an assumed font and paper size. ### Example For input height 75% and width 25%, from top left, print the following document: --- [![[25,75]](https://i.stack.imgur.com/rfZeO.png)](https://i.stack.imgur.com/rfZeO.png) --- [Answer] # MacOS Bash + OfficeJet Pro 8600, 46 ``` (yes ''|sed $[$2*3/5]q;printf %$[$1*4/5]sX)|lp ``` Origin is the top-left corner. I did a test print to check the character dimensions of what gets printed by `lp` to my printer - it appears to be 82w x 64h, so (integer) multiplying percentages by 3/5 and 4/5 respectively gets within the 10% tolerance. ### Result, with command-line input of `25 75`: [![enter image description here](https://i.stack.imgur.com/I81Aj.jpg)](https://i.stack.imgur.com/I81Aj.jpg) [Answer] # [APL (Dyalog)](https://www.dyalog.com/) on Windows, ~~36~~ 35 bytes Anonymous function taking (Y,X) in percent from top left as argument ``` {'X.'⎕WC'Text'(2↓'X'⎕WC'Printer')⍵} ``` We begin with a list of three elements: `{` an anonymous function (all variables are local)  `⍵` the argument, e.g. `75 25`  `(` to the right of   `'X'⎕WC'Printer'` **W**indows **C**reate a Printer object named *X*, returning `'#.X'`   `2↓` drop two characters to get just `'X'`  `)` to the right of  `'Text'` what we will add  `'X.'⎕WC` **W**indows **C**reate a (type, content, position) object in the object *X*, returning `'#.X'` `}` end of function (since *X* is local, it is destroyed when the function terminates, signalling to Windows that we are done with the print job, which causes Windows to print it) --- ## [X @ 75 25](https://i.stack.imgur.com/QNXgD.png) [Answer] # Java 8, ~~210~~ 209 bytes *-1 byte: changed to currying syntax* ``` import java.awt.print.*; x->y->{PrinterJob j=PrinterJob.getPrinterJob();j.setPrintable((g,p,i)->{g.drawString("X",(int)(p.getWidth()*x),(int)(p.getHeight()*y));return i;});try{j.print();}catch(Exception e){}}; ``` Takes input as floating-point version of percent: `0.25, 0.75`. ### If paper size can be assumed as 8.5x11in (72dpi), 184 bytes ``` import java.awt.print.*; x->y->{PrinterJob j=PrinterJob.getPrinterJob();j.setPrintable((g,p,i)->{g.drawString("X",x*612/100,y*792/100);return i;});try{j.print();}catch(Exception e){}}; ``` Uses default values for printing to PDF. Now takes input as integer version of percent: `25, 75`. ### If a Windows OS can also be assumed, 177 bytes ``` import sun.awt.windows.*; x->y->{WPrinterJob j=new WPrinterJob();j.setPrintable((g,p,i)->{g.drawString("X",x*612/100,y*792/100);return i;});try{j.print();}catch(Exception e){}}; ``` Same inputs as above: `25, 75`. ## Usage ``` import java.awt.print.*; ... Function<Double, Consumer<Double>> f = x->y->{PrinterJob j=PrinterJob.getPrinterJob();j.setPrintable((g,p,i)->{g.drawString("X",(int)(p.getWidth()*x),(int)(p.getHeight()*y));return i;});try{j.print();}catch(Exception e){}}; ... f.apply(.25).accept(.75); ``` ## Test Case For input of `0.25, 0.75`: `[![Java Printing Test Case](https://i.stack.imgur.com/WkG9N.png)](https://i.stack.imgur.com/WkG9N.png)` (I don't have a physical printer, but this *should* still work without issue) [Answer] # C#, ~~259~~ ~~202~~ 201 bytes ``` namespace System.Drawing.Printing{w=>h=>{var p=new PrintDocument();p.PrintPage+=(s,e)=>e.Graphics.DrawString("X",new Font("Onyx",9),Brushes.Red,e.PageBounds.Width*w,e.PageBounds.Height*h);p.Print();};} ``` Onyx is a font installed on my Windows 10 machine by default where 4 seems to be the shortest font name. I tested that by running the following in C# and then inspecting `blah` in the debugger. ``` var blah = FontFamily.Families.GroupBy(o => o.Name.Length) .OrderBy(g => g.Key); ``` Full/formatted version: ``` namespace System.Drawing.Printing { class P { static void Main(string[] args) { Func<float, Action<float>> f = w => h => { var p = new PrintDocument(); p.PrintPage += (s, e) => e.Graphics.DrawString("X", new Font("Onyx", 9), Brushes.Red, e.PageBounds.Width * w, e.PageBounds.Height * h); p.Print(); }; f(0.25f)(0.75f); } } } ``` Test case (0.25, 0.75): --- ## [Example document](https://i.stack.imgur.com/WClzU.jpg) ]
[Question] [ Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think). A digit is a sig-fig if at least one of the following apply: * Non-zero digits are always significant. * Any zeros between two significant digits are significant. * final zero or trailing zeros in the decimal portion only are significant. * all digits are significant if nothing follows the decimal place. * when there are only zeroes, all but the last zero are considered leading zeroes ## Input A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all. ## Output How many sig-figs there are. ## Examples ``` 1.240 -> 4 0. -> 1 83900 -> 3 83900.0 -> 6 0.025 -> 2 0.0250 -> 3 2.5 -> 2 970. -> 3 0.00 -> 1 ``` [Answer] # Retina, ~~29~~ 27 bytes *Saved 2 bytes thanks to @MartinEnder* ``` ^0\.0*.|^\d(\d*?)0+$ 1$1 \d ``` [**Try it online!**](http://retina.tryitonline.net/#code=XjBcLjAqLnxeXGQoXGQqPykwKyQKMSQxClxk&input=MS4yNDA) | [**Test suite**](http://retina.tryitonline.net/#code=JShgXjBcLjAqLnxeXGQoXGQqPykwKyQKMSQxClxk&input=MS4yNDAKMC4KODM5MDAKODM5MDAuMAowLjAyNQowLjAyNTAKMi41Cjk3MC4KMC4wMA) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes ``` D.ïi0Ü}þïg ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RC7Dr2kww5x9w77Dr2c&input=MC4wMjUw) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHZ5eS7Dr2kww5x9w77Dr2cs&input=MS4yNDAKMC4KODM5MDAKODM5MDAuMAowLjAyNQowLjAyNTAKMi41Cjk3MC4) **Explanation** ``` D # duplicate .ïi } # if it is an integer 0Ü # remove trailing zeroes þ # remove the "." if present ï # convert to int g # length ``` [Answer] ## Batch, ~~204~~ 202 bytes ``` @set/ps= :t @if %s:.=%%s:~-1%==%s%0 set s=%s:~,-1%&goto t @set s=%s:.=% :l @if not %s%==0 if %s:~,1%==0 set s=%s:~1%&goto l @set n=0 :n @if not "%s%"=="" set/an+=1&set s=%s:~1%&goto n @echo %n% ``` Takes input on STDIN. Works by removing trailing zeros if the number does not contain a `.`, then removing the `.` and leading zeros, unless there are only zeros, in which case it leaves one zero. Finally it takes the length of the remaining string. [Answer] # Scala, 90 bytes ``` & =>(if(&contains 46)&filter(46!=)else&.reverse dropWhile(48==)reverse)dropWhile(48==)size ``` Explanation: ``` & => //define an anonymous function with a parameter called & ( if(&contains 46) //if & contains a '.' &filter(46!=) //remove all periods else //else &.reverse //reverse the string dropWhile(48==) //remove leading zeros reverse //and reverse again ) dropWhile(48==) //remove leading zeros size //return the length ``` [Answer] # C#6, 163 bytes ``` using System.Linq; int a(string s)=>System.Math.Max(s.Contains('.')?(s[0]<'1'?s.SkipWhile(x=>x<'1').Count():s.Length-1):s.Reverse().SkipWhile(x=>x<'1').Count(),1); ``` Ungolfed ``` int a(string s)=> System.Math.Max( s.Contains('.') // Has decimal place? ?( // Has decimal place! s[0]<'1' // Start with '0' or '.'? ?s.SkipWhile(x=>x<'1').Count() // Yes: Skip leading '0' and '.', then count rest... But gives 0 for "0." and "0.00" :s.Length-1) // No: Count length without decimal place :s.Reverse().SkipWhile(x=>x<'1').Count() // No decimal place: Skip trailing '0' and count rest ,1); // For "0." and "0.00" ``` ]
[Question] [ Being a Haskell hacker, I prefer pointfree notation over pointful. Unfortunately some people find pointfree notation hard to read, and I find it hard to get the correct number of parentheses when I write in pointful. Help me convert code written in pointfree to pointful notation! ## About In pointfree notation we use points (yes, really) to feed the output of one function into another. Say, if you had a function `succ` that takes a number and adds 1 to it, and you wanted to make a function that adds 3 to a number, instead of doing this: ``` \x -> succ(succ(succ(x))) ``` you could do this: ``` succ.succ.succ ``` Pointfree only works with functions that take a single parameter however (in this challenge anyway), so if our function wasn't `succ` but rather `add` which take 2 numbers and adds them together, we would have to feed it arguments until there is only one left: ``` pointful: \x -> add 1(add 1(add 1 x)) pointfree: add 1 . add 1 . add 1 ``` Lastly, functions may take other functions as arguments: ``` Pointfree: map (f a . f b) . id Pointful: \x -> map (\x -> f a (f b x)) (id x) Javascript equivalent: x => map (x => f(a,f(b,x)), id(x)) ``` ## Input and expected output ``` f . f . f \x -> f (f (f x)) f a . f b . f c \x -> f a (f b (f c x)) f (f a . f b) . f c \x -> f (\x -> f a (f b x)) (f c x) a b c . d e . f g h i . j k l . m \x -> a b c (d e (f g h i (j k l (m x)))) a.b(c.d)e.f g(h)(i j.k).l(m(n.o).p) \x->a(b(\y->c(d y))e(f g h(\z->i j(k z))(l(\q->m(\w->n(o w))(p q))x))) ``` ## Rules * Your output may have more spaces or parentheses than required, as long as they are balanced * You don't have to make sure that the name of the variable you create `\x` isn't already used somewhere else in the code * It is your choice whether to create a function or a full program * This is `codegolf`, shortest code in bytes win! You might find blunt useful, it converts between the two notations (but also factorizes the code when possible): <https://blunt.herokuapp.com> [Answer] # Haskell, ~~163 142~~ 133 bytes ``` p(x:r)|[a,b]<-p r=case[x]of"("->["(\\x->"++a++p b!!0,""];"."->['(':a++")",b];")"->[" x)",r];_->[x:a,b] p r=[r,r] f s=p('(':s++")")!!0 ``` [Try it on Ideone.](http://ideone.com/tbgKLY) Ungolfed: ``` p('(':r)|(a,b)<-p r = ("(\\x->"++a++(fst(p b)),"") p('.':r)|(a,b)<-p r = ('(':a++")", b) p(')':r) = (" x)", r) p(x :r)|(a,b)<-p r = (x:a, b) p _ = ("", "") f s=fst(p('(':s++")")) ``` [Answer] # Haskell, ~~402~~ 289 bytes Quite long, but I think it works.. ``` (!)=elem n%'('=n+1 n%')'=n-1 n%_=n a?n=a!"."&&n<1 a#n=a!" ("&&n<1||a!")"&&n<2 q a='(':a++")" p s o n[]=[s] p s o n(a:b)|o a n=[t|t@(q:r)<-s:p""o(n%a)b]|0<1=p(s++[a])o(n%a)b k=foldr((++).(++" ").f)"".p""(#)0 f t|not$any(!"(. ")t=t|l@(x:r)<-p""(?)0t=q$"\\x->"++foldr((.q).(++).k)"x"l|0<1=k t ``` ]
[Question] [ # Introduction You are sitting with your coworker, having lunch, and bragging to him/her about the latest and supposedly greatest project you've been working on. Getting sick and tired of your constant showcase of egoism, he/she gives you a challenge just so you'll shut up. Being the egoistic and happy-go-lucky person you are, you of course accept (because you *must* accept each and every challenge). The **challenge**, as he/she explains it is, given an **input** of a block of text containing 1 or more of each character in `!@#$^&*`, **output** in any reasonable format the coordinates of the switch(es) that is/are "on". According to your coworker, a switch is a `$`, and a switch is classified as "on" if and only if it satisfies at least 1 of the following criteria: 1. It is surrounded by all `^`. So... ``` ^^^ ^$^ ^^^ ``` results in an "on" switch. 2. It is surrounded by all `&`. So... ``` &&& &$& &&& ``` results in an "on" switch. 3. It is completely covered on at *least* two sides with `*`. For instance, ``` *** &$& *** ``` results in an "on" switch, but ``` &*& &$& &*& ``` does not, since the switch is not *completely covered* on any two sides by `*`s. 4. There is at least 1 `!` and/or 1 `@` in any of the corners around it. This does *not* count if either of these are *not* in a corner. So... ``` !&& ^$@ @&! ``` results in an "on" switch, since there is at least 1 `!` and/or `@` in at least 1 of the corners (in the above case, there are 2 valid `!`s and 1 valid `@` in 3 corners). And... ``` &!& ^$@ ^!& ``` does *not*, although there are 2 `!`s and 1 `@`, since none of them are in *any* of the corners. 5. 1 or more `#` are *not* on *any* sides around the switch, unless at least 1 `&` surrounds the switch. In other words, if there is at least 1 `#` present on a side, it overrides all other rules, unless there is also a `&` present. Therefore: ``` #&* *$* !** ``` results in an "on" switch, although a `#` exists, since there is an `&` around the switch, and it follows at least 1 of the above rules. However, if the exclamation point were not present like so: ``` #&* *$* *** ``` The switch would be off, since it does not follow at least one of the above rules. Therefore, even though a switch may be surrounded by a `#` and a `&`, it would still be off unless it follows one or more of these rules. Also, there must *always* be a >=1:1 ratio between `&`s and `#`s for the switch to be valid. For instance, ``` #&! *$* **# ``` would still be an invalid switch, although it follows 1 of these rules, since there are 2 `#`s, but only 1 `&`, and therefore not a >=1:1 ratio between `&`s and `#`s. To make this valid, you must add 1 or more additional `&`s to any edge in order balance the number of `#`s and `&`s out, possibly like so: ``` #&! *$& &*# 3:2 ratio between &s and #s ``` Finally... ``` #^^ ^$* @^! ``` results in an "off" switch, although it follows 1 or more of the above rules, since it contains *at least* 1 `#` around it, and no `&`s to outbalance it. 6. The valid switches will *only* be *inside* an input, and therefore, each valid `$` must be surrounded *completely* by any 8 of the valid characters. For instance, if the entire input were to be: ``` *$* !$! !!! ``` the top `$` is definitely *not* a valid switch since the switch is on an edge, and therefore the switch is not completely surrounded by 8 valid characters. In this instance, the switch should not even be considered. However, the switch in the middle is completely valid, and as a matter of fact is "on", since it meets at least one of the above requirements. To demonstrate, consider this block of characters: ``` !@#^^$#!@ !@#$$*$&@ @$^!$!@&& ``` which we can label for coordinates like so, calling the vertical axis `y` and the horizontal axis `x`: ``` y 3 !@#^^$#!@ 2 !@#$$*$&@ 1 @$^!$!@&& 123456789 x ``` The coordinates must *always* be returned in an `(x,y)` format, similar to a two-dimensional coordinate grid. Now, which switches are on? Well, let's first find them all. We can already see that there is 1 in the very top row, and another in the very bottom. However, those are automatically no-ops, since they are not completely surrounded by 8 characters. Next comes the one in row 2. Specifically, this one: ``` #^^ #$$ ^!$ ``` We can see that there are 3 `$` signs in this, but we just want to focus on the one in the middle, and, as you can probably see, it is already invalid, since it has 2 `#`s around it with no `&`s to balance them out. Additionally, this does not even follow any of the rules, so even if it was a valid switch, it would be "off" anyways. Next comes another one in row 2: ``` ^^$ $$* !$! ``` Again, only focus on the switch in the middle. This switch is "on", since it has *at least* 1 `!` in *at least* 1 corner. The coordinates of this one are `(5,2)`. Moving on, we finally move onto the last switch. This one is also in the second row and appears like so: ``` $#! *$& !@& ``` and, as you can probably see, this one is also a valid switch, although there is a `#` surrounding it, since there are 2 other `&`s to outbalance the `#`. In addition to that, it also has at least 1 `!` in at least 1 of the corners, and therefore not only is the switch valid, but it's also "on". The coordinates of this switch are `(7,2)`. We have finally reached the end, and have found 2 "on" switches in that entire block on text. Their coordinates are `(5,2)` and `(7,2)`, which is our final answer, and what the output should be. However, this input was very simple. Inputs can get *a lot* bigger, as there is not limit on how big the block of text can get. For instance, the input could even be a randomized `200x200` block of text. # Contraints * Standard Loopholes are prohibited. * There can't *possibly* be a built-in for this, but just in case there is (looking at you Mathematica), the use of built-ins that directly solve this are prohibited. # Test Cases: Given in the format `string input -> [array output]`: ``` @#$$&^!&!# @*&!!^$&^@ $!#*$@#@$! -> [[7,3],[9,2]] *@^#*$@&*# #^&!$!&$@@#&^^&*&*&& !^#*#@&^#^*$&!$!*^$$ #^#*#$@$@*&^*#^!^@&* -> [[19,3],[15,3],[8,2]] #$@$!#@$$^!#!@^@^^*# @!@!^&*@*@ *$*^$!*&#$ @$^*@!&&&# **$#@$@@#! -> [[2,8],[5,8],[6,6],[9,3]] ##*&*#!^&^ $&^!#$&^&@ ^^!#*#@#$* $@@&#@^!!& #@&#!$$^@$ !!@##!$^#!&!@$##$*$# $^*^^&^!$&^!^^@^&!#! @*#&@#&*$!&^&*!@*&** -> [[9,4],[9,3]] ^!!#&#&&&#*^#!^!^@!$ &$$^*$^$!#*&$&$#^^&$ ``` More coming soon # Additional Notes * You can assume that the input will always be in the form of a complete block (i.e. a rectangle or square) * There will *never* be any other character in the input than those in `!@#$^&*`. Remember, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins! [Answer] # Haskell, 304 bytes ``` import Data.List s!c=sum[1|a<-s,a==c] f t|Just w<-elemIndex '\n't,h<-t!'\n'=[c|c<-mapM(\a->[2..a-1])[w,h],s<-[(\[x,y]->t!!((h-y-1)*(w+1)+x))<$>mapM(\a->[a-2..a])c],s!!4=='$',foldr1(-)((s!)<$>"#&")<1,or$("@!"/="@!"\\map(s!!)[0,2..8]):zipWith(\c i->all(==c)$(s!!)<$>[0..8]\\(4:i))"^&**"[[],[],[1,7],[3,5]]] ``` This defines the function `f` which performs the given task. [Answer] ## JavaScript (ES6), ~~363~~ ~~339~~ ~~312~~ ~~309~~ 298 bytes This is a function taking the input as a string and returning a list of coordinates. It's split into 2 main parts: a transformation of switches into a pair of coordinates and its surrounding characters, and a 'is it on' check based on the rules of the challenge on the surrounding characters. ``` a=>[...a].map((z,p,m)=>(y-=z==B,z)=='$'&&(r=m[p-n-2]+m[p-n]+m[p+n]+m[p+n+2]+m[p-n-1]+m[p-1]+m[p+1]+m[p+n+1],r=r[L]<9?r:'')[T]`&`[L]>=r[T]`#`[L]&&(/(\^|&){8}|\*{4}(.\*\*.|\*..\*)/.exec(r)||/!|@/.exec(r.substr(0,4)))&&[1+(p-(w-y))%n,y],y=w=a[T='split'](B='\n')[L='length'],n=a.search(B)).filter(e=>e) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~299~~ ~~297~~ ~~279~~ ~~275~~ ~~261~~ 259 bytes ``` m=input() R=range h=len(m) for y in R(h-2): for x in R(len(m[0])-2): a=''.join(m[y+o][x:x+3]for o in R(3)) if(a.count('&')>=a.count('#'))*(a[:4]+a[5:]in('^'*8,'&'*8)or'*'*6in(a[:3]+a[6:],a[::3]+a[2::3])or'!'in a[::2]or'@'in a[::2])*a[4]=='$':print x+2,h+~y ``` [Try it online!](https://tio.run/##RY3NaoQwEMfP61MYEjJmtEvR7bIIKfMMe5UEpOxWSzcRcUEvfXWbKLSXyfz@H5NhmTrvynV96N4NzylTyVWPrfu8JZ3@vrnsoZK7H9Ml7V16zbqXUtVJGpV5V7ZM82rU5hxaDXD88n0Ul9ybZq7nvDKx4PdCpVRy6O9Ze/zwTzdlIEG96z/ioBRmbVOfTN42b7UJp8ACXooQxIvyIyDgOaghU8XMuTZF2Hco4xtDDMJvUS5NIPonhW1zMlqDgHoYezelc14WXf6zrGsDxIhZiYQERQoo0AqGkotIJCwSk1LyzUPBSRBxFolzlMhD1UYS0jIehtyu2ADIiQvcPCLJyTImt14AJoQlAeYX "Python 2 – Try It Online") Takes input as a list of strings Prints the output as a pair of x,y coordinates on each line ]
[Question] [ Inspired by [Draw a timeline](https://codegolf.stackexchange.com/questions/73477/draw-a-timeline). Given a timeline of events, output the date for each event. A timeline will be given in the form ``` 2000 --AF-C-------E--D---B-- ``` Where the first line shows a known point in time. The known year is always the character below the first digit of the known year You may assume: * On the timeline itself, each character represents one year. * There will always be at least one event * The events don't have to be in order * You may assume every character in the range between `A` and the furthest character is present * There will be at most 26 events * The known point will not have any padding to the right * There can be negative numbers in both the known point and the output * You will not have to handle numbers bigger than 2^32 * You will not have to handle ranges bigger than 2^8 * You can take input as lowercase letters instead of uppercase You should write a program that takes a timeline in this form and outputs the key dates in order (A, B, C, D...) You may output in a convenient form but you must take input in the format given. Test cases: ``` 2000 --AF-C-------E--D---B-- [1998, 2016, 2001, 2012, 2009, 1999] 10 --C-AB--D [9, 10, 7, 13] 0 --ABCDEFG-- [-3, -2, -1, 0, 1, 2, 3] 5 --ABCDEFG-- [-3, -2, -1, 0, 1, 2, 3] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 18 bytes Code: ``` ð¢>UágF²N>.bkX-¹+, ``` Explanation: ``` ð¢ # Count the number of spaces before the year starts > # Increment by 1 U # Pop and store this into X á # Keep the alphabetic characters of the second input g # Take the length F # For N in range(0, length), do... ² # Take the second input N> # Push N and increment by 1 .b # Converts 1 to A, 2 to B, etc. k # Find the index of that letter in the second input X # Push X - # index - X ¹ # Get the first input, which contains the year + # Add to the difference of the index , # Pop and output the sum ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w7DCoj5Vw6FnRsKyTj4uYmtYLcK5Kyw&input=ICAgIDIwMDAKLS1BRi1DLS0tLS0tLUUtLUQtLS1CLS0) Uses **CP-1252** encoding. [Answer] # Pyth, 16 bytes Takes input as lowercase letters instead of uppercase. ``` VS@GJw+-sz/zdxJN ``` [Answer] # JavaScript (ES6), 72 ``` (a,b,r=[])=>[...b].map((x,i)=>r[parseInt(x,36)-10]=+a+i-a.search`\\d`)&&r ``` **Test** ``` f=(a,b,r=[])=>[...b].map((x,i)=>r[parseInt(x,36)-10]=+a+i-a.search`\\d`)&&r console.log=x=>O.textContent+=x+'\n' ;[[' 2000','--AF-C-------E--D---B--'], [' 10','--C-AB--D'], [' 0','--ABCDEFG--'], [' 5','--ABCDEFG--']] .forEach(t=>{ var a=t[0],b=t[1],r=f(a,b) console.log(a+'\n'+b+'\n'+r+'\n') }) ``` ``` <pre id=O></pre> ``` [Answer] # Bash + coreutils, 68 Line 1 is input as a quoted command-line option and line 2 is input from STDIN: ``` s="${1//[0-9]}" fold -1|nl -v$[$1-${#s}]|sort -k2|sed '/-$/d;s/.$//' ``` [Answer] ## Perl, 58 + 1 = 59 bytes ``` /\d/;$b=<>;for$c(A..Z){($z=index$b,$c)>-1&&say$_+$z-$-[0]} ``` Breakdown: ``` /\d/; # Match first digit in input string, this will set $-[0] $b=<>; # Read next line (--A--CB--...) into $b for $c (A..Z){ # Iterate over A, B, C, ... Z ($z=index$b,$c) >-1 && # If the character is found inside $b say $_+$z-$-[0] # then print } ``` Requires `-n` and the free `-M5.010`: ``` # Added line breaks for each test case $ perl -nE'/\d/;$b=<>;for$c(A..Z){($z=index$b,$c)>-1&&say$_+$z-$-[0]}' tl 1998 2016 2001 2012 2009 1999 9 10 7 13 -3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 $ cat tl 2000 --AF-C-------E--D---B-- 10 --C-AB--D 0 --ABCDEFG-- 5 --ABCDEFG-- ``` [Answer] ## Pyth, 22 bytes ``` V+r\AJeSKwJ+xKN-izT/zd ``` No I did not write this before I posted the challenge. Explanation: ``` - autoassign z = input() +r\AJeSKwJ - create range of letters Kw - autoassign K = input() eS - sorted(K)[-1] (get the biggest character) J - autoassign J = ^ r\A - range("A", ^) + J - ^ + J V - for N in ^: V -izT/zd - Get the number at the start izT - int(z, 10) - - ^-V /zd - z.count(" ") + - V+^ xKN - K.index(N) ``` [Try it here](http://pyth.herokuapp.com/?code=V%2Br%5CAJeSKwJ%2BxKN-izT%2Fzd&input=++++2000%0A--AF-C-------E--D---B--&debug=0) [Answer] # Python 3, 118 Man, today is the day of long Python answers. ``` def f(p,l):o=sum(x<'0'for x in p);e={x:i-o+int(p[o:])for i,x in enumerate(l)if'@'<x};return list(map(e.get,sorted(e))) ``` [Answer] ## Seriously, 40 bytes ``` ' ,c,;)l@;±)@-(x@;╗@Z`i3╤τ+@┐`MX╜ú∩S`└`M ``` [Try it online!](http://seriously.tryitonline.net/#code=JyAsYyw7KWxAO8KxKUAtKHhAO-KVl0BaYGkz4pWkz4QrQOKUkGBNWOKVnMO64oipU2DilJRgTQ&input=JyAgICAyMDAwJwonLS1hZi1jLS0tLS0tLWUtLWQtLS1iLS0n) Explanation to come later after further golfing. [Answer] ## Perl, ~~80~~ ~~79~~ ~~71~~ 67 bytes ``` ($a=<>)=~/\d/;$b=<>;say$a+$_-$-[0]for grep{$_+1}map{index$b,$_}A..Z ``` Thanks to [@dev-null](https://codegolf.stackexchange.com/users/48657/dev-null) for 12 bytes! ``` ($a=<>)=~/\d/; # read first line of input, find position of first digit # (saved in the $- variable) $b=<>; # read the second line A..Z # generate range 'A','B',... map{index$b,$_} # find index for each grep{$_+1} # select only those != -1 for # foreach of remaining... say$a+$_-$-[0] # calculate proper date ``` ]
[Question] [ A while ago I purchased a new wallet which is able to hold 8 cards (4 on both side). However, I seem to have way more cards than that and I need to make choices on which ones I want to carry with me. Some cards I use more often than others, but the cards I prefer to carry with me are not necessarily the ones I use most. ## The challenge Given a stack of cards, return the layout of my wallet in the best way possible w.r.t. my preferences and restrictions. The layout should be as follows: ``` __ __ (row 1) __ __ (row 2) __ __ (row 3) __ __ (row 4) ``` Currently I posess the following cards - stacks will always consist of a selection from these: * *1* identity card (**ID**) * *1* driver's license (**DL**) * *2* credit cards (**CC**) * *5* debit cards (**DC**) * *1* public transport card (**PC**) * *1* gym access card (**GC**) * *9* membership cards from random stores and warehouses (**MC**) I have some preferences and restrictions: * Cards sorted by priority: **ID, DL, CC, DC, PC, GC, MC** * Cards sorted by usage frequency: **CC, DC, PC, GC, MC, ID, DL** * For safety reasons, the total number of debit cards and credit cards in my wallet can be at most 1 more than the sum of all other cards that will go in my wallet ( *N*DC+*N*CC ≤ *N*ID+*N*DL+*N*PC+*N*GC+*N*MC+1 ). * If present, my identity card and driver's licence should always go in row 1. This does not mean that other cards may not occupy spots in row 1. * The most frequently used cards from the stack should always go in row 4. ## Rules * No 2 cards can occupy the same spot. * Higher priority cards are always prefered over lower priority ones, unless the DC/CC restriction kicks in. * ID/DL at row 1 overrules the frequency rule: if only ID is provided, it will go in row 1 and row 4 will be empty! * Input formatting can be done in any way you like, as long as the order of the input stack is retained. e.g. `ID,CC,PC,MC,MC,MC,DL` may also be supplied as e.g. `1ID 1CC 1PC 3MC 1DL 0DC 0GC` or `ID CC PC MC MC MC DL`. * Output formatting does have a few restrictions: rows must all start at a new line, columns must be delimited in some way. Empty spots may be presented any way you like, as long as it does not mess up the 4x2 layout. * There can be more than one solution/order, it's up to you which one you provide as output. * You may assume that cards of the same type will always be grouped at input. * Apart from the above, standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and loopholes apply. ## Bonus You are allowed to remove **15%** of your bytecount if you also return any cards that did not go in the wallet. Print "It fits!" in case of no remaining cards. This additional output should be clearly separated from the returend layout. ## Examples Input: ``` ID, DL, CC, GC, MC ``` 2 possible outputs: ``` ID DL DL ID __ __ or __ MC MC __ __ __ CC GC GC CC optional: It fits! ``` --- Input: ``` ID, CC, DC, PC, GC, MC, MC, MC, MC, MC ``` 2 possible outputs: ``` ID MC GC ID MC MC or MC PC PC GC MC MC CC DC DC CC optional: e.g. (MC, MC) or (2MC) ``` --- Input: ``` DC, DC, CC, CC, GC, DL ``` 2 possible outputs: ``` DL __ GC DL __ __ or DC __ GC DC __ __ CC CC CC CC optional: e.g. (DC) or (1DC) ``` --- Input: ``` CC, DC, DC, DC ``` 2 possible outputs: ``` __ __ __ __ __ __ or __ __ __ __ __ __ CC __ __ CC optional: e.g. (DC, DC, DC) or (3DC) ``` --- Input: ``` CC, CC, MC, MC, MC, MC, MC, MC, PC, DC, DC, DC, DC, DC, GC ``` 2 possible outputs: ``` MC MC MC DC PC GC or DC GC DC DC PC MC CC CC CC CC optional: e.g. (DC, DC, DC, MC, MC, MC, MC) or (3DC, 4MC) ``` --- Input: ``` MC, MC, MC, MC, MC, MC, MC ``` 2 possible outputs: ``` __ MC MC MC MC MC or MC MC MC MC MC __ MC MC MC MC optional: It fits! ``` --- Input: ``` ID, CC ``` 2 possible outputs: ``` ID __ __ ID __ __ or __ __ __ __ __ __ CC __ CC __ optional: It fits! ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins. [Answer] # Java 10, ~~385~~ ~~384~~ ~~382~~ 381 bytes ``` C->{String[]R=new String[8],F={"CC","DC","PC","GC","MC"};int c=C.size(),i=1,s=0;c=c>8?8:c;for(var q:C)if("DCC".contains(q))s++;for(;s+--s>c;c=(c=C.size())>8?8:c)i=C.remove(F[i])?i:0;for(c=0,i=8;i>0&c<5;c++)for(;i>0&C.remove(F[c]);)R[--i]=F[c];if(C.remove("ID"))R[c=0]="ID";if(C.remove("DL"))R[c<1?1:0]="DL";for(i=0;i<8;)System.out.print((R[i]!=null?R[i]:"__")+(i++%2>0?"\n":" "));} ``` Although it wasn't too difficult, I can see why it was unanswered. Especially that rule regarding \$N\_{DC}+N\_{CC}\leq N\_{ID}+N\_{DL}+N\_{GC}+N\_{MC}+1\$ costs quite a lot of bytes at the moment.. And since it's been about 2.5 year since this challenge has been posted, OP might have got another wallet by now anyway.. ;p -1 byte thanks to *@Jakob* -1 byte thanks to *@ceilingcat* [Try it online.](https://tio.run/##dVNtb9owEP7eX@FZ2mQrL4JJk1CMgyZHRZMAIbp@olGVmTCZBUNjw9Qhfjs7J6G8lEY5K@d77rnzPfEi22bBYvbnIIvMGDTMlN7dIaS0zct5JnM0ci5C25WaIUkWAA83VhXh97LMXgfK2O6DLZX@HSOZlTNDGcD3YPAam1kl0QhpxNFBBPGuhk7TCdf5X9R4ndS/5zssBPZx4paxW/puGQq8Z9ALklyERv3LCfUVb/uGt5jkMu70OpFk81VJtlmJXiJB1ZwAicChXGkLhzHkhVLjeRWIGS8ITCwhl5wYaU1DFeyU@XK1zcn9VKW0p6JWlSZ5C6p2mIpbX2T3G5OeRys6t3GWI1PK6GQaBCrlzmPQzFsY/0gwhSiQpdw5l9FkUEe77V47cgjYqIorOKrqdhh9eDU2X4arjQ3XMDdLyAS6/MT1pih67jPCz8@YekR53uevcauHnzSOMAJetj@wWpL15lcBkjTKVKIuYUrkKAzKaK23zY11PfsoGfhICB/1wUCPSuDzuIslYOM3zLVd5iQNXogTrzv9OebIWdv7mLhZp7bxRe7J@lc8ww85bp0R3/ixq/FVoHp8yDTDu5aq0EAzGj/@jBD2jOeEaUroUBJ3FW7cq@u7ZsLMVPsmNOtCQWe@05Y2TLdqPungo@fYwv5uf/gP) **Explanation:** ``` C->{ // Method with String-List parameter and String return-type String[]R=new String[8], // String-array of size 8 F={"CC","DC","PC","GC","MC"}; // Frequency-order String-array int c=C.size(), // Size of the input-List i=1, // Index integer, starting at 1 s=0; // Count-integer, starting at 0 c=c>8?8:c; // If the size is larger than 8, set it to 8 for(var q:C) // Loop over the cards of the input-List: if("DCC".contains(q)) // If the card is a DC or CC: s++; // Increase the counter by 1 for(;s+--s>c; // Loop as long as the amount of DC/CC is larger than the // other amount of cards + 1: c=(c=C.size())>8?8:c) // Recalculate the size after every iteration i=C.remove(F[i])?i:0; // If the List still contains a DC, remove it // Else: remove a CC instead for(c=0, // Reset `c` to 0 i=8;i>0 // Loop as long as there is still room in the wallet, &c<5; // and we still have cards left: c++) // Go to the next card-type after every iteration for(;i>0 // Inner loop as long as there is still room in the wallet, &C.remove(F[c]);) // and we still have a card of the current type left: R[i--]=F[c]; // Put a card of the current type in the wallet if(C.remove("ID"))R[c=0]="ID"; // Add the 'ID' card to the first row if present if(C.remove("DL"))R[c<1?1:0]="DL"; // Add the 'DL' card to the first row if present for(i=0;i<8;) // Loop over the wallet: System.out.print( // Print: (R[i]!=null? // If the current slot contains a card: R[i] // Append this card : // Else: "__") // Append an empty slot ("__") +(i++%2>0?"\n":" "));}// Append the correct delimiter (space or new-line) ``` --- # Java 10, ~~390.15~~ 389.3 (458 bytes - 15% bonus) ``` C->{String r="",R[]=new String[8],F[]={"CC","DC","PC","GC","MC"},t=r;int c=C.size(),i=1,s=0;for(var q:C)if("DCC".contains(q))s++;for(;s+--s>(c>8?8:c);c=C.size())if(C.remove(F[i]))t+=F[i]+",";else i=0;for(c=0,i=8;i>0&c<5;c++)for(;i>0&&C.remove(F[c]);)R[--i]=F[c];if(C.remove("ID")){t+=R[0]+",";R[c=0]="ID";};if(C.remove("DL")){t+=R[c=c<1?1:0]+",";R[c]="DL";}for(i=0;i<8;)r+=(R[i]!=null?R[i]:"__")+(i++%2>0?"\n":" ");return r+"\n"+(C.size()>0?t+C:"It fits!");} ``` [Try it online.](https://tio.run/##dVNtb9owEP7eX@FaWhXLSQSTJqEYgyZHRZUoQnT7lEVVZsJkFgK1DVOH8tvZOYTyMrBylnP33HPnO98822TBfPp7J4vMGPScqXJ7h5Aqba5nmczRyP0i9GK1Kn8h6c3BIVxbVYRftc7eh8rY7t7YQzLTU0MYOFQg8BmbWSXRCJWIo50IetuGR3OM/UmS8jL/03AnndR/BM0WC4F9HLtt7LaB254FrnzLNYPMkOQiNOpv7hFf8bZveIvNltrbZBq9RYKomQfuAodyWVq4kPHeCDGU1iBmaBCYnid7nX4nkoQdyZyjCHW@WG5y7zFRKSGWcnegkAHLC5Mj1cSSvAWxO0z1Wg@y@4VJSklN7xQPJywyJYxMkiBQKXd/7DQIfooxIVuIMkla@yiTBKhT7iysOgfHww@w5LLb7rejoxO4gJ1VLgmXpOp2GNGUexPI/56X66Lou2OEX18xoZ6i9NPnXquPf5Q4wggTpnO71iXS1Kmod6gKYCwVEX6yaKasuQdktWP7/q7WPwvob9PmzVJN0QIK7jUdTVFG9s/H5sa62/ooHvpICB8NQKCp9Ws5tTtbDDL@wFzKuU/c4IU48rpCnWIOnHv53yauxtnL@Mz3KIMLnuebHNfuiK9MSV2@GtQMiWmK9/JubL4Il2sbrsBgixJoRuPv3yKEqanb1YS4gixD6bkhuzK3l7NswszUehOaVaEgWR/ehVs32SF2cGsd0qruqt0/) ]
[Question] [ # Background [Hex](https://en.wikipedia.org/wiki/Hex_%28board_game%29) is a two-player abstract strategy game played on a `K×K` rhombus of hexagonal tiles. Two opposite sides of the rhombus are colored white, and the other two black, and the two players, black and white, take turns in placing a token of their color on an unoccupied tile. The player who first manages to construct a path between the opposite sides of their color is the winner. It is known that the game cannot end in a draw, and that the first player has a winning strategy regardless of the board size (see the Wikipedia page for details). # The Task In this challenge, we fix the board size at `K = 4`, and represent the board as the following grid. The thick lines denote adjacent tiles. ![A 4x4 grid.](https://i.stack.imgur.com/yayMX.png) Your task is to produce a winning strategy for the first player, which you can choose to be either black or white. This means that whichever legal moves the opposing player makes, your play must result in a victory. Your input is a game position (the arrangement of tokens on the board), and your output is a legal move, in the format specified below. If you want to find a winning strategy yourself, do not read this spoiler: > > **Outline of one possible winning strategy, assuming white goes first.** > > First select 5. After that, if you have a path from 5 to the bottom row OR black selects 0 or 1 at any point, respond by selecting whichever of 0 or 1 is vacant. > > If black selects 9 or 13, select 10 and then whichever of 14 or 15 is vacant. If black does not select 9, 13 or 14, then select 9 and next whichever of 13 or 14 is vacant. > > If black selects 14, respond by selecting 15. Next, select 10 if it is vacant; if black selects 10, respond with 11. If black then selects 6, respond with 7, and next whichever of 2 or 3 is vacant. If black does not select 6, select it, so you have a path from 5 to the bottom row. > > > # Input and Output Your input is a string of 16 characters `WBE`, which stand for white, black and empty. They represent the tiles of the board, as enumerated above. You can choose the input method (which also determines your output method) from the following: 1. Input from STDIN, output to STDOUT. 2. Input as one command line argument, output to STDOUT. 3. Input as 16 single-character command line arguments, output to STDOUT. 4. Input as argument of named function, output as return value. Your output represents the tile on which you place your next token, as it is your turn to move. You can choose from the following output formats: 1. A zero-based index (as used in the above picture). 2. A one-based index. 3. The input string with one `E` replaced by whichever of `W` or `B` you chose for your player. # Rules Your strategy must be deterministic. You are not required to correctly handle game positions that are unreachable from the empty board using your strategy, or positions that are already winning for either player, and you may crash on them. Conversely, on boards that are reachable using your strategy, you must return a legal move. This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed. # Testing I have written a Python 3 controller for validating entries, since it would be extremely tedious to do by hand. You can find it [here](https://github.com/iatorm/4x4-hex). It supports the first three input formats and Python 3 functions (functions in other languages have to be wrapped into programs), all three output formats, and both players. If a strategy is not winning, it will output a losing game it found, so you can tweak your program. [Answer] # Marbelous, 973b This is a naive implementation of the hinted strategy in the question. It expects the board to be provided as 16 commandline/mainboard parameters like `hex.mbl B W E E E W E E E B E E E E E E` and it will output the zero-indexed position of white's next move. ``` 00 }1 }0 &G B? W! &0 &G &G !! 00 }0 }1 &H B? W! &1 &H &H !! .. }D .. }9 }9 }D }E }A }D }9 }A .. }E }F }5 }9 B! }E E? W? E? .. E? B? B? W? .. E? .. E? B! ?0 B! &M &N &O E? &I \\ .. &J .. &K E? &5 ?0 ++ ?0 &9 .. &D &P &A &I /\ &J .. &E &L !! ++ .. ++ !! .. !! &E !! \/ &L /\ &K !! &F \\ .. // .. .. .. !! .. .. \/ .. \/ .. !! .. =3 \/ &M /\ &N \/ &O /\ &P }0 }1 }6 .. }6 .. }7 &7 }2 }3 }A }A }B }E }F .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. B? W! .. .. .. .. .. .. .. .. .. .. .. .. .. &Q &Q .. .. .. .. B? .. E? W? E? .. E? B? E? &F \/ .. .. .. &S /\ &T &S &T &U E? &A &R &R !! .. .. .. &7 .. .. \/ .. &2 &V !! &B \/ .. .. .. !! .. .. &U /\ &V &3 .. !! .. .. .. .. .. .. .. .. .. !! .. .. .. .. .. E? E? .. &6 &X E? !! !! &Y .. !! }4 }8 }C \/ \/ \/ 30 30 31 31 32 33 35 36 37 39 31 30 31 31 31 33 31 34 31 35 &0 &X &1 &Y &2 &3 &5 &6 &7 &9 &A &A &B &B &D &D &E &E &F &F :W? }0 ^4 =1 {0 :B? }0 ^0 =0 {0 :E? }0 ^1 =0 {0 :W! }0 ^4 =0 {0 :B! }0 ^0 >0 {0 ``` I think I can probably golf about 200 characters out of this with better branching and elimination of code re-use. ]
[Question] [ I previously asked [a question](https://codegolf.stackexchange.com/questions/51436/calculate-a-probability-exactly-and-quickly) for how to compute a probability quickly and accurately. However, evidently it was too easy as a closed form solution was given! Here is a more difficult version. This task is about writing code to compute a probability exactly *and quickly*. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output `4/8` but rather `1/2`. For some positive integer `n`, consider a uniformly random string of 1s and -1s of length `n` and call it A. Now concatenate to `A` a copy of itself. That is `A[1] = A[n+1]` if indexing from 1, `A[2] = A[n+2]` and so on. `A` now has length `2n`. Now also consider a second random string of length `n` whose first `n` values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B. Now consider the inner product of `B` with `A[1+j,...,n+j]` for different `j =0,1,2,...`. For example, consider `n=3`. Possible values for `A` and `B` could be `A = [-1,1,1,-1,...]` and `B=[0,1,-1]`. In this case the first two inner products are `0` and `2`. **Task** For each `j`, starting with `j=1`, your code should output the probability that all the first `j+1` inner products are zero for every `n=j,...,50`. Copying the table produced by Martin Büttner for `j=1` we have the following sample results. ``` n P(n) 1 1/2 2 3/8 3 7/32 4 89/512 5 269/2048 6 903/8192 7 3035/32768 8 169801/2097152 ``` **Score** Your score is the largest `j` your code completes in 1 minute on my computer. To clarify a little, each `j` gets one minute. Note that the dynamic programming code in the previous linked question will do this easily for `j=1`. **Tie breaker** If two entries get the same `j` score then the winning entry will be the one that gets to the highest `n` in one minute on my machine for that `j`. If the two best entries are equal on this criterion too then the winner will be the answer submitted first. **Languages and libraries** You can use any freely available language and libraries you like. I must 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 machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. **Winning entries** * `j=2` in **Python** by Mitch Schwartz. * `j=2` in **Python** by feersum. Currently the fastest entry. [Answer] # Python 2, j=2 I tried to find a sort of 'closed form' for j=2. Perhaps I could make a MathJax image of it, although it would be really ugly with all the index fiddling. I wrote this unoptimized code only to test the formula. It takes about 1 second to complete. The results match with Mitch Schwartz's code. ``` ch = lambda n, k: n>=k>=0 and fac[n]/fac[k]/fac[n-k] W = lambda l, d: ch(2*l, l+d) P = lambda n, p: n==0 or ch(n-1, p-1) ir = lambda a,b: xrange(a,b+1) N = 50 fac = [1] for i in ir(1,4*N): fac += [i * fac[-1]] for n in ir(2, N): s = 0 for i in ir(0,n+1): for j in ir(0,min(i,n+1-i)): for k in ir(0,n+i%2-i-j): t=(2-(k==0))*W(n+i%2-i-j,k)*W(i-(j+i%2),k)*W(j,k)**2*P(i,j+i%2)*P(n+1-i,j+1-i%2) s+=t denp = 3 * n - 1 while denp and not s&1: denp -= 1; s>>=1 print n, '%d/%d'%(s,1<<denp) ``` Consider a sequence where the ith member is `e` if A[i] == A[i+1] or `n` if A[i] != A[i+1]. `i` in the program is the number of `n`s. If `i` is even, the sequence must begin in and end with `e`. If `i` is odd, the sequence must begin and end with `n`. Sequences are further classified by the number of runs of consecutive `e`s or `n`s. There are `j` + 1 of one and `j` of the other. When the random walk idea is extended to 3 dimensions, there is an unfortunate problem that there are 4 possible directions to walk in (one for each of `ee`,`en`,`ne`, or `nn`) which means they are not linearly dependent. So the `k` index sums over the number of steps taken in one of the directions (1, 1, 1). Then there will be an exact number of steps which must taken in the other 3 directions to cancel it. P(n,p) gives the number of ordered partitions of n objects into p parts. W(l,d) gives the number of ways for a random walk of `l` steps to travel a distance of exactly `d`. As before there is 1 chance to move left, 1 chance to move right and 2 to stay put. [Answer] ## Python, j=2 The dynamic programming approach for `j = 1` in my [answer](https://codegolf.stackexchange.com/a/51465/2537) to the previous question does not need many modifications to work for higher `j`, but gets slow quickly. Table for reference: ``` n p(n) 2 3/8 3 11/64 4 71/512 5 323/4096 6 501/8192 7 2927/65536 8 76519/2097152 9 490655/16777216 10 207313/8388608 ``` And the code: ``` from time import* from fractions import* from collections import* def main(): N_MAX=50 T=time() n=2 Y=defaultdict(lambda:0) numer=0 for a1 in [1]: for b1 in (1,0): for a2 in (1,-1): for b2 in (1,0,0,-1): if not a1*b1+a2*b2 and not a2*b1+a1*b2: numer+=1 Y[(a1,a2,b1,b2,a1*b1+a2*b2,a2*b1,0)]+=1 thresh=N_MAX-1 while time() <= T+60: print('%d %s'%(n,Fraction(numer,8**n/4))) if thresh<2: print('reached N_MAX with %.2f seconds remaining'%(T+60-time())) return n+=1 X=Y Y=defaultdict(lambda:0) numer=0 for a1,a2,b1,b2,s,t,u in X: if not ( abs(s)<thresh and abs(t)<thresh+1 and abs(u)<thresh+2 ): continue c=X[(a1,a2,b1,b2,s,t,u)] # 1,1 if not s+1 and not t+b2+a1 and not u+b1+a1*b2+a2: numer+=c Y[(a1,a2,b2,1,s+1,t+b2,u+b1)]+=c # -1,1 if not s-1 and not t-b2+a1 and not u-b1+a1*b2+a2: numer+=c Y[(a1,a2,b2,1,s-1,t-b2,u-b1)]+=c # 1,-1 if not s-1 and not t+b2-a1 and not u+b1+a1*b2-a2: numer+=c Y[(a1,a2,b2,-1,s-1,t+b2,u+b1)]+=c # -1,-1 if not s+1 and not t-b2-a1 and not u-b1+a1*b2-a2: numer+=c Y[(a1,a2,b2,-1,s+1,t-b2,u-b1)]+=c # 1,0 c+=c if not s and not t+b2 and not u+b1+a1*b2: numer+=c Y[(a1,a2,b2,0,s,t+b2,u+b1)]+=c # -1,0 if not s and not t-b2 and not u-b1+a1*b2: numer+=c Y[(a1,a2,b2,0,s,t-b2,u-b1)]+=c thresh-=1 main() ``` Here we are keeping track of the first two elements of `A`, the last two elements of `B` (where `b2` is the last element), and the inner products of `(A[:n], B)`, `(A[1:n], B[:-1])`, and `(A[2:n], B[:-2])`. ]
[Question] [ On my website, users enter their date of birth in the style `xx.xx.xx` - three two-digit numbers separated by dots. Unfortunately, I forgot to tell the users exactly which format to use. All I know is that one section is used for the month, one for the date, and one for the year. The year is definitely in the 20th century (1900-1999), so the format `31.05.75` means `31 May 1975`. Also, I'm assuming everyone uses either the Gregorian or the Julian calendar. Now, I want to go through my database to clear up the mess. I'd like to start by dealing with the users with the most ambiguous dates, that is, those where the range of possible dates is the biggest. For example, the date `08.27.53` means `27 August 1953` in either the Gregorian or Julian calendar. The date in the Julian calendar is 13 days later, so the range is just `13 days`. In contrast, the notation `01.05.12` can refer to many possible dates. The earliest is `12 May 1901 (Gregorian)`, and the latest is `1 May 1912 (Julian)`. The range is `4020 days`. ## Rules * Input is a string in the format `xx.xx.xx`, where each field is two digits and zero-padded. * Output is the number of days in the range. * You can assume that the input will always be a valid date. * You may not use any built-in date or calendar functions. * Shortest code (in bytes) wins. ## Testcases * `01.00.31` => `12` * `29.00.02` => `0` (The only possibility is `29 February 1900 (Julian)`) * `04.30.00` => `13` * `06.12.15` => `3291` [Answer] # Pyth, 118 bytes ``` M++28@j15973358 4G&qG2!%H4FN.pmv>dqhd\0cz\.I&&&hN<hN13eN<eNhgFPNaYK+++*365JhtN/+3J4smghdJthNeNInK60aY-K+12>K60;-eSYhSY ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=M%2B%2B28%40j15973358+4G%26qG2!%25H4FN.pmv%3Edqhd%5C0cz%5C.I%26%26%26hN%3ChN13eN%3CeNhgFPNaYK%2B%2B%2B*365JhtN%2F%2B3J4smghdJthNeNInK60aY-K%2B12%3EK60%3B-eSYhSY&input=06.12.15&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=zFz.zp%22+%3D%3E+%22z%3DY%5B)M%2B%2B28%40j15973358+4G%26qG2!%25H4FN.pmv%3Edqhd%5C0cz%5C.I%26%26%26hN%3ChN13eN%3CeNhgFPNaYK%2B%2B%2B*365JhtN%2F%2B3J4smghdJthNeNInK60aY-K%2B12%3EK60)))-eSYhSY&input=Test+Cases%3A%0A08.27.53%0A01.05.12%0A01.00.31%0A29.00.02%0A04.30.00%0A06.12.15&debug=0). ### Necessary knowledge of Julian and Gregorian Calendars Julian and Gregorian Calendar are quite similar. Each calendar divides a year into 12 months, each containing of 28-31 days. The exact days in a month are `[31, 28/29 (depends on leap year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]`. The only difference between the calendars are their definition of a leap year. In the Julian Calendar any year divisible by 4 is a leap year. The Gregorian Calendar is a bit more specific. Any year divisible by 4 is a leap year, except the year divisible by 100 and not divisible by 400. So in the 20th century only one year is different. The year 1900, which is a leap year in the Julian Calendar, but not a leap year in the Gregorian Calendar. So the only date, that exists in the one calendar but not in the other calendar is the day `29.02.1900`. Because of the different leap year definition, there's a difference between a date in the Julian Calendar and the Gregorian Calendar. 12 days difference for a date before the `29.02.1900`, and 13 days difference for dates after the `29.02.1900`. ### Simplified Pseudo-Code ``` Y = [] # empty list for each permutation N of the input date: if N is valid in the Julian Calendar: K = number of days since 0.01.1900 append K to Y if K != 60: # 60 would be the 29.02.1900 L = K - (12 if K < 60 else 13) append L to Y print the difference between the largest and smallest value in Y ``` ### Detailed Code Explanation The first part `M++28@j15973358 4G&qG2!%H4` defines a function `g(G,H)`, which calculates the number of days in month `G` of a year `H` in the Julian Calendar. ``` M def g(G,H): return j15973358 4 convert 15973358 into base 4 @ G take the Gth element +28 + 28 + &qG2!%H4 + (G == 2 and not H % 4) ``` And the next part is just the for loop, and the ifs. Notice that I interpret `N` in the format `(month, year, day)`. Just because it saves some bytes. ``` FN.pmv>dqhd\0cz\. cz\. split input by "." mv>dqhd\0 map each d of ^ to: eval(d[d[0]=="0":]) FN.p for N in permutations(^): I&&&hN<hN13eN<eNhgFPN I if hN month != 0 & and <hN13 month < 13 & and eN day != 0 & and <eNhgFPN day < 1 + g(month,year): aYK+++*365JhtN/+3J4smghdJthNeN JhtN J = year +*365J /+3J4 J*365 + (3 + J)/4 + smghdJthN + sum(g(1+d,year) for d in [0, 1, ... month-2]) + eN + day K K = ^ aYK append K to Y InK60aY-K+12>K60 InK60 if K != 60: aY-K+12>K60 append K - (12 + (K > 60)) to Y ;-eSYhSY ; end for loop -eSYhSY print end(sorted(Y)) - head(sorted(Y)) ``` [Answer] # [Perl 5](https://www.perl.org/), 294 bytes ``` sub f{map/(\d\d)(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])/ #1 &&$3<29+($2==2?!($1%4):2+($2/.88)%2) #2 &&($j{$_}=++$j+12) #3 &&$j!#1=60?$g{$_}=++$g:0,'000101'..'991231'if!%g; #4 pop=~/(\d\d).(\d\d).(\d\d)/; #5 @n=sort{$a<=>$b} #6 grep$_, #7 map{($j{$_},$g{$_})} #8 ("$1$2$3","$1$3$2","$2$1$3","$2$3$1","$3$1$2","$3$2$1"); #9 $n[-1]-$n[0]} #10 ``` [Try it online!](https://tio.run/##1VTbbuIwEH3nK4ZoArYIxhdgCanb/sC@7RtEVbo4bBCXbJwKVWn211k7tCvtJ8Qvc3yOPXNs2VOa6ri43ezbK@TNKStnZLvb7ijhGzGN0w@x4UKm/6YbN9nuPpRjUzobjVA9yHhCUGotn4YERTina@mJGVutaCjpaETw0OBLqycTPEyEZ/Aw1Ev@hPsvfr/m0ZhzLrgYMzaOYyGVGBf5MNwn5aXUfz5dsf/CLHk@a3up6gazB/2Ir@2@MiW@RO4YzWfV6F6EtiRAgRJVEHmgUHogPbwDhcID5VfdgRMDmuB5MxXp1AWetrfTOzzXxtb695VAj8YAgAvGOVMCQMheGZexN86dad6zG58z5Yw710L1y/iSCcnEAkDJWPTJ@IrJb2yh@nfj7nMumP@Ycy5788wHNBm8WQM/XEdcr79fKgO@OVrQj7BMBtdfxdGQrl/Sxh3y9E5wl9UmwoxqWx6Ln6YTIx7JpNMBbV05qSrOdU4Cv1h3WwCys72aSofTuQXIdWgDlybK7xkp9fsLS@CLiMCpXTontbe/ "Perl 5 – Try It Online") 298 bytes when spaces, newlines and comments are removed. Lines 1-4 initializes (if not done) the `%g` and `%j` hashes where the values are the Gregorian and Julian day numbers accordingly counting from Jaunary 1st 1900 up to December 31st 1999. Line 5 puts input date into $1, $2 and $3. Line 9 lists all six permutations of those three input numbers. Line 8 converts those six into two numbers each, the Gregorian and the Julian day numbers, but only those who are valid dates. Line 7 makes sure of that, it filters out non existant day numbers. Line 6 sorts the list of valid date numbers from the smallest to the largest. Line 10 returns then difference between the last and first (max and min), which was the wanted range. ]
[Question] [ Yes, the good old GIF. Loved for its versatility, hated for its patents and partly obsoleted due to its limitations (and patents), GIF consists, at the core, of a color palette and a palette-indexed image compressed using the LZW algorithm. Your task is to write a program that reads an image in ASCII [PPM](http://en.wikipedia.org/wiki/Netpbm_format) format ("P3" magic number) from the standard input, and writes the same image (identical pixel-by-pixel) in GIF format to the standard output. The output can either be in binary form, or ASCII text with each byte represented by a number between 0 and 255 (inclusive), separated by whitespace. The input image is guaranteed not to have more than 256 different colors. **Scoring:** Your program will be tested on 3 sample images, and your score will be calculated as: *program size + sum(output size - reference size for each sample image)* Lowest score wins. **Requirements:** * Your program must work with any similar kinds of images of various sizes, and not be limited to the sample images. You could, for example, restrict the dimensions to be multiples of 2 or assume that the ppm max color is 255, but it should still work with a wide variety of input images. * The output must be a valid GIF file that can be loaded with any compliant program (after converting back to binary if using the ASCII output option). * You can not use any image processing functions (built-in or third-party), your program must contain all the relevant code. * Your program must be runnable in Linux using freely available software. * The source code must use only ASCII characters. **Sample images:** Here are the 3 sample images that will be used for scoring. You can download a [zip archive with the ppm files](https://drive.google.com/file/d/0By6e_kN-xWs1dnlYelBlbHVGUDg/view?usp=sharing) (use the download button on the top of that page). Or you can convert them from the png images below, using ImageMagick with the following command: ``` convert file.png -compress none file.ppm ``` I am also providing the MD5 checksums of the ppm files for confirmation. **1. amber** ![amber.png](https://i.stack.imgur.com/hDsX5.png) Reference size: 38055 MD5 checksum of ppm: d1ad863cb556869332074717eb278080 **2. blueeyes** ![blueeyes.png](https://i.stack.imgur.com/VrKCI.png) Reference size: 28638 MD5 checksum of ppm: e9ad410057a5f6c25a22a534259dcf3a **3. peppers** ![peppers.png](https://i.stack.imgur.com/pxKG0.png) Reference size: 53586 MD5 checksum of ppm: 74112dbdbb8b7de5216f9e24c2e1a627 [Answer] # Perl, 515 + -2922 + 0 + -2571 = -4978 Another approach. This time I am trying to save the image in tiles of size 64xH. This is fine according to specs, but some software may show only the first tile or an animation. The tiles compress better because of better spacial locality. I still do normal compression as well for the second image and choose whatever came shorter. Since this compresses the image twice, it is twice as slow compared to my previous solution. ``` #!perl -n0 sub r{$r.=1&"@_">>$_ for 0..log(@d|256)/log 2} @k=/(\d+) (\d+)/; @l=map{$$_||=(push(@t,split$"),++$i)}/\d+ \d+ \d+/g; print+GIF89a,pack(vvCxxC768,@k,~8,@t); sub v{($w,$h)=@_;for$k(0.."@k"/$w-1){ $k*=$w;$r='';@d=();@p=grep+($z++-$k)%"@k"<$w,@l; $"=' ';$_="@p ";$"='|';while(/./){ r 256;%d=map{($_,$_-1)}@d=1..256; $d{$&}=@d+2,r$d{$1},unshift@d,$&while@d<4095&&s/^(@d) (\d*)/$2/} r 257;$_=pack"b*",$r; $h.=pack"Cv4n(C/a)*",44,$k,0,$w,$k[1],8,/.{0,255}/gs }$b=$h if!$b||length$b>length$h} "@k"%64||v 64;v"@k";print"$b;" ``` # Perl, 354 + 12 + 0 + -1 = 365 ~~418 9521 51168 56639~~ Either there is some bug in my code or the second image is optimized for a specific encoder as seemingly insignificant change reduced the size to the reference exactly. Takes about 30s-60s per image. Golfed version. ``` #!perl -n0 sub r{$r.=1&"@_">>$_ for 0..log(@d|256)/log 2} @k=/(\d+) (\d+)/; @p=map{$$_||=(push(@t,split$"),++$i)}/\d+ \d+ \d+/g; $_="@p ";$"='|';while(/./){ r 256;%d=map{($_,$_-1)}@d=1..256; $d{$&}=@d+2,r$d{$1},unshift@d,$&while@d<4095&&s/^(@d) (\d*)/$2/} r 257;$_=pack"b*",$r; print+GIF89a,pack(vvCxxC768,@k,~8,@t), pack("Cx4vvn(C/a)*",44,@k,8,/.{0,255}/gs),';' ``` The only decision a GIF compressor can take is when to reset the LZW dictionary. In general because of how the images for this task were chosen the best moment to do so is each 4096 codes which is the moment the dictionary would overflow. With such limit the dictionary never overflows which saves a couple of bytes in the implementation. This is how it works in detail: ``` #!perl -n0 # function to add one codeword to the output stream @r. # the current codeword length is based on the dictionary size/ sub r{push@r,map"@_">>$_,0..log(@d|256)/log 2} # get the dimensions into @k @k=/(\d+) (\d+)/; # get pixel indexes to @p and palette to @t @p=map{$$_||=(push(@t,split$"),++$i)}/\d+ \d+ \d+/g; # convert index table into space separated string $_="@p ";$"='|'; # LZW encoder; while something to encode while(/\S/){ # output reset code r 256; # reset code dictionary $d is the last code number, # %d is the map of codes and @d list of codes $d=257;%d=map{($_,$_-1)}@d=1..256; # find codes using regexp, stop at dictionary overflow while($d<4096&&s/^(@d) (\d*)/$2/){ unshift@d,$&;$d{$&}=++$d;r$d{$1}}} # end LZW encoder; output end code r 257; # convert bit string @r to bytes $f vec($f,$j++,1)=$_ for@r; # output header up to the color table print+GIF89a,pack(vvCvC768,@k,~8,0,@t), # output rest of the header pack(Cv4CC,44,0,0,@k,0,8), # output the LZW compressed data $f slicing into sub-blocks $f=~s/.{0,255}/chr(length$&).$&/egsr,';' ``` # Perl, 394 + -8 + 0 + -12 = 374 Adding a heuristic to guess the reset point improves compression a bit but not enough to justify the extra code: ``` #!perl -n0 sub r{$r.=1&"@_">>$_ for 0..log(@d|256)/log 2} @k=/(\d+) (\d+)/; @p=map{$$_||=(push(@t,split$"),++$i)}/\d+ \d+ \d+/g; $_="@p ";$"='|';while(/./){ r 256;%d=map{($_,$_-1)}@d=1..256; $d{$&}=@d+2,r$d{$1},unshift@d,$&while (@d<4001||(/((@d) ){11}/,$&=~y/ //>12))&@d<4095&&s/^(@d) (\d*)/$2/} r 257;$_=pack"b*",$r; print+GIF89a,pack(vvCxxC768,@k,~8,@t), pack("Cx4vvn(C/a)*",44,@k,8,/.{0,255}/gs),';' ``` [Answer] # CJam, score 155 + 35306 + 44723 + 21518 = 101702 Just a dumb reference implementation. It's slow, doesn't do any actual compression and it's not golfed. ``` "GIF89a":iS*SqN/S*S%1>:i3/:M0=2<256f{md\}S*:ZS247S0S0SM1>_|:PL*_,768\m0a*+S*S44S0S0S0S0SZS0S8SM1>Pf{\a#}254/256a*{512+2b1>W%}%:+8/{W%2b}%255/{_,S@S*S}/0S59 ``` ]
[Question] [ # Input Your input is a single string, separated by newlines into `2n+1` lines of length `2n+1`, for some integer `n ≥ 0`. The integer `n` is not part of the input; you'll have to compute it from the string. The lines are composed of the "direction characters" `>^<v`. If newlines pose a problem, you can replace them by vertical pipes `|`. The input forms a square grid of size `(2n+1)x(2n+1)`, and each cell of the grid is interpreted as a *rotor router*, which points in one of the four cardinal directions. We proceed to drop a *token* on the router at the center of the grid, and then the routers will move it around in the following way. When the token lands on a router, the router turns 90 degrees in the counter-clockwise direction, and moves the token one step in the new direction it points to. If it lands on another router, the process is repeated, but eventually, the token will fall off the grid. # Output Your output is the final configuration of the routers, in the same format as the input. # Example As an example input, consider the `3x3` grid ``` <^< ^**>**< >^v ``` where the central router has been highlighted to indicate the token (it's a bit hard to see). The central router rotates to face north, and moves the token to the central cell of the top row: ``` <**^**< ^^< >^v ``` This router rotates to face west, and sends the token to the top left corner: ``` **<**<< ^^< >^v ``` The router in the corner sends the token south, so it's now at the leftmost cell of the middle row: ``` v<< **^**^< >^v ``` That router rotates to face west and sends the token off the grid. ``` v<< <^< >^v ``` This is the final grid configuration, so your program should output it. Note that in more complex examples, the token can pass the same router multiple times before falling off the grid. # Rules You can write either a function or a full program. This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed. You can decide whether there is a trailing newline in the input and/or output. # Test Cases ``` Input: v Output: > Input: <^< ^>< >^v Output: v<< <^< >^v Input: >>^>> v<vv< >^>^< ^<>>^ vvv>> Output: >>^>> >v>>v ^>>vv ^^>>> v^<<^ Input: <^^^^^^^^ <<^^^^^^> <<<^^^^>> <<<<^^>>> <<<<^>>>> <<<vv>>>> <<vvvv>>> <vvvvvv>> vvvvvvvv> Output: >>>>>>>>v ^>>>>>>vv ^^>>>>vvv ^^^>>vvvv <<<<<vvvv ^^^^<<vvv ^^^<<<<vv ^^<<<<<<v ^<<<<<<<< ``` [Answer] # CJam, ~~62~~ ~~61~~ 63 bytes [Try it online](http://cjam.aditsu.net/#code=Nq_N%23)%3AD%3B%2B_%2C2%2F%7B%3AP%22%5E%3Cv%3E%5E%0A%0A%22_P4%24%3D%23%3AX)%3Dt_%2C0PX%5B1DW*WDSP%5D%3D-e%3Ee%3C%7Dh%3B1%3E&input=%3C%5E%3C%0A%5E%3E%3C%0A%3E%5Ev) ``` Nq_N#):D;+_,2/{:P"^<v>^ "_P4$=#:X)=t_,0PX[1DW*WDSP]=-e>e<}h;1> ``` Expanded and commented: ``` Nq "Read the input grid"; _N#):D; "Calculate the vertical delta (line length + 1)"; + "Prepend a newline to the grid"; _,2/ "Calculate the initial position as the length of the grid string divided by 2"; { "Do..."; :P"^<v>^ " _P4$= "Get the character indexed by the position in the grid"; #:X "Map the character to an operation number: '^'=>0, '<'=>1, 'v'=>2, '>'=>3, '^'=>4, '\n'=>5, '\n'=>6 (the unreachable duplicate mappings are important below)"; )=t "Set the character indexed by the position in the grid to the result of mapping the operation number + 1 backwards"; _,0PX[1DW*WDSP]="Map the operation number to a negated delta (this occurs after rotating routers, which means that operation n should act like the character corresponding to operation n + 1): 0=>1, 1=>-delta, 2=>-1, 3=>delta, 5=>position"; -e>e< "Subtract the negated delta from the position and clamp it to [0, length of the grid string] (array indices are circular, so the length of the grid string will act like the index 0 and point to the initial newline next iteration, which will *really* set the position to 0)"; }h "... while the position is not 0 (i.e. not at the initial newline)"; ;1> "Clean up and remove the initial newline"; ``` My solution operates on the input as a flat string, so there's only one position value to keep track of and virtually no pre/postprocessing; there are only 2 bytes of preprocessing to add newline to the beginning of the grid and 2 bytes of postprocessing to remove it from the output. But these 4 bytes are well worth the cost as they let me keep newlines in and "execute" them like routers, but they "rotate" into another newline and set the position to zero. And the main loop ends when the position becomes zero. [Answer] # CJam, ~~90~~ 69 bytes ``` q_,mqi):L_*Lm2/(:X;{_X_@="^<v>"_@#_[WL1LW*]=X+:X;)=tX)L%XW>XLL(*<**}g ``` ~~Huge for now,~~ Can still be reduced a lot. [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript (ES6) 121 ~~120 127 129~~ A named function that gets the string as an input parameter and returns the output. Assuming the input string is terminated with a newline. **Edit** bug fix, .search() does not work well with `undefined` ``` F=s=>(o=~s.search('\n'),s=[...s], R=p=>~(u='^<v>'.indexOf(s[p]))?R(p+[-1,-o,1,o][u],s[p]='<v>^'[u]):s)(-~o*o/2-1) .join('') ``` **Ungolfed** and explained ``` F=s=>{ o = s.search('\n')+1; // offset to next row s = [...s]; // string to array R=p=>{ // recursive search functiom, parameter p is current position in grid u = '^<v>'.indexOf(s[p]); // find direction if (u<0) return s; // if no direction found, out of grid -> stop recursion s[p] = '<v>^'[u] // set new direction into the array cell return R(p+[-1,o,1,-o][u]) // call recursive function with new position } return R((o-1)*o/2-1) // start recursive search with initial position at grid center .join('') // array to string } ``` **Test** In Firefox/FireBug console ``` s='<^^^^^^^^\n\ <<^^^^^^>\n\ <<<^^^^>>\n\ <<<<^^>>>\n\ <<<<^>>>>\n\ <<<vv>>>>\n\ <<vvvv>>>\n\ <vvvvvv>>\n\ vvvvvvvv>\n' console.log(F(s)) ``` *Output* ``` >>>>>>>>v ^>>>>>>vv ^^>>>>vvv ^^^>>vvvv <<<<<vvvv ^^^^<<vvv ^^^<<<<vv ^^<<<<<<v ^<<<<<<<< ``` ]
[Question] [ Your task this time is to implement a variant of the POSIX [`expand(1)`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/expand.html) utility which expands tabs to spaces. Your program is to take a *tabstop specification* and then *read input on standard in* and replace tab characters in the input with the appropriate amount of spaces to reach the next tabstop. The result should be *written to standard out*. ### Tabstop specification A *tabstop specification* consists of either a single number, or a comma-separated list of tabstops. In the case of a single number, it is repeated as if multiples of it occurred in a comma-separated list (i.e. `4` acts as `4,8,12,16,20,...`). Each entry in a comma-separated list is a positive integer optionally prefixed by a `+`. A `+` prefix indicates a relative difference to the previous value in the comma-separated list. The first value in the list must be absolute (i.e. unprefixed). The tabstops specify the column of the next non-space character (following the expanded tab), with the leftmost column taken as number 0. Tabs should always expand to at least one space. ### Input/output The tabstop specification is either to be taken as the first command-line parameter to the program, or read from standard in as the first line of input (terminated by a newline), at your discretion. After the tabstop has been read, the remaining input (all input, in the former case) until EOF is to be processed and expanded. The expanded output shall be written to standard out. All expanded tabstops, and all input, is assumed to be a maximum of 80 columns wide. All expanded tabstops are strictly increasing. --- ## Example Tabstop specification `4,6,+2,+8` is equivalent to `4,6,8,16`, and with both the input ``` ab<Tab>c <Tab><Tab>d<Tab>e<Tab>f ``` is expanded into (`␣` indicates a space) ``` ab␣␣c ␣␣␣␣␣␣d␣e␣␣␣␣␣␣␣f ``` ``` 01234567890123456 (Ruler for the above, not part of the output) 1111111 ``` --- Scoring is pure [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins. [Answer] ## GolfScript (77 75 chars) ``` n/(','/{'+'/{~t++}*~:t}%81,{t*}%+:T;{[0\{.9={;T{1$>}?(.)@-' '*}*\)}/;]n+}/; ``` I'm quite pleased with the tabspec parsing. ``` # Split on commas ','/ # For each element: { # Split on '+' '+'/ # We now have either ["val"] or ["" "val"] # The clever bit: fold # Folding a block over a one-element array gives that element, so ["val"] => "val" # Folding a block over a two-element array puts both elements on the stack and executes, # so ["" "val"]{~t++}* evaluates as # "" "val" ~t++ # which evaluates val, adds the previous value, and concatenates with that empty string {~t++}* # Either way we now have a string containing one value. Eval it and assign to t ~:t }% ``` Then I add multiples of the last element until I'm guaranteed to have enough to reach the end of the 80 columns: ``` 81,{t*}%+ ``` This gives the desired behaviour when only one tabstop was specified, and is otherwise only relevant in cases which the spec doesn't mention. (NB it makes the list of tab-stops dip back to 0 and then repeat the last parsed element, but that's irrelevant because when it comes to using the list I look for the first element greater than the current position). The rest is pretty straightforward. [Answer] ## C, 228 chars Here is a C solution to start things off. There's still a lot of golfing to do here (look at all those `if`s and `for`s and `putchar`s...). Tested with the example testcase, as well as with the same input but `4` and `8` for the tab spec. ``` S[99],i;L,C;main(v){for(v=1;v;)v=scanf("+%d",&C),v=v>0?C+=L:scanf("%d",&C), v&&(S[L=C]=++i,getchar());for(;i==1&&C<80;)S[C+=L]=1;for(C=L=0;C=~getchar();) if(C+10)putchar(~C),L+=C+11?1:-L;else for(putchar(32);!S[++L];)putchar(32);} ``` [Answer] # Ruby 161 145 Reads the tabstop specification on the first line of input. ``` i=t=[] gets.scan(/(\+)?(\d+)/){t<<i=$2.to_i+($1?i:0)} 81.times{|j|t<<j*i} while gets $_.sub!$&," "*(t.find{|s|s>i=$`.size}-i)while~/\t/ print end ``` edit: Added two lines that makes the last read tabstop repeat so that tabstop specifications of a single number also works correctly `i` is a temporary variable for holding the last parsed tabstop. `t` is the list of tabstobs, parsed from the `gets.scan` line. For good measure we add 81 multiples of the last parsed tabstop. the `while gets` loop keeps going until there is no more input. For each line of input we substitute tabs for spaces, one tab at the time because the string moves as we add the spaces and we must recalculate the correct tabstop. [Answer] ## Pascal, 441 B * The Pascal programming language is standardized by ISO standards 7185 (“Standard Pascal”) and 10206 (“Extended Pascal”). Since the notion of command-line arguments something highly specific, not universally found on all computing systems, Pascal lacks of a standardized facility to access command-line arguments (if such exist). Therefore the following complete `program` expects the tabulator specification given on the first line of `input`. * The tabulator stop specification reading algorithm uses the built‑in `read` procedure. Such will allow and ignore leading blanks. Thus `8, 12, 14, 15` is accepted, too. However, relative tabulator stop specifications are only processed correctly if the plus sign is immediately adjacent to the comma. * With respect to (POSIX™ locale) blank characters, the Pascal programming language only guarantees there is *a* space character. The provision of a tabulator character is an implementation-defined characteristic. Obviously the following program requires that there is a horizontal tabulator character in the utilized implementation. * The golfed version omits certain verification steps (non-empty `input`, first tabulator specification must be non-relative). It is unclear whether such vigorous enforcement is required by the task specification. ``` program e(input,output);var t:set of 1..80;c,p:1..80;begin read(p);t:=[p];while','=input^do begin get(input);if'+'=input^then begin read(c);p:=p+c end else read(p);t:=t+[p]end;readLn;if[]=t-[p]then begin for c:=1 to 80 do if c mod p=0 then t:=t+[c]end;p:=1;while not EOF do begin if EOLn then begin writeLn;p:=1 end else begin if' '=input^then repeat p:=p+1;write(' ')until p-1 in t else begin write(input^);p:=p+1 end end;get(input)end end. ``` Ungolfed: ``` program expand(input, output); const { The character count of the longest line this program can process. } lineIndexMaximum = 80; type { A valid character index in an `input` line. } lineIndex = 1‥lineIndexMaximum; { A set of valid character indices. } lineIndices = set of lineIndex; var { This mimics a mechanical typewriter implementation that has retractable pins installed catching the carriage. } tabulatorStop: lineIndices; { Where are we at in the currently processed line. } position: lineIndex; { Processes an input line containing a tabulator stop specification. ┈┈┈ } procedure processTabulatorStopSpecification; var { In Pascal `for`-loop counter variables must be declared in the _closest_ containing block. } column: lineIndex; begin { A negative number will be caught by the `lineIndex` data type. } read(input, position); tabulatorStop ≔ [position]; while input↑ = ',' do begin { Skip comma. } get(input); { “A `+` prefix indicates a relative difference to the previous value in the comma-separated list.” } if input↑ = '+' then begin read(input, column); position ≔ position + column; end else begin read(input, position); end; tabulatorStop ≔ tabulatorStop + [position]; end; { Discard the rest of the line, especially the end-of-line mark. } readLn(input); { “In the case of a single number, it is repeated as if multiples of it occurred in a comma-separated list.” } if tabulatorStop − [position] = [] then begin for column ≔ 1 to lineIndexMaximum do begin if column mod position = 0 then begin tabulatorStop ≔ tabulatorStop + [column]; end; end; end; end; { Expands `input` lines according to `tabulatorStop`. ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ } procedure expandTabulatorCharacters; begin position ≔ 1; while not EOF(input) do begin if EOLn(input) then begin { `Input` is a variable possessing the data type `text`. A `text` file automatically replaces the character (sequence) that indicates the end-of-line with a single space character (`' '`). The only /universally/ valid way to emit an end-of-line character (sequence) is `writeLn`. } writeLn(output); { Reset `position` to the beginning of a new line. } position ≔ 1; end else begin { Note, as this might not be properly displayed, this checks for a tabulator character. } if input↑ = ' ' then begin { “Tabs should always expand to at least one space.” Ergo elect a `repeat … until` loop. } repeat begin write(output, ' '); { Cannot fail: “All expanded tabstops […] is assumed to be a maximum of 80 columns wide.” } position ≔ position + 1; end until position − 1 in tabulatorStop; end else begin write(output, input↑); { Note, fatal error if exceding `lineIndexMaximum`. } position ≔ position + 1; end; end; { Advance the reading cursor. } get(input); end; end; { ─── MAIN ───────────────────────────────────────────────────────────── } begin { Accessing `input↑` is invalid if `input` is an empty file. } if not EOF(input) then begin { “The first value in the list must be absolute […]” } if input↑ ≠ '+' then begin processTabulatorStopSpecification; expandTabulatorCharacters; end; end; end. ``` ]
[Question] [ Your goal is to input any arbitrary text, such as: ``` This is some text ``` And output that text formatted as code for posts (SE-flavored Markdown) and comments (mini-Markdown) on Stack Exchange, such as: ``` `This is some text` `This is some text` ``` However, it gets trickier. Consider the input: ``` Perl has a variable called $` ``` The output must be ``` `` Perl has a variable called $` `` `Perl has a varaible called $\`` ``` The full rules for the formatting are: * Full posts (full SE Markdown) + Step 1: count the least number for which there are not exactly that many consecutive backticks in the string. Let's call this `n`. (For example, for the string `potato`, `n` is 1, for `this is a backtick: ``, `n` is 2, and for `` `` ``` ````` ```````, `n` is 4.) + Step 2: wrap the string in `n` backticks. If the string starts or ends with a backtick, you must wrap with spaces as well. (For example, `potato` becomes ``potato``, `this is a backtick: `` becomes ``` this is a backtick: ` ```, and `` `` ``` ````` ``````` becomes ````` ` `` ``` ````` `````` `````. * Comments (mini-Markdown) + Wrap in ``` and escape all ```'s with `\``. (For example, `potato` becomes ``potato``, `this is a backtick: `` becomes `this is a backtick: \``, and `` `` ``` ````` ``````` becomes `\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest answer in byte count wins. [Answer] ## APL (90) (Yes, the APL charset does fit in a byte, here's IBM's [codepage 907](http://www-03.ibm.com/systems/resources/systems_i_software_globalization_pdf_cp00907z.pdf).) ``` {⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'} ``` This is a function that takes a string, and returns an array of two strings, where the first string is the *comment* representation and the second string is the *full post* representation. Tests: ``` backtickify←{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'} ↑backtickify 'potato' `potato` `potato` ↑backtickify 'this is a backtick: `' `this is a backtick: \`` `` this is a backtick: ` `` ↑backtickify '` `` ``` ````` ``````' `\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\`` ```` ` `` ``` ````` `````` ````       ⍝ testcase for not wrapping with spaces       ↑backtickify 'no`spaces``at````the`edges' `no\`spaces\`\`at\`\`\`\`the\`edges` ```no`spaces``at````the`edges```  ``` Note: I gave the function a name for readability's sake, this is not strictly necessary to use it (you can just put the argument next to the anonymous function) so I didn't count it. [Answer] ## Ruby, 119 ``` s=gets.chop c=1 c+=1while s=~/([^`]|\A)#{?`*c}([^`]|\z)/ puts ?`+s.gsub('`','\\\\`')+'` '+?`*c+(s=~/$`|`^/?" #{s} ":s)+?`*c ``` Ungolfed: ``` def backtickify str, comment = false return "`#{str.gsub '`', '\\\\`'}`" if comment c = 1 c += 1 while str =~ /([^`]|\A)#{?` * c}([^`]|\z)/ str = ' ' + str + ' ' if str[0] == ?` || str[-1] == ?` return ?` * c + str + ?` * c end ``` ]
[Question] [ My home town, [Rhyl](http://maps.google.co.uk/maps?q=rhyl&um=1&ie=UTF-8&hq=&hnear=0x48652618418b2481:0xfce1c44350b2b6e1,Rhyl,+Denbighshire&gl=uk&ei=xBELT6mLBdC3hAe7pICxCQ&sa=X&oi=geocode_result&ct=title&resnum=3&ved=0CGIQ8gEwAg), has a one-way traffic system which seems to have been designed to keep people away from their destination for as long as possible. Your task, should you choose to attempt it, is to produce a program to give the shortest route through such a traffic system. ## Input Input will be on `STDIN`, and will be a list of start and end points followed by a blank line followed by a list of queries, as follows: ``` A B B A B C C D D C A D C A B A ``` Each road can only be travelled in the direction(s) given, so, in the above example the road A - B is a two way street whereas B - C is a one-way street from B to C. Travelling from C to B is prohibited. Start and end points will all be represented by a single upper-case letter. ## Output Output should be the shortest route (measured by number of points visited) from the given start point to the given end point for each query received. If no such route exists, output a blank line. If more than one shortest route exists, output the first when sorting all shortest routes lexicographically. For the above example the output would be: ``` A B C D B A ``` ## Test Scripts As before I'm providing tests for this task based on scripts written by [Joey](https://codegolf.stackexchange.com/users/15/joey) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero):- * [Bash](http://www.garethrogers.net/tests/oneway/test) * [PowerShell](http://www.garethrogers.net/tests/oneway/test.ps1) and also tests and expected output for anyone who can't use the above scripts * [Plain text](http://www.garethrogers.net/tests/oneway/test.txt) Usage: `./test [your program and its arguments]` ## Rewards All answers which have obviously had some attempt at golfing that meet the spec and pass all the tests will get my upvote. The shortest working answer by 26/01/2012 will be accepted. [Answer] ## Haskell, ~~223~~ 207 characters ``` main=interact$unlines.f.break null.map words.lines s%[f,t]=[[f]]#t where[]#_="";x#t|y@(_:_)<-[z|z<-x,last z==t]=unwords$minimum y|1<3=s&x#t s&z=[x++[b]|x<-z,[a,b]<-s,last x==a,notElem b x];f(s,_:q)=map(s%)q ``` [Answer] ## Python (2.x), 382 369 358 338 323 318 characters All tips and comments welcome! ``` import os;u=str.split;l=u(os.read(0,1e9),'\n') p,g,c=l.index(''),{},map;o=g.setdefault def f(g,s,e,q=[]):q=q+[s];y=([],[q])[s==e];[c(y.append,f(g,n,e,q))for n in set(o(s,[]))-set(q)];return y for k,v in c(u,l[:p]):o(k,[]);g[k]+=v for w,e in c(u,l[p+1:]):h=sorted(f(g,w,e));print''if not h else' '.join(min(h,key=len)) ``` Should pass the tests in this form. Feed input via stdin, e.g. `python shortestroute.py < test.txt`. [Answer] # C:450,437,404,390 characters ``` #include<stdio.h> #include <string.h> r[99][99],p[99],q[99],m[99],i,j,x,y,s; char t[9],e[9999]; F(k) { m[k]^s?r[p[k]=q[i]][k]?m[q[j++]=k]=s:0:0; if(++k<99)F(k); } f() { F(0); if(++i^j)f(); } P(o) { if(p[o])P(p[o]); *t=m[o]^s?0:o; strcat(e,t); } w() { gets(t); r[*t][t[2]]=*t?w():0; } W() { gets(t); x=*t,x?y=t[j=2],s=x+y*99,m[q[t[2]=i=p[x]=0]=x]=s,f(),P(y),strcat(e,"\n"),W():0; } main() { w(); W(); puts(e); } ``` ]
[Question] [ In a given 2d grid of positive integers (representing different types of "bubbles"), there are one of two actions that you can do each "step". You can either: 1. Pop an island (a connected group of bubbles - two bubbles that are diagonally adjacent are not considered connected) of the same type of bubbles, given that the island consists of **at least 2 bubbles** AND at least one bubble in said island has **no bubbles above it**. Or, 2. Drop a **single** bubble of any type into any column, given that the chosen column is **not filled** to the top of the grid. After one of these two steps, all bubbles will **fall** towards the bottom of the grid, and the next step will start. The grid can also include `0`'s, which represent empty space. # Task Your task is: Given a \$m\times n\$ 2d grid of positive integers representing a grid of bubbles and the optional \$m\$ and \$n\$ and input, determine the fewest amount of moves in which the entire grid can be cleared of bubbles. The input grid is guaranteed to be clearable. # Worked example ``` 22222 21212 22222 21212 22222 ``` The first step will be to first pop the island of `2`'s. After all the bubbles have fallen, the grid will then look like this, where the `0`'s represent empty space: ``` 00000 00000 00000 01010 01010 ``` The second step will be to drop a `1` bubble in the middle column, so that the grid now looks like this: ``` 00000 00000 00000 01010 01110 ``` And the final step is to pop the island of `1`'s, clearing the entire grid. # Test Cases ``` m, n grid -> output 5, 5 22222 21212 22222 21212 22222 -> 3 7, 7 1111111 2222222 1111111 2222222 1111111 2222222 1111111 -> 7 7, 6 000000 121212 212121 121212 212121 121212 212121 -> 22 2, 7 0000000 1000001 -> 4 8, 1 0 1 2 2 2 2 2 1 -> 5 8, 2 00 10 20 20 20 20 20 10 -> 4 ``` If any of y'all need it, I also made a (pretty bad) tool that will take in a list of steps (more info in the TIO link) and output the board state after those steps have been taken: [Try It Online!](https://tio.run/##rVbfb9s2EH7nX3F1HmytsmE7aTZ484AiQYa9DH4othWuUC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K9TgydKOL7VtiQ@TjFAxVcqu9kb0WIWPse1fPvKu8kEdX1bApDEfannp1MKzU5BTV6jQRYNLNVRiwrVtHizgJ4OHWvu0R5iwYIrmfnoe56vSKX@Zi2mGNIVMzwL5QLwxHCuUpw2@agw26oY1tMMVl462T6IEAWbRizkzB2zfuY3/dHIEU@PNo5Fx8bMQFAc@zT131hj2loBl9d/NCiQKBsU5AN@yFAlr5jSlSKJiR3A4Xs8XUftZCasUXQB1qH@FGU4EiHdVL1kwLU4ahG98lzhEF03x6HRPD1qNf5xfGFC2@Jk04kwqUppK4s8s4X/XFl1nga8SmO4zCBv/n/fzrR09P3MVyKIT9iNKY/wb@jb75dwxgnagZDGPN6jOsRr0dQa6/hnG1GOJvXlXbMv@f8e1F5fTjhRVryvYDzb/ien/SdwQe4aGxoPYNLthyy5BLxiH8B) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes for each language wins! [Answer] # Python3, 901 bytes: ``` E=enumerate def B(b): P,R,s=[(x,y)for x,j in E(b)for y,k in E(j)if k],[],[];p=P while p: x,y=p[0];q=[(x,y)];s+=p[0], while(o:=[X for x,y in q for X in[(x+1,y),(x,y+1),(x-1,y),(x,y-1)]if X in P and b[x][y]==b[X[0]][X[1]]and(X in s)^1]):q+=o;s+=o R+={*q},;p=[i for i in p if(i in s)^1] return R F=lambda b:[*map(list,zip(*[[0]*i.count(0)+[j for j in i if j]for i in zip(*b)]))] def f(b): q,S=[(b,0)],{} while q: b,c=q.pop(0) if sum(sum(b,[]))<1:return c I=B(b) for i in I: if len(i)>1and sum(all(b[x-t][y]==b[x][y]or 1>b[x-t][y]for t in range(x+1))for x,y in i): W=eval(str(b)) for x,y in i:W[x][y]=0 if(str(w:=F(W))in S)^1or-~c<S[str(w)]:q+=(w,c+1),;S[str(w)]=c+1 for y,C in E(zip(*b)): if C[0]<1: for v in{j for k in b for j in k if j}: W=eval(str(b));W[0][y]=v if(len(B(e:=F(W)))<=len(I))&((str(e)in S)^1or-~c<S[str(e)]):q+=(e,c+1),;S[str(e)]=c+1 ``` [Try it online!](https://tio.run/##jVJtT9swEP68/AqLScNuXdSUF00p5gMIpH6ZEEwqUuZNSesMlzSvLpAh9te7OzukMKppSdrkXp7nzs9d0ZjbPNv/XFTr9blQ2Wqpqsgob64SckpjFnjkkl/xWoT0kTcsySvyyBdEZ@Qcomg2/M6ZC6YTcid5iM@4EJceebjVqSIFkACqEUU4lOOypZLjum89HKI2keaBCG@Iq9EgaWmNG/gETN8HFEds38f3oLMHPpNQG/PIJYmyOYnDRxk2Uog4vIESEv59KSFCbVLNvvuSBWVf5NhFDh1c9cVTr3zm0HiobVmNmQXRCdUdxiOVMqsqI1fehUijZTyPSByEvWVU0FTXhv/SBe2FULKn92b5KjN0yPrhwhJa2YArIQvZFbCAmEnGJLGqJ071kl@DUDEfMsmfnl@kLFHKmM9EuVfkBXCDCXz1aknxF4PyjB37QdvlDMITgXOEj67kBEkQlqqManbio2IIj9KUgnID86KdFRFg/knnRhaDLFWU/VQ4FcZeTUwzS06mQt1HKa1NBcWZdb3OCqbtgIY2BBpj5kMgLuiUMci4BrXzavB7dnwd2hCTOC76wGc4/XHnFWC3h2v4mdvEVlP2cs4zmAeI0nVxD2lPbiZ2d@PNeO7seJ5d7l@nGE@BB5u@d1HoGhU8partmx0LdEwY@0QtSG07imJu9ah6cxblzrLGHTD5jziPqrldhQ/tMEO3ZjozXLPNAiU6NaqiX/JMcRLv1UWqDd39lu3CRnle7BNBdnZ2vBFe3siH@/03JsQjAS/fXc4NSf9pW4J9JBjay/Nbdvv@l2WRBxskQO3LBQ5twIN63e0CRw4Byd7o7eMPMcErKhCKJnQjJSwq2@Ieofvje/8@@MlXVRsyi2pFjF6qmuQrs4XiYDvz4Xb3EbjXfwA) ]
[Question] [ # Introduction to Mahjong tiles Mahjong (麻雀) is a board game that originates from China. Mahjong tiles used in this challenge are in Unicode points U+1F000 – U+1F021: ``` 🀀🀁🀂🀃🀄🀅🀆🀇🀈🀉🀊🀋🀌🀍🀎🀏🀐🀑🀒🀓🀔🀕🀖🀗🀘🀙🀚🀛🀜🀝🀞🀟🀠🀡 ``` They are categorized as: * **Winds** (風牌): 🀀(East Wind), 🀁(South Wind), 🀂(West Wind), 🀃(North Wind) * **Dragons** (三元牌): 🀄(Red Dragon), 🀅(Green Dragon), 🀆(White Dragon) * **Ten Thousands** (萬子): 🀇(One of the Ten Thousands) through 🀏(Nine of the Ten Thousands) * **Bamboos** (索子): 🀐(One of the Bamboos; note that it depicts a bird) through 🀘(Nine of the Bamboos) * **Circles** (筒子): 🀙(One of the Circles) through 🀡(Nine of the Circles) * Winds and Dragons are together called **Honors** (字牌). * Ten Thousands, Bamboos and Circles are each called a **suit** and together called **Numbers** (数牌). They have **ranks** from 1 to 9. * Among Numbers, the Ones and the Nines are called **Terminals** (老頭牌). The Twos through the Eights are called **Simples** (中張牌). * Honors and Terminals are together called **Orphans** (幺九牌). Every Mahjong tiles have 4 copies of themselves. # Mahjong Hand A legal **Hand** consists of: * A **Head** (対子), which is 2 identical tiles. * 4 **Bodies** (面子), each which is either: + A **Sequence** (順子), which is 3 consecutive Numbers with same suit. + A **Triplet** (刻子), which is 3 identical tiles. Hence, a Hand consists of 14 tiles. There are exceptional valid Hands. **Seven Heads** (七対子), which is 7 *distinct* Heads, and **Thirteen Orphans** (国士無双), which collects all 13 Orphans with an additional Orphan. # Tenpais and Shantens 13 Mahjong tiles will be given as the input. If an additional tile would make a valid Hand, this is called **Tenpai** (聽牌). Tenpai is zero Shantens. If a tile must be exchanged to be Tenpai, this is **1-Shanten** (1向聴). If a tile must be exchanged to be 1-Shanten, this is **2-Shantens**, and so on. The objective is to output the number of Shantens. # Examples 🀇🀇🀇🀎🀎🀎🀓🀓🀙🀚🀛🀟🀠 : **Tenpai** waiting for 🀞 or 🀡 to make a Sequence. An example of **Two-sided Wait** (兩面待機). 🀀🀀🀇🀇🀍🀎🀏🀕🀖🀗🀜🀝🀞 : **Tenpai** waiting for 🀀 or 🀇 to make a Triplet. An example of **Wait for a Triplet** (双碰待機). 🀊🀋🀌🀍🀎🀏🀐🀑🀘🀘🀘🀚🀚 : **Tenpai** waiting for 🀒 to make a Sequence. An example of **One-sided Wait** (邊張待機). 🀅🀅🀇🀈🀉🀓🀓🀓🀙🀚🀛🀜🀞 : **Tenpai** waiting for 🀝 to make a Sequence. An example of **Wait for the Middle** (坎張待機). 🀇🀇🀇🀌🀍🀎🀓🀖🀗🀘🀝🀞🀟 : **Tenpai** waiting for 🀓 to make a Head. An example of **Wait for a Head** (單騎待機). 🀇🀈🀉🀉🀊🀋🀌🀍🀐🀐🀓🀔🀕 : **Tenpai** waiting for 🀈, 🀋, or 🀎. This example demonstrates how multiple ways of waiting can be combined. 🀇🀇🀇🀈🀉🀊🀋🀌🀍🀎🀏🀏🀏 : **Tenpai** waiting for any of Ten Thousands. This is called **Nine Gates** (九蓮宝燈), and has the highest possible number of tiles to wait for to be a "normal" Hand. 🀄🀈🀈🀊🀊🀌🀌🀐🀐🀑🀑🀝🀝 : **Tenpai** waiting for 🀄 to make a Head. An example of Seven Heads. 🀀🀀🀁🀂🀃🀄🀅🀆🀇🀏🀐🀘🀙 : **Tenpai** waiting for 🀡. An example of Thirteen Orphans. 🀀🀁🀂🀃🀄🀅🀆🀇🀏🀐🀘🀙🀡 : **Tenpai** waiting for any of Orphans. Another example of Thirteen Orphans. 🀀🀀🀀🀁🀁🀁🀂🀂🀂🀃🀃🀃🀃 : **1-Shanten**. Note that this is not Tenpai waiting for 🀃 because it would be a fifth 🀃. 🀈🀈🀈🀊🀊🀌🀌🀐🀐🀑🀑🀝🀝 : **1-Shanten**. Note that this is not Tenpai for Seven Heads because getting 🀈 will result in a duplicated Head. 🀁🀁🀃🀃🀄🀄🀉🀉🀋🀏🀓🀗🀞 : **2-Shantens**. 🀀🀁🀂🀃🀈🀋🀎🀑🀔🀗🀚🀝🀠 : **6-Shantens**. This is the highest possible number of Shantens. You can demonstrate arbitrary examples [here](https://uradora.com/#/). (for 13 or 14 tiles) # Rules about code golf * Input type and format doesn't matter, but it must consist of the Unicode characters above. In C++, valid examples include `std::u8string` (sorted or not) , `u32char_t[13]`, and `std::multiset<u32char_t>`. * Output type and format doesn't matter either. * Invalid input (not exactly 13 tiles, contains 5 copies of the same tile, contains a character not in U+1F000 – U+1F021, etc) falls into *don't care* situation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~80~~ ~~77~~ ~~73~~ ~~72~~ ~~77~~ 74 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₂Ý8+3ä€ü3€`4иML3δи©«4㮀¦©âʒ˜D¢à5‹}®7.Æ«8L•1«þï•₆в«D¸â«ε˜•1óñ•+çJœIœδ.L}W< ``` -5 bytes thanks to *@Grimmy*, and also for teaching me about a hidden builtin +5 bytes to fix two bugs Brute-force approach that's extremely slow, so obviously no TIO with test cases. Although TIO is too slow for the entire solution, I've added a TIO after each section so you can verify the individual parts work as intended. Note that the final TIO-link only uses a portion of each hand (including the input). ### General explanation: 1. Generate a list of all valid 14-tile hands 2. Get every possible permutation of every 14-tile hand 3. Get the input-hand and get all its permutations as well 4. Get the Levenshtein distance between every input-hand permutation and every valid 14-tile hand permutation 5. Keep the lowest Levenshtein distance across all these checks, and decrease it by 1 to get the number of Shantens ### Code explanation: Create a list of all overlapping consecutive triplets of the Numbers: ``` ₂Ý # Push a list in the range [0,26] 8+ # Add 8 to each to make the range [8,34] 3ä # Split it into 3 equal-sized parts: [[8,16],[17,25],[26,34]] € # For each inner list: ü3 # Create all overlapping triplets of this list # [a,b,c,d,e,...] → [[a,b,c],[b,c,d],[c,d,e],...] €` # Then flatten one level down to have a list of triplets 4и # And repeat each consecutive triplet 4 times in the list ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UVPT4bkW2saHlzxqWnN4jzGQTDC5sOP/fwA) Create a list of all possible triplets of all tiles: ``` M # Push the largest value on the stack thus far (including inner lists), # which is 34 L # Pop and push a list in the range [1,34] δ # For each value in this list, 3 и # Repeat it 3 times as list © # Store the list of identical triplets in variable `®` (without popping) ``` [Try it online.](https://tio.run/##ASEA3v9vc2FiaWX//@KCgsOdOCvDvDMgNNC4TUwzzrTQuMKp//8) Then: ``` « # Merge the two lists together 4ã # And take the cartesian product of 4 with this list ``` Which results in all possible combinations of 4 Bodies: [Try it online](https://tio.run/##yy9OTMpM/f//UVPT4bkW2saHlzxqWnN4jzGQTDC5sMPXx/jclgs7Dq08tNrk8OL//wE). Then we'll generate all possible Heads: ``` ® # Push the list of identical triplets from variable `®` €¦ # Remove one value from each so we have identical pairs (Heads) instead © # Store that as new variable `®` (without popping) ``` [Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//zM0TDPOtNC4wqkKwq7igqzCpsKp//8) And create every possible combination of these 1 Heads + 4 Bodies: ``` â # By taking the cartesian product of the two lists ʒ } # And then filtering it so we won't use more than 4 of the same tile: ˜ # Flatten the pairs/triplets to a single list D¢ # Duplicate it, and count for each item how much it occurs à # Get the maximum for the tile that occurs the most 5‹ # And check that this it smaller than 5 ``` Now we have all possible regular 14-tile hands: [Try it online](https://tio.run/##AUgAt/9vc2FiaWX//@KCgsOdOCszw6TigqzDvDPigqxgNNC4TUwzzrTQuMKpwqs0w6PCruKCrMKmwqnDosqSy5xEwqLDoDXigLl9//8). Next we'll also create the special type of 14-tile heads, starting with the 7 Heads: ``` ® # Push the list of identical pairs (Heads) from variable `®` again 7.Æ # Get all 7-element combinations of these distinct heads « # And merge it to the earlier created valid 14-tile hands ``` [Try it online.](https://tio.run/##AU4Asf9vc2FiaWX//@KCgsOdOCszw6TigqzDvDPigqxgNNC4TUwzzrTQuMKpwqs0w6PCruKCrMKmwqnDosqSy5xEwqLDoDXigLl9wq43LsOG//8) And the final valid 14-tile hands are the 13+1 Orphans: ``` 8L # Push a list in the range [1,8] (4 Winds, 3 Dragons, and One of the Ten Thousands) •1«þï• # Push compressed integer 27700378 ₆в # Convert it to base-36 as list: [16,17,25,26,34] (Nine of the Ten Thousands, # One & Nine of the Bamboos, One & Nine of the Circles) « # Merge those together D¸ # Duplicate this list of 13 Orphans, and wrap it into a list â # And take the cartesian product of the two « # And also merge those to the earlier created valid 14-tile hands ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fwudRwyLDQ6sP7zu8Hsh61NR2YdOh1S6Hdhxe9P8/AA) Now that we finally have all our valid 14-tile hands, we're going to get all their permutations as well as the permutations of the input, and check the Levenshtein-distance between each possible combination. After which the lowest Levenshtein-distance across all permutation-comparisons minus 1 is our number of Shatens: ``` ε # Map over each valid 14-tile hand: ˜ # Flatten the pairs/triplets to a single 14-length list •1óñ• # Push compressed integer 126975 + # Add it to each value in the list ç # Convert each from integer to their unicode character J # And join it together to a single string œ # Get all permutations of this hand Iœ # Then push the input, and get all its permutations as well δ # And then check for every possible combination of the permutations: .L # What the Levenshtein-distance is between the two ``` And finally get the (flattened) lowest one to calculate the number of Shantens: ``` }W # After the map: push the flattened lowest Levenshtein-distance < # And subtract it by 1 to get the number of Shantens # (after which this is output implicitly as result) ``` [Try it online with just a portion of the valid hands, each cut into a smaller hand, and with added debug-lines.](https://tio.run/##VY9BSwJBFMfvfophT4YZiIoSSQQGGdsx6ti4@8KFbVacWYVAEA/dNMhTYRRrFLJhVAYKUTCDlwTxM@wn6BvYTBrV4T/vvZnfe@8/DsV5C2azZFbbwsSkyKVgorB4X1pF2npQr4vLdCQuboL6vXiNy/MgMR3s6PFJfzrgXe4nRIf35DW/5V3hfZyN21nuietkUBtWeS8lOqrxPCWG3E/rQc2LcV@8iQeZBfWT6RP3s3wgPO5T3smEEtldbRMbBVTEJWZhGxWkJXRoY8aASFuqMhxShhKTFXOQSyzDMQExywaKwgqPUusY0ML/5GXcVkvFs3iUMSLutvd5p5oJaRu2jYpQOnIZZpZDqCq@183bRi0F5UjRZf8xTFEFbFtROTlq1FoOaTqUgdACA4sg06IMEwNQHlgFgCCQ/5nPnPOT/oquZutOBSj75aMoprC9teXZ7POqdirVkGpKXfzJG4u35iL@5I0v) [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1«þï•` is `27700378`; `•1«þï•₆в` is `[16,17,25,26,34]`; and `•1óñ•` is `126975`. ## How slow? To give you an idea of how slow this approach is, here are some numbers: *Regular hands: \$34×118^4-X\$* * There are [\$118\$ valid Bodies](https://tio.run/##yy9OTMpM/f//UVPT4bkW2saHlzxqWnN4jzGQTDC5sMPXx/jclgs7Dq08tNr20Db7dJ3//wE) (including duplicated subsequent triplets for the Numbers, which each occur four time), and thus \$118^4\$ combinations of 4 Bodies (yes, this includes duplicated combinations due to the duplicated subsequent Number triplets). * There are [\$34\$ valid Heads](https://tio.run/##ASQA2/9vc2FiaWX//zM0TDPOtNC4wqkKwq7igqzCpsKpPcK2P2cs//8), and thus \$34×118^4\$ combinations of 1 Head + 4 Bodies. * After which \$X\$ (*TODO: do the math..*) combinations are removed, because they contain a certain tile more than four times. *Special hands: \$\binom{34}{7} + 13\$* * There are again \$34\$ valid Heads, and thus \$\binom{34}{7}\$ combinations of 7 distinct Heads. * There are \$13\$ Orphans (\$4\$ Winds + \$3\$ Dragons + \$3\$ Ones + \$3\$ Nines), and thus [\$13\$ valid Orphan hands](https://tio.run/##yy9OTMpM/f/fwudRwyLDQ6sP7zu8Hsh61NR2YdOh1S6HdhxeZHtom326zv//AA). There are therefore a total of \$34×118^4-X + \binom{34}{7} + 13 = 6597224013-X\$ valid 14-tile hands. *Comparing the input-hand and a single valid-hand: \$14!×13!\$* * Getting all permutations of the 14-tile hands means there are \$14!\$ permutations. * Getting all permutations of the 13-tile input-hand means there are \$13!\$ permutations. * Checking each permutation of a valid 14-tile hand with each permutation of the input-hand are therefore \$14!×13! = 542861032610856960000\$ valid permutation-pairs. **So in conclusion:** Assuming a standard Levenshtein algorithm is used in the `.L` builtin, the complexity is in general about \$O(n^2)\$ (\$n\$ being the length of the string). Which in this case would be complexity \$O(14^2) = O(196)\$ for each of the \$14!×13! × (34×118^4-X + \binom{34}{7} + 13) = \$\$3581375840062321621020180480000 - 542861032610856960000×X\$ permutation-combinations across all valid hands (after which we still have to get the flattened \$minimum-1\$). Safe to say: way too slow for a TIO link for even a single test case, let alone a test suite of all test cases. ;) ]
[Question] [ This is a follow up to [Count arrays that make unique sets](https://codegolf.stackexchange.com/questions/174407/count-arrays-that-make-unique-sets) . The significant difference is the definition of uniqueness. Consider an array `A` of length `n`. The array contains only positive integers. For example `A = (1,1,2,2)`. Let us define `f(A)` as the set of sums of all the non-empty contiguous subarrays of `A`. In this case `f(A) = {1,2,3,4,5,6}`. The steps to produce `f(A)` are as follows: The subarrays of `A` are `(1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2)`. Their respective sums are `1,1,2,2,2,3,4,4,5,6`. The set you get from this list is therefore `{1,2,3,4,5,6}`. We call an array `A` **unique** if there is no other array `B` of the same length such that `f(A) = f(B)`, except for the array `A` reversed. As an example, `f((1,2,3)) = f((3,2,1)) = {1,2,3,5,6}` but there is no other array of length `3` that produces the same set of sums. **Task** The task, for a given `n` and `s` is to count the number of unique arrays of that length. You can assume that `s` is between `1` and `9`. You only need to count arrays where the elements are either a given integer `s` or `s+1`. E.g. if `s=1` the arrays you are counting only contain `1` and `2`. However, the definition of uniqueness is with respect to any other array of the same length. As a concrete example `[1, 2, 2, 2]` is **not** unique as it gives the same set of sums as `[1, 1, 2, 3]`. You should count the reverse of an array as well as the array itself (as long as the array is not a palindrome of course). **Examples** `s = 1`, the answers for n = 2,3,4,5,6,7,8,9 are: ``` 4, 3, 3, 4, 4, 5, 5, 6 ``` For `s = 1`, the unique arrays of length 4 are ``` (1, 1, 1, 1) (2, 1, 1, 2) (2, 2, 2, 2) ``` `s = 2`, the answers for n = 2,3,4,5,6,7,8,9 are: ``` 4, 8, 16, 32, 46, 69, 121, 177 ``` An example of an array that is not unique with `s = 2` is: ``` (3, 2, 2, 3, 3, 3). ``` This has the same set of sums as both of: `(3, 2, 2, 2, 4, 3)` and `(3, 2, 2, 4, 2, 3)`. `s = 8`, the answers for n = 2,3,4,5,6,7,8,9 are: ``` 4, 8, 16, 32, 64, 120, 244, 472 ``` **Score** For a given `n`, your code should output the answer for all values of `s` from `1` to `9`. Your score is the highest value of `n` for which this completes in one minute. **Testing** I will need to run your code on my ubuntu machine so please include as detailed instructions as possible for how to compile and run your code. **Leaderboard** * **n = 13** by Christian Sievers in **Haskell** (42 seconds) [Answer] # Haskell ``` import Control.Monad (replicateM) import Data.List (tails) import qualified Data.IntSet as S import qualified Data.Map.Strict as M import qualified Data.Vector.Unboxed as V import Data.Vector.Unboxed.Mutable (write) import System.Environment (getArgs) import Control.Parallel.Strategies orig:: Int -> Int -> M.Map S.IntSet (Maybe Int) orig n s = M.fromListWith (\ _ _ -> Nothing) [(sums l, Just $! head l) | l <- replicateM n [s, s+1], l <= reverse l ] sums :: [Int] -> S.IntSet sums l = S.fromList [ hi-lo | (lo:r) <- tails $ scanl (+) 0 l, hi <- r ] construct :: Int -> Int -> S.IntSet -> [Int] construct n start set = setmax `seq` setmin `seq` setv `seq` [ weight r | r <- map (start:) $ constr (del start setlist) (V.singleton start) (n-1) (setmax - start), r <= reverse r ] where setlist = S.toList set setmin = S.findMin set setmax = S.findMax set setv = V.modify (\v -> mapM_ (\p -> write v p True) setlist) (V.replicate (1+setmax) False) constr :: [Int] -> V.Vector Int -> Int -> Int -> [[Int]] constr m _ 0 _ | null m = [[]] | otherwise = [] constr m a i x = [ v:r | v <- takeWhile (x-(i-1)*setmin >=) setlist, V.all (V.unsafeIndex setv . (v+)) a, let new = V.cons v $ V.map (v+) a, r <- (constr (m \\\ new) $! new) (i-1) $! (x-v) ] del x [] = [] del x yl@(y:ys) = if x==y then ys else if y<x then y : del x ys else yl (\\\) = V.foldl (flip del) weight l = if l==reverse l then 1 else 2 count n s = sum ( map value [ x | x@(_, Just _) <- M.toList $ orig n s] `using` parBuffer 128 rseq ) where value (sms, Just st) = uniqueval $ construct n st sms uniqueval [w] = w uniqueval _ = 0 main = do [ n ] <- getArgs mapM_ print ( map (count (read n)) [1..9] `using` parBuffer 2 r0 ) ``` The `orig` function creates all the lists of length `n` with entries `s` or `s+1`, keeps them if they come before their reverse, computes their sublist `sums` and puts those in a map which also remembers the first element of the list. When the same set of sums is found more than once, the first element is replaced with `Nothing`, so we know we don't have to look for other ways to get these sums. The `construct` function searches for lists of given length and given starting value that have a given set of sublist sums. Its recursive part `constr` follows essentially the same logic as [this](https://codegolf.stackexchange.com/a/174303), but has an additional argument giving the sum the remaining list entries need to have. This allows to stop early when even the smallest possible values are too big to get this sum, which gave a massive performance improvement. Further big improvements were obtained by moving this test to an earlier place (version 2) and by replacing the list of current sums by a `Vector` (version 3 (broken) and 4 (with additional strictness)). The latest version does the set membership test with a lookup table and adds some more strictness and parallelization. When `construct` has found a list that gives the sublist sums and is smaller than its reverse, it could return it, but we are not really interested in it. It would almost be enough to just return `()` to indicate its existence, but we need to know if we have to count it twice (because it is not a palindrome and we'll never handle its reverse). So we put 1 or 2 as its `weight` into the list of results. The function `count` puts these parts together. For each set of sublist sums (coming from `orig`) that was unique amongst the lists containing only `s` and `s+1`, it calls `value`, which calls `construct` and, via `uniqueval`, checks if there is only one result. If so, that is the weight we have to count, otherwise the set of sums was not unique and zero is returned. Note that due to lazyness, `construct` will stop when it has found two results. The `main` function handles IO and the loop of `s` from 1 to 9. ### Compiling and Running On debian this needs the packages `ghc`, `libghc-vector-dev` and `libghc-parallel-dev`. Save the program in a file `prog.hs` and compile it with `ghc -threaded -feager-blackholing -O2 -o prog prog.hs`. Run with `./prog <n> +RTS -N` where `<n>` is the array length for which we want to count the unique arrays. ]
[Question] [ Have fun with this one, [The Powder Toy](https://powdertoy.co.uk/) is a interesting challenge for golf, especially with filt logic. The thing that makes TPT a challenge is the many many many many ways to approach a problem: `Should I use Cellular Automaton rules, SWCH logic, Filt logic, subframe filt logic, and/or wall logic?` As such, a location for tips for TPT golfing would be quite helpful, so I made this question thread. This thread will likely use a lot of abbreviations. A lot of them will be in-game elements, so searching them up on [the Wiki](https://powdertoy.co.uk/Wiki.html) will bring you a lot of information about them, like what they are. Here are the most common ones you'll likely see in this thread, with their ingame description attached (and their full name), for people who don't want to go searching: * SPRK: Electricity. The basis of all electronics in TPT, travels along wires and other conductive elements. * FILT: Filter. Filter for photons, changes the color. * ARAY: Ray Emitter. Rays create points when they collide. * BTRY: Battery. Generates infinite electricity. * DRAY: Duplicator ray. Replicates a line of particles in front of it. * CRAY: Particle Ray Emitter. Creates a beam of particles set by its ctype, with a range set by tmp. * SWCH: Switch. Only conducts when switched on. (PSCN switches on, NSCN switches off) [List of all elements](https://powdertoy.co.uk/Wiki/W/Category:Elements.html) [Answer] # Only use subframe logic when it's smaller And, for more complex machines, it's often much smaller. Subframe generally imposes the overhead of creating solid SPRK (about 3 pixels for most directions, an extra pixel compared to just a BTRY), FILT 'channels' (for fast BRAY transfer), and minimizing the amount of nonsubframe logic, even if it's smaller, due to it being many times (4x to 20x-30x slower!) slower. Subframe logic is often good for complex operations (which is most of the challenges here), but for simpler ones, subframe logic is probably not optimal. [Answer] # Know your FILT modes FILT is, at least for FILT and subframe logic, the cornerstone of computing in TPT. And as such, it has a bunch of tricks to make your life easier, in the form of it's various modes. You set a FILT mode using `tmp`, but a comprehensive list that describes the intricacies of these modes isn't really a thing right now. FILT takes two inputs: it's own color (CTYPE) and the color of what it's interacting with, either BRAY or CRAY. I'll label these FILTC and INTRC, respectively, for this list. * Mode 0: The simplest mode, it sets INTRC to the value of FILTC, nothing more. ``` INTRC = FILTC ``` * Mode 1: This is a binary AND, it ands together INTRC and FILTC, setting INTRC to the result. ``` INTRC = INTRC & FILTC ``` * Mode 2: This is a binary OR, it ors together INTRC and FILTC, setting INTRC to the result. ``` INTRC = INTRC & FILTC ``` * Mode 3: This mode is slightly more complicated, it ands together the inverse of FILTC and INTRC, setting INTRC to the result. ``` INTRC = INTRC & (~FILTC) ``` * Mode 4: This mode is a bit harder to describe. It's a red shift (binary left shift), The catch here is that the amount it shifts by is controlled by it's temperature, with the equation (Temperature-273.0)\*0.025, defaulting to a shift by 1 if the value is less than 1. You can acheive a shift of any required amount by multiplying the number of bits you need by 40, and adding 273.0. I'll call the amount shifted X. As such, INTRC is shifted left by X, setting INTRC to the result. ``` X = (temperature-273.0)*0.025 INTRC = INTRC << X ``` * Mode 5: This is essentially mode 4, but with a right shift instead. See the information on mode 4 for how to use it. ``` X = (temperature-273.0)*0.025 INTRC = INTRC >> X ``` * Mode 6: Does nothing. ``` INTRC = INTRC ``` * Mode 7: Performs a binary XOR on INTRC and FILTC, setting INTRC to the result. ``` INTRC = INTRC ^ FILTC ``` * Mode 8: Performs a binary NOT on INTRC, setting INTRC to the result. ``` INTRC = ~INTRC ``` * Mode 9: Sets INTRC to a random color. ``` INTRC = rand() ``` * Mode 10: Performs a different version of a red shift. [TODO: figure out how to describe] ``` LSB = FILTC & (-FILTC) INTRC = INTRC * LSB ``` * Mode 11: Performs a different version of a blue shift. [TODO: figure out how to describe] ``` LSB = FILTC & (-FILTC) INTRC = INTRC / LSB ``` ]
[Question] [ ### Input: A 2D array containing two distinct (optional) values. I'll use **0** and **1** when explaining the rules. The input format is of course flexible. --- ### Challenge: Zeros are water, and ones are islands. In order to ensure loneliness, your task is to surround all islands with water by inserting rows and columns of zeros. **You don't want to waste water, so you must minimize the amount of water added. In case there are more than one solution that requires the same amount of water added, then you should add columns of water, not rows.** I'll show this in the test cases. --- ### Output: The new, modified 2D array. The output format is of course flexible. --- ### Test cases: Input and output are separated by dashes. Added zeros are shown in bold font. Use one of the answers [here](https://codegolf.stackexchange.com/q/129136/31516) if you want to convert the test cases to more convenient formats. ``` 1 --- 1 ``` --- ``` 1 1 --- 1 **0** 1 ``` --- ``` 1 1 1 1 --- 1 **0** 1 **0** **0** **0** 1 **0** 1 ``` --- ``` 1 0 0 1 --- 1 **0** 0 0 **0** 1 ``` Note that we added a column of zeros, not a row of zeros. This is because the number of necessary zeros is equal, and columns should be preferred. --- ``` 1 0 0 0 1 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 --- 1 0 0 0 1 **0** **0** **0** **0** **0** 0 1 0 1 0 **0** **0** **0** **0** **0** 0 0 1 0 0 **0** **0** **0** **0** **0** 0 1 0 1 0 ``` Note that we added rows, not columns, since that requires the least amount of extra zeros. --- ``` 0 0 1 0 0 0 1 1 1 0 --- 0 0 **0** 1 **0** 0 0 **0** **0** **0** **0** **0** **0** **0** 0 1 **0** 1 **0** 1 0 ``` This required both columns and a row. --- ``` 0 0 1 0 0 0 1 0 1 0 --- 0 0 **0** 1 **0** 0 0 0 1 **0** 0 **0** 1 0 ``` Better to add two columns than one row, since it requires less water. --- ``` 0 0 1 0 0 1 1 0 0 0 --- 0 0 1 0 **0** **0** 0 1 **0** **0** 1 0 0 0 ``` Better to add two rows than one column, since it requires less water. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` ṫƤ-S€ZƊ⁺FỊẠ Z_,,WƲ€ŒpẎ€Ʋ⁺€ẎLÞFL$ÞṚÇÞṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hztXHlugGP2paE3Ws61HjLreHu7se7lrAFRWvoxN@bBNQ/Oikgoe7@oAMIK9xF5AG8nwOz3PzUTk87@HOWYfbQdSq/4fbgVLuQJz1qGHOoW22MHBo26OGuf//R3NxRhvGcsXqgBk6CqhsHUxBA7CgAZogDBnCZSFcJPVwQQMsaqBG4VJmSJwyLKbBvIDkbHQRA4RHDBAQKmuIIYKuhnhdEFFDuIghTBToAAA "Jelly – Try It Online") Function returning a 2D array of integers. Note that naturally in Jelly singleton list displays as its value so `G` is used to format the output. --- * Link 1: Return (validity). * Link 2: Main program. --- The program runs in exponential time, but so-far I could not think of any polynomial time algorithm. Uses `Ƥ` on dyadic function, that feature postdates the challenge. [Answer] # [Python 2](https://docs.python.org/2/), ~~374~~ ~~346~~ ~~340~~ ~~339~~ ~~323~~ 317 bytes ``` R=range;L=len def f(a): w,h=L(a[0]),L(a);W=[] for i in R(2**w): A=zip(*a) for c in R(w):A[-c:-c]=[[0]*h]*(i&1<<c>0) for j in R(2**h): B=zip(*A);x=L(B[0]) for r in R(h):B[-r:-r]=[(0,)*x]*(j&1<<r>0) y=L(B);W+=[(w*h-x*y,x,B)]*all(sum(B[i][j:j+2]+B[i+1][j:j+2])<2for i in R(y-1)for j in R(x)) return max(W)[2] ``` [Try it online!](https://tio.run/##rZA/b4MwEMXn@lPcVNnGSDYjCZXCnClLBssDohBAhERuokC/PD2HkD9tqFSpgIB773fPPu@7Q7Frgr5fRTZpNtlsGdVZQ96zHHKasJDASRTRkiZaGibwy2brSBsC@c5CCWUDKxpwfkLyZRF9lnvKE0ZenJsOLloL7aehn5pIYwovDKflq5rP0zd5QatrUOGCIB6SFmzW4tqxWxtVR9qBRCzWvg19i6FUCsZbTK1cqj2nQucacbMe@ide@C3vRCtiZnhS1/TjuMXY0ugqrLzAePjvqbFi8@Buus5X7G6PLWMEbHY42ga2SUvXTAemd@e1Gc7LsbVjk3Bvy@YANSEbmlOtlTHYfBZHRcCEKGDSlM6UU@b4qJEaqlvbVZM/ie@BE7j6G/5b@mXQ20yPtXwyo7y/jSCAF7LqufyU/peQURh61KOsxrcboP8C "Python 2 – Try It Online") ]
[Question] [ In [this](https://codegolf.stackexchange.com/q/135127/56656) question I defined a "chain" function as a function that: * is a permutation, meaning that every value maps to and is mapped to by exactly one value. * and allows any value can be obtained from any other value by repeated applications of the function or its inverse. There are a lot of functions that do this and some of them are pretty simple (see the answers on that question). Now we are going to define a separate class of functions I am going to call "interwoven" functions. An interwoven function is a function on a set **A**, that has two infinite partitions **a0** and **a1** such that the function is a chain function on both **a0** and **a1**. This means that no value in **a0** can map to a value in **a1** under the function or vice versa. # Task Your task is to write a code that performs or defines an interwoven function on the positive integers. Your function can be anything as long as it satisfies the criteria for being interwoven. You should include a explanation as to why your function is interwoven in the answer. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better. [Answer] # Python, ~~46~~ ~~42~~ 37 bytes *5 bytes saved thanks to @notjagan* ``` lambda x:1<x<4and x*2%5or x-(x&2)*4+4 ``` [Try it online!](https://tio.run/##nYwxEoIwEEX7nOI3Sha1IIQGiSexiROimZGFyVCsp4@oN7B9//23vNbHzG2JcLiWp59uwUP6ZpDBeg6Q2uy6OUNOWvaGanuwRTbXGBU3nJAY2fN91E1HPZaceNVyxMjBVXAXVHTG5xC1kPrNpL6F9o9CeQM) Iterates the even and odd numbers with steps of 4 and links on 2 and 3: ``` => 22 => 18 => 14 => 10 => 6 => 2 => 4 => 8 => 12 => 16 => 20 => 24 => => 23 => 19 => 15 => 11 => 7 => 3 => 1 => 5 => 9 => 13 => 17 => 21 => ``` [Answer] # x86 32-bit machine code, 11 bytes ``` 48 34 02 40 40 34 02 48 7E FA C3 ``` [Try it online!](https://tio.run/##XZE9b8MgEIZn8yuurqJA7FT5kDokcZbMXTpVaiqLYGxTYWxh3BJF@et1sRM3bRlAPPfevcfBqmqaMda290Ix2SQcNrVJRPmQb9EfJMXhP9NCZR1D3BquFfg7H05xTI2LHBrD4xhjzbOK6gLPCSEglIEUdzsl6zOidQEYnn2MHjJZHqiEFKUr5CWcAacWebbUQGUIC@Q5255pXnFqVjfwW/ST@C45XJTI09wg4gNZI9Q5F1SoSws6YyGwnGqYTNzlg6ATAre6oIUIZiEcu2Pd089cuKI4CCxsIpg/kp52q3JzMCn2RwKmWxiJvfJDsKF7qSXkkjxI9uqJslwoDqxM@Mq/hu3NJinhNKhhNFu8uFrHCONG1SJTPOkbnpCUvNogeHNTHBo7wp0rYnfLwbIxnRSP92p8RW4Sjfsm53RGbfvFUkmzup0Wy4Xb3GdEzpbLbw "C++ (gcc) – Try It Online") Uses the regparm(1) calling convention – argument in EAX, result in EAX. In assembly: ``` f: dec eax xor al, 2 inc eax repeat: inc eax xor al, 2 dec eax jle repeat # Jump back if pre-decrement value was ≤1 ret ``` [![Graph of how this affects numbers](https://i.stack.imgur.com/MyK1W.png)](https://i.stack.imgur.com/MyK1W.png) [Answer] # JavaScript, ~~30~~ 24 bytes ``` a=>(a+=a&2?-4:4)<0?a*a:a ``` Sequences: 1. `... 19 15 11 7 3 1 5 9 13 17 21 ...` 2. `... 18 14 10 6 2 4 8 12 16 20 24 ...` **Code snippet** ``` f=a=>(a+=a&2?-4:4)<0?a*a:a console.log('23 19 15 11 7 3 1 5 9 13 17'.split` `.map(a=>f(a|0)).join` `); console.log('22 18 14 10 6 2 4 8 12 16 20'.split` `.map(a=>f(a|0)).join` `); ``` [Answer] # Dyalog APL, ~~24~~ 22 bytes ``` {x*1+0>x←4+⍵-8×2|⌊⍵÷2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqCi1DbQO7CiDTRPtR71Zdi8PTjWoe9XQB2Ye3G9UCVR1a8ah3s6mBAQA) Same chains as my [python answer](https://codegolf.stackexchange.com/a/138145/65326). ]
[Question] [ [Drunk Uncle](https://www.youtube.com/watch?v=PuduYMzY3Dc) (sorry M.E. and AUS for region lock) is a fictional character from Saturday Night Live. He often confuses words for others that sound like them. For this challenge you need to convert normal speech into drunkspeak. # Algorithm Translating to drunkspeak requires swapping the order of words in the text. Swapping is based on the *drunkenness similarity* of two words. Drunkenness similarity is defined as **the number of letters that two words have occuring at the same indices**. However, **two identical words have a drunkenness similarity of -1**. For example, `tree` and `friend` have a drunkenness similarity of 2, because they both have an 'r' at index 1, and an 'e' at index 3. All you have to do is find the two words in the text with the highest drunkenness similarity, then swap them. Once you swap two terms, they do not move any more. Then you look at the remaining swappable terms and swap the two that have the highest drunkenness similarity. You keep doing this until you can't swap any more. Then you output (or return, for a function) the updated text. # Specifics * For simplicity, input is a list of words consisting of characters in [A-Za-z] * Every input contains at least one word * Letter matching is case-insensitive: `A` matches with `a` (**Note:** Due to this rule `Dog` and `dog` are identical, and thus have a D.S. of -1) * If multiple pairs have the highest drunkenness similarity: 1. Of the words, that can maximize drunkenness similarity, pick the one with the lowest index in the list 2. Pair that word with the lowest-index word that maximizes drunkenness similarity # Examples 1. `Drunk Uncle needs your help` (title) * S1: Drunk<=>your (DS: 1) `your Uncle needs Drunk help` * S2: needs<=>help (DS: 1) `your Uncle help Drunk needs` * Output: `your Uncle help Drunk needs` 2. `I love fidget spinners` (boring example) * S1: I<=>love (DS: 0) `love I fidget spinners` * S2: fidget<=>spinners (DS: 0) `love I spinners fidget` 3. `dog eat dog ear` * S1: eat<=>ear (DS: 2) `dog ear dog eat` * S2: dog<=>dog (DS: -1) `dog ear dog eat` (this step just formality) 4. `Let me tell you a story` * S1: Let<=>me (DS: 1) `me Let tell you a story` * S2: tell<=>you (DS: 0) `me Let you tell a story` * S3: a<=>story (DS: 0) `me Let you tell story a` 5. `Too many money and purple people` * S1: purple<=>people (DS: 4) `Too many money and people purple` * S2: many<=>money (DS: 2) `Too money many and people purple` * S3: Too<=>and (DS: 0) `and money many Too people purple` Let me know if there are more examples you want me to cover. [Answer] # JavaScript - ~~286~~ 279 bytes ``` f=(a,n=(a=a.split` `).length)=>{for(d=n>>1;w=-2,d--;){for(i=n;i--;)for(j=n;j--;)s=((a,f,v=0)=>{for(u=s=a!=f;(r=a[v])&&(t=f[v++]);s+=(p=a=>a.toLowerCase())(r)==p(t));return u*s-1})(a[i],a[j]),!(f[i]|f[j])&&s>=w&&(w=s,x=i,y=j);f[x]=f[y]=1,[a[x],a[y]]=[a[y],a[x]];}return a.join` `} ``` You can try it on [JSFiddle](https://jsfiddle.net/ggLywtf8/). [Answer] # Python 3, ~~285~~ ~~277~~ ~~270~~ 267 Bytes, not working ``` i=input().split();r=range;l=len;t=y=z=-1;n=str.lower for p in r(l(i)): for q in r(p): b=min(l(i[p]),l(i[q]));x=0 for s in r(b): if n(i[p][s])==n(i[q][s]): x=x+1 if n(i[p])==n(i[q]): x=-1 if x>t: t=x;y=p;z=q i[y],i[z]=i[z],i[y] print(" ".join(i)) ``` I tried to make the output match the challenge, not the test cases, as a couple of the test cases contradict the challenge. Edit: golfed the 'lower' thingy. Edit: changed split(" ") to split() Edit: I realised this doesn't actually complete all the thingys, and while I might come up with a full working answer, in the meantime I might as well add that this only completes one iteration. ]
[Question] [ This is [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"). This is the **Cops** thread. For the robbers thread, go [here](https://codegolf.stackexchange.com/questions/128066/stealing-sequences-robbers). I've noticed a number of OEIS (On-line Encyclopedia of Integer Sequences) challenges since I joined the site. It seems only fair that we have a cops-and-robbers challenge that determines who is the master of online integer sequences, once and for all. Edit: In order to prevent trivial answers, cops lose 1/2 point for each submission that is cracked. Additionally, for the purposes of this challenge, constant sequences are not allowed. This only applies to solutions posted after this edit. ## Cops Write a program or function that, given no input, deterministically prints any sequence from the [OEIS](https://oeis.org/). By deleting some subset of the characters, your program must be able to print a different OEIS sequence when run in the same language. The new sequence must be entirely new, not just the first by a different name or with a different offset. Neither sequence may be simply a repeated constant value. You must provide the first function, along with the name of the OEIS sequence so correctness can be verified. It's OK if behavior gets questionable around your language's MAX\_INT value or 256, whichever is larger. ## Robbers Delete characters from some Cop's submission such that your new program outputs any other sequence from the OEIS. Provide the new function along with the name of the new OEIS sequence. [Here](https://tio.run/##lZGxCoMwEIb3PMXhZKBDSzfBDmrabim2mzgETDUQosRI6dNbY6uQVgre@N//fXBc8zRVrfZ9X/A7SF4y6ddalEIxuYGHMFXCJTeiVi0OEAwjbE3NJQxhCFtgqhhjlxh3b8yO5qbTCm664@tVhwXTkcl2Vk2abJtbkYMP2Q/sHpvtgvzrYBthtIbA/bSEEDzPQzG9QEwTAidKrnAmKUE2Rg716aY0iki6WG@0UMb//x3cvwA) is a utility to make sure that your submission is valid (i.e. deletes characters without any funny business. Doesn't check the sequence itself.) It's in your best interest to delete as many characters from the Cop's submission as possible. If another robber (anyone except the Cop who authored the original program) comes along and finds a shorter solution that finds another *different* sequence, that robber steals your point. (Note that simply golfing off characters and printing the same sequence is not sufficient to steal the point.) ## Rules & Scoring If, after one week, nobody has been able to crack your solution, you can mark your solution as safe by providing the second program along with the name of the sequence it generates. You get one point for each safe posting and one point for each submission you crack. Cops lose 1/2 point for each cracked submission. Note that another robber can steal your point from the cracked submission at any time by providing a shorter program that yields a different sequence. Cops may only post one challenge per language, per person. The player with the most points at 12:00 UTC on 7 July wins. [Answer] # [MarioLANG](https://esolangs.org/wiki/MarioLANG), 23 bytes [cracked](https://codegolf.stackexchange.com/a/128094/67067) ``` >+ :<": >+^!< ===#= ``` [Try it online!](https://tio.run/##y00syszPScxL//9fQUHBTptLwcpGyYrLTjtO0YbL1tZW2fb/fwA "MarioLANG – Try It Online") produces the odd numbers A005408 [Answer] # C, A000217, 239 bytes [Cracked](https://codegolf.stackexchange.com/a/128087/17355) This isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so I didn't bother. ``` #include <stdio.h> #include <limits.h> int main() { int i, n, temp = 0; for(i = 0; i < INT_MAX; i++) { n = 0; temp = i; while(temp) n+=temp--; printf("%d, ", n); } return 0; } ``` Sequence: <https://oeis.org/A000217> [Answer] # Python 2, 273 bytes, cracked ## Initial Sequence: [A004442](http://oeis.org/A004444) ``` import zlib, base64;exec(zlib.decompress(base64.b64decode('eJzLtDUAAAHoANc='))) while True:print eval(zlib.decompress(base64.b64decode('eJwzAgAAMwAz')))^eval(zlib.decompress(base64.b64decode('eJwzjssEAAHBAPs='))),;exec(zlib.decompress(base64.b64decode('eJzL1LY1BAAC1AED'))) ``` [Try it online!](https://tio.run/##K6gsycjPM9ItqCyo/P8/M7cgv6hEoSonM0lHISmxONXMxDq1IjVZAySil5KanJ9bUJRaXKwBkdNLMjMBCaakaqinelX5lLiEOjo6euQ7@iXbqmtqanKVZ2TmpCqEFJWmWhUUZeaVKKSWJeYQZVh5lWO6o6NvuWMVyKA4EvRlFRe7Ah3h5BhQDHaEDik@MPSJNHRydHQ2dHR1AWn@/x8A "Python 2 (PyPy) – Try It Online") [Answer] # MOO, 86 bytes, safe ``` a=0;b=1;while(a>-1)a=$math_utils:sum(a,a);a=max(1,a);notify(player,tostr(a));endwhile ``` Prints powers of two (A000079). Solution: > > a=1;while(a>-1)a=$math\_utils:sum(a,a,a);notify(player,tostr(a));endwhile > (which prints powers of 3 (A000244) instead) > > > [Answer] # [PHP](https://php.net/), 20 bytes [Cracked](https://codegolf.stackexchange.com/questions/128066/stealing-sequences-robbers/128072#128072) ``` for(;;)echo+!$i,","; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKytNVOTM/K1FVUydZR0lKz///@al6@bnJickQoA "PHP – Try It Online") print sequence <https://oeis.org/A000012> [Answer] # [cQuents](https://github.com/stestoltz/cQuents/tree/c183e7ad0fbcaf21e17ae5b57a251d717af38e12) (older commit), 10 bytes, [cracked](https://codegolf.stackexchange.com/a/128098/48934) ``` =0,1,1:z+y ``` This is still a heavily WIP language, but I patched the interpreter up so it worked. Click the language name for the Github link. This outputs the Fibonnacci sequence: [A000045](https://oeis.org/A000045) # Explanation: (because I have no documentation and I don't expect you to read my interpreter code) ``` =0,1,1 Set start to [0,1,1] : Mode: sequence z+y Each term is the previous two terms added together Because there is no input, output the whole sequence ``` If constant sequences were still allowed, this would be super easy to rob. ]
[Question] [ Your task is simple: tell me who wins the battle of the letters. # The troops There are three different "troops" in this battle, summarized by this table. ``` name | health | damage A 25 25 B 100 5 C 10 50 ``` You may use any three unique characters to represent the the troops, but must specify if they are not these letters. # The battle Suppose we have a sample battle: ``` ABC # army 1 CBA # army 2 ``` Each army repeatedly fires at the leftmost unit, until it is dead; then they move to the troop to the right and repeat. So army 2 attacks `A` in army 1 until `A` is dead, then move to `B`, then `C`. Army 1 attacks `C` first, then `B`, then `A`. Assume the armies attack at the same time, and thus troops will always fire if they were alive before the round and can kill each other at the same time. They fire in order from left to right. The battle would play out as so: ``` ABC CBA BC # A (25 hp) killed by C (-50 hp), B (100 hp) attacked by B (-5 hp) and A (-25 hp), has 70 hp BA # C (10 hp) killed by A (-25 hp), B (100 hp) attacked by B (-5 hp) and C (-50 hp), has 45 hp BC # B (70 hp) attacked by B (-5 hp) and A (-25 hp), has 40 hp A # B (45 hp) killed by B (-5 hp) and C (-50 hp) BC # B (40 hp) attacked by A (-25 hp), has 15 health # A (25 hp) killed by B (-5 hp) and C (-50 hp), army 2 dead ``` Therefore, army 1 wins the battle! # Input Two strings, the first representing army 1 and the second army 2. They are not necessarily the same size (because who said it would be a fair fight?) # Output Any three unique, constant values to represent army 1 winning, army 2 winning, or the unlikely event of a tie. Yes, it is possible for the last troops to kill each other, ending in a tie. # Battles ``` ABC CBA Army 1 CCCCC CCCCC Tie CABCAB ABBABBA Army 2 ``` [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). You must submit a full program. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest solution wins. [Answer] # [Pyth](https://github.com/isaacg1/pyth) ~~145~~ 97 bytes ``` =Y.d[,\A,25 25,\B,*TT5,\C,T*5T)Km=G@YdzJm=H@YdwW&KJMX0hG_smedH gKJ gJKI<hhK0=tK)I<hhJ0=tJ;?K1?J2Z ``` A little less naive than before. [Try it online!](https://pyth.herokuapp.com/?code=%3DY.d%5B%2C%5CA%2C25+25%2C%5CB%2C%2aTT5%2C%5CC%2CT%2a5T%29Km%3DG%40YdzJm%3DH%40YdwMX0hG_smedHW%26KJ+gKJ+gJKI%3ChhK0%3DtK%29I%3ChhJ0%3DtJ%3B%3FK1%3FJ2Z&input=CABCAB%0AABBABBA&debug=0) # Explanations: Let's cut the program in several parts. ``` =Y.d[,\A,25 25,\B,*TT5,\C,T*5T) ,\A,25 25 Create this list: ['A', [25, 25]] ,\B,*TT5 Create this list: ['B', [100, 5]] ,\C,T*5T Create this list: ['C', [10, 50]] .d[ ) From the three lists, create a dictionary whose keys are the letters, and values are the inner lists =Y Assign to the variable Y ``` The dictionary `Y` is: `{'A': [25, 25], 'C': [10, 50], 'B': [100, 5]}`. Then: ``` Km=G@YdzJm=H@YdwMX0hG_smedH m=G@Ydz For all letters in first input string, make a copy of Y[letter]. Make a list of all those values... K ...and assign the list to the variable K m=H@Ydw For all letters in second input string, make a copy of Y[letter]. Make a list of all those values... J ...and assign the list to the variable J MX0hG_smedH Create a function g which takes two lists of couples, and subtract the sum of the second elements of the couples of the second list from the first element of the first couple of the first list ``` At this point, `K` is a list of couples that represents the first army. Each couple of this list is a letter of the army, and is `(health, damage)` for that letter. `J` is exactly the same, but for the second army. `g` is a function which takes two armies, and deals the damage made by the second army to the first one. Now: ``` W&KJ gKJ gJKI<hhK0=tK)I<hhJ0=tJ; W&KJ While K not empty and J not empty gKJ Call g(K,J). That computes the damages to first army gJK Call g(J,K). That computes the damages to second army I<hhK0=tK) If the first army's first letter is dead, remove it I<hhJ0=tJ If the second army's first letter is dead, remove it ; End of while loop ``` When the while loop is over, `K` and `J` have their final value. If they are both empty, it's a tie; otherwise the non-empty army win. That is handled by the last piece of code: ``` ?K1?J2Z ?K1 If K non-empty, display 1. Else... ?J2 ...if J non-empty, display 2. Else... Z ...display zero ``` That's it! [Answer] # [Haskell](https://www.haskell.org/), 199 193 179 176 171 bytes ``` a!b=(t<$>a)?(t<$>b) t v=[(5,5),(20,1),(2,10)]!!(fromEnum v-65) m=sum.map snd f=filter((>0).fst) []?[]=0 []?_=2 _?[]=1 a@((c,d):e)?b@((h,i):j)=f((c-m b,d):e)?f((h-m a,i):j) ``` [Try it online!](https://tio.run/##LY/BboMwDIbveQoT7WBLoYJK7FAtMIJ23BMwhJKVCDbCKkj7@ixhsyx9/n9bsj3q7XuY533XiZHoX55KTdVBQ8zDQ7ZYiIIEnjORR4g8oy5J0K4/7m25O3ikzwUxJ7e7Ozl9g225MivtNPthRSwzOtnNE2u7qu1kFtnLM@ujypl@RfwUV7oMVJlQj2KiyxdJG@zUgflvBTkGqf@6u9PTIsOu9x7wA7UwBGkJt3VaPGB4hAha5LVquOCNqnm4mzcxoj54OGGgVsGqlYrJqdt/AQ "Haskell – Try It Online") Small trick: divided all the army stats by 5. [Answer] # C#, 446 Bytes ``` using System.Linq;(c,d)=>{int z=c.Length,v=d.Length,j=0,k=0,l=0,m=0,q=0;int[]e=(c+d).Select(x=>x!='A'?x=='B'?100:10:25).ToArray(),f=e.Skip(z).ToArray();e=e.Take(z).ToArray();int[]g=(c+d).Select(x=>x!='A'?x=='B'?5:100:25).ToArray(),h=g.Skip(z).ToArray();g=g.Take(z).ToArray();try{for(;;){for(q=l;q<z;q++){if(e[j]<=0)j++;e[j]-=h[q];}for(q=k;q<v;q++){if(f[m]<=0)m++;f[m]-=g[q];}if(e[k]<=0)k++;if(f[l]<=0)l++;}}catch{}return k-z>=l-v?k-z>l-v?0:2:1;}; ``` Formatted version: ``` (c, d) => { int z = c.Length, v = d.Length, j = 0, k = 0, l = 0, m = 0, q = 0; int[] e = (c + d).Select(x => x != 'A' ? x == 'B' ? 100 : 10 : 25).ToArray(), f = e.Skip(z).ToArray(); e = e.Take(z).ToArray(); int[] g = (c + d).Select(x => x != 'A' ? x == 'B' ? 5 : 100 : 25).ToArray(), h = g.Skip(z).ToArray(); g = g.Take(z).ToArray(); try { for (;;) { for (q = l; q < z; q++) { if (e[j] <= 0) j++; e[j] -= h[q]; } for (q = k; q < v; q++) { if (f[m] <= 0) m++; f[m] -= g[q]; } if (e[k] <= 0) k++; if (f[l] <= 0) l++; } } catch { } return k - z >= l - v ? k - z > l - v ? 0 : 2 : 1; }; ``` Outputs 1 if army1 wins , 2 for army2 and 0 for tie [Answer] # Javascript (ES6) - ~~316~~ 269 Bytes I'm sure this can be golfed like hell, but this is what I've come up with :) I managed to shave off 47 bytes though! Outputs 0 for tie, 1 for Team 1 and 2 for Team 2. ``` l=(d,f)=>{for(t=[d,f].map(g=>g.split``.map(k=>[[25,100,10],[25,5,50]].map(m=>m[k.charCodeAt()-65])));(w=t.map(g=>g.some(k=>0<k[0])))[0]&&w[1];)t.forEach((g,k,m)=>m[k].sort(o=>0>o[0])[0][0]-=m[+!k].filter(o=>0<o[0]).reduce((o,p)=>o+p[1],0));return w[0]||w[1]?w[0]?1:2:0} ``` **Readable**: ``` function ltt(a,b){ t=[a,b].map(x=>x.split``.map(c=>[[25,100,10],[25,5,50]].map(e=>e[c.charCodeAt()-65]))) while((w=t.map(_=>_.some(x=>x[0]>0)))[0]&&w[1]){ t.forEach((y,i,n)=>n[i].sort(j=>j[0]<0)[0][0]-=n[+!i].filter(x=>x[0]>0).reduce((h,v)=>h+v[1],0)) } return(!w[0]&&!w[1])?0:(w[0])?1:2 } ``` **Demo**: ``` l=(d,f)=>{for(t=[d,f].map(g=>g.split``.map(k=>[[25,100,10],[25,5,50]].map(m=>m[k.charCodeAt()-65])));(w=t.map(g=>g.some(k=>0<k[0])))[0]&&w[1];)t.forEach((g,k,m)=>m[k].sort(o=>0>o[0])[0][0]-=m[+!k].filter(o=>0<o[0]).reduce((o,p)=>o+p[1],0));return w[0]||w[1]?w[0]?1:2:0} var prnt=(g,h)=>{ n=l(g,h); return(n==0)?"Tie!":`Team ${n} wins!` } console.log("ABCB - ABC: " + prnt("ABCB","ABC")); console.log("BAAA - BBC: " + prnt("BAAA","BBC")); console.log("AAAA - BBC: " + prnt("AAAA","BBC")); console.log("ABC - BBC: " + prnt("ABC","BBC")); console.log("ABC - CBA: " + prnt("ABC","CBA")); ``` ]
[Question] [ ## Challenge Write two programs that: * run in two different programming languages. + These may not be two versions of one language. * when one program is run, it outputs the second program, and vice versa. * The two programs must be different (no polyglots). Here's the catch though: * The programs must be radiation hardened. + This means that when any set of \$n\$ (defined below) characters is removed from either of the two programs, their functionality is unaffected. + \$n\$ is defined as the number of characters that may be omitted with your program's functionality unaffected. + \$n\$ must be at least \$1\$. ## Rules * Standard loopholes are disallowed. * Your programs must be proper cyclic quines. They may not read their own source code. * Scoring is performed as follows: + Your score is \$\frac{S\_1+S\_2}n\$… + where \$S\_1\$ and \$S\_2\$ are the size of your first and second programs respectively… + and \$n\$ is as defined above. * This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), lowest score wins. ## Reward As this challenge is difficult to answer, I will be giving a bounty to the first person to answer. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish) and [><>](https://esolangs.org/wiki/Fish), (117 bytes + 117 bytes)/1 = 234 ### Gol><> ``` \\<<'3d*}}}}~}:r0<}!o::! ?>~~a<o>Hr~Kl a}}:?%2l}}}ss2"<<\\ \\<<'3d*}}}}~}:r0<}!o::! ?>~~a<o>Hr~Kl a}}:?%2l}}}ss2"<<\\ ``` [Try it online!](https://tio.run/##S8/PScsszvj/PybGxkbdOEWrFgjqaq2KDGxqFfOtrBQV7O3q6hJt8u08iuq8cxQSa2ut7FWNcoCqiouNlGxsYmK4yNf6/z8A "Gol><> – Try It Online") ### ><> ``` \\<<"2ss}}}l2%?:}}a lK~rH>o<a~~>? !::o!}<0r:}~}}}}*d3'<<\\ \\<<"2ss}}}l2%?:}}a lK~rH>o<a~~>? !::o!}<0r:}~}}}}*d3'<<\\ ``` [Try it online!](https://tio.run/##S8sszvj/PybGxkbJqLi4trY2x0jV3qq2NlEhx7uuyMMu3yaxrs7OXkHRyipfsdbGoMiqtg6oqlYrxVjdxiYmhot8rf//AwA "><> – Try It Online") [Verification!](https://tio.run/##nVNNb5swGD7jX/GGaTIsHVnam0dTaZO2STvssGOIKgtMsEptyzaNoon89fR1IDTSlss4ILCfr/cBm71vtLo7ymejrQftiLF6a/kz3IOllB6LIs/pXfWhx@vQM/sp72easRk8rA4HnuvVD3v42QLve/bw/rZFlHO3cZ4XBfl/6hGd10v2cbnBOFL5hH7ZewGl7pRn9AZaoZIxZyZUqSuRUO5KKWmapoSQStRQNqJ8erS8ktxLPeFvAPWENVbgPWWERAFsO/U4As5A3IuinfQNaIN2NLigNd3RFLiDOmxHdbaz0ouJg2so3FmFTWbmRKxjM3QMfy6cewh6cZpZwasEeSTSnTedD73/IwzmROLL14ZbRFD6GRdqbUHiOGC52orkopT0FF7WML6v5QZm93BWYADv4PeTNCArobwseYtxlBNl5@UL9owYXmJKF2bU10KtGcrO3zzmS7YJDQTjQELHYSYGYynfeOtEQFzM8haRTN2dWIRMjVz9lvFCG7/Y6raWrlk4W56fM7OP0/Hnib/rdpWv4NcQplDxfFBOrzsMG2eDk/pfslc0uXMiHKVReprw@Ao) These two programs are the same, just reversed. They both follow the same general code structure. ### Explanation (Gol><> on top, ><> on the bottom) ``` \\<< <<\\ Transition to the copy of the code that is not radiated \\<< <<\\ " Wrapping string literal over the rest of the code ' ss2 Push the string character *3d }}} Rotate the "<<\" to the correct end of the stack }}} }}:?%2l Use the extra \ to replace a possible irradiated copy }~}: ~ lK Duplicate the code ~~>? !::o!}<0r Print a copy of the code in reverse a Push a newline a Hr Reverse, print the rest of stack and terminate >o< Print the rest of the stack and terminate ``` ]
[Question] [ ## Challenge Given the high resolution molecular mass of an organic molecule, output the molecule's molecular formula. ## Explanation The input will be a single number to three decimal places of precision, the relative molecular mass of the molecule. Here, the molecular mass is defined as the sum of the masses of the atoms in the compound. Since you only are finding the molecular formulae of organic compounds, the atomic masses you need to know are: * **C**, Carbon: 12.011 * **H**, Hydrogen: 1.008 * **O**, Oxygen: 15.999 * **N**, Nitrogen: 14.007 Your formula should only ever contain carbon, hydrogen, oxygen or nitrogen. When writing the formula, it should take the form: ``` CaHbOcNd ``` Where the elements must be in that order (`C -> H -> O -> N`, so `C2O8N4H6` should be `C2H6O8N4`) and `a`, `b`, `c` and `d` are numbers of the preceding element in the molecule (i.e. `C2` means that there are two carbon atoms in the molecule). If `a`, `b`, `c` or `d` are zero, that element should not be included in the formula (e.g. `C2H6O2N0` should be `C2H6O2`). Finally, if `a`, `b`, `c` or `d` are one, you should not include the number in the formula (e.g. `C1H4` should be `CH4`). The input will always be valid (i.e. there will be a molecule with that mass). If the input is ambiguous (multiple molecules have the same mass), you must only output one of the molecules. How you choose this molecule is up to you. ## Worked Example Suppose the input is `180.156`, there is only one combination of the elements which can have this molecular mass: ``` 12.011*6 + 1.008*12 + 15.999*6 + 14.007*0 = 180.156 ``` So there are: * 6 Carbons * 12 Hydrogens * 6 Oxygens * 0 Nitrogens Therefore, your output should be: ``` C6H12O6 ``` ## More Examples ``` Input -> Output 28.054 -> C2H4 74.079 -> C3H6O2 75.067 -> C2H5O2N 18.015 -> H2O ``` ## Winning Shortest code in bytes wins. [Answer] # Mathematica, 108 bytes ``` Print@@Join@@({Characters@"CHON",#}ᵀ/.a_/;Last@a<2:>Table@@a)&/@{12011,1008,15999,14007}~FrobeniusSolve~#& ``` Pure function expecting the input as an integer (1000 times the relative molecular mass); it prints all possible answers to STOUD (and returns an array of `Null`s). The heavy lifting is done by the builtin `{12011,1008,15999,14007}~FrobeniusSolve~#`, which finds all nonnegative integer combinations of the hardcoded weights that equal the input. `{Characters@"CHON",#}ᵀ` puts each such combination in a form like `{{"C", 0}, {"H", 1}, {"O", 2}, {"N", 3}}`. (`ᵀ` is actually the 3-byte private Mathematica character U+F3C7.) The transformation rule `/.a_/;Last@a<2:>Table@@a` changes pairs of the form `{x, 0}` to `{}` and pairs of the form `{x, 1}` to `{x}` (and spits out errors as it tries to apply to the whole expression as well). Then `Print@@Join@@` prints the result in the correct form, avoiding the need to cast the integers as strings and concatenate. [Answer] # [Python 2](https://docs.python.org/2/), 242 bytes ``` b=[12011,1008,15999,14007] def p(m): if m in b:x=[0,]*4;x[b.index(m)]=1;return x elif m<1:return 0 else: for i in range(4): x=p(m-b[i]) if x:x[i]+=1;return x return 0 print''.join(a+`n`*(n>1)for n,a in zip(p(input()),'CHON')if n) ``` [Try it online!](https://tio.run/nexus/python2#Vc3BisIwEAbge59ibk00Smap1rbWy148uQ9QCraYyohOQ6wQ9uVrArKwx//nn2/mvm7wSyMq1HqncFMUhcJM67xNLmYAKx6yTIAGeAAx9KWvG63aRVb5pl8TX4wPi7bGypnp5Rh8AuYe53ssP5WO1dMEBobRAUXIdXw1Ios2gK/Dm1XfUCtjDNe@9CEt/7Hwx1lHPKXp@jYSi2555vNC8AFl1Fl10f8lK6wgtq9JSKnS7@PPKZVBZjnP@UZv8zc "Python 2 – TIO Nexus") Recursive function, the input is an integer (1000 times the relative molecular mass) thanks Stephen S for the idea --- My machine took 40 segs to turn `672336` into `C33H115O3N8` with [this modified code](https://tio.run/nexus/python2#TY7RToMwGEbv@xS9o4WK7caGFOuNN17pAxCSQSimAl1hkDQue3ZsE5Vd/idf/nPWXhQl6MT1BmpRsB1ljDBKnwg7ZFlGWEJpWoJGttCgAXMAVQsHqDTs@STnZdKQbqz7Y10xlBuuuRUFJWWY5LaoY6Ubad2zUrD8d28BlL2fPzt3yvu4Mkbqxo3yzSL7i3QBsD1PUPm/U6U/JUp8FYSjQMPjZRlQjXHEPLHCJT/UhSrDEXvgBJZbd0dizLt4MU01S3QduL3huxJ4p3fXfwAwk9JzEMRfZ6VRFZ30KUT6hWEfpEnlk76VQQYpbZYZYUyC17eP9wA7scbrekx3@/3xBw "Python 2 – TIO Nexus"). It contains a lookup table for hits/fails to reduce the amount of recursive calls and a optimization to count an element multiple times (if the mass is high enough) [Answer] ## JavaScript (ES6), ~~159~~ 158 bytes Not exactly fast... ``` w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join`` ``` ### Demo ``` let f = w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join`` console.log(f(28.054)) // -> C2H4 console.log(f(18.015)) // -> H2O ``` --- ## Faster version, ~~174~~ 173 bytes ``` w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join`` ``` ### All test cases ``` let f= w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join`` console.log(f(180.156)) // -> C6H12O6 console.log(f(28.054)) // -> C2H4 console.log(f(74.079)) // -> C3H6O2 console.log(f(75.067)) // -> C2H5O2N console.log(f(18.015)) // -> H2O ``` ]
[Question] [ Logo is a programming language that was designed back in 1967 that has great potential for creating graphics in relatively few bytes compared to other languages. Logo is an educational programming language that utilizes [Turtle Graphics](https://en.wikipedia.org/wiki/Turtle_graphics). There are multiple interesting implementations of Logo including: * [Apple Logo](https://applelogointroduction.wikispaces.com/file/view/Apple%20Logo.pdf/334025686/Apple%20Logo.pdf) * [Atari Logo](http://www.atarimania.com/documents/Atari_LOGO_Introduction_to_Programming_Through_Turtle_Graphics.pdf) * [LibreLogo](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language) (my personal favorite) * [Texas Instruments Logo](https://archive.org/details/tibook_the-texas-instruments-logo-manual) * [UCBLogo](https://people.eecs.berkeley.edu/~bh/usermanual) * And [many others](https://en.wikipedia.org/wiki/Logo_(programming_language)#Implementations)... In addition, multiple Logo interpreters can be found online. This page is intended to be a hub for code golf [tips](/questions/tagged/tips "show questions tagged 'tips'") regarding any implementation of the Logo programming language. [![enter image description here](https://i.stack.imgur.com/mS8gU.png)](https://i.stack.imgur.com/mS8gU.png) Source: [The Great Logo Adventure](https://books.google.com/books/about/The_Great_Logo_Adventure.html?id=9E0GXFoYr3MC) (1998) by Jim Muller [Answer] # LibreLogo **Shorten Color Definitions:** It is [documented](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language) that colors can be defined by name, identifier, RGB value, or HEX code. In the majority of cases, if you have the opportunity to use an identifier for a color constant, that is typically the shortest option. On the other hand, a little known fact is that you can also use the decimal value to define a color, and you can occasionally save bytes. **Color Chart:** ``` +------------------------------------------------------------------------+ +-------------+ | Name | Identifier | RGB | HEX | Decimal | | Best Option | |------------------------------------------------------------------------| |-------------| | "BLACK" | [0] | [0,0,0] | 0x000000 | 0 | | 0 | | "SILVER" | [1] | [192,192,192] | 0xc0c0c0 | 12632256 | | [1] | | "GRAY"/"GREY" | [2] | [128,128,128] | 0x808080 | 8421504 | | [2] | | "WHITE" | [3] | [255,255,255] | 0xffffff | 16777215 | | [3] | | "MAROON" | [4] | [128,0,0] | 0x800000 | 8388608 | | [4] | | "RED" | [5] | [255,0,0] | 0xff0000 | 16711680 | | [5] | | "PURPLE" | [6] | [128,0,128] | 0x800080 | 8388736 | | [6] | | "FUCHSIA"/"MAGENTA" | [7] | [255,0,255] | 0xff00ff | 16711935 | | [7] | | "GREEN" | [8] | [0,128,0] | 0x008000 | 32768 | | [8] | | "LIME" | [9] | [0,255,0] | 0x00ff00 | 65280 | | [9] | | "OLIVE" | [10] | [128,128,0] | 0x808000 | 8421376 | | [10] | | "YELLOW" | [11] | [255,255,0] | 0xffff00 | 16776960 | | [11] | | "NAVY" | [12] | [0,0,128] | 0x000080 | 128 | | 128 | | "BLUE" | [13] | [0,0,255] | 0x0000ff | 255 | | 255 | | "TEAL" | [14] | [0,128,128] | 0x008080 | 32896 | | [14] | | "AQUA" | [15] | [0,255,255] | 0x00ffff | 65535 | | [15] | | "PINK" | [16] | [255,192,203] | 0xffc0cb | 16761035 | | [16] | | "TOMATO" | [17] | [255,99,71] | 0xff6347 | 16737095 | | [17] | | "ORANGE" | [18] | [255,165,0] | 0xffa500 | 16753920 | | [18] | | "GOLD" | [19] | [255,215,0] | 0xffd700 | 16766720 | | [19] | | "VIOLET" | [20] | [148,0,211] | 0x9400d3 | 9699539 | | [20] | | "SKYBLUE" | [21] | [135,206,235] | 0x87ceeb | 8900331 | | [21] | | "CHOCOLATE" | [22] | [210,105,30] | 0xd2691e | 13789470 | | [22] | | "BROWN" | [23] | [165,42,42] | 0xa52a2a | 10824234 | | [23] | | "INVISIBLE" | [24] | N/A | N/A | N/A | | [24] | +------------------------------------------------------------------------+ +-------------+ ``` [Answer] # LibreLogo **Use Abbreviated Commands:** Abbreviated commands, also called "short names," are used across most implementations of Logo. Here is the full list of abbreviated commands for [LibreLogo](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language). ``` +-----------------------------------------------+ | Full Command | Short Command | Bytes Saved | |-----------------------------------------------| | forward 10 | fd 10 | 5 | | back 10 | bk 10 | 2 | | left 90 | lt 90 | 2 | | right 90 | rt 90 | 3 | | penup | pu | 3 | | pendown | pd | 5 | | position 0 | pos 0 | 5 | | heading 0 | seth 0 | 3 | | hideturtle | ht | 8 | | showturtle | st | 8 | | clearscreen | cs | 9 | | pensize 10 | ps 10 | 5 | | pencolor 0 | pc 0 | 6 | | fillcolor 0 | fc 0 | 7 | | picture [ ... ] | pic [ ... ] | 4 | +-----------------------------------------------+ ``` [Answer] # LibreLogo **Random Numbers:** Use [`any`](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#ANY) instead of [`random`](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#RANDOM) when possible. *Random Integer (0 - 9):* ``` x = int random 10 ; 17 bytes x = int(ps any) ; 15 bytes ``` *Random Floating-Point Number (0 - 9):* ``` x = random 10 ; 13 bytes x = (ps any) ; 12 bytes ``` *Directly Assigned to Setting:* ``` pensize random 10 ; 17 bytes ps random 10 ; 12 bytes ps any ; 6 bytes ``` [Answer] # LibreLogo **Use `PAGESIZE` to your Advantage:** > > `PAGESIZE` is a variable that is dependent on the [Paper Format](https://help.libreoffice.org/Common/Page#Format) in LibreOffice Writer and returns an array containing the `[width, height]` of the page in points (`pt`). > > > This could be useful for a variety of situations, but I personally found it useful for generating a number without using the digits `[0-9]`. <https://help.libreoffice.org/Writer/LibreLogo_Toolbar#PAGESIZE> [![enter image description here](https://i.stack.imgur.com/cGVDA.png)](https://i.stack.imgur.com/cGVDA.png) --- **Value Chart:** ``` +-------------------------------------------------------------------+ | Paper Format | PAGESIZE | |-------------------------------------------------------------------| | A6 | [297.35433070866145, 419.75433070866137] | | A5 | [419.75433070866137, 595.4456692913386] | | A4 | [595.4456692913386, 841.6913385826772] | | A3 | [841.6913385826772, 1190.8913385826772] | | B6 (ISO) | [354.2456692913386, 498.95433070866136] | | B5 (ISO) | [498.95433070866136, 708.4913385826771] | | B4 (ISO) | [708.4913385826771, 1000.8] | | Letter | [612.0, 792.0] | | Legal | [612.0, 1008.0] | | Long Bond | [612.0, 936.0] | | Tabloid | [792.0, 1224.0] | | B6 (JIS) | [362.8913385826771, 516.2456692913386] | | B5 (JIS) | [516.2456692913386, 728.6456692913387] | | B4 (JIS) | [728.6456692913387, 1031.7543307086614] | | 16 Kai | [521.2913385826771, 737.2913385826771] | | 32 Kai | [368.64566929133855, 521.2913385826771] | | Big 32 Kai | [396.7086614173228, 575.2913385826771] | | User | CURRENT PAGE SIZE | ← Current Paper Format | DL Envelope | [311.7543307086614, 623.5086614173229] | | C6 Envelope | [323.29133858267716, 459.3543307086614] | | C6/5 Envelope | [323.29133858267716, 649.4456692913386] | | C5 Envelope | [459.3543307086614, 649.4456692913386] | | C4 Envelope | [649.4456692913386, 918.7086614173228] | | #6¾ Envelope | [261.35433070866145, 468.0] | | #7¾ (Monarch) Envelope | [279.35433070866145, 540.0] | | #9 Envelope | [279.35433070866145, 639.3543307086613] | | #10 Envelope | [297.35433070866145, 684.0] | | #11 Envelope | [324.0, 747.3543307086613] | | #12 Envelope | [342.0, 792.0] | | Japanese Postcard | [283.69133858267713, 419.75433070866137] | +-------------------------------------------------------------------+ ``` ]
[Question] [ ## Challenge Given a SE user's ID, output the sum of their reputation from across all of the Stack Exchange networks​ the user has signed up to. ## Rules If a user has 101 or less reputation on a site, count it as zero in the sum. ***You should not count Area 51 rep or hidden communities!!*** URL shorteners are disallowed. ## Examples ***Subject to change*** ### [User 3244989 (Beta Decay)](http://stackexchange.com/users/3244989/beta-decay) ``` 14141 ``` ### [User 918086 (Dennis)](http://stackexchange.com/users/918086/dennis) ``` 204892 ``` ### [User 11683 (Jon Skeet)](http://stackexchange.com/users/11683/jon-skeet) ``` 1029180 ``` ## Winning The shortest code in bytes wins. [Answer] ## Python 2 (with Requests), 149 Bytes ``` from requests import* lambda i,r="reputation":sum(u[r]for u in get("http://api.stackexchange.com/users/"+i+"/associated").json()["items"]if u[r]>101) ``` I requested the API, converted the API to JSON, then summed the reputation via a generator expression. The generator does remove accounts with less than 101 reputation. Credit for improving the code: [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # curl, grep and awk, 106 bytes ``` curl http://api.stackexchange.com/users/$1/associated|grep -o n\"[^,]*|awk -F: '$2>101{s+=$2}END{print s}' ``` It's dirty but seems to work well. I don't use `awk` often so I wouldn't be surprised if there was a way to golf the `grep` away with it. [Answer] # R with httr, 146 Bytes ``` library(httr) a=sapply(content(GET(paste0("http://api.stackexchange.com/users/",readline(),"/associated")))$items,'[[','reputation') sum(a[a>101]) ``` [Answer] # Ruby 2.4, 136 + 20 = 156 bytes Requires the `-rjson -rnet/http -n` flags. Input is from STDIN (no trailing newline). Ruby 2.4 is needed for `sum`. ``` p JSON.parse(Net::HTTP.get URI"http://api.stackexchange.com/users/#$_/associated")["items"].map{|i|i["reputation"]}.select{|i|i>101}.sum ``` [Answer] # JavaScript (ES6), ~~148~~ ~~143~~ ~~142~~ 141 bytes ``` u=>fetch(`//api.stackexchange.com/users/${u}/associated`).then(j=>j.json(s=0)).then(i=>(i.items.map(r=>s+=(r=r.reputation)>101&&r),alert(s))) ``` --- ## Try it ``` f= u=>fetch(`//api.stackexchange.com/users/${u}/associated`).then(j=>j.json(s=0)).then(i=>(i.items.map(r=>s+=(r=r.reputation)>101&&r),alert(s))) i.addEventListener("submit",e=>{e.preventDefault();(v=+i.firstChild.value)&&f(v)}) ``` ``` <form id=i><input type=number><button>Calc.</button></form> ``` ]
[Question] [ > > **Note:** This is based on [Two roads diverged in a yellow wood (part 2)](https://codegolf.stackexchange.com/questions/114379/two-roads-diverged-in-a-yellow-wood-part-2), a previous challenge of mine. Because of the popularity of that question and [Two roads diverged in a yellow wood (part 1)](https://codegolf.stackexchange.com/questions/114253/two-roads-diverged-in-a-yellow-wood-part-1), I wanted to make a third. But the first 2 were too easy (a *2-byte* answer on the first, a 15-byte answer on the second.) So I made something more complex... > > > ## The inspiration 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; > > > ...2 paragraphs trimmed... > > > 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,`. ## The backstory You were assigned to help a blind adventurer who is walking on a road and was inspired by *The Road Not Taken*. The adventurer is approaching a fork in the road and would like to take the path less traveled by. You must find where the adventurer actually is and tell the adventurer where to turn. ## The challenge Your goal is to find the road least traveled by on your map where the road forks. Your map is a string containing newlines (or `\n`, if you prefer) and has an unknown width and height. In the map, roads are made up of **digits 0 to 9**, the intersection are made of `#`s. You must find the road you are currently on, and out of the other roads the road most traveled by, and the road less traveled by for your blind adventurer. Woods in you map is represented by a space. Here is a simple map: ``` 2 2 1 0 # 2 2 ``` This map is 5 wide and 5 tall. Notice how the road forks in a Y shape. The Y may be oriented any way, so you must be able to understand a "rotated" map. ## What the `#` means Where the map forks there will be a `#`. This does not impact the score of any path. ## What the numbers actually mean Each path (a line of numbers, may have a bend in it) has a score. A path's score is determined by adding up its digits, so for the first example, the first path (from upper-left, clockwise) has a score of 2+1=3, the second has 2+0=2, and the third has 2+2=4. Roads may contain numbers connected diagonally. ## Finding where you are You are on the path with the highest score. The other 2 paths are the road more traveled by, and the road less traveled by. You need to find the road with the *lowest* score. ## Telling your traveler where to go You must tell your traveler to go "left" or "right". Keep in mind that directions are from your traveler's point of view (he is facing the fork.) ## Example maps ``` 14 9# 04 ``` Output: "right" (traveler is at the `9` road, 0+4 < 1+4 ``` 9 9 9 9 9 # 8 8 8 8 88 88 8 7 ``` Output: "left" (traveler is at the `99999` road, 8+8+8+8+8 > 8+8+8+8+7 ``` 02468 #98765 13579 ``` Output: "right" (traveler is at the `98765` road, 0+2+4+6+8 < 1+3+5+7+9) ``` 4 2 4 2 # 4 4 2 2 ``` Output: "right" (traveler is at the `4422` road, 4+4 > 2+2) ``` 9 9 9 # 8 7 8 7 8 7 ``` Output "left" (traveler is at the `999` road, 8+8+8 > 7+7+7 ## Stuff to know: * Maps will be padded with spaces to make each line the same length. * You must output to STDOUT / console / file the string `left` or `right`, optionally followed by a trailing newline. * You must take input as either a string containing newlines, `\n`s, or an array/list of lines (each line is a string). Where that input is put **must be a function, command-line argument, file, or STDIN one line at a time or similar. A variable is not a acceptable input device (unless it is a function parameter.) Likewise, function expressions in JS and other languages must be assigned to a variable.** * 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) ## Things you can assume * Your input will be valid. Nothing like this will be tested for: ``` 0 0 0 0 0 # 0 0 ``` * Paths' scores will never be tied. * The input can be of any length in width or height, less than the string limit of your language. * There will always be at least 1 space between the 2 paths. * Paths may have bends, turns, etc. These are roads, not highways. # Have any questions? Ask me below in the comments and happy golfing! [Answer] # [D](https://dlang.org/), ~~348~~ ~~321~~ ~~312~~ 302 bytes ``` import std.stdio,std.algorithm,std.regex,std.range;void h(R,U)(R s,U r){U[2]c;foreach(L;s.map!(a=>a.array.split)){U l=L.length-1;r>1?r=l^r-2:0;l?c[]+=l*L.map!sum.array[]:c;}write(c[r]>c[!r]?"right":"left");}void main(){auto s=stdin.byLineCopy.array;!s.join.match(`\d \d`)?h(s.transposed,2UL):h(s,3UL);} ``` ## Ungolfed ``` import std.stdio,std.algorithm,std.regex,std.range; void h(R,U)(R s, U reverse) { U[2] counts; /* Now that all paths are up/down, every line we need to count up has precisely two space-delimited parts to sum up. */ foreach (line; s.map!(a=>a.array.split)) { U len = line.length - 1; reverse > 1 ? reverse = len ^ reverse - 2 : 0; len ? counts[] += len * line.map!sum.array[] : counts; } /* Switch left/right as needed based on our orientation */ write(counts[reverse] > counts[!reverse] ? "right" : "left"); } void main() { /* Treat the input as a matrix of integers */ auto s = stdin.byLineCopy.array; /* If moving left/right intead of up/down, transpose */ !s.join.match(`\d \d`)?h(s.transposed,2UL):h(s,3UL); } ``` [Try it online!](https://tio.run/nexus/d#VU89b4MwEN37Ky5ksVtqhS5pYzkZOiExZSVUccGBqzBGtmkbpfnt1JApw737enf3bkTdG@vB@YoFQxNPkWxrY9E3es6sqtXvLZJdrfi3wQoaso9TSvbg4hQsvQzY@fylKHkKOkZ@MlbJsiEZd0zLfkGk2EomrZVn5voWPaUXPJGMtaqrfbNNaJkXTyKbyW7QN2pecNU6BfpPIEcRLSMhsnxV8Kv@sLsw8Siek03Jf4JYRcrQ2ZZ5Uuwii3Xjo03UqpOPKL/OkrXEjtCLHLwBJ6ZvO/Z5zrBT76Y/3y7yhWNfJjS09EH@8VDBoTrSXUMc8@F91xunqnhFN6ESJ2H1OMIbADzc4XLCV1jPGNyEsP4H "D – TIO Nexus") [Answer] ## Python 2, 304 bytes [Try it online](https://tio.run/nexus/python2#hY9LboMwEED3PoUVVI1dMMUIqcGpK3GGLC0vUEpaV4Qgm4iqi149HQJto2wqL9583ozG50q7rj8NjJOtDoNnFTe5ErlNfdO39a5hK0gorBIATpzepq57aT4YRJh63TYdq0xmORm1JLV2D564PVB42honvFWjFuOm0pVRarSbeh7g8Vf9p8XSqkp/up7dT5qQlqPo7q43XSl8dn53CTSFJEFnZH/0dEddh1Pp@9F17FD3DOY4wTNVbTlPQ986/K4KsQ6nw8Vx3ZDsON8ELQLpPaYG2mY/QALevb4NYC/3m/Cc2XNkIKeU5tikkhZ0Io3ozPyGEmkJwRmMCyyVP2ZWLA1ZLJWoRGRTZs@TXy71/7hsXOO74hq5noi3PoL9Bg) ``` A=input() S=str(A)[2:-2].replace("', '",'') i=S.index('#') r=len(A[0]) w=1 a=i/r if' '<S[i-r]:w=-w;A=A[::w];a=len(A)+~a if' '<S[i+1]:A=zip(*A[::-1]);a=i%r if' '<S[i-1]:A=zip(*A)[::-1];a=len(A)-i%r-1 s=0 for c in' '.join(map(''.join,A[0:a])).split():s+=sum(map(int,c));s=-s print['left','right'][::w][s>0] ``` This program deduces direction of roads and rotates it facing up to use my solution from part 2 of this challenge. ]
[Question] [ # XKCD Comic:[enter image description here](https://i.stack.imgur.com/U7Hdw.png) --- # Goal: Given a date, the current Dow Opening, and your current coordinates as a rounded integer, produce a "geohash." # Input: Input through any reasonable means (STDIN, function argument, flag, etc.) the following: * The current date. This does necessarily have to be the date of the system's clock, so assume that the input is correct. * The most recent Dow Opening (must support at least 2 decimal places) * The floor of your current latitude and longitude. To make input easier, you can input through any reasonable structured format. Here are some examples (you may create your own): ``` ["2005","05","26","10458.68","37",-122"] 2005-05-26,10458.68,37,-122 05-26-05 10458.68 37 -122 ``` # Algorithm: Given your arguments, you must perform the "geohash" algorithm illustrated in the comic. The algorithm is as follows. 1. Format the date and Dow Opening in this structure: `YYYY-MM-DD-DOW`. For example, it might look like `2005-05-26-10458.68`. 2. Perform an md5 hash on the above. Remove any spacing or parsing characters, and split it in to two parts. For example, you might have these strings: `db9318c2259923d0` and `8b672cb305440f97`. 3. Append each string to `0.` and convert to decimal. Using the above strings, we get the following: `0.db9318c2259923d0` and `0.8b672cb305440f97`, which is converted to decimal as aproximately `0.8577132677070023444` and `0.5445430695592821056`. You must truncate it down the the first 8 characters, producing `0.857713` and `0.544543`. 4. Combine the coordinates given through input and the decimals we just produced: `37` + `0.857713` = `37.857713` and `-122` + `0.544543` = `-122.544543` # Notes: * To prevent the code from being unbearably long, you may use a built-in for the md5 hash. * Standard loopholes (hardcoding, calling external resource) are forbidden. [Answer] # Python 2, 129 bytes ``` import md5 d,q,c=input() h=md5.new(d+'-'+q).hexdigest() print map(lambda p,o:o+'.'+`float.fromhex('.'+p)`[2:8],(h[:16],h[16:]),c) ``` Input is given in the form `'2005-05-26','10458.68',('37','-122')` (using the example). Computes the MD5 hash with `md5.new().hexdigest()`, then performs the necessary transforms. I *could* save five bytes by using `h` instead of `h[:16]`, but I'm not sure if that would affect the six most significant digits in the decimal conversion. [Ideone it!](http://ideone.com/QpgLgI) (substituting an `eval()` call for the `input()`) [Answer] # Bash + Coreutils + md5, 98 bytes: ``` C=`md5 -q -s $1-$2`;C=${C^^};for i in 3 4;{ dc -e 16i[${!i}]n`cut -c1-7<<<.${C:$[16*(i>3)]:16}`p;} ``` [Try It Online!](https://tio.run/nexus/bash#DctBDoIwEADAr6xJD2qyhC1QCC1eeAYBmxSMPVCMyqn27SvJXIf7zi7uuQEGEIRC/ta5@uyr1X0nYj9NST@2N3jwAQoodYTZAS5Ayg8innwag3X7F9AR1saY7EitGEhdz/5WXMaWVLIvnZhZ5nmFB6mY8rJqMtVwUfOdpPwD) Uses the built-in `md5` command on OSX to generate the MD5 hash. Takes 4 space separated command line arguments in the following format: ``` YYYY-MM-DD DOW LAT LONG ``` with *negative numbers* input and output with a leading *underscore* (i.e. `_122` instead of `-122`). **Note:** Depending on your system, you may need to substitute in `echo -n $1-$2|md5sum` for `md5 -q -s $1-$2` in order for this to work. Doing so brings the byte count up to 103, and is indeed the case in the TIO link. [Answer] # Groovy, ~~198~~ 161 bytes ``` {d,o,l,L->m=""+MessageDigest.getInstance("MD5").digest((d+"-"+o).bytes).encodeHex() h={(Double.valueOf("0x0."+it+"p0")+"")[1..7]} [l+h(m[0..15]),L+h(m[16..31])]} ``` This is an unnamed closure. ``` Input f("2005-05-26","10458.68","37","-122") Output [37.857713, -122.544543] ``` [Try it here!](http://ideone.com/b2Mokj) **Ungolfed** - ``` import java.security.* { date,open,lat,lon -> md = "" + MessageDigest.getInstance("MD5").digest((date+"-"+open).bytes).encodeHex() decimal = {(Double.valueOf("0x0."+it+"p0")+"")[1..7]} [lat+decimal(md[0..15]),lon+decimal(md[16..31])] //Implicity returns } ``` [Answer] ## Javascript (Node, using built-in Crypto), 165 characters ``` (d,o,l)=>l.map((p,i)=>p+Math.sign(p)*[...require('crypto').createHash('md5').update(d+-o).digest`hex`.slice(z=i*16,z+16)] .reduce((a,d,i)=>a+parseInt(d,16)*16**~i,0)) ``` Such a verbose API! ## JavaScript (using `md5` library), 125 characters ``` (d,o,l)=>l.map((p,i)=>p+Math.sign(p)*[...require('md5')(d+-o).slice(z=i*16,z+16)] .reduce((a,d,i)=>a+parseInt(d,16)*16**~i,0)) ``` Nothing very golfy here. In both cases: ``` f('2005-05-26', 10458.68, [144,-37]) => [ 144.857713267707, -37.54454306955928 ] ``` ``` [Answer] # [Python](https://www.python.org), 185 bytes ``` import hashlib as h x,y,a,n=input().split(',') b=h.md5((x+'-'+y).encode()).hexdigest() q=list(map(str,map(float.fromhex,['0x.'+b[:15],'0x.'+b[16:]]))) print(a+q[0][1:8]+','+n+q[1][1:8]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BaoYwFIT3nsJdEvIMia3-IngSySJWbQKa5Df5Qc_SjZv2DqUn6W2aYgsP5n0wwzBvH_6I2tnzfH_EuWi-P83q3RZzrYJezJCrkOtshwMU2M5Y_4iYsOAXEzECRLKh02wdK4x3igpED8Im--LGCRPC9LSP5nUKKZLdu8WkZ1Ueh7jBr86LU5HNm1uTEXrEd4bo0LeikvAPom6lJIRkfjM2YkXvPZe9aBtJUz21icXF5Brwt-P8KjmvinRlDYI_Vw2rG3i6QSHK8rL8AA) Hashlib stole my bytes, :P. ]
[Question] [ As a terrible Latin student for several years I have learned to hate many things about Latin. However there is one thing I love. Latin scansion. [Scansion](https://en.wikipedia.org/wiki/Scansion) is the act of determining the meter of a particular line of poetry. For Latin this means demarcating each syllable in the line as "light" or "heavy". In Latin scansion has many of rules. However unlike English Latin scansion is fairly regular and often requires no knowledge of Latin vocabulary or grammar to be performed. For this problem we will be using simplified subset of those rules (real Latin does not have a neat spec). Before you begin the scansion you must [elide](https://en.wikipedia.org/wiki/Elision). Elision is the dropping syllables between words to ease pronunciation. (e.g. "he is" -> "he's"). Unlike English, Latin elision follows very nice rules. * The final vowel of a word ending with a vowel is omitted if the next word begins with a vowel. NAUTA EST -> NAUTEST * The same goes for words ending in a vowel followed by "m". FIDUM AGRICOLAM -> FIDAGRICOLAM * Word-initial "h" followed by a vowel counts as a single vowel for elision purposes and is always dropped when elided. MULTAE HORAE -> MULTORAE or MULTAM HORAM -> MULTORAM After elision we can begin scansion. Scansion is done to a specific meter. The meter for this challenge is [dactylic hexameter](https://en.wikipedia.org/wiki/Dactylic_hexameter). Dactylic hexameter has six "feet" each foot consists of two or three syllables. Syllables can be either long or short depending on the vowel. Each of the first five feet will be either a dactyl, a long syllable followed by two short ones, or a spondee, two long syllables. And the last foot will be a long followed by an anceps (short or long, for this problem you will not have to determine which). * A vowel in latin can be either short or long * An "i" sandwiched between two vowels (e.g. eiectum) is a consonant. (i.e. a "j") * An "i" beginning a word followed by a vowel (e.g Iactus) is also a consonant * A "u" after a "q" is also a consonant (i.e. a "v") * Diphthongs (ae, au, ei, eu, oe, and ui) are made up of two vowels but count as one vowel and are always long * A vowel with two or more consonants between it and the next vowel is always long * For the previous rule an "l" or an "r" after a "b","c","d","g","p", or "t" does not count as a consonant * "x" counts as two consonants * "ch", "ph", "th", and "qu" count as one consonant * The syllable "que" at the end of a word (after elision) is always short * If a vowel is not forced by one of the previous rules it can be either long or short this will depend on the meter Your task will be to take a line of latin and produce the scansion of it. You will take in the line as string via standard input and output a string representing the final scansion. The input will contain only spaces and characters A-Z. To represent the scansion you will output all of the syllables with `|` demarcating the separation of feet. A long syllable will be represented by a `-` while a short syllable will be marked by a `v` and an anceps (the last syllable of every line) will be marked by a `x`. If there are multiple solutions as there often will be you may output anyone of them. ## Test Cases The start of Virgil's Aeneid. ``` ARMA VIRUMQUE CANO TROIAE QUI PRIMUS AB ORIS -> -vv|-vv|--|--|-vv|-x (or -vv|-vv|--|-vv|--|-x) ITALIAM FATO PROFUGUS LAVINIAQUE VENIT -> -vv|--|-vv|-vv|-vv|-x LITORA MULTUM ILLE ET TERRIS IACTATUS ET ALTO -> -vv|--|--|--|-vv|-x VI SUPERUM SAEVAE MEMOREM IUNONIS OB IRAM -> -vv|--|-vv|--|-vv|-x (or -vv|--|-vv|-vv|--|-x) MULTA QUOQUE ET BELLO PASSUS DUM CONDERET URBEM -> -vv|--|--|--|-vv|-x INFERRETQUE DEOS LATIO GENUS UNDE LATINUM -> --|-vv|-vv|-vv|-vv|-x ALBANIQUE PATRES ATQUE ALTAE MOENIA ROMAE -> --|-vv|--|--|-vv|-x ``` ## Further stipulations In the proper fashion of Latin poetry all answers must begin with an [invocation to the muses](https://tcw1.wordpress.com/2009/04/28/invocations-to-the-muse-in-epic-poems/). Latin has only two one letter words "e" and "a". You may assume that no other one letter words will appear as input. [Answer] # sed, ~~402~~ ~~392~~ ~~374~~ ~~359~~ ~~363~~ ~~334~~ 333 bytes > > “Sing, goddess, the anger of Peleus’ son Achilleus > and its devastation, which put pains thousandfold upon the Achians, > hurled in their multitudes to the house of Hades strong souls > of heroes, but gave their bodies to be the delicate feasting > of dogs, of all birds, and the will of Zeus was accomplished > since that time when first there stood in division of conflict > Atreus’ son the lord of men and brilliant Achilleus.” > > > *— Homer (The Iliad); confused why this quote is here? check the rules.* ``` sed -E 's/[AEIOU]M? H?([AEIOU])/\1/g;s/X/cc/g;s/(^|[ AEIOU])I([AEIOU])/\1c\2/g;s/QUE( |$)/cv/g;s/A[EU]|E[IU]|OE|UI/-/g;s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g;s/ //g;s/ucc+/-/g;s/c//g;s/^[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u].$/-\1|-\2|-\3|-\4|-\5|-x/;s/[uv]/-/g;s/---/-vv/g' ``` Not exactly golfed, but this implements all the given rules in the form of regular expressions, which sed just runs one-by-one to reach the solution. This handles each line independently, so can process an entire multi-line input. ### Usage: ``` printf 'ARMA VIRUMQUE CANO TROIAE QUI PRIMUS AB ORIS ITALIAM FATO PROFUGUS LAVINIAQUE VENIT LITORA MULTUM ILLE ET TERRIS IACTATUS ET ALTO VI SUPERUM SAEVAE MEMOREM IUNONIS OB IRAM MULTA QUOQUE ET BELLO PASSUS DUM CONDERET URBEM INFERRETQUE DEOS LATIO GENUS UNDE LATINUM ALBANIQUE PATRES ATQUE ALTAE MOENIA ROMAE' | sed -E '<...>'; ``` ### Breakdown: ``` sed -E " # Apply Elision s/[AEIOU]M? H?([AEIOU])/\1/g; # Convert into vowels (u, v or -) and consonants (c) according to the rules given s/X/cc/g; s/(^|[ AEIOU])I([AEIOU])/\1c\2/g; s/QUE( |\$)/cv/g; s/A[EU]|E[IU]|OE|UI/-/g; s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g; s/[A-Z]/u/g; # all remaining vowels are unknown # Remove all spaces s/ //g; # A vowel followed by 2 consonants before the next vowel is long # (and we don't care if the last vowel is long or short) s/ucc+/-/g; # Remove all consonants s/c//g; # Look for a matching dactylic hexameter and insert pipe separators s/^\ [-u]([-u]|[vu]{2})\ [-u]([-u]|[vu]{2})\ [-u]([-u]|[vu]{2})\ [-u]([-u]|[vu]{2})\ [-u]([-u]|[vu]{2})\ [-u].\$/-\1|-\2|-\3|-\4|-\5|-x/; # Substitute identified feet with the necessary long/short vowels s/[uv]/-/g; s/---/-vv/g " ``` ### Results for test cases: ``` -vv|-vv|--|--|-vv|-x -vv|-vv|--|-vv|-vv|-x -vv|--|--|--|-vv|-x -vv|--|-vv|-vv|--|-x -vv|--|--|--|-vv|-x --|-vv|-vv|-vv|-vv|-x --|-vv|--|--|-vv|-x ``` ]
[Question] [ # Lets Play Kick The Can! ## Although Moogie is the current winner, if anyone can take his crown they are encouraged to do so Kick the can is a children's game. Involving one defender, and multiple attackers. Today it is no longer such a game! Your job is to write a bot that plays it, to win, [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") style! <https://en.wikipedia.org/wiki/Kick_the_can> There are some key differences in this game. The first key difference is that the game is multiplayer (5v5). The second key difference is that both sets of bots can kill and eliminate enemy players with both mines and thrown bombs! Bots can not see any mines (regardless of distance) or players at greater than five blocks away! The map is a maze as follows. [![Maze](https://i.stack.imgur.com/dylCb.png)](https://i.stack.imgur.com/dylCb.png) This maze is procedurally generated by first creating a maze using a depth first recursive backtracking algorithm. And then placing the shown holes in (as well as make the maze more "imperfect". The maze is 65x65 blocks wide, and zero indexed. Thus the blue flag (can) is at 1,1 and the red flag (can) is at 63,63. Blue team spawns at 2,2 and 3,3 4,4 etc. red team spawns at 62,62 and 61,61, 60,60 etc. The blocks in cyan are bots on the blue team, and the blocks in magenta are red bots. The game is always five versus five. Each bot on the team will use your code (but may store other instance variables (or create local files) to keep track of state and differentiate roles. --- ## Gameplay Mines can be placed as you can see in gray. And bombs can be thrown a maximum distance of up to four blocks. These travel for up to four blocks through walls and other players killing only the enemies which stand in your way. After each step they have a 40% chance of falling away. So they have 100% chance of 1 range 60% at 2 range 36% at 3 range and 21.6% at three range Placing a mine or throwing a bomb takes one team ammo. This starts at 0 and can be increased by collecting the orange boxes. Note that four (4) of these ammo caches will be conveniently centered. The Bots are lined up in an array of two red and two blue. I.E RRRRRBBBBB. Gaurding the flag is permitted, but beware that being near the flag(i.e less than five blocks) results in slowness, and only allows movent. every three turns. The Arena picks a random starter for each turn. I.E The order can be RBBBBBRRRRR BBBBBRRRRR BBBRRRRRBB etc.. ## Objective Program your five bots (each has the same class file) to successfully navigate the maze and touch the opposing can while being careful not to accidentally knock over ones own can, or step on a mine. ## Programming The arena and bot entries are currently in Java however a stdin/out wrapper exists for other languages. The arena code will be made available but here is the relevant details. ### Bot Class ``` public class YourUniqueBotName extends Bot{ public YourUniqueBotName(int x , int y, int team){ super(x,y,team); //optional code } public Move move(){//todo implement this method //it should output a Move(); //A move has two paramaters //direction is from 0 - 3 as such // 3 // 2-I-0 // 1 // a direction of 4 or higher means a no-op (i.e stay still) //And a MoveType. This movetype can be //MoveType.Throw //MoveType.Mine //MoveType.Defuse defuse any mine present in the direction given //MoveType.Move } } ``` ### Key Methods Available Note that using any techniques to modify or access data you should generally not have access to is not permitted and will result in disqualification. ``` Arena.getAmmo()[team];//returns the shared ammo cache of your team Arena.getMap();//returns an integer[] representing the map. Be careful since all enemies more than 5 blocks away (straight line distance) and all mines are replaced with constant for spaces //constants for each block type are provided such as Bot.space Bot.wall Bot.mine Bot.redTeam Bot.blueTeam Bot.redFlag Bot.blueFlag Arena.getAliveBots();//returns the number of bots left getX();//returns a zero indexed x coordinate you may directly look at (but not change X) getY();//returns a zero indexed y coordinate (y would work to, but do not change y's value) //Although some state variables are public please do not cheat by accessing modifying these ``` ### StdIn/Out wrapper Interface Specification The interface consists of two modes: initialisation and running. During initialisation mode, a single INIT frame is sent via stdout. This frame's specification is as follows: ``` INIT {Team Membership Id} {Game Map} TINI ``` Where: {Team Membership Id} is an single character: R or B. B meaning blue team, R meaning red team. {Game Map} is a series of rows of ascii characters representing one row of the map. The following ascii characters are valid: F = blue flag G = red flag O = open space W = wall The game will then proceed to send game frames over stdout to each bot as so: ``` FRAME {Ammo} {Alive Bot Count} {Bot X},{Bot Y} {Local Map} EMARF ``` Where: {Ammo} is a string of digits, value will be 0 or greater {Alive Bot Count} is a string of digits, value will be 0 or greater {Box X} is a string of digits representing the X co-ordinate of the bot on the game map. Value will be 0 <= X < Map Width. {Box Y} is a string of digits representing the Y co-ordinate of the bot on the game map. Value will be 0 <= Y < Map Height. {Local Map} is a series of rows of ascii characters representing the whole map surrounding the bot. The following ascii characters are valid: F = blue flag G = red flag O = open space W = wall R = red team bot B = blue team bot M = mine A = ammo The Controller expects that your bot will then output (to stdout) a single line response in the format: ``` {Action},{Direction} ``` Where: {Action} is one of: Move Defuse Mine Throw {Direction} is a single digit between 0 and 4 inclusive. (see direction information earlier) NOTE: all strings will be delimited by \n End of Line character. This will be an elimination tournament. My sample bots will participate as fillers, but I will not award myself the win. In the event of a victory by one of my bots, the title goes to the second place member, and will continue until there is a bot which is not one of mine. Each match consists of 11 rounds of kick the can. If neither team has won a single match by then they both are eliminated. If there is a tie of non-zero score one tie breaker match will be played. If a tie remains both are eliminated. Later rounds may consist of more matches. The seeding of the tournament will be based on the number of upvotes as of 7/31/16 (date subject to change). Each match lasts 4096 turns. A victory grants one point. A tie or loss grants zero points. Good luck! Feel free to look at the code or critique it at this GitHub Repo. <https://github.com/rjhunjhunwala/BotCTF/blob/master/src/botctf/Arena.java> --- Note that I do not have interpreters for too many languages on my computer, and I may need volunteers to run the simulation on their computer. Or I can download the language interpreter. Please ensure that your bots. * Respond in a reasonable amount of time (say 250 ms) * Will not damage my host machine [Answer] # NavPointBot, Java 8 [![enter image description here](https://i.stack.imgur.com/dAkCj.gif)](https://i.stack.imgur.com/dAkCj.gif) Bot is white/blue This bot nominates a leader from friendly bots each frame that will then assign nav points for each bot to navigate to. Initally, all bots are on ammo depot finding duty, then two bots are assigned as guards with the remainder looking for ammo and then attacking the enemy flag. I have found that the game is very dependant on the starting location of depots. As such i cannot really say that this bot is better than any others. Run with `java NavPointBot` ``` import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; public final class NavPointBot implements Serializable { private static final int[][] offsets = new int[][]{{-1,0},{0,-1},{1,0},{0,1}}; private static final List<int[]> navPointsBlue = Arrays.asList(new int[][]{{1,2},{2,1}}); private static final List<int[]> navPointsRed = Arrays.asList(new int[][]{{63,62},{62,63}}); transient private static int mapWidth=0; transient private static int mapHeight=0; transient private char[][] map; transient private char team; transient private int ammo; transient private int botsAlive; transient private int enemyFlagX; transient private int enemyFlagY; private int frameCount; private int botX; private int botY; private String id; private int navPointX; private int navPointY; transient static Object synchObject = new Object(); // used for file read/write synchronisation if multiple instances are run in the same VM final static class Data implements Serializable { int frameCount; boolean[][] diffusedMap = new boolean[mapWidth][mapHeight]; Map<String,NavPointBot> teamMembers = new HashMap<>(); } interface DistanceWeigher { double applyWeight(NavPointBot p1Bot, PathSegment p1); } static class PathSegment { public PathSegment(int tileX, int tileY, int fscore, int gscore, PathSegment parent, int direction, int targetX, int targetY) { super(); this.tileX = tileX; this.tileY = tileY; this.fscore = fscore; this.gscore = gscore; this.parent = parent; this.direction = direction; this.targetX = targetX; this.targetY = targetY; } public PathSegment(PathSegment parent) { this.parent = parent; this.targetX = parent.targetX; this.targetY = parent.targetY; } int tileX; int tileY; int fscore; int gscore; int direction; PathSegment parent; int targetX; int targetY; } public static void main(String[] args) throws Exception { new NavPointBot(UUID.randomUUID().toString()); } private NavPointBot(String id) throws Exception { this.id = id; System.err.println("NavPointBot ("+id+") STARTED"); Data data; while(true) { String line=readLine(System.in); // decode initial frame if ("INIT".equals(line)) { // read team membership team = readLine(System.in).charAt(0); // get the map line = readLine(System.in); List<char[]> mapLines = new ArrayList<>(); while(!"TINI".equals(line)) { mapLines.add(line.toCharArray()); line = readLine(System.in); } map = mapLines.toArray(new char[][]{}); mapHeight = map.length; mapWidth = map[0].length; out: for (int y = 0; y<mapHeight;y++) { for (int x=0; x<mapWidth;x++) { if (map[y][x]==(team=='B'?'G':'F')) { enemyFlagX = x; enemyFlagY = y; break out; } } } data = readSharedData(); data.diffusedMap=new boolean[mapWidth][mapHeight]; writeSharedData(data); } else { System.err.println("Unknown command received: "+line); return; } line = readLine(System.in); while (true) { // decode frame if ("FRAME".equals(line)) { frameCount = Integer.parseInt(readLine(System.in)); ammo = Integer.parseInt(readLine(System.in)); botsAlive = Integer.parseInt(readLine(System.in)); line = readLine(System.in); String[] splits = line.split(","); botX = Integer.parseInt(splits[0]); botY = Integer.parseInt(splits[1]); // get the map line = readLine(System.in); int row=0; while(!"EMARF".equals(line)) { map[row++] = line.toCharArray(); line = readLine(System.in); } } else { System.err.println("Unknown command received: "+line); return; } data = readSharedData(); // this bot is nomitated to be the leader for this frame if (data.frameCount<frameCount || (frameCount==0 && data.frameCount > 3)) { data.frameCount=frameCount; List<NavPointBot> unassignedBots = new ArrayList<>(data.teamMembers.values()); // default nav points to be enemy flag location. unassignedBots.forEach(t->{t.navPointY=enemyFlagY;t.navPointX=enemyFlagX;}); // after 700 frames assume dead lock so just storm the flag, otherwise... if (frameCount<700) { // if the after the initial rush then we will assign guard(s) while we have enemies if (frameCount>70 && botsAlive > data.teamMembers.size()) { Map<NavPointBot, PathSegment> navPointDistances = assignBotShortestPaths(unassignedBots,team=='B'?navPointsBlue:navPointsRed,true, new DistanceWeigher() { @Override public double applyWeight( NavPointBot owner ,PathSegment target) { return target.gscore; } }); navPointDistances.keySet().forEach(s->{s.navPointX=navPointDistances.get(s).targetX;s.navPointY=navPointDistances.get(s).targetY;}); } // the remaining bots will go to ammo depots with a preference to the middle ammo depots List<int[]> ammoDepots = new ArrayList<>(); for (int y = 0; y<mapHeight;y++) { for (int x=0; x<mapWidth;x++) { if (map[y][x]=='A') { ammoDepots.add(new int[]{x,y}); } } } System.err.println("ammoDepots: "+ammoDepots.size()); if (ammoDepots.size()>0) { Map<NavPointBot, PathSegment> ammoDistances = assignBotShortestPaths(unassignedBots,ammoDepots,true, new DistanceWeigher() { @Override public double applyWeight( NavPointBot owner ,PathSegment target) { return target.gscore + (Math.abs(target.targetX-mapWidth/2)+Math.abs(target.targetY-mapHeight/2)*10); } }); // assign ammo depot nav points to closest bots ammoDistances.keySet().forEach(s->{s.navPointX=ammoDistances.get(s).targetX;s.navPointY=ammoDistances.get(s).targetY;}); } } System.err.println("FRAME: "+frameCount+" SET"); data.teamMembers.values().forEach(bot->System.err.println(bot.id+" nav point ("+bot.navPointX+","+bot.navPointY+")")); System.err.println(); } // check to see if enemies are in range, if so attack the closest List<int[]> enemies = new ArrayList<>(); for (int y = 0; y<mapHeight;y++) { for (int x=0; x<mapWidth;x++) { if (map[y][x]==(team=='B'?'R':'B')) { int attackDir = -1; int distance = -1; if (x==botX && Math.abs(y-botY) < 4) { distance = Math.abs(y-botY); attackDir = botY-y<0?1:3;} if (y==botY && Math.abs(x-botX) < 4) { distance = Math.abs(x-botX); attackDir = botX-x<0?0:2;} if (attackDir>-1) { enemies.add(new int[]{x,y,distance,attackDir}); } } } } enemies.sort(new Comparator<int[]>() { @Override public int compare(int[] arg0, int[] arg1) { return arg0[2]-arg1[2]; } }); String action; // attack enemy if one within range... if (enemies.size()>0) { action = "Throw,"+enemies.get(0)[3]; } else { // set action to move to navpoint PathSegment pathSegment = pathFind(botX,botY,navPointX,navPointY,map,true); action = "Move,"+pathSegment.direction; // clear mines if within 5 spaces of enemy flag if ((team=='B' && botX>=mapWidth-5 && botY>=mapHeight-5 ) || (team=='R' && botX<5 && botY<5 )) { if (!data.diffusedMap[pathSegment.parent.tileX][pathSegment.parent.tileY]) { action = "Defuse,"+pathSegment.direction; data.diffusedMap[pathSegment.parent.tileX][pathSegment.parent.tileY]=true; } } } writeSharedData(data); System.out.println(action); line = readLine(System.in); } } } /** * assigns bots to paths to the given points based on distance to the points with weights adjusted by the given weigher implementation */ private Map<NavPointBot, PathSegment> assignBotShortestPaths(List<NavPointBot> bots, List<int[]> points, boolean exact, DistanceWeigher weigher) { Map<Integer,List<PathSegment>> pathMap = new HashMap<>(); final Map<PathSegment,NavPointBot> pathOwnerMap = new HashMap<>(); for (NavPointBot bot : bots) { for(int[] navPoint: points) { List<PathSegment> navPointPaths = pathMap.get((navPoint[0]<<8)+navPoint[1]); if (navPointPaths == null) { navPointPaths = new ArrayList<>(); pathMap.put((navPoint[0]<<8)+navPoint[1],navPointPaths); } PathSegment path = pathFind(bot.botX,bot.botY,navPoint[0],navPoint[1],map,exact); pathOwnerMap.put(path, bot); navPointPaths.add(path); } } // assign bot nav point based on shortest distance Map<NavPointBot, PathSegment> results = new HashMap<>(); for (int[] navPoint: points ) { List<PathSegment> navPointPaths = pathMap.get((navPoint[0]<<8)+navPoint[1]); if (navPointPaths !=null) { Collections.sort(navPointPaths, new Comparator<PathSegment>() { @Override public int compare(PathSegment p1, PathSegment p2) { NavPointBot p1Bot = pathOwnerMap.get(p1); NavPointBot p2Bot = pathOwnerMap.get(p2); double val = weigher.applyWeight(p1Bot, p1) - weigher.applyWeight(p2Bot, p2); if (val == 0) { return p1Bot.id.compareTo(p2Bot.id); } return val<0?-1:1; } }); for (PathSegment shortestPath : navPointPaths) { NavPointBot bot = pathOwnerMap.get(shortestPath); if (!results.containsKey(bot) ) { results.put(bot,shortestPath); bots.remove(bot); break; } } } } return results; } /** * reads in the previous bot's view of teammates aka shared data */ private Data readSharedData() throws Exception { synchronized(synchObject) { File dataFile = new File(this.getClass().getName()+"_"+team); Data data; if (dataFile.exists()) { FileInputStream in = new FileInputStream(dataFile); try { java.nio.channels.FileLock lock = in.getChannel().lock(0L, Long.MAX_VALUE, true); try { ObjectInputStream ois = new ObjectInputStream(in); data = (Data) ois.readObject(); } catch(Exception e) { System.err.println(id+": CORRUPT shared Data... re-initialising"); data = new Data(); } finally { lock.release(); } } finally { in.close(); } } else { System.err.println(id+": No shared shared Data exists... initialising"); data = new Data(); } //purge any dead teammates... for (NavPointBot bot : new ArrayList<>(data.teamMembers.values())) { if (bot.frameCount < frameCount-3 || bot.frameCount > frameCount+3) { data.teamMembers.remove(bot.id); } } // update our local goals to reflect those in the shared data NavPointBot dataBot = data.teamMembers.get(id); if (dataBot !=null) { this.navPointX=dataBot.navPointX; this.navPointY=dataBot.navPointY; } // ensure that we are a team member data.teamMembers.put(id, this); return data; } } private void writeSharedData(Data data) throws Exception { synchronized(synchObject) { File dataFile = new File(this.getClass().getName()+"_"+team); FileOutputStream out = new FileOutputStream(dataFile); try { java.nio.channels.FileLock lock = out.getChannel().lock(0L, Long.MAX_VALUE, false); try { ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(data); oos.flush(); } finally { lock.release(); } } finally { out.close(); } } } /** * return the direction to move to travel for the shortest route to the desired target location */ private PathSegment pathFind(int startX, int startY, int targetX,int targetY,char[][] map,boolean exact) { // A* if (startX==targetX && startY==targetY) { return new PathSegment(targetX,targetY,0, 0,null,4,targetX,targetY);//PathSegment.DEFAULT; } else { int[][] tileIsClosed = new int[mapWidth][mapHeight]; // find an open space in the general vicinity if exact match not required if (!exact) { out: for (int y=-1;y<=1;y++) { for (int x=-1;x<=1;x++) { if (startX == targetX+x && startY==targetY+y) { return new PathSegment(targetX,targetY,0, 0,null,4,targetX,targetY);//PathSegment.DEFAULT; } else if (targetY+y>=0 && targetY+y<mapHeight && targetX+x>=0 && targetX+x < mapWidth && map[targetY+y][targetX+x]=='O') { targetX+=x; targetY+=y; break out; } } } } PathSegment curSegment = new PathSegment(targetX,targetY,1,1,null,4,targetX,targetY); PathSegment newSegment; Set<PathSegment> openList = new HashSet<PathSegment>(); openList.add(curSegment); do { if (openList.isEmpty()) { break; } PathSegment currentBestScoringSegment = openList.iterator().next(); // Look for the lowest F cost square on the open list for (PathSegment segment : openList) { if (segment.fscore<currentBestScoringSegment.fscore) { currentBestScoringSegment = segment; } } curSegment = currentBestScoringSegment; // found path if (startX==curSegment.tileX && startY==curSegment.tileY) { break; } // if not in closed list if (tileIsClosed[curSegment.tileX][curSegment.tileY]==0) { // Switch it to the closed list. tileIsClosed[curSegment.tileX][curSegment.tileY]=1; // remove from openlist openList.remove(curSegment); // add neigbours to the open list if necessary for (int i=0;i<4;i++) { int surroundingCurrentTileX=curSegment.tileX+offsets[i][0]; int surroundingCurrentTileY=curSegment.tileY+offsets[i][1]; if (surroundingCurrentTileX>=0 && surroundingCurrentTileX<mapWidth && surroundingCurrentTileY>=0 && surroundingCurrentTileY<mapHeight ) { newSegment = new PathSegment( curSegment); newSegment.tileX = surroundingCurrentTileX; newSegment.tileY = surroundingCurrentTileY; newSegment.direction = i; switch(map[surroundingCurrentTileY][surroundingCurrentTileX]) { case 'W': case 'F': case 'G': continue; } int surroundingCurrentGscore=curSegment.gscore+1 + ((surroundingCurrentTileX!=startX && surroundingCurrentTileY!=startY && map[surroundingCurrentTileY][surroundingCurrentTileX]==team)?20:0);//+map[surroundingCurrentTileY][surroundingCurrentTileX]!='O'?100:0; newSegment.gscore=surroundingCurrentGscore; newSegment.fscore=surroundingCurrentGscore+Math.abs( surroundingCurrentTileX-startX)+Math.abs( surroundingCurrentTileY-startY); openList.add(newSegment); } } } else { // remove from openlist openList.remove(curSegment); } } while(true); return curSegment; } } /** * Reads a line of text from the input stream. Blocks until a new line character is read. * NOTE: This method should be used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing * text line tokenization. This means that BufferedReader.readLine() will block until many game frames have been received. * @param in a InputStream, nominally System.in * @return a line of text or null if end of stream. * @throws IOException */ private static String readLine(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); int readByte = in.read(); while (readByte>-1 && readByte!= '\n') { sb.append((char) readByte); readByte = in.read(); } return readByte==-1?null:sb.toString(); } } ``` [Answer] # Optimised Pathfinder JAVA Thanks to @Moogie for helping me optimise my messy floodfill pathfinding. Here is the source for the bot. This guy knows how important it is to defend his flag. He alocates three defenders and two attackers. The defenders hang back and defend/gather ammo, the two attackers take (a fairly straight) path to the flag (and collect the ammo at the middle). He shoots anyone he sees, and should be fierce competition. The defenders place mines around the flag and camp until there is no opposition left so they can go and kick the can. ``` /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * todo fight */ package botctf; import botctf.Move.MoveType; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * * @author rohan */ public class PathFinderOptimised extends Bot { private static final int[][] offsets = new int[][]{{0,-1},{1,0},{0,1},{-1,0}}; public static boolean shouldCampingTroll = true; private int moveCounter = -1;//dont ask public boolean defend; public PathFinderOptimised(int inX, int inY, int inTeam) { super(inX, inY, inTeam); //System.out.println("Start"); //floodFillMap(getX(), getY()); //System.out.println("Finish"); defend=inX%2==0; } public static int[][] navigationMap; boolean upMine = false; boolean sideMine = false; int[][] myMap; @Override public Move move() { moveCounter++; myMap=getMap(); int targetX, targetY; int enemyTeam=team==redTeam?blueTeam:redTeam; ArrayList<Coord> enemyCoordinates=new ArrayList<>(); for(int i = 0; i<65;i++){ for(int j = 0;j<65;j++){ if(map[i][j]==enemyTeam){ enemyCoordinates.add(new Coord(i,j)); } } } for(Coord enemy:enemyCoordinates){ int enemyX=enemy.x; int enemyY=enemy.y; int dX= enemy.x-this.x; int dY= enemy.y-this.y; //System.out.println(dX+"|"+dY); if((dX==0||dY==0)){ if(Arena.getAmmo()[this.team]>0){ if(dX>0&&dX<5){ return new Move(0,MoveType.Throw); } if(dX<0&&dX>-5){ return new Move(2,MoveType.Throw); } if (dY>0&&dY<5){ return new Move(1, MoveType.Throw); } if(dY<0&&dY>-5){ return new Move(3,MoveType.Throw); } } } } if(myMap[x+1][y]==ammo){ return new Move(0,MoveType.Move); } if(myMap[x-1][y]==ammo){ return new Move(2,MoveType.Move); } if(myMap[x][y+1]==ammo){ return new Move(1,MoveType.Move); } if(myMap[x][y-1]==ammo){ return new Move(3,MoveType.Move); } int bestOption = 4; if (defend) { if(Arena.getAliveBots()==1){ defend=false; } int bestAmmoX = -1; int bestAmmoY = -1; int bestAmmoDist = Integer.MAX_VALUE; for (int i = 0; i < 65; i++) { for (int j = 0; j < 65; j++) { if (myMap[i][j] == ammo) { int path = pathFind(getX(),getY(),i,j,myMap); if ((path & 0xFFFFFF) < bestAmmoDist) { bestAmmoX = i; bestAmmoY = j; bestAmmoDist = (path & 0xFFFFFF); bestOption = path >> 24; } } } } if (bestAmmoDist<15||Arena.getAmmo()[this.team]==0){ targetX = bestAmmoX; targetY = bestAmmoY; } else { targetX = team == redTeam ? 62 : 2; targetY = team == redTeam ? 62 : 2; } } else { if(this.x>18&this.x<42&&this.y>16&&this.y<44&&myMap[33][33]==ammo){ targetX=33; targetY=33; }else{ if (this.team == redTeam) { targetX = 1; targetY = 1; } else { targetX = 63; targetY = 63; } } } if(upMine&&sideMine){ if(targetX==2||targetX==62){ if(targetY==2||targetY==62){ targetX+=targetX==2?3:-3; targetY+=targetY==2?3:-3; } } }else if (targetX == getX() && targetY == getY()) { if (!upMine) { upMine = true; if (this.team == redTeam) { return new Move(0, MoveType.Mine); } else { return new Move(2, MoveType.Mine); } }else if(!sideMine){ sideMine=true; if (this.team == redTeam) { return new Move(1, MoveType.Mine); } else { return new Move(3, MoveType.Mine); } } else { return new Move(5, MoveType.Move); } } bestOption = pathFind(getX(),getY(),targetX,targetY,myMap) >> 24; MoveType m=MoveType.Move; if(moveCounter%2==0){ if(this.team==redTeam?x<25&&y<25:x>39&&y>39){ m=MoveType.Defuse; } } //System.out.println(bestOption); return new Move(bestOption, m); } /** * returns a result that is the combination of movement direction and length of a path found from the given start position to the target * position. result is ((direction) << 24 + path_length) */ private int pathFind(int startX, int startY, int targetX,int targetY,int[][] map) { class PathSegment { public PathSegment(int tileX, int tileY, int fscore, int gscore, PathSegment parent) { super(); this.tileX = tileX; this.tileY = tileY; this.fscore = fscore; this.gscore = gscore; this.parent = parent; } public PathSegment(PathSegment parent) { this.parent = parent; } int tileX; int tileY; int fscore; int gscore; PathSegment parent; } // A* if (startX==targetX && startY==targetY) { return 4; } else { int[][] tileIsClosed = new int[64][64]; PathSegment curSegment = new PathSegment(targetX,targetY,1,1,null); PathSegment newSegment; Set<PathSegment> openList = new HashSet<PathSegment>(); openList.add(curSegment); do { if (openList.isEmpty()) { break; } PathSegment currentBestScoringSegment = openList.iterator().next(); // Look for the lowest F cost square on the open list for (PathSegment segment : openList) { if (segment.fscore<currentBestScoringSegment.fscore) { currentBestScoringSegment = segment; } } curSegment = currentBestScoringSegment; // found path if (startX==curSegment.tileX && startY==curSegment.tileY) { break; } // if not in closed list if (tileIsClosed[curSegment.tileX][curSegment.tileY]==0) { // Switch it to the closed list. tileIsClosed[curSegment.tileX][curSegment.tileY]=1; // remove from openlist openList.remove(curSegment); // add neigbours to the open list if necessary for (int i=0;i<4;i++) { final int surroundingCurrentTileX=curSegment.tileX+offsets[i][0]; final int surroundingCurrentTileY=curSegment.tileY+offsets[i][1]; if (surroundingCurrentTileX>=0 && surroundingCurrentTileX<64 && surroundingCurrentTileY>=0 && surroundingCurrentTileY<64 ) { newSegment = new PathSegment( curSegment); newSegment.tileX = surroundingCurrentTileX; newSegment.tileY = surroundingCurrentTileY; if (map[surroundingCurrentTileX][surroundingCurrentTileY]=='W') { continue; } int surroundingCurrentGscore=curSegment.gscore+1; newSegment.gscore=surroundingCurrentGscore; newSegment.fscore=surroundingCurrentGscore+Math.abs( surroundingCurrentTileX-startX)+Math.abs( surroundingCurrentTileY-startY); openList.add(newSegment); } } } else { // remove from openlist openList.remove(curSegment); } } while(true); if (curSegment.parent.tileX-startX<0) return (2 << 24) | curSegment.gscore; else if (curSegment.parent.tileX-startX>0) return (0 << 24) | curSegment.gscore; else if (curSegment.parent.tileY-startY<0) return (3 << 24) | curSegment.gscore; else if (curSegment.parent.tileY-startY>0) return (1 << 24) | curSegment.gscore; } throw new RuntimeException("Path finding failed"); } } ``` ]
[Question] [ Back in the day, all the 1337 kids used text faders in chatrooms. I don't know about you guys, but I want to feel cool like they did. The only problem is that their old scripts and applications were heavily coupled to the software they were made for, so I can't just make use of this amazing functionality wherever I want. I also want the solution to be easily portable so you're going to need to make the code as small as possible so that it will fit on my floppy disk (I'd rather only carry one floppy but if your source code is too big I can carry more than one [:P](https://www.youtube.com/watch?v=up863eQKGUI)). ## Input * A list of colors (rgb, hex, names, etc) * Text to format Your program should expect the list of colors to contain at least 2 colors. Text to format can be any length greater than zero and characters will be limited to printable ascii. (Hint: Longer text inputs may require you to reuse intermediate colors for consecutive characters) ## Output The output text should not differ from the input text in any way other than font and/or markup/styling (Note: if your output contains html markup then you'll need to html encode the input). You may output text with markup/styling (html style tags, console colors, etc.) or a picture of the faded text. All color hexes should be present in the output unless the input does not contain enough characters to meet this requirement. If this is the case, then consult the priority rules to determine which color hexes should be present in your output. **The order or these colors in your output should still be input order.** ### Color Priority Rules 1. In the event that the input is one character, the first color will be used 2. In the event that there are only two characters, the first and last color will be used 3. In the event that there are more than three colors and more colors than characters, the first and last colors should be prioritized, then the rest of the colors in their inputted order. 4. In the event that there are more characters than colors, the characters should fade from one color to the next using intermediate colors Examples (Priority rules 1-3 respectively): # Colors | Color0 | ... | Colorn | Text `3 ff0000 0000ff ffff00 M` -> [![only first](https://i.stack.imgur.com/663Ue.png)](https://i.stack.imgur.com/663Ue.png) `3 ff0000 0000ff ffff00 hi` -> [![ignore 2nd](https://i.stack.imgur.com/YM9GY.png)](https://i.stack.imgur.com/YM9GY.png) `4 ff0000 0000ff ffff00 0fff00 sup` -> [![ignore 3rd](https://i.stack.imgur.com/iZ8ne.png)](https://i.stack.imgur.com/iZ8ne.png) To be clear, the text color should fade from one color hex to the next. The fade does not have to be perfectly uniform but it shouldn't be an abrupt color change unless there aren't enough characters to fade nicely. Generally this fade is achieved by choosing intermediate colors for each of the characters by incrementing/decrementing the rgb values by some interval determined by the number of characters you have to work with and the difference between the colors. For example if we needed a single color between [![red](https://i.stack.imgur.com/Pd5ir.png)](https://i.stack.imgur.com/Pd5ir.png) (#ff0000) and [![black](https://i.stack.imgur.com/2Aupr.png)](https://i.stack.imgur.com/2Aupr.png) (#000000), we might choose [![#800000](https://i.stack.imgur.com/27PDQ.png)](https://i.stack.imgur.com/27PDQ.png) as it sits right in the middle. Optimal output will look rather pretty. Example (Priority rule 4): `3 ff0000 ff7f00 f0ff00 To be or not to be, that is the question...` -> [![to be or not](https://i.stack.imgur.com/SHqHo.png)](https://i.stack.imgur.com/SHqHo.png) **-OR-** ``` <span style="color:#ff0000;">T</span><span style="color:#ff0600;">o</span><span style="color:#ff0c00;"> </span><span style="color:#ff1200;">b</span><span style="color:#ff1800;">e</span><span style="color:#ff1e00;"> </span><span style="color:#ff2400;">o</span><span style="color:#ff2a00;">r</span><span style="color:#ff3000;"> </span><span style="color:#ff3600;">n</span><span style="color:#ff3c00;">o</span><span style="color:#ff4300;">t</span><span style="color:#ff4900;"> </span><span style="color:#ff4f00;">t</span><span style="color:#ff5500;">o</span><span style="color:#ff5b00;"> </span><span style="color:#ff6100;">b</span><span style="color:#ff6700;">e</span><span style="color:#ff6d00;">,</span><span style="color:#ff7300;"> </span><span style="color:#ff7900;">t</span><span style="color:#ff7f00;">h</span><span style="color:#fe8500;">a</span><span style="color:#fe8b00;">t</span><span style="color:#fd9100;"> </span><span style="color:#fc9700;">i</span><span style="color:#fb9d00;">s</span><span style="color:#fba400;"> </span><span style="color:#faaa00;">t</span><span style="color:#f9b000;">h</span><span style="color:#f9b600;">e</span><span style="color:#f8bc00;"> </span><span style="color:#f7c200;">q</span><span style="color:#f6c800;">u</span><span style="color:#f6ce00;">e</span><span style="color:#f5d400;">s</span><span style="color:#f4da00;">t</span><span style="color:#f4e100;">i</span><span style="color:#f3e700;">o</span><span style="color:#f2ed00;">n</span><span style="color:#f1f300;">.</span><span style="color:#f1f900;">.</span><span style="color:#f0ff00;">.</span> ``` **In your answer please specify how your output should be displayed (as html, in a console, as an image, etc.).** \* All black backgrounds are only for color emphasis and are not required ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. If you manage to add fade to individual characters then I'll forever think you're cool (but no bonus to score as this will not be fair for some langs) [Answer] ## JavaScript (ES6), 290 bytes ``` h=a=>f(a,a.shift());f= (a,w)=>[...w].map((c,i)=>{l=w.length-1;m=a.length-1;s=o.appendChild(document.createElement('span'));s.textContent=c;s.style.color=`#${i?i-l?a[r=l%m,n=l/m|0,i<r*n+r?++n:i-=r,k=i/n|0,k++].replace(/./g,(c,d)=>((parseInt(c,16)*(n-i%n)+i%n*parseInt(a[k][d],16))/n|0).toString(16)):a[m]:a[0]}`;}) ``` ``` <textarea rows=10 cols=40 oninput="o.textContent='';h(this.value.split`\n`)">Type the text here and the colours on subsequent lines. FF0000 00FF00 0000FF</textarea><div id=o> ``` [Answer] # Pyth, 126 bytes Obligatory root-mean-square average instead of direct arithmetic mean. ``` L%"<span style=\"color:#%s\">%s</span>",smt.H+256s*255@d2ebhbMm+hG*-eGhGcdHH=Q^RL2Q+smsyMC,hdCgRlhdCedC,ctlQPzC,QtQy,ez?tlzeQh ``` [Try it online!](http://pyth.herokuapp.com/?code=L%25%22%3Cspan+style%3D%5C%22color%3A%23%25s%5C%22%3E%25s%3C%2Fspan%3E%22%2Csmt.H%2B256s%2a255%40d2ebhbMm%2BhG%2a-eGhGcdHH%3DQ%5ERL2Q%2BsmsyMC%2ChdCgRlhdCedC%2CctlQPzC%2CQtQy%2Cez%3FtlzeQh&input=%5B%5B1.0%2C+0.0%2C+0.0%5D%2C+%5B1.0+%2C0.51+%2C0.0%5D%2C+%5B0.942%2C+1.0%2C+0.0%5D%5D%0ATo+be+or+not+to+be%2C+that+is+the+question...&debug=0) Sample output: [![sample](https://i.stack.imgur.com/Yex0N.png)](https://i.stack.imgur.com/Yex0N.png) [Answer] ## Java, ~~702~~ 662 characters Two functions golfed: ``` import java.awt.*;String f(Color C,char c){return"<span style=\"color:#"+Integer.toHexString(C.getRGB()).substring(2)+";\">"+c+"</span>";}String c(String t,String[]h){String r="";int l=h.length,e=t.length(),i=0,s=0,g=1,c=-1,p,q,u;double d,m=0,v;char[]T=t.toCharArray();Color C[]=new Color[l],H[],a,b;for(;i<l;)C[i]=Color.decode(h[i++]);if(l>e){H=java.util.Arrays.copyOfRange(C,0,e);H[e-1]=C[l-1];H[0]=C[0];C=H;l=e;}d=--e/(l-1.);for(;++c<e;){a=C[s];b=C[g];p=b.getRed()-a.getRed();q=b.getGreen()-a.getGreen();u=b.getBlue()-a.getBlue();v=m/d;r+=f(new Color(a.getRGB()+((int)(v*p)<<16|(int)(v*q)<<8|(int)(v*u))),T[c]);if(++m>d){m-=d;s=g++;}}return r+f(C[l-1],T[e]);} ``` As nobody can read this: here are both functions in there ungolfed version in a class: ``` import java.awt.*; public class Q80554 { static String format(Color color, char character) { return "<span style=\"color:#" + Integer.toHexString(color.getRGB()).substring(2) + ";\">" + character + "</span>"; } static String colorizeB(String text, String[] hexColors) { String result = ""; int colorsLength = hexColors.length, textLength = text.length(), i, currentStartColorPos = 0, currentGoalColorPos = 1, currentCharPos = -1, diffColorRed, diffColorGreen, diffColorBlue; double difference, goneDifference = 0, relativeChange; char[] textArray = text.toCharArray(); Color colors[] = new Color[colorsLength], changer[], currentStartColor, currentGoalColor; for (i = 0; i < colorsLength;) colors[i] = Color.decode(hexColors[i++]); if (colorsLength > textLength) { changer = Arrays.copyOfRange(colors, 0, textLength); changer[textLength - 1] = colors[colorsLength - 1]; changer[0] = colors[0]; colors = changer; colorsLength = textLength; } // fade difference = --textLength / (colorsLength - 1.); // space between colors for (; ++currentCharPos < textLength;) { currentStartColor = colors[currentStartColorPos]; currentGoalColor = colors[currentGoalColorPos]; diffColorRed = currentGoalColor.getRed() - currentStartColor.getRed(); diffColorGreen = currentGoalColor.getGreen() - currentStartColor.getGreen(); diffColorBlue = currentGoalColor.getBlue() - currentStartColor.getBlue(); relativeChange = goneDifference / difference; result += format(new Color(currentStartColor.getRGB() + ((int) (relativeChange * diffColorRed) << 16 | (int) (relativeChange * diffColorGreen) << 8 | (int) (relativeChange * diffColorBlue))), textArray[currentCharPos]); if (++goneDifference > difference) { goneDifference -= difference; currentStartColorPos = currentGoalColorPos++; } } // last character always has last color return result + format(colors[colorsLength - 1], textArray[textLength]); } } ``` Here you have an upper bound for your own code. Usage is by calling `colorize` (or c in the golfed version) and pass the text and an array of hex color codes. The function will return a String with HTML-tags like the OP did, thus you need some way to render the HTML. The algorithm is easier as the question looks like. The first character always gets the first color, the last one always the last. ~~If we have more colors than chars in the text we just iterate over the text and colors and apply these.~~ The fun part is the one with the fades: I started of by finding out in what distance the colors are on the text. I basically calculate the red, green and blue difference between two given colors and then add a part of this difference to the first color, depending on where the char is between the colors. If it leaves the interval of two colors we start from new with the next two colors. This is repeated for all but the last character, which we know is always the last color. This gives a very beautiful fading. That question was very much fun! Thanks! ### Updates Now I don't handle all the cases specially. Instead I trim the colors if there are two much and apply the fade function to every string. If there were more colors than text then the colors will be trimmed and the fading function will work exactly as a simple mapping. ]
[Question] [ I have not laughed as much from Stack Exchange content as I have from [this](https://english.stackexchange.com/q/312686/106629). I think you all will enjoy this challenge, as it is inspired by what is over there. You will write a function or program that is code-golf, i.e. it would have to be as short as you can make it. Given a text, return (both by any means) the text where you will have contracted as many words as possible according [this table](https://gist.github.com/KeyboardFire/f30c0c851bf758f9957c). You shall not pull information from the table, rather you must have all necessary information included in your code. All default rules ought not to be broken as we will not have any unfair competition. You need not consider text if it is not capitalized as in the table, so you must not convert *`you all WOULD not have`* or *`You all would not have`* to *`y'all'dn't've`*. You may match just the good old apostrophe (U+0027) or [any nice ones](https://en.wikipedia.org/wiki/Apostrophe#Unicode); whatever you want to. # Example input above ↑ and corresponding output below ↓ I'ven't laughed as much from StackExchange content as I've from [this](https://english.stackexchange.com/q/312686/106629). I think y'all'll enjoy this challenge, as 'tis inspired by what's over there. You'll write a function or program that's code-golf, i.e. it'd've to be as short as you can make it. Given a text, return (both by any means) the text where you'll have contracted as many words as possible according [this table](https://gist.github.com/KeyboardFire/f30c0c851bf758f9957c). You shan't pull information from the table, rather you must've all necessary information included in your code. All default rules oughtn't to be broken as we'lln't've any unfair competition. You needn't consider text if it'sn't capitalized as in the table, so you mustn't convert *`you all WOULD not have`* or *`You all would not have`* to *`y'all'dn't've`*. You may match just the good ol’ apostrophe (U+0027) or [any nice ones](https://en.wikipedia.org/wiki/Apostrophe#Unicode); whatever you wanna. [Answer] ## Perl, ~~3429~~ 1095 bytes Compressed the text. [uuencoded version of script](http://pastebin.com/82F5EDhG) ``` @a=split('!',uncompress(<DATA>.<DATA>));while(<>){chomp;$l=$_;for$d(@a){chomp $d;($x,$y)=split(/,/,$d);if($l=~m/$y/){$l=~s/$y/$x/g}}print "$l\n"} __DATA__ x<9c>uVK<b2><a3>0^L<dc><e7>^Tdņ<8b>p^Lϋ'<b8>^FpUL<e2><e2><f6><a3><af>-<9b><bc>^Mv<b7>d<a9>%<c4><c7>m<fb>xLn^[<f6>x<dc><ee><ee><e5> <be><<e3>^_<87>^P<ae>^B<e3>{}<8c>^_?<d1>fX<dc><c7>^K n<95>^G<df><ce>V^M<b7><fb>#^P^C<8b><e0><e8>^S^Q<b0>*Ø<d1>3<9e>1<ec><cf>ሷ<fb><e2>4^[<ec>L.<e6><95>D<9c>^X'<c5>^_<cf><c4>G<aa>[<fc><f8><98>^V^O<e7>^_^L(<a8>^_<b2><a9>N}<88>#<b8><ae><88><d3><e2><d6><d5><e0>^\^DrR^L<9a>J<96>$D<e3>^P:{@s̘.<e6>^A<da>c<a1><a6>^G^B<f3>!<c3> <81>H<84>9|<81><a1>A<d8><db><db>}<86>`3W;s<b1>sS+<db>%Ռ<89>f<ad>S^P'<9d><c7>^M<f6>n<c3>^]<f7>t^^jWg^N<cc>!^CU<ab><a5><86>^C2<84><83>% @W<c0>V<84><fa><88>^L<80><90>^Y<b0>^H)<98><a5>^@<e4>^LGm8rB4^N<aa>b<f5><e8>^@<d7><e1>^M^N<9b>^[<dd>6m<ee><81><f5>l<e1><b9>^\2]<b4>7<f3><a5><b6>j^P<ae>:<8b><e3>;<b1>^_<ac><e2>^F;<f2>B<86><9d>v<ef>i\qe<a7>8<fe><ac><f1><e7><df>^T<ff>^N^G<8c>^C^A`<d7>q<8a>؈<f8><96><f4><b4><e1>#<d0>^Sd<a8>5<ca><e0><bc>&^]<ea><a4>S<9d><ba><b1><ae>~<d2><e7>ē<9c><ea>h^[<86>{<9d>tx<93>^]ob<95><ea><9c><c2><c5>'<90><8b><be>FxW$<99>^W<89>Xj<f7><8b>՘<80><8d><9b><ff>^S^_'<d6>"[)<bc>^X(<9a>ښ^V|9<ab><cd>(&<95><d3>^F0<b2><d4>^S;<a5>N<da><c0>o6i<a5><9a><92>՝<be>^[<82><f0>q<f7><a2>^Uv<b5>L<a2>U$Z<fa>"<db>s<a6>D4<88>6<b4><18><a5><8a>FC2^Z<d2>7Z^E^_^K<bc><b3>%5<ed><ab>h1<a9>l<b6><f6>¯<e7><8d>x6<8a>H<b6><9a>^B<be>Xk^QlL<8d><ae><f4><9b> <8b>9^VG<af>^]\%^NQ<89>^Y:m ><e3>_<d8>wZ<b9>p<a1><b0>hfmm<bf>^T<ca><e4>K<fd>Ử\*<81>SOI▒%w^]g<a2><fb>Q.^^<9d>Y-<dd>A{<c8><f0>ƻ^KU<bf>^P<e4>A<ed><f4><e5>a^Q<ae>^Q^X<f8><ad>fS<ad>k^S^X=~<89><ab><b7> <a8><97>^D<d4><f6><9d>6Fw\<93>s<ce><f1>^H<89>?^]<b8>ώ@Ɩg<87>^?%p=<e8><a7>$<f3><cf>Fַb<c6>[<99><e5><be>#<90>²<bf><f4>=<cb>H<e4>v^^4<82>t5<fb>ڝ<ec><fb>ސUy<82>/r<a3><8a>^A<f1>!<f5><e5><9f><\E<ac><8c>7<ae>z?^ZN<a2>"<85>q<91><e2><c8><<f3><b9><^D<96>^H^]<e6>^?^Pb>^ϐ<a0>^E<f4><a0><93><df>5J%8?^Z<b4><f2><9f>Q<96><89><cf><f5>!h<a9>pa4?r$<80>O<b2><82>H<e1><a3><dc>/<84><ec>^S<db>{R<fc><f4><ae>^@AM<8a><b5>o<85>ѮEnZԞE<92>^TU<b5><c2> H<f2>jƓÝ%<dc><c9><e1>N^Mw<d2><f9>S<c3>)<a4>pQ'<a6>^[^W<fa><c1>V^R<b1>|<90><9b>b<cd><e7><f8>2<b3><fa>16o<89>s<84>^FLg|^O<d4>^H<82>e^L<bf>x]]<ac><99>^F<bf>ڋl<b5>6<a7><f5><95>И/<e7><eb>S<af>^<8d>^]<e8><f8><86>[<8d>^\<8d>^DA<cd><d3>(,~2^RHH4^Y <c3><d4><d8>/<91><fc><f2><8a><8b>F},<91><ae>ҍb<e2>^K <ff><92><91>z\<ba><fa>^_<bf><fc><b5><8f> perl -MCompress::Zlib script.pl <sample.txt You will write a function or program that's code-golf, i.e. it'd've to be as short as you can make it. Given a text, return (both by any means) the text where you'll have contracted as many words as possible according this table. You shan't pull information from the table, rather you must've all necessary information included in your code. All default rules oughtn't to be broken as we'lln't've any unfair competition. You needn't consider text if 'tisn't capitalized as in the table, so you mustn't convert y'all WOULD not've or You all wouldn't've to y'all'dn't've. You may match just the good ol' apostrophe (U+0027) or any nice ones; whatever you wanna. ``` ]
[Question] [ A Norwegian Birth Number consists of 11 digits, composed the following way: ``` DDMMYYiiikk ``` * `DD` is the day (from 01-31) * `MM` is the month (from 01-12) * `YY` is the year (from 00-99). It's not differentiated between 1900 and 2000 * `iii` is the "individual number" * `kk` are two control digits `iii` is determined by birthyear and gender the following way * 0000-1900: Disregard, there is some inconsistency and special cases * 1900-1999: Range = 000-499 * 2000-2039: Range = 500-999 * Female: Even numbers (and 000) * Male: Odd numbers The control numbers are determined the following way: Let's call the 11 digits: ``` d1 d2 m1 m2 y1 y2 i1 i2 i3 k1 k2 ``` Then the control digits can be calculated using the equations: ``` k1 = 11 - ((3 * d1 + 7 * d2 + 6 * m1 + 1 * m2 + 8 * y1 + 9 * y2 + 4 * i1 + 5 * i2 + 2 * i3) mod 11) k2 = 11 - ((5 * d1 + 4 * d2 + 3 * m1 + 2 * m2 + 7 * y1 + 6 * y2 + 5 * i1 + 4 * i2 + 3 * i3 + 2 * k1) mod 11). ``` For some combinations, the control numbers `k1` or `k2` can become `10`. If that's the case, the number will be invalid. If the sum modulus 11 for `k1` or `k2` is 11, i.e. `k1 = 11 - (11 mod 11)`, then the control digit will be 0, not 11. **Challenge** Take a letter, `M` or `F` (male or female), and an eleven digit number as input, and check if the Birth Number is valid according to the rules above. * Input format and order is optional * The 11 numbers must be a single number or a consecutive string (you can't take the input as `DD, MM, YY, iii, kk`). * You can assume the date is valid (310699xxxxx will not be given as input) * Output is a truthy/falsy value (1/0, true/false etc.) * Program or function * All standard rules apply You can find all valid numbers on [this page](http://www.fnrinfo.no/Verktoy/FinnLovlige_Dato.aspx) (in Norwegian) by choosing a date. Examples: ``` M, 01010099931 True F, 01029042620 True M, 0101009841 False F, 01010051866 True F, 08021690849 True M, 01029040105 True M, 01029037473 False ``` Shortest code in bytes win. [Answer] # Python 3, ~~227~~ 221 bytes Function that takes two arguments, the gender 'm', and the birthnumber 'n', both as strings. There may be some more golfing to be done, especially in the last line. I'll keep working on it. ``` def a(m,n): o=[3,7,6,1,8,9,4,5,2];t=[5,4,3,2,7,6,5,4,3,2];n=list(map(int,n));y=z=b=0;q=11 for i in n[:9]:z+=o[b]*i;y+=t[b]*i;b+=1 print((q-z%q)%q==n[9] and (q-(y-z-z)%q)%q==n[-1] and len(n)<12 and ord(m)%2==n[8]%2) ``` [Answer] ## JavaScript (ES2016), 275 259 255 254 252 Bytes **Golfed**: ``` f=(g,I)=>{[,d,m,y,i,k]=/(..)(..)(..)(...)(..)/.exec(I.padEnd(12)),v=g.charCodeAt()%2!=i%2|y<=39&i<500,s=k=>11-([...I].slice(0,-2).map((e,i)=>e*[..."376189452543276543"][i+!k|9]).reduce((a,b)=>a+b)+2*k)%11,[s(0),s(s(0))].map((s,i)=>v&=k[i]!=s);return!v} ``` **Tests**: ``` for (let args of [ ["M", "01010099931"], // true ["F", "01029042620"], // true ["M", "0101009841"], // false ["F", "01010051866"], // true ["F", "08021690849"], // true ["M", "01029040105"], // true ["M", "01029037473"] // false ]) { console.log(f(...args)); } ``` **Ungolfed**: ``` let f = (g, input) => { /* Sanitize input, destructure arguments via RegExp */ let [, d, m, y, i, k] = /(..)(..)(..)(...)(..)/.exec(input.padRight(12)); /* Validate gender and year */ let violation = g.charCodeAt() % 2 != i % 2 | y <= 39 & i < 500; let n = [..."376189452543276543"]; /* This function computes k1 if given no arguments, k2 if given one argument */ let s = k => 11 - ([...input].slice(0, -2).map((e, i) => e * n[i + !k | 9]).reduce((a, b) => a + b) + 2 * k) % 11; /* Validate the control numbers k */ [s(0), s(s(0))].map((s, i) => violation &= k[i] != s); return !violation; } ``` [Answer] ## JS, 343 Bytes ``` x=prompt().replace(/F/,1).replace(/M/,2).match(/\d{1}/g);v=Math.abs((x[0]-x[9])%2);v++;t=x[5]*10+x[6]*1;i=x[7]*1;if(t>39&&i>4){v--}if((11-(3*x[1]+7*x[2]+6*x[3]+1*x[4]+8*x[5]+9*x[6]+4*x[7]+5*x[8]+2*x[9])%11)%11===x[10]*1&&(11-(5*x[1]+4*x[2]+3*x[3]+2*x[4]+7*x[5]+6*x[6]+5*x[7]+4*x[8]+3*x[9]+2*x[10])%11)%11===x[11]*1){v++}alert(Math.floor(v/3)) ``` ]
[Question] [ Inspired by <https://puzzling.stackexchange.com/questions/24334/to-catch-a-thief> You are given an `n` by `n` (`n` itself is optional input) grid filled with `0`s and `1`s (or any other character of your choice). You aim is to make every cell the same (either `0` or `1`). You can make a series of moves as defined below (note dissimilarity with Puzzling SE link): * Select a cell. * Every cell in the same row and column (except the cell itself) gets changed into its opposite. `0` to `1` and `1` to `0`. Output the minimum number of moves required to complete the task. If unsolvable, output anything except a non-negative integer. Shortest code wins. **Sample data** ``` 1 0 0 0 0 0 0 0 0 ``` `-1` ``` 1 1 1 1 1 1 1 1 1 ``` `0` ``` 1 0 1 0 1 0 1 0 1 ``` `1` ``` 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 ``` `2` ``` 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 ``` `2` [Answer] # Matlab 171 bytes The input should be a 2d matrix, so you would call it like `c([1,1,1,1;0,0,0,0;0,0,0,0;1,1,1,1])` (semicolons start a new row). This function just bruteforces all possible moves, so we get a runtime of `O(2^(n^2))`. ### How it is done This is done by choosing all possible ways to fill another matrix of the same size with ones and zero, this is basically counting in binary wich where each entry of the matrix represents a certain power of 2. Then we perform the *moves* on those cells that are 1, this is done by the sum (mod 2) of two two dimensional convolution with an vector of ones of size 1xn and nx1. Finally we decide if those moves actually produced the desired result, by computing the standard deviation over all entries. The standard deviation is only zeros if all entries are the same. And whenever we actually found the desired result we compare it with the number of moves of previous solutions. The function will return `inf` if the given problem is not solvable. ### Math? It is actually worth noting that all those *moves* together generate an abelian group! If anyone actually manages to calssify those groups please let me know. Golfed version: ``` function M=c(a);n=numel(a);p=a;M=inf;o=ones(1,n);for k=0:2^n-1;p(:)=dec2bin(k,n)-'0';b=mod(conv2(p,o,'s')+conv2(p,o','s'),2);m=sum(p(:));if ~std(b(:)-a(:))&m<M;M=m;end;end ``` Full version (with the output of the actual moves.) ``` function M = c(a) n=numel(a); p=a; M=inf; %current minimum of number of moves o=ones(1,n); for k=0:2^n-1; p(:) = dec2bin(k,n)-'0'; %logical array with 1 where we perform moves b=mod(conv2(p,o,'same')+conv2(p,o','same'),2); %perform the actual moves m=sum(p(:)); %number of moves; if ~std(b(:)-a(:))&m<M %check if the result of the moves is valid, and better M=m; disp('found new minimum:') disp(M) %display number of moves of the new best solution (not in the golfed version) disp(p) %display the moves of the new best solution (not in the golfed version) end end ``` [Answer] # Perl 5, 498 bytes This accepts 'n' and the desired result, and outputs the count, or 'X' if none. For example: ``` perl ./crack.golf.pl 3 000111111 ``` gives `2`. It will only work when n^2 <= 64, so `n <= 8`. Although it's pretty slow even with n as low as 5. It builds a n^3 bit array, and sorts a 2^(n^2) array beforehand, because *why not*? I have wasted a couple of linefeeds here for *readability*: ``` $n=shift;$y=shift;$p=$n*$n;@m=(0..$n-1);@q=(0..$p-1);@v=(0..2**$p-1);@d=map{0}(@q);@b=map{$r=$_;map{$c=$_;$d[$r*$n+$_]^=1 for(@m);$d[$_*$n+$c]^=1 for(@m);$j=0;$k=1; map{$j|=$k*$d[$_];$k<<=1;}@q;@d=map{0}(@q);$j;}@m}@m;for$k(sort{$a->[0]<=>$b->[0]}map{$z=0;map{$z+=$_}split(//,sprintf"%b",$_);[$z,$_]}@v){$l=sprintf"%0${p}b",$k->[1]; @m=map{$_}split(//,$l);$s=0;for(@q){$s^=$b[$_]if$m[$_];}$z=0;map{$z+=$_}split(//,sprintf"%b",$_);if($y eq sprintf"%0${p}b",$s){print"$k->[0]\n";exit 0;}}print"X\n"; ``` ]
[Question] [ # Introduction You are the manager of the electronics department in a major retail store and the biggest sales day of the year is this [Friday](https://en.wikipedia.org/wiki/Black_Friday_%28shopping%29). To help manage the crowds, your store is implementing a ticket system for the biggest deals, where customers must present a ticket before purchasing an item. Your job is to write a program to validate the tickets. Since the only available computer in the store (due to budget cuts) is a dinosaur with a broken keyboard, (and all you have is USB keyboards, which aren't compatible) you'll have to input your program with a mouse. Therefore, your program should be as short as possible. # Products You store is running sales on the five different products listed below. Each product has an all lowercase name and different rules on how many can be purchased and at what time of day. * `television`: There are `5` flat-screen televisions in stock that may be purchased from `00:00:00` (midnight) to `00:59:59`. * `smartphone`: There are `10` smartphones in stock, but any customer in line from `00:00:00` (midnight) to `00:59:59` receives a voucher for one once they run out. * `tablet`: There are `10` tablets that may be purchased at anytime. * `laptop`: There are an unlimited number of laptops that may be purchased from `00:00:00` (midnight) to `07:59:59`. * `lightbulb`: There are an unlimited number of light bulbs that may be purchased at anytime. # Input A multi-line string with each line in the following format. Lines are sorted by the time-stamp. ``` <time stamp> <product name> <ticket number> ``` * The ticket number is 8 digits long. The last digit is a check-digit equal to the sum of the first seven digits modulo 10. To be valid, a ticket number must have the correct check-digit and must be strictly greater than all previous ticket numbers. * The product name is one of the string listed above. * The time stamp is the time of day in the format `HH:MM:SS` where `HH` is the two-digit hour from 00-23, and `MM` and `SS` are the two-digit minute and second respectively. # Output The output is one of the following strings, with one line per ticket. The conditions must be applied **in order**. 1. `Expired offer` (Applies to televisions, smartphones, and laptops.) The time-stamp of the ticket is after the cutoff to buy the product. 2. `Invalid ticket` Either the ticket number is less than or equal to the number of the previous ticket, or the check-digit is invalid. 3. `Give voucher` (Applies to smartphones.) The product is out of stock, but all the customers in line before the offer expires get a rain check. 4. `Out of stock` (Applies to televisions and tablets.) All of the product has been sold. Sorry, quantity was limited. 5. `Accepted` All conditions are met, so give them the product. Note that only accepted tickets reduce the number of items in stock. # Example ``` Input Output ---------------------------- -------------- 00:00:00 television 00010001 Accepted 00:00:25 smartphone 00011697 Accepted 00:01:25 laptop 00030238 Accepted 00:02:11 smartphone 00037291 Accepted 00:02:37 lightbulb 00073469 Invalid ticket 00:03:54 smartphone 00096319 Accepted 00:05:26 tablet 00152514 Accepted 00:06:21 tablet 00169893 Accepted 00:07:10 television 00190268 Accepted 00:07:47 smartphone 00194486 Accepted 00:07:55 tablet 00220071 Accepted 00:08:20 lightbulb 00321332 Accepted 00:10:01 smartphone 00409867 Accepted 00:11:10 tablet 00394210 Invalid ticket 00:11:46 television 00581060 Accepted 00:12:44 lightbulb 00606327 Accepted 00:13:16 tablet 00709253 Accepted 00:13:53 television 00801874 Accepted 00:14:47 laptop 00832058 Accepted 00:15:34 smartphone 00963682 Accepted 00:16:24 smartphone 01050275 Accepted 00:17:45 tablet 01117167 Accepted 00:18:05 laptop 01107548 Invalid ticket 00:19:00 lightbulb 01107605 Invalid ticket 00:19:47 lightbulb 01492983 Accepted 00:19:50 smartphone 01561609 Accepted 00:21:09 television 01567098 Accepted 00:21:42 laptop 01597046 Accepted 00:22:17 smartphone 01666313 Accepted 00:24:12 tablet 01924859 Accepted 00:24:12 smartphone 02151571 Accepted 00:25:38 smartphone 02428286 Give voucher 00:31:58 television 02435284 Out of stock 00:35:25 television 02435295 Out of stock 00:52:43 laptop 02657911 Invalid ticket 00:53:55 smartphone 02695990 Give voucher 01:08:19 tablet 02767103 Accepted 01:34:03 television 02834850 Expired offer 01:56:46 laptop 02896263 Accepted 02:02:41 smartphone 03028788 Expired offer 02:30:59 television 03142550 Expired offer 02:51:23 tablet 03428805 Accepted 03:14:57 smartphone 03602315 Expired offer 03:27:12 television 03739585 Expired offer 03:56:52 smartphone 03997615 Expired offer 04:07:52 tablet 04149301 Accepted 04:12:05 lightbulb 04300460 Invalid ticket 04:24:21 laptop 04389172 Accepted 04:40:23 lightbulb 04814175 Accepted 04:40:55 tablet 04817853 Accepted 04:42:18 smartphone 04927332 Expired offer 05:06:43 tablet 05079393 Out of stock 05:16:48 tablet 05513150 Out of stock 05:33:02 television 05760312 Expired offer 05:43:32 tablet 06037905 Out of stock 06:12:48 smartphone 06440172 Expired offer 06:35:25 laptop 06507277 Accepted 06:42:29 lightbulb 06586255 Invalid ticket 06:55:31 lightbulb 06905583 Accepted 06:55:33 lightbulb 06905583 Invalid ticket 07:40:05 smartphone 07428006 Expired offer 07:49:12 television 07588086 Expired offer 08:14:56 laptop 08111865 Expired offer ``` I have tried to make the example cover every possible output scenario, but please leave a comment if anything is unclear. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), you may write a program or function, and standard loop-holes are disallowed. [Answer] # Javascript(ES6), ~~396~~ ~~433~~ 419 bytes ``` h=0;f=1/0;i={television:{c:5,s:0,e:1},smartphone:{c:10,s:0,e:1,v:1},tablet:{c:10,s:0,e:24},laptop:{c:f,s:0,e:8},lightbulb:{c:f,s:0,e:24}};while(1){t=prompt().split(' ');a=t[0];r=a[0]+a[1]-0;o=i[t[1]];m=0;z='Accepted';u=t[2]-0;u<=h||(u-u%10+'').split('').reduce((p,c)=>-(-p-c))%10!=u%10?m='Invalid ticket':0;r<o.s||r>=o.e?m='Expired offer':0;if(!m)o.c?o.c--:(o.v?z='Give voucher':m='Out of stock');!m?h=u:0;alert(m?m:z)} ``` **Edit:** Reduced size by using es6 big arrow function ### More readable: ``` h=0 f=1/0 i={television:{c:5,s:0,e:1},smartphone:{c:10,s:0,e:1,v:1},tablet:{c:10,s:0,e:24},laptop:{c:f,s:0,e:8},lightbulb:{c:f,s:0,e:24}} while(1){t=prompt().split(' ') a=t[0] r=a[0]+a[1]-0 o=i[t[1]] m=0 z='Accepted' u=t[2] if(u<=h||(u-u%10+'').split('').reduce(function(p,c){return-(-p-c)})%10!=u%10)m='Invalid ticket' if(r<o.s||r>=o.e)m='Expired offer' if(!m){if(o.c)o.c-- else o.v?z='Give voucher':m='Out of stock'}if(!m)h=u alert(m?m:z)} ``` Interestingly the longer code is faster: <http://jsperf.com/compare-read> ### GUI with same logic: ``` var app = angular.module('app', []); app.controller('MainCtrl', function MainCtrl ($scope) { $scope.items = { television: {c: 5, s:0, e: 1}, smartphone: {c: 10, s:0, e: 1}, tablet: {c:10, s:0, e: 24}, laptop: {c:Infinity, s: 0, e: 8}, lightbulb: {c: Infinity, s: 0, e: 24}, }; var h = -1;//highest $scope.hours_offset = 0; $scope.ticket = {}; for (var i = 0; i < 8; i++) $scope.ticket[i] = 0; $scope.selected_item = -1; $scope.nums = new Array(10); $scope.history = []; $scope.buy = function() { } $scope.selectItem = function($i) { $scope.selected_item = $i; } $scope.purchase = function() { if ($scope.selected_item === -1) return; var ticnum = ''; var msg = 'Accepted'; for(var key in $scope.ticket) ticnum+=$scope.ticket[key]; var d = new Date(); //Variable declarations to setup for code like the code I designed for console r = d.getHours()-$scope.hours_offset;//hour o = $scope.items[$scope.selected_item];//item m = 0//msg z = 'Accepted'//default_msg u=ticnum //This is copied from my console code if(ticnum<=h||(ticnum-ticnum%10+'').split('').reduce(function(p,c){return-(-p-c)})%10!=ticnum%10)m='Invalid ticket' if(r<o.s||r>=o.e)m='Expired offer' if(!m){if(o.c)o.c-- else o.v?z='Give voucher':m='Out of stock'}if(!m)h=ticnum msg = m?m:z; $scope.history.unshift({ time: time(d), item: $scope.selected_item, ticket_num: ticnum, message: msg }); } }); function time(date) { return padToTwo(date.getHours()) + ':' + padToTwo(date.getMinutes()) + ':' + padToTwo(date.getSeconds()); } function padToTwo(number) { return number = ("00"+number).slice(-2); } ``` ``` #parent { width: 100vw; height: 100vh; padding-bottom: 25vh; } #parent > div { padding-top: 25vh; -webkit-display: flex; display: flex; -webkit-flex-direction: row; flex-direction: row; -webkit-align-items: flex-start; align-items: flex-start; -webkit-justify-content: center; justify-content: center; } #items { width: 15vw; min-width: 110px; margin-right: 4vw; background-color: #222223; color: #eeeeef; border-radius: 4px; border: 2px solid black; } #items > span { box-sizing: border-box; display: block; padding: 5px; -webkit-transition: .2s background-color ease-in-out; transition: .2s background-color ease-in-out; text-align: center; width: 100%; border-radius: 4px; } #items > span:hover, #ticket p:hover { background-color: gray; } #items > span.selected, #ticket p.selected { background-color: #999999; } #ticket { -webkit-display: flex; display: flex; -webkit-flex-direction: row; flex-direction: row; margin-right: 4vw; color: #eeeeef; } #ticket p { margin: 1px; padding: 3px; width: 20px; text-align: center; background-color: #22222f; border: 2px solid black; border-radius: 3px; } #purchase { padding: 15px; padding-top: 6px; padding-bottom: 6px; background-color: #22222f; border: 2px solid black; border-radius: 3px; color: #eeeeef; } #purchase:active { background-color: gray; } #error { margin-top: 15px; color: red; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> <div id="parent" ng-app="app" ng-controller="MainCtrl"> For testing hours-offset (If it's 6:00 setting this to 18 would simulate it being midnight): <input ng-model="hours_offset" type="number"></input> <div> <div id="items"> <span ng-attr-class="{{selected_item===name ? 'selected' : ''}}" ng-repeat="(name, obj) in ::items track by $index" ng-click="selectItem(name)">{{::name}}<br></span> </div> <div id="ticket"> <span ng-repeat="(ticket_index, val) in ::ticket"> <p ng-attr-class="{{ticket[ticket_index]===$index ? 'selected' : ''}}" ng-repeat="nothing in ::nums track by $index" ng-click="ticket[ticket_index] = $index">{{::$index}}</p> </span> </div> <span id="purchase" ng-click="purchase()">Purchase</span> </div> <div id="error">{{error_msg}}</div> <table id="output"> <tr ng-repeat="item in history track by $index"> <td ng-repeat="(key, value) in item track by $index">{{value}}</td> </tr> </span> </div> ``` ]
[Question] [ The goal of this challenge is to create a program that takes in a matrix and outputs its reduced row-echelon form. > > A matrix is in reduced row-echelon form if it meets all of the > following conditions: > > > 1. If there is a row where every entry is zero, > then this row lies below any other row that contains a nonzero entry. > 2. The leftmost nonzero entry of a row is equal to `1`. > 3. The leftmost nonzero entry of a row is the only nonzero entry in its column. > 4. Consider any two different leftmost nonzero entries, one located in > row i, column j and the other located in row s, column t. If `s>i`, then > `t>j`. > > > [Source](http://linear.ups.edu/html/section-RREF.html) > > > The general process to transform the matrix is: 1. Deal with each row i from 1 to n in turn, and work across the columns j from 1 to m skipping any column of all zero entries. 2. Find the next column j with a nonzero entry. 3. Interchange rows, if necessary, so that the pivot element A(i,j) is nonzero. 4. Make the pivot equal to 1 by dividing each element in the pivot row by the value of the pivot. 5. Make all elements above and below the pivot equal to 0 by subtracting a suitable multiple of the pivot row from each other row. 6. Repeat for all rows. If you want to read more on this type of matrix, view the [Wikipedia](https://en.wikipedia.org/wiki/Row_echelon_form) article on it and a [tool](http://www.math.odu.edu/~bogacki/cgi-bin/lat.cgi?c=rref) and [article(steps above)](http://www.di-mgt.com.au/matrixtransform.html) that shows the steps to transform the matrix. **As for the actual challenge, here it goes:** The input can be given in any way you wish through STDIN or equivalent, just please explain it in your answer. The output will be the reduced row-echelon form of the input in the same form as the input through STDOUT or equivalent. Standard loopholes are not allowed and external libraries or functions that do this task are also not allowed (`TI-BASIC`'s `rref(` command, for example). You may write a full program or function. This is code golf, lowest BYTES wins. Good luck! Example Input: `[[2,1,1,14][-1,-3,2,-2][4,-6,3,-5]]` Example Output: `[[1,0,0,1][0,1,0,5][0,0,1,7]]` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~29~~ 23 bytes ``` (ƛh/;ḣ„D"„-‟wJƛǓ:h±*]ƛǓ ``` it's so complex that I forget how it works, but it does work I guess...? [29 bytes](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiTCjGm2gvO+G4o+KAnjo6XCLigJ4t4oCfd0rGm8eTO8abaMKxKjspxpvHkzsiLCIiLCJbWzIsMSwxLDE0XSxbLTEsLTMsMiwtMl0sWzQsLTYsMywtNV1dIl0=) by me [24 bytes](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiTCjGm2gvO+G4o+KAnkRcIuKAni3igJ93Ssabx5M6aMKxKl3Gm8eTIiwiIiwiW1syLDEsMSwxNF0sWy0xLC0zLDIsLTJdLFs0LC02LDMsLTVdXSJd) by @emanresu A [23 bytes](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiKMabaC874bij4oCeRFwi4oCeLeKAn3dKxpvHkzpowrEqXcabx5MiLCIiLCJbWzIsMSwxLDE0XSxbLTEsLTMsMiwtMl0sWzQsLTYsMywtNV1dIl0=)(current) by great god @lyxal [Try it Online!](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiKMabaC874bij4oCeRFwi4oCeLeKAn3dKxpvHkzpowrEqXcabx5MiLCIiLCJbWzIsMSwxLDE0XSxbLTEsLTMsMiwtMl0sWzQsLTYsMywtNV1dIl0=) [Answer] # R, 232 bytes ``` function(M){p=1;R=nrow(M);C=ncol(M);for(r in 1:R){if(C<=p)break;i=r;while(M[i,p]==0){i=i+1;if(R==i){i=r;p=p+1;if(C==p)return(M)}};t=M[i,];M[i,]=M[r,];M[r,]=t;M[r,]=M[r,]/M[r,p];for(i in 1:R)if(i!=r)M[i,]=M[i,]-M[r,]*M[i,p];p=p+1};M} ``` This is just an implementation of the usual Gaussian elimination algorithm. Ungolfed: ``` rref <- function(M) { p <- 1 R <- nrow(M) C <- ncol(M) for (r in 1:R) { if (C <= p) break i <- r while (M[i, p] == 0) { i <- i + 1 if (R == i) { i <- r p <- p + 1 if (C == p) return(M) } } t <- M[i, ] M[i, ] <- M[r, ] M[r, ] <- t M[r, ] <- M[r, ] / M[r, p] for (i in 1:R) if (i != r) M[i, ] <- M[i, ] - M[r, ] * M[i, p] p <- p + 1 } M } ``` ]
[Question] [ Write a term on the pure untyped lambda calculus that, when applied to a [church-encoded](https://en.wikipedia.org/wiki/Church_encoding) list of numbers, returns it with its numbers sorted in ascending or descending order. Church lists and numbers must be encoded as folds for their usual ADTs: ``` -- Usual ADTs for Lists and Nats (in Haskell, for example) data List a = Cons a (List a) | Nil data Nat a = Succ (Nat a) | Zero -- Their respective folds are the λ-calculus representation used on this challenge church_list = (λ c n . (c ... (c ... (c ... n)))) church_num = (λ succ zero . (succ (succ (succ ... zero)))) ``` Example input: ``` (λ cons nil . (cons (λ f x . (f x)) -- 1 (cons (λ f x . (f (f (f (f (f (f (f x)))))))) -- 7 (cons (λ f x . (f (f x))) -- 2 (cons (λ f x . (f (f (f x)))) -- 3 nil))))) ``` Example output: ``` (λ cons nil . (cons (λ f x . (f x)) -- 1 (cons (λ f x . (f (f x))) -- 2 (cons (λ f x . (f (f (f x)))) -- 3 (cons (λ f x . (f (f (f (f (f (f (f x)))))))) -- 7 nil))))) ``` The score of a submission will be calculated as follows: ``` score(x) = 1 score(λx.t) = score(t) + 1 score(t s) = score(t) + score(s) + 1 ``` Lowest score wins. [Answer] I've managed to beat my own mark: ``` sort = λabcd.a(λef.f(λghi.g(λj.h(λkl.kj(ikl)))(hi))e(λgh.h)) (λe.d)(λe.b(λf.e(f(λghi.hg)(λgh.cfh)))) ``` There is a caveat, though - this term must receive an additional argument with the maximum size of naturals that are considered. For example, `sort 4 [1,7,3,6,5]` will return `[1,3]`, ignoring anything above or equal 4. Of course, you could just give infinity (i.e., the Y-combinator): ``` sort = λbcd.(λfx.f(x x))(λfx.f(x x))(λef.f(λghi.g(λj.h(λkl.kj(ikl))) (hi))e(λgh.h))(λe.d)(λe.b(λf.e(f(λghi.hg)(λgh.cfh)))) ``` And it would sort any list of natural numbers, but this term obviously doesn't have a normal form anymore. [Answer] **121 characters / score 91** ``` sort = λabc.a(λdefg.f(d(λhij.j(λkl.k(λmn.mhi)l)(h(λkl.l)i)) (λhi.i(λjk.bd(jhk))(bd(h(λjk.j(λlm.m)k)c))))e)(λde.e) (λde.d(λfg.g)e)c ``` It is in normal form and could be made shorter by lifting common subexpressions. [Answer] Here's an implementation of an insertion sort: ``` let nil = \f x.x in let cons = \h t.\f x.f h (t f x) in let 0 = \f x.x in let succ = \n.\f x.f (n f x) in let None = \a b.b in let Some = \x.\a b.a x in let pred = \n.n (\opt.opt (\m.Some(succ m)) (Some 0)) None in let optpred = \opt.opt pred None in let - = \m n.n optpred (Some m) in let < = \m n.\trueval falseval.- m n (\diff.falseval) trueval in let pair = \x y.\f.f x y in let snd = \p.p (\x y.y) in let insert = \n l.snd (l (\h recpair.recpair (\rawtail insertedtail. let rawlist = cons h rawtail in pair rawlist (< h n (cons h insertedtail) (cons n rawlist)))) (pair nil (cons n nil))) in \l.l insert nil ``` Here, `pred n` returns an element of `option nat`: `pred 0` is `None` whereas `pred (n+1)` is `Some n`. Then, `- m n` returns an element of `option nat` which is `Some (m-n)` if `m>=n` or `None` if `m<n`; and `< m n` returns a boolean. Finally, `insert` uses an internal function returning a pair where `f l = (l, insert n l)` (a fairly typical method to get the tail of the list to get passed to the recursion along with the recursive value). Now, some notes for future golfing work: actually `nil`, `0`, `None` happen to be the same function formally (and it also appears in `snd`). Then, I would certainly consider doing beta reductions on the `let` statements (which is of course the usual syntactic sugar where `let a = x in y` means `(\a.y)x` and thus has score `score(x) + score(y) + 2`) to see in which cases doing so would reduce the score - which it most definitely would for the bindings that are only used once. Then would come trickier things: for example, I just noticed that formally `pred = pair (pair (\m.Some(succ m)) (Some 0)) None`, `optpred = pair pred None`, `- = \m.pair optpred (Some m)`, the sort function definition amounts to `pair insert nil`, etc. which could reduce the score slightly. ]
[Question] [ You are given a nonary (base 9) non-negative integer consisting of the digits 0 through 8 as usual. However the number of digits in this number (with no leading zeros) is a prefect square. Because of this, the number can be arranged in a square grid (with the reading order still preserved). Example with 1480 (1125 base 10): ``` 14 80 ``` Now let every digit in such a nonary grid indicate a motion to another grid space (with [periodic boundary conditions](http://en.wikipedia.org/wiki/Periodic_boundary_conditions)): ``` 432 501 678 ``` This is saying that ``` 0 = stay still 1 = move right 2 = move right and up 3 = move up ... 8 = move right and down ``` So, if in the 1480 grid you start at the 4, you then move up (remember pbc) and left to the 8, which means you move right and down back to the 4, starting a cycle with period 2. In general this process is continued until you get to a 0 or a cycle is noticed. (A 0 is considered a cycle with period 1.) In the case of 1480, the period eventually reached at each of the 4 starting digits is `2 2 2 1` respectively. For a larger grid these numbers might be larger than 8, but we can still use them as "digits" in a new nonary number (simply the coefficients of 9^n as if they were digits): ``` 2*9^3 + 2*9^2 + 2*9 + 1 = 1639 (base 10) = 2221 (base 9) ``` We will call this the *strength* of the original nonary number. So the strength of 1480 is 1639 (base 10) or, equivalently, 2221 (base 9). ## Challenge Write the shortest program that tells whether the strength of a nonary number is greater than, less than, or equal to the nonary number itself. (You do not necessarily need to compute the strength.) The input will be a non-negative nonary number that contains a square number of digits (and no leading zeros besides the special case of 0 itself). It should come from the command line or stdin. The output should go to stdout as: ``` G if the strength is larger than the original number (example: 1480 -> strength = 2221) E if the strength is equal to the original number (example: 1 -> strength = 1) L if the strength is less than the original number (example: 5 -> strength = 1) ``` **Fun Bonus Challenge:** Whats the highest input you can find that is equal to its strength? (Is there a limit?) [Answer] # Python 2, 213 209 202 Edit: Removed shortcircuiting, which is sometimes incorrect. See below. (Largely) The same algorithm as @KSab, but very heavily golfed. ``` n=`input()` s=int(len(n)**.5) c=0 for i in range(s*s): a=[] while(i in a)<1:a+=[i];x='432501678'.find(n[i]);i=(i+x%3-1)%s+((i/s+x/3-1)%s)*s c=c*9+len(a)-a.index(i) d=long(n,9) print'EGL'[(c>d)-(c<d)] ``` Golfs: * 213: Short-circuiting, flawed solution. * 209: First working solution. * 202: Combined the two string lookups into one. Edit: I just realised that this program, and thus KSab's too, were flawed in that they ignore multidigit cycle lengths. Example failure: ``` 3117 2755 3117 7455 ``` While the 3 has a cycle length of 2, and thus the above algorithm short circuits to 'L', this should in fact return 'G', because the cycle length of 14 on the second digit more than overcomes that. I have therefore changed the program. It also got shorter, funnily enough. To test your program, use `3117275531177455`. It should return `G`. [Answer] # Python 296 Not actually too inefficient, it only checks as many digits as it needs to. ``` n=raw_input();s=int(len(n)**.5);t=0 for i in range(s**2): l=[] while i not in l:l.append(i);c=n[i];i=(i%s+(-1 if c in'456'else 1 if c in'218'else 0))%s+((i/s+(-1 if c in'432'else 1 if c in'678'else 0))%s)*s t=t*9+len(l)-l.index(i) print'EGL'[cmp(t,long(n,9))] ``` As for numbers equal to their strength, I think the only solutions are, for every N x N square up to N=8 a square containing N in every space. My thinking is that since every number in a loop must be the same number (the length of the loop) each loop would have to be all in one direction. This of course means that the loop's size must be N (and each element must be N). I'm pretty sure that this logic can be applied to squares and loops of any size, meaning there are no squares equal to their strength other than the first 8. [Answer] # CJam - 81 ``` q:X,:L,{[L2*{_[_Lmqi:Smd@X=432501678s#3md]2/z{~+(S+S%}%Sb}*]L>_&,\X=~-}%9bg"EGL"= ``` Try it at <http://cjam.aditsu.net/> It can probably be golfed some more. [Answer] # Lua - Not golfed yet Just putting in here for safekeeping. I'll golf it (and implement the "For a larger grid these numbers might be larger than 8, but we can still use them as "digits"") later. Works though. ``` d={{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1}} d[0]={0,0}ssd='' n=arg[1] q=math.sqrt(#n)t={} for y=1,q do table.insert(t,y,{}) for x =1,q do v=(y-1)*q+x table.insert(t[y],x,n:sub(v,v)+0) io.write(t[y][x]) end end for y=1,q do for x=1,q do cx=x cy=y pxy=''sd=0 while pxy:match(cx..':%d*:'..cy..' ')==nil do pxy=pxy..cx..':'..sd..':'..cy.." " ccx=cx+d[t[cx][cy]][2] ccy=cy+d[t[cx][cy]][1] cx=ccx cy=ccy if cx<1 then cx=q elseif cx>q then cx=1 end if cy<1 then cy=q elseif cy>q then cy=1 end sd=sd+1 end dds=(pxy:sub(pxy:find(cx..':%d+:'..cy)):match(':%d*')) ssd=ssd..(sd-dds:sub(2)) end end print(ssd) nn=tonumber(n,9) tn=tonumber(ssd,9) if tn>nn then print("G") elseif tn==nn then print("E") else print("L") end ``` ]
[Question] [ # preface In a very heated situation you have to go even further with golfing. (e.g. in a challenge where your answer is 100 characters long and it is just embarrassing that you couldn't make it 99) In that case, from now on you use the winner's algorithm of this challenge :) # goal You have to write a program that takes an uint32 and returns the most compressed form. ``` $ mathpack 147456 9<<14 ``` * There will be multiple solutions for a number. Pick the shortest one * If the compressed form is longer or equal to the original number, return the original number # rules * write in any language - output in any language * i'm aware of that in C `'abc'` is `6382179` and you can achieve pretty good results with this conversion. but languages are separated in this challenge so don't lose heart * it is prohibited to use external variables. only operators and literals and math related functions! # scoring here are the test cases: [pastebin.com/0bYPzUhX](http://pastebin.com/0bYPzUhX) your score (percent) will be the ratio of `byte_size_of_your_output / byte_size_of_the_list` **without line breaks**. (you have to do this by yourself as i'll just verify the best codes just in case) winners will be chosen by score and **language of output**! **examples:** ``` $ mathpack 147456 | mathpack 97787584 | mathpack 387420489 9<<14 | 9e7^9e6 | pow(9,9) ``` [Answer] # Code: Mathematica, Output: Julia, ~98.9457% (20177/20392 bytes) ``` optimise[n_] := Module[{bits, trimmedBits, shift, unshifted, nString, versions, inverted, factorised, digits, trimmedDigits, exponent, base, xored, ored, anded}, nString = ToString@n; versions = {nString}; (* Try bitshifting *) bits = IntegerDigits[n, 2]; trimmedBits = bits /. {x___, 1, 0 ..} :> {x, 1}; shift = ToString[Length[bits] - Length[trimmedBits]]; unshifted = ToString@FromDigits[trimmedBits, 2]; AppendTo[versions, unshifted <> "<<" <> shift]; (* Try inverting *) inverted = ToString@FromDigits[1 - PadLeft[bits, 32], 2]; AppendTo[versions, "~" <> inverted]; (* Try invert/shift/invert *) trimmedBits = bits /. {x___, 0, 1 ..} :> {x, 1}; shift = ToString[Length[bits] - Length[trimmedBits]]; unshifted = ToString@FromDigits[trimmedBits, 2]; AppendTo[versions, "~(~" <> unshifted <> "<<" <> shift <> ")"]; (* Try factoring *) factorised = Riffle[ FactorInteger[n] /. {a_, 1} :> ToString@a /. {a_Integer, b_Integer} :> ToString[a] <> "^" <> ToString[b] , "+"] <> ""; AppendTo[versions, factorised]; (* Try scientific notation *) digits = IntegerDigits[n, 10]; trimmedDigits = digits /. {x___, d_ /; d > 0, 0 ..} :> {x, d}; exponent = ToString[Length[digits] - Length[trimmedDigits]]; base = ToString@FromDigits[trimmedDigits, 10]; AppendTo[versions, base <> "e" <> exponent]; (* Don't try hexadecimal notation. It's never shorter for 32-bit uints. *) (* Don't try base-36 or base-62, because parsing those requires 12 characters for parseint("...") *) SortBy[versions, StringLength][[1]] ]; mathpack[n_] := Module[{versions, increments}, increments = Range@9; versions = Join[ optimise[#2] <> "+" <> ToString@# & @@@ ({#, n - #} &) /@ Reverse@increments, {optimise@n}, optimise[#2] <> "-" <> ToString@# & @@@ ({#, n + #} &) /@ increments, optimise[#2] <> "*" <> ToString@# & @@@ Cases[({#, n / #} &) /@ increments, {_, _Integer}], optimise[#2] <> "/" <> ToString@# & @@@ ({#, n * #} &) /@ increments ]; SortBy[versions, StringLength][[1]] ]; ``` The function takes a *number* and returns the shortest *string* it finds. Currently it applies four simple optimisations (I might add more tomorrow). You can apply it to the entire file (to measure its score) as follows: ``` input = StringSplit[Import["path/to/benchmark.txt"]]; numbers = ToExpression /@ input; output = mathpack /@ numbers; N[StringLength[output <> ""]/StringLength[input <> ""]] ``` Note that some of these optimisations assume that you're on a 64-bit Julia, such that integer literals give you an `int64` by default. Otherwise, you'll be overflowing anyway for integers greater than 231. Using that assumption we can apply a few optimisations whose intermediate steps are actually even larger than 232. **EDIT:** I added the optimisation suggested in the OP's examples to bitwise *xor* two large numbers in scientific notation (actually, for all of *xor*, *or* and *and*). Note that extending the `xormap`, `ormap` and `andmap` to include operands beyond 232 might help finding additional optimisations, but it doesn't work for the given test cases and only increases run time by something like a factor of 10. **EDIT:** I shaved off another 16 bytes, by checking all `n-9, n-8, ..., n+8, n+9` for whether any of *those* can be shortened, in which case I represented the number based on that, adding or subtracting the difference. There are a few cases, where one of those 18 numbers can be represented with 3 or more characters less than `n` itself, in which case I can make some extra savings. It takes about 30 seconds now to run it on all test cases, but of course, if someone actually "used" this function, he'd only run it on a single number, so it's still well under a second. **EDIT:** Another incredible 4 bytes by doing the same for multiplication and division. 50 seconds now (the divided ones don't take as long, because I'm only checking these if the number is actually divisible by the factor of interest). **EDIT:** Another optimisation that doesn't actually help with the given test set. This one could save a byte for things like 230 or 231. If we had uint64s instead, there'd be a lot of numbers where this could be a huge saving (basically, whenever the bit representation ends in a lot of 1s). **EDIT:** Removed the *xor*, *or*, *and* optimisations altogether. I just noticed they don't even work in Julia, because (quite obviously) scientific notation gives you a float where bit-wise operators are not even defined. Interestingly, one or more of the newer optimisations seem to catch all of the cases that were shortened by these optimisations, because the score didn't change at all. [Answer] ## Code: Mathematica, Output: C, ~62.1518% (12674/20392) I thought I'd also give C a try because of those funny character literals. Currently this is the only thing this answer is trying, and it's working quite well. ``` mathpack[n_] := Module[{versions, charLiteral}, charLiteral = "'" <> StringReplace[Map[ Switch[#, (*d_ /; d < 32, "\\" <> IntegerString[#, 8],*) 10, "\\n", 13, "\\r" 39, "\\'", 92 , "\\\\", _, FromCharacterCode@#] &, FromDigits[#, 2] & /@ (Partition[PadLeft[IntegerDigits[n, 2], 32], 8] //. {{0 ..} .., x__} :> {x}) ] <> "", {(*"\\10" -> "\\b", "\\11" -> "\\t", "\\13" -> "\\v", "\\14" -> "\\f",*) RegularExpression["(?!<=\?)\?\?(?=[=/()!<>-]|$)"] -> "?\\?" } ] <> "'"; versions = {ToString@n, charLiteral}; SortBy[versions, StringLength][[1]] ]; ``` I hope I didn't miss anything, but this answer makes sure to escape backslashes, single quotation marks as well as trigraphs. There is some commented out code that uses octal or other escape sequences for non-printable characters, but I don't think that's actually necessary, because C should be able to deal with any bytes in character literals, afaik (please correct me if I'm wrong). As with the other submission, test this with ``` input = StringSplit[Import["path/to/benchmark.txt"]]; numbers = ToExpression /@ input; output = mathpack /@ numbers; N[StringLength[output <> ""]/StringLength[input <> ""]] ``` [Answer] # J to C (untested, but works in most cases, kind of a baseline answer.) ``` f=:(,~ (($&0) @: (8&-) @: (8&|) @: #)) @: #: g=:($~ ((,&8) @: (%&8) @: #))@:f toCString=:({&a.)@:#.@:g toCString 6382179 abc ``` Outputs an string literal that, if entered in C, represents the number (as mentioned in the OP). This is not a serious submission, but rather something to strengthen my J skills, that I thought I'd share. Alternative one-liner: ``` toCString=:({&a.) @: #. @: ($~ ((,&8) @: (%&8) @: #))@: (,~ (($&0) @: (8&-) @: (8&|) @: #)) @: #: ``` What J tries to make of this when you input it: ``` {&a.@:#.@:($~ ,&8@:(%&8)@:#)@:(,~ $&0@:(8&-)@:(8&|)@:#)@:#: ``` Thanks a bunch, J. Also, for those in 'the know' about J, visio rocks for creating more complex functions: ![enter image description here](https://i.stack.imgur.com/MvInW.png) ]
[Question] [ Make the shortest proxy server. ### Input/Output Specifications Client: * Input: a port number (32-bit integer) **(,) or (space)** a url (see test cases) * Output: html source of the url Server: * Input: port to listen to (32-bit integer) * Output: **REC** when input is received from the client, **OK** when finished sending the html source to the client. ### Rules * You may make either a **complete program** or **functions in an interpreted language**. * Input is taken through **stdin** or given as a **arguments**. * Your code has to work for the given **test cases only** (more is optional, less is invalid). * The client output has to be the same as with what you get when you "view source" from a browser. * The server **may exit** after each handled request (i.e does not have to be persistent/daemon) * (**edit**) Any other input/output than what specified, is forbidden. ### Test cases (client inputs) 1. N1 <https://stackoverflow.com/> 2. N2 <http://en.wikipedia.org/wiki/Proxy_server> 3. N3 <http://stackexchange.com/search?q=code+golf> where Ni are random integers between 1 and 2048. [Answer] ## ZSH - 57 + 42 characters Server: ``` s=$(nc -l $1) echo REC curl -s $s|nc 127.0.0.1 $1 echo OK ``` Client: ``` echo $2|nc 127.0.0.1 $1 echo "$(nc -l $1)" ``` Usage: ``` sudo zsh server.zsh 123 sudo zsh client.zsh 123 http://stackoverflow.com/ sudo zsh client.zsh 123 http://en.wikipedia.org/wiki/Proxy_server sudo zsh client.zsh 123 "http://stackexchange.com/search?q=code+golf" ``` ]
[Question] [ Suppose we want to encode a large integer \$x\$ as a list of words in such a way that the decoder can recover \$x\$ regardless of the order in which the words are received. Using lists of length \$k\$ and a dictionary of \$n\$ words, there are \$\binom{n+k-1}k\$ different multisets possible ([why?](https://math.stackexchange.com/questions/3751384/number-of-multisets)), so we should be able to represent values of \$x\$ from \$1\$ through \$\binom{n+k-1}k\$. This is a code golf challenge to implement such an encoder and decoder (as separate programs or functions); your golf score is the total code length. Any sensible/conventional input & output formats are allowed. Encode: Given positive integers \$n,k,x\$ with \$x\le\binom{n+k-1}k\$, encode \$x\$ as a list of \$k\$ integers between \$1\$ and \$n\$ (inclusive). Decode: Given \$n\$ and a list of \$k\$ integers between \$1\$ and \$n\$, output the decoded message \$x\$. Correctness requirement: If `encode(n,k,x)` outputs \$L\$ and \$\operatorname{sort}(L)=\operatorname{sort}(M)\$, then `decode(n,M)` outputs \$x\$. **Runtime requirement**: Both operations must run in [polynomial time](https://en.wikipedia.org/wiki/Time_complexity#Polynomial_time) with respect to the length of \$x\$ in bits. This is meant to rule out impractical brute-force solutions that just enumerate all the multisets. [Answer] # [Python](https://www.python.org), 258 bytes ``` from numpy import* P=cumprod;p=prod def e(x,k):r=r_[:k]+1;f=p(r);X=x*f-f;i=int(X**(1/k));Q=P([1,*i+r]);Q[-2::-1]*=P(i+1-r);j=sum(Q<=X);x-=Q[j-1]//f;k-=1;return*(1//k*[x]or e(x,k)),j+i-k d=lambda L,j=1:1+sum([p(s-1+r_[:j])//p(r_[1:(j:=j+1)])for s in sort(L)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NVBLTsMwEBUscwov_VUwC1TZzA26aHeVrKgKJAY7JLGcRErPwqYbuBOcBlspI43mzTzN05v5_A6X-X0crtevZbZi93t3b-PYo2HpwwW5PoxxpsUBXlMfx0YHyKVoWotavPKOqAjxbFRXMaktBByJPsFKrbDagRtmfKIUy7IjRB_hgI3k1LFYpc6IR6WErGgaOyZF2vQwLT0-PsOJ6FXA0fjEl6XVnQCpYzsvcchqZUfNWo3x5oFwz5zoigY-6v6lqdGee5BKsqxmAp6EZNmkr0hZJotnIxX2CjyTpCI26UzIDWhKt-J9mmyv-IHMuMzEenhrseTyYYsbIKpAIeYjHW9TPhHe4A2Qm8j_X_8A) Two functions `e` and `d` for encoding and decoding: We do not use or accept parameter `n` since it is not needed (because using the "natural" encoding different `n` will give the same result provided they are large enough). Multisets are represented as sorted sequences; the decoder also accepts unsorted input. With `n` eliminated it actually makes sense to talk about complexity in `x` because now `x` can grow without bound. I'll assume fixed `k` and that all basic operations including taking the `kth` root are polynomial in the bit length of their operands. As `k` is fixed this will also hold for all factorials and binomial coefficients the functions use. ### How? Decoding is easy since it amounts to summing a couple of binomial coefficients. Encoding is a bit more tricky as we need to invert binomial coefficients (in `n`, `k` is fixed) to make this constant in terms of basic operations we use the simple inequality \$n^\underline k \le n^k \le n^\overline k\$ where the underline and overline denote falling and rising factorials. To find the largest `n` such that \$\begin{pmatrix}n+k-1 \\ k \end{pmatrix}\le x\$ we take the `kth` root of `k!x` and then brute force check all rising factorials whose terms "pass" through the value obtained, `k` in total. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 80 + 31 = 111 bytes ## Encoder, 80 bytes ``` NθNη≔⁰ζ≔⁰ε≔¹δW¬›δη«≔δε≦⊕ζ≔÷×δ⁺ζθζδ»F⮌…⁰θ«W›εη«≦⊖ζ≔÷×εζ⁺ζ⊕ιε»⟦Iζ⟧≧⁻εη¿ι≔÷×ε⊕ι⁺ζιε ``` [Try it online!](https://tio.run/##dY89a8MwEIZn@1doPIELCR07lQZKhoRgupUMqnWxDmw5lmQXHPzbXSm2GyeQ8b2v57lMCZNVohiGrT43bt@UP2ig5m/xMiuf362lXMMqYd1dwltaJ0z69KuoQAb7ysGnQeH8AZkwxTlnlziaZuW4Ge3EeapsdWawRO1Qjozov@E21JJE@KISbVg9FI2FLmE152F25PbxqTIMUmzRWIRU6ByDYT2RJ6/ZCa9OobGQ2OCjxDMLHMGzycIeiAet63t9HB0MaQffH8I66Pjx7umUcuVgR7qxfiEI@S6dmD/BnnMfWDcJmrn9MLzG69Xw0hZ/ "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Takes `k` and `x` as inputs. Explanation: Port of the `sord` function from [this Math.SE answer](https://math.stackexchange.com/a/1370461/30622), but outputs the values in reverse order since it's golfier. ## Decoder, 31 bytes ``` W⁻θυF№θ⌊ι⊞υ⌊ιIΣEυ÷Π…·ι⁺ικΠ…·¹⊕κ ``` [Try it online!](https://tio.run/##bYwxC8IwEIV3f0XGK0RQHDvWpUMh6Fg6hPS0h2miSa7@/Ji4Cd5yvO99PLPoYLy2Ob8XsihgIMcRXlJw04ibDwI6zy5VUipaeQVqSqU4LsA/sN2pQEXtdExwLWzQz6r0Lp1poxlBBT@zSdA7YznShhft7ggkhSq5/kfZLum/d6xbJuCKLuEM1f1em/M4HqQ4SXGYprzf7Ac "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Takes a list of `k` integers as input. Explanation: ``` W⁻θυF№θ⌊ι⊞υ⌊ι ``` Sort the integers. ``` IΣEυ÷Π…·ι⁺ικΠ…·¹⊕κ ``` Apply the `ords` algorithm from [this Math.SE answer](https://math.stackexchange.com/a/1363513/30622). [Answer] # [Haskell](https://www.haskell.org/), 283 bytes ``` import Data.List i=fromIntegral p=product m=map s=succ t=pred f n=p[1..n] a k n=p[n..n+k-1]`div`f k b k x=t$until((>x).a k)s$floor((i$x*f k)**(1/i k)) d _ _[]=0 d k n(e:f)=a k e+d(k-1)e f e 1 n x=[x] e k n x|let m=b k x=m:e(k-1)m(x-a k m) c k n=(m s.e k n.t,s.d k n.m t.reverse.sort) ``` [Try it online!](https://tio.run/##bVC7bsMwDNz1FRw8SHmoMbIFVaYuBfoHhpGolpQKlmRDogMP/XeXdocu3Y7k8Y7HL116G8Ky@DgOGeFNo5YfviDzyuUhvie0j6wDG9WYBzN1yKKKemRFlanrGFLbGuYgqbGppUwt09BvVaJq3x/r9m788@6gZ580mRVWU0IfOL/OQhJZlMqFYcic@2reEU/sdrx@8QQEM3CDW9OqEyGS5fbihFod7N5wEhcWHLNQQyLlZm4J9yv@DhYhql/HeLEbN/L5uO5GwbrtSB6hyG1D4qHIzUJGQJnt0@ZiZaGfiCVqT4GyT8hdQd7BGc7itbqugetTeyjJ/DX/Y4jlBw "Haskell – Try It Online") ]
[Question] [ [Hearts](https://en.wikipedia.org/wiki/Black_Lady) is a 4-player game that uses the following scoring rules: 1. Everyone starts with *score* 0. 2. Each round every player gets a non-negative amount of *points*. The sum of the points is 26, and at least one player gets 13 or more points.1 3. The points are then added to the players' score except if a player gets 26 points. If that happens, everyone else adds 26 to their score, and the player who got 26 points adds none. 4. The game ends when someone gets a score of 100 or more. Until then, steps 2 and 3 are repeated. Your task is to take 4 non-negative integers representing the scores of the players at the end of the game and decide if it's a valid game. That is, are those scores possible to achieve by following the rules until the game ends. # Samples ``` [26,26,26,26] -> False (The game has not ended since no one has a score of 100 or more) [1,1,2,100] -> True ([1,0,0,25]+[0,1,0,25]+[0,0,1,25]+[0,0,1,25]) [1,1,2,108] -> False (Sum not divisible by 26) [26,26,26,260] -> False (Game should have ended before a score of 260 is reached. In fact, 125 is the maximum score a player can have) [104,104,104,0]-> True ([26,26,26,0]+[26,26,26,0]+[26,26,26,0]+[26,26,26,0]) [0,0,0,104] -> False (One can't just add 26 points to his score. That would add 26 to the 3 other players) [13,13,104,104]-> True ([0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[13,0,13,0]+[0,13,0,13]+[0,0,13,13]) [10,10,120,120]-> False (The last turn must be [26,26,26,0] for two players to reach 120, but two players also have <26 score) [0,0,5,125] -> False (The last turn can't be [0,0,0,26], suggested by Neil [117,117,117,117]-> False (Last turn get >26 point and is not a [0,26,26,26]) [104,104,104,104]-> False (Even if last round is [13,5,4,4], it was [91,99,100,100] which is impossible) [101,101,101,113]-> True ([7,7,6,6]+[26,26,26,0]+[26,26,0,26]+[26,0,26,26]+[0,26,26,26]+[13,13,0,0]+[0,0,13,13]+[3,3,4,16] thank AnttiP for the example) [15,125,125,125] -> True ([5,13,4,4]+[5,4,13,4]+[5,4,4,13]+[0,26,26,26]+[0,26,26,26]+[0,26,26,26]+[0,26,26,26] as Nitrodon suggest) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins. # Note * All true cases can be seen [here](https://github.com/837951602/PossibleHearts-242415/blob/master/possible/EndedConclusion.txt?raw=true). You can also see [here](https://github.com/837951602/PossibleHearts-242415/tree/master/possible) for possibilities of score for a given amount of rounds and state(ended/not) 1 `non-negative amount of points` is the game part. 13 is the Queen of spades [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 69 bytes ``` ∧‹﹪Σθ²⁶‹³⁻Σθ⌈θ⎇‹⁹⁹⌊θ›³¹¹⁻Σθ⌈θ¬÷⎇‹²ΣEθ‹²⁵ι⁻⌈θ¹⁰⁰∨±‹¹²⁴⌈θ⊖ΣEθ⌈⟦⁰⁻ι⁹⁹⟧²⁶ ``` [Try it online!](https://tio.run/##fZBNi8IwEIb/yhynMEIT7ULxtCAsgnUFvUkPoR3cQJtqmsr662NstvvhYecwBN43zxNSfShbdarxfme1cfhqatxw32PR1UPT4X5o8ZIQyJewxmBOUGgz9N9RoT51O57DEBzYGmVvkZLnY3vKCd4sK8cW50L8xyHYdg7Xxq30VdeMf6CS4HGnUGe8fD1KZgQ6@iP0B0Yg0jTsd4tbPgV5hAi5eFauuLLcsnFc4y/BVDqmE1wT5HlSJkk0hr95zNL7Y@iklJGQWVn62bW5Aw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if possible, nothing if not. Explanation: A final score is valid if it satisfies the following: * The sum of all the scores is a multiple of 26. * The three players excluding the highest score have scored at least 4 between them. * If all four players have scored at least 100, then the three players excluding the highest score have scored at most 310 between them. * Otherwise if at least three players have scored 26, then the highest score is between 100 and 125 inclusive. * Otherwise, the highest score is less than 125 but the sum of the amounts by which the relevant players have scored over 99 is between 1 and 26 inclusive. In order to verify the assertions above I devised an alternative approach which unfortunately is still 7 bytes longer than the fixed version after it discovered a bug in my original approach. ``` F³⁸⁴¹⁶F⁴⊞υE⁴⁺﹪÷ιX¹⁴λ¹⁴×¹³⁼κλ›∧‹⁹⁹⌈θ‹³⁻Σθ⌈θ∨﹪Σθ²⁶⬤υ∨⁻²⁶Σι⊙⎇№ι²⁶⁻²⁶ιι÷⁻§θμλ¹⁰⁰ ``` [Try it online!](https://tio.run/##VU9BasMwELz3FTquQAXLcUxDTqYtJVBTQ3MLOYhYIUtlqZasNHm9KskNoQtaxM7M7szhJOzBCBXC0VgCi6eK15Tkf0VJ590JPCOt@IaKkU55B63pvTKw0dMLnrGXgBEwP9ICjxRFKSO8im2Lg3TAF4y8jl4oB18ZjbV@6CzqCd6sFFPUNbqHd@kcrFbp1AUHP8CYFuVp3NCijpc/8/gfJZE@7M3TjVDWsTVKJesJzeqyZiQRMGkafYWttFrYKzwbH83gn@xORjq/e9IZa6aN7uUFRkYGmjLFwEVB51qHsNsVrGBLxsvlfh8ez@oX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F³⁸⁴¹⁶F⁴⊞υE⁴⁺﹪÷ιX¹⁴λ¹⁴×¹³⁼κλ ``` Generate all valid captures for a single round (plus some invalid ones as well, but they'll be filtered out later). The idea is to generate all lists of four non-negative integers that sum to 13, then take each of those and add 13 in turn to each integer. ``` ›∧‹⁹⁹⌈θ‹³⁻Σθ⌈θ∨﹪Σθ²⁶ ``` Check at at least one score is at least 100, at least one other score is at least 4, and the sum of the scores is a multiple of 26. ``` ⬤υ∨⁻²⁶Σι⊙⎇№ι²⁶⁻²⁶ιι÷⁻§θμλ¹⁰⁰ ``` Check that there's at least one valid capture arrangement where subtracting the scores of that arrangement (adjusting for the case where one player captured all of the penalty cards) from the input results in a set of four scores between 0 and 99 inclusive. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes ``` ®ṗ4’S⁼®ƊƇṀ>12ƊƇ 4⁻þ`×26©;¢ṗ⁴+\Ṁ>99ƊƇḢƊ€ċ ``` A monadic Link accepting a list of integers that yield `0` (falsey) if not a possible Hearts result or a positive integer (truthy) if it is. **[Don't Try it online!](https://tio.run/##y0rNyan8///Quoc7p5s8apgZ/Khxz6F1x7qOtT/c2WBnaARicZk8atx9eF/C4elGZodWWh9aBFT7qHGLdgxIiaUlWPGORce6HjWtOdL9////aBMdBQMdBUMDIGEQq6CgrFCSkVqUql6skJevUJCfmVeiUFJUmZmXDhTPLNZRyCxRKM/PUy9RSMvMyyzOUAQA "Jelly – Try It Online")** ...it won't finish (Maybe I'll golf one that will too...). ### How? ``` ®ṗ4’S⁼®ƊƇṀ>12ƊƇ - Helper link: no arguments ® - recall 26 from the register ṗ4 - All length 4 lists of [1..26] ’ - decrement (vectorises) S⁼®ƊƇ - keep those with sum 26 Ṁ>12ƊƇ - keep those with a maximum value over 12 4⁻þ`×26©;¢ṗ⁴+\Ṁ>99ƊƇḢƊ€ċ - Link: list of four integers, X 4⁻þ` - table of not-equal between [1,2,3,4] and itself 26© - place 26 in the register × - multiply the table values by 26 ;¢ - concatenate all the other scores by calling the helper Link ṗ⁴ - All length 16 lists with those lists as elements note: games take at most 15 rounds (and ⁴ is shorter than 15) Ɗ€ - for each, last three links as a monad: +\ - cumulative reduce by addition (non-vectorising, unlike Ä) Ƈ - keep those for which: Ṁ>99Ɗ - maximum is greater than 99 Ḣ - head (first reached winning score list) ċ - count occurrences of X ``` [Answer] # Python 3, 220 bytes ``` s={(0,)*4} r=range(27) f=lambda*a:[a]*(12<max(a)<sum(a)==26or sum(a)-min(a)*2==78)if len(a)>3 else sum([f(*a,i)for i in r],[]) for t in r:s={i*(max(i)>99)or tuple(map(sum,zip(i,j)))for j in f() for i in s} s.__contains__ ``` It should work in theory. But I had never tested it actually. No TIO links as it certainly timed out on TIO. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 48 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) An extremely slow brute-force approach.. ``` 30Åœ4ù<ć_₂*šʒà13@}€œ€`₂ã€η€`€øOʒàƵP‹}ʒ{¨OƵÓ‹}€Qà ``` No TIO since it's way too slow. A port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/242422/52210) would be 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage): ``` {¨OUт@PiXƵÓ‹ë₂@O3@iàтƵOŸsåë₂LIZƵO‹*99-DdÏOå]IO₂ÖX4@P ``` [Try it online](https://tio.run/##yy9OTMpM/f@/@tAK/9CLTQ4BmRHHth6e/Khh5@HVj5qaHPyNHTIPL7jYdGyr/9EdxYeXgkV9PKOAfKAaLUtLXZeUw/3@h5fGevoDZQ5PizBxCPj/P9pAx0DHVMfQyDQWAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKSvdL/6kMr/EMvNjkEZEYc23p48qOGnYdXP2pqcvA3dsg8vOBi07Gt/kd3FB9eChb18YwC8oFqtCwtdV1SDvf7H14a6@kPlDk8LcLEIeC/kl6YDhfIBq7yjMycVIWi1MQUhcw8rpR8LgUF/fyCEn2IQ6AUmttsFFTAavNS/0cbmenAUCxXtKGOoY6RjqGBARLbAshGUgWWMjDRgWEQ30AHBIE8kJyxDghBZMFqdUDICIyhak2BbFOQnKG5DhJGMxmmH@gQGDY0BomAtcNwLBcA). **Explanation:** ``` 30Åœ # Get all lists of positive integers that sum to 30 4ù # Only keep all lists of length 4 < # Decrease each by 1 # (we now have all non-negative integers that sum to 26) ć # Extract head; pop and push remainder-list and first list # separated to the stack # (the first list is [0,0,0,26]) _ # Check for each if it's 0: [1,1,1,0] ₂* # Multiply that by 26: [26,26,26,0] š # Prepend it back to the list ʒ # Filter these lists by: à13@ # Check if the maximum is ≥13 }€ # After the filter: map over each remaining list: œ # Get all its permutations €` # Flatten it one level down to a list of lists again ₂ã # Take the cartesian product of 26 # (at least 15 is required, and 26 is the smallest single byte # constant above this) €η # Get the prefixes of each inner list of 26 lists €` # Flatten it one level down to a list of list of lists €ø # Zip/transpose each inner list of lists O # Sum each inner-most list ʒ # Filter these lists of sums: àƵP‹ # Check if the maximum is smaller than 126 }ʒ # Filter again: { # Sort the four values ¨ # Remove the last/highest O # Sum the lowest three ƵÓ‹ # Check if it's smaller than 311 }€Q # After the filter: check for each remaining list if it's equal to # the (implicit) input-list à # Max: check if any is truthy # (which is output implicitly as result) ``` ``` { # Sort the (implicit) input-list ¨ # Remove the last/highest value O # Sum the remaining three U # Pop and store it in variable `X` т@Pi # If all four values in the (implicit) input-list are ≥100: XƵÓ‹ # Check if `X` is smaller than 311 ë₂@O3@i # Else-if at least three values are ≥26: àтƵOŸså # Check if the maximum is in the range [100,125] ë # Else: IZƵO‹ # Check if the maximum of the input is <125 * # Make everything 0 if this is falsey 99- # Decrease each value in the input-list by 99 DdÏ # Only keep the non-negative values O # Sum those together ₂L å # Check if this sum is in a [1,26]-ranged list ] # Close all if-else statements IO₂Ö # Check that the sum of the input-list is divisible by 26 X4@ # Check that `X` is ≥4 P # Check if all four checks on the stack are truthy # (after which this is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵÓ` is `311` and `ƵO` is `125`. ]
[Question] [ This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge (and test cases) are inspired by the work of Project Euler users amagri, Cees.Duivenvoorde, and oozk, and Project Euler Problem 751. (And no, this isn't on OEIS). [Sandbox](https://codegolf.meta.stackexchange.com/a/23997/82007) A non-decreasing sequence of integers \$a\_n\$ can be generated from any positive real value \$\theta\$ by the following procedure: $$ \newcommand{\flr}[1]{\left\lfloor #1 \right\rfloor} \begin{align} b\_n & = \begin{cases} \theta, & n = 1 \\ \flr {b\_{n-1}} (b\_{n-1} - \flr{b\_{n-1}} + 1), & n \ge 2 \end{cases} \\ a\_n & = \flr{b\_n} \end{align} $$ Where \$\flr x\$ is the floor function. For example, \$\theta=2.956938891377988...\$ generates the Fibonacci sequence: 2, 3, 5, 8, 13, 21, 34, 55, 89, ... The *concatenation* of a sequence of positive integers \$a\_n\$ is a real value denoted \$τ\$ constructed by concatenating the elements of the sequence after the decimal point, starting at \$a\_1\$: $$\tau = a\_1.a\_2a\_3a\_4...$$ For example, the Fibonacci sequence constructed from \$\theta=2.956938891377988...\$ yields the concatenation \$τ=2.3581321345589...\$ Clearly, \$τ ≠ \theta\$ for this value of \$\theta\$. We call a positive real number \$\theta\$ **coincidental** if \$\theta = τ\$ as generated above. # Challenge Given a natural number \$k > 0\$ as input, you must output the number of coincidental numbers \$\theta\$ such that \$k = \flr \theta\$. # Test Cases ``` 1 -> 1 2 -> 1 3 -> 0 4 -> 2 5 -> 1 6 -> 0 7 -> 0 8 -> 0 9 -> 0 10 -> 1 11 -> 1 12 -> 1 13 -> 1 14 -> 1 15 -> 1 16 -> 2 17 -> 1 18 -> 1 19 -> 1 20 -> 2 21 -> 2 22 -> 1 23 -> 1 24 -> 1 25 -> 1 26 -> 1 27 -> 2 28 -> 2 29 -> 1 30 -> 2 31 -> 2 32 -> 1 33 -> 0 34 -> 1 35 -> 1 36 -> 3 37 -> 0 38 -> 2 39 -> 3 40 -> 1 41 -> 1 42 -> 1 43 -> 4 44 -> 3 45 -> 1 46 -> 1 47 -> 2 48 -> 2 49 -> 4 50 -> 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žhтã'.ì«ʒтsλ£Dï©->®*}ïć'.«šJyÅ?}g ``` Brute-force, so extremely slow. The program above validates all real values \$\theta\$ in the range \$[input,input+1)\$ in increments of \$10^{-100}\$. Replacing the two `т` above with `4` and `5` respectively (to make the increments of size \$10^{-4}\$) at least gives outputs, although does still fail for some of the test cases unfortunately*†*: [Try it online.](https://tio.run/##ATwAw/9vc2FiaWX//8W@aDTDoycuw6zCq8qSNXPOu8KjRMOvwqktPsKuKn3Dr8SHJy7Cq8WhSnnDhT99Z///MTY) *†*: the failing test cases when we use `4` & `5` are: \$k=21\$ (requires at least `9` & `6`); \$k=29\$ (requires at least `5` & `4`); \$k=33\$ (requires at least `5` & `4`); \$k=36\$ (requires at least `6` & `4`); \$k=37\$ (requires at least `5` & `4`); \$k=39\$ (requires at least `5` & `4`); \$k=40\$ (requires at least `5` & `4`); \$k=43\$ (requires at least `7` & `5`); \$k=44\$ (requires at least `5` & `4`); and \$k=49\$ (requires at least `5` & `4`). **Explanation:** ``` žh # Push builtin 0123456789 тã # Cartesian power of 100: create all possible strings of size 100 # using these digits '.ì '# Prepend a "." in front of each « # Merge each to the (implicit) input-integer # (we now have a list of decimal values in the range # [input,input+1) in increments of 1e-100) ʒ # Filter this list of real values `θ` by: λ # Start a recursive environment, т £ # to output the first 100 values s # Where a(0)=`θ` # and where every following a(n) is calculated as follows: # (Implicitly push a(n-1)) D # Duplicate this a(n-1) ï # Floor it © # Store this floored a(n-1) in variable `®` (without popping) - # Subtract it from a(n-1) > # Increase it by 1 ®* # Multiply it by `®` }ï # After the recursive method: floor all values in the list ć # Extract the head (the floored value we started with; a.k.a. the # input); pop and push remainder-list and first item separated to # the stack '.« '# Append a "." š # Prepend it back to the list J # Join this list together to a string yÅ? # Check if it starts with the current `θ` as prefix }g # After the filter: pop and push the length # (which is output implicitly as result) ``` ]
[Question] [ The objective is to make the smallest SB3 file that can simply be imported into Scratch 3.0 without a "The project file that was selected failed to load" error. Any means can be used, like editing the JSON or better compression. Here's where I am with project.json, the only file inside mine: ``` {"targets":[{"isStage":true,"name":"Stage","variables":{},"lists":{},"broadcasts":{},"blocks":{},"comments":{},"costumes":[{"assetId":"00000000000000000000000000000000","name":"","md5ext":"00000000000000000000000000000000.svg","dataFormat":"svg"}],"sounds":[]}],"meta":{"semver":"3.0.0","vm":"0.0.0"}} ``` [Answer] # 303 bytes I think this is the lowest possible score. I managed to remove some more stuff from `project.json` and used the best compression 7-zip could offer me. File is [here](https://drive.google.com/file/d/1OG11X6RIQPhHM3Lwl5iBddG-kPUm9VYN/view?usp=sharing). project.json ``` {"targets":[{"isStage":true,"name":"Stage","variables":{},"blocks":{},"costumes":[{"assetId":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"","md5ext":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.svg","dataFormat":"svg"}],"sounds":[]}],"meta":{"semver":"3.0.0","vm":"0.1.0"}} ``` [Answer] # ~~263~~ 257 bytes ~~The MD5 uses 0s instead of As, `semver` and `vm`'s locations are swapped, `vm`'s `0.0.0`, `project.json`'s creation, modification and access times are 01/01/2000 00:00:00 with the N (none) attribute (Attribute Changer 10 used) and FileOptimizer's used to optimize the SB3's compression. ``` {"targets":[{"isStage":true,"name":"Stage","variables":{},"blocks":{},"costumes":[{"assetId":"00000000000000000000000000000000","name":"","md5ext":"00000000000000000000000000000000.svg","dataFormat":"svg"}],"sounds":[]}],"meta":{"vm":"0.0.0","semver":"3.0.0"}} ```~~ I've done some more swapping, used the A (archive) attribute and changed all the numbers to 3, even the date and time (03/03/3333 03:33:33). Oddly, the year 2108 problem occurs after optimization. ``` {"targets":[{"costumes":[{"assetId":"33333333333333333333333333333333","md5ext":"33333333333333333333333333333333.svg","dataFormat":"svg","name":""}],"name":"Stage","isStage":true}],"blocks":{},"sounds":[],"variables":{},"meta":{"semver":"3.3.3","vm":"3.3.3"}} ``` ]
[Question] [ *Because [ARM is the July 2021 LoTM](https://codegolf.meta.stackexchange.com/questions/23648/language-of-the-month-for-july-2021-arm), I figured I'd create the tips thread.* ARM is probably the most successful architecture for the digital world. From mobile phones to supercomputers, ARM is everywhere! Consequently, let's have a thread where we can help each other shorten our ARM code. One tip per answer, and no stupid tips like "oh remove comments and whitespace". [Answer] # Use `s` instructions to your advantage. ### ARM Unlike x86, ARM lets you choose whether to set the condition codes on its instructions, by suffixing the instructions with `s`. This is useful for do-while loops, where you can subtract, do some things, and keep that condition set until you want to branch or conditionally execute. ``` loop: // Subtract from r0, set condition codes subs r0, r0, #1 // idk, do something silly ldr r1, [r0, r2] add r1, r3, r1, lsl #2 str r1, [r0, r2] // condition codes are still set from subs // loop while r0 is not zero bne loop ``` ## Thumb-2 This applies in a different way on Thumb-2. In Thumb-2, most of the narrow instructions always set the condition codes\*, while wide instructions give you the freedom of choice. However, the assembler won't warn you if it is using the wide instruction. Take the following "Hello World" program: ``` .syntax unified .arch armv6t2 .thumb .thumb_func .globl _start _start: mov r0, #1 // stdout adr r1, .Lhello // "Hello, World!" mov r2, #13 // string length mov r7, #4 // sys_write svc #0 // write(1, "Hello, World!", 13) mov r7, #1 // sys_exit svc #0 // exit(dontcare) // UNREACHABLE .Lhello: .ascii "Hello, World!" ``` This is very inefficient, as `mov Rd, #imm` is a wide instruction: ``` 00000000 <_start>: 0: f04f 0001 mov.w r0, #1 4: f20f 0110 addw r1, pc, #16 // adr r1, .Lhello 8: f04f 020d mov.w r2, #13 c: f04f 0704 mov.w r7, #4 10: df00 svc #0 12: f04f 0701 mov.w r7, #1 16: df00 svc #0 ``` Instead, if you use `movs` which sets the condition codes, you get a much smaller result: ``` 00000000 <_start>: 0: 2001 movs r0, #1 2: f20f 010c addw r1, pc, #12 // adr r1, .Lhello 6: 220d movs r2, #13 8: 2704 movs r7, #4 a: df00 svc 0 c: 2701 movs r7, #1 e: df00 svc 0 ``` Note: 2 bytes can be saved here by [placing this code at an address that is not 4 byte aligned](https://codegolf.stackexchange.com/a/230923/94093) \*There is one exception. IT blocks. IT Blocks will prevent condition codes from being set, even on narrow instructions (aside from ones like `cmp` and `tst` where it is pointless not to). If you are in a situation where you want to chain up to 4 instructions together without setting the condition codes, you can use `it al`. Note that this is only beneficial for two or more instructions, as IT blocks require an opcode themselves. For only one, it might just be better to use a wide instruction or to `cmp` again. [Answer] # ARM/Thumb: Use block loads/stores `ldm`, `stm`, `push`, and `pop` are pretty cool. They let you load/store multiple registers in order, optionally incrementing or decrementing before or after. It can be useful for large literal pools instead of a chain of `ldr`s. In Thumb-2, this also lets you postincrement without a wide instruction. ``` // *r1++ = r0 str r0, [r1], #4 // f841 0b04 stm r1!, {r0} // c101 ``` [Answer] # Thumb: Make sure your literal pools are aligned. The PC-relative instructions `adr` and `ldr =x` will only be narrow instructions if they are accessing a 4 byte aligned pointer. Simply reordering things or adding padding can make your literal pools aligned and prevent a wide instruction. This can often create a chain reaction when you have multiple constants, as the act of making one `ldr`/`adr` aligned will change the alignment of other literals, this can be for better or worse. Another option is to load your code at an address that is **not** 4 byte aligned, so the literal **is** 4 byte aligned. You can typically just put a `nop` at the top of the code to simulate this (assemblers will align your code by default) ]
[Question] [ I have a bunch of ASCII art that I have recovered from a failed hard drive. Unfortunately, all of the newlines were stripped out, and I don't know the resolution of the original artwork. I do know that each one was originally rectangular, but to make matters worse, all the white space at the beginning and end was stripped out too! I *do* at least know what one small piece of each one looks like. Can you help me recover the artwork based on the input stream of bytes and the piece of ASCII art I remember? ## Example I remember this one: ``` __(((55^$$%^/\__%%//\/_666332@12 ``` Had this diamond in it: ``` /\ \/ ``` The original artwork in this case was 8 characters wide: ``` __(((55^ $$%^/\__ %%//\/_6 66332@12 ``` Then there's this one, which had a bigger diamond in it. ``` /\/\/\/\/\:;/ \00F\/\/\ /E%epopox\/e ``` The diamond looked like this: ``` /\ / \ \ / \/ ``` The original artwork contained that diamond, but the white space surrounding the diamond was not white space in the original artwork. I’ve only added in the white space to the left to get the indentation right. More generally, in each row, any space to the left of the first non-white-space character is indentation padding, and any white space to the right necessarily represents actual white space. Note that this is also one of those pieces that has had its white space trimmed off. Here's the original, 11 characters wide, with white space restored: ``` /\/\/\/\ /\:;/ \00F \/\/\ /E%e popox\/e ``` Remember, the amount of white space removed is unknown. That means I can’t even figure out the possibilities for line length by finding the divisors of the input’s character count. ## Input A string of characters (the artwork, sans newlines, trimmed of white space at the beginning and end), and a two-dimensional string of characters (the piece to look for) Essentially, the string of characters can be generated from the original artwork thus: `artwork.Replace("\n", "").Trim(" ")` ## Output The original artwork with newlines inserted where necessary, and with trimmed white space re-added to the beginning of the first line and the end of the last line. If there is more than one possible solution, you may return one arbitrarily (or all of them if you really want to). ## Test Cases ``` Input: __(((55^$$%^/\__%%//\/_666332@12 /\ \/ Output: __(((55^ $$%^/\__ %%//\/_6 66332@12 ----------- Input: _-/\-_-_vv:;/ \00F\\||\ /E%epopox\/e0 /\ / \ \ / \/ Output: _-/\-_-_ vv:;/ \00F \\||\ /E%e popox\/e0 -------- Input: __ ( ) || || ___|""|__.._ /____________\ \____________/~~~. ( ) || || "" Output: __ ( ) || || ___|""|__.._ /____________\ \____________/~~~. -------- Input: ..XX...XX.......X..X..X X.....X..X...X X.....XX......XX... XX X X X X XX Output: ..XX...XX....... X..X..X X.....X ..X...X X.....X X......XX... ``` Notably, in this last case, the following is *not* valid output: ``` ..XX...XX...... .X..X..X X.... .X..X...X X... ..XX......XX... ``` Credit to jrei @ [asciiart.eu](https://www.asciiart.eu/computers/joysticks) for the joystick ## Rules * This is code golf, so shortest answer in bytes wins. * Default I/O rules apply [Answer] # [Perl 5](https://www.perl.org/), 192 bytes To be golfed more ``` ($_,@F)=@F;$l=max map length,@F;map{$_.=" "x($l-y///c);s/(^ +| +$)|\W/$1=~y, ,.,r||"\\$&"/gme}@F;for$i(0..y///c){$"=".{$i}";$i+=$l,$_=" "x($i-"@-").$_,map{printf"%-$i\s ",$_}/.{1,$i}/g if/@F/} ``` [Try it online!](https://tio.run/##fVHBasJAEL3vVwzLpiSY3YlKPBgCuTSn9lh6GRykRLsQk6BBFFc/vemm9tD20IE5zHvz3huYrtrX6TCEiuOijPKizFSd79Yn2K07qKtm2797IvPTRbHJJchTqGp9RsS3KDtguIKJg4mKHL2imua3cwyxiffOSSL1IHG7q67eYNPulQ0TY@7Ki5K5NBdlrzJTdpKrOlb87W61LLSMjD9pjO32tuk3MtDK0kFIv3dFc5nGXotbsBssSrwOA3MYhmm6UipYITEHASIhLxaL@XxWTGcCSRAKAayRNGs@HpcZAlCSlETOEQA@BlXXdu2JsEoEeMHIi5ERMGqZ4XeFANEfyDn4F2FmJ6VjNubuhvyjaEToJ4K3282IMUh4p3tLKT7arrdtcxh0kjSDfn6yh365fOnt1/cGvS6RGvREapLpJw "Perl 5 – Try It Online") ]
[Question] [ ## Input: An `NxM` grid or multi-line string (or other reasonable input-format), containing only printable ASCII (unicode range `[32,126]`). ## Output: The amount of closed polygons of the same character that can be found, with two special rules: * Spaces are wildcards and can be used (multiple times) for any character * `o`, `O`, and `0` are counted as closed polygons themselves ## Challenge rules: * (Anti-)Diagonal connections between the same characters (or spaces) are included to form closed polygons. * You cannot go over other characters (except for the wild-card spaces). (I.e. in the first test case/example below, you cannot form two triangles with the `A`'s by going over the `x`.) So all characters used for a closed polygon should be connected (horizontally, vertically, and/or (anti-)diagonally). * Polygons are at least three characters (excluding the single characters `o`, `O`, `0`). * Lines of adjacent characters are not closed polygons. * The same characters cannot be used for multiple polygons, excluding wildcard spaces. * Wildcard spaces cannot be counted as `o`, `O`, or `0`. * Three or more spaces alone cannot form a closed polygon. It should always have at least one non-space (and non `o`/`O`/`0`) character. * Input can be in any reasonable format. Can be a character-matrix, new-line delimiter string, string-array, character-array with added integer width, etc. * The inputs will always be an N by M rectangle (or square), so no weird input-shapes * Since the same characters cannot be used more than once and we want to have as many closed polygons, using multiple characters to form two (or more) closed polygons instead of one larger polygon is of course the intended goal in the counting (which is also why closed polygons formed by `o`, `O`, or `0` will never be counted, since they are already closed polygons individually). * Uppercase and lowercase letters are of course counted as individual characters. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Examples / Test Cases: Input: ``` AAAw AxA4 'AoQ ``` Output: `2`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/t8csd.png)](https://i.stack.imgur.com/t8csd.png) --- Input: ``` 1822uaslkoo 12*2sl ljoo a* 0a91)j$* ()*#J9dddj* *Q#ID dJj!" *UJD SO&*93 ``` Output: `12`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/9EEsk.png)](https://i.stack.imgur.com/9EEsk.png) Note that: - The yellow one below is not a polygon, because the `o`'s are already counted as separated polygons - The purple and brown ones aren't closed - The red, grey, green, and light-blue use one or more non-space characters that were already used for other closed polygons [![enter image description here](https://i.stack.imgur.com/I9E4r.png)](https://i.stack.imgur.com/I9E4r.png) --- Input (dimensions are `2x4`): ``` 3 3 2 ``` Output: `3`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/rx7Bm.png)](https://i.stack.imgur.com/rx7Bm.png) --- Input: ``` AAAA AAAA AAxA ``` Output: `3`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/BQdQm.png)](https://i.stack.imgur.com/BQdQm.png) Of course other polygons are possible here, but no more than 3. Here another valid example with `3` polygons: [![enter image description here](https://i.stack.imgur.com/tfrA1.png)](https://i.stack.imgur.com/tfrA1.png) --- Input: ``` 0QoO ``` Output: `3`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/QdcaH.png)](https://i.stack.imgur.com/QdcaH.png) --- Input: ``` W w Ww ``` Output: `3`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/VlAeR.png)](https://i.stack.imgur.com/VlAeR.png) Note that the top layer space is used for all three polygons. Here are the three polygons individually highlighted: [![enter image description here](https://i.stack.imgur.com/ioBZF.png)](https://i.stack.imgur.com/ioBZF.png) [![enter image description here](https://i.stack.imgur.com/pUvRb.png)](https://i.stack.imgur.com/pUvRb.png) [![enter image description here](https://i.stack.imgur.com/FM5gF.png)](https://i.stack.imgur.com/FM5gF.png) --- Input: ``` W W WW ``` Output: `3`, because the same three polygons as in the previous test can be formed. **So no, it's not `2` with these two polygons:** [![enter image description here](https://i.stack.imgur.com/xFFi1.png)](https://i.stack.imgur.com/xFFi1.png) --- Input: ``` abcdQefg hQiQjQQk QlQmnopQ QqrstQQu QvQQQwxy QQz0QQQQ ``` Output: `3`, because these polygons can be formed: [![enter image description here](https://i.stack.imgur.com/eGwTK.png)](https://i.stack.imgur.com/eGwTK.png) [Answer] # [Python 2](https://docs.python.org/2/), 714 ~~737~~ ~~821~~ bytes * -23 bytes thanks to Kevin Cruijssen ``` M=input() m=''.join(M) def P(L): if len(L)<2:yield[L];return for p in P(L[1:]): for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:] yield[[L[0]]]+p h,w,R,C=len(M),len(M[0]),0,[-1,0,1] K=[(i,j)for i in range(h)for j in range(w)] Z=[(i,j)for i,j in K if' '==M[i][j]] from networkx import* for l in set(m): G,S=[],[] if l in'oO0':R+=m.count(l);continue for I in K: i,j=I for p in C: for q in C: X=x,y=i+p,j+q if X in K and X!=I and set(M[i][j]+M[x][y])<=set(' '+l):G+=[(I,X)];S+=[I,X] B=0 for L in P(list(set(S))): b=0 for p in L: for i,j in p: if' '!=M[i][j]: try:find_cycle(from_edgelist([(I,X)for I,X in G if I in p+Z and X in p+Z]));b+=1 except:1 break if b>B:B=b R+=B print R ``` [Try it online!](https://tio.run/##TVFNb@IwED3jX@GeEq/dCno09R7oAaGCuoIDqJZVkcQUp4njGiPIr2fHSbrdSzye8Zv3EdeGY2Mfb7eVMNadQ0pQLZLkoWyMTVcEFfqA/6RLwhE2B1xpC/XTI2@Nrgq5VFOvw9lbhA@Nxw4bGx/LCVcAGMWeZafY1fZca78POnWkB2MnuVVUyqUcK0VPijppKSDRqF/eD6CNjuzC1uxZRPYVYd0BM8LGTN5P4DtR6EXI1LCSRE4TGf3efuj02DXKn8aFKPT2/1vWDV/AXYITIVbSKFkqhQ6@qbHV4dL4zys2tWt8@IUipIqAkw5pHVOZs42QiknVBwSzpHkdJ3xNRf2QN2cb0opM88YGY8@6D2rRUQI40osFnP/iex5y@/q@4J24slYY6lhJv@AOLLte8t4WeHcnFl0RBQ3i6UpelWwVeRKxC75oRficgu0F2xE13UAJFUieiXEvadn/u8qcQhpBG0KiO5zFBz/yloO8ITbHO0HAcPedHMdoNAq@5Qdji/e8zSudxizfdfGhu/W9ii4H1jmZR09dJo6@9a6GiyJkmlExgZX6mmsXeCwzr/efaASg7PeMz0SGMKQ9Q84bG/D6dpPJFm8TluDtNlF/AQ "Python 2 – Try It Online") 1. For each letter `A` (except `o`, `O`, and `0`) the code build a graph representing the adjacency of the different occurrences of letter `A` and space in the initial given matrix. Then it computes the set of semi-separated cycles covering the graph when maximizing the number of cycles (separation is based only on the letter `A`, the same space can be used for several cycles). 2. The code passes all tests. 3. Input: the list of lines of the matrix. 4. More explanation and golfing coming soon. ]
[Question] [ inspired by [this chat conversation](https://chat.stackexchange.com/rooms/240/conversation/satisfying-numbers) A *satisfying number* is a number whose decimal representation is of the form `abx`, with the following properties: * `x` is the longest trailing repeating suffix, or the last digit if there is no repetition at the end (`123333` -> `3333`, `545656` -> `5656`, `123` -> `3`) * `b` is the single digit prior to `x` (`123333` -> `2`, `55545656` -> `4`) * `a` is the remaining prefix (`123333` -> `1`, `55545656` -> `555`) * `a == c**b` (`**` denotes exponentation), where `c` is the number of repetitions of the smallest repeating portion of `x` (`1623333` -> `4` (`3 3 3 3`, not `33 33`)) For example, `8300` is a satisfying number with `a = 8`, `b = 3`, `c = 2`, and `x = 00`. `24651` is not a satisfying number, because `x = 1`, `b = 5`, `a = 246`, and there is no integer `c` that satisfies `c^5 = 246`. `1222` is also not a satisfying number, because with `x = 222` and `b = 1`, there are no remaining digits for `a`. Given a positive integer `n >= 100`, output whether or not `n` is a satisfying number. ## Examples ``` 8300: True (a=8, b=3, c=2, x=00) 24651: False 1222: False 92555: True (a=9, b=2, c=3, x=555) 64633: True (a=64, b=6, c=2, x=33) 512944: True (a=512, b=9, c=2, x=44) 123: True (a=1, b=2, c=1, x=3) 822809: False 376664: False 723799: False 1234: False 34330000000: True (a=343, b=3, c=7, x=0000000) 92313131: True (a=9, b=2, c=3, x=313131) 16424442444: True (a=16, b=4, c=2, x=24442444) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) feels too long ``` DŒṖṖEÐƤḄ$ÐṀLÐṂṪµḢ*@0¦LµṪ⁼Ḍ ``` A monadic link taking an integer and returning `1` if the input is satisfying and `0` if not. **[Try it online!](https://tio.run/##y0rNyan8/9/l6KSHO6cBkevhCceWPNzRonJ4wsOdDT4gsunhzlWHtj7csUjLweDQMh8gc@eqR417Hu7o@f//v6WRsSEIAgA "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8/9/l6KSHO6cBkevhCceWPNzRonJ4wsOdDT4gsunhzlWHtj7csUjLweDQMh8gc@eqR417Hu7o@X90z@H2R01r3P//j7YwNjDQsTQyNTXVMTMxMzbWMTU0sjQx0TE0MtYxNjEGyoIBUImxIQjqGJmYmRoCpY2MdCyMjCwMLHWMzc3MzEx0zI2MzS0tQRpNYgE "Jelly – Try It Online") ### How? ``` DŒṖṖEÐƤḄ$ÐṀLÐṂṪµḢ*@0¦LµṪ⁼Ḍ - Link: integer, n e.g. 8300 D - to decimal list [8,3,0,0] ŒṖ - all partitions [[[8],[3],[0],[0]],[[8],[3],[0,0]],[[8],[3,0],[0]],[[8],[3,0,0]],[[8,3],[0],[0]],[[8,3],[0,0]],[[8,3,0],[0]],[[8,3,0,0]]] Ṗ - pop (the "no tail" one) [[[8],[3],[0],[0]],[[8],[3],[0,0]],[[8],[3,0],[0]],[[8],[3,0,0]],[[8,3],[0],[0]],[[8,3],[0,0]],[[8,3,0],[0]]] ÐṀ - keep maximal under the operation: e.g. for [[8,3],[0],[0]] $ - last two links as a monad: ÐƤ - for suffixes: i.e. [[[8,3],[0],[0]],[[0],[0]],[[0]]] E - all equal? [0 ,1 ,1] Ḅ - convert from binary 3 - ...which yields [[[8],[3],[0],[0]],[[8,3],[0],[0]]] ÐṂ - keep minimal under the operation: L - length - ...which yields [[[8,3],[0],[0]]] Ṫ - tail (rightmost) [[8,3],[0],[0]] µ - monadic chain separation Ḣ - yield head and modify [8,3] ...leaving [[0],[0]] L - length (of modified) 2 ¦ - sparse application (to the [8,3]) 0 - ...to index: 0 (to the rightmost digit, the 3) *@ - power (sw@p args) [8,8] ([8, 3*@2] = [8, 2*3] = [8,8]) µ - monadic chain separation Ṫ - yield tail and modify 8 ...leaving [8] Ḍ - from decimal (modified) 8 ⁼ - equal? 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 141 bytes ``` a=b=0;k=[] c=[*input()];l=len(c) while c[1:]>[]==k:a=a*10+b;b=int(c.pop(0));k=[i for i in range(2,l)if c==i*c[:l//i]];l-=1 a==(k+[1])[0]**b>q ``` [Try it online!](https://tio.run/##bU67csIwEOz1FRoabJME62GDzRwdKZMmnUaFrMigsSM7Qkzg6x2LSUGRu@Lmbvd2d7yF0@DYpIdPA4vFYlLQQL7rQEikQWTWjZeQpHLXQ29colP0c7K9wVqQWu6FBOhqBSoj@arZNWBdSPTLOIxJnqZRxeJ28Nhi67BX7mgS@tSntsUawGZa1P16beWs/gwEKYCkWwkiU5HLLGv239Oc6M/ww19MjTAO/hYHxuZqdBJjp/d19NF76YaAzyrYc3uz7riMmLlqMwb8pr7MwfvB14/8/7mH99cHauON6qYty3NEeVkQRCilqKJFUaCSl4yhgtCK8/nO0JbSbV4htinLkqMNZZuqigBHjLNZ4l7zMyOxfwE "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 144 bytes ``` a=b='';k=[] c=[*input()];l=len(c) while c[1:]>[]==k:a+=b;b,*c=c;k=[i for i in range(2,l)if c==i*c[:l//i]];l-=1 int(a or-1)==(k+[1])[0]**int(b)>q ``` [Try it online!](https://tio.run/##bU47b8IwEN79KyyWxAFE/EggQcdGx3bpFnlwXANWUic1RoVfn8aoQ4feDae773Hf@AiXwfFJDx8GFovFpKCFJNl30EikocmsG28hJXLfQ29cqgn6vtjeYN3QWh4aCdDVagntvl1lGnQUWnwaPLbYOuyVO5uUrXpiT1gD2Ew3db/ZWDkbroEi60Kq8ODXlACk3bKhkjS5zLIItOTwNc2hfl@@@5upEcbBP@LA2NyNTmNy8lxHH0WJGwK@qmCvp4d15yRi5q7NGPCr@jRH7wdf/@X/zz2@vfyhtt6obtrxPEdMlAVFlDGGKlYUBSpFyTkqKKuEmO8c7Rjb5RXi27IsBdoyvq2qCAjEBZ8tnjWLOY39Aw "Python 3 – Try It Online") output is via exit code [Answer] # [Perl 6](http://perl6.org/), 66 bytes ``` {/^(\d+?)(\d)((\d+?)$0+||\d)$/&&($2.comb/($2[0]||1).comb)**$1==$0} ``` [Try it online!](https://tio.run/##JYzbCoMwEER/ZZAgXqAmu0k0tNoP6UV686lisU@ifruNdhaGObvsfF792y7tgLBBuYzZNTo/02PsPY7@Uch0mjyKLAwjQbtH194zH07yMk0q3jhOEqHKUsh52eN7GxCIGmWFsYGo5wBN1@NQsJQgbY2CIiI4MsbAassMo8hp7feMgqiQDpxbazVy4ty59aDBmn3FJv/Map1q@QE "Perl 6 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 101 bytes ``` import re x,_,b,a=re.findall(r"((.+?)\2+)(.)(.*)",input()[::-1])[0] if int(a[::-1])!=len(x)**int(b):d ``` # [Python 3](https://docs.python.org/3/), 107 bytes ``` import re x,_,b,a=re.findall(r"((.+?)\2+)(.)(.*)",input()[::-1])[0] if int(a[::-1])!=len(x)**int(b):int('') ``` Output is by exit code. This code doesn't run properly on Tio due to a range error. Works perfectly in IDLE. [Answer] # JavaScript (ES6), ~~282~~ 268 bytes ``` t=(d,n,l,i,r)=>d.slice((m=-l*i)-l,m).join``!=n?r:t(d,n,l,i+1,{p:r.p+n,r:r.r+1});p=(d,l,r)=>l<1?r:p(d,l-1,r.r<(z=t(d,(m=d.slice(-l).join``),l,1,{p:m,r:1})).r&&(z.r>1|l==1)?z:r);u=n=>(d=[...n]).slice(0,(q=(s=d.length)-(m=p(d,s,{p:"",r:0})).p.length-1)).join``==m.r**d[q] function onChange() { var value = document.getElementById("input").value; console.log("%s => %s", value, u(value)); } ``` ``` <input id="input" type="number" onchange="onChange()" /> ``` [Answer] ## Python 2, 286 bytes *yeesh.* ``` n=`input()` N=lambda p,l=0:N(n[:-len(p)],p,l+1)if n[-len(p):]==p else l try: s=[(N(n[-i-1:]),n[-i-1:])for i,_ in enumerate(n)if N(n[-i-1:])!=1] if len(s)==0:s=[(1,n[-1])] q=max(s,key=lambda a:len(a[0]*a[1])) i=len(q[0]*q[1]) print n[:-i-1]==`min(s)[0]**int(n[-i-1])` except:print 0 ``` `N` is a recursive function that finds the number of times a suffix substring is repeated in a string. This basically loops through all possible suffixes, finding the number of times each is repeated using `N`; this excludes all values where `N==1` because they refer to no repeats; if the list ends up being empty, the suffix of the last character is appended to the list. Then, the longest suffix is taken, (`q`), the number of characters it takes up is found (`i`), and `a==c**b` is checked (`print ...`). If an error occurs along the way (which it often will), it is caught in the `except` block. Any suggestions are more than welcome! ]
[Question] [ [<< Prev](https://codegolf.stackexchange.com/questions/150150/advent-challenge-7-balance-the-storage-carts) Thanks to the PPCG community, Santa now has balanced his storage carts. Now, he needs to move them into the transport docks so that they can be sent to the loading bays. Unfortunately, the tracks to move the carts around are a mess, and he needs to figure out how to get them all around without them crashing together! # Challenge You will be given the tracks for each of the carts as lists of "labels" (or stations). The carts must be moved such that at any time frame, no two carts are on the same label/station. Essentially, the carts move between positions that each have a unique label. # Task Given the tracks for each of the carts as a list of lists of labels (which are all positive integers), determine when each cart should be released in order to send all the carts to their destinations safely in the shortest time possible. Here's an explanation of how the entire track system works. Let's say cart `i` is released at time `t_i` onto a track with labels `T_i_1, T_i_2, ..., T_i_n`. Then, during `t_1` to `t_i-1`, cart `i` is not on the grid and can be ignored. At time frame `t_i`, the cart is on label `T_i_1`, and for each time frame `t_k` from `t_i` to `t_i+n` (half-inclusive), the cart is on label `T_i_k+1`. For all time frames after and including `t_i+n`, the cart is at its destination and is no longer on the grid. The total amount of time `t_T` taken is the last time frame with a cart still on a track in the system. # Specifications Given a track system, return a list of time frames `[t_1, t_2, ..., t_n]` where the `i`th cart starts at time `t_i`, such that no other arrangement would allow the carts to safely get to their destinations with a lesser total amount of time. In terms of "safely", if at any time frame from `t_1` to `t_T` there is more than one cart on any label, then they collide and the arrangement was not "safe". Note that two carts can move from `a, b` to `b, a` and still be "safe" because the tracks are 2-way. # Formatting Specifications Input will be given as a matrix of positive integers in any reasonable format. Output should be given as a list of positive integers in any reasonable format. You may give output in zero-indexed time frames, so then the output would be a list of non-negative integers in any reasonable format. # Rules * Standard Loopholes Apply * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins * No answer will be accepted # Test Cases ``` Input -> Output [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> [1, 1, 1] [[1, 2, 3], [1, 2, 3]] -> [1, 2] [[1, 2, 3], [3, 2, 1]] -> [1, 2] [[1, 2, 3, 4], [4, 3, 2, 1]] -> [1, 1] [[1, 1, 1], [1, 1, 1]] -> [1, 4] [[1, 2, 3, 4], [2, 4, 3, 1]] -> [2, 1] [[1, 2, 3, 4, 5, 6, 7], [2, 3, 3, 4], [5, 4, 3]] -> [1, 3, 4] [[1, 2, 3, 4, 4], [1, 2, 3, 5, 4], [1, 2, 3, 4, 5]] -> [2, 3, 1] ``` Note: I drew inspiration for this challenge series from [Advent Of Code](http://adventofcode.com/). I have no affiliation with this site You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge [here](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault). Happy Golfing! [Answer] # JavaScript (ES7), 172 bytes Returns an array of 0-indexed time frames. ``` a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0) ``` *NB*: This can only work with labels in [0-31]. This is a JS limit, not a limit of the algorithm. ### Test cases ``` let f = a=>(g=k=>a.map((a,i)=>[l=a.length+1,i,a,L=L<l?l:L]).sort(([a],[b])=>a-b).every(([,n,b],i)=>b.every((c,t)=>o[t+=A[n]=k/L**i%L|0]&1<<c?0:o[t]|=1<<c),o=[],A=[])?A:g(k+1))(L=0) console.log(JSON.stringify(f([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))) // -> [0, 0, 0] console.log(JSON.stringify(f([[1, 2, 3], [1, 2, 3]]))) // -> [0, 1] or [1, 0] console.log(JSON.stringify(f([[1, 2, 3], [3, 2, 1]]))) // -> [0, 1] or [1, 0] console.log(JSON.stringify(f([[1, 2, 3, 4], [4, 3, 2, 1]]))) // -> [0, 0] console.log(JSON.stringify(f([[1, 1, 1], [1, 1, 1]]))) // -> [0, 3] or [3, 0] console.log(JSON.stringify(f([[1, 2, 3, 4], [2, 4, 3, 1]]))) // -> [1, 0] console.log(JSON.stringify(f([[1, 2, 3, 4, 5, 6, 7], [2, 3, 3, 4], [5, 4, 3]]))) // -> [0, 2, 3] console.log(JSON.stringify(f([[1, 2, 3, 4, 4], [1, 2, 3, 5, 4], [1, 2, 3, 4, 5]]))) // -> [1, 2, 0] ``` ### Commented ``` a => ( // given a = array of tracks g = k => // g = recursive function taking k = counter a.map((t, i) => [ // map each track t in a to a new entry made of: l = t.length + 1, // - its length + 1 (l) i, // - its original index in the input array t, // - the original track data L = L < l ? l : L // and update the maximum track length L ]) // end of map() .sort(([a], [b]) => // let's sort the tracks from shortest to longest a - b // so that solutions that attempt to delay short ) // tracks are tried first .every(([, n, b], // for each track b with an original position n, i) => // now appearing at position i: b.every((c, t) => // for each label c at position t in b: o[t += A[n] = // add to t the time frame A[n] corresponding k / L**i % L | 0 // to this position (i) and this combination (k) ] & 1 << c ? // if the station c is already occupied at time t: 0 // make every() fail : // else: o[t] |= 1 << c // mark the station c as occupied at time t ), // end of inner every() o = [], // start with: o = empty array (station bitmasks) A = [] // A = empty array (time frames) ) ? // end of outer every(); if successful: A // return A : // else: g(k + 1) // try the next combination )(L = 0) // initial call to g() + initialization of L ``` ]
[Question] [ [Muriel](https://esolangs.org/wiki/Muriel) is a language where the only way to loop is to create a quine and execute it. Your job is to create your own language with this property and an implementation of it in a pre-existing language. We will define a Muriel-like language like as follows: 1. It has a built-in command for executing code in its own language, similar to Muriel's [`@`](http://web.archive.org/web/20020609004312/http://demo.raww.net:80/muriel/spec1.txt) command or python's [`exec`](https://docs.python.org/2.0/ref/exec.html). 2. It is Turing complete. 3. If you remove the built-in execution command it is no longer Turing complete. Muriel is Muriel-like with `@` as its built-in execution command. [Smurf](https://esolangs.org/wiki/Smurf) is also Muriel-like (its built-in execution command is `x`). Python is *not* Muriel-like, since it is still Turing complete if you remove `exec`. Your job is to create a Muriel-like programming language, and then to provide an implementation of it in a language of your choice. Your score is the length of the implementation, which you are trying to minimize. Notes: 1. Your built-in execution does not need to function exactly like Muriel. It is up to you how it handles termination of the child program, errors, scoping, etc... 2. The language you write the implementation can not *itself* be Muriel-like. (This is so that `@` is not a valid entry.) It also must have existed before this post. [Answer] # [Python 3](https://docs.python.org/3/) and "The minimum TC subset of Underload but with the characters changed to `2019`~~, reversed, and with a `0` on top~~", ~~156~~ 129 bytes ``` c,n,*s=input(),0,[] while c: i,*c=c;q="6">i if n:n+=q*int(i)-q;s[n and-1]+=i, elif q:n="1"<i;s+=s[-1]*(1-n), else:c=s.pop()+c ``` [Try it online!](https://tio.run/##XVOxctswDN35FThzkWwlJ7l37cWp2qVLpw5pJ50HmoJsXmRSJikn@XoXoC1dzpNI8AEPDw8aPuLB2S8X@YIInXMRPX08jHbv@g5bULYF7Y5HtBH51OKjEPKXigpMgBCdp7CxoOis9KuQaz74GCiy6x1HSkDbfrpX0I5Db7SKGODvnxchn0ANQwLRFaJLPEL@G9qE4YbiAWFdrkuq4xGsizC4EMyuR6qGnMOI1o0UaWEt5G8b0BPKGxszU@giFDYH1bFCUyx1rZ9P9eLr4odJ9VvcjXsS0rmLLmyxDLWxwxizvCiLZiveDoaY9Ebc5Yo7AnrvwG7sqj4tUzx/OD2HxvIcH6rtqjaFAOwJdNrYelEtvpvnsKpDQ4/LrHqweXoPuNF1eBzckOUrfbkTITtPbqWOBb6bmJUUGzyeySQaA/nSeXcEP1pr7F4IPWkBmQZr6xJkiFR0DxZD5G/GL5N1Nz8ZkItQN812ywns7zQIkNcTTZ38IMqUTzYQ6zQkkEd3ThDojA8R9EF5cN2MNZAZSzyjjsaRdFB9YPPtGbkNzZjehChgskqq3Y6EGsUJt2GD/NTvTwEUTWB24eZBBfJADlC/s941qdQeVcBQQEnTnC8VvCIOdODd/8ba8F33Y4ttnooTZfJrVTeG5kKBT/zFbZVJGzXP2w1XP0NTThmOh/ZmAs5ggrbj8fhBUORfTcwarnJ4T2hfKt6V2Q3a7ivnREG@JkDqjjDzb3bt436tQOJZ9Zd1VVZPT/8B "Python 3 – Try It Online") Explanations in the header, ungolfed code in the footer. [Answer] # CJam, [CFU](https://esolangs.org/wiki/CJam-Flavored_Underload) analogue of the `():~^` subset of Underload, 12 bytes ``` q_"_\~\""--~ ``` CJam already happens to be a stack-based language with an eval instruction, which makes it a good candidate for having a Muriel-like subset. In particular, we define a subset with the following instructions: * `"..."`: Push a string `...` to the stack. Quotes and backslashes inside the string can be escaped using backslashes. Equivalent to Underload's `()`. * `_`: Duplicate the top stack value. Equivalent to Underload's `:`. * `\`: Swap the top two stack values. Not strictly necessary for Turing-completeness, but we need to permit backslashes anyway. Equivalent to Underload's `~`. * `~`: Execute the top stack value. Equivalent to Underload's `^`. Explanation of the code: ``` q | read input "_\~\""- | remove all these characters: "_\~ _ - | remove all characters in the resulting string from the input ~ | execute the result ``` ]
[Question] [ ### Purpose The idea is to provide the code necessary to map a 32-bit integer to/from a pronouncable word of 9 characters maximum. That could be useful, for example, to make a serial number easier to remember, or type in a form. Both the method for translating an integer to the corresponding word and for translating back a word to the corresponding integer are required. ### Rules There must be a one-to-one mapping between integers and words, and the whole set of 32-bit integers (or, put in another way, any integer from 0 to 4294967295) must be mappable. Although, obviously, not all words will be meaningful, and inputting words that don't map to an integer may have unspecified behavior. You are free to decide on exactly which set of "pronouncable" words is meaningful, and how the mapping is done, but words must at least follow these rules: * Only the basic 26 letters (A...Z) should be used as characters. Accents, casing, etc... should not be used to extend the possible combinations. * 9 characters maximum per word. * two consonants (BCDFGHJKLMNPQRSTVWXZ - 20 possiblities) should not be placed next to each other (they must be surrounded by vowels). * two vowels (AEIOUY - 6 possibilities) should not be placed next to each other (they must be surrounded by consonants). Note: the simplest scheme where you have all words constructed as `CVCVCVCVC` (`C` being a consonant and `V` a vowel) gives 4147200000 combinations, and a 32 bit integer has 4294967296 possible values, so it is not enough. You need to expand the number of combinations, either by allowing shorter words, or by allowing `VCVCVCVCV` combinations, as well. Other standard rules apply, and standard loopholes are forbidden. ### Inputs/Outputs For each submission, two pieces of code must be provided: * One that takes an integer as argument/input and returns/prints the corresponding word * One that takes a word as argument/input and returns/prints the corresponding integer Alternatively, you can choose to submit a single piece of code that handles both operations: * When given an integer as an input, it outputs the corresponding word * When given a string as an input, it outputs the corresponding integer ### Winning condition This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer which has the fewest bytes (when summing both pieces of code, for solutions opting for the separated pieces of code) wins. [Answer] # PHP, 353 Bytes Encoding + Decoding `is_numeric($argn)` contains the boolean. It is true if the input is an integer. ``` $c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);if(is_numeric($a=$argn)){$r=($a)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r;}else{for($p=1;$i++<strlen($a);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s;} ``` ## PHP, 190 Bytes (Encode) + 195 Byte (Decode) = 385 Bytes ## Encoding ``` $c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);$r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r; ``` 5391360000=26\*120\*\*4 combinations are available [Online Version Encoding without E\_NOTICE](http://sandbox.onlinephpfunctions.com/code/a401c39aa0a3839a1f22c514a119f53a890b9537) ## Expanded ``` $c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]); sort($c); # End of Prepare the two array $r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6]; #base 26 decision input mod 26 <6 end with vowel $a=$a/26^0; #integer division input with 26 while($a){ $z=count($t=in_array($r[0],$v)?$c:$v); # use vowel if last entry is consonant and viceversa $r=$t[$n=$a%$z].$r; # base 6 or base 20 decision $a=$a/$z^0; # divide through base }echo$r; # Output result ``` ## Input => Output ``` 4294967296 => TYPYQACOV 333 => DAT 1 => E 7 => C 4294967276 => UTOPOQAMI ``` If you need always 9 Byte result please replace `while($a)` with `while(strlen($r)<9)` + 10 Bytes ## Decoding ``` $c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);for($p=1;$i++<strlen($a=$argn);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s; ``` ## Expanded ``` $c=array_diff(range("A","Z"),$v=["A","E","I","O","U","Y"]); sort($c); # End of Prepare the two array for($p=1;$i++<strlen($a=$argn);){ $u=($b=in_array($a[-$i],$c))?$c:$v; # find use array for $a[-$i] $s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0); # sum value $p*=$i>1?count($u):26; # raise multiple for next item }echo$s; ``` ## Input => Output ``` ABABABABE => 1 E => 1 UTOPOQAMI => 4294967276 BABABADAT => 333 DAT => 333 TYPYQACOV => 4294967296 ``` [Online Version Decoding without E\_NOTICE](http://sandbox.onlinephpfunctions.com/code/b97d6a2c6f9a39ba688cd88b86d3a52f0b8968f2) ## Additional Check If we need a check if a string is valid. Add `$x.=$b?:0;` in the end of the decoding loop + 10 Bytes Replace `echo$s;` with `echo!preg_match('#([01])\1$#',$x)?$s:_;` + 32 Bytes [Answer] ## JavaScript (ES6), 205 bytes ``` p=>(a='bcdfghjklmnpqrstvwxzaeiouy',1/p)?[...Array(9)].map(_=>r=a[p%(n=26-n)+(p=p/n|0,n<7)*20]+r,n=p>(p%=4e9)?20:6,r='')&&r:[...p].map(c=>r=r*(n=26-n)+a.search(c)%20,n=a.search(p[r=0])<20?6:20)&&r+(n<7)*4e9 ``` Cutoff point between CVCVCVCVC and VCVCVCVCV is 4e9, so starts going wrong at 5244160000 (numeric input) or `zesuwurib` (string input). [Answer] # R, 165 bytes Encoding and decoding in one function. This function uses the brute-force method of creating all possible values and then simply returning the index when it's given string input and returning the string when given integer input. As a consequence, it's very slow and uses 16GB+ of memory! ``` function(x){i=c(1,5,9,15,21,25) d=apply(expand.grid(c<-letters[-i],v<-letters[i],c,v,c,v,c,v,c(c,"")),1,paste,collapse="") `if`(mode(x)=="numeric",d[x],which(d==x))} ``` 4,354,560,000 values are possible. This covers all strings of form CVCVCVCV(C), with the last C being optional. ]
[Question] [ Your task is to build a bridge to connect two cliffs given an input `d`, the distance apart. `d` will always be even However, the bridge needs columns to hold it up. Each column can hold a max of 6 spaces on each side. For this example: ``` ________ ________ | | A | | B |----------------------| d = 22 ``` The bridge for `d = 20`should look like this with two columns. Columns do not count in d. ``` _____|__________|_____ 12345|1234554321|12345 | | ``` **Rules:** 1. Must have enough columns to stand up. 2. Must have minimum number of columns needed to stand up. 3. Must be symmetrical 4. Lowest amount of Bytes Wins Examples: (#s are only to help you count spaces. Should not be included in your output) d = 10 ``` _____|_____ 12345|12345 | ``` d = 32 ``` _____|___________|___________|_____ 12345|12345654321| | | | | ``` d = 8 ``` ____|____ 1234|1234 | ``` d = 4 ``` __|__ 12|34 | ``` d = 22 ``` _____|____________|_____ 12345|123456654321| | | ``` or ``` ______|__________|______ 123456|1234554321|123456 | | ``` [Answer] ## JavaScript (ES6), 92 bytes ``` d=>[..."_ "].map(c=>(s=c+c[r='repeat'](n%6))+'|'+(c[r](12)+'|')[r](n/6)+s,n=d-1>>1).join`\n` ``` Where `\n` represents the literal newline character. If `d` can be odd, it takes me 128 bytes: ``` d=>[..."_ "].map(c=>[...Array(d+1)].map((_,i)=>(d&1?i&&d-i&&(i>m)+5+i-m:((d-1)%24>11)*6+i-m)%12?'':'|',m=d>>1).join(c)).join`\n` ``` [Answer] # Ruby, 108 bytes Probably can be golfed down a lot more. Greedy algorithm. ``` ->d{s='',k=6 (s+=?_*[d,k].min+(d>k/2??|:'');d-=k;k=12)while d>0 s=s.chomp(?|)+s.reverse+$/ s+s.tr(?_,' ')*2} ``` ]
[Question] [ ## Task Given an image with a line on it, produce or display an image with the line extended till the edge of image. The line is black and the background is white. The image size is `100x100` The image comes in any reasonable format (e.g. `jpg`, `png`, `ppm`, `bmp`). ## Line format I'm using a simplified version of [Bresenham's line algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) for drawing lines. Lines will only have an integer slope so that the line will never partially cover a pixel but not color it: ![](https://i.stack.imgur.com/XeLYJ.png) ([Wikipedia image](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#/media/File:Line_1.5x%2B1.svg)) At a minimum the line will be 3x3 unless the line is straight, in which case you will only see 3x1 or 1x3 in the image. Lines will also have one side on the edge of the image, so you only have to extend it in one direction. ### Example (`.png`, red line added so you can see it): [![enter image description here](https://i.stack.imgur.com/kyqoX.png)](https://i.stack.imgur.com/kyqoX.png) [![enter image description here](https://i.stack.imgur.com/XlgVc.png)](https://i.stack.imgur.com/XlgVc.png) ## Real examples (`.png`) [![enter image description here](https://i.stack.imgur.com/BFbH9.png)](https://i.stack.imgur.com/BFbH9.png) [![enter image description here](https://i.stack.imgur.com/wo1PO.png)](https://i.stack.imgur.com/wo1PO.png) ### ==================== [![enter image description here](https://i.stack.imgur.com/6nqBI.png)](https://i.stack.imgur.com/6nqBI.png) [![enter image description here](https://i.stack.imgur.com/deXkK.png)](https://i.stack.imgur.com/deXkK.png) ### ==================== [![enter image description here](https://i.stack.imgur.com/x2Lkc.png)](https://i.stack.imgur.com/x2Lkc.png) [![enter image description here](https://i.stack.imgur.com/kXxTK.png)](https://i.stack.imgur.com/kXxTK.png) ### ==================== [![enter image description here](https://i.stack.imgur.com/TJM7G.png)](https://i.stack.imgur.com/TJM7G.png) [![enter image description here](https://i.stack.imgur.com/VK38Y.png)](https://i.stack.imgur.com/VK38Y.png) ### ==================== [![enter image description here](https://i.stack.imgur.com/UdoWr.png)](https://i.stack.imgur.com/UdoWr.png) [![enter image description here](https://i.stack.imgur.com/kw5Ml.png)](https://i.stack.imgur.com/kw5Ml.png) [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 93 bytes ``` {w←⍵⋄m←÷/(⊢/-⊃)p←⍸¯1≠⍵.mat⋄y x←⊃p⋄P5.size←⍵.sz⋄P5.setup←{P5.G.bg¯1⋄P5.G.ln∊{⍵,y+m×⍵-x}¨⍳101}} ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkG/6vLgdSj3q2PultygazD2/U1HnUt0td91NWsWQCW2nFoveGjzgVANXq5iSVAdZUKFSCJruYCICfAVK84syoVYohecRVUKLWkFKS7Gsh210tKBxkBlnDXy8l71NFVDVSsU6mde3g6kKFbUXtoxaPezYYGhrW1//8DAA "APL (dzaima/APL) – Try It Online") A dfn which takes the image as an `APLImg` object. Taking the image as a URL is 102: [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkG/6vLgVSAqR5QND1V4VHv1kfdLblAocPb9TUedS3S133U1axZABR41Lvj0HrDR50LyvVyE0uAqioVKkDCXc0FQA7QhOLMqlSgQLlecRVUILWkFKSzGsh210tKB2kHS7jr5eQ96uiqBtqmU6mde3g6kKFbUXtoxaPezYYGhrW1//8DAA "APL (dzaima/APL) – Try It Online") Uses `⎕IO←0` (0-indexing). The function effectively takes the line, calculates its equation and redraws it. ## Explanation **Slope calculation:** `m←÷/(⊢/-⊃)p←⍸¯1≠⍵.mat` `⍵.mat` get the image as an integer matrix `¯1≠` check which pixels aren't white `⍸` get all the required coordinates `p←` store in p `(⊢/-⊃)` subtract the last point from the first `÷/` reduce by division --- `y x←⊃p` store the first point in y and x `P5.size←⍵.sz` set canvas size to image size --- **Draw the image:** `P5.setup←{P5.G.bg¯1⋄P5.G.ln∊{⍵,y+m×⍵-x}¨0,w.width}` `P5.setup←{...}` draw the following once: `P5.G.bg¯1` set the background to white `P5.G.ln∊{⍵,y+m×⍵-x}¨⍳101` draw lines between the following points: `{...}¨0,w.width` get the points for each x in 0-100: `y+m×⍵-x` \$y = y\_1+m(x-x\_{1})\$ `⍵,` pair the x value with that `∊` enlist so it can be drawn [Answer] # Mathematica, 125 bytes ``` ImageRotate@Image@SparseArray[Array[Floor,101,#&@@ImageLines[ColorNegate@#,Method->"RANSAC"]]+1->0,{101,101},1][[;;-2,;;-2]]& ``` --- **Explanation** `ImageLines` detect lines in the image with method `RANSAC`. We take the first detected line and convert it back to an image. The whole function takes an image as the argument and returns an image. ]
[Question] [ # Calculate the p-adic norm of a rational number Write a function or a program, that takes 3 integers `m,n,p` (where `p` is a positive prime) as input, that outputs the p-adic norm (denoted by `|m/n|_p`) as a (completely reduced) fraction. Fermat is known to have only very small margins, but what is rather unknown is that he only had a very small computer screen. So try to make the code as short as possible for it to fit on Fermat's screen! ## Definition Given a prime `p`, every fraction `m/n` can uniquely be written (ignoring the signs) as `(a/b)* p^e` such that `e` is a integer and `p` divides neither `a` nor `b`. The *p-adic norm* of `m/n` is `p^-e`. There is a special case, if the fraction is 0: `|0|_p = 0`. The output format must be `x/y` (e.g. `1/3`; for integers both `10` or equivalently `10/1` is allowed, for negative numbers there must be a leading minus e.g. `-1/3`) ## Details The program must use stdin/stdout, or just consist of a function that returns the rational number or string. You have to assume that the input `m/n` is not fully reduced. You can assume that `p` is a prime. The program has to be able to process integers between `-2^28` up to `2^28`, and should not take more than 10 seconds. Built in factorization and prime checking functionalities are not allowed, as well as built in base conversatio, and built in function that calculate the p-adic valuation or norm. # Examples (stolen from [wikipedia](https://en.wikipedia.org/wiki/P-adic_number)): ``` x = m/n = 63/550 = 2^-1 * 3^2 * 5^-2 * 7 * 11^-1 |x|_2 = 2 |x|_3 = 1/9 |x|_5 = 25 |x|_7 = 1/7 |x|_11 = 11 |x|_13 = 1 ``` # Interesting *trivia* (Not necessary to know/read for this challenge, but perhaps nice to read as a motivation.) (Please correct me if I use the wrong words, or something else is wrong, I am not used to talking about this in english.) If you consider the rational numbers as a field, then the p-adic norm induces the p-adic metric `d_p(a,b) = |a-b|_p`. Then you can [*complete*](https://en.wikipedia.org/wiki/Complete_metric_space) this field with regard to this metric, that means you can construct a new field where all cauchy sequences converge, which is a nice topological property to have. (Which e.g. the rational numbers do not have, but the reals do.) These *p-adic numbers* are as you might have guessed, used a lot in number theory. Another interesting result is [Ostrowski's theorem](https://en.wikipedia.org/wiki/Ostrowski's_theorem) which basically says, any absolut value (as defined below) on the rational numbers is one of the following three: * The trivial: `|x|=0 iff x=0, |x|=1 otherwise` * The standard (real): `|x| = x if x>=0, |x| = -x if x<0` * The p-adic (as we defined it). [An absolute value](https://en.wikipedia.org/wiki/Absolute_value_%28algebra%29) / [a metric](https://en.wikipedia.org/wiki/Metric_space) is just the generalization of what we consider a *distance*. A absolute value `|.|` satisfies following conditions: * `|x| >= 0 and |x|=0 if x=0` * `|xy| = |x| |y|` * `|x+y| <= |x|+|y|` Note that you can easily construct metrics from absolute values and vice versa: `|x| := d(0,x)` or `d(x,y) := |x-y|`, so they are almost the same if you can *add*/*substract*/*multiply* (that is in integral domains). You can of course define a metric on more general sets, without this structure. [Answer] # Julia, ~~94~~ ~~80~~ 75 bytes ``` f(m,n,p)=(k=gcd(m,n) g(m)=m%p>0?g(m÷p)p:1 m!=0?print(g(n÷k),/,g(m÷k)):0) ``` Note: using linefeeds in place of semicolons for readability - will work same either way. This is quite simple - the `g(m,n)` function uses recursion and remainder (`%`) to extract the `p^n` factor from input `m`, with `n=1` as default and then multiplied by `p` on each step of the recursion, so that the output will be `p^n`. The code applies that to `n/gcd(m,n)`, and then to `m/gcd(m,n)` to obtain the appropriate expression. `k=gcd(m,n)` is used to avoid calculating the `gcd(m,n)` twice, to save characters. `m!=0` is a test to handle the case where `x=0`. The output is of the form `N/1` or `1/N` as appropriate, where `N` is `p^e`. [Answer] ## J, ~~35~~ 34 bytes ``` (,'/'&,)&":/@(%+./)@(]<.^+.|.@])x: ``` This is a binary verb that takes the prime `p` as its left argument, and the array `m n` as its right argument. It always prints the slash `/`, and returns `0/1` if `m = 0`. Use it like this: ``` f =: (,'/'&,)&":/@(%+./)@(]<.^+.|.@])x: 5 f 63 550 25/1 ``` ## Explanation The `x:` turns on extended precision, since we're handling very large numbers. The rest of the code works as follows: ``` (,'/'&,)&":/@(%+./)@(]<.^+.|.@]) ^ Power: this gives the array p^n p^m +. Take element-wise GCD with |.@] the rotated array n m; this gives the largest powers of p that divide n and m <. Take element-wise minimum with [ The array m n to handle the m=0 case correctly %+./ Divide this array by its GCD to get it to lowest terms &":/ Convert both elements to strings ,'/'&, Insert the slash '/' between them ``` [Answer] # CJam, 42 bytes ``` q~)\_:*g_sW<o@*28#f{{{_@\%}h;}:G~}_~Gf/'/* ``` THis finishes with an error (after printing 0) for input 0. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~)%5C_%3A*g_sW%3Co%40*28%23f%7B%7B%7B_%40%5C%25%7Dh%3B%7D%3AG~%7D_~Gf%2F'%2F*&input=%5B550%2063%207%5D). [Answer] # [Stax](https://github.com/tomtheisen/stax), 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éE▌ΦΔΘao£╙)ΩuÅI~AAε3∞xC█&½╤%╩▌ïö ``` [Run and debug it](https://staxlang.xyz/#p=8245dde8ffe9616f9cd329ea758f497e4141ee33ec7843db26abd125cadd8b94&i=[63%2F550,2]%0A[63%2F550,3]%0A[63%2F550,5]%0A[63%2F550,7]%0A[63%2F550,11]%0A[63%2F550,13]%0A[0%2F1,2]%0A[-63%2F550,2]&a=1&m=2) Should be able to make it shorter. The native support for fraction by Stax is quite neat. ASCII equivalent: ``` hY{y:+y|aEGsG-ys|**}0?}0{^scxHY%Cy/sWd ``` ]
[Question] [ You work for a company that wants to make a user-friendly calculator, and thus you have been tasked with adding the ability for users to use "numerical shorthands," that is, letters that represent numerical values, such as `k` for `1000`. Because your company wants to save money on storage in said calculators, you must minimize your code as much as possible to reduce the cost of storage. --- ## Your Task You are to create a function that either reads an expression as input from STDIN or takes it as a parameter and returns its evaluation or prints it to STDOUT. ## Some Clarification Let me do some definitions. First off, we have the input, which I call an expression. This can be something like the following: ``` x + y / z ``` Within this expression we have three numbers: `x`, `y`, and `z`, separated by operators (`+` and `/`). These numbers are not necessarily positive integers (or even integers). What complicates things is when we have to evaluate shorthands contained within numbers. For example, with ``` 2k15 ``` for purposes of evaluation, we split this up into three numbers: `2`, `1000` (which is `k`), and `15`. Then, according to the rules, we combine them to obtain ``` 2*1000 + 15 = 2015 ``` Hopefully this makes it a bit easier to understand the following rules. ## Rules N.B. Unless specified otherwise, you can interpret the word "numbers" or its synonyms to include shorthands. 1. The following constitutes the numerical shorthands your function must be able to process: `k, m, b, t, and e`. `k, m, b, and t` correspond to the values `1000, 1000000, 1000000000, and 1000000000000` respectively (one thousand, one million, one billion, and one trillion). The `e` shorthand will always be followed by another number, `n`, and represents `10^n`. You must allow for numerical shorthands to be present in `n` and present before `e`. For example, `kek` evaluates to `1000*10^1000`. 2. For simplicity's sake, if a number has the shorthand `e` in it, it will only be used once. 3. Any number (*shorthands included*) before a shorthand is multiplied by it. e.g. `120kk` would be evaluated as `120 * 1000 * 1000`. If there is no number before it, you must assume that the number is 1 (like how you might, in mathematics, treat a variable `x` implicitly as `1x`). e.g. `e10` evaluates to `10^10`. Another example: `2m2k` evaluates to `2*1000000*2*1000` (nothing is added to it). 4. Any number (shorthands do not apply) following the **last shorthand** in a number containing a shorthand is added to it. e.g. `2k12` would be evaluated as `2*1000 + 12`. The exception to this is if the shorthand `e` is used, in which case the number (*shorthands included*) following `e` will be treated as `n` and evaluated as `10^n` (see the first rule). 5. Your function must be able to process the operators `+, -, *, and /` which are addition, subtraction, multiplication, and division respectively. It may process more, if you so desire. 6. Operations are evaluated according to the [order of operations.](https://en.wikipedia.org/wiki/Order_of_operations) 7. Numbers in shorthands are not only integers. `3.5b1.2` is valid and is to be evaluated as `3.5*1000000000 + 1.2 = 3500000001.2` 8. Built-ins are not allowed, if they exist for this sort of thing. The exception that I'll add would be if your language automatically converts large numbers to scientific notation, in which case that is admissible for your output. 9. Shortest code in bytes wins, standard loopholes applying. ## Input The input will be an expression with each number and operator separated by spaces. Numbers may or may not contain a shorthand. A sample is shown below: ``` 10 + 1b - 2k ``` ## Output Your function must output the evaluation of the expression as a number. It is admissible to use scientific notation if the output would be too large to display. You must have at least three decimal places if the number is not an integer. It is admissible if you retain these decimal places if the number is an integer. ## Test Cases Input ``` t ``` Output ``` 1000000000000 ``` --- Input ``` 1 + 4b / 10k11 ``` Output ``` 399561.483 ``` --- Input ``` e2 + k2ke-1 - b12 ``` Output ``` -999799912 ``` or ``` -999799912.000 ``` --- Input ``` 142ek12 ``` Output ``` 142e1012 ``` or ``` 142.000e1012 ``` --- Input: ``` 1.2m5.25 ``` Output: ``` 1200005.25 ``` ## Final Notes This is my first challenge posted (with some help from users on the sandbox). If anything is unclear, make it known to me and I will do my best to clarify. [Answer] # Python 2, 553 bytes ``` import sys a=lambda i:lambda j:j*10**i d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)} e='e' o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j} r=[e,'*','/','+','-'] x=0 y=k=b='' z=[] q=lambda i,j:float(i or j) for l in ''.join(sys.argv[1:]): if l in d:x,y=d[l](q(x,1)*q(y,1)),b elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=0,b elif k==e:y+=l elif l in o:z.extend([x+q(y,0),l]);x,y=0,b else:y+=l k=l z.append(x+q(y,0)) for m in r: while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])] print repr(z[0]) ``` This question looked a little unloved and seemed fun, so I gave it a shot. I've never done code golf before, so there's probably a lot that can be improved, but I gave it my best based on my knowledge of the language. An equivalent solution is possible in Python 3 at the cost of one extra byte: `print repr(z[0])` -> `print(repr(z[0]))`. Usage is something along the lines of ``` python2 ShorthandMath.py <equation> ``` i.e. ``` python2 ShorthandMath.py e2 + k2ke-1 - b12 ``` outputs ``` -999799912.0 ``` Input for how to improve this would be much appreciated. If there is sufficient interest, I can ungolf and comment the program, but most of it pretty legible already (a concerning fact in code golf). It should be noted that the program breaks with the example `142ek12` because that value is ludicrously large and the program overflows. To compensate, the following is slightly longer, but can theoretically handle anything thrown at it due to use of the built in arbitrary precision library. Syntax is identical. # Python 2, ~~589~~ 588 bytes (arbitrary precision) ``` import sys from decimal import* a=lambda i:lambda j:j*10**i d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)} e='e' o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j} r=[e,'*','/','+','-'] x=c=Decimal(0) y=k=b='' z=[] q=lambda i,j:Decimal(float(i or j)) for l in ''.join(sys.argv[1:]): if l in d:x,y=d[l](q(x,1)*q(y,1)),b elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=c,b elif k==e:y+=l elif l in o:z.extend([x+q(y,0),l]);x,y=c,b else:y+=l k=l z.append(x+q(y,0)) for m in r: while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])] print z[0] ``` ]
[Question] [ I designed a language in which pointer arithmetic is the main tool of programming. Here are some examples. ``` (print 0 to 8) =9[>1=9-*-1.>-1-1] (print 1 to 10 with spaces in between, character literal extension used) =1[.>1=10-*-1[>1=' '!>-2+1;-2];1]='\n'! (compute the factorial of 10) =10>1=*-1-1[>-1**1>1-1]>-1. (print "hi") =104!=105! (print "hi" with extension for arrays) ={104,105,0}[!>1] (print "Hello, world!" with extension for C-style string literals) ="Hello, world!"[!>1] ``` ## Language Specification The language definition is very simple. You will understand very easily if you have experience with C, but I will not assume so. Every program in PointerLang has *the pointer*, in short, `P`. You can think it as a hidden single global variable, which you can control by using *commands*. `P` initially *points to* the beginning of *the array*. Every element in the array has the type `int` which is a 32-bit signed integer. For C programmers ``` int32_t *P = malloc(1000); ``` In PointerLang, there are *commands* and *arguments*. An argument is an `int` which must come after a command. All commands are executed from left to right unless specified otherwise. The following is the list of commands. `A` stands for argument. A command without `A` means it does not take an argument. A command with `A` must take an argument. Inside the parentheses is the equivalent C expression. * `=A` : assign A at P (`*P = A`) * `+A` : add A at P (`*P += A`) * `-A` : subtract A at P (`*P -= A`) * `*A` : multiply by A at P (`*P *= A`) * `/A` : divide by A at P (`*P /= A`) * `>A` : move `P` by `A` (`P += A`) * `.` : print the integer at P (`printf("%d", *P)`) * `!` : print the integer at P as ASCII (`printf("%c", (char)*P)`) * `[` : if the value at P is 0 go to the command after the next `]` (`while (*P) {`) * `]` : go to the previous `[` that is the matching pair (`}`) * `;A` : if `A` is positive, go to the command after the `A`th `]` coming next; if `A` is negative, go to the `A`th `[` coming before; if A is 0, do nothing. An integer literal is an argument. The following two are special arguments that take an argument. * `-A` : evaluated as an argument having the same absolute value as `A` and the opposite sign of `A`; unary minus * `*A` : move `P` by `A`, evaluate the value at `P`, move `P` by `-A` (`P[A]`) All comments in PointerLang are between parentheses `(comment)`. ## Example Program This program which counts from 1 to 10 is a good example to complete your understanding. ``` (print 1 to 10 with spaces in between) =1[.>1=10-*-1[>1=32!>-2+1;-2];1]=10! ``` Be careful when you interpret `-*-1`. `-` is the command and `*-1` is the argument. An integer literal effectively indicates the end of a command-argument pair. It can be translated to C with 1-to-1 correspondence as ``` int main(void) { int32_t *P = malloc(1000); *P = 1; // =1 l: while (*P) { // [ printf("%d", *P); // . P += 1; // > 1 *P = 10; // =10 *P -= P[-1]; // -*-1 while (*P) { // [ P += 1; // >1 *P = 32; // =32 printf("%c", (char)*P); // ! P += -2; // >-2 *P += 1; // +1 goto l; // ;-2 } // ] break; // ;1 } // ] *P = 10; // =10 printf("%c", (char)*P); // ! return 0; } ``` Extensions can be applied to this language such as character literals, arrays, string literals etc, but you don't have to implement them, for simplicity. ## The Challenge You have to implement the core features detailed in the *Language Specification* section and the NOTEs below. Give it a try with your favourite programming language, writing the shortest program possible. NOTE1: The size of *the array* is undefined. But it should be big enough to solve most problems. NOTE2: Integer overflow is undefined. NOTE3: The specification only defines the result or effect of certain language constructs. For example, you don't have to exactly follow the steps in the definition of the argument `*`. NOTE4: ~~Any characters that are not commands, arguments, or comments~~ Whitespaces are ignored. `=104!=105!` is as same as `= 1 0 4! = 1 05 !` for example. NOTE5: Comments are not nested. `((comment))` is a syntax error. NOTE6: I've made a breaking change to fix a hole in my language. The `~` command is now unused and `;` always takes an argument. NOTE7: Every integer literal is decimal. [Answer] # C 406 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` #define L strtol(I++,0,0) #define A*I==42?I++,P[L]:L #define F(a)-91-a|i;i-=*I-93+a?*I==91+a:-1);} i,c;char*I;X[999],*P=X;Y(){for(;*I++F(2)B(){for(i=!--I;*--I F(0)main(j,a)int**a;{for(I=a[1];j=*I++;printf(j-4?j+9?j==19?*P=A:j==1?*P+=A:j==3?*P-=A:!j?*P*=A:j==5?*P/=A:j==20?P+=A:j-17?j-51?j-49?I=j+2?I:index(I,41)+1:*P||Y(i=1):B():({for(c=A;c;c+=c<0?:-1)if(i=c<1)B();else for(;*I++F(2)),"":P:"%d",*P))j-=42;} ``` [Try it online!](https://tio.run/##VZBNa@MwEIbv/RWKS0EfVutxUhZJVUX2UDDkkGOL8UGrKK1E65TE0ELT3@4dJ7sLexke5p2vd4J8DmEcLzdxm/pIVuQw7IfdK22EKKuyYhd/lSVvrF3UbhLW7arTq3/SA/VMKpD@mEySljdSzYV3U4MC4bUEZr4vUhlMePF73pjHVinVlXxtH80TZV/b3Z4ajpMfaM1@/kkkO5OyMRwDbqjYm089zaVnqR849@ZU1FjfQmeynbrN@x61Lc1y4bJQLlsLyuGWpZ4QSZxxjigRZxmBn3O3iDdnrCt3rpTww2V5CxgWyjU2C/SvU7@Jn7QpF8AEaL4@Hp/wWGAaL9f0dFawS4NuhQ13lZv8py2WhDuY3Jn4eojkP8@sLAq91sXVpsCvMJYlvtp8j@NY0JMpAmTYEajIRxpeyOHdh3ggqSe/4vARY88stNf3YKGSXEKLNK9n97IWYGTdGehQmRW/AQ "C (gcc) – Try It Online") and the slightly less golfed version of my original answer: ``` #include <stdio.h> #include <stdlib.h> #define L strtol(I++,&I,10) #define A *I=='*'?I++,P[L]:L int X[999],*P=X; int main(int i, char *a[]) { char* I=a[1]; while(*I) { switch(*I++) { case '(': while(*I++!=')'); break; case '.': printf("%d",*P); break; case '!': printf("%c",(char*)*P); break; case '[': if(!*P) for(i=1;*I++!=']'||i;) { if(*I=='[') i+=1; if(*I==']') i-=1; } break; case ']': for(--I,i=0;*--I !='['||i;) { if(*I==']') i+=1; if(*I=='[') i-=1; } break; case '=': *P=A; break; case '+': *P+=A; break; case '-': *P-=A; break; case '*': *P*=A; break; case '/': *P/=A; break; case '>': P+=A; break; case ';': for(int c=A; c; c+=c<0?1:-1) { if(c>0) for(i=0;*I++!=']'||i;) { if(*I=='[') i+=1; if(*I==']') i-=1; } else for(--I,i=0;*--I !='['||i;) { if(*I==']') i+=1; if(*I=='[') i-=1; } } } } return 0; } ``` [Answer] # JavaScript (ES6) - 560 bytes Uses `prompt()` for input and `alert()` for output. It could be shortened if `alert()` was called for every character instead but I decided it would be better to buffer the characters so they could all be displayed at once. ``` b=[],d=0,e=[],f=0,g="",h="",k=prompt().replace(/(\s+|\(.*\))/g,""),l=0;n=()=>{m=g;if(m&&(a=m.substr(1),c=m.charAt(),a="*"==a.charAt()?b[d+parseInt(a.substr(1))]:parseInt(a),"["==c&&(b[d]?e.push(f-1):l++),"]"==c&&l&&(0<l&&(f=e.pop()),0>l&&(l=-l),l--),!l&&("="==c&&(b[d]=a),"+-*/".includes(c)&&eval("b[d]"+c+"=a"),">"==c&&(d+=a),"."==c&&(h+=b[d]),"!"==c&&(h+=String.fromCharCode(b[d])),";"==c&&(0<a&&(l=-l-a),0>a))))for(i=0;i<-a;i++)f=e.pop()} for(f=0;f<k.length;f++)0<f&&"=+-*/>.![];".includes(k[f])&&k[f-1].match(/[0-9.!\[\]]/)&&(n(),g=""),g+=k[f];h&&alert(h); ``` ]
[Question] [ Today your goal is to decrypt a secret message using [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard). Given a ciphertext and key you will decrypt and print the message. --- 1. Your program may be in any language. It will be run with input on stdin, and its output on stdout will be checked for correctness. 2. The first line of input on stdin will be the 16 byte key, encoded in hexadecimal. The second line of input on stdin will be the 16 byte ciphertext, encoded in hexadecimal. 3. The output of the program must be the 16 byte message after decrypting the ciphertext using AES-128 with the given key. You must output the result interpreted as ASCII octets. You may assume that any result is valid ASCII after decrypting. 4. You may not use any library/built-in features that implement AES. You may use such features to convert between hex/binary/ASCII encodings. Shortest code in bytes wins. Example input and output: ``` bd8ab53f10b3d38576a1b9a15cf03834 02c0ee126cae50ba938a8b16f0e04d23 ``` > > Attack tomorrow. > > > And another: ``` f4af804ad097ba832906db0deb7569e3 38794338dafcb09d6b32b04357f64d4d ``` > > Congratulations. > > > [Answer] ## Python, 661 chars ``` R=range I=lambda x:[int(x[2*i:2*i+2],16)for i in R(16)] k=I(raw_input()) c=I(raw_input()) P=[] x=1 for i in R(512):P+=[x];x^=x*2^(x>>7)*0x11b S=[255&(99^j^(j>>4)^(j>>5)^(j>>6)^(j>>7))for i in R(256)for j in[(P[255-P.index(i)]if i else 0)*257]] for r in R(10): for i in R(4):k+=[k[-16]^S[k[-3-(i>2)*4]]] k[-4]^=[1,2,4,8,16,32,64,128,27,54][r] for i in R(12):k+=[k[-16]^k[-4]] for r in R(11): c=[x^y for x,y in zip(k[160-16*r:],c)] if r>9:break for i in[0,4,8,12]*(r>0):c[i:i+4]=[x^y^z^w for j in R(4)for x,y,z,w in[[P[a+P.index(v)]if v else 0 for a,v in zip((2*[104,238,199,223])[3-j:],c[i:i+4])]]] c=(c*13)[::13];c=map(S.index,c) print''.join(map(chr,c)) ``` `k` is the key, `c` is the ciphertext. I build P, the powers of 3 in the field, then `S`, the sbox. Then `k` is extended with the key schedule. Finally we do the AES decryption. Mixcolumns is the hard phase, all the other phases are pretty straightforward. ]