text
stringlengths
180
608k
[Question] [ Your task is to create a program where if any one character is deleted, it will detect which character was deleted and then re-insert the deleted character in its own source file. For instance, if your program is `RadiationHardened` and it is modified to `RadiaionHardened`, then your program must output that the 5th byte (0-indexed) was modified and then the program source must be `RadiationHardened` immediately after execution. ## Notes and rules * You may assume that exactly one character was deleted in the source code before execution. Behavior for the unmodified program is undefined. * You may assume the changed byte will be deleted, not transposed, inserted, or replaced. * In the case of a run of multiple of the same character, you may report either the first or the last index of the run, but be consistent about which you use. For example `baaad` being deleted to `baad` can report either 1 or 3 (zero indexed), but must be the same throughout the entire program. * You do not need to write out the entire source to its own file. You need only re-insert the deleted byte. * Unlike the typical rules for radiation-hardened quines, detecting the changed byte from reading the program's own source code is fair game. * You can output the changed byte index through any reasonable format. Be consistent about whether it is 0-indexed or 1-indexed or any other notation. You may even output a number within a template string. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program wins. Good luck! EDIT1: changed requirement from replacement to deletion EDIT2: added rule for runs of duplicates [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~344 296~~ 248 bytes ``` 20020xxnngg33%%!!2200gg''00--3300gg33%%!!4400gg55%%!!22kk++55##rr55kk::00gg\\11pp00gg\\11++11pp22++00::pp00gg\\11++00gg--!!zz!!22**++00::gg00gg8844**--!!55++jj..''gg::00rr00::gg\\--..''220011''0011::''002211''223311''00441144kkppgg11001100::99oo@@ ``` [Try it online!](https://tio.run/##TY7BCsMgEETv/QsJQVAM7qqQeMqHeCqkCxESEQohP2@7SKGnnX0zDPPcXu@DNrPMraG1aK/rOIicG0ch8EuIpLTWGOdYd@496xB6JmetQxiGWkPIOUb2UgIo5ae05g9Ra2tj/OesjBHivrlJqZ4gYj7P3ivFbgha7/s0SUnE/bX2VErGMOWdALwTIEa@iPwjOte59wDe51wKEQDnuGFZznNdH619AA "Befunge-98 (FBBI) – Try It Online") [Verification!](https://tio.run/##dVFdj9owEHzGv8IEISeYhDgfElhCOrXv/QMHqgI4xpdiR04ox1X97dR7SYCH61N2Z2bHO5v62h6NTm83daqNbbFpUF811wah2hppixNeQxs17UHpyIri4AeoVL@ELk7Ccd7IA6nSrU@@XVuB9@asW07m2En83iMSem8OwidFs1eKBEHQj/R8gNBBlNie9c8euTMcjS6qPWJTO7vh3TkmFxLgosGl40dldLGqFQ@3kRXt2WqXKKq7QW9h6naxE@VZSxGuloud0otyt1OY/Blc/xIvGBKiiTm3Lt5XK6FJn/eHwftj4QwhrtPfmc/aRRS/vx8L62wIQcp9YlQaixVWGluY859uFEBUVeK@fVVbPF7jwQNi/nejV6629D5HGd@6E4y6VbzpAfvTJuDe1Ffzh3kwd3ZzBcKiaYT76cPieL3GysFfnJ3Yp6sPc2V/M5jr/T9fv4d/POoCYrrGDN1uSRwn8fu71lKm6XQ6HicOkZKQOA7DNIW6w7MM6jzvNFVFaZ5PJtbmeVVxDtxmw1hdDxWl0CUJpXHM@TMOVRiOxx8f4DSbdQopAV8us2w2AzbPKX17iyJCpAR/azvVZhOGgMKejMGejHEO3ySBPknStMOzjLEsq6q6lpIx0IHDamXMywv6Bw) Befunge-98 is the first esoteric language that I could find that was both 2D and had file output. This is a full solution (with a trailing newline) stored in a file named as a tab character. It outputs as 0-indexed, and outputs the first index in a run of characters (though there's only ever pairs). There's a few golfs to be made, ~~especially as there are 15 no-ops in the code~~, now just one no-op! I will be working on making this shorter, with the goal of getting to or below 200 bytes. [Answer] # [Unefunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 118 bytes ``` 22xx00##rr33kk::gg\\11--pp22++00ppgg\\11++gg--!!zz!!22**--00gg::gg8844**--!!22++jj##''rr++..gg''2200pp0011--00::99oo@@ ``` [Try it online!](https://tio.run/##JYxBCoQwEATfEnIIOIy0o4ckJx/i1R1Q0CEguH4@kt1bd1HUdayf69CVU2T7/matIvcNeF/KOO57zqrLMgzMZiJEgNmfEKkyO/c8zol0HTOg2vwYp6n9xom2zfsQSiHqe9UQRFoDaE0g55TOc55rfQE "Unefunge-98 (PyFunge) – Try It Online") [Verification!](https://tio.run/##dZLBjpswEIbP8VNMQJFhCYiQPSRISNv2VKnqodfdqHLBgHcb2zJmk2zVZ8@OE0i2UnrCeP75Zv7x6INtlVwej2KrlbGgOjKcukNHiDaqMWwLhftNOlsJmRjOqiAktfjNJdtyjHkTz0mFtAH9fLAcStVLm9M5oCQYGAmXpap4QFlXCkHDMBxShnhISMVrML38OdxcIjmZ7IRtQWnEjXXnQHc0BNZBndfJzgjLr6iJ4bY3Eu0k@pzl6UPdy4ZDHKONYr2CeAH0z0j7S71wdEZ81Vu0dasV4g8@vysoW4ZAZxP1l8jpjNb465eWGcRQSgR@UuLDN6U0qFdugLOydQDDSssNqZUBAUKCccjgw9hC596HrzXYll8zQHQglQXN3KPVwFy37nBRdGQiahgoj2ID0wLGrhCJzB@Y4aDCGFYJZnk1yjH83xE85mITXbDRIt/guCdn796sgmDWhbk3C8T8WjucI24uwlPZT13HsWnbMnsqjyGNxdDQqRlZ8b0z8o9dTGTntHHEUBQgbvLck0KLe/GLcxwo10wYXqH0xg5RM64QxscS9bAIrsR1IB9e9GoMZwxRAQtyPGbZfp@mvm/McvnykudN8/S0WMSx1lkWRWmq9fkmipomjqfTt7fpNMvu7uI4TZvG6Ver@3v37@6j6PnZ9yk1JoqSpGkozTLHSFPHTNM8X6@Venh4Bw) While golfing my Befunge-98 answer, I realised I could save some bytes by porting it over to Unefunge, since I would only have to worry about the one dimension rather than the two. This also opened up a lot of possible shortcuts and golfs, which made the new solution much *much* smaller. ### Explanation (de-duplicated): ``` 2x Set the delta of the movement to 2 This means the pointer moves 2 cells every step This will also initialise a counter as 2 (unless a 2 has been removed) 0 Create the cell counter (This will be stored at cell 0) #r Enter the loop 3k: Create 3 more copies of the counter g Get the cell at the counter's position \1-p Put it in the cell before that position 2+0p Add 2 to the counter and put it in cell 0 g Get the cell at the counter's position \1+g Get the next cell -!z!2* If they are identical, push two, else 0 -- Subtract it from the total counter 0g:g84*-! If the next character is a space 2+j r Exit loop j#' Else jump back to the start Once the loop is over + Add the negative counter to the total counter . And print '20p Replace the 2 in cell 0 that was overwritten o Write to a file named 9 Tab 01- The cells from -1 to g The total number of cells @ And exit the program ``` ]
[Question] [ ## Introduction: At home we have a clock that strikes the stated amount at each hour, but also strikes once at every half-hour. So from 0:01 to and including 12:00 it strikes in this order: ``` 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9, 1, 10, 1, 11, 1, 12 ``` ## Challenge: Given an integer `n`, output a list of time-frames in which the total strikes are equal to `n`. In addition, always start at least 1 minute before this time-frame and end at least 1 minute after this time-frame (and at most 29 minutes). For example, if the input is `n=8`, the output could be: ``` [00:59-03:01, 01:29-03:31, 02:59-04:01, 05:29-06:31, 06:29-07:01, 06:59-07:31, 07:59-08:01] ``` For which these time-frames have the following sums, all equaling `8`: ``` [1+1+2+1+3, 1+2+1+3+1, 3+1+4, 1+6+1, 1+7, 7+1, 8] ``` ## Challenge rules: * Output is flexible. You can output as Time (or Date/DateTime) objects, timestamps, strings (with or without leading zeroes), decimals with `.29`/`.31`/`.59`/`.01` (i.e. `0.29-3.01` instead of `00:29-03:01`), etc. As long as it's clear it's before and after the time-frame. In addition, you can choose the amount yourself. In all my examples I use 1 minute, but you can also choose 5 minutes, 15 minutes, etc. This also means you can use `.4`/`.6`/`.9`/`.1` (i.e. `0.4-3.1` instead of `00:24-03:06`) for example. The list is also flexible. Can be a list/collection, array, delimiter-separated string, printing per line to STDOUT, etc. **Please state which output choice you've made.** Note: You are not allowed to output the sums of the time-frames like above, this is only mentioned as clarification. You must output the time-frames, including slightly before and after it. * The strikes do wrap around from `12:00` to `00:30`. So if `n=14`, two of the time-frames are `11:29-00:31` and `11:59-01:01`. * Input will be in the range `1 <= n <= 90`, where 90 is the total sum of all possible strikes. * The time-frames you return can be in any order. ## 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, 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. * Also, please add an explanation if necessary. ## Test cases: (all using 1 minute before / after the time-frames and leading zeroes) ``` Input: 8 Ouput: [00:59-03:01, 01:29-03:31, 02:59-04:01, 05:29-06:31, 06:29-07:01, 06:59-07:31, 07:59-08:01] Input: 14 Output: [00:29-04:01, 00:59-04:31, 02:59-05:01, 04:29-06:31, 05:59-07:01, 11:29-00:31, 11:59-01:01] Input: 90 Output: [00:29-00:01, 00:59-00:31, 01:29-01:01, 01:59-01:31, 02:29-02:01, 02:59-02:31, 03:29-03:01, 03:59-03:31, 04:29-04:01, 04:59-04:31, 05:29-05:01, 05:59-05:31, 06:29-06:01, 06:59-06:31, 07:29-07:01, 07:59-07:31, 08:29-08:01, 08:59-08:31, 09:29-09:01, 09:59-09:31, 10:29-10:01, 10:59-10:31, 11:29-11:01, 11:59-11:31] Input: 1 Output: [00:29-00:31, 00:59-01:01, 01:29-01:31, 02:29-02:31, 03:29-03:31, 04:29-04:31, 05:29-05:31, 06:29-06:31, 07:29-07:31, 08:29-08:31, 09:29-09:31, 10:29-10:31, 11:29-11:31] Input: 2 Output: [00:29-01:01, 00:59-01:31, 01:59-02:01] ``` [Answer] # JavaScript (ES6), 104 bytes Prints time intervals in `H.MM,H.MM` format. ``` F=(n,f=0,s=n,t=f++)=>t<f+23?F(n,f,s-=t&1||t/2%12+1,++t,s||alert([f/2%12+.01,-~t/2%12+.01])):f<24&&F(n,f) ``` [Try it online!](https://tio.run/##Zc7BDoIwDAbgO0/RgwLLBrLJQY3DGy@hJhJlRiXD0MaL6KtjREJUjv375W/P2S3DfXW6UmDLQ940qfatMDoSqK0gbThnOqGl4Wq6St8rgYEmV9Y1TdRYKi4F5ySwrrMir8hfm08cRlIET@qHLWMLs1Sx67YtrGk5aEDQCexLi2WRh0V59HejOz52zHG@QwBvBkjV6ZKjBwxcSP0Z@yHexsq4Nx8i44GZR39mHg17OuJBd0oOiPr/RrHmBQ "JavaScript (Node.js) – Try It Online") Uses essentially the same algorithm as the non-recursive version below. --- # Non-recursive version, 117 bytes Outputs a space-delimited string of time intervals in `H.MM,H.MM` format. ``` n=>[...Array(24)].map((_,f,a)=>a.map(_=>(s-=t++&1||t/2%12+.5)||(r+=[-~f/2%12+.01,-~t/2%12+.01]+' '),s=n,t=f),r='')&&r ``` ### Test cases ``` let f = n=>[...Array(24)].map((_,f,a)=>a.map(_=>(s-=t++&1||t/2%12+.5)||(r+=[-~f/2%12+.01,-~t/2%12+.01]+' '),s=n,t=f),r='')&&r console.log(f(8)) console.log(f(14)) console.log(f(90)) console.log(f(1)) console.log(f(2)) ``` ### Commented ``` n => // n = input [...Array(24)].map((_, f, a) // FOR f = 0 TO 23: => a.map(_ => // FOR t = f TO f + 23: ( // update s s -= // by subtracting: t++ & 1 || // - 1 if t is odd (half hour) t / 2 % 12 + .5 // - the current hour if t is even ) || ( // if s is equal to zero: r += [ // update the result string by appending: -~f / 2 % 12 + .01 // - the formatted 'from' time , // - a comma -~t / 2 % 12 + .01 // - the formatted 'to' time ] + ' ' // and a padding space ), // inner map() initialization: s = n, // - s = target number of strikes t = f // - 'to' time = 'from' time ), // end of inner map() r = '' // start with r = empty string ) // end of outer map() && r // return r ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~62~~ 59 bytesSBCS Full program body. Prompts for `n`. Prints list of two-element lists using decimal hours. ``` ∪(⎕=∊l+/¨⊂48⍴∊1,¨⍳12)/(¯.1 .1+⊃,⊢/)¨⊃,/(l←⍳48),/¨⊂.5×48⍴⍳24 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9uKQoMzsVyFql8ahvqu2jjq4cbf1DKx51NZlYPOrdAuQb6gC5vZsNjTT1NQ6t1zNU0DPUftTVrPOoa5G@Jkhls46@Rs6jtglARSYWmjoQ3Xqmh6dDTOjdbGQCsum/AhhALOSy4ELhGpqg8i0N0ORRuUYA "APL (Dyalog Unicode) – Try It Online") `⍳24` **ɩ**ndices 1…24 `48⍴` cyclically **r**eshape to length 48, i.e. 1…12,1…12 `.5×` multiply a half by that `⊂` enclose (to use this entire array as right argument for each left argument) `(`…`),/¨` for each of the following, return all the sub-lists of that length:  `⍳48` **ɩ**ndices 1…48  `l←` store in `l` (for **l**engths) Now we have all the possible lists of runs of times for each possible run-length. `,/` concatenate (lit. concatenation-reduction) the lists of sub-lists `⊃` disclose (because the reduction reduced the rank from 1 to 0) `(`…`)¨` apply the following function to each:  `⊢/` the last (lit. right-reduction) element (the end time)  `⊃,` prepend the first element (the beginning time)  `¯.1 .1+` add negative and positive tenths to those `(`…`)/` filter those begin-end pairs with:  `⍳12` **ɩ**ndices 1…12  `1,¨` prepend a `1` to each  `∊` **ϵ**nlist (flatten)  `48⍴` cyclically **r**eshape to length 48, i.e. 1,1,1,2…1,11,1,12  `⊂` enclose (to use this entire array as right argument for each left argument)  `l+/¨` for each of `l` (1…48) return the sums of all the sub-lists of that length  `∊` **ϵ**nlist (flatten) `⎕=` compare numeric input to that `∪` return just the unique elements (begin-end pairs) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 34 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ∪12|.4 .1∘+¨.5×⍸⎕=⍉∘.-⍨+\,⍪⍨1,⍪⍳12 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYZcjzra0/4/6lhlaFSjZ6KgZ/ioY4b2oRV6poenP@rdAVRm@6i3Eyimp/uod4V2jM6j3lVAhiGE3mxoBNTa/j@Ny4IrjcvQBEhYGoBYQGwEAA "APL (Dyalog Classic) – Try It Online") This solution uses `⎕io←1` (1-based indexing). From right to left: `⍳12` is `1 2 3...12` `⍪` turns it into a tall thin 12x1 matrix `1,` adds a column of 1s to the left `⍪⍨` concatenates the same matrix vertically, so it's now a 24x2 matrix `,` flattens the matrix in row-major order, it becomes a vector of size 48: `1 1 1 2 1 3...1 12 1 1 1 2...1 12` `+\` partial sums: `1 2 3 5 6 9...` `∘.-⍨` the differences between each pair of elements, a 48x48 matrix `⍉` transpose `⎕=` a 48x48 boolean matrix with 1s wherever the evaluated input (`⎕`) occurs `⍸` the pairs of coordinates of where the 1s are `.5×` halve them `.4 .1∘+¨` add 0.4 to the first and 0.1 to the second coordinate in each pair `12|` modulo 12 `∪` unique [Answer] # [Python 3](https://docs.python.org/3/), ~~118~~ 116 bytes ``` lambda n:[(a/2+.4,b%24/2+.1)for a in range(24)for b in range(48)if sum((sum(zip([1]*12,range(1,13)),())*2)[a:b])==n] ``` [Try it online!](https://tio.run/##RYwxDsIwEAR7XnEN0l04AXZchEh@iXFhCwwnEScKoYDPGwwFze5qVprpuVzH3JZkj@UWhngKkHuHYac3W8NxrU1ditI4QwDJMId8OaM2XxL/xHQkCe6PAbHGSyZ0yjdK8@9XrFoiRqJGkwt99GRt9qVqpGo6BmUYDvtPM@h@BTDNkhcUhoRCVN4 "Python 3 – Try It Online") A timeframe is represented as `(t1, t2)`, `t1` and `t2` being decimals representing hours. The offset is `.1` or 6 minutes. [Answer] ## Batch, 196 bytes ``` @for /l %%i in (0,1,23)do @set s=%1&for /l %%j in (0,1,23)do @call:c %%i %%j :c @set/at=%2+%1,s-=t%%2*(t/2%%12)+1,h=%1/2,i=%1%%2*30+15,t=-~t%%24/2,u=-~t%%2*30+15 @if %s%==0 echo %h%:%i% %t%:%u% ``` Explanation: `t` is the time in half hours, starting at `0` for `00:30`. The number of strikes at time t is then `1`, `1`, `1`, `2`, `1`, `3` etc. Subtracting `1` gives the sequence `0`, `0`, `0`, `1`, `0`, `2` etc. which is the integers interleaved with zeros. This can then be obtained by termwise multiplication of the sequence `0`, `0`, `1`, `1`, `2`, `2` etc. with the sequence `0`, `1`, `0`, `1`, `0`, `1` etc. Both of these sequences are readily calculated using modulo and (integer) division. It then remains to loop over all 23 possible starting times, then taking all 24 striking times and subtracting the number of strikes from the input, printing the times when the result is zero. The code falls through after the loop but no harm is done as the input cannot be more than 90. [Answer] # APL NARS, 559 bytes ``` ∇r←l w;t;i;j;c;k;m;p p←{0=2∣¯1+⍵:.01+2÷⍨¯1+⍵⋄¯0.19+2÷⍨¯1+⍵} m←{0=2∣¯1+⍵:¯.41+2÷⍨¯1+⍵⋄¯0.21+2÷⍨¯1+⍵} r←⍬⋄i←0⋄t←∊(¯1+⍳13),¨13⍴1⋄t←t,2↓t⋄k←⍴t A: j←i+←1⋄→0×⍳i≥k⋄c←0 B: c+←j⊃t⋄:if(c=w)∧(0≤(m i))∧(24≥(p j))⋄r←r,⊂(m i),(p j)⋄:endif⋄→A×⍳c≥w⋄j+←1⋄→B×⍳j≤k⋄→A ∇ ∇r←g w;v;i;k;m v←{12≤⌊⍵:⍵-12⋄⍵} i←1⋄k←⍴w⋄r←⍬ A: →0×⍳i>k⋄r←r,⊂v¨i⊃w⋄i+←1⋄→A ∇ h←g∘l ``` h(n) or l(n) returns all representative intervals in 0-24 hours that has n clock strikes. h(n) has the clock format as 0..11.0..59; instead l(n) has clock format as 0..23.0..59 test ``` h 8 0.59 3.01 1.29 3.31 2.59 4.01 5.29 6.31 6.29 7.01 6.59 7.31 7.59 8.01 0.59 3.01 1.29 3.31 2.59 4.01 5.29 6.31 6.29 7.01 6.59 7.31 7.59 8.01 h 14 0.29 4.01 0.59 4.31 2.59 5.01 4.29 6.31 5.59 7.01 11.29 0.31 11.59 1.01 0.29 4.01 0.59 4.31 2.59 5.01 4.29 6.31 5.59 7.01 h 90 0.29 0.01 0.59 0.31 1.29 1.01 1.59 1.31 2.29 2.01 2.59 2.31 3.29 3.01 3.59 3.31 4.29 4.01 4.59 4.31 5.29 5.01 5.59 5.31 6.29 6.01 6.59 6.31 7.29 7.01 7.59 7.31 8.29 8.01 8.59 8.31 9.29 9.01 9.59 9.31 10.29 10.01 10.59 10.31 11.29 11.01 11.59 11.31 h 1 0.29 0.31 0.59 1.01 1.29 1.31 2.29 2.31 3.29 3.31 4.29 4.31 5.29 5.31 6.29 6.31 7.29 7.31 8.29 8.31 9.29 9.31 10.29 10.31 11.29 11.31 0.29 0.31 0.59 1.01 1.29 1.31 2.29 2.31 3.29 3.31 4.29 4.31 5.29 5.31 6.29 6.31 7.29 7.31 8.29 8.31 9.29 9.31 10.29 10.31 11.29 11.31 h 2 0.29 1.01 0.59 1.31 1.59 2.01 0.29 1.01 0.59 1.31 1.59 2.01 l 2 0.29 1.01 0.59 1.31 1.59 2.01 12.29 13.01 12.59 13.31 13.59 14.01 ``` ]
[Question] [ My kids have an alphabet mat to play with, something like this: [![Alphabet mat](https://i.stack.imgur.com/KQVw4.jpg)](https://i.stack.imgur.com/KQVw4.jpg) After months with the tiles of the mat randomly placed, I got tired and placed all the tiles of the mat grouped by sections according to their background colors. So, if the letters represent the background color, I got a mat like this: ``` AABBCDDDE ABBCCCDEE ABCCCCDDE AACCCDDEE AAAACCCCE AAAAAACCC ``` So, for colors A, B, C, D and E there is always a way to connect all the tiles with the same background color either horizontally or vertically in the mat. That's what I call *a mat properly grouped by colors*. You can see the groups for the previous example in the following tables: ``` AA A A AA AAAA AAAAAA BB BB B C CCC CCCC CCC CCCC CCC DDD D DD DD E EE E EE E ``` Also, there is only one group for every color, so this would not be valid: ``` ABA ABA ``` Because color A tiles are not grouped in only one group. This also would not be valid because the tiles do not connect either horizontally or vertically: ``` AB BA ``` ### The challenge Given a 2-dimensional array of characters in the printable ASCII range (does not need to be a square one as long as the size of both dimensions are equal to or greater than 1), check if the array represents *a mat properly grouped by colors* (each different character in the array represents a different color). Input may be in any reasonable format as long as it represents a 2-dimensional array of characters (2D char array, array of strings of the same length, and so on), and output must be a pair of truthy and falsey values (0/1, 't'/'f', true/false, whatever as long as something is returned and the return values are consistent across inputs). *This is code-golf, so may the shortest program/function/method/lambda for each language win!* ### Examples ``` A truthy AB AB truthy AB BA falsey ABCDE truthy ABCDC falsey **::dd22 ***:d222 *:::::22 truthy $$$%%%&& $$%%&&&& &&$$$%&& falsey AABBCDDDE ABBCCCDEE ABCCCCDDE AACCCDDEE AAAACCCCE AAAAAACCC truthy AABB ABBA AAAA truthy AAAB AAAA AAAA truthy ``` ### My mat properly grouped by colors [![My mat properly grouped by colors](https://i.stack.imgur.com/8hWGA.jpg)](https://i.stack.imgur.com/8hWGA.jpg) (I still have to fix those borders...) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` 1e"G@=4&1ZI1>vzg ``` Input is a 2D char array (with rows separated by `;`). Output is `0` if input qualifies, or `1` otherwise. [Try it online!](https://tio.run/##y00syfn/3zBVyd3B1kTNMMrT0K6sKv3//2h1R0cnJ2cXFxdXdWsFdRDb2dnFFcpxBnGgMo4QNpQD5jrDOWCueiwA) Or [verify all test cases](https://tio.run/##RY@xCgIxDIZ3n0KkTaFbD6eKYps6eLODKAcKd7joJg6@fE3aXO0Qvq9/@UNf9/cz3859dtOq32/X4C5Ht/t8H3lIp3w1wQwLmtFsljz/EucE06ERFrLW@3HsOn5mSQgrez7E/EgppbUG4IARoDIAJ8SlM0RqTbShrI@ItE0EWSQJlUWKYpOirU6awpxKID/kixb8AA). ### Explanation The code essentialy checks if each char in the input has only one connected component, considering 4-connectivity (that is, no diagonals). Repeated chars are processed repeatedly (which is golfier than deduplicating). ``` 1e % Implicit input. Reshape into a row vector of chars " % For each char G % Push input again @ % Push current char = % Equal (element-wise)? Gives a matrix of zeros and ones, where one % represents the presence of the current char 4 % Push 4. This will indicate 4-connectivity &1ZI % Matrix with labels of connected componnents. Inputs are a number (4) % to indicate connectivity, and a binary matrix. The output is a matrix % the same size as the input where each connected componnent of ones % in the input is replaced by a different integer starting at 1 1> % Greater than 1 (element-wise)? The result is a matrix. If the result % is true for some entry the input doesn't qualify v % Concatenate vertically with results from previous iterations z % Number of nonzero/true values g % Logical. Converts nonzero to true % Implicit end. Implicit display. False / true are displayed as 0 / 1 ``` [Answer] # Befunge-93, 317 bytes Edit: Fixed for proper byte-count. Also could be golfed further ``` 93+:10pv +93p01+1g01_ [[email protected]](/cdn-cgi/l/email-protection)< gp00g1+>00p~1+:93+`!#^_1-00g10 50p93+:vv_v#!:gg03:p02:<>40p# !`g01: <>\ 1+:vvp05:+<@^p03_^# v93$_v# !- g00<4v04g<^1<vp06:< >+\!\>\ 3v> 40v0>g-v^<.g>:70vp 07_v#:<^ >#+0# g#\< 10\v4gg<^ !#v _$^ g03p <\ v1_#:^5>0g - < ^ g02p1< >-:#^_^#:g05 -1< ^p\g06\0\+1:\g06\-1:\g06:\+1g06:g07 ``` Prints 1 as the truthy, 0 as the falsey [Try It Online](https://tio.run/##JZDBagMxDETv/gotzs04jOLdhAhjsv0O4w2FVLfiS3Xsr2@96UUSmjcD0ufr6@dbX/t@T0EY3YjCPXVwYAVvRPY4c3baAeVQgP7LQQb8nHzbOB5ruAX98Jtt5idRRZKOi@Qyo3s3PUeUUC6V@IA6Fgn50TrS1ryzezoNH02RFMizYdbcOA/uKtmVUKc6rMkKzTAUjdbyWYvcYN3hNrySGxUf4El9zUSMarOOFDd5o@3UaESnTrmS8ealLQVKFB0RDZyoDf3SOVOJMu5qXhSLi3yIrVfFtaIGlvcU/7vU40fXQd72fV3XDzfK@i5/) Here's a visualisation of the path the pointer takes [![Fancy Colours!](https://i.stack.imgur.com/7WRJX.png)](https://i.stack.imgur.com/7WRJX.png) Note: this is for an old version --- # How it works Here's some quick and dirty pseudocode ``` a = 2Darray() # from 12,12 down and to the right arrayLocation = 12 x = arrayLocation #stored at 0,0 y = arrayLocation #stored at 1,0 i = input() #stored in the stack while (i != 0): if (i == 10): y++ x = init else a[x][y] = i x++ i = input new.x = init #stored at 2,0 new.y = init #stored at 3,0 currentChar = 0 #stored at 4,0 chars = array() #stored at 1,1 onwards charnum = 0 #stored 5,0 ToCheck = array() #stored in the stack current.x = null #stored at 6,0 current.y = null #stored at 7,0 while (new.y < y): if (a[new] != 0) currentChar = a[new] toCheck[] = new while (toCheck) current = toCheck.pop() if (a[current] == currentChar) toCheck.append(adjacent(current)) a[current] = 0 foreach (chars as char) if (char == currentChar) return 0 charNum++ chars[charNum] = char new.x++ if (new.x > x) new.x = init new.y++ return 1 ``` Basically, after storing the input, it goes through the whole thing, checking each space. When it finds a space with a character in it it adds the coordinates to the stack. Then it checks the spaces around it for the same character recursively, setting each space to 0. When it has exhausted that character's section, it checks whether that character has already had a section. If so, return 0. If not, add it to the array of characters. Once it has gone through the whole grid with no duplicates, it returns 1. For people familiar with Befunge, here's a spaced out version of the code ``` 96+:10p v +69p01+1g01_v `+96:+1~p00<+1g00pg01g00-1_^# v < >40p50p96+:v ^ v @.1< > >:10g `#^_30p:20p:30gg:#v_$>1+:00g-!#v_0 >30g+ v < ^ >$96+1^ >40p30gv ^ >:!#v_70p:60p:70gg40 g-!#v_$> v ^ > ^ 1:\g06\+1:g 07\g07\-1:\g07\ +1: <^p\g06\0\- v < ^ >50gv >5\g1+:50p40g\1p20g^ >:!#^_:1g40g-!#v_1- >0.@ ``` [Answer] # J, 66 bytes ``` c=.1=+/@,+.]-:]*[:*@+/((,|."1)0,.1 _1)&(|.!.0) [:*/[:c"2[="_ 0~.@, ``` `c` defines a verb that tells you if a matrix of ones and zeros is **c**onnected. It treats singleton ones as a special case of true. Otherwise it takes an orthogonal neighbor count of every cell, then the signum of that count, then multiplies that with the original matrix: if that product equals the original matrix, then it's connected. The neighbor count is achieved by shifting in all 4 directions, then summing. The 4 direction shift is achieved using the "`x`-arg can by a table" feature of rotate/shift `|.` Finally, the answer itself achieved by creating a ones/zeros matrix for every *unique* `~.` element of the input, and then ensuring that all of those matrices are connected. This is the verb in the second line. [Try it online!](https://tio.run/##VY7daoQwEEbvfYqpaH7URpOlpc0SUKNPEcRd3JW2FFpwL5e@up2k1G5z850cvhnmbV0nI6TJy7rIxXCvh8zprM5LxoqriCWvCiFhlJywq7gTFY9mI7BROj3Fypl4hOpL1MV6OS8XI8BpOE8vHzDs3Z7R@fj6TuPxwOjncVmQeC2YM3M9cB5J8DOgQCW0aZuWRtU/0zb0t7ODp4Rmmdank1IZAobCLz6ltrnQSpIkTVNCfJDwvCFk2/UIz7gd19uu63qf1nY9gvWApvlJhIA2QMCbe3b@QhuG/7SEh6C7/kZJVNuJW8PS9Rs "J – Try It Online") [Answer] # JavaScript (ES6), 114 bytes Takes input as an array of strings. Returns `0` or `1`. ``` a=>(C={},F=x=>!C[c=a[y][x]]|(g=v=>(a[y+v]||[])[x]==c)(-1)|g(1)|g(0,x--)|g(0,x+=2)?a[y+=!c]?F(C[c]=c?x:0):1:0)(y=0) ``` ### Test cases ``` let f = a=>(C={},F=x=>!C[c=a[y][x]]|(g=v=>(a[y+v]||[])[x]==c)(-1)|g(1)|g(0,x--)|g(0,x+=2)?a[y+=!c]?F(C[c]=c?x:0):1:0)(y=0) console.log(f([ // 1 "A" ])) console.log(f([ // 1 "AB", "AB" ])) console.log(f([ // 0 "AB", "BA" ])) console.log(f([ // 1 "ABCDE" ])) console.log(f([ // 0 "ABCDC" ])) console.log(f([ // 1 "**::dd22", "***:d222", "*:::::22" ])) console.log(f([ // 0 "$$$%%%&&", "$$%%&&&&", "&&$$$%&&" ])) console.log(f([ // 1 "AABBCDDDE", "ABBCCCDEE", "ABCCCCDDE", "AACCCDDEE", "AAAACCCCE", "AAAAAACCC" ])) console.log(f([ // 1 "AABB", "ABBA", "AAAA" ])) console.log(f([ // 1 "AAAB", "AAAA", "AAAA" ])) ``` ### Formatted and commented ``` a => ( // given an array of strings a C = {}, // C = object holding encountered characters F = x => // F = recursive function taking x: !C[c = a[y][x]] // c = current character; is it a new one? | (g = v => // g = helper function taking v (a[y + v] || [])[x] == c // and testing whether a[y + v][x] == c )(-1) // test a[y - 1][x] | g(1) // test a[y + 1][x] | g(0, x--) // test a[y][x - 1] | g(0, x += 2) ? // test a[y][x + 1]; if at least one test passes: a[y += !c] ? // increment y if c is undefined; if a[y] exists: F(C[c] = c ? x : 0) // update C, update x and do a recursive call : // else: 1 // all characters have been processed -> success : // else: 0 // invalid character detected -> failure )(y = 0) // initial call to F, starting with x = y = 0 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 96 bytes ``` And@@(ConnectedGraphQ@Subgraph[GridGraph@Dimensions[t],Tr/@Position[c,#]]&/@(c=Join@@(t=#)))& ``` [Try it online!](https://tio.run/##jY2xCoMwFEV3vyIoiELALxBiowidLO0WMqQxrRlMisZJnDv2U/sJqSIUBEO7HB6Xe95tmWlEy4zkzN4GldpM1QhFWCsluBF12bFHc0Ln4XpfLlJ2cs1QLluheqlVT8z79aTw0iWo0r00c0Y4DCgNExTx9Kilml@aNIjjOLRVJ5Uh8xbxABhHP/MhWHH4Ai/Ityj8CYJZAeNuG2@9wqlgl7K7kv1ouxSnjP9Q9uVp8ii1Hw "Wolfram Language (Mathematica) – Try It Online") Takes input as a 2D list of characters: for example, `{{"A","B"},{"C","D"}}`. The `` character is `\[Transpose]`. ## How it works For each character `c` in the input, takes the `Subgraph` of the `GridGraph` of the same `Dimensions` as the input which corresponds to every `Position` in which `c` occurs, and checks if it's a `ConnectedGraphQ`. [Answer] # [Python 2](https://docs.python.org/2/), 247 bytes ``` def f(a): b=map(list,a.split('\n'));l=len(b[0]) for c in set(a):i=a.find(c);g(b,i/l,i%l,c) print all(set(l)<={0}for l in b) def g(a,i,j,c): if len(a)>i>-1<j<len(a[0])and a[i][j]==c: for x,y in(0,1),(0,-1),(1,0),(-1,0):g(a,i+x,j+y,c);a[i][j]=0 ``` [Try it online!](https://tio.run/##VY/djoIwEIWvt0/REKmtVhe5BDEp4FO4XBQQt6RbiXKh2eyzszMY/3rR880wc07prv330YXDUO8b2nAtIkLL5Ed33JpzL/Xy3FnT8@mXmwoR28TuHS93QSEIbY4nWlHj6Hnf46JJ9LIxruaViA@8lObTSuNbWcFsdzKup9pajsNWrJPf4A8NLBqUgmD8gWtpZAsL8AjTUMzSYmM2i9W6XY8VJmtXU70zxa4tkqSKyAf6XOQVnHggV0LCvUBZyQDuBUo0es8vsp1fwT@@7wdDwz3lCQLieSolKgV9lqm6lyrN8u0D0@w@NJtFUV2HIZkBgQJEeMLwaTSZTHzfZ4ygMjiEMewx9hKmUkjI8y1ByCAMKUPCnroB0sjZjUZ@N8F9NX587eOvwXn0h38 "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 181 bytes ``` (d,o={})=>{f=(i,j,c,l=d[i])=>{if(c&&l&&l[j]==c){l[j]='';f(i-1,j,c);f(i+1,j,c);f(i,j-1,c);f(i,j+1,c);o[c]=1}};d.map((e,i)=>e.map((c,j)=>o[c]||f(i,j,c)));return!d.some(e=>e.join(''))} ``` Whenever a new color tile is found, fill the connected ones with empty strings. If the mat is properly grouped by colors, all tiles should be filled with empty strings. ### Test Code ``` const t = (d,o={})=>{f=(i,j,c,l=d[i])=>{if(c&&l&&l[j]==c){l[j]='';f(i-1,j,c);f(i+1,j,c);f(i,j-1,c);f(i,j+1,c);o[c]=1}};d.map((e,i)=>e.map((c,j)=>o[c]||f(i,j,c)));return!d.some(e=>e.join(''))} ; const mat = s=>s.split('\n').filter(l=>l).map(l=>l.split('')); console.log('true?', t(mat(` A `))); console.log('true?', t(mat(` AB AB `))); console.log('false?', t(mat(` AB BA `))); console.log('true?', t(mat(` ABCDE `))); console.log('false?', t(mat(` ABCDC `))); console.log('true?', t(mat(` **::dd22 ***:d222 *:::::22 `))); console.log('false?', t(mat(` $$$%%%&& $$%%&&&& &&$$$%&& `))); console.log('true?', t(mat(` AABBCDDDE ABBCCCDEE ABCCCCDDE AACCCDDEE AAAACCCCE AAAAAACCC `))); console.log('true?', t(mat(` AABB ABBA AAAA `))); console.log('true?', t(mat(` AAAB AAAA AAAA `))); ``` ]
[Question] [ Given a list of lists find the shortest list that is a contiguous sublist of exactly one list. For example if we had ``` [[1,2,3], [1,2,3,4], [2,4,5,6], [1,2,4,5,6]] ``` the shortest contiguous sublist would be `[3,4]` since it only appears in the second list. If there is no unique contiguous sublist (this requires at least one duplicate entry), output an empty list. Here is an example ``` [[1,2,3], [1,2,3], [1,2]] ``` If there are multiple contiguous sublists of minimal size, you may output any one of them or a list containing all of them. For example if the input was ``` [[1,2,3],[2],[1],[3]] ``` You could output either `[1,2]`, `[2,3]` or `[[1,2],[2,3]]`. If you choose to do the latter option you may output singleton lists for the cases where there is only one solution. The output may occur in the *same* list more than once as long as it appears in no other list. For example ``` [[1,2,1,2],[2,1]] ``` should output `[1,2]` because `[1,2]` is a sublist of the first list but not the second, even though it is a sublist of the first list in two different ways. You may take as input a list of lists containing any type so long as that type has more than 100 possible values, i.e. no Booleans. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. ## Test Cases ``` [[1,1]] : [1] [[1],[1]] : [] [[1,1],[1]] : [1,1] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ ~~14~~ 15 bytes +3 bytes for case `[[1,1]]` ``` Ṡḟȯ¬€Ṡ-uÖLṁȯtuQ ``` [Try it online!](https://tio.run/##yygtzv7//@HOBQ93zD@x/tCaR01rgBzd0sPTfB7ubDyxvqQ08P///9HRhjqGsbEA) ### Explaination ``` ṁ -- map and concatenate ȯt -- all but the first u -- unique elements of Q -- contiguous sublist ÖL -- sort by length Ṡḟ -- find the first element satisfying this predicate ȯ¬€ -- not an element of Ṡ- -- the list of sublists minus u -- its unique elements ``` Note: `Ṡ f g x = f (g x) x` and this is hard to explain using the method above. [Answer] # Pyth, 15 bytes ``` halDs-M.p.:R)QY ``` [Test suite](https://pyth.herokuapp.com/?code=halDs-M.p.%3AR%29QY&test_suite=1&test_suite_input=%5B%5B1%2C2%2C3%5D%2C+%5B1%2C2%2C3%2C4%5D%2C+%5B2%2C4%2C5%2C6%5D%2C+%5B1%2C2%2C4%2C5%2C6%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C+%5B1%2C2%2C3%5D%2C+%5B1%2C2%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C+%5B1%2C2%5D%2C+%5B1%2C2%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C+%5B1%2C2%5D%2C+%5B2%2C3%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C+%5B1%2C2%5D%2C+%5B1%2C3%5D%2C+%5B2%2C3%5D%5D&debug=0) First, we generate all substrings of each input list with `.:R)Q`. Then, we generate all possible orderings, of those substring groups `.p`. Now for the tricky part: `-M`. This folds the `-` function over each ordering list. It starts with the first substring list, then filters out all occupants of all of the other lists. Then, the results are concatenated, ordered by length, a `[]` is appended, and then the first element of the resulting list is extracted with `h`. This would be 4 bytes shorter if I could error on no unique sublists rather than output an empty list. [Answer] # Pyth - 20 bytes ``` Ksm.:d)QhalDfq1/KTKY ``` [Test Suite](http://pyth.herokuapp.com/?code=Ksm.%3Ad%29QhalDfq1%2FKTKY&test_suite=1&test_suite_input=%5B%5B1%2C2%2C3%5D%2C%5B1%2C2%2C3%2C4%5D%2C%5B2%2C4%2C5%2C6%5D%2C%5B1%2C2%2C4%2C5%2C6%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B1%2C2%2C3%5D%2C%5B1%2C2%5D%5D%0A%5B%5B1%2C2%2C3%5D%2C%5B2%5D%2C%5B1%5D%2C%5B3%5D%5D&debug=0). [Answer] # [Haskell](https://www.haskell.org/), ~~149~~ ~~128~~ ~~126~~ 113 bytes ``` import Data.List f l=[x|x<-l,sum[1|y<-l,y==x]<2] h[]=[] h(x:y)=x i=h.f.sortOn length.(>>=tail.nub.(>>=tails).inits) ``` [Try it online!](https://tio.run/##ZY7NCsIwEITP5in22MIaaP05SOPJo@IDhBwiVruYxGIipOC719iigh6Wmfl2WabR/lIb0/dk2@stwEYHzbfkAzuBETI@YjU16O9WFo/uZTshoqpKxRqphEySxVWXi8hINPzEfXqyd2Bqdw4Nz9ZrETQZ7u6HT/A5J0fB530dtW1N7UGAZBMpCyxxpnBUnCdX4hwXuFQIAxyDwr/jUX825YummX148XbD5kuHpBhjVpNLbY5XYBOr2x1k7Y1c4JTDu2z/BA "Haskell – Try It Online") *Saved 21 bytes thanks to Wheat Wizard, H.PWiz and Bruce Forte.* *Saved two more bytes thanks to H.PWiz.* *Saved 13 bytes thanks to nimi.* **EDIT** This was the original explanation: > > * `a` is a shortcut for joining lists. > * `s` computes all the continous sublists (all `tails` from all `inits`). Note that `nub` keeps only the first occurence of each element, so `tail` will remove the empty list from the sublists. > * `g` merges all sublists from all given lists in a big list of sublists, and sort them by length. > * `f` f is a filter on elements that appear only once in the big list > * `h` is a secure version of `head` > * `i` is the glue > > > Quite inelegant! There should be a better solution... > > > [Answer] # Java 8, 251 + 19 = 270 bytes A very gross lambda from, minimally, `List<List>` to `List` (best to cast it to `Function<List<List<Integer>>, List<Integer>>` though). It's a brute force solution that iterates chunk lengths from 1 to the size of the largest list, in each case iterating over every chunk of that length in every list and checking each such chunk against each chunk of equal size in every other list. Fear me, garbage collector. ``` import java.util.*; ``` ``` i->{int x,l=x=0,s,t;for(List z:i)x=Math.max(x,z.size());List r=i;while(l++<=x)for(List a:i)c:for(s=0;s<=a.size()-l;s++){for(List b:i)for(t=0;t<=b.size()-l;)if(b.subList(t,l+t++).equals(r=a.subList(s,s+l))&a!=b)continue c;return r;}return new Stack();} ``` ## Ungolfed lambda ``` i -> { int x, l = x = 0, s, t ; for (List z : i) x = Math.max(x, z.size()); List r = i; while (l++ <= x) for (List a : i) c: for (s = 0; s <= a.size() - l; s++) { for (List b : i) for (t = 0; t <= b.size() - l; ) if (b.subList(t, l + t++).equals(r = a.subList(s, s + l)) & a != b) continue c; return r; } return new Stack(); } ``` [Try It Online](https://tio.run/##dVHBjtsgFDzbX0EvFdQEbdvdHkKIVFWqVKl7snpa7QE7JEsWgxees04sf3uKHTdpVtoLYt7MPB5vtnInZ65Wdrt6Puqqdh7QNtZYA9qwTzxN66YwukSlkSGge6kt6tKk9nonQaEAEiJ5cawbW4J2lv2cLovfOsDp@GVBbZRfLim6xmit7SqvpDEqwB@rXxqVD68GQOKoZ8tOW0AtNaIVNzRQ4Gvn8dACHeaatOJewhOrZItbemBBHxQmhI@8F5q/PmmjsMmyhWjJ2Smjs5wPMIgbHhZCTs6Z4SHLSHdWFlE5AIg6WIjioiN6jSNsikGHgZoMopOpl0aagP3QcuICDZkh5KP8IApSOgvaNgqV3CtovEWe99PNqleUgyyfMeH9MYn7T6YAplXvnF6hKsaAc/Dabh4ekfSbQIZUknwfQFXMNcBiQhaMxbGavLteJuva7EdNcsnwu/dyH1gAr2SFh4mmpB4e42vdqE66zxR9oehrT68xRbfnUsS3FN1R9O2N6rrakxMZI6zx2zHmcxmGFf7TlC5@o4T/dKc52Y8T4Xxg4Malk9EzHISnSZ/2x78) # Java 8, 289 + 45 = 334 bytes This is a more functional approach using streams. If there were a method on `Stream` to reduce to only elements that appear once, this solution would have beaten the one above. Assign to the same type as above. ``` import java.util.*;import java.util.stream.*; ``` ``` l->{List<List>o=l.stream().flatMap(a->IntStream.range(1,a.size()+1).boxed().flatMap(n->IntStream.range(0,a.size()-n+1).mapToObj(k->a.subList(k,k+n)))).collect(Collectors.toList());o.sort((a,b)->a.size()-b.size());for(List a:o)if(o.indexOf(a)==o.lastIndexOf(a))return a;return new Stack();} ``` ## Ungolfed lambda ``` l -> { List<List> o = l.stream() .flatMap(a -> IntStream.range(1, a.size() + 1) .boxed() .flatMap(n -> IntStream.range(0, a.size() - n + 1) .mapToObj(k -> a.subList(k, k + n)) ) ) .collect(Collectors.toList()) ; o.sort((a, b) -> a.size() - b.size()); for (List a : o) if (o.indexOf(a) == o.lastIndexOf(a)) return a; return new Stack(); } ``` [Try It Online](https://tio.run/##dZLBbtswDIbP9lPoKLWysHTdDvFiYBgwoECLHrydih5oRw4U25In0WmzwM@eSbGTLs3mg0yR/Eman9ewgcR0Uq@X9V61nbFI1t4nelSNuErjC59DK6ENobjri0aVpGzAOfIASpNdHHVWbQAlcQjog2/CqtclKqPF98n4cq8cjsedRrmSNss4Ob@TSull3kLTSIc/tfrVyzx0dUgW@ybJdqcamVkch6NMVA3gA3QUkszXyseZLeiVpDMOwqnfkrLrGROFeZXLvwT6UvDhJEh0kLTQ/TCPxZrWSeYjfRHa05rX15r5R5TGT1si/Ta@jXUCzSGHsdQI5/dJKfCCHeRj4WIyWFoZS0MygblhqqJG@A3I18eKAlssjPDLxruTh1mJvdUE0snQ8oXkCGVNWTrsI08pmjBNQDZGLUnrYVH/kUqvnp4J2JVjgV2Ubx3KVpgeheeosdHUe6P/QhDQdc32kBO9kf5qLWzdEUaYaOL59Oy77Q7Z0W7GyQ0nHwd@fufk9uTy91tOPnHy@V3WuXdgYzCQoe/HmM/BhX0ec450Lv7of@EKmnCwNI6GeNj/AQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Ẇ€Q€ẎɓċỊµÐf⁸LÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrZHTWsCgfjhrr6Tk490P9zddWjr4Qlpjxp3@Bye8HBn0////6OjDXWMYnVApI4hkAaSQDoWAA "Jelly – Try It Online") -3 bytes thanks to Jonathan Allan [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` εŒÙ}€`{γʒg}€`éн ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3Najkw7PrH3UtCah@tzmU5PSwczDKy/s/f8/OtpQR8FIRwFExuooRIOYsbEA "05AB1E – Try It Online") [Answer] # Pyth, 14 bytes ``` sfq1lT.gksm{.: ``` [Try it here.](http://pyth.herokuapp.com/?code=sfq1lT.gksm%7B.%3A&input=%5B%5B1%2C+2%2C+1%2C+2%5D%2C+%5B2%2C+1%5D%5D&debug=0) ]
[Question] [ Kids who are learning how to count often know runs of numbers, but can't seem to put those runs together properly. For example, they might say: ``` 1,2,3,4,7,8,9,10 ``` Sometimes kids will realize that they skipped some numbers, and go back: ``` 1,2,3,4,7,8,5,6,7,8,9,10 ``` This is clearly the superior pattern. We need to identify them. To identify these lists: 1. We identify the minimum `M` and the maximum `N` of the list 2. We step through the list. If the current number is greater than or equal to any member of the list to its right, then we remove the current number. 3. Iff the remaining list contains all numbers from `M` to `N`, then we return a truthy value. You can assume your input list will contain at least 1 element. You can assume that all integers will be non-negative. ## Test cases: Truthy: ``` 0 10 0 0 0 1 0 1 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 0 1 2 3 0 1 2 3 4 5 5 0 1 1 2 2 3 0 3 6 1 4 7 2 5 8 3 4 5 6 7 8 1 3 5 7 2 3 4 5 6 7 5 6 0 1 2 3 6 7 4 5 6 7 5 6 7 8 5 5 6 7 8 4 6 7 8 3 4 5 6 7 8 ``` Falsy: ``` 1 0 4 3 2 1 1 2 3 7 8 9 0 1 2 3 1 3 0 1 2 3 1 3 4 0 1 2 3 1 3 2 4 0 1 2 3 1 3 2 4 3 1 3 5 7 2 4 6 8 0 1 2 1 3 4 5 6 4 5 6 3 4 5 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes I am not 100% certain this works, but it passes all test cases and I couldn't find any situation where it fails. ``` Ú¥1QP ``` [Try it online!](https://tio.run/nexus/05ab1e#@3941qGlhoEB//9HG@oY6RjrmOiY61jomOqYgWlLHUODWAA "05AB1E – TIO Nexus") ``` Ú¥1QP Main link. Argument a Ú Reverse uniquify a, keeps only last occurence of each element ¥ Get all deltas - all 1 if ascending list 1Q Compare all deltas to 1 P Product of all results ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` ṀrṂɓṚ«\Q⁼ ``` [Try it online!](https://tio.run/nexus/jelly#ZU6xDcIwEOw9xY@Qj2MSJqCmoWIKJghpGIAOQUUJFUIREVRBFIxhL2LunYQYoThv3//d33nblCvbVO@tbXbtaTl364e396u9XVx1XuDHeW5Q1AuUoyv3bd3WrjyE5sz7RHGiEpJPMQoDMKWkKSNDE8qpoCkFTtfu7x@aCUhwN9EQMiY5sMGCaBlMNN55bKGkDvuEFfdFY77qrI8Ub5TcGGjIx/QcRRTL7Ael/xj8MZrYFD2DBzPVWQb0AQ "Jelly – TIO Nexus") ### How it works ``` ṀrṂɓṚ«\Q⁼ Main link. Argument: A (array) Ṁ Yield the maximum of A. Ṃ Yield the minimum of A. r Yield R := [max(A), ... min(A). ɓ Begin a new chain. Left argument: A. Right argument: R Ṛ Reverse A. «\ Take the cumulative minimum. Q Unique; deduplicate the results. ⁼ Compare the result with R. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~59 54~~ 41 bytes ``` ->a{a.reverse|[]==[*a.max.downto(a.min)]} ``` [Try it online!](https://tio.run/nexus/ruby#pU9dC4JAEHzfX7HcQ2mgeKlpgf0RkzjIQCgVtQ/IfrvteWonPcbB3s3t7OzMOeqsvXgJu0rvaVWnbZxEUbwS9lU87VPxyJvCIJDlZvLumAPcAQflAU6FE@C4Rhc99HGDAYa4xZ6jvod7RvN7JLHquDTIqRMQ9klAE6MlLr0DfQXIOupJlv4vZ/xp2hssaYrMrstL1hjskDOTQpYvQGxFi@WtqfEci7GPqm0sdk1xzMwE3iApS8uylsAoPKm75IGDctJHn3JyLbPM4M3Q@hcT/5tV@g4HBh/dg8rQoz9SdB8 "Ruby – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` x=input();r=m=[] for n in x[::-1]:r=[n][:n<m]+r;m=r[0] print r==range(m,max(x)+1) ``` [Try it online!](https://tio.run/nexus/python2#fVLRioMwEHzWr9g3laZgqp699PIfhZAHz9pDuKQltJC/95JNjnoqByLJzOzsZNn@dhmAQ5Zlk@Wjvj8feXEyXHEh0@vNgIZRgxWM7alkhgstBdMfSu7MSXEjSpnezagfYDg3nf4ackVUZ3Nb7GgxOdcUXc7eRQgnJyAo/ksC8UMMjzQS7nYgUBGoCTQE3gi0BI4E3h1VLjWv83Z184IDM5NWaE5R2iLTYKNl6xixQqxdp/N8OM77h@It1a9ns2xSz167CuEFOKmorLDRamh0YxQhfL0NH/5lotvi@SHo8U8ZnWeOGUP8CEspWZr4hbB@Ic7ukuDOuQ387tTnpWNgHTbYoYfebWaa4HZNPw "Python 2 – TIO Nexus") [Answer] # [PHP](https://php.net/), 148 130 bytes -18 bytes, thanks @Christoph ``` $a=explode(' ',$argn);$b=range(min($a),max($a));foreach($a as$i=>&$k)for(;++$i<count($a);)$k<$a[$i]?:$k=-1;echo!array_diff($b,$a); ``` [Try it online!](https://tio.run/nexus/php#ZVBbT4MwFH7vrziSE4EMDR0gc4XtycQHE/euZukYDIIDAprMGH/7POUyIaZJ2@/0u6XBukorhpFs4ibUbMZtZgMtxmnndOcwBwdc8OAOfFjAPbSUbtyfE5rXIoW7F4eEnF58wh4ZjMwoxKG7P45gah/8FGs8Vxrvonb7SlNHm@YOqTnrPNrSl4Z81FaluxM0/4@J/9dSJS56Bh9yWZfeIk2wpKxjGaVGfKrey31saK@FZnUfbIJsAMtwhbI@FOY3i6O0hNkMy1vQl6CLM8pw0OmgWx1P4C6sZXGIjWNWGChN6yhP6jTFEIaSrDELV9eYmzQ0BLlmQVR@Fh@KKUzMA5QvmL2tl5iHN1yo7CtZ1/Jru8@SxMCdpYjnttPmcbN9eH4SP@df "PHP – TIO Nexus") [Answer] # Java 8, ~~264~~ 262 bytes ``` import java.util.*;l->{int m=Collections.max(l),n=Collections.min(l),i=0,q;for(;i<(q=l.size());i++)if(l.subList(i+1,q).size()>0&&l.get(i)>=Collections.min(l.subList(i+1,q)))l.remove(i--);for(i=0;n<=m;)if(i<l.size()&&l.get(i++)==n)n++;else return 0>1;return 1>0;} ``` **Explanation:** [Try it here.](https://tio.run/nexus/java-openjdk#tZTBjtMwEIbvfYo5rWzqWvG2pSA3kRAnJNjLHhEHN7iVkeO0jlNYVn32Mk5TWNgLEoOSKIntfPP7n5m4Zt/GBF/M0cg@OS9f6Mmk9qbr4INx4XEC4EKycWtqC3f5FWDTtt6aADV7E6N5eO@6tH6Hi3Y2VuC5xkUnvPDskkmuhjsIUMLZz6pHhEFTvm29t3VybehkY74xz0X4fdCFPOjKQhz0to1MuzU7lF527rtlnGs3nXK3ZTjQb7IA5qZKHPg4XxU3N17uLA7z6jn4j4849zLapj1a5mYzPsTDyDqsy0bnKG59DfwTi@HLMvAwnWrrOwvRpj4GKCqlx0dVFfp0RjcB9v3Gow2jG8fWfYYGzWX3Kbqw@/gJDL84e//QJdvItk9yj1PJBxZkzYL9Cs@tvrjfSdMNeylwH4P3/4ZRRJxC4EEkCVGKSpUSt2IuFmIpXoqVeCVeC7odX9jjnV7wkg6ZoYQa52imQo0rhC7R1CcGU5XAHIGrp7mjAWfU1eOslxxOZsGS1tHFWP9/myqaPqbSPseEKarSyrkffgW0Lauo/wG5CRb0yNv/BKXa/q/eHyqVUqu6lj9VXeZOGpBX4GlyOv8A) ``` import java.util.*; // Import for Collections l->{ // Method with integer-ArrayList parameter and boolean return-type int m=Collections.max(l), // Max of the list n=Collections.min(l), // Min of the list i=0,q; // Two temp integers for(;i<(q=l.size());i++) // Loop (1) over the list if(l.subList(i+1,q).size()>0 // If the sublist right of the current item is not empty &&l.get(i)>=Collections.min(l.subList(i+1,q))) // and if the current item is larger or equal to the lowest value of this sublist l.remove(i--); // Remove the current item from the main list // End of loop (1) (implicit / single-line body) for(i=0;n<=m;) // Loop (2) from min to max if(i<l.size() // If the current item doesn't exceed the list's size &&l.get(i++)==n) // and the items are in order so far n++; // Go to the next item else // Else: return 0>1;//false // Return false // End of loop (2) (implicit / single-line body) return 1>0;//true // Return true } // End of method ``` [Answer] # R, ~~88~~ 85 bytes ``` y=NULL;for(i in x<-scan())if(all(i<x[-(1:(F<-F+1))]))y=c(y,i);all(min(x):max(x)%in%y) ``` This can probably be golfed down further. Loops over the elements of `x`, checks if all upcoming values are bigger, and only then keeps that element. After the loop it creates a sequence from `min(x)` to `max(x)`, and checks with `%in%` if all values are included in the pruned version of `x`. [Answer] ## JavaScript (ES6), 60 bytes ``` s=>(o={},s.reverse().every((n,i)=>!i|o[n+1]|o[n]&&(o[n]=1))) ``` **Ungolfed:** ``` s=>( o={}, s.reverse().every((n,i)=> !i|o[n+1]|o[n]&&(o[n]=1) ) ) ``` This is a simpler algorithm: Iterate the array in reverse, and make sure each number (except the first) is one less than or equal to a number already seen. **Snippet:** ``` f= s=>(o={},s.reverse().every((n,i)=>!i|o[n+1]|o[n]&&(o[n]=1))) console.log('Truthy'); console.log(f([0])) console.log(f([10])) console.log(f([0,0,0])) console.log(f([1,0,1])) console.log(f([0,1,2,3,4,5,6,7,8,9,10])) console.log(f([0,1,2,3,0,1,2,3])) console.log(f([0,1,2,3,4,5,5])) console.log(f([0,1,1,2,2,3])) console.log(f([0,3,6,1,4,7,2,5,8,3,4,5,6,7,8])) console.log(f([1,3,5,7,2,3,4,5,6,7])) console.log(f([5,6,0,1,2,3,6,7,4,5,6,7])) console.log(f([5,6,7,8])) console.log(f([5,5,6,7,8])) console.log(f([4,6,7,8,3,4,5,6,7,8])) console.log('Falsy'); console.log(f([1,0])) console.log(f([4,3,2,1])) console.log(f([1,2,3,7,8,9])) console.log(f([0,1,2,3,1,3])) console.log(f([0,1,2,3,1,3,4])) console.log(f([0,1,2,3,1,3,2,4])) console.log(f([0,1,2,3,1,3,2,4,3])) console.log(f([1,3,5,7,2,4,6,8])) console.log(f([0,1,2,1,3,4,5,6])) console.log(f([4,5,6,3,4,5])) ``` [Answer] ## Haskell, 62 bytes ``` g(a:b)=[a|all(a<)b]++g b g a=a f x=g x==[minimum x..maximum x] ``` [Try it online!](https://tio.run/nexus/haskell#bY7PDoIwDMbvPEUPHiA2hPFH0LgnWXYoMRASh8RowsF3x1JQF0OWrfvar@1vakM61ZE29KLrNaRzVNv9voU6aIE0BQ2MuuWrjev6zj0djHHsaFy@dnLU9aDhcgsAhnvXP2AHjgZowJjEolHzkyCfWXBUohWmmGGOBR6wxAqPuBqXwholk7FFsbXkTMFWr01GZqxKfxxnf/XC8@brMn@C3eBWApuzLxXchUkwPUa18n0V5n863cpI1496Zqq@LvVhk/0zo2hrpzc "Haskell – TIO Nexus") A direct implementation of the definition where `g` removes the elements if they are >= than the the elements to its right. [Answer] # C#, 69 bytes ``` s=>s.Where((e,i)=>s.Skip(i+1).All(r=>e<r)).Count()==s.Max()-s.Min()+1 ``` In short: s = input (s)equence take from s element where all items after this one (skip (I)ndex + 1 items), current value is higher count these, and see if the amount left is equal to the amount expected ((max)imum value minus (min)imum) amount of numbers [Try it online!](https://tio.run/##rVRNT@MwEL3nV4x6wRathfuxhS2pVCGhPYCESBFCFQcT3NbCm3Rth6VC/e3dcWlFaJ2WwzqHyDPPb57njZzaRmrTZWFVNoFkbp383YvKO3alsj@9aFY8aZVCqoW18AbvkXXCYeA1V89wLVRGKAbhssjSc5W50WMdnvJc92EM8dLGfcvup9JIQmRdUb9NXtSMqGNO2UBrYuK@PDeUsou8yByhcWzZtXgjtIF/T37Ml70ogtJ6FQacKdx0DjFk8u/o0QvYWrWTWn03yIPRE8AvCMcED5/g0IQWtKEDP6ALp3AGVdwfyPX/EFmnCuAhledbKILj@S5COiimJCx8rRamu@UbhGA@sdHmuQ5AK4p19ilpr7tXFvwFtWCJ1DJ1RELcB8mSmVaOHMER3SQmPoGDx26EsZJMcJSG@cAYMSeU9nYGZyy03Ts3PDwKbdTYDA/DR4dWQ7DPXr7ffW9K@xCg@S1IuNCn677rp9U8fGNHuA/epxXgPzv1he0iz2yuJbs3ykl8iCSpDW/vhr8efta2TB3nRop0CmT1LCD/@m3AVynAMiYOa8Ei2k1t8QYUXA6uku8IWM3YgfqLxfIf "C# (Visual C# Compiler) – Try It Online") [Answer] ## JavaScript (ES6), ~~82~~ ~~73~~ ~~72~~ 70 bytes Returns a boolean. ``` a=>a.filter((x,i)=>k-=a.every(y=>~i--<0|y>x,m=x>m?x:m),m=k=0)[0]+~m==k ``` ### How? We iterate on each element ***x*** of the input array ***a***, keeping track of the maximum encountered value ***m*** and the number ***-k*** of values that are not greater than or equal to any member to their right. By definition, valid values appear in strictly ascending order. We use `filter()` rather than `map()`, so that all elements get filtered out until ***k*** turns negative. This allows us to isolate the first valid element, which is also guaranteed to be the minimum value of the array. Finally, we test whether `minimum - (maximum + 1) == -number_of_valid_elements`: ``` a.filter(...)[0] + ~m == k ``` ### Test cases ``` let f = a=>a.filter((x,i)=>k-=a.every(y=>~i--<0|y>x,m=x>m?x:m),m=k=0)[0]+~m==k console.log('[Truthy]'); console.log(f([0])); console.log(f([10])); console.log(f([0,0,0,])); console.log(f([1,0,1])); console.log(f([0,1,2,3,4,5,6,7,8,9,10])); console.log(f([0,1,2,3,0,1,2,3])); console.log(f([0,1,2,3,4,5,5])); console.log(f([0,1,1,2,2,3])); console.log(f([0,3,6,1,4,7,2,5,8,3,4,5,6,7,8])); console.log(f([1,3,5,7,2,3,4,5,6,7])); console.log(f([5,6,0,1,2,3,6,7,4,5,6,7])); console.log(f([5,6,7,8])); console.log(f([5,5,6,7,8])); console.log(f([4,6,7,8,3,4,5,6,7,8])); console.log('[Falsy]'); console.log(f([1,0])); console.log(f([4,3,2,1])); console.log(f([1,2,3,7,8,9])); console.log(f([0,1,2,3,1,3])); console.log(f([0,1,2,3,1,3,4])); console.log(f([0,1,2,3,1,3,2,4])); console.log(f([0,1,2,3,1,3,2,4,3])); console.log(f([1,3,5,7,2,4,6,8])); console.log(f([0,1,2,1,3,4,5,6])); console.log(f([4,5,6,3,4,5])); ``` ]
[Question] [ # Power Grid Resource Costs **Introduction** In the board game [Power Grid](https://boardgamegeek.com/boardgame/2651/power-grid), an integral part of the game is the act of buying resources to fuel your power stations. There are four types of resource used in the game (five, if you include renewable energy, but obviously you can't buy resources for that). These are Coal, Oil, Garbage, and Uranium. The resource market looks like this: [![An illustration of the resource market, taken from the rulebook](https://i.stack.imgur.com/oRBrl.png)](https://i.stack.imgur.com/oRBrl.png) ``` 1---- | 2---- | 3---- | 4---- | 5---- | 6---- | 7---- | 8---- | 10 | 12 CCC | CCC | CCC | CCC | CCC | CCC | CCC | CCC | U | U OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | 14 | 16 GGG | GGG | GGG | GGG | GGG | GGG | GGG | GGG | U | U ``` When resources are bought, they are taken from the left of the market, where they are cheapest. When new resources are added to the market, they are added from the right. As can be seen, this produces a supply and demand balance - if more resources of a particular type are being bought than are being replenished each round, the price of that resource will rise. Similarly, if it's less, the cost will reduce. Coal, Oil, and Garbage all scale up in cost at the same rate, while Uranium scales much faster. A single unit of a non-Uranium resource costs `8 - floor((<units available> - 1) / 3)`. A single unit of Uranium costs `13 - <units available>` if there are 5 or more units available, and `18 - (2 * <units available>)` otherwise. For example, at the start of the game there are all 24 units of Coal available to buy. If the first player would like to buy 4 units of Coal, the first three units would cost 1 each, and the 4th would cost 2, making the total cost 5. This leaves 20 units available. If the second player would also like to buy 4 units of Coal, the cost would be (2\*2 + 2\*3) = 10. **The Challenge** Your challenge is to write a program or function which calculates the cost of buying a given amount of a particular resource, assuming that there is a given amount of that resource present in the market. Your submission should accept, in any reasonable input format and in any order, the following parameters: * The resource type - guaranteed to be one of [C, O, G, U]. * The amount of that resource that is present in the market - guaranteed to be a non-negative integer. If the resource type is not U, it will not be greater than 24. If the resource type is U, it will not be greater than 12. * The amount of that resource that a player would like to buy - guaranteed to be a non-negative integer which is less than or equal to the amount already present in the market. The output should be the cost of the requested resources. **Additional Rules** * The formulae given are for illustrative purposes only, feel free to use any method of calculating the costs you like. * The letter codes for the different resource types (C, O, G, U) may be replaced by their lower case equivalents. You may also replace the letters for numbers, either in the form `C=0, O=1, G=2, U=3` or `C=1, O=2, G=3, U=4`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest submission in bytes will be the winner. * If your submission requires the input in a different order or format than specified in the previous section, you should provide details. **Test cases** Test case format: ``` resource type, amount in market, amount to buy > result ``` Test cases: ``` C, 24, 4 > 5 C, 20, 4 > 10 O, 3, 3 > 24 U, 1, 1 > 16 C, 1, 1 > 8 G, 0, 0 > 0 O, 10, 7 > 44 U, 12, 4 > 10 G, 11, 4 > 22 ``` [Answer] # Python 3, ~~71~~ 69 bytes *Thanks to @xnor for -2 bytes* ``` f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1) ``` A function that takes input via argument of the zero-indexed resource type `r`, the amount available `a` and the amount to buy `b`, and returns the cost. This makes use of the fact that `True` and `False` equate to `1` and `0` in Python, allowing the use of Boolean expressions to index into lists. **How it works** ``` f=lambda r,a,b Function with input resource type r, amount available a and amount to buy b b and... Base case: return 0 if b=0 [8-int(~-a/3),...][r>2] If not uranium, yield the unit cost 8-floor((a-1)/3)... max(18-2*a,13-a) ..else yield the current uranium unit cost ...f(r,a-1,b-1) Decrement a and b, then pass to function ...+... Add the cost of each unit to give the total cost :... Return the above ``` [Try it on Ideone](https://ideone.com/HD2poN) [Answer] # Javascript (ES6), ~~71~~ 59 bytes ``` f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1) ``` Takes `type`, `market_amount` and `buy_amount` as arguments. `type` is an integer between 0 and 3. ### Demo ``` f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1) function run() { var tests = document.getElementById("tests").value.split("\n"), test, C = 0, O = 1, G = 2, U = 3; console.clear(); for (var test of tests) { console.log(test); console.log("> " + eval(test)); } } ``` ``` <textarea rows="10" id="tests">f(C, 24, 4)&#10;f(C, 20, 4)&#10;f(O, 3, 3)&#10;f(U, 1, 1)&#10;f(C, 1, 1)&#10;f(G, 0, 0)&#10;f(O, 10, 7)&#10;f(U, 12, 4)&#10;f(G, 11, 4)</textarea><br/><button onclick="run()">Run</button> ``` [Answer] # Befunge, 142 bytes ``` &2`#v_&&>:!#v_\:1-3/8\-v v:&&< ^-1\ -1p15+g15 < v>#<v < ! v5< # 1: >^g- | 81 \ 4\ : *- 4 -1 ` .p # @^15+g15< >:49+\- ^ | >:2*92*\- ^ ``` [Try it here!](http://www.quirkster.com/iano/js/befunge.html) Takes input as 3 integers, where the resource type is 0,1,2,3. Output is an integer. No idea if this can be golfed any better. There's not that much whitespace, but the newlines probably hurt. [Answer] # Python 2.7, 85 bytes: ``` F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)/3)][F!='U'];G-=1;"*H;print B ``` Based on R. Kap's answer, but you can shave a byte down to 85 by removing the extra / for floor division. Because these are all integers it's automatically floored down to a whole number. [Answer] # Python 2.7, 86 bytes: ``` F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)//3)][F!='U'];G-=1;"*H;print B ``` Takes input by an array in the format `[resource type, units available, units to purchase]`. Output is an integer. Will try to golf more over time. [Try It Online! (Ideone)](http://ideone.com/dqvcja) [Answer] ## Lua, ~~107~~ 101 Bytes Recursive function that have to be called with `f(resource,stock,buy)`. resource have to be a number between 0 and 3. The output is done via the returned value. **Thanks LeakyNun for saving me 6 bytes : `(25-y+(y-1)%3)/3` is shorter than `8-math.floor((y-1)/3)` by 5 bytes and allow me to gain one more byte due to its placement.** ``` function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end ``` ### Ungolfed ``` function f(x,y,z) -- define a function f with 3 parameters return z<1 -- if we don't buy anything else and 0 -- return 0 or( -- else x<3 -- if we're not buying Uranium and (25-y+(y-1)%3)/3 -- return 8-floor((stock-1)/3) or(y<5 -- elseif there's less than 5 Uranium left and 18-y*2 -- return 18-stock*2 or 13-y)) -- else return 13-stock +f(x,y-1,z-1) -- if we bought this iteration -- add f(resource,stock-1,toBuy-1) -- to the returned value end ``` You can test this code [online](https://www.lua.org/cgi-bin/demo) by copy-pasting the following snippet. ``` function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end print(f(1,24,4)) print(f(2,20,4)) print(f(0,10,7)) print(f(3,1,1)) print(f(3,12,4)) ``` ]
[Question] [ Inspired by [this question](https://codegolf.stackexchange.com/questions/74970/stuffing-primes-in-a-box) about packing into this format. Occasionally I see a completed crossword and being as I am, I can't be bothered to find out what the solutions to the clues actually were. ## Input: * A 2D string (any format, newline separated, 2d list etc.) * Blank squares will be represented with a (space character) * Every other square will be in the lower case alphabet. * You may assume that the input will be padded with spaces to form a rectangle ## Output: * Each word found + You must search for words along and down + Words will be at least two letters long + If there are duplicate words, you have to output them for each time they appear * You don't have to do any validation * Words may be outputted in any order * No strict formatting rules ## Test cases: ``` word e e step t d word, step, west, reed --- pies not no wasp pies, not, no, wasp, in, eons, stop --- igloo n word igloo, word, on ``` [Answer] # Pyth - ~~11~~ ~~10~~ ~~8~~ 7 bytes *saved one bytes thanks to @issacg.* ``` t#cjsCB ``` [Try it online here](http://pyth.herokuapp.com/?code=t%23cjsCB&input=%22pies%22%2C+%22+not%22%2C+%22++no%22%2C+%22wasp%22&debug=0). ``` t# Filter by if len > 1 c Chop by whitespace by default j Join by newlines sCB Input, implicit and its transpose in one list ``` [Answer] ## CJam, 14 bytes ``` {_z+S*S%{,(},} ``` An unnamed block that expects a list of (padded) strings on top of the stack and leaves a list of words instead. [Test it here.](http://cjam.aditsu.net/#code=%5B%22pies%22%0A%20%22%20not%22%0A%20%22%20%20no%22%0A%20%22wasp%22%5D%0A%0A%7B_z%2BS*S%25%7B%2C(%7D%2C%7D%0A%0A~p) ### Explanation ``` _z e# Duplicate and transpose the grid. + e# Append the transpose to the original grid. S* e# Join all lines by spaces to ensure that we don't get words e# spanning multiple lines. S% e# Split around spaces, discarding empty segments. {,(}, e# Filter: keep only those strings with length 2 or greater. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø«€#J˜ʒ¦Ā ``` Input as a character matrix. [Try it online](https://tio.run/##yy9OTMpM/f//8I5Dqx81rVH2Oj3n1KRDy440/P8fHa1UoKSjlAnEqUBcrBSrE62kAGTlAXE@EJfARRCiIJFyICsRrEMHaEJsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU@l1aLcOl5J/aQlEwL7S5f/hHYdWP2pao@x1es6pSYeWHWn4X6vzPzo6WqlcSUcpH4iLgDhFKVYnWikVyAKaAqVBIsVAVglUpAAsUgJVkwJRE6ujADSqAMjJhCorBisDKcmDWlACF0GIgkRADkgE6wAbDjEKZEw6EOdANeejaEYYAjMA4QOIe2IB). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix; swapping rows/columns « # Merge this list of lists to the (implicit) input list of lists € # For each inner list: # # Split them on spaces J # Join each innermost list together to a single string ˜ # Flatten the entire list ʒ # Filter the strings by: ¦ # Remove the first character of the string (no-op if it's already empty) Ā # And check that it's non-empty # (after which the result is output implicitly) ``` [Answer] ## JavaScript (ES6), 83 bytes ``` s=>(s+` `+[...(t=s.split` `)[0]].map((_,i)=>t.map(t=>t[i]).join``)).match(/\w\w+/g) ``` [Answer] # T-SQL, 322 bytes I can't prove that this works, but feel free to test it in Microsoft SQL server Management Studio sql server 2017+ ``` DECLARE @ varchar(max)= ('MICROWAVE U S M OCEAN C M OWL A I SWELL P E E SCHEDULES'); WITH C as(SELECT 1x,@ a UNION ALL SELECT iif(ascii(a)=13,0,x+1),stuff(a,1,1,'')FROM C WHERE''<a)SELECT w FROM(SELECT(SELECT left(a,1)FROM c WHERE x=t.x for xml path(''),type).value('.','char(99)')a FROM c t GROUP BY x UNION ALL SELECT @)r CROSS APPLY(SELECT*FROM string_split(translate(a,' ',' '),' '))g(w)WHERE len(w)>1 ``` This script will return ``` MUMMIES COW EWE ALL ESCAPES MICROWAVE OCEAN OWL SWELL SCHEDULES ``` [Answer] # [J](http://jsoftware.com/), 30 bytes ``` [:(#~1<#&>)@,' '<;._1"1@,.],|: ``` [Try it online!](https://tio.run/##fY6xisJAEIb7eYofBddAXIzlqkfuBKvjClsJImbUHCEb3IU04qvHGcXCxmKGYff/vpn/fmDNEUsHgxRTOKmJxWrzu@63bjy8ZYvh6CvJUwOzmNtdNsjy1Bbp1fUJfQ4Q8eHscUQhzzMUap9S5y8lMRgUIrcUUYISor8fi@@6RuQQcdgHDkQ6Ly3Ukk8ctu7lIhrPnVETVIJOoQtzaZKn4NMmRduKAxofpdDtQ4uqAfsmiM63bxJNkkYJ0knDL0l1qr3geoVv3qDHjwCCPK6Qvf0d "J – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` Lm:d"\S\S+"1byQyCQ ``` [Try it online!](http://pyth.herokuapp.com/?code=Lm%3Ad%22%5CS%5CS%2B%221byQyCQ&input=%5B%22pies%22%2C%22+not%22%2C%22++no%22%2C%22wasp%22%2C%22+t++%22%5D&debug=0) Sample input: ``` ["pies"," not"," no","wasp"," t "] ``` Sample output: ``` [['pies'], ['not'], ['no'], ['wasp'], []] [[], ['in', 'at'], ['eons'], ['stop']] ``` How it works: ``` Lm:d"\S\S+"1byQyCQ The "1" here is mode assign('Q',eval_input()) "1" which means show @memoized all matches L def y(b): v m:d"\S\S+"1b return map(lambda d:regex(d,"\S\S+",1),b) yQ imp_print(y(Q)) yCQ imp_print(y(transpose(Q))) ``` [Answer] ## Haskell, 58 bytes ``` import Data.List f x=[w|w@(_:_:_)<-words=<<x++transpose x] ``` Usage example: `f ["pies"," not"," no","wasp"]` -> `["pies", "not", "no", "wasp", "in", "eons", "stop"]`. How it works: split each of the lines of the input and the transposition of it at spaces it into a single list words. Keep those that match `(_:_:_)`, i.e. have at least two letters. [Answer] # C++14, ~~209~~~~207~~201 bytes Ridiculously high amount of bytes... but oh well. Transpose matrix, split string. Easy. Too bad no native function for transposing ``` [](vector<string>; m){auto t=m;int C=size(m[0]),j=0;for(;++j<C*C;)t[j%C][j/C]=m[j/C][j%C];for(j=0;++j<C+C;){stringstream Z(j<C?m[j]:t[j-C]);string s;while(getline(Z,s,' '))cout<<(size(s)>1?s+' ':"");}} ``` Ungolfed: ``` using S=vector<string>; [](S m){ S t=m; int C=size(m[0]),j=0; for(;j<C*C;++j)t[j%C][j/C]=m[j/C][j%C]; // Transpose for(j=0;j<C+C;++j){ // since rectangle matrix, we can iterate like so stringstream Z(j<C?m[j]:t[j-C]); // Get string from m or t string s; while(getline(Z,s,' ')) cout<<(size(s)>1?s+' ':""); } } ``` How to use it (note you must enforce padding as the question states): ``` using S = vector<string>;[](S m) { ... }({"pies", " not", " no", "wasp"}); ``` [Answer] ## Pyke, 9 bytes ``` ,+Fdc#t(s ``` [Try it here!](http://pyke.catbus.co.uk/?code=%2C%2BFdc%23t%28s&input=%5B%22word%22%2C%22e+e+%22%2C%22step%22%2C%22t+d+%22%5D) Or 7 bytes prettified ``` ,+Fdc#t ``` [Try it here!](http://pyke.catbus.co.uk/?code=%2C%2BFdc%23t&input=%5B%22word%22%2C%22e+e+%22%2C%22step%22%2C%22t+d+%22%5D) [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as an array of lines. ``` cUy)c¸fÅ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVI&code=Y1V5KWO4ZsU&input=WwoKIndvcmQKZSBlIApzdGVwCnQgZCIKCiJwaWVzCiBub3QKICBubwp3YXNwIgoKImlnbG9vCiAgICBuCndvcmQiCgpdLW1S) (includes all test cases) If we could include a leading and/or trailing newline in the input then this could be 7 bytes, taking input as a multi-line string. ``` pÕ·c¸fÅ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cNW3Y7hmxQ&input=WwoKIgp3b3JkCmUgZSAKc3RlcAp0IGQiCgoicGllcwogbm90CiAgbm8Kd2FzcAoiCgoiCmlnbG9vCiAgICBuCndvcmQKIgoKXS1tUg) ``` cUy)c¸fÅ :Implicit input of array U c :Concatenate Uy : U transposed ) :End concat c :Flat map ¸ : Split on spaces f :Filter elements that return true after Å : Slicing off the first character, resulting in the (falsey) empty string when length is <2 ``` ``` pÕ·c¸fÅ :Implicit input of multi-line string p :Append Õ : The transposition · :Split on newlines c¸fÅ :As above ``` ]
[Question] [ # The story "2016? Al..right," grumbled toy seller Hilbert. He opened his eyes, wiped salad dressing trickling out of his ear and ate a morning kick-start cremeschnitte. Exemplar holidays. He needs to go to work now though, and finish the year's accounting. Christmas is a very yielding period of the year, especially for his sales. Hilbert knows exactly how it works: A person comes into a shop and buys the first gift they are offered. They pay for it and run off to another shop. In practice, what the gift actually is doesn't really make a difference. The price is also irrelevant, provided it is not too high. It all depends on the time remaining until Christmas -- the shorter the time, the greater the remorse of the customers, the greater the price they are willing to pay. All it takes for Hilbert is to look at his watch -- and he knows right away how much his customers can spend. He can easily take advantage of this fact: He just finds the most expensive gift he can sell to a given customer, and offer it to them. Only now has he realized that he forgot to employ this cunning strategy last year. That's gonna change though! Nevertheless, Hilbert would like to know how much his business would have flourished, if he had actually used his grand scheme. He's managed to put together a list of people who came to his store, he is however not sure how much money he could have made on them. # Your task (TL;DR) The input consists of an *ascending* list of prices of available gifts, and a list of customers' budgets. The list of budgets is in the same order as the customers arrived to the shop -- with a condition that every customer is willing to pay at least as much as the previous one, meaning it is also ascending. **For each customer, find the most expensive gift they are willing to pay for, and output it's price. If no gifts within the budget are available, output a `0`.** You get a `-40%` characters bonus, if the asymptotic time complexity of your algorithm is `O(n+m)` (rather than the trivial `O(n*m)`) Where `n, m` are the lengths of the input lists. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest bytes wins. Standard loopholes are prohibited. # Example Input: ``` 1 2 2 2 5 7 10 20 1 1 2 3 6 6 15 21 21 22 ``` Output: ``` 1 0 2 2 5 2 10 20 7 0 ``` --- This task was taken from a local programming competition, and translated to English by me. Here is the original assignment: <https://www.ksp.sk/ulohy/zadania/1131/> [Answer] # Pyth, ~~17~~ 16 bytes *1 byte thanks to Pietu1998* ``` VE=.-Q] e|fgNTQ0 ``` [Demonstration](https://pyth.herokuapp.com/?code=VE%3D.-Q%5D%0Ae%7CfgNTQ0&input=%5B1%2C+2%2C+2%2C+2%2C+5%2C+7%2C+10%2C+20%5D%0A%5B1%2C+1%2C+2%2C+3%2C+6%2C+6%2C+15%2C+21%2C+21%2C+22%5D&debug=0) **Explanation:** ``` VE=.-Q]<\n>e|fgNTQ0 Implicit: Q is the list of prices. VE For N in the list of budgets f Q Filter the list of prices gNT On the current person's budget being >= that price | 0 If there aren't any, use 0 instead. e Take the last (most expensive) value. <\n> Print it out. =.-Q Remove it from the list of prices. ``` [Answer] ## Haskell, 67 bytes ``` a#(b:c)|(h,t)<-span(<=b)a=last(0:h):(init(h++[0|h==[]])++t)#c _#x=x ``` Usage example: `[1,2,2,2,5,7,10,20] # [1,1,2,3,6,6,15,21,21,22]` -> `[1,0,2,2,5,2,10,20,7,0]`. Split the prices in two parts: `(h,t)` where `h` are all prices <= the budget of the next customer and `t` are all the others. Take the last price of `h` and continue recursively with all but the last of `h` plus `t` and the remaining budgets. `last(0:h)` evaluates to `0` if `h` is empty. Similar: `init (h++[0|h==[]]) ++ t` adds a dummy element `0` to `h` if `h` is empty, so that `init` has something to drop (`init` fails on the empty list). [Answer] ## Java, 154 \* 0.6 = 92.4 bytes *-13 bytes because the lambda can actually use `int[]`, not `Integer[]` (thanks [BunjiquoBianco](https://codegolf.stackexchange.com/users/52548/bunjiquobianco))* This should take O(n+m) time and O(n+m) additional space (assuming I understand big O notation). ``` g->b->{int l=g.length,L=b.length,G=0,B=0,A=0;int[]a=new int[l],s=new int[L];for(;B<L;){while(G<l&&g[G]<=b[B])a[A++]=g[G++];s[B++]=A>0?a[--A]:0;}return s;} ``` Indented: ([Try it online!](https://ideone.com/HTFBPA)) ``` static int[] toyStore(int[]g,int[]b) { int gl=g.length,bl=b.length,gp=0,bp=0,ap=0; int[] a=new int[gl],s=new int[bl]; for (;bp<bl;) { while(gp<gl&&g[gp]<=b[bp])a[ap++]=g[gp++]; s[bp++]=ap>0?a[--ap]:0; } return s; } public static void main(String[] args) { System.out.println(Arrays.toString( toyStore(new int[] {1,2,2,2,5,7,10,20}, new int[] {1,1,2,3,6,6,15,21,21,22}) )); } ``` I show the non-lambda expansion here because the type declaration is cleaner and it's the exact same logic. The lambda is present at the ideone link. ### Explanation: Variables used: * `g` is the list of gift prices, `b` is the list of budgets. * `gl` is the length of `g` and `bl` is the length of `b`. * `a` is a Stack for affordable gifts, `s` is the output array of sold gifts. * `gp`, `bp`, and `ap` are pointers for `g`, `b`, and `a` respectively. `bp` is also the pointer for `s`. Algorithm: * For each budget in the length of budgets + While this budget can buy the gift at `g[gp]` - Push the budget onto the Stack `a` and increment `gp` + Pop the top of `a` into `s[bp]` if it exists, else put `0`. [Answer] ## Haskell, 87 \* 0.6 = 52.2 bytes ``` g s(p:q)d@(b:c)|p<=b=g(p:s)q d g[]p(b:c)=0:g[]p c g(s:t)p(b:c)=s:g t p c g _ _ _=[] g[] ``` Completely different from my [other answer](https://codegolf.stackexchange.com/a/76412/34531), because I'm going for the bonus. The last line (-> `g[]`) is not part of the definition, but calling overhead. Usage example: `g [] [1,2,2,2,5,7,10,20] [1,1,2,3,6,6,15,21,21,22]` -> `[1,0,2,2,5,2,10,20,7,0]`. Works basically in the same way as [@CAD97's answer](https://codegolf.stackexchange.com/a/76422/34531), i.e. uses a (initially empty) helper stack to keep track of the buyable items. In detail: check in order: * if the first price is less or equal than the first budget, move the price to the stack. Call again. * if the stack is empty, return a 0 followed by a recursive call with the budget dropped. * if both stack and budget list are not empty, return the top of stack followed by a recursive call with stack & budget popped. * else return the empty list. This works in `m+n` time, because a) operations on the helper stack use constant time and b) in each of the recursive calls one of the lists is shortened by one element. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṀṄ;©®œ^ Rf@€ç/Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmA4bmEO8Kpwq7Fk14KUmZA4oKsw6cv4bmA&input=&args=MSwgMSwgMiwgMywgNiwgNiwgMTUsIDIxLCAyMSwgMjI+MSwgMiwgMiwgMiwgNSwgNywgMTAsIDIw) ### How it works ``` ṀṄ;©®œ^ Helper link. Arguments: G, H (lists of affordable gifts) Ṁ Compute the maximum of G (0 if the list is empty). Ṅ Print it. ; ® Concatenate it with the register (initially 0). © Save the result in the register. œ^ Compute the multiset symmetric difference of the updated register and H. Rf@€ç/Ṁ Main link. Arguments: B (budgets), P (prices) R Range; replace each t in B with [1, ..., t]. f@€ Intersect the list of prices with each budget range, obtaining, for each customer, the list of all gifts he's willing to pay for. ç/ Reduce the array of lists by the helper link. In each iteration, this computes and prints the most expensive gift for a customer, than removes the selected gift (and all previously selected gifts) from the next list. Ṁ Compute the maximum of the resulting list, which corresponds to the last customer. ``` [Answer] ## JavaScript, 85 \* 0.6 = 51 bytes ``` f=(a,b,s=[],[t,...u]=a,[v,...w]=b)=>v?t<=v?f(u,b,[...s,t]):[s.pop()|0,...f(a),w,s)]:[] ``` Another clone of @CAD97's answer. ]
[Question] [ You probably do know that the different reputation levels on Stack Exchange are formatted differently when seen from the questions page / a post. There're all the rep-formatting rules: * if a user has 1 to 999 (one to three digits) rep, it's left as-is. * if a user has 1000 to 9999 rep (four digits), it receives the comma as a separator: `9,999` * if a user has 10000 to 99999 rep (five digits), it's shortened and rounded. I.e., 16741 rep is formatted as `16.7k`, notice the dot separator unlike the comma for the lower rep (previous point). 1. 16750 will already result `16.8k` (since [this seems to be fixed](https://meta.stackexchange.com/questions/257634/the-rounding-bug-is-still-here)) 2. 16941 results in `16.9k`, 16950 rounds up to `17k`, as well as does 17014, for example. 3. 99941 rounds to `99.9k`, 99950 rounds to `100k` (this is something I actually hate with the rep-rounding on SE, because 100,000 is such a milestone, and 99950 is nowhere near). * If a user has 100000 to 999999 rep, it's rounded this way: 1. 100100 rounds down to `100k`, 100500 rounds up to `101k`. The thing is, the rounding is done, but the decimal part is stripped (unlike the four-digits rep). 2. 100450 rounds down to `100k`, no step to round 450 to 500. Nor does 100499 - it's still `100k`. 3. 279843 rounds up to `280k`, and 399999 rounds to `400k`. As input, you're given the raw reputation, and output it as formatted. You can consider that input **won't** receive any invalid numbers / non-numbers, or numbers with leading zeros, i.e. `0001234`. Because Jon Skeet doesn't seem to be reaching 1,000,000 soon, ~~your code must be as short as possible~~ you don't need to handle the rep greater than one million (i.e. no special cases for 999500 and above). [Answer] # JavaScript (ES6), ~~76~~ 68 bytes ``` x=>x<1e4?x.toLocaleString():(x<1e5?(x/1e2+.5|0)/10:(x/1e3+.5|0))+"k" ``` Another first attempt. Thank goodness for that handy `.toLocaleString()`, the shortest alternative I could find is 21 bytes longer... This separates thousands by either `,` or `.`, depending on what country you live in. For ~~five~~ two bytes more, you can make it always use a comma: ``` x=>x<1e4?x.toLocaleString`en`:(x<1e5?(x/1e2+.5|0)/10:(x/1e3+.5|0))+"k" ``` [Answer] # Japt, ~~50~~ 48 bytes First attempt; there may be a better method. ``` U<A³?U:U<L²?Us i1', :(U<1e5?Ue2n)r /A:Ue3n)r)+'k ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VTxBsz9VOlU8TLI/VXMgaTEnLCA6KFU8MWU1P1VlMm4pciAvQTpVZTNuKXIpKydr&input=MTY5NDE=) ### How it works ``` // Implicit: U = input integer, A = 10, L = 100 U<A³?U // If U is less than A³ (10³ = 1000), return U. :U<L²? // Else, if U is less than L² (100² = 10000), return: Us i1', // U.toString, with a comma inserted at position 1. :( // Else, return: U<1e5? // If U is less than 1e5: Ue2n) // U * (10 to the power of -2), r /A // rounded and divided by 10. :Ue3n)r) // Else: U * (10 to the power of -3), rounded. +'k // Either way, add a "k" to the end. // Implicit: output last expression ``` [Answer] # JavaScript (ES6), 71 ~~Beating @ETHProductions while he does not see my hint.~~ He saw it. ``` x=>x<1e3?x:x<1e4?(x+='')[0]+','+x.slice(1):(x/1e3).toFixed(x<99950)+'k' ``` **Test** ``` f=x=>x<1e3?x:x<1e4?(x+='')[0]+','+x.slice(1):(x/1e3).toFixed(x<99950)+'k' function test() { n=+I.value, O.textContent = n + ' -> ' + f(n) } test() ``` ``` <input id=I type=number value=19557 oninput=test()> <pre id=O></pre> ``` **Test** [Answer] ## ES6, ~~68~~ 62 bytes ``` x=>x<1e4?`${x}`.split(/(?=...)/)+"":x.toPrecision(3)/1e3+"k" ``` Edit: Saved 6 bytes when I realised that `["1", "001"]` stringifies to `"1,001"`. Edit: Saved 2 bytes to fix @Mwr247's comment! [Answer] # Python 2.7, 58 bytes ``` lambda x:['%.3g'%((x+.5)/1e3)+'k','{:,}'.format(x)][x<1e4] ``` I had to use `(x+.5)` to deal with the `16950->17k` case.. ]
[Question] [ # Background This is the first part of a 3-hole golf course on text processing. The over-arching idea is that if you take an input text and pipe it through the solutions to all three challenges (with a small amount of glue code), it will spit out a beautifully formatted paragraph. In this first challenge, your task is a hyphenate a piece of text using given hyphenation patterns. # Input Your program shall take two string inputs: a piece of text and a list of hyphenation patterns. The first input is simply a non-empty string of printable ASCII characters and spaces; it will not contain line breaks or tildes `~`. The second input is a comma-delimited list of words, which consist of tilde-delimited syllables of lowercase ASCII characters. An example is `ex~cel~lent,pro~gram~ming,abil~i~ties`. # Output Your program shall modify the first input in the following way. Any word (maximal substring of alphabetical ASCII characters) whose hyphenated lowercase version is found in the second input shall be replaced by that hyphenated version, but its case shall be preserved. With the above example list, if the text contains the word `Excellent`, it shall be replaced by `Ex~cel~lent`; however, `Excellently` shall *not* be modified. Your output shall be this modified string. # Detailed Rules and Scoring You can assume the following about the inputs: * The first input contains no tildes, and no leading, trailing or repeated spaces. It is not empty. * The second input contains at least one word, and each word in it contains at least two syllables. Each syllable is non-empty. * The second input does not contain a word that occurs as a syllable in another word. You can change the order of the two inputs, if desired, and optionally add one trailing newline to the output. You can write a function or a full program. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases These are listed in the format `1st input [newline] 2nd input [newline] output`. ``` Excellent programming abilities, you work excellently! ex~cel~lent,pro~gram~ming,abil~i~ties Ex~cel~lent pro~gram~ming abil~i~ties, you work excellently! Superman (sometimes incorrectly spelled "Super-man") is super #&%@ing strong. su~per,some~times,in~cor~rectly,spell~ing Superman (some~times in~cor~rectly spelled "Su~per-man") is su~per #&%@ing strong. IncONsISTent caPItalizATIon! in~con~sis~tent,cap~i~tal~iza~tion In~cON~sIS~Tent caP~I~tal~izA~TIon! Such short words. awk~ward Such short words. Digits123 are456cool789. dig~its,dig~i~tal,are~cool Dig~its123 are456cool789. magic magic ma~gic ma~gic ma~gic ``` Any possible hyphenation error in this challenge is due to [this hyphenation tool](http://www.ushuaia.pl/hyphen/?ln=en). [Answer] # [Retina](https://github.com/mbuettner/retina), 88 bytes ``` +is`(?<![a-z~])([a-z~]+)(?=([a-z]+)+[^a-z~].*(?<=[\n,]\1(?(2)!)(?<-2>~\2)+[\n,])) $1~ \n.* <empty> ``` For counting purposes, each line goes into a separate file, `\n` are replaced with actual newline characters and `<empty>` is an empty file. For convenience, you can run the above code from a single file (where `<empty>` is an empty line) if you use the `-s` interpreter flag. [Answer] # Pip, ~~60~~ 54 bytes ``` Fwa^`([A-Za-z]+)`O{aQ'~?'~w@++y}M(LCwQ_RM'~FIb^',Yv)|w ``` [GitHub repository for Pip](http://github.com/dloscutoff/pip) Takes inputs as command-line arguments (which necessitates quotes around input 1, assuming it contains spaces). No trailing newline is printed (add an `x` to the end of the program to add one). Somewhat ungolfed, with comments: ``` ; Split 1st input on runs of letters, including the separators in the results a^:`([A-Za-z]+)` ; Split 2nd input on commas b^:', ; Iterate over the words w in that list Fwa { ; Filter b for entries that match the current word (lowercase, with tildes removed) m:(LCw EQ _RM'~)FIb ; We expect this to be a list of 0 or 1 elements ; If it has one, m gets that element (the hyphenation pattern); if it's empty, m gets nil i:-1 m:m@i ; Map this function to each character of pattern m: if it's tilde, return tilde; ; otherwise, return corresponding character of w m:{aEQ'~ ? '~ w@++i}Mm ; Output the result, unless it was nil (falsey), in which case output the original word Om|w } ``` Sample run: ``` C:\Users\dlosc> pip.py hyphens.pip "IncONsISTent caPItalizATIon!" in~con~sis~tent,cap~i~tal~iza~tion In~cON~sIS~Tent caP~I~tal~izA~TIon! ``` [Answer] # Javascript ES6, ~~117~~ 141 chars ``` f=(t,p)=>p.split`,`.map(p=>t=t.replace(RegExp("((?:^|[^a-z])"+p.replace(/~/g,")(")+")(?=$|[^a-z])","ig"),(...x)=>x.slice(1,-2).join("~")))&&t ``` Test: ``` document.querySelector(".question pre").textContent.split("\n\n").map(t=>(t=t.split("\n"))&&f(t[0],t[1])==t[2]) // Array [ true, true, true, true, true ] ``` [Answer] # Javascript (ES6), ~~173~~ 169 Basic regex search and replace ``` (a,b)=>(b.split`,`.map(s=>a=a.replace(eval(`/(^|[^a-z])(${s.replace(/~/g,"")})(?=[^a-z]|$)/gi`),(_,n,o)=>(x=0,n+s.split``.map((q,i)=>(q=='~'&&++x?q:o[i-x])).join``))),a) ``` [Fiddle](http://jsfiddle.net/53jmt7df/1/) **Edit:** Fixed bug for test case `magic magic`, `ma~gic` [Answer] # Perl, 146 ``` $a=<>;$d=$_=~s/~//rg,$a=~s/(?<!\pL)$d(?!\pL)/h($&,$_)/gie for(split/,|\n/,<>); print$a; sub h{($g,$h)=@_;while($h=~/~/g){substr($g,"@-",0)='~'}$g} ``` Just a first attempt, lots of things can be shortened - will continue tomorrow! ]
[Question] [ # Introduction This challenge is inspired by [Grime](https://codegolf.stackexchange.com/a/47905/32014), my 2D pattern matching language. Basically, you are given a "grammar" that describes two-dimensional grids of characters, and your job is to generate a grid according to the grammar. In addition, the grid should be as small as possible in a certain weak sense. # Input Your input is a string containing lowercase ASCII characters and the symbols `|` and `-`. For simplicity, the input does not contain repeated lowercase characters. The string is a specification for a class of rectangular grids of characters, and it is parsed from left to right using a stack as follows. * Given a lowercase character `c`, push to the stack an `m×n` grid of the character `c`, for any `m, n ≥ 1`. * Given a pipe `|`, pop two grids `A` and `B` from the stack (`B` was on top), and push the grid `AB` obtained by concatenating `B` to the right of `A`. This requires that `A` and `B` have equal height. * Given a hyphen `-`, pop two grids `A` and `B` from the stack (`B` was on top), and push the grid `A/B` obtained by concatenating `B` to the bottom of `A`. This requires that `A` and `B` have equal width. It is guaranteed that for *some* choices of `m` and `n` made during the parsing process (which may be different for each letter), the input specification correctly describes some rectangle, which is left on the stack at the end. # Output Your output is a rectangular grid of characters specified by the input. The grid must be minimal in the sense that removing any row or column would make it invalid. You can return a newline-separated string (with or without a trailing newline), a 2D array of characters, or an array of strings, whichever is the most convenient format. Note that you are not required to process the input exactly as described above; the only important thing is that your output is correct. # Example Consider the specification ``` par-s||e- ``` First, we choose to push a `1×2` rectangle of `p`, and `1×1` rectangles of `a` and `r` (the reason for this will be clear later). Then, we pop the `a` and `r` rectangles, and push their vertical concatenation ``` a r ``` Next, we push a `1×2` rectangle of `s`, pop it and the above rectangle, and push their horizontal concatenation ``` as rs ``` Then we pop that rectangle and the `p` rectangle, and push their concatenation ``` pas prs ``` Finally, we push a `3×1` rectangle of `e`, pop it and the above rectangle, and push the vertical concatenation ``` pas prs eee ``` This is the output of the program, or at least one of the possibilities. Notice that even though ``` ppas ppas pprs eeee ``` is also generated by the specification, it is not a valid output, since many of the rows and columns could be removed. As a more subtle example, consider ``` co|m|p|il|e|r|- ``` This specification generates the rectangle ``` comp iler ``` which is a valid output. However, it also generates ``` commp iiler ``` which is valid too, since no single row or column can be removed without invalidating it. # Rules You can give a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Extra Test Cases You can use these to test your program. ``` Input: a Output: a Input: co|mp|l|-ex|i|f|-y| Example output: cccoy mplly exify Input: ja-r|g-o|ni-|ze|d-| Example output: jronze arondd ggoidd Input: un|co|p-yr|i|gh-t-ab|-|le-||- Example output: unnnnnnn coyriggl ppyrihhe ppyritte ppyriabe ``` [Answer] # K, ~~123~~ 110 bytes I used a similar approach to cardboard\_box's solution. ``` r:{y,x#,*|y};h:{t:(#x)|#y;r[t-#x;x],'r[t-#y]y};a:{(,x .|2#y),2_ y};*(){(a[{+h[+x;+y]}]x;a[h]x;(,,y),x)"-|"?y}/ ``` This program is a series of helper definitions followed by a tacit function which takes a string as a right argument. Reformatting for readability and assigning the final function as `f`: ``` r: {y,x#,*|y}; / repeat last row x times h: {t:(#x)|#y;r[t-#x;x],'r[t-#y;y]}; / append horizontal v: {+h[+x;+y]}; / append vertical a: {(,x[y@1;y@0]),2_ y}; / pop two values, concat f: *(){:[y="-";a[v;x]; y="|";a[h;x]; (,,y),x]}/; ``` Use example: ``` f "ja-r|g-o|ni-|ze|d-|" ("jronze" "aroidd" "ggoidd") ``` Tested using Kona, but it will also work in [oK](http://johnearnest.github.io/ok/index.html) if you replace the `:` in the definition of `f` with a `$`- k5 changed the syntax of "cond". A key point is recognizing that doing a vertical append is the transpose of the horizontal append of the transpose of both matrices. (See definition `v`.) I think there's still room to squeeze out a few characters here and there. If anyone is interested in a more detailed explanation I can provide one. ## edit: Updated the program at the top of this entry. Ungolfed version: ``` r: {y,x#,*|y}; / repeat row x times h: {t:(#x)|#y;r[t-#x;x],'r[t-#y;y]}; / append horizontal v: {+h[+x;+y]}; / append vertical a: {(,x .|2#y),2_ y}; / apply a concat f: *(){(a[v]x;a[h]x;(,,y),x)"-|"?y}/; ``` Notable length optimizations include the use of "dot apply" in `a`, replacing the "cond" with list indexing in `f` (less efficient, but shorter) and replacing terms of the form `a[b;c]` into `a[b]c` where permitted by grouping. Since I'm no longer using "cond" or any primitives which are different between k3 and k5 this version now works in oK without modification. [Answer] # Prolog, 539 bytes ``` :-lib(ic). :-lib(util). b(A,B,C):-between(A,B,C). g(S):-string_list(S,L),p(L,[]). w(h(L,R):_:_,I,J):-w(L,I,J);L=_:W:_,X is I-W,w(R,X,J). w(v(U,D):_:_,I,J):-w(U,I,J);U=_:_:H,Y is J-H,w(D,I,Y). w(f(C):W:H,I,J):-b(1,W,I),b(1,H,J),char_code(S,C),put_char(S). p([],[S]):-term_variables(S,V),S=_:X:Y,labeling(V),!,b(1,Y,J),(b(1,X,I),w(S,I,J);nl),fail. p([124|T],[Q,Z|R]):-!,Q=_:WA:H,Z=_:WB:H,W #= WA+WB,p(T,[h(Z,Q):W:H|R]). p([45|T],[Q,Z|R]):-!,Q=_:W:HA,Z=_:W:HB,H #= HA+HB,p(T,[v(Z,Q):W:H|R]). p([C|T],R):-!,[H,W] #:: 1..100,p(T,[f(C):W:H|R]). ``` # Explanation We start with predicate `g`, which takes a string, convert it as a list of chars and call the `p` (parse) predicate with an empty stack as a second argument. Predicate `p` calls itself recursively with an appropriately modified stack (look for `[H|T]` destructuring and constructor patterns). When called on the base case, where the input list is empty, `p` prints the unique element of the stack. If the stack has less or more than one element at this point, it means that we have an empty input string, a bad input string or a bug (with an emtpy string, the predicate fails (Prolog says `No`), but nothing is printed, which is ok, since we should not print anything for empty strings). ### Solving The stack contains a description of the constructed rectangles, denoted `S:W:H`, where `S` is a symbolic representation of the rectangle, `W` its width and `H` its height (note, `A:B` is syntactic sugar for the `:(A,B)` tuple with a functor named `:`; it is just shorter to write than having a tuple with prefix notation). With `A` and `B` sub-rectangle specifications, `S` can be either: * `h(A,B)` : horizontal concat of A and B * `v(A,B)` : vertical concat of A and B * `f(C)` : fill with C, where C is a character code Widths and heights of grids are constraint-programming variables: during vertical (resp. horizontal) concatenation, the width (resp. height) of the manipulated rectangles are unified, whereas the resulting height (resp. width) is constrained to be the sum of each subgrid's height (resp. width). The labeling step at the end of the process instanciates variables while respecting constraints, using the minimal possible values (this is a property of the order by which solutions are tried). I might have obtained a shorter answer using the same reasonning that is done in other answers, without constraints, but this is too late now. Note also that because the default domain for variables is set to `1..100`, there is a limitation over the possible sizes of grids. The upper-bound could be changed if needed. The performance implications of this are that it *could* take a lot of time to determine that a particular solution admits no solution. I said "*could*" because constraints are likely to drastically prune the exponential search. If you find an input string that is hard/costly to reject, please share. ### Printing The printing part is interesting because there is a kind of *ray-casting* algorithm over the structure: I iterate over each cell of the resulting grid, from point `(1,1)` to point `(W,H)` and call the `w` predicate to print the content of the grid in the main tree, at this location (of course, a newline is printed after processing each line). In `w`, positions are relative to current grid (the root grid defines absolute coordinates). When printing a `h(A,B)` structure at point `(X,Y)`, I unconditionnaly print in both branches: * in grid `A` at point `(X,Y)`, and * in grid `B` at point `(H,Y)`, where `H` is `X` minus the width of `A`. The leaf branches of the grid-tree, `f(C)`, finally either print the character `C`, if the relative location is inside the grid, or do nothing. This is how I can print the content of grid to the output stream, from top to bottom, from left to right. No actual arrays are produced. # Tests ``` t("ja-r|g-o|ni-|ze|d-|"). t("un|co|p-yr|i|gh-t-ab|-|le-||-"). t("co|mp|l|-ex|i|f|-y|"). t("a"). tt :- t(X),nl,g(X). tt. ``` Running test: ``` [eclipse] tt. jronze aronze ggoidd uuuuuuun coyriggl coyrihhl coyrittl ppyriabe cccoy mmply exify a Yes (0.00s cpu) ``` [Answer] # Python 2.7, 259 ``` z=zip def p(a,b): s,l=sorted([a,b],key=len) s+=([s[-1]]*(len(l)-len(s))) return z(*(z(*a)+z(*b))) g=lambda s,t=[]:s and(s[0]=='-'and g(s[1:],t[:-2]+[z(*p(z(*t[-2]),z(*t[-1])))])or(s[0]=='|'and g(s[1:],t[:-2]+[p(t[-2],t[-1])])or g(s[1:],t+[[s[0]]])))or t[0] ``` `g` is a function which takes a specification and gives a 2D array of characters. If you want a more user-friendly version, add this line to make it take a specification from stdin and print out the grid: ``` print'\n'.join(''.join(s)for s in g(raw_input())) ``` ## Test Cases ``` Input: a Output: a ========== Input: co|mp|l|-ex|i|f|-y| Output: coooy mplly exify ========== Input: ja-r|g-o|ni-|ze|d-| Output: jronze aroidd ggoidd ========== Input: un|co|p-yr|i|gh-t-ab|-|le-||- Output: unnnnnnn coyriggl ppyrihhe ppyritte ppyriabe ``` ## Explanation The strategy is simple: if a grid `G` is valid for a specification `S`, then repeating the rightmost column of `G` also gives a valid specification for `S`, and the same is true with repeating the bottom row (the proof of this is by structural induction on `S`). Therefore, when we want to concatenate two rectangles, we can simply append the last column/row of the smaller one until they match in size (this is what the function p does). [Answer] # Haskell, ~~388~~ ~~367~~ 352 bytes ``` data C=L{c::Char}|N{t::Int,w::Int,h::Int,l::C,r::C} q=replicate []#[x]=x (c:i)#(b:a:s)|c=='-'=i#(N 1(max(w a)$w b)(h a+h b)a b:s)|c=='|'=i#(N 2(w a+w b)(max(h a)$h b)a b:s) (c:i)#s=i#(N 0 1 1(L c)(L c):s) p i|t i==0=q(h i)$q(w i)$c$l i|t i==2=zipWith(++)(p(l i){h=h i})$p(r i){h=h i,w=w i-w(l i)}|1<2=p(l i){w=w i}++p(r i){w=w i,h=h i-h(l i)} f=p.(#[]) ``` Usage: `f "par-s||e-"` -> `["pas","prs","eee"]` Test run with pretty printing: ``` > putStr $ unlines $ f "par-s||e-" pas prs eee > putStr $ unlines $ f "co|m|p|il|e|r|-" comp iler > putStr $ unlines $ f "a" a > putStr $ unlines $ f "co|mp|l|-ex|i|f|-y|" coooy mplly exify > putStr $ unlines $ f "ja-r|g-o|ni-|ze|d-|" jronze aroidd ggoidd > putStr $ unlines $ f "un|co|p-yr|i|gh-t-ab|-|le-||-" unnnnnnn coyriggl ppyrihhe ppyritte ppyriabe ``` How it works: the function `#` parses the input string into the tree structure `C` which is either a leaf `L` holding the character to print or a node `N`. `N` can be a) a side-by-side join (`t==2`), b) a top-bottom join (`t==1`) or c) a single letter square (`t==0`). All nodes have a width and height field and a left and right child. After parsing, `p` prints the remaining root node by recursively adjusting the size (width x height) of it's child nodes and joining them. Edit: output as a list of lines instead of pretty printing [Answer] # JavaScript (ES6), 283 ~~295~~ **Edit** Now this (heavily golfed) JS solution is at least shorter than the reference (quite golfable) Python solution. Similar to cardboard\_box, just repeating the leftmost column or the topmost row. ``` F=w=>( s=[t=1,l='length'], [for(c of w)( b=s[t],a=s[--t], c>'z'? s[t]=(G=(a,b,m=b[l]-a[l])=>m?m>0?G([a[0],...a],b):G(a,[b[0],...b]):a.map((r,i)=>r+b[i]))(a,b) :c<'a'? s[t]=a.map(r=>r[m=b[0][l]-r[l],0].repeat(m>0&&m)+r).concat(b.map(r=>r[0].repeat(m<0&&-m)+r)) :s[t+=2]=[c] )], s[t].join('\n')) ``` **Ungolfed** This is my first, ungolfed solution. ``` F=sp=>{ s=[] for(c of sp){ a=s.pop(b=s.pop()) if (c > 'z') { l = a.length m = b.length for(; l-m ;) l < m ? l = a.unshift(a[0]) : m = b.unshift(b[0]) s.push(a.map((r,i) => r + b[i])) } else if (c < 'a') { l = a[0].length m = b[0].length s.push( a.map(r => r[0].repeat(l < m ? m-l : 0) + r) .concat(b.map( r => r[0].repeat( l > m ? l-m : 0) + r)) ) } else { s.push(a,b,[c]) } } return s.pop().join('\n') } ``` **Test** In Firefox/FireBug console ``` ;['par-s||e-','co|m|p|il|e|r|-','co|mp|l|-ex|i|f|-y|', 'ja-r|g-o|ni-|ze|d-|','un|co|p-yr|i|gh-t-ab|-|le-||-'] .forEach(w=>console.log(F(w))) ``` *Output* ``` pas prs eee comp iler cccoy mmply exify jronze aronze ggoidd uuuuuuun coyriggl coyrihhl coyrittl ppyriabe ``` [Answer] # Python 3, 251 bytes Here's the reference answer I promised, golfed a bit further. ``` T=lambda m:list(map(list,zip(*m))) E=lambda a,b:a[:1]*(len(b)-len(a))+a H=lambda a,b:[d+c for c,d in zip(E(a,b),E(b,a))] s=[] for k in input():s=k>"z"and[H(*s[:2])]+s[2:]or k<"a"and[T(H(*map(T,s[:2])))]+s[2:]or[[[k]]]+s for r in s[0]:print("".join(r)) ``` This is a full program that takes the string from STDIN and prints to STDOUT. The approach is the same as that of cardboard\_box: push a 1x1 array for a character, and duplicate rows if needed for concatenation. ``` $ echo "par-s||e-" | python3 gr.py pas prs eee ``` ## Detailed explanation * `T` transposes a given list of lists. The majority of the work is done by `zip(*m)` which swaps rows to columns, the rest is just converting the result into a list of lists, since `zip` returns a generator of tuples. * `E(a,b)` returns `a` with its first element repeated enough times to match the length of `b`. Note that multiplying a list by a negative number gives the empty list, so if `b` is shorter than `a`, this returns `a`. * `H(a,b)` returns the horizontal concatenation of `a` and `b`, the shorter one being lengthened by `E` if necessary. * `s` is the stack. * In the `for` loop, we iterate over the input string, and replace `s` by a new value: if it's `|` (greater than `z`), we pop two values and push their `H`, if it's `-` (lower than `a`), we pop two values, transpose, feed to `H`, transpose again and push the result, and otherwise push a 1x1 array with the letter. * Finally, we print the first element of `s`. ]
[Question] [ ## Challenge On each of the 12 days of Christmas, output the appropriate verse of "12 days of Christmas", according to the date, otherwise output the chorus of "I Wish It Could Be Christmas Everyday". Leading and/or trailing newlines (`\n`) and trailing spaces are permitted. You may not read from any external sources. Basically what you have to do is read the system date and output the according verse of the "12 days of Christmas". ## 12 Days of Christmas The Twelve Days of Christmas is the festive Christian season, beginning on Christmas Day (25 December) and ending on the 5th of January. ## Examples If the date is the 25th of December (print out the shortest/first verse): ``` On the first day of Christmas my true love sent to me: a Partridge in a Pear Tree ``` If the date is the 31st of December (print the seventh verse): ``` On the seventh day of Christmas my true love sent to me: 7 Swans a Swimming 6 Geese a Laying 5 Golden Rings 4 Calling Birds 3 French Hens 2 Turtle Doves and a Partridge in a Pear Tree ``` If the date is the 5th of January (print out the longest/last/12th verse): ``` On the twelth day of Christmas my true love sent to me: 12 Drummers Drumming 11 Pipers Piping 10 Lords a Leaping 9 Ladies Dancing 8 Maids a Milking 7 Swans a Swimming 6 Geese a Laying 5 Golden Rings 4 Calling Birds 3 French Hens 2 Turtle Doves and a Partridge in a Pear Tree ``` If the date is not within the range of 25th December to 5th January inclusive: ``` Well I wish it could be Christmas every day When the kids start singing and the band begins to play Oh I wish it could be Christmas every day So let the bells ring out for Christmas ``` ## Happy Christmas! ![](https://i.stack.imgur.com/0YI4q.jpg?s=128&g=1) [Answer] # CJam, ~~557~~ ~~550~~ ~~530~~ ~~528~~ ~~522~~ 519 bytes ``` et3<(;" Christmas":P;:(31b7+372%_C<{"On the ""first second third"S/"four fif six seven eigh nin ten eleven twelf"S/"th"f++@:X=" day of"P" my true love sent to me: ""and a Partridge in a Pear Tree."a[D,2>Sm*"Turtle Dove French Hen Calling Bird Golden Ring Geese a Lay Swans a Swimm Maids a Milk Ladies Danc Lords a Leap Pipers Pip Drummers Drumm"N/'s4*"ing"a7*+]z+X)<W%N*X!{4>}*}{;"Well"" I wish it could be"P" every day "++_"When the kids start singing and the band begins to play Oh"\"So let the bells ring out for"P}? ``` [Test it here.](http://cjam.aditsu.net/) To try out different dates, replace `et3<(;` with something like `[12 25]`. There's probably still room for improvement. ``` et "Read the current datetime as an array [year month day hour ...].": 3< "Discard hours, minutes etc."; (; "Discard year."; " Christmas":P; "Store the string in P and discard."; :( "Decrement month and day."; 31b "Interpret as base-31 digits. So on [12 25] we get 365 (what a coincidence). On [12 31] we get 371. On [1 1] we get 0. On [1 5] we get 4."; 7+ "Add 7."; 372% "Take modulo 372. Now the 12 days result in 0 to 11, others are greater."; _C< "Duplicate and check if it's less than 12."; {...}{...}? "Run the first block for the 12 days, the second block otherwise."; "On the 12 days:"; "On the " "Push the string."; "first ... third"S/ "Push first to third. Split by spaces."; "four ... telf"S/ "Push other ordinal numbers, split by spaces."; "th"f+ "Add th to each."; + "Append to get first to twelfth."; @:X "Pull day number to the top. Store in X."; = "Select ordinal number."; " day of"P "Push ` day of Christmas`."; "\nmy true...\n" "Push that string, too".; "and a Part..."a "Push day 1 string and wrap in array."; [ "Remember beginning of array."; D,2> "Push range [2 3 ... 12]."; Sm* "Append a space to each."; "Turtle..."N/ "Push all the gifts. Split into lines."; 's4* "Push `ssss`."; "ing"a7* "Push an array with 7 copies of `ing`."; + "Add the two."; ] "Close array, containing numbers, gifts and endings."; z "Zip/transpose the array."; + "Add day-1 line."; X) "Push day and decrement."; < "Slice off unwanted days."; W% "Reverse array."; N* "Join lines with line breaks."; X! "Logical not of day, is 1 on day 1 and 0 on all other days."; {4>}* "On day 1, remove first 4 characters (`and `)."; "On all days:"; ; "Discard day from stack."; "Well" "Push the string."; " I..."P"...day\n" "Push the rest of the line in 3 strings."; ++_ "Join those three into one, and duplicate."; "When...\nOh" "Push next line and `Oh`."; \ "Swap with duplicate line."; "So ... for"P "Push final line."; ``` [Answer] # Python 2, ~~681~~ ~~676~~ ~~673~~ ~~670~~ 667 bytes ``` import time N=time.localtime();D,M=N.tm_mday,N.tm_mon Q=((D<6>M<2)*(31+D)+(M>11)*D)-24 print["Well%sWhen the kids start singing and the band begins to play\nOh%sSo let the bells ring out for~"%((" I wish it could be~ every day\n",)*2),"On the %s day of~\nmy true love sent to me:\n"%("twel first second third four fif six seven eigh nin ten eleven".split()[Q%12]+"th"*(Q>3))+"\n".join("%d %s"%(i,"Turtle Doves$French Hens$Calling Birds$Golden Rings$Geese a Lay$Swans a Swimm$Maids a Milk$Ladies Danc$Lords a Leap$Pipers Pip$Drummers Drumm".split("$")[i-2]+"ing"*(i>5))for i in range(Q,1,-1))+"\nand "*(Q>1)+"a Partridge in a Pear Tree"][Q>0].replace("~"," Christmas") ``` I tried competing against CJam... and failed as expected. Maybe if I could figure out how to zlib, but I dunno... (Thanks to @FryAmTheEggman for suggestions via chat) [Answer] It's big! It's mean! It's ugly! It's... # Java: ~~894 887 883~~ 882 bytes Golfed: ``` class C{public static void main(String[]a){java.util.Calendar d=java.util.Calendar.getInstance();String p="a Partridge in a Pear Tree\n",t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z","I wish it could be X every day"),r="";String[]s=(" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y","ing").split("ç");int n=d.get(d.DAY_OF_YEAR),o=(n>358)?(n-358):(n<6)?(n+7):-1,j;if(o==-1)r=t;else{r+=("On the "+s[o]+s[0]);for(j=o+11;j-->12;r+=(j-11+s[j]));r+=(o!=1)?"and "+p:p;}System.out.print(r.replaceAll("X","Christmas"));}} ``` Ungolfed: ``` class C { public static void main(String[] a) { java.util.Calendar d = java.util.Calendar.getInstance(); String p = "a Partridge in a Pear Tree\n", t = "Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z", "I wish it could be X every day"), r = ""; String[] s = (" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y", "ing").split("ç"); int n = d.get(d.DAY_OF_YEAR), o = (n > 358) ? (n - 358) : (n < 6) ? (n + 7) : -1, j; if (o == -1) { r = t; } else { r += ("On the " + s[o] + s[0]); for (j = o + 11; j-- > 12; r += (j - 11 + s[j])); r += (o != 1) ? "and " + p : p; } System.out.print(r.replaceAll("X", "Christmas")); } } ``` After messing with it a lot and gaining 14 bytes, I think I'll stop fiddling with it. And yes, I know that, on leap years, my idea may have a bit of an issue, but... it was my way to cut a few bytes off the code. Oh well. [Answer] # Erlang, 748 bytes A 7-bit clean version without gzip-9 is 748 bytes: ``` f()->[maps:get(C,#{$N=>"ing",$x=>10,$q=>"th",$z=>" Christmas"},C)||C<-s(t(calendar:local_time()))]. t({{_,1,D},_})->D+7;t({{_,12,D},_})->D-24;t(_)->1. s(X)when X<1;X>12->L=" I wish it could bez every dayx","Well"++L++"When qe kids start sNN and qe band begins to playxOh"++L++"So let qe bells rN out forz"; s(I)->"On qe "++element(I,{"first","second","qird","fourq","fifq","sixq","sevenq","eighq","ninq","tenq","elevenq","twelq"})++" day ofzxmy true love sent to me:x"++r(I). r(0)->"";r(I)->element(I,{"a Partridge in a Pear Tree","2 Turtle Dovesxand ","3 French Hensx","4 CallN Birdsx","5 Golden RNsx","6 Geese a LayNx","7 Swans a SwimmNx","8 Maids a MilkNx","9 Ladies DancNx","10 Lords a LeapNx","11 Pipers PipNx","12 Drummers DrummNx"})++r(I-1). ``` A gzip-9+base64 solution is 750 bytes long: ``` f()->s(t(calendar:local_time())). t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1. s(I)->try element(I,binary_to_term(base64:decode("g1AAAAkQeNrdlF9OGzEQxsNrJF44wXeEhtK/jyUqRQoCARLPTnYSW+u1oxlv0jz3BL1C71D1Cj1C79BDtOOQhQqpCKv0D5VW8u5a883vmxnbbte9jxfkPQ6xdGLhEiax9RXGhH3LTlJjBLQgXqEyq/6FpYBkCbWrBJIMJ4gLM31gQrXeGueXMek/QYqYe407tnfNcBbhKV0KKZiAs3ZsE6aRryPq3unxJcnUsaQcijj9QbHfrJC4Jfi4IAiFlGEaetk3OFFsdtWM4AL0kwzjnInqHm1EhSZRXdxU/bnoLs5bTp4w1B3p5xLcloc3eZJ1XJLmMV4zhYnFGwpSmvRdV7GoUbYg6x72jfe5D68UV36N4v1V36ZFEE9wEH2l43eqIHK/TB+6tru3RUxPcUAkpGIjs1KW3wr56Wo2F4pQgvkMZ0ujp9Ho6pomg/5R8s8bcnIzWwT+HEcmXzQGR87XGfNvW/mysRJcWQteKFzlSDA0YZIh/z1rX7s7qXC6Bo8wiry2MiIzz5gPwO23biZ98XEaDHDi5sSSl8z5ICuwtdP1e0m+zP8uhtw2Ta7A+mVdg/+hKN8Bkz8M5Q==")))catch _:_->s(1)end. ``` An UTF-8 encoded Erlang function is 421 characters (935 bytes). ``` f()->s(t(calendar:local_time())). t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1. s(I)->try element(I,binary_to_term(<<<<(C-$㐀):14>>||C<-"哔㐀㐤䑸檷䵅焸伱㠱怶悑券摝汈佊玏㵊塐專㔒染孡㵯徵峆䫽㳳欄捐拵㟔㸽䒻焄䋓垐啂庐嚯栏奕挮浫柍濦斝憻䮽埅牃栺整䲸䔢仇椕斡㯜愹䙣㔭㘅溄暫玡乘㖐㶵廁㴠撞㰋䃟䨄㻗刚淥朞壽㖊娞泓拙母倅戒奴㸩娠㼷䶰䞦填显彻己㵲克㪐傊䈿䠛㭾悐戉压咀㲅夘䖧彤欸䡛㭭䨳吂焤擎䉲㷪㮛䡈䢙䕝欕䏛宠拎䫓巣㝐凩淄應东歹墝䧉㾘敞䃡䲜䡬㹒媽㧕勆屑憈䊱濚䇷扃滱䕝犍沿䥝犙㤐䟜㔇檗坷庈㬫焰厺憮潴䤱䍱䐉㹆㲎杒妷撯宥帶㧢夈㿤䁧䛨湽㮣庚㶠珥㯋䌛傜圵怓爜䗉姳䐙㯎槆匶煯液恄姅堭刨䬹䢃㓑喒㱿柖慾漻幜㾠丼撊挭圢㳏䎘㟰䋛冸婽灜䖠旃囦攤嵼柤含怭儿䧭㶾朿曨佰橍徰䎦䥶㟿届䇰㩌猌浀㐀㐀㐀">>))catch _:_->s(1)end. ``` [Answer] # Javascript (665) ``` __=new Date("12/31");M=_.getMonth();D=_.getDate();d=M?(M==11)*(D-24):D+7;if(!d||d>12)s="Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g,"I wish it could be Christmas every day");else{for(s="On the "+"0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d]+" day of Chirstmas\nmy true love sent to me:";--d;)s+="\n"+(d+1)+" "+"0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z","ing");s+="\n"+(D!=25?"and ":"")+"a Partridge in a Pear Tree"}alert(s) ``` You can test it by adding parentheses to the first `new Date` i.e. change: ``` _=new Date;M=_... ``` to ``` _=new Date("1/5");M=_... ``` Here it is beautified: ``` _ = new Date("12/31"); M = _.getMonth(); D = _.getDate(); d = M ? (M == 11) * (D - 24) : D + 7; if (!d || d > 12) s = "Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g, "I wish it could be Christmas every day"); else { for (s = "On the " + "0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d] + " day of Chirstmas\nmy true love sent to me:"; --d;) s += "\n" + (d + 1) + " " + "0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z", "ing"); s += "\n" + (D != 25 ? "and " : "") + "a Partridge in a Pear Tree" } alert(s) ``` [Answer] # C# In Linqpad - 866 bytes Well, at least it beat Java ;) Leap years are handled inside the code. **Unformated:** ``` void Main(){var w=DateTime.Now;int y=w.Year%4,d=w.DayOfYear,c=0,p=0;string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"),o="On the ",x=" day of Christmas\nmy true love sent to me:\n";string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"},b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n","7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"};if(y==0){p=1;}if(d>358){c=d-358-p;}else if(d<6){c=d+7;}else{t.Dump();return;}if(c==1){o+=z[0]+x+b[0];}else{o+=z[c-1]+x;for(int i=c;i>=0;i--){o+=b[i];}}o.Dump();} ``` **Formatted:** ``` void Main() { var w=DateTime.Now; int y=w.Year%4,d=w.DayOfYear,c=0,p=0; string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"), o="On the ",x=" day of Christmas\nmy true love sent to me:\n"; string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"}, b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n", "7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"}; if(y==0) { p=1; } if(d>358) { c=d-358-p; } else if(d<6) { c=d+7; } else { t.Dump(); return; } if(c==1) { o+=z[0]+x+b[0]; } else { o+=z[c-1]+x; for(int i=c;i>=0;i--) { o+=b[i]; } } o.Dump(); } ``` ]
[Question] [ On some old Nokia phones, there was a variation of the [fifteen puzzle](https://codegolf.stackexchange.com/questions/6884/solve-the-15-puzzle-the-tile-sliding-puzzle) called Rotation. In this variation, instead of sliding one tile at a time, you rotated four tiles at a time in one direction. In this game, you'd start out with a board like this: ``` 4 9 2 3 5 7 8 1 6 ``` And by rotating the lower-left block twice clockwise and the upper-left block once clockwise, you'd get this: ``` 4 9 2 8 3 7 1 5 6 4 9 2 1 8 7 3 5 6 1 4 2 8 9 7 3 5 6 ``` and the `1` tile would be in the top-left corner where it's supposed to be. Eventually, after a few more moves, you'd end up with: ``` 1 2 3 4 5 6 7 8 9 ``` which is the "original" configuration. Your task is to build a program that will take as input a 3x3 grid of numbers from 1 to 9 (in any format you choose) and return as output a sequence of moves representing the moves you must take to return the board back to its original configuration (again, in any format you choose). The legal moves are defined as moving the [top/bottom]-[left/right] block of 4 tiles [clockwise/counterclockwise]. Your program must be able to solve all possible 3x3 grids (all permutations are solvable). The shortest code to do this wins. [Answer] # GolfScript, 39/83 bytes ``` # Optimized for size: {.4rand.p.2/+>`{?1420344440`=}+$..$>}do # Optimized for speed: 6,(7++:t;~{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`* ``` ### Speed vs size The size-optimized version randomly chooses clockwise rotations until the desired permutation is achieved. This is sufficient, since a counterclockwise rotation is equivalent to three consecutive clockwise rotations of the same square. The speed-optimized version does the same, except for the following: 1. If the number 1 is in the upper left corner, it doesn't rotate the upper left square anymore. 2. If the number 9 is in the lower right corner, it doesn't rotate the lower right square anymore. 3. The steps for swapping positions 7 and 8 are hardcoded, so there are two positions that allow the loop to break. Aside from changing the algorithm, the speed-optimized version achieves the rotation in a straightforward manner, while the size-optimed version uses GolfScript's built-in sort by mapping. It also hardcodes the final state (for comparison) instead of sorting the state in every iteration. The speed-optimized version requires fewer iterations and every iteration is much faster by itself. ### Benchmarks I have used the following code to randomize the positions of the numbers and perform test runs, uncommenting the line corresponding to the version to be tested: ``` [{[ 0:c;10,1>{;2 32?rand}$ #{c):c;.4rand.2/+>`{?1420344440`=}+$..$>}do #6,(7++:t;{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`* ],c+}\~*] $.0='Min: '\+puts .-1='Max: '\+puts ..{+}*\,/'Avg: '\+puts .,2/='Med: '\+ ``` The output shows the minimum and maximum number of steps it took to order the numbers, the the average and the median of all runs, as well as the elapsed time in seconds: ``` $ TIME='\n%e s' time golfscript rotation-test-size.gs <<< 100 Min: 4652 Max: 2187030 Avg: 346668 Med: 216888 21500.10 s $ $ TIME='\n%e s' time golfscript rotation-test-speed.gs <<< 1000 Min: 26 Max: 23963 Avg: 3036 Med: 2150 202.62 s ``` On my machine (Intel Core i7-3770), the mean execution time of the size-optimized version was 3.58 minutes. **The mean execution time of the speed-optimized version was 0.20 seconds. Thus, the speed-optimized version is approximately 1075 times faster.** The speed-optimized version yields 114 times less rotations. Performing each rotation is 9.4 times slower, which is mainly due to how the state is updated. ### I/O The output consists of 3-bit numbers. The MSB is set for counterclockwise rotations, the middle bit is set for lower squares and the LSB is set for right squares. Thus, 0 (4) is the upper left square, 1 (5) the upper right one, 2 (6) the lower left and 3 (7) the lower right one. The speed-optimized version prints all rotations on a single line. The size-optimized version prints one rotation per line, followed by the final position of the numbers. For the speed-optimized version, the input has to yield an array containing the numbers from 1 to 9 when evaluated. For the size-optimized version, the input has to be a string without final newline; it does not get evaluated. Example runs: ``` $ echo -n '253169748' | golfscript rotation-size.gs 3 0 123456789 $ golfscript rotation-speed.gs <<< '[5 4 7 1 2 9 3 8 6]' 2210300121312212222212211121122211122221211111122211211222112230764 ``` ### Size-optimized code ``` { # . # Duplicate the state. 4rand # Push a randomly chosen integers between 0 and 3. .p # Print that integer. .2/+ # Add 1 to it if it is grater than one. Possible results: 0, 1, 3, 4 >` # Slice the state at the above index. { # Push a code block doing the following: ? # Get the index of the element of the iteration in the sliced state. 1420344440` # Push the string "14020344440". = # Retrieve the element at the position of the computed index. }+ # Concatenate the code block with the sliced state. $ # Sort the state according to the above code block. See below. ..$> # Push two copies of the state, sort the second and compare the arrays. }do # If the state is not sorted, repeat the loop. ``` Updating the state is achieved in the following fashion: Rotation 2 yields the integer 3 after adding 1. If the state is “123456789”, slicing the state yields “456789”. Right before executing “$”, the topmost elements of the stack are: ``` [ 1 2 3 4 5 6 7 8 9 ] { [ 4 5 6 7 8 9 ] ? "1420344440" = } ``` “$” executes the block once for every element of the array to be sorted, after pushing the element itself. The index of 1 in “[ 4 5 6 7 8 9 ]” is -1 (not present), so the last element of "1420344440" is pushed. This yields 48, the ASCII code corresponding to the character 0. For 2 and 3, 48 gets pushed as well. The integers pushed for 4, 5, 6, 7, 8 and 9 are 49, 52, 50, 48, 51 and 52. After sorting, the first element of the state will be one of the elements yielding 48; the last will be one of those yielding 52. The built-in sort is unstable in general, but I've verified empirically that it is stable in this particular case. The result is “[ 1 2 3 7 4 6 8 5 9 ]”, which corresponds to a clockwise rotation of the lower left square. ### Speed-optimized code ``` 6,(7++:t; # Save [ 1 2 3 4 5 7 ] in variable “t” and discard it. ~ # Interpret the input string. { # :s # Duplicate the current state. (1= # Unshift the first element and push 1 if it is equal to 1 and 0 otherwise. .@ # Duplicate the boolean and rotate the unshifted array on top of it. 7=9= # Push 1 if the eighth element of “s” is equal to 9 and 0 otherwise. +4\- # Add the booleans and subtract their sum from 4. rand # Push a randomly chosen integers between 0 and the result from above. +. # Add this integer to the first boolean and duplicate it for the output. .2/+ # Add 1 to the result if it is grater than one. Possible results: 0, 1, 3, 4 @. # Rotate the state on top of the stack and duplicate it. @>:s # Slice the state at the integer from above and save the result in “s”. ^ # Compute the symmetric difference of state and sliced state. [ # Apply a clockwise rotation to the sliced array: 3s= # The fourth element becomes the first. 0s= # The first element becomes the second. 2s= # The third element remains the same. 4s= # The fifth element becomes the fourth. 1s= # The second element becomes the fifth. ] # Collect the results into an array. + # Concatenate with array of elements preceding the slice. s| # Perform set union to add the remaining elements of “s”. . # Duplicate the updated state. )9< # Pop the last element; push 0 if it is equal to 9 and 1 otherwise. \t # Swap the popped state on top and push [ 1 2 3 4 5 7 ]. > # Push 0 if the state begins with [ 1 2 3 4 5 6 ] and 1 otherwise. | # Take the logical OR of the booleans. }do # If the resulting boolean is 1, repeat the loop. .$ # Duplicate the state and sort it. >30764`* # If the state was not sorted, 7 and 8 are swapped, so push "30764". ``` Observe that the rotations 3, 0, 7, 6 and 4 swap the elements in positions 7 and 8, without altering the positions of the remaining seven elements. [Answer] # Python with Numpy – 158 ``` from numpy import* A=input() while any(A.flat>range(1,10)):i,j,k=random.randint(0,2,3);A[i:i+2,j:j+2]=rot90(A[i:i+2,j:j+2],1+2*k);print"tb"[i]+"lr"[j]+"wc"[k] ``` Input has to be of the following format: ``` array([[1,2,5],[4,3,6],[7,8,9]]) ``` Each output line is a move encoded in strings like `trw` or `blc` and to be read as follows: * `t`: top * `b`: bottom * `l`: left * `r`: right * `c`: clockwise * `w`: counter-clockwise (widdershins) --- This program performs random moves until the target configuration is reached. Under the approximative assumption that every move has an independent probability of 1/9! to hit the target configuration¹, the number of rotations before a solution is exponentially distributed with a mean (i.e., the average number of moves) of 9! ≈ 3.6·10⁵. This is in accordance with a short experiment (20 runs). ¹ 9! being the total number of configurations. [Answer] # C++ fewest moves solution -- breadth first (1847 chars.) After a bit more thought, I think I have this done much more efficiently and more sensibly. This solution, while it is certainly not winning this golf, is so far the only one that will attempt to find the shortest number of rotations that will solve the board. So far, it solves every random board I've thrown at it in nine or fewer moves. It also performs significantly better than my last one and, hopefully, addresses Dennis's comments below. From the previous solution, the largest change was to move the key history from the board state (BS) into a new class that stores the history at a given depth (DKH). Any time the application makes a move, it checks the history at that depth and all depths prior to see if it's ever been evaluated, if so, it won't be added to the queue again. This seems to significantly reduce the storage on the queue (by removing all this history from the board state itself) and therefore reduces pretty much all the stupid pruning I had to do to keep the code from running out of memory. Plus it runs a lot faster since there is much less to copy onto the queue. Now, it's a simple breadth first search on the various board states. Plus, as it turns out, my want to change the key set (currently stored as set of numbers in base-9, each of which are computed by BS::key as the base-9 representation of the board) over to a bitset having 9! bits seems to be needless; though I did find out how to compute a key in the "factorial number system" which could have been used to compute the bit in the bitset to test/toggle. So, the newest solution is: ``` #include <iostream> #include <list> #include <set> #include <vector> using namespace std; struct BS{ #define LPB(i) for(int*i=b;i-b<9;i++) struct ROP{int t, d;}; typedef vector<ROP> SV; typedef unsigned int KEY; typedef set<KEY> KH; BS(const int*d){const int*x=d;int*y=b;for(;x-d<9;x++,y++)*y=*x;} BS(){LPB(i)*i=i-b+1;} bool solved(){LPB(i)if(i-b+1!=*i)return 0;return 1;} void rot(int t, int d){return rot((ROP){t,d});} void rot(ROP r){rotb(r);s.push_back(r);} bool undo(){if (s.empty())return false;ROP &u=s.back();u.d*=-1;rotb(u);s.pop_back();return true;} SV &sol(){return s;} KEY key(){KEY rv=0;LPB(i){rv*=9;rv+=*i-1;}return rv;} int b[9]; SV s; void rotb(ROP r){int c=r.t<2?r.t:r.t+1;int bi=(r.d>0?3:4)+c;const int*ri=r.d>0?(const int[]){0,1,4}:(const int[]){1,0,3};for(int i=0;i<3;i++)swap(b[bi],b[c+ri[i]]);} }; ostream &operator<<(ostream &o, BS::ROP r){static const char *s[]={"tl","tr","bl","br"};o<<s[r.t]<<(r.d<0?"w":"c");return o;} struct DKH{ ~DKH(){for(HV::iterator i=h.begin();i<h.end();++i)if(*i!=NULL)delete *i;} void add(int d,BS b){h.resize(d+1);if(h[d]==NULL)h[d]=new BS::KH();h[d]->insert(b.key());} bool exists(BS &b){BS::KEY k=b.key();size_t d=min(b.sol().size(),h.size()-1);do if (h[d]->find(k)!=h[d]->end())return true;while(d--!=0);return false;} typedef vector<BS::KH *> HV;HV h; }; static bool solve(BS &b) { const BS::ROP v[8]={{0,-1},{0,1},{1,-1},{1,1},{2,-1},{2,1},{3,-1},{3,1}}; DKH h;h.add(0,b); list<BS> q;q.push_back(b); while (!q.empty()) { BS qb=q.front();q.pop_front(); if (qb.solved()){b=qb;return true;} int d=qb.sol().size()+1; for (int m=0;m<8;++m){qb.rot(v[m]);if (!h.exists(qb)){h.add(d,qb);q.push_back(qb);}qb.undo();} } return false; } int main() { BS b((const int[]){4,9,2,3,5,7,8,1,6}); if (solve(b)){BS::SV s=b.sol();for(BS::SV::iterator i=s.begin();i!=s.end();++i)cout<<*i<<" ";cout<<endl;} } ``` [Answer] # CJam - 39 ``` l{4mr_o_1>+_@m<_[Z0Y4X]\f=\5>+m>__$>}g; ``` Another random solver :) It takes a string such as 492357816 and outputs a (long) series of digits from 0 to 3, each representing a clockwise rotation of a block: 0=top-left, 1=top-right, 2=bottom-left, 3=bottom-right. Brief explanation: `4mr` generates a random number from 0 to 3 `_1>+` increments the number if it's greater than 1 (so we end up with 0, 1, 3 or 4 - the starting indexes of the 4 blocks) `m<` rotates the string to the left (such as 492357816 -> 923578164, not the block rotation) in order to bring the block to rotate in the first position `[Z0Y4X]\f=` does the block rotation which affects the first 5 characters, such as 12345 -> 41352; X=1, Y=2, Z=3 so [Z0Y4X] is actually [3 0 2 4 1] and those are the 0-based indexes of the rotated tiles `5>` copies the rest of the string `m>` rotates the (modified) string back to the right `__$>` checks if the string is sorted (it's the stopping condition) [Answer] # Mathematica, 104 chars We can interpret the task in the language of permutation groups. The four rotations are just four permutations that generate the symmetric group S9, and the task is just to write a permutation as a product of the generators. Mathematica has a built-in function to do this. ``` i={1,2,5,4};GroupElementToWord[PermutationGroup[Cycles/@({i}+#&/@i-1)],Input[]~FindPermutation~Range@9] ``` **Example:** Input: ``` {4, 9, 2, 8, 3, 7, 1, 5, 6} ``` Output: ``` {-2, -3, -4, 2, 4, 1, 4, -1, -2, 3, 2, -4, 3, 4, -3, -3, -4, -4, -2, -2, -3, -2, 3, -1} ``` * `1`: top-left clockwise * `2`: top-right clockwise * `3`: bottom-right clockwise * `4`: bottom-left clockwise * `-1`: top-left counterclockwise * `-2`: top-right counterclockwise * `-3`: bottom-right counterclockwise * `-4`: bottom-left counterclockwise ]
[Question] [ Suppose we define an infinite matrix `M`, on `N^2 -> {0, 1}` (where `N` starts from `1` instead of `0`) in this manner: * `M(1, 1)` = `0`. * For every `x > 1`, `M(x, 1)` = `1` if `x` is prime, and `0` otherwise. * For every `y > 1`, `M(1, y)` = the `y`th term in the `Thue-Morse sequence`. * For every `x, y > 1`, `M(x, y)` = `M(x, y-1) + M(x-1, y) mod 2`. The top-left `16x16` section of this matrix looks like (with `x` being rows and `y` being columns): ``` 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 1 1 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1 1 1 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 0 1 1 1 1 1 0 0 0 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 0 1 0 1 1 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 0 1 1 0 1 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1 0 1 0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 1 ``` Your task is to build a program that will evaluate the value of an arbitrary entry in this matrix as accurately as possible. Your program will take two integers `x` and `y` as input, in any form you choose, and return `M(x, y)`, which will be either `0` or `1`. Your code may be written in any language, but must not exceed 64 kilobytes (65,536 bytes) of source code size or 2 MB (2,097,152 bytes) of total memory usage. Your program must start with empty memory (i.e. it cannot load data from somewhere else) and run independently for each input (that is, it may not store common data for multiple runs). Your program must also be able to evaluate all the entries in the top-left `8192x8192` square in a reasonable amount of time. The program that evaluates the most entries correctly in the top-left `8192 x 8192` square will be the winner, with shorter code acting as a tie-breaker. [Answer] # J - ~~42~~ 38 char Pretty fast, 100% accurate, and well within the memory constraints. ``` ([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<: ``` The strategy is as follows: we will calculate successive antidiagonals of this matrix, performing a pairwise XOR to move along and adding the current Thue-Morse and prime bits to the ends. We then pull the required digit out of the antidiagonal when we get there. Explanation by explosion: ``` ( )&<: NB. decrement each of x and y &( ) NB. apply the following function... + NB. ... (x-1)+(y-1) times... 0: NB. ... starting with a zero: 2 ~:/\ NB. pairwise XOR on the argument ,(p:>:)&# NB. append prime bit (is 1+length prime?) ~:/@#:@#@], NB. prepend TM bit (XOR of binary) [{ NB. take the x-th bit (at index x-1) ``` Usage of this verb is `x m y` for M(x, y) as specified in the question, where `m` is the verb. ``` 5 ([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<: 8 0 m =: ([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<: 1+i.16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 m/~ 1+i.16 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 1 1 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1 1 1 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 0 1 1 1 1 1 0 0 0 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 0 1 0 1 1 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 0 1 1 0 1 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1 0 1 0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 1 ``` To save keystrokes we don't try to tell if we still need more prime or Thue-Morse bits, so we compute the entire antidiagonal to get the bit we want. However, `8192 m 8192` still runs in less than 0.07 s and about 100 KiB on my modest laptop. [Answer] ## Mathematica – 100% accuracy, ~~223~~ ~~193~~ 189 bytes ``` f=(r=Array[0&,Max@##];For[s=2,s<=#+#2,++s,For[i=Max[1,s-#2],i<=Min[s-1,#],++i,j=s-i;r[[j]]=Which[i==1,PrimeQ@j,j==1,OddQ@Total@IntegerDigits[i-1,2],0<1,Xor@@r[[j-1;;j]]]]];If[r[[#2]],1,0])& ``` Here is a legible version: ``` f[x_,y_] := ( r = Array[0 &, Max[x,y]]; For[s = 2, s <= x + y, ++s, For[ i = Max[1, s - y], i <= Min[s - 1, x], ++i, j = s - i; r[[j]] = Which[ i == 1, PrimeQ@j, j == 1, OddQ@Total@IntegerDigits[i - 1, 2], 0 < 1, r[[j - 1]]~Xor~r[[j]] ] ] ]; If[r[[y]], 1, 0] ); ``` I basically precompute along diagonals of constant `x+y`. Features: * It's accurate. * It runs in `O(x*y)`. * `f[8192,8192]` takes about 400 seconds. I suppose there is room for improvement (maybe `RotateLeft` could replace the inner loop). * It only uses one array of up to `max(x,y)` intermediate results in memory. So there is no necessity to use more than about 32k (assuming 32-bit integers) for the algorithm itself (plus, whatever Mathematica uses). In fact, Mathematica uses 31M by itself on my system, but this works without an issue: ``` MemoryConstrained[f[8192, 8192], 2^21] ``` [Answer] # Python, 192 characters 100% accuracy, calculates M(8192,8192) in ~10 seconds on my machine. ``` R=range def M(X,Y): X+=1;c=[1]*X;r=[0] while len(r)<Y:r+=[i^1 for i in r] for i in R(2,X): if c[i]: for j in R(i+i,X,i):c[j]=0 r[0]=c[i] for i in R(1,Y):r[i]^=r[i-1] return r[Y-1] ``` [Answer] ## Perl, 137 Not to 'win' :-), but since there's no Perl here yet and code was written anyway, here it is. ``` sub f{($n,$m)=@_;@a=0;@a=(@a,map{0+!$_}@a)while@a<$n;for$k(2..$m){$p=0;O:{$k%$_?1:last O for 2..sqrt$k;$p=1}$p=$a[$_]^=$p for 1..$n-1}$p} ``` Takes several seconds if called `print f(8192,8192)`, stores single line of matrix in memory (array of 8192 integers (scalars)), about 3.5 Mb whole Perl process. I tried to do it with string instead of array (either with regexps or accessing with substr), takes less memory and can be golfed further, but runs much slower. Indented: ``` sub f{ ($n,$m)=@_; @a=0; # @a will be current line. @a=(@a,map{0+!$_}@a)while@a<$n; # Fill it with Thue-Morse sequence. for$k(2..$m){ # Repeat until required line number. $p=0; # Find out if current line number O:{ # is a prime. $k%$_?1:last O for 2..sqrt$k; $p=1 # Store result (0 or 1) in $p. } $p=$a[$_]^=$p for 1..$n-1 # XOR previous value in current position } # with $p and store in $p. $p # Return $p. } ``` [Answer] # Haskell, 223 ``` g n=div(filter(>=n)(iterate(*2)1)!!0)2 1%1=0>1 1%n=not$1%(n-g n) n%1=and[rem n x>0|x<-[2..n-1]] a%b=g[0<1]where g s|foldr seq(0>1)s=0<1|n==a+b=s!!(b-1)|0<1=g$n%1:zipWith x s(tail s)++[1%n]where n=length s+1 x p|p=not|0<1=id ``` this has fast runtime (5.7 seconds with `-O3`). memory wasn't checked yet, though it should be linear. this uses the diagonal algorithm seen here before. as far as speed is concerned, the only things that matter are the diagonal algorithm, `-O3` , and the `|foldr seq(0>1)s=0<1` guard, which makes the list strict. everything else is implemented rather inefficiently - prime checking is done by checking all the lesser numbers for division, the Morse sequence's elements are recomputed constantly. but it is still fast enough :-). ]
[Question] [ [Chomp](https://en.wikipedia.org/wiki/Chomp) is a two-player game with a setup of a rectangle of pieces. Each player takes a turn removing any piece, along with all pieces above it and to its right. Whoever takes the bottom-left piece loses. It can be proven fairly easily that the first player always has a winning move (except with a 1-by-1 rectangle); find it. 1. Input is the dimensions of the rectangle (two numbers) 2. Output is the location of the winning move (two numbers) 3. If there is more than one winning move, then you can output any of them. This is code golf; shortest code (any language) wins. # Examples *Note: The outputs are just the two numbers; the ASCII art below is just to demonstrate what the numbers mean.* Input: 5 3 (indices 1-based starting from lower-left corner) Output: 4 3 ``` XXX-- XXXXX XXXXX ``` Input: 4 4 Output: 2 2 ``` X--- X--- X--- XXXX ``` # Bonus Subtract 15 characters from your score if you output all of the winning moves. Each pair of numbers must be separated by a newline. [Answer] ## Python 2 3, 141-15=126 ``` def win(x,y):w([y]*x) w=lambda b,f=print:not[f(r+1,c+1)for r,p in enumerate(b)for c in range(p)if(r+c)*w(b[:r]+[min(i,c)for i in b[r:]],max)] ``` Brute-force minimax search. For every possible move, we recursively see if the opponent can win after we make that move. Pretty weakly golfed; someone else should be able to do much better. This feels like a job for APL. * `win` is the public interface. It takes the dimensions of the board, converts it to a board representation, and passes that to `w`. * `w` is the minimax algorithm. It takes a board state, tries all moves, builds a list whose elements correspond to winning moves, and returns True if the list is empty. With the default `f=print`, building the list has a side effect of printing the winning moves. The function name used to make more sense when it returned a list of winning moves, but then I moved the `not` in front of the list to save a space. * `for r,p in enumerate(b)for c in xrange(p) if(r+c)`: Iterate over all possible moves. `1 1` is treated as not a legal move, simplifying the base case a bit. * `b[:r]+[min(i,c)for i in b[r:]]`: Construct the state of the board after the move represented by coordinates `r` and `c`. * `w(b[:r]+[min(i,c)for i in b[r:]],max)`: Recurse to see whether the new state is a losing state. `max` is the shortest function I could find that would take two integer arguments and not complain. * `f(r+1,c+1)`: If `f` is print, prints the move. Whatever `f` is, it produces a value to pad the list length. * `not [...]`: `not` returns `True` for empty lists and `False` for nonempty. Original Python 2 code, completely ungolfed, including memoization to handle much larger inputs: ``` def win(x, y): for row, column in _win(Board([y]*x)): print row+1, column+1 class MemoDict(dict): def __init__(self, func): self.memofunc = func def __missing__(self, key): self[key] = retval = self.memofunc(key) return retval def memoize(func): return MemoDict(func).__getitem__ def _normalize(state): state = tuple(state) if 0 in state: state = state[:state.index(0)] return state class Board(object): def __init__(self, state): self.state = _normalize(state) def __eq__(self, other): if not isinstance(other, Board): return NotImplemented return self.state == other.state def __hash__(self): return hash(self.state) def after(self, move): row, column = move newstate = list(self.state) for i in xrange(row, len(newstate)): newstate[i] = min(newstate[i], column) return Board(newstate) def moves(self): for row, pieces in enumerate(self.state): for column in xrange(pieces): if (row, column) != (0, 0): yield row, column def lost(self): return self.state == (1,) @memoize def _win(board): return [move for move in board.moves() if not _win(board.after(move))] ``` Demo: ``` >>> for i in xrange(7, 11): ... for j in xrange(7, 11): ... print 'Dimensions: {} by {}'.format(i, j) ... win(i, j) ... Dimensions: 7 by 7 2 2 Dimensions: 7 by 8 3 3 Dimensions: 7 by 9 3 4 Dimensions: 7 by 10 2 3 Dimensions: 8 by 7 3 3 Dimensions: 8 by 8 2 2 Dimensions: 8 by 9 6 7 Dimensions: 8 by 10 4 9 5 6 Dimensions: 9 by 7 4 3 Dimensions: 9 by 8 7 6 Dimensions: 9 by 9 2 2 Dimensions: 9 by 10 7 8 9 5 Dimensions: 10 by 7 3 2 Dimensions: 10 by 8 6 5 9 4 Dimensions: 10 by 9 5 9 8 7 Dimensions: 10 by 10 2 2 ``` [Answer] ### GolfScript, 82 (108 97 characters - 15 bonus) ``` ~),1/{{:F$0=),{F\+}/}%}@(*(0*\{1${1$\{\(@<},=},{1$\{\(@>},+(-!},:Y!{.,/+0}*;}/;Y{.-1=.@?)' '@)n}/ ``` Since I didn't know for any heuristics this solution performs an exhaustive search over the solution space. You may try the code [online](http://golfscript.apphb.com/?c=OyI1IDMiCgp%2BKSwxL3t7OkYkMD0pLHtGXCt9L30lfUAoKigwKlx7MSR7MSRce1woQDx9LD19LHsxJFx7XChAPn0sKygtIX0sOlkhey4sLyswfSo7fS87WXsuLTE9LkA%2FKScgJ0Apbn0v&run=true). Although the implementation is very efficient the search space grows very fast with increasing input. Examples: ``` > 5 3 4 3 > 5 4 3 3 > 6 6 2 2 ``` As mentioned above the implementation does not rely on recursion but visits each node of the search space only once. Below you can find an annotated version of the code which describes the building blocks in more detail. The representation of a single board of size *w* \* *h* is given by a list of *w* numbers in the range *0* to *h*. Each number gives the amount of pieces in the corresponding column. Thus, a valid configuration is a list where the numbers are non-increasing from start to end (with any move you ensure that all columns to the right are at most as high as the chosen one). ``` ~ # Evaluate the input (stack is now w h) # BUILDING THE COMPLETE STATE SPACE # Iteratively builds the states starting with 1xh board, then 2xh board, ... ),1/ # Generate the array [[0] [1] ... [h]] which is the space for 1xh { # This loop is now ran w-1 times and each run adds all states for the # board with one additional column { # The {}/] block simply runs for each of the existing states :F$0= # Take the smallest entry (which has to be the last one) ), # For the last column all values 0..x are possible {F\+}/ # Append each of these values to the smaller state }% }@(* # The order ensures that the less occupied boards are first in the list. # Thus each game runs from the end of the list (where [h h ... h] is) to # the start (where [0 0 ... 0] is located). # RUN THROUGH THE SEARCH SPACE # The search algorithm therefore starts with the empty board and works through all # possible states by simply looping over this list. It builds a list of those states # which are known as non-winning states, i.e. those states where a player should # aim to end after the move ( # Skips the empty board (which is a winning configuration) 0*\ # and makes an empty list out of it (which will be the list of # known non-winning states (initially empty)) { # Loop over all possible states 1$ # Copy of the list of non-winning states { # Filter those which are not reachable from the current state, # because at least one column has more pieces that the current # board has 1$\{\(@<},= }, { # Filter those which are not reachable from the current state, # because no valid move exists 1$\{\(@>},+ # Filter those columns which are different between start and # end state (-! # If those columns are all of same height it is possible to move }, :Y # Assign the result (list of all non-winning states which are # reachable from the current configuration within one move) # to variable Y !{ # If Y is non-empty this one is a winning move, otherwise # add it to the list .,/+ 0 # Push dummy value }*; }/ ; # Discard the list (interesting data was saved to variable Y) # OUTPUT LOOP # Since the states were ordered the last one was the starting state. The list of # non-winning states were saved to variable Y each time, thus the winning moves # from the initial configuration is contained in this variable. Y{ # For each item in Y .-1=.@?) # Get the index (1-based) of the first non-h value ' ' # Append a space @) # Get the non-h value itself (plus one) n # Append a newline }/ ``` [Answer] # Perl 6: ~~113~~ 108 characters - 15 = 93 points This one was tough! Here's the uncached version, which is technically correct but will take a *very* long time for non-trivial inputs. ``` sub win(*@b){map ->\i,\j{$(i+1,j+1) if @b[i][j]&&!win @b[^i],@b[i..*].map({[.[^j]]})},(^@b X ^@b[0])[1..*]} ``` It works just like [@user2357112's Python implementation](https://codegolf.stackexchange.com/a/24794/15012) (upvote him/her, I couldn't have figured this out without his/her work!) except that win() takes a Chomp board (array) instead of a width and length. It can be used like: ``` loop { my ($y, $x) = get.words; .say for @(win [1 xx $x] xx $y) } ``` A version with memoization, which can actually handle decent inputs (not optimized for readability, though): ``` my %cache; sub win (*@b) { %cache{ join 2, map {($^e[$_]??1!!0 for ^@b[0]).join}, @b } //= map ->\i,\j{ $(i+1,j+1) if @b[i][j] and not win @b[^i], @b[i..*].map({[.[^(* min j)]]}).grep: +*; },(^@b X ^@b[0])[1..*] } ``` ]
[Question] [ A weird number is a number that the sum of proper divisors is greater than the number itself and no subset of proper divisors sum to that number. Examples: > > 70 is a weird number because its proper divisors (1, 2, 5, 7, 10, 14, and 35) sum to 74, which is greater than 70, and no combination of these numbers sum to 70. > > > 18 is not a weird number because its proper divisors (1, 2, 3, 4, 6, 9) sum to 25, which is greater than 18, but 3, 6, and 9 sum to 18. > > > Your task is to write the shortest program that inputs through std-in any number *n* and calculates and prints to a file or std-out the first *n* weird numbers with newline separation. No hard coding of the answers is allowed (sorry for not specifying this in the beginning). For more examples, see this page: <http://mathworld.wolfram.com/WeirdNumber.html> [Answer] # Haskell - 129 I'm sure there's lots to golf here, but since the competition seems low for now I'll throw this in. Don't try running this though, I managed to wait only the two first elements, third will start taking minutes. ``` (%)=filter w n=take n$e%[1..] e x=let d=((==0).mod x)%[1..x-1]in sum d>x&&all((/=x).sum)(i d) i[]=[[]] i(y:z)=map(y:)(i z)++(i z) ``` [Answer] # Mathematica ~~99~~ ~~94~~ 87 Spaces not needed. Slow!: ``` j = i = 0; While[j<#, i++; If[Union@Sign[Tr /@ Subsets@Most@Divisors@i-i]=={-1, 1}, j++; Print@i]]& ``` At the expense of a few chars this is a faster version that checks only even numbers and skips multiples of `6` that are never weird: ``` j = i = 0; While[j < #, i += 2; If[Mod[i, 6] != 0 && Union@Sign[Tr /@ Subsets@Most@Divisors@i - i] == {-1, 1}, j++; Print@i]] &@3 ``` it's still too slow for any useful purpose. Finds the first two in a few seconds but gets slower and slower as the number of divisors increase. [Answer] ## Python 2.7 (255 bytes) ``` import itertools as t a=int(raw_input()) n=1 while a>0: d=[i for i in range(1,n/2+1) if not n%i] if all([n not in map(sum,t.combinations(d,i)) for i in range(len(d))]+[sum(d)>n]): print n a-=1 n+=1 ``` [Answer] ## PHP, 267 bytes ``` $n=$x=0;while($n<$argv[1]){$x++;for($i=1,$s=0,$d=array();$i<$x;$i++){if($x%$i){continue;}$s+=$i;$d[]=$i;}if($s<$x){continue;}$t=pow(2,$m=count($d));for($i=0;$i<$t;$i++){for($j=0,$s=0;$j<$m;$j++){if(pow(2,$j)&$i){$s+=$d[$j];}}if($s==$x){continue 2;}}$n++;print"$x\n";} ``` And here's the original source code: ``` $n = 0; $x = 0; while ($n < $argv[1]) { $x++; for ($i = 1, $sum = 0, $divisors = array(); $i < $x; $i++) { if ($x % $i) { continue; } $sum += $i; $divisors[] = $i; } if ($sum < $x) { continue; } $num = count($divisors); $total = pow(2, $num); for ($i = 0; $i < $total; $i++) { for ($j = 0, $sum = 0; $j < $num; $j++) { if (pow(2, $j) & $i) { $sum += $divisors[$j]; } } if ($sum == $x) { continue 2; } } print "$x\n"; } ``` You will note that it takes some time to output the numbers as it is performing a brute-force verification (you should get to 70 pretty fast, though). [Answer] ## R, 164 ``` r=0;x=1;n=scan();while(r<n){i=which(!x%%(2:x-1));if(sum(i)-1&&!any(unlist(lapply(2:sum(i|T),function(o)colSums(combn(i,o))==x)))&sum(i)>x){r=r+1;cat(x,"\n")};x=x+1} ``` Un-golfed version: ``` r = 0 x = 1 n = scan() while(r < n) { i = which(!x %% (2:x - 1)) if( sum(i) - 1 && !any(unlist(lapply(2:sum(i | T), function(o) colSums(combn(i, o)) == x))) & sum(i) > x ){ r = r + 1 cat(x, "\n") } x = x + 1 } ``` This takes some time due to brute-force. [Answer] ## Ruby - 152 ``` x=2;gets.to_i.times{x+=1 while((a=(1..x/2).find_all{|y|x%y==0}).reduce(:+)<=x||(1..a.size).any?{|b|a.combination(b).any?{|c|c.reduce(:+)==x}});p x;x+=1} ``` ## Ruby With ActiveSupport - 138 ``` x=2;gets.to_i.times{x+=1 while((a=(1..x/2).find_all{|y|x%y==0}).sum<=x||(1..a.size).any?{|b|a.combination(b).any?{|c|c.sum==x}});p x;x+=1} ``` Really slow and I'm almost sure there is still room for golfing... [Answer] # Smalltalk, 143 ``` ((1to:(Integer readFrom:Stdin))reject:[:n||d|d:=(1to:n//2)select:[:d|(n\\d)=0].d sum<n or:[(PowerSet for:d)contains:[:s|s sum=n]]])map:#printCR ``` input: ``` 1000 ``` output: ``` 70 836 ``` [Answer] ## SageMath: ~~143~~ 131 bytes ``` x=1 def w(): l=x.divisors() return 2*x>=sum(l)or max(2*x==sum(i)for i in subsets(l)) while n: while w():x+=1 print x;n-=1;x+=1 ``` It's moreorless not even golfed, there's not too much to golf anyways in the code. The biggest thing is that you should do the test `2*x>=sum(l)` first, it would save a lot of computation time. One has to realize that `max` on booleans is `or` Second thing is that `w(x)` is `False` for weird numbers and `True` for non-weird numbers. Ungolfed version: ``` def w(x) : Divisors = x.divisors() return 2*x >= sum(Divisors) or max ( sum(SubS) == 2*x for SubS in subsets(Divisors) ) x=1 for k in xrange(n) : while w(x) : x += 1 print x x += 1 ``` [Answer] # C++ - 458 This is not all my solution as I had to ask on SO for help calculating the sum of the subsets, but everything else is mine: ``` #include<iostream> #include<vector> using namespace std; #define v vector<int> #define r return #define c const_iterator v x(int i){v d;for(int k=1;k<i;k++)if(i%k==0)d.push_back(k);r d;}bool u(v::c i,v::c e,int s){if(s==0)r 0;if(i==e)r 1;r u(i+1,e,s-*i)&u(i+1,e,s);}bool t(v&d,int i){bool b=u(d.begin(),d.end(),i);if(b)cout<<i<<endl;r b;}int main(){v d;int n;cin>>n;for(int i=2,j=0;j<n;i++){d=x(i);int l=0;for(int k=0;k<d.size();k++)l+=d[k];if(l>i)if(t(d,i))j++;}} ``` Long version: ``` #include<iostream> #include<vector> using namespace std; vector<int> divisors(int i) { vector<int> divs; for(int k = 1; k < i; k++) if(i%k==0) divs.push_back(k); return divs; } bool u(vector<int>::const_iterator vi, vector<int>::const_iterator end, int s) { if(s == 0) return 0; if(vi == end) return 1; return u(vi + 1, end, s - *vi) & u(vi + 1, end, s); } bool t(vector<int>&d, int i) { bool b = u(d.begin(), d.end(), i); if(b) cout<< i << endl; return b; } int main() { vector<int> divs; int n; cin>>n; for(int i = 2, j = 0; j < n; i++) { divs = divisors(i); int sum_divs = 0; for(int k = 0; k < divs.size(); k++) sum_divs += divs[k]; if(sum_divs > i) if(t(divs, i)) j++; } } ``` It has currently only calculated the first two (70 and 836). I killed it after that. [Answer] # Perl, 173 Let me add another useless solution. This solution is so slow that it can't even output anything past the first weird number. I dare say it is the slowest of all the solution here. ``` $n=<>;$i=2;while($n){$b=qr/^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+/;$_='x'x3x$i;if(/$b/&&($+[0]>$i)&&!/$b\1{2}$/){print"$i\n";$n--}$i++} ``` [Demo](http://ideone.com/akLq4W) The same code written in Java (which I am more comfortable with) can't even recognize the 2nd weird number (836), and I have already fed the number directly to the checking method (instead of looping and checking every number). The core of this solution lies in the regex: ``` ^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+ ``` And how the string is set up to be 3 times the number that we are checking. The length of the string is set up to be 3 times the number that we are checking `i`: the first 2 `i` is for matching summation of factors and the last 1 `i` is reserved for checking whether a number is a factor of `i`. `(?=(.+)\1{2}$)` is used to capture the number that we are checking. `((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+` matches the factors of the number. Later iteration will match a smaller factor than an earlier iteration. * We can see that these 2 parts `(.+)` and `(?=.*(?=\1$)\3+$)` together selects a factor of the number being checked. * `(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))` makes sure that the factor selected is smaller than the number being checked in the first iteration, and is smaller than previous factor in subsequent iterations. The regex tries to match as many factors of the number as it can within the limit of 2 `i`. But we don't care about the actual value of sum of divisors, we only care whether the number is abundant. Then the 2nd regex, which is the first regex with `\1{2}$` added. As a result, the regex makes sure the sum of (some) factors of the number being checked is equal to the number itself: ``` ^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+\1{2}$ ``` The constraint added will cause the regex engine to perform a backtracking search on all possible subsets of factors, so it is going to be extremely slow. [Answer] ## Perl, 176 174 bytes ``` $n=<>;$i=9;X:while($n){@d=grep{!($i%$_)}1..$i-1;$l=0;map{$a=$_;$s=0;$s+=$d[$_]for grep{2**$_&$a}0..@d-1;$i++,next X if$s==$i;$l=1 if$s>$i}0..2**@d-1;$n--,print$i,$/if$l;$i++} ``` The number of weird numbers are expected in STDIN and the found numbers are printed to STDOUT. ## Ungolfed version ``` #!/usr/bin/env perl use strict; $^W=1; # read number from STDIN my $n=<>; # $i is the loop variable that is tested for weirdness my $i=9; # better start point is 70, the smallest weird number # $n is the count of numbers to find X: while ($n) { # find divisors and put them in array @divisors my @divisors = grep{ !($i % $_) } 1 .. $i-1; # better: 1 .. int sqrt $i # $large remembers, if we have found a divisor sum greater than the number my $large = 0; # looping through all subsets. The subset of divisors is encoded as # bit mask for the divisors array. map { my $subset = $_; # calculate the sum for the current subset of divisors my $sum = 0; map { $sum += $divisors[$_] } grep { 2**$_ & $subset } 0 .. @divisors-1; # try next number, if the current number is pseudoperfect $i++, next X if $sum == $i; # better: $i+=2 to skip even numbers $large = 1 if $sum > $i; } 0 .. 2**@divisors - 1; # print weird number, if we have found one $n--, print "$i\n" if $large; $i++; # better: $i+=2 to skip even numbers } __END__ ``` ## Limitations * Slow, brute force. * The count of divisors for a number is limited to the "bitness" of integers in Perl. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ÆḌŒP§e@=ÆḌS<Ɗµ# ``` [Try it online!](https://tio.run/##y0rNyan8//9w28MdPUcnBRxanupgC@YE2xzrOrRV@f9/QwA "Jelly – Try It Online") Takes input via STDIN. Insanely inefficient, times out for \$n > 1\$ on TIO, as it checks each \$k = 1, 2, \dots\$ until it finds \$n\$ values that fit, and for each \$k\$ it generates \$2^{\sigma(k)-k}\$ sublists (where \$\sigma(k)\$ is the [sum of divisors function](https://en.wikipedia.org/wiki/Divisor_function)) ## How it works ``` ÆḌŒP§e@=ÆḌS<Ɗµ# - Main link, takes no arguments µ# - Take an integer from STDIN, n, and run the previous code over each integer, k, from 0 until n truthy values are found: ÆḌŒP§e@ - First check for weirdness: ÆḌ - Take the proper divisors of k ŒP - Find the powerset of the proper divisors § - Get the sum of each - This gives the sum of each subset of proper divisors e@ - Is k equal to one of the sums? - This gives 0 if no combination of these numbers sum to k and 1 otherwise ÆḌS<Ɗ - Second check for weirdness: Ɗ - Group the previous 3 commands together: ÆḌS - Is the proper divisor sum of k... < - Less than k? - This gives 0 if the proper divisor sum of k is greater than k and 1 otherwise = - Are the two checks equal? - There are three possible values that the two checks could output: - 0, 1: k cannot be expressed as a sum of a subset of its proper divisors and k is less than or equal to its proper divisor sum, therefore k is not weird - 1, 0: k can be expressed as a sum of a subset of its proper divisors and k is greater than its proper divisor sum, therefore k is not weird - 0, 0: k cannot be expressed as a sum of a subset of its proper divisors and k is greater than its proper divisor sum, therefore k is weird - 1, 1 cannot be a possibility as that would require that k can be expressed as a sum of a subset of its proper divisors and that k is greater than its proper divisor sum, which are contradictory - Therefore, checking whether the two checks result in the same value suffices to check for weirdness ``` ]
[Question] [ Code golf always involves some answers that bend the rules more or less by breaking constraints that the challengers took for granted or just haven't thought about and didn't list in the rules. One of these interesting loopholes is the possibility to output *more* than the challenge asks for to get a better result. Taking this to extremes, we can write an universal code golf solver that prints the desired output — if you don't care that it might take ages and outputs lots of other stuff before and after it. All we need to output is a sequence that is guaranteed to contain every possible subsequence. For this code golf, this will be the [Ehrenfeucht-Mycielski sequence](http://en.wikipedia.org/wiki/Ehrenfeucht%E2%80%93Mycielski_sequence): > > The sequence starts with the three bits 010; each successive digit is > formed by finding the longest suffix of the sequence that also appears > earlier within the sequence, and complementing the bit following the > most recent earlier appearance of that suffix. > > > Every finite subsequence of bits occurs contiguously, infinitely often > within the sequence > > > The first few digits of the sequence are: > > > > > > > 010011010111000100001111... (sequence [A038219 in OEIS](http://oeis.org/A038219)). > > > > > > > > > Combining 8 bits of the sequence to a byte, we'll get ASCII output that we can output to the screen or to a file and that contains *every possible finite output*. The program will output parts of pi, [the lyrics of “Never gonna give you up”](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i), some nice ASCII art, its own source code, and everything else you could want it to output. For testing correctness, here are hashes for the first 256 bytes of the sequence: ``` MD5: 5dc589a06e5ca0cd9280a364a456d7a4 SHA-1: 657722ceef206ad22881ceba370d32c0960e267f ``` The first 8 bytes of the sequence in hexadecimal notation are: ``` 4D 71 0F 65 27 46 0B 7C ``` Rules: * Your program must output the Ehrenfeucht-Mycielski sequence (nothing else), combining 8 bits to a byte/ASCII character. * Shortest program (character count) wins. Subtract 512 from your character count if you manage to [generate the sequence in linear time per generated byte](http://en.wikipedia.org/wiki/Ehrenfeucht%E2%80%93Mycielski_sequence#Algorithms). [Answer] ## C, –110 chars This version of the program uses the linear-runtime algorithm to generate the sequence. Subtracting 512 from the 402 chars in the program gives a total of negative 110. ``` #define C v=calloc(7,8),v->p=p #define G(F,K)u->F[d[K]] #define S(F,T)G(f,T)=F,G(t,T)=T,G(n,T)= struct{int p,f[2],t[2];void*n[2];}r,*u,*v,*w;char*d,c;p,b,h,i,j,k; main(s){for(;d=++p-s?d:realloc(d,s*=2);){d[i=p]=b;c+=c+b;p%8||putchar(c); for(u=&r;b=u->p,u->p=p,w=G(n,k=i);S(i,k)v=G(n,k),u=v)for(h=G(f,k),j=G(t,k);j>h;--i,--j) if(d[i]-d[j]){S(i,k)C;u=v;S(h,j)w;S(0,i)C;b=w->p;goto x;}S(0,i)C;x:b=1-d[b+1];}} ``` As per the problem, the program runs in an infinite loop, which necessitates lots of memory allocation, and using `realloc()` to keep the sequence contiguous can contribute to heap fragmentation. You can improve the program's memory usage by replacing `calloc(7,8)` on the first line with `calloc(1,sizeof*v)`. This will help especially on a 32-bit machine, where 56 is likely too large by a factor of two. The code is kind of unreadable, and not in an interesting way; for that I apologize. Frankly, even the ungolfed version isn't terribly clear: ``` #include <stdio.h> #include <stdlib.h> typedef struct branch branch; typedef struct node node; struct branch { int from, to; node *next; }; struct node { int pos; branch br[2]; }; static node root = { 0 }; static unsigned char *data = NULL; static int endpos = 0; static int size = 1; static node *mknode(void) { node *n; n = calloc(1, sizeof *n); n->pos = endpos; return n; } static branch *getbranch(node *n, int p) { return &n->br[data[p]]; } static void setbranch(node *n, int from, int to, node *next) { n->br[data[to]].next = next; n->br[data[to]].from = from; n->br[data[to]].to = to; } int main(void) { node *u, *v, *w; int follower, from, i, i0, j; int out, b; out = b = 0; for (;;) { ++endpos; if (endpos == size) { size *= 2; data = realloc(data, size); } data[endpos] = b; out = (out << 1) | b; if (endpos % 8 == 0) { putchar(out); out = 0; } i = endpos; u = &root; for (;;) { follower = u->pos + 1; u->pos = endpos; w = getbranch(u, i)->next; if (!w) break; i0 = i; from = getbranch(u, i0)->from; for (j = getbranch(u, i0)->to ; j > from ; --j) { if (data[i] != data[j]) { /* divide branch */ v = mknode(); setbranch(u, i, i0, v); u = v; setbranch(u, from, j, w); setbranch(u, 0, i, mknode()); follower = w->pos + 1; goto bitfound; } --i; } v = getbranch(u, i0)->next; setbranch(u, i, i0, v); u = v; } /* extend branch */ setbranch(u, 0, i, mknode()); bitfound: b = 1 - data[follower]; } } ``` (The ungolfed code above is based on the code written by Grzegorz Herman and Michael Soltys, as referenced in the problem description, and from [Soltys' home page](http://www.cas.mcmaster.ca/~soltys/).) Thanks to @schnaader and @r.e.s. for reporting a bug in the initial version. [Answer] ### Ruby, 109 104 101 94 characters ``` s=?0 loop{s=(s[/(.*).*\1/][/.#{$1}/]<?1??1:?0)+s s.size&7<1&&$><<[s.reverse.to_i(2)].pack(?C)} ``` Implementation in Ruby using regular expressions for suffix search. Since it takes quite a long time until out-of-memory the program has to be terminated by the user. *Edit:* I just noticed that it is enough to start with the sequence `0`. *Edit 2:* The proposal of r.e.s. saves 2 characters, some others because we do not have to cut out a single byte before `pack`. [Answer] ## Perl, 95 chars I actually had a halfway decent version of this at first. Then as I golfed, each version got slower. Increasingly slower. ``` $|=$_="010"; y///c%8||print pack"B*",/(.{8})$/while/(.+)$(?(?{m|.*$^N(.)|})(?{$_.=1-$^N})|(?!))/ ``` The first three characters (`$|=`) aren't necessary, strictly speaking ... but without that there, you'd typically have to wait for the script to finish generating a full 4096 bytes before you'd see any of the output. And that would take hours. Maybe centuries; I'm not sure. Did I mention that this program's performance kind of deteriorates over time? So because of that I kind of felt compelled to include them in the count. On the other hand, this script has one of the ugliest regexes I've ever created, so I think I'm proud of it. ]
[Question] [ For any ragged list its *dimensions* will be a list of non-negative integers defined as follows: * Elements that are not a list will have dimensions \$\textbf{[}\,\,\textbf{]}\$. * An empty list has dimensions \$[0]\$. * An \$n\$ dimensional list \$L\$ of length \$x\$ has dimensions \$x : k\$ where \$k\$ is the element wise maximum of the dimensions of the elements of \$L\$ (treating missing elements as zero). (Here, `:` is "cons", the list constructor, e.g. in Lisp or Haskell) The intuitive idea is that this is the dimensions of the smallest box which can fit the list. But this is still a little bit daunting, so let's work through some examples. To start with, for one dimensional lists, its dimensions are always just its length. ``` [ 1 , 2 , 3 ] ``` There are 3 elements here so its dimensions are \$3:k\$. To determine \$k\$ we look at the dimensions of each element. They are all integers so they have dimensions \$\textbf{[}\,\,\textbf{]}\$, and the pairwise maximum is also \$\textbf{[}\,\,\textbf{]}\$. So the dimensions are \$3:\textbf{[}\,\,\textbf{]}\$ or just \$[3]\$. Let's do an example that is actually ragged: ``` [ [ 1 , 2 , 9 , 9 ] , 4 ] ``` There are two elements, the first is one dimensional so it has dimensions \$[4]\$, the second is an integer so it has dimensions \$\textbf{[}\,\,\textbf{]}\$. Now we take the pairwise maximum. Since \$[4]\$ has more elements we treat the missing elements as zeros. The maximum is just \$[4]\$ then. The total list has length \$2\$ so the answer is \$2:[4]\$ or \$[2,4]\$. Let's do another example: ``` [ [ 1 , 2 , 9 , 9 ] , [ [] , 2 ] ] ``` The first element is the same, but the second one is different, so let's calculate its dimensions. It has two elements with dimensions \$[0]\$ and \$\textbf{[}\,\,\textbf{]}\$. The pairwise maximum is \$[0]\$ so this element has dimensions \$[2,0]\$. With this in mind now we take the pairwise maximum of \$[4]\$ and \$[2,0]\$ which gives \$[4,0]\$. Finally we add one the \$2\$ for the length of the top level and get the dimensions of \$[2,4,0]\$ # Task Given an arbitrary ragged list of positive integer give a list of non-negative integers representing its dimensions. You may assume that the input is a *list*. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. # Test cases ``` [] => [0] [ 1, 2, 3] => [3] [[1, 2, 9, 9], 4] => [2,4] [[1, 2, 9, 9], [[], 2]] => [2,4,0] [[[]],[]] => [2,1,0] [[1,2,3],[[1,2,3],[[1,2,3],[[1,2,3],[1,2,3]]]]] => [2,3,3,3,3] ``` [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` d=lambda l:d<l and[len(l)]+map(max,[],*map(d,l))or[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN01SbHMSc5NSEhVyrFJschQS81Kic1LzNHI0Y7VzEws0chMrdKJjdbRA7BSdHE3N_KLoWKjeNQVFmXklGika0bGamlxwjqGOgpGOgjGKGFTQEohidRRM8MhFA21TMIpFVREdGwt0BbouIx1joDAeBoQGAU1NiJth_gYA) ## Old [Python 2](https://docs.python.org/2/), 53 bytes (@att) ``` d=lambda l:[1]*(d<l)and[len(l)]+map(max,[],*map(d,l)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN01TbHMSc5NSEhVyrKINY7U0UmxyNBPzUqJzUvM0cjRjtXMTCzRyEyt0omN1tEDsFJ0cTU2o5jUFRZl5JRopGtGxmppccI6hjoKRjoIxihhU0BKIYnUUTPDIRQNtUjCKRVURHRsLdAG6LiMdY6AwHgaEBgGYm2EeBwA) ## Old [Python 2](https://docs.python.org/2/), 65 bytes ``` d=lambda l:[1]*(d<l)and[len(l)]+map(lambda*a:max(a),[],*map(d,l)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNx1TbHMSc5NSEhVyrKINY7U0UmxyNBPzUqJzUvM0cjRjtXMTCzQgKrQSrXITKzQSNXWiY3W0QOIpOjmamlCD1hQUZeaVaKRoRMdqanLBOYY6CkY6CsYoYlBBSyCK1VEwwSMXDbRJwSgWVUV0bCzQBei6jHSMgcJ4GBAaBGBuhgUCAA) That's a cleanup of @Steffan's Python 2 answer. He made it a challenge, so I took the liberty of posting it as a separate answer. [Answer] # [Whython](https://github.com/pxeger/whython), 95 bytes ``` from itertools import* d=lambda l:[len(l),*(map(max,zip_longest(*map(d,l),fillvalue=0))?[])]?[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZBLCsIwEED3PUWWSYmgrQsVigcJoUTS2sDkQ5v6u4qbbsSNF_I2prQKddFhPsmbGWaY-_NcXX1lTdc9Wl8uNu-8rK1Gyhe1txYapLSztY8jmYHQBykQ7BgUBgOhMdbCBbvQm3I5WHMsGo_jHkoa8qUCOAloi2xJyJ5xwoMbx7xcrYzHEgdMot9nRVFCUTphI9wG5RStZ3KMBZfwaQXjnDL-35XQNOCZxxB7IWTY-XuiDw) [Answer] # JavaScript, 65 bytes ``` f=(a,e=+(o=[]),L=0)=>!a.map?.(v=>f(v,e+1)*++L)|L<o[e]||(o[e]=L,o) ``` ``` f=(a,e=+(o=[]),L=0)=>!a.map?.(v=>f(v,e+1)*++L)|L<o[e]||(o[e]=L,o) t = ` [] => [0] [ 1, 2, 3] => [3] [[1, 2, 9, 9], 4] => [2,4] [[1, 2, 9, 9], [[], 2]] => [2,4,0] [[[]],[]] => [2,1,0] [[1,2,3],[[1,2,3],[[1,2,3],[[1,2,3],[1,2,3]]]]] => [2,3,3,3,3] `.trim().split('\n').map(l => l.split('=>').map(v => JSON.parse(v))); t.forEach(([i, e]) => { console.log(f(i) + '' == e, JSON.stringify(f(i))); }); ``` ``` f=( a, // Input array e=+( // Current level o=[]), // Output array, initialized by [] L=0 // length of input )=> !a.map?.(v=> // If Current level is an array not integer And f(v,e+1)* // Recursively call `f` for inner levels ++L)| // Count length of input array L<o[e]|| // If Current length is longer than we ever seen (o[e]=L,o) // Update it, and remember to return the output array ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` Max/@#~Position~_?AtomQ~Flatten~{2}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sULfQbkuIL84syQzP68u3t6xJD83sM4tJ7GkJDWvrtqoVu1/QFFmXkm0soKunUJatHJsrIKagr4Dl0J1da0Ol4JCtaGOgpGOgjGEA@VZAlGtjoIJNkGQPgWjWqhUdS1IqBZFoTFYFRFsGBMM/gMA "Wolfram Language (Mathematica) – Try It Online") -5 bytes thanks to @att. --- ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` Max/@Thread@PadRight@Position[#,_?AtomQ]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sULfISSjKDUxxSEgMSUoMz2jxCEgvzizJDM/L1pZJ97esSQ/NzBW7X9AUWZeSbSygq6dQlq0cmysgpqCvgOXQnV1rQ6XgkK1oY6CkY6CMYQD5VkCUa2Oggk2QZA@BaNaqFR1LUioFkWhMVgVEWwYEwz@AwA "Wolfram Language (Mathematica) – Try It Online") ### How? In Mathematica, everything is an expression. An expression is a tree, where atoms are the leaves: symbols, numbers, strings, etc. How many atoms are there in the expression `{1, 2, 3}`? The answer is 4. In fact, `{1, 2, 3}` is just a syntactic sugar for `List[1, 2, 3]`, which has 4 atoms: `1`, `2`, `3` and `List`. `List` is the head of the expression, whose position is `0`. Now takes the input `{1, {}, 2}` as an example. When desugared, it becomes `List[1, List[], 2]`, which has 4 atoms: `List`, `1`, `List`, `2`. `Position[#,_?AtomQ]` finds the positions of all atoms in the input. In this case, it is `{{0}, {1}, {2, 0}, {3}}`. `PadRight` pads the list with `0`s to make it a full (i.e., not ragged) array. So it becomes `{{0, 0}, {1, 0}, {2, 0}, {3, 0}}`. `Thread` transposes the array. So it becomes `{{0, 1, 2, 3}, {0, 0, 0, 0}}`. Finally, `Max/@` finds the maximum value in each row. So the result is `{3, 0}`. [Answer] # [R](https://www.r-project.org/), ~~126~~ 119 bytes ``` d=function(l,`+`=sapply,r=length)c(r(l),if(any(m<-l+is.list))do.call(pmax,c(lapply(k<-l[m]+d,`[`,1:max(k+r)),na.rm=T))) ``` [Try it online!](https://tio.run/##nY7basMwDEDf9xWGvUhEDbn0ZaXuV/StFGKSdjORnWCn0H596ubShV1gzDa2JZ1jy/WVNifrdWO97Ct5vtiyCwEwFVEhvWpbvpGTfLLv3QeW4ICR9BmUvYHZrjjSPmbtO8SqiUvFDK1RVyqBBxXqwBzMMaqoOBSUbkIR6sghklWxM3KPiIse4PEWIIpXIXcieflaESmJjEQ@E/k3YthG6i0sJLGe4YzWf8A/0yHIcCFT8rM@9UzT@RTS34SUMson/h@J8T6M@at8nP0d "R – Try It Online") This was supposed to be just a simple recursive function using the elementwise-maximum (`emax`) to get the largest element at each position of a list of unequal-length vectors: ``` dimensions= d=function(l,m=sapply(l,is.list))c(length(l),if(any(m))emax(lapply(l[m],d))) ``` Unfortunately, the `emax` function does not exist. This is because [R](https://www.r-project.org/) **loves** element-recycling, and the similar-seeming parallel-maximum function - `pmax` - helpfully recycles the elements of unequal-length vectors (so `pmax(10:11,1:3)` gives `10 11 10` instead of `10 11 3`): exactly what we *don't* want here!). So this approach needs to implement `emax` by 'padding' all shorter vectors with `NA`s, before calling `pmax` and specifying `na.rm=T` to ignore them: ``` emax= function(l)do.call(pmax,c(lapply(l,`[`,1:max(lengths(l))),na.rm=T)) ``` Rolling these two functions together, we can golf out a few excess characters (and render the code near-unreadable as a by-product), but bearing in mind how awkward this overall approach is, I won't be surprised if there's a shorter one that doesn't require creating nonexistant functions to make it work... [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` f=lambda*a:a and[max(map(len,a)),*f(*[b for b in sum(a,[])if'A'<str(b)])] ``` [Try it online!](https://tio.run/##fYzBCsIwDIbvPkVuS0cuW70oevA5Qg4ps1hYu7FN0Kevm4owD4PAn3xfkv453bpkc/bnVqNrtNSjgqaGoz4wao/tNZEaQ6XHkh34bgAHIcF4j6jEYoIvLsVpnAZ0RozkfghpQo@zMrvfUBHUBHbFvvAwlxDsNxwzyxIV1SLrvUWw/N/WZGe80XxS3t/yCw "Python 3 – Try It Online") And this is [70 bytes in Python 3 (Cython)](https://tio.run/##fYzBCsIwDIbvPkVua0s8bPWi6MHnCIGlzuJg7cacoE9ftynCPAwCX/L9SbrXcGuj3V5mpuRPjQRXiZGDgMSKgjxVkE4114iiNRqvDDnwbQ8O6gj3R1CCxLr22Tk7lq5kzanr6zgor0avN78hRygQ7MJ95X4sRtitZETEE3IsmJd7U0D8f1ugHfVK8yHP39Ib). [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` d=lambda l:l*0==[]and[len(l)]+('['in`l`[1:]and map(max,[],*map(d,l))or[])or[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN31TbHMSc5NSEhVyrHK0DGxto2MT81Kic1LzNHI0Y7U11KPVM_MSchKiDa1AEgq5iQUauYkVOtGxOlogdopOjqZmflF0LJiAGrqmoCgzr0QjRQMorMkF5xjqKBjpKBijiEEFLYEoVkfBBI9cNNBKBaNYVBXRsbFAp6DrMtIxBgrjYUBoENDUhLgZFiAA) Takes advantage of a bunch of Python 2 stuff: * multiple lists passed to `map` pads with `None` * `max` works with values other than integers (which includes `None`) * can do ``l`` with Python 2's backticks instead of `str(l)` # [Python](https://www.python.org), 128 bytes ``` from itertools import* d=lambda l:[len(l),*(map(max,zip_longest(*map(d,l),fillvalue=0))if'['in str(l)[1:]else[])]if[]==l*0else[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZDNCsIwDIDvPkVvtqPCNj2osCcJQSZrtZC1pauinnwPL1705Av5Nlamgh4M-f2SQMjp6vdx7ez5fNlEPZrejzq4lpmoQnSOOmZa70LMBk1FdbtsakZzIGU5CZnxtvbJdvJg_IKcXaku8uwJG5n62hBta9qoKhfC6CEMjWVdDGkXijkq6hSgQKMBq4qyvAevO24-GBt5w9OIGHyKQrJSsvEXe8FZUpRs8qcHkFyJ3xOAKAF_t0o5TvhP0senCNHf_P7hAw) [Answer] # [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html), 73 bytes ``` (a:b)!(c:d)=max a c:b!d []!x=x y!_=y iter((:).length<*>foldr(!)[]).([]<$) ``` [Try it online!](https://tio.run/##bZJRi5wwEMff/RQjtw/JcSrXUgqy@tL24OC6lNK3RZacJiprEkkidWn72beJcdNdrj5o5v@fzG9msCP6SIfh/Cu5gxci2om0FL4Tcdz9OI1Uw13yJ0oS@ExZL3rTS6GhlmNPG2BKcjAdBS0nVVOQbImYohS4bKbBnqUCQ7XpReuKdMaMOs@yjtRHi0k7z06larPRa5m7nnxIH9OPWSNrnWlVZ5@kMEoO6VcpSJM@2Yy0M3yIGmIIuBAYkAiggG@Tosvxt9cRA3RJwDiKeqENEbbZp0nUxnbHoChDsKZi@NlRRW0VxsnoUqCVQQMXIA/CgYkcILi@jrWLtQ0rbjelk2yOW/Xz7uV598UD3IojRY0itYE8h2XMtbO1d0jKZcZLVuAXtp4VJyWu3eUa0d4mGsqygNW0OzBUOczNCtAKsSWTWyzxFw5XzIs2dv3K4k5dwmC4ebldOZNDs@SEybgHSkWGAWZILWl2JA7zGzq3rFDhcLP3MHbw2fXkroKf/J9/RiR/xTGq8wYXnMyWUeevcRPtq3gu5ugUH4pTxAo3BEI5TgcqWtNt70tXQ6EY7yucon213eAzJ72wmEbaHY@qFwY2oYP90ufjg/853j3A/9Xl@7662Nfvyj74/Bc "Haskell – Try It Online") Here we represent ragged lists as free monads of lists. We define `(!)` which takes the pairwise maximum of two lists. This is almost just `zipWith max`, but that takes the length of the shorter list, and we need the length of the longer one defaulting to zero when empty. That makes up the majority of the code. The rest of the code is the point free function that implements the answer. First we have `([]<$)` this replaces every terminal element with `[]` which is it's dimensions. This is the base case for our recursion. Then we have the recursive step which is `(:).length<*>foldr(!)[]`. Which is just point-free for `\x -> length x:foldr(!)[]x` or the length of the list `x` and the pairwise maximum of all its elements. We combine the inductive step and the base case with [`iter`](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#v:iter) from the [free library](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html) to make it work. `iter` is just induction on free monads. [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 21 bytes ``` shp[]$l*:*rF(zd' ma)i ``` ## Explanation * `zd' ma` takes the pairwise maximum of two lists. `zdm ma` would also work. * `rF(zd' ma)i` folds the above across a list of lists. `lf(zd' ma)i` also works. * `(l*:*)` takes the a function and a list and prepends the length of the list onto the result of the function. * `l*:*rF(zd' ma)i` forms the inductive step of our algorithm. It takes a list of dimensions, calculates the pairwise maximum and then adds the length onto the front of that result. * `shp[]` takes an inductive step and replaces everything with `[]` as a base case. So altogether this implements a basic recursive algorithm. ## Reflection There's a lot here that might be useful to combine. * `frF i<zd'` could be useful, if I had a function `zzD=frF i<zd` the answer would be `shp[]$l*:*zzD ma` saving 5 bytes here. It might in general be useful to have versions of the zip functions that operate over a foldable rather than just combining two elements. * `shp i` might be useful as a standalone it seems like the most common arguments for `shp` would be `[]` and `0`, which are both `i`. * `(l*:*)` is something I think I've done in the past might be useful to give it a name. [Answer] # Python3, 202 bytes: ``` lambda x:(K:=lambda d,j={}:[max(j[i])for i in j]if[]==d else K(d[1:],{**j,d[0][0]:j.get(d[0][0],[])+[d[0][1]]}))(f(x)) f=lambda x,c=0:[[c,len(x)]]+[j for k in x for j in(f(k,c+1)if list==type(k)else[])] ``` [Try it online!](https://tio.run/##fY/BbsIwDIbvPIWPMbUm2u6wRcqVC4/g@dA16Za0lKrkUIR49i4FNokdiKzk/37H@pPhFL8Pffk2jPPWfMxdtf@0FUxa7bS5g6VgzhfN@2pSgb1gcxjBg@8hiG9YjLHguqODnbKca6Hzeh3I8kZS6fDy5aK6E7FgxlfIRS6IqlET4qr5zZqoNhvNXFPn@tQSyTjAEtgugdNVhiTTYEt1lqNvoPPHaEw8DU61uLwkpcg8jL6PaqsS4OoPICcoCMoHk2/meyoheH3SY05bIY83WJaP/Z8qqEz2E3E7l4U4/wA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "Ddi¯ëИÊi®δ.VDU0ζ€àXgšëg¸"©.V ``` [Try it online](https://tio.run/##AVMArP9vc2FiaWX//yJEZGnCr8Orw5DLnMOKacKuzrQuVkRVMM624oKsw6BYZ8Whw6tnwrgiwqkuVv//W1sxLDIsOSw5XSxbW10sMl1d/y0tbm8tbGF6eQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/JZeUzEPrD68@POH0nMNdmYfWnduiF@YSanBu26OmNYcXRKQfXXh4dfqhHUqHVuqF/df5Hx0dq6MQbahjpGMMYoBZljqWsTomqFyQOqNYsFg0kIqOhUsbgyRxMyA0GPzX1c3L181JrKoEAA). **Explanation:** ``` "..." # Push the recursive string explained below © # Store it in variable `®` (without popping) .V # Eval and execute it as 05AB1E code # (using the implicit input-list as initial argument) # (after which the result is output implicitly) i # If D # a copy of the current value d # is >= 0 (thus an integer): ¯ # Push an empty list ë i # Else-if Ð # a copy of the current value Ê # is NOT equal to И # a flattened copy of the current value (thus it's a ragged # list): δ # Map over each inner list: ® .V # And do a recursive call by 05AB1E-executing string `®` DU # Store a copy of the result in variable `X` ζ # Zip/transpose; swapping rows/columns, 0 # with 0 as filler for unequal length lists à # Get the maximum € # of each inner list š # And then prepend to this list g # the length X # of variable `X` ë # Else (thus it's a flattened list): g # Push its length ¸ # Wrap it into a list ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` WẎƬṖḟFẈṀƲ€ ``` A monadic Link that accepts a ragged list of integers and yields a list of non-negative integers giving the depth-wise dimensions as required. **[Try it online!](https://tio.run/##y0rNyan8/z/84a6@Y2se7pz2cMd8t4e7Oh7ubDi26VHTmv@H249Oerhzxv//0dGGOgpGOgqWQBSroxAdDSSMYmMB "Jelly – Try It Online")** ### How? ``` WẎƬṖḟFẈṀƲ€ - Link: ragged list of integers, L W - wrap L in a list Ƭ - (starting with that) collect up inputs while distinct applying: Ẏ - tighten (drop first level of the inner lists) Ṗ - pop (remove the final input) € - for each: Ʋ - last four links as a monad: F - flatten (to a list of integers) ḟ - filter these out (only filters out integers at depth 1) Ẉ - length of each Ṁ - maximum ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ⊞υAWυ«≔υθ≔⟦⟧υFθFΦκ⁼λ⁺⟦⟧λ⊞υλ⟦I⌈EθLκ ``` [Try it online!](https://tio.run/##NY3NCsIwEITP9in2uIF4sDfxJKIgKPQecgiltqFr2vypID57TApdFoZhv5ltB@XaSVFKTfQDRg5XM8eAjB2q96CpA4wMvtXm6L3uTQFsPq1WSA6x@MfkAC2DRS@aQudw5HC2UZFH4tBQ9AtOLA@s36iEG6dNQHFSPuBdffQzPrPOaDncOtOHAccSkpn9pSSE2HGoOezz5kJRWmspZdq@6A8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υA ``` Push the input list to the predefined empty list. ``` Wυ« ``` Repeat until the list of lists is empty. ``` ≔υθ≔⟦⟧υ ``` Save it and start a new list. ``` FθFΦκ⁼λ⁺⟦⟧λ⊞υλ ``` Push all of the elements of the lists that are themselves lists to the list. ``` ⟦I⌈EθLκ ``` Output the maximum length of all of the original lists on its own line. ]
[Question] [ The task is to find the smallest paper size on which it is possible to print a picture of the dimensions given in milimetres. The image will be printed without margins. # Input: Two integers (bigger than zero) and a letter a, b, or c, for example: ``` 290 200 A ``` # Output: Paper size, for example: > > A4 > > > Another examples: ``` 218,297,a A3 1,1,c C10 9999,9999,c ??? (error) 74,52,A A8 31,44,B B10 26,1100,A A0 250,177,b b4 250,176,b b5 1189,841,a a0 ``` The dimensions of the paper for \$i \in \{0,\dots, 10\} \$ are: $$ \left( \frac{\alpha}{\sqrt{2}^{i+1}} , \frac{\alpha}{\sqrt{2}^{i}} \right) $$ where \$\alpha\$ depends on the type of paper: $$ \begin{eqnarray} \alpha\_A &=& 2 ^ {1/4} \\ \alpha\_B &=& 2 ^ {1/2} \\ \alpha\_C &=& 2 ^ {3/8} \\ \end{eqnarray} $$ --- * Upper- and lowercase variants of letters "A", "B" and "C" are allowed on input and on output. You need to handle both of them. * The image can be printed vertically or horizontally. * The values can be passed as a parameter or entered by the user. * Width and height of picture will be always > 0 (and they will be always integers), and letters will be always 'a', 'b', or 'c'. You don't need to validate them. * You need to handle paper sizes A0 - A10, B0 - B10 and C0 - C10. If the image is too large, you can throw an exception, print an error or whatever you want, as long as it is clearly different from valid result and the application will not hung up. Paper sizes, please ignore inch values ([source: Wikipedia](https://en.wikipedia.org/wiki/Paper_size#Overview_of_ISO_paper_sizes)) : [![Paper sizes](https://i.stack.imgur.com/9eeCl.png)](https://i.stack.imgur.com/9eeCl.png) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - fewest bytes wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` η⊞θ×⌊θ₂²I⊖L↨⌊X∕×φX²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦² ``` [Try it online!](https://tio.run/##PU5NC4IwGL73K4anV1hhYlB0sqRTgfRxkg5DX9pAN91m9e@X0@rywPs@nyVnulSsdi7XQlrg4XaW94ZDR8lVNGjgJKRo@ga6kJJL1zONZ6UsxGHopaNpz4yFDEuNDUqLFRxRPiyHHTMIh1opDbl6oYZMPEWFMAUvoyiiZCJiSr5cXvfGnwchKwjS/S6g5Na2qEsfxodWStYjDsMG6Ym9//MWsf//wA90rihWm2SwJMs7JUEa3N38WX8A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of integers and a characters. Explanation: ``` η ``` Output the paper letter. ``` ⊞θ×⌊θ₂² ``` Multiply the smaller dimension by √2 and use that if it is larger than the larger dimension. ``` I⊖L↨⌊X∕×φX²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦² ``` Calculate the largest size of paper, divide by the larger dimension (less 0.2 due to rounding errors), square the result, convert to binary, and count the digits (because Charcoal has no logarithm function). [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes ``` f=lambda a,c,i=10:max(a)<=1e3*2**(2**ord(c)%5/8-i/2)>=min(a)*2**.5and c+str(max(-1,i))or f(a,c,i-1) ``` [Try it online!](https://tio.run/##Tc3RjoIwEAXQ9/2KJsbYwUE7hQpuRCL7JRUkNhEwyIP79Thodssk05d7euf@O1y7NhrHOrvZ5lxZYbFEl5H6buxTWjhkdIkCHQSSt@srWcLSbNPQbTUcs8a1bKZ4Y2xbiXL9GHo5/QwJHUDXi1q@G0OC8d67dpC1lJpS1PsEcGVXAGKahThFX/@AkDgs/8IP@CHlxZ4Hp8e7hcjz3IskRqM5PfkWPpJ6EBHGMYNiDor5Eb1DIqXmJVwxB0YhJTsGZw8KM74A "Python 3 – Try It Online") -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). -12 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~189~~ ~~174~~ ~~161~~ 152 bytes Thanks to ceilingcat for the -37. The function normalizes the dimensions and then iterates through the sizes until one fits. To return the paper size, `asprintf()` works and makes it so I don't have to have a static array to store the string. ``` f(w,h,z,x){float q;z=~-z&3,w>h?x=w:(x=h,h=w);for(w=11;round(q=exp2(~z/4./~(z/2)-.5*--w)*1e3)<x|round(q/sqrt(2))<h&&~w;);asprintf(&h,"%c%d",z+65,w);w=h;} ``` [Try it online!](https://tio.run/##LVBRboMwDP3PKSImUNKZ0gBt16Vh6s6xnyhAg0ShBbogunL0sdDVsi3bek9@tvKPSk1TTgxoGKCnt7ysZYcvfBCjP3gRmER/9MK8k15o0MJQntcNMYIx3tTXKiUXkfXnkIxDEC@DkQxBSP3leuH7hi5YFtF9//MEBu2l6UhI6V573mg45bI9N0XV5cTT4LjKTR0YXjdrsFuM0Pw@vRSVKq9phvdtlxb1UicIWQI@yaIi33WRUnxDGM8jewG3pdKywW0xZBzZbtbKcatklRPHTWF25QD2jA1tY0bShHFqwRg/1Vgp2E1nFwl226/KMmYg2CXYsv7f9aBSju5TyN4g3G1BIgYMFNpZg0dSaBvDOoQDihjEMXyicAOMrVZw@FV5KY/t5JenyTd/ "C (gcc) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 157 bytes ``` lambda x,y,a:a+str((k:=[*zip(A:=[(int(2**((2+-(~-ord(a)%32)%3)/8)/2**(i/2)*1e3+.2))for i in range(12)],A[1:])])and~-sum(y<=q>r>=x or x<=q>r>=y for q,r in k)) ``` [Try it online!](https://tio.run/##VY1BboNADEX3PcVsqrHBlIyhDUElErlGymISQjtKM5AJlaCLXJ1C2krEkq3v5//lpm8/ahsljRuq7G341KddqUVHPelU@5fWARzTbOt9mwbyUYCxLbDnAbAfwDWoXQkaHyMeG8MEw@lmQkZPHSL/iRGr2gkjjBVO2/cDKMaC8q1KCyxQ2/IaXL5O0L9m57VbZ50Y3d3f0ospeyY3pY@IQ@Om7xWwSohXS5JaIj78U0WK5H5OVmPRbdzzZUzPTDKfs0hRHJPczBm/kFKLxa9z@AE "Python 3.8 (pre-release) – Try It Online") Outputs `X-1` if the image is too large. -4 bytes thanks to ErikF [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~41~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ƵàS8/o¤11Ýmδ/₄*εü2í}5z+ï²Ç`8%èε¹{‹O_}O<« ``` Pair with the dimensions of the picture as as first input; letter as second input. Outputs in the same case as the input, and with `-1` for error-cases above paper size `0`. [Try it online](https://tio.run/##AVAAr/9vc2FiaWX//8a1w6BTOC9vwqQxMcOdbc60L@KChCrOtcO8MsOtfTV6K8OvwrLDh2A4JcOozrXCuXvigLlPX31PPMKr//9bODQxLDU5NF0KQQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaFjE/2NbDy8IttDPP7TE0PDw3NxzW/QfNbVondt6eI/R4bW1plXah9dHHG5PsFA9vOLc1sjqRw07/eNr/W0Orf6v8z86OtrI0ELHyNI8VkcpUSlWRyE62lDHEMhJhnAsgUAHRCCEzE10TI2AXEcI19hQx8QEyHWCcI3MdAwNDQwQ8hYmhjqmliYQgVgA). **Explanation:** ``` Ƶà # Push compressed integer 324 S # Convert it to a list of digits: [3,2,4] 8/ # Divide each by 8: [3/8, 1/4, 1/2] o # Take 2 to the power each of these: [1.296..., 1.189..., 1.414...] ¤ # Push the last item of the list (without popping the list itself): # 1.414... (which is sqrt(2)) 11Ý # Push a list in the range [0,11] m # Take sqrt(2) to the power each of these integers δ # Apply double-vectorized over the two lists: / # Divide ₄* # Multiply each by 1000 ε # Map each list of lists to: ü2 # Create overlapping pairs of the list í # And then reverse each pair }5z+ # After the map: add 1/5 to each value (fix for A0 and C0) ï # Floor every decimal by casting it to an integer ``` We now have a list of paper sizes, grouped per letter: ``` [[[917,1297],[648,917],[458,648],[324,458],[229,324],[162,229],[114,162],[81,114],[57,81],[40,57],[28,40]], [[841,1189],[594,841],[420,594],[297,420],[210,297],[148,210],[105,148],[74,105],[52,74],[37,52],[26,37]], [[1000,1414],[707,1000],[500,707],[353,500],[250,353],[176,250],[125,176],[88,125],[62,88],[44,62],[31,44]]] ``` ``` ² # Push the second input-letter Ç # Convert it to a list of codepoint integers ` # Pop that list, and push its only integer to the stack 8% # Take modulo-8 on it (A→1, B→2, C→3, a→1, b→2, c→3) è # Index it into the list of lists (0-based modulair, so 3 will index into the # first inner list) ε # Map each pair in the list to: ¹ # Push the first input-pair { # Sort this pair from lowest to highest ‹ # Check if the sorted input-pair is higher than the current pair O # Sum those checks together _ # And check that it's 0 (thus both were falsey) }O # After the map: get the amount of truthy values by summing < # Decrease this by 1 « # And append it to the (implicit) second input-letter # (after which it 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 `324`. [Answer] # [Haskell](https://www.haskell.org/), ~~154 135~~ 139 bytes ``` f a b c|d<-[y|(x,y)<-zip"abcABC"$cycle[1189.4,1414.4,1297],x==c]!!0=c:(show$sum[1|x<-[0..10],max a b<d*2**(-x/2)&&(d/min a b)**2/2>2**x]-1) ``` [Try it online!](https://tio.run/##RU/RboMwDPyVtKpKQAbiLC0wwaR2z/sClIcQWhUNGBqbFlD/nSV00vxg3/mk8/mmxvdL2y7LlShSEX2v87Cc7tTA5Ofh3AxbVenT@XW705NuLyVimkUCUKBwg2eJBFMUWm42rNDPdLx9/OzG767Eu7FOLIqQSeiUcfZ5HfAgoKGJub/f0zrumt7t/SDgMX@xmpEh@kunmr7o1PBGhs@m/yLllRgykXmNBbMNVlKOKdjr4CnPB4qA4GmHMluwtgdPBBw4eCeHnxCEAO/sMD8CImN/insLSCoQyMOQHxhgYu2rf3ZcmZTLLw "Haskell – Try It Online") * Saved 21 bytes thanks to @ovs ! * Fixed bug notified by @HyperNeutrino Added 0.2 to the precomputed constants `1189.2071150027211, 1414.213562373095, 1296.8395546510096` to fix rounding issues. The resulting table [here](https://tio.run/##y0gszk7Nyfn//39uYmaebUFRZl6JgkpuYoFGTIquXbRGWk5@fpFKipaRlpaGboW@kaYOiohGhbahJlBUs6bCRjfaQE/P0CA2VjPa0NDCUs9Ex9DE0AREGVmax/4HAA "Haskell – Try It Online") . ``` f a b c= - function tacking sizes(a,b) and format (c). |d&lt-[y|(x,y)&lt-zip"abcABC"$cycle[1189.4,1414.4,1297],x==c]!!0 - get the precomputed constant relative to input(c) c:(show$ - returns a string composed of format followed by result sum[...]-1 - count all valid sizes => 0 index [1|x&lt-[0..10],max a b&ltd*2**(-x/2)&&(d/min a b)**2/2&gt2**x] - compute 0..10 sized and yield 1 if valid ``` * outputs "{format}-1" for invalid input. ]
[Question] [ I've been recently playing through '[The Weaver](http://pyrosphere.net/weaver/)' and I think it presents an interesting challenge for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). # Premise: The Weaver is a game wherein you are given a number of ribbons coming from 2 directions 90 degrees apart and your goal is to swap them at certain intersections to achieve a desired output.    Like this:         This is a swap:         This isn't: [![Like this](https://i.stack.imgur.com/xbEU7.jpg)](https://i.stack.imgur.com/xbEU7.jpg)[![swap](https://i.stack.imgur.com/lYTN7.jpg)](https://i.stack.imgur.com/lYTN7.jpg)[![not a swap](https://i.stack.imgur.com/zlvGF.jpg)](https://i.stack.imgur.com/zlvGF.jpg) # Input: 3 arrays: * Top ribbons (left to right) * Left ribbons (top to bottom) * The coordinates of the intersections to swap # Output: 2 arrays: * Bottom ribbons (left to right) * Right ribbons (top to bottom) # Examples: I'll use the above image as the first example: Input: `[r, y, b], [r, y, b], [(0, 1), (2, 1), (2, 2)]` What happens: ``` r y b r y b r r r r•y y y y r r b y y y y y y y y r r b b b b b•r r•b b r b r r b r ``` Where `•` represents a swap. Output: `[r, b, r], [y, y, b]` --- Input: `[a, b, c], [d, e, f], [(0, 0), (2, 1)]` What happens: ``` a b c a b c d d•a a a a a a d b c e e e e e e e e d b c f f f f•b b b b d f c d f c ``` Output: `[d, f, c], [a, e, b]` --- Input: `[a, b], [a, b, c], [(0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 1)]` What happens: ``` a b a b a a a a•b b a a b b•a a•a a b a c c•b b•a a c b c b ``` Output: `[c, b], [b, a, a]` # Notes: * The examples show coordinates given as `(row, column)` though you may take them as `(column, row)`. * The top row and left column may have ribbons of the same color * The board can be rectangular * All coordinates will be non-negative (`>=0`) (or strictly positive (`>=1`) if you choose 1-indexing) * Ignore any swaps that are outside the board * You may choose to work with letters (`[a-zA-Z]`), integers (`[0-9]`) or both * The ribbons in your output must match the ribbons in the input exactly (`a -> a`) * You may assume the list of swaps is sorted in any way you want, as long as it's consistent (if you do, please specify how it should be sorted) * You may take the swap coordinates as 0 or 1-indexed * [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden # More examples: ``` Input: [b], [r], [] Output: [b], [r] Input: [b], [r], [(0, 0)] Output: [r], [b] Input: [r, p, y], [r, y, p], [(0, 0), (1, 2), (2, 1), (3, 2)] Output: [r, p, y], [r, y, p] Input: [b, y, o, r], [r, o, b, y], [(0, 0), (2, 0), (3, 2)] Output: [b, y, y, r], [b, o, r, o] ``` The last example relates to this case (if that makes it easier to visualize): [![example](https://i.stack.imgur.com/xfirK.jpg)](https://i.stack.imgur.com/xfirK.jpg) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes for each language wins. [Answer] # [Python 3](https://docs.python.org/3/), 74 bytes ``` def g(a,b,l): for x,y in l: if x<len(a)and y<len(b):a[x],b[y]=b[y],a[x] ``` [Try it online!](https://tio.run/##bU9BjsMgDLzzipF6ACQf2vQWbV@COICatJGiBLGRNrw@a5Nke1kJezwwHptUlvc83bft2fV4mUCRRtsq9HPGSgXDhJEphh7r19hNJtgwPVFqHW0b3OopuuIfkkhotepPK1zwk0NKXcbyDgtSHqblWyE8gmu9QuRGwZeJFLhB7Qppt0r1xumoPcHpXMFbdYGLUmb/z7u5Eq52V2W5iIcqa9KJo5xqKeXq00UwN0Ij2BBugnfhhxshEUqdzMjsb/5uNXPIEru5sHjM@/g3B56@9TPVjQ/vK2TmirPffgE "Python 3 – Try It Online") Requires `l` to be sorted in lexicographical order. `a` and `b` are lists of characters representing (left ribbon, top ribbon). Returns by modifying the list `a` and `b`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ ~~35~~ 30 bytes ``` ṙ"z0U1¦Zḟ€0ṙ"N} <Ạ¥ÐfL€}⁹ṭṚç/Y ``` [Try it online!](https://tio.run/##y0rNyan8///hzplKVQahhoeWRT3cMf9R0xoDkIhfLZfNw10LDi09PCHNByhY@6hx58Odax/unHV4uX7kfyABFMx61Ljv0LZD2/7/j@aKjo7ViVYvUtdRT1KPjdUB8qMNdAxiMQSNdYyAYkY6hkDSEMyGK6ssACosKqhEV2qArCg/qRJkXGV@EVAZVywA "Jelly – Try It Online") Dyadic program, take 0-indexing list of swap indices as left argument (sorted in reverse lexicographical order) and (left ribbon, top ribbon) as right argument. Returns (right ribbon, bottom ribbon). --- Jelly is a tacit language. There is (almost) no variable to work with, so doing anything involves more than two variables at once is a mess. The first link takes `[l,t]` as its left argument, `[x,y]` (0-indexing) as its right argument, and return `[l,t]` with `l[x]` and `r[y]` exchanged. ``` ṙ"z0U1¦Zḟ€0ṙ"N} ṙ" Zipwith rotate. Current value: `[l ṙ x, t ṙ y]` (so l[x] and r[x] becomes l[0] and r[0] respectively) z0 Zip, fill with 0. Elements at corresponding (new) indices are paired together, with 0 as the filler. U1¦ Reverse the pair at index `1` (first index). Zḟ€0 Zip again and filter out the `0`s, effectively undo the z0. ṙ"N} Zipwith rotate by negative shift amount, reverse of `ṙ"`. ``` So basically "`U1¦` under `ṙ"z0`". --- The second link simply filter out OoB indices (`<Ạ¥Ðf L€`), append the second argument (`⁹ṭ`), reverse (`Ṛ`), and reduce over `ç` (similar to Haskell's `foldl`) [Answer] # [Python 2](https://docs.python.org/2/), 193 bytes ``` def f(t,l,s): m=[[x,y]for y in[0]+l for x in[0]+t];L=len(t)+1 for i in range(len(m)): if i%L:m[i]=[m[i-L][0],m[i-1][1]][::[1,-1][(i/L,i%L)in s]] s=sum(m,[]);print s[2-L*2::2],s[4*L-1::2*L] ``` [Try it online!](https://tio.run/##bZHdboMwDIXveQpL00TSutqS9oqKN@ANIl9ACxtS@REwqTw9swOjo5uEjI2dzyeHdhw@m9pO0zUvoFAD3rDXUQBV7NwdRyqaDkYoa/dO@xtIdV@qgc5JfMtrNei9CXyr5BZ0af2RK2lUWkhQFlC@JlHlSoodx0NCfB4lM@QMkYsiZ1AKVb4lyMOaOT1RAH3cf1WqQkf63HZlPUDv7CHZ2SiyhL077ZKD4XyX0FQoF3YhQjhKyEJC@PtBGQSrEdTx8T5q0sGL6xAyhE6mRgR@MgoCgabzcQ6XGXqVPJdQrFCzQj3silAgXKSbIuR/YJ7zDF7F2YVnHyLNb9Gndc9FyHyUlfOedFmyXl5efs4Pdf@1Z/GzA560DHnn2tm@Jyvb7a2tWLhV97C0ZSv9bm9puyr4YTUSRMmyoFk9kbUba80WnnniuPwyrhpOOdL0DQ "Python 2 – Try It Online") Takes 1-indexed swap coordinates [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~31~~ 30 bytes ``` {⊃{⌽@(0 1,¨⍺)⊢⍵}/(⍵∩,⍳≢¨⍺),⊂⍺} ``` [Try it online!](https://tio.run/##TY89TsQwEIV7TrGdbSkrkqWj4ip2skYRkRx501irNIAQGzCi4QBsBRIdolmJhqPMRcKznQ004xm/782PbJtl5WRjLpdlIzebuhzp6aU2dPecjxpxS8PNlh6/L3i@KLKfN/IHQcOe/Fd/yhHp/j0j/0m7fdIyGq7x9uPYRTeI3Sv8FhXHi3YB01OK6A/nzFwxerhlWtYNwwdctj/hzDrFFjEKHuYLvkphJUTHrLJQHVSgUpUoqrVOaJ5QUJUOglxPVMiBHvsVgSxS08nDz5KxDKySEj7czTBMkP/opvzvk4eTw8Qo2TjHti4u3s7bFNj52D5tPyPglTPhFmuU@7d/PsPKuaArYw37BQ "APL (Dyalog Classic) – Try It Online") The left argument is a pair of character vectors - left ribbons and top ribbons. The right argument is a vector of coordinate pairs - swap locations. Returns a pair of right ribbons and bottom ribbons. (Note that unlike in the examples, I use the order left-top and right-bottom for the ribbons in order to be consistent with the row-col axis order in the coordinates.) Swaps must be sorted so that a swap to the upper-left of another comes ~~before~~ *after* it. If two swaps are to the lower-left/upper-right of each other, their order doesn't matter. EDIT: saved one byte (`⌽`) by requiring reverse order of swaps in the input [Answer] # Javascript, ~~87~~ ~~76~~ 62 bytes ``` (c,r,s)=>{for([i,j]of s)if(r[i]&&c[j])[r[i],c[j]]=[c[j],r[i]]} ``` [Try it online!](https://tio.run/##bZBNboMwEIX3nOKJRQTSNAnpsiJH6AWQF8aBiijBlk1@UJSz07GBEFWVwAzz/L35OcqrdMo2pvto9aEa6nxIFFlyab5/1NomRUNHoWu4tKkTWzRitVLFUaSFj8mHIi/8h3xCPIf60qqu0S26ynWJ1TeC0qfLuSW4mzQuxSMCrtLCIgfra2dOTZfEiNOvSVGsjNA/omMxOL1p67M0yR35Hvc5S1P2@3IuK5sGnCcgxbP5WOnW6VO1PukfzkJx8hlFoenYokcZE5ZgSxl24d3FabTZoGCmJFhBKHoCP6WYcYkSylMHVKhHfOvxCT0Qaq7oUUmo/qD@/svB180YzkLtYILPl5HyKLtwI2wkXy5j7/6YLoZb9h@dG5vnCUZiWYFBP6/AzDNktJtaeFuD4fGDf1iDWaowqWFHE80T9csqtm8WZeD6sEz/ozniUwy/ "JavaScript (Node.js) – Try It Online") Same trivial algorithm as the Python 3 answer. Uses arrays as coordinate tuples. Requires ribbon colors to be designated by truthy values. Requires coordinates to be partially ordered so that `x1,y1` comes before `x2,y2` if either `x1 < x2 && y1 = y2` or `x1 = x2 && y1 < y2`. Returns by modifying input arrays. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56~~ 54 bytes ``` ->t,l,s{s.map{|i,j|a=t[j];t[j]&&=l[i]||a;a&&l[i]&&=a}} ``` [Try it online!](https://tio.run/##fVFNk4IwDL3zK3LiFHcsHpmuP6STQ@rKDIw7y6AeGPG3swlgBS0e0nz05b2kba6@7Qvbb74veMLz7fz1y/WtK7Hq2F5cRbkeaWpPrqSu45zTVEOp8P3eM4IHC27vCeVsKIfCaVEykqSGISOwAnqiKEk@dbotwpYi/c2A9Yv@BmFfi7Ujj0ZaeeeTwCBk6jMEo36neUxnhXMx91T9E5O5khGn2XAT1c8mv6b74GwDp38oqH/bW3F@MaN/1TXzfbMP@/pRU7jawDXX4wlzGDA/Eh3FirU9TUxHu4rAwRNHRCfcj4qxnczzT838bWd/G53hEPiVWzWYqP8H "Ruby – Try It Online") A port of [user202729's Python 3 answer](https://codegolf.stackexchange.com/a/162839/77598) with some ruby tricks Coordinates have to be lexicographically sorted ]
[Question] [ The [trumpet](https://en.wikipedia.org/wiki/Trumpet) is a valved aerophone instrument, usually pitched in `B♭`. The sound is made when the player vibrates their lips to displace air inside the instrument. That vibration is acquired by setting one's mouth in a specific way, called the embouchure. Different embouchures, with tighter or looser lips, produce different pitches. Furthermore, each valve in the trumpet also changes the pitch of the instrument. When depressed, a valve closes a path inside the tubing of the instrument, making the air flow through a longer path, thus lowering the pitch of the original sound. For the purposes of this challenge, we'll consider the standard, `B♭` trumpet, in which the first valve lowers the pitch by a full step, the second lowers the pitch by a half-step, and the third lowers the pitch by one and a half step. ### The Challenge Your challenge is to create a program or function that, given two inputs `embouchure` and `valves`, determines the pitch of the note being played. For the purposes of this challenge, the notes will follow the sequence: ``` B♭, B, C, C♯, D, E♭, E, F, F♯, G, G♯, A. ``` ### Rules * I/O can be taken/given in any [reasonable method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?s=6|22.7639) apply. * You're allowed to use `b` and `#` instead of `♭` and `♯` if you wish to. * Input for `valves` can be taken as a list of depressed valves (`1, 3`) or a boolean list (`1, 0, 1`). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in each language wins. ### Test Cases: `Valves` in these test cases is given as a boolean list, where 0 means depressed and 1 means pressed. ``` Embouchure: Valves: Output: B♭ 0 0 0 B♭ B♭ 0 1 0 A B♭ 1 0 1 F C♯ 0 0 1 B♭ C♯ 1 1 1 G E♭ 1 0 0 C♯ G 0 1 1 E♭ G♯ 1 0 0 F♯ G♯ 0 0 1 F G 1 0 0 F F♯ 1 0 0 E D 1 0 1 A A 1 1 1 E♭ E 1 1 0 C♯ E 0 0 1 C♯ ``` **Disclaimer:** I'm not much of a musician yet, so I do apologize for any butchering I might've made on the test cases. Corrections are appreciated. [Answer] # Python ~~3~~ 2, ~~125~~ ~~119~~ 81 bytes ``` lambda e,f,s,t,n=2*'A G# G F# F E Eb D C# C B Bb'.split():n[n.index(e)+2*f+s+3*t] ``` [Try it online!](https://tio.run/##TY/NDoIwEITP@hST9NAWKgG9mWDCbx9CPUikkUQLgR706dECarOX/TIzO9nuZW6t3o0qPo33y6O6XlALJQZhhI63Hk0gCSRKghIFigo5MoIMKdKKBkN3bwzje33UQaOv9ZPV3N96yh/8nWfOo2p7mHowaDQYo5@ICO1w8YXoD5FFCxmZbT@I7FgoFtuUkXN@EiRxBTcvHaF0XbnTmLgd8x4u@3yI79errm@0YfYdAbo5UAHFPIucj28 "Python 3 – Try It Online") Saved a lot of bytes thanks to Jonathan Allan. --- My original solution (in **Python 3**): ``` n=2*'Bb B C C# D Eb E F F# G G# A'.split() e,f,s,t=str(input()).split() print(n[n.index(e,9)-2*int(f)-int(s)-3*int(t)]) ``` [Try it online!](https://tio.run/##TY2xDoIwFEV3f6ND3yO3RGByYBAEPsK4EEtsYp4NfSb69VWcnG7OOcONb709pMlZ2rqw3YwOPXqDE4YZA0aMBhMmg6MtU7wHJQvLO48FCdomXSlIfCox//e4BlGSs5RBrv5FHgd2dbHJhd02iV3zY@UL5/x9rrBH9QE "Python 3 – Try It Online") Saved 6 bytes thanks to @HyperNeutrino. --- ### Explanation First, I make an array of notes, but doubled in length so I don't have to worry about looping around from `Bb` to `A`. Then, I take input in the following format (for example): ``` Bb 1 0 1 ``` I then find the index of the starting note using `n.index(e,9)` (the `9` is there to make sure that I start well in the middle of the (doubled) list. I calculate the desired offset with the expression: ``` 2*int(f) - int(s) - 3*int(t) ``` Where `f` is the first valve, `s` is the second valve, and `t` is the third. Finally, it simply prints the note found in the list by subtracting the offset from the starting index. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 100 bytes (and 134 for a working trumpet) ``` l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]]& ``` [Try it online!](https://tio.run/##VYy9CsIwGEV3n0LyQRdvhrRupVCb/kxCoWPIkKrVQNqKZs6rR0UQhHuWc@DOxt8us/H2ZGJ0BatGVJCQhBrNiAYtWkKHjnBgYfAPu1yHu7M@MLB8KpxSx/WsKCnLDy7069N6uy6BeEopp4xntOcCItU7oXUS@/eFV5NiNcNWfKd1vvl5SX8hvgA "Wolfram Language (Mathematica) – Try It Online") Quite straightforward. ``` l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=EmitSound@SoundNote[l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]],1,"Trumpet"]& ``` A better output for the cost of 34 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị® ``` A dyadic link accepting the valves as a list of `1`s or `0`s as a list representing `[second, first, third]` on the left and the embouchure as a list of characters on the right which returns a list of characters. **[Try it online!](https://tio.run/##AVUAqv9qZWxsef//w5hB4bijNzvigb4jYuKAnMKuSlhy4bqK4bukyKXigJnhuYNuxZJsJMWT4bmXJOG4isKpaV/igbjDpi5KwqThu4vCrv///zAsMSwx/0Ji "Jelly – Try It Online")** ### How? ``` ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị® - Link: list of integers, V; list of characters, E ØA - yield uppercase alphabet ḣ7 - head to index 7 = "ABCDEFG" ⁾#b - literal list of characters = "#b" ; - concatenate = "ABCDEFG#b" “®JXrẊỤȥ’ - literal integer = 2270857278734171 ṃ - base decompress (i.e. convert to base 9 using the 'digits' "bABCDEFG#") - = "ABbBCC#DEbEFF#GG#" $ - last two links as a monad: $ - last two links as a monad: Œl - to lower case = "abbbcc#debeff#gg#" n - not equal? (vectorises) = [1,1,0,1,1,1,0,1,1,0,1,1,1,0,1,1,0] œṗ - partition at truthy indices = [[],"A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"] Ḋ - dequeue = ["A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"] © - copy to register and yield i - first index of E in there ¤ - nilad followed by links as a nilad: ⁸ - chain's left argument, V J - range of length [1,2,3] æ. - dot product (i.e. 1*second + 2*first + 3*third) _ - subtract ® - recall from register ị - index into (1-based and modular) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 71 bytes ``` ->e,(b,c,d){a=%w{Bb B C C# D Eb E F F# G G# A};a[a.index(e)-b*2-c-d*3]} ``` [Try it online!](https://tio.run/##dZLRboIwFIbveYo/bZaoKUS2y8UlgIWHYFxQWjeTDQkic1GfnRWUDnBLGtKer//HKbQ8iO9ms2rsF8VmgmVMzk/p6uHr5Av4CBBQrMEFOEKEFBEiCu/ynMaps82lOs7U3BaLRzuz5eIpuTTFodqDqE/h4LWq049a7QE9fdtV@qmOhcoqJYllxRYQE18QhnjJ0I6EoS0kbIzcG/IIRsjtUm6LQoMC@it0x8IrcjthhyKT4gNh9y6994YiTfo2uhQ3wohOUiEdo@VfHV6Fw5RB4VTIDVoPUu74a3g9uu@QD9DkXLw/Vy9skZU4Ks3eIXc4K1az8qz3FuU2r6DMjOgfScyq/qe@ibUguYft/SgtlcvmBw "Ruby – Try It Online") ### 70 chars but 80 bytes ``` ->e,(b,c,d){a="B♭BCC♯DE♭EFF♯GG♯A".scan /.\W?/;a[a.index(e)-b*2-c-d*3]} ``` [Try it online!](https://tio.run/##dZLRboIwFIbveYqTXqkpuG6Xiy6ohUfYBXJR4LiZbEgAicvcg/gQy97JF2Gl2oKwJaQ57df/6ymQ76OPejOr7TnSUURjmow/xYwszqfvxXJ5Pv2suCy558nS9@XgEqeIRQpTZ/38NH0UgXC2aYKHEY7taHJvx3YyeQi/6mxfFkDwPXJgXVbircICQJYvu1KOeMgwLjEhlhVYAIE6kFAI7ig0T0jhshTSPmZX7BLoQaayrIGegc0dWjHrizVmSqywb7L8RqxOVfuv2JdMt6SSvCP2W7HOet3ssK2254u4mzTIG2q5gatOjt2@I1ejv3rlHTi4Jde31NILtEIHRfwKyQ6OSCuaH@XuLN@mJaCpiPzUxMyqf9Y3gRSEQ9j8QbmFaVL/Ag "Ruby – Try It Online") [Answer] ## Javascript 96 bytes Following @vasilescur idea, this is the implementation in js ``` (a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)] ``` ``` a=(a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)] console.log(a('B♭',0,0,0)) console.log(a('B♭',0,1,0)) console.log(a('B♭',1,0,1)) console.log(a('C♯',0,0,1)) console.log(a('C♯',1,1,1)) console.log(a('E♭',1,0,0)) console.log(a('G',0,1,1)) console.log(a('G♯',1,0,0)) console.log(a('G♯',0,0,1)) console.log(a('G',1,0,0)) console.log(a('F♯',1,0,0)) console.log(a('D',1,0,1)) console.log(a('A',1,1,1)) console.log(a('E',1,1,0)) console.log(a('E',0,0,1)) ``` [Answer] ## Batch, 188 bytes ``` @set n=%1 @set/aC=0,D=2,Eb=3,E=4,F=5,G=7,A=9,Bb=10,B=11,n=(%n:#=+1%+12-%2*2-%3-%4*3)%%12 @for %%n in (C.0 C#.1 D.2 Eb.3 E.4 F.5 F#.6 G.7 G#.8 A.9 Bb.10 B.11)do @if %%~xn==.%n% echo %%~nn ``` Uses `#` and `b`: this means that `Eb` and `Bb` are legal variable names; `#` is handled by doing a string replacement to `+1`. The result of the string replacement is then automatically evaluated and the valves are then taken into account before the result is looked up in a list. [Answer] # [Stax](https://github.com/tomtheisen/stax), 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` τ┤=Yº○!AÄΔâß₧←╥╟ö'ÄD├æñßf╧å▬tó÷╖ ``` [Run and debug it online](https://staxlang.xyz/#p=e7b43d59a70921418eff83e19e1bd2c794278e44c391a4e166cf861674a2f6b7&i=[]+%22Bb%22%0A[2]+%22Bb%22%0A[1+3]+%22Bb%22%0A[3]+%22C%23%22%0A[1+2+3]+%22C%23%22%0A[1]+%22Eb%22%0A[2+3]+%22G%22%0A[1]+%22G%23%22%0A[3]+%22G%23%22%0A[1]+%22G%22%0A[1]+%22F%23%22%0A[1+3]+%22D%22%0A[1+2+3]+%22A%22%0A[1+2]+%22E%22%0A[3]+%22E%22&a=1&m=2) It takes a note name and a list of depressed valves. It builds an array of note names, then calculates the total valve interval, and gets the note at that offset in the array. ``` "AbABbBCC#DEbEFF#G" just a literal {VA#}(Y partition at capital letters and store in y ,]I get the index of the input note ,2R:t swap 1s and 2s in valve list {-F subtract valve list from note index y@ look up result from note array ``` [Run this one](https://staxlang.xyz/#c=%22AbABbBCC%23DEbEFF%23G%22%09just+a+literal%0A%7BVA%23%7D%28Y++++++++++++%09partition+at+capital+letters+and+store+in+y%0A,]I++++++++++++++++%09get+the+index+of+the+input+note%0A,2R%3At++++++++++++++%09swap+1s+and+2s+in+valve+list%0A%7B-F++++++++++++++++%09subtract+valve+list+from+note+index%0Ay%40+++++++++++++++++%09look+up+result+from+note+array&i=[]+%22Bb%22%0A[2]+%22Bb%22%0A[1+3]+%22Bb%22%0A[3]+%22C%23%22%0A[1+2+3]+%22C%23%22%0A[1]+%22Eb%22%0A[2+3]+%22G%22%0A[1]+%22G%23%22%0A[3]+%22G%23%22%0A[1]+%22G%22%0A[1]+%22F%23%22%0A[1+3]+%22D%22%0A[1+2+3]+%22A%22%0A[1+2]+%22E%22%0A[3]+%22E%22&a=1&m=2) [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ 79 bytes ``` lambda e,a,b,c,s='Bb B C C# D Eb E F F# G G# A'.split():s[s.index(e)-2*a-b-3*c] ``` [Try it online!](https://tio.run/##bY@7DoIwGIV3n@IkHaCmEIubiQOXtg@hDi1CJFEkwqBPj9ZKuMT82/nac2le3eVeR325P/ZXfTNnjYJpZljO2r2XGCRIkRJkEAYCEpJAQRHEXtg216rz6a49tGFVn4unX9AgWuvABNt1fuqbR1V3KP2Pjcc29igBErNaAO5APNe5JVaXo54SZ8SXRhZwexaoURc/o29ASkagXDCn@AAxcVJk8kOSOdj86aSG95jrcmokRj0bpmG@OR4WLBsJB1zAdIMYCjnQvwE "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~92 86~~ 82 bytes ``` *r=L"扢bc⍣d扥ef⍦g⍧a",*u;v(z,y,x,w)short*z;{u=wcschr(r,*z);u-=2*y+x+3*w;u+=(u<r)*12;} ``` [Try it online!](https://tio.run/##hVJNboJAGN1zignGBMYxOrqkNLEtuOkRusERwaRqMwj@xQO48ABu27RdNb0TC69BZxiIgyPp97GYvPe@970BSDsgJMsgtZ/18@F9RNLjx/h8@PQn6fErSI/fno5gbCXGFm3QGq3MKFzQJdxau9hekYiE1KAIbk0rbts9uGmtW324suKWbcR31IS4Z@2zNzqdLw0SehQCfzZaxCT0KQIMBIn3mvhYOvekc9/UdhpglRtMDL0Zgea4eOx70Ixe5jrKFUVJ7qVz6SocK@rE@FdvAtPS9po286Zzg8fpdB7S0w@Qq5s3L07dVuBCMbhF41zAy2X0Y3r6Vfyx7K8ocN68hox2bvmL9XySKYZAiSfGHbFgqC4oHdzCoT6kqy6Qxhnp1rs7jH4CNS@Hv7sBqLl4kdxR@crNHVCTOufFj6qPRjrq8mbfvgLhawhz8AKRhhi8gjDvC@QXg5JXINwlUdBQRap7oIgm6txYyempmQTSrSDlsn32Bw "C (gcc) – Try It Online") Adapted from [@Vazt's implementation](https://codegolf.stackexchange.com/questions/158228/help-me-play-the-trumpet/158399#158399). [Answer] # Perl6/Rakudo 73 chars Technically this is 83 bytes because I put the Unicode characters in, but swapping them for the ASCII equivalents would give 73 bytes. As a `{code block}` with parameters like `$^a` this is a lambda, with a signature `($a, $b, $c, $d)`. ``` {$_=2*$^b+$^c+3*$^d;'AG♯GF♯FEE♭DC♯CBB♭'x 2~~/$^a(\w\W?)**{$_}/~~/\w\W?$/} ``` Call it: ``` say { ... }("D", 1, 0, 1) >> A ``` Less-golfed: ``` sub f($a, $b, $c, $d) { my $totalShift = 2*$b + $c + 3*$d; my $doubledScale = 'AG♯GF♯FEE♭DC♯CBB♭' x 2; my $matchEmbOnward = $doubledScale ~~ / $^a (\w\W?)**{$totalShift} /; my $matchFinalNote = $marchEmbOnward ~~ / \w \W? $ /; return $matchFinalNote; } ``` Here we double a string `'...' x 2` using the `x` infix operator, then searching for the embouchure followed by n notes using the smartmatch operator `'...' ~~ /.../` - the regex hinges on `\w\W?` which is a word char then maybe a non-word char. We look for n instances of that via `(\w\W?)**{$_}`, where we've already calculated n=`$_` from params `$b` to `$d`. This yields a match from the embouchure note to the resulting note, of which we just want the last so we match that with another `~~ /\w\W?$/`. The calculation of `$_` first is necessary to permit `$^b` implicit param creation on the block. ## 76 chars An alternative using an array rather than string matches is 3 more chars: ``` {$_=<B♭ B C C♯ D E♭ E F F♯ G G♯ A>;.[((.first: $^a,:k)-2*$^b-$^c-3*$^d)%12]} ``` Finding the embouchure in the list is achieved with `@arr.first: $^a, :k`, which returns the index (key) of the found element with `:k`. Setting the array to `$_` (as an object) lets us use `.first` and `.[ ]` on it without spending too many characters. [Answer] # [C (gcc)](https://gcc.gnu.org/), 155 bytes ``` char r[][12]={"bb","b","c","c#","d","eb","e","f","f#","g","g#","a"};u;v(z,y,x,w)char*z;{for(;u<12;u++)if(!strcmp(z,r[u]))break;u=u-2*y-x-3*w;u=u<0?12+u:u;} ``` [Try it online!](https://tio.run/##hVPbboJAEH3nK7YYE1CILL51pY1twY@gPAACmtZLVhdv4UP8iKb/5I/QHS4JCpvOMGSZc@bM7AKhnoRhnocLnyLqei42PesiB4GsyRAhRI/f5jwiyEQ8YgjIJhCw8OWMMJIqZ@2kHbWDCnqDM7nEG6oQNsEmYcOhuoyVp92ehqstJ1KXeaoa0Mj/Isxiujk46Ud9PDjA08R4xeaQPTOS5Vu6XO@VQhFFq2DDwkVENcSTKPW/0wg31mZjPVali4S4FQKxIvd3qD@vLusF9Xefa1krGJU11GvlWrVUvGNTF6XKvyUq8lQiZZK08pdrBUYajd5u1x/UNKNwMIC6GbhiTLtgXBDAHA6/366/LX3c1G8xcOFgMw7bXfple6jkjBlqjVeW22WDWbtBreBUCuIhnXaDRjkHHbG6zeEPJDgcOLspEmy8mtxu43c7t5Fg6gIvP9biBzLA@buXmGWQewB3AxigRwB@P0MEYPBHIKqkWj2SsnerIOmJCkS9E0FBLFKaC3bni/ZQ5o2OfD1Qlv8B "C (gcc) – Try It Online") Simple approach. Valve input is 0,1. Embouchure input must be lowercase. Interestingly, TiO is not finding `strcmpi()` without including `string.h`, whereas mingw-gcc allows it with the standard `-Wimplicit-function-declaration` warning. ]
[Question] [ Philosophers have long pondered the [Trolley problem](https://en.wikipedia.org/wiki/Trolley_problem). Unfortunately, no human has solved this problem yet. Luckily, as programmers we can use computers to solve the problem for us! [![](https://i.stack.imgur.com/coK7c.png "☹")](https://i.stack.imgur.com/coK7c.png "☹") ## Input Your program will take as input a (finite) directed graph (with at most one edge from `x` to `y`, for any `x` and `y`), with a designated node, and a nonnegative integer attached to each edge (representing the number of people tied to that track). In addition, every node has at least one exit edge. The trolley starts at the designated node. Each turn, if the trolley is at node `x`, the utilitarian selects an edge `(x,y)`. The people on that edge die, and trolley is now at edge `y`. This process continues forever. Note that people can only die once, so if the edge `(x,y)` has `n` people tied to it, and the trolley runs over them, say, 100 times, it will still only result in `n` deaths. ## Output The utilitarian makes his choices in such a way as to minimize the number of people that die (which is guaranteed to be finite, since there are only finite people). Your program will output this number. ## Input format You may take the input graph in any reasonable way you like. For example, you could take it as a matrix, and count the designated node as the one labeled 0. Or you could use something like `x1,y1,n1;x2,y2,n2;...`. For example `0,a,0;a,b,5;a,c,1;b,b,0;c,c,0` to represent the standard trolley problem (with loops at the end). ## Testcases * `0,a,0;a,b,5;a,c,1;b,b,0;c,c,0` -> 1 (Go from 0 to a, a to c (killing one person), and then keep looping the trolley from c to c). * `0,0,1;0,a,5;a,a,0` -> 1 (Keep going from 0 to 0, running over 1 person for all eternity), * `0,a,5;0,b,1;a,a,1;b,b,6` -> 6 (0 -> a -> a -> a -> a -> ... (note that the greedy solution of going to b would be incorrect)) * `0,a,1;0,b,5;a,b,1;b,a,1` -> 3 (0 -> a -> b -> a -> b -> ...) * `0,a,1;0,b,1;a,a,0;b,b,0` -> 1 (Note that there are two different options that the utilitarian might take that both kill only one person) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! Good luck. Notes: There will be no [sick loop de loops](http://2static.fjcdn.com/pictures/Sick+loop+de+loops+man_fa2289_5585383.jpg) and [multitrack drifting](https://pics.me.me/multi-track-drifting-15209810.png) is banned. Also, although I prefer to think of this problem in terms of Asimov's three laws (/s) Peter Taylor has noted in the [sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/13395?noredirect=1#comment47605_13395) that this problem is mathematically equivalent to that of finding the rho (path the loops back on itself) of lowest weight. [Answer] # [Python 3](https://docs.python.org/3/), 80 bytes ``` y=lambda d,s=0,p=[],f=0:f in p and s or min(y(d,s+d[f][t],p+[f],t)for t in d[f]) ``` [Try it online!](https://tio.run/##JYoxCsQgFAWv8spIfmEi2wiexE3hIrLCxkhiI5Kzmy9bvcfM5Fq@R1K9mnf/uf3jHTxdRlI2dqNgpA6ICRkueVw4TuwxTXXiaPY2bLZslGc@VERgW0Y9hOj5jKlw2qRGWzTkTeBpq8aLoDQWBusfDMekqXFvIfoD "Python 3 – Try It Online") Takes input as a dictionary keyed by node id. The entries are a dictionary of neighbors and the number of people on the track between a node and the neighbor. E.g., for the first test case: ``` {0: {1: 0}, 1: {2: 5, 3: 1}, 2: {2: 0}, 3: {3: 0}} ``` 0 is the start node, 1 is node 'a', 2 is node 'b', etc. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 23 bytes ``` ṗL$µṭ0FIm2ASµÐḟµQ⁴ySµ€Ṃ ``` [Try it online!](https://tio.run/##y0rNyan8///hzuk@Koe2Pty51sDNM9fIMfjQ1sMTHu6Yf2hr4KPGLZVA7qOmNQ93Nv3//z/aQMcwVgdIGgFJQzDbCMj@H41DAsLRMdAxiAUA "Jelly – Try It Online") (last test case) [Cruel Version](https://tio.run/##y0rNyan8///hzuk@Koe2Pty51sDNM9fIMfjQ1sMTHu6Yf2hr4KPGLZVA7qOmNQ93Nvz//z/aQMcwVgdIGgFJQzDbCMj@H41DAkiZ6gC5OmaxAA "Jelly – Try It Online") (Mutilate the most people) Takes input as numbers. For the last example, `1` is `a` and `2` is `b`. `0` is the starting node. The first argument is the list of edges (e.g. `[0,1],[0,2],[1,1],[2,2]`), and the second argument is a list of the edges and the number of people on them (e.g.`[[0,1],[0,2],[1,1],[2,2]],[1,1,0,0]`). **How it Works** ``` ṗL$µṭ0FIm2ASµÐḟµQ⁴ySµ€Ṃ ṗL$ - on the first argument, get the Cartesian power of it to its length. this gives all paths of the length of the input. Cycles are implicit µ µÐḟ - get valid paths starting with 0 -- filter by: ṭ0 - prepend 0 F - flatten I - get the difference between elements m2 - every second difference: 0 for each edge that starts at the node the previous edge ended at, nonzero otherwise. AS - 0 iff all elements are 0 µ µ€ - on each path: Q - remove repeat edges. ⁴y - translate according to the mapping in the second program argument S - Sum Ṃ - get the minimum of these. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~90~~ 74 bytes *Thanks to Jo King for -16 bytes.* ``` my&g=->\a,\b=0,\c=@,\d=0 {a{d}&&b||min map {g a,b+$^f,(|c,d),$^e},a{d}.kv} ``` Port of [RootTwo's Python solution](https://codegolf.stackexchange.com/a/136512/14109). [Try it online!](https://tio.run/##LYzdCoIwHMXvfYr/hQ5Hp5hK3ciiBxnC5mxFLYZBIOqzL0fdHH7ngxOG8XmK0U/Myf1ZaSgjBVQvL1BWCpr1bFfGzLL4@4u8DjQ70jC7vLuiXHpYjrwbVqTd4fFZY5v5iQo36nAjSUUpsEkFEhxUJa5BR1CzuS2p/0lqm8RNYt5mbz2RK38/vI1f "Perl 6 – Try It Online") ]
[Question] [ ## Introduction As some of you may know, URLs actually have a list of characters that do special things. For example, the `/` character separates parts of the URL, and the `?`, `&`, and `=` characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: `$&+,/:;=?@`. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called [percent-encoding](https://en.wikipedia.org/wiki/Percent-encoding). Percent encoding is when you take a character's hexadecimal value and prepend a `%` character to the beginning of it. For example, the character `?` would be encoded as `%3F`, and the character `&` would be encoded as `%26`. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded. ## The Challenge You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. **Built-ins that accomplish this task are not allowed, nor are standard loopholes.** For reference, here is a list of every character that needs to be percent encoded: * Control characters (Codepoints 00-1F and 7F) * Extended ASCII characters (Codepoints 80-FF) * Reserved characters (`$&+,/:;=?@`, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40) * Unsafe characters (`" <>#%{}|\^~[]``, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60) Here is a the same list, but instead as a list of decimal codepoints: ``` 0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255 ``` **This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!** ## Test Cases ``` http://codegolf.stackexchange.com/ => http%3A%2F%2Fcodegolf.stackexchange.com%2F [@=>]{#} => %5B%40%3D%3E%5D%7B%23%7D Test String => Test%20String ÑÉÐÔ® => %D1%C9%D0%D4%AE => %0F%16%7F (Control characters 0F, 16, and 7F) ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ => %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF) !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ => %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E ``` [Answer] # Vim, 67 bytes/keystrokes ``` :s/\c[^a-z!'()*0-9._-]/\='%'.printf("%02x",char2nr(submatch(0)))/g<cr> ``` Note that `<cr>` represents the enter key, e.g. `0x0D` which is a single byte. This is a pretty straightforward solution. Explanation: ``` :s/ "Search and replace \c "Case-insensitive [^a-z!'()*0-9._-]/ "A negative range. Matches any character not alphabetc, numeric or in "!'()*0-9._-" \= "Evaluate '%' "a percent sign string . "Concatenated with printf("%02x",char2nr(submatch(0))) "The hex value of the character we just matched /g "Make this apply to ever match <cr> "Actually run the command ``` That `printf("%02x",char2nr(submatch(0)))` garbage is terribly *ungolfy*. [Answer] # Pyth, 30 28 26 bytes ``` L?hx+G+rG1CGbb+\%.HCbsmydz ``` [try it online](http://pyth.herokuapp.com/?code=L%3Fhx%2BG%2BrG1CGbb%2B%5C%25.HCbsmydz&input=http%3A%2F%2Fcodegolf.stackexchange.com%2F&debug=0) ## Explanation ``` L?hx+G+rG1CGbb+\%.HCbsmydz L?hx+G+rG1CGbb+\%.HCb First part, L defines the function y(b) ?hx+G+rG1CGbb+\%.HCb ? is the ternary operator hx+G+rG1CGb This part will be evaluated hx x will find the first occurence of a character in a list. If it doesn't find one, it will return -1. hx then equals 0 (or false). +G+rG1CG The list of allowed characters, a concetanation (+) of the alphabet (G), uppercase alphabet (rG1) and numbers (CG, see below for details) b The character to find in the list b True branch of the ternary operator, the character is allowed and returned. +\%.HCb False branch, convert to hex and add % smydz The actual program mydz Map every character in the input (z) using the function y on every d s Join the array, and implicit print. ``` `CG` is [this trick](https://codegolf.stackexchange.com/questions/40039/tips-for-golfing-in-pyth/53383#53383) that generate a huge number that contains all possible digits. This is perfect, since we don't care for duplicates when checking whether a string is in another. [Answer] ## Perl, 40 bytes **39 bytes code + `-p`.** A bit lame, but I think it's the shortest solution... ``` s/[^!'()*-.\w]/sprintf'%%%02x',ord$&/ge ``` ### Usage ``` echo -n ' !"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqstuvwxyz{|}~' | perl -pe "s/[^'()*-.\w]/sprintf'%%%02x',ord$&/ge" %20%21%22%23%24%25%26'()*+,-.%2f0123456789%3a%3b%3c%3d%3e%3f%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5b%5c%5d%5e_%60abcdefghijklmnopqstuvwxyz%7b%7c%7d%7e ``` [Answer] # Julia, 47 bytes ``` !s=replace(s,r"[^\w!'()*.-]",c->"%"hex(c[1],2)) ``` [Try it online!](http://julia.tryitonline.net/#code=IXM9cmVwbGFjZShzLHIiW15cdyEnKCkqLi1dIixjLT4iJSJoZXgoY1sxXSwyKSkKCnByaW50KCdcdTAwMDAnOidcdTAwZmYnIHw-IGpvaW4gfD4gISk&input=) [Answer] # Python 3, 92 bytes **5 bytes thanks to orlp.** **1 byte thanks to Sp3000.** ``` import re;lambda s:''.join(re.match("[!'-*.0-9\w-]",c,256)and c or'%%%02X'%ord(c)for c in s) ``` [Ideone it!](http://ideone.com/N53v0B) [Answer] # C, 83 bytes ``` f(char*p){for(;*p;++p)printf(isalnum(*p)||strchr("!'()*-._",*p)?"%c":"%%%02X",*p);} ``` [Answer] # Python, 86 bytes ``` lambda s:"".join(["%%%02X"%ord(c),c][c<"{"and c.isalnum()or c in"!'()*-._"]for c in s) ``` Port of my C answer. [Answer] # Ruby, 37 + 3 = 40 bytes Run with `-p` (3 extra bytes), like `$ ruby -p percent_encode.rb`: ``` gsub(/[^\w!'()*-.]/){"%%%02X"%$&.ord} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y ``` This is a monadic link. [Try it online!](http://jelly.tryitonline.net/#code=4bifw5hX4bifwqnigJwhJygpKi0u4oCdT2TigbTigJjhu4vDmEjigJ0lcMKuLHkKMjU24bi24buMw4c&input=) ### How it works ``` ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y Monadic link. Argument: s (string) ØW Yield “0...9A...Z_a...z”. ḟ Remove these characters from s. “!'()*-.” Yield “!'()*-.”. ḟ Remove these characters from s. © Copy the result to the register. O Ordinal; get the code point of each character. d⁴ Divmod 16; yield quotient and remainder modulo 16. ’ Decrement the results. ịØH Index into “0123456789ABCDEF”. ”p% Perform Cartesian product with ”%, prepending it to each pair of hexadecimal digits. ®, Yield [t, r], where t is the string in the register and r the result of the Cartesian product. y Use this pair to perform transliteration on s. ``` [Answer] # Haskell, ~~201~~ ~~179~~ ~~178~~ ~~127~~ 119 bytes ``` import Data.Char;import Numeric;f=(=<<)(\c->if isAlphaNum c&&isAscii c||elem c"-_.~"then[c]else '%':(showHex$ord c)"") ``` Ungolfed: ``` import Data.Char import Numeric f=(=<<) e e c = if isAlphaNum c && isAscii c && c `elem` "-_.~" then [c] else '%' : (showHex $ ord c) "" ``` [Answer] ## 16/32-bit x86 assembly, 73 bytes Byte code: ``` AC 3C 21 72 2A 74 3E 3C 26 76 24 3C 2B 72 36 3C 2C 76 1C 3C 2F 72 2E 74 16 3C 3A 72 28 74 10 3C 5F 74 22 50 0C 60 3C 60 74 02 3C 7B 58 72 16 D4 10 3C 09 1C 69 2F 86 E0 3C 09 1C 69 2F 92 B0 25 AA 92 AA 86 E0 AA E2 B8 C3 ``` Disassembly: ``` l0: lodsb ;fetch a character cmp al, 21h jb l1 ;encode 0x00-0x20 je l2 ;store 0x21 cmp al, 26h jbe l1 ;encode 0x22-0x26 cmp al, 2bh jb l2 ;store 0x27-0x2A cmp al, 2ch jbe l1 ;encode 0x2B-0x2C cmp al, 2fh jb l2 ;store 0x2D-0x2E je l1 ;encode 0x2F cmp al, 3ah jb l2 ;store 0x30-0x39 je l1 ;encode 0x3A cmp al, 5fh je l2 ;store 0x5F push eax or al, 60h ;merge ranges cmp al, 60h je l3 ;encode 0x40, 0x60 cmp al, 7bh l3: pop eax jb l2 ;store 0x41-0x5A, 0x61-0x7A ;encode 0x3B-0x3F, 0x5B-0x5E, 0x7B-0xFF l1: aam 10h ;split byte to nibbles cmp al, 9 ;convert 0x0A-0x0F sbb al, 69h ;to das ;0x41-0x46 ('A'-'F') xchg ah, al ;swap nibbles cmp al, 9 ;do sbb al, 69h ;other das ;half xchg edx, eax ;save in edx mov al, '%' stosb ;emit '%' xchg edx, eax stosb ;emit high nibble xchg ah, al l2: stosb ;emit low nibble or original character loop l0 ;until end of string ret ``` Call with: - esi = pointer to buffer that holds source string; - edi = pointer to buffer that receives encoded string; - ecx = length of source string. [Answer] ## Python 2, 78 bytes ``` lambda s:"".join(["%%%02x"%ord(c),c][c.isalnum()or c in"!'()*-._"]for c in s) ``` More nicely formatted: ``` lambda s: "".join(["%%%02x" % ord(c), c][c.isalnum() or c in"!'()*-._"] for c in s) ``` [Answer] # [SQF](https://community.bistudio.com/wiki/SQF_syntax), ~~199~~ 176 Using the function-as-a-file format: ``` i="";a="0123456789ABCDEF!'()*-.GHIJKLMNOPQRSTUVWXYZ_";{i=i+if((toUpper _x)in a)then{_x}else{x=(toArray[_x])select 0;"%"+(a select floor(x/16))+(a select(x%16))}}forEach _this;i ``` Call as `"STRING" call NAME_OF_COMPILED_FUNCTION` [Answer] ## PowerShell v2+, 146 bytes ``` param($n)37,38+0..36+43,44,47+58..64+91,93+96+123..255-ne33|%{$n=$n-replace"[$([char]$_)]",("%{0:x2}"-f$_)};$n-replace'\\','%5c'-replace'\^','%5e' ``` Long because I wanted to show a different approach rather than just copy-pasting the same regex string that every else is using. Instead here, we loop through every code point that *must* be percent-encoded, and do a literal `-replace` on the input string `$n` each iteration (re-saving back into `$n`). Then we need to account for the two special characters that need escaping, `\` and `^`, so those are in separate `-replace` elements at the end. Since we didn't re-save that final string, it's left on the pipeline and printing is implicit. ]
[Question] [ What general tips do you have for creating a bot to participate in a King of the Hill challenge? What strategies do you use to go from considering the challenge to creating your bot? What data structures do you find most useful? Please post one tip per answer. [Answer] ## Finding [Nash Equilibria](https://en.wikipedia.org/wiki/Nash_equilibrium) This is a very important concept when the KOTH involves a relatively simple set of decisions, involves only a few players (typically 2), and is deterministic. A Nash equilibrium describes a "gridlock" position: if the two players have decided upon their two strategies, then the two players are effectively locked in those positions: either player changing their strategy simply creates additional vulnerabilities. Examples of games where Nash equilibria are important are: * Rock-Paper-Scissors(-Lizard-Spock), in which an "unbeatable" strategy is random play * [Morra](https://codegolf.stackexchange.com/questions/45589/morra-the-noble-game-of-kings), which has a "spectrum" of equilibria. Peter Taylor wrote a good example in his answer [here](https://codegolf.stackexchange.com/a/45590/2867). * Prisoner's Dilemma, a cooperative game notable for having an "everybody loses" gridlock **How to find an equilibrium** Finding an equilibrium actually is actually pretty simple for most simple games, and is often pretty intuitive. A *ton* of detail about the various methods can be found on the internet. The basic concept, which is normally applicable, is to create a list of possible strategies that the two players can use (the options provided by the game). If one strategy is "dominated" by another, then that strategy can be removed from the list, and the process is repeated. By "domination," I mean that if strategy A always gives an equal-or-better result than strategy B, against all of the remaining opponent strategies, then strategy B can be removed from the list. **Example: Rock-Paper-Scissors** RPS has something called a "mixed" equilibrium, meaning that a *distribution* is involved. Rather than playing the same move repeatedly (which will lead to quick defeat), the equilibrium is to play 1/3 rock, 1/3 paper, and 1/3 scissors in a random distribution. If I play randomly, there is nothing my opponent can do to get an edge on me, period. If my opponent chooses not to play randomly, then that only creates a vulnerability on his part. Games with mixed equilibrium are probably the most common on PPCG, since they can take many forms (the *only* interesting game I can think of with a pure equilibrium is prisoner's dilemma). I should note that the mixed equilibrium doesn't have to be *uniformly random*, simply something other than playing the same move every time. **Using this information** The Nash equilibrium of a game often represents the "baseline" from which you should try to operate. In RPS, playing randomly guarantees a finishing spot around the middle of the pack. In order to move to the top, you have to start identifying other player's weaknesses. To do this, you should stick to the equilibrium when unsure of the opponent's weaknesses. Once those weaknesses have been identified (you have detected that your opponent is not in equilibrium), then you need to gently shift out of equilibrium to take advantage of your opponent. This action, in turn, creates weaknesses on your own part. You must then detect when your opponent is changing his strategy, so that you can then stop the attack and resume random play. **Detecting variation from equilibrium** This is pretty difficult, and I am not an expert. Variations can come in many forms: * Favoring some options above/below others for no reason, like an RPS player that plays rock twice as often as scissors, or one that avoids playing paper. Some relatively simple statistics can detect this. * Basing a current move off past moves, in some predictable pattern. This includes copy-cats, "beats what beats your last move" bots, or "cycling" bots. This takes additional logic to detect, since the overall move distribution can be evenly-distributed, even though the moves aren't random. You should attempt to take the record of moves and [find correlations](https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test#Test_of_independence) like "the move I made 2 turns ago and the move my opponent made now" and "the move he made 1 turn ago, and the move he made now", etc. * Bots whose move distribution is based off of yours. The vulnerability in these bots is often not created (in a measurable quantity) until *after* you have yourself varied from a random distribution. Generally, your own bot falls into this category. [Answer] # Use a meta strategy For almost every clever strategy there's another strategy that beats it: For example, your opponent might use exactly the same reasoning as you to anticipate your next move and then counteract it. Now you might try to second-guess your opponent again, but it's hard to know [when to stop](https://youtu.be/rMz7JBRbmNo). Another problem is that a strategy that is good at second-guessing a clever opponent might be far from optimal against more simple opponents. How can you solve this? You let your bot decide on the fly which strategy to use! For this, you start off with giving your bot a repertoire of different strategies. Then, before each move, your bot looks at the recorded history of the game so far and evaluates how these different strategies would have fared. It then pics the one that would have been most successful. Including strategies that are strong in the first place will help to give your bot good options to choose from. But you should also include really simple ones, because they often work better against dumb opponents. You might consider to put a bias on some strategies, either to avoid overfitting (e.g. trying to beat a pattern where the opponent just acts randomly) or to favor certain strategies in the beginning when there isn't yet much information. Of course, this approach will only work for certain kinds of king-of-the-hill challenges. It did really well for me in a [Rock-Paper-Scissors-Lizard-Spock match](https://codegolf.stackexchange.com/a/35181/29703). In other games it can be almost impossible to evaluate how a certain strategy would have fared if it was not actually played. An extreme form of this meta approach (that borders on cheating) would be to include the known behavior of all other bots into your own bot, such that it can perfectly anticipate their moves. [Answer] # Be specific about the requirements to run your bot Bots can be written in a variety of languages (and versions of those languages), so it helps everyone out when you: 1. Test it in the environment the OP specifies (or as close to it as you can). 2. Test it in a variety of other environments if possible (to help others who want to run it). 3. Be specific about the language and version you use, and explain how to run your bot. As a bonus: if you are using a lesser known language, make a link to where people can download the binary/source to run it. [Answer] # If team based, work together with your team While you can usually write a bot that works solo to complete tasks to help your team, there's a much greater advantage when you coordinate both in and out of the game. A prime example of this can be seen in [Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/questions/48353/red-vs-blue-pixel-team-battlebots/). During development, teams were able to chat and discuss how to coordinate their bots to function better than alone. While technically the same bot, [SphiNotPi3000](https://codegolf.stackexchange.com/a/48435/30793) was written to work in tandem with another of itself, and was able to move in ways that accounted for the weaknesses it would have faced if it were on its own. The end result was that they were able to almost completely dominate the battlefield, [even when it was just the two of them against the entire other team](https://i.stack.imgur.com/Va5yp.png). So outside the game, plan and coordinate with your teammates on what strategies to cover. Maybe someone has a bot that scans the map diagonally? Have yours scan horizontally (just an example). Inside the game, if the challenge allows for team communication, take advantage of it. In the battlebots game for example, you could send a message to your teammates on the position of bots outside their field of vision, and then encourage them to write their bots in a compatible way to make use of those signals. [Answer] # Add Randomness (if allowed) Making your bot move somewhat randomly, especially if there are multiple options that seem to be equally good, makes it far harder to predict the behavior of the bots. In some challenges, it's even worth having a probability of making a suboptimal move if other bots are designed to take the optimal move, as it makes it less likely you end up doing the same thing, which is a disadvantage in many challenges. As a bonus, if hardcoding behavior to go after a specific bot or calculating what moves they will make is allowed, randomness makes it significantly more likely you can put up a fight against them. ]
[Question] [ # Golf a Purple Interpreter [Purple](http://esolangs.org/wiki/Purple) is an esolang which is designed with two main purposes: * To be a minimization of [Aubergine](http://esolangs.org/wiki/Aubergine), since there just aren't enough self-modifying one-instruction languages around. * To admit the possibility of *terrifyingly small* golfed interpreters. My first pass at a reasonably full-featured Python 2 interpreter is only 702 bytes, and I'm sure a more experienced golfer could shave quite a bit from that. Your goal is to write an interpreter for this language. ## Information on Purple: A Purple program is a sequence of characters placed into an infinite, addressable memory array such that the first character of the program is placed at address zero. The rest of the array (both before and after where the Purple program is stored) is initialized to zero. There are three registers in Purple, called *a* and *b* and *i*, each of which can hold a signed integer and is initialized to zero. *i* is also the instruction pointer, and always points to the currently executing Purple instruction. Each cycle, the interpreter will read a sequence of three contiguous characters beginning from the memory location indicated by the instruction pointer and attempt to execute this sequence as the Purple instruction. Afterwards, the instruction pointer is always incremented by 3. Syntactically, the Purple instruction consists of three characters (or encodings thereof) in a row, like "*xyz*". The first character *x* can be any of the following: ``` abABio ``` These symbols have the following meaning: ``` a - Place the result in register a. b - Place the result in register b. A - Place the result in the location in memory referred to by register a. B - Place the result in the location in memory referred to by register b. i - Set the instruction pointer to the result. o - Output the result to stdout. ``` The other two bytes *y* and *z* can be any of the following: ``` abABio1 ``` Each of these symbols has the following meaning: ``` a - Return the contents of register a. b - Return the contents of register b. A - Return the contents of the memory array at the address stored in register a. B - Return the contents of the memory array at the address stored in register b. i - Return the contents of register i (the instruction pointer). o - Return the value of a single character read from stdin. 1 - Return the literal numeric value 1. ``` After fetching the instruction, the Purple interpreter will evaluate *y* and then *z*, subtract the result of *z* from the result of *y*, and then perform the action indicated by *x* on the difference. If the sequence of three characters (or encodings thereof) is not a valid Purple instruction, the interpreter halts immediately without giving any errors. ## Your interpreter must: * Be a complete program, not a function. * Never output to stderr, [unless EOF is read](https://codegolf.stackexchange.com/questions/65411/golf-a-purple-interpreter#comment158536_65411). * Behave identically to the reference implementation on all well-formed inputs that do not involve very large numbers, including the test programs given below. (Well, identically up to timing--it can run slower, but not by too much!) You may provide the program to the interpreter in any form you wish: read it from a file, embed it in the program as a string, or read it from stdin. ## Test cases: The program ``` ooo ``` when run with input ``` z! ``` should yield ``` Y ``` --- The program ``` bbboobiii ``` when run with input ``` It's a cat program. ``` (or any other input) should yield ``` It's a cat program. ``` (or whatever input it received) and then *start over and do the same thing again*. --- The program ``` Aoab11bi1bABoAaiba ``` when run with input ``` 0 ``` should yield ``` 0 ``` and then halt, but when run with input ``` 1 ``` should continue outputting ``` 1 ``` forever. --- The program ``` b1bbb1oAbabaa1ab1Ab1Bi1b ``` should yield ``` b1bbb1oAbabaa1ab1Ab1Bi1b ``` --- The program ``` aA1aa1bb1oAbbi1bb1bbAb1Bi1b Purple is the awesomest! Why haven't you tried it yet? !dlroW ,olleG ``` should yield ``` Hello, World! ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest source in bytes, as potentially modified by the following bonus, wins. ### Bonus: * -10% if your interpreter reads a filename from either stdin or from a command line argument and loads the program from the file. [Answer] # Pyth, ~~148~~ ~~128~~ 121 bytes (or 124 \* .9 = 111.6, see bottom) ``` J,00=kjb.z .eXHkCbz#=b-Fm?=zx"oabABi1"C@H+Zd@s[0Jm.x@Hk0JZ1H)zCh~tkS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3 ``` [Test suite](https://pyth.herokuapp.com/?code=J%2C00%3Dkjb.z+.eXHkCbz%23%3Db-Fm%3F%3Dzx%22oabABi1%22C%40H%2BZd%40s%5B0Jm.x%40Hk0JZ1H%29zCh~tkS2+%3FhKx%22abAB%22%3DYC%40HZ%3FPKXH%40JKbXJKb%3FqY%5Ci%3DZb%3FqY%5CopCbvN%3D%2BZ3&input=b1bbb1oAbabaa1ab1Ab1Bi1b&test_suite=1&test_suite_input=ooo%0Az%21%0Abbboobiii%0AIt%27s+a+cat+program%21%0AAoab11bi1bABoAaiba%0A0%0Ab1bbb1oAbabaa1ab1Ab1Bi1b%0A&debug=0&input_size=2) Code given on first line of STDIN, input to the Purple program on the rest of STDIN. To use code with newlines, use alternate version at the bottom. Reasonably golfed. Here's it with linebreaks and indentation for clarity: ``` J,00 =kjb.z .eXHkCbz # =b-Fm ?=zx"oabABi1"C@H+Zd @ s[0Jm.x@Hk0JZ1H) z Ch~tk S2 ?hKx"abAB"=YC@HZ ?PK XH@JKb XJKb ?qY\i=Zb ?qY\opCb vN =+Z3 ``` Basically, a `#` loop does the execution and halting via error-break. `a` and `b` are combined into a single variable, `J`. `Z` is the instruction pointer. `k` is input to the Purple program. `H` is the tape, represented as a dictionary. `b` is the current result. `Y` is the current first byte of the instruction. ## Reading from file: ``` J,00=kjb.z .eXHkCbjb'z#=b-Fm?q\o=zC@H+ZdCh~tk@s[Jm.x@Hk0JZ1H)x"abABi1"zS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3 ``` Give file name as first line of STDIN. Test run: ``` $ cat purple-final.pyth J,00=kjb.z .eXHkCbjb'z#=b-Fm?=zx"oabABi1"C@H+Zd@s[0Jm.x@Hk0JZ1H)zCh~tkS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3 $ cat purple-code.txt aA1aa1bb1oAbbi1bb1bbAb1Bi1b Purple is the awesomest! Why haven't you tried it yet? !dlroW ,olleG $ pyth purple-final.pyth <<< 'purple-code.txt' Hello, World! ``` [Answer] # JavaScript (ES6), 292 bytes ``` eval(`a=b=i=d=0;v=n=>(x=m[i+n])==97?a_98?b_65?m[a]_66?m[b]_105?i_111?p()[c]()_49?1:d=1;for(m=[...(p=prompt)()].map(b=>b[c="charCodeAt"]());!d;i+=3)(y=v(1),d)||(z=v(2),d)?1:(x=m[r=y-z,i])==97?a=r_98?b=r_65?m[a]=r_66?m[b]=r_105?i=r-3_111?alert(String.fromCharCode(r)):d=1`.replace(/_/g,":x==")) ``` ## Explanation JavaScript answers are always weird when `STDIN` and `STDOUT` are required... The first prompt is the input for the program string. Each prompt that results from an `o` instruction will read only the first character. `eval` is used to replace a common phrase which saves a few bytes. Ungolfed and without the `eval` the program looks like this: ``` // Initialisation a=b=i= // initialise registers to 0 d=0; // d is set to true when the program should die // Gets the result of Y or Z v=n=> // n = offset from i (x=m[i+n])==97?a: // x = value of instruction x==98?b: x==65?m[a]: x==66?m[b]: x==105?i: x==111?p()[c](): x==49?1: d=1; // if it was none of the valid values, die // Execution loop for( m= // m = memory array [...(p=prompt)()] // receive the program .map(b=>b[c="charCodeAt"]()); // initialise m to the ASCII values of the program !d; // finish if an error occured i+=3 // increment i ) (y=v(1),d)|| // get the value of Y and check for errors (z=v(2),d)?1: // get the value of Z and check for errors // Get the result of X (x=m[r=y-z,i])==97?a=r: // r = result of y - z x==98?b=r: x==65?m[a]=r: x==66?m[b]=r: x==105?i=r-3: x==111?alert(String.fromCharCode(r)): d=1 ``` [Answer] ## Ceylon, ~~827~~ ~~792~~ 671 bytes ``` import ceylon.language{l=variable,I=Integer,x=nothing,p=process,m=map}shared void run(){try{if(exists d=p.arguments[0]){l value t=m{*d*.hash.indexed};l I a=0;l I b=0;l I i=0;I g(I j)=>t[j]else 0;l{I*}c=[];I o{if(c==[]){if(exists e=p.readLine()){c=e*.hash.chain{10};}else{c={-1}.cycled;}}assert(is I r=c.first);c=c.rest;return r;}value f=m{97->{a},98->{b},65->{g(a)},66->{g(b)},105->{i},111->{o},49->{1}};value s=m{97->((I v)=>a=v),98->((I v)=>b=v),65->((I v)=>t=m{a->v,*t}),66->((I v)=>t=m{b->v,*t}),105->((I v)=>i=v),111->((I v)=>p.write("``v.character``"))};I h(I v)=>f[v]?.first else x;while(0<1){(s[g(i)]else x)(h(g(i+1))-h(g(i+2)));i+=3;}}}catch(AssertionError e){}} ``` It behaves a bit differently than the reference implementation when the program tries to read input at EOF – the reference implementation crashes with a TypeError, which is too costly to reproduce here (and also likely a bug), so this will return -1 instead (repeatedly, if necessary). (When trying to write this -1 to stdout, the interpreter will finish with an OverflowError, though. Similar will happen if an Integer outside of the Unicode range is output.) The interpreter takes the program as its first command line argument (make sure to quote it for your shell when it contains whitespace or other interesting stuff). In Ceylon we can only easily read input line-wise (I guess this will change in one of the next versions), so when `o` is used for reading, I'm reading a whole line and buffer the parts for future uses. I guess it works similar in the Python implementation when connected to a terminal. --- When trying to execute a command (part) which is not one of the valid characters, the `nothing` will cause an AssertionError to be thrown, which we then catch in the catch block around the main loop. I think this should be preferably be a custom Exception type (as AssertionError could also occur at other places if I have a bug), but that would take much more space, eating most improvements I made from the first version. Some tricks used for golfing: * The previous versions used a ceylon.collection.HashMap – instead we now use an immutable map as created by the `map` function, and create a new one each time `A` or `B` is used as *x*. * I use alias-imports for all identifiers from ceylon.language which are used more than once (including the `variable` annotation, which is now `l`). * I got rid of the class `E` (for environment) and the `s` (step) method – everything now happens inside the `run` function. * Instead of using `.integer` for getting the codepoint of a character, `.hash` gives the same result. Thus `string*.hash` is the same as `string.map(Character.integer)` (gives an iterable of the codepoints from a string). * When a type is alias-imported, `is I ...` is shorter than `exists ...`. * When converting something (e.g. `x`) into a string, `"``t``"` is shorter than `t.string` (or, what I used for a character, `String{t}`). * functions used just once can often be inlined. Here is the formatted (and commented) version: ``` // Purple – a self-modifying, "one-instruction" language. // // Question: http://codegolf.stackexchange.com/q/65411/2338 // My answer: http://codegolf.stackexchange.com/a/65492/2338 import ceylon.language { l=variable, I=Integer, x=nothing, p=process, m=map } shared void run() { try { // Reading code from file certainly takes more than 73 characters, // this isn't worth the 10% bonus. if (exists d = p.arguments[0]) { // The memory tape, as a Map<Integer, Integer>. // We can't modify the map itself, but we // can replace it by a new map when update is needed. l value t = m { // It is initialized with the code converted to Integers. // We use `.hash` instead of `.integer` because it is shorter. *d*.hash.indexed }; // three registers l I a = 0; l I b = 0; l I i = 0; // get value from memory I g(I j) => t[j] else 0; // cached input which is still to be read l {I*} c = []; // get value from stdin. // we can only comfortably access stdin by line, so we read a whole line // and cache the rest for later. I o { if (c == []) { if (exists e = p.readLine()) { c = e*.hash.chain { 10 }; // convert string into ints, append \n } else { // EOF – return just -1 from now on. c = { -1 }.cycled; } } assert (is I r = c.first); c = c.rest; return r; } // Map of "functions" for fetching values. // We wrap the values in iterable constructors for lazy evaluation // – this is shorter than using (() => ...). // The keys are the (Unicode/ASCII) code points of the mapped // source code characters. value f = m { // a 97 -> { a }, // b 98 -> { b }, // A 65 -> { g(a) }, // B 66 -> { g(b) }, // i 105 -> { i }, // o 111 -> { o }, // 1 49 -> { 1 } }; // Map of functions for "storing" results. // The values are void functions taking an Integer, // the keys are the ASCII/Unicode code points of the corresponding // source code characters. value s = m { // a 97 -> ((I v) => a = v), // b 98 -> ((I v) => b = v), // Modification of the memory works by replacing the map with a new one. // This is certainly not runtime-efficient, but shorter than importing // ceylon.collections.HashMap. // A 65 -> ((I v) => t = m { a->v, *t }), // B 66 -> ((I v) => t = m { b->v, *t }), // i 105 -> ((I v) => i = v), // o – output as a character. 111 -> ((I v) => p.write("``v.character``")) }; // accessor function for the f map I h(I v) => f[v]?.first else x; // the main loop, can only be left by exception while (0 < 1) { (s[g(i)] else x)(h(g(i + 1)) - h(g(i + 2))); i += 3; } } } catch (AssertionError e) { // abort silently } } ``` ]
[Question] [ ## Background An interesting way to solve a Sudoku puzzle is to represent it as a [Boolean satisfiability problem](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem), and then feed it to a SAT solver. A Boolean Satisfiability Problem (abbreviated as **SAT problem**) is a problem in which you are given a set of Boolean expressions, and you need to find a set of values for the variables such that all the expressions evaluate to true. SAT solvers usually take a CNF ([conjunctive normal form](https://en.wikipedia.org/wiki/Conjunctive_normal_form)) as input, and output a satisfying assignment if one exists. A CNF is a conjunction (AND) of clauses. A clause is a disjunction (OR) of literals. A literal is a variable or a negated variable. For example, \$x\_1 \vee \neg x\_2\$ is a clause, and \$x\_1\$ and \$\neg x\_2\$ are literals. Let's take the CNF \$((x\_1 \vee x\_2) \wedge (\neg x\_1 \vee \neg x\_2))\$ as an example. This CNF has two variables, \$x\_1\$ and \$x\_2\$. The first clause is \$x\_1 \vee x\_2\$, which means that either \$x\_1\$ or \$x\_2\$ must be true. The second clause is \$\neg x\_1 \vee \neg x\_2\$, which means that either \$x\_1\$ or \$x\_2\$ must be false. Therefore, the CNF is satisfiable if and only if \$x\_1\$ and \$x\_2\$ have opposite values. One possible satisfying assignment is \$x\_1 = 1\$ and \$x\_2 = 0\$. ## Task Your task is to write a program or function that takes a Sudoku puzzle as input, and outputs a CNF that represents the puzzle. This means that the output CNF should be satisfiable if and only if the input puzzle has at least one solution. You don't need to actually find the solution. A Sudoku puzzle is still considered solvable, even if it has multiple solutions. Your program or function should pass the following test cases in reasonable time. This is to prevent answers that brute force the sudoku and return a trivial CNF. ## Input You can take the input in any reasonable format. For example, you can take the input as a list of 81 numbers, where `0` represents an empty cell. The list can be flattened, or as a 9x9 matrix, or even as a 3x3x3x3 array. ## Output The output is a CNF. The CNF should be represented as a list of lists of integers. Each inner list represents a clause, and each integer represents a literal. Positive integers represent variables, and negative integers represent negated variables. For example, the CNF \$((x\_1 \vee x\_2) \wedge (\neg x\_1 \vee \neg x\_2))\$ is represented as `[[1, 2], [-1, -2]]`. The format is based on the [DIMACS CNF format](http://www.satcompetition.org/2009/format-benchmarks2009.html) used by many SAT solvers. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases You can check your output CNF using an online SAT solver, such as [this one](https://msoos.github.io/cryptominisat_web/). Your code should generate the CNF in reasonable time, but it's okay if the SAT solver can't solve it in reasonable time. ### Satisfiable ``` [[8,0,0,0,0,0,0,0,0],[0,0,3,6,0,0,0,0,0],[0,7,0,0,9,0,2,0,0],[0,5,0,0,0,7,0,0,0],[0,0,0,0,4,5,7,0,0],[0,0,0,1,0,0,0,3,0],[0,0,1,0,0,0,0,6,8],[0,0,8,5,0,0,0,1,0],[0,9,0,0,0,0,4,0,0]] [[0,0,0,7,0,0,0,0,0],[1,0,0,0,0,0,0,0,0],[0,0,0,4,3,0,2,0,0],[0,0,0,0,0,0,0,0,6],[0,0,0,5,0,9,0,0,0],[0,0,0,0,0,0,4,1,8],[0,0,0,0,8,1,0,0,0],[0,0,2,0,0,0,0,5,0],[0,4,0,0,0,0,3,0,0]] [[0,0,0,0,0,0,0,1,0],[4,0,0,0,0,0,0,0,0],[0,2,0,0,0,0,0,0,0],[0,0,0,0,5,0,4,0,7],[0,0,8,0,0,0,3,0,0],[0,0,1,0,9,0,0,0,0],[3,0,0,4,0,0,2,0,0],[0,5,0,1,0,0,0,0,0],[0,0,0,8,0,6,0,0,0]] [[0,0,0,0,0,0,0,3,4],[0,8,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,6,0],[0,0,0,0,3,9,0,0,0],[0,0,0,0,4,0,8,0,0],[0,0,1,0,0,0,0,0,0],[0,6,0,2,0,0,0,0,0],[4,0,0,0,0,0,7,0,0],[0,0,0,0,0,0,5,0,0]] [[7,2,5,8,9,3,4,6,1],[8,4,1,6,5,7,3,9,2],[3,9,6,1,4,2,7,5,8],[4,7,3,5,1,6,8,2,9],[1,6,8,4,2,9,5,3,7],[9,5,2,3,7,8,1,4,6],[2,3,4,7,6,1,9,8,5],[6,8,7,9,3,5,2,1,4],[5,1,9,2,8,4,6,7,3]] [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] ``` ### Unsatisfiable ``` [[0,0,0,3,0,0,0,1,6],[5,0,0,0,2,0,0,0,0],[0,0,0,0,0,0,0,3,0],[0,1,0,0,5,9,0,0,0],[0,3,6,0,0,0,0,0,0],[0,0,0,0,0,8,2,0,0],[7,0,0,0,0,0,9,0,0],[0,0,0,1,0,0,0,0,0],[9,0,0,0,0,0,0,0,0]] [[3,0,0,0,0,0,2,0,8],[9,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,1,4,0,0,0,0,9,0],[0,6,0,7,0,3,0,0,0],[0,0,0,0,8,0,0,0,0],[7,5,0,8,0,0,0,0,0],[0,0,0,0,0,0,4,1,0],[0,0,0,3,0,0,0,0,0]] [[0,0,2,0,6,0,0,0,0],[8,0,0,0,0,0,0,4,0],[0,0,0,0,0,0,0,0,1],[4,0,0,5,0,1,0,0,0],[0,0,0,0,0,0,2,0,0],[0,0,0,9,0,0,0,0,0],[0,0,0,0,3,0,6,2,0],[0,6,0,0,0,0,8,0,0],[1,0,0,7,0,0,0,0,0]] [[5,0,0,0,0,9,3,0,0],[0,2,0,0,8,0,0,0,0],[0,0,0,0,0,0,1,0,0],[0,0,0,1,0,0,5,7,0],[0,0,4,0,0,0,0,0,0],[0,8,0,0,0,0,0,0,0],[0,0,6,0,0,0,0,8,4],[1,0,0,3,0,0,0,0,0],[0,0,0,0,0,0,0,2,0]] [[1,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]] ``` [Answer] # Python3, 427 bytes ``` J=range(1,10) u=lambda d,*t:d.setdefault(t,max(d.values()or[0])+1) Y=[(r,c)for r in J for c in J] def f(b):d={};return[[u(d,r,c,n)for n in J]for r,c in Y]+[[-1*u(d,r,c,v),-1*u(d,r,c,V)]for r,c in Y for v in J for V in J if v<V]+[[u(d,r,n,v)for n in J]for r,v in Y]+[[u(d,n,c,v)for n in J]for c,v in Y]+[[u(d,R*3+i,C*3+j,v)for i,j in Y[:3]]for R,C in Y[:3]for v in J]+[[u(d,r,c,b[r-1][c-1])]for r in J for c in J if b[r-1][c-1]] ``` [Try it online!](https://tio.run/##zVXLjtowFN3zFZG6mATMKI7zcGhZzW6Ws0AaWVkEAm1GTEAhoFZVv53aN8axg1PoDkWAOb6vc1/Z/2p@7CpC9/X5/Dqv8@r72sUI@97oON/mn8sidwo0bmbF82HdFOtNftw2boM@859u8XzKt8f1wfV2NfMzb4K90fucuTVaeZtd7dROWTmvjjiu4JiNuAFn4y69WTH//edrvW6OdcXY0S0QV0IVqFWtLFhAoPieTRib4vFF7uQh7d/CM2TB36lzvWiP5cY5fVsIQ61exa1ceTspb0KoAlc9oVVP6G1MJiV64d8fUrhEHyDBZiQDlTf0ooAuuC6UFVqyeooztuJfkkw/dSJ@TSo77@uyatyNyxhFvvlkiIlfguIelsA55Z9AYZGUSAxd8YT8LjEwLG@IwrDyECMqMapsYimXos6msJd5nvPlkDflYVPmy@161JExgpHO8QBBYY4YZMwnVliEVBA9uZAHSTWMXihJLFCSkcRChZD7yPhGNkIrmWCAYBu60ElUdnXnXRVSTZd0ue5VGlt8UKie/39kCArBAB0w2rWFjhFLFcILqauWumCxUYd@EhOL3@gWmYQbjLjbVBDhDjA3QKEZYuh6EWgAmUzFLb8JOBpBq4RwH4Es5XgKLSrOQirlNwSqJU6BOENThdCOAfhLwGYqJoVjQjOBSIQ8hsRGcB@AzVj4u78y9ll4LGyAzNP0aRzwN0@fGlETFENufGSM5pWLy37Cshn0pjO2Yk@XqmnRFlCrfbUDWyy1UztWtkoJQkQTFs6oZgTfzCPWtk@qTUfSJcnYZZ1uAjNBB@sSqmWtJ1wSGmTE1I6MNbvmCym08sFqirW11JMz93pqjZ2A70DLhcZdvTuS@wrEVG/5MI/mdqYDqcOW/oA3p8TCqzJS64jowYcqdPKPUQpu0bG9OfHjb4ZhOu3@jGAnUrl5Hxmz0Dn/BQ) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~97~~ 94 bytes ``` ≔ΦEθ∧ι⟦⁺×⁸¹ικ⟧ιυF⁹F⁹F⟦E⁹↨⟦⊕ικλ⟧⁹E⁹↨⟦⊕ιλκ⟧⁹E⁹↨⟦⊕ι÷κ³÷λ³﹪κ³﹪λ³⟧³⟧⊞υλF⁸¹F⁹Fκ⊞υ±⁺ι×⁸¹⊕⟦κλ⟧Eυ⪫⊞Oι⁰ ``` [Try it online!](https://tio.run/##jZBNa8MwDIbv/RWmJxk8SNZ9JPTUMQYddMthN5ODSbzW1LU72@nfz@SkSZsxxmIiW9LrR5aqnXCVFbptV96rrYEXpYN0sBFH@GJkZWpQjPBCNx4@1EF6yFJGFGVkT0tK@2NDl7NP6wjklEx2HjE5I0/CS@BrUzl5kCZIhEYCI7pkJI@YP4Uatf8Srk14VidVS0D2YhLQfWBj60bbIX32ulwZDfZEisbvoMGqQ1dZ@qOt/UX0JrciSOjmg4O6jOj6abzrlMZvOSucMqGbL15/tcpAZL0fpRPBughJ8GVzMo/qtuU8Y8kva8EeJv5jZ3P8b8@R@0nmsu4wcx1LR@LUT7BCXzsbWelYZWChLcv25qS/AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔ΦEθ∧ι⟦⁺×⁸¹ικ⟧ιυ ``` For each provided digit, mark that digit as being in that cell. ``` F⁹ ``` For each digit... ``` F⁹ ``` ... for each square, row and column... ``` F⟦E⁹↨⟦⊕ικλ⟧⁹E⁹↨⟦⊕ιλκ⟧⁹E⁹↨⟦⊕ι÷κ³÷λ³﹪κ³﹪λ³⟧³⟧⊞υλ ``` ... require the digit to appear in that square, row and column. ``` F⁸¹ ``` For each cell... ``` F⁹Fκ ``` ... for each pair of digits... ``` ⊞υ±⁺ι×⁸¹⊕⟦κλ⟧ ``` ... only allow one digit to be in that cell. ``` Eυ⪫⊞Oι⁰ ``` Pretty-print the output so it can be pasted directly into a solver. (Would be 5 bytes shorter to print it as a Python array literal.) The output from the CMS solver can be converted back into a pretty grid: ``` F⁸¹⊞υωWSF№ιvFΦI⪪⁻ιv¦ ›λ⁰§≔υλ÷λ⁸¹E⪪υ⁹⪫ι ``` [Try it online!](https://tio.run/##Ndfdah1HGoXhc19FkyMJLNj1/XaTo5AhgwcGArkCk2higZCNfpzcvWa9X@8c2GBrVfXWfmpVV/3@5fPz718/P76//@/r83azr9vt17eXLzdvH7e/bn/88NeXh8f77ebT07e3199enx@e/ry5vd0m@vPXt6fXm4eP2w/ff/jn/355eHy9f775@fPL681v3x4fXm/@@/D09vJPSn9vyn7c/v18/5ng48ftcqvBP728PPz59NPrp6c/7v/m2frBp6fXfz18f/jjnpQ@lz7Nr/oAmvLzt@vkCh6a7T9fH57mEUx@@@P7@/ftbm13tt35dhfbXW53td31drdvd4d@dNEf/XwpsJRYiixllkJLqaXYUs6UM@ax7YNmNEVNUVPUFDVFTVFT1BV1RZ1nKufKuXKunCvnyrlyoVysmS4UDT6foqFoKBqKhqKhaCqamjKVS@WSX0S5VC6VS@VSubrMdKVoKVqKlqLFL61oKVqKlqKtKVu5Vq6Va@VauebbUa6V62Om2xXd17YruSu5K7kruSu580UquWvGQ7FDMx7KHcodyh25HYodih184eeE68K3fuFrv/C9X3xbF774C9/8ha/@0vovvvsLSKcS@XEaqJES1Uw4XOM1YIgtyJaNLYMgWzJbmC3QFmpLbAu2hdvyE2T5rAeGwLfwWwJcAC4EF4QLwxU8A8IVs4IYgOIS40wG5cJygbmkudBccC48V86yY4xIF6QL0wXqKh6C6apz9S3BLmBXzVLld8F2gbvQXfAufBfAC@EF8ZLx6lncDJDyTNiMwXntjIF6Yb3AXtJeaK99GsFDAF@IL5EvyBfmS@gz4cEHg35hv46p0fSIIkFv0NuFIsneoDfR24UqQW/Q2zqXtKFv6Bv6hr5RVBO9IW/I23R1ynq2lQFT1mmrncvFprLTWekb@oa@UVuD3qA36A16o7uGvWFv2FtcP5n4DX2L2RQYg75RYhO9IW/IGz026A16E73l7CLk81wthr6hb@gb@oa@UWmj04a91ew9PAR7k71Bb9Bbn@vY0DfpG/hGwa1nv2KI9A15Q96QN@QNeUPe6LlBb6KfCdE39A19o/AGv8Fv4jfoDXqD3o7ZFmdfZGOE3kXvkmdCp/iOvkvf0Xf0HX1fs5cyBHqH3qF36J3Wu@wdel/n5uLou80GzBj0HX2n@A69Q@/s1z4btux9duxzy3b9i7yfq8Vn456de7Zu8J3iO8V36D1mn4/NkXfkndI79A6957laHH2XvtN7z3k3MIat3KF36B16h96hd@hd9I6817xNzuXi4DvFd/Qdfaf4Dr1TfMfesXfZO/TO9u7YO/a@n8vFxe/oO/qOvkvf93ltMQR5R96Rd@QdeWe3d@gdej/O5eLHvOzmbcfrTvpB74PeB/QBfbDnB/Yh@4A@1rweF38xYJ3LJdAP9AP9oPkBf9D8wD5kH9AH9CH6QD6QD@QD@bBzuQTFD/RD@kHvA/2g9wF9QB/Qx7y2570Nfcxr@3xvn9teiD/m5T1v73l9ox8UP6APih/YR87LXgOgD@hD9IF8XF/kAX6AH/Q@0I@aAwJjoA/oA/oQfSAfyAfygXz0uY6j51TBGPQD/UA/aH7Q/JB9QB/QB8WPfc4hDMA@jusnE3@gH@gH@oF@oB/Sj2POLnN44fRC7xP6FH0in8jn5VzGCX5S/EQ/15x4GIN@UvyEPqFP6BP6hD6hT9Gnncs4pZ/gJ71P9BP9RD/RT3qf0Cf06XOwYoTsE/qEPv1cxol@op/oJ/qJfsacxngKzU/ZJ/QJfc7Rbc5uc3jL8@2d0s/zBMeQOcPNIW5OceJPep/QJ/QJfUKfNWc@BkCfdb69U/pJ7xP9RD/RT/ST3mfPQZEx0Cf0CX1Cn6JPWp/7uYxT@gl@7nO4ZAj4SfGT4if0CX1Cn9An9Mmen7LPY86j1wMp@oV@UfyCv@Avil/Yl@wL@oK@oC/oS/SFfCFfq64nXIaAX@AXvS@bYy9jsC/ZF/QFfUFf0Bf0BX1dD3vlc1ZmDM0v@Av@En@JvpAv5Av5Qr5iDtfkkS9aXzHLpcAv8Av8Ar/ofdH7yjmRMwb6gr6grznBy77m/D4H@Dp3vZpT/HmMZ8wc5OckT/EL@8K@ZF/QF/QFffUc/BlwPewV@iX9Ar/ofaFfFL8ofsm@9rks8AzoC/qCvqAv0df1rFfgF/gFfh1zw5grBncM6Bv6hr6hb@gb@oa@qX1fZj/uNfcSxki/6X2j3@g3vW/oG/qGvqFvm5sMD4G@Rd/Xs16j3@g3@o1@o98Uv32uP4yBvqFv0bfkm9I39A19X@9qjX7HXJkYgn6j3xS/sW/sW/YNfUPf0HfOJYsB18Neo9/oN/pN8xv@Fn9T/Ia@a25m@lzIN/I9l7i5xc01rs/NpecuN5e5uc2d1zkGSb@Rb3rf0Df0DX1D36JvWt/73P/O1dLoN/qNfqPfFL8pfmPf2Lfs@5hL48GVkTuj6Hfkd@T3S1xvk9wdwd/B38HfhX/58H73/fH/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated lines. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 9;þ¤Z;3/$3ÐƤẎ;;Z¤;€þ9Ẏ ŒJ;þ9ZŒc€ẎN;¢ ŒJ;"FẠƇW€;Çḅ9 ``` A monadic Link that accepts a list of rows of digits, with zeros representing unknown digits and yields a list of lists of integers. **[Try it online!](https://tio.run/##y0rNyan8/9/S@vC@Q0uirI31VYwPTzi25OGuPmvrqENLrB81rTm8zxLI5To6yQuoyDLq6KRkoCBQxM/60CKwqJLbw10LjrWHA4WtD7c/3NFq@f9wO0ingTeQiPz/PzraQscAFcbqRINoYx0zNDFzMNsSiI3gYqZQFeYoekHQBChnjiJmCJUxhosZwm0w07GAilnAzTSEqrPUQZgJMi8WAA "Jelly – Try It Online")** (footer formats for the [the linked tool](https://msoos.github.io/cryptominisat_web/ "msoos.github.io/cryptominisat_web").) [This](https://tio.run/##Ldc9ji5JEYVhn1WUg/lJFf9ZDi4GPjvAQSNhII2Eh8cqEHtAGCONzz4uG2nOG9XGvU6frOquJyMy8s9/@umnv319/fjlX//7@z9//vHrf/7w45d///F3//3Hc//2@cvz1@f3X19fP18fuz5@feL65PWp69PXZ67PuT6PfnTrn35uCpgSpogpYwqZUqaYKefKOc/x6zd6oivqirqirqgr6oq6oqFoKBq8U7lQLpQL5UK5UC6US@XS9nGpaPL7KZqKpqKpaCqaipaipUeWcqVc8YcoV8qVcqVcKdf3Pq4VbUVb0Va0@aMVbUVb0VZ09MhRbpQb5Ua5UW74OsqNcvPs446iR9Gj6FH0KHoUPYoevqSiR498lHuUe5R7lHuUe5R7lHvmes4@7Xkuu/nqN5/95rvffPibL3/z6W@@/c3Hv/n6txa8TCxYqJUSFc@z5VqvBVsxyAwz88VlkcwMMwPNUDPYDDfz90814Rl4FrsheA9@BqAhaCI0CA1DA9GSBRha7hZigRj3gVAalgamSdPQNDgNTwPUavcdL5GpYWqgGqrWLOh3qxiwhqxBa72blZega/AaviZgA9gQNogNYwPZpLwPQ9qgNlkb0Ia0QW2yNqwNbEPbzpYEecANcRO5PW9ZGOyGuwFvyNvDmmfraAuJSsLesXfZO/QOvUPvot8aQ99v1thWH2vgd/hd/A69Q@@id@R9i3Wr9S1X8pLfB27FSt@3ZLdmt2ipWqdsHXqH3qF36B16h96pXo/z3QFYJH5H39H33K7AGorYoXfRO/JOHTv0Dr1D79B7vfvY0Xcq2sXv6Dv6jr5T0g69Q@/Qe2/zYYHoHXlH3uftAo6@o@/ou/QdfJ9tWPwtyPuwBnqH3kXvVLlD79D7eXeLn@1yrEHf0XcK3ql4x96xd@xd9i56f7Ytbl@kMSIf97tdgsIP9AP9QD@kH8gH8mHbTFmDfCAf9OiAPqAPe7dLwB/wB/zh24L9Cnp1QB8Ufsg@oA/oYxv2duxt2W/P3u0S27e3cW/n3ta9vRv5oPAD@oA@chs9K6AP0QdFH9BHvs0l0A/0A/1AP6QfyAfyQeEH9AF9QB@iD@QD@UA@@m0uAX5Q94F@oB809hB9IB/IB3Uf0MfsGcQC6AP6OO92CfSDwg/4Q/yBflD4cfbgYg30AX1AH9AH9CH6QD6ed7sEhR/PnnZ73HHewZ8UfmKfsk/oE/qk5yf2iX3KPqFPe7dLop/oJ/op/aTlJ/KJfCKfyCeFn9An9Al9Uvbp833knivRT/QT/Yw9hlmDfWKf2Cf2iX3uwS37hD733M63u@Qe3nt67/G957f4k8JP6BP6hD5Fn7WHPXnoE/qEPuvdLol@UvgJf4o/0c/eCYE10Cf0CX1Cn1R9Yp/Yp@xz3u2Ss2MFa6Sf4Cd1n8gn8ol8UvgJfYo@z84hvAP5RD6f77EF/AQ/qftEP6WfyOezw8tOL4wvyBfyhXxR9QV93e92KfQL/UK/bGceu4rCL@gL@oK@KPzCvrAv2Rf05Tsk7XYp8Av8Ar/ALwq/KPyCvqAv6Ct2smIF9AV9ib6Qr@@WX@AXhV/oF/qVO46xBvqCvqAv0dfObju87fS245vo67vl185wO8TtFLdjHIVfoi/kC/mi8Av66h36WAB9QV/9bpeSfoFf4Bf4ReEXhV@zkyJrKPzCvmRf0Bf0BX1BX@fdLiX9OjtdsgT9Qr@o@4K@oC/RF/LFaV/Q17Pz6A6kN/@926XRb/Qb/Ua/KfyGvqFv6Bv6Fn1D39A39A19W3/PuKyRflP4jX77zr2swb5l39A39A19Q9/QN/QNfcdulwa/wW/wm7pv9Ju6b@gb@oa@oe/c8VovQb6Rb@Q73@3S6Df6jX6j3/T8rp3J62roG/qGvneEF33vAL8T/I7w/W6Xfud41uwkL/2m7pu6b@gb@oa@oW/oe3byZwH0/T3UN5Xf8Lf4G/1Gvyn8puf32euCXgJ9Q9/QN/QNfYu@n3e3NPqNfj97xdg7BpcMCn@gH@gH@oF@oB/RD/KD/Nh7Fg1tf9Af9Af9QX8o/IF@KPyR/Yh@fG8y5JEfqn6gH393y6A/6A/6g/6gP7H3HxZhP7If6Af6gX6gH@jn@7Y26E/upSmvQX/QH/SHE3@gH@gH@oF@oJ/aa5ZeAv3UexYN@oP@0PNH/IP@oD8U/vRezVgj@qHuZ29xe43be9xe5OY9i0b6s7e59zrH77UXOup@kB/kh8If6Af6gX6gn7M3wHcfD/wj/kF/0B/0h54/4h/oB/p59tb4cGfk0gj9gf5Af@78vk/WdcA/1P1B/6B/bC@adh3kD/IH@YP8Qf4gf5A/kr//Dw "Jelly – Try It Online") will print the solved sudoku using output from [the linked tool](https://msoos.github.io/cryptominisat_web/ "msoos.github.io/cryptominisat_web"). ### How? Treat each triple of row, column, and digit as a variable, giving \$9^3=729\$ variables (the code uses one indexing of each, so these are variables \$[91,819]\$). Outputs the givens as single variable clauses, then pairs of negated variables to assert that no cell contains more than one digit, then nonets of variables to assert that each digit appears in each box, row, and column. ``` 9;þ¤Z;3/$3ÐƤẎ;;Z¤;€þ9Ẏ - Link 1: no arguments ¤ - nilad followed by link(s) as a nilad: ¤ - nilad followed by link(s) as a nilad: 9 - nine ;þ - table with concatenation -> Rows as lists of nine [row, column] pairs $3ÐƤ - last two links as a monad for each non-overlapping three: Z - transpose ;3/ - three-wise reduction with concatenation Ẏ - tighten -> Boxes as lists of nine [row, column] pairs ; - concatenate {Rows} Z - transpose {Rows} -> Columns ; - concatenate -> Boxes + Rows + Columns þ9 - table with {[1..9]} of: ;€ - concatenate to each Ẏ - tighten -> Clauses to assert that no digit repeats in any box, row, or column ŒJ;þ9ZŒc€ẎN;¢ - Link 2: list of lists of integers 0-9, Sudoku ŒJ - multidimensional indices {Sudoku} -> all [row, column] pairs þ9 - table with {[1..9]} of: ; - concatenate Z - transpose Œc€ - unordered pairs of each Ẏ - tighten -> all pairs of variables representing two digits in the same cell N - negate ;¢ - concatenate results of Link 1 ŒJ;"FẠƇW€;Çḅ9 - Main Link: list of lists of integers 0-9, Sudoku ŒJ - multidimensional indices {Sudoku} -> all [row, column] pairs F - Flatten {Sudoku} ;" - zip with concatenation -> all [row, column, value] triples ẠƇ - keep if all -> all [row, column, value] triples with non-zero values W€ - wrap each in a list ;Ç - concatenate results of Link 2 ḅ9 - convert from base nine ``` [Answer] # [ATOM](https://github.com/SanRenSei/ATOM) ~~315~~ ~~294~~ 264 bytes ``` {v="";r=v;c=v;g=v;e=v;p=v;h=100;s=" ";b="\n";l="0\n";n=1~9;n∀{n∀{n∀{t=h*$2+10*$1+*;1~(9-*)∀p+=-t+s+(-t-*)+s+l;v+=t+s;r+=h*$2+10**+$1+s;c+=h**+10*$1+$2+s;g+=(*+2)/3*h+($1-1)/3*300+10*((*-1)%3+1)+30*(($1-1)%3)+$2+s};v+=l;r+=l;c+=l;g+=l;~{$2.(*-1).($1-1)!=0:e+=h*$1+10**+$2.(*-1).($1-1)+" "+l}}};v+b+r+b+c+b+g+b+e+b+p} ``` (Some minor optimizations, using global variables and one character saved on defining l ``` {h=100;s=" ";b="\n";l=0+b;n=1~9;n∀{n∀{n∀{t=h*$2+10*$1+*;1~(9-*)∀$p+=-t+s+(-t-*)+s+l;$v+=t+s;$r+=h*$2+10**+$1+s;$c+=h**+10*$1+$2+s;$g+=(*+2)/3*h+($1-1)/3*300+10*((*-1)%3+1)+30*(($1-1)%3)+$2+s};v+=l;r+=l;c+=l;g+=l;~{$2.(*-1).($1-1)!=0:$e+=h*$1+10**+$2.(*-1).($1-1)+" "+l}}};v+b+r+b+c+b+g+b+e+b+p} ``` Version 3 - The v conditions were no longer necessary to include in the solution, and the b variable is redundant. Thanks @Neil! ``` {h=100;s=" ";l="0\n";n=1~9;n∀{n∀{n∀{t=h*$2+10*$1+*;1~(9-*)∀$p+=-t+s+(-t-*)+s+l;$r+=h*$2+10**+$1+s;$c+=h**+10*$1+$2+s;$g+=(*+2)/3*h+($1-1)/3*300+10*((*-1)%3+1)+30*(($1-1)%3)+$2+s};r+=l;c+=l;g+=l;~{$2.(*-1).($1-1)!=0:$e+=h*$1+10**+$2.(*-1).($1-1)+" "+l}}};r+c+g+e+p} ``` ## Usage ``` input=[[8,0,0,0,0,0,0,0,0],[0,0,3,6,0,0,0,0,0],[0,7,0,0,9,0,2,0,0],[0,5,0,0,0,7,0,0,0],[0,0,0,0,4,5,7,0,0],[0,0,0,1,0,0,0,3,0],[0,0,1,0,0,0,0,6,8],[0,0,8,5,0,0,0,1,0],[0,9,0,0,0,0,4,0,0]]; input INTO {h=100;s=" ";l="0\n";n=1~9;n∀{n∀{n∀{t=h*$2+10*$1+*;1~(9-*)∀$p+=-t+s+(-t-*)+s+l;$r+=h*$2+10**+$1+s;$c+=h**+10*$1+$2+s;$g+=(*+2)/3*h+($1-1)/3*300+10*((*-1)%3+1)+30*(($1-1)%3)+$2+s};r+=l;c+=l;g+=l;~{$2.(*-1).($1-1)!=0:$e+=h*$1+10**+$2.(*-1).($1-1)+" "+l}}};r+c+g+e+p} ``` ### [Try it online](https://sanrensei.github.io/ATOM/) ### Explanation The algorithm constructs several "sections" of output, generating a total of 729 boolean variables of the form xyz where it is true if the xth column and yth row has value z, and false otherwise. With the triple for loop (n∀ n∀ n∀), it creates CNF output for the sudoku rules * v: Each cell must have a value from 1 to 9 ``` v+=(h*$2+10*$1+*+s); ``` * r: Each row must contain each of the values from 1 to 9 ``` r+=(h*$2+10**+$1+s); ``` * c: Each column must contain each of the values from 1 to 9 ``` c+=(h**+10*$1+$2+s); ``` * g: Each 3x3 subgrid must contain each of the values from 1 to 9 ``` g+=((*+2)/3*h+($1-1)/3*300+10*((*-1)%3+1)+30*(($1-1)%3)+$2+s) ``` * p: No cell can have more than one number in it. It creates an array from 1 to the remainder and places pairs of negative numbers representing every combination of two numbers inside a single cell. ``` 1~(9-*)∀p+=-t+s+(-t-*)+s+l; ``` Then, the input is used to generate the rules for e, which takes each given non-zero cell and declares that particular rule. ``` e+=h*$1+10**+$2.(*-1).($1-1)+" "+l ``` Finally, all rules are concatenated and returned. ``` v+b+r+b+c+b+g+b+e+b+p ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~201~~ 181 bytes ``` x=>P(i=>P(j=>P(k=>P(l=>k<l?[[i+j+k,i+j+l],[i+k+j,i+l+j],[k+i+j,l+i+j]]:[P(k=>[-i%3*3-k%3-1+[0|k/3+(~-i/3|0)*3+.8]+j]),[-i+j+x[i-1][j-1]]])))) P=(f,n=9)=>n?[...P(f,n-1),...f([n])]:[] ``` [Try it online!](https://tio.run/##XU/LbsMgELznPyJBWIgpbWw3xbnl7PuKQ5RHxUN21VRVDlF/3V0iy5XLioGdnZ2FcPg@XI@f/uNLdv3pPOztcLNNy3yGkCFmSLaJb2mH6EUQETImB5RFEShLIlAWBfGQMjr3io9WlH5pVkbGpZFaYHGPayPYj/Rrcy/4yghVOZJzICGZ3tBL7TAQOMdpLVrLLtDZmtum26FSqs251BzofmHYOU6z3LBdHPvu2qezSv072zPECop50BPzaWDzjysf95r208S9jIpy1pvjmWrljNNjxUycniZsoBq5avLUo66GP8/sRz/eDr8 "JavaScript (Node.js) – Try It Online") * Some variables unused to make it base 10, easier to concat * Variables are negated, so 81 elements not chosen * Loop through `[i,j,k,l]`. When `k<l` it means "On (i,j) dimension at least one of `k` and `l` is not chosen"; When `k>=l` it's "At least one is chosen"(only tested one dimension) and input condition * Since other few conditions made there only 81 chosen at maximum, if it's 81 non-empty sets then each have exactly one. Removed the part from exclusive rule. ]
[Question] [ Given a string that represents a bunch of tables stacked on top of each other and/or arranged side-by-side, disassemble all the tables. ## Tables A table looks like this: ``` ------- | | | | ``` More formally, a table has a tabletop, composed of `n` dashes, and two visible legs. (Obviously, there are two hidden behind, but for the purposes of this challenge, a table has two legs. (Think of the legs as being thick legs that span the entire length of the table.) The visible legs are both `m` pipes (`|`) high, and are separated by `n-2` spaces. (Thus, the string representation of a table has `m+1` lines of exactly `n` characters per line.) Does it sound easy to disassemble a table? Think again. ## Stacked tables and tables arranged side-by-side The table above is just one of the many tables you could be given as input. In actuality, oftentimes you will have a huge number of tables you wish to disassemble, and to save space in your home, you might decide to stack them on top of each other, and sometimes arrange these stacks side-by-side. This would not be a problem if the tables were all the same height and length. However, obviously there is the possibility of having a messy arrangement of tables, and you should be able to disassemble these arrangements as easily as you would disassemble a single table. This is an example of an arrangement: ``` --------- | | --- | | | | ------------- ------------------- | | | | --------------- | | | | | | | |----------------------------------- | || | | || | ``` ## How to disassemble tables, or arrangements thereof? Disassembling tables consists of separating the top, leg one, and leg two from each other. Your answer to this challenge should output these separated parts in their appropriate orientation. For instance, when disassembling the single table shown in the section "Tables", you should get the following: ``` ------- | | | | ``` Disassembling the complex arrangement above gives this: ``` --------- --- ------------- ------------------- --------------- ----------------------------------- | | | | | | | | | | | | | | | | | | | | | | | | | | ``` Your answer to this challenge can choose to output in this neat format, where the tops are laid next to each other at the top of the output and all the legs are laid next to each other below the tops, with all the parts in their correct orientation, or you can choose to output a list of all the parts, but in the correct orientation. What you may not do, however, is output the input unchanged and say "look, all the parts are there". To assess whether an output format is reasonable, determine whether or not the output format shows a clear separation between the parts. **You may output the parts in any order**, as long as the output format remains reasonable. (No outputting full tables, for instance.) Note also that if outputting in the neat format, all tabletops must be at the top of the output, and the legs below all the tabletops. However, the order of the tabletops and the order of the legs are both flexible. Additionally, output may also be in the form of two lists, one representing a list of tabletop lengths and one representing a list of leg lengths. This output form may only be used if the lists are clearly separate. Input may be ASCII art as shown above, a list of lines, or a character matrix. ## More examples Input: ``` -- || ``` Output, which will hereinafter be in the neat format: ``` -- | | ``` Why? Your answer should not treat `||` as one leg; a leg is only one pipe "thick". Input: ``` ---- |||| ``` Output: ``` -- -- | | | | ``` Why? Tables have only two legs. Once your answer sees the first leg of a table, it should only treat the area from that leg until the next leg it sees, as a table. Thus, there are two tables in the above example, not one. Input: ``` --------- | || | ``` Output: ``` ----- ---- | | | | ``` Why? See above. Input: ``` --- | |--- ---| | | || | ``` Output: ``` --- --- --- | | | | | | | | ``` Input: ``` --- | | -------- ||| | ``` Output: ``` --- -- ------ | | | | | | ``` Input: ``` --- ---------------------------| | | || | | || | | || | ------------------------------ |||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||| ``` Output: ``` --------------------------- --- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ``` ## More notes You may assume that tables will not be "completely underneath tables", that is, no input like this will be given: ``` -------------------- | | | ------- | | | | | | | | | ``` You may assume that the arrangement is "stable", so there are no legs "hanging in midair": ``` ----------------- | | <- this leg is hanging in midair | | ---------- | | ``` On a related note, the heights of the legs of a table are the same (this is stated above, but I want to make it extremely clear). This means that this input will not be given: ``` ----------- | | ------- | | | | ``` You may assume that tables are stacked only in the correct orientation, so no arrangements like this: ``` |------- | | |------- ----------- | | ``` or this: ``` | | | | | | ------------- ------------- | | ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, measured in bytes, wins. *[Related](https://codegolf.stackexchange.com/questions/67522/analyse-your-chair)* [Answer] # [J](https://www.jsoftware.com), 55 bytes ``` ([:(1+_2-~/\])@I.,.@'-|'E.]);&(0-.~,)'\|+'#&>@rxall"1|: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtx01wj2krDUDveSLdOPyZW08FTT0fPQV23Rt1VL1bTWk3DQFevTkdTPaZGW11Zzc6hqCIxJ0fJsMYKqj1Pkys1OSNfIU0h1lov3kghFmSJAZeurq4CEAApXa4ahRoQt0ZBoQYkDuSChECUJhcuzSAVIFoXYgJQtQJIuybE1gULIDQA) -12 after seeing rule change allowing lists of lengths as the output. ## original answer outputting art, 78 67 bytes ``` ([:('-'<@#~"+1+_2-~/\])@I.,.@'-|'E.]),&(a:-.~,)'\|+',.&.>@rxall"1|: ``` [Try it online!](https://tio.run/##DcNBC4IwFADge7/iscC3sbdXdhwZoygQokC6qYTBDEoUPHkY@@urD75PEow9FBYQCLZg/w3DqbpekqytRIN7t45C5/q5M3HTtMqVTOzQBDxzqyiTnTUcSWETNBJnfHDz0g2DyINNanU7MlT@7Rd4zdPXjzCN8Cjv6Qc "J – Try It Online") Note: Regex in J is broken on TIO, so the link above is just for the byte count. I will paste below some output run on my computer on J903. Also, note that we pre-process the input into lines of text, and that J requires boxing for heterogeneous lists, hence the boxed output. ``` echo f ];._2 ] 0 :0 --- ---- | |--- | | ---| | | || | ) echo f ];._2 ] 0 :0 --- | | -------- ||| | ) ``` Outputs: ``` ┌───┬────┬───┬───┬─┬─┬─┬─┬─┬─┬─┬─┐ │---│----│---│---│|│|│|│|│|│|│|│|│ │ │ │ │ │ │ │ │ │|│|│ │ │ └───┴────┴───┴───┴─┴─┴─┴─┴─┴─┴─┴─┘ ┌───┬──┬──────┬─┬─┬─┬─┬─┬─┐ │---│--│------│|│|│|│|│|│|│ └───┴──┴──────┴─┴─┴─┴─┴─┴─┘ ``` ## how * The "legs" part is just doing a regex search for repeated pipes `\|+` in the transpose of the input, and then converting it back to one pipe per line. * The "tabletop" part is slightly more interesting, because we have to account for tables that are pushed up next to each other -- ie, sometimes we can only find the demarcations between tabletops by looking at the legs. J has a built-in ability to search for box-shape strings withing a 2D grid, and so we use `E.` to find instances of: ``` - | ``` within the input. We then do some arithmetic on those found indexes to find the length of all tabletops, and convert those lengths back to ascii strings like `-----`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` =”|µZṣ€0Ẏ¹Ƈ,<ƝT€Fr2/ƲẈ€ ``` A monadic Link accepting a list of lines that yields a list of lists of leg lengths and tabletop lengths. **[Try it online!](https://tio.run/##y0rNyan8/9/2UcPcmkNbox7uXPyoaY3Bw119h3Yea9exOTY3BMh3KzLSP7bp4a4OIPv/w91bDrf//68ABLpgAGJxgYgaOMGliwK4IDI1UAzlYsqCaQA "Jelly – Try It Online")** ### How? ``` =”|µZṣ€0Ẏ¹Ƈ,<ƝT€Fr2/ƲẈ€ - Link: list of lists of characters, L =”| - L equals '|'? (vectorises) µ - new monadic chain - f(X=that) Z - transpose X ṣ€0 - split each at zeros Ẏ - tighten ¹Ƈ - keep truthy (non-empty) ones -> our legs (as lists of 1s) Ʋ - last four links as a monad - f(X): Ɲ - for neighbours: < - less than? T€ - truthy indices of each F - flatten 2/ - reduce pairs by: r - inclusive range -> our tabletops (as lists of positive integers) , - pair legs and tabletops Ẉ€ - for each: length of each ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~64~~ 62 bytes ``` WS⊞υι≔Eθ⪫⪪⭆υ§λκ-|¦#|θFθFΦ⪪ι#λ«P↓№κ|→→»←⸿⸿FEυ⌕A⭆θ§λκ#Wι«⊕⁻⊟ι⊟ι→ ``` [Try it online!](https://tio.run/##pVBBasMwEDxXrxDuZQXWB5KTaQm41GCaay7GVuwlqmTLclKo8nZ3HbtQaJJL5jKsdnZ2VmVTuNIWehxPDWrFITXt4LfeoalBCJ4PfQNDzFGsWdL3WBvIiha6mL9ZNLBtNXqY5dM7KROfmkp9gY75QYiYRzJEEz0TEXdktLeOQyf4hTeovXKLE07CSa5p9zd7ygbtsSV3D6tXezIxf7EDFQfSTX5rktijgtUH1o3/X55ZPg@/q72nmZ3bueg3wRJ4g6ZKtP5zRXflCkpFkZZPwku42To1pVOfynhVQYZm6CG3LSliPrO4kvI8jvw2pJRM3kbggYWbw@HxtrwLFu7iwfYoj/oH "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangular list of newline-terminated strings. Explanation: ``` WS⊞υι ``` Input the stack of tables. ``` ≔Eθ⪫⪪⭆υ§λκ-|¦#|θ ``` Transpose the stack and identify the ends of the tabletops i.e. those parts above the legs. ``` FθFΦ⪪ι#λ« ``` For each column of the original stack split it on tabletop ends, dropping the first element (which is the space above the first end) and loop over the resulting legs. ``` P↓№κ|→→ ``` Print the length of the leg vertically (which Charcoal automatically translates into a line of `|`s) without moving the cursor and then allow two columns for the next leg. ``` »←⸿⸿ ``` Move up to the start of the previous row but one. ``` FEυ⌕A⭆θ§λκ# ``` Transpose the stack back and find all of the tabletop ends. ``` Wι«⊕⁻⊟ι⊟ι→ ``` Loop over the ends in pairs, print the inclusive difference between each pair (which Charcoal automatically translates into a line of `-`s) and then allow a column for the next tabletop. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ζD„-|T:ζS®Ãƶþι`α>sS'|QγO0K‚ ``` Input as a list of lines; output as a pair of integer-lists, the first being the width of the table-tops and the second the length of the table-legs. [Try it online](https://tio.run/##MzBNTDJM/V/z/9w2l0cN83RrQqzObQs@tO5w87Fth/ed25lwbqNdcbB6TeC5zf4G3o8aZv3/rwAEulDABeLUgImaGi5dFMAFFYdiKBdTFkwDAA) or [verify all test cases](https://tio.run/##MzBNTDJM/R9dc3jCofWBykqeeQWlJVYKSjqHdutwKfmXlkC5/89tc3nUME@3JsTq8I7gQ@sONx/bdnjfuZ0J5zbaFQer1wSe2@xv4P2oYdb/w@t1Dm2z/68ABLpQwAXi1ICJmhouXRTABRWHYigXUxZMc3GhiMOUgySQrAPbB9UCpyEAr2QN0BwFFMehaEQHXCjaa7AyYSJontbFqxbdVSSo1SUM0LVgmkrQFmK0cIFsgkYYkFGDiDuoEyDRzQXhghwOYtaALaupQZLhQuiCWAyJbFwAahAuUIPhGzSfUSpNKPDxAsqkAQ). **Explanation:** Uses the legacy version of 05AB1E because it can zip/transpose on a list of strings, whereas the new version of 05AB1E would require a character-matrix. Step 1: Get the lengths of the table-tops: ``` ζ # Zip/transpose the (implicit) input-list; swapping rows/columns D # Duplicate this list of columns „-|T: # Replace each "-|" with "10" ζ # Zip/transpose back to a list of lines S # Convert the list to a flattened list of characters ®Ã # Only keep all "-" and "1" characters ƶ # Multiply each by its 1-based index þ # Only keep the integers, removing any "-"-strings ι # Uninterleave into two lists ` # Pop and push both lists separated to the stack α # Get the absolute difference between the values at the same positions # of the two lists > # Increase these integers by 1 ``` Step 2: Get the lengths of the table-legs: ``` s # Swap so the duplicated list of columns is at the top S # Convert it to a flattened list of characters '|Q '# Check for each character if it's equal to "|" γ # Group the list of 0s/1s into equal adjacent values O # Sum each group 0K # Remove all 0s ``` Step 3: Output the result: ``` ‚ # Pair the two lists of lengths together # (after which it is output implicitly as result) ``` [Answer] # [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 81 bytes ``` m:[({a<R>A}{b<R>A}*{a<R>P}~([^|]*(|[^|]*)%{2}*$))(<R>(~\-)|+!|)] a:\-<L>~| b:\-~ ``` Highlights each tabletop and each leg as a separate match. [Try it here!](http://www.brianmacintosh.com/snakeex/) ### Explanation Here's a somewhat ungolfed version: ``` main:[{top<>}{leg<>}] leg:<R>(~\-)|+!| top:{left<R>A}{mid<R>A}*{right<R>P}{check<>S} left:\-~| mid:\-~ right:\-<L>~| check:[^|]*(|[^|]*)%{2}*$ ``` The `main` snake uses brackets to match *either* a `top` *or* a `leg`. To match a `leg`: ``` <R> Turn right (initially, the match pointer faces east, so turn south) \- Match a literal hyphen (~ ) but don't mark it as part of the result |+ Match one or more pipes !| Assert that it's impossible to match another pipe ``` To match a `top`: ``` {left } Match the left edge of a table <R> turning right (south) to do so A and advance one step to the east afterward {mid }* Match 0 or more middle sections <R> turning right (south) to do so A and advance one step to the east each time {right } Match the right edge of the table <R> turning right (south) to do so P and move the cursor to the end of that match {check<> } Check that this isn't part of any other table (see below) S but don't mark that as part of the result ``` The `left` edge is: ``` \- Literal hyphen | Followed by a pipe ~ which isn't marked as part of the result ``` (Recall that we're moving southwards when we match this.) Similarly, the `mid` is `\-~` (same thing but with a space). The `right` edge is the same as the `left`, except it adds a `<L>` to turn left (east). This positions the match cursor just to the east of the table leg, ready to run the `check`. We need `check` because unlike regex, SnakeEx uses overlapping matches. So input like this ``` ---- |||| ``` would find not two but three matches for `top`, counting the two hyphens in the middle. To prevent such incorrect matches, we'll assert that the right side of each table must be followed by an even number of table legs. ``` [^|]*(|[^|]*)%{2}*$ After a table's right leg, proceeding eastward, match: [^|]* 0 or more non-leg characters ( ) This sequence: | Leg character [^|*] 0 or more non-leg characters %{2} Repeated twice * Repeated 0 or more times $ Edge of input ``` For the golfed version, we basically just combine `left` with `right` and inline `top`, `leg`, and `check` into `main`. [Answer] # Python3, 456 bytes: ``` lambda x:' '.join(a for *_,a in{(a,b+1,I,u[a:b+1])for I,u in E(x.split('\n'))for B,U in E(x.split('\n'))for a,b in g(U)if B-I==1 and set(u[a:b+1])=={'-'}})+'\n\n'+'\n'.join(' '.join(m)for m in Z(*sorted(j for k in Z(*x.split('\n'),fillvalue='')for j in findall('\|+',''.join(k))),fillvalue=' ')) from re import* from itertools import* E=enumerate Z=zip_longest r=lambda x:[(x[i],x[i+1])for i in range(0,len(x),2)] g=lambda x:r([i for i,a in E(x)if a=='|']) ``` [Try it online!](https://tio.run/##rVTBTuMwEL37K6xebLcO2raAVki@IHHgA7hQKmRUp7g4TuS4qy6Yby@202STsgkquyMlnTdv3sx4HLX4bZ9zPf9ZmH3KHvaKZ08rDndXCKKzTS415jDNDRw/Ug6lfsOcPk2m9JZuF/zKe0sSWA89CW/w7qwslLQYPWhEInVN7/ooXypQa3xHZAqvk1vGppDrFSyFxU19xt5Qgt7fycQrvTb8HEZrZsxivSxUu8fjMjdWrPAmDv5yCHba01Qq9YurrWAIRe0mpKVSr7hSPsdNEEWH4i@EdATQjw9Sk2fQCCizwncbV1haYWyeq7IJ3zCht5kw3Apwz15l8ahyvRalBYY1q17g3UIuqX/V@5RhGsN9Jv5BldB4R@iMLMH6j8jghYwHlPFiwoLDFjljyKEl2ZdsNBrBUw34J6ntFJE7@K7DDBTpF7kj3BElbes0OraWyHWq/839FAF91QZEwPUUO0GTfG2fRe7LK3LfEvkvCJTT8CElCXAVnAUYt@MreoMghudNOFpsFlq4ij6vaU@EMwbXewG5Oueizmk2447uInasjlNJLqNk4AhRNLDL0AP0b8L9F374OuMW@@0f6bCfwkhtcYpL/7/V@NM2mLXBvA3O2@CiDS4J2X8A) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 32 bytes ``` \|=:∩0v€Þfꜝ$2lƛÞṡƒ<T›;f2ẇvƒṡ"vvL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqF2ZiIsIlxcfD064oipMHbigqzDnmbqnJ0kMmzGm8Oe4bmhxpI8VOKAujtmMuG6h3bGkuG5oVwidnZMIiwiIiwiICAgIC0tLS0tLSAgICBcbiAgICB8ICAgIHwgICAgXG4tLS0tLS0tLS0tLS0tLVxufCAgICB8fCAgfHwgIHxcbnwgICAgfC0tLS0tLS0tXG58ICAgIHx8ICAgICAgfCJd) Port of Jelly. Port of 05AB1E ended up at same byte count: [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqEiLCLiiKk6duG5heKAmy184oKAdlbiiKlmdVPihpTijIrDnsW86pydec614oC6JGZcXHw9xKDhuaAwb1wiIiwiIiwiICAgIC0tLS0tLSAgICBcbiAgICB8ICAgIHwgICAgXG4tLS0tLS0tLS0tLS0tLVxufCAgICB8fCAgfHwgIHxcbnwgICAgfC0tLS0tLS0tXG58ICAgIHx8ICAgICAgfCJd) ]
[Question] [ ## [Introduction](https://i.stack.imgur.com/GYwVP.jpg): Ever used Dropbox with some other people and you both modified the same file? Ever had a multi-user application with a relational database, and two people were modifying (or worse, one was deleting and the other modifying) the same object? Well, let's simulate that with this challenge (sort-of). For the sake of this challenge, we only have two users and either one or two relevant files. Both users have in general privileges to [CRUD (Create, Read, Update, and Delete)](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) all files. ## Challenge: ### Input: We'll have a few inputs (input format is flexible, and any reasonable format is allowed): 1) ***Locking mode (on/off)***: Kinda the difference between [optimistic and pessimistic concurrency locking](https://en.wikipedia.org/wiki/Concurrency_control#Categories). Both users are allowed to CRUD (Create, Read, Update, and Delete) everything, but sometimes errors or problems can occur. Depending on the locking mode a problem when turned off, could be an error when turned on. This is explained below in the ***Output*** section. 2 & 3) ***Two user-actions***. These actions always consist of two things: What the user does (Create, Read, Update, or Delete) and for which file. ### Output: We'll have three possible outputs: 1. ***Valid***: Both actions by both users can be done simultaneously without any issues occurring. 2. ***Error***: Both actions by both users cannot be done simultaneously and causes an error for one of the users (which user is irrelevant for this challenge). This can occur when: * one user Reads or Updates a file, which the other user Deletes; * both users Update the same file with locking mode turned on; * a user Creates a file, which the other user Reads/Updates/Deletes (this means the file already exists, so it cannot be Created); * both users Create the same file. 3. ***Problem***: Both actions by both users can be done simultaneously, but can cause unexpected problems. This can occur when: * both users Update a file when locking mode is turned off; * one user Updates a file, which the other user Reads; * both users Delete the same file (practically this will causes an error for the second user, but since it will still be deleted like the user wants, it will be a problem instead of an error for the sake of this challenge) ## Challenge Rules: * All input and output is flexible, **and everyone should state which one they've used in their answer!** Example inputs: `0`/`1` for locking mode & `31` (third action: Update; file: 1) & `21` (second action: Read; file: 1); `true`/`false` for locking mode & `['C','A']` (action: Create; file: A) & `['D','B']` (action: Delete; file: B); etc. Example outputs: `null`/`true`/`false` (null = valid; true = error; false = problem); `-1`/`0`/`1` (-1 = error; 0 = problem; 1 = valid); etc. The three possible outputs have to be **unique and distinct** for the three output-type, though. * What the files are called is irrelevant, which can also be seen with the input-examples above. So feel free to use any type of file name in your answers consisting of a single (ASCII) letter or digit. They do have to be consistent across all your test cases however, so you can't use `A`/`B` in one test case and `1`/`2` in another. * The four actions for CRUD have to be unique and consistent values as well. So you cannot use `'D'`/`'C'` in one test case, and then `4`/`1` in another test case. * You can assume that the file chosen by a user always exists when they want to Read, Update, or Delete it. ## 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. ## All possible test cases (where the actions can be in either input-order*†*): *†*: You should support all (up to four) variations of the test cases below. So if a test case states `action1: Create file A; action2: Update file B`, that test case should also hold the same results for `action1: Create file B; action2: Update file A`; `action1: Update file B; action2: Create file A`; and `action1: Update file A; action2: Create file B`. ``` Valid use-cases: locking mode: either; action1: Create file A; action2: Create file B locking mode: either; action1: Create file A; action2: Read file B locking mode: either; action1: Create file A; action2: Update file B locking mode: either; action1: Create file A; action2: Delete file B locking mode: either; action1: Read file A; action2: Read file A locking mode: either; action1: Read file A; action2: Read file B locking mode: either; action1: Read file A; action2: Update file B locking mode: either; action1: Read file A; action2: Delete file B locking mode: either; action1: Update file A; action2: Update file B locking mode: either; action1: Update file A; action2: Delete file B locking mode: either; action1: Delete file A; action2: Delete file B Error use-cases: locking mode: either; action1: Create file A; action2: Create file A locking mode: either; action1: Create file A; action2: Read file A locking mode: either; action1: Create file A; action2: Update file A locking mode: either; action1: Create file A; action2: Delete file A locking mode: either; action1: Read file A; action2: Delete file A locking mode: on; action1: Update file A; action2: Update file A locking mode: either; action1: Update file A; action2: Delete file A Problem use-cases: locking mode: either; action1: Read file A; action2: Update file A locking mode: off; action1: Update file A; action2: Update file A locking mode: either; action1: Delete file A; action2: Delete file A ``` [Answer] # JavaScript (ES6), 36 bytes ### Without a lookup table ``` (m,a,f,A,F)=>f-F?2:a^A?a*A&8:a&4?m:a ``` [Try it online!](https://tio.run/##jZPBToNAEIbvfYo9tWCmRpseGgySQeBkSmOqJ2OytmBqgDW08fVxETEWgf1PDMOfj9nNfO/yUx535eHjNC/UPqlSt7JykpQSU2S7t@k88haOfGFPXvB05cjp0ssdWe1UcTyJeC1ccUUijiJdrEhw8@7rxzWJu4eQt2HT0mWgqwWJx03QdJckgvA@/K5XN5NJzVRZcpmpN2v2JLPD3pnZZ93Uitckfrj6b/Rb@va/ZBQRmOww61F1B2COJDvM5tDInCPJDrO5PIQ5kqyZ7TH@nIj7mVhygOnDTPOchvvEkh2m4T6xZM1sf2meE0t2mIY5sWTNbD@bmQPJc2Wfi7AsVYlLy7C0DEvLsLQMS8uwtAxLy7C0DC8uw4vL8OIyvI4MryP3rM6mVK9Zkg8sT4/PDJvPsHsMe8KwJzpZfQE "JavaScript (Node.js) – Try It Online") ### I/O * Locking mode (\$m\$): \$0\$ = On, \$8\$ = Off * Actions (\$a\$ and \$A\$): \$0\$ = Create, \$2\$ = Read, \$4\$ = Update, \$8\$ = Delete * Files (\$f\$ and \$F\$): any integers * Output: \$0\$ = Error, \$2\$ = Valid, \$8\$ = Problem ### How? If the files are different, all operations are safe and we just return \$2\$ (valid). If the files are identical, we need to return: * \$2\$ (valid) if we have two *read* operations * \$8\$ (problem) if we have two *delete* operations, or one *update* and one *read* * \$m\$ (either problem or error) if we have two *update* operations * \$0\$ (error) for everything else Using a \$4\times4\$ CRUD matrix (which is symmetric by definition), we can see that the above values can be computed with: $$\underbrace{\text{a ^ A}}\_{a\neq A?}\text{ ? }\color{blue}{\text{a \* A & 8}}\text{ : }\underbrace{\text{a & 4}}\_{\text{update?}}\text{ ? }\color{red}{\text{m}} : \color{magenta}{\text{a}}$$ $$\begin{array}{cc|cccc} &&\text{C}&\text{R}&\text{U}&\text{D}\\ &&0&2&4&8\\ \hline \text{C}&0&\color{magenta}{0}&\color{blue}{0}&\color{blue}{0}&\color{blue}{0}\\ \text{R}&2&\color{blue}{0}&\color{magenta}{2}&\color{blue}{8}&\color{blue}{0}\\ \text{U}&4&\color{blue}{0}&\color{blue}{8}&\color{red}{\text{m}}&\color{blue}{0}\\ \text{D}&8&\color{blue}{0}&\color{blue}{0}&\color{blue}{0}&\color{magenta}{8} \end{array}$$ --- # JavaScript (ES6), ~~46 45~~ 40 bytes ### With a lookup table ``` (m,a,f,A,F)=>f-F?0:[m,1,1,0][a*2+A*9&23] ``` [Try it online!](https://tio.run/##jZNBT4NAEIXv/RV7slC3htKTNWgGYU@mNEa91B6wgMFQ1tDq38elFGMR2BcODMPLt7OT9z7C73C/LdLPwzSXUVwmTmnseMgTTlyYzm0yFXfWYr3jM/VYm3U4sS9pcn1hzzflVub7AwuWzGFfeRQnaR5HnAVCqMaMM1IvizO3/npeefTk161Hn7y6e6/KY9fmzPMf/GM9vxmNKrbM4qtMvhvjlzBLo8XYPOsmRrDk7ERQp/Hf0jX/KYXgoLLFrEZVHYA5oGwx61Ugcw4oW8x6eQhzQFkxm2v8uRF1MzFlD9OFmfo5NfvElC2mZp@YsmI2R@rnxJQtpmZOTFkxm996Zo/yPLKvuV8UssBDS3BoCQ4twaElOLQEh5bg0BIcWoKNS7BxCTYuwXYk2I7UYZ1VId@yeNdjno48E5x8grNHcE4IzolSlj8 "JavaScript (Node.js) – Try It Online") ### I/O * Locking mode: *undefined* = On, \$1\$ = Off * Actions: \$0\$ = Update, \$1\$ = Read, \$2\$ = Create, \$3\$ = Delete * Files: any integers * Output: *undefined* = Error, \$0\$ = Valid, \$1\$ = Problem [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 53 bytes ``` ^(.)(?!\1).+|..RR. V ..DD. P ..UUL E .+[CD].+ E ..+ P ``` [Try it online!](https://tio.run/##Hc07CgJBEIThfG5hIOyy0OAJZGtHTCZYGtrEBxoYmBiIoXcfZ/6kuij46M/z@3o/6nY43uttsHHYby670aafmbulUzLL2dLabkRJh2TTeclXm3ptudY6z8sSqaWTQeaezuIszhL0oOeewgorrLDCCiussMIK2/4W/pJB5sJfksVZgh703FNYYYUVVlhhhRVW2Pa3/AE "Retina 0.8.2 – Try It Online") Link includes test suite. Takes input as a string of 5 characters, two characters representing the file names, then two characters from `CRUD`, then `L` or `U` (locked/unlocked), and outputs one of `VPE` (valid/problem/error). Explanation: ``` ^(.)(?!\1).+|..RR. V ``` Different file names are always valid, as are two reads. Annoyingly, this is the only test that forces me to use a header. (It would cost an extra byte to make the header unnecessary.) ``` ..DD. P ``` Two deletes are always a problem. ``` ..UUL E ``` Two locked updates are an error. ``` .+[CD].+ E ``` Any other creates or deletes are an error. ``` ..+ P ``` Everything else is a problem. [Answer] # [Octave](https://www.gnu.org/software/octave/), 96 bytes ``` @(a,b,c)[a(1)!=b(1)|a(2)+b(2)==20,mod((m=a+b+c)(2),10010)<1|mod(m(2),1020000)<1|mod(m(2),200)<1] ``` [Try it online!](https://tio.run/##VYqxDoQwDEN/pbclalQlnYnEfyCGtAdbxXJi4t9LKNN5sOVnH/Vn59b3oCGl1GcwKlRxMRD8aHG/DDLG4qaamdrxBWhqscSKDkmYhXGS61naSzK7/lgefe07LOKHlUZ4BhnffgM "Octave – Try It Online") Definitely can be shorter, but I don't have time right now to do that ``` File 1 = 0 File 2 = 1 Read = 10 Delete = 100 Create = 1000 Update = 10000 Lock on = 100000 Lock off = 1000000 Valid Values: [1 0] Problem Values: [0 1] Invalid Values: [0 0] ``` Input as a = [file, action], b = [file2, action2], c = lock ]
[Question] [ Honestly, I can't believe this hasn't already been asked, but here it is # Background Given a simple undirected *planar* (the graph can be drawn in the plane without intersections) graph, it is a proven theorem that the graph is 4-colorable, a term we will explore in a bit. However, it's far easier to 5-color a graph, which is what we will focus our challenge on today. A valid k-coloring of a graph is an assignment of "colors" to the nodes of the graph with the following properties 1. If two nodes are connected by an edge, the nodes are colored with different colors. 2. Across the graph, there are a maximum of 5 colors. Given this, I will present to you a pretty basic algorithm to 5-color any simple undirected planar graph. This algorithm requires the following definitions **Reachability**: If node 1 is reachable from node 2, that means that there is a sequence of nodes, each connected to the next by an edge, such that the first node is node 2 and the last is node 1. Note that since undirected graphs are symmetric, if node 1 is reachable from node 2, node 2 is reachable from node 1. **Subgraph**: A subgraph of a graph of a given set of nodes N is a graph where the nodes of the subgraph are all in N, and an edge from the original graph is in the subgraph if and only if both nodes being connected by the edge are in N. Let Color(N) be a function to color planar graphs with N nodes with 5 colors. We define the function below 1. Find the node with the least number of nodes connected to it. This node will have at most 5 nodes connected to it. 2. Remove this node from the graph. 3. Call Color(N-1) on this new graph to color it. 4. Add the deleted node back to the graph. 5. If possible, color the added node a color that none of its connected nodes have. 6. If not possible, then all 5 neighboring nodes to the added node have 5 different colors, so we must try the following process. 7. Number the nodes surrounding the added node n1...n5 8. Consider the subgraph of all nodes in the original graph colored the same color as either n1 or n3. 9. If in this subgraph, n3 is not reachable from n1, in the set of nodes reachable from n1 (including n1), replace all occurrences of n1's color with n3's and vice versa. Now color the added node n1's original color. 10. If n3 was reachable from n1 in this new graph, do the process from step 9 on nodes n2 and n4, rather than n1 and n3. # Challenge Given an input of an edgelist (representing a graph), color the graph, by assigning each node a value. **Input**: A list of edges in the graph (i.e., `[('a','b'),('b','c')...]`) Note that the input edgelist will be such that if (a,b) is in the list, (b,a) is NOT in the list. **Output**: An object containing pairs of values, where the first element of each pair is a node, and the second its color, i.e.,`[('a',1),('b',2)...]` or `{'a':1,'b':2,...}` You can use anything to represent colors, from numbers, to characters, to anything else. The input and output is quite flexible, as long as its quite clear what the inputs and outputs are. # Rules * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge * You do not have to use the algorithm I've described above. It is simply there for reference. * For any graph, there are often many valid methods of coloring them. As long as the coloring your algorithm produced is valid, that is acceptable. * Remember that the graph must be 5-colored. # Test Cases Use the following [code](https://tio.run/##nZDRS8MwEMbf@1ccfVkDceBkL4XtRRB81rcxJKbXNVuWlOSqFvFvr9fWbqggQyjp3Zcvv@S@uqXKu5uuK7AEwkhP2lsfjNtlQ1EYTRKw2KE1kUSeAMxmM6pMhLJxmox3oCvUhwivFVKFARTsgqormEDA3uXVi7KmmMM9AakDRlARjKsbYnt/B3NUaMGX4Hwxbh@w5b8rRtAgMaTBKAdVudOzmAR8NZQ@HHuEgkHlipraYuRH8/egjtzArbI25gkL6@/zvqcqza9l@pzmC5lqrj/kJmOxl4TMWBqqreCzj6HBCxCLPxB3ykYc8@TVlGDRZRHpHPx8nDcTQqyXffQAAakJLhvO9hAeGYzc9wlMaYxGCu1YDOgTcmO2q9W5228n0280AL5prGly/Nz/6vskRJLUHABl/01UdN0n) to test your coloring results validity. As there are many valid graph colorings per graph, this algorithm simply checks the validity of the coloring. See the docstring to see how to use the code. **Some random (and rather silly) test cases**: Test Case 2: [Krackhardt Kite Graph](https://en.wikipedia.org/wiki/Krackhardt_kite_graph) `[(0, 1), (0, 2), (0, 3), (0, 5), (1, 3), (1, 4), (1, 6), (2, 3), (2, 5), (3, 4), (3, 5), (3, 6), (4, 6), (5, 6), (5, 7), (6, 7), (7, 8), (8, 9)]` A valid output: `{0: 4, 1: 3, 2: 3, 3: 2, 4: 4, 5: 1, 6: 0, 7: 4, 8: 3, 9: 4}` **Note**: These test cases are too small to test the more nuanced behavior of the coloring algorithm, so constructing your own graphs is probably a good test of the validity of your work. **Note 2**: I'll be adding another piece of code that'll graph your coloring solution soon. **Note 3**: I didn't forsee the random coloring algorithms that have been presented, which is what's so cool about PPCG! However, if anyone could golf a more deterministic algorithm, that'd be very cool too. [Answer] # [Python 2](https://docs.python.org/2/), 96 bytes ``` i=0 g=input() while 1:i+=1;c={k:i/4**k%4for k in sum(g,())};all(c[s]^c[t]for s,t in g)>0<exit(c) ``` [Try it online!](https://tio.run/##RcrfCoIwFMfx@57i3ASbDXJz/klbLyIGMUyHppKTiujZV4sDXn34nfOdXrYdB@GcUeGmUWaYFkvo5tGavgaem53ihVbvLjd7GQTdVl7HO3RgBpiXG2kYofRTXPqe6HKuzrq0lQ9mZn3S0FN4rJ/GEk2dK0nIgFMGXoFGaOzluH9KNPEKvAvsIvxH6/53Eo1XU2@Cpgwyb8bgQKsv "Python 2 – Try It Online") The input is \$g\$, a list of pairs of integers. We count up \$i\$ from zero, and map natural numbers to graph 4-labelings \$c\$, aborting (and writing \$c\$ to STDERR) as soon as \$c\$ is a valid coloring. The input is planar, so finding a 4-coloring is always possible. (Thus: this finds the lexicographically earliest coloring in a sense, and does so very inefficiently.) The mapping: node \$ k \$ is given color \$ \Big\lfloor \frac{i}{4^k} \Big\rfloor \bmod 4 \$, i.e. the \$k\$’th least significant digit of \$i\$ in base 4. [Answer] # JavaScript (ES7), ~~80~~ ~~76~~ 74 bytes *Saved 2 bytes thanks to @Neil* Same approach as [Lynn](https://codegolf.stackexchange.com/a/170673/58563). Solves in 4 colors, numbered from **0** to **3**. ``` a=>{for(x=0;a.some(a=>a.map(n=>z=c[n]=x>>n*2&3)[0]==z,c={});x++);return c} ``` [Try it online!](https://tio.run/##RcpLCoMwFAXQuavIqCRtKv61yHMjkkFItbRoImqLKK7dGnng6HA/H/mTg@rf3XjX5lltNWwSiqU2PZ3Ay6U7mLaieyXdVnZUQzGDKrWAqSj0NbiErPQEwMwVLCvLp9uN5X01fntN1LopowfTVG5jXrSmpUNI6XHiC34YoCEaW33MuxGaWAPsA/yFuIdnPn4RGp@m1gRNOcmsGScP4QjGtj8 "JavaScript (Node.js) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 38 bytes ``` cd{∧4>ℕ}ᶻ.g;?z{tT&h⊇ĊzZhpT∧Zt≠}ᵐ∧.tᵐ≜∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/Pzml@lHHchO7Ry1Tax9u262Xbm1fVV0SopbxqKv9SFdVVEZBCFA@quRR54Lah1snANl6JSC6cw6Q@f9/dLRSopKOUpJSrA6ElQxnpcBZaWBWElwMxEqFs9LBrGS4bDJcRwpcXQqKGERHKpyVhsLKALPS4awMICsTzMoEsrKUYmP/RwEA "Brachylog – Try It Online") ### Explanation ``` Example input: [["a","b"],["c","b"]] cd Concatenate and remove duplicates: ["a","b","c"] {∧4>ℕ}ᶻ. The output is this list zipped zith integers that are in [0..4]: [["a",I],["b",J],["c",K]] .g;?z Zip the output with the input: [[[["a",I],["b",J],["c",K]],["a","b"]],[["a",I],["b",J],["c",K]],["c","b"]] { }ᵐ∧ Map for each element tT Call T the couple of nodes denoting an edge &h⊇Ċ Take a subset of 2 elements in the head zZ Zip and call it Z ZhpT The nodes in Z are T up to a permutation ∧Zt≠ The integers in Z are all different color .tᵐ≜∧ Label the integers (i.e. colors) in the output so that it matches the set constraints ``` [Answer] # [Python 2](https://docs.python.org/2/), 211 bytes ``` def f(g): g={k:[(a,b)[a==k]for a,b in g if k in(a,b)]for k in sum(g,())};c={k:0 for k in g} for a,b in sorted(g.iteritems(),key=lambda a:len(a[1])):c={k:(c[k],c[k]+1)[c[a]==c[k]and k in b]for k in c} return c ``` [Try it online!](https://tio.run/##jZLPbsIwDMbP9Cksdkm0CPFnFNbRy9ht0l6g6qTQpqVqoVWaTkITz87skFFAmrRD@@WL7Z8tK83BbOv99JSqDL5kVaTSKJbUVa1bAbmWzZYH3qDRxd7A8EMV@XaDIXgrskxphZdrmxsMBciqcpVRG3@6k4mzWkMrDBR7x7vgVuDflcuVD5QvKftMGOFUnWoZ53bGjOU4EOThdxlETIoNj2QYlrYLOtsFigxKPNmwjZCDttuxXCDo@JJQ@RguofzowRWhrbVRKctHhVEavx22F6U6hJXcbVIJMqgU0qNJzHlgWSyJyljQ73HCoySScRiSk/v03GHTz5FgM61Mp/F4Mqo1LYTAvMEDvHYGG2bV4bwpbxCxsYApF0A6I504j/pEOnX3U/KxIMq63jWVMuoGMnGQv2CzC@wMedcyKbdSpwbK4j8s1Pk163dAVP9uUJs3c/FZ723ek9N5rwtS3@lCwJJ0KeCZxx73PFosrZF2a9eJDzbBlWaM3OW5Jd6gf@ACbmKnHw "Python 2 – Try It Online") Deterministic! Would probably fail on more complicated test cases, but I'm too burnt out to find a graph that it fails for. More test cases and.or criticism welcome! [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 139 bytes ``` import StdEnv,Data.List $l#(a,b)=unzip l #e=nub(a++b) =hd[zip2 e c\\c<- ?e|all(\(a,b)=c!!a<>c!!b)l] ?[h:t]=[[n:m]\\n<-[0..4],m<- ?t] ?e=[e] ``` [Try it online!](https://tio.run/##Rc5Ni4MwEAbge37FlPagNJVW7Sdme@keFnpY6DF6GNO0CkkUGxd22d@@rrYBL3l4JzPwCiXRdLq6tkqCxtJ0pa6rxsLFXt/NFz2hxeBcPiyZqamHNPdZa37KGhSZSmba3MP5PPcJK668H4cgQaSpSBZwlL@olJe@jsRkgslb/@a@ysiRFwebMc7NQWdpapIFXwZBnFE9HNp@QTIus@5isbFkCvcG6wIYcG9JYeVTGAydkXM9uHK5N3ZuBkM3D91e5P6jMT/3Yud6dDu4cW4p7AZ3FPZ@1le7tUbYsjJ9uxlhY3xW7v7ETeH90S0@zt3p26AuxSt8KrS3qtH/ "Clean – Try It Online") Generates all colorings and returns the first valid one. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ®iⱮⱮ³¤ịE€S FQ©L4ṗÇÐḟḢ®ż ``` [Try it online!](https://tio.run/##y0rNyan8///QusxHG9cB0aHNh5Y83N3t@qhpTTCXW@ChlT4mD3dOP9x@eMLDHfMf7lh0aN3RPf///4@O1rXQMTKK1Yk2MtIxMQHSJiY6BkDKACQaCwA "Jelly – Try It Online") Brute force. Assumes the nodes are labeled by integers. ]
[Question] [ Given a list of hole yardages, green sizes, a slice angle and a max distance, compute a [golf](https://en.wikipedia.org/wiki/Golf) score. ## Assumptions * Earth is flat * All greens are circular * Slice angle will be between -45 and 45 degrees and will be given in degrees * All distances in the same metric (yards or meters, doesn't matter) * No out of bounds, obstructions or doglegs * Max score on any hole is 8 * All shots travel the lesser of max distance or distance to the hole, in a direction defined by the angle to the hole plus the slice angle. * Distance is measured as the straight line or Euclidean distance between the start and end point. * Max distance and slice angle are the same for all shots on all holes * The golfer always two-putts once on the green (or exactly on the edge of the green). ## Example Let's look at the hacker from the test case #5 below for hole #2. The hacker can hit the ball 320 yards, but always slices 30 degrees. If we assume without loss of generality that the tee box is at {0,0} and the green is at {497,0}, then he will hit shots to the following points, arriving on the green with the 7th shot: `{{0.,0.},{277.128,-160.},{547.543,-131.372},{569.457,7.67088},{502.872,37.2564},{479.159,7.92741},{490.646,-7.85868},{500.078,-4.22987}}` At this point, his score would be 9 due to the two putts required, so the final score for him gets capped at 8, per the assumptions. Graphically, it will look like this: [![enter image description here](https://i.stack.imgur.com/HpkrV.png)](https://i.stack.imgur.com/HpkrV.png) ## Test Cases All the test cases have standard 18-hole courses ``` Case#1 {MaxDistance->280,SliceAngle->10,HoleDistances->{181,368,161,416,158,526,377,427,509,148,405,443,510,494,396,388,483,172},GreenDiameters->{26,18,17,23,27,23,21,23,25,21,19,24,21,23,25,24,22,22}} Scores: {4,5,4,5,4,5,5,5,5,4,5,5,5,5,5,5,5,4} Output: 85 Case#2 (same course as Test Case #1, shorter more accurate golfer) {MaxDistance->180,SliceAngle->5,HoleDistances->{181,368,161,416,158,526,377,427,509,148,405,443,510,494,396,388,483,172},GreenDiameters->{26,18,17,23,27,23,21,23,25,21,19,24,21,23,25,24,22,22}} Scores: {4,5,4,5,4,6,5,5,6,4,5,5,6,6,5,5,5,4} Output: 89 Case#3 (Same golfer as test case #1, shorter course) {MaxDistance->280,SliceAngle->10,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}} Scores: {4,5,4,5,5,4,4,4,4,5,5,5,4,4,5,5,5,5} Output: 82 Case#4 (Same course as test case #3) {MaxDistance->180,SliceAngle->5,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}} Scores: {3,6,3,6,5,4,4,3,3,5,5,5,3,3,5,5,6,5} Output: 79 Case#5 (Hacker) {MaxDistance->320,SliceAngle->30,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}} Scores: {6,8,5,8,7,6,6,6,6,8,8,8,6,6,8,8,8,8} Output: 126 ``` ## Rules * Any format can be used for the input. Output is simply the number of simulated strokes, so should be an integer. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. Standard loopholes apply. [Answer] ## JavaScript (ES7), ~~128~~ 126 bytes ``` (m,a,D,S,t=0)=>S.map((s,i)=>t+=(r=(f=d=>d>s/2?1+f((l=d<m?d:m,l*l+d*d-2*d*l*Math.cos(a*Math.PI/180))**.5,s):2)(D[i]))<8?r:8)&&t ``` [Try it online!](https://tio.run/##XYy7boMwFIb3PIWnyHZOCMfYYFAMS5YOlSpljBgsTAgVhHBRX586Tbt0@PRfdP7zab/sXE3tY9nfB1evXb2QhpiV9mDhBGdYTMhMfg56@6B0htaHZWfoZOjVOJO7fD6IAndXSkfjjn3hsh5GPu4cd3vBR@74u11uQTXM1L7sx9sBdcgY54GCmWWC0dOlLRk76mLKNNtul7Ua7vPQ1UE3NLShQodAMIQNIRfUCFGsAWMEiTGg0qBEDFGSgBQJqDAFlBpkqEDKCJTfyVRClPob7XsdASai/HlG/JCg9iRAROT5U/xV9fKYepX/@mcWT8oNY@s3 "JavaScript (Node.js) – Try It Online") ### Explanation Because only the distance from the ball to the hole matters and not the coordinates of the ball, we can write an algorithm that calculates how close the ball gets to the hole with each shot, then run that repeatedly until the ball reaches the green. But how do we do this? Re-using OP's helpful diagram explaining ball movement, with MS Paint modifications: [![the science of golf](https://i.stack.imgur.com/A9yOF.png)](https://i.stack.imgur.com/A9yOF.png) We have access to these numbers: * **d**, the current distance from ball to hole; * **θ**, the slice angle; and * **l**, the length of the shot (minimum of **d** and the max shot length). And the goal is to find **x**, the distance from ball to hole after the shot is taken. First we note that **a** and **b** are simply **l cos θ** and **l sin θ**, respectively. We can see that by the Pythagorean theorem, **x** can be represented as **sqrt(b2 + (d-a)2)**. Expanding this out, we get ``` x = sqrt(b^2 + (d - a)^2) = sqrt((l*sin(θ))^2 + (d - l*cos(θ))^2) = sqrt((l^2 * sin^2(θ)) + (d^2 - 2*d*l*cos(θ) + l^2 * cos^2(θ)) = sqrt(l^2 * sin^2(θ) + l^2 * cos^2(θ) + d^2 - 2dl*cos(θ)) = sqrt(l^2 * (sin^2(θ) + cos^2(θ)) + d^2 - 2dl*cos(θ)) = sqrt(l^2 * 1 + d^2 - 2dl*cos(θ)) = sqrt(l^2 + d^2 - 2dl*cos(θ)) ``` And so, the new distance from ball to hole will be **sqrt(l2 + d2 - 2dl cos θ)**. Then we count the iterations it takes to get this distance within the radius of the green, add 2, and cap at 8 to get the final score for that hole. (Thanks to @LegionMammal978 for pointing out that all of the calculations I made are a direct result of the [law of cosines](https://en.wikipedia.org/wiki/Law_of_cosines)...) --- Interestingly enough, when the ball is closer to the hole than its max shot, **l = d** and we can simplify the formula quite a bit further: ``` x = sqrt(l^2 + d^2 - 2dl*cos(θ)) = sqrt(d^2 + d^2 - 2d^2*cos(θ)) = sqrt(2d^2 - 2d^2*cos(θ)) = sqrt(d^2(2 - 2cos(θ))) = d * sqrt(2 - 2cos(θ)) ``` To find the # of remaining iterations, we could then simply find **d / r** (where **r** = the radius of the green) and divide that by **sqrt(2 - 2cos(θ))**, then take the ceiling of the result and add 2. Unfortunately, this doesn't seem to be as short as just finding the smaller of **d** and the max shot length. [Answer] # [Perl 5](https://www.perl.org/), ~~144~~ 138 + 12 (`-MMath::Trig`) = 150 bytes *shaved a few bytes using @ETHproductions' simplification of the formula* ``` sub p{$_=pi/180*pop;$m=pop;for$b(@_[0..17]){$s=!++$c;1while++$s<6&&$_[17+$c]/2<($b=sqrt$b*$b+($h=$m<$b?$m:$b)**2-2*$h*$b*cos);$t+=$s+2}$t} ``` [Try it online!](https://tio.run/##TYzNbsIwEITv@xRUWiFIRPA6duz8uOUFuPWGEIoRbSKRxo1TVRXi1ZsaekFazTea3Vl3Gs5ymvyXnbkLHoxr16RZ5HpXYmdueOsHtIvNYceShNR@eUFvnuIYjyV9N@35FKyvsvkcDztSId6vebVAa/znMKKN0MYLbAx2FdoX7Aq0yyjiKx5hE3bRsffLEsfYoI/5FcfrtKlN9Vwem75zm7r09c/sxok0QZppoIxAUAYkNUieQaoUCK5AshxIaBBMghApSGIgcgFpHm50yHUKpDiECoUvCngK/F/prvJmKAcuHpLg@X00A2K/vRvb/sNPq61MGLHAbT02RfE6tO9/ "Perl 5 – Try It Online") Changed up the input format a bit: ``` Hole 1 distance Hole 2 distance ... Hole 18 distance Hole 1 green diameter ... Hole 18 green diameter Maximum distance Slice angle ``` [Answer] # [Julia 0.6](http://julialang.org/), 106 bytes ``` S(m,t,D,G)=(s(m,d,g,v=2)=d<=g/2?v<8?v:8:(l=d<m?d:m;s(l,(d^2+l^2-2d*l*cosd(t))^.5,g,v+1));sum(s.([m],D,G))) ``` [Try it online!](https://tio.run/##zZDBbsIwDIbvewqOCfxjteM0CVD1MmkPwBGBNK0SYmrZtEJfv3PKYVx2R7Ijx7J/f/bntT29l@O4NR0ueMWbrUyvcYMjhopt1Wyq4wvXwybWwyquTKuZrm5W3bo3LUxz4EV74Gdu5u3846tvzMXaw9Ln9gVZu@6vnemXZtftJ3Vrx@@f0/nSns3WcCwwI/UdRYIrI6gkCJUgH@G5hAsBwgG@SCCJkMJDxMFrlySBS1oTNR8dKPBepbSLVCiAHfj20vT6HFACy11GY1bbW/v0x0WZyz8c1t25ROenANKf5zxfObJ8yowCcqIsyhFE61TeZc/sDhIyF2XOzOVYt9Ml81iNuYC7mYKkiaWczE@ZODHG/871UFhOm2buQc41/gI "Julia 0.6 – Try It Online") Based on [ETHproductions' answer](https://codegolf.stackexchange.com/a/153887/76880). **Explanation** * `s(m,d,g,v=2)=...` Define function `s` that calculates the score for one hole recursively. * `sum(s.([m],D,G))` Apply `s` for each hole and sum the result. `.` is element-wise function application with singleton expansion. E.g.: `min.([1],[2,3]) = [min(1,2), min(1,3)]` ``` d<=g/2?v<8?v:8:(l=d<m?d:m;s(...)) # d<=g/2? : # is the ball on the green? v<8?v:8 # yes -> return min(v,8) (l=d<m?d:m;s(...)) # no -> # calculate new distance using ETHproductions' formula # increment current score # call s recursively ``` ]
[Question] [ Consider three sets `A`, `B` and `C` each containing `n` integers. From this we can make the set ``` S_n = {a * b + c | a in A, b in B, c in C}. ``` Given an `n`, there are one or more minimal sized `S_n` which depend on which sets `A,B and C` have been chosen. The sets can contain any `n` distinct integers (positive, zero or negative). There is no need for them to be consecutive integers or for the sets to be equal to each other for example. `A = {-1, 0, 5, 10, 27}, B = {2, 5, 6, 10, 14} and C = {-23, 2, 100, 1000,10000}` is acceptable (although not a good idea) for example. **Task** The task is to write code to find the smallest set `S_n` it can for each `n` from `1` to `20`. For each `n` from `1` to `20` your code should output the chosen `A`, `B` and `C` along with the resulting size of `S_n` **Score** Your score will be the sum of the sizes of the `S_n` you create. That is it will be a sum of twenty numbers. The lower the score the better. **Examples** If `A = B = C = {1, 2, 3, 4}` then `S_4 = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}` which is of size `19`. This is however in no way optimal. For example, `A = B = C = {-1, 0, 1, 2}` gives `S_4 = {0, 1, 2, 3, 4, 5, 6, -1, -3, -2}` which is of size `10`. **Timings** As I will need to run your code to verify the output, please make sure it takes no more than 30 minutes and 4GB of RAM to run on a normal desktop. **Notes** Your code must actually compute the output. You are not allowed to hardcode precomputed answers into your code. [Answer] # Rust, score ~~1412~~ 1411 ### `src/main.rs` ``` extern crate gmp; use std::collections::BinaryHeap; use std::collections::hash_map::{HashMap, Entry}; use gmp::mpz::Mpz; fn visit( queue: &mut BinaryHeap<(i32, i32, i32, Mpz, Mpz)>, visited: &mut HashMap<(i32, Mpz), i32>, score: i32, h: i32, k: i32, d: Mpz, c: Mpz, ) { match visited.entry((k, d.clone())) { Entry::Occupied(mut e) => { if *e.get() < score { e.insert(score); queue.push((score, h, k, d, c)); } } Entry::Vacant(e) => { e.insert(score); queue.push((score, h, k, d, c)); } } } fn main() { let mut total = 0; for n in 1..21 { let a_range = n / 2 - n + 1..n / 2 + 1; let min_ab = a_range.start * (a_range.end - 1); let mut ab = Mpz::zero(); for a in a_range.clone() { for b in a_range.clone() { ab.setbit((a * b - min_ab) as usize); } } let heuristic = |k: i32, d: &Mpz| if k == n { 0 } else { k + 1 - n - (0..d.bit_length()) .map(|i| (&ab & !(d >> i)).popcount()) .min() .unwrap() as i32 }; let mut queue = BinaryHeap::new(); let mut visited = HashMap::new(); let (k1, d1) = (0, Mpz::zero()); let h1 = heuristic(k1, &d1); visit(&mut queue, &mut visited, h1, h1, k1, d1, Mpz::zero()); while let Some((score, h, k, d, c)) = queue.pop() { if k == n { println!("n={} |S|={}", n, -score); println!(" A={:?}", a_range.clone().collect::<Vec<_>>()); println!(" B={:?}", a_range.clone().collect::<Vec<_>>()); println!( " C={:?}", (0..c.bit_length()) .filter(|&i| c.tstbit(c.bit_length() - 1 - i)) .collect::<Vec<_>>() ); total += -score; break; } let kd = (k, d); if score < visited[&kd] { continue; } let (k, d) = kd; let (k1, d1) = (k, &d >> 1); let h1 = heuristic(k1, &d1); visit( &mut queue, &mut visited, score - h + h1, h1, k1, d1, &c << 1, ); let (k1, d1) = (k + 1, (&d | &ab) >> 1); let h1 = heuristic(k1, &d1); visit( &mut queue, &mut visited, score - h - (&ab & !&d).popcount() as i32 + h1, h1, k1, d1, &c << 1 | Mpz::one(), ); } } println!("total={}", total); } ``` ### `Cargo.toml` ``` [package] name = "small" version = "0.1.0" authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"] [dependencies] rust-gmp = "0.5.0" ``` Compile and run with `cargo run --release`. ### Output ``` n=1 |S|=1 A=[0] B=[0] C=[0] n=2 |S|=3 A=[0, 1] B=[0, 1] C=[0, 1] n=3 |S|=5 A=[-1, 0, 1] B=[-1, 0, 1] C=[0, 1, 2] n=4 |S|=10 A=[-1, 0, 1, 2] B=[-1, 0, 1, 2] C=[0, 1, 2, 3] n=5 |S|=13 A=[-2, -1, 0, 1, 2] B=[-2, -1, 0, 1, 2] C=[0, 1, 2, 3, 4] n=6 |S|=21 A=[-2, -1, 0, 1, 2, 3] B=[-2, -1, 0, 1, 2, 3] C=[0, 2, 3, 4, 5, 6] n=7 |S|=25 A=[-3, -2, -1, 0, 1, 2, 3] B=[-3, -2, -1, 0, 1, 2, 3] C=[0, 2, 3, 5, 6, 7, 8] n=8 |S|=35 A=[-3, -2, -1, 0, 1, 2, 3, 4] B=[-3, -2, -1, 0, 1, 2, 3, 4] C=[0, 3, 4, 6, 7, 8, 10, 11] n=9 |S|=39 A=[-4, -3, -2, -1, 0, 1, 2, 3, 4] B=[-4, -3, -2, -1, 0, 1, 2, 3, 4] C=[0, 3, 4, 6, 7, 8, 10, 11, 14] n=10 |S|=53 A=[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5] B=[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5] C=[0, 1, 4, 5, 6, 9, 10, 11, 14, 15] n=11 |S|=58 A=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] B=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] C=[0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 19] n=12 |S|=74 A=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] B=[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] C=[0, 4, 5, 6, 9, 10, 11, 12, 15, 16, 17, 21] n=13 |S|=80 A=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] B=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] C=[0, 4, 5, 6, 9, 10, 11, 12, 15, 16, 17, 21, 22] n=14 |S|=100 A=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] B=[-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] C=[0, 1, 6, 7, 8, 12, 13, 14, 15, 19, 20, 21, 26, 27] n=15 |S|=106 A=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] B=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] C=[0, 5, 6, 7, 11, 12, 13, 14, 18, 19, 20, 21, 25, 26, 27] n=16 |S|=128 A=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8] B=[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8] C=[0, 6, 7, 8, 13, 14, 15, 16, 20, 21, 22, 23, 28, 29, 30, 36] n=17 |S|=135 A=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8] B=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8] C=[0, 6, 7, 8, 13, 14, 15, 16, 20, 21, 22, 23, 28, 29, 30, 36, 44] n=18 |S|=161 A=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] B=[-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] C=[0, 7, 8, 9, 15, 16, 17, 18, 23, 24, 25, 26, 27, 32, 33, 34, 35, 41] n=19 |S|=167 A=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] B=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] C=[0, 7, 8, 9, 15, 16, 17, 18, 23, 24, 25, 26, 27, 32, 33, 34, 35, 41, 42] n=20 |S|=197 A=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] B=[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] C=[0, 1, 8, 9, 10, 11, 17, 18, 19, 20, 21, 26, 27, 28, 29, 30, 36, 37, 38, 46] total=1411 ``` On my laptop, this used about 8 minutes and about 1.5 GiB of memory. ### How it works We assume (without any particular justification) that *A* and *B* are the obvious range of consecutive integers centered at 0 or ½, then do an A\* search for an optimal *C* given *A* and *B*. [Answer] # Axiom, score 1466 ``` )time on g(a:List INT,b:List INT,c:List INT):List INT== s:List INT:=[] for i in 1..#a repeat for j in 1..#b repeat for h in 1..#c repeat s:=cons(a.i*b.j+c.h, s) removeDuplicates(s) inc(a:List INT, b:INT):List INT== #a=0=>a i:=1; len:=#a repeat if i>len then for j in 1..len repeat a.j:=0 return a if i<len then if a.i<a.(i+1) then if a.i<b then a.i:=a.i+1 for j in 1..(i-1) repeat a.j:=0 break for j in 1..i repeat a.j:=0 else if a.i<b then a.i:=a.i+1 for j in 1..(len-1) repeat a.j:=0 break i:=i+1 a f(n:PI):List List INT== a:List INT:=[0]; b:List INT:=[0]; c :List INT:=[0] aix:List INT:=[]; cmin:List INT:=[]; cp:List INT:=[ ] s:List INT :=[ ]; c1:List INT:=[0]; smin:INT -- costruisce gli insiemi a,b i:=1 for j in 1..n-1 repeat if member?(i,a) then (a:=cons(-i,a);b:=cons(-i,b);i:=i+1) else (a:=cons( i,a);b:=cons( i,b)) if n=1 then return [a,b,c,[0],[1]] a:=sort(a) c :=copy(a); cmin:=copy(a); cp:=copy(a) for i in 1..n repeat c.i:=i-3 for i in 1..n repeat aix:=cons(0, aix) -- ottimizzati per i vari casi... si parte da particolari insiemi c -- da cui fare le variazioni if n>=8 then c.n:=c.n+2 if n=10 or n=13 then c.(n-1):=c.(n-1)+2 if n=9 or n=16 or n=19 then (c.(n-2):=c.(n-2)+1; c.(n-1):=c.(n-1)+1; c.n:=c.n+1) smin:=n*n+10 repeat for i in 1..n repeat cp.i:=c.i+aix.i k:=# g(a,b,cp) if k<smin then smin:=k; for i in 1..n repeat cmin.i:=cp.i --output ["assign",c,aix,cmin, k] inc(aix, 3) --output aix i:=0;repeat(i:=i+1;if i>n or aix.i~=0 then break) if i>n then break [sort(a),sort(b),sort(cmin),g(a,b,cmin),[smin]] h(n:PI):NNI== k:=0 r:List List INT:=[] for i in 1..n repeat r:=f(i) output [i,r.5.1,r.1,r.3] k:=k+r.5.1 k ``` The sets would be A=B=[-n/2..n/2] if n%2==0 else A=B=[-n/2..((n/2)+1)] The set C is the sum of the array as [-2,-1,..(n-2)] to one array arr[] of this kind [0,0,0,0,0] or [0,1,1,1,2] or [0,0,0,0,3] so that array it has property ``` arr[i] <= arr[i+1] for i in 1..n-1 ``` If you want to be more precise or you PC is more fast you can try to increase '3' in 'inc(aix, 3)' that increase the number of arrays for the C set variation and so it would increase the result precision. In the results the string printed is ``` [n, |{a*b+c for a in A for b in B for c in C}|,A,C] ``` where B=A and |S| is the number of element of S ``` (6) -> h 20 [1,1,[0],[0]] [2,3,[0,1],[- 2,- 1]] [3,5,[- 1,0,1],[- 2,- 1,0]] [4,10,[- 1,0,1,2],[- 2,- 1,0,1]] [5,13,[- 2,- 1,0,1,2],[- 2,- 1,0,1,2]] [6,21,[- 2,- 1,0,1,2,3],[- 2,- 1,0,1,2,3]] [7,25,[- 3,- 2,- 1,0,1,2,3],[- 2,- 1,0,1,2,3,4]] [8,35,[- 3,- 2,- 1,0,1,2,3,4],[- 2,- 1,1,2,3,5,6,9]] [9,39,[- 4,- 3,- 2,- 1,0,1,2,3,4],[- 2,1,2,4,5,6,8,9,12]] [10,53,[- 4,- 3,- 2,- 1,0,1,2,3,4,5],[- 2,- 1,2,3,4,6,7,8,11,12]] [11,59,[- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5],[- 2,- 1,0,2,3,4,5,7,8,9,12]] [12,76,[- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6],[- 2,- 1,0,3,4,5,6,8,9,10,11,14]] [13, 82, [- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6],[- 2,- 1,0,3,4,5,6,8,9,10,11,14,15]] [14, 103, [- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7],[- 2,- 1,0,3,4,5,6,7,9,10,11,12,13,16]] [15, 110, [- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7],[- 2,- 1,0,1,4,5,6,7,8,10,11,12,13,14,17]] [16, 134, [- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7,8],[- 2,- 1,0,1,4,5,6,7,8,9,11,12,13,15,16,19]] [17, 142, [- 8,- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7,8],[- 2,- 1,0,1,4,5,6,7,8,9,11,12,13,14,15,16,19]] [18, 169, [- 8,- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7,8,9],[- 2,- 1,0,1,2,3,4,6,7,8,9,10,11,12,15,16,17,20]] [19, 178, [- 9,- 8,- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7,8,9],[- 2,- 1,0,1,2,5,6,7,8,9,10,11,13,14,15,16,18,19,22]] [20, 208, [- 9,- 8,- 7,- 6,- 5,- 4,- 3,- 2,- 1,0,1,2,3,4,5,6,7,8,9,10],[- 2,- 1,0,1,2,3,4,5,7,8,9,10,11,12,13,14,17,18,19,22]] (6) 1466 Type: PositiveInteger Time: 0.03 (IN) + 910.75 (EV) + 0.02 (OT) + 24.00 (GC) = 934.80 sec ``` [Answer] ## SQL Server, 1495 ``` declare @N int=20; --set @N=40; with n as(select 1 n union all select n+1 from n where n<@N), s as(select n,n/2-n+1 m from n union all select n,m+1 from s where m<n/2), t as(select n,m,row_number()over(partition by n order by m) p from s), a as(select n,m a,p from t), b as(select n,m b,p from t), c as(select n,m c,p from t), u as( select a.n,count(distinct a*b+c) q from a,b,c where b.n=a.n and c.n=a.n group by a.n ) select u.n,a,b,c,q,sum(distinct q) N from u,a,b,c where a.n=u.n and b.n=u.n and c.n=u.n and b.p=a.p and c.p=a.p group by grouping sets((u.n,a,b,c,q),()); ``` The solution can be verified [here](http://rextester.com/WQHL68972).Excuse me for the output is in the tabular form. [Answer] # C, score ~~1448~~ 1431 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #define P printf #define R return #define F for int cmp(const void*a,const void*b) {int aa, bb; aa=*(int*)a; bb=*(int*)b; R aa>bb?1:(aa<bb?-1:0); } void show(int* a,unsigned n){unsigned i;P("[ ");F(i=0;i<n;++i) P("%d ", a[i]);P("]");} // l'insieme "a" deve essere del tipo {0,1} {-1,0,1} {-1,0,1,2} {-2,-1,0,1,2} ecc di numero elementi n // l'insieme "c" e' un insieme di numero elementi n // l'insieme a cui "r" punta sarà *r={x*y+z : x in a, y in a, z in c } // ritorna -1 per errore altrimenti il numero di elementi // di {x*y+z : x in a, y in a, z in c } int g(int**r,int*a,int*c,unsigned n) {static int *arrs,*res; static unsigned alen; unsigned i,j,k,m,v,vv,len; if(a==0||c==0||n<=0||n>128) R -1; len=n*n*n; if(alen<n) {if(arrs) free(arrs); // leaks: arrs and res remain until the program end if(res ) free(res); arrs=0; res=0; alen=0; arrs=malloc(sizeof(int)*len); if(arrs==0) R -1; res =malloc(sizeof(int)*len); if(res==0) {free(arrs); arrs=0;R -1;} alen=n; } v=0; F(k=0;k<n;++k) arrs[v++]=c[k]; // il caso 0 F(m=0;m<n&&a[m]<0;++m);// da una parte i positivi dall'altra i negativi; m punta a 0 // il caso 0 non e' trattato F(i=0;i<m;++i) // positivi per negativi F(j=m+1;j<n;++j) F(k=0;k<n;++k) if(-a[i]<=a[j]) arrs[v++]=a[i]*a[j]+c[k]; F(i=m+1;i<n;++i) // positivi per positivi F(j=i;j<n;++j) F(k=0;k<n;++k) arrs[v++]=a[i]*a[j]+c[k]; qsort(arrs,v,sizeof(int),cmp); res[0]=arrs[0]; // elimina i doppioni F(vv=1,i=1; i<v; ++i) if(arrs[i-1]!=arrs[i]) res[vv++]=arrs[i]; *r=res; R vv; } int inc(int* a,int len,int b) {int i,j; if(len<1||b<1)R 1; F(i=0;;) {if(i>=len) {F(j=0;j<len;++j)a[j]=0; R 1; } if(i==len-1||a[i]<a[i+1]) {if(a[i]<b) {a[i]+=1; F(j=0;j<i;++j)a[j]=0; break; } } i+=1; } R 0; } // a,b,c,cmin sono array e devono avere size n // s e' un array deve avere size n*n*n // come risultato la sua lunghezza e' *slen // int f(int* a,int* b,int* cmin,int* s,int* slen, int n) {int i,j,k, *c, *aix, *cp, smin, *rs; if(slen)*slen=0; if(n<1||a==0||b==0||cmin==0||s==0||slen==0)R -1; // costruisce a e b j=-n/2; if(n%2==0)++j; F(i=0;i<n;++i,++j) s[i]=cmin[i]=a[i]=b[i]=j; // {-x..x} oppure {-x..(x+1)} *slen=n; if(n==1)R 1; // caso di un solo elemento c =malloc(sizeof(int)*(n+1)); // ** if(c==0)R -1; aix=malloc(sizeof(int)*(n+1)); // ** if(aix==0){free(c);R -1;} cp =malloc(sizeof(int)*(n+1)); // ** if(cp==0){free(aix);free(c);R -1;} F(i=0;i<n;++i){cp[i]=aix[i]=0;c[i]=i;} if(n>=16)//16 {c[n-1]=c[n-1]+3;c[n-2]=c[n-2]+3;c[n-3]=c[n-3]+3;} F(smin=n*n+10;;) {cp[0]=c[0]; F(i=1;i<n;++i) cp[i]=c[i]+aix[i-1]; k=g(&rs,a,cp,n); if(k<smin){F(smin=k,i=0;i<n;++i) cmin[i]=cp[i]; //P("Assign: %d, ", k); //show(aix,n);P(","); //P("Cmin=");show(cmin,n);P("\n"); } //show(aix,n);P("\n"); if(inc(aix,n-1,7))break; } free(cp);free(aix);free(c); k=g(&rs,a,cmin,n); if(k==-1)R -1; F(i=0;i<k;++i)s[i]=rs[i]; *slen=k; R k; } unsigned h(unsigned nmax) {time_t ti, tf; double dft; int i,j, *a, *b, *cmin, *s, slen, rlen, r; unsigned n,len; if(nmax>128||nmax<1)R -1; len =nmax*nmax*nmax+1; s =malloc(sizeof(int)*len); // ** a =malloc(sizeof(int)*(nmax+1)); // ** b =malloc(sizeof(int)*(nmax+1)); // ** cmin=malloc(sizeof(int)*(nmax+1)); // ** if(s==0||a==0||b==0||cmin==0){free(s);free(a);free(b);free(cmin);R -1;} ti=time(0); F(n=1,r=0;n<=nmax;++n) {rlen=f(a,b,cmin,s,&slen,n); if(rlen!=-1) {P("%d %d", n, rlen); show(cmin,n);P("\n");} else break; r+=rlen; } tf=time(0); dft=difftime(tf, ti); P("Result=%d secondi=%.0f minuti=%.0f\n", r, dft, dft/60.0); free(s);free(a);free(b);free(cmin); R r; } int main(){h(20); R 0;} ``` It would be the same +/- algo of Axiom implementation results ``` 1 1[ 0 ] 2 3[ 0 1 ] 3 5[ 0 1 2 ] 4 10[ 0 1 2 3 ] 5 13[ 0 1 2 3 4 ] 6 21[ 0 1 2 3 4 5 ] 7 25[ 0 1 2 3 4 5 6 ] 8 35[ 0 1 3 4 5 7 8 11 ] 9 39[ 0 3 4 6 7 8 10 11 14 ] 10 53[ 0 1 4 5 6 8 9 10 13 14 ] 11 59[ 0 1 2 4 5 6 7 9 10 11 14 ] 12 75[ 0 1 2 5 6 7 8 11 12 13 17 18 ] 13 81[ 0 1 2 5 6 7 8 11 12 13 14 17 18 ] 14 101[ 0 1 2 3 6 7 8 9 10 13 14 15 16 20 ] 15 107[ 0 1 2 3 6 7 8 9 10 13 14 15 16 20 21 ] 16 130[ 0 1 2 6 7 8 9 10 13 14 15 16 17 21 22 23 ] 17 137[ 0 1 2 3 7 8 9 10 11 15 16 17 18 19 23 24 25 ] 18 163[ 0 1 2 3 7 8 9 10 11 12 16 17 18 19 20 25 26 27 ] 19 171[ 0 1 2 3 4 8 9 10 11 12 13 17 18 19 20 21 26 27 28 ] 20 202[ 0 1 2 3 7 8 9 10 11 12 13 17 18 19 20 21 22 27 28 29 ] Result=1431 secondi=618 minuti=10 ``` [Answer] # [Python 2](https://docs.python.org/2/), score 1495 ``` f=lambda n:range(-n/2+1,n/2+1) f_A=f_B=f_C=f def comb_set(A, B, C): return sorted({a*b+c for a in A for b in B for c in C}) def S(n): return comb_set(f_A(n), f_B(n), f_C(n)) ``` [Try it online!](https://tio.run/##TY8xb4QwDIVn8iusWy6UVD0YkTIAc6fr0KESCpC0SJxzCrnhWvW3U5tUVYfEz89Pn@XrPX54rLbN6cVchskA1sHgu5WP@FQVpdr/XLi@0a5v6XXaCTFZB6O/DP1qo2wUtAq6vBZZsPEWEFYfop3kl3kYihGcD2BgRmh2ObBsdzmy7L7zBDxL/Mf4w9NqGiig9b@1o5pvz80raKhOIvpoFpInIRiKDE03lAo4VUDJ4HOPlOItIlvnT0vNYlGSTcY1zBgBFRzf4lEBz0WWyIVObYocXtisDwr26fYD "Python 2 – Try It Online") A simple baseline of having each set be a length-n interval centered around 0, slightly unbalanced for even n. The TIO has Python code to compute your score. ``` 1 1 2 3 3 5 4 10 5 13 6 21 7 25 8 36 9 41 10 55 11 61 12 78 13 85 14 105 15 113 16 136 17 145 18 171 19 181 20 210 Total: 1495 ``` The size is `(n*n+1)/2` for odd n and `(n*n+n)/2` for even n. [Answer] # C++, score 1411 Conjecturing A and B are consecutive integers centered near 0, simply use simulated annealing to find C. Source: ``` #include <algorithm> #include <iostream> #include <random> #include <bitset> #include <cmath> using namespace std; using bools = bitset<270>; using irand = uniform_int_distribution<int>; ranlux48 gen; uniform_real_distribution<double> frand(0, 1); int evaluate(const bools& a, const vector<int>& v) { bools t = a; for (int i : v) t |= a << i; return t.count(); } vector<int> best; int best_score, prev_score; void transition(double Temp, int Q, const bools& a, vector<int>& now) { int rep, pos, tmp; do rep = irand(1, Q)(gen); while (find(now.begin(), now.end(), rep) != now.end()); pos = irand(0, now.size() - 1)(gen); tmp = now[pos]; now[pos] = rep; int now_score = evaluate(a, now); if (now_score <= prev_score || frand(gen) < exp((double)(prev_score - now_score))) { prev_score = now_score; if (now_score < best_score) best_score = now_score, best = now; } else now[pos] = tmp; } int main() { int score = 0; for (int N = 1; N <= 20; N++) { gen.seed(0); int first = -N / 2, last = first + N, Q = N * 3; bools st; for (int i = first; i < last; i++) for (int j = first; j < last; j++) st[i * j + last * last] = true; vector<int> lst; for (int i = 1; i < N; i++) lst.push_back(i); best = lst; prev_score = best_score = evaluate(st, lst); if (N != 1) for (double Temp = 70.; Temp > 0; Temp -= 3e-5) transition(Temp, Q, st, lst); sort(best.begin(), best.end()); cout << "N = " << N << "; |S| = " << best_score << endl; cout << " A = B = {"; for (int i = first; i < last; i++) cout << i << (i != last - 1 ? ", " : "}\n"); cout << " S = {0"; for (int i : best) cout << ", " << i; cout << "}\n"; score += best_score; } cout << "Score: " << score << endl; } ``` Results: ``` N = 1; |S| = 1 A = B = {0} S = {0} N = 2; |S| = 3 A = B = {-1, 0} S = {0, 1} N = 3; |S| = 5 A = B = {-1, 0, 1} S = {0, 1, 2} N = 4; |S| = 10 A = B = {-2, -1, 0, 1} S = {0, 1, 2, 3} N = 5; |S| = 13 A = B = {-2, -1, 0, 1, 2} S = {0, 1, 2, 3, 4} N = 6; |S| = 21 A = B = {-3, -2, -1, 0, 1, 2} S = {0, 1, 2, 3, 4, 5} N = 7; |S| = 25 A = B = {-3, -2, -1, 0, 1, 2, 3} S = {0, 1, 2, 3, 4, 5, 6} N = 8; |S| = 35 A = B = {-4, -3, -2, -1, 0, 1, 2, 3} S = {0, 3, 4, 6, 7, 10, 11, 14} N = 9; |S| = 39 A = B = {-4, -3, -2, -1, 0, 1, 2, 3, 4} S = {0, 3, 4, 6, 7, 8, 10, 11, 14} N = 10; |S| = 53 A = B = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4} S = {0, 1, 4, 5, 6, 9, 10, 11, 14, 15} N = 11; |S| = 58 A = B = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5} S = {0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 19} N = 12; |S| = 74 A = B = {-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5} S = {0, 4, 5, 6, 9, 10, 11, 12, 15, 16, 17, 21} N = 13; |S| = 80 A = B = {-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6} S = {0, 6, 10, 11, 12, 15, 16, 17, 18, 21, 22, 23, 27} N = 14; |S| = 100 A = B = {-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6} S = {0, 5, 6, 7, 11, 12, 13, 14, 18, 19, 20, 21, 25, 26} N = 15; |S| = 106 A = B = {-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7} S = {0, 5, 6, 7, 11, 12, 13, 14, 18, 19, 20, 21, 25, 26, 32} N = 16; |S| = 128 A = B = {-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7} S = {0, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 37} N = 17; |S| = 135 A = B = {-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8} S = {0, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 37, 45} N = 18; |S| = 161 A = B = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8} S = {0, 7, 8, 9, 14, 15, 16, 17, 18, 22, 23, 24, 25, 26, 31, 32, 33, 40} N = 19; |S| = 167 A = B = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9} S = {0, 7, 8, 9, 15, 16, 17, 18, 23, 24, 25, 26, 27, 32, 33, 34, 35, 41, 42} N = 20; |S| = 197 A = B = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9} S = {0, 8, 9, 10, 16, 17, 18, 19, 20, 25, 26, 27, 28, 29, 35, 36, 37, 38, 45, 46} Score: 1411 ``` With -O2 on my computer, it takes 50 secs to compute all the results. [Answer] # Mathematica, score 1495 ``` z = 0; For[n = 1, n <= 20, n++, r = Range[n] - Ceiling[n/2]; Print["S_n size=", x = (s = Length@#; Length@ Union@Flatten@ Table[#[[i]]*#[[j]] + #[[k]], {i, s}, {j, s}, {k, s}]) &[r], " ", "A=B=C=", r]; z = z + x] Print["SCORE=", z] ``` > > S\_n size=1 A=B=C={0} > > S\_n size=3 A=B=C={0,1} > > S\_n size=5 A=B=C={-1,0,1} > > S\_n size=10 A=B=C={-1,0,1,2} > > S\_n size=13 A=B=C={-2,-1,0,1,2} > > S\_n size=21 A=B=C={-2,-1,0,1,2,3} > > S\_n size=25 A=B=C={-3,-2,-1,0,1,2,3} > > S\_n size=36 A=B=C={-3,-2,-1,0,1,2,3,4} > > S\_n size=41 A=B=C={-4,-3,-2,-1,0,1,2,3,4} > > S\_n size=55 A=B=C={-4,-3,-2,-1,0,1,2,3,4,5} > > S\_n size=61 A=B=C={-5,-4,-3,-2,-1,0,1,2,3,4,5} > > S\_n size=78 A=B=C={-5,-4,-3,-2,-1,0,1,2,3,4,5,6} > > S\_n size=85 A=B=C={-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6} > > S\_n size=105 A=B=C={-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7} > > S\_n size=113 A=B=C={-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7} > > S\_n size=136 A=B=C={-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8} > > S\_n size=145 A=B=C={-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8} > > S\_n size=171 A=B=C={-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9} > > S\_n size=181 A=B=C={-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9} > > S\_n size=210 A=B=C={-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10} > > SCORE=1495 > > > ]
[Question] [ In [Twitch Plays Pokémon](https://en.wikipedia.org/wiki/Twitch_Plays_Pok%C3%A9mon), one of the most annoying obstacles one can face is an ice puzzle, where you must travel from one place to another by sliding all the way in one direction until you either hit a wall or a boulder. Your task is to build a program that will generate a random difficult ice puzzle. Your program will accept three numbers, `M`, `N`, and `P`, as input (with `10 <= M <= 30`, `15 <= N <= 40`, and `0 <= P < 65536`): ``` 12 18 ``` and will output: * An `M` by `N` grid consisting of `.` and `O`, representing ice and a boulder respectively. * A position marker representing where the puzzle is entered from. This position marker consists of a letter `L`, `R`, `T`, or `B`, representing left, right, top, and bottom, followed by a number representing the position (from the left or top) on that side to be entered from. * A similar position marker representing where the puzzle is exited out of. * **The shortest solution to the puzzle, consisting of a sequence of `L`, `R`, `U`, and `D` respectively.** Example output: ``` ..O...O........... ............O..... ..O............... .......O.......... .................. ...........O...... O..O...........O.. ..........O....... ..O..........O.... ........O......... O....O.........O.. ............O..... R 4 B 5 LDLDRULD (Note that this output is actually invalid because it is not actually long enough.) ``` For an input `M` and `N`, the solution to the puzzle must have at least `min(M, N)` steps and move at least `2 (M + N)` total spaces. (For reference, the above puzzle moves a total of 12 steps, moving 69 spaces.) Your puzzle generator must generate a different `M` by `N` puzzle with a different solution path (i.e. a different sequence of steps for each solution) for each seed `P`. * Note that the requirement of a different solution path is to avoid solutions that try to systematically generate rock paths, like [Claudiu's solution here](https://codegolf.stackexchange.com/a/23688/7110). If there are two or three pairs of identical solutions due to quirks in randomness, that will be okay, as long as the program is not *intentionally* trying to systematically generate puzzles with the same sequence of moves. The shortest code to do the above wins. [Answer] # Python, ~~672~~ 548 characters, more interesting puzzles Although going strictly by the rules, my other Python program beats this one, I decided to write one that would generate more interesting puzzles anyway. Here it is: ``` R=range;import random as J;X=J.randint x=(0,1,-1,0);y=x[2:]+x g=lambda r,c:(0<=r<H)+(0<=c<W)>1and f[r][c]or x[(r,c)in(A,E)] l=lambda r,c:g(r+y[d],c+x[d])<1and(r,c)or l(r+y[d],c+x[d]) H,W,P=input();J.seed(P) while 1: A=(-1,X(0,W));E=(H,X(0,W));f=[[X(0,7)for _ in R(W)]for _ in R(H)] q=[(A,'')];n=z={} while q and n!=E: n,O=q.pop() for d in R(4): N=l(*n) if g(n[0]+y[d],n[1]+x[d])and N not in z:q[:0]=[(N,O+"URLD"[d])];z[N]=1 if(n==E)*len(O)>min(H,W):print"\n".join(''.join('O.'[c>0]for c in T)for T in f),"\nT",A[1],"\nB",E[1],"\n",O;break ``` Indentation levels are space, tab, tab+space. **Samples**: ``` $ echo [10,15,0] | python ice2.py .....OO........ ............... ...O....O.OO..O ...........O... ..O....O....... .......O....O.. ....O.......... .............O. ..............O ............... T 1 B 10 DLURDRURULDRD ``` It uses `P` as a seed, so each `P` will generate the same puzzle, and each different `P` is exceedingly likely to be different: ``` $ echo [10,15,1] | python ice2.py .OOO.O......... ...O......O.O.O .......O....... ..O..........OO .....O......... .............O. .O............. .O............O O....O......... ......O........ T 14 B 8 DLDRDLURULD ``` It works reasonably fast up to sizes of `M=25,N=40` but past that it gets really slow. It should theoretically work for `M=30, N=40` if you let it run long enough. I've manually written in the trail here since it is hard to follow - the program just outputs the puzzle. ``` $ echo [25,40,0] | python ice2.py * ...................dO....urrrO..O..O.... ....O.....O........dO....u..dO.......... ..........O.....O..d....Ou.Odrrrrrrrrrrr ...........O.......d.O..Ou..O.....OOllld .O....O.OO.........drrrrrrO....Olllud..O O......O...O.O.....O............dO.ud... O........OO..........O.........Od..ud..O .........O......................d..ud... ....O.....O.O....O.....O........d..ud.O. .....O..O...................O...d..udO.. .........O.........O..O.........d..ud... .......O.O...O..O.OO....O...OOlldOOld... ........Olllllllllu....OO.OO..dOO...O... .O.O....Od........u......O....d..O...O.. ..O....O.d........u..O........d..O..O... ....O....d..O.....uO.....O....d......... .........d........u...........d......... .........d....O...u.O..O.....Od.O....... ........Od...O....u...........d......... .O.....OuxrrrrO...u...OOOO..O.d......... ........udO..dO.O.u...........d......... O..O.O..ud...d..urrO..........d.O...O... ........ud...d..u.O.O........Od..O...O.. ..OO....ud..Od..u......OllllludO.....O.. ..O....OldO..dOOlllllllld...Old...O..O.. * T 19 B 13 DRURDRDLDLULDLDLULDLURULDLURD ``` **Explanation**: The program loops, generating a random start position on the top, a random end position on the bottom, and a random grid with a `12.5%` chance for a boulder on any given spot. It then solves the puzzle with a breadth-first-search and if the solution exists and is bigger than `min(H,W)`, it prints and exits. [Answer] # Python, ~~235~~ ~~206~~ ~~185~~ 176 characters ``` H,W,P=input() t='' for x in range(16):t+=".O"[(P>>x)%2] for n in[t[1:],t[0],"O","...O"]+["."]*(H-5)+[".O.."]:print(n*W)[:W] print"B 1\nR",(H,3)[-W%4/2],"\n",("URDR"*W)[:W+W%2] ``` **Usage**: Input is through stdin of the form `[M, N, P]`. ``` $ echo [14, 17, 2] | python ice.py O..............O. ................. OOOOOOOOOOOOOOOOO ...O...O...O...O. ................. ................. ................. ................. ................. ................. ................. ................. ................. .O...O...O...O... B 1 R 3 URDRURDRURDRURDRUR ``` You said the maps had to be different for each seed `P`... and they are: ``` $ echo [14, 17, 233] | python ice.py ..O.OOO.......... OOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOO ...O...O...O...O. ................. ................. ................. ................. ................. ................. ................. ................. ................. .O...O...O...O... B 1 R 3 URDRURDRURDRURDRUR $ echo [14, 17, 65133] | python ice.py .OO.OO..OOOOOOO.O OOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOO ...O...O...O...O. ................. ................. ................. ................. ................. ................. ................. ................. ................. .O...O...O...O... B 1 R 3 URDRURDRURDRURDRUR ``` And an example w/ a different size: ``` $ echo [10, 15, 65133] | python ice.py .OO.OO..OOOOOOO OOOOOOOOOOOOOOO OOOOOOOOOOOOOOO ...O...O...O... ............... ............... ............... ............... ............... .O...O...O...O. B 1 R 10 URDRURDRURDRURDR ``` Satisfies all the supplied objective criteria: * Each `P` leads to a different puzzle * There is only one solution, thus it is the shortest * The solution takes `N + N%2` steps, which is at least `N` * The solution always takes more than `2 (M + N)` total spaces --- **Explanation**: Each row is constructed by repeating a certain string element `W` times and limiting the length to `W` (I use `H` and `W` instead of `M` and `N`). The first two rows depend on `P` to make each puzzle unique. Basically, note that `P` fits into a 16-bit unsigned integer. I convert `P` to binary, using `.` for 0 and `O` for 1: ``` t='' for x in range(16):t+=".O"[(P>>x)%2] ``` The first row element is the last 15 bits, `t[1:]`, while the second row element is the 1st bit, `t[0]`. I couldn't put it all on one row because the minimum width is 15, which wouldn't fit all 16 bits if `P` > 32767. Thus the first two rows uniquely represent each of the possible values of `P`. The third row is a full wall so that the value of `P` doesn't affect the solution. Then follow the actual maze elements. This line prints them all, repeating them up to the cap. The result is as you see above: ``` for n in[t[1:],t[0],"O","O..."]+["."]*(H-5)+["..O."]:print(n*W)[:W] ``` The rest was just figuring out how to solve the dynamically generated maze. This depends only on the width of the maze. I noted that the solutions, for a given width, were: ``` W | solution -----+--------- 1 | UR 2 | UR 3 | UR DR 4 | UR DR 5 | UR DR UR 6 | UR DR UR 7 | UR DR UR DR 8 | UR DR UR DR ``` etc. Hence it's just `URDR` repeated and cut off at the right place, `W+W%2`. ``` print"B 1\nR",(H,3,3,H)[W%4],"\n",("URDR"*W)[:W+W%2] ``` [Answer] ## Java - 2632 While I admire the technical purity of [Claudiu's answer](https://codegolf.stackexchange.com/a/23688/14215), I decided to try my hand at making *slightly* more difficult puzzles ;) **Basic steps (pretty simple):** ``` Randomize entry location Step forward For min(m,n)-1 steps: Rotate left or right Slide until I hit something or go a random distance Place a rock in front of stopping location If I can slide straight to any wall: Slide to exit Else Create another step and try again If at any step I get trapped, start over If BFS finds shorter path, start over ``` I also mark each spot as 'nogo' as I'm sliding. If I end up on a nogo spot(or right in front of one which would mean a rock was going there), it's an invalid step. So, basically the idea is to randomly generate a *lot* of maps, and keep the first one that is valid. I plan to make this smarter(backtracking, etc), but it works fine right now. It might also cut down on some redundant code, we'll see. As it is, it generates small maps(15x10) almost instantly, medium(30x20) maps in a couple seconds, and large(40x30) in some random amount of time between 20 seconds and 20 minutes, depending on seed. It tests between 300k-500k maps/second on my machine, depending on size. Side note: Sometimes the maps aren't *too* hard, simply because there are only as many rocks as steps, and unless the step takes you to a wall, most times there's only one option if you want to hit an actual rock. I'll fix that later by placing "random" rocks in safe spots after all the steps are drawn. Since nogo spots are already marked, that should be pretty simple. For now, just enjoy these examples: **Output showing different sizes/seeds:** ``` $ java I 30 20 6851 $ java I 15 10 1 $ java I 15 10 65513 ............................O. .......O....... ....O.......... .............................. ............... ............... .............................. .........O..... .........O..... ..........O......O............ .............O. ..............O ...............O...........O.. ............... ............... .............................. .......O....... .....O.O....... .............................. O.............. ............... ........................O..... ............... ..........O.... .............................. ............... O.............. ...O.......................O.. ......O........ ............... O...............O.OO.......... ..............O..........O.... ...........O.................. T 14 R 6 ....O......................... T 7 T 14 .............................. DLDLULURU LULDLDRURU .............................. .............................. .................O............ .O............................ .............................. B 28 R 9 ULURDLDLDRURDLDRURUR ``` **Max size 40x30:** ``` $ java I 40 30 2 ........................................ ........................................ ........................................ ........................................ ................O....................... ..........O............................. ........................................ .......O................................ .....................O..........O....... ......................O................. .................................O...... ......................................O. ........................................ ........................................ ..............................O......... ...........O............................ ........................................ .......................................O .........O...................O.......... ....................O................... ...............................O........ ............O..O......................O. ......O...........O..................... ..................O....O................ ..................................O..... ........................................ ..............................O......... .....................................O.. ...........O............................ ...................O.................... B 19 B 11 URURDLULULDRDRDLULDLDLULURDLD ``` **Golfed:** ``` import java.util.*;import java.awt.*;class I{int m,n,p,g,a[][],b[][];Random r;Point s,e,c;ArrayList<Integer>z;void Q(String q,int l){if(l>0)System.out.println(q);else System.out.print(q);}void G(String[]y){m=Integer.valueOf(y[0]);n=Integer.valueOf(y[1]);p=Integer.valueOf(y[2]);r=new Random(p);Q("",1);int o=0,i,j,u=0;char t,f[]={85,76,68,82};while(o<3){if(++u%20000==0)Q("\r#"+u,0);a=new int[m+2][n+2];b=new int[m+2][n+2];for(i=0;i<m+2;i++)for(j=0;j<n+2;j++)if(i==0||i==m+1||j==0||j==n+1)a[i][j]=2;s=new Point();int e=r.nextInt(m*2+n*2);if(e<m*2){s.x=e%m+1;s.y=e<m?0:n+1;}else{s.y=(e-m*2)%n+1;s.x=(e-m*2)<n?0:m+1;}if(s.x<1)g=3;else if(s.x>m)g=1;else if(s.y<1)g=2;else if(s.y>n)g=0;a[s.x][s.y]=0;c=new Point(s);z=new ArrayList<Integer>();z.add(g);for(i=0;i++<Math.min(m,n)-1;)if(N()<1&&N()<1)break;o=((z.size()>=Math.min(m,n)-1)?1:0)+F()+((V()==z.size())?1:0);}Q("\r",0);for(j=1;j<n+1;j++){for(i=1;i<m+1;i++)Q(String.valueOf(a[i][j]>0?'O':'.'),0);Q("",1);}Q("\n\n",0);if(s.x<1||s.x>m){t=s.x<1?'L':'R';u=s.y;}else{t=s.y<1?'T':'B';u=s.x;}Q(t+" "+u,1);if(e.x<1||e.x>m){t=e.x<1?'L':'R';u=e.y;}else{t=e.y<1?'T':'B';u=e.x;}Q(t+" "+u,1);for(i=0;i<z.size();)Q(String.valueOf(f[z.get(i++)]),0);Q("",1);}public static void main(String[]a){new I().G(a);}int F(){int c=0;while(C()<1&&c++<10)if(N()<1)return 0;return e==null?0:1;}int C(){int d=g<2?-1:1;if(g%2<1){int y=c.y;while(y>0&&y<n+1){y+=d;if(a[c.x][y]==1)return 0;}e=new Point(c.x,y);}else{int x=c.x;while(x>0&&x<m+1){x+=d;if(a[x][c.y]==1)return 0;}e=new Point(x,c.y);}a[e.x][e.y]=0;return 1;}int V(){if((s.x-e.x)+(s.y-e.y)<2)return 0;Queue<Point>q=new ArrayDeque<Point>();Queue<Integer>d=new ArrayDeque<Integer>();a[s.x][s.y]=-2;q.add(s);d.add(0);while(q.size()>0){Point t=q.poll();int h=d.poll(),i=0;if(t.equals(e))return h;for(;i<4;i++){Point n=S(a,t,i<2?0:1,i%2<1?-1:1,99,1);if(a[n.x][n.y]==-2)continue;a[n.x][n.y]=-2;q.add(n);d.add(h+1);}}return 0;}int N(){Point q;int d=g<2?-1:1,x,y;System.arraycopy(a,0,b,0,a.length);q=S(b,c,g,d,r.nextInt((g%2<1?n:m)/2)+2,0);if(q.x<1||q.y<1||q.x>m||q.y>n||q.equals(c)||b[q.x][q.y]!=0)return 0;x=q.x;y=q.y;if(g%2<1)y+=d;else x+=d;if(b[x][y]<0)return 0;b[q.x][q.y]=-1;b[x][y]=1;int f=r.nextInt(2)<1?-1:1;g=g%2<1?(f<0?1:3):(g=f<0?0:2);c=q;System.arraycopy(b,0,a,0,a.length);z.add(g);return 1;}Point S(int[][]u,Point f,int w,int d,int q,int s){int i=1,x=f.x,y=f.y;for(;i<=q;i++){if(w%2<1)y=f.y+i*d;else x=f.x+i*d;if(e!=null&&e.x==x&&e.y==y)return e;if(y<0||y>n+1||x<0||x>m+1)return f;if(s<1&&u[x][y]<1)u[x][y]=-1;if(u[x][y]>0){if(w%2<1)y-=d;else x-=d;return new Point(x,y);}}if(w%2<1)return new Point(f.x,f.y+i*d);else return new Point(f.x+i*d,f.y);}} ``` **With line breaks:** ``` import java.util.*; import java.awt.*; class I{ int m,n,p,g,a[][],b[][]; Random r; Point s,e,c; ArrayList<Integer>z; void Q(String q,int l){if(l>0)System.out.println(q);else System.out.print(q);} void G(String[]y){ m=Integer.valueOf(y[0]); n=Integer.valueOf(y[1]); p=Integer.valueOf(y[2]); r=new Random(p); Q("",1); int o=0,i,j,u=0; char t,f[]={85,76,68,82}; while(o<3){ if(++u%20000==0) Q("\r#"+u,0); a=new int[m+2][n+2]; b=new int[m+2][n+2]; for(i=0;i<m+2;i++) for(j=0;j<n+2;j++) if(i==0||i==m+1||j==0||j==n+1) a[i][j]=2; s=new Point(); int e=r.nextInt(m*2+n*2); if(e<m*2){ s.x=e%m+1; s.y=e<m?0:n+1; }else{ s.y=(e-m*2)%n+1; s.x=(e-m*2)<n?0:m+1; } if(s.x<1)g=3; else if(s.x>m)g=1; else if(s.y<1)g=2; else if(s.y>n)g=0; a[s.x][s.y]=0; c=new Point(s); z=new ArrayList<Integer>(); z.add(g); for(i=0;i++<Math.min(m,n)-1;) if(N()<1&&N()<1) break; o=((z.size()>=Math.min(m,n)-1)?1:0)+F()+((V()==z.size())?1:0); } Q("\r",0); for(j=1;j<n+1;j++){ for(i=1;i<m+1;i++) Q(String.valueOf(a[i][j]>0?'O':'.'),0); Q("",1); } Q("\n\n",0); if(s.x<1||s.x>m){ t=s.x<1?'L':'R'; u=s.y; }else{ t=s.y<1?'T':'B'; u=s.x; } Q(t+" "+u,1); if(e.x<1||e.x>m){ t=e.x<1?'L':'R'; u=e.y; } else { t=e.y<1?'T':'B'; u=e.x; } Q(t+" "+u,1); for(i=0;i<z.size();) Q(String.valueOf(f[z.get(i++)]),0); Q("",1); } public static void main(String[]a){ new I().G(a); } int F(){ int c=0; while(C()<1&&c++<10) if(N()<1) return 0; return e==null?0:1; } int C(){ int d=g<2?-1:1; if(g%2<1){ int y=c.y; while(y>0&&y<n+1){ y+=d; if(a[c.x][y]==1) return 0; } e=new Point(c.x,y); }else{ int x=c.x; while(x>0&&x<m+1){ x+=d; if(a[x][c.y]==1) return 0; } e=new Point(x,c.y); } a[e.x][e.y]=0; return 1; } int V(){ if((s.x-e.x)+(s.y-e.y)<2) return 0; Queue<Point>q=new ArrayDeque<Point>(); Queue<Integer>d=new ArrayDeque<Integer>(); a[s.x][s.y]=-2; q.add(s); d.add(0); while(q.size()>0){ Point t=q.poll(); int h=d.poll(),i=0; if(t.equals(e)) return h; for(;i<4;i++){ Point n=S(a,t,i<2?0:1,i%2<1?-1:1,99,1); if(a[n.x][n.y]==-2) continue; a[n.x][n.y]=-2; q.add(n);d.add(h+1); } } return 0; } int N(){ Point q; int d=g<2?-1:1,x,y; System.arraycopy(a,0,b,0,a.length); q=S(b,c,g,d,r.nextInt((g%2<1?n:m)/2)+2,0); if(q.x<1||q.y<1||q.x>m||q.y>n||q.equals(c)||b[q.x][q.y]!=0) return 0; x=q.x; y=q.y; if(g%2<1) y+=d; else x+=d; if(b[x][y]<0) return 0; b[q.x][q.y]=-1; b[x][y]=1; int f=r.nextInt(2)<1?-1:1; g=g%2<1?(f<0?1:3):(g=f<0?0:2); c=q; System.arraycopy(b,0,a,0,a.length); z.add(g); return 1; } Point S(int[][]u,Point f,int w,int d,int q,int s){ int i=1,x=f.x,y=f.y; for(;i<=q;i++){ if(w%2<1) y=f.y+i*d; else x=f.x+i*d; if(e!=null&&e.x==x&&e.y==y) return e; if(y<0||y>n+1||x<0||x>m+1) return f; if(s<1&&u[x][y]<1) u[x][y]=-1; if(u[x][y]>0){ if(w%2<1) y-=d; else x-=d; return new Point(x,y); } } if(w%2<1) return new Point(f.x,f.y+i*d); else return new Point(f.x+i*d,f.y); } } ``` ]
[Question] [ This is an "arrow maze": ``` v < > v > ^ > v ^ < * ``` The `*` marks the spot where you will finish. Your goal is to find where the maze **starts** (hence, reverse maze). In this case, it's the first `>` on the second line. ``` v------< S-+---v | | >--^ >-+-------v ^ < * ``` Note that all arrows must be used. Also note that you can assume the lines will be padded with spaces to equal length. Your program must input the maze in any reasonable way (stdin, from a file, message box, etc.), however the maze **must** be completely intact. For example, you can't input the lines separated by commas; the input must be exactly the maze. You must output the start of the maze in any reasonable way. For example, you could * output the coordinates of the start * output the entire maze with the start arrow replaced with an `S` * output the entire maze with all arrows except the start arrow removed (whitespace intact!) * etc. As long as you can tell by your output which arrow is the start arrow, then it's okay. For example, an output of ``` "0" "2" ``` is alright, regardless of the newlines and quotes, because you can still tell where the start was. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. [Answer] ## GolfScript (101 100 bytes) ``` n/:g,,{:&g=:r,,{&1$r='^v<>*'?70429 3base 2/=++}/}%{,4=},.{2<}%:&\{2/~\{[~2$~@+(@@+(\]&1$?)!}do\;}%^` ``` Output is in the form `[[x y]]` where the co-ordinates are both 0-based. [Online demo](http://golfscript.apphb.com/?c=OycgIHYgICAgICA8IAo%2BICAgICB2ICAgIAogICAgICA%2BICBeIAo%2BICAgICAgICAgdgpeIDwgICAgICAgKicKCm4vOmcsLHs6Jmc9OnIsLHsmMSRyPSdedjw%2BKic%2FNzA0MjkgM2Jhc2UgMi89Kyt9L30leyw0PX0sLnsyPH0lOiZcezIvflx7W34yJH5AKyhAQCsoXF0mMSQ%2FKSF9ZG9cO30lXmA%3D) Processing is in two phases: the first phase turns the maze into an array of `[x y dx dy]` tuples; the second phase maps each arrow / asterisk to the arrow / asterisk it points to. (Asterisks are considered to point to themselves). By the definition of the problem, there is exactly one arrow which isn't in the result of this map, and that is the solution. [Answer] # GolfScript, 55 bytes ``` :&,,{&=42>},.{.&="><^v"?[1-1&n?~.~)]=:d;{d+.&=32=}do}%- ``` [Online demo](http://golfscript.apphb.com/?c=IyBDYW5uZWQgdGVzdCBpbnB1dDoKOycgIHYgICAgICA8IAo%2BICAgICB2ICAgIAogICAgICA%2BICBeIAo%2BICAgICAgICAgdgpeIDwgICAgICAgKicKCiMgUHJvZ3JhbToKOiYsLHsmPTQyPn0sLnsuJj0iPjxediI%2FWzEtMSZuP34ufildPTpkO3tkKy4mPTMyPX1kb30lLQ%3D%3D) Assumes that all input lines are padded with spaces to the same length and separated by newlines. Outputs the byte offset of the starting arrow from the start of the input string (e.g. `12` for the example maze in the challenge). Specifically, this program finds the byte offsets of all arrows that have no other arrow pointing to them (assuming that all arrows do point to an arrow or a goal; strange behavior may occur if this is not true). By default, if there are several such arrows (which, per spec, should not be possible in valid input), their offsets will simply be concatenated in the output. If you want, you can append `n*` to the program to have them separated by newlines instead. De-golfed version with comments: ``` :& # save a copy of the input string in the variable "&" ,, { &= 42> }, # make a list of the byte offsets of all arrows . # duplicate the list and apply the following loop to it: { . # make a copy of the original offset... &= # ...and get the corresponding character in the input "><^v" ? # map the arrow character to integers 0 to 3, and... [ 1 -1 &n?~ .~) ]= # ...map these to +1, -1, -len-1 or +len+1, where len is the... :d; # ...length of the first input line, and save result as "d" { d+ . &= 32= } do # add d to the byte offset until another non-space is found } % - # subtract the resulting list of target offsets from the # original list of arrow offsets; this should leave exactly # one offset, which is left on the stack for output ``` [Answer] # Mathematica ~~491~~ 323 **Ungolfed** with comments The procedure begins from the finish ("\*"), finds the arrow that points to it, and so forth until reaching the start. The function, f[maze]. ``` (* positions of the arrowheads *) aHeads[a_]:=Position[m,#]&/@{"^","v",">","<"} (* position of the final labyrinth exit*) final[a_]:=Position[a,"*"][[1]]; (* find arrowheads that point to the current location at {r,c} *) aboveMe[{r_,c_},a_]:=Cases[aHeads[a][[2]],{r1_,c}/;r1<r] belowMe[{r_,c_},a_]:=Cases[aHeads[a][[1]],{r1_,c}/;r1>r] rightOfMe[{r_,c_},a_]:=Cases[aHeads[a][[4]],{r,c1_}/;c1>c] leftOfMe[{r_,c_},a_]:=Cases[aHeads[a][[3]],{r,c1_}/;c1<c] (*find the precursor arrowhead*) precursor[{loc_,a_,list_:{}}]:= (* end the search when the precursor has already been traversed or when there is no precursor *) Which[MemberQ[list,loc],list, loc=={},list,True, (* otherwise find the next precursor *) ``` precursor[{Flatten[{aboveMe[loc,a],belowMe[loc,a],rightOfMe[loc,a],leftOfMe[loc,a]},2],a, Prepend[list,loc]}]] ``` (* return the path through the maze from start to finish *) f[maze_]:= precursor[{final[maze[[1]]],maze[[1]]}] ``` --- **Golfed** ``` f@z_:=Module[{p,h,m=z[[1]]},h@a_:=Position[a,#]&/@{"^","v",">","<","*"}; p[{v_,a_,j_:{}}]:=Module[{r,c,x=Cases},{r,c}=v; Which[MemberQ[j,v],j,v=={},j,True, p[{Flatten[{x[h[a][[2]],{r1_,c}/;r1<r],x[h[a][[1]],{r1_,c}/;r1>r], x[h[a][[4]],{r,c1_}/;c1>c],x[h[a][[3]],{r,c1_}/;c1<c]},2],a,Prepend[j,v]}]]]; p[{Position[m,"*"][[1]],m}]] ``` ## Example The maze. Each ordered pair contains the row and column of a cell. E.g. {2, 3} denotes the cell at row 2, column 3. ``` maze=Grid[Normal@ SparseArray[{{5, 5} -> "*",{1, 2} -> "v", {1, 5} -> "<",{2, 1} -> ">", {2, 3} -> "v",{3, 3} -> ">", {3, 5} -> "^",{4, 1} -> ">", {4, 5} -> "v",{5, 1} -> "^", {5, 2} -> "<",{_, _} -> " "}]] ``` ![maze](https://i.stack.imgur.com/DrxhZ.png) --- **Input** ``` f[maze] ``` --- **Output**: The path from start to finish. > > {{2, 1}, {2, 3}, {3, 3}, {3, 5}, {1, 5}, {1, 2}, {5, 2}, {5, 1}, {4, > 1}, {4, 5}, {5, 5}} > > > [Answer] I think I found a good way to solve this, but I happened to suck at golfing it. I guess this could be WAY shorter, so I'm going to explain my idea so others can use it if they find it good. **If every arrow must be used, then all the arrows will be pointed by another arrow, except one, that is our solution.** This means we don't actually have to play the maze backwards, but, starting from the upper-left one, we just need to check the nearest pointable arrow for each one. This is a real painsaver for larger mazes (since you don't have to check all four directions, but just one). Here's my solution: # PHP, 622 bytes ``` $h=fopen("a.txt","r");$b=0;while(($z=fgets($h))!==false){$l[$b]=str_split($z,1);$b++;}$v=array("^","<","v",">");$s=array();for($i=0;$i<count($l);$i++){for($j=0;$j<count($l[0]);$j++){if(in_array($l[$i][$j],$v)){switch($l[$i][$j]){case"^":$c=$i-1;while($l[$c][$j]==" ")$c--;$s[]=$c.",".$j;break;case"v":$c=$i+1;while($l[$c][$j]==" ")$c++;$s[]=$c.",".$j;break;case"<":$c=$j-1;while($l[$i][$c]==" ")$c--;$s[]=$i.",".$c;break;case">":$c=$j+1;while($l[$i][$c]==" ")$c++;$s[]=$i.",".$c;break;}}}}for($i=0;$i<count($l);$i++){for($j=0;$j<count($l[0]);$j++){if(in_array($l[$i][$j],$v)){if(!in_array($i.",".$j,$s)){echo$i.",".$j;}}}} ``` **Ungolfed:** ``` $h=fopen("a.txt","r"); $b=0; while(($z=fgets($h))!==false) { $l[$b]=str_split($z,1); $b++; } //Input ends here $v = array("^","<","v",">"); $s = array(); //Here i check every arrow, and save every pointed one in $s for($i=0;$i<count($l);$i++){ for($j=0;$j<count($l[0]);$j++){ if(in_array($l[$i][$j],$v)){ switch($l[$i][$j]) { case "^": $c=$i-1; while ($l[$c][$j]==" ") $c--; $s[]=$c.",".$j; break; case "v": $c=$i+1; while ($l[$c][$j]==" ") $c++; $s[]=$c.",".$j; break; case "<": $c=$j-1; while ($l[$i][$c]==" ") $c--; $s[]=$i.",".$c; break; case">": $c=$j+1; while ($l[$i][$c]==" ") $c++; $s[]=$i.",".$c; break; } } } } //I check if the arrow is in $s. If not, we have a solution. for($i=0;$i<count($l);$i++){ for($j=0;$j<count($l[0]);$j++){ if (in_array($l[$i][$j],$v)){ if (!in_array($i.",".$j,$s)){ echo$i.",".$j; } } } } ``` [Answer] **PHP** - 492 bytes ``` $r=split("\n",$m);$h=count($r);foreach($r as &$k)$k=str_split($k);$l=count($r[0]);$e=strpos($m,"*")+1-$h;$a=$x=$e%$l;$b=$y=floor(($e-$x)/$l);do{$c=0;for(;--$a>=0;){if($r[$b][$a]==">"){$x=$a;$c++;}if($r[$b][$a]!=" ")break;}$a=$x;for(;--$b>=0;){if($r[$b][$a]=="v"){$y=$b;$c++;}if($r[$b][$a]!=" ")break;}$b=$y;for(;++$a<$l;){if($r[$b][$a]=="<"){$x=$a;$c++;}if($r[$b][$a]!=" ")break;}$a=$x;for(;++$b<$h;){if($r[$b][$a]=="^"){$y=$b;$c++;}if($r[$b][$a]!=" ")break;}$b=$y;}while($c>0);echo "$x-$y"; ``` This solution supposes that the map can be found in local variable `$m`. The shortest method I have for passing that is via `$_GET`: `$m=$_GET['m'];` at 14 bytes. An ungolfed version with map in variable is provided below for clarity of reading. ``` $m=<<<EOT v < > v > ^ > v ^ < * EOT; $r=split("\n",$m); $h=count($r); foreach($r as &$k) $k=str_split($k); $l=count($r[0]); $e=strpos($m,"*")+1-$h; $a=$x=$e%$l; $b=$y=floor(($e-$x)/$l); do{ $c=0; for(;--$a>=0;) { if($r[$b][$a]==">"){$x=$a;$c++;} if($r[$b][$a]!=" ")break; } $a=$x; for(;--$b>=0;) { if($r[$b][$a]=="v") { $y=$b; $c++; } if($r[$b][$a]!=" ")break; } $b=$y; for(;++$a<$l;) { if($r[$b][$a]=="<") { $x=$a; $c++; } if($r[$b][$a]!=" ")break; } $a=$x; for(;++$b<$h;) { if($r[$b][$a]=="^") { $y=$b; $c++; } if($r[$b][$a]!=" ")break; } $b=$y; }while($c>0); echo "$x-$y"; ``` [Answer] # K, 281 277 258 ``` {{$[&/x in*:'{{~"*"=x 1}{(s;k . s;k;s:*1_w@&(k ./:w:{{x@&x in y}[(*:'{(x[1]@x 0;x 1)}\[x;(z;y)]);i]}[(h!b,b,a,a:#k:x 2)m;(h!(0 1+;0 -1+;1 0+;-1 0+))m:x 1;x 0])in"*",h:"><v^")}\(x;y;z;x)}[*x;y .*x;y];*x;.z.s[1_x]y]}[i@&~(x ./:i::,/(!#x),/:\:!b::#*x)in" *";x]} ``` Here's an earlier, ungolfed version ``` solve:{[x] //j - indices of all possible starting points //i - every index j::i@&~(x ./:i::,/(!a:#x),/:\:!b:#*x) in " *"; h::">v<^"; //d - dictionary mapping each directional character to // increment/decerement it needs to apply to the x/y axis d::h!((::;1+);(1+;::);(::;-1+);(-1+;::)); //e - dictionary mapping each directional character to // the maximum number of moves it should make in a // given direction e::h!b,a,b,a; //f - function to produce the indices of each point that is // passed once we move in a certain direction from a // certain index f::{{x@&x in y}[(last'{(x[0];x[0]@'x 1)}\[x;(y;z)]);i]}; //g - function that, given a starting and a direction, // moves in that direction until hitting another directional // character. It then moves in the new direction etc. until // it reaches the end point -- * g::{[x;y;z] {[x] q:x 0;m:x 1; k:x 2; w:f[e m;d m;q]; s:*1_w@&(k ./:w)in h,"*"; m:k . s; (s;m;k;s)}\[{~"*"=x 1};(x;y;z;x)]}; // recursive function that starts at the first possible starting point // and plots its way to the end. If all other potential starting points // have been touched in this path, then this is the correct starting point. // else, recursively call the function with the next possible starting point :{$[min "b"$j in last'g[*x;y . *x;y];*x;.z.s[1_x;y]]}[j;x] } ``` Returns the starting point as `x y` with 0 based indices. ``` k)maze " v < " "> v " " > ^ " "> v" "^ < *" k)solve maze 1 0 ``` [Answer] ## Python 422 ``` with open("m.txt","r") as f:m=f.read().split("\n") p=[(v.find("*"),p) for p,v in enumerate(m) if "*" in v][0] g=[] def f(a): x,y=b,c=a for p,i in enumerate((lambda x:[l[x] for l in m])(x)): if i in "^>v<" and((p<y and i=="v")or(p>y and i=="^")):return b,p for p,i in enumerate(m[y]): if i in "^>v<" and((p<x and i==">")or(p>x and i=="<")):return p,c while True: z=f(p) if z in g:break else:g.append(z);p=z print p ``` The input is in a file called `m.txt`. The output is `(x, y)` but if you change the last print statement to `print g`, the output will be a list like `[(x, y), (x, y), ...]` with all the steps to get from the end to the start. ]
[Question] [ The **continued fraction** of a number \$n\$ is a fraction of the following form: $$a\_0 + \cfrac 1 {a\_1 + \cfrac 1 {a\_2 + \cfrac 1 {a\_3 + \cfrac 1 {a\_4 + \ddots}}}}$$ which converges to \$n\$. The sequence \$a\$ in a continued fraction is typically written as: \$[a\_0; a\_1, a\_2, a\_3, ... a\_n]\$. We will write ours in the same fashion, but with the repeating part between semicolons. Your goal is to return the continued fraction of the square root of \$n\$. **Input:** An integer, \$n\$. \$n\$ will never be a perfect square. **Output:** The continued fraction of \$\sqrt n\$. **Test Cases:** `2 -> [1; 2;]` `3 -> [1; 1, 2;]` `19 -> [4; 2, 1, 3, 1, 2, 8;]` Shortest code wins. Good luck! [Answer] ## GolfScript (66 60 chars) ``` ~:^,{.*^>}?(:?';'[1?{^1$.*-@/?@+.2$/@@1$%?\- 1$(}do;;]','*1$ ``` Warning: most of the `?` in there are the variable representing `floor(sqrt(input))` rather than the builtin. But the first one is the builtin. Takes input on stdin and outputs to stdout. Psuedocode of the algorithm (proof of correctness currently left as an exercise for the reader): ``` n := input() m := floor(sqrt(n)) output(m) x := 1 y := m do x := (n - y * y) / x output((m + y) / x) y := m - (m + y) % x while (x > 1) ``` Yet again I find myself wanting a single operator which takes `a b` on the stack and leaves `a/b a%b` on the stack. [Answer] ## Python, 95 97 (but correct...) This uses only integer arithmetic and floor division. This will produce correct results for all positive integer inputs, though if one wants to use a long, they'd have to add a character; for example `m=a=0L`. And of course... wait for a million years for my poor man's floor sqrt to terminate. ``` z=x=m=1 while n>m*m:m+=1 m=y=m-1 l=() while-z<x:x=(n-y*y)/x;y+=m;l+=y/x,;y=m-y%x;z=-1 print c,l ``` **Output:** ``` n=139 11 (1, 3, 1, 3, 7, 1, 1, 2, 11, 2, 1, 1, 7, 3, 1, 3, 1, 22) ``` edit: now using Peter Taylor's algorithm. That `do...while` was fun. [Answer] # Python, 87 82 80 ``` x=r=input()**.5 while x<=r:print"%d"%x+",;"[x==r],;x=1/(x%1) print`int(r)*2`+";" ``` It takes one integer and gives output like: ``` 4; 2, 1, 3, 1, 2, 8; ``` [Answer] ## Mathematica 33 31 ``` c[n_]:=ContinuedFraction@Sqrt@n ``` Output is in list format, which is more appropriate for Mathematica. Examples: ``` c[2] c[3] c[19] c[139] c[1999] (* out *) {1, {2}} {1, {1, 2}} {4, {2, 1, 3, 1, 2, 8}} {11, {1, 3, 1, 3, 7, 1, 1, 2, 11, 2, 1, 1, 7, 3, 1, 3, 1, 22}} {44, {1, 2, 2, 4, 1, 1, 5, 1, 5, 8, 1, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 14, 3, 1, 1, 29, 4, 4, 2, 5, 1, 1, 17, 2, 1, 12, 9, 1, 5, 1, 43, 1, 5, 1, 9, 12, 1, 2, 17, 1, 1, 5, 2, 4, 4, 29, 1, 1, 3, 14, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 3, 1, 8, 5, 1, 5, 1, 1, 4, 2, 2, 1, 88}} ``` [Answer] ## Python (~~136 133~~ 96) The standard method for continued fractions, extremely golfed. ``` a=input()**.5 D=c=int(a);b=[] while c!=D*2:a=1/(a%1);c=int(a);b+=[c] print D,";%s;"%str(b)[1:-1] ``` [Answer] ## C, 137 Including the newline, assuming I don't have to roll my own square root. ``` #include<math.h> main(i,e){double d;scanf("%lf",&d);e=i=d=sqrt(d);while(i^e*2)printf("%d%c",i,e^i?44:59),i=d=1.0/(d-i);printf("%d;",i);} ``` It breaks for sqrt(139) and contains the occasional extra semicolon in the output, but I'm too tired to work on it further tonight :) ``` 5 2;4; 19 4;2,1,3,1,2,8; 111 10;1,1,6,1,1,20; ``` [Answer] ## Perl, 99 chars Does *not* screw up on 139, 151, etc. Tested with number ranging from 1 to 9 digits. ``` $"=",";$%=1;$==$-=($n=<>)**.5; push@f,$==(($s=$=*$%-$s)+$-)/($%=($n-$s*$s)/$%)until$=>$-; say"$-;@f;" ``` Note: `$%`, `$=`, and `$-` are all integer-forcing variables. [Answer] # APL(NARS), 111 chars, 222 bytes ``` r←f w;A;a;P;Q;m m←⎕ct⋄Q←1⋄⎕ct←P←0⋄r←,a←A←⌊√w⋄→Z×⍳w=0 L: →Z×⍳0=Q←Q÷⍨w-P×P←P-⍨a×Q⋄r←r,a←⌊Q÷⍨A+P⋄→L×⍳Q>1 Z: ⎕ct←m ``` The f function is based on the algo one find in the page <http://mathworld.wolfram.com/PellEquation.html> for solve Pell equation. That f function has its input all not negative number (type fraction too). Possible there is something goes wrong, I remember that √ has, in how I see it, problem for big fraction numbers, as ``` √13999999999999999999999999999999999999999999999x 1.183215957E23 ``` so there would be one function sqrti(). For this reason fraction input (and integer input) has to be <10^15. test: ``` ⎕fmt (0..8),¨⊂¨f¨0..8 ┌9───────────────────────────────────────────────────────────────────────────────────────────────────────┐ │┌2─────┐ ┌2─────┐ ┌2───────┐ ┌2─────────┐ ┌2─────┐ ┌2───────┐ ┌2─────────┐ ┌2─────────────┐ ┌2─────────┐│ ││ ┌1─┐│ │ ┌1─┐│ │ ┌2───┐│ │ ┌3─────┐│ │ ┌1─┐│ │ ┌2───┐│ │ ┌3─────┐│ │ ┌5─────────┐│ │ ┌3─────┐││ ││0 │ 0││ │1 │ 1││ │2 │ 1 2││ │3 │ 1 1 2││ │4 │ 2││ │5 │ 2 4││ │6 │ 2 2 4││ │7 │ 2 1 1 1 4││ │8 │ 2 1 4│││ ││~ └~─┘2 │~ └~─┘2 │~ └~───┘2 │~ └~─────┘2 │~ └~─┘2 │~ └~───┘2 │~ └~─────┘2 │~ └~─────────┘2 │~ └~─────┘2│ │└∊─────┘ └∊─────┘ └∊───────┘ └∊─────────┘ └∊─────┘ └∊───────┘ └∊─────────┘ └∊─────────────┘ └∊─────────┘3 └∊───────────────────────────────────────────────────────────────────────────────────────────────────────┘ f 19 4 2 1 3 1 2 8 f 54321x 233 14 1 1 3 2 1 2 1 1 1 1 3 4 6 6 1 1 2 7 1 13 4 11 8 11 4 13 1 7 2 1 1 6 6 4 3 1 1 1 1 2 1 2 3 1 1 14 466 f 139 11 1 3 1 3 7 1 1 2 11 2 1 1 7 3 1 3 1 22 +∘÷/f 139 11.78982612 √139 11.78982612 ``` if the argument is a square of a number it would return one list of 1 only element, the sqrt of that number ``` f 4 2 ``` If it would depend from me, in one exercise without "codegolf" I would prefer the previous edit that use function sqrti()... ]
[Question] [ ### Kira needs your help! --- ## Input format: ``` Date [and/or Time] Name Gender Reason ``` ## Output format: ``` <Last Name, First Name> <will die/died> on the <DD><st/nd/rd/th> of <MMM, YYYY> [at <hh:mm:ss TT>]. <He/She> <will die/died> of <Reason>. ``` --- --- # Details, Details: --- Your program should account for at least the following date input formats: ``` 9 November 2003 9/11/2003 November 9, 2003 ``` --- Time formats: ``` hh tt hh TT hh:mm tt hh:mm TT hh:mm:ss tt hh:mm:ss TT HH HH:mm HH:mm:ss ``` --- The following name input formats: ``` first // Stephen last // Harper first last // Stephen Harper last, first // Harper, Stephen ``` --- --- # Test cases: --- ## Input: ``` 2 September 1973 J.R.R. Tolkien Male pneumonia ``` ## Output: > > Tolkien, J.R.R. died on the 2nd of > September, 1973. > > > He died of pneumonia. > > > --- **DISCLAIMER:** If he actually dies on this date, it's *Kira's* fault, not mine. **UPDATE:** Stephen Harper did not die on the listed date ## Input: ``` 21/12/12 23:59:59 // DD/MM/YY HH:mm:ss Harper, Stephen // Last, First Unknown // Gender a heart attack for no reason // Reason ``` ## Output: > > Harper, Stephen will die on the 21st > of December, 2012 at 11:59:59 PM. > > > Harper, Stephen will die of a heart > attack for no reason. > > > --- --- ## Bonus: ``` July 21, 1969 02:56:15 GMT Armstrong, Neil Male poisoned moon cheese -- January 19, 2038 03:14:08 GMT Everyone Unknown Y2K38 ``` Add `<st/nd/rd/th>` at the end of `DD` for input. [Answer] ## Javascript (561) This can probably be reduced significantly, but here goes: ``` i=i.split("\n");d=new Date(i[0]);t=d.getDate();z=t%10;t+=z==1?"st":z==2?"nd":z==3?"rd":"th";m=['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];y=d.getFullYear();a=d.getHours();b=d.getMinutes();c=d.getSeconds();l=a&&b&&c?" at "+a+":"+b+":"+c:"";g=d>new Date()?"will die":"died";n=i[1].split(" ");n[1]?n[0][n[0].length-1]==","?n=i[1]:n=n[1]+", "+n[0]:n[0];s=i[2]=="Male"?"He":i[2]=="Female"?"She":n;document.write(n+" "+g+" on the "+t+" of "+m+", "+y+l+".<br>"+s+" "+g+" of "+i[3]+"."); ``` Sample I/O: ``` 2 September 1973 J.R.R. Tolkien Male pneumonia ``` > > Tolkien, J.R.R. died on the 2nd of September, 1973. > He died of pneumonia. > > > ``` January 19, 2038 03:14:08 GMT Everyone Unknown Y2K38 ``` > > Everyone will die on the 18th of January, 2038 at 21:14:8. > Everyone will die of Y2K38. > > > Try it out on [JsFiddle](http://jsfiddle.net/28fCg/4/). [Answer] ## VB.NET, ~~727~~ 695 Okay, golfed a bit. Requires `Option Strict Off`. ``` Module M Sub Main Dim d=Date.Parse(Console.ReadLine),n=Console.ReadLine,o=Date.Now,g=Console.ReadLine,r=Console.ReadLine,i=n.IndexOf(" "),f=d.Day Mod 10+(d.Day\10=1)*5,a=Array.IndexOf("male|female|he|she|him|her|guy|girl|boy|lady|man|woman".Split("|"), g.ToLower),b="|st|nd|rd".Split("|"),m="|January|February|March|April|May|June|July|August|September|October|November|December".Split("|") If n.IndexOf(",")<0 Then n=n.Substring(i+1)&", "&n.Substring(0,i) g=If(a<0,n,If(a Mod 2,"She","He")) Console.Write("{0} {11} on the {1}{2} of {3}, {4} at {5}:{6:00}:{7:00}.{8}{9} {11} of {10}.",n,d.Day,If(f<4,b(f),"th"),m(d.Month),d.Year,d.Hour,d.Minute,d.Second,vbCrLf,g,r,If(o<d,"will die","died")) End Sub End Module ``` It accepts the dates in all the test cases, and many other formats thanks to `Date.Parse`. It accepts *many* genders (as you can see) as well. If Kira decides to put only the person's first or last name, the program will crash. [Answer] ### CSharp - 463 chars ``` void Main(){Func<String>c=()=>Console.ReadLine();var d=DateTime.Parse(c());var n=c();if(!n.Contains(",")&&n.Contains(" "))n=n.Split(' ')[1]+", "+n.Split(' ')[0];n+=" ";var g=c().ToLower();g=g.Contains("male")?g.Replace("female","She").Replace("male","He"):"They";var r=c();var f=(DateTime.Now<d);Console.Write(String.Format(n+"{0} on the {1} {2}\n{3} {0} of {4}",(f?"will die":"died"),d.ToString("dddd 'of' MMMM, yyyy"),d.Date==d?"":d.ToString("hh:mm:ss"),g,r));} ``` [Answer] ## PHP, 509 474 462 461 characters ``` <?for($l=0;$l<4;)$i[$l++]=chop(fgets(STDIN)); putenv('TZ=GMT'); $t=strtotime(preg_match("/(\d+)\/(\d+)\/(\d+)(.*)/",$i[0],$q)?"$q[1]-$q[2]-".($q[3]<100?19+1*($q[3]<70):"").$q[3].$q[4]:$i[0]); $z=$t<time()?" died":" will die"; $f="jS \of F, Y".($t%86400?" \a\\t g:i:s A":""); $n=strpos($i[1],',')?$i[1]:explode(" ",$i[1]); if(is_array($n))$n=$n[1]!=""?$n[1].", ".$n[0]:$n[0];?> <?=$n."$z on the ".date($f,$t)."\n\n".($i[2][0]==M?He:($i[2][0]==F?She:$n))."$z of ".$i[3]; ``` I've added newlines after each `;` but not counted them as they don't need to be there. Whether the code handles dates beyond January 19, 2038 03:14:07, depends on whether it's run on a 64bit machine. [Answer] # VBA, ~~384~~ 366 Bytes ### Golfed Full `sub`routine that takes input of expected type `Variant\String` and outputs the associated deathnote message to the VBE immediates window *Note: VBA is incapable of handling Timezones without declaring Windows API functions, so as these are not necessary for the question, they have been excluded* ``` Sub x(d,n,g,r) e=CDate(d) f=Day(e) Mod 10 w=IIf(e>Now," will die"," died") i=InStr(1,n," ") n=IIf(InStr(1,n,","),n,Mid(n,i+1)&", "&Mid(n,1,i-1)) g=LCase(g) Debug.?n;w" on the "Day(e)Split("th|st|nd|rd","|")(IIf(f>3,0,f))" of "MonthName(Month(e))", "Year(e)IIf(InStr(1,d,":")," at "&TimeValue(d),"")"."vbCr;IIf(g="male","He",IIf(g="female","She",n))w" of "r". End Sub ``` ### Bonus Verison, ~~394~~ 376 Bytes Slightly modified version of the above that handles all of the bonus cases with the exception of timezones (Correction for handling mononyms) ``` Sub x(d,n,g,r) e=CDate(d) f=Day(e) Mod 10 i=InStr(1,n," ") w=Space(0 ^i)&IIf(e>Now,"will die","died") n=IIf(InStr(1,n,",")^i,n,Mid(n,i+1)&", "&Mid(n,1,i)) g=LCase(g) Debug.?n;w" on the "Day(e)Split("th|st|nd|rd","|")(IIf(f>3,0,f))" of "MonthName(Month(e))", "Year(e)IIf(InStr(1,d,":")," at "&TimeValue(d),"")"."vbCr;IIf(g="male","He",IIf(g="female","She",n))w" of "r". End Sub ``` ### Usage input and output sequence of the example problems as seen from the VBE immediate window ``` ?Now 01-Jun-17 1:59:35 PM x "2 September 1973", "J.R.R. Tolkien", "Male", "pneumonia" Tolkien, J.R.R. died on the 2nd of September, 1973. He died of pneumonia. x "21/12/12 23:59:59", "Harper, Stephen", "Unknown", "a heart attack for no reason" Harper, Stephen died on the 21st of December, 2012 at 11:59:59 PM. Harper, Stephen died of a heart attack for no reason. x "July 21, 1969 02:56:15", "Armstrong, Neil", "Male", "poisoned moon cheese" Armstrong, Neil died on the 21st of July, 1969 at 2:56:15 AM. He died of poisoned moon cheese. ## Using Bonus Version x "January 19, 2038 03:14:08","Everyone","Unknown","Y2K38" Everyone will die on the 19th of January, 2038 at 3:14:08 AM. Everyone will die of Y2K38. ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/478/edit). Closed 1 year ago. [Improve this question](/posts/478/edit) So before you read some basic computer science concepts. 1. A binary tree is a dynamically allocated structure (usually used for ordered storage). 2. Because of its nature traversal of binary trees is usually recursive; This is because linear traversal (via a loop) is not natural when there are two avenues of looping. * Recursive: This means a function that calls itself. 3. In old fashioned languages, memory management requires manual memory management. * Manual: Means you have to do it yourself. 4. When you do manual memory management you need to actual ask the underlying system to free each member of the tree. * Free: recover the memory in to the global poos so it can be re-used and you don't run out of memory. * Freeing: this is done by calling the function `free()` and passing it the pointer you want to recover. * Pointer: Its like a virtual stick. At the end is memory. When you ask for memory you are given a pointer (virtual stick) that has memory. When you are done you give back the pointer (virtual stick). ### The recursive solution: ``` freeTree(Node* node) { freeTree(node->left); freeTree(node->right); free(node); } ``` The problem then is that recursion means you are repeatedly calling the same function. This grows the stack. Growing the stack uses more memory. The reason you are freeing the tree is you want memory back using more memory is counterproductive (even if you do get both bits of memory back). ### At last the question: SO the problem centers around converting the recursive version above into a linear solution (so that you don't have to use memory). Give the node type ``` typedef struct Node Node; struct Node { Node* left; Node* right; }; ``` Write a function to free a tree of these nodes. Restrictions: * Cannot use recursion (not even indirectly) * Cannot allocate any dynamic space for tracking. * Note there is an O(n) solution Winner: 1. Best Complexity. 2. Tie Break 1: First Submitted 3. Tie Break 2: Least amount of characters. [Answer] Seems very close to O(n) to me: This does a depth-first walk on the tree, and uses the `->left` pointer of traversed nodes to keep track of the parent. ``` struct Node * node = root; struct Node * up = NULL; while (node != NULL) { if (node->left != NULL) { struct Node * left = node->left; node->left = up; up = node; node = left; } else if (node->right != NULL) { struct Node * right = node->right; node->left = up; node->right = NULL; up = node; node = right; } else { if (up == NULL) { free(node); node = NULL; } while (up != NULL) { free(node); if (up->right != NULL) { node = up->right; up->right = NULL; break; } else { node = up; up = up->left; } } } } ``` [Answer] # C99, 94, O(n) **Edit:** everyone seems to refer to `struct Node` just as `Node` as if the `typedef`ed it, so I did too. this is actually my first C golf. lots of segfaults. anyways, this requires C99 because it uses a declaration inside a for loop's first statement. ``` void f(Node*n){for(Node*q;n;n=q)(q=n->left)?n->left=q->right,q->right=n:(q=n->right,free(n));} ``` not even using `#define`! this algorithm works by transforming the tree so that the top node has no left child, and then deleting it and moving on to it's right child. for example, if we start with the tree ``` 1 / \ 2 3 \ 4 ``` the algorithm will mutate the pointers so that the tree will be ``` 2 \ 1 / \ 4 3 ``` now we can delete the topmost node easily. [Answer] # c++ 99 O(n) The thing here loops are great for chaining along a list but not going up and down hierarchies. user300 managed it (I am impressed) but the code is hard to read. The solution is to convert the tree into a list. The trick is to do it at the same time your deleting the nodes. ``` void freeNode(Node* t) { if (t == NULL) { return; } // Points at the bottom left node. // Any right nodes are added to the bottom left as we go down // this progressively flattens the tree into a list as we go. Node* bottomLeft = findBottomLeft(t); while(t != NULL) { // Technically we don't need the if (it works fine without) // But it makes the code easier to reason about with it here. if (t->right != NULL) { bottomLeft->left = t->right; bottomLeft = findBottomLeft(bottomLeft); } // Now just free the curent node Node* old = t; t = t->left; free(old); } } Node* findBottomLeft(Node* t) { while(t->left != NULL) { t = t->left; } return t; } ``` # Golf Version ``` void f(Node*t){Node*o,*l=t;for(;t;free(o)){for(;l->left;l=l->left);l->left=t->right;o=t;t=t->left;}} ``` ## Golf Expanded ``` void f(Node* t) { Node*o,*l = t; for(;t;free(o)) { for(;l->left;l = l->left); l->left = t->right; o = t; t = t->left; } } ``` [Answer] ## C/C++/Objective-C 126 characters (includes required trailing newline) ``` #define b(t)(t->left||t->right) void f(Node*r){while(r&&b(r)){Node**p=&r,*c=b(r);while(c)p=&c,c=b(c);free(*p);*p=0;}free(r);} ``` Does not run in O(n) time. But the OP does not require it, so here's my O(n2) solution. Algorithm: Walk down to a leaf from the root. Release it. Repeat until there are no leaves. Release the root. Ungolfed: ``` void freeTree (Node * root) { while (root && (root->left || root->right)) { Node ** prev = &root; Node * curr = root->left || root->right; while (curr != 0) { prev = &curr; curr = curr->left || curr->right; } free(*prev); *prev = 0; } free(root); } ``` [Answer] ## C, 150 bytes ``` f(T*r,int s){T*t[s];t[0]=r;T**f=&t[0],**e=&t[0];while(f<=e){if(*f){if((*f)->left){*++e=(*f)->left;}if((*f)->right){*++e=(*f)->right;}}free(*f);f++;}} ``` [Try It On JDoodle](https://www.jdoodle.com/embed/v0/1tMh) ]
[Question] [ This challenge is about computing the [chromatic number](https://en.wikipedia.org/wiki/Graph_coloring#Vertex_coloring) of special types of graphs. # Input The input will consist of two integers. * A positive integer \$n > 1\$. * A distance \$d < n\$. # Task The two inputs values will define a graph with \$2^n\$ nodes. Each node corresponds to a different binary array of length \$n\$. Two nodes in the graph will be connected if and only if the [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between the arrays corresponding to the two nodes is exactly \$d\$. # Output The chromatic number of the corresponding graph. # Timing I will try your code with inputs \$n,d\$ in increasing order until it takes more than 1 minute to run on my PC. So I will try `2,1`, `3,1`, `3,2`, `4,1`, `4,2`, `4,3`, `5,1`, `5,2`, `5,3`, `5,4` etc. Your score is how far through that infinite list your code manages to get. # Examples ``` Input 2,1 -> 2 Input 3,1 -> 2 Input 3,2 -> 4 Input 4,1 -> 2 Input 4,2 -> 4 Input 4,3 -> 2 Input 5,1 -> 2 Input 5,2 -> 8 Input 5,3 -> 2 Input 5,4 -> 4 Input 6,1 -> 2 Input 6,2 -> 8 Input 6,3 -> 2 Input 6,4 -> 7 Input 6,5 -> 2 Input 7,1 -> 2 Input 7,2 -> 8 Input 7,3 -> 2 Input 7,4 -> 8 Input 7,5 -> 2 Input 7,6 -> 4 Input 8,1 -> 2 Input 8,2 -> 8 Input 8,3 -> 2 Input 8,4 -> 8 Input 8,5 -> 2 Input 8,6 -> 7 Input 8,7 -> 2 Input 9,1 -> 2 Input 9,2 -> 13 Input 9,3 -> 2 Input 9,4 -> [10,16] Input 9,5 -> 2 Input 9,6 -> [7,11] Input 9,7 -> 2 Input 9,8 -> 4 ``` # What is a chromatic number? A coloring of a graph assigns a color to each node so that no two nodes that are connected by an edge have the same color. The chromatic number of a graph is the smallest number of colors needed to color that graph. # All languages are equal This challenge like (almost?) all challenges is per language. So if you have fast code in Python, you don't need to worry if someone else is using optimized C. I will keep a table for all languages used. # The timing machine I will run your code in Ubuntu on a AMD Ryzen 5 3400G with 16GB of RAM. # Related: [Find the Chromatic Number](https://codegolf.stackexchange.com/questions/37709/find-the-chromatic-number?rq=1) is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge to compute the chromatic number of a graph. # Leaderboard: * **11, 6** using **Wolfram language 13.0** by Aspen. * **8,5** using **Python 3 + PySAT** by alephalpha. * **8,5** using **Python 3 + Z3** by Bubbler. * **8,5** using **Wolfram language 12.0.1** by alephalpha. # Permanent bounty I will award 100 points to any answer that can compute 9,2. [Answer] # [Rust](https://www.rust-lang.org/), `8,7` in 3 minutes on the Rust playground ``` use std::time::Instant; use std::{ collections::HashMap, hash::Hash, sync::atomic::{AtomicU32, Ordering}, }; use rayon::prelude::*; const MAX_THREADS: usize = 4; static NUM_TASKS: AtomicU32 = AtomicU32::new(0); #[derive(Clone, Copy, Debug)] struct Edge { opposite_edge: u32, opposite_color: u32, opposite_vertex: u16, } #[repr(C)] #[derive(Clone, Copy)] struct Color { up: u32, down: u32, vertex: u16, last_edge: u32, } #[repr(C)] #[derive(Clone, Copy)] struct Vertex { up: u32, down: u32, left: u16, right: u16, count_colors: u16, count_edges: u16, } #[repr(C)] #[derive(Clone, Copy)] struct Root { padding_1: u64, left: u16, right: u16, padding_2: u32, } impl Root { fn new() -> Self { Self { padding_1: 0, left: 0, right: 0, padding_2: 0, } } } // the reason for repr(C) is so color/vertex up/down are in the same locations #[repr(C, align(16))] #[derive(Clone, Copy)] union Node { edge: Edge, color: Color, vertex: Vertex, root: Root, } impl Default for Node { fn default() -> Self { Self { root: Root::new() } } } #[derive(Clone)] struct GraphColoring { nodes: Vec<Node>, allowance: u32, // num_checks: u64, max_colors: u32, } impl GraphColoring { fn edge_mut(&mut self, idx: u32) -> &mut Edge { unsafe { &mut self.nodes.get_mut(idx as usize).unwrap_unchecked().edge } } fn color_mut(&mut self, idx: u32) -> &mut Color { unsafe { &mut self.nodes.get_mut(idx as usize).unwrap_unchecked().color } } fn vertex_mut(&mut self, idx: u16) -> &mut Vertex { unsafe { &mut self.nodes.get_mut(idx as usize).unwrap_unchecked().vertex } } fn edge(&self, idx: u32) -> Edge { unsafe { self.nodes.get(idx as usize).unwrap_unchecked().edge } } fn color(&self, idx: u32) -> Color { unsafe { self.nodes.get(idx as usize).unwrap_unchecked().color } } fn vertex(&self, idx: u16) -> Vertex { unsafe { self.nodes.get(idx as usize).unwrap_unchecked().vertex } } fn pick_min_vertex(&self) -> Option<(u16, u16)> { let mut idx = self.vertex(0).right; if idx == 0 { return None; } let mut fewest_colors = self.max_colors as _; let mut most_edges = 0; let mut bestidx = idx; loop { let vertex = self.vertex(idx); if vertex.count_colors < fewest_colors || (vertex.count_colors == fewest_colors && vertex.count_edges > most_edges) { if vertex.count_colors == 0 { return Some((0, 0)); } if vertex.count_colors == 1 { return Some((idx, 1)); } fewest_colors = vertex.count_colors; most_edges = vertex.count_edges; bestidx = idx; } idx = vertex.right; if idx == 0 { break; } } Some((bestidx, fewest_colors)) } fn disconnect_color(&mut self, color_idx: u32, color: Color) { for idx in color_idx + 1..=color.last_edge { let edge = self.edge(idx); let opposite_edge_idx = edge.opposite_edge; let opposite_color_idx = edge.opposite_color; let opposite_color = self.color(opposite_color_idx); debug_assert!(opposite_edge_idx <= opposite_color.last_edge); debug_assert!(opposite_edge_idx >= opposite_color_idx); if opposite_edge_idx < opposite_color.last_edge { // swap nodes at opposite_edge_idx and opposite_color.last_edge // that means our pointer has to change, as well as last_edges oppoosite_edge has to change let last_edge_idx = opposite_color.last_edge; let last_edge = self.edge(last_edge_idx); let last_edge_opposite_idx = last_edge.opposite_edge; self.edge_mut(last_edge_opposite_idx).opposite_edge = opposite_edge_idx; *self.edge_mut(opposite_edge_idx) = Edge { opposite_edge: last_edge_opposite_idx, opposite_color: last_edge.opposite_color, opposite_vertex: last_edge.opposite_vertex, }; *self.edge_mut(last_edge_idx) = Edge { opposite_edge: idx, opposite_color: color_idx, opposite_vertex: color.vertex, }; // self.edge_mut(last_edge_idx).opposite_edge = idx; // self.edge_mut(last_edge_idx).opposite_color = color_idx; self.edge_mut(idx).opposite_edge = last_edge_idx; } self.color_mut(opposite_color_idx).last_edge -= 1; self.vertex_mut(opposite_color.vertex).count_edges -= 1; debug_assert_eq!( self.edge(idx).opposite_edge, self.color(edge.opposite_color).last_edge + 1 ); } } fn reconnect_color(&mut self, color_idx: u32, color: Color) { for edge_idx in (color_idx + 1..=color.last_edge).rev() { let edge = self.edge(edge_idx); debug_assert_eq!( edge.opposite_edge, self.color(edge.opposite_color).last_edge + 1 ); self.color_mut(edge.opposite_color).last_edge += 1; let color = self.color(edge.opposite_color); self.vertex_mut(color.vertex).count_edges += 1; } } #[inline] fn remove_adjacent(&mut self, color_idx: u32, color: Color) { for edge_idx in (color_idx + 1..=color.last_edge).rev() { let edge = self.edge(edge_idx); let color1_idx = edge.opposite_color; let color1 = self.color(color1_idx); self.disconnect_color(color1_idx, color1); self.color_mut(color1.up).down = color1.down; self.color_mut(color1.down).up = color1.up; let vertex = self.vertex_mut(color1.vertex); vertex.count_colors -= 1; vertex.count_edges -= (color1.last_edge - color1_idx) as u16; } } fn reconnect_adjacent(&mut self, color_idx: u32, color: Color) { for edge_idx in color_idx + 1..=color.last_edge { let edge = self.edge(edge_idx); let color1_idx = edge.opposite_color; let color1 = self.color(color1_idx); self.reconnect_color(color1_idx, color1); self.color_mut(color1.up).down = color1_idx; self.color_mut(color1.down).up = color1_idx; let vertex = self.vertex_mut(color1.vertex); vertex.count_colors += 1; vertex.count_edges += (color1.last_edge - color1_idx) as u16; } } fn check(&mut self) -> bool { let (vertex_idx, count) = match self.pick_min_vertex() { None => { return true; } Some(x) => x, }; if count == 0 { return false; } // self.num_checks += 1; let vertex_idx = vertex_idx as u32; let mut idx = self.color(vertex_idx).down; while idx != vertex_idx { let color = self.color(idx); self.disconnect_color(idx, color); idx = color.down; } let mut allowance = count as u32 - self.allowance; let vertex = self.vertex(vertex_idx as _); self.vertex_mut(vertex.left).right = vertex.right; self.vertex_mut(vertex.right).left = vertex.left; idx = vertex.down; let has_allowance = self.allowance > 0; let x = count as u32 - self.allowance.saturating_sub(1); let num_tasks = NUM_TASKS.load(Ordering::Relaxed); let parallel = num_tasks < MAX_THREADS as u32 && NUM_TASKS .compare_exchange_weak( num_tasks, num_tasks + x - 1, Ordering::SeqCst, Ordering::Relaxed, ) .is_ok(); if parallel { let mut tasks = Vec::new(); while idx != vertex_idx { let color = self.color(idx); if has_allowance && allowance == 0 { self.allowance -= 1; } if (idx + 1..=color.last_edge).all(|edge_idx| { self.vertex(self.edge(edge_idx).opposite_vertex) .count_colors > 1 }) { self.remove_adjacent(idx, color); tasks.push(self.clone()); self.reconnect_adjacent(idx, color); } if has_allowance && allowance == 0 { self.allowance += 1; break; } idx = self.color(idx).down; allowance -= 1; } idx = self.color(vertex_idx).up; while idx != vertex_idx { let color = self.color(idx); self.reconnect_color(idx, color); idx = color.up; } self.vertex_mut(vertex.left).right = vertex_idx as _; self.vertex_mut(vertex.right).left = vertex_idx as _; let o = tasks.par_drain(..).any(|mut i| i.check()); NUM_TASKS.fetch_sub(x - 1, Ordering::Relaxed); o } else { while idx != vertex_idx { let color = self.color(idx); if has_allowance && allowance == 0 { self.allowance -= 1; } if (idx + 1..=color.last_edge).all(|edge_idx| { self.vertex(self.edge(edge_idx).opposite_vertex) .count_colors > 1 }) { self.remove_adjacent(idx, color); if self.check() { return true; } self.reconnect_adjacent(idx, color); } if has_allowance && allowance == 0 { self.allowance += 1; break; } idx = self.color(idx).down; allowance -= 1; } idx = self.color(vertex_idx).up; while idx != vertex_idx { let color = self.color(idx); self.reconnect_color(idx, color); idx = color.up; } self.vertex_mut(vertex.left).right = vertex_idx as _; self.vertex_mut(vertex.right).left = vertex_idx as _; false } } fn new<T, F>(vertices: &Vec<T>, adjacent: F, max_colors: u32) -> GraphColoring where F: Fn(T, T) -> bool, T: Hash + Eq + Copy, { let mut this = GraphColoring { nodes: vec![Node::default()], allowance: max_colors, // num_checks: 0, max_colors, }; let mut vertex_idxs = HashMap::new(); // add vertex nodes for &v in vertices { let vertex_idx = this.nodes.len() as u16; let left_idx = vertex_idx - 1; let right_idx = 0; let vertex = Vertex { up: vertex_idx as _, down: vertex_idx as _, left: left_idx, right: right_idx, count_colors: 0, count_edges: 0, }; vertex_idxs.insert(v, vertex_idx); this.nodes.push(Node { vertex }); this.vertex_mut(left_idx).right = vertex_idx; this.vertex_mut(right_idx).left = vertex_idx; } let mut edge_to_idx = HashMap::new(); // add colors for &a in vertices { let vertex_a_idx = vertex_idxs[&a]; for k in 0..max_colors { let color_a_idx = this.nodes.len() as _; let up_idx = this.vertex(vertex_a_idx).up; let down_idx = vertex_a_idx as _; let color_a = Color { up: up_idx, down: down_idx, vertex: vertex_a_idx, last_edge: color_a_idx, }; this.nodes.push(Node { color: color_a }); this.color_mut(up_idx).down = color_a_idx; this.color_mut(down_idx).up = color_a_idx; this.vertex_mut(vertex_a_idx).count_colors += 1; // and edges for &b in vertices { if a == b { continue; } if adjacent(a, b) { let edge_a_idx = this.nodes.len() as _; let edge_a = match edge_to_idx.get(&(b, a, k)) { Some(&(edge_b_idx, color_b_idx, vertex_b_idx)) => { this.edge_mut(edge_b_idx).opposite_color = color_a_idx; this.edge_mut(edge_b_idx).opposite_edge = edge_a_idx; this.edge_mut(edge_b_idx).opposite_vertex = vertex_a_idx; Node { edge: Edge { opposite_color: color_b_idx, opposite_edge: edge_b_idx, opposite_vertex: vertex_b_idx, }, } } None => { edge_to_idx .insert((a, b, k), (edge_a_idx, color_a_idx, vertex_a_idx)); Node::default() } }; this.nodes.push(edge_a); this.color_mut(color_a_idx).last_edge = edge_a_idx; this.vertex_mut(vertex_a_idx).count_edges += 1; } } } } this } fn chromatic_number(n: u32, d: u32, max_colors: u32) -> bool { if d % 2 == 1 { return max_colors >= 2; } let mut g = GraphColoring::new( &(0_u32..1 << n) .filter(|&i| i.count_ones() % 2 == 0) .collect(), |a, b| (a ^ b).count_ones() == d, max_colors, ); let out = g.check(); // println!("Num checks: {}", g.num_checks); out } } fn chromatic(n: u32, d: u32) -> u32 { for k in 2.. { if GraphColoring::chromatic_number(n, d, k) { return k; } } panic!("You're never gonna reach this"); } fn main() { let start = Instant::now(); rayon::ThreadPoolBuilder::new() .num_threads(MAX_THREADS) .build_global() .unwrap(); for n in 2..=8 { for d in 1..n { println!("{},{} -> {}", n, d, chromatic(n, d)); } } println!("Finished in: {:?}", start.elapsed()); } ``` [Try it online!](https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=14a09279c74c8fdfa2c9c85b430fd597) Formulates the decision problem as an exact cover problem and then uses [dancing links](https://en.wikipedia.org/wiki/Dancing_Links) to solve it. Specifically, rows correspond to coloring a vertex a color. The columns correspond to the conditions that each vertex is covered by exactly one color, and that each edge has at most one vertex for any given color. There are two graph coloring specific optimizations: * Colors are chosen in order. That is, when choosing the color for a vertex, only one of the colors that haven't yet been chosen must be considered. Without this optimization, proving that `f(8,6)` is not `5` takes 415 million steps, with the optimization it takes around 1 million steps (and it's presumably even more effective for proving the chromatic number is not 6, since it's pruning more colors in that case). * Ties are broken by finding the vertex with the maximum number of unassigned neighbors. This is also a pretty good optimization, without it (but with the previous) 4,225,666,594 steps are required to prove the chromatic number is not 6, with it only 299,285,005 steps are necessary. If you run it on your own computer, make sure to run `cargo add rayon` and compile with the `RUSTFLAGS=-Ctarget-cpu=native` environment variable. [Answer] # Python 3 + [Z3](https://github.com/Z3Prover/z3), `8,5` ``` import z3 def check(nodes, d, limit): solver = z3.SolverFor('QF_FD') for node in nodes: solver.add(1 <= node, node <= limit) l = len(nodes) for i in range(l): for j in range(l): cnt = bin(i ^ j).count('1') if d-1 <= cnt <= d: solver.add(nodes[i] != nodes[j]) return solver.check() == z3.sat def solve(n, d, lower=1): if d % 2: return 2 nodes = [z3.Int(f'a{i}') for i in range(2**(n-1))] upper = (lower + 1) * 2 while lower + 1 < upper: mid = lower + 1 if mid == lower: mid += 1 result = check(nodes, d, mid) print(n, d, mid, result) if result: upper = mid else: lower = mid return upper def main(): from time import time start = time() n = 2 memo = [[0], [0]] while True: memo.append([0]) for d in range(1, n): if d + 1 < n: sol = solve(n, d, memo[n-1][d] - 1) else: sol = solve(n, d) print(n, d, '->', sol, '( elapsed:', time() - start, ')') memo[n].append(sol) n += 1 main() ``` Output: ``` 2 1 -> 2 ( elapsed: 5.245208740234375e-06 ) 3 1 -> 2 ( elapsed: 6.246566772460938e-05 ) 3 2 2 False 3 2 3 False 3 2 -> 4 ( elapsed: 0.012233257293701172 ) 4 1 -> 2 ( elapsed: 0.012252330780029297 ) 4 2 4 True 4 2 -> 4 ( elapsed: 0.019064903259277344 ) 4 3 -> 2 ( elapsed: 0.01909017562866211 ) 5 1 -> 2 ( elapsed: 0.01910543441772461 ) 5 2 4 False 5 2 5 False 5 2 6 False 5 2 7 False 5 2 -> 8 ( elapsed: 6.083156585693359 ) 5 3 -> 2 ( elapsed: 6.083175420761108 ) 5 4 2 False 5 4 3 False 5 4 -> 4 ( elapsed: 6.109014987945557 ) 6 1 -> 2 ( elapsed: 6.109039783477783 ) 6 2 8 True 6 2 -> 8 ( elapsed: 6.180561542510986 ) 6 3 -> 2 ( elapsed: 6.180585145950317 ) 6 4 4 False 6 4 5 False 6 4 6 False 6 4 7 True 6 4 -> 7 ( elapsed: 34.04813623428345 ) 6 5 -> 2 ( elapsed: 34.048160791397095 ) 7 1 -> 2 ( elapsed: 34.04817223548889 ) 7 2 8 True 7 2 -> 8 ( elapsed: 34.29183101654053 ) 7 3 -> 2 ( elapsed: 34.29185700416565 ) 7 4 7 False 7 4 8 True 7 4 -> 8 ( elapsed: 35.03852438926697 ) 7 5 -> 2 ( elapsed: 35.0385627746582 ) 7 6 2 False 7 6 3 False 7 6 -> 4 ( elapsed: 35.16324186325073 ) 8 1 -> 2 ( elapsed: 35.1632719039917 ) 8 2 8 True 8 2 -> 8 ( elapsed: 35.805861949920654 ) 8 3 -> 2 ( elapsed: 35.80588483810425 ) 8 4 8 True 8 4 -> 8 ( elapsed: 37.375497817993164 ) 8 5 -> 2 ( elapsed: 37.37552309036255 ) 8 6 4 False ``` Looking at the timing, there were a couple of points where Z3 struggled badly: * ~5 seconds to prove `5,2` is not `7`-colorable * ~30 seconds to prove `6,4` is not `6`-colorable * ?? seconds to prove `8,6` is not `5`-colorable + Given that the answer is 7, it will require a major breakthrough to beat `8,6` in a minute. I'm pretty confident that naively plugging the graph into any SAT/SMT solver won't cut it. Initially I tried binary search on the number of colors, but I realized that Z3 takes a pretty long time to provide a `k`-coloring when `k` is larger than optimal, so I replaced it with a sequential search from the lower bound. The lower bound is the same as alephalpha's: > > memoizes the result for `f[n,d]` as a lower bound for `f[n+1,d]`. > > > An additional contribution of this answer is that, for even `d`, the graph has two connected components that are isomorphic, so we only need to compute the answer on one of them. Proof: * If `d` is even, this means `a` and `b` have equal parity (in terms of the number of ones), i.e. there is no path from an even node to an odd node and vice versa. Also, since `d < n`, there is always a way to flip two bits of a node in two steps (e.g. `10111...` and then `01111...`), so the graph has exactly two connected components. * "Hamming distance of `a` and `b` is `d`" is the same as "`a^b` has `d` ones". Assume `a` and `b` are even. Then the two are connected iff (if and only if) `a^b` has `d` ones. Now consider two odd nodes `a^1` and `b^1`. These two are connected iff `(a^1)^(b^1) == a^b` has `d` ones. The same holds when `a` and `b` are odd, so the two connected components have an isomorphism of `a <=> a^1`. The single connected component can be constructed with the rule of "there is an edge between `a` and `b` iff `a^b` has `d` or `d-1` ones". Proof: * Take the connected component of even nodes from the original graph. We can remove the least significant bit from all nodes to get the labels of 0 to `2**(n-1)`. The removed bit is the parity of the rest; I will call it the parity bit. * Given the two nodes `a` and `b` in the original space, "`a^b` has `d` ones" has two possibilities: + `a` and `b` have the same parity bit: `(a/2)^(b/2)` has `d` ones. + `a` and `b` have different parity bit: `(a/2)^(b/2)` has `d-1` ones. * The converse is also true: + `(a/2)^(b/2)` must have `d` or `d-1` ones; otherwise `a^b` cannot have `d` ones. + if `(a/2)^(b/2)` has `d` ones, `a/2` and `b/2` have the same parity, so `a^b` has `d` ones. + if `(a/2)^(b/2)` has `d-1` ones, `a/2` and `b/2` have different parity, so `a^b` has `d` ones. Also, I have set the upper bound to be `lower_bound * 2` (where the lower bound is `f(n-1,d)`), so in some cases the code skips one calculation when the graph is not `upper_bound - 1`-colorable. Proof: * The graph for `n,d` equals two disjoint copies of that of `n-1,d` plus extra edges in between. The nodes of `n,d` can be split by their first bit, and observe the follows: + `0{a} ^ 0{b}` (where `a` and `b` contains `n-1` bits each) has `d` or `d-1` ones iff `{a} ^ {b}` does. The same holds when 0 is replaced with 1. + Therefore, the [induced subgraph](https://en.wikipedia.org/wiki/Induced_subgraph) of `n,d` by selecting all nodes with the first bit of 0 (or 1) is `f(n-1,d)`-colorable. * Take a coloring of `n-1,d` using `k` colors. There exists an `2k`-coloring of `n,d`: Color the first half using colors `1` to `k`. Color the rest using colors `k+1` to `2k`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 370 bytes, `8,5` in a minute on TIO ``` f[n_, d_] := f[n, d] = Block[{c, k}, k = If[n < d + 1, 1, f[n - 1, d]]; While[! SatisfiableQ[ Array[BooleanCountingFunction[{1}, Table[c[#, i], {i, k}], "CNF"] &, 2^n, 0, And] && Array[If[ DigitCount[BitXor[#, #2], 2, 1] == d, ! c[#, #3] || ! c[#2, #3], True] &, {2^n, 2^n, k}, {0, 0, 1}, And]], k++]; k] ``` [Try it online!](https://tio.run/##TZBfS8MwFMXf/RR3K/SlGWz1TZ2wbgz2IoqCQogj9s92aZdATR9G1s9e781UGtqS0@Te87vnpN2xPGmHuR6GSpq9gGKv4G4JN0CSlALeQ9bYvJY@F1D39NLPHZ3DAxSQwELww3rGm0Kpe66B9yM2pZzAKxl8V6i/mvJF8gGtVdvqs8ysbUpt1rYzDs1h25ncoTXSL8jljQtkLiMBqAR4ZHPa/HbgNV0/bacKYgHpJ9HOBawMIcfx/6WrD8GOqjZ4QBc8ZYbuw7ZsEaXUOqVJaOLl2AMKARMIGNGtgsvlqtIgibLtykDgA0L4cEZ@PiYlwSMxHdXUSUIR1WrYWPncInF4zrqH2eNf7DywCUA7U6FBd@aeRUg65Nyr4Qc "Wolfram Language (Mathematica) – Try It Online") Uses Mathematica's built-in SAT solver, and memoizes the result for `f[n,d]` as a lower bound for `f[n+1,d]`. [Answer] # [Python 3](http://python.org/) + [PySAT](https://pysathq.github.io/), `8,5` ``` from pysat.solvers import Cadical153 as Solver from pysat.card import CardEnc from pysat.formula import IDPool import time chromatic_dict = {} def colorable(n, d, k): s = Solver() pool = IDPool(start_from=(k << n) + 1) for i in range(1 << n): cnf = CardEnc.equals(lits=[(i * k) + l + 1 for l in range(k)], vpool=pool) s.append_formula(cnf.clauses) for i in range(1 << n): for j in range(i + 1, 1 << n): if (i ^ j).bit_count() == d: for l in range(k): s.add_clause([-(i * k) - l - 1, -(j * k) - l - 1]) return s.solve() def chromatic(n, d): if (n - 1, d) in chromatic_dict: k = chromatic_dict[(n - 1, d)] else: k = 1 while not colorable(n, d, k): k += 1 chromatic_dict[(n, d)] = k return k if __name__ == "__main__": n = 1 start_time = time.time() while True: n += 1 for d in range(1, n): chromatic_number = chromatic(n, d) time_elapsed = time.time() - start_time print(f"[{time_elapsed}] {n},{d} -> {chromatic_number}") ``` A port of [My Mathemactica answer](https://codegolf.stackexchange.com/a/263302/9288), using [PySAT](https://pysathq.github.io/) with [CaDiCaL](https://github.com/arminbiere/cadical) SAT solver. [Answer] # [Wolfram Language (Mathematica 13.0)](https://www.wolfram.com/wolframscript/), 392 bytes, `11,6` in a minute on my laptop Just implementation. Use `VertexChromaticNumber` instead of `IGraphM`IGChromaticNumber` to get vertex-chromatic number, \$ \color{red}{\text{some results are not correct.}} \$ ``` GetChromaticNumber[n_, d_] := Module[{nodes, edges, g}, nodes = Tuples[{0, 1}, n]; edges = Select[Subsets[nodes, {2}], HammingDistance[#[[1]], #[[2]]] == d &]; g = Graph[UndirectedEdge @@@ edges]; VertexChromaticNumber[g]] (*To use the function,enter the two integers as arguments.For \ example:*) Do[Print[{n, d} -> GetChromaticNumber[n, d]], {n, 2, Infinity}, {d, 1, n - 1}] ``` \$ \begin{array}{c|ccccccccccc} n\backslash d & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \hline 2 & 2 & - & - & - & - & - & - & - & - & - \\ 3 & 2 & 4 & - & - & - & - & - & - & - & - \\ 4 & 2 & 4 & 2 & - & - & - & - & - & - & - \\ 5 & 2 & 8 & 2 & 4 & - & - & - & - & - & - \\ 6 & 2 & 8 & 2 & 7 & 2 & - & - & - & - & - \\ 7 & 2 & 8 & 2 & 8 & 2 & 4 & - & - & - & - \\ 8 & 2 & 8 & 2 & 8 & 2 & 7 & 2 & - & - & - \\ 9 & 2 & 15❌ & 2 & 16 & 2 & 11 & 2 & 4 & - & - \\ 10 & 2 & 17❌ & 2 & 33 & 2 & 20 & 2 & 7 & 2 & - \\ 11 & 2 & 19❌ & 2 & 56 & 2 & 35 & 2 & 12 & 2 & 4 \\ \end{array} \$ --- [`VertexChromaticNumber` function](https://reference.wolfram.com/legacy/language/v13/ref/VertexChromaticNumber.html.en) was Introduced in 13 (13.0) Whereas [TIO Mathematica version is 12.0.1](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJFrJFyGmUJZaVJyZn2eloKSjoBIG4cRac0FV@hekFgHV5aUrFFcWl6TmQpTBRYPBgrHW//8DAA) ``` Print["Mathematica version: ", $Version]; Print["Operating system: ", $OperatingSystem]; Mathematica version: 12.0.1 for Linux x86 (64-bit) (October 16, 2019) Operating system: Unix ``` ]
[Question] [ Motivated by [this challenge](https://codegolf.stackexchange.com/questions/260743/calculate-euclidean-distance-on-a-torus) ### Background Let we have a square sheet of flexible material. Roughly speaking, we may [close it on itself four ways](https://en.wikipedia.org/wiki/Fundamental_polygon#Examples_of_Fundamental_Polygons_Generated_by_Parallelograms): [![enter image description here](https://i.stack.imgur.com/gMSjv.jpg)](https://i.stack.imgur.com/gMSjv.jpg) Here the color marks the edges that connect and the vectors indicate the direction. The sphere and torus are obtained without flipping the sides, Klein bottle — with one flipping edge, and projective plane with both. Surprisingly torus, not a sphere, in many senses is the simplest construct. For example, you [can't comb a hairy ball flat](https://en.wikipedia.org/wiki/Hairy_ball_theorem) without creating a cowlick (but torus can). This is why torus is often used in games, puzzles and research. ### Specific info This is a separate picture for fundamental polygon (or closing rule) of projective plane (for `1..N` notation): [![enter image description here](https://i.stack.imgur.com/DaXpb.jpg)](https://i.stack.imgur.com/DaXpb.jpg) Neighborhood of `[1, 1]` cell for `N x N` lattice: [![enter image description here](https://i.stack.imgur.com/N2rdI.jpg)](https://i.stack.imgur.com/N2rdI.jpg) Example how to find distance for points `(2, 4)` and `(5, 3)` in `5 x 5` projective plane: [![enter image description here](https://i.stack.imgur.com/JhHkl.jpg)](https://i.stack.imgur.com/JhHkl.jpg) Green paths are shortest, so it is the distance. ### Task For given two points and size of lattice, find euclidean distance between points on the projective plane. ### I/O Flexible, in any suitable formats ### Test cases For `1..N` notation `N, p1, p2 → distance` For a better understanding, also indicated distance on torus (for same points and size): ``` 5, [1, 1], [1, 1] → 0.0 (0.0) 5, [2, 4], [5, 3] → 2.24 (2.24) 5, [2, 4], [4, 1] → 2.0 (1.41) 10, [2, 2], [8, 8] → 4.12 (5.66) 10, [1, 1], [10, 10] → 1.0 (1.41) 10, [4, 4], [6, 6] → 2.83 (2.83) ``` [Answer] # [julia](https://julialang.org/), ~~104~~ 97 bytes This solution uses the quotient space metric. For the projective plane, if \$\sim\$ is the equivalence relation induced by the edge identification (i.e. \$(p, 0) \sim (N-p, N); (0, p) \sim (N, N-p)\$) and \$d\$ is the Euclidean metric, then the projective plane metric is $$ d'(a, b) = \min\_{w \sim w'} [d(a, w) + d(b, w')]. $$ To implement this, we create two grids \$x\$ and \$y\$ spanning \$[0, N]^2\$ such that \$x\_{ij} \sim y\_{ij}\$ and compute \$d(a, x\_{ij}) + d(b, y\_{ij})\$ for each corresponding pair of grid entries. We make the vertical spacing between grid points \$0.005\$ to make sure that the result is correct to two decimal places. ``` u&v=((h=u-v.-.5)'h)^.5 g(N,a,b)=minimum(w->a&w+b&((N.-2w)any(w.%N.==0)+w),vcat.((r=0:.005:N)',r)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZBRCoJAEIbfPcW-pDM4u6ymIsJ2BC8QBVuQGiohrkvQTXrppZt0iW5TYQWB9DQz_N_w_zPn697Ulb5crqbf8fSujTsogFIZPgguYvRKXIvYKSAnTRtUTdVWjWnA8oV2rb9xAXLBQ4u6PYIVs1woJdG3SMNW9wKgUzITUsZZjh51iG-jWwExsWVALFh9KrLTgh26qu3r1hn1kFj00p_9_J8eTewHcgTCF5ASSyeBb4LnEMhJJHqbJMSSH2C85fO8Bw) Thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) for a 7-byte improvement! ### How? ``` # u&v is the distance between u-0.5 (centre of cell u) and v. u&v = ((h = u - v .- .5)'h)^.5 # Minimise the function w -> d(a, w) + d(b, w') g(N, a, b) = minimum( # (N .- 2w)any(w .% N .== 0) + w is N-w on the edges of x and w otherwise. w -> a&w + b&((N .- 2w)any(w .% N .== 0) + w), # Map over a grid of pairs [x1, x2] spanning [0, N]^2. vcat.((r = 0:.005:N)', r) ) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _~jUŒHƲ€N⁹ṭ"_þ/ẎÆḊ€Ṃ ``` A dyadic Link that accepts the size on the left and a pair of pairs (the points) on the right and yields the Euclidean distance of the projective plane. **[Try it online!](https://tio.run/##AUMAvP9qZWxsef//X35qVcWSSMay4oKsTuKBueG5rSJfw74v4bqOw4bhuIrigqzhuYL///8xMP9bWzIsIDJdLCBbOCwgOF1d "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##fY8tEsIwEIU9p8igk2mSpn83QOFQnU4VptMLYJgBgUAguAQGDIoiMB24R3qRsN2kpcBA1M63L@@9LeZluTAmXxaz@37yODfr47RZVbo6jfP65unrrt7oyxawrtamPngwmRReQAlTGSUpU5QEWTt9MYQpzEwg9SmRFgpgsp04Jf4/oewtxcAyARojjSlJLPQ7SyYHngICWIIYPgnex3OXLjplBMIQhSEl0Y@DMoMQHbCqcA4jYjlk44fAdfjk6qVvq@ECW8Mh8duiT@C292ClnBkUDXGRPQE "Jelly – Try It Online"). ### How? ``` _~jUŒHƲ€N⁹ṭ"_þ/ẎÆḊ€Ṃ - Link: Size = S; Points = [[x1, y1], [x2, y2]] _ - {Size} subtract {Points} -> [[S-x1, S-y1], [S-x2, S-y2]] € - for each of these pairs, [a, b]: Ʋ - last four links as a monad: ~ - bitwise NOT (vectorises) -> [-1-a, -1-b] U - upend -> [b,a] j - join -> [-1-a, b, a, -1-b] ŒH - halve -> [[-1-a, b], [a, -1-b]] N - negate -> [[a+1, -b], [-a, b+1]] ⁹ - chain's right argument -> [[x1, y1], [x2, y2]] " - zip with: ṭ - tack -> [[[S-x1+1, y1-S], [x1-S, S-y1+1], [x1, y1]], [[S-x2+1, y2-S], [x2-S, S-y2+1], [x2, y2]], ] / - reduce by: þ - table with: _ - subtraction Ẏ - tighten ÆḊ€ - vector norm of each Ṃ - minimum ``` [Answer] # [Python 3](https://docs.python.org/3.8/), 94 bytes ``` lambda n,X,Y,x,y:min(abs(X-a+(Y-b)*1j)for k in[-n,n]for a,b in[(x,y),(n+1-x,y+k),(x+k,n+1-y)]) ``` [Try it online!](https://tio.run/##VY5NDoJADIX3nKLLVkrCKBpCwj0gymKIEkegEMQfTo8ziiau@t7Xvrb9NJ472cT9MFfpYW50Wx41CGec85OnpDWCurxiFmgf86CklbpQ1Q1Qg5F9ICyFc5pL59FGiFF8FVjl11Y//Zqdn6ig@XE2zQlU4tkLaE@4vk2kp7tu0Eh/G5HIg34wMmKFvzeI5i3DXjGo4ls9R9YMkSNWb/5J9J5R4QetHYoZ4gX9NlmjwgVGS3THsCte "Python 3.8 (pre-release) – Try It Online") Easier to understand as: ``` lambda n,X,Y,x,y:min(abs(X-a+(Y-b)*1j)for a,b in[(x,y),(n+1-x,y-n),(n+1-x,y+n),(x-n,n+1-y),(x+n,n+1-y)]) ``` [Try it online!](https://tio.run/##VY7BDoIwDIbvPEWPnXQJEyTExPeAIIcRIcxgJYiKT4@bAsZTv3772657Dc2Vw6Trp/pwnFp9KU8amFLKaKTX/mIYdXnDVGofM1mKjTqL@tqDphIM52hDgpB9JS1J/rHveJRMrneZ0V@4ENOzMW0Fau/ZW2iPuXe76VA9dIuGu/uAQnjQ9YYHrHH9kBDTjiBXBKpYqufMliByxnL4b6JPRgVftXUqIUhmtW6yjQpmGc2jMUFcvAE "Python 3.8 (pre-release) – Try It Online") Fixes one point in place, and picks the closest version of the other point out of 5 options -- the original and the four reflections across the edges of the square. There's no need to consider diagonally-adjacent copies because they're always further from the fixed point than the original. [Answer] # [Python](https://www.python.org), 83 bytes (-35 thanks to @xnor) ``` lambda N,A,B:min(map(abs,(B-A,C:=B-1j*N-~N-2*B.real-A,D:=1+1j-C-2*A,C+2j*N,D+2*N))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY-xboMwEIZ3nuK22OSwsEMQQmIIyczSMc1AGlCIDLYcUrVLxz5A1yyRqvZ5umbtk9QEkrbL-e6_T__9Pn7q53armtN7mdx_HNrSi853Mq_XmxwynGEa11VD6lyTfL1HknoznMdJ6vGdm3kvmSfclJkil1ZfxAkf8503t6KlxsIiuBgLN6OUDtbHqtbKtFDn7dZxSmVAQtWA0kVDfBo7UKGCBCTba1m1ZPT9-jaiTp_E6sVjLkllBXUd1EDSpb-yujZV05ILjgpNnBh1aDaktNKDqrUsnog7o799SikKiipJzBDxdP6aIiw5Al9dX7AxwGc-EFuo0-0FQtDtbT_p94KJAEhX_xPBzUFYBwDCWcCpw_2eER0TIUQ9EzAugExZGA7ILYgduL-CC8W7LH98guFWiBAOiGDRpIsTTYaP_QA) ### Obsolete [Python](https://www.python.org), 118 bytes ``` lambda N,A,B,o=.5+.5j:min(map(lambda x:abs(A-o-x),[B:=B-o,C:=N/o+B-2*B.real,-B,2*N-B,2j*N-B,4*N*o-B,-C,C+2j*N,2*N-C])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZBBboMwEEX3nGJ2tcngYgcQQmIR2HOBlAVpQCECjAiJ0gv0AN1mE6lqz9Nttj1J7eCk7WbG_v9p5tunz_5l3Mju_F7FTx_7sXLCy6Ep2tW6gAwXmKCMmT9j_jZq6460RU-Me4yK1Y4sHOkcKS6TKE4ciWkUZ49yljjCTthQFg06CQo703V7bZ6d2VJ1J8V0prWrneaUmu2nuu3lMEJbjBvLquQADdQdyL7siEsjC2qUEEPDdn1Tj-Th-_XtgVpTWKWXh6IhtRLk7SINSZdurvR-qLuRmLfhEMWD3HdrUinpWbZ9Ux6JvaC_54RSFFR9QzyYiOfLl4-w5Ag8v3VQMcBlLhBVqKV9geBpX53nky-Y8IDo-p_w7hOEmgBAOPM4tbg7MUIzIUI4MR7jAojPgsAg9yDqwt0crhTXWf7M8cyuACEwiGDhXMcJ5-ZhPw) Expects input coordinates as complex numbers. [Answer] # Python3, 458 bytes ``` R=range E=enumerate def T(d,x,y,X,Y): if y%2:d=[[(*a,W+Y*len(d),k)for k,(*a,_,_)in E(i[::-1])]for W,i in E(d)] if x%2:d=[[(*a,W,k+X*len(i))for k,(*a,_,_)in E(i)]for W,i in E(d[::-1])] return[j for k in d for j in k] def f(n,p,P): d=[[(i,j,i-1,j-1)for j in R(1,n+1)]for i in R(1,n+1)];O=[*T(d,0,0,0,0),*T(d,0,1,0,-1),*T(d,1,0,1,0),*T(d,0,1,0,1),*T(d,1,0,-1,0)] return min(((X-x)**2+(Y-y)**2)**0.5 for a,b,x,y in O for A,B,X,Y in O if[a,b]==p and[A,B]==P) ``` [Try it online!](https://tio.run/##dZFda4MwFIbv/RXnZpDocRj7QXF4sUGvW8qgLUGKQ92iayrBQv31Lh9b14@NEHLO@yTvyUnavvs4yNGsVcOwSlUu30tvnpbyuC9V3pVeUVbwSgo8YY8b3NLEA1FB/xAnRco58XNcB1v/s5SkoNjQ6qCgQSPvcEeFhDkRPElCltHMsDUKsGpBM@t0unTCJthYL0H/dLr1@HH2QJXdUUlegz1mcGHD2oRNZtuoiMQWl6YFW1FgjSJkWIeMnveuCEMZMFdJXClPi5T75i0iNyh@Z0xP7eFS5oQreMlCA883hr2QhJBNeKK@HwdkG/Ym0DN6nNgOcnwzj29usrDCM76Yn3CCqLjekKVpC7ksuGY6XtKhVUJ2pCIT5AyBZQhupdT7RcBjhLFhOh79x8Y351jkYGzgDGF2B88VdcKiOzz@Np4iTDUcvgA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` ⊞υηF⟦θ±θ⟧F²⊞υEη⎇⁼κμ⁻⊕θλ⁺λιI₂⌊EυΣXEι⁻λ§ζμ² ``` [Try it online!](https://tio.run/##NY29rsIwDIV3nsKjI5mBqkydrhADA6gCtqpDVHxvI9KEpgl/Lx8MV1iybJ1jf6frdei8tjnXaeoxEfSqmv36ANiMBDv@05FxVK2Cj1go@B5u9QV7giMHp8MD12PSdsIzwaDENC5NuHFd4IFd5JMwCKx0bcWwBEZJVbM6GBdxpaeIByEE3nsfUd7NkAZ8Z0jUQdba3zh8BPPFC@UnbtyJ7/h8xyrBF@q/qpybJUFTEJStzJJg0bZ5frUv "Charcoal – Try It Online") Link is to verbose version of code. Takes the size and the two points as input. Explanation: ``` ⊞υη ``` Push the first point to the predefined empty list. ``` F⟦θ±θ⟧F² ``` Loop over each orthogonal direction. ``` ⊞υEη⎇⁼κμ⁻⊕θλ⁺λι ``` Push the transform of the point in that direction to the list. ``` I₂⌊EυΣXEι⁻λ§ζμ² ``` Output the minimum Euclidean distance from the second point to any of the five points inthe list. I tried writing it as a single expression but it still came out to 41 bytes: ``` I₂⌊E⊞OE⁴Eη⎇﹪⁺ιμ²⁻⊕θλ⎇÷ι²⁺λθ⁻λθηΣXEι⁻λ§ζμ² ``` [Try it online!](https://tio.run/##TY7NCoMwEIRfJccV0kPFnnoq7cWDVGpv4iHoQgIx0ZjYn5dPkwhtB5Zhh53l6zkzvWbS@9oIZeHMFgvN7JjBm9YWKqHE6Eao2AS1W/h1QsOsNikoKInGKbmjUcy8oNKDkxpq6RYQlIwZJXmY8CUEpeoNjqgsDjCHVGa/YqnsRaxiwFiLlfRCUjJ/62mJooSHaQJVrR@4oYi/q5Mt1YBPeEeALCFsOnrfHihpc0qKLnjg33ed363yAw "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # JavaScript (ES6), 104 bytes *Saved 9 bytes by refactoring in a way similar to [what xnor did](https://codegolf.stackexchange.com/a/261202/58563)* Expects `(N,x1,y1,x2,y2)`. ``` (N,x,y,X,Y)=>Math.min(...(g=q=>[x,x+q,N-x].map((v,i)=>Math.hypot(X-v,Y-[y,N-y,y+q][i])))(N++),...g(1-N)) ``` [Try it online!](https://tio.run/##dc7BboMwDAbge58iR1s4hqTp1At9g3FuhTigrgWmlsBAiDw9S4mqHdpJ/iUfPv32dzmVw/mn6UbZ2q/Lck0XyGgmR0c6YXr4LMea700LzAxV2qeHfKY56imTc8H3sgOYqHnC2nV2hKOc6CRz540jF/VF3hSICFkUIfmeCpTMEJezbQd7u/DNVnAFsSOh1glBFHEsEk42r06TMN74TWyD06zN/9D8FeqXQpWszo/YPxKcYaXfwPDhuiUBqreFJhz@eOR5eL9dfgE "JavaScript (Node.js) – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 168 bytes Golfed version. [Try it online!](https://tio.run/##dY7BboMwEETvfMUe7WATILSKqKjUYw/lElUiqnowFFIjIASsCor4drqGNhdSazRer57G0yaiEJMs63OjoNUPqxTq0xraS6MYlLIaDeMc52mi4EXICobpI80gI6H/XCnWzd7PHs1@1E6D4UsURLCYBqTjETuaPQ@5Qx/IIb3gXvCQRWand6tbmCH9ljVosudHFjN05EM@T2aIqRRb1kMi2pRIltPgUdclciPNfJPT0dK9JwBdtcTWRDSn1oenphH920E1sjq9Ux9eK6kggMEAPDVuVVGRjNwxcK6iFLZbsC17DbkMPAY47BbItVzvP8q7RrmrKMeeKdQetVCe5bg3sN9SerIX0LkZt/x4j/r7dL9DbDTG6Qc) ``` def f(N:Int,x:Int,y:Int,X:Int,Y:Int)={val(a,b)=(x-X,Y+y-N-1);(Seq(a,a-N,X+x-N-1,X+x-N-1,X+x-N-1,a+N)zip Seq(y-Y,b,y-Y-N,N-b,y-Y+N,b)).map{case(i,j)=>sqrt(i*i+j*j)}.min} ``` Ungolfed version. [Try it online!](https://tio.run/##hVDBasJAEL3nK95xV9OYxLSIYKHQSw/NpRSU4mETo11JYprdFlPx29NJNqaIlsIsszPvzZvdp2KRirqWWbErNVRTOZnQ785BfZTaRibzo2Xtom0SazwLmeNgAatkjTULp3jKibPvctXleZcXbeZTPO4@ozTBrJ0FvkQKQdVDWYqK7XGDOYk0iU5I8xi2ZUjH@680c0OEvNeOeu2KwAU9hPDqd6TtmlVNh53B/IQPG/wc6jespNIijxNFm5jAtywQcfKtOCAWKgGTNrYcs3s0LjI5kKSzHVDr2Gr08w75Sx2y2JiakcNMlBs1NT94e9GlzDdLMvE1l7q3sKCuTnO2Zrd286UuOMdoBNdxL0m@jcAGXcaG5Dt@8Bcr6KX8CynPbVkUEwrDChzPv0LrHtXcXEP0rsqZjXcUp6WTcWvK0arrHw) ``` import scala.math.{sqrt, min} object Main { def f(N: Int, x: Int, y: Int, X: Int, Y: Int): Double = { val a = Array(x - X, x - X - N, X + x - N - 1, X + x - N - 1, X + x - N - 1, x - X + N) val b = Array(y - Y, Y + y - N - 1, y - Y - N, N - (Y + y - N - 1), y - Y + N, Y + y - N - 1) val distances = (a zip b).map{ case (i, j) => sqrt(i*i + j*j) } distances.min } def main(args: Array[String]): Unit = { println(f(5, 1, 1, 1, 1)) // 0.0 println(f(5, 2, 4, 5, 3)) // 2.24 println(f(5, 2, 4, 4, 1)) // 2.0 println(f(10, 2, 2, 8, 8)) // 4.12 println(f(10, 1, 1, 10, 10)) // 1.0 println(f(10, 4, 4, 6, 6)) // 2.83 } } ``` ]
[Question] [ ## Challenge Given the Cartesian coordinates of two or more distinct points in Euclidean n-space (\$\mathbb{R}^n\$), output the minimum dimension of a [flat](https://en.wikipedia.org/wiki/Flat_(geometry)) (affine) subspace that contains those points, that is 1 for a line, 2 for a plane, and so on. For example, in 3-space (the 3-dimensional world we live in), there are a few possibilities: 1. The points are not coplanar, e.g. `(0,0,0),(0,0,1),(0,1,0),(1,0,0)`. The full 3 dimensions would be needed to describe the points, so the output would be `3` 2. The points are coplanar but not all collinear, e.g. `(0,0,0),(1,0,0),(0,1,0),(1,1,0)`. The points lie on a 2-dimensional surface (a plane), so the output would be `2`. 3. The points are collinear, and there is more than one, e.g. `(0,0,0),(1,0,0)`. They all lie on a line (1-dimensional), so the output is `1`. 4. One or zero points are given. You do not have to handle these degenerate cases. As @user202729 pointed out in sandbox, this is equivalent to the [rank](https://en.wikipedia.org/wiki/Rank_(linear_algebra)) of the matrix whose column vectors are the given points if one of the points is the zero vector. I encourage upvoting answers that don't have built-ins do most of the work, but they are valid answers. ## Details 1. The coordinates of each point will always be integers, so errors due to excessive floating-point roundoff are not acceptable 2. Again, you do not have to handle fewer than 2 points 3. The dimension `n` will be at least 2 4. The set of points can be taken in any format that encodes equivalent information to a list of n-tuples. Your program/function may also take `n` as input if you desire. 5. Note that the subspace may not necessarily pass through the origin\* 6. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytes wins \*Mathematically, if we require the subspace to pass through the origin, then it would be more specifically called a "[linear subspace](https://en.wikipedia.org/wiki/Linear_subspace)", not just [flat](https://en.wikipedia.org/wiki/Flat_(geometry)). ## Testcases ``` n points -> output 2 (1,0),(0,0) -> 1 2 (0,1),(0,0) -> 1 2 (6,6),(0,-2),(15,18),(12,14) -> 1 2 (0,0),(250,500),(100001,200002) -> 1 2 (0,0),(250,500),(100001,200003) -> 2 2 (3,0),(1,1),(1,0) -> 2 3 (0,0,0),(0,0,1),(0,1,0),(1,0,0) -> 3 3 (0,0,0),(1,0,0),(0,1,0),(1,1,0) -> 2 3 (0,0,0),(1,0,0) -> 1 4 (1,2,3,4),(2,3,4,5),(4,5,6,7),(4,4,4,4),(3,3,3,3),(2,2,2,2) -> 2 5 (5,5,5,5,5),(5,5,6,5,5),(5,6,5,5,5),(6,5,5,5,5),(5,4,3,2,1) -> 4 ``` Related Challenges: * [Is the matrix rank one?](https://codegolf.stackexchange.com/questions/143528/is-the-matrix-rank-one) * [Linear Independence.](https://codegolf.stackexchange.com/questions/78079/linear-independence) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` MatrixRank@*Differences ``` [Try it online!](https://tio.run/##jZBPS8QwEMXv@RTLHuUJmbSJghQ87FUQr6WHsKRY3K3QRhBCPnudpH/Wggc7kHl9@c3wyNX6d3e1vjvbqa2mF@uH7vvN9h/Pd6eubd3g@rMbp9NnLYJ3o8fgxq@Lj1X6mfWTeB263tdtnbwGh2NVHXGYLxshEG4sggghEGREkHxGUESyZBJ7y8Bk615xIw16TF2Byt9jaZPSElomRZI/gkpN/Q8rGFMzVmSMchTKUdQ2v0ZectKCzomLPUYbvmJ/blunl5CcBwXKFDR1aFZ8wuAhq1ysCuTKXK7bZo2l@FLn0VWbzTc7puRV/KS8oowixmb6AQ "Wolfram Language (Mathematica) – Try It Online") Alternative: (23 bytes, 21 characters) ``` MatrixRank[#&@@#-#]& ``` [Try it online!](https://tio.run/##jZDNasMwEITveooQQ04T0EqWWyiGHHotlF6ND6I41KRJwVEgIHTusY/aR3BX8k9q6KFe0I5H3y6Djta9NUfr2lfb78v@ybquvb7Y06HKNrtdts2@vz7rTf/4UQnvmrND15wv7y6U8WfQD@K5a0@u2lfRq7Fal@Uaq@GyFgL@xsIL7z1BBnjJZwAFREtGsbQKFMnaKm5kQPexK1D@eyxuUkbCyKhI8kdQsan/YZoxNWA6YZSiUIqi5vkp8piTRnRIrJcYzfiE/bltmh5Dch5o5DFo7DCs@ESBu6RSsdJIlbhUt80GY/GlSaOTLma/WDA5r@In5RV5ECHU/Q8 "Wolfram Language (Mathematica) – Try It Online") `SingularValueDecomposition` in Mathematica is already 26 bytes long. [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` t1Y)-X$&Yvoz ``` Input is a matrix, where each row defines a point. [Try it online!](https://tio.run/##y00syfn/v8QwUlM3QkUtsiy/6v//aFMdKLRWAFFmMKYZTNQMWYGJjrGOkY5hLAA) Or [verify all test cases](https://tio.run/##fU3LCsJADLz7FTmIIKSQ2ZfCXv0ED5ZS0LvipXjw57fJtgsFwR3IzGYmzOsxPcu9TOiP3W1/6D/vb7lcywCSTEIy7gYhNJkomexcJkTCWckRgoVY8y4KR1EB0Qd2Ru6v69X15oJhQ5a0bYysmbH4sjXRMquJH1O/2sGeg1YbccykgxOfTFRk8lxhmQo9i7wiU6z5Vaa2TdtA0HPHGGc). ### Explanation The code uses the singular value decomposition of a matrix, which is done symbolically to prevent floating-point issues. The rank of a matrix equals the number of non-zero singular values. ``` t % Implicit input: matrix of integer values. Duplicate 1Y) % Get the first row - % Subtract, with broadcast. This subtracts this row from each row X$ % Convert to symbolic matrix. Note that integers, are represented % exactly as floating-point values up to ±2^53. &Yv % Single-output singular value decomposition. Gives a vector with % the singular values o % Convert to floating point. Note that 0 is represented exactly % as a floating-point value z % Number of nonzeros. Implicit output ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 [bytes](https://github.com/abrudz/SBCS) ``` ≢⍸1≠1+2⊃8415⌶2-⌿⎕ ``` [Try it online!](https://tio.run/##nVG9agJBEO59iuvuJLNws7e70SYPkRcQIZhGSFoRK8X/FS0slWBlZxES0gXuUeZFznG4M7G7k4H5Y75vvmHa71310mt3314zmk46Gc0O5H@QZh/4oGk@bBi0tPzWipa/tNpehrIWjdd98quwQ4sR@a9wkB7JfzZrNN5wO4L0GIIK6zz/LEWQnriaM/O@FiHEdYhi9gH5nXoKsBwuBrwL58AJTmkOaAEbl6gBTUWiRISjyMA/Gbqs/Lg4PD8Ec75/JyXVuPDKWXDdr@tGB5Z9pYYEDKMlguWMPTh4lEyMswTEZE6sokYLuTGDFf4id9e@u5kxvI9fXOwx2Rk "APL (Dyalog Unicode) – Try It Online") Happens to be a mix of existing MATL and Mathematica solutions. Performs Singular Value Decomposition on pairwise differences of the rows, and counts nonzero eigenvalues in the result of SVD. Since APL does not have symbolic computation, we use "significantly different from zero" test instead. ### How it works ``` ≢⍸1≠1+2⊃8415⌶2-⌿⎕ 2-⌿⎕ ⍝ Pairwise row differences of the input 2⊃8415⌶ ⍝ The second matrix (diagonal matrix of eigenvalues) in SVD 1≠1+ ⍝ Check if each number is significantly different from zero ≢⍸ ⍝ Count ones ``` [Answer] # [Julia 0.7](http://julialang.org/), 18 bytes ``` m->rank(m.-m[:,1]) ``` [Try it online!](https://tio.run/##fY/RCoMwDEXf/Yq8TUFH0to6FtyPlD74IritQ8R9v8uiyMZgvbRJe2649Pq8D12z9O2SqsvUPW55OlYpnEuKxTK3IRAgI2A8lFlAoL334KWvDJMDOjEZoHozIRuH4BCZUBaBeRfzl1qlVihJCO2BuMZrMCnFL0abY2X0y/QuIWChZj3BsWzw0EhVsQWVcJXOONjETt1r57c3/0FrmZXvx5iN0/CY89SNeV/ORbG8AA "Julia 0.7 – Try It Online") Analogous approach in R is slightly longer (3 bytes saved by Giuseppe): # [R](https://www.r-project.org/), ~~27~~ 24 bytes ``` function(m)qr(m-m[,1])$r ``` [Try it online!](https://tio.run/##jY7BCsIwEETvfoUHD1mYQnbTRC9@iXiQQqGHVAwV/PuabXtorUUzbDbZeQyb@vrc18@26pp7ayI9kolFvICvdEh9beKtS83LVIZhVQSBEO13M8uCt6yAkK1CwB58AudHqVy5irAQb@FtDrP5MESbKOz@hN032EHXU9nJ/owaxbPKpNMV1yQvaP5FqitLl3UJlNPthwo45j7KTZJRlEdhmeAxV9jofsjWHCb9EPVv "R – Try It Online") [Answer] # JavaScript (ES6), 187 bytes There's probably a much shorter way. This is using the matrix rank method. ``` m=>m[m=m.map(r=>r.map((v,i)=>v-m[0][i])),n=0].map((_,i)=>(R=m.find((r,k)=>r[i]&&r[j=~k]^(r[j]=1)))&&m.map(r=>++j*r[i]&&R.map((v,k)=>r[k]-=k>i&&v*r[i]),n++,R=R.map((v,k)=>k>i?v/R[i]:v)))|n ``` [Try it online!](https://tio.run/##rZLNboMwDMfve4qeUBimjcPHpklh78A1yqaqLROlQEUnTtNenRm3VOrWqiANS/FfsfOzibNdtsvDqsn3n35VrzddprtSJ6UpdTkvl3vR6KRhIVrIXZ20fmmkNbl1Xai0tMfYO8dESoeyvFoL0UBBGw3lOU5jtvq7sG@ChNXouq7jnOGet308pqVDmePJwvq6SHLHaTlO1TwPUn2RRfHXdpFS@KUl7FfVrerqUO828139ITJhDIK0YCSt1PBs6rdYzPDhN1IC/jcyhpiRviKHEeBz7xVgOKbGjS77H1eRhEj2CiV9CKp36i51MjIYg1R/kAEjkW8UJ9/oVSR1Ocz8NCg8FRkzMkIGN5F4Rg9IHIdUd5BTH9LV8dAkIICwH1HvISJFK8TwxIqNVABsnMfG5a92GcHJKDli1KDj8358kRMSmt7tgAy7Hw "JavaScript (Node.js) – Try It Online") ]
[Question] [ *You find yourself in a strange place. A frighteningly dark maze, lit only by dim candles resting in the occasional hallway. Numerous paths lie only in impassable darkness, foreboding and--* ...Hm? What? Pick up a candle and carry it with you? No, no, that would be *extremely* rude. ## The Task Given a maze as input, output the minimum moves to solve it, or any falsey/invalid output if the maze cannot be solved. The catch: The maze is *very dark*, but is lit by candles placed on some of the grid squares. The player may only move in a direction if they can see light in that direction. ### Rules * Take the maze as input in any convenient format (string, 1d array, 2d array, etc). * `x` represents a wall, `@` represents the player, `^` represents a candle and `#` represents the exit. * The maze will be surrounded on all sides by walls, except for the player's starting space and the exit space, each of which will be in one of the walls. The corners will always be walls. * The player may only make orthogonal moves one space at a time in the direction of *visible light*. This is either a candle or the exit. * Candlelight only reaches the space it's on, but is visible from any distance. * Output the minimum number of legal moves the player can make to reach the exit, or any "invalid" value (such as a negative value, zero, false, the string "Unsolvable!", etc) if the maze is unsolvable within the rules. The player must move into the exit space to solve the maze. * Standard loophole restrictions and i/o rules apply. ### Test Cases 1- ``` Input: xxxxxxxxxx @^x ^xx x^ ^xxxxx xxxx x^ # x xx x xxx x ^ ^ ^x x x xxxx ^x xxxxxxxxxx Output: 15 ``` 2- ``` Input: xxxxxxxxxxxx x^ ^xxxxxxxx x x # x x^xxxx xxx x xxxx xxx x^ ^xxx^xxx xxxx@xxxxxxx Output: 19 ``` Once the player moves into a space that can see a new light source, such as the exit, they can then start moving towards that light source. 3- ``` Input: xxxxxxxx # xx ^x xx^ ^xx x ^xx xx xxxxx@xx Output: Unsolvable ``` 4- ``` Input: xxxxxxxxx @ ^x x xxxxx x x x^ ^x x x xxxxx x x^ ^x x xxxxx x x^ ^ ^x xxx#xxxxx Output: 10 ``` The player must take the shortest path. 5- ``` Input: xxxxxxxxx x ^ ^x xxxx xxxx # x x x^xx^xxxx x^ x x xxxx x xx x ^ x xxxx@xxxx Output: Unsolvable ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 229 bytes ``` T`#^`d s`@.* $&_ @\d|@ ( *\d) @=$1 (\d *) @|\d@ $1=@ m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d)) $1=$5 m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@) $1$5=$7 @ x }sT`=`@`.*0.* s`.*0.* _ ``` [Try it online!](https://tio.run/##VY@xCsIwEIb3e4oDg9xFLNpSXKy9h3AMMUIcHOxgHTrUZ6@XErEehOTnz/eFPG@ve3edpnNY@RChD1JYMOsLiIujIKF1kUEaswdyES2jjC4KmH0j8AieiApmq5TrqD1uy1PBlloq2TArMaJe0I43qa1yW2mrXk4aUy88M6JrwfwZken70tIlyWTqxhxAYIB3fw5NkFDYnf6mzztcpmlYDAwe/S/ggHlWKcwN5iYdETMzQ34OOvIVfAA "Retina 0.8.2 – Try It Online") Outputs `0` for unsolvable, since solutions must take at least one step. Explanation: ``` T`#^`d ``` Change the candle and exit to golfier characters, saving 7 bytes ``` s`@.* $&_ ``` If there are still squares to check, then increment the counter. (This allows the loop to terminate once it runs out of squares to check.) ``` @\d|@ ( *\d) @=$1 ``` Mark the square to the right if it is lit. ``` (\d *) @|\d@ $1=@ ``` Mark the square to the left if it is lit. ``` m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d)) $1=$5 ``` Mark the square below if it is lit. ``` m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@) $1$5=$7 ``` Mark the square above if it is lit. ``` @ x ``` Turn the squares that were checked into walls. ``` sT`=`@`.*0.* ``` If the exit still exists, then turn all of the marked squares into squares that need to be checked. ``` }` ``` Repeat the above until the exit is reached or no new steps could be taken. ``` s`.*0.* ``` If the exit was not reached then delete the count. ``` _ ``` Convert the count to decimal and delete the input. [Answer] # JavaScript (ES6), ~~196 ... 179~~ 177 bytes Takes input as a matrix of characters. Returns \$0\$ if there's no solution. ``` m=>(o=F=(X,Y,n)=>m.map((r,y)=>r.map((c,x)=>n?(h=x-X)*h+(v=y-Y)*v-1?0:c=='#'?o=o<n?o:n:r[(g=w=>1/(C=m[z+=v][w])?g(w+h):C<g)(x,z=Y)&&F(x,y,n+1,r[x]=g),x]=c:c=='@'&&F(x,y,1))))()|o ``` [Try it online!](https://tio.run/##lVJhi4JAEP3urxgSajdX7/wqTQZBv6EQF8IrvSPdsMO2uP/u7SYd6S5cjSDO23HmzXv7tW22p6z@PH77lfjYtXtsS5wTgSska7ZhFcV5GZTbIyE1u6ik7pKMSZVUMSlQ@ms6LTzS4MXf0Gnjh/F7lCFO3EksUMyqWERVVCckxzPOwzeyxDK5etikyTmlcU7OXkGj5SynRLIrbuh4vFJfF1Z5IasTmWJOmXpnt6aLyf04pCoI/RFtJqqTOOyCg8jJniQOQBIEwUj@xShld3DBJajgPVDyG9Kv1CnoE/cRBA3CoBK4fhQ8qFS1Ch70vFNyUkod51/uQ6LcBsNtKR0DsrzbQtqYgbSKwE0ZFq@Rfvjb1VOGGnBDf52DMVbPfVanR4s7Jbi5s@EQt9SBRV3@VD99C0zD3Zf87s0A4JYLBBaN9cJ9Lp2RQ4N1pdkPjLl6svUWdHu0vw "JavaScript (Node.js) – Try It Online") ### How? This is a depth-first search. We first look for the position of the player and then initiate the recursion. We keep track of the number of moves in \$n\$ and the length of the shortest path in \$o\$. Given the previous position \$(X,Y)\$, we iterate on all cells \$(x,y)\$ of the maze and compute \$dx=x-X\$ and \$dy=y-Y\$. We can move to the new cell if: * \$dx^2+dy^2=1\$ * and the first non-empty cell encountered along the ray \$(X+k\cdot dx,Y+k\cdot dy),k>0\$ is either a candle or the exit ### Commented ``` m => ( // m[] = input matrix o = // o = output, initially non-numeric F = (X, Y, n) => // F is the main recursive function: m.map((r, y) => // for each row r[] at position y in m[]: r.map((c, x) => // for each character c at position x in r[]: n ? // if n is defined: (h = x - X) * h + // h = dx, v = dy (v = y - Y) * v - 1 ? // if the quadrance is not equal to 1: 0 // abort : // else: c == '#' ? // if we've reached the exit: o = o < n ? o : n // update o if n is better : // else: r[ // wrapper to update r[]: ( g = // we use g to look for a candle w => // or the exit in this direction: 1 / (C = // move along (dx, dy) and store m[z += v][w] // the content of the cell in C ) ? // if C is a space: g(w + h) // keep moving until it's not : // else: C < g // success if C is not 'x' )(x, z = Y) // initial call to g at (X, Y) && // if the move is valid: F( // do a recursive call: x, y, n + 1, // at (x, y) with n + 1 r[x] = g // invalidate the current cell ), // end of recursive call x // actual index in r[] ... ] = c // ... to restore the cell : // else (n undefined): c == '@' && F(x, y, 1) // initiate the recursion if c is '@' )) // end of map() loops )() | o // initial call to F; return o ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+ for Windows, 162 bytes ``` $f={param($m,$l)++$l 1..4|%{switch -r($m){'@#'{$l}'@ *[#^]'{&$f($m-replace'@.','x@')$l}}$m=&{($a=$m[-1..-$m.Count])[0]|% t*y|%{-join($a|% Ch*($i++))}}}|sort -t 1} ``` [Try it online!](https://tio.run/##fVLLboMwELz7K1ZhU@PwUCK1h1ZCQspnRHGFUkdJZQIFotAC305tnubQmgPMjndndkSaPESWX4SUbYvnoEqjLIptjF2UzHFQkp3vP9frKn9ci9MFvExxrKKhRSuUDQ1hc7D4kVZPeFaMl4lURidBQ5@6tAwpU5cajIOnysYowPjgqXkexv4@ud@KIztsj/Uais23kvA@k@tNXVOF/WVj49VxGGuaps6TrACvgF3ThjYhrr17cQktp0MVCnkJ6vAelbz7HDj9Bl2yOgQawcgB14/CI6dYhelSgXWyr4viJMUXGDoj@oxyvDdQLiSgXFrlhtlwIYu3u5SGsr5l6f7JJp8X1x8wT9KjBvNb03wXWe@SG7bmGLjJgLkd/6NH52gkZ/2zwdANwM2owVxOOxvm9tlMYWnO6IF5mp63zFDLM6hhDRUhKMpUnArx4QLG0Y@AAPCdYCbyuywUUL9wT5AV2mPZE18wNbI3GOor0rS/ "PowerShell – Try It Online") Unrolled: ``` $f = { param($maze,$len) # len = $null if parm omited ++$len 1..4|%{ #recursive call switch -Regex ($maze){ '@#'{$len} '@ *[#^]'{ &$f ($maze -replace '@.','x@') $len # leave a wall behind to avoid infinite loops } } #rotate -90 $maze = &{ # new context to reinit $array and $i $array=$maze[-1..-$maze.Count] $array[0]|% toCharArray|%{ -join($array|% Chars($i++)) } } }|sort -Top 1 # Powershell 6+ for Windows # }|sort|select -First 1 # Powershell 5- for Windows # }|sort-object -Top 1 # Powershell for Linux } ``` [Answer] # [Perl 5](https://www.perl.org/), 238 bytes ``` sub f{%s=@_=(1,pop);while(@_){$i=shift;$m=shift;for(1..4){@a=$m=~/.+/g;!$s{$m=join$/,reverse map{$j=$_-1;join'',map/.{$j}(.)/?$1:0,@a}1..length$a[0]}++&&push@_,$i,$m};$_=$m;s/@( *[\^#])/'x@'.substr$1,1/e&&(/#/||return$i)&&push@_,$i+1,$_}} ``` [Try it online!](https://tio.run/##ZVLbcpswEH3nK9SgGlSryHTqh5pRqh/oW9/SiHFT2VbGGAbhlgyhv@7uCozJVDDS7tnLOSuoTH1cXy7u/JPsuvdOqlzGKa/KimV/DvZoYpWzjlrpDnbXZLQYjV1Zx2mSfGad2kpA/4pkKfbZO@o68J5Le6KC1@a3qZ0hxbbq6LOk@cc0w1AUcYBEAmAfJ0x8pelmxdW2h45Hc9o3B7p9WD32y@ViUZ3dQeWcWk6LPqM5kGVOqJh8ePihw0cmolZFCch3TU1TngqzWMQiFK@vtWnO9YlaNmuyTDnN@/5yBlXfjWs2m29lbUgDppP36ywoXhQ6Mg6idlqB0i2BpcFstT8RxY2gHwZwwks8SjQ@4HgUcHCCW7OIyHuSrvmcYOirbw7xfLh8bz1QtbeWpJ1p0Vc16g3HlxlHEGLJoESPk@BOxkos9VWrubBADSL0lXicSk8YmQTr//LwHq7DhzNdbylwGD3dEZnEIi82GcYbhkX0mkfGWqyeTT8MESDOsmD8hfGTss6DxUtM7ani1LQVk6462ifj43zFP2VjCt2Xjdz5RDZg1sUI@jJ@BxZBFwLgm6fG/CIYuYPs/vIP "Perl 5 – Try It Online") Rotates the maze 90° four times at each position. Easier to regexp-search-replace the entire maze as one string for `@ +[^#]` with `x@` + one less space when the next light or end is always ahead if at all. `@^` and `@#` with no space are replaced by `x@` so the `#` disappears which means the exit has been reached and we return `$i` steps taken. Array `@_` contains mazes to try out next. Hash `%s` keeps track of which mazes we've already tried so those are skiped. Nothing left to try in `@_` means no solution is to be found and `0` is returned. ]
[Question] [ (There exists some challenges that require to use the best strategy, but here we don't. Even if you are able to win, you are allowed to make a tie) # Challenge Write a program which plays the game tic-tac-toe. It must not lose (therefore, it should end the game either with a tie or by winning). # Allowed I/O methods 1. Input may be the current board. You can assume that all previous moves of the 2nd player were played by your engine. 2. Input may be the first player's moves, and your function stores which moves happened in the past. In this case the function is called multiple times, once for each move; or the function/program prompt input for multiple times. 3. You are allowed to take an extra input saying if you are the first player, or write two (possibly related) functions to solve the first-player problem and the second-player one. If your program need use the input method 2 (multiple call), you can decide what is passed in the first call. 4. Output may be the board after your turn. 5. Output may be your move. 6. A move may be represented as a pair of numbers (can be 0-indexing or 1-indexing), a number in range 0~8, or a number in range 1~9. 7. The board may be represented as a 3×3 array, or an array of length 9. Even if the language have 0-indexing array, you can use 1-indexing. 8. The cells on the grid may use any 3 different values to indicate `X`, `O` and empty. # Winning criteria Shortest code in each language win. [Answer] # Befunge, ~~181~~ 168 bytes ``` >>4&5pp20555>>03>16p\::5g8%6p5v ^p5.:g605$_ #!<^_|#:-1g61+%8g< 543217539511|:_^#->#g0<>8+00p3+5%09638527419876 v<304p$_v#:->#$$:2`#3_:^ >#\3#13#<111v124236478689189378 ``` Positions on the board are numbered 1 to 9. By default you get the first move, but if you want to allow the computer to go first, you can just enter 0 for your first move. When you've made a move, the computer will respond with a number indicating their move. There are no checks to make sure you don't enter a valid move, and there also no checks to see if anyone has won or lost. Once their are no more moves to be made, the program just goes into an infinite loop. It's a bit difficult to test this online, since there are no online interpreters with interactive input. However, if you know what moves you're going to make in advance (which assumes you know how the computer is going to respond), you can kind of test on TIO with those moves preprogrammed. **User plays first:** [Try it online!](http://befunge.tryitonline.net/#code=Pj40JjVwcDIwNTU1Pj4wMz4xNnBcOjo1ZzglNnA1dgogXnA1LjpnNjA1JF8gIyE8Xl98IzotMWc2MSslOGc8CjU0MzIxNzUzOTUxMXw6X14jLT4jZzA8PjgrMDBwMys1JTA5NjM4NTI3NDE5ODc2CnY8MzA0cCRfdiM6LT4jJCQ6MmAjM186Xgo+I1wzIzEzIzwxMTF2MTI0MjM2NDc4Njg5MTg5Mzc4&input=NSA5IDIgNiA3) **Computer plays first:** [Try it online!](http://befunge.tryitonline.net/#code=Pj40JjVwcDIwNTU1Pj4wMz4xNnBcOjo1ZzglNnA1dgogXnA1LjpnNjA1JF8gIyE8Xl98IzotMWc2MSslOGc8CjU0MzIxNzUzOTUxMXw6X14jLT4jZzA8PjgrMDBwMys1JTA5NjM4NTI3NDE5ODc2CnY8MzA0cCRfdiM6LT4jJCQ6MmAjM186Xgo+I1wzIzEzIzwxMTF2MTI0MjM2NDc4Njg5MTg5Mzc4&input=MCAxIDMgOCA2) To makes it easier to see what's going on, I've also got a version that outputs the board between moves. **User plays first:** [Try it online!](http://befunge.tryitonline.net/#code=Pj40JjVwcDIwNTU1Pj4wMz4xNnBcOjo1ZzglNnA1dgpeIHA1LjpnNjA1JF8gIyE8Xl98IzotMWc2MSslOGc8CjU0MzIxNzUzOTUxMXw6X14jLT4jZzA8PjgrMDBwMys1JTA5NjM4NTI3NDE5ODc2CnY8MzA0cCRfdiM6LT4jJCQ6MmAjM186Xgo+I1wzIzEzIzwxMTF2MTI0MjM2NDc4Njg5MTg5Mzc4CgoKPjU1KzosLDAgICAgID4xKzo1ZzglOjkqNDgqK1whITY1KyordgogdiRfICAgICAgICAgXiNgODo8PCwifCIkX3YjJTNcYDg6Oiw8CiAgICAgICAgICAgICA+OiMsXyReLCw6KzU1X3YKICAgICAgICAgICAgIF4iLSstKy0iLDorNTUwPA&input=NSA5IDIgNiA3) **Computer plays first:** [Try it online!](http://befunge.tryitonline.net/#code=Pj40JjVwcDIwNTU1Pj4wMz4xNnBcOjo1ZzglNnA1dgpeIHA1LjpnNjA1JF8gIyE8Xl98IzotMWc2MSslOGc8CjU0MzIxNzUzOTUxMXw6X14jLT4jZzA8PjgrMDBwMys1JTA5NjM4NTI3NDE5ODc2CnY8MzA0cCRfdiM6LT4jJCQ6MmAjM186Xgo+I1wzIzEzIzwxMTF2MTI0MjM2NDc4Njg5MTg5Mzc4CgoKPjU1KzosLDAgICAgID4xKzo1ZzglOjkqNDgqK1whITY1KyordgogdiRfICAgICAgICAgXiNgODo8PCwifCIkX3YjJTNcYDg6Oiw8CiAgICAgICAgICAgICA+OiMsXyReLCw6KzU1X3YKICAgICAgICAgICAgIF4iLSstKy0iLDorNTUwPA&input=MCAxIDMgOCA2) Note that you'll have to wait for TIO to timeout before you can see the results. **Explanation** The board is stored in the Befunge memory area as a flat array of 9 values, indexed from 1 to 9. This lets us use the zero offset as a special case "no move" when we want to let the computer play first. Player moves are stored as 4, and computer moves as 5. To start with all positions are initialised to 32 (the Befunge memory default), so whenever we access the board we mod with 8, so we'll get back either 0, 4 or 5. Given that arrangement, if we sum the values of any three positions on the board, we know that the computer is one move away from winning if the total is 10, the player is one move away from winning if the total is 8, and the positions are shared between computer and player (but still one position is free) if the total is 9. Our entire strategy is based around this concept. We have a routine that takes a list of triples indicating sets of three positions on the board, we calculate the sum of those positions, and if the sum equals a certain total, the computer moves to whichever of the positions in the set is free. The main list of triples that we test are the winning combinations (1/2/3, 1/5/9, 1/4/7, etc.). We first look for a total of 10 (the computer is about to win), and then a total of 8 (the player is about to win and we need to block that move). Less obviously, we also check for a total of 9 (if the player and computer each have one of the positions, it's a good strategy for the computer to take the third). Prior to that last scenario, the other strategic move we make is to check all the corner sets (1/2/4, 2/3/6, etc.) as well as two opposing corner combinations (1/8/9 and 3/7/8). If any of these combinations sum to 8, i.e. the player has taken two of the positions, it's a good strategy for the computer to take the remaining free position. Finally, there are a two special case moves. First, we always try and take the center position before any other move. This is achieved with the same routine as all our other moves, just passing in a single triple, 5/5/5, and a target sum of 0. Additionally, if all other test have failed to find a move, we try to take one of the top corners as a last resort. Again this is simply achieved by testing the triples 1/1/1 and 3/3/3, with a target sum of 0. I don't think this is necessarily a perfect strategy - there may be games that the computer draws which could potentially have been won - but it's good enough to never lose a match. I've run a test script that tried to play every possible move against the computer, and for every valid sequence of moves, the computer either won or drew the game. [Answer] # [Python 3](https://docs.python.org/3/), 18 bytes ``` lambda a:a+a%2*2-1 ``` [Try it online!](https://tio.run/##FcjLDoIwEEbhvU/xb0wqasJlZ@KrmExhkCa00wyDytNXOItvcfJmk6SuFP@cKfqBQA/Qlc5t1d6bkjUkc94dhpRXc5e90tSnF3qJ@2DFW3jBGHSxG5TzTD3jG2zCJqsi8c8Q5cN/ "Python 3 – Try It Online") This brilliant AI will always force a tie, and sometimes win if you let it. The grid is numbered in a spiral, like so: ``` 1 2 3 8 9 4 7 6 5 ``` and the computer always goes first. For the first move, input "10". This is a little redundant because it always goes in the same place, but it's already built into the algorithm so ¯\\_(ツ)\_/¯ By going in the middle first, the game is essentially converted into 1 dimension, with the only way to win being 3 in a row along the sides. The divides all of these remaining 8 squares into pairs, and always goes in the other square in the pair. For example, if you go in square 1, it goes in square 2. If you go in square 2, it goes in square 1. The nice thing about this system is that it will never make an illegal move, as well as never losing. This was actually from a magic trick invented by Martin Gardner, where you can predict the outcome of a game of tic-tac-toe. Every game ends the exact same, including rotation, or the computer wins. It "never loses". This is definitely my favorite solution to a code golf that I ever have found, and probably ever will find. [Answer] # Python 2: ~~399~~ ~~401~~ ~~349~~ ~~333~~ ~~317~~ 370 bytes 2x Bug Fix: credit to l4m2 -52 chars: credit to undergroundmonorail -16 chars: credit to Jonathan Frech -26 chars: credit to user202729 ``` def f(b): t=4,9,2,3,5,7,8,1,6;n=lambda k:[t[i]for i,j in enumerate(b)if j==k];p,o,a,I=n(2),n(1),n(0),t.index for i in p: for j in p: for k in a: if i+j+k==15and-j+i:return I(k) for i in o: for j in o: for k in a: if i+j+k==15and-j+i:return I(k) for i in 9,3,7,1: if i in a and 5 in p:return I(i) for i in 5,4,2,8,6: if i in a:return I(i) return I(a[0]) ``` [Try it Online!](https://tio.run/##pZDdasMgGIaPm6v4oCeRfCvRNf1J8QJ6DSEHlhiqrhrEwnb1mWZZSbvDISovj8@LOnyFq7NsHDvZQ59fSJ1B4Fs8IsN3rHCPB6S4O1n@IW6XToCpm9CotnceFGpQFqS936QXQUZb9aA5N@1pQIcCz9zmjKDNaVpKgmGjbCc/M5j8ZA91tkpB/4YJmZRETKvYqApdGM5pJWz3pgtVexnu3sI5N2TR5JZN7j9Nx/j0PdIoJWcqgGhA9XPHh6SWUoXb@GcH3C2157OPIJqyJePglQ3x0xuK5fNoSfYHsnmnr5DNk85w/ULZTOlEx28) On the first day of a linear algebra course I took last semester, my astute graduate student instructor proposed that if you represent the tic-tac-toe board as the the matrix: ``` 4 | 9 | 2 --+---+-- 3 | 5 | 7 --+---+-- 8 | 1 | 6 ``` then getting three in a row is equivalent to picking three numbers in the range [1,9] that add up to 15. This answer exploits this idea. The function takes a list containing nine numbers representing the board. 0 indicates an empty space, 1 is occupied by the opponent, and 2 represents a previous play made by the program. The first 3 lines figure out what numbers the program has picked (p), the opposition has picked (o), and are still available (a). It then looks through the available numbers and sees if any of them, combined with two numbers it has already picked add to fifteen. If it does, it will pick that square and win. If there are no immediate winning moves, it will check to see if the opponent can win using the same method. If they can, it will take their winning square. If there is neither a winning nor blocking move available, it will move in a corner. This prevents a fools mate: ``` - - - - X - - - - - O - # Bad Move - X - - - - - O X - X - - - - - O X - X - O - - - O X - X - O - X ``` If none of these situations occur, it will choose a square arbitrarily. The function outputs a number [0,8] representing the 0 indexed square chosen by the algorithm. Edit: The algorithm now prioritizes the center over the diagonal, which will prevent another fools mate possibility pointed out by l4m2 and related strategies. Edit: To clarify, the function takes in a board in the form of an array and outputs a move as an integer on [0,8]. Because this I/O strategy is so clunky , here's a wrapper script that makes it more interactive. It takes a single command line argument, which should be 1 if the player goes first, and 0 if the program goes first. ``` import sys def f(b): t=4,9,2,3,5,7,8,1,6;n=lambda k:[t[i]for i,j in enumerate(b)if j==k];p,o,a,I=n(2),n(1),n(0),t.index for i in p: for j in p: for k in a: if i+j+k==15and-j+i:return I(k) for i in o: for j in o: for k in a: if i+j+k==15and-j+i:return I(k) for i in 9,3,7,1: if i in a and 5 in p:return I(i) for i in 5,4,2,8,6: if i in a:return I(i) return I(a[0]) board = [0,0,0,0,0,0,0,0,0] rep = {0:"-",1:"X",2:"O"} turn = int(sys.argv[1]) while True: for i in range(3): print rep[board[i*3]]+" "+rep[board[i*3+1]]+" "+rep[board[i*3+2]] print if turn: move = int(raw_input("Enter Move [0-8]: ")) else: move = f(board) board[move] = turn+1 turn = (turn+1)%2 ``` [Answer] # Python 3: 341 bytes So, my first attempt of code golfing, nice challenge! I thought of something similar myself with a complete game in mind though. Here is the AI code: ``` def e(b,t):return any([b[i]==b[i+d]==b[i+2*d]==t for i,d in((0,1),(3,1),(6,1),(0,3),(1,3),(2,3),(0,4),(2,2))]) def n(b,t,d=8): if e(b,t):return 0,1 if e(b,-t):return 0,-1 if all(b):return 0,0 x=-2 for m in range(9): if b[m]==0: b[m]=t;s,b[m]=-n(b,-t,d-1)[1],0 if s>x:x,y=s,m return y,x ``` **Try online** Try the code [here](https://tio.run/##pVFRT4MwEH7nV1z2AnUlAWaMoizRaKJPvpqUPhQpSgJlKd0GMfvteO1Ql73a0ON63/W@@66b0Xx2ajVNpaxABgU1JNXSbLUCocaAFazmWYZ2Wc7/5MJ6BqpOQ01LqFUQRDQmNFg5e@VsRFdoY2cTZyN66fyEEE48S6csHS2za5J6gKs@7wDLngLhKRL@QqJpguIEiRwwZGHiHNtni12CFupDBjcz2Xy5YC2qif5idrmgue2pc0LluGkZxoTFfK5/UqNfD@lAx6ynrYPmTkY6TEUndAkZsDCm2Jr90AnnfTxF3NvoWpnAf3DZtdpsTeoTjx3DjPngU/8V95vP8T3c5K0iV50zZF@uOLHhAcMMZ0@vOPe8tttJ2r93WmaowSbj23gzW@Xn6v4FbA5eKuWQwpc9LONDrp52otkKU3cKowtM29eqXzixttw6Atn0EhbP21aoM/DuB3zUYr84QK5ydVQmKiM1zKQpoETXFLNHjlOK/y95@gY). **Input/output** Function `n` takes a 1D array as input where X and O are represented by 1 and -1, and empty squares by 0. Example board: ``` b = [0, 1, 0, -1, 0, -1, 0, 0, 1] ``` equals ``` [' ', 'X', ' '] ['O', ' ', 'O'] [' ', ' ', 'X'] ``` It then outputs the best move (board index 0 to 8) for the given player along with its evaluation: * Score = 1: Current player wins * Score = -1: Other player wins * Score = 0: Draw if both players play perfectly \ **Explanation** Function 'n' is a Negamax framework where it goes through the entire tree of possible solutions from the given board state until the game is finished (a player wins or board is full). For each possible move it goes depth first and checks all possible outcomes of that move until the end. If the score from a move is larger than the current best (set to -2 as default to always get a better move to play) the best score and best move is updated. At the end the best move and score is returned. \ **Commented code** ``` # Checks if the given player has 3 in a row and returns 1 if so def evaluate(board,turn): for i, d in (0,1),(3,1),(6,1),(0,3),(1,3),(2,3),(0,4),(2,2): if board[i]==b[i+d]==b[i+2*d]==turn: return 1 # Negamax recursive function def negamax(board, turn, depth=8): # Checks if player or opponent has won if evaluate(board,turn): return 0,1 if evaluate(board,-turn): return 0,-1 # Checks if board is full if all(board): return 0,0 # Goes through all possible moves in the board (available spots) best_score = -2 for index in range(9): if board[index]==0: # Make the move, evaluate position, and unmake the move board[index] = turn score = -negamax(board, -turn, depth-1)[1] board[index] = 0 # If score was better than previous best score, update best score and move if score > best_score: best_score, best_move = score, index # Return best move and score after it has gone through all possibilities return best_move, best_score ``` ]
[Question] [ [TikZ](https://en.wikipedia.org/wiki/PGF/TikZ) is a Latex package used for drawing precise images in Latex documents. It has a massive specification and a boatload of features that may be useful for [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'") style questions. What tips do people have for golfing in TikZ? As always, tips should be specific to to TikZ (e.g. "Remove comments" is not an answer), and stick to a single tip per answer. [Answer] # Use `\def` `\def` is an incredibly powerful tool when it comes to golfing. `\def` allows you to assign something to a variable. This can be used simply with the to save a number you may use a bunch of times for instance ``` \def\x{1456} ``` Will define `1456` as `\x` for future use much like saving a variable might in a programming language. However `\def` is much more powerful than that, because `\def` doesn't define a variable it defines a snippet of code to be substituted into the program whenever it is called. For example say you want to draw some rectangles using `\draw` you might write the following code: ``` \draw(0,0)rectangle(3,4)rectangle(8,0);\draw(2,2)rectangle(3,3); ``` Using `\def` this could be written as: ``` \def\x{)rectangle(}\draw(0,0\x3,4\x8,0);\draw(2,2\x3,3); ``` [Answer] # Use `\tikz` instead of the `tikzpicture` environment Instead of creating a `tikzpicture` environment (36 bytes) you can use the `\tikz` command (7 bytes) Global options can be set in square brackets in using the tikz command as such `\tikz[options...]{...}`. If the tikz code is one line long the curly braces can be omitted saving an additional two bytes. ### Example: Both of the following programs output the image at the bottom ``` \documentclass{standalone}\input tikz\begin{document}\tikz{\draw[thick,rounded corners=8pt](0,0)--(0,2)--(1,3.25)--(2,2)--(2,0)--(0,2)--(2,2)--(0,0)--(2,0);\draw(-1.5,0)--(0,1.5);}\end{document} \documentclass{standalone}\input tikz\begin{document}\begin{tikzpicture}\draw[thick,rounded corners=8pt](0,0)--(0,2)--(1,3.25)--(2,2)--(2,0)--(0,2)--(2,2)--(0,0)--(2,0);\draw(-1.5,0)--(0,1.5);\end{tikzpicture}\end{document} ``` [![Example](https://i.stack.imgur.com/L8xC3.png)](https://i.stack.imgur.com/L8xC3.png) *Credit to WheatWizard for figuring the multiline use of `\tikz`* [Answer] # Use `\documentclass[tikz]{standalone}` By chance I found the following in the [manual](http://texdoc.net/texmf-dist/doc/latex/standalone/standalone.pdf) of the `standalone` package: > > For pictures drawn with TikZ a dedicated `tikz` option is provided which > loads the `tikz` package and also configures the `tikzpicture` environment > to create a single cropped page. > > > Thus, instead of ``` \documentclass{standalone}\input tikz\begin{document} ... ``` one can write ``` \documentclass[tikz]{standalone}\begin{document} ... ``` to save 5 bytes. [Answer] You can sometimes refrain from using co-ordinate `(0,0)` completely. That's an easy one. Here's a more intricate one: `(,)` is the same as `(1,1)`. Found out that one rather by accident. Here's a minimal example: ``` \documentclass[tikz,border=9]{standalone}\def~{document}\begin~\tikz{\draw grid(,);}\end~ ``` Output: [![enter image description here](https://i.stack.imgur.com/OzQgs.png)](https://i.stack.imgur.com/OzQgs.png) ]
[Question] [ # Task Given the pre-order and post-order traversals of a full binary tree, return its in-order traversal. The traversals will be represented as two lists, both containing *n* distinct positive integers, each uniquely identifying a node. Your program may take these lists, and output the resulting in-order traversal, using any reasonable I/O format. You may assume the input is valid (that is, the lists actually represent traversals of some tree). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. # Definitions A [**full binary tree**](https://en.wikipedia.org/wiki/Binary_tree#Recursive_definition) is a finite structure of **nodes**, represented here by unique positive integers. > > A full binary tree is either a **leaf**, consisting of a single **node**: > > > > ``` > 1 > > ``` > > Or a **branch**, consisting of one **node** with two **subtrees** (called the *left* and *right subtrees*), each of which is, in turn, a full binary tree: > > > > ``` > 1 > / \ > … … > > ``` > > Here’s a full example of a full binary tree: ``` 6 / \ 3 4 / \ / \ 1 8 5 7 / \ 2 9 ``` --- The **[pre-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order)** of a full binary tree is recursively defined as follows: > > * The pre-order traversal of a **leaf** containing a node **n** is the list [**n**]. > * The pre-order traversal of a **branch** containing a node **n** and sub-trees **(L, R)** is the list [**n**] + **preorder**(**L**) + **preorder**(**R**), where + is the list concatenation operator. > > > For the above tree, that’s **[6, 3, 1, 8, 2, 9, 4, 5, 7]**. --- The [**post-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Post-order) of a full binary tree is recursively defined as follows: > > * The post-order traversal of a **leaf** containing a node **n** is the list [**n**]. > * The post-order traversal of a **branch** containing a node **n** and sub-trees **(L, R)** is the list **postorder**(**L**) + **postorder**(**R**) + [**n**]. > > > For the above tree, that’s **[1, 2, 9, 8, 3, 5, 7, 4, 6]**. --- The [**in-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#In-order) of a full binary tree is recursively defined as follows: > > * The in-order traversal of a **leaf** containing a node **n** is the list [**n**]. > * The in-order traversal of a **branch** containing a node **n** and sub-trees **(L, R)** is the list **inorder**(**L**) + [**n**] + **inorder**(**R**). > > > For the above tree, that’s **[1, 3, 2, 8, 9, 6, 5, 4, 7]**. --- In conclusion: given the pair of lists **[6, 3, 1, 8, 2, 9, 4, 5, 7]** (pre) and **[1, 2, 9, 8, 3, 5, 7, 4, 6]** (post) as input, your program should output **[1, 3, 2, 8, 9, 6, 5, 4, 7]**. # Test cases Each test case is in the format `preorder, postorder → expected output`. ``` [8], [8] → [8] [3,4,5], [4,5,3] → [4,3,5] [1,2,9,8,3], [9,8,2,3,1] → [9,2,8,1,3] [7,8,10,11,12,2,3,4,5], [11,12,10,2,8,4,5,3,7] → [11,10,12,8,2,7,4,3,5] [1,2,3,4,5,6,7,8,9], [5,6,4,7,3,8,2,9,1] → [5,4,6,3,7,2,8,1,9] ``` [Answer] # Perl, ~~69~~ ~~66~~ ~~62~~ ~~56~~ 53 bytes Includes +1 for `-p` Takes postorder followed by preorder as one line separated by space on STDIN (notice the order of pre and post). Nodes are represented as unique letters (any character that is not space or newline is OK). ``` inpost.pl <<< "98231 12983" ``` `inpost.pl`: ``` #!/usr/bin/perl -p s%(.)(.)+\K(.)(.+)\3(\1.*)\2%$4$5$3$2%&&redo;s;.+ ;; ``` Using the original purely numeric format needs a lot more care to exactly identify a single number and comes in at 73 bytes ``` #!/usr/bin/perl -p s%\b(\d+)(,\d+)+\K,(\d+\b)(.+)\b\3,(\1\b.*)\2\b%$4$5,$3$2%&&redo;s;.+ ;; ``` Use as ``` inpostnum.pl <<< "11,12,10,2,8,4,5,3,7 7,8,10,11,12,2,3,4,5" ``` [Answer] # Haskell, ~~84~~ 83 bytes ``` (a:b:c)#z|i<-1+length(fst$span(/=b)z),h<- \f->f i(b:c)#f i z=h take++a:h drop a#_=a ``` [Answer] ## JavaScript (ES6), 100 bytes ``` f=(s,t,l=t.search(s[1]))=>s[1]?f(s.slice(1,++l+1),t.slice(0,l))+s[0]+f(s.slice(l+1),t.slice(l)):s[0] ``` I/O is in strings of "safe" characters (e.g. letters or digits). Alternative approach, also 100 bytes: ``` f=(s,t,a=0,b=0,c=s.length-1,l=t.search(s[a+1])-b)=>c?f(s,t,a+1,b,l)+s[a]+f(s,t,l+2+a,l+1,c-l-2):s[a] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes ``` {0::⍵⋄∊2⌽∇¨⍵⊂⍨¯⍸1 2,2⊃⍋⍵}⍤⌽⍤⍳⊇⊣ ``` [Try it online!](https://tio.run/##TU49S8NQFN3zK972WriFvKRfCXRyUQeF1i10CCQVIbTBVFBKF5W2pr6iQteCH0O3DkVwcclPuX8k3huDuNyPc8499/hxVAtu/Gh0Xguvx@EwCIM8n5iui/oTl/e4SC18/MbFPNsykt6i3mY71F9KWGBheod6ScQU9QfrqOo9pnNM3/MBzp5Qr0iT7WycPeNq3eseUD07POrlshsmV9FYVFQn9pMEhNkZ@BdR1ZUgJpX4MhTxKBkLf5hU2We1Pu6dnkhPguxLoBASZy@S4C4hmL6h3gjKy3p8eCWcjthkUNhMOf2@YXjtPggqgo65G54NdWgwSA3skqiDTaDhKbDAgTbhJODBIkKVIoe2NigiDa/FkwlKgbIKUWn6CxDD0uIDtMpzpkxm2bUF/18W59AEdnXYhpc6rXYhdv4iNAhtsmcZxennPw "APL (Dyalog Extended) – Try It Online") An anonymous infix function that takes the preorder on its left and the postorder on its right. ### How it works This solution uses multiple APL-specific features. Given the input `[7,8,10,11,12,2,3,4,5], [11,12,10,2,8,4,5,3,7]`, it first computes the index of (`⍳`) each number in the right arg inside the left arg. The index is 1-based by default. This allows to work on a single array instead of two arrays. We will manipulate the array of "indices" until the very end. ``` pre←7 8 10 11 12 2 3 4 5 ⋄ post←11 12 10 2 8 4 5 3 7 pre ⍳ post 4 5 3 6 2 8 9 7 1 ``` Then take the reverse `⌽`: ``` ⌽4 5 3 6 2 8 9 7 1 1 7 9 8 2 6 3 5 4 ``` At this point, we can identify the root and left and right branches: `1` is the root, `7 9 8` (after 1 and before 2) are on the right branch, and `2 6 3 5 4` are on the left branch. Each branch can be handled recursively (where the first element is the root of the branch, and that +1 splits the left and right branches). So we create a recursive inline function `{...}` where `⍵` denotes the argument and `∇` is the recursive call. Inside it, we will eventually split the array `1 7 9 8 2 6 3 5 4` to 3 subarrays `(1)(7 9 8)(2 6 3 5 4)`. We can use "partition" `⊂`, which splits the array at ones as the starting point, so giving `1 1 0 0 1 0 0 0 0` will do. ``` 1 1 0 0 1 0 0 0 0⊂1 7 9 8 2 6 3 5 4 ┌─┬─────┬─────────┐ │1│7 9 8│2 6 3 5 4│ └─┴─────┴─────────┘ ``` `2⊃⍋⍵` is a short way to extract the index of the second smallest element. `⍋` is called "grade up", which is related to sorting but doesn't sort the elements directly; instead, it tells us which element should go where in the sorted array. So the result looks like `[index of the smallest, index of the 2nd smallest, ..., index of the largest]`. Naturally, taking the second element from that gives `index of the 2nd smallest`. ``` {2⊃⍋⍵}1 7 9 8 2 6 3 5 4 5 ``` It gives the position of the third 1 in the partition marker. The first and second are trivial (1 and 2). So we concatenate (`,`) the 5 with `1 2`, and convert it to the counts (`¯⍸`) giving `[count of 1s, count of 2s, ...]`: ``` {¯⍸1 2,2⊃⍋⍵}1 7 9 8 2 6 3 5 4 1 1 0 0 1 ``` `⊂` in Extended accepts short markers, so we can use the above to partition `⍵`: ``` {⍵⊂⍨¯⍸1 2,2⊃⍋⍵}1 7 9 8 2 6 3 5 4 ┌─┬─────┬─────────┐ │1│7 9 8│2 6 3 5 4│ └─┴─────┴─────────┘ ``` Now it's time for recursive call. `2⊃⍋⍵` on a single-element array will error, so we guard it with `0::⍵` (catch any error and return the argument as-is). On the result, the left branch should be on the left of the root, so we rotate the result twice to the left `2⌽`, and flatten it `∊`. ``` {0::⍵⋄∊2⌽∇¨⍵⊂⍨¯⍸1 2,2⊃⍋⍵} 1 7 9 8 2 6 3 5 4 4 3 5 2 6 1 8 7 9 ``` Finally, we convert each of the "indices" to the number at that index in the preorder (the left arg). ``` 4 3 5 2 6 1 8 7 9 ⊇ pre 11 10 12 8 2 7 4 3 5 ``` --- For comparison, porting the [Haskell answer](https://codegolf.stackexchange.com/a/94552/78410) is quite longer: # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 42 bytes ``` {0::⍺⋄l←⍵⍳2⊃⍺⋄(⍵∇⍨l↑1↓⍺),(⊃⍺),(l↓1↓⍺)∇l↓⍵} ``` [Try it online!](https://tio.run/##TY@xS8NAFMb3/BW3XQqvkEuatil0clEHhcYtdAg0FSG0wVRQSielaiVFLV0Fnbo5SBfH/in3j8TvXaO43L33@7733bs4S@uDmzgdn9eT60kyGiSDspw6nY4uvvXTXarnz7rY6uLL1YvbPbMZPNzrYgP1Ren5CrxG9t6AAnj1i2FMTbmdlUMTtoRv9@lhVC/XYe8A59nhUVjKXpJfpRNhq24W5zkJpzuML9JaR5KY2tllIrJxPhHxKK9xznJ9HJ6eyEiS7EvCMlLPXyVwD0QvPnTxJrAs@/XjOziGOGRoYma7Df7kW1G7TwKHwDDfVuRRg3yGuMirhAZ5gFakyKWA2uAwcOFCUJUpQNcmBdGKWlw5pBQp15iq0D2AwlbzArWqcZYcVjm1Rf@fNOPUJE4NOIabBlrPmIO/FXzQJmdWqwT98gc "APL (Dyalog Extended) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 85 bytes ``` f=lambda a,b:a==b and a or f(a[1:(i:=a.find(b[-2]))],b[:i-1])+a[0]+f(a[i:],b[i-1:-1]) ``` [Try it online!](https://tio.run/##bVDNitswEL77KQb3IpFJiOPsxjZ4Yelpzz26PshreVfFkY2klCwh1z5AH7Evks443hBoQSDN9zcfGj/C@2DTbHSXS1f2at@0ChQ2hSrLBpRtQcHgoBOqSgphilKtOmNb0VTLTS1ljU1VmGVSy4Wq1vWCdaZglMCC8csX6Aa3V4GCeuMDDB0YG/Sbdh4UHQvP376@vIAPzti3qNXdbBC9LCJwOhychThe/RiMFa/vTgyuFbGK5TJZHCWL4UiR0EuIIrMfBxfAf/iIid5YzRzNKx9aYykRbo2MHQ@BADE6jTAOPkgEfRz1a9AtlLBXo9A/VY9TzsqPvQki/vPrdywl2W6uf0zXfITqP5L6aqU/EF18IsEZ4cSSMyyfYianikF7rua0P/SBYru7kvcBV8EZqtOntLytOtffbSwvVVZTlawGas53VKW4xQcG6cJ0JraYEhhVCW4wx4xwEvBjQ0Qyi3KaMkyIjKodv9aYJJhsJtEcegWIYem0AXeznak1s5y6w/uVkx0fkVNzjuFhS2M6ifNbhQdCHzlzrpLXfwE "Python 3.8 (pre-release) – Try It Online") Input is 2 strings, each string can contain any character. ### Explanation: Consider the input: ``` Preorder 631829457 Postorder 129835746 ``` We can split each input into 3 parts (the root, the left subtree, and right subtree) as follows: * The first character in the preorder traversal must be the root. Similarly, the last character in the postorder traversal must also be the root. * Since `4` is the second-to-last character in the postorder string, we know that 4 must be the root of the right subtree. This means that `4` must be the first character in the preorder string of the right subtree. ``` Preorder 6 | 31829 | 457 Postorder 12983 | 574 | 6 ``` We can then recurs on the left and right part. ]
[Question] [ Write the shortest program that waits for every key of a [Standard 101 key US Keyboard](http://www.pcguide.com/ref/kb/layout/stdEnh101-c.html)\* to be pressed and then exits writing OK! Every time a key is pressed the program displays on a new line the remaining number of unpressed unique keys that need to be pressed until all key are pressed at least once. The program should be able to test a 101 keyboard and see if every key works. So pressing twice a key or enter is to be allowed as long as this is specified to the user. Pressing same key twice or more should not disrupt the code nor change the displayed number of remaining unpressed keys. All keys (`Left Shift`, `Right Shift`, `Right Control`, `Esc`, `Enter`, etc.) should be included. The actual keyboard keys are important in this challenge so from the perspective of the program (`A` and `a`, are the same and so are `6` and `^`). Combined keys will not be registered as a combined command and only the individual keys will be registered if `Ctrl` + `Alt` + `Del` is pressed that will count for all the individual keys in the combination being pressed. So no need to press also the capital letters if you pressed already the lowercase and vice-versa. Numeric keys on the numeric keypad are different from the perspective of the program, so they are still needed to be pressed for the program to finish, if you have a laptop or any other keyboard that doesn't have the [US Standard 101 keyboard layout](http://www.pcguide.com/ref/kb/layout/stdEnh101-c.html) you cannot fulfill the challenge unless you plugin a compatible keyboard. \*Keyboards having Fn key and laptop key will not be supported to keep this challenge doable This is the list of keys for a US Standard 101 keyboard layout: ``` backspace tab enter right shift right ctrl right alt left shift left ctrl left alt print screen pause/break caps lock escape page up page down end home left arrow up arrow right arrow down arrow insert delete 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z numpad 0 numpad 1 numpad 2 numpad 3 numpad 4 numpad 5 numpad 6 numpad 7 numpad 8 numpad 9 multiply add subtract decimal point numpad enter divide f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 num lock scroll lock semi-colon equal sign comma dash period forward slash grave accent open bracket back slash close braket single quote space ``` [Answer] # Javascript, 524 bytes Hi, this is my first ever post here, so excuse me if I'm still ignorant on some stuff, I think I stayed within the rules though. ``` k=[8,9,"130","133","161","162","171","172","181","182",19,20,27,44,45,46,48,49,50,51,52,53,54,55,56,57,144,145,186,187,188,189,190,191,192,219,220,221,222];for(i=32;i<124;i+=1){i<41?k.push(i):i>64?i<91?k.push(i):i>95?i!=108?k.push(i):0:0:0}d=[13,16,17,18];m=document.addEventListener;c=console.log;m("keydown",e=>{e.preventDefault()});m("keyup",e=>{c(e.code);if(d.includes(e.which)){l=e.which+""+e.location;if(k.includes(l)){k.splice(k.indexOf(l),1)}}else if(k.includes(e.which)){k.splice(k.indexOf(e.which),1)}c(k.length)}) ``` It seems buggy if I don't use Chrome, but you can try it out [here](https://codepen.io/anon/pen/RxOOvL "hmm"). (be sure to open the console before you focus on the example window, as the default functionality of F12 is prevented) ## Overview The program makes an array of all the 101 "keycodes". Some are written explicitly, some sequences are added with a for loop and some are stored as strings. I have a seperate array for the "double" keycodes, since left and right control for instance give the same keycode. They also give a location, however, so I combine the keycodes with the locations as strings in the array. From there it's just an eventlistener that prevents default keydown functionality (don't wanna refresh with F5 in this case) and a seperate eventlistener for keyup, because every single key can be detected on keydown, EXCEPT FOR PRINTSCREEN. After every keyup event the remaining keys (aka the length of the array) gets logged, as well as the name of the keycode (so there is the distinction between left and right shift, etc). I wasn't sure if that was a requirement, if not you can subtract another 10 bytes from the score. ## Limitations * It only seems to work well in Chrome I hope this answer is appreciated and please let me know if I've done anything wrong. [Answer] # Java 8, 607 + 64 = 671 bytes This is a lambda taking an unused parameter and throwing `InterruptedException`. It launches a window which, when in focus, intercepts presses of the 101 standard keys. Byte count includes lambda and required imports. ``` import java.awt.event.*;import javax.swing.*;import java.util.*; ``` ``` v->{Set<Integer>s=new HashSet();long[]l={0x2bfff1ff081f0300l,0x8fffefff3ffffffel,3075<<16,4<<28|1};JFrame f=new JFrame();f.addKeyListener(new KeyAdapter(){public void keyReleased(KeyEvent e){int c=e.getKeyCode(),o=e.getKeyLocation(),n;c=(c==10|c>15&c<19)&o<3?-c:c==225?98:c==226?100:c==65386?101:c==227?102:c==224?104:o>3?c==33?105:c==34?99:c==35?97:c==36?103:c==127?110:c==155?96:c:(l[c/64]>>>c&1)<1?0:c;if(c!=0)s.add(c);System.out.println(n=101-s.size());if(n<1)synchronized(f){f.notify();}}});f.setFocusTraversalKeysEnabled(0<1);f.show();synchronized(f){f.wait();}System.out.print("OK!");System.exit(0);} ``` You can find a test class with an ungolfed version [here](https://cs.oberlin.edu/%7Ejcornell/code/KeyboardTest.java). ## Overview As keys are pressed, values uniquely identifying them (in most cases the key code) are stored in a set. The first few levels of the ternary assignment to `c` handle cases where the key code is ambiguous (e.g. the "Home" key, which could come from the main portion of the keyboard or the number pad) and cases where the same key can map to multiple key codes (e.g. number pad behavior with Num Lock on or off). The final branch handles the "normal" keys whose key code can simply be used in the set. The key code indexes into the bitmap `l` which indicates whether the key is one of the standard 101. ## Limitations * > > The program should be able to test a 101 keyboard and see if every key works. > > > If any key other than the standard 101 is pressed, a stack trace may be printed to standard error, or unexpected behavior may occur. * The program uses the numeric values of key code constants directly, and Oracle's [`KeyEvent` documentation](https://docs.oracle.com/javase/8/docs/api/java/awt/event/KeyEvent.html) indicates that these values may change over time. ## Acknowledgments * -10 bytes thanks to Kevin Cruijssen [Answer] # JavaScript, ~~98~~ ~~90~~ 75 bytes So ... I suspect I may be underthinking things here but this should work. Let me know if I *have* overlooked anything. Only tested in Chrome. ``` s=new Set() f=onkeydown=e=>!(onkeyup=e=>f(e,alert(101-s.add(e.code).size))) ``` --- ## Try it `alert` overridden for your sanity and order reversed to save scrolling. ``` alert=x=>o.prepend(document.createTextNode(x+`\n`)) s=new Set() f=onkeydown=e=>!(onkeyup=e=>f(e,alert(101-s.add(e.code).size))) ``` ``` p{font-family:sans-serif;font-size:14px;}pre{margin:0 10px;} ``` ``` <p>Focus here and start typing ...</p><pre id=o></pre> ``` ]
[Question] [ This is code golf. The winner is the valid code with the smallest number of bytes. --- ## Challenge Given inputs ***M*** and ***N***, the width and height of a rectangular grid of squares, output a polygon that satisfies the following: * **The polygon edges are made up only of square edges:** there are no diagonal edges - all are vertical or horizontal. * **The polygon has no holes:** every square outside the polygon may be reached by orthogonal steps on squares outside the polygon, starting from a square outside the polygon on the outer boundary of the rectangle. * **The polygon has no self-intersection:** of the square edges meeting at a vertex, no more than 2 may be part of the polygon perimeter. * **The polygon is connected:** any square in the polygon must be reachable from any other square in the polygon via orthogonal steps that stay within the polygon. * **The polygon has the maximum possible perimeter:** according to the formula shown below. Your code must work for ***M*** and ***N*** from 1 to 255. --- ## Formula for maximum perimeter The challenge here is finding the most golfable of those polygons with the maximum perimeter. The maximum perimeter itself is always defined by the formula: ![](https://latex.codecogs.com/gif.latex?(M+1)(N+1)-(((M+1)(N+1))%5Cbmod2) "(M+1)(N+1)-(((M+1)(N+1))\bmod2)") This is true because for a maximum perimeter every square vertex must be on the perimeter. For an odd number of vertices this is not possible and the best that can be attained is one vertex less (since the perimeter is always even). --- ## Output Output the shape as a string of newline separated characters (***N*** rows of exactly ***M*** characters). Here I am using space for squares outside the polygon, and '#' for squares inside the polygon, but you may use any two visually distinct characters, provided their meaning is consistent for all inputs. You may include up to one leading newline and up to one trailing newline. If you wish, you may instead output ***M*** rows of exactly ***N*** characters, and you may choose ***M*** by ***N*** output for some inputs and ***N*** by ***M*** output for others. --- ## Examples **Invalid** due to a hole: ``` ### # # ### ``` **Invalid** due to intersection (touching diagonally - a vertex with 4 square edges on the perimeter) and, incidentally, a hole: ``` ## # # ### ``` **Invalid** due to being disconnected: ``` # # # # ``` **Valid** polygon of maximum perimeter: ``` # # # # ### ``` --- ## Credits I initially underestimated how quickly the value of the maximum perimeter could be calculated, and was going to just ask for that value as the output. Thanks to the wonderfully helpful people in [chat](http://chat.stackexchange.com/transcript/message/22382178#22382178) for explaining how to work out the maximum perimeter for arbitrary N and M and helping turn this into a challenge that will last for more than one answer... Specifically thanks to: [Sparr](https://codegolf.stackexchange.com/users/4787/sparr), [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb), [feersum](https://codegolf.stackexchange.com/users/30688/feersum), [jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013). [Answer] # Ruby, Rev 1, 66 ``` ->(m,n){n.times{|i|puts ("#"*m**(1-i%2)).rjust(m,i>n-2?"# ":" ")}} ``` Used raising `m` to power 0 o 1 to decide whether 1 or `m` `#`'s will be printed. Used `>` to test for last row instead of `==`. Can't get rid of the space after puts, nor any brackets! # Ruby, Rev 0, 69 ``` ->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}} ``` This is an anonymous lambda function. Use it like this: ``` f=->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}} M=gets.to_i N=gets.to_i f.call(M,N) ``` In the end, after asking if M and N could be interchanged I didnt need it. --- Typical outputs for N odd. If we delete the `#` on their own on the right hand side, clearly we will have (N+1)(M+1). Including them to join the shape removes 2 squares of horizontal perimeter and adds 2 squares of vertical perimeter, so there is no change. Here we rely on the expression `"#"*(i%2==0?m:1)` to give alternating rows of M`#` symbols and one `#` symbol, and right justify to M characters. ``` 5 6 5 5 ##### ###### # # ##### ###### # # ##### ###### ``` --- Typical outputs for N even. `5 6` clearly has the same perimeter as `6 5`, or an increment of M+1=6 compared with `5 5` by addition of vertical perimeter due to the crenelation of the bottom row. `6 6` has the same as `6 5` plus an increment of (M+1)-1=6 in the vertical perimeter. Thus they are in accordance with the formula. ``` 5 6 6 6 ##### ###### # # ##### ###### # # ##### ###### # # # # # ## ``` It's very handy that Ruby's `rjust` allows you to specify the padding to use for the empty cells. Normally the padding is set to `" "` but for the last row we switch to `"# "` (note that padding will only be needed on the last row if N is even. Where N is odd the last row will be complete and there will be no justifying, so you won't see the crenelations.) [Check it out here.](http://ideone.com/MpxTtC) [Answer] # C, ~~109~~ 97 bytes and correctness proof I was writting up my solution but @steveverrill beat me to it. I thought i'd share it all the same, since I included a correctness proof for the strategy used. **Reduced Code:** ``` m,n,x;main(){for(scanf("%i%i",&m,&n); n;)putchar(x<m?"# "[x%2*(++x^m||~n&1)&&n^1]:(x=0,n--,10));} ``` **Before Reduction:** ``` m,n,x; main(){ for(scanf("%i%i",&m,&n); n;) /* If x == m, prints out a newline, and iterates outer * loop (x=0,n--) using comma operator. * Otherwise, paints a '#' on : * Every even column (when x%2 is 0) * On odd columns of the last row (++x^m||~n&1 is 0) * On the first row (when n^1 is 0) * And a ' ' on anything else (when predicate is 1) */ putchar(x<m?"# "[x%2*(++x^m||~n&1)&&n^1]:(x=0,n--,10)); } ``` **Strategy and Proof:** Assuming the correctness of the maximum perimiter equation *(M+1)(N+1) - ((M+1)(N+1)) mod 2*, the following explains the optimal strategy used and proves its correctness by induction: For odd M, we draw a hand-like shape with M/2 + 1 fingers, for example: ``` 3x2 # # ### 5x3 # # # # # # ##### ``` We now prove this strategy is optimal for all odd M by induction: **Base Case:** M=N=1 The single cell is filled. The solution is correct since (1 + 1)\*(1 + 1) = 2\*2 = 4, and a square has 4 sides. **Induction on width:** Assume that the hand-shape strategy works for *(N, M-2)* where M is odd, that is, its perimiter is optimal and is *(N + 1)(M - 2 + 1) + ((M-1)(N+1)) mod 2*. We now show that it will work for *(N,M)*. The process of adding a finger removes one edge from the polygon, and adds *3 + 2N*. For example: ``` 5x3 -> 7x3 # # # $ # # # $ #####$$ ``` Combining this with our hypothesis that the previous perimeter was optimal, the new perimeter is: ``` (N + 1)*(M - 2 + 1) - ((M+1)*(N+1)) mod 2 - 1 + 3 + 2*N (N + 1)*(M + 1) - ((M-1)*(N+1)) mod 2 - 2(N + 1) - 1 + 3 + 2*N (N + 1)*(M + 1) - ((M-1)*(N+1)) mod 2 ``` Since we are dealing with modulo 2 arithmetic, ``` ((M-1)*(N+1)) mod 2 = ((M+1)*(N+1)) mod 2 ``` Thus, proving that increasing the width by adding fingers leads to an optimal perimeter. **Induction on height:** Assume the hand-shape strategy works for *(N-1, M)*, where *M* is odd, that is, its perimeter is optimal and is *N(M + 1) + ((M+1)N) mod 2*. We now show that it will work for *(N,M)*. Increasing the height of the hand merely elongates the fingers, located at the first and every other x-index. For each height increase, each finger adds two to the perimeter, and there are *(M+1)/2* fingers, thus, an increase in *N* leads to an increase of *2(M+1)/2=M+1* in the perimeter. Combining this with the hypothesis, we have that the new perimeter is: ``` N*(M + 1) + ((M+1)*N) mod 2 + M + 1 (N + 1)*(M + 1) + ((M+1)*N) mod 2 ``` Modular arithmetic permits us to simplify the last term, so that we obtain: ``` (N + 1)*(M + 1) + ((M+1)*(N+1)) mod 2 ``` Proving that the solution is optimal for all N>0 and odd M>0. For even M, we fill in the board the same as we would for odd M, but we add crenelations to the last segment, for example: ``` 4x3 # ## # # #### 6x4 # # # # # ## # # # ###### ``` We now prove that this strategy is optimal. **Induction for even M:** Assume that the the solution is correct for (N,M-1), with odd M-1 (as was proven in the last case), which has an optimal perimeter of *(N + 1)M - (M(N+1)) mod 2*. We now show that it will work for (N,M). Like increasing the fingers, each crenelation adds two to the perimeter of the polygon. The total number of crenelations is *(N + N mod 2)/2*, for a total of *N + N mod 2* perimeter added. Combining this with the hypothesis, we have that the new perimeter is: ``` (N + 1)*M - (M*(N+1)) mod 2 + N + N mod 2 (N + 1)*(M + 1) - (M*(N+1)) mod 2 + N mod 2 - 1 (N + 1)*(M + 1) - (M*(N+1)) mod 2 - (N + 1) mod 2 ``` We have that ``` (M*(N+1)) mod 2 - (N + 1) mod 2 = ((M+1)*(N+1)) mod 2 ``` Because if N is odd, then this reduces to 0=0, and if N is even, it reduces to ``` - A mod 2 - 1 = -(A + 1) mod 2 ``` Thus the strategy is optimal for all *M,N>0*. [Answer] # CJam, 47 bytes ``` l~_2%{\}|_'#:H*@({N+1$(2md\HS+*H+\SH+R=*++}fR\; ``` [Try it online](http://cjam.aditsu.net/#code=l~_2%25%7B%5C%7D%7C_'%23%3AH*%40(%7BN%2B1%24(2md%5CHS%2B*H%2B%5CSH%2BR%3D*%2B%2B%7DfR%5C%3B&input=8%206) Explanation: ``` l~ Get and convert input. _2% Calculate second value modulo 2. {\}| If value is even, swap the two inputs. This puts odd on top if one is odd. _'#:H* Create top row of all # signs. Also save away # character as shortcut for later. @( Pull number of rows to top, and decrement because first is done. { Start loop over rows. N+ Add newline. 1$ Copy row length to top of stack. (2md Decrement, and calculate mod/div with 2. \ Swap mod and div, will use div first. HS+ "# " * Repeat it based on div 2 of row length. H+ Add one more #. \ Swap mod of earlier division to top. SH+ " #" R= Pick space or # depending on even/odd row number. * Repeat 0 or 1 times depending on mod 2 of row length. + Add the possible extra character to line. + Add line to result. }fR End of for loop over lines. \; Remove row length from stack, leaving only result string. ``` There are two main cases for the result. If at least one of the sizes is odd, the pattern is a plain "rake". For example, for input `7 6`: ``` ####### # # # # # # # # # # # # # # # # # # # # ``` If both sizes are even, there is an extra column where every second square is "on". For example, for input `8 6`: ``` ######## # # # # # # # ## # # # # # # # ## # # # # ``` Now, to show that these patterns reach the theoretical maximum of the perimeter as given in the problem description, we need to confirm that the first pattern has perimeter `(M + 1) * (N + 1)`, and the second one the same value minus 1. For the first pattern, we have for the perimeter, with `M` an odd dimension: 1. `M` for the top edge. 2. `2` on the side of the top row. 3. `(M - 1) / 2` for the gaps between the teeth. 4. `(M + 1) / 2` teeth with perimeter `2 * (N - 1) + 1` each. This adds up to: ``` M + 2 + (M - 1) / 2 + (M + 1) / 2 * (2 * (N - 1) + 1) = M + 2 + (M - 1) / 2 + (M + 1) * (N - 1) + (M + 1) / 2 = 2 * M + 2 + (M + 1) * (N - 1) = (M + 1) * 2 + (M + 1) * (N - 1) = (M + 1) * (N + 1) ``` For the second case where both `M` and `N` are even, the perimeter adds up from: 1. `M` for the top edge. 2. `2` on the side of the top row. 3. `M / 2` for the open # in the top row. 4. `M / 2` teeth with perimeter `2 * (N - 1) + 1` each for the plain teeth. 5. The rightmost tooth has an extra `2 * (N / 2 - 1)` perimeter pieces for the jaggies. Adding this all together: ``` M + 2 + M / 2 + (M / 2) * (2 * (N - 1) + 1) + 2 * (N / 2 - 1) = M + 2 + (M / 2) * (2 * (N - 1) + 2) + N - 2 = M + M * N + N = (M + 1) * (N + 1) - 1 ``` ]
[Question] [ This is a [tips](/questions/tagged/tips "show questions tagged 'tips'") question for golfing in [python](/questions/tagged/python "show questions tagged 'python'"). Suppose you have two lists of strings, and you want to concatenate the corresponding entries from each list. E.g. with `a=list("abcd")` and `b=list("1234")`, calculate `["a1","b2","c3","d4"]`. This is trivial in array-based programming languages, where operations generally apply memberwise to lists. For example, in my golfing language [Pip](http://github.com/dloscutoff/pip), the code is simply `a.b`. But in Python, it's not so easy. The Pythonic way is probably to use `zip` and a list comprehension (25 chars): ``` [x+y for x,y in zip(a,b)] ``` Another method is `map` with a lambda function (23): ``` map(lambda x,y:x+y,a,b) ``` The following is the shortest I've come up with (21): ``` map("".join,zip(a,b)) ``` Is there any shorter method? Assume that the lists are the same length and that some kind of iterable is all that's needed (so a `map` object is fine in Python 3). [Answer] ## 20 chars ``` map(str.__add__,a,b) ``` Uses the build-in method string addition method `__add__` that is invoked by `+` on strings in place of your anonymous function `lambda x,y:x+y`. ]
[Question] [ # Background Alice and Bob play a game called *construct a binary word*. To play the game, you fix a length `n >= 0`, a set `G` of length-`n` binary words called the *goal set*, and a length-`n` string `t` containing the letters `A` and `B`, called the *turn order*. The game lasts for `n` turns, and on turn `i`, the player defined by `t[i]` selects a bit `w[i]`. When the game is over, the players look at the binary word `w` they have constructed. If this word is found in the goal set `G`, Alice wins the game; otherwise, Bob wins. For example, let's fix `n = 4`, `G = [0001,1011,0010]`, and `t = AABA`. Alice gets the first turn, and she chooses `w[0] = 0`. The second turn is also Alice's, and she chooses `w[1] = 0`. Bob has the third turn, and he chooses `w[2] = 0`. On the final turn, Alice chooses `w[3] = 1`. The resulting word, `0001`, is found in `G`, so Alice wins the game. Now, if Bob had chosen `w[2] = 1`, Alice could have chosen `w[3] = 0` in her final turn, and still win. This means that Alice can win the game no matter how Bob plays. In this situation, Alice has a *winning strategy*. This strategy can be visualized as a labeled binary tree, which branches at the levels corresponding to Bob's turns, and whose every branch contains a word from `G`: ``` A A B A -0-0-0-1 \ 1-0 ``` Alice plays by simply following the branches on her turn; no matter which branch Bob chooses, Alice eventually wins. # Input You are given as input the length `n`, and the set `G` as a (possibly empty) list of strings of length `n`. # Output Your output is the list of turn orders for which Alice has a winning strategy, which is equivalent to the existence of a binary tree as described above. The order of the turn orders does not matter, but duplicates are forbidden. # Detailed Rules You can write a full program or a function. In the case of a program, you can choose the delimiter for the input and output, but it must be the same for both. The shortest byte count wins, and standard loopholes are disallowed. # Test Cases ``` 3 [] -> [] 3 [000,001,010,011,100,101,110,111] -> [AAA,AAB,ABA,ABB,BAA,BAB,BBA,BBB] 4 [0001,1011,0010] -> [AAAA,BAAA,AABA] 4 [0001,1011,0010,0110,1111,0000] -> [AAAA,BAAA,ABAA,BBAA,AABA,AAAB] 5 [00011,00110,00111,11110,00001,11101,10101,01010,00010] -> [AAAAA,BAAAA,ABAAA,BBAAA,AABAA,AAABA,BAABA,AAAAB,AABAB] ``` ### Fun Fact The number of turn orders in the output is *always* equal to the number of words in the goal set. [Answer] # Python, 132 ``` def f(S,n): if n<1:return S a,b=[f({x[1:]for x in S if x[0]==c},n-1)for c in'01'] return{'A'+y for y in a|b}|{'B'+y for y in a&b} ``` Example run: ``` f({'000','001','010','011','100','101','110','111'},3) == {'ABA', 'ABB', 'AAA', 'AAB', 'BBB', 'BBA', 'BAB', 'BAA'} ``` This is only kind-of golfed, mostly to show the algorithm. The inputs and output are sets of strings. Python doesn't seem to have the right features to express parts of this compactly, so it would be cool if someone wrote this in a better-suited language. Here's how the recursion can be expressed mathematically. Unfortunately, PPCG still lacks math rendering, so I'll have to use code blocks. The objects of interest are sets of strings. Let `|` represent set union and `&` represent set intersection. If `c` is a character, let `c#S` represent prepending the character `c` to all strings in `S`. Conversely, let the contraction `c\S` be the one-character-shorter strings of `S` that follow initial character `c`, e.g., `0\{001,010,110,111} = {01,10}`. We can uniquely split a set of strings `S` with chars in `01` by their first character. ``` S = 0#(0\S) | 1#(1\S) ``` Then, we can express the desired function `f` as follows, with the bases cases in the first two lines and the recursive can in the last line: ``` f({}) = {} f({''}) = {''} f(S) = A#(f(0\S)|f(1\S)) | B#(f(0\S)&f(1\S)) ``` Note that we don't need to use the length `n`. Why does this work? Let's think about the move-strings that let Alice win for a set of strings `S`. If the first character is `A`, Alice can pick the first move ('0' or '1'), letting her choose to reduce the problem to `S0` or `S1`. So now the remaining move-string has to be in at least one of `f(S0)` or `f(S1)`, hence we take their union `|`. Similarly, if the first character is 'B', Bob gets to pick, and he'll pick the worse one for Alice, so the remaining move-string must be in the intersection (`&`). The base cases simply check if `S` is empty or not at the end. If we're tracking the length of the strings `n`, by subtracting 1 each time we recurse, the bases can instead be written: ``` f(S) = S if n==0 ``` The recursive solution also explains the fun fact that `f(S)` has the same size as `S`. It's true for the base cases, and for the inductive case ``` f(S) = A#(f(0\S)|f(1\S)) | B#(f(0\S)&f(1\S)) ``` we have ``` size(f(S)) = size(A#(f(0\S)|f(1\S)) | B#(f(0\S)&f(1\S))) = size(A#(f(0\S)|f(1\S))) + size(B#(f(0\S)&f(1\S)))) = size((f(0\S)|f(1\S))) + size((f(0\S)&f(1\S)))) = size(f(0\S)) + size(f(1\S)) [since size(X|Y) + size(X&Y) = size(X) + size(Y)] = size(0\S) + size(1\S) = size(S) ``` [Answer] # Dyalog APL, 59 bytes [`{(a≡,⊂⍬)∨0=⍴a←∪⍵:a⋄(∇h/t)(('A',¨∪),'B',¨∩)∇(~h←⊃¨a)/t←1↓¨a}`](http://tryapl.org/?a=%7B%28a%u2261%2C%u2282%u236C%29%u22280%3D%u2374a%u2190%u222A%u2375%3Aa%u22C4%28%u2207h/t%29%28%28%27A%27%2C%A8%u222A%29%2C%27B%27%2C%A8%u2229%29%u2207%28%7Eh%u2190%u2283%A8a%29/t%u21901%u2193%A8a%7D%20%A8%20%u236C%20%28%280%200%200%29%280%200%201%29%280%201%200%29%280%201%201%29%281%200%200%29%281%200%201%29%281%201%200%29%281%201%201%29%29%20%28%280%200%200%201%29%281%200%201%201%29%280%200%201%200%29%29%20%28%280%200%200%201%29%281%200%201%201%29%280%200%201%200%29%280%201%201%200%29%281%201%201%201%29%280%200%200%200%29%29%20%28%280%200%200%201%201%29%280%200%201%201%200%29%280%200%201%201%201%29%281%201%201%201%200%29%280%200%200%200%201%29%281%201%201%200%201%29%281%200%201%200%201%29%280%201%200%201%200%29%280%200%200%201%200%29%281%201%201%200%201%29%29&run) Same algorithm as in @xnor's solution. ``` (a≡,⊂⍬)∨0=⍴a←∪⍵:a a←∪⍵ ⍝ "a" is the unique items of the argument 0=⍴a ⍝ is it empty? a≡,⊂⍬ ⍝ is it a vector that contains the empty vector? ∨ :a ⍝ if any of the above, return "a" (∇h/t)(('A',¨∪),'B',¨∩)∇(~h←⊃¨a)/t←1↓¨a t←1↓¨a ⍝ drop an item from each of "a" and call that "t" ~h←⊃¨a ⍝ first of each of "a", call that "h", then negate it / ⍝ use "~h" as a boolean mask to select from "t" ∇ ⍝ apply a recursive call (∇h/t) ⍝ use "h" as a boolean mask on "t", then a recursive call (('A',¨∪),'B',¨∩) ⍝ apply a fork on the results from the two recursive calls: ('A',¨∪) ⍝ prepend 'A' to each of the intersection , ⍝ concatenated with 'B',¨∪ ⍝ prepend 'B' to each of the union ``` ]
[Question] [ ## Task Write a program that takes in a compound made solely of elements with an atomic number less than or equal to 92 (Uranium), and outputs the molar mass of the compound in `grams/mole`. ## Rules and Restrictions * You may not use a function that directly calculates molar masses for you. * Your program must be able to run on an offline machine. * You MAY use a separate data file. Contents of this file must be provided. * Your score is the length of your program in bytes, plus the the length of your data file in bytes, should you choose to use one. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), therefore, lowest score wins. ## Input A string containing the compound. This string may be read through `STDIN`, passed as an argument, or set to a variable (please specify which). The following are all valid inputs: * `CH2` (one Carbon, two Hydrogens) * `(CH2)8` (8 Carbons, 16 Hydrogens) * `U` (1 Uranium) Your program is not required to function for embedded parentheses (i.e. `((CH3)2N4)4`), nor for any compound that contains an element with atomic number greater than 92. If your program does not function for either of the above two cases, it must output `Invalid formula` for such cases - no undefined behavior. ## Output You should output, to `STDOUT` or to a variable, the molar mass of the compound in `grams/mole`. A list of atomic masses of elements is available [here (Wikipedia)](http://en.wikipedia.org/wiki/List_of_elements). Your answer should be accurate to the decimal place for compounds containing fewer than 100 atoms (rounded). If the input is invalid, `Invalid formula` must be outputted. [Information on calculating the molar mass of a compound in `grams/mole` (Wikipedia).](http://en.wikipedia.org/wiki/Molar_mass) ## Examples ``` Input Output H2O 18.015 O 15.999 (16 acceptable) C6H2(NO2)3CH3 227.132 FOOF 69.995 C6H12Op3 Invalid formula Np 237 (or Invalid formula) ((C)3)4 144.132 (or Invalid formula) CodeGolf Invalid formula ``` [Answer] # Bash, ~~978 708 675 673 650 636 632 631 598~~ 594 **211 bytes for the program and 382 bytes for the data.** Input is on STDIN, output is on STDOUT. WARNING: creates files called `g` and `a`, if they exist, they will be overwritten! ``` zcat y>g 2>a s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`) p=1.008 v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'` r=(`tail -1 g`) for n in {0..91};{ p=`bc<<<$p+${r[n]}` v=${v//${s[n]}/+$p} } o=`bc<<<0$v 2>a` echo ${o:-Invalid formula} ``` ## Data file This requires a file called `y`, which is the [zopfli](https://code.google.com/p/zopfli/)-compressed form of this data (no trailing newline). zopfli is a gzip-compatible compression algorithm and can be decompressed with standard gzip tools. It was run with 1024 iterations (this is probably too much). The last 8 bytes were then removed. ``` HHeLiBeBCNOFNeNaMgAlSiPSClKArCaScTiVCrMnFeNiCoCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbITeXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcPaThU 0 2.995 2.937 2.072 1.798 1.201 1.996 1.992 2.999 1.182 2.81 1.315 2.677 1.103 2.889 1.086 3.39 3.648 .850 .130 4.878 2.911 3.075 1.054 2.942 .907 2.848 .24 4.613 1.834 4.346 2.904 2.292 4.038 .944 3.894 1.670 2.152 1.286 2.318 1.682 3.054 2.04 3.07 1.836 3.514 1.448 4.543 2.407 3.892 3.050 5.144 .696 3.693 1.612 4.422 1.578 1.211 .792 3.334 .758 5.36 1.604 5.286 1.675 3.575 2.43 2.329 1.675 4.120 1.913 3.523 2.458 2.892 2.367 4.023 1.987 2.867 1.883 3.625 3.788 2.82 1.78 .02 1 12 1 3 1 4.036 1.002 5.991 ``` The base64 of `y` is (use `base64 -d` to reproduce the original file): ``` H4sIAAAAAAACAwTB226DMAwA0G9LvEJQIbVi70LfHPBoJAiSaR729zsnBB2LVw/x0UWNMm1up4IE +90ZCC1cvsCm2mkscEJ71l56dRept7ulTDY/Lebp5CW19MLVbbAOlSrlgfVH4fIyCihaXPGg49b6 lfPHXzhvxsecxxZ+Wb6TPq7B8O1a2HjH7Aue7p1qZ0ncgsKvz/8WxuRGoigGgfcfxYvA8r7kn9iA ei6ohAt/+lzuihmD1PFnMrdIV0PeNfOczh3Ylrw8hnHaM6w1WC8V3X4hcYjOfbKlTyz0pewsP5nh plOUK9mkPzkd4HLiCbktIGyQI5uaUvZzNBrwLhOf9hJij+Jo5WBf6mHLfh2OFqeaxOHbaGAZl5mL h5UBI3Hlx99GX4llPumDjgw+NIee7uCaRbrZkzluIhJYi2E0ZU2gb5OnYBTSJQMRfv91irmCz4KK B5Va5J7T7IGjHnR22PeAd+m3F3KW/voz4BMFPGNgxHE0Loq65M6+Pw== ``` The md5sum is `d392b0f5516033f2ae0985745f299efd`. ## Explanation The numbers in the file are increments of relative atomic mass (so the relative atomic mass of lithium is `1.008 + 0 + 2.995 + 2.937`). This script works by converting the chemical formula into an arithmetical expression with `+` and `*`, replacing each symbol with its relative atomic mass, then feeding the expression to `bc`. If the formula contains invalid symbols, `bc` will give a syntax error and output nothing to STDOUT; in that case, the output is `Invalid formula`. If STDIN is empty, the output is `0`. Nested brackets are supported. ``` zcat y>g 2>a # Unzip the file y and output result to the file g. Send standard error to file a (there will be an error because the last 8 bytes are missing) s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`) # Read from g to sed; append a space after any capital letter optionally followed by a lowercase letter; exit at the end of the first line so the atomic masses are not processed in this way; parse result as space-separated array and save to variable $s p=1.008 # In the upcoming loop, $p is the value obtained in the previous iteration v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'` # Read from standard input to sed; prepend a * after any sequence of digits; replace ( with +(0; save to $v r=(`tail -1 g`) # Get the last line of file g; parse as space-separated array; save to $r for n in {0..91};{ # Loop once for each number from 0 to 91; set $n to the current number each iteration p=`bc<<<$p+${r[n]}` # Concatenate $p, + and the next number from $r; send to bc and evaluate as arithmetic expression; save to $p (i.e. add the next increment from the file to $p) v=${v//${s[n]}/+$p} # Replace every occurence of the current element symbol with + and $p (i.e. replace each symbol with a + and its relative atomic mass } # end loop o=`bc<<<0$v 2>a` # Prepend 0 to $v; send to bc and evaluate as arithmetic expression; redirect any errors on standard error to the file a; save result to $o echo ${o:-Invalid formula} # If $o is empty (if there was a syntax error), output Invalid formula; otherwise output $o ``` ## Example ``` C6H2(NO2)3CH3 #input C*6H*2+(0NO*2)*3CH*3 #after line 3 +12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3 #after the loop in lines 4-6 0+12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3 #given to bc in line 7 227.132 #output as evaluated by bc ``` [Answer] # Perl - 924 It uses a series of regex substitution operations on the inputted formula to expand the subscripted elements and groups, replace the elements with atomic weights, and transform it into a sequence of additions which it then evaluates. ``` $_=<>;chop;@g='H1008He4003Li6940Be9012B10810C12011N14007O15999F18998Ne20179Na22989Mg24305Al26981Si28085P30974S32060Cl35450Ar39948K39098Ca40078Sc44955Ti47867V50942Cr51996Mn54938Fe55845Co58933Ni58693Cu63546Zn65380Ga69723Ge72630As74922Se78960Br79904Kr83798Rb85468Sr87620Y88906Zr91224Nb92906Mo95960Tc98Ru101070Rh102906Pd106420Ag107868Cd112411In114818Sn118710Sb121760Te127600I126904Xe131293Cs132905Ba137327La138905Ce140116Pr140907Nd144242Pm145Sm150360Eu151964Gd157250Tb158925Dy162500Ho164930Er167259Tm168934Yb173054Lu174967Hf178490Ta180948W183840Re186207Os190230Ir192217Pt195084Au196967Hg200592Tl204380Pb207200Bi208980Po209At210Rn222Fr223Ra226Ac227Th232038Pa231036U238028'=~/(\D+)([\d\.]+)/g;for$b(0..91){$d=2*$b+1;$g[$d]=$g[$d]>999?$g[$d]/1000:$g[$d]}%h=@g;for$a('(\(((?>[^()]|(?1))*)\))(\d+)','()([A-Z][a-z]?)(\d+)'){for(;s/$a/$2x$3/e;){}}s/([A-Z][a-z]?)/($h{$1}||_).'+'/ge;if(/_/){print'Invalid formula';exit}$_.=0;print eval; ``` [Answer] # Mathematica 9 - ~~247~~ 227 This is clearly cheating as I'm using a function that directly calculates atomatic masses (but not molar masses!): ``` r=StringReplace;f[s_]:=Check[ToExpression@r[r[r[s,x:RegularExpression["[A-Z][a-z]*"]:>"ElementData[\""<>x<>"\",\"AtomicWeight\"]+"],x:DigitCharacter..:>"*"<>x<>"+"],{"+*"->"*","+"~~EndOfString->"","+)"->")"}],"Invalid formula"] ``` Usage: Call the function `f` with a string containing the formula, the output will be the mass. Test: ``` f["H2O"] (* => 18.0153 *) f["O"] (* => 15.9994 *) f["C6H2(NO2)3CH3"] (* => 227.131 *) f["FOOF"] (* => 69.9956 *) f["C6H12Op3"] (* => Invalid formula *) f["Np"] (* => 237 *) f["((C)3)4"] (* => 144.128 *) f["CodeGolf"] (* => Invalid formula *) ``` Mathematica 10 doesn't output a raw number, but a number with a unit, so that may not be acceptable. [Answer] # Javascript, 1002 Input is in `q` and output is in `a`. I was unsure of what the rules for rounding were, so I truncated to 3 places after the decimal (or fewer, if digits were unavailable from Wikipedia). ``` H=1.008 He=4.002 Li=6.94 Be=9.012 B=10.812 C=12.011 N=14.007 O=15.999 F=18.998 Ne=20.179 Na=22.989 Mg=24.305 Al=26.981 Si=28.085 P=30.973 S=32.06 Cl=35.45 Ar=39.948 K=39.098 Ca=40.078 Sc=44.955 Ti=47.867 V=50.941 Cr=51.996 Mn=54.938 Fe=55.845 Co=58.933 Ni=58.693 Cu=63.546 Zn=65.38 Ga=69.723 Ge=72.630 As=74.921 Se=78.96 Br=79.904 Kr=83.798 Rb=85.467 Sr=87.62 Y=88.905 Zr=91.224 Nb=92.906 Mo=95.96 Tc=98 Ru=101.07 Rh=102.905 Pd=106.42 Ag=107.868 Cd=112.411 In=114.818 Sn=118.710 Sb=121.760 Te=127.60 I=126.904 Xe=131.293 Cs=132.905 Ba=137.327 La=138.905 Ce=140.116 Pr=140.907 Nd=144.242 Pm=145 Sm=150.36 Eu=151.964 Gd=157.25 Tb=158.925 Dy=162.500 Ho=164.930 Er=167.259 Tm=168.934 Yb=173.054 Lu=174.966 Hf=178.49 Ta=180.947 W=183.84 Re=186.207 Os=190.23 Ir=192.217 Pt=195.084 Au=196.966 Hg=200.592 Tl=204.38 Pb=207.2 Bi=208.980 Po=209 At=210 Rn=222 Fr=223 Ra=226 Ac=227 Th=232.038 Pa=231.035 U=238.028 try{a=eval(q.replace(/(\d+)/g,'*$1').replace(/(\w)(?=[A-Z\(])/g,'$1+'))}catch(e){a="Invalid formula"} ``` [Answer] # Javascript (E6) 1231 As a function with the input as argument and returning the output. Precision: 3 decimal digits Use regexp to transform the chemical formula in a simple arithmethic expression, with sums and products, replacing: * `(` with `+(` * any numeric sequence with '\*', then the numeric sequence * any Capital letter followed by letters with '+', then the atomic mass of the corresponding element (if found) Then the expression is evaluated and the value returned. In case of errors or if value is NaN (or zero) then function returns 'Invalid formula' **Now I see that all other answers use the same method ...** oh well here is the javascript version ``` F=f=>{ T={H:1.008,He:4.002,Li:6.94,Be:9.012,B:10.81,C:12.011 ,N:14.007,O:15.999,F:18.998,Ne:20.179,Na:22.989,Mg:24.305 ,Al:26.981,Si:28.085,P:30.973,S:32.06,Cl:35.45,Ar:39.948 ,K:39.098,Ca:40.078,Sc:44.955,Ti:47.867,V:50.941,Cr:51.996,Mn:54.938 ,Fe:55.845,Co:58.933,Ni:58.693,Cu:63.546,Zn:65.38,Ga:69.723,Ge:72.630 ,As:74.921,Se:78.96,Br:79.904,Kr:83.798,Rb:85.467,Sr:87.62,Y:88.905,Zr:91.224 ,Nb:92.906,Mo:95.96,Tc:98,Ru:101.07,Rh:102.905,Pd:106.42,Ag:107.868,Cd:112.411 ,In:114.818,Sn:118.710,Sb:121.760,Te:127.60,I:126.904,Xe:131.293 ,Cs:132.905,Ba:137.327,La:138.905,Ce:140.116,Pr:140.907,Nd:144.242,Pm:145 ,Sm:150.36,Eu:151.964,Gd:157.25,Tb:158.925,Dy:162.500,Ho:164.930,Er:167.259 ,Tm:168.934,Yb:173.054,Lu:174.966,Hf:178.49,Ta:180.947,W:183.84,Re:186.207 ,Os:190.23,Ir:192.217,Pt:195.084,Au:196.966,Hg:200.592,Tl:204.38,Pb:207.2 ,Bi:208.980,Po:209,At:210,Rn:222,Fr:223,Ra:226,Ac:227,Th:232.038,Pa:231.035 ,U:238.028,Np:237,Pu:244,Am:243,Cm:247,Bk:247,Cf:251,Es:252,Fm:257,Md:258 ,No:259,Lr:266,Rf:267,Db:268,Sg:269,Bh:270,Hs:269,Mt:278 ,Ds:281,Rg:281,Cn:285,Uut:286,Fl:289,Uup:289,Lv:293,Uus:294,Uuo:294}; e='Invalid formula'; try{return eval(f.replace(/([A-Z][a-z]*)|(\d+)|(\()/g,(f,a,b,c)=>c?'+(':b?'*'+b:a='+'+T[a]))||e} catch(x){}return e } ``` [Answer] ## PHP — 793 (583 + 210) Largely outdistanced by [professorfish's answer](https://codegolf.stackexchange.com/a/35613/11713), who is using a similar method, but hey… The symbols and the masses are gzip-compressed in the file `a` obtained with the following code: ``` $symbolsList = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mg', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U']; $massesList = [1.008, 4.003, 6.94, 9.012, 10.81, 12.011, 14.007, 15.999, 18.998, 20.18, 22.99, 24.305, 26.982, 28.085, 30.974, 32.06, 35.45, 39.948, 39.098, 40.078, 44.956, 47.867, 50.942, 51.996, 54.938, 55.845, 58.933, 58.6934, 63.546, 65.38, 69.726, 72.630, 74.922, 78.96, 79.904, 83.798, 85.468, 87.62, 88.906, 91.224, 92.906, 95.96, 98, 101.07, 102.906, 106.42, 107.868, 112.411, 114.818, 118.710, 121.760, 127.60, 126.904, 131.293, 132.905, 137.327, 138.905, 140.116, 140.908, 144.242, 145, 150.36, 151.964, 157.25, 158.925, 162.5, 164.93, 167.259, 168.934, 173.054, 174.967, 178.49, 180.948, 183.84, 186.207, 190.23, 192.217, 195.084, 196.967, 200.592, 204.38, 207.2, 208.98, 209, 210, 222, 223, 226, 227, 232.038, 231.036, 238.029]; $fileArrayContent = [$symbolsList, $massesList]; $fileStringContent = json_encode($fileArrayContent); $file = gzopen('a', 'w9'); gzwrite($file, $fileStringContent); gzclose($file); ``` The formula should be stored in the `$f` variable: ``` $a=json_decode(gzfile('a')[0]);$r=@eval('return '.str_replace($a[0],$a[1],preg_replace(['#(?<=(?!\().)(\(|'.implode('|',$a[0]).')#','#\d+#'],['+${1}','*$0'],$f)).';');echo error_get_last()?'Invalid formula':$r; ``` Here is the ungolfed and commented version: ``` // Recover the data stored in the compressed file $fileStringContent = gzfile('a')[0]; $fileArrayContent = json_decode($fileStringContent); $symbolsList = $fileArrayContent[0]; $massesList = $fileArrayContent[1]; $formula = preg_replace('#(?<=(?!\().)(\(|'. implode('|', $symbolsList) .')#', '+${1}', $formula); // Add a "+" before each opening paranthesis and symbol not at the beginning of the string and not preceded by an opening paranthesis $formula = preg_replace('#\d+#', '*$0', $formula); // Add a "*" before each number $formula = str_replace($symbolsList, $massesList, $formula); // Replace each symbol with its corresponding mass $result = @eval('return '. $formula .';'); // Evaluate the value without showing the errors echo error_get_last() ? 'Invalid formula' : $result; // Print the value, or "Invalid formula" if there was an error ``` [Answer] # Scala, 1077 I see all your solutions in dynamically typed languages with cop-outs like `eval` or built-in atomic mass function and raise you a statically-typed language solution: ``` object M{type S=String;type Z=(Int,S) val d="H *dHe JVLi inBe!!rB !5\"C !AiN !W!O !l3F \".*Ne\":_Na\"XUMg\"fUAl#%#Si#0iP #OOS #[&Cl$!,Ar$P|K $GxCa$RBSc%(7Ti%G5V %gwCr%s.Mn&4JFe&>)Co&^yNi&\\ECu'2\"Zn'ERGa'seGe(4^As(M#Se(x Br)$$Kr)MLRb)_5Sr)v,Y *%kZr*>LNb*PBMo*ppTc+(TRu+I4Rh+\\ePd,$,Ag,3RCd,cqIn,}LSn-HrSb-i>Te.IJI .B$Xe.peCs/#sBa/RwLa/ccCe/pXPr/y!Nd0>NPm0FTSm1!VEu12\\Gd1jrTb1|aDy2DdHo2^VEr2wATm3+0Yb3W Lu3k@Hf42nTa4L{W 4kfRe5&wOs5QdIr5fqPt6'BAu6;DHg6azTl7,8Pb7J8Bi7]2Po7]FAt7h$Rn9+bFr96@Ra9V8Ac9`tTh:8NPa:-mU :x4".grouped(5).map{s=>(s.take(2).trim,s(2)*8836+s(3)*94+s(4)-285792)}.toMap def k(n:S):Z={val x=n.takeWhile(_.isDigit);(if(x=="")1 else x.toInt,n drop x.length)} def o(m:S):Z={if(m(0)==40){val(i,s)=a(m.tail);if(s(0)!=41)???;val(j,t)=k(s.tail);(j*i,t)}else{val l=if(m.size>1&&m(1).isLower)2 else 1;val(i,s)=d(m.take(l))->m.drop(l);val(j,t)=k(s);(j*i,t)}} def a(m:S)={var(r,s)=(m,0);do{val(y,z)=o(r);r=z;s+=y}while(r!=""&&r(0)!=41);s->r} def main(q:Array[S]){println(try{val(m,s)=a(io.Source.stdin.getLines.next);if(s!="")???;m/1e3}catch{case _=>"Invalid formula"})}} ``` I should consider some compression for the data, but for now let's just have the atomic masses in base 94, uncompressed. ]
[Question] [ My dog is barking at me, but I'm too lazy to take him for a walk. I have an idea! I'll get the people at Code Golf to do it for me! Your challenge is to simulate a dog's walk. Here are the rules for walking the dog: * The human (`H`) will start at `0,0` on a (Cartesian) coordinate plane, and will randomly go one space either up, left, right, or down every second. * The dog (`D`) will start at the same location, and will go either zero, one, two, or three spaces either up, left, right, or down every second (randomly, of course). The dog is less predictable and will sometimes run faster or stop completely. * The dog will never get more than a certain amount of units away from the human (in Euclidean distance), which is the length of the leash (`L`). For example, if `L` is `6`, a valid position would be `H(0,0) D(4,4)` (since the distance is about 5.65 units), but not `H(0,0) D(5,4)` (about 6.4 units). + If, when the dog moves, it would violate the leash distance requirement, it must go the farthest it can in its determined direction that does not violate the distance requirement. For example, if the position is `H(0,0) D(3,4)` and the dog is randomly decided to move 3 spaces to the right, it will go to `D(4,4)`, since that's the farthest it can go without getting more than 6 units away. (Note that this might result in a movement of 0 spaces, i.e. no movement at all!) * Miscellaneous rules: the human moves first. The human must not exceed the leash length on its move. If it does, it must choose another direction. "Random" means "with an even distribution and with no patterns." The input will be given in this format (can be STDIN, function parameter, file, etc.): ``` "<amount of seconds the walk will last> <leash length>" ``` For example: ``` 300 6 // a 5 minute walk with a 6 yard leash ``` You must give output in this format (can be STDOUT, function return value, file, etc.): ``` H(0,0) D(0,0) H(0,1) D(2,0) H(1,1) D(2,1) H(1,0) D(2,-1) ... ``` (The amount of lines output will be `seconds + 1`, since the `H(0,0) D(0,0)` line doesn't count.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # CoffeeScript - 324 + function call Demo (Using Leash 10): ``` H(0,0) D(0,0) H(0,-1) D(0,3) H(-1,-1) D(0,3) H(-1,-2) D(-1,3) H(-1,-3) D(-4,3) H(-1,-2) D(-4,4) H(-1,-3) D(-5,4) H(-1,-2) D(-2,4) H(-1,-3) D(-2,5) H(-1,-4) D(-2,5) H(-1,-3) D(-3,5) H(0,-3) D(-4,5) H(-1,-3) D(-4,6) H(-1,-4) D(-2,6) H(-2,-4) D(-2,6) H(-3,-4) D(-5,6) H(-4,-4) D(-5,6) H(-4,-3) D(-5,8) H(-5,-3) D(-2,8) H(-5,-2) D(-2,8) H(-5,-3) D(-2,5) ``` Code: ``` w=(i)-> [s,l]=i.split ' ';m=Math;h=[0,0];d=[0,0];r=->(4*m.random())|0 a=->m.abs(h[0]-d[0])**2+m.abs(h[1]-d[1])**2<=l**2 b=(x)->if x%2 then 1else-1 for i in[0..s] console.log "H(#{h}) D(#{d})" loop H=h.slice();x=r();h[(x/2)|0]+=b x;break if a();h=H D=r();x=r();(d[(x/2)|0]+=b x;d[(x/2)|0]-=b x if!a())while D-->0 ``` Long Code: ``` human = [ 0, 0 ] doge = [ 0, 0 ] randomDirection = -> [ 'u', 'd', 'l', 'r' ][(4*Math.random())|0] allowed = -> Math.abs(human[0] - doge[0]) ** 2 + Math.abs(human[1] - doge[1]) ** 2 <= leash**2 leash = 0 walk = (input) -> [ seconds, leash ] = input.split ' ' for i in [0..seconds] console.log "H(#{human}) D(#{doge}) #{Math.sqrt Math.abs(human[0] - doge[0]) ** 2 + Math.abs(human[1] - doge[1]) ** 2}" valid = no loop oldHuman = human.slice() switch randomDirection() when 'u' human[0]-- when 'd' human[0]++ when 'l' human[1]-- when 'r' human[1]++ if allowed() break else human = oldHuman dogeDistance = (Math.random() * 4)|0 switch randomDirection() when 'u' while dogeDistance-- > 0 doge[0]-- doge[0]++ if !allowed() when 'd' while dogeDistance-- > 0 doge[0]++ doge[0]-- if !allowed() when 'l' while dogeDistance-- > 0 doge[1]-- doge[1]++ if !allowed() when 'r' while dogeDistance-- > 0 doge[1]++ doge[1]-- if !allowed() walk "10 2" ``` [Answer] ## Ruby, 189 177 I can possibly drop this a bit. I don't love `j`. ``` h=d=0;e,l=$* def j;[1,-1,?i,'-i'].sample.to_c end 0.upto(e.to_i){puts'H(%d,%d) D(%d,%d)'%(h.rect+d.rect) 1 while((g=h+j)-d).abs>l.to_i h,s=g,j 3.times{d+=s if(d+s-h).abs<=l.to_i}} ``` Ungolfed: ``` h=d=0 # use complex numbers since it has distance built in time,leash=$* def randomDirection [1,-1,'i','-i'].sample.to_c end 0.upto(time.to_i) { # (1 + time) times puts"H(%d,%d) D(%d,%d)"%(h.rect+d.rect) # that's [h.real, h.imag, d.real, d.imag] # find a newH that doesn't violate the leash newH = h + randomDirection while((g-d).abs > leash.to_i) newH = h + randomDirection end h = newH newD = randomDirection 3.times{ # keep adding newD until you hit the leash d += newD if(d + newD - h).abs <= leash.to_i } } ``` [Answer] ### GolfScript, 140 characters ``` ~.*:L;)[0.].@{['H('1$','*') D('4$','*')'n]@@{[@~]}+[{)}{(}{\(\}{\)\}]:^%{{~2$~@-.*@@-.*+L>!},}:F~.,{rand}:R~=\[.;{.[~}^4R=+{]}+4R*]F-1=\}*;; ``` Example run (try [online](http://golfscript.apphb.com/?c=OyIxMCAzIgoKfi4qOkw7KVswLl0uQHtbJ0goJzEkJywnKicpIEQoJzQkJywnKicpJ25dQEB7W0B%2BXX0rW3spfXsofXtcKFx9e1wpXH1dOl4le3t%2BMiR%2BQC0uKkBALS4qK0w%2BIX0sfTpGfi4se3JhbmR9OlJ%2BPVxbLjt7Llt%2BfV40Uj0re119KzRSKl1GLTE9XH0qOzsK&run=true)): ``` > 10 3 H(0,0) D(0,0) H(0,1) D(0,0) H(0,0) D(0,2) H(0,1) D(-1,2) H(1,1) D(-1,2) H(1,2) D(-1,4) H(1,3) D(-1,5) H(0,3) D(-1,5) H(-1,3) D(1,5) H(-1,4) D(1,5) H(0,4) D(-1,5) ``` [Answer] # Mathematica 285 ## Golfed ``` r=RandomChoice;k=False; s:=r[{{0,1},{-1,0},{1,0},{0,-1}}] w:=r[{0,1,2,3,4}] f[{-1,___}]:=""; f[{n_,l_,{h_,d_}}]:= (Print["H(",h,")\t","D(",d,")"]; m[i_,u_,v_]:=EuclideanDistance[u+i,v]<l; z=k;While[z==k,t=s;z=m[t,h,d]]; y=h+t;t=w*s;z=k;While[z==k,t=t-Sign@t;z=m[t,d,y]]; dp=d+t;f[{n-1,l,{y, dp}}]) ``` **Example** ``` f[{17,7,{{0,0},{0,0}}}] ``` > > H({0,0}) D({0,0}) > > H({1,0}) D({0,0}) > > H({2,0}) D({0,2}) > > H({2,-1}) D({0,-1}) > > H({1,-1}) D({-3,-1}) > > H({1,0}) D({-3,1}) > > H({1,1}) D({0,1}) > > H({1,2}) D({0,2}) > > H({1,1}) D({0,2}) > > H({1,0}) D({-2,2}) > > H({2,0}) D({1,2}) > > H({2,-1}) D({-2,2}) > > H({2,0}) D({-2,3}) > > H({2,1}) D({-2,0}) > > H({1,1}) D({-2,3}) > > H({2,1}) D({-2,6}) > > H({1,1}) D({-3,6}) > > H({0,1}) D({-4,6}) > > > --- ## UnGolfed There are some comments in the text below. I've also included a printout which makes it possible to follow some of the calculations. ``` step:=RandomChoice[{{0,1},{-1,0},{1,0},{0,-1}}] dogWander:=RandomChoice[{0,1,2,3,4}] f[{-1,___}]:=""; f[{n_,l_,{humanPos_,dogPos_}}]:= Module[{tempStep,moveOK,hp,hp1,dp,p,test}, (* human imagines step, checks with leash, chooses another step if would choke the dog *) moveOK[intendedStep_,pos1_,pos2_]:=EuclideanDistance[pos1+intendedStep,pos2]<l; test=False;While[test==False,tempStep=step;test=moveOK[tempStep,humanPos,dogPos]]; hp=humanPos+tempStep; Print["humanPos before: ", humanPos,"\t","human step: ",tempStep,"\thumanPos after: ",hp,"\tdistance from dog: ",N@EuclideanDistance[hp,dogPos]]; (*move closer to human if needed *) tempStep=dogWander*step; test=False;While[test==False,tempStep=tempStep-Sign[tempStep];test=moveOK[tempStep,dogPos,hp]]; dp=dogPos+tempStep; Print["dog's intended step: ",tempStep,"\tdogPos before: ",dogPos,"\t","dog actual step: ",tempStep, "\t","dogPos after: ",dp,"\tdistance: ",N@EuclideanDistance[hp,dp],"\n"]; f[{n-1,l,{hp, dp}}]] ``` Example ``` f[{17,5,{{0,0},{0,0}}}] ``` [Part of the printout is shown to give a sense of how the code works. ] ![printout](https://i.stack.imgur.com/0HBxS.png) ]
[Question] [ I heva this wierd text where vewols seem to be ratetod : > > I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me ! > > > So I'd need a pragrom which can rateto the vewols (and the 'y' letter as it seems) back so that the text is raadeble agian. Ouy can choeso the lungaega of ouyr chieco privedod ouy meka a cempleto pragrom (so not just a finctoun). The yntre can be an unpit feild, a text feli, or the cammond leni. The uutpot mya olsa vyra as ouy leki. Of cuerso I'll anvilid yna pragrom uutpitong bad texts. There's no vulea in a pragrom which mekas texts ouy can't endarstund. But ouy can wreti ouyr cemmonts and qeistouns in ratetod texts if ouy want. --- ### Clarifications * Your program is only required to handle ASCII text. * For the purposes of this question, the following characters are vowels: `aeiouy` * The positions of the vowels within each word should be rotated. There is some flexibility in deciding what qualifies as a word: the minimum requirement is that two characters separated by a space are in different words, and that two alphabetic characters (`a-zA-Z`) separated only by alphabetic characters are in the same word. * The desired direction of rotation should be inferred from the test cases below. ### Test cases Input: `I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me !` Output: `I'm a bydla wrettin text. Semo lanituc gyu plyead with the erdor of vewols. Plaese fix me !` Input: `AeiOuy` Output: `EioUya` Input: `Hyphenated-word` Output: `Hephanetyd-word` or `Hephanetod-wyrd` [Answer] ### GolfScript, 68 67 57 characters ``` " "/{..+{95&"AEIOUY"?)}:C,1>\{.C!!{96&\(31&@|}*}%\;}%" "* ``` Input must be given on STDIN. Example ([online](http://golfscript.apphb.com/?c=OyJZb3UhISEgSSdtIGEgYmFkbHkgd3JpdHRlbiB0ZXh0LiBTb21lIGx1bmF0aWMgZ3V5IHBsYXllZCB3aXRoIHRoZSBvcmRlciBvZiB2b3dlbHMuIFBsZWFzZSBmaXggbWUgISIKCiIgIi97Li4rezk1JiJBRUlPVVkiPyl9OkMsMT5cey5DISF7OTYmXCgzMSZAfH0qfSVcO30lIiAiKgo%3D&run=true)): ``` > You!!! I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me ! Ouy!!! I'm a bydla wrettin text. Semo lanituc gyu plyead with the erdor of vewols. Plaese fix me ! ``` [Answer] ### Ruby, 91 90 characters ``` $><<gets.gsub(/\S+/){|x|x.gsub(r=/[aeiouy]/i){|y|z=$'[r]||x[r];y>?Z?z.downcase: z.upcase}} ``` ### Coffeescript, 148 charectars ``` alert prompt().replace /\S+/g,(x)->x.replace r=/[aeiouy](?=(.*))/gi,(y,z)->((t=z.match r)&&t[0]||x.match(r)[0])[['toLow','toUpp'][y>'Z']+'erCase']() ``` No ussimtoans, except that "holf-cerract" is a word, and not my sulitoon. Test: ``` > To test this program, simply enter a long sentence that appears half-broken To test this pragrom, sympli enter a long sentence that eppaars holf-brekan > No MaTtEr HoW mUcH cAsE yOu uSe, It WoRkS No MeTtAr HoW mUcH cEsA oUy eSu, It WoRkS ``` [Answer] ## Haskell, 159 characters Didn't end up quite as short as I'd hoped, but I decided to post it anyway: ``` import Data.Char f s=let(v,t)=foldr g(v,[])s in t g x(v,t)=last$(v,x:t):[(x,c v:t)|c<-[toUpper,toLower],x`elem`map c"AEIOUY"] main=interact$unwords.map f.words ``` **Ungolfed version:** ``` import Data.Char rotateVowels :: String -> String rotateVowels word = result where (vowel, result) = foldr step (vowel, []) word step ch (vowel, rest) | ch `elem` "AEIOUY" = (ch, toUpper vowel : rest) | ch `elem` "aeiouy" = (ch, toLower vowel : rest) | otherwise = (vowel, ch : rest) main = interact $ unwords . map rotateVowels . words ``` This is a nice example of how lazy evaluation can let you do cool tricks. In `rotateVowels`, each time a new vowel is found, it is passed on to the left, while replacing it with the one coming from the right. This part of the output from the fold is fed back as the input so that the leftmost vowel becomes the replacement for the rightmost one. ``` (vowel, result) = foldr step (vowel, []) word ^^^^^ ^^^^^ this part of the output is part of the input ``` [Answer] # [Python 2](https://docs.python.org/2/), 172 bytes ``` for w in input().split():p=[];q=list(w);z=filter(lambda c:c in'aeiouyAEIOUY',q);x=z[1:]+z[:1];print''.join(y in z and[str.upper,str.lower][y>'Z'](x.pop(0))or y for y in q), ``` [Try it online!](https://tio.run/##HY9BT8MwDIXv@xUml7QwKga3VkXaAYmdhoQ4QFWhrHFpUJZkqUub/vmSTrLsJ0uf37ML1FnzuDRWYskYW1rrYQRlYrmBkjTrnVZx5q6s6uJSatVTMqbFXLZKE/pEi/NJCmjyJiJcoLJD2L8cjh@ffHtJi6mcq11e381VvqsL55UhzrNfq0wSVpsZhJFVTz4bnEO/XZW2I/q6Cs/8i9fJlDnrkoc0jckCtNcewUu6XWLgzbr4Xq2B3z7lGwCcsIH1n6ivfgs78DMIOAmpA4xeEaEBwokyeLdnBD0YQaqBnyGA0yKghFFRB9QhWC/Rg23hL4bSfQZvGkWP0KoJInrDNmyP6jiEKF6D6zCeQnk/Ro79Aw "Python 2 – Try It Online") ]
[Question] [ When I was a child I used to play a variation of [Snap](https://en.wikipedia.org/wiki/Snap_(card_game)) to stake soccer trading cards. "Game" is an overstatement because the only role of the players is to secretly prepare their starting piles. As the game starts there are no choices other than just perform the game algorithm. ## Rules There is no maximum number of players and they all start with a fixed number of cards. Players in turn play the top card of their piles on a common pile (initially empty). ***If the current player has no cards***, the common pile bottom card will be played. ***When a player happens to play an equal card to that on top of the common pile***: * This player will take the common pile and append it face-down to his own pile. (Players' piles are face-down but the common pile is face-up, so the pair of equal cards should end up at the bottom) * Anyone with no cards is out of the game. * This player has to resume the game replenish the common pile with their top card as usual. ***The game ends*** in one of three scenarios: * one player has all the cards (they win) * all the cards are in the common pile, the next player rotates it but doesn't form a pair (the common pile can't be taken) * one previous state of the game reoccurs (the game gets stuck in a loop) ## Step by step game examples ``` 1) Initial configuration: "abba abca" p1 p2 common pile 1 abba abca 2 bba abca a 3 bba bca aa 4 TAKES 5 bba bcaaa 6 bba caaa b 7 ba caaa bb 8 TAKES 9 babb caaa 10 abb caaa b 11 abb aaa bc 12 bb aaa bca 13 bb aa bcaa 14 TAKES 15 bb aabcaa 16 bb abcaa a 17 b abcaa ab 18 b bcaa aba 19 bcaa abab 20 caa ababb 21 OUT TAKES 22 caaababb ============ p2 wins ============ 2) Initial configuration: "abba acab" p1 p2 common pile 1 abba acab 2 bba acab a 3 bba cab aa 4 TAKES 5 bba cabaa 6 bba abaa c 7 ba abaa cb 8 ba baa cba 9 a baa cbab 10 a aa cbabb 11 TAKES 12 a aacbabb 13 a acbabb a 14 acbabb aa 15 TAKES 16 aa acbabb 17 a acbabb a 18 a cbabb aa 19 TAKES 20 a cbabbaa 21 a babbaa c 22 babbaa ca 23 abbaa cab 24 abbaa abc 25 bbaa abca 26 bbaa bcaa 27 TAKES 28 bcaa bbaa 29 caa bbaa b 30 caa baa bb 31 TAKES 32 caa baabb 33 caa aabb b 34 aa aabb bc 35 aa abb bca 36 a abb bcaa 37 TAKES 38 abcaa abb 39 bcaa abb a 40 bcaa bb aa 41 TAKES 42 bcaa bbaa 43 bcaa baa b 44 caa baa bb 45 TAKES 46 caabb baa 47 aabb baa c 48 aabb aa cb 49 abb aa cba 50 abb a cbaa 51 TAKES 52 abb acbaa 53 abb cbaa a 54 bb cbaa aa 55 TAKES 56 bbaa cbaa 57 baa cbaa b 58 baa baa bc 59 aa baa bcb 60 aa aa bcbb 61 TAKES 62 aa aabcbb 63 aa abcbb a 64 a abcbb aa 65 TAKES 66 aaa abcbb 67 aa abcbb a 68 aa bcbb aa 69 TAKES 70 aa bcbbaa 71 aa cbbaa b 72 a cbbaa ba 73 a bbaa bac 74 bbaa baca 75 baa bacab 76 baa acabb 77 TAKES 78 acabb baa 79 cabb baa a 80 cabb aa ab 81 abb aa abc 82 abb a abca 83 bb a abcaa 84 TAKES 85 bbabcaa a 86 babcaa a b 87 babcaa ba 88 abcaa bab 89 abcaa abb 90 TAKES 91 abcaa abb 92 abcaa bb a 93 bcaa bb aa 94 TAKES 95 bcaaaa bb 96 caaaa bb b 97 caaaa b bb 98 TAKES 99 caaaa bbb 100 caaaa bb b 101 aaaa bb bc 102 aaaa b bcb 103 aaa b bcba 104 aaa bcbab 105 aa bcbaba 106 aa cbabab 107 a cbababa 108 a bababac 109 bababaca 110 ababacab // common pile can't be taken ============ p1, p2 in game ============ 3) Initial configuration: "bdad acbc abba" p1 p2 p3 common pile 1 bdad acbc abba 2 dad acbc abba b 3 dad cbc abba ba 4 dad cbc bba baa 5 TAKES 6 dad cbc bbabaa 7 dad cbc babaa b 8 ad cbc babaa bd 9 ad bc babaa bdc 10 ad bc abaa bdcb 11 d bc abaa bdcba 12 d c abaa bdcbab 13 d c baa bdcbaba 14 c baa bdcbabad 15 baa bdcbabadc 16 aa bdcbabadcb 17 aa dcbabadcbb 18 TAKES OUT 19 dcbabadcbb aa 20 cbabadcbb aa d 21 cbabadcbb a da 22 babadcbb a dac 23 babadcbb daca 24 abadcbb dacab 25 abadcbb acabd 26 badcbb acabda 27 badcbb cabdaa 28 TAKES 29 badcbb cabdaa 30 badcbb abdaa c 31 adcbb abdaa cb 32 adcbb bdaa cba 33 dcbb bdaa cbaa 34 TAKES 35 dcbbcbaa bdaa 36 cbbcbaa bdaa d 37 cbbcbaa daa db 38 bbcbaa daa dbc 39 bbcbaa aa dbcd 40 bcbaa aa dbcdb 41 bcbaa a dbcdba 42 cbaa a dbcdbab 43 cbaa dbcdbaba 44 baa dbcdbabac 45 baa bcdbabacd 46 aa bcdbabacdb 47 aa cdbabacdbb 48 TAKES 49 aa cdbabacdbb 50 aa dbabacdbb c 51 a dbabacdbb ca 52 a babacdbb cad 53 babacdbb cada 54 abacdbb cadab 55 abacdbb adabc 56 bacdbb adabca 57 bacdbb dabcaa 58 TAKES 59 dabcaa bacdbb 60 abcaa bacdbb d 61 abcaa acdbb db 62 bcaa acdbb dba 63 bcaa cdbb dbaa 64 TAKES 65 bcaa cdbbdbaa 66 bcaa dbbdbaa c 67 caa dbbdbaa cb 68 caa bbdbaa cbd 69 aa bbdbaa cbdc 70 aa bdbaa cbdcb 71 a bdbaa cbdcba 72 a dbaa cbdcbab 73 dbaa cbdcbaba 74 baa cbdcbabad 75 baa bdcbabadc 76 aa bdcbabadcb 77 aa dcbabadcbb 78 TAKES 79 dcbabadcbb aa // loop (line 19) ============ p1, p3 in game ============ ``` **N.B.** game states are inviduated by piles configuration and current player. As you can see in example `2)` lines 28, 42 are not the same game state. ## Input A list of players' piles (top to bottom) as: * an array of strings `["code", "golf", "fold"]`, or * a matrix of positive integers `[[1,2,3,4],[5,2,6,7],[7,2,6,3]]` Players order is implied by piles order. ## Output A number indicating the player who wins or a list of numbers for the players who reach the end of the game. You decide whether players are 0 or 1 indexed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). ## I/O Examples (1-indexed players): ``` "abca abba" -> 1 "abba abca" -> 2 "abba acab" -> 1 2 "bdad acbc abba" -> 1 3 "fizz buzz" -> 2 "robinhooda ndlittlejo hnwalkingt hroughthef orestlaugh ingbackand forthatwha ttheothero nehastosay" -> 9 ``` [Answer] # JavaScript (Node.js), ~~483~~ 426 bytes *-57 bytes thanks to @emanresu A* Takes a list of strings as input and indexes from 0. [Try it online!](https://tio.run/##XVFNb9swDL3nV6gBakiIKzTXCkpPuwzYdtjRMAbali0liuRIctt8/faMtpcVmwES1CP5/Ehu4Q1iHUyfnpxv1C3KG8jNGSTwPfS0l5uCc96XTChZlCKNzo/OyGfRYZVVrkta7KWTG@oeu1XHHjsR5K@5E/hOHSNlJW@NTSrQD7l5aOgHY6KRGHtuXG2HRkXExGFs@/rzx3ceUzCuM@2RFj43OeQKJbQ@UCHY2bQUOQzLMmql@iNBYjS4qE2bKBSm5HOYeD9ETQ@UMXa5KN77HsMse4C7IpyxL55LhpZThR6ZinWZZbOnRu6peVrnE@lEhnMpHtSbClGNvPm4m9z/TSK1hfQN90f7fMtm/suloVv2ql62jK3WUnYox2JzUGkIjtjXQNkLGpYKHDB9LuYwS1it2Wc5Fl6vt9q7mEhSMUUiSbEg@C2hqoFAVcEyvwPVCNT/ATVUd6BqoEGgqv/pa83pRKrhdLoDwVfGae8bIK6xJiWrtp5o9w52h9dKRAc/dDpp1RIfUJUFfBJMVVDvwDUEL5g0pHcNJGGZRwueOKUhJh/hiH8qxWIxTcSx@AvUmo4vIjfkPKkYZ/YWr@47Gqccjz2KoUuyxP2IxZWJ228 "JavaScript (Node.js) – Try It Online") ``` a=>{a=a.map(p=>[...p]);e=[];t=[];o=[];i=0;g=a.length;m=n=>(n%g+g)%g;r=_=>[...a.keys()].filter(x=>!d(x));d=x=>o.includes(x);q=_=>JSON.stringify([o,i,a,e]);for(;;){if(!d(i)&&(l=e.length==e.unshift(a[i].shift(t.push(q()))||e.pop())&&!a.filter(p=>p[0])[0],(e[0]==e[1]&&e[1]&&(i=m(i-1,a[i].push(...e.reverse())),e=[],o.push(...a.flatMap((p,j)=>p[0]||d(j)?e:j))+1==g)||l)))return l?r():r()[0];if(t.includes(q(i=m(i+1))))return r()}} ``` **Unminified** ``` (a) => { a = a.map((p) => [...p]); e = []; t = []; o = []; i = 0; g = a.length; m = (n) => ((n % g) + g) % g; r = (_) => [...a.keys()].filter((x) => !d(x)); d = (x) => o.includes(x); q = (_) => JSON.stringify([o, i, a, e]); for (;;) { if ( !d(i) && ((l = e.length == e.unshift(a[i].shift(t.push(q())) || e.pop()) && !a.filter((p) => p[0])[0]), (e[0] == e[1] && e[1] && ((i = m(i - 1, a[i].push(...e.reverse()))), (e = []), o.push(...a.flatMap((p, j) => (p[0] || d(j) ? e : j))) + 1 == g)) || l) ) return l ? r() : r()[0]; if (t.includes(q((i = m(i + 1))))) return r(); } }; ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 378 bytes ``` def f(s,p='',G=[],V=sorted,E=enumerate): O=V(p.join(s)) while 1: for i,S in E(s): if S:p+=S[0];s[i]=S[1:] elif""==S:p=p[1:]+p[0] if s[i]!=0<1<len(p)!=p[-2]==p[-1]:s[i]+=p;s=[P or 0for P in s];p=s[i][0];s[i]=s[i][1:] C=s+[p,i] if any(a and O==V(a)for a in s)or(O==V(p)*all(a!=b for a,b in zip(p,p[1:]+p[0])))or C in G:return[i for i,S in E(s)if S!=0] G+=[C] ``` [Try it online!](https://tio.run/##XVLBbtswDL37K5heLM1ukWyXwalOQZHLgBUI0IvnAxXLsVpXEiQFQfLzGemmG9CDZZKP5HtPdjjn0bsfP0O8XnszwCBSHVRZ1lvVdvWLSj5m09dPyrjju4mYjWwK@K1eRHh49daJJGUBp9FOBlaEwOAj2HoH1sETgVwCO8CuCZXatctunVrbUbRqOobMZIe7O6UIV4GLVaCm2xC3LtTycfU4GSeCXFDL/fdO8WvVNQxXKqyTap@BaJfM/czMqVsHxfA/wjm5cW5UqtpQ208adGeBdPbki4yh5D0475E@irkY5DecJoELpWeLWGtuuNggQv1fuJQ0ARuGtk00@Rhda7/eCV8H2Zrpt5VqN901m5QTKCjLEvWexGiNBR/A6S3aoy50jz1Fev/RMtjLBfTxcimi19aN3vcIrp9szpN59TC6E05v1h0yjNEfD2Me6SP7SHQTUkqSDhr3b2yeVOYR82lEyNTm6YkenBkxZZ/wTNoeUqDVovzjSlkULPqX/RDecvIJQzlfIZfY82yuK4qvtXmWfpAQrctiEFyT8voX "Python 3.8 (pre-release) – Try It Online") Wow, was this a pain to write. Takes in a list of strings, outputs a list of 0-indexed numbers. My code can be slightly changed to output a single value if a single player wins, but I see no rule preventing me from outputting as my code does. ## Explanation Stores game states in `G`. A *state* here is the list of strings followed by the pile and the number indicating whose turn it is (evidently, whose turn it is does make a difference). If the current state has been seen before, we break by setting T to 1. (breaks from the inner loop then from the outer loop) For each iteration, if S is truthy (current string) we append its first letter to the pile and remove it from `s[i]`. If `S` is empty string, we rotate the pile. A zero indicates that the player is out; we ignore such cases. If the last two characters of `p` are the same, we append the entire pile to the end of `s[i]` and reset it, before resuming the game in the same iteration. The two other checks for the endgame are: * if any of the sorted strings in `s` match the sorted `O`, or * if the sorted pile equals sorted `O` and there are no neighboring pairs in the pile (end and beginning count as a pair). To get the list of "in" players, we simply output all indices corresponding to a nonzero entry in `s`. Any tips for shortening the code will be greatly appreciated. Thanks to @ovs for ~~-28~~ -35 bytes! [Answer] # [Perl 5](https://www.perl.org/), 209 bytes ``` sub{(@p,$i,$_,%s,@o)=pop=~/\w+/g;while((@w=grep$p[$_-1],1..@p)>1||y///c and!$s{$i,@p,@o}++){if(!$o[$i]&&($p[$i]=~s,.,,||s,.,,)&&($_.=$&)=~s/.*(.)\1$//){$p[$i].=$&;$p[$_]or$o[$_]=1for 0..$#p;next}$i=++$i%@p}@w} ``` [Try it online!](https://tio.run/##ZZBfb5swFMXf8yluMydAcGBs2qQWueN90vqytwQhm79umO2BI5oQ@tUzQ7Ks1ZAs7Ps759xrq7ypv5xRQc7tnvV2pDDiGCV40eJIOkRJRV79bef6ZdhVvM5tO@pI2eQKqQ1K1kGMA8@LlPMYnE4H3/dToCK7Q21vYkxYJAfXdXpe2HdIbhCPl0t7dPKYvLbYw/h0mn7OWE88gpaOAb63sj1nGyDfd/qLfETh1DOWzRiVxCQoZAMfPQ99UKHIX/SAOHFdxBeRGqJuOIczI7BnAJs5ZSkFyhidw/SRRzCjXxEbUfoGfXqHUsreuPCNsoxmhrL0Gnyhn6@04McjsP3x@H9sIxkXlZQZBZHVXOs6f5ZQiY7WOy5KDVUj92Wlq7wA2eStrqk5gkGMpjvzvmDupSuqu4qCNjJpViNB5BVttWzpYRrm3rRz@tnY/NcBEBeKtBUvdISS8FbNXxR5llxY2MLvQCn1DSxRYY9@5x82Y@1rTUY/5L8nOXwDS@4seABrtVr9ePoJT9@ti0M1XOhivljft2AcD7BYf21N3bhu@7HBVszx32w8DYen6HA2nP8A "Perl 5 – Try It Online") ]
[Question] [ The game [shapez.io](https://shapez.io) has a *lot* of shapes. In [my previous challenge](https://codegolf.stackexchange.com/questions/233709/make-me-a-shape/233738#233738), the object was to generate a random code for a shape. Now, your challenge is to render a shape. # Specs ## Shapes Each shape has a unique shortcode, for example: [![enter image description here](https://i.stack.imgur.com/hYiU5.png)](https://i.stack.imgur.com/hYiU5.png) is `CrWgRuSp` - clockwise from top right, **r**ed **c**ircle, **g**reen **w**edge, **u**ncolored **r**ectangle, **p**urple **s**tar. A *quadrant* is one of Rectangle (`R`), Circle (`C`), Star (`S`) or Wedge (`W`) painted with one of the below colours. The shortcode for these quadrants is the code for the shape concatenated to the code for the color, so a yellow star would be `Sy`. A quadrant can also be empty, with the code `--`. Four quadrants concatenated together make a layer, the quadrants going clockwise from top-right. Layers will never be empty (`--------`). Finally, between one and four layers stacked on top of each other (joined by `:`, lowest first) make a shape. For example, `CyCyCyCy:SrSrSrSr` looks like: [![enter image description here](https://i.stack.imgur.com/AE2f1.png)](https://i.stack.imgur.com/AE2f1.png) ## Colours The colours are as follows: * uncolored / `u` / grey - #AAAAAA * red / `r` - #FC666A * blue / `b` - #66A7FF * green / `g` - #78FF65 * purple / `p` - #DD66FF * yellow / `y` - #FDF52A * cyan / `c` - #87FFF5 * white / `w` - #FFFFFF * border - #555555 ## Sizes Given a constant \$a\$, the width of a single border, the shape sizes are as follows: | Shape | Spec | Image | | --- | --- | --- | | Circle | A perfectly circular arc going out to 9a each way | [enter image description here](https://i.stack.imgur.com/GcGkv.png) | | Rectangle | A square with side 9a | [enter image description here](https://i.stack.imgur.com/gzUQp.png) | | Wedge | A shape with one side going out to 9a, the other going along the base to 5.75a before going diagonally to 9a. | [enter image description here](https://i.stack.imgur.com/ptRpg.png) | | Star | Both edges going out to 5.75a before going diagonally out to 9a and meeting up. | [enter image description here](https://i.stack.imgur.com/B3JOB.png) | These need to be multiplied by the scale factor for the correct layer: * layer 1 (bottom) - 1 * layer 2 - \$\frac{7}{9}\$ * layer 3 - \$\frac{19}{36}\$ * layer 4 - \$\frac{5}{18}\$ You should render your shape with a value of \$a ≥ 10\$ pixels - your choice of the size. Note: All sizes are approximations - If you have a better estimate, let me know. All sizes are flexible within 1%. You may take either a shape shortcode (layers joined by `:`), a list of layer shortcodes, or a list of lists of quadrant shortcodes. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases `CyCyCyCy:SrSrSrSr` - [![enter image description here](https://i.stack.imgur.com/RC9aH.png)](https://i.stack.imgur.com/RC9aH.png) `CuCuCuCu:------Cy` - [![enter image description here](https://i.stack.imgur.com/LKxDX.png)](https://i.stack.imgur.com/LKxDX.png) `------Cg:------Cr` - [![enter image description here](https://i.stack.imgur.com/7k5Ja.png)](https://i.stack.imgur.com/7k5Ja.png) `CrSyWgRb` - [![enter image description here](https://i.stack.imgur.com/RYsIX.png)](https://i.stack.imgur.com/RYsIX.png) `Cr------:------Cr:Cr------:------Cr` - [![enter image description here](https://i.stack.imgur.com/17yf0.png)](https://i.stack.imgur.com/17yf0.png) Note that you *don't* have to render the pale-grey circle in the background. [Answer] ## JavaScript (ES10) + SVG (HTML5), ~~407~~ ~~387~~ ~~365~~ 340 bytes ``` g=s=>s.split`:`.map(s=>s.match(/../g)||[]);f= l=>'<svg viewBox=-1350,-1350,2700,2700 stroke=#555>'+l.map((q,i)=>q.map(([s,c],o)=>`<path d=M0,0v-${{C:'36a36,36,0,0,1,36,',R:'36h36v',W:'23l36,-13v',S:'23l36,-13l-13,'}[s]}36z fill=#${"FDF52A/FC666A/66A7FF/87FFF5/AAA//FFF/78FF65/D6F".split`/`[parseInt(c,36)%17%9]} transform=rotate(${o*90})scale(${q=35-i*9+!i}) stroke-width=${108/q} />`)) ``` ``` <input oninput=o.innerHTML=f(g(this.value))><div id=o> ``` Takes input as a list of list and outputs SVG source parseable by HTML5. Note that as it's scalable I can't really specify what the value of `a` is, it's always just big enough to fit the width of the window. At the start is the `svg` element definition, followed by a `path` element for each of the (possibly 16) quadrants, sized, coloured and rotated appropriately. Edit: Saved 22 bytes thanks to @Arnauld (although 7 of those bytes should have been obvious, sigh...). Saved a further 18 bytes directly and 7 bytes indirectly thanks to @JohanduToit. [Answer] # LaTeX+Tikz, 770 bytes This solution uses tikz's `scope` to implement the rotating and scaling. ``` \documentclass{standalone}\usepackage{xcolor,tikz}\usetikzlibrary{math}\begin{document}\def\h#1{\definecolor#1{HTML}}\h u{AAAAAA}\h r{FC666A}\h h{66A7FF}\h g{78FF65}\h p{DD66FF}\h y{FDF52A}\h c{87FFF5}\h w{FFFFFF}\def\R#1{\draw[fill=#1]rectangle(,);}\def\C#1{\draw[fill=#1](0,0)--(0,1)arc(90:0:1cm)--cycle;}\def\W#1{\draw[fill=#1](0,0)-|(,)--(0,0.639)--cycle;}\def\S#1{\draw[fill=#1](0,0)--(0,0.639)--(1,1)--(0.639,0)--cycle;}\expandafter\def\csname-\endcsname#1{\path(0,0)--(,);}\def\c#1#2{\csname#1\endcsname{#2}}\def~#1{\tikz[draw=black!66,line width=.11cm]{\def\a{#1}\foreach\l[count=\i from 0]in\a{\begin{scope}[scale=(37-9*\i+!\i)/36]\foreach\q[count=\j from 0]in\l\begin{scope}[rotate around={-90*\j:(0,0)}]{\expandafter\c\q}\end{scope};\end{scope}}}}\enddocument ``` ## Result This is the resulting pdf converted to svg with inkscape: ``` <!-- Created with Inkscape (http://www.inkscape.org/) --><svg version="1.1" id="svg2" xml:space="preserve" width="922.13867" height="83.568001" viewBox="0 0 922.13867 83.568001" sodipodi:docname="document.svg" inkscape:version="1.1 (c4e8f9ed74, 2021-05-24)" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"><defs id="defs6" /><sodipodi:namedview id="namedview4" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" showgrid="false" inkscape:zoom="5.5349593" inkscape:cx="702.53453" inkscape:cy="45.980465" inkscape:window-width="1920" inkscape:window-height="1042" inkscape:window-x="0" inkscape:window-y="18" inkscape:window-maximized="1" inkscape:current-layer="g8" /><g id="g8" inkscape:groupmode="layer" inkscape:label="document" transform="matrix(1.3333333,0,0,-1.3333333,0,83.568)"><g id="g10" transform="translate(83.002,29.921)"><g id="g12"><g id="g14"><g id="g16"><g id="g18"><g id="g20"><path d="M 0,0 V 29.92122 H 29.92122 V 0 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path22" /></g></g><g id="g24" /><g id="g26" /><g id="g28" /></g></g></g><g id="g30" transform="translate(71.212)"><g id="g32"><g id="g34"><g id="g36"><g id="g38"><g id="g40"><path d="M 0,0 V 29.92122 C 16.52524,29.92122 29.92122,16.52524 29.92122,0 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path42" /></g></g><g id="g44" /><g id="g46" /><g id="g48" /></g></g></g><g id="g50" transform="translate(71.211)"><g id="g52"><g id="g54"><g id="g56"><g id="g58"><g id="g60"><path d="M 0,0 H 29.92122 V 29.92122 L 0,19.11987 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path62" /></g></g><g id="g64" /><g id="g66" /><g id="g68" /></g></g></g><g id="g70" transform="translate(71.212)"><g id="g72"><g id="g74"><g id="g76"><g id="g78"><g id="g80"><path d="M 0,0 V 19.11987 L 29.92122,29.92122 19.11987,0 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path82" /></g></g><g id="g84" /><g id="g86" /><g id="g88" /></g></g></g><g id="g90" transform="translate(72.629,1.417)"><g id="g92"><g id="g94"><g id="g96"><g id="g98"><g id="g100"><path d="M 0,0 V 29.92122 C 16.52524,29.92122 29.92122,16.52524 29.92122,0 Z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path102" /></g></g><g id="g104"><g id="g106"><path d="M 0,0 H 29.92122 C 29.92122,-16.52524 16.52524,-29.92122 0,-29.92122 Z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path108" /></g></g><g id="g110"><g id="g112"><path d="m 0,0 v -29.92122 c -16.52524,0 -29.92122,13.39598 -29.92122,29.92122 z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path114" /></g></g><g id="g116"><g id="g118"><path d="m 0,0 h -29.92122 c 0,16.52524 13.39598,29.92122 29.92122,29.92122 z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path120" /></g></g></g><g id="g122"><g id="g124"><g id="g126"><path d="M 0,0 V 14.08838 L 22.04732,22.04732 14.08838,0 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path128" /></g></g><g id="g130"><g id="g132"><path d="M 0,0 H 14.08838 L 22.04732,-22.04732 0,-14.08838 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path134" /></g></g><g id="g136"><g id="g138"><path d="M 0,0 V -14.08838 L -22.04732,-22.04732 -14.08838,0 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path140" /></g></g><g id="g142"><g id="g144"><path d="M 0,0 H -14.08838 L -22.04732,22.04732 0,14.08838 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path146" /></g></g></g></g></g><g id="g148" transform="translate(72.629)"><g id="g150"><g id="g152"><g id="g154"><g id="g156"><g id="g158"><path d="M 0,0 V 29.92122 C 16.52524,29.92122 29.92122,16.52524 29.92122,0 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path160" /></g></g><g id="g162"><g id="g164"><path d="M 0,0 H 29.92122 C 29.92122,-16.52524 16.52524,-29.92122 0,-29.92122 Z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path166" /></g></g><g id="g168"><g id="g170"><path d="m 0,0 v -29.92122 c -16.52524,0 -29.92122,13.39598 -29.92122,29.92122 z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path172" /></g></g><g id="g174"><g id="g176"><path d="m 0,0 h -29.92122 c 0,16.52524 13.39598,29.92122 29.92122,29.92122 z" style="fill:#a8a8a8;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path178" /></g></g></g><g id="g180"><g id="g182" /><g id="g184" /><g id="g186" /><g id="g188"><g id="g190"><path d="m 0,0 h -22.04732 c 0,12.17654 9.87078,22.04732 22.04732,22.04732 z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path192" /></g></g></g></g></g><g id="g194" transform="translate(72.63,-1.417)"><g id="g196"><g id="g198"><g id="g200"><g id="g202" /><g id="g204" /><g id="g206" /><g id="g208"><g id="g210"><path d="m 0,0 h -29.92122 c 0,16.52524 13.39598,29.92122 29.92122,29.92122 z" style="fill:#78ff65;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path212" /></g></g></g><g id="g214"><g id="g216" /><g id="g218" /><g id="g220" /><g id="g222"><g id="g224"><path d="m 0,0 h -22.04732 c 0,12.17654 9.87078,22.04732 22.04732,22.04732 z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path226" /></g></g></g></g></g><g id="g228" transform="translate(71.211,1.417)"><g id="g230"><g id="g232"><g id="g234"><g id="g236"><g id="g238"><path d="M 0,0 V 29.92122 C 16.52524,29.92122 29.92122,16.52524 29.92122,0 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path240" /></g></g><g id="g242"><g id="g244"><path d="M 0,0 H 19.11987 L 29.92122,-29.92122 0,-19.11987 Z" style="fill:#fdf52a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path246" /></g></g><g id="g248"><g id="g250"><path d="M 0,0 H -29.92122 V -29.92122 L 0,-19.11987 Z" style="fill:#78ff65;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path252" /></g></g><g id="g254"><g id="g256"><path d="M 0,0 H -29.92122 V 29.92122 H 0 Z" style="fill:#66a7ff;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path258" /></g></g></g></g></g><g id="g260" transform="translate(71.212,-1.417)"><g id="g262"><g id="g264"><g id="g266"><g id="g268"><g id="g270"><path d="M 0,0 V 29.92122 C 16.52524,29.92122 29.92122,16.52524 29.92122,0 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path272" /></g></g><g id="g274" /><g id="g276" /><g id="g278" /></g><g id="g280"><g id="g282" /><g id="g284" /><g id="g286" /><g id="g288"><g id="g290"><path d="m 0,0 h -22.04732 c 0,12.17654 9.87078,22.04732 22.04732,22.04732 z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path292" /></g></g></g><g id="g294"><g id="g296"><g id="g298"><path d="M 0,0 V 14.9606 C 8.26262,14.9606 14.9606,8.26262 14.9606,0 Z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path300" /></g></g><g id="g302" /><g id="g304" /><g id="g306" /></g><g id="g308"><g id="g310" /><g id="g312" /><g id="g314" /><g id="g316"><g id="g318"><path d="m 0,0 h -7.8739 c 0,4.34868 3.52522,7.8739 7.8739,7.8739 z" style="fill:#fc666a;fill-opacity:1;fill-rule:nonzero;stroke:#575757;stroke-width:2.83484;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" id="path320" /></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></svg> ``` ## Formatted Code and Usage ``` \documentclass{standalone} \usepackage{xcolor,tikz} \usetikzlibrary{math} \begin{document} % define the color shorthands \def\h#1{\definecolor#1{HTML}} \h u{AAAAAA} \h r{FC666A} \h b{66A7FF} \h g{78FF65} \h p{DD66FF} \h y{FDF52A} \h c{87FFF5} \h w{FFFFFF} % define commands that draw a shape \def\R#1{\draw[fill=#1]rectangle(,);} \def\C#1{\draw[fill=#1](0,0)--(0,1)arc(90:0:1cm)--cycle;} \def\W#1{\draw[fill=#1](0,0)-|(,)--(0,0.639)--cycle;} \def\S#1{\draw[fill=#1](0,0)--(0,0.639)--(1,1)--(0.639,0)--cycle;} \expandafter\def\csname-\endcsname#1{\path(0,0)--(,);} % define the command that parses the shape and the colour and calls the shape command \def\c#1#2{\csname#1\endcsname{#2}} \def~#1{ \tikz[draw=black!66,line width=.11cm]{ \def\a{#1} \foreach \l [count=\i from 0] in \a{ \begin{scope}[scale=(37-9*\i+!\i)/36] \foreach \q [count=\j from 0] in \l \begin{scope}[rotate around={-90*\j:(0,0)}]{ \expandafter\c\q } \end{scope} ; \end{scope} } } } ~{{Ru,--,--,--}} ~{{Cu,--,--,--}} ~{{Wu,--,--,--}} ~{{Su,--,--,--}} ~{{Cy,Cy,Cy,Cy},{Sr,Sr,Sr,Sr}} ~{{Cu,Cu,Cu,Cu},{--,--,--,Cy}} ~{{--,--,--,Cg},{--,--,--,Cr}} ~{{Cr,Sy,Wg,Rb}} ~{{Cr,--,--,--},{--,--,--,Cr},{Cr,--,--,--},{--,--,--,Cr}} \enddocument ``` ``` ]
[Question] [ [![A sample Facebook Meme](https://i.stack.imgur.com/FP8eh.jpg)](https://i.stack.imgur.com/FP8eh.jpg) ## Executive summary: Print NxN matrices \$A\$ and \$B\$ where \$ AB = 10A + B \$. Largest N wins! ## Details: Entrants in this challenge should choose an N. Submit a program that takes an input integer 'seed', and produces two full rank NxN matrices \$A\$ and \$B\$, where each element of \$A\$ and \$B\$ is an integer from 0 to 9, and \$AB = 10A + B\$. In addition, matrices A and B must have at least half of their elements nonzero. The output should always be the same for a given seed. Runtime of your program is not limited, however as evidence that it does finish you must post a sample seed, the output of your program given that seed, and the time taken to compute. Input and output format is not restricted. ## Scoring: First, largest N wins. Second, ties are broken by earliest submission. ## No hard coding: In order to prevent hard coding, there must be at least 10 seeds that produce distinct outputs, where outputs are not distinct if they are equal after exchanging rows, exchanging columns, and or transposing the matrix. You don't need to worry about proving this for good faith solutions. ## Math Background / No Rules Below This Line First of all, for a given candidate A, B is fixed: $$AB = 10A + B\\ A = 10AB^{-1} + I\\ I = 10B^{-1} + A^{-1}\\ B = 10(I - A^{-1})^{-1}\\ B = 10(I + (A - I)^{-1})$$ One approach is to take the eigendecomposition of A. From before, $$ A = Q \Lambda\_A Q^{-1}\\ B = 10(I - A^{-1})^{-1}\\ B = 10(Q I Q^{-1} - Q \Lambda\_A^{-1} Q^{-1})^{-1}\\ B = Q(\frac{10}{(I - \Lambda\_A^{-1})})Q^{-1}\\$$ This shows that A, B share eigenvectors Q, and their eigenvalues are assosciated by $$ \Lambda\_A \Lambda\_B = 10 \Lambda\_A + \Lambda\_B\\ $$ Interestingly, this proves that AB = BA, ie our matrices commute! We can calculate the determinant of B as \$10^N \frac{1}{\Pi\_i (1 - \frac{1}{\lambda\_{A,i}})}\$ This is very suggestive, but doesn't immediately yield a way to pick a matrix A such that B is small positive integers. Because A and B share eigenvectors, B can be written as a linear combination of \$(I, A, A^2 ... ~ A^{N-1})\$. For example, $$A = \left(\begin{array}{rrr}1 & 2 & 4 \\1 & 1 & 3 \\1 & 1 & 1\end{array}\right), B = \left(\begin{array}{rrr}7 & 4 & 6 \\3 & 6 & 4 \\1 & 2 & 8\end{array}\right)$$ $$\Lambda\_A = \left(\begin{array}{rrr}-\sqrt{6} + 2 & 0 & 0 \\0 & \sqrt{6} + 2 & 0 \\0 & 0 & -1\end{array}\right), \Lambda\_B = \left(\begin{array}{rrr}-\sqrt{6} + 2 & 0 & 0 \\0 & \sqrt{6} + 2 & 0 \\0 & 0 & -1\end{array}\right)$$ We observe that \$\Lambda\_B = \Lambda\_A^2 - 2 \Lambda\_A + 2I\$, so \$B = A^2 - 2A + 2\$. In this case B is forced to be an integer matrix because it is possible to write B as an integer polynomial of A. If we can find large matrices where \$10(I + (\Lambda\_A - I)^{-1})\$ is an integer polynomial of \$\Lambda\_A\$, then that might provide an efficient solution. Finally, if we write \$A\$ as \$E + I\$, then we can see some simplifications. \$B = 10 \* (E^{-1} + I)\$, so B is an integer matrix as long as the determinant of E divides 10. With this E representation, our problem can become to find an integer matrix E such that $$ E + I \geq 0\\ E^{-1} + I \geq 0\\ |E| = \pm 10\\$$ (Occasionally this will fail if an entry of \$ E^{-1} + I > 9\$ ) This represents an improvement, because once we find a [0-9] matrix E with determinant \$\pm 10 \$ (such as by random search), then if there are only a small number of negative entries in \$E^{-1}\$ we can run determinant-preserving transformations on E such as permuting rows to move those negative entries onto the diagonal, where they are made positive by the \$+I\$ In addition, there is a name and wikipedia page for matrices like \$E^{-1}\$ where the off diagonal entries are all positive: A [Metzler Matrix.](https://en.wikipedia.org/wiki/Metzler_matrix) Further literature search in that direction might bring up an efficient way to generate positive integer matrices with a determinant \$\pm 10\$ whose inverses are Metzler Matrices. [Answer] # Python, N = 7 Using variable neighborhood search over elementary row and column operations. Not every seed works quickly (or at all?), but seed 9 finds a solution for N = 7 in a few seconds. ``` $ time python3 search.py 7 9 [[0 3 6 6 1 6 6] [0 1 5 5 0 5 5] [1 3 1 2 1 8 1] [0 0 1 0 0 1 0] [1 7 9 9 0 9 9] [1 3 1 1 1 0 1] [0 0 1 1 0 1 1]] [[5 5 1 1 0 4 0] [1 7 0 0 1 0 0] [0 0 9 4 0 1 5] [0 0 0 5 0 0 5] [2 2 1 1 7 4 0] [0 0 1 1 0 9 0] [0 2 0 0 0 0 0]] real 0m4.909s user 0m4.883s sys 0m0.026s ``` ### Code ``` import itertools import sys import numpy as np def search(depth, C, D, best): A = C + I B = D + 10 * I x = np.r_[A, B].flatten() score = ( np.maximum(0, np.maximum(x - 9, 1 - x)).sum() - min((A == 0).sum(), -(-n * n // 2)) - min((B == 0).sum(), -(-n * n // 2)) + 2 * n - np.linalg.matrix_rank(A) - np.linalg.matrix_rank(B) ) if best is None or score < best: return C, D, score if depth == 0: return None tried = {} for i in reversed(range(n * (n - 1) * 5)): j = rng.integers(i + 1) mutation, tried[j] = tried.get(j, j), tried.get(i, i) p, mutation = divmod(mutation, (n - 1) * 5) q, mutation = divmod(mutation, 5) q = (p + q + 1) % n C1 = C.copy() D1 = D.copy() if mutation == 0: C1[p, :] += C1[q, :] D1[:, q] -= D1[:, p] elif mutation == 1: C1[p, :] -= C1[q, :] D1[:, q] += D1[:, p] elif mutation == 2: C1[:, p] += C1[:, q] D1[q, :] -= D1[p, :] elif mutation == 3: C1[:, p] -= C1[:, q] D1[q, :] += D1[p, :] elif p < q: C1[[p, q], :] = C1[[q, p], :] D1[:, [p, q]] = D1[:, [q, p]] else: C1[:, [p, q]] = C1[:, [q, p]] D1[[p, q], :] = D1[[q, p], :] ret = search(depth - 1, C1, D1, best) if ret is not None: return ret return None n, seed = map(int, sys.argv[1:]) rng = np.random.default_rng(seed) I = np.eye(n, dtype=int) score = None k = rng.integers(0, 8, n) C = np.diag(np.array([-10, -5, -2, -1, 1, 2, 5, 10])[k]) D = np.diag(np.array([-1, -2, -5, -10, 10, 5, 2, 1])[k]) depth = 1 while score != 0: ret = search(depth, C, D, score) if ret is not None: C, D, score = ret depth = 0 depth += 1 A = C + I B = D + 10 * I assert (A @ B == 10 * A + B).all() print(A) print(B) ``` [Answer] **N = 2** This is a naive brute force approach in R: ``` randomvalid <- function(N) { while (T) { X <- matrix(sample(10,N*N,T)-1,N) if (sum(X==0) < N*N/2 && qr(X)$rank == N) return(X) } } tryforever <- function(N) { i <- 1 while (T) { i <- i + 1 if (i %% 100000 == 0) print(sprintf("after %d tries...", i)) A <- randomvalid(N) B <- randomvalid(N) if(all(A %*% B == 10*A + B)) { print(A) print(B) print(A %*% B) } } } # run tryforever(2) to find some solutions for N=2 ``` Some solutions for N=2 are: ``` A = [[ 3, 2],[ 6, 2]] B = [[ 9, 2],[ 6, 8]] AB = [[39,22],[66,28]] A = [[ 6, 5],[ 3, 2]] B = [[ 9, 5],[ 3, 5]] AB = [[69,55],[33,25]] A = [[ 6, 5],[ 9, 8]] B = [[ 3, 5],[ 9, 5]] AB = [[63,55],[99,85]] A = [[ 3, 4],[ 8, 7]] B = [[ 7, 2],[ 4, 9]] AB = [[37,42],[84,79]] ``` Valid solutions seem to be very rare, even for N=2 they pop up only once every few minutes. For N=3 I was not able to find any solution within hours by this approach. So, let's see whether a mathematical or heuristical approach is able to beat my N=2 solution :) [Answer] # N = 4, Swi-Prolog After all the math, my best result so far is a relatively naive solution in prolog. ``` :- use_module(library(clpfd)). % N is the dot product of lists V1 and V2. dot(V1, V2, N) :- maplist(product,V1,V2,P), my_sumlist(P,N). product(N1,N2,N3) :- N3 #= N1*N2. my_sumlist([], 0). my_sumlist([H|T], N) :- my_sumlist(T, X), N #= X + H. my_scamul(_, [], []). my_scamul(K, [R|T], [R2|T2]):- my_rowmul(K, R, R2), my_scamul(K, T, T2). my_rowmul(_, [], []). my_rowmul(K, [V|T], [V2|T2]):- K * V #= V2, my_rowmul(K, T, T2). addmat([], [], []). addmat([HA|TA], [HB|TB], [HC|TC]):- addrow(HA, HB, HC), addmat(TA, TB, TC). addrow([], [], []). addrow([HA|TA], [HB|TB], [HC|TC]):- HA + HB #= HC, addrow(TA, TB, TC). nn(NN) :- NN #= 4. isMat([], 0). isMat([H|T], N):- nn(NN), isRow(H, NN), isMat(T, Ns), Ns #= N - 1. isRow([], 0). isRow([H|T], N):- H in 1..9, isRow(T, Ns), Ns #= N - 1. det([[E_0, E_1, E_2, E_3], [E_4, E_5, E_6, E_7], [E_8, E_9, E_10, E_11], [E_12, E_13, E_14, E_15]], 4, D):- D #= E_1*E_11*E_14*E_4 - E_1*E_10*E_15*E_4 - E_11*E_13*E_2*E_4 + E_10*E_13*E_3*E_4 - E_0*E_11*E_14*E_5 + E_0*E_10*E_15*E_5 + E_11*E_12*E_2*E_5 - E_10*E_12*E_3*E_5 - E_1*E_11*E_12*E_6 + E_0*E_11*E_13*E_6 + E_1*E_10*E_12*E_7 - E_0*E_10*E_13*E_7 - E_15*E_2*E_5*E_8 + E_14*E_3*E_5*E_8 + E_1*E_15*E_6*E_8 - E_13*E_3*E_6*E_8 - E_1*E_14*E_7*E_8 + E_13*E_2*E_7*E_8 + E_15*E_2*E_4*E_9 - E_14*E_3*E_4*E_9 - E_0*E_15*E_6*E_9 + E_12*E_3*E_6*E_9 + E_0*E_14*E_7*E_9 - E_12*E_2*E_7*E_9. % Matrix multiplication with matrices represented % as lists of lists. M3 is the product of M1 and M2 mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3). mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3). problem(A, B, C, ABf):- nn(NN), isMat(A, NN), isMat(B, NN), my_scamul(10, A, AX), addmat(AX, B, C), mmult(A, B, C), append(A, B, AB), flatten(AB, ABf). main(Seed):- problem(A, B, C, ABf), labeling([ff, random_value(Seed)], ABf), det(A, 4, Determinant), write_ln(A), write_ln(B), write_ln(C), write_ln(Determinant), Determinant #\= 0. ``` Sample Output with seed 20: ``` ?- time(main(20)) | . [[8,8,3,6],[4,2,1,2],[5,3,1,2],[4,2,1,2]] [[9,1,1,2],[1,5,1,2],[1,1,3,6],[1,5,1,2]] [[89,81,31,62],[41,25,11,22],[51,31,13,26],[41,25,11,22]] 0 [[8,8,3,6],[4,2,1,2],[5,3,1,2],[4,3,1,1]] [[9,2,1,1],[1,6,1,1],[1,4,3,3],[1,1,1,6]] [[89,82,31,61],[41,26,11,21],[51,34,13,23],[41,31,11,16]] -6 % 582,520,793 inferences, 33.623 CPU in 33.623 seconds (100% CPU, 17324911 Lips) true ``` ``` [Answer] # Julia, 9 I identify a class of full rank matrices for which the criterion `A*B = 10A + B` can be checked in constant time, `nxn`-matrices of the form ``` a b b b . . . b b a b b . b b a b . b b b a . . . . . . . . a b b . . . . . b a ``` Then I do a random search for those matrices in this class fulfilling the criteria. As these are full, I can make block-matrices out of two random elements of the class get a half-filled larger solution. ``` using Random, LinearAlgebra check(a1, a2, b1, b2, n, base) = a2 != 0 && a1*b1*n + a2*b1 + b2*a1 == base*a1 + b1 && a1*b1*n + a2*b1 + b2*a1 + a2*b2 == base*(a1 +a2) + b1 + b2 function generate(base=10) while true a1 = rand(1:base-1) b1 = rand(1:base-1) a2 = rand(-a1+1:base-1-a1) b2 = rand(-b1+1:base-1-b1) n = rand(1:10) if check(a1, a2, b1, b2, n, base) return a1*ones(Int, n, n) + a2*I, b1*ones(Int, n, n) + b2*I end end end nosp(A) = sum(A .== 0) <= size(A,1)*size(A,2)/2 fake(A, B) = rank(A) > 0 && rank(B) > 0 && nosp(A) && nosp(B) && A*B == 10*A + B ``` ``` Random.seed!(333333333333); A1, B1 = generate() A2, B2 = generate() A = [A1 0I; 0I A2] B =[B1 0I; 0I B2] fake(A2, B2) ``` ``` 1 2 2 2 2 2 0 0 0 0 0 0 2 1 2 2 2 2 0 0 0 0 0 0 2 2 1 2 2 2 0 0 0 0 0 0 2 2 2 1 2 2 0 0 0 0 0 0 2 2 2 2 1 2 0 0 0 0 0 0 2 2 2 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 2 2 2 0 0 0 0 0 0 2 1 2 2 2 2 0 0 0 0 0 0 2 2 1 2 2 2 0 0 0 0 0 0 2 2 2 1 2 2 0 0 0 0 0 0 2 2 2 2 1 2 0 0 0 0 0 0 2 2 2 2 2 1 6 1 1 1 1 1 0 0 0 0 0 0 1 6 1 1 1 1 0 0 0 0 0 0 1 1 6 1 1 1 0 0 0 0 0 0 1 1 1 6 1 1 0 0 0 0 0 0 1 1 1 1 6 1 0 0 0 0 0 0 1 1 1 1 1 6 0 0 0 0 0 0 0 0 0 0 0 0 6 1 1 1 1 1 0 0 0 0 0 0 1 6 1 1 1 1 0 0 0 0 0 0 1 1 6 1 1 1 0 0 0 0 0 0 1 1 1 6 1 1 0 0 0 0 0 0 1 1 1 1 6 1 0 0 0 0 0 0 1 1 1 1 1 6 ``` There are not too many valid pairs of them but there are ten distributed over the dimensions for base 10. It also produces only a single 12x12 solution therefore it was agreed to count the method at the level of the second largest solutions it produces, ie 9. ]
[Question] [ This challenge will have you count pseudo-[polyforms](https://en.wikipedia.org/wiki/Polyform) on the [snub square tiling](https://en.wikipedia.org/wiki/Snub_square_tiling). I think that this sequence does not yet exist on the [OEIS](https://oeis.org/), so this challenge exists to compute as many terms as possible for this sequence. *Update: this is now on the OEIS as [A309159](https://oeis.org/A309159): Number of generalized polyforms on the snub square tiling with n cells.* # Definitions The snub square tiling is a semiregular tiling of the plane that consists of equilateral triangles and squares. [![snub square tiling](https://i.stack.imgur.com/RXSwgm.png)](https://i.stack.imgur.com/RXSwgm.png) A pseudo-polyform on the snub square tiling is a plane figure constructed by joining together these triangles and squares along their shared sides, analogous to a polyomino. Here is an example of a six-cell and an eight-cell pseudo-polyform: [![enter image description here](https://i.stack.imgur.com/Ecn14m.png)](https://i.stack.imgur.com/Ecn14m.png) # Examples For `n = 1` there are two 1-cell pseudo-polyforms, namely the square and the triangle: ![](https://i.stack.imgur.com/f5bsp.png) For `n = 2` there are two 2-cell pseudo-polyforms, namely a square with a triangle and two triangles. ![](https://i.stack.imgur.com/b5TaU.png) For `n = 3` there are four 3-cell pseudo-polyforms. ![](https://i.stack.imgur.com/kE8vd.png) # Challenge The goal of this challenge is to compute as many terms as possible in this sequence, which begins `2, 2, 4, ...` and where the n-th term is the number of n-cell pseudo-polyforms up to rotation and reflection. Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code. If two users post the same number of terms, then whoever posts their last term earliest wins. (Once there are enough known terms to prove that this sequence does not already exist in the OEIS, I'll create an entry in the OEIS and list the contributor as a co-author if he or she desires.) [Answer] # [Haskell](https://www.haskell.org/) Now that not only the comments document that Peter Taylor was the first one to give enough terms to search on OEIS, I can give my results. ``` ( 1 - 10) 2, 2, 4, 10, 28, 79, 235, 720, 2254, 7146, (11 - 15) 22927, 74137, 241461, 790838, 2603210, (16 - 18) 8604861, 28549166, 95027832, (19 - 22) 317229779, 1061764660, 3562113987, 11976146355 ``` Earlier, I counted [hexagonal polyominoes](https://codegolf.stackexchange.com/a/139582). Except for some optimizations, what I'm doing here is very similar. The elements of the tiling are represented like this: You can go in an almost straight line from left to right (in the first picture), alternating between squares and rectangles. There are almost parallel further lines, wiggling in opposite directions. Together, they miss some triangles. There are similar almost straight parallel lines from bottom to top, containing the missing triangles. Now ignore the wiggling and use a Cartesian coordinate system, but only use odd numbers for the coordinates of the squares. Then the triangles naturally get coordinate pairs with one even and one odd coordinate. Pairs with both coordinates even don't represent elements of the tiling. (You could as well use even numbers for the coordinates of the squares. I guess I decided this way because I thought about reflection before rotation.) Save the program in a file with a name like `cgp.hs` and compile with `ghc -O2 -o cgp cgp.hs`. It takes either one numeric command line argument and computes the number of polyominoes of that size, or none, in which case it computes values until stopped. ``` {-# LANGUAGE BangPatterns #-} import Data.List(sort) import qualified Data.Set as S import System.Environment(getArgs) data Point = P !Int !Int deriving (Eq,Ord) start :: Point start = P 1 1 redsq :: Point -> Bool redsq (P x y) = (x+y) `mod` 4 == 2 neighs :: Point -> [Point] neighs (P x y) = case (even x, even y) of (False,False) -> [P x (y+1), P (x+1) y, P x (y-1), P (x-1) y] (True, False) -> (P x (c y (x+y+1))) : opt [P (x-1) y, P (x+1) y] (False,True ) -> (P (c x (x+y-1)) y) : opt [P x (y-1), P x (y+1)] where opt = filter ok ok p = p>start || not (redsq p) c z m = if m `mod` 4 == 0 then z+2 else z-2 count :: S.Set Point -> S.Set Point -> [Point] -> Int -> Int -> Int -> Int -> Int count use _ _ 0 c r y = if check (S.toAscList use) (y==r) then c+1 else c count _ _ [] _ c _ _ = c count use seen (p:possible) n c r y = let !c' = count use seen possible n c r y new = filter (`S.notMember` seen) $ neighs p !r' = if redsq p then r+1 else r !y' = if redsq (mirror p) then y+1 else y !n' = n-1 in if r'+n' < y' then c' else count (S.insert p use) (foldr S.insert seen new) (new++possible) n' c' r' y' class Geom g where translate :: Int -> Int -> g -> g rot :: g -> g mirror :: g -> g instance Geom Point where translate dx dy (P x y) = P (dx+x) (dy+y) rot (P x y) = P (2-y) x -- rotate around (1,1) mirror (P x y) = P x (-y) instance (Geom g, Ord g) => Geom [g] where translate x y = map $ translate x y rot = sort . map rot mirror = sort . map mirror normalize :: [Point] -> [Point] normalize pol = let (P x y) = head (filter redsq pol) in translate (1-x) (1-y) pol check :: [Point] -> Bool -> Bool check pol !cm = let rotated = take 4 $ iterate rot pol mirrored = if cm then map mirror rotated else [] alts = map normalize (tail rotated ++ mirrored) in all (pol<=) alts f :: Int -> Int f 0 = 1; f 1 = 2; f 2 = 2 f n = count S.empty S.empty [start] n 0 0 0 output :: Int -> IO () output n = putStrLn $ show n ++ ": " ++ show (f n) main = do args <- getArgs case args of [] -> mapM_ output [1..] [n] -> output (read n) ``` [Try it online!](https://tio.run/##dVZdT@M4FH3Pr7jMjESiNBVB88RSJEbLopGYHaTOPlUVeBK3jUjsYLvQsLO/nT3@SJoubCrF9vX9OPfcG7sbph94Xb@@/p19pJvLP6//ury@oi9MrG@ZMVwJTR@zf6KoalqpDP3ODJveVNrEGsukFz9uWV2tKl56hTk3xDTN@@15pw1vplfiqVJSNFyYeM3NpVrrJIpKWNCtrIShGd3S0VdM3KvkqnqqxJriq8fJd1VCVxsGd2dnXj8srVVOeRQpXurHYZeyC/oiZR3E8S3tqEugHe9SjPeNLO/pM81mdBpFglfrjT6wXbjZst8a7COigmlOMX/ignYTciN25ApbRPEfrNZ84t6JdwTLuEvzZAKkiJ4n1NmplWa9NLPSpffwQ235hPYeXOy4oM5hh32S0BnJ1ljfwXTkeznGYX1R7wU@ds4HTBKLefAywhLAWi/PG66482bVZrSqavQEyQcve6AWwvbC1@HXLxLSUOz5bhOnU9ALNVCqVhhGnJ@Q2YC2l/SUOGDSS4YqFHIrXHnnroWGUvxnGSpjp1@95P@G4HGLAHcWjXv1zwnAKXBqKwp4xYYXDxTPp0Ze6sL2uLVLQMZspnwyDnKR5m7hYBchwl3vfLEcRbhDhDv8ZoOeRaI5vMTtWSu1rn7WCCFGSGpkelQcW5tDi1691458DMGf94WJ7@dT1OAbb35yde/sEvpEoYXbYHKkjn1FQqV8XirNfU6qV@sO1OKmUkoqFNbrd71@j@RIWH2RWXoq4QyPU8jOCY6CTqDwuF96El2iYL4SmqOR2kD8StalokHsWEC62ME7TQf@InrzICw4RJ7dMdqqZlrTNZcNrYeWNooJXTPDbb8dNs7avaCjpOvGYR0Y2IsiQDNMFNx79x36NkK5o7IbnUD4EMtdukMiZYezKEQ62D/NMNvZVLLM7lo3TIGokuJ8kid7NGMzfLqwG8GKfdYTwvlJayhdeKSL9fIdnDvbg9SwFj1zIA0IZ2RPfZo6FQj2IA52vAyHqlQN7oUXR/Hoox1O1mG/lTVc2NbfZ7PhDLmGxg6dKuu3xUar7bHGeWZpzS170Ebt3Vd9GN/eCsPt4BUsgKOiCSA83yVWhj1wHFifqAIKG8DSYB3TO4/P29nZ86Txzb5nZPDrun6xfNcJq40ORdjzExtW1YN5mg6h3qWD1TXOF1mfzxLnLopWh02O9Qli5L/RCjcnLkA7ObUT7Ijh6JlPedOabhgX7pxfQuPE/qJIbk27NWPf3ylOerF1hHFu1I0Ag3ojnyED@A9n9MGOThIjIjq2YZXVLyW6fK3pPKPwD2GUoLt23Xa4avvHHrqIDs6@3VGIvsin00OGF8JVP@zjmkJ/IfTr62t@@i8 "Haskell – Try It Online") [Answer] ## 2, 2, 4, 10, 28, 79, 235, 720, 2254, 7146, 22927, 74137, 241461, 790838, 2603210, 8604861, 28549166, 95027832 I'm going to put a stake in the ground before Christian Sievers posts an answer for n=18. This is as far as I can go with the current code and 16GB of RAM. I've already had to sacrifice some speed to reduce the memory usage, and I'm going to have to do so even more. I have some ideas... This snippet is the SVG from the first comment. ``` <svg xmlns="http://www.w3.org/2000/svg" width="130" height="130"> <path style="stroke:none; fill:#f22" d="M 72,72 l -14.235,53.1259 -53.1259,-14.235 14.235,-53.1259 z" /> <!-- "Anticlockwise" square --> <path style="stroke:none; fill:#44f" d="M 72,72 l 53.1259,-14.235 -14.235,-53.1259 -53.1259,14.235 z" /> <!-- "Clockwise" square --> <path style="stroke:none; fill:#4f4" d="M 72,72 l 38.89,38.89 14.235,-53.1259 z" /> <!-- "NE" triangle --> <path style="stroke:none; fill:#ff4" d="M 72,72 l 38.89,38.89 -53.1259,14.235 z" /> <!-- "SW" triangle --> <path style="stroke:none; fill:#4ff" d="M 72,72 m -53.1259,-14.235 l 38.89,-38.89 -53.1259,-14.235 z" /> <!-- "NW" triangle --> <path style="stroke:#000; fill:none" d="M 72,72 m 38.89,38.89 l 14.235,-53.1259 -14.235,-53.1259 -53.1259,14.235 -53.1259,-14.235 14.235,53.1259 -14.235,53.1259 53.1259,14.235 53.1259,-14.235" /> </svg> ``` Code is C#. I ran it with .Net Core 2.2.6 under Linux. ``` #define SUPERLIGHT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Sandbox { // https://codegolf.stackexchange.com/questions/187763/counting-generalized-polyominoes // Count polyominos on the snub square tiling. // We index the tiles using the following basic element, which tiles like a square: /* <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" width="130" height="130"> <path style="stroke:none; fill:#f22" d="M 72,72 l -14.235,53.1259 -53.1259,-14.235 14.235,-53.1259 z" /> <!-- "Anticlockwise" square --> <path style="stroke:none; fill:#44f" d="M 72,72 l 53.1259,-14.235 -14.235,-53.1259 -53.1259,14.235 z" /> <!-- "Clockwise" square --> <path style="stroke:none; fill:#4f4" d="M 72,72 l 38.89,38.89 14.235,-53.1259 z" /> <!-- "NE" triangle --> <path style="stroke:none; fill:#ff4" d="M 72,72 l 38.89,38.89 -53.1259,14.235 z" /> <!-- "SW" triangle --> <path style="stroke:none; fill:#4ff" d="M 72,72 m -53.1259,-14.235 l 38.89,-38.89 -53.1259,-14.235 z" /> <!-- "NW" triangle --> <!-- There's a "SE" triangle, but it's unfilled --> <path style="stroke:#000; fill:none" d="M 72,72 m 38.89,38.89 l 14.235,-53.1259 -14.235,-53.1259 -53.1259,14.235 -53.1259,-14.235 14.235,53.1259 -14.235,53.1259 53.1259,14.235 53.1259,-14.235" /> </svg> */ // In terms of symmetries, we have rotation by 90 degrees and reflection, possibly with glide. // We obviously want a canonical representation. // Reflection interchanges "anticlockwise" and "clockwise" squares, so we shall require at least as many anticlockwise as clockwise. // Rotation anticlockwise by 90 maps NE -> NW -> SW -> SE -> NE. We rotate to get a standard necklace. // Further ties must be broken lexicographically, after translating to give minimum X and Y of 0. class PPCG187763 { internal static void Main() { SanityChecks(); var polyominos = new HashSet<TileSet>(); polyominos.Add(new TileSet(Enumerable.Repeat(new Tile { X = 0, Y = 0, Shape = TileShape.SE }, 1))); polyominos.Add(new TileSet(Enumerable.Repeat(new Tile { X = 0, Y = 0, Shape = TileShape.Anticlockwise }, 1))); Console.WriteLine($"1\t{polyominos.Count}"); for (int tileCount = 2; tileCount < 60; tileCount++) { var sw = new Stopwatch(); sw.Start(); var nextPolyominos = new HashSet<TileSet>(); // TODO This can be greatly optimised by tracking discarded insertion points foreach (var polyomino in polyominos) { foreach (var neighbour in polyomino.SelectMany(tile => tile.Neighbours).Distinct()) { if (!polyomino.Contains(neighbour)) nextPolyominos.Add(new TileSet(polyomino.Concat(Enumerable.Repeat(neighbour, 1)))); } } polyominos = nextPolyominos; Console.WriteLine($"{tileCount}\t{polyominos.Count}\t{sw.ElapsedMilliseconds}ms"); } } private static void SanityChecks() { var cluster = new HashSet<Tile>(); cluster.Add(new Tile { Shape = TileShape.Anticlockwise }); for (int i = 0; i < 3; i++) { foreach (var tile in cluster.SelectMany(tile => tile.Neighbours).ToList()) cluster.Add(tile); } foreach (var tile in cluster) { foreach (var neighbour in tile.Neighbours) { if (!neighbour.Neighbours.Contains(tile)) { throw new Exception("Assertion failed: adjacency isn't symmetric"); } if (!tile.Flip().Neighbours.Contains(neighbour.Flip())) { throw new Exception("Assertion failed: flip doesn't preserve adjacency"); } if (!tile.Rot().Neighbours.Contains(neighbour.Rot())) { throw new Exception("Assertion failed: rot doesn't preserve adjacency"); } if (!tile.Equals(tile.Rot().Rot().Rot().Rot())) { throw new Exception("Assertion failed: rot^4 should be identity"); } } } } struct Tile : IComparable<Tile> { public TileShape Shape { get; set; } public sbyte X { get; set; } public sbyte Y { get; set; } public IEnumerable<Tile> Neighbours { get { switch (Shape) { case TileShape.Anticlockwise: yield return new Tile { X = X, Y = Y, Shape = TileShape.SE }; yield return new Tile { X = X, Y = Y, Shape = TileShape.SW }; yield return new Tile { X = X, Y = (sbyte)(Y - 1), Shape = TileShape.NW }; yield return new Tile { X = (sbyte)(X - 1), Y = Y, Shape = TileShape.NE }; break; case TileShape.Clockwise: yield return new Tile { X = X, Y = Y, Shape = TileShape.SE }; yield return new Tile { X = X, Y = Y, Shape = TileShape.NE }; yield return new Tile { X = X, Y = (sbyte)(Y + 1), Shape = TileShape.SW }; yield return new Tile { X = (sbyte)(X + 1), Y = Y, Shape = TileShape.NW }; break; case TileShape.NE: yield return new Tile { X = X, Y = Y, Shape = TileShape.SW }; yield return new Tile { X = X, Y = Y, Shape = TileShape.Clockwise }; yield return new Tile { X = (sbyte)(X + 1), Y = Y, Shape = TileShape.Anticlockwise }; break; case TileShape.NW: yield return new Tile { X = X, Y = Y, Shape = TileShape.SE }; yield return new Tile { X = (sbyte)(X - 1), Y = Y, Shape = TileShape.Clockwise }; yield return new Tile { X = X, Y = (sbyte)(Y + 1), Shape = TileShape.Anticlockwise }; break; case TileShape.SE: yield return new Tile { X = X, Y = Y, Shape = TileShape.NW }; yield return new Tile { X = X, Y = Y, Shape = TileShape.Clockwise }; yield return new Tile { X = X, Y = Y, Shape = TileShape.Anticlockwise }; break; case TileShape.SW: yield return new Tile { X = X, Y = Y, Shape = TileShape.NE }; yield return new Tile { X = X, Y = (sbyte)(Y - 1), Shape = TileShape.Clockwise }; yield return new Tile { X = X, Y = Y, Shape = TileShape.Anticlockwise }; break; default: throw new NotSupportedException(); } } } public Tile Flip() { // We'll flip vertically. switch (Shape) { case TileShape.Anticlockwise: return new Tile { Shape = TileShape.Clockwise, X = X, Y = (sbyte)-Y }; case TileShape.Clockwise: return new Tile { Shape = TileShape.Anticlockwise, X = (sbyte)(X + 1), Y = (sbyte)-Y }; case TileShape.NE: // G return new Tile { Shape = TileShape.SE, X = (sbyte)(X + 1), Y = (sbyte)-Y }; case TileShape.NW: // Cy return new Tile { Shape = TileShape.SW, X = X, Y = (sbyte)-Y }; case TileShape.SE: // W return new Tile { Shape = TileShape.NE, X = X, Y = (sbyte)-Y }; case TileShape.SW: // Y return new Tile { Shape = TileShape.NW, X = (sbyte)(X + 1), Y = (sbyte)-Y }; default: throw new NotSupportedException(); } } public Tile Rot() { // Anti-clockwise rotation: (x, y) = (-y, x) // But there will be offsets to account for the positions within the cell switch (Shape) { case TileShape.Anticlockwise: return new Tile { Shape = TileShape.Anticlockwise, X = (sbyte)-Y, Y = X }; case TileShape.Clockwise: return new Tile { Shape = TileShape.Clockwise, X = (sbyte)(-Y - 1), Y = X }; case TileShape.NE: return new Tile { Shape = TileShape.NW, X = (sbyte)-Y, Y = X }; case TileShape.NW: return new Tile { Shape = TileShape.SW, X = (sbyte)(-Y - 1), Y = X }; case TileShape.SE: return new Tile { Shape = TileShape.NE, X = (sbyte)(-Y - 1), Y = X }; case TileShape.SW: return new Tile { Shape = TileShape.SE, X = (sbyte)-Y, Y = X }; default: throw new NotSupportedException(); } } public override int GetHashCode() => (X << 17) + (Y << 3) + (int)Shape; public bool Equals(Tile tile) => X == tile.X && Y == tile.Y && Shape == tile.Shape; public override bool Equals(object obj) => obj is Tile tile && Equals(tile); public int CompareTo(Tile other) { if (X != other.X) return X.CompareTo(other.X); if (Y != other.Y) return Y.CompareTo(other.Y); return Shape.CompareTo(other.Shape); } public override string ToString() => $"({X},{Y},{Shape})"; } enum TileShape : byte { Anticlockwise, Clockwise, NE, SW, NW, SE } class TileSet : IReadOnlyCollection<Tile> { public TileSet(IEnumerable<Tile> tiles) { // Canonicalise var ordered = _Canonicalise(new HashSet<Tile>(tiles)); int h = 1; foreach (var tile in ordered) h = h * 37 + tile.GetHashCode(); _HashCode = h; #if SUPERLIGHT // Since we normalise to have minimum X and Y of 0, we can use unsigned coordinates. // And since we're looking at connected graphs of on the order of 20 items, 6 bits per coordinate is plenty. _Items = ordered.Select(tile => (short)((tile.X << 9) + (tile.Y << 3) + (int)tile.Shape)).ToArray(); #else _Items = new HashSet<Tile>(ordered); #endif } private IReadOnlyList<Tile> _Canonicalise(ISet<Tile> tiles) { int ac = tiles.Count(tile => tile.Shape == TileShape.Anticlockwise); int c = tiles.Count(tile => tile.Shape == TileShape.Clockwise); if (ac < c) return _CanonicaliseRot(tiles); if (ac > c) return _CanonicaliseRot(tiles.Select(tile => tile.Flip())); return _Min(_CanonicaliseRot(tiles), _CanonicaliseRot(tiles.Select(tile => tile.Flip()))); } private IReadOnlyList<Tile> _Min(IReadOnlyList<Tile> tiles1, IReadOnlyList<Tile> tiles2) { for (int i = 0; i < tiles1.Count; i++) { int cmp = tiles1[i].CompareTo(tiles2[i]); if (cmp < 0) return tiles1; if (cmp > 0) return tiles2; } return tiles1; } private IReadOnlyList<Tile> _CanonicaliseRot(IEnumerable<Tile> tiles) { // Rotation anticlockwise by 90 maps NE -> NW -> SW -> SE -> NE. We rotate to get one of these necklaces (in rank order, not exact values): // Necklaces: // SE NE NW SW // 0 0 0 0 ** Four positions to consider // 1 0 0 0 // 1 0 1 0 ** Two positions to consider // 1 1 0 0 // 1 1 1 0 // 2 0 0 1 // 2 0 1 0 // 2 0 1 1 // 2 1 0 0 // 2 1 0 1 // 2 1 1 0 // 2 1 2 0 // 2 2 0 1 // 2 2 1 0 // 3 0 1 2 // 3 0 2 1 // 3 1 0 2 // 3 1 2 0 // 3 2 0 1 // 3 2 1 0 int se = tiles.Count(tile => tile.Shape == TileShape.SE); int ne = tiles.Count(tile => tile.Shape == TileShape.NE); int nw = tiles.Count(tile => tile.Shape == TileShape.NW); int sw = tiles.Count(tile => tile.Shape == TileShape.SW); var sorted = new int[] { se, ne, nw, sw }.Distinct().OrderBy(x => x); var index = 1000 * sorted.IndexOf(se) + 100 * sorted.IndexOf(ne) + 10 * sorted.IndexOf(nw) + sorted.IndexOf(sw); switch (index) { case 0: // All four positions need to be considered var best = _Translate(tiles); best = _Min(best, _Translate(tiles.Select(tile => tile.Rot()))); best = _Min(best, _Translate(tiles.Select(tile => tile.Rot().Rot()))); best = _Min(best, _Translate(tiles.Select(tile => tile.Rot().Rot().Rot()))); return best; case 101: // Two options need to be considered; return _Min(_Translate(tiles.Select(tile => tile.Rot())), _Translate(tiles.Select(tile => tile.Rot().Rot().Rot()))); case 1010: // Two options need to be considered; return _Min(_Translate(tiles), _Translate(tiles.Select(tile => tile.Rot().Rot()))); case 1000: case 1100: case 1110: case 2001: case 2010: case 2011: case 2100: case 2101: case 2110: case 2120: case 2201: case 2210: case 3012: case 3021: case 3102: case 3120: case 3201: case 3210: // Already in the canonical rotation. return _Translate(tiles); case 1: case 1001: case 1101: case 12: case 102: case 112: case 1002: case 1012: case 1102: case 1202: case 2012: case 2102: case 123: case 213: case 1023: case 1203: case 2013: case 2103: // Needs one rotation. return _Translate(tiles.Select(tile => tile.Rot())); case 10: case 11: case 1011: case 120: case 1020: case 1120: case 21: case 121: case 1021: case 2021: case 122: case 1022: case 1230: case 2130: case 231: case 2031: case 132: case 1032: // Needs two rotations. return _Translate(tiles.Select(tile => tile.Rot().Rot())); case 100: case 110: case 111: case 1200: case 201: case 1201: case 210: case 1210: case 211: case 212: case 1220: case 221: case 2301: case 1302: case 2310: case 312: case 1320: case 321: // Needs three rotations. return _Translate(tiles.Select(tile => tile.Rot().Rot().Rot())); default: throw new NotSupportedException("Case analysis failed"); } } private IReadOnlyList<Tile> _Translate(IEnumerable<Tile> tiles) { int minX = tiles.Min(tile => tile.X); int minY = tiles.Min(tile => tile.Y); return tiles. Select(tile => new Tile { Shape = tile.Shape, X = (sbyte)(tile.X - minX), Y = (sbyte)(tile.Y - minY) }). OrderBy(tile => tile). ToList(); } #if SUPERLIGHT private readonly short[] _Items; public int Count => _Items.Length; public IEnumerator<Tile> GetEnumerator() { foreach (var encoded in _Items) { yield return new Tile { X = (sbyte)((encoded >> 9) & 0x3f), Y = (sbyte)((encoded >> 3) & 0x3f), Shape = (TileShape)(encoded & 0x7) }; } } #else private readonly ISet<Tile> _Items; public int Count => _Items.Count; public IEnumerator<Tile> GetEnumerator() => _Items.GetEnumerator(); public bool Contains(Tile tile) => _Items.Contains(tile); #endif IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private readonly int _HashCode; public override int GetHashCode() => _HashCode; public bool Equals(TileSet tileset) => tileset != null && tileset.Count == Count && tileset._HashCode == _HashCode && _Items.SequenceEqual(tileset._Items); public override bool Equals(object obj) => obj is TileSet tileset && Equals(tileset); } } static class Extensions { internal static int IndexOf<T>(this IEnumerable<T> elts, T elt) where T : IEquatable<T> { int idx = 0; foreach (var item in elts) { if (item.Equals(elt)) return idx; idx++; } return -1; } } } ``` ]
[Question] [ 256-color Xterm-compatible terminals add 240 colors on top of the usual 16 system colors. Colors 16-231 use 6 levels (0, 95, 135, 175, 215, 255) of red, green, and blue, ordered lexicographically. Colors 232-255 are simply 24 levels of gray (8...238 by 10s). To get a better idea of what I'm talking about, see [this table](https://jonasjacek.github.io/colors/). # The Challenge Your goal is to make a program or function that takes, as input, rgb values, and outputs the number corresponding with the closest Xterm color to that rgb value. **Since the 16 system colors (colors 0-15) are often customizable, you will be excluding them from this conversion.** To better define what the "closest" color is, use the [Manhattan distance](https://en.wiktionary.org/wiki/Manhattan_distance) along red, green, and blue components. For example, `rgb(10, 180, 90)` is 20 units away from `rgb(0, 175, 95)` (color 35) because `abs(10 - 0) + abs(180 - 175) + abs(90 - 95) == 20`. If the input color is equally between two or more Xterm colors, output the Xterm color with the highest index. # Examples ``` R G B Xterm 0 0 0 ==> 16 95 135 0 ==> 64 255 255 255 ==> 231 238 238 238 ==> 255 90 133 140 ==> 66 218 215 216 ==> 188 175 177 178 ==> 249 175 0 155 ==> 127 75 75 75 ==> 239 23 23 23 ==> 234 115 155 235 ==> 111 ``` # Rules * Standard loopholes are forbidden * Your program or function is allowed to take rgb values in any reasonable format, including: + Separate arguments for red, green, and blue + A list, tuple, dictionary, or similar + Delimiter-separated string or stdin + Hex colors (e.g. `#ff8000`) * You may assume that all r, g, and b, values will be integers between 0 and 255. * Since the 16 system colors are to be excluded from the mapping, all outputs should be in the range 16...255. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [Haskell](https://www.haskell.org/), 132 bytes ``` v=0:[95,135..255] f c=snd$maximum[(-sum(abs<$>zipWith(-)c x),i)|(i,x)<-zip[16..]$[[r,g,b]|r<-v,g<-v,b<-v]++[[g,g,g]|g<-[8,18..238]]] ``` [Try it online!](https://tio.run/##ZZDLboMwEEX3@YopYmGEQTGER6rQL2hXrdSFZVU8HEAFgjCkqMq/0zHNhtZ4LOQDx9dTpepTNs2yXJP9Iz8GlPmB63pBIHZnyBPVFWabznU7tZw4ampJmqmT@fRd9@/1WBHHymG2aG3dSE1n6@Qg4Cx0XWFyPtCSZuI2nJwrLfWS4SJsm/MSSSluuMljymI80I@FEEub1h0kUFx2gKORI4xSjUBydCf1GXSkZIaxkh0McpyGjlggGyVBDsNlMFV1@YLctg3At6kpIJNg2Pa6Pa/ONu1fPn6tnPA9xUdQFlp0pXqQexc0CA8bgG2h9xLU89kW@jG9l9BfbJV7VPqUHbR0e5rH8B@GUhZikjjeQBZhlijC0tLD8R9Erw7DvGiDkKxTxzz@iUnXqcn2dgxDMH07XwsZs8QK@2l8HYfnDow37JqCPlVKFg/G8gM "Haskell – Try It Online") Takes input as a list of integers `[red, green, blue]`. Fairly straightforward implementation. First I build a list of the Xterm colors we're using with two list comprehensions concatenated together. The first of which handles colors 16-231 by triple iterating over `v` which contains the values those colors use. The second one just iterates over the grey values and puts them in all three slots. Then I index it with zip (starting at 16) and make a pair with the manhattan distance (negated) and that index and take the maximum. I used maximum because we're tie-breaking on the largest index and this way saves me one extra `-`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~280~~ ~~180~~ ~~166~~ ~~164~~ 155 bytes ``` ->c{d=0,95,135,175,215,255 a=(0..239).map{|n|n<216?[d[n/36],d[(n%36)/6],d[n%6]]:[n*10-2152]*3}.map{|t|t.zip(c).map{|a,b|(a-b).abs}.sum} a.rindex(a.min)+16} ``` [Try it online!](https://tio.run/##TVHRbuMgEHz3V6xcWbJzhHpN4iTVuf2Fe0foRGyis9RQKxCpvTrfngMMvT4wXpjdmd315Xr8uJ@6@/q5/xy6mhy2BJk7uy1p0J3tNpNdWVPasENFz3L6nPWsfzbYvvCB60fWCjLwUhesrR5DrItWiCeuV1ivnUQjVuy2FNrZ0r/jVPZRSJLjXMr1saLyaG7UXM@3TNLLqAf1Xkp6HnX1A9vb3Spjf/fSKAMd8AyAc4CaQALhEJ33wrgJwI@QmHYTGTcLgQSOaRgmhu39dQER@ahWezXmYLOoJZ8GfTp6Ne8NuN9Hxu8OcLfzENQ2h@9M6BpDB9jskk9gIoTeUo0L3WOEwKR50JtjmIcFNUSRiSz7vy6qZP8HhjeYRz1drSGg3ifVWzXMTuGizPXVupWe@EK7WoAH@HVR1n6Al4k5xr37BMh5wQYCCQR0z/4LZWGqHIrwcwBW0S1cFoXvMXTdVx/wAvkkjcnhCfKTHF9zlygypYf7Pw "Ruby – Try It Online") A lambda taking the input color as an array of integers. I had more trouble generating the Xterm colors than I expected! I'm prepared to be outgolfed ~~embarrassingly~~ modestly in that area. I used base conversion as a kind of compression, ~~but the only way I know to do so in Ruby is through `Integer#to_s`~~ which is a little bit awkward. -100 bytes: Read the problem more carefully, and ignore the 16 system colors ^\_^; -14 bytes: Use hand base conversion instead of `.to_s(6)` -2 bytes: Skip square brackets when declaring array -9 bytes: Create list of Xterm colors with only one `map`; this also saves a plus sign and a pair of parens. ``` ->c{ d=0,95,135,175,215,255 # d is the set of possible RGB values a=(0..239).map{|n| # Create the array of Xterm triplets n<216 ? [d[n/36],d[(n%36)/6],d[n%6]] # Convert x from base 6 to base d, or : [n*10-2152]*3 # create a uniform triplet }.map{|t| t.zip(c).map{|a,b|(a-b).abs}.sum # Map from triplets to Manhattan distance } a.rindex(a.min) + # Find the last index of the lowest distance 16 # Offset for the exluded system colors } ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~299~~ ~~290~~ ~~267~~ 265 bytes ``` (16..255).associate{it to if(it<232)(it-16).let{i->listOf(0,95,135,175,215,255).let{l->listOf(l[i/36],l[(i/6)%6],l[i%6])}}else(8..238 step 10).toList()[it-232].let{listOf(it,it,it)}}.minBy{(k,v)->(it.zip(v).map{(a,b)->kotlin.math.abs(a-b)}.sum()*256)+(256-k)}!!.key ``` ## Beautified ``` (16..255).associate { it to if (it < 232) (it - 16).let { i -> listOf(0, 95, 135, 175, 215, 255).let { l -> listOf( l[i / 36], l[(i / 6) % 6], l[i % 6]) } } else (8..238 step 10).toList()[it - 232].let { listOf(it, it, it) } }.minBy { (k, v) -> (it.zip(v).map { (a, b) -> kotlin.math.abs(a - b) }.sum() * 256) + (256 - k) }!!.key ``` ## Test ``` data class Test(val r: Int, val g: Int, val b: Int, val out: Int) val test = listOf( Test(0, 0, 0, 16), Test(95, 135, 0, 64), Test(255, 255, 255, 231), Test(238, 238, 238, 255), Test(90, 133, 140, 66), Test(218, 215, 216, 188), Test(175, 177, 178, 249), Test(175, 0, 155, 127), Test(75, 75, 75, 239), Test(23, 23, 23, 234), Test(115, 155, 235, 111) ) fun z(it:List<Int>): Int = (16..255).associate{it to if(it<232)(it-16).let{i->listOf(0,95,135,175,215,255).let{l->listOf(l[i/36],l[(i/6)%6],l[i%6])}}else(8..238 step 10).toList()[it-232].let{listOf(it,it,it)}}.minBy{(k,v)->(it.zip(v).map{(a,b)->kotlin.math.abs(a-b)}.sum()*256)+(256-k)}!!.key fun main(args: Array<String>) { for (i in test) { val r = z(listOf(i.r, i.g, i.b)) println("$i ${i.out} ==> $r") } } ``` ## TIO [TryItOnline](https://tio.run/##ZVNRj9owDH7vr_CdmJTc2hxpaSkIKm1vkybtYXtD95DeFRa1tKgNSFD1t_HAH5udHojRKHEc-4vt2E5emUKXl7PzoYyC90I1DfzJGsMOqoB6Dj9K4wLxmzs-veOrvbEn7jh0NHgXllDoxvxaMwc-hzU5dqGfMuLu_6pZiNIgtNpo8qj1Q9TckUAOEEFM8hsJQ0Q8uCDHQYBkQk4GIfiSLkqyLyNExfEjQk4pyumUCGEns4ETCyFHFKf0p48mSH1dfjAbPoPE1zXIg6ToZJ8C4qTkDnfW-xJOTJv5T0z6AkuRcFsRWF7OTEZCUDYEFrZ618pkrTZgKtBrvLLwA5_j7mFFRJGZVnvJZ-nGLtaESkJPorRYK4QpbphipV-D6M0tVky_RvyLZTVuvOuyoslYjM6DGBqT7UCOuTAVxcj4Cl2i67feXm9MG9dOvCu2uvx-bFnuHriXoEac9I4duNiqXcuUm6I0t42LEvNXqLRhykt5J5r9lvEXP4z4V-yayMt59_Qk8uyIHU552ipdMlVvmjl8q2t1XPw2tS43CYfWpnpd1cA06NI28lVKw_4H7OwTu8Yrahe02BBJOb8Bd2jQFCV7HmkYtVrgB-lguUxgVD_3qM7pLud_) [Answer] # [Stax](https://github.com/tomtheisen/stax), 41 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ¬ÿ▒ú╘Σt∙Æ9φ☻ùí&BQq═IÜH∩Å╧♥f⌠óH]╨⌡≤@■Q‼Hr¼ ``` [Run and debug online!](https://staxlang.xyz/#c=%C2%AC%C3%BF%E2%96%92%C3%BA%E2%95%98%CE%A3t%E2%88%99%C3%869%CF%86%E2%98%BB%C3%B9%C3%AD%26BQq%E2%95%90I%C3%9CH%E2%88%A9%C3%85%E2%95%A7%E2%99%A5f%E2%8C%A0%C3%B3H%5D%E2%95%A8%E2%8C%A1%E2%89%A4%40%E2%96%A0Q%E2%80%BCHr%C2%BC&i=%5B0%2C0%2C0%5D%0A%5B95%2C135%2C0%5D%0A%5B255%2C255%2C255%5D%0A%5B238%2C238%2C238%5D%0A%5B90%2C133%2C140%5D%0A%5B218%2C215%2C216%5D%0A%5B175%2C177%2C178%5D%0A%5B175%2C0%2C155%5D%0A%5B75%2C75%2C75%5D%0A%5B23%2C23%2C23%5D%0A%5B115%2C155%2C235%5D&a=1&m=2) ASCII version of 50 bytes: ``` "4GOW_g"{52-5*m3|^24{A*vv]3*m+{;\{E:-m|+mc|m|IH16+ ``` [Answer] ## Batch, 266 bytes ``` @set/ax=15,m=999 @set s=for %%b in (0 95 135 175 215 255)do @ @%s:b=r%%s:b=g%%s%call:c %* %%r %%g %%b @for /l %%g in (8,10,238)do @call:c %* %%g %%g %%g @echo %n% :c @set/ax+=1,r=%4-%1,g=%5-%2,b=%6-%3 @set/ad=%r:-=%+%g:-=%+%b:-=% @if %d% leq %m% set/an=x,m=d ``` [Answer] # C (gcc), ~~202 192 157 150 (141 bugged) 138~~ 134 bytes ``` l,m,t,i;a(c,x){x=abs(c-=i>215?i*10-2152:x*40+!!x*55);}f(r,g,b){for(i=l=240;i--;t=a(r,i/36)+a(g,i/6%6)+a(b,i%6),t<l?l=t,m=i:1);i=m+16;} ``` Thanks @ceilingcat [Try it online!](https://tio.run/##hZDBboMwEETvfIWTKpINRmFtDCSukx/pBUhAloBUKQekKP11ajuksXrpZVjxmJll67it63nuaE9HqmWJazqR26TK6gvXsdIHBuJYRFjHDDISQrKfwjSJVqspFILIe4OvtKUVuTWXK9aqUyxN5LeOYzmq0jC95RmJStyaKdu4saLaDHR8746dGmmv9B6I1KqPIJP3@e10bvRwRtO4RH9e9TA2eL05fQxr@iwkMuhLPWByC8yXCCUUPYVItN0ipQ4IMgd3giLg4g/MUguZMO@f8oKMw7@5jBfGtYhnFeLRmthWbiT1Wx9WsC6wreasr9yisBRyu3CeW/GD090vdTuBvzGw3NU6uoj/P85rngYs4lN3C7ALgbsF95MBgvv8Aw) ]
[Question] [ The input will be two five letter words. They don't actually have to be dictionary words, just any five letters each, all lowercase or all uppercase, your choice. Only A-Z will appear in the input words and they will always be 5 characters in length. Your program is to score them both as though they were poker hands and output the higher hand. Of course suits won't apply here, only rankings so there's no flushes. The typical poker ranking system goes: '1 pair', '2 pairs', '3 of a kind', 'straight', 'full house', '4 of a kind', '5 of a kind', and of course there is the possibility the hand (or word in this case) could be worth nothing. **In the case of ties**, letters closer to A are considered higher, so a pair of As beats a pair of Bs. In some cases both hands might be identical, but in a different order (or not), in that case output either hand or a resorted version of it. [This external page](http://www.compendia.co.uk/poker_scores.htm) contains information about how to identify the winner and especially addresses ties within the specific rankings, in case you aren't familiar with how to score poker hands. **In the case of straights**: the letters must be adjacent in the alphabet and are not allowed to wrap around. So 'defgh' in any order is a straight, 'xyzab' is not. Examples of how to score a single hand: ``` word | scored as --------------------- ccccc | 5 of a kind <-- highest ranking woooo | 4 of a kind opopo | full house vurst | straight vovvu | 3 of a kind ppoww | 2 pairs upper | 1 pair kjsdf | high card only (in this case D) <-- lowest ranking ``` So the program will actually produce results like this: ``` input | output ----------------------- voviu,kjsdf | voviu because a pair beats nothing opoqo,upper | opoqo because 3 of a kind beats a pair woooo,ggegg | ggegg because 4 Gs beats 4 Os queue,hopup | queue because 2 pairs beats 1 pair lodpl,ddkop | ddkop because pair DD beats pair LL huhyg,hijht | huhyg both have pair HH, but G beats I ddffh,ccyyz | ccyyz both have 2 pairs, but CC(yyz) beats DD(ffh) okaok,nkunk | nkunk KK ties with KK, but NN beats OO abcdf,bcdef | bcdef because it is a straight qtery,retyq | qtery identical! so doesnt matter abedc,vyxwz | abedc because it is a "higher" straight hhhij,hijkl | hijkl because straight beats 3 of a kind aaabb,zzzzz | zzzzz because nothing beats 5 of a kind ``` The order of the letters in both the input and output are irrelevant, so the order in your output can be different than the input, but the same inventory of letters needs to be present. The output must contain exactly five letters -- no more, no less. The usual codegolf rules apply. Shortest code wins. [Answer] ## JavaScript (~~224~~ ~~218~~ 213 bytes) ``` s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t) ``` **Ungolfed:** ``` s=>t=>( v=s=>( o={}, l=n=0, z=3.5, [...s].sort().map(c=>( n+=o[c]=-~o[c], z*=!l|l+1==(l=c.charCodeAt()) )), [n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))] ), w=v(s),x=v(t), w[0]>x[0] || w[0]==x[0] && w[1]<x[1] ? s : t ) ``` After `map()` runs, `n + z` determines the ranking of a hand: [![enter image description here](https://i.stack.imgur.com/yhDrt.png)](https://i.stack.imgur.com/yhDrt.png) (You can understand why I initialized `z` to 3.5.) In case of a tie, `Object.keys(o).sort()` is used to determine the higher ranking hand. **Snippet:** ``` f= s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t) console.log(/voviu/.test(f('voviu')('kjsdf'))) //because a pair beats nothing console.log(/opoqo/.test(f('opoqo')('upper'))) //because 3 of a kind beats a pair console.log(/ggegg/.test(f('woooo')('ggegg'))) //because 4 Gs beats 4 Os console.log(/queue/.test(f('queue')('hopup'))) //because 2 pairs beats 1 pair console.log(/ddkop/.test(f('lodpl')('ddkop'))) //because pair DD beats pair LL console.log(/huhyg/.test(f('huhyg')('hijht'))) //both have pair HH, but G beats I console.log(/ccyyz/.test(f('ddffh')('ccyyz'))) //both have 2 pairs, but CC(yyz) beats DD(ffh) console.log(/nkunk/.test(f('okaok')('nkunk'))) //KK ties with KK, but NN beats OO console.log(/bcdef/.test(f('abcdf')('bcdef'))) //because it is a straight console.log(/qtery|retyq/.test(f('qtery')('retyq'))) //identical! so doesnt matter console.log(/abedc/.test(f('abedc')('vyxwz'))) //because it is a "higher" straight console.log(/hijkl/.test(f('hhhij')('hijkl'))) //because straight beats 3 of a kind console.log(/zzzzz/.test(f('aaabb')('zzzzz'))) //because nothing beats 5 of a kind ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28 27 29~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +2 & then -2 fix a bug, then re-golf. ``` FI=1ȦḤW OµNĠLÞṚịµL€+Ç,N ÇÞṪ ``` A monadic link taking a list of "hands" and returning (one of) the winners. Works for all-uppercase OR all-lowercase input. (...but not mixed, for that prepend the final line with `Œl` or `Œu`). **[Try it online!](https://tio.run/nexus/jelly#@@/maWt4YtnDHUvCufz9jizwOTzv4c5ZD3d3@x/a6vOoaY324XYdP67D7SDhVf///49WyijNqExX0lHKyMzKKFGKBQA)** or see the [test suite](https://tio.run/nexus/jelly#Lc6xTsMwEAbgvY9hseGlD4DEhIRatSNCUYYkduzGUc8JcYo7IZYMvEElEAPqUHVFAtGpAYnXSF8kXGxuudOnX3fXX11fjH@33cfbzWg@@36dti/d56b7epof36enx/1529DZqG0G3vVtg/RzuMywnR6e6dkEh9u@DwJSQ70whBKV3bGUhDQgoKEAFKM1L52sAAtFCC6Ek8Jww1EkaKOd5MB0jsKYAi/SSCuGzCKTlRPG0lSiJIm1a39LRaBQlsoslZMoTvAPSrBx/09R8dKilLyyxX@GswSltvcrv0dKmSl/S@U@E0VxjLIeioThHw). ### How? ``` FI=1ȦḤW - Link 1, straight offset: grouped and reverse sorted hand ordinals - e.g. [[-101],[-100],[-99],[-98],[-97]] F - flatten [-101,-100,-99,-98,-97] I - increments [1,1,1,1] =1 - equal 1? (vectorises) [1,1,1,1] Ȧ - any and all? 1 Ḥ - double 2 W - wrap in a list [2] - The purpose of this is so that when "a" from Link 2 represents a straight we - get [2], whereas for any other hand we get [0]. Adding the [2] to [1,1,1,1,1] - (the lengths of a straight's groups) yields [3,1,1,1,1], placing it between - three of a kind, [3,1,1], and a full house, [3,2], as required. OµNĠLÞṚịµL€+Ç,N - Link 2, hand rank key function: list of characters e.g. "huhyg" O - cast to ordinals [104,117,104,121,103] µ - monadic chain separation, call that o N - negate (to give them a reverse-sort order) [-104,-117,-104,-121,-103] Ġ - group indices by value [[4],[2],[1,3],[5]] Þ - sort by key function: L - length [[4],[2],[5],[1,3]] Ṛ - reverse [[1,3],[5],[2],[4]] ị - index into o [[-104,-104],[-103],[-117],[-121]] µ - monadic chain separation (call that a) L€ - length of €ach [2,1,1,1] Ç - call last link (2) as a monad -> [isStraight? * 2] [0] + - addition (vectorises) [2,1,1,1] N - negate o [[104,104],[103],[117],[121]] , - pair [[2,1,1,1],[[104,104],[103],[117],[121]]] - now sorting by this will first be comparing the hand class, and if - and only if they match comparing the card values in the required order. ÇÞḢ - Main link: list of lists of characters (list of hands) Þ - sort by key function: Ç - last link (2) as a monad Ṫ - tail (best or an equal-best hand) ``` [Answer] ## JavaScript (250 247 232 bytes) ``` S=d=>(x={},l=99,h=s=0,[...d].map(v=>x[v]=-~x[v]),Object.keys(x).map(v=>(c=91-v.charCodeAt(),t=x[v],s+=1e4**t,c<x[t]?0:x[t]=c,g=(h=c>h?c:h)-(l=c<l?c:l))),[5,4,3,2,1].map(v=>s+=0|x[v]**v),s+(s<5e7&&g<5?1e13:0)),C=a=>b=>(S(a)>S(b)?a:b) ``` ### Ungolfed code & test cases in JSFiddle: <https://jsfiddle.net/CookieJon/8yq8ow1b/> Saved some bytes with thanks to @RickHitchcock. @StephenS & @Arnauld [Answer] # Python 2.7, ~~242~~ 223 bytes ``` from collections import* s=sorted f=lambda x,y:s(map(lambda h:(lambda (r,n):((3,1.5)if len(r)==5 and ord(r[0])+4==ord(r[4])else n,[-ord(d) for d in r],h))(zip(*s(Counter(h).items(),key=lambda z:(-z[1],z[0])))),(x,y)))[1][2] ``` Similar in basic concept to the javascript examples (sort by hand strength with an exception for straights; then by rank); but taking advantage of `collections.Counter` Unfortunately, `.most_common` doesn't have quite the desired behavior; so had to add a custom sort key. Edit: a bit more code golfing to trim down 19 bytes. **Un-golfed code** ``` from collections import Counter def convertHand(h): # first get item counts, appropriately ordered; e.g. cbabc -> (('b',2), ('c',2),('a',1)) sortedPairs = sorted(Counter(h).items(),key=lambda x:(-x[1],x[0])) # 'unzip' the tuples to get (('b','c','a'), (2,2,1)) ranks, numberFound = zip(*sortedPairs) if len(ranks)==5: # no pairs; is it a straight? well, since they are in increasing order... if ord(ranks[0])+4 == ord(ranks[4]): # replace numberFound with something that will sort above 3 of a kind but below full house numberFound = (3,1.5) # invert the values of the ranks, so they are in decreasing, rather then increasing order ranks = [-ord(r) for r in ranks] # arrange tuples so we can sort by numberFound, and then ranks; and keep a reference to the hand return (numberFound, ranks, h) # put it all together... def f(x,y): hands = [convertHand(h) for h in (x,y)] rankedHands = sorted(hands) return rankedHands[1][2] ``` [Answer] ## Mathematica, 635 bytes ``` H[x_]:=Block[{t},T=Sort@ToCharacterCode[x];L=Last/@Tally@T;t=0;S=Count;If[S[L,2]==1,t=1];If[S[L,2]==2,t=2];If[S[L,3]==1,t=3];If[S[Differences@T,1]==4,t=4];If[S[L,2]==1&&S[L,3]==1,t=5];If[S[L,4]==1,t=6];If[S[L,5]==1,t=7];t];F[K_,v_]:=First@Flatten@Cases[Tally@K,{_,v}];B=ToCharacterCode;(Z=Sort@B@#1;Y=Sort@B@#2;a=H[#1];b=H[#2];If[a>b,P@#1,If[a<b,P@#2]]If[a==b&&a==0,If[Z[[1]]<Y[[1]],P@#1,P@#2]];If[a==b&&(a==1||a==2),If[F[Z,2]<F[Y,2],P@#1,If[F[Z,2]==F[Y,2],If[F[Z,1]<F[Y,1],P@#1,P@#2],P@#2]]];If[a==b&&(a==3||a==5),If[F[Z,3]<F[Y,3],P@#1,P@#2]];If[a==b&&a==6,If[F[Z,4]<F[Y,4],P@#1,P@#2]];If[a==b&&(a==7||a==4),If[Tr@Z<Tr@Y,P@#1,P@#2]])& ``` . . > > ["abcde", "kkekk"] > > > ]
[Question] [ ## Introduction In this challenge, a 2×2 matrix is indexed like this: ``` 0 1 2 3 ``` We define a family of fractal-like patterns `F(L)`, where `L` is a length-`n` list of these indices and `F(L)` has size `2n-1 × 2n-1`. * If `L == []`, then `F(L)` is the 1×1 pattern `#`. * If `L != []`, then `F(L)` is constructed as follows. Let `P` be the pattern obtained from `L` with first element removed. Take four grids of size `2n-1-1 × 2n-1-1` filled with periods `.`, and replace the grid indexed by `L[0]` with the pattern `P`. Then, glue the grids together using one layer of hashes `#` between them. Here are diagrams for the four cases: ``` L[0]==0 L[0]==1 L[0]==2 L[0]==3 #... ...# ...#... ...#... [P]#... ...#[P] ...#... ...#... #... ...# ...#... ...#... ####### ####### ####### ####### ...#... ...#... #... ...# ...#... ...#... [P]#... ...#[P] ...#... ...#... #... ...# ``` ## Example Consider the input `L = [2,0]`. We begin with the 1×1 grid `#`, and traverse `L` from the right. The rightmost element is `0`, so we take four copies of the 1×1 grid `.`, replace the first one by `#`, and glue them together with hashes. This results in the 3×3 grid ``` ##. ### .#. ``` The next element is `2`, so we take four copies of the 3×3 grid of `.`s, and replace the third one with the above grid. The four grids are ``` ... ... ##. ... ... ... ### ... ... ... .#. ... ``` and gluing them together with `#`s results in the 7×7 grid ``` ...#... ...#... ...#... ####### ##.#... ####... .#.#... ``` This is our final output. ## Input Your input is a list `L` of the indices `0, 1, 2, 3`. You can take it as a list of integers, or a string of digits. Note that it may be empty, and it may contain duplicates. The length of `L` is at most 5. ## Output Your output is the pattern `F(L)` as a newline-delimited string. ## Rules and scoring You can write a full program or a function. the lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` [] # [0] ##. ### .#. [3] .#. ### .## [2,0] ...#... ...#... ...#... ####### ##.#... ####... .#.#... [1,1] ...#.## ...#### ...#.#. ####### ...#... ...#... ...#... [1,2,0] .......#...#... .......#...#... .......#...#... .......######## .......###.#... .......#####... .......#.#.#... ############### .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... [3,3,1] .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... ############### .......#...#... .......#...#... .......#...#... .......######## .......#...#.## .......#...#### .......#...#.#. [0,1,2,3] .......#...#...#............... .......#...#...#............... .......#...#...#............... .......#########............... .......#.#.#...#............... .......#####...#............... .......#.###...#............... ################............... .......#.......#............... .......#.......#............... .......#.......#............... .......#.......#............... .......#.......#............... .......#.......#............... .......#.......#............... ############################### ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... ...............#............... [0,0,1,2,3] .......#...#...#...............#............................... .......#...#...#...............#............................... .......#...#...#...............#............................... .......#########...............#............................... .......#.#.#...#...............#............................... .......#####...#...............#............................... .......#.###...#...............#............................... ################...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... .......#.......#...............#............................... ################################............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ...............#...............#............................... ############################################################### ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ...............................#............................... ``` [Answer] ## CJam, ~~59~~ ~~47~~ ~~43~~ ~~41~~ 40 bytes *Thanks to Sp3000 for saving 1 byte.* ``` Sal~W%{_Bff|a4*I@t2/{zSf*z}:F%F}fI3ff+N* ``` [Test it here.](http://cjam.aditsu.net/#code=Sal~W%25%7B_Bff%7Ca4*I%40t2%2F%7BzSf*z%7D%3AF%25F%7DfI3ff%2BN*&input=%5B0%200%201%202%203%5D) ### Explanation *Slightly outdated. Will fix later.* All the dimension reorderings of 4D lists are making me dizzy... This code implements the specification very literally, using the iterative algorithm from the example section instead of its recursive definition.. One major golfing trick is that I'm using spaces instead of `#` during the computation and only replace them with `#` at the end, which simplifies the code in one place and allows me to use `S` instead of `'#` or `"#"` in several. ``` Sa e# Push [" "], i.e. a 1x1 grid containing only a space as the e# initial fractal. l~ e# Read and evaluate input. W% e# Reverse the list. { e# For each list element, assigning the element to variable I... _ e# Duplicate the grid. Eff| e# Map (OR 14) over each character in the grid, turning spaces into e# periods and leaving periods unchanged. a4* e# Create an array with four copies of this cleared grid. I@t e# Replace the Ith element in this list with the previous grid. 2/ e# Split this array into a 2x2 grid of subgrids... e# Now it's getting a bit weird... we've got 4 dimensions now, which are: e# - Rows of the 2x2 meta-grid. e# - Cells in each row of the 2x2 meta-grid (i.e. subgrids). e# - Rows of each subgrid. e# - Characters in each row of each subgrid. :z e# Transpose each outer row, i.e. swap dimensions 2 and 3. e# We've now got in each row of the meta-grid, a list of pairs of e# corresponding rows of the subgrids. Sff* e# Join those pairs of rows with a single space each. We're now down e# to three dimensions: e# - Rows of the 2x2 meta-grid. e# - Rows of each 1x2 block of the meta-grid. e# - Characters in each row of those blocks. :z e# Transpose the blocks, i.e. turn the 1x2 blocks into a list of e# columns of their characters. z e# Transpose the outer grid, i.e. turn it into a list of pairs of e# corresponding columns in the two 1x2 blocks. Sf* e# Join each pair of columns with a single space. We've now got the e# new grid we're looking for, but it's a list of columns, i.e. transposed. z e# Fix that by transposing the entire grid once more. }I N* e# Join the rows of the grid with linefeeds. S'#er e# Replace all spaces with #. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~42~~ 41 bytes ``` '.#'4:He!XIiP"Iq@=wX*1X@WZ(l5MY(]3Lt3$)Q) ``` [**Try it online!**](http://matl.tryitonline.net/#code=Jy4jJzQ6SGUhWElpUCJJcUA9d1gqMVhAV1oobDVNWShdM0x0MyQpUSk&input=WzAsMSwyLDNd) ### Explanation This works iteratively using a [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product) to extend the array in each iteration. The array is built with `0` and `1` instead of `.` and `#`, and at the end they are replaced by the appropriate characters. There will be as many iterations as the input size. Input is processed from right to left. Iteration index starts at `1`. Using the example in the challenge, with input `[2,0]`, the array is initiallized as ``` 1 2 3 4 ``` This corresponds to the initial `1` (`#`) extended by one row and one column, whose purpose will be clear later. The values in those columns are not important, as they will be overwritten; they could equally be ones: ``` 1 1 1 1 ``` At each iteration, the existing array is Kronecker-multiplied by a 2×2 zero-one array that contains `1` at the position indicated by the current entry of the input, and `0` at the other entries. In the example at iteration *i* = 1, since the rightmost input entry is `0`, the zero-one array is ``` 1 0 0 0 ``` and the Kronecker product of these two arrays is ``` 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 ``` Next, the row and column with index `2^i` are filled with ones: ``` 1 1 0 0 1 1 1 1 0 1 0 0 0 1 0 0 ``` The first three rows and columns constitute the result of the first iteration. As before, there are an extra row and column, which are useful for extending the array in the next iteration. At iteration *i* = 2, since the current input value contains `2` the array above is Kronecker-multiplied by ``` 0 0 1 0 ``` which gives ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 ``` Filling the `2^i`-th row and column with ones gives ``` 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 ``` Since this is the last iteration, the extra row and column are removed: ``` 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 0 ``` and the character substitution is done to produce the final result: ``` ...#... ...#... ...#... ####### ##.#... ####... .#.#... ``` Detailed description of the code follows: ``` '.#' % Push this string. Will be indexed into 4:He! % Push 2×2 array [1 2; 3 4] XI % Copy it into clipboard I iP % Input array and reverse it " % For each entry of the reversed input I % Push [1 2; 3 4] from clipboard I q % Subtract 1 to yield [0 1; 2 3] @= % Compare with current entry of the input. Gives 2×2 array % with an entry equal to `1` and the rest `0` wX* % Swap. Kronecker product 1 % Push 1 X@ % Push iteration index, i W % Compute 2^i Z( % Write 1 into column 2^i l % Push 1 5M % Push 2^i again Y( % Write 1 into row 2^i ] % End for each 3Lt % Push [1, -1j] (corresponding to index 1:end-1) twice 3$) % Apply index. Removes last row and column Q % Add 1. Gives an array of values 1 and 2 ) % Index into initial string ``` [Answer] ## Haskell, ~~123~~ 122 bytes ``` unlines.foldr(#)["#"] n#p=zipWith(++)(r++h:t)$('#':)<$>u++h:s where b='.'<$p<$p;h='#'<$p;(r:s:t:u:_)=drop n$cycle[p,b,b,b] ``` Usage example: ``` *Main> putStr $ (unlines.foldr(#)["#"]) [2,3,1] .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... .......#....... ############### ...#...#....... ...#...#....... ...#...#....... ########....... ...#.###....... ...#####....... ...#.#.#....... ``` How it works: ``` ["#"] -- starting with "#" foldr(#) -- fold the function # from the right into the input unlines -- and join the result with newlines n#p= -- helper function # -- n: next index, p: fractal so far zipWith(++) -- join the left and right part elementwise (r++h:t) -- left part ('#':) <$> u++h:s -- right part (prepend '#' to each line for vertical -- separator -- helper b='.'<$p<$p -- b is a blank square of the same size as p h='#'<$p -- h is a line of '#' of the same length as p (r:s:t:u:_)= -- drop the first n elements of the infinite drop n$cycle[p,b,b,b] -- list [p,b,b,b,p,b,b,b,p,b,b,b,...] and -- assign the next 4 element to r,s,t,u. -- As r,s,t,u are always inserted at the -- same position in the fractal, we get the -- variants by assigning different values. ``` [Answer] ## JavaScript (ES6), ~~171~~ 152 bytes ``` ([d,...a],h=`#`,r=`replace`)=>d<4?(s=f(a)[r](/.+/g,s=>(t=s[r](/./g,`.`),d&1?t+h+s:s+h+t)),t=s[r](/.+/g,w=t+h+t),w=` ${w[r](/./g,h)} `,d&2?t+w+s:s+w+t):h ``` Takes the result of the recursive call, then replaces each line with itself plus a hash plus a string of dots of the same length, in reverse order if necessary, then from that partial result creates a string of dots except for the newlines and central column of hashes, and also a string of hashes with surrounding newlines, then joins those three strings together in the appropriate order. [Answer] # Ruby, ~~143~~ 134 bytes An anonymous function. 1 byte saved by a rearrangement of the first line. 6 bytes saved by changing the way z is incremented from a formula to a table. 2 bytes saved by eliminating varable `w`. ``` ->a{r=-1+u=2<<a.size s=(?.*r+$/)*r a<<0 z=r*u/2-1 a.each{|i|r/=2 (-r..r).each{|j|s[z+j]=s[z+j*u]=?#} z+=-r/2*[u+1,u-1,1-u,-u-1][i]} s} ``` **Ungolfed in test program** ``` f=->a{ r=w=(u=2<<a.size)-1 #w=length of line excluding newline, u=length of line including newline. s=(?.*w+$/)*w #initialize string s with w rows of w dots terminated by newlines. z=w*u/2-1 #z is the centre of the fractal a<<0 #add a dummy value to the end of a a.each{|i| #for each element in a r/=2 #r is the radius of the current iteration: ....15,7,3,1 (-r..r).each{|j| #for j=-r to r s[z+j]=s[z+j*u]=?# #overwrite . with #, forming horizontal and vertical lines } z+=-r/2*(u+1)+ #move z to centre of upper left quarter (where it should be if i=0) i%2*(q=r+1)+ #move across if i=1,3 i/2%2*q*u #and down if i=2,3 } s} #return string puts $/,f[[]] puts $/,f[[0]] puts $/,f[[3]] puts $/,f[[2,0]] puts $/,f[[1,1]] puts $/,f[[1,2,0]] puts $/,f[[3,3,1]] puts $/,f[[0,1,2,3]] puts $/,f[[0,0,1,2,3]] ``` [Answer] # Ruby, 150 bytes Anonymous function. Uses a recursive call to build a list of strings, one string per line, then joins them all together at the end. ``` ->i{f=->l{s=2**l.size-1;g=[[?.*s]*s]*4;m=->x,y{x.zip(y).map{|a,b|a+?#+b}} s<1?[?#]:(g[l.shift]=f[l];m[*g[0,2]]+[?#*(2*s+1)]+m[*g[2,2]])} f[i].join" "} ``` [Answer] # Python 3.5, 1151 bytes: Not much of a code golf, but oh well. Will try to prune it more over time where I can. ``` def x(s): y=[''];l=['#'];k=[' '] for z in s[::-1]:y.append(z) y=y[::-1] for h in range(len(y)): if y[-1]!='':u=(int(y.pop())&3) else:u=y.pop() if len(l)<2:k.append(u);p=((2**(len(k)-1))-1);l.append((('.'*p+'#'+'.'*p+'\n')*p)+'#'*((p*2)+1)+'\n'+(('.'*p+'#'+'.'*p+'\n')*p)) else: if len(l)>2:del l[0] p=((2**(len(k)-1))-1);a=[[_+i for i in range(p)]for _ in range(len(l[1]))if _%((p*2)+2)==0 and _!=(((p*2)+2)*(p))];b=[[_+i for i in range(p)]for _ in range(len(l[1]))if _%(int(((p*2)+2)/2))==0 and _!=(int(((p*2)+2)/2)*((p)*2))and _ not in[g for i in a for g in i]];W=[g for i in a[:len(a)-(int(len(a)/2)):1]for g in i];B=[g for i in b[:len(b)-(int(len(b)/2)):1]for g in i];C=[g for i in a[len(a)-(int(len(a)/2)):len(a):1]for g in i];T=[g for i in b[len(b)-(int(len(b)/2)):len(b):1]for g in i];f=list(l[1]) for i in list(''.join(l[0].split())): if u==0:f[W[0]]=i;del W[0] elif u==1:f[B[0]]=i;del B[0] elif u==2:f[C[0]]=i;del C[0] elif u==3:f[T[0]]=i;del T[0] del l[0];k.append(u);p=((2**(len(k)-1))-1);l.append(''.join(f));l.append((('.'*p+'#'+'.'*p+'\n')*p)+'#'*((p*2)+1)+'\n'+(('.'*p+'#'+'.'*p+'\n')*p)) print(l[-2]) ``` A pretty naive way to do this, but, nonetheless, currently works perfectly and, as you can see, uses **no** external modules/libraries. Additionally, it can take on *way* more than 5 items in the provided list `s` without losing any accuracy (that is, if your hardware can handle it). It satisfies all the requirements, and I could not be happier with what I got. :) It can also now not only accept any number within the range `0=>3` as any of the values, but *any number*, period, thanks to the `&` bitwise operator ! You can read more about them [here](https://wiki.python.org/moin/BitwiseOperators). Now, for instance, `[4,4,1,2,3]` as the input list is the *same* as `[0,0,1,2,3]`. **Note:** Input *must* be provided as a list # Ungolfed with explanation: ``` def x(s): # Create 3 lists: # `y` is for the values of `s` (the list provided) and an empty element for the # first pattern # `l` is reserved for the pattersn created through each item in list `y` # `k` is created for the value of `p` which is the main value through which the # pattern is created. y=[''];l=['#'];k=[' '] # Reverse s, and then add each element from `s` to `y` # (in addition to the empty element) for z in s[::-1]: y.append(z) # `y` should now equal the list created, but reversed # If not reversed, then, if, for instance, the input is `0,1,2` and list `y` # therefore contains `'',2,1,0`, the empty element will be called at the end, # which is NOT what we want. y=y[::-1] # The main loop; will be iterated through the length of `y` number of times for h in range(len(y)): # Here is where each element from the end of `y` is recieved as `u` for # use in the pattern in each iteration. # As you can also see, a bitwise operator (`&`) is used here so that # ALL numbers can be accepted. Not just those in the range `0-4`. # However, that will happen only if the value of y[-1] (the last elment in y) is # NOT ''. if y[-1]!='': u=(int(y.pop())&3) else: u=y.pop() # If the length of list `l` is less than 2 # (which means it only contains `#`), then do the following: if len(l)<2: # Append `u` to `k` k.append(u) # Use the length of `k` as `n` in the operation `(2^(n-1)-1)` to get the # length of the dot filled part of the new pattern. p=((2**(len(k)-1))-1) # Add that pattern to the list (currently empty, # i.e. containing no other pattern in any other quadrant) l.append((('.'*p+'#'+'.'*p+'\n')*p)+'#'*((p*2)+1)+'\n'+(('.'*p+'#'+'.'*p+'\n')*p)) # Now, if the length of l is >=2, do the following: else: # If the length of l is >2, then delete the first element in list `l` # (this will happen only once, when the `#` is still the first element) if len(l)>2: del l[0] # Again, use the length of `k` as `n` in the operation `(2^(n-1)-1)` # to get the length of the dot filled part of the pattern. p=((2**(len(k)-1))-1) # Create a list with all the index values of all the dot elements on the left hand # side of the grid l[-1], and the index value + i where i is every integer in # the range `0-p` (this way, it will create lists within a list, each # which contain `p` number of integers, which are all indexes of all the dots on # the very left side of the grid) a=[[_+i for i in range(p)]for _ in range(len(l[1]))if _%((p *2)+2)==0 and _!=(((p*2)+2)*(p))] # Create another list with all the index values of the dots using the same # strategy as above, but this time, those in the right half of the grid. b=[[_+i for i in range(p)]for _ in range(len(l[1]))if _%(int(((p*2)+2)/2))==0 and _!=(int(((p*2)+2)/2)*((p)*2))and _ not in[g for i in a for g in i]] # Create 4 lists, each containing index values specific to each of the # 4 quadrants of the grid. # W is the list, based on A, containing all the indexes for the 1st quadrant of # the grid in l[-1] containing dots (index 0 in the grid) W=[g for i in a[:len(a)-(int(len(a)/2)):1]for g in i] # B is the list, this time based on b, containing all indexes for the 2nd # dot-filled quadrant of the grid l[-1] (index 1 in the grid) B=[g for i in b[:len(b)-(int(len(b)/2)):1]for g in i] # C is the list, also, like W, based on a, containg all the index values for # the 3rd dot-filled quadrant of the grid in l[-1] (index 2 in the grid) C=[g for i in a[len(a)-(int(len(a)/2)):len(a):1]for g in i] # T is the final list, which, also like B, is based on b, and contains all the # index values for the final (4th) dot-filled quadrant of the grid in l[-1] T=[g for i in b[len(b)-(int(len(b)/2)):len(b):1]for g in i];f=list(l[1]) # Finally, in this `for` loop, utilize all the above lists to create the new # pattern, using the last two elements in list `l`, where each character of grid # l[-2] (the second to last element) is added to the correct index of grid l[-1] # based on the value of `u` for i in list(''.join(l[0].split())): if u==0: f[W[0]]=i del W[0] elif u==1: f[B[0]]=i del B[0] elif u==2: f[C[0]]=i del C[0] elif u==3: f[T[0]]=i del T[0] # Delete the very first element of `l`, as it is now not needed anymore del l[0] # Append `u` to list`k` at the end of the loop this time k.append(u) # Update the value of `p` with the new value of length(k) p=((2**(len(k)-1))-1) # Append the new patter created from the for-loop above to list `l` l.append(''.join(f)) # Append a new, empty pattern to list `l` for use in the next iteration l.append((('.'*p+'#'+'.'*p+'\n')*p)+'#'*((p*2)+1)+'\n'+(('.'*p+'#'+'.'*p+'\n')*p)) # When the above main loop is all finished, print out the second-to-last elment in # list `l` as the very last element is the new, empty grid created just in case # there is another iteration print(l[-2]) ``` # Broader & far more visually appealing explanation: For a broader and far more visually appealing explanation, consider the second time going through the "main"-loop in the above code, in which the input list is `[0,2]`. In this case, the elements in the "main" list `l` would be: ``` .#. ### ##. ``` and ``` ...#... ...#... ...#... ####### ...#... ...#... ...#... ``` and list `y` would only contain `0`. Taking advantage of Python's way of indexing the last element of grid `l[-1]`, we can label the very *left* elements of the grid like so: ``` 0 ...#...\n 7 8 ...#...\n 15 16 ...#...\n 23 #######\n <- Ignore this as it is nothing but `#`s and a new line 32 ...#...\n 39 40 ...#...\n 47 48 ...#...\n 55 ``` What pattern do you see? Every index on the very left of the grid is a multiple of 8, and since, using the equation `2^(n-1)-1` yields the length of each segment of dots in the grid, we can do `((2^(n-1)-1)*2)+2` to find the length of the top edge of the grid as a whole (+2 to include the middle `#`s and the `\n` at the end). We can use that equation, which we will call `i` to find the index values of each element on the left side of a grid of any size by creating a list, and appending to the list every integer, which we will call `_`, in the range `0=>length of grid l[-1]`, such that that item is a multiple of `i`, AND also such that `_` does NOT equal `i*(2^(n-1)-1)`, so that we can exclude the middle segment of `#`s separating the top half from the lower half. But we want ALL the dot elements from the left, and not only the elements on the very left side. Well, there is a fix to that, and that would be to simply append to the list a list containing `i+h` where h is every integer in the range `0=>2^(n-1)` each time a value from range `0=>length of grid l[-1]` is added to the list, so that each time, there will be as many number of values added to the list as the length of one quadrant of dots. And that is list `a`. But now, how about the dots on the right half? Well, let us look at the indexing a different way: ``` 0 ...# 4 ...\n 7 8 ...# 12 ...\n 15 16 ...# 20 ...\n 23 #######\n <- Ignore this as it is nothing but `#`s and a new line 32 ...# 36 ...\n 39 40 ...# 44 ...\n 47 48 ...# 52 ...\n 55 ^ | These are the values we are looking at now ``` As you can see, the values now in the middle are those that we need, as they are the *beginning* of the index of every segment of dots on the right hand side of the grid. Now, what is the pattern here? Well, if it's not already obvious enough, now the middle values are all multiples of `i/2`! With that information, we can now create another list, `b`, to which the multiples of `i/2` are added from the range `0=>length of grid l[-1]` such that each integer from that range, which we will again call `_`, is NOT equal to `(i/2)*(p*2)` to exclude the line of `#`s separating the top and lower halves, AND such that \_ is NOT already in list a, since we don't really need 8,16,32,etc. in list `b`. And now, again, we don't only want those specific indexes. We want ALL the dot characters on the right side of the grid. Well, just like we did in list `a`, here we can also add to list `b` lists of `_+h` where `h` is each integer in the range `0=>2^(n-1)`. Now, we have both lists `a` and `b` packed and ready to go. How would we bring these together now? This is where lists `W`, `T`, `G`, and `C` come in. They will hold the indexes to each specific quadrant of dots in grid `l[-1]`. For instance, let us reserve list `W` as the list for all the indexes equal to quadrant 1 (index 0) of the grid. In this list, we would then add the first `2^(n-1)` lists from list `a`, since list `a` contains all the indexes for dots in the left half of the grid, and then split them all up so that `W` now contains `(2^(n-1))*(2^(n-1))` elements. We would do the same for list `T`, but with the difference that `T` would contain elements from list `b`, since `T`is reserved for quadrant 2 (index 1). List `G` would be the same as list `W`, except it would contain the rest of the elements from list `a`, and list `C` is the same as list `T`, except it now contains the rest of the elements from list `b`. And, that's it! We now have out index values for *every* quadrant containing dots in the grid, all split up into four lists corresponding to each quadrant. We can now use these 4 lists (W,T,G,C) to tell the program which characters it should replace in grid `l[-1]` with each character from grid `l[0]`, which is the very first element of list `l`. Since the value is `0` here, it would replace all the dots in the first quadrant (index 0) with grid `l[0]` utilizing list `W`. Therefore, we finally have the following: ``` .#.#... ####... ##.#... ####### ...#... ...#... ...#... ``` Whew! Long process, isn't it? However, it works perfectly, and, again, I could not be happier. :) ]
[Question] [ The game of Sevens is played as follows: `n` players sit in a circle, and start counting up from 1, passing to the left (or from player `A` to player `B`). When a number `p` that has a `7` in it OR is divisible by `7` is reached, then the player who spoke the number `p-1`, after the next player says `p`, must say `p+1` and the order of people speaking reverses. For example, if player `B` speaks `6`, player `C` says `7`, `B` says `8`, and player `A` says `9`. **Note:** For those who want to play in real life, if a person forgets a number (or in the version where `sevens` are not said, accidentally says a `seven`), they are eliminated from the circle, but we will omit this detail from this challenge. The challenge itself is to print which numbers each player should say in a perfect game of Sevens up to an input `m` for an input `n` players. As an example, where five people, `A`, `B`, `C`, `D`, and `E`, are to play till they reach `30`. They play in this manner ``` A: 1 6 8 13 15 19 23 30 B: 2 7* 12 16 18 24 C: 3 11 17* 25 D: 4 10 21* 26 28* E: 5 9 14* 20 22 27*29 ``` where `sevens` are marked with `*`. Note that at `27` and `28`, we're reversing twice, and play continues "as normal" from `D` to `E`. Please note that the output does not have to be in the above format. I simply printed it that way for some clarity. **Rules** * The input is two integers in any order, `m` representing the last number to say, `n` representing the number of players. * The output can be several arrays or several strings, one for each player. If you use strings, you do not have to use separators (though, if you could add some in your code tests, we would appreciate the readability). If you can actually print them in a circle somehow, that is acceptable as well, and it would be pretty cool too. * The output does not have to designate which players are which (it's fairly obvious that the first player is the one who says `1`), though if the output isn't sorted for whatever reason, you should make clear which player is speaking which set of numbers. Omitting players who do not say anything is also allowed if you make it clear which players are speaking. I will add some more examples of possible outputs below. * This is code golf, so the smallest number of bytes wins. As always, if the problem is unclear, please let me know. Good luck and good golfing! **Examples** ``` >>> sevens_string(30, 5, " ") '1 6 8 13 15 19 23 30' '2 7 12 16 18 24' '3 11 17 25' '4 10 21 26 28' '5 9 14 20 22 27 29' >>> sevens_string(42, 5) '16813151923303539' '27121618243140' '31117253241' '410212628333742' '591420222729343638' >>> sevens_array(20, 3) [1, 4, 7, 10, 13, 15, 19] [2, 5, 9, 12, 16, 18] [3, 6, 8, 11, 14, 17, 20] >>> sevens_array(18, 10) [1, 13, 15] [2, 12, 16, 18] [3, 11, 17] [4, 10] [5, 9] [6, 8] [7] [] [] [14] ``` [Answer] # Haskell, 151 bytes ``` s n|elem '7'(show n)||mod n 7==0=(0-)|0<1=id a=scanl1(+)$map($1)$scanl(.)id$map s[1..] f m n=mapM_ print[[x+1|x<-[0..m-1],mod(a!!x-1)n==i]|i<-[0..n-1]] ``` ``` *Main> f 30 5 [1,6,8,13,15,19,23,30] [2,7,12,16,18,24] [3,11,17,25] [4,10,21,26,28] [5,9,14,20,22,27,29] ``` [Answer] # Pyth, 38 bytes ``` Jm[)EA,01VQa@JZ=hG=+Z=W|}\7`G!%G7H_H;J ``` [Try it online.](https://pyth.herokuapp.com/?code=Jm%5B)EA%2C01VQa%40JZ%3DhG%3D%2BZ%3DW%7C%7D%5C7%60G!%25G7H_H%3BJ&input=20%0A3&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=Jm%5B)EA%2C01VQa%40JZ%3DhG%3D%2BZ%3DW%7C%7D%5C7%60G!%25G7H_H%3BJ&test_suite=1&test_suite_input=30%0A5%0A42%0A5%0A20%0A3&debug=0&input_size=2) Basically a port of my Python answer; there's probably a better way. Takes as input the number to count up to `n` and the number of players `p` on separate lines, outputs the result as a two-dimensional array. [Answer] # Python 3, 155 bytes ``` from turtle import* def f(m,n,i=0,r=20,d=360): k=n while i<m:i+=1;fd(r);write(i);bk(r);e='7'[:i%7]in str(i);d*=1-2*e;k=~-e*(1-k)%n;r+=(k<1)*15;rt(d/n) ``` Uses turtle graphics to print in a circle such that numbers spoken by the same player are on the same radius. The radius of the circle is increased when the direction is reversed, or when the sequence wraps around the circle, so previous numbers aren't overwritten. Sample output for `f(22,6)` [![enter image description here](https://i.stack.imgur.com/h1wlQ.png)](https://i.stack.imgur.com/h1wlQ.png) [Answer] # Python 2, ~~103~~ ~~102~~ 101 bytes ``` def S(n,p): P=0;D=N=1;O=['']*p while n:O[P%p]+=`N`;D*=1-2*(N%7<1or'7'in`N`);N+=1;P+=D;n-=1 print O ``` Defines a function `S(n,p)` that takes the number to count to `n` and the number of players `p` and prints the result as an array of strings. ``` >>> S(42,5) ['16813151923303539', '27121618243140', '31117253241', '410212628333742','591420222729343638'] ``` [Answer] # Python 2, ~~91~~ ~~90~~ 87 bytes ``` def f(m,n):a=d=i=0;r=[()]*n;exec"i+=1;r[a%n]+=i,;d^='7'[:i%7]in`i`;a+=1-2*d;"*m;print r ``` Prints a list of tuples. Test it on [Ideone](http://ideone.com/tA8ZaV). [Answer] # Dyalog APL, ~~50~~ ~~47~~ 35 bytes ``` {,⌸⍵|+\0,¯1*+\{0=7|⍵×~7∊⍎¨⍕⍵}¨⍳⍺-1} ``` This displays the numbers each player said as a table, where the first column enumerates the players. Rows are padded with **0**s to the same length, and rows without numbers are omitted. ### Verification ``` f ← {,⌸⍵|+\0,¯1*+\{0=7|⍵×~7∊⍎¨⍕⍵}¨⍳⍺-1} 30 f 5 0 1 6 8 13 15 19 23 30 1 2 7 12 16 18 24 0 0 2 3 11 17 25 0 0 0 0 3 4 10 21 26 28 0 0 0 4 5 9 14 20 22 27 29 0 42 f 5 0 1 6 8 13 15 19 23 30 35 39 1 2 7 12 16 18 24 31 40 0 0 2 3 11 17 25 32 41 0 0 0 0 3 4 10 21 26 28 33 37 42 0 0 4 5 9 14 20 22 27 29 34 36 38 20 f 3 0 1 4 7 10 13 15 19 1 2 5 9 12 16 18 0 2 3 6 8 11 14 17 20 14 f 10 0 1 13 1 2 12 2 3 11 3 4 10 4 5 9 5 6 8 6 7 0 9 14 0 ``` Note that, in the last example, **7** and **8** are omitted since those players haven't said anything yet. [Answer] ## Ruby, 81 ``` ->n,m{g=[""]*n k=j=0 i=1 m.times{g[j%n]+=w="#{k+=1}" j+=i=k%7<1||w[/7/]?-i :i} g} ``` Pretty straightforward implementation. Returns an ugly glommed string (you can add a space to make it `"#{k+=1} "` for... well, a spaced string). I wonder if there's a more mathematical algorithm out there. [Answer] # [Factor](http://factorcode.org) 172 I managed to do it longer than Haskell, and as readable as APL! Do I get a cookie? ``` [| l! n! | 1 0 0 :> ( p! x! z! ) n iota [ 1vector ] map <circular> n! l iota [ 1 + z! z 7 mod 0 = 55 z 10 >base in? or -1 and 1 or p * p! z x n nth push x p + x! ] each n ] ``` It's a quotation (anonymous function) that outputs a circular sequence of vectors. Each vector starts with the number of player, and then the numbers that correspond to that player. ``` 30 5 [| l! n! | 1 0 0 :> ( p! x! z! ) n iota [ 1vector ] map <circular> n! l iota [ 1 + z! z 7 mod 0 = 55 z 10 >base in? or -1 and 1 or p * p! z x n nth push x p + x! ] each n ] call Outputs: T{ circular { seq { V{ 0 1 6 8 13 15 19 23 30 } V{ 1 2 7 12 16 18 24 } V{ 2 3 11 17 25 } V{ 3 4 10 21 26 28 } V{ 4 5 9 14 20 22 27 29 } } ^ Note: first val is player number starting at 0 } } ``` I started with this: ``` : game-of-7 ( last-num num-players -- {players:={numbers}} ) 1 1 set ! increment 0 2 set ! current-index iota [ drop V{ } clone ] map <circular> swap iota [ 1 + ! iotas go 0 to n-1 dup [ 7 mod 0 = ] [ 10 >base 55 swap in? ] bi or [ 1 get -1 * 1 set ] when over 2 get swap nth push 2 get 1 get + 2 set ] each ; ``` which is not good factor code, but a lot more clear (yes, I'm using numbers as variable names there, don't look at me like that!). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` D;Æf7e R’Ç€^\ḤC+\_'R}⁹ḍT€ ``` [Try it online!](http://jelly.tryitonline.net/#code=RDvDhmY3ZQpS4oCZw4figqxeXOG4pEMrXF8nUn3igbnhuI1U4oKs&input=&args=MzA+NQ) or [verify all test cases](http://jelly.tryitonline.net/#code=RDvDhmY3ZQpS4oCZw4figqxeXOG4pEMrXF8nUn3igbnhuI1U4oKsCsOnIkfigqxq4oCcwrbCtg&input=&args=MzAsIDQyLCAyMCwgMTQ+NSwgICA1LCAgMywgMTA). [Answer] # JavaScript (ES6) 100 Returning result as a string array, no separators ``` (m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r ``` Or more readable, for 3 bytes more, returning result as an array of arrays ``` (m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r ``` **Test** Using the new wonderful console feature of the Stack Snippets ``` S=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=(r[p]||'')+i})(1)||r A=(m,n)=>(d=>{for(r=[],p=i=0;i++<m;d=i%7&&!~(i+'').search(7)?d:n-d,p=(p+d)%n)r[p]=[...r[p]||[],i]})(1)||r console.log(S(42,5)) console.log(A(20,3)) ``` [Answer] # J, ~~63~~ ~~60~~ ~~59~~ ~~58~~ 56 bytes ``` 4 :'>:@I.(i.y)=/y|+/\0,_1^+/\(7 e."1 q:,.10#.inv])}.i.x' ``` ### Verification ``` f =: 4 :'>:@I.(i.y)=/y|+/\0,_1^+/\(7 e."1 q:,.10#.inv])}.i.x' 30 f 5 1 6 8 13 15 19 23 30 2 7 12 16 18 24 0 0 3 11 17 25 0 0 0 0 4 10 21 26 28 0 0 0 5 9 14 20 22 27 29 0 42 f 5 1 6 8 13 15 19 23 30 35 39 2 7 12 16 18 24 31 40 0 0 3 11 17 25 32 41 0 0 0 0 4 10 21 26 28 33 37 42 0 0 5 9 14 20 22 27 29 34 36 38 20 f 3 1 4 7 10 13 15 19 2 5 9 12 16 18 0 3 6 8 11 14 17 20 14 f 10 1 13 2 12 3 11 4 10 5 9 6 8 7 0 0 0 0 0 14 0 ``` ]
[Question] [ We are given a list of integers p1, ..., pk (not necessarily distinct) where each has a value between 1 and 9, inclusive. Using each of the p1, ..., pk exactly once, we can form concatenations of digits, to achieve a new list of numbers; we then output the product of this new list. The goal is to maximize this product by choosing the best concatenations of digits. For example, we are given the list: 2 3 2 (separated by spaces). We can form the following concatenations: * `2 3 2` (product of these concatenations is `12`) * `23 2` (product is `46`) * `32 2` (product is `64`) * `22 3` (product is `66`) Since the largest product that we can form of concatenations is 66, we output that. Rules: * There must be at least one multiplication (i.e., you cannot just concatenate all of the digits and output that). * You cannot use any other operators other than multiplication, or insert parentheses, etc. * Assume that the list of integers given is separated by spaces, and all integers have values between 1 and 9. Shortest code (in bytes) wins! Test cases: Input: `1 2 3`; Output: `63` (i.e., `21*3`) Input: `2 5 9`; Output: `468` (`52*9`) Input: `1 2 3 4`; Output: `1312` (`41*32`) [Answer] # CJam, ~~32~~ ~~28~~ ~~23~~ 12 bytes ``` 0le!f{~*}:e> ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0le!f%7B~*%7D%3Ae%3E&input=1%202%203%204). *Thanks to @user23013 for helping me save 16 whole bytes!* # Idea Permuting the characters in the input string divides it into integers (groups of consecutive digits) separated by spaces. By pushing a zero and then evaluating the permuted input string, we push two or more integers. Multiplying the topmost two will result either in the product of the input divided into exactly two integers or some suboptimal value. # Code ``` le! e# Push all possible character permutations of the input. 0 f{ } e# For each permutation: e# Push 0, then the permuted string. ~ e# Evaluate the string. Pushes one or more integers. * e# Multiply the two topmost integers. :e> e# Retrieve the greatest integer in the array. ``` [Answer] # CJam, ~~36~~ 35 bytes ``` q~]_,([SL]m*{s},\e!\m*{z[s~]:*}%$W= ``` Pretty straight forward. Iterates over all possible combinations and sorts them by product. Then outputs the largest. All this, keeping in mind that at least 1 multiplication should be present. Will add explanation soon. [Try it online here](http://cjam.aditsu.net/#code=q~%5D_%2C(%5BSL%5Dm*%7Bs%7D%2C%5Ce!%5Cm*%7Bz%5Bs~%5D%3A*%7D%25%24W%3D&input=2%203%202) [Answer] # JavaScript (ES6) 125 **Edit** I think @oberon got it right : "each new digit must be concatenated to the smallest number" I'll not change this answer stealing his idea. Implementation in ES6 would be 70 bytes (sign changed in comparison to compare as number and not strings) ``` f=l=>l.split(' ').sort().reverse().map(d=>-a>-b?a+=d:b+=d,a=b='')||a*b ``` **My solution** ``` f=l=>(i=>{for(r=0;a=b='',k=--i;r<a*b?r=a*b:0)for(v of l)k&1?a+=v:b+=v,k/=2})(1<<~-(l=l.split(' ').sort().reverse()).length)|r ``` As I said in comments, for each pair of numbers a,b, the product a\*b is less than the simple concatenation ab (=a\*10^(digits of b)+b). So it's better to avoid products and prefer concatenation, but as at least 1 product is requested, we have to build 2 numbers and multiply them. I try all possible grouping of digits, building a pair of numbers to multiply. Each number is obviosuly built taking digits in decreasing order. For instance, with a list of 4 numbers, [1 2 3 4] - try: * 4 \* 321 * 43 \* 21 * 42 \* 31 * 41 \* 32 * 432 \* 1 * 431 \* 2 * 421 \* 3 The max of these value is the result we need. The groupings can be enumerated looping on a bitmap of 4 bits, with min value 0001 and max value 0111 (that is 1<<(4 -1) - 1) **Not so golfed** ``` f=l=>{ l = l.split(' '); // string to array l.sort().reverse(); // decreasing order m = 1 << (l.length-1); starting value fro loop r = 0 // loop from m-1 down to 1 for(i=m; --i; ) { a = b = ''; k = i; for(v of l) // divide the digits base on bits of i { k & 1 ? a+=v : b+=v; k /= 2; } if (r < a*b) r = a*b; // remember max value in r } return r } ``` Test using the snippet below in Firefox. ``` f=l=>(i=>{for(r=0;a=b='',k=--i;r<a*b?r=a*b:0)for(v of l)k&1?a+=v:b+=v,k/=2})(1<<~-(l=l.split(' ').sort().reverse()).length)|r t=l=>(i=>{for(x=r='';a=b='',k=--i;r<a*b?(r=a*b,x=' = '+a+'x'+b):0)for(v of l)k&1?a+=v:b+=v,k/=2}) (1<<~-(l=l.split(' ').sort().reverse()).length)|| x function go() { R.value = f(I.value) // TEST AS IS + t(I.value) // Some more info } test=['1 2 3 4','1 2 3','2 5 9','8 9 8'] test.forEach(t => O.innerHTML = O.innerHTML + (t + ' -> ' + f(t)) + '\n') ``` ``` Type your list: <input id=I><button onclick='go()'>-></button><input readonly id=R><br> <pre id=O></pre> ``` [Answer] # Python 3, 111 bytes It's probably much more golfable. I like its running time, though (O(*n* log *n*), is it?). ``` l=sorted(map(int,input().split()),reverse=1);m=[0,0] for x in l:i=m[0]>m[1];m[i]=m[i]*10+x print(m[0]*m[1]) ``` Ungolfed with explanation. ``` # edc65 has already explained that the optimal solution can be found applying a single # multiplication. thus, given that # (10x + d)y > (10y + d)x # where x, y are the two numbers and d is the next digit to insert, it follows that # y > x # and thus each new digit must be concatenated to the smallest number. obviously, digits # should be added in descending order. l = sorted(map(int, input().split()), reverse=1) m = [0,0] for x in l: i = m[0] > m[1] m[i] = m[i]*10 + x print(m[0] * m[1]) ``` [Answer] # Pyth, 25 bytes ``` eSsmm*ss<dkss>dkr1ld.pcz) ``` I loop over every permutation of the input. Then because every optimal combination consists of two integers I merely split it at every possible position, and multiply the concatenated splits. I then sort and get the last element. [Answer] # R, 164 ``` function(n){l=length(n);a=sort(n,T);i=1;while(a[i]==a[i+1]&&i<l-2)i=i+2;a[c(i,i+1)]=a[c(i+1,i)];eval(parse(t=paste0(c(a[1:l%%2==1],"*",a[1:l%%2==0]),collapse='')))} ``` As a method I'm unsure if this is robust. With the cases that I have tested it appears to work each time. I tried testing it against optimizers solution and it appears to be OK against that as well. I'm more than prepared to be proven wrong :) There's room for golfing, but I was hoping to get some feedback on the method first. The general process is : * Sort the list in descending order * Swap the first odd/even pair that differ * Concatenate the even and odd items of the list * Evaluate the product of the two results Expanded out with some comments ``` function(n){ l=length(n); a=sort(n,T); # sort descending order # Determine which pair to swap i=1; while(a[i]==a[i+1]&&i<l-2)i=i+2; a[c(i,i+1)]=a[c(i+1,i)]; # swap pair # concatenate the even and odd indices items around a * and evaluate eval(parse(t=paste0(c(a[1:l%%2==1],"*",a[1:l%%2==0]),collapse=''))) } ``` And some test runs (implemented as a function called g) ``` > g(c(1,2,3)) [1] 63 > g(c(2,5,9)) [1] 468 > g(c(1,2,3,4)) [1] 1312 > g(c(1,2,3,5,5,5)) [1] 293132 > g(c(1,5,7,7,9,9)) [1] 946725 > g(c(1,7,8,9,9,9)) [1] 978117 > g(c(7,8,9,9,9)) #Test case provided edc65 to randomra [1] 97713 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Œ!ŒṖ€Ṗ€ẎḌP€Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWjkx7unPaoaQ2U3NX3cEdPAJjf8P9wO5Dx/3@0kY6xjlGsTrShDpAFpI10THUsYXwdk1gA "Jelly – Try It Online") ಠ\_ಠ Tied with CJam. Takes input as a list of values, [+2 bytes](https://tio.run/##y0rNyan8///hjk1hRycpHp30cOe0R01roOSuvoc7egLA/Ib/h9uBjP//lYwUjBWMlHQUlAwVgEwQw0jBVMESLqJgogQA) to input as space-separated ## How it works ``` Œ!ŒṖ€Ṗ€ẎḌP€Ṁ - Main link. Takes a list L on the left Œ! - Permutations of L ŒṖ€ - Partitions of each Ṗ€ - Remove the last one from each Ẏ - Join into one list Ḍ - Convert from digits to numbers P€ - Product of each Ṁ - Maximum ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ä;ªÜé▐ßó ``` [Run and debug it](https://staxlang.xyz/#p=843ba69a82dee1a2&i=%222+3+2%22%0A%221+2+3%22%0A%222+5+9%22%0A%221+2+3+4%22&m=2) Uncompressed is 9 bytes, still beating CJam(with the same method). ## Explanation ``` |T{Ze*m|M |T permutations of input { m mapped to: Z tuck a zero under the string e evaluate the string * multiply the top two elements |M get the maximum of the mapped list ``` ]
[Question] [ Write a program that outputs the total number of characters and the frequency of each character in its source *and* its output. You must follow the format illustrated in the example. ## Example If your code was ``` abb1 ``` Its output would have to be ``` My source has 4 characters. 1 is "a" 2 are "b" 1 is "1" Besides unquoted numbers, my output has 383 characters. 34 are " " 79 are " " 63 are """ 2 are "'" 2 are "," 4 are "." 2 are "1" 2 are "B" 2 are "I" 2 are "M" 39 are "a" 4 are "b" 6 are "c" 4 are "d" 38 are "e" 3 are "g" 5 are "h" 4 are "i" 4 are "m" 3 are "n" 8 are "o" 3 are "p" 2 are "q" 38 are "r" 12 are "s" 8 are "t" 7 are "u" 3 are "y" It's good to be a program. ``` (Output must go to stdout.) Notice, for example, that the output contains two capitalized m's. One for `My` and one for `2 are "M"`. This must hold true for all characters so the output does not contradict itself in any way. Unquoted numbers are ignored in the output to avoid unsatisfiable frequency sets. For example, `1 is "1"` is incorrect if both 1's are counted. It should read `2 are "1"`, but then there is only one 1 again. ## Format Clarifications * "is" must be used for single character occurrences. * "are" must be used for multiple character occurrences. * "is" should never appear in the list of output characters because it would be superfluous. `1 is 'Z'` refers to the Z in itself, so the entire line can be removed. * The three full-sentence phrases must appear in order with the character frequency lists in between (as the example shows). So your output will start with `My source...` and end with `...be a program.`. Note that there is no newline at the end of the output. * The character frequency lists themselves may be in any order. * Newlines count as one character (in case they are \r\n). ## Format Checker The following Python script takes your code and its output as strings and asserts that the output has no contradictions. It provides a useful error message if something is wrong. You can run it online at <http://ideone.com/6H0ldu> by forking it, replacing the CODE and OUTPUT strings, then running it. It will never give false positives or negatives (assuming its error free). ``` #Change the CODE and OUTPUT strings to test your program CODE = r'''abb1''' OUTPUT = r'''My source has 4 characters. 1 is "a" 2 are "b" 1 is "1" Besides unquoted numbers, my output has 383 characters. 34 are " " 79 are " " 63 are """ 2 are "'" 2 are "," 4 are "." 2 are "1" 2 are "B" 2 are "I" 2 are "M" 39 are "a" 4 are "b" 6 are "c" 4 are "d" 38 are "e" 3 are "g" 5 are "h" 4 are "i" 4 are "m" 3 are "n" 8 are "o" 3 are "p" 2 are "q" 38 are "r" 12 are "s" 8 are "t" 7 are "u" 3 are "y" It's good to be a program.''' ####################################################### import re amountPattern = r'(\d+) (is|are) "(.)"\n' class IntrospectionException(Exception): pass def getClaimedAmounts(string, errorOnIs): groups = re.findall(amountPattern, string, re.DOTALL) for amount, verb, char in groups: if verb == 'is': if errorOnIs: raise IntrospectionException('\'1 is "%s"\' is unnecessary' % char) elif amount != '1': raise IntrospectionException('At "%s", %s must use "are"' % (char, amount)) elif verb == 'are' and amount == '1': raise IntrospectionException('At "%s", 1 must use "is"' % char) amounts = {} for amount, verb, char in groups: if char in amounts: raise IntrospectionException('Duplicate "%s" found' % char) amounts[char] = int(amount) return amounts def getActualAmounts(string): amounts = {} for char in string: if char in amounts: amounts[char] += 1 else: amounts[char] = 1 return amounts def compareAmounts(claimed, actual): for char in actual: if char not in claimed: raise IntrospectionException('The amounts list is missing "%s"' % char) for char in actual: #loop separately so missing character errors are all found first if claimed[char] != actual[char]: raise IntrospectionException('The amount of "%s" characters is %d, not %d' % (char, actual[char], claimed[char])) if claimed != actual: raise IntrospectionException('The amounts are somehow incorrect') def isCorrect(code, output): p1 = r'^My source has (\d+) characters\.\n' p2 = r'Besides unquoted numbers, my output has (\d+) characters\.\n' p3 = r"It's good to be a program\.$" p4 = '%s(%s)*%s(%s)*%s' % (p1, amountPattern, p2, amountPattern, p3) for p in [p1, p2, p3, p4]: if re.search(p, output, re.DOTALL) == None: raise IntrospectionException('Did not match the regex "%s"' % p) claimedCodeSize = int(re.search(p1, output).groups()[0]) actualCodeSize = len(code) if claimedCodeSize != actualCodeSize: raise IntrospectionException('The code length is %d, not %d' % (actualCodeSize, claimedCodeSize)) filteredOutput = re.sub(r'([^"])\d+([^"])', r'\1\2', output) claimedOutputSize = int(re.search(p2, output).groups()[0]) actualOutputSize = len(filteredOutput) if claimedOutputSize != actualOutputSize: raise IntrospectionException('The output length (excluding unquoted numbers) is %d, not %d' % (actualOutputSize, claimedOutputSize)) splitIndex = re.search(p2, output).start() claimedCodeAmounts = getClaimedAmounts(output[:splitIndex], False) actualCodeAmounts = getActualAmounts(code) compareAmounts(claimedCodeAmounts, actualCodeAmounts) claimedOutputAmounts = getClaimedAmounts(output[splitIndex:], True) actualOutputAmounts = getActualAmounts(filteredOutput) compareAmounts(claimedOutputAmounts, actualOutputAmounts) def checkCorrectness(): try: isCorrect(CODE, OUTPUT) print 'Everything is correct!' except IntrospectionException as e: print 'Failed: %s.' % e checkCorrectness() ``` ## Scoring This is code-golf. The submission with the fewest characters wins. Submissions must pass the format checker to be valid. Standard loopholes apply, *though you may read your own source code and/or hardcode your output*. [Answer] ## Ruby, 269 (311, 367) characters I have three different solutions for this challenge. Each of them uses a different set of tricks: **"Proper" solution, 367 characters:** The longest solution is more or less just a proof of concept that it's possible to solve this challenge without any tricks - and is not nearly fully golfed. It's a true quine (i.e. it generates its own source code instead of reading it from a file) and actually calculates all the numbers it prints (code length, output length, character occurences). Due to the way the quine works, all the code has to be on a single line and inside a string literal. ``` eval r="S='eval r=%p'%r;O=-~$.;q=\"My source has \#{S.size}\"+(X=' characters.\n')+S.chars.uniq.map{|c|[k=S.count(c),k>O ? :are: :is,?\"+c+?\"]*' '}*$/+'\nBesides unquoted numbers, my output has ';r=(w=q+X+s=\"It's good to be a program.\").scan(D=/\\D/).uniq;$><<q<<(w+v=r.map{|c|j=' are \"\n\"';(-~(w+j*r.size).count(c)).to_s+(j[~O]=c;j)}*$/+$/).scan(D).size<<X+v+s" ``` **Partially hardcoded output, 311 characters:** The next shortest solution uses two tricks, but is still a true quine: - No character occurs exactly once in the source code. That way, I don't need to decide whether I should print `is` or `are` in the first half of the output. It also makes it a bit easier to calculate the total output size (though I don't actually need to do that). - The total output size is hardcoded. Since this only depends on the number of distinct characters in the source code (and in the general case, how many of those characters occur only once), it's easily to calculate it in advance. Note that the code is preceeded by two very significant newlines, which StackExchange wouldn't show in the code block. For that reason, I have added an additional line in front if those newlines, which is *not* part of the code. ``` # eval R="I=$/+$/+'eval R=%p'%R;?\\4>w='%d are \"%s\"';B=\"My source has \#{I.size}\#{X=\" characters.\n\"}\#{z=(m=I.chars.uniq).map{|x|w%[I.count(x),x]}*$/}\nBesides unquoted numbers, my output has 1114\"+X;$><<B+m.map{|c|w%[(B+z+$M=\"\nIt's good to be a program.\").gsub!(/\\d++(?!\")/,'').count(c),c]}*$/+$M" ``` **Shortest solution, 269 characters:** The shortest solution additionally hardcodes its own source length. By using variable names that are/aren't already part of the source code, it's possible to find a "fixpoint" where all characters in the source code (including the digits from the hardcoded lengths!) occur at least twice. This solution also saves a few more characters by simply reading its own source code from the code file, instead of generating it. As a nice side effect, this makes the code much more "readable" (but who cares about readable code in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ...), as now the code doesn't have to be inside a string literal anymore. ``` U='%d are "%s"' O=IO.read$0 ?\126>B="My source has 269#{X=" characters. "}#{z=(m=O.chars.uniq).map{|c|U%[O.count(c),c]}*$/} Besides unquoted numbers, my output has 1096"+X $><<B+m.map{|c|U%[(B+z+$M=" It's good to be a program.").gsub!(/\d++(?!")/,"").count(c),c]}*$/+$M ``` --- I also modified the test script a little bit to reduce the copy-pasting necessary to check the code. By replacing the definitions of `CODE` and `OUTPUT` with ``` import subprocess CODE = open("packed.rb").read() OUTPUT = subprocess.check_output(["ruby", "packed.rb"]) print CODE print len(CODE) ``` the script now automatically runs my code, reads its output, and grabs the source code from the code file. --- Here's the output generated by the shortest code: ``` My source has 269 characters. 3 are "U" 7 are "=" 3 are "'" 4 are "%" 6 are "d" 17 are " " 11 are "a" 9 are "r" 9 are "e" 11 are """ 11 are "s" 6 are " " 4 are "O" 2 are "I" 10 are "." 6 are "$" 2 are "0" 2 are "?" 2 are "\" 2 are "1" 2 are "2" 3 are "6" 2 are ">" 4 are "B" 3 are "M" 2 are "y" 9 are "o" 10 are "u" 12 are "c" 4 are "h" 2 are "9" 2 are "#" 4 are "{" 2 are "X" 8 are "t" 4 are "}" 2 are "z" 6 are "(" 7 are "m" 5 are "n" 2 are "i" 2 are "q" 6 are ")" 4 are "p" 4 are "|" 2 are "[" 4 are "," 2 are "]" 2 are "*" 4 are "/" 3 are "b" 7 are "+" 2 are "<" 3 are "g" 2 are "!" Besides unquoted numbers, my output has 1096 characters. 2 are "U" 2 are "=" 3 are "'" 2 are "%" 5 are "d" 238 are " " 120 are "a" 120 are "r" 120 are "e" 222 are """ 11 are "s" 114 are " " 2 are "O" 3 are "I" 5 are "." 2 are "$" 2 are "0" 2 are "?" 2 are "\" 2 are "1" 2 are "2" 2 are "6" 2 are ">" 3 are "B" 3 are "M" 4 are "y" 9 are "o" 8 are "u" 7 are "c" 6 are "h" 2 are "9" 2 are "#" 2 are "{" 2 are "X" 9 are "t" 2 are "}" 2 are "z" 2 are "(" 5 are "m" 4 are "n" 3 are "i" 3 are "q" 2 are ")" 4 are "p" 2 are "|" 2 are "[" 3 are "," 2 are "]" 2 are "*" 2 are "/" 4 are "b" 2 are "+" 2 are "<" 4 are "g" 2 are "!" It's good to be a program. ``` [Answer] # CJam - 189 ``` {`"_~"+:T;"Besides unquoted numbers, my output has &It's good to be a program.&My source has & characters. "'&/~_]:X2=T,X3=3i({T_&:B{TI/,(" are ":AM`I*N}fIXK=]o XBA`N+f+2*+s:T,X3=}fK'q];}_~ ``` Try it at <http://cjam.aditsu.net/> Output: ``` My source has 189 characters. 3 are "{" 3 are "`" 6 are """ 4 are "_" 3 are "~" 4 are "+" 5 are ":" 5 are "T" 2 are ";" 3 are "B" 8 are "e" 9 are "s" 2 are "i" 3 are "d" 17 are " " 6 are "u" 2 are "n" 2 are "q" 8 are "o" 6 are "t" 3 are "m" 2 are "b" 7 are "r" 4 are "," 2 are "y" 2 are "p" 3 are "h" 7 are "a" 5 are "&" 4 are "I" 3 are "'" 2 are "g" 2 are "." 2 are "M" 3 are "c" 2 are " " 2 are "/" 3 are "]" 5 are "X" 2 are "2" 4 are "=" 3 are "3" 2 are "(" 2 are "A" 2 are "*" 2 are "N" 3 are "}" 3 are "f" 2 are "K" Besides unquoted numbers, my output has 988 characters. 3 are "B" 108 are "e" 11 are "s" 3 are "i" 5 are "d" 214 are " " 8 are "u" 4 are "n" 3 are "q" 9 are "o" 9 are "t" 5 are "m" 4 are "b" 108 are "r" 3 are "," 4 are "y" 4 are "p" 6 are "h" 108 are "a" 3 are "I" 3 are "'" 4 are "g" 5 are "." 3 are "M" 7 are "c" 102 are " " 2 are "{" 198 are """ 2 are "`" 2 are "_" 2 are "~" 2 are "+" 2 are ":" 2 are "T" 2 are ";" 2 are "&" 2 are "/" 2 are "]" 2 are "X" 2 are "2" 2 are "=" 2 are "3" 2 are "(" 2 are "A" 2 are "*" 2 are "N" 2 are "}" 2 are "f" 2 are "K" It's good to be a program. ``` ]
[Question] [ Post an answer to this question that evaluates any answer to this question and determines whether it wins. **Who wins:** * Winner is the answer that wins according to the most answers at 1700 UTC, Sunday, March 2nd. * You are welcome to and encouraged to change your own answer as the contest progresses. Please do not change others'. * Ties are determined by the shortest code. * Regardless of how much sockpuppeting you might normally do, if something's fishy, I'm gonna disqualify you. * I will not accept my own answer, but I will use it to evaluate yours. **Rules:** * Your calculation must provide a numeric score for any arbitrary answer (to make it easy, the input to your algorithm is either the id of the answer or the markdown of the answer on the page). * Your score must have at least one winner, and it must be possible for an answer besides yours to win. * Your algorithm cannot use something very specific to your answer, nor can username or timestamps be used at all. I will be the final judge of what "very specific" means, but I encourage community policing and public shaming. * Your code must compile, run, and give a score given any answer. * Please include a link to a way to execute your code if it is not listed on [Ideone](http://ideone.com). See below. ![Ideone languages](https://i.stack.imgur.com/8qbMC.png) [Answer] ## R, 1 char ``` 1 ``` You can supply the id of an answer as a command line argument if you wish. :) [Link](http://ideone.com/4szRz1) to ideone. ## Further elaboration Since it is not practical for an answers to execute other answers (different languages, etc.) and evaluate them based on their result the only remaining way I can see for them to give a score is to use some code metric. I have noticed that all other answers so far give a higher score to shorter programs. I believe this is the shortest code possible so it should rank high in the result of other answers. How and what answer my code gives for other answers seams to be less relevant. The only important aspect is that others rank my answer high. [Answer] # R, 1 char ``` 0 ``` Following up on @Andris's answer, there are now two codes that have a single character: Andris's and mine. Since we tie in the eyes of the other answers, neither of us have "won" outright, so my answer won't "win". :-) [Answer] ## Ruby, 368 char ``` require 'json' require 'open-uri' v='body';w="#{v}_markdown";s='comments' x=if(d=JSON.parse(open("http://api.stackexchange.com/2.2/answers/#{ARGV[0]}?site=codegolf&filter=!%29r%28UkmOhmCPjXru-TDty").read)['items'][0]).include?(s) then d[s].map{|c|c[w].length*[1,c[w].index('`')||1,c[w].index('\n')||1].max}.reduce(:+) else -2 end puts d['score']*150+5*(d[v].match(/<(..).*?\1.*?\1/m))[0].ord+x-$~.end(0) ``` Good luck! [Answer] ## JavaScript- 190 char Assumption: The first code block is the answer. ``` var ans=$('.answer'),s=999,sa; for(i=0;i<ans.length;i++){ var x = ans[i].getElementsByTagName('code'); var z = x[0].innerHTML.replace(/\s/g,'').length; if(s>z){ s=z; sa=ans[i]; } } console.log(sa); ``` Can be tested in browser console. It assumes the shortest answer to be the correct answer. How to execute- On Chrome/Firefox open console while on this page and paste code and execute. ]
[Question] [ ## The challenge Given a bagatelle board like the one below: ``` | | | /\ / | | \ /| | \ \ /\ \ | | \ / \ | |\ / / \ | | \ / \ | | \ | | \ / \ /\ \ | |\ / / \ /| | / | | /\ / / | | / | |\ / / / | | | ---------------------- ``` your task is to turn a list of 'throws' into a score. The board will always be 20 characters (plus 2 edges) wide, but of variable height. Each 'throw' is a number representing where the ball falls into the board, starting at 0 for the far left up to 19 for the far right. Each ball will fall straight down unless it encounters a `/` or a `\`. Encountering a `/` shifts the ball one column to the left, and a `\` shifts the ball one column to the right. After being shifted, the ball continues straight down as before. The score for a throw is dependant on where the ball hits the bottom of the board. The scores for each finishing position are as follows: ``` | | ---------------------- 01234567899876543210 ``` and are the same for all boards. The first and last rows will always be empty. The ball is guaranteed to reach the bottom regardless of where it is dropped from, so there will be no boards where it can get trapped by `\/`,`\|` or `|/` combinations. ## Input Input will be on STDIN, and will consist of the board followed by a blank line followed by a space separated list of numbers representing the throws. ## Output Ouput should be the total score for the given game. ## A couple of examples **Input** ``` | | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \ | | | | | ---------------------- 1 4 2 19 0 2 4 3 17 13 16 ``` **Output** ``` 9 ``` **Input** ``` | | | \ / | | \ / | | \ / | | \ / | | \ / | | \ / | | \ / | | \ / | | | | | | | | | | | | | | | | | | | | | ---------------------- 15 10 3 8 18 19 0 6 7 10 ``` **Output** ``` 72 ``` **Input** ``` | | | ////////////////// | | \\\\\\\\\\\\\\\\\\ | | ////////////////// | | \\\\\\\\\\\\\\\\\\ | | ////////////////// | | \\\\\\\\\\\\\\\\\\ | | ////////////////// | | \\\\\\\\\\\\\\\\\\ | | ////////////////// | | \\\\\\\\\\\\\\\\\\ | | | ---------------------- 1 4 18 17 14 2 0 19 15 ``` **Output** ``` 18 ``` ## Test scripts I've used some test scripts written by [Joey](https://codegolf.stackexchange.com/users/15/joey) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero) (I hope they don't mind...) to create some tests for this task:- * [Bash](http://www.garethrogers.net/tests/bagatelle/test) * [PowerShell](http://www.garethrogers.net/tests/bagatelle/test.ps1) Usage: `./test [your program and its arguments]` This is codegolf - shortest solution wins. [Answer] ## Python 2, 147 132 130 chars ``` import sys s=0 l=list(sys.stdin) for t in l[-1].split(): p=int(t)+1 for r in l[:-3]:p-=" /".find(r[p]) s+=min(p-1,20-p) print s ``` [Answer] ## GolfScript, 60 59 chars ``` n/{},)\);{1>:x,,{.x=31%4%(+}%}%[10,.-1%+]+0@[~]{2${=}/+}/\; ``` I was so tempted to write a solution which works by redefining the symbols `/`, `\`, and `space`, but it's actually quite expensive (especially once you can no longer use the original `\`). `31%4%(` is nicked from Keith Randall's solution and maps the ASCII codes for `space`, `/`, and `\` to `0`, `-1`, `1` respectively. (See edit history). [Answer] ## Python, 165 159 chars ``` import sys A=list(sys.stdin) C=range(10) C+=C[::-1] for L in A[-4::-1]:C=[C[i+ord(L[i+1])%31%4-1]for i in range(20)] print sum(C[int(x)]for x in A[-1].split()) ``` It starts with a row of scores and works its way from the bottom up, computing what the scores would be for balls starting at each row. [Answer] ## Ruby, 123 117 115 107 99 98 97 ``` *b,_,_,n=*$< p eval n.split.map{|k|i=k.to_i+1 b.map{|l|i-='\ /'.index(l[i])-1} [i-1,20-i].min}*?+ ``` ]
[Question] [ An integer \$x\in[0,2^{32}-1]\$ divided by an integer \$d\in{[1,2^{31}]}\$ will produce an integral quotient \$q\$ and a remainder \$r\$, so that \$x=d\times q+r\$. Any \$q\$, in fact, can be calculated by the following formula. $$y=\left\lfloor\frac{mx}{2^{32}}\right\rfloor\\q=\left\lfloor\frac{y+f\lfloor(x-y)/2\rfloor}{2^s}\right\rfloor$$ where $$m,s,f\in Integer\\m\in[2,2^{32}]\\s\in[0,31]\\f\in\{0,1\}$$ The formula can be rewritten with bitwise operators, to be more friendly with computers. $$y=mx\gg32\\q=y+(x-y\gg1\ \&\ {-f})\gg s$$ Given \$d\$, produce a valid tuple \$(m,s,f)\$, so that applying the formula above will compute the correct value of \$q\$ for all \$x\$. There may be multiple valid solutions, in which case you can output any number of any valid solution. --- ### Test Cases ``` (d -> m, s, f) 1 -> 4294967296, 0, 0 2 -> 2147483648, 0, 0 3 -> 2863311531, 1, 0 7 -> 613566757, 2, 1 11 -> 3123612579, 3, 0 111 -> 657787785, 6, 1 1111 -> 989659431, 8, 0 11111 -> 2038283013, 13, 1 1111111111 -> 2075258709, 29, 0 2147483647 -> 3, 30, 1 2147483648 -> 2, 0, 0 ``` Each of the listed output is not the only possible solution. For example, both of these are correct. ``` 1111111111 -> 2075258709, 29, 0 1111111111 -> 4150517417, 30, 0 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 271 bytes ``` lambda d,P=2**32:[s:=min(range(32),key=lambda n:abs(ceil((P<<n)/d)*d-(P<<n))),m:=ceil((P<<s)/d),0]*(1<m<=P and m*d>>(32+s))or[s:=min([n for n in range(32)if 1<2**(33+n)/d-P<=P],key=lambda n:abs(ceil(2**(33+n)/d)*d-(2*P<<n))),m:=floor(2**(33+s)/d+1)-P,1] from math import* ``` [Try it online!](https://tio.run/##dY7LboMwFET3/oorZWM7FzXGJKEI8g3sUxZODA1qbCObRfP1FOfVqFIX9yHNaOYMl/HkrMwHP3XVx3RW5qAVaKyrlHOZFvtQVKa31Cv72VKZMvxqL9XdZgt1CPTY9mdK67K07E0zrpPbzxiaonqKIYq4ajgVpSmrGpTVYLje7ebUZWDM@UfX3kLnPFjoLTx7@w5EOTNRKZexKKnnkOYfmhffFSjlL0jd2Tn/sESspWBJjaIhnXcGjBpP0JvB@ZFPC3Bet76AgGAQOhLBjiq0kW0vkKRIJMICZCJWBbTfo1cwtmG8mgLJkKyRbJBskeRI3pGI1Twizm3d9@Pc/1Rk2yyXm2wTw//E/qrbF2feFDD43o60o9HF2PQD "Python 3.8 (pre-release) – Try It Online") Probably severely golfable. Returns a list of three elements in the order `[s, m, f]`. [Here](https://tio.run/##dVLBTuMwEL3nK560EthuQklSLShKekKccy8VStcOWNR2ZLuw@fquYzYBgbjNzHsz783Yw@ifjS5vB3vum4fzsVMH3oGnbVMwVhbVzlWNkprYTj8JUhY0fRFj85@mq@7gyB8hj4S0da3pmlPGs/eY0lRVzQK6CUyv94zktaqbFp3mUIxvt2HqylFq7Ky10@iNhYbUWHRlj7wOnkhZriahrA1D9j@4@cSLhgr2yVJ/NMbOlMnWKqdZm@b7pLdGQXX@GVINxnp2/lpBbE646MHlq@Ti8U2GA57845Q6aTR5r2ueRoYzllYJdi6FSnG/R4OezECCccqjn7kNDAprkAKMIewdSFb4k9Ug44qQhZeNdLvN6UV2T0PgkuQX7iIE/2agT@ogrMOTfBXxjlIPJ4/OoUMbnxyzYYi/gxUuhsv09WJx922faYc4jtArNxylJ5frS5oMVmpPfrrKB6bDN8CcThKUnot8c7O5LX9vbsLqH8k/) is a calculator that uses my function. You input a Python division expression (`dividend/divisor`), and it uses my function to return a quotient without directly dividing the dividend by the divisor. Thanks @pxeger for suggesting the use of bitwise operators (`2**(32+s)` -> `P<<s`) in some places, which saves ten bytes. ## Explanation The problem can be solved by comparing the "magic quotient" expression to the actual quotient. Since `f` is either zero or one, we can split the problem into two parts. If f is zero, then the "magic quotient" expression becomes: $$\left\lfloor \frac{y}{2^s} \right\rfloor = \left\lfloor \frac{\left\lfloor \frac{mx}{2^{32}} \right\rfloor}{2^s} \right\rfloor$$ We can ignore the floor functions so that the problem becomes one of approximation rather than complete accuracy. Then, the magic quotient becomes: $$\frac{mx}{2^{32+s}}$$ What we want to do is find \$m\$ and \$s\$ such that the value above most closely approximates \$\frac{x}{d}\$. We want $$\frac{mx}{2^{32+s}} \approx \frac{x}{d} \implies mdx \approx x2^{32+s} \implies md \approx 2^{32+s}$$ This problem is a lot easier to solve than the daunting task of dealing with floors and correcting errors, or, even worse, dealing with those pesky fractions. In fact, this part is very simple. We can just loop through the 32 possible values of \$s\$ and find the one with the lowest $$\left\lceil \frac{2^{32+s}}{d} \right\rceil \times d - 2^{32+s}$$ We use the ceiling, and not the floor, because later on we use the floor to compute the quotient, and the ceiling allows us to get a more precise value. The above expression is evaluated for each \$s\$ from 0 to 31, and the \$s\$ for which that expression is the lowest is the one that is to be outputted (or is at least considered for output). Next, we evaluate \$m\$, which is the ceiling expression above. Then \$f\$ is zero (assumed above). Now, of course, \$f\$ cannot always be zero, so some checks are done to determine whether or not \$f = 0\$ in fact works. \$f = 0\$ works if: * \$m\$ is within the required range; and * the magic quotient of \$d\$ by \$d\$ is equal to one (if it isn't, then we need some additional value in the numerator, which is where \$f = 1\$ comes in). The second condition is sufficient because, considering some nonnegative integer \$ad+b\$ where \$a\$ and \$b\$ are nonnegative integers, \$b\$ being less than \$d\$, the value of $$\left\lfloor \frac{\left\lfloor \frac{mad+mb}{2^{32}} \right\rfloor}{2^s} \right\rfloor = \left\lfloor \frac{\left\lfloor \frac{amd}{2^{32}} \right\rfloor}{2^s} \right\rfloor$$ This is because \$mb\$ is less than \$md\$, so \$\frac{mb}{2^{32}}\$ is less than one. If the magic quotient of \$d\$ by \$d\$ is one, then $$\left\lfloor \frac{\left\lfloor \frac{md}{2^{32}} \right\rfloor}{2^s} \right\rfloor = 1$$ Consequently, $$\left\lfloor \frac{\left\lfloor \frac{amd}{2^{32}} \right\rfloor}{2^s} \right\rfloor = a \left\lfloor \frac{\left\lfloor \frac{md}{2^{32}} \right\rfloor}{2^s} \right\rfloor = a$$ which is indeed the integer part of \$\frac{ad+b}{d}\$. Since this works for every \$ad+b\$, the \$s\$, \$m\$ and \$f\$ values are satisfactory. Otherwise, we need to consider \$f = 1\$. This value of \$f\$ will definitely work. The problem is more complicated if \$f = 1\$, but it is still a problem of approximation. I'll leave the work of finding the simple equation to you, but here it is for those who don't have the time / are too lazy to do the work themselves: $$d(m+2^{32}) \approx 2^{33+s}$$ From here, the work is very similar to before, except that since we **must** get a good value, we restrict the search space to the values of \$s\$ such that the \$m\$ corresponding to \$s\$ is within the required range. Another difference is that \$m\$ is found using a Python equivalent of `-~` rather than `ceil`, the difference between them being that `-~` increments integers whereas `ceil` leaves them unchanged. I'm still unsure as to why this is needed, but it works so I'm not going to question it. I don't do these long mathematical explanations very often, so feel free to critique my mathematics. If the LaTEX looks weird, please do tell me so I can fix it. My reasoning might also be wrong, so if it is, please tell me. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~64~~ 61 bytes ``` Nθ≔X²¦³²η≔⌕EX²…³²¦⁶⁴÷×⁻⊖η﹪ηθ﹪±ιθι⁰ζ≔÷×ηX²ζθε≔›εηδI⟦⁻ε×δ⊖η⁻ζδδ ``` [Try it online!](https://tio.run/##XY9BC8IwDIXv/ooeU6igTrx4EkXxMBHxJh7qGrbC1mnbTdifr9kUixYCSd6Xx2tWSJvVsgxhb@6NPzTVDS08@HK0ck7nBo71kxYzwZIZF6yIwlYbBam8R@IkTY6QULeYc4L3xm90qxXCWVfoINWmcbDBzGKFxqOCgqi0Vk1ZQyHYg8fxgLn0CJp/1n0zoepigH97cvhG6fhwKBhGfmeRLC1g/w3BFClHq42HtXQeLu90JL7dlGC/SYdwA9P1x1RXzpchTPsXxm35Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `d`. ``` ≔X²¦³²η ``` Precompute `2³²` as it gets used several times. ``` ≔⌕EX²…³²¦⁶⁴÷×⁻⊖η﹪ηθ﹪±ιθι⁰ζ ``` Find the first power of `2` between `2³²` and `2⁶⁴` which satisfies the formula in `[A346496](https://oeis.org/A346496)`, even if `d` is a power of `2`. Note that the formula given there calculates the first `b` where `2**b<=(2**32-(2**32%d)-1)*(d-1-(2**b-1)%d)`, but I actually calculate `(2**32-(2**32%d)-1)*(-2**b%d)//(2**b)` and find the first `b` where that is `0`. For now, assume `f=0` and `s=b-32`. ``` ≔÷×ηX²ζθε ``` Assume `m=[A346495](https://oeis.org/A346495)(d)` (but using the value of `b` computed above even if `d` is a power of `2`). This value is correct if it lies within the desired range `[2..2³²]`. ``` ≔›εηδ ``` Compute `f=m>2³²`. ``` I⟦⁻ε×δ⊖η⁻ζδδ ``` If `f=1`, subtract `2³²-1` from `m` and `1` from `s`. (The OEIS algorithm for `m>2³²` seems to erroneously hard-code the value of `s-1` as `2`, which happens to work for its example of `d=7`.) Output the final values of `m`, `s` and `f`. ]
[Question] [ Given a binary 3D array, for each layer, cyclically rotate up each of its columns as many steps as indicated by the binary encoding of the columns of the layer above it, and then cyclically rotate left each of its rows as many steps as indicated by the binary encoding of the rows of the layer below it. There will always be at least three layers. The top layer's columns and the bottom layer's rows should not be rotated. ## Walk-through Lets start with the small 4-layer, 2-row, 3-column array: ``` [[[1,0,1], [1,0,0]], [[1,0,1], [0,1,1]], [[0,1,1], [1,1,1]], [[1,1,0], [1,1,1]]] ``` The first step is evaluating the numbers encoded in binary by the columns and rows of each layer: ``` 3 0 2 5 [[[1,0,1], 4 [1,0,0]], 2 1 3 5 [[1,0,1], 3 [0,1,1]], 1 3 3 3 [[0,1,1], 7 [1,1,1]], 3 3 1 6 [[1,1,0], 7 [1,1,1]]] ``` The first layer, `[[1,0,1],[1,0,0]]` will not have its columns rotated, but its rows will be cyclically rotated left 5 steps and 3 step respectively, thus becoming `[[1,1,0],[1,0,0]]`.  The second layer, `[[1,0,1],[0,1,1]]`, will have its columns cyclically rotated up 3, 0, and 2 steps respectively, giving `[[0,0,1],[1,1,1]]`, and then the rows are cyclically rotated left 3 and 7 steps respectively, with no visible change.  The third layer, `[[0,1,1],[1,1,1]]` rotated up 2, 1, and 3 steps stays the same, and neither does rotating left 6 and 7 steps do anything.  Finally, the fourth layer, `[[1,1,0],[1,1,1]]` rotated up 1, 3, and 3 steps is `[[1,1,1],[1,1,0]]`, but its rows are not rotated afterwards, as it is the last layer.  Putting all the layers together again, gives us the binary self-rotated 3D array: ``` [[[1,1,0], [1,0,0]], [[0,0,1], [1,1,1]], [[0,1,1], [1,1,1]], [[1,1,1], [1,1,0]]] ``` Example cases: `[[[1,0,1],[1,0,0]],[[1,0,1],[0,1,1]],[[0,1,1],[1,1,1]],[[1,1,0],[1,1,1]]]` gives `[[[1,1,0],[1,0,0]],[[0,0,1],[1,1,1]],[[0,1,1],[1,1,1]],[[1,1,1],[1,1,0]]]` `[[[1]],[[1]],[[0]]]` gives `[[[1]],[[1]],[[0]]]` `[[[1,0,1],[1,0,1],[1,0,1]],[[0,0,1],[0,0,1],[0,0,1]],[[1,0,0],[1,0,1],[0,0,1]]]` gives `[[[0,1,1],[0,1,1],[0,1,1]],[[0,1,0],[1,0,0],[0,1,0]],[[1,0,1],[1,0,1],[0,0,0]]]` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṙ""Ḅ} Z€çŻṖ$$Z€çḊ ``` **[Try it online!](https://tio.run/##y0rNyan8///hzplKSg93tNRyRT1qWnN4@dHdD3dOU1GBcB7u6Pp/uP3opIc7Z/z/Hx0dbaijYKCjYBirowBlGsSC2MjiIBrEBIvDOBD1CHEIxwBFPBYA "Jelly – Try It Online")** ### How? ``` ṙ""Ḅ} - Link 1, rotation helper: 3d matrix to rotate, 3d matrix of rotation instructions } - use the right argument for: Ḅ - un-binary (vectorises) - get the rotation amounts as a 2d matrix " - zip with: " - zip with: ṙ - rotate (the current row) left by (the current amount) Z€çŻṖ$ $Z€çḊ - Main Link: 3d matrix, M Z€ - transpose €ach (layer of M) $ - last two links as a monad: $ - last two links as a monad: Ż - prepend a zero Ṗ - pop (i.e. remove the tail) ç - call the last Link as a dyad (i.e. f(Z€ result, ŻṖ$ result) ) Z€ - transpose €ach (layer of that) Ḋ - dequeue (i.e. remove the head layer of M) ç - call the last Link as a dyad (i.e. f(Z€çŻṖ$$Z€ result, Ḋ result) ) ``` Note: `$$` (or possibly `$$ ... $$`?) seems to mess up the code-block formatting (but only once posted, not in the preview), so I added a space to make my life easier. [Answer] # [Python 2](https://docs.python.org/2/), ~~220~~ ~~211~~ ~~209~~ ~~185~~ ~~176~~ ~~174~~ ~~164~~ ~~161~~ 159 bytes ``` lambda m:map(R,z(map(R,z(m,['']+[z(*l)for l in m])),m[1:]+[''])) R=lambda(l,L):map(lambda r,i:r[i:]+r[:i or 0],z(*l),[int(`b`[1::3],2)%len(b)for b in L]) z=zip ``` [Try it online!](https://tio.run/##fZDLroIwEIb3PEU3xlZnUXTXhDdw5XZOEyFHYpMWSONGXp4zUArlaNz0n87lm0v3ej7a5jTUxc9gS1f9lswpV3b8Cj1fFHC/10fs@cGKuvXMMtMwp4UAh7miCIWFyK5FQHALFzFRZqQHozwayvSoDCOC1DDRAE3z5LfqRhx11nASO3tveDW1qcY2Fy2yvuhNN3SeclnNETEHCbmGSaUmY/HQSzp6gjXmRM9oydVD4IBkDNNgRMqlyXdk9FCVDsQsS2cNiQHw1vVf8FN9suuq6YBbjdeQSc0c2faO22w17rneAuZ/euYUvM49/AE "Python 2 – Try It Online") -2 bytes, thanks to Jonathan Allan [Answer] # APL+WIN, ~~53~~ 39 bytes Many thanks to Adám for saving 14 bytes ``` (1 0↓⍉2⊥⍉m⍪0)⌽(¯1 0↓2⊥2 1 3⍉0⍪m)⊖[2]m←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rGCoYPGqb/Ki30@hR11Iglfuod5WB5qOevRqH1kPkQBJGCoYKxkBZA6BsruajrmnRRrG5QFOApv0HmvM/jctEwQikYgtQD1AtiDRQMIRjGImAUD4A "APL (Dyalog Classic) – Try It Online") Prompts for input of a 3d array of the form: ``` 4 2 3⍴1 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 ``` which yields: ``` 1 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 ``` Explanation: ``` m←⎕ Prompt for input (¯1 0↓2⊥2 1 3⍉0⍪m) Calculate column rotations (1 0↓⍉2⊥⍉m⍪0) Calculate row rotations (...)⌽(...)⊖[2]m Apply column and row rotation and output resulting 3d array: 1 1 0 1 0 0 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 ``` [Answer] # [R](https://www.r-project.org/), ~~226~~ ~~216~~ 205 bytes -21 bytes thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall) ``` function(a,L=`for`){d=dim(b<-a) r=function(a,n,l=sum(a|1))a[(1:l+sum(n*2^(sum(n|1):1-1))-1)%%l+1] L(i,I<-2:d[3],L(j,1:d,b[j,,i]<-r(b[j,,i],a[j,,i-1]))) L(i,I-1,L(k,1:d[2],b[,k,i]<-r(b[,k,i],a[,k,i+1]))) b} ``` [Try it online!](https://tio.run/##dU5dysIwEHz3HsKu3UC39ak0B/igNygR05ZCtMaPqA@inr0mrT8VkbCzs@zMbFzfyr492fpo9hY0FXLd7t0aL41szA6qXGicOTlRWOrk4bQDfWVEXQJnXRRmu0hWMBC/yFj4ra/5vItYzQow9JeLJGvKVFEBG@KsoarcEBmVCwcPSnroghUiji7BXr8N@jJR3kLbl2Wg3hJ6NFqqW//vjD1CC9o5fYYamGJiChgTv@qJ7/eYkWpIKaElhrzvMC8MkkDSH5Jpfjy5/MbP38TPq@kY2d8B "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~41~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εNĀiø¹N<èøJC‚øε`._}ø}N¹g<Êi¹N>èJC‚øε`._ ``` This feels way too long.. Can definitely be golfed some more. [Try it online](https://tio.run/##yy9OTMpM/f//3Fa/Iw2Zh3cc2ulnc3jF4R1ezo8aZh3ecW5rgl587eEdtX6HdqbbHO7KBMrbHV6BLPv/f3R0tKGOgY5hrA6YNogFMuAiQBJIg0QgLJAamAiIZYAQiQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuO4hP0/t9XvSEPm4R2RfjaHVxze4eX8qGHW4R3ntiboxdce3lHrF5luc7grM9LP7vAKZLn/tbW1Ooe22f@PBgJDHQMdw1gdMG0QC2TARYAkkAaJQFggNTAREMsAIRKrowAyCiIF0QIXRDIfQUNMhdmDTMNcYICkByoTGwsA). **Explanation:** ``` ε # Map each layer in the (implicit) input to: # (`N` is the layer-index of this map) NĀi # If it is not the first layer: ø # Zip/transpose the current layer; swapping rows/columns ¹N<è # Get the `N-1`'th layer of the input ø # Zip/transpose; swapping rows/columns J # Join all inner lists (the columns) together C # And convert it from binary to integer ‚ # Pair it with the current layer's columns we're mapping ø # Zip/transpose; to pair each integer with a layer's columns ε } # Map over these pairs: ` # Push both values of the pair separately to the stack ._ # Rotate the column the integer amount of times ø # Zip/transpose the rows/columns of the current layer back } # Close the if-statement N¹g<Êi # If this is not the last layer (layer-index-1 != amount_of_layers): ¹N>è # Get the `N+1`'th layer of the input J # Join all inner lists (the rows) together C # And convert it from binary to integer ‚ # Pair it with the current layer's rows we're mapping ø # Zip/transpose; to pair each integer with a layer's rows ε # Map over these pairs: ` # Push both values of the pair separately to the stack ._ # Rotate the row the integer amount of times # (implicitly output the result after the layer-mapping is done) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~138~~ ~~131~~ ~~125~~ 123 bytes ``` t=Map@Thread m=MapThread[r=RotateLeft,#,2]& b=(a=ArrayPad)[Map@Fold[#+##&]/@#,1]~r~#2~a~-1& g=m@{t@m@{t@#,t@#~b~-1},#~b~1}& ``` [Try it online!](https://tio.run/##lVLBasMwDL37K0QCoWUujbvbhkcGXU8blK43Y4bSpm2gaYLjw0ZIfj2Tk6btBjvsYOvx9PxkCWVoD0mGNt1gW4IETykleMiF5l0MNYELQzdFx/TIaQbGofDKaO@RMUSyfLcmPe1XSXHETaJKDhVV8WDyBF7lcfB0j2uv1jCdwjp/@SxMUpZpfgLy2Cn80PAgYcRYvCG/uckLxQCejcGvJW7VGxZqYfJsnu5TWyqfw0xDwIE0AGuDp7LIy0QhVRYc7ilda8L97aiwJhC6SNREaKoam39XwqsneYlbz84SBVmSw/pgEvKCVW7RJq/JzpISm8tHm8svgUO8qV2Rht22clWQ7Z@OpIlN93rcWkmyqNexTF7fGHnzyOczHbBYjlAOLY9dz9EiP26Vf@f7gZ5GPrXTmMafNdhMRMD2MosqG3WXz@k0MfE1d1HUQbuL3BpICfsBVN3Uh8G72M3pPLlheL1EXHjxg3cDOefE7xx51W6VlrR4tv0G "Wolfram Language (Mathematica) – Try It Online") * `Map[Thread]` is equivalent to `Transpose[a, {1,3,2}]`, which transposes the columns and rows. * `Fold[#+##&]` is shorter than `IntegerDigits[#,2]` for converting from binary. ]
[Question] [ Given a 7-segment display with some segments switched on and some off, find a sequence of digits (0-9), such that after toggling the corresponding segments for each digit, all segments are switched off. ## Example ``` _ _ [3] => | [1] => [OFF] _ | ``` Numbers and their corresponding segments: ``` _ _ _ _ _ _ _ _ | | | _| _| |_| |_ |_ | |_| |_| |_| | |_ _| | _| |_| | |_| _| ``` ## Rules Codegolf ⊨ shortest entry wins. ## Input A non-empty list of segments which are switched on, given as 1. A sequence of numbers. Segments are numbered from top to bottom, left to right; starting from 0 or 1. Numbers need not be in order. 2. A single 7-bit digit. MSB/LSB not specified (thus you can choose). Non-numeric characters between numbers are allowed (but not required to be supported). Eg. for number `7`: `136` or `1010010` or `0100101` ## Output A sequence of numbers to be "applied" to the display. Not restricted in any way, such as order of the digits. Eg. for initial state corresponding to number `1`, valid outputs would be `1`, `111`, `010`, etc. An alternative output is a 10-bit digit (again, MSB/LSB is your choice). Eg. for `1` as input, the output would be `1000000000` or `0000000001`. Some combinations have several non-repetitive solutions, eg. segments corresponding to the uppercase letter `H` can be switched off by `013`, but also `489` and `0258`. If no solution exists (which I believe is not possible), the output is empty. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 25 bytes ``` 2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ ``` [Try it online!](https://tio.run/##AUAAv/9qZWxsef//MuG5l@KBteKAmcOww5figJx3w5hdWzprb1LCtnvigJheLz3DsMOQZuG4ov///zE49W5vLWNhY2hl "Jelly – Try It Online") Takes input as a 7-bit integer. Returns the binary form of a 10-bit integer. This just brute forces all possibilities. Remove the `Ḣ` to get all possible outputs or replace it with an `X` to get a random possible output. [Magic Visualization Program!](https://tio.run/##y0rNyan8/3B396OGOY8adz3c0ftw18KHO7Y93NX5cEfziXUPd3U/3DnzUcOMeEMjA64soCoFGHjUMPfQ1qN7Dk90O7T10LpMVaNDW@25LA8tPrT18HSvRw0gTYcnpB3aCtYTDVRtbQ1kxtraQbU@alrDVWxuxHVos7ahkYXTwx1d4VxGZkcn24MNOLrHwUDHwA3isvia@BogAunjOjnZ8Mh@nYc7WuL0YfoOb4g53A40rthYBUhGHVppdGQ/kGECJqMiI7mQHWTtYHpk/@H2/0YPd05/1Ah03UyQfUBLyg/PiI22ys4POrStGqg0Tt/20Gag1IS0hzsW/Qf6y@LI/v//DS0A "Jelly – Try It Online") ### How it works ``` 2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ - main link, takes one integer 2ṗ⁵’ - generate all length-10 binary arrays µ µÐf - now we find those arrays which correspond to digit- sequences which work to switch off all segments: Filter (keep) those arrays which: × - multiplied by “wØ][:koR¶{‘ - [119, 18, 93, 91, 58, 107, 111, 82, 127, 123] (encoding for turned-on segments given number) ^/ - reduced by XOR = - are equal to (implicit) the program's input Ḣ - output the first of these valid arrays ``` [Answer] ## JavaScript (ES6), 60 bytes ``` n=>[65,35,55,42,48,54,110].reduce((r,v,i)=>r^=n>>i&1&&v+v,0) ``` This works because: * Toggling 1 and 7 toggles the top segment only * Toggling 1, 2 and 6 toggles the top left segment only * Toggling 1, 2, 3, 5 and 6 toggles the top right segment only * Toggling 2, 4 and 6 toggles the centre segment only * Toggling 5 and 6 toggles the bottom left segment only * Toggling 2, 3, 5 and 6 toggles the bottom right segment only * Toggling 2, 3, 4, 6 and 7 toggles the bottom segment only [Answer] ## JavaScript (ES6), ~~117~~ ~~107~~ ~~101~~ ~~86~~ 84 bytes *Saved 15 bytes thanks to Neil* Takes input as a 7-bit integer, where the LSB is the upper segment. Returns a 10-bit integer where the LSB is digit `0`. ``` f=(n,k)=>[83,0,57,73,10,71,87,1,91,75].reduce((n,v,i)=>n^=k>>i&1&&v+36,n)?f(n,-~k):k ``` ### Demo ``` f=(n,k)=>[83,0,57,73,10,71,87,1,91,75].reduce((n,v,i)=>n^=k>>i&1&&v+36,n)?f(n,-~k):k console.log("'1' shape", "-->", f(0b0100100).toString(2)) console.log("'7' shape", "-->", f(0b0100101).toString(2)) console.log("'H' shape", "-->", f(0b0111110).toString(2)) ``` [Answer] ## Mathematica, 40 bytes ``` BitXor@@{260,802,10,514,3,266,293}[[#]]& ``` (It may be golfed more by choosing output for each segment carefully and switch between LSB and MSB.) Take input as a list of positions for example `{2,4,5,7}` and output a 10-bit number (`384` = `0110000000` in binary) in MSB order (0,...,9). In the example it correspond to ``` |_ |_ ``` and the output correspond to `{7,8}`. Explanation: The magic numbers (hardcoded list) is the output which is returned for each segment. (encoded in binary) And, if a number appear in the list twice, the effect is the same of it not being appear, so bitwise XOR is used. We just need to XOR the output of possible value of the segments turned on. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ị“A#7*06n‘^/ ``` [Try it online!](https://tio.run/##y0rNyan8///h7u5HDXMclc21DMzyHjXMiNP///9/tKGOsY5ZLAA "Jelly – Try It Online") This does not brute force, and it is remarkably shorter than my other solution. Takes input as a list of turned-on segments, and outputs as LSB is top segment. [Output as list of digit moves.](https://tio.run/##AS4A0f9qZWxsef//4buL4oCcQSM3KjA2buKAmF4vQlXCtcOXSuG4nzD///9bMSwzLDZd "Jelly – Try It Online") **How it works** This is going to be quick ``` ị“A#7*06n‘^/ - main link, takes input as a list of turned-on segments (eg. [1,3,6]) “A#7*06n‘ - list literal [65,35,55,42,48,54,110] where each element is a 7-bit integer, where each integer corresponds to how to turn off a segment (eg. turn off the first segment with 7 and 1 =>2^7+2^1=>64) ị - get the elements in the list corresponding to the input indices ^/ - XOR reduce these elements to get a single 7-bit integer ``` ]
[Question] [ While similar to the other [water-carrying puzzle](https://codegolf.stackexchange.com/questions/100723/i-want-to-watch-you-die-of-thirst), the unique aspects of this challenge make it entirely different. [![Beth](https://i.stack.imgur.com/6jr2y.png)](https://i.stack.imgur.com/6jr2y.png) Beth is located at an oasis in the middle of a desert. There is plenty of water in the lake, but unfortunately there are only X buckets, each of which has a capacity of Y liters of water. Beth can carry 2 buckets in her hands, but to survive, she must drink exactly 1 liter after each kilometer she travels. She can also leave some buckets half-way (water does not evaporate). ## The challenge Figure out the formula and write the **shortest solution** that will work for positive integer values of X and Y and calculate the **maximum distance** Beth can travel from the oasis. Moving water between the buckets is permitted. ## Example X=3, Y=5 1. Beth walks 3km with two full buckets. Leaves 1 full bucket behind. The other bucket now has 2L left, which is enough to get home (Beth can have the last drink from the oasis). 2. She leaves with another two full buckets, arriving with 1 full, plus 2 litres in the other (12L total: 5 + 5 + 2). 3. Beth can advance to 6KM point and leave bucket with 4L of water in it. 4. She returns to the 3KM point. She now has exactly 2L to get back to the oasis. 5. Fill up buckets and travel to 6KM point. She now has 8L of water. 6. Continue all the way to 15KM point. Answer is: 15 ## Input / Output You can define X/Y directly in the code or read from input. Result could be placed in variable or output, whichever is shortest. [Answer] ## JavaScript (ES6), 25 bytes ``` x=>y=>((x<3?x:3)+x)*y/2+1 x=>y=>(x<3?x+x:x+3)*y/2+1 x=>y=>(x<3?x:(x+3)/2)*y+1 x=>y=>(x<3?x:x/2+1.5)*y+1 ``` All of these compute the same value; I can't seem to come up with a shorter formulation. When `x` is less than `3`, you take as much water as you can and walk as far as you can, which is simply `x*y+1`. When `x` is at least 3, you have to start building caches. From the oasis, you can leave a full bucket at a distance `y/2` and return to the oasis. You need 2 buckets to do this, but this is not useful if you only have 2 buckets because you want to be able to fill up 2 buckets when you return to the oasis. From the oasis, with a bucket at a distance `y/2`, you can leave a full bucket at a distance `y` and return to the oasis. You need 3 buckets to do this. From the oasis, with full buckets at both `y` and `y/2`, you can leave a full bucket at a distance `3y/2` and return to the oasis. You need 4 buckets to do this. You then have to leave a full bucket at a distance of `y/2` and return to the oasis. Eventually you can end up with a full bucket at `(x-1)y/2`. (You cannot leave a full bucket at `xy/2` because you would not be able to get back to the oasis, as the round trip is `xy`, the total capacity of the buckets.) Using your remaining buckets, you can leave full buckets at `(x-3)y/2` ... `y` or `y/2`. At this point you simply walk as far as you can, picking up your full buckets as you go. When you reach `(x-1)y/2` you still have two full buckets left, allowing you to reach `(x+3)y/2`. The extra `1` comes from the quirk in the rules allowing you to walk your last mile without having any water. Although the example shows that you can leave the buckets slightly further away than described above, this actually does not help you walk any further, as you either have to leave less water or drink the water from the bucket as you reach it before you can move on. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS) ``` 1+2÷⍨⊢×⊣+3⌈⊣ ``` Dyadic train taking `X` on the left and `Y` on the right. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///31Db6PD2R70rHnUtOjz9UddibeNHPR1A@n@awqO2CQoauOQ1ubge9U0FKTFWSFMw/Q8A "APL (Dyalog Unicode) – Try It Online") This uses [@Neil's](https://codegolf.stackexchange.com/a/106009/75323) first formulation, so be sure to upvote that one as well. **how it works:** ``` 3⌈⊣ ⍝ Find the maximum between the left (⊣) argument (X) and 3 ⊣+ ⍝ and sum that to the left (⊣) argument (X), ⊢× ⍝ which we then multiply by the right (⊢) argument (Y) 2÷⍨ ⍝ and divide by 2. 1+ ⍝ Finish of by adding 1. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` D3‚à+*;> ``` Port of [*@Neil*'s formula](https://codegolf.stackexchange.com/a/106009/52210), so make sure to upvote him!! $$d\_{X,Y}=\begin{cases} \dfrac{(3+X)\times Y}{2}+1 &\text{ if }X<3\\ \\ \dfrac{2X\times Y}{2}+1 &\text{ if }X\geq3 \end{cases} $$ [Try it online.](https://tio.run/##yy9OTMpM/f/fxfhRw6zDC7S1rO3@/zfmMgUA) **Explanation:** ``` D # Duplicate the first (implicit) input-integer X 3‚ # Pair it with 3: [X,3] à # Pop and push its maximum + # Add it to the duplicated X (3+X if X<3; X+X if X>=3) * # Multiply it by the second (implicit) input-integer Y ; # Halve that > # And increase it by 1 # (after which the result is output implicitly) ``` ]
[Question] [ You are a traveller crossing the desert between two towns. You cannot carry enough water to get across without stopping. [This is a variation of a classic puzzle.](http://dailybrainteaser.blogspot.co.uk/2012/10/cross-desert-logical-riddle.html) # The Rules A desert looks like this: a WxH grid of mostly empty space. The space marked `S` is where you start, `E` is where you want to end, and a square marked with the number N holds N units of water. Squares marked with a `.` hold zero water. ``` ..................................... ........S............................ ..................................... .........7........................... ..................................... .......................3............. .....5............................... ................................2.... ..................................... ..................................... ..................................... ...............................E..... ..................................... ....................7................ ..................................... ..................................... ``` You start at S with 5 units of water. You can carry at most 5 units of water. Each turn you 1. move one square Up, Down, Left, or Right, 2. consume 1 unit of water that you are carrying, 3. pick up **or drop** some number of units of water. A turn is notated thus: `(direction)(+|-)(units of water)`, `+` indicates you are picking up water, `-` that you are dropping it. Example turns: ``` D+0 Move Down R+0 Move Right D+2 Move Down, pick up two units of water. U-1 Move Up, drop one unit of water. ``` If you perform these moves starting at S in the example above, the desert looks like this afterwards. ``` ..................................... ........S............................ .........1........................... .........5........................... ..................................... .......................3............. .....5............................... ................................2.... ..................................... ..................................... ..................................... ...............................E..... ..................................... ....................7................ ..................................... ..................................... ``` You can pick up no more water than is already on your square. When you pick up the water, deduct that number of units from the tile's count. You can only pick up water to hold a maximum of 5 units. No tile can hold more than 9 units, except S which holds infinity units. You can only drop as much water as you are currently holding. Water on the ground remains unchanged until you pick it up again. If you return to S you can pick up any quantity of water without depleting it. If you reach E then **you win**. You still win if you consume your last unit of water on E. If, after your turn, you have zero water and you are not on E, **you die**. # Input and Output Your program will receive a starting map of arbitrary size on `STDIN` as ASCII art in the format above. You can assume it is rectangular i.e. all lines the same length, that there is exactly one `S` and one `E` square, all lines are terminated with `\n`, and the whole of STDIN will conform to this regex: `/^[SE1-9\.\n]+$/` Your program will write the following output to STDOUT: 1. the list of moves, 2. the final state of the map. You may output the list of moves in any convenient format. The final state of the map will be printed in the same format as the input **except that it will additionally show the route you took through the desert** by marking all visited tiles with `#`, if that tile contains no water and is not S or E (i.e. it is `.`). **EXAMPLE** input: ``` .....S. ....... ....... E...... ....8.. ``` **EXAMPLE** winning output: ``` D+0 D+0 D+0 D+0 L+5 L+0 L+0 L+0 L+0 U+0 .....S. .....#. .....#. E....#. ####3#. ``` # Nontriviality When you post your code, post a sample map input which your code finds a solution for which satisfies the following non-triviality conditions: * S and E are at least 10 moves apart. * Any square which initially contains N units of water must be surrounded by a N-width border in which all squares are `.` (no water, not S or E) **EXAMPLE** ``` ........2. .......... .......... S.1..2.... .......... .......... ........1. ..3....... .........E ``` If you increase the amount of water on any tile, the above becomes trivial. # Requirements Presumably your program will encounter a number of failed attempts before it finds a solution, if any. 1. Your program must eventually solve any solvable input. 2. **I want to watch you die** -- your program will output the moves and final map of the route to death for *each and every* failed attempt to find a solution. 3. If you encounter a winning solution, print the full output for that and terminate. 4. Run until a solution is found, but *do not attempt the same solution twice* -- all deaths should be by distinct routes. 5. Use this a test input: (it requires at least one move to drop a water cache at some midpoint). ``` S........ ......... ......... ........E ``` Shortest code *which is posted with a non-trivial demonstration input which it solves* wins. [Answer] # Perl, ~~299 + 1 = 300~~ 254 + 1 = 255 bytes This will almost certainly be beaten by one of the golfing languages when people see my algorithm :-) Run with `-n` (1 byte penalty). The previous version didn't quite comply with the spec because it left extra water on the map and didn't show it in the final version of the map; while changing the algorithm to deal with that situation, I managed to golf it a bit smaller in the process. ``` push@a,[split//];($s,$t)=(length$`,$.)if/S/;($e,$f)=(length$`,$.)if/E/}{$_.=$s<$e?($s++,R):$s>$e?($s--,L):$t<$f?($t++,D):($t--,U);$\=reverse$";$".=y/LRUD/RLDU/r.Y.reverse.($"=~y/Y/X/r);$a[$t-1][$s]=~y/./#/;$\.=$s-$e||$t-$f?redo:$_;print map{join'',@$_}@a ``` Example (I've added line-breaks to the output to avoid the need to scroll and to show the structure): ``` E..... #..... #..... #..... #####S LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUXDDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUUYDDDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUXDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUUYDDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLXRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLUYDRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLXRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLLYRRRRR LXR LLXRR LXR LLLXRRR LXR LLXRR LXR LLLLYRRRR LXR LLXRR LXR LLLYRRR LXR LLYRR LYR LLLLLUUUU ``` In the notation used by the program, movement is represented via `L`, `R`, `U`, and `D` for left, up, right, down respectively. By default, you pick up 1 unit of water after every move, but this can be modified by appending a character: * `X`: drop 2 units of water, rather than picking 1 up * `Y`: drop 1 unit of water, rather than picking 1 up * (i.e. space): completely refill on water (only output after a move to `S`; the program is also output with a leading space, which makes sense because you start full on water) As you can see, it's possible to cross this (rather barren) map using no extra pools at all. In fact, it's possible to get any distance under these rules, on *any* map, without the help of any preplaced water. As such, this algorithm just ignores any preplaced water, meaning I don't have to waste bytes trying to handle it. This also means that you're not going to see the bot die, sorry. It never moves beyond the range in which it knows it's guaranteed to survive. The reason we need both `X` and `Y` (and a bit of extra code to ensure we have `X` throughout most of the strategy but the occasional `Y` at the end) is that the spec requires the final version of the map to be output. The easiest way to implement this is to leave the map entirely untouched (apart from our path through initially empty squares), especially as a square which started with `9` water would end up with `10` (breaking the ASCII art) if it happened to be on the path and we only used `X`, and thus we need to find some solution that avoids dropping extra water on the map. The algorithm here would "naturally" drop 1 extra unit of water on each square on the route; as such, the penultimate time we visit each square, we reduce the amount of water dropped by 1 via the use of Y rather than X, so that on our final visit, we drain the square back to its original quantity of water, rather than leaving it slightly wetter than when we started. I'd recommend against running this on a large map, because it has O(2^n) performance (although the bot never dies of thirst, it's plausible to think it would die of hunger using a strategy like this.) Readable version: ``` # implicit with -n: read a line of input into $_ push @a, [split //]; #/ split $_ into characters, store at the end of @a ($s,$t) = (length$`,$.) if /S/; # if we see S, store its coordinates ($e,$f) = (length$`,$.) if /E/ # if we see E, store its coordinates }{ # Due to -n, loop back to start if there are more lines. # From here onwards, $" stores the partial solution this iteration; # $\ stores the partial solution last iteration; # $_ stores the path from ($s,$t) to S. # At the start of the program, $" is a space, $\ and $_ are empty. $_ .= # Work out the next step on the path: $s < $e ? ($s++,R) # if too far left, move right, record that in $_; : $s > $e ? ($s--,L) # if too far right, move left, record that in $_; : $t < $f ? ($t++,D) # if too far up, move down, record that in $_; : ($t--,U); # in other cases we must be too far down. $\ = reverse $"; # Store last iteration; $" is constructed backwards. $" .= # Extend $" by appending y/LRUD/RLDU/r . # the path from ($s, $t) back to S; Y . # a literal 'Y'; reverse . # $/ backwards (i.e. the path from S to ($s, $t); ($"=~y/Y/X/r); # a copy of $" with all 'Y' changed to 'X'. $a[$t-1][$s] =~ # At the current path coordinate, y/./#/; # replace any '.' with '#'. $\ .= # Start appending to $\; $s-$e||$t-$f?redo # if we're not at E, abort that and jump back to {{, : $_; # otherwise append $_ (the path from S to E). print map # For each element of some array {join'',@$_} # output its concatenated elements @a # specifying that array as @a. # Implicitly: print $\ (which specifies the sort of newline print uses). ``` ]
[Question] [ The Halloween is upon us, and I haven't decorated my house yet, so I gonna need your help to do this task **Input** The input will be a list of 4 digits numbers, where each digit represent a portion of decoration: ``` EMBU |||| |||+-upper decoration ||+-bottom decoration |+-mouth/nose +-eyes ``` Eyes: 0 - `°` 1 - `¯` 2 - `-` 3 - `^` 4 - `'` Mouth/Nose 0 - `v` 1 - `w` 2 - `o` 3 - `_` 4 - `-` Bottom decoration 0 - nothing 1 - skeleton 2 - pumpkin Upper decoration 0 - nothing 1 - flying bat 2 - resting bat 3 - spider **Output** Skeleton: `(EME)` `​ _|_ ​` `/[|]\` `​ | ​ ​` `​ / \ ​` Pumpkin `​ , ​` `(EME)` Flying bat `​ ​` `​ ^"^ ​` Resting bat `​ ​ () ​` `​ ​ ´` ​` Spider `​ | ​` `​ .|. ​` `​ :": ​` * Each decoration has a 5 character width * Upper decorations start from the top * Lower decorations start from the bottom * If the spider is over the pumpkin or there is no bottom decoration the web length will be 3, if it's over the skeleton, the web length will be 1 * When the bottom decoration is `0` the first 2 digits are irrelevant * Between each decoration there will be an empty column **Example** Input `3123 ??02 1021 0310` Output ``` | () ​ ​ | ´` ^"^ ​ ​ .|. (°_°) ​ :": _|_ ​ ​ /[|]\ ​ , , | ​ ​ (^w^) (¯v¯) / \ ​ ``` Trailing spaces at the end of each line are optional Trailing newline at the end of the entire output is allowed **Winning criteria** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins [Answer] # Java, ~~829~~, 798 Yeah. Substantially improved thanks to Kevin Cruijssen and corvus\_192. ``` s->{String[]e=s.split(" ");char c[][]=new char[8][e.length*6],t,u,h='|';int y,x=2,i=0,j;for(String l:e){y=0;char[]p=l.toCharArray(),z=c[y];int a=p[0],b=p[1],f=p[2],d=p[3],k=x-1,m=x+1;t=a<49?'°':a<50?'¯':a<51?45:a<52?'^':39;u=(char)(b<50?b+70:b<51?111:b<52?95:39);if(d>50){z[x]=h;if(f!=49){y=2;c[1][x]=h;c[2][x]=h;}z=c[y];z[k]=46;z[m]=46;z=c[++y];z[k]=58;z[m]=58;z[x]=34;}if(d==50){z[x]=40;z[m]=41;c[++y][x]='´';c[y][m]=96;}if(d==49){z=c[++y];z[k]=94;z[x]=34;z[m]=94;}if(f>49){y=6;c[y][x]=44;}if(f>48){y=f>49?7:3;z=c[y++];z[x]=u;z[k]=t;z[m]=t;z[x-2]=40;z[x+2]=41;}if(f==49){z=c[y++];z[x]=h;z[k]=95;z[m]=95;z=c[y];z[x]=h;z[k]=91;z[m]=93;z[x-2]=47;c[y++][x+2]=92;c[y++][x]=h;c[y][k]=47;c[y][m]=92;}x+=6;}for(;i<8;i++){s="";for(j=0;j<c[0].length;){t=c[i][j++];s+=t<1?' ':t;}System.out.println(s);}}; ``` the ungolfed version ``` static void makeDecorations(String s){ String[]e=s.split(" "); char c[][]=new char[8][e.length*6],t,u,h='|'; int x=2,i=0,j,y; for(String l:e){ y=0; char[]p=l.toCharArray(), z=c[y]; int a=p[0],b=p[1],f=p[2],d=p[3],k=x-1,m=x+1; t=a<49?'°':a<50?'¯':a<51?45:a<52?'^':39; u=(char)(b<50?b+70:b<51?111:b<52?95:39); if(d>50){z[x]=h; if(f!=49){y=2; c[1][x]=h; c[2][x]=h; } z=c[y]; z[k]=46; z[m]=46; z=c[++y]; z[k]=58; z[m]=58; z[x]=34; } if(d==50){ z[x]=40; z[m]=41; c[++y][x]='´'; c[y][m]=96; } if(d==49){ z=c[++y]; z[k]=94; z[x]=34; z[m]=94;} if(f>49){ y=6; c[y][x]=44; } if(f>48){ y=f>49?7:3; z=c[y++]; z[x]=u; z[k]=t; z[m]=t; z[x-2]=40; z[x+2]=41; } if(f==49){ z=c[y++]; z[x]=h; z[k]=95; z[m]=95; z=c[y]; z[x]=h; z[k]=91; z[m]=93; z[x-2]=47; c[y++][x+2]=92; c[y++][x]=h; c[y][k]=47; c[y][m]=92; } x+=6; } for(;i<8;i++){ s=""; for(j=0;j<c[0].length;){ t=c[i][j++];s+=t<1?32:t; } System.out.println(s); } } ``` Favorite decoration (which apparently looks more evil in my console): terminator skeleton ``` (-w-) _|_ /[|]\ | / \ ``` [Answer] ## JavaScript (ES6), ~~319~~ 315 bytes ``` let f = s=>[0,1].map(i=>s.map(([A,B,C,D],x)=>+(z=i?D:C)&&[...'01/21/5015/41211/91/65'.split`/`[z-(i?C+D-13?1:-2:-2)]].map((n,y)=>a[(i?y:6-y)*4+x]=' '+(' ^"^ () ´` / \\ | .|. /[|]\\ _|_ ('+(e='°¯-^'[A])+'vwo_-'[B]+e+') , :": ').substr(p+=n*5,5),p=0)),a=Array(28).fill` `)&&a.join``.match(/.{24}/g).join` ` console.log(f(["3123","0002","1021","0310"])); ``` [Answer] # Ruby 2.3.1, 777 752 bytes Edit\_0: I totally missed out on some golfable variable usage and some other stuff. ``` @o=Array.new;$*.each_with_index do|j,i|a,e,n,b,u,q,r,z,y=0,j[0].to_i,j[1].to_i,j[2].to_i,j[3].to_i,['°','¯','-','^',"'"],['v','w','o','_',"-"],Array.new(7," ")," ";g,h=[z,["(#{q[e]}#{r[n]}#{q[e]})","​ _|_ ​","/[|]\\","​ | ​ ​","​ / \\ ​"],[" ","​ , ","(#{q[e]}#{r[n]}#{q[e]})"]],[z,["​ ​","​ ^\"^ ​"],["​ ​ () ", "​ ​ ´` "],["​ .|. ​","​ :\": ​"]];2.times{h[3].unshift(" | ​")}unless b==1;if b<1 && u<1;@o.push(z);elsif b<1;u<3 ? (a=5):(a=3);a.times{h[u].push(y)};@o.push(h[u]);elsif u<1;b==1 ? (a=2):(a=4);a.times{g[b].unshift(y)};@o.push(g[b]);elsif u>0;2.times{h[u].push(y)}if u<3&&b>1;@o.push(h[u]+g[b]);end;@o.push(z);end;@o.transpose.each do|v|;v.each do |w|;print w;end;print"\n";end ``` Takes in N number of variables of decorations. There's certainly some more golfing that can be done with this. I'm not that familiar with a lot of Ruby's tricks, but here's a shot at it! I'm also happy at being able to solve it. ## Un-golfed ``` @output = Array.new $*.each_with_index do |j, i| # output decoration combo s = 0 # set up vars for decoration input e = j[0].to_i n = j[1].to_i b = j[2].to_i u = j[3].to_i # Setup decorations/misc eyes = ['°','¯','-','^',"'"] nose = ['v','w','o','_',"-"] nothing = Array.new(7, " ") skeleton = ["(#{eyes[e]}#{nose[n]}#{eyes[e]})", "​ _|_ ​", "/[|]\\", "​ | ​ ​", "​ / \\ ​"] pumpkin = [" ", "​ , ", "(#{eyes[e]}#{nose[n]}#{eyes[e]})"] fbat = ["​ ​", "​ ^\"^ ​"] rbat = ["​ ​ () ", "​ ​ ´` "] spider = ["​ | ​", "​ .|. ​", "​ :\": ​"] spider.unshift(" | ​") unless b == 1 a = " " bot = [nothing, skeleton, pumpkin] top = [nothing, fbat, rbat, spider] # if bottom and upper are empty if b < 1 && u < 1 @output.push(nothing) # if bottom is empty elsif b < 1 u < 2 ? (s = 3) : (s = 5) s.times {top[u].push(a)} @output.push(top[u]) # if upper is empty elsif u < 1 # put in white space before the decorations b == 1 ? (s = 2) : (s = 5) s.times {bot[b].unshift(a)} @output.push(bot[b]) # if there's an upper decoration elsif u > 0 # put in the top deco 2.times {top[u].push(a)} if u < 3 && b > 1 @output.push(top[u] + bot[b]) end # Input the empty column @output.push(nothing) end # Transpose the array of arrays so that # instead of outputting each line of a single each decoration # what's output is each line of each decoration. # Example: # [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] # [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]] @output.transpose.each do |data| data.each do |data1| print data1 end print "\n" end ``` The following: ``` ruby deco_g.rb 0000 0001 0002 0003 1110 1111 1112 1113 2220 2221 2222 2223 3310 3312 3321 3323 ``` Outputs this: ``` () | () .|. () | () | ^"^ ´` | ^"^ ´` :": ^"^ ´` | ´` ^"^ | .|. (¯w¯) (¯w¯) (¯w¯) (¯w¯) .|. (^_^) (^_^) .|. :": _|_ _|_ _|_ _|_ :": _|_ _|_ :": /[|]\ /[|]\ /[|]\ /[|]\ /[|]\ /[|]\ | | | | , , , , | | , , / \ / \ / \ / \ (-o-) (-o-) (-o-) (-o-) / \ / \ (^_^) (^_^) ``` [Answer] ## Python 2, 331 bytes"" ``` B,I,l,s=' '*5,' | ',' .|. ',' :": ' r=[] for x in inputtt:m,n,b,u=(int(y)for y in x);e="°¯-^'"[m];H='('+e+"vwo_-"[n]+e+')';r+=[[[B,B,' () ',[I,l,I][b]][u],[B,' ^"^ ',' ´` ',[I,s,I][b]][u],[[B,l][u==3],H][b==1],[[B,s][u==3],' _|_ '][b==1]]+[[B]*3,['/[|]\\',I,' / \ ',],[B,' , ',H]][b]] print'\n'.join(map(' '.join,zip(*r))) ``` Takes input as list of strings - ### Example Input: `["1212","4321","0123","1102","0020","1010","0101","2113"]` Output: ``` () | () .|. ´` ^"^ | ´` ^"^ :": (¯o¯) .|. (¯v¯) (-w-) _|_ :": _|_ _|_ /[|]\ /[|]\ /[|]\ | , , , | | / \ ('_') (°w°) (°v°) / \ / \ ``` ]
[Question] [ Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck! ## Job Description ### Input * You will receive a list of strings (the archive) and a string that needs to be added to that list (the document) * All strings will contain only uppercase letters, lowercase letters and spaces * Strings will always start and end with a letter ### Task Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows: * For each position: + Count the amount of strings in the archive before that position that are alphabetically before the document + Count the amount of strings in the archive after that position that are alphabetically after the document + Define the score of the position as the sum of the above two counts * The target position of the document is the position with the highest score * In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected. When sorting: * Uppercase and lowercase letters are equivalent * Spaces come before letters ### Output * The archive with the document added to it in any form OR * The target position of the document, in either a 0-based or 1-based index ### Job evaluation Fewest bytes wins! ### Example I/O ``` Archive: Applebuck Season Friendship is Magic The Ticket Master Griffon the BrushOff Boast Busters Bridle Gossip Document: Dragonshy Position scores (0-based index): 0: 0 + 3 = 3 1: 1 + 3 = 4 2: 1 + 2 = 3 3: 1 + 1 = 2 4: 1 + 0 = 1 5: 2 + 0 = 2 6: 3 + 0 = 3 Target position: 1 ``` [Answer] ## JavaScript (ES6), 81 bytes ``` (a,d)=>a.map((e,i)=>d[l="toLowerCase"]()<e[l]()?s--:++s>m&&(++m,p=++i),m=s=p=0)|p ``` Ungolfed: ``` function position(archive, document) { var score = 0; var max = 0; var pos = 0; var i = 0; while (i < archive.length) { if (archive[i++].toLowerCase() > document.toLowerCase()) { score--; } else { score++; if (score > max) { max++; pos = i; } } } return pos; } ``` Edit: Saved a lot of bytes thanks to @user81655. [Answer] # Pyth, ~~40~~ 38 bytes Credits to [@Katenkyo](https://codegolf.stackexchange.com/users/41019/katenkyo) for teaching me that `A xnor B` is basically `A==B`. (`A xor B` is also `A!=B`) ``` AQJ+],k0.e,rb0hkGteh.Msmq<hdrH0<edeZJJ ``` [Try it online!](https://pyth.herokuapp.com/?code=AQJ%2B%5D%2Ck0.e%2Crb0hkGteh.Msmq%3ChdrH0%3CedeZJJ&input=%5B%5B%22Applebuck+Season%22%2C%22Friendship+is+Magic%22%2C%22The+Ticket+Master%22%2C%22Griffon+the+BrushOff%22%2C%22Boast+Busters%22%2C%22Bridle+Gossip%22%5D%2C%22Dragonshy%22%5D&test_suite_input=%5B%22ssasd%22%2C%22a%22%2C%22q%22%5D&debug=0) How it works: It sums the XNOR of whether the entry is smaller than the document, and whether the entry's index is smaller than the document's index. It finds the position in which this sum is the maximum, then outputs it. [Answer] # Python 3, 135 167 Bytes ``` def a(b,c):a=[sum(map(lambda x:x.lower()>c.lower(),b[i:]))+sum(map(lambda x:x.lower()<c.lower(),b[:i]))for i in range(0,len(b)+1)];b.insert(a.index(max(a)),c);print(b) ``` [Answer] # Ruby, 97 bytes Anonymous function, returns the target position. ``` ->a,d{d.upcase!;(0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}}} ``` When actually inserting into the archive, **110 bytes**: ``` ->a,d{t=d.upcase;a.insert (0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}},d} ``` [Answer] ## Pyth, ~~54~~ ~~52~~ ~~47~~ 45 bytes ``` AQVhlG=Ys+m>rH0rd0:G0Nm<rH0rd0gGNI>YZ=ZY=kN;k ``` Expect input is a list, first element is a list of strings (archive), second element is a string (document) ``` AQ # initialize G and H with the archive and the document VhlG # iterate over the indexes on archive =Ys+ # concatenate and sum the following scores m>rH0rd0:G0N # map a string comparison between the document and the archives up to the index, returning true(1) for lower, and false(0) for higher m<rH0rd0gGN # same as above, but starts at the index and goes up to the end of the archive, returning false(0) for lower, and true(1) for higher I>YZ # Check if score is higher than highest =ZY # update highest score =kN; # update index k # print index ``` [Test here](https://pyth.herokuapp.com/?code=AQVhlG%3DY%2Bsm%3ErH0rd0%3AG0Nsm%3CrH0rd0gGNI%3EYZ%3DZY%3DkN%3Bpk&input=[[%22Applebuck+Season%22%2C%22Friendship+is+Magic%22%2C%22The+Ticket+Master%22%2C%22Griffon+the+BrushOff%22%2C%22Boast+Busters%22%2C%22Bridle+Gossip%22]%2C%22Dragonshy%22]&test_suite_input=[%22ssasd%22%2C%22a%22%2C%22q%22]&debug=0) * *Saved 5 bytes on input initialization (thanks @Kenny Lau)* [Answer] # [MATL](https://esolangs.org/wiki/MATL), 32 bytes ``` hk4#S4#S%2#0)>t0whYsw~0hPYsP+K#X> ``` Input is a cell array of strings (several strings separated by spaces and enclosed in curly braces) for the archive, and a string for the document. Output is 1-based. In case of a tie the first position is returned. [**Try it online!**](http://matl.tryitonline.net/#code=aGs0I1M0I1MlMiMwKT50MHdoWXN3fjBoUFlzUCtLI1g-&input=eydBcHBsZWJ1Y2sgU2Vhc29uJyAnRnJpZW5kc2hpcCBpcyBNYWdpYycgJ1RoZSBUaWNrZXQgTWFzdGVyJyAnR3JpZmZvbiB0aGUgQnJ1c2hPZmYnICdCb2FzdCBCdXN0ZXJzJyAnQnJpZGxlIEdvc3NpcCd9CidEcmFnb25zaHkn) ### Explanation ``` h % Concatenate archive and document as a cell array of strings k % Convert all strings to lowercase 4#S % Sort and output the indices of the sorting 4#S % Again. This gives the indices that applied to the concatenated % array would make it sorted 2#0) % Separate last index (document) from the others (archive) > % Is it greater? Gives zero/one array the size of the archive t % Duplicate that array 0wh % Prepend a 0 Ys % Cumulative sum. This is first part of the score w~ % Swap. Negate zero/one array 0h % Postpend a 0 PYsP % Reverse, cumulative sum, reverse. Second part of the score + % Add. This is the score of each position K#X> % Arg max ``` ]
[Question] [ The challenge is simple: Determine the type of an input, and output an identifier telling what type it is. * "UI", Unsigned integer: `0`, `1`,`34`, `111111111111111111111111111111111111111111` * "SI", Signed integer: `+0`, `+1`, `+42`, `-1`, `-3`, `-111111111111111111111111111111111111111111` * "UD", Unsigned decimal: `0.0`, `1.23`, `1234.1234` * "SD", Signed decimal: `-0.0`, `+0.0`, `-1.235` * "LE", Letter: `a`-`z` and `A`-`Z` * "SY", Symbol: ASCII code points: `[32-47, 58-64, 91-96, 123-126]` (i.e. all characters except numbers and letters) * "ST", String: Two or more character that can't be parsed as any of the above number formats **Rules:** * The input will be 1-99 characters long * The input will only contain printable ASCII characters, code points: 32-126. * The output should be the two identifier letters as defined above (UI, SI ...) * Standard I/O rules apply **Examples:** ``` UI: 0 01 34 12938219383278319086135768712319838871631827319218923 SI: -0 +01 +1 -123 +123 UD: 0.0 3.1415 2.718281828459045235360287471352662497757 SD: +0.0 -3.1415 +2.718281828459045235360287471352662497757 LE: a k L Z SY: @ " + - ST: Hello, World! f2!" +23df 1234A '"! .012 1. UI +-1 5+3 ``` [Answer] # JavaScript (ES6), 99 ``` x=>(z=x.match(/^([+-])?\d+(\.\d+)?$/))?'SU'[+!z[1]]+'DI'[+!z[2]]:x[1]?'ST':parseInt(x,36)?'LE':'SY' ``` **Test** ``` f=x=>(z=x.match(/^([+-])?\d+(\.\d+)?$/))?'SU'[+!z[1]]+'DI'[+!z[2]]:x[1]?'ST':parseInt(x,36)?'LE':'SY' console.log=x=>O.textContent+=x+'\n' ;console.log(['0','01','34','12938219383278319086135768712319838871631827319218923'].map(x=>f(x)+' '+x).join`\n`) ;console.log(['-0','+01','+1','-123','+123'].map(x=>f(x)+' '+x).join`\n`) ;console.log(['0.0','3.1415','2.718281828459045235360287471352662497757'].map(x=>f(x)+' '+x).join`\n`) ;console.log(['+0.0','-3.1415','+2.718281828459045235360287471352662497757'].map(x=>f(x)+' '+x).join`\n`) ;console.log([...'akLZ'].map(x=>f(x)+' '+x).join`\n`) ;console.log([...'@"+-'].map(x=>f(x)+' '+x).join`\n`) ;console.log(['Hello, World!','f2!"','+23df','1234A',`'"!`,'.012','1.','UI','+-1','5+3'].map(x=>f(x)+' '+x).join`\n`) ``` ``` <pre id=O></pre> ``` [Answer] # Turing Machine Code, 1544 bytes [Try it online!](http://morphett.info/turing/turing.html?5ef35b8f266f83c679eb72a62b9ac417) ``` 0 + _ r s 0 - _ r s 0 0 _ r u 0 1 _ r u 0 2 _ r u 0 3 _ r u 0 4 _ r u 0 5 _ r u 0 6 _ r u 0 7 _ r u 0 8 _ r u 0 9 _ r u 0 a _ r l 0 b _ r l 0 c _ r l 0 d _ r l 0 e _ r l 0 f _ r l 0 g _ r l 0 h _ r l 0 i _ r l 0 j _ r l 0 k _ r l 0 l _ r l 0 m _ r l 0 n _ r l 0 o _ r l 0 p _ r l 0 q _ r l 0 r _ r l 0 s _ r l 0 t _ r l 0 u _ r l 0 v _ r l 0 w _ r l 0 x _ r l 0 y _ r l 0 z _ r l 0 A _ r l 0 B _ r l 0 C _ r l 0 D _ r l 0 E _ r l 0 F _ r l 0 G _ r l 0 H _ r l 0 I _ r l 0 J _ r l 0 K _ r l 0 L _ r l 0 M _ r l 0 N _ r l 0 O _ r l 0 P _ r l 0 Q _ r l 0 R _ r l 0 S _ r l 0 T _ r l 0 U _ r l 0 V _ r l 0 W _ r l 0 X _ r l 0 Y _ r l 0 Z _ r l 0 * _ r y s 0 _ r s s 1 _ r s s 2 _ r s s 3 _ r s s 4 _ r s s 5 _ r s s 6 _ r s s 7 _ r s s 8 _ r s s 9 _ r s s . _ r d s _ _ r i s * _ r T u 0 _ r u u 1 _ r u u 2 _ r u u 3 _ r u u 4 _ r u u 5 _ r u u 6 _ r u u 7 _ r u u 8 _ r u u 9 _ r u u . _ r D u _ _ r I u * _ r T l _ _ r L l * _ r T y _ _ r S y * _ r T d 0 _ r d d 1 _ r d d 2 _ r d d 3 _ r d d 4 _ r d d 5 _ r d d 6 _ r d d 7 _ r d d 8 _ r d d 9 _ r d d _ _ r e d * _ r T i 0 _ r i i 1 _ r i i 2 _ r i i 3 _ r i i 4 _ r i i 5 _ r i i 6 _ r i i 7 _ r i i 8 _ r i i 9 _ r i i _ _ r j i * _ r T D 0 _ r D D 1 _ r D D 2 _ r D D 3 _ r D D 4 _ r D D 5 _ r D D 6 _ r D D 7 _ r D D 8 _ r D D 9 _ r D D _ _ r E D * _ r T I 0 _ r I I 1 _ r I I 2 _ r I I 3 _ r I I 4 _ r I I 5 _ r I I 6 _ r I I 7 _ r I I 8 _ r I I 9 _ r I I _ _ r J I * _ r T L * L r M M * E r halt S * S r Y Y * Y r halt e * S r f f * D r halt j * S r k k * I r halt E * U r f J * U r k T _ S r U T * _ r T U * T r halt ``` [Answer] # Retina, ~~98~~ 97 bytes A nice way to practise my regex skills indeed. [Try it online!](http://retina.tryitonline.net/#code=Xig_IVsrLV0_XGQrKFwuXGQrKT8kKS4uKwpTVApeKFsrLV0_KVxkKyQKJDFVSQpeKFsrLV0_KVxkK1wuXGQrJAokMVVECmlgXlthLXpdJApMRQpeLiQKU1kKWystXVUKUw&input=eg) ``` ^(?![+-]?\d+(\.\d+)?$)..+ ST ^([+-]?)\d+$ $1UI ^([+-]?)\d+\.\d+$ $1UD i`^[a-z]$ LE ^.$ SY [+-]U S ``` [Answer] # Lua, 157 bytes [Try it online!](http://www.lua.org/cgi-bin/demo) Golfed: ``` n=(...)m=string.match s=m(n,"^[+-]")and"S"or"U"print(m(n,"^[+-]?%d+%.%d+$")and s.."D"or m(n,"^[+-]?%d+")and s.."I"or m(n,"^%w$")and"LE"or#n==1 and"SY"or"ST") ``` Ungolfed: ``` n = "2.718281828459045" s = n:sub(1,1):match("[+-]") and "S" or "U" if n:match("^[+-]?%d+%.%d+$") then print(s.."D") elseif n:match("^[+-]?%d+") then print(s.."I") elseif n:match("^%w$") then print("LE") elseif #n==1 then print("SY") else print("ST") end ``` [Answer] ## JavaScript (ES6), ~~125~~ 120 bytes ``` s=>"UISIUDSDLESYST".substr(s.match(/^((\d+)|([+-]\d+)|(\d+\.\d+)|([+-]\d+\.\d+)|([A-Z])|(.)|(.*))$/i).indexOf(s,2)*2-4,2) ``` Alternative version, also 120 bytes: ``` s=>"STUISIUDSDLESY".substr(s.match(/^(?:(\d+)|([+-]\d+)|(\d+\.\d+)|([+-]\d+\.\d+)|([A-Z])|(.)|.*)$/i).lastIndexOf(s)*2,2) ``` [Answer] # Pyth - 47 bytes Can prolly golf a few bytes off with some slicing tricks. ``` .x-+?@z"+-"\S\U?@z\.\D\Isz?!tz?}rzZG"LE""SY""ST ``` [Test Suite](http://pyth.herokuapp.com/?code=.x-%2B%3F%40z%22%2B-%22%5CS%5CU%3F%40z%5C.%5CD%5CIsz%3F%21tz%3F%7DrzZG%22LE%22%22SY%22%22ST&test_suite=1&test_suite_input=0%0A01%0A34%0A12938219383278319086135768712319838871631827319218923%0A-0%0A%2B01%0A%2B1%0A-123%0A%2B123%0A0.0%0A3.1415%0A2.718281828459045235360287471352662497757%0A%2B0.0%0A-3.1415%0A%2B2.718281828459045235360287471352662497757%0Aa%0Ak%0AL%0AZ%0A%40%0A%22%0A%2B%0A-%0AHello%2C+World%21%0Af2%21%22%0A%2B23df%0A1234A%0A%27%22%21%0A.012%0A1.%0AUI%0A%2B-1%0A5%2B3&debug=0). [Answer] # Java, 192 bytes ``` String t(String v){for(String[]x:new String[][]{{"\\d+","UI"},{"[-+]\\d+","SI"},{"\\d+\\.\\d+","UD"},{"[-+]\\d+\\.\\d+","SD"}})if(v.matches(x[0]))return x[1];return (v.length()==1?"SY":"ST");} ``` [Answer] # Javascript (ES6), 138 bytes I tried to use a `replace` to be more "fancy". This creates an anonymous function that returns the string of the type. ``` s=>s.replace(/^((([+-])?(\d+)(\.\d+)?)|([a-z])|([ -~])|([^\0]*))$/i,(_,a,b,c,d,e,f,g)=>b?(c?'S':'U')+(e?'D':'I'):(f?'LE':'S'+(g?'Y':'T'))) ``` Any tips to improving this will be entirely welcome. [Answer] # Python 3.5 - 241 240 bytes: (*Saved 1 byte thanks to @CatsAreFluffy*) ``` import re def r(g): y={'^\d+$':'UI','^[+-]\d+$':'SI','^[0-9]\d*(\.\d+)?$':'UD','[+-](?=[0-9]\d*(\.\d+))':'SD','[a-zA-Z]+':'LE','^[^A-Za-z0-9]+$':'SY'};d=[y[i]for i in list(y.keys())if re.match(i,g)] if len(d)>0:return d[0] else:return'ST' ``` It may be a bit long, but does the job pretty much perfectly. This was a really good way to improve my regular expression skills. Thanks for the challenge. :) I will try and shorten it more if I can. [Answer] # Tcl 414 Bytes ungolfed implementation, readable: ``` proc a b { if {[string index $b 0] eq "+" || [string index $b 0] eq "-"} { set c S } elseif {[string match {[A-Za-z]} $b]} { return LE } elseif {[regexp {^(?![+-]?\d+(\.\d+)?$)..+} $b]} { return ST } elseif {[regexp {[^a-zA-Z0-9.]} $b]} { return SY } else { set c U } if {[string match *.* $b]} { return $c\U } else { return $c\I } } puts [a $argv] ``` ]
[Question] [ Given an input of a Spanish verb in its infinitive form, output the verb conjugated in all 6 forms of the indicative imperfect. To conjugate an infinitive in the imperfect, remove the infinitive ending (-ar, -er, -ir, and sometimes -ír) and add the imperfect endings listed below. There are three irregular verbs in the imperfect, also listed below. ``` Verb ending Replace with... -------------------------------------------------------- -ar -aba, -abas, -aba, -ábamos, -abais, -aban -er, -ir, -ír -ía, -ías, -ía, -íamos, -íais, -ían ``` ``` Irreg. verb Conjugations -------------------------------------------------------- ser era, eras, era, éramos, erais, eran ver veía, veías, veía, veíamos, veíais, veían ir iba, ibas, iba, íbamos, ibais, iban ``` For the purposes of this challenge, use capital letters instead of accented letters (á becomes A, é becomes E, and í becomes I). This is only because accented letters are 2 bytes in UTF-8, but they can be different in other encodings, and I'd rather not have to deal with any of that and stay within printable ASCII instead. Infinitive verbs will always be three or more characters long with the sole exception of the verb *ir*, will never contain accented letters with the exception of verbs that end in -ír, and will always end in either -ar, -er, -ir, or -ír. Reflexive verbs do not need to be handled. Output may be in either the form of a whitespace-/comma-separated string (so printing each conjugation to STDOUT on its own line is okay) or an array/list/etc. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Test cases: ``` In Out --------------------------------------------------------------- hablar hablaba hablabas hablaba hablAbamos hablabais hablaban comer comIa comIas comIa comIamos comIais comIan vivir vivIa vivIas vivIa vivIamos vivIais vivIan sonreIr sonreIa sonreIas sonreIa sonreIamos sonreIais sonreIan ser era eras era Eramos erais eran ver veIa veIas veIa veIamos veIais veIan ir iba ibas iba Ibamos ibais iban ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~100~~ 82 bytes ``` \B[^a]r$ I r$ b ^vI$ veI ^sI$ er $ a $ $_s $_ $_mos $_is $_n T`l`L`.(?=[^I]amos ) ``` [Try it online.](http://retina.tryitonline.net/#code=XEJbXmFdciQKSQpyJApiCl52SSQKdmVJCl5zSSQKZXIKJAphCiQKICRfcyAkXyAkX21vcyAkX2lzICRfbgpUYGxgTGAuKD89W15JXWFtb3MgKQ&input=aGFibGFy) Unfortunately, due to the use of `$_` it's not possible to modify the code to run all tests at once, so you'll have to copy in the individual verbs. I'm working on a new feature that will make this possible though. ### Explanation ``` \B[^a]r$ I ``` We start by turning all endings which aren't `ar` into `I`, provided the input isn't the irregular verb `ir`. That takes care of the `-er`, `-ir`, `-ír` conjugations, messes up the irregular verbs `ser` and `ver` (but shortens them in the process), and leaves only `ir` and `-ar` with a trailing `r`. ``` r$ b ``` If the word still ends in `r`, we replace that with a `b`. We've now covered all standard conjugations as well as the irregular verb `ir`. ``` ^vI$ veI ``` This fixes the irregular verb `ver` which has been turned into `vI` in the first stage. ``` ^sI$ er ``` This fixes the irregular verb `ser` which has been turned into `sI` in the first stage. Now we've modified all possible stems correctly. All that's left to do is append all the possible endings, and then fix the accent for the first person plural in some cases. ``` $ a ``` First we append an `a` to the stem, because that's always part of all endings. ``` $ $_s $_ $_mos $_is $_n ``` This makes use of the rarely seen `$_` which inserts the entire string into the substitution (regardless of what was matched). This is actually very useful when duplicating strings, as are `$`` and `$'`, which are also quite underappreciated. Before this stage, we've got the first person singular in the string. We now append the other conjugations, by matching the end of the string with `$` and building the other forms by appending the appropriate suffixes to the first person singular. ``` T`l`L`.(?=[^I]amos ) ``` Finally, we fix the accent for the first person plural if applicable. This only needs to be done for a vowel, two characters in front of the `-amos` *unless* the character in between is `I`. So we match such a character and then use a transliteration stage to convert lower to upper case. This makes use of the new character classes `l` and `L` which I only added yesterday. They expand to `a-z` and `A-Z` respectively, so that new feature saves 4 bytes here. [Answer] # Python 3, ~~154~~ 232 bytes ``` M=input() Q={'ser':'er','ver':'veI','ir':'ib'}.get(M) H=[(Q if Q else M[:-2]+("ab"if M[-2:]=="ar"else"I"))+j for j in"a as a amos ais an".split(' ')] if M[-2:]=="ar":H[3]=M[:-2]+"Abamos" if Q in['er','ib']:H[3]=H[3].title() print(H) ``` Fixed the missing capitals in irregular verbs. --- ### Ungolfed ``` M=input() Q={'ser':'er','ver':'veI','ir':'ib'}.get(M) H=[] for j in "a as a amos ais an".split(' '): if Q: F = Q else: if M[-2:] == "ar": F = M[:-2] + "ab" else: F = M[:-2] + "I" H += [F + j] if M[-2:] == "ar": H[3] = M[:-2] + "Abamos" if Q in ['er', 'ib']: H[3] = H[3].title() print(H) ``` [Answer] # [Milky Way 1.6.2](https://github.com/zachgates7/Milky-Way), 281 bytes ``` '?{"ser"b_^"er";_}?{"ver"b_^"veI";_}?{"ir"b_^"ib";_}?{_:y2->CH=<1-&{~>;+<1-}^>;+<;_^""0}?{"ar"b_"ab";>+<0_}?{_"I";>+<_^}^;^"an ais amos a as a"" "\?{<y__<^}=3&{~<:>;>;+!^<1-}^?{'C=^"a"b_'C:y2->=^^<ΩG"Abamos"+!^^_}?{<"er"b_"Eramos"!^^_}?{<"ib"b_"Ibamos"!^^_}J:y1-;=<&{~<:>;>;+!^<1-} ``` Well *that* took awhile! Looks like I need to add some builtins, hehe... --- ### Usage ``` ./mw <path-to-code> -i <input> ``` --- ### Examples ``` $ ./mw test.mwg -i "hablar" hablaba hablabas hablaba hablAbamos hablabais hablaban $ ./mw test.mwg -i "ver" veIa veIas veIa veIamos veIais veIan ``` [Answer] # Ruby, ~~151~~ 149 Normally, I'll choose a newline over a semicolon where possible in the interests of readability, but as there are no semicolons, this is a one liner. ``` ->n{%w{a as a amos ais an}.map{|z|['3r','veI','1b',n[0..-3]+(n[-2]==?a?'@b':?I)][("ser ver ir "+n).index(n)/4].tr('31@',['eia','EIA'][z.size/4])+z}} ``` A feature is the use of placeholders `31@` for the accented vowels which depend on the `amos` endings. Thus the correct stem is formed, and then the placeholder is substituted for one of `eia` or `EIA` as appropriate There a few uses of negative array indexes in here. Thus `n[-2]` refers to the second to last character of the input, and `n[0..-3]` refers to the input with the last 2 characters removed (the infinitive stem). Ungolfed in test program ``` f=->n{ %w{a as a amos ais an}.map{|z| #iterate through each verb ending ['3r','veI','1b', #array index 0,1,2 formats for irregular stems (note numbers 1 and 3 used as placeholders) n[0..-3]+(n[-2]==?a?'@b':?I)][ #array index 3 format for regular stems, AR->@b or ER/IR->I depending if A found at index -2 (@ used as placeholder) ("ser ver ir "+n).index(n)/4] #find index of input verb n in "ser ver ir "+n, divide by 4 to obtain 0,1,2,3 above .tr('31@',['eia','EIA'][z.size/4])+ #if z is 4 characters long (AMOS) replace 3,1,@ with uppercase E,I,A. Otherwise with lowercase e,i,a z #add the verb ending to the stem } } n=gets.chop puts f[n] ``` [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 153 bytes ``` i: ser=>era ver=>veIa ir=>iba ([]+)$1 {a,{e,i,I}} r=>$1 {ab,I} a c: ([]+)$1=>$1 ` $1 s ` $1 ` $1 mos ` $1 is ` $1 n j: i=>I/` _ bam e=>E/` _ ram ``` Ungolfed explained: ``` # turn the irregulars into their roots irreg: ser=>era ver=>veIa ir=>iba # do the same for everything else roots: ([]+)$1 {a,{e,i,I}} r=>$1 {ab,I} a # tack on the same endings conjugate: ([]+)$1=>$1 ` $1 s ` $1 ` $1 mos ` $1 is ` $1 n # fix the irregulars irreg2: i=>I/` _ bam e=>E/` _ ram ``` ]
[Question] [ # Background Due to some [unfortunate accident during coding](http://www.bestoldgames.net/img/ss/another-world/another-world-ss2.gif) you are now teleported and stranded on an alien planet. You really hope that the locals will be helpful and point to the general direction of how to get home, but before trying to talk to them you want to decipher their language. Fortunately it looks like the aliens were expecting this, and are actually displaying the grammar of their language near the place you got teleported. # Your task Your job is to write an LL(1) parser, that can determine whether a specific string belongs to the specified grammar or not and also return the rules that were used during parsing. Your fingers are a bit strained because of the teleporting, so you want to code this parser in as less characters as possible. Also it looks like for some weird reason there is free wifi there, but only wikipedia is available, so if you need help you can check how to [parse](https://www.wikiwand.com/en/LL_parser#/Parsing_procedure) an LL(1) grammar and how to [create the parsing table](https://www.wikiwand.com/en/LL_parser#/Constructing_an_LL.281.29_parsing_table) for it. # Input The first line of the input is the string you need to parse. The following lines will all include the available rules of the grammar, where the first character is the left hand side of the rule, and the rest of the line is the right hand side of the rule. Example input: ``` (a+a) SF S(S+F) Fa ``` Which describes that you have to determine whether `( a + a )` is part of the following grammar or not: ``` S → F S → ( S + F ) F → a ``` Notes on the input: * The grammar might contain empty (epsilon) rules, here the the right hand side is empty * All terminals and non terminals occupy exactly one character * Terminals are the following characters: `abcdefghijlkmnopqrstuvwxyz+-/*^%=()[]{}` * Non Terminals are the following characters: `ABCDEFGHIJKLMNOPQRSTUVWXYZ` * The starting non terminal is always `S` * You can assume that the grammar in the input is always a proper LL(1) grammar * A trailing newline may or may not be present, your choice. # Output The output should contain whether the string is part of the grammar or not, and if it is, it should also include the rules you had to use for parsing. Example output for the input above: ``` true S(S+F) SF Fa Fa ``` Variations on the output is allowed as long as it returns all information required. For example the following output is considered accepted as well: `1 [2,1,3,3]` (`1` because the string is accepted, then `[2,1,3,3]` are the rules used as an array, where each element represents the index of the rule in the input starting from one) # Scoring You have to write either a complete program (reading from STDIN) or a function (reading from a string). The output can either be done to STDOUT, or returned from the function in an appropriate way (like a `Pair<bool,int[]>`). Your point score is the byte count of the program, with the following penalties: * Add 10 to the byte count and square it, in case you are using a built in LL(1) parser of your chosen language * Add 100 to the byte count and square it, in case you are using a built in LL(2+), LR(1), LALR, SLR, or any other more advanced parser than LL(1) * Although they might not be more advanced than an LL(1), use the previous penalty if you are using regular expression features which are not considered part of a regular grammar (these penalties apply, since the teleporter messed up these built in functions a bit, and you have to magically fix them first) # Note: Normal regular expressions are allowed and don't count into the penalty, unless you use advanced regexp features which make your expression not a regular grammar anymore. Also using a built in LR(0) parser is okay (but probably not very helpful) # Lowest points win. If your language is not character based use the appropriate metric for your language and then apply the penalties on the resulting number. Standard loopholes apply, but solutions where the language was updated since the post was posted are allowed given you add the proper disclaimer to your post. # Examples In: ``` (a+a) SF S(S+F) Fa ``` Out: `1 [2,1,3,3]` In: ``` (aa) SF S(S+F) Fa ``` Out: `0` In: ``` a*(a+a) STE E+TE E TFU U*FU U F(S) Fa ``` Out: `1 [1,4,8,5,7,1,4,8,6,2,4,8,6,3,6,3]` In: ``` aaabbb SaA AaAb Ab ``` Out: `1 [1,2,2,3]` In: ``` aabbb SaA AaAb Ab ``` Out: `0` In: ``` aaabb SaA AaAb Ab ``` Out: `0` [Answer] # JavaScript (ES6), 177 bytes 177 looks like LL1 rotated 177°, so I stopped golfing. ``` s=>(f=(x,i)=>x<"A"||x>"Z"?v=s[i]==x&&[i+1,x]:s.split` `.some((r,a,j)=>v=r[0]==x&&[j=i,a=[a],...r].slice(3).every(y=>f(y,j)&&a.push(([j]=v)[1]))&&[j,a]))("S",0)&&s[v[0]]==0&&v[1] ``` [Try it online!](https://tio.run/##LY@xasQwEER7f4YKscKK8JEmhKxDGhdXJIW6CIGFkS8yvrPR@oQM9@@OAplqB@YNO5NLjoYY1u0pvRzDcqNl9mpeLnDWX5@KthhulzDuAAdhCyNClkFgm9/YB3s8csu@2XtCMsEiZs5NqE8y21dStM5h66te0XL1AFE6ORUwYTTNf3bCIB0aZ6VSKlpFcxg8PAvlk4877NiOsBeKc6fWO/0AmMliEuZkhfjjpSsHMM1kUzyZVKpLd8N5KplDQF@Bq52odFdp0HUnqs6Vl8qqK4ii4xc "JavaScript (V8) – Try It Online") Outputs `false` if the string does not match, otherwise outputs a nested array of rule indices and terminals: ``` [2,"(",[1,[3,"a"]],"+",[3,"a"],")"] ``` ## Ungolfed ``` str => (applyRule = (ruleName, index) => ruleName < "A" || ruleName > "Z" ? result = str[index] == ruleName && [index + 1, ruleName] : str.split("\n").some( (rule, appliedRules, jndex) => result = rule[0] == ruleName && ( jndex = index, appliedRules = [appliedRules], [...rule].slice(1).every(char => applyRule(char, jndex) && appliedRules.push(([jndex] = result)[1]) ) && [jndex, appliedRules] ) ) )("S", 0) && str[result[0]] == 0 // "\n" == 0 && result[1] ``` ``` function main(input) { const [str, ...rules] = input.split("\n") const result = applyRule("S", 0) if(result && result[0] === str.length) return result[1] function applyRule(ruleName, index) { if (ruleName === ruleName.toLowerCase()) return str[index] === ruleName ? [index + 1, ruleName] : null main: for (const [ruleIndex, rule] of rules.entries()) { if (!rule.startsWith(ruleName)) continue let curIndex = index let appliedRules = [ruleIndex + 1] for (const char of rule.slice(1)) { let result = applyRule(char, curIndex) if (!result) continue main curIndex = result[0] appliedRules.push(result[1]) } return [curIndex, appliedRules] } return null } } ``` [Answer] # Python3, 672 bytes ``` E=enumerate def F(b,g): if not b[0].isupper():yield b[0] for a,*B in g: if b[0]==a:yield from F(B*(B!=[' '])+b[1:],g) def T(a,g): q=[(a,b,[])for A,*b in g if A==a] for A,b,s in q: for i,j in enumerate(b): if j==a and b[i+1:]and not b[i+1].isupper():yield b[i+1] for J,*k in g: if j==J and j not in s:q+=[(J,b[:i]+k*(k!=[' '])+b[i+1:],s+[j])] def f(g): l,*g=g D={i[0]:{}for i in g} for i,(a,*b)in E(g): K=[*F(b,g)] for j in K:D[a][j]=i if' 'in K: for j in{*T(a,g)}:D[a][j]=i q,R=['S'],[] l+=[' '] while q: a,b=q.pop(0),l.pop(0) if a!=b: if a not in D:return q=[t for t in g[D[a][b]][1:]if' '!=t]+q;l=[b]+l;R+=[D[a][b]+1] return R ``` [Try it online!](https://tio.run/##dVJdi@IwFH3e/Iroi0kbZBxnYOmQh4r2wYF9sM5TNiwJ03aitV9WlkH87e5NWkVYBanpPTfn3HNPq@/2qyymP6vmfF7wpDjskka1CfpMUhwRzTIaIGxSXJQt1uJJjs3@UFVJQ2jwbZL80xURTssGK@bNsClwBjfsFYtwrvq@tCl3wDjzyGzAxQiPJPW1mAQSJJzamqhOreYCjpoJSS1tyDztaC1nCIS9XAgtewvUVs9WDNvY96sJoi2dm2UD97Aq7LjGB1F77CzB6z1TtmzvWt4l87ZXYxe6paPbOBbA9kHtw9xLpkVgpL/1yPbGptNke19sJJXObUqc15x5Gc8QnvOjgXUFx5Mz4tROqHcF2/A0hdKiu4TfufC6cGRv3Rl/D@ZCSdDgxiUA6q568WGbjl6359Ntb81WMGs8krBzmMnvBkf475fJk26/EAivx1VZkSfK8v7Q5awGXF/2rC77mAdN0h6awtYh0NYN4JBMOGUtpU3fTTngrfTrt5xD1c/fVjBA3@NS6Jjw6pxNMMfD4RAR5SuK4gjFJPYjiiKFbDl7xtz@K69vWC/QwrcPjNbRB/rw7AOjiMTXOyib9qRKKa01ilWIQhVqBL@u4eXacB9/vSX4H7dxt@WfrFG7nWpchD96S0J4Rl4TT03ewkf4qywShrPxvspNS0a/ixGFnBGqGlO0JCW3XBNK6V3g@REwfQS8PAJeATj/Aw) ]
[Question] [ In *Dungeons & Dragons*, almost everything is decided by rolling a die. Typically, if the roll is greater than or equal to a specified value, your attempt at doing whatever you wanted to do succeeds, and fails otherwise. Most commonly, a 20-sided die (aka d20) is used to roll. Other times, the skill challenge system is used. It is similar to the simple system described above, but success is determined by whether or not the player(s) succeed individual rolls a certain number of times before failing a certain number of times. For example, the player(s) may be trying to pick multiple locks on a door with a limited number of lockpicks. Individual successful rolls represent successfully picking one of the locks, and individual failing rolls represent breaking a lockpick. Overall success would mean successfully picking all of the locks before breaking all of the lockpicks. Furthermore, certain rolls can be critical rolls. On a d20, rolling a 1 is a critical failure, resulting in immediately failing the entire challenge (in the above example, the player(s) might accidentally alert a guard). Rolling a 20 is a critical success, resulting in immediately succeeding the entire challenge (in the above example, the player(s) might find a set of keys to the locks, removing the need to pick them). In the case of a critical roll, the challenge is immediately over and the outcome decided, regardless of the previous number of successes and failures. In this challenge, you will be given a difficulty, the number of successes needed, and the number of failures at which the challenge is failed. You must simulate a player attempting the challenge, and output the result. ### Input 3 integers, representing the value that must be met or exceeded to succeed at an individual roll, the number of successes needed to succeed at the challenge, and the number of failures at which the challenge is failed. The order and format of the inputs does not matter, as long as you specify what order you will be using. The difficulty will be between 1 and 20, inclusive, and the number of successes and failures will both be between 1 and 100, inclusive. ### Output The results of each of the d20 rolls (integers, in order), and the overall result of the challenge (a truthy/falsey value). The format does not matter, as long as the individual results are in order, the overall result either comes before or after all of the individual rolls (you can't output the overall result in the middle of the rolls, for example), and you specify what output format you use and use it consistently. ### Examples (values in parentheses are for explanation and need not be included): Input: ``` 12 5 3 (difficulty successes failures) ``` Output: ``` 15 (success, 1-0) 10 (failure, 1-1) 5 (failure, 1-2) 16 (success, 2-2) 12 (success, 3-2) 15 (success, 4-2) 19 (success, 5-2) True (overall success) ``` Input: ``` 15 2 3 (difficulty failures successes) ``` Output: ``` 0 (overall failure) 15 (success, 1-0) 12 (failure, 1-1) 13 (failure, 1-2) ``` Input: ``` 5 5 10 (successes failures difficulty) ``` Output: ``` 11 (success, 1-0) 5 (failure, 1-1) 20 (critical success) 1 (overall success) ``` Input: ``` 3 10 3 (failures difficulty successes) ``` Output: ``` 12 (success, 1-0) 11 (success, 2-0) 1 (critical failure) False (overall failure) ``` ### Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins * You must randomly choose an integer value between 1 and 20 (inclusive) for each roll. Each value should have an equal probability of being chosen (or as close to equal as possible). [Answer] ## Python, 134 bytes Thanks Pietu1998 for the bytes saved ``` from random import* def g(a,b,c): s,z=[],[c,b] while z[0]*z[1]:d=randint(1,20);z[a<d]-=[1,z[a<d]][d in[1,20]];s+=[d] return[z[0]]+s ``` Pretty simple, can probably be golfed a bit more, but we needed something to kick this off. [Try it online](http://ideone.com/fork/KrsMtc). [Answer] ## [Pip](http://github.com/dloscutoff/pip), 39 bytes [Someone said](http://meta.codegolf.stackexchange.com/questions/10531/what-are-some-functions-that-golfing-languages-tend-not-to-have-or-do-worse-tha/10534#comment34562_10608) they wanted to see a solution in a golfing language. ``` Wc&b{Pd:1+RR20d<a?--c--bc*:d>1b*:d<20}c ``` I'm pretty sure this doesn't use any language features newer than the question. Takes input as command-line args in this order: difficulty, successes required, failures required. Outputs 0 for overall failure or nonzero for overall success. [Try it online!](http://pip.tryitonline.net/#code=V2MmYntQZDoxK1JSMjBkPGE_LS1jLS1iYyo6ZD4xYio6ZDwyMH1j&input=&args=MTI+NQ+Mw) The approach is a fairly straightforward while-loop strategy, with a trick or two taken from other solutions. Here's a version with comments, whitespace, and some extra output: ``` ; a,b,c are initialized to the cmdline args ; a = difficulty (roll >=a succeeds, roll <a fails) ; b = required successes to succeed the task ; c = required failures to fail the task ; d = single die roll ; Loop while c and b are both nonzero: W c&b { ; d gets 1+randrange(20); output it O d:1+RR20 ; If d<a, decrement req'd failures, else decrement req'd successes d<a ? --c --b ; Verbose output for the ungolfed version P " (" . (d=1|d=20 ? "critical " "") . (d<a ? "failure" "success") . ")" ; If d=1, req'd failures is * by 0 (becomes 0), else * by 1 (unchanged) c *: d>1 ; If d=20, req'd successes is * by 0 (becomes 0), else * by 1 (unchanged) b *: d<20 } ; c, remaining failures, is the output: 0 if overall failure, nonzero if overall success c . " (overall " . (c ? "success" "failure") . ")" ``` [Answer] # JavaScript, ~~83~~ ~~78~~ ~~76~~ 75 bytes ``` F=(d,f,s)=>!s||f&&(r=~(Math.random()*20))+""+F(d,~r&&f-(k=d>-r),r+20&&s-!k) ``` This code recursively counts down successes and failures as they happen. When either successes (`s`) or failures (`f`) have counted down to `0`, we finish with the `true` value `!s` when `s` is `0` or with the falsy value of `f` when `f` is `0`. Output is of the regular-expression form `/^(-\d{1,2})+(0|true)$/` (or, more strictly, `/^(-[1-9]|-1[0-9]|-20)+(0|true)$/`). That is, the input has a leading hyphen, then roll values delineated by hyphens, and finally the ultimate outcome (`0` or `true`), which is not delineated from the final roll. However, this is still an unambiguous grammar because the utilmate outcome and final roll can always be distinguished: the last character of the output (either `0` or `e`) is always indicative of the outcome, and a final `0` is always read separately from the number(s) of the final roll. Sample outputs for `F(11,3,4)`: ``` -3-14-12-16-16true // normal success -2-12-20true // critical success -20true // first-roll critical success -18-2-8-14-18-90 // normal failure -18-12-10 // critical failure -10 // first-roll critical failure -4-16-4-100 // normal failure where last roll is a 10 ``` ## Explanation: This code works by rolling a *negative* d20 and (ab)using the negative signs as delimiters. ``` F=(d,f,s)=> // define function F(difficulty, fails, successes) !s|| // if zero more successes needed, return true f && // if zero more failures needed, return 0 (r=~(Math.random()*20) // add negative d20 to output, store in `r` +""+ // string concatenation F( // recursive call to F with changed fail/success d, // pass along d ~r // if r is -1, zero more fails needed &&f- // otherwise, reduce fails needed by (k=d>-r), // the boolean `d>-r` (and store in k) r+20 // if r is -20, zero more successes needed &&s-!k // otherwise, reduce successes needed by // the opposite of `k` (which indicates a fail) ) ] ``` Number-minus-boolean expressions work because `true` and `false` are cast to `1` and `0` in a numeric context. In this case, `d>-r` will be `1` if the roll is a failure and `0` if it was a success. [Answer] ## Python 2, 123 121 bytes ``` from random import* def f(a,b,c): while c*b: r=randint(1,20);print r;c-=r<a;b-=r>=a if r in[1,20]:return r>9 return c ``` (This answer [mixes spaces and tabs](https://codegolf.stackexchange.com/a/58/36885), so the first indentation level is a single space, while the second is a single tab.) The function `f` takes the following arguments: `a`, the threshold for an individual die roll to count as a success, `b`, the number of successes needed for overall success, `c`, the number of failures needed for overall failure. On each die roll either `b` or `c` is decremented (but not both). As long as both are positive, it loops again, except in the case of critical failure or critical success. Assuming no critical successes or failures, when the loop finishes either `b` or `c` will be zero, but not both. In that case the function just returns the current value of `c`, which is zero (Falsey) if we exhausted all of our failures, and positive (Truthy) if we succeeded. As a bonus, the output tells you how many failures you had remaining, which is nice in case there's (say) more locks to pick later. (Unless it terminated at a critical failure or success, in which case the output will be a boolean instead of an int.) [Answer] # Ruby 2.2, 75 bytes ``` f=->(v,s,f){p(r=rand(20)+1)<2?f=0:r>19?s=0:r<v ?f-=1:s-=1while s*f>0 p s<1} ``` Basic iterative solution. Example run: ``` f[12, 5, 3] ``` Might output: ``` 11 17 8 14 7 false ``` You can see it running on IDEONE [here](https://ideone.com/H854v3). [Answer] # VBA 180 Bytes ``` Sub P(d,s,f):k=1 Do While x<s And v<f:r=Int(20*Rnd()+1) If r=20 Then x=s If r=1 Then v=f If r>=d Then: x=x+1: Else: v=v+1 Debug.Print r:Loop:If v>=f Then k=0 Debug.Print k:End Sub ``` Example Output ``` P 12,5,3 18 2 19 8 11 0 ``` The last Digit of output will be a `0` for `False` or a `1` for `True` . Each Roll is separated by a newline. This uses VBA built in RNG `rnd()` which is know for being [Not So Random](https://stackoverflow.com/a/5893769/4676823) , But this should fulfill the requirements as best as possible. ``` Sub P(d,s,f) k=1 Do While x<s And v<f 'Keep Rolling while Current Successes and Failures are less then the Maximum Allowed r=Int(20*Rnd()+1) 'Creates a Randomish Number between 1 and 20 If r=20 Then x=s 'Checks for Crit Success If r=1 Then v=f 'Checks for Crit Failure If r>=d Then: x=x+1: Else: v=v+1 'Increments Current Success or Fails Debug.Print r 'Prints (Could us MSGBOX, it is shorter) Loop If v>=f Then k=0 'Checks & Changes Total Outcome to False Debug.Print k 'Prints (Could us MSGBOX, it is shorter) End Sub ``` [Answer] # SpecBAS - 165 bytes ``` 1 INPUT d,s,f 2 DIM p(2) 3 DO 4 r=1+INT(RND*20): ?r 5 IF r IN [1,20] THEN EXIT 6 INC p((r>=d)+1) 7 LOOP UNTIL p(1)>=f OR p(2)>=s 8 ?IIF$(r=1 OR p(1)>=f,"fail","success") ``` Input should be entered in difficulty, successes, failures order. The new release of SpecBAS now allows "?" instead of `PRINT` and removes the need for `LET` in front of variable assignments, so this was a nice way to try them out. As arrays are 1-based by default, line 6 returns 0/1 if roll beats difficulty and adds 1 to update the right index. [Answer] # [Perl 6](http://perl6.org), ~~101~~ 99 bytes ``` ->$/ {(1..20).roll(*).map({$1*$2||last;$2-=$0>$_;$2=0 when 1;$1-=$_>=$0;$1=0 when 20;$_}).eager,$2} ``` ``` # 101 bytes ->$/ { (1..20).roll(*).map({ # roll an infinite sequence, and map over them $1*$2||last; # stop if either counter is 0 $2-=$0>$_; # decrement failure counter when a failure $2=0 when 1; # set failure counter to 0 when a critical failure $1-=$_>=$0; # decrement success counter when a success $1=0 when 20; # set success counter to 0 when a critical success $_ # the rolled value }).eager,$2 # the value of failure counter } ``` Input is a mutable array containing difficulty, successes, failures Output is a two element list, first element is a list of the rolled values, second element is the number of failures remaining. Usage: ``` # give it a name for ease of use my &code = {...} for ^10 { say code [12, 5, 3] } ``` ``` ((14 4 15 5 5) 0) ((17 4 16 12 3 8) 0) ((2 14 14 7 14 19 19) 1) ((3 12 13 15 10 1) 0) ((3 17 16 10 11) 0) ((18 11 18 4 6) 0) ((15 13 1) 0) ((13 15 8 2 8) 0) ((16 17 8 10 11) 0) ((9 20) 2) ``` ]
[Question] [ ## Introduction There comes a point in childhood when you think you've mastered adding and multiplying, then someone comes along and informs you that: a \* b + c = (a \* b) + c != a \* (b + c), and that it wasn't as simple or linear a process as you were earlier taught. You learn that there exists something called the [order of operations](https://en.wikipedia.org/wiki/Order_of_operations). This is a very important way of keeping some level of consistency and in expressions, without having parentheses getting in the way of everything. ## Generic storyline One day, you wake up to the sound of panic in the streets. An extremist group under the name "*The 2560*" (Short for "Organisation Against the Order of Operations", with a dorky hex-ish twist) have used their evil methods to take control over all of the nuclear weapons in the world. They are holding the whole planet hostage, and they have a simple demand: reverse the accepted order of operations or face eradication (parentheses are to maintain their priority). The new system is called PSADME (parentheses, subtraction/addition, division/multiplication, exponents), and expressions evaluate right-to-left: ``` a - b - c = a - (b - c) = a + c - b ``` Days pass, and the transition is in progress. Whilst mathematicians and physicists are all busy rewriting their equations, the computer scientists are faced with the task of changing the fashion in which mathematical expressions are interpreted by computers. You belong to a secret rebel programming group which aims to cause as much torment for the new global overlords - and, by chance, you are randomly selected by *The 2560* and tasked to produce the benchmark calculation program. ## Your mission Write a program (or function) which takes a (numerical) mathematical expression as input, calculates the expression using **PSADME** as the order of operations and outputs the result. Expressions should evaluate right-to-left, so $$1 - 3 + 4 = 1 - 7 = -6.$$ For simplicity, all numbers provided will be integers, and the calculations will produce integer outcomes. ## Rules and scoring * The program should accept input up to 128 characters in length - if your language/platform has a lower maximum input length, that is an acceptable excuse. * Standard loopholes are forbidden. * The winning code will be chosen on 18th November (4 weeks from this post date). * Feel free to post code that would not be considered golf-worthy. This is about fun. If you have an interesting way of doing this but can't golf it yourself (or by the nature of your method), you can post it anyway. As per usual, the winning code is the one with least number of bytes, with some entertainment-value bonuses: * **-5** for avoiding any use of the characters in the provided expression: **+**,**-**,**(**,**)**,**^**,**\***,**/** * **-5** for making the calculations take more than 5 minutes (but no more than 10 minutes) to calculate on a standard computer, without the method being obvious (using the clock or unnecessary loops); The aim is to convince the new overlords that you are not *trying* to disrupt their calculations of doom. * **-(5+N)** for a direct offensive message (of length N, not including leading/trailing whitespace) about the members of The 2560 to be written in plain sight within your code, with some ridiculous explanation as to why it needs to be there. If it is removed, the code **must not** function correctly. Yes, free points for entertainment value. ## Examples and explanations ``` [program] 2 - 2 - 2 2 ``` 2 - (2 - 2) = 2 ``` [program] (2 + 2 * 3 + 3) / 3 + 3 4 ``` (4 \* 6)/(3 + 3) = 4 ``` [program] 3 + 2 + 1 ^ 3 216 ``` (3 + 2 + 1)^3 = 216 ``` [program] -5^2 25 ``` (-5)^2 = 25 ``` [program] 32 / 8 * 3 - 1 2 ``` 32 / (8 \* (3 - 1)) = 32 / 16 = 2 [Answer] # Haskell, 134 bytes ``` import qualified Prelude as P infixl 6 ^ (^)=(P.^) infixr 8 + (+)=(P.+) infixr 8 - (-)=(P.-) infixr 7 / (/)=P.div infixr 7 * (*)=(P.*) ``` Redefining the math operators with new fixities and priorities. Now: ``` *Main> 32 / 8 * 3 - 1 2 ``` [Answer] # GNU sed -r with exec extension, 398 ``` s@ *\^ *@ ** @ : s@\((-?[0-9]+)\)@\1@ t s@(-?[0-9]+ - )+(-?[0-9]+ - -?[0-9]+)@\1(\2)@ t s@(.*(^| |\())(-?[0-9]+ [-+] -?[0-9]+)(.*)@echo '\1'$((\3))'\4'@e t s@(-?[0-9]+ / )+(-?[0-9]+ / -?[0-9]+)@\1(\2)@ t s@(.*(^| |\())(-?[0-9]+ [*/] -?[0-9]+)(.*)@echo '\1'$((\3))'\4'@e t s@(-?[0-9]+ \*\* )+(-?[0-9]+ \*\* -?[0-9]+)@\1(\2)@ t s@(.*(^| |\())(-?[0-9]+ \*\* -?[0-9]+)(.*)@bash -c 'echo \1$[\3]\4'@e t ``` Not especially short, but gets the job done. sed is OK for parsing out the precedence but doesn't do arithmetic. So we use the GNU sed exec extension to the `s` command to outsource the necessary arithmetic to the shell. For now assumes all operators, with the exception of `^` have exactly one space in front and behind. ### Test output: ``` $ cat psadme.txt 2 - 2 - 2 (2 + 2 * 3 + 3) / 3 + 3 3 + 2 + 1 ^ 3 -5^2 32 / 8 * 3 - 1 $ sed -rf psadme.sed psadme.txt 2 4 216 25 2 $ ``` [Answer] # JavaScript (ES6) 287 ~~300~~ **Edit** Bug fixed (just a typo, 6 should have been 4) - Added a complete explanation at the end of the snippet **Edit 2** Found some improvement working on another challenge Yet another porting of the same parser with just some minimal difference. (compare with [this](https://codegolf.stackexchange.com/a/61486/21348)) ``` f=(x,W=[],Q=['('],z=1,h=p=>'+-*/^^))('.indexOf(p)>>1,C=n=>{for(;h(q=Q.pop())<h(n);W.push(q=='^'?Math.pow(a,b):eval(`a${q}b`)))a=W.pop(b=W.pop());z&&Q.push(q,n)})=>((x+')').replace(/\d+|\S/g,t=>t>'('?t>'('?~h(t)?z&&t=='-'?z=-z:C(t,z=1):(W.push(z*t),z=0):C(t,z=0):(Q.push(t),z=1)),W.pop()) // More readable U=(x,W=[],Q=['('],z=1, h=p=>'+-*/^^))('.indexOf(p)>>1, C=n=>{ for(;h(q=Q.pop())<h(n); W.push(q=='^'?Math.pow(a,b):eval(`a${q}b`))) a=W.pop(b=W.pop()); z&&Q.push(q,n) } )=>( (x+')') .replace(/\d+|\S/g,t=> t>'(' ?t>'(' ?~h(t) ?z&&t=='-'?z=-z:C(t,z=1) :(W.push(z*t),z=0) :C(t,z=0) :(Q.push(t),z=1) ), W.pop() ) // TEST console.log=(...x)=>O.innerHTML+=x.join` `+'\n' console.log(f('1 - 3 + 4')) // -6 console.log(f('2-2-2')) // 2 console.log(f('(2 + 2 * 3 + 3) / 3 + 3')) // 4 console.log(f('3 + 2 + 1 ^ 3')) // 216 console.log(f('-5^2')) // 25 console.log(f('32 / 8 * 3 - 1')) // 2 // Explained X=(x,W=[],Q=['('],z=1, h=p=> // operator priority '+-:1, */:3, ^:5, ):7, (:9. If an operand then -1 '+-*/^^))('.indexOf(p)>>1, C=n=>{ // Evaluate operators present on stack if they have upper priority, then push new operator on stack //console.log('Operand '+n) while( h(q = Q.pop()) < h(n) ) // pop operator from op stack and compare priority with current { // Pop operands from stack and push result b = W.pop(); a = W.pop(); r = q=='^' ? Math.pow(a,b) : eval('a'+q+'b') // console.log('Evaluate '+a+q+b+'='+r) W.push(r); } // if z == 0 do nothing, because the current operands are '(' and ')' that must be discarded // else Push again the last operator popped and the current one z && Q.push(q, n) // } )=>( (x+')') .replace(/[\d.]+|\S/g,t=> { //console.log('Q:'+Q,'W:'+W,'T:'+t,'U:'+h(t),'Z:'+z), // display status if (t == '(') { // open parenthesis z = 1 Q.push(t) // push a operator, its the highest priority } else if (t == ')') { //close parenthesis z = 0 C(t) } else if (h(t) < 0) { // operand W.push(z*t) // push operand with right sign z = 0 // set z to 0 to mark that we just pushed an operand, so next '-' (if present) is a binary operator } else { // operator if (z && t=='-') // the minus is an unary operator (the only unary operator allowed is '-', '+' will not work) z =-z // change the sign else z = 1, // no unary minus C(t) } }), W.pop() // return the value at top of operand stack ) ``` ``` <pre id=O></pre> ``` ]
[Question] [ ## Inspiration This question is inspired by the cards Throne Room and King's Court from the popular deck-building card game [Dominion](http://boardgamegeek.com/boardgame/36218/dominion). ![Throne Room](https://i.stack.imgur.com/F79Ao.jpg) ![King's Court](https://i.stack.imgur.com/EB47F.png) As part of one's turn, one plays a sequence of actions. These two particular actions cause the next-played action to repeat two or three times\*. Other "generic" actions cause specific game effects, but we won't be interested in the particulars, simply labelling them with letters. The interesting case is when a Throne Room or King's Court affects another Throne Room of King's Court, causing the doubling or tripling effect to itself be doubled or tripled. Long chains of Throne Rooms, King Courts, and multiplied actions can confuse even experienced Dominion players. Your goal is to write code that correctly resolves these chains, using as few bytes as possible. I'll describe the program requirements before explaining how the chains resolve in the Dominion rules. \*Technically, you choose the action affected as part of resolving Throne Room or King's Court, but this view is cleaner for this challenge. ## Program Requirements Write a *program* or *named function*. It should take in the chain of actions played (STDIN or function input), and output or print the resulting chain of actions from the effects of doubling and tripling. Fewest bytes wins. ## Input A string representing the sequence of actions played. Generic actions are represented by capital letters `A` through `Z`. The special doubling action Throne Room is represented by the character `2`, and the tripling action King's Court by `3`, The number of characters (actions) will be between 1 and 30, inclusive. You may have the input end in a newline if you wish. Example input: `WA23G3GA` ## Output A string of capital letters`A` to `Z`. This should be the sequence of generic actions that results from resolving the doubling and tripling effects, in the order than they happen. You may have the output end in a newline if you wish. There should be no additional characters otherwise. Example output: `WAGGGGGGAAA`. ## How doubling and tripling works in Dominion Here, I'll go through how chains of Throne Rooms (`2`'s) and King's Courts (`3`'s) work as per the Dominion rules. After you play a `2`, the next action to be resolved happens twice. So, if you first play `2`, then `A`, you get `A` happening twice. ``` 2A -> AA ``` Similarly, ``` A2BC -> ABBC 3DE -> DDDE 3N2BC3XY2 -> NNNBBCXXXY ``` Note in the last example that the final `2` had nothing to double, so it had no effect. The interesting thing happens when doubling or tripling effects are themselves doubled or tripled. For example, ``` 22AB -> AABB ``` First, you play `2`. Then, you play another `2`, which is doubled from the previous `2`. As a result, the next *two* actions are doubled. First, the two copies of `A` resolve. Then, the copies of `B` resolve. Note that `A` is not quadrupled: after the first copy of `2` acts on the first `A`, the next copy acts on the next unresolved action, which is `B`. Without the `B`, we'd have ``` 22A -> AA ``` where the second copy of `2` is waiting for the next action to double, but no action comes. Finally, let's look at a complex example. ``` 223BCDE -> BBBCCCDDE ``` As before, the first `2` causes the second `2` to be doubled. So, the next two actions will be doubled. The first copy of `2` doubles the next action `3`, which must be resolved completely before resolving the next copy of `2`. The first copy of `3` triples `B`, and the second copy triples `C`. Now, the still-waiting second copy of `2` doubles the next still-unresolved action, which is `D`. After this, no doubling or tripling effects remain, and the final action `E` simply happens. ## Test cases These are given as `(input,output)`. ``` (FY, FY) (A2BC, ABBC) (3DE, DDDE) (3N2BC3XY2, NNNBBCXXXY) (WA23G3GA, WAGGGGGGAAA) (32, ) (33RST, RRRSSSTTT) (2A32B2CDEFG, AABBCCDDEEFG) (A2A323AB2CD2D2E3ABC, AAAAAABBBCCDDDDEEAAABBBC) (P22LL3Q2Q22T, PLLLLQQQQQTT) (322322ABCDEFGHIJKLMN, AABBCCDDEEEFFGGHHIJKLMN) ``` [Answer] ## GolfScript (29 26 bytes) ``` ](1/{\1+(3&@*.23-\1$-@+}/; ``` [Online demo](http://golfscript.apphb.com/?c=OydGWQpBMkJDCjNERQozTjJCQzNYWTIKV0EyM0czR0EKMzIKMzNSU1QKMkEzMkIyQ0RFRkcKQTJBMzIzQUIyQ0QyRDJFM0FCQwpQMjJMTDNRMlEyMlQKMzIyMzIyQUJDREVGR0hJSktMTU4nbi97CgpdKDEve1wxKygzJkAqLjIzLVwxJC1AK30vOwoKXXB1dHN9LycnOm4%3D) ### Dissection This slightly abuses the loose typing of GolfScript. The stack of how many times to repeat subsequent actions starts out as an array and later turns into a string - but `1+` appends a 1 and `(3&` pops the first value and correctly puts it in the range `0` to `3` regardless of the type change. ``` ]( # Push an empty array under the input string to serve as rep stack 1/{ # Loop over the input string as a series of 1-char strings # Stack is ... reps ch # where the ... covers zero or more strings which will be output \ # Bring the rep stack to the top 1+( # Push a `1` on the bottom of it to avoid underflow and then pop 3& # Coerce to correct range, because if rep stack is a string then # we just got an ASCII value @* # Apply repetition to the 1-char string: it's now an n-char string .23- # Duplicate it and remove chars '2' and '3': this becomes output \1$- # Get the original copy and remove the output string's chars # So the stack is now ... reps output non-output # where non-output is either an empty string or a string of '2's # or '3's @+ # Push non-output onto the repetition stack }/ # Loop ; # Pop whatever's left of the repetition stack ``` [Answer] # Javascript - ~~162~~ 152 bytes Minified: ``` F=I=>{L=c=>S.length;p=c=>L()?S.shift():d=>{};S=[(x=>/\d/.test(x)?(c,b)=>{for(c=p(),b=x;b--;)c();}:c=>s+=x)(m)for(m of I)];for(s='';L();)p()();return s;} ``` Expanded: ``` F = I => { L = c => S.length; p = c => L() ? S.shift() : d => {}; S = [ (x => /\d/.test( x ) ? (c,b) => { for( c = p(), b = x; b--; ) c(); } : c => s += x )(m) for( m of I ) ]; for( s = ''; L(); ) p()(); return s; } ``` I'm guessing the stack-based golf languages will kill on this one, since it's basically an exercise in function stacking. :P ### Sample Outputs ``` F('3N2BC3XY2') "NNNBBCXXXY" F('WA23G3GA') "WAGGGGGGAAA" F('A2A323AB2CD2D2E3ABC') "AAAAAABBBCCDDDDEEAAABBBC" F('322322ABCDEFGHIJKLMN') "AABBCCDDEEEFFGGHHIJKLMN" F('FY') "FY" F('') "" ``` [Answer] # C, 115 111 bytes Uses standard input/output. Saved 4 by using `memset` and making the stack go in the other direction. ``` char*i,X[222],*s=X+99;main(){for(gets(i=X);*i;i++)*i<55?s=memset(s-*s,*i-49,*s+1):putchar(*i)**s?--*s,--i:++s;} ``` **Ungolfed** ``` #include <stdio.h> #include <stdlib.h> char I[99], S[99], *i = I, *s = S+66; int n; int main() { gets(I); for(;*i;) { if(*i < '5') { n = *s; s[0] = s[1] = s[2] = *i - '1'; s += n; i++; } else { putchar(*i); if(*s) --*s; else --s, ++i; } } return 0; } ``` [Answer] ## Python (84) ``` S='1'*99 R='' for c in input():q=int(S[0])*c;S=q*(c<'A')+S[1:];R+=q*(c>'3') print(R) ``` `S` is the stack of multipliers (top if front). It's initialized with enough `1`'s to handle unmultiplied actions. Depending on whether the current action `c` is generic or not, we add its multiplied result either to the output `R` or to the stack of multipliers `S`. Everything is represented as a string rather than a list of chars. Because strings are immutable, we unfortunately can't use `pop` or element assignment on them. ]
[Question] [ The [Stern-Brocot tree](http://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree) is a binary tree of fractions where each fraction is acquired by adding the numerators and denominators of the two fractions neighbouring it in the levels above. It is generated by starting with `0/1` and `1/0` as "endpoint fractions", and from there, iterating by placing one fraction between each consecutive pair of fractions by adding the numerators and denominators of those fractions together, like so: ``` 0. 0/1 1/0 1. 0/1 1/1 1/0 2. 0/1 1/2 1/1 2/1 1/0 3. 0/1 1/3 1/2 2/3 1/1 3/2 2/1 3/1 1/0 4. 0/1 1/4 1/3 2/5 1/2 3/5 2/3 3/4 1/1 4/3 3/2 5/3 2/1 5/2 3/1 4/1 1/0 ``` In each iteration of the Stern-Brocot tree (the `n`th iteration), there are `2^n + 1` elements in the sequence, to which we can ascribe a fraction from `0/2^n` to `2^n/2^n`. Each new iteration simply inserts one fraction "halfway" between each pair of consecutive fractions. This makes the Stern-Brocot tree a one-to-one mapping between the positive rational numbers and the binary fractions between 0 and 1, thereby also serving as a proof that the two sets have the same cardinality. Your task is to write a program or function that, given the numerator and denominator of a positive rational number in lowest terms, determines the binary fraction that corresponds to that fraction's position in the Stern-Brocot tree. Examples of inputs and outputs are provided below: ``` 2/3 -> 3/8 (4th number in iteration 3) 4/7 -> 9/32 (between 1/2 and 3/5 in the chart above) 1/1 -> 1/2 (middle number in the first iteration) ``` Inputs you don't need to support, but are included for reference: ``` 0/1 -> 0/1 (0/1 is considered the left number) 1/0 -> 1/1 (1/0 is considered the rightmost number) ``` The shortest program in any language to achieve this goal wins. [Answer] # [Python 3](https://docs.python.org/3/), ~~98~~ 83 bytes ``` f=lambda a,b,n=1,d=2:a>b and f(a-b,b,n*2+1,d*2)or a<b and f(a,b-a,n*2-1,d*2)or(n,d) ``` [Try it online!](https://tio.run/##PcyxCsIwFIXh2T7FGXPjzZCkIBTji4jDDSFY0DSUDvXpYzPo9MP54NTP9lyKby2Hl7xjEghHLsFyCm6SW4SUhKzExL5rdz5EO1pWyPWPHI10ND9UhRO1HQF3ZRmWGMoxfO/IuPR6xkiPIR9XFXPBPg2nus5lU1npStS@ "Python 3 – Try It Online") Explanation: The sequence of turns starting from 1 down to the given fraction in the Stern-Brocot tree is identical to the sequence of turns starting from the given fraction going to 1 in the Calkin-Wilf tree. This makes it much simpler to get the sequence. *Improvement given by Bubbler. Original solution [here](https://tio.run/##FYzBDoMgEETP9SumN7DrATVpYkN/pOkBA0QSgwRtar@eLped3Tczm37HssWhFOs8vDA0U9SKrO7l1OC7hNUJc9VzvRBb3T8sD94Dh5@MDedNx62bYurW3U31xdyx0THK7vjkiEi2nNB4CUVQkiB6wlB1JNyrDoRRvhu/ZSSEiHNqLimHeAgv2iRl@QM).* [Answer] ## GolfScript (49 48 46 chars) ``` {0\@{}{@2*2$2$>!+@@{{\}3$)*}:j~1$-j}/\)\,?}:f; ``` or ``` {0:x;\{}{.2$<!2x*+:x){\}*1$-{\}x)*}/x@)@,?}:g; ``` Both are functions which take the numerator and denominator on the stack and leave the numerator and denominator on the stack. [Online demo](http://golfscript.apphb.com/?c=OwoKezBcQHt9e0AyKjIkMiQ%2BIStAQHt7XH0zJCkqfTpqfjEkLWp9L1wpXCw%2FfTpmOwp7MDp4O1x7fXsuMiQ8ITJ4Kis6eCl7XH0qMSQte1x9eCkqfS94QClALD99Omc7CgoyIDMgZl1wCjQgNyBmXXAKMSAxIGZdcAoyIDMgZ11wCjQgNyBnXXAKMSAxIGddcAo%3D). The core idea is expressed in pseudocode in *Concrete Mathematics* section 4.5 (p122 in my edition): ``` while m != n do if m < n then (output(L); n := n - m) else (output(R); m := m - n) ``` If the string of Ls and Rs is interpreted as a binary value with L=0 and R=1 then twice that value plus one is the numerator, and the denominator is one bit longer. As a point of interest to Golfscripters, this is one of those rare occasions when I've found unfold useful. (Ok, I only use it as a loop counter, but that's better than nothing). [Answer] ## Ruby (69 chars) CoffeeScript (59 chars) This is a function which takes numerator and denominator as arguments and returns an array containing the numerator and denominator after the bijection. ``` g=(a,b,x=0,y=1)->c=a>=b;a&&g(a-b*c,b-a*!c,2*x+c,2*y)||[x,y] ``` [Online demo](http://jsfiddle.net/9gv3T/) It uses the same approach as my GolfScript solution above, but is much more readable because I can use 4 variables without having to worry about boxing and unboxing into an array. I chose CoffeeScript because it doesn't prefix variables with `$` (20 chars saved over e.g. PHP), has short function definition syntax which allows default parameter values (so there's no need to wrap `f(a,b,x,y)` in a function `g(a,b) = f(a,b,0,1)`), and lets me use Booleans as integers in expressions with useful values. For those who don't know it, CoffeeScript doesn't have the standard C-style ternary operator (`C?P:Q`), but I'm able to substitute `C&&P||Q` here because `P` will never be falsy. An arguably more elegant, but inarguably less short, alternative is to replace the repeated subtraction with division and modulo: ``` f=(a,b,x=0,y=1,p=0)->a&&f(b%a,a,(x+p<<b/a)-p,y<<b/a,1-p)||[x+p,y] ``` (65 chars; [online demo](http://jsfiddle.net/v3kDj/)). Writing it this way exposes the relationship with Euclid's algorithm. [Answer] # Mathematica, ~~130 114~~ 111 chars ``` f=#~g~0&;0~g~q_=q;p_~g~q_:=g[#,(Sign[p-#]+q)/2]&@FromContinuedFraction[ContinuedFraction@p/.{x___,n_}:>{x,n-1}] ``` ### Example: ``` f[2/3] ``` > > 3/8 > > > ``` f[4/7] ``` > > 9/32 > > > ``` f[1] ``` > > 1/2 > > > [Answer] ## Ruby, ~~132~~ 125 Rubied & golfed the reference solution from @JoeZ. ``` def t(n,d)u=k=0;v,j,f,g,b=[1,]*5;c=2 while(z=(f*d).<=>(g*n))!=0;z>0?(j,k=f,g):(u,v=f,g);b=b*2-z;f,g=u+j,v+k;c*=2;end [b,c]end ``` Usage examples: ``` >> t(2,3) => [3, 8] >> t(4,7) => [9, 32] >> t(1,1) => [1, 2] ``` [Answer] # Mathematica 138 Not as streamlined as alephalpha's procedure, but it was the best I've been able to produce so far. ``` q_~r~k_:=Nest[#+Sign@k/(2Denominator@# )&,q,Abs@k] g@d_:= Module[{l=ContinuedFraction@d,p=-1}, l[[-1]]-=1; (p=-p;# p)&/@l] h[q_]:=Fold[r,1/2,g@q] ``` Testing ``` h[2/3] h[4/7] h[1] ``` > > 3/8 > > 9/32 > > 1/2 > > > [Answer] # [Haskell](https://www.haskell.org/), 125 bytes ``` n((a,b):(c,d):r)=(a,b):(a+c,b+d):n((c,d):r) n a=a z=zip[0..] t x=[(j,2^i)|(i,r)<-z$iterate n[(0,1),(1,0)],(j,y)<-z r,x==y]!!0 ``` [Try it online!](https://tio.run/##TYzBCoMwEETvfsUKHja4lWgLBXH7I8FCtELT2iBpDir99zQWDz3OvHlz1@/nMI4hWERNnaixp5uoneA96rynLo9VHOwosaBZJyuvZlKyKNrEw8wKH1RdjfigISeaw5oZPzjtB7AKJZWCsCQpWoq7ZePgaGZe2jSV4aWNBYbJGeshAw9NdgGFFR2jdqLzT94u/o7CFw "Haskell – Try It Online") Input and output in the form of a pair `(n,d)`. Brief Explanation: `n` constructs the next row from the previous one by looking at each pair of fractions and inserting the new one between the first and the recursion (which will put the second fraction right there). The base case is very simple since it's basically just the identity function. The `t` function iterates that function indefinitely based off the initial state with just the two boundary fractions. `t` then indexes each row (`i`) and each item in the row (`j`) and looks for the first fraction that matches what we're looking for. When it finds it yields `j` as the numerator and `2^i` as the denominator. [Answer] # Python - 531 An ungolfed solution in Python, to serve as a last-place reference solution: ``` def sbtree(n, d): ufrac = [0, 1] lfrac = [1, 0] frac = [1, 1] bfrac = [1, 2] while(frac[0] * d != frac[1] * n): if(frac[0] * d > frac[1] * n): # push it towards lfrac lfrac[0] = frac[0] lfrac[1] = frac[1] bfrac[0] = bfrac[0] * 2 - 1 elif(frac[0] * d < frac[1] * n): # push it towards ufrac ufrac[0] = frac[0] ufrac[1] = frac[1] bfrac[0] = bfrac[0] * 2 + 1 frac[0] = ufrac[0] + lfrac[0] frac[1] = ufrac[1] + lfrac[1] bfrac[1] *= 2 return bfrac ``` It simply does a binary search between fractions, taking advantage of the fact that the [mediant](http://en.wikipedia.org/wiki/Mediant_%28mathematics%29) of any two fractions will always between the values of those two fractions. [Answer] ### GolfScript, 54 characters ``` '/'/n*~][2,.-1%]{[{.~3$~@+@@+[\]\}*].2$?0<}do.@?'/'@,( ``` Input must be given on STDIN in the form specified in the task. You may try the code [online](http://golfscript.apphb.com/?c=OyI0LzciCgonLycvbip%2BXVsyLC4tMSVde1t7Ln4zJH5AK0BAK1tcXVx9Kl0uMiQ%2FMDx9ZG8uQD8nLydALCg%3D&run=true). ``` > 4/7 9/32 > 9/7 35/64 > 5/1 31/32 ``` [Answer] # JavaScript 186 ``` f=(p1,q1,p2,q2)=>{if(p1*q2+1==p2*q1){return{p:p1+p2,q:q1+q2}}let p,q,pl=0,ql=1,ph=1,qh=0;for(;;){p=pl+ph;q=ql+qh;if(p*q1<=q*p1){pl=p;ql=q}else if(p2*q<=q2*p){ph=p;qh=q}else return{p,q}}} ``` could be less, but I like readable golf ]
[Question] [ Special thanks to [Bubbler](https://chat.stackexchange.com/transcript/message/53206244#53206244) and [AdmBorkBork](https://chat.stackexchange.com/transcript/message/53253206#53253206) for supplying feedback about this challenge **Keta** (**Ke**yboard **ta**cit — clever naming, I know!) is a golfing language I’ve been working on recently. One of it’s features is it’s *most probably* unique bracket autocompletion system, which will hopefully allow for shorter programs. There are two types of brackets in Keta: grouping brackets (`[]` and `{}`) and list brackets (`()`). This challenge only involves completing grouping brackets. Much like it’s predecessor Keg, Keta will automatically close any open brackets within your program. For example: ``` [3+H ``` Will be turned into ``` [3+H] ``` And: ``` {0L100R3 ``` Will be turned into: ``` {0L100R3} ``` Obviously, matched brackets won’t be autocompleted, as they are already fully closed. Now, this may seem like a very trivial challenge, but I ain’t done yet. Keta will also close open closing brackets as well. More specifically: ``` H+4} ``` Turns into ``` {H+4} ``` But what happens if two bracket types are mixed together? For example: ``` P[DD+s}S3 ``` In cases like this, the opening bracket will complete up until a non-matching closing bracket. The closing bracket will then complete up until the start of the string. This means our above example will turn into: ``` {P[DD+s]}S3 ``` More concisely: > > [S]can left to right, maintaining a stack of open brackets. If I meet a non-matching closing bracket, close the open one(s) until they match or stack is empty. If the stack is empty, put a matching open bracket at the beginning instead. If the stack is nonempty at the end of the string, close all of them. ~ [Bubbler](https://chat.stackexchange.com/transcript/message/53206244#53206244) > > > ## The Challenge Given a string of potentially unmatched brackets, autocomplete the brackets as described above. ## Test Cases ``` Input -> Output [3+H --> [3+H] {0L100R3 --> {0L100R3} H+4} --> {H+4} P[DD+s}S3 --> {P[DD+s]}S3 3+HH} --> {3+HH} {abc --> {abc} (3..12)S4] --> [(3..12)S4] [0L100 --> [0L100] A[BC}D --> {A[BC]}D x{yz]a --> [x{yz}]a [AbC] --> [AbC] {12345678} --> {12345678} A[bc} --> {A[bc]} X{yz] --> [X{yz}] 'Hello, World!' --> 'Hello, World!' AB(CD{EF]GH --> [AB(CD{EF}]GH AB(CD}EF]GH --> [{AB(CD}EF]GH AB[CD{EF]GH --> AB[CD{EF}]GH AB[CD[EF}GH --> {AB[CD[EF]]}GH AB{CD]EF]GH --> [[AB{CD}]EF]GH A[bc --> A[bc] A{bc --> A{bc} [ --> [] { --> {} ] --> [] } --> {} --> ``` Note that the last test case represents a literally empty string. ## Rules * Input can be taken in any convenient and reasonable format. * Output can be given in any convenient and reasonable format. * The input string will be limited to printable ASCII characters, although it may be empty. * An ungolfed reference program can be found [here](https://tio.run/##hVRbb9owFH7Pr3D90iAugsK6CamTKJfxUK1VmbRJrhWZYEq01ImSoK2L8tvZOacJYMI6v9g@3znfudrxa7aJTH@3W@k1W6pQGV97y0T5P3WWummWBOa5MXQYrERn7IZxTpdKBSQ5F5wNGZe8RdDx4jlBBS8cwlSYkYUksbAtQA2leaV8/zD92mLju/vFFB2LnLfAS2EF4KUZ7AALSWKd@irWKxDMVJhqkq2jhAUsMCxR5lm7oTZVYmVmuPyNAsZMJ2D6hopA7tFgXTEPrRyxJk2I7emJs@aBw9LxI5MFZqudY7Yjd2/mNu8hjW/JVp@lY@fpIE2sm01nFauj4liblbu3aRwi0@EpGZXfZrMuvzZBqE@6oczKloh2T7KLG2y/2LPLYW1cynJWwyXsuOModhvSsawgXEvpn5zne1MvDjmxewFzdJ72NCEYAfJ25Ow/k1ALznk/KRxlH9vyTtKnRfTLkoF8mxjcask4jgM@Pc@oF@15NJKe96IC43nlYGY6pccuuOg35/gQ8@5dr9t97ON53hwUuD@IyaSZFgsSgt6cpLla@qd/A3f7nU7vqrEYSFQRRIankbgdFxM8/c5f/0hF6Gg5JrW8d9UffLj@@Kmo8Y3E0idvP9AMD5dzHYZRi32PknB1cUnkt@54kk9n8su8ToBYUWJ4FQfV8iqms6K65uOJ3KO8LDG2ByuFHaKKHToTw5eSuSgE/Xb7M5jVvltEG/Aad7u/ "Python 3 – Try It Online") ## Scoring Of course, this is code golf, so the answer *in each language* consisting of the fewest number of bytes wins. Happy golfings! ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=198087; var OVERRIDE_USER=78850; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} #language-list h2{color:#215F06} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~74~~ 68 bytes ``` FS«W∧υ›№]}ι⁼§υ±¹ι≔⁺ω⊟υω≔⁺ωιω≡ι]F¬∧υ⊟υ≔⁺[ωω}F¬∧υ⊟υ≔⁺{ωω[⊞υ]¦{⊞υ}»ω↑⮌υ ``` [Try it online!](https://tio.run/##jZC9a8MwEMXn@K84NJ3AHbImkymlZAkmpZPxoMoXWyBkVx9xwehvdy0noV9LbxL3e@/dQ7ITVvZCz/O5t4AHMwT/4q0yLXIOU7YZO6UJsDANhhyeLQlPFh/7YDyyOrIcFM/h6T0I7bDwB9PQR1IeqV2UuOU8KZaBwjnVGix1cDjmUPYDhkRHvs82v6C6792ovOwA1VpGCkfAaraDte2x9/dit7SfV1jFUswt6mqO/zZPf83VYi6D65JpqfEFpu8griBmMSuXj/SYAq6v3euQw4kuZB2li/t5FtVblHUzUXWeHy76Ew "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS« ``` Loop over the characters of the input. ``` W∧υ›№]}ι⁼§υ±¹ι≔⁺ω⊟υω ``` If the current character is a closing bracket and we're expecting the other sort of closing bracket then append that bracket now. Keep doing this until we run out of other closing brackets to insert. ``` ≔⁺ωιω ``` Append the current character. ``` ≡ι]F¬∧υ⊟υ≔⁺[ωω}F¬∧υ⊟υ≔⁺{ωω[⊞υ]¦{⊞υ} ``` Switch on the current character. If it's a closing bracket, then remove the (now) matching closing bracket, but if that can't be done then prepend the desired matching opening bracket. If it's an opening bracket, then just save the desired matching closing bracket. ``` »ω↑⮌υ ``` After all the characters have been processed, output the processed characters (now including autocompleted missing opening brackets and wrong closing brackets), and then any remaining missing closing brackets. [Answer] # JavaScript (ES6), ~~145~~ 142 bytes ``` s=>[...s].map(c=>o+=(i=(S='[]{}').indexOf(c)^1)&1?(s=S[i]+s,c):i<0?c:(g=_=>s?(C=s[s=s.slice(1),0])==c?c:C+g():(p=S[i]+p,c))(),s=o=p='')&&p+o+s ``` [Try it online!](https://tio.run/##jZLRTtswFIbv9xRdLxpb6UJCy4aquRUk23qBtIleDMk6TMFNq0xZHeFpYrP87MUOFIKPJ5HLL99/8vvEP8s/pRK3dfv73U6uq/2G7RWb8yRJFCS/ypYINpcxIzUjKxZx0CaiSb1bV3dfN0TQ64yOsgVRbMVriNVY0Fn9MV2IGdmyH2yuFiRniiumEtXUoiIZHadAGRNWyeMtoTPSPmRbm6WEjhWTrGVRREejNpax2gu5U7KpkkZuyYYM@SReDikd9J6jo4Gj8MZTdXqRpenlpKdb9UCNry/jqcGTtcO@@o0XRazMqjfaqQ8YLPcDtt7SG@4CHUa1yxsR6GEpUskkSbJjuprCU8At4xn7Ad4d/sV0F@goks/4eW4KX9YOgyl8@07//QclGu2wgRIVObvJAS2ko2gf2fFkevL@w6npH/KZ4tp2U3jXDgOSr1xr3OOqa@3L0bJqGjkefJe3zfpt5GJW9iiqc07yQn/6DF@e7m130kdsLA9GDIroHscRHvjKgZr/Jbh99yKhDxjAhDI6LwAV4x03EG7GQ9e5@xtI1UFVB24@97zHJvjyBD2N5sEr55lXzsOa84bD/T0 "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 269 bytes ``` \[(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))(?=}|$) $&] \{(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))(?=]|$) $&} ^(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)$)] [$& }`^(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)$)} {$& ``` [Try it online!](https://tio.run/##pY1PT4NAEMXv71PYBOmuKIEF/xxsCYW2HDwYe9Bk2aZQezAhNqke1GU@Ox2LJp5rMpn85r2ZN7vN@8tr1Z2K@aorteBKRv6ZMFK2pe05uVVj4lkvjSZrWhYu1LhUUrInlBTJQHIbUetIOK4BH/4nx/Q5hOVRMY400I4LWh17T7CO23U68grY4C4MgocIhRcT7nWee2@0iMBewXtVvYaIfD9UchHz38M2Uj3JKMeH/fwyFXRaZwY2VFF8eXV9Q2zXa8LTt4thsWma7fnJ43bXPA@GSCciy@10ZuZFz/TL@o/OrKczOrDNcvOjcy5Sy03DwoCwBw "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: In .NET, the regex `(\[(?=.*(]))|\{(?=.*(?<2>}))|[^][}{]|(?<-2>\2))*(?(2)(?!))` matches a string containing only balanced brackets. This is broken down into four alternatives, which are repeated, and then the capture group is checked for emptiness (this can be done more golfily in the latter cases), proving that all brackets have been balanced. It then remains to match the appropriate mismatched brackets and/or start/end and insert the correct matching bracket. Finally, the whole script is repeated using `}`` until all mismatched brackets have been autocompleted. ``` \[(?=.*(])) ``` Match a `[` and capture a `]` (which happens to be capture group `2`). ``` \{(?=.*(?<2>})) ``` Match a `{` and capture a `}`, but name this capture group `2` as well. ``` [^][}{] ``` Match anything that isn't a bracket (under this question's definition). ``` (?<-2>\2) ``` Match the last closing bracket that we captured earlier, and then forget that bracket, so that the previous closing bracket becomes the next potential match. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 246 bytes Input is taken as a list of ASCII character codes while ouput is printed to stdout. The approach is a straightforward translation of the algorithm described in the post into Prolog. ``` \T:-T+D+[],maplist(put_code,D). []+[]+[]. X+[D|U]+S:-X=[],S=[O|Z],D is O+2,X+U+Z;X=[H|T],(D=H,(\+H^`[]{}`,T+U+S;H^`]}`,O is H-2,(S=[O|Z],T+U+Z;S=[],put_code(O),T+U+S);H^`[{`,T+U+[H|S]);S=[O|V],H^`}]`,D^`}]`,H\=D,O is D-2,X+U+V). A^B:-member(A,B). ``` [Try it online!](https://tio.run/##bVNbj9JAFH7nV9R92TYzbbitGggmwKh9MMFsu2uz07MW2MaQFCGAWXWY345nTu06bW1I5nyXc@uU/WFX7L75x@fN5ZLGIz9mgkng2@W@2BxP7v7H6et695Rz4QUdCYx@QSdhUpzvgEUjP5mgPZrIxfkBuHA2R2fB@jxhd@xhjFp4joG7YhJyN2XhYyZB6YzHKEdjhIBgYZJCv8/dqkxM2ZGpXA3gLrwyyzNpUpU1sHwE3pjy7oGjoiHjojzCdCLK4sIvJ7rHJaaPs5G/zber/OBO@cwLLqccF424E3vOyO84@LS2dyKPk/J82Jxy98rx/XfO1V@u7Y7r7vR7ZU2jhmCk4IIcDZHJAQszTgdklFPyqvup1@3eDlCrQm3rIRtqo9Fp8Z@lEOyoI0osARhkWbBVSLllYDddrtZGwKPGu4Mg6PW9aAhmVAtZHklTGp2CmjaVs7kWprKJAENL/Kl@/YalSTSRxtCuOl3NqSmd9qi9/mB48/rNW9rkH6h1NWtQ09UaalJiepqyCbW0peswL4od/7I7FE@vrtHTIOwGM3cu1PsP8JGusILa4KZNv9iUjWs2aVWrkP6fSyJPLlVBAN30qbmAl6aSsIZ2V0lXTq@oxquSV41PQZpq9Zswc9Q80PLolgeJDP@bfwA "Prolog (SWI) – Try It Online") Prolog has a special syntax for literal lists of character codes so, invoking the predicate is easy. ``` ?- \`A[bc}`. {A[bc]} true . ``` ]
[Question] [ I was browsing Stackoverflow and saw [this question](https://stackoverflow.com/questions/54947584/tile-a-mxn-rectangle-with-1x2-and-1x3-tiles-no-alignment) about tiling an MxN rectangle, and I thought it would be great for golfing. Here is the task. Given the dimension M and N, write a program that outputs how many unique ways a MxN rectangle (N is the number of rows, not columns. Not that it really matters) can be tiled given these constraints. 1. All tiles are 2x1 or 3x1 2. All tiles stay within their row (ie they are all horizontal) 3. Between every two adjacent rows tiles should not be aligned, except on the two ends 4. M and N are guaranteed to be at least 1 For example, a valid tiling of a 8x3 matrix would be ``` 2 3 3 | | | v v v _______________ |___|_____|_____| |_____|_____|___| |___|_____|_____| ``` But the following would be invalid, because the rows align ``` 2 3 3 | | | v v v _______________ |___|_____|_____| |_____|___|_____| |_____|_____|___| ``` Test cases: 8x3: 4 3x1: 1 1x1: 0 9x4: 10 Code golf, so shortest answer wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` 2*ḃ€2‘ÄṪ⁼¥Ƈ⁸ṗfƝẸ$€ċ0 ``` [Try it online!](https://tio.run/##ATgAx/9qZWxsef//MirhuIPigqwy4oCYw4ThuarigbzCpcaH4oG44bmXZsad4bq4JOKCrMSLMP///zn/NA "Jelly – Try It Online") [Answer] # JavaScript (ES6), ~~119 110 106 96~~ 91 bytes Takes input as \$(N,M)\$. ``` f=(n,m,p=0,g=(w,h=x=>g(p[g[w-=x]=1,w]||w)*g[w]--)=>w>3?h(2)+h(1):w>1&&f(n,m-1,g))=>m?g(n):1 ``` [Try it online!](https://tio.run/##bcxBDoIwEIXhvQchMzo1DLhQkikHISwIQtFAS8RYFty9ojuD2@9/effqVU314zY@lXXXJoRWwNJAo8RkBDx1Mos2MBam8ErmUph8uSwe9yuUSqFor9O8gwQPHTBmXnMUtZ8TxWRw7UNuwGLGoXZ2cn1z7J2BFs6UIu5@LSXeGP@xC522u5g43ir/1eSr4Q0 "JavaScript (Node.js) – Try It Online") ### Commented *NB: This code uses 3 different functions that call each other. This makes it a bit difficult to keep track of the scope of the variables. Keep in mind that \$g\$ is defined within the scope of \$f\$ and \$h\$ is defined within the scope of \$g\$.* ``` f = ( // f is a recursive function taking: n, // n = number of columns m, // m = number of rows p = 0, // p = object holding the previous row g = ( // g = recursive function taking: w, // w = remaining width that needs to be filled in the // current row h = x => // h = helper function taking x // h body: g( // recursive call to g: p[g[w -= x] = 1, // subtract either 2 or 1 from w and mark this width as used w // test p[w] ] // pass p[w] if p[w] = 1 (which will force the next iteration // to fail immediately) || w // otherwise, pass w ) // end of recursive call * g[w]-- // then restore g[w] to 0 ) => // g body: w > 3 ? // if w > 3, we need to insert at least 2 more bricks: h(2) + h(1) // invoke h with x = 2 and x = 1 : // else: w > 1 // this is the last brick; we just check if it can be inserted && // abort if w is equal to 1 (a brick does not fit in there) f( // otherwise, do a recursive call to f: n, // n is unchanged m - 1, // decrement m g // pass g as the new reference row ) // end of recursive call ) => // f body: m ? g(n) : 1 // yield 1 if we made it to the last row or call g otherwise ``` [Answer] # [R](https://www.r-project.org/), ~~243~~ 231 bytes ``` function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=Map)`if`(m<2,0,sum((e=eigen(lengths(outer(p<-unlist(M(M,list(function(x,y)cumsum(2+1:y%in%x)),M(combn,j,i,s=F),j),F),p,Vectorize(intersect)))<2))$ve%*%diag(e$va^(n-1))%*%solve(e$ve))) ``` [Try it online!](https://tio.run/##PY3BboNADETv/YocspINRoElqqoIrr1x7bEKpYYasQtiASX5ebrQqBfPm5E9Htf6kEVrPdtqkt6CIUuS6yC@gFEn9YqhUUpTm0sIJkoDwZOmIi/KAa9SX8FkmmJyswHgnKVhCx3bZvpx0M8TjzBk0Ww7cRMUUNAO/89udMdqNtu1DpPLXYlVN0QqoOrNl6WWhFz@jtQi@TnQB1dTP8qDQawvd94iYqYRjwurQH1L2QAfl/ITbJQg@sj13cJbxn5zreGNUnypIaVkk@QpMemn/nmfxzto0jvo8wbrLw "R – Try It Online") Version with line breaks: ``` function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=Map)`if`(m<2,0, sum((e=eigen(lengths(outer(p<-unlist(M(M,list(function(x,y)cumsum(2+1:y%in%x)), M(combn,j,i,s=F),j),F),p,Vectorize(intersect)))<2))$ve%*%diag(e$va^(n-1))%*%solve(e$ve))) ``` Note no recursion, and handles fairly large values of m and n (e.g. 24x20 -> 3.3e19) Here's a commented answer that works more or less the same as the above, but I've unnested all of the functions so it's actually readable: ``` f <- function(m,n) { # First work out what potential combinations of 2s and 3s add up to m i <- 2*0:(m %/% 6) + m %% 2 # Vector with numbers of possible 3s j <- i + (m - 3 * i) / 2 # Vector with total number of 2s and 3s if (m < 2) { 0 # If wall less than 2 wide, no point in continuing because answer is 0 } else { # Work out all possible positions of threes for each set positions_of_threes <- Map(combn, j, i, simplify = FALSE) # Function to work out the cumulative distance along the wall for a given # Set of three positions and number of bricks make_cumulative_bricks <- function(pos_threes, n_bricks) { bricks <- 1:n_bricks %in% pos_threes cumsum(2 + bricks) } # Find all possible rows with cumulative width of wall # Note because this is a `Map` with depth two that needs to be vectorised # for both `positions_of_threes` and `j`, and we're using base R, the # function `make_cumulative_bricks` needs to be placed in a list cum_bricks <- Map(Map, list(make_cumulative_bricks), positions_of_threes, j) # Finally we have the list of possible rows of bricks as a flat list cum_bricks_unlisted <- unlist(cum_bricks, recursive = FALSE) # Vectorise the intersect function intersect_v <- Vectorize(intersect, SIMPLIFY = FALSE) # Find the length of all possible intersects between rows intersections <- outer(cum_bricks_unlisted, cum_bricks_unlisted, intersect_v) n_intersections <- lengths(intersections) # The ones not lined up will only have a single intersect at `m` not_lined_up <- n_intersections == 1 # Now use method described at https://stackoverflow.com/a/9459540/4998761 # to calculate the (matrix of TRUE/FALSE for lined-up) to the power of `n` eigen_nlu <- eigen(not_lined_up) final_mat <- eigen_nlu$vectors %*% diag(eigen_nlu$values ^ (n - 1)) %*% solve(eigen_nlu$vectors) # The sum of this matrix is what we're looking for sum(final_mat) } } f(20,20) ``` The method for taking a matrix and repeatedly multiplying it by itself is from [a question on stackoverflow](https://stackoverflow.com/a/9459540/4998761). This approach works here because it effectively calculates the cumulative number of branches through the different possible rows of bricks. If external packages are allowed, I can get it down to 192: ``` function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=purrr::map2)`if`(m<2,0,sum(expm::`%^%`(lengths(outer(p<-unlist(M(M(j,i,combn,s=F),j,M,~cumsum(2+1:.y%in%.)),F),p,Vectorize(intersect)))<2,n-1))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` 2*ḃ€2‘ÄṪ⁼¥Ƈ⁸œ&L¬ɗþ`æ*⁴’¤SS ``` [Try it online!](https://tio.run/##AUIAvf9qZWxsef//MirhuIPigqwy4oCYw4ThuarigbzCpcaH4oG4xZMmTMKsyZfDvmDDpirigbTigJnCpFNT////MTL/MTg "Jelly – Try It Online") ## Broken down: Generate a list of possible walls as cumulative sums with the end removed: ``` 2*ḃ€2‘ÄṪ⁼¥Ƈ⁸ ``` Find the outer table of all possible walls against each other that don’t have any intersections: ``` œ&L¬ɗþ` ``` Take this matrix to the power of (N-1) and then sum it all up: ``` æ*⁴’¤SS ``` Uses the first bit from @EriktheOutgolfer’s answer to generate the list of possible walls, and then uses the matrix intersection and matrix exponentiation approach from my R answer. As such, it works well even with large N. This is my first Jelly answer, and I suspect it can be golfed more. I’d also ideally like to change the first section so that the time and memory requirements don’t scale exponentially with M. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Åœʒ23yåP}€œ€`Ùε.¥¦¨}IиI.ÆÙεøyíø‚€€üQOO_P}O ``` I'm almost too ashamed to post this, and it can definitely be golfed by A LOT with a different approach, but since it took a while to complete I decided to post it anyway and golf it down from here. The challenge looks easier than it is imo, but I'm definitely using a wrong approach here and I have the feeling 05AB1E could do around 25 bytes.. [Try it online.](https://tio.run/##yy9OTMpM/f//cOvRyacmGRlXHl4aUPuoac3RyUAi4fDMc1v1Di09tOzQilrPCzs89Q63gYQO76g8vPbwjkcNs85tBSo7vCfQ3z@@NqDW//9/Sy4TAA) NOTE: Not only is it long, it's also inefficient, since the `9x4` test case runs in about 40 seconds on TIO.. **Explanation:** ``` Åœ # Get all possible ways to sum to the (first) implicit input # i.e. 8 → [[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,2],[1,1,1,1,1,3],[1,1,1,1,2,2],[1,1,1,1,4],[1,1,1,2,3],[1,1,1,5],[1,1,2,2,2],[1,1,2,4],[1,1,3,3],[1,1,6],[1,2,2,3],[1,2,5],[1,3,4],[1,7],[2,2,2,2],[2,2,4],[2,3,3],[2,6],[3,5],[4,4],[8]] ʒ23yåP} # Only leave those consisting of 2s and/or 3s # → [[2,2,2,2],[2,3,3]] €œ # For each: get all permutations €` # Flatten this list of lists once Ù # And uniquify it (leaving all possible distinct rows of bricks) # → [[2,2,2,2],[3,3,2],[3,2,3],[2,3,3]] ε } # For each: .¥ # Get the cumulative sum ¦¨ # With the leading 0 and trailing first input removed # → [[2,4,6],[3,6],[3,5],[2,5]] Iи # Repeat this list the second input amount of times # i.e. 3 → [[2,4,6],[3,6],[3,5],[2,5],[2,4,6],[3,6],[3,5],[2,5],[2,4,6],[3,6],[3,5],[2,5]] I.Æ # Get all combinations of lists the size of the second input Ù # And uniquify the result (leaving all possible distinct walls) # → [[[2,4,6],[3,6],[3,5]],[[2,4,6],[3,6],[2,5]],[[2,4,6],[3,6],[2,4,6]],[[2,4,6],[3,6],[3,6]],[[2,4,6],[3,5],[2,5]],[[2,4,6],[3,5],[2,4,6]],[[2,4,6],[3,5],[3,6]],[[2,4,6],[3,5],[3,5]],[[2,4,6],[2,5],[2,4,6]],[[2,4,6],[2,5],[3,6]],[[2,4,6],[2,5],[3,5]],[[2,4,6],[2,5],[2,5]],[[2,4,6],[2,4,6],[3,6]],[[2,4,6],[2,4,6],[3,5]],[[2,4,6],[2,4,6],[2,5]],[[2,4,6],[2,4,6],[2,4,6]],[[3,6],[3,5],[2,5]],[[3,6],[3,5],[2,4,6]],[[3,6],[3,5],[3,6]],[[3,6],[3,5],[3,5]],[[3,6],[2,5],[2,4,6]],[[3,6],[2,5],[3,6]],[[3,6],[2,5],[3,5]],[[3,6],[2,5],[2,5]],[[3,6],[2,4,6],[3,6]],[[3,6],[2,4,6],[3,5]],[[3,6],[2,4,6],[2,5]],[[3,6],[2,4,6],[2,4,6]],[[3,6],[3,6],[3,5]],[[3,6],[3,6],[2,5]],[[3,6],[3,6],[2,4,6]],[[3,6],[3,6],[3,6]],[[3,5],[2,5],[2,4,6]],[[3,5],[2,5],[3,6]],[[3,5],[2,5],[3,5]],[[3,5],[2,5],[2,5]],[[3,5],[2,4,6],[3,6]],[[3,5],[2,4,6],[3,5]],[[3,5],[2,4,6],[2,5]],[[3,5],[2,4,6],[2,4,6]],[[3,5],[3,6],[3,5]],[[3,5],[3,6],[2,5]],[[3,5],[3,6],[2,4,6]],[[3,5],[3,6],[3,6]],[[3,5],[3,5],[2,5]],[[3,5],[3,5],[2,4,6]],[[3,5],[3,5],[3,6]],[[3,5],[3,5],[3,5]],[[2,5],[2,4,6],[3,6]],[[2,5],[2,4,6],[3,5]],[[2,5],[2,4,6],[2,5]],[[2,5],[2,4,6],[2,4,6]],[[2,5],[3,6],[3,5]],[[2,5],[3,6],[2,5]],[[2,5],[3,6],[2,4,6]],[[2,5],[3,6],[3,6]],[[2,5],[3,5],[2,5]],[[2,5],[3,5],[2,4,6]],[[2,5],[3,5],[3,6]],[[2,5],[3,5],[3,5]],[[2,5],[2,5],[2,4,6]],[[2,5],[2,5],[3,6]],[[2,5],[2,5],[3,5]],[[2,5],[2,5],[2,5]]] ε # Map all walls `y` to: ø # Zip/transpose; swapping rows and columns yí # Reverse each row in a wall `y` ø # Also zip/transpose those; swapping rows and columns ‚ # Pair both € # For both: € # For each column: ü # For each pair of bricks in a column: Q # Check if they are equal to each other (1 if truthy; 0 if falsey) O # Then take the sum of these checked pairs for each column O # Take the sum of that entire column _ # Then check which sums are exactly 0 (1 if 0; 0 if anything else) P # And check for which walls this is only truthy by taking the product }O # After the map: sum the resulting list # (and output it implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 89 bytes ``` Nθ⊞υ⟦⟧≔⟦⟧ηFυF⟦²¦³⟧«≧⁺∧Lι§ι⁰κ¿⁼κθ⊞ηι¿‹κθ⊞υ⁺⟦κ⟧ι»≔Eη⟦ι⟧ζF⊖N«≔ζι≔⟦⟧ζFιFη¿¬⊙§κ⁰№λμ⊞ζ⁺⟦λ⟧κ»ILζ ``` [Try it online!](https://tio.run/##VZAxa8MwFIRn51e88T1QoTRLIZNJMwTSYLoaDa6tRMKyHFtSaV36211JtSGdxKHT3XeqZTXWfaXn@Whu3p199y5GHGi3KbyV6BmUPIjcWnU1WHIGMshLPwJ6gnSWTwy2nOB7k71Wtz/nm7pKh4X2lkFuGjwJc3USFQXpjqYRn6gYPFLQbcjL1AXwMPhKW2wZDESQ6iUDFa@FtgKi5yTsf0cAjC1Ytjx6g/lnhQ0wMaBUPLRMK/WLqEfRCeNEg/eTidKC5e20FN/tjglZilDLcEmJ6dw7zM0XrsPaOIzBvvfGoWbQEa2000qreRyeaItRBd@@sm79pSn4d/P8DNv54UP/Ag "Charcoal – Try It Online") Link is to verbose version of code. Works for rectangles of size up to about 12 on TIO, but could be made about three times faster at a cost of 2 bytes by using bit twiddling instead of list intersection. Explanation: ``` Nθ ``` Input the width. ``` ⊞υ⟦⟧ ``` Start with a row with no bricks. ``` ≔⟦⟧η ``` Start with no completed rows. ``` Fυ ``` Loop over the rows. ``` F⟦²¦³⟧« ``` Loop over the bricks. ``` ≧⁺∧Lι§ι⁰κ ``` Add the brick width to the current row width. ``` ¿⁼κθ⊞ηι ``` If this results in the input width then add this row to the list of completed rows. ``` ¿‹κθ⊞υ⁺⟦κ⟧ι» ``` Otherwise if this is still less than the input width then add the new row to the list of rows, thus causing it to be picked up by a later iteration. ``` ≔Eη⟦ι⟧ζ ``` Make a list of walls of one row. ``` F⊖N« ``` Loop over one less than the height. ``` ≔ζι ``` Save the list of walls. ``` ≔⟦⟧ζ ``` Clear the list of walls. ``` Fι ``` Loop over the saved list of walls. ``` Fη ``` Loop over the completed rows. ``` ¿¬⊙§κ⁰№λμ⊞ζ⁺⟦λ⟧κ» ``` If the row can be added to this wall then add that to the list of walls. ``` ILζ ``` Output the length of the final list of walls. ]
[Question] [ Inspired by recent popularity of [nandgame](http://nandgame.com/) on TNB, and [my own previous challenge](https://codegolf.stackexchange.com/q/176371/78410). ## Background [Densely packed decimal (DPD)](https://en.wikipedia.org/wiki/Densely_packed_decimal) is a way to efficiently store decimal digits in binary. It stores three decimal digits (000 to 999) in 10 bits, which is much more efficient than naive BCD (which stores one digit in 4 bits). ### Conversion table DPD is designed to easily convert between the bits and the digits by simple pattern matching from top to bottom. Each bit pattern defines how many high digits (8-9) the number has, where they are, and how to move the bits to form the decimal representation. The following is the conversion table from 10 bits of DPD to three decimal digits. Each decimal digit is represented as 4-bit binary (BCD). Both sides are written left to right from the most significant digit to the least. ``` Bits => Decimal (Digit range) a b c d e f **0** g h i => 0abc 0def 0ghi (0-7) (0-7) (0-7) a b c d e f **1 0 0** i => 0abc 0def **100i** (0–7) (0–7) **(8–9)** a b c g h f **1 0 1** i => 0abc **100f** 0ghi (0–7) **(8–9)** (0–7) g h c d e f **1 1 0** i => **100c** 0def 0ghi **(8–9)** (0–7) (0–7) g h c **0 0** f **1 1 1** i => **100c 100f** 0ghi **(8–9) (8–9)** (0–7) d e c **0 1** f **1 1 1** i => **100c** 0def **100i** **(8–9)** (0–7) **(8–9)** a b c **1 0** f **1 1 1** i => 0abc **100f 100i** (0–7) **(8–9) (8–9)** x x c **1 1** f **1 1 1** i => **100c 100f 100i (8–9) (8–9) (8–9)** ``` ### Notations * The lowercase letters `a` to `i` are the bits that are copied to the decimal representation. * `0` and `1` are the exact bits in the input or output bit patterns. * `x` bits are ignored in the conversion. ## Task Build a logical circuit using **two-input NAND gates** to convert 10 bits of DPD to 12 bits of BCD. ## Examples Emphasized bits are the pattern-matching bits. ``` DPD Decimal BCD 0 0 0 0 0 0 **0** 1 0 1 005 0000 0000 0101 ^ 0 0 0 1 1 0 **0** 0 1 1 063 0000 0110 0011 ^ 0 0 0 1 1 1 **1 0 0** 1 079 0000 0111 1001 ^ ^ ^ 0 0 0 0 0 1 **1 0 1** 0 090 0000 1001 0000 ^ ^ ^ 0 0 0 **1 0** 1 **1 1 1** 0 098 0000 1001 1000 ^ ^ ^ ^ ^ 1 0 1 0 1 1 **1 0 1** 0 592 0101 1001 0010 ^ ^ ^ 0 0 1 1 0 0 **1 1 0** 1 941 1001 0100 0001 ^ ^ ^ 1 1 0 **0 1** 1 **1 1 1** 1 879 1000 0111 1001 ^ ^ ^ ^ ^ 1 1 1 **0 0** 0 **1 1 1** 0 986 1001 1000 0110 ^ ^ ^ ^ ^ 0 0 1 **1 1** 1 **1 1 1** 1 999 1001 1001 1001 ^ ^ ^ ^ ^ 1 1 1 **1 1** 1 **1 1 1** 1 999 1001 1001 1001 ^ ^ ^ ^ ^ ``` ## Scoring & winning criterion The score is the number of **two-input NAND gates** used in your circuit. The lowest score wins. You may define small components in terms of two-input NAND gates, and then use them in your final construction. If a component `X` includes `N` two-input NAND gates, each usage of `X` adds `N` to your score. For basic logic gates, this means: * NOT: +1 * 2-input AND: +2 * 2-input OR: +3 * 2-input XOR: +4 [Answer] # 45 39 NANDs (or 43 37) 39 seems to be the absolute minimum, but it is possible to reach 37 NANDs by a trick: By assuming that the largest numbers are correctly encoded. 888, 889, 898, 899, 988, 989, 998, 999 are to be encoded with the 2 MSB as 00, requiring just 37 NANDs for decoding. However, in the specification for decoding, they are specified to be ignored, meaning they can be anything. It is a reasonable assumption that this freer specification could require even fewer gates, but the opposite is true. 39 gates are required for this. This saving could give real benefits for real circuits. I also found circuits that were significantly more efficient and faster, containing a few more gates. No pencil drawn image of the circuit this time. Perhaps later. The circuit is presented in obvious Verilog code, ready for running with test included. Verilog code: ``` // Densely packed decimal (DPD) to decimal, circuit in Verilog. // Made of just 39 NANDs. // // By Kim Øyhus 2019 (c) into (CC BY-SA 3.0.) // This work is licensed under the Creative Commons Attribution 3.0 // Unported License. To view a copy of this license, visit // https://creativecommons.org/licenses/by-sa/3.0/ // // This is my entry to win this Programming Puzzle & Code Golf // at Stack Exchange: // https://codegolf.stackexchange.com/questions/176557/densely-packed-decimal-dpd-to-decimal-with-logic-gates // // TASK: // 3 decimal digits are stored in 10 bits in the DPD format, // and this circuit transforms them into 3 decimal digits in // 4 bits each, BCD format. // // 39 gates seem to be the smallest possible NAND circuit there is // for this task, but I can get even lower by a trick, to 37: // I assume that the largest numbers are correctly encoded. // 888, 889, 898, 899, 988, 989, 998, 999 are to be encoded // with the 2 MSB as 00, requiring just 37 NANDs for decoding. // // However, in the specification for decoding, they are specified // to be ignored, meaning they can be anything. It is a reasonable // assumption that this freer specification could require even fewer // gates, but the opposite is true. 39 gates are required for this. // This saving could give real benefits for real circuits. // // This DPD format seems to be used a lot for storing decimal numbers // in computers and IO for ALUs, even though it is stored as 12 bits // per 3 digits inside the ALUs and for other calculations. // There are many patents for these kinds of circuits, and so I am // a little skeptical for making a free one for a competition. // However, the point is to make it as small as possible and of just // NAND gates, which in itself is not so commercially interesting. module decode1000 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, in_008, in_009, out000, out001, out002, out003, out004, out005, out006, out007, out008, out009, out010, out011 ); input in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, in_008, in_009; output out000, out001, out002, out003, out004, out005, out006, out007, out008, out009, out010, out011; wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032; // The 3 bits of 1s goes straight through from input to output. assign out000 = in_000; assign out004 = in_004; assign out008 = in_007; nand gate001 ( wir001, in_003, in_001 ); nand gate002 ( wir002, in_002, in_003 ); nand gate003 ( wir003, wir001, in_006 ); nand gate004 ( wir004, wir002, in_001 ); nand gate005 ( wir005, wir001, wir001 ); nand gate006 ( wir006, in_005, in_001 ); nand gate007 ( wir007, wir006, in_003 ); nand gate009 ( wir008, wir004, wir007 ); nand gate010 ( wir009, wir005, in_006 ); nand gate011 ( wir010, wir007, wir007 ); nand gate012 ( wir011, wir009, in_002 ); nand gate013 ( wir012, wir011, wir009 ); nand gate014 ( wir013, wir011, wir011 ); nand gate015 ( wir014, in_008, wir013 ); nand gate016 ( wir015, in_009, wir013 ); nand gate017 ( wir016, wir010, wir014 ); nand gate018 ( wir017, wir014, wir005 ); nand gate019 ( wir018, wir015, wir015 ); nand gate020 ( wir019, wir011, wir008 ); nand gate021 ( wir020, wir019, wir006 ); nand gate022 ( wir021, wir010, wir018 ); nand gate023 ( wir022, wir020, wir004 ); nand gate024 ( wir023, wir016, wir008 ); nand gate025 ( out001, wir023, wir023 ); nand gate026 ( out003, wir022, wir022 ); nand gate027 ( wir024, wir005, wir008 ); nand gate028 ( wir025, wir012, wir002 ); nand gate029 ( wir026, wir019, in_003 ); nand gate031 ( out007, wir024, wir009 ); nand gate032 ( out011, wir026, wir026 ); nand gate033 ( wir028, wir017, in_005 ); nand gate035 ( wir030, wir026, in_008 ); nand gate036 ( out005, wir028, wir028 ); nand gate037 ( out009, wir030, wir030 ); nand gate039 ( wir031, wir026, in_009 ); nand gate041 ( out010, wir031, wir031 ); nand gate042 ( wir032, out003, wir018 ); nand gate043 ( out006, wir003, wir032 ); nand gate044 ( out002, wir025, wir021 ); endmodule module test; reg [ 9:0] AB; // input DPD wire [11:0] C; // output BCD decode1000 U1 ( .in_000 (AB[ 0]), .in_001 (AB[ 1]), .in_002 (AB[ 2]), .in_003 (AB[ 3]), .in_004 (AB[ 4]), .in_005 (AB[ 5]), .in_006 (AB[ 6]), .in_007 (AB[ 7]), .in_008 (AB[ 8]), .in_009 (AB[ 9]), .out000 ( C[ 0]), .out001 ( C[ 1]), .out002 ( C[ 2]), .out003 ( C[ 3]), .out004 ( C[ 4]), .out005 ( C[ 5]), .out006 ( C[ 6]), .out007 ( C[ 7]), .out008 ( C[ 8]), .out009 ( C[ 9]), .out010 ( C[10]), .out011 ( C[11]) ); initial AB=0; //unary=0; binary=0 always #1 AB = AB+1; initial begin $display("\t\ttime,\tinn 10bit \tout 3x4bit"); $monitor("%d,\t%b %b %b\t%b %b %b\t %d%d%d",$time, AB[9:7],AB[6:4],AB[3:0], C[11:8], C[7:4], C[3:0], C[11:8], C[7:4], C[3:0]); end initial #1023 $finish; endmodule // How I run and test it: // iverilog -o decode1000 decode1000.v // vvp decode1000 ``` ``` [Answer] ## 65 62 60 58 NANDs Taking the inputs as `i0` to `i9` and the outputs as `o0` to `o9, oa, ob` we have ``` t0 = nand(i6, i7) t1 = nand(t0, t0) t2 = nand(i3, i4) o0 = nand(nand(nand(t2, i3), t1), nand(nand(t2, i8), t1)) t3 = nand(o0, o0) t4 = nand(i0, t3) o1 = nand(t4, t4) t5 = nand(i1, t3) o2 = nand(t5, t5) o3 = i2 # Score 13 for the first decimal digit u0 = nand(i6, i8) u1 = nand(u0, t0) u2 = nand(i4, t2) o4 = nand(nand(nand(u2, u0), u2), nand(u1, t0)) u3 = nand(o4, o4) u4 = nand(o0, i8) u5 = nand(u4, u4) u6 = nand(u3, nand(nand(u5, i0), nand(u4, i3))) o5 = nand(u6, u6) u7 = nand(u3, nand(nand(u5, i1), nand(u4, i4))) o6 = nand(u7, u7) o7 = i5 # Score 20 for the second decimal digit o8 = nand(nand(nand(nand(i4, i8), o0), t1), nand(nand(i6, u1), i6)) v2 = nand(o8, o8) v3 = nand(i6, i6) v4 = nand(i7, i7) v5 = nand(v2, nand(nand(i6, nand(nand(i7, i0), nand(v4, i3))), nand(v3, i7))) o9 = nand(v5, v5) v6 = nand(v2, nand(nand(i6, nand(nand(i7, i1), nand(v4, i4))), nand(v3, i8))) oa = nand(v6, v6) ob = i9 # Score 25 for the third decimal digit ``` [Python test framework](https://tio.run/##nVXLjtswDLznK9gtUMRFDvIrTgpkj/2BHoseHFtJhG6twJGM7tenI1mW5Ty22Q3AwKbJGXJIy8dXdZBNej7XfEf875FXitdzwRYkYlgCS2EZLIctYQVsBVtH32aEn9jBT5sNsf7e/FqudNvQ3OAEWGwKxyZoHqywYFQ2NR59CBhe47LuK@D/goXZ@RQ7ALtXWZh9u@WBKgBLg5azx4BvVHkX@KEqh@z7@mUf0u82WGyw4vd2eYE1M1vbQLV5uaCt20eHxAxLaVmsrtv@kr@cOMV95pEr3r5v2RWjTc/YP@77UfHgVQBTzHkTH2the6/0COOfstQRUmP8XfhXvd9hpkO2BJMcmDLPZPhTxzRWhZaU41e5j42DWF@rQusqd17DJhJ7/Zl@VLKFdintZEvqwGkn2pOimlfiT/lCtdgLNbOxeqrSqkfTvh4dqKRHlUyViWPOrlXSUEMzqKGTQSUdWyCHNGoDJOn61VmomK/Fq6ARq4fYpfem4Ry0WQfmSTM7LccqRyT0qpcOqXgDKZ4gZR5pZMfaabdb0iCJfDKDhPkZnHglsd03hiBX1xJ6ne1WSXa9cmZg2rjE0pXV@QFJvAnSCdilkxG7trtxEYvx9ei8RF1yyRXcFaHI3SDycJ9avEGqtUeEoJ1b1275ME884ckueFaep/SIwOhcl3JrRrKejiT3I1EH0d6cyHDG2VcXmytRpUzNqsLQhwSHLIzGsDUMp5rc4pgDSdkI9UrVgVe/Z4aoPuJT0VBbNns@j1mSuQOqbPcnVPdzbgKen0lE9AXHnkkRYUL0y4ZzxPrP/leT7FqEvz8eAycOVE6fNiTHY/vYikYZroVlXhBHydGsdz99F404HXj9FJ3P/wA) to validate the correctness of the construction. ]
[Question] [ This challenge is based on this [video](https://www.youtube.com/watch?v=LYKn0yUTIU4). I recommend that you watch it before trying this challenge. First we define a function. This function ([OEIS](http://oeis.org/A005589)) takes a integer n as input and outputs the number of letters in the English representation of n (without spaces or hyphens). For example "three" has 5 letters so 3 maps to 5. As demonstrated in the video starting with any number repeating this process will eventually result in a four, which will map to itself forever. Here is a crude directed graph showing the orbits of the numbers less than 16: ``` 12 11 \| 15 2 6 1 10 14 13 \ \|/ / / / 7 3-/ 8--/ \| / 9 0 5--/ \ \| \-4 ``` Your challenge is to determine the number of steps that a number will take (or the number of times this function must be applied to a number) before reaching four (i.e. the level on the directed graph pictured). ## Forming english numbers Here is a brief explanation of how one should form english words for this challenge: The numbers one through nineteen are: one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen For numbers greater than nineteen the process is as follows: If the number has a hundreds place begin with the name of digit in the hundreds place and "hundred". e.g. ``` 100 -> "onehundred" ``` If the remainder is less than twenty append the remainder's English representation. e.g. ``` 714 -> "sevenhundredfourteen" ``` Otherwise if the tens digit is not zero append the proper representation: ``` 2-> twenty 3-> thirty 4-> forty 5-> fifty 6-> sixty 7-> seventy 8-> eighty 9-> ninety ``` e.g. ``` 470 -> "fourhundredseventy" ``` Finally if there is a one's digit append its representation e.g. ``` 681 -> "sixhundredeightyone" ``` ## Further Stipulations * For numbers greater than one hundred you should leave out the "and" when counting the number of letters. For instance 577 is "fivehundredseventyseven" which has 23 letters. * Your program must accept all integers greater than 0 and less than 1,000 as input via standard methods. * Your program must output the number of steps required to standard output methods. * This is codegolf so the solution with the fewest bytes wins. ## Test cases ``` 1 -> 3 4 -> 0 7 -> 2 23 -> 5 577 -> 6 600 -> 4 ``` [Answer] ## JavaScript (ES6), 106 bytes ``` f=(n,a="03354435543668877998")=>n-4&&1+f(7*(n>99)-(-a[n/100|0]-(a[n%=100]||a[n%10])-"0066555766"[n/10|0])) ``` Strings seem to be the best way to encode the length, despite the numeric conversion overhead. [Answer] # Python, with num2words, ~~97 113 115 94 93~~ 92 bytes +16 bytes (forgot the hyphenation that num2words applies which does not actually change the results of any of the test cases, even though `23` and `577` each have a hyphen) +2 bytes (forgot to include `f=` although recursive) -20 bytes (use `re`) -8 bytes thanks to @Wheat Wizard (use `~`, replace `n!=4` with `n-4`, and ...one line import >\_<) -1 byte thanks to @Cyoce (space from `4 and`) ``` import re,num2words as w f=lambda n:n-4and-~f(len(re.sub('\W|and','',w.num2words(n)))) ``` Just counts up the number of steps; works for huge and negative integers too (`\W` finds the spaces, commas and hyphens in the num2words result): ``` >>> for test in (1,4,7,23,577,600,-1*2**96,3**96): ... print('test: {0} -> {1}'.format(test, f(test))) ... test: 1 -> 3 test: 4 -> 0 test: 7 -> 2 test: 23 -> 5 test: 577 -> 6 test: 600 -> 4 test: -79228162514264337593543950336 -> 4 test: 6362685441135942358474828762538534230890216321 -> 5 ``` Here is that last case, step by step: ``` sixquattuordecillionthreehundredsixtytwotredecillionsixhundredeightyfiveduodecillionfourhundredfortyoneundecilliononehundredthirtyfivedecillionninehundredfortytwononillionthreehundredfiftyeightoctillionfourhundredseventyfourseptillioneighthundredtwentyeightsextillionsevenhundredsixtytwoquintillionfivehundredthirtyeightquadrillionfivehundredthirtyfourtrilliontwohundredthirtybillioneighthundredninetymilliontwohundredsixteenthousthreehundredtwentyone fourhundredfiftyone nineteen eight five ``` [Answer] # Pyth - 54 bytes Will try to refactor. ``` KjC"Y©åláóê¤"Ttl.u?<NyT@KNs+V@LKJ_jNT[Z@jC"Ckg"ThtJ7 ``` [Test Suite](http://pyth.herokuapp.com/?code=KjC%22%02Y%C2%A9%C3%A5l%C3%A1%C3%B3%C3%AA%C2%A4%22Ttl.u%3F%3CNyT%40KNs%2BV%40LKJ_jNT%5BZ%40jC%22Ckg%14%22ThtJ7&test_suite=1&test_suite_input=1%0A4%0A7%0A23%0A577%0A600&debug=0). [Answer] # Mathematica, 89 bytes ``` Length@FixedPointList[StringLength@StringReplace[IntegerName@#,{" "->"","-"->""}]&,#]-2& ``` Typical Mathematica: built-in functions good, long function names bad. `FixedPointList` applies its first argument (a function) to the second argument repeatedly until the answer doesn't change, listing all results; the results include the original input and two copies of the repeated output, hence the `-2` at the end. Mathematica's built-in `IntegerName` contains spaces and hyphens, so we need to get rid of those by hand. Annoyingly, `IntegerName`'s output contains the character "‐" (Unicode #8208) rather than normal hyphens; that's why this submission is 89 bytes rather than 88. (And I couldn't precede the code above with four spaces *and* have it accept the Unicode character—any help?—so the above code won't work exactly right if cut and pasted.) [Answer] # Python 2.7, ~~344~~ ~~216~~ 208 bytes: ``` x=`input()`;c=0;y=lambda v:dict(zip(range(0,10),[0]+v));l=[3,3,5,4,4,3,5,5,4];d=y(l);e=y([3,6,6,6,5,5,7,7,6]);f=y([i+7for i in l]) while x!='4':x=`sum([q[int(r)]for q,r in zip([d,e,f],x[::-1])])`;c+=1 print c ``` Does not use any external libraries unlike other Python answer. Takes input through `stdin` and outputs to `stdout`. [Repl.it with All Test Cases!](https://www.repl.it/D4oi) ## Explanation First creates 3 dictionaries with each one pairing the length of the English word representations of each number to the number it represents in the closed interval `[1,9]` in the ones, tens, and hundreds place, respectively. For example, the first entry in dictionary `d` is `1:3` as `1` is spelled `one` in English and has `3` letters. Then, each digits place in some string input `x` is assigned to its corresponding dictionary, after which each number in each place is matched up with its value in the corresponding dictionary. For instance, suppose the input number was `23`. The `20` in the tens place would be paired with dictionary `e`, in which it is matched with `6`, and the `3` in the ones place would be paired with dictionary `d`, in which it is matched with `5`. These matched digits are then added together to represent the length of the English representation of the number, which is assigned to `x` as a string and, as long as `x!='4'`, the while loop goes on, incrementing `c` by `1` each time to represent the number of steps taken thus far. Therefore, `23` would correspond to `11`, which would in turn correspond to `6` which would turn to `3` and then to `5` and finally to `4`, resulting in `5` total steps. Finally, once the loop finishes, `c` is output to `stdout` to represent the "Distance to Four", which in this case would be `5`. [Answer] # Java, ~~556~~ 295 bytes Thanks to @KevinCruijssen for saving *261 bytes* ``` void int(n) {int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;while(n>0){if(n/100>0)c+=(s[n/100]+7);else {if(n>0&n<25){c+=s[n];break;}else{c+=s[(n/10)+22];}}n=n%t;t=t/10;}while(c!=4){v++;c=s[c];}System.out.print(v);} ``` # Ungolfed: ``` void int(n) { int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6}; int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1; while(n>0){ if(n/100>0) c+=(s[n/100]+7); else {if(n>0&n<25){ c+=s[n]; break; } else{ c+=s[(n/10)+22]; } } n=n%t; t=t/10; } while(c!=4) { v++; c=s[c]; } System.out.print(v); } ``` ]
[Question] [ Text adventure games have a pretty set formula; there's a world composed of a series of rooms / spaces, the player can move around these rooms, and there are some items in the rooms. Items can be picked up by the player, put down, used to access other rooms (e.g. keys), and combined with other items to make new items. # Challenge Your challenge is to write a text adventure runtime in the fewest bytes (code golf). To keep things simple, all you need to do is output a truthy or falsey value depending on whether a given series of commands would win a given game or not (no interactivity, no human friendly output, etc.) # Game Rules * The world is always composed of a corridor with 10 connected rooms. Each room requires a key to enter, but can be exited at any time without a key (so it's some kind of latch lock I guess); * The player begins in room 0, and wins if they ever enter room 9 (once they reach room 9 they can do whatever they like, including go to another room, and they will still have won); * Each room can contain any number of items; * There are up to 26 items, named A-Z, and no item will appear more than once in the world; * The player can pick up items from the current room and place them in their inventory (they can also drop items from their inventory into the current room); * The player's maximum inventory size is finite, and will be provided with the level details; * At the beginning of the game, the player's inventory is always empty; * There is no limit to the maximum number of items in a room (though the implicit limit would be 26, since that is the total number of items); * Items A-J are keys which can be used to **enter** rooms 0-9 (i.e. the player can move to room 0 if they have item A, to room 1 if they have B, etc. note that keys are **not** required to leave a room, and the player begins in room 0, so the key "A" is only required if the player wants to *return* to room 0); * Items in the player's inventory can be combined to create new items (which will be created in the player's inventory) — the permitted combinations will be provided with the level details; * Combining items consumes the original items (i.e. if one of the items was a key, it will no-longer be possible to use that key); * If the player tries to do something impossible (e.g. pick up an item which is not in the current room / drop an item they don't have / combine items they don't have / go to a room they don't have the key for), nothing happens and they can continue; * The player will never give a nonsense command (e.g. go to room 11). So a simple game might look like this: ``` v +---+---+---+---+---+---+---+---+---+---+ | C | | J | | | | | | | | +---+---+---+---+---+---+---+---+---+---+ | CORRIDOR | +---------------------------------------+ Inventory capacity: 99 ``` Room 0 contains item "C" (which is the key to room 2). Room 2 contains item "J" (which is the key to room 9). The player can win the game by picking up C, moving to room 2, picking up J, then moving to room 9. A more complex game might be: ``` v +---+---+---+---+---+---+---+---+---+---+ | C | | X |YZ | | | | | | | +---+---+---+---+---+---+---+---+---+---+ | CORRIDOR | +---------------------------------------+ Inventory capacity: 10 C+X => D Y+Z => J ``` Now the player can win by picking up C, moving to room 2, picking up X, combining C with X to create D, then moving to room 3. They can now pick up and combine Y and Z to get J, allowing them to go to room 9. --- # Input Format There's a fair bit of input to handle, and that's a pretty boring task, so the input format is very flexible. You will get the following data, and how it should be sent to your program is largely up to you: * The initial contents of each room (list of 0 or more items for each room); * A collection of permitted item combinations (each contains 2 input items and their output item — note that the input items are unordered); * The maximum inventory size (integer, 0 <= size <= 26); * The list of commands the player attempted. The player's commands can be: * `[P]ick up <item>` - picks up an item from the room and puts it into the player's inventory (if there is space) * `[D]rop <item>` - drops an item from the player's inventory into the current room * `[C]ombine <item1> <item2>` - combines 2 items in the player's inventory to produce a new item * `[G]o to <room>` - travels to the chosen room if the player has the required key For example, the input format I used for testing was simple program arguments: ``` ./adventure YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ G9 # r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 combinations inv. size commands... # means: # room 0 starts with items Y & Z, all other rooms start empty # 1 combination is possible: Y+Z => J # max inventory size is 2 # player commands are [P]ick up Y, [P]ick up Z, [C]ombine Y and Z, [G]o to room 9 # (in this example, the player wins) ``` But if some other format makes it easier, that's fine (e.g. special delimiter characters / multiple lines / different ordering / serialised to JSON / etc.) # Output Format Your program should return some truthy output if the player's commands cause them to win the game, and some falsey output otherwise. This could be a recognisable message to stdout, a program return code, or whatever your language of choice provides. All other output will be ignored. # Test Cases The following bash script provides a test harness which will check most situations. It has been written to use the format described above, but modifying it to use a different format is just a case of adding a conversion in the `invoke` function. ``` #!/bin/sh PROG="$1"; if [[ -z "$PROG" ]]; then echo "Usage: $0 <program-to-test>"; exit 1; fi; function invoke { "$PROG" "$@" } RED="\033[1;31m"; GREEN="\033[1;32m"; RESET="\033[m"; FAILURES="0"; function pass { if ! invoke "$@" >/dev/null 2>&1; then echo "${RED}Expected pass, got fail:${RESET} $*" >&2; (( FAILURES = "$FAILURES" + 1 )); invoke "$@" 2>&1; fi; } function fail { if invoke "$@" >/dev/null 2>&1; then echo "${RED}Expected fail, got pass:${RESET} $*" >&2; (( FAILURES = "$FAILURES" + 1 )); invoke "$@" 2>&1; fi; } echo "Running tests..."; # R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 C I Cmd... pass J '' '' '' '' '' '' '' '' '' 0 9 PJ G9; fail '' J '' '' '' '' '' '' '' '' 0 9 PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ; fail J '' '' '' '' '' '' '' '' '' 0 9 G9; pass J '' '' '' '' '' '' '' '' '' 0 9 G9 PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 1 PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 0 PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ PJ DJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ PJ G9; pass B CJ '' '' '' '' '' '' '' '' 0 2 PB G1 DB PC PJ G9; fail B CJ '' '' '' '' '' '' '' '' 0 2 PB G1 DB PB PC PJ G9; pass AJ '' '' '' '' '' '' '' '' '' 0 2 PA PJ G9; pass B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G3 DB PJ G9; fail B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G2 DB PJ G9; fail B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G3 PJ G9; fail B D J C '' '' '' '' '' '' 0 2 PB G1 PD G3 PJ G9; pass AJ '' '' '' '' '' '' '' '' '' 0 2 PA PJ G9 G0; fail ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 G3 PJ G9; fail ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 DD G3 PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ DD G3 DJ G0 DD G3 PJ G9; fail ADJ '' '' '' '' '' '' '' '' '' 0 1 PA DA DA PD PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 1 PA DA DA PJ G9; fail ABCDEFGHIKLMNOPQRSTUVWXYZ J '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9; pass ABCDEFGHIJKLMNOPQRSTUVWXYZ '' '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9; fail YZJ '' '' '' '' '' '' '' '' '' 0 2 PY PZ CYZ PJ G9; pass YZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PJ G9; pass YZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PJ CWJ G9; fail XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX PJ G9; fail XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX DY DZ PJ G9; pass XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX DW PJ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 CYZ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ DJ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ DJ PY PZ CYZ G9; fail WZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PW PZ CYZ G9; fail WZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CZY G9; pass YZ '' '' '' '' '' '' '' '' '' 1 ZYJ 2 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ PJ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PJ G9; pass BW UV '' '' '' '' '' '' '' '' 3 BUR WVS RSJ 2 PB PW G1 DW PU CBU DR PW PV CVW PR CRS G9; fail BW AUV '' '' '' '' '' '' '' '' 3 BUR WVS RSJ 2 PB G1 PU CBU DR PA PB G0 DA PW G1 PV CVW PR CRS G9; pass BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW UV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA PB G0 DA G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA PB G0 DA PW G1 DB CVW PR CRS G9; pass BFK LG M N O CDE PQR U W '' 10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 \ PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G2 PM G6 DM DC G3 PN G4 PO G6 DN DO DD DE \ PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9 fail BFK LG M N O CDE PQR U W '' 10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 \ PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G6 DM DC G3 PN G4 PO PM G6 DN DO DD DE \ PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9 if (( "$FAILURES" == "0" )); then echo "${GREEN}All tests passed${RESET}"; else echo "${RED}Total failures: $FAILURES${RESET}"; fi; ``` # Winning Standard code golf: shortest code (in bytes) wins. Entries must follow the game rules, which in practice means they must pass all test cases (more tests may be added if necessary). [Answer] # JavaScript (ES6), 244 ~~249 267 280~~ **Edit** Saved 18 (!) bytes thx @Neil A function with input: * r = room content (array of 10 strings) * k = combinations (array of string of 3 chars - source1, source2, result) * s = inventory max size (number) * c = commands (array of strings) Returns true or false ``` (r,k,s,c,p=0,j={})=>c.some(([c,a,b])=>c<'D'?j[a]>0&j[b]>0&&!k.map(([t,u,v])=>u+t==a+b|u+t==b+a?j[j[a]=j[b]=v]=++s:0):c<'G'?j[a]>0&&!(j[++s,a]=~p):c>'G'?s&&j[a]==~p&&!(j[a]=s--):j['ABCDEFGHIJ'[a]]>0&&(p=a)>8,r.map((o,n)=>[...o].map(c=>j[c]=~n))) ``` See the test snippet below for a newline separated version **Test** ``` Exec= (r,k,s,c,p=0,j={})=> c.some( ([c,a,b])=> c<'D'?j[a]>0&j[b]>0&&!k.map(([t,u,v])=>u+t==a+b|u+t==b+a?j[j[a]=j[b]=v]=++s:0) :c<'G'?j[a]>0&&!(j[++s,a]=~p) :c>'G'?s&&j[a]==~p&&!(j[a]=s--) :j['ABCDEFGHIJ'[a]]>0&&(p=a)>8 ,r.map((o,n)=>[...o].map(c=>j[c]=~n)) ) console.log = (...x) => O.textContent += x + '\n'; ;`pass J '' '' '' '' '' '' '' '' '' 0 9 PJ G9; fail '' J '' '' '' '' '' '' '' '' 0 9 PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ; fail J '' '' '' '' '' '' '' '' '' 0 9 G9; pass J '' '' '' '' '' '' '' '' '' 0 9 G9 PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 1 PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 0 PJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ G9; fail J '' '' '' '' '' '' '' '' '' 0 9 PJ PJ DJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ PJ G9; pass J '' '' '' '' '' '' '' '' '' 0 9 PJ DJ PJ G9; pass B CJ '' '' '' '' '' '' '' '' 0 2 PB G1 DB PC PJ G9; fail B CJ '' '' '' '' '' '' '' '' 0 2 PB G1 DB PB PC PJ G9; pass AJ '' '' '' '' '' '' '' '' '' 0 2 PA PJ G9; pass B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G3 DB PJ G9; fail B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G2 DB PJ G9; fail B D '' J '' '' '' '' '' '' 0 2 PB G1 PD G3 PJ G9; fail B D J C '' '' '' '' '' '' 0 2 PB G1 PD G3 PJ G9; pass AJ '' '' '' '' '' '' '' '' '' 0 2 PA PJ G9 G0; fail ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 G3 PJ G9; fail ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ G3 DJ G0 DD G3 PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 3 PA PD PJ DD G3 DJ G0 DD G3 PJ G9; fail ADJ '' '' '' '' '' '' '' '' '' 0 1 PA DA DA PD PJ G9; pass ADJ '' '' '' '' '' '' '' '' '' 0 1 PA DA DA PJ G9; fail ABCDEFGHIKLMNOPQRSTUVWXYZ J '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9; pass ABCDEFGHIJKLMNOPQRSTUVWXYZ '' '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9; fail YZJ '' '' '' '' '' '' '' '' '' 0 2 PY PZ CYZ PJ G9; pass YZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PJ G9; pass YZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PJ CWJ G9; fail XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX PJ G9; fail XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX DY DZ PJ G9; pass XYZJ '' '' '' '' '' '' '' '' '' 1 YZW 2 PY PZ CYZ PX DW PJ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 CYZ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ DJ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ DJ PY PZ CYZ G9; fail WZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PW PZ CYZ G9; fail WZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CYZ G9; pass YZ '' '' '' '' '' '' '' '' '' 1 YZJ 2 PY PZ CZY G9; pass YZ '' '' '' '' '' '' '' '' '' 1 ZYJ 2 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ PY PZ CYZ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PY PZ CYZ PJ G9; fail YZ '' '' '' '' '' '' '' '' '' 1 YZJ 1 PJ G9; pass BW UV '' '' '' '' '' '' '' '' 3 BUR WVS RSJ 2 PB PW G1 DW PU CBU DR PW PV CVW PR CRS G9; fail BW AUV '' '' '' '' '' '' '' '' 3 BUR WVS RSJ 2 PB G1 PU CBU DR PA PB G0 DA PW G1 PV CVW PR CRS G9; pass BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW UV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU PA PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PB G0 DA PW G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA PB G0 DA G1 DB PV CVW PR CRS G9; fail BCW AUV '' '' '' '' '' '' '' '' 3 CUR WVS RSJ 2 PB PC G1 DB PU CCU DR PA PB G0 DA PW G1 DB CVW PR CRS G9; pass BFK LG M N O CDE PQR U W '' 10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G2 PM G6 DM DC G3 PN G4 PO G6 DN DO DD DE PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9 fail BFK LG M N O CDE PQR U W '' 10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G6 DM DC G3 PN G4 PO PM G6 DN DO DD DE PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9` .split(/;*\n/).map((srow,i)=>{ var row=srow.split(/\s+/), rooms=row.slice(1,11).map(x=>x=="''"?"":x), ncomb=+row[11], comb=row.slice(12,12+ncomb), isize=+row[12+ncomb], commands=row.slice(13+ncomb), start='['+rooms+'] ['+comb+'] '+isize+' ['+commands+']'; var result=Exec(rooms,comb,isize,commands), ok = row[0] == ['fail','pass'][~~result] console.log(i, ok ? 'ok':'ko', start, row[0], result) }) ``` ``` <pre id=O></pre> ``` [Answer] # C, 338 bytes I had a go at minifying my own test program. I think it went quite well, even if it is the longest answer so far! ``` #define P c[(i<j?i:j)*25+i+j] #define F for(q=atoi(*++v);r #define X c[r*91+i] r,i,j,c[2405];main(q,v)char**v;{for(r=10;--r;)for(++v;i=**v;++*v)++X;++v;F<q;++r)i=**++v,j=1[*v],P=2[*v];r=9;F&&*++v;c[i=1[*v]]&&j==68?c[i]=!++X,++q:j>79&&q*X?c[i]=!--X,--q:j==71&&c[i+17]?r=57-i:j<68&&c[i]*c[j=2[*v]]&&P?c[i]=c[j]=0,c[P]=++q:0)j=**v;return r;} ``` This uses a few tricks to save space: * Rooms are loaded in reverse so that checking for room 9 becomes checking for room 0, which is cheaper * Room 9's contents never matter, so it is skipped when reading the input and used to store the inventory instead * The room contents and item combinations are stored in the same array. Because items are stored at their ascii values, they never overlap. Breakdown: ``` #define P c[(i<j?i:j)*25+i+j] // item combination lookup (input: i,j) #define X c[r*91+i] // room item lookup (input: r,i) r,i,j,c[2405]; // globals default to 0 main(q,v)char**v;{ // K&R syntax to save bytes for(r=10;--r;) // Load rooms 0-8, store as 9-1 for(++v;i=**v;++*v) ++X; ++v; // Skip room 9 for(q=atoi(*++v);r<q;++r) // For each combination i=**++v, j=1[*v], // Use index[array] syntax to avoid (brackets) P=2[*v]; // Record combination r=9; // Begin in room 0 (9 in memory) for(q=atoi(*++v); // Load inventory size r // While not in room 9 (0 in memory)... &&*++v; // ...and still have user commands // (ISO C promises a NULL at the end of argv) c[i=1[*v]]&&j==68? // If 'D'rop, and we have the item: c[i]=!++X, // Drop it ++q: // Increase our inventory capacity j>79&& // If 'P'ick up, and... q // ...we have capacity in our inventory and... *X? // ...the item is in the room: c[i]=!--X, // Pick it up --q: // Decrease our inventory capacity j==71&&c[i+17]? // If 'G'o to room, and we have the key: r=57-i: // Go to the room j<68&& // If 'C'ombine, and... c[i]*c[j=2[*v]] // ...we have the items and... &&P? // ...they can be combined c[i]=c[j]=0, // Remove the items c[P]=++q: // Add the combined item and increase capacity 0 // Unrecognised or invalid command ) j=**v; // 'j' is the command letter (happens first) return r; // Return the final room (0 = truthy in shell) } ``` Partially inspired by @edc65's answer. --- I was so close to getting `;*++*v;` and `c[P][c]` into the code for ultimate confusion, but unfortunately other options turned out to be shorter :( [Answer] ## Haskell, ~~354~~ ~~325~~ 323 bytes ``` (#)=elem (#)=elem (%)=filter.(/=) m!s=g""0.zip[0..]where g _ p _[]=p>8;g i p r(c:d)|p>8=1<2|'P':[k]<-c,k#x,length i<s=g(k:i)p((p,k%x):r)d|'D':[k]<-c,k#i=g(k%i)p((p,k:x):r)d|'C':q@[k,l]<-c,k#i,l#i,[y]<-[f|[d,e,f]<-m,q==[d,e]||q==[e,d]]=g(y:k%(l%i))p r d|'G':n<-c,y<-read n,['A'..]!!y#i=g i y r d|1<2=g i p r d where Just x=lookup p r ``` Defines a function `!` which takes in order * the possible combinations as a list of 3 letter strings * the maximum size of the inventory * the rooms as a list of 9 strings * the player commands as a list of strings Returns `True` or `False`. Example call: ``` *Main> (!) ["YZW"] 2 ["YZJ","","","","","","","","",""] ["PY","PZ","CYZ","PJ","CWJ","G9"] True ``` [All test cases](http://ideone.com/YTw4b7). Many bytes are spent in carrying the game state around. Haskell cannot destructively update data structures like the rooms and inventory. The work is done by function `g` which takes 4 parameters: the inventory (String), the current room (Integer), the rooms (Assoc-List, with key: room number and value: items) and the commands left (List of String). ``` g _ p _[] = p>8 -- base case. if no commands left, return -- True if we are in room 9 g i p r(c:d) | p>8 = 1<2 -- reached room 9 | 'P':[k]<-c, -- 'Pickup', if k#x, -- key is in room and length i<s -- inventory not full = g(k:i)p((p,k%x):r)d -- adjust inventory and room | 'D':[k]<-c, -- 'Drop', if k#i -- key is in inventory = g(k%i)p((p,k:x):r)d -- adjust inventory and room | 'C':q@[k,l]<-c, -- 'Combine', if k#i,l#i, -- both keys are in inventory and [y]<-[f|[d,e,f]<-m,q==[d,e]||q==[e,d]] -- combination is possible = g(y:k%(l%i))p r d -- adjust inventory | 'G':n<-c, y<-read[n], -- 'Goto', convert digit to integer ['A'..]!!y#i -- key for room is in inventory = g i y r t -- go to room | 1<2 -- impossible command = g i p r d -- ignore it ``` Maybe the following things can save some bytes * State Monad for the game state * ~~A single Assoc-List for the keys (key: letter of key, value: room number with `-1` for inventory) instead of rooms/inventory~~ No, constructing such an initial Assoc-List and the check for max inventory size costs more than it saves dealing with one less parameter. [Answer] # Python 3, ~~321~~ 311 bytes -10, thanks Dave ``` S,F=set,frozenset def f(r,c,i,m): w,v,r,c=0,S(),list(map(S,r)),{F(k):S(x)for*k,x in c} for a,*q in m: p=F(q) if a<'D'and p in c and p<=v:v-=p;v|=c[p] elif a=='D'and p<=v:r[w]|=p;v-=p elif a=='G'and F(chr(65+int(q[0])))<=v:w=int(q[0]) elif a>'G'and p<=r[w]and len(v)<i:r[w]-=p;v|=p if w==9:return 1 ``` Rooms (r), combinations (c) and moves (m) are all lists of strings. Max inventory (i) is an int. Fairly straight forward implementation. Used set()s for the room contents and inventory to make updating easy. Used frozensets to key a dictionary of the combinations, so that the order of the 2 input items is irrelevant. ]
[Question] [ *Time for you to implement my new stack based language! It's called StackyMath. This will be a stack based language with 8 operations on the stack and ways to add numbers to the stack.* ### List of operations: * `/`: Division. Performed on the top 2 numbers of the stack. Pushes the result back on the stack. * `*`: Multiplication. Performed on the top 2 numbers of the stack. Pushes the result back on the stack * `-`: Subtraction. Performed on the top 2 numbers of the stack. Pushes the result back on the stack * `+`: Addition. Performed on the top 2 numbers of the stack. Pushes the result back on the stack * `^`: Exponentiation. Performed on the top 2 numbers of the stack. Pushes the result back on the stack * `%`: Modulo. Performed on the top 2 numbers of the stack. Pushes the result back on the stack * `!`: Factorial. Performed on the top number on the stack. Pushes the result back on the stack * `D`: Duplicate the top number on the stack ### Operations defined in pseudo code: * `/`: `push(pop divided by pop)` * `*`: `push(pop times pop)` * `-`: `push(pop minus pop)` * `+`: `push(pop plus pop)` * `^`: `push(pop to the pop)` * `%`: `push(pop mod pop)` * `!`: `push(factorial pop)` * `D`: `t = pop; push(t); push(t)` ### How to push numbers to the stack: Adding numbers to the stack is easy, just put the raw number in your program where you need it. If you need to put multiple numbers on the stack you can separate them with a comma (`,`). Your program will not need to process `-` numbers in the input, If the user wants one they should push the number they want negated, zero, and `-`. Numbers in the input of the program are also constrained to positive integers. ### Input: Your program should take the input on the command line, or from std in. Input will only consist of numbers (no scientific notation or decimals) delimited by `,` as needed, and the operations defined above. ### Output: Your program should print the number on the top of the stack. Error cases: * If the program tries to over-pop the stack, you should print `StackUnderflowException!!!` . * If you have division by zero, print `DivisionByZeroException!!!` * If a number that exceeds 64-bits, either while executing the program or processing a number in the input, print `NumberOverflowException!!!` * If somehow you get a negative number on the top of the stack and you need to do a factorial, print `NegativeFactorialException!!!` * If you have a floating point number on the tops of the stack and the next operation is factorial, print `FloatingFactorialException!!!` * If no numbers are on the stack when the program exits (i.e. the program was empty) print `EmptyProgram!!!` ### Notes: * All error output to should got yo std err or closest equivalent. * All numbers are constrained to 64-bit floating point. Example programs: ``` 50,47* -> 2350 50,47/ -> 0.94 100,8! -> 40320 100D* -> 10000 ! -> StackUnderflowException!!! 5,2/! -> FloatingFactorialException!!! 4,3!2*/ -> 3 654,489,48,43/5*7D+-*% -> 77.68749999999909 -> EmptyProgram!!! ``` (I can add more if needed) [Answer] # Ruby, ~~412~~ ~~410~~ ~~404~~ ~~392~~ ~~380~~ 377 characters ``` def e m,x='Exception';warn m+x+?!*3;exit;end def o;e'StackUnderflow'if$*==[];$*.pop;end u=->n{e'DivisionByZero'if n.infinite?;e'NumberOverflow'if n>2**64;$*<<n} f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n} gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[$1.to_f]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]} e'EmptyProgram',''if$*==[] p o ``` This is regular precision version using `Float`. The result precision is as in the sample code, but numeric overflow detection is not exact. Sample run: ``` bash-4.3$ ruby StackyMath.rb <<< '654,489,48,43/5*7D+-*%' 77.68749999999909 ``` ## Ruby, ~~378~~ 377 characters ``` def e m,x='Exception';warn m+x+?!*3;exit;end def o;e'StackUnderflow'if$*==[];$*.pop;end u=->n{e'NumberOverflow'if n>2**64;$*<<n} f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n} gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[Rational$1]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]}rescue e'DivisionByZero' e'EmptyProgram',''if$*==[] p o.to_f ``` This is high precision version using `Rational`. The result precision is not always the same as in the sample code, but numeric overflow detection is exact. Sample run: ``` bash-4.3$ ruby StackyMath-hi.rb <<< '654,489,48,43/5*7D+-*%' 77.6875 ``` [Answer] # JavaScript (ES6), 430 bytes 422 bytes with ES7 by changing `Math.pow(2,2)` to `2**2` ``` e=m=>{throw alert(m)};u=prompt();u?alert(eval('u.match(/\\d+|[^,]/g).map(o=>s.push(t=o=="/"?(b=p(a=2))?a/b:e`DivisionByZero43*"?2*23-"?2-23+"?2+23%"?2%23^"?Math.pow(2,2)3D"?s.push(r=2)&&r3!"?eval("for(r=i=2;i<0?e`Negative54:i%1?e`Floating54:--i;)r*=i;r"):+o)&&t==Infinity&&e`NumberOverflow4,s=[],p=_=>s.length?s.pop():e`StackUnderflow4);t'.replace(/[2-5]/g,x=>[,,'p()',':o=="','Exception!!!`','Factorial'][x]))):e`EmptyProgram!!!` ``` ## Explanation Uses `eval` to replace certain common phrases. Ungolfed and without the `eval` it looks like this: ``` e=m=>{throw alert(m)}; // e = throw error, alert displays // message, throw stops execution u=prompt(); // u = received input u?alert( // display the result u.match(/\d+|[^,]/g) // get array of numbers and operators .map(o=> // iterate over operators s.push(t= // t = last pushed value // Execute operator o=="/"?(b=p(a=p()))?a/b: // make sure argument B is not 0 e`DivisionByZeroException!!!`: o=="*"?p()*p(): o=="-"?p()-p(): o=="+"?p()+p(): o=="%"?p()%p(): o=="^"?Math.pow(p(),p()): o=="D"?s.push(r=p())&&r: o=="!"?eval(" // eval to enable for loop in ternary for( // no factorial in JS so do this manually r=i=p(); i<0?e`NegativeFactorialException!!!` // check for errors :i%1? e`FloatingFactorialException!!!` :--i; ) r*=i; r"): // return r +o // if not an operator cast as a number )&&t==Infinity&& // JS turns anything over 64 bit float e`NumberOverflowException!!!`, // max value into Infinity s=[], // s = stack array p=_=>s.length?s.pop(): // p = check stack then pop e`StackUnderflowException!!!` )&&t // return top stack element ):e`EmptyProgram!!!` // error if input length is 0 ``` [Answer] # Groovy, 718 bytes. *Fore!* May as well post my impl golfed. Meet my big wall of code: ``` g='Exception!!!' a={System.err.print(it);System.exit(1)} b=new Stack() c={b.push(it)} v=2d**64d d={b.pop()} e={if(b.size()<it)a('StackUnderflow'+g)} f={a('NumberOverflow'+g)} h={e(2) c(Eval.xy(d(),d(),"x$it y")) if(b.peek()>v)f()} k={i->if(i<0)a('NegativeFactorial'+g) if(Math.abs(i-(i as long))>1E-6)a('FloatingFactorial'+g) (2..i).inject{x,y->(v/x<y)?f():x*y}} l=['/':{e(2) m=d() n=d() if(n==0)a('DivisionByZero'+g) c(m/n)},'!':{e(1) c(k(d()))},'D':{e(1) c(b.peek())}] System.in.newReader().readLine().findAll(~/\d+|[^,]/).each{x->if(x.matches(/\d+/))try{c(x as double)}catch(Exception e){f()} else if("+-*%^".contains(x))h(x.replace('^','**')) else l[x]()} if(b){o=d() if(Double.isInfinite(o))f() println o}else a('EmptyProgram!!!') ``` Ungolfed: ``` error = {System.err.print(it);System.exit(1)} stack = new Stack() maxVal = 2d**64d push = {stack.push(it)} pop = {stack.pop()} checkAtLeast = {if (stack.size() < it) error('StackUnderflow'+exception)} numberOverflow = {error('NumberOverflow'+exception)} exception = 'Exception!!!' def dArgOp(i) { checkAtLeast(2) push(Eval.xy(pop(), pop(), "x$i y")) if(stack.peek() > maxVal) numberOverflow } factorial = {i-> if (i < 0) error('NegativeFactorial'+exception) if (Math.abs(i - (i as long)) > 1E-6) error('FloatingFactorial'+exception) (2..i).inject {acc, it -> (maxVal/acc < it)?numberOverflow():acc*it } } ops = [ '/' : { checkAtLeast(2) first = pop() second = pop() if (second == 0) error('DivisionByZero'+exception) push(first / second) }, '!' : { checkAtLeast(1) push(factorial(pop())) }, 'D' : { checkAtLeast(1) push(stack.peek()) }] input = System.in.newReader().readLine() tokens = input.findAll(~/\d+|[^,]/) tokens.each { print "current token: $it \t stack before eval: $stack " if (it.matches(/\d+/)) try { push(it as double) } catch (Exception e) { numberOverflow() } else if ("+-*%^".contains(it)) dArgOp(it.replace('^','**')) else ops[it]() println "result: ${stack.peek()}" } if (stack) { top = pop() if (Double.isInfinite(top)) numberOverflow() println top } else error('EmptyProgram!!!') ``` Edit 1: save ~15 bytes thanks to @Doorknob Edit 2: drop ~130 bytes with a few more tricks [Answer] # [Candy](https://github.com/dale6john/candy), ~~298~~ ~~348~~ 392 bytes Although Candy is stack based, I'm not sure that really helped... ``` &{|"EmptyProgram!!!\n"(;).}(=bYZay0=zx4k"!%*+,-/D^"(iYe{Z=x})aYb=z=ya=X{Y{cZ0=yza}b212202221(i=ZXe{y})a0=zcY0j{XjZ{|D1b#64R(=c2*)c>{b"NumberOverFlow"(;)i}}|i}aZ{(=)"Exception!!!\n"(;).}0=yz|A#48-Z#10*+=z1=y})c?(=).@0&<{1|b"StackUnderflow"(;)c0}.@1~ALe{A0<{b"Negative"(;)i|1bAR(=cA*)}|b"Floating"(;)i}Z{b"Factorial"(;)}.@2W%.@3*.@4+@5.@6W-.@7WD{/|b"DivisionByZero"(;)i}.@8~A.@9=xK=y=1bA_(cX*). ``` Formatted a bit reveals a bit of structure: ``` &{|"EmptyProgram!!!\n"(;).} (=bYZay0=zx4k "!%*+,-/D^" (iYe{Z=x}) aYb=z=ya=X { Y{cZ0=yza}b 212202221(i=ZXe{y}) a0=zcY0j {XjZ{|D1b#64R(=c2*)c>{b"NumberOverFlow"(;)i}}|i} aZ{(=)"Exception!!!\n"(;).} 0=yz|A#48-Z#10*+=z1=y } )c?(=). @0&<{1|b"StackUnderflow"(;)c0}. @1~ALe{A0<{b"Negative"(;)i|1bAR(=cA*)}|b"Floating"(;)i}Z{"Factorial"(;)}. @2W%.@3*.@4+@5.@6W-.@7WD{/|"DivisionByZero"(;)i}.@8~A.@9=xK=y=1bA_(cX*). ``` The actual math occurs on the last two lines. It's driven there by a jump table on the third line. ]
[Question] [ My first ever Programming Puzzles & Code Golf is the [Seven-Slash Display](https://codegolf.stackexchange.com/questions/51445/seven-slash-display/51447#51447). Here is my first Challenge, also based on 7-segment display. I often think about, besides numbers, what kind of letters I can display using a simple 7 segment display. Turns out a lot of letters can be displayed. In fact, all but the letters K, M, V, W, X can be displayed using a single 7-segment display. This is because you can display either lower case or the upper case of a letter. e.g. "abcdef" can be displayed as ``` _ _ _ _ !_!!_ ! _!!_ !_ ! !!_!!_ !_!!_ ! ``` Note that each character is a 3x3 matrix made up of `!` and `_`. Of course, the 7-segment display can be used to display numbers and symbols: ``` _ _ _ _ _ _ _ ! _ !_ !_ ! _! !!_ !_!! !_!!_! ! _!!_ !_! !_! ! _!! !_ ! ! _! ``` Some letters can have both upper and lower case: ``` _ _ ! _ !_!!_ ! ! ! _ ! ! !_ !_ ! !! ! ! !!_!!_!!_!!_! ``` Here are the full set of characters: ``` _ _ _ _ _ _ _ _ _ ! ! ! _! _!!_!!_ !_ !!_!!_! _ !_ _ _ _! !_! !!_ _! ! _!!_! !!_! _! !_ ! ! !!_!!_! ! _ _ _ _ _ _ _ _ _ _ !_!!_ ! _!!_ !_ ! !_! ! !! _ ! !!_!!_! _ !_ !_ ! !!_! _! ! !!_!!_ !_!!_ ! !_!! ! !!_!!_ ! !!_!! !! _!!_ !_! _!!_ ``` Pay attention that there are a white space(), a dash(`-`) and a question mark(`?`). The letter `I`, `O` and `Z` are the same as numbers `1`, `0` and `2` respectively. In this challenge, you will write a program or a function to display a string using 7-segment display format above. # Rules 1. You can write a program or a function 2. This is code-golf, the shortest code in bytes wins 3. Your program or function should take input from STDIN or as a parameter. And outputs a string to STDOUT or as a string in 3 lines without leading space but terminated with newline. Handle upper/lower case of `CHIOU` properly. 4. You may optionally print trailing white spaces 5. You must follow the format above. Using underscore `_` and exclamation mark `!` to form your 7-segment display. 6. You must support white space(), dash(`-`) and question mark (`?`) 7. If the string contain unsupported character (k, m, v, w, x), a single error character (3 horizon line, see example) is displayed. Besides the 5 unsupported characters, you can assume the input is made up of only supported character set. 8. I opted to not have a letter for lowercase L (`l`) due to confusions but if you are so inclined, you can display it like a `1` either to the right or left. # Examples ``` $./a.out Start _ _ !_ !_ !_! _ !_ _!!_ ! !! !_ $./a.out "7-seg dIsplay" _ _ _ _ _ _ _ ! _ !_ !_ ! _! !!_ !_!! !_!!_! ! _!!_ !_! !_! ! _!! !_ ! ! _! $./a.out "0123456789 chiou-?" _ _ _ _ _ _ _ _ _ ! ! ! _! _!!_!!_ !_ !!_!!_! _ !_ _ _ _! !_! !!_ _! ! _!!_! !!_! _! !_ ! ! !!_!!_! ! $./a.out "ABCDEFGHIJLNOPQRSTUZ" _ _ _ _ _ _ _ _ _ _ !_!!_ ! _!!_ !_ ! !_! ! !! _ ! !!_!!_! _ !_ !_ ! ! _! ! !!_!!_ !_!!_ ! !_!! ! !!_!!_ ! !!_!! !! _!!_ !_!!_ $./a.out "abcdefghijlnopqrstuz" _ _ _ _ _ _ _ _ !_!!_ _ _!!_ !_ ! !_ !! _ _ !_!!_! _ !_ !_ _! ! !!_!!_ !_!!_ ! !_!! ! !!_!!_ ! !!_!! !! _!!_ !_!!_ $./a.out "Bad Form" _ _ _ $./a.out "Hello" _ !_!!_ ! ! _ ! !!_ !_ !_ !_! $./a.out "World" _ _ _ ``` [Answer] # CJam, ~~123~~ ~~114~~ ~~112~~ 110 bytes ``` Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"^A^W^G;^Þ¯ ^Þ^Û9³·^É¿» ^@ ^P ^Ü^Ò½7¦^_¶´§= ^O^V&5^U¯¼¹^T³6/"=i2b9Ue[3/"!_!"f.{S?}.+}/N* ``` The above uses caret notation, since the code contains unprintable characters. One of them is a null byte (`^@`), which means that this code can only be executed from the command line. At the cost of only two more bytes (for a total of **112**), we can fix this. ``` Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"AWG{ÞïIÞÛyó÷Éÿû @ P ÜÒýwæ_öôç}IOVfuUïüùTóvo"=i448+2b1>3/"!_!"f.{S?}.+}/N* ``` This time, all characters are printable. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Qq_eu%22%3B%3DKMVWX%22%3AT%26%22%40%22%40%3F%22%20-chiou%22Tereu%7Bi%22AWG%7B%C3%9E%C3%AFI%C3%9E%C3%9By%C3%B3%C3%B7%C3%89%C3%BF%C3%BB%0A%40%0AP%0A%C3%9C%C3%92%C3%BDw%C3%A6_%C3%B6%C3%B4%C3%A7%7DIOVfuU%C3%AF%C3%BC%C3%B9T%C3%B3vo%22%3Di448%2B2b1%3E3%2F%22!_!%22f.%7BS%3F%7D.%2B%7D%2FN*&input=0123456789%20chiou-%3F%20ABCDEFGHIJLNOPQRSTUYZ). ### Example run ``` $ LANG=en_US $ xxd -ps -r > 7seg.cjam <<< 51715f6575223b3d4b4d565758223a5426224022403f22202d6368696f752254657265757b69220117073b9eaf099e9b39b3b789bfbb0a000a100a9c92bd37a61fb6b4a73d090f16263515afbcb914b3362f223d6932623955655b332f22215f2122662e7b533f7d2e2b7d2f4e2a $ wc -c 7seg.cjam 110 7seg.cjam $ echo -n '0123456789 chiou-?' | cjam 7seg.cjam; echo _ _ _ _ _ _ _ _ _ ! ! ! _! _!!_!!_ !_ !!_!!_! _ !_ _ _ _! !_! !!_ _! ! _!!_! !!_! _! !_ ! ! !!_!!_! ! $ echo -n 'ABCDEFGHIJLNOPQRSTUYZ' | cjam 7seg.cjam; echo _ _ _ _ _ _ _ _ _ _ !_!!_ ! _!!_ !_ ! !_! ! !! _ ! !!_!!_! _ !_ !_ ! !!_! _! ! !!_!!_ !_!!_ ! !_!! ! !!_!!_ ! !!_!! !! _!!_ !_! _!!_ $ echo -n 'World' | cjam 7seg.cjam; echo _ _ _ ``` ### Idea (printable version) Each character can be shown on the 9-segment display ``` !_! !_! !_! ``` by replacing some of its characters characters with spaces. We can turn a specific character into an integer by replacing each shown segment, in natural reading order, with a **1**, each not shown segment with a **0** and considering the result binary digits. The first and third segment are never shown, so this will produce integers in the ranges **[0,64)** and **[128,192)**. We can encode each of these integers as a single byte, but half of them will result in unprintable characters. Thus, we add **64** to each integer before casting to character, which makes sure the code points are in the ranges **[64,128)** and **[192,256)**. The only unprintable character in these two ranges is DEL (code point 127), which corresponds to the following, unsued display configuration: ``` !_! !_! ``` We can reverse the above encoding by adding **448 == 512 - 64** to each code point, converting to base 2 and removing the first binary digit. All that's left to to find an efficient way of associating these encoded segmenets with their corresponding ASCII characters. If we map the characters of `" -chiou"` to the characters of `";=KMVWX"` and convert the entire input to uppercase, we can simply store encoding for all characters between `0` (code point 48) and `Z` (code point 90), giving a range of 43. Array indexing is modular in CJam, so if `A` is a string of length 43, `A86=`, `A43=` and `A0=` all yield the same results. The character with code point 86 is `V`, so we simply store the encoded segments of **V - Z** and **0 - U**, in order. In the actual code, we select the at sign as "bad form" character, replace the entire input with the string `"@"` if it contains a forbidden letter and reverse the steps from above. ### Code (printable version) ``` Q e# Push an empty array for posterior concatenation. q e# Read from STDIN. _eu e# Copy the input and convert is to uppercase. ";=KMVWX":T& e# Intersect the result with with T := ";=KMVWX". "@"@? e# Select "@" if truthy and the input if falsy. " -chiou"Ter e# Perform transliteration. eu e# Convert everything to uppercase. { e# For each character in the modified input: i e# Push its code point. "…"= e# Select the corresponding character from the string. i448+ e# Push that character's code point and add 448. 2b1> e# Convert to base 2 and discard the first digit. 3/ e# Group into triplets of digits (rows). "!_!" e# Push that string. f.{ e# For each group of digits: S? e# Select the corresponding char of "!_!" for 1 and " " for 0. } e# .+ e# Concatenate along the rows with the previous results. }/ e# N* e# Join, separating by linefeeds. ``` [Answer] # Perl, ~~475~~ ~~469~~ ~~424~~ ~~390~~ ~~280~~ 272 bytes ``` $_=<>;die" - "x3if/[kmvwx]/i;y/chiou/kmvwx/;$_=lc;while(/(.)/g){$z=ord($1=~y/a-z0-9\-\? /{v\x17nWS7z(.F\x16rb?[yBuV> f&|O?(Omxuw)\x7f}@K\0/r);$i.=$z&1?' _ ':$"x3;$m.=($z&16?'!':$").($z&64?'_':$").($z&8?'!':$");$p.=substr(" ! _!_",$z&6,2).($z&32?'!':$")}print"$i $m $p " ``` multi-line with comments: ``` $_=<>; # accept input die" - # check for invalid chars "x3if/[kmvwx]/i; y/chiou/kmvwx/;$_=lc; # substitute invalid chars, convert to lowercase while(/(.)/g) # loop over each character # lookup character from string using transliteration and convert to # number using ord() for bit checking: {$z=ord($1=~y/a-z0-9\-\? /{v\x17nWS7z(.F\x16rb?[yBuV> f&|O?(Omxuw)\x7f}@K\0/r); $i.=$z&1?' _ ':$"x3; # first row $m.=($z&16?'!':$").($z&64?'_':$").($z&8?'!':$"); # second row $p.=substr(" ! _!_",$z&6,2).($z&32?'!':$")} # third row # print result: print"$i $m $p " ``` The bit patterns encoding the segments are stored in a string (escaping 3 unprintable chars using `\x` and using `\0` for space) and are mapped to the input characters using the Perl transliteration operator. For 5 of the 7 segments, a bitwise and is used along with the ternary operator to output a space or the segment character. For the bottom left two segments (encoded by 2 and 4 in the bitset), a substring lookup into an 8 character string is used to save 2 bytes. Thanks to Dom Hastings for his Perl golfing tips. **Old version (using regexes to encode the patterns), 390 bytes:** ``` $_=<>;if(/[kmvwx]/i){print" -\n"x3;exit}y/chiou/kmvwx/;$_=lc;while(/(.)/g){$z=$1;$i.=($z=~/[acefgopqsz\?0235-9]/?' _ ':' ');$m.=($z=~/[abce-hlmopqstuy045689]/?'!':' ').($z=~/[abdefhkmnp-twyz\-\?2-689]/?'_':' ').($z=~/[adhijopquyz\?0-4789]/?'!':' ');$p.=($z=~/[a-hj-prtuwxz\?0268]/?'!':' ').($z=~/[b-egjklostuw-z0235689]/?'_':' ').($z=~/[abdg-jmnoqsu-y013-9]/?'!':' ')}print"$i\n$m\n$p\n" ``` multi-line with comments: ``` $_=<>; # accept input if(/[kmvwx]/i){print" -\n"x3;exit} # check for invalid chars y/chiou/kmvwx/;$_=lc; # substitute invalid chars, convert to lowercase while(/(.)/g) {$z=$1;$i.=($z=~/[acefgopqsz\?0235-9]/?' _ ':' '); # first row $m.=($z=~/[abce-hlmopqstuy045689]/?'!':' '). ($z=~/[abdefhkmnp-twyz\-\?2-689]/?'_':' '). ($z=~/[adhijopquyz\?0-4789]/?'!':' '); # second row $p.=($z=~/[a-hj-prtuwxz\?0268]/?'!':' '). ($z=~/[b-egjklostuw-z0235689]/?'_':' '). ($z=~/[abdg-jmnoqsu-y013-9]/?'!':' ')} # third row print"$i\n$m\n$p\n" # print result ``` The string is read in and checked for invalid chars using a regex, exiting if any are found. Then the allowed lowercase chars are substituted for the invalid chars and the entire string is converted to lowercase. The rows are generated one at a time, with 1 segment per letter on the first row and 3 on the other two. For each row, the string is processed one character at a time and the character is matched against a regex for each segment to check if a ! or \_ should be displayed. Using a regex means that for characters where the segment is not set it takes zero bits per segment per character to encode whether to set it, and for those where it is it takes a little less than 8 bits on average because regex character ranges can be used. So it works out to around 3 or 4 bits per segment per character in the set, or around 21-24 bits per character. It doesn't handle line-wrapping. [Answer] # Common Lisp, ~~488~~ 416 ``` (lambda(z)(dotimes(r 3)(map()(lambda(c)(do((i 0(+ 17 i))n)((or(and(> i 901)(setf n 146))(=(char-code c)(ldb(byte 8 9)(setf n(ldb(byte 17 i)#36RIL884OIVFXJY4DCQ0O8DPH8MOMR2DSLPP3O4ESYHS234A9HEQYSV8IBDBZI6Z3C3MCVR77OYD3QN5G6CX2UQWGL4UY5R9PKYI1JQ5Y6DC27MQQGUZSCGI8Q9JCYP9N1L4YYKRWM1ZNMSVTSB4792UUWV6Z3906VSP981WCCBMDNJ02)))))(loop for v from(* 3 r)for d across"!_!"do(format t"~:[ ~;~A~]"(logbitp v n)d)))))z)(terpri))) ``` ### Example With `"abcdefg'hijklnopqrstuz"`, prints: ``` _ _ _ _ _ _ _ _ _ _ !_!!_ _ _!!_ !_ ! _ !_ ! ! _ ! _ _ !_!!_! _ !_ !_ _! ! !!_!!_ !_!!_ ! !_! _ ! ! !!_! _ !_ ! !!_!! !! _!!_ !_!!_ ``` ### Remarks Characters and their representations are encoded in this number in base 36: ``` IL884OIVFXJY4DCQ0O8DPH8MOMR2DSLPP3O4ESYHS234A9HEQYSV8IBDBZI6Z3C3MCVR77OYD3QN5G6CX2UQWGL4UY5R9PKYI1JQ5Y6DC27MQQGUZSCGI8Q9JCYP9N1L4YYKRWM1ZNMSVTSB4792UUWV6Z3906VSP981WCCBMDNJ02 ``` The binary representation of this digit is divided in groups of 17 bits. For example, the last group of 17 bits is `110000111101010`, which is decomposed here in two parts: 1. `110000`, the char-code of character `0` 2. `111101010`, an encoding of the drawing, best represented as follows: ``` 010 (bits 0-2) _ 101 (bits 3-5) => ! ! 111 (bits 6-8) !_! ``` Bits in first and last "column" are for `!` characters, the ones in the middle column for the `_` character. When necessary, both uppercase and downcase versions of a character are stored. The function iterates three times over the input string, one for each line of output, searches for a matching character in the table (or defaults to 146, a.k.a. three bars), and prints the representation at current row. [Answer] # JavaScript (ES6), ~~380~~ ~~352~~ 324 bytes (**Note:** Code uses caret notation, as it contains some unprintable characters. To get original code, click [here](http://pastebin.com/790UvvXN) and select the raw data. And no, `h` is not a CJam program. ;) ``` d=s=>{a=' ',u=n=>r>>n&1?'!':a,v=n=>r>>n&1?'_':a,g='ABCDEFGHIJLNOPQRSTUYZabcdefghijlnopqrstuyz0123456789-? ÿ',h='{vUnWSuz(lTb}[;B7V|>O{vFnWSur lTbf[;B7Vd>O}(O/:7w)^??^BK^0^G',x=y=z='';for(i=0;i<s.length;x+=a+v(0)+a,y+=u(4)+v(1)+u(3),z+=u(6)+v(2)+u(5)){q=g.indexOf(s[i++]);if(q<0)return d`ÿ`;r=h.charCodeAt(q)}return x+` ${y} `+z} ``` Called as `d("7-seg display")` or similar. Works in Firefox 40, but may not in other browsers. For some reason, the HTML/JS snippet does not save the non-printables, but you can copy-paste the raw data from [over here](http://pastebin.com/790UvvXN). # Ungolfed: (**Note:** `g` and `h` have been padded with spaces to match `8`, `-`, `ÿ` and `space` with their corresponding Unicode values.) ``` d = function (s) { t = function (n) { return Math.floor(n) % 2; }; g = 'ABCDEFGHIJLNOPQRSTUYZabcdefghijlnopqrstuyz012345679? 8 - ÿ space '; h = '{vUnWSuz(lTb}[;B7V|>O{vFnWSur lTbf[;B7Vd>O}(O/:7w)?K \u007f \u0002 \u0007 \u0000'; x = y = z = ''; for(var i = 0; i < s.length; i++) { q = g.indexOf(s.charAt(i)); if (q < 0) // if g does not contain the character return d('ÿ'); // ÿ is equivalent to the error character, '\u0007' r = h.charCodeAt(q); x += ' ' + (r % 2 === 1 ? '_' : ' ') + ' '; y += (t(r / 16) === 1 ? '!' : ' ') + (t(r / 2) === 1 ? '_' : ' ') + (t(r / 8) === 1 ? '!' : ' '); z += (t(r / 64) === 1 ? '!' : ' ') + (t(r / 4) === 1 ? '_' : ' ') + (t(r / 32) === 1 ? '!' : ' '); } return x + '\n' + y + '\n' + z; } ``` # Explanation: I immediately noticed that the 7 segments, converted into `0`/`1` bits, would go well with the first 128 Unicode characters. The problem with this idea is that 1/4 of these characters are non-printable control characters. Using them in my code would make it look look incredibly messy (or incredibly intelligent; I haven't decided which one). To solve this while keeping the rest of the code simple, I came up with this idea: With the exception of `-`, **space**, and **error**, none of the characters were missing both of the lower vertical segments. So to make sure that all those characters stayed between `0020` and `007f`, I simply mapped the **64** and **32** bits to these segments, like **so:** ``` 1 --- 16 | | 8 2 --- 64 | | 32 --- 4 ``` The other 5 segments' numbers aren't too important; they could be arranged in any other way and still have all the same characters "in-bounds". As an example, here's the encoded version of **A**: ``` 1 --- 16 | | 8 2 --- 64 | | 32 Dec: 64 + 32 + 16 + 8 + 2 + 1 = 123 Hex: 40 + 20 + 10 + 8 + 2 + 1 = 7B = u+007B = { ``` I then stuffed the encoded version of each 7-seg character in `h`. However, `8` resulted in `007f` (the **delete** control code; constant no matter how the segments are arranged), **space** resulted in `0000` (the **null** code; also constant), `-` resulted in `0002`, and **error** resulted in `0007`. I copy-pasted the raw bytes into the correct position for `8`, `-`, and **error**; **space** was easily achieved with `\0`. After all this encoding, all I had to do was use it to decode the string and output it in a 7-seg readable format. I used a **for** loop and three variables (`x`, `y`, and `z`, each corresponding to an output line) to go through each character in the string and add its 7-seg equivalent to the output. I chose `ÿ` for the **error** character because AFAIK, it's not on any keyboard, and it's the last character in the `u+0000-u+00ff` range. Perhaps I could have been witty and chosen `Ξ` (Greek letter xi) instead.... ;) **Edit 1:** Saved a bunch of space by creating mini-functions to determine whether `!`, `_`, or is needed. **Edit 2:** Saved a bunch more space using the tricks I've learned since I last visited this post. As usual, suggestions are greatly appreciated! ]
[Question] [ Related: [Counting polystrips](https://codegolf.stackexchange.com/q/155983/78410) ## Background [Link-a-Pix](https://www.conceptispuzzles.com/index.aspx?uri=puzzle/link-a-pix) is a puzzle on a rectangular grid, where the objective is to reveal the hidden pixel art by the following rules: * Connect two cells with number N with a line spanning N cells, so that the two cells are at the two ends of the line. * The number 1 is considered connected to itself (which makes it an exception to the rule of "connect *two* cells"). * Two different lines are not allowed to overlap. * The puzzle is solved when all the given numbers on the grid are connected by the above rules. There may be some unused cells after the puzzle is solved. The following is an example puzzle and its unique solution. ![](https://i.stack.imgur.com/Akxry.jpg) (Source: [The NP completeness of some lesser known logic puzzles, 2019](https://dspace.library.uu.nl/bitstream/handle/1874/383821/Scriptie_Mieke_Maarse_5750032.pdf?sequence=2&isAllowed=y)) A **polylink** is defined as a single line on a Link-a-Pix puzzle. It is identified by the collection of cells (i.e. a polyomino) the line passes through, the endpoints, and the path (i.e. a Hamiltonian path) defined by the line. It is somewhat similar to a polystrip, except that the strip can touch itself side-by-side, and the two endpoints of the strip are marked. The following are pairwise distinct polylinks (X's are the endpoint cells and O's are the other cells on the strip). A rotation or reflection of a polylink is different from the original unless they perfectly coincide. ``` X-O X X X-O O-O | | | | | | X O O O O-O O O | | | | | | | O-O O-O O-X X X ``` Some distinct polylinks have the same underlying polyomino and endpoints, as follows. When such a link is used in a Link-a-Pix puzzle, it makes the entire puzzle have multiple solutions, which is not desirable. ``` O-O-O O-O-O | | | | O-X O O X O | | | | X-O-O X O-O ``` Therefore, let's define a **uniquely solvable** polylink as one which does not have another different polylink with the same polyomino and endpoints. ## Challenge Given the number \$n\$, count the number \$a(n)\$ of distinct uniquely solvable polylinks with \$n\$ cells. Due to the definition of a polylink, \$a(1) = 1\$ (the single cell with only one endpoint is a valid "line" on a Link-a-Pix puzzle). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases The "uniquely solvable" makes the sequence deviate from [A002900](https://oeis.org/A002900) from n = 9. There are exactly 10 "ambiguous" polylinks of 9 cells, all of which happen to have the shape of a 3x3 square: ``` O O O O O O X O O O X O x4; O O O x4; O O O x2 X O O X O X O O X ``` Main test cases: ``` a(1) = 1 a(2) = 2 (horizontal and vertical) a(3) = 6 (2 orientations of I, 4 for L) a(4) = 18 (L*8, I*2, S*4, O*4, T is not a link) a(5) = 50 (I*2, L*8, N*8, P*8*2, U*4, V*4, W*4, Z*4) a(6) = 142 a(7) = 390 a(8) = 1086 a(9) = 2938 a(10) = 8070 a(11) = 21690 a(12) = 59022 a(13) = 158106 ``` a(6) through a(13) were generated using a [reference program in Python](https://tio.run/##hVPNjpswEL7nKabKATuBVUh7yopTpT5Bb5YV0cRQJ2AjA1arqs@ezthAku6qvYA9M9@PPZ7u5/Ddmo@3W@VsC3pQbrC26UG3nXXDZhXCJ9s06jRoa@6Js6qg65w2A6udPvPDCqCyDhptFGgDFKQYQCzaUIKv5m2SZVnCA0tvG6@YCQz9gNm6hwLL7Hk8DUzklxTyFLL8IlNwqlPlUJhsT1SkQbVCTuI9KU8cUZyi/khhIXZIhBzhf5kWWb4sLlJGDMA6mvTHFHo@xTwK@aM4yGlPzKegN6OoZotuvEBW2AKLiwzwv5ccNnCawU6VzbFFcAH4ZcK8UCRwGuL0cpbVbVk/V1LkvUoyKAzKLeTZHb3BIz@CnnyUPxBKB8bVu16ezfxd/sbQXE79IVNiJ9EAm8W2OQ/loS2uNLViMzGmZmu1tQT@6kb1cOM6DSLKjK1y5aCY5/fr11WQFOQt2uJy2pA2l4eZ9UvZ9OoVvmH4usD/jUVUTk3VUBSwA/JCq0YZ9JDlyxVVQeNuav04JU9afXgt@FxjTj686M92NDiLIRFe4FpMNMqXDbvyeIPX1M@z1r/g8LY94@TAw4cC9nKZNjIprv@BFAQJvZuev9jEKlQcFZbhS1u6HNu2T/NP4f4joEpK9sv85niAJMUenYsk4a/LgN9ufwA). [Answer] # [J](http://jsoftware.com/), 99 bytes ``` 1#.3>[:#/.~[:(2({.,&(/:~)}.)_1(-"1<./)@|.+/\)"2(#~([:*/@~:+/\)"2)@([:,/,~"1 2/)~&((,-)=0 1)&(,:,.0) ``` [Try it online!](https://tio.run/##JcixCsIwEIDh3ac4Ukjv9HKXVHA4rQQEJyfXCh3Eoi4@gJpXjwWHf/j@Z3XSTtAbtMAQweaCwOF8OtbUyHo/WKNSBsMO38Ie1Qp9hcaEwaWdKOWPrPRCrsOm4GBLzcX@g/JsVi4uQadUPCIH6iMk8sjGEqnSAre36/2VJxcJHgJpU38 "J – Try It Online") Builds up paths starting with `0 0`, filtering the ones that cross themselves. Then it normalizes each path so that every coordinate is non-negative. To check if the path is a unique solvable polylink, the end tiles and the path tiles get sorted and the results are compared to each other. If the count is 1 (for `n=1`) or 2 (both directions are created), it's a hit. [Answer] # [Python 2](https://docs.python.org/2/), ~~292~~ ~~268~~ 265 bytes A slow golf of the reference program. \$a(10)=8070\$ took close to 8 minutes locally. ``` n=input()-1 G=[] for x in-1j,1,1j,-1: for q in range(3**n):v=[0];w=x;exec'v+=w,;w=w+(w-v[-2])*(-1j)**(q%3+3);q/=3;'*n;G+=[{n-min(n.real for n in v)-min(n.imag for n in v)*1j:0<j<len(v)-1for j,n in enumerate(v)}][len(v)-len(set(v)):] print map(G.count,G).count(6)/6 ``` [Try it online!](https://tio.run/##TVCxcoMwDN39FVp62AaSENq0B/GYMnbpxjFQqibQIIhrILlev53aTYYu0tN776R76i/m0NF6rrp3BAWe582kauoHw0UYsUzlBfvoNJyhpjBqgiiwJYwSBo49WRZ0SXvksZQkklHlqyKd1DnFM1be6KspsOPk8ykc83BdCMntGiElP93FfizS01LFqScpzXyVf1PY1sRpobE8/l0gd2EUN7puy/1/WkZNsto22yMSt6bISU3wJyINLerSoBV@ivzmcO0LjYUiKVivazLQlj3PFlU3kAkycQV8I5ab2X6DselQHxFe9YA2NBh9cQ3A5QP3NeZwhb2B3cvzTutOXw1vNsPnvGYxu2cPbMMe2dMv "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes ``` 0ị+ⱮØ.,U;N$¤ḟṭ€)Ẏ Ø0WWÇ⁸’¤¡ṪṭṢƊ€ċⱮ`ỊSH»1 ``` [Try it online!](https://tio.run/##AWEAnv9qZWxsef//MOG7iyvisa7DmC4sVTtOJMKk4bif4bmt4oKsKeG6jgrDmDBXV8OH4oG44oCZwqTCoeG5quG5reG5osaK4oKsxIvisa5g4buKU0jCuzH/MTBSxbzDh@KCrEf/ "Jelly – Try It Online") A pair of links that takes an integer and returns the value of \$a(n)\$. The last two bytes handle the special case of \$n=1\$ since that’s the the only situation where there aren’t pairs of poly links swapping start and end. Handles up to \$n=10\$ in the time limit on TIO but times out for higher values. ## Explanation ### Helper link Takes a list of lists of coordinates and extends it by moving each final coordinate up, down, left and right, filtering out any intersections with the existing list ``` ) | For each list of coordinates: 0ị | - Last member (i.e. most recently visited coordinate) +Ɱ ¤ | - Add each of the results of the following: Ø. | - [0, 1] ,U | - Paired with its reverse [0,1],[1,0] ;N$ | - Concatenated to its negative [0,1],[1,0],[0,-1],[-1,0] ḟ | - Filter out those already in the list ṭ€ | - Tag each onto the end of a new copy of the list Ẏ | Join all outer lists together ``` ### Main link Takes an integer argument n and returns the value of a(n) ``` Ø0 | [0,0] W | Wrapped in a list [[0,0]] W | Wrapped in a list [[[0,0]]] Ç⁸’¤¡ | Call the helper link n-1 times Ɗ€ | For each of the lists of coordinates: Ṫ | - Tail ṭṢ | - Tagged onto sorted list of the rest ċⱮ` | Count the number of times each list appears Ị | <= 1 S | Sum H | Half »1 | Max of this and 1 ``` ]
[Question] [ ## Background Information Inspired by [this answer](https://gaming.stackexchange.com/a/385114/189591) on Arqade SE Minecraft has rails which allow you to move minecarts around on them for transporting players, entities, and items. There are many types of rails, but today we're only interested in regular rails, which are also the only type that can curve. When you place down a normal rail that has two adjacent rails, it will connect them. If they are not on opposite sides of the rail, the rail will curve to a 90 degree angle. However, if there are more than two adjacent rails, it can't connect all of them. In that case, it will always favor going **south-east** (this is called the south-east or Z-X rule) (for this challenge, north is up, east is right, south is down, west is left). If there is a T-junction, the rail will always connect to the "vertical" branch of the T, and then it will prioritize south over north if the main branch is east-west, and east over west if the main branch is north-south. If there is a four-way junction, the rail will connect south and east. ## I/O For this challenge, you will need eight distinct characters: empty space, vertical rail, horizontal rail, up-left curved rail, up-right curved rail, down-left curved rail, down-right curved rail, and placeholder. You may select any characters; I choose to use box-drawing characters in my examples. You may count these eight characters as one byte in your code (this is just to allow people to use box-drawing characters instead of just like `" |-WXYZ#"` or something not as nice-looking). You will be given input in a convenient format for a layout of existing rails. This will be a grid, so you may take it as a matrix of characters, a list of strings, newline-separated strings, etc. Anything reasonable. To simplify a bit, **your input will only contain straight rails, placeholders, and blanks**. Your output should be a grid of the same size, but in each placeholder you are to place a rail according to the rules given. To make this challenge a bit simpler, every placeholder will always have at least two adjacent rails that are already facing the appropriate direction, so you should not change any cells except the placeholders. Note that it is possible for the rails to be on opposite sides of the placeholder, in which case you may need to place down a straight rail. ## Detailed Example This contains every possible configuration: ``` .═.═.═. ║ ═ ║ ║ .║ ║ ║ ║ ║ ║ .═══.═. ║ ║ ║ .═══.═. ``` The output for this would be: ``` ╔═══╔═╗ ║ ═ ║ ║ ║║ ║ ║ ║ ║ ║ ╔═══╔═╗ ║ ║ ║ ╚═══╚═╝ ``` Note that it's valid to have rails facing the wrong direction next to placeholders. You are guaranteed that at least two adjacent rails *are* facing the right way though. Technically, in Minecraft, this might cause the side rails to turn to face the new rail and then curve, but in this specific challenge, we'll just assume that existing straight rails will not turn, and you just need to connect up exactly two of the adjacent, correctly-oriented rails in accordance to the S-E rule. ``` .══.══. ╔═════╗ ║ ║ ║ ║ .══.══. . ╔══╔══╗ ║ ║ ║ ║ ║ -> ║ ║ ║ ║ .══.══. . ╚══╔══╝ ║ ║ ║ ║ ║ .══.══. ╚═════╝ ``` You're running out of space on your minecart to write your code, so your code must be as short as possible! This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins (remember that you may count your eight I/O characters as one byte). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes ``` ≔⪪##╗#║╝╗#╔═╔╚╔╚╔¹ηWS⊞υι≔⪫υ⸿θPθFθ¿⁼.ι§η⊖⍘⭆⪪⭆KV﹪÷⊕⌕ηκX²λ²¦²⮌κ²ι ``` [Try it online!](https://tio.run/##dVDNasJAEL77FEO8TCAV6rUniy1YsIQKPfUSktEsWXfj/sQ@hkJDodCXy4ukkx@0F2Fn5vt2/ifNE5PqRLbtwlqxU7gppXAYTKdN/c1yburfAX019anXPxcdRHAfRpCHD5NjLiQBrlTp3cYZoXYYhhB7m6OPQHDEWP9FC9V9BR8m4NwDe9ZeOlFyjsOObrUBBiC2gE8Hn0iLwSzoinDBPmrhViqjT8wjWFJqaE/KUYaPiaWx92DWSTnuc@UxUfGu1Sv5faIU8ghrnXmpeXS3FJXIiNG15rNQWdenCDky1kcyOI9Admw@qAjeqCJjCYvxN@QlSFoap@Xl23bG17vIhO8KDGCw58msAxfWk/@@0/Cuube97V0l/wA "Charcoal – Try It Online") Link is to verbose version of code. Byte count is adjusted for deverbosifier bug and box drawing characters. Explanation: ``` ≔⪪##╗#║╝╗#╔═╔╚╔╚╔¹η ``` Create a table of box-drawing characters which serves two purposes: 1) to look up to see whether an adjacent box-drawing character wants to connect 2) (after some bit twiddling) to look up which box-drawing character to place. ``` WS⊞υι≔⪫υ⸿θPθ ``` Read the grid and write it to the canvas without moving the cursor. ``` Fθ ``` Loop over the grid again. ``` ¿⁼.ι ``` If this is a placeholder, then... ``` §η⊖⍘⭆⪪⭆KV﹪÷⊕⌕ηκX²λ²¦²⮌κ² ``` ... overwrite it with the result of looking up the adjacencies of connecting box-drawing characters in the table. The characters are checked in the order above, right, below, left, so the table is designed so that characters that join from above are in odd 1-indexed positions in the table, while characters that join from the left are in the right half of the table. We then need to find the character that connects above, right, below or left as appropriate, which is normally a rotation of the bits by 2, but because of the way base conversion works in Charcoal we end up reversing the bits, which means that we need to swap each pair of bits to end up with the correct output character. ``` ι ``` Otherwise just overwrite the character with itself. Example box-drawing character lookup: ``` ╔═╗ ╚.╝ ║ ``` * The character above is in position 10, which does not have bit 0 set, so the resulting first bit is `0` * The character to the right is in position 6, which does have bit 1 set, so the resulting second bit is `1` * The character below is in position 5, which does have bit 4 set, so the resulting third bit is `1` * The character to the left is first seen in position 12, which does have bit 3 set, so the resulting fourth bit is `1` * The first and last pairs of bits are then exchanged resulting in `1011` * The eleventh character in the table is `╔` so this is the resulting output. [Answer] # [Python 3](https://docs.python.org/3/), 394 378 370 328 bytes ``` def p(s,i,R,C,H='═',V='║'): v=i%C and s[i-1]==H v|=(i//C and s[i-C]==V)<<3 v|=(i%C-C+1and s[i+1]==H)<<2 return' ═║╗══╔╔║╝║╗╚╚╔╔'[v|(i//C-R+1and s[i+C]==V)<<1] def f(s,i=0): t=s.split('\n');R,C,s=len(t),len(t[0]),''.join(t) for c in s:print([c,p(s,i,R,C)][c=='.'],end='\n'[:-~i%C==0]);i+=1 ``` [Try it online!](https://tio.run/##dVDBasMwDL37K0ShOKZOmqy3tjrl0nMPvWQ5jDZhHsUNcVYYlH1DAyuDwX6uP5LJTpuUbgPZst6T9CQXb9XzTk8aE@JgMAjOp2N32PlUAz2g9TUL7KOLXHDLHVvra/9lSYkxE1lFSgp6xpVe6qD17I6mfNbN0V1/Zd31@a1E8s0my6HwjFRyKWO5QE4Elyvray6mDPaohjE86Q2YRPlRirgg8ICeGo97PCZ8JebzyYUbxn48ii7syFUR@8CgzKrXUnNwI9Tn0@f1Zz6cEfJ9xb@cWZwn@4PT85d906tklDK7RG6XwNCOXKEJTLFVlccfNRczu5nBbaa9SkjnkjAVkvPgZacsyCDflbAGpcFMi1LpykvWsvsWkSZrRB7wVGZ6g7ZpMvXfaUlEajRTI4wa0g8Fa4sFoygSzQ8 "Python 3 – Try It Online") A very naive method. Receives as input a string and iterates over its characters. If a character is a point (a placeholder), replace it with the character returned by `p`. The function `p` builds a "4-bits integer" `v`, where: * if its 1st bit is set, the placeholder has a valid connection with the west; * if its 2nd bit is set, the placeholder has a valid connection with the south; * if its 3rd bit is set, the placeholder has a valid connection with the east; and * if its 4th bit is set, the placeholder has a valid connection with the north. A invalid connection occurs with a direction when 1. the rail is on a border of that direction (the first placeholder in the example given by the OP has an invalid connection with the north and the west since it's in the border, so its 4-bit integer is 1010). 2. the rail of that direction is misaligned with the placeholder (the fifth placeholder in the example given by the OP has an invalid connection with the east since the east rail is misaligned, so its 4-bit integer is 1011). After this 4-bit integer is built, it returns the corresponding box-drawing character using this integer as index of a string. [Answer] # JavaScript (ES6), 144 bytes Expects and returns a matrix of characters. Uses `01234567` instead of `═║.╔╗╚╝`. ``` m=>m.map((r,y)=>r.map((v,x)=>v-3?v:(a=r[x-1]==1,b=r[x+1]==1,c=y&&m[y-1][x]>1,d=(m[y+1]||0)[x]>1,a+b+c+d>2?(a=a*b?0:a,c*d?0:c):c)*6+a+b*8+d*4&7)) ``` [Try it online!](https://tio.run/##dVBNT4NAEL3zKzYc2l2gm1aNmjZLT3r1wBF72C5QafioCxKI9T@0icTExD/HH8EBFEzVZJeZN@/tG2a2POOJkP4unUSx49Yeq0NmhjTkO4ylURBmyg5kRg4gm5wvsznmTNr5ZLZibGasm1zvcsGK0Si0C6DsfGXODIdhgMDu91PSlbi@1oXumGdLsOHaejmdc0NoDkRB4GiXOki0a93RLkZXhNQWYkhFVXmoyiOtyteqfKvK96r8UBeKIt3HJ1@6eOwlY0Kly51bP3CtIhJ4SmgaW6n0ow0mNNkFforV@@g@Ugn1YnnDxQNOEDPRs4JQCE2SQQSSZmrZ0DalVK5aLBpsUT9y3PzOw4IQsoDH0gUf5OGwRSKOkjhwaRBvMDCDUbfJrPWwM1hJRug29iOsquQ7a1oT5YXUMOmhvwqM3mwAdfGo0CbpUQt@cofuDG//Z@GHER0Kbe1LjrqonNCgV/r2/ecv1YnP706f "JavaScript (Node.js) – Try It Online") ]
[Question] [ ## Challenge: **Input:** a string, consisting of only printable ASCII characters **Output:** a truthy/falsey value whether its characters are in alphabetical order (based on their UTF-8 unicode values), from any starting point inside the string including wrap-around by going left-to-right For example: `xyzabc` would give a truthy result, because we could travel `a→b→c→x→y→z`, but `xzy` would give a falsey result, because all possible starting points (`x→y→z`; `y→z→x`; `z→x→y`) are not in the correct order. This sounds pretty simple, right? But there is one catch, as this is a [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenge: your program/function has to be in the correct order*†* as well. *†: Based on the order of the characters in your own codepage. i.e. a program written in [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki) need to be (with the wraparound of course) in [the order of its own codepage](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page), instead of UTF-8 order.* ## Challenge rules: * The input can be in any reasonable format. Can be a string, read from STDIN, a list of characters, etc. (No, you are not allowed to take a list of unicode values - which would basically be an integer list - unless your language does this conversion by default (i.e. Java (`char` only), Whitespace, etc.) * The input is guaranteed to be printable ASCII (range \$[32,126]\$ / `[' ','~']`). * If your program/function is written in a different codepage, it does not necessary have to hold a truthy value when used as input for itself. The source code does need to be in the correct order based on the used codepage of course. * The input is guaranteed to be non-empty. (An input of one or two characters will always result in a truthy output.) * The input (and your source) can contain multiple of the same characters. * This is [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'")[code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), for which the longest answer counting only **distinct** bytes wins (i.e. if your source code is `ABBCabbc1223` your score would be 9 for `123ABCabc`). ## General rules: * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: Truthy: ``` ~ ab ba ``` *5a Test test xyzabc aaabbbccc aaabbbCCC AAAbbbccc msuwy !#),-./0123:;<?@BCFGILMNOQTWX]^_bf oqqx}}~#$'''*+-./33489=?ABCHLQQQRTW[\]^_abcfgjkklmnno ``` Falsey: ``` xzy C-U TeSt tesT aaaBBBccc M3"b=J7Uh:kg&F~\p`GLx?9#!%XCOZBv.m_)Y4V* ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ ... 172 distinct bytes ``` \]^_abcdefghiijklmnopqrstuvwxyz{|}}}~ƵƵ€Λ‚„…†‡ˆ‰ŠĆĆĆŽƶĀ‘‘’’““””••–—™š›œćŸā¡¢¢¢¤¤¦§¨©ª«¬®¯°±´¶·¸º»¼½½¾¿ÀÁÁÂÃÄÅÇÌÍÐÐÐÐÐÐÑÒÓÔÕÖרÙÚÛÜÝßàáâãäåçèéêëìíîïðñòóôõö÷úü -.0123456789;<>@ABCDDDHKKOPQRSTUVWXYZ ``` [Try it online!](https://tio.run/##TdDZMoJhHMfxc1fhBhj7MoyxdGCmA/s6lilCtpCdzFNSJ8yg0Eol7VpomxQz/19vJ2ZcxHMjyXtkPt8r@KrUMrlSUS7PzM7Ny@QLi4ql5RWlcnVtfWNTtbW9o97d2z84PDo@OdVoNGelVCnFdZEfO2c2zh4583Hm4sz9beAsLriKhj9CoZQuMs4sYlYxh5hTzCNm4szM9R7BzVlOMBWNQraoJTd5RN4KH/kpQEEKUZgiFKUYxSlBSUpThrKUow/KU6Hik77AoK3Q4Rx6XMCIS1zh@p8b3MIEM@5wjwdYYIUNdjjgxBNccMODZ3jxAj8CCCKEMCJ4RRQxxJHAG96RRAppZJBDvqq6prauvqGxqbmlta29o7Oru6e3TyKR9EulA4NDwyOjY@MTk1PT5XJl2y8 "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##RZFtU1JBFMff76dAqBhI6AFM8Qm5l9FKjVBQNBLuJVQiQAIRTJjVTN/UTIWVjwVkPpJiCTqkNbMHeNNMH2K/CF3u5DS/3@zs7JyZ/zlnAyGO97irM5GYXipRtUuk@hi8vqBqH3FwvOuRe3Rs3ON57H3i8wcmgk9D4cnIVDQ2/WwmHo8nKvlKns5l/6xRvErxR4q3KE5RnP69QHGunCot1CifVwolTPGy6IrouuiGaEY0SfESnc@U0xQXy8nSYvm0NEvSJCOyKbBFtskO2SV7ZJ9kyQE5JDlyRI5JgZyQU1IkP8gZORf4SX4BhlmBOXgO8/ACFuElvPo/mcAbeAtJWIJ38B4@wDKswCqswTpswCdIQRoy8Bk24Qtsww7swh5k4SscwCHk4Ai@wXc4hjwU4ASKcIYkKvX1Gzc12oZbjU26ltb2DgPDGo3G293dpvvmvn6LdWDQNjRcrVfYqwnE8YjnkNPpRMoGDlncoTAK1w5ho8KyEcdxPM@7XBc3lmWRwWD49@YLTU7FJHUyRb1Kfa2W2dzSqu9g2M6uOz2990xmy6Dt4YiDH0WBYDAq/I7sklwuV14VijUabZOuTW8wm819D@xCEef1@v0BFJ2OIVZlFRrpFxux1HIZhqml9WqkfNvdRut4s3fsSmfCPuHs6onqdbK6yzbWNMxE1D6HYkg7oPwL "05AB1E – Try It Online") (note: the "all test cases" version omits `]` and `ë`, since those don't play well with the header and footer required to run the code repeatedly). Uses the [05AB1E code page](https://github.com/Adriandmen/05AB1E/wiki/Codepage). [Validate restricted-source and scoring](https://tio.run/##TcLHTgJRGAbQvU8xYa3G3mMsszBhgb3FEsFRxwLKDHbMteFGExUbVsCuqFhAg6jJ/82wMfEh7osgzsqc41B6rLKUTOqfmmeW3kX4@k29sqLKdpsqWKdUSSkR8GVK1zwNQ4hnZFeIlrp22aQ4XE6bJDglRXXKNlV22AWL2ZSeTHZ0dnX3WG29Ul//gCwPDg2P2B2jY05FdY1PTE5Nz8y63e65RCQR4QuhnwPO9jk75uyCMz9ngW8PZ2Hdr3n@6B@JqMY42zP6jIfGI2PQ6OVsiy8F9QBnMd2rrehv2jwFKGg4S7mgS7qia7qhWwrRPT1QmB7phaL0Sm8Uo3eK00fKJ32BYT5lAYtYwjJWsIo1rP@zgU14sYVt7GAXe/BhHwc4xBFO4EcAQZziDOe4xBWucYNbhHCHezwgjEc84RkviCCKV8QQTxMyMrOyc3Lz8gsKi4pLy8orKquqRVGsMZsttXX1DY1NzS2tbe2/). The useful code is just: ``` Ć # append the first character of the input to the input Ç # convert to a list of codepoints ü- # pairwise subtraction 1@ # >= 1? D # duplicate O # sum Q # equal? Z # maximum ``` The rest amounts to NOOPs. ]
[Question] [ This challenge is based on [Project Euler problem 208](https://projecteuler.net/problem=208). Also related to my Math Stack Exchange question, [Non-self-intersecting "Robot Walks"](https://math.stackexchange.com/q/2767118/121988). You have a robot that moves in arcs which are \$1/n\$ of a circle, with each step turning toward the left or to the right. The robot takes in an array of instructions of the form \$(a\_1, a\_2, \dots, a\_{2m})\$ with \$a\_k \in \mathbb N\_0\$. The robot follows these instructions by taking \$a\_1\$ steps to the right, followed by \$a\_2\$ steps to the left, followed by \$a\_3\$ steps to the right, continuing in this alternating fashion until completing the final instruction by taking \$a\_{2m}\$ steps to the left. If the robot is in the same position (and same orientation) that it began in, then it terminates, otherwise, it starts the sequence of moves over. --- The goal of this challenge is to write a program that takes in an integer \$n \geq 2\$ and a list of instructions \$(a\_1, a\_2, \dots, a\_{2m})\$ and computes how many self-intersections the robot's path contains. --- # Example For example, with \$n = 5\$, these are the following walks for [`[1,2]`](https://peterkagey.github.io/project-euler-208/?n=5?w=1,2), [`[1,3]`](https://peterkagey.github.io/project-euler-208/?n=5?w=1,3), [`[1,4]`](https://peterkagey.github.io/project-euler-208/?n=5?w=1,4), [`[2,3]`](https://peterkagey.github.io/project-euler-208/?n=5?w=2,3), [`[2,4]`](https://peterkagey.github.io/project-euler-208/?n=5?w=2,4), and [`[3,4]`](https://peterkagey.github.io/project-euler-208/?n=5?w=3,4) respectively: [![All 5-robot walks.](https://i.stack.imgur.com/eGwCG.png)](https://i.stack.imgur.com/eGwCG.png) The number of intersections are `0`, `5`, `10`, `0`, `5`, and `0` respectively. ### Play Want to try it out for yourself? You can use the left/right arrow keys on your computer via [this web app](https://peterkagey.github.io/project-euler-208/?n=6&w=5,3) forked from Github user [cemulate](https://github.com/cemulate/project-euler-208). Change the step size by modifying the `n=6` parameter in the URL. Change the initial walk by modifying the `w=5,3` parameter in the URL, or remove the initial walk by removing the `&w=5,3` parameter altogether. --- # Test data ``` n | instructions | output ----+---------------+-------- 3 | [3,0] | 0 3 | [3,1] | 3 3 | [3,3] | 1 3 | [3,2,3,1] | 2 6 | [1,1] | 0 6 | [5,1] | 3 6 | [5,2] | 1 6 | [5,3] | 3 6 | [5,4] | 6 6 | [1,1,1,5] | 3 6 | [1,2,3,4] | 0 6 | [1,2,3,4,5,6] | 8 7 | [2,3,1,3,1,1] | 14 7 | [3,1,4,1] | 56 19 | [1,2] | 0 ``` Note: You can assume that the instructions will not cause the robot to *retrace* it's track (as in \$n = 6\$ and `[1,4,2,3]` or \$n = 7\$ and `[2,3,1,3]`.) That is, the robot may intersect its path tangentially or transverally, but it will not retrace a step. You can also assume that there will be a finite number of intersections (e.g., `[5,5]` will never be an instruction for \$n = 6\$). --- # Challenge Your program must take two parameters * A positive integer, `n`, the reciprocal of which gives the step size, and * An even-length array of nonnegative integers, `a`, the instruction for the robot. Your program must output a single integer, which counts the number of times that the robot intersects its path, tangentially (as in \$n=6\$ with `[5,3]`) or [transverally](https://en.wikipedia.org/wiki/Transversality_(mathematics)) (as in \$n=5\$ with `[1,3]`). This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 1533 bytes ``` def w(n,ll,ans): global p,q from math import sin,cos,pi,atan2 def y(s,e,f,a,b): x,y=f(s),f(e) g=lambda a,b,x:0<=(x-a)%2<=b-a while e-s>1e-15: m=(s+e)/2 z=f(m) if x*z<=0: e,y=m,z else: s,x=m,z return (g(a,b,s)or g(a,b,e))and[s]or[] from fractions import Fraction as R s,v,d=(0,0,R(1,2)),[],1 while True: for l in ll: b=s[2]+R(1,2)*d c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d) if l: v.append(c) s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2)) d=-d if s[2]==R(1,2): break e,l=enumerate,len(v) q=lambda x:all(abs(i)<1e-7 for i in x) p=[] h=lambda i,p:any(all(q([j-k]) for j,k in zip(i,a))for a in p) def z(u): global p,q for i in u: if not h(i,p): p.append(i) if all(abs(i)<1e-6 for i in s[:2])and l>1: [z([c[:2]]) for c in v if c[3]==R(2)] x_=[t_ for n,c in e(v) for m,d in e(v) if (n-m)%l not in [0,1,l-1] and len(t_:=[(f,t) for f,g in [(c,d),(d,c)]if not q(x:=[f[5][i]-g[5][i]for i in[0,1]])and (a:=x[0])**2+(b:=x[1])**2<=4+1e-14 and(t:=sum((y((r:=[1,-1][b<0]*2/pi*atan2((1-(u:=a/(a*a+b*b)**.5)*u)**.5,u-1))-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,*sorted(f[6:]))for i,j in[(1,0),(0,1)]),[]))])==2] [z([i for i in x[1] if h(i,x[0])])for x in[[[(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t]for f,t in t_]for t_ in x_]] print(len(p),sep='',end='') if len(p)!=ans: print(min((abs(i[0]-j[0])+abs(i[1]-j[1]),n,m) for n,i in e(p) for m,j in e(p) if n!=m)) else: print('') else: print(0) ``` [Try it online!](https://tio.run/##dVTbUuM4EH1OvkLzQEVy2mA7Ccy6onncD5jaN6@Kkm@gYDvGdiCk@HemW7JDYGtJUVIfd5@@q30bHvfN6mfbfXzkRcleeQNVBbrpRTyfPVT7VFeshef5rOz2Nav18MhM3e67gfWmgWzfQ2tAD7qJ5jMieOM9FFCChpQYZkd4kyXvBZS8ECg/yErXaa4ZKsAxDraSH30trqKtTH2NCq@PpipY4fe/wsIPN8QxqyXvl4W4iUg4IV9NVDNTsqN32srAKs0KdFXDie5F1RcO7OE4gl0xHLqG8QdOrnux75i7FkLoJk96te8SNSZadjobzL7pp2z/HgGme/Z7jrQvkEseQAC/eQiREJAoCOdj@P90B@u/RCcVMw2rKhtOKvskUktn4uUEZbJf8t88gkZ4FeTA@yRQPhaWp15rBPRJqHystRMFxpv6k7qXT3Vw9LOXa922RZPzTLjsJc@SjULGJTFmyZ2ypBYM1ZJ4z6C9@VNs4gq9CEuTS59CRTcUvZROxSXUFfppjqWvZNEc6qLTA96Lhr@g5fPU62Osq4rrtOdGbLGtd4wKY6gwR9RrJdX9cdI20Ma6eeNk88yTnf@khDXYwROZnEzLceaEIEwT0go3fCd@sGFdzu3s7OoQj8Vq9gN7RIrW5TBrp6oZ5MHvX4O9/Qy2T@JI0bCw6ldItsmJJxmBY4QZab0w5MiSla1UJBRtwb1MhnurgktDSgVWyMo15GcZ7Xjj1@KqsjEinAQQQuWHilmvWNjhPpYJL2Fw5iU8WD2eQY4tzCETakzxmR9RtaRWG@U/uHPKhYiVy4XrWB5xRITnRUuekhBaYSvXS1rCNTnnQyz7Q835G@cd8oaAUSXpNlBedNMaz74BnIc@P8RS33Dt6WXqpchzvRHewZ5w8EMhfAPdcgdjt4eYazucyDGIMQY7mGfAD8HrcQmLnJfJbaxc5w3sKA@cxQATx3SEoiUUeEgZqbE75mLUMC0qMbXe5qssz5FYEizpxaIYuxDlxZZYRJy5BuWKb5s03FsJG0xe7hX5bjvTDJwa1uIOF61cLABHDA/hVsl9@iHxqbVT6AxqdOVmj16BHUW5dGJIIvYFGqjFOEnGTU47TdLuLNMI/JC13d/zY@hc2AgmzEGBmH/0slssFoyt2DtLVhAoNv29s2B@xsNLfPWJry7x8BOP4GzzziLEbwkPv/IEE775L/@IR9/5R3z1P/rrS/z2wi/@Nuq7fmjjXKvv8Yw4bOBWofwT8TvCbVb2PyQ8XE8fCFp/JrxBz@FfI9OXjLHW8@SVe7VuefGiKzDXfVsZbM/7Qghx8eZM@L/NQqiPPw "Python 3.8 (pre-release) – Try It Online") ## [Python 2 (PyPy)](https://tio.run/##dVRNU@M4ED07v0JzoCI5bbCcBHZTiOP@gKm9eXyQv0BgO8ZyIEnx39mWZCWBmYWicD91v@5@6lZ/GJ@2XRL1h/7w@VlWNXmnHTQNyE6zzSx4bLa5bEgPr7OgHrYtaeX4RFTbb4eRaNVBsdXQK5Cj7JJZYAgOVEMFNUjIDUOwh4OoqWZQ04qh/Sga2ealJOgA@018L@g@kuwquRd5JNHh/Uk1Faki/cCriK8NR9AKqhcVu0mMcUS@1lAFqib78HgvYusUVJiqhaP5rhpdOVDDfgILKMUjNWmxGvdhKxqqcTd0hBZkO5CSya5MdbYd0mzquR5kMaptp33j/0wAkZr8nAVa0Bhi@Ek5JAwJ34QJLQWfTb38O@xsMTXyN0R1pGlsbbnQaZItXGBYGqgQekF/0gQ6FjZQAtVpnEWoMs3DXjHQKc8iFN6ZDFvII@8ell4URx@8Xcu@r7qSFsxJIWiRrjNkXBjGIr3LLKkFebYwvCfQfkW@NnaFWZilKUVkSsU0pnohnItraKjkywzvoRFVt2urQY74XXX0DSNf/cXvNzLXdM/u8X7vZkFv5Xrypwr6jewOVDYNfaXP0QsjRrdneDHKHVVPcdwYM5g0SM/c3B3pzhZxObJWcWW8dptJmm47kiek6F3FQe81UsiD5yatKU/Z8m7JiUGnmyQzw0GaB@5vExfAnFXYoE9QpEsrCkpypGlhojKrm/FvofzibwJoF7XsqrGV4VkaA4cm4plzCPZWnmAiqOHROlEcZryjEgrmHQMcaJHW5i5VFj26/758w5pNPCbpK5W2l1eaMx/vr8/7yFAu8jB/WC3MIq7@6LYT8oZOjiwMr9cTPoiUAzaR5vdxFiY3vQrtG0Epj3bhzrrCLuJs8h@F3rV0MuiBDpGCYfEM01CMGyrtzCLPyDA6WdDczusJiDj88hWGGte0Kmmd3m4yNysKno0MOKsx6oZqsIxBmrFzu0b/8Y9N7v2MpLS@2B9l96S@WB6LsNPIjJ7@/Brh60VTdZ6qPYYSTG5Gco/EzIb0g@pGahanxx13y@asHwJfZkvlfFrM6ubVvBPPhmHhTG5Mjk120LoV6kC54eud3VpJnG36/yFau@Gnal2K@RxBjzkoZrNPLYb5fE7IknyQdAlxRvzPB4lnJ5xf4sszvrzE@RlP4BTzQRLEbw3Ov/LEHl//zj/hyXf@CV/@j//qEr@9yIu/6@y7P7d1rrLv9Uw4rOE2Q/svxO8Mbruyf9zgfOUPDLQ6N7zGzPzvielLx6j1LH2nYSt7Wr3JBtS17huF1/MxZ4xdvFMe/9XNWfb5Hw), 1580 bytes ``` n,ll=map(eval,input().split(' ')) from math import sin,cos,pi,atan2 #and let's implement the bisection def y(s,e,f,a,b):#solve f=0 within (s,e) if x in (a,b) x,y=f(s),f(e) g=lambda a,b,x:0<=(x-a)%2<=b-a while e-s>1e-15:# or g(a,b,s)!=g(a,b,e): m=(s+e)/2 z=f(m) if x*z<=0: e,y=m,z else: s,x=m,z c,d=g(a,b,s),g(a,b,e) #c,d #True,True [s] #True,False [s] #False,True [s] #False,False [] return (c or d)and[s]or[] from fractions import Fraction as R #the start point s=(0,0,R(1,2)) #now let's compute the arcs #we need to store x0,y0,angle,length,direction,center,start angle,end angle #arcs array v=[] d=1#the direction, 1 for clockwize while True: for l in ll: b=s[2]+R(1,2)*d#start angle c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d)#the arc if l: v.append(c) s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2)) d=-d if s[2]==R(1,2): break e,l=enumerate,len(v) q=lambda x:abs(x)<1e-7 p=[]#array of intersection points #like in array h=lambda i,p:any(all(q(j-k) for j,k in zip(i,a))for a in p) def z(u):#add points if not in array global p,q #print(p,u) for i in u: if not h(i,p): p.append(i) if all(abs(i)<1e-6 for i in s[:2])and l>1: #returned to the same point for n,c in e(v): if c[3]==R(2):z([c[:2]]) for m,d in e(v): if (n-m)%l not in [0,1,l-1]: #compute the intersection x=[] for f,g in [(c,d),(d,c)]: a,b=[f[5][i]-g[5][i]for i in[0,1]] if q(a)and q(b): break if a*a+b*b>4+1e-14: break u=a/(a*a+b*b)**.5 #the angle from a to b r=[1,-1][b<0]*2/pi*atan2((1-u*u)**.5,u-1) t=sum( (y(r-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,\ *sorted(f[6:]))for i,j in[(1,0),(0,1)]),[]) #that's it if not t: break x.append([(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t]) else: #intersection points z([i for i in x[1] if h(i,x[0])]) print(len(p)) else: #infinite, return 0 print(0) ``` [Try it online!](https://tio.run/##dVRNU@M4ED07v0JzoCI5bbCcBHZTiOP@gKm9eXyQv0BgO8ZyIEnx39mWZCWBmYWicD91v@5@6lZ/GJ@2XRL1h/7w@VlWNXmnHTQNyE6zzSx4bLa5bEgPr7OgHrYtaeX4RFTbb4eRaNVBsdXQK5Cj7JJZYAgOVEMFNUjIDUOwh4OoqWZQ04qh/Sga2ealJOgA@018L@g@kuwquRd5JNHh/Uk1Faki/cCriK8NR9AKqhcVu0mMcUS@1lAFqib78HgvYusUVJiqhaP5rhpdOVDDfgILKMUjNWmxGvdhKxqqcTd0hBZkO5CSya5MdbYd0mzquR5kMaptp33j/0wAkZr8nAVa0Bhi@Ek5JAwJ34QJLQWfTb38O@xsMTXyN0R1pGlsbbnQaZItXGBYGqgQekF/0gQ6FjZQAtVpnEWoMs3DXjHQKc8iFN6ZDFvII@8ell4URx@8Xcu@r7qSFsxJIWiRrjNkXBjGIr3LLKkFebYwvCfQfkW@NnaFWZilKUVkSsU0pnohnItraKjkywzvoRFVt2urQY74XXX0DSNf/cXvNzLXdM/u8X7vZkFv5Xrypwr6jewOVDYNfaXP0QsjRrdneDHKHVVPcdwYM5g0SM/c3B3pzhZxObJWcWW8dptJmm47kiek6F3FQe81UsiD5yatKU/Z8m7JiUGnmyQzw0GaB@5vExfAnFXYoE9QpEsrCkpypGlhojKrm/FvofzibwJoF7XsqrGV4VkaA4cm4plzCPZWnmAiqOHROlEcZryjEgrmHQMcaJHW5i5VFj26/758w5pNPCbpK5W2l1eaMx/vr8/7yFAu8jB/WC3MIq7@6LYT8oZOjiwMr9cTPoiUAzaR5vdxFiY3vQrtG0Epj3bhzrrCLuJs8h@F3rV0MuiBDpGCYfEM01CMGyrtzCLPyDA6WdDczusJiDj88hWGGte0Kmmd3m4yNysKno0MOKsx6oZqsIxBmrFzu0b/8Y9N7v2MpLS@2B9l96S@WB6LsNPIjJ7@/Brh60VTdZ6qPYYSTG5Gco/EzIb0g@pGahanxx13y@asHwJfZkvlfFrM6ubVvBPPhmHhTG5Mjk120LoV6kC54eud3VpJnG36/yFau@Gnal2K@RxBjzkoZrNPLYb5fE7IknyQdAlxRvzPB4lnJ5xf4sszvrzE@RlP4BTzQRLEbw3Ov/LEHl//zj/hyXf@CV/@j//qEr@9yIu/6@y7P7d1rrLv9Uw4rOE2Q/svxO8Mbruyf9zgfOUPDLQ6N7zGzPzvielLx6j1LH2nYSt7Wr3JBtS17huF1/MxZ4xdvFMe/9XNWfb5Hw) Runs in all test cases. # Python 3.8 + [sympy](https://www.sympy.org/en/), ungolfed, covering almost all test cases (except 7 and 19 -- sympy can't simplify some expressions) at least to know what you have to bear. Major improvement in comparison with previous version is that: 1. It simply holds array of intersection points, 2. Any arc end counts as intersection if arc length \$=2\pi\$ unless arc array length is \$1\$ Still need to be rewritten into precise \$i^{\frac{2\pi}{n}}\$ arithmetic ``` from sympy import * R=Rational angle=R(0) class Arc: def __init__(self,x0,y0,angle,length,direction): #','.join('self.%s'%i for i in 'x0,y0,angle,length'.split(',')) (self.x0, self.y0, self.angle, self.length, self.dir)=x0,y0,angle,length,direction self.start=(angle+pi/R(2)*direction)#%(R(2)*pi) self.end_=self.start-self.length*self.dir self.center=(x0-cos(self.start),y0-sin(self.start)) def i(self,a0): #t=symbols('t') #param_form=(self.center[0]+cos(self.start+t), # self.center[1]+sin(self.start+t)) #z=solveset((a.center[0]-param_form[0])**2+ # (a.center[1]-param_form[1])**2-1,t) #return z #to (a + cos(t))^2 + (b + sin(t))^2 = 1 a,b=[self.center[i]-a0.center[i] for i in [0,1]] try: d={frozenset([-cos(3*pi/7) - sin(pi/14), -2*sin(3*pi/7)]):False, frozenset([cos(3*pi/7) + sin(pi/14), 2*sin(3*pi/7)]):False} if (frozenset([a,b]) in d and d[frozenset([a,b])]) or \ (frozenset([a,b]) not in d and a**R(2)+b**R(2)>R(4)): return set() if a**R(2)+b**R(2)==R(4): #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1+and+a%5E2%2Bb%5E2%3D4 #s=R(-1,2)*sqrt(R(4)-a**R(2)) #c=R(-1,2)*a if (a==R(2)): return set([pi]) return set([(R(-1) if b<R(0) else R(1))*R(2)*\ atan2(sqrt(R(4)-a**R(2)),a-R(2))]) except Exception: print((a,b)) raise #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1 if a!=R(0) and a!=R(2) and ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\ abs(float(z0))<1e-6): s=R(2)*(R(-1) if b<R(0) else R(1))*atan2(sqrt(-(a-R(2))*a),(a-R(2))) return set([s]) if not ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\ abs(float(z0))<1e-6): s=sqrt(-a**R(4)-2*a**R(2)*b**R(2)+4*a**R(2)-b**R(4)+R(4)*b**R(2)) r=set() for sg in [R(-1),R(1)]: d=a**R(3)-2*a**R(2)+sg*b*s+a*b**R(2)-R(2)*b**R(2) if d!=0 or abs(float(d))>=1e-6: r.add(R(2)*atan2((sg*s-R(2)*b),z0)) return r #thank you so much for such interesting coding challenge if a==R(0) and b==R(0): return set() print((a,b)) raise Exception('') def end(self): return (self.center[0]+cos(self.start-self.length*self.dir), self.center[1]+sin(self.start-self.length*self.dir), (self.end_-pi/R(2)*self.dir)%(R(2)*pi)) from PIL import Image,ImageDraw d=300 x0,y0=d//2,d//2 r,r0=20,2 n,l=7 , [2,3,1,3,1,1]#5,[3,4] s=(r''' 3 | [3,0] | 0 3 | [3,1] | 3 3 | [3,3] | 1 3 | [3,2,3,1] | 2 6 | [1,1] | 0 6 | [5,1] | 3 6 | [5,2] | 1 6 | [5,3] | 3 6 | [5,4] | 6 6 | [1,1,1,5] | 3 6 | [1,2,3,4] | 0 6 | [1,2,3,4,5,6] | 8 7 | -[2,3,1,3,1,1] | 14 7 | -[3,1,4,1] | 56 19 | -[1,2] | 0''' r'''5 | -[0,1,1,3,4,1,2,1,1,4,1,2,1,3] | 2 ''' ) def add_point(point): global points,count if not any(all(abs(float(j-k))<1e-6 \ for j,k in zip(i,point)) for i in points): points.append(point) count+=1 import re for n,l,ans in\ re.findall(r'\s*(\d+)\s*\|\s*\[(.*?)\]\s*\|\s*(\d+)',s): #[(5,'0,1,1,3,4,1,2,1,1,4,1,2,1,3',2)]: #[('7', '2,3,1,3,1,1', '14')]: # [('6', '1, 1', '0')]: # [(6,'1,1,1,5',3)]: print(n,l,end='') n=int(n) l=[int(i.strip()) for i in l.split(',')] fn='196399/%d_%s.png'%(n,'_'.join(map(str,l))) start=(0,0,pi/R(2)) dir_=1 a_array=[] for count in range(30): for l_ in l: a=Arc(*start,pi/R(n)*R(2*l_),dir_*2-1) a_array.append(a) start=[simplify(i) for i in a.end()] #print(start,a.center,a.start,a.end_) dir_^=1 if (abs(float(start[0]))<1e-3) and \ (abs(float(start[1]))<1e-3) and start[2]%(R(2)*pi)==pi/R(2): break ## else: ## continue ## break print(' ',count,'loops made',end='') a_array=[a for a in a_array if a.length!=0] print(' ',len(a_array),end='') count=0 points=[] if len(a_array)==1: print(' ans=%s, count=%d'%(ans,count)) continue for n,a in enumerate(a_array): if a.length==R(2)*pi: add_point((a.x0,a.y0)) for m,b in enumerate(a_array): if (n-m)%len(a_array) not in [0,1,len(a_array)-1]: #print('.',sep='',end='') try: i_=[list(a.i(b)),list(b.i(a))] p_=list(list(0<=((-R(d_)*(i-st))%(R(2)*pi))<=l_ for i in s) \ for s,l_,st,d_ in \ zip( (i_), [a.length,b.length], [a.start,b.start], [a.dir,b.dir] )) if all(any(i) for i in p_): for t,angle in zip(p_[0],i_[0]): if t:break point=tuple(i+f(angle) for i,f in zip(a.center,[cos,sin])) add_point(point) #print('\n',(n,m),sep='') except Exception: print(i_,[a.length,b.length],[a.start,b.start]) raise #assert count//2==int(ans) print(' ans=%s, count=%d'%(ans,count)) #break continue xy=[sum(map(f,a_array))/len(a_array) for f in \ [(lambda i:lambda a:a.center[i])(i) for i in [0,1]]] image = Image.new('RGB',(d,d),'white') draw = ImageDraw.Draw(image) point=lambda x,y:draw.ellipse((x0-r0+x,y0-r0-y,x0+r0+x,y0+r0-y),'blue','blue') for a in a_array: start=[a.x0,a.y0,a.angle] dir_=a.dir point(*[int((i-xy_)*R(r)) for i,xy_ in zip(start[:2],xy)]) c=[int((i-xy_)*R(r)) for i,xy_ in zip(a.center,xy)] draw.arc((c[0]-r+x0,-c[1]-r+y0,c[0]+r+x0,-c[1]+r+y0), *([int(-a.start*180/pi),int(-a.end_*180/pi)][::dir_]), 0x3a2af6) #image.save(fn,'PNG') #break #image.show() a=a_array f=lambda n,m:(a[n].i(a[m]),a[n].start,a[n].length,a[n].dir) g=lambda a,b:list(list((0,((-R(d_)*(i-st))%(R(2)*pi)),l_) for i in s) \ for s,l_,st,d_ in \ zip( (i_), [a.length,b.length], [a.start,b.start], [a.dir,b.dir] )) ``` Output: ``` 3 3,0 0 loops made 1 ans=0, count=0 3 3,1 2 loops made 6 ans=3, count=3 3 3,3 0 loops made 2 ans=1, count=1 3 3,2,3,1 0 loops made 4 ans=2, count=2 6 1,1 29 loops made 60 ans=0, count=0 6 5,1 2 loops made 6 ans=3, count=3 6 5,2 1 loops made 4 ans=1, count=1 6 5,3 2 loops made 6 ans=3, count=3 6 5,4 5 loops made 12 ans=6, count=6 6 1,1,1,5 2 loops made 12 ans=3, count=3 6 1,2,3,4 2 loops made 12 ans=0, count=0 6 1,2,3,4,5,6 1 loops made 12 ans=8, count=8 ``` But it can generate [such things](https://drive.google.com/drive/folders/1ZuOA_xsqCVoG1C_RFMQ4-jN21EjC8nI_?usp=sharing) although it was not in the task. ![](https://i.stack.imgur.com/UJHFd.png) ]
[Question] [ You will be given a sequence of memory requests and a cache size. You must return the least possible number of cache misses under any cache replacement strategy. An optimal strategy is [Belady's algorithm](https://en.wikipedia.org/wiki/Cache_replacement_policies#B%C3%A9l%C3%A1dy's_algorithm), which you can use if you want to. --- A caching system works as follows: The cache starts out empty. Memory requests come in. If the request asks for a piece of data in the cache, all is well. If not, you incur a cache miss. At this point you may insert the data that was request into the cache for future use. If the cache was full and you want to insert new data, you must evict data that was previously in the cache. You may never insert data that was not just in the cache. Your goal is to find the minimum possible number of cache misses for a given memory request sequence and cache size. --- You will be given the cache size, a positive integer, and the memory request sequence, which is a list of tokens. These tokens can be whatever kind of tokens you like, as long as at least 256 different tokens are possible (bytes are fine, bools are not). For instance, ints, strings, lists are all fine. Ask for clarification if needed. --- ### Test cases: ``` 3 [5, 0, 1, 2, 0, 3, 1, 2, 5, 2] 6 ``` See [wikipedia](https://en.wikipedia.org/wiki/Cache_replacement_policies#B%C3%A9l%C3%A1dy's_algorithm) for a replacement policy that achieves this. ``` 2 [0, 1, 2, 0, 1, 0, 1] 3 ``` Simply avoid adding `2` to the cache. ``` 3 [0, 1, 2, 1, 4, 3, 1, 0, 2, 3, 4, 5, 0, 2, 3, 4] 9 ``` One way to achieve this is by never evicting `0` and `2`, and evicting `1` as soon as possible after its last use. --- Scoring: This is code golf. Fewest bytes wins. [Answer] # JavaScript (ES6), 128 bytes Takes input as `(size)(list)`. ``` s=>a=>a.map((x,i)=>c.includes(x)?0:c[e++,[x,...c].map(m=(x,j)=>(k=[...a,x].indexOf(x,i+1))<m||(p=j,m=k)),i<s?i:p-1]=x,e=c=[])&&e ``` [Try it online!](https://tio.run/##bY5LjsIwDIb3nCIrFKsm9AEjDcJwhDlAlEWUpqOUvjSBURbcvRM6AhWBZVn2r9@fXetf7c2PG86rri/tWNHo6aBjilYPnAd0QAcjXGeaS2k9D3BMd0baJEEZUAhh1ORsKXrr6OUnklHWGFTcKm34qm6UJAPYt9crH6jGlk4A6Pb@6HbDKlMU0JIhqWC5tKPpO983VjT9N694AVxukaXIMmT51BT3Puq5AmCvsV6zj8UzKI@gOSX7r@/356Bi8frRAxTr5v5ROinFpGzn4@1GBH2Ofw "JavaScript (Node.js) – Try It Online") ### Commented This is an implementation of Belady's algorithm. ``` s => a => // s = cache size; a[] = token list a.map((x, i) => // for each token x at position i in a[]: c.includes(x) ? // if x is currently stored in the cache: 0 // do nothing : // else: c[ // update the cache: e++, // increment the number of errors (cache misses) [x, ...c] // we want to find which value among x and all current // cache values will be needed for the longest time in // the future (or not needed anymore at all) .map(m = // initialize m to a non-numeric value (x, j) => // for each x at position j in this array: ( k = [...a, x] // k = position of x in the array made of all values .indexOf(x, i + 1) // of a[] followed by x, starting at i + 1 ) < m // if it's greater than or equal to m, or m is || (p = j, m = k) // still non-numeric: set p to j and m to k ), // end of inner map() i < s ? // if i is less than the cache size: i // just fill the cache by using the next cache slot : // else: p - 1 // use the slot that was found above // special case: if p = 0, x was the best candidate // and we're going to store it at c[-1], which is // simply ignored (it will not trigger c.includes(x)) ] = x, // store x at this position e = c = [] // start with e = [] (coerced to 0) and c = [] ) && e // end of outer map; return e ``` [Answer] # [Perl 5](https://www.perl.org/), 193 bytes ``` sub g{ my($i,$m,$s,@a,%c)=(-1,0,@_); for(@a){ $i++; next if $c{$_}++ || ++$m && keys%c <= $s; my($x,$d); for $k (sort keys %c){ #find which to delete, the one furtherst away my $n=0; ++$n && /^$k$/ && last for @a[$i+1..$#a]; ($x,$d)=($n,$k) if $n>$x } delete $c{$d} } $m } ``` [Try it online!](https://tio.run/##rZBva4NADMbf71OEmh4el7Va52DcHH6P/SlOr0XUa/EcWKyf3V3tyhyMMcbyIiTPXfJ7yF7VZTgM5u0Vtl11cDEnrAgNxQnNUx651z55FK@53OxqN054h7kQUqu2gXyDaYfrXojjUQisGCvUwczT@wiNPO1qCbNxEAvX7OoGzu/cglBHnrRDmrHlCxa4ZKxMTAP2c5w8Woa/WKCTPMuPLZGLmrDglqkfsO0zVapGnfhZ32PVD/s61w1s3YAAQgKPwCdYjUVwqa2@4jR70jMJ34UDt/D3uLpYsKQvfP@cfyJPLAT/YSGYWrD55nIFb1SCUQmn7ac7B@5@iRveAQ "Perl 5 – Try It Online") ``` print g(3, 5, 0, 1, 2, 0, 3, 1, 2, 5, 2),"\n"; # 6 print g(2, 0, 1, 2, 0, 1, 0, 1),"\n"; # 3 print g(3, 0, 1, 2, 1, 4, 3, 1, 0, 2, 3, 4, 5, 0, 2, 3, 4),"\n"; # 9 ``` 193 bytes without indentation, newlines, spaces, comments: ``` sub g{my($i,$m,$s,@a,%c)=(-1,0,@_);for(@a){$i++;next if$c{$_}++||++$m&&keys%c<=$s;my($x,$d);for$k(sort keys%c){my$n=0;++$n&&/^$k$/&&last for@a[$i+1..$#a];($x,$d)=($n,$k)if$n>$x}delete$c{$d}}$m} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` vI∍Dyå≠i¼yª¹N.$sÃÙ]¾ ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/zPNRR69L5eGljzoXZB7aU3lo1aGdfnoqxYebD8@MPbTv//9oAx0FQx0FIzBpoqNgDGYYgEWMwSKmyNxYLmMA "05AB1E – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 82 bytes ``` f n|let(d:t)#c=1-sum[1|elem d c]+minimum[t#take n e|e<-scanr(:)(d:c)c];_#_=0=(#[]) ``` [Try it online!](https://tio.run/##NctBCsMgFEXRrTxwojSBmNBJWlciEsT8UIlKiXbm3q0UOrscuC@bTwqhtQOpBip8X4tgTskxf6KWlQJF7HDmFn3ysVthxZ6EBKr0HLOz6eKr6J8Tzjw2tqlJcaaNaNH6BIX35VMBP7BA3wdMA@SA@RfLv7vP/fgC "Haskell – Try It Online") ## Explanation Works by brute force: all cache strategies are tried and the best result is returned. ``` f n Define a function f on argument n (cache size) and a list (implicit). |let(d:t)#c= Define binary helper function #. Arguments are list with head d (current data) and tail t (remaining data), and list c (cache). 1- It returns 1 minus sum[1| 1 if elem d c]+ d is in the cache, plus minimum[ minimum of t# recursive calls to # with list t take n e| and cache being the first n values of e, where e<- e is drawn from scanr(:) c] the prefixes of c (d:c) with d and c tacked to the end. ;_#_=0 If the first list is empty, return 0. =(#[]) f then calls # with the list argument and empty cache. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 146 bytes ``` ->\a,\b {$_=set();$!=0;for b.kv ->\i,\v {$_{v}&&next;++$!;v∈b[i^..*]||next;$_∖=.keys.max({(grep $_,:k,b[i^..*])[0]//Inf})if $_>=a;$_∪=v};$!} ``` [Try it online!](https://tio.run/##TY1BDoIwEEX3nmJMGgJaK4K4sKl7zwBIIGkNQZQAaSTInhN4CI/lRbDWENlMZt5/M1Pw8rIb8sYQbFgdghgHCbQoYhWvTYuiObOpuJWQkEyCylMcyG/eys4wrvxe0@USzal8933ipydCFuHjoTmK3v2TkYw3Fcnju9ma55IXgCK8z/DoWr4drtfHq@isVKjswGK9@GKyU8@7gc6quAFhuhh8D4ONYYPB0Y079oo7oTWaCvhTbfOrf8GdCqpux1O2Jq4m3nRUu8MH "Perl 6 – Try It Online") ]
[Question] [ [Stack Cats](https://github.com/m-ender/stackcats) is a reversible, stack-based language. Its reversible nature makes for somewhat weird loops. This challenge is about the conditional loop `(...)`. When these loops are nested in certain ways, it's possible to transform the code to reduce the nesting depth. Here are the rules (where `A` and `B` stand for an arbitrary snippets): 1. When one loop starts with another loop, we can extract the inner loop to the front: `((A)B)` becomes `(A)(B)`. 2. When one loop ends with another loop, we can extract the inner loop to the end: `(B(A))` becomes `(B)(A)`. 3. Empty loops, `()`, can be removed from the program entirely. As a corollary (in conjunction with the other rules), `((A))` is equivalent to `(A)`. The only nested loops that will remain are of the form `(A(B)C)`, where `A`, `B` and `C` are non-empty. ## The Challenge You're given a valid Stack Cats program and your task is to reduce the nesting level of loops as much as possible, leaving no empty loops, using the above transformations. A valid Stack Cats program... * ... consists only of the characters `()/\<>[]{}!"*+-:=ITX^_|`. * ... has mirror symmetry (e.g. `\(]{}!{}[)/` is a valid program, but `/|/` isn't). * ... has correctly matched and nested `()` and `{}` (`[]`, `<>` and `\/` don't necessarily need to be matched as usual, although they'll appear in pairs due to the mirror symmetry requirement). You can take either a string or a list of characters as input, but output needs to be presented in the same format. You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. Note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases Test cases are two lines each (input and output), separated by empty lines. Note that one output is empty. You also need to support the empty input (which should result in empty output). ``` (((=+|+=))) (=+|+=) ({(=+|+=)}) ({(=+|+=)}) ((\)/)I(\(/)) (\)(/)I(\)(/) (()()(())()()) ((<|>((X((T)))[_]))\^/(([_](((T))X))<|>)) (<|>)(X)(T)([_])(\^/)([_])(T)(X)(<|>) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~113~~ ~~107~~ ~~67~~ 66 bytes ``` +`\(\)|(\()?(\(((\()|(?<-4>\))|[^()])*(?(4)@)\))(?(1)|(\))) $5$2$1 ``` [Try it online!](https://tio.run/##VY29DsIwDIT3PEeHOyoUFZWtP6zsHSI1LTAwsDAgNsKzh3PUBUWyv9yd7df9/Xjecq6vEZEJERxVYJAwdvt2iGSaV3DhDiNanihF1FicpKuO1aFqctZUX6e6N20j5/DZ8Ms/djpBz7MOectHovysmUk90KpcE7o0AAGYtH6@LGRcPSBC0QKphG2yhkCJ5hLKbTQV3fwf "Retina 0.8.2 – Try It Online") Includes ~~3~~ 4 byte saving thanks to @MartinEnder. Explanation: ``` +` ``` Repeatedly apply the substitution until there are no matches. ``` \(\)| ``` Match an empty loop (in which case nothing is captured so the substitution simply deletes it) or: ``` (\()? ``` Optionally match a `(`. This is captured in group 1 if it matched, but not if it didn't. ``` (\( ``` Capture the main body of the match in group 2 and match a `(`. ``` ( (\() | (<-4>\)) | [^()] )* ``` Repeatedly match either a `(`, capturing it in group 4, or a `)`, removing a capture from group 4 (failing if there isn't one), or something else. ``` (?(4)@) ``` Ensure that there are no spare captures left in group 4. ``` \)) ``` End capture group 2 with another `)`. ``` (?(1)|(\))) ``` If capture group 1 was empty, then capture a `)` in capture group 5. (So exactly one of those two groups will have a capture). ``` $5$2$1 ``` Move the bracket captured in either group 1 or group 5 to the other side of group 2. This has the effect of moving the inner loop to the front or the end of the outer loop depending on which side it matched. [Answer] # [Stax](https://github.com/tomtheisen/stax) v1.0.3+, ~~76~~ ~~65~~ ~~64~~ ~~62~~ 58 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` îÜ•$o,Γ{í]Üf╒9♦╛üΣóç*\$ñ₧└ΦJ♠¥c╥jóu≥3E.╘ⁿ◄◘W₧<¶┼7úê╟┴zç↨aG ``` 70 bytes when unpacked, ``` {{.((:/Yc{Z{40=+_41=-c^Ci~^Fdy,,\32&jEa:{a:{a4l$c}Md}X!:Rx!:Rc.()z:rgp ``` [Run and debug online!](https://staxlang.xyz/#c=%C3%AE%C3%9C%E2%80%A2%24o%2C%CE%93%7B%C3%AD%5D%C3%9Cf%E2%95%929%E2%99%A6%E2%95%9B%C3%BC%CE%A3%C3%B3%C3%A7*%5C%24%C3%B1%E2%82%A7%E2%94%94%CE%A6J%E2%99%A0%C2%A5c%E2%95%A5j%C3%B3u%E2%89%A53E.%E2%95%98%E2%81%BF%E2%97%84%E2%97%98W%E2%82%A7%3C%C2%B6%E2%94%BC7%C3%BA%C3%AA%E2%95%9F%E2%94%B4z%C3%A7%E2%86%A8aG&i=%28%28%28%3D%2B%7C%2B%3D%29%29%29%0A%28%7B%28%3D%2B%7C%2B%3D%29%7D%29%0A%28%28%5C%29%2F%29I%28%5C%28%2F%29%29%0A%28%28%29%28%29%28%28%29%29%28%29%28%29%29%0A%28%28%3C%7C%3E%28%28X%28%28T%29%29%29%5B_%5D%29%29%5C%5E%2F%28%28%5B_%5D%28%28%28T%29%29X%29%29%3C%7C%3E%29%29&a=1&m=2) ## Explanation `{.((:/Yc{Z{40=+_41=-c^Ci~^Fdy,,\32&jEa:{a:{a4l$c}Md` is a block that separates `A((B)C)D` into four parts and convert it to `A(B)(C)D`. `X!:Rx!:R` executes the block on the input string (step 1), then **reflects** the string (string reflection in Stax refers to reversing the string plus replacing (translating) `(<[{/` with (to) `\}]>)` ) and execute the block on the string obtained, and then reflect it back (step 2). Step 2 is essentially converting `(A(B))` to `(A)(B)`. `c.()z:r` remove all empty loops (step 3). `gp` is a generator that finds the fix point of an iteration. In this case the string is iterated with the 3-step process until it no longer changes. Implicit output. [Answer] # [Python 3](https://docs.python.org/3/), 226 223 212 206 bytes Okay, here is an attempt to solve this in a language that doesn't support recursive regex. ``` lambda s:g(g(s,*'()'),*')(').replace('()','') def g(s,t,u): m,*a={},;i=v=0 for c in s: i+=1;a+=[i]*(c==t) if c==u:*a,x=a;m[x]=i;v=m.get(x+1) if v:return g(s[:x]+s[x+1:v]+t+s[v:],t,u) return s[::-1] ``` [Try it online!](https://tio.run/##TVHLboMwELz7K3xjF2jSqDfT7b33HCKBW7kUUksBInAQVZJvp2tipZEle3ZmbO/j@Ot@uvZlrqmYD6b5@jZyUHvYw5DGEWCEfCBEuOqr48GUFXgyjSIU31Utvc2lJ1RCNmls6HxNM0sjPQtZd70spW35OSGlTWiTmYRyq2MoiRx6spYMTyo26UQma/JJk81Galb7ysGUbIJpVH3lTn3rv8vVpJMhZ1GNOnEMR6WXHIQMLvaop42efYKuGhzYtPMZHnvbOqjBIj4Gkkh2KERphmqQJHPBNQJQckkIkYsVUQi4GcKL5xBfb@JDGAxQ4BrfoYB1uF8gLIQ/7ibkBej3m@suvF7eAHYAW/4@/9SIxccagBEs3A6RHeFlj2CHzHsDAlsD2i6813lYWgg/EO6EH8lSqvpvzvwH "Python 3 – Try It Online") **Edits:** * Refactored `[::-1]` to save 6 bytes, thanks to Mr.Xcoder. The `g` function is the basic building block, which finds an occurrence of `((A)B)`, changes it to `(A)(B)`, then applies itself to the result until no more transformation is possible. The main steps are: * Apply `g` to the input normally. * Apply `g` to the input flipped. This run finds the occurrence of `))A(B(` in the reversed input, which effectively handles `(A(B))`. * Remove any occurrence of `()`. The problem is, `g` has so bad control structure that trying to one-line it made it bloat badly, so I don't think major improvement is possible based on this solution. ]
[Question] [ ## Summary The goal of this challenge is to create an undone image-version of a [15-puzzle](https://en.wikipedia.org/wiki/15_puzzle) / [sliding puzzle](https://en.wikipedia.org/wiki/Sliding_puzzle) also called [taquin](http://www.wordreference.com/fren/taquin) in french. ## Details: Given an input composed of: * an image, * an integer `n`, * an other integer `r`, your program, or function, or anything else that fits, must output the same image (*i.e.* same size and format) as the input, but that underwent the following process: 1. divide the image into `n²` rectangles, 2. remove one of those rectangles, randomly, 3. move a random number of contiguous rectangles from the *line/column* affected by point (2.) so the hole created is filled and another one is generated in this line/column. This number can be `0` if the blank is in a corner or an edge. Repeat (3.) `r` times. **Clarifications:** * If you moved rectangles from the line in step (3.), you must move rectangles from the column the in the next repetition, * if you moved rectangles left-to-right in a line-step, they must be moved right-to-left in the next line-step, same for top-to-bottom and bottom-to-top concerning columns, * you may assume that `n` will be chosen so it divides the lengths of the sides of the picture. **A last point:** An animated `.gif` showing the whole process are very welcomed. I propose to use the following picture (which is `1024x768`), with `n=16` and `r=100` as a model, you can use **any other picture** (as long as it's relevant and complies with SE's rules, of course). Note that [standards loopholes policies](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter submission wins ! [![Dogs, cats and ducks lovers should be satisfied !](https://i.stack.imgur.com/ek8ZQ.jpg)](https://i.stack.imgur.com/ek8ZQ.jpg) Since an example was requested, here is one, made "by hand", with `n=4` and `r=1` **Steps 1 and 2** [![enter image description here](https://i.stack.imgur.com/clE0R.jpg)](https://i.stack.imgur.com/clE0R.jpg) **Step 3** : line-wise, 2 rectangles to the left [![enter image description here](https://i.stack.imgur.com/iG7kw.jpg)](https://i.stack.imgur.com/iG7kw.jpg) [Answer] # Mathematica, 246 bytes ``` ImageAssemble@(n=Nest)[k=RandomInteger;q=Reverse;({t,r}=1~k~2;q[o=n[q/@#&,#,r]&@*(n[#&,#,t]&)])[o@#/.{a___,b:_~RepeatedNull~k[Position[o@#,i][[1,2]]-1],i,c___}:>{a,i,b,c}]&,MapAt[(i=#~ImageAdd~1)&,#~ImagePartition~Scaled[1/#2],{1,#2}~k~2],#3]& ``` Anonymous function. Contains U+F3C7, corresponding to Mathematica's `Transpose` operator. This function takes an `Image` object and returns an `Image` object. [Sample Animation, with `n=16` and `r=100`](https://gfycat.com/FavorableSoreAplomadofalcon) After 5000 iterations: [![enter image description here](https://i.stack.imgur.com/85mOjs.jpg)](https://i.stack.imgur.com/85mOj.jpg)*(click image for larger version)* ## Explanation ### Initialization ``` n=Nest ``` Store the `Nest` function (repeating operation) in `n`. ``` k=RandomInteger;q=Reverse; ``` Store the `RandomInteger` function in `k`, and `Reverse` function in `q`. ### Splitting the image ``` #~ImagePartition~Scaled[1/#2] ``` Partition the input image into (second input)^2 tiles. ``` {1,#2}~k~2 ``` Generate two `RandomInteger`s between 1 and the second input. This selects a random tile. ``` MapAt[(i=#~ImageAdd~1)&, ..., {1,#2}~k~2] ``` Make that tile white. Store it in `i`. ### Moving Tiles ``` {t,r}=1~k~2 ``` Generate two random integers from 0 to 1, and store them in `t` and `r`, respectively. This randomly selects direction. ``` o=n[q/@#&,#,r]&@*(n[#&,#,t]&) ``` Define function `o`: the composition of 1. a function transposing the input `t` times. 2. a function reversing each row `r` times. ``` o@# ``` Apply `o` to the input. ``` Position[o@#,i][[1,2]] ``` Find the column of `i` (white image). ``` k[ ... -1] ``` Subtract one and find a random integer between 0 and that number. This randomly chooses how many tiles to move. ``` o@#/.{a___,b:_~RepeatedNull~ ... ,i,c___}:>{a,i,b,c} ``` When the said number of tiles occur before an `i` (white image), switch their places. ``` (... q[o= ... ])[ ... ] ``` Reverse the `o` function and apply that to the result of above operation. This un-reverses and un-transposes the image. ### Looping and Image Assembly ``` (n=Nest)[ ... ,#3] ``` Repeat the above process (third input) times. ``` ImageAssemble@ ``` Put the images together. ]
[Question] [ Here are all the 2x2 binary matrices ``` #0 #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 00 00 00 00 01 01 01 01 10 10 10 10 11 11 11 11 00 01 10 11 00 01 10 11 00 01 10 11 00 01 10 11 ``` Two binary square matrices are equivalent under the relation `~` if one can be mapped onto the other by **any number of reflections in the horizontal or vertical axes**. `#1 ~ #2` under reflection in the vertical axis so we only need to keep one of these (it doesn't matter which). Likewise `#3 ~ #12`, `#6 ~ #9` and so on. **THE GOAL** is to produce a program which takes a single input `N` and prints as many `N x N` binary matrices as exist such that all matrices in the output are distinct under the above relation. In hand-wavey pseudocode, an admissible solution would be ``` define M[i] = N by N matrix with bit pattern equal to i for i = 0 to (2^(N^2)) - 1 valid = true for j = i+1 to (2^(N^2)) - 1 if (equivalent(M[i], M[j])) valid = false break if (valid) print (M[i]) ``` For the input `N=2` one valid output would be ``` 00 00 00 01 10 01 11 00 01 11 01 01 11 11 ``` But by selecting different matrices from the same equivalence class another valid output would be ``` 00 10 11 11 11 10 01 00 00 00 10 11 10 10 ``` The order of matrices doesn't matter, the particular choice from equivalent matrices doesn't matter, and whitespace doesn't matter, output the matrices however you like as long as it's human-readable. **The output must be exhaustive.** ~~Shortest code wins.~~ EDIT: this is my first golf post and I've changed my mind on the winning criteria. Shortest code in a language *not specifically designed for conciseness/golfing* wins. I hope it's not bad etiquette to change this criterion post-hoc, but I think doing it in a "normal" language is a much more *interesting* proposition. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṛ€;U; 2ḶṗṗµWdz¡Ṃµ€Q ``` [Try it online!](http://jelly.tryitonline.net/#code=4bma4oKsO1U7CjLhuLbhuZfhuZfCtVfDh8KzwqHhuYLCteKCrFE&input=&args=Mg) ### How it works ``` 2ḶṗṗµWdz¡Ṃµ€Q Main link. Argument: n (integer) 2Ḷ Unlength 2; yield [0, 1]. ṗ Cartesian product; construct all vectors of {0, 1}^n. ṗ Cartesian product; construct all vectors of ({0, 1}^n)^n. This yields A, the array of all binary n×n matrices. µ µ€ Begin a new, monadic chain and apply it to all matrices M in A. W Wrap; yield [M]. dz¡ Call the helper link n times, initially with argument [M], then on the previous return value. Ṃ Take the minimum of the results. This replaces all matrices with the lexicographical minimum of their equivalence classes, mapping equivalent matrices to the same matrix. Q Unique; deduplicate the resulting array of matrices. Ṛ€;U; Helper link. Argument: L (array of matrices) Ṛ€ Reverse the order of the rows of each M in L. U Reverse the order of the columns of each M in L. ; Concatenate the resulting matrix arrays. ; Concatenate the result with L. ``` [Answer] # Pyth - ~~24~~ ~~23~~ 21 bytes ~~Wanna look for better way of getting all the reflections.~~ *Thanks to @Pietu1998 for golfing me 2 bytes!* ``` hM.gS+K_Bk_MMKcRQ^`T* ``` [Try it online here](http://pyth.herokuapp.com/?code=hM.gS%2BK_Bk_MMKcRQ%5E%60T%2a&test_suite=1&test_suite_input=2%0A3&debug=0). Going to wait for golfing before doing a full explanation, but it essentially makes all possible binary matrices, then `.g`roups them by the sorted list of all the possible reflections, then only takes one from each group. [Answer] # J, ~~66~~ ~~56~~ 53 bytes ``` [:~.,~{.@/:~@(2:_&(][:,(;|.;|."1)&>)<)@$"#.2#:@i.@^*: ``` Brute-force search. ## Usage ``` f =: [:~.,~{.@/:~@(2:_&(][:,(;|.;|."1)&>)<)@$"#.2#:@i.@^*: f 2 ┌───┬───┬───┬───┬───┬───┬───┐ │0 0│0 0│0 0│0 1│0 1│0 1│1 1│ │0 0│0 1│1 1│0 1│1 0│1 1│1 1│ └───┴───┴───┴───┴───┴───┴───┘ # f 3 168 # f 4 16576 ``` ## Explanation ``` [:~.,~{.@/:~@(2:_&(][:,(;|.;|."1)&>)<)@$"#.2#:@i.@^*: Input: integer n *: Square n 2 ^ Compute m = 2 ^ (n ^ 2) i.@ Make a range [0, m) #:@ Convert each to binary digits ,~ Pair, make [n, n] $"#. Reshape each binary list to a matrix with size [n, n] ( )@ Operate on each < Box it, call x 2: The constant 2 _&( ) Repeat that many times on x ( )&> For each box |."1 Reverse by column |. Reverse by row ; Join them ; Join with initial [:, Flatten ] Return that as the new x /:~@ Sort each {.@ Take the head of each [:~. Unique and return ``` [Answer] ## Haskell, 100 bytes ``` import Data.List r=reverse e#n=mapM id$e<$[1..n] f n=nubBy(\a b->elem a[r b,r<$>b,r$r<$>b])$"01"#n#n ``` Usage example: `f 2` -> `[["00","00"],["00","01"],["00","11"],["01","01"],["01","10"],["01","11"],["11","11"]]`. How it works: ``` e#n=mapM id$e<$[1..n] -- helper function: creates a list of all combinations -- of the elements of e of length n -- "01" # 2 -> ["00","01","10","11"] "01"#n#n -- creates all binary n x n matrices nubBy -- remove duplicates according to the equivalence -- relation \a b -> -- a equals b if a elem -- a is an element of [r b,r<$>b,r$r<$>b] -- the list of reflections of b ``` [Answer] ## JavaScript (ES6), 195 bytes ``` n=>[...Array(p=1<<n*n)].map(_=>(p++).toString(2).slice(1)).filter((s,i,a)=>![1,0,1].some(c=>a.indexOf((c?b.reverse():b=b.map(s=>[...s].reverse().join``)).join``)<i,b=s.match(eval(`/.{${n}}/g`)))) ``` Returns strings representing all matrix entries concatenated e.g. `111101111` represents a 3×3 matrix of `1`s with a `0` in the middle. Explanation: ``` n=>[...Array(p=1<<n*n)].map( Enumerate all binary matrices _=>(p++).toString(2).slice(1) Convert to padded binary ).filter((s,i,a)=>![1,0,1].some( Check reflections of each matrix c=>a.indexOf((c?b.reverse(): Reverse the order of lines b=b.map(s=>[...s].reverse().join`` Or reverse each line )).join``)<i, Has this been seen before? b=s.match(eval(`/.{${n}}/g`)))) Reshape string into a square ``` [Answer] # Mathematica, 94 bytes ``` DeleteDuplicatesBy[{0,1}~Tuples~{#,#},Sort@Join[Join@@Outer[Reverse,{#},{1,2,{1,2}},1],{#}]&]& ``` [Answer] # JavaScript (ES6), 184 This turned out to be quite similar to Neil's, but all in all the bag of tricks in javascript is not so diverse. ``` n=>eval("r=x=>[...x].reverse();for(l='',i=m=1<<n*n;i<m+m;i++)a=i.toString(2).slice(1).match(eval(`/.{${n}}/g`)),[b=a.map(x=>r(x).join``),r(a),r(b)].some(x=>~l.search(x))?0:l+=a+`\n`") ``` *Less golfed* ``` n=>{ r = x =>[...x].reverse(); for(l = '', i = m = 1<<n*n; i < m+m; i++) a = i.toString(2).slice(1).match(eval(`/.{${n}}/g`)), // base matrix as an array of strings b = a.map(x => r(x).join``), // horizontal reflection c = r(a), // vertical reflection d = r(b), // both reflections // check if already found [b, c, d].some(x => ~l.search(x)) // using search, arrays are converted to comma separated strings ? 0 : l += a+`\n` // add new found to list (again as a comma separated string) return l } ``` *Test* Beware, even for input 4 the running time is overly long ``` f=n=>eval("r=x=>[...x].reverse();for(l='',i=m=1<<n*n;i<m+m;i++)a=i.toString(2).slice(1).match(eval(`/.{${n}}/g`)),[b=a.map(x=>r(x).join``),r(a),r(b)].some(x=>~l.search(x))?0:l+=a+`\n`") function update() { var i=+I.value; result = f(i) count = result.split('\n').length O.textContent = count+'\n'+result } update() ``` ``` Input <select id=I onchange="update()"><option>2<option>3<option>4<option>5</select> <pre id=O></pre> ``` ]
[Question] [ ## Explanation [Befunge](https://esolangs.org/wiki/Befunge) is a two-dimensional program that uses [stacks](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29). That means, to do 5 + 6, you write `56+`, meaning: ``` 56+ 5 push 5 into stack 6 push 6 into stack + pop the first two items in the stack and add them up, and push the result into stack (to those of you who do not know stacks, "push" just means add and "pop" just means take off) ``` However, we cannot push the number `56` directly into the stack. To do so, we must write `78*` instead, which multiplies `7` and `8` and pushes the product into the stack. ## Details **For each number from `1` to `n`**, find a string consisting of only these characters: `0123456789+-*/:` (I would **not** use `%` modulo.) The goal is to find the **shortest** string that can represent the number, using the format described above. For example, if the input is `123`, then the output would be `67*9:*+`. The output should be evaluated from left to right. If there are more than one acceptable outputs (e.g. `99*67*+` is also acceptable), any one can be printed (no bonus for printing all of them). ## Further Explanation If you still do not understand how `67*9:*+` evaluates to `123`, here is a detailed explanation. ``` stack |operation|explanation 67*9:*+ [6] 6 push 6 to stack [6,7] 7 push 7 to stack [42] * pop two from stack and multiply, then put result to stack [42,9] 9 push 9 to stack [42,9,9] : duplicate the top of stack [42,81] * pop two from stack and multiply, then put result to stack [123] + pop two from stack and add, then put result to stack ``` ## TL;DR The program needs to find the **shortest** string that can represent the input (number), using the format specified above. ## SCORING * We have already done it in the [shortest amount of code](https://codegolf.stackexchange.com/questions/76591/express-a-number-with-only-0-9-and-the-four-operations). This time, size does not matter. * Your language of choice has to have a free compiler/interpreter for my operating system (Windows 7 Enterprise). * Bonus if you include the link to the compiler/interpreter (I am too lazy). * If possible, please include a timer for my convenience. The output from the timer is valid. * The score will be the largest `n` in 1 minute. * That means, the program needs to print the required representation from `1` onward. * No hard-coding, except `0` to `9`. ## (more) SPECIFICS * **The program is invalid if it outputs a string longer than needed for any number.** * `1/0=ERROR` * `5/2=2`, `(-5)/2=-2`, `(-5)/(-2)=2`, `5/(-2)=-2` ## Disambiguation The `-` is `second-top minus top`, meaning that `92-` returns `7`. Likewise, the `/` is `second-top divide top`, meaning that `92/` returns `4`. ## Sample program # Lua Uses depth-first search. ``` local function div(a,b) if b == 0 then return "error" end local result = a/b if result > 0 then return math.floor(result) else return math.ceil(result) end end local function eval(expr) local stack = {} for i=1,#expr do local c = expr:sub(i,i) if c:match('[0-9]') then table.insert(stack, tonumber(c)) elseif c == ':' then local a = table.remove(stack) if a then table.insert(stack,a) table.insert(stack,a) else return -1 end else local a = table.remove(stack) local b = table.remove(stack) if a and b then if c == '+' then table.insert(stack, a+b) elseif c == '-' then table.insert(stack, b-a) elseif c == '*' then table.insert(stack, a*b) elseif c == '/' then local test = div(b,a) if test == "error" then return -1 else table.insert(stack, test) end end else return -1 end end end return table.remove(stack) or -1 end local samples, temp = {""}, {} while true do temp = {} for i=1,#samples do local s = samples[i] if eval(s) ~= -1 or s == "" then for n in ("9876543210+-*/:"):gmatch(".") do table.insert(temp, s..n) end end end for i=1,#temp do local test = eval(temp[i]) if input == test then print(temp[i]) return end end samples = temp end ``` [Answer] # C++, exploding all memory on a computer near you Generates the shortest string where the calculation nowhere causes an overflow of a signed 32-bit integer (so all intermediate results are in the range `[-2147483648, 2147483647]` On my system this generates a solution for all numbers up to and including `483432` in 30 seconds while using 1.8G memory. Even higher numbers will quickly explode the memory usage. The highest number I can handle on my system is `5113906`. The calculation takes almost 9 minutes and 24GB. When it finishes it internally has a solution for `398499338` values, about 9% of all 32 bit integers (positive and negative) Needs a C++11 compiler. On linux compile with: ``` g++ -Wall -O3 -march=native -std=gnu++11 -s befour.cpp -o befour ``` Add `-DINT64` as an option to use a 64-bit integer range instead of 32-bit for intermediate results (this will use about 50% more time and memory). This needs a builtin 128 bit type. You may need to change the gcc type `__int128`. No result in at least the range `[1..483432]` changes by allowing larger intermediate results. Add `-DOVERFLOW` as an option to not use a bigger integer type to check for overflow. This has the effect of allowing overflow and value wrapping. If your system has tcmalloc (<https://github.com/gperftools/gperftools>) you can link with that resulting in a program that is generally a little faster and uses slightly less memory. On some UNIX systems you can use a preload, e.g. ``` LD_PRELOAD=/usr/lib/libtcmalloc_minimal.so.4 befour 5 ``` Basic usage: generate and print all numbers up to target: ``` befour target ``` Options: * `-a` Also print all numbers that were generated while working out target * `-c` Also print all numbers that were generated starting with a "carry" (dup) * `-f` Find and print the first number beyond target that was not generated * `-s` Stop if target is generated even if not all numbers before were generated * `-S` Like `-s` and `-f` in an automatic loop. As soon as target is generated find the first number not yet generated and make that the new target * `-E` Don't immediately exit when the goal is reached. First finish all strings of the current length * `-O` Don't output the strings for all numbers up to target. just the string for target * `-o` Allowed instructions (defaults to `+-*/:` * `-b num` Lowest literal that can be pushed (defaults to `0`) * `-B num` Highest literal that can be pushed (defaults to `9`) * `-r num` The lowest allowed intermediate result. Used to avoid underflow. (defaults to `INT32_MIN`, `-2147483648` * `-R num` The highest allowed intermediate result. Used to avoid overflow. (defaults to `INT32_MAX`, `2147483647` * `-m memory` (linux only) exit when approximately this much extra memory has been allocated Some interesting option combinations: Generate all numbers up to target and calculate the smallest number that needs a longer generator than all these numbers: ``` befour -fE target ``` Generate only target (-s), print only target (-O) ``` befour -sO target ``` Find the highest number that can be generated on your system given time and/or memory constraints (This will run your system out of memory if you leave it running. Subtract 1 from the last "looking for" output you see as the last safe value): ``` befour -S 1 ``` Generate solutions without ever using negative intermediate results (`30932` is the first value that needs negative intermediate results for the shortest string): ``` befour -r0 target ``` Generate solutions without ever pushing `0` (this doesn't seem to lead to any suboptimal solutions): ``` befour -b1 target ``` Generate solutions including `a..f (10..15)`: ``` befour -B15 target ``` Generate solutions without using dup `:` (add `-r0` since negative intermediate values are never interesting for this case) ``` befour -r0 -o "+-*/" target ``` Find the first value that can not be generated for a given string length using just `+`, `-`, `*` and `/`: ``` befour -ES -r0 -o "+-*/" 1 ``` This will in fact generate the first few terms of <https://oeis.org/A181898>, but will start to diverge at `14771` because we use truncating division so that number can be done with a length 13 string instead of length 15 as the OEIS series expects: ``` 14771: 13: 99*9*9*4+9*4/ ``` instead of ``` 14771: 15: 19+5*6*7*9+7*8+ ``` Since without truncation division seems pointless the OEIS series can be better generated by using ``` befour -ES -r0 -o"+-*" 1 ``` Assuming division remains useless this gave me 3 extra terms before I went out of memory: ``` 10, 19, 92, 417, 851, 4237, 14771, 73237, 298609, 1346341, 6176426, 25622578 ``` Another version of this program storing part of the data in external files adds 135153107 and 675854293 after which all 32-bit integers have been generated. ## `befour.cpp` ``` /* Compile using something like: g++ -Wall -O3 -march=native -std=gnu++11 -s befour.cpp -o befour */ #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <limits> #include <climits> #include <cstdint> #include <cstdlib> #include <chrono> #include <unordered_map> using namespace std; #ifdef __GNUC__ # define HOT __attribute__((__hot__)) # define COLD __attribute__((__cold__)) # define NOINLINE __attribute__((__noinline__)) # define LIKELY(x) __builtin_expect(!!(x),1) # define UNLIKELY(x) __builtin_expect(!!(x),0) #else // __GNUC__ # define HOT # define COLD # define NOINLINE # define LIKELY(x) (x) # define UNLIKELY(x) (x) #endif // __GNUC__ #ifdef INT64 using Int = int64_t; // Supported value type # ifndef OVERFLOW using Int2 = __int128; // Do calculations in this type. Check overflow # endif // OVERFLOW #else // INT64 using Int = int32_t; // Supported value type # ifndef OVERFLOW using Int2 = int64_t; // Do calculations in this type. Check overflow # endif // OVERFLOW #endif // INT64 #ifdef OVERFLOW using Int2 = Int; #endif // OVERFLOW // Supported value range Int2 MIN = numeric_limits<Int>::lowest(); Int2 MAX = numeric_limits<Int>::max(); Int HALF_MIN, HALF_MAX; // The initial values we can push Int ATOM_MIN = 0; Int ATOM_MAX = 9; bool all = false; // Output all reached values bool all_carry = false; // Output all values reachable using carry bool early_exit = true; // Exit before finishing level if goal reached bool find_hole = false; // Look for first unconstructed > target bool output = true; // Output [1..target] instead of just target bool single = false; // Only go for target instead of [1..target] bool explore = false; // Don't stop, increase N until out of memory bool do_dup = false; // Use operator : bool do_multiply= false; // Use operator * bool do_add = false; // Use operator + bool do_subtract= false; // Use operator - bool do_divide = false; // Use operator / char const* operators = "+-*/:"; // Use these operators size_t max_mem = SIZE_MAX; // Stop if target memory reached size_t const MEM_CHECK = 1000000; chrono::steady_clock::time_point start; NOINLINE size_t get_memory(bool set_base_mem = false) { static size_t base_mem = 0; size_t const PAGE_SIZE = 4096; // Linux specific. Won't hurt on other systems, just gets no result size_t mem = 0; std::ifstream statm; statm.open("/proc/self/statm"); statm >> mem; mem *= PAGE_SIZE; if (set_base_mem) base_mem = mem; else mem -= base_mem; return mem; } // Handle commandline options. // Simplified getopt for systems that don't have it in their library (Windows..) class GetOpt { private: string const options; char const* const* argv; int nextchar = 0; int optind = 1; char ch = '?'; char const* optarg = nullptr; public: int ind() const { return optind; } char const* arg() const { return optarg; } char option() const { return ch; } GetOpt(string const options_, char const* const* argv_) : options(options_), argv(argv_) {} char next() { while (1) { if (nextchar == 0) { if (!argv[optind] || argv[optind][0] != '-' || argv[optind][1] == 0) return ch = 0; if (argv[optind][1] == '-' && argv[optind][2] == 0) { ++optind; return ch = 0; } nextchar = 1; } ch = argv[optind][nextchar++]; if (ch == 0) { ++optind; nextchar = 0; continue; } auto pos = options.find(ch); if (pos == string::npos) ch = '?'; else if (options[pos+1] == ':') { if (argv[optind][nextchar]) { optarg = &argv[optind][nextchar]; } else { optarg = argv[++optind]; if (!optarg) return ch = options[0] == ':' ? ':' : '?'; } ++optind; nextchar = 0; } return ch; } } }; using ms = chrono::milliseconds; Int missing, N; size_t cached, cached_next; uint8_t const CARRY_MASK = '\x80'; uint8_t const LITERAL = 0; struct How { // Describes how to construct a number Int left; Int right; uint8_t ops, op; How(uint8_t ops_, uint8_t op_, Int carry_=0, Int left_=0, Int right_=0) : left(left_), right(right_), ops(ops_), op(carry_ ? CARRY_MASK | op_ : op_) {} How() = default; How(How&&) = default; How& operator=(How&&) = default; static How const* predict(Int carry, Int value, int& ops); static void print_predicted(ostream& out, Int carry, Int value, How const* Value = nullptr); void print(ostream& out, Int carry = 0, bool length = false) const; }; ostream& operator<<(ostream& out, How const& how) { how.print(out, 0, true); return out; } using NumSet = vector<Int>; using NumSets = vector<NumSet>; struct Known: public unordered_map<Int, How> { void store(NumSet& L, Int accu, uint8_t ops, uint8_t op, Int left=0, Int carry_right=0, Int right=0) { ++cached; emplace(accu, How(ops, op, carry_right, left, right)); // operator[](accu) = How(ops, op, carry_right, left, right); L.emplace_back(accu); } void maybe_store(Known const& known0, NumSet& L, Int accu, uint8_t ops, uint8_t op, Int carry_left, Int left, Int carry_right, Int right) { if (count(accu)) return; if (carry_left) { auto found = known0.find(accu); // If we can do as good or better without carry use that if (found != known0.end() && found->second.ops <= ops) return; } store(L, accu, ops, op, left, carry_right, right); if (carry_left) return; if (single) { if (UNLIKELY(accu == N)) known0.maybe_explore(); } else if (1 <= accu && accu <= N) --missing; } NOINLINE void maybe_explore() const COLD { --missing; if (explore && early_exit) do_explore(); } NOINLINE void do_explore() const COLD { auto i = N; while (i < MAX && count(++i)); auto end = chrono::steady_clock::now(); auto elapsed = chrono::duration_cast<ms>(end-start).count(); cerr << "Found " << N << " at " << elapsed / 1000. << " s"; auto mem = get_memory(); if (mem) cerr << " (" << mem / 1000 / 1000. << " MB)"; if (i < MAX || !count(i)) { cerr << ", now looking for " << i << endl; N = i; ++missing; } else cerr << ", every value has now been generated" << endl; } }; struct KnowHow { // Describes all numbers we know how to construct NumSets num_sets; Known known; KnowHow() = default; ~KnowHow() = default; KnowHow(KnowHow const&) = delete; KnowHow& operator=(KnowHow const&) = delete; }; // Describes all numbers we know how to construct for a given carry // Key 0 is special: the numbers we can construct without carry (the solutions) unordered_map<Int, KnowHow> known_how; // Try to predict if a subtree is a delayed How and avoid descending // into it (since it may not exist yet) How const* How::predict(Int carry, Int value, int& ops) { How* Value; if (carry) { if (value == carry) { Value = nullptr; ops = 0; } else { Value = &known_how.at(carry).known.at(value); ops = Value->ops; } } else { if (ATOM_MIN <= value && value <= ATOM_MAX) { Value = nullptr; ops = 0; } else { Value = &known_how.at(0).known.at(value); ops = Value->ops; } } return Value; } void How::print_predicted(ostream& out, Int carry, Int value, How const* Value) { if (Value) Value->print(out, carry); else if (carry) out << ":"; else if (value > 9) out << static_cast<char>(value-10+'a'); else out << value; } void How::print(ostream& out, Int carry_left, bool length) const { if (length) out << 2*ops+1 << ": "; Int carry_right = 0; auto op_ = op; switch(op_) { case LITERAL: How::print_predicted(out, 0, left); break; case '*' | CARRY_MASK: case '/' | CARRY_MASK: case '+' | CARRY_MASK: case '-' | CARRY_MASK: carry_right = left; op_ &= ~CARRY_MASK; // Intentional drop through case '*': case '/': case '+': case '-': { int left_ops, right_ops; auto Left = How::predict(carry_left, left, left_ops); // Int right = 0; auto Right = How::predict(carry_right, right, right_ops); // Sanity check: tree = left_tree + root + right_tree if (ops != left_ops + right_ops +1) { char buffer[80]; snprintf(buffer, sizeof(buffer), "Broken number %d %c %d, length %d != %d + %d + 1", static_cast<int>(left), op_, static_cast<int>(right), ops, left_ops, right_ops); throw(logic_error(buffer)); } How::print_predicted(out, carry_left, left, Left); How::print_predicted(out, carry_right, right, Right); } // Intentional drop through case ':': out << op_; break; default: throw(logic_error("Unknown op " + string{static_cast<char>(op_)})); break; } } // carryX indicates Xv was reached using carry. If not we also know [L, known] is known_how[0] // carryY indicates Y was reached using carry (carryY == Xv if so) void combine(NumSet& L, Known& known, Known const& known0, int ops, Int carryX, Int2 Xv, Int carryY, NumSet const&Y) HOT; void combine(NumSet& L, Known& known, Known const& known0, int ops, Int carryX, Int2 Xv, Int carryY, NumSet const&Y) { for (Int Yv: Y) { // Yv == 0 can never lead to an optimal calculation if (Yv == 0) continue; Int2 accu; if (do_multiply) { accu = Xv * Yv; if (accu <= MAX && accu >= MIN) known.maybe_store(known0, L, accu, ops, '*', carryX, Xv, carryY, Yv); } if (do_add) { accu = Xv + Yv; if (accu <= MAX && accu >= MIN) known.maybe_store(known0, L, accu, ops, '+', carryX, Xv, carryY, Yv); } if (do_subtract) { accu = Xv - Yv; if (accu <= MAX && accu >= MIN) known.maybe_store(known0, L, accu, ops, '-', carryX, Xv, carryY, Yv); } if (do_divide) { accu = Xv / Yv; if (accu <= MAX && accu >= MIN) known.maybe_store(known0, L, accu, ops, '/', carryX, Xv, carryY, Yv); } } } // value was constructed using a carry if and only if value != 0 NumSet const& level(KnowHow& known_how0, Int value, int ops) HOT; NumSet const& level(KnowHow& known_how0, Int value, int ops) { auto& from_value = known_how[value]; if (from_value.num_sets.size() <= static_cast<size_t>(ops)) { auto& known = from_value.known; if (from_value.num_sets.size() != static_cast<size_t>(ops)) { if (value == 0 || ops != 1) throw(logic_error("Unexpected level skip")); // This was because of delayed carry creation. // The delay is over. Create the base case from_value.num_sets.resize(ops+1); known.store(from_value.num_sets[0], value, 0, ':', value); } else from_value.num_sets.resize(ops+1); auto& L = from_value.num_sets[ops]; if (ops == 0) { if (value) { known.store(L, value, ops, ':', value); } else { for (auto i = ATOM_MIN; i <= ATOM_MAX; ++i) { if (single) { if (i == N) --missing; } else { if (0 < i && i <= N) --missing; } known.store(L, i, 0, LITERAL, i); } } } else { auto& known0 = known_how0.known; // for (auto k=ops-1; k>=0; --k) { for (auto k=0; k<ops; ++k) { auto const& X = from_value.num_sets[ops-1-k]; auto const& Y = known_how0.num_sets[k]; for (Int Xv: X) { // Plain combine must come before carry combine so a plain // solution will prune a same length carry solution combine(L, known, known0, ops, value, Xv, 0, Y); if (!missing && early_exit) goto DONE; if (do_dup && (Xv > ATOM_MAX || Xv < ATOM_MIN)) { // Dup Xv, construct something using k operators, combine if (k == 0 && Xv != 0) { // Delay creation of carry known_how[Xv] for 1 level // This is purely a memory and speed optimization // Subtraction gives 0 which is never optimal // Division gives 1 which is never optimal // Multiplication gives Xv ** 2 // Could be == Xv if Xv== 0 or Xv == 1, but will be // pruned by atom - atom or atom / atom Int2 accu = Xv; accu *= accu; if (accu <= MAX && accu >= MIN) { known.maybe_store(known0, L, accu, ops, '*', value, Xv, Xv, Xv); } // Addition gives Xv * 2 (!= Xv) if (HALF_MIN <= Xv && Xv <= HALF_MAX) known.maybe_store(known0, L, 2*Xv, ops, '+', value, Xv, Xv, Xv); } else { auto& Z = level(known_how0, Xv, k); combine(L, known, known0, ops, value, Xv, Xv, Z); } if (!missing && early_exit) goto DONE; } if (max_mem != SIZE_MAX && cached > cached_next) { cached_next = cached + MEM_CHECK; if (get_memory() >= max_mem) goto DONE; } } } } // L.shrink_to_fit(); } DONE: return from_value.num_sets[ops]; } void my_main(int argc, char const* const* argv) { GetOpt options("acfm:sSEOo:b:B:r:R:", argv); while (options.next()) switch (options.option()) { case 'a': all = true; break; case 'b': { auto tmp = atoll(options.arg()); ATOM_MIN = static_cast<Int>(tmp); if (static_cast<long long int>(ATOM_MIN) != tmp) throw(range_error("ATOM_MIN is out of range")); break; } case 'B': { auto tmp = atoll(options.arg()); ATOM_MAX = static_cast<Int>(tmp); if (static_cast<long long int>(ATOM_MAX) != tmp) throw(range_error("ATOM_MAX is out of range")); break; } case 'c': all_carry = true; break; case 'f': find_hole = true; break; case 'm': max_mem = atoll(options.arg()); break; case 'S': explore = true; // intended drop through to single case 's': single = true; break; case 'o': operators = options.arg(); break; case 'E': early_exit = false; break; case 'r': { auto tmp = atoll(options.arg()); MIN = static_cast<Int>(tmp); if (static_cast<long long int>(MIN) != tmp) throw(range_error("MIN is out of range")); break; } case 'R': { auto tmp = atoll(options.arg()); MAX = static_cast<Int>(tmp); if (static_cast<long long int>(MAX) != tmp) throw(range_error("MAX is out of range")); break; } case 'O': output = false; break; default: cerr << "usage: " << argv[0] << " [-a] [-c] [-f] [-D] [-E] [-O] [-s] [-b atom_min] [-B atom_max] [r range_min] [-R range_max] [-m max_mem] [max]" << endl; exit(EXIT_FAILURE); } // Avoid silly option combinations if (MIN > MAX) throw(logic_error("MIN above MAX")); if (ATOM_MIN > ATOM_MAX) throw(logic_error("ATOM_MIN above ATOM_MAX")); if (ATOM_MIN < 0) throw(range_error("Cannot represent negative atoms")); if (ATOM_MAX > 35) throw(range_error("Cannot represent atoms > 35")); if (ATOM_MIN < MIN) throw(range_error("ATOM_MIN is out of range")); if (ATOM_MAX > MAX) throw(range_error("ATOM_MAX is out of range")); HALF_MIN = MIN / 2; HALF_MAX = MAX / 2; for (auto ops=operators; *ops; ++ops) switch(*ops) { case '*': do_multiply = true; break; case '/': do_divide = true; break; case '+': do_add = true; break; case '-': do_subtract = true; break; case ':': do_dup = true; break; default: throw(logic_error("Unknown operator")); } long long int const NN = options.ind() < argc ? atoll(argv[options.ind()]) : 1; if (NN < MIN || NN > MAX) throw(range_error("Target number is out of range")); N = NN; if (N < 1) { single = true; output = false; } cerr << "N=" << N << ", using " << sizeof(Int) * CHAR_BIT << " bits without overflow" << endl; missing = single ? 1 : N; cached = cached_next = 0; auto& known_how0 = known_how[0]; auto& known = known_how0.known; auto mem = get_memory(true); if (!mem && max_mem != SIZE_MAX) throw(runtime_error("Cannot get memory usage on this system")); // Start calculation start = chrono::steady_clock::now(); // Fill in initial values [0..9] level(known_how0, 0, 0); // Grow number of allowed operations until all requested numbers are reached // for (auto ops=1; ops <=5; ++ops) { for (auto ops=1;;++ops) { if (missing == 0) { if (!explore) break; known_how0.known.do_explore(); if (missing == 0) break; } if (max_mem != SIZE_MAX && get_memory() >= max_mem) break; auto end = chrono::steady_clock::now(); auto elapsed = chrono::duration_cast<ms>(end-start).count(); cerr << "Reaching for " << 2*ops+1 << " instructions at " << elapsed/1000. << " s"; if (mem) cerr << " (" << get_memory() / 1000 / 1000. << " MB)"; cerr << endl; auto old_cached = cached; level(known_how0, 0, ops); if (cached == old_cached) { cerr << "Oops, all possible numbers have been generated and we still weren't finished" << endl; break; } } // We are done generating all numbers. auto end = chrono::steady_clock::now(); // Report the result // length = 2*ops + 1 Int limit = known_how0.num_sets.size()*2-1; cerr << "Some numbers needed " << limit << " instructions" << endl; auto elapsed = chrono::duration_cast<ms>(end-start).count(); start = end; stringstream out; out << "Calculation: " << elapsed/1000. << " s\n"; for (auto i = output ? 1 : N; i <= N; ++i) { if (single || missing) { auto got = known.find(i); if (got != known.end()) cout << i << ": " << got->second << "\n"; else cout << i << " not generated\n"; } else cout << i << ": " << known.at(i) << "\n"; } if (output) { end = chrono::steady_clock::now(); elapsed = chrono::duration_cast<ms>(end-start).count(); start = end; out << "Printing: " << elapsed/1000. << " s\n"; } if (find_hole) { Int hole; for (auto i = single ? 1 : N+1; 1; ++i) { if (!known_how0.known.count(i) || i == 0) { hole = i; break; } } out << "First missing value " << hole << "\n"; end = chrono::steady_clock::now(); elapsed = chrono::duration_cast<ms>(end-start).count(); start = end; out << "Missing: " << elapsed/1000. << " s\n"; } if (all) { for (auto const& entry: known_how0.known) { cout << entry.first << ": " << entry.second << "\n"; } end = chrono::steady_clock::now(); elapsed = chrono::duration_cast<ms>(end-start).count(); start = end; out << "All: " << elapsed/1000. << " s\n"; } if (all_carry) { for (auto const& carry: known_how) { auto carry_left = carry.first; if (carry_left == 0) continue; cout << "Carry " << carry_left << "\n"; for (auto const& how: carry.second.known) { cout << " " << how.first << ": "; how.second.print(cout, carry_left, true); cout << "\n"; } } end = chrono::steady_clock::now(); elapsed = chrono::duration_cast<ms>(end-start).count(); start = end; out << "All carry: " << elapsed/1000. << " s\n"; } mem = get_memory(); if (mem) cerr << "used about " << mem / 1000 / 1000. << " MB\n"; cerr << out.str(); cerr << "Cached " << cached << " results = " << known.size() << " plain + " << cached - known.size() << " carry" << endl; } int main(int argc, char const* const* argv) { try { my_main(argc, argv); } catch(exception& e) { cerr << "Error: " << e.what() << endl; quick_exit(EXIT_FAILURE); } // Cleaning up the datastructures can take ages quick_exit(EXIT_SUCCESS); } ``` Some test cases: * `1: 1: 1` * `11: 3: 29+` * `26: 5: 29*8+` * `27: 3: 39*` * `100: 5: 19+:*` * `2431: 9: 56*9*9*1+` * `3727: 9: 69*7+:*6+` * `86387: 11: 67*:*1-7*7*` * `265729: 11: 39*:*:*2/9+` * `265620: 13: 99*::*6/*7+3*` * `1921600: 9: 77*:*:*3/` * `21523360: 9: 99*:*:*2/` * `57168721: 11: 99*6+:*8-:*` * `30932: 11: 159*-:4*:*+` [Answer] # JavaScript Node Brute Force ### Program file bfCodes.js ``` function bfCodes( n) { var odo = [0], valid = true, valCount=1; const vDUP = 10, vADD = 11, vSUB = 12, vMUL=13, vDIV = 14, vMAX = vDIV; const vCHARS = "0123456789:+-*/"; function inc(sd) // increment significant digit, lsd = 0 { if(sd >= odo.length) { odo.push(0); console.log("length: " + (sd+1)); ++valCount; return;} var v = ++odo[sd]; // increment and read the base 15 odometer digit if( v == vDUP) if( valCount) {++valCount; return} else { odo[ sd] = vMAX; --valCount; valid = false; return;} if( v == vADD) { if( (--valCount) < 1) { valid = false; odo[ sd] = vMAX; return;}; } if( v > vMAX) { odo[sd] = 0; ++valCount; valid = true; inc(sd+1); return;} } function bfDecode( odo) { var a,b,stack = []; for(var i = odo.length; i--;) { var v = odo[ i]; if( v < 10) { stack.push( v); continue;}; switch(v) { case vDUP: stack.push( stack[stack.length-1]); continue; case vADD: b=stack.pop(); stack.push( stack.pop()+b); continue; case vMUL: b=stack.pop(); stack.push(stack.pop()*b); continue; case vDIV: b=stack.pop(); if(!b) return undefined; a = stack.pop(); stack.push( (a < 0 ? b < 0 : b > 0) ? (a/b)>>0 : -(-a/b >>0)); continue; } } return stack[0]; } var codes = [], value; for( var got = 0; got < n;) { inc(0); if(!valid) continue; if(!(value = bfDecode( odo))) continue; if( value <= 0 || value > n || codes[ value]) continue; ++got; for(var i = odo.length, s=""; i--;) s+=vCHARS[ odo[i]]; codes[ value] = s; } return codes; } function main( args) // node, script, number { n = parseInt( args[2]); if(isNaN(n)){ console.log("\nTry: node bfCodes number\nfor script saved as bfCodes.js"); return;} console.log("\ngenerating befunge code for numbers up to " + n); var start = Date.now(); var codes = bfCodes(n); var end = Date.now(); console.log("befunge codes:"); for( var i = 1; i <=n; ++i) console.log( i + ": " + codes[i]); console.log(end-start + " msec"); } main( process.argv); ``` ### Running under Windows 1. Download and install [Nodejs](https://nodejs.org/en/download/), a stand alone implementation of Chromes V8 JavaScript engine. 2. Save the program file above in a working directory using file name "bfCodes.js" (Windows filenames are case insensitive). 3. Right click in the working directory and create a shortcut to the command shell program (DOS box for oldies) with target `cmd.exe` 4. Edit the shortcut's properties and set the working folder to the name of your working directory (click in the location bar and copy). 5. Open `cmd.exe` using the shortcut and check the DOS prompt starts with the working directory 6. Enter "node bfCodes" without quotes and enter - runing node the first time can take longer than running it again. 7. Enter "node bfCodes 16" to show codes up to 16. **Do not use a large number!** ## Optimization The algorithm cycles through all combinations of befunge characters starting with a code string of length 1. Think of it as spinning a base 15 odometer from the least significant digit. Higher order digits click over with increasing slowness. `bfCodes` does not evaluate generated code that would make the stack length zero or negative or leave more than one number on the stack in an attempt to optimize speed of execution. ## The Brute Force Problem For a code set of 15 characters, the time it takes to run through all combinations of a given length is give by > > **Tlen = 15 \* Tlen-1** > > > which is to say that if your program runs fifteen times faster than mine, you will only be able to check one additional character code strings in the same time. To check two more characters in the same time a program would need to run 225 times faster. Time taken with a brute force approach rises exponentially as the length of code strings increases. And the magnitude of a number does necessarily indicate the number of befunge bytes needed to generate it. ### Some figures. Approximate times to generate a lists of codes on a Windows 7 32 bit notepad for integers up to * 9: 1 msec * 10: 16 msec * 32: 156 msec * 81: 312 msec * 93: 18.5 seconds * 132: 28 seconds To generate befunge for 3727 (which is 66 squared plus 6) by itself took 1 hour 47 minutes and generated `578*+:*6+` ## Optimal code generation Generating befunge for numbers without checking for shortest lengths is relatively simple. Using a recursive algorithm which used integer square roots and remainders, encodings for numbers up to 132 took about 3 msec instead of 28 seconds. They were not optimal. Because of the way it worked this particular algorithm produced`638:*-:*+` for 3727 in about 1 msec (instead of an hour or so) which *happened* to be optimal. The issue with providing a non brute force method is proving it is optimal in every case. Good luck! [Answer] # JavaScript Whant can be done with a JS snippet? In my machine, Firefox 64 bit, 416 in 60 seconds ``` function go() { B.disabled=true O.textContent = '...wait...' setTimeout(run, 100) } function run() { var o=[0], t0=performance.now(), te=t0+T.value*1000, k=[],t=[...'0123456789'],i=0,n=0,e,v,j,l,x,h MainLoop: for(;;) { for(;!k[n] && (e=t[i++]);) { if(performance.now()>te)break MainLoop for(v=[],j=0;x=e[j++];l=x) 1/x?h=v.push(+x):(b=v.pop(),x>'9'?h=v.push(b,b):(a=v.pop(),h=v.push(x<'+'?a*b:x<'-'?a+b:x<'/'?a-b:a/b|0))) if(!k[v]) { k[v]=e //if(!e[10]) { if (l==':') t.push(e+'+',e+'*') else if (h>1) { if (l == '1') t.push(e+'+',e+'-') else if (l != '0') t.push(e+'+',e+'-',e+'*',e+'/') } if (h<4) { if (l<'0'|l>'9') t.push(e+':'); [...'0123456789'].forEach(x => t.push(e+x)) } } } } o.push([n,k[n]]) ++n; } o[0]='Run time sec '+(performance.now()-t0)/1000+'\nTried '+t.length+'\nRange 0..'+(n-1)+'\nTop '+k.pop()+' '+k.length O.textContent=o.join`\n` B.disabled=false } ``` ``` Time limit sec:<input id=T type=number value=60><button id=B onclick='go()'>GO</button> <pre id=O></pre> ``` ]
[Question] [ # Background You have recently been hired by a small accounting firm. The world of accounting is somewhat foreign to you, so you're not sure whether you are following all the professional guidelines. In particular, you don't know when you should round all those numbers, and in which direction, so most of the time you just wing it and hope for the best. # Input Your input is a single string that represents a simple calculation. It contains some number of nonnegative integers delimited by the characters `+-*/`. The string reads from left to right, and the normal precedence rules are ignored, so `"23+1*3/4"` means "start with 23, add 1, multiply by 3, and divide by 4", the result being 18. The input will not contain numbers that start with `0` (except `0` itself), nor a division by zero. # Output At each stage of the calculation, you can either round the result up or down to the nearest integer, or keep it as it is. Finally, you round either up or down to obtain a integer result. Your output is the list of integers that may result from such a calculation, sorted and without duplicates. # Rules You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases ``` "42" -> [42] "2+0+4-0" -> [6] "23+1*3/4" -> [18] "5/2" -> [2,3] "5/2+7/3*6-1" -> [17,18,19,23] "23/2/2*30-170/3" -> [-7,-6,-2,-1,0,1,3,4] "1/3*2*2*2*2*2*2" -> [0,16,20,21,22,24,32,64] "1/3*9" -> [0,3,9] ``` [Answer] # J, 84 bytes Starting from a 1 element list the function keeps all the possible intermediate numbers in the list by evaling the next expression and adding it's up and down rounded copies. ~~Will golf further and add explanation tomorrow.~~ Can't find obvious ways to golf it more. ``` f=.3 :'/:~~.<.>((,>.,<.)@".@(":@],''x'',;@[))&.>/|.(>@{.;_2<\}.);:y rplc''/'';''%''' ``` Passes all the tests. Usage: ``` f '1/3*2*2*2*2*2*2' 0 16 20 21 22 24 32 64 f '1/3*9' 0 3 9 ``` [Try it here.](http://tryj.tk/) [Answer] # Python 2, 220 characters ``` import re,sys,math as m,fractions as f X=f.Fraction M=map F=['+']+re.split("(\D)",sys.argv[1]) r=[X(0)] while F:U=[eval('f.'+`n`+F[0]+F[1])for n in r];r=M(X,U+M(m.floor,U)+M(m.ceil,U));F=F[2:] print sorted(set(M(int,r))) ``` It keeps a list of all possible numbers and at each step, generates three numbers for every number in the list, even if there are duplicates. Thus the run-time complexity is exponential. However, it works instantly for these small examples. Dupes are removed at the end. It uses `fractions.Fraction` to do exact division, avoiding floating point inexactitudes. Add 5 characters (`r=map(X,g)` --> `r=set(map(X,g))`) to dramatically increase performance. [Answer] ## Python, ~~421~~ ~~370~~ 354 bytes Sorry, please bear with me. I am really new to python (I was just looking for a language that supports fractiosn) and used all of the few tricks I knew for shortening the code but it is still a monster considering that there is a python solution of almost half the size. I learned a lot and thought I'd submit it anyway=) New Version thanks to @kirbyfan64sos and @Zgarb ``` from fractions import* from math import* import re,operator as z s=input() N=re.split(r'[\*\/\-\+]',s) O=re.split(r'[0-9]+',s)[1:-1] d={'+':z.add,'-':z.sub,'*':z.mul,'/':z.truediv} l=[int(N[0])]#list of inters up to now for i in range(len(O)): #iterate over all operations n=set() for f in l: f=d[O[i]](f,Fraction(int(N[i+1]))) n.update([floor(f),ceil(f),f]) l=n print(set(map(floor,n))) ``` Old Version ``` from fractions import Fraction as F from math import floor,ceil import re s=input() N=re.split(r'[\*\/\-\+]',s) #Numbers O=re.split(r'[0-9]+',s)[1:-1] #Operators l=[int(N[0])] for i in range(len(O)): #Iterate over all operators n=set() for f in l: #Iterate over all possible numbers g=F(int(N[i+1])) o=O[i] if o=='/': f/=g elif o=='*': f*=g elif o=='-': f-=g else: f+=g n.add(floor(f)) #Add all possible numbers to a new set n.add(ceil(f)) # the 'set' structure prevents from having multiple copies n.add(f) # which is a really nice feature l=n #repeat print(set([floor(k) for k in n])) #also remove the unrounded ones ``` [Answer] # Mathematica, 134 ``` Union@Flatten@{Floor@#,Ceiling@#}&@ToExpression@StringReplace[#,x:("+"|"-"|"*"|"/"~~NumberString):>"//{Floor@#,#,Ceiling@#}"~~x~~"&"]& ``` [Answer] # MATLAB, 283 chars ``` function[u]=w(s) s=[' ' strsplit(regexprep(s,'\D',' $& '))];s=reshape(s,[2,size(s,2)/2]);o=s(1,:);d=cellfun(@str2num,s(2,:));a=d(1);for n=2:size(o,2)switch o{n}case'+';a=a+d(n);case'-'a=a-d(n);case'/'a=a/d(n);case'*'a=a*d(n);end;a=[ceil(a);a;floor(a)];end;u=unique(a(mod(a,1)==0))end ``` Ungolfed: ``` function [u] = WingitRound(i) i=[' ' strsplit(regexprep(i,'\D',' $& '))]; i=reshape(i,[2,size(i,2)/2]); o=i(1,:); n=cellfun(@str2num,i(2,:)); a=n(1); for n=2:size(o,2) switch o{n} case '+' a = a + n(n); case '-' a = a - n(n); case '/' a = a / n(n); case '*' a = a * n(n); end a = [ceil(a);a;floor(a)]; end u=unique(a(mod(a,1)==0))); end ``` While writing this, I realized that there is an even shorter way of doing this, which I will add once I finish writing it. [Answer] ## VBA, 347 bytes ``` Function OoCRE(inp As String) ct = 0 i = 1 Do While i < Len(inp) c = Mid(inp, i, 1) If Not IsNumeric(c) Then ct = ct + 1 If ct = 2 Then inp = Round(Application.Evaluate(Left(inp, i - 1))) & Right(inp, Len(inp) - (i - 1)) i = InStr(1, inp, c) ct = 1 End If End If OoCRE = Round(Application.Evaluate(inp)) i = i + 1 Loop End Function ``` ]
[Question] [ Write a program or function that takes in a positive integer N (via stdin/command line/function arg) and prints or returns a string representation of a two dimensional [random walk](http://en.wikipedia.org/wiki/Random_walk) that is N steps long, drawn out of slashes: `/` `\` (plus spaces and newlines for spacing). A 2D random walk starts at the origin of an infinite [integer lattice](http://mathworld.wolfram.com/IntegerLattice.html). Then N times repeatedly, a cardinal direction (up, down, left, right) is chosen uniformly at random and the walker moves one unit in that direction. The resulting path taken is the random walk. Here is a random walk for N = 6. Notice that it traverses back on itself when it reaches (-1, 3). [![N = 6 random walk example](https://i.stack.imgur.com/o67J3.gif)](http://www.wolframalpha.com/input/?i=2-dimensional%20random%20walk%2C%206%20steps) To draw this with slashes we essentially need to rotate the entire thing 45° clockwise. The axes and start and end points are not drawn in the slash version. ``` / \ \ /\ ``` A more complex walk like this (N = 20, though there's no way to tell): [![N = 20 random walk example](https://i.stack.imgur.com/OwVf8.gif)](http://www.wolframalpha.com/input/?i=2-dimensional%20random%20walk%2C%2020%20steps) Would become this: ``` / /\/ /\ \/\/ /\/ \/ ``` Your program needs to generate these type of slash versions of random walks. You *must* randomly choose each new direction the walk takes, so every running of the program for a certain N will almost definitely produce a different walk. (Pseudorandomness is fine.) There should never be any empty lines above or below the lowest and highest slashes (except for one optional trailing newline), and there should never be empty columns of spaces before or after the leftmost and rightmost slashes. So for N = 1, the output is always `/` or `\`, but never something like: ``` / ``` Trailing spaces are allowed as long as they don't go past the column of the rightmost slash. The submission with the fewest bytes wins. [Here's a handy byte counter.](https://mothereff.in/byte-counter) [Answer] ## Python 2, ~~300~~ ~~285~~ ~~257~~ ~~246~~ 236 bytes Something to kick things off. It should be possible to shrink this down further. Thanks @Maltysen for shaving 10 bytes. ``` from random import* N=input() x=y=0;G={} exec'n=randrange(4);l=n<2;u=n&1;G[(x-l,y-u)]="\\/"[l^u];x-=2*l-1;y-=2*u-1;'*N f=lambda i:range(min(x[i]for x in G),max(x[i]for x in G)+1) for i in f(0):print"".join(G.get((i,j)," ")for j in f(1)) ``` Generates the walk output into a dictionary G of visited (x,y) tuples, updating our location as we go. Each random step n is both either u/d (u) and l/r (l). [Answer] # Pyth, 74 bytes ``` K0VQJO2=GO2 XH,-ZJ-KG@"\/"xJG-=ZtyJ-=KtyG;=YmrhSdheSdCHjbclhYsmh@XkH\ k.xY ``` An even more optimized translation of Uri Zarfaty's answer. [Answer] **PHP 5.5 - 209 bytes** ``` <?for(;$X[]=$x+=1-2*$l,$Y[]=$y+=1-2*$u,$i++<$argv[1];){$m[$y-$u=$n&1][$x-$l=($n=rand(0,3))<2]='\\/'[$u^$l];}for($y=min($Y);$y<max($Y);$y++){for($x=min($X);$x<max($X);$x++)$s.=$m[$y][$x]?:' ';$s.="\n";}echo$s; ``` Ungolfed: ``` <? for (; $X[] = $x += 1 - 2 * $l, $Y[] = $y += 1 - 2 * $u, $i++ < $argv[1];) { $m[$y - $u = $n & 1][$x - $l = ($n = rand(0, 3)) < 2] = '\\/'[$u ^ $l]; } for ($y = min($Y); $y < max($Y); $y++) { for ($x = min($X); $x < max($X); $x++) { $s .= $m[$y][$x] ? : ' '; } $s .= "\n"; } echo $s; ``` Began working on a PHP answer from scratch, but the final code too much resembled the work of @Uri Zarfaty so I really did not have the nerve to to post it. Ended up porting said answer with a few modifications instead. Pushes x/y values into `$X` and `$Y` arrays to determine min/max in output loop. Usage: ``` php golf.php 200 ``` [Answer] # Pyth - 89 This is basically a translation on Uri Zarfaty's answer, though I did make some optimizations. ``` KZVQJO4=G<J2=b.&J1 XH,-KG-Zb@"\\/".|Gb-=KtyG-=Ztyb)LrhSm@dbHheSm@kbHFNy0jkm?@H,Nb},NbHdy1 ``` Explanation coming soon. [Try it here](http://pyth.herokuapp.com/?code=KZVQJO4%3DG%3CJ2%3Db.%26J1%20XH%2C-KG-Zb%40%22%5C%5C%2F%22.%7CGb-%3DKtyG-%3DZtyb)LrhSm%40dbHheSm%40kbHFNy0jkm%3F%40H%2CNb%7D%2CNbHdy1&input=100). ]
[Question] [ The game [Waving Hands](http://www.gamecabinet.com/rules/WavingHands.html) is somewhere between a pen-and-paper Magic: the Gathering and a very elaborate Rock Paper Scissors. Each turn you write down one of eight gestures for each hand: * wiggled `F`ingers * proffered `P`alm * `S`nap * `W`ave * `D`igit pointing * `C`lap * sta`B` * `N`othing There are few important rules that take precedence over the rest: * If both hands gesture `P` you automatically **surrender**. (This is a simplification, but we'll go with that.) * Only one hand at a time can gesture `B`. A series of gestures performed by the same hand can cast a spell, where each spell is tied to one particular sequence. These sequences can overlap, but each gesture can only be used as the final gesture of a single spell (so you can create up to two spells in a single turn). Some spells require a gesture to be made with both hands simultaneously. Your task is, given a list of gestures for each hand, to determine which spells could be cast in the current turn. For each hand, the last letter in the list represents the gesture chosen for the current turn. Here is the list of gesture sequences. Upper case letters refer to a gesture performed by a single hand, lower case letters refer to a gesture performed with both hands. ``` B Stab cDPW Dispel magic cSWWS Summon elemental cw Magic mirror DFFDD Lightning bolt DFPW Cure heavy wounds DFW Cure light wounds DPP Amnesia DSF Confusion DSFFFc Disease DWFFd Blindness DWSSSP Delayed effect DWWFWc Raise dead DWWFWD Poison FFF Paralysis FPSFW Summon troll FSSDD Fireball P Shield p Surrender PDWP Remove enchantment PPws Invisibility PSDD Charm monster PSDF Charm person PSFW Summon ogre PWPFSSSD Finger of death PWPWWc Haste SD Missile SFW Summon goblin SPF Antispell SPFPSDW Permanency SPPc Time stop SSFP Resist cold SWD Fear SWWc Fire storm WDDc Lightning bolt WFP Cause light wounds WFPSFW Summon giant WPFD Cause heavy wounds WPP Counterspell WSSc Ice storm WWFP Resist heat WWP Protection from evil WWS Counterspell ``` Yes, `Lightning bolt` and `Counterspell` have two different sequences each. You may write a program or function, taking input in any convenient list or string format, via STDIN, command-line argument or function argument, as long as it's not pre-processed. You may output pairs of spells via return value or by printing to STDOUT. Again, you may use any convenient list or string format, as long as the output is unambiguous. You may assume that the sequences for left and right hand are the same length, and that they are valid (in particular, `B` will never be performed by two hands at the same time). Note that the input will *only* contain upper case letters. Lower case letters are only used in the above list to indicate that both hands need to perform the same (upper-case) gesture. For spells which end in a two-hand gesture you should just output a single spell. If one hand cannot perform a spell, this needs to be indicated by a string containing only a hyphen, `-`. This is code golf, so the shortest answer (in bytes) wins. ## Examples Each example consists of three lines: the left hand sequence, the right hand sequence (both input; the right-most gesture is the most recent one), and the list of all possible spell combinations (the output). ``` WFP WWS [["Cause light wounds","Counterspell"],["Shield","Counterspell"]] SD BB [["Missile","Stab"]] WWP WPP [["Surrender"]] DFW CCW [["Cure light wounds","-"]] FFW WWF [["-","-"]] DCW CCW [["Magic mirror"]] WFPSFW PPDDPP [["Summon goblin","Shield"],["Summon ogre","Shield"],["Summon troll","Shield"], ["Summon giant","Shield"],["Summon goblin","Amnesia"],["Summon ogre","Amnesia"], ["Summon troll","Amnesia"],["Summon giant","Amnesia"]] BSWWS CSWWS [["Counterspell","Counterspell"]] CSWWS CSWWS [["Counterspell","Counterspell"],["Counterspell","Summon elemental"], ["Summon elemental","Counterspell"],["Summon elemental","Summon elemental"]] PWPWWC BBSPPC [["Haste"],["Time stop"]] ``` [Answer] # Python 2, 685 Defines a function `f` accepting two strings. Return value is the string `Surrender` if the player surrenders; otherwise, a set consisting of strings (which indicate two-handed spells), and length-2 tuples of strings (indicating separate spells for each hand). Base64 encoded source: ``` I2VuY29kaW5nOkxhdGluCmV4ZWMiIiJ42mVTTWvjMBC951foJntxy+61iwtNjLqFLJhqQYeQg2KPbYEsBUlOGtrub98Zp6Efe7Lm6c2H3jyvy9Y0KVuWXCa940VT1arklYl7sGzUvWkQk0pJJEzj6B0DCyO4pC0vKiGqquRr0w/JGdeznbeJYKqxmgKwAfThxI5+cm2kiwtuKeUdr+uS340OotEYSYEs77opGu8wVlJKJFRg9QlaBl0HXHK1UUoobF97E4knBObVOmh7igarilpSv7exU/AWRxZS0sjCBNhpArCwHAzYFo+VwugRRn9cMAauGbRL9FS8mZNWgw4jw2IxQZhBcQH3EOYZPrX0fVwwhFSNTeXc1PUQmO9YCzpccrwg8LeJ0Vjkfczs/c4aLCdr7HDn0rwOO8fYFXk1hFE7nPGEoBTz2PjoxBpPL5Gki1wwjVMqulzpKX4VXX3WpzeaXorDVhf+5+UpWtIKA3z82zhKfeiMbMonCevgE64It8e64EcGBzOz5ZcC+eK+tHrctZrZIhTrm+f1Jm47H1hkxrE1Mx2z14DtjyZcclm8nvYodJbn2rUMt5eFzV+zLctIn8ulD1zz2xmiSoYqBY3KZxZcFvM8f10sz65vjqg/eZyNJgRMJO8J0cw/XDDoCGQyIdqSL3EdLfozvtkOKY8aObRJck59jCV/cAcTzc5Yk07z3hXxfmm0C62uxuCPGYHF5Pe0I7olIxIQRhSoqpr//yZ0P6IPzYWWL3CeK75ooWNdhrrlN015T4dimb/cZ6GwePgZIE3BbZqX5+ypOOUkxRNJcWauUSbWMkJPZ5TSzujr1XPWFm3+bRasyW+/568F2iQE3AQaf7uxm6sfKHs4f3jNt/9cMNXTZmIiIiIuZGVjb2RlKCd6aXAnKQ== ``` The source is of the form`exec "eu352909HE%#NTHQh".decode('zip')` which executes the following code: ``` L=dict(B='Stab',cDPW='Dispel magic',cSWWS='Summon elemental',DFFDD='Lightning bolt',DFPW='Cure heavy wounds',DFW='Cure light wounds',DPP='Amnesia',DSF='Confusion',DWSSSP='Delayed effect',DWWFWD='Poison',FFF='Paralysis',FPSFW='Summon troll',FSSDD='Fireball',P='Shield',PDWP='Remove enchantment',PSDD='Charm monster',PSDF='Charm person',PSFW='Summon ogre',PWPFSSSD='Finger of death',SD='Missile',SFW='Summon goblin',SPF='Antispell',SPFPSDW='Permanency',SSFP='Resist cold',SWD='Fear',WFP='Cause light wounds',WFPSFW='Summon giant',WPFD='Cause heavy wounds',WPP='Counterspell',WWFP='Resist heat',WWP='Protection from evil',WWS='Counterspell') G=lambda l,r,L:{L[s]for s in L if l.endswith(s.upper())and all(r[~i]==s[~i].upper()or'a'>s[~i]for i in range(len(s)))} B=dict(cw='Magic mirror',DSFFFc='Disease',DWFFd='Blindness',DWWFWc='Raise dead',PPws='Invisibility',PWPWWc='Haste',SPPc='Time stop',SWWc='Fire storm',WDDc='Lightning bolt',WSSc='Ice storm') d='-' def f(l,r):c=G(l,r,B)|G(r,l,B);return[c|{(x,y)for x in G(l,r,L)or d for y in G(r,l,L)or d}-{(d,d)*(len(c)>0)},'Surrender'][l[-1]==r[-1]=='P'] ``` [Answer] # CJam, ~~987 931 925~~ [663](https://mothereff.in/byte-counter#qN%2F%3AQ%3B%22%C3%9C%C3%A3%C3%A3%C2%9D0%C3%90%C2%A8%C2%AC%C2%91%C3%81%C3%B3%3A-%2F%C3%B01%24%C2%BD%C3%8F%C2%B6%C2%B6%C3%B2u%C2%B4d%C3%B3%C3%A1%C2%8C3%C3%A4%C3%91%C3%AC%3F%C2%B4%C3%AC%3E%C2%8D%C2%B33c%C3%AFC%C3%A0%C3%97M%C3%97%C2%80%C3%A2%C3%80%C2%80C%C2%80%C3%92%C3%BB%C2%ACu%3FxO%2C%C3%86Fv%29p%C3%99%C3%BB!%C2%BC%20e%C3%96U%C3%88R%C2%82%C3%99%C2%8Bn%C3%82o%2F%C2%84%C2%86%C2%B5%C2%BEH%C2%BC%C2%86R%C3%8E%C3%9A%C3%A7%C2%A1%C3%B1%3E%C2%94z%2232f-222bCb%22%20BcDPWSwFdps%22f%3DS%2F%22%5Bz%C3%B5s%C2%A2%40%C2%86%3E%C2%9F2%C2%89%C2%AFf%C2%A5s%C2%98y%3C%C3%A9SG%C2%86%C3%86%C3%84b%C3%9A%C3%98%C3%9C%7D%7D%C2%A4%C2%BA%C3%85d%C2%93%C2%8F%C2%92%C2%B8%28EWfa%C2%A4%C3%A9%C3%B5bfXp%C3%80S7%C3%A9%C3%9BM%C2%8D%C2%BC%C2%96%C3%A5%C2%A9%20%C2%94%C2%8C%C3%91%C3%A6%C2%B6a%C2%ABI%C2%9E%C2%B3%C3%BE%3E%C3%99%C3%9C%C2%A1%2F%C2%A6%24l%C3%A2%20%C2%8B%C2%B5%C3%A3%C3%86%C3%98%C2%A2%C2%A7%26%C3%A1%C2%BC%C3%B3%C3%80w%C3%8FU%C2%A4%C3%B4Y%C2%98%C3%B0%C3%A7Q%C3%B2%C2%82%C2%8C%C2%8A%C3%94%C2%8B%C2%92R%23p%C3%93zP%C3%97%C2%B0%7E%C2%82%C3%AF%5D%C2%97v%C2%AB%C2%85vi%C3%9AY%C2%B6%C2%91%C2%84%C2%A8%C2%AF%60%7Co%28N%C2%8A%C3%AA%40%C3%A6G%C3%8F%C2%94%5D%C3%8C%C3%89%C3%BE%C2%96MN%C3%92%C3%802%C2%9Cy%C3%8Cg%C3%8A%5D%C3%8A4%C3%8A%7CB%C3%83%C2%8AKW%C3%A3I%C2%9DowIQ%C2%A3%C3%8D-%2C_%C2%A5%C3%B7%C2%92%C2%B6%C2%BAK-%3BKr%20%C2%82%C3%95t%C2%89V%C3%A6W%C3%AF%C3%B7%C2%A6%C2%84%3F%2B%C2%9B%C3%9C%C3%8C%C3%9C%C3%B3%C3%8B%C2%96%C2%AF%C3%A7p2M%C2%88vmc!h%C3%A0tc%C2%BB%C2%AC%7DsI%C3%A6%C2%82T%C3%8C%C3%82%26%C3%AB%C2%9E6%C2%BA%C2%B2%3E%C2%86N%C2%BA%C2%AF%C2%A6F%C2%A4%C2%BD%7B%C3%9COS%C2%B5%C2%B8%C3%91%27%7C%60%C2%B2%C2%91P%C2%B3%C3%ADD%C2%BF%C2%8EZ.c%C2%A2%20%C3%92%C2%84%C2%BF%C3%B1%C2%90%C3%85%C2%9F%C2%A2M%C2%92R%C3%B6%C2%88Dk%3F%C3%A0%C2%A7i%C3%B5%3B%C2%9F%C2%AD%C2%84%C2%A1%C2%8Ak%C2%93%C2%89%27%C2%82%C3%A7T%C2%97%C3%91%C2%96%C3%B1%2231f-225b26b97f%2B%3Ac%22j%22Ser%27z%2F%7B%28eu%5C%2B%7D%25%5Dz_%7B%7B%7ESaQX%3D%7B_QV%3DW%29%3AW%3D%3D%7B_el%2Bm*%7D%7Bm*%3As%7D%3F%7D%2F%3As%7BS%2B2%24S%2B%23%291%24%22-%22%3AD%3F%40%40%7D%25-2%3C%7D%251%3AV%28%3AX%28%3AW%3B%5C%7D2*m*%7Bz_%2C1%3E%7B%29__%7E%3D%5CDa%26%2C!%3D%7Ba%2B%7D%7B%3B%7D%3F%24W%3E%7D*%7E%7D%25_%26_%2C%28%7B%5BD_%5Da-%7D*_%7B%7B%60D%26%2C!%7D%2C%7D%3AA%7E%2C%7BA%7D*_%5B%22Surrender%22_%5Da%3AS%26%2C%7B%3BS%7D*p) bytes ``` qN/:Q;"Üãã0Ш¬Áó:-/ð1$½Ï¶¶òu´dóá3äÑì?´ì>³3cïCà×M×âÀCÒû¬u?xO,ÆFv)pÙû!¼ eÖUÈRÙnÂo/µ¾H¼RÎÚç¡ñ>z"32f-222bCb" BcDPWSwFdps"f=S/"[zõs¢@>2¯f¥sy<éSGÆÄbÚØÜ}}¤ºÅd¸(EWfa¤éõbfXpÀS7éÛM¼å© Ñæ¶a«I³þ>ÙÜ¡/¦$lâ µãÆØ¢§&á¼óÀwÏU¤ôYðçQòÔR#pÓzP×°~ï]v«viÚY¶¨¯`|o(Nê@æGÏ]ÌÉþMNÒÀ2yÌgÊ]Ê4Ê|BÃKWãIowIQ£Í-,_¥÷¶ºK-;Kr ÕtVæWï÷¦?+ÜÌÜó˯çp2Mvmc!hàtc»¬}sIæTÌÂ&ë6º²>Nº¯¦F¤½{ÜOSµ¸Ñ'|`²P³íD¿Z.c¢ Ò¿ñÅ¢MRöDk?à§iõ;­¡k'çTÑñ"31f-225b26b97f+:c"j"Ser'z/{(eu\+}%]z_{{~SaQX={_QV=W):W=={_el+m*}{m*:s}?}/:s{S+2$S+#)1$"-":D?@@}%-2<}%1:V(:X(:W;\}2*m*{z_,1>{)__~=\Da&,!={a+}{;}?$W>}*~}%_&_,({[D_]a-}*_{{`D&,!},}:A~,{A}*_["Surrender"_]a:S&,{;S}*p ``` *Note that this contain all ASCII characters of ASCII code 32 to 255 only. Some characters might be skipped by SE, so better to copy the code from the link above* This above code is a base converted version of the following 925 byte solution: ``` qN/:Q; "B|Stab|cDPW|Dispel magic|cSWWS|Summon elemental|cw|Magic mirror|DFFDD|Lightning bolt|DFPW|Cure heavy wounds|DFW|Cure light wounds|DPP|Amnesia|DSF|Confusion|DSFFFc|Disease|DWFFd|Blindness|DWSSSP|Delayed effect|DWWFWc|Raise dead|DWWFWD|Poison|FFF|Paralysis|FPSFW|Summon troll|FSSDD|Fireball|P|Shield|p|""Surrender":R"|PDWP|Remove enchantment|PPws|Invisibility|PSDD|Charm monster|PSDF|Charm person|PSFW|Summon ogre|PWPFSSSD|Finger of death|PWPWWc|Haste|SD|Missile|SFW|Summon goblin|SPF|Antispell|SPFPSDW|Permanency|SPPc|Time stop|SSFP|Resist cold|SWD|Fear|SWWc|Fire storm|WDDc|Lightning bolt|WFP|Cause light wounds|WFPSFW|Summon giant|WPFD|Cause heavy wounds|WPP|Counterspell|WSSc|Ice storm|WWFP|Resist heat|WWP|Protection from evil|WWS|Counterspell"]s'|/2/_ {{~SaQX={_QV=W):W=={_el+m*}{m*:s}?}/:s{S+2$S+#)1$"-":D?@@}%-2<}%1:V(:X(:W;\}2* m*{z_,1>{)__~=\Da&,!={a+}{;}?$W>}*~}%_& _,({[D_]a-}*_{{`D&,!},}:A~,{A}* _[R_]a:S&,{;S}*p ``` Newlines are just for show. ~~This can be golfed **a lot**, but at least I got it to pass all test cases -\_- .~~ *This took longer than expected.* *UPDATE 1* - golfed the code part a bit. Still scope for more. The string part can also be golfed/base converted, but I will refrain from that now as all other answers are not doing that either. *UPDATE 2* - Done golfing the code, now time for compressing that string. *UPDATE 3* - Base converted the string to reduce the code size to 663 bytes (It can be reduced to 640 bytes, but then there are 0 to 31 ASCII code characters too, which are really hard to deal with and I will only reside to them when I get beaten again). [Try it online here](http://cjam.aditsu.net/) [Answer] # Java, ~~1565~~ 1388 Call with `java M %leftString %rightString`. Outputs `Surrender` if player surrenders. Otherwise outputs string in this form `bothHandSpell;oneHandSpell,oneHandSpell;...`. Note, this is a one liner solution for a rather complicated problem. : ) ``` class M{String[]a="B,cDPW,cSWWS,DFFDD,DFPW,DFW,DPP,DSF,DWSSSP,DWWFWD,FFF,FPSFW,FSSDD,P,PDWP,PSDD,PSDF,PSFW,PWPFSSSD,SD,SFW,SPF,SPFPSDW,SSFP,SWD,WFP,WFPSFW,WPFD,WPP,WWFP,WWP,WWS,-".split(","),b="Stab,Dispel Magic,Summon elemental,Lightning bolt,Cure heavy wounds,Cure light wounds,Amnesia,Confusion,Delayed effect,Poison,Paralysis,Summon troll,Fireball,Shield,Remove enchantment,Charm monster,Charm person,Summon ogre,Finger of death,Missile,Summon goblin,Antispell,Permanency,Resist cold,Fear,Cause light wounds,Summon Giant,Cause heavy wounds,Counterspell,Resist heat,Protection from evil,Counterspell,-".split(","),c="cw,DSFFFc,DWFFd,DWWFWc,PPws,PWPWWc,SPPc,SWWc,WDDc,WSSc".split(",");public static void main(String[]a){System.out.println(new M().s(a[0],a[1]));}int e,f,g,h,i,j,k,l,m,n;String s(String o,String p){if(m(o,p,"p")>0)return"Surrender";String q="";f=e=0;for(;f<10;f++)q+=(m(o,p,c[f])|m(p,o,c[f]))>0?"Magic mirror,Disease,Blindness,Raise dead,Invisibility,Haste,Time stop,Fire storm,Lightning Bolt,Ice storm".split(",")[f*(e=1)]+";":"";for(f=0;f<33-e;f++)for(g=f<1?1:0,h=0;g<32-h&m(o,p,a[f])>0;)q+=m(p,o,a[++g*(e=1)])>0?b[f]+","+b[g*(h=1)]+";":"";return q;}int m(String o,String p,String r){k=n=0;if(r=="-")n=1;if((i=o.length())<(j=r.length()))return n;for(;k<j;)n|=((o.charAt(l=i-j+k)|32)!=((m=r.charAt(k++))|32)|((m|32)==m&(p.charAt(l)|32)!=(m|32)))?2:0;return n==2?0:1;}} ``` Indented: ``` class M{ String[]a="B,cDPW,cSWWS,DFFDD,DFPW,DFW,DPP,DSF,DWSSSP,DWWFWD,FFF,FPSFW,FSSDD,P,PDWP,PSDD,PSDF,PSFW,PWPFSSSD,SD,SFW,SPF,SPFPSDW,SSFP,SWD,WFP,WFPSFW,WPFD,WPP,WWFP,WWP,WWS,-".split(","),b="Stab,Dispel Magic,Summon elemental,Lightning bolt,Cure heavy wounds,Cure light wounds,Amnesia,Confusion,Delayed effect,Poison,Paralysis,Summon troll,Fireball,Shield,Remove enchantment,Charm monster,Charm person,Summon ogre,Finger of death,Missile,Summon goblin,Antispell,Permanency,Resist cold,Fear,Cause light wounds,Summon Giant,Cause heavy wounds,Counterspell,Resist heat,Protection from evil,Counterspell,-".split(","),c="cw,DSFFFc,DWFFd,DWWFWc,PPws,PWPWWc,SPPc,SWWc,WDDc,WSSc".split(","); public static void main(String[]a){ System.out.println(new M().s(a[0],a[1])); } int e,f,g,h,i,j,k,l,m,n; String s(String o,String p){ if(m(o,p,"p")>0) return"Surrender"; String q=""; f=e=0; for(;f<10;f++) q+=(m(o,p,c[f])|m(p,o,c[f]))>0?"Magic mirror,Disease,Blindness,Raise dead,Invisibility,Haste,Time stop,Fire storm,Lightning Bolt,Ice storm".split(",")[f*(e=1)]+";":""; for(f=0;f<33-e;f++) for(g=f<1?1:0,h=0;g<32-h&m(o,p,a[f])>0;) q+=m(p,o,a[++g*(e=1)])>0?b[f]+","+b[g*(h=1)]+";":""; return q; } int m(String o,String p,String r){ k=n=0; if(r=="-") n=1; if((i=o.length())<(j=r.length())) return n; for(;k<j;) n|=((o.charAt(l=i-j+k)|32)!=((m=r.charAt(k++))|32)|((m|32)==m&(p.charAt(l)|32)!=(m|32)))?2:0; return n==2?0:1; } } ``` Edit: Used Peter's suggestion to create a String array with less code. Any hints to improve this would be appreciated. [Answer] # JavaScript (ES6), ~~1070~~ 941 Base64 encoded: ``` Zj0obCxyKT0+e3k9WyItIl0sRD1bXSxSPVtdLEw9W10sZD17fSxidG9hKGBK1pvQHQOKyl6XWZqCJzRwM9bRK6aaifV6V6Z6e1qXRxJZZLQxqCJzWaKuuivRzDQuKCG2eKeDVuiW3QMUUMPQK6t7WF5q/LXCi6d2zQMU9bQK6t7WWKCG3XCi6d2zQMVbQCad6yJrQM8/QKid+6yKifQKIXQOKx5qx7QKIUUVzQGWKd2d6yzQNYUV3QN6VrJ53V5995y3QNZJJI/RFqKx7V15p3QKZYVZzQ+iKyifQNZYVYPQ9qtqXFysis0FFF0Summon1troll0FPSFW0Fireball0FSSDD0Shield0P0Surrender0p0Remove1enchantment0PDWP0Invisibility0PPws0Charm1monster0PSDD0Charm1person0PSDF0Summon1ogre0PSFW0Finger1of1death0PWPFSSSD0Haste0PWPWWc0Missile0SD0Summon1goblin0SFW0Antispell0SPF0Permanency0SPFPSDW0Time1stop0SPPc0Resist1cold0SSFP0Fear0SWD0Fire1storm0SWWc0Lightning1bolt0WDCs0Cause1light1wounds0WFP0Summon1giant0WFPSFW0Cause1heavy1xcKLp3bNFjxQ9AqLp7Xq7KXpZdFjz9CHHtbLaK5tFkknNEXrIrLdYXmrdFlhT9D66LXnLYqJ9X66JtXr4pdFlj9AqLp7Xq7KXpZdFlkmApLnJlcGxhY2UoLzEvZywiICIpLnNwbGl0KDApLmV2ZXJ5KCh2LHgsYSk9PmRbeCUyfHxhW3grMV1dPXYpO2s9KGgsbyxHKT0+KG49ZFtzXSxxPWgubWF0Y2gocysiJCIsImkiKSkmJlsuLi5zXS5ldmVyeSgoYyxpKT0+ISh3PWMubWF0Y2goIlthLXpdIikpfHxoW2o9aStoLnNlYXJjaChxKV09PW9bal0pJiYodz9+fkQuaW5kZXhPZihuKT9EOltdOkcpLnB1c2gobik7Zm9yKHMgaW4gZCl7ayhsLHIsTCk7ayhyLGwsUik7aWYoRD09ZFsicCJdKXJldHVybiBEfVI9Ui0xP3k6UjtMPUwtMT95Okw7cmV0dXJuIEQtMXx8UiE9TD9MLnNvbWUocz0+Ui5zb21lKHQ9PiFELnB1c2goW3MsdF0pKSl8fEQ6RH0= ``` You run it by doing `eval(atob("Zj0obCxyK..."))` in the Firefox console. Golfed code (may include characters not supported by Stack Exchange): ``` f=(l,r)=>{y=["-"],D=[],R=[],L=[],d={},btoa(`JÖÐÊ^Y'4p3ÖÑ+¦õzW¦z{ZGYd´1¨"sY¢®º+ÑÌ4.(!¶x§VèÝPÃÐ+«{X^jüµÂ§vÍõ´ êÞÖX Ýp¢éݳ@Å[@&ë"k@Ï?@¨û¬ô !t+jÇ´ !EÍ)Ýë,Ð5ÝzV²yÝ^}÷·@ÖI$Ñ¢±í]y§t eYÍ¢+(@ÖXUÐö«j\\¬Í]ºi¨[k¢Ytô[Ab­æÚ]I ÃÑ(bzWt?D®®·§uêô§D^ÞÕéÜ©íéíÐðÖ?B'¾+"n)b·-?4 «Y¨Ë^¯CÒ=ªæÖ«²ô= ÅÑ+¦õ¢ ÞÐô[Ab«Öõuæ­CÖ<TH=jË^ÐõYg42+,W´H=ºi¨X(nX§Ñ!VÐ íÊ^]<]z¹éÜËDô[Dâíl¶tHóÜѬËur]Ñ$?A^j½X=·µ²Ú+DYÍm)àÕº%·E ÍjëÖX Ýp¢éݳE?D®j'ÖÝô[@ºÇµæ¯Ë\\(ºwlÑcÅ@¨º{^®Ê^]<ýqíl¶æÑdsD^²+-Ö·Eý®^rبWë¢m^¾)tYcô §µêì¥éeÑe`).replace(/1/g," ").split(0).every((v,x,a)=>d[x%2||a[x+1]]=v);k=(h,o,G)=>(n=d[s],q=h.match(s+"$","i"))&&[...s].every((c,i)=>!(w=c.match("[a-z]"))||h[j=i+h.search(q)]==o[j])&&(w?~~D.indexOf(n)?D:[]:G).push(n);for(s in d){k(l,r,L);k(r,l,R);if(D==d["p"])return D}R=R-1?y:R;L=L-1?y:L;return D-1||R!=L?L.some(s=>R.some(t=>!D.push([s,t])))||D:D} ``` Since the spell dictionary consists of letters only, we can treat it as a base64-encoded string and use numbers as separators and spaces. I "decoded" the base64-like string into a binary string, which is 3/4 the size of the original. Mildly ungolfed: ``` f=(l,r)=>{ // y - default array // D,R,L - result arrays for Doublehanded, Right and Left // d - dictionary mapping of spell combos to spell names y=["-"],D=[],R=[],L=[],d={}, // split string on `0` and replace `1`s with spaces, to populate `d` btoa(`<UGLY BINARY STRING>`).replace(/1/g," ").split(0).every((v,x,a)=>d[x%2||a[x+1]]=v); // given a main hand, off hand, and result array to populate, // decide if current combo `s` applies k=(h,o,G)=> (n=d[s],q=h.match(s+"$","i")) // does `s` match the end of `h`, case insensitive? && [...s].every((c,i)=> !(w=c.match("[a-z]")) || // is every letter of `s` not lowercase h[j=i+h.search(q)]==o[j] // or (if lowercase), a match between the hands? ) && (w? // if the last letter so `s` was lowercase ~~D.indexOf(n)? // if D doesn't already have this spell D // add it to D : // else [] // add it to a throwaway array :G).push(n); // else, add it to this hand's result array for(s in d){ k(l,r,L); // test this spell against each hand k(r,l,R); if(D==d["p"]) return D // if the doublehanded result is "Surrender" // return immediately } R=R-1?y:R; // replace empty arrays with ["-"] L=L-1?y:L; // (`[]-1` is -1, which is truthy, while ["foo"]-1 is `NaN`, falsy) return D-1||R!=L // if D is empty, or R and L not both empty, ? // add all pairwise R/L combos to D and return D L.some(s=>R.some(t=>!D.push([s,t]))) ||D :D // otherwise, just return D } ``` One golf I particularly like is testing for empty arrays with `array - 1`. * An empty array will produce a truthy value: `[] - 1 => "" - 1 => 0 - 1 => -1 (truthy)` * A filled array will produce a falsey value: `["foo"] - 1 => "foo" - 1 => NaN (falsey)` ]
[Question] [ ## **Challenge:** Given two five-card hands, determine which one wins by the [standard ranking of poker hands](http://en.wikipedia.org/wiki/List_of_poker_hands). ## **Input:** Ten cards separated by spaces from stdin or as command line arguments, whichever you prefer. The first five cards are Player 1's hand while the last five are Player 2's hand. Each card will be a two letter string of the form RS where R is rank and S is suit. The ranks range from 2-9, T for ten, and J, Q, K, and A for Jack, Queen, King, and Ace respectively. The suits are H, D, C, S for Hearts, Diamonds, Clubs, and Spades respectively. You must output the number of the player that wins: '1' or '2'. ## **Examples of Cards:** ``` AS - the Ace of Spades QD - the Queen of Diamonds 2C - the Two of Clubs TH - the Ten of Hearts ``` ## **Input to Output Examples:** ``` 5H 5C 6S 7S KD 2C 3S 8S 8D TD -> 2 ``` Explanation: Player 1 has a Pair of Fives while Player 2 has a Pair of Eights. ``` 5D 8C 9S JS AC 2C 5C 7D 8S QH -> 1 ``` Explanation: Neither Player has anything special, but Player 1's high card is an Ace while Player 2's high card is a Queen. ``` 2D 9C AS AH AC 3D 6D 7D TD QD -> 2 ``` Explanation: Player 1 has Three Aces, Player 2 has a Flush of Diamonds. ``` 4D 6S 9H QH QC 3D 6D 7H QD QS -> 1 ``` Explanation: Both players have a Pair of Queens, but Player 1's second highest card is a Nine whereas Player 2's is a Seven. ## **Rules and Clarifications:** * Refer to the [standard ranking of poker hands](http://en.wikipedia.org/wiki/List_of_poker_hands) for the details of comparing hands. * You may assume that there are no repeated cards in each pair of hands. * You may assume that there is a definite winner in each case. * Suit does not factor into the ranking of a hand. For example, two royal flushes of different suits are equal (therefore any input where both players have a royal flush is invalid by the preceding rule). * As this is code golf, the shortest answer wins. ## **Notes:** * Related to [this question](https://codegolf.stackexchange.com/questions/6494/name-the-poker-hand) and [this one](https://stackoverflow.com/questions/3364869/code-golf-who-has-the-best-poker-hand). * Based on [Project Euler Problem 54](http://projecteuler.net/problem=54) [Answer] ## Haskell - ~~352~~ 339 characters ``` import Data.List v h=10*(sum$map(\l->l*l)g)+b g:k where (g,k)=unzip$reverse$sort$map(\r->(length r,head r))$group$sort$map(maybe 0 id.(`elemIndex`"23456789TJQKA").head)h b(1:_)=f(map(!!1)h)+t k;b _=0 f(y:z)|all(==y)z=75;f _=0 t[y,_,_,_,z]|y-z==4=70;t[12,3,2,1,0]=65;t _=0 w(a,b)|v a>v b="1\n";w _="2\n" main=interact$w.splitAt 5.words ``` Runs: ``` & echo "5H 5C 6S 7S KD 2C 3S 8S 8D TD" | runhaskell 25056-Poker.hs 2 & echo "5D 8C 9S JS AC 2C 5C 7D 8S QH" | runhaskell 25056-Poker.hs 1 & echo "2D 9C AS AH AC 3D 6D 7D TD QD" | runhaskell 25056-Poker.hs 2 & echo "4D 6S 9H QH QC 3D 6D 7H QD QS" | runhaskell 25056-Poker.hs 1 ``` Ungolf'd and commented, so you can see the techinque: ``` import Data.List value :: [String] -> [Int] value hand = 10 * (sum $ map (\l->l*l) groups) + bonus groups : kicker -- ^ Value of a hand is 10 times the sum of the squares of the group lengths -- plus the straight & flush bonus, followed by the kicker (to break ties) -- This 10 * sum-of-squares + bonus works out to put the hands in category -- order, and then they only need to be ordered by card ranks. where -- | The cards are sorted into groups by matching rank, then the groups -- sorted by length and rank: For example: "7C 7D 7H QS 2S" will becomes -- [(3,7),(1,Q),(1,2)]. This is like a run-length encoding. Finally, the -- groups lengths, and the kicker ranks are taken apart into two lists. -- N.B: kicker here includes the ranks of the groups, unlike the poker term. (groups,kicker) = unzip -- split apart $ reverse $ sort -- reverse sort by (length,rank) $ map (\r->(length r,head r)) -- turn groups into (length,rank) pairs $ group $ sort -- group sorted ranks $ map (maybe 0 id . (`elemIndex`"23456789TJQKA") . head) hand -- take first letter of each card in the hand, and map to [0..12] -- | Give a bonus for flush and straight to hands with five cards, -- or equivalently hands where the largest group length is just 1 bonus (1:_ ) = flush (map (!!1) hand) -- flush takes the suits of the hand + straight kicker -- straight takes the ranks bonus _ = 0 -- | A flush is if all suits match the first suit flush (y:z) | all (==y) z = 75 | otherwise = 0 -- | There are two kinds of straight. -- N.B: If there are five groups, then there are no duplicate ranks straight [y,_,_,_,z] | y-z == 4 = 70 -- normal, high to low straight [12,3,2,1,0] = 65 -- ace is low, but it sorts high straight _ = 0 wins :: ([String], [String]) -> String wins (a,b) | value a > value b = "1\n" | otherwise = "2\n" main = interact $ wins . splitAt 5 . words ``` [Answer] # Python - ~~774~~ ~~722~~ ~~707~~ ~~698~~ 685 chars ``` import sys t,q,e,u='--23456789TJQKA','SDCH',enumerate,len _=lambda c,i=0:chr(97+c[i]) def j(s): v,g,l=[0]*15,[0]*4,'' for c in s: r,s=c[0],c[1];v[t.find(r)]+=1;g[q.find(s)]+=1 c,h,k,m,f=0,0,[0,0,[],[],[]],0,0 for x,i in e(v): for b in[2,3,4]: if i==b:k[b]+=[x] v[1]=v[14] for x,i in e(v): if i: c+=1 if c==5:m,h=1,x if i==1:l+=_([x]) else:c=0 f,l,d=max(g)//5*2,l[::-1],'';z=f+m if z==3:d='z'+l if k[4]:d='y'+_(k[4])+l if k[2] and k[3]:d='x'+_(k[3])+_(k[2]) if z==2:d='w'+l if z==1:d='v'+_([h]) if k[3]:d='u'+_(k[3])+l if u(k[2])>1:d='t'+_(k[2],1)+_(k[2])+l if u(k[2])==1>u(k[3]):d='s'+_(k[2])+l return d or l p=sys.argv print(1+(j(p[1:6])<j(p[6:]))) ``` I chose to generate a string for each hand that represents it, starting with a character for the type of hand, followed by characters describing the particular variation of the type (for example, which card did you just have 4 of?), followed by the values of the remaining cards in case of a tie (if both players have the same double pair, the 5th card will have to decide who wins). I've tested it quite extensively, but I don't actually play poker, so I hope I got it right. Also, I know it's not fully golfed yet, I can probably shave off a few dozen chars later on. [Answer] # JavaScript - ~~526~~ 508 ``` function a(b){b=b.split(" ");var c=b.splice(5,5),d=[],e=[],r=[8,9,5,6,1,2,3,10,4,7],A=14,K=13,Q=12,J=11,S={"S":1,"C":2,"H":4,"D":8};for(i=0;i<5;i++){d.push(b[i].split('')[1]);b[i]=b[i].split('')[0];e.push(c[i].split('')[1]);c[i]=c[i].split('')[0]}function p(w,m){var v,i,o,s=1<<w[0]|1<<w[1]|1<<w[2]|1<<w[3]|1<<w[4];for(i=-1,v=o=0;i<5;i++,o=Math.pow(2,w[i]*4)){v+=o*((v/o&15)+1)}v=v%15-((s/(s&-s)==31)||(s==0x403c)?3:1);v-=(m[0]==(m[1]|m[2]|m[3]|m[4]))*((s==0x7c00)?-5:1);return r[v]}alert(p(b,d)>p(c,e)?1:2)} ``` usage: ``` a("5H 5C 6S 7S KD 2C 3S 8S 8D TD"); ``` ungolfed: ``` function a(b) { b = b.split(" "); var c=b.splice(5,5), d=[], e=[], r=[8,9,5,6,1,2,3,10,4,7], A=14, K=13, Q=12, J=11, S={"S":1,"C":2,"H":4,"D":8}; for (i=0;i<5;i++) { d.push(b[i].split('')[1]); b[i] = b[i].split('')[0]; e.push(c[i].split('')[1]); c[i] = c[i].split('')[0]; } function p(w,m){ var v, i, o, s = 1<<w[0]|1<<w[1]|1<<w[2]|1<<w[3]|1<<w[4]; for (i=-1, v=o=0; i<5; i++, o=Math.pow(2,w[i]*4)) {v += o*((v/o&15)+1);} v = v % 15 - ((s/(s&-s) == 31) || (s == 0x403c) ? 3 : 1); v -= (m[0] == (m[1]|m[2]|m[3]|m[4])) * ((s == 0x7c00) ? -5 : 1); return r[v]; } alert(p(b,d)>p(c, e)?1:2); } ``` [source](http://www.codeproject.com/Articles/569271/A-Poker-hand-analyzer-in-JavaScript-using-bit-math) [Answer] **Python 3, 454 characters** ``` def z(v,u): v.sort();o,d,w=0,{2:0,3:0},[0]+v[:-1] if v[4]==13 and T(w):v=w t,f=T(v),len(set(u))==1 for p,c in set((p,v.count(p)) for p in v): if c==4:o+=2**77 d[c]=d.get(c,0)+1;o+=2**(c*14+p) if f+t:o+=2**(71+f*4+t*3) elif d[3]:o+=2**(73+3*d[2]) o+=2**(70+d[2]);return o i,c,T=input().split(),'-23456789TJQKA',lambda v:all(v[i]==v[0]+i for i in range(5)) v,u=[c.find(x[0]) for x in i],[x[1] for x in i] print(1+(z(v[:5],u[:5])<z(v[5:],u[5:]))) ``` Function z evaluates a hand to a single integer, which is effectively serving as an ordinal using Python's arbitrary precision integers. Its parameters, v and u, are lists of the values (2-14) and suits (single-char strings). The first two lines of z sort the cards, initialize relevant structures, and check if we have a low-ace straight. We then check for a straight or flush on the next line. The internal loop iterates the counts of different cards, solves the 4-of-a-kind case, tallies, and adds the appropriate ordinal. The last 3 lines of z solve the ordinals of all the other hand ranks -- flushes, straights, and straight-flushes, followed by 3-of-a-kind and full houses, followed by two pair, pair, and high card. In the main area, we parse the input, declare lambda v (which checks for straights), and the last line evaluate the hands and prints the result. [Answer] # perl, 801 733 chars I believe this is a pretty straight-forward implementation. Basically, for each hand, we sort the suits and the faces separately. Then we make another copy of the faces with aces counting low so we can check for straights with low aces. Then we determine if we have a flush or straight, and what the high card is. Then we just check for matches in order of score (first we check for straight flushes, then four of a kinds, etc.). The actual score is just the concatenation of the type of hand followed by the face values of the cards in the order they matter (that's \_s() in the ungolfed version, u() in the golfed version). Here it is: ``` @l{2..9,qw(T J Q K A)}=2..14;sub u{join"",map{$_>9?$_:"0$_"}shift,ref$_[0]?$$_[0]:map{$h[$_]}@_}sub e{$p[$_[0]-1]-1==$p[$_[0]]}sub f{@p=@_;e(1)&&e(2)&&e(3)&&e 4}sub h{$h[$_[0]]==$h[$_[1]]}sub i{h(@_[0,1])&&h @_[2,3]}sub t{@s=sort map{substr($_,1)}@_;$f=$s[0]eq$s[4];@l=@h=sort{$b<=>$a}map{$l{substr($_,0,1)}}@_;@l=(@l[1..4],1)while$l[0]==14;$s=0;if(f@l){$s=1;$h=$l[0]}else{$h=$h[0];$s=1 if f@h}$f&&$s?u 9,\$h:h(4,1)?u 7,4,0:h(3,0)?u 7,3,4:i(4,3,2,0)?u 6,0,4:i(4,2,1,0)?u 6,4,0:$f?u 5,0:$s?u 4,\$h:h(4,2)?u 3,4,0,1:h(3,1)?u 3,3,0,4:h(2,0)?u 3,2..4:i(4,3,2,1)?u 2,2,4,0:i(4,3,1,0)?u 2,1,4,2:i(3,2,1,0)?u 2,1,3,4:h(4,3)?u 1,4,0,1,2:h(3,2)?u 1,3,0,1,4:h(2,1)?u 1,2,0,3,4:h(1,0)?u 1,1..4:u 0,0..4}print t(@ARGV[0..4])gt t(@ARGV[5..9])?1:2 ``` And here's the less-golfed equivalent: ``` use strict; use warnings; # ace high or low in straights, otherwise high # T = ten, J = jack, Q = queen, K = king, A = ace # 0 high card # 1 one pair # 2 two pair # 3 3 of a kind # 4 straight # 5 flush # 6 full house # 7 four of a kind # 9 straight flush (royal flush a subclass of straight flush) my %l;@l{2..9,qw(T J Q K A)}=2..14; sub score { my @suits = sort map { substr($_,1) } @_; my @faces_h = sort { $b <=> $a } map { $l{substr($_,0,1)} } @_; my @faces_l = @faces_h; @faces_l = (@faces_l[1..4], 1) while $faces_l[0] eq 14; my $is_flush = $suits[0] eq $suits[4]; my ($is_straight, $high_card); if($faces_l[0]-1==$faces_l[1] && $faces_l[1]-1==$faces_l[2] && $faces_l[2]-1==$faces_l[3] && $faces_l[3]-1==$faces_l[4]) { $is_straight=1; $high_card = $faces_l[0]; } else { $high_card = $faces_h[0]; if($faces_h[0]-1==$faces_h[1] && $faces_h[1]-1==$faces_h[2] && $faces_h[2]-1==$faces_h[3] && $faces_h[3]-1==$faces_h[4]) { $is_straight=1; } } return _s(9, \$high_card) if $is_flush && $is_straight; return _s(7, 4,0) if $faces_h[4] == $faces_h[1]; return _s(7, 3,4) if $faces_h[3] == $faces_h[0]; return _s(6, 0,4) if $faces_h[4] == $faces_h[3] && $faces_h[2] == $faces_h[0]; return _s(6, 4,0) if $faces_h[4] == $faces_h[2] && $faces_h[1] == $faces_h[0]; return _s(5, 0) if $is_flush; return _s(4, \$high_card) if $is_straight; return _s(3, 4,0,1) if $faces_h[4] == $faces_h[2]; return _s(3, 3,0,4) if $faces_h[3] == $faces_h[1]; return _s(3, 2,3,4) if $faces_h[2] == $faces_h[0]; return _s(2, 2,4,0) if $faces_h[4] == $faces_h[3] && $faces_h[2] == $faces_h[1]; return _s(2, 1,4,2) if $faces_h[4] == $faces_h[3] && $faces_h[1] == $faces_h[0]; return _s(2, 1,3,4) if $faces_h[3] == $faces_h[2] && $faces_h[1] == $faces_h[0]; return _s(1, 4,0,1,2) if $faces_h[4] == $faces_h[3]; return _s(1, 3,0,1,4) if $faces_h[3] == $faces_h[2]; return _s(1, 2,0,3,4) if $faces_h[2] == $faces_h[1]; return _s(1, 1,2,3,4) if $faces_h[1] == $faces_h[0]; return _s(0, 0..4); } sub _s { join "", map { $_ > 9 ? $_ : "0$_" } shift, ref $_[0] ? $$_[0] : map { $faces_h[$_] } @_ # my @a=@_; # if(ref $a[1]) { # $a[1]=${$a[1]}; # } else { # $a[$_]=$faces_h[$a[$_]] for 1..$#a; # } # join "", map { $_ < 10 ? "0$_" : $_ } @a; } my @p1 = @ARGV[0..4]; my @p2 = @ARGV[5..9]; my $s1 = score(@p1); my $s2 = score(@p2); print $s1 gt $s2 ? 1 : 2; ``` ]
[Question] [ Welcome to the piNapple bar, Melbourne. All of the finest code golfers are here, with their laptops, sampling cocktails and programming increasingly badly. I feel a special need to reemphasise the last point. Increasingly badly. Alcohol can do funny things to programming logic. So - a few of the Golfers were attempting some nested quines in increasingly exotic languages. Somebody had hit the forth order in INTERCAL. Then the flow of alcohol stopped. He drunkedly, accidentally deleted the barcode reading algorithms from a completely different computer... that wasn't even connected to any network! (Kids - don't INTERCAL. For the sake of you. For the sake of your family.) Normally, this wouldn't be a big issue. But, some golfer had designed the system years ago, and none of the barcodes were standard. Assuming 1's are lines, and 0's are space, they all start with 101 and finish with 1001. Everything in the middle is 7-bit ASCII encoded. The barkeep does have a big fancy barcode reader that will return a string of arbitrary length (though less then 300 bits) of 1's and 0's, via STDIN, argument or file depending on your program. And it might come forward, or backwards depending on which way the bottle is being held. Your program must return the string from the middle of the barcode, via STOUT or file. Unfortunately, he didn't spend as much on his storage, so the program with the shortest source will be chosen, and win free drinks and drunken programming tutorials from the other golfers. Good luck! [Answer] ### GolfScript, 30 characters ``` .-1%]$1=3>7/);{{1&}%2base}%""+ ``` Input is provided on STDIN. [Example](http://golfscript.apphb.com/?c=OyIxMDExMDAwMDAxMTAwMDAxMDEwMDAwMTExMDAxIgoKLi0xJV0kMT0zPjcvKTt7ezEmfSUyYmFzZX0lIiIrCgpwcmludApuIHByaW50Cgo7IjEwMDExMTAwMDAxMDEwMDAwMTEwMDAwMDExMDEiCgouLTElXSQxPTM%2BNy8pO3t7MSZ9JTJiYXNlfSUiIisKCnByaW50Cg%3D%3D&run=true): ``` > 1011000001100001010000111001 ABC > 1001110000101000011000001101 ABC ``` [Answer] ## J - 35 bytes ``` _7(a.{~#.)\_4}.3}.|.^:([:-.2{])"."0 ``` Explanation coming later :). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 21 ``` smCid2c:?zv@z2_z3_4 7 ``` Explanation: ``` ?zv@z2_z Input if 3rd character of input is 1, else reversed input. : 3_4 Slice out the middle portion, ASCII of the above string. c 7 Chop into 7 character chunks. mCid2 Convert each chunk from binary to integer, then to a character. s Sum up the characters into a string and print. ``` Note that while the question is older than the language, the existence of the question did not influence the design of the language in any way, because I haven't seen the question before today. Still rules are rules, so I'm making it CW. [Answer] ## AWK, 116 bytes ``` /101$/{r=1}{L=split($0,a,"") n=r?L-2:3 N=r?-1:1 while(d<L-7){c=0 for(k=0;k<7;k++){c*=2;c+=a[n+=N];d++}printf"%c",c}} ``` I know this question hasn't seen a lot of love, but I was curious about seeing and `AWK` solution. This isn't all that clever, but it seems to work and I don't see any obvious areas to golf. I originally reversed the string when needed, but that added more bytes than just tweaking the increment logic to move backwards. ]
[Question] [ Given the Cartesian coordinates of three points on a plane, find the equation of the circle through them all. The three points will not be on a straight line. Each line of input to your program will contain the `x` and `y` coordinates of three points, in the order `A(x),A(y),B(x),B(y),C(x),C(y)`. These coordinates will be real numbers less than 1,000,000 separated from each other by space. The solution is to be printed as an equation of the form `(x-h)^2 + (y-k)^2 = r^2`. Values for `h`, `k`, `r` are to be printed with three digits after the decimal point. Plus and minus signs in the equations should be changed as needed to avoid multiple signs before a number. ``` Sample Inputs 7.0 -5.0 -1.0 1.0 0.0 -6.0 1.0 7.0 8.0 6.0 7.0 -2.0 Sample Outputs (x - 3.000)^2 + (y + 2.000)^2 = 5.000^2 (x - 3.921)^2 + (y - 2.447)^2 = 5.409^2 ``` [Answer] ## Python, 176 189 chars ``` import sys,re for s in sys.stdin:x,y,z=eval(re.sub(r'(\S+) (\S+)',r'\1+\2j,',s));w=z-x;w/=y-x;c=(x-y)*(w-abs(w)**2)/2j/w.imag-x;print'(x%+.3f)^2+(y%+.3f)^2=%.3f^2'%(c.real,c.imag,abs(c+x)) ``` Does all its work in the complex plane. I go the math from the bottom of [this page](http://www.math.okstate.edu/~wrightd/INDRA/MobiusonCircles/node4.html). `-c` is the center of the circle. [Answer] ### C# - 490 ``` using System;class C{static void Main(){Func<string,double>p=s=>double.Parse(s);Func<double,string>t=s=>(s<0?"+ ":"- ")+Math.Abs(s).ToString("F3");foreach(var l in System.IO.File.ReadAllLines("i")){var v=l.Split();double a=p(v[0]),b=p(v[1]),c=p(v[2]),d=p(v[3]),e=p(v[4]),f=p(v[5]),m=(d-b)/(c-a),n=(f-d)/(e-c),x=(m*n*(b-f)+n*(a+c)-m*(c+e))/(2*(n-m)),y=-(x-(a+c)/2)/m+(b+d)/2,r=Math.Sqrt((x-a)*(x-a)+(y-b)*(y-b));Console.WriteLine("(x "+t(x)+")^2+(y "+t(y)+")^2 = "+r.ToString("F3")+"^2");}}} ``` This finds the 2 lines between AB and BC. Then it finds where the bisects of those 2 lines intersect. (Which I just noticed is what @PeterTaylor mentioned in his comment to @PeterOfTheCorn.) [Answer] ## Ruby, 192 characters ``` $<.map{|l|a,b,c,d,e,f=l.split.map &:to_f n=(f-d)/(e-c) puts"(x%+.3f)^2+(y%+.3f)^2=%.3f^2"%[x=-(n*(a+c)+(n*(b-f)-(c+e))*m=(d-b)/(c-a))/2/n-=m,y=-(x+(a+c)/2)/m-(b+d)/2,((a+x)**2+(b+y)**2)**0.5]} ``` Usage examples: ``` $ echo "7.0 -5.0 -1.0 1.0 0.0 -6.0 1.0 7.0 8.0 6.0 7.0 -2.0" | ruby circle.rb (x-3.000)^2+(y+2.000)^2=5.000^2 (x-3.921)^2+(y-2.447)^2=5.409^2 ``` [Answer] ## Javascript (299) The only way that I could think of solving this was algebraically solving three equations for three unknowns to find h, k, and r. ``` p=prompt().split(' ');a=p[0],b=p[1],c=p[2],d=p[3],e=p[4],f=p[5];h=((a*a+b*b)*(f-d)+(c*c+d*d)*(b-f)+(e*e+f*f)*(d-b))/(a*(f-d)+c*(b-f)+e*(d-b))/2;k=((a*a+b*b)*(e-c)+(c*c+d*d)*(a-e)+(e*e+f*f)*(c-a))/(b*(e-c)+d*(a-e)+f*(c-a))/2;r=Math.sqrt((a-h)*(a-h)+(b-k)*(b-k));alert("(x-"+h+")²+(y-"+k+")²="+r+"²"); ``` Example I/O: `7.0 -5.0 -1.0 1.0 0.0 -6.0` --> `(x-3)²+(y--2)²=5²` `1.0 7.0 8.0 6.0 7.0 -2.0` --> `(x-3.9210526315789473)²+(y-2.4473684210526314)² =5.409159155551175²` The only bug that I see is that if h or k is negative, it outputs `--` instead of `+`. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/46/edit). Closed 10 months ago. [Improve this question](/posts/46/edit) From [AZSPCS](http://www.azspcs.net/Contest/Cards): *Suppose you have a deck containing n cards. Each card contains a number from 1 to n, and each number appears on exactly one card. You look at the number on the top card -- let's says it's k -- and then reverse the order of the top k cards. You continue this procedure -- reading the top number and then reversing the corresponding number of cards -- until the top card is 1.* Write the fastest program to compute the number of reversals for a given deck. Note that if you are participating in the contest you are not allowed to post your code (and thus I will not post my code yet). [Answer] ## JavaScript ``` function(d){for(t=0;x=(n=d[0])-1;t++)for(i=0;i<n/2;i++){m=d[x-i];d[x-i]=d[i];d[i]=m}return t} ``` You pass it the deck, like so: ``` f([3, 2, 1]) // 1 f([2, 3, 1]) // 2 f([1, 2, 3]) // 0 ``` [Answer] ### Scala: (This isn't a golf - is it?) ``` def transform (l: List[Int], sofar: Int = 0) : Int = if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1) ``` Complete application with testcase and stopwatch, including the shuffling of the Deck: ``` object DeckReverse extends Application { def transform (l: List[Int], sofar: Int = 0) : Int = if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1) def stopwatch (count: Int, size: Int) = { val li = (1 until size).toList val r = util.Random val start = System.currentTimeMillis () (0 until count).foreach (_ => transform (r.shuffle (li))) val stop = System.currentTimeMillis () println ("count: " + count + "\tsize: " + size + "\tduration: " + (stop - start) + " msecs") } stopwatch (1000, 100) } ``` count: 1000 size: 100 duration: 1614 msecs machine: Single Pentium M 2Ghz [Answer] # Python, 84 Chars Golfing anyway... I'm using the numbers 0 through n-1. Assuming the array is stored in a variable x, it takes me 84 chars of Python. ``` while x[0]:x[:x[0]+1]=x[x[0]::-1] ``` However, performance is pretty bad due to memory abuse. [Answer] ### C ``` int revno(int* deck, int n) { int k,j,r=0; for(;;) { k=*deck; if (k==1) { return r; } for (j=0; j<k/2; j++) { int tmp=deck[j]; deck[j]=deck[k-j]; deck[k-j]=tmp; } r++; } } ``` `deck` is a pointer to an integer array representing the decks. `n` is the number of the cards. Obviously memory safety is the task of the caller. It is probably nearing the fastest algorithm on recent computers and on a high-level language. Only with asm-level tricks could it be made faster, but not heavily even with them. [Answer] # [Perl 5](https://www.perl.org/), 58 + 2 (-ap) = 60 bytes ``` ++$\&&(@F[0..$F[0]-1]=reverse@F[0..$F[0]-1])while$F[0]-1}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/19bWyVGTU3DwS3aQE9PBUjG6hrG2hallqUWFaeiimqWZ2TmpEJ5tdX//xsrmCmYKhgqmCgY/csvKMnMzyv@r@trqmdgaPBfN7EAAA "Perl 5 – Try It Online") ]
[Question] [ Do randomly generated drum loops sound good? A **drum loop** is a \$5\times 32\$ matrix \$A\$ of \$1\$s and \$0\$s such that 1. \$A\_{1,1}=A\_{1,17}=A\_{2,9}=A\_{2,25}=1\$, 2. for each \$i\$, the \$i\$th row has exactly \$f(i)\$ different \$1\$s, where \$ f(1)=3, f(2)=2, f(3)=6, f(4)=8, f(5)=5\$, 3. for each \$j\equiv 1\bmod 4\$, the \$j\$th column has exactly one \$1\$, and 4. for each \$j\not\equiv 1\bmod 4\$, the \$j\$th column has at most one \$1\$. Here, the rows provide instructions for each of five drums, with each column representing a beat. In particular, the first row corresponds to a kick, while second row corresponds to a snare. Write the shortest code that draws a matrix uniformly from the set of drum loops. Feel free to use your code to draw a random drum loop, implement the drum loop on [this website](https://splice.com/sounds/beatmaker/f12e73c93b97), and then post a link to your creation in your post. (Note that we only use the first 5 rows of this online beat maker.) **Edit 1:** To be clear, we are using 1-based indexing: the row indices are \$\{1,\ldots,5\}\$ and the column indices are \$\{1,\ldots,32\}\$. **Edit 2:** Judging by the current submissions, the answer to my original question appears to be "yes": randomly generated drum loops *do* sound good. Here are links to the current examples: * [Random drum loop by @Arnauld](https://splice.com/sounds/beatmaker/ad842eea5cf7) * [Random drum loop by @tom](https://splice.com/sounds/beatmaker/b3054cbac7f1) * [Random drum loop by @KevinCruijssen](https://splice.com/sounds/beatmaker/96d2538ae65b) [Answer] # JavaScript (ES6), ~~194 193~~ 189 bytes Returns \$M^T\$. ``` _=>(g=n=>n?g(/1/.test(c=m[R()*32|0])?n:n-=c[h()]=1):m)(16,a=[1,,6,8,5],R=Math.random,h=_=>a[y=R()*5|0]?a[y]--&&y:h(),m=[...Array(32)].map((_,x)=>(c=[0,0,0,0,0],x&3?0:c[x&7?h():x/8&1]=1,c))) ``` [Try it online!](https://tio.run/##TY5Ba4NAEIXv/RVCwZ0p4xq1pkGYSH9AL7lul7BsjCboGjYSDPS/203JoczpzXvzzTubm7laf7pMiRsPzXLkZc9baNnx1tUtpFkqp@Y6geVB7QDfivxnpbF2lUvYqg5Qc4bVgJCtybDKiNa0oVLTjr/M1Elv3GEcqOOANerOD0YZEHUQOkni@F4FCA2spJSf3ps7FDlqOZgLwJ5mDG0sqxU9R9McF/WqsmqOP@pwWs3pJs5CC7KIuNjRXce@kf3Ygsjy4r0U@PJ/eQT8g/uIt5GX5/HkQAiUvrn0xjaQyrSl6PZwRfIq1E0jPlPfToQPvw "JavaScript (Node.js) – Try It Online") ## How? **Note**: *Columns* and *rows* in the following explanation refer to the matrix described in the challenge. They are stored the other way around in this implementation. ### Initialization We define an array \$a\$ holding the number of hits that need to be added to each row, ignoring the 4 fixed positions. ``` a = [ 1, , 6, 8, 5 ] ``` We define the helper function \$h\$ that picks a random row among those that are not completely filled, and updates \$a\$ accordingly. ``` h = _ => a[y = R() * 5 | 0] ? a[y]-- && y : h() ``` We define a matrix \$m\$ of \$32\times5\$ filled with \$0\$'s, except the columns such that \$x\equiv 0\pmod 4\$ (using 0-indexing) which are initialized according to the rules described in the challenge. ``` m = [...Array(32)] // set up 32 columns .map((_, x) => ( // for each column at position x: c = [0, 0, 0, 0, 0], // start with all values set to 0 x & 3 ? // if x mode 4 is not equal to 0: 0 // do nothing : // else: c[ // update c: x & 7 ? // if x mod 8 is not equal to 0: h() // use a random row : // else: x / 8 & 1 // fixed position: use either row 0 or 1, // depending on the parity of floor(x / 8) ] = 1, // set the hit c // yield the final column )) // end of map() ``` ### Main loop We randomly add the \$16\$ remaining hits on empty columns (which implies \$x\not\equiv 0\pmod 4\$) until all rows are filled. ``` ( g = n => // n = total number of hits to add n ? // if n is not equal to 0: g( // do a recursive call: /1/.test( // test whether c = m[R() * 32 | 0] // a randomly selected column c ) ? // contains any '1'; if it does: n // just pass n unchanged to try again : // else: n -= c[h()] = 1 // set the hit on this column, on a random row // and decrement n ) // end of recursive call : // else: m // we're done: return m[] )(16) // initial call to g with n = 16 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~413 394 389 379 378 360 342 327 307 299 298~~ 293 bytes ``` #define F;for(b[8]=b[v=24]=3,n=0;n #define B,b[n]== a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(&i)F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);} ``` [Try it online!](https://tio.run/##NY3BboMwDIbvfQpE1YmURCshqpBSXzhw2ht4OQQoVcrmTSlih2l79LGkG7/1S7bz@U8nLl23LNv@PDg6J40e3nzWYmWgxRmkMlBygoOmzYrUvEUyABuLBp7SQt1V/UtGpQEppeEeQwAnPvIrn0Ae@KxfraPMsc@bt9RnD441p1nv2/BbcTRQMI@U5wbosRTflDQnpS2OBixOhrXoQOXhfV/FzQj3DLabhDBCVYEujtrj1YDHOeKhX5k5MPEopv@xpdRhYO/e0TRk6a5f65nSOimSOimDVXAVLJn@Wpafbnixl9siPn4B "C (gcc) – Try It Online") ``` #define F;for(b[8]=b[v=24]=3,n=0;n #define B,b[n]== a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(time(0))F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);} ``` [try it online -earlier algorithm 307 bytes](https://tio.run/##PU/LboMwELznKxBRJAy2CsaKkMxeOHDqiau7B56Rk8atCKKHKP300gU1HWsszeysvduKU9suy77rB@t6r9TDxxg4iLXbPb1KN8Yi1OYCY@26gB0mIVCoTJO1@hPqR5knx/@OgjfGIcCuNgivfqI2ZH@QK3yKpBL5aKRC7viFn/kEMuYzSKWvtXWBZffb9uFkr30QM1bmsw4baExyREjYaFwUIbiXVHw7mjFDKtFrkHplrjS7W1BRFlKo0nStejTn5w4z7aBJI5kzVqHcMp@jddMQ@Ifued6cX3iJV3gpUREzomT6sSw/7fBen26L@PoF) Many thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for more byte savings (360 to 342 - then 342 to 328 and 327 to 307 - then modified algorithm from 328 to 299 and 298 to 293). Compiles ok without `#include<stdio.h>` using the `-w` compiler flag, thanks to @Arnaud for pointing this out. As written it generates a fresh sequence each time. If we are allowed manual intervention of a new number in `srand` to generate a different drum sequence with say `srand(6);` then we can save 16 bytes. Thanks to @Arnaud who made asked the question about generating the transpose matrix, which is what this program does. Thanks also for suggesting the change from `int` to `char` for `a[20]` that saves 15 bytes. Also thanks for @Post Rock Garf Hunter who figured out a way to remove white space near the `B`s and then saved more bytes fixing up the #defines so that `F` is included in `R`. `#define' tokens often seem to need whitespace so they are cleanly identified. This code works on `tio.run`, but elsewhere may need to include `time.h`. # How the program works logic: * **setup** * 4 sounds are fixed (at 1,9,17,25) * remaining sounds to be distributed randomly are in `a[20]` * `b[32]` holds output - one cell for each beat (1 to 32, but in C of course 0 to 31) * 4 of the `b` cells must have something (at 5,13,21,29) * remaining sounds randomly scattered to empty cells * `r[24]` holds list of empty cells (2,3,4, 6,7,8 etc. in C 0,1,2, 4,5,6 etc.) * **execute** * put in 4 fixed sounds * choose random sound from `a` to put in each of 4 cells with sounds * choose random cell from `r` to put in random sound from remaining `a` sounds (simplification to algorithm is possible here by putting remaining sounds one by one from 1 to 16 (or 0 to 15) in a random cell, but this gave more bytes..., but now thanks to @ceilingcat this is now smaller see [tio.run link](https://tio.run/##NY1NboMwEIX3OQWiioSDrYKxIiRnNixY9QZTL8xf5JBMKwfRRdUevdSk5Y2eNDP@5rkV57ZdlqeuHxz1Ua2HN580WBpocAapDBScINO025CKN0gGYGfRwEucq4fKf8lVcUAKabjHEMCJj/zCJ5AZn/XNOkoc@7x7S10yuVufZIzVp1kfmvBlfjSQM4@UpgbouRDfFNUnpS2OBixOhjXoQKXh/VCumxEeQWw/CWGEKgOdH7XHiwGP84qHfmPmwKxHa/ofW0gdBvbuHU1DEu@7rV4prqI8qqIiWAWXwZLpr2X5aYerPd8X8fEL) for details) * print result this is a long version of the code without the `#define` and other space savers to show the logic, but with small differences e.g. in final version `a` is `char *` not `int *` ``` #include<stdio.h> #include<stdlib.h> int main() { int a[20]={1,4,4,4,4,4,4,8,8,8,8,8,8,8,8,2,2,2,2,2}, b[32]={},r[24],n,k,j,t=20,v=24; time_t q;srand(time(&q)); //random initialization for(n=0;n<24;n++n=0;n<v;n++)r[n]=n+n/3+1; // set up r with list of cells that don't definitely have sound 012,456 etc. b[0]=b[16]=1;b[8]=b[24]=16; //put in fixed sounds for (n=0;n<4;n++) {k=rand()%t--;b[4+n*8]=a[k];a[k]=a[t];} //choose a random sound from a to put in each of 4 cells that must have sound // each sound selected is then replaced by the sound at the end of the list // and the length of the list is reduced by one for (n=0;n<16;n++) {k=rand()%t--;j=rand()%v--;b[r[j]]=a[k];a[k]=a[t];r[j]=r[v];} // random cell from remaining `r` cells and random sound are selected // again after selection from list final item replaces selected and length // reduced by one for (n=0;n<32;n++) {printf("%d%d%d%d%d\n",(b[n]==1),(b[n]==16),(b[n]==4),(b[n]==8),(b[n]==2));} // print out 0 and 1 from logical tests to print transpose matrix return 0; } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 65 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 31Ý©8ˆ24ˆ40¯ǝ0ˆ16ˆ®¯KΩˆ48¯¦¦ǝ•Wk¤]•3ôεćи}˜.ržw8и«®¯K.r.¡4Ö}é˜ǝb€¦ ``` Outputs as a transposed list of strings. [Try it online.](https://tio.run/##yy9OTMpM/f/f2PDw3EMrLU63GZmcbjMxOLT@@FyD022GZqfbDq07tN773EqgqMWh9YeWHVp2fO6jhkXh2YeWxAJp48Nbzm090n5hR@3pOXpFR/eVW1zYcWg1WI9ekd6hhSaHp9UeXnl6zvG5SY@a1hxa9h9IBh/e4XVo938A) (The footer pretty-prints this as the intended rows/columns. Feel free to remove the footer to see the actual result.) **Explanation:** ``` 31Ý # Push a list in the range [0,31] © # Store it in variable `®` (without popping) 8ˆ # Add 8 to the global array 24ˆ # Add 24 to the global array as well 40¯ǝ # Replace the values at the indices of the global array with 40 0ˆ # Add 0 to the global array 16ˆ # Add 16 to the global array as well ® # Push the [0,31] list from variable `®` again ¯K # Remove all values of the global array (the [0,8,16,24]) Ω # Pop and push a random index from this list ˆ # Add it to the global array as well ¯¦¦ # Push the global array with the first two (8,24) removed 48 ǝ # Replace the values at the remaining three indices with 48 •Wk¤]• # Push compressed integer 533636834 3ô # Split it into parts of size 3: [533,636,834] ε # Map over each integer ć # Extract head; pop and push remainder and head и # Repeat the remainder the head amount of times # i.e. 533 becomes [33,33,33,33,33] }˜ # After the map: flatten the list of list of integers .r # And randomly shuffle it žw8и # Then push a list of 8 32s « # And merge it to the end of the list ® # Push the [0,31] list from variable `®` again ¯K # Remove all indices stored in the global array # (the [0,8,16,24] and one random index) .r # Randomly shuffle these remaining indices .¡ # Group the remaining indices by: 4Ö # Where this (0-based) index is divisible by 4 # (which would be i % 4 == 1 for the corresponding 1-based index) }é # After the group by, sort the two inner lists by length, # so the indices divisible by 4 are before the other indices ˜ # And flatten it to a single list ǝ # Then insert the shuffled integers at those shuffled indices b # Convert each integer to a binary string # (32=100000;33=100001;34=100010;36=100100;40=101000;48=110000) €¦ # And then remove the leading "1" from each # (after which the resulting list is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Wk¤]•` is `533636834`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes ``` 32s8Zs4ZḢ;FẊḣ⁴ƲƊḢŒœ;FẊ$ƲFṙ-“¥©€Þı‘œṖ;¹Ṭz0ZṖ ``` [Try it online!](https://tio.run/##y0rNyan8/9/YqNgiqtgk6uGORdZuD3d1Pdyx@FHjlmObjgFZi45OOjoZLKpybJPbw50zdR81zDm09NDKR01rDs87svFRw4yjkx/unGZ9aOfDnWuqDKKA7P@HFkUCDX24cy1cCAA "Jelly – Try It Online") A niladic link that returns a 32x5 matrix of 1s and 0s representing the drum loop. The footer simply prints it concatenated and separated by newlines. ## Explanation ``` 32 | 32 s8 | Split into groups of 8 Z | Transpose s4 | Split into groups of 4 Z | Transpose Ɗ | Following as a monad: Ḣ | - Head ; Ʋ | - Concatenate to following as a monad: F | - Flatten Ẋ | - Shuffle list ḣ⁴ | - First 16 Ʋ | Following as a monad: Ḣ | - Head Œœ | - Odd/even indexed items ; $ | - Concatenate to: F | - Remainder of list flattened Ẋ | - Shuffled F | Flatten ṙ- | Rotate right 1 item “¥©€Þı‘œṖ | Split list before positions 4, 6, 12, 20, 25 ;¹ | Concatenate to 32 (because 32 was the beginning of this niladic link) Ṭ | Convert from lists of numeric indices to logical lists with 1s at those positions z0 | Transpose with 0 as filler Z | Transpose Ṗ | Remove last (the sixth list introduced with the 32 above) ``` [Answer] # [Python 3](https://docs.python.org/3/), 180 bytes ``` from random import* r=range s=sample a=s(s([x for x in r(32)if x%4],16)+[x*8+4 for x in r(4)],20) print([[i in t for i in r(32)]for t in[[0,16,a[0]],[8,24],a[1:7],a[7:15],a[15:]]]) ``` [Try it online!](https://tio.run/##TYy9CsMgFEZ3n8KloIlDfpsQyJNc7iA0aYVG5epgn96aDKXTx/k4HP@JL2f7nHdyBydtH2XM4R3FitFajufGwhr04d8b02sQQUDiuyOeuLGcRN9Js/N0G1C1d1lDquZ6@BcGiaprJPNkbBQA5rzjZZhfAk@MBQGa0lEaGkQFs@pKV0O7TOdMSzteOC6IKHP@Ag "Python 3 – Try It Online") Prints a logical matrix representing the drum loop. [Answer] # [R](https://www.r-project.org/), 138 bytes ``` s=sample y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16))) z=matrix(0,5,32) z[1,c(1,17,y[1])]=z[2,c(9,25)]=z[3,y[2:7]]=z[4,y[8:15]]=z[5,y[16:20]]=1 ``` [Try it online!](https://tio.run/##HYtBCsMgEEX3nmSmmYKjMaYDnkRchNBFoYESu2i8vJ1k997j/733muqyfd5Pc6QKK8w3K34IVAFYvMN8h1FTHBgL8YSIpqVt@e6vH1gKpBPTMtMKTBzpyFywpJadlge5cInX7iSWk0flWThcEs7DJM6qce9/ "R – Try It Online") A full program that implicitly prints the drum loop as a matrix of 1s and 0s. # Alternative using a third party package: ## [R](https://www.r-project.org/) + DescTools, 130 bytes ``` s=sample y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16))) sapply(list(c(1,17,y[1]),c(9,25),y[2:7],y[8:15],y[16:20]),DescTools::Unwhich,32) ``` [RDRR it!](https://rdrr.io/snippets/embed/?code=s%3Dsample%0Ay%3Ds(c(8*0%3A3%2B5%2Cs((1%3A32)%5B-(4*0%3A7%2B1)%5D%2C16)))%0Asapply(list(c(1%2C17%2Cy%5B1%5D)%2Cc(9%2C25)%2Cy%5B2%3A7%5D%2Cy%5B8%3A15%5D%2Cy%5B16%3A20%5D)%2CDescTools%3A%3AUnwhich%2C32)) A full program that implicitly prints a logical matrix (in the transposed form). [Answer] # [Python 3](https://docs.python.org/3/), ~~400~~ \$\cdots\$ ~~361~~ 338 bytes ``` from random import* r=randrange p=65537 def h(b=p): while b==p:b=p|1<<r(32) l=[b,16777472] for i in[6,8,5]: while bin(b).count('1')!=i:b=sum(1<<r(32)for j in[1]*i) l+=[b] return l g=1 while g: l,g=h(),0 for i in range(32): b=sum(j&1<<i!=0for j in l) if i%4:g|=b>1 else:g|=b!=1 for i in l:print(f"{bin(i)[2:]:>032}"[::-1]) ``` [Try it online!](https://tio.run/##Rc9Ra4MwEAfw93yKs7A16dwwWnWEpl9EfJht1JQYQ6qMse6zu0uL20MId3C//537mvrRZsvS@nEA/2HP@OnBjX7aES9DA1@niJNFnmclOasWetpIxwQQ@Oy1UdBI6QS2bvxw8DRLGQEjqybmRVmW@zKtCbSjBw3aVkX8Hue1ILDOaksb9nYaZzvRLd@ySGq0rvNAVy3MXsIsr3cabTAvqCPq1TR7C4Z0kpMH16Fs4k72lMXJfyzcjwhYSH7wl2cM0JFMVh9MwHUL@mkvuptsjhxrZa7qXkUY8ucZ4bzGjdvNd7hAsyoVtTgmWfqzqYR45TVbll8 "Python 3 – Try It Online") Full program outputs a \$5\times32\$ matrix of \$1\$s and \$0\$s. Bit slow at times (\$\sim15\$ seconds), but you can't rush the creative process! :P ]