text
stringlengths
180
608k
[Question] [ # Challenge Create a function takes in two 2-dimensional arrays of characters (or strings if the programming language does not have characters as a datatype) as inputs: a and b. If your language does not support these inputs, you may use any other standard one-byte variable. Your task is to determine if b contains a. If this is so, return true. Otherwise, return false. # Sample Test Cases ``` a: 123 456 789 b: 123 456 789 ``` should return true. ``` a: code golf b: thisis code!! golf!! ohyeah ``` should return true. ``` a: abcd efgh ijkl b: abcdef ghijkl mnopqr ``` should return false. ``` a: abc def b: 1abc2 3def4 5ghi6 ``` should return true ``` a: ab cd b: #ab## ##cd# ``` should return false This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so least bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 4 bytes ``` s\s\ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzimOOb//@hopRIlHaUMIM4E4mI4HasTrZQMZOUDcQoQpwKxIhiDZNKhMjlAnIYikw81rRKqJxHMjwVZhGocpjGxsQA "Brachylog – Try It Online") Most easily run as a full program, as usual for a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"), with *a* specified as a command-line argument, *b* on standard input. The question asks for a function, and the program also works as a function, with *b* on the left, *a* on the right, and output via [producing an exception if and only if the decision is false](https://codegolf.meta.stackexchange.com/a/11908/76359). ## Explanation ``` s\s\ s a substring of rows of {the left input} \…\ assert rectangular; swap row and column operations s a substring of <s>rows</s> columns of {the above matrix} {implicit} assert that the result can be {the right input} ``` The "assert rectangular" is, obviously, pointless, as the question guarantees that already. The rest of the program does the grid-finding for us by identifying a substring of the rows and of the columns, i.e. a submatrix. ## Meta-discussion We've had a [very similar question](https://codegolf.stackexchange.com/a/178188) before; I'd expect most answers to one question to be modifiable into answers to the other. I think this is the neater version of it, though. [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes ``` f=lambda a,b,r=4:b*r and f(a,b[1:],r)|f(a,zip(*b)[::-1],r-1)or a==b ``` [Try it online!](https://tio.run/##ZZDBboQgEIbP@hQsJ9mwyarYbk14EuIBVlhoVVilh2367nbQNtmkF5j/m3/yZyY8ovVTta6GD3JUvUSSKjpz1qrjjOTUI1MAEWXb0Zl8J/HlQnFURLTtqQR4KokHJ@dqjXqJC@JIZELgq@81pvjmB4M7KnC0bnELkNQ4HH5bW@HtQ0uLu47mWRotqxooa17gfb28beP/2J9ZqmsPTJubhc@9fwzgRzvXJsXYDVI8Tj7c5@cYgDXb7TU7n2uIQIDLirFUAWFNAwOoy3MDW6ZTEOQmtG3a5pnkowxF/AyDppLkmXrSCnSY3RT3E5L1Bw "Python 2 – Try It Online") Takes input as lists of tuples of characters. Tries all sub-grids of `b` and checks if `a` is among them. The sub-grids are generated by recursively branching on either removing the first row of `b` or rotating it 90 degrees. After exactly four rotations, checks if the trimmed down `b` is equal to `a`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ⌈⭆η⭆ι⁼θE✂ηκ⁺Lθκ¹✂νμ⁺L§θ⁰μ¹ ``` [Try it online!](https://tio.run/##VYw9C8IwFEV3f8VrphQi6Ozk4CBYKHQMHUIam2A@TJNK/fUxsQXxwYV7D4fHJZu4YzqldlI24oYtyswGdzHPsWFPLAn8hiJw8TPTAXsCBXRacVGcB4FWzwHfhB2jxL7OKOeYszqWgPl3zvFqB7GUV4c6e@brr3dKiVLE3SAQ2QGg0ek76nOlKEoVVFhxVYxq68XZupNvwSTq@7R/6Q8 "Charcoal – Try It Online") Link is to verbose version of code. Heavily based on my answer to [Count the contiguous submatrices](https://codegolf.stackexchange.com/questions/178173/), the only difference being that instead of taking the sum of the matches I take the maximum, and because of the implicit string conversion due to the use of `⭆` the result is already a string which saves a byte. [Answer] # [J](http://jsoftware.com/), ~~21~~ ~~15~~ ~~8~~ 7 bytes ``` 1#.,@E. ``` [Try it online!](https://tio.run/##XYyxDoIwFEX3fsVFDZWIT7HGAQMhMTo5uToVbC2KVsXF8PEIkhjjcN9wz33nVPeIa0QhOHxMETYZE1a77aYO@uQna6o99sxkqSLCPoTKjEVFzThwq@bGSRViCe3Gk2Q4cyvyGJMRBaOcBET3Cdks2gQfNsMcA/DMHtTRFpqzNKI5Fm33NHmZly1xnJY5jjUvJQ3/EaVfkehEMs0OSh9NfjoXH5noZL/95Wpv98e/ZspY/QY "J – Try It Online") *-7 bytes thanks to Bolce Bussiere* ## original answer ## [J](http://jsoftware.com/), ~~21~~ 15 bytes ``` <@[e.&,$@[<;.3] ``` [Try it online!](https://tio.run/##XYy7DoJAFET7/YrBGFYjXoU1FgiGxMTKypZYLLCw@FoVG8PHI0hijMXcYs6dc2wGxHOEPjgczOG3mRI2@922CaJYke0MozhYkTg0Y/ZMZaVCQuxDpdqgpnbk2nV711HtY4XcXs@ikWfXNGZMhuROShIQ/RKy/ejifpiHBYbgqclUYc45Z0lICyy77qnLqqw6YlkdsyyjX0pq/iNKviLRi2SSZiovdHk8nT8y0ct@@8vV3O6Pf82cseYN "J – Try It Online") *-6 bytes thanks to FrownyFrog* ## how * `<@[` boxed left arg * `$@[<;.3]` all rectangles in the right arg with the same shape as the left arg * now pass those as the left and right arg to... * is the left arg an elm of the right arg, after flattening both `e.&,` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øŒεøŒI.å}à ``` Takes `b` as first input, `a` as second. Both inputs as character-matrices. Port of [*@Mr.Xcoder*'s 05AB1E answer for this related challenge](https://codegolf.stackexchange.com/a/178180/52210), so make sure to upvote him! [Try it online](https://tio.run/##yy9OTMpM/f//8I6jk85tBZGeeoeX1h5e8P9/dLRSiZKOUgYQZwJxMZyO1YlWSgay8oE4BYhTgVgRjEEy6VCZHCBOQ5HJh5pWCdWTCObHxnJFo5uHaU5sLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/spuSZV1BaUmyloGTv6WKvpJCYlwJmhuoo@ZeWAKVAMv8P7zg66dxWEBmhd2hR7eEF/3UObbP/Hx2tVKKko5QBxJlAXAynY3WilZKBrHwgTgHiVCBWBGOQTDpUJgeI01Bk8qGmVUL1JIL5sbFc0ejmYZoDUWUIZBsBsTFYhQmQZQrEZmCeOZBlAcSWZKgFuSQJiJPBLgCpSIW6Ph3iRqAIyO9ZQJwNdhM2fTpQXTDXw0IOSRdQJhfIyoP6rQCIC4G4CGgeAA). **Explanation:** ``` øŒ # Get the sublists of every column of the (implicit) input `b` ε # Map each list of sublists to: øŒ # Get the sublists of every column again # (now we have all sub-matrices of `b`) I.å # Check if the second input `a` is in this list of sub-matrices }à # After the map: check if any are truthy by taking the maximum # (which is output implicitly as result) ``` [Answer] ## [JavaScript (ES6)](https://developer.mozilla.org/en-US/docs/Web/JavaScript), ~~131 112~~ 105 bytes **105 bytes:** ``` f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&x.some((c,j)=>n.every((l,z)=>(m[i+z]+'').indexOf(l,j)==2*j))) ``` [Try it online!](https://tio.run/##fZDvaoMwFMW/@xR@WpI1FWZbGHTuFfoAIiOzUePyp6iI7cu743R1HWLgQO753Zt7b0rRijqt1KXZtq99n0XUcMuidxPUzkhKO64QqbfIBFravCm2dro8dVNKykuk2EC2srpSqvkNITWx2tySDSEsUPYsu1MGgsQofC4ZY30rKl/oSyH8yI9jIggnn1AKnSFJEu75f09MMvg5VEAKKhdyvuBryEAWciRJjp43dGtk3Xy8/LYb7Lsbju48wAPdjXR5LPRcngVgHuD@1v7/ugtl844PpYextBi7DVulztZOy0C7nGb05zf5tCZjxxUcruPdOt6v4wNw/w0 "JavaScript (V8) – Try It Online") Changes: * `m[i]` into `x` and `n[z]` into `l`: *Totally forgot that these variables were already instanciated* * `&&` into `&`: *Both sides of the operator are already booleans so a bitwise operator will work* --- **112 bytes:** ``` f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&&m[i].some((c,j)=>n.every((l,z)=>(m[i+z]+'').indexOf(n[z],j)==2*j))) ``` [Try it online!](https://tio.run/##fZDvaoMwFMW/@xR@apI1Dcy2UOiyV9gDhDAyGzUuf4qKdL68u05X1yEKPzDnnJt7b0rVqjqtzLXZtae@zzh21BP@6lgdnMb4Rg2czAt3zGqfN8XOTz@bjRNGTrGUlhDzTLe6@sLY0g6OGALbTm4RIsz4i769ZdiLTg5ZnjyVhJC@VVWs7LVQMY@FQApR9AGkwAXQSNIo/vsJlIGeAwVggHIh8wm6BRzggYCkPEfR0K3RdfP@/NtukO9qMqrzAA/ufnSXx4Key7OAMQ9wv@vwf92FsnnHh9LjWFqM3Yat0uDrYDWzIccZ/nlNOq1JyHnFTtbt/bp9WLePYPff "JavaScript (V8) – Try It Online") Changes: * `map((c,j)=>{...}).some(s=>s)` into `some((c,j)=>{...})`: *Redundancy* * `m[i+z].join()` into `m[i+z]+''`: *A shorter way to convert the array into a string* * `indexOf(n[z].join(),j)` into `indexOf(n[z],j)`: *The* `indexOf` *method already converts* `n[z]` *into a string* --- **131 bytes:** ``` f=(m,n)=>m.some((x,i)=>i<=m.length-n.length&&m[i].map((c,j)=>n.every((l,z)=>m[i+z].join().indexOf(n[z].join(),j)==2*j)).some(s=>s)) ``` [Try it online!](https://tio.run/##fZDvaoMwFMW/@xR@apItDcy2UOjSV9gDBBmZjRqXP2JEur68u85O1yEGfpCck5tzbyrZyZA1um633bHvc44tdYSfLQveKoyvVMNJv3LLjHJFW27dfbPZWKFTZmWNcUYruOWY6lTzhbGht@EJoZ9vKau8dpgw7S7q@pZjJyZtKOLJU0XIGBb4ORDSd7KJpalLGfNYCCQRRR9ABlwAhVIaxX@XQDnoBVACGqgW7nyCbgALOMCjND1F0ZDWqtC@v/zGDfKkJqM6N/Dg7kZ3uS3IXO4FjLmB6a39/3EXyuYZH0oPY2k5pg1TZd4FbxQzvsA5/vlNeh@TkNOKnazbu3V7v24fwO6/AQ "JavaScript (V8) – Try It Online") Readable: ``` function f (m, n) { return m.some((x, i) => { return i <= m.length - n.length && m[i].map((c, j) => { return n.every((l, z) => { return m[i + z].join().indexOf(n[z].join(), j) == 2 * j }) }) .some(s => s) }) } ``` Instead of compairing individual values, I checked if the lines from grid N were included in the lines of grid M, and if so, at which indexes. If all of the lines are included starting from the same index then the grid N is contained in the grid M. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` 1∊⍷ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BRR9ej3u3/0x61TXjU2/eob6qn/6Ou5kPrjR@1TQTygoOcgWSIh2fwfw1jBeNHvVsMFYwUjBVMFEwVzBTMFSwULDUV0hRwyykoPOqdq1BSVJrKpWGkYAJUpJ6cn5Kanp@Tpg7WaaJgBhIsycgsziwGSSkqgiQVFfMzKlMTM4CKEAYYQwxITEpOSU1Lz8jMys5Rh1pvhi6Rm5dfUFikDnNBWmJOMdgJxgiFML2mICFDoJiRMVDUxBRogBlYIxwg@8EIZgBEuxFEu3JikjIQJKcoo@pEMgDsBAA "APL (Dyalog Unicode) – Try It Online") It's like this question was made for APL! ## Explanation ``` ⍷ ⍝ 'find', returns a matrix with '1' in all positions where the first matrix is contained in the second 1∊ ⍝ checks if '1' is a member of this matrix ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~46~~ 37 bytes ``` Partition[#2,Dimensions@#,1]~FreeQ~#& ``` [Try it online!](https://tio.run/##hY@9DoIwFIV3ngLbxOku@O9gwmCcdSYMFYtUBRS6mAZfHS/1gmhMHL60p73n9DQVOpGp0CoSdbyqt6LQSqs8C/gI1iqVWYmi9Dl44WNTSLl78GG9LVSmgzjgPAyHvu87xnGNMR6MYFyB47qumcAUZrSfwwKWlRV/hxqFUSxiwHLkgEhGM@xIpxckZm0k0ygTRCFlt7amzyhgA8vvyO/bnJLv5BVWv2s2eo9ENr91Sco6vqbptGl1Qs72ta78ZwSQuV@v/VrPTLcpqow@cEVuSNHUc6r6CQ "Wolfram Language (Mathematica) – Try It Online") Returns `True` if b does *not* contain a, and `False` if it does. [Answer] # [Python 2](https://docs.python.org/2/), ~~106~~ ~~118~~ 113 bytes ``` lambda a,b,L=len:any(sum(A==B[j:j+L(A)]for A,B in zip(a,b[i:]))==L(a)for i in range(L(b))for j in range(L(b[0]))) ``` [Try it online!](https://tio.run/##ZZDNboQgFIXX@hQMK0hZOIr9MWHhrH0D6gJnQLEKVu3Cvry9OG3Sphu4@c45Obl32tbOu3Q34nUf1NjcFFKsYZUYtCuU28jyMZJSiIvsi/6hIiWtjZ9RyS7IOvRpJwJ2aYuaUiEqomhQbdBm5VpNKtLQg/V/mEwgQPdVL@uCBJKRlPjqbxoz3PrB4JpJvHZ2sQuQIJxO39Ix@G7TqsN1zeIoRM9pBpTnj/A@Pb8c8X/sx6ya6w2YNm0Hn@3fBvCjO9cm1HQHZHh0fnqff9cAzPjdnvEkyaACAT6nnIcJCM9zCKA6jsPW4To0bH5sWsTRNFu3InPw/Qs "Python 2 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~71~~ ~~102~~ ~~85~~ 98 bytes thanks @Jo King; test cases added. ``` param($a,$b)!!($a|%{$p=[regex]::Escape($_) $b|sls $p -a -ca|% m*}|group index|?{"$a"-ceq$_.Group}) ``` [Try it online!](https://tio.run/##rZVtb4IwEMff8ymqdAMWNPPZmZi5F8ve7Qssi6lwCBsKUs1YxM/urmh1U4yMQNLQ3v3vftwl9MLgCyLugu9vqUOGZL0NWcRmOmUmnRiVCm6SmzUNh28RTCF@HwyeucVC0OnYUOgk4T4nNCQ1RmoWKsnsbpNMo2AVEm9uQ5w8rquUVWsWLOi4/iIcG2O7UZSRriimrhB8NItxIA3NJHQZrcBMjaO9r9FsaTuL1u505bbXf9DSnWHmUBqKcQJrZsOswAYZOA1854yxdD3ucSkR8krld8DxFLjfwNwMdEugHebzEzabWLYMBmfqyr338emffYcQg3Mgu6lof5rNg3ARZZDb2UVjLhkqcp61Ff1NKWihoi0PHeR2szj1@@IkXL0/NFz968RGcWIcx0WIzWJEpBWtsVViV/EzchDbJRGRlrPGTiHiLp95FZ9F7F7@H/9XJB5ytrVXUlsFMU9bOxdLPNxk9hlOZRNVlX5VtWw1I/PF5tVLvlN6F0BPJVxeBknIDVmndipor2wGiIM4BGsJtiDjMMOXN8cJScc7ZQR85S/RcIuDM1UIQeqrUn3vTgefTGQMZJR5BFWVzfYH "PowerShell – Try It Online") Less golfed: ``` param($a,$b) $matches = $a|%{ $pattern = [regex]::Escape($_) $b|Select-String $pattern -AllMatches -CaseSensitive|% Matches } $relevantGroupsByMatchPosition = $matches|group index|?{ "$a"-ceq$_.Group # the '$_.Group' contains matches in source order # -ceq is case sensitivity equation operator # -ceq performs an implicit conversion to the left operand type } !!($relevantGroupsByMatchPosition) # true if the variable is not $null ``` [Answer] ## Javascript, 150 bytes ``` f=(a,b)=>{_='length';for(r=i=0;i<=b[_]-a[_];i++)for(j=0;j<=b[0][_]-a[0][_];j++){u=0;a.map((l,y)=>l.map((c,x)=>u=u||b[i+y][j+x]!=c));r=r||!u;}return r} ``` [Try it online](https://tio.run/##dZDRasMgFIbv8xTmSkNs6eXAnUH7GiLFuCQ12FhMDA1Nnz3TOUJhmxefHr/Df8ROTnJQTt/G3fS2rg0QSasCPh5nwKbu2/GCWWMdcaDhwPQ7VPwsdjKA6bIsouqC6KI4iOS@d9YF/fDByf1V3ggxdA65JhWK3kPhwS9LxXU5C96Vd5GDKgrmwC1L7tnT1aN3PXLPdZIOHREgnqGwOFaYImwjPiNqLOiPaTdjIhosMsGyLAacXgLGKC8ROmJ4OW1Rv4YE5An/j/ujx26z5i1Hprv0OGX7wZp6b2xLGnKk6BR@Yf0C) [Answer] # [JavaScript (V8)](https://v8.dev/), 81 bytes ``` (m,n)=>m[s='some']((a,i)=>a[s]((b,j)=>!n[s]((c,k)=>c[s]((d,l)=>m[i+k][j+l]!=d)))) ``` [Try it online!](https://tio.run/##fZBtC4IwFIW/@yvs0yatoDcIYv2RMWJOzZfpwol/345aWSEOHrg7x7tzr7lqldN19mg27blLeEdLVgX8WgrHibNlTCSlimWQlHCoQ5ajXlXDRbMCFz3UETNDX7YupMjXRq54FOB0rap9ZR6p8rkvBFGEkRBoEAEkMM//PoIk0O8gBRnIZ74poBtQggpYIuXF8/q0JnbNbfeO6@WPuh/VaYAf9zC682Mhc34WGNMAn7eO/@vOtE07/rSextZ0TOu30rZy1sRbY@80ocPfZK81g@CyYO@X7cOyfVy2T7C7Jw "JavaScript (V8) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/)/[Matlab](https://www.mathworks.com/products/matlab.html), ~~47~~ ~~45~~ ~~44~~ 40/38 bytes * -2 Default output to `ans` * -1 Trace of inner product is the sum of the squares of the elements. Therefore use `trace(a*a')` instead of `sum(a(:).^2)` * -4 Use `find` instead of `any(any(...))` since any non-zero output of `find` is considered as a logical truth, and Matlab/Octave is 1-indexed. * -2 but only in Matlab, since the second argument to `xcorr2` does not need to be made numeric and is implicitly converted to whatever is the first argument's type. ## Octave ``` @(a,b)find(xcorr2(a*1,b*1)==trace(a*a')) ``` [Try it online!](https://tio.run/##dVNNb9swDL3nVzCHwFKrFP7ALkkNtMA2YPYGFEtvaQ6yLSNqUsmQlM3Yn88o2UnabjVgmZb4HslHSteO/xLH4x3hrKKtVA3pa21MSvhVwqqrhOa5M7wW@M8jSo@mgxzuiKVQb7khhqtGknWWQZKmG2YpXcIMfnBnZA@6BX@uX6AzUjle7UVA8doJYycFMmVLKPGTxB62kn@E9SgOCIPqBg1pIeszBpW3krhP4kmrDUgPWqQxonAZozhhnZ0APm0I2JIoz3N4/LJ6hFkDaD@piEkaXMLCkcZ0pMCsq8EsxwJ24sQ6JhP8B9QMHjw9uK2AF19qLd6FHQXgQGZx2vR@oQuIWMGKIbqv4TlPFgU7Y2YWHTh5ZgtKmVDNW8YnNXJWyImMA1/JygvfDvnKd3wV2X3EF73WQSpff8v3VizDjhx6dxvffMJ6P4taNgJ@bwXWbMBp6A7Od0ehOUqDj5@NYSLKecHWCUs3dHk@rcg6XqSb644klJ3MlFIE8YvXmIozB3HZPKcdBkIqPw4KOm2lk1p5RRgq4rvbjQEFVvIBXGkXKLwEo/Oozqm9Pw8qNLc9qNoHCNtG2MPe@WSVDbflLFSv8SKEU@azp//GnU6n8PX@23dA41XY/@Y4n8/h4X61AjTepojv8fgX "Octave – Try It Online") ## Matlab ``` @(a,b)find(xcorr2(a*1,b)==trace(a*a')) ``` This works by computing the [2D cross-correlation function](https://www.mathworks.com/help/signal/ref/xcorr2.html) of matrices `a` and `b` (in a numeric from), and then checking whether an entry corresponding to a perfect overlap exists. ]
[Question] [ # Rotonyms 1 [ROT13](https://en.wikipedia.org/wiki/ROT13 "The ROT13 wikipedia page") ("rotate by 13 places") is a simple letter substitution cipher that replaces a letter with the 13th letter after it, in the alphabet. So, `A` becomes `N`, `N` becomes `A`, `B` <-> `O`, and so on to `M` <-> `Z`. `ROT13('abcdefghijklmnopqrstuvwxyz') == 'nopqrstuvwxyzabcdefghijklm'` A "Rotonym" is a word (pair) that ROT13s into another word (in the same language). For example: `ROT13('Terra') == 'Green'` # The Challenge Write a program or function that accepts a dictionary/word list and prints or returns a complete list of rotonyms. 1. Order doesn't matter. 2. Comparisons should be case-insensitive. Since the code can accept a dictionary, you can assume it will be passed a lower-case-only dictionary. 3. Result should be expressed as single words (not the pairs) and contain no duplicates. 4. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). # Example Given ``` ask green irk me terra vex you ``` Return ``` green irk terra vex ``` # A Real Test Given ``` ab aba abba abe abjurer abo acieral acock adoxy advised adviser aefald affeer agena ah aha ahaunch aho ajowan albe alula alypin amesite amidic amidin amylin an ana anakes analogy anan anil ann anorexy ant apaid aparai ar arba arc areek argyle argyria arn arne aro arsheen arshin asaphic assegai atresic audian aum avar avertin avo avoid awesome ba babiism baler balita balk ban bana bar baraca bare batino bauson bawra baywood be beamage beamed bean becuna bedaub beg begrime bel bell ben ber bes beshlik beyond bhang bickern bimane bin birl bizonia bloat blunter bolero bonded bonnie boozer bor borasca boun boxhaul brava bromoil bronc bu bub bucksaw buggy built bullism bunga bunny bunt burion buttery byerite cabinda cadjan cadrans calas calends callus cameist cant capulet carpent cater caution cayuga censor cha chab chack chal chat chatta che chechen chee cheer cheery cheney chevon chian chirr cho chob cholo chopin city clerk clouted clover coach coder codworm coeval coff colic color conopid consul contra coraise corneum coster coueism cougnar couxia cowbind coz crag craggan crax crea creel crete crex crissal cross crowder cub cuba cuculus cullen cullion cur cuvy cymar czarian dabb dalles damson dand darger decapod decream deeping delible demi deworm dhanush dhoon didym diehard dill dineric disglut diss doghole donnish dorab doubled downy drop droshky dubb ducker dudish duit dungan durance ebony ehlite ejam eleven ella elohism eluder en enation endear endew enrut envy er erava erg erikite erne err ers evasive facient faden falisci fant faro fetish figment filite finless fipenny fitchet fiuman flabby flap flirter flyboat fogon foiler footle forgot fra fracas fraghan frank frater freir fu fub fubby fun fundic funt fur fury fusc gangdom ganglia gaonate garbel gast gaul gear geat gel gen gena genny gent genu gerenuk gers ghan ghat ghee gist gledy glee gnar gnat gnawing godpapa gordian gouda gra graddan granter grat greeny grr grummet grutch guacin guesten gul gun guna gunj gur gurl gurr ha hack haler hallage han haught haver he hein hen henotic her hern hetaery hexine hin hippus hiro hirudin hissing hoer hoghood homo hooklet horned howe hundi huspil hydrula hyppish ideally illeck imbed imburse immi impasse incog ing integer iowan iraq irk isobare isocrat istle ithacan ivan ivin ivoried jaunce jerry jitters juergen juha jun june junior jura kalends keacorn kemple kialee kinch kippeen kittul kohen koli komati koniga kulimit la laine lamb lapel laurate led leeward lexia liman linin linten lipan lisper loave lobcock loom luite maestri magiric mahra maimer mannose mano manuao map marcher marcid married mary maun maundy maxim medal meddler mentum merfold mew mho miamia midwise milchy molary molpe moslem mousse mudden mun muricid mysidae mysore myxa na naa nag nakhod namer nan nana navy ne nea neb neon nep nettler newtake nib nine ninon nizamut no nob nobby nodding nodiak non noon nor nourice nowhere nu nub nucleus numeral nun nunnery obe octose odso oenin off ogam ogor oh oho omasum omitter on ona onan one oner oniscus onyx oppidan or ora ore orf orlo orna orotund orphan ort ory osamine ourie outpay ova overget ovey palama paludic panical panisic pavia penk pent perjury perk pern perry phil pho phon phonics pickee picture pien pimpled piously pirl pit platty pledger pollack pomato ponerid poria postic poteye poulter pounce powdry prefer privy profile pross pruner psaltes psylla pub pun punatoo pung punicin puno puny pur purpura purr purre purrel pusscat pyrex pyropen pyropus quader qubba ra rabi rabitic rail rappage rarity re reaal rear rebend redcoat redweed ree rees ref regrasp reluct renin replate reseize residua ret retour retral rheic rhymer rife rifling ripping robing rohuna romanly romic rookish rumor rupial sairve saltant saltery salvo samekh scissel scraw scrubby seafolk seaware seldor sen serer serve setness seton setsman setting settlor sex sexto sh sha shag shave she shedded shel sher sho shool showish shrinal shrip shrove sievy sinus sinusal sirrah sis skither slait sley slicken slinker sloven smoker snag snap snath sneb sniping snithe soiling sort sourer spalax spent spex spidger spirt spiry spryly spyship squalor stilt strive strue styrian sucuriu suevi summary sumpter sundry swahili sylphy sync taccada talao tane tang tanghin tanglad tankert tarazed tarve taxon tealery teaser tecuna tee telical ten teng tercio terral terrify testily tha than thaw the thecate thee theft they thistle thob thole thone thorny thy thymoma timawa tiphead titrate toadess tomnoup tomosis toplike toryess tra trag trah train tran tref tremble triarch trilobe try tubbie tueiron tumored tuna tung tuning turfdom turr tweil tyrr ulcery un una unaloud unfrank unionid unkeyed unlit unmount unoften unpiety unscent unspike unurban unwhig unwon upperch uprid ur ura ure urea urocyon urva usurp uta utopian uva vacancy vacuist valkyr valois vapored vari vat vejoces vend verd vesbite vesicae vex victim vina vitals viva walloon warori warp waucht wearily weblike wedded weftage wha whample whar when whence whites whorish whun wilhelm wincey wog woodlet wouch wuzzer yakona yamp yaru yerava yezdi ym yn za zimme ``` Return ``` ab aba abba abe abjurer abo ah aha aho an ana anan anil ann ant ar arba arc arn aro avar avo ba balk ban bana bar bare be bean becuna beg bel ben ber bes bin birl bor brava bu bub cha chab chal chat che chechen chee cheer cheery cho clerk crag crax crea creel crex cub cuba cuvy dhoon en envy er erava erg erne err ers fant faro flap fra freir fu fub fubby fun funt fur fury gel gen gena gent genu gers ghan ghat ghee glee gnar gnat gra grat greeny grr gul gun guna gunj gur gurl gurr ha han he hein hen her hern hin ing iraq irk ivan ivin juha jun june jura la na naa nag nan nana navy ne nea neb neon nep nib nine no nob non noon nor nowhere nu nub nun obe oenin oh oho on ona onan one oner onyx or ora ore orf orna orphan ort ory ova ovey penk pent perk pern perry phil pho phon pub pun pung puno puny pur purpura purr purre purrel pyrex qubba ra rail re rear ree ref renin ret sen serve sh sha shag she shel sho shool snag sneb sync tane tang tee ten teng terral tha than thaw the thee they thy tra trag trah tran tref try tuna tung turr tyrr un una ur ura ure urea urva uva vat vend vex vina viva wha whar when whun yn ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes *Two bytes were saved by turning this into a function, as suggested by @EriktheOutgolfer.* A function expecting a list of strings in lowercase and returning a list of Jelly strings. ``` O_5ịØaf ``` [Try it online!](https://tio.run/##y0rNyan8/98/3vTh7u7DMxLT/h9u9/7/P1o9sThbXUc9vSg1NQ9IZxaBeLmpQKIktagoEUiXpVYAycr8UvVYAA "Jelly – Try It Online") ### How? ``` O_5ịØaf - link taking a list of strings such as ['irk','me','vex'] O - convert to ASCII codes --> [[105,114,107], [109,101], [118,101,120]] _5 - subtract 5 ((-96 + 13) mod 26) --> [[100,109,102], [104, 96], [113, 96,115]] Øa - yield the lowercase alphabet --> 'abcdefghijklmnopqrstuvwxyz' ị - pick new letters from there (modulo 26) --> ['vex','zr','irk'] f - filter out elements that are not in the original list --> ['vex','irk'] ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 12 bytes ``` {Rot=>_∩_} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX7vzoov8TWLv5Rx8r42v8BRZl5JdFp0QrRSonF2Uo6CkrpRampeSBGZhGYn5sKIktSi4oSQYyy1AoQVZlfqhSrEBv7HwA "Attache – Try It Online") (10 chars) I thought I'd never see the day where `Rot` came in handy... :D On Attache's [showcase entry](https://codegolf.stackexchange.com/a/164865/31957), I said that `Rot` is a residual command from its days of being a joke language. It's default behaviour is Rot13. ## Explanation ``` {Rot=>_∩_} { } anonymous lambda. argument: _ Rot=>_ calculate all rot-13 shifts of each item in _ ∩_ and keep only those that were in _ (by using an intersection) ``` ## Extended test case [Try it online!](https://tio.run/##LZhbjvS2EYXfvQrCywjgrCFwHg3DYEuUxBHFonlpjSbIe7aSbWUjf77DMdA8R6J4LdaN7Xv3yxF@bH/75ce/frX@y9//@N9//vvHv3/8o8bcf9t@@@mfJcX@28/@5fzLUyYEyseoocLm/BJD9Qm25XR@tc8HfMcW1r@YdmHziddtC3rbQ2acg5/Ij7zomaE@7PbZ@aQp0kh8TU@J1FyhxU7lFde4fJNqnyTSz6ucoYmS7Y9Y9ZGFZT1YDVpY7s4XH1dh9dF5llO1q8qwNQR2UPcnhUk16kNWUQULrO0IIU/WzM2XQ@tpLewarFfWyftYo2Yfl/NvzfAOtav921Q0@x2aXcEx88u/YmwXnJANGLsq0wlkFb3pQ/XLfFQvRjNoNFOTu@rDc5utDtG9gr@Q8eSgGo0TlqGRwurHC9pVatQSQlIRqBkzIUXKkSJLCI9lhjh8pkdczoA4XvHyCOQV9VjpGL8sI6pXMt/BkbuGMfbDIumvRVjOkT5mX/PbLL5pRzYYxz7RA4aqCAy0y6LeLC/uNfix5rGczd/wzvG@RkzMNVKasht598KsL1kfapRoRmcp1D2hSn8WZJ1XD68fCAWqPjc4@Ykhr5PTEF0htg5nQRkpiGsJ811bXPzommbxz2D@JeTGxha0mvISYBFgEvQJXd@CCr8sni8aTPiIcpj01siHFAmsamAqGtfSfJRpLLHTGlEzU7LRkTX81oCGcYPrfF5vqxcc3lqObRuQ0FVQa7bMaKu4DX3PHZ1aOCLsV5zDUO82t20jSOrwnv18/4xqfUu68Jdbqt8n7Fp@9Z9A8AK0DdRZYJBAbE0Lqtaa8J6r5bgptB/LmGfBOUtaOm5JZajNm30/l@b/8lViWvFPAE0bdMk2Vs@CVmyZUdfAKWIhMGu54IAAdzjFFxa/hisCU04rCj/aAZtGietDXQyHr/SPGAv@B5Va4Lan0cVMajtHw0hSdvVGfqzIBsPTz27Uc61WBO04eRla8ZBZQevsMyKjSZ@Zd6CeS3AB63lcwCKRW/hg7SGFNwLBbD1gh44jpCHhqTr7qZeoc/B10g1W1hkyYlOraWih7pR4znHl5ELVp@bQkhbfwW3y7uj75lfGxYnHtkR4VmHdW@ha9Bb3azaLc4lbzJxBgzEWVr7Fjj7r88BzuC1xUI@oALFKp7b0vOQ9NttZ@Ib1q9KsI87N6m58QiM3OcEm2g@NhHxO4RyihggOfi8VTYFroShmbHIL21CDqg9tcYh4X@2anFDg3RuCC3CVU9w91r/LK@2SIsCr6pHEjGD73NyujQMDqNApbm6ub5fZ77LxXa5kRw0eIe8yHKALbqnhbmshKMF1Ro/dBp5qr7Osq2rYrTYK0w1T0uxV7@O6gqoGcnb74NBoPQLWKmbJQ6wlj/wBVBVV0xtvNf3UMeMPmBQ7tHo88n50SN4Ep3UEhpXXolhHpsesr6roXs7rCJ/YhVNsPGIpWC6eywRjnXWtaauHqaOMBXM88PWAnfKvhzyN6m5G0cGBrRAKjmetSgiOpxRpXESzU3octhhYfLyIbMJR8VfxwpLjVRSXXcyL7U7TktMEOYI4s4xY/Z8AfZvNqAovkiwnhdLFjlTU7D0hCqxGZvlQwhLcB7byuI@oCNPcx8CWEM3HQJ4fQw8IAoh4V5Il786/wssZvPwpfBXmOaOXPpxRSdCJ0JRfYJCdYztN0j7x08CFTUM5EmnOkeKFn0AgyUviyV8voKCeyQ/Zg5PLYeRbLisFOeikuA3mOFHKkWKZVa0gF8I3Jp/sNTO5ZJhGGrLny6NKNcJ7lNO7/MGGLk/6UKGcrakRKQkwvKhQ6nLM73UhskBTevADICHBqufPeDkSFcIAuEoL5UyGKutm5I0X7usi@l2RzI@J43orLF0xLQcDWJpjWirUWUuBnjZ09tdY5bcuzUZGMNfxtLj6ICYlhD69y/qp7JTzQCmz19aUQmY/v@I1EXMmhuXwouCkciiU3rXgHO5O@uly5KMOBFCT@OUvvC6SyQRuCk4p27pKHeHoTzfb2QTGMS2T7nYjO3jwo@MgwmNNeVwz185siJJlc0bGZ0vXEdjazFnQ@SrA206kwJ9WZwc/Pl2@IVa7ptI65sThqeghqKgSF89URJxPZxibPI@G4MQlMKsMXMk/0GHVWOcU4XLMdp3CmhoHpRHZjbAXTyUBR4nJjp3DjyukXZcXDXloNDGSe01u8/3NYRNBTjdzLlT0Q767KNcpcjtlmiApOJ3YHiVPiEtzRclqEHWuKjB6UKJMboVRD5xHUfZasKOSyMx456McRDGcICZQZHSMK8GgOsV0ISgkQVqd9fAwro3UZ5fpFAoJjJZUw6bKGt96MeJiEBMTSx0ScyHr6eQppT2K4YVDLhwqhRlNvAuiPDk8axgKz00p8idFzlsQvpGdoPMkpq48Sq1AK9q0mAP9c3ilB38OXeKqfq84Qbshz0tAKfL9lXQKaTAweRIHUhX@auB@sELrojgN3yHoXa3YCDumEJpagdNY1EaaWIOkq1YtxK/JcR3MH9SioyIiaXUlwLCU45Ht1bgFQZKpVPziZHt906Fgxi3BZ44RVj9CiCIDwRB1raPgWF3zseLTJGzlLFPonA/MVQwlDefhyGjwFbTF@9/CmTq04PE9p/hWdKAF6RyUKbr7gho59KxUBzZ96U0@Fu5aqDjNXp8q6BILbEQIyi7QCMcsq25JcBLQ41BbM73aHWc3LuXaElyEps4xoGEEVQ54ohpwWeBy3SJVBJI5GlGC3SeMriUZRhbnc34yZZLtsvkmHwgUQWcQebuW45Q@3LVYkrP5KmtvNv8IaLJl9jgNFdRjnLYEqxnI3KU@SfRwfWYKVHJKp@supwijHfU6hM9M6RsXgBoHHN4RvGb4gIuMruF69Hp7XACfn1SIB@3h0tj9wu3Ow4l41HVf7brDCpSeiJNfxey7w9V/Bb3rVLv/5DR7UEr0iPUnRv@@Qnc0vnNlkKtSCKUwbCDImajOamLdpo7aGsyJd/lH4HaSIUVXSPGErQvV8jv76Lrn9XmZAPPEmvV9lgvNd51wfovKEbST2Gfc74ado5HdLqJJEZt0oVvhRq/v9Znf8QFd17QubQEklapFypSBS5ciDkVxXJwUabrkgYHg1ju3wCoxyeAkuikdOS4gTqqb8usuT9XvgIvhWKsbaZFYcXfqMfSHzVjh72xeKVOOej9xsGLuFCAhPYttk9RHxqN3DdKWMOtRMXY38qj632Tk@4i7iBUOsiptYhS5cRyO/KeiwtCldFRbHrWqBKjRcK9ucE0fCEwqOKh9KxVcHvFQIs8d@nyqyJDsm2ulBPDGbwJ8Dh@24BPf8phEPEF7KZN66/8hL/50b0ITmQ@pJRNEFJUOZJvuJrFVPoDbIeCICjAWUvEbTyyFusNrnuX97TZu9EeO@0bPKDOvhCuAqASLKqICzo0iyZ3cuFB3x4THuWBaMCyJsv5EUiZ@GzO6e3zp/5rHn8oUHoYG6nDP9/3xCV@k6NyNn@y@vPsi8Q4///7T77//@D8 "Attache – Try It Online") ## Alternatives **14 bytes:** `{_&Has\Rot=>_}` **14 bytes:** `{`in&_\Rot=>_}` (Both of these work by filtering using functions.) [Answer] # [Python 2](https://docs.python.org/2/), ~~70~~ 63 bytes ``` lambda l:l&{''.join(chr((ord(c)-6)%26+97)for c in w)for w in l} ``` [Try it online!](https://tio.run/##HcfLDoIwEIXhV5k0Udp4WbDAaOKbuKmllWqZIWMVCeHZa4bN@b8zTLkjrEu43kqy/b21kC5pO1fV8UkRtetYa@JWO3NozKZudueTCcTgICKMK0dhWsrAETMEPSv7fqk9qAd7j4LI6@@9bPbMVvD1P8lEH7WY8gc "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` lambda l:l&{w.encode('rot13')for w in l} ``` [Try it online!](https://tio.run/##HYdLDsIgEECvMmEhNDEm1p2JN3GD7VCJMNOMWGwIZ8fg5n3WPT2ZxuZu9xZsfMwWwjUcSj4hTTyj0cLpfNGDY4EMniDUtoqnBM4UZd8vdQS1CCL18PL/iJ0JRWyPDb9dO39UHdoP "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` tot2Y2t13YSXEXm) ``` [Try it online!](https://tio.run/##y00syfn/vyS/xCjSqMTQODI4wjUiV/P//2r1xOJsdQX19KLU1DwgnVkE4uWmAomS1KKiRCBdlloBJCvzS9VrAQ "MATL – Try It Online") ### Explanation The stack is shown upside down, that is, the most recent element is below. ``` t % Implicit input: cell array of strings. Duplicate % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} o % Convert to double. Gives a matrix, right-padding with 0 % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [97 115 107 0 0; ...; 121 111 117 0 0] t % Duplicate % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [97 115 107 0 0; ...; 121 111 117 0 0] % [97 115 107 0 0; ...; 121 111 117 0 0] 2Y2 % Push predefined literal 'abc...xyz' % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [97 115 107 0 0; ...; 121 111 117 0 0] % [97 115 107 0 0; ...; 121 111 117 0 0] % 'abc...xyz' t13YS % Duplicate. Circularly shift by 13 positions % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [97 115 107 0 0; ...; 121 111 117 0 0] % [97 115 107 0 0; ...; 121 111 117 0 0] % 'abc...xyz' % 'nop...klm' XE % Replace entries in the 1st input that are in the 2nd input by % those of the 3rd input % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [97 115 107 0 0; ...; 121 111 117 0 0] % [110 102 120 0 0; ...; 108 98 104 0 0] Xm % Ismember-rows: true for rows of 1st input that are in the 2nd % STACK: {'ask' 'green' 'irk' 'me' 'terra' 'vex' 'you'} % [false; true; true; false; true; true; false] ) % Index. Implicit display % STACK: {'green' 'irk' 'terra' 'vex'} ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function, taking a list of uppercase words. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. ``` ⊢∩{⎕A[⍵⍳⍨13⌽⎕A]}¨ ``` [Try it online!](https://tio.run/##RZhPryw3EcX3fArvbrJAIsoGlhF6gghBpJeAQIiFp9vT7Ttu2/Gf6dsXsUJ6gigvCovsUVZhxQLBjk0@ynyRx@943hPSuE63u@22y1Wnqsbm8MP5sCEtb25fffPxJ7dXX//oB3sqc/C1cfPBez/@4Ce3L//z/oN5eO/217/fvnh1@@Lb9x/sydjTySIcLRk7eVdsMHZxkd7VWEG0F1eBaGy2xXpjy3IERpQowbBq8@onY/vsLW9dbUG40nw0J3vyvm6grpnuxBTTAIfYC5cu0Hjsn1P03KcYPQ8LE5lT5xcXayYmirMw2Io8ujpXxy8KozsAfX9aU0hmSt3pw1OxTwjXnCSXnQ1PfeqhM00PgeFz9w3BZ6Jxj3YzLgSLSKtmcGMhZ4syJ2/Ovm@8du7FLDZFy7yL7cGgsniYZeXZgub9wM6CV4caVl9QTjQ@LsannYe@2M@NbyvK4OaKeOyuMAu4WoQuUPBjR0UXH6fVXJL2eknBIzbbBNGjhuAz4wO7cGazKwM2Ww4Ek2ypBreZ7ah@tk6Y0Hzk/ajjiC6bmExizYbdqEUEW0U9iX1ne@VMsitMyCkHk1NRR2dUPqTRz7udXTGFAzLFObVqCguM4RBiGdUV3qgrJ13XRCvp6kzNnOWTqe0oUlft7upN3S1f8aZZVNUwlmc3m@amzuLa6kxL5XC1mlYY0kbvUYrRRS9pOlI0vaWsCa82XI4iSL6aq3tMkxPG2ew2hMSrO/ZbvNl9YG2bOexFSjhs6ea4n/vhnmdMfngJZ8E27JSmi7FzejqQV19Z4B155rATbs9npzs8aJUjcRCTrvGVx3H6NsjlQsfMbDgylmE3V3V@dvOzfEmg3iMI4jtXxMcPoTo4jOGVkRPVWmKTh3o@z6eLVlyYiOO4DJfVseGzNA7C3VFz1@oWeXUrrEBevOG9SU1T7a6mTa7KL7AnpG/j5vLWqcs7Z8bfE9BrUvexpzTj2PzsBqMMdOrRqPuBntxs@wlY1IrXhwYbhLeUoA9yZrQ1eD7oOF@mWGUcJz9dXBFvYGoMFNv4wsCQbEP22DQ8seokUpn18ZSeR@dotoqJEl5ySk@rvPiEvSY/ME538mF5fbpUu4MLyj91H5ge5hi81uX2SHUVr533xnfpw4B0oJOdH8VKdsZixVwwzjxwMBA6gaTBKJF7cMKS3bjXDibbmyaeXMR3oTfxHtSNwA6RQaIN0QYnqt1FuUtRo7tqDohIfUlNUyTZ3uQbb6AnpgupNxQFXjU6WQx3SvO4nokpMGpyV30znc@IgMkgtbAUmW0W1q7nER8FCBnVCaPrGl3HplJfoh345PXWLnoHn8XYyxCiYzjbSmAVU/G16sMl4f/IfayKAxKNDw113V/Zy7Fp7mc7iGUmyCGg@gpsMs/Z8rEZr2CG2aF3TBXkYxvosnh6dsGfiHOz2zxi7H3G8npdQbHH7OeDPu9WWxjvsVqclmOfwLqE3oR8NC3EJGZSZNNodMKKUmd6xqUdE5pLyhJ1vXDTteIu@wbmMYY4ECdnHJZ8GIc7YFsuOOgM6FKFrghI0gQm5mwZsCMLK3ERxeitstD8ZYxXCIfaadVwqtVDy2elAVjfGVon0NlxiQudXdNCzn7ZxmM/lnD2MYiPzz6PCHj2DVvjcUDrhyAjfNGhn8Nxkm@eCTfMjKOpM6WGbs6pLIlHmMxZGUIVjHAKxovkmKI4j@z8Tmr6RFc4jmLNs/xQoZmmB3UiOMdlTtvAgKUtMCPGtFicbpGOELoaEdyMxGfR9hAdUYCLsCq20y3PWuSxC2d3SHIvS0Y0iV22s6Q5w8VmKaPNs9IB9qEtgLyISStfKLrv2@bU1VGdWTr65@3ucBQhK@tCrazHR0RRUzejYYPBA@tgZ2QQ10pvENqyNkCODCkoeaClhqLW0VXU0az4YXVPWK5ZR66SM8wEUyRErdrPmjRAZoyjrHAkIl3EVav8Wn07o3UKyJqh0PWYi@LbeuQsu/FYZCAjwEsc6/Ub5C/ZC@zgN3zMb1nBiCRpSss9VUJhclEPM/maRpwBJ2mQM8Bs/FVZ1ZUgzmyPirOkTCNZefTi4foui4oeirq8Jd@Ls@IjcMtMcvFWx3hh4wqMuEZD65ce/EZiyB6ClXKC3U6IjK0E22WPRv7L0F3@H5yYLCgaIaMfUkdIoCB/MoQlvCuk08gfSD/IyiyHTP5BfPRijc0SAgsQY6rK5QioiG4FWVndtI7nZYJogbFt5Xmz0r0nz5SE1CA5yx7kqV2d5ZzISzbYYIP8N09@QZbo513cvPkwrUyQwkgbU8j0pa6z2PosFtiUSRLfxmePJ/JG/dQW2mXFKqLV0v@fWFroBqVFpyTzRMPlR7bpWtPSotsblYWJnodSL0Kv@Ge7QVfsPBKhaLh4TPMsewC9vZjxXhqCeZLWxfC0oxuw82NgJ6BhxrFvo6aJ7IAWZeyJrCRNTSpOcyX7dTotxbO0EADSyo/ezVZ0RwIrQyIpfpsgOzXdH08mYdvybWXPuLpS61SYplCBYGDqSSSpM5jX8V6jsYLKAWgm1i7Zsj1Guq2ou@BWIPk2@fGmFBx@xzpI8j1pw0BlahDuxYxEAfN6FONlhfAsv36XsCe1OISfqsnKmZygkcuCnG32coIZ5Mhx0KwkKmP4OZBQcM9DOWFOcAuWm1V7MK@0gDlkAroWk5o7mDH10MbLwxUzQVrrKO6szuKvuknEDickbuTSpc1MZG/E51wP1V6ZE6TEUONbSbhIeFEjyCywIC2rPMoiQgl3lywf4yV7eluhIFPWToXYxOddVW@xo2bR4klRAiJncWcha2DbRZWMRd1FUaK4k@qG4uZJEQzcnZvf1jtnGqxeMxj6pMcyqOKkQb1QnX8e6OfOV53eaJy9QMZZKBJZxXrIhYo/O4kgiy9w0sB0usOqOFAgX3EqkQPLK51yh8rK@qKqCkUqZg@FonuQbB57c5fVUMHi1bwLhe6SI4JWZ6GHi3AXxfIGKQoQVblpTteigjyY1NeqSA5sWpQwjPef1JoKPH5WbZHQDOtos5Lwuo5iUK@lNCrC3Y8RxUftA8ymeoetEHw4ryH1hOSVmqpSzVVIekwDNbPXgLfUIOOOwngZj5KSo7qlcSeqQmSJxiQipRr90C6o2rKSkYxbuWlNo9qrw8GQ7A1fX0aX13MkH83lCIKDYoq5KYaHKpqKBHG79t5KR3bSU9/BbVTnYJanVOhBt0fIq4C6o9mJcoHKFv9PqoTdu3I4LorQwmBnIVtrKpOveuWJw2lOicAhVEHaMNBGIiveUCyiMY8jfiRBGd2EkbNGaNXgqkpb1fWKjYyae3UqRYRDnJuk3rwH4aZaoo0UFxmHLFHPR9sgDNOIi7sgr05L920E0JbIMlXOpw0iz8Kk86WEp@BzKvPVFolVQtuXxyE2ZeeoWFFRGMTrTXvHqqHV1skVpRJ5if5FGP8WiEkQfkA5Kzds4o@2O0igh0nag3q6iu0@g/cEVBlE9Lq/QHRC8l8kgTIK01n67RFObZqgTm70Yyfso8deVC73uK9@EeiPCvINrb1nESl0IDITL3dVPb0QD3qF40ynruvcXfVv0XQIu3LQK4WLdnaFshDt/ucGIUSinpSfX1XUW@GTuUL7pAikTExFFR8qwLQ4fUb0iXRxh@1kBbs7jQPY7z67c@gixx3joI20CSwIdi0xqcOLw3dOXw69w1WGdHjCVHYyOv0hoJRxT3zJ7P1ZpfjBXIYq6ojm2ZpnEkH38Ob2xbe3v/zjj7evvvno97fX/769/tft9XcffHj78r/q@sOfvv/uzfn26uvb66/u/3d@8efv//nh7dXfuPv05U@Rn/3840/fnM3DR5/@4sE8/Ozlixe/Aj9@qbtfvkB89uLly4/A37z4LfJ3n/z64Qdn8@4v0/8B "APL (Dyalog Unicode) – Try It Online") (edit: now with big word list!) `⊢` the argument's `∩` intersection with `{`…`}¨` the result of the following function applied to each word (`⍵` is the word):  `⎕A[`…`]` index the uppercase **A**lphabet with:   `⍵⍳⍨` the indices of the word into   `13⌽` the rot-13 of   `⎕A` the uppercase **A**lphabet [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes ``` .+ $&¶$&! T`l`n-zl`.+! O` !`\b(.+)(?=¶\1!) ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRe3QNhU1Ra6QhJyEPN2qnAQ9bUUu/wQuxYSYJA09bU0Ne9tD22IMFTX//08szuZKL0pNzePKLMrmyk3lKkktKkrkKkut4KrMLwUA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $&¶$&! ``` Duplicate all of the words, suffixing a `!` to the duplicate. ``` T`l`n-zl`.+! ``` ROT13 all of the duplicates. ``` O` ``` Sort the words. ``` !`\b(.+)(?=¶\1!) ``` Find the duplicates. [Answer] # JavaScript (Node.js), 59 bytes *Saved 1 byte thanks to @ovs* Takes input as an array of strings in lowercase. Returns an array of strings. ``` a=>a.filter(s=>a.some(S=>Buffer(S).map(c=>(c-6)%26+97)==s)) ``` [Try it online!](https://tio.run/##FYyxDsIwEEO/BiURNANDEcNl4Bc6VgyncKkCTVLl2gq@PlwXP9uS/cYd2de4rF0uL2oBGoJDG@K8UtV8eC6J9ADusYUg3WBswkV7cNp3vTld@/P9ZgDYmOZL5jKTncukgx4V8kdd1FSJsjDWIyUSkfOKwp2@or@yqafM/w "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // given the input array a[] a.filter(s => // for each string s in a[]: a.some(S => // for each string S in a[]: Buffer(S) // create a buffer from S (deprecated method) .map(c => // for each byte c in the buffer: (c - 6) % 26 // apply rot13 transformation ((-97 + 13) mod 26 = -6) + 97 // and convert it back to [a-z] ) == s // implicit coercion to string; compare with s ) // end of some() ) // end of filter() ``` [Answer] # [Perl 6](https://perl6.org), ~~57~~ 35 bytes ``` .say for ($/=lines.Set).keys.grep:{$/{TR/a..z/n..za..m/}} ``` [Try it](https://tio.run/##DcoxDkBAEEbhfk6hUNDMdAqJS@ACW/xEliWziLVx9rXNy1e8A7o2KbE3oZh2LapSunVx8DzgrNkieJ4VRxtLiWMvhvkVl5OxyfelZLylfMDRopY20AlVQzceCvv1Aw "Perl 6 – Try It Online") ``` {@^a.grep:{@a∋TR/a..z/n..za..m/}} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7/aIS5RL70otcCq2iHxUUd3SJB@op5elX4ekAAycvVra//rFSdWKqTlFymA9GjkZOalFmv@TyzO5gLqS83jyizK5spN5SpJLSpK5CpLreCqzC8FAA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with placeholder parameter @a @^a # declare and use placeholder parameter .grep: # find all the values in it that match the following { @a ∋ # Set contains operator TR/a..z/n..za..m/ # do the rotation on the grepped value } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~45~~ 35 bytes -10(!) thanks to G B ``` ->a{a&a.map{|x|x.tr"a-z","n-za-m"}} ``` [Try it online!](https://tio.run/##HYfLDYAgDEBXIT14om6gixgONanGGJRUNKgwew1e3kfO8dapU@zppYZaT@HNKac2ChA@YGHDh9BDKRrMNAxAxwrWwCzMW41F/vdcGVmEalycqu79BOf0Aw "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~101~~ 94 bytes ``` lambda d:[w for w in d if{''.join(chr((ord(c)+i)%26+97)for c in w)for i in range(26)}&(d-{w})] ``` [Try it online!](https://tio.run/##HYpBDsIgEEWvMhtlSNVFFzWaeBJ1gQXaUQvNWMWm4ewIbt57P/njPPXe1cmeLumphptWoI/nANYzBCAHGsguQuzunhy2PSN61tjKiuSqbqrDXpZrW67hn1SSlesM1o2Ma9TbJUR5TSOTm8DiItTrITaiY2NcNnFZg8mYDLPK/phv5uzfIsr0Aw "Python 2 – Try It Online") Takes a set of words (lowercase), and returns a list of rotonyms. [Answer] # [Perl 5](https://www.perl.org/) `-a`, 40 bytes ``` y/a-z/n-za-m/;for$i(@F){/\b$i\b/&&say$i} ``` [Try it online!](https://tio.run/##BcGxDoJADADQX@lwITLU4sDk4uTmH7CUpJoGuCM9NByEX6e@N4uNrXshxo0ibowT3d/Jgl4ez3qnrg/a9VRVmUvQw53zAB8TiaA2wCSwiBnDT1Yo6XumedEUsyM7vtprc2v@ "Perl 5 – Try It Online") Input is as a space separated list of words. [Answer] # [C (gcc)](https://gcc.gnu.org/), 137 bytes ``` char*a,*b,x[99];f(_)char*_;{strcpy(x,_);for(a=strtok(x," ");a=strtok(0," ");strstr(_,a)&&printf("%s ",a))for(b=a;*b;++b)*b=(*b-6)%26+97;} ``` [Try it online!](https://tio.run/##VY7RisIwEEXf/YqhUEnSCO4@KN2xf@GbW2oS0m4opjKNUpF@ezetrLBDCPee3FzGbBpjpsn8KBJKCi2HU56XWLOKL6zCZx/IXB9skBXHuiOmikhC10aSQMLx7bcvH108rJKKr9dXcj7ULEl7SCLgc4EuFAqNWaa50AUTerPj6ecuy/c4TjEOF@U8m4WixkiYFwER9f1U8ucK4syPDhcZG4G54gPBwWH5gZBljsMrOc/fEkfbB@ebLzin/fnbJxKWUldyfGdr9p@Ny0023MjDFlfjNKm@hYas9eCohYuFYIkU3O0Aj@72Cw "C (gcc) – Try It Online") Description: ``` char*a,*b,x[99]; // Variables f(_)char*_;{ // f(space separated string) strcpy(x,_); // copy input to x for(a=strtok(x," "); // loop from first word a=strtok(0," "); // to last word strstr(_,a)&&printf("%s ",a)) // at each step printing if found in original string // this occurs after the next loop which // rot13's the loop argument 'a' for(b=a;*b;++b) // for each character in a *b=(*b-6)%26+97;} // set it to its rot13 variant (x-6)%26+97 for ascii ``` [Answer] # Python 3, ~~68~~ 60 bytes ``` lambda d:d&{encode(w,"rot13")for w in d};from codecs import* ``` Although we could put the `import` on the previous line without penalty, it just seems more amusing this way. The function now only accepts the dictionary as a `set`, which makes a huge performance improvement for very large dictionaries. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εAA2äRJ‡}Ã ``` -2 bytes thanks to *@Emigna*. [Try it online.](https://tio.run/##MzBNTDJM/f//3FZHR6PDS4K8HjUsrD3c/P/Q7v/RSonF2Uo6CkrpRampeSBGZhGYn5sKIktSi4oSQYyy1AoQVZlfqhQLAA) **Explanation:** ``` # example input: ["ask","green","irk","terra"] ε } # For-each over the input-list: A # Take the lowercase alphabet twice A2äRJ # Split the alphabet in halve, reverse both parts, and joined it back together # → nopqrstuvwxyzabcdefghijklm ‡ # Transliteral; changing the characters in the input-words, from # the letters in the alphabet, to the letters in the ROT-13 alphabet # → ['nfx','terra','vex','green'] Ã # Remove all items from the input-list, that are not in the list above # → ['green','terra'] ``` --- **Old 12-byte version:** ``` Ç6-₂%εAsèJ}Ã ``` -1 byte thanks to *@Emigna* changing `мм` to `Ã` (couldn't find this builtin myself in the available commands). [Try it online.](https://tio.run/##MzBNTDJM/f//cLuZ7qOmJtVzWx2LD6/wqj3c/P/Q7v/RSonF2Uo6CkrpRampeSBGZhGYn5sKIktSi4oSQYyy1AoQVZlfqhQLAA) **Explanation:** ``` # example input: ["ask","green","irk","terra"] Ç # Convert all input-characters to their unicode values # → [[97,115,107],[103,114,101,101,110],[105,114,107],[116,101,114,114,97]] 6-₂% # Subtract 6, and take modulo-26 # → [[13,5,23],[19,4,17,17,0],[21,4,23],[6,17,4,4,13]] ε } # For-each: Asè # Take the letters from the lowercase alphabet at the calculated indices # → [['n','f','x'],['t','e','r','r','a'],['v','e','x'],['g','r','e','e','n']] J # Join all letters together again # → ['nfx','terra','vex','green'] Ã # Remove all items from the input-list, that are not in the list above # → ['green','terra'] ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 97 bytes ``` l->l.stream().filter(s->l.contains(new String(s.chars().map(m->m%26+65).toArray(),0,s.length()))) ``` [Try it online!](https://tio.run/##bY5PS8NAEMXv/RRDQdjV7SKCPfRPoIcoUquQqCjiYU2Tdutms@xMKkX62eMmtSDoXIaZ95t5b6O2arBZfjS6dJUn2IRZ1qSNPB33/uyK2makK/uviORzVbZSZhQiLJS28NUDcPW70RkgKQptW@kllEFjKXltV69voPwKeYcCXP1YTG410uSARCLtfh/HCAqYNmYQHU0Zl4U2lHuG7TKrLAUDZDb/hMMNQ5mtlcdAlsqxchCVJxfDs@Ell1TNvFc7xsW5QGlyu6I146GacZfodxAwMIUOR6mwVVh/ls7FdRLHd@ImmYtFLB7iJJmJp/hZvNw/9iU6owMm@pwfHhZSOWd2zITUlY9VtmbpDikvZVXTaOSCExnbwfvevvkG "Java (JDK 10) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` @ms@LGm-Ck6 ``` [Try it online](https://pyth.herokuapp.com/?code=%40ms%40LGm-Ck6&input=%5B%22ask%22%2C%22green%22%2C%22irk%22%2C%22me%22%2C%22terra%22%2C%22vex%22%2C%22you%22%5D&debug=0) Expects input as an array of lowercase words. Explanation: ``` @ms@LGm-Ck6dQQ Q=input(), final 3 tokens are implicit m Q For each word d in input, map over... m d For each letter k in d, map over... Ck Convert to ASCII code point - 6 Subtract 6 @LG Modular index each over the lowercase alphabet (G) s Join each array of chars into a string @ Q Filter the input on presence in the resulting set ``` [Answer] # [Julia 0.6](http://julialang.org/), 49 bytes ``` W->filter(w->String(([w...].-'S')%26.+'`')∈W,W) ``` [Try it online!](https://tio.run/##jZnLbiS3FYb38xSEgMASMp5FFlkEsPMQXnhhGAi7il1FNYukeelSCX4A77PN0/lFnO9nj2TN2HE8EM/fxTsPz5Xz2IO3f//lbL4yv3z75ddnH5or9/uXX3/Tio/L/f13@4cPH77/8OUX33zx8Je//f3DX7/41xcPP//007fvv3345dzj1HyKZrM@3j@8M@acirnfU5lrK@@Ne8puam5OvT0YH82zz/c@5t7qJ21VI43RsOBrYy/fuHZfc/DtZa6HW5eSWorHVulyvn/pf2vK7LeFeP/S5fdrzVdfvV3Z/NPc/fyff9@Zf5i7pzsNcXF@p/JuSpGt3HbLcvd3tl7MUpyLxpeL2ZyBU8Waq3syR@p378d6b//d2ZOxJ0sZxFEee3EFTMZO3hUbwDRdjJ3T0wG9@urmj0g/d7aBz/PZ6WtxkXlW/gQW3us3Uz2m3UZjg5YIPdAajgy77eaqb1RufvbTDVR7BIH@rMrFVUFIyyFUvWdjUT9ScdpYbMZm62fRYr2xbKfoVIVp4QknKMsR3IDi1RBVVMEGS13FN6FWrjav2k@tbtFkrbBPvvvstXrfjL1qhasrTf2vSUWr764mOM/KJ3vyvm5ggDdQ31QZLpCooi81FDuNnxrFbAnoNanLXtRw7CnNBtadnN3g8UCnGs3jpq6Z3Gz7CVhUitcWXFARUTdWgouUNXi24I4UmWK1kRF@ujjYcfKbhSEnr5@Fgf45RVh1Csk2aI9N0yTOwyYZr02kGD1jUnoebaPYqhOlzjzpCTlgqgLDoGlLXl8pTubU@WPPfbpUu4ML13vqKDg0hMG7HhcrGtUS1VCkzafe2Ap1hyuSnwlex9mC8yNMAYqNFQx2UPRlYOiCzUmHJ8nMZHMPTliyG9864mT7MBqTPTrrTy5WDjYh1ZSTCBoBDSJtkKY2p8JfFI4PTSZ6CKIbcNXMqwQJWtQhqWjeFMZPqcbkG71hNSsFDAG8Bq@aMFn0akrz@D1jZDbQXbWddD5DArIK1Z5TZLZZWLvaY0OmJq4I/RVG1zW6jmOn7sR1cIl2fD959d7FXfDZTMUugyzafrFPEGdFkDao7gKFhPhataGSahXdx265bgr9@9THXXDP4pauW1zp6nPl3Mem9Z9tEZtm7BOErhXYpBuzZUMzusyss@MW0RCQvWygg4ELGPwJjZ/d5iGDTzMC3@sKJs3i54M671ZbGO9RFuwPIjWBdQmYX5BF08LVMJOEXaPhHztKnekZl3bEcy4pi9T1wkfXjrvUCpjHmO6ZTfLMuh3xnJxxaM9hHBoJ39wje3fBXWEIamshadV1uNDFPFVHO@QScXa2DNihhX26CNvUayiaKwvFX8a8MnI4Ako1SEn1V2fOsu7I@9nOzIsR93Xy4KhCu8@uadNnv2yjmx9bPPvIHVQQZWHnZ9@QZzV3LIc5By7qEGSIL5KpczhOsh7ntLDxM9qvypQa7MQVL4kmJPIsI1gFy6qZ4M9FdExRnId2/k4qWgLTQpHPOMssnLs6FDXUycDiZU7bQIIHMME4BxYZxcWi/Yus0iIuQvhUPZwYHmwZh1t0cEiHFOAirGbsb5HaL9LxRaZkQQwOUb6lOJAmsksMlzRnnBJYhvdYUsdSLWWUeVYNp9VBwXZz4ExW9N23zamqw2ezdC6N3t2hrUK23IXaco@PkKKiakZjrYadWof/gQb5Du0ei7ysDZA1wWitjmlltSipwdN11BdVNCvjtbon9MLIN64@ZzQXy5VE@jzqatVR16SBUhbUccXWQ9JF9nWVpVHdziy6OGjNuIL1mIsCgvXIWRLnkewQDoMuOjbvNzybaC/YK7@hyX7L8ssEPlNajJYlgHIyBH5EGb7YH0YA5GsaXhWcxFluCqHzDa6o23UQL5KKZ5VHBSzOPKIrh3n08jDVPHZ0CdY8dvj52PUDRkA81pVgyZrLR/dycVb2FNwy61y8lTxcvIKgC0xTfIFCNq7tksTtC3YasqHTQPR4mgvB7oadgCHBiuPBbidIRjyD7dIHI5PDzLtMVnAy0EF@Gxr9oBKO4POoqhm@4L5R@ZBOI5ILCdUIXfq8WUSpeHDxMnqbXTkQofLGKOaMqaoTIQmkW0GmlGkd7WXCswCDe@AB6XGQWb@f/EYUiuEWnSWFMiZdleWciBs3zNeG99s8kR8L@3mXW9p8mFYmSGHMmUKmLtXgGJm67n7rs@zWptWICMY@jupn64SEhMCTNVF/KgvlsiKU0epoCiGjHa1YTdgc8WHRnSgYqegypTVtOLq9EX6a6GnUhUDUxT/bDasLZyKOm4JRimmeJY6gtxcz@qVBmCdpmwxPO7wDO38M7Hh4tCn2bcTakQNRonQuEfGlqekK0lyTSU73KwefFjwF9rSYtPJH02YrbE3bEFrDmhg8Ff1wKqrExLMUHufJJJRNlkdTcONiWCpMXIg/kGHVpMYtgnkd/RqFPVUuSjNyGtGWLZU4HAUmC3oOHiYTdm1W0GWhkURP7DWwju8rl40HuZgRcyGij7LdWbFOltnJQwUJwRnE8ShxED9VkxWsOkEjVQGRg@ylcjOIeGA8sqLXjB7lQGTGN40yEDlhBFGBLKVjXjEG0clJCUEmCNLuUnMH86auRFMoo5AJYLSl4s6qLP6qj4RfdEJ8Yi5dbM5EPY04JddDPjxzyZlLpbBiEi4iXpYcHDVMheWmZNmTLOMt4m6UkyDzBKYmHwqtoCnr0EIu9IduFR780JXEFf2d/CA6DXFegOQs218Ip@AGExMncSFF7q848oMZmCf5aXB3Tt/qxUE4MQXXVDMY@qQ@ksTixF31qs4/D/RzZ32nHg0REUiqCw6GrayHdK/4sxMJUpWCXRyYTjdY5czIEmzkGkGNw4XIM@AMEdfSM4bVVOsLNk3MVswymM79gKRiCKm7rIaIBltBX6z/LjpCh@ostuci3OUd6EE4B0SKcl@oZnYtKtQBk1palY0FmzYqDGPUkwqyxAYrHoKyiGiGdZRZWRIYRBixqm9K@ky7H8OKjzoSmEWTBnuHhOFUueBB1YFkgeS6eqpwJGM2vASnDyhdDVKMKIyX0ZQUSdYtjS/ZQEgWaUwia1ejH9wHmzZLcDY@pe01jYeAKl3mjENRofrphy6B6gZl7VyOIDhIn1kCkRzcacrl5GF0ola66DFC@koCUHwH3dVDt@E@wCylq5gefe4WE0DzETL@oB4kjc1OZHcWDPijpny1KYcVUXgiDHYWcu4GFvvs9K1bbfaJ22xOIdEh1CNGu6XQzenBJAxTJRdKWfSCMvl0e0gJA/xZA3U0kBtvso@Q3YiHFKWQwkHOTVQ9b9FHU57XRjIBjYOWqPZRNiTfNNz5Lsir00l8G36/JfQciWxpw5tkYZIstJTJ6NVejtGODWhK05qkBSKuFG1SqgzZlBRxKfLjwiBP08QPFASz3sgCi9gkhRPrBndkuCB@QDkrvm6yVG13mBiutZgeJrEVc6cRXQ82fQZv0bxCpuj1fcHACskpoLj0KExncb1HLHrTJHVyox4R43Q99qJ3kx731S8CdtiJqnSInmXGMTiyn/IKXUlpL2k61KvgoHrFvJpOmt5hmESwU3tVKDgdwq5Anhz6chRBgrNX0kox4IrdhNDsHtOETbzKYuLxROpJkdRV70PWjbe2K66JyIfQkgU8gsoAok2zE9gqHsDs4HAEGdInQvEdSyyB2t1p3OV@Mxs78iPDvSNnlBFXggUCq0QmVXg5nB1BkjnZMaFm9wGLs4H0YFoCZT0iKRLfEyuavT/rveawF0UKB1NDSjfHLX883DMhOrnxEc2zNc8E3u7u3cPLm@Pbl1G9POox9Lu7kbncvTd3BN@CoTT6AVPuvn94/@7XN9M/fnh8eUBMb54AP3nza58978XbI97tSS7dHt9@553NfXxEe/Nqtnx8JnvzQvb6@qW3rNuz1e2h6u37z@vLzx8/@aSXF5yPzyafP5c8vX0SweDfniVGpv/bdP5NGv8mUR/J9sig/1eW/CY9/jzN/TXB/W1i@1k2e8tXP81P/0wGGj/LMF8ySyVeyt1es7XXfOzzVKsoGfo0lv@/4ftruP4SoH8Si38Wg8dbrH2Lrz9G1L8fQit0/jxkHtHyp1HyLSA@Po1x/yi2/TVKXP58VDiiwTdhnyI99xLUuY@B2y1Say/xzYhL3kYq7iU2eQ1LbpGCwoObv331sMM//uoXh0P8PQfoXlze8Vtf9OqFjk/civzI8CAfXcdvLLks@LDX7cX4Pr0Y2Kt9sY@vdpFpjnj38IDBIuPQ24rFJF/d/YP58ceX/wr65b8 "Julia 0.6 – Try It Online") Takes a `Set` of words and returns a `Set` of rotonyms. `[w...]` takes a string `w` and "explodes" it into an array of `Char`s, which enables us to do arithmetic on it. The `String` call does the reverse, making a string from an array of `Char`s after the arithmetic operations are done. We have to subtract `'S'` and not 83, because `Char`-`Char` is an `Int` on which `%` works, whereas `Char`-`Int` is a `Char` which would lead to an error. Similarly, adding `'`'` changes the result of the mod from `Int` back to a `Char`, which is necessary for the `String` call to work. [Answer] # JavaScript, 93 bytes Takes input as an array of lowercase words, filters the array by the result of a lookup for the rot13 result. ``` d=>d.filter(t=>d.indexOf(t.replace(/[a-z]/ig,c=>((parseInt(c,36)+3)%26+10).toString(36)))>-1) ``` [Answer] # PHP, 60 bytes Given an array of words, echos only those having a rotonym match `foreach($l as$w)if(in_array($j=str_rot13($w),$l))echo"$w\n";` [Try it online!](https://tio.run/##DcxLCsMgEADQq4i4UJhN6TINvUghWDNRE6t2Yn69vHX94GWX6@OZXWYisJ7hmUMaUXLgwLjRBTwtsOMJBYk0WEKMYGODoqOFMVnQbzPiZJ2fl/CJKX83Wsu2H@f146qrUyLUxsn261Ucyk/Sx0G37ZJi7tdCA6Vyu8tmIIJSaFzi4nhF3tX6Bw "PHP – Try It Online") ]
[Question] [ # Introduction On the 26th of August, 2017, [Floyd Mayweather, Jr.](https://en.wikipedia.org/wiki/Floyd_Mayweather,_Jr.) will face up to [Conor McGregor](https://en.wikipedia.org/wiki/Conor_McGregor) in a boxing match. Both participants will receive the phenomenal amount of 100 million dollars! Unfortunately, we do not have the money yet, but we can already prepare the big briefcase that will contain all the banknotes. ``` _________________________ | | |=======================================| | $ $$$$$ $$$$$ $ $ | | $ $ $ $ $ $ $$$ $$$ | | $ $ $ $ $ $ $$$ $ | | $ $$$$$ $$$$$ $ $ | |_______________________________________| ``` The briefcase is composed of `_`,`|`,`=` and `$`. It has a size of 41 characters in width (ignoring the newlines) and 6 in height (+2 for the handle). # Challenge Given no input, write a full program to output a 2D briefcase (see above). # Score This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~92~~ 75 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁽©Ḍṃ“_= ”x"“€Þ‘x2,6¤;"⁾_|x1,7¤z⁶ZUŒBY”$“¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’BT+134¤¦ ``` **[Try it online!](https://tio.run/##y0rNyan8//9R495DKx/u6Hm4s/lRw5x4W4VHDXMrlIDMR01rDs971DCjwkjH7NASa6VHjfviayoMdcwPLal61LgtKvToJKdIoGIVoNpDi2wf7timXmJcqfZwR@vDHS0nlh7Z@HBHL5AFNrrh4c6FD3c0Pdw1OeDhjsUPdzYGPtw549Dek9MfNcx0CtE2NDY5tOTQsv//AQ "Jelly – Try It Online")** ### How? Step 1. Build a list of the rows of the right half of an empty briefcase, ignoring trailing spaces: ``` ⁽©Ḍṃ“_= ”x"“€Þ‘x2,6¤;"⁾_|x1,7¤ “_= ” - literal list of characters = "_= " ⁽©Ḍ - base 250 literal = 2674 ṃ - base decompress (2674 in base: 1='_', 2='=', 0=' ') - ...yields the list of characters: "_ = _" ¤ - nilad followed by link(s) as a nilad: “€Þ‘ - literal list of code page indexes = [12,20] 2,6 - literal list of numbers = [2,6] x - repeat -> [12,12,20,20,20,20,20,20] x - repeat -> ["_"*12, " "*12, "="*20, " "*20, ..., "_"*20] ¤ - nilad followed by link(s) as a nilad: ⁾_| - literal list of characters = "_|" 1,7 - literal list of numbers = [1,7] x - repeat -> list of characters "_|||||||" " - zip with the dyad: ; - concatenate -> ["_"+"_"*12, "|"+" "*12, ...] ``` Step 2: transform that into a whole empty briefcase: ``` z⁶ZUŒBY ⁶ - literal space character z - transpose with filler (adds the "leading" spaces, to the 1st 2 rows) Z - transpose (back from columns to rows again) U - upend (reverse each row to make it a left-hand side of an empty briefcase) ŒB - bounce (add a reflection of each row with one central character) Y - join with new lines ``` Step 3: Show me the money! ``` ”$“¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’BT+134¤¦ ¦ - sparse application of: ”$ - literal '$' character - ...to indexes: ¤ - nilad followed by link(s) as a nilad: “¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’ - base 250 literal = 1999171130867115278012045759181600763304793110829063794065408 B - convert to a binary list -> [1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,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] T - truthy indexes -> [1,4,5,6,7,8,11,12,13,14,15,18,26,39,43,46,50,53,57,60,61,62,66,67,68,85,88,92,95,99,102,105,106,107,110,127,130,131,132,133,134,137,138,139,140,141,144,152] 134 - literal 134 + - addition -> [135,138,139,140,141,142,145,146,147,148,149,152,160,173,177,180,184,187,191,194,195,196,200,201,202,219,222,226,229,233,236,239,240,241,244,261,264,265,266,267,268,271,272,273,274,275,278,286] - (that's where the $s at!) ``` [Answer] ## JavaScript (ES6), ~~187~~ 184 bytes ``` _=>`70 78B B2B 9F33CDB AEFEFEF54B 9FEFEFF6DB 9F33CDB B1B`.replace(/./g,c=>'__=$$$$ ||||$$$$'[n=+('0x'+c)].repeat(n>6?1:n?+'0005333'[n]||39:25)+' '.repeat(n-8?'0002632707307632'[n]:23)) ``` ### How? The output is built using these 16 unique patterns: ``` ID | Character | Repeated | Following spaces | Rendering ---+-----------+----------+------------------+------------------------------------------- 0 | _ | 25 | 0 | "_________________________" 1 | _ | 39 | 0 | "_______________________________________" 2 | = | 39 | 0 | "=======================================" 3 | $ | 5 | 2 | "$$$$$ " 4 | $ | 3 | 6 | "$$$ " 5 | $ | 3 | 3 | "$$$ " 6 | $ | 3 | 2 | "$$$ " 7 | space | 1 | 7 | " " 8 | | | 1 | 23 | "| " 9 | | | 1 | 7 | "| " A | | | 1 | 3 | "| " B | | | 1 | 0 | "|" C | $ | 1 | 7 | "$ " D | $ | 1 | 6 | "$ " E | $ | 1 | 3 | "$ " F | $ | 1 | 2 | "$ " ``` ### Demo ``` let f = _=>`70 78B B2B 9F33CDB AEFEFEF54B 9FEFEFF6DB 9F33CDB B1B`.replace(/./g,c=>'__=$$$$ ||||$$$$'[n=+('0x'+c)].repeat(n>6?1:n?+'0005333'[n]||39:25)+' '.repeat(n-8?'0002632707307632'[n]:23)) console.log(f()) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 80 bytes ``` •Cā½œSÖ<ô’=-¾Ì„*нcF/“è∊αΔú9d:î₅•6B5¡.B€û»•H0αű¼Āß8PβÁ19]× ôв•bvðy.;}4ÝJ"$ |=_"‡ ``` [Try it online!](https://tio.run/##AY0Acv8wNWFiMWX//@KAokPEgcK9xZNTw5Y8w7TigJk9LcK@w4zigJ4q0L1jRi/igJzDqOKIis6xzpTDujlkOsOu4oKF4oCiNkI1wqEuQuKCrMO7wrvigKJIMM6xw4XCscK8xIDDnzhQzrLDgTE5XcOXCsO00LLigKJidsOweS47fTTDnUoiJCB8PV8i4oCh//8 "05AB1E – Try It Online") --- # Explanation The basic outline of the briefcase: # [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes ``` •Cā½œSÖ<ô’=-¾Ì„*нcF/“è∊αΔú9d:î₅•6B5¡.B€û» ``` [Try it online!](https://tio.run/##AVMArP8wNWFiMWX//@KAokPEgcK9xZNTw5Y8w7TigJk9LcK@w4zigJ4q0L1jRi/igJzDqOKIis6xzpTDujlkOsOu4oKF4oCiNkI1wqEuQuKCrMO7wrv//w "05AB1E – Try It Online") **Sub-explanation explanation (part one):** I converted the overall design by cutting the design in half, replacing all characters with 2-6 and finally converting it to base 255 and reconstructing the shape using `5` as a newline delimiter. ``` •Cā½œSÖ<ô’=-¾Ì„*нcF/“è∊αΔú9d:î₅• # Push the base-255 compressed number 6B # Convert it to base-6 (the number of unique symbols) 5¡ # Split on 5 (the newlines). .B # Pad all elements with space to equal largest element length. €û # For each element, mirror it. » # Separate list with newlines. 77793946998265282127108152676813925695887415511783202442861719287811277 ``` Is the number that's expressed in base 255, and the base 6 conversion of it is... ``` 11111111444444444444511111111211111111111523333333333333333333525252525244444444444444444445 ``` Then, splitting that on fives, mirroring and joining by newlines gets us... ``` 111111114444444444444444444444411111111 111111112111111111111111111111211111111 233333333333333333333333333333333333332 2 2 2 2 2 2 2 2 244444444444444444444444444444444444442 ``` **Sub-explanation explanation (part two):** Starting to see where this is going? Next, I compress the inner pattern as a base-255 string: ``` •H0αű¼Āß8PβÁ19]× ôв• ``` Which is: ``` 353343914082943027578174279006736773101445087 ``` Convert to binary: ``` 1111110110000011000001101111111011111110111011011101101110110001110001111111111101101110110111011011000110111111111110110000011000001101111111011111 ``` For each of those characters, replace a space with the next character, iteratively: ``` 111111114444444444444444444444411111111 111111112111111111111111111111211111111 233333333333333333333333333333333333332 211111101100000110000011011111110111112 211011101101110110111011000111000111112 211111101101110110111011011000110111112 211111101100000110000011011111110111112 244444444444444444444444444444444444442 ``` Finally, replace the characters with what they're supposed to be. ``` 0 = '$' 1 = ' ' 2 = '|' 3 = '=' 4 = '_' 4ÝJ"$ |=_"‡ ``` For the loss: ``` _______________________ | | |=====================================| | $ $$$$$ $$$$$ $ $ | | $ $ $ $ $ $ $$$ $$$ | | $ $ $ $ $ $ $$$ $ | | $ $$$$$ $$$$$ $ $ | |_____________________________________| ``` --- By compressing it as two separate patterns I save 20 bytes over: ``` 7ºnF@É₄S¡‘nz'W›мλнbнžSÍõ₄óð½²Ç0Δεenë3aŽÖk∍&1ŒâÜ[¤öüuиSð±zαÛʸq¥KÃĀ›Ć^ü¹ÉRKq®Ùì=Ö‚≠ØÖì¾!(Δ∍Ú ``` Which is: ``` 111111114444444444444444444444411111111 111111112111111111111111111111211111111 233333333333333333333333333333333333332 211111101100000110000011011111110111112 211011101101110110111011000111000111112 211111101101110110111011011000110111112 211111101100000110000011011111110111112 244444444444444444444444444444444444442 ``` Converted to base-10: ``` 29962958783786255124710309272045448655717311098547870227488323781868803792449842685227629539722703574931794395923080776255103394202825327279714682601797290475465885089686540986020693577678744259173981845378875732421872 ``` 92 bytes plus the transliteration, which would total to about 105. [Answer] ## Bubblegum, 55 bytes Probably possible to do some header removal magic, but I'm not as good as Dennis! ``` 00000000: 5380 8278 5c80 0ba6 a246 013b a8e1 aab1 S..x\....F.;.... 00000010: 250e 0055 42f5 a800 1108 2028 9804 dc4c %..UB..... (...L 00000020: 2847 059d 0229 8790 6080 6a26 3a85 6c36 (G...)..`.j&:.l6 00000030: 49b6 c713 076a 00 I....j. ``` [Try it online!](https://tio.run/##dY6xTgMxEET7fMU0RKFZrdf2eh06ikRIdIiOAts5kKJQRsrfH3vKtZlid5p5ev3a@2X6vf7NM6/ZI0djmBRDHt64N0WTpOAQO5pNAa31AHwQ3b7Ic6CX5W3uhOAMyTyBOWck@ck@YkYIbBAWQzVOOI00gCeiz9dlTNj5eV8ZsjAsFXCuJ7BIhZXKUHYjbaKIzTJ0RAV2R18@E33Tebuni66M6IxUu2KUEMFFmxvhQd4WhTNt5vkf "Bubblegum – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 155 bytes ``` /~/\/\///2/ ~3/2 ~6/33~7/6 ~1/____~4/__111~5/411___~#/=============~%/$$$~&/%$$~9/$2$3$2$3$2~@/| |~8/@7$2&2&2$7$6/ 75 7|33377@###8@3$39%3%6@79$2%2$68@45| ``` [Try it online!](https://tio.run/##TYgxCkMhEET7fwrB9bfDuupqEfAggZAikCKdrezVjSHNf4@ZgRmf53i/xlow3LdAhHMmiM4KRExRnDEeG0t7mNkyEvPv8LhdsQAishNhdwNFkn@sYx7TKrpSPLekVOA0H06niKh2733tQtKChNK1UQyRSu0pz7W@ "/// – Try It Online") I love it when /// can compete. **Explanation:** This works by defining common replacements like `$$$$$`, then defining meta-replacements that include the original replacements. More in-depth: First of all, the only feature of /// is it's `/pattern/replacement/` syntax and it's ability to use backslashes to escape other backslashes and forward-slashes. This information is important in the explanation. The first pattern/replacement in the code is for golfing purposes only (and detailed [here](https://codegolf.stackexchange.com/a/120317/64159)). It replaces `~` with `//`, so the resulting code looks like this: ``` /2/ //3/2 //6/33//7/6 //1/____//4/__111//5/411___//#/=============//%/$$$//&/%$$//9/$2$3$2$3$2//@/| |//8/@7$2&2&2$7$6/ 75 7|33377@###8@3$39%3%6@79$2%2$68@45| ``` Then a bunch of basic replacements are made. Some rely on others (meta-replacements), but the table of replacements looks like this (code wrapped in ```s): ``` Pattern |Replacement ===================================== `2` |` ` ------------------------------------- `3` |` ` ------------------------------------- `6` |` ` ------------------------------------- `7` |` ` ------------------------------------- `1` |`____` ------------------------------------- `4` |`______________` ------------------------------------- `5` |`_________________________` ------------------------------------- `#` |`=============` ------------------------------------- `%` |`$$$` ------------------------------------- `&` |`$$$$$` ------------------------------------- `@` |`| ||` (Pipe, newline, pipe) ------------------------------------- ``` The meta-replacements here are things like `/&/%$$/`. This takes the already-existing replacement `$$$` and uses it to define a new replacement `$$$$$`. Then come the very large replacements. The first one replaces `9` with `$ $ $ $ $ $` and the second one replaces `8` with: ``` | | $ $$$$$ $$$$$ $ $ ``` Note the trailing spaces. Then all of these replacements are used in the following string: ``` 75 7|33377@###8@3$39%3%6@79$2%2$68@45| ``` To get the desired output. [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~58~~ 57 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ¹&‘┐4Ο"ε@»-⅜Η⁄№ν½7bč═⁴‘'⁴n{╥ι}¹54"~æαΟ9≠š:+VæΨT-⅟yu7‘'∑nž ``` Explanation: ``` ¹&‘┐ push 20 spaces 4Ο swap between the 20 spaces and "|" 9 times, resulting in "| | | | |" "...‘ push " _____________ | |====================ŗ____________________", with ŗ replaced with the string above '⁴n split into chunks of length 21 {╥ι}¹ palendromize horizontally "...‘ push the sign - " $ $$$$$ $$$$$ $ $$ $ $ $ $ $ $$$ $$$ $ $ $ $ $ $ $$$ $ $ $$$$$ $$$$$ $ $" '∑n split into chunks of length 30 54 ž at coordinates (5;4) place the sign in the briefcase ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUI5JTI2JXUyMDE4JXUyNTEwNCV1MDM5RiUyMiV1MDNCNUAlQkItJXUyMTVDJXUwMzk3JXUyMDQ0JXUyMTE2JXUwM0JEJUJEN2IldTAxMEQldTI1NTAldTIwNzQldTIwMTglMjcldTIwNzRuJTdCJXUyNTY1JXUwM0I5JTdEJUI5NTQlMjIlN0UlRTYldTAzQjEldTAzOUY5JXUyMjYwJXUwMTYxJTNBK1YlRTYldTAzQThULSV1MjE1Rnl1NyV1MjAxOCUyNyV1MjIxMW4ldTAxN0U_) ## 54 bytes ([competing?](https://codegolf.meta.stackexchange.com/q/12877/59183)) ``` ¹&‘┐4Ο"ε@»-⅜Η⁄№ν½7bč═⁴‘'⁴n╥ι54"~æαΟ9≠š:+VæΨT-⅟yu7‘'∑nž ``` The command used here is `╥` - palendromize, which only worked on strings, but [was documentated for arrays](https://github.com/dzaima/SOGL/blob/d11de364da6102d7e099881bcf43933263bd7edc/charDefsParser/data/charDefs.txt#L502) too. (currently it's only implemented on the online interpreter) [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUI5JTI2JXUyMDE4JXUyNTEwNCV1MDM5RiUyMiV1MDNCNUAlQkItJXUyMTVDJXUwMzk3JXUyMDQ0JXUyMTE2JXUwM0JEJUJEN2IldTAxMEQldTI1NTAldTIwNzQldTIwMTglMjcldTIwNzRuJXUyNTY1JXUwM0I5NTQlMjIlN0UlRTYldTAzQjEldTAzOUY5JXUyMjYwJXUwMTYxJTNBK1YlRTYldTAzQThULSV1MjE1Rnl1NyV1MjAxOCUyNyV1MjIxMW4ldTAxN0U_) [Answer] # PHP, 117 bytes I am sad that there is nothing shorter than the lazy approach - gzip the string and base64-encode it: ``` <?=gzinflate(base64_decode(U1CAgHhcACqvwAVj1ChgB3Bxrhpb4kANF0yPChCBAIJCSIDNBqtUgapEpVTADBUUlQpYVUKVYVVJwHacwYMKagA)); ``` --- Custom compression: **188 bytes** ``` for(;$c=" 6_777 6| 883| |=8899| | 5$ $3 $3 $ 5$ 4| | 1$ 1$ $ 1$ $ 1$ $1 1$1 4| | 5$ $ 1$ $ 1$ $ $2 $ 4| | 5$ $3 $3 $ 5$ 4| |_8899|"[$i++];)echo+$c?str_pad($d,$c+1,$d):$d=$c; ``` --- **~~168 164 159 152~~ 151 bytes** with an adaption of [officialaimm´s idea](https://codegolf.stackexchange.com/a/126895/55735): The lines can be seen as a bitmap between a boundary character (spaces for the first two, pipe after that), with space as `0` and another character as `1`. Inverting lines 3 and 8 gave them a value `0`, so I could shift all values by 6 bits. The array contains the bitmaps (converted to base 34; but only 7 values - the 8th element is omitted, an empty element evaluates to `0` as well). Base 35 would work as well; but base 33 has longer values and base 36 would need one more value quoted. The string contains the boundary, `0` and `1` characters in that order for each line (omitting the last character, because lines 3 and 8 need no `1` character, having no bit set). ``` for(;$i<8;)echo strtr(sprintf("b%039bb ",intval(["1g7em2",p3ob4,0,v839j,cm7f3d,sfxq9,v839j][+$i],34)<<6),b01,substr(" _ ||= | $| $| $| $|_",$i++*3)); ``` --- Custom compression by Jörg, **~~159~~ 156 bytes**: ``` <?=strtr("5 _2222 5 |555 | |===333333| |516161504$414141$$4$$0514141 6 051616150___222222|",["$ | |","$ $",______,"======"," "," ","$$$"]); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 114 bytes ``` “£zḂİẹḋmẋ>zạṾʂṀAYnŀ67ŻḢkðṡẉHLV'²ṙæṠṆoPẸCÞƒṿÑḢƲp4ƊƘṂɠ5×ṗ²X³⁻%ẹṄÑỊWÐh.ẹƁɗṫ0ạṢṆ@Gị}xM`JʠɠS"LṂÐ÷ṙḃ?ṄP9÷/⁵EṛṇD’ṃ“ ¶|=$_ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDi6se7mg6suHhrp0Pd3TnPtzVbVf1cNfChzv3nWp6uLPBMTLvaIOZ@dHdD3csyj684eHOhQ93dXr4hKkf2vRw58zDyx7uXPBwZ1t@wMNdO5wPzzs26eHO/YcnAtUe21Rgcqzr2IyHO5tOLjA9PP3hzumHNkUc2vyocbcqyKqdLUBlu7vCD0/I0APyjzWeBCpZbQC2eRHQRAf3h7u7ayt8E7xOLTi5IFjJB2jQ4QmHtwMtfbij2R6oP8Dy8Hb9R41bXR/unP1wZ7vLo4aZD3c2A32kcGhbja1K/P//AA "Jelly – Try It Online") [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 267 bytes ``` 764*.7,2-#&744742222222562222574474#&[# ][#_]# [# ]#|[# ]"| |"[#=]"| |"[# ]#$,.[#$]# .[#$]" $"[# ]#$,[# ]"| |"[# ]#$[# ]"$ $"[# ]"$ $"[# ]"$ "[#$][# ][#$][# ]"| |"[# ]"$ $"[# ]"$ $"[# ]#$[# ]#$,.[#$]" $"[# ]"| |"[# ]#$,.[#$]# .[#$]" $"[# ]#$,[# ]"| |"[#_]#|&@ ``` [Try it online!](https://tio.run/##SypKzMxLz89J@//f3MxES89cx0hXWc3cxMTcxAgCTM3AJFhIWS1aWSE2Wjk@VpkLxFKuAZFKNVw1StHKtjAGUFxFRy9aWSVWWQFMKSkoqMDEkTSA@GCuCkwelaUE0guxEELD9WHTATELZjPcShLdBPRZjZrD//8A "Braingolf – Try It Online") So golfy... [Answer] # [Python 2](https://docs.python.org/2/), 221 205 197 196 193 bytes * Saved 16 Bytes: Compression changed from 16-base to 36-base * Saved 8 bytes: Use of `a="6ZBRS533| $"` and `b="70JYF0U7|"` * Saved 1 byte: Switched from Python 3 to 2 * Saved 3 bytes: Removed a white-space and a pair of braces(after rearranging the string-replacement) ``` a="6ZBRS533| $" b="70JYF0U7|" for u in["6YKXAYYN _","6ZKFUZR3 |",b+"= ",a,"6JNFT2RJ| $","6ZFOPPKV| $",a,b+"_ "]:print u[-3]+bin(int(u[:-3],36))[2:].replace("1",u[-2]).replace("0",u[-1])+u[-3] ``` [Try it online!](https://tio.run/##RYzBCoJAFEX3fsXj0UJxCnVIQXBRi1komFhGowwyhpEQKqKLwH@30U3Lczj39t/x3bXOssgA3fycXo@UzrBDrQrQs0LOrMybUXt1A0zQtAW6PHqcOI8BSiRqErEsTynAjKQyMQAkUukwZjcnDdenNWKXJInuG8k1KwGF3w9NO8JU7Kkwq6bVFelT4Ssk1DWMwvHFYaj7j3zWOtpIVOkI46@sTdnCMLePZfkB "Python 2 – Try It Online") ### Explanation: Each line is in a generic form of `pup` where `p` is a boundary character and u is a string with two unique characters(for each line) which can be represented by 1 and 0. For example, line 5 is: `| $ $ $ $ $ $ $$$ $$$ |` It has | as boundary character and the middle string contains only and `$`. The middle string can be represented by: `111011101101110110111011000111000111111` Now this binary string can be represented by 36-base number: `6JNFT2RJ` We can represent all the lines by a definitive string along with the 36-base string, boundary character and the characters used in middle string as follows: ``` 111111100000000000000000000000001111111 "6YKXAYYN _" 111111101111111111111111111111101111111 "6ZKFUZR3 |" 111111111111111111111111111111111111111 "70JYF0U7|= " 111111101100000110000011011111110111111 "6ZBRS533| $" 111011101101110110111011000111000111111 "6JNFT2RJ| $" 111111101101110110111011011000110111111 "6ZFOPPKV| $" 111111101100000110000011011111110111111 "6ZBRS533| $" 111111111111111111111111111111111111111 "70JYF0U7|_ " ``` We can thus decompress the base-36 string (after extractcing it from the definitive string) to binary string, replace 1 and 0 by the characters(also obtained from the definitive string) used in the middle string and glue with boundary characters at both ends. Thus, required string is obtained. [Answer] # C, ~~415~~ ~~402~~ 397 bytes ``` #define P(x)D(x,4,4) #define S(r,c)i=r;j=c; #define D(x,c,n)for(k=x+n;x<k;t[i][j]=c)++x; t[8][41]={0};i,j,k;o(x){S(2,x)P(i)P(j)S(3,x)P(j)D(i,4,3)}f(){t[1][8]=t[1][32]=92;t[4][4]=4;S(0,7)D(j,63,25)S(1,0)D(i,92,6)D(j,63,39)S(2,0)D(j,29,39)S(1,40)D(i,92,6)S(2,9)P(i)o(12);o(19);S(2,26)P(i)i-=2;D(j,4,2)++i;D(j,4,3)--i;D(j,4,3)i-=2;P(i)for(i=0;i<8;++i,puts(t))for(j=0;j<41;)printf("%c",t[i][j++]+32);} ``` [Try it online!](https://tio.run/##TVDBasMwDL3nK0rHwCIKxI7XNai@7QMKOQYfhtcMuywtWQaBkG/PZHfdZjCWnp7ek@WKd@fW9eHt1Pn@tDmKCV7EhBo1ZHewEQM68GagYBz9wpHnsIfuMoizmfKepsOZxtbbNljjIM8nysZ2b1strZnLhTwGPNOFPeZGKJzgKDzfAI2oUhbY3LN5BUsnYB5babnfpLdS1tSK9TULWqOpESU@c0PAXYXqiUUklkmgVri7F6oaoleZclXfcon6HzPW6zTLRUgFPKCsgSKqdgn2hVEU@zUq/pb/iSsoir84kSI77sObkvxhT0zG69f4KUZIeGA8HLQkuA6@HzuxfXRbvO0sz21esf2ycmXz8ep7AdmcbfjwMihb1m8) [Answer] # [Retina](https://github.com/m-ender/retina), ~~140~~ ~~137~~ 129 bytes *-3 bytes thanks to @Neil* ``` 8aaaa_¶8|23|¶|bbbbbb===c3A3d3d3dAA3AAA6|¶|7d3d3d2AAd6caaaaaa___| d A2A c |¶|7A2AAAAA2AAAAA2A7A6|¶| b ====== a ______ A $ \d+ $* ``` [Try it online!](https://tio.run/##Ncs7CoAwEATQfk5hkUq7BNQmxdxDWPKxsLEQy5zLA3ixaFZ8C8uwn2M9tz3Uijm85L7mYl25rxKV9z45utyKdCTHtpx0YMk8pqBEpCCDlkjQkzc2f5@@T0R4hQBRIAyWPMD0Xa0P "Retina – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~388~~ ~~386~~ 302 bytes ``` char*r="8 24_08 1|22 1|01|37=1|01|6 1$2 5$2 5$2 1$7 1$5 1|01|2 1$3 1$2 1$3 1$2 1$3 1$2 3$3 3$5 1|01|6 1$2 1$3 1$2 1$3 1$2 1$2 3$2 1$5 1|01|6 1$2 5$2 5$2 1$7 1$5 1|01|37_1|";char d[9];main(i){do{if(*r==48)puts(""),r++;for(i=0;isdigit(*r);d[i++]=*r++);for(d[i]=0,i=atoi(d);i--;putchar(*r));}while(*r++);} ``` [Try it online!](https://tio.run/##fY/JCoMwEIZfJYiHRCuYxK2EPImISOIy0Nailh7Ux@7ZRm0plNLDzM/MfLMpr1ZqWVRTdE4nrQSxIPcTRCfGjPPpxGO5aYSozVD4MmrHxsIdWUO@lb@VG@VvLPqJ7Bj7TPuziMc5nSyxHot0eszEuYALBjLqdoQKmwdkkJDrbeixZZFD57qiajsM0hfQa6hhMAwROgXXzaRj6mQDTCKT/gFkMbSANRHgecKMWRetHUTM9wZOJd5b5mV5XFpPFaopnw "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 121 bytes ``` •?íLñ>ć£P¹ĀJδšlÔ@.ì@E'a‘2‡ΔÉ₅’Õ'8¾—Hú∊‹£ñ₂C*ƶ¬}ʒ³öG`ŒªKµδB₁вÑ(δüc›½ćˆ3αÂÝβ+Í‘]~é£42îĆ$Ÿ₅Ë!∊s₆L×ä5Uñ₁δǝβζ•6B•1’₃•" _ |=$"‡ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMi@8NrfQ5vtDvSfmhxwKGdRxq8zm05ujDn8BQHvcNrHFzVEx81zDB61LDw3JTDnY@aWh81zDw8Vd3i0L5HDVM8Du961NH1qGHnocWHNz5qanLWOrbt0JraU5MObT68zT3h6KRDq7wPbT23xelRU@OFTYcnapzbcnhP8qOGXYf2Hmk/3WZ8buPhpsNzz23SPtwLtCS27vDKQ4tNjA6vO9KmcnQH0K7D3YpA84sfNbX5HJ5@eIlpKMiWxnNbjgP1nNsGdLqZE5AwBDrpUVMzkKWkEM9VY6uiBHTt//8KUBCPC3DBVNQoYAc1QMOIA0CVUD0qQAQCCAohATUTylHBoFTADBUUlQpYVUKVYVVJwPZ44kANAA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), ~~177~~ 166 bytes ``` _=>` 8_25 8| 23| |=39| ${r='| 7$ 2$5 2$5 2$ 7$ 6|'} | 3$ ${s='3$ 2$ 3$ 2$ '}3$ 2$3 3$3 6| | 7$ 2$ ${s}2$3 2$ 6| ${r} |_39|`.replace(/(.)(\d+)/g,(_,b,c)=>b.repeat(c)) ``` The string holds a collection of the characters to display along with the number of times to repeat. If a character isn't repeated, the number of times can be omitted. Repeated string runs are optimized by storing in the variables `r` and `s`. **Snippet:** ``` f= _=>` 8_25 8| 23| |=39| ${r='| 7$ 2$5 2$5 2$ 7$ 6|'} | 3$ ${s='3$ 2$ 3$ 2$ '}3$ 2$3 3$3 6| | 7$ 2$ ${s}2$3 2$ 6| ${r} |_39|`.replace(/(.)(\d+)/g,(_,b,c)=>b.repeat(c)) console.log(f()); ``` [Answer] # [Python 2](https://docs.python.org/2/), 135 bytes ``` print'eNpTUICAeFwAKq/ABWPUKGAHcHGuGlviQA0XTI8KEIEAgkJIgM0Gq1SBqkSlVMAMFRSVClhVQpVhVUnA9njiQA0AtPhDOg=='.decode('base64').decode('zlib') ``` [Try it online!](https://tio.run/##PcvBDoIgGADgxyEvZa21Onj4NUViloZS11QmJkMsq9XL07p0/bbPvEfZ64W15tbqEYm9yQsSgIheQIcZ@Ke0oBjiKsYPrJ5tBu45J2sakhCabkeaxMXDnPlDxxRPIImOjAdK8sxwyQsNG339HRhTuT00noemtaj6WkxQebmL1RI5f/iotkSOtV8 "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ←×_²⁰↑⁵|×=²⁰↖↑←×_¹³↘↙|↓↷‖O”{“↷γαc7sa%}⦃N№T⊕VⅉH➙U₂&ηy ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJzWtREchJDM3tVhDKV5JR8HIQFPTmgsqG1qgo2AK5yrVKMHZUB22cB2@@WWpIA0gA5G4CLMwbDI0RuhzyS/PC8pMzyhBqAcJQfRA7c0syy8Bq9FA0QbkBKWm5aQml/iXpRblJBZoIBysAgQxeQowjEZAMUQRCEJYKmBZFJJkFRCooAJ0@P///3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ←×_²⁰↑⁵|×=²⁰↖↑←×_¹³↘↙| ``` Print the left half of the briefcase. ``` ↓↷ ``` Prepare the cursor so that the compressed string can be printed directly after reflecting. (Putting the downward movement after the reflection or before the compressed string changes their meaning.) ``` ‖O ``` Reflect to complete the briefcase. ``` ”{“↷γαc7sa%}⦃N№T⊕VⅉH➙U₂&ηy ``` Print the amount as a compressed string. (Sadly this was the shortest approach, as otherwise the `M` consumed too many bytes.) [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 751 bytes ``` {iii}iicccccccc{iiiiii}iii{cc}ccccc{{d}ii}dddddc{ii}iicccccccc{{i}d}iic{{d}i}dd{cc}ccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{dddddd}ddd{cc}{c}ccccccccc{iiiiii}iiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccccccciiiicddddcciiiicccccddddcciiiicccccddddcciiiicddddccccccciiiicddddcccccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccciiiicddddccciiiicddddcciiiicddddccciiiicddddcciiiicddddccciiiicddddcciiiicccddddccciiiicccddddcccccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccccccciiiicddddcciiiicddddccciiiicddddcciiiicddddccciiiicddddcciiiicddddcciiiicccddddcciiiicddddcccccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddccccccciiiicddddcciiiicccccddddcciiiicccccddddcciiiicddddccccccciiiicddddcccccc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{ddd}i{cc}{c}ccccccccc{iii}dc ``` [Try it online!](https://tio.run/##vVLtCoAwCHyiHiq0yN/9FJ99@QXVWFENEgZ63umxDacRZ1qXoRQmIiGCDCsDIQaQwBi1FrQwwpHOilvtHKWk6ISLntAqKuzDtePzvGMizmWVibsBuTJFjjkrUovrMtJaCA@t75uP4trBOxhODfjsCLqdNEx13dHfr2O/ilp/ShBK2QA "Deadfish~ – Try It Online") Only eight or nine times longer than the others... ]
[Question] [ # The House of Santa Claus **Note:** This is the first challenge that I have attempted to set. It has been through the Sandbox however if you find something wrong with it please do not just downvote but leave a comment so that I can improve it. **Background** There is a old childrens puzzle where the challenge is to draw a box with a roof and a cross through the middle without lifting your pen from the paper or going over any line twice. In Germany it is known as "das Haus des Nikolaus" or "The House of Santa Claus". I honestly can't remember what we used to call it. For anyone who is not familiar with the puzzle, full details are available [here](http://www.mathematische-basteleien.de/house.html). Here is an ASCII art representation of the house. ``` /\ /__\ |\/| |/\| ---- ``` **Challenge** Write a program or function to draw the House of Santa Claus in any language of your choice. Sounds too easy? Well here's the catch. It must also output each stage of the drawing and comply with the rules of the puzzle. Your program is not required to take any input. The finished house must look exactly as shown above. According to the site above there are 44 possible solutions. You may use any one of them. This is an ASCII art challenge so you are not required to calculate the solution but only to draw it. **Output** An example of the required output from one of the 44 solutions is shown below: ``` ---- \ \ ---- __ \ \ ---- \ __\ \ \ ---- /\ /__\ \ \ ---- /\ /__\ |\ | \ ---- /\ /__\ |\/ |/\ ---- /\ /__\ |\/| |/\| ---- ``` **Rules** * I have added 1 extra newline between each expected output to try to make the requirements clearer. This is optional. Any number of blank lines between each output is allowed. * Your output must consist only of the characters /,\,-,\_, and space as shown above. Trailing spaces are allowed. * Each line in your drawing must continue from the end of the previous line and you may not repeat any line. * Standard loopholes prohibited. * You are not required to output the rhyme mentioned in the above link. * This is code golf so the shortest answer in bytes will be the winner. **Result** Some great answers and thanks and respect to all who posted. I did say lowest byte count but I have marked as top answer not just for that but also for the great explanation of the code. Nice one @Dennis. [Answer] ## Javascript (ES6), ~~119~~ ~~116~~ ~~96~~ ~~92~~ 91 bytes ``` for(i=8;i--;)console.log(`834 3554 2610 2160 7777`.replace(/./g,c=>'|/|/\\_\\- '[c<i?8:c])) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ ~~39~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ḥ%DtƊVḍI’ḃ9W;“|_/-\/\|‘ˤy@\FỌ»⁶s4Y ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4bilJUR0xopW4biNSeKAmeG4gzlXO-KAnHxfLy1cL1x84oCYxJbCpHlAXEbhu4zCu-KBtnM0WQ&input=) ### How it works ``` “ḥ%DtƊVḍI’ ``` is a bijective base-250 literal; each character corresponds to its code point in [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page). The result is the integer **13192938935880491074**. ``` ḃ9 ``` converts the generated integer to bijective base 9, yielding the integer array **[9, 6, 7, 9, 6, 2, 2, 7, 1, 5, 3, 8, 1, 3, 5, 8, 4, 4, 4, 4]**. The integers correspond to the order of the stroke, with the exception of **9**, which indicates a space. ``` W ``` wraps the generated array into a singleton array, which will be required to prepend it to the array we'll generate now. ``` “|_/-\/\|‘ˤ ``` works as follows. `¤` combines the two links to the left into a niladic chain. The first one, `“|_/-\/\|‘` yields the code points of the specified characters, yielding **[124, 95, 47, 45, 92, 47, 92, 124]**. Then, `Ė` enumerates the code points, yielding **[[1, 124], [2, 95], [3, 47], [4, 45], [5, 92], [6, 47], [7, 92], [8, 124]]**. The pair **[n, c]** means that the **n**th stroke will be the ASCII character with code point **c**. ``` ; ``` concatenates the generated arrays. The result is the array **[[9,6,7,9,6,2,2,7,1,5,3,8,1,3,5,8,4,4,4,4],[1,124],[2,95],[3,47],[4,45],[5,92],[6,47],[7,92],[8,124]]**. ``` y@\ ``` performs a cumulative (i. e., showing all intermediate steps) reduce, using transliteration (`y`) with swapped arguments (`@`). In the first step, e.g., we replace each **1** in the original array with **124**, which is the code point of the character **|**. ``` FỌ ``` flattens the result and replaces all code points with the corresponding ASCII characters. In all steps, this will generate some unprintable characters with code points **1** to **9**. ``` »⁶ ``` takes the character-wise maximum with the space character, replacing all unprintable characters with spaces. ``` s4Y ``` splits the generated string into chunks of length four and joins them with a linefeed as separator. [Answer] ## Batch, ~~356~~ ~~344~~ ~~341~~ 337 bytes ``` @set s=@set " %s%g=@goto 1 %s%r= %s%c= %s%u=| %s%l=| %s%f= @for /l %%i in (1,1,7)do @call:%%i %s%u=|\/| %s%l=|/\| %g% :7 %s%u=|\/ %s%l=|/\ %g% :6 %s%f=---- %g% :5 %s%u=|\ %s%l=| \ %g% :4 %s%c=/__\ %g% :3 %s%r= /\ %s%c=/ \ %g% :2 %s%r= / %s%c=/ :1 @for %%l in ("%r%" "%c%" "%u%" "%l%" "%f%")do @echo(%%~l ``` ~~Stupid Batch `|` quoting rules... if you want a `|` in a variable, you need to quote it with three `^`s, so it's cheaper to use `@` instead and substitute it on output, although to achieve this I have to start with the left wall. Line one has a trailing space.~~ `echo(` is used because the `r`, `c`, and `f` variables could be empty and we don't want `ECHO is off.` printed. Edit: Saved 12 bytes by using fallthrough for the last part. Saved 3 bytes by using a `for` loop to print each part, this means that I now use `|`s in my variables which makes the code slightly easier to read. Saved 4 bytes by using explicit `@` characters instead of `@echo off`. I think starting with the left wall still requires the fewest bytes. [Answer] # C, 118 bytes ``` main(){char *p,n;for(n='B';n++<'J';)for(p="ZFEAFDDEAGCHIAGHCIABBBBAA";*p;p++)putchar(" \n-\\_\\/|/|"[(*p<n)**p&15]);} ``` [Answer] # [///](http://esolangs.org/wiki////), 112 bytes ``` /!/\/\///*/---- !@/\\\\!$/ @@!^/ *@\/@@ @\/__@@ /*@ $ *__ $ $ *$ __@ $ $^$ $^|@ |$^|@\/ |\/@^|@\/| |\/@| * ``` [Try it online!](//slashes.tryitonline.net#code=LyEvXC9cLy8vKi8tLS0tCiAhQC9cXFxcISQvIEBAIV4vCipAXC9AQApAXC9fX0BACi8qQAogJAoqX18KJAogJAoqJAogX19ACiQKICReJAogJF58QAp8JF58QFwvCnxcL0BefEBcL3wKfFwvQHwKKg) [Answer] # PHP, ~~98~~ 95 bytes inspired by [Arnauld´s solution](https://codegolf.stackexchange.com/q/93616#93616) ``` for($i=8;$i--;)for($p=24;$p--;)echo"|/|/\\_\\- "[($c="977779061290162945539438"[$p])<$i?8:$c]; ``` Note: The first code line has a trailing space. [Answer] # PHP with GD, ~~348~~ 338 bytes (not competing) not exactly what was being asked for, but ... ``` function f($v,$w){global$x,$y,$i;imageline($i,$x,$y,$x=$v,$y=$w,1);ob_start();imagepng($i);$s=ob_get_clean();ob_end_clean();echo'<img src="data:image/png;base64,',base64_encode($s),'" > ';}$i=imagecreate($w=9,$h=$w+$z=$w/2);imagecolorallocate($i,255,255,255);f(--$w,$y=--$h);f(0,$z);f($w,$z);f($w/2,0);f(0,$z);f(0,$h);f($w,$z);f($w,$h); ``` save to file, call in a browser **breakdown** ``` function f($v,$w) { global$x,$y,$i; imageline($i,$x,$y,$x=$v,$y=$w,1); // draw line, set end coords as new start coords ob_start();imagepng($i);$s=ob_get_clean();ob_end_clean(); // get image output echo'<img src="data:image/png;base64,',base64_encode($s),'" > '; // print <img> tag } // calculate dimensions, create image, allocate background color (foreground implicitly black) $i=imagecreate($w=9,$h=$w+$z=$w/2);imagecolorallocate($i,255,255,255); // paint lines: implicit `$x=0` f(--$w,$y=--$h);f(0,$z);f($w,$z);f($w/2,0);f(0,$z);f(0,$h);f($w,$z);f($w,$h); ``` To draw a larger house, change `$w=9` to your desired width. ]
[Question] [ Every player has a number. Can yours be the farthest from them all? ## Requirements Write a Java, Python 2, or Ruby function named `choose()` that accepts three arguments: * an integer - the number of rounds already completed * an integer - the number of players * an array of strings - the results of each previous round + each string is a space-separated list of integers, sorted from lowest to highest For example, `choose(2, 4, ["4 93 93 174", "1 84 234 555"])` means: * there were already two rounds (this is the third round) * there are a total of four players * in the first round, the numbers chosen were 4, 93, 93, 174 * in the second round, the numbers chosen were 1, 84, 234, 555 You must return a whole number from 1 to 999 (inclusive). For each other player, your score is the square root of the distance between your number and theirs. Your score for the round is the total of all of these scores. 100 rounds will be played. The highest total score wins! ## Rules * Your code may not use any I/O, including console, files, network, etc. * You may not interfere with the control program or any other players. * Programs which look like they violate the above rules will be excluded. * Each call of a function should take under five seconds on my computer (Intel Core i5 2450M with 8GB of RAM). * If a program throws an exception or returns an invalid value, it will be treated as if it returned 1. * Each user may submit at most one program. ## Miscellaneous * The control program is [on GitHub](https://github.com/Ypnypn/src). * There are three built-in players. They can be found in [this answer](https://codegolf.stackexchange.com/a/44782/16294). * The winner will be chosen on January 28. ## Leaderboard The winner is [Conservator](https://codegolf.stackexchange.com/a/44802/16294). Honorable mention to [Gustav](https://codegolf.stackexchange.com/a/45001/16294), the highest scoring player with a non-constant strategy. * Conservator - 36226 * High - 36115 * FloorHugger - 35880 * NumberOne - 35791 * Overestimator - 35791 * Gustav - 35484 * Historian - 35201 * Sampler - 34960 * Incrementer - 34351 * JumpRightIn - 34074 * Vickrey - 34020 * Teenager - 33907 * Randu - 33891 * Weightlifter - 33682 * Middleman - 33647 * BounceInwards - 33529 * NastyMathematician - 33292 * Jumper - 33244 * Copycat - 33049 The full results can be found [here](http://pastebin.com/W42DHeGd). (I recommend disabling text wrapping.) [Answer] ## Python, Conservator ``` def choose(round, players, scores): return 999 ``` Since every exception throws 1, it stays away as much as possible from it. Makes its fortune at the expense of the weak. Fun fact: I thought about improving it, but couldn't find a better way than just hiding in a corner. [Answer] # Number One, Java The name explains this one completely. ``` public static int choose(int round, int players, String[] args) { return 1; } ``` [Answer] # Python, AncientHistorian Firmly believes that the future will be exactly like the past, but believes the last round is too recent to be histiry, so it just loops through 1 - 999 and chooses what would have been the best the previous rounds exept the last. First 2 round returns 500. ``` def choose(round, players, scores): calc = lambda n, scores: sum([abs(int(i)-n)**.5 for i in scores.split(' ')]) return max(range(1, 1000), key=lambda n: sum([calc(n, j) for j in scores[1:]])) if round>1 else 500 ``` [Answer] # Python, Vickrey ``` def choose(rounds, players, results): if not results: return (id(0)/7)%999 + 1 def best(array): score = lambda x: sum(abs(x-y)**.5 for y in array) m = max(score(x) for x in range(1, 1000)) return [x for x in range(1, 1000) if score(x) == m] def second_best(array): array.extend(best(array)) options = best(array) return options[(id(0)/7) % len(options)] results = [map(int, s.split()) for s in results] counts = {} for round_ in results: for number in round_: counts[number] = counts.get(number, 0) + 1 most_common = sorted([(c, n) for n,c in counts.items()], reverse=True) to_avoid = [t[1] for t in most_common[:players]] return second_best(to_avoid) ``` Makes a list of numbers which have been played often, assumes that everyone else will play optimally and opts for the *second* best choice given the list. For example, if the most common numbers are `[1, 990, 999]`, then Vickrey inserts the optimal play 200 to give `[1, 200, 990, 999]`, then picks the best option for the new array (which is 556). [Answer] ## Java, Overestimator As the name suggests, this program assumes all the other programs will try to play "well" by picking the best answer based on the last round - so this "overestimator" always picks the **worst** possible position based on the previous round. ``` public static int choose(int round, int players, String[] args) { String[] lastRoundStrings = args[args.length - 1].split(" "); int[] lastRound = new int[lastRoundStrings.length]; int worstSelection = 0; for (int i = 0; i < lastRound.length; i++) { double worstScore = Double.MAX_VALUE; for (int j = 1; j < 999; j++) { double computedScore = score(j, lastRound); if (computedScore < worstScore) { worstScore = computedScore; worstSelection = j; } } } return worstSelection; } public static double score(int position, int[] otherPositions) { double total = 0; for (int i = 0; i < otherPositions.length; i++) { total += Math.sqrt(Math.abs(otherPositions[i] - position)); } return total; } ``` [Answer] # Java - Weightlifter Loops through 1-999 to figure out which would be the best for each round. Weighs them according to recency (recent rounds have more weight), and returns its best overall guess. Hopefully if patterns form in later round, this will be able to pick up on it. **Edit: Now with +Inf% more recursion!** Not being able to store/save/see what you chose on previous rounds is a drag. Taking your own inputs into account messes you up when trying to figure out what *others* are going to do. So, let's compute it! This will now recurse to figure out what it chose on the previous round and ignore that when calculating the next move. Note that it only *really* ignores its own input from the last turn, but since that one is weighted the highest, it seems to work okay. This could be fixed with a bit more work, but I'll wait for the leaderboard to see if it's needed. ``` int choose(int rounds, int players, String[] hist){ if(rounds < 1) return 1; int lastChoice = choose(rounds-1,players,java.util.Arrays.copyOf(hist, hist.length-1)); int[][] history = new int[hist.length][players]; for(int i=0;i<hist.length;i++){ String[] tokens = hist[i].split(" "); boolean flag = false; for(int j=0;j<tokens.length;j++){ history[i][j] = Integer.parseInt(tokens[j]); if(i==history.length-1 && history[i][j]==lastChoice && !flag){ flag = true; history[i][j] = -1; } } } double best = 0; int guess = 1; for(int i=1;i<1000;i++){ double score = 0; for(int j=0;j<history.length;j++){ double weight = (double)(j+1)/history.length; for(int k=0;k<history[j].length;k++){ if(history[j][k] > 0) score += Math.sqrt(Math.abs(history[j][k]-i)) * weight; } } if(score > best){ best = score; guess = i; } } return guess; } ``` [Answer] # Ruby, Copycat Simply returns whichever number won last time. ``` def choose r, p, hist last = hist.last.split.map &:to_i scores = last.map{|n| last.map{|m| (n-m).abs ** 0.5 }.inject :+ } last[scores.index scores.max] end ``` [Answer] # Ruby, JumpRightIn ``` def choose(round, players, args) return 500 if args.size == 0 last_round = args[-1].split.map(&:to_i) + [1000] max_gap = 0 last = 0 move = 1 last_round.each { |i| gap = i - last - 1 if gap > max_gap max_gap = gap move = (i + last)/2 end last = i } move end ``` It's probably the most straight-forward strategy. It finds the largest gap in the last round, and chooses the number right in the middle of that gap. [Answer] # Gustav (Python 2) This is a pretty straight forward meta strategy, shamelessly copied from one of my old [answers](https://codegolf.stackexchange.com/a/35006/29703) in a similar KotH challenge. It considers a few simple strategies, looks how they would have performed over all previous rounds, and then follows the highest scoring one for the next round. ``` def choose(k, N, h): if k<2: return 999 H = [[int(x) for x in l.split()] for l in h] score = lambda x,l: sum(abs(x-y)**.5 for y in l) S = [range(1,1000) + [max(range(1,1000), key=lambda x: score(x, H[i-1]))] + [max(range(1,1000), key=lambda x: score(x, H[i-2]))] + [min(range(1,1000), key=lambda x: score(x, H[i-1]))] + [min(range(1,1000), key=lambda x: score(x, H[i-2]))] for i in range(2,k+1)] scores = [sum(score(s[j],l) for s,l in zip(S[:-1], H[2:])) for j in range(len(S[0]))] return max(zip(scores, S[-1]))[1] ``` I realize now that the algorithm still has some flaws. E.g. it might keep "chasing itself" because it does not distinguish its own moves from those of the opponents. However, I'll leave it like this for now. [Answer] # Python, Randu Numbers selected by [the most ill-conceived random number generator ever](https://en.wikipedia.org/wiki/RANDU). ``` def choose(round, players, scores): x = 15 for i in range(round * players + 1): x = (x * 65539) % 2147483648 y = int((x / 2147483648.0) * 999.0)+1 return y ``` [Answer] The following three programs are built-in. ## High (Ruby) ``` def choose(round, players, args) return 990 end ``` ## Incrementer (Java) ``` public static int choose(int round, int players, String[] args) { return round * 10 + 5; } ``` ## FloorHugger (Python) ``` def choose(round, players, args): if len(args) == 0: return 10 last = args[-1].split(); # next line from http://stackoverflow.com/a/7368801/3148067 last = map(int, last) dist = 0 for i in range(1, 999): if i in last: dist = 0 else: dist = dist + 1 if dist == 10: return i return 500 ``` [Answer] # Python, Sampler Out of a list of places, choose the one that is farthest away from recently used numbers, ignoring the previous turn. ``` def choose(turn, players, history): sample = map(int, (' '.join( history[-5:-1] )).split()) def distance(x): return sum(abs(x-y)**0.5 for y in sample) places = range(1, 1000, 13) score, place = max((distance(x), x) for x in places) return place ``` [Answer] ## Java, BounceInwards Starting at 1, it gradually gets closer to 500 while bouncing between the higher and lower option. ``` public static int choose(int round, int players, String[] args) { return round%2 == 0 ? round * 5 : 1000 - round * 5; } ``` [Answer] ## NastyMathematician (Java) Examines the last two rounds (if the best numbers were 70 and 80, it will output 90). It is nasty because it tries to take as high numbers as possible to win against his opponents. ``` public static int choose(int round, int players, String[] args) { if (round == 0) { return 999; } int[][] results = new int[args.length][players]; // parse input for (int i = 0; i < args.length; i++) { String[] rounds = args[i].split(" "); for (int j = 0; j < rounds.length; j++) { results[i][j] = Integer.parseInt(rounds[j]); } } int bestNumber = 0; double bestScore = -1; // get the best number for the last round for (int i = 1; i < 1000; i++) { double score = 0; for (int result : results[results.length - 1]) { score += Math.sqrt(Math.abs(i - result)); } if (score >= bestScore) { bestScore = score; bestNumber = i; } } if (round == 1) { return bestNumber; } int bestNumber2 = 0; double bestScore2 = -1; // get the best number for the second last round for (int i = 1; i < 1000; i++) { double score = 0; for (int result : results[results.length - 2]) { score += Math.sqrt(Math.abs(i - result)); } if (score > bestScore2) { bestScore2 = score; bestNumber2 = i; } } // add the difference between last round and second last round to get this rounds best number int difference = bestNumber - bestNumber2; bestNumber = bestNumber + difference; return bestNumber > 999 ? 999 : bestNumber; } ``` [Answer] # Python - I don't want to think of a name... If the average of the numbers chosen in the past rounds is less than 500, it picks 999. It picks 1 otherwise. ``` def choose(a,b,c): total=0 for i in c: for j in i.split(" "): total+=int(i) average=total/(a*b) if average<500: return 999 return 1 ``` [Answer] ## Python, Middleman (based on conservator by @clabacchio) ``` def choose(round, players, scores): return 500; ``` After I noticed that the upper edge scores high (and outperformed the lower edge), I wondered whether there could be anything worse than just getting caught in the middle. [Answer] # Jumper (Ruby) ``` def choose(round, players, args) 495*(round%3)+5 end ``` Alternates between bottom, middle and top. (5,500,995) ]
[Question] [ Here is a list of the 118 (current) elements of the periodic table (in a collapsed Stack Snippet for your convenience): ``` Hydrogen Helium Lithium Beryllium Boron Carbon Nitrogen Oxygen Fluorine Neon Sodium Magnesium Aluminium Silicon Phosphorus Sulfur Chlorine Argon Potassium Calcium Scandium Titanium Vanadium Chromium Manganese Iron Cobalt Nickel Copper Zinc Gallium Germanium Arsenic Selenium Bromine Krypton Rubidium Strontium Yttrium Zirconium Niobium Molybdenum Technetium Ruthenium Rhodium Palladium Silver Cadmium Indium Tin Antimony Tellurium Iodine Xenon Caesium Barium Lanthanum Cerium Praseodymium Neodymium Promethium Samarium Europium Gadolinium Terbium Dysprosium Holmium Erbium Thulium Ytterbium Lutetium Hafnium Tantalum Tungsten Rhenium Osmium Iridium Platinum Gold Mercury Thallium Lead Bismuth Polonium Astatine Radon Francium Radium Actinium Thorium Protactinium Uranium Neptunium Plutonium Americium Curium Berkelium Californium Einsteinium Fermium Mendelevium Nobelium Lawrencium Rutherfordium Dubnium Seaborgium Bohrium Hassium Meitnerium Darmstadtium Roentgenium Copernicium Ununtrium Flerovium Ununpentium Livermorium Ununseptium Ununoctium ``` *Note: This list was found by running the following JavaScript code on [this Wikipedia page](https://en.wikipedia.org/wiki/List_of_elements): `[].slice.call($('.wikitable:first tr td:nth-child(3)').map(function(){return this.innerText})).slice(1,-1).join('\n')`* Your challenge is to output as many of them as possible, in as many languages as possible. This goal is even further complicated by the fact that the radioactive elements are slowly eating away at your remaining usable characters as you go! ## Rules 1. Your answer will consist of 1 to 95 code snippets. 2. Each code snippet must be in a different programming language. For the purpose of this challenge, I'm using a very loose definition of "language": Anything that's not backwards-compatible is a different language. For example, if all Lang A code works in Lang B but Lang B adds more, then they're considered the same language. But Python 2 and Python 3 are considered different, because `print 'foo'` is valid in Python 2 but not in Python 3. 3. The first code snippet may use some or all of the 95 printable ASCII characters. In the second snippet, one ASCII character of your choice will be forbidden. In the third snippet, that character plus one more of your choice must be forbidden. And so on. Tabs and newlines are never forbidden. 4. The forbidden character **must** have been used in the previous snippet, *not* in a comment, string literal, etc.; it must actually get interpreted by the compiler/interpreter. For example, if my first snippet is `print 'Hydrogen'`, I can't make `&` forbidden because I didn't use it. My choices are any of the characters `p`, `r`, `i`, `n`, `t`, , or `'` (I can't use `H`, `y`, `d`, ... because those are in a string literal). The character you choose is from then on forbidden to appear at all in any subsequent snippets. 5. Each code snippet must output a unique element of the periodic table (found in the list above). "Output" can be done by any method you wish: STDOUT, an alert box (ex. in JS), REPL "output" (keep in mind that if it includes quotes, it's invalid), writing to a file, etc. 6. You must either take no input, or an empty string as input (for languages like sed). 7. You may not use built-in functions that return the element name (ex. `ElementData` in Mathematica). ## Formatting Please format your answer with the following format: ``` ### 1. Language A - none forbidden code Optional commentary on this snippet goes here. ### 2. Language B - `a` forbidden code More optional commentary ### 3. Language C - `ab` forbidden code More optional commentary ``` etc. If backticks (```) are forbidden, simply use two backticks around the list instead. For example, ```ab`cd``` will result in `ab`cd`. (If the backtick is the first or last character, you must also pad the outer backticks with spaces; ex. ``` abc` ``` -> `abc``.) ## Scoring The answer with the most programming languages will win. In the event of a tie, the answer with the smallest cumulative character count of all of the programs will win. --- This question was [inspired by this.](https://codegolf.stackexchange.com/q/40562/3808) [Answer] # 51 Languages I might add to this later, but here are 51 languages. ### 1. Java - none forbidden ``` public class p{public static void main(String[]J){System.out.println("Tellurium");}} ``` ### 2. C++ - `J` forbidden ``` #include<cstdio> main(){int Q=std::puts("Palladium");} ``` ### 3. C - `JQ` forbidden ``` main(W){puts("Neodymium");} ``` ### 4. D - `JQW` forbidden ``` import std.stdio;void main(string[]z){write("Zirconium");} ``` ### 5. Nimrod - `JQWz` forbidden ``` var q="Ruthenium" echo q ``` ### 6. Fortran-95 - `JQWzq` forbidden ``` program Y print *,"Potassium" end program Y ``` ### 7. Batch - `JQWzqY` forbidden ``` @set @c=Aluminium&echo %@c% ``` ### 8. Befunge - `JQWzqY%` forbidden ``` "muinoloP">:#,_@ ``` Output Polonium. ### 9. Vala - `JQWzqY#%` forbidden ``` int main(string[]@a){print("Manganese");return 0;} ``` ### 10. Bash - `JQWzqY#%@` forbidden ``` cd /usr/bin ~/cake;./echo Germanium ``` ### 11. ECMAScript 6 - `JQWzqY#%@~` forbidden ``` alert(`Strontium`) ``` ### 12. Perl 5 - `JQWzqY#%@~`` forbidden ``` $_=Magnesium;say ``` ### 13. Scala - `JQWzqY#%@~`_` forbidden ``` object e{def main(args:Array[String]){print("\u0059tterbium")}} ``` ### 14. Perl 6 - `JQWzqY#%@~`_:` forbidden ``` $j='Lanthanum';say ``` ### 15. Python 2 - `JQWzqY#%@~`_:j` forbidden ``` print'Lutetium' ``` ### 16. Python 3 - `JQWzqY#%@~`_:jL` forbidden ``` print('Krypton') ``` ### 17. PHP - `JQWzqY#%@~`_:jLK` forbidden ``` $n='Berkelium';echo$n; ``` ### 18. Pascal - `JQWzqY#%@~`_:jLK$` forbidden ``` Program f(X);begin write('Ununtrium');end. ``` ### 19. POGAACK - `JQWzqY#%@~`_:jLK$X` forbidden ``` poock!pogack?poock!pock!pock!pock!pock!pock!pock!pogack!pogaaack!pogaack!pogaack?pogack!poock!pogaaack?pogack?poock!pock!pock!pogack!pogaaack!pock!pock!pock!pock!pogaack!pogaack?pogack!pogaaack!pogaaack?poock!pock!pogack?poock!pogack!pogaaack!pock!pock!pogaack!pogaack?pogack!poock!pogaaack?pogaaack!pock!pock!pock!pock!pock!pock!pock!pock!pock!pock!pock!pock!pock!pogaaack?poock!pock!pock!pogaaack?poock!pock!pock!pock!pock!pock!pock!pock!pogaaack?poock!pock!pogaaack?pogaaack!pock!pock!pock!pock!pock!pock!pock!pogaaack? ``` Prints Hydrogen. ### 20. COW - `JQWzqY#%@~`_:jLK$Xg` forbidden ``` MoOMoOMoOMoOMOOmoOMoOMoOMoOMoOMoOmOoMOomoomoOMOOmoOMoOMoOMoOMoOmOoMOomoomoOMooMoOMOOMOoMOoMOomoOMoOMoOMoOMoOmOomoomoOMooMoOMoOMoOMoOMoOMoOMoOMoOMoOMooMOoMooMOoMOoMOoMOoMOoMooMOoMooMOoMOoMOoMOoMOoMooMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMooMOoMOoMOoMOoMOoMOoMOoMOoMoo ``` Prints Plutonium. ### 21. Blub - `JQWzqY#%@~`_:jLK$XgM` forbidden ``` Blub!Blub!Blub!Blub?Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub?Blub.Blub.Blub?Blub.Blub?Blub!Blub.Blub?Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub!Blub!Blub!Blub!Blub!Blub?Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub?Blub.Blub.Blub?Blub.Blub?Blub!Blub.Blub?Blub!Blub.Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub!Blub.Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub!Blub.Blub!Blub?Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub.Blub?Blub.Blub.Blub?Blub.Blub?Blub!Blub.Blub?Blub!Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub.Blub!Blub.Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub!Blub. ``` Prints Flerovium. ### 22. Ook!- `JQWzqY#%@~`_:jLK$XgMB` forbidden ``` Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook?Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook?Ook.Ook.Ook?Ook.Ook?Ook!Ook.Ook?Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook?Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook?Ook.Ook.Ook?Ook.Ook?Ook!Ook.Ook?Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook. ``` Prints Americium. ### 23. Ruby - `JQWzqY#%@~`_:jLK$XgMB!` forbidden ``` def e?()return "Neptunium"end;print e? ``` ### 24. Lua - `JQWzqY#%@~`_:jLK$XgMB!?` forbidden ``` f=2*4 if f==8then print("Titanium")end ``` ### 25. R - `JQWzqY#%@~`_:jLK$XgMB!?*` forbidden ``` U<-"Rubidium";print(U) ``` ### 26. Scheme - `JQWzqY#%@~`_:jLK$XgMB!?*U` forbidden ``` (display "Francium") ``` ### 27. TI Basic - `JQWzqY#%@~`_:jLK$XgMB!?*U)` forbidden ``` Disp ("Vanadium" ``` ### 28. REXX - `JQWzqY#%@~`_:jLK$XgMB!?*U)(` forbidden ``` do Z=1 to 1 say 'Europium' end return ``` ### 29. BASIC (Yabasic) - `JQWzqY#%@~`_:jLK$XgMB!?*U)(Z` forbidden ``` PRINT "Chromium" ``` ### 30. Pyth - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI` forbidden ``` |0"Scandium ``` ### 31. CJam - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|` forbidden ``` "Nobelium"1\\- ``` ### 32. GolfScript - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\` forbidden ``` "Samarium"1/ ``` ### 33. Brainfuck - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/` forbidden ``` ,>-[--->+<]>-----.+[--->++++<]>.-----------.--[--->+<]>-.-----------.+++++.+++++++.--------. ``` Takes an empty string as input. ### 34. Haskell - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,` forbidden ``` 'Antimon'++['y'] ``` ### 35. Deadfish - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[` forbidden ``` iisiiiisiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioddddddoiiiodddddddddoiiiiiodddddddddo] ``` One of the few of these snippets to output a newline afterwards. ### 36. [Rebmu](http://rebmu.hostilefork.com/) - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]` forbidden ``` PR"Tungsten" ``` ### 37. Tcl - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P` forbidden ``` puts "Actinium" ``` ### 38. There Once was a Fish Named Fred - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"` forbidden ``` a named a a a once was there Fred once a a fish named a a a a a once was was was there Fred once fish was was was was was was was fish a a a a a a a fish was was was was was was was was was fish a a a a a fish was was was was was was was was was was was was fish a a a a a a a a fish ``` Prints Selenium. ### 39. BrainFNORD - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"F` forbidden ``` eris 23 eris eris eris fnord hail pineal 5 fnord eris eris eris eris eris eris eris kallisti 23 eris eris eris fnord hail hail hail hail pineal 5 fnord hail kallisti hail hail hail hail hail hail hail hail hail hail hail kallisti eris eris kallisti eris eris eris kallisti eris eris eris eris eris eris eris eris kallisti eris eris kallisti hail hail hail hail hail hail hail hail hail kallisti ``` Prints Nitrogen. ### 40. [Text](http://esolangs.org/wiki/Text) - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fl` forbidden ``` Astatine ``` ### 41. J - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln` forbidden ``` 'Caesium' ``` ### 42. Pi - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'` forbidden ``` 3.4743302180342223222232222423222332223225222222427402331802252232322322343223322224434433435 ``` Prints Tantalum. ### 43. [Marbelous](https://github.com/marbelous-lang/marbelous.py) - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.` forbidden ``` 43686C7072696E65 -- }0 ``` Prints Chlorine. This relies on the use of spaces for empty cells. [Marbelous Interpreter](https://codegolf.stackexchange.com/a/40808/29611) ### 44. DNA# - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}` forbidden ``` ATCGGCTAATCGATCGATCGATATATTAATGCGCCGATATATCGGCATGCTAATCGATCGATCGATCGATATATTAATTAATTAATTAATTAATGCGCCGATATATCGGCATATCGATCGATCGATCGATCGATCGATCGGCATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAGCATGCATATCGATCGATCGGCATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAGCATATCGATCGATCGATCGATCGATCGATCGATCGGCAT ``` Prints Thallium. ### 45. oOo - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}G` forbidden ``` OoOOoOOoOOoOoOoOoOOoOOoOOoOoooOooOooOooooOoOOoooOooOOoOooOooOoooOoOooOooOooOooOoooooOoOooOoOOoooOooOOoOooOooOooOOoOooOooOOoOooOooOooOooOOoOoOOoOOoOOoOOoOOOoOooOooOooOooOooOooOooOooOooOOo ``` Prints Bromine. ### 46. ABC - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GO` forbidden ``` AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAACAAAAAC ``` Prints Tin. Note that the interpreters on esolang are all unavailable. However, [4chan's implementation written in Scheme](http://dis.4chan.org/read/prog/1217371234) works (#59). ### 47. WASD - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GOC` forbidden ``` w1sssdwwa2dwwwe1sssdwa2dweessesssssssssewwwwwwwwwwwwesssssssse ``` Prints Yttrium. ### 48. Super Stack! - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GOCw` forbidden ``` 99 105 110 101 115 114 65 if outputascii fi ``` Prints Arsenic. ### 49. Golunar - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GOCws` forbidden ``` 1334726751425099782624362025339077479253628945660119316869724137277474322140 ``` Prints Lithium. ### 50. Unary - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GOCws1` forbidden The source is `0` repeated ``` 40732627912143966203790325934799402365062057246763194506454552300861148 ``` times. Prints Hassium. ### 51. Lenguage - `JQWzqY#%@~`_:jLK$XgMB!?*U)(ZI|\/,[]P"Fln'.}GOCws10` forbidden The source is `>` repeated ``` 9305604867582777545366404070305393137665254080212227303922021923795365639900 ``` times. Prints Bohrium. --- Most of the odd languages used can be found on the [esolangs wiki](http://esolangs.org/wiki/Main_Page). Please note that all brainfuck (and brainfuck derivatives) snippets were written with 8-bit cells in mind. [Answer] # 95 languages (all characters used!) ## (TODO: a couple more answers that I have planned out but not implemented) ### 1. COBOL - forbids `A` ``` PROGRAM-ID.g.PRODECURE DIVISION.DISPLAY"Ununtrium". ``` Prints `Ununtrium`. ### 2. REBOL - forbids `B` ``` REBOL[]prin"Tellurium" ``` Prints `Tellurium`. ### 3. bc - forbids `^` ``` a=0^0 "Strontium" ``` Prints `Strontium`. ### 4. D - forbids `D` ``` void main(char[][]D){printf="Ruthenium";} ``` Prints `Ruthenium`. ### 5. Java - forbids `E` ``` enum E{E;{System.out.print("\x41luminium");}} ``` Prints `Aluminium`. ### 6. Scala - forbids `F` ``` val F=print("Plutonium") ``` Prints `Plutonium`. ### 7. Rust - forbids `G` ``` fn main(){let G:u8;print("\x41mericium")} ``` Prints `Americium`. ### 8. Nim - forbids `&` ``` discard 0&0 echo "Neptunium" ``` Prints `Neptunium`. ### 9. C# - forbids `C` ``` class V{static void Main(){System.Console.Write("Neodymium");}} ``` Prints `Neodymium`. ### 10. [Burlesque](http://esolangs.org/wiki/Burlesque) - forbids `%` ``` ,1 1.%vv"Manganese"Q ``` Prints `Manganese`. ### 11. Nemerle - forbids `I` ``` Nemerle.IO.print("Magnesium") ``` Prints `Magnesium`. ### 12. Ada - forbids `J` ``` procedure gnat.io.J is begin put("Palladium");end; ``` Prints `Palladium`. ### 13. Go - forbids `|` ``` package main func main(){if 1|1>0{print("Germanium")}} ``` Prints `Germanium`. ### 14. K - forbids ``` ``` `0:"Ytterbium" ``` Prints `Ytterbium`. ### 15. Erlang - forbids `/` ``` -module(test). -export([m/0]). m()->io:put_chars("\x42eryllium"). ``` Prints `Beryllium`. ### 16. Prolog - forbids `:` ``` m:-write('\102erkelium'). ``` Prints `Berkelium`. ### 17. Smalltalk - forbids `K` ``` K:=0.'Lanthanum'display ``` Prints `Lanthanum`. ### 18. PARI/GP - forbids `L` ``` print(Potassium) ``` Prints `Potassium`. ### 19. REXX - forbids `M` ``` M=0 say "Tungsten" ``` Prints `Tungsten`. ### 20. LilyPond - forbids `N` ``` #(let((N 0))(print"\x46levorium")) ``` Prints `Flevorium`. ### 21. Arc - forbids `Q` ``` (let Q 1(pr "\x41ntimony")) ``` Prints `Antimony`. ### 22. Common LISP - forbids `R` ``` (let((R 0))(princ"Tantalum")) ``` Prints `Tantalum`. ### 23. Clojure - forbids `U` ``` (def U)(pr'Selenium) ``` Prints `Selenium`. ### 24. Logo - forbids `Z` ``` to Z end pr[Scandium]bye ``` Prints `Scandium`. ### 25. Groovy - forbids `W` ``` print"Samarium";W=0 ``` Prints `Samarium`. ### 26. Asymptote - forbids `X` ``` write('\x52ubidium');int X=0; ``` Prints `Rubidium`. ### 27. Octave - forbids `Y` ``` Y=0;disp Yttrium ``` Prints `Yttrium`. ### 28. gnuplot - forbids `V` ``` V=0;prin"Vanadium ``` Prints `Vanadium`. ### 29. Kite - forbids `z` ``` z=0;"\x4eobelium"|print; ``` Prints `Nobelium`. ### 30. Squirrel - forbids `_` ``` print("\x4eitrogen");local _=0; ``` Prints `Nitrogen`. ### 31. Curry - forbids `v` ``` v=v;main=putStr"\x4cutetium" ``` Prints `Lutetium`. ### 32. Fortran - forbids `q` ``` q=0;print'("Thallium")';end ``` Prints `Thallium`. ### 33. Pascal - forbids `l` ``` begin;var l:integer;write(#70#114#97#110#99#105#117#109)end. ``` Prints `Francium`. ### 34. PHP - forbids `k` ``` <?=$k="\70\108\117\111\114\105\110\101"; ``` Prints `Fluorine`. ### 35. Haskell - forbids `S` ``` main=putStr"Sodium" ``` Prints `Sodium`. ### 36. C++ - forbids `~` ``` #include<cstdio> main(){~puts("\x41ctinium");} ``` Prints `Actinium`. ### 37. ObjC - forbids `j` ``` main(j){puts("Hydrogen");} ``` Prints `Hydrogen`. ### 38. Lua - forbids `g` ``` print("\65statine") ``` Prints `Astatine`. ### 39. JavaScript - forbids `b` ``` alert("\x43h\x6corine") ``` Alerts `Chlorine`. ### 40. Bash - forbids `h` ``` echo Osmium ``` Prints `Osmium`. ### 41. Cyan - forbids `o` ``` say"Hassium" o=0 ``` Prints `Hassium`. ### 42. J - forbids `d` ``` wd'Titanium' ``` Prints `Titanium`. ### 43. Scheme - forbids `x` ``` (let((x 0))(print"Vana\x64ium")) ``` Prints `Vanadium`. ### 44. C - forbids `{` ``` main(){puts("\x55ranium");} ``` Prints `Uranium`. ### 45. FORTH - forbids `m` ``` 84 emit 104 emit 111 emit 114 emit 105 emit 117 emit 109 emit ``` Prints `Thorium`. ### 46. BASIC - forbids `T` ``` T$="Tin" ?T$ ``` Prints `Tin`. ### 47. Perl 6 - forbids `y` ``` say "\o124\o145\o162\o142\o151\o165\o155" ``` Prints `Terbium`. ### 48. [Asdf](http://esolangs.org/wiki/Asdf) - forbids `a` ``` asaasaasssasaasssassaasaasssaasaasssaasaasssaasaasssaasaasssasaasssassaasaasssasaasssassasaasssassasaasssassaasaasssaasaasssasaasssassaasaasssaasaasssasaasssassasaasssassasaasssassaasaasssaasaasssasaasssassasaasssassaasaasssasaasssassasaasssassaasaasssaasaasssasaasssassaasaasssasaasssassaasaasssasaasssassasaasssassaasaasssasaasssassasaasssassasaasssassaasaasssaasaasssasaasssassasaasssassaasaasssasaasssassaasaasssaasaasssasaasssassaasaasssasaasssassasaasssassaasaasssaasaasssaasaasssasaasssassasaasssass ``` Prints `Arsenic`. [Generating script](https://bpaste.net/show/1e0b74843da1). ### 49. Tcl - forbids `s` ``` puts "\123\151\154\151\143\157\156" ``` Prints `Silicon`. ### 50. Perl - forbids `;` ``` print"\122\150\157\144\151\165\155"; ``` Prints `Rhodium`. ### 51. Python - forbids `r` ``` print"\103\150\162\157\155\151\165\155" ``` Prints `Chromium`. ### 52. [WARP](http://esolangs.org/wiki/WARP) - forbids `=` ``` =nn0(82(104(110(105(117(109 ``` Prints `Rhenium`. ### 53. [ETA](http://esolangs.org/wiki/ETA) - forbids `n` ``` nnOtOe nHHOne enenteht O nnHHHe nHHtOe enenteht O nntOHe nHHtne enenteht O nnHnHe nHHtne enenteht O nntnte nHHtne enenteht O nHOHne nHHHte enenteht O ``` Prints `Bromine`. ### 54. [Axo](http://esolangs.org/wiki/Axo) - forbids `\` ``` 99*3+(94+8*('u'(93+9*(35*7*('fu'(7+(\ ``` Prints `Thulium`. ### 55. Ruby - forbids `t` ``` putc 69 putc 117 putc 114 putc 111 putc 112 putc 105 putc 117 putc 109 ``` Prints `Europium`. ### 56. [DBFV!](http://esolangs.org/wiki/DBFV!) - forbids `u` ``` u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u6 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u6 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u3 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u8 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u6 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 u> u<9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u9 *u6 *u4 u> ``` Prints `Niobium`. Each space is actually a newline. ### 57. [Mouse](http://esolangs.org/wiki/Mouse) - forbids `'` ``` 77 !' 101 !' 114 !' 99 !' 117 !' 114 !' 121 !' ``` Prints `Mercury`. ### 58. [Word](http://esolangs.org/wiki/Word) - forbids `f` ``` fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. ``` Prints `Cadmium`. ### 59. [Ftack](http://esolangs.org/wiki/Ftack) - forbids `$` ``` H 109 117 105 104 116 105 $ 1 76 ``` Prints `Lithium`. ### 60. [WASD](http://esolangs.org/wiki/WASD) - forbids `e` We introduce the concept of the *trivial Brainfuck solution* (TBS): we can print any character in 257 Brainfuck commands by incrementing the accumulator *c* times, outputting, then incrementing it (256-*c*) more times to reset it. Repeating this for each character in the string yields the solution. Whenever we have two subprograms `i` and `o` that function exactly like Brainfuck's `+` and `.`, we call the translated TBS the (`i`, `o`)-TBS. Instead of wrapping around we might be able to set the accumulator to zero after printing using some subprogram `o'`. This is the (`i`, `o'`)-zeroing TBS. Alternatively, we might have no wrapping but a subprogram `d` that decrements the accumulator. This is a the (`i`, `o`, `d`)-TBS. For WASD a (`w`, `e`)-TBS prints `Silver`. ### 61. [URSL](http://esolangs.org/wiki/URSL) - forbids `w` A (`i1`, `w1`, `c1`)-TBS prints `Krypton`. ### 62. [Emmental](http://esolangs.org/wiki/Emmental) - forbids `#` ``` #73#114#105#100#105#117#109 ``` Prints `Iridium`. ### 63. [Owl](http://esolangs.org/wiki/Owl) - forbids `?` ``` 0[]?83)117)108)102)117)114) ``` Prints `Sulfur`. ### 64. [RUBE](http://esolangs.org/wiki/RUBE) - forbids `)` ``` + + + + 8478 666 667 6965767 6 ) cccccccccccccccccccccccc ........................ O c . ``` Prints `Holmium`. ### 65. [Headsecks](http://esolangs.org/wiki/Headsecks) - forbids `(` A (`(`, `"`)-TBS prints `Bohrium`. ### 66. [FALSE](http://esolangs.org/wiki/FALSE) - forbids `[` ``` []!71,97,108,105,117,109, ``` Prints `Gallium`. ### 67. [Betterave](http://esolangs.org/wiki/Betterave) - forbids `-` ``` ,-,++66,-,+8,+5,+*55,*8958 ``` Prints `Hafnium`. ### 68. [Kipple](http://esolangs.org/wiki/Kipple) - forbids `>` ``` 70>o 101>o 114>o 109>o 105>o 117>o 109>o ``` Prints `Fermium`. ### 69. [GolfScript](http://esolangs.org/wiki/GolfScript) - forbids `]` ``` 68]117]98]110]105]117]109]""^ ``` Prints `Dubnium`. ### 70. [FlogScript](http://esolangs.org/wiki/FlogScript) - forbids `"` ``` 67"P.97"P.108"P.99"P.105"P.117"P.109"P. ``` Prints `Calcium`. ### 71. [OOo CODE](http://esolangs.org/wiki/OOo_CODE) - forbids `p` A (`PpP`, `PPp`)-TBS prints `Bismuth`. ### 72. [dc](http://esolangs.org/wiki/dc) - forbids `P` ``` 67P97P100P109P105P117P109P ``` Prints `Cadmium`. ### 73. [Capuirequiem](http://esolangs.org/wiki/Capuirequiem) - forbids `O` ``` 82O97O100O105O117O109O ``` Prints `Radium`. ### 74. [BitChanger](http://esolangs.org/wiki/BitChanger) - forbids `}` ``` TODO ``` Prints `Cobalt`. ### 75. [Vrejvax](http://esolangs.org/wiki/Vrejvax) - forbids `<` ``` TODO ``` Prints `Cerium`. ### 76. [Fueue](http://esolangs.org/wiki/Fueue) - forbids `H` ``` 80 111 108 111 110 105 117 109 H ``` Prints `Polonium`. ### 77. [Pi](http://esolangs.org/wiki/Pi) - forbids `6` Run `bf2pi` from the wiki article on a trivial Brainfuck solution to print `Xenon`. ### 78. [CJam](http://esolangs.org/wiki/CJam) - forbids `5` A (`1+`, `c 0`)-zeroing TBS (with `0` prepended) prints `Nickel`. ### 79. [Wordfuck](http://esolangs.org/wiki/Wordfuck) - forbids `9` A (`9999`, `99`)-TBS prints `Carbon`. ### 80. [Lenguage](http://esolangs.org/wiki/Lenguage) - forbids `7` ``` ≈ 3^(257*4*3) sevens ``` See 91-94 (use only `7`.) Prints `Radon`. ### 81. [Binaryfuck (hexadecimal)](http://esolangs.org/wiki/Binaryfuck) - forbids `4` ``` TODO ``` Prints `Barium`. ### 82. [CaneCode](http://esolangs.org/wiki/CaneCode) - forbids `8` A (`1`, `8`)-TBS prints `Iodine`. ### 83. [Numberwang](http://esolangs.org/wiki/Numberwang) - forbids `3` A (`2`, `3`)-TBS prints `Indium`, but `2` decrements instead of incrementing, so subtract each character code from 256 first. ### 84. [ferNANDo](http://esolangs.org/wiki/ferNANDo) - forbids `2` ``` 1 1 1 2 1 2 2 2 2 2 1 2 1 1 1 2 2 1 2 2 1 1 2 2 1 1 1 2 1 1 2 1 1 1 1 2 1 1 2 1 1 1 2 ``` Prints `Argon`. ### 85. [Unefunge-98](http://esolangs.org/wiki/Befunge) - forbids `@` Prepending `0` to a (`1+`, `,0`)-zeroing TBS, and appending `@`, prints `Helium`. ### 86. [Whirl](http://esolangs.org/wiki/Whirl) - forbids `1` Prepending `One Load Zero` to an (`Add`, `AscIO Zero`)-zeroing TBS prints `Boron`. ### 87. [ReverseFuck](http://esolangs.org/wiki/ReverseFuck) - forbids `,` A (`-`, `,`)-TBS prints `Erbium`. ### 88. [Brainfuck](http://esolangs.org/wiki/Brainfuck) - forbids `+` A (`+`, `.`)-TBS prints `Curium`. ### 89. [Deadfish~](http://esolangs.org/wiki/Deadfish~) - forbids `c` An (`i`, `c`)-TBS prints `Copper`. ### 90. [Iota](http://esolangs.org/wiki/Iota) - forbids `i` We compute a Church-numeral base-256-decoding to `Zinc` to make up for Iota's lack of IO. Define ``` succ = ***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii ``` Then the solution is 1516858978 repetitions of `succ` followed by `*ii`, for a total length of 69775512991 bytes. ### Unary-like programs The following four solutions (and 70) are similar: they all consist of approximately 3^(257\*4\*3) repetitions of the character they forbid (except Ellipsis is thrice as long). The exact value is decided by converting the TBS to octal as described on the wiki. ### 91. [Ellipsis](http://esolangs.org/wiki/Ellipsis) - forbids `.` ``` ≈ 3^(257*4*3+1) periods ``` Prints `Neon`. ### 92. [Ecstatic](http://esolangs.org/wiki/Ecstatic) - forbids `!` ``` ≈ 3^(257*4*3) exclamation marks ``` Prints `Lead`. ### 93. [MGIFOS](http://esolangs.org/wiki/MGIFOS) - forbids `*` ``` ≈ 3^(257*4*3) asterisks ``` Prints `Iron`. ### 94. [Unary](http://esolangs.org/wiki/Unary) - forbids `0` ``` ≈ 3^(257*4*3) zeros ``` Prints `Gold`. ### 95. [Whitespace](http://esolangs.org/wiki/Whitespace) - forbids space The Whitespace program generated by this Python script: ``` import sys for c in 'Oxygen': print ' ' + ''.join(' \t'[int(b)] for b in bin(ord(c))[2:]) sys.stdout.write('\t\n ') print '\n\n' ``` prints `Oxygen`. [Answer] # ~~20~~ 24 languages Here's something to get the ball rolling. I decided to do the elements in order because I don't know enough languages for the order to matter much. ### 1. C# - none forbidden ``` public class P{public static void Main(){System.Console.Write("Hydrogen");}} ``` ### 2. PHP - `W` forbidden ``` echo$e="Helium"; ``` ### 3. QBasic - `W$` forbidden ``` ?"Lithium" ``` ### 4. Windows Batch Script - `W$?` forbidden ``` dir>nul&echo Beryllium ``` ### 5. Brainf\*\*\* - `W$?&` forbidden ``` ++++++[>+++++++++++<-]>.----------[>++<-]-.+++.---.-. ``` Outputs Boron. ### 6. C++ - `W$?&+` forbidden ``` #include<iostream> main(){std::cout<<"Carbon";} ``` ### 7. Befunge - `W$?&+<` forbidden ``` "n eg or ti N">,_@ ``` Outputs Nitrogen. ### 8. Bash - `W$?&+<@` forbidden ``` echo Oxygen 2>1 ``` ### 9. [Sisi](https://github.com/dloscutoff/sisi) - `W$?&+<@>` forbidden ``` 9 print "Fluorine" ``` ### 10. C - `W$?&+<@>9` forbidden ``` #include"stdio.h" main(){printf("Neon%c",10);} ``` ### 11. Common Lisp - `W$?&+<@>9,` forbidden ``` (format t "~Codium" #\S) ``` ### 12. [Zephyr](https://github.com/dloscutoff/zephyr) - `W$?&+<@>9,#` forbidden ``` if 1\=0:print"Magnesium";end if ``` ### 13. Prolog - `W$?&+<@>9,#\` forbidden ``` :-write('Aluminium'). ``` ([Test here](http://ideone.com/EofJ9r).) ### 14. Java - `W$?&+<@>9,#\:` forbidden ``` class A{public static void main(String[]a){System.out.print("Silicon");}} ``` ### 15. Golfscript - `W$?&+<@>9,#\:.` forbidden ``` ];"Phosphorus" ``` ### 16. Pyth - `W$?&+<@>9,#\:.]` forbidden ``` |0"Sulfur ``` ### 17. ActionScript - `W$?&+<@>9,#\:.]|` forbidden ``` trace("Chlorine"); ``` ### 18. PowerShell - `W$?&+<@>9,#\:.]|;` forbidden ``` write-host"Argon" ``` Fortunately, PowerShell commands can be written in lowercase, avoiding the forbidden `W`. ### 19. JavaScript - `W$?&+<@>9,#\:.]|;-` forbidden ``` alert("Potassium") ``` ### 20. Python 3 - `W$?&+<@>9,#\:.]|;-"` forbidden ``` print('Calcium') ``` ### 21. Python 2 - `W$?&+<@>9,#\:.]|;-"(` forbidden ``` print'Scandium' ``` ### 22. Perl - `W$?&+<@>9,#\:.]|;-"('` forbidden ``` say q{Titanium} ``` ### 23. Ruby - `W$?&+<@>9,#\:.]|;-"('{` forbidden ``` puts %q!Vanadium! ``` ### 24. CJam - `W$?&+<@>9,#\:.]|;-"('{!` forbidden ``` 67c104c114c111c108)c105c117c108)c ``` Outputs Chromium. `)` increments were used to avoid the forbidden 9 in 109 (`m`). [Answer] ## 23 Languages I set out to beat the 20 language answer... and now I can't be bothered to shoot for 52. ;) ### 1. Mathematica - none forbidden ``` J;"Krypton" ``` ### 2. Ruby - `J` forbidden ``` K=1;puts 'Vanadium' ``` ### 3. Python 2 - `JK` forbidden ``` Q=1;print 'Xenon' ``` ### 4. Python 3 - `JKQ` forbidden ``` X=1;print('Osmium') ``` ### 5. PHP - `JKQX` forbidden ``` $V=1;echo 'Oxygen'; ``` ### 6. Julia - `JKQXV` forbidden ``` O=1;println('Ytterbium') ``` ### 7. JavaScript - `JKQXVO` forbidden ``` Y=1;alert('Yttrium') ``` ### 8. CoffeeScript - `JKQXVOY` forbidden ``` q=1;alert 'Zinc' ``` ### 9. C - `JKQXVOYq` forbidden ``` main(Z){printf("Zirconium");} ``` ### 10. C++ - `JKQXVOYqZ` forbidden ``` #include <cstdio> int main(){int x;printf("Lawrencium");} ``` ### 11. Matlab - `JKQXVOYqZx` forbidden ``` w=1;'Nickel' ``` ### 12. Perl - `JKQXVOYqZxw` forbidden ``` $k=1;print "Berkelium"; ``` ### 13. Perl 6 - `JKQXVOYqZxwk` forbidden ``` $f=1;say'Darmstadtium'; ``` ### 14. Java - `JKQXVOYqZxwkf` forbidden ``` public class p{public static void main(String[]v){System.out.println("Dubnium");}} ``` ### 15. [Marbelous](https://github.com/marbelous-lang/marbelous.py) - `JKQXVOYqZxwkfv` forbidden ``` 44797370726F7369756D ``` Prints `Dysprosium`. ### 16. Lua - `JKQXVOYqZxwkfvD` forbidden ``` G=1;print("Erbium") ``` ### 17. Octave - `JKQXVOYqZxwkfvDG` forbidden ``` F=1;disp('Einsteinium'); ``` ### 18. Rust - `JKQXVOYqZxwkfvDGF` forbidden ``` fn main(){let E=1;println!("Europium");} ``` ### 19. Fortran - `JKQXVOYqZxwkfvDGFE` forbidden ``` print *,"Indium" ``` ### 20. CJam - `JKQXVOYqZxwkfvDGFEp` forbidden ``` H;"Iodine" ``` ### 21. Golfscript - `JKQXVOYqZxwkfvDGFEpH` forbidden ``` U"Iridium" ``` ### 22. Pyth - `JKQXVOYqZxwkfvDGFEpHU` forbidden ``` I1"Iron ``` I *think* this should be ``` if 1: print "Iron" ``` ### 23. Brainfuck - `JKQXVOYqZxwkfvDGFEpHUI` forbidden ``` ++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>++++++++++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>++.--<<<<<<<<>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<<<<<<<>>>>>>>>>>>>>>>+.-<<<<<<<<<<<<<<<>>>>>>>>>>>>>>----.++++<<<<<<<<<<<<<<>>>>>>>>>>>>>>----.++++<<<<<<<<<<<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<<<>>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<<. ``` Prints `Beryllium`. [Answer] ## ~~20~~ ~~21~~ 26 languages Okay, let's see if I can do something out of this, not even trying to aim for top spot... if I can get 20 languages without any mistakes I'll be more than happy. ### 1. JAVA - none forbidden ``` class J{public static void main(String[]a){System.out.print("Hydrogen");}} ``` Prints `Hydrogen`. ### 2. Pascal - `J` forbidden ``` Program H; begin write('Helium'); end. ``` Prints `Helium`. ### 3. C - `JP` forbidden ``` #include <stdio.h> main(){printf("Lithium");} ``` Prints `Lithium`. ### 4. PHP - `JPf` forbidden ``` <?php echo "Beryllium";?> ``` Prints `Beryllium`. ### 5. C# - `JPf?` forbidden ``` using System;class O{static void Main(){Console.Write("Boron");}} ``` Prints `Boron`. ### 6. PROLOG - `JPf?W` forbidden ``` :-initialization(main). main:-write('Carbon'). ``` Prints `Carbon` - tested [here](http://www.compileonline.com/execute_prolog_online.php). ### 7. JavaScript - `JPf?W'` forbidden ``` <html> <script language="javascript" type="text/javascript"> alert("Nitrogen"); </script> </html> ``` Prints `Nitrogen`. ### 8. LOLCODE - `JPf?W'=` forbidden ``` HAI VISIBLE "Oxygen" KTHXBYE ``` Prints `Oxygen`. ### 9. Befunge '93 - `JPf?W'=K` forbidden ``` "eniroulF">:#,_@ ``` Prints `Fluorine` - tested [here](http://www.bedroomlan.org/tools/befunge-93-playground). ### 10. Visual Basic - `JPf?W'=K@` forbidden ``` Module V Sub Main() Console.WriteLine("Neon") End Sub End Module ``` Prints `Neon`. ### 11. HTML5 - `JPf?W'=K@M` forbidden ``` &#83;&#111;&#100;&#105;&#117;&#109; ``` Prints `Sodium` - inspired by [this answer](https://codegolf.stackexchange.com/a/40586/32139). ### 12. Brainfuck - `JPf?W'=K@M&` forbidden ``` ++[---------->+<]>.-[------>+<]>-.++++++.+++++++.---------.[--->+<]>----.----------.++++++++++++.--------. ``` Prints `Magnesium` - tested [here](http://copy.sh/brainfuck/). ### 13. JSFuck - `JPf?W'=K@&M<` forbidden ``` (+![]+[][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+([][[]]+[])[+[]]+((+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+[]]+((+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]] ``` Prints `Aluminium` - tested [here](http://www.jsfuck.com/). ### 14. Bash - `JPf?W'=K@&M<[` forbidden ``` #!/bin/bash echo "Silicon" ``` Prints `Silicon`. ### 15. Assembly NASM - `JPf?W'=K@&M<[!` forbidden ``` section .text global _start section .data msg db "Phosphorus" len equ $ - msg _start: mov edx, len mov ecx, msg mov ebx, 1 mov eax, 4 int 0x80 mov eax, 1 int 0x80 ``` Prints `Phosphorus`- tested [here](http://www.compileonline.com/compile_assembly_online.php). ### 16. D - `JPf?W'=K@&M<[!$` forbidden ``` import std.stdio;void main(){write("Chlorine");} ``` Prints `Chlorine`. ### 17. Fortran '95 - `JPf?W'=K@&M<[!$d` forbidden ``` program C print *, "Argon" end program C ``` Prints `Argon` - tested [here](http://www.compileonline.com/compile_fortran_online.php). ### 18. Lua - `JPf?W'=K@&M<[!$d*` forbidden ``` print("Sul\x66ur") ``` Prints `Sulfur` - tested [here](http://www.compileonline.com/execute_lua_online.php). ### 19. Golfscript - `JPf?W'=K@&M<[!$dt` forbidden ``` U"\x50o\x74assium" ``` Prints `Potassium` - tested [here](http://golfscript.apphb.com/). ### 20. Perl 5 - `JPf?W'=K@&M<[!$*dU` forbidden ``` use v5.10; say "Calciu\x{6d}"; ``` Prints `Calcium` - tested [here](http://www.compileonline.com/execute_perl_online.php). ### 21. Nimrod - `JPf?W'=K@&M<[!$*dUu` forbidden ``` echo "Scan\x64i\x75m" ``` Prints `Scandium`. ### 22. Python - `JPf?W'=K@&M<[!$*dUuh` forbidden ``` print "Titani\165m"; ``` Prints `Titanium`. ### 23. Unlambda - `JPf?W'=K@&M<[!$*dUuh;` forbidden ``` `r````.I.r.o.ni ``` Prints `Iron`. - tested [here](http://www.compileonline.com/execute_unlambda_online.php). ### 24. Forth - `JPf?W'=K@&M<[!$*dUuh;`` forbidden ``` \ .( Cobalt) CR ``` Prints `Cobalt` - tested [here](http://www.compileonline.com/execute_forth_online.php). ### 25. Lua - `JPf?W'=K@&M<[!$*dUuh;`\` forbidden ``` print("Nickel") ``` Prints `Nickel` - tested [here](http://www.compileonline.com/execute_lua_online.php) ### 26. Emoticon - `JPf?W'=K@&M<[!$*dUuh;`\p` forbidden ``` Zinc :-Q ``` Prints `Zinc`- tested [here](http://repl.it/languages/Emoticon) Oh well, I think that's about enough for me. ]
[Question] [ A [square-free word](https://en.wikipedia.org/wiki/Square-free_word) is a word consisting of arbitrary symbols where the pattern \$XX\$ (for an arbitrary non-empty word \$X\$) does not appear. This pattern is termed a "square". For example, `squarefree` is not square-free (using the lowercase letters as the alphabet), as the square `ee` appears; but `word` is square-free. Additionally, note that \$X\$ does not have to be a single symbol, so `1212` is not square-free, as `12` is repeated. If the alphabet used has exactly one symbol, there are only two square-free words: the empty word, and the word of exactly one symbol. For a binary alphabet, e.g. \$\{0,1\}\$, there are a finite number of square-free words: the empty word, \$0, 1, 01, 10, 010, 101\$. All other words made from just two symbols will contain a square. However, for an alphabet of three or more symbols, there are an infinite number of square-free words. Instead, we can consider the number of words of length \$n\$ for an alphabet of \$k\$ characters: | \$\downarrow\$ Alphabet length \$k\$     Word length \$n\$ \$\rightarrow\$ | \$0\$ | \$1\$ | \$2\$ | \$3\$ | \$4\$ | \$5\$ | \$6\$ | | --- | --- | --- | --- | --- | --- | --- | --- | | \$1\$ | \$1\$ | \$1\$ | \$0\$ | \$0\$ | \$0\$ | \$0\$ | \$0\$ | | \$2\$ | \$1\$ | \$2\$ | \$2\$ | \$2\$ | \$0\$ | \$0\$ | \$0\$ | | \$3\$ | \$1\$ | \$3\$ | \$6\$ | \$12\$ | \$18\$ | \$30\$ | \$42\$ | | \$4\$ | \$1\$ | \$4\$ | \$12\$ | \$36\$ | \$96\$ | \$264\$ | \$696\$ | | \$5\$ | \$1\$ | \$5\$ | \$20\$ | \$80\$ | \$300\$ | \$1140\$ | \$4260\$ | | \$6\$ | \$1\$ | \$6\$ | \$30\$ | \$150\$ | \$720\$ | \$3480\$ | \$16680\$ | For example, there are \$36\$ different squarefree words of length \$3\$ using a alphabet of \$4\$ symbols: ``` 121 123 124 131 132 134 141 142 143 212 213 214 231 232 234 241 242 243 312 313 314 321 323 324 341 342 343 412 413 414 421 423 424 431 432 434 ``` For a ternary alphabet, the lengths are given by [A006156](https://oeis.org/A006156). Note that we include the zero word lengths for \$k = 1, 2\$ in the table above. --- This is a (mostly) standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You must take one input \$k\$, representing the length of the alphabet. Alternatively, you may accept a list (or similar) of \$k\$ distinct symbols (e.g. single characters, the integers \$1, 2, ..., k\$, etc.). You can then choose to do one of the following: * Take a non-negative integer \$n\$, and output the number of square-free words of length \$n\$, using an alphabet with \$k\$ symbols * Take a positive integer \$n\$ and output the first \$n\$ elements of the sequence, where the \$i\$th element is the number of of square free words of length \$i\$ using an alphabet of \$k\$ symbols + Note that, as \$i = 0\$ should be included, \$n\$ is "offset" by 1 (so \$n = 3\$ means you should output the results for \$i = 0, 1, 2\$) * Take only \$k\$ as an input, and output indefinitely the number of square free words of increasing length, starting at \$i = 0\$, using the alphabet of \$k\$ symbols. + For \$k = 1, 2\$ you may decide whether to halt after outputting all non-zero terms, or to output `0` indefinitely afterwards This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases Aka, what my sample program can complete on TIO ``` k => first few n 1 => 1, 1, 0, 0, 0, 0, 0, 0, 0, ... 2 => 1, 2, 2, 2, 0, 0, 0, 0, 0, ... 3 => 1, 3, 6, 12, 18, 30, 42, 60, 78, ... 4 => 1, 4, 12, 36, 96, 264, 696, 1848, 4848, ... 5 => 1, 5, 20, 80, 300, 1140, 4260, 15960, 59580, ... 6 => 1, 6, 30, 150, 720, 3480, 16680, 80040, ... 7 => 1, 7, 42, 252, 1470, 8610, 50190, ... 8 => 1, 8, 56, 392, 2688, 18480, 126672, ... 9 => 1, 9, 72, 576, 4536, 35784, 281736, ... 10 => 1, 10, 90, 810, 7200, 64080, ... 11 => 1, 11, 110, 1100, 10890, 107910, ... 12 => 1, 12, 132, 1452, 15840, 172920, ... 13 => 1, 13, 156, 1872, 22308, 265980, ... 14 => 1, 14, 182, 2366, 30576, 395304, ... 15 => 1, 15, 210, 2940, 40950, 570570, ... ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes ``` ÞẊǎ:∷d=Ṡ† ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiw57huorHjjriiLdkPeG5oOKAoCIsIiIsIjNcblwiYWJjXCIiXQ==) # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ÞẊǎ:∷d=Ṡ†∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuG6iseOOuKIt2Q94bmg4oCg4oiRIiwiIiwiM1xuXCJhYmNcIiJd) ``` ÞẊ # Cartesian product; all ways to choose n items from k ----- # Next bit contains only vectorising elements, applied to each ǎ: # Get substrings and duplicate --- # Next bit over each substring ∷ # Get the second half d # Double it = # Is it equal to the original? # (If it is, that word's a square) Ṡ # Sum each result - truthy if any are equal and word contains squares † # NOT each result - those that are squarefree ∑ # Sum the result (s flag) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` Count[Or@@@Tuples@##,_?(FreeQ[x_||x_])]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@985vzSvJNq/yMHBIaS0ICe12EFZWSfeXsOtKDU1MLoivqamIj5WM1btf0BRZl6Jgr6DQkhiUk5qdFp0UGJeeqpDto5CXqyOQjWQNtRRMK8FMvN0FAx0FMxqY/8DAA "Wolfram Language (Mathematica) – Try It Online") Takes a list of \$k\$ distinct non-Boolean symbols and a non-negative integer \$n\$. [Answer] # JavaScript (ES7), 90 bytes Expects `(k)(n)` and returns the number of square-free words of length \$n\$, using \$k\$ symbols. ``` k=>n=>eval("for(i=t=k**n;i--;)t-=/(-.*),\\1/.test([...Array(n)].map((_,j)=>~(i/k**j%k)))") ``` [Try it online!](https://tio.run/##NY1Ba8MwDIXv@xWiMColtbNeenEV6KG/YMd1DNMkxXEmB9sUxuj@eubAdhB6enzvabR3m67RzVlJ6Ppl4MVzK9z2dzvhZggRHWf2VSXGKWUoK25Q6Yp2l8u@0blPGd@01qcY7RcKvetPOyN@7Ebi9gddU6LjsyeiDS1rnQeGvQEPR4ZD2XVN8P0EkIq/3ZqiVkrK9WJA/ij5p1auZhjQU3mmc3jN0ckNSc@2O0uHB1orHmWuQVKYej2FG6biPpZf "JavaScript (Node.js) – Try It Online") ### How? The symbols are depicted with the decimal representation of the ones' complements of non-negative integers (\$-1\$, \$-2\$, \$-3\$, ... and so on) and implicitly joined with commas when the array is coerced to a string. Hence the regular expression to detect squares: `/(-.*),\1/`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` lf!:T"(.+)\\1"0^F ``` [Test suite](http://pythtemp.herokuapp.com/?code=lf%21%3AT%22%28.%2B%29%5C%5C1%220%5EF&test_suite=1&test_suite_input=%220%22%2C0%0A%220%22%2C1%0A%220%22%2C2%0A%220%22%2C3%0A%220%22%2C4%0A%220%22%2C5%0A%2201%22%2C0%0A%2201%22%2C1%0A%2201%22%2C2%0A%2201%22%2C3%0A%2201%22%2C4%0A%2201%22%2C5%0A%22012%22%2C0%0A%22012%22%2C1%0A%22012%22%2C2%0A%22012%22%2C3%0A%22012%22%2C4%0A%22012%22%2C5%0A%220123%22%2C0%0A%220123%22%2C1%0A%220123%22%2C2%0A%220123%22%2C3%0A%220123%22%2C4%0A%220123%22%2C5%0A%2201234%22%2C0%0A%2201234%22%2C1%0A%2201234%22%2C2%0A%2201234%22%2C3%0A%2201234%22%2C4%0A%2201234%22%2C5%0A%22012345%22%2C0%0A%22012345%22%2C1%0A%22012345%22%2C2%0A%22012345%22%2C3%0A%22012345%22%2C4%0A%22012345%22%2C5%0A%220123456%22%2C0%0A%220123456%22%2C1%0A%220123456%22%2C2%0A%220123456%22%2C3%0A%220123456%22%2C4%0A%220123456%22%2C5%0A%2201234567%22%2C0%0A%2201234567%22%2C1%0A%2201234567%22%2C2%0A%2201234567%22%2C3%0A%2201234567%22%2C4%0A%2201234567%22%2C5%0A%22012345678%22%2C0%0A%22012345678%22%2C1%0A%22012345678%22%2C2%0A%22012345678%22%2C3%0A%22012345678%22%2C4%0A%22012345678%22%2C5%0A%220123456789%22%2C0%0A%220123456789%22%2C1%0A%220123456789%22%2C2%0A%220123456789%22%2C3%0A%220123456789%22%2C4%0A%220123456789%22%2C5%0A%220123456789a%22%2C0%0A%220123456789a%22%2C1%0A%220123456789a%22%2C2%0A%220123456789a%22%2C3%0A%220123456789a%22%2C4%0A%220123456789a%22%2C5%0A%220123456789ab%22%2C0%0A%220123456789ab%22%2C1%0A%220123456789ab%22%2C2%0A%220123456789ab%22%2C3%0A%220123456789ab%22%2C4%0A%220123456789ab%22%2C5%0A%220123456789abc%22%2C0%0A%220123456789abc%22%2C1%0A%220123456789abc%22%2C2%0A%220123456789abc%22%2C3%0A%220123456789abc%22%2C4%0A%220123456789abc%22%2C5%0A%220123456789abcd%22%2C0%0A%220123456789abcd%22%2C1%0A%220123456789abcd%22%2C2%0A%220123456789abcd%22%2C3%0A%220123456789abcd%22%2C4%0A%220123456789abcd%22%2C5%0A%220123456789abcde%22%2C0%0A%220123456789abcde%22%2C1%0A%220123456789abcde%22%2C2%0A%220123456789abcde%22%2C3%0A%220123456789abcde%22%2C4%0A%220123456789abcde%22%2C5&debug=0) Takes input as a list/tuple of the alphabet as a string and the word length as an integer. ##### Explanation: ``` lf!:T"(.+)\\1"0^F | Full code lf!:T"(.+)\\1"0^FQ | with implicit variables filled -------------------+-------------------------------------------------------------------------------------------------------- ^FQ | Repeated cartesian product (get all combinations of elements of the alphabet of the appropriate length) f | Filter this list for elements T such that !:T 0 | T does not match the regex pattern "(.+)\\1" | which searches for a repeated substring l | Print the length of the filtered list ``` [Answer] # Haskell, 118 bytes ``` s []=1>0 s l=and[take n l/=take n(drop n l)|n<-[1..length l]]&&s(tail l) n!k=length$filter s$mapM id$replicate n[1..k] ``` [Try it Online!](https://tio.run/##JYxBCoMwEADvvmKFIPZQW/Ha9Ad9QchhqWldsq4h2WP/nirehhmYBUsMzLUWcN6Oz3tTgC3K7BRjAAG@2ZP6OW/pEJefPK5uHAYO8tUF2PuuK70i8R4baaM9i/kQa8hQzIrpBTSbHBLTG3XfHYPo64okYCFlEgUztVP9Aw) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` k=>g=(n,e,i=k)=>n?i&&g(n-1,[e,i])+g(n,e,i-1):!/(,.*)\1/.test(e) ``` [Try it online!](https://tio.run/##NYwxDsIwDEV3TmGWYpM20KUDJTBxAkZgqGgahVRO1UQsiLOXVMBg@fv9Jz@aZxPuox1iwb7VU6cmpw5GIec6t8qROvDRZplBLsr8ktiNhPm2RUm75QZzuaZruZFRh4iaps6P6EBBWYODvYIqbSEIXguAkPhqVac0W5yubQ38s/hvzZ5QgKJDR8hEMvpzHC0bJDk07YlbrGj@8k5z9xx8r2XvDYZE39MH "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` (k,r=0)=>g=(n,e)=>n?[...Array(k)].map((_,i)=>g(n-1,[e,i]))|r:r+=!/(,.*)\1/.test(e) ``` [Try it online!](https://tio.run/##NY3BysIwEITvPsV6ctfG1V48WKN48An@o4oEm5Za3ZQkCOLvs9cU9DDszPCxczUPEy6@6eJMXGn7SvfYKq8XpDe1RlE2GdkemHnnvXliSye@mw7xrJqBQZnl6mBVcyL69yuf6fEcFU/pmM852hDRUl85jy1oyAtoYa1hmW6WEbxGACH1k0mR3EBJSosC5EvJjxq4TEOV9lGIo/uLvpEaiTtT7qXEJQ0v3kkXJ8HdLN9cjSG17/4D "JavaScript (Node.js) – Try It Online") Something like Arnauld's solution but recursive. `[e,i]` finally returns `,1,2,1` which provides convenience for checking, no need to add minus sign. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ 16 bytes ``` {gʰj₎∋ᵐ¬{s~jb}}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/aP6yR02NpzZUVQNZD7dOB9NgkUdtGx41NZc/3LmovPbh1gmPOpY/3LXj4a5OEOd/dfqpDVmPmvoedXQDuYfWVBfXZSXV1j7cNuf//2hTHfNYAA "Brachylog – Try It Online") *-3 thanks to Fatalize actually reading the challenge 🙃* Input as a list `[alphabet of n characters, k]`. Phenomenally slow, and I still can't help thinking there's a somewhat shorter way to brute-force the words. ``` { }ᶜ Count how many ways it's possible to ∋ᵐ choose an element from each of gʰj₎ k copies of the supplied alphabet ¬{ } such that it is impossible to s find a substring ~j which is something concatenated to itself b which is non-empty. ``` The empty list is considered a substring of itself but nothing else, so this is correct for \$n>0\$ without the `b`. # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` gʰj₎ẋ{sᶠ~jˢcĖ}ˢl ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/aP6yR02NpzZUVQNZD7dOB9NgkUdtGx41NZc/3LmovPbh1gmPOpY/3LXj4a5OEOd/@qkNWY@a@h7u6q4ufrhtQV3W6UXJR6bVnl6U8/9/tKmOeSwA "Brachylog – Try It Online") More or less the same thing, but handling \$n=0\$ slightly differently might offer an opportunity to shave something off, maybe... ``` ẋ Get the Cartesian product of gʰj₎ k copies of the supplied alphabet, { }ˢ then keep only the tuples for which sᶠ the list of all substrings ~jˢ filtermapped from "squares" to their halves c concatenated Ė is the empty list. l How many remain? ``` The empty list is considered a substring of itself but nothing else, so this is correct for \$n>0\$ without the `c`. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` #ȯΠṁoẊ≠½Qπ ``` [Try it online!](https://tio.run/##ASAA3/9odXNr//8jyK/OoOG5gW/huoriiaDCvVHPgP///zX/Mw "Husk – Try It Online") or [Try first elements of first few test cases](https://tio.run/##AS4A0f9odXNr/1ThuarigoEoxYA2KSjhuKM1Kf8jyK/OoOG5gW/huoriiaDCvVHPgP//) Input is arg1=`k`, arg2=`n`. Outputs number of square-free words of length `n`, using an alphabet with `k` symbols. ``` π # Cartesian arg2-th power of range [1..arg1] #ȯ # how many truthy elements of the following function: Q # get all contiguous sublists ṁo # and for each of them: ½ # split them in half Ẋ≠ # and check if both halves are unequal Π # now take the product of all of that # (so product is zero if any sublist contained # non-unequal halves, non-zero [truthy] otherwise) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ãεŒε2äË≠]PO ``` Inputs \$n\$ and a list in the range \$[1,k]\$ and outputs the single result. [Try it online](https://tio.run/##ASgA1/9vc2FiaWX//8OjzrXFks61MsOkw4viiaBdUE///zMKWzEsMiwzLDRd) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m6hdqdmySUratkn2EvZJOHpD2s1dSeNQ2SQEo4uOn9P/w4nNbj046t9Xo8JLD3Y86F8QG@P9X0gvT@Q8A). **Explanation:** ``` ã # Get the second (implicit) input-list [1,k] to the cartesian power of # the first (implicit) input-integer n, creating a list of all n-sized # sublists with elements from [1,k] ε # Map over each inner list: Œ # Get all its sublists ε # Map over each sublist: 2ä # Split it into two equal-sized halves Ë≠ # Check that both halves are NOT equal ] # Close the nested maps P # Take the product of each inner list O # Take the sum to get the amount of truthy values # (after which this is output implicitly as result) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ṗµẆ;"ḟƑ$)S ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//4bmXwrXhuoY7IuG4n8aRJClT/8mTxbvDp0DDvkf//zX/Nw "Jelly – Try It Online") Went through no fewer than six 11-byters before finally reaching par, and turns out it's pretty much just what Dennis did on the linked challenge... ``` µ ) Map over ṗ the Cartesian power of the arguments: Ẇ The list of the word's contiguous substrings ;" $ with each one concatenated to itself, Ƒ is it unchanged by ḟ removing every substring of the word? S Sum the results. ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes ``` 1A` $ ; "$+"+%Lv$`(.).*; $>`$1$' A`(.+)\1 ; ``` [Try it online!](https://tio.run/##K0otycxLNPz/39AxgUuFy5pLSUVbSVvVp0wlQUNPU0/LmkvFLkHFUEWdyxEooK0ZY8hl/f@/CVdiUjIA "Retina – Try It Online") No test suite due to the way the program uses history. Takes input as `n` on the first line and a string of `k` letters (any printable ASCII except semicolon) on the second. Explanation: ``` 1A` ``` Delete `n` from the buffer. ``` $ ; ``` Append a marker. ``` "$+"+%Lv$`(.).*; $>`$1$' ``` Generate the Cartesian product. ``` A`(.+)\1 ``` Remove all square results. ``` ; ``` Count the remaining results. [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->n,k{([*1..n]*k).permutation(k).uniq.count{|w|w*?_!~/(.+)_\1/}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7taI1rLUE8vL1YrW1OvILUot7QksSQzP08DyC3NyyzUS84vzSuprimvKdeyj1es09fQ09aMjzHUr639X6CQFm2iYxLLpQE0wURTLzexoLqmoqZAQcMAwa@sSYuu0KmMBaoHAA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 106 bytes ``` lambda k,n:sum(not re.search(r'(.+)\1',''.join(p))for p in i.product(k,repeat=n)) import itertools as i,re ``` [Try it online!](https://tio.run/##bZPbbqMwEIbveQrfgVU2wjY@Rcq@SIoiljgtS2IQEO0hyrNnZ4zJVmoR4NM3/8x47OHP/N578TjtXh/n@vLjWJMu99vpesl8P5PRbSZXj817NqbZ5oW@sjRP083PvvXZQOmpH8lAWk/azTD2x2szZ10@usHV885TmrSXoR9n0s5unPv@PJF6Ii0Aj7gwzWPr3/Kx9sf@krjfg2tmdyQ7cksIPIxsyZ7lBN7i81vlAeIR4uv7FSQiJHKiQA8oZmAERAl9Ba02ES0jWi6cAN7CxxVMKOwxU4JtCf9oIaOFBAqUTIHK8GOsDA5QnkmLjbTSrDGpaKaWQJjEKFBAlCjBlDJBrShXCx0t9BI2l5hHqZFSDNULZlfWRBZClejBooEyZokf9blSmkfaRtpiCGChwaSUmLuQ2kDm3DAtVKRZsRYGdCy6Z0vs8Fdl8cyQPQsYvrAlYWMKY0OjLXuyax1DcUTILOQnDe4i09zyJ7uWkwkEQk0wbM5FYTBNaf/HsNaTYUENUkKFLQ9JCitFUa7sWkmGpcR4uQ0lLCwWR2qwQd170ry7pnMjnNQsfb1yXTZpTkKPiZQm49VPsKaT5WQfOhztl8EGG/jeXAaezs5n67mn5IUwSvBSHfBSLRBq0WpV8l8rfZTZdxVdVLqosoRQJWEuJx6n/7ZD9lzKyVOebsNWoJtTttzPTT01bXs497/c2NST22@7ClRoAB2AHzzvfRWmBzCcs1Pa4WXu7ugUOv5Ovn0nt@lObnEH9263m6p7Sh//AA "Python 3 – Try It Online") Inputs a string of \$k\$ distinct characters and a positive integer \$n\$. Returns the number of square-free words of length \$n\$ for alphabets of length \$k\$. ]
[Question] [ Consider a triangle where the **N**th row (1-indexed) is the array of the first **N** positive integer powers of **N**. Here are the first few rows: ``` N | Triangle 1 | 1 2 | 2 4 3 | 3 9 27 4 | 4 16 64 256 5 | 5 25 125 625 3125 ... ``` Now if we concatenate those powers into a single sequence, we get OEIS [A075363](https://oeis.org/A075363): ``` 1, 2, 4, 3, 9, 27, 4, 16, 64, 256, 5, 25, 125, 625, 3125, 6, 36, 216, 1296, 7776, 46656 ... ``` --- Given an integer **N**, your task is to return the **N**th term of this sequence. You can choose either 0 or 1-indexing. ## Test cases **1-indexed:** ``` N -> Output 1 -> 1 2 -> 2 3 -> 4 5 -> 9 10 -> 256 12 -> 25 15 -> 3125 ``` **0-indexed:** ``` N -> Output 0 -> 1 1 -> 2 2 -> 4 4 -> 9 9 -> 256 11 -> 25 14 -> 3125 ``` 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'"), thus the shortest valid submission in each language wins! [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes **1-indexed** ``` f=lambda x,n=1:n**x*(x<=n)or f(x-n,n+1) ``` [Try it online!](https://tio.run/##BcExCoAwDADArzgmsQ7BQRD7mIhWBZuW0iG@Pt7Vr99FZ/cUX8n7IYMFjbwqkRHYFhVLGxLYpEFHRq/t0Q6UpUIKTfQ6gQMviOg/ "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` !ṁṠM^ḣN ``` [Try it online!](https://tio.run/##yygtzv7/X/HhzsaHOxf4xj3csdjv////hqYA "Husk – Try It Online") 1-indexed ### Explanation: ``` N Get the list of all natural numbers ṁ Map over each n in that list and then concatenate Ṡ ḣ Create the range [1,n] then ... M^ raise n to the power of each ! Index into that sequence ``` [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes ``` r=Range;Flatten[r@#^r@r@#][[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KCloPG/yDYoMS891dotJ7GkJDUvushBOa7IAUjGRkcrx8aq/ddUqFNwLCpKrATShgYG/wE "Wolfram Language (Mathematica) – Try It Online") Ranges to the power of ranges of ranges... [Answer] # [R](https://www.r-project.org/), 40 bytes *-2 bytes porting [Halvard Hummel's answer](https://codegolf.stackexchange.com/a/148574/67312)* ``` function(N){while(N>T){N=N-T;T=T+1};T^N} ``` [Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Pw0@zujwjMydVw88uRLPaz9ZPN8Q6xDZE27DWOiTOr/Z/cWJBQU6lhqGVoYFOmuZ/AA "R – Try It Online") # [R](https://www.r-project.org/), (original answer) 42 bytes ``` function(N)(rep(1:N,1:N)^sequence(1:N))[N] ``` [Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Pw09Toyi1QMPQyk8HiDXjilMLS1PzklNBIpqa0X6x/4sTCwpyKoF8QwOdNM3/AA "R – Try It Online") 1-indexed. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~15~~ ~~13~~ 10 bytes *3 bytes saved thanks to @Adám* ``` ⊢⊃∘∊⍳*⍳¨∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYsedTU/6pjxqKPrUe9mLSA@tALE7d0MVABk9m42NAAA) **How?** `⍳¨∘⍳` - create a range for each number in the range of input `⍳*` - raise each number in the range of input to the corresponding powers `∊` - flatten `⊢⊃` - pick the nth element [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` *R$€Ẏ⁸ị ``` [Try it online!](https://tio.run/##y0rNyan8/18rSOVR05qHu/oeNe54uLv7////hqYA "Jelly – Try It Online") -1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). 1-indexed. [Answer] # [Haskell](https://www.haskell.org/), ~~30~~ 28 bytes Saved 2 bytes thanks to xnor. ``` ([n^m|n<-[1..],m<-[1..n]]!!) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyM6Ly63Js9GN9pQTy9WJxfCyIuNVVTU/J@bmJmnYKtQUJSZV6KgopCbWKCQphBtoKdnZBD7/19yWk5ievF/3eSCAgA "Haskell – Try It Online") 0-indexed [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` :t!^RXzG) ``` Indexing is 1-based. [Try it online!](https://tio.run/##y00syfn/36pEMS4oospd8/9/Q1MA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmfEOH136pEMS4oospL879LyH9DLiMuYy5TLkMDLkMjLkNTAA). ### Explanation Consider input `5` as an example. ``` : % Implcit input n. Push range [1 2 ... n] % STACK: [1 2 3 4 5] t!^ % Matrix of all pair-wise powers % STACK: [1 2 3 4 5; 1 4 9 16 25; 1 8 27 64 125; 1 16 81 256 625; 1 32 243 1024 3125] R % Upper triangular matrix % STACK: [1 2 3 4 5; 0 4 9 16 25; 0 0 27 64 125; 0 0 0 256 625; 0 0 0 0 3125] Xz % Nonzeros. Reads values in column-major order % STACK: [1; 2; 4; 3; 9; ...; 625; 3125] G) % Get n-th entry (1-based). Implcit display % STACK: 9 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~14~~ 12 bytes ``` {⍵⌷∊*∘⍳⍨¨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bH/Vsf9TRpfWoY8aj3s2PelccWgGmt9YClSgYmgIA "APL (Dyalog Unicode) – Try It Online") Uses 1-indexing Saved 2 bytes with `↑,/ → ∊`, taken from [Graham's answer](https://codegolf.stackexchange.com/a/148589/71256) Note that in the test link, the code requires an extra `f←`, but this is not counted as per our rules. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` @s^RSdSh ``` [Try it here.](http://pyth.herokuapp.com/?code=%40s%5ERSdSh&input=14&debug=0) -1 thanks to [Steven H.](https://codegolf.stackexchange.com/users/55696/steven-h). 0-indexed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ƒNDLm`}I@ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//2CQ/F5/chFpPh///TQE "05AB1E – Try It Online") **Explanation** 1-indexed. ``` ƒ # for N in range [0 ... input] N # push N DL # push range [1 ... N] m # raise N to the power of each in [1 ... N] ` # flatten to stack } # end loop I@ # get the element at index (input) ``` **Alternative solution over a list instead of a loop** ``` ÝεDLm}˜sè ``` [Answer] # [Perl 6](https://perl6.org), 29 bytes ``` {({|($++X**1..$++)}...*)[$_]} ``` [Test it](https://tio.run/##TU7LCoJAFN3fr7iE5YzW2JgJIUXb9i2CigidQDAbmikK88va9WPmqESrczive6W4ZmF1UwLvIYsjOD9xEF8SgfOqIMWLWK67cRzOWE1oyRhz6NY67MuqDi61UBrnmKW5UIR@3kzJLNXE2ykX7dHCxpp4Rl/lOgJzZF03IpDZMUe3qUdwuly7pdECiZXm8qaHaImHFLEWCcUCEFOF5qvOpn/@EHutyE5nTez@RNnULP0CPSirMRqJA2/QB7/BAIIGZzBr9WkInLcMeGDIhPvTLw "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate the sequence { # code block used to generate each value in the sequence |( # slip the values into the outer sequence $++ # post-incremented anonymous state value X** # cross using &infix:«**» 1 .. $++ # from 1 to post-incremented anonymous state value ) } ... # keep generating values until * # never stop )[ $_ ] # index into the sequence (0-based) } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` ->n{w=0;n-=w+=1until n<0;w**=w-~n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vutzWwDpP17Zc29awNK8kM0chz8bAulxLy7Zcty6v9n9BaUmxgoaBnp6RgaZebmJBdU1RTVp0UWytlor@fwA "Ruby – Try It Online") [Answer] # [JavaScript](https://nodejs.org), 30 bytes *-1 byte thanks to Nahuel Fouilleul* ``` f=(x,n=1)=>x>n?f(x-n,n+1):n**x ``` [Try it online!](https://tio.run/##BcFRCoAgDADQ62ymgdBXoJ1FzEUhW2TEbr/eu8pXRn3O@w0sezOjBOo5RUxZM28EGtjzFHFl59Sq8JDe5i4HEMQF0X4 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda N:[n**-~e for n in range(N+2)for e in range(n)][N] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcHPKjpPS0u3LlUhLb9IIU8hM0@hKDEvPVXDT9tIEySUihDK04yN9ov9X1CUmVeikJtYoJGmA5UxNDDQ1PwPAA "Python 2 – Try It Online") (0-indexed.) *0-indexed alternative [74 bytes long version](https://tio.run/##HYwxCoAwEAS/cuVdJGoCgii@RCwEE7XIKUcsbPx6NFYLO7N73nE72Ka0OA8embow7BwRsVVcGFKqbLShylIvLl7C8FPWD/@sKJsvMSj9hErbXKdTPgfG/Ab@EMgbkJlXh6auaUov)*. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) [~~Probably~~ not optimal.](https://codegolf.stackexchange.com/a/148577/53748) -3 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)'s golfing. ``` =RṁR€T€µT*FḢ ``` **[Try it online!](https://tio.run/##y0rNyan8/9826OHOxqBHTWtCgPjQ1hAtt4c7Fv3//9/QCAA "Jelly – Try It Online")** [Answer] # [J](http://jsoftware.com/), 20 bytes ``` {1,[:;[:(^&.><\)1+i. ``` 1-indexed [Try it online!](https://tio.run/##y/qfVqxgq6dgoGClYPC/2lAn2so62kojTk3PziZG01A7U@@/JpeSnoJ6mq2VuoKOQq2VQloxV2pyRr5CmoKh6f//AA "J – Try It Online") [Answer] # APL+WIN, 23 bytes ``` (∊n↑¨⊂[2]n∘.*n←⍳n)[n←⎕] ``` Explanation: ``` [n←⎕] prompts for screen input and selects the nth element of the concatenated vector see below n←⍳n creates a vector of 1 to n ∘.* outer product with exponentiation as the operator ⊂[2] enclose each row of the resulting array as an element of a nested array ∊n↑¨ take 1 to n elements from the 1 to nth row of the matrix and concatenate into a vector ``` [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 45 bytes ``` readIO lblb a+1 i-a if i b i+a a^i printInt a ``` [Try it online!](https://tio.run/##K87MyS/@/78oNTHF058rJykniStR25ArUzeRKzNNIVMhiStTO5ErMS6Tq6AoM6/EM69EIfH///@GpgA "S.I.L.O.S – Try It Online") [Answer] # Perl 5, 30+1 (-p) bytes ``` $_-=$.++until$.>$_;$_=$.**++$_ ``` [try it online](https://tio.run/##Dcg7DoAgEAXA/p1jKzYQUfETglehsiAhQBSv7@qU084rOyETrBeKOpBhfkpPmcxB0VP8RylmiiIDLEZMmOGwYMWG/a2tp1pu0S1/) [Answer] ## Clojure 51 bytes 0-indexed, for example input `9` returns `256.0`. ``` #(nth(for[i(range)j(range i)](Math/pow i(inc j)))%) ``` [Answer] # C ~~76~~, 62 bytes ``` y;f(n){for(y=0;n>y*++y/2;);return(int)pow(y-1,n+y*(3-y)/2-1);} ``` ~~y;f(n){y=(int)(-.5+sqrt(1+8\*~-n)/2)+2;n+=y\*(3-y)/2-1;return(int)pow(y-1,n);}~~ [I based it on this code](https://gist.github.com/PhDP/2358809) [Try it on ideone](https://ideone.com/M7oIeU) [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~39~~ 37 bytes 1-indexed ``` ←000`ŕŕ⁺ĐĐř^Đ04Ș↔+⇹Ł-Đ↔3Ș0>łŕ0↔⇹+⁻⦋↔ŕ ``` Explanation: Briefly, it calculates each row. If the requested number is in that row, return it; otherwise, go to the next row. ]
[Question] [ ### Introduction Let's observe the following square, consisting only of the digits `0 - 9`: ``` 1034 4167 8414 3542 ``` The outer shell of this square is: ``` 1034 4 7 8 4 3542 ``` It contains zeros, so we need to *peel* off the outer shell, leaving: ``` 16 41 ``` The outer shell of this square is: ``` 16 41 ``` It does **not** contain any zeros and is therefore a ***non-contaminated*** square. So basically, the **definition** of a non-contaminated square is when the **outer shell** of the square contains *no* zeros. ### The Task Given a square of digits (containing only non-negative integers) in any reasonable format, output the **largest non-contaminated square** by constantly peeling off the outer shell, in any reasonable format. ### Test cases Test case 1: ``` Input Output 1234 1234 2345 2345 3456 3456 4567 4567 ``` Test case 2: ``` Input Output 123 123 204 204 346 346 ``` Test case 3: ``` Input Output 101 1 010 101 ``` Test case 4: ``` Input Output 000 (none) 000 000 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # JavaScript, ~~105~~ 97 bytes Saved 8 bytes thanks to @Patrick Roberts! ``` l=a=>a.slice(1,-1) p=a=>l(a).map(l) c=a=>a.join``.replace(/[^0]/g,"") s=a=>c(p(a))<c(a)?s(p(a)):a ``` Defines function `s`, which returns a 2D array of integers when provided a 2D array of integers as input. ### How it Works * function `l`: given an array `a`, returns a copy without its first and last indexes. * function `p`: given a 2D array `a`, calls `l` to remove the first and last row, then for each remaining row calls `l` to remove the fist and last column. This performs the onion peeling. * function `c`: given a 2D array `a`, returns a string that only contains the `0`s in the stringified form of `a`. * function `s`: given a 2D array `a`, calls `c` on the peeled form of the array given by `p`, and on the array itself. Compares these strings lexicographically to determine if the peeled form has less `0`s than the original. If it does, then the original is contaminated, so call `s` recursively on the peeled form. Otherwise return the original. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~60~~ 57 bytes Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant. ``` +`(?<=(?=.*0|[^_]+(¶0|0¶|0.*$))^[^_]*)(^.+¶|¶.+$|.?\b.?) ``` [Try it online!](http://retina.tryitonline.net/#code=bXMrYCg_PD0oPz1cZCowfC4rKF4wfDAkfDBcZCpcWikpXEEuKikoXEFcZCvCtnzCtlxkK1xafF4ufC4kKQo&input=MTAzNAo0MTY3Cjg0MTQKMzU0Mg) ### Explanation Due to the trailing linefeed, this finds all matches of the regex after the ``` and removes them from the input. Due to the leading `+` this is done repeatedly until the output stops changing (which will be because the regex will stop matching). As for the regex itself, it consists of two parts: ``` (?<=(?=.*0|[^_]+(¶0|0¶|0.*$))^[^_]*) ``` This part checks whether there's a `0` anywhere in the outer shell. It does this by moving the regex engine's "cursor" to the beginning of the string with a lookbehind (we use `[^_]` to match both digits and linefeeds): ``` (?<=...^[^_]*) ``` And then from that position we use a lookahead to find a `0` either in the first line, adjacent to a linefeed, or in the last line: ``` (?=.*0|[^_]+(¶0|0¶|0.*$)) ``` Then the actual match will consist either of the first line (including its trailing linefeed), the last line (including its leading linefeed) or the first or last character of a line, where we abuse the word boundary `\b` as a beginning/end of line anchor: ``` (^.+¶|¶.+$|.?\b.?) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~19~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Fœ^F}P ḊṖZµ⁺⁸ßç? ``` [Try it online!](http://jelly.tryitonline.net/#code=RsWTXkZ9UArhuIrhuZZawrXigbrigbjDn8OnPw&input=&args=W1sxLDAsMyw0XSxbNCwxLDYsN10sWzgsNCwxLDRdLFszLDUsNCwyXV0) or [verify all test cases](http://jelly.tryitonline.net/#code=RsWTXkZ9UArhuIrhuZZawrXigbrigbjDn8OnPwrDh-KCrOG5vuKCrGrigbc&input=&args=W1tbMSwyLDMsNF0sWzIsMyw0LDVdLFszLDQsNSw2XSxbNCw1LDYsN11dLCBbWzEsMiwzXSxbMiwwLDRdLFszLDQsNl1dLCBbWzEsMCwxXSxbMCwxLDBdLFsxLDAsMV1dLCBbWzAsMCwwXSxbMCwwLDBdLFswLDAsMF1dXQ). ### How it works ``` ḊṖZµ⁺⁸ßç? Main link. Argument: M (2D list) Ḋ Dequeue; remove the first row. Ṗ Pop; remove the last row. Z Zip; transpose rows with columns. µ Combine the chain to the left into a link. ⁺ Copy the link, executing it twice. The copy removes the first and last column and restores the orientation. ç? If the helper link returns a non-zero integer: ⁸ Return M unmodified. ß Else, recursively call the main link on the "peeled" M. Fœ^F}P Helper link. Arguments: P ("peeled" M), M (unmodified) F Flatten P. F} Flatten M. œ^ Perform multiset symmetric difference, removing the elements of P from the elements of M, respecting multiplicities, leaving precisely the elements of the outer shell. P Return the product of the remaining elements. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~26~~ 21 bytes ``` t"t5LY)y5LZ)h?}6Lt3$) ``` Input is in the following format ``` [1 0 3 4; 4 1 6 7; 8 4 1 4; 3 5 4 2] ``` So the other four test cases are ``` [1 2 3 4; 2 3 4 5; 3 4 5 6; 4 5 6 7] [1 0 1; 0 1 0; 1 0 1] [1 2 3; 2 0 4; 3 4 6] [0 0 0; 0 0 0; 0 0 0] ``` The program errors in the last test case, but produces the correct output (which is nothing). Thanks to @Dennis for noticing! [Try it online!](http://matl.tryitonline.net/#code=dCJ0NUxZKXk1TFopaD99Nkx0MyQp&input=WzEgMCAzIDQ7IDQgMSA2IDc7IDggNCAxIDQ7IDMgNSA0IDJd). Or [verify all test cases](http://matl.tryitonline.net/#code=NToiaSAgICAgICAgICAgICAgICAgICAgICUgdGFrZSBlYWNoIGlucHV0CnQidDVMWSl5NUxaKWg_fTZMdDMkKSAgICAlIGFjdHVhbCBjb2RlCl1dRCAgICAgICAgICAgICAgICAgICAgICAlIGNsb3NlIGlmIGJyYW5jaCBhbmQgbG9vcCwgYW5kIGRpc3BsYXk&input=WzEgMCAzIDQ7IDQgMSA2IDc7IDggNCAxIDQ7IDMgNSA0IDJdClsxIDIgMyA0OyAyIDMgNCA1OyAzIDQgNSA2OyA0IDUgNiA3XQpbMSAwIDE7IDAgMSAwOyAxIDAgMV0KWzEgMiAzOyAyIDAgNDsgMyA0IDZdClswIDAgMDsgMCAwIDA7IDAgMCAwXQ) (this includes wrapping code). ### Explanation This iterates as many times as the number of columns in the input matrix, which is more than enough. At each iteration, the shell is removed or kept depending on its values. ``` t % Take a matrix as input. Duplicate " % For each column (i.e. repeat that many times) t5LY) % Duplicate top of the stack. Extract first and last rows y5LZ) % Duplicate the element below the top. Extract first and last columns h % Concatenate the two arrays into a row vector ? % If all its entries are non-zero: do nothing } % Else 6Lt3$) % Get the central part % End if, end for. Implicitly display ``` [Answer] # Pyth, 19 bytes ``` .W}\0.-`H`JutCPG2HJ ``` [Test suite](https://pyth.herokuapp.com/?code=.W%7D%5C0.-%60H%60JutCPG2HJ&test_suite=1&test_suite_input=%5B%271234%27%2C+%272345%27%2C+%273456%27%2C+%274567%27%5D%0A%5B%27123%27%2C+%27204%27%2C+%27346%27%5D%0A%5B%27101%27%2C+%27010%27%2C+%27101%27%5D%0A%5B%27000%27%2C+%27000%27%2C+%27000%27%5D&debug=0) ``` .W}\0.-`H`JutCPG2HJ .W While the first function returns true, apply the second function, starting with the input. u 2H Apply the following twice to the input: PG Remove the last row C Transpose t Remove the first row This removes the outermost shell. J Save it to J ` Stringify the matrix `H Stringify the input .- Multiset difference }\0 Check if there is a '0' in the resulting string. J If that succeeds, update the current value to J. When it fails, return the current value. ``` [Answer] ## JavaScript (ES6), 74 bytes ``` f=s=>/^.*0|0\n|\n0|0.*$/.test(s)?f(s.replace(/^.*\n?|.(.*).|\n.*$/g,"$1")):s ``` Takes input in the form of a string with newlines separating each row (but no leading or trailing newline). Explanation: `/^.*0|0\n|\n0|0.*$/` is a regexp that matches contaminated squares, while `/^.*\n?|.(.*).|\n.*$/` matches that parts of the square that need to be deleted, except for the `(.*)` which needs to be kept. (This is shorter than looking ahead or behind for the newline character.) [Answer] ## Perl 5, 63 + 3 = 66 bytes ``` $_=<>;s/\A.*\n?|^.|.$|\n.*\Z//mg while/\A.*0|0$|^0|0.*\Z/;print ``` Requires the `-0` flag. Input should *not* contain a trailing newline character. [Answer] ## Pyke, 29 bytes ``` "D3lt%sBR,"2*ER3*I /)tOmtmOr; ``` [Try it here!](http://pyke.catbus.co.uk/?code=%22D3lt%25sBR%2C%222%2aER3%2aI%0A%2F%29tOmtmOr%3B&input=%5B%5B1%2C1%2C3%2C4%5D%2C+%5B1%2C1%2C6%2C7%5D%2C+%5B8%2C4%2C1%2C1%5D%2C+%5B3%2C5%2C4%2C2%5D%5D) Also 29 bytes ``` QeQhQmhQme]4sBI /)QtOmtmO=Qr; ``` [Try it here!](http://pyke.catbus.co.uk/?code=QeQhQmhQme%5D4sBI%0A%2F%29QtOmtmO%3DQr%3B&input=%5B%5B0%2C1%2C3%2C4%5D%2C+%5B1%2C1%2C6%2C7%5D%2C+%5B8%2C4%2C1%2C1%5D%2C+%5B3%2C5%2C4%2C2%5D%5D) [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~31~~ 30 bytes ``` L+hbeb.W!*F+1iRTs+yHyMHPtmPtdZ ``` [Test suite.](http://pyth.herokuapp.com/?code=L%2Bhbeb.W!*F%2B1iRTs%2ByHyMHPtmPtdZ&test_suite=1&test_suite_input=[%221034%22%2C%224167%22%2C%228414%22%2C%223542%22]%0A[%221234%22%2C%222345%22%2C%223456%22%2C%224567%22]%0A[%22123%22%2C%22204%22%2C%22346%22]%0A[%22101%22%2C%22010%22%2C%22101%22]%0A[%22000%22%2C%22000%22%2C%22000%22]&debug=0) (The last testcase errors) Improvement: made part the outer-loop extractor a function (`L+hbeb`). # Previous 31-byte version: ``` .W!*F+1iRTs++hHm+hdedHeHPtmPtdZ ``` ## How it works: The code is basically: while the product of the outershell is zero, peel it. Let us analyze the main code (Q is implicit here): ``` .W<lambda:H><lambda:Z>Q ``` Start from `Q` (input), `while` first lambda, perform second lambda. The first part would be the [lambda](https://en.wikipedia.org/wiki/Anonymous_function) in `H`: ``` !*F+1iRTs++hHm+hdedHeH ``` The second part would be the [lambda](https://en.wikipedia.org/wiki/Anonymous_function) in `Z`: ``` PtmPtdZ ``` ### The first part ``` !*F+1iRTs++hHm+hdedHeH ``` Let us analyze this: ``` s++hHm+hdedHeH s++ Concatenate: hH 1. the first row m+hdedH 2. the first and last item of each row eH 3. the last row ``` Since Pyth uses [prefix notation](https://en.wikipedia.org/wiki/Polish_notation), this would then get evaluated: ``` !*F+1iRT iRT Convert each to integer *F+1 Product ! Negate. If any element of the outer shell is zero, this would return 1. ``` ### The second part ``` PtmPtdZ mPtdZ the inner of each row Pt the inner rows ``` [Answer] # Mathematica, 78 bytes ``` NestWhile[#[[a=2;;-2,a]]&,#,Count[{#[[b={1,-1}]],#[[;;,b]]},0,3]>0&]~Check~{}& ``` Anonymous function, takes input as a matrix. Ignore any errors that may result during execution. ]
[Question] [ A [centered polygonal number](https://en.wikipedia.org/wiki/Centered_polygonal_number) is a positive integer given by the number of vertices when a point is surrounded by (increasingly larger) polygons with the same number of sides, as shown below. For example, \$p\_5(3) = 1 + 5 + 10 + 15 = 31\$ is a centered pentagonal number formed by taking a vertex and adding three layers of pentagons: [![The centered polygonal number p(5,3).](https://i.stack.imgur.com/zTxXA.png)](https://i.stack.imgur.com/zTxXA.png) --- This question, however, concerns center*less* polygonal numbers. In particular, we want to know how many ways we can write \$n\$ as the difference of two \$k\$-gonal numbers with \$k \geq 3\$—that is, a centered polygon with the center removed. For example, \$35\$ can be written as the difference of two \$k\$-gonal numbers in five ways: * \$p\_5(4) - p\_5(2) = 51 - 16\$, * \$p\_5(7) - p\_5(6) = 141 - 106\$, * \$p\_7(3) - p\_7(1) = 43 - 8\$, * \$p\_7(5) - p\_7(4) = 106 - 71\$, and * \$p\_{35}(1) - p\_{35}(0) = 36 - 1\$, the first four of which are illustrated below: [![p_5(4) - p_5(2)](https://i.stack.imgur.com/P0cq0.png)](https://i.stack.imgur.com/P0cq0.png) [![p_5(7) - p_5(6)](https://i.stack.imgur.com/23Pi5.png)](https://i.stack.imgur.com/23Pi5.png) [![p_7(3) - p_7(1)](https://i.stack.imgur.com/wBRTW.png)](https://i.stack.imgur.com/wBRTW.png) ## [p_7(5) - p_7(4)](https://i.stack.imgur.com/H88zn.png) # The Challenge This challenge will have you write a script that takes a positive integer `n` and outputs the number of ways to write \$n\$ as a center*less* polygonal number. Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the shortest code wins. The sequence begins: ``` 0, 0, 1, 1, 1, 2, 1, 2, 3, 2, 1, 5, 1, 2, 5, 3, 1, 6, 1, 5, 5, 2, 1, 8, 3, 2, 6, 5, 1, 10, 1, 4, 5, 2, 5, 12, 1, 2, 5, 8, 1, 10, 1, 5, 12, 2, 1, 11, 3, 6, 5, 5, 1, 12, 5, 8, 5, 2, 1, 19, 1, 2, 12, 5, 5, 10, 1, 5, 5, 10, 1, 18, 1, 2, 12, 5, 5, 10, 1, 11, 10, 2 ``` This is now in the OEIS as [A339010](https://oeis.org/A339010). [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` f n=sum[0^mod n q|a<-[3..n],q<-[a,3*a..n]] ``` [Try it online!](https://tio.run/##FcdNDkAwEAbQq3wLK6Hxs@UkTSUTFNGOUnbObrB7b6a4js6JWHAbL6@Lzm8DGPtNTa5rpdhk@yfK6pT@GfG0MFqEY@ETCTwFWOhSqaow8vTW0RQl70N4AQ "Haskell – Try It Online") **51 bytes** ``` f n=sum[1|a<-[3..n],b<-[1,3..n],c<-[1..n],a*b*c==n] ``` [Try it online!](https://tio.run/##JcoxDoAgDADAr3RwMkpEV3kJYShE1AgNEd18u1V0u@EWzNsUArMHUvmMWl44tnoQgkxjX8nmtyv@hLWtnVJkOOJKoCDtKx1QQcQEHsrqO8O38wHnzK1L6QE "Haskell – Try It Online") The output is the number of ways to factor \$n=abc\$ into three positive factors, where \$a \geq 3\$, \$b\$ is odd, and \$c\$ is unconstrained. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 10 bytes ``` 3÷ÝsÑÃÑÉOO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f@PD2w3MPLTs16dDO4sPTas9tPTz50DK7gFp/oJQpAA "05AB1E – Try It Online") Edit: Saved 5 bytes thanks to @ovs. Explanation: ``` 3÷L Get a list from `0` to `n//3`. sÑà Keep only factors of `n`. ÑÉO Number of odd divisors of each factor. O Output the sum. ``` [Answer] # [J](http://jsoftware.com/), 29 bytes ``` [:+/@,[=[+/\\.@(*1+i.)~"+3+i. ``` [Try it online!](https://tio.run/##dY5NDoIwEIX3nmLSDdSW0imWYBMSEhNXrtwCKyNRN17AePXaUoawMenP9L2vb@blmcomaB1kIEGDC7tQcLpezr53ouxk3/aiHAbV5XsUT8W/TFTh9ny3u98eb/g4yKWaONOQR6CyPBn5xPQ4QtQaw6EI0TIupGXorKi2pNhZDHVNuiWmIb4mHlPogaComk1Ss6UWM/mIc1hNHTCZ6c/aEY/ruGYl9Waw5YHNXw6XAYz/AQ "J – Try It Online") ``` [:+/@,[=[+/\\.@(*1+i.)~"+3+i. i. 0…N-1 3+ 3…N+2 "+ for each y in 3…N+2: [ (*1+i.)~ y * 0…N, thus f.e. 5 10 15 20 … for p_5 \\.@ take every possible sublist +/ and sum it [= which sums are equal to N? [:+/@, count the true bits ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :3ḍƇ⁸ÆDFḂS ``` A monadic Link accepting \$n\$ which yields the count. **[Try it online!](https://tio.run/##y0rNyan8/9/K@OGO3mPtjxp3HG5zcXu4oyn4////xqYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ASMA3P9qZWxsef//OjPhuI3Gh@KBuMOGREbhuIJT/8OH4oKs//84Mg "Jelly – Try It Online"). ### How? ``` :3ḍƇ⁸ÆDFḂS - Link: n 3 - three : - (n) integer divide (3) -> x Ƈ - filter keep those v in [1..x] for which: ḍ - (v) divides: ⁸ - chain's left argument, n ÆD - divisors (of each) F - flatten Ḃ - least significant bit (of each) S - sum ``` [Answer] # JavaScript (ES6), 49 bytes Uses [the method described by @xnor](https://codegolf.stackexchange.com/a/215392/58563). ``` f=(n,d=k=1)=>k<=n&&!(n/~++k%d)+f(n,d>n||k--&&d+2) ``` [Try it online!](https://tio.run/##FctBCsIwEADAr6wH013SrFTxZgK@Q0RC00qbuimpCELx61HPw4z@5Zc2D/PTSApdKb1FqYONtiHr4smKUhuU3UfruA2k@786WddojFJB76m0SZY0dTylO16Y@Zyzf@PhSFd@@BnxVoMQWAe/CxoaIh7TIFhBRVS@ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input d = k = 1 // d = odd divisor, k = other divisor ) => // k <= n && // stop if k is greater than n !( // otherwise: n / ~++k // - increment k % d // - increment the final result if d is a divisor of n / (k + 1) ) + // f( // add the result of a recursive call: n, // - pass n unchanged d > n || // - if d is greater than n, leave k unchanged and reset d to 1 k-- && d + 2 // otherwise, decrement k and add 2 to d ) // end of recursive call ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` Sum[Boole[(2i j-i)∣#],{i,3,#},{j,#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0N9opPz8nNVrDKFMhSzdT81HHYuVYnepMHWMd5Vqd6iwgGav2P7A0M7UkOqAoM69EQd8hXd8hKDEvPdXB0MAg9v9/AA "Wolfram Language (Mathematica) – Try It Online") *special thanks to @att for saving 20 bytes* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` NθFθFθFθ⊞υ×⁺³ι×⊕⊗κ⊕λI№υθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQQKcDSoszNEp1FEIyc1OLNQJySos1jHUUMjVhIp55yUWpual5JakpGi75pUk5QDpbEyiNLJGjCQTWXAFFmXklGs6JxUAivxTIBJpbCJL5/9/Y9L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Port of @xnor's answer. Explanation: ``` Nθ ``` Input `n`. ``` FθFθFθ ``` Create loops `i`, `k` and `l` ranging from `0` to `n`. ``` ⊞υ×⁺³ι×⊕⊗κ⊕λ ``` Calculate `a*b*c` where `a=i+3`, `b=2k+1` and `c=l+1`. ``` I№υθ ``` Count how many times this equals `n`. [Answer] # [Python 3](https://docs.python.org/3/), ~~84~~ 65 bytes Saved a whopping 19 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` lambda n,R=range:sum(n%q<1for a in R(3,n+1)for q in R(a,n+1,2*a)) ``` [Try it online!](https://tio.run/##dVDLboMwELzzFXupsBsqZU2gNCr9iFyTHFxiGquJQ4BIrRDfTm3DIi61VtbO7OxDU/2255uJhzI/DBd5/TxJMNEur6X5UtvmcWXm6f6O5a0GCdrAjsWRWSF3xH0kpCMi8Sw5H9RPpYpWnSAHto7ABlII@mPKE2IST9o8JT4hTUb6lPQ4Dt2QyLFiMSlbqqbiWEf0w1LagGNx7Jk34tt8rpiV68VhE8DsXx1OBwgeFGdVfKva@REeHuJ1U4QR@AzjkAfORu1s9H6zizKMLOR8G4B9xvZqWAF61FhUMsM9UBaQfK@PnqtqbVpWhp3p4eUDuqaHbjpir/K8OfYhH/4A "Python 3 – Try It Online") Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s method from his [Haskell answer](https://codegolf.stackexchange.com/a/215392/9481). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes ``` .+ $* M!&`(.+)$(?<=^\1{3,}) m&`(.(..)*)$(?<=^\1+) ``` [Try it online!](https://tio.run/##K0otycxL/K@nzaWixeWrqJYAZPkncKlq@CYYIolq6GlrqmjY29jGxRhWG@vUanLlggQ19PQ0teAS2pr//xubAgA "Retina 0.8.2 – Try It Online") Link includes test suite that checks all numbers from `1` to the input. Explanation: ``` .+ $* ``` Convert to unary. ``` M!&`(.+)$(?<=^\1{3,}) ``` List (`!`) all (`&`) factors not greater than `n/3`. ``` m&`(.(..)*)$(?<=^\1+) ``` Count the number of odd factors of all the factors. (The `M` is implicit as this is the last stage.) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~79~~ ~~63~~ 62 bytes Saved a whopping 16 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved a byte thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` a;q;s;f(n){for(s=0,q=a=3;n/q||n/(q=++a);)s+=n%(q-=2*a)<1;n=s;} ``` [Try it online!](https://tio.run/##dVLRboIwFH33K25ITFqBSHEaTO1e3L5i@EBqUbKtCjUZmfLrYwV6mT6MlOb23HNPL@ciw4OUbZvxkhueE02v@akiRkRBKTKx4Hpe3m56Tkrh@xnl1PhCT0kZiniW0Q3jWhjetIW@wGdWaEIn1wnYpwNUfVbyovZvOxBwjQKwi@GKcV9gvERk2YM2XiG@RE6C/BXy2SD6hKQOje@UknuWSw55xnqxFd7AhuRQM97I1mO78ciM7hpzB5b8y2OugbjhvTfymFUzeVTyXVXWG@jc8dL6NU7r9UtaJ1svADxv7bvwXKGdDJDO2ULvVW3LIu7CDZjiW51ygp7TuQNmI8LB93s2hWFGOCdtlQYZHxh/SBmb6n6KR1RZdBxuX7n7I5wrS8mJN91D@Ax2n5pUe4EOwASAX22EUDun2kya9kfmH9nBtOHXLw "C (gcc) – Try It Online") Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s method from his [Haskell answer](https://codegolf.stackexchange.com/a/215392/9481). [Answer] # [Ruby](https://www.ruby-lang.org/), 76 bytes ``` ->n{(1..n/3).select{|k|n%k==0}.sum{|o|(1..o).select{|i|o%i==0}.sum{|j|j%2}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9P31hTrzg1JzW5pLomuyZPNdvW1qBWr7g0t7omvwakIh8hn1mTr5qJkM@qyVI1qq2t/Z@WX6SQqZCZpwBUbmrApaCgUKCQFp0Zy5Wal/IfAA "Ruby – Try It Online") Based on Neil's answers. [Answer] # Java 8, 73 bytes ``` n->{int r=0,a=2,t;for(;a++<n;)for(t=a;t<=n;t+=2*a)if(n%t<1)r++;return r;} ``` Port of [*@Noodle9*'s Python 3 answer](https://codegolf.stackexchange.com/a/215406/52210), which uses the same method as [*@xnor*'s Haskell answer](https://codegolf.stackexchange.com/a/215392/52210). [Try it online.](https://tio.run/##fVJRS8MwEH73VxwFoTFbaaobdWkEER/di4/iQ@wyyezSmaZDGfvtNblmMBClNMl9333f3TXdyL2cblYfQ93IroMnqc3hAkAbp@xa1gqWIUQA6jSshnCPHC/80jnpdA1LMCBgMNO7Q0iwIp9IUUwcX7c25ZLSynASzk5I7iphuKOiuJJEr1Nz6SpGLKXcKtdbA5YfBx7Md/1b481jjX2rV7D13aXPzmrz/vIKkoytjQCor52qnVr5VpIccmD4FPhe4z7D88xHDOYYzxAvkZ8jz4LwBgkfFlFRnhjEAsqYF83RggUs5Ixu7HYsW4xkHgvhgZW/OIbOBSR8HOa7c2qbtb3Ldn4s15g0eYyTLSChpykJP59d1q6XTZg82oSvHe5CC8ZBV6Is/EYpQRJiPhUm83dKaPJf9XvMXXg2oaOO/J380Frr@zvvNFOfXtOlURv/nuPwAw) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=0, // Result-sum, starting at 0 a=2, // Temp-integer `a`, starting at 2 t; // Temp-integer `t`, uninitialized for(;a++<n;) // Loop `a` in the range [1, n]: for(t=a;t<=n; // Inner loop `t` in the range [a, n], t+=2*a) // in increments of 2a if(n%t<1) // If the input is evenly divisible by `t`: r++; // Increase the result-sum by 1 return r;} // And after the loops, return the result-sum ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` 3/╒÷mÉî*──¥Σ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/99Y/9HUSYe35x7uPLxO69GUBiA6tPTc4v//DbmMuIy5TLhMucy4zLksuCy5DA24jEy5jE25TA24zE2BXAMA) **Explanation:** ``` 3/ # Integer-divide the (implicit) input-integer by 3 ╒ # Pop and push a list in the range [0, input//3] ÷ # Check for each that they evenly divide the (implicit) input # (1 if truthy; 0 if falsey) m # Then map each boolean to, É # using the following three characters as inner code-block: î* # Multiply the boolean by the 1-based map-index ─ # Pop and push a list of its divisors ─ # Flatten this list of list of integers ¥ # Modulo-2 on each Σ # And sum those together # (after which the entire stack joined together is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~40~~ 33 bytes (SBCS) *Saved 7 bytes thanks to @[Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!* Port of Neil's 05AB1E [answer](https://codegolf.stackexchange.com/a/215389/95792). ``` {+/∊(⊢(|⍨<2|⊢)1+⍳)¨⍵(⊢∩∨)⍳1+⌊⍵÷3} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6u19R91dGk86lqkUfOod4WNUQ2QqWmo/ah3s@ahFY96t4KkHnWsfNSxQhMoBpTo6QKKHt5uXPs/DWjCo96@R13Nj3rXPOrdcmi98aO2iUCzg4OcgWSIh2fw/7RDK8CGGZsCAA "APL (Dyalog Unicode) – Try It Online") ``` {+/∊(⊢(|⍨<2|⊢)1+⍳)¨⍵(⊢∩∨)⍳1+⌊⍵÷3} ⍳1+⌊⍵÷3 ⍝ Range to n//3 + 1 ⍵(⊢∩∨) ⍝ Keep divisors of n ¨ ⍝ For each divisor ∊(⊢(|⍨<2|⊢)1+⍳) ⍝ A train to find odd divisors of the divisor, not sure how it works exactly 1+⍳) ⍝ Make a range from 2 to the divisor+1 (⊢ ⍝ On this side, just give back the divisor (|⍨<2|⊢) ⍝ Checks that the element of the range divides the divisor and that it's odd (|⍨ ⍝ The possible divisor mod its divisor < ⍝ Is less than 2|⊢) ⍝ 2 mod the divisor's possible divisor ∊ ⍝ Turn into vector so a single sum is needed +/ ⍝ Sum that ``` ]
[Question] [ A [Pythagorean Triple](https://en.wikipedia.org/wiki/Pythagorean_triple) is a positive integer solution to the equation: [![Pythagorean triple](https://i.stack.imgur.com/7aloH.png)](https://i.stack.imgur.com/7aloH.png) A Trithagorean triple is a positive integer solution to the equation: [![Trithagorean equation](https://i.stack.imgur.com/oRG0W.png)](https://i.stack.imgur.com/oRG0W.png) Where Δn finds the nth [triangular number](https://en.wikipedia.org/wiki/Triangular_number). All Trithagorean triples are also solutions to the equation: [![enter image description here](https://i.stack.imgur.com/syeXo.png)](https://i.stack.imgur.com/syeXo.png) ## Task Given a positive integer `c`, output all the pairs of positive integers `a,b` such that the sum of the `a`th and `b`th triangular numbers is the `c`th triangular number. You may output the pairs in whatever way is most convenient. You should only output each pair once. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ## Test Cases ``` 2: [] 3: [(2, 2)] 21: [(17, 12), (20, 6)] 23: [(18, 14), (20, 11), (21, 9)] 78: [(56, 54), (62, 47), (69, 36), (75, 21), (77, 12)] 153: [(111, 105), (122, 92), (132, 77), (141, 59), (143, 54), (147, 42), (152, 17)] 496: [(377, 322), (397, 297), (405, 286), (427, 252), (458, 190), (469, 161), (472, 152), (476, 139), (484, 108), (493, 54), (495, 31)] 1081: [(783, 745), (814, 711), (836, 685), (865, 648), (931, 549), (954, 508), (979, 458), (989, 436), (998, 415), (1025, 343), (1026, 340), (1053, 244), (1066, 179), (1078, 80), (1080, 46)] 1978: [(1404, 1393), (1462, 1332), (1540, 1241), (1582, 1187), (1651, 1089), (1738, 944), (1745, 931), (1792, 837), (1826, 760), (1862, 667), (1890, 583), (1899, 553), (1917, 487), (1936, 405), (1943, 370), (1957, 287), (1969, 188)] 2628: [(1880, 1836), (1991, 1715), (2033, 1665), (2046, 1649), (2058, 1634), (2102, 1577), (2145, 1518), (2204, 1431), (2300, 1271), (2319, 1236), (2349, 1178), (2352, 1172), (2397, 1077), (2418, 1029), (2426, 1010), (2523, 735), (2547, 647), (2552, 627), (2564, 576), (2585, 473), (2597, 402), (2622, 177), (2627, 72)] 9271: [(6631, 6479), (6713, 6394), (6939, 6148), (7003, 6075), (7137, 5917), (7380, 5611), (7417, 5562), (7612, 5292), (7667, 5212), (7912, 4832), (7987, 4707), (8018, 4654), (8180, 4363), (8207, 4312), (8374, 3978), (8383, 3959), (8424, 3871), (8558, 3565), (8613, 3430), (8656, 3320), (8770, 3006), (8801, 2914), (8900, 2596), (8917, 2537), (9016, 2159), (9062, 1957), (9082, 1862), (9153, 1474), (9162, 1417), (9207, 1087), (9214, 1026), (9229, 881), (9260, 451), (9261, 430), (9265, 333)] ``` [Answer] # Mathematica, ~~53~~ ~~49~~ 48 bytes ``` Solve[{x.(x+1)==#^2+#,a>=b>0},x={a,b},Integers]& ``` Example: ``` In[1]:= Solve[{x.(x+1)==#^2+#,a>=b>0},x={a,b},Integers]&[21] Out[1]= {{a -> 17, b -> 12}, {a -> 20, b -> 6}} ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 13 bytes ``` :Ys&+G:s=R&fh ``` Each pair is output with the smaller number first. [Try it online!](https://tio.run/nexus/matl#@28VWaym7W5VbBuklpbx/7@hgYUhAA "MATL – TIO Nexus") ### Explanation Consider input `3`. ``` : % Implicitly input n. Push [1 2 ... n] % STACK: [1 2 3] Ys % Comulative sum % STACK: [1 3 6] &+ % All pairwise sums % STACK: [2 4 7; 4 6 9; 7 9 12] G:s % Push 1+2+...+n % STACK: [2 4 7; 4 6 9; 7 9 12], 6 = % Is equal? % STACK: [0 0 0; 0 1 0; 0 0 0] R % Upper triangular part of matrix. This removes duplicate pairs % STACK: [0 0 0; 0 1 0; 0 0 0] &f % Push row and column indices (1-based) of non-zero entries % STACK: 2, 2 h % Concatenate horizontally. Implicitly display % STACK: [2, 2] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` j‘c2ḅ- ŒċçÐḟ ``` [Try it online!](https://tio.run/nexus/jelly#@5/1qGFGstHDHa26XEcnHek@vPzwhIc75v@3Vjrc/qhpjTcQu///b6SjYKyjYGQIxEDa3EJHwdDUGAA "Jelly – TIO Nexus") ### How it works ``` ŒċçÐḟ Main link. Argument: c Œċ Yield all 2-combinations w/repetition of elements of [1, ..., c]. çÐḟ Filterfalse; keep only 2-combinations for which the helper link returns 0. j‘c2ḅ- Helper link. Left argument: [a, b]. Right argument: c j Join [a, b] with separator c, yielding [a, c, b]. ‘ Increment; yield [a+1, c+1, b+1]. c2 Combination count; compute [C(a+1,c), C(c+1,c), C(b+1,c)], yielding [½a(a+1), ½c(c+1), ½b(b+1)]. ḅ- Convert from base -1 to integer, yielding ½(-1)²a(a+1) + ½(-1)¹c(c+1) + ½(-1)⁰b(b+1) = ½(a(a+1) - c(c+1) + b(b+1)), which is 0 if and only if a(a+1) + b(b+1) = c(c+1). ``` [Answer] ## Python 2, 69 bytes [Try it online](https://tio.run/nexus/python2#87GN@Z@TmJuUkqiQbBWtkaiTpJmWX6SQqJCZp1CUmJeeqpEMFkhCCCRqG2pmptUlaiXa2iZr1SXr1iVpJcX@LyjKzCtR8NEwtDS30PwPAA) ``` lambda c:[(a,b)for a in range(c)for b in range(a+1)if~a*a==c*~c-~b*b] ``` -9 bytes, thanks to @WheatWizard [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes ``` RS ŒċÇ€S$⁼¥ÐfÇ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//UlMKxZLEi8OH4oKsUyTigbzCpcOQZsOH////MjE "Jelly – Try It Online") This is too long for sure... Explanation: ``` ŒċÇ€S$⁼¥ÐfÇ (main) Arguments: z Œċ Return [[1, 1], [1, 2], ..., [1, z], [2, 2], ..., [z, z]] Ç Return T(z) Ç€S$⁼¥Ðf Only keep the pairs such as ΣT(a, b)=T(z) RS (helper 1) Arguments: z R [1, 2, ..., z] S Take the sum ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 72 bytes ``` {for(n=$1;++i<=n;)for(j=i;j<=n;++j)if(i^2+j^2+i+j==n^2+n)$0=$0" "i":"j}1 ``` [Try it online!](https://tio.run/nexus/awk#FYixCsMwDAX39xXFeIjRYslt4tTVr3QMSIMLXUu/3XGGg7sbP9Pcjs936Rq5EdlLe0vXcLXmVxF5smOxt5BPjFy1T@kpZo053IKFZ/A/jyEoEIYUbBX8KLjvKzhXBu/zyCoVu2yMEw "AWK – TIO Nexus") Output is `c a1:b1 a2:b2 ...`. The TIO link has 4 extra bytes `i=0;` to allow for multiline input. This isn't efficient at all, but it works. :) [Answer] # PHP, 94 Bytes ``` for($a=$c=$argn;$a--;)for($b=$a;$b;$b--)$a**2+$a+$b**2+$b!=$c**2+$c?:$e[]=[$a,$b];print_r($e); ``` [Try it online!](https://tio.run/nexus/php#HYvBCoMwEAXv/YvCOxjtHvRS2jX4ISKyG6L2EkPw13uOITCHYWDGKR7xAUl7sJ/h3XPeztRALJytlSFEbGrVkhhaIDKQth06SAetos/yVHPTF35e7Ax5QReO6ReutfzecM7/cJITd/gb "PHP – TIO Nexus") [Answer] ## Haskell, 50 bytes ``` f c=[(a,b)|a<-[1..c],b<-[1..a],a^2+a+b^2+b==c^2+c] ``` Usage example: `f 21` -> `[(17,12),(20,6)]`. [Try it online!](https://tio.run/nexus/haskell#@5@mkGwbrZGok6RZk2ijG22op5ccq5MEYSXG6iTGGWknaicBySRb22QglRz7PzcxM0/BViEln0tBQaGgKDOvREFFIU3ByBCVb2hq/B8A "Haskell – TIO Nexus") Uses the 2nd equation. [Answer] # [J](http://jsoftware.com/), 35 bytes ``` 1+[:~.,~/:~@#:[:I.@,@({:=+/~)2!2+i. ``` [Try it online!](https://tio.run/nexus/j#@5@mYGulYKgdbVWnp1Onb1XnoGwVbeWp56DjoFFtZautX6dppGiknanHxZWanJGvkKZgZPj/PwA "J – TIO Nexus") [Answer] # Axiom, ~~281~~ ~~204~~ ~~196~~ 191 bytes ``` q(b,m)==(r:=1+4*m;v:=4.*b*(b+1);r<v=>0;(sqrt(r-v)-1)/2);g(c:NNI):Any==(r:List List INT:=[];i:=0;repeat(i:=i+1;i>=c=>break;w:=q(i,c^2+c);w>=i and fractionPart(w)=0=>(r:=cons([w::INT,i],r)));r) ``` test and ungolf ``` -- if m=c^2+c than a^2+a+b^2+b-m=0 has the solutions [a,b] with a>0,b>0 -- if it is used a=(-1+sqrt(1+4*m-4*(b)*(b-1)))/2 because the other return a<0 -- o(b,m) return that solution if 1+4*m-4*(b)*(b-1)>0 [so exist in R sqrt] else return 0 o(b,m)==(r:=1+4*m;v:=4.*b*(b+1);r<v=>0;(sqrt(r-v)-1)/2) --it Gets one not negative integer c; return one list of list(ordered) of 2 integers --[a,b] with a^2+a+b^2+b=c^2+c gg(c:NNI):List List INT== r:List List INT:=[] -- initialize the type make program more fast at last it seems 10x i:=0 repeat i:=i+1 i>=c=>break w:=o(i,c^2+c) w>=i and fractionPart(w)=0=>(r:=cons([w::INT,i],r)) r (6) -> [[i,g(i)] for i in [2,3,21,23,78,153,496,1081,1978,2628,9271]] (6) [[2,[]], [3,[[2,2]]], [21,[[17,12],[20,6]]], [23,[[18,14],[20,11],[21,9]]], [78,[[56,54],[62,47],[69,36],[75,21],[77,12]]], [153,[[111,105],[122,92],[132,77],[141,59],[143,54],[147,42],[152,17]]], [496, [[377,322], [397,297], [405,286], [427,252], [458,190], [469,161], [472,152], [476,139], [484,108], [493,54], [495,31]] ] , [1081, [[783,745], [814,711], [836,685], [865,648], [931,549], [954,508], [979,458], [989,436], [998,415], [1025,343], [1026,340], [1053,244], [1066,179], [1078,80], [1080,46]] ] , [1978, [[1404,1393], [1462,1332], [1540,1241], [1582,1187], [1651,1089], [1738,944], [1745,931], [1792,837], [1826,760], [1862,667], [1890,583], [1899,553], [1917,487], [1936,405], [1943,370], [1957,287], [1969,188]] ] , [2628, [[1880,1836], [1991,1715], [2033,1665], [2046,1649], [2058,1634], [2102,1577], [2145,1518], [2204,1431], [2300,1271], [2319,1236], [2349,1178], [2352,1172], [2397,1077], [2418,1029], [2426,1010], [2523,735], [2547,647], [2552,627], [2564,576], [2585,473], [2597,402], [2622,177], [2627,72]] ] , [9271, [[6631,6479], [6713,6394], [6939,6148], [7003,6075], [7137,5917], [7380,5611], [7417,5562], [7612,5292], [7667,5212], [7912,4832], [7987,4707], [8018,4654], [8180,4363], [8207,4312], [8374,3978], [8383,3959], [8424,3871], [8558,3565], [8613,3430], [8656,3320], [8770,3006], [8801,2914], [8900,2596], [8917,2537], [9016,2159], [9062,1957], [9082,1862], [9153,1474], [9162,1417], [9207,1087], [9214,1026], [9229,881], [9260,451], [9261,430], [9265,333]] ] ] Type: List List Any ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~30~~ 28 bytes ``` {_,2m*:$_&f+{{_)*}%~+=},1f>} ``` Anonymous block expecting its argument on the stack and leaving the result on the stack. [Try it online!](https://tio.run/nexus/cjam#K8r8Xx2vY5SrZaUSr5amXV0dr6lVq1qnbVurY5hmV/u/ruC/kTEA "CJam – TIO Nexus") ### Explanation I will refer to the input as `n` ``` _, e# Copy n, and get the range from 0 to n-1. 2m* e# Get the 2nd Cartesian power of this range. :$_& e# Sort the pairs and deduplicate, to get all unique pairs. f+ e# Prepend n to each pair. { e# Filter these triplets; keep only those that give a truthy result: { e# Map this block over the triplet: _)* e# Multiply x by x+1. (i.e. x^2 + x) }% e# (end map) ~+= e# Check if the sum of the second and third is equal to the first. }, e# (end filter) 1f> e# Remove the first element from all remaining triplets. ``` [Answer] # Pyth - ~~23~~ 21 bytes ``` L*bhbfqyQ+yhTyeT.CUQ2 ``` [Try it](https://pyth.herokuapp.com/?code=L%2F%2abhb2fqyQ%2ByhTyeT.CUQ2&input=2&test_suite=1&test_suite_input=2%0A3%0A21%0A23%0A78&debug=0) ``` L*bhbfqyQ+yhTyeT.CUQ2 L*bhb Define y(b)=b*(b+1) .CUQ2 All pairs of numbers less than the input fqyQ+yhTyeT Filter based on whether y(input) == y(1st elem. of pair) + y(2nd elem. of pair) ``` [Answer] ## JavaScript (ES6), 83 bytes ``` c=>[...Array(c*c)].map((_,x)=>[x%c,x/c|0]).filter(([a,b])=>a>=b&a++*a+b++*b==c*c+c) ``` ### Test cases Omitting here the largest inputs that take too much time for the snippet. ``` let f = c=>[...Array(c*c)].map((_,x)=>[x%c,x/c|0]).filter(([a,b])=>a>=b&a++*a+b++*b==c*c+c) console.log(JSON.stringify(f(2))) console.log(JSON.stringify(f(3))) console.log(JSON.stringify(f(21))) console.log(JSON.stringify(f(23))) console.log(JSON.stringify(f(78))) console.log(JSON.stringify(f(153))) console.log(JSON.stringify(f(496))) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes ``` fo=Σ¹ṁΣüOπ2 ``` [Try it online!](https://tio.run/##AR0A4v9odXNr//9mbz3Oo8K54bmBzqPDvE/PgDL///8yMw "Husk – Try It Online") `Σ` has a mode where it returns the nth triangular number, which is very useful here. -1 byte from Dominic van Essen. ## Explanation ``` fo=Σ¹ṁΣüOπ2 π2 cartesian power 2 for range 1..n(all possible pairs) üO uniquify, ignoring ordering fo filter by the following 2 functions: ṁΣ triangular numbers of the pair summed = equals Σ¹ nth triangular number? ``` ]
[Question] [ You're driving a car in an infinite city whose blocks are pentagons arranged in [the order-4 pentagonal tiling](https://en.wikipedia.org/wiki/Order-4_pentagonal_tiling). At each step, you proceed to the next intersection and choose whether to continue left, right, or straight. A sequence of choices that returns you to your initial state (street segment and direction) is called a *round trip*. Write a function (or program) that takes a string of `L`/`R`/`S`s and returns (or outputs) one of two values, indicating whether the input represents a round trip. Examples: ``` LLLLL -> yes (this is a drive around one pentagonal block) LLLLSRRRRS -> yes SRRSRRSRRSRR -> yes (empty sequence) -> yes R -> no LLLLLL -> no (starts with a round trip but leaves initial state) SLLLLR -> no (returns to initial street but opposite direction) ``` (Note that `L` and `R` are not in-place rotations; every move includes entering *and exiting* the next intersection.) [Answer] # [Python](https://www.python.org), 259 bytes ``` from numpy import* k=kron u=lambda x:fromiter(base_repr(x,3),int).reshape(4,4)-1 s=k(u(25952008),u(27752297))+k(u(21543856),u(18501071)) t=k(u(21169798),i:=eye(4,4,0,object)) a=b=2*k(i,i) for c in input():b=[s@t,s,s@t@t@t][-ord(c)%4]@b//2 print(all(a*a==b*b)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVDLasMwEKT05q_wpaB15cZyrPgBgnxDegyhSI5MVD8kZBnib-nFl_bUL-rXVE5K2WFZdmaWZT6-zOwueliWz8k1cfHz8NhY3YfD1Js5VL3R1kVBy1qrh2BiHe_FmYfXahUpJy0SfJRvVhqLrngLWA0OXqwcL9xIlOEMYhKMrEUTSmlJ0yQpAPs5z2maljnA840iNNsWdLdSpKAJSXICELi7j5BdmZfepyom59tVnGAt3mXtvIozwdKoRQorCBptwzpUg4eZHIJKsOO4d3jEvq91OsbanlENT9lpLzabNDDW_4x41yEeccZEJADuWfxFsny_Hg7_uO9-AQ) ### How it works Uses only big integer linear algebra. This is probably not the golfiest solution method, but OP said they’re interested in this approach. The rigid motions of the hyperbolic plane are [isomorphic](https://en.wikipedia.org/wiki/SL2(R)#M%C3%B6bius_transformations) to \$\mathrm{PSL}(2, \mathbb R)\$, which can be represented by 2×2 matrices acting on \$\mathbb R^2\$. \begin{gather\*} S = \begin{bmatrix} \frac1{\sqrt 2}(-\sqrt φ + φ + \sqrt φ^3) & 0 \\ 0 & \frac1{\sqrt 2}(\sqrt φ + φ - \sqrt φ^3) \end{bmatrix}, \\ T = \begin{bmatrix} \frac1{\sqrt2} & -\frac1{\sqrt2} \\ \frac1{\sqrt2} & \frac1{\sqrt2} \end{bmatrix}, \quad L = ST, \quad R = ST^3. \end{gather\*} However, in the hyperbolic plane, floating-point errors accumulate exponentially with distance, so we need a way to do the same calculation exactly. For our purposes, we only need to work in the 16-dimensional sublattice \$M\mathbb Z^{16} ⊂ \mathbb R^2\$ generated by the columns of $$M = \left[\begin{smallmatrix} 1 & \sqrt φ & φ & \sqrt φ^3 & \frac{1}{\sqrt 2} & \frac{\sqrt φ}{\sqrt 2} & \frac{φ}{\sqrt 2} & \frac{\sqrt φ^3}{\sqrt 2} & 0 & 0 & 0 & 0 & -\frac{1}{\sqrt 2} & -\frac{\sqrt φ}{\sqrt 2} & -\frac{φ}{\sqrt 2} & -\frac{\sqrt φ^3}{\sqrt 2} \\ 0 & 0 & 0 & 0 & \frac{1}{\sqrt 2} & \frac{\sqrt φ}{\sqrt 2} & \frac{φ}{\sqrt 2} & \frac{\sqrt φ^3}{\sqrt 2} & 1 & \sqrt φ & φ & \sqrt φ^3 & \frac{1}{\sqrt 2} & \frac{\sqrt φ}{\sqrt 2} & \frac{φ}{\sqrt 2} & \frac{\sqrt φ^3}{\sqrt 2} \end{smallmatrix}\right].$$ In order for \$L, S, R\$ to act on this lattice, we need it to be closed under multiplication by \$\sqrt2\$ and \$\sqrt φ\$, which it is; for example: $$ \sqrt2 \begin{bmatrix}1 \\ 0\end{bmatrix} = \begin{bmatrix}\frac1{\sqrt 2} \\ \frac1{\sqrt 2}\end{bmatrix} - \begin{bmatrix}-\frac1{\sqrt 2} \\ \frac1{\sqrt 2}\end{bmatrix}, \quad \sqrt φ\begin{bmatrix}\sqrt φ^3 \\ 0\end{bmatrix} = \begin{bmatrix}1 \\ 0\end{bmatrix} + \begin{bmatrix}φ \\ 0\end{bmatrix}. $$ We also need to multiply some points by \$\frac12\$, but it turns out that as long as we use \$2I\$ as the initial matrix rather than \$I\$, those points always have even coefficients. The resulting actions are given by \begin{gather\*} SM = \frac12 M\left[\begin{smallmatrix} 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & -1 & 0 \\ 0 & 0 & 0 & 0 & -1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & -1 & -1 \\ 0 & 0 & 0 & 0 & 1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & -1 & 0 & -1 & -1 \\ 0 & 0 & 0 & 0 & 1 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & -1 & -1 & 0 & -1 \\ 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 0 & 0 & 0 & 0 \\ -1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & -1 & 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & -1 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 1 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & -1 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & -1 & 1 \\ 0 & 0 & 0 & 0 & 1 & 0 & 1 & -1 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & -1 \\ 0 & 0 & 0 & 0 & -1 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 1 \\ 0 & -1 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & -1 & -1 & 0 & 0 & 0 & 0 & 1 & 0 & -1 & 1 & 0 & 0 & 0 & 0 \\ -1 & 0 & -1 & -1 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & -1 & 0 & 0 & 0 & 0 \\ -1 & -1 & 0 & -1 & 0 & 0 & 0 & 0 & -1 & 1 & 0 & 1 & 0 & 0 & 0 & 0 \end{smallmatrix}\right], \\ TM = M\left[\begin{smallmatrix} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \end{smallmatrix}\right], \end{gather\*} which we compress slightly using the [Kronecker product](https://numpy.org/doc/stable/reference/generated/numpy.kron.html). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes ``` \d $*RF FRRRFRRRF RFRFR FRFRF RRRFRRRFRRR }`FF|RRRR ^$ ``` [Try it online!](https://tio.run/##K0otycxL/B@SEOMTHJRgaGTMpaqh4Z7wPyaFS0UryI3LLSgoCIy5gJRbEBeIALKhgkDMVZvg5lYTBGJxxan8/@8DAlwgIhgkGMwFpOCIiysILAVUEQwigwA "Retina 0.8.2 – Try It Online") Takes input as `123` but test suite converts from `LSR` for convenience. Explanation: Similar approach to @AndrovT's Vyxal answer, but reduces the problem further to two movements, `R` (rotate on the spot without moving) and `F` (flip around and move to the next intersection). ``` \d $*RF ``` Convert digits to the appropriate `R` and `F` movements. ``` FRRRFRRRF RFRFR FRFRF RRRFRRRFRRR ``` Simplify moving along three sides of the same pentagon to moving along the other two sides. ``` FF|RRRR ``` Remove redundant multiples of `F` and `R` movements. ``` }` ``` Repeat until the path cannot be simplified further. ``` ^$ ``` Check whether the path is now empty. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes ``` fC‹\1꘍›ṅ»¬½ẆZ¶ẋḞ≥P»3R2€yøV ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZkPigLlcXDHqmI3igLrhuYXCu8Kswr3huoZawrbhuovhuJ7iiaVQwrszUjLigqx5w7hWIiwiIiwiXCJSUlJSUlwiXG5cIkxMTExTUlJSUlNcIlxuXCJTUlJTUlJTUlJTUlJcIlxuXCJcIlxuXCJSXCJcblwiU1wiXG5cIkxMTExMTFwiXG5cIlNMTExMUlwiXG5cIlNTU1NSU1JSU0xTTExSTFJMXCIiXQ==) Port of [*@Neil's* Retina answer](https://codegolf.stackexchange.com/a/259059/116074). Returns a falsey value if the path is closed and truthy otherwise. ``` fC # covert to a list of charcodes ‹ # decrement \1꘍ # prepend that many spaces to "1" › # replace spaces with zeros ṅ # join by nothing »...» # push the compressed integer 36932780194571550874 3R # convert to base 3 "100010001201010210101200010001000200002211" 2€ # split on 2 ["100010001", "01010", "10101", "00010001000", "0000", "", "11"] y # uninterleave ["100010001", "10101", "0000", "11"], ["01010", "00010001000", ""] øV # replace strings from the first list with corresponding strings from the second list while it's possible ``` ## Old: # [Vyxal](https://github.com/Vyxal/Vyxal), 44 bytes ``` ‹‹C‹λ2Ẏk₁⁼[ḢḢǔk₁-3Y]₌ǔh¬[3₌ȯẎ∑J]:hċßN4%;İṪta ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oC54oC5Q+KAuc67MuG6jmvigoHigbxb4bii4biix5Rr4oKBLTNZXeKCjMeUaMKsWzPigozIr+G6juKIkUpdOmjEi8OfTjQlO8Sw4bmqdGEiLCIiLCJcIlJSUlJSXCJcblwiTExMTFNSUlJSU1wiXG5cIlNSUlNSUlNSUlNSUlwiXG5cIlwiXG5cIlJcIlxuXCJTXCJcblwiTExMTExMXCJcblwiU0xMTExSXCJcblwiU1NTU1JTUlJTTFNMTFJMUkxcIiJd) Returns `0` for closed paths and `1` otherwise. First it represents the turns right, straight, left and backwards with numbers 1, 2, 3 and 0 respectively. If the path is closed with length greater than 1, then it can be reduced to path `0, 0` with the following transformations: 1. Rotating the path (e. g. `0, 1, 2, 1, 3 -> 3, 0, 1, 2, 1`) 2. Changing right turns to left turns and vice versa (e. g. `0, 1, 2, 1, 3 -> 0, 3, 2, 3, 1`) 3. If the path contains the pattern `a, 0, b` replacing it with `a+b mod 4` (e. g. `2, 0, 1, 3 -> 3, 3`) 4. If the path contains the pattern `a, 1, 1, b` replacing it with `(a-1 mod 4), 3, (b-1 mod 4)` (e. g. `1, 1, 1, 2 -> 0, 3, 1`) This is because a closed path has at least one of `0`, `[1, 1]` and `[3, 3]` so we can always use the transformations to shorten it. ## Code explanation Append "--" representing two backwards turns to avoid cases where the path is too short. ``` ‹‹ ``` Replace L, R, S and - with the corresponding numbers. ``` C # get the ascii value ‹ # decrement # eventually when mod 4 gets applied it will transform into the correct numbers ``` Apply the a function repeatedly and collect unique results ``` λ ... ;İ ``` where the function is: * Use the fourth transformation ``` 2Ẏk₁⁼ # are the first two items equal to 1? [ ] # if they are: ḢḢ # remove first two items ǔ # rotate right k₁- # subtract 1 from the first two items 3Y # insert 3 into the second position ``` * Use the third transformation and rotate ``` ₌ǔh # push the list rotated to the right and then the first item of the original list ¬[ ] # if it's equal to 0: 3₌ȯẎ # push a[3:] and a[:3] ∑ # sum J # join ``` * Mirror the turns such that the first turn is not 3 ``` :hċß # if the first item is not 1: N # negate each 4% # mod 4 ``` Finally check if the second to last item in the list is `[0, 0]`. ``` Ṫ # remove last item t # last item a # is any truthy ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔⭆SXχ⊕⌕LSRιθW⌊ΦE⪪”←“tU≧*h?λêQ✳x”¶⪪κ №θ⌈κ≔⪫⪪θ⌈ι⌊ιθ¬θ ``` [Try it online!](https://tio.run/##TU/NasMwDL7vKYRPMnjgnHsag0FHM0py7SWkphV15CR1lr69K6dNqW0ZS9b3o/bcjG1ofEpf1yudGOs4Ep/Kpsct91N8pAb2YXYjFtbAltvRdY6jO@IP8RHVrq6UAdKyDAx68zGfyTvAkpi6qZMuHwWcOeveU0RlC9lQWGuXOPD6koD8JyUo8iUFK@TqwErIH/CL5KCy2HeYOOJgoGxui9Qlm9DwnOU3ED8l33ooI1dvtHrey5wR/4K0ar1Jqa6q10mf//4O "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a round trip, nothing if not. Explanation: Based on my Retina 0.8.2 answer, but using `1` instead of `F` and `0` instead of `R` because it's golfier in Charcoal. ``` ≔⭆SXχ⊕⌕LSRιθ ``` Change `L` to `10`, `S` to `100` and `R` to `1000` in the input. (These are actually reversed from my Retina answer but it doesn't matter because round trips are reversible.) ``` W⌊ΦE⪪”...”¶⪪κ №θ⌈κ ``` While the string contains one of the patterns `100010001`, `10101`, `11` or `0000`... ``` ≔⪫⪪θ⌈ι⌊ιθ ``` ... replace all matches with the `01010`, `00010001000` or the empty string respectively. ``` ¬θ ``` Test whether the string is now empty. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 (or 23) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç<°JΔ•6o₁EAÛr£ð•3B2¡ι`:}õQ ``` Port of [*AndrovT*'s top Vyxal answer](https://codegolf.stackexchange.com/a/259048/52210), which in turn is a port of [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/259059/52210), which in turn is inspired by *AndrovT*'s bottom Vyxal answer. 😅 -1 byte thanks to *@Neil*. Outputs `1`/`0` for truthy/falsey respectively. If outputting an empty string for truthy and a bunch of `0`s and/or `1`s as falsey is acceptable, the last three bytes could be removed. [Try it online](https://tio.run/##yy9OTMpM/f//cLvNoQ1e56Y8alhklv@oqdHV8fDsokOLD28AChg7GR1aeG5nglXt4a2B//8HBwXBEQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@02hzZ4nZvyqGGRWf6jpkZXx8Oziw4tPrwBKGDsZHRo4bmdCVa1h7cG/tf5H63kAwJKOmA6OAgIgoEcIAOOgFwgCoIqAasNBtEgkWAgACvzAQoFAaFSLAA). [Try it online](https://tio.run/##yy9OTMpM/f//cLvNoQ1e56Y8alhklv@oqdHV8fDsokOLD28AChg7GR1aeG5ngtX//8FBQXAEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@02hzZ4nZvyqGGRWf6jpkZXx8Oziw4tPrwBKGDsZHRo4bmdCVb/a3X@Ryv5gICSDpgODgKCYCAHyIAjIBeIgqBKwGqDQTRIJBgIwMp8gEJBQKgUCwA) with the last three bytes removed. **Explanation:** ``` Ç # Convert the (implicit) input-string to a list of codepoint integers < # Decrease each by 1 ° # Take 10 to the power each J # Join them together Δ :} # Keep doing the following replacements as long as it's possible: •6o₁EAÛr£ð• # Push compressed integer 110798340583714652624 3B # Convert it to base-3: 1000100012010102101012000100010002000022112 2¡ # Split it on 2s: [100010001,"01010",10101,"00010001000","0000","",11,""] ι # Uninterleave it into 2 parts: [[100010001,10101,"0000",11],["01010","00010001000","",""]] ` # Pop and push both lists separately to the stack } # After the changes loop: õQ # Check if what remains is an empty string # (after which the result 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 `•6o₁EAÛr£ð•` is `110798340583714652624`. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~381~~ ~~309~~ ~~286~~ ~~284~~ ~~282~~ ~~266~~ ~~264~~ ~~259~~ ~~253~~ 247 bytes (381 -> 247) Saved 134 bytes thanks to the comment of [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) --- Golfed version. [Try it online!](https://tio.run/##fVHbbuMgFHz3VyBLlTgp1RonjpNYSPsBfbL7tpcIY9yiEmwZXKWK8u0p1E2yu4oWIZhznYHTCcff5OnUvz4j3fEG2fdd3WklinY0wqnOoJK1uAIysu94D4O0L7yX2LohNeMON1KkNbcS78kc8AaALMgCHmjBWc3ku8R0CUXbDUiwqqgZfh06g0ecZussTZKVb4vTPM/SdJ0D3J@jNFvMV9kyROkqS2iSUwCYXcJ0uc7XvjgQLAB@HyhJyPx42HUNfnAdt0IpLLwWuKfHWf0tLaRpipJxrTGfccbqWQ3Bd3LSuq3wD7DsECEUP4YVkzOsSr@qyfb4sifPdJbX9HNpFWAZR8cikvteCiebrf@5UTvLfvgEN4yS/OduubY3QPSriMJfKkY3Wppn94Kv@sFnKdOPbutnw67@g/IqEJro/SgvORDc3Fo5OPwVZf@qxQqI7QdlXIvjJ98ThZ7orvGClJbNZqJEDN1Zgs7VwWwI4sKNXH8aMUGKXJjJLZoJwqeq9iZlH8T@RfnTxOSPvr42zPQD) ``` pkg load symbolic;function R=f(S),u=@(x)reshape(str2num(dec2base(x,3)(:)),4,4)-1;a=b=eye(16);for c=S;b=(kron(u(25952008),u(27752297))+kron(u(21543856),u(18501071)))*kron(u(21169798),eye(4))^{1,0,3}{mod(-toascii(c),4)+1}*b/2;end;R=all(a*a==b*b);end ``` Ungolfed version, modified from [@Anders Kaseorg's answer](https://codegolf.stackexchange.com/a/259038/110802). [Try it online!](https://tio.run/##fVLbjpswEH3nK0aRVjJdogayLLkof9CnpG9tFxljNlYIINtUWWXz7ekMFpCsoiID4/HxOeMzroXlf@X12hzeoax5DubjmNWlEp5XtJWwqq7gyC1soGUn3wPIuJHzVMtGYy6XIqIEOwUw99e47LBamj1vJDNWR1V7ZOMmtvL9AF5w@DCFcO3JKu@FbiSRoC2JSeylOKSqalrLum@KnFSHwcWDrivWsihextFstkBinCRJHEXLxPfheQCE8ct8Eb92gHARz8JZEvpdvfaGJgxfl8mSaOSHZF2NHYYjJsM3gm8OOyzfIxFa1BoEQodSMQeg8hPmjnXOprbmRijFhN9Z8EwWEIT4zwYFbAAGB0Vv88sZt14wzuA7RIQku2pNUoNFvCxZ98IG68Rzf37e56YZVXdntJXGpgK7QjaekW3yg55J0Ie7LT47N8d4GC7jvtsR3m/dUbideBd0Q54aKazMU1cpKf0ix3Urg//8C16aB4H3BynJXoU84aqU1bvds/EcdCcG1xEyrpzVZX3r1@Mr1TXaGKkt65Eb@HoEprBtptGqsgWb/EQJIAl4yrFIVcp85WpAlSfsYr@dpnkAXNiWl91kEoAKxnqDx0oudpeweKjaUMl3qr@rL9yu9dfrPw) ``` pkg load symbolic function mat = u(x) base3_repr = dec2base(x, 3); mat = reshape(str2num(base3_repr(:)), 4, 4) - 1; endfunction function result = check_input(input_str) s = kron(u(25952008), u(27752297)) + kron(u(21543856), u(18501071)); t = kron(u(21169798), eye(4, 4)); a = b = 2 * kron(eye(4, 4), eye(4, 4)); for c = input_str idx = mod(-toascii(c), 4) + 1; b = {s * t, s, s * t^3}{idx} * b / 2; endfor result = all(all(a == b)) || all(all(a == -b)); endfunction test_cases = { "LLLLL", "LLLLSRRRRS", "SRRSRRSRRSRR", "", "R", "LLLLLL", "SLLLLR" }; expected_results = [ true, true, true, true, false, false, false ]; for i = 1:length(test_cases) input_str = test_cases{i}; result = check_input(input_str); assert(result == expected_results(i), sprintf("Test case %d failed: input = %s, expected = %d, actual = %d", i, input_str, expected_results(i), result)); fprintf("Test case %d passed: input = %s\n", i, input_str); end ``` ]
[Question] [ *2fuck* is a simple 2D variation on brainfuck. Like traditional brainfuck, there is an 1D memory tape that extends 30000 bytes to the right from its beginning, consisting of values between 0 and 255. Arithmetic should wrap around, adding 1 to 255 sets the cell to 0, and moving right from memory cell 29999 should move the pointer back to 0. The converse should happen when decrementing or moving left. The input is an 1D unidirectional string/stream. It has the following commands: * `<` change the direction of the instruction pointer to left. * `>` change the direction of the instruction pointer to right. * `^` change the direction of the instruction pointer to up. * `v` change the direction of the instruction pointer to down. * `[` decrement the data pointer. * `]` increment the data pointer. * `-` decrement the value of the tape under the data pointer. * `+` increment the value of the tape under the data pointer. * `?` if the value under the data pointer is *not* 0, rotate the instruction pointer counterclockwise 90 degrees. * `.` Output the value of the tape under the data pointer as a character. * `,` Read a character from standard input and copy it to the position in the tape under the data pointer. If EOF is reaches this should NOOP. * Any other character should be ignored. The instruction pointer starts in the top left corner, moving right, execution terminates if it ever goes out of bounds in any direction, aka when it would be impossible to reach any more instructions. The program can be passed to the interpreter as a two dimensional array or a simple string featuring line breaks. The input might be passed as an additional parameter or concatenated to the program with a separator like a null byte. However, do not assume that all lines in the program are the same length. ## Test cases ### "Hello World" ``` v >]++]+++]+++]+[[[[-v v >[v v >]++++>?]+]+]-]]+>?[ -v >++++++++>?]].]- --.+++++++ .. + ++. ]].[-.[.+++.------.--------.]]+.]++. ^ < ^ < ^ < ``` ### Cat Copies the input to the output ``` v >-v v >.>?, v >,>? ^ < ^ < ``` ## Print the ASCII code page *Thanks [Matteo\_C](https://codegolf.stackexchange.com/a/249379/91213)* ``` v >-[v v >->?]] +[v v >-[++++]v v >-[[. +]]v v >-v v >-]]++++>?[>?++++ +++ +++.>?[ v >]->?] -]+ ++ +++>? ^ < ^ < ^ < ^ < ^ < ^ < ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~317~~ ~~268~~ 250 bytes ``` X,Y=1;E;Z['zz'];P;*Q=Z;main(M,s)char**s;{for(;Q=(Q-Z+'u0')%'u0'+Z,X+0u<Y*(E=strlen(s[Y]),M=M<E?E:M);P%2?Y-=2-P%4:(X+=1-P%4))X<E?write(E=s[Y][X]-45,Q,1),P=E-15?E-17?E-49?E-73?P+(E==18&&*Q%256):3:1:0:2,E-46?E-48?E?E+2?read(~E,Q,1):++*Q:--*Q:++Q:--Q:0;} ``` [Try it online!](https://tio.run/##fU5ba4MwFP4rvliNJwnqelti6pOPgr6pIYXiuq2wdaBtBx3bX3cnRUbZyg7Jl0O@yzkte2rbYahorSKZyUZ757NnZCGDUjXydbPb@zntSfu86YKglx@Pb50vS@WXrAHvGHrEtQgNrSA8JnXgZ6o/dC/bvd/r2hCaqzzJ0kzkRBZunNZMxaxwp8KvQEW2I6RCwXu3O2ytF026Mmw6oyWNCC1UxqJZirBAmN4jLO7SAlCqouVkEpRuPJsTcSciEYqYomZuhcsUh0KcdtvNg/@VXcIEQFAKxhAAbFOKUH4Ow3ByftXKAOAZr8Zip7@qa4O@5q0dYJUaNBtmDLbawYQVjIWU4YY5jPHxx@HcAQeAO8hoxrUlOLvU@GCDURyz@fAzan17n2T4Z9n1Lf5WUPIN "C (gcc) – Try It Online") 60 bytes saved(45 direct + some indirect) by c-- Segfault when going down outside of range, correct output Assume only stdin and stdout. (`/` writes to stderr, but it's fine to ignore them) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 113 bytes ``` ₌L↵r⅛⅛k2T0ẋ⅛k≈N→0{:k□i←+:¾hÞẏ$c¬ßQ→¾h←Þi:¨□›[¨□N$_|`?.,+-][`$v=÷N+&+N+^¼¥k2T%:£~i„+„[¼ḣ⅛:[C$]_]₈%:‟Ȧ⟑;⅛^$[:C₴]∧[‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwi4oKMTOKGtXLihZvihZtrMlQw4bqL4oWba+KJiE7ihpIwezpr4pahaeKGkCs6wr5ow57huo8kY8Ksw59R4oaSwr5o4oaQw55pOsKo4pah4oC6W8Ko4pahTiRffGA/LiwrLV1bYCR2PcO3TismK04rXsK8wqVrMlQlOsKjfmnigJ4r4oCeW8K84bij4oWbOltDJF1fXeKCiCU64oCfyKbin5E74oWbXiRbOkPigrRd4oinW+KAuSIsIiIsIlwiKysrKysrdlsuKysrPFxcbiAgICAgID8tXSsrK15cIlxuXCJhYmNkXFwwXCIiXQ==) It takes the program as a string and the input as a string. [Here](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwi4oKMTOKGtXLihZvihZszMFQw4bqL4oWba+KJiE7ihpIwezpr4pahaeKGkCs6wr5ow57huo8kY8Ksw59R4oaSwr5o4oaQw55pOsKo4pah4oC6W8Ko4pahTiRffGA/LiwrLV1bYCR2PcO3TismK04rXsK8wqUzMFQlOsKjfmnigJ4r4oCeW8K84bij4oWbOltDJF1fXeKCiCU64oCfyKbin5E74oWbXiRbOkPigrRd4oinW+KAuSIsIiIsIlwiKysrKysrdlsuKysrPFxcbiAgICAgID8tXSsrK15cIlxuXCJhYmNkXFwwXCIiXQ==) is a version with 90 cells. ``` ₌L↵ # parallel apply length and split on newline r # pad with spaces to given length ⅛ # push to global array ⅛ # push input to global array k2T0ẋ⅛ # push a list of 30000 zeros to global array k≈N→ # save [0, -1] to a variable with empty name 0 # push 0 # Together this sets up the global array as [code, input, tape], # the position in a variable and the direction on stack. { # start a while loop : # duplicate k□i # index into [[0,1],[1,0],[0,-1],[-1,0]] ← # load variable + # add # Stack: direction position :→ # duplicate and store variable ¾h # push the global array and get the first item, this pushes code Þẏ # multidimensional indices $c # check if it contains current position ¬ßQ # if not stop execution # Stack: direction ¾h← # push code and position Þi # index into, this gets the current instruction :¨□›[ # if it is an arrow: ¨□N$_ # convert to integer, negate and remove the previos direction from the stack | # else: `?.,+-][`$v=÷ # for each of the characters in the string push 1 if it's equal to current instruction and 0 otherwise # Stack: direction ? . , + - ] [ N # negate + # sum the top two elements &+ # add top of stack to the register (the register represents the data pointer) N+ # negate and add ^ # reverse the stack ¼ # pop from global array ¥ # push register # Stack: value_delta , . ? direction tape ptr 30T%:£ # modulo 30000 and store to the register ~i # index into without popping # Stack: value_delta , . ? direction tape ptr value „+ # rotate stack left and add „ # rotate stack left [ # if the instruction was ",": ¼ḣ⅛ # pop from global array, extract head, push to global array # this gets the next character from input :[C$]_ # if non-empty conver to number and replace the current value ] # end if # Stack: . ? direction tape ptr value ₈% # modulo 256 :‟ # duplicate and rotate stack right Ȧ # tape[ptr] = value ⟑;⅛ # push tape to global array ^$ # reverse stack and swap the top two items # Stack: direction ? value . [:C₴] # if instruction was "." print value ∧[‹ # if value != 0 and the instruction was "?" decrement direction ``` [Answer] # JavaScript (ES6), 224 bytes *-16 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* *+8 to deal with unpadded input :-(* Expects `(code)(input)`, where `code` is an array of strings and `input` is an array of bytes. Returns another array of bytes. ``` c=>i=>{for(o=[],T=[x=y=d=p=j=0];c[v=T[p%=3e4]&=255,y]+0&&(c+0)[x];d&=3,x-=~-d%2,y+=~-~-d%2)(q='?[]-+.,v>^<'.indexOf(c[y][x]))>6?d=q:eval("d+=!!v;p+=29999;p++;T[p]--;T[p]++;o.push(v);T[i[j]*0+p]=i[j++]".split`;`[q]);return o} ``` [Try it online!](https://tio.run/##jVFRb5swEH7nV7hITewZn6J0nbQRm2nS9rqH9M01agSmJSJAgKBEVfvXs4OiLluyLCcsH3f3ne@@b7loF3VUpWUj8iK2@0TuI6lSqZ6ToqKF1Ma7k3ordzKWpVzKifEj3co7XV7LG/vRjOT09tbbGT4ZjWjEJ0xvjR@P5I23FfJVxNdTb8fR6V1G13IcaCM4eK0KZ2NI89hufyY00juDSMbUpyCW6y@2XWTUjbm8umr9ksvpZzR0uI8vGyH6C/8KKDf1E20ZBlK9NB8mvDQSPc6NC3WZpc2D/6DXhvmVbTZVToqXfWXXm7SydJzUYwaVXcQ/0szOd3lEJwyaYt5Uaf5I2Rueuvf5V7T73GWApHxfRE@0JlKRZ4eQzDZkRSSpfxe7zMdEVOR1kVnIikf6bZMktoKkKlY0oStGNQAcBt15sbIkzctN4zJk4WAIbPbC9i35yxRuj99wNJponaOqQ4A@zHdwzlVgEGyEMehqgh0UHwxTBowgQsAQIQCEE86BYEYL0F0CRG/DhQ62AuwNzvtT4el5Zs6ZYcNT@fBkl06aYTH1RoECFXgEd/FU4LzDhn7hBZhD0GkUwgY6leiYIlyfZR/LOwrNeYn6Oo0sm/8WHuFOAVQnbK@lVkEv4XCgUxuXNd3wRJguSPpCh1zC@qUyXqbrP547Vxj@UXSM6SKzXw "JavaScript (Node.js) – Try It Online") ## Commented ### Main code ``` c => // c[] = code, as a list of strings i => { // i[] = input array for( // main loop: o = [], // o[] = output array T = [ // T[] = tape array x = y = // (x, y) = position of the program pointer d = // d = direction // (0:right, 1:up, 2:left, 3:down) p = // p = tape pointer j = 0 // j = input pointer ] // ; // before each iteration: c[v = T[p %= 3e4] // force the tape pointer in [0 .. 29999] &= 255, // coerce the current tape cell to a byte y // and save it in v ] + 0 && (c + 0)[x] // stop if we're out of bounds ; // after each iteration: d &= 3, // force d in [0 .. 3] x -= ~-d % 2, // x <- x + dx y += ~-~-d % 2 // y <- y + dy ) // at each iteration: ( q = // let q be the index '?[]-+.,v>^<' // in this lookup string .indexOf(c[y][x]) // of the current instruction ) > 6 ? // if this is a direction instruction: d = q // update d accordingly : // else: eval( // evaluate some specific code "..." // (detailed below) .split`;`[q] // for this instruction, or just do ); // eval(undefined) if unrecognized return o // end of loop: return the output string } // ``` ### Instructions ``` d += !!v // '?': conditional 90° turn p += 29999 // '[': decrement the tape pointer p++ // ']': increment the tape pointer T[p]-- // '-': decrement the value of the tape T[p]++ // '+': increment the value of the tape o.push(v) // '.': output the value of the tape T[i[j] * 0 + p] = i[j++] // ',': load a new value from the input ``` [Answer] # [Python](https://www.python.org), ~~264~~ 260 bytes *-4 bytes thanks to @gsitcia by replacing `r,x,y,p=[0]*4` with `r=x=y=p=0`* ``` def g(i,t,L=30000): d,c=[0]*L,-1;r=x=y=p=0 while x*y>=0: if(s:="v<^>[]-+?.,".find(i[y][x]))==9:print(chr(d[p])) d[p]=s>9and-~c<len(t)and ord(t[c:=c+1])or(d[p]+(s==7)-(s==6))%256;r=[r-(s==8and 0<d[p]),s][0<=s<4]%4;x+=r-2&-r;y+=7%~r+1;p=(p+(s==5)-(s==4))%L ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZNLbsIwEIbVqqucwrJEZePYCi1vMuEC3MAYqUp4REIhSlxKNlykGzbtoXqaTkjooiBKfyXyxDPz-Vc0fv9MC7vaJIfDx6tdyP7X3UM0X5Ali13rTuDZQ_GhQyI3BO2Z5sSVrVEGOyggBc8hb6t4PSe7ZhGAh2UkXrB8CHTrzwJtpBgrl6pFnEQs1oXRO8M5wGCYZnFiWbjKWKRT3MPGMoA8GLwkkdyH_nqeMMvxg2yyiFkdDiEULcM3VYtgOUCPy3Lpct546nTRlc6OG_2yzfOPaDc32vMh99um0R7tBGTy6VFmo0JAr7HPRGuUAkuPuE6FayNuUv-Me2XnuSUwdSilW_JLgRECn_rVKHlWcybnWkmg_wZcIpVOhAjGBn0YaQyGmtxg5kQKRC1EGGUkkVLVO0QpIogQimBGS6XLhJJH1QsGeKRCD8r5Yc4uH-Xf7OlKbvYPzgXSJWs38XAIVJ6uY8voNKHcqcZ4ycohcSnlvBqb0136Bg) Since the utilities in Python for taking in single characters from standard input are bad, this program instead takes in the input as a string (and the instructions as a list of strings or a 2D array of characters). It terminates with an error if the pointer goes off the right or bottom edge of the instructions. [Answer] # JavaScript ## ~~422...396~~ ~~425...~~372 bytes ``` f=q=>i=>{k=q.split` `;x=[a=b=p=n=t=d=0,1,0,-1,0];k.every(o=>t=Math.max(t,o.length));m=Array(z=3e4).fill(0);for(u="";a<t&b<k.length&a>=0&b>=0;m[p%=z]&=255,b-=x[d&=3],a+=x[1+d])(c=k[b][a])=="["?p++:c=="]"?p+=z-1:c=="+"?m[p]++:c=="-"?m[p]--:c=="."?u+=String.fromCharCode(m[p]):c==","&n<i.length?m[p]=i.codePointAt(n++):c=="?"&&m[p]?d++:d=(e=">^<v".indexOf(c))+1?e:d;return u} ``` Although JS is not the best language for golfing, it is fun for not being something too obscure and is one where many people would actually try to understand what is going on. In fact, is the most used programming language in the world, so it should not be missed. If you really want to see all of that running, just click the "Show code snippet" link below and then hit the "Run snippet button" button. In the snippet code (see below), for legibility, I added spaces and new lines. For golfing purposes, those should not be counted. All but one of the spaces and all but one of the line breaks are unnecessary. So I present the code with spaces and line breaks and remove them before actually running. Also, I added a lot of JS, HTML and CSS for easy testing with different programs and different inputs. Feel free to reuse them if you want to. ``` // Here is the code. For legibility, I added spaces and new lines. // For golfing purposes, those should not be counted. // All but one of the spaces are unnecessary. /// Starts here. w = q => i => { k = q.split` `; x = [a = b = p = n = t = d = 0, 1, 0, -1, 0]; k.every(o => t = Math.max(t, o.length)); m = Array(z = 3e4).fill(0); for ( u = ""; a < t & b < k.length & a >= 0 & b >= 0; m[p %= z] &= 255, b -= x[d &= 3], a += x[1 + d] ) (c = k[b][a]) == "[" ? p++ : c == "]" ? p += z - 1 : c == "+" ? m[p]++ : c == "-" ? m[p]-- : c == "." ? u += String.fromCharCode(m[p]) : c == "," & n < i.length ? m[p] = i.codePointAt(n++) : c == "?" && m[p] ? d++ : d = (e = ">^<v".indexOf(c)) + 1 ? e : d; return u } /// Ends here. // How many characters? Take out the spaces and new lines and count them. // We prepend the "f=" because it would be unfair to not count them. // We call it f instead of w to ensure that f is the variant without // spaces and line breaks. The only significant space are the "return u" // and the `\n` which I special case for them. const code = ("f=" + w.toString()) .replace(/ |\n/gi, "") .replace("returnu", "return u") .replace("``", "`\n`"); const howMany = code.length; eval(code); // Make f come to existence. document.querySelector("#howMany").value = "" + howMany; document.querySelector("#golfed").value = code; // The Let's run button. document.querySelector("#run").onclick = () => { const program = document.querySelector("#program").value; const input = document.querySelector("#input").value; const output = f(program)(input); document.querySelector("#output").value = output; } // Convenience for preloading Hello World, cat and ascii table example programs. const loader = t => () => document.querySelector("#program").value = t; const helloWorld = [ "v >]++]+++]+++]+[[[[-v", "v >[v", "v >]++++>?]+]+]-]]+>?[ -v", ">++++++++>?]].]- --.+++++++ .. + ++. ]].[-.[.+++.------.--------.]]+.]++.", " ^ <", " ^ <", " ^ <" ].join("\n"); document.querySelector("#helloWorld").onclick = loader(helloWorld); const cat = [ "v >-v", "v >.>?, v", ">,>? ", " ^ <", " ^ <" ].join("\n"); document.querySelector("#cat").onclick = loader(cat); asciiTable = [ "v >-[v", "v >->?]] +[v", "v >-[++++]v", "v >-[[. +]]v", "v >-v", "v >-]]++++>?[>?++++ +++ +++.>?[ v", ">]->?] -]+ ++ +++>?", " ^ <", " ^ <", " ^ <", " ^ <", " ^ <", " ^ <" ].join("\n"); document.querySelector("#asciiTable").onclick = loader(asciiTable); ``` ``` /* I used the StackOverflow snippet for making testing easier, and I also added a few CSS and HTML for that. Feel free to reuse it for other answers. */ all { width: 100%; padding-left: 10px; padding-right: 10px; } div, input:not(#howMany), textarea { width: 90%; } textarea { height: 200px; } .warning { color: red; } button { width: 50%; } ``` ``` <!-- I used the StackOverflow snippet for making testing easier, and I also added a few CSS and HTML for that. Feel free to reuse it for other answers. --> <div class="all"> <h2>How many characters?</h2> <input type="text" readonly="true" id="howMany" /> <h2>How is it golfed</h2> <input type="text" readonly="true" id="golfed" /> <h2>Type the program here</h2> <textarea id="program"></textarea> <button id="helloWorld">Load a Hello World program above</button> <br> <button id="cat">Load the cat program above</button> <br> <button id="asciiTable">Load the ASCII table dumper program above</button> <h2>Type the input here</h2> <input type="text" id="input" value="Some cool input here!"/> <h2>And finally...</h2> <button id="run">Let's run!</button> <div>This is the output</div> <textarea type="text" readonly="true" id="output" /></textarea> </div> ``` ### Contributions from comments: > > `q.split("\n");` can be `q.split`\n`;` for -2. –  > Kevin Cruijssen > > > > > I think what @KevinCruijssen meant was `q.split`literal newline`;` –  > Jacob > > > [Answer] # [Pyth](https://github.com/isaacg1/pyth), 191 bytes ``` K*30000]0JE=.tQd=G,ZZ=H,1ZW.A+-VlMhBQGhMG=Y@@QhGeG=T@KZ [&qY\v=H,01&qY\^=H,0_1&qY\<=H,_1 0&qY\>=H,1 0&&TqY\?=H,eH_hH &qY\[=tZ&qY\]=hZ&qY\-XZK_1&qY\+XZK1&qY\.pC@KZ&qY\,&J,XKZChJ=tJ=+VGH=%R255K ``` [Try it online!](https://tio.run/##bY5RS8MwFIXf/RWhYB@8zaVV9rZ01SEpDXuojLklpn1xEEGkQi346@tNLLK5HhLul9yTc9N9924c1c1dSrJp9Siwr1@FTLQWZZLpZ7wHvnvfuIdauo0Uh6KonTxKsS2UZib@PLwMZEwzT42nNuCSsM1Y6jn3SYTxlg4rOhzL1pXMt4zota9WuFD5XqvfACAKgN2aRnlK4irZK712legrATtZiuun28VCjaOJBvZPuQWgNW1D4kOUXPpOn5hzh48AyFeWAiy3ltCwkJLDJGpatJxxjtMNQ2TAAJBRx3A0voE8aCoEFIaUjpT1N66Z/9Xy1HOpZt7RzCbZq@jto/vqox8 "Pyth – Try It Online") Could definitely be golfed some more. Takes the program as an array of strings first, and any input as the second input. It's very slow since the whole tape is run through mod 255 on every instruction, but here's a [TIO](https://tio.run/##bY5RS8MwFIXf/RWhYB@8zaVV9rZ01SEpDXuojLklpn1xEEGkQi346@tNLLK5HhLul9yTc9N9924c1c1datPqUWBfvwqZaC3KJNPPeA98975xD7V0GykORVE7eZRiWyjNTPx5eBnImGaeGk9twCVhm7HUc@6TCOMtHVZ0OJatK5lvGdFrX61wofK9Vr8BQBQAuzWN8pTEVbJXeu0q0VcCdrIU10@3i4UaRxMN7J9yC0Br2obEhyi59J0@MecOHwGQrywFWG4toWEhJYdJ1LRoOeMcpxuGyIABIKOO4Wh8A3nQVAgoDCkdKetvXDP/q@Wp51LNvKOZTbJX0dtH99VHPw) link to a version with a tape of length 30 which doesn't time out. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 126 bytes ``` WS⊞υιUO⌈EυLιLυ P⪫υ¶≔⪪⮌S¹θ≔E׳⁰φ⁰η≔⁰ζ≔⁰εWKK«≔﹪§ηζ²⁵⁶δ≡ι<≔⁴ε>≔⁰ε^≔²εv≔⁶ε[≦⊖ζ]≦⊕ζ-§≔ηζ⊖δ+§≔ηζ⊕δ?≧⁺∧δ²ε.≔⁺ω℅δω,F¬¬θ§≔ηζ℅⊟θP⁰M✳ε»⎚ω ``` [Try it online!](https://tio.run/##lZJdb5swFIavw6844sooEGXd2ou2Ioram0zLitreZSBROAnWHDsFQ6pN/e3smLASmrTdLDkc@33e8xE5yeI8UbGo623GBQKbyU2p73TO5Yo5DgRlkbHSBe5cWDcPQtHtPH7i63JN341RvqFc6Yxxx3FeDiWFNtjkmZdC84CyafZVcWkM9g9pOyRNi4KvJLvbCK7ZLVaYF/iqvAufaD92sKl5z9dYsM9jF5YkjmlnHUC3v3onpFM7WoD408z02xr8TafSUig21TOZ4hPLjNmFk9Mz@k3JOCi2XCcZ0HTGlcQFgn1pn0Pr/7LL3wp@J4x7QtQJJz2h6oSznrAggWZttWtMclyj1JjuxmupsEfN5HHKeymyP6cLe1lZ6nT88A1@L3@Pn@x3cctXmWaBKAsXppJA@jud3mijbmaDsa0LV/QI40RjbvK6sO1gl@ClyoF9V7rZj/TMjnZ3k6dcxoIFatNAlCLFZUzPj7rrHuHYCM/WYK4qZNc8x0RzJRkaw7N1JTDOGYU7mBqp6wqa5XuLyqqawJ@EIQzb4xuL8CGt8F1oxy1GMAw/BA98xwy@F4amrD9Z@BMTQLtHdAOV5YemefBCcwkNaB0kid6vfGn9T5/Rh4bonzJHPejQEzWxVXuV@AM "Charcoal – Try It Online") Link is to verbose version of code. Takes the program as a list of newline-terminated strings, then the input follows after a blank line (if there is no input you need a second blank line). Explanation: ``` WS⊞υι ``` Input the program. ``` UO⌈EυLιLυ ``` Fill a rectangle of the canvas with spaces. ``` P⪫υ¶ ``` Overprint the program without moving the cursor. ``` ≔⪪⮌S¹θ ``` Split the input into characters and reverse it. ``` ≔E׳⁰φ⁰η ``` Create an array of 30,000 cells. ``` ≔⁰ζ ``` Initialise the data pointer. ``` ≔⁰ε ``` Initialise the direction pointer. ``` WKK« ``` Repeat while the current instruction is not off limits. ``` ≔﹪§ηζ²⁵⁶δ ``` Get the value of the cell at the data pointer, modulo 256. ``` ≡ι ``` Switch over the current instruction. ``` <≔⁴ε ``` If it's a `<` then set the direction pointer to left. ``` >≔⁰ε ``` If it's a `>` then set the direction pointer to right. ``` ^≔²ε ``` If it's a `^` then set the direction pointer to up. ``` v≔⁶ε ``` If it's a `v` then set the direction pointer to down. ``` [≦⊖ζ ``` If it's a `[` then decrement the data pointer. ``` ]≦⊕ζ ``` If it's a `]` then increment the data pointer. ``` -§≔ηζ⊖δ ``` If it's a `-` then decrement the cell at the data pointer. ``` +§≔ηζ⊕δ ``` If it's a `+` then increment the cell at the data pointer. ``` ?≧⁺∧δ²ε ``` If it's a `+` and the current cell is nonzero then rotate the direction pointer. ``` .≔⁺ω℅δω ``` If it's a `.` then append the character of the current cell to the output string. ``` ,F¬¬θ§≔ηζ℅⊟θ ``` If it's a `,` and the input is not empty then replace the current cell with the ordinal of the next input character. ``` P⁰ ``` Otherwise do nothing. (The newer version of Charcoal on ATO supports `switch_delimited` which avoids this but itself requires two extra bytes anyway.) ``` M✳ε ``` Move one step in the current direction. ``` »⎚ω ``` Clear the canvas and print the final output string. [Answer] # Java 10, ~~343~~ ~~339~~ ~~336~~ 317 bytes ``` m->i->{int l=0,M=30000,x=0,y=0,p=0,d=0,c,I=0,q;for(var t=new byte[M];;d=(q=">^<v?".indexOf(c))<0?d:q>3?t[p]!=0?-~d%3:d:q,p+=c==91?1:c==93?M-1:0,t[p%=M]-=c>42&c<46?c-44:0,System.out.print(c==46?(char)t[p]:""),y+=d%2-d%3%2*2,x+=3%-~d-d-~d%2)if((c=x>=(q=m[y].length)&(l=q>l?q:l)>x?0:m[y][x])==44&I<i.length)t[p]=i[I++];} ``` -3 bytes thanks to *@ceilingcat*. Input 2fuck program as a 2D array of bytes, and optional input-characters as a second byte-array. Stops the execution of the input-programs with `ArrayIndexOutOfBoundsException`s. [Try it online.](https://tio.run/##nVVRb5swEH7Pr7ghpcIDW2kSTRoJRtu0SXmI@tC9MWei4DR0BAiYNFHU/fXuzGCZGtJ2O8Xg2N/dffg@23fBNqB30Y/HMAnKEuZBnB56AKUKVBzCHc6ySsUJW1ZpqOIsZV@azvRmr6QvfGF3oT5laVmtZdGgOIcluI9rymPKD3GqIHEH9twdDdDsHfb32HJsEbbQnuFzM1lmhbkNClBuKu@hjjQXk0nkmhvX4Ivp1jNYnEZyd7U0Q0KmAy9yNnzkKT8Xb9yBR39G/ZGDY3ZuuaHrvr/0Lh39HnlzeukMbAT23bmgbsjHw4twOn7nhXQ8xpnrfankmmWVYnmBfE10w1kzXAUF0fEdwyD23nKj/pBilv7w7dDeWe6oj0lppDMPSbw00W/HNd@1vxcskemtWpELM3E3PPE2TkL4zhs4etLfCYI5xhezadwCdSI39meWJSYPj5MeFiavbhIsTFOfbRZHsMaamdcKad76IiAHQOvph5KlMo0tPDEuMJ7VNh@Nbr@lhtX7gzj1@dvdP4/WoS2LewIDCyoEdn04ic6txhAomKBAKWtGgDGwwLIY4IxPma8nGK2teWEHAzPMxJ7E/dNbdDOfnsOf2uJldFeSqUEmJ0vPu5aXM@7ZcLIyNvdO0i6eYa95GjYYX1dxCfgL6swQp3mlAPcPqJWEMFCQF9ltEay7@CHBzpJyqusDVne9r7O17BAH9XUZRadLUd3cxOWq08vHuotuNyV36g28bPwVMuZalLXyfO7Vgmsa00o9KYfQSwBUaAjUbi9JaPE8x3@Q4P9o8gyV17stnnF5Kd7iuAEeesc7pD6jar39PqNaKZLDUYnNEAr59f42NP9rsZdNuKcHd5KaxnBZhT9aNwfaPdABbamdBRizOhkGsZq056FXlULEMZ8q9oclC/I82beJWBKnsjQJWwd583mOcyvVR7zrSsJU9qEogr3ZXrWOgxchISwIQ5kr8zcD1uJNQiYPdSbc8OHKrH1n9f1Yqavlx6xKo/LzTrviFQ2SHBrWsiiOrK9VlucygvtYrQBnskJ/rGxDd32oVoPx3WCFzGWgzMvBgFh6sCnlw@Mv) **Explanation:** ``` m->i->{ // Method with byte-matrix & byte-array parameters and no return int l=0, // Longest line integer, starting at 0 M=30000, // Memory size, set to 30,000 x=0,y=0, // x,y-coordinates, starting at 0,0 p=0, // Data pointer integer, starting at 0 d=0, // Direction integer, starting at 0 (right) c, // Character value, uninitialized I=0, // Index integer for potential inputs, starting at 0 q; // Temp integer, uninitialized for(var t=new byte[M] // Tape byte-array, starting at 30k amount of 0s ; // Start an infinite loop: ; // After every iteration: d= // Update the direction to: (q=">^<v?".indexOf(c)) // Set `q` to the index of the character in ">^<v?", // or -1 if the character is not in this String <0? // If this `q` is -1, thus not one of those characters: d // Keep the direction the same :q>3? // Else-if `q` is 4 (thus '?'): t[p]!=0? // If the current tape-value at the pointer is 0: -~d%3 // Set the direction to (d+1)%3 (90 degrees counterclockwise) : // Else ('?', but the tape-value is 0): d // Keep the direction the same : // Else (`q` is one of 0,1,2,3 / >,^,<,v): q, // Set the direction accordingly to this `q` p+= // Increase the data-pointer by: c==91? // If the character is '[': 1 // Increase the data pointer by 1 :c==93? // Else-if the character is ']': M-1 // Increase the data pointer by 29,999 : // Else (a different character): 0, // Keep the data pointer the same by increasing with 0 t[p%=M // Modulo the data pointer by 30,000 ]-= // Decrease the tape-value at the data pointer by: c>42&c<46?// If the character is 43/44/45 (+/,/-): c-44 // Decrease it by c-44 (+→-1; ,→0; -→1) : // Else (a different character): 0, // Keep the tape-value the same by decreasing with 0 System.out.print( // Print to STDOUT: c==46? // If the character is '.': (char) // Convert the following integer to a character: t[p] // The tape-value at the current data pointer : // Else (a different character) ""), // Print an empty string (aka nothing) instead y+=d%2-d%3%2*2, // Update `y` based on the direction† x+=3%-~d-d+-~d%2) // Update `x` based on the direction† if((c= // Set `c` to: (q=m[y].length) // Set `q` to length of the current line <=x // Check whether `x` is out of bounds for the current line &(l= // Set `l` to: q>l? // If `q` (length of the current line) is larger than `l`: q // Set `l` to this new longest line `q` : // Else (the current line is shorter than `l`): l) // Keep `l` the same >x // Check whether this `l` is larger than `x` ? // If both these checks were truthy (so `x` is out of bounds // for the current line, but in bounds for the longest line): 0 // Set `c` to 0 : // Else: m[y][x] // If `x` is in bounds for the current line: // Set `c` to the `x,y`'th character of the input-program // If `x` is out of bounds for the full program-block: // Stop the program with an ArrayIndexOutOfBoundsException )==44 // If the current character `c` is ',' &I<i.length) // and there are input-characters left: t[p]= // Set the tape-value of the current data pointer to: i[I // The current input-character (at index `I`) ++];} // And increase index `I` by 1 afterwards with `I++` ``` † `d` is used to update the `x,y`-coordinate like this: *(I'm pretty bad at magic numbers, so both can most likely be golfed)* | `d` | `d%2` | `d%3` | `d%3%2` | `d%3%2*2` | `d%2-d%3%2*2` | `y` | | --- | --- | --- | --- | --- | --- | --- | | \$0\$ | 0 | 0 | 0 | 0 | \$0\$ | `y` | | \$1\$ | 1 | 1 | 1 | 2 | \$-1\$ | `y-1` | | \$2\$ | 0 | 2 | 0 | 0 | \$0\$ | `y` | | \$3\$ | 1 | 0 | 0 | 0 | \$1\$ | `y+1` | | `d` | `-~d` | `3%-~d` | `3%-~d-d` | `~d` | `~d%2` | `3%-~d-d-~d%2` | `x` | | --- | --- | --- | --- | --- | --- | --- | --- | | \$0\$ | 1 | 0 | 0 | -1 | -1 | \$1\$ | `x+1` | | \$1\$ | 2 | 1 | 0 | -2 | 0 | \$0\$ | `x` | | \$2\$ | 3 | 0 | -2 | -3 | -1 | \$-1\$ | `x-1` | | \$3\$ | 4 | 3 | 0 | -4 | 0 | \$0\$ | `x` | ]
[Question] [ ### The Challenge Given a multiline string, return the longest substring of leading whitespace present in every line, ignoring empty lines or lines composed only of whitespace. If input is empty or whitespace, return nullish or the empty string--up to you. Update: Per [Meta consensus](https://codegolf.meta.stackexchange.com/a/17095/53748), the input may also be treated as an array of strings. My examples below could be shortened by excluding the `.split()` calls. --- I wrote a quick script for my iPhone that comments or uncomments JavaScript code (since I can't use `ctrl`+`/`). I want the `//` placed the furthest right that it can, given that each `//` is aligned with the other lines. If a line is only whitespace (or empty), I want to skip adding a comment. To do this, I must determine the longest leading whitespace substring that exists in every line. So, given the input string ``` const x = () => y.split() .map(s => s.length ) .join() console.log(x) ``` the result of the algorithm would be 2 spaces. (Note: Line 7 has 4 leading spaces, but the browser may or may not remove them. It does not appear to remove them in the example solutions below.) If the input was only lines 3-7, the result would be 6 spaces. A simple JS solution to achieve this would be ``` const solution = text => { const lines = text.split('\n').filter(l => !!l.trim()) let result = '' while (lines.every(l => l.startsWith(result + ' '))) { result += ' ' } return result } // test const text = ` const x = () => y.split() .map(s => s.length ) .join() console.log(x)` let result = solution(text); console.log(`|${result}| ${result.length} spaces`) const lines3Through7 = text.split('\n').slice(2, 7).join('\n') result = solution(lines3Through7) console.log(`|${result}| ${result.length} spaces`) result = solution( `abc def`) console.log(`|${result}| ${result.length} spaces`) ``` I'm sure you can do better than this. Another would be ``` const solution = text => ' '.repeat( text.split('\n') .filter(l => !!l.trim()) .map(l => l.length - l.trimStart().length) .reduce((m, v) => Math.min(m, v)) ) // test const text = ` const x = () => y.split() .map(s => s.length ) .join() console.log(x)` let result = solution(text); console.log(`|${result}| ${result.length} spaces`) const lines3Through7 = text.split('\n').slice(2, 7).join('\n') result = solution(lines3Through7) console.log(`|${result}| ${result.length} spaces`) result = solution( `abc def`) console.log(`|${result}| ${result.length} spaces`) ``` --- Assume all whitespaces are space characters (i.e. not `\t`). For input that has no non-whitespace characters, it should return nullish or 0 spaces, up to you. You can use any language~~, but I'd also like *someone* to present an answer in JavaScript~~ ✅. Shortest answer wins. Include your answer, a prettified version of your answer for readability, and for esoteric languages, an explanation of how your script works. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` =⁶Pi0’⁶ẋ ``` [Try it online!](https://tio.run/##y0rNyan8/9/2UeO2gEyDRw0zgYyHu7r/P9y95XD7w537NCP//1dXV4/hUlBIzs8rLlGoULBV0NBUsLUDiigoVOoVF@RklmhognkKCnq5iQUaxTBZECjWy0nNSy/JgArAFWblZ@ZBtUHNzs9J1cvJT9eo0ARaqAO1lGxD4WYkJiVzKaSkpiEZSgufKOjr@6VWlCjkZOalAi3ILchJLUnNqVRIyknMy1YoycgsVijJzE1VSCzKL81L4cLrZxgG8gE "Jelly – Try It Online") -1 thanks to Jonathan Allan reminding me of meta consensus on being able to take a list of lines. ``` =⁶ For each character on each line, is it a space? P Take the product along each column, i0 and find the first 1-index of 0 (or 0 if not found). ’ Decrement ⁶ẋ and yield a space repeated that many times (or none if not positive). ``` `n⁶SĬS⁶ẋ` works similarly, but does not ignore all-whitespace lines if there's nothing else. If we can assume the input contains no codepoints under 32 other than newlines, this *almost* works: # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ ~~6~~ 5 bytes ``` Ṁ»\f⁶ ``` [Try it online!](https://tio.run/##tY8xDoJAEEV7TvE7IDFwAjyCvYkNwgCrwy5x1wQ6rbyQMSEkFnoSvMiKBo2VhYmTTDF/Zt7PXxFzY23f7i7dIrvtT7bvjtdD3579ubWu6y4cIFFSG9SI4PmIpoMCNIGuWBjPf05AUMaVp1/bR@mASeamGIX34UoJOb6NbMUUsMq92h8MJ6Ppz9A3I14mDlLKPqD/SIIwnFFtwELSYFBWTIa4wZJjuYYphIYRJSHeqK1Mna@ZXz3Mdw "Jelly – Try It Online") -1 because I tried replacing `»/` with `Ṁ` just in case that would work, and after further consideration, of course it would work--the lexicographically greatest line is precisely some line with the fewest leading spaces that has something else after them (under the assumption stated above). -1 thanks to Jonathan Allan reminding me of meta consensus on being able to take a list of lines. Fails to ignore all-whitespace lines if there's nothing else. A fix in fewer than 3 bytes seems unlikely (though `Ṁ»\ḟȧfɗ⁶` in 3 bytes seems worth mentioning). ``` Ỵ Split on newlines. Ṁ Take the lexicographically greatest row, »\ find the largest character in each of its prefixes, f⁶ and remove any that aren't spaces. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 10 ~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 by using the default ruling that [Submissions may use list of strings instead of multi-line strings](https://codegolf.meta.stackexchange.com/a/17095/53748). ``` n⁶T€FṂ’⁶ẋ ``` A monadic Link accepting a list of lines (lists of characters) that yields a list of characters. **[Try it online!](https://tio.run/##y0rNyan8/z/vUeO2kEdNa9we7mx61DATyHu4q/v/w91bDrc/3Lnv/391dfUYLgWF5Py84hKFCgVbBQ1NBVs7oIiCQqVecUFOZomGJpinoKCXm1igUQyTBYFivZzUvPSSDKgAXGFWfmYeVBvU7PycVL2c/HSNCk2ghQA "Jelly – Try It Online")** ### How? ``` n⁶T€FṂ’⁶ẋ - Link: list lists of characters, Lines ⁶ - space character n - not equals? (vectorises across all the characters in Lines) € - for each: T - truthy indices (1-indexed) F - flatten Ṃ - minimum (minimum of the empty list is 0) ’ - decrement -> number of "common" leading spaces, N ⁶ - space character ẋ - repeat N times (repeating -1 or 0 times gives an empty list) ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εDðKk}ßð× ``` Input as a list of character-lists. [Try it online](https://tio.run/##yy9OTMpM/f//3FaXwxu8s2sPzz@84fD0/48alikd3q/0PzpaSUFJB4yTgTgfiPOAuBiIS6DiFVDaFkprALEmkpidUqwOwhQYrgRiPahJBUCcA8SZUFMhJmDTBcMgnblAnAjVrQE1Cb@d6LgYahLI7lSoz9KhbsjAawJh12VBQysTai4uPyGLoIdwPpLbYO7Mh7pRAxryYDNjYwE) (footer is added to pretty-print the string of spaces) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU2nLpeSYXFKamIMQCz607dBC2//ntroc3uCdXXt4/uENh6f/V/IvLYEosHd51LBM6fB@Jft0JQWNw/sVigsSk1OLNZV0Dm2z/x@tpKCQnJ9XXKJQoWCroKGpYGsXk6cABJV6xQU5mSUamhCugoJebmKBRjFcHgSK9XJS89JLMmAiCLVZ@Zl5MK0gEmRFfk6qXk5@ukYF0GoFJQoNBRmRmJQM4qSkpoF4SrEA). **Explanation:** ``` ε # Map over each inner character-list of the (implicit) input-list: D # Duplicate the current character-list ðK # Remove all spaces from the copy k # Get the first 0-based index of each of these characters in the list }ß # After the map: pop and push the flattened minimum ð× # Convert it to a string with that many spaces # (after which the result is output implicitly) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes ``` G`\S O^`.+ !`^ + ``` [Try it online!](https://tio.run/##PYy7CoAgGIV3n@K0KcH/BrU2NrRGKCFlmEY61NPbvW8711VH41RKlWwbVneScpbJDnlKQO9diNhQgAsUJcPJTmGxJnJxK4BmtfDwpReBrHZDHF/jL07euHfGnm9vNVk/8E0c "Retina 0.8.2 – Try It Online") Explanation: ``` G`\S ``` Discard lines that only consist of whitespace. ``` O^`.+ ``` Sort them in reverse order, so the line with the least space sorts first. ``` !`^ + ``` Output the leading spaces. If just the count of leading spaces suffices, then for 14 bytes: ``` G`\S O^`.+ \G ``` [Try it online!](https://tio.run/##PYy7CoAgGIV3n@KMSvC/ga2ODa0RSUgZppEO9fR279vOdTXJep2z6pqaVW1HBWsUcgb64GPCBgkuIEuGk53i4mzi4lYAzXrh8UsvIjnjhzS@xl@cgvXvjD3fwRlyYeCbOAA "Retina 0.8.2 – Try It Online") Explanation: The last stage `\G` counts consecutive spaces at the start of the buffer. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ↵ƛðv≠TgI;g ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLihrXGm8OwduKJoFRnSTtnIiwicSIsIlwiICAgSm9lIFxcbiAgIEJydWhcXG4gICAgIFBpcGlzXFxuICAgICAgXCIiXQ==) A port of the jelly answer. 8 bytes with the `g` flag. ## Explained ``` ↵ƛðv≠TgI;g ↵ƛ # For each item n in the input split on newlines: ðv≠ # Is each character not a space? Tg # Smallest index where ^ is truthy. Returns an empty list if all spaces. I # Push that many spaces or two empty lists if it's all spaces. ;g # Return the smallest item of that. ``` [Answer] # [Python](https://www.python.org), 39 bytes ``` lambda l:max(l)[:-len(max(l).lstrip())] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU7LCsIwELz3K5Zc3CDNWQr1R9RD1D4i2yQ0EVrwT7wURC9-kX9jahrnsszs7M7cX3b0rdHToy73z6uv881nRbI7niVQ0ckBie-KnCqNkQhyvlcWOT8s9rftlfZYI2MM4GS08zBACcih3GYQMApnSfkg_CiA6KRFl9YznAgRjW8XgSfjxSiNkSXvnGCoEmQaHHgIjd9J6cqFWrAGdmM8-7cKJyypsfI0xfkF) Takes input as a list of lines, per [default I/O rules](https://codegolf.meta.stackexchange.com/a/17095). Uses [Unrelated String's observation](https://codegolf.stackexchange.com/a/242847) that the lexicographically greatest line will be the one with the least leading whitespace. This means the input must not contain unprintables other than newline. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ ~~11~~ ~~10~~ 9 bytes *Thanks to Jonathan Allan for bug-spotting (both versions)* ``` ←T↑o¬wTfw ``` [Try it online!](https://tio.run/##yygtzv6fYKWuBESPmhoPbfv/qG1CyKO2ifmH1pSHpJX///9fQSE5P6@4RKFCwVZBQ1PB1o5LAQgq9YoLcjJLNDTBPAUFvdzEAo1imCwIFOvlpOall2RABeAKs/Iz86DauCBm5@ek6uXkp2tUaHIBAA "Husk – Try It Online") Takes a list of lines, removes all-space lines (`fw`), transposes (`T`), keeps longest prefix of all spaces (`↑o¬w`), transposes back again (`T`), and output first element (`←`). --- # [Husk](https://github.com/barbuz/Husk), ~~7~~ ~~9~~ 8 bytes ``` ↑=' →Ofw ``` [Try it online!](https://tio.run/##yygtzv6fYKWuBESPmhoPbfv/qG2irbrCo7ZJ/mnl////V1BIzs8rLlGoULBV0NBUsLXjUgCCSr3igpzMEg1NME9BQS83sUCjGCYLAsV6Oal56SUZUAG4wqz8zDyoNi6I2fk5qXo5@ekaFZpcAA "Husk – Try It Online") Uses [Unrelated string's lexicographic sorting approach](https://codegolf.stackexchange.com/a/242847/95126): Takes a list of lines, removes all-space lines (`fw`), sorts (`O`), keeps last element (`→`), and keeps the longest prefix of spaces (`↑='` ). [Answer] # JavaScript (ES6), 43 bytes ``` s=>(s.match(/^ *(?=\S)/gm)||[""]).sort()[0] ``` [Try it online!](https://tio.run/##PU69DoIwEN55iouLdyYWdlPdHBx0YERNCBYsqS32qoHEd0fAn2@77/fq/Jlz4XUTltZdVF/KnuUaWdzyUFwxPsMCN/KYUlzd6PXKZrMTCXY@IGXJqWeQ4NX9ob3CeclzEl7ll602Ku1sgQmJ4NLgta2QVlHhLDujhHEV7tLDXvAk6bLDEpmIeoDRE6AdepFAriMY0AlujB4mpwtgeK5B/qkjWBhlq3D9En9j7bT9xqJP92@/pTc "JavaScript (Node.js) – Try It Online") Or **40 bytes** by using optional chaining, as suggested by the OP: ``` s=>s.match(/^ *(?=\S)/gm)?.sort()[0]||'' ``` (doesn't work on TIO) [Answer] # [R](https://www.r-project.org/), ~~50~~ ~~62~~ ~~60~~ 57 bytes *Edit: -2 bytes thanks to pajonk* ``` sub("^( *).*","\\1",sort(sub(" *$","",readLines()),T)[1]) ``` [Try it online!](https://tio.run/##PYzBCsIwEETv@Ypl8bAbQqAfUL/AozerUDXUSExKNkL9@lhrdW4zb2ZyrfI8E54INFuNBruuQSMpF1oA6M0cosmuv@58dELMZs@H5sgV4JKiFJigBWJotwpmvayMwRfixQHYRz@S/OhHYoOLQ7mtwb94Tz6uM/X9TsHZkAaaWKn6Bg "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~47~~ 46 bytes ``` fst.minimum.filter((>[]).snd).map(span(==' ')) ``` [Try it online!](https://tio.run/##PY47EsIwDER7n0IddoEPkBmnp6KgBApPsINAVjzIzITLY/IBXqXP7kpXL/dAVJNHhqaB3R60UUvnALmEh@8K6AgWCDmIUSrOuuOhPJD7M2xbWEsV3alGKTYhY3omG5Emu9bt8Wys8MXY5LOW7Fk7t4GNMbUCdANLgXG6pg24VsHEy0omLNMjsLAaf9sZsRS4L9fv4C@8Dchfm1qzBwqWhl6P5t1F8r3UbZfzBw "Haskell – Try It Online") Nothing special here, it's a very standard approach, just with less whitespace. A more presentable version: ``` main :: IO () main = interact (f . lines) f :: [String] -> String f = fst -- extract it from the tuple . minimum -- find the shortest leading whitespace (tuples are sorted by first element) . filter ((> []) . snd) -- remove any tuples for which 'everything else' is empty . map (span (== ' ')) -- split each line into tuples of (leading whitespace, everything else) ``` Since `minimum` is a partial function, it will raise an exception if given input that consists only of whitespace. From my perusal of the rules, I'm under the impression that this is acceptable; but I'm fairly new here so please correct me if I'm wrong. [Answer] # Excel, ~~48~~ 58 bytes Revised to return *N* spaces instead of just the value of *N*. ``` =LET(t,TRIM(A:A),REPT(" ",MIN(IF(t="","",FIND(t,A:A)))-1)) ``` Trim the leading and trailing white space from each line then find the position what's left in the original line, ignoring those lines that are empty once they're trimmed. Find the minimum of those positions minus 1. Return a space repeated that many times. [![Screenshot](https://i.stack.imgur.com/YeYIW.png)](https://i.stack.imgur.com/YeYIW.png) Screenshot shows formula returning repeated pipes instead of spaces so you can see the results. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-r`, 15 bytes ``` @SS Ks~Y#||_FIg ``` Takes input from stdin; prints a string of spaces (with a trailing newline) to stdout. Outputs nothing if the input contains only whitespace. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSbpFS7IKlpSVpuhbrHYKDFbyL6yKVa2ri3TzTIaJQyQU3MxUUkvPziksUKhRsFTQ0FWztuBSAoFKvuCAns0RDE8xTUNDLTSzQKIbJgkCxXk5qXnpJBlQArjArPzMPpI0LYnB-TqpeTn66RoUmxEYA) ### Explanation The `-r` flag reads all of stdin and stores it as a list of lines in `g`. Then: ``` @SS Ks~Y#||_FIg FIg ; Filter g on this function: || ; Strip whitespace from _ ; each line # ; and get the length of what remains Y ; Yank the result (used here just to manipulate precedence) ~ ; Get first match of this regex in (each line of) the above: s ; Preset variable: space K ; Kleene star (results in this regex: ` *`) SS ; Sort in lexicographic order (in this case, shortest first) @ ; Get the first element ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 39 bytes ``` s=>/( *)\S(.|\s+(\1|$))*$|$/.exec(s)[1] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k5fQ0FLMyZYQ68mplhbI8awRkVTU0ulRkVfL7UiNVmjWDPaMPZ/cn5ecX5Oql5OfrqGV7C/n15xSVFmXnpmWqVGmoa6gkJiTF5SUmKiuqamJhcRahUUSFNNgvokIABqIUotEACVkqQD5Bqwyv8A "JavaScript (Node.js) – Try It Online") Return `undefined` if no line # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` s=>/( *)\S(.|\s+(\1|$))*$/.exec(s)[1] ``` [Try it online!](https://tio.run/##lc6xDoIwFIXhnafoQNJ7MZbwALi5OEgCo3UotSCGtIY2RiI8ey2bTuKZvz85N/EQVg7d3W21uSjf5N7muxRIgrwCNnG7AZ5NMWISp0w9lQSLp@zspdHW9Ir1poVDVRyZdUOn264ZoQFKiOC6roWgiBitsIT8p//wdVhIVtmwQD8LN4yvn9XyaNGzFE5evzzdl2VRUpwj/wY "JavaScript (Node.js) – Try It Online") Throw if no line [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` WS⊞υι× ∨⌊ΦEυ⌕E⪪ι ¬λ⁰⊕ι⁰ ``` [Try it online!](https://tio.run/##PU1BboNADLzzCisnWyIod5QcI@WQNFL6AURW4MjrRaxp6Ou3C6WdgzUzHo/bvhnb0EhK757FAV50mOxhI2uHRHCfYo9TCUx1cc@m4Sd7F3EHuxI@Rryysp88nlnMZdkMS/rM@lz5YxA25BJynkq4BUOhTA7LuGg7Ou/U3BOZNpvqlADaoNFghiMgwfFUQMZ3Fdc2WhVA5fOD@LddECtx2lm/Gf/BV2Ddzorf7iCuktDhTEXaf8kP "Charcoal – Try It Online") Link is to verbose version of code. Takes input by default as a list of newline-terminated strings, so if you want to provide an empty string as part of the input you'll have to encode it as a JSON list instead. Explanation: ``` WS⊞υι ``` Input the string. ``` × ∨⌊ΦEυ⌕E⪪ι ¬λ⁰⊕ι⁰ ``` Split each line on spaces and find the index of the first non-space character, but filter out those lines that only have spaces, and then take the minimum number of spaces, or 0 if all lines only have spaces, and repeat a space that many times. [Answer] # [Ruby](https://www.ruby-lang.org/), 29 bytes ``` ->a{a.map{_1[/^ +/]}.sort[0]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZ7de0SqxP1chMLquMNo_XjFLT1Y2v1ivOLSqINYmshalYWKLhFOwa5u8VC-Atu5igoJOfnFZcoVCjYKmhoKtjacSkAQaVecUFOZomGJpinoAAyVqMYJgsCxXo5qXnpJRlQAbjCrPzMPKg2LojZ-Tmpejn56RoVmhBLAQ) [Answer] # [Perl 5](https://www.perl.org/), 38 bytes ``` print[sort map/^ +/g,grep/\S/,<>]->[0] ``` [Try it online!](https://tio.run/##RUy7DsIgFN37FScuhVjBxamWn3Bsa2IMQQxyCTDUr6/U@jjTeQcd3WEO0fpcb@p2ZX2imPG4BHnGVprGRB3kcJLNUY071e/Huf0vgCv5lDGhA@PoVIWCp0jB2cz4WwGivLH0TRck4bQ3@fYxfsU7WV9m1fpLTgtHhk38BQ "Perl 5 – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 23 bytes ``` t]:nzm{Jt[.-}saq<]qesIE ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@T978k1iqvKrfaqyRaT7e2OLHQJrYwtdjT9f9/BSDgUlBIzk9JhVIA "Burlesque – Try It Online") ``` t]:nz # Filter null/wspc lines m{ # Map J # Dup t[ # Trim left .- # String Difference } -- Diff pre/post trim sa # non-destructive Length q<] # If non-zero length find max qes # Else Empty Block -> Empty string IE # If Else ``` [Answer] ## [Scala](http://www.scala-lang.org/), 51 bytes ``` "\\n[\\s]*".r.findAllIn("\n"+y).map(_.length).min-1 ``` [Try it online!](https://tio.run/##rZA9SwQxEIZ7f8VLqkQxYHuwwpUHd5WFhRGJu7lcjjgJOyl28fzta/aw0BULxSkG5uudZ4ZbG@2Uno@uLdjZQHBDcdQx1jnj9QLo3B4xkXdcts52gfz9IRTH2bZOjivclb7m1AobKmgmYQw9GMOPl0L3eh@oW8e4ISkMiatR6Reb5ZOOjnw51CjQ9c0E5KpRIskfF1UQQAhxAtpEXDCggVRobs@VaqfZjZpzDEWqL1ngvJaX3bPxB8ui8E3gmAItZD8FM1OKTsfk5aAqp@b6lryzvQ@k5rHfXPifxH9iEaL2vU3v) **Explanation:** ``` "\\n[\\s]*".r // regex to find newlines and all whitespaces after .findAllIn( // iterator of all matches in the given string "\n"+y) // add a newline to the front to count first line .map(_.length).min // find the shortest match -1 // subtract one since lengths include the newlines ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), 28 bytes ``` :*&(~:[]&/^ */)|:sort|:first ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWe6y01DTqrKJj1fTjFLT0NWusivOLSmqs0jKLiksgStYVKLhFOwa5u-mV5McnxkIEF9zMUVBIzs8rLlGoULBV0NBUsLXjUgCCSr3igpzMEg1NME9BQS83sUCjGCYLAsV6Oal56SUZUAG4wqz8zDyoNi6I2fk5qXo5-ekaFZoQSwE) ## Explanation ``` :* & ( # Map lines with... ~:[] & /^ */ # Get part that matches /^ */ ) | # then :sort | :first # sort, then get the first ``` ]
[Question] [ **Description** You have a list of integers and start counting from the first term to the next and continue from that to the next and so on.. How many times have you counted? For example given [ 2, 5, 3, 8 ] you start at 2 and count to 5 -> *3 4 5* (3 times) then from 5.. *4 3* (2 times) and finally *4 5 6 7 8* (5 times) You counted 10 times. With ragged lists, when you have a sublist just count the sublist and use that result. for example [ 1, [ 3, 6 ] ] 1 to ( count[ 3, 6 ] ->3 ) 1 to 3 -> 2 For empty lists you count 0 times, the same applies for lists of one element or lists of equal elements. [ ] -> 0 [ 99 ] -> 0 [ 8, 8, 8 ] -> 0 **Task** Given a ragged list of non negative integers count it as described above. **Test cases** ``` [] -> 0 [[2,5]] -> 0 [99] -> 0 [8,8,8] -> 0 [1,1] -> 0 [0,9] -> 9 [2,5,3,8] -> 10 [1,[3,6]] -> 2 [[],4,[[5,3],2]] -> 8 [100,100,[7,[[[6]]]],[[4,8]]] -> 100 [[9,5],0] -> 4 [[],[]] -> 0 [[],3,[]] -> 6 [1,[2,5,10]] -> 7 [2,6,9] -> 7 [[1,2],[1,3],[1,4]] -> 2 [1,99] -> 98 [11,9,6] -> 5 [0,1,2,3,4] -> 4 [2,3,3,3,2] -> 2 [0,1,0,1] -> 3 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), all usual golfing rules apply. [Answer] # [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#v:iter), 36 bytes ``` iter$sum.map abs.(zipWith(-)<*>tail) ``` [Try it online!](https://tio.run/##fVDLasMwELz7K/ZgqFTqQF16CbFPJdBTeyj0UEJRYileasvGkttQ8u/uSrKTGkIOfszs7MxIpTBfsqqGJIEjPEmFGvUebIkGStlJMKh3krAE1UkJdVP0lQQ0@saC@BZYiS3hRsPb80tUCCtg7XQKRASQwWtPHu73GHimgE0CzqMItbGCEkjBYN3rnW06UIQ4PWSQn8hxzfE/rpmfq1q0ZMV8zIFD5lkIsTFNDjOZt/gn8zgOYxZEnFYitLKD5fJcyBWh6gKSnHq793QIz4SFz7EHCbKJa0scY2vHengarOKc6EFljolNXy9cBbE1C/aL7TvakiV8dZtbumY@1AJ1VjRUve1QW3@8YP3hY@83/NLsMhs27sJFpVc06ah5HL8P1/1mfWYwndBMstmcOwx/ "Haskell – Try It Online") To represent a ragged list we use a free monad. Then this process is just iteration. Our iterative step is `sum.map abs.(zipWith(-)<*>tail)` which calculates the absolute differences and then sums them. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` ߀IASƲ⁸ŒḊ? ``` [Try it online!](https://tio.run/##y0rNyan8///w/EdNazwdg49tetS44@ikhzu67P///x9taGCgA8LR5jrR0dFmsUAAZJjoWAAZAA "Jelly – Try It Online") ## Walkthrough ``` ? If ŒḊ Depth (of input) != 0? € Foreach ß call this link I consecutive differences A Absolute of each SƲ sum ⁸ If == 0? return the link argument ``` [Answer] # [R](https://www.r-project.org/), ~~87~~ 86 bytes *Edit: -1 byte thanks to pajonk* ``` f=function(l,`+`=sapply)`if`(length(m<-l+is.list),{l[m]=l[m]+f;sum(abs(diff(l+c)))},0) ``` [Try it online!](https://tio.run/##bVHBboMwDL3zFZV2iYVbJZBC0cZ@ZJpE1y0dUmBVQw/TtG9nTkYCZFOEiZ/tF/v5Oo6qVrf@NLQfPdPYpE1tjpeL/oSmVQ3Tb/15eGfdw1anrdnp1gyAX/qpe66tSdW9uXXs@GLYa6sU0@kJAL6Rw0gOJTOAzd1m@8iTyXcmwz3EgaqKkQPSiUGBIoY4@tLKQ/QA5qFYLKrdL8fCv5@tGgOUOHvEAZj5zEMg4Rzt55xyke@MZYYFKG0boZG1DhXpQFr9BmXUySTff/oBDbcKF9GAdn7BfbScZSmCVuWKUdCcON3ycJN/VBIY9lTNghBqFXXwfl4LkVKjMp7PgvZkMbmt4GG/eZKMPw "R – Try It Online") **Ungolfed** ``` f=function(l){ # argument = l = ragged list m=sapply(l,is.list) # m = elements of l that themselves are lists if(length(l)){ # if l isn't an empty list l[m]=sapply(l[m],f) # replace its list elements by recursive call sum(abs(diff(unlist(l))) # and now count from each to the next and so on } else 0 # otherwise ( it's an empty list ) return zero. ``` Note: we use `sapply` twice above, so to save bytes we re-assign the `+` infix operator as `sapply`. Once we've done that, we might as well use it wherever we can: `unlist()` is a bit long, so instead we can `sapply` the identity function `c()` to all elements of a list, to get them unlisted: hence `l+c` instead of `unlist(l)`.... [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` λIȧ[vx¯ȧ∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu0nIp1t2eMKvyKfiiJEiLCIiLCJbMSxbMiw1LDEwXV0iXQ==) -1 thanks to lyxal. Or if we can assume no empty lists, 8 bytes: ``` λ-[vx¯ȧ∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOuy1bdnjCr8in4oiRIiwiIiwiWzEsWzIsNSwxMF1dIl0=) Both are essentially the same, just with different `is_array` checks. ``` λ # Create a recursive lambda... - [ # If the input is a list... - # int - int = 0 (falsy), lst - lst = list of zeros, truthy Iȧ # If n is int, remove_whitespace(" " * n) which is falsy. # If n is list, split into two halves and take the absolute value. vx # Call the lambda on each element of the list ¯ # Get differences between pairs of elements ȧ # Take the absolute value of those ∑ # Sum ``` [Answer] # Python, 68 bytes ``` f=lambda x:sum(abs(f(j)-f(k))for j,k in zip(x,x[1:]))if 0!=x*0else x ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRocKquDRXIzGpWCNNI0tTN00jW1MzLb9IIUsnWyEzT6Eqs0CjQqci2tAqVlMzM03BQNG2QssgNac4VaHif0FRZl4JUF80UI4LzjFE4RnpmOoY61igiUWDhKDi/wE "Python 3.8 (pre-release) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes (@att) ``` Tr@Abs@Differences@{##}&@@#&//@#& ``` [Try it online!](https://tio.run/##TU8xDoMwDNx5haVITKlIgNIytEqlPqBDN8RAEagMMACblbdTOwGKFNkX@@5y6av52/TV3NXV0sJteY/m8ZnMs2vbZmyGupkMCmFDY0QYRVSW19gNcyHgdIe2EGUJIUQmQLQyAMRYwtk6mOeuXSXwcVhL0A4oCX7LdAnJgYB0ybwDWUJKE2QK4diPtSK5K3jhLRKdNoRS9lm1OQeRoHYn/Jsm@40f9Bm0sluibEvH65il2gfgnu7C9YOaIWdeP8Ya90S6@SXbiQ8crtYuPw "Wolfram Language (Mathematica) – Try It Online") --- ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes ``` Map[Tr@*Abs@*Differences,#,{0,-2}]& ``` [Try it online!](https://tio.run/##TU@xCoMwEN39igOhg5w0idbWocVC10KHbuJgJVKHlmLdjny7zSVqhZB7uXvv3curHp76VQ9dU48tHMdr/SnvfRGdH98iunRtq3v9bvQXQySBsTLVZrz13XsoQ4hP0JZhVcEGtkVAZDAAIoWwMw7muSsHBD4OSwTpgEDwU6YjJCsC2UfmHawlpLZDTLFY@bYUVu4u2vOULN1OLErZZ9LmHARBLE70N02WFy/0GaQwc6JsTsdjxVLpA3BNF@H0QcmQM08fY41bkc5@yXzUisO3MeMP "Wolfram Language (Mathematica) – Try It Online") --- ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes ``` #/.x:List->Tr@*Abs@*Differences@*x& ``` [Try it online!](https://tio.run/##TU89D4IwEN39FZeQMJAqFOoHJhJMHB0c3IgDGogMMCCDyaW/vd61gCRN793de6@vbTm8q7YcmldpajgZL9x8j9fmM6yze58H5@cnDy5NXVd91b0qar6@ufVNNxQerDOoC@/xAB/CfIWoxQoQYwFbbWGa2nIQwMdiKUBaEAlwW6YLSBYEpGbnHMgSFE2QKYRjN5YRye2Fe94i0WlDSLHPqE05iIBodsK/aTJ3/KDLICM9JdpN6Xgds1S6AFzVLBw/KBly5vFjrLFPqMkvmU684PCttfkB "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 72 bytes ``` \d+ $* \[ <; {`(<1*);(1*)(1*),\2(1*)(,|]) $1$3$4;$2$4$5 }`<(1*);1*] $1 1 ``` [Try it online!](https://tio.run/##LU67DsIwDNzzHUFqi4c4SQtVu/MRrqUiwcDCgNiAbw/ntLL80Pl859f9/Xhey6G5rGW5HZ3v3CJuntxnbWbu2qlBsaQl1pG@2jrPPvk8@eiz791vnW01cafYOC5F1IlE6hV9HFHOhEBnYtRAhmFPaUcl0WBkUcokgoVSNIBDIEs5ARZwVDFknFX6CA8K26HsAmmbIGoOHLR6DdUTaASTTR81b8T6IqPjCfsOJKjkepdqxB1H6h8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` \[ <; ``` Place markers at the start of each sublist. ``` {` }` ``` Repeat until no more replacements can be made. ``` (<1*);(1*)(1*),\2(1*)(,|]) $1$3$4;$2$4$5 ``` If a sublist starts with two integers, then remove the first and insert the difference before the marker, which tracks the cumulative absolute total. ``` <(1*);1*] $1 ``` When a sublist runs out of integers then simply replace it with its total. ``` 1 ``` Convert to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` ⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκWυ«≔⊟υι≔⟦⟧ηWι⊞ηΣ⁺⟦⁰⟧⊟ι⊞ι↨EΦηλ↔⁻κ§ηλ¹»Iθ ``` [Try it online!](https://tio.run/##NY5Pa8MwDMXPy6fQUQYN9q@nndKywQ6DwI7GB7fNahEvaWJ7K5R9dldOU12Ent7vSTtnp91gfc5NCg4Twaheq@9hAkwK5s5LfxuT9QE7gsangNoQdEopuIGdgH@OfTuj5@quDoEPPTbDUQQClv1NK7Ar8wLwEuMIvtIPXg88iKnALFeKd3YwwdqGFj/tEd/Zx3YqkJf8ehsGn6KsuE/zn3X86Pft6WqQIngsQf9VM3EfcWNDxFGUnLWWj15I6xU9G3oyxuT7X38B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υθFυ ``` Start extracting all of the sublists. ``` FιF⁼κ⁺⟦⟧κ⊞υκ ``` Loop over all the lists and when a sublist is found then push it to the predefined empty list. ``` Wυ« ``` Process all of the sublists. ``` ≔⊟υι ``` Get the deepest remaining sublist. ``` ≔⟦⟧η ``` Start collecting the terms in this sublist. ``` Wι⊞ηΣ⁺⟦⁰⟧⊟ι ``` Remove the terms from the list and push their numeric value to the temporary list. Any sublists will have been reduced to their count as a single term `[n]` at this point, so prepending `[0]` results in `[0, n]` and taking the sum returns `n`, while adding `[0]` to an integer `n` results in `[n]` and then taking the sum returns `n` again. ``` ⊞ι↨EΦηλ↔⁻κ§ηλ¹ ``` Compute the absolute pairwise differences and push the total to the list. ``` »Iθ ``` Output the final total of the original list. [Answer] # JavaScript, ~~60~~ 52 bytes ``` f=(a,t=0)=>p=a.map?.(p=x=>t+=Math.abs(p-f(x)|0))?t:a ``` ``` f=(a,t=0)=>p=a.map?.(p=x=>t+=Math.abs(p-f(x)|0))?t:a console.log(f([])) console.log(f([[2,5]])) console.log(f([99])) console.log(f([8,8,8])) console.log(f([1,1])) console.log(f([0,9])) console.log(f([2,5,3,8])) console.log(f([1,[3,6]])) ``` *Saved 8 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718).* [Answer] # [SWI-Prolog](http://www.swi-prolog.org), ~~123~~ 105 bytes ``` []+0. [_]+0. [H,S|T]+C:-(is_list(H)->H+G;G is H),(is_list(S)->S+Q;Q is S),D is abs(Q-G),[S|T]+R,C is D+R. ``` *-18 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)!* [Try it online!](https://tio.run/##TZDLasMwEEX3/govLTQyku04UQIpeYC9ddzdIEK7SDEEEupCN/13d0Z@KAhbujNXV0d6fj/ujy/V/3bDgE7qNMLrONXQ/r07edqqpOuv967/SWqh9rWsdlXc9XEtYGm01Ghls2u40Qo48/zx2SeNqgSgD7rAiatneUmHW3KAo9iqgzym0Zu6Jegg1gIiWmEGKxektWG9ARpBGjBBaGCjHQVFQO6tZvFiDiXnZtMxDgpAJJ@DjOubyag18Idr6iLtoB5iQWHOx82UlihBU6lY8vAFm2Q@FsoFgKmM5tp6xiw99STJk1GKYST6Fy@0Bvw72BmSNN0G4tV8edpKBxaBhyWPLISwS/s3y0U6/AM "Prolog (SWI) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 75 bytes ``` f=->a{a*0==0?a:([a[0]]*(a.size%2)+a).map(&f).each_cons(2).sum{(_2-_1).abs}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVFbasMwEKS_OYUwtNiJLCTZcewWpwfoEVRhlGDTQB6msgutyQF6hv7koz1Ue5ruWlYQEjur2dmR9uv7td-8Xy4_fdfE-e9TU8ZrM5g5L0v-aO5DZRTXeh4aZncf9a2MFiZiB9OGd03EarN9qbanow1lxGx_GMJKxpWImNnY89lJ_t18BkqTeE34TClJl9qDovBRTmF5IKjwIaeOUsywkCYTSYwsldDMaUkQ1jSlSgFHU-myOZA4p7jVCu4UsLWGIAUZPQmhpwI8UT4m0lFJXS0CSDzMxqboQ3CXWaGtbPIIAO4lVAs0AWd6dSfo9NYCTQEC5wiX-EQogiap748Al_TFyODTnyQBs-1-14XB8zEY5zDYshIuCYN6aIklCxIgN4CgUfWb2ROrWXeq7DQRP-x_) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "ИÊi®δ.V}ИQi¥ÄO"©.V ``` Ugh.. :/ [Try it online](https://tio.run/##yy9OTMpM/f9f6fCE03MOd2UeWndui15YLYgXmHlo6eEWf6VDK/XC/v@PNjQw0AHhaHOd6Ohos1ggADJMdCxAdGwsAA) or [verify all test cases](https://tio.run/##NU4xDsIwDPxKldmqkiYUOvUJiKWLlQEkhk4MSEgd2BADE2JmZWBh4gXtiMQj@Eg4J60sO875zufdfr1pt@HQ1Sr7nW@ZqrughuvnPlza/vV9581Rfqu2fwynpeqfeRMoMHvKmAuaeWmqSuqCENIYMvJoijBIZKcBWyqjBAscMWPkqYiI0ZokeQ6cwQLK7KBMggpmpEctT0vs2GK1GBntk2eZzIEXYBuxQXUjNx1s0OCceCp42OWS2MYopgnS@z8). **Explanation:** ``` "..." # Define the recursive string below © # Store it in variable `®` (without popping) .V # Evaluate and execute it as 05AB1E code, using the (implicit) # input-list as argument # (after which the result is output implicitly) Ð˜Ê # Check if there is an inner list: Ð # Triplicate the current list ˜ # Flatten it Ê # Check if the top two lists are NOT the same i # If this is truthy: δ # Map over each inner item: ® .V # Do a recursive call } # After the if-statement, whether we executed its body or not: ИQ # Check if this is a 1D list: Ð # Triplicate the current list ˜ # Flatten it Q # Check if the top two lists are equal i # If this is truthy: ¥ # Pop the list, and push its deltas/forward-differences Ä # Convert each to its absolute value O # And then sum this list ``` [Answer] # [Python](https://www.python.org) NumPy, 69 bytes ``` f=lambda s:sum(abs(s*-1or diff([*map(f,s or[])]))) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVDLbsMgEFSv_gqUE0SbCmzHiSOlp_bUT0AcHCUoSLZBfrTKt_SSS_tP7dd01zYRAu0sM7MDXz_hNlx9e79_j4Pd7H_f7LGumtO5Yv2hHxtenXrerzfKd-zsrOV63VSBW-iZ77QRRgiR2M43rB2bcGOuCb4b1ovZ6-fV1RemDgljzIFnR0bqy0dVg2vDOHDx3IfaDXzFNi9shV5IDJ1rB-7AcifAi9nr_vf0rg2xZKJ1ClsTQVnGag-4IlCgYilhppQJCSFbSGpi6QyK2StFYwM5aI0cA-nc3SNJSqCtd3inkW0MFjnamMWIMpWYCeTUyCcn_YiIIIuwmIZSDiXnzo5iFUtGBHifolpRCDzzRzoFy1tLCoUIkxPc0hNRhEPyOJ8ArTSKiSGXP8mS-VP_AQ) I suspect it's 66 bytes in Python2 but have no way of checking. [Answer] # [Perl 5](https://www.perl.org/), 88 bytes ``` sub f{$_=pop;1while s!\[[\d,]*\]!@a=$&=~/\d+/g;0+sum map abs$a[$_-1]-$a[$_],1..$#a!e;$_} ``` [Try it online!](https://tio.run/##bVLfT8IwEH7nrzi0OtAD2m2gY6n6rpEXfeoaMqXMRX5MNqKG4L@ON9iMI0vT5fp9vfvuuy4xq1l/t04NPMRpNhw@Z/EMPj5b83gB6Xre9hvT5arVUABgKW2BvAFOscYCUjb2dQ3ueTXgNdKqwQWKGpRjUcP7j5IeOmUVcVRGOTgourErXWp0USnK1GgXF64rqZxjvtUVXVNUQ2sKXNLRpVLVtke2kR8490hK1Q2EcOePGRy1nZsSvCCvqnYH5RgqOGXZpCRyR/R161wLLF/Bq5olgua0Z/rViVNVatOt8ZXj@bJrhPI8Xr6hc2DamwYFMP9usRiZacs7NvYLiEVySnD7cE5W8SKbnpx1BimA@UrMa2YmQzhzJkRGy6wM40WypgOLg8UJAjNSsghuwVq@WzAE63H0BKN7K2doR4fa7FVyv7HdpesXmG7YWCbLxBefb/HMQNoMlAomqC8C3bwLJTuXP71gctmLfH5J/z7MwwTCl5SFio07Qnf2gUbR7bLTsGl8Nt7udr8 "Perl 5 – Try It Online") ]
[Question] [ A rhyme scheme is the pattern of rhymes at the end of the lines in a poem. They are typically represented using letters, like `ABAB`. We consider two rhyme schemes identical if they are [isomorphs](https://codegolf.stackexchange.com/q/50472), and therefore only report the lexicographically earliest. Equivalently, rhyme schemes are simply strings in [standard order](https://codegolf.stackexchange.com/q/241457). The rhyme schemes of length 4 are: ``` AAAA, AAAB, AABA, AABB, AABC, ABAA, ABAB, ABAC, ABBA, ABBB, ABBC, ABCA, ABCB, ABCC, ABCD ``` A *complete* rhyme scheme is one where every line rhymes with at least one other line; that is, every letter in the string appears more than once. For length 4, these are: ``` AAAA, AABB, ABAB, ABBA ``` Now consider the sequence of the number of complete rhyme schemes for any length. With length `0`, `2`, or `3`, there is exactly one way to do this (`​`, `AA`, and `AAA` respectively), and length `1` has no ways. As we see, length 4 gives `4` ways. The first 30 terms of this sequence are: ``` 1, 0, 1, 1, 4, 11, 41, 162, 715, 3425, 17722, 98253, 580317, 3633280, 24011157, 166888165, 1216070380, 9264071767, 73600798037, 608476008122, 5224266196935, 46499892038437, 428369924118314, 4078345814329009, 40073660040755337, 405885209254049952, 4232705122975949401, 45398541400642806873, 500318506535417182516, 5660220898064517469939 ``` This is [A000296](https://oeis.org/A000296) in the OEIS. It is also the number of ways to partition a set into subsets of a size of at least 2. Your task is to output this sequence. The sequence should not be limited by the 26 letters in the alphabet; the letters can be abstracted such that the sequence continues infinitely. The complete rhyme schemes which use the digits `1`-`9` is OEIS [A273978](https://oeis.org/A273978). ## Rules * As with standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you may choose to either: + Take an input `n` and output the `n`th term of the sequence + Take an input `n`and output the first `n` terms + Output the sequence indefinitely, e.g. using a generator * You may use 0- or 1-indexing * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` (%1) 0%_=1 n%i|i<n=(i-1)%1+(n-i)/i*n%(i+1)|1>0=0 ``` [Try it online!](https://tio.run/##FccxDsIwDADAva/wgKWEKsXecX/ACyhCUUXAIrUiyti3Y9Tb7pXX96NWLzJ5QI4d4V24M9RNzyZBE0fkPljSeNKjYdCe48YjCfmS1UBgye0C7aP2hcMeKHClYWC6@W8uNT9XT3Nrfw "Haskell – Try It Online") Uses this recursion I found: $$ f(n)=g(n,1), $$ where $$ \begin{eqnarray} g(0,i) &=& 0\nonumber \\ g(n,i) &=& g(i-1,1) +\frac{n-i}{i} g(n,i+1) \text{, if } i< n \nonumber \\ g(n,i) &=& 0 \text{, otherwise} \end{eqnarray} $$ **45 bytes** ``` (%0) 0%_=1 n%i|i>n-2=0|j<-i+1=i%0+(n-j)/j*n%j ``` [Try it online!](https://tio.run/##Fcc7DsIwDADQvafwUEv9KMVhrrkBJ4AKRRUBh9SKKGPPjqu@7b3D@nnmbJHv1iC1FeGDfaUom1zUnZm2NDrpPQtS36hL7Sl1ismWIAoMSyhXKF/RH9RHIMKNhsHTZP855vBazc2l7A "Haskell – Try It Online") **47 bytes** ``` (%1) 0%_=1 n%i=sum[(i-1)%1+(n-i)/i*n%(i+1)|i<n] ``` [Try it online!](https://tio.run/##FcdBDoIwEADAO6/Yg5u0kkL3bp/gC4CQhlDc2G4aqzfe7hrnNo/YnnvOmsKsBsl2HtdAnSCH9imTYUcWqTfi2I58FTTckz35JouWyAIBSqx3qC@WN1z@gQSTHwbyi363lOPR1G21/gA "Haskell – Try It Online") **45 bytes** ``` f n=foldr(\j x->f(j-1)+n/j*x-x)(0**n)[1..n-1] ``` [Try it online!](https://tio.run/##FcfBEYMgEADAVu6RB5A5hAKwg1SgPhj1DIgXRn1QfS6T/e07XvtaiggBB/qU5VRjhoY9qYxeP7nLpmHTyhnDevDWMvpJjpgYAhyxvqCeiW94/AMEg7PWu0m@M5W4XYJzrT8 "Haskell – Try It Online") Some float inaccuracies show up. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` 1IS;ƊÄ$¡IIS+¬ ``` [Try it online!](https://tio.run/##y0rNyan8/9/QM9j6WNfhFpVDCz09g7UPrfn//7@RJQA "Jelly – Try It Online") ``` 1IS;ƊÄ$¡IIS+¬ 1 $¡ Starting from [1], iterate an operation n times: IS Sum the increments (i.e. last minus first), ;Ɗ prepend this to the array, Ä and take the cumulative sum. e.g. [a,b,c,d] → [d-a, d, d+b, d+b+c, d+b+c+d] IIS Increments, increments, sum. +¬ This erroneously gives a(0)=0, so add 1 if n=0. ``` This is a port of the Maple code contributed to the OEIS page by Peter Luschny. As far as I understand, it's similar to Neil's answer, but modifies Aitken's array to get the result directly. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes *Avoid another loop variable saves ~~7~~ 8 bytes as suggested by [att](https://codegolf.stackexchange.com/users/81203/att).* ``` f=(n,i=n)=>i?--i&&f(n,i)*i/(n-i)+f(n+~i):1 ``` [Try it online!](https://tio.run/##FchBDoMwDAXRq3iFbEIobEsDZ0FpUv0K2RUgllw9hdXozXc@5i2u@O1e7Z1KyYG1QVAJIybvUVX5HlLjweoh7qI7Ic@@ZFuJQYG6gUAv6u86JxRNN1tSu9iH0VBmiAzlDw "JavaScript (Node.js) – Try It Online") $$ f(x) = \sum\_{i=1}^{x-1} \binom{x-1}{i}\cdot f(x-1-i) $$ with special $$ f(0) = 1 $$ For complete rhyme patterns with length n: 1. The first rhyme is `A` by definition 2. We choose `i` rhymes after it and fill it by `A`; 1 < i < n-1 3. For unfilled cells, it become a recursive question 4. So we count `f(n-1-i)*combination(n-1,i)` rhyme patterns. [Answer] # [MATL](https://github.com/lmendo/MATL), 23 bytes ``` :Y@!"@Y>@=f@d0<fX=]N~vs ``` Input is 0-indexed. Try it at [**MATL Online**](https://matl.io/?code=%3AY%40%21%22%40Y%3E%40%3Df%40d0%3CfX%3D%5DN%7Evs&inputs=5&version=22.4.0)! ### Explanation This uses the following characterization from OEIS: *a*(*n*) is the number of permutations of [1, 2, ..., *n*] for which the positions of the left-to-right maxima coincide with the positions of entries that are followed by a smaller number. ``` : % Implicit input: n. Range [1 2 ... n] Y@ % All permutations. Gives a matrix where each permutation is a row ! % Transpose. Now each permutation is a column " % For each column @Y> % Cumulative maximum of the column @= % Compare each entry with that of the column f % Indices of true entries, i.e. of left-to-right maxima (*) @d % consecutive differences of the column 0< % True for negative values f % Indices of true entries, i.e. of descents (**) X= % Are (*) and (**) equal? Gives true or false ] % End N~ % Number of terms in the stack, negated. Gives 1 for n=0 v % Concatenate all values into a column vector s % Sum. Implicit display ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes ``` Nest[#'&,E^(E^#-1-#)&,#]@0& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCRaWV1NxzVOwzVOWddQV1lTTUc51sFA7X9AUWYeUFLXLs1BOVatLjg5Ma8uKDEvPTXaQMfYIPY/AA "Wolfram Language (Mathematica) – Try It Online") Uses the exponential generating function given on OEIS: > > E.g.f.: exp(exp(x) - 1 - x). > > > --- **alternative 27 bytes:** ``` D[E^(E^x-1-x),{x,#}]/.x->0& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yXaNU7DNa5C11C3QlOnukJHuTZWX69C185A7X9AUWZeSbSyrl2ag3KsWl1wcmJeXVBiXnpqtIGOsUHsfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES7), 90 bytes Outputs the \$n\$-th term, 0-indexed. ``` f=(n,k=n)=>~k&&(h=j=>~j&&(F=n=>n?F(n-1)/n:1)(j)*F(k-j)*(-1)**j--*(-j)**n+h(j))(k)-f(n,k-1) ``` [Try it online!](https://tio.run/##FYxBDoJADEX3nKILQtrBUXGpFnecA4IgzpCOAeKG4NXHsnqv/zffNd9mbqf3Z7ESnl2MPaMcPAtx@fNZhgM7NadWsXApjwrFFnSSa0HoyFTorQI1M8ZZq6ankXzQltCT7fdBrWMfJhy7BQQYzjfFHS4785xgTQDaIHMYu@MYXlg3mK6ykb6mqy7QVlOyxT8 "JavaScript (Node.js) – Try It Online") There's a floating-point rounding error for \$a(3)\$. ### How? This is based on the following formula from [A000296](https://oeis.org/A000296): $$a(n)=\sum\_{k=0}^n{(-1)^{n-k}\times\sum\_{j=0}^k\left((-1)^j\times\binom{k}{j}\times (1-j)^n\right)/k!}$$ which can be turned into: $$a(n)=\sum\_{k=0}^n{(-1)^{n-k}\times\sum\_{j=0}^k(-1)^j\times (1-j)^n/j!/(k-j)!}$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔¹η⊞υ¹FN«≦⁻⌊υη⊞υ⌈υUMυΣ✂υλ»Iη ``` [Try it online!](https://tio.run/##NYzNCsIwEITP7VPkuIEK5uxJehJMKfQJ1tqaQH5KkhVBfPaYUD3Nzjc7MysMs0eT8zlG/XAgOqb4qR0pKqCOiXKvPjC4uI3SQPa2BOCcvdtG4rZ3rsuaQGpHsWNFtCULxPed5j8k8fULKi3d3luL7l6zqfDJ6HmpxvD68WnHoF2CHmMCVUjO4pgPT/MF "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed, obviously, given that this is the number of complete rhyme schemes for a given length, so the input should be the length. Explanation: ``` ≔¹η ``` Start with `1` complete rhyme scheme for a length of `0`. ``` ⊞υ¹ ``` Start computing Bell numbers (A000110). ``` FN« ``` Loop length times. ``` ≦⁻⌊υη ``` Subtract the current result from the current Bell number. ``` ⊞υ⌈υUMυΣ✂υλ ``` Compute the next row of Aitken's array to obtain the next Bell number. (Actually computes the row reversed because it's golfier.) ``` »Iη ``` Output the final number of complete rhyme schemes. [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ 74 bytes Port of a Maxima function found in the *prog* section on OEIS. -4 bytes thanks to xnor! ``` from math import* f=lambda n:sum(comb(n-1,i)*f(i)for i in range(n-1))+0**n ``` [Try it online!](https://tio.run/##RclLCsJADADQfU@RZTJV8IMgBQ8zrcaGmmRIx4Wnn9KVb/vKr85u13uJ1jhcQXOdQbR41NTx45N1fGawYf0qTq4j2vF8EEqMQuwBAmIQ2d6vfYj6U0rW9ln@c7nR0AGUEKvYMy5EbQM "Python 3.8 (pre-release) – Try It Online") Same length with more recursion: ``` f=lambda n,i=0:(n-i>1and comb(n-1,i)*f(i)+f(n,i+1))+0**n f=lambda n,i=0:~i+n and(n<1or comb(n-1,i)*f(i)+f(n,i+1)) ``` [Answer] # x86 32-bit machine code, ~~29~~ 28 bytes ``` 31 c0 99 e2 09 c3 52 e8 f6 ff ff ff 5a 59 42 51 f3 0f b8 ca 3b 0c 24 7c ed 59 40 c3 ``` [Try it online!](https://tio.run/##ZVHRTsMwDHwmX2EVIbVbN8F4Yys/AqjK3LQNStOSpFAJ8esUpwljQB7c3NV3jm3cNIjzfCk1qrEScLCukv22vWe/KCWPfzkjdeM5VpbcETqOTpRlmtbcOuRKZRlI7aBOfeTZnnHbQcqSR71tVH/kCurEo/pu@VxMvQHBp9yHhTECR2Nlr2MCVi/hovp@AKGdMP4WOCNcFA2Cu6gYRtuCqKaop0fByTRmeKfvhAVgACf7aEWNnyUuvvgjQ2qRcH5WrBsC8yDs8BS4Z1/eP@9/ueAfGw/N0MSYH13HpQ4zNA3mgC03sFoReM3YOwM6/ucEBVzvF/jWSiUgneBQwM0uWzh/BtqYq9PkSkKS016m9TqjIr7aaLRXf7B5/sRa8cbOm@52R4GWVpBMqC8) Following the `fastcall` calling convention, this takes the 0-indexed `n` in ECX and returns the `n`th value in EAX. -1 with some rearrangement and changes. Assembly: ``` .intel_syntax noprefix .global f f: xor eax, eax # Set EAX to 0. recursion: # Starting here will add the value to EAX instead of replacing it. cdq # Set EDX to 0 (as long as EAX hasn't overflowed). loop enterloop # Calculate n-1 and jump if that's not 0 (n≠1). ret # Return with 0 for n=1. repeat: push edx # Push EDX onto the stack. call recursion # Recursive call, using the number of different positions. pop edx # Restore EDX from the stack. pop ecx # Restore ECX from the stack. enterloop: # EDX will be a bitmask of positions different from the last. inc edx # Add 1 to EDX. push ecx # Push ECX (n-1) onto the stack. popcnt ecx, edx # Count the different positions, into ECX. cmp ecx, [esp] # Compare that with the value of n-1 on top of the stack. jl repeat # Continue the loop if fewer than n-1 different positions. pop ecx # (Otherwise: all n-1 positions, or n=0) Take n-1 off the stack. inc eax # Count 1 for the all-the-same rhyme scheme. ret # Return. ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes ``` n->n!*Vec(exp(exp(x+O(x^n++))-1-x))[n] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLk9RKyw1WSO1ogCMK7T9NSri8rS1NTV1DXUrNDWj82L/p@UXaeQp2CoY6CgYA3FBUWZeCVBASUHXDkikaeRpamr@BwA "Pari/GP – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 128 bytes ``` lambda n:round(sum((-1)**(n-k)*sum((-1)**j*comb(k,j)*(1-j)**n/perm(k)for j in range(k+1))for k in range(n+1))) from math import* ``` [Try it online!](https://tio.run/##RU9dj4MgEHzvr9g3wcMcCwq0ifdH2j5Yi1drRYM0ubumv93D3kcJGXaGnYUZP8NpcNKMfm7K3Xyp@sOxArfxw9UdyXTtCcmQpilxWUfTJz@n9dAfSMfONCWYRUzd62h9TzraDB7O0DrwlXu3pHtB@tC6p@YWja4aP/TQV@EEbT8OPqSz/RhtHewRStgiA84AHzuPuBwLU4KBxoKBzEVE1FpEZW1EIRkUhkvU8U5JKUz0i5wjYqEXozLGoFo8AhXXXC4Na6FyrlGr2KKl4lyv44xIFDe5jtygEPtVfbJ1Z338GEl2V6HzOmHwqFAmMUoMGJhdIn61I/mJebGO/CWilMF/vVlBXFMc1pBAH2T0rQukSW7hDtkb3KY73H7f3E5laff3hM7f "Python 3.8 (pre-release) – Try It Online") Uses the same formula (unchanged) from [A000296](https://oeis.org/A000296) that [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) uses in his [JavaScript answer](https://codegolf.stackexchange.com/a/240631/9481). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1=λD¥OšηOD¥¥O, ``` Port of [*@Lynn*'s Jelly answer](https://codegolf.stackexchange.com/a/240650/52210), but outputs the infinite sequence newline-delimited instead. [Try it online.](https://tio.run/##yy9OTMpM/f/f0PbcbpdDS/2PLjy33R/IADJ1/v//r6ubl6@bk1hVCQA) **Explanation:** ``` 1 # Push 1 = # Print it with trailing newline (without popping) # (workaround for edge case a(0)=1) λ # Start the recursive environment, # to output the infinite sequence # Starting with the a(0)=1 we've pushed # (implicitly push the value of a(n-1)) D # Duplicate this a(n-1) ¥ # Pop and push a list of its forward differences O # Sum those š # Prepend it in front of the list η # Pop and push a list of its prefixes O # Sum those as well D # Duplicate it (which will be the result of this a(n)) ¥ # Pop and push a list of its forward differences ¥ # Do it again O # Sum those , # Pop and print it with trailing newline ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes ``` 1w?(:¯∑p¦)¯¯∑1⟑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxdz8oOsKv4oiRcMKmKcKvwq/iiJEx4p+RIiwiIiwiNCJd) A messy port of [Lynn's answer](https://codegolf.stackexchange.com/a/240650/100664), go upvote that! ]
[Question] [ Thanks to [rak1507](https://codegolf.stackexchange.com/users/95516/rak1507) for the [suggestion](https://chat.stackexchange.com/transcript/message/58238593#58238593) > > "Random" in this challenge always refers to "uniformly random" - of all possible choices, each has an equal chance of being chosen. Uniform shuffling means that every possible permutation of the array has an equal chance of being chosen. > > > Given an array consisting of positive digits (`123456789`), select a randomly chosen, non-empty subsequence from the array, shuffle the elements and reinsert them back into the array in the former indices, outputting the result For example, take `L = [5, 1, 2, 7, 4]`. We choose a random non-empty subsequence, e.g. `[5, 2, 4]`. These are at indices `1, 3, 5` (1-indexed). Next, we shuffle `[5, 2, 4]` to give e.g. `[2, 5, 4]`. We now reinsert these into the list, with `2` at index `1`, `5` at index `3` and `4` at index `5` to give `[2, 1, 5, 7, 4]`. You may also take the input as an integer or a string, and output it as such, or you may mix and match types. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 11 bytes ``` JŒPḊX,Ẋ$yJị ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJKxZJQ4biKWCzhuookeUrhu4siLCIiLCIiLFsiNSwxLDIsNyw0Il1d) ``` JŒPḊX,Ẋ$yJị Main Link J Get the list of indices [1, 2, ..., n] ŒP Powerset - all possible subsets Ḋ Remove the empty one X Select a random one ,Ẋ$ Pair that with a random permutation of itself yJ Translate the original indices according to that mapping ị Index back into the original list ``` [Answer] # [J](http://jsoftware.com/), 37 40 39 35 bytes ``` ({~#?#)@:{~`]`[}1 I.@#:@+0{1?_1+2^# ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NarrlO2VNR2squsSYhOiaw0VPPUclK0ctA2qDe3jDbWN4pT/a3KlJmfkK6QpmOooGOooGOkomOsomPwHAA "J – Try It Online") +3 after reading hyperneutrino's answer and realizing I had to remove the empty subset -4 after reading loopy walt's answer and realizing I could make my random choice before converting to binary Consider `5 1 2 7`: * `1 ...+0{1?_1+2^#` If `n` is input length, picks a random number between 1 and 2^n. * `I.@#:@` converts it to binary, and then converts that mask to indices. That is, the first 2 steps amount to choosing a random element from the 2nd column: ``` ┌───────┬───────┐ │0 0 0 1│3 │ │0 0 1 0│2 │ │0 0 1 1│2 3 │ │0 1 0 0│1 │ │0 1 0 1│1 3 │ │0 1 1 0│1 2 │ │0 1 1 1│1 2 3 │ │1 0 0 0│0 | │1 0 0 1│0 3 │ │1 0 1 0│0 2 │ │1 0 1 1│0 2 3 │ │1 1 0 0│0 1 │ │1 1 0 1│0 1 3 │ │1 1 1 0│0 1 2 │ │1 1 1 1│0 1 2 3│ └───────┴───────┘ ``` * `({~#?#)@:{~`]`[}` Now "amend" the original input at those indices with the current values at those indices, shuffled. [Answer] # [Perl 5](https://www.perl.org/) List::Util, 47 bytes ``` sub{@_[@s]=@_[shuffle@s=grep.5<rand,0..$#_];@_} ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKnaIT7aoTjWFkgVZ5SmpeWkOhTbphelFuiZ2hQl5qXoGOjpqSjHx1o7xNf@ty4oyswrUcjKz8xTV9dRU0nTKC7IySzR19cxNDI2MTUzt7DU/P8vv6AkMz@v@L@ur09mcYmVVWhJZo4t1HAA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~82~~ ~~79~~ 77 bytes Or **[R](https://www.r-project.org/)>=4.1, 70 bytes** by replacing the word `function` with a `\`. *Edit: fix for 1-length input thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` function(v,k=seq(!v),`[`=sample)`[<-`(v,m<-k[k[1,,choose(max(k),k)]],sort(m)) ``` [Try it online!](https://tio.run/##bY5NCoMwEIX33qKuZiClDcVN0ZOINDGMKElM6iRiT2/tpivf8n28n2XnMQ@DoxfnnumdaTbU7EOeTZrCDKuwzWHDZUWhWtWw9tERqra@qgP6@mpb20ohzBgCE3i9gUVhsesEhyWBRzybAPmUdywKSdUt6d4R5NlNnMDpGN3nh6kS/xsbRs2J4LzpgcIEdySZmrLEQ8X@BQ "R – Try It Online") Different approach to [Dominic's R answer](https://codegolf.stackexchange.com/a/240312/55372) (test harness stolen from him). Samples length of the subsequence to shuffle from a distribution given by a truncated row of Pascal's triangle. Then samples this many indices in random order and substitutes the corresponding values for the sorted counterparts. ``` function(v, # function taking v as input k=seq(!v), # sequence along v (1:length(v)) s=sample){ # rename for golfing purposes n<- # how long the subsequence s(k,1, # sample from k one number prob=choose(max(k),k)) # distribution given by row of Pascal's triangle # without the first 1 (corresponding to empty subsequence) m<-s(k,n) # sample n items from k v[m]= # in v: at indices given by m v[sort(m)] # place values from indices at sorted m v} # return v ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` ẏÞS℅~İṖ℅Z(n÷Ȧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/DnlPihIV+xLDhuZbihIVaKG7Dt8imIiwiIiwiWzUsIDEsIDIsIDcsIDRdIl0=) ## Explained ``` ẏÞS℅~İṖ℅Z(n÷Ȧ ẏ # Push the input and the range [0, len(input)) ÞS℅ # Choose a random sublist of indices ~İ # And index into the input at those places, without popping anything Ṗ℅ # Choose a random permutation of the indexed items Z # and zip that with the chosen indices - this creates a list of [[original index, new item]...] ( # for each pair: n÷Ȧ # input[original index] = new item ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 72 bytes ``` SubsetMap[c@*Permutations,#,c@Rest@Subsets[i=0;++i&/@#]]& c=RandomChoice ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0qTi1xDexIDrZQSsgtSi3tAQol59XrKOsk@wQlFpc4gBRUhydaWtgra2dqabvoBwbq8aVbBuUmJeSn@uckZ@ZnPo/oCgzr8QhzaHaVMdQx0jHXMekts4lv87I4D8A "Wolfram Language (Mathematica) – Try It Online") ``` SubsetMap[ ,#, ] replace at indices: Subsets[i=0;++i&/@#] of subsequences c@Rest@ (random nonempty) c@*Permutations with a random permutation ``` [Answer] # Python, 140 bytes ``` from random import* def f(a): n=len(a);s=randint(1,2**n-1);t=[j for j in range(n)if s&2**j] while t:u=choice(t);T,*t=t;a[T],a[u]=a[u],a[T] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZJNTsMwEEbFNqfwCtnBDQQ2qJGlSlyhO8uqUtchLvGPnIloOAM3YNMN3AlOg93QUphF7ChPb754_PbhR2id3e_fB2hm95-vTXAGhdpu4qKNdwHybKMa1OCazDNkWads3FY9S5C2gEt6m-d2VpIKGN-ixgW0RdomyaPClugG9ZcR2YoMPbe6UwjmA5Ot01JhINWS5sCgqvlS0JoPgqUHTa9Tpq-LcQqC7GD8SDWoAM51PZWu65QE7WyfHULKVsmnKWgsz3h-gguvghmgPtAREUdEM3bwFnLFa5HS65TeT0Cy9rBZBeXx-sebKigYgkVGW4xzrBd4_UdDFrpYksI6-6KCw4SXghL0KycHkWRnf1A8uMHGtHj69u8Yy5tYZ_13rC6k8yMmVYN3pJL8mHJHxBUrTw5PZbLIwrgeVtIZ4yw-E_mQZhip69iCZNl0hDwOld4JMk3geDu-AQ) Changes the input list in-place (no return value). It first draws a random integer from `[1,2^n-1])` where `n` is the length of input list `a`. Its binary representation is used as a mask to uniformly select from the allowed subsets (all but the empty one). This subset is then randomly shuffled by applying a series of swaps. The swap is always the lowest active with a randomly chosen active position. I say "active" because after the swap the low element is retired from the active set and no longer eligible for swaps. It is left as an easy exercise for the reader to verify that this draws uniformly from all permutations of the subset. The test code makes the histogram suggested by @tsh (more or less; I lump together permutations with the same structure) in a comment and the distribution looks ok. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~36~~ 35 bytes ``` ≔⌕A⮌⍘⊕‽⊖X²Lθ²1ηFLθ⊞υ⎇№ηι‽⁻ηυιIEυ§θι ``` [Try it online!](https://tio.run/##RY47C8JAEIR7f8VitYGzMCgWVjEiBBSC2onFkay5g7in9/Dx68@LCG4xxTDz7TRK2sbIPsbCOd0xbjS3Rd/jnh5kHeFKOjp4q7nDihtLV2JPLe4lt@aKa/pbtXmSxVzAlrjzCu9ZOgH5IOPpOKnKlqOLsYD/BNTBKQwCjmRZ2jeWJrBHJUCnwu/LTnNwgxcGls4Spk6LPJbSedzJ2wAofMUtvfD@TaRMjKfTXMA0TRCwEDA7n@Pk0X8A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⌕A⮌⍘⊕‽⊖X²Lθ²1η ``` Choose a random number from 1 to 2 to the power of the length of the input (exclusive). Convert it to base 2, and get the exponents of the powers of 2 that sum to that number. ``` FLθ⊞υ⎇№ηι‽⁻ηυι ``` Create a random permutation of those exponents, while keeping the unused exponents in their original position. ``` IEυ§θι ``` Apply that permutation to the original input. [Answer] # [R](https://www.r-project.org/), ~~91~~ ~~85~~ ~~84~~ 82 bytes *Edit: -1 byte thanks to pajonk, then -2 bytes thanks to Giuseppe* ``` function(v,l=sum(v|T),`?`=sample,m=(l:0)[!(2:2^l-2?1)%/%2^(0:l)%%2]){v[m]=v[?m];v} ``` [Try it online!](https://tio.run/##bY7NCoJAFIX3vkWBcC9M6Ey4MQZfop1o/nAl4Y5a4wxF9exmm1ae7eE737kv9uq6juliXWPp5mhoSS@dG9q5HwfwgrV1Bvz7jKLKKm1rMzEJo4HTGPMdqFSVfFCZxDAKVQlxyhiGqsCXz02hfZ6Z4uQ/Wx6QqYwxCCQl0Vw3TOAG7u0MXE8TP381JeL/5YFTbWeC7aUjinbklbSk93tcEyxf "R – Try It Online") TIO link includes (reciprocal) distribution of `shuffle_subsequence(1:3)` to check conformity to tsh's calculations. [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html), ~~60~~ 53 bytes *Edit: -7 bytes thanks to mlochbaum, and also thanks to ovs and mlochbaum for bug-spotting* ``` •rand.Deal{(𝔽∘≠⊸⊏⌾(((2⋆⊒˜𝕩)(2|·⌊÷)˜1+⊑𝔽1-˜2⋆≠𝕩)⊸/)𝕩)} ``` [Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=U2h1ZmZsZV9zdWJzZXEg4oaQIOKAonJhbmQuRGVhbHso8J2UveKImOKJoOKKuOKKj+KMvigoKDLii4biipLLnPCdlakpKDJ8wrfijIrDtynLnDEr4oqR8J2UvTEty5wy4ouG4omg8J2VqSniirgvKfCdlakpfQoKdiDihpAg4p+oMSwyLDMsNCw1LDYsNyw4LDksMTDin6kKU2h1ZmZsZV9zdWJzZXEgdgo=) Ungolfed, commented ([try it here](https://mlochbaum.github.io/BQN/try.html#code=dmVjIOKGkCDin6gxLDIsMyw0LDUsNiw3LDgsOSwxMOKfqQpEZWFsIOKGkCDigKJyYW5kLkRlYWwgICAgIyByYW5kb20gcGVybXV0YXRpb24gb2YgMC4u8J2VqS0xClJhbmQg4oaQIOKKkURlYWwgICAgICAgICAjIHJhbmRvbSBudW1iZXIgZnJvbSAwLi7wnZWpLTEKU2h1ZiDihpAg4oqi4oqPy5zCt0RlYWziiaAgICAgICMgcmFuZG9tIHNodWZmbGUgb2YgbGlzdCDwnZWpCm51bSDihpAgMStSYW5kIDEty5wy4ouG4omgIHZlYyAgICAgICAgIyBwaWNrIGEgcmFuZG9tIG51bWJlciBmcm9tIDEuLjJeKGxlbih2ZWMpLTEpCmJpdHMg4oaQIHsoMuKLhuKKksucdmVjKSgyfMK34oyKw7cpy5zwnZWpfW51bSAjIGNvbnZlcnQgaXQgaW50byBiaXRzCmFucyDihpAgKFNodWbijL4oYml0c+KKuC8pdmVjKSAgICAgICAjIHNodWZmbGUgdmVjIGF0IHBvc2l0aW9ucyBiaXRzCmJpdHPigL9hbnMgICAgICAgICAgICAgICAgICAgICAgICMgc2hvdyB0aGUgYml0cywgYW5kIHRoZSBzaHVmZmxlZCBsaXN0Cg==)): ``` Deal ← •rand.Deal # random permutation of 0..𝕩-1 Rand ← ⊑Deal # random number from 0..𝕩-1 Shuf ← ⊢⊏˜·Deal≠ # random shuffle of list 𝕩 num ← 1+Rand 1-˜2⋆≠ vec # pick a random number from 1..2^len(vec)-1 bits ← {(2⋆⊒˜vec)(2|·⌊÷)˜𝕩}num # convert it into bits ans ← (Shuf⌾(bits⊸/)vec) # shuffle vec at positions given by bits ``` [Answer] # APL+WIN, 31 bytes Prompts for vector of digits. Will also work with a string of characters. ``` v[i]←v[i[(⍴i)?⍴i←(?⍴v)?⍴v←⎕]]⋄v ``` Index origin = 1. Randomly selects the length of the subset from 1 to length. Randomly selects indices corresponding to the length of subset. Randomly shuffles values at those indices. [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf1l0ZiyQB6SiNR71bsnUtAeRQBENEKMMzC0DcoHaYmMfdbeU/Qdq4/qfxmWoYKRgrGCiYMqVxqWemJSckpqWnpGZpQ7kAgA "APL (Dyalog Classic) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ ~~29~~ 27 [bytes](https://github.com/abrudz/SBCS) Requires index origin 0. ``` {⍵[?⍨≢⍵]}@{k∘←?{2}¨⍵}⍣{∨/k} ``` [Try it online!](https://tio.run/##PVBNS8NgDL73V@T2rljZ2s0PvGzgxV3mcLuJh25Ldaxss287lNKLwphl79CB4Hl6KF48iEw8bv8kf6SmRQwhJE@ehDyxx@5u79Z2R5dpGpL6Oq@SSuhhxelFVAsHNHuh6WM1tKJNwlhE6jWkWVIcRKnDDVILWjzXTym@33yUafrEVevsmGP7pN5K8x5wbDaB2VCCfU0rULwyBE2XwnB02AMTLDiAiiaERrNY1Hx5JYQEH6XftSUaotDIh81SZrrwgqE0wEPX9vsTBMfD6wCH3T7KI5EtadsdF/MJFvRjNLbrf0kRzb@dTdIoUnxn7pD6LGt8HFOFhzJwfRh1JHoT7AHejLHrY0/wuaxqvuZH5IuzNyzNDFBvJivJQR0MIPVubddlsMw/P6yw/wI "APL (Dyalog Unicode) – Try It Online") If we would allow the empty subsequence as a random choice, `k∘←` and `⍣{∨/k}` could be removed. **How?** `{k∘←?{2}¨⍵}` Get a random subsequence and store it's binary mask in `k` `{2}¨⍵` A 2 for each value in `⍵`. This could be `2⍨¨⍵` in version 18 and above. `?` For each, draw a random integer in `[0, 2)` / 0 or 1. `k∘←` Store that vector in a global variable named `k` and return it. `{⍵[?⍨≢⍵]}@` Shuffle the selected that subsequence `{ ... }@` Replace the subsequence indicated by 1's in the boolean mask with the return value of the function on the left. `≢⍵` `n` = Length of the subsequence `?⍨` Choose `n` random integers in the interval `[0, n)` (Permutation of `[0,1,2,...,n-1]`). `⍵[ ... ]` Index into the subsequence with the permutation. `⍣{∨/k}` ... until `k` contains at least a single 1. [Answer] # BQN, 19 bytes `{𝕩⊏˜•rand.Deal≠𝕩}⍟≢` Explanation:- `{𝕩⊏˜•rand.Deal≠𝕩}` shuffles array randomly `⍟≢` shuffles it again if (by chance) the shuffled array is equal to the original array [Answer] # JavaScript (ES6), 170 bytes ``` x=>(s=n=>n?(w=(x,i,k)=>[x[i],x[k]]=[x[k],x[i]])(y,--n,o()*n|0)&&s(n):y)((r=_=>(y=[...x.keys()].filter(_=>(o=Math.random)()<.5))+y?y:r())().length).map((k,i)=>w(x,i,k))&&x ``` [Answer] # Python3, 142 bytes: ``` from random import* r=range def f(s):g=sample(r(l:=len(s)),randint(1,l));j=g[:];shuffle(j);return[s[j.pop(0)]if i in g else s[i]for i in r(l)] ``` [Try it online!](https://tio.run/##JYzBCsMgEAXv@QqPbpGSNG0pCX6JeAjENQajsppDv94aenowvJn0LVsM4ydRrUjxYLSEtY07UqRy60g2YE23GmTIM0xW5uVI3nDifpLehAZBXJYLhQ/CA8y7tGrSc95OxPbcYSZTTgoqq/2eYuI9aIfMMReYZcZnw7JyGiP9WUuDromuInI1iIcYxVO8xFsD1B8) [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~197~~ \$\cdots\$ ~~175~~ 174 bytes ``` #import<regex> using V=std::vector<int>;int f(V&v){V i=v,r=v;int y=0,n,j;for(int&a:i)a=y++;std::random_shuffle(&i[0],&*end(i));for(j=n=rand()%y+1;j;)r[i[--j]]=v[i[j%n]];v=r;} ``` [Try it online!](https://tio.run/##1VHBjpswEL3nK0ZUi3Awq@xut@3GOD1Uva16KxeCKmoMaxpMZAxNFvHrTW0TdSNV23st2ZqZ9@bNY2D7fVQxdjq9Ec2@VTpWvOKHzaLvhKwgoZ0u1uuBM92qWEi9IeaBMkj8AY0JCDpgRQdXPNIVlrgmZasCk/v5WqCcHsOQOA2Vy6JtvnVPfVnueOCLdJVhf8llEQiEXFdNJbW0AF0dwxtSE6RSkUZRnWV0MFF9JbOMDFSRydiVbNcXHGLRdlrxvPmH54X11@RCBmhcgDmdG6NFw4MvXx8fzXxXZq3sNLCnXC3Ny9kPrtIMKIze9vD5dnt4@GTuvYfhMr/zprn7cmyyAc073dnm8QbD7YRhvMdgQwzvMby1hTm7MxkGA75zyAcMD9NZ0mwF7DJByIIfjNiKnMN41r/uxDMPEIEwdHUE8wfak4A2HY6WOjAjfzDnlbW9hjgGL/VeEDdyXkTe69YHoRWsQV8q/6VgfqdhUQr@Ul9/55XdNHwEzzOddl3IkgzlZcz0ipUMog1c2gk0@h9se6@Z3MozNC2m0y9W7vKqO0U/fwM "C++ (gcc) – Try It Online") *Added 2 bytes to fix an error.* *Saved ~~3~~ 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a vector of integers. Randomly shuffles a random subgroup of the elements in place. [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Simply shuffles the array randomly and has the possibility to output the original array, which would seem to satisfy the requirements to me. ``` ö¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9qw&input=WzUgMSAyIDQgN10) But, if not, then ... ## [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ... This version interleaves the array with a random permutation of itself, chooses an element at random from each pair, and continues to do so until the result equals the input when both are sorted. ``` @ÍeXÍ}a@íUö¬ mö ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QM1lWM19YUDtVfasIG32&input=WzUgMSAyIDQgN10) ]
[Question] [ ### Background The summary of a non-negative integer \$n\$ is the concatenation of all digits that appear in \$n\$ in increasing order, with each digit being preceded by the number of times it appears in \$n\$. Some Examples: ``` n -> summary(n) 1221 -> 2122 (2 ones, 2 twos) 1212 -> 2122 (2 ones, 2 twos) 912334 -> 1112231419 (1 one, 1 two, 2 threes, 1 four, 1 nine) 888888888888 -> 128 (12 eights) ``` The \$k\$-th order summary is result repeatedly applying the summary operation on a number \$k\$ times (i.e. \$2\$nd order summary of \$n\$ is `summary(summary(n))`, \$3\$rd order summary of \$n\$ is `summary(summary(summary(n)))`, etc.). **Note:** The \$0\$th order summary of a number is itself ### Task Write a program/function that outputs the \$k\$-th order summary of a non-negative integer \$n\$. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins ### Sample Testcases ``` n, k -> answer 0, 1 -> 10 1, 10 -> 41122314 1221, 0 -> 1221 1221, 1 -> 2122 1212, 1 -> 2122 912334, 1 -> 1112231419 912334, 3 -> 412213141519 21322314, 1 -> 21322314 21322314, 123 -> 21322314 21322314, 2222 -> 21322314 888888888888, 1 -> 128 888888888888, 2 -> 111218 1888888888888, 1 -> 11128 ``` --- *Inspired by [A005151](https://oeis.org/A005151)* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` (søeRf∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28s%C3%B8eRf%E2%88%91&inputs=10%0A%271%27&header=&footer=) ``` ( # k times... s # Sort øe # Run length encode R # Reverse each f # Flatten ∑ # Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṢŒrUFVµ¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkVHJxWFuoUd2npo4f///w0tkMB/QwA "Jelly – Try It Online") Credit to hyper-neutrino for the `µ` trick, and for telling me [I was wrong](https://chat.stackexchange.com/transcript/message/59537861#59537861) :P Full program. Takes `n` then `k` on the command line ## How it works ``` ṢŒrUFVµ¡ - Main link. Takes n on the left, k on the right µ - Last links as a monadic chain f(n): Ṣ - Sort the digits of n Œr - Run length encode UF - Reverse each and flatten V - Eval as a single number ¡ - Iterate f(n) k times ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 67 bytes ``` f=(n,k)=>k?f("".join(str(n.count(x))+x for x:sorted(set(n))),k-1):n ``` [Try it online!](https://tio.run/##TctBCoAwDAXRq5Su8rEKuhJBPYxa0EIiaYTevrp01m9uFROuNc7EIWFe0hrJ@@6SkymbEnebPGxUgKa4KOrKlEXt2CkfRgwgpLbHxPXW84PfPv7ywQ1AfQE "Proton – Try It Online") # [Python 3](https://docs.python.org/3/), 78 bytes ``` f=lambda n,k:k and f("".join(str(n.count(x))+x for x in sorted({*n})),k-1)or n ``` [Try it online!](https://tio.run/##bc7BboMwDAbgO09h9dJkC6gOTKKV6LuwUbQM6kQklUDTnp05iFW0mi@J/P1x7KbwaSmf57bq6@t7UwOp7tRBTQ20YrfLvqwh4cMgKPuwNwpilPJ1hNYOMIIh8HYIl0Z8v9CPlKpLUbLQbK6OAfzkkxjtDV2W9OQzHxpDpwS4DDkF9hagWhKZd70JYp@e93JxUtCxceyP1CpuMLxLKzgRL52UUFVxFI8fjBNSzqgAD7Cp9AwFotY5Fgkf7IcHjL0V8AE0NxlQ/wtH1HlebCiOWv/B453zhzX4l8hvHCg3tUxZVimf@vo@F8sEn9@sVP4C "Python 3 – Try It Online") -7 bytes thanks to Mukundan314 [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` ToString@#2<>#&@@@Sort@Tally@Characters@#<>""&~Nest~##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQ/uKQoMy/dQdnIxk5ZzcHBITi/qMQhJDEnp9LBOSOxKDG5JLWo2EHZxk5JSa3OL7W4pE5ZWe1/AFBTSbSyrl2ag4NyrFpdcHJiXl01V7WSoZKOoUGtDohlZATkILMNoWxDIxjb0tDI2NgEnWcM5lkgAZgKVDEjiHnoCrlq/wMA "Wolfram Language (Mathematica) – Try It Online") Input `["n", k]`. [Answer] # JavaScript (ES6), 73 bytes Expects `(k)(n)`, where `n` is given as a string. Returns a string. ``` k=>g=n=>k--?g([...n].sort().join``.replace(/(.)\1*/g,s=>s.length+s[0])):n ``` [Try it online!](https://tio.run/##bY5BTsMwEEX3OcWom9g0ceKkSGmR0xVcoMu2UqPESdMEO8QGgRA3QGLDEu7BeXoBjhCcUpW2Yha29N//f2aTPCQqbctGu0JmvMtZV7G4YILFletOCzQnhIglUbLVCJONLMVqRVre1EnKkYcIXtALr3AUixWpuSj0eqjm/hLjiehafndfthzZubKxCSXZTVnz2ZNIkY@JljPdlqIwtaqpS40GCzHAJJftdZKukQIWw7MFUHMNcxAOVA7wx4anmmewBAaK3CbaOL1FNvQK7BhvPy03UcjRsMJI4CvLyKkUStac1LJABju/HvZXNwX7@@tt@/FuXhsmYG8/X22TfcEddYD6cDRuDCNKgyCkI8t8hvsnsNf2gJ6AwIgG0OBfMKZBGI6OUF@130PHBxyenGG29PjSGKKj2bXsTonO9ODQSyOLnmf2KPoB "JavaScript (Node.js) – Try It Online") ### Commented ``` k => // outer function taking k g = n => // inner recursive function taking n as a string k-- ? // decrement k; if it was not 0: g( // do a recursive call: [...n] // split n into a list of digits .sort() // sort this list in ascending order .join`` // join the digits again .replace( // replace ... /(.)\1*/g, // ... runs of consecutive identical digits ... s => // ... with: s.length + // the number of occurrences s[0] // followed by the digit ) // end of replace() ) // end of recursive call : // else: n // we're done: return n ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` d!¡oṁoṁd§eL←kDd ``` [Try it online!](https://tio.run/##yygtzv7/P0Xx0ML8hzsbQTjl0PJUn0dtE7JdUv7//29ogQT@GwEA "Husk – Try It Online") Order is taken 1-indexed. ## Explanation ``` d!¡oṁoṁd§eL←kDd d digits ¡ apply the following repeatedly and collect results: kD group digits into lists ṁ map each list and join: §e two element list with: L length ← first element oṁd convert each to individual digits ! index into that using order d convert back to integer. ``` [Answer] # [R](https://www.r-project.org/), 94 bytes Or **[R](https://www.r-project.org/)>=4.1, 87 bytes** by replacing the word `function` with `\`. ``` function(n,k){while(k<-k-1)n=Reduce(paste0,c(rbind(r<-table(el(strsplit(n,""))),names(r))));n} ``` [Try it online!](https://tio.run/##fc7dCoIwFAfw@55C1s1GG3g2AyXtIXoDPyaJtmROuoie3TYTNJPO1YH/73zooUyGsle5qe4KK1qT5@NaNRLXMasZEJVcZNHnErdpZ6RPc6yzShVYx8ykmXWywZ3RXdtUxo4jRAihKr3JDmvbkpN6DSVGAJwjKsjO9Yh64B@A7L1FsbMXOCUgGBHnzq2YRS5YAPgB3CYfAPwviIALEayJOzH9AdEXEysWuBccO35guKh56/hyuJHzObf3YCSwuWMi4fAG "R – Try It Online") Expects `n` as a string and `k` 1-indexed. Outputs a string. Creates `table` of digits and interleaves resulting values (counts) with their names (digits) using [this trick from SO](https://stackoverflow.com/a/25961969/6713210). The rest is just string manipulation which is quite cumbersome in R. --- Recursive approach results in the same byte-count: ### [R](https://www.r-project.org/), 94 bytes Or **[R](https://www.r-project.org/)>=4.1, 87 bytes** by replacing the word `function` with `\`. ``` f=function(n,k)"if"(k,f(Reduce(paste0,c(rbind(r<-table(el(strsplit(n,""))),names(r)))),k-1),n) ``` [Try it online!](https://tio.run/##fY7bCoMwDIbv9xTS3aRQwUQHCtseYm/goQXRddLW53etB9Ahy1XI9yV/zDSphxp17dqPBi06zlrFoBMKXrIZawlDaZ1MRA2manUD5h67suolyB6sM3boW@f3GOOcC12@pQXDQ9/F6Ad8UsAQiZggfgk9ExEm/BrtKn5GWXBSzGaFKFgHySthvMP4g8nPF4z0BxdIaZodhXB8zcfiIKUHKQvRQbotWr6r7eL8aH5CaaM@CWcBT/ZXIZ@@ "R – Try It Online") Here `k` is 0-indexed. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes ``` 1A` "$+"{O`. (.)\1* $.&$1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/39AxgUtJRVup2j9Bj0tDTzPGUItLRU9NBShlzGVpaGRsbAIA "Retina – Try It Online") Takes input in the order `k, n`. No test suite due to the program's use of history. Explanation: ``` 1A` ``` Delete `k` from the input. ``` "$+"{` ``` Retrieve `k` from the history and repeat the rest of the program `k` times. ``` O`. ``` Sort the digits in ascending order. ``` (.)\1* $.&$1 ``` Precede each distinct digit by its count. The best I could do in # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) is 45 bytes: ``` ,\d+ $*_ {O`.(?=.*_) (\d)\1*(?=.*_) $.&$1 _$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXycmRZtLRSueq9o/QU/D3lZPK16TSyMmRTPGUAvGVdFTUzHkilfh@v/fUMfQgMvQyMhQB0oZAilDIyBlaWhkbGyCYBhzWSABoDgK14jLEFUaAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ,\d+ $*_ ``` Convert `k` to unary, using `_` because they sort after digits, saving a byte. ``` {` ``` Repeat (until `k` is zero, at which point the loop converges). ``` O`.(?=.*_) ``` If `k` is not zero, sort the digits in ascending order. (If `k>1`, `k` is also sorted, but it always sorts after digits.) ``` (\d)\1*(?=.*_) $.&$1 ``` If `k` is not zero, precede each distinct digit by its count. ``` _$ ``` If `k` is not zero, then decrement `k`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74~~ 66 bytes ``` ->n,k{k.times{a=n.chars n=(a|a).sort.map{|d|[a.count(d),d]}*''} n} ``` [Try it online!](https://tio.run/##bZBdT4MwFIbv@yuO7IKhXbcCJsykeOWtej8XUqHLCK4QWhIN9LdjmWyBxXPRk7zP6Xs@6ubzpz@wfhVLXLQF0flJqJYzSdIjrxWSbMk77hFV1pqceNV2WbfjJC0bqZeZh7O9uXddg6TptVA6UU2ugYFDMdANTGIVQ0ip7wc0RDZZvpnBQRsBnQHfihZQ/1@wpX4QhBM0WI196PaKg9kYtsuAH21BNImzy3mU6Eb3r740QvT2z4gihwieHpOvXIq2G94Ogb0qFt@VSLXIGAwiUSmXy/VH9rD2ENRC2XMddiABgz1/meSwRxU4i1YaDIu2MMBim22h@UvAGFws4RncsnDhCdzXt/eXO9c4CBnUT3f8BQ "Ruby – Try It Online") * Thanks to @ovs for actually golfing thus saving 8 Bytes! .uniq => a|a and join by \*'' instead of appending values * takes *n* as string, *k* as int * reconstruct *n* by appending each (count,digit) *k* times * uses a=n.split n='' instead of a,n=n.chars,'' which is the same byte count [Answer] # [Raku](http://raku.org/), 44 bytes ``` {($^a,{[R~] .comb.Bag{~9...0}:kv}...*)[$^k]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlLlGnOjqoLlZBLzk/N0nPKTG9us5ST0/PoNYqu6wWyNDSjFaJy46t/V@cWKmgVO2gEl@rYGunUJ2mUANkKimk5Rcp2BgqGBrY6QBpIyNDBQTLEMIyNIKwLA2NjI1NUNjGILaRobGRkbEhVAbBMwLLWiABiAoUESOwHWiK/gMA "Perl 6 – Try It Online") * `($^a, { ... } ... *)[$^k]` selects the `$^k`-th element of the infinite sequence starting with `$^a`, where `$^a` and `$^k` are the first and second arguments to the function, respectively. The bracketed expression is an anonymous function that generates each summary number from the previous one, passed as `$_`. * `.comb` splits the number `$_` into its (string) digits. * `.Bag` assembles those digits into a Bag--a set with multiplicity. * `{~9...0}` slices into that bag with the digits from 9 to 0. The leading `~` stringifies the `9` and gives us a sequence of strings, not numbers. (The Bag knows the difference.) * The `:kv` adverb on the slicing subscript `{...}` does two things: it returns a flat list of key-value pairs (ie, each digit along with its multiplicity, in order from 9 to 0), and it omits elements from the slice which don't exist in the Bag. * `[R~]` reduces that list with the operator `R~`, which is the `R`eversed string concatenation operator `~`. That gives us the required summary of the previous number in the series. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F{Åγøí˜J ``` -1 byte thanks to a tip of *@ovs* Inputs in the order \$k,n\$. Outputs as a digit-list (unless \$k=0\$, in which case it outputs \$n\$ as is - although we could take input \$n\$ as digit-list as well to be consistent). [Try it online](https://tio.run/##yy9OTMpM/f/frfpw67nNh3ccXhv8/7@hAZchAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf7fqw63nNh/ecXht8P/aw@t1/kdHG@gYxupEG@oYGoAoIyNDHTgDLGFkaARmWBoaGRubIDONgUwjQ2MjI2NDiDiCY4QiZwQEQL4FEgCrRxEAqTBEUxILAA). **Explanation:** ``` F # Loop the first (implicit) input amount of times: { # Sort the digits of the current number # (which is the second implicit input-integer in the first iteration) Åγ # Pop and run-length encode, pushing a list of digits and a list of lengths # separated to the stack ø # Create pairs of these two lists í # Reverse each pair S # Convert the list of integer-pairs to a flattened list of digits # (after which the result is output implicitly) ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 73 bytes ``` param($n,$k)for(;$k--){$n=-join("$n"|% t*y|group|%{$_.Count,$_.Name})} $n ``` [Try it online!](https://tio.run/##fVJfS8MwEH/vpwgjk1ZaWdIKG2MwGPoiTHGPIqPW1LluSU1aVNp@9npp6lq26ZHC3e/P3YU0FZ9Mqg3b7bxISFbjeFbUaSjDvY25ixMnFtKe4sTznALzmbcV79weYD4ohyi7/C7fpMjTcljg9dVC5DxzIVmGe1Y5lYV5XVnW3LYQhIvm9shFBM7IOSBN6aKAEEp9EvQISoHTBkiOYTgUsj5M6Bl4QqjvB2ZoO4FMTmlfLwCNNX3dFwDUmNrW/tGOPZr6/wsoxDnFuBdmTzr@i6XmFqQnIKd@0nRwUIluhbwJo413/7JlUYaKxgWPinACH/tKAWWvaIbw2lCSqXyXAXCBYxCCzuAqjyKmlFa2Eo99dB0a0dPDapGrTOzNtOe5Gadj1dnbTtMDt9Qo7@o7XSdd/fi7UjvZMJUF/1X9Aw "PowerShell Core – Try It Online") Same byte count using `$ofs`: [Try it online!](https://tio.run/##fVJda4MwFH33V4SSrjp0NNFBSxEKZXsZdGN9HKM4F9fVNnFR2Yb6292NcVXabpcIuefjniuaiE8m0w3b7ZxQSFbjyC/qJJDB3sTcxrEVCWliEaX@aDTDseNYBeb@APNBOUTZ5Xf5JkWelMMCr68WIueZDZdlsGdVZWBeV4YxNw0EZaO5ObYRgTO2DkjT2sgjhFKXeD2CUuCUAS7HMBwKtz5M6Bl4Sqjrejq0TSDTU9pVC8BgRV/3BQA1pna0e7Rjj6bu/wIKdU4x6ZXek07@Yql@C9ITkFM/aSZYqES3Qt4E4ca5f9myMENF44KPinAMD/tKAGWvyEd4rSnJ0nyXAeBsxTs3L3AEclDrPJzmYcjSVBlapcM@ukGN6OlhtcjTTOx16PNcp6padfZ20uzALRXKu/5O9XHXP/5u1iZrpjLg96p/AA "PowerShell Core – Try It Online") Takes two integer parameters and returns a string or an integer [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` FN≔⭆Φ⭆χκ№ηκ⁺№ηκκηη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTwbG4ODM9TyO4pCgzL903sUDDLTOnBCiFEDA00FHI1tRRcM4vzSvRyABxgLyAnNJiDSQhqHCGpjVXAFAnUFTT@v9/Yy5LQyNjY5P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `k, n`. Explanation: ``` FN ``` Input `k` and loop that many times. ``` ≔⭆Φ⭆χκ№ηκ⁺№ηκκη ``` Filter the characters `0-9` that are present in `n`, prefixing them with their count and joining the result. ``` η ``` Output the final value of `n`. [Answer] # Excel (Insider Beta), 108 bytes ``` =LAMBDA(q,k,IF(k,LET(a,f(q,k-1),x,SEQUENCE(10)-1,y,LEN(a)-LEN(SUBSTITUTE(a,x,"")),CONCAT(FILTER(y&x,y))),q)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnVfgN6n5ytPTEHau?e=cAAsE5) Set name f equal to the above formula. Spreadsheet requires Insider Beta version of Excel to work currently because of LAMBDA. ### Explanation ``` =LAMBDA(q,k, IF(k, # if k <> 0 then LET(a,f(q,k-1), # a = f(q,k-1) x,SEQUENCE(10)-1, # x = [0..9] y,LEN(a)-LEN(SUBSTITUTE(a,x,"")), # y = count of each x in a CONCAT(FILTER(y&x,y))) # concatenate y&x if y > 0 ,q)) # else q ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 354 bytes ``` mod R is pr LIST{Nat}+ CONVERSION . ops k s : Nat Nat ~> Nat . op f : Nat ~> String . var N K : Nat . var X Y :[Nat]. eq k(N,0)= N . eq k(N,s K)= k(rat(f(s(N,0 0 0 0 0 0 0 0 0 0)),10),K). eq s(0,X)= X . ceq s(N,X K Y)= s(N quo 10,X(s K)Y)if size(X)= N rem 10[owise]. eq f(nil)= "" . eq f(X 0)= f(X). eq f(X s N)= f(X)+ string(10 * s N + size(X),10). endm ``` The result is obtained by reducing the `k` function with \$n\$ and \$k\$. ### Example Session ``` Maude> red k(1, 10) . --- Expected: 41122314 result NzNat: 41122314 Maude> red k(1221, 0) . --- Expected: 1221 result NzNat: 1221 Maude> red k(1221, 1) . --- Expected: 2122 result NzNat: 2122 Maude> red k(1212, 1) . --- Expected: 2122 result NzNat: 2122 Maude> red k(912334, 1) . --- Expected: 1112231419 result NzNat: 1112231419 Maude> red k(912334, 3) . --- Expected: 412213141519 result NzNat: 412213141519 Maude> red k(21322314, 1) . --- Expected: 21322314 result NzNat: 21322314 Maude> red k(21322314, 123) . --- Expected: 21322314 result NzNat: 21322314 Maude> red k(21322314, 2222) . --- Expected: 21322314 result NzNat: 21322314 Maude> red k(888888888888, 1) . --- Expected: 128 result NzNat: 128 Maude> red k(888888888888, 2) . --- Expected: 111218 result NzNat: 111218 Maude> red k(1888888888888, 1) . --- Expected: 11128 result NzNat: 11128 ``` ### Ungolfed ``` mod R is pr LIST{Nat} + CONVERSION . ops k s : Nat Nat ~> Nat . op f : Nat ~> String . var N K : Nat . var X Y : [Nat] . eq k(N, 0) = N . eq k(N, s K) = k(rat(f(s(N, 0 0 0 0 0 0 0 0 0 0)), 10), K) . eq s(0, X) = X . ceq s(N, X K Y) = s(N quo 10, X (s K) Y) if size(X) = N rem 10 [owise] . eq f(nil) = "" . eq f(X 0) = f(X) . eq f(X s N) = f(X) + string(10 * s N + size(X), 10) . endm ``` Maude doesn't have logarithms for integers, only for floating-point numbers, so the only good way I could find to "concatenate" integers is to convert them to strings, concatenate, and convert back. # Core Maude + Cheating, 331 bytes ``` mod R is pr CONVERSION . ops k s : Nat Nat -> Nat . op f : Nat Nat -> String . var N K S : Nat . eq k(N,0)= N . eq k(N,s K)= k(rat(f(0,s(N,0)),10),K). eq s(0,S)= S . eq s(N,S)= s(N quo 10,S + 512 ^(N rem 10))[owise]. eq f(10,S)= "" . eq f(N,S)= if(S & 511)> 0 then string(10 *(S & 511)+ N,10)else "" fi + f(s N,S >> 9)[owise]. endm ``` ### Ungolfed ``` mod R is pr CONVERSION . ops k s : Nat Nat -> Nat . op f : Nat Nat -> String . var N K S : Nat . eq k(N, 0) = N . eq k(N, s K) = k(rat(f(0, s(N, 0)), 10), K) . eq s(0, S) = S . eq s(N, S) = s(N quo 10, S + 512 ^ (N rem 10)) [owise] . eq f(10, S) = "" . eq f(N, S) = if (S & 511) > 0 then string(10 * (S & 511) + N, 10) else "" fi + f(s N, S >> 9) [owise] . endm ``` If we make the small assumption that no digit occurs more than 511 times, we can avoid having to import `LIST` and keep the intermediate summary packed in an integer with 9 bits per digit tracked. The bit size is sort of arbitrary since Maude has unbounded integers, so I picked 9 bits to avoid paying 4 extra bytes for `10` and `1024`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~112~~ \$\cdots\$ ~~123~~ 125 bytes ``` f(n,k){int c[10]={!n},t=n,i=-1,l;for(;t;t/=10)++c[t%10];for(;i++<9;t=l?i+l*10+t*exp10(l=log10(l)+2):t)l=c[i];n=k?f(t,k-1):n;} ``` [Try it online!](https://tio.run/##bVHdaoMwFL7fU2RCIZpIjXYXNs16MfYUVkZJYyexadHAZOKrzx1rLO2YHI/6/SU5yvAo5TAU2FDtd6WxSGYsykX3bHpqhaGlCBmteHGuMbfcLgWLfEJkZhcgm@CSkE3Krai2JakCFhEbqPbCIlyJ6nwcnz6J/bX1KyGzMudG6G2BLdUh89eG98O47GlfGuyj7gnBNQJWNfbDZDkSqIsoYlBxfNdZTFHK4iRZ9fzRpCfTqAKj80Ld6WB/Slp1cErQrBgEJ2w1LwD58dyZ41jqIuTnvg6gK6lVPWV4u/Y93rXpG9wvHkX334nnfDAuhMf1S3NQLdgi7l43qCm/1bnA8878pQOCG8IRIVf1PKb5NAaS3LiufM4faD3T@l@6AXr6/4@4Avw2p7/GSw2SAnuLA4IKX8e@aHYGTm4o0hQ19DafRgiVu/D@qR9@ZFHtj80Qfg1hdfoF "C (gcc) – Try It Online") *Saved ~~a~~ 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* *Added 21 bytes to fix an error kindly pointed out by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).* *Saved 8 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!* *Added 2 bytes to handle \$n=0\$.* [Answer] # [Perl 5](https://www.perl.org/), 72 bytes ``` sub g{($c,$d)=@_;$c=join"",map{(@e=$c=~/$_/g)?@e.$_:""}0..9for 1..$d;$c} ``` [Try it online!](https://tio.run/##fVHda8IwEH/3rzhCxARi7aUWrNJZXwaDPQx8dEWcrcXhZ1sZQ9y/3l2Cc@t0u5ckv6@7cLs0X/lVVRxeIDsKPlc8kWE0HfB5@LpdbhhT69nuKKI0JOSjw6edTA6j1OHTPmMn13GCxTYHdByekOdUrd8hSmblDEIQDaCa7N@ECwjoylhdEPOGLqLWHnZrhNYIpKfjCkbQdNZh1DfgALXndU3TcwcMbtAeDUCxhvbrAgKtzUZ7VzN@09r7X6Cpbip6P8rMqXt/str@AmsC/O3Hc4IcNMw@aAu8TIsShF2GhKO1GjhPi8OqpPVkwkradxM3VvB1x5gijHaXLzflQrBMNNvoFwqabb@Q5LPPPjSL5w1TEFmjuuSm@0uUjmEIrafReNyCPrD70cMjiLNOMmpzqj4B "Perl 5 – Try It Online") Ungolfed: ``` sub g{ ($c, $d) = @_; for (1 .. $d) { $c = join('', map {(@e = $c =~ /$_/g) ? @e . $_ : ""} 0 .. 9); } $c; } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~121 125 117~~ 116 bytes ``` E=10,r,c,t,i;g(n,k){for(;k--;n=n?r:E)for(r=i=0;i<E;r=c?r*E*E+c*E+i:r,i++)for(c=0,t=n;t;t/=E)r*=t%E-i||++c%E?:E;r=n;} ``` [Try it online!](https://tio.run/##ldLdaoMwFAfwe59CCoLRiDmJA2sWvMpb7GZktITSbITsqu2zu8SP6bbQsgNeJP@fJ8cPVR2VGgYpgGCLFXZY82Nu8AldDu8256eq4kaY3nYShQ0rtCBcP0tuheptIQtZKn/pzmJdlqNRgmAnDHfc1UIiWwiXyUpfr2WpMtl34V7Db8P5VZscXZL0w2rjDvkue3sxO3zMCU4JQryuUxINYQohntIlBYjmbMlZJAdK4fv0sPhL0snMQ1C/ihqg3qRR9DmjPVDGmpUBeMeggf0dPI/fhCmCffqhl/N9NrbazjDt3MeU/YdTXw95u6kwzvKwtH2I6fpeIKbhV@@Vt/HvttS2NaHjvwA0SW7DFw "C (gcc) – Try It Online") * Saved 1 thanks to @ceilingcat * Fixed: now works with n=0 , k>0 as required. [Try it uint64\_t](https://tio.run/##lZJdT8IwFIbv9yuaGZJ9dNLTTQKUylUvvDNcmxhTYDZoJbW7MMBvnx0wmNhIPEmTnvM@5/RtN5mVUtY3Ssu3ar5AE6Wt/VovPm9f7@vKJYPi2SLBgWCDJbZYseBULqPTVmO3Q6t4s/wwEVtlGdNcT81YxE3BcMUJUxPBDJdTk4hEpNItNTZYpemekZxgyzWzzPa5iE3CbU9kartNU9kTUxg3zZrt6vcXpaN4E6C1cWcuo7A3f9IhLiOCEYlj1u8j4hXhIIJfpa0K4NXzVs89OlAKp9Ob5DeCDszRBHWZlwHqGOSFqiM0AprnxRkDcFwOBYw6cPg4e6gGRXjRc7xF0ZhpWu5@NLU2nLaf2LVyqPwN0/w/OHVxFR92orHT3pkOr8L0/Dzgo@Fi9hkf@j9fG93RhO5/CaBBsKu/AQ "C (gcc) – Try It Online") [Answer] # [Lua](https://www.lua.org/), 112 bytes Chunk function (can be executed using `loadstring(code)("42",0)`). Expects `n` as a string and `k` as either number or string. Doesn't play well with TIO; replace the `return n` with `print(n)` to test. ``` n,k=...for _=1,k do m=""for j=1,9 do c=""..#n:gsub("[^"..j.."]","")m=m..(c>"0"and c..j or"")end n=m end return n ``` [Try it online!](https://tio.run/##FYnRCsIwEAR/5ThfWghLfVPh@iOiUtNWaJsLRPP952Vflpk56mSmYRcAay70knPYac6UhLmJzcW1iegCOOnt863vju9Ppw3gBwfmPkkCujjywJPOFL1RLh4WJ5VE7cvyq0VJzezSZsMf "Lua – Try It Online") ]
[Question] [ This is based off [this](https://codegolf.stackexchange.com/questions/203893/bl-lu-ur-rr-ry-yv-vi-is-si-io-on-blur-the-text/) challenge. Given an input string, check whether the string is blurry. ## What's a blurry string? A blurry string is a string that's contained in the set of all blurrified pure-ASCII strings. Take a non-blurrified pure-ASCII string `abc` as an example. You repeat every character of this twice: ``` aabbcc ``` And then insert spaces at every odd-even index. ``` a ab bc c ``` Then, remove the preceding 2 and succeeding 2 extra characters. If there isn't enough space left, ignore the abundant removing instructions. ``` ab bc ``` As an example, all of these strings are blurry (the empty line stands for an empty string): ``` Before After "a" -> "ab" ->ab "abc" ->ab bc "abcd"->ab bc cd ... (Before = the string before blurrification) (After = the string after blurrification, i.e. the strings in the set of all blurry strings.) ``` ## Specification * The input string consists purely of printable ASCII characters. The only whitespace it will contain is the space character. * You don't have to remove extra characters before the check. * Your output can consist of any trailing whitespace, as long as it's possible to tell a truthy result from a falsy result. * It's noteworthy that the definition of "blurry" in this challenge is **different** than the previous challenge. ## Test cases [Here](https://tio.run/##yy9OTMpM/a@kxKWUmAQmFJKSYbRCcgqQqYBgQkUVlLiAbDAfqhYkDFOinJSsDGUmJUMYCkjGATlgrgLIuqREheQkhZRkCBOoBMx0c0tMzMkpLk5NVeLS5Dq39f@hZYdWGB/ecm6r0bmdCcWHu4sPbwhUqz08/3/tfwA) is a program I use to check my test cases. ``` "" -> True "ab" -> True "ab bc" -> True "aa aa" -> True "ab bc cd" -> True " b bc cd" -> True "ab bc c " -> True "a c cd" -> True " " -> True "a" -> False "abc" -> False "ab bc cd"-> False "ab#bc#cd" -> False "abbccd" -> False "a ab bc cd"-> False "a a ab b b"-> False "ba cb dc" -> False "ba bc dc" -> False "FFaallssee"-> False "a aa a" -> False ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 14 bytes ``` a`.((.) \2)*.| ``` [Try it online!](https://tio.run/##PYxBCsJADEX3OcWHUpiKDOghegG3LvqTzqJQXFiX3n1MOq3hQ16SR97ls7x4q316TNfKKaeUBzzvwyV/axWqB2pCgmwMmwUnHBsIAbTTURK6hRBGczu1bge1aPj/c9wHqChhitkC/OgwjuS6blsp4Xl@ "Retina – Try It Online") # Explanation `a` forces the match to be on the entire string `.((.) \2)*.` just means any character (`.`) followed by a captured group repeated 0 to many times (`(...)*`) of any character saved into a second captured group (`(.)`) followed by a space and the same character that was matched in the second capture group (`\2`). The final `.` just matches the last character `|` allows the empty string to match by having an alternative match of the empty string [Answer] # [Python 3](https://docs.python.org/3/), ~~60~~ 54 bytes -6 bytes thanks to Surculose Sputum! ``` a,*b,c=input()or'ab' while b:x,y,z,*b=b;x[x!=z][y>' '] ``` [Try it online!](https://tio.run/##TY1Ba8MwDIXv/hUaPTgdue2WkR4GzXG77FZ6kBRBQ0McVIfZ/fOpnaRlRqAnve/JY/QXN3zM7FqprbUzlu9Uct0N4@SLvVOLZM3fpesFqAplLO8JqOkznMJbfT@f4sGCPc8pajbsVyepDIDXmBuABOEif7BfxlG7wRf2q59Uo807CSyjh@NPc1R1uqZIBa8vs/of/XYeaIvPBikVEBtEQFw1cGvgKbYNGEwnVmt7JuOcgUys7I54twji3OB1L8llADKEwAQtZ5HMJJoGse9vN5HMpXoA "Python 3 – Try It Online") Output is via exit code. By using different sets of errors for truthy/falsy inputs this can be [52 bytes](https://tio.run/##fYw9a8QwDIZ3/wqVG5yUbN1S0qFwgS7XpXQ5bpAUwYW6cfA51L4/n9pJ@rXUCPRIevyO0Z/tcDez7aTRWs9Y3VLFTT@Mky9K6yCoj3NvBKgOVayu6dzQfTiGm@Z6OsYHDfo0p49q017cJLUC8C7mBiBBuMjx5TKOrh98oR/N5FzUeSeBZfRwwHfZO2dd/b@3f25/aeQE336OxSuaaY2p4GnoJCxc/sk8WA@05c4KKRUQK0RAXBm4U/AF2wYUpoj1tD2Vdc5CNlZ3R7xbgDg3@M5LuAxAihCYoOMM6ZigbRGNuVxEspfqEw), as suggested by Surculose Sputum. [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda x:x==''.join(c+' '+c for c in x[::3]+x[-1:])[2:-2] ``` [Try it online!](https://tio.run/##rZFNboMwEIX3PsVoosggRNSmO0t0yQmyIyzGxqhEFBCmEj09tQklOGXZJ6@@@Xmeme57@Gib81Qm16mmT1kQjGJMEs5Pt7ZqAhVx4JGCsu1BQdXAmAnxlkdjFr@KPMzOIj7n09B/6Ys2g4EE0AlWxe9wsVGGJHGHgVT4xAiIcCcPVIEbBjtsyQOP2UZ/ahc9mP0zYyXVxpuDcDtH6sLOROEOBGftfLbwINXh13qFUs3Ig7CO6MEZg9xASaAkFMrraaEtfoJpSlTXxmjt97TPc7@Pbu9bufuupzyZrq6GgF8bHgoG0FE/76VaArYphpbrUasAu75qBiiDownxOKdmL3nI2J1jsmjr9Nj2f1hNPw "Python 2 – Try It Online") Uses the same approach as my [Pyth answer](https://codegolf.stackexchange.com/a/204259/65425). The blurring portion of the code is based off of [@Surculose Sputum's answer](https://codegolf.stackexchange.com/a/203895/65425) to the original "Blur a string" challenge. [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` _#""=1<2 p#(' ':x:y:s)|p==x=y#s _#_=2<1 f""=1<2 f(x:y:s)=y#s f _=2<1 ``` [Try it online!](https://tio.run/##XZBPa8MgGMbv@RQPemgCo9AeQ73s0OPYvYzwaswmc0nQtDSw754ZY0M6Efm9j@@fR7/If2trp6nijInD6Zj1PN9hV97LsfTFby/EXYzcZxWvxPF0yJqU1uRLRrxsEC@nHzItBOouA6weYPyrvTo3Bq1JUkPW6zf9SYO56Vk3dtAOedsN2K8FBS6MvYCRXE5IFYFAtCpQ9czYcNIRGcCakxb72Np477x5trEavrA0R6W2c991CJeKP1iqRNiaClGMER8gCUqiVolD1sLnM5G13mudasKOFntn2n9/9aw@rAfV6eHqWuRF4OkP "Haskell – Try It Online") ## Explanation `f` is the entry point. No real tricks; loop through recursively ensuring that every third character is a space, while keeping track of the second character of the previous chunk each time and ensuring that it's equal to the first of the next chunk. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` qjd.:+%3Q>1Q2 ``` [Try it online!](https://tio.run/##K6gsyfj/vzArRc9KW9U40M4w0Oj/f6XEJIWkZIXkFCUA "Pyth – Try It Online") ``` qjd.:+%3Q>1Q2 %3Q Take every 3rd character of the input string (eg. "ab bc cd" becomes "abc") + >1Q Append the last character of the input string jd.: 2 "Blur" the resulting string (ie. find all substrings of length 2 and join on spaces) q Return true if that matches the input string ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~13~~ 12 bytes ``` ¤º«3ô€нüJðýQ ``` [Try it online!](https://tio.run/##yy9OTMpM/V9Wqa6kd3iHvZKCrp2Ckn2ly/9DSw7tOrTa@PCWR01rLuw9vMfr8IbDewP/6/yPVlLSUUpMAhMKSckgOlEhMRHGV0hOATIVEEyoqAKIqaCgAFMABUo6CkoQvckQtSDFMI3KScnKUGZSMoShgGQJkAPmKoAck5SokJykkJIMYQKVgJlubomJOTnFxampEPVApBQLAA) Uses the blurring program [here](https://codegolf.stackexchange.com/a/203906/78850) to re-blur the string. -1 byte thanks to Kevin Cruijssen! ## Old Answer Explained ``` 3ô`©)€н`®θJüJðýQ 3ô # Split the input into chunks of 3 `© # Item split the above and store the last item in the register ) # Wrap everything back into a list €н # Get the first character from each item in then above list ` # Item split the list generated from the above map ®θJ # Join the above with the last letter from the register üJðý # Blatant port of https://codegolf.stackexchange.com/a/203906/78850 -- i.e. blur the string Q # Check to see if the blurred string is the input ``` [Answer] # [Perl 5](https://www.perl.org/) with `-plF/^(.((.)\x20\3)*.|)$/`, 7 bytes ``` $_=@F^1 ``` [Try it online!](https://tio.run/##PYzPCsIwDIfveYrAdmgFO//gUfDUpxiTJOtBKG5YDx58dmuzTsMP8iX5yBwe8ZRzez1f/LDPGYhLkAWIkKgyygj4g3WDQIhYT2uB6qKCGtVtWJoFWLTh/1/BZUAGJhTGURTKsYD3RDGmFIJ6JZ9pft6me8rbOfpuMM4YZ/vXYdcf7ca9bdt9AQ "Perl 5 – Try It Online") ### Explanation Continuing the theme of abusing `-F`, I ended up with the same expression used in the Retina answer. The `-F` argument splits the input string on the valid expression and will place an even number of elements in `@F`, if the regular expression doesn't match, `@F` will just contain one entry, the whole string. When numeric operators are applied to a list (`@F` in this case) the length is implicitly used, so we XOR with 1 to give `0` for the failing test cases and a positive integer for all others. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 21 bytes ``` ⁼✂θ¹±¹¦¹⭆✂θ¹±¹¦³⁺⁺ι ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1gjOCczOVWjUEfBUEfBLzU9sSRVw1ATyAPi4BKgwnTfxAJcioyBOCCntFgDTGTqKCgpKAGFMjVBwPr//0QFBYVkheQUrv@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, `-` for a blurry string, nothing if not. Explanation: ``` θ Input string ✂ ¹±¹¦¹ Slice off the first and last characters ⁼ Is equal to θ Input string ✂ ¹±¹¦³ Every other third character ⭆ Map over characters and join ⁺⁺ι ι Wrap a space in that character Implicitly print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) The empty string being truthy cost a couple of bytes :\ ``` ¶¬ë3 pUÌ ä+ ¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=tqzrMyBwVcwg5CsguA&footer=V2dWIPpBICsiID0gIitV&input=WyIiLCAiYWIiLCAiYWIgYmMiLCAiYWEgYWEiLCAiYWIgYmMgY2QiLCAiIGIgYmMgY2QiLCAiYWIgYmMgYyAiLCAiYSAgIGMgY2QiLCAiICAgICAgICAiLCAiYSIsICJhYmMiLCAiYWIgIGJjICBjZCIsICJhYiNiYyNjZCIsICJhYmJjY2QiLCAiYSBhYiBiYyBjZCIsICJhIGEgYWIgYiBiIiwgImJhIGNiIGRjIiwgImJhIGJjIGRjIiwgIkZGYWFsbHNzZWUiLCAiYSBhYSBhIl0KLW1S) (includes all test cases) ``` ¶¬ë3 pUÌ ä+ ¸ :Implicit input of string U ¶ :Test for equality with ¬ :Split to an array ë3 :Take every 3rd element, starting with the first p :Push UÌ : Last character of U ä+ :Consecutive pairs, reduced by concatenation ¸ :Join with spaces ``` [Answer] # [Red](http://www.red-lang.org), ~~52~~ 51 bytes ``` func[a][s:[skip]parse a[opt[s any[copy t s" "t]s]]] ``` [Try it online!](https://tio.run/##XZAxDsIwDEX3nuIrzAwwdmDkAKxWBsdJBaK0UR2Gnr4EaNqCFSV@tn@U/CH46RI82aqpMTXPTogtaU16v0UbedAApj4mUnA3kvRxRIIamGTVWjs1/RBYrkhBE6hCDmO@B7slgZOSM5i3dYifEb84d1Ewb9vhOUp3Eckqf@u39@2c7DboZAX8vSUXPiWUPziGOHhZMY8veD4zt61qCKs@L1NZisOty85E9nj0rf8adTjC7E@m@VB28QU "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` m3żḊ$K⁼Ṗ ``` A monadic Link accepting a list of characters which yields `1` (blurry), or `0` (not blurry). **[Try it online!](https://tio.run/##y0rNyan8/z/X@Oiehzu6VLwfNe55uHPa////lRIVFBSSFZJTlAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/X@Oiehzu6VLwfNe55uHPa/6N7Drc/alrjDcSR//9HKylx6SglJkFIhaRkMCNRITERLqKQnAJiKyCxoeIKYLaCggJcDRSAxSEKk6HqQRrgupWTkpVh7KRkKEsB2TYgD8xXALssKVEhOUkhJRnKBqqCsN3cEhNzcoqLU1OheoBIiSsWAA "Jelly – Try It Online"). ### How? ``` m3żḊ$K⁼Ṗ - Link: list of characters, S m3 - modulo-3-slice (S) $ - last two links as a monad (f(X)): Ḋ - remove the head (X) ż - zip together (X and that) K - join with spaces Ṗ - remove the tail (S) ⁼ - equal? ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 29 bytes ``` s=>/^.((.) \2)*.$|^$/.test(s) ``` [Try it online!](https://tio.run/##PY5BC4MwDIXv/RUBPbSba2HXsR39FUNMY5WNYsXITvvvLtVt8CBf3gvhPfGFTPNjWk5j6sLaX1e@3lxjtbYG7mdzsOW7KZ1dAi@azXqBVqEXgSeFCIg7A3UKfvB1QCEA7I54lP0c7CeFp2IDT3nA/43gtoBXHoE8dJRBQoG6RoyROYR8J1KtncMUkYJ29uiGSvpTGjnFYGMaNFfQS3Fj1g8 "JavaScript (Node.js) – Try It Online") Pure port ]
[Question] [ Create a program that generates a drum fill. Your program will output a pattern of `L` (left hand hits), 'R' (right hand hits), and `K` for kick drum hits. ## Rules * The pattern must never have more than 2 of the same hits consecutively. * The pattern must be loopable, so it mustn't have more than 2 of the same hits when it loops. * Your program accepts 1 argument which is the length of the pattern. You can assume this will always be an integer > 1. * Program output must be random each time it's ran. It should be properly random each time, so that every combination is possible, so for an input of 2 for example: LR, LK, RL, RK, KL, KR all have a chance of being generated. * IO can be used with any convenient method. * Standard loopholes are forbidden. * This is code-golf, so smallest program wins! **Example valid output:** ``` RLRRKKLL LRLLKKLR LKKRLRKLRRKL LRLR ``` **Example invalid output:** ``` LRLL // 3 characters when looped LRLRRRLLR // 3 characters in a row RRLRLLRR // 4 characters when looped ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “LRK”ṗ;`E3Ƥ$ÐṂX ``` A monadic Link accepting an integer which yields a list of characters. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4oCcTFJL4oCd4bmXO2BFM8akJMOQ4bmCWP///zQ "Jelly – Try It Online")** ### How? Pretty similar to [Nick Kennedy's](https://codegolf.stackexchange.com/a/197748/53748) Jelly answer... ``` “LRK”ṗ;`E3Ƥ$ÐṂX - Link: integer, n “LRK” - "LRK" ṗ - Cartesian power (all length n strings with alphabet "LRK") ÐṂ - keep those entries which are minimal under: $ - last two links as a monad: ;` - concatenate with itself 3Ƥ - for each infix of length 3: E - all equal? X - random element ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` …LRKãʒDJÅγà3‹}Ω ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//@KApkxSS8OjypJESsOFzrPDoDPigLl9zqn//zQ "05AB1E – Try It Online") ``` …LRK # literal "LRK" ã # strings made of `input` of those letters ʒ } # filter: DJ # concatenate the string with itself Åγ # run-length encode à # maximum (largest run length) 3‹ # less than 3? Ω # get a random element ``` [Answer] # [R](https://www.r-project.org/), 67 bytes ``` n=scan();while(max(rle(c(x<-sample(c("L","R","K"),n,T),x))$l)>2)0;x ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVIzexQqMISCdrVNjoFifmFoDZSj5KOkpBQOytpKmTpxOiqVOhqamSo2lnpGlgXfHfyOA/AA "R – Try It Online") A full program taking an integer, n and implicitly printing the drum pattern. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` “LRK”ṗ;`ŒɠṀ<ʋƇ3X ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//4oCcTFJL4oCd4bmXO2DFksmg4bmAPMqLxoczWP///zM "Jelly – Try It Online") A monadic link taking the length \$n\$ and returning a Jelly string of the drum pattern. Like the other answers, assumes that \$n > 1\$ ## Explanation ``` “LRK”ṗ | Cartesian power of "LRK" and n ʋƇ | Keep those where the following is true: ;` | - Concatenate to itself Œɠ | - Lengths of runs Ṁ | - Max < 3 | - Less than 3 X | Pick one at random ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~115~~ \$\cdots\$ ~~112~~ 104 bytes ``` from random import* f=lambda n,s='L':any(b*3in s*3for b in'LRK')and f(n,''.join(choices('LRK',k=n)))or s ``` [Try it online!](https://tio.run/##HcsxDsIwDIXhvafwFjuyGAgwVOoJ6MQNkpaoBupUSZeePgSGp394@rZjX5K6WmNOK2Svc4usW8q77eLw8WuYPSiXwYym93pgsE4UinUxZQggasbH3VCTEFHZmNMrieK0JJmeBf8vvwclogZK/TFpDNDxmS9tjq98o76DLYvuGFGI6hc "Python 3 – Try It Online") Saved a byte thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)!!! Saved 8 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function. ``` {'LRK'[?⍺⍴3]}⍣{~1∊≢¨3∪/⍺,2↑⍺}⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rdJ8hbPdr@Ue@uR71bjGNrH/Uurq4zfNTR9ahz0aEVxo86VukD5XSMHrVNBNJA6RX/0x61TXjU2/eob6qn/6Ou5kPrjUGSfVODg5yBZIiHZ/D/tEMrHvVuNjUAAA "APL (Dyalog Unicode) – Try It Online") `{`…`}`…`⍨` apply the following function using the single argument also as left argument:  `'LRK'[`…`]` index into the string `"LRK"` using the following indices:   `⍺⍴3` reshape the number three into the length indicated by the left argument   `?` random indices in those ranges `⍣{`…`}` keep applying that function until the following is true:  `2↑⍺` take the first two characters of the previously generated string  `⍺,` prepend the previously generated string  `3∪/` the unique elements in each window of width three (lit, the union-reduction)  `≢¨` the length of each set  `1∊` is one a member thereof?  `~` negate [Answer] # [R](https://www.r-project.org/), 75 bytes ``` `?`=diff;n=scan();while(!all(??c(x<-sample(9+c(2,3,9),n,T),x)))0;LETTERS[x] ``` [Try it online!](https://tio.run/##K/r/P8E@wTYlMy3NOs@2ODkxT0PTujwjMydVQzExJ0fD3j5Zo8JGtzgxtwAoZKmdrGGkY6xjqamTpxOiqVOhqalpYO3jGhLiGhQcXRH738jgPwA "R – Try It Online") Rejection sampling until an allowable pattern is found. Samples \$x\_i\$ from the set \$\{11, 12, 18\}\$ (the positions in the alphabet of K, L, R). Agreeably, these numbers are such that a pattern is allowable iff \$\forall i, (x\_{i+1}-x\_i)-(x\_i-x\_{i-1})\neq 0\$. This condition is verified by calling `diff` twice (`diff` computes lagged differences, and here we want the lagged differences of the lagged differences). [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->x{0while /(.)\1\1/=~(w=(%w(L K R)*x).sample(x)*'')+w;w} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166i2qA8IzMnVUFfQ08zxjDGUN@2TqPcVkO1XMNHwVshSFOrQlOvODG3ICdVo0JTS11dU7vcurz2f0FpSbFCml5yYk6OhpEmFzLXGJVrgso1ReWaaf4HAA "Ruby – Try It Online") [Answer] # JavaScript (ES6), ~~77~~ 74 bytes Assumes that the input is greater than \$1\$. ``` n=>(g=s=>s[n-1]?/(.)\1\1/.test(s+s)?g``:s:g(s+'LRK'[Math.random()*3|0]))`` ``` [Try it online!](https://tio.run/##Dce9DoIwEADgnae4jZ6EQnUDCw@gLq5A0oY/NXg1XOOiPntl@vI97Ntyv95fPiU3jGHSgXQlZs264oZS1dWZkNiqVmXSj@wFJ4z1bEzBxbwlPl9PcXOx/iZXS4N7CtwdvnmHaEyY3CoINOxLIDiCyjeTBOETAfSO2C2jXNwsJkGIZfQLfw "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` Nθ≔KηW⊙KLR№×η³×κ³≔⭆θ‽KLRηη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1PQ8lbSUchA8gvz8jMSVXQcMyrBIr5BAFFnfNL80o0QjJzU4s1MnQUjDV1FCCcbBAHCBSgZgSXFGXmpfsmFmgU6igEJeal5OdCzNDUhJgdAJQv0QCy/v@3/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Hangs for an input of `1` (could be changed to output a random hit at a cost of 1 byte). Explanation: ``` Nθ ``` Input the number of hits. ``` ≔Kη ``` Initialise the output to an illegal value. ``` W⊙KLR№×η³×κ³ ``` Repeat while the output is illegal, determined by tripling the output and each of the three letters `K`, `L` and `R`, and checking whether one contains any of the others. ``` ≔⭆θ‽KLRη ``` Assign the desired number of randomly selected letters to the output. ``` η ``` Output the final legal result. [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 86 bytes ``` $_=R x("@F"+2);1while s|(.)(?=\1\1)|(R,L,K)[rand 3]|e;s/..$//;($_.$_)=~/(.)\1\1/&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jZIoUJDycFNSdtI09qwPCMzJ1WhuEZDT1PD3jbGMMZQs0YjSMdHx1szuigxL0XBOLYm1bpYX09PRV/fWkMlXk8lXtO2Th@oHqRYX02tKDUl//9/03/5BSWZ@XnF/3V9TfUMDA3@6xYkAgA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 97 bytes ``` ->x,y=->{[*1..x].map{%w[L R K].sample}}{a=y[];a=y[]while(a+a).chunk{|n|n}.any?{|_,e|e[2]};a.join} ``` [Try it online!](https://tio.run/##VcfBCoIwGADge0@xS@BKf8jKi2gPUKeuY8SfTLTmkmzo2PbsCzq1ywffW99NaElFQlYvqamy2rLNDmDhMOBo1zO7kCs5c5hwGKXw3mJlGC9/zl0vRYJbpNB0Wj2tU055QGVO1t1S4QTLuS8RHq9e@TDqz0RaaFDKJKer/@7jHuIe4xY0fAE "Ruby – Try It Online") This is a lambda function, which takes the length input as `x`. It creates a function `y` which generates a list of length `x` containing random characters from the list `["L", "R", "K"]`. It then checks to see if there are any repeating occurrences of more than 2, and if so recreates a random string. The `chunk` method on an array groups consecutive elements. I check for any repetitions on `(a+a)` (where `a` is the generated drum loop), to find any looping-round repetitions. ## Golfy Tricks * Using `e[2]` instead of `e.size > 2` - this works as everything is truthy in Ruby except `nil` and `false`, and indexing out of bounds in an array returns `nil`. * Using `%w[L R K]` instead of `["L","R","K"]` or `[?L,?R,?K]` - This is ruby's [whitespace-separated word array](https://stackoverflow.com/questions/1274675/what-does-warray-mean). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 55 bytes ``` {({S:g{.}=<R L K>.pick}...{!/(.)$0$0/}o*x 2).tail}o\*x* ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqM62Cq9Wq/W1iZIwUfB206vIDM5u1ZPT69aUV9DT1PFQMVAvzZfq0LBSFOvJDEzpzY/RqtC6781V3FipUKagul/AA "Perl 6 – Try It Online") Anonymous code block that takes an integer and returns a string of `RKL`s. ### Explanation: ``` o\*x* # Generate a string of n *s { } # And pass to code block ( ... ).tail # Get the last element of the sequence { } # Where each element is S:g{.}= # Substitute each character of the previous string with <R K L>.pick # A random character { } # Until o*x 2 # The double of the string ! # Does not /(.)$0$0/ # Contain three of the same character in a row ``` [Answer] # [Red](http://www.red-lang.org), ~~141~~ 112 bytes ``` func[n][until[s: copy""loop n[append s random/only"LRK"]parse rejoin[s s][any[copy t skip opt t ahead not t]]]s] ``` [Try it online!](https://tio.run/##LY1LDsIwDET3PYWVC/BZ9gqw6tbyIiKuCBTbilOhnj40qLsZad6bwqlNnJCGEiXp5@TMCUS/wzy2eZUHCuEqNS/oIzzUthAWVQPBaMaSwOEgVZYt3KdbIIvFeSj80izo4IRRNuwwVPB3NlCre4xPjv1sz0Tk1P7myxlQxsPam5UsFdD6Fq4wgxC1Hw "Red – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 43 bytes ``` pe"LRK"jCB{J?+gw)-]>]3.<}f[sa0#Rx/x/jrn-]!! ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/IFXJJ8hbKcvZqdrLXju9XFM31i7WWM@mNi26ONFAOahCv0I/qyhPN1ZR8f9/YyNDUwUTAA "Burlesque – Try It Online") Made trickier by the fact there is no "select random element from list" as far as I am aware. 15 bytes are just trying to select a random element. ``` pe # Push inputs onto stack takes "SEED N" "LRK" # Literal LRK jCB # Form all combinations of length N { J?+ # Double string gw # Zip with length of consecutive vals )-] # Take length >] # Maximum 3.< # Less than 3 }f[ # Filter for sa0 # Find number of matches #Rx/x/j # Fiddle stack to get SEED 0 num_matches rn # Gen random ints -]!! # Select the first ``` ]
[Question] [ Given guaranteed strictly positive **integers \$w\$ and \$n\$**, output * An **equilateral triangle array** with **side length \$w\$**, filled with two distinct, consistent values. I'll call these `0` and `1` but they do not have to be equal to `0` and `1`. * The **number of `1`s** inside this array **must be equal to \$n\$**. * The output triangle **must be symmetrical**, meaning that it is the same when flipped horizontally or diagonally (**your choice**). * An equilateral triangle array can be an array with \$w\$ elements where for \$1\$ to \$w\$ (inclusive), there is a sub-array with that number of elements inside of \$w\$ (for example, but it may be outputted via ascii-art, see below). (\$n\$ values are guaranteed to fit in the triangle) ## Examples ``` w=3, n=1 1 0 0 0 0 0 w=3, n=2 0 1 1 0 0 0 w=3, n=3 1 1 1 0 0 0 w=3, n=4 0 1 1 1 0 1 w=3, n=5 0 1 1 1 1 1 w=3, n=6 1 1 1 1 1 1 ``` ## Valid Output Format List In this case the distinct values are `1` and `0`. Possible output triangles (all considered equivalent) with `1`s at their corners and center and a width of 4 are: ``` 1 0 0 0 1 0 1 0 0 1 ``` ``` 1 00 010 1001 ``` ``` [[1],[0,0],[0,1,0],[1,0,0,1]] ``` ``` 1 0 0 1 0 1 0 0 0 1 ``` ``` [[1],[0,0],[0,1,0],[1,0,0,1]] ``` ``` 1 0 00 11 00 0 1 ``` ``` 1 0 0 0 1 1 0 0 0 1 ``` --- [here is a test case validator in Jq](https://jqplay.org/s/fuamafVDxH), takes `{"w": w, "n": n, "a": result you wish to check}` (in the JSON array format like `[[1],[0,0],[0,1,0],[1,0,0,1]]`) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` RØ.ṗŒpFS=ɗƇUƑƇḢ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//UsOYLuG5l8WScEZTPcmXxodVxpHGh@G4ov///zP/NA "Jelly – Try It Online") -1 byte thanks to caird coinheringaahing ``` RØ.ṗŒpFS=ɗƇUƑƇḢ Main Link; accepts w as the left argument and n as the right argument R Range; [1, 2, ..., w] Ø.ṗ [0, 1] ~ cartesian power ~ ^ Œp Cartesian Product of ^'s items - this gets all valid triangles of the right size ---ɗƇ Keep elements where S the sum of F the triangle flattened = equals (right argument) Ƈ Keep elements where Ƒ the element is the same when U each sub-list is reversed Ḣ Get the first such triangle ``` [Answer] # JavaScript (ES6), 54 bytes A much shorter approach. I think this is equivalent to [@ovs' answer](https://codegolf.stackexchange.com/a/226109/58563). Expects `(n)(w)`. Returns a list of lists, from bottom to top. ``` n=>g=w=>w?[Array(w).fill(n<w?0:(n-=w,1)),...g(w-1)]:[] ``` [Try it online!](https://tio.run/##VY1BbsIwFET3nGKW/zeOS2i7ITiIRU8RZWEZO6Wy7MihtRDi7KnJrts3b2a@9a@eTbpM1zrEs12cWoLqRpVVl4/9KSV9o8zSXbyncMjH7Z5CrbJomIWUcqRcNzzs@2Fpe@wE3gTeBT4wSBfTpzZflKE63DdAARSg0LQIOChkvKCkFRrGK3aFVhWvJpDsXExHgct7uyITwxy9lT6OVGLxdKTz@koskz3/GEs0CRh@/k1l1vDafGz@dwt88PIH "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~88~~ 85 bytes This one inserts \$1\$'s as soon as it can. Expects `(n)(w)`. Returns a list of lists, from bottom to top. ``` n=>g=w=>w?[(h=q=>k--?k--?[q=n>1?--n/n--:0,...h(),q]:[n&&n/n--]:[])(k=w),...g(w-1)]:[] ``` [Try it online!](https://tio.run/##VY27bsMwDEX3fMWdArKWlDptl7iUp36F4cFQ/GhjyK@0Gop8uyt760CAOPdc8qv6qRY3f4537YdrvTayerGtBLEhL6iTSexN63ybYhJv01xrf/JaX56VMaYjVlN5KfzxuNO4lkw3CbylLQWd8sbWrMBZ4UXhVeENpWmG@aNyHQWIxe8BiIA8BGkGj3dBwBNimiBlnHCONEl4N4G5XqLZkGcKnO3IDX4Z@tr0Q0sxVptjmr66E5u5vn67mmhUcLz9G@NZx3vzcfjfjfDB6x8 "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò1 Ô®>V?Zî0:(VµZ,Zî1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8jEg1K4%2bVj9a7jA6KFa1Wixa7jE&footer=bV9xIHFTfSAg%2byBxUg&input=Mwo0) * we start from the biggest row, if `n` is not smaller than its length we fill the row with 1s * we can always put the rest of 1s on the next lines. * filling entire rows gives a specular triangle. ``` - input: U=w , V=n ò1 Ô - range[1..w] reversed ® - map to Z=> >V? - if Z>n Zî0 * string of Z 0s :( - else VµZ, * n-=Z and.. Zî1 * string of Z 1s ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 47 bytes Returns a nested list of booleans. ``` f=lambda w,n:w*[1]and[[x:=n>=w]*w]+f(w-1,n-w*x) ``` [Try it online!](https://tio.run/##JczLDoIwEIXhPU8xG9ILFFLcGBJ8EcICpSgGp6RWBje@euWynfP9M339w@LpPLkQ@mpsX9euBUqxJFnrpsWurpeywktFjaQm6TkpnaIiuYhAUMEp6q0DhAHBtXg3nKT6UZ4XiRZlBODM@zP6Fa5limK9bN5Z2ot93BjA5Ab0nAHLnnZAzuKOxfOO551aEtnNoDeOF3I0yI9YKC22r0cuwh8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 12 bytes Based on the observation that all outputs can be created by having each row as all 1's or all 0's. Check out [AZTECCO's answer](https://codegolf.stackexchange.com/a/226105/64121), which got there an hour earlier. ``` 1ÝIã.ΔƶOQ}ā× ``` [Try it online!](https://tio.run/##ASoA1f9vc2FiaWX//zHDnUnDoy7OlMa2T1F9xIHDl/99zrVTw7DDvX0uY/8zCjU "05AB1E – Try It Online") ``` 1Ý # push the range [0..1] == [0, 1] Iã # raise this to the first input (w) cartesian power # this yields all w-tuples of 1's and 0's .Δ } # find the first that satisfies: ƶ # each value multiplied by its 1-based index O # take the sum of that Q # is equal to the second input (n) ā # push the range [1..len(value)] == [1..w] × # repeat each digit in the select tuple that number of times ``` --- Alternative 12 byters (Both find a subset of `[1..w]` that sums to `n` and build the triangle from that): ``` L©æ.ΔOQ}®å®× ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f59DKw8v0zk3xD6w9tO7wUiCe/v@/MZcpAA "05AB1E – Try It Online") ``` LDæIÅœÃнsåā× ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//0xEw6ZJw4XFk8OD0L1zw6XEgcOX//8zCjU "05AB1E – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ ~~40~~ 28 bytes ``` NηF⮌…·¹N«G↘↖ιI¬‹ηι↓¿¬‹ηι≧⁻ιη ``` [Try it online!](https://tio.run/##ZU7NCsIwGDuvT9HjN5iHIV62k@hlsA0Z@AB1fGsLtR39ExGfvW7uIphTEpKQUTA7GqZSavQcfB/uN7Qg8ppMxlIYMKJ1CI0eVXAy4sA0RygL@hvPF9AXyS5GPbnRUJ3NQw@SC1/Q6jq3OC1EFvTEnIfeeGjRORCLtzZrknUm4tZalZzoX4p2bD46J/m2C53UwX1H16/vlMo9OaRdVB8 "Charcoal – Try It Online") Link is to verbose version of code. Takes arguments in the order `n`, `w`. Explanation: Port of @AZTECCO's answer. ``` Nη ``` Input `n`. ``` F⮌…·¹N« ``` Count from `w` down to `1`. ``` G↘↖ιI¬‹ηι↓ ``` Output a line of `1`s or `0`s depending on whether `n` is big enough. ``` ¿¬‹ηι≧⁻ιη ``` Reduce `n` accordingly. Previous 40 byte answer: ``` NθFN⊞υ¹Eθ⭆E⌊⟦⊕ι⁻θι⟧‹⁺ιλ⊖θ∧›№υ¹λ⊟E⊕λ⊟υ‖O↘ ``` [Try it online!](https://tio.run/##TY5NC4JAEIbv/oo9zoAdIrrkKRJC6EPqGB3MRl1Yd3XdrZ@/jUrUwBzeZ154pmwKW5pChZDpzruTbx9kocckqowV8A8RRe6HBnwslnzPrdQOjkUHfSyujlM9hmmllq1v4Zbp0lJL2tETJMaCD34Y@xLvHA80DJArRjIWikFKv36PyGSrn7C3VDh@YGc8Gyf9XM/N7PvXfLnHeZLoQpWi0p1fZBWXN6l564usG4dJCOtouQqLl/oA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `w`. ``` FN⊞υ¹ ``` Input `n` and make a list of that many `1`s. ``` Eθ ``` Start drawing a triangle of height `w`. ``` ⭆E⌊⟦⊕ι⁻θι⟧ ``` Draw the upper left half of the triangle. ``` ‹⁺ιλ⊖θ ``` Calculate whether this square lies on the diagonal or not. ``` ∧›№υ¹λ⊟E⊕λ⊟υ ``` If `n` is large enough to need both this square and its reflection, then reduce `n` accordingly and output a `1`, otherwise output a `0`. This always works because the very last square is on the diagonal. ``` ‖O↘ ``` Reflect to complete the triangle. [Answer] # [C (gcc)](https://gcc.gnu.org/), 62 bytes ``` f(w,n,c){for(c=n>=w,w&&f(w-1,n-w*c);~w;putchar(w--?48+c:10));} ``` [Try it online!](https://tio.run/##HY5BDoIwEEXX7SmaJjSttAkIEmNFz0LGoF04GsB0QfDqderiLf7Lz58BdwdIadTRogWzjq9JQ4@XPtqoFGlXW3RxB8Z/o39/FngME1l3bY8lnOrKGL@l5xBQm5WzgIugJc9ZHsop9JUP586HsswFNsOAo5bFTRQ3aVW0Cg3V2f8Dky/MWsqsNr6lRtS8EXuiIVriQHQ/ "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ŒPS=¥ƇḢċ⁹xɗⱮ⁸ ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//xZJQUz3CpcaH4biixIvigbl4yZfisa7igbj///8z/zU "Jelly – Try It Online") A dyadic link taking `w` as its left argument and `n` as it’s right. Returns a list of lists of 0s and 1s. Based on the observation by @AZTECCO and @ovs that we can compose this solely of rows of 0s and 1s so be sure to upvote their answers too! [Answer] # [J](http://jsoftware.com/), 33 bytes ``` ((]echo@#>:)]0>.<:@],~[-]*>:)/^:_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTRiU5Mz8h2U7aw0Yw3s9GysHGJ16qJ1Y7WAAvpxVvH/NbnSgOqNgaQhmDQCk8Zg0gRMmoJJMyD5HwA "J – Try It Online") A function whose output (rather than return value) prints what we want. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `r`, ~~18~~ 16 bytes ``` ⅛ɾṘƛ¼:n≤:Sn*,[-⅛ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=r&code=%E2%85%9B%C9%BE%E1%B9%98%C6%9B%C2%BC%3An%E2%89%A4%3ASn*%2C%5B-%E2%85%9B&inputs=5%0A3&header=&footer=) ``` ⅛ # (Implicit input) Push to global array ɾṘ # (Implicit input) range(1,n+1) reversed ƛ # Foreach [n] ¼: # Push from global array and duplicate [n,r,r] n≤ # Push n and check if r >= n [n,r,b] :Sn*, # Duplicate, coerce to string (0 or 1), multi by n and output. [ # If ToS is truthy (r >= n) [n,r] - # Subtract [r-n] (r flag reverses arguments) ⅛ # Push to global array. ``` Due to a bug with redefining the register inside a lambda, I'm forced to use the global array. It works well though, and I don't think it'd be any more golfable if the register worked properly. Based on the insight that everything can be made of rows of 1s and 0s. [Answer] # [R](https://www.r-project.org/), 54 bytes ``` function(w,n)for(i in w:1){show(1:i&(a=n>=i));n=n-i*a} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jXCdPMy2/SCNTITNPodzKULO6OCO/XMPQKlNNI9E2z842U1PTOs82TzdTK7H2f5qGsY6pJleahomOoeZ/AA "R – Try It Online") Using `TRUE` and `FALSE` as the values. ]
[Question] [ Given 2 inputs (m=*minimum starting id*, n=*number of ids*), generate a sequential list of ids, starting at >=m, made up of the digits 0-9 where no 2 contiguous numbers are the same, e.g. 1232 is ok, 1233 is not (contains 2 '3's next to each other). **Example** for m=985, n=6, below shows what ids would be generated/skipped ``` ... 985 - ok, 1st 986 - ok, 2nd 987 - ok, 3rd # skip 0988 (contains '88') 989 - ok, 4th # Skip 099x (contains '99') # Skip 100x (contains '00') 1010 - ok, 5th # Skip 1011 (contains '11') 1012 - ok, 6th ... ``` **Output** Each ID should be printed on a new line, as for the above sequence: ``` 985 986 987 989 1010 1012 ``` **Rules** Standard code-golf rules, lowest byte count wins [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~11~~ 10 bytes ``` {≤ṫẹ~ḅẉ}ᶠ⁾ ``` Input is a list of two numbers. [Try it online!](https://tio.run/##AS0A0v9icmFjaHlsb2cy//974omk4bmr4bq5fuG4heG6iX3htqDigb7//1s5ODUsOV0 "Brachylog – Try It Online") ## Explanation The built-in `ḅ` takes a list or string, like `"1000220"`, and splits it into blocks of equal adjacent elements, like `["1","000","22","0"]`. In this program, I apply the `~` operator to it, so it works in reverse: it takes a list of strings, checks that each string consists of repetitions of a single character and neighboring strings have different characters, and concatenates the list. The predicate `≤` enumerates numbers starting from the first input in increasing order, and I check a condition on them, printing those that satisfy it and stopping when I've found enough. ``` {≤ṫẹ~ḅẉ}ᶠ⁾ Input is a pair, say [M=988,N=3]. { }ᶠ⁾ Apply this predicate to M and compute the first N results. ≤ Take a number that is greater than or equal to M (first up is 988). ṫ Convert it to string: "988" ẹ Split it into substrings of length 1: ["9","8","8"] ~ḅ Apply ḅ in reverse: fails, try next number. ẉ If ḅ succeeds, print the resulting string and a newline. This counts as a result of the predicate. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` µÐÔQi=¼}> ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0NbDEw5PCcy0PbSn1u7/fzMuSwtTAA "05AB1E – Try It Online") **Exlpanation** ``` µ # loop until counter equals n Ð # triplicate current value (initially m) Ô # connected uniqueified on the copy at the top of the stack Q # compare to unmodified for equality i } # if true = # print current value while leaving it on the stack ¼ # increment the counter > # increment current value ``` [Answer] # Java 8, 83 bytes ``` (m,n)->{for(;n>0;m++)if(!(m+"").matches(".*(.)\\1.*")){System.out.println(m);n--;}} ``` **Explanation:** [Try it online.](https://tio.run/##LY67DsIwDEV3vsJ0smkbwQACRfAHsDACQwgppDRu1QQkVPXbS3hI9uB7ZZ1TqqfK68ZwebkPulLew1ZZ7kYAloNpC6UN7D4nwLO2F9AYc3DZpwYmGZs@bhwfVLAadsCwhgFdxpRvuqJuUfJmKl2aki1wjC5NEhJOBX0zHhMxQUHH40xMEqJu//LBOFE/gmjaiKgYHUnOc9n3g/yBmse5iqA/72vlojPuQ/y4Hk6Kfr4sNK6W8wwWf81@eAM) ``` (m,n)->{ // Method with two integer parameters and no return-type for(;n>0; // Loop as long as `n` is larger than 0 m++) // After every iteration: increase `m` by 1 if(!(m+"").matches(".*(.)\\1.*")){ // If there are no repeated adjacent digits: System.out.println(m); // Print `m` n--;}} // And decrease `n` by 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` DIẠµ#Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/F8@GuBYe2Kkf@///f0sL0vxkA "Jelly – Try It Online") ## How it works? ``` DIẠµ#Y – Full program. Argument: two integers, X and Y. µ# – Return the first Y integers higher than or equal to X that satisfy: I – The increments ... D – ... Of their base-10 digits ... Ạ – ... Are all non-0. Y – Join the result by newlines. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 59 bytes ``` param($m,$n)for(;$n){if("$m"-notmatch"(.)\1"){$m;$n--}$m++} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVXRyVPMy2/SMMaSFdnpmkoqeQq6ebll@QmliRnKGnoacYYKmlWq@QC5XV1a1VytbVr////b2xsYvLfDAA "PowerShell – Try It Online") Basically similar to the other answers. Loops so long as we have numbers left to print (`for(;$n)`), tests whether we have a regex match against a double-digit and if not it puts that on the pipeline and decreases `$n`. Then we increment `$m` and loop again. The elements are picked up from the pipeline and the implicit `Write-Output` gives us a newline-separated output for free. [Answer] # [R](https://www.r-project.org/), ~~111~~ ~~92~~ 71 bytes ``` function(m,n)while(F<n){if(!grepl("(.)\\1",m)){cat(m,' ');F=F+1} m=m+1} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNXJ0@zPCMzJ1XDzSZPszozTUMxvSi1IEdDSUNPMybGUEknV1OzOjmxBKhSnUtd09rN1k3bsJYr1zYXSP1P07C0MNUx0@QCMSx0jDX/AwA "R – Try It Online") Uses `grepl` to search for repeated digits. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` DŒgZLỊµ#Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6KT0KJ@Hu7sObVWO/P//v6WF6X8zAA "Jelly – Try It Online") If not for the output restriction, `Y` can be removed. [Answer] # C, 73 bytes ``` k;f(s,n){for(;n--;printf("%d\n",s++))for(k=s;k;)k=k%10-k/10%10?k/10:++s;} ``` [Try it online!](https://tio.run/##FYsxCoQwEAD7vCIIwi5JUIsTdZH7iI1EcsjiKsZOfHsuTjPFMN79vE@JKUC0gnfYTyBxjo5zlStAUS6TFDYag/g2HiMxIY9cNrXjqqmzv68HYyI9KV96m1cBVLfSmQB997G6RVJP@gM) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes ``` {.put for grep({none .comb Zeq.comb.skip},$^a..*)[^$^b]} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@79ar6C0RCEtv0ghvSi1QKM6Lz8vVUEvOT83SSEqtRDM0CvOziyo1VGJS9TT09KMjlOJS4qt/Q/Wb2lhqqNg9h8A "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with placeholder params $a $b .put for grep( { none # create a none junction (True if all are False) .comb # the input split into digits Zeq # Zip using &infix:«eq» operator .comb.skip # the input split into digits starting at second one }, $^a .. * # a Range starting at the first argument )[ ^ $^b ] # take the first $b values } ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 34 bytes ``` .0A` "$+"{\/(.)\1/{`.+ * )C` .+ * ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8/AMYFLSUVbqTpGX0NPM8ZQvzpBT5tLi0vTOYELzPj/34zL0sIUAA "Retina – Try It Online") Takes `n` and `m` as input on separate lines. Explanation: ``` .0A` ``` Turn off automatic output and delete `n` from the work buffer. ``` "$+"{ ``` Repeat `n` times. ``` \ ``` Print the value of `m` at the end of the following looped group. ``` /(.)\1/{` ``` Loop while there are contiguous digits. ``` .+ * ``` Convert to unary. ``` )C` ``` Count the number of empty strings, which is one more than the number of characters, thus adding 1 and converting back to decimal. This ends the inner loop. ``` .+ * ``` Having printed `m`, add 1 again in the same way. (The last line doesn't need a `C`` because it's the default stage type for the last line.) The outer loop is implicitly ended. Note that converting to unary and back to decimal is a little slow; for 39 bytes, a version that doesn't do any conversion: ``` .0A` "$+"{\/(.)\1/+`.+ $.(*__ .+ $.(*__ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8/AMYFLSUVbqTpGX0NPM8ZQXztBT5tLRU9DKz6eC876/9@My9LCFAA "Retina – Try It Online") Explanation: `$.(` calculates the length of the rest of the substitution, conveniently without actually expanding it; since the length of `*_` is implicitly the matched value and the length of `_` is of course 1 this just increments the value. [Answer] # [Perl 5.10.0](https://www.perl.org/) + `-n`, ~~40~~ 39 bytes ``` for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0jDWiXTWiVeW1uzWlFfQ08zxlBfTU0lU1dXTa04sbJWJdNWJf7/fzMuSwvTf/kFJZn5ecX/dfP@6/qa6hka6BkAAA "Perl 5 – Try It Online") *-1 byte thanks to Xcali* Input on two lines, first n, then m. Make sure that there is NO newline after m: ``` (echo '6'; echo -n '985') | perl -nE 'for(;$i;$_++){!/(.)\1/&&$i--&&say}$i=$_' ``` [Answer] # [Perl 5](https://www.perl.org/), `-ln` 33 bytes Enter 2 lines on STDIN, first starting id then count ``` #!/usr/bin/perl -ln $n-=!/(.)\1/&&say,$_++while$n.=<> ``` [Try it online!](https://tio.run/##K0gtyjH9/18lT9dWUV9DTzPGUF9NrTixUkclXlu7PCMzJ1UlT8/Wxu7/f0sLUy6zf/kFJZn5ecX/dXPy/uv6muoZGugZAAA "Perl 5 – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` j.f.A.+jZTEQ ``` **[Try it here](https://pyth.herokuapp.com/?code=j.f.A.%2BjZTEQ&input=985%0A6&debug=0)** [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 73 bytes -7 bytes thanks to Mr. Xcoder ``` m,n=input() while n: if~-sum(i*2in`m`for i in`99**9`):print m;n-=1 m+=1 ``` [Try it online!](https://tio.run/##DcaxCoAgEADQ3a@4sSwHhSIL/8Ul8aA7xYxo6detN7381JjYtEYjO@R81a4Xd8RjB14FYHjVeVGH0iB78iEVQPhrrZTW92suyBVoY@W0ABqcbs0u0zh/ "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 70 bytes *-19 bytes thanks to nimi.* ``` s#n=unlines$map show$take n$filter(and.(zipWith(/=)=<<tail).show)[s..] ``` [Try it online!](https://tio.run/##FcrBCoMwDADQXwnYQ3upp8kG9is8eBAPgXU0GGMxEWE/37F3fgV1y8ytaSfpEibJ6nasoOW4neGWQdyH2PLpUd7Rf6nOZMX3KaRxNCQO8X/DojGubUcSSFAvm@wEB6/nAzoY2g8 "Haskell – Try It Online") 17 bytes dedicated to separating by newlines. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~9~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` ç@F6╕↔┤ú ``` [Try it online!](https://staxlang.xyz/#c=%C3%A7%40F6%E2%95%95%E2%86%94%E2%94%A4%C3%BA&i=985+6%0A99+3&a=1&m=2) Happen to coincide with @Mr.Xcoder's algorithm in his Jelly answer. -1 byte per comment by @recursive. ## Explanation Uses the unpacked format to explain. ``` {$:-|A}gn { }gn Generator, generate given number of values, using block as a filter And implicit output, one element on a line. In Stax, only 0 and [] is falsy. $ Convert the number to string :- Difference between contiguous digit |A All of them are truthy (may use `:*` as well) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~94~~ ~~93~~ 91 bytes -1 byte thanks to Laikoni -2 bytes thanks to Zgarb ``` import Data.List a!0=[] a!b|all(null.tail)$group$show a=show a++'\n':(a+1)!(b-1)|c<-a+1=c!b ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrUdHANjoWSCXVJObkaOSV5uTolSRm5miqpBfllxaoFGfklysk2kIobW31mDx1K41EbUNNRY0kXUPNmmQbXSDPNlkx6X9uYmaebUFpSXBJkYKKgqWFqaLZfwA "Haskell – Try It Online") First Haskell golf. [Answer] # JavaScript (ES6), 50 bytes Takes input in currying syntax `(m)(n)`. ``` m=>g=n=>n?/(.)\1/.test(m++)?g(n):~-m+` `+g(n-1):'' ``` [Try it online!](https://tio.run/##DcdBDkAwEADAu4/YTdM2DgRJ@YgDoRrS7oo2jr5e5jbn8ixxvY8rSeLN5t3kYAZnyAw0alA4VVolGxMEIXB0QNi/Moi5mMUfWWFflnlliuyt8uxgh66tERrE/AE "JavaScript (Node.js) – Try It Online") [Answer] # C# (.NET Core), 91 bytes ``` m=>n=>{for(;n-->0;System.Console.WriteLine(m++))for(int k=m;k>0;k=k%10!=k/10%10?k/10:++m);} ``` [Port of @Steadybox' C answer.](https://codegolf.stackexchange.com/a/156886/52210) [Try it online.](https://tio.run/##NY5BC8IgGIbv@xVfh0Cxre1QVKYRQad26tB5mIE4FaYFMfbbTaNO38fD88IjfCncIKPoO@@hHQsAH7qgBLycukPbKYtwpgDXtw/SVOenFXtlw@IPjiIoZzPiHAQwiIZxy/j4cAOitix5TX/qyVnvelndBhXkRVmJDCEYZzHNQTNDdbI10/OmnjG9bOr0HPLdEWIwnWIuoannmyTQdrPCaI0zmYopfgA) [Answer] # [Perl 5](https://www.perl.org/) (`-nl`), 42 bytes ``` $l=<>;do{!/(.)\1/&&$l--&&say}while++$_&&$l ``` [Try it online!](https://tio.run/##K0gtyjH9/18lx9bGzjolv1pRX0NPM8ZQX01NJUdXV02tOLGytjwjMydVW1slHiT4/7@lhSmX2b/8gpLM/Lzi/7p5Of91fU31DAwNAA "Perl 5 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 90 bytes ``` {for(j=$1;k<$2;j++){for(a=b=d;++b<=(n=split(j,A,""))&&a!=c=A[b];a=c);if(n<b&&++k)print j}} ``` [Try it online!](https://tio.run/##HcjRCkAwFADQX0Fau10vFNHdffAd8rCR2qYRyoN8@5TzePTtY3yW7ZCO85K8yityiPCXZsMzIRrFMvC5r/aSruiLLAMQQqc8cT@YkTRPQHaRQRkhED3shw1X4t43xq6tk@YD "AWK – Try It Online") This is a lot uglier than I thought it would be. I discovered that `AWK` only has back-substitution in its `gensub` function which would make it not very efficient to use for this application. So this is a very straightforward approach of incrementing an ID counter, splitting the counter at each character, looping through the characters to see if any character is the same as the previous character. If no repeated characters are found, print the ID counter and increment the number of IDs printed. I will try to refrain from making a statement along the lines of "`AWK` should have the ability to do more robust regular expressions", but it will be difficult. [Answer] # Bash + GNU utilities, 35 ``` seq $1 inf|egrep -v '(.)\1'|sed $2q ``` [Try it online](https://tio.run/##S0oszvhfnFqiYGlhqmAGZBUqqBgqZOal1aSmF6UWKOiWKahr6GnGGKrXFKemKKgYFf7/DwA). [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` ->s,n{/(.)\1/!~s&&p(s)&&n-=1;s.next!;n>0&&redo} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ69aX0NPM8ZQX7GuWE2tQKNYU00tT9fW0LpYLy@1okTROs/OQE2tKDUlv/Z/WrS6pYWFuo5x7H8A "Ruby – Try It Online") ### If you don't like the quote marks, it's 50 bytes ``` ->s,n{puts s if/(.)\1/!~s&&n-=1;s.next!;n>0&&redo} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165YJ6@6oLSkWKFYITNNX0NPM8ZQX7GuWE0tT9fW0LpYLy@1okTROs/OQE2tKDUlv/Z/WrS6pYWFuo5x7H8A) [Answer] # [Pip](https://github.com/dloscutoff/pip), 22 bytes ``` --aLb{W`(.)\1`N++a0Pa} ``` [Try it online!](https://tio.run/##K8gs@P9fVzfRJ6k6PEFDTzPGMMFPWzvRICCx9v///5YWpv/NAA "Pip – Try It Online") ### Explanation ``` --aLb{W`(.)\1`N++a0Pa} a,b are command-line arguments --a Decrement a Lb{ } Loop b times: `(.)\1` Regex matching a character followed by itself W N++a While that regex matches in incremented a: 0 No-op Pa When the while loop exits, a is a valid ID; print it ``` ]
[Question] [ I was playing around with some numbers and found a sequence that, of course, is on OEIS. It is [A005823](https://oeis.org/A005823): ***Numbers whose ternary expansion contains no 1's***. It goes: > > a(2n) = 3\*a(n)+2 > > > a(2n+1) = 3\*a(n+1) > > > a(1) = 0 > > > a = 0,2,6,8,18,20,24,26,54.... > > > I wrote a [CJam program](http://cjam.aditsu.net/#code=qi%7BYbXYerZbS%7D%25&input=30) that generates the first *n* of these numbers by converting the index to binary, replacing the 1's with 2's, and converting from ternary to decimal. I also noticed that any even number can be obtained by taking the sum of two numbers in the sequence (sometimes the number with itself). **The Challenge:** Given any non-negative even number as input, output the indices of two numbers in the sequence that sum to it. (Note that sometimes multiple pairs are possible.) **The Rules:** * Specify if you're using 0- or 1-indexing. * If you're outputting as a string, put a delimiter between the two indices. * You are allowed to output as a complex number. * If you so desire, you can output every valid pair. * Code Golf: shortest answer wins ## Test Cases I use 0-indexing. Here I list every possible output for each input, but you only need to output one. ``` **0:** [0 0] **2:** [1 0] **4:** [1 1] **6:** [2 0] **8:** [2 1] [3 0] **10:** [3 1] **12:** [2 2] **14:** [3 2] **16:** [3 3] **18:** [4 0] **30:** [6 2] **32:** [6 3] [7 2] **46:** [7 5] **50:** [7 6] **120:** [10 10] **338:** [19 18] **428:** [30 23] [31 22] **712:** [33 27] [35 25] [41 19] [43 17] [49 11] [51 9] [57 3] [59 1] **1016:** [38 37] [39 36] ``` Thanks to @Luis Mendo for test case help. Related: [Is it within the Cantor set?](https://codegolf.stackexchange.com/questions/108838/is-it-within-the-cantor-set/) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~14~~ 13 bytes -7 bytes, thanks to @Neil's [JS answer](https://codegolf.stackexchange.com/a/141195/71256) -1 byte inspired by betaveros's [Parradoc answer](https://codegolf.stackexchange.com/a/141350/71256) Uses 0-indexing ``` mḋTmMo±>ḋ2B3½ ``` [Try it online!](https://tio.run/##yygtzv7/P/fhju6QXN/8QxvtgCwjJ@NDe////29oYGgGAA "Husk – Try It Online") ### Explanation ``` ½ Half the input B3 Convert to Base 3 m Map over the list Mo±>ḋ2 Function such that: 0 -> [0,0], 1 -> [0,1], 2 -> [1,1] ḋ2 Binary 2, [1,0] M For each in that list o±> check if the argument is greater than it T Transpose mḋ Convert each from binary ``` ### Previous 21 byte Solution First time I've seen a use for `»`. ``` mḋT»o%2+ȯ?´eḋε%3`-0B3 ``` [Try it online!](https://tio.run/##yygtzv7/P/fhju6QQ7vzVY20T6y3P7QlFcg/t1XVOEHXwMn4////hgaGZgA) Longer, as I was dealing with carries [Answer] ## JavaScript (ES6), ~~75~~ 71 bytes ``` f= n=>[1,0].map(i=>parseInt((n/2).toString(3).replace(/./g,c=>+c+i>>1),2)) ``` ``` <input type=number min=0 step=2 oninput=o.textContent=this.value%2?``:f(this.value)><pre id=o> ``` Explanation: Dividing input and the elements of A005823 by 2 doesn't alter the problem, however it makes the solution simpler as the ternary representations now only use 0s and 1s and therefore there is no carrying to consider. It also saves a step when converting from the element to its index (each element's ternary is twice the binary of its index). Examples: ``` A005823 halved n in values A005823 n n/2 base 3 base 3 indices 0 0 0 0 0 0 0 2 1 1 1 0 1 0 4 2 2 1 1 1 1 6 3 10 10 0 2 0 8 4 11 11 0 3 0 10 5 12 11 1 3 1 12 6 20 10 10 2 2 14 7 21 11 10 3 2 16 8 22 11 11 3 3 18 9 100 100 0 4 0 30 15 120 110 10 6 2 32 16 121 111 10 7 2 46 23 212 111 101 7 5 50 25 221 111 110 7 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26, 22~~, 21 bytes ``` ḶBḤḅ3 ÇŒcS=¥Ðf⁸ḢiЀÇT ``` [Try it online!](https://tio.run/##ATIAzf9qZWxsef//4bi2QuG4pOG4hTMKw4fFkmNTPcKlw5Bm4oG44biiacOQ4oKsw4dU////OA "Jelly – Try It Online") One byte saved thanks to @JonathanAllan! Explanation: ``` # Helper link: A005823 to *N* terms Ḷ # Lowered range(N) B # Converted to binary Ḥ # Double each digit ḅ3 # Converted from base 3 to decimal # Main link Ç # Last link Œc # All combinations of 2 items (with replacement) Ðf # Remove every combination where this isn't true: S=¥ # The sum of the two items is equal to N ⁸Ḣ # Take the first combination left i # Index of Ѐ # Each element of the combination Ç # In the sequence T # Return the truthy indices ``` [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda n:[n and(n/2%3>r)+2*f(n/3)[r]for r in 0,1] ``` [Try it online!](https://tio.run/##LY1BCsMgEEXX8RSzKWgi1OouYC8SstBG20A7hold9PR2Atn99@Dxt199FbStZf8On7gEwHFCCLhIvNqLu5MabJ8ZnJpozoWAYEUw@ja3JWV4BKyFJKpRAFCqX0Kw/YpVxhVZT3actVNCHCkeKQV8Jmm0M0Zbzrqgo@cHJbqNOATUbFjveyIm78@PoIZzRdX@ "Python 2 – Try It Online") The task can be done like this: 1. Halve the input 2. Convert to ternary list 3. Split that into two binary lists that sum elementwise to it 4. Convert those lists from binary We can do the splitting in (3) by converting `0->0,1->1,2->1` for one list and `0->0,1->0,2->1` for the other. That is, by checking is the value is above a threshold of 0 or 1. The two values can be found by respective recursive functions: ``` p=lambda n:n and(n/2%3>0)+2*p(n/3) q=lambda n:n and(n/2%3>1)+2*q(n/3) ``` The function `f` combines the two of these in a list comprehension. This makes it inefficient due to exponential branching. If complex numbers could be output, we could save 10 bytes with: ``` f=lambda n:n and(n%6>1)+n%6/4*1j+2*f(n/3) ``` [Answer] # J, ~~35~~ 32 bytes ``` ($#:I.@,)@(=[:+/~3#.+:@#:@i.@>:) ``` [Try it online!](https://tio.run/##y/r/P03BVk9BQ0XZylPPQUfTQcM22kpbv85YWU/bykHZyiFTz8HOSpMrNTkjXyFNwQDCUFeHCRihCxgaYagxNzT6/x8A) 0-indexed and input is given monadically. Returns all possible summations to the value (it treats `a b` and `b a` as different possible summations). Converting from a boolean matrix to indices takes a lot of code... I'd like to also remove the fork on the left so I don't have to use as many parentheses and `@`-ats, but I can't figure out a good way to do it (my alternate approach doesn't save any bytes). # Explanation For purposes of explaining and ungolfing, consider the following components of the main function ``` valid_nums =. = [: +/~ 3 #. +:@#:@i.@>: indices_of_ones =. $ #: I.@, ``` **valid\_nums** yields a boolean matrix where the indices are the indices of the summed sequence values. If there's a one at those indices, it means that the two numbers sum to the input value. **indices\_of\_ones** is a J idiom for giving the coordinates of the ones in an arbitrary rank boolean matrix The main function is composed quite simply as ``` indices_of_ones@valid_nums ``` ### valid\_nums ``` = [: +/~ 3 #. +:@#:@i.@>: Input is n #:@i.@>: Binary numbers in range [0,n] +: Doubled 3 #. Interpreted as ternary +/~ Addition table with self (sum all possible pairs) = Equate to n ``` ### indices\_of\_ones ``` $ #: I.@, , Ravel matrix into a single list I. Find the indices of ones in that list #: Convert to the base given by $ The shape of the matrix ``` `,`-ravel works in this case by joining each row to the next. ``` i.3 3 0 1 2 3 4 5 6 7 8 , i.3 3 0 1 2 3 4 5 6 7 8 ``` We can see that if this were a boolean matrix, the coordinates of ones can be found by interpreting the indices of the raveled matrix as numbers in the base of the shape of that matrix using as many prepositional phrases as possible to help confuse the poor reader. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~22~~ ~~21~~ ~~19~~ 17 bytes ``` tQ:qBEI_ZA&+=R&fh ``` Output is 1-based. The program produces all solution pairs. [Try it online!](https://tio.run/##y00syfn/vyTQqtDJ1TM@ylFN2zZILS3j/39TAwA) Or [verify all test cases](https://tio.run/##y00syfmv5PC/JNCq0MnVMz7KUU3bNkgtLeO/uq6u@v9oAwUjBRMFMwULBUMDBUMjBUMTBUMzBUMLBWMDBWOglJmCKUgcyDG2UDAxslAwBykyMDSLBQA). ### Explanation ``` t % Implicit input: n. Duplicate Q:q % Range [0 1 ... n] B % Convert to binary. Gives a matrix where each row corresponds to a number E % Multiply each entry by 2 I_ZA % Convert each row from ternary to a number &+ % Matrix of all pair-wise additions = % Does each entry equal n? R % Upper triangular matrix &f % Push row and column indices of nonzero entries h % Concatenate horizontally. Implicit didsplay ``` [Answer] # [Paradoc](https://github.com/betaveros/paradoc) (v0.2.10), 11 bytes (CP-1252) ``` ½3B2>_B™2Bv ``` [Try it online!](https://tio.run/##K0gsSkzJT/5vaGBo9v/QXmMnI7t4p0cti4ycyv4n/AcA "Paradoc – Try It Online") Algorithmically it's very much just like [Neil's ES6 answer](https://codegolf.stackexchange.com/a/141195/19857). On a lower level, also strikingly similar to [H.PWiz's Husk answer](https://codegolf.stackexchange.com/a/141204/19857). I am amused that we got to use all three overloadings of `B`. Takes an integer on the stack, leaves a list of two integers on the stack. Explanation: ``` ½ .. Halve input 3B .. Convert to ternary 2 .. 2, which will get implicitly coerced to [0,1] >_ .. Greater than, as a block B .. "Bimap": take the block and map it over the Cartesian .. product of the last two lists to get a matrix ™ .. Transpose 2Bv .. Convert each row from binary ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 37 bytes 0-indexed Certainly not golfed as well as it could be. ``` KUQJmi:.Bd\1\23KhfqQ+@JeT@JhTsmm,dkKK ``` [Try it online!](https://tio.run/##K6gsyfj/3zs00Cs300rPKSXGMMbI2DsjrTBQ28ErNcTBKyOkODdXJyXb2/v/fwA "Pyth – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 29 bytes This one returns all possible pairs of indices. ``` fqQ+@Kmi:.Bd\1\[[email protected]](/cdn-cgi/l/email-protection) ``` **[Try it here.](https://pyth.herokuapp.com/?code=fqQ%2B%40Kmi%3A.Bd%5C1%5C23QhT%40KeT.cUQ2&input=46&debug=0)** # [Pyth](https://pyth.readthedocs.io), 30 bytes ``` hfqQ+@Kmi:.Bd\1\[[email protected]](/cdn-cgi/l/email-protection) ``` **[Try it here.](http://pyth.herokuapp.com/?code=hfqQ%2B%40Kmi%3A.Bd%5C1%5C23QhT%40KeT.cUQ2&input=46&debug=0)** This returns the pairs of indices as `[LowerIndex, HigherIndex]`. --- # How does this work? ``` hfqQ+@Kmi:.Bd\1\[[email protected]](/cdn-cgi/l/email-protection) Full Program. Q means input throughout the whole explanation. m Q Map over the range [0, Q) with a variable d. .Bd Convert to binary. : \1\2 Replace 1 with 2. i 3 Convert it from base 3 to integer. K Assign the mapped range to a variable K. .cUQ2 All possible two-element combinations of the range [0...Q). +@ hT@KeT Sum of the integers on positions in K of the two-element combination. fqQ Filter those that equal the input. h Optional: Head. Take the first element. Print the result, implicitly. ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~122~~ 120 bytes -2 bytes thanks to Mr. Xcoder! 0-indexed ``` def f(a):r=range(a);s=[int(bin(x)[2:].replace(*'12'),3)for x in r];return[(i,j)for i in r for j in r if s[i]+s[j]==a][0] ``` Ungolfed: ``` def f(a): r=range(a) s=[int(bin(x)[2:].replace(*'12'),3)for x in r] return[(i,j)for i in r for j in r if s[i]+s[j]==a][0] ``` [Try it online!](https://tio.run/##JcjBDoIwDADQX@mNTYlRuEH2JU0PQzftYgrpRoJfPxRvL2/5lNcsfa2PECEabwd16uUZvhyzQ5ZiJhazWewGumhY3v4ezKm5dY1textnhQ1YQGnUUFYVNNym4/l4@DH9yREyMp0zJnLOE16p1h0 "Python 3 – Try It Online") [Answer] # Mathematica, 94 bytes ``` (w=#;Position[s,#]&/@#&@@(k=Select)[Tuples[s=k[Range@w,DigitCount[#,3,1]==0&],{2}],Tr@#==w&])& ``` 1-indexed [Answer] # JavaScript, ~~120~~ 101 bytes ``` n=>[(A=[...Array(n+1)].map(Z=(a,b=a)=>b&&3*Z(b/2|0)+b%2*2))[F='findIndex'](a=>z=~A[F](b=>a+b==n)),~z] ``` [Try it online!](https://tio.run/##Jc7dasJAEEDhV@mNOmOm6@4mTXMzgdwIfQWXgLP5kYjdlSiiUnz1qPT6g8PZy0VOzTgcz58htt3U8xS4dFCxU0pV4yg3CInBWv3KETYMQp4FufTzebrcgF/ZP42Jn9mlRXRrXvRDaH9C210XNQiXd35Ubl2D51ISzxwQ6XGvpyaGUzx06hB34DRZyiingowmY8lkZHIyBaWa0hfl9KUpswV9v1Gb/H/nle9BENU@DmH7scXpCQ) 0-indexed. It returns the pair of indices where one index is the smallest possible (for example in the case of `428` it returns `22,31`). [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~220~~ 166 bytes -54 bytes by looking up the modulo function on the wiki, allowing some structural changes ``` ({()<({}[()()])>}{}){({}(<>))<>(()()())({()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>[()])}([]){{}<>(({}){})<>(({}){}{()<({}[()]){<>({}())<>(<{}>)}>}{})([][()])}({}{}<>) ``` [Try it online!](https://tio.run/##RY2xCsNADEN/RxoKzdLJ@EeOG9KhEBoyZDX37VfZLQ34wNaTdM9z3Y7ba1/fcyJAQ4wGgp0@YjB0w5w0R8ogvzbpLNrSa2nOZ25oirCLe7GB1hmJKqT5b9eHckjNYFJTGauPCv9aouo553JfHh8 "Brain-Flak – Try It Online") 0-indexed. ### Explanation Like many of the other solutions, this computes the ternary expansion of `n/2` and converts that to two binary numbers. Step 1: Divide input by 2 ``` ({()<({}[()()])>}{}) { } until number becomes zero: ({}[()()]) subtract two ( ()< > {}) push number of iterations ``` Step 2: compute ternary expansion ``` {({}(<>))<>(()()())({()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>[()])} ({}(<>))<> { (({})){({}[()])<>}{} }{}<> ([{}()]{}) modulo (from wiki) (()()()) use 3 as base ()< > evaluate as 1 every time the 3 rolls over ( < >[()]) push number of rollovers (function is now division with remainder) { } repeat until quotient is zero, leaving all remainders on stack ``` Step 3: Convert to solution ``` ([]){{}<>(({}){})<>(({}){}{()<({}[()]){<>({}())<>(<{}>)}>}{})([][()])}({}{}<>) ([]){{} ([][()])} repeat while stack height > 1: (loop happens once when initial stack height is 1, but that's fine) <>(({}){}) double smaller output number <>(({}){} ) double larger output number { }{} if digit in ternary expansion is nonzero: ()< > add 1 to larger output number ({}[()]){ } if digit is 2: <>({}())<>(<{}>) add 1 to smaller output number ``` [Answer] ## JavaScript (ES6), 70 ~~72~~ bytes ``` n=>[6,4].map(x=>parseInt((n/2).toString(3).replace(/./g,d=>x>>d&1),2)) // thanks @Neil n=>[0,1].map(x=>parseInt((n/2).toString(3).replace(/1|2/g,d=>~-d||x),2)) ``` (0-indexed, and apparently nearly the same solution as @Neil even if I hadn't seen his answer) I started off with getting the index back from a number using the reverse of the process: stringify with base 3, replace every `2` with `1`, parse with base 2. To get two numbers, and that for every even one, we just half the input - but now, also `1` digits can occur. So we replace it with a `0` in the one number and a `2` in the other number, which does not change the sum of the two, before the replace-and-parse step. Here is what I came up with (doing the two replacements, `1` -> 0-or-2 and `2` -> `1` in one step): ``` n=>["001","011"].map(x=>parseInt((n/2).toString(3).replace(/./g,d=>x[d]),2)) ``` Of course the two replacement maps (strings) differ only in one index, so we should be able to shorten the array literal by only replacing `1` and `2` with `d == 2 ? 1 : x`. Or `d-1 || x`. Where `-1` does the same as the two unary operators - but they look scarier :-) Trying to avoid the array literal and the parenthesis around `n/2` I also came up with ``` n=>Array.from(parseInt,(h=n/2,i)=>parseInt(h.toString(3).replace(/1|2/g,d=>~-d||i),2)) ``` but it did not turn out fruitful. [Answer] # Pyth, 22 bytes ``` J.m}1jb3hQxLJhfqsTQ^J2 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=J.m%7D1jb3hQxLJhfqsTQ%5EJ2&input=1016&debug=0) ### Explanation: ``` J.m}1jb3hQxLJhfqsTQ^J2 hQ input + 1 .m find all values of [0, 1, 2, ..., input], where jb3 value converted to base 3 }1 check if it contains the digit 1 this boolean ^ is false J store this list in variable J ^J2 every pair of J f filter for pairs with sT sum of pair q equal Q the input h take the first of these pairs xLJ and find the corresponding indices of J ``` ]
[Question] [ ## Challenge Code an ASCII cookie of a kind according to the input. ## Input * The cookie kind. This is one of the three strings: "Plain", "Chocolate", or "Nuts". May be function arguments, stdin (or closest equivalent), or file arguments. ## Output * An ASCII cookie. See below. Must be ``` ___ / \ | | \___/ ``` for Plain input, ``` ___ /. .\ | . | \___/ ``` for Chocolate input, and finally ``` ___ /^ \ |^ ^| \___/ ``` for Nut input. ## Other information * This is my first challenge, it's as simple as can be. Constructive feedback is greatly appreciated. * Use any means to do so. * Trailing spaces are fine. * This is a code golf challenge, so shortest entry at the end of 9 days (Wednesday, the 12th of August 2015) wins. ## Thank you! The winner is Jakube using Pyth with 41 bytes. Thank you to all who participated. I will now task myself with coming up with more complicated challenges. [Answer] # Ruby, 73 ``` ->s{' ___ /'+['^ \ |^ ^','. .\ | . ',' \ | '][s[0].ord%3]+'| \___/'} ``` This is an anonymous lambda function. Here it is in a test program: ``` g=->s{' ___ /'+['^ \ |^ ^','. .\ | . ',' \ | '][s[0].ord%3]+'| \___/'} puts g.call(gets) ``` It just uses the first letter of the cookie type (in uppercase) and takes it modulo 3 to get an index in the range `0..2`. Then it returns the string representing the cookie, with the appropriate strings embedded in the right places. [Answer] # Pyth, ~~42~~ 41 bytes ``` X" ___ /d a\\ |cac| \___/"G.>"^X . .^"Cz ``` Try it online: [Regular Input / Test Suite](http://pyth.herokuapp.com/?code=X%22+___%0A%2Fd+a%5C%5C%0A|cac|%0A%5C___%2F%22G.%3E%22%5EX+.++.%5E%22Cz&input=Chocolate&test_suite=1&test_suite_input=Plain%0AChocolate%0ANuts&debug=0) ### Explanation: ``` "..." template string X G replace "a..z" in ^ with: Cz convert z to an integer (base 256 of ord(char)) .>"^X . .^" rotate "^X . .^" ["Plain" -> " . .^^X", "Chocolate" -> ". .^^X ", "Nuts" -> " .^^X . "] ``` [Answer] # Python 2.7.6, 99 bytes ``` def c(t):n=hash(t)%3;return" ___\n/"+" ^."[n]+" "+" ."[n]+"\\\n|"+[" ","^ ^"," . "][n]+"|\n\\___/" ``` This algorithm relies on the fact that `hash(cookie)%3` gives 0 when `cookie = "Plain"`, 1 when `cookie = "Nut` and 2 when `cookie = "Chocolate`. If anyone knows a way to make this code shorter, please let me know in the comments. [Answer] # C: 122 ``` q(char *p){char *t,*m;int i=*p%3;t=i?i%2?". .":" ":"^ ";m=i?i%2?" . ":" ":"^ ^";printf(" ___\n/%s\\ \n|%s|\n\\___/",t,m);} ``` Explanation after i finish golfing. Example of use: ``` int main(void){ q("Plain"); printf("\n"); q("Nut"); printf("\n"); q("Chocolate"); } ``` [Answer] # CJam, ~~49~~ 48 bytes ``` " ___ /""^ ^ ^. . ."S7*+6/rci=3/"\ |"*"| \___/" ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%20___%0A%2F%22%22%5E%20%20%5E%20%5E.%20.%20.%22S7*%2B6%2Frci%3D3%2F%22%5C%0A%7C%22*%22%7C%0A%5C___%2F%22&input=Chocolate). ### How it works ``` " ___ /" e# Push that string. "^ ^ ^. . ."S7*+6/ e# Push that string, append 7 spaces and split into chunks of length 6. e# This pushes ["^ ^ ^" ". . . " " "]. rci e# Read from STDIN, cast to character, then to integer. e# "Plain", "Chocolate", "Nuts" -> 'P', 'C', 'N' -> 80, 67, 78 = e# Select the corresponding element from the array. e# Arrays wrap around in CJam, so for an array A of length 3, e# A80= is A2=, A67= is A1= and A78= is A0=. 3/ e# Split into chunks of length 3. "\ |"* e# Join those chunks, using that string as separator. "| \___/" e# Push that string. ``` At the end, CJam automatically prints all elements on the stack. [Answer] # Javascript (ES6), 90 ``` s=>" ___\n/"+(s.length-4?s.length-5?". .\\\n| . ":" \\\n| ":"^ \\\n|^ ^")+"|\n\\___/" ``` This is an anonymous arrow function. It uses the length of the input to determine which cookie to draw. Explanation: ``` s=> " ___\n/" + //build the first part of the cookie (s.length - 4 ? //if the length is 4, this condition will evaluate to 0, which coerces to false. Otherwise it is true s.length - 5 ? //if the length is 5, this evaluates to false; otherwise true ". .\\\n| . " : //build the unique part of the Chocolate cookie, if length was not 5 " \\\n| " //build the unique part of the Plain cookie, if length was 5 : "^ \\\n|^ ^" //build the unique part of the Nuts cookie, if length was 4 ) + "|\n\\___/" //build the last part of the cookie, and implicitly return the built string ``` To test: ``` f=s=>" ___\n/"+(s.length-4?s.length-5?". .\\\n| . ":" \\\n| ":"^ \\\n|^ ^")+"|\n\\___/" console.log(f("Nuts")) console.log(f("Plain")) console.log(f("Chocolate")) ``` [Answer] # BrainFuck, ~~481~~ ~~447~~ 436 bytes Why not BrainFuck?, the program can probably be golfed more, but I think it's pretty neat. ``` ,>++++++[-<---------->]<-------[----------->>>-<<+<[-->->+<<]]>>>+>>++.<+++++++++[->>>>>>>++++++++++<+++++<++++++++++++++<++++++++++<+++++<++++++++++<+++<]++++++++++>+++.>+++++...>++>++>-->+>++++<<<<<<<.<<<[->>>>>>.>>>.<<<<<.>>>>>.<<.<<<<.>>>>>.<<<<.>>>>>.<<<<<.>>>>.<<<<<.>>>>.<<...>.<<<<<<]>[->>>>>.<<...>>>.<<<<.>>>>>.<<<<...>>>>.<<<<<.>>>>.<<...>.<<<<<]>[->>>>.>>>>.<<<<<<..>>>.<<<<.>>>>>.>>.<<<<<<.>>>>>>.<<.<<<<<.>>>>.<<...>.<<<<] ``` [Answer] **C# With indentation and line break** ``` using System; class Cookie { static void Main() { String E="",N="",C=Console.ReadLine(); if(C=="P"){E=" ";N=" ";} if(C=="C"){E=". .";N=" . ";} if(C=="N"){E="^ ";N="^ ^";} Console.Write(" ___ \n/" + E + "\\ \n|" + N + "|\n\\___/"); } } ``` **Golfed (225 Characters)** ``` using System;class X{static void Main(){String E="",N="",C=Console.ReadLine();if(C=="P"){E=" ";N=" ";}if(C=="C"){E=". .";N=" . ";}if(C=="N"){E="^ ";N="^ ^";}Console.Write(" ___ \n/" + E + "\\ \n|" + N + "|\n\\___/");}}[![enter image description here][1]][1] ``` [Answer] ## **C# 6, 105 bytes** So very nearly got this sub-100 bytes, no idea where to squeeze the last few bytes from though :C ``` string C(string t)=>$" ___\n/{(t[0]=='C'?". .\\\n| . ":t[0]=='N'?"^ \\\n|^ ^":" \\\n| ")}|\n\\___/"; ``` [Answer] # Pyth, ~~58~~ ~~54~~ ~~53~~ ~~52~~ 50 bytes ``` +d*\_3p+\/j"\\ |"c@["^ ^ ^"*". "3*d6)Chz3\|"\___/ ``` I don't think this can be golfed more. I was really trying to squeze this in under 50 bytes [Answer] ## JavaScript (ES6), 72 bytes About as simple as it gets… new lines are counted as 1 byte each. ``` f=s=>` ___ /${s[4]?s[5]?`. .\\ | . `:` \\ | `:`^ \\ |^ ^`}| \\___/` ``` ### Demo As it is ES6, this demo only works in Firefox and Safari for now. ``` f=s=>` ___ /${s[4]?s[5]?`. .\\ | . `:` \\ | `:`^ \\ |^ ^`}| \\___/` // Snippet stuff A.innerHTML = f("Nuts"); B.innerHTML = f("Plain"); C.innerHTML = f("Chocolate"); ``` ``` <p>Nuts</p> <pre id=A></pre> <p>Plain</p> <pre id=B></pre> <p>Chocolate</p> <pre id=C></pre> ``` [Answer] # Commodore 64 BASIC, 181 bytes ``` 10 INPUT A$ 20 IF A$="PLAIN" THEN B$="/ \":C$="| |" 30 IF A$="CHOCOLATE" THEN B$="/. .\":C$="| . |" 40 IF A$="NUTS" THEN C$="/^ \":C$="|^ ^|" 50 PRINT" ___":PRINT B$:PRINT C$:PRINT"\___/" ``` Notes: Instead of backslashes `\` the SHIFT-M characters have been used, for slashes `/` - SHIFT-N and for pipes `|` - SHIFT-T. SHIFT-Z (card diamond sign) was used for `^`. In fact characters do not matter as they all occupy one byte each. Because on C64 each command (PRINT, INPUT, THEN, etc.) takes 2 bytes in memory (or some even one, IIRC), the BASIC language was worth trying (however, it took more bytes than I expected). The program size was calculated by measuring free memory before typing the program (38909 bytes) and after (38728 bytes), using `PRINT FRE(0)+65536` command, giving 181 bytes of difference. Code tested and screenshots prepared with this tool: <http://codeazur.com.br/stuff/fc64_final/> (GPL). Screenshots: [![C64 screenshot 1](https://i.stack.imgur.com/21Zwo.png)](https://i.stack.imgur.com/21Zwo.png) [![C64 screenshot 2](https://i.stack.imgur.com/cyzS2.png)](https://i.stack.imgur.com/cyzS2.png) [Answer] # Lua 5.3, 113 Bytes 112 Bytes ``` c=io.read()print(' ___\n/'..(c=='plain'and' \\\n| 'or c=='nut'and'^ \\\n|^ ^'or'. .\\\n| . ')..'|\n\\___/') ``` It uses a lot of the ternary operator and string concatenation, and I squeezed out all whitespace that isn't part of the output itself. [Answer] ## Java 258 217 characters/bytes --- **Golfed** ``` class C{public static void main(String[] a){p(" ___");if(a[0].equals("Chocolate")) {p("/. .\\");p("| . |");}if(a[0].equals("Nut")){p("/^ \\");p("|^ ^|");}p("\\___/");}static void p(String s) {System.out.println(s);}} ``` ***Original*** ``` class C { public static void main(String[] a) { p(" ___"); if(a[0].equals("Chocolate")) { p("/. .\\"); p("| . |"); } if(a[0].equals("Nut")){ p("/^ \\"); p("|^ ^|"); } p("\\___/"); } static void p(String s) { System.out.println(s); } } ``` [Answer] # **LUA 270 characters 270 bytes** ``` c = io.read() if c == "plain" then print" ___" print"/ \\" print"| |" print"\\___/" io.read() elseif c == "chocolate" then print" ___" print"/. .\\" print"| . |" print"\\___/" io.read() elseif c == "nut" then print" ___" print"/^ \\" print"|^ ^|" print"\\___/" end ``` [Answer] ## LOLCODE 265 characters ``` HAI I HAS A T GIMMEH T VISIBLE " ___" BOTH SAEM T AN "Chocolate", O RLY? YA RLY VISIBLE "/. .\" VISIBLE "| . |" OIC BOTH SAEM T AN "Nut", O RLY? YA RLY VISIBLE "/^ ^\" VISIBLE "|^ |" OIC BOTH SAEM T AN "Plain", O RLY? YA RLY VISIBLE "/ \" VISIBLE "| |" OIC VISIBLE "\___/" KTHXBYE ``` `[Run](http://repl.it/BBgl)` ]
[Question] [ Shorten (or not) text using run length encoding **Input:** ``` heeeello woooorld ``` **Output:** ``` 1h4e2l1o 1w4o1r1l1d ``` * Read lines from stdin. * Print to stdout. * Stderr is of course discarded. * Assume there are hidden testcases (no embedding of the output) * Input/Output as ASCII * Any language is accepted [Answer] # Perl: ~~46~~ → 36 or 27 characters ~~`perl -pe's|((.)\2*)|@x=split//,$1;@x.$x[0]|eg'`~~ All hail @ardnew for coming up with the idea of using the `tr///c` operator to count the number of characters in the matched string instead of splitting: ``` perl -pe's|((.)\2*)|$1=~y///c.$2|eg' ``` Degolfed: ``` while(defined($_ = <>)) { $_ =~ s{((.)\2*)} # match 1 or more consecutive identical non-newlines { ($1 =~ y///c ) # count the number of characters in $1 . # and concatenate it $2 # with the first matched character }eg; # execute substitution, match "global" print $_; # print the modified line } ``` Usage: ``` $ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' infile ``` or via STDIN ``` $ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' heeeello ``` prints ``` 1h4e2l1o ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 28 bytes ``` {,/($#:'c),'*:'c:(&~=':x)_x} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pHX0NF2Uo9WVNHXQtIWWmo1dmqW1VoxlfUKmWkAkFOTr5CeT4QFOWkKP3/DwA "K (oK) – Try It Online") On mobile, explanation to follow... [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ûèB☼å°╤ ``` [Run and debug it st staxlang.xyz!](https://staxlang.xyz/#p=968a420f86f8d1&i=heeeello%0Awoooorld) ### Unpacked (8 bytes) and explanation: ``` m|RFNppz m For each line of input: |R Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]] F For each pair: N Uncons-left: [104,1] -> push [104]; push 1 ppz Pop and print. Pop and print. Push "". Implicit print (always an empty string) with a newline ``` ### 5 bytes, works only on a single line: ``` ∩l↨me |RmEp] Unpacked |R Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]] m Map block over input: E Explode array: [104,1] -> push 104, push 1 p Pop and print with no newline ] Make a one-element list: 104 -> [104] (which is "h") Implicit print with newline ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=ef6c176d65&i=heeeello) Perhaps not legal. This program prints each pair on a line of its own. A bit sketchy. If that output format is illegal, I give you **6 bytes**: ``` ╡δôZ→╬ |RFEp]p Unpacked F For each item in array, execute block: p Pop and print with no newline No implicit print in for-each block, so no extra newlines ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=b5eb935a1ace&i=heeeello) The language's creator [recursive](https://codegolf.stackexchange.com/users/527/recursive) points out that uncons-right (`N`) can shorten this to six bytes unpacked, as it handles the `E` and the `]` on its own. Programs this short, however, often get no shorter when packed, and this is am example. Still six bytes: [`|RFNpp`](https://staxlang.xyz/#c=%7CRFNpp&i=heeeello) Edit: Had to update my main answer; this form is what I used. [Answer] # [Scala](http://www.scala-lang.org/), ~~150~~ ~~144~~ 134 bytes ``` io.Source.stdin.getLines.map(s=>println{val(x,y,z)=s.tail./:(("",s.head,1)){case((a,b,c),d)=>if(b==d)(a,b,c+1)else(a+c+b,d,1)};x+z+y}) ``` [Try it online!](https://tio.run/##VYtBDsIgEEX3PcXEFQRC41aDiXt3nmCAscUgrR001aZnrzau/Lv38j57TLh07kq@wBFoLJQDw7HvJ6hryF2Bge6POFCAmOG85sAtpbTEzpy7x@DJcAkxm4bKKWZic8NesD30Q8wl5emJSYz6pd/SsikYk6l3Qmw2mk1LGPRWyskjkxConfZSB2kP8SKctUH@nNpKSt8ClVdOr5d5P6q3es1ymRdc55zzPtClaZrqX/xjhR8 "Scala – Try It Online") **UPDATE**: * 6 bytes saved thanks to @Kjetil S. * 10 bytes saved thanks to @user Here the pure Lambda de-golfed (97 bytes): ``` s => { val (x,y,z) = s.tail./:(("", s.head, 1)) { case ((a, b, c), d) => if (b == d) (a, b, c + 1) else (a + c + b, d, 1) } x+z+y } ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 74 bytes ``` D,g,@:,BGd€q$€bLzBFJ D,f,@,10C$t€g ]getchar y:'' Wx,`y,+x,`x,]getchar $f>y ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HwUrHyT3lUdOaQhUgkeRT5eTmxeWik6bjoGNo4KxSAhRM54pNTy1Jzkgs4qq0UlfnCq/QSajU0QaSFTpwGZU0u8r//zNSgSAnJ5@rPB8IinJSAA "Add++ – Try It Online") This could be [half the size](https://tio.run/##S0xJKSj4/99FJ13HwUrHyT3lUdOaQhUgkeRT5eTmxeWjY2jgrFICFEj/r5KTmJuUkqhgaGf//39GKhDk5ORzlecDQVFOCgA) if we could take input from the command line ## How it works The first line (the function `g`) actually performs RLE. The rest of it just reads the input char by char, passes it to a function `f`, which splits on newlines, then runs `g` on each line. `g` simply groups equal adjacent characters with `BG`, then gets the lengths (`€bL`) and deduplicates (`€q`). We then `z`ip these together, flatten, `J`oin and print. [Answer] ## J, 35 31 characters ``` ,(](":@#,{.);.1~1,2~:/\])1!:1[1 ``` Usage: ``` ,(](":@#,{.);.1~1,2~:/\])1!:1[1 heeeello 1h4e2l1o ,(](":@#,{.);.1~1,2~:/\])1!:1[1 woooorld 1w4o1r1l1d ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` |εÅγs.ιJ, ``` [Try it online.](https://tio.run/##yy9OTMpM/f@/5tzWw63nNhfrndvppfP/f0YqEOTk5HOV5wNBUU7Kf13dvHzdnMSqSgA) Or alternatively: ``` |εÅγøí˜J, ``` [Try it online.](https://tio.run/##yy9OTMpM/f@/5tzWw63nNh/ecXjt6TleOv//Z6QCQU5OPld5PhAU5aT819XNy9fNSayqBAA) **Explanation:** ``` | # Read all lines of input as list ε # For-each over the lines: Åγ # Run-length encode, pushing the list of characters and lengths separately s # Swap so the characters at at the top and lengths below it .ι # Interleave the two lists J # Join the list of characters and lengths together to a single string , # And output it with trailing newline |εÅγ # Same as above ø # Zip/transpose; creating pairs of [character, length] í # Reverse each pair to [length, character] ˜ # Deep flatten the pairs to a single list J, # Join them together to a single string, and output it with trailing newline ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->s{s.gsub(/(.)\1*/){|m|"#{m.size}"+m[0]}} ``` [Try it online!](https://tio.run/##LcZBEoIgFADQqzDfjWahHUBnPAex0AnTGRCGL2kBZycWvdWzbvqkuUu3Hj3SF7qpbEpaPe6XpvJBBSi8orh@RYRasZbHmIzbkTBYRCalhiscOrPymTv85W6aWLchOZZxRy3ewgKnajQ@nGFmJ4/pBw "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 84 bytes ``` def f(s,c=1):i,*j=s;b=j[:1]==[i];print(end='%s%s'%(c,i)*(b^1));f(j,1+b*c) f(input()) ``` [Try it online!](https://tio.run/##JcxBDoMgEADAO6/Yi2HXcqG9YXiJsU1EiBgDBDDV11OTzgMmXXWN4dVczPABH0CKp2JQ86XsaQ1yzttiHTgswmhJyot@02WY9TYqOWk9@mlI2YeKNiyad6UrvEMjPPU4vyXR4HAT8jH3hphDH9JRkajBPRMDexqbqvoP1FZ72/fIvvGW9@UH "Python 3 – Try It Online") # Explanation Checks if the first and second characters of the string are equal. If they are, increase the counter by 1. If they are not, print the counter and the first item and reset the counter to 1. In both cases, the function is called recursively with the first character removed. Raises an error when end of string is reached. --- Without I/O restrictions, but with minimal byte count: # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 70 bytes ``` f=lambda s:'%s%s'%(len(s)-len(t:=s.lstrip(p:=s[0])),p)+f(t)if s else'' ``` [Try it online!](https://tio.run/##PYhBCoMwEADvfUUQQnZpFaGXIviS4sFigoFtsmQXpK@P8dK5zDD80z2n54tLrWGm9fvZViOTs2LFWSCfQLC/pNMsA4mWyMCt3@OC@GC8B1CMwYjxJN65yiUmhQDd7htEuUO8/eeRG4W2NusJ "Python 3.8 (pre-release) – Try It Online") [Python 3 equivalent](https://tio.run/##PYq7CsMwDAD3foUJGFv0AaVbQr6kdItEDMIWlkro17vq0lsOjpOP7a0@xtiQAmWFWVZ9zvfXYqveWK0XyQJLR3v3mqJGTTEzVl@vPxlcBM7kLhQ0ICumNKSXapnytKPD3CaA0z8ezem8eRxf "Python 3 – Try It Online") (77 bytes) # Explanation Strips all repeating characters off the start of the string. Then it returns a string containing (1.) the difference in lengths between the original string and the stripped string; (2.) the first character of the original string; (3.) the result of the recursive function applied to the stripped string. Recursion ends when an empty string is encountered. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 98 bytes ``` Print[""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]]&/@StringSplit[$ScriptInputString," "] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@z@gKDOvJFpJycYuuATITHdOLE4tjlbWKbaqiNfTs7ILyYeIO0Aon9S89JIMh2Ibu4rYWDV9qGhwQU5mSbRKcHJRZkGJZ15BaQlEXEeJSyn2//@MVCDIycnnKs8HgqKcFC4jIwA "Wolfram Language (Mathematica) – Try It Online") A more flexible I/O format reduces this solution to **54 bytes**: ``` ""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@19JycYuuKQoMy/dObE4tThaWafYqiJeT8/KLiQfIu4AoXxS89JLMhyKbewqYtWAWvUdFKqVMlKBICcnX0lHQak8HwiKclJAbCMjpdr//3ULgBpLAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 2 bytes ``` e` ``` `e`` is a built-in for run-length encoding. CJam's implicit output ignores array brackets, and so turns `[[1 'h] [2 'e]]` into `"1h2e"` [Try it online!](https://tio.run/##S85KzP1fHV/wPzXhf75ffi1XtFJGak5OvkJ5flFOipKCUlJiHhACGYZGxiamZuYWlkB2RioQAFVxlecDAURhYlIyUEkqBOSDgVKs6n8A "CJam – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` m(ṁ§:osL←g ``` [Try it online!](https://tio.run/##yygtzv7/P1fj4c7GQ8ut8ot9HrVNSP///3@0UkYqEOTk5CvpKJXnA0FRTopSLAA "Husk – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 78 bytes ``` import Data.List m@main=getLine>>=putStrLn.(>>=shows.length<*>take 1).group>>m ``` [Try it online!](https://tio.run/##XccxDoAgDADA3Vc4qgOJuzYOjmy@oIkNEAslUOPz0dnbzmO9iLm1ELMU7XdUNDZU7eIWMaTVkdqQCGDNtx5abDLDl@rlqYYpOfXLBIoX9fNoXJE7A8TWPH2YpXt@pPD5Ag "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` Åγsø˜ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cOu5zcWHd5ye8/9/RioQ5OTkAwA "05AB1E – Try It Online") ``` Åγsø˜ # full program ˜ # flatten each sublist of... ø # list of all elements of... Åγ # chars and corresponding run lengths of chars in... # implicit input... ø # with each element from... s # second... ø # sublist paired with corresponding element in... s # first... ø # sublist # implicit output ``` [Answer] # JavaScript (V8), 66 bytes *-10 thanks to @Original Original Original VI* ``` r=>r.split` `.map(d=>d.replace(/(.)\1*/g,g=>g.length+g[0])).join` ` ``` My first time using `\1` in a regular expression, which is a super overpowered way to approach this problem (looks like a few answers already use it). The rest of the code is basically just I/O. [Answer] # Scala, 116 bytes ``` _ split "\n"map{def d:Seq[_]=>Any={case e+:f=>val(g,h)=f span e.== ""+e+(g.size+1)+d(h)case x=>x} d(_)}mkString "\n" ``` [Try it online!](https://scastie.scala-lang.org/Q3M5rRPKQQmxKqpZpBbfEA) Is it short? No. Does it use best practices where it wouldn't make the code longer? No. Did I do it for ethical reasons? No. Is it creative? No. Am I proud of it? Yes. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` ḅ⟨{lṫ}ch⟩ᵐc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GO1kfzV1TnPNy5ujY549H8lUDB5P//o5UyUoEgJydfSUepPB8IinJSgExHKAAy8/IVikrzihXKMxJLivNTy1KLlGIB "Brachylog – Try It Online") (If output *really* has to be on stdout, add one byte for `w` at the end.) ``` c The output is the concatenation of ⟨ c ⟩ᵐ the concatenated pairs of {lṫ} length converted to a string h and first element ḅ ᵐ for every run in the input. ``` [Answer] # [Python 3](https://docs.python.org/3/) iterative, ~~115~~ ~~99~~ 97 bytes ``` while 1: a=b='';k=0 for c in input():e=a!=c;b+=(str(k)+a)*e;k+=1-k*e;a=c print(b[1:]+str(k)+a) ``` [Try it online!](https://tio.run/##PYqxCsMgFAB3v@J1ilYKlW7K@5KQQa1FUVSMIeTrjVOPG264enVf8meM04fkQEgCGg0ui4r4JvArDSyEPK1Hp0w61A@0ynCke280Mq7Z06nIUbziDI2WQG0hd2pWITf@v8bwbpJSIWeZtPS9AQ "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/) recursive, ~~136~~ ~~130~~ 129 bytes ``` f=lambda r,c,s,k=1:s and(c==s[0]and f(r,c,s[1:],k+1)or f(r+str(k)+c,s[0],s[1:]))or r[1:]+str(k)+c while 1:print(f('','',input())) ``` [Try it online!](https://tio.run/##PcmxCsMgGATgPU/hFn90iHQTfJLgYGNE0aqoIfTprbbQ44bjvvxuNsVH70YE9XpqhQo9aKVeMF6RihofQtR9k2Mig7@4My6pJwxSmReprWAPZMomfwzTylx/XW7rwokYz8XFhg1eVzrqYr4aBoDe7TkSQlruNFKC/gA "Python 3 – Try It Online") The iterative approach seems quite successful, while the recursive version has a lot of room for improvement. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes ``` (.)\1* $.0$1 ``` [Try it online.](https://tio.run/##K0otycxLNPz/X0NPM8ZQi0tFz0AFyMtIBYKcnHyu8nwgKMpJAQA) **Explanation:** Get a part of 1 or more of the same character, capturing the character in capture group 1. ``` (.)\1* ``` Replace it with the length of the total match, concatted with the character from capture group 1: ``` $.0$1 ``` [Answer] # [Julia 1.1](http://julialang.org/), ~~94~~ ~~84~~ 81 bytes ``` foldl(((n,l),c)->(c==l||print(n,l);((c==l&&n)+1,c)),readline()*'\n',init=("","")) ``` [Try it online!](https://tio.run/##HcoxCoAwDEDRu3Soicahs9STuEhbMRJSkQoO3r1K//j4xy28uqfWLUsUAFASpIDjDMF7ed/zYi1NJ2hkreLg/gXpSmsU1gTYd4t2xMrFgzFkDGKte/oTyR8 "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `d`, 2 bytes ``` øe ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=d&code=%C3%B8e&inputs=woooorld&header=&footer=) That is, ``` øe # run length encode the implicit input # the d flag deep sums the top of the stack before outputting ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 5 bytes ``` jksr8 ``` Relatively self explanatory, just joins together Pyth's run length encode instruction Edit: -1 byte because while working on something completely different I remembered flattening a 2D list is just summing the elements. [Try it online!](https://tio.run/##K6gsyfj/PytbL6/I4v9/pYxUIMjJyVcCAA "Pyth – Try It Online") [Answer] # Bash: 104 characters ``` while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done ``` Sample run: ``` bash-4.2$ while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done <<END heeeello woooorld END 1h4e2l1o 1w4o1r1l1d ``` [Answer] ## Zsh, 117 ``` while read s;do n=1;for i in {1..$#s};do if [[ $s[i] != $s[i+1] ]];then echo -n $n$s[i];n=0;fi;((n++));done;echo;done ``` Run it like this: ``` zsh script.zsh < infile ``` ### De-golfed ``` while read s; do # while stdin has more n=1 # repeat counter for i in {1..$#s}; do # for each character if [[ $s[i] != $s[i+1] ]]; then # same as next one? echo -n $n$s[i] # print if no n=0 fi ((n++)) done echo # newline between words done ``` [Answer] ## APL (24) ``` ,↑{(⍕⍴⍵),⊃⍵}¨B⊂⍨B≠¯1⌽B←⍞ ``` [Answer] # Burlesque (17B) ``` {=[{J[-jL[Q}\m}WL {=[{^^[~\/L[Sh}\m}WL ``` Older/Alternative and longer versions: ``` {=[{^^L[Sh\/-]Sh.+}m[\[}WL {=[{^^L[Sh\/-][-.+}m[\[}WL {=[{^^L[Sh\/-~.+}m[\[}WL {=[{^^L[Sh\/-].+}\m}WL {=[{^^L[Sh\/[~.+}\m}WL {=[{^^L[Sh\/[~_+}\m}WL {=[{^^L[Sh\/fc.+}\m}WL {=[{^^L[Sh\/-~.+}\m}WL {=[{^^L[Sh\/-]\/}\m}WL ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), 19 chars This doesn't really count because I created rs *way* after this was posted...but it was fun anyway! ``` (.)(\1*)/(^^\1\2)\1 ``` [Try it here!](http://kirbyfan64.github.io/rs/index.html?script=(.)(%5C1*)%2F(%5E%5E%5C1%5C2)%5C1%0A&input=heeeello%0Awoooorld%0A) [Answer] # [Zsh](https://zsh.sourceforge.io/), 44 bytes [44 bytes: try it online](https://tio.run/##qyrO@J@moVn9PzU5I19BpVqj2MpK07C2piKxKL1YQTfPsKY0L7NQQTe5pqRIQTdFISYmL0bhfy1XmoJSRioQ5OTkx@SV5wNBUU6K0n8A). Based on [this](https://codegolf.stackexchange.com/a/1029/15940). ``` echo ${(s::)1}|xargs -n1|uniq -c|tr -d \\n\ ``` --- [70 bytes: try it online](https://tio.run/##HYlBCsMgFAX3OcVrGkRx06zVk1gXoRoU5P9iC0Ivb5PMaob5ffLoudSElraIbhB5Km7s3CAludUUre29G9JaKe@xdF8Cbu4SvQaEIMS7FfruWOi6QpB7TOmVeUSmBAsrz8Kc00Gt/KTOB63GWY0/). Based on [this](https://codegolf.stackexchange.com/a/7323/15940). ``` for ((n=1;i++<#w;n++))[[ $w[i] != $w[i+1] ]]&&printf $n$w[i]&&n=0 echo ``` ]
[Question] [ A Shift matrix is a binary matrix with one superdiagonal or subdiagonal formed by only ones, everything else is a zero. A superdiagonal/subdiagonal is a diagonal parallel to the main diagonal, which is not the main diagonal, i.e. all entries \$a\_{ij}\$ where \$i=j+k\$ and \$k \neq 0\$. The main diagonal is defined to be all entries \$a\_{ij}\$ where \$i=j\$. ## Specs * The matrix is *not* guaranteed to be square and will consist of only zeros and ones * Take a nested list or a matrix as the input * Output a truthy/falsy result or use two distinct values to represent truthy and falsy results * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer wins! ## Examples ``` [[1]] -> 0 [[0, 1], [0, 0]] -> 1 [[0, 0, 0], [1, 0, 0], [0, 1, 0]] -> 1 [[0, 1, 0], [1, 0, 0], [0, 0, 0]] -> 0 [[0, 1, 0], [0, 0, 1]] -> 1 [[0, 0], [0, 0]] -> 0 [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0]] -> 0 [[1, 1], [1, 1]] -> 0 [[0,1,0,0], [1,0,1,0], [0,1,0,1], [0,0,1,0]] -> 0 [[0,1,0], [1,0,0], [0,1,0]] -> 0 [[0,1,0], [0,0,1], [1,0,0]] -> 0 [[1,0,0], [0,1,0]] -> 0 [[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [1,0,0]] -> 1 [[1,0,1], [0,1,0], [0,0,1]] -> 0 [[0,1,0], [1,0,0]] -> 0 ``` [Answer] # [J](http://jsoftware.com/), 37 bytes ``` 1=1#.([:(+./*[:*/%)/.|."1),_*<@0 1|:] ``` [Try it online!](https://tio.run/##hY/PDoIwDMbvPEVF5M/AjmJiwuIM0cST8eCVLB6MRL34Arw7FhYiJETSdFvX376vezf5QpHZLlQeBI6LQQVaQQAJpKA41wjH6/nUkKYlhqUKY5SiVEKuIok1uhQlN7ErUqBamSZyLgeEjmU000LGe5RMlqplTWyElv4LZeH9yLCV68WM8JMZpHdzHvfnh0fUUMGGw@MzcXYLb101hBIkW1aQcVi@Ze0tjZTSf0rTdukMRCMla5cNoVaChhK2SzPd6RntF/uXzRc "J – Try It Online") *Thanks to AndrovT for catching a bug* * `,<@0 1|:]` Append `,` items along [main diagonal](https://www.jsoftware.com/help/dictionary/d232.htm) (works for non-square) multiplied by infinity to... * `([:(+./*[:*/%)/.|."1)` Product of reciprocals of every diagonal, multipled by "is there at least a single 1". This will return 1 for all ones, infinity for partial ones, and 0 for all zeros. To get the diagonals, we combine J's built-in for anti-diagonals `/.` with a flip about the y-axis `|."1`. * `1#.` Sum of those catted lists * `1=` Is the sum 1? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒDµẒ¬ṛ¦ⱮJḊċ ``` A monadic Link that accepts a matrix of ones and zeros and yields `1` if it's a shift matrix or `0` otherwise. **[Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/umnRozcOdsw8te7RxndfDHV1Huv///x8dbaCjAEWxOlwK0YaoXCDDEIzgXAMoNxYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJJdDWx/umnRozcOdsw8te7RxndfDHV1Huv8fbn/UtOb//2iu6GjD2FgdLiBtoKNgCGQpgBgGCDEwDyRsiMQGqUVRZYhDlQF2VRAZJJsNcNiMZiyayWjGIXQbwvxiiGKLIYaJhmg@Qg4DYv0IUxULAA "Jelly – Try It Online"). ### How? Constructs all diagonalised representations of shift matrices of the same dimensions as the input and counts occurrences of a diagonalised version of the input. ``` ŒDµẒ¬ṛ¦ⱮJḊċ - Link: matrix of [0,1], M e.g. [[0,1,0],[0,0,1],[0,0,1]] ŒD - diagonals (main first) [[0,0,1],[1,1],[0],[0],[0,0]] µ - start a new monadic chain - f(D=those diagonals) Ẓ - is prime? (D) (used as a zero-all entries function) J - (set the right argument to) range of length (D) Ɱ - map with: ¦ - sparse application (to elements of D)... ṛ - ...at indices: right argument (i.e. one of [1..length(D)]) ¬ - ...apply: logical NOT (making that single diagonal all ones) Ḋ - dequeue (removing the only non-shift matrix (main diagonal one)) ċ - count occurrences of (D) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` m=>m.every((r,y)=>r.every((c,x)=>+m?x-y==m==c:c?m=x-y:1))*m ``` [Try it online!](https://tio.run/##hZBNDoMgEIX3PQVLaFGZrQY9iHFhKDZtRBpsjJ6eWsWa1r8V883MexPeI2/yWpj78@VV@iptwa3isfJlI02HsaEd4bGZUNC2x4tKWq/jXHEuQpEo3lMIhJyVFbqqdSn9Ut9wgdMUsoyQCAUBYqf/GaMIKGIZRenndSVz5a7uu3mwNtvCD7EVgn27fgzOaP9TQBl1JwcYLwwwlmP3wGIymOUbChKtBrsICLYCWuYPhzr4TW5etm8 "JavaScript (Node.js) – Try It Online") Output falsy (`0`, `-0`, `NaN`) if input is not a shift matrix, output truthy (\$k\$) otherwise. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ÞD₌~aḢ~AẊ₃ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnkTigox+YeG4on5B4bqK4oKDIiwiIiwiW1swLCAxXSwgWzAsIDBdXSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiw55E4oKMfmHhuKJ+QeG6iuKCgyIsIiIsIltbMV1dXG5bWzAsIDFdLCBbMCwgMF1dXG5bWzAsIDAsIDBdLCBbMSwgMCwgMF0sIFswLCAxLCAwXV1cbltbMCwgMSwgMF0sIFsxLCAwLCAwXSwgWzAsIDAsIDBdXVxuW1swLCAxLCAwXSwgWzAsIDAsIDFdXVxuW1swLCAwXSwgWzAsIDBdXVxuW1swLCAwLCAwLCAwXSwgWzEsIDAsIDAsIDBdLCBbMCwgMCwgMCwgMF0sIFswLCAwLCAxLCAwXV1cbltbMSwgMV0sIFsxLCAxXV1cbltbMCwxLDAsMF0sIFsxLDAsMSwwXSwgWzAsMSwwLDFdLCBbMCwwLDEsMF1dIl0=). ``` ÞD # list of all diagonals ₌ # apply the next two elements in parallel: ~a # filter by Any Ḣ # remove head (removes the main diagonal) ~A # filter by All # Now the stack has the the list of diagonals that have at least one 1 and list of all sub/superdiagonals that don't contain 0 Ẋ # cartesian product ₃ # is length equal to 1? ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` &fyh!dt&=bd1=v ``` Outputs a [truthy or falsy](https://codegolf.stackexchange.com/a/95057/36398) column array. [Try it online!](https://tio.run/##y00syfn/Xy2tMkMxpUTNNinF0Lbsv716SVFpSUaleq16WmJOcaV67P9oAwUwtFYwhDEMkBlA0VgA "MATL – Try It Online") (includes truthy/falsy test; delete footer to see actual output). Or [verify all test cases](https://tio.run/##y00syfmf8F8trTJDMaVEzTYpxdC27L@9eklRaUlGpXqtelpiTnGleiyXS8j/aMNYrmgDBUNrBQMFAzATCK0VDCGUAYgBUYAiaoAsCuJCTDFAMQWuA64HrhqsyBBkqyFUqyFCvSHcZqizwOoB). ### How it works Consider `[0 0 0 0; 1 0 0 0; 0 0 0 0; 0 0 1 0]` as example input. ``` &f % Implicit input. Two-output find: row and column indices of non-zeros % STACK: [2; 4], [1 ;3] yh % Duplicate from below. Concatenate horizontally % STACK: [2; 4], [1 2; 3 4] ! % Transpose % STACK: [2; 4], [1 3; 2 4] d % Vertical onsecutive differences % STACK: [2; 4], [1 1] t&= % Duplicate. All pairwise equality comparisons % STACK: [2; 4], [1 1], [1 1; 1 1] bd % Bubble up third-topmost entry. Consecutive differences % STACK: [1 1], [1 1; 1 1], 2 1= % Equal to 1?, element-wise % STACK: [1 1], [1 1; 1 1], 0 v % Concatenate vertically, converting to column vectors if non-matching sizes % STACK: [1; 1; 1; 1; 1; 1; 0] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 72 bytes ``` A=>A.map((B,i)=>B.map((C,j)=>N-=i*j?A[i-1][j-1]-C&&9:i-j?C:2*C),N=1)&&!N ``` [Try it online!](https://tio.run/##dY67DoIwGIV3ngKXpiUtad3U/BDozsTWdCAIpg1SIsbw9hXEQUxYTs7lG46tXtVYP8zwZL27Nr4Fn0GSxfdqwDinhkCSr0FSO4eCgYlsminDhFZ2FiYROp0Ns6k8HyNJaAGCIHQo/KWECZLa9aPrmrhzN9ziiZAgKLFSQuvwazkNhaZBuBi@qT/Fsogfv@D/oNgB@S64jtsXfPPCvwE "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εI˜d·«NFÀ]øJ2мõK€SDPsOĀ+ćÌL¢J ``` Outputs a 05AB1E truthy/falsey result (only `1` is truthy in 05AB1E): `01` if truthy; anything else (e.g. `0000`, `20`, `11`, `0100`, etc.) if falsey. [Try it online](https://tio.run/##yy9OTMpM/f//3FbP03NSDm0/tNrP7XBD7OEdXkYX9hze6v2oaU2wS0Cx/5EG7SPth3t8Di3y@v8/OtpAx1DHIFYnGkgC6dj/urp5@bo5iVWVAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU@l1aLcOl5JjcklpYg5c2L7S9tBKpf/nth5ad3pOyqHth1b7uR1uiD28w8vowp7DW70fNa0Jdgko9j/SoH2k/XCPz6FFXv@V9MKU/EtLoAa42GcqKWiUFJWWZFRqKh1eDeSkJeYUpwI5tTqHttn/j46ONoyN1VGIjjbQMYzVAZIGMC6IqRNtCKWB0ggpQzQpA3QpkBDcXAMMcxHaEQYg9MGUGoJdZIgwyBBJpyHCVTCH43OhIXYXwpRA7cOiGtmLuGk0UwzhpqAFBbKzYmP/6@rm5evmJFZVAgA). **Explanation:** 05AB1E lacks a builtin to get all (anti-)diagonals, so the first 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) of the code is to do just that.. Step 1: Get a list of all diagonals, starting with the main diagonal: ``` ε # Map over each row of the (implicit) input-matrix: I˜ # Push the input-matrix again, and flatten it d # Transform every 0 to a 1 as well, so we have a list of 1s · # Double each to a list of 2s « # Merge it to the current row NF # Loop the 0-based map-index amount of times: À # Rotate the row-list once towards the left ] # Close both the inner loop and outer map ø # Zip/transpose; swapping rows/columns J # Join each inner row together 2м # Remove all 2s in every string õK # Remove all empty strings from the list €S # Convert each inner string back to a list of digits ``` For a matrix `[[a,b,c],[d,e,f],[g,h,i]]`, the order of the list of diagonals will be `[[a,e,i],[b,f],[c],[g],[d,h]]`. [Try just step 1 online.](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU@l1aLcOl5JjcklpYg5c2L7S9tBKpf/ntnqenpNyaPuh1X5uhxtiD@/wMrqw5/BW70dNa4L/K@mFKblkJqbn5yXmFIP0HF6vc2ib/f/o6GjD2FgdhehoAx3DWB0gaQDjgpg60YZQGiiNkDJEkzJAlwIJwc01wDAXoR1hAEIfTKkh2EWGCIMMkXQaIlwFczg@FxpidyFMCdQ@LKqRvYibRjPFEG4KWlAgOys29r@ubl6@bk5iVSUA) Step 2: Check whether it's a valid Shift Matrix, so there is exactly one diagonal consisting solely of 1s without any 1s in another diagonal, and it's not the first main diagonal: ``` D # Duplicate the list of diagonals P # Get the product of each, to check which diagonals consists solely of 1s s # Swap so the list of diagonals is at the top again OĀ # Sum and Python-style truthify (!=0), to check which diagonals contain a 1 + # Add the two list of checks together ć # Extract the head; push remainder-list and first item separately Ì # Increase this first item (check of the main diagonal) by 2 L # Pop and push a list in the range [1,value] ¢ # Count for each value in this list how many times it occurs J # Join these counts together # (after which the result is output implicitly) ``` [Try both steps online, with added debug-lines.](https://tio.run/##fVA/S8NAFN/7KY4stfQCuYIIQgnFIFiLLTqGDGdybQIxKclFjFAoLi7uLk5uUsGpKuiUdBPEz@AXie9s0pS2miF37/3@vN87P6SnDsvOpV7AOI/lYeB4nFnI8YYR30USjtvJG65ILZNH1F201biZPGSS5tCB71E3FK3P6cHHnZW8JJOj/XQ8GqWv7cbXezo9/L56PEmfmhWY4VuRyZHfR4yaNrJyuVBrPSC0vHgDKD5JDbuzsaBYFsTj/oBxmwVzEOWUOuAdJ5wPuOABNcUqNqMWqqOGmDK7Tm86miqhrWN2Rh3PYoHsgkJgoaaG1RrsuudHHg9hVwQjULBGTO5hTjfi@VO0NdUBQx5E3I5rUjqBog9vwqAY4Sx5VqvyznZ6i@GW6bpODAMjXVcwMTD8laIUV6yT/AS4hMgKpKxCorXwVdZ8S3lpUOoKKvlNREojsqQkZaoi@H8JyeaEBSWft4G9vOLf54oLWbisPMVyLMPIZNnzZZdexj8) [Answer] # [R](https://www.r-project.org), ~~76~~ ~~69~~ 66 bytes *Edit: -3 bytes thanks to pajonk* ``` \(m)all(d<-diff(t(which(m>0,T))),d==max(dim(m)-sum(m))*sign(d[1])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH6zGK94ozMtJLcxJKizArbpaUlaboWN51iNHI1E3NyNFJsdFMy09I0SjTKMzKTMzRy7Qx0QjQ1NXVSbG1zEys0UjJzgSp1i0tBlKZWcWZ6nkZKtGGspibEpFuMPKg2aECpZA1DTR1DHUNNTQVlBTcuXIoMgGq4ODkVFBQMdAw0dYx0jMAaQvBoAEGIFkMkNsggoAHGOsYEDTAkxgD8TkZoAvJAzoZqggTKggUQGgA) [Answer] # [Python](https://www.python.org), 138 bytes ``` lambda d:any(i for i in range(-len(d)-len(d[0]),len(d)+len(d[0]))if all(d[j][k]==(j-k==i)for j in range(len(d))for k in range(len(d[0])))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY9BDoIwEEX3nGISN22kSbszJvUi2EUNVAu1EoILruAV3LDBO3kOLyBtiQjKaqZ__vv5vT_Kpj5dbNsp4LDvrrUim-fNyPMhlZBupW2QBnWpQIO2UEl7zBAxmUUpDiOhAsdBWH8ErBVIY_pHLpJCcI5yUnCusUvKx6TAebWYqT4G46HRq6y0rZFCScJEf4AVkB3QKBp1GgMTcQRuoc7jLWxm8UfnYl-7QwcI_lJsgaIT6qfO1MmW8-mk-JAWvt62Yb4B) [Answer] # PHP, 139 bytes ``` fn($m)=>$m[0][0]?!1:(count($f=array_merge(...array_map(fn($v)=>array_keys($v,1),$m)))>1?$f==range(min($f),max($f)):end($m)[0]||end($m[0])); ``` [Try it online!](https://tio.run/##fVLdaoMwFL73Kc7AiwSCNbd11geRUEKb1LHFhkTLyrpndydqa9dmAyHnO@f7ORptY4fXyjY2SdJO@c5DCXUCUNdcCAarFWj54VUytnIGXLBQYpXP8871y3jsBwbU/BcK0j80/B/NXc7DHo80Hl3njhK1ia78tMFTVtSOX78OTGUkj7OcLWEjvhmP@IammVgcRIE3FG5n0C1JDS03qalzgU/1wtdkd@zbjqS6lM7J89Yod1Aky7IZSkuC7ISyqfOuzh4x45ShGaUbXqG4dLJFnXlDrqbMyM9w0rVq9yETwy6XqcaS0mLQR6fkrgEy/zzSA/LgC9/iJN123xtLUh@0tEi@hx8 "PHP – Try It Online") **Ungolfed** ``` fn($m) => $m[0][0] ? !1 : (count($f = array_merge(...array_map(fn($v) => array_keys($v, 1), $m))) > 1 ? $f == range(min($f), max($f)) : end($m)[0] || end($m[0])); ``` [Answer] # [Julia 1.0](http://julialang.org/), 118 bytes ``` using LinearAlgebra ~A=((m,n)=size(A);X=map(i->diag(A,i),1-m:n-1);!i=sum(all.(==(i),X));A[1]<1&&!1>0&&!0==length(X)-1) ``` [Try it online!](https://tio.run/##jU@9asMwEN79FBcCQQK76NaoCjVk7NTJEDJcW9VRkN0gycV0yKu7MnVETRIoB3fD93vHzhrCfhg6b9oank2ryZW21q@OsnOpGGvylitvvjUruaxUQydmis27oZqVueE5Fs26LZDLhVG@axhZ@8CUYhGqOJflDvePuFotcCPiFkpZ3dbhwCoeRcMTea9dgPNOAIKQ4xqPGGcPSsEHWa@zxHPaH@ikWbTN1znyRIElvPxigFv40m/h0wF5wB6hoeBMn83C5BQQXKdniJjVwKnGFe1fbS@8kYC3fYS8r/1bJuUkvzsyjL/hlHazzsUS04dRcW05/AA "Julia 1.0 – Try It Online") The function `~A` returns `true` if `A[1,1]` is not 1 (main diagonal check), one diagonal contains all 1's, and all but one diagonal contains all 0's. Otherwise, it returns `false`. The intermediate value `X` is a vector of all `A`'s diagonals, and the intermediate function `!i` determines if all elements in a diagonal equal the value `i`. Note: As in [a somewhat related answer](https://codegolf.stackexchange.com/a/253819/114865), `LinearAlgebra` is imported only for the function `diag(A,k)`, which returns the `k`th diagonal of A. If the diagonal `k` doesn't exist, no error results, but an empty set is returned. If these are filtered out, the bounds don't need to be specified precisely; using the range `-9:9` would work for all test cases and eliminate the need for calculating `size(A)`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` WS⊞υι≔ΣEυ⁻⌕Aι1κθ¿⌈θ¿⁼⌈θ⌊θ¬№ΣEυ⁻⌕Aι0κ⌈θ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfPl2dk5qQqaHjmFZSWBJcUZeala2hqKgSUFmdolOooZGpaczkWF2em52kEl-Zq-CYWgER9M_NKizXcMvNSHHNyNDJ1FJQMlTR1FLI1NYFkIVBLZpoCUG1FZi5QTyHQOBDftbA0MacYSRhsDkwJ0Eqg3SUafvklGs75pUAWXvsMEPYh2aOpab2kOCm5GOq55dFKumU5SrFrDAwMuAyB2MDQgAsiBQA) Link is to verbose version of code. Takes input as a list of newline-terminated binary strings and outputs a Charcoal boolean i.e. `-` for a shift matrix, nothing if not. Explanation: ``` WS⊞υι ``` Input the matrix. ``` ≔ΣEυ⁻⌕Aι1κθ ``` Find the diagonals of all of the `1`s in the matrix. ``` ¿⌈θ ``` If there is at least one `1` not on the main diagonal\*, and ... ``` ¿⁼⌈θ⌊θ ``` ... if all of the `1`s are on the same diagonal, ... ``` ¬№ΣEυ⁻⌕Aι0κ⌈θ ``` ... check whether there are any `0`s on that diagonal. \*Strictly speaking this tests that either at least one `1` is above the diagonal or there are `1`s that are only below the diagonal. ]
[Question] [ Consider the \$4\$ divisors of \$6\$: \$1, 2, 3, 6\$. We can calculate the harmonic mean of these numbers as $$\frac 4 {\frac 1 1 + \frac 1 2 + \frac 1 3 + \frac 1 6} = \frac 4 {\frac {12} 6} = \frac 4 2 = 2$$ However, if we take the \$6\$ divisors of \$12\$ (\$1, 2, 3, 4, 6, 12\$) and calculate their harmonic mean, we get $$\frac 6 {\frac 1 1 + \frac 1 2 + \frac 1 3 + \frac 1 4 + \frac 1 6 + \frac 1 {12}} = \frac 6 {\frac {28} {12}} = \frac {18} {7}$$ [Ore numbers](https://en.wikipedia.org/wiki/Harmonic_divisor_number) or harmonic divisor numbers are positive integers \$n\$ where the harmonic mean of \$n\$'s divisors is an integer, for example \$6\$. They are [A001599](https://oeis.org/A001599) in the OEIS. The first few Ore numbers are ``` 1, 6, 28, 140, 270, 496, 672, 1638, 2970, 6200, 8128, 8190, ... ``` Point of interest: this sequence contains all the [perfect numbers](https://en.wikipedia.org/wiki/Perfect_number) (see [Wikipedia](https://en.wikipedia.org/wiki/Harmonic_divisor_number#Harmonic_divisor_numbers_and_perfect_numbers) for a proof). --- This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You may choose which of the following three options to do: * Take a positive integer \$n\$ and output the first \$n\$ Ore numbers. * Take a positive integer \$n\$ and output the \$n\$th Ore number. + You may use 0-indexing (so non-negative input) or 1-indexing, your choice * Take no input, and output the never ending list of Ore numbers. Note that your answer cannot fail due to floating point errors. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Factor](https://factorcode.org/) + `lists.lazy math.primes.factors math.unicode`, ~~69~~ 65 bytes ``` [ 1 lfrom [ divisors [ length 1 ] keep n/v Σ mod 0 = ] lfilter ] ``` [Try it online!](https://tio.run/##JYwxEsIgEEWv8k@AxlLH2rGxcawyKRiyGMYFIpA48TrexyshkW7//@@tlir5kG/X8@W0B5uYomD5XuoJK9MgxmAsRaH/aESk50ROUcSDgiOu0Ex1XQPGQCktxXOprpMzyveEQ27RgHXwFi16M5u4Si2Y3L2IDbrylUa4zYzvB9b32OJYWtaGEwV0WUlmNDvElxzBST6o@GJFSKoh/wA "Factor – Try It Online") It's a quotation that returns an infinite lazy list of the harmonic divisor numbers. ## Explanation * `1 lfrom` an infinite lazy list of natural numbers * `[ ... ] lfilter` select numbers for which the quotation returns `true` * `divisors` get the divisors of a number (e.g. `6 divisors` -> `{ 1 2 3 6 }`) * `[ length 1 ] keep` (e.g. `{ 1 2 3 6 } [ length 1 ] keep` -> `4 1 { 1 2 3 6 }`) * `n/v` divide number by vector (e.g. `1 { 1 2 3 6 } n/v` -> `{ 1 1/2 1/3 1/6 }`) * `Σ` take the sum * `mod 0 =` is it a divisor? [Answer] # [Raku](http://raku.org/), 46 bytes ``` grep {{@_%%sum 1 X/@_}(grep $_%%*,1..$_)},^∞ ``` [Try it online!](https://tio.run/##K0gtyjH7r1ecWKmQll@koPE/vSi1QKG62iFeVbW4NFfBUCFC3yG@VgMsrAIU1NIx1NNTides1Yl71DHvv2Z0nHnsfwA "Perl 6 – Try It Online") This is a lazy infinite sequence of the harmonic divisor numbers. [Answer] # [R](https://www.r-project.org/), ~~55~~ 52 bytes *-3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` while(F<-F+1)(1/mean(1/(y=1:F)[!F%%y]))%%1||print(F) ``` [Try it online!](https://tio.run/##K/r/vzwjMydVw81G103bUFPDUD83NTEPSGlU2hpauWlGK7qpqlbGamqqqhrW1BQUZeaVaLhp/v8PAA "R – Try It Online") Prints Ore numbers infinitely. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes ``` ÆDpWSḍ/µ# ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLDhkRwV1PhuI0vwrUjIiwiIiwiMTIiLFtdXQ==) This is horribly scuffed because I couldn't figure out how to get it working with precision. I had the same idea as ovs it turns out, but `ÆDÆmḍµ#` fails due to precision issues. I honestly hate how this is written. ``` ÆDpWSḍ/µ# Main Link µ# nfind; return first n values satisfying: ÆD divisors of n p cartesian product with W [n] (returns [[a, n], [b, n], ...]) S sum (returns [divisor sum, divisor count * n]) ḍ/ reduce by divisibility check ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes ``` for(n=1,oo,numdiv(n)*n%sigma(n)||print(n)) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPP1lAnP18nrzQ3JbNMI09TK0@1ODM9NxHIrKkpKMrMKwGyNP//BwA "Pari/GP – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ 40 bytes -2 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)! ``` Do[Mean@Divisors@n∣n&&Print@n,{n,∞}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lP9o3NTHPwSWzLLM4v6jYIe9Rx@I8NbWAosy8Eoc8neo8nUcd82pj//8HAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` Nθ≔⁰ηWθ«≦⊕η≔Φ⊕η∧κ¬﹪ηκζ¿¬﹪×ηLζΣζ≦⊖θ»Iη ``` [Try it online!](https://tio.run/##TY7BCsIwDIbP21PkmEIFL552GoowcEPQF6hbXcvabm6twsRnry0OXE4J35/kqwUb654p7wszOFs5feMjPkiW5tMkW4NbCiJMLyEVhwDgnSYlGxZamHrkmhvLm18uWcBRKhsOrTgKQiE3DXYUqt5i2TdO9SgodCQUhTmuyzvgil6l5lPMnLhprcA5Bi9Ox4YQ@Isc@Eok6n/S8yiNxT2bbHhNMu93fvNUXw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the 1-indexed `n`ᵗʰ Ore number. Explanation: ``` Nθ ``` Input `n`. ``` ≔⁰η ``` Start looking for Ore numbers greater than zero. ``` Wθ« ``` Repeat until the `n`ᵗʰ number has been found. ``` ≦⊕η ``` Try the next integer. ``` ≔Φ⊕η∧κ¬﹪ηκζ ``` Get its factors. ``` ¿¬﹪×ηLζΣζ ``` If the harmonic mean is an integer, then... ``` ≦⊖θ ``` Decrement the count of remaining Ore numbers to find. ``` »Iη ``` Print the found Ore number. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~71~~ 56 bytes ``` 1.step{|n|k=0;(1..n).count{|x|n%x<1&&k+=1r/x}%k>0||p(n)} ``` [Try it online!](https://tio.run/##KypNqvz/31CvuCS1oLomrybb1sBaw1BPL09TLzm/NK@kuqaiJk@1wsZQTS1b29awSL@iVjXbzqCmpkAjT7P2/38A "Ruby – Try It Online") * Saved 15 thanks to @G B lots of golfs Outputs the sequence indefinitely. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 1Æd×ọÆsƲ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/wcFvK4ekPd/cebis@tkn5P1DECAA "Jelly – Try It Online") More boring than the other answer: ``` Implicit input: an integer z. 1 Ʋ# Count up from 1, finding z numbers for which... Æd× divisor_count(n) × n ọ is divisible by Æs divisor_sum(n). ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 248 bytes ``` mod H is pr LIST{Rat}. ops o h : Rat ~> Rat . var A B C D : Rat . eq o(A)= o(2 A). eq o(s A 0)= A . eq o(A s B)= o(s A(B + ceiling(frac(h(A A 0 0))))). eq h(A s B C D)= h(A B(0 ^(A rem s B)/ s B + C)(0 ^(A rem s B)+ D)). eq h(A 0 C D)= D / C . endm ``` The result is obtained by reducing the `o` function with the zero-indexed input \$n\$. ### Example Session ``` Maude> red o(0) . --- 1 result NzNat: 1 Maude> red o(1) . --- 6 result NzNat: 6 Maude> red o(2) . --- 28 result NzNat: 28 Maude> red o(3) . --- 140 result NzNat: 140 Maude> red o(4) . --- 270 result NzNat: 270 Maude> red o(5) . --- 496 result NzNat: 496 Maude> red o(6) . --- 672 result NzNat: 672 Maude> red o(7) . --- 1638 result NzNat: 1638 Maude> red o(8) . --- 2970 result NzNat: 2970 Maude> red o(9) . --- 6200 result NzNat: 6200 Maude> red o(10) . --- 8128 result NzNat: 8128 Maude> red o(11) . --- 8190 result NzNat: 8190 ``` ### Ungolfed ``` mod H is pr LIST{Rat} . ops o h : Rat ~> Rat . var A B C D : Rat . eq o(A) = o(2 A) . eq o(s A 0) = A . eq o(A s B) = o(s A (B + ceiling(frac(h(A A 0 0))))) . eq h(A s B C D) = h(A B (0 ^ (A rem s B) / s B + C) (0 ^ (A rem s B) + D)) . eq h(A 0 C D) = D / C . endm ``` Maude has built-in support for rational arithmetic, so we just compute the harmonic mean of the divisors with `h`. Then, `ceiling(frac(h(...)))` will be `0` if `h(...)` is a natural number or `1` otherwise. Also, note that in Maude `0 ^ 0 == 1` and `0 ^ X = 0` for `X =/= 1`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ¡♪♫ö╪ü♣↕¥Vv ``` [Run and debug it](https://staxlang.xyz/#p=ad0d0e94d88105129d5676&i=) Runs an infinite loop with no input. [Answer] # [Zephyr](https://github.com/dloscutoff/zephyr), 151 bytes ``` set n to 1 while 1=1 set s to 0 set c to 0 for d from 1to n if(n mod d)=0 set s to(/d)+s inc c end if next if((c/s)mod 1)=0 print n end if inc n repeat ``` [Try it online!](https://tio.run/##PY1LCgMhEAX3fYq3VLKY8QBzmKAt05BpRYV8Lm@mE5JdUbzivbjuzzZn5wHFKAh03@XGCFsgk93k@sH4xVwaEnIrB8IplCQ7xVESkt/Wf@SW5C@dRCMisSZIJuXHsLmLS/dWBCtqEz3ffyMrlBpXvo453w "Zephyr – Try It Online") Uses the output-infinitely strategy; you'll need to kill the program before 60 seconds in order to see any output. ### Ungolfed ``` # Start from 1 set num to 1 # Loop forever while true # Calculate the sum of the reciprocals of the divisors # and also the total number of divisors set reciprocalSum to 0 set divisorCount to 0 for divisor from 1 to num if (num mod divisor) = 0 set reciprocalSum to reciprocalSum + (/ divisor) inc divisorCount end if next # Print the number if the divisor count divided by the # divisor-reciprocal sum is an integer if ((divisorCount / reciprocalSum) mod 1) = 0 print num end if # Go to the next number inc num repeat ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 22 bytes ``` 1`ĐðĐĐΠ⇹/Ʃ⇹Π|?ŕĐƥ:ŕ;⁺ł ``` [Try it online!](https://tio.run/##AS8A0P9weXT//zFgxJDDsMSQxJDOoOKHuS/GqeKHuc6gfD/FlcSQxqU6xZU74oG6xYL//w "Pyt – Try It Online") Prints Ore numbers forever. ``` 1 Push 1 ` ł Do... while top of stack is truthy Đ Đuplicate ð Get list of ðivisors ĐĐ Đuplicate twice Π Get product ⇹ Swap top two elements on stack / Divide Ʃ Ʃum ⇹ Swap top two elements Π|? Does the sum divide the product cleanly? ŕĐƥ If so, ŕemove the boolean, Đuplicate, and ƥrint :ŕ Otherwise, ŕemove the boolean ;⁺ Either way, increment ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` î∙─‼Σ£î*\÷╛p∟ ``` Outputs indefinitely. [Try it online.](https://tio.run/##ASgA1/9tYXRoZ29sZv//w67iiJnilIDigLzOo8Kjw64qXMO34pWbcOKIn///) (You do have to manually cancel it during runtime to see output apparently, before it times out after 60 seconds..) **Explanation:** ``` ∟ # Do-while true without popping: î # Push the 1-based loop-index ∙ # Triplicate it ─ # Pop the top, and get a list of its divisors ‼ # Apply the following two commands separately: Σ # Sum the divisors-list £ # Get the length of the divisors-list î* # Multiply the length by the 1-based loop-index \ # Swap the top two values on the stack ÷ # Check that the length*î is divisible by the sum ╛ # If this is truthy: p # Pop the remaining copy of the index, and print it ``` [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` n=0 while 1:n+=1;a=[i for i in range(1,n+1)if n%i<1];n*len(a)%sum(a)or print(n) ``` [Try it online!](https://tio.run/##DcqxDkAwFAXQ3Ve8RdKqwYsN/RIxdGh5CZdURXx9dTrLub60nehzhu2qd5PdEw8wlkdnZ6FwRhISUHRYveIWhrUEQi0TLyOa3UM5Xd/PUSj5ioKkoHP@AQ "Python 3 – Try It Online") Outputs indefinitely. [Answer] # [JavaScript (V8)](https://v8.dev/), 63 bytes Prints the sequence forever. ``` {for(n=0;;s%t||print(n))for(k=++n,t=s=0;k;)n%k--||(s+=n,t-=~k)} ``` [Try it online!](https://tio.run/##FcnBCoAgDADQrxEcNugYyD5GgsAGS3R4yfr1Zdf3ztRT22suin0zu4@reqE1xuZ0jFKzqBeAn5lCkEWpzeYI4hhxDN8CTUV6GR6zDw "JavaScript (V8) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` fo§¦ṁ\LḊN ``` [Try it online!](https://tio.run/##AR4A4f9odXNr/@KGkTjigoH/Zm/Cp8Km4bmBXEzhuIpO//8 "Husk – Try It Online") (header outputs the first few elements to avoid timing-out) ``` N # from the infinite list of integers fo # output those for which ṁ\ # the sum of the reciprocals of their divisors §¦ # exactly divides LḊ # the length (number) of their divisors ``` [Answer] # Scala, 111 bytes ``` Stream.iterate(1:BigInt)(_+1)filter{n=>val d=n to(1,-1)filter(n%_<1) val p=d.product p*d.size%d.map(p./).sum<1} ``` [Try it online!](https://scastie.scala-lang.org/Nn84cmH0QvKcXgqUkraZlA) Returns an infinite `Stream`. ## Scala, 92 bytes ``` Stream from 1 filter{n=>val d=1 to n filter(n%_<1) val p=d.product p*d.size%(0/:d)(_+p/_)<1} ``` [Try it online!](https://scastie.scala-lang.org/fj1Gm8mcStWejSHSpOJSIg) This one uses normal `Int`s, evading some of the boilerplate above, but it only generates the first three elements correctly due to integer overflows. [Answer] # Python 3, 94 bytes ``` v=0 while 1:p=q=1;v+=1;-~len([(p:=p*d+q,q:=q*d)for d in range(2,v+1)if v%d<1])*q%p or print(v) ``` [Try it online!](https://tio.run/##Dco7CsMwDADQPafQEvAnhbhdgludpHQo2EkMQZFMUOnSq7tZ3vT4e6w73SaurSmO3WctW4YQGQXDXf3J5bdlMk/DEdklL4NEFJfsvFdIUAjqm5ZsroP6YMsM2qdHeFknPcNZuBY6jNrW/g "Python 3.8 (pre-release) – Try It Online") Outputs indefinitely. This is otherwise like (my edit to) @Jitse's answer, but computes the sum of the reciprocals `p/q` exactly as a pair of (big)ints `(p,q)`. [Answer] # [Vyxal 2.6.1](https://github.com/Vyxal/Vyxal), 5 bytes ``` ≬KṁḊȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiaxL4bmB4biKyK8iLCIiLCI4Il0=) This doesn't work in 2.4 because 2.6 uses sympy rationals to store non-integers. Essentially a port of hyper's hypothetical Jelly answer. ## Explained ``` ≬KṁḊȯ ≬ # The next three elements as a function, taking single argument n: K # divisors of n ṁ # the average of that Ḋ # does that divide n? ȯ # First input numbers that satisfy the above function. ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes ``` |,~~%*,;|,$~%@$@+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMFiG0OjpaUlaboWG2t06upUtXSsa3RU6lQdVBy0IeILoBSUBgA) ]
[Question] [ You are probably familiar with the [Fibonacci sequence](http://oeis.org/A000045) where the first two terms are `0, 1` (or sometimes `1, 1`) and every term after that is the sum of the previous two. It starts like this: `0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...` Sometimes, the sequence contains numbers that have a particular pattern that I find interesting: the difference between any pair of adjacent digits is the same as any other pair. For instance, in the sequence starting with `0, 1`, the 18th term is `987`. `9-8=1` and `8-7=1`. I am mildly satisfied. **Challenge** Given two initial values `F(0)` and `F(1)`, output every number in the sequence generated by `F(n) = F(n-1) + F(n-2)` that meets the following criteria: * The difference between any pair of adjacent digits is the same as any other pair * It is as least three digits long (1 and 2 digit numbers are not interesting for this pattern) **Input** * Two non-negative integers less than 10\*\*10 (10 billion) **Output** * All integers that are less than 10\*\*10 and meet the criteria in the Challenge section * It is acceptable to output digits greater than 10\*\*10 but it is not a requirement * Given that repeated digits meet the pattern (e.g. `777`), it is possible that there are infinite numbers that meet the criteria but your program is not required to output forever * If no such integers exist, output whatever you want so long as it's not a number (nothing, null, empty array, error message, sad face, etc.) * If a number matching the pattern appears more than once in the sequence, you can output it once or as many times as it occurs * If any input meets the criteria, it should be included in the output **Rules** * Input and Output can be in any [standard format](https://codegolf.meta.stackexchange.com/q/2447/38183) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/38183) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins **Examples / Test Cases** ``` Input , Output [1,10] , [] [0,1] , [987] [2,1] , [123] [2,3] , [987] [61,86] , [147] [75,90] , [420] [34,74] , [1234] [59,81] , [2468] [84,85] , [7531] [19,46] , [111] [60,81] , [222] [41,42] , [333] [13,81] , [444] [31,50] , [555] [15,42] , [666] [94,99] , [777] [72,66] , [888] [3189,826] , [888888888] [15,3] , [159,258] [22,51] , [321,1357] [74,85] , [159,4444] [27,31] , [147,11111] [123,0] , [123,123,123,246,369] [111,0] , [111,111,111,222,333,555,888] [111,222] , [111,222,333,555,888] [33345,692] , [987654321] [3894621507,5981921703] , [9876543210] [765432099,111111111] , [111111111,876543210,987654321] [1976,123] , [123, 2222, 4321, 6543, 45678] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes *Thanks to Emigna for pointing out a mistake, now corrected* ``` `yVdd~?yD]wy+T ``` Infinite loop that outputs the numbers as they are found. [**Try it online!**](https://tio.run/##y00syfn/P6EyLCWlzr7SJba8Ujvk/38jcy5jQwA) Note that in the online interpreter the results are displayed after the 1-minute time-out. ### Explanation Let `F(n)` and `F(n+1)` denote two generic consecutive terms of the Fibonacci sequence. Each iteration of the loop starts with the stack containing `F(n)`, `F(n+1)` for some `n`. ``` ` % Do...while y % Duplicate from below. Takes the two inputs F(0), F(1) (implicitly) % in the first iteration % STACK: F(n), F(n+1), F(n) V % Convert to string. Let the digits of F(n) be '3579' for example % STACK: F(n), F(n+1), '3579' d % Consecutive differences (of ASCII codes) % STACK: F(n), F(n+1), [2 2 2] d % Consecutive differences % STACK: F(n), F(n+1), [0 0] ~ % Logical negate, element-wise % STACK: F(n), F(n+1), [1 1] ? % If top of the stack is non-empty and only contains non-zero entries % (this is the case for digits '3579', but not for '3578' or '33') % STACK: F(n), F(n+1) y % Duplicate from below % STACK: F(n), F(n+1), F(n) D % Display immediately. This prints the copy of F(n) % STACK: F(n), F(n+1) ] % End w % Swap % STACK: F(n+1), F(n) y % Duplicate from below % STACK: F(n+1), F(n), F(n+1) + % Add. Note that F(n)+F(n+1) is F(n+2) % STACK: F(n+1), F(n+2) T % Push true. This will be used as loop condition % STACK: F(n+1), F(n+2), true % End (implicit). The top of the stack is consumed as loop condition. % Since it is true, a new iteration will begin, with the stack % containing F(n+1), F(n+2) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 15 bytes ``` тFÂ2£O¸«}ʒS¥¥_W ``` [Try it online!](https://tio.run/##ASoA1f8wNWFiMWX//9GCRsOCMsKjT8K4wqt9ypJTwqXCpV9X//9bMTExLDIyMl0 "05AB1E – Try It Online") **Explanation** ``` # implicitly input list of F(0) and F(1) тF } # 100 times do:  # bifurcate current list 2£ # take the first 2 items O # sum ¸« # append to list ʒ # filter, keep only elements that are true after: S¥¥ # delta's of delta's of digits _ # logically negate each W # min ``` [Answer] # JavaScript (ES6), ~~85~~ ~~84~~ 81 bytes ``` f=(p,q,a=[])=>p|q?f(q,p+q,![...p+''].some(x=d=n=>r=d-(d=x-(x=n)))/r?[...a,p]:a):a ``` [Try it online!](https://tio.run/##lZTLbsIwEEX3/Yp0RSKcYI8fsZEMH4JYRASqVjQvqopF/z0dE1BVJ05VL7xwzlyPr6/zVnwWl0P32nykVV0e@/5k44a0pLC7fWI3zVe7PcUtaZYted5lWdYsF4t9dqnfj/HVlraym86WaVzaa4oLVZIkq27rwII0@3WRrIv@UFeX@nzMzvVLfIoZiRhNkmg8VqsoffoNU4QnWQcbnXs4zOEM@Bjn/1BX2LpWUwVOXfh4LklkaAAXQD2cCxLlIqQOXHi8NNgNC/AglPZ4jfpaBvhccubxDPVF8LTMxxWdawfAwwV6KSCAc@7fFOMz6kL43nBUlyHrpZS@upxpRinl4QadNCbkZD7KAcZMhYzUWk80w0Pvg7lbB@nXAG4hQ/ZwcE@Oy1Ffc4G4bSTGzkKO3bHwGyAuGqNwYHxJRMPZJsOEqUV1Zfxqxmaq3cfbBM4FjA5xN0ymnL1TY6WHzp8SXBuhgEmKB5VGMwMsp7fbGv4YSgq023/awzI15u6OG0MTw8bDwP0e9eRHq/8G "JavaScript (Node.js) – Try It Online") ### Testing adjacent digits ``` ![...p + ''].some(x = d = n => r = d - (d = x - (x = n))) / r ``` Both **x** and **d** are initialized to an anonymous function, which forces `NaN` for all arithmetic operations they're involved in. The first iteration of `some()` always gives `(d = [function] - n) === NaN` and `(r = [function] - d) === NaN` (falsy). On the second iteration, we have `d = x - n` (an integer) and `(r = NaN - d) === NaN` (falsy again). Starting from the third iteration, **r** is set to an integer which is non-zero if the difference between digit #3 and digit #2 is not equal to the difference between digit #2 and digit #1. The number **p** is meeting the required criteria if and only if `some()` is falsy (all adjacent digits have the same difference) and the final value of **r** is **0** (there were at least 3 iterations). This gives `!false / 0 === true / 0 === Infinity` (truthy). We may otherwise have: * `!true / r` with **r > 0** or **r < 0**, which gives `false / r === 0` (falsy) * `!false / NaN`, which gives `true / NaN === NaN` (falsy) ### Halting condition The recursion stops when `p | q` evaluates to **0**. This is guaranteed to happen when both **p** and **q** reach values around **1025** which are 84-bit long. Because JS has 52 bits of mantissa, the last 32 bits are zeroed. So, the 32-bit bitwise OR evaluates to **0**. Due to the fast growing rate of the sequence, this happens rather quickly. [Answer] # Java 8, ~~151~~ ~~144~~ ~~140~~ ~~136~~ 130 bytes ``` (a,b)->{for(long n,m,d,p;;System.out.print(m>99&p==d?m+" ":""),m=a+b,a=b,b=m)for(m=n=a,d=p=10;n>9&d==p|p>9;d=n%10-(n/=10)%10)p=d;} ``` Infinite loop outputting the numbers when it finds them. [Try it online](https://tio.run/##TU/BboMwDL3vKyykVYkaGPRGI7Mf2HrpseLgEFrRkRBB2mnq@PYsLT1MsmU/PdnvvTNdKR1ca8/6KzQ9TRN8UmdvLwCd9e14pKaF3R0CXIdOQ8P6wZ6AxGMoLiM1x441efJdAzuwgBAYCcXT6nYcxuXECiO0cFLufybfmmy4@MyNUYWZqixXDlG/m3UCyTZJuDBIayUIlVBo@P2JQYskNDoscmmrcqUR3a@rSqnRvhZ5yuxbpHhcuUMt5yAXX@6i@ujrae@RwsSMbO@j@ulQA/EloM0aZttv@Ih2GR3ymgv4h4uaP@POIRRFETabzR8) (times out after 60 sec). **136 bytes** version with added 1010 limit (`a<1e10`): ``` (a,b)->{for(long n,m,d,p;a<1e10;System.out.print(m>99&p==d?m+" ":""),m=a+b,a=b,b=m)for(m=n=a,d=p=10;n>9&d==p|p>9;d=n%10-(n/=10)%10)p=d;} ``` [Try it online.](https://tio.run/##bVLLTsMwELzzFVYlqkTdlqwfSUxw@QHgwhFxcB5FhcaxmhQJQb@9mAREHIgc2bPemZ2V91m/6mVjK/NcvpyKnW5bcqu35v2MkK3pqv1GFxW5@4KEvDbbkhTBrjFPREO/5WHmro7ud6vtdLctyB0xRJFToCEPl@v3TbMfKAZqKMFm@gorjLL7t7ar6lVz6FZ272oF9VrKuVWqvK4XMzK7nM1CqJVe5KBVDrmqwy@pWhmloVRWOQ2zlvNSKfth1zIrlTnHaBmYC3cVumNoVZkdT9ngzh7ynXP3bbLvpXadBvedq/708Eh0OLTZVW0XIDh@9osjwDGkU8jGMEZI43EgESA9OcYh4eOAkJB6kimHVIwDKIF7onE0oXAETj0Km2QwBOH5QDGhSA5SetYpxPGE4jVLKQivSDJ1ThNgXgZSBr4NxL8BSj1nLJU8piii5AaETFFSTCJ241WOBWc0khLw5/tnPvun7/P9SR5e36yKfnIH2emQ7kzwrXg8fQI) **Explanation:** ``` (a,b)->{ // Method with two long parameters and no return-type for(long n,m, // Temp numbers d,p; // Current and previous differences a<1e10; // Loop as long as `a` is still below 10^10 ; // After every iteration: System.out.print( // Print: m>99 // If the number has at least three digits, &p==d? // and the previous and current differences are still the same m+" " // Print the current number with a space delimiter : // Else: ""), // Print nothing // Go to the next Fibonacci iteration by: m=a+b, // Setting the temp-number `m` to `a+b` a=b, // Replacing `a` with `b` b=m) // And then setting `b` to the temp number `m` for(m=n=a, // Set both `m` and `n` to `a` d=p=10; // Set both `d` and `p` to 10 n>9 // Inner loop as long as `n` has at least two digits, &d==p // and `p` and `d` are still the same, |p>9 // or `p` is still 10 ; // After every iteration: d=n%10-(n/=10)%10) // Set `d` to the difference between the last two digits of `n` // And integer-divide `n` by 10 at the same time p=d;} // Set the previous difference `p` to `d` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20 19~~ 18 bytes ``` >ȷ2ȧDIEƊ +ƝḢ;Ɗȷ¡ÇƇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/uxHajE8tdPF2PdXFpH5v7cMci62NdJ7YfWni4/Vj7/9DD7aH//5ubmZoYGxlYWuooGMIAAA "Jelly – Try It Online") `+ƝḢ;Ɗȷ¡` produces the first thousand (`ȷ`) terms in the series which will always be sufficient. I think there is probably a shorter way to do this. `+ȷ¡` gets close but only works if the first term is zero. I am assuming we can take in the two numbers in reverse which allows one byte to `DIE`. If we aren't required to output either of the inputs: ### [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` >ȷ2ȧDIEƊ +ṄÇ¡ß@ ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//Psi3MsinRElFxooKK@G5hMOHwqHDn0D///8xOTc2/zEyMw "Jelly – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~91~~ ~~90~~ 83 bytes Saved 7 bytes thanks to Luis Mendo! ``` @(t)eval"for i=3:99,if~diff(diff(+num2str(t(1))))disp(t(1))end,t=[t(2) sum(t)];end" ``` [Try it online!](https://tio.run/##XVLbasMwDH3vV5i9LGFaseRL7JWM/UfIQ2kbCKzraLPtoXS/3qmRbegECc7RkaxzosNmWn/vrkO7XC6vb9VU777X7w/D4ajG1rzECOPwux2HoZpfTx9fezpNx2qqsObYjqdPOe8@tjC13VRRrU5fe27Urxh7uG7ac4eAulegul4pteg04PwVQyMAJQDJZMDcMzxC8MKxCWocROlqSQtkLDQ2d7KCuQhBupP1QbBgIbgZa5xBwTCCTTdggrwupUQCWQRLM2RMmhVNZlmb7jQITkZzziWWy4Xee4GihRhliiZrIvAyRAihFIoXyErIJZQInFxqiN01Ljcoym50WyaiBgxm/wCxaGSjQGfL4PawTWB8TGnEnObT7WErgLUDK4PbkMKZDUqs/ww1B7sSovWETjfgYsBI2Ojym72zrERzOzlqXj3MkVtLQGFDKewvq8ViMa@tahW@HA8/p2pTg5o3tGOqyqu7OY@AF049qufnV/V4n6FL3XNuKDRe4usf "Octave – Try It Online") Well, it works! [`eval` with for loop inside](https://codegolf.stackexchange.com/a/163131/31516) to save a few bytes. [Skipping colons and semicolons](https://codegolf.stackexchange.com/a/107780/31516) to save a few. Uses the fact that a vector is considered truthy iff all elements are non-zero to save `any` or `all`. Other than that, it's pretty much a straight forward implementation of Fibonacci. [Answer] # [Python 2](https://docs.python.org/2/), ~~102~~ 98 bytes ``` f=lambda x,y:x<1e10and[x]*(len(set(int(a)-int(b)for a,b in zip(`x`,`x`[1:])))<2<99<x)+f(y,x+y)or[] ``` [Try it online!](https://tio.run/##dVLLboMwEDy3X@EjJK7k9Qs7ol9iWQpRgoqUAkqpBP15un5A1EMjxayHmfXs4HGZPoaer2v7fm8@L9eGzHQ5zTXcgDX91c3@UNxvffF1m4qun4qmfAuPS9kOD9LQC@l68tONxXk@U/w7OPmyLGteW1vP5bEtFjofl3J4OL8GSdePdPiexqBzzgElwDwlzofFMdyGwpoqATwDwMUOiD8MjS2MjhyZoUpRYmNXyVmChKSkkrmTTJiyqIzdudQmYQZ5RoWyUgISBsiT6QTIkGa7lPMESfQheSiFyF5BbCwp85kCWSpaU0plltqEWusEWXRhbXRRbTPh4DqaMMY8hTELCJNwlWGOTBVPFTzEK9TWYp8tCuRuilfYCHKEqIB9TgyLEpZjwzdhwbCQrm1mAGyMUMWFBwuYAvpQ6PFpOL/c2f8RhbFSc1AM3ShrwHKo2PbZtZI4WP6uaceszbaj9dQ@/bDrpsBMt9p7f3p9GR94leONJOFKUtIWB9yV6y8 "Python 2 – Try It Online") Thx for 4 bytes from [ovs](https://codegolf.stackexchange.com/users/64121/ovs) [Answer] # [Haskell](https://www.haskell.org/), 105 bytes ``` u%v|let s=u:scanl(+)v s=[n|n<-s,d<-[f(-).map fromEnum.show$n],length d>1,and$f(==)d] f g=zipWith g=<<tail ``` Defines the operator `(%)` which returns an infinite list with all the solutions. To actually see the result on *stdout* we need to disable buffering (or run it in `ghci` or with `runhaskell`), [try it online!](https://tio.run/##PU67TsMwFN37FXcoki2SCAaEiOIOVB1YYOjAEDJY@BEL@zqyr1OB@u/BLEznKZ0zy/ylvd9cWGIiOH9n0qF7edvKzXr1miCL0udPiZ7d8rWqEa84tLlRQzsa1vIuyAVMiuGEJXR5jpc9To3XaGkGdbhvJKq9YUJwNe0MWPHjlndXMyuGgaTzW5AOQYCKO4D5rOm5GKOTQwuZVCwEr/HfqpWlIkEH7IOVfu3HibcHqG959f6@JC1VpZeYVIa6AVbTMSJppLw9PsDT3S8 "Haskell – Try It Online") ### Explanation/Ungolfed The function `f` is just a helper function that expects a binary function and a list, it applies the function `g` to all adjacent pairs. It's essentially the same as: ``` adjacent g xs = zipWith (tail xs) xs ``` The operator `(%)` is just a list comprehension that does some filtering (making sure that there are at least 3 digits & that the adjacent digits have the same distance): ``` u % v -- recursively define s as the "Fibonacci sequence" with f(0) = u and f(1) = v | let sequence = u : scanl (+) v sequence -- take all numbers from that sequence using the filters below = [ number | number <- sequence -- convert to string, get the ASCII codepoints and build a list of the adjacent differences , let differences = adjacent (-) . map fromEnum . show $ number -- numbers with > 3 digits have >= 2 adjacent digits (or rather differences of digits) , length differences > 1 -- make sure all of these are equal by comparing them and reducing with logical and , and $ adjacent (==) differences ] ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 55 bytes ``` q~{1$_99>"_`2\ew{{-}*}%""3,"?~_(+="0$p"*~;_@+_11_#<}g;; ``` [Try it online!](https://tio.run/##S85KzP3/v7Cu2lAl3tLSTik@wSgmtby6WrdWq1ZVSclYR8m@Ll5D21bJQKVASavOOt5BO97QMF7Zpjbd2vr/f0MjYwUDAA "CJam – Try It Online") My first CJam submission, not very short but a lot of fun. Any suggestions are welcome! [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~26~~ 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç╕SôεPN^:·░ßⁿ {@ÿ}Ü╫╣1╣X ``` [Run and debug it](http://stax.tomtheisen.com/#p=80b85393ee504e5e3afab0e1fc207b40987d9ad7b931b958&i=[1,10]%0A[0,1]%0A[2,1]%0A[2,3]%0A%0A[61,86]%0A[75,90]%0A[34,74]%0A[59,81]%0A[84,85]%0A%0A[19,46]+%0A[60,81]+%0A[41,42]++%0A[13,81]+%0A[31,50]++%0A[15,42]%0A[94,99]+%0A[72,66]%0A[3189,826]++%0A%0A[15,3]%0A[22,51]+%0A[74,85]+%0A[27,31]+%0A%0A[123,0]++%0A[111,0]+%0A[111,222]+++++%0A%0A[33345,692]%0A[3894621507,5981921703]%0A[765432099,111111111]%0A%0A[1976,123]%0A&a=1&m=2) **Explanation** ``` E{b+}99*L{E%2>|cd_E:-u%1=!C_Qf # Full program, unpacked, implicit input E # Push all elements from array onto stack. {b+}99*L # Generate the first 99 numbers of the Fibonacci sequence given the input { f # Loop through all Fibonacci elements E # Array of decimal digit %2> # Does the array have at least 3 digits |c # Assume Truthy past this point d # discard top of stack _E # Copy the current element of the Fibonacci sequence and Digitize it :- # Pairwise difference of array. :u # Is there exactly 1 unique number !C # Flip the comparison, if truthy proceed _Q # Copy the current element of the Fibonacci sequence and Peek and print with a newline. ``` Not as short as I would like it and can probably be golfed a bit more, but it works. [Answer] # [Ruby](https://www.ruby-lang.org/), 79 bytes ``` ->a,b{loop{a>99&&!(a.digits.each_cons(2).map{|a,b|a-b}|[])[1]&&p(a);a,b=b,a+b}} ``` [Try it online!](https://tio.run/##DcpLCoAgFADAs7QRJRN0F1EXEYn3@kOlZC1CPbu1HeZ68M1zm6sOOIbdWhegq2tCCgpi3Jbt9mKCYe0He3qqmDjAhfjfCBWmqA3T0hDiKLDm1xY5lJhSnrWUkiulTP4A "Ruby – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), ~~86~~ 81 bytes ``` a<b=b>=0&&((n->n>99&&2>endof(∪(diff(digits(n))))&&println(n)).([a,b]);a+b<a+2b) ``` [Try it online!](https://tio.run/##ZVNtbpwwEP3PKdz8QKBMKs/4W93lf8@A@MEmS0UVsdEu6Rl6lh6rF9naGBvSWDKyH88z8549P99fx17f7/3hdDw1R16WVTU9NVPjXFlSc55eLkP19/ef6mUcBv/5Mc63aqr9KMu36zjNr1PYfq3aHk5d/a1/PB36RzrV9@fLdJvZOL29zzd2ZFXRtgjIOwbs@zS3HWOsAw9ywIC1zpqM0YohiR0mPvE0gtWRKTfUKHBLnlYSz6iQYGSKKjOsHNiYjKS2GbYSrFpgowRmGB3INSFuqOY5BlFGJYKkBRVik4EicaXcqhAIKpaslNq4KkXQWmfUSXAulmZ2ogl0rMzaIGMNa708yngc4UxOEE1FbwOpTT4RqFilIH9rQu0SZWfCIblXQQYEpusAxL1H3nTgyX5I03sOQruNhZhYfpWmdxW8h@C9gVB/pi52r@T/SYxlmR6WCrSj9IC0kl7X5r51UhMqbkA5i47QcPGRy2PSuOPORXVRYSwgDsgH4HMedEbD8qZXGxiFqlkgAQtkv1bapHuoi2Ic2Jfx5vvsfO2f5/HXuaoLxobLlVUzsEvtG2ztsSLITS3p/z08NQ@BseBzi91hbqn7wAr/fIcXYRb3fw "Julia 0.6 – Try It Online") Pretty straightforward - check if input has at least 3 digits (`n>99`), then take the difference between each digit pair in the number (`diff(digits(n))`), check that the length of (`endof`) a unique set of (`∪`) those differences is 1 (i.e. all the differences are the same), and if so print the number. Do that for both the given numbers, then recursively call the function with the next two numbers. ~~(Unfortunately, it looks like `±` has higher precedence than `+`, or else the final call could have been `a+b±a+2b`, saving 3 bytes.)~~ Now overloads the `<` operator, thus saving on both the operator bytes and the precedence brackets. (Can't use `<` in our code though, so just rearranged `endof(...)<2` to `2>endof(...)`). If some extraneous output is allowed, we can save 2 bytes using `@show` instead of `println`, printing `n = 987` instead of just `987`. We could even use `dump` for 1 byte lower than that, but `dump` prints the type information along with the value, so output will be `Int64 987` instead of just `987`. ]
[Question] [ I enjoy participating in math competitions run by Mu Alpha Theta, a mathematics honor society in the United States. At competitions, I take a 30-question multiple choice test. There are five choices per question, labeled A through E. My score on a test is four points for each correct answer, zero points for a question left blank, and negative one points for each wrong answer. Write a program that grades a test according to the above scoring system. There should be two components to the input: an answer key followed by responses. Questions left blank are to be inputted as blank spaces. The first input must contain only the letters A-E (or a-e, your choice), and it can be assumed that there is no whitespace in the input. The second input must only contain blank spaces and the letters A-E (or a-e). Inputs not implementing 30-question tests must print `Invalid test` as output. The output should be the grade or `Invalid test`. *Bonus* If your program prints the number right, number left blank, and number wrong after the final score as `(aR bB cW)`, take off 20 bytes. **Sample input** ``` CABBDCABECDBACDBEAACADDBBBEDDA //answer key CABEDDABDC BACDBBAADE CBBEDDA //responses ``` **Sample output** *No bonus* ``` 73 ``` *Bonus* ``` 73 (20R 3B 7W) ``` --- Standard rules apply. Shortest code in bytes wins. [Answer] # Pyth, ~~53~~ 51 ``` ?&!-sJ.z+d<G5&FqR30lMJ+sm?qFd4_1CJ/eJd"Invalid test ``` [Try it online](https://pyth.herokuapp.com/?code=%3F%26%21-sJ.z%2Bd%3CG5%26FqR30lMJ%2Bsm%3FqFd4_1CJ%2FeJd%22Invalid+test&input=cabbdcabecdbacdbeaacaddbbbedda%0Acabeddabdc+bacdbbaade++cbbedda&debug=0) The checks are done by seeing if the entire input contains any characters when all of the spaces and `a-e` are removed, and by checking if both strings have length `30`. The score calculation is done by zipping the two lines together, then by mapping each pair to: `(letters are equal) ? 4 : -1`. Then simply summing the values, and adding the number of spaces in the second line back to the score. [Answer] ## [Seriously](https://github.com/Mego/Seriously), 86 bytes ``` ,`;l5╙¬=);' UΣS" ABCDE"=(**;l`Mi@)=YWé"Invalid test"0WX@Z```i@;(=5*(' =D+`(;l@)5╙¬=IMΣ ``` Takes input like `"CABBDCABECDBACDBEAACADDBBBEDDA", "CABEDDABDC BACDBBAADE CBBEDDA"` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c603b6c35d3aa3d293b272055e45322204142434445223d282a2a3b6c604d6940293d59578222496e76616c6964205465737422305758405a60606069403b283d352a2827203d442b60283b6c402935d3aa3d494de4&input=%22CABBDCABECDBACDBEAACADDBBBEDDA%22, "CABEDDABDC BACDBBAADE CBBEDDA") (you will have to manually enter the input because permalinks don't like quotes) ~~Working on the bonus now.~~ Nope, adding the bonus would cost more than 20 bytes. I knew I was forgetting something... `Invalid Test` wasn't being printed in the event of an error. There go my hopes of out-golfing Dennis. [Answer] # JavaScript (ES6), 134 bytes **Edit:** The question requirements changed. This answer is from when the program needed to make sure each answer character is A-E, each response character is A-E or space and they both have lengths of 30, else return `Invalid test`. ``` (a,r)=>[...a].map((q,i)=>q>"E"|q<"A"?x=1:(c=r[l=i])==" "?0:c>"E"|c<"A"?x=1:c==q?s+=4:s--,s=x=0)&&x|l!=29|r.length!=30?"Invalid test":s ``` ## Explanation ``` (a,r)=> // a = answer string, r = responses string [...a].map((q,i)=> // iterate over answers, q = answer, i = question number q>"E"|q<"A"?x=1: // x = 1 if answer is invalid (c=r[l=i])==" "?0: // c = question response, l = answer length, add 0 for space c>"E"|c<"A"?x=1: // x = 1 if response is invalid c==q?s+=4:s--, // add 4 if correct, subtract 1 if incorrect s=x=0 // s = total score, x = is invalid )&& x|l!=29|r.length!=30? // check input lengths for validity "Invalid test": s // return the score ``` ## Test ``` <input type="text" id="answers" value="CABBDCABECDBACDBEAACADDBBBEDDA" /><br /> <input type="text" id="responses" value="CABEDDABDC BACDBBAADE CBBEDDA" /><br /> <button onclick='result.innerHTML=( (a,r)=>[...a].map((q,i)=>q>"E"|q<"A"?x=1:(c=r[l=i])==" "?0:c>"E"|c<"A"?x=1:c==q?s+=4:s--,s=x=0)&&x|l!=29|r.length!=30?"Invalid test":s )(answers.value,responses.value)'>Go</button><pre id="result"></pre> ``` [Answer] # CJam, 60 bytes ``` 2{l_,30=\N?}*_2$|S'F,65>+-!@2$.{=4W?}@' f=+:+"Invalid test"? ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2%7Bl_%2C30%3D%5CN%3F%7D*_2%24%7CS'F%2C65%3E%2B-!%402%24.%7B%3D4W%3F%7D%40'%20f%3D%2B%3A%2B%22Invalid%20test%22%3F&input=CABBDCABECDBACDBEAACADDBBBEDDA%0ACABEDDABDC%20BACDBBAADE%20%20CBBEDDA). [Answer] # JavaScript (Firefox 31+), 86 bytes ``` (x,y)=>(r=i=0,[for(l of y)x[i++]==l?r+=4:r-=l!=' '],i!=30|i-x.length?'Invalid test':r) ``` Uses array comprehension which is proposed for ES7. Thus support is limited to Firefox for the moment. ## With bonus, 106 bytes (126 - 20) ``` (x,y)=>[r=w=i=0,[for(l of y)x[i++]==l?r++:w+=l!=' '],`${r*4-w} (${r}R ${i-r-w}B ${w}W)`,'Invalid test'][i!=30||i-x.length?3:2] ``` **Edit:** Previously my solution only checked answer or question length, now checks both. ``` F=(x,y)=>(r=i=0,[for(l of y)x[i++]==l?r+=4:r-=l!=' '],i!=30|i-x.length?'Invalid test':r) G=(x,y)=>[r=w=i=0,[for(l of y)x[i++]==l?r++:w+=l!=' '],`${r*4-w} (${r}R ${i-r-w}B ${w}W)`,'Invalid test'][i!=30||i-x.length?3:2] var score = () => result.innerHTML = (bonus.checked ? G:F)(questions.value, answers.value); questions.oninput = answers.oninput = bonus.onchange = score; score(); ``` ``` * { box-sizing: border-box; } label { float: left; clear: left; vertical-align: middle; line-height: 2; padding-right: 0.5em; } input[type="text"] { width: 100%; vertical-align: middle; line-height: 2; font-family: monospace; padding: 0 0.5em; } input[type="checkbox"] { vertical-align: middle; line-height: 2; margin: 0.5em; } hr { clear: both; } .input-wrapper { overflow: hidden; width: auto; } #result, #error { font-weight: bold; } #error { display: none; } ``` ``` <script type="text/javascript"> window.onerror = () => { var inputEls = document.getElementsByTagName('input'); for (var i = 0; i < inputEls.length; i++) { inputEls[i].disabled = true; } error.style.display = 'block'; output.style.display = 'none'; } </script> <label for="questions">Q:</label> <div class="input-wrapper"> <input id="questions" type="text" value="CABBDCABECDBACDBEAACADDBBBEDDA"/> </div> <label for="answers">A:</label> <div class="input-wrapper"> <input id="answers" type="text" value="CABEDDABDC BACDBBAADE CBBEDDA"/> </div> <label for="bonus">Bonus:</label> <div class="input-wrapper"> <input id="bonus" type="checkbox" checked/> </div> <hr/> <div id="output"> Result: <span id="result"></span> </div> <div id="error"> ERROR: Unsupported browser! Try Firefox 31+ </div> ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), 71 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` Ul ¥30©Vl ¥30«(U+V k"[A-E ]+" ?U¬r@VgZ ¥Y?X+4:VgZ ¥S?X:X-1,0 :`InvÃ. È. ``` The two `.`s at the end should be the unprintable Unicode chars U+0017 and U+0099, respectively. ### How it works ``` Ul ==30&&Vl ==30&&!(U+V k"[A-E ]+" ?Uq r@VgZ ==Y?X+4:VgZ ==S?X:X-1,0 :"Invalid test // Implicit: U = first input, V = second input Ul ==30&&Vl ==30&& // If both input lengths are 30, and !(U+V k"[A-E ]+"? // removing all ABCDE and spaces from (U+V) results in an empty string: Uq r@ ,0 // Reduce U with this function, starting with a value of 0: VgZ ==Y? // If the matching char in V is equal to this char, X+4 // return previous value + 4. :VgZ ==S?X // Else if the matching char in V is a space, return previous value. :X-1 // Else (if it's wrong), return previous value - 1. :"Invalid test // Else, return "Invalid test". // Implicit: output last expression ``` I hope there's a shorter way to make sure both lengths are equal to 30. Suggestions welcome! [Answer] ## Python 2.7, ~~131, 116, 109~~, 139 I tried to do a "short" python solution... Well here it is, suggestions are more than welcome ``` lambda c,d:d.count(' ')+sum([-1,4][a==b]for a,b in zip(c,d)if b!=' ')if not set('ABCDE ')^set(c+d)and len(c)==len(d)==30 else'Test Invalid' ``` Adding a few more characters makes it far more readable... ``` def m(c, d): if len(c)==len(d)==30:return d.count(' ')+sum((a==b)*4+(a!=b)*-1 for a,b in zip(c,d)if b!=' ') return'Test Invalid' ``` [Answer] # Haskell, ~~144~~ 138 bytes ``` a%b|map length[a,b]==[30,30]&&"ABCDE"!a&&"ABCDE "!b=show$sum$zipWith(?)a b|0<1="Invalid test" l!s=all(`elem`l) _?' '=0 x?y|x==y=4|0<1=0-1 ``` Would be about 50 without the validation. *sniff*. Usage: `"ABCDEABCDEABCDEABCDEABCDEABCDE" % "AAAAABBBBBCCCCCDDDDDEEEEEAAAAA"` [Answer] ## C#, 162 154 148 134 bytes ``` string g(string k,string a)=>k.Length!=30||a.Length!=30?"Invalid Test!":Enumerable.Range(0,30).Sum(e=>a[e]==' '?0:k[e]==a[e]?4:-1)+""; ``` Usage ``` g("CABBDCABECDBACDBEAACADDBBBEDDA", "CABEDDABDC BACDBBAADE CBBEDDA") ``` Test <http://csharppad.com/gist/15f7c9c3c8cfce471ff2> [Answer] # Ruby, 81 characters ``` ->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'} ``` Sample run: ``` 2.1.5 :001 > ->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'}['CABBDCABECDBACDBEAACADDBBBEDDA','CABEDDABDC BACDBBAADE CBBEDDA'] => 73 2.1.5 :002 > ->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'}['CCCATCH','CABEDDABDC BACDBBAADE CBBEDDA'] => "Invalid test" ``` [Answer] # Java, ~~183~~ 169 bytes This was a nice bit of Java 8 practice: ``` String f(String a,String r){return a.length()==30&r.length()==30?""+IntStream.range(0,30).map(i->a.charAt(i)==r.charAt(i)?4:r.charAt(i)!=' '?-1:0).sum():"Invalid test";} ``` [Answer] # brainfuck, 354 bytes ``` +[--[>]<<+>-],----------[[<<<]>>->[>>>],----------]<<<[<<<]>>+[<-[-------<+>]<.+[---<+>]<.++++++++.[-<+++>]<-.+++++++++++.---.-----.-[---<+>]<-.---[-<++++>]<.+++[-<+++>]<.[---<+>]<----.+.>]>[[>,----------->+++++++[<---<<+++>>>-]<[<<+[>>+<<-]]>[>]<<<[>[>+>+<<-]>>[<<+>>-]>[>>>]>----<<<<[<<<]>>[-]]>[>-<-]>[>>[>>>]>-----<<<<[<<<]>[-]]>>]----[>+++<--]>--.<] ``` Requires an interpreter that allows you to go left from cell 0. Output is a signed byte. For example, the byte `0x49` is printed for the example input, and `0xFF` is printed for input with the same first line but the second line replaced with "C" and 29 spaces. The score starts at 0, and as the second line of input is read these changes are made to it: * Input is correct: Do nothing * Input is incorrect: Subtract 5 * Input is a space: Subtract 4 Finally, 120 is added. This is functionally the same as assuming a perfect score and applying penalties, rather than starting at 0. With comments: ``` +[--[>]<<+>-] Get 29 ,----------[[<<<]>>->[>>>],----------] Get first line of input; for each char sub one from the 29 <<<[<<<]>>+ Add one to the cell that originally held 29 [ If the cell that originally held 29 is nonzero: Write "Invalid test" <-[-------<+>]<.+[---<+>]<.++++++++.[-<+++>]<-.+++++++++++.---.-----.-[---<+>]<-.---[-<++++>]<.+++[-<+++>]<.[---<+>]<----.+. >] >[ If the cell to the right is nonzero: This block is only ever entered if "Invalid test" isn't written! [ For all 30 characters of the first input: >, Get char from second input to the right ---------- Subtract 10 for consistency - Subtract one more >+++++++[<---<<+++>>>-] Subtract 21 (plus above lines = 32) <[ If it's nonzero: <<+[>>+<<-] Add 22 to the character ] >[>]<<<[ If the above block wasn't entered: >[>+>+<<-]>>[<<+>>-] Make a copy of the character from input 1 >[>>>]>---- Subtract 4 from the score <<<<[<<<]>>[-] Go to the cell just before first character ] >[>-<-] Subtract input 1 char from input 2 char >[ If the result is nonzero: >>[>>>]>----- Subtract 5 from the score <<<<[<<<]>[-] Go back to the result and set it to 0 ] >> Move on to next character ] ----[>+++<--]>-- Add 120 to score (perfect score) . Print score < Go to an empty cell to kill loop ] ``` [Answer] # Python 3, ~~187 179 175 165 155~~ 151 ``` lambda a,b:(['Invalid test',sum([-1,4][i==j]for i,j in zip(a,b))+b.count(' ')][len(a)==len(b)==30and set(a)^set('ABCDE')==set(b)^set('ABCDE ')==set()]) ``` [Answer] # JavaScript ES7, 102 As usual, the bonus is not worth the effort. ``` (k,h,t=i=0)=>[for(x of h)t+=k[i++]==x?4:1-x?0:-1]|/[^ A-E]/.test(k+h)|i-30|k.length-i?"Invalid test":t ``` Checking for invalid spaces in first input (as this makes sense to me) **112** ``` (k,h,t=i=0)=>[for(x of h)(y=k[i++])>' '?t+=y==x?4:1-x?0:-1:k=h+h]|/[^ A-E]/.test(k+h)|i-30|k[i]?"Invalid test":t ``` [Answer] # Prolog, 165 bytes More than half the bytes are for the invalid tests check. **Code:** ``` p(X,X,4). p(_,32,0). p(_,_,-1). A*B:-length(A,30),length(B,30),subset(A,`ABCDE`),subset(B,`ABCDE `),maplist(p,A,B,L),sum_list(L,S),write(S);write('Invalid Test'). ``` **Explained:** ``` p(X,X,4). % If corresponding elements are equal, 4p p(_,32,0). % If answer is 'space', 0p p(_,_,-1). % Else, -1p A*B:-length(A,30),length(B,30), % Check that input is of correct length subset(A,`ABCDE`),subset(B,`ABCDE `), % Check that input has correct characters maplist(p,A,B,L),sum_list(L,S),write(S); % Create a list of scores (L) and print sum write('Invalid Test'). % If anything failed, write Invalid Test ``` **Example:** ``` `CABBDCABECDBACDBEAACADDBBBEDDA`*`CABEDDABDC BACDBBAADE CBBEDDA`. 73 ``` Try it out online [here](http://swish.swi-prolog.org/p/XkOWpXBJ.pl) [Answer] ## MATLAB, 92 90 bytes Thanks to Tom Carpenter for helping me to reduce my answer by 2 bytes! ``` function c(q,a),if nnz(q)~=30,t='Invalid test';else s=q-a;t=5*nnz(~s)-sum(s<9);end,disp(t) ``` Function can be called by assigning the answer sheet to *q* and the submitted answers to *a*. e.g.: ``` c('CABBDCABECDBACDBEAACADDBBBEDDA','CABEDDABDC BACDBBAADE CBBEDDA') ``` The answer is simply printed to the screen. **8 bytes** could be saved if it is allowed to print *ans = 73* [Answer] ## C# 6.0 --> (270 - 20 = 250) 246 - 20 = 226 bytes ``` void m(string b,string c){if((b+c).Length==60){var a=new int[3];int s=0;for(int i=0;i<30;i++){if(b[i]==c[i]){a[0]++;s+=4;}else if(c[i]==' ')a[2]++;else{a[1]++;s--;}}Console.Write(s+$" ({a[0]} {a[2]} {a[1]})");}else Console.Write("Invalid test");} ``` Readable & ungolfed version: ``` void m(string b, string c) { if ((b+c).Length==60) { var a = new int[3]; int s = 0; for (int i = 0; i < 30; i++) { if (b[i]==c[i]) { a[0]++; s+=4; } else if (c[i] == ' ')a[2]++; else { a[1]++; s--; } } Console.Write(s+$" ({a[0]} {a[2]} {a[1]})"); } else Console.Write("Invalid test"); } ``` Really wanted to get the bonus :D [Answer] # Groovy 2.4.5, 107 bytes Just a simple translation of the earlier [Java answer](https://codegolf.stackexchange.com/a/64861/39490). ``` f={a,b->a.length()==30&b.length()==30?(0..29).collect{a[it]==b[it]?4:b[it]!=' '?-1:0}.sum():'Invalid test'} ``` [Answer] # C, 273 - 20 = 253 bytes ``` #include<stdio.h> #include<string.h> int main(int c,char**v){char*p=v[1],*q=v[2],*s=" ABCDE",r[]={0,0,0};if(strspn(p,s+1)!=30||p[30]||strspn(q,s)!=30||q[30])puts("Invalid test");else{for(;*p;++q)++r[(*p++!=*q)+(*q==' ')];printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]);}} ``` I've taken the bonus, even though it cost me 23 bytes just to print it. :-( ## Explanation ``` #include <stdio.h> #include <string.h> int main(int c,char**v) { char *p=v[1], *q=v[2], /* arguments */ *s=" ABCDE", /* valid chars */ r[]={0,0,0}; /* results - right, wrong, blank */ if (strspn(p,s+1) != 30 /* validity check - answer key begins with [A-E]{30} */ || p[30] /* and ends there */ || strspn(q,s) != 30 /* same for answers, but allow space, too */ || q[30]) { puts("Invalid test"); } else { for ( ; *p; ++q) /* for each answer */ ++r[(*p++!=*q)+(*q==' ')]; /* increment the appropriate counter */ printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]); /* print result */ } } ``` There's twice as much code to check for invalid input as there is to count the answers - the real meat of the challenge is in the `for` loop near the end. In fact here's a version that assumes the input is always valid, in 163-20 = 143 bytes: ``` #include<stdio.h> int main(int c,char**v){char*p=v[1],*q=v[2],r[]={0,0,0};for(;*p;++q)++r[(*p++!=*q)+(*q==' ')];printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]);} ``` And one that makes the same assumption and prints only the score, in 133 bytes: ``` #include<stdio.h> int main(int c,char**v){char*p=v[1],*q=v[2],r[]={4,-1,0};for(c=0;*p;++q)c+=r[(*p++!=*q)+(*q==' ')];printf("%d",c);} ``` [Answer] ## **SAS** 9.4, 291-20 = 271 bytes(with bonus), or 231 bytes(without bonus) With bonus: ``` data a;k='CABBDCABECDBACDBEAACADDBBBEDDA';r='CABEDDABDC BACDBBAADE CBBEDDA';c=0;b=0;w=0;if length(k) ne 30 then put "Invalid test";do i=1 to 30;if substr(k,i,1)=substr(r,i,1) then c=c+1;else if substr(r,i,1) =' ' then b=b+1;else w=w+1;end;a=cat(c*4-w,' (',c,'R ',b,'B ',w,'W)');put a;run; ``` Without bonus: ``` data a;k='CABBDCABECDBACDBEAACADDBBBEDDA';r='CABEDDABDC BACDBBAADE CBBEDDA';c=0;if length(k) ne 30 then put "Invalid test";do i=1 to 30;if substr(k,i,1)=substr(r,i,1) then c=c+4;else if substr(r,i,1)ne' ' then c=c-1;end;put c;run; ``` Sas does not really have an input/output, so you would need to replace the k='..' with the key, and r='..' with the response. The output is printed to the log. ]
[Question] [ This is a somewhat different task. Calculate 1024 hexadecimal digits of π, beginning at the 1024th hexadecimal place. Formally: Your program should complete in less then 1 minute and produce the following output: > > 25d479d8f6e8def7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4bb3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb9790e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae909198eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df01c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a1477e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b35e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9c5832603766295cfa911c819684e734a41b3472dca7b14a94a > > > The program with the shortest length wins. You have to calculate all the digits at runtime. You do not have to implement the algorithm that computes π; if your language already provides that functionality, you can use it. [Answer] **Sage, 29 char** This isn't technically cheating, since the digits are computed at runtime. That said, it's still cheap as hell. ``` hex(floor(pi*2^8192))[1025:] ``` [Answer] # Shell Utilities: 48 `curl -sL ow.ly/5u3hc|grep -Eom 1 '[a-f0-9]{1024}'` * All output is "calculated" at runtime. (thanks to OP posting the solution) * Runs in under a minute. (may be dependent on your internet connection speed) [Answer] ## JavaScript, 536 (Linebreaks and indentation for legibility only) ``` var d='0123456789abcdef',p='',o='',l=3e3,c=0,e='length';d=d+d; function $(n,r){return n[e]<=r?0:d.indexOf(n[r])} function g(a,b){for(i=0,t='',s=16;i<l;i++,t+=d[~~(s/b)],s=(s%b)*16); for(;a--;t=_(t,t,1));return t} function _(a,b,s){for(i=(a[e]>b[e]?a[e]:b[e])-1,r='',c=0;i>=0;r=(s? function(k){c=k>15;return d[k]}($(a,i)+$(b,i)+c): function(k){c=k<0;return d[k+16]}($(a,i)-$(b,i)-c))+r,i--);return r} for(i=0;i<l;i++,p+='2'); for(j=1;j<l;p=_(p,(o+='0')+_(_(_(g(2,8*j+1),g(1,8*j+4)),g(0,8*j+5)),g(0,8*j+6)),1),j++); console.log(p.slice(1024,2048)) ``` It takes about 25 seconds, on Google Chrome 14 on my lap-top using Intel i5 core. Can someone else golf this code? I can't golf well.. :( Below is non-golfed. I just remove all comments and changed for loop to golfing. Don't mention about `for(;s>=b;s-=b);s*=16;`. I changed it to `s=(s%b)*16`. :P ``` /** Calculate PI-3 to 3000 (3e3) digits. a : a b : b c : carry d : digits e : length f : get from d g : calculate (2^a)/b. i,j, : for looping l : length to calculate p : pi r,t : return value */ var d='0123456789abcdef',p='',o='',l=3e3,c=0,e='length'; d=d+d;//for carring function $(n,r){return n[e]<=r?0:d.indexOf(n[r])} /* Calculate (2^a)/b. Assume that 2^a < b. */ function g(a,b){ for(i=0,t='',s=16;i<l;i++){t+=d[~~(s/b)];for(;s>=b;s-=b);s*=16;} for(;a--;t=_(t,t,1));return t} /* Calculate a±b. (+ when s=1, - when s=0) When calculating minus, assume that 1>b>a>0. */ function _(a,b,s){ for(i=(a[e]>b[e]?a[e]:b[e])-1,r='',c=0;i>=0; r=(s?function(k){c=k>15;return d[k]}($(a,i)+$(b,i)+c): function(k){c=k<0;return d[k+16]}($(a,i)-$(b,i)-c))+r,i--);return r; } /* Using BBP formula. Calc when j=0... 4/1 - 2/4 - 1/5 - 1/6 = 3.22222222.... (b16) */ for(i=0;i<l;i++,p+='2'); //Calc when j>0 for(j=1;j<l;p=_(p,(o+='0')+_(_(_(g(2,8*j+1),g(1,8*j+4)),g(0,8*j+5)),g(0,8*j+6)),1),j++); console.log(p.slice(1024,2048)); ``` EDIT : Removed totally unused function. (Why did I keep that? :/ ) PS. First 100 digits of PI `243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d01377be5466cf34e90c6cc0ab` [Answer] ## PHP ~~116~~ 114 bytes ``` <?for(;$g?$d=0|($$g=$g--/2*$d+($$g?:2)%$g*$f)/$g--:4613^printf($i++>257?'%04x':'',$e+$d/$f=4*$g=16384)^$e=$d%$f;); ``` This solution calculates all of pi up to 2048 hex digits, four hex digits at a time, and outputs the last half of them. Execution time is less than 5 seconds. The formula used for the calculation is the following: ``` pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + 5/11*(2 + 6/13*(2 + 7/15*(2 + ... ))))))) ``` The precision is obtained storing the remainders in an array, and continuing each of the 2^14 divisions incrementally. ## Python 64 bytes ``` x=p=16385 while~-p:x=p/2*x/p+2*2**8192;p-=2 print('%x'%x)[1025:] ``` Same method as above. Runs in about 0.2s. Or as a one-liner in **73 bytes**: ``` print('%x'%reduce(lambda x,p:p/2*x/p+2*2**8192,range(16387,1,-2)))[1025:] ``` [Answer] ## PARI/GP-2.4, 141 ``` forstep(d=1024,2047,8,y=frac(apply(x->sum(k=0,d+30,16^(d-k)/(8*k+x)),[1,4,5,6])*[4,-2,-1,-1]~);for(i=0,7,y=16*frac(y);printf("%X",floor(y)))) ``` Using the Bailey–Borwein–Plouffe formula (of course). Runs in well under a minute. [Answer] C code: ``` long ki,k,e,d=1024; int dig,tD=0,c,Co=0,j,js[4] ={1,4,5,6}; double res=0.0,tres=0.0,gT,ans[4] ={0.0}; while(tD < 1024) {while(Co<4){ j= js[Co],gT=0.0,ki= 0; for(; ki < d+1;ki++){ k = 8*ki+j,e= d-ki,c=1; while(e--) c = 16*c % k; gT+=((double)(c)/(double)k);} ans[Co] = (gT - (int)gT),++Co;} double gA = 4*ans[0]-2*ans[1]-ans[2]-ans[3]; gA = (gA<0) ? gA + -1*(int)gA +1 : gA -(int)gA; dig=0;while(dig++ < 6 && tD++ < 1024) gA *=16, printf("%X",gA),gA -= (int)gA; d+=6,Co = 0;} ``` runtime = 8.06 seconds on a intel Quad core [Answer] ## PARI/GP - 40 bytes This version 'cheats' by using `\x` to display the hexadecimal digits of the result. ``` \p8197 x=Pi<<4^6;x-=x\1;x=(x<<4^6)\1 \xx ``` This version takes 87 bytes to convert to hexadecimal in the usual way. ``` \p8197 x=Pi<<4^6;x-=x\1;concat([Vec("0123456789abcdef")[n+1]|n<-digits((x<<4^6)\1,16)]) ``` Both versions run in a small fraction of a second. [Answer] # Perl - 59 ``` use ntheory"Pi";say substr int(Pi(3000)<<8192)->as_hex,1027 ``` Less than 0.1s. [Answer] ## Shell 68 ### tools: bc -l, tr, cut ``` echo "scale=2468;obase=16;4*a(1)"|bc -l|tr -d '\\\n'|cut -c1027-2051 ``` ### Shell 64, tools: bc -l, tr, tail, differs in the rounding of the last place ``` echo "scale=2466;obase=16;4*a(1)"|bc -l|tr -d '\\\n'|tail -c1024 ``` Might be considered cheating, since the knowledge how to compute PI is in 4\*a(1), and that 1 have to use scale=2466 was iteratively investigated. Thanks to breadbox for the idea to use cut. ]
[Question] [ This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will give you two positive integers `n` and `k` as inputs and have you count the number of rectangles with integer coordinates that can be drawn with vertices touching all four sides of the \$n \times k\$ rectangle $$ \{(x,y) : 0 \leq x \leq n, 0 \leq y \leq k\}. $$ That is, there should be: * at least one vertex with an \$x\$-coordinate of \$0\$, * at least one vertex with an \$x\$-coordinate of \$n\$, * at least one vertex with an \$y\$-coordinate of \$0\$, and * at least one vertex with an \$y\$-coordinate of \$k\$. ### Example There are \$a(5,7) = 5\$ rectangles with integer coordinates touching all four sides of a \$5 \times 7\$ rectangle: [![Five examples of rectangles embedded in the 5 by 7 rectangle.](https://i.stack.imgur.com/D6RQw.png)](https://i.stack.imgur.com/D6RQw.png) ### Table The lower triangle of the (symmetric) table of \$a(n,k)\$ for \$n,k \leq 12\$ is ``` n\k| 1 2 3 4 5 6 7 8 9 10 11 12 ---+---------------------------------------------- 1 | 1 . . . . . . . . . . . 2 | 1 2 . . . . . . . . . . 3 | 1 1 5 . . . . . . . . . 4 | 1 1 1 6 . . . . . . . . 5 | 1 1 1 3 9 . . . . . . . 6 | 1 1 1 1 1 10 . . . . . . 7 | 1 1 1 1 5 1 13 . . . . . 8 | 1 1 1 1 1 1 5 14 . . . . 9 | 1 1 1 1 1 5 1 1 17 . . . 10 | 1 1 1 1 1 3 1 3 1 18 . . 11 | 1 1 1 1 1 1 5 1 5 5 21 . 12 | 1 1 1 1 1 1 1 1 5 1 1 22 ``` --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~66~~ 59 bytes ``` lambda n,k:sum(a%n*(n-a%n)==a/n*(k-a/n)for a in range(n*k)) ``` [Try it online!](https://tio.run/##VY0xDsIwEAR7XnGNZV9IQA5dJP@E5lAwGJN1ZEKR1ztOhahWO9LszuvyTOiLd9fyluk2CqGNw@c7GVFoDLoa7Jyca4ldDfYpk1AAZcHjbtBE5rJD/KBtyV54OBDNOWAhTfr0SgFGq37Uypt6wrRL8U/C0daxDQ "Python 2 – Try It Online") Each possible rectangle inside the \$n \times k\$-rectangle can be specified by two integers, \$0 \le a \lt n\$ and \$0 \le b \lt k\$: [![enter image description here](https://i.stack.imgur.com/tqGgy.png)](https://i.stack.imgur.com/tqGgy.png) [![enter image description here](https://i.stack.imgur.com/B0WVl.png)](https://i.stack.imgur.com/B0WVl.png) To verify a rectangle given \$a\$ and \$b\$, it suffices to check if one angle is a right angle. To do this I take the dot product of \$\binom{b}{0}-\binom{0}{a}=\binom{-b}{a}\$ and \$\binom{k-b}{n}-\binom{0}{a}=\binom{k-b}{n-a}\$ to check whether the angle at \$\binom{0}{a}\$ is a right angle: $$ \langle \left( \begin{matrix} -b \\ a \\ \end{matrix}\right), \left(\begin{matrix} k-b \\ n-a \\ \end{matrix} \right) \rangle = 0 \\\Leftrightarrow a\cdot(n-a)-b\cdot(k-b)=0 \\\Leftrightarrow a\cdot(n-a)=b\cdot(k-b) $$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes ``` LDI-*`¢O ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx8VTVyvh0CL///@jTXUUTGMB "05AB1E – Try It Online") **Commented**: ``` # implicit input: [n, k] L # for both values take the [1..x] range # [[1,...,n], [1,...,k]] D # duplicate this list I # push the input [n,k] - # subtract this from the ranges # [[1-n,...,n-n], [1-k,...,k-k]] # =[[-n+1,...,0], [-k+1,...,0]] * # multiply with the ranges # [[1*(-n+1),...,n*0], [1*(-k+1),...,k*0]] ` # push all lists of this list on the stack ¢ # count the occurences of each value of one list in the other O # sum those counts ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~63~~ 61 bytes Saved 2 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` s;a;f(n,k){for(s=a=n*k;a--;)s-=a%n*(n-a%n)!=a/n*(k-a/n);a=s;} ``` [Try it online!](https://tio.run/##lZTfb4IwEMff/StuJCSAbWZBVNJ1L8v@CvWhQdwMWWeABxPD386uMmk3wR/k6F3p99NeLy0p/UjTpim55FtPkdw/br8LrxRSqCDnklLul1RIVwWeouj8JyGfsZNTdD6XouR1s1MVfMmd8vzRcQT46A/ZYZ@lVbZhyzUIODICN6zmF2zYshMC4cNs1LFo8WPs1GbRZgSie9n4H4uWnMTxbXZ2yaKxyZmJuzx64HkvrNnIWjzuhxdDsOanJ3J45eQKrPn5eeW4B2aT67SeYDGYN2M3aX16BhJn4T20niA0dNDhLdxNRsy5NWFkwqkJYxPOTDg34cKECbFqZcXWeuycXvopiwCKNjFndXgPV4fkDd/YIWD3I@eX0Nddl0QhwTi6F/Qhh/FY@dDeZluWt7Jcy5RW5baqqy@quiLlQIGtl@rk@IW2Qm376/k7ti9wdOs57oa4G6CvgK1brhRuRBHICVQEN1oJka0tsh61bd38AA "C (gcc) – Try It Online") Port of [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s [Python answer](https://codegolf.stackexchange.com/a/213759/9481). [Answer] # [Scala](http://www.scala-lang.org/), ~~65~~ ~~64~~ ~~60~~ 51 bytes ``` n=>k=>0 to n*k-1 count(a=>a%n*(n-a%n)==a/n*(k-a/n)) ``` [Try it online!](https://tio.run/##VY3BCsJADETv/YpQEDaVVutR2AWPHvwDL7G2ULdmFxtFkH77mgoemkMeMwMzY0MDpXC5tY3AiXqG9i0tX0c4xPjJQO9FA3R7OLKAdQskts5btwUJwIUva2jCk8WQdbTiwnCpQGtpo8KXCsRUVxJMvcPqTtHw3DXPLFz/dwHio9fCzjAaj7CG/Cw5ajLN7xcObDBTOaUv "Scala – Try It Online") * -1 thanks to [user](https://codegolf.stackexchange.com/users/95792/user)! * -4 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! * -9 thanks to [Kjetil](https://codegolf.stackexchange.com/users/64733/kjetil-s)! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` NθNηIΣEθ№Eη×λ⁻ηλ×ι⁻θι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaDgnFpdoBJfmavgmFmgU6ig455cCRUGcDB2FkMzc1GKNHB0F38y80mKQSI6mpiZMPBMmDtSWqQkB1v//myqY/9cty0kEAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates \$ x(n-x) \$ for \$ 0 \le x < n \$ and \$ y(n-y) \$ for \$ 0 \le y < k \$ and counts the number of times an integer appears in both lists, which corresponds to the parallelogram with coordinates \$ (x, 0), (0, y), (n - x, 0), (0, k - y) \$ having 90 degree angles: ``` NθNη ``` Input \$ n \$ and \$ k \$. ``` IΣ ``` Output the total sum of all matches found. ``` Eη×λ⁻ηλ ``` Calculate \$ y(n-y) \$ for \$ 0 \le y < k \$. ``` Eθ№...×ι⁻θι ``` Calculate \$ x(n-x) \$ for \$ 0 \le x < n \$ and count how many times each integer appears in the other list. [Answer] # JavaScript (ES6), ~~63 58~~ 56 bytes *Saved 2 bytes thanks to @ovs* ``` (n,y=x=0)=>g=k=>(x=x||++y*k--&&n)&&(y*k==--x*(n-x))+g(k) ``` [Try it online!](https://tio.run/##FYzBTsJAEEDvfMWc2hk6u2FBRcWpJ77AozFm09JSFmeb0pgl4rfXenl5yUveyX/7SzV0/Wg01oepkQmVr5JkRVK2EqTEJOl2K4rrMhiTZUpZhrOLGJOWqCYRFS0Gmnbvjte84Tu@5wfe8iM/sVuxc@zWH7aJw95XR8TA8MngCaSEnwVAFfUSzwd7ji16@@V71P8080UgwCs0qDT/4Rlym5Md49s4dNoi2d7Xe61xQ2RPsVPMc6Ld4pemPw "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` r1×ḶċⱮ/S ``` A monadic Link accepting a pair of integers which yields the count. **[Try it online!](https://tio.run/##y0rNyan8/7/I8PD0hzu2Hel@tHGdfvD///@jTXXMYwE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/7/I8PD0hzu2Hel@tHGdfvB/QyOdw/sSDrc/aloDRO7/AQ "Jelly – Try It Online"). ### How? ``` r1×ḶċⱮ/S - Link [n,k] r1 - ([n,k]) inclusive range to 1 = [[n,n-1,...,1],[k,k-1,...,1]] Ḷ - lowered range ([n,k]) = [[0,1,...,n-1],[0,1,...,k-1]] × - multiply = [[n×0,(n-1)×1,...,1×(n-1)],[k×0,(k-1)×1,...,1×(k-1)]] / - reduce by - i.e.: f(A=[n×0,(n-1)×1,...,1×(n-1)], B=[k×0,(k-1)×1,...,1×(k-1)]) Ɱ - map with - i.e.: [f(A,v) for v in B] ċ - count occurrences (of v in A) S - sum ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 45 bytes ``` \d+ * L$w`(_+) (_+) $.`*$1=$.2*$' m`^(.*)=\1$ ``` [Try it online!](https://tio.run/##K0otycxLNPzPZWikxeWjUp6gp82loqehoqairqmjoqdmC@MoADlcfglc@jEp2gpArB@vquGe8B/I4oJo1IjX1lQAEUD9CVoqhkCdRloq6ly5CXEaelqatjGGKv//AwA "Retina – Try It Online") Link includes test suite. Takes space-separated inputs. Explanation: ``` \d+ * ``` Convert the inputs to unary. ``` L$w`(_+) (_+) ``` Match all substrings that contain `_ _`. This corresponds to all pairs of \$ 0 \le x < n \$ and \$ 0 \le y < k \$ which are represented by the unmatched parts at the beginning and end of the string `$`` and `$'` respectively while \$ n - x \$ and \$ k - y \$ are represented by `$1` and `$2` respectively. ``` $.`*$1=$.2*$' ``` For each pair, list the (unary) products \$ x (n - x) \$ and \$ y (k - y) \$. ``` m`^(.*)=\1$ ``` Count the number of times that they are equal. [Answer] # [Haskell](https://www.haskell.org/),~~53~~ 47 bytes ``` a#b=sum[1|x<-[1..a],y<-[1..b],x*(a-x)==y*(b-y)] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yba4NDfasKbCRjfaUE8vMVanEsJKitWp0NJI1K3QtLWt1NJI0q3UjP2fm5iZp2CrkJtY4BuvUFBaElxS5JOnEK1RnJFfrpCoqa2tpKOkrQ3hJoG4CrZ2CjARFaBtmjWJEOMNjWJ1kmB2xv4HAA "Haskell – Try It Online") * Saved 6 thanks to @ovs We use the expression `x/(b-y)==y/(a-x)` which is converted to `x*(a-x)==y*(b-y)` to avoid modulo checks. The expression computes the ratio between sides(the second inverted) which has to be the same to be a valid rectangle. [Answer] # [Perl 5](https://www.perl.org/), (`-p` `-Minteger`) 54 bytes ``` / /;$_=grep$_%$'*($'-$_%$')==$_/$'*($`-$_/$'),1..$`*$' ``` [Try it online!](https://tio.run/##HYhBCoAgEEX3ncLFhBVNMgtpER6hM@hmkCBSzPM3lYv/3uNnLqcVMcps4F0snMH3oKcBNLYanQNv2hOw1TjTskCYQItYtXarst9@E3VEH5@U65GuW/DMgvtxVY5cXg "Perl 5 – Try It Online") Using the same formula, and range product as ovs except the range starts from 1 [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 72 bytes ``` : f 0e over 0 do dup 0 do 2dup i - i * swap j - j * = s>f f- loop loop ; ``` [Try it online!](https://tio.run/##JY3NDsIgEITvPMV31mCKvdnYdzGW1RITCKA@Pi542J2fZGYk5vq0D@nQ2gVh8sSPz0xske2dBjHnznas3oHyvSWCiqDiSlkFsbxiTP@3aFH1pRpwM64X7bjjYOqhKuiSrIWZU1ZrxO55oFlGuP0A "Forth (gforth) – Try It Online") Yet another port of [ovs's Python 2 answer](https://codegolf.stackexchange.com/a/213759/78410), except that it uses nested loops. Direct loop counters are much cheaper when multiple copies are needed. Takes `n k` from the main stack and returns the count via the FP stack. ``` : f ( n k -- f:cnt ) 0e \ setup the initial count over 0 do \ outer loop (j): 0 to n-1 dup 0 do \ inner loop (i): 0 to k-1 2dup \ ( n k n k ) i - i * swap \ ( n k i*[k-i] n ) j - j * = \ ( n k i*[k-i]==j*[n-j] ) Forth boolean is 0/-1 s>f f- \ increment count if equal loop loop ; ``` [Answer] # Java 8, 75 bytes ``` n->k->{int r=0,a=n*k;for(;a-->0;)if(a%n*(n-a%n)==a/n*(k-a/n))r++;return r;} ``` Port of [*@ovs*' Python 2 answer](https://codegolf.stackexchange.com/a/213759/52210), so make sure to upvote him! [Try it online.](https://tio.run/##jZExb8IwEIV3fsXJUiUb4xSQOhTjdKvUoRNj6eBCghyHS@Q4SIjmt6cOBAbUVJ3u7Od7@u450wctsq1tN7muKnjXBk8jgMprbzaQBTWqvcmjtMaNNwVGr32zfEOf7BI3@d@jvoljSEG1KGIr4pNBD05NJ1rh2Mq0cFRqIeKpZCal@gHHFEUoTCn9GA5WhMKY41y6xNcOwcmmlaPAW9ZfeeDtsQ@F2cI@rEJX3hncfXyCZt1aAKtj5ZN9VNQ@KoPkKcH12n4TJs9yx9BRoZpKwKWazUPhnJ3F36aBRC4pE@0pxs8vs8WcceThtve7H8iRDitECMEJJ@Lm@TRjd2C2A7MXMBvATkNk1AYeQhYdC7cB6bbj8JZXM4DLz6SRLsv8SJH1jb1Z/J2Fu2bhLlk0A5TnODqxGTXtDw) ]
[Question] [ Take an arbitrarily sized string as input. This string represents a baseball plate appearance, in which each character represents a pitch as follows: * Strike: `S` * Ball: `B` * Foul ball: `F` * Hit by pitch: `H` * Ball in play: `X` (For those wondering, this is a very *very* simplified version of [Retrosheet](https://www.retrosheet.org/eventfile.htm)'s notation) --- Your program must output 1 of 3 possible outputs to signify 1 of the mutually exclusive outcomes: * Strikeout * Walk * Ball in play It doesn't matter what the outputs are exactly, as long as they are *guaranteed* to be distinct. --- For those unfamiliar with the rules of baseball: * 3 strikes results in a strikeout * 4 balls results in a walk * A foul ball is a strike UNLESS the batter already has 2 strikes, in that case nothing happens * Hit by pitch immediately results in a walk * "Ball in play" immediately results in the "Ball in play" outcome --- You may assume that: * the input string is encoded as ASCII * the input string represents an *entire* plate appearance (in other words it *will* end in one of the 3 outcomes above) * there are no other characters other than the ones above You may **not** assume that: * there are no extra pitches/characters after the plate appearance is supposed to legally end * your program must return on the last pitch/character --- Examples: "Strikeout"fy: ``` SSS SBSBS BBBSSS BSBSBS BSFFBFS BBSSFFFFFFFFS SSSBBBB FSS ``` "Walk"y: ``` BBBFB BBBB BBBSB SSBBBB SSH SBSFFBFFFFBFFFFFFFFB BBBBSSS HSSS SBBBBSS ``` "Ball in play"ly: ``` X SSX BBBX SBSX FFFFFFFFFFFFFFX XBSBSBSB ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. (This challenge was inspired by [this YouTube video](https://www.youtube.com/watch?v=JwMfT2cZGHg)) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes ``` 4=`B H 2`F|S 1!`[XHS] ``` [Try it online!](https://tio.run/##VU6hDkJBDPP9CwQJFoLFVIzzNUvISw6BwCAIkn8/tt0ZtmRpt3bb@/F5vu5jf7j2cb50ouHU7SvguOs3b9rGkAQxEiSTcDGZ0bKrQDNCKYWMSLERhdNHrIHUcl16bZUCJc31bR4sBnj0vWyJ6Ol12F84fP7EHw "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `X` for ball in play, `H` for walk, and `S` for strikeout. Explanation: ``` 4=`B H ``` The fourth ball results in a walk, same as hit by pitch. ``` 2`F|S ``` The first two foul balls/strikes are ignored. ``` 1!`[XHS] ``` Take the first available result. [Answer] # JavaScript (ES9), ~~68 66~~ 55 bytes *Saved 11 bytes thanks to @Neil!* Returns \$S\$ for *Strikeout*, \$X\$ for *Ball in play* or an empty string for *Walk*. ``` s=>/(?<=(B.*){4})|(?=H)|X|(?<=([SF].*){2})S/.exec(s)[0] ``` [Try it online!](https://tio.run/##dVKxCsIwFNz9CsmUCFYRR6vwhtD9DQaqQ6hRqqERW0Wx/fbaVgdLXxII4S6Xd/eSs37oPLml12KauYOpj2Gdh@sZ36xCDsFEvJeVKPkmjESpyg6NUe5bYlEJnAXmaRKei3i@rxOX5c6awLoTZ1jc0otx94KJ0T9xbChEJoYoNJPAAYAWgFeBUoKk78KG@w7SA2JTDlqmR7FdttX2wihzEmjTHhiBrOsRIEZ0q9qE8rd0G48JunWR7wk6BRUftLXjNBtfrX4N26BI64r2pOhEFCx7gzqhvr@gjV9/AA "JavaScript (Node.js) – Try It Online") ### How? We match either: * `(?<=(B.*){4})` : an empty string preceded by 4 `B`'s * `(?=H)` : an empty string followed by an `H` * `X` : the character `X` * `(?<=([SF].*){2})S` : an `S` preceded by 2 other strike characters (`S` or `F`) As a result, we get an `S` for a *Strikeout*, an `X` for a *Ball in play*, or an empty string for a *Walk*. [Answer] # [Python 3](https://docs.python.org/3/), ~~90~~ ~~88~~ ~~86~~ 85 bytes *-2 bytes thanks to @ovs* ``` s=b=0 for i in map(ord,input()):s+=~i%2*~s*i%71<3;b+=i<67;b//4+s//3==i%4//2>exit(i%6) ``` [Try it online!](https://tio.run/##FcmxCsIwFEDRPV8RCIG0UVKTkhTb5@Ag7llcDVV8g21oKujSX4/tdLjc@Jtf42Ay83RPG0PYZdVVhJ1XrSXsurUm7Lb9JicIUJHnOFGkOND3PYpx6nc4xM8siuKYJCzIdbmkErk7dKYNErCzrg1K1TIpZQCQ10rp0@OLs0Bui5y9938 "Python 3 – Try It Online") Returns via exit code: `0` for a walk, `4` for ball-in-play, and `5` for a strikeout. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~26~~ ~~24~~ ~~22~~ 20 bytes ``` Ç.Δ6Ö½$¾4@N¾Ì@)yè}6% ``` [Try it online!](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@1656aYHZ52aK/KoX0mDn6H9h3ucdCsPLyi1kz1v96hrTr/o5WCg4OVdJSCnYAQSDs5OUEEnOAiwW5uTm4QuWAgGwLAeoKDgcqdgCw3ZBbEFDcnCA2lgp3AGqACwcEeEDtBRrtBCTADqgniBg@Y28AiQFYEWG8ERFEExAgQ5YYCQCIREPc7KcUCAA "05AB1E – Try It Online") Outputs 5 for strike out, 0 for walk, or 4 for ball in play. ``` Ç # convert the input to a list of ASCII codepoints .Δ } # find the first codepoint y such that: 6Ö # is y divisible by 6? (true for B and H only) ½ # if yes, increment the counter variable c $ # push 1 and input ¾4@ # is c >= 4? N¾Ì@ # is the iteration count N >= c + 2? ) # wrap the stack in a list: [1, input, c >= 4, N >= v + 2] yè # get the y-th element of that list (wraps around) # * H and X are mapped to 1, so those characters always result in a match # * nothing is mapped to `input`, it's just there to pad the list # * B and F are mapped to `c >= 4`, so the 4th B results in a match (this would also # match HBBB or BBBBF, but we stop after the first match, so that's irrelevant) # * S is mapped to `N >= c + 2`, so an S matches if it's preceded by at least 2 characters not in (B, H) 6% # after the loop: modulo 6 (B => 0, H => 0, S => 5, X => 4) ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 172 bytes ``` I =INPUT N I LEN(1) . P REM . I :($P) S S =LT(S,2) S + 1 :F(K)S(N) B B =LT(B,3) B + 1 :F(H)S(N) F S =LT(S,2) S + 1 :(N) X OUTPUT =0 :(E) K OUTPUT =1 :(E) H OUTPUT =2 E END ``` [Try it online!](https://tio.run/##bc2xCsIwEIDh@e4pbnDIYRFTnQpZgikJrTF4KTg7ix18f2K02Mnpju/nuNdzvs@PYykQyISYpoyxrqOLSjPtKNHVnesM0KlNYhQQMmNW0rRMQlvS0PVqYFGR0YL9RtscmOwv@iX2fy4/foPLlOtfMvsKjnFYQS/gV2jRoYunUryIvAE "SNOBOL4 (CSNOBOL4) – Try It Online") `0` for a ball in play, `1` for a strikeout, and `2` for a walk. gosh, I miss baseball :-( *Thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector) for pointing out several bugs!* [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ \$\cdots\$ ~~87~~ 86 bytes Saved ~~12~~ 13 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved 6 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` c;b;s;f(char*p){for(b=s=0;c=*p++-66,s+=c==4&s<2|c==17,b+=!c,c!=6&b<4&s<3&c<22;);c%=3;} ``` [Try it online!](https://tio.run/##bZI9b4MwEIb3/gqCFAQBpJZUdDDu4MFi91APWcAtLQolCNOhSvPbqYF@xHcYCVnvPT7fvWcVvyo1joqURJPKV29Fv@uCc3Xq/ZJqeksU3XVhGKdppEOqKL33dJZ8mc3dQ1SGdKMitaGpV2ZTYO@pLElIQNSW7sllfC/q1g/ON11ft0Plu2Lo6@PL6WPQh9YNyL8uhBM/OttnI0fOIrjBNcDMB5BJsiDGGEq0aDa2koytZBOcM464WQTXCqMuC91@FbIbEsKUxlDXkziDf@ShfSqaIzDMUJyhTjmDfmAGIQIzgoFa10pFuYTIIZPDIU7u8Z/fvEEzRQRqaW3GaMg5onL8puZzsIJZhCNgRdNop26drik@7VFIO4EEnkjoiYQNSdSNhLZJZJONcGsBGgStg3J5@GAMv@qMXsZv "C (gcc) – Try It Online") Returns \$0\$ for a walk, \$1\$ for a ball in play, and \$2\$ for a strikeout. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~42~~ 41 bytes *Thanks to @Neil for saving a byte!* ``` (?<=(B.*){3})B H 1!`X|H|(?<=([SF].*){2})S ``` [Try it online!](https://tio.run/##VU6xCkIxDNzzFw5C6yCoqw/hhtj9loAIz8HBxUHcfO/ba5M@BC9Q7pLLpa/7@/G81XU6jzWdjkPCdpM/hzlDiuxWo01liv6FevXRfs6slaQQrQSACyyKqlDvsrGO5iSbDTJ0@I5CouXrkGVOFk/1CF2eIGH1K6XfDfVLsza22HYG8wgT/YOJ9R/iCw "Retina 0.8.2 – Try It Online") Based on @Arnauld's JavaScript answer. Returns `X` for ball-in-play, `H` for a walk, and `S` for a strikeout. [Answer] # [Io](http://iolanguage.org/), 142 bytes Returns `0` for a strikeout, `5` for a walk, `4` for a ball-in-play. ``` method(I, s :=b :=0 I foreach(i,s=s+i%2+if((s-1)*i%69<3,1,0);b=b+if(i<67,1,0);if(((b/4)floor!=0)or(i%8<1)or((s/3)floor!=0),System exit(i%6)))) ``` [Try it online!](https://tio.run/##VY5PT8MwDMXv/RSmUiWHBdKyUf61lxwq7cQhBzhwaSHVrGXNlASJffrSUBDdkyxZfr9nm@zYtV7DYw1v40GHnf3ALQc/Dbqp8mQLvXW6fd8hcV/7FWU3K@oR/VXBLikrH6o1L3jOnrq6iwZV5d08iBR2YsN6Y627qHNmHVJ2XxWxQS/W/w5XJx/0AfQXhYkp2aRRCBUc7fXzZwDMWZIIEX/FVEqlml@plMHR0RDMEIGX1uwBbxewkhMrIyr/MvI8A7I1BmiAo2lPgJufMMzp5kyv6ezFK9cLSjZKysXW8Rs "Io – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ηε.•Çšy•uS¢`+3@y'SÅ¿*·s4@r;M}0Kн ``` Outputs `2` for Strikeout; `1` for Walk; and `0.5` for Ball in play. [Try it online](https://tio.run/##yy9OTMpM/f//3PZzW/UeNSw63H50YSWQLg0@tChB29ihUj34cOuh/VqHthebOBRZ@9YaeF/Y@/@/W3CwExAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c9vPbdV71LDocPvRhZVAujT40KIEbWOHSvXgw62H9msd2l5s4lBk7Vtr4H1h73@d/9FKwcHBSjpKwU5ACKSdnJwgAk5wkWA3Nyc3iFwwkA0BYD3BwUDlTkCWGzILYoqbE4SGUsFOYA1QgeBgD4idIKPdoASYAdUEcYMHzG1gESArAqw3AqIoAmIEiHJDASCRCIj7nZRiAQ). Could be **31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** by removing the `u` if we can take the input as lowercase. **Explanation:** ``` η # Get all prefixed of the (implicit) input-string ε # Map each prefix to: .•Çšy• # Push compressed string "xhbsf" u # Convert it to uppercase: "XHBSF" S # Convert it to a list of characters: ["X","H","B","S","F"] ¢ # Count each character in the current prefix-string ` # Push the counts separated to the stack + # Add the counts of "S" and "F" together 3@ # Check that it's >= 3 * # And: y'SÅ¿ '# Check whether the current prefix ends with an "S" · # And double this combined check (so 2 if truthy; 0 if falsey) s # Swap so the count of 'B' is at the top of the stack 4@ # Check that it's >= 4 (1 if truthy; 0 if falsey) r # Reverse the stack, so the count of 'X' is at the top of the stack ; # Halve it (0.5 if truthy; 0.0 if falsey) M # Push the largest value of the stack }0K # After the map: remove all 0s н # And pop and push the first value of the list # (after which it is output implicitly as result) ``` Note that this assumes the count of `"H"` and `"X"` can never be larger than 1, which we can due to the assumptions mentioned in the challenge description. [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•Çšy•` is `"xhbsf"`. [Answer] # [C#], 147 bytes ``` d=(p,s,b,i)=>{var P=p[i];int t=0;if(P=='B')b++;if(P=='S'||(P=='F'&&s<2))s++;if(P=='H'||b>3)t=2;if(P=='X')t=3;if(s>2)t=1;return t!=0?t:d(p,s,b,++i);}; ``` [Try It online!](https://tio.run/##bVJNT8MwDL33V5gK0UYrY2w3SooIItqBA1KQqLTt0HUBIqoUJRkIjf324awpiI9Eiu3n@tl9SW2Pa6t2r5UBKx1Q0PJttoANxEKIOEPDcHuHMRYg9o0JzhkPaYFBt7pCIbCEoXtyIpxRz7Jduwj@LE/MWejQW8E6ih4SYhqG8Q15OPZOXxmGm3YWm95XzfN//cqOsAyFZSDeW/5j7aGy@10WwxZJWdU00VDIRtYutUALsMO79uqpMpfGVO8pITlAFPG1rs9rRGeLDJR2v44CVl7qddPk0Yru0pfMZstMEVps/E3c0peZWuT4ITg6ytVDektpwhKyHAz6SCQfH3uHJ0dH9nxMiP1OTjG5LCbE0XEPlQlGEx/ZYozuaW6kWxsN7oCOLtzZKgwxGCiSb/PdVatt28jhvVFO3igt08P4FIf@usq5HmPoRZ7rCXpembme65jkET4lVOVGWZeSIW/NdVU/dWr9R7vBNwcWefVjaskWjgvYrFKbjfwm2xg13X0C) Return values: 1 = Strikeout, 2 = Walk, 3 = Ball in play. (I wanted to use recursion for this answer, for learning) [Answer] # [Z80Golf](https://github.com/lynn/z80golf), 49 bytes ``` 00000000: 0603 0e04 cd03 80fe 5320 0105 fe42 2001 ........S ...B . 00000010: 0dfe 4620 0310 0104 fe48 2001 4afe 5828 ..F .....H .J.X( 00000020: 0caf b93e 5728 06af b820 d93e 53cd 0080 ...>W(... .>S... 00000030: 76 v ``` [Try it online!](https://tio.run/##jY67DsIwDEV3vsIjU3TzaGoYOnRAiLUDXUvTsCCxMfDzwU7zAVxLiR35HOXLeL5fuRS0nAkRnrAh0JqkY@SNOu9AsOgob8GRAyyRaZm0G8kcdoNVRxIoRIW8rWRQkncyLKpkx@q47J4rmZuZj83h1LEumR4nL6u9rCLqyKJM9c2viQBG/cdwP8pJZpjkag4vjj7Sf/mUMo9TrR8 "Z80Golf – Try It Online") Prints W for walk, S for strikeout, and X for ball in play. ## Ungolfed ``` ld b,3 ; number of strikes until strikeout ld c,4 ; number of balls until walk input: call $8003 ; A = next character from stdin strike: ; if A == 'S', record a strike cp 'S' jr nz,ball dec b ball: ; if A == 'B', record a ball cp 'B' jr nz, foul dec c foul: ; if A == 'F', cp 'F' jr nz, hit_by_pitch ; record a strike ; jump to the next section if batter hasn't struck out djnz hit_by_pitch ; if batter has struck out, give them another chance ; foul balls can't strike out a batter inc b hit_by_pitch: cp 'H' jr nz, ball_in_play ld c, d ; d is initialized to 0 by default ball_in_play: cp 'X' jr z, exit walk: xor a ; 1 byte shorter than ld a, 0 cp c ld a, 'W' jr z, exit strikeout: xor a cp b jr nz, input ld a, 'S' exit: call $8000 halt ``` [Answer] # [sed](https://www.gnu.org/software/sed/) -E, ~~69~~ ~~60~~ 59 bytes ``` s/([FS][^FS]*){2}S/&K/;s/([^B]*B){4}/&H/;s/[^KHX]*(.).*/\1/ ``` [Try it online!](https://tio.run/##VU6xCsJADN3zIaU9aA/FzS1gOOj4lkBtJ0VcWqE6lf665@XaxQRC3st7Seb7rX6MnxhnX3aCvhtScdVyXOGL1p@NHrh3XC2n1RfBmG5og/aubKrG@evBxwiAwCmJmQ3wjiDCYixSt0VSAknGJMh6YcrQrEz7DAi20eyyl9xkqV0I282MSJNebaRmUpK/UNLtH/5Or/dzGudYX34 "sed – Try It Online") *9 bytes off, thanks to math junkie.* Input on stdin. Output on stdout: H for walk, K for strikeout, X for in play. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` ≔⪪S¹θF⪪B34HF02SS02F⁴F✂⌕Aθ§ι⁰I§ι¹I§ι²§≔θκ§ι³§Φθ№XHSι⁰ ``` [Try it online!](https://tio.run/##bY7NCoMwEITvfYrgKYEU/Lt5skLQWyEXr6LWLl2ixlj69umKLW2hA3uZ3Z352mtj27FB7/NlgcFwPSE4XplpddpZMAMXkkU0s8gOl9Gy10VwStJShbHWYawCyVIh2L5GaHuuwHQ5Ip8ly11luv7BQbJQUFDRLI5/mdE/MxYktjO9bcq6/cQlgpjOBPl5VYCut9tpMa7kB3WpiQ62DmrPvFekE0nX/njHJw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `X`, `H` or `S` as appropriate. Explanation: ``` ≔⪪S¹θ ``` Split the input string into an array of characters. (If that is a legal input format, then these 5 bytes could be removed, but it would be really hard to enter in any of the examples.) ``` F⪪B34HF02SS02F⁴ ``` Iterate over a string literal which encodes the following rules: The fourth Ball counts as a Hit by pitch. The first two Fouls might count as Strikes. The first two Fouls or Strikes don't strike the batsman out so turn them back into Fouls. ``` F✂⌕Aθ§ι⁰I§ι¹I§ι² ``` Find the range of matches of the source character that we're interested in. ``` §≔θκ ``` Update those matches with the destination character. ``` §ι³§Φθ№XHSι⁰ ``` Filter out all characters except `X`, `H` and `S` and output the first remaining character. [Answer] ## Javascript, 84 characters ``` z=>{y={B:-1,S:i=0,F:0};while(c=z[i++],d={H:'B',F:'S'}[c]||c,y[d]++,y[c]<3);return d} ``` Returns S, X or B for a strike-out, on-base or walk. Auto-formatted version: ``` f = (z) => { y = { B: -1, S: (i = 0), F: 0 }; while (((c = z[i++]), (d = { H: 'B', F: 'S' }[c] || c), y[d]++, y[c] < 3)); return d; }; ``` [Answer] # [Foxrabbit's Finite-State Binary (FSB)](https://esolangs.org/wiki/FFM/FFB), 57 bytes The 57 bytes in hexadecimal are: ``` 01 04 43 04 01 06 47 08 02 06 49 0c 03 06 54 09 0c 00 00 05 05 02 04 06 07 01 00 00 00 02 48 07 0c 01 02 0a 0b 01 00 0a 0a 02 03 0b 0c 00 00 00 00 05 00 0d 0d 07 00 0d 0d ``` Assumes an ASCII-superset environment. Outputs a single byte with value 3 for strike-out, value 72 (ASCII 'H') for walk, or value 88 (ASCII 'X') for ball in play. As an FFM program: ``` Get;inp;67;Ball:NotB NotB;nop;71;Foul:NotBF NotBF;nop;73;Print:NotBFH NotBFH:nop;84;Strike:Print Ball;lft;0;CountBall:CountBall CountBall;inc;4;BallRet:SetH BallRet;rgt;0;Get:Get SetH;inc;72;SetH:Print Foul;rgt;2;CountStrike:StrikeRet Strike;rgt;0;CountStrike:CountStrike CountStrike;inc;3;StrikeRet:Print StrikeRet;lft;0;Get:Get Print;out;0;End:End End;hlt;0;End:End ``` The VM for both languages is a finite-state machine with access to an infinite tape of byte values. I used the initial tape cell for the most recent input character, the cell to the right for the number of strikes, and the cell to the left for the number of balls. [Try it online!](https://tio.run/##rVZtb@JGEP4c/4oNfDi7GGIIyV3R@T7kDhqkNJwIaVVxKFrsNWzPL6tdO4T@@XRm13YMzUmpWhB4X@Z9npmx2OfbLD1/bp@eFUqerXl6xtJHIsyxxRORyZyovXIJz6wgpkqRu5zmbGSdhCwiDw885fnDg61YHLkkSEKXrKl0yZ@JcIDmBM97cOzDr9oCgQ@/agukPvysdhBnihH2yCSo5@mGFMJCJfrcDrKQ@QMUuomzNY2JqFfTX8eLejNrbrIir9c8nfCYWSe53KNlomfkOtYJewqYyMktTdhYykzqa3C1pgUx/4LaKHoLAwS2x554rp1zrLbaZjuyZbHxG3fXsLHRaSF5mtutVute0Q0bEVh1kJ3KzePSW3VgT5azr4vp7HbV6/XIcjK9Ga@seZEqQkkvitYkQve7XZ6KIse1j39Ef5RgAY84Q1p9mmdkw3KiaUkks8QlkuZbJkm@pak@AdJCMQkSITz/EPmaREMHq1eEwZYEWaoytHHrkm4X40DqDwZDARVXOkBEQBQscBqiJosUlARZktA01JGDk89JaAPmGnjJqWAvYHgLenh6VUQRuHgMoSa6eISw9/3WzWTR0ukXHb@Pzwi0@H7MUhtV63I4wVXHh4QBLOKadf5LyWpYvJoUKTvGcKBXTF9w0UUFDf7p7WfNj5RLLla1AdXBp8HFRS0UD3zvkOCjd3gN9AcavowPNXT/dw3T269aw26LaFnIonQ2IhjBKhXOJyOmqrWmxEyGNR3EzdHXZfEt9uKl@JpMDQZ9U@1fLvojcyNZXsgUl@0dIyljIWJaMkB3rOG7LsGijUZUgVf3d@N5a3QsGarANuYdu1clH5SkmSk/s625l92@tqeGQ1OwbjyS0dDu/zf5jcTM7mtwzo6dMl0poU92FVDXc1yWhj5WZsNI7KA7yXNmr/c5U/byiGflOAdKr2@MUtNEPajy6YwkDMZSqCwdW2OFNWus2zvoKYxAdhR9ZGXzghYDfUyRHeU5DhXI2Zph5wqt2ucW8GK7EzLbSJpYwudZ7woNnc6MwT1sUlv2ZD@3vL43HJ57Q3heDt97H7wBPH/2Au/cu7wYerjCzwV8B0B16b0HSvMZDD/ALoD9wKPeWp9T@A6Ad13yGV7PC@H73jxbzxCdtqASxiMCrTLT1IC2XOMPDCU7HuZb6@Tqj8X49@mXxbWuClFhwrHKeviNxkVdEOVsGc/ns/moko4xY4nI96eYyWqYtRVOf5JQYemV8pcr6MAgHbq8VPCugKeW8kuVg59qSzoDxzLFjYhUAMWDy8oTnkbZy0gw4qpqR2zYutG6ume6uvO5uju5uoO4Gq5u63aGa0SRs1RQ26t6DE/TkD29zOED14tUsiDbpPwvKO5yoJiwfsNxq@fsN4Pserrj24xaYs3AS4yC5WBk1v4SD5Yj9BZXztnZYOXqs@bRaGXIQTgUcK6B9mCKxJy62gJIIwD13Zpv3rlE8U3KQn9Cobwcw91/lbv/Bu42DUPCcSzriMdcQUswye1RIaCYbf3KZx@@3SGnzrshBTUk2BbBd3yt@UH29aRuAPj01KqGnAVzzzOQgufBDChzX850o22pHyt8s3TelNmF7gwAaeh6BsI6o7k0Ap2jvIKx2O8OlYHrH/2qZ@mXW23uIZGJulV3vh/ReKvnu6u7yeRqMin/9OJv) In that link, the header and footer are the FFB interpreter written in Python and linked from the esolangs page, but modified a little to take an `io.BytesIO` instead of opening a binary file, and to skip the `chr` on an output instruction (since a printed byte 3 is annoying to verify). So the output there will be the decimal string "3", "72", or "88". ]
[Question] [ Lets define a pointer sequence to be any sequence such that **a(n) = a((n-1)-(a(n-1)))** forall **n** greater than some finite number. For example if our sequence begun with ``` 3 2 1 ``` Our next term would be `2`, because **a(n-1) = 1**, **(n-1)-1 = 1**, **a(1) = 2** (this example is zero index however it does not matter what index you use the calculation will always be the same.). If we repeat the process we get the infinite sequence ``` 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ``` ## Task Given some initial array of positive integers output the pointer sequence starting with that array. ### Output types Output is intended to be flexible, if you choose to write a function as your program it can return, either an infinite list of integers or a function that indexes the sequence. If you choose to write a full program you may output terms of the sequence indefinitely. You may also choose to take two inputs, the starting array and an index. If you choose to do this you need only output the term of the sequence at that index. --- You will never be given a sequence that requires indexing before the beginning of the sequence. For example `3` is not a valid input because you would need terms before the `3` to resolve the next term. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so your score will be the number of bytes in your program with a lower score being better. ## Test Cases *test cases are truncated for simplicity* ``` 2 1 -> 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 ... 2 3 1 -> 2 3 1 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ... 3 3 1 -> 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 ... 4 3 1 -> 4 3 1 3 4 4 3 3 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 ... ``` [Answer] # JavaScript (ES6), 25 bytes ``` a=>f=n=>a[n]||f(--n-f(n)) ``` An anonymous function that, when called, creates a function `f` that gives the item at a given index in the sequence. Please let me know if I misunderstood anything... [Answer] # [Husk](https://github.com/barbuz/Husk), ~~7~~ 6 bytes ``` ¡S!o_→ ``` Returns an infinite list. [Try it online!](https://tio.run/##yygtzv7//9DCYMX8@Edtk/7//x9tomOsYxgLAA "Husk – Try It Online") Note that it takes a while for TIO to truncate and print the result. ## Explanation The operator `¡` has several meanings. Here I'm using "construct infinite list by iterating a function that computes a new element from the list of existing ones". Given a list of length **N**, the new element will have 1-based index **N+1**. All we need to do is negate the last element of the list (which is the previous value) and index into the list using the result. ``` ¡S!o_→ Implicit input. ¡ Construct infinite list by iterating this function on input: S! Element at index → last element o_ negated. ``` [Answer] # [Haskell](https://www.haskell.org/), 36 bytes *Takes a list and returns a function that indexes the sequence* ``` l!n|n<length l=l!!n|e<-n-1=l!(e-l!e) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0cxrybPJic1L70kQyHHNkcRyE@10c3TNQSyNVJ1cxRTNf/nJmbm2RYUZeaVqOQmFmhEG@kYxipqRhvo6RkZxP4HAA "Haskell – Try It Online") ## Explanation Here we are defining a function `!` that takes a list `l` and a index `n`. If `n` is less than the length of `l` we index `l` by `n`, otherwise we return `l!((n-1)-l!(n-1))`. This follows the recursive definition of the function I gave in the question. Here is the same program ungolfed. ``` a l n |n<length l = l!!n |otherwise = (a l) ((n-1) - (a l) (n-1)) ``` I use `e<-n-1` instead of otherwise to save bytes while assigning `n-1` to `e` so it can be used later. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 9 bytes ``` :"tt0)_)h ``` Outputs the initial terms followed by *n* additional terms (allowed by the challenge), where *n* is a positive integer taken as input. [Try it online!](https://tio.run/##y00syfn/30qppMRAM14z4/9/U65oEwVjBcNYAA) ### Explanation ``` :" % Implicitly input n. Do the following n times tt % Duplicate the sequence so far, twice. In the first iteration this % implicitly inputs the array of initial terms 0) % Get value of the last entry, say m _) % Get value of the entry which is m positions back from the last h % Append. This extends the array with the new entry % Implicit end. Implicitly display ``` [Answer] # Mathematica, 63 bytes takes two inputs ``` (Clear@a;(a@#2[[1]]=#)&~MapIndexed~#;a@n_:=a[n-1-a[n-1]];a@#2)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X8M5JzWxyCHRWiPRQdkoOtowNtZWWVOtzjexwDMvJbUiNaVO2TrRIS/eyjYxOk/XUBdMxsZag5Rrqv0PKMrMK1FwSI@uNtIxrNUxieVCFjHGEDOBif3/DwA "Wolfram Language (Mathematica) – Try It Online") -3 bytes from Martin Ender [Answer] # [R](https://www.r-project.org/), 55 bytes ``` f=function(a,n)"if"(n<=sum(a|1),a[n],f(a,n-1-f(a,n-1))) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jUSdPUykzTUkjz8a2uDRXI7HGUFMnMTovVicNJKdrqAulNTU1/6dpJGsY6xjpAJUYGmj@BwA "R – Try It Online") Takes two inputs. [Answer] # [Standard ML (MLton)](http://www.mlton.org/), 58 bytes ``` fun a$n=if n<length$then List.nth($,n)else a$(n-1-a$(n-1)) ``` [Try it online!](https://tio.run/##JcqxCsIwFEbh3ae4Q4YEkkJRN/sAgptjEcmQNoHbP@K99vVjxOnwwZGNw8Za0dryAUWDqSyECyesmo3mBLoV0QGarfFwiSX1zSKM4R/n2h6ZhCaaT/7ox8fh52e3fb0LlCpdoYPWu3aunZHE0bl9AQ "Standard ML (MLton) – Try It Online") The function `a` takes the initial list and an index and returns the sequence element at that index. Example usage: `a [4,3,1] 5` yields `4`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` NṪịṭµ¡ ``` Takes a sequence **S** and an integer **k**, and adds **k** terms to **S**. [Try it online!](https://tio.run/##ASQA2/9qZWxsef//TuG5quG7i@G5rcK1wqH///9bMiwgMywgMV3/MjA "Jelly – Try It Online") ### How it works ``` NṪịṭµ¡ Main link. Left argument: S (sequence). Right argument: k (integer) µ¡ Combine the links to the left into a (variadic) chain and call it k times. The new chain started by µ is monadic, so the chain to the left will be called monadically. N Negate; multiply all elements in S by -1. Ṫ Tail; retrieve the last element, i.e., -a(n-1). ị At-index; retrieve the element of S at index -a(n-1). Since indexing is modular and the last element has indices n-1 and 0, this computes a( (n-1) - a(n-1) ). ṭ Tack; append the result to S. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ¡Ṡ!o_→ ``` [Try it online!](https://tio.run/##yygtzv7//9DChzsXKObHP2qb9P///2gTHWMdw1gA "Husk – Try It Online") Figured this out after a lot of frustration with Jo King's help. [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` a=lambda S,n:n<len(S)and S[n]or a(S,~a(S,~-n)+n) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9E2JzE3KSVRIVgnzyrPJic1TyNYMzEvRSE4Oi82v0ghUSNYpw5M6OZpaudp/i8oyswrUchNLNCAasyzStSINtJRMFRQUIjVydPUKUrMS0/VMDTQ1OTCqdgYqJ44xcakKDbBrvg/AA "Python 2 – Try It Online") [Answer] # CJam, 10 bytes ``` {{(_j-j}j} ``` For CJam, this does very well (It even beats 05ab1e!). This is an anonymous block that expects input in the form `i n` on the stack, where `i` is the index in the sequence and `n` is an array of starting numbers. The reason this works so well is because of the `j` operator, which provides memoized recursion from a set of starting values. ## Explanation: ``` { Function j(n) with [j(0), j(1), j(2)] = [4, 3, 1], return j(6): ( Decrement: 5 _ Duplicate: 5 5 j j(5): ( Decrement: 5 4 _ Duplicate: 5 4 4 j j(4): ( Decrement: 5 4 3 _ Duplicate: 5 4 3 3 j j(3): ( Decrement: 5 4 3 2 _ Duplicate: 5 4 3 2 2 j j(2) = 1: 5 4 3 2 1 - Subtract: 5 4 3 1 j j(1) = 3: 5 4 3 3 - Subtract: 5 4 0 j j(0) = 4: 5 4 4 - Subtract: 5 0 j j(0) = 4: 5 4 - Subtract: 1 j j(1) = 3: 3 }j End: 3 ``` [Answer] # Java (8), 60 bytes ``` int a(int[]a,int n){return n<a.length?a[n]:a(a,--n-a(a,n));} ``` Takes two inputs (integer-array `a` and integer `n`), and outputs the `n`'th value of the sequence. **Explanation:** [Try it here.](https://tio.run/##fVDLbsIwELzzFStOtvKAlnIhVFU/oOqBY5TDNjhgGjapvaZCUb49dayoXGgPXj9mZ2bHJ7xg0rSKTvvPoazRWnhDTd0MwDKyLmHQxIDC17zAeLyQ7IxiZwhoi2mt6MDHF8yp2KDAOEkoGXeSMusHgNZ91F5mUrs0eg9n7yB2bDQd8gJQjm4ArCwLUt8QrLrH@KGX2X1k9Se2@gd7umG9X7eIYajQHBrD8dUYvE6TLRbw7rh1DHxUUGljGdZL0KzOFpoqvFr15RSVahMYVWNGLdDPywz0dj3WKJrkAHZX67lp4zht/S@wQPHrGYOW0TyeTxn62T1CTWLK0Q8/) (Might take a few seconds.) ``` int a(int[]a,int n){ // Method with int[] and int parameters and int return-type return n<a.length? // If input `n` is smaller than the length of the array: a[n] // Output the `n`'th item of the array : // Else: a(a,--n-a(a,n)); // Recursive call with `n-1-a(n-1)` } // End of method ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` λN<α₅ ``` Outputs the infinite sequence. [Try it online.](https://tio.run/##yy9OTMpM/f//3G4/m3MbHzW1/v8fbaRjGAsA) (No test suite with all test cases at once, because there is [a bug](https://github.com/Adriandmen/05AB1E/issues/168) when using the recursive environment within an iterator.) Outputting the \$n^{th}\$ value or first \$n\$ values would cost an additional byte: [Output the (0-based) \$a(n)\$.](https://tio.run/##yy9OTMpM/f//3O7DK/xszm181NT6/3@0iY6xjmEslykA) [Output the first \$n\$ values.](https://tio.run/##yy9OTMpM/f//3O5Di/1szm181NT6/3@0iY6xjmEsl6EBAA) **Explanation:** ``` λ # Start a recursive environment # to output the infinite sequence # Using the (implicit) input-list I, start the sequence at a(0)=I[0], a(1)=I[1], # ..., a(n)=I[n], # For which we calculate the next a(n) value as follows: # (implicitly push a(n-1)) N< # Push n-1 α # Calculate the absolute difference between the two: |a(n-1)-(n-1)| ₅ # And use that as n'th value: a(|a(n-1)-(n-1)|) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs the `n`th term, 0-indexed. Change the second `g` to `h` to output the first `n` terms instead. ``` ÈgZw}gV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGdad31nVg&input=MTAKWzIsMywxXQ) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ ~~31~~ ~~30~~ 29 bytes ``` a_f@n_:=a[--t-a@t]&@@a[[t=n]] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8xPs0hL97KNjFaV7dEN9GhJFbNwSExOrrENi829n9gaWZqiUNAUWZeSbRrcka@Q7Wycq11SGJSTmp0WrSycqxDpk51po6RaW0sSJ9DNVe1kY5hrQ6IMoYwjGEMEzCDq/Y/AA "Wolfram Language (Mathematica) – Try It Online") Input `f[initial...][n]`, e.g. as `f[2, 1][3]`. ``` a_f@n_:= f[initial...][n], where a=f[initial...] a[[t=n]] attempt to take an index a[--t-a@t]&@@ if out of bounds, recurse ``` --- ### Alternative input formats (also 29 bytes): ``` f=f[#,--t-#~f~t]&@@#[[t=#2]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NNi1aWUdXt0RXuS6triRWzcFBOTq6xFbZKDZW7X9gaWZqiUNAUWZeSbRrcka@g7J1SGJSTmo0SFNmrE51po6RaS1QZV1wcmJeXTVXtZGOYa0OiDKGMIxhDBMwg6v2PwA "Wolfram Language (Mathematica) – Try It Online") Input `[initial, n]`, e.g. as `f[{2, 1}, 3]`. ``` h:f@a_=h[--t-h@t]&@@a[[t=#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/DKs0hMd42I1pXt0Q3w6EkVs3BITE6usRWOTZW7X9gaWZqiUNAUWZeSbRrcka@g7J1SGJSTmp0WrRybHRmrE51po6RaS1QaV1wcmJeXTVXtZGOYa0OiDKGMIxhDBMwg6v2PwA "Wolfram Language (Mathematica) – Try It Online") Input `[initial][n]`, e.g. as `f[{2, 1}][3]`. [Answer] # [Nibbles](http://golfscript.com/nibbles), 4 bytes ``` .~~_=`($ ``` explanation ``` .~~ # append until null (aka always in this case) _ # first input int list = # array subscript (aka haskell !!) `( # uncons (returning head) $ # second value from uncons (the tail) ``` Note that the `$` can't also be implicit due to part of the uncons bin representation using part of its encoding after its arg :( I say this is non competing because this problem influenced the idea to have the `.~~` operator, although something like this was definitely needed and its a standard op in Husk. [Answer] # Perl, 38 +3 (-anl) bytes ``` {print;push@F,$_=$F[$#F-$F[$#F]];redo} ``` [Try It Online](https://tio.run/##K0gtyjH9/7@6oCgzr8S6oLQ4w8FNRyXeVsUtWkXZTRdCxcZaF6Wm5Nf@/2@kYPj/X35BSWZ@XvF/3cS8HAA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` #`r[=ˆŽ¼}[¯¾¯¾è-è=ˆ¼ ``` Expects the input as a space-separated string, keeps outputting indefinitely; pretty straightforward implementation Example run: ``` $ 05ab1e -e '#`r[=ˆŽ¼}[¯¾¯¾è-è=ˆ¼' <<< '3 2 1' 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~95~~ ~~93~~ ~~91~~ 90 bytes ``` a->i->{int j=0,b[]=new int[++i];for(;j<i;j++)b[j]=j<a.length?a[j]:b[~-j-b[j-1]];return b;} ``` [Try it online!](https://tio.run/##ZY5BT4QwEIXv/Io50gDNEj1ZwHgx8eCJI@mhsF1shbaWsoYQ/OtYgY2JzmU635t5fZJdWaINV/L8voreaOtAeoZHJzr8ZC2bBhL8Ey6japzQCj8fDxIEZqw70UDTsWGAVyYUzAH4OvjgmPPtqsUZeq@GpbNCtRUFho7NnyqnwfEe69Fh43UX7hmw0/t@aLSn3Jb8Y@Sq4ZgZ002h4p/geUXn@/guThd08PSEECKb@xJs7chxC55tV/Hv/OLdW27j3a4o4M@HkMPKkkIkxew5yPwU1xXNbwGiSFBy0TYkMhNERhGqK0lzmTHccdW6t0fm54e6@kpk4qUkpZRY7karoCbLSoJl/QY "Java (OpenJDK 8) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), `-a` 30 bytes ``` #!/usr/bin/perl -a use 5.10.0 say$F[@F]=$F[-1-$F[-1]]while 1 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLFLdrBLdYWSOka6oLJ2NjyjMycVAXD//@NFYwUDP/lF5Rk5ucV/9dN/K/ra6pnaKBnAAA "Perl 5 – Try It Online") ]
[Question] [ The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2. For example: ``` | | Input | Starting Word | Output | |----|-----------------------------|---------------|-------------| | #1 | Hello world -wo -ld +Ea +th | Hello world | Hello Earth | | #2 | Hello World -wo -ld +Ea +th | Hello World | Hello Worth | | #3 | Hello -llo +y | Hello | Hey | | #4 | Red -R -d +Gr +en | Red | Green | | #5 | mississippi -is -i +lz +p | mississippi | mlzslzspppp | | #6 | Football -o -a +a +i | Football | Fiitbill | | #7 | mississippi -is -i +iz +p | mississippi | mpzspzspppp | ``` ### Explanation The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of `mississippi -is -i +iz +p` to give the output `mpzspzsppp` (see example `#7` above) ``` | Step | Input | Output | |------ |--------------------------- |------------- | | #1 | mississippi -is -i +iz +p | | | #2 | mississippi -is +iz | mizsizsippi | | #3 | mizsizsippi -i +p | mpzspzspppp | ``` ### Rules * Inputs are always in this order `<starting_string> <list_of_letters_to_replace> <replacement_letters>`. * Letters to replace and replacement groups will never be mixed (ie: there will never be `-a +i -e +o`). * Letters to replace are *always* prefixed with `-` and replacement letters are always prefixed with `+`. (The prefix is mandatory) * There may be more than one set of letters to replace, so you'd need to look at the prefix. * Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be `-a -e +i`) * Replacements are case-sensitive (see example `#1` and `#2`). * Replacements are done in the order they were given in the input. * Letter replacements can be replaced with other replacements. See example `#6`. * The first segment (starting word) will *never* include `-` or `+` characters. * This is code-golf so shortest bytes win. ## 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=96473,OVERRIDE_USER=38505;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ 17 bytes ``` IIð¡€áIð¡€á‚øvy`: ``` [Try it online!](http://05ab1e.tryitonline.net/#code=SUnDsMKh4oKsw6FJw7DCoeKCrMOh4oCaw7h2eWA6&input=bWlzc2lzc2lwcGkKLWlzIC1pCitpeiArcA) **Explanation** ``` I # read starting string I # read letters to be replaced ð¡ # split on space €á # and remove "-" I # read replacement letters ð¡ # split on space €á # and remove "+" ‚ø # zip to produce pairs of [letters to replace, replacement letters] vy`: # for each pair, replace in starting string ``` Or with a less strict input format ``` vy`: ``` [Try it online](http://05ab1e.tryitonline.net/#code=dnlgOg&input=W1snaXMnLCAnaXonXSxbJ2knLCAncCddXQptaXNzaXNzaXBwaQ) [Answer] ## JavaScript (ES6), ~~85~~ 83 bytes ``` f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0] ``` ### Test cases ``` f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0] console.log(f("Hello world -wo -ld +Ea +th")); console.log(f("Hello World -wo -ld +Ea +th")); console.log(f("Hello -llo +y")); console.log(f("Red -R -d +Gr +en")); console.log(f("mississippi -is -i +lz +p")); console.log(f("Football -o -a +a +i")); console.log(f("mississippi -is -i +iz +p")); ``` [Answer] ## Pyke, ~~13~~ 11 bytes ``` z[zdcmt)[.: ``` [Try it here!](http://pyke.catbus.co.uk/?code=z%5Bzdcmt%29%5B.%3A&input=Hello+world%0A-wo+-ld%0A%2BEa+%2Bth%0A) ``` z - input() [zdcmt) - def func(): zdc - input().split(" ") mt - map(>[1:], ^) - func() [ - func() .: - translate() ``` Or 2 bytes if in a different input format: ``` .: ``` [Try it here!](http://pyke.catbus.co.uk/?code=.%3A&input=%5B%22wo%22%2C+%22ld%22%5D%0A%5B%22Ea%22%2C+%22th%22%5D%0AHello+world&warnings=0) [Answer] ## Perl, 58 bytes **57 bytes code + 1 for `-p`.** Requires first item on one line, then the replacements on the next. Big thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada) who came up with a different approach to help reduce by 4 bytes! ``` $a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee ``` ### Usage ``` perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'Football -o -a +a +i' Fiitbill ``` ``` perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi -is -i +iz +p' mpzspzspppp ``` ``` perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi -ippi -i -mess +ee +e +tenn' tennessee ``` [Answer] # GNU sed 86 Bytes Includes +1 for -r ``` :;s,^([^-]*)(\w+)([^-]*-)\2( [^+]*\+)(\w*),\1\5\3\2\4\5, t;s,-[^-+]*,,;s,\+[^-+]*,,;t ``` [Try it online!](http://sed.tryitonline.net/#code=OjtzLChbXi1dfF4pKFx3KykoW14tXSotKVwyKCBbXitdKlwrKShcdyopLFwxXDVcM1wyXDRcNSwKdDtzLC1bXi0rXSosLDtzLFwrW14tK10qLCw7dA&input=SGVsbG8gd29ybGQgLXdvIC1sZCArRWEgK3RoCkhlbGxvIFdvcmxkIC13byAtbGQgK0VhICt0aApIZWxsbyAtbGxvICt5ClJlZCAtUiAtZCArR3IgK2VuCm1pc3Npc3NpcHBpIC1pcyAtaSArbHogK3AKRm9vdGJhbGwgLW8gLWEgK2EgK2kKbWlzc2lzc2lwcGkgLWlzIC1pICtpeiArcA&args=LXI) Example: ``` $ echo 'Hello world -wo -ld +Ea +th'|sed -rf replace.sed Hello Earth ``` [Answer] # PHP, ~~98~~ 97 bytes ``` for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s); ``` This challenge describes the exact behaviour of str\_replace so for php it's all about making the arrays of replacements. I tried to do it using only one "substring" but that might not be the best solution. Use like: ``` php -r "for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);" "mississippi" "-is" "-i" "+iz" "+p" ``` edit: 1 byte saved thanks to Titus [Answer] # Java 7, ~~153~~ 133 bytes ``` String c(String[]a){String r=a[0],z[]=a[1].split(" ?-");for(int i=0;i<z.length;r=r.replace(z[i],a[2].split(" ?[+]")[i++]));return r;} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/FmSlYw) ``` class M{ static String c(String[] a){ String r = a[0], z[] = a[1].split(" ?-"); for(int i = 0; i < z.length; r = r.replace(z[i], a[2].split(" ?[+]")[i++])); return r; } public static void main(String[] a){ System.out.println(c(new String[]{ "Hello world", "-wo -ld", "+Ea +th" })); System.out.println(c(new String[]{ "Hello World", "-wo -ld", "+Ea +th" })); System.out.println(c(new String[]{ "Hello", "-llo", "+y" })); System.out.println(c(new String[]{ "Red", "-R -d", "+Gr +en" })); System.out.println(c(new String[]{ "mississippi", "-is -i", "+lz +p" })); System.out.println(c(new String[]{ "Football", "-o -a", "+a +i" })); System.out.println(c(new String[]{ "mississippi", "-is -i", "+iz +p" })); } } ``` **Output:** ``` Hello Earth Hello Worth Hey Green mlzslzspppp Fiitbill mpzspzspppp ``` [Answer] # PHP, 164 Bytes ``` preg_match_all("#^[^-+]+|-[\S]+|[+][\S]+#",$argv[1],$t);for($s=($a=$t[0])[0];++$i<$c=count($a)/2;)$s=str_replace(trim($a[+$i],"-"),trim($a[$i+$c^0],"+"),$s);echo$s; ``` [Answer] # Vim, 25 bytes `qq+dE+r-PdiW:1s<C-R>"-g<CR>@qq@q` Assumes input in this format: ``` mississippi -is -i +lz +p ``` * `+dE+r-PdiW`: Combines `-` and `+` into single register, with the `+` turned into a `-`. * `:1s<C-R>"-g`: Uses the register as a code snippet, inserted directly into the `:s` command, with `-` as the separator. [Answer] # [Convex](http://github.com/GamrCorps/Convex), 19 bytes ``` ¶:äz{S*"-+"-ä~@\ò}/ ``` [Try it online!](http://convex.tryitonline.net/#code=wrY6w6R6e1MqIi0rIi3DpH5AXMOyfS8&input=&args=SGVsbG8gV29ybGQ+LVdvIC1sZA+K0VhICt0aA&debug=on) [Answer] # R, 98 94 bytes Edit: saved 4 bytes thanks to @rturnbull ``` i=scan(,"");s=i[1];i=gsub("\\+|-","",i[-1]);l=length(i)/2;for(j in 1:l)s=gsub(i[j],i[l+j],s);s ``` **Ungolfed and test cases** Because `scan` (reads input from stdin) doesn't work properly in R-fiddle I showcase the program by wrapping it in a function instead. Note that the function takes a vector as an input and can be run by e.g.: `f(c("Hello world", "-wo", "-ld", "+Ea", "+th"))`. The gofled program above would prompt the user to input using stdin whereby typing `"Hello world" -wo -ld -Ea +th` in the console would yield the same result. [Run the code on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=ZleCbk79) ``` f=function(i){ s=i[1] # Separate first element i=gsub("\\+|-","",i[-1]) # Remove + and - from all elements except first, store as vector i l=length(i)/2 # calculate the length of the vector i (should always be even) for(j in 1:l)s=gsub(i[j],i[l+j],s) # iteratively match element j in i and substitute with element l+j in i s # print to stdout } ``` [Answer] ## Haskell, ~~85~~ 78 bytes ``` import Data.Lists g=map tail.words a#b=foldl(flip$uncurry replace)a.zip(g b).g ``` Usage example: `("mississippi" # "-is -i") "+lz +p"` -> `"mlzslzspppp"`. How it works: ``` g=map tail.words -- helper function that splits a string into a -- list of words (at spaces) and drops the first -- char of each word zip(g b).g -- make pairs of strings to be replaced and its -- replacement foldl(flip$uncurry replace)a -- execute each replacement, starting with the -- original string -- -> "flip" flips the arguments of "uncurry replace" -- i.e. string before pair of replacements -- "uncurry" turns a function that expects two -- lists into one that expects a list of pairs ``` Edit: @BlackCap found 6 bytes to save and I myself another one. [Answer] # Python 3, 93 byte ``` def f(s): s,m,p=s for n,o in zip(m.split(),p.split()):s=s.replace(n[1:],o[1:]) return s ``` [Try it online!](https://repl.it/Dxv1/1) Input is a list with strings, replacement strings are space separated. Example input: `['mississippi','-is -i','+iz +p']` [Answer] ## PowerShell v2+, 90 bytes ``` param($a,$b,$c)-split$b|%{$a=$a-creplace($_-replace'-'),((-split$c)[$i++]-replace'\+')};$a ``` Takes input as three arguments, with the `-` and `+` strings space-separated. Performs a `-split` on `$b` (the `-split` when acting in a unary fashion splits on whitespace), then loops `|%{...}` through each of those. Every iteration we're removing the `-`, finding the next `[$i++]` replacement string and removing the `+` from it, and using the `-creplace` (case-sensitive replacement) to slice and dice `$a` and store it back into `$a`. Then, `$a` is left on the pipeline and output is implicit. ``` PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'mississippi' '-is -i' '+iz +p' mpzspzspppp PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello world' '-wo -ld' '+Ea +th' Hello Earth PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello World' '-wo -ld' '+Ea +th' Hello Worth ``` [Answer] # PHP, 106 bytes ``` for($s=($v=$argv)[$i=1];$i++<$n=$argc/2;)$s=str_replace(substr($v[$i],1),substr($v[$n+$i-1],1),$s);echo$s; ``` straight forward approach. Run with `php -r '<code> <arguments>`. ]
[Question] [ Given a matrix of positive integers, output whether it's possible to generate it by starting with an empty1 matrix of the same dimensions and repeatedly filling a whole row or a whole column with the same value, overwriting any values already written. ### Example The following matrix: $$\begin{pmatrix}1&1&1\\2&3&4\\2&3&4\end{pmatrix}$$ Can be obtained with the following steps: $$ \begin{pmatrix}2&0&0\\2&0&0\\2&0&0\end{pmatrix}\rightarrow \begin{pmatrix}2&3&0\\2&3&0\\2&3&0\end{pmatrix}\rightarrow \begin{pmatrix}2&3&4\\2&3&4\\2&3&4\end{pmatrix}\rightarrow \begin{pmatrix}1&1&1\\2&3&4\\2&3&4\end{pmatrix} $$ ### Test cases ``` [[1,1,1,1,1], [2,3,4,5,6], [2,3,4,5,6]] => true [[1,1,1,1,1], [2,3,4,1,6], [2,3,4,1,6]] => true [[1,1,1,1,6], [2,3,4,1,6], [2,3,4,1,6]] => true [[1,1], [1,1]] => true [[1,2], [2,1]] => false [[1,2], [3,4]] => false [[1,1,2], [4,5,2], [4,3,3]] => false [[1,2,4], [2,1,4], [3,3,3]] => false ``` Shortest code in each languages win. 1 You can assume it is initially filled with zeros [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 21 bytes ``` ø<<yyc$jn m$tx<fn lq ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY3LSsNAFIb38xQ_JYsWJkJqBSmZFimuzaILIWYxNDN2dJLJZYIT6JvoohsRH0Bw71P0bZy0Iihzrv93zpnnty1vH4XW7-kovF0lySg7vKiiMo1FQn6KuuNaSSVyJI3QXS4ICUOsTDVIsjEFWtM1G0Fxtb6BasGhlbVawHQWRiLnVpyRvt_M5-PrGnzCFmMeLvjEu7eBQMIxt_QRT1vRCLhlv3OM9czt1qz3oCdEsrvXzsrw8uPrM479VvBQogisi2UJXZ_Y4b7gqgRDbghQNQj87TSN6DSj6ZRGWfZX9u8IzunsN_8b8aJHEZ0dR4b-Istw-m6_P-Vv) ## Explanation The algorithm employed here repeatedly removes all rows of equal elements, removes all columns of equal elements, until we reach a fixed point where additional operations stop changing things. If that fixed point is the empty list we return `True` otherwise `False`. * `lq` determines if all elements of a list are equal. * `fn lq` takes a list of lists and filters out all rows of equal elements. * `tx` transposes a list. * `jn m` takes a function and composes it with itself. * `jn m$tx<fn lq` takes a list of lists removes all constant rows, transposes it to remove all constant columns and transposes back. * `yyc` repeats an operation until it reaches a fixed point * `ø` determines if a list is empty ## Alternate version, 21 bytes ``` ø<<yyc$tx<fn lq<.<tx ``` ## Reflection It's really nice to see `yyc` paying off already. The weak point in this answer is really with the glue. We have all the right components, but we waste a couple bytes putting it together. * `jn` could use an infix. We already have `fjn`, so I don't know why there isn't an infix. Even if it's 3 bytes it would save here if it had the right precedence. * `jn m` is a really expensive way to compose a function with itself. This should be a built in operator, probably 2 bytes long. It would save 2 bytes here. * The composition operator we really want is something like `f<|<g=f<g<f<g`, which alternates two functions back and forth. We have the similar "sandwich compose" `<.<` which is useful in the alternate answer, but this other operator is probably worth having. With this we would save 3 bytes. * It might be worth having a stronger version of `yyc` which stops when there is any repeated value. With this we could do away with the whole double compose and just write `ø<<yyC$tx<fn lq`. * We have column map with `mC` it might be worthwhile implementing a column filter. * `tx` could be an `Iso`. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 6.5 bytes (13 nibbles) ``` /\`.$|`'$>>=~ ``` Returns truthy (nonempty list) if the matrix cannot be 'painted with lines', falsy (empty list) if it can. ``` /\`.$|`'$>>=~ `. # iterate while unique $ # (starting with input): | # filter `' # the transpose of $ # the result so far =~ # by groups of its identical elements >> # without the first group # (so: all elements equal => empty list = falsy # different elements => nonempty list = truthy) \ # reverse the list of results / # and return the first element # (which will be an empty list if the matrix # can be 'painted with lines', or nonempty list # if it cannot). ``` [![enter image description here](https://i.stack.imgur.com/1fCLB.png)](https://i.stack.imgur.com/1fCLB.png) [Answer] # [Rust](https://www.rust-lang.org), ~~436~~ 280 bytes ``` |a:&[&[u8]]|f(&|c,d|a[c][d],a.len(),a[0].len());fn f(a:&dyn Fn(usize,usize)->u8,b:usize,c:usize)->bool{b<1||c<1||h(a,b,c)||h(&|e,f|a(f,e),c,b)}fn h(a:&dyn Fn(usize,usize)->u8,b:usize,c:usize)->bool{(0..b).any(|x|(0..c).all(|y|a(x,y)==a(x,0))&&f(&|d,e|a(d-(d>x)as usize,e),b-1,c))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nZDBTsMwDIbFtU_AMewQJZJbtYWhqtBx4yWiHJI03SqVbFpbaaXpk3CZEDwAjwNPQ7KOC-KEIjm_Hfuz45e3fd92x4_KoCdRG0LR2OgOrYv3vqvC7Ovi0oocM8z6jHNbEWwVlFYwxVnJQUSNdjUgWMxnSe8cqSKuphwMejSkb-tnDSdLw1WfgcznkMp_gnK7bUZ5n1irvNkQARIU9QpbDZUVpAJNQYGkk8Nv_oEncRRJGgkzEHuw3lPOaxpiB4c_wECLwt8xpRj7b5ag3UMZknJ1oKJFM9VNIcPEDUeneUGfu92-Nl1jrshizB-mBaA18ftK4Hw4BJilcA03sITbXx53CwuCPxDBzEhdPvIFCefBKffc9_iaLmf1DQ) ## Explanation The basic idea is we check if there is at least one row or column with all elements the same, then recurse over the remaining rows and columns. Since transposing and editing arrays is a bit tricky in rust instead we pass callback functions that can represent transformations on the original matrix. ``` // This function wraps the main program, converting our array into a function that will return the array position from a coordinate postion let g = |a: &[&[u8]]| f(&|c, d| a[c][d], a.len(), a[0].len()); // f performs the transposition. Returns true if the array is empty, or if h(a), or h(a) transposed. b and c are the size of the array. fn f(a: &dyn Fn(usize, usize) -> u8, b: usize, c: usize) -> bool { b < 1 || c < 1 || h(a, b, c) || h(&|e, f| a(f, e), c, b) } // h is the core of the function. Check if there is at least one row that is all equal and that f(the remaining matrix) fn h(a: &dyn Fn(usize, usize) -> u8, b: usize, c: usize) -> bool { (0..b).any(|x| { (0..c).all(|y| a(x, y) == a(x, 0)) && f(&|d, e| a(d - (d > x) as usize, e), b - 1, c) }) ``` [Answer] # [R](https://www.r-project.org), 71 bytes ``` f=\(m,n=o,o=sum(m|1))`if`(n,f(t(m[,apply(m,2,\(l)any(l-l[1]))]),n-1),o) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZA9CoNAEIVJa5cbCGlmYCzWREmzaXMIFVzEBWF_RFeIkJukMUXqnCc5TSQimC6E8Ip5xXvfwLtcm-FeCGOsU5UpZaUUv3VOBvvHUfIUNBluyfK206DPDDGvZA6GJDjQCYm6Vv0YCikFhcL0oAKVsAwxQzIBQ7I44Z6r9ecb0MI11QkKYDTL80Pa0o4iipceKUL0Nz4_-FKotvS871FsgWK_oOJ_oMJ3cZwjnCuu6cppmWGY7gs) Returns truthy (nonzero value) if the matrix cannot be 'painted with lines', falsy (zero) if it can. Performs n (=number of elements of matrix) iterations of removing all-the-same columns and transposing, and outputs the number of elements remaining at the end. Since at least one row or column of a paintable-with-lines matrix must be all-the-same at the start, this number of iterations is always enough to check paintability. [Answer] # [Python](https://www.python.org) + NumPy, 64 bytes ``` f=lambda A,c=2:f(A[x].T,c-all(x))if c*any(x:=A.ptp(1)>0)else c>0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZA9boQwEIV7TjGisiOvBeRHERIo3CEdS2FYW7FkbMuYCA6RE6ShSfocZ28TE0iRVRJNNd97b2Y0r-929k9GL8vb6MXh_vwgCsX69sSgIl2R5QJV9dTQR9IdmFJowlgK6K6YntGUFxW13qIUlwnmauDQlck-50X21jgPeuztDGwAbSNhHLQgNRjLNUowdZydEKaDVdKj-KiPOsZ5BJIYKKD95lCUEOOAA9SWMufYjPgzU0jigFfvV2eol15xtELrpPYoDCJidW1HLeePuk7JXg2JoM7INbkht-TuomvWpd6NPIp-j6Q_IulfkUvTv5Fsl9NNECy8dLv8Ew) As @TheThonnu points out per meta consensus (thanks @pxeger for sharing the exact link in the comments) this can be **62 bytes**: simply drop the last two characters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` EÐḟZ$ÐL ``` A monadic Link that accepts a matrix and yields an empty list if possible (falsey) or a non-empty list if not (truthy). **[Try it online!](https://tio.run/##y0rNyan8/9/18ISHO@ZHqRye4PP/cPvRSQ93zvj/PzraUAcCzWJ1uBSizXWMdczhPCMgzwTKiwUA "Jelly – Try It Online")** ### How? ``` EÐḟZ$ÐL - Link: matrix, M ÐL - loop while distinct, applying: $ - last two links as a monad - f(current): Ðḟ - filter discard those for which: E - all equal? Z - transpose ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ≬~≈F∩İ÷ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4omsfuKJiEbiiKnEsMO3IiwiIiwiW1sxLDEsMSwxLDFdLFsyLDMsNCw1LDZdLFsyLDMsNCw1LDZdXVxuW1sxLDEsMSwxLDFdLFsyLDMsNCwxLDZdLFsyLDMsNCwxLDZdXVxuW1sxLDEsMSwxLDZdLFsyLDMsNCwxLDZdLFsyLDMsNCwxLDZdXVxuW1sxLDJdLFsyLDFdXSJd) *-1 byte: changed output method (thanks to @emanresuA)* Outputs an empty list if it's possible or a non-empty list if not. ``` ≬ # three element lambda: ~≈ # filter by: are all elements equal F # remove elements of a that are in b ∩ # transpose İ # apply function while results are unique, collecting results ÷ # push each item to stack ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 55 bytes ``` f(a)=g(a)||g(a~) g(a,i)=!a||[#Set(c)<=f(a[,^i++])|c<-a] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN83TNBI1bdOBRE0NkKzT5AKSOpmatoqJNTXRysGpJRrJmja2QFXROnGZ2tqxmjXJNrqJsVDtFxILCnIqNRIVdO0UCooy80qATCUQR0kBZLCmjkJ0tKEOFFob6RjrmOiY6pghWLFAFegKDOEKDFEVmOFRYA3EEKYRUA7OBCqCmWBkDbIRRBrrGEPldUxAioGkMVgwVhPiL1jwAAA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 59 bytes ``` f(a)=if(a!=b=g(g(a)),f(b),!a) g(a)=Mat([c|c<-a~,#Set(c)>1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN63TNBI1bTOBpKJtkm26RjqQq6mTppGkqaOYqMkF4tr6JpZoRCfXJNvoJtbpKAenlmgka9oZxmpCjbiQWFCQU6mRqKBrp1BQlJlXAmQqgThKCmlg0xSiow11oNDaSMdYx0THVMcMwYoFqkBXYAhXYIiqwAyPAmsghjCNgHJwJlARzAQja5CNINJYxxgqr2MCUgwkjcGCMH_BgggA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~89~~ 84 bytes ``` f=m=>m<(m=m.map(u=x=>x.map((y,j)=>x.some(v=>v-y)&m.some(v=>v[j]-y)?u=y:f)))?f(m):u>f ``` [Try it online!](https://tio.run/##pYzLCoMwEEX3@QpXJQNRiX0spIkfIi6CTUrFMWKM6NdbLX3QrlrKzGLOcO@p1KBc2V3aPmzsSc9GLItC4pGiwAhVS70YhRxvJ51YBSs4i5oOQg7hBBt8YV4VyyfzYkoNAGSGIqRemrm0jbO1jmp7pobmJAhyzu5TsBUTtmU7tmeHTyQFQBDHQd95Tci3Iv4u4r@IDv@LkkeHP9NG1U7PVw "JavaScript (Node.js) – Try It Online") Notice that only change is (number) => `m=>m<m.ma...`, so the first change makes string larger [Answer] # [Haskell](https://www.haskell.org/), 94 bytes ``` e=[]:e s(a:b)=all(==a)b g m=m==[]||any s m&&p(filter(not.s)m) p m=g m||g(foldr(zipWith(:))e m) ``` [Try it online!](https://tio.run/##ZcqxCsMgFIXh3ae4Qwn3ghSSdgr4HB3EwRCTSNWIurT47lY6dClnOMP3Hzo/jXOtGSHVbFhGPS8ktHMohKaF7eCFFx1r1eEFGfwwRNysKyZhOMs1kycWe9XLWnfcTrcmfNv4sOXAmciAp@a1DSBgPRlATDYUuEAEKUc@KS4nPir1J31fu/H771X7AA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 98 bytes ``` import Data.List s=(<2).length.nub g m=all s m||any s m&&p(filter(not.s)m) p m=g m||g(transpose m) ``` [Try it online!](https://tio.run/##PYoxCgMhEAB7X2ERDgURckkZu5T5gVyxAeNJdBV3UwTu7@auCVPMFLMCvUPOY6TSamd5Bwb7SMSCnLrN2uaAkVeLn6eIsjjIWZIs2wb4PWKamnqlzKErrGxJFy3a/sXjiYo7ILVKQRY9CiR0rSfkU/P@bHYW42dzMde/l/ED "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 (or 7) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ2FøʒË≠]˜P ``` Outputs a 05AB1E truthy/falsey result (`1` if truthy; any other positive integer if falsey). [Try it online](https://tio.run/##yy9OTMpM/f//3BQjt8M7Tk063P2oc0Hs6TkB//9HRxvqAGGsTrSRjrGOCZyOBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/3NTjNwO7zg16XD3o84FsafnBPxX0gtzsc9UUtAoKSotyajUVDq8GshJS8wpTgVyanX@R0dHG@oAYaxOtJGOsY4JnI7VUYBKIUvrmOqYobBxKDNEUmaIrsyMoDKgIIiEco3AalC4KC4ECYBcA6GNdYzhKqH@MQTTxhCpWAA). Could be 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) by outputting an empty list for truthy and non-empty matrix for falsey, even though both are considered falsey in terms of 05AB1E booleans, by removing the final three bytes: ``` Δ2FøʒË≠ ``` [Try it online](https://tio.run/##yy9OTMpM/f//3BQjt8M7Tk063P2oc8H//9HRhjpAGKsTbaRjrGMCp2MB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/3NTjNwO7zg16XD3o84F/5X0wlzsD60PzFRS0CgpKi3JqNRUOrwayElLzClOBXJqdf5HR0cb6gBhrE60kY6xjgmcjtVRgEohS@uY6pihsHEoM0RSZoiuzIygMqAgiIRyjcBqULgoLgQJgFwDoY11jOEqof4xBNPGEKlYAA). **Explanation:** ``` Δ # Loop until the result no longer changes: 2F # Inner loop 2 times: ø # Zip/transpose the matrix; swapping rows/columns # (which will use the implicit input-matrix in the very first iteration) ʒ # Filter this matrix of rows by: Ë≠ # Check that all values in the row-list are NOT equal ] # Close the filter, loop, and changes-loop ˜ # Flatten the remaining list P # Take the product (1 for an empty list; or a positive integer if not empty†) # (after which the result is output implicitly) ``` † Note that the matrix can never contain just `1`s at this point, since it would have been reduced further. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` ⊞υθFυF²«≔E⌊ιEι§νμι≔Φι⁻⌈λ⌊λκ¿⁻ικ¿κ⊞υκP¹ ``` [Try it online!](https://tio.run/##bY4/D4IwEMVn@RQ39pI6gMbFicXEgcS9YSAIcqEU7B9DYvzstQXZzA137@X9Xq7uKl2PlfT@5kzHHIcnnpN21MAcwrIzhHeyy42hh2JFNbGCFA1uYIQcoiYOub2qezMzxWFADD6Flo25kLSNjrFAOhM65oWXuDi/O1J9pKgFtgYpOgjR6BG2B0MIGmkaKJy0NGlSlqUB/HgvhEj5OqeSJwAi4wd@/CfL0u9f8gs "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` if the array can be painted, nothing if not. Explanation: ``` ⊞υθFυ ``` Start a breadth-first search with the original array. ``` F²« ``` Loop over the transpose as well as the array. ``` ≔E⌊ιEι§νμι ``` Transpose the array. ``` ≔Φι⁻⌈λ⌊λκ ``` Remove rows of identical elements. ``` ¿⁻ικ ``` If this results in a smaller array, then: ``` ¿κ⊞υκ ``` If this array is not empty then add it to the list of arrays to search. ``` P¹ ``` But if it is empty then output that it can be painted. [Answer] # JavaScript (ES6), ~~112~~ 95 bytes Returns a Boolean value. ``` f=m=>m+''==(m=(g=a=>a.filter((v,x)=>new Set(v.at?v:m.map(r=>r[x])).size>1))(m.map(g)))?m<1:f(m) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZBNCsIwEIVxJz1Fds5gjMQ_RJx4CJdFJGhShKaVNlbxKm5c6KH0NCpVQd1YZvWY974H73BK0qU5Hs8bb1vDy9ySI-WajQYROIKINCkt7Cr2JgMo-A5JJWbLpsZDIbSfFCMnnF5DRioLdzNEka_2RklEKB8RIk7cWI4sOCxrrrX6Ik3yNDYiTiOwEAaMhZI_b8YfssO7vMf7fPAtg3sJa7eZzzYmCP4FyU-QrAL6SVYHdV4Z-XZbHeemHOS1_w0) ### Commented ``` f = m => // f is a recursive function taking the input matrix m[] m + '' == ( // compare the current version of m[] with ... m = ( // ... the updated one g = a => // g is a helper function taking an array a[]: a.filter((v, x) => // for each entry v at position x in a[]: new Set( // turn into a set: v.at ? // if v is an array: v // use v directly : // else: m.map(r => // extract the x-th column from m[] r[x] // ) // ).size > 1 // remove if there's less than 2 distinct values ) // end of filter() )(m.map(g)) // invoke g on each row of m[] and then on the result ) ? // if m[] was not updated: m < 1 // return true if m[] is empty, false otherwise : // else: f(m) // try to remove more rows or columns ``` [Answer] # [Factor](https://factorcode.org) + `combinators.extras`, 62 bytes ``` [ [ [ [ all-eq? ] reject flip ] twice ] to-fixed-point { } = ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZFBTsMwEEXFNqf4HCCV0gaEQC1LxIYNYoW6MGZcGVzbtR1RFOUkbLIp52ELp8GRpTSCUKFZzHzr_T_S-O1dMB6Ma7-OPu5ur2-uzsHN-kFqFh_9hLbBMY-VM5WVegVPm4o0Jz-k8ExOk4J1FMKrdVIHXGR1VqNG0VeDLOopZihxgtMR3eAY8wWCqyg7YC5-mIvD5jH4X-aEpWkEmPY5A0Aw5X8R3Z5xYs90N9jPs1h_ZZaDvWW_YcTR7Kog8rPPxT1SMaVy2lxiCUdPxAOEkjaq8CI5dd3kQm7pMbem-8I6xs2xTCm7NbOYpLltU_8G) * `[ ... ] to-fixed-point` Call `[ ... ]` on the input until it stops changing * `[ ... ] twice` Call `[ ... ]` twice * `[ all-eq? ] reject` Remove the rows with numbers that are all equal * `flip` Transpose * `{ } =` Is it empty? ]
[Question] [ > > Compute, O friend, the number of the cattle of the sun which once grazed upon the plains of Sicily, divided according to color into four herds, one milk-white, one black, one dappled and one yellow. The number of bulls is greater than the number of cows, and the relations between them are as follows: > > > **White bulls \$= (\frac{1}{2} + \frac{1}{3})\$ black bulls + yellow bulls,** > > **Black bulls \$= (\frac{1}{4} + \frac{1}{5})\$ dappled bulls + yellow bulls,** > > **Dappled bulls \$= (\frac{1}{6} + \frac{1}{7})\$ white bulls + yellow bulls,** > > **White cows \$= (\frac{1}{3} + \frac{1}{4})\$ black herd,** > > **Black cows \$= (\frac{1}{4} + \frac{1}{5})\$ dappled herd,** > > **Dappled cows \$= (\frac{1}{5} + \frac{1}{6})\$ yellow herd,** > > **Yellow cows \$= (\frac{1}{6} + \frac{1}{7})\$ white herd.** > > > If thou canst give, O friend, the number of each kind of bulls and cows, thou art no novice in numbers, yet can not be regarded as of high skill. Consider, however, the following additional relations between the bulls of the sun: > > > **White bulls + black bulls = a [square number](https://en.wikipedia.org/wiki/Square_number),** > > **Dappled bulls + yellow bulls = a [triangular number](https://en.wikipedia.org/wiki/Triangular_number).** > > > If thou hast computed these also, O friend, and found the total number of cattle, then exult as a conqueror, for thou hast proved thyself most skilled in numbers. > > > - Archimedes > > > Some clarifications: * black herd = black bulls + black cows, white herd = white bulls + white cows, etc. * \$(\frac{1}{2} + \frac{1}{3})\$ black bulls + yellow bulls, means only the black bulls get the coefficient * A [square number](https://en.wikipedia.org/wiki/Square_number) is a number which can be represented as `n * n` where n is an integer * A [triangular number](https://en.wikipedia.org/wiki/Triangular_number) is a number which can be represented as `1 + 2 + ... + (n - 1) + n` # Task Write a program/function to output the size of the smallest herd that could satisfy both the first and second parts of the above problem. # Output You must output [this number](https://gist.githubusercontent.com/Mukundan314/b0396980ef565cf04bc3f2798d9aa1f7/raw/7a44850bffeff59745049c4e0d2188aecce4bdbc/archimedes_cattle_number). [Standard Output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes) for integers apply. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins. --- Hash of decimal representation of answer for easy checking: * sha256 (with newline): `4fce7274734a18e9d27592e59480b50876da243de4caef4323f783339c456a7c` * sha256 (without newline): `8500b362f3d6b5e96c775ca16d1475b519ff18669b0f6f3d35e4fb23d2c18d01` --- *Inspired by [The Archimedes Number - Numberphile](https://www.youtube.com/watch?v=dNxyFtqcNss)* [Answer] # Sledgehammer, ~~67~~ ~~66~~ 26 bytes ## -40 bytes thanks to @GregMartin and I also no longer have any idea about how my answer works Completes in less than a few seconds! ``` ⡇⣄⠀⠇⣺⠇⢞⡞⣵⣍⠪⢺⡇⠜⢂⡒⢃⠦⠲⣎⠇⠣⡔⢻⡦⠔ ``` Mathematica code: ``` Floor[Divide[25194541,184119152] * (NumberFieldFundamentalUnits@Sqrt[4729494])^4658] ``` (the reason for the Divide is that by default Mathematica represents `x/y` as `x * y^-1`, which is half a byte longer in Sledgehammer). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~84~~ 83 bytes ``` 224571490814418y^2/.{1}.FindInstance[x^2-410286423278424y^2==1&&x>1,{x,y},Integers] ``` [Try it online!](https://tio.run/##FY7BasJAFEX3fsWsJNrUzntzJ/Nmka6K4K7QZYgQNeiATmgyLRHx29N0eeDcw7016dLemhSOzdSoUm2vXddXH@E3nNqKLXlYUE4CIk@Wa7VWGWnvDXkpnGFh7wy8m6ngfyQYY2G8Ji2i4dWLWiirLTzEsoEhq43RDnBOaB5bCw0tc8BAq6/vPlVw7Ge/Xu1RWKlVtlbtGIYU4lkN3fUnhS6q9WpxKLOJGdYRvBYCSO57fts86LnZhnjaxSE18dhW455fQZqlwHzSCRizWJa0XI7vlD/G/P7MdzG157Yf6mm1@OxDTFVTlod6@gM "Wolfram Language (Mathematica) – Try It Online") -1 byte thanks to @J42161217. Gives the identical result to the [existing Sledgehammer solution](https://codegolf.stackexchange.com/a/206457/78410). Uses the Pell equation directly to find the required y, and substitutes into the formula for the desired value. One problem was that the [OEIS](https://oeis.org/A096151) didn't have the correct constant factor (which must be multiplied by 4456749). This one should be easier to port to other languages, since the Pell equation can be brute-forced using just integers. ### Deriving the formula Start with the minimal solution of the linear equations, which is already present on [MathWorld](https://mathworld.wolfram.com/ArchimedesCattleProblem.html), where \$W,X,Y,Z\$ denote white, black, dappled, and yellow bulls and \$w,x,y,z\$ denote the cows, and \$S\$ is the grand total: $$ W,X,Y,Z = 10366482, 7460514, 7358060, 4149387 \\ w,x,y,z = 7206360, 4893246, 3515820, 5439213 \\ W+X = 17826996, Y+Z = 11507447, S = 50389082 $$ Now we need to find the integer multiple of all the values such that \$(W+X)n\$ is a square and \$(Y+Z)n\$ is a triangular number (which can be alternatively written as "8 times that plus 1 is a square"): $$ (W+X)n = x^2 \\ 8(Y+Z)n + 1 = y^2 $$ Note that \$W+X\$ is squarefree except for having the prime factor 2 twice, so \$x\$ must be a multiple of \$\frac{W+X}{2}\$. Substitute \$x=\frac{W+X}{2}x\_1\$, then we get $$ n = \frac{W+X}{4}x\_1^2 $$ Substitute this into the equation for \$y\$ and rearrange a bit, then we get $$ y^2 - 2(W+X)(Y+Z)x\_1^2 = 1 $$ So the \$2(W+X)(Y+Z)\$ is where the number 410286423278424 comes from. Now assume we solved it; then we have the value for \$x\_1\$. The final answer we want is \$S n\$, or $$ S n = \frac{W+X}{4}Sx\_1^2 $$ where \$\frac{W+X}{4}S\$ evaluates to 224571490814418. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~373 ... 304~~ 296 bytes Returns a BigInt of 206545 digits. Most BigInt literals in the code are stored as strings in base 119. This saves 8 bytes but leads to many unprintable characters. Below is a sanitized version without this compression scheme. ``` _=>[...1e9+[9542]].map(i=>M.push(m=([a,b,c]=m,[d,e,f]=M[i-2]||m,[v=a*d+b*f,a*e+b*d,u=c*d+a*f])),m=[0x4EDF512CD794532694B80D70C2648ADB08931n,0x119A739D926824D28537A6B609D64903072098n,0x16163EA6FB9A566AD5B17C9614A6476F10864n],M=[[0x104941B82B6E51BED5n,0n,0x48F880D7EEB3F6CAAn]])&&v*u*v*u*48222351474n/4657n ``` [Try it online!](https://tio.run/##ZZHvi9MwGMdh4ND5SpggjJNyL9aky7JubDfmmYIFj5065JgMsYu2a9Mud11a82Pnwf3vMzsVQV@EJ/l8v988D8l1sk9UKnmt@6LK2OGCHL6RIMIYD9msF80m4xGleJfUgJNggWujtmBHQJSgDUop2aEoQwzllCwi3h/R@3tL9iTxst7Gy1HiMVszZEhqSeLlFEK0IxEIiSJBaPKcSaAin0LM9kzeAUECTbQ3HM5EL@TFpdBAQKSJL2C3q2HcyMxl/rF1Mq@fQPkiyoA2ZjmNURi32gHrVJ2GyM6beqVWdae5dMlR@SrGxdP2p0dX5vHVQMj2a1@kdUzRgkRRGAfr9er5y88n7zfvYuQL63/2tnm6KumXAY4ptW33nvGOK4wbjenNOu7Gg/HZZCoOkimHOBcAnreUlnZrAdbVUksuiiNNK6GqkuGyKoB1YFXylAEfORMfOj3Hta/s2vpX6v8W1sL9J@5@YKLQ21fOn0D5cD6anYwXXKv/Esv5m9Hk7FdCsu@GSwbcVN7VunIhTiVLNJsn9j9dtU2s00JTZxYeZ4XY3sqUBu6W/XAfhnLALdfbymhHsNuSCwZty8NP "JavaScript (Node.js) – Try It Online") Note: Interestingly, it takes 6 times longer to turn the number into a string than to compute it (~2400ms and ~400ms on TIO respectively). ## How? ### Preamble Node is definitely not the right tool for the job. We need to use an algorithm relying on integers exclusively and we don't have any advanced math built-in at our disposal. It would probably be possible to solve [the Pell equation used by Bubbler](https://codegolf.stackexchange.com/a/206460/58563), but given the magnitude of the number we're looking for, I doubt that a size-optimized version of such an algorithm would return anything in a reasonable amount of time. In order to get something that actually works, I've decided to use the formula described in the next paragraph. ### Formula This is an implementation of the method described in [*A simple solution to Archimedes' cattle problem*](http://jultika.oulu.fi/Record/isbn951-42-5932-7) by Antti Nygrén, whose final formula is: $$\begin{pmatrix}v\\u\end{pmatrix}=\begin{pmatrix}a\_1&a\_2\\a\_3&a\_1\end{pmatrix}^{1164}\times\begin{pmatrix}r\_1\\r\_2\end{pmatrix}$$ $$T=6299\times 957\times u^2v^2+\frac{21054639\times 957\times u^2v^2}{4657}$$ with: $$\begin{align}&a\_1=109931986732829734979866232821433543901088049\\ &a\_2=392567302329690546856394748066206816187916440\\ &a\_3=30784636507697855142356992218944109072681060\\ &r\_1=300426607914281713365\\ &r\_2=84129507677858393258\end{align}$$ ### Implementation We start with `m = [a1, a2, a3]` and `M = [[r1, 0, r2]]`. We iterate through the list `[...1e9 + [9542]]` which expands to: ``` ['1','0','0','0','0','0','0','0','0','0','9','5','4','2'] ``` For each value \$i\$ in the above list: * we build the vector `[a,b,c]` from `m` * we build the vector `[d,e,f]` from either `M[i-2]` if it exists, or `m` otherwise * we update `m` to `[v,v',u]` where: $$\begin{pmatrix}v&v'\\u&\color{grey}{u'}\end{pmatrix}=\begin{pmatrix}a&b\\c&a\end{pmatrix}\times\begin{pmatrix}d&e\\f&d\end{pmatrix}=\begin{pmatrix}ad+bf&ae+bd\\cd+af&\color{grey}{ce+ad}\end{pmatrix}$$ Note: we don't need \$u'\$, so it's not computed at all * we push the new instance of `m` into `M` During the first 10 iterations, `M[i-2]` is undefined and `m` is used instead. So we essentially just square the original matrix 10 times. In other words, we compute: $$\begin{pmatrix}a\_1&a\_2\\a\_3&a\_1\end{pmatrix}^{1024}$$ During the next 3 iterations, we multiply by previous occurrences of `m`: `M[9-2]`, `M[5-2]` and `M[4-2]`, which correspond to the original matrix to the power of \$128\$, \$8\$ and \$4\$ respectively in order to reach: $$\begin{pmatrix}a\_1&a\_2\\a\_3&a\_1\end{pmatrix}^{1024+128+8+4}=\begin{pmatrix}a\_1&a\_2\\a\_3&a\_1\end{pmatrix}^{1164}$$ The last iteration is a multiplication by `M[0]` where we've stored `[r1, 0, r2]` at the very beginning of the process, leading to: $$\begin{pmatrix}v&\color{grey}{v'}\\u&\color{grey}{u'}\end{pmatrix}=\begin{pmatrix}a\_1&a\_2\\a\_3&a\_1\end{pmatrix}^{1164}\times\begin{pmatrix}r\_1&\color{grey}{0}\\r\_2&\color{grey}{r\_1}\end{pmatrix}$$ At this point, \$v\$ and \$u\$ are set correctly and we just need to compute: $$\frac{v^2u^2\times 48222351474}{4657}$$ [Answer] # [Python 2](https://docs.python.org/2/), 166 bytes ``` u=0x104941b82b6e51bed5 v=0x48f880d7eeb3f6caa k=2*u*v a=0x4edf512cd794532694b80d70c2648adb08931 exec"u,v=a*u+7766*k*v,a*v+609*k*u;"*1164 print u*u*v*v*48222351474/4657 ``` [Try it online!](https://tio.run/##FYzbCsMgEETf/YrSRxOou66rUvIx3kJLIA0lSvr1NmFehjOH2X7767Ni73VSByjyBNFh5GIglmxEOzG52TmVbSlRz5xCEMuEssomwrWWPBvAlK0no5E9xUtWCZlcyFE5r0GUo6R7HdsUZB2sZZaLbGOQbWDlz16fdwnAJLbve91v9bo/Qw4RtQGy9CA2tvc/ "Python 2 – Try It Online") Based on [Arnauld's formula and method](https://codegolf.stackexchange.com/a/206466/20260). I start with an initial `u,v`, and update them by a 2\*2 matrix operation 1164 times. I looked for constants sharing large common factors and extracted those. ]
[Question] [ To celebrate the 2497th anniversary of the Greek victory at Salamis in 480 BC. Draw the lambda blazon. The lambda blazon was the lambda painted on greek shields like so: [![images of red capital lambda on circular white and gold shield backgrounds](https://i.stack.imgur.com/13rw9.jpg)](https://i.stack.imgur.com/13rw9.jpg) **Puzzle:** Given a positive odd integer n, produce an ascii art image of the above shield. **Specifications:** **n=1:** ``` ( /\ ) ``` **n=3:** ``` ( /\ ) | / \ | ( / \ ) ``` **n=5** ``` ( /\ ) | / \ | | / \ | | / \ | ( / \ ) ``` **Graph:** **n=3** ``` 2| ( /\ ) y-axis 1| | / \ | 0| ( / \ ) ___________ 0123456789 x-axis ``` **Description:** There should be exactly *n* `\` characters and *n* `/` characters. The `/`s and `\`s should not touch the edge of the shield. The bottom and top corners of the shield will be denoted with a `(` or `)` unless *n*=1 where there will be one `)` and one `(`. There will always be one space between the bottom corners and the lambda, increasing by 1 with the y axis until `y + 1 == n`. Non corners of the shield side will be denoted with `|`. There is no shield top. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 13 bytes *Thanks to @Neil for saving 4 bytes!* ``` (↙↓⊖θM↑(→↗N‖M ``` [Try it online!](https://tio.run/##S85ILErOT8z5/1/jUdvMR22TH3VNO7fj/Z61j9omAkUmPWqb/n7PukcN04BC//8bAwA) **Explanation:** ``` (↙ // Print '(' and move one step down and to the left. ↓⊖θ // Print n-1 '|'s downwards. M↑ // Move one step up. (→ // Print '(' and move one step to the right. ↗N // Print n '/'s towards the upper right corner. ‖M // Mirror the left half to produce the right half. ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~17~~ 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┐*ƨ(Κm«@.╚┼┼╬³ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTEwKiV1MDFBOCUyOCV1MDM5QW0lQUJALiV1MjU1QSV1MjUzQyV1MjUzQyV1MjU2QyVCMw__,inputs=Mw__) Explanation: ``` example input: 3 ┐* push a string of input amount of "|" "|||" ƨ( push "(" "|||", "((" Κ prepend that to the vertical bar string "((|||" m mold that string as the input (remove excess characters) "((|" « put the first character at the end "(|(" @ push a space "(|(", " " .╚ create a diagonal of input length "(|(", " ", [" /", " / ", "/ "] ┼┼ append those three horizontally together ["( /", "| / ", "( / "] ╬³ palindromize that all ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~103~~ 96 bytes * Saved seven bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` f(n,j,b){for(j=n;j--;printf("%c%*c%*c%*c\n","|("[b],j+2,47,n+n-j+~j,92,j+2,"|)"[b=j<1|n-2<j]));} ``` [Try it online!](https://tio.run/##NYxBCsIwEEWvUgKFGTMBGwSRNBfIFbQLG4l0wKkUd0avHlu18Ffv8V801xhLSSDE1OMzjROwF8fGuPs0yCOBqmO9@e8kilQGdew7Ym1ptyfRYli/mQ72i1TGWXtumyzGttwhule5nQeB8Ou7YJqtwzUvla/qy1IOSAmC1kirm@ny/gA "C (gcc) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 41 bytes ``` .+ $* ( $'/$`$`\$' )¶ G`. sT`()`|`¶.*¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRUuBS4FLQ0FFXV8lQSUhRkVdQfPQNi73BD2u4pAEDc2EmoRD2/S0Dm37/98UAA "Retina – Try It Online") Explanation: ``` .+ $* ``` Convert to unary, but using spaces. ``` ( $'/$`$`\$' )¶ ``` Use the match prefix and suffix operators to generate a series of lines with increasing amounts of centre space on each line. ``` G`. ``` However, there's an extra blank line, which throws off the final transliteration, so delete it here. ``` sT`()`|`¶.*¶ ``` On all lines except the first and last, change the `()`s to `|`s. [Answer] # [Perl 5](https://www.perl.org/), 91 + 1 (`-p`) = 92 bytes ``` $_='('.($s=$"x($q=$_))."/\\$s)";while(--$q){say;y/()/|/;s| /|/ |;s|\\ | \\|}s/\|/(/;s/\|/)/ ``` [Try it online!](https://tio.run/##FclBCsIwEEDRq4Qw0MkimYp0FXIEbzBQXBQsFJs6gi2OV3eMq/fh1@mxDGYwlg67hCAF/I6wFRhDSJ6YQYLPr9u8TBgjbOEt1yMfhIGUsqhrOG3B7NQx60eIlbC9v4HMzt@1Puf1LhYvQ@pPvcX6Aw "Perl 5 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~200~~ ~~190~~ 170 bytes ``` n->{for(char i=0,s[];i<n;s[-~n-i]=47,s[2+n+i]=92,s[0]=i<1|i>n-2?40:'|',s[3+n+n]=i<1|i++>n-2?41:'|',System.out.println("".valueOf(s).replace('\0',' ')))s=new char[4+n+n];} ``` [Try it online!](https://tio.run/##RZA9b4MwEIZ3fsUpCyCCRdJIUUtIh04dqg4ZKYPrOOSoOSPbpKqS9K9Th1L1ptP73tdzDT/xVHeSmv3HgG2njYPGa6x3qNihJ@FQE3vSZPtWmjwIuv5doQChuLXwwpHgHIAP67jz@l/l5pmcrKXZQmeQ3O6IUu2hgIHS7fmgTSSO3AAW2dyWVY4bym2ZflOKVbFae22ZUOLz@6XPs6rAzeKCW0qXj6vsIbyEXr3zFTQ5SfLrLUZv92WdbJnuHRuXK4pmM3biqpevh8jGzMhOcSGj8C0L5yGEcRzbguQn3I4qV@Pg/Dp42hvZRDwBnjTuofXc0c754XVZATe1jac3jA3/xIwLITsXreN8tK/BNRh@AA "Java (OpenJDK 8) – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 43 bytes This is quite gigantic given that it's been done on mobile :-/ ``` j_m++++++@"(|"J!/,1QdK*;d\/*;y-Qd\\K@")|"JS ``` **[Try it online!](https://pyth.herokuapp.com/?code=j_m%2B%2B%2B%2B%2B%2B%40%22%28%7C%22J%21%2F%2C1QdK%2a%3Bd%5C%2F%2a%3By-Qd%5C%5CK%40%22%29%7C%22JS&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0)** [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` n=a=input() while a:print'(|'[1<a<n]+a*' '+'/'+(n-a)*' '+'\\'+a*' '+')|'[1<a<n];a-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8820TYzr6C0REOTqzwjMydVIdGqoCgzr0Rdo0Y92tAm0SYvVjtRS11BXVtdX11bI083URPIA3FjYtRhMppwtdaJuraG//@bAgA "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 153 bytes ``` function(n){s=2*n+4 m=matrix('|',s,n) m[3:s-1,]=' ' m[cbind(5:s-2,c(n:1,1:n))]=1 m[1,c(1,n)]='(' m[s,c(1,n)]=')' m[m>0]=rep(c('/','\\'),n) rbind(m,'\n')} ``` [Try it online!](https://tio.run/##bc0xDsIwDAXQPadgsw1BkJYulcxFaIcSWqlDTNUUCQk4e3BYkBDjf/625zRwGm7il/EqKPSIXKxlczCBQ7fM4x3hCTZaIRNOZR23zrYMK9Dkz6NcsFIrrEepnXW1ELXsdOiUnG5pGXM5fjPlHI77lud@Qo@wAwtNA5SfzJ@jQUGAXinwgI6M7xa12E8MQMZkLf9q9avJvQE "R – Try It Online") [Answer] ## Batch, 218 bytes ``` @echo off set s= for /l %%i in (1,1,%1)do call set s= %%s%% set s=%s%/\%s% echo (%s%) for /l %%i in (2,1,%1)do call:l %1 %%i exit/b :l set s=%s: /=/ % set s=%s:\ = \% if %1==%2 (echo ^(%s%^))else echo ^|%s%^| ``` As if `|`s weren't bad enough, `()`s don't work well with `if`...`else`. [Answer] # 05ab1e (27 bytes) ``` F"|("0NQ¹<NQ~èð¹N-×'/ðN×J∞, ``` [try it online](https://tio.run/##AS8A0P8wNWFiMWX//0YifCgiME5Rwrk8TlF@w6jDsMK5Ti3Dlycvw7BOw5dK4oieLP//Mw) explanation ``` F #Loop n times |("0NQ¹<NQ~è #Use ( or | ð¹N-× #put spaces (1) '/ #put / ðN× #put more space J∞, #reverse image ``` [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 101 bytes ``` n=>for(i=0;i<n;i++)print(((c=(i==n-1)or!i)?"(":"|")..(s=" "*n-i).."/"..(" "*i*2).."\\"..s..c?")":"|") ``` [Try it online!](https://tio.run/##JcuxCoNAEIThPk@RTLWreIkRm5iNL2InLCyBVU4tAnn3yx1pBr4fRg9/f5JKcnnpEsnkNtjTB6trXqP5TkSz5CzetLzEi/EIwgNfcAi0Cc6ovLEMXJFLsVX34mnKYQthHsH/R1Jq@aTUlek5/QA "Funky – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 90 bytes ``` n=input() for i in range(n):m=-~i%n<2;s=' '*(n-i);print'|('[m]+s+'/'+' '*i+'\\'+s+'|)'[m] ``` [Try it online!](https://tio.run/##FckxDoMwEATAnldcg9bGQlEoAb8EKFIk4QoWy5gCCeXrDrQz4UjzyiZnemXYk7HFZ42iopT44vdtaNvF1z8t2Tfd5iGoDGu1XYjKhNNgWCa3OTzgINeqwzjiltPel/PzDw "Python 2 – Try It Online") -1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 188 bytes ``` n=>{int y=0,i=-1;var s="";while(y<n){var r=new char[n*2+4];r[n+1-y]='/';r[n+2+y]='\\';if(y<2|y++>n-2)i++;r[0]="(|("[i];r[n*2+3]=")|)"[i];s+=new string(r)+"\n";}return s.Replace("\0"," ");} ``` [Try it online!](https://tio.run/##fY8xb8IwEIXn5lecvMSuCYXQqoMxS6VOrVSVoQNhiIzbnJReKtuAopDfnpogVra79927u2d8Zhpnh71H@oF164P9VYmpS@/ho0t8KAMaeN2TWSKFCfjg4uAK1hXaegcaBtKrLiJo9WyCOpurQ@nAa8bUscLa8nZJojtrTpM9gqlKt6H7XD5uVSzkPGu3On1IxyaX56YoUoXf0ZifWilXlOUCpYwDs61m/MTZBkdvXLKIijiJUfFyPHD5kDshWUFM9c6GvSPw00/7V5fGclbM2IQBE6ofVHKNeGhwB@8lEhdJl9y9NOSb2k6/HAb7hmT5JTGfC6Fu4MVt/HQbP59xn/TDPw "C# (.NET Core) – Try It Online") ### Degolfed ``` n=>{ int y=0,i=-1; var s=""; while(y<n){ var r=new char[n*2+4]; r[n+1-y]='/'; r[n+2+y]='\\'; if(y<2 | y++>n-2) i++; r[0] = "(|("[i]; r[n*2+3] = ")|)"[i]; s += new string(r)+"\n"; } return s.Replace("\0"," "); } ``` [Answer] # Python 3, 110 bytes 93 bytes ``` b=c=int(input())*2 d,e='/\\' while b:print('(|%%ss)|'[2<b<c::2]%f' {d+e:^{c}} ');d+=' ';b-=2 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~93~~ ~~91~~ ~~90~~ 89 bytes -2 Thanks to ASCII-only for pointing out extra parens -1 Thanks to Mazzy for tweaking swap logic ``` param($n)0..--$n|%{"|("[!($x=($n-$_)*$_)]+($y=" "*($n-$_+1))+"/"+" "*$_+"\$y"+"|)"[!$x]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT9NAT09XVyWvRrVaqUZDKVpRQ6XCFiiuqxKvqQXEsdoaKpW2SgpKWhBBbUNNTW0lfSVtJQWgGJCvFKNSCeTVaAL1qlTE1v6v5VJTSVMwBJNGYNIYTJr@BwA "PowerShell – Try It Online") ~~Trying to tweak that `$x=` bit. There's probably a smarter way to get the 1st and last line out in a few less bytes.~~ There is a better `$x=` but it isn't much cheaper. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ┤|×(e⟳ +╴/+║ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTI0JTdDJUQ3JTI4JXVGRjQ1JXUyN0YzJTIwJXVGRjBCJXUyNTc0JXVGRjBGJXVGRjBCJXUyNTUx,i=NQ__,v=0) Explanation: ``` ┤ decrease the input by 2 |× repeat "|" vertically - if the amount is -1 (for input of 1), ir just removes the item currently ( push "(" e encase in that parentheis - if that first string isn't there, currently it just fails doing anything and leaves the parenthesis on the stack ⟳ rotate clockwise + append horizontally a space ╴/ get a diagonal the length of the input + append it horizontally to the current result ║ and palindromize horizontally with 0 overlap ``` ]
[Question] [ You will be given a number `x`, where `0 <= x <= 2^32 - 1`. You should output a list of numbers in decimal, after recursive splitting in binary format. ### Examples: **Example 1:** ``` 255 -> 255 15 15 3 3 3 3 1 1 1 1 1 1 1 1 ``` The current list is just `255`. The binary representation of `255` is `1111 1111`. Splitting it, we get `1111` and `1111`, which in decimal are `15` and `15`. We add those to the list, so we will have `255 15 15`. Now the numbers `15` and `15` will serve as inputs and these numbers are to be split. Doing it again, we get (`3 3` from both `15`s): `255 15 15 3 3 3 3`. Continuing the logic, final list will be `255 15 15 3 3 3 3 1 1 1 1 1 1 1 1` . And since `1` can no longer be split, the output stops. **Example 2:** ``` 225 -> 225 14 1 3 2 1 1 1 0 ``` The starting list is `225`. The binary representation of `225` is `1110 0001`. Splitting it, we get `1110` and `0001`, which in decimal are `14` and `1`. Adding those to the list, we get `225 14 1`. Now the numbers `14` and `1` will serve as inputs and these numbers are to be split. Since `1` is no splittable, the output will be `225 14 1 3 2`. **Example 3:** ``` 32 -> 32 4 0 1 0 ``` **Conditions**: 1. If the number of binary digits are odd, the first number will have one fewer binary digit than the next one. Example, `20 (10100)` will be split as `10` and `100`, with decimal output being `2` and `4`. 2. Standard loophole rules apply. 3. `0`s and `1`s do not propagate further. 4. Program crashing for trying to display too many numbers is a valid exit condition. [Answer] # Pyth, 18 bytes ``` u+QiR2smc2+0dt#.BM ``` [Test suite](https://pyth.herokuapp.com/?code=u%2BQiR2smc2%2B0dt%23.BM&test_suite=1&test_suite_input=255%0A225%0A32&debug=0) This code does something very tricky and clever with `u`, Pyth's fixed point operator. The body of the function, which is everything other than the `u`, is fairly straightforward: ``` +QiR2smc2+0dt#.BM +QiR2smc2+0dt#.BMG Implicit variable G will store the list of numbers from the previous iteration. .BMG Map each number to its binary representation t# Filter out the ones of length 1 (0 and 1) m Map the remaining binary +0d Prefix with a 0 c2 Chop in half. Since c puts the larger half first, prefixing with a 0 makes the chop work out right, and doesn't change the value. s Concatenate iR2 Map back to binary +Q Add the input to the front of the list ``` This code removes 0s and 1s, splits every number, and adds the input in front. `u` will run this function on the prior result of the function until the result stops changing. What initial value does `u` use? That's the clever part: the code doesn't specify what value to use, so it defaults to the input. But the input isn't a list of numbers - it's a number. Pyth implicitly coerces the number on the fist time through the loop to the range of the number - `[0, 1, ..., Q-1]`. That doesn't look anything like the output we want to get. Fortunately, `u` will find the correct result regardless of what the initial input is - the desired output is the only fixed point of the function, and repeated application will always reach it. Let's look at the intermediate values of the program with the input `7`. I've highlighted the prefix of the result which is guaranteed to be correct, regardless of initial input: 1. `7` (Implicitly `[0, 1, 2, 3, 4, 5, 6]`) 2. **`[7,`**`1, 0, 1, 1, 1, 0, 1, 1, 1, 2]` 3. **`[7, 1, 3,`**`1, 0]` 4. **`[7, 1, 3, 1, 1]`** Which is the output. --- # Packed Pyth, 16 bytes Note that since Pyth uses only the 0-127 range of ASCII, it can be compressed by using a 7-bit encoding rather than an 8 bit encoding. Thus, the above program can be packed into 16 bytes. The resulting program is: ``` ꮎ�L����[ ���4 ``` hexdump: ``` 0000000: eaae 8e9a 4cb9 edc6 c95b 0c9d 11ae 8534 ....L....[.....4 ``` The interpreter is found [here](https://github.com/isaacg1/pyth/blob/master/packed-pyth.py). Provide the input as a command line argument. The code page of this language (Packed Pyth) is the 0-127 range of ASCII, and every character is represented with 7 bits, padded at the end. Thus, the above unreadable hexdump represents: ``` u+QiR2smc2+0dt#.BM ``` But in 16 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ ~~18~~ 17 bytes ``` ,¸[Žrbvy0ì2äCʒ=1› ``` [Try it online!](https://tio.run/nexus/05ab1e#AR4A4f//LMK4W8W9cmJ2eTDDrDLDpEPKkj0x4oC6//8xNjc "05AB1E – TIO Nexus") ## Explanation ``` ,¸[Žrbvy0ì2äCʒ=1› Argument n ,¸ Print n and push n as array [Ž Loop until stack is empty r Reverse stack b Convert elements in array to binary v For each y in array y0ì2ä Prepend '0' to y and split it into 2 elements (the first element will take the additional character) C Convert elements to decimal ʒ=1› Keep only elements greater than 1, while printing each element ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte by removing a monadic chain and then dealing with the consequence of an empty list being converted from binary yielding 0 later. ``` ỊÐḟBUœs€2UḄF WÇÐĿṖUF ``` A monadic link taking a number and returning the list specified. **[Try it online!](https://tio.run/nexus/jelly#ASsA1P//4buKw5DhuJ/CtUJVxZNzMlXhuITCteKCrEYKV8OHw5DEv1VG////MjI1)** ### How? ``` ỊÐḟBUœs€2UḄF - Link 1, perform an iteration: list of numbers Ðḟ - filter out if: Ị - insignificant (absolute value <= 1 - hence any 0s or 1s) B - convert to a binary list (vectorises) U - upend (reverse each) œs€2 - split €ach into 2 equal chunks (the first half is longer if odd ...hence U - upend (reverse each) ...this upend and the previous one) Ḅ - convert from binary list to number (vectorises, although when the filter - removes everything a zero is yielded) F - flatten the resulting list of lists to a single list WÇÐĿṖUF - Main link: number W - wrap in a list ÐĿ - loop and collect results until no change occurs: Ç - call last link (1) as a monad Ṗ - pop (remove the last element - a list containing a single zero which results - from the effect of Ḅ when link 1's input only contained ones and zeros) U - upend (put the iterations into the required order) F - flatten to yield a single list ``` [Answer] ## JavaScript (ES6), 99 bytes This looks a bit too long. There might be a better way to get the correct order. ``` f=(n,p=(a=[],1),i=33-Math.clz32(n)>>1)=>(a[p]=n)>1?f(n>>i,p*=2)&&f(n&(1<<i)-1,p+1):a.filter(n=>1/n) ``` ### Demo ``` f=(n,p=(a=[],1),i=33-Math.clz32(n)>>1)=>(a[p]=n)>1?f(n>>i,p*=2)&&f(n&(1<<i)-1,p+1):a.filter(n=>1/n) console.log(JSON.stringify(f(255))) console.log(JSON.stringify(f(225))) console.log(JSON.stringify(f(32))) ``` [Answer] # [Python 2](https://docs.python.org/2/), 110 bytes ``` l=[input()];i=1 while i: z=0 for k in l[-i:]: if k>1:b=~-len(bin(k))/2;l+=[k>>b,k&2**b-1];z+=2 i=z print l ``` [Try it online!](https://tio.run/nexus/python2#BcFBCsMgEADAc/cVeyqaVFqFXpT1I@JFSOjiYkNIKXjI183MEErctt@hdA5MFv4flgXZA3Z6Aa7fHStyQ0mGffZw4xVrtL7QaWRpqnBTVeunCzJTqjGWR727aSrG5tBncoBMHbad24EyhnPvCw "Python 2 – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), 142 bytes ``` .+ $* +`(1+)\1 ${1}0 01 1 {`.+$ $&¶<$&> +`;(\d*)> >;<$1> <.> {`(\d)> >$1 }`<(\d) $1< <> ; \b0+\B }`^;|;\B ¶ ; ;; 1 01 +`10 011 0\B 1+ $.& ``` [Try it online!](https://tio.run/nexus/retina#FY7RCcMwDET/bw5hkgiMFeiXhD4yhymmdIs0a2WALOZKf6d3h@5mZdAGHovw2gV0ytXQBIJzVCZQeW6j4hHRpX@31eFqJA6rjggFTEaCa1geIDGYQ9E/jfuBMN7601TPHVgV8T46eEh2hU5PYkktc@776w8 "Retina – TIO Nexus") [Answer] # PHP, 132 Bytes ``` for($r=[$argn];""<$n=$r[+$i++];)$n<2?:[$r[]=bindec(substr($d=decbin($n),0,$p=strlen($d)/2)),$r[]=bindec(substr($d,$p))];print_r($r); ``` [Try it online!](https://tio.run/nexus/php#bY1BCsIwEEX3HqPMIkMCSsCNk6EHCaFYUzUgY0jr@dPRtcv3@I8fxvqsB7i2h7D3Z@r3dzPQOP5UomEIIAwtWijWJkKQ4MdLVJN4LpKXm1k/87pplVlJnQFBd3JQWfVrUc549Ijub6Q7xES1Fdmm7zdS7zs "PHP – TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), 102 bytes ``` f=->*a{a==[]?[]:a+=f[*a.map{|i|s='%b'%i;i>1?[s[0...h=s.size/2].to_i(2),s[h..-1].to_i(2)]:[]}.flatten]} ``` [Try it online!](https://tio.run/nexus/ruby#PcnBCoJAEADQu1/hIbEsJ12QBWP0Q4ZBNthtB7SEXQhSv92gQ9f3dodlV5jFIBL3xK05o6PCwGTmZZU1YJ7d80xu0tU9BaoAwGOAIB97VQzxNchRnS6BPEBZ/4Fb4g3caGK0T972OXV0GH7Lby@jTR82hl01TaKqRGv9BQ "Ruby – TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), 98 bytes ``` f=->*a{a==[]?a:a+=f[*a.flat_map{|i|s='%b'%i;i>1?[s[0...h=s.size/2].to_i(2),s[h..-1].to_i(2)]:[]}]} ``` [Try it online!](https://tio.run/nexus/ruby#PcjBCoJAEADQu1/hIbEsJ12QBWP0Q4ZhmcBtF4yEXQhSv32DDr3jSxbroZJVEIlH6eWMlioBO0s0T1nWzW8By@JeFv7mh3akQA0AOAwQ/Ge6Kob4Mv6oTpdADqBu/8E98c57WnJLB/Nbfjs/T/ljiiGprstUk2mtvw "Ruby – TIO Nexus") Simply a basic optimization of [Value Ink's answer](https://codegolf.stackexchange.com/questions/121504/split-me-in-half/121691#121691) : use flat\_map instead of map...flatten, and use `a==[]?a` instead of `a==[]?[]` [Answer] # Java 10, ~~541~~ ~~521~~ ~~245~~ 243 bytes ``` n->{var L=new java.util.Stack<Integer>();L.add(n);for(int i=9,o=0,t;o<i;)for(i=o;i<L.size();o++)if((t=L.get(i++))>1){var b=n.toString(t,2);L.add(n.parseInt(0+b.substring(0,t=b.length()/2),2));L.add(n.parseInt(b.substring(t),2));o++;}return L;} ``` [Try it online.](https://tio.run/##hVE9b8IwEN35FTfaAlyaiqEyZq@UsjBWHZzEpAfBRvaFqkX57elBEGJo1cXy@d6Xnrf2aKfbateXjU0JXi360wgAPbm4saWD1XkE2DJOtYSNyjHR4oX3tYtLKMX1Cl5qRnYjPhJZwhJW4MFA76fL09FGyI13n3dCa7Ll7qYkpM6VrSrBOpsQBScANM@TYGYT0mGBWl6eTdC4yFXCb8eUMB5L3AhBJle1I4E8y@WjvBgWxisKa4roa0GT7OagDjYmx85iNi5Uaos0YNjJFKpxvqYPIR8yyZxfSPcUGjCcQ3fRURs95Lrr9bmGQ1s0XMO1jWPACvbcrxgSvb2DlUO5669Ebq9CS@rAK2o825Uim8/lpdS/Edl/iKdMXv@l638A) -22 bytes thanks to *@ceilingcat*. **Explanation:** ``` n->{ // Method with Integer parameter & Integer-List return-type var L=new java.util.Stack<Integer>(); // Create the result-List L.add(n); // Add the input-Integer to it for(int i=9, // Index integer `i`, set to a non-0 digit o=0, // Off-set integer `o`, starting at 0 t; // Temp integer `t`, uninitialized o<i;) // Loop as long as `o` isn't `i` yet: for(i=o;i<L.size() // Inner loop `i` in the range [`o`,list-size): ;o++) // After every iteration: Increase `o` by 1 if((t=L.get(i++)) // Set `t` to the `i`'th item // (and increase `i` by 1 afterwards with `i++`) >1){ // If `t` is larger than 1 (thus can be further split): var b=n.toString(t,2); // Convert `t` to a binary-String L.add( // Add to the List: n.parseInt( // A String converted to Integer: 0 // A "0", +b.substring( // Appended with a substring of `b` 0,t=b.length()/2) // in the char-range [0,length/2) ,2)); // Converted as a base-2 String to base-10 Integer L.add( // Also add to the List: n.parseInt( // A String converted to Integer: b.substring( // A substring of `b` t) // in the char-range [length/2,length) ,2)); // Also converted from a base-2 String to base-10 Integer o++;} // And increase `o` by 1 return L;} // Return the result-List ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 18 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` {gÉo1>môàh½‼<≥å}∟; ``` Takes the input wrapped inside a list. If this is not allowed, a leading `a` can be added. Print each of the resulting items on a separated line to STDOUT. [Try it online.](https://tio.run/##y00syUjPz0n7/786/XBnvqFd7uEthxdkHNr7qGGPzaPOpYeX1j7qmG/9/3@0kalpLFe0kRGINDYCEgZAbAgSAtEGsQA) **Explanation:** ``` { }∟ # Do-while true without popping: g # Filter the current list of integers by # (or the implicit input-list in the first iteration), É # using the following 3 characters as inner code-block: o # Print the integer with trailing newline (without popping) 1> # Check that it's larger than 1 (thus can be further split) m # Map over the remaining integers, ô # using the following 6 characters as inner code-block: à # Convert the integer to a binary-string # Split it into the correct halves by: h # Pushing its length (without popping) ½ # Integer-dividing this length by 2 ‼ # And apply the following commands separated on the stack: < # Slice to get the first length//2 bits ≥ # Slice to get the remaining bits å # After the map: convert all binary-parts back to integers ; # After the do-while: remove the empty list from the stack # (the empty stack is then output implicitly with newline) ``` ]
[Question] [ Write a program that outputs all 64 layers of this representation of [Graham's number](http://en.wikipedia.org/wiki/Graham's_number) from Wikipedia:   ![Graham's number](https://i.stack.imgur.com/Jjuqn.png) Your output **must exactly match** this ASCII version (in which `^` represents [Knuth's up-arrows](http://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) and combinations of slashes and underscores represent the large horizontal curly brackets): ``` 3^^...............................................................................................................................^3 \_______________________________________________________________ _______________________________________________________________/ \/ 3^^.............................................................................................................................^3 \______________________________________________________________ ______________________________________________________________/ \/ 3^^...........................................................................................................................^3 \_____________________________________________________________ _____________________________________________________________/ \/ 3^^.........................................................................................................................^3 \____________________________________________________________ ____________________________________________________________/ \/ 3^^.......................................................................................................................^3 \___________________________________________________________ ___________________________________________________________/ \/ 3^^.....................................................................................................................^3 \__________________________________________________________ __________________________________________________________/ \/ 3^^...................................................................................................................^3 \_________________________________________________________ _________________________________________________________/ \/ 3^^.................................................................................................................^3 \________________________________________________________ ________________________________________________________/ \/ 3^^...............................................................................................................^3 \_______________________________________________________ _______________________________________________________/ \/ 3^^.............................................................................................................^3 \______________________________________________________ ______________________________________________________/ \/ 3^^...........................................................................................................^3 \_____________________________________________________ _____________________________________________________/ \/ 3^^.........................................................................................................^3 \____________________________________________________ ____________________________________________________/ \/ 3^^.......................................................................................................^3 \___________________________________________________ ___________________________________________________/ \/ 3^^.....................................................................................................^3 \__________________________________________________ __________________________________________________/ \/ 3^^...................................................................................................^3 \_________________________________________________ _________________________________________________/ \/ 3^^.................................................................................................^3 \________________________________________________ ________________________________________________/ \/ 3^^...............................................................................................^3 \_______________________________________________ _______________________________________________/ \/ 3^^.............................................................................................^3 \______________________________________________ ______________________________________________/ \/ 3^^...........................................................................................^3 \_____________________________________________ _____________________________________________/ \/ 3^^.........................................................................................^3 \____________________________________________ ____________________________________________/ \/ 3^^.......................................................................................^3 \___________________________________________ ___________________________________________/ \/ 3^^.....................................................................................^3 \__________________________________________ __________________________________________/ \/ 3^^...................................................................................^3 \_________________________________________ _________________________________________/ \/ 3^^.................................................................................^3 \________________________________________ ________________________________________/ \/ 3^^...............................................................................^3 \_______________________________________ _______________________________________/ \/ 3^^.............................................................................^3 \______________________________________ ______________________________________/ \/ 3^^...........................................................................^3 \_____________________________________ _____________________________________/ \/ 3^^.........................................................................^3 \____________________________________ ____________________________________/ \/ 3^^.......................................................................^3 \___________________________________ ___________________________________/ \/ 3^^.....................................................................^3 \__________________________________ __________________________________/ \/ 3^^...................................................................^3 \_________________________________ _________________________________/ \/ 3^^.................................................................^3 \________________________________ ________________________________/ \/ 3^^...............................................................^3 \_______________________________ _______________________________/ \/ 3^^.............................................................^3 \______________________________ ______________________________/ \/ 3^^...........................................................^3 \_____________________________ _____________________________/ \/ 3^^.........................................................^3 \____________________________ ____________________________/ \/ 3^^.......................................................^3 \___________________________ ___________________________/ \/ 3^^.....................................................^3 \__________________________ __________________________/ \/ 3^^...................................................^3 \_________________________ _________________________/ \/ 3^^.................................................^3 \________________________ ________________________/ \/ 3^^...............................................^3 \_______________________ _______________________/ \/ 3^^.............................................^3 \______________________ ______________________/ \/ 3^^...........................................^3 \_____________________ _____________________/ \/ 3^^.........................................^3 \____________________ ____________________/ \/ 3^^.......................................^3 \___________________ ___________________/ \/ 3^^.....................................^3 \__________________ __________________/ \/ 3^^...................................^3 \_________________ _________________/ \/ 3^^.................................^3 \________________ ________________/ \/ 3^^...............................^3 \_______________ _______________/ \/ 3^^.............................^3 \______________ ______________/ \/ 3^^...........................^3 \_____________ _____________/ \/ 3^^.........................^3 \____________ ____________/ \/ 3^^.......................^3 \___________ ___________/ \/ 3^^.....................^3 \__________ __________/ \/ 3^^...................^3 \_________ _________/ \/ 3^^.................^3 \________ ________/ \/ 3^^...............^3 \_______ _______/ \/ 3^^.............^3 \______ ______/ \/ 3^^...........^3 \_____ _____/ \/ 3^^.........^3 \____ ____/ \/ 3^^.......^3 \___ ___/ \/ 3^^.....^3 \__ __/ \/ 3^^...^3 \_ _/ \/ 3^^^^3 ``` Notice that there are 64 layers, that there are no trailing spaces, and that two `^` occur before the dots and only one occurs after. The [MD5 hash](http://www.miraclesalad.com/webtools/md5.php) of your output should precisely be `c84d0e20eac2a7f891ab42a8eb77759f`, or `1ad3b10d06e38693436c14958b2c47a8` if there is a trailing newline (which is ok). The shortest code in bytes wins. Output to stdout. There is no input. [Answer] ## Python, 122 ``` i=63 while i: for s in'3^^'+'..'*i+'.^3','\%s %s/'%(('_'*i,)*2),'\/':print' '*(66-len(s)/2)+s i-=1 print' '*63+'3^^^^3' ``` Example: ``` $ python grahams.py | md5 1ad3b10d06e38693436c14958b2c47a8 ``` [Answer] # Perl -- 113 (112 + 1 for -E) --- Golfed: ``` $.=$"x63,$y="_"x($!=63-$_),$x.=($z=$"x$_)."3^^".".."x$!.".^3$/ $z\\$y $y/$/ $. \\/$/"for 0..62;say"$x$.3^^^^3" ``` Ungolfed: ``` for(0..62) { $.=$"x63; $!=63-$_; $y="_"x$_; $z=$"x$!; $x.=$z."3^^".".."x$!.".^3$/ $z\\$y $y/$/ $. \\/$/"; } say"$x$.3^^^^3" ``` ~~EDIT: There was an error in string interpolation where perl thought $m3 was a variable, so I had to add 2 characters to fix that.~~ Solved by changing $m to $. NINJA EDIT: Replaced instances of " " with $". Saves 2 characters NINJA EDIT 2: Thanks @chilemagic for pointing out that I can use say instead of print with -E to save a character. NOT-SO-NINJA EDIT 3: @Nax's solution beat my old solution, so I buffed it up a little to hold its ground. [Answer] # Haskell, 152 ``` (?)=replicate g 0=["3^^^^3"] g i=("3^^"++(i*2)?'.'++".^3"):map(' ':)(("\\"++i?'_'++" "++i?'_'++"/"):((i+1)?' '++"\\/"):g(i-1)) main=putStr.unlines.g$63 ``` [Answer] # CJam - 64 ``` 63{SI*3'^_'._63I-:J*_'^3NSI)*'\'_J*_S_@'/NS65*"\/ "}fIS63*3'^4*3 ``` Try it at <http://cjam.aditsu.net/> [Answer] # C 161 182 (i think i maxed out this method, maybe i should find a new one that can be golfed down more) compile as C99! ``` main(i){for(char d[]={[0 ...126]=46,i=0},l[]={[0 ...62]=95,0};i<63;)printf("3^^%s^3\n%*s\\%s %s/\n%*s\n%*s",d+2*i++,i,"",l+i,l+i,67,"\\/",i,"");puts("3^^^^3");} ``` # JS 158 ``` r="repeat";o="";u="_";s=" ";(f=i=>i?"3^^"+"."[r](i*2+1)+"^3\n"+s[r](64-i)+"\\"+u[r](i)+s[r](2)+u[r](i)+"/\n"+s[r](65)+"\\/\n"+s[r](64-i)+f(i-1):"3^^^^3")(63); ``` [xem.github.io/obfuscatweet/](http://xem.github.io/obfuscatweet/) **124:** ``` eval(unescape(escape('¨†Ωò°≤©ë∞©ë°≠Ä¢û±Øüê¢ò†ª≠êΩò°üò†ª¨∞Ωò††ò†ªöŶüë©üêæ™êøò†≥ß°ûò†´ò†Æò°õ¨°ùöÅ©ö†≤ö∞±öê´ò°ûú±ú´†¢ö±≥¶±≤ßê®ù†¥õë©öê´ò°úßÄ¢ö±µ¶±≤ßê®™ê©ö±≥¶±≤ßê®ú†©ö±µ¶±≤ßê®™ê©ö∞¢õ±ú´†¢ö±≥¶±≤ßê®ù†µöê´ò°úßÄØßÅÆò†´¨±õ¨°ùöÄ∂ùÄ≠™ê©ö±¶öÅ©õê±öê∫ò†≥ß°ûß°ûú∞¢öê®ù†≥öêª').replace(/uD./g,''))) ``` [Answer] # Bash+coreutils, 150 I thought I might be able to do better than this. Oh well. ``` r()(yes "${2:- }"|head -$[$1]|tr -d ' ') for i in {63..1};{ r 63-$i echo "3^^`r 2*$i .`.^3 `r 64-$i`\\`r $i _` `r $i _`/ `r 65`\/" } r 63 echo 3^^^^3 ``` ### Output: ``` $ ./graham.sh | md5sum 1ad3b10d06e38693436c14958b2c47a8 - $ ``` [Answer] ## STATA 135 ``` forv x=63(-1)1{ di _d(63-`x')" ""3^^"_d(2*`x'+1)".""^3"_n_d(64-`x')" ""\"_d(`x')"_"" "_d(`x')"_"_n-d(65)" ""\/" } di _d(63)"3^^^^3" ``` [Answer] # JavaScript 179 ``` n='';a=Array;for(b=64;b>1;)n+=(c=a(65-b).join(' '))+'3^^'+a(2*b).join('.')+'^3\n'+c+' \\'+(u=a(b--).join('_'))+' '+u+'/\n'+(d=a(64).join(' '))+' \\/\n' console.log(n+d+'3^^^^3') ``` Test it in your browser console or at <http://jsfiddle.net/2qwvrvcw/>. [Answer] # Javascript (203) ``` u="_";s=" ";for(i=64;i>1;i--)console.log(s.repeat(64-i)+"3^^"+".".repeat(i*2-1)+"^3\n"+s.repeat(64-i)+"\\"+u.repeat(i)+s.repeat(2)+u.repeat(i)+"/\n"+s.repeat(65)+"\\/");console.log(s.repeat(63)+"3^^^^3") ``` Ungolfed: ``` underscore = "_"; space = " "; for (i = 64; i > 1; i--) console.log(space.repeat(64 - i) + "3^^" + ".".repeat(i * 2 - 1) + "^3\n" + space.repeat(64-i) + "\\" + underscore.repeat(i) + space.repeat(2) + underscore.repeat(i) + "/\n" + space.repeat(65) + "\\/"); console.log(space.repeat(63) + "3^^^^3"); ``` [Answer] ## C# (~~212~~211) ``` using C=System.Console;class P{static void Main(){for(int i=64;i>1;)C.Write(@"{0}3^^{2}.^3 {0} \{1} {1}/ {3,65}\/ ",new string(' ',64-i),new string('_',--i),new string('.',i*2),"");C.Write("{0,69}","3^^^^3");}} ``` [.Net Fiddle](https://dotnetfiddle.net/tFQvfb "Fiddle with it") (it seems to require that the class and Main method are public) Slightly ungolfed: ``` using C = System.Console; class Program { static void Main() { for (int i = 64; i > 1; ) { C.Write("{0}3^^{2}.^3\n{0} \\{1} {1}/\n{3,65}\\/\n", new string(' ', 64 - i), new string('_', --i), new string('.', i * 2), ""); } C.Write("{0,69}", "3^^^^3"); } } ``` [Answer] # Perl, 116 112 109 108 (including -E) My first attempt at golfing. Please take it as such: Golfed: ``` perl -E'map{$_=" $_!^".(($b=63-$_)?"2.$b.$b.^! $_ \\_$b 2_$b/ 65\\/":"4!");s#(.)(\d+)#"$1"x$2#eg;y/!/3/;say}0..63' ``` Very slightly ungolfed (not maintained ... ): ``` map { $b = 63 - $_; $_ = " $_!^".($b ? "2.$b.$b.^!N $_ \\_$b 2_$b/N 65\\/" : "4!"); s#(.)(\d+)#"$1"x$2#eg; # behaves exactly as $_ =~ s/(.)(\d+)/"$1"x$2/eg y/!N/3\n/; # y == tr, so this does $_ =~ tr/!N/3\n/ say; # once more $_ completion, this does say $_ == print "$_\n" } (0..63); ``` Essentially it works like this: for each line of 3s and a brace (these are handled together), it writes their sequence *RLE-encoded*, then decodes it. The rule is simple: every char followed by a number is expanded to that char that number of times. Characters without a number are left alone. Finally, the character `!` denotes a 3 and a `N` means a newline (3 had to be encoded because it is number and would eagerly participate as the number of repetitions). Each line of 3s and its brace get an element in the 64-element array the map is generating. Say, like print, can output arrays -- if given an array, it prints all the elements (without any separators). I used chilemagic's trick with `-E`. Thanks for it. **Reinforcements:** Two 113 byte solutions started to lurk here. RLE shall not succumb without fight! **Cleansing of Feeds**: I have now realized that I have no need for a special transliteration of \n, because all strings in Perl are automagically multiple-lined! Thus RLE clings nearer to the Ruby's back! Now at 109 bytes. **Agonizing Enlightment**: To count characters properly is harder than I thought. After some struggling, I settled on ``` echo $((wc -c <<<'golf'-1)) ``` (-1, because it counts a LF at the very end of the script). Moreover I have rearranged my assignments and saved 1 character, hereby settling on 108 bytes. [Answer] **MATLAB (325)** ``` m=127:-2:0;n=0:63;p='UniformOutput';q=false;f=@ones;g=@arrayfun;a=g(@(x,y)[f(1,y)*' ' '3^^' f(1,x)*'.' '^3'],m,n,p,q);b=g(@(x,y)[f(1,y+1)*' ' '\' f(1,(x-1)/2)*'_' ' ' f(1,(x-1)/2)*'_' '/'],m,n,p,q);a{64}(a{64}=='.')='^';g(@(x,y)fprintf('%s\n%s\n%s\n',x{:},y{:},[f(1,65)*' ' '\/']),a,b),fprintf(repmat('\b',1,137)) ``` ungolfed: ``` m=127:-2:0; n=0:63; p='UniformOutput'; q=false; f=@ones; g=@arrayfun; a=g(@(x,y)[f(1,y)*' ' '3^^' f(1,x)*'.' '^3'],m,n,p,q); b=g(@(x,y)[f(1,y+1)*' ' '\' f(1,(x-1)/2)*'_' ' ' f(1,(x-1)/2)*'_' '/'],m,n,p,q); a{64}(a{64}=='.')='^'; g(@(x,y)fprintf('%s\n%s\n%s\n',x{:},y{:},[f(1,65)*' ' '\/']),a,b),fprintf(repmat('\b',1,137)) ``` **MATLAB (252)** ``` n=0;f=@ones;g=@arrayfun;for i=127:-2:0 if n~=63 y=f(1,i)*'.';else y='^';z='';end;fprintf('%s\n%s\n%s\n',[f(1,n)*' ' '3^^' y '^3'],[f(1,n+1)*' ' '\' f(1,(i-1)/2)*'_' ' ' f(1,(i-1)/2)*'_' '/'],[f(1,65)*' ' '\/']);n=n+1;end;fprintf(repmat('\b',1,137)) ``` ungolfed: ``` n=0; f=@ones; g=@arrayfun; for i=127:-2:0 if n~=63 y=f(1,i)*'.'; else y='^'; z=''; end fprintf('%s\n%s\n%s\n',[f(1,n)*' ' '3^^' y '^3'],[f(1,n+1)*' ' '\' f(1,(i-1)/2)*'_' ' ' f(1,(i-1)/2)*'_' '/'],[f(1,65)*' ' '\/']); n=n+1; end fprintf(repmat('\b',1,137)) ``` [Answer] # PHP 214 Thought I was doing alright until I counted the characters, anyway here it is - ``` <?function a($n,$v=" "){for($j=0;$j<$n;$j++){$r.=$v;}return $r;}for($i=64;$i>1;$i--){$b=a($i-1,"_");$v.=a(64-$i)."3^^".a($i*2-1,".")."^3\n".a(64-$i+1)."\\".$b.a(2).$b."/\n".a(65)."\/\n";}$v.=a(63)."3^^^^3";echo $v; ``` [Answer] # Lua - 174 ``` p=print a=" "b="_"for i=0,62 do j=63-i p(a:rep(i).."3^^."..(".."):rep(j).."^3")p(a:rep(i+1).."\\"..b:rep(j).." "..b:rep(j).."/")p(a:rep(65).."\\/")end p(a:rep(63).."3^^^^3") ``` --- Before that, I got two algorithmically different solutions (both 182 !) : ``` a=" "b="_"for i=0,62 do j=63-i print(a:rep(i).."3^^."..(".."):rep(j).."^3")print(a:rep(i+1).."\\"..b:rep(j).." "..b:rep(j).."/")print(a:rep(65).."\\/")end print(a:rep(63).."3^^^^3") ``` # ``` a=" "b="_"i=63 while i>0 do c=b:rep(i/2)for _,s in pairs{"3^^."..(".."):rep(i/2).."^3","\\"..c.." "..c.."/","\\/"}do print(a:rep(66-#s/2)..s)i=i-1 end end print(a:rep(63).."3^^^^3") ``` ]
[Question] [ Welcome, brave code golfer! Today you will stand in the midst of a great battle between a goblin and an elf! ``` goblin attacks elf! elf dodges! elf attacks goblin!     elf hits goblin for 13 damage!     goblin has 37 health left.     goblin attacks elf!     goblin hits elf for 1 damage!     elf has 49 health left.     elf attacks goblin!     elf hits goblin for 19 damage!     goblin has 18 health left.     goblin attacks elf!     goblin hits elf for 26 damage!     elf has 23 health left.     elf attacks goblin!     elf hits goblin for 20 damage!     goblin has been slain! ``` ## The Challenge Your challenge is to simulate a battle, like the above one. You will recieve input in this form: ``` creatureName health strength defense accuracy agility ``` For example, the battle between the goblin and elf would be: ``` goblin 50 40 35 3 2 elf 50 35 30 4 5 ``` The first and second creatures will alternate attacks. * Print 'creatureName attacks otherCreatureName!' * Check to see if the creature dodges. The creature will dodge an attack if (its agility times rand() divided by 2) is greater than (the attacker's accuracy times rand()). + If the creature dodges, print 'creatureName dodges!' + Otherwise, calculate the damage dealt by subtracting (the attacker's strength times rand()) and (the defender's defense times rand() divided by 2). Minimum damage is 1. Print 'creatureName hits otherCreatureName for (x) damage!' Then print 'creatureName has (x) health left.' unless the creature's health is 0 or less, in which case... - If the creature's health is 0 or less, print 'creatureName has been slain!' and end the program. ## Rules * Shortest code wins. * Don't literally print 'creatureName,' but replace it with the creature's name. Don't print '(x) damage' or '(x) health;' replace them with the actual amount. (I have to specify this because some people are *very* creative with bending the rules. :P) [Answer] ## Perl, 254 + 1 ``` for((@a[0..5],@b)=split;$a[1]>0;@c=@a,@a=@b,@b=@c){say"$a[0] attacks $b[0]!\n",rand$b[5]/2<rand$a[4]?do{($==rand($a[2])-rand$b[3]/2)<1and$==1;"$a[0] hits $b[0] for $= damage!\n$b[0] has ",($b[1]-=$=)>0?"$b[1] health left.":"been slain!"}:"$b[0] dodges!"} ``` Run with `perl -nM5.010` (or `perl -nE '<code>'`). Per [meta](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), the `-n` switch counts as one extra character. No fancy golfing tricks in this code, except maybe the use of `$=` as the damage variable to save an `int`. **Edit:** Hopefully, the damage calculation is correct now. [Answer] # CoffeeScript *454* 432 Pass a string to `b` to get the results. I thought it would be more fun to have a graphic animated output, so I put a demo together. Just change the input box to change statistics and names. The pictures from from [jpg.to](http://jpg.to) which is the unofficial google-images API. ## [Super Action Demo](http://cdpn.io/LHaJm) ![battle simulator in action](https://i.stack.imgur.com/YpzfA.jpg) ``` b=(s)-> r=Math.random p=s.split ' ' n=p.map Number l='' o=(x...)->l+=x.join(' ')+'!\n' while 1|i=!i c=(x)->n[i*6+x]*r() d=(x)->n[(i||6)+x]*r() t=->d(4)/2>c 5 h=->Math.max c(2)-d(3)/2,1 a=p[i*6] b=p[6+i*-6] o a,'attacks',b if c(5)/2>d 4 e=Math.ceil h() q=n[(i||6)+1]-=e o a,'hits',b,'for',e,'damage' o b,'has',q,'health left'if q>0 else o b,'dodges' if q<1 o b,'has been slain' break l ``` Recommended Inputs (suggest your own): ``` charmander 50 40 25 3 2 bulbasaur 90 30 40 4 5 voldemort 9999 10 5 1 1 batman 20 50 10 1010 30 ``` [Answer] ## Ruby, ~~292~~ 264 ``` v=$* def p*a;puts a*' 'end loop{a,b=v[0],v[6] w=v.map &:to_i p a,:attacks,b+?! w[11]*rand/2>w[4]*rand ? (p b,:dodges!):(h=v[7]=w[7]-=d=[rand(w[2])-rand(w[9])/2,1].max p a,:hits,b,:for,d,:damage! p b,:has,h<1?"been slain!":"#{h} health left." h<1&&exit) v.rotate!6} ``` My first code golf entry; how that method definition parses is beyond me :) Is it OK to read the input from command-line parameters (e.g. `ruby battle.rb goblin 50 40 35 3 2 elf 50 35 30 4 5`)? [Ideone run](http://ideone.com/FhtAs7) [Answer] ## JavaScript; ~~347~~ ~~341~~ 333 As I always do, I shall start off with my own solution: ``` for(m=prompt().split(' '),r=Math.random,a=console.log,c=0,d=6;;){if(a(m[c]+' attacks '+m[d]+'!'),r()*m[c+4]>r()*m[d+5]/2){if(a(m[c]+' hits '+m[d]+' for '+(h=Math.max(~~(r()*m[c+2]-r()*m[d+3]/2),1))+' damage!'),(m[d+1]-=h)<1){a(m[d]+' has been slain!');break}a(m[d]+' has '+m[d+1]+' health left.')}else a(m[d]+' dodges!');t=c;c=d;d=t} ``` EDIT: apparently assigning `console.log` to a variable breaks on some browsers, so here's the same code with a function declaration instead: ``` for(m=prompt().split(' '),r=Math.random,a=function(x){console.log(x)},c=0,d=6;;){if(a(m[c]+' attacks '+m[d]+'!'),r()*m[c+4]>r()*m[d+5]/2){if(a(m[c]+' hits '+m[d]+' for '+(h=Math.max(~~(r()*m[c+2]-r()*m[d+3]/2),1))+' damage!'),(m[d+1]-=h)<1){a(m[d]+' has been slain!');break}a(m[d]+' has '+m[d+1]+' health left.')}else a(m[d]+' dodges!');t=c;c=d;d=t} ``` I was thinking of changing it to `alert`, but that would just be evil :P [Answer] ## APL (~~249~~ ~~244~~ 242) Procedural style this time, so (in Dyalog at least) you have to paste this into an editor window. I named it `G` (the first line is the name, I've included it because that's how it shows up in the editor window so it should probably be counted). ``` G ⎕ML←3 D A←{(⊂↑⍵),⍎¨1↓⍵}¨↓2 6⍴A⊂⍨' '≠A←⍞ →5 ⎕←(↑D)'dodges!' A D←D A ⎕←(↑A)'attacks','!',⍨↑D →4/⍨>/?A[6],D[5] ⎕←A[1],'hits',D[1],'for','damage!',⍨D[2]-←1⌈-/?A[3],⌈D[4]÷2 →12/⍨D[2]≤0 ⎕←D[1],'has',D[2],'health left!' →5 ⎕←D[1],'has been slain!' ``` (edit: used numeric GOTOs instead of line labels. Turns out that (in Dyalog at least) all defining a label `X:` does is set `X` to the line number, so might as well use the numbers directly.) [Answer] # Python: 393 I squeezed a little harder, if I had 3 I could probably do `print = p` to shorten it by a few more, but I don't think there is much left in this one. 393: ``` from random import randrange as r x = input().split() t=range a,b=6,0 for i in t(1,6)+t(7,12):x[i]=int(x[i]) while x[b+1] > 0: a,b=b,a;print x[a]+" attacks "+x[b] if r(x[a+5]/2)>r(x[b+5]):print x[a]+' dodges!';continue d=max(r(x[a+2])-r(x[b+3]/2),1);print x[a]," hits ",x[b]," for ",d," damage!";x[b+1]-=d if x[b+1]>0:print x[b]," has ",x[b+1]," health left." print x[b]," has been slain" ``` 399: ``` from random import randrange as r x = raw_input().split() t=range a,b=6,0 for i in t(1,6)+t(7,12):x[i]=int(x[i]) while x[b+1] > 0: a,b=b,a;print x[a]+" attacks "+x[b] if r(x[a+5]/2) > r(x[b+5]):print x[a]+' dodges!';continue d=max(r(x[a+2])-r(x[b+3]/2),1);print x[a]," hits ",x[b]," for ",d," damage!";x[b+1]-=d if x[b+1]>0:print x[b]," has ",x[b+1]," health left." print x[b]," has been slain" ``` I think people are skipping that if you have a good condition in the loop, you don't need to check if the target is below health. [Answer] # JavaScript: ~~340~~ 306 339: ``` for(m=Math.random,a=prompt().split(" "),c=[a,a.splice(6)],e;0<+c[0][1]&&0<+c[1][1];)c.reverse(),console.log(c[0][0]+" attacks "+c[1][0]+"!\n"+(c[0][4]*m()<c[1][5]*m()/2?c[1][0]+" dodges!":c[0][0]+" hits "+c[1][0]+" for "+(e=1+(c[0][2]*m()-c[1][3]*m()/2|0))+" damage!\n"+c[1][0]+" has "+(0>(c[1][1]-=e)?"been slain!":c[1][1]+" health left."))) ``` 306: ``` for(var m=Math.random,a=prompt().split(" "),b=a.splice(6),d,e;0<+a[1]&&0<+b[1];d=a,a=b,b=d)console.log(a[0]+" attacks "+b[0]+"!\n"+(a[4]*m()<b[5]*m()/2?b[0]+" dodges!":a[0]+" hits "+b[0]+" for "+(e=a[2]*m()-b[3]*m()/2|0,e<=0?e=1:e)+" damage!\n"+b[0]+" has "+(0>(b[1]-=e)?"been slain!":b[1]+" health left."))) ``` Sample output: ``` goblin attacks elf! elf dodges! elf attacks goblin! elf hits goblin for 21 damage! goblin has 29 health left. goblin attacks elf! elf dodges! elf attacks goblin! elf hits goblin for 15 damage! goblin has 14 health left. goblin attacks elf! goblin hits elf for 1 damage! elf has 49 health left. elf attacks goblin! elf hits goblin for 16 damage! goblin has been slain! ``` Edit notes: +1 character, i missed the "!" after "dodges" Oh and i forgot to actually put an output after "Sample output" Changed the header to JavaScript, as @tbodt suggests [Answer] ## R: 387 characters ``` a=scan(,"");i=as.integer;r=runif;C=cat;X=data.frame(i(a[2:6]),i(a[8:12]));z=1;Y=c(a[1],a[7]);repeat{p=1+z%%2;n=X[,p];m=X[,-p];N=Y[p];M=Y[-p];C(N,"attacks",M,"\n");if(r(1)*n[5]<r(1)*m[5]/2){C(M,"dodges!\n")}else{C(N,"hits",M,"for",d<-max(round(n[2]*r(1)-m[3]*r(1)/2),1),"damages!\n");h=max(m[1]-d,0);if(h){C(M,"has",X[1,-p]<-h,"health left\n")}else{C(M,"has been slained!");break}};z=z+1} ``` Or fully-developed, with indentations and comments, to make things clearer: ``` a=scan(,"") # Read stdin as character vector i=as.integer r=runif C=cat X=data.frame(i(a[2:6]),i(a[8:12])) # Data frame with opponents stats z=1 # Turn counter Y=c(a[1],a[7]) # Vector of opponents name repeat{ # shorter than while(T) p=1+z%%2 # R indexing starts with 1 not 0 n=X[,p] # Attacking opponent stats m=X[,-p] # Defending opponent stats N=Y[p] # Attacking opponent name M=Y[-p] # Defending opponent name C(N,"attacks",M,"\n") # By default, cat separates elements with a space if(r(1)*n[4]<r(1)*m[5]/2){ C(M,"dodges!\n") }else{ C(N,"hits",M,"for",d<-max(round(n[2]*r(1)-m[3]*r(1)/2),1),"damages!\n") h=max(m[1]-d,0) # Health after the strike if(h){ # If health is not 0 C(M,"has",X[1,-p]<-h,"health left\n") }else{ # If it is C(M,"has been slained!") break } } z=z+1 } ``` [Answer] **C# - 464 453 chars** After a couple of nights on this I can't seem to get even close to the other entries (not that surprising for C#). Still room for improvement I suspect. No especially clever tricks. ``` using System;using System.Linq;class P{static void Main(string[]a){int D,h=1,z=6; var n=a.Select(x=>int.TryParse(x,out D)?D:0).ToList();var r=new Random();Func<int> R=()=>r.Next(101);for(;h>0;z=z>0?0:6){D=(n[8-z]*R()-n[3+z]*R()/2)/100;var d=n[5+z] *R()/2>n[10-z]*R();h=d?h:n[1+z]-=D=D<1?1:D;Console.Write("{0} attacks {1}!\n"+(d? "{1} dodges!\n":"{0} hits {1} for {2} damage!\n")+(d?"":"{1} has {3}\n"),a[6-z],a [z],D,h>0?h+" health left.":"been slain!");}}} ``` Commented: ``` using System; using System.Linq; class P { static void Main(string[] a) { int D, // string to int parsing and attack damage h = 1, // health z = 6; // index // painful requirement to convert the input strings to integers var n = a.Select(x => int.TryParse(x, out D) ? D : 0).ToList(); // set up a function to return a new random number var r = new Random(); Func<int> R = () => r.Next(101); // we'll exit the loop when the defender's health (h) is <= 0. // z is used as an index offset to get values out of the list, it flips between 0 an 6 each round for (; h > 0; z = z > 0 ? 0 : 6) { // calculate damage D = (n[8 - z] * R() - n[3 + z] * R() / 2) / 100; // see if defender dodges var d = n[5 + z] * R() / 2 > n[10 - z] * R(); // subtract health from defender if necessary. store health of defender in h h = d ? h : n[1 + z] -= D = D < 1 ? 1 : D; // print the round Console.Write( "{0} attacks {1}!\n" + (d ? "{1} dodges!\n" : "{0} hits {1} for {2} damage!\n") + (d ? "" : "{1} has {3}\n"), a[6 - z], a[z], D, h > 0 ? h + " health left." : "been slain!"); } } } ``` [Answer] ## Python 3, 314 ``` from random import* r=random p=print I=input().split() H=1 while H>0:s,a,H,D,G=map(int,I[2:5:2]+I[7::2]);N=I[6];p(I[0],"attacks",N+"!");I=I[6:]+I[:6];X=max(int(s*r()-D*r()/2),1)*(G*r()/2<a*r());I[1]=H=H-X;X<1and p(N,"dodges!")or p(I[6],"hits",N,"for",X,"damage!\n"+N,"has",["been slain!","%s health left."%H][H>0]) ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 6 years ago. [Improve this question](/posts/12090/edit) Create a function that will take two strings as input and return a single output for the result. Most popular answer wins. The rules of Rock-paper-scissors-lizard-Spock are: * Scissors cut paper * Paper covers rock * Rock crushes lizard * Lizard poisons Spock * Spock smashes scissors * Scissors decapitate lizard * Lizard eats paper * Paper disproves Spock * Spock vaporizes rock * Rock breaks scissors The output for every possible input case is: ``` winner('Scissors', 'Paper') -> 'Scissors cut Paper' winner('Scissors', 'Rock') -> 'Rock breaks Scissors' winner('Scissors', 'Spock') -> 'Spock smashes Scissors' winner('Scissors', 'Lizard') -> 'Scissors decapitate Lizard' winner('Scissors', 'Scissors') -> 'Scissors tie Scissors' winner('Paper', 'Rock') -> 'Paper covers Rock' winner('Paper', 'Spock') -> 'Paper disproves Spock' winner('Paper', 'Lizard') -> 'Lizard eats Paper' winner('Paper', 'Scissors') -> 'Scissors cut Paper' winner('Paper', 'Paper') -> 'Paper ties Paper' winner('Rock', 'Spock') -> 'Spock vaporizes Rock' winner('Rock', 'Lizard') -> 'Rock crushes Lizard' winner('Rock', 'Scissors') -> 'Rock breaks Scissors' winner('Rock', 'Paper') -> 'Paper covers Rock' winner('Rock', 'Rock') -> 'Rock ties Rock' winner('Lizard', 'Rock') -> 'Rock crushes Lizard' winner('Lizard', 'Spock') -> 'Lizard poisons Spock' winner('Lizard', 'Scissors') -> 'Scissors decapitate Lizard' winner('Lizard', 'Paper') -> 'Lizard eats Paper' winner('Lizard', 'Lizard') -> 'Lizard ties Lizard' winner('Spock', 'Rock') -> 'Spock vaporizes Rock' winner('Spock', 'Lizard') -> 'Lizard poisons Spock' winner('Spock', 'Scissors') -> 'Spock smashes Scissors' winner('Spock', 'Paper') -> 'Paper disproves Spock' winner('Spock', 'Spock') -> 'Spock ties Spock' ``` Extra challenge suggested by @Sean Cheshire: Allow custom lists, such as those from this site. With the n-item list, the item loses to the (n-1)/2 previous, and wins over the (n-1)/2 following [Answer] # APL ``` vs←{ n←'Scissors' 'Paper' 'Rock' 'Lizard' 'Spock' x←n⍳⊂⍺ ⋄ y←n⍳⊂⍵ ⋄ X←⍺ ⋄ Y←⍵ ⋄ r←{X,⍵,⊂Y} x=y: r (-x=0)↓'ties' y=5|1+x: r x⌷'cut' 'covers' 'crushes' 'poisons' 'smashes' y=5|3+x: r x⌷'decapitate' 'disproves' 'breaks' 'eats' 'vaporizes' ⍵∇⍺ } ``` Output exactly as required in all cases, including tie/ties. No lookup table, except for the actual words. You can try it on <http://ngn.github.io/apl/web/> ``` 'Spock' vs 'Paper' Paper disproves Spock ``` APL just knows! [Answer] ## SED ``` #!/bin/sed #expects input as 2 words, eg: scissors paper s/^.*$/\L&/ s/$/;scissors cut paper covers rock crushes lizard poisons spock smashes scissors decapitates lizard eats paper disproves spock vaporizes rock breaks scissors/ t a :a s/^\(\w\+\)\s\+\(\w\+\);.*\1 \(\w\+\) \2.*$/\u\1 \3 \u\2/ s/^\(\w\+\)\s\+\(\w\+\);.*\2 \(\w\+\) \1.*$/\u\2 \3 \u\1/ t b s/^\(\w\+\)\s\+\1;\(\1\?\(s\?\)\).*$/\u\1 tie\3 \u\1/ :b ``` [Answer] Here is a general solution based on a rule string of any size. It performs correct capitalization for the proper name "Spock" and also allows rules for specifying 'tie' instead of 'ties' for plural objects. ``` def winner(p1, p2): rules = ('scissors cut paper covers rock crushes lizard poisons Spock' ' smashes scissors decapitate lizard eats paper disproves Spock vaporizes' ' rock breaks scissors tie scissors'.split()) idxs = sorted(set(i for i, x in enumerate(rules) if x.lower() in (p1.lower(), p2.lower()))) idx = [i for i, j in zip(idxs, idxs[1:]) if j-i == 2] s=' '.join(rules[idx[0]:idx[0]+3] if idx else (rules[idxs[0]], 'ties', rules[idxs[0]])) return s[0].upper()+s[1:] ``` Results: ``` >>> winner('spock', 'paper') 'Paper disproves Spock' >>> winner('spock', 'lizard') 'Lizard poisons Spock' >>> winner('Paper', 'lizard') 'Lizard eats paper' >>> winner('Paper', 'Paper') 'Paper ties paper' >>> winner('scissors', 'scissors') 'Scissors tie scissors' ``` [Answer] ## Python ``` class Participant (object): def __str__(self): return str(type(self)).split(".")[-1].split("'")[0] def is_a(self, cls): return (type(self) is cls) def do(self, method, victim): return "%s %ss %s" % (self, method, victim) class Rock (Participant): def fight(self, opponent): return (self.do("break", opponent) if opponent.is_a(Scissors) else self.do("crushe", opponent) if opponent.is_a(Lizard) else None) class Paper (Participant): def fight(self, opponent): return (self.do("cover", opponent) if opponent.is_a(Rock) else self.do("disprove", opponent) if opponent.is_a(Spock) else None) class Scissors (Participant): def fight(self, opponent): return (self.do("cut", opponent) if opponent.is_a(Paper) else self.do("decaitate", opponent) if opponent.is_a(Lizard) else None) class Lizard (Participant): def fight(self, opponent): return (self.do("poison", opponent) if opponent.is_a(Spock) else self.do("eat", opponent) if opponent.is_a(Paper) else None) class Spock (Participant): def fight(self, opponent): return (self.do("vaporize", opponent) if opponent.is_a(Rock) else self.do("smashe", opponent) if opponent.is_a(Scissors) else None) def winner(a, b): a,b = ( eval(x+"()") for x in (a,b)) return a.fight(b) or b.fight(a) or a.do("tie", b) ``` [Answer] # Ruby, arithmetic approach The actors can can be arranged in an array in such a way that each actor `a[i]` wins against the actors `a[i+1]` and `a[i+2]`, modulo 5, for instance: ``` %w(Scissors Lizard Paper Spock Rock) ``` Then, for an actor `A` with index `i` we can see how he matches agains actor `B` with index `j` by doing `result = (j-i)%5`: Result `1` and `2` means that actor A won against an actor 1 or 2 places in front of him respectively; `3` and `4` similarly means he lost against an actor behind him in the array. `0` means a tie. (Note that this may be language dependent; in Ruby `(j-i)%5 == (5+j-i)%5` also when `j>i`.) The most interesting part of my code is the use of this property to find a sorting function of the indices of two actors. The return value will be -1, 0 or 1 [as it should](http://www.ruby-doc.org/core-2.0/Array.html#method-i-sort): ``` winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 } ``` Here's the whole thing: ``` def battle p1,p2 who = %w(Scissors Lizard Paper Spock Rock) how = %w(cut decapitate poisons eats covers disproves smashes vaporizes crushes breaks) i,j = [p1,p2].map { |s| who.find_index s } winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 } method = (winner-loser)%5/2 what = method == 0 && "ties" || how[winner*2 + method-1] return "#{who[winner]} #{what} #{who[loser]}" end ``` [Answer] ## Python ``` def winner(p1, p2): actors = ['Paper', 'Scissors', 'Spock', 'Lizard', 'Rock'] verbs = {'RoLi':'crushes', 'RoSc':'breaks', 'LiSp':'poisons', 'LiPa':'eats', 'SpSc':'smashes', 'SpRo':'vaporizes', 'ScPa':'cut', 'ScLi':'decapitate', 'PaRo':'covers', 'PaSp':'disproves', 'ScSc':'tie'} p1, p2 = actors.index(p1), actors.index(p2) winner, loser = ((p1, p2), (p2, p1))[(1,0,1,0,1)[p1 - p2]] return ' '.join([actors[winner], verbs.get(actors[winner][0:2] + actors[loser][0:2], 'ties'), actors[loser]]) ``` [Answer] # Python --- ``` def winner(p,q): if p==q: return(' '.join([p,'tie',q])) d = {'ca':'cut','ao':'covers','oi':'crushes','ip':'poisons','pc': 'smashes','ci':'decapitate','ia':'eats', 'ap':'disproves', 'po':'vaporizes','oc': 'breaks'} [a,b] = [p[1],q[1]] try: return(' '.join([p,d[a+b],q])) except KeyError: return(' '.join([q,d[b+a],p])) ``` Using a tricky dictionary. [Answer] # C# ### Assumptions The opponents are arranged in an n-item array where players beat the (n-1)/2 players ahead of them and lose to the (n-1)/2 players behind them. *(With even length lists, the player loses to the ((n-1)/2 + 1) players behind them)* Player actions are arranged in an array where actions within the range of [(indexOfPlayer \* (n-1)/2)] to [(indexOfPlayer \* (n-1)/2)) + (n-2)/2 - 1]. ### Additional Info `CircularBuffer<T>` is a wrapper around an array to create an "infinitely" addressable array. The `IndexOf` function returns the index of an item within the actual bounds of the array. ### The Class ``` public class RockPaperScissors<T> where T : IComparable { private CircularBuffer<T> players; private CircularBuffer<T> actions; private RockPaperScissors() { } public RockPaperScissors(T[] opponents, T[] actions) { this.players = new CircularBuffer<T>(opponents); this.actions = new CircularBuffer<T>(actions); } public string Battle(T a, T b) { int indexA = players.IndexOf(a); int indexB = players.IndexOf(b); if (indexA == -1 || indexB == -1) { return "A dark rift opens in the side of the arena.\n" + "Out of it begins to crawl a creature of such unimaginable\n" + "horror, that the spectators very minds are rendered\n" + "but a mass of gibbering, grey jelly. The horrific creature\n" + "wins the match by virtue of rendering all possible opponents\n" + "completely incapable of conscious thought."; } int range = (players.Length - 1) / 2; if (indexA == indexB) { return "'Tis a tie!"; } else { indexB = indexB < indexA ? indexB + players.Length : indexB; if (indexA + range < indexB) { // A Lost indexB = indexB >= players.Length ? indexB - players.Length : indexB; int actionIndex = indexB * range + (indexA > indexB ? indexA - indexB : (indexA + players.Length) - indexB) - 1; return players[indexB] + " " + actions[actionIndex] + " " + players[indexA]; } else { // A Won int actionIndex = indexA * range + (indexB - indexA) - 1; return players[indexA] + " " + actions[actionIndex] + " " + players[indexB]; } } } } ``` ### Example ``` string[] players = new string[] { "Scissors", "Lizard", "Paper", "Spock", "Rock" }; string[] actions = new string[] { "decapitates", "cuts", "eats", "poisons", "disproves", "covers", "vaporizes", "smashes", "breaks", "crushes" }; RockPaperScissors<string> rps = new RockPaperScissors<string>(players, actions); foreach (string player1 in players) { foreach (string player2 in players) { Console.WriteLine(rps.Battle(player1, player2)); } } Console.ReadKey(true); ``` [Answer] ## Python, one-liner ``` winner=lambda a,b:( [a+" ties "+b]+ [x for x in "Scissors cut Paper,Paper covers Rock,Rock crushes Lizard,Lizard poisons Spock,Spock smashes Scissors,Scissors decapitate Lizard,Lizard eats Paper,Paper disproves Spock,Spock vaporizes Rock,Rock break Scissors" .split(',') if a in x and b in x])[a!=b] ``` [Answer] Just a small thing I came up with: ``` echo "winners('Paper', 'Rock')"|sed -r ":a;s/[^ ]*'([[:alpha:]]+)'./\1/;ta;h;s/([[:alpha:]]+) ([[:alpha:]]+)/\2 \1/;G"|awk '{while(getline line<"rules"){split(line,a," ");if(match(a[1],$1)&&match(a[3],$2))print line};close("rules")}' IGNORECASE=1 ``` Here, rules is the file containing all the rules that were given. [Answer] ## Python Inspired by @Tobia's APL code. ``` def winner(p1, p2): x,y = map(lambda s:' scparolisp'.find(s.lower())/2, (p1[:2], p2[:2])) v = (' cut covers crushes poisons smashes'.split(' ')[x*(y in (x+1, x-4))] or ' decapitate disproves breaks eats vaporizes'.split(' ')[x*(y in (x+3, x-2))]) return ' '.join((p1.capitalize(), v or 'tie'+'s'*(x!=1), p2)) if v or p1==p2 \ else winner(p2, p1) ``` Results: ``` >>> winner('Spock', 'paper') 'Paper disproves Spock' >>> winner('Spock', 'lizard') 'Lizard poisons Spock' >>> winner('paper', 'lizard') 'Lizard eats paper' >>> winner('paper', 'paper') 'Paper ties paper' >>> winner('scissors', 'scissors') 'Scissors tie scissors' ``` [Answer] # C++ ``` #include <stdio.h> #include <string> #include <map> using namespace std ; map<string,int> type = { {"Scissors",0},{"Paper",1},{"Rock",2},{"Lizard",3},{"Spock",4} }; map<pair<int,int>, string> joiner = { {{0,1}, " cuts "},{{0,3}, " decapitates "}, {{1,2}, " covers "},{{1,4}, " disproves "}, {{2,3}, " crushes "},{{2,0}, " crushes "}, {{3,4}, " poisons "},{{3,1}, " eats "}, {{4,0}, " smashes "},{{4,2}, " vaporizes "}, } ; // return 0 if first loses, return 1 if 2nd wins int winner( pair<int,int> p ) { return (p.first+1)%5!=p.second && (p.first+3)%5!=p.second ; } string winner( string sa, string sb ) { pair<int,int> pa = {type[sa],type[sb]}; int w = winner( pa ) ; if( w ) swap(pa.first,pa.second), swap(sa,sb) ; return sa+(pa.first==pa.second?" Ties ":joiner[pa])+sb ; } ``` A bit of a test ``` int main(int argc, const char * argv[]) { for( pair<const string&, int> a : type ) for( pair<const string&, int> b : type ) puts( winner( a.first, b.first ).c_str() ) ; } ``` [Answer] # Javascript ``` function winner(c1,c2){ var c = ["Scissors", "Paper", "Rock", "Lizard", "Spock"]; var method={ 1:["cut", "covers", "crushes", "poisons", "smashes"], 2:["decapitate", "disproves", "breaks", "eats", "vaporizes"]}; //Initial hypothesis: first argument wins var win = [c.indexOf(c1),c.indexOf(c2)]; //Check for equality var diff = win[0] - win[1]; if(diff === 0){ return c1 + ((win[0]===0)?" tie ":" ties ") + c2; } //If s is -1 we'll swap the order of win[] array var s = (diff>0)?1:-1; diff = Math.abs(diff); if(diff >2){ diff = 5-diff; s= s * -1; } s=(diff==1)?s*-1:s; if(s === -1){ win = [win[1],win[0]]; } return c[win[0]] + " " + method[diff][win[0]] + " " + c[win[1]]; } ``` [Answer] # Javascript I see this isn't a golfing contest, but I had been fiddling with this puzzle for a while before finding this thread, so here goes. Here's a (standard) js version in 278 characters: ``` function winner(a,b){var c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5;return i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b} ``` Or one using E6 features (likely only works in Firefox) in 259 characters: ``` winner=(a,b,c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5)=>i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b ``` ]
[Question] [ # The Challenge Your goal is to write the shortest program possible that will take a list of events (such as upvote, downvote, etc) and return the user's reputation and the privileges that he has earned. ## What sort of events? Here is a chart of the events, listed in order of reputation earned: ``` -15 answer unaccepted -10 answer unupvoted -5 question unupvoted -2 answer downvoted -2 question downvoted -2 unaccept answer -1 downvote answer +1 join website +1 undownvote answer +2 accept answer +2 question undownvoted +2 answer undownvoted +5 question upvoted +10 answer upvoted +15 answer accepted +100 association bonus ``` ## What sort of privileges? Here is a list of privileges, in order of reputation required. ``` 1 create posts 5 participate in meta 10 remove new user restrictions 10 create wiki posts 15 vote up 15 flag posts 20 talk in chat 50 comment everywhere 75 set bounties 100 edit community wiki 100 create chat rooms 125 vote down 150 create tags 200 retag questions 250 view close votes 500 cast close and reopen votes 750 established user 1000 edit questions and answers 1000 create gallery chat rooms 1250 create tag synonyms 1500 approve tag wiki edits 2000 access to moderator tools 3500 protect questions 4000 trusted user ``` ## Input Input (on STDIN) will be a list of events, one per line, exactly how they appear in the first chart (except for the amount of reputation). A blank line represents the end of input. Here is an example (there should be a blank line at the end): ``` join website association bonus answer upvoted answer upvoted question upvoted answer accepted answer upvoted accept answer unaccept answer question unupvoted accept answer question upvoted ``` ## Output The first line of output (to STDOUT) should name the amount of rep accumulated. Each line after that should list one privilege earned, exactly as they appear and in the same order as the second chart. The expected output for the above input: ``` 153 reputation 1 create posts 5 participate in meta 10 remove new user restrictions 10 create wiki posts 15 vote up 15 flag posts 20 talk in chat 50 comment everywhere 75 set bounties 100 edit community wiki 100 create chat rooms 125 vote down 150 create tags ``` # Rules, Restrictions, and Notes This is code golf. Standard code golf rules apply. (EDIT: Since I have had two entries that access files, I would like to point out that the length of the file needs to be added to code length as part of the standard rules for code golf) [Answer] ## GolfScript (569 568 475 473 chars) This uses non-printable characters to compress the required strings, so in xxd format: ``` 0000000: 305c 6e2f 7b2e 2775 6e27 2f27 272a 2e2d 0\n/{.'un'/''*.- 0000010: 3162 6173 6527 6e3f 696d 646f 700a 705f 1base'n?imdop.p_ 0000020: 6c27 3132 2a3d 3131 302d 4040 3d7b 7e29 l'12*=110-@@={~) 0000030: 7d2a 2b7d 2f3a 5e2e 6e27 7978 0a51 b318 }*+}/:^.n'yx.Q.. 0000040: 34fd e3ad 76f0 9f48 a7db efe2 2e06 9a7a 4...v..H.......z 0000050: 0733 c726 2c43 7e1c 4bf6 bbbc dae7 3bd8 .3.&,C~.K.....;. 0000060: 835b d3b5 23ed c195 f733 6257 0741 296e .[..#....3bW.A)n 0000070: a97c b473 e67b 3f95 5218 0256 8c58 067c .|.s.{?.R..V.X.| 0000080: 1358 e5a6 0e7a 2894 3f26 9d0f afbc 0697 .X...z(.?&...... 0000090: 9048 7845 0041 d335 0c6f e88b 0b97 e9d9 .HxE.A.5.o...... 00000a0: d840 6808 c17d c1b2 5e79 f423 2436 dc33 .@h..}..^y.#$6.3 00000b0: 8da5 03d8 f563 f61a 7687 cff9 d489 24de .....c..v.....$. 00000c0: 5a70 4966 e614 d632 d4ba c9e4 5b1e f561 ZpIf...2....[..a 00000d0: 9308 215f b7bc f475 edc0 1686 a212 d4d0 ..!_...u........ 00000e0: 75c6 bab8 c4a0 1c85 d0b8 7f3f 53d1 8920 u..........?S.. 00000f0: 3923 895f 15d5 6c2e 965e c295 62c7 00cd 9#._..l..^..b... 0000100: 8b46 6e2a 3d7b 9ac3 7f90 e526 b960 dbe5 .Fn*={.....&.`.. 0000110: 5242 defa 24cf 5976 8378 f958 34f6 657d RB..$.Yv.x.X4.e} 0000120: 41da 28a9 cc4f 3930 dd25 d982 3b67 9400 A.(..O90.%..;g.. 0000130: 3a19 cf72 6ae9 3c19 ee5a 6fd2 ef52 e29c :..rj.<..Zo..R.. 0000140: 4872 8a86 c243 dcc1 23b1 7958 dcbc 307d Hr...C..#.yX..0} 0000150: 7c26 67d3 dd6a fbd2 1680 4de3 156b 8a4d |&g..j....M..k.M 0000160: ad31 d6fa 08ca 92a7 76d4 8e6e 8b71 167f .1......v..n.q.. 0000170: 3582 9d84 8038 d6c1 da9d 8b30 1805 c1aa 5....8.....0.... 0000180: b05d dfe2 4474 b26f 14be fc7f ccba c499 .]..Dt.o........ 0000190: 856a c31f c361 90f1 8c27 3235 3662 6173 .j...a...'256bas 00001a0: 6520 3134 3962 6173 655b 305d 2f28 3236 e 149base[0]/(26 00001b0: 2c7b 5c5b 3124 295d 2f5c 3224 3d2a 7d2f ,{\[1$)]/\2$=*}/ 00001c0: 5c2c 297b 2d7d 2b25 2b6e 257b 2761 272d \,){-}+%+n%{'a'- 00001d0: 7e5e 5c3c 217d 2c6e 2a ~^\<!},n* ``` Modulo the string compression, the program is ``` 0\n/{.'un'/''*.-1base'n?imdop p_l'12*=110-@@={~)}*+}/:^.' reputation 1 create posts 5 participate in meta 10 remove new user restrictions 10 create wiki posts 15 vote up 15 flag posts 20 talk in chat 50 comment everywhere 75 set bounties 100 edit community wiki 100 create chat rooms 125 vote down 150 create tags 200 retag questions 250 view close votes 500 cast close and reopen votes 750 established user 1000 edit questions and answers 1000 create gallery chat rooms 1250 create tag synonyms 1500 approve tag wiki edits 2000 access to moderator tools 3500 protect questions 4000 trusted user'n%{'a'-~^\<!},n* ``` Pretty trivial in most respects, but there are two points of interest. The first is the hash function for the input strings. I was astonished by how simple a hash function produces unique results for each of the 9 (once `un` is removed) different strings, and as a bonus it also produces a different result for the empty string, which saves stripping out the final blank line from the input. The calculation of rep for an individual line is ``` .'un'/''*.-1base'n?imdop p_l'12*=110-@@={~)}* ``` First, it removes `un` from the string, and makes a note of whether it was found. Then it applies a super-simple hash function, `h(s) = ( sum over i: (-1)^i s[i] ) % 11`. (You can see why I was surprised when I found it). The string ``` 'n?imdop p_l' ``` is a lookup table which maps the hash value to the change in rep (subtract 110 from the ASCII value), and then if it found `un` at the start it negates the change. The second point of interest is the filter for the privileges. I tried a slightly simpler one: ``` {~^\<!}, ``` which evaluates the line (undefined words do nothing) in order to get its score for comparison with the reputation (stored in `^`). It *almost* works. The thing which breaks it is that `and` occurs in some of the strings, and is a pre-defined function. Solution: mangle the lines enough that `and` no longer occurs. (There is a case to be made that removing spaces would be better than removing the letter `a`, but it doesn't make any difference to the length). [Answer] ## Ruby 1.9.3, 514 467 459 (507 460 452 + 7 for flags) Run with `ruby -rzlib <program>`. ``` #coding:binary r=0 $<.each{|l|b=l.sub!('un','')?-1:1 r+=('cvuwdsaifo'[/.#{l[9]||break}/].ord-2)*b} puts"#{r} reputation" Zlib.inflate('xÚ]QKrà Ýû:BìÖ“ó(XM˜`D‘lo_‰ÒL¦;ÐÓûÁ¡*AaQf(X5†X|3¬¤8Œ¨´òNé€M¨Ú]´Æ ‘³8ÞUŽøŒ]jœagmÅ_ ï˜. ˜ž®¨Ãll^WÊ ´S=U®3)ÜxËÉ=.@KÔ¶»å¨g3kónîjP™WÛžºûÂG6ÿ׎âÝx!;Â÷f=Z‡ÉvöhõBb¡F¶çpqíCÌ‹ñ¸PîøÕH&€·åAK{OÔ£¾Ô³TåïqUþý=-È™9Ÿx,¥úG8ÒÛZ#ÃB P†•ª¨\\íÂI†§Q)¼¥>¥uýËþ²d').lines{|l|l.to_i<=r&&$><<l} ``` If the binary string literals didn't paste properly (which they probably didn't), here's a hex dump: ``` 0000: 23 63 6F 64 69 6E 67 3A 62 69 6E 61 72 79 0A 72 #coding:binary.r 0010: 3D 30 0A 24 3C 2E 65 61 63 68 7B 7C 6C 7C 62 3D =0.$<.each{|l|b= 0020: 6C 2E 73 75 62 21 28 27 75 6E 27 2C 27 27 29 3F l.sub!('un','')? 0030: 2D 31 3A 31 0A 72 2B 3D 28 27 11 63 0C 76 07 75 -1:1.r+=('.c.v.u 0040: 00 77 00 64 04 73 01 61 03 69 66 6F 27 5B 2F 2E .w.d.s.a.ifo'[/. 0050: 23 7B 6C 5B 39 5D 7C 7C 62 72 65 61 6B 7D 2F 5D #{l[9]||break}/] 0060: 2E 6F 72 64 2D 32 29 2A 62 7D 0A 70 75 74 73 22 .ord-2)*b}.puts" 0070: 23 7B 72 7D 20 72 65 70 75 74 61 74 69 6F 6E 22 #{r} reputation" 0080: 0A 5A 6C 69 62 2E 69 6E 66 6C 61 74 65 28 27 78 .Zlib.inflate('x 0090: DA 5D 51 4B 72 C3 20 0C DD FB 14 3A 42 EC D6 93 .]QKr. ....:B... 00A0: F3 28 58 4D 98 60 44 91 6C 8F 6F 5F 89 D2 4C A6 .(XM.`D.l.o_..L. 00B0: 3B D0 D3 FB C1 08 A1 12 2A 41 61 51 19 66 28 58 ;.......*AaQ.f(X 00C0: 35 86 58 7C 16 33 AC A4 38 8C 17 A8 B4 F2 4E 90 5.X|.3..8.....N. 00D0: E9 80 4D A8 DA 5D B4 C6 A0 91 B3 38 DE 55 8E F8 ..M..].....8.U.. 00E0: 8C 5D 6A 9C 61 67 1B 6D C5 8F 5F 09 EF 1D 98 2E .]j.ag.m.._..... 00F0: A0 98 9E AE 1E 1E A8 C3 6C 6C 5E 57 CA 0A B4 53 ........ll^W...S 0100: 3D 8F 07 55 1A AE 33 08 29 DC 78 CB 1A C9 3D 2E =..U..3.).x...=. 0110: 40 4B D4 B6 BB E5 A8 67 33 6B F3 6E EE 6A 50 99 @K.....g3k.n.jP. 0120: 57 DB 9E BA FB C2 47 36 FF D7 8E E2 DD 13 78 21 W.....G6......x! 0130: 3B C2 F7 66 3D 5A 87 C9 76 F6 68 F5 42 62 A1 46 ;..f=Z..v.h.Bb.F 0140: B6 E7 70 71 14 ED 43 CC 8B F1 B8 50 EE F8 D5 48 ..pq..C....P...H 0150: 26 80 B7 14 E5 41 4B 7B 1A 4F D4 A3 BE D4 1B 13 &....AK{.O...... 0160: B3 1C 54 E5 17 EF 71 EE 98 92 55 FE 17 FD 3D 2D ..T...q...U...=- 0170: C8 99 39 9F 0E 78 1A 2C A5 FA 47 38 D2 1E DB 8D ..9..x.,..G8.... 0180: 5A 23 C3 42 20 11 50 86 95 17 AA A8 5C 5C ED C2 Z#.B .P.....\\.. 0190: 49 86 0F A7 1A 51 29 BC A5 1A 3E 9D A5 75 13 FD I....Q)...>..u.. 01A0: CB FE 03 06 1A B2 64 27 29 2E 6C 69 6E 65 73 7B ......d').lines{ 01B0: 7C 6C 7C 6C 2E 74 6F 5F 69 3C 3D 72 26 26 24 3E |l|l.to_i<=r&&$> 01C0: 3C 3C 6C 7D <<l} ``` [Answer] ## Haskell, 787 characters ``` main=interact$unlines.f.z(l 0[521,471,703,455,687,320,355,0,582,93,914,682,476,244,294,545][-15,-10,-5,-2,-2,-2,-1,1,1,2,2,2,5,10,15,100].g).s f r=[show x++" "++y|(x,y)<-(r,"reputation"):takeWhile((<=r).fst)(zip[1,5,10,10,15,15,20,50,75,100,100,125,150,200,250,500,750,1000,1000,1250,1500,2000,3500,4000].s$"A E@participate in meta@remove new I restrictions@A K E@J up@flag E@talk in C@comment everywhere@set bounties@B community K@A C G@J down@A Hs@reH F@view D Js@cast D and reopen Js@established I@B F and answers@A gallery C G@A H synonyms@approve H K Bs@access to moderator tools@protect F@trusted I">>=h)] g x=z fromEnum x-1219 h x=l[x]['@'..]("\n":words"create edit chat close posts questions rooms tag user vote wiki")x l d k v x=maybe d id.lookup x$zip k v s=lines z=(sum.).map ``` [Answer] ## C# ~~1271~~ ~~1208~~ 1206 ``` public class D:Dictionary<string,int>{} void A(){ string a="answer",q="question",c="create",y="accept",x=y+"ed",u="upvote",d="downvote"; var p=new D{{c+" posts",1},{"participate in meta",5},{"remove new user restrictions",10},{c+" wiki posts",10},{"vote up",15},{"flag posts",15},{"talk in chat",20},{"comment everywhere",50},{"set bounties",75},{"edit community wiki",100},{c+" chat rooms",100},{"vote down",125},{c+" tags",150},{"retag "+q+"s",200},{"view close votes",250},{"cast close and reopen votes",500},{"established user",750},{"edit "+q+"s and "+a+"s",1000},{c+" gallery chat rooms",1000},{c+" tag synonyms",1250},{"approve tag wiki edits",1500},{"access to moderator tools",2000},{"protect "+q+"s",3500},{"trusted user",4000}}; var e=new D{{a+" un"+x,-15},{a+" un"+u+"d",-10},{q+" un"+u+"d",-5},{a+" "+d+"d",-2},{q+" "+d+"d ",-2},{"un"+y+" "+a,-2},{d+" "+a,-1},{"join website",1},{"un"+d+" "+a,1},{y+" "+a,2},{q+" un"+d+"d",2},{a+" un"+d+"d",2},{q+" "+u+"d",5},{a+" "+u+"d",10},{a+" "+x,15},{"association bonus",100}}; var s=0; for(var l=Console.ReadLine();l!="";l=Console.ReadLine())s+=e[l]; Console.WriteLine(s+" reputation");foreach(var i in p.Where(i=>i.Value<=s))Console.WriteLine(i.Key);} ``` [Answer] # C - 1083 1069 I realize that I'm a bit late to the game, but C's not represented, so I figured I'd take a stab at it. ``` #include <stdio.h> H(char*c){int h,n;for(h=n=0;*c!=0;++n,++c)h=(h^*c)+n;return h;} main(){int h,r=0,R[483];R[110]=-15;R[122]=-10;R[153]=2;R[157]=1;R[189]=-2;R[20]=-2;R[235]=5;R[238]=15;R[28]=10;R[30]=2;R[351]=-5;R[388]=100;R[482]=-2;R[52]=2;R[77]=-1;R[87]=1;char L[99];while(h=H(gets(&L)))r+=R[h]; #define G(x)if(r<x)goto E; #define P(x)printf("%s\n",x); P("1 create posts")G(5)P("5 participate in meta")G(10)P("10 remove new user restrictions\n10 create wiki posts")G(15)P("15 vote up\n15 flag posts")G(20)P("20 talk in chat")G(50)P("50 comment everywhere")G(75)P("75 set bounties")G(100)P("100 edit community wiki\n100 create chat rooms")G(125)P("125 vote down")G(150)P("150 create tags")G(200)P("200 retag questions")G(250)P("250 view close votes")G(500)P("500 cast close and reopen votes")G(750)P("750 established user")G(1000)P("1000 edit questions and answers\n1000 create gallery chat rooms")G(1250)P("1250 create tag synonyms")G(1500)P("1500 approve tag wiki edits")G(2000)P("2000 access to moderator tools")G(3500)P("3500 protect questions")G(4000)P("4000 trusted user")E:} ``` ``` #include <stdio.h> H(char*c){int h,n;for(h=n=0;*c;++n,++c)h=(h^*c)+n;return h;} main(){int h,r=0,R[483];R[110]=-15;R[122]=-10;R[153]=2;R[157]=1;R[189]=-2;R[20]=-2;R[235]=5;R[238]=15;R[28]=10;R[30]=2;R[351]=-5;R[388]=100;R[482]=-2;R[52]=2;R[77]=-1;R[87]=1;char L[99];while(h=H(gets(&L)))r+=R[h]; #define G(x)if(r<x)return; #define P(x)puts(x); P("1 create posts")G(5)P("5 participate in meta")G(10)P("10 remove new user restrictions\n10 create wiki posts")G(15)P("15 vote up\n15 flag posts")G(20)P("20 talk in chat")G(50)P("50 comment everywhere")G(75)P("75 set bounties")G(100)P("100 edit community wiki\n100 create chat rooms")G(125)P("125 vote down")G(150)P("150 create tags")G(200)P("200 retag questions")G(250)P("250 view close votes")G(500)P("500 cast close and reopen votes")G(750)P("750 established user")G(1000)P("1000 edit questions and answers\n1000 create gallery chat rooms")G(1250)P("1250 create tag synonyms")G(1500)P("1500 approve tag wiki edits")G(2000)P("2000 access to moderator tools")G(3500)P("3500 protect questions")G(4000)P("4000 trusted user")} ``` Here's a slightly less golfed version: ``` #include <stdio.h> int hash(char * c){int h,n;for(h=n=0;*c!=0;++n,++c)h=(h^*c)+n;return h;} int main(int argc, char *argv[]) { int R[483]; R[110]=-15;// answer unaccepted R[122]=-10;// answer unupvoted R[153]=2; // question undownvoted R[157]=1; // join website R[189]=-2; // question downvoted R[20]=-2; // answer downvoted R[235]=5; // question upvoted R[238]=15; // answer accepted R[28]=10; // answer upvoted R[30]=2; // answer undownvoted R[351]=-5; // question unupvoted R[388]=100;// association bonus R[482]=-2; // unaccept answer R[52]=2; // accept answer R[77]=-1; // downvote answer R[87]=1; // undownvote answer int h,r=0; char L[99]; while(h=hash(gets(&L)))r+=R[h]; #define G(x)if(r<x)goto end; #define P(x)printf("%s\n",x); P("1 create posts") G(5) P("5 participate in meta") G(10) P("10 remove new user restrictions") P("10 create wiki posts") G(15) P("15 vote up") P("15 flag posts") G(20) P("20 talk in chat") G(50) P("50 comment everywhere") G(75) P("75 set bounties") G(100) P("100 edit community wiki") P("100 create chat rooms") G(125) P("125 vote down") G(150) P("150 create tags") G(200) P("200 retag questions") G(250) P("250 view close votes") G(500) P("500 cast close and reopen votes") G(750) P("750 established user") G(1000) P("1000 edit questions and answers") P("1000 create gallery chat rooms") G(1250) P("1250 create tag synonyms") G(1500) P("1500 approve tag wiki edits") G(2000) P("2000 access to moderator tools") G(3500) P("3500 protect questions") G(4000) P("4000 trusted user") end: return 0; } ``` I think the basic idea is similar to many other people's approaches. I use a little home-made hash to deal with recognizing inputs. The hash conveniently gives zero for an empty string, making the input-reading line very compact. I'm sure that the hash could be greatly improved. Some good character savings could be gotten by allowing some strategic hash collisions for things that have the same reputation. I also had some real perverse fun hiding a `goto` inside a macro (my first time ever using a `goto`, I'm proud to say). The one place where I'm sure I have a *lot* of room for improvement is in the output section. I haven't even attempted to compress the actual printing logic, so I'm sure that I could save some characters there as well. [Answer] # C (~~765~~ 737 chars) ``` #define P(x,m) if(s>=x)puts(#x" "#m); s;char*e="&g 5 x$hg54 $ G5UC vg",l[99];main(){while(gets(l))s+=e[(l[11]%8^l[7])-97]*7%118-15;printf("%d reputation\n",s);P(1,create posts)P(5,participate in meta)P(10,remove new user restrictions)P(10,create wiki posts)P(15,vote up)P(15,flag posts)P(20,talk in chat)P(50,comment everywhere)P(75,set bounties)P(100,edit community wiki)P(100,create chat rooms)P(125,vote down)P(150,create tags)P(200,retag questions)P(250,view close votes)P(500,cast close and reopen votes)P(750,established user)P(1000,edit questions and answers)P(1000,create gallery chat rooms)P(1250,create tag synonyms)P(1500,approve tag wiki edits)P(2000,access to moderator tools)P(3500,protect questions)P(4000,trusted user)} ``` Or a bit more readable with added linebreaks and indentation: ``` #define P(x,m) if(s>=x)puts(#x" "#m); s;char*e="&g 5 x$hg54 $ G5UC vg",l[99]; main(){ while(gets(l))s+=e[(l[11]%8^l[7])-97]*7%118-15; printf("%d reputation\n",s); P(1,create posts) P(5,participate in meta) P(10,remove new user restrictions) P(10,create wiki posts) P(15,vote up) P(15,flag posts) P(20,talk in chat) P(50,comment everywhere) P(75,set bounties) P(100,edit community wiki) P(100,create chat rooms) P(125,vote down) P(150,create tags) P(200,retag questions) P(250,view close votes) P(500,cast close and reopen votes) P(750,established user) P(1000,edit questions and answers) P(1000,create gallery chat rooms) P(1250,create tag synonyms) P(1500,approve tag wiki edits) P(2000,access to moderator tools) P(3500,protect questions) P(4000,trusted user) } ``` The above codes assumes a single newline at the end of the file. If there are two, then one needs to write `s+=*l?e[…]:0` instead of `s+=e[…]`, at an **additional cost of 5 chars**. Writing `while(*gets(l))` would be shorter but won't work since I don't include headers, so the compiler assumes `gets` returns `int` not `char*`. The hashing expression `(l[11]%8^l[7])-97` was found by trying all expressions of the following forms, looking for the one with shortest resulting code length: ``` for i in range(13): for j in range(13): pat("a[i]^a[j]", i=i, j=j) pat("a[i]-a[j]", i=i, j=j) pat("a[i]|a[j]", i=i, j=j) pat("a[i]&a[j]", i=i, j=j) pat("a[i]*a[j]", i=i, j=j) pat("a[i]%a[j]", i=i, j=j) for k in range(13): pat("a[i]^a[j]^a[k]", i=i, j=j, k=k) pat("a[i]%a[j]^a[k]", i=i, j=j, k=k) pat("a[i]*a[j]^a[k]", i=i, j=j, k=k) pat("a[i]+a[j]^a[k]", i=i, j=j, k=k) pat("a[i]-a[j]^a[k]", i=i, j=j, k=k) pat("a[i]^a[j]|a[k]", i=i, j=j, k=k) pat("a[i]%a[j]|a[k]", i=i, j=j, k=k) pat("a[i]*a[j]|a[k]", i=i, j=j, k=k) pat("a[i]+a[j]|a[k]", i=i, j=j, k=k) pat("a[i]-a[j]|a[k]", i=i, j=j, k=k) pat("a[i]*k^a[j]", i=i, j=j, k=k) pat("a[i]%k^a[j]", i=i, j=j, k=k) pat("a[i]%k+a[j]", i=i, j=j, k=k) pat("a[i]%k-a[j]", i=i, j=j, k=k) pat("a[i]%k|a[j]", i=i, j=j, k=k) for l in range(13): pat("a[i]%k^a[j]%l", i=i, j=j, k=k, l=l) for k in range(100): pat("a[i]+k^a[j]", i=i, j=j, k=k) pat("a[i]-k^a[j]", i=i, j=j, k=k) ``` A suitable printable ASCII character representation was found using a similar brute force search. # Python 3 (~~743~~ 715 chars) In the same spirit as above. This one relies on a second newline at the end of the input, though. ``` s=0 while 1: l=input() if not l:break s+=b'>-/1/.04-1*//0//91%\x93/ -'[(ord(l[11])%8^ord(l[7]))-97]-47 print(s,"reputation") for p in "1 create posts|5 participate in meta|10 remove new user restrictions|10 create wiki posts|15 vote up|15 flag posts|20 talk in chat|50 comment everywhere|75 set bounties|100 edit community wiki|100 create chat rooms|125 vote down|150 create tags|200 retag questions|250 view close votes|500 cast close and reopen votes|750 established user|1000 edit questions and answers|1000 create gallery chat rooms|1250 create tag synonyms|1500 approve tag wiki edits|2000 access to moderator tools|3500 protect questions|4000 trusted user".split("|"): if s>=int(p.split(" ")[0]):print(p) ``` [Answer] **Java - 1519 chars** ``` import java.util.*;public class A{static List m=new ArrayList();static String c="create",p="posts",w="wiki",e="edit",v="vote",t="tag",q="questions"; static void g(String a){m.add(a);}public static void main(String a[]){ g("1 "+c+" "+p);g("5 participate in meta");g("10 remove new user restrictions");g("10 "+c+" "+w+" "+p);g("15 "+v+" up");g("15 flag "+p);g("20 talk in chat");g("50 comment everywhere");g("75 set bounties");g("100 "+e+" community "+w);g("100 "+c+" chat rooms");g("125 "+v+" down");g("150 "+c+" "+t+"s");g("200 re"+t+" "+q);g("250 view close "+v+"s");g("500 cast close and reopen "+v+"s");g("750 established user");g("1000 "+e+"s "+q+" and answers");g("1000 "+c+" gallery chat rooms");g("1250 "+c+" "+t+" synonyms");g("1500 approve "+t+" "+w+" "+e+"s");g("2000 access to moderator tools");g("3500 protect "+q);g("4000 trusted user"); Scanner s=new Scanner(System.in);String i=s.nextLine();int r=0;int b; while(!i.equals("")){b=r(i);if(b==1740)r-=15;if(b==1690)r-=10;if(b==1922)r-=5;if(b==1674||b==1906||b==1539)r-=2;if(b==1574)r-=1;if(b==1219||b==1801)r+=1;if(b==1312||b==2133||b==1901)r+=2;if(b==1695)r+=5;if(b==1463)r+=10;if(b==1513)r+=15;if(b==1764)r+=100;i=s.nextLine();} System.out.println(r+" reputation");for(Object q:m)if(c(q,r))System.out.println((String)q);} static boolean c(Object q,int r){StringTokenizer t=new StringTokenizer((String)q);if(Integer.parseInt(t.nextToken())<=r)return true;return false;} static int r(String i){int r=0;for(int k=0;k<i.length();)r+=i.charAt(k++);return r;}} ``` To find reputation, it adds all the character in input string (example 'join website' adds to form 1219) and when b==1219, r=r+1. [Answer] ### Scala 1089 ``` object R extends App{val t=List(("j.*",1),(".*s",100),(".*r a.*",15),(".*r d.*",-2),(".*n d.*",-2),(".* una.*",-15),("u.*",-2),("ac.*",2),("und.*",1),("d.*",-1),(".*r up.*",10),(".*n up.*",5),(".*r unu.*",-10),(".*r .*",2),(".*n unu.*",-5),(".*n .*",2)) def a(s:String)=t.find(x=>s.matches(x._1)).map(x=>x._2).getOrElse(0) var(r,s)=(0,"") do{s=readLine r+=a(""+s)}while(s!=null) println(r+" reputation") val (q,c)=(" questions","create ") val d=List(1->(c+"posts"),5->"participate in meta",10->"remove new user restrictions",10->(c+"wiki posts"),15->"vote up",15->"flag posts",20->"talk in chat",50->"comment everywhere",75->"set bounties",100->"edit community wiki",100->(c+"chat rooms"),125->"vote down",150->(c+"tags"),200->("retag"+q),250->"view close votes",500->"cast close and reopen votes",750->"established user",1000->("edit"+q+" and answers"),1000->(c+"gallery chat rooms"),1250->(c+"tag synonyms"),1500->"approve tag wiki edits",2000->"access to moderator tools",3500->("protect"+q),4000->"trusted user") d.filter(_._1<=r).toList.sortBy(_._1).map(v=>println((v._1)+" "+v._2))} ``` Rewrote from scratch, nearly. If I have to calculate the data in, it is cheaper (while ugly) to include the data directly. First approach, reading event prices and privilege tab from files: ### reading data from file: 405 ``` object R extends App{import io.Source._ import java.util._ def m(n:String)={fromFile(n).getLines.toList.map{l=>val s=new Scanner(l);(s.next(),s.nextLine())}} val e=m("e").map(a=>(a._2.trim->a._1.replaceAll("\\+","").toInt)).toMap val p=m("p").map(b=>(b._1.toInt,b._2)) var(r,t)=(0,"") for(t<-stdin.getLines)r+=e(t) println(r+" reputation") p.filter(_._1<=r).toList.sortBy(_._1).map(v=>println(v._1+v._2))} ``` [Answer] ## J (704) The program consists of four parts: 1. the following decoder script (**277** bytes) ``` b=:,@#:@(a.i.fread) s=:(15+6*#.@(3{.12&}.))({.;$:^:(40<#)@}.)] r=:3 :'(15-~#.12{.y);;:^:_1[(#._6>\15}.y){u:@(96&+)&.>0 cut#._5>\b''w'''&.>@s@b f=:3 :'>>{.&.>e#~;((<y)=}.)&.>e=:r''e''' echo' reputation',~":R=:+/;f&.>LF cut 1!:1[3 echo>((":@>@{.),' ',>@{:)&.>p#~R>>>{.&.>p=:r'p' ``` 2. a binary words file, called `w`, also **277** bytes (download [here](http://frankenstein.d-n-s.org.uk/privs/w)). The file format is as follows: each word is encoded as a group of five-bit "bytes". Each group of five bits can have a value from `1` to `27` representing letters, or `0` being the separator. Every unique word in the description of the events and privileges is stored here. 3. a binary events file, called `e`, which is **54** bytes (download [here](http://frankenstein.d-n-s.org.uk/privs/e)). Each event consists of a 12-byte reputation and one or more 6-byte words. For example, `accept answer` is encoded as follows: ``` rep+15 Nwords word1 word2 000000010001 010 000110 011101 17 2 6 29 <- these are indices in "w" "accept" "answer" ``` 4. a binary privileges file, called `p`, which is **96** bytes (download [here](http://frankenstein.d-n-s.org.uk/privs/p)). The file format is the same as `e`, e.g. `access to moderator tools` is encoded as follows: ``` rep+15 Nwords word1 word2 word3 word4 011111011111 100 011010 011011 100000 010000 2015 4 26 27 32 16 "access" "to" "moderator" "tools" ``` [Answer] # Perl, ~~856~~ 849 characters ``` $_="reputaT,A unPed,-15,A unU,-10,Q unU,-5,A DVd,-2,Q DVd,-2,unP A,-2,DV A,-1,join website,1,unDV A,1,P A,2,Q unDVd,2,A unDVd,2,Q U,5,A U,10,A Ped,15,associaT bonus,100,1,C Ps,5,participate in meta,10,remove new R restricTs,10,C wiki Ps,15,V up,15,flag Ps,20,talk in H,50,comment everywhere,75,set bounties,100,edit community wiki,100,C H rooms,125,V D,150,C tags,200,retag Qs,250,view close Vs,500,cast close and reopen Vs,750,established R,1000,edit Qs and As,1000,C gallery H rooms,1250,C tag synonyms,1500,approve tag wiki edits,2000,access to moderator tools,3500,protect Qs,4000,trusted R";$s="UupVd;Paccept;Aanswer;QquesT;Ccreate;Vvote;Ddown;Ttion;Opost;Hchat;Ruser;";$s=~s,(.)(.+?);,s/$1/$2/g;,g;eval $s;@D=split/,/;%R=@D[1..32];@P=@D[33..80];while(<>){chomp;$r+=$R{$_}}print("$r $D[0]\n");for(0..23){print"@P[$_*2,$_*2+1]\n"if$r>=$P[$_*2]} ``` just adding linebreaks after some semicolons for readability ;) : ``` $_="reputaT,A unPed,-15,A unU,-10,Q unU,-5,A DVd,-2,Q DVd,-2,unP A,-2,DV A,-1,join website,1,unDV A,1,P A,2,Q unDVd,2,A unDVd,2,Q U,5,A U,10,A Ped,15,associaT bonus,100,1,C Ps,5,participate in meta,10,remove new R restricTs,10,C wiki Ps,15,V up,15,flag Ps,20,talk in H,50,comment everywhere,75,set bounties,100,edit community wiki,100,C H rooms,125,V D,150,C tags,200,retag Qs,250,view close Vs,500,cast close and reopen Vs,750,established R,1000,edit Qs and As,1000,C gallery H rooms,1250,C tag synonyms,1500,approve tag wiki edits,2000,access to moderator tools,3500,protect Qs,4000,trusted R"; $s="UupVd;Paccept;Aanswer;QquesT;Ccreate;Vvote;Ddown;Ttion;Opost;Hchat;Ruser;"; $s=~s,(.)(.+?);,s/$1/$2/g;,g;eval $s; @D=split/,/;%R=@D[1..32];@P=@D[33..80]; while(<>){chomp;$r+=$R{$_}}print("$r $D[0]\n"); for(0..23){print"@P[$_*2,$_*2+1]\n"if$r>=$P[$_*2]} ``` [Answer] # Java (1470 chars) --- **Note:** It's a modification of [Aman ZeeK Verma's answer](https://codegolf.stackexchange.com/a/5512/14156) but since my edit wasn't accepted and my answer is significantly shorter than his, I'm posting it here. *Readable Version:* ``` import java.util.*; public class A { static List m = new ArrayList(); static String c = "create", p = "posts", w = "wiki", e = "edit", v = "vote", t = "tag", q = "questions"; static void g(String a) { m.add(a); } public static void main(String a[]) { g("1 " + c + " " + p); g("5 participate in meta"); g("10 remove new user restrictions"); g("10 " + c + " " + w + " " + p); g("15 " + v + " up"); g("15 flag " + p); g("20 talk in chat"); g("50 comment everywhere"); g("75 set bounties"); g("100 " + e + " community " + w); g("100 " + c + " chat rooms"); g("125 " + v + " down"); g("150 " + c + " " + t + "s"); g("200 re" + t + " " + q); g("250 view close " + v + "s"); g("500 cast close and reopen " + v + "s"); g("750 established user"); g("1000 " + e + "s " + q + " and answers"); g("1000 " + c + " gallery chat rooms"); g("1250 " + c + " " + t + " synonyms"); g("1500 approve " + t + " " + w + " " + e + "s"); g("2000 access to moderator tools"); g("3500 protect " + q); g("4000 trusted user"); Scanner s = new Scanner(System.in); String i = s.nextLine(); int r = 0; int b; while (!i.equals("")) { b = r(i); if (b == 1740) { r -= 15; } if (b == 1690) { r -= 10; } if (b == 1922) { r -= 5; } if (b == 1674 || b == 1906 || b == 1539) { r -= 2; } if (b == 1574) { r -= 1; } if (b == 1219 || b == 1801) { r += 1; } if (b == 1312 || b == 2133 || b == 1901) { r += 2; } if (b == 1695) { r += 5; } if (b == 1463) { r += 10; } if (b == 1513) { r += 15; } if (b == 1764) { r += 100; } i = s.nextLine(); } System.out.println(r + " reputation"); for (Object o : m) { if (c(o, r)) { System.out.println((String) o); } } } static boolean c(Object q, int r) { return Integer.parseInt(new StringTokenizer((String) q).nextToken()) <= r; } static int r(String i) { int r = 0; for (int k = 0; k < i.length();) { r += i.charAt(k++); } return r; } } ``` *Minified Version:* ``` import java.util.*;public class A{static List m=new ArrayList();static String c="create",p="posts",w="wiki",e="edit",v="vote",t="tag",q="questions";static void g(String a){m.add(a);}public static void main(String a[]){g("1 "+c+" "+p);g("5 participate in meta");g("10 remove new user restrictions");g("10 "+c+" "+w+" "+p);g("15 "+v+" up");g("15 flag "+p);g("20 talk in chat");g("50 comment everywhere");g("75 set bounties");g("100 "+e+" community "+w);g("100 "+c+" chat rooms");g("125 "+v+" down");g("150 "+c+" "+t+"s");g("200 re"+t+" "+q);g("250 view close "+v+"s");g("500 cast close and reopen "+v+"s");g("750 established user");g("1000 "+e+"s "+q+" and answers");g("1000 "+c+" gallery chat rooms");g("1250 "+c+" "+t+" synonyms");g("1500 approve "+t+" "+w+" "+e+"s");g("2000 access to moderator tools");g("3500 protect "+q);g("4000 trusted user");Scanner s=new Scanner(System.in);String i=s.nextLine();int r=0;int b;while(!i.equals("")){b=r(i);if(b==1740)r-=15;if(b==1690)r-=10;if(b==1922)r-=5;if(b==1674||b==1906||b==1539)r-=2;if(b==1574)r-=1;if(b==1219||b==1801)r+=1;if(b==1312||b==2133||b==1901)r+=2;if(b==1695)r+=5;if(b==1463)r+=10;if(b==1513)r+=15;if(b==1764)r+=100;i=s.nextLine();}System.out.println(r+" reputation");for(Object o:m)if(c(o,r))System.out.println((String)o);}static boolean c(Object q,int r){return Integer.parseInt(new StringTokenizer((String)q).nextToken())<=r;}static int r(String i){int r=0;for(int k=0;k<i.length();)r+=i.charAt(k++);return r;}} ``` [Answer] ## PHP: 676 chars It won't win any prizes but gosh darn it I just can't figure out how to make this any smaller, so I'll just post it: ``` <?php while($l=fgets(STDIN))foreach(@[j=>1,bo=>100,pt=>2,pte=>13,'r un?u?p'=>5,up=>5,wn=>-2,'e '=>1]as$k=>$v)@$r+=$v*ereg($k,$l)*(ereg(un,$l)?-1:1);$p=@preg_replace;foreach(split(' ',$p('/[A-Z]/e','" ".$p("/.*?$0|[A-Z].*/","",@AaCcreateEeditGtagHchatIinLcloseMcommPpostsQquestionsRroomsTtUuserVvoteWwikiZre)',$r."Zputation 1CP 5 participateI meta 10Zmove newUZstrictions 10CWP 15V up 15 flagP 20TalkIH 50Ment everywhere 75 set bounties 100EMunityW 100CHR 125V down 150CGs 200ZtagQ 250 viewLVs 500 castLAndZopenVs 750 establishedU 1000EQAndAnswers 1000C galleryHR 1250CG synonyms 1500ApproveGWEs 2000AccessTo moderatorTools 3500 protectQ 4000TrustedU"))as$i)$r>=$i&&print"$i "; ``` Since the part that calcs the rep is very hard to read, here it is with extra formatting. It abuses undefined constants and uses @ to shut them up: ``` while($l=fgets(STDIN)) foreach(@[ j=>1, // join website bo=>100, // association bonus pt=>2, // (un)?accept answer|answer (un)?accepted pte=>13, // answer (un)?accepted 'r un?u?p'=>5, // answer (un)?upvoted up=>5, // (answer|question) (un)?upvoted wn=>-2, // (answer|question) (un)?downvoted|(un)?downvote answer 'e '=>1 // (un)?downvote answer ]as$k=>$v) @$r+=$v*ereg($k,$l)*(ereg(un,$l)?-1:1); ``` [Answer] ## APL (549) This one packs the data in Unicode characters. ``` P D←{,⍉(20/2)⊤⎕UCS⍵} M←{×⍴⍵:(2⊥⍺↑⍵),⍺∇⍺↓⍵⋄⍬} Z←{15<⍴⍵:(⊂(15-⍨2⊥12↑⍵),' ',.,w[6M 15↓r↑⍵]),∇⍵↓⍨r←15+6×2⊥3↑12↓⍵⋄⍬} w←⎕UCS¨96+1↓¨w⊂⍨0=w←5M D'崫񈁯񫒮򠉥򠁨퀖񽂠򫪰򳺅𠀣𙘔䢴鰒𫸅񰉹񳷙񬰍𭀠򓷭򘈵𬺉񻩠񋠕񰑣𬊅𠁬񼲠򣷬򘂏򻫏򡒀򤪳򡒀𬺁𓄳񁒀򳺅򘀮𠁏򫪉𬰃򑐴𨈵𬺉񻠕򅧴𩀁𘲳򘊏ᒉ򤰁񴻥򐇅򸋥𔴴𨆯𡙁򣹀򠓳৮򬰒𬺒񈺉񻩠멷𬩠𳀧ᛅ򖛨𬢠𛶭򫤴󈂏򻫏򡐁𘲰򡒀𸖌𬬠칯𚐴񋷀𣻮䉏򡑴⧩񰊮𣻮򳺅ᒉ򠈏򝉠򬀒𫗶𨁡򝀔鰕񰑣𬊀򫢏򻫏򡒀򀙔񈴰킠򲒷ؐ򓻅倬񘊳𬠀' ⎕←'reputation',⍨r←+/{⊃⊃e/⍨⍵∘{⍺≡⊃1↓⍵}¨e←Z D'O𞀊򞆀𩌣ڧ򒀍񌩀𚭷򀎕𯀈𫸀𐖃󀈨񷠄񓏀詻򀅄󋐃𩹨礽񐎚򲌀'}¨{×⍴⍵:(⊂' ',⍵),∇⍞⋄⍬}⍞ ⎕←↑↑{⍵,⍨⍕⍺}/¨p/⍨r≥⊃¨p←Z D'၌񤀨󹎋ᦚ𿻈㋘爁󤋦㲦󈂍󸜈节򜅩殃򛱨䇍򰈘𑢅򴊕𱄆򺈍𐥽𠪐𝵐񘥔򿔩󩾼󄵚񓽸󅘡򉸭򍢥󫧞󀮯򿆷𡑶󭗆󽞤󽀀' ``` [Answer] # Python 3.x (801 chars) Best I can do so far, just need to work out a better encoding than base64 (hint hint: can somebody assist?). ``` import base64,zlib exec(zlib.decompress(base64.b64decode(b'eJxtU93O2jAMve9T+K7tCJ+ArZqExpMgLkJrICNNsvxQoel799kplI7toqLYPsfHx27hxVkoIYXbrcT+IJRxKVa1+F0m09nB3GxEkCYM6MvtWpSybdHFKbKhSH6FMYEdVTWi/GmVgQGPQUUccSHYVsmorIGjNSlQdLUS5a+EIQeT41YEJ3Qyb22Wm3nlJKybC5gFufwf8cv1VJrM1G25not445jKX8MtebqZlBdRM6v/r8CpdL36JH899vaGYHCAFCjtidOrlnmzOYRzznNJlGcY1FUBdipyrmHnWo8yjslwN9bce05tGkoFjGRyMlEhxb6TMkZCa/s+GRXvme2xgOxRcuPaqF/ENsJzQEJ/nTc7S63R36G9yAje2n5cIxcQN5oIeKP8cEFPa2/+UjkKp4gMJEXbwKvpaGzr0ADLCAx5YfLIzob4sCNKfQU6K25OvrJ2ReaNVA98Hj8PO42Qu4wreKkdOzzJx7MOAaKF3nboZbSe/ljNlBlBZPKoVbhgl9fFtrImn0KcQt/m5G8ekbnSR9Uqx0kao8co87V75B3OLN9w9UlT8CmweeyJ7yov+bM4kULNPOojOK1iVZZlQU+9LUCdQNMP+MVO7vWhcF6ZWHluRV93/gjLOjMoZnAjxO3V4cfOM/D8QbeHpqvoJCuO14sSyoWqH1RfgvU0dnUWV7zvtOyPnQS5Bc7Jpx4o6/3qUNcioNs91RV/ACHUeCw=')).decode()) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 714 bytes ``` r=0 L=' questions' C=',create ' K=f'j,nv,n u,r u,ss,e ,t ,pte,reputation{C}posts,participate in meta,remove new user restrictions{C}wiki posts,vote up,flag posts,talk in chat,comment everywhere,set bounties,edit community wiki{C}chat rooms,vote down{C}tags,retag{L},view close votes,cast close and reopen votes,established user,edit{L} and answers{C}gallery chat rooms{C}tag synonyms,approve tag wiki edits,access to moderator tools,protect{L},trusted user'.split(',') while 1: i=input() if not i:break r+=[1,-2,5,10,100,-1,2,15][[a in i for a in K].index(1)]*(1-2*('un'in i)) for R,j in zip([r,1,5,10,10,15,15,20,50,75,100,100,125,150,200,250,500,750,1e3,1e3,1250,1400,2e3,3500,4e3],K[8:]): if R<=r:print(R,j) ``` [Try it online!](https://tio.run/##bVNNb9swDL37V/Bmu2OLOGmwIphPPbanXoMcFJtJ1DqSJtHxsqK/PSOdFEW7AiIsfr5HUg5H3nk3uwvxdIr1JHusc/jdU2LrXcqz@zrHJpJhgjx7qDf5M7oDOugxiqSEBMiAgQkjhZ6N5r3evwWfOGEwkW1jg6ZbB3tiI2F7fyBwNECfKEIUrGibEU8SB/ti4Zx98JLWB9x0ZnsxseletFKzM4yN3@/JMdCB4nHYUSRMxLD2vWNLQq21DBrUO8tH0MoCoKkQvd9fAFo/KGE22yTc5PP6@IYHK/SazicCDUrYmMQXg3GtkPaB3MUnDZh1Z9OO2rGlEViqjJHGpYGidrY1XSdE4YPAGRbS0Xl3FD4mhKizUeM4By0k5qahlIA97H1L0bCPovhO5huFQKNYyLFPfCGQ36TQWS5yzMts2NmOoFpkYGvrZEVFKdcNOM9gF2vZ7UsG8Ue9rPB6inOsJnImeF3hFKv5ark0OnALG0Edrw@rG@ta@lNU5eqqqK6nV0Xeu1yDyjLTsCd81sC/NhTLiNV7USmnZzrB@QR/zkeYUaZqn4hDZK5edYudZmdRY3WrXtFm6r6l2QoflneLVbkYu3n6VcdFiNZxIejl6fTshcFA62SZMpOSb@z4NuV5uD5l57XI69IVtl/V9x/gq183Eb6JP9svu85691n/qOa@T/gPLvsH "Python 3.8 (pre-release) – Try It Online") Yay, I'm 1 byte below the best answer! Uses the restricted input format (input through STDIN, output through STDOUT). Surprisingly, switching to a lambda only saves thirteen bytes. ]
[Question] [ The program will be provided as the first argument, stdin should be used for all read requests by the program and stdout for all write requests. It can be assumed that the program is less than 80 characters wide and less than 25 lines high. * `~` should push -1 if there is nothing to read. * Any pop off the bottom of the list should simply return 0, including for any calculations. * For `p` and `g`, `x` and `y` are 0 based indices. * Input should be fully buffered, i.e. `&` and `~` block the program until `EOF` is encountered on stdin then any remaining input is kept to serve future requests. The following commands must be available: > > > `0-9` >     Push this number on the stack > `+` >     Addition: Pop `a` then `b`, push `a+b` > `-` >     Subtraction: Pop `a` then `b`, push `b-a` > `*` >     Multiplication: Pop `a` then `b`, push `a*b` > `/` >     Integer division: Pop `a` then `b`, push `b/a`, rounded down. If `a` is 0, result is undefined > `%` >     Modulo: Pop `a` then `b`, push the remainder of the integer division of `b/a`. If `a` is 0, result is undefined > `!` >     Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0. > ``` >     Greater than: Pop `a` then `b`, push 1 if `b>a`, otherwise 0. > `>` >     Start moving right > `<` >     Start moving left > `^` >     Start moving up > `v` >     Start moving down > `?` >     Start moving in a random cardinal direction > `_` >     Pop a value; move right if value=0, left otherwise > `|` >     Pop a value; move down if value=0, up otherwise > `"` >     Start string mode: push each character's ASCII value all the way up to the next `"` > `:` >     Duplicate value on top of the stack > `\` >     Swap two values on top of the stack > `$` >     Pop value from the stack > `.` >     Pop value and output as an integer > `,` >     Pop value and output as ASCII character > `#` >     Trampoline: Skip next cell > `p` >     A "put" call (a way to store a value for later use). Pop `y` then `x` then `v`, change the character at the position `(x,y)` in the program to the character with ASCII value `v` > `g` >     A "get" call (a way to retrieve data in storage). Pop `y` then `x`, push ASCII value of the character at that position in the program > `&` >     Input an integer (may be multiple characters and may be negative) and push it > `~` >     Input a single character from stdin and push its ASCII value > `@` >     End program > > This is a code golf, shortest answer wins. If there is a tie then the first answer wins. You may use any language feature not specifically designed for Befunge to implement this, if you want to try and translate Befunge to native code and eval it good luck. For test cases look at my recent answers. The reference interpreter I have been using is <http://www.quirkster.com/js/befunge.html>. One quick test case of some features from [`"egnufeB">:#,_@`](http://www.quote-egnufeb-quote-greaterthan-colon-hash-comma-underscore-at.info/befunge/compat.php) ``` 1-0g:"Z"-#v_$91+"sparw tup/teG">:#,_$ v Z >:" "-#v_$91+"ecaps snruter teg BOO">:#,_$v v >0" snruter teg BOO">:#,_$.91+, > >8:+:*11p11g#v_91+"tib 8 dengis"01-11p11g!#v_"nu">" era slleC">:#,_v vv >91+"tib 8>" > ^ >91+"krow " # > >"spmuj egdE">:#,_ 91+"krow "04-3%1+#v_ >"sredniamer evitag"v >"ton od "^ >"ton od "^ "eN">:#,_ 91+"skrow edomgnirts ni @">:#,_@ > ``` [Answer] # Befunge-93 - ~~404~~ ~~371~~ ~~361~~ ~~352~~ ~~339~~ ~~337~~ 323 bytes ``` <xyXYvp01<>110vv5_v#`0+1:_v#+!-"g"\<v"<":::<>1v#p03-1_>! g20gp00g1+0v25p v2g02 < p0 20p<+vp020p01-10$_:"p"-!^>>-!\ v^ <>0p20pv|!*-";"\+1::~p0< v2-10<^v# ^#< <<$< < ^+!-"_"\+!-"?"<>#^_10v4p<:^00 _$20g1+20p^ v21p010>#<40g20v>\%:40p5+g:92p:75*1--00g!\#^_\$0 v >91+-^ <3+g01g 03p04+g<^++g04g02:*54p03:%\++g03g01:"P"p0< ``` [Try It Online!](http://esolang.rutteric.com/fungejs/?initprog=JTNDeHlYWXZwMDElM0MlM0UxMTB2djVfdiUyMyU2MDAlMkIxJTNBX3YlMjMlMkIhLSUyMmclMjIlNUMlM0N2JTIyJTNDJTIyJTNBJTNBJTNBJTNDJTNFMXYlMjNwMDMtMV8lM0UhJTIwZzIwZ3AwMGcxJTJCMHYyNXAlMEF2MmcwMiUyMCUzQyUyMHAwJTIwMjBwJTNDJTJCdnAwMjBwMDEtMTAlMjRfJTNBJTIycCUyMi0hJTVFJTNFJTNFLSElNUMlMjB2JTVFJTIwJTNDJTNFMHAyMHB2JTdDISotJTIyJTNCJTIyJTVDJTJCMSUzQSUzQX5wMCUzQyUwQXYyLTEwJTNDJTVFdiUyMyUyMCU1RSUyMyUzQyUyMCUyMCUzQyUzQyUyNCUzQyUyMCUyMCUyMCUyMCUyMCUyMCUyMCUzQyUyMCU1RSUyQiEtJTIyXyUyMiU1QyUyQiEtJTIyJTNGJTIyJTNDJTNFJTIzJTVFXzEwdjRwJTNDJTNBJTVFMDAlMjBfJTI0MjBnMSUyQjIwcCU1RSUwQXYyMXAwMTAlM0UlMjMlM0M0MGcyMHYlM0UlNUMlMjUlM0E0MHA1JTJCZyUzQTkycCUzQTc1KjEtLTAwZyElNUMlMjMlNUVfJTVDJTI0MCUyMHYlMjAlMjAlMjAlM0U5MSUyQi0lNUUlMEElM0MzJTJCZzAxZyUyMDAzcDA0JTJCZyUzQyU1RSUyQiUyQmcwNGcwMiUzQSo1NHAwMyUzQSUyNSU1QyUyQiUyQmcwM2cwMSUzQSUyMlAlMjJwMCUzQyUwQSUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUzQiUwQTBfNzElM0FFbnRlciUyMGlucHV0JTIwcmVhZGluZyUyMHN1YnByb2dyYW0lMEEyXzU4JTNBbGVmdCUyMGlmJTIwbm90JTIwbmV3bGluZSUyQyUyMHJpZ2h0JTIwaWYlMjBuZXdsaW5lJTBBMV81MyUzQXVwJTIwaWYlMjBFT0YlMjBvciUyMCUzQiUyMGRvd24lMjBvdGhlcndpc2UlMEEwXzUzJTNBZXhpdCUyMGlucHV0JTIwcmVhZGluZyUwQTBfNTIlM0FiZWdpbiUyMGluaXRpYWxpemF0aW9uJTIwb2YlMjAoMCUyQzApJTIwdG8lMjAoNSUyQzApJTBBNF80OSUzQWVudHJ5JTIwdG8lMjBtYWluJTIwbG9vcCUwQTNfNDQlM0FyaWdodCUyMGlmJTIwbGFzdCUyMG9wJTIwd2FzJTIwJTIyJTIwbGVmdCUyMGFuZCUyMHVwJTIwb3RoZXJ3aXNlJTBBM180NiUzQXRocm93JTIwYXdheSUyMHB1c2hlZCUyMCUyMiUwQTNfNDclM0F1cGRhdGUlMjAoMCUyQzApJTIwd2l0aCUyMG5ldyUyMHN0cmluZyUyMG1vZGUlMjBmbGFnJTBBMl80NiUzQXJpZ2h0JTIwaWYlMjBzdHJpbmclMjBtb2RlJTJDJTIwbGVmdCUyMGFuZCUyMHVwJTIwb3RoZXJ3aXNlJTBBMF80MyUzQWVudGVyJTIwc3BlY2lhbCUyMGNhc2UlMjBwcm9jZXNzaW5nJTBBMV8yOCUzQWxlZnQlMjBpZiUyMGN1cnJlbnQlMjBvcCUyMGNvdWxkJTIwc2V0JTIwZGlyZWN0aW9uJTIwdG8lMjB3ZXN0JTIwKCUyMl8lMjIlMkMlMjAlMjIlM0YlMjIlMkMlMjBvciUyMCUyMiUzQyUyMiklMkMlMjBvdGhlcndpc2UlMjByaWdodCUwQTFfMjYlM0FzZXQlMjBkaXJlY3Rpb24lMjB0byUyMHdlc3QlMEEwXzI1JTNBbGVmdCUyMGlmJTIwY3VycmVudCUyMG9wJTIwaXMlMjAlMjJnJTIyJTIwb3IlMjAlMjJwJTIyJTJDJTIwcmlnaHQlMjBhbmQlMjBkb3duJTIwb3RoZXJ3aXNlJTBBMF8xNyUzQWxlZnQlMjBpZiUyMHklMjB2YWx1ZSUyMGlzJTIwbm9ubmVnYXRpdmUlMkMlMjByaWdodCUyMGFuZCUyMGRvd24lMjBvdGhlcndpc2UlMEEyXzE3JTNBcmVtb3ZlJTIwdGhlJTIwMCUyMHdlJTIwcHVzaGVkJTIwb24lMjBlaXRoZXIlMjBvZiUyMHRoZSUyMHR3byUyMGJyYW5jaGVzJTIwdGhhdCUyMGFycml2ZSUyMGhlcmUlMEExXzE1JTNBaW5jcmVhc2UlMjBub25uZWdhdGl2ZSUyMHklMjB2YWx1ZXMlMjBieSUyMDUlMjAodG8lMjBhdm9pZCUyMG1vZGlmeWluZyUyMHRoaXMlMjBpbnRlcnByZXRlciklMEEyXzE1JTNBYWxsJTIwc3BlY2lhbCUyMGNhc2UlMjBicmFuY2hlcyUyMGFyZSUyMHRvZ2V0aGVyJTIwbm93JTBBMl85JTNBZXhlY3V0ZSUyMHRoZSUyMGN1cnJlbnQlMjBvcCUyMGhlcmUlMEEwXzEwJTNBc2V0JTIwZGlyZWN0aW9uJTIwdG8lMjBlYXN0JTBBMV80JTNBcmVhZGluZyUyMGZyb20lMjAoMiUyQzApJTIwYW5kJTIwd3JpdGluZyUyMGl0JTIwYWdhaW4lMjBpcyUyMGElMjBub3AlMjB0byUyMGFsbG93JTIwYWxsJTIwYnJhbmNoZXMlMjB0byUyMGVuZCUyMHdpdGglMjAwcCUwQTJfNDclM0F3cml0aW5nJTIwMSUyMHRvJTIwKDAlMkMwKSUyMGV2ZW4lMjB0aG91Z2glMjBpdCUyMGlzJTIwYWxyZWFkeSUyMDElMjBhbGxvd3MlMjB0aGlzJTIwYnJhbmNoJTIwdG8lMjBlbmQlMjB3aXRoJTIwMHAlMEE0XzQ4JTNBYWxsJTIwNyUyMGJyYW5jaGVzJTIwdGhhdCUyMGV2ZW50dWFsbHklMjBtZXJnZSUyMGhlcmUlMjBhcmUlMjByZWFkeSUyMHRvJTIwd3JpdGUlMjB0byUyMHRoZSUyMGdyaWQlM0IlMjB0aGlzJTIwMHAlMjBpcyUyMGZvciUyMGFsbCUyMG9mJTIwdGhlbSUwQTBfOSUzQXNldCUyMGRpcmVjdGlvbiUyMHRvJTIwbm9ydGglMEEzXzYlM0FzZXQlMjBkaXJlY3Rpb24lMjB0byUyMHNvdXRoJTBBM18xMCUzQWluY3JlbWVudCUyMElQJTIwb25jZSUyMGZvciUyMHRyYW1wb2xpbmUlMjAobWFpbiUyMGxvb3AlMjB1cGRhdGUlMjB3aWxsJTIwaGFuZGxlJTIwd3JhcHBpbmclMjBpdCklMEEzXzI1JTNBZmV0Y2glMjBjdXJyZW50JTIwb3AlMEEzXzI2JTNBa2VlcCUyMGElMjBjb3B5JTIwb24lMjB0aGUlMjBzdGFjayUwQTNfMjklM0FwbGFjZSUyMHRoZSUyMG90aGVyJTIwaW4lMjB0aGUlMjBleGVjdXRpb24lMjBwZW4lMjBhdCUyMCg5JTJDMiklMEEzXzM2JTNBbWFrZSUyMHplcm8lMjBpZiUyMGN1cnJlbnQlMjBvcCUyMGlzJTIwJTIyJTBBM180MCUzQWZldGNoJTIwYW5kJTIwaW52ZXJ0JTIwc3RyaW5nJTIwbW9kZSUwQTNfNDElM0F0aGVuJTIwcHV0JTIwJTIyJTIwdGVzdCUyMGJhY2slMjBvbiUyMHRvcCUwQTBfMCUzQXdoZW4lMjBpbnB1dCUyMHJlYWRpbmclMkMlMjBjb2x1bW4lMjBudW1iZXIlM0IlMjBlbHNlJTIwc3RyaW5nbW9kZSUyMGZsYWclMEEwXzElM0F4JTIwaW5jcmVtZW50JTIwZm9yJTIwY3Vyc29yJTBBMF8yJTNBd2hlbiUyMGlucHV0JTIwcmVhZGluZyUyQyUyMHJvdyUyMG51bWJlciUzQiUyMGVsc2UlMjB5JTIwaW5jcmVtZW50JTIwZm9yJTIwY3Vyc29yJTBBMF8zJTNBeCUyMGNvb3JkaW5hdGUlMjBvZiUyMGN1cnNvciUyMChyZWxhdGl2ZSUyMHRvJTIwaW50ZXJwcmV0ZWQlMjBwcm9ncmFtKSUwQTBfNCUzQXklMjBjb29yZGluYXRlJTIwb2YlMjBjdXJzb3IlMjAocmVsYXRpdmUlMjB0byUyMGludGVycHJldGVkJTIwcHJvZ3JhbSk%3D) Input program must have at most 20 lines. Input can be provided in same file as Befunge program by placing it after a `;` character. Yes, it can interpret itself, but the `*54` in the bottom line should be replaced by `*53` if you do that. And if you ask that interpreted interpreter to interpret itself, change it to `*52` etc. If run in a Befunge-97 interpreter, it will also support the `a-f` commands (but not `'` or any new command that affects control flow or wrapping behavior). Note that it basically asks the interpreter it runs in to handle all the stuff relating to I/O and stack, so its specific behavior is largely dependent on that of the interpreter running it. In other words, it is perfectly compliant if run in a compliant interpreter. It works by reading in the program from input (until EOF or semicolon) directly into the playfield below it, then simulating the movement of a virtual instruction pointer through that program. It copies each command from the program into its own execution area (at position (9,2) on the grid) and runs its own instruction pointer through it after ensuring all of its own data has been removed from the stack (as all of the interpreted program's stack data is maintained at the bottom of the stack). This is the standard methodology for Befunge self-interpretation since the early 00s, but I don't think it has ever been done in such a small program. A fuller explanation is in the annotations you can see by clicking the link above. [Answer] ## Perl, 515 ~~525~~ ~~532~~ Ok, so this might not be the most readable code I've ever written, but it does run all the examples in the reference implementation page properly, and use -1 as a `~`-didn't-have-a-reply value. (the programs in the page exercise the empty stack behavior extensively) As usual, Perl 5.10 or later. In this instance, `-M5.010` is your best bet. Newlines for presentation on CG.SE, you should remove them before trying. (in this "edit 1.5" ragged-right version, it might actually work out of the box) ``` @p=map[/./g],<>;$h=1;$_="for(;;){for(D_=P[Y][X]){ when('\"BS=!S}when(!!S){IordW0'||/\\d/){ID_W+BIO+ OW-BEO;IO-MW*BIO*OW/BEO;Iint(O/M)W%BEO;IO% MW!BI! OW`BEO;I(M<O)W?BD_=qw(< > ^ v)[rand 4]R_BD_=O?'<' :'>'R|BD_=O?'^':'v'R>BH=1;V=0W<BH=-1;V=0W^BH=0;V =-1WvBH=0;V=1W:BI0+S[-1]W\\\\BIO,OWDBOW.BsayOW,B print chrOW#BFWpBEO;N=O;P[M][N]=chrOWgBEO;IordP[ M][O]W&BIE<>W~BIord<>||-1WABexit}}F}";s/B/'){/g; s/I/pushAs,/g;s/E/M=/g;s/F/X=(X+H)%A{P[0]};Y=(Y+ V)%Ap/g;s/O/(popAs)/g;s/R/;redoW/g;s/W/}when('/g ;y/DA/$@/;s/[A-Z]/\$\l$&/g;eval ``` Improvements welcome :-D *Edit 1:* fix integer division (+2), reorganize (-9) *Edit ~~2~~ 1.5:* ~~read char by char (+4);~~ halt on division by zero (-10) Still missing char by char input, I'm not clear yet how it parses numbers and I'm too tired to be able to do it now. Not motivated enough to make the cell size unsigned 8-bit as suggested by the compatibility test, and not sure how negative remainders are expected in an unsigned environment. [Answer] ## 16bit MSDOS .COM File - 1104 bytes This is Base64 encoded ([decoder here](http://www.motobit.com/util/base64-decoder-encoder.asp)), save decoded file as a .com and execute from command line with name of program file to run as the only argument. Tested in WinXP command prompt. ``` yEAAADP/jNiAxBCJRv6JRvKAxBCJfuqJRuyJfvqJfviJfvSAxBCJRvbHRuiMAo7AM8C5AIDzq7Qs zSGJVvC6RgWKHoAAMv+A6wF9Cei3ALQJzSHJw8aHggAAuAA9uoIAzSG6SAVy5YvYjkb+uQCAM8Dz q7kBALpQBbQ/zSG6SgVyygvAdCWgUAU8CnQHPCBy4qrr34vHOkb5cgOIRvn+RviB5wD/gccAAevI tD7NIQv/ukwFdJa4AwDNEDPb6FQAtAfNITxxdDk8cnQhPDF0DTwydBE8c3Xo6I8A6+CLRvaJRvLr 2ItG/olG8uvQi0b2iUby6B4A6HEAgH76AHTu67zoAgDJw7gAuI7AuCAHuQCA86vDYB6OXvK4ALiO wLUZM/8z9rQHsVCsq/7JdfqBxrAA/s118FOLRvI7Rv6yz3QFi170svCA+1BzG4D/GXMWise0oPbk ANiA1AAA2IDUAIv4R4rCqlsfYcOORv4migc8MHJVPDl3UbQALDDoKwD/ZugK23UDil75/svD/sM6 Xvl1+DLbwwr/dQOKfvj+z8P+xzp++HX4Mv/DBsR+6quJfuoHwwbEfuozwAv/dAmD7wImiwWJfuoH w77uBIPGA4A8/3QOOAR19ItEAQvAdAP/4MO6TgXpZP7olP8migc8InSNtADos//r7+i4/4nB67To 9v8Dwel0/+ju/yvB6Wz/6Ob/9+npZP/o3v+Z9/npW//o1f+Z9/mLwulQ/+iF/wvAuAEAdAFI6UL/ 6Lz/O8G4AQB/AUjpNP/HRuiMAukv/+hh/wvAdPHHRuiCAukg/+hS/wvAdAjHRuiWAukR/8dG6KAC 6Qn/i0bwuk189+IFGTaJRvAkBgWSA4vwrYlG6Ont/pYCoAKCAowC6Bf/6Ar/6dn+6FP/kegA/4nI 6c3+6AL/6cr+6Pz+C8B5CffYULAt6CYAWFO7UAUz0rkKAPfxgMIwiBdDC8B170uKB+gKAIH7UAV1 9Fvplf48CnQUBsR+9KqLxzxQdQSBx7AAiX70B8PGRvQA/kb1w+in/uja/+ls/uhp/ulm/ugOAOiV /gaORv4miAQH6VX+6If+ik74C8B5BwLBgNQA6/X28YjhtQDocP5Rik75C8B5BwLBgNQA6/X28Yjg WYjMi/DD6Mr/Bo5G/iaKBAe0AOkP/v928otG9olG8jP2Msnol/20B80hPC11CwrJdfH+wehc/+vq PA11Do9G8ovGCsl0AvfY6dr9iMUsMDwJd9C0AFCwCvfmC9JadcT2xIB1vwHC9saAdbiJ1ojo6CH/ 66//dvKLRvaJRvLoPf20B80hPCBy+FDoB/9YtACPRvLpkP3GRvoBwysAAy0IAyoQAy8YAyUhAyEs A2A6Az5IAzxXA15mA3ZuAz92A19QA3xfAyLoAjqaA1yjAySvAy61AywKBCMTBHAZBGddBCZtBH7L BEDsBCB/AgB/Av8xJDIkMyQ0JDUk ``` On startup, the display shows the program. Commands are: * r - runs the program (switches to output screen) * s - single steps the program * q - quits the interpreter * 1 - shows output screen (white cursor is current output position) * 2 - shows program screen (red cursors is current program position) When an input command is executed, the display switches to the output screen. Input is echoed to the output screen. For ascii input, only characters in the range 32-255 are accepted. For numeric input, only values in the range -32768 to 32767 are allowed, press enter to complete input (sorry, no backspace). I really should add a stack screen as well. **Update** Here's the original assembly source code, assembled using A86. It's quite long: ``` enter 64,0 xor di,di mov ax,ds add ah,10h mov [bp-2],ax ; program mov [bp-14],ax ; current display add ah,10h mov w[bp-22],di ; stack off mov [bp-20],ax ; stack seg mov w[bp-6],di ; exit status mov w[bp-8],di ; size of field -8=lines,-7=columns mov w[bp-12],di ; output window position add ah,10h mov w[bp-10],ax; output segment mov w[bp-24],MoveRight ; clear output mov es,ax xor ax,ax mov cx,8000h rep stosw ; random seed mov ah,2ch int 21h mov w[bp-16],dx ; get filename mov dx,StrNoFile mov bl,[80h] xor bh,bh sub bl,1 jge NoError Error: call ClearScreen mov ah,9 int 21h leave ret NoError: ; open file mov b[82h+bx],0 mov ax,3d00h mov dx,82h int 21h mov dx,StrBadFile jc Error mov bx,ax ; clear program mov es,[bp-2] mov cx,8000h xor ax,ax rep stosw ; read file ReadLoop: mov cx,1 mov dx,EOP mov ah,3fh int 21h mov dx,StrBadRead jc Error or ax,ax jz EOF mov al,b[EOP] cmp al,10 je EOL cmp al,32 jb ReadLoop stosb jmp ReadLoop EOL: mov ax,di cmp al,[bp-7] jb l9 mov [bp-7],al l9: inc b[bp-8] and di,0ff00h add di,100h jmp ReadLoop EOF: mov ah,3eh int 21h or di,di mov dx,StrEmptyFile jz Error ; initialise mov ax,3 int 10h xor bx,bx ; PC ; execute Redraw: call DisplayProgram WaitForInput: mov ah,7 int 21h cmp al,'q' je Quit cmp al,'r' je DoRun cmp al,'1' je ShowIO cmp al,'2' je ShowProgram cmp al,'s' jne WaitForInput ; single step call Execute jmp Redraw ShowIO: mov ax,[bp-10] mov [bp-14],ax jmp Redraw ShowProgram: mov ax,[bp-2] mov [bp-14],ax jmp Redraw DoRun: mov ax,[bp-10] mov [bp-14],ax call DisplayProgram call Execute cmp b[bp-6],0 je DoRun jmp Redraw Quit: call ClearScreen leave ret ClearScreen: mov ax,0b800h mov es,ax mov ax,720h mov cx,8000h rep stosw ret DisplayProgram: pusha push ds mov ds,[bp-14] mov ax,0b800h mov es,ax mov ch,25 xor di,di xor si,si mov ah,7 l1: mov cl,80 l2: lodsb stosw dec cl jnz l2 add si,256-80 dec ch jnz l1 push bx mov ax,[bp-14] cmp ax,[bp-2] mov dl,0cfh je l33 mov bx,[bp-12] mov dl,0f0h l33: cmp bl,80 jae l3 cmp bh,25 jae l3 mov al,bh mov ah,160 mul ah add al,bl adc ah,0 add al,bl adc ah,0 mov di,ax inc di mov al,dl stosb l3: pop bx pop ds popa ret Execute: mov es,[bp-2] mov al,es:[bx] cmp al,'0' jb NotPush cmp al,'9' ja NotPush ; push number mov ah,0 sub al,'0' PushValueUpdatePC: call PushValue UpdatePC: jmp [bp-24] MoveLeft: or bl,bl jnz MoveLeftNoWrap mov bl,[bp-7] MoveLeftNoWrap: dec bl ret MoveRight: inc bl cmp bl,[bp-7] jne ret xor bl,bl ret MoveUp: or bh,bh jnz MoveUpNoWrap mov bh,[bp-8] MoveUpNoWrap: dec bh ret MoveDown: inc bh cmp bh,[bp-8] jne ret xor bh,bh ret PushValue: push es les di,[bp-22] stosw mov [bp-22],di pop es ret PopValue: push es les di,[bp-22] xor ax,ax or di,di jz PopValueZero sub di,2 mov ax,es:[di] mov [bp-22],di PopValueZero: pop es ret NotPush: mov si,Functions-3 NextFunction: add si,3 FindFunction: cmp b[si],255 je Endsearch cmp b[si],al jne NextFunction mov ax,[si+1] or ax,ax je EndSearch jmp ax ret EndSearch: mov dx,StrEndSearch jmp Error DoStringMode: call UpdatePC mov al,es:[bx] cmp al,'"' je UpdatePC mov ah,0 call PushValue jmp DoStringMode PopTwoValues: call PopValue mov cx,ax jmp PopValue DoAdd: call PopTwoValues add ax,cx jmp PushValueUpdatePC DoSub: call PopTwoValues sub ax,cx jmp PushValueUpdatePC DoMultiply: call PopTwoValues imul cx jmp PushValueUpdatePC DoDivide: call PopTwoValues cwd idiv cx jmp PushValueUpdatePC DoModulo: call PopTwoValues cwd idiv cx mov ax,dx jmp PushValueUpdatePC DoNot: call PopValue or ax,ax mov ax,1 jz DoNotZero dec ax DoNotZero: jmp PushValueUpdatePC DoGreaterThan: call PopTwoValues cmp ax,cx mov ax,1 jg DoGreaterThanIs1 dec ax DoGreaterThanIs1: jmp PushValueUpdatePC DoMoveRight: mov [bp-24],MoveRight jmp UpdatePC DoLeftRight: call PopValue or ax,ax jz DoMoveRight DoMoveLeft: mov [bp-24],MoveLeft jmp UpdatePC DoMoveUpDown: call PopValue or ax,ax jz DoMoveDown DoMoveUp: mov [bp-24],MoveUp jmp UpdatePC DoMoveDown: mov [bp-24],MoveDown jmp UpdatePC DoRandomDirection: mov ax,[bp-16] mov dx,31821 mul dx add ax,13849 mov [bp-16],ax and al,6 add ax,Movements mov si,ax lodsw mov [bp-24],ax jmp UpdatePC Movements: dw MoveUp, MoveDown, MoveLeft, MoveRight DoDuplicate: call PopValue call PushValue jmp PushValueUpdatePC DoSwap: call PopTwoValues xchg ax,cx call PushValue mov ax,cx jmp PushValueUpdatePC DoPop: call PopValue jmp UpdatePC DoPopPrint: call PopValue or ax,ax jns Positive neg ax push ax mov al,'-' call PrintChar pop ax Positive: push bx mov bx,EOP DivLoop: xor dx,dx mov cx,10 div cx add dl,'0' mov [bx],dl inc bx or ax,ax jnz DivLoop PrintLoop: dec bx mov al,[bx] call PrintChar cmp bx,EOP jne PrintLoop pop bx jmp UpdatePC PrintChar: cmp al,10 je AsciiCR push es les di,[bp-12] stosb mov ax,di cmp al,80 jne NoLF add di,256-80 NoLF: mov [bp-12],di pop es ret AsciiCR: mov b[bp-12],0 inc b[bp-11] ret DoPopAsciiPrint: call PopValue call PrintChar jmp UpdatePC DoTrampoline: call UpdatePC jmp UpdatePC DoPut: call GetCoord call PopValue push es mov es,[bp-2] mov es:[si],al pop es jmp UpdatePC GetCoord: call PopValue mov cl,[bp-8] DoGet1: or ax,ax jns DecrementY add al,cl adc ah,0 jmp DoGet1 DecrementY: div cl mov cl,ah mov ch,0 call PopValue ; x push cx mov cl,[bp-7] DoGet2: or ax,ax jns DecrementX add al,cl adc ah,0 jmp DoGet2 DecrementX: div cl mov al,ah pop cx ; ax=x, cx=y mov ah,cl mov si,ax ret DoGet: call GetCoord push es mov es,[bp-2] mov al,es:[si] pop es mov ah,0 jmp PushValueUpdatePC DoInput: push [bp-14] mov ax,[bp-10] mov [bp-14],ax xor si,si xor cl,cl DoInput1: call DisplayProgram mov ah,7 int 21h cmp al,'-' jne DoInputEnter or cl,cl jnz DoInput1 inc cl call PrintChar jmp DoInput1 DoInputEnter: cmp al,13 jnz DoInputDigit pop [bp-14] mov ax,si or cl,cl jz DoInput3 neg ax DoInput3: jmp PushValueUpdatePC DoInputDigit: mov ch,al sub al,'0' cmp al,9 ja DoInput1 mov ah,0 push ax mov al,10 mul si or dx,dx pop dx jnz DoInput1 test ah,80h jnz DoInput1 add dx,ax test dh,80h jnz DoInput1 mov si,dx mov al,ch call PrintChar jmp DoInput1 DoInputAscii: push [bp-14] mov ax,[bp-10] mov [bp-14],ax call DisplayProgram DoInputAscii1: mov ah,7 int 21h cmp al,32 jb DoInputAscii1 push ax call PrintChar pop ax mov ah,0 pop [bp-14] jmp PushValueUpdatePC DoExit: mov b[bp-6],1 ret Functions: db '+' ; Addition: Pop a then b, push a+b dw DoAdd db '-' ; Subtraction: Pop a then b, push b-a dw DoSub db '*' ; Multiplication: Pop a then b, push a*b dw DoMultiply db '/' ; Integer division: Pop a then b, push b/a, rounded down. If a is 0, result is undefined dw DoDivide db '%' ; Modulo: Pop a then b, push the remainder of the integer division of b/a. If a is 0, result is undefined dw DoModulo db '!' ; Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0. dw DoNot db '`' ; Greater than: Pop a then b, push 1 if b>a, otherwise 0. dw DoGreaterThan db '>' ; Start moving right dw DoMoveRight db '<' ; Start moving left dw DoMoveLeft db '^' ; Start moving up dw DoMoveUp db 'v' ; Start moving down dw DoMoveDown db '?' ; Start moving in a random cardinal direction dw DoRandomDirection db '_' ; Pop a value; move right if value=0, left otherwise dw DoLeftRight db '|' ; Pop a value; move down if value=0, up otherwise dw DoMoveUpDown db '"' ; Start string mode: push each character's ASCII value all the way up to the next " dw DoStringMode db ':' ; Duplicate value on top of the stack dw DoDuplicate db '\' ; Swap two values on top of the stack dw DoSwap db '$' ; Pop value from the stack dw DoPop db '.' ; Pop value and output as an integer dw DoPopPrint db ',' ; Pop value and output as ASCII character dw DoPopAsciiPrint db '#' ; Trampoline: Skip next cell dw DoTrampoline db 'p' ; A "put" call (a way to store a value for later use). Pop y then x then v, change the character at the position (x,y) in the program to the character with ASCII value v dw DoPut db 'g' ; A "get" call (a way to retrieve data in storage). Pop y then x, push ASCII value of the character at that position in the program dw DoGet db '&' ; Input an integer (may be multiple characters and may be negative) and push it dw DoInput db '~' ; Input a single character from stdin and push its ASCII value dw DoInputAscii db '@' ; End program dw DoExit db ' ' ; NOP dw UpdatePC db 0 ; NOP dw UpdatePC db 255 StrNoFile: db "1$";"No File$" StrBadFile: db "2$";"Bad File$" StrBadRead: db "3$";"Bad Read$" StrEmptyFile: db "4$";"Empty File$" StrEndSearch: db "5$";"Bad Instruction$" EOP: ``` [Answer] # C (gcc), ~~853 815 801 787 770~~ 748 bytes ``` #define z(a,b);a(){b;} #define Q s[1] #define Z*--s S[1<<20],*s=S,x,y,m,r,c=-1,t;M[25][80]z(b,*s=!*s)z(G,m=1)z(k,c+=x;r+=y)z(H,Z)z(E,Z%=Q)z(K,scanf("%d",++s))z(B,Z*=Q)z(A,Z+=Q)z(i,putchar(*s--))z(a,Z-=Q)z(I,printf("%d ",*s--))z(d,Z/=Q)z(g,1[s++]=*s)z(L,x=-1;y=0)z(R,x=1;y=0)z(w,t=Z;*s=*++s;*s=t;)z(U,x=0;y=-1)z(h,*s--?L():R())z(e,Z=*s>Q)z(J,*s=M[1[--s]][*s])z(j,M[*s][2[s-=3]]=Q)z(D,x=0;y=1)z(v,*s--?U():D())z(l,read(0,++s,1))(*f[])()={[33]=b,G,k,H,E,K,[42]=B,A,i,a,I,d,[58]=g,0,L,0,R,[92]=w,0,U,h,e,['g']=J,['p']=j,['v']=D,['|']=v,0,l}z(F,f["><^v"[rand()&3]]())main(C,V)int**V;{for(t=open(V[1],0);read(t,&C,1);)C-10?M[y][x++]=C:(x=!++y);for(R(f[63]=F);m|t-64;m?t-34?*++s=t:(m=0):t>47&t<58?*++s=t-48:f[t]&&f[t]())t=M[r=(r+y+25)%25][c=(c+x+80)%80];} ``` [Try it online!](https://tio.run/##jVNtU5tAEP7OrzjPJj1gUUhiGyGHrdHaF1OndvQDN9ghQBA1JAOXmGj97XaP@NZxOtObgd3bfe7Z55ZlGFXn93Eke739owHxh6Pt9kZ8v56ko7xIyQ2LYKh7EdNvh96d9hj@QSrhhE/bwLCsSvspnF6vZYdgVPwnLGAJYygh5pYD0huI1lYounZ4w4YKsGZU@g07gDF30F5CbPKFV5p8ibvPEOB7H4IG/4HON6jiqBgx2kgomGalY2wXAqNOfoTArJ0cpjMZn0clMyrLUpgIAqtOfYFpmReyZiAUHvMJBJt1PgNHVKYZ8lrTISxQsrfkNm6OcfPoX4PkgYfaDRShrPQweoIIGxGWusd5Tb5zyHT3mKkaKQTI6qsqX9W1B8IR2KswFEYVYvACBsoTLVFZvB2GtZ69B0rFOF8xniDjXs14BWUaJcxWnQBH15kxEqHOdH4r2u2QD@EALuEz7MM3EJ1WyHfhI@QQwRdIQGx1Q56BDYf4HIPYxvw1uidwDimIt9nbkH9FO0V7gXaOdg/tb7RzxF3d3bBPMBLU753NqSijImF6E2WjsnGUF6wPpzp22jBOvdvRpGSST6ZpwU5xWMDWvVq5hGYfhXt633LsnYFYhmKhmt932YKvmeZS99TRYzYS7/BCn3Rv/Fta7zreeEda7c6O6j6XLhvjR3Gl33nflL2t7kPY6nTdkZBhs6neKEtiy0vOSnNptrb0hhrCmLPYXJhdW2/gPHp39zj4WhyT1egTa1J7RHv@KWRayQ0V1BzLzlwaUGt9/uvNtmPSahqV10TOppsyPaC@uw6/3pC/15z8cwXas@@7lDzzpnE0rUhVlDOZlkSmGdk9Onrgn2uvKH2b/gO8gWxQQzS/65qu4ThTx8mwjioj8yHpkiQtsryitmOtkmuYpcWM@pSkZUSqq6u0v6LD0i9r@08cCH21/Pp99jquTl2Wk2tCybr2AFNx7OZ4dkHSLNlflcPgM9buWO2GY6K2FwfKNCnyaIzXTue5jDI613wqJwWZ4K9@Rv5rvTig0fT7Y@n689al02Qyzoq8lBUpcvJhBfjwX9SapqZrY7Meqac5uv8D "Bash – Try It Online") The program is loaded into an array and the interpreter enters the main loop; the byte at the current program counter is the offset of an array of function pointers, each function performs the operation required by that instruction. String mode and numeric literals are special cases that are handled differently. Slightly golfed less ``` S[1<<20],*s=S,x,y,m,r,c=-1,t,M[25][80]; b(){*s=!*s;} /* ! */ G(){m=1;} /* string mode */ k(){c+=x;r+=y;} /* # */ H(){s--;} /* $ */ E(){*--s%=s[1];} /* % */ K(){scanf("%d",++s);} /* & */ B(){*--s*=s[1];} /* * */ A(){*--s+=s[1];} /* + */ i(){putchar(*s--);} /* , */ a(){*--s-=s[1];} /* - */ I(){printf("%d ",*s--);} /* . */ d(){*--s/=s[1];} /* / */ g(){1[s++]=*s;} /* : */ L(){x=-1;y=0;} /* < */ R(){x=1;y=0;} /* > */ w(){t=*--s;*s=*++s;*s=t;} /* \ */ U(){x=0;y=-1;} /* ^ */ h(){*s--?L():R();} /* _ */ e(){*--s=*s>s[1];} /* ` */ J(){*s=M[1[--s]][*s];} /* g */ j(){M[*s][2[s-=3]]=s[1];} /* p */ D(){x=0;y=1;} /* v */ v(){*s--?U():D();} /* | */ l(){*++s=getchar();} /* ~ */ (*f[])()={[33]=b,G,k,H,E,K,[42]=B,A,i,a,I,d,[58]=g,0,L,0,R,[92]=w,0,U,h,e,['g']=J,['p']=j,['v']=D,['|']=v,0,l}; F(){f["><^v"[rand()&3]]();} /* ? */ main(C,V)int**V;{ /* load */ for(t=open(V[1],0);read(t,&C,1);) C-10?M[y][x++]=C:(x=!++y); /* execute */ for(R(f[63]=F);m|t-64;m?t-34?*++s=t:(m=0):t>47&t<58?*++s=t-48:f[t]&&f[t]()) t=M[r=(r+y+25)%25][c=(c+x+80)%80]; } ``` [Answer] ## Delphi, 970 842 Since I did the Fish golf first, I just copied that and changed the interpretation to use Befunge-93 specs (which are simpler than Fish) so I mainly had to strip things away. In the next revision I won 64 characters by implementing the movement code using 2 instead of 4 variables. Oh, and I inverted the stack, removing the need for a length variable. Another nice win is the '?' (random direction) instruction - I just change it into one of the four directions and let them handle it. ``` const X=80;var f:TextFile;c,s:String;i,p,d,A:Int16;procedure U(v:Int8);begin s:=Chr(v)+s;end;function O:Int8;begin if s=''then Exit(0);O:=Ord(s[1]);Delete(s,1,1)end;procedure E;begin i:=(p div X)+(d div X);p:=i*X+(p+d)mod X;i:=Ord(c[1+p])end;begin Assign(f,ParamStr(1));Reset(f);for A:=1to 26do begin ReadLn(f,s);c:=c+s+StringOfChar(' ',X-Length(s))end;d:=1;p:=-d;repeat E;A:=i;case i-32of1,63,92:A:=Ord(O=0);2:repeat E;U(i)until i=A;5,15,26,60:A:=O;31:i:=Ord('<>^v'[1+Random(4)]);71,80:A:=X*O+O+1;6:Read(A);94:Read(PChar(@A)^)end;if i=58then U(A);case i-32of 16..25:U(i-48);11:U(O+O);13:U(-O+O);10:U(O*O);15:U(O div A);5:U(O mod A);64:U(Ord(O<O));28,30:d:=i-61;62:d:=-X;86:d:=X;63:d:=2*A-1;92:d:=2*A*X-X;2,4:O;60:s:=Chr(O)+Chr(A)+s;14:Write(O,' ');12:Write(Chr(O));3:E;80:c[A]:=Chr(O);71:U(Ord(c[A]));32:Exit;1,6,26,94:U(A)end;until 0=1;end. ``` Here the indented and commented code : ``` {debug}uses Windows;{} const X=80; var // f is the source file f:TextFile; // c is the entire codebox (a 2-dimensional program) c, // s is the stack (kept as a string) s:String; // i is the current instruction read from the program i, // p is the position in the program p, // d is the delta for each step d, // A is a temporary variable (only uppercase var, to coincide with comments) A :Int16; procedure U(v:Int8); // PUSH begin // Push value onto the stack: s:=Chr(v)+s; end; function O:Int8; // POP begin // Pop value from the stack : if s=''then Exit(0); O:=Ord(s[1]); Delete(s,1,1) end; procedure E; // STEP begin //{debug}Sleep(3);{} // Note : x-step needs to stay on same line, y-step needs to stay on same column i:=(p div X)+(d div X); // i:=i mod 25;// Enable this to wrap y-edge too p:=i*X+(p+d)mod X; i:=Ord(c[1+p]) end; begin // Open file given at the command-line, and read & expand it's lines into our program buffer : Assign(f,ParamStr(1)); Reset(f); for A:=1to 26do begin ReadLn(f,s); c:=c+s+StringOfChar(' ',X-Length(s)) {debug};SetLength(c,A*X) end; // s:=''; Since we read 1 line too many above, s should always be empty now d:=1; p:=-d; repeat // Take a step (which gives a new 'i'nstruction) and make a copy of the stack : E; // Prevent begin+end pairs by handling instructions in 3 consecutive case blocks; This is applied to // all situations where this saves 1 or more characters, justifying the cost for another case-block. // Shorten '"' (>2) string-collecting, by remembering the quote character in A : A:=i; // Shorten a few cases by preparing variables so they can be shared with eachother and the 3rd case-block below : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! // Shorten '!' (>1), '_' (>63) and '|' (>92), by remembering Ord(O=0) in A : 1,63,92:A:=Ord(O=0); // Shorten '"' string-collecting, by pushing the entire string here (the opening quote was remembered in A) : 2:repeat E;U(i)until i=A; // Note : We stop at the closing character, so the next block will still handle 'i'! // These instructions all need to Pop A, so write it just once here : 5,15,26,60:A:=O; // Shorten '?' (>31): Choose a random direction instruction and let the 3rd case-block handle it : 31:i:=Ord('<>^v'[1+Random(4)]); // Shorten 'g' (>71) and 'p' (>80): Calculate A so that the 3rd case-block doesn't need a begin+end pair : 71,80:A:=X*O+O+1; // Note : This assumes Delphi evaluates leftmost call to O first! // Shorten '&' by reading a number from the input into A : 6:Read(A); // Shorten '!' Prevent begin+end for input retrieval, by reading the input into A here : 94:Read(PChar(@A)^) // Note : This case is last, because it ends on ')', which avoids a closing ';' end; // Shorten ':' (>58-32=26): Share implementation with '&' (>6) and '~' (>94) by pushing first copy of A (read above) here if i=58then U(A); // This 3rd case-block contains the final code for all statements : case i-32of // Note : The instruction is decreased by 32, resulting in less digits in the cases below! //'0'..'9': Push this number on the stack 16..25:U(i-48); //'+': Addition: Pop A then B, push A+B 11:U(O+O); // Note : A and B are inverted, but order is irrelevant here //'-': Subtraction: Pop A then B, push B-A 13:U(-O+O); // Note : Delphi evaluates left-to-right, so we need to reverse the operation //'*': Multiplication: Pop a then b, push a*b 10:U(O*O); // Note : A and B are inverted, but order is irrelevant here //'/': Integer division: Pop A then B, push B/A, rounded down. If A is 0, result is undefined 15:U(O div A); // if A=0then U(0)else U(O mod A); //'%': Modulo: Pop A then B, push the remainder of the integer division of B/A. If a is 0, result is undefined 5:U(O mod A); // if A=0then U(0)else U(O mod A); //'`': Greater than: Pop A then B, push 1 if B>A, otherwise 0. 64:U(Ord(O<O)); // Note : Delphi evaluates left-to-right, so we need to reverse the test //'<': Start moving left //'>': Start moving right 28,30:d:=i-61; //'^': Start moving up 62:d:=-X; //'v': Start moving down 86:d:=X; //'_': Pop a value; move right if value=0, left otherwise 63:d:=2*A-1; // Note : A is already determined as Ord(O=0) in 1st case block //'|': Pop a value; move down if value=0, up otherwise 92:d:=2*A*X-X; // Note : A is already determined as Ord(O=0) in 1st case block //'"': Start string mode: push each character's ASCII value all the way up to the next " //'$': Pop value from the stack 2,4:O; //'\': Swap two values on top of the stack 60:s:=Chr(O)+Chr(A)+s; // Note : A was Popped in 1st case block //'.': Pop value and output as an integer 14:Write(O,' '); //',': Pop value and output as ASCII character 12:Write(Chr(O)); //'#': Trampoline: Skip next cell 3:E; //'p': A "put" call (a way to store a value for later use). Pop y then x then v, change the character at the position (x,y) in the program to the character with ASCII value v 80:c[A]:=Chr(O); // Note : A was Popped in 1st and 2nd case block, calculating y*width+x //'g': A "get" call (a way to retrieve data in storage). Pop y then x, push ASCII value of the character at that position in the program 71:U(Ord(c[A])); // Note : A was Popped in 1st and 2nd case block, calculating y*width+x //'@': Rotates the top 3 values on the stack clockwise, respectively. (eg. if your stack is 1,2,3,4, would result in 1,4,2,3) 32:Exit; //'!': Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0. //'&': Input a number from stdin and push its value //':': Duplicate value on top of the stack //'~': Input a single character from stdin and push its ASCII value 1, // Note for '!' : A is already determined as Ord(O=0) in 1st case block 6, 26, // Note for ':' : First A was already pushed once above 94:U(A) // Note for '~' : Read() into A was done in 1st case block end; until 0=1; end. ``` Output from compat.bf : ``` OOB get returns 0 Cells are unsigned 8 bit Edge jumps work Negative remainders work @ in stringmode works ``` Output from b93 : ``` ` works : works 0-9 probably work $ works Westwards edge jump arrives at 79 0! is 1 5! is 0 ``` Edit history: (970-64=906) : Reimplemented movement, using 2 instead of 4 variables (906-9=897) : Moved more calculations into 1st and 2nd case-blocks (897-11=886) : Skip intermediate variable for all double-pop instructions (886-6=880) : Read 1 input line extra to clear 's'tack (880-14=866) : Simplified '?' by changing it into one of the 4 direction-instructions (866-8=858) : Removed one case block (858-13=845) : Fixed edge-jump, simplifying direction handling. Use 8 bit stack. (845-3=842) : Combined left-right direction instruction into a single expression ]
[Question] [ Recently a friend of mine posed the following: > > What subset of the integers satisfies the condition if distinct a and b are in the subset, their average is not in the subset? I know the set of non-0 squares satisfies the condition, but I wonder if there exists a more... dense set that satisfies the condition. > > > (It turns out my friend was wrong about "the set of non-0 squares satisfies the condition", just ignore that.) Now, I thought I could turn this into a coding challenge. The goal of this challenge is to submit a function \$f: \mathbb{N} \to \{\top, \bot\}\$ which takes in a positive integer and returns a boolean satisfying the conditions in the "Rules" section. Your score is the length of your program in bytes. Program \$A\$ is better than program \$B\$ if \$A\$ is shorter than \$B\$. # Rules * For any distinct \$a, b\$ so that \$f(a)\$ is true, \$f(b)\$ is true and \$a+b\$ is even, then \$f(\frac{a+b}{2})\$ is false. * Let \$e: \mathbb{N} \to \mathbb{N}\$ be defined as \$e(x) = \text{the } x^{\text{th}} \text{ number so that } f(x) \text{ is true}\$. Then, there exists some \$m\$ so that \$e(n) < n^2\$ for all \$n \geq m\$. * The set \$\{a: f(a) \text{ is true}\}\$ is infinite, i.e. you can't make \$f\$ hold for only finitely many values. # Leaderboard 1. [allxy](https://codegolf.stackexchange.com/users/110449/allxy) - [4 bytes (Jelly)](https://codegolf.stackexchange.com/a/246026/108434) 2. [Neil](https://codegolf.stackexchange.com/users/17602/neil) - [6 bytes (Charcoal)](https://codegolf.stackexchange.com/a/246032/108434) 3. [m90](https://codegolf.stackexchange.com/users/104752/m90) - [10 bytes (x86 32-bit machine code)](https://codegolf.stackexchange.com/a/246127/108434) 4. [m90](https://codegolf.stackexchange.com/users/104752/m90) - [12 bytes (Re:direction)](https://codegolf.stackexchange.com/a/248195/108434) 5. [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) - [15 bytes (BQN)](https://codegolf.stackexchange.com/a/246071/108434) 6. [knomologs](https://codegolf.stackexchange.com/users/112018/knomologs) - [20 bytes (МК-52/МК-61)](https://codegolf.stackexchange.com/a/246331/108434) 7. [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha) - [22 bytes (PARI/GP)](https://codegolf.stackexchange.com/a/246037/108434) 8. [chunes](https://codegolf.stackexchange.com/users/97916/chunes) - [23 bytes (Factor + `math.unicode`)](https://codegolf.stackexchange.com/a/246052/108434) (tied with #8) 9. [G B](https://codegolf.stackexchange.com/users/18535/g-b) - [23 bytes (Ruby)](https://codegolf.stackexchange.com/a/246059/108434) (tied with #7) 10. [Neil](https://codegolf.stackexchange.com/users/17602/neil) - [26 bytes (Retina 0.8.2)](https://codegolf.stackexchange.com/a/246051/108434) 11. [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) - [28 bytes (JavaScript ES6)](https://codegolf.stackexchange.com/a/246035/108434) 12. [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt) - [31 bytes (Python 2)](https://codegolf.stackexchange.com/a/246031/108434) 13. [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt) - [33 bytes (Python)](https://codegolf.stackexchange.com/a/246031/108434) 14. [solid.py](https://codegolf.stackexchange.com/users/110265/solid-py) - [50 bytes (Python 3.6)](https://codegolf.stackexchange.com/a/246030/108434) 15. [friddo](https://codegolf.stackexchange.com/users/111021/friddo) - [68 bytes (Python 3.8)](https://codegolf.stackexchange.com/a/246029/108434) 16. [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) - [110 bytes (Whitespace)](https://codegolf.stackexchange.com/a/246060/108434) [Answer] A simple greedy approach gives the set `[1, 2, 4, 5, 10, 11, 13, 14...]`. This is probably optimal. It can be constructed by: * Start with the set `[1]` * Forever: + Take the maximum value of the set, double it, and subtract 1 + Add that to each value of the set + Append that to the current set [Here](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxdyA/KCBEIEcgZOKAuStKIiwiIiwiNSJd)'s an example program to do this. After a bit of digging on OEIS, we find that the sequence we're looking for is [A003278](http://oeis.org/A003278). A more convenient way of constructing this set is to use one of the definitions on said OEIS page - [Try it Online!](https://vyxal.pythonanywhere.com/#WyI1IiwiIiwiw57iiJ7igLliM3bOsuKAuiIsIiIsIjUiXQ==) This one takes the infinite list of nonnegative integers, converts each to binary and from ternary, and increments them. This definition is really easy to implement as a check. We simply check that (n-1) in ternary contains no twos. The sequence plus or minus any constant has the same properties so we can check if n in ternary contains no twos. Thanks to Jonathan Allan for this insight, saving a byte on both versions. Finally: # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` 3τ2<A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIzz4QyPEEiLCIiLCI1Il0=) ``` 3τ # Convert to base 3 A # Are all elements 2< # Less than 2? ``` Jelly has a convenient builtin for this which saves a byte: # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` b3ỊȦ ``` [Try it online!](https://tio.run/##y0rNyan8/z/J@OHurhPL/pscbv8PAA "Jelly – Try It Online") ``` b3 # Convert to base 3 Ȧ # Are all elements Ị # Less than two? ``` [Answer] # [Python 2](https://docs.python.org/2/), 27 bytes ``` f=lambda n:n>n%3/2>-f(n/3) ``` [Try it online!](https://tio.run/##JYvNDoIwGATvPMVeTNqAUssNhRchHL4GqyR1IU0vPn3l5zabnVl/6bPQ5uy7IF83Cdiy56WpbX/1inWjkUM3jIVfIoiZiML3S92NMbotMHtwSdhU3WKNMxP4CGXHqjjXoKRyGnsuex4OdCdutTwdhBOUlE7X9nYcY/4D "Python 2 – Try It Online") Swaps True and False. ### [Python 2](https://docs.python.org/2/), 29 bytes (@xnor) ``` f=lambda n:n<1or n%3<2*f(n/3) ``` [Try it online!](https://tio.run/##JYtLDoMgFEXnrOJOmkA1FXFGYSXGwSOW1oQ@DXHS1VPR2bmfs/32z8qmlOgTfcNMYMuuXzP4Njhzj5K7QZXkx0nE2mJhZOL3S/Zaa2UFlojjpSy2vPAOfqbGcyuuNEpqg0JVqarpxHDhYZILIJ4hqQmqM49zmMof "Python 2 – Try It Online") Thanks to @Jonathan Allan for convincing me that @xnor's switching to [A005836](http://oeis.org/A005836) (without its first element) is actually perfectly good. ### [Python 2](https://docs.python.org/2/), 31 bytes (@KevinCruijssen) ``` f=lambda n:n<2or n%3>0<f(n/3+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboW-9NscxJzk1ISFfKs8myM8osU8lSN7Qxs0jTy9I21DTUhqm6qFBRl5pVoRGdqpWlkaqYBlWUqZOYpFCXmpadqGOoYGhhoxkLVwkwGAA) Improved logic is inspired by @alephalpha's [PARI/GP answer](https://codegolf.stackexchange.com/a/246037/107561). Could save another two bytes by allowing any nonzero value for True. ### [Python](https://www.python.org), 33 bytes ``` f=lambda n:n<2or n%3and f(n//3+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3FdNscxJzk1ISFfKs8myM8osU8lSNE_NSFNI08vT1jbUNNaEKVQuKMvNKNLQ0MrXSNDI104AqMxUy8xSKEvPSUzUMdQwNDDQ1oYphpgMA) Uses the base 3 characterisation at [OEIS](http://oeis.org/A003278). Returns 0 and True. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~7~~ 6 bytes ``` ›²⌈↨N³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIw0hHwTexIjO3NFfDKbE4VcMzr6C0xK80Nwkop6mjYKwJBNb//xuZ/dctywEA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` if the input is a member of A005836, nothing if not. Explanation: Another port of @allxy's solution. ``` ² Literal integer `2` › Is greater than ⌈ Maximum of N Input number ↨ Converted to base ³ Literal integer `3` Implicitly print ``` Previous 7-byte version: ``` ›2⌈⍘⊖N³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIQ8lISUfBN7EiM7c0V8MpsTg1uAQon67hkppclJqbmleSmqLhmVdQWuJXmpsEVK@pqaNgrAkE1v//G5n/1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` if the input is a member of A003278, nothing if not. Explanation: ``` 2 Literal characater `2` › Is greater than ⌈ Maximum of N Input integer ⊖ Decremented ⍘ Converted to base ³ Literal integer `3` Implicitly print ``` String base conversion is used because array base conversion returns an empty array for an input of `1` (decremented) which has no maximum. A003278 is infinitesimally denser than A005836 because it effectively includes an extra element at the beginning, so given any finite integer, the number of terms in A003278 less than that integer is always at least as many as the number of terms in A005836 less than that integer, but I don't know whether A003278 always beats all other possible subsets in this way. [Answer] # Regex (or [Retina](https://github.com/m-ender/retina/wiki/The-Language)), 9 bytes ``` ^[0268]*$ ``` [Try it online!](https://tio.run/##K0otycxLNPz/Py7awMjMIlZL5f9/I1MA "Retina – Try It Online") For any two different numbers composed of 0, 2, 6, 8 in decimal, at any digit position where they differ, their average has 1, 3, 4, 5, or 7, and thus does not satisfy the condition. This condition includes asymptotically \$ 4^{log\_{10}n} = n^{log\_{10}4} \approx n^{0.602}\$ of the first \$n\$ numbers. [Answer] # JavaScript (ES6), 25 bytes A port of [loopy walt's answer](https://codegolf.stackexchange.com/a/246031/58563). [24 bytes](https://tio.run/##DcvBCoMwDADQX9lFTAZmqCdhCn7H8FBqKnUlkVYGgvjrne/@VvMzyUa/7ZXozDm7XvpB3s15StE@HVQXyKtFzFYlaWAKusCHiMYYzQFdh/TlIwFOlIK3DDWS82HnCA5pVS9QPsr7/wE) if we can return zero / non-zero. ``` f=n=>n<2||n%3&&f(-~(n/3)) ``` [Try it online!](https://tio.run/##DcvBCoMwDADQX/EyTQ5GNk@CCn6HeChdOupKIq0Igvjr3d79reYwyUa/7bXom3N2gwyj9K/rkkdblg7qG6RpEbNVSRqYgn5gJqIpRnNC1yF9@UyAC6XgLcMTyfmwcwSHtKoXqIrq/38 "JavaScript (Node.js) – Try It Online") [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 22 bytes ``` f(n)=n<2||f(n\3+1)*n%3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboW29I08jRt82yMamqArBhjbUNNrTxVY4jkTeWCosy8Eo1okCKFGoU8BRtdhWhDPT1DA4NYHQWQaKwmRCnMPAA) A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/246031/58563). [Answer] # Электроника [МК-52](http://www.rskey.org/mk52)/[МК-61](http://www.rskey.org/mk61), 20 bytes ``` X→П0 3 - Fx≥0 18 П→X0 3 ÷ K{x} Fx≠0 19 FBx K[x] 1 + X→П0 БП 01 1 С/П ``` or, in bytecode: ``` 40 03 11 59 18 60 03 13 35 57 19 0F 34 01 10 40 51 01 01 50 ``` Port of [loopyWalt's Python answer](https://codegolf.stackexchange.com/a/246031/52210). The MK-52 and MK-61 were the most advanced Soviet programmable calculators to use keystroke programming (later models, like the MK-85 and MK-90, had a form of BASIC). Despite looking more like macros than "real" programs, the language is actually Turing-complete. Each instruction occupies 1 byte in memory. Code-golfing was in fact very popular with these calculators in the 80s, because one had to fit the program in 104 bytes – however, even quite complex games were written with this limitation. [Online emulator here.](https://pmk.arbinada.com/mk61emuweb.html#_%D0%9C%D0%9A-61) Turn on the calculator (switch labeled Вкл), paste the above bytecode into the text area on the right and click "Ввести в память" ("Write to memory"). Input number into calculator and press В/О, then С/П to run program. Outputs 1 for true and 0 for false (not exactly quickly though...) [Answer] # [Re:direction](https://esolangs.org/wiki/Re:direction), 12 bytes ``` +++> v +> < ``` [Try it online!](https://tio.run/##K0rVTcksSk0uyczP@/9fW1vbjqtMAUgo2Pz/b2gBAA "Re:direction – Try It Online") Outputs by exit code, 0 for False and 1 (by queue underflow) for True. (This is a bit dubious; it matches the usual convention for numbers in general, but is the opposite of the convention normally used for exit codes.) The condition used is that the number consists only of 0s and 2s in ternary, which is another variation that also works. This program goes into an infinite loop on 0, which thankfully does not need to be handled. The following notation will be used for the contents of the queue: a number means that many `►`s, and `|` means one `▼`. If the input number is N, the initial queue is `N|`. The possibilities are as shown: [![Execution path for 3N](https://i.stack.imgur.com/0azFa.png)](https://i.stack.imgur.com/0azFa.png) [![Execution path for 3N+1](https://i.stack.imgur.com/i7lu9.png)](https://i.stack.imgur.com/i7lu9.png) [![Execution path for 3N+2](https://i.stack.imgur.com/4dsS6.png)](https://i.stack.imgur.com/4dsS6.png) [![Execution path for 2](https://i.stack.imgur.com/LHLYL.png)](https://i.stack.imgur.com/LHLYL.png) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 bytes ``` lambda n,s={1}:any(n in(s:=s|{a+max(s)*2-1for a in s})for _ in[0]*n) ``` [Try it online!](https://tio.run/##FclBCsIwEEDRvaeYXWdqC0Y3EogX0VJGNBqw05B0YYk5e2x27/P9urxnOZ19KNbcyoen@4NBumiSypplRQEnGLWJv8T7ib8YqT32ys4BeFsQM1WPm6@HoRUqNV1dgeX1RNUpRXoHPjhZ0DbJZegvkCw6yg2VPw "Python 3.8 (pre-release) – Try It Online") By no means the shortest solution, but a fun one! Builds up the set using the method described by @allxy's Jelly answer and checks if n is in it. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes ``` .+ $* +`^1?(1*)\1\1$ $1 ^$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSzshztBew1BLM8YwxlCFS8WQK07l/39DLiMuYy4TLlMuMy5zLgsuSwA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `1` if the input is a member of A005836, `0` if not. Explanation: ``` .+ $* ``` Convert to unary. ``` +` ``` Repeat as many times as possible... ``` ^1?(1*)\1\1$ $1 ``` ... integer divide by `3`, but only if the remainder is not `2`. ``` ^$ ``` Test to see whether it was possible to reach `0`. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 23 bytes ``` [ 1 - 3 >base "10"⊂ ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkgEm9AoSi4pTiyDs0rzM5PyUVIWCotSSksqCosy8EgVrLi7T/9EKhgq6CsYKdkmJxakKSoYGSo@6mhRi/ycn5uQo6P0HAA "Factor – Try It Online") Based on @allxy's Vyxal/Jelly [answers](https://codegolf.stackexchange.com/a/246026/97916). Subtract 1 from the input, convert it to base 3, but instead of checking whether each digit is less than two, check whether the result is a subset of `"10"` since that's shorter in Factor. [Answer] # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->n{(n-1).to_s(3)!~/2/} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNP11BTryQ/vljDWFOxTt9Iv/Z/gUK5rYahnp6hgYGmXnFqTmpyiYZamuZ/AA "Ruby – Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 110 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][N S S N _Create_Label_FUNC][S N S _Duplicate_input][S S S T S N _Push_2][T S S T _Subtract][N T T T N _If_negative_Jump_to_Label_TRUTHY][S N S _Duplicate_input][S S S T T N _Push_3][T S T T _Modulo][S S S N _Push_0][S N T _Swap_top_two][T S S T _Subtract][N T T S N _If_negative_Jump_to_label_CONTINUE][N N N _Exit_Program][N S S S N _Create_Label_CONTINUE][S S S T T N _Push_3][T S T S _Integer_divide][S S S T N _Push_1][T S S S _Add][N S N N _Jump_to_Label_FUNC][N S S T N _Create_Label_TRUTHY][S S S T N _Push_1][T N S T _Print_1_as_number] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Port of [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/246031/52210). Whitespace doesn't have any booleans, but this will output `1` for truthy and nothing for falsey (could also output `0` for falsey at the cost of 8 additional bytes). [**Try it online**](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QYALwgMCTgUuTgWIMEwEyAESEA2cUEkFLhAAi8FUgNVyQdWB5Di5ICJAW/7/NzQAAA) (with raw spaces, tabs and new-lines only). ### Explanation in pseudo-code: ``` Integer n = STDIN as number FUNC: If(n-2 is negative): Jump to TRUTHY If(0-(n%3-1) is negative): Jump to CONTINUE Exit program (falsey result) CONTINUE: n = n//3+1 Jump to FUNC TRUTHY: Print 1 as number to STDOUT (implicitly stop the program with an error stating 'no exit is defined') ``` [Answer] # x86 32-bit machine code, 10 bytes ``` 48 25 AA AA AA AA 0F 94 C0 C3 ``` [Try it online!](https://tio.run/##XZFdT8IwFIav119xnDG0bBCE6AUwE8O1N16ZiFm6rt2adB3ZOu0k/HVnNyAo56Ifz2nf8/aU7XaTjLGuu5WaqSblsK5NKstp/oT@ISWTa1ZJnfUMcWt4pcHf@LCPY2pcJmkMj2OMK57taFXge0IIsJxWILDUBihZHRCtC8Dw6mM0zVSZUAUCiSXyUs6AU4s8qtN@EcLMPp8CeTU330AV8ipuEPGBrBDqJQsq9VG7ylh4LDYeu80nQXsELvqkhQhmIbT9tBroVy4VBxwEFtYRzB8eyYCHCwKwwJZcSB8793AjsH8nwQ/BkqPMmW71C2W51BxYmfKlf0rbS8G0hP35NNzN5m9OpY0wbnQtM83TwfqYCPJug@DDNepssYUbJ2I3i6uSgJ2VpDW8Jlv911Jjeik82urRCbmeNe6rnJND1/0woWhWd5NiMXeD@47ICXL1Cw "C++ (gcc) – Try It Online") Uses the `regparm(1)` calling convention – argument in EAX, result in AL. This implements a slightly different criterion from the one most other answers use: n-1 consists of only 0s and 1s in base *4*. This still works, and barely satisfies the \$e(n) < n^2\$ condition; removing the subtraction of 1 would make it fail that condition. This modified criterion is simple to implement, by checking whether the odd-position bits in n-1 are all zero. In assembly: ``` f: dec eax and eax, 0xAAAAAAAA setz al ret ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html), ~~15~~ ~~14~~ 13 bytes *Edit: -1 byte thanks to Razetime* ``` ⌊´2-3|⊢⌊∘÷3⋆↕ ``` [Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyKwrQyLTN84oqi4oyK4oiYw7cz4ouG4oaVCijiiqLDl0YpwqggMSvihpU1MAo=) ``` ↕ # range from 0...input-1 3⋆ # get 3 to the power of those ⌊∘÷ # now use these to divide & floor (=integer division) ⊢ # the input 3| # get each one modulo 3 2- # subtract it from 2 ⌊´ # and find the minimum ``` The final ~~`2>·⌈´`~~ `⌊´2-` part seems a bit clunky to me (although now improved a bit): I'd want to be able to do something like `¬2∊` (NOT is `2` a member of), but unfortunately this returns an array which doesn't seem to work as a boolean. ]
[Question] [ [Github](https://github.com/Artemis21/guessers-and-liars) You have probably played, and may even have written a program to play, a simple number guessing game. If so, this probably looks familiar: ``` Try to guess my number (1 to 100)! Please enter a guess: 50 Too small, guess again! Please enter a guess: 75 Too big, guess again! Please enter a guess: 63 Correct! ``` (Obviously, it usually takes a little longer.) But what if your opponent *lied*? Or, to be more generous, isn't very good at comparing numbers. There are two parts to this challenge. ## 1: The liar * Your program will be passed a number between 0 and 255 inclusive. * Your program will be passed a guess, within the same bounds. * Your program should return one of -1 (the guess is smaller than your number), 0 (the guess *is* your number) or 1 (the guess is greater than your number). * You may store state for the duration of a single game. * You may return an inaccurate result (lie!) up to 8 times in a game. * If you return 0 when the guess is not equal to your number, your opponent will win anyway. However, you may chose not to return 0 even when the guess *is* equal to your number (this counts as one of your allotted lies). * Your aim is to delay returning 0 for as long as possible ("long" as in most calls to the program, not length of time, obviously). ## 2: The guesser * Your program will be passed a function to call. You should pass this function a guess, between 0 and 255. It will return -1 (indicating that you should guess lower), 0 (indicating that your guess was correct) or 1 (indicating that you should guess higher). * The function may return an inaccurate result up to 8 times in a single invocation of your program. * Your aim is to receive output of 0 from the function after calling it the fewest possible times. ## General notes * Once the liar has used up their allotted lies, the function passed to the guesser (henceforth "guess function") will simply begin returning the correct answer without invoking the liar. * The maximum number of guesses is 2304 (equivalent to trying every possible number 9 times). After this, the guess function will return 0 and end the game. * Practically, the guess function will never return 0, it will just end the game. So the guesser only needs to handle a return of -1 or 1. * The best guesser is the one that takes the fewest guesses to end the game. The best liar is the one that delays the end of the game for the greatest number of guesses. ## Submissions All submissions must be written in Python 3. Answers should use the following template: ``` # <type>: <name> <code> <description> ``` Where `<type>` is either `Liar` or `Guesser`. Every submission should define a callable called `Main` (this may be a class or function). For the liar, it should accept two parameters: an instance of `random.Random`, to generate any non-determinism needed, and an `int`, which is the secret to protect. It should return another callable, which accepts a guess (as an `int`) and returns `-1`, `0` or `1` (it is never advantageous to return `0`). The recommended way of implementing this is as a class, for example: ``` class Main: """Liar that always returns one.""" def __init__(self, rng: random.Random, secret: int): """Store the rng and secret even though we do nothing with them.""" self.rng = rng self.secret = secret def __call__(self, guess: int) -> int: """Return 1.""" return 1 ``` For the guesser, `Main` should also accept to arguments: an instance of `random.Random`, as above, and a callable (the guess function). For example: ``` def Main(rng: random.Random, liar: Callable[[int], int]): """Guess randomly.""" while True: liar(rng.randrange(256)) ``` Note that the function never needs to exit, this will be handled by the game runner. ## Latest Results ``` 10 repetitions with seed XHMS2Z: Top liars: ------------------------------------- tsh_equal_lie 499 mojo_black_one_big_lie 497 mojo_black_keep_away 486 qwatry_illusionist 485 sheik_yerbouti_the_liar_king 353 citty_mislead 346 spitemaster_look_over_there 341 leo_knave 99 Top guessers: ------------------------------------- user1502040_bayes_bot 26 mojo_black_phoenoix_wright 29 l4m2_fib_trust 30 tsh_most_correct_guess 30 att_top_median 32 sheik_yerbouti_no_matter_what 61 tsh_most_recent_guess 65 citty_pester 67 m_virts_binary_reset_gaussian 1528 m_virts_binary_reset 2015 Slowest submissions: ------------------------------------- m_virts_binary_reset_gaussian 0.0063s m_virts_binary_reset 0.0049s user1502040_bayes_bot 0.0028s l4m2_fib_trust 0.0021s tsh_most_recent_guess 0.0013s att_top_median 0.00089s tsh_most_correct_guess 0.00073s mojo_black_keep_away 0.00052s qwatry_illusionist 0.00042s mojo_black_one_big_lie 0.00042s tsh_equal_lie 0.00037s citty_pester 0.00018s citty_mislead 0.00016s sheik_yerbouti_no_matter_what 0.00016s spitemaster_look_over_there 0.00015s sheik_yerbouti_the_liar_king 0.00013s mojo_black_phoenoix_wright 0.0001s leo_knave 7.5e-06s 0 submissions were disqualified. ``` Congrats to tsh and user1502040 for topping the leaderboards! [Answer] # Guesser: phoenix\_wright ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): while liar(0) == -1: pass previous = {0:1} lb = 0 ub = 255 while True: while lb <= ub: g = (lb+ub)//2 if g in previous: r = previous[g] else: r = liar(g) if r == 1: lb = g+1 elif r == -1: ub = g-1 previous[g] = r k = g == ub n = 0 while True: n += 1 g = min(max(ub+k,0),255) k = 1-k r = liar(g) if previous[g] != r: previous[g] = r break lb = 0 ub = 255 ``` My idea was to cross-examine the liar witness (do a binary search), and when it finds a contradiction, press it (specifically, if it finds a -1 right next to a 1, it repeatedly guesses between the two). If that didn't solve the case, then we get a new testimony (reset the binary search bounds). The idea is to quickly cause the liar to run out of lies. It also has other optimizations. It keeps track of previous responses, so when it resets after the contradiction goes away, it doesn't actually have to use guesses to get back to where it was before. It also begins by checking that the liar isn't lying at the very beginning. [Answer] # Liar, equal\_lie ``` """A liar that only lies when equal.""" import random class Main: def __init__(self, rng: random.Random, secret: int): """Store the rng and secret.""" self.rng = rng self.secret = secret def __call__(self, guess: int) -> int: """Work out the correct response. mostly.""" if guess == self.secret: if guess % 2: return -1 return 1 if guess < self.secret: return 1 return -1 ``` I have no idea why this works. [Answer] # Guesser: top\_median ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): poss=[0]*256 while True: height = max(poss) top = [i for i in range(256) if poss[i]==height] guess = top[len(top)//2] i = liar(guess) for j in [range(guess+1), range(guess,256)][i<0]: poss[j] -= 1 ``` [Answer] # Guesser, most\_recent\_guess ``` """A guesser that based on recent guesses.""" import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): scores, current = [0] * 256, 0 while True: max_score = max(scores) values = [val for val, score in enumerate(scores) if score == max_score] guess = values[len(values) // 2] result = liar(guess) current -= 1 if result > 0: scores[:guess + 1] = [current] * (guess + 1) else: scores[guess:] = [current] * (256 - guess) ``` Basic idea: The more recent response would be more trustable. [Answer] # Liar: theLiarKing ``` import random, math class Main: def __init__(self, rng: random.Random, secret: int): self.rng = rng self.secret = secret def __call__(self, guess: int) -> int: timeToLie = self.rng.randint(1,16) if guess == self.secret: res = self.rng.choice([-1,1]) elif timeToLie == 1: if self.secret > guess: res = -1 else: res = 1 elif self.secret > guess: res = 1 else: res = -1 return res ``` This liar has a 6.25% chance to lie in each turn, and also lies every time the guesser guesses the right number. I chose 6.25% (1/16) because in this way, on average, it lies againist my guesser one time because the guess was right and one time just because it wanted to lie. Check [my guesser answer](https://codegolf.stackexchange.com/a/220569/100356) [Answer] # Guesser, most\_correct\_guess ``` """A guesser that based number of correct times.""" import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): scores = [1] * 256 while True: index, mid_score = 0, sum(scores) >> 1 while mid_score > 0: mid_score, index = mid_score - scores[index], index + 1 guess = max(0, index - 1) result = liar(guess) for index in (range(guess + 1, 256) if result > 0 else range(guess)): scores[index] <<= 1 ``` Basic idea: We just consider all response from liar with same possibility of lying. There for, an answer may be correct if more responses support it. I still have no idea why `1 <<` is added there. It just works better than infinity weight (use max instead) and 0 weight (only use sum). [Answer] # Liar: Knave ``` import random class Main: """A **real** liar""" def __init__(self, rng: random.Random, secret: int): """Store the rng and secret.""" self.rng = rng self.secret = secret def __call__(self, guess: int) -> int: """You can trust me, really""" if guess > self.secret: return 1 return -1 ``` I think this challenge needs more Liar submissions. Here's a very straightforward one, lying as much as it can. As simple as it is, it can really throw off some guessers. --- Extra: [here's a TIO link](https://tio.run/##3RvbbttG9l1fMdtiIdKmaMuJs6lgGuu2RlAg2xZxFsVC1RIUNZInpkgtL3EEw9@ePWdunOHNipvuw/rBlsgzZ879NuPdvrzN0hef2XaX5SXJo3SVbUfrPNuScr9j6YbINz9ESRItEzoafXvID3nzz@ubm@t3N7PRaFPRoqB5QQIyX4xGK7omycvtmZOnG48kLMrd2YjAT8m2tAjmrxdHZ@ev@JN7yja3ZTCfemfeC@/ce@1NX3hnU@/FS@/8fCFAbllCyVRgwJ8omLPL4JQAJ3L9nC3IOssJIywVmyw09DJwimrrRO7x1D050485ycFkqh98u8tZWjp8taufis2Xl6f19vVq/vt4ar1ZBstJNOdvahri7S5AMTj8eY1dyoP/AR4mDgsEUgLMOLDq4tT9t8MuxDK35hG0uKEOCNFd1NL3o92OpisHRe8KLfBXYcJo4eD@nniAOgEmpU5y@IyKMwjkG4X1Rt9N@ALBUE7LKk/FuvlkuhDYyDHZstRx@GM/ziqQ5WTqeub3qetKumJWlvtwR4uS5mglM2mX/jv@RxjNTJvkfA6qgY3wtyRbKOZ9XtFaM0l2D4yc6u@3YBvw4Oz8vAYRzNYwyOmHmtPXboeiYYGDuI85RpecnJAzCyqnhScxD0rcWsTWuI5ckoZt1ZyIzY@JbWE0KWh7heRVLJnAkpZZmDKXaiiL23CbFWUYZ3lO4zLka56nkAJwCEOaLsgR0Q7eoSeWrugnD@xlFfJVqBCPoJcKJC65vDSYFihq6JbE9CtPoAZ8NfREUjbnrxYKxJSqUvI2@uScKgCQYa0vWF8lJYB0eTH3Sr4GzMgRdqRV56EkXKlsxAHUcxUSA9BtWJ1FMbm4CLr02a28pmbhDU2/gmI9ElewTYpCmJ9KDXvSkbqUDMLU2kXBStXq9x@jpBL2Ap@4DOGvJ3ZDQdK02tI8Kqk2CpChRBjU2BctLQrE84SmjvgoHHZxmDIVl5PAMBBLe52qmmmFL5AliQXFVJtCvUnbhSUaDjtroQBRgz0q/fYagqlraQfb8CPLyyJcsjTK9wBR0PJ5ZvDNN9@84ZysKAQQiPWsKFkM8HsfXnGQahmoWJssg37T2AROtZwkS/fk5Ow4WdaKkUnStQQfQJa2hQXIN4YsBVADpjJhACJZXgbVsgVj5gZNd0vCXVIcEHC4iaqiYFH6ByWdfC1xi8CG@RkWeFjmAGE@p9IBVRwLVXhCKZikn6MRoxAa0Mlk@qdqRYteqicqy7DMduGWrp6tj10GtR7EvKOhnHbLC1EZ63CFUeVlO3Ro1lW@oRAQGqq/IBA42hENEPBwBn9RTzVALcqB1MSrm7mRbaAQ9szs4/E6cs4uThe2JjhhHxYiFrbEb4tWyrsAHu7CPc2XWVWyMM3CLcDRPLy/jZ4ZeBiv1wzBM3JBvmtWfR/6Kr9GGfEBFr9@Zo2nhCxX/E/LOfPlB3LMNVJr/7hTQ4PKAIWNVAsHOz1s/DBMoy0Nw9mG280G7UahfBwd2ha@/emK94QoKdUQxknEw1kW3qXRR6rD3BU5OspplBwdccFiYOOv0JLCEGJeGYZOQZM12GuH6RQ0hmZkhsZiFFCA5abEMqG8pbiM94kCVIdOnnIBr4/vA4SyHwtweCM@mFRhDNZUiXzNCSCTS/xr0fGvrCJxhL1SVZRkC/UpcpvsTTKY7NLAcoytZw3b4y3XdNR4AMFUyFm3fkrErhJ6wwZAJiGuCO@g8599BWn/2VLE3vh99pZRjkbs5SNlmMWm3vSV25ZkEAyJsjAxxbcZi6kDfaw3Xbh2AjO2DkgjlWEtarB4KXlo@bHYbnKIywvQRhJ9cpP2qibuFgnSeOB5w3qGbKU2qB0r6TbCLjJMsuwuzD7CJ4DNa79@C6vA/aKS7Fh8V5CIQDG/pDl59ZJk6zUR0ydwzyguK6j@yyjfAIPoqDugDmgp@PJxwaFkgwPvi3ua@0@EiYG48CtQg8TQ@96A0LBZCNevXvjnQt/8wQWZnr0WHZx8MuEgz40R7@Q4BfgcS0bHJqct6774gjjBbejQ8GIOw8jNbVYlKxAVaJfccgNpGtBp03z6LUNbD/Yq9D@gcxyRzP6/ov1vWX5HwHMsmwUv22VpQX2CLZpRvR8csTTQX8lZV9Ro6q7TEJ5lPX1ZxlIi1hE852MRkdRFhOjpEywi@OLHz8D5e5AMtKj5fpeB9ESIyKtUuHlRLbcMincQF5eSnEtDbNjBeqq@x1la0k9lwpbqCZhdXmZZUqgHSbbZQMwa2TNv@a0oc@MdBnkxDY@zJAGN4fZqJA42EEHXv2Jx2TUxv0r3njE2x13BWQK1vQ8x7S1/5oxlHcXj6dhFiV3fhFdv3/7y2/WPsOL16Ob6h3fX78N3Vz@/ueaV66uR8pk3INBfwJWc608x3SGBdaN4lRKqngpxsgL4ZQVdQcFLU4h2G1iOT9EbB2OnoLEY9DAZx7O1ghabQrCC99EdTdtOpwADtcQkAJQh9@cuBV@tjX9kxS6J9nxrmuc4FS94YErHJcQmYLLMyBK8DZRAV661ubTe9Rjlx7kn0RoshTyYZD0qqvyxFviNNsRr3LNP7pweBpVIHJVoFRFZVrxojgxTHpT4FnaONnSGfHvGIv6gTwU1mJB9DB0vCkKJqCOn1SsCY3kNVO3AulxfUyfpcjsk8hM4X76O4jrZfx9BKhRgYhIqAFAi96y8bbl1nzA4CjQ/7lYYRaRcjjgYhAHxzpbL2yxaNcTSFgAiA9bxj/2CfqJxhZoNMQ5YLWRbcj9naWO5JBneyU/2a003AOjPNf8Q@ITl2/VAlQ7xs81WVaKLYbntXHNZzwaE7PH5LYS/hIY1wpDbSeE0p84tjsVmzpHNjStY@HsdiH35cRulYDa55rB35zbbP0RlfAvJey@MuOB5nAcylMaWRC23LGw9Qw1ZKi3iHx9/OcYUJt/b7O4ZTVZ1pcR9nGhXxw1ph3waFnNsbYaHDZqOZhJnBUvhbQrtBjSCDWbcdmb/lvyYYZiLuWSyCqLuDkoJSJ9QFgshtasBLrAntlb5pGPPrvXiWTMmtpauxzWIDLFokI8qG0XkAbInEODqGuFRsDEj4w5sD/Rx7NXua0G4ooMYduYh1ai4ho2KjmhOR5SrI/4/uG2LSkXFOCq8DB9hYofmJdvk0XYwzBmB7Yuq3J8ACYsS6RB8P9sBmkGcF2ViP6svchs1MUQh97kl71VxV3MPqVhUuzwrR2KtReOXxyRVPquAVy9ojjrF/E0Ap1nJz@Kgq8eTxWkT6aEWzftYy5Z5TYHWnMIGH0EdK3HeNCMPavdHf@y1cPXYcUdPznHUtZ@oG7@Ojcoi9AkzbcW8p2zWHtXjwABNaBnFd4Nz3W67VjQqolkuGxeFs53drS3ljFZ/P7AQ6OgMm/6khqVGUPL0YvlJ7Wo4lHp06DRAO5AhDQj4bWcCg3e4odfBXd41QOQuXiFRLd9p/eUyIGar8UzHkGZp@YagddXyC/788fk@0daxcn2zQRKmnzdcIeclKdTjUI1C1YSt0OFW/0R4VkcX3C2koroKd1qSaie0idYna6QnJ08jy6OkfZrEGLWNAgEcdOWoCak8ZTo6Ojs/N870VCs6jNKAOgir2VOFvBNsV9N4BybM6TYCmfPNzS647dMIYOVncaFGMeuZYuskBDG0Aqh85Zkc9nvvcI2u7alrc5lZ63KuSYo2PlKYwzZh9h75gGcGwiNVxeYZ2IoMI8A9HX8EOjKcpUCPv0YBmWGUfmIl@CSN8mTvj2w/13MFa/ZwRBxrOIEXFwyBbKi8YBCqXHVYYHtDxVxM52g9A25XMm1TOm7cxugAuSRPstE57jr9smmcnFibtm0MWS8OWDg0q9dA9jE5hvkOD@rkR6AY9RVQXafEZun0l0Bi6Oh9Gv5rXZFpFTB/OP/JArI2FOVX9pDHZq/DPAeYBUWfdmVA7RltO3MHT1q6i7j3GRaN@8EUhReeSoYjHgSG/dNysI3AmCxHJTnd0ZLxwSUXLNrYaWcS4j21jF2NfexqqMaIKaL@1sxYEFoCTkpnNdWTWvThG88r@KsZvbE71PcJjSGsg2bTUfwdCKsi/oHgdj/5NPyKFTgUZ2vGxTJftBqtEDkrmqIAD4mrJCoVz46df@Si7iwEzqUzUcFvP/erls/j6zupmANFoPLEXV89RvehQVhVwGOrZOM9pX9H90Ckp2@A6weiNjDjsOt1zBgQqGlnzSuQKqRSnCi25dseXeAIiqVVa/bBK4k/gMLSnaMEZsmxQ1/aS7@0XORKFZXikpb3FDJbeZ@1hqi9U62N6HCMktgxe5RO6pvrG5WLHI2poIiTMe6hOFLvyBKG986tjRaYxvVKFVafGrEJJHotd/gGyNMoTAraVs3xquwygBp/JodR0ZJeo6lCITaHH40rdfzkyL@Pcky2DhiK01zgum3OTQvXB7ONdcYUxW5U7TDUNaSVIFBQxuZkHxpUGVQxyAzEIK5@/t8Ag/EUsTi2lerzKe3MhqH5ePLcGh5hh9zr/rxBdoZijHtghDB4qm21lUePrPq0F4FpqV@Co5kMDa/p8zM7HVo7N9fUqUPfz25u2K2CHrKgOAB2V@JqNzlpi9A2hTpfWbvbDAwQ0MfpEBkKyKakNnmPoPuLUTM/4y5Kpyv2KLLatolVvbljjXvRtrwVTbpDm7HqgEtGT6EgXfFRhDHF7Ekf0a11RnDh/1wVikv0XZHl11zcB6Dyon2BHUBRrrLKjh944VTdLCyyHHpbZ9De7PID6pQgibbLVaSScad5eo2qHrJVQQO87ztqx3ekyPj/t16ibBvspauuDAYMd9SVZprFai8lDdBeUqzz6Cfs5otEJv7Tbj1@aAa4R7PXUKcFUEw/6HbjcTZu4hn/nr7PduKSyez3dAyt/ngyhlj54m9uK4DxElnZUOO2s6KKm8bFi7NHuW/LPmaXLx/7yFCmMEiJkXVM8@mhR5mEQVKPXfQRdpNk97QozSpykD7jEBj/E8dWu01l6wR9nWRRdyQ07cXtZtUwOcGtjQL4888ei3HblH5PH/CGfDuHP5pMi3sqVomEl3EYdtfiSBJHAuMwxBFHGI7l/X@8fYSzRHUTyb/KNxWWNr/yN7WLrWgR54yfHwdjWckL1ZzIEzJVFIkTT9fA70erFR6vc8TOeFKMPdDOBI0ePgHmMhjzL/2LNB3jSS5WG@4ED/D8NeCtiCy8gqnCbAIapMnLC3Iz/odfAZDdgRwA4BNfTwH0vMpssRKKF895WOLXr/yoiBkLKyhQ8xgvkByrFyu2YaU5aOBbjMf@h4yljpwpiGu7hSPReuQueCWrYXvYwscLnqDQ7DZ9OyG5nz//Fw "Python 3 – Try It Online") to test submissions online that I put together by ~~vandalizing~~ modifying Artemis' code from Github. Feel free to use it to test your future submissions (add your submission to the header, with a unique name instead of "main", and remember to append it to either the `guessers` or `liars` list). This liar turned out to be not exactly great, my consolation is that at least it managed to mess with the top positions of the guessers board ^^" [Answer] # Guesser: FibTrust ``` #def Main(rng: random.Random, liar: Callable[[int], int]): def Main(rng, liar): times=[8]*256 weight=[1,2,3,5,8,13,21,34,55] while 1: a=[i>=0 and weight[i] for i in times] b=(sum(a)+1)/2 guess=-1 #print(times) while b>0: guess=guess+1 b=b-a[guess] cmp=liar(guess) times=[times[i]-(i==guess or (cmp<0)^(i<guess)) for i in range(256)] ``` [Try it online!](https://tio.run/##dVNNj9owEL37V7isKjldwxIoFUIYqeq5qtQ99BClyMkacGtiahuV/fV0/EE@SutDAjNv5j2/yZxe3UE386s8nrRx2PDmRR/R9eFF7PBnLhtimv0qhSdfw4tiJblZ4U9cKV4pURSycSXF/pmtUL8yQiGI4Th5FJYVy/LdbPEhRH4LuT84VuR0Rud0QZc0n9NZTufv6WJRRshBKoHz2MEfzgq5YVMMUlJ9IUu80wZLUBBJyhZdMWLPR8Kzxzx7mrXh/VlYy8Z5G3g4GZBPQnXWRiN5tZl29F11eD7mg0zFqjEvQqbTUB9PzNtAQrzrnvwIL7jDmEgWm2K4DIGq9TT7TuQ6lmXdHWEae0HAxKxE19Fo9DG4jN2BO6wb9Qp/hQXxosHi15mrCWDQcMAI1YoDky/0w1qhIMvPbruVjXTbLbFC7SgOU7SiNsJlnQ3Q8dlpI4BUeEgYR0QFthvO95j4PPOoYTjCIRN/9BXU8Gm1CuL9B9zftPmJ9dkF@lobI2q4mrAn3VgxwUdtnXodCJG72Acz1mcfDrYFvcWzYcYfgJ9Ng8fDkadofs@0/j/RXVHXG0U8my8QjNF/HGyJ/Ji@VD/Aq9vAyGAlSdbOKOzfAaJKGHJJtu2VrrjCqeENi5Lcy@Zvje1uCOXz6/v8LW1FPzpFcUXtrXVi7K9vugto61tm3zA@9CiVjhNVXNALtZTTlIoN8ieOehZyhP7tT/Iku6I/ "Python 3 – Try It Online") [Answer] # Liar: keep\_away ``` """A liar that tries to keep the guesser away from the secret""" import random class Main: def __init__(self, rng: random.Random, secret: int): """Store the rng and secret.""" self.rng = rng self.secret = secret self.lb = 0 self.ub = 255 self.lies = 4 def __call__(self,guess): r = (guess <= self.secret) - (guess > self.secret) a = (self.lb+self.secret)//2 b = (self.ub+self.secret)//2 if self.lies: if a <= guess < self.secret: self.lies -= 1 self.lb = guess r = -r elif self.secret < guess <= b: self.lies -= 1 self.ub = guess r = -r return r ``` Similar to my other [liar](https://codegolf.stackexchange.com/a/220887/95116), this tries to waste time, but instead it keeps track of how close the guesser has gotten, and lies when it gets too close (the threshold for too close gets smaller each time). [Answer] # Guesser, BinaryReset ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): """Guess deterministically.""" ub=255 lb=0 while True: g=(ub-lb)//2+lb r=liar(g) if r==-1: lb=g elif r==1: ub=g if lb>=ub: ub=255 lb=0 ``` Untested, for now ill just hope it works. # Guesser, BinaryResetGaussian ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): """Guess less deterministically.""" ub=255 lb=0 while True: g=max(0,min(255,int(rng.gauss((ub+lb)//2,(ub-lb)/6)))) r=liar(g) if r==-1: lb=g+1 elif r==1: ub=g-1 if lb>=ub: ub=255 lb=0 ``` Instead of fixing my binary search, why not just add randomness? [Answer] # Guesser: BayesBot ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): num_possibilities = 256 max_lies = 8 distribution = {(secret, max_lies) : 1. / num_possibilities for secret in range(num_possibilities)} lie_rates = [ 0, 0.211, 0.195, 0.188, 0.138, 0.207, 0.202, 0.140, 0.228, ] while True: secret_distribution = [0] * num_possibilities for (secrets, _), p in distribution.items(): secret_distribution[secrets] += p q = 0.5 for guess, p in enumerate(secret_distribution): q -= p if q < 0: break result = liar(guess) next_distribution = {} for (secret, lies), p in distribution.items(): if secret == guess: lie = True cond_p_result = 0.55 if secret % 2 else 0.83 if result == -1: cond_p_result = 1 - cond_p_result else: lie = (result == 1) != (guess < secret) cond_p_result = lie_rates[lies] if lie else 1 - lie_rates[lies] if lies == 0 and lie: continue next_p = p * cond_p_result if lie: next_distribution[(secret, lies - 1)] = next_p else: next_distribution[(secret, lies)] = next_p c = 1. / sum(next_distribution.values()) distribution = {k : c * p for k, p in next_distribution.items()} ``` Uses a statistical model to estimate the probability that each number is the secret, then always guesses the median of this distribution. Sort of like a fuzzy binary search. [Answer] # Liar: LookOverThere ``` class Main: """Liar that picks a number 64 off from the actual target and pretends that's the correct answer.""" def __init__(self, rng, secret: int): """Pick a new secret.""" self.secret = secret + 63.5 if secret < 128 else secret - 63.5 def __call__(self, guess: int) -> int: """Return the 'correct' answer.""" if guess < self.secret: return 1 elif guess > self.secret: return -1 # Should never happen return 0 ``` Maximizing time spent lying is probably the way to go. So we want to give the correct answer most of the time, lying only when necessary. I may adjust the difference after testing (down to 32 off or 16 off the correct answer). [Answer] # Guesser: noMatterWhat ``` import random from typing import Callable def Main(rng: random.Random, liar: Callable[[int], int]): i = 0 while i < 9: low = j = 0 high = 255 while j < 8: guess = (low + high) // 2 res = liar( guess ) if res > 0: low = guess + 1 else: high = guess - 1 j += 1 i += 1 ``` The code implements a binary search to look for the secret value. A binary search over 256 values is granted to find the key in 8 steps. But since the liar can lie 8 times, a single binary search is not enough, we need at most 9 of them. So this guesser is granted to end the game in at most 8 \* 9 = 72 turns, no matter what's the strategy implemented by the liar. Special thanks go to [Artemis](https://codegolf.stackexchange.com/users/80756/artemis), who had the patience to explain me how to run the game, so that I could debug my answers. Check [my liar answer](https://codegolf.stackexchange.com/a/220570/100356) [Answer] # Guesser: Pester ``` import random from typing import Callable def guess_lies(liar, guess, lies): tries = [liar(guess) for _ in range(9-lies)] return tries[-1], lies + min((tries.count(-1),tries.count(1))) def Main(rng: random.Random, liar: Callable[[int], int]): while True: low = 0 high = 255 lies = 0 for j in range(8): guess = (low + high) // 2 res,lies = guess_lies(liar, guess, lies) if res > 0: low = guess + 1 else: high = guess - 1 ``` Repeatedly guesses the possible amount of times that the liar could lie at any instance + 1, and assumes the last answer is correct. This is only slightly worse than just doing 9 binary searches. [Answer] # Liar: one\_big\_lie ``` """A liar that lies once at the very beginning""" import random class Main: def __init__(self, rng: random.Random, secret: int): """Store the rng and secret.""" self.rng = rng self.secret = secret self.lied = False def __call__(self,guess): r = (guess <= self.secret) - (guess > self.secret) if not self.lied: self.lied = True r = -r return r ``` The idea is that lying on the very first turn would waste a lot of time for the guesser while using a minimal number of lies. [Answer] ## Liar: Mislead ``` from collections import defaultdict import random class Main: """Liar that tries to foil binary searchers and repeat guesses""" def __init__(self, rng: random.Random, secret: int): self.rng = rng self.secret = secret self.lies = 0 self.low = 0 self.high = 255 self.prev_guess = defaultdict(int) def __call__(self, guess: int) -> int: """Return 1""" if self.prev_guess[guess] > 0: if guess != self.secret: if self.rng.randint(0,self.prev_guess[guess]-1) == 0: self.lies += 1 answer = -1 if guess > self.secret else 1 else: answer = 1 if guess > self.secret else -1 if guess == self.secret: self.lies += 1 return self.rng.choice((-1, 1)) self.prev_guess[guess] += 1 if not (self.low <= guess <= self.high): self.low = 0 self.high = 255 self.prev_guess = defaultdict(int) if self.low <= self.secret <= self.high: if self.rng.randint(1,self.lies+1) == 1: self.lies += 1 if not (guess <= self.secret <= self.high): self.low = guess + 1 return 1 else: self.high = guess - 1 return -1 answer = -1 if self.secret < guess else 1 if answer < 0: self.low = guess + 1 else: self.high = guess - 1 return answer ``` Tries to break binary searchers and doesn't seem to do a great job at it, also lies to people who ask the same guess multiple times. Isn't great but at least it beats LookOverThere? [Answer] # Liar: Illusionist ``` import random class Main: def __init__(self, rng: random.Random, secret: int): self.rng = rng self.secret = secret self.fake_secret = (127-secret)%256 self.unreserved_lies = 4 self.prev_lies = [] def __call__(self, guess: int) -> int: if guess < self.secret: secret_direction = 1 elif guess > self.secret: secret_direction = -1 else: secret_direction = 0 if self.unreserved_lies and guess not in self.prev_lies: if guess < self.fake_secret: if secret_direction != 1: self.prev_lies.append(guess) self.unreserved_lies -= 1 return 1 if secret_direction != -1: self.prev_lies.append(guess) self.unreserved_lies -= 1 return -1 elif secret_direction != 0: return secret_direction return -1 ``` The liar picks an illusory number to lead the guesser towards. However, if the guesser double checks the liar's answer, it will tell the truth in order to avoid wasting lies. The liar reserves 4 lies for when the guesser chooses a number equal to the real `secret`. ]
[Question] [ [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) is a method used for blurring images smoothly. It involves creating a matrix which will be used by convolving it with the pixels of an image. In this challenge, your task is to construct that matrix used in Gaussian blur. You will take an input *r* which will be the radius of the blur and an input *σ* which will be the standard deviation in order to construct a matrix with dimensions (2 *r* + 1 × 2 *r* + 1). Each value in that matrix will have an (*x*, *y*) value that depends on its absolute distance in each direction from the center and will be used to compute *G*(*x*, *y*) where the formula *G* is: $$G(x,y)=\frac{1}{2 \cdot \pi \cdot \sigma ^ 2} e ^ {-\frac{x^2+y^2}{2\cdot \sigma ^2}} $$ For example, if *r* = 2, we want to generate a 5 x 5 matrix. First, the matrix of (*x*, *y*) values is ``` (2, 2) (1, 2) (0, 2) (1, 2) (2, 2) (2, 1) (1, 1) (0, 1) (1, 1) (2, 1) (2, 0) (1, 0) (0, 0) (1, 0) (2, 0) (2, 1) (1, 1) (0, 1) (1, 1) (2, 1) (2, 2) (1, 2) (0, 2) (1, 2) (2, 2) ``` Then, let *σ* = 1.5 and apply *G* to each (*x*, *y*) ``` 0.0119552 0.0232856 0.0290802 0.0232856 0.0119552 0.0232856 0.0453542 0.0566406 0.0453542 0.0232856 0.0290802 0.0566406 0.0707355 0.0566406 0.0290802 0.0232856 0.0453542 0.0566406 0.0453542 0.0232856 0.0119552 0.0232856 0.0290802 0.0232856 0.0119552 ``` Normally in image blurring, this matrix would be normalized by taking the sum of all the values in that matrix and dividing by it. For this challenge, that is not needed and the raw values calculated by the formula is what the output should be. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * The input *r* will be a nonnegative integer and *σ* will be a positive real number. * The output must represent a matrix. It can be formatted as a 2d array, a string representing a 2d array, or something similar. * Floating-point inaccuracies will not be counted against you. ## Test Cases ``` (r, σ) = (0, 0.25) 2.54648 (1, 7) 0.00318244 0.00321509 0.00318244 0.00321509 0.00324806 0.00321509 0.00318244 0.00321509 0.00318244 (3, 2.5) 0.00603332 0.00900065 0.0114421 0.012395 0.0114421 0.00900065 0.00603332 0.00900065 0.0134274 0.0170696 0.0184912 0.0170696 0.0134274 0.00900065 0.0114421 0.0170696 0.0216997 0.023507 0.0216997 0.0170696 0.0114421 0.012395 0.0184912 0.023507 0.0254648 0.023507 0.0184912 0.012395 0.0114421 0.0170696 0.0216997 0.023507 0.0216997 0.0170696 0.0114421 0.00900065 0.0134274 0.0170696 0.0184912 0.0170696 0.0134274 0.00900065 0.00603332 0.00900065 0.0114421 0.012395 0.0114421 0.00900065 0.00603332 (4, 3.33) 0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074 0.00464913 0.00637454 0.00798657 0.0091434 0.00956511 0.0091434 0.00798657 0.00637454 0.00464913 0.00582484 0.00798657 0.0100063 0.0114556 0.011984 0.0114556 0.0100063 0.00798657 0.00582484 0.00666854 0.0091434 0.0114556 0.013115 0.0137198 0.013115 0.0114556 0.0091434 0.00666854 0.00697611 0.00956511 0.011984 0.0137198 0.0143526 0.0137198 0.011984 0.00956511 0.00697611 0.00666854 0.0091434 0.0114556 0.013115 0.0137198 0.013115 0.0114556 0.0091434 0.00666854 0.00582484 0.00798657 0.0100063 0.0114556 0.011984 0.0114556 0.0100063 0.00798657 0.00582484 0.00464913 0.00637454 0.00798657 0.0091434 0.00956511 0.0091434 0.00798657 0.00637454 0.00464913 0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074 ``` [Answer] # Mathematica, ~~60~~ ~~54~~ 50 bytes Thanks @GregMartin for 4 bytes! ``` Array[s=2#2^2;E^(-{##}.{##}/s)/π/s&,1+2{#,#},-#]& ``` Takes r and sigma as input, returns the matrix (exact numbers). **Built-in version (58 bytes)** ``` GaussianMatrix[{##},Standardized->1<0,Method->"Gaussian"]& ``` Of course, Mathematica has a built-in for this, too, but it's too long. [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` _G&:U&+iUE/_Ze5MYP*/ ``` [Try it online!](https://tio.run/nexus/matl#@x/vrmYVqqadGeqqHx@VauobGaCl//@/IZc5AA) ### Explanation ``` _ % Take input r implicitly. Negate G % Push r again &: % Binary range: [-r -r+1 ... r] U % Square, elementwise &+ % Matrix of all pairwise additions i % Take input σ U % Square E % Multiply by 2. Gives 2σ^2 / % Divide _ % Negate Ze % Exponential 5M % Push 2σ^2 again YP % Push pi * % Multiply / % Divide. Display implicitly ``` [Answer] # Octave, 45 bytes ``` @(r,s)exp((x=-(-r:r).^2/2/s^2)+x')/2/s^2/pi ``` [Answer] # Octave, 49 bytes ``` @(r,q)1./((Q=2*q^2)*pi*e.^(((x=(-r:r).^2)+x')/Q)) ``` [Try It Online!](https://tio.run/#zZLWf) [Answer] # Python, 88 bytes ``` lambda r,s:[[.5/3.14/s/s/2.72**((x*x+y*y)/2/s/s)for x in range(-r,r+1)]for y in range(-r,r+1)] ``` Uses the rule where you may hardcode 3.14 and 2.72 at 1 byte cost each. [Answer] # [Perl 6](http://perl6.org/), 71 bytes ``` ->\r,\σ{map ->\y{map ->\x{exp((x*x+y*y)/-2/σ/σ)/2/pi/σ/σ},-r..r},-r..r} ``` Technically this may be more than 71 bytes if encoded and saved to a file, but I couldn't resist naming the "sigma" input with an actual Greek sigma. It could be renamed to any plain-ASCII letter if one wanted. [Answer] # SAS Macro Language, 296 bytes Probably a much more efficient way to do this but it works :) This code prints out the resulting dataset. ``` %macro G(r,s);%let l=%eval(2*&r+1);%let pi=%sysfunc(constant(pi));data w;array a[*] t1-t&l;%do i=-&r %to &r;%do j=-&r %to &r;%let t=%sysfunc(sum(&j,&r,1));a[&t]=%sysevalf(1/(2*&pi*&s**2)*%sysfunc(exp(-(%sysfunc(abs(&j))**2+%sysfunc(abs(&i))**2)/(2*&s**2))));%end;output;%end;proc print;run;%mend; ``` [Answer] ## Haskell, 59 bytes ``` r#s|i<-[-r..r]=[[exp(-(x*x+y*y)/2/s/s)/2/pi/s/s|x<-i]|y<-i] ``` Usage example: ``` 1#7 [[3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3], [3.2150851187016326e-3,3.2480600630999047e-3,3.2150851187016326e-3], [3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3]] ``` [Answer] # Python 2.7, 167 bytes A very simple solution: ``` from __future__ import division;from math import*;r,s=input();s*=2*s;R=range(-r,r+1);print"\n".join("\t".join(str(pow(e,-(x*x+y*y)/s)/(pi*s))[:9]for x in R)for y in R) ``` [Try it here](https://tio.run/nexus/python2#LclBDoIwEADArzScdkuBKF604RNcxTQmgq4J22ZbFF6PUblNMusgflTODVOapHdO0Ri8JHWjF0XybH8/XtNjG23FxIY4TAnQRt3sdbRtI1e@91CIkXyHNghxyjrOyqcnhqxLm2ISCP4NvSlg1nO@6AWriBUE0hHxfDpeBi9qVsSqxS@XP9f1YOqyrj8)! Ungolfed: ``` from __future__ import division from math import * r,s = input() # Take input s *= 2*s # Set s = 2*s^2; simplifies the expression R = range(-r,r+1) # Range object; used twice # G(x,y) # Stripped print "\n".join("\t".join(str(pow(e,-(x*x + y*y)/s)/(pi*s))[:9] for x in R) for y in R) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~260~~ ~~229~~ ~~212~~ 208 bytes ``` (r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU87TsQwFLwKdP7EJraEhGTedhQUSPSrFBtINpaieOV1tHaiVDkGTYTgClwjtNwGB9PMjN6bGb339tGZ12p5r-GzdzW7-_lGNltnDLvRwb5QwwbrTGCdVQmWMKECWHUASSyl6tLotkLhGkom8Oih_J_YncfjwE_9uUE-C1h5SqfA2FQbizTkSt8PvK26o2uUpiC37LDXRSyPREWhXAqLGyTJ08E1_PmRxLuSPpkL-hMPGWKCeEIkDRHw5o4ujCdbud52V25Kf329mO5s2oq35ohqlGc5l7cYp-WyJP4F) How? ``` (r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t} : main function t=[];z=[]; : Define empty arrays σ*=σ; : set σ to σ squared a=2*r+1;b=r*-1;y=r; : set variables for looping while(y!=b-1){ : open while loop for y's x=b; : reset x value while(r+1>x){ : open while loop for x's z.push(x,y); : push xy values to array z x++} : increment x and close loop y--} : decrement y and close loop for(i=0;i<z.length;i+=2){ : open for loop based off length of array z x=s(z[i]);y=s(z[i+1]); : retrieve x and y values from z t.push(....)} : push results to array t +closes for loop 1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)) : Gaussian function return t} : returns the results and closes the main function ``` [Answer] # [J](https://www.jsoftware.com), 39 bytes ``` {{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxU726WiNON1G1zlBZT8vKrtpBQ0fNRrMu06pCUzVfL9FWT9tKy6qythaifL0mV2pyRr6CiUKagrGesTFEdMECCA0A) ``` {{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}} {{ }} NB. direct definition o.a=.+:*:y NB. π * (a = 2σ²) (^-a%~1#.*:>{@(,&<)~i:x) NB. computes the eʸ portion i:x NB. range [-n..n] {@(,&<)~ NB. cartesian product, creates a grid of boxed pairs > NB. unbox *: NB. square the pairs 1#. NB. sum¹ the pairs a%~ NB. divide each sum by a, x f~ y -> y f x - NB. negate ^ NB. eʸ % NB. division ``` See common use 3 for [sum¹](https://code.jsoftware.com/wiki/Vocabulary/numberdot#dyadic). The DD allows a non-tacit definition, which helps implement the function directly, but I am working on refactoring this. ]
[Question] [ In this challenge, your task is to make write a program **with less than 300 characters** that takes a short paragraph or a few sentences that a candidate has said and output who said it. **Input**: Can be taken as a parameter to a function, input to a program etc. It will be a short paragraph, properly punctuated. **Output**: The candidate that you think it is. This could be one of ``` Ben Carson (1) Ted Cruz (2) John Kasich (3) Marco Rubio (4) Donald Trump (5) Hillary Clinton (6) Bernie Sanders (7) ``` I've left off the names of people who have dropped out as of March 1st. You may output the name itself, or, more conveniently, the number that corresponds to the name. **Scoring:** Your score is the percentage of test cases you get right. Highest score wins. Ties (or perfect scores) are broken by code length as in a code golf. The test cases can be pulled from: <http://www.presidency.ucsb.edu/debates.php> Click on each debate, both Democrat and Republican that has happened so far (before March 1st). Every paragraph is a test case, unless the "paragraph" is less than 20 characters long. Here is code that pulls out the test cases from a particular page: ``` var t = $(".tools").parentNode.querySelectorAll("p"); var categ = {}, cur = 0; for (var i = 0; i < t.length; ++i) { var p = t[i], str = p.innerText; if (p.querySelector("b")) { cur = p.querySelector("b").innerText.replace(':', ''); str = str.replace(/^.*?:\s/, ''); } str = str.replace(/\[applause\]/g, '') if (str.length < 20) continue; if (categ[cur] == null) categ[cur] = []; categ[cur].push(str); } ``` You can then do `categ.SANDERS` to get a list of all the paragraphs that Senator Sanders has said. You can discard anything that isn't said by the candidates listed above (e.g. `categ.BUSH` or `categ.CHRISTIE`). Here is the file with all the test cases: <https://drive.google.com/file/d/0BxMn8--P71I-bDZBS2VZMDdmQ28/view?usp=sharing> The file is organized by candidate ``` CANDIDATE CANDIDATE_LAST_NAME (empty line) Series of statements. Each paragraph is separated by (NEW PARAGRAPH)- (empty line) CANDIDATE NEXT_CANDIDATE_LAST_NAME (empty line) etc. ``` An example partial submission would be: ``` if (/ win | wall | great | beautiful/.test(p)) return 5; if (/ percent | top one | rigged /.test(p)) return 7; // etc. for all candidates ``` or ``` var words = p.split(' '); // majority of words have less than 5 characters if (words.length - words.filter(a => a.length < 5).length < 4) evidence[5]++; // at the end return /* index with the most evidence */ ``` Here is a place where you can test javascript solutions: <https://jsfiddle.net/prankol57/abfuhxrh/> The code uses the parameter `p` to represent the phrase to classify. Example code that scores around 20% (guessing would get around 11%): ``` if (/ rigged | top | percent | Wall Street /.test(p)) return 'Sanders'; return 'Trump'; ``` **Exactly what I'm asking:** Write a program/function in less than 300 characters that takes as input a phrase that a candidate has said and returns as output which candidate said it. Your score is the percentage of test cases you get right. Highest score wins. Yes, I know that a lot of lines have `[laughter]` or `[cheering]` in them. These will not be removed. At worst, they are extra information you can ignore; at best, they are extra information you can use (e.g. I made this up, but maybe people laughter is evidence that Marco Rubio is speaking). The test cases are as they appear in the text file. [Answer] # Polyglot, ~18.6% This works in: Cjam, Pyth, TeaScript, Japt, Seriously, 05AB1E, GolfScript, Jelly, and probably many more. ``` 6 ``` This outputs Hillary for all inputs. This is because Hillary said the most. While it's not the most ingenious way to do this. It works ¯\\_(ツ)\_/¯ [Answer] ## Pyth, 34.16% (297 bytes) ``` FNc"7creta 6enato 3ohio 2donal 7 major 6o try t 5tot 5se me 7nai 4m pres 2he ob 3 bala 5jeb 6e aff 5mendous 2mnest 5. we'r 7ave got to 2c ter 4ntur 7 campaign 2flat 5obo 4is pre 4-here' 2note 2m el 4 issue 5, very 6o af 1fact o 6en's 5pany 6he republicans 7 -- 4meon 5bea 4ory o 7"bI}tNrzZhNB ``` (note that some lines end in spaces) I've gone with the simplest option I could think of: check a list of patterns, and as soon as you find a match, output the corresponding candidate. If all else fails, output the most likely candidate from the remainder. After that, it's all about cramming as much data into 300 bytes as possible. ``` FNc"<data>"bI}tNrzZhNB ``` Breakdown: ``` FN for N in ... "<data>" the hard-coded data (newline separated) c split using... b '\n' constant, I if tN tail (all but first char) of current item } is contained within rzZ the input (lowercased), then: hN print the head (first char) of the current item B and break out of the loop. ``` So where does that data come from? Well the structure is simply: ``` <candidate_number><phrase> <candidate_number><phrase> <etc.> ``` (with an entry at the end with no phrase to act as the final fall-back) But why those particular items? I wrote a C++ program to analyse the provided dataset (with some manual cleaning of newlines first to make the structure consistent). It looks at all substrings ("tokens") in each quote (1-16 characters), then repeatedly checks for the token which gives the most benefit to go next in the list. Once a pattern is in the list, remove any quotes which match it and repeat (it gets a bit more complicated to keep it fast but that's the basics). The code is probably too long to include here, but I might put it on github later (when I've cleaned it up a little). I tried a couple of scoring systems. In the end I went with this one: ``` score = ( + matching_quote_count_for_most_likely_author * 10 - matching_quote_count_for_other_authors * 7 - token_length ) ``` A stricter approach of only allowing new items which don't introduce incorrect answers seemed to get stuck at about 20-25%, needing a *lot* of patterns to get higher. This fuzzier approach does much better, and can still reach ~80% accuracy (with 550 items). The submitted score has 38 items, which was the most I could fit in the 300 character limit. The 34% result actually comes from a test C++ program which performs the same steps. It should match, but I haven't got a Pyth test harness to check it with. This is the first time I've used Pyth, so I imagine some more bytes could be squeazed out, allowing a bit more data. [Answer] # Javascript, 32.87% 299 Characters: ``` function Q(a,b){return p.toLowerCase().split(' ').join('').includes(a)<<b}z=Q('ink',0)+Q('int',1)+Q('ona',2)+Q('rica',3)+Q('twe',4)+Q("we'",5)+Q('youkn',6);return '55472726464727446676664676767676563641233643334456364233336141745116222136477126111113361611262316263122216111673336225611363276'[z]*1 ``` **Strategy:** I did a bruce force search on which word segments to include in a "hash". Then a string lookup happens with that hash in such a way that chooses the most likely candidate for that hash. **The code itself:** ``` // The Q function checks if a string is present. // Then left-shifts the true/false result up to e.g. 64,32,16,8,4,2,1 // This way we can combine results into any number 0 to 127. function Q(a,b){return p.toLowerCase().split(' ').join('').includes(a)<<b} // Now we check for key string occurrences: z=Q('ink',0)+Q('int',1)+Q('ona',2)+Q('rica',3)+Q('twe',4)+Q("we'",5)+Q('youkn',6) // Finally, use this as an index into the lookup string. (Multiply by 1 to convert char to int.) return '55472726464727446676664676767676563641233643334456364233336141745116222136477126111113361611262316263122216111673336225611363276'[z]*1 ``` This is my first ever code golf submission, so suggestions are welcome :) [Answer] ## Mathematica, 23.7775 % ``` (l=ToLowerCase@#;Ordering[-StringCount[l,#]&/@{"fact","donald"|"obama","done"|"ohio","issue"|"united"|"why"|"world","great"|"many","senator","american"|"believe"|"campaign"|"secretary"|"street"|"wall"},1])[[1]]& ``` It counts the occurences of common keywords unique to each candidate and outputs the number of the candidate with the highest score. Basically, I found the commonest words of all candidates ``` t = Import["~/Documents/candidate quotes.txt"]; ts = DeleteCases[StringSplit[t, "\n\n"], ""]; tss = Split[ts, StringLength[#2] > 20 &][[{3, 4, 5, 6, 7, 1, 2}]]; names = StringSplit[#][[2]] & /@ tss[[All, 1]]; quotes = StringSplit[#, "(NEXT PARAGRAPH)"] & /@ StringJoin /@ tss[[All, 2 ;;]]; (* remove the 100 commonest english words *) wd = WikipediaData["Most common words in English", "ArticleWikicode"]; Flatten[StringSplit[StringCases[wd, Shortest["{| class=\"wikitable\"" ~~ w__ ~~ "}"] -> w], "\n"]]; common100 = Alternatives @@ ToLowerCase@DeleteDuplicates@Flatten[StringSplit /@ StringCases[#, "|| " ~~ ("[[" | "") ~~ w : ((WordCharacter | " ") ..) -> w] & /@ %]; commonest = Commonest[ Flatten[StringSplit[ StringDelete[ToLowerCase[#], PunctuationCharacter | (WordBoundary ~~ (common100) ~~ WordBoundary)]] & /@ #], 20] & /@ quotes; ``` and chose the common keywords that are unique for each candidate. ``` keywords = Alternatives @@@ Table[Complement[commonest[[n]], Union[Flatten[Delete[commonest, n]]]], {n, Length[names]}]; ``` After manually deleting some of the keywords, this is the final table: > > > ``` > Carson fact > Cruz donald|obama > Kasich done|ohio > Rubio issue|united|why|world > Trump great|many > Clinton senator > Sanders american|believe|campaign|secretary|street|wall > > ``` > > With these keywords the total function length is 211 characters. I tested the function over all quotes: ``` pairs = Flatten[MapThread[Table[q -> #1, {q, #2}] &, {names, quotes}]]; test[q_ -> n_] := Boole[n === names[[p@q]]] (* here p is my function that outputs the predicted candidate's number *) Total[ParallelMap[test, pairs]]/Length[pairs] // N ``` which gives an accuracy of 23.7775 %. [Answer] # Python, 25.677868% Arbitrarily picked four different characters that would be used to identify the candidates. Each candidate is given a score factor per character based on a hill climbing search that I ran for a few minutes to end up at 25.68%. I suppose that this at least proves that the concept is better than picking a candidate blindfolded or just picking Clinton, but I would be interested in seeing someone apply a better search algorithm, both for the factors and for the characters used. ``` w=dict(zip("hr?.",((.847,.491,.821,.54,.744,.765,.234),(.494,.777,.202,.587,.7,.852,.484),(.915,.187,.161,.559,.748,.244,.43),(.11,.013,.628,.974,1.037,.484,.302)))) def f(t,r=(0,0,0,0,0,0,0)): s=r for c in t:s=map(lambda a,b:a+b,s,w.get(c,r)) return s.index(max(s))+1 ``` [Answer] # Javascript, TBD ``` a=[...p].reduce((a,b)=>(a<<5)-a+b.charCodeAt(0)|0,0)%1000,alert(a>0?0:1000,a<79?1:a<226?2:a<333?3:a<497?4:a<697?5:a<849?6:7) ``` Converts each string to a hash code, then uses probabilistic methods to determine the speaker. Would be nice if someone with a good setup could test this for me. ]
[Question] [ The goal of this challenge is to receive an input and output that input but with sentence order reversed. Example Input: ``` Hello friend. What are you doing? I bet it is something I want to do too! ``` Example Output: ``` I bet it is something I want to do too! What are you doing? Hello friend. ``` As you can tell from the examples, your program has to deal with question marks, exclamation points, and periods. You can assume each sentence has a punctuation and than a space before the next sentence. Trailing spaces/newlines are ok, as long as it is readable. Shortest code wins. Good luck! EDIT: You can assume the sentences has no quotes or parentheses, but if you make your code be able to deal with both of those then you get **-5 bytes** Example output for parens/quotes: ``` "Hello, " she said. (I didn't know what she was talking about.) --> (I didn't know what she was talking about.) "Hello, " she said. ``` [Answer] # Julia, ~~45~~ 42 bytes - 5 bonus = 37 ``` s->join(reverse(split(s,r"[.?!]\K "))," ") ``` This creates an anonymous function that accepts a string as input and returns the string with its sentences reversed. This handles any special character appropriately, though double quotes and dollar signs must be escaped, otherwise they aren't valid strings in Julia. Ungolfed + explanation: ``` function f(s) # Get individual sentences by splitting on the spaces that # separate them. Spaces are identified by matching punctuation # then moving the position beyond that match and matching a # space. This is accomplished using \K. sentences = split(s, r"[.?!]\K ") # Reverse the order of the array of sentences. reversed_order = reverse(sentences) # Join the array elements into a string, separated by a space. join(reversed_order, " ") end ``` Examples: ``` julia> f("Hello friend. What are you doing? I bet it is something I want to do too!") "I bet it is something I want to do too! What are you doing? Hello friend." julia> f("\"Hello, \" she said. (I didn't know what she was talking about.)") "(I didn't know what she was talking about.) \"Hello, \" she said." ``` And if you don't like looking at the escaped quotes in the output: ``` julia> println(f("\"Hello, \" she said. (I didn't know what she was talking about.)")) (I didn't know what she was talking about.) "Hello, " she said. ``` Saved 3 bytes on the regular expression thanks to Martin Büttner! Previously this used a lookbehind: `(?<=[.?!])`. [Answer] # CJam, ~~23~~ 22 bytes I am not sure if this qualifies for the bonus or not, but here goes the solution: ``` Sq{1$".?!"-{])[}|}%]W% ``` **Code Expansion (bit outdated)**: ``` Sq+ e# Read the input and prepend with a space { }% e# For each input character _".?!"& e# Copy and check if its one of ., ? and ! {][}& e# If it is one of the above, wrap everything till now in an array e# and start a new array to be wrapped next time we get one of those e# three characters. We now have an array of strings, each having e# a single sentence W% e# Reverse the ordering of these sentences s( e# Convert to string and remove the first space ``` [Try it online here](http://cjam.aditsu.net/#code=Sq%7B1%24%22.%3F!%22-%7B%5D)%5B%7D%7C%7D%25%5DW%25&input=Hello%20friend.%20What%20are%20you%20doing%3F%20I%20bet%20it%20is%20something%20I%20want%20to%20do%20too!) [Answer] # J, 35 32 It almost handles bonus input, except I have to escape single apostrophes, so I guess it doesn't count. (Also, my first submission here) ``` f=.;@|.@(]<;.2~'.?!'e.~])@,~&' ' ``` Usage: ``` f 'Hello friend. What are you doing? I bet it is something I want to do too!' ``` [Answer] # Perl, 27/25 ``` #!perl -n print reverse/ |[^.!?]*./g ``` Or from the command line: ``` $perl -nE'say reverse/ |[^.!?]*./g' ``` [Answer] ## PHP, 60 ``` echo join(' ',array_reverse(preg_split('/(?<=[?!.])/',$s))); ``` [Answer] # Bash + coreutils, 40 bytes ``` sed 's/\([?.!]\) */\1\n/g'|tac|tr \\n \ ``` This reads from STDIN so input may me redirected in from a file, or simply piped in, e.g.: ``` $ printf 'Hello friend. What are you doing? I bet it is something I want to do too!' | sed 's/\([?.!]\) */\1\n/g'|tac|tr \\n \ I bet it is something I want to do too! What are you doing? Hello friend. $ ``` [Answer] # [Pip](http://github.com/dloscutoff/pip), 25 bytes ``` a.:sRV(a^@2+$ALa@*^".?!") ``` After appending a space to the input string, we find all indices of `.`, `?`, and `!`, add 2, and use the `^@` split-at operator to break the string into sentences (each with a trailing space). Reverse the list, and it's auto-printed at the end of the program. Voilà! Example showing the stages of the main computation with input `A! B? C. D!`: ``` ^".?!" ["." "?" "!"] a@* [[7] [4] [1 10]] $AL [7 4 1 10] 2+ [9 6 3 12] a^@ ["A! " "B? " "C. " "D! "] RV( ) ["D! " "C. " "B? " "A! "] D! C. B? A! ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~61~~ ~~34~~ ~~33~~ 30 bytes *Credits to nutki for cutting this down by 24 bytes.* ``` ^ # +`(#.*[.!?]) (.+) $2 $1 # <empty> ``` Where `<empty>` stands for an empty line. This assumes that `#` is not part of the input, but if that's not legitimate, I could swap it out for any other character, including `"` (which I'd only need to handle for the bonus) or something unprintable. You can run the code like that in a single file if you use the `-s` flag, or you can put each line in a separate file and pass them all to Retina. Reversing this with a single regex replacement is possible, but really cumbersome. Even with .NET balancing groups I needed something around 90 bytes, so instead I tried doing it in multiple steps. In Retina, every pair of lines is one replacement stage, where the first line is the pattern and the second line is the replacement. ``` ^ # ``` This stage simply prepares the string for further processing. It prepends a `#` as a marker. This marker indicates that everything in front of it has already been put in the right place, and everything after it still needs to be processed. ``` +`(#.*[.!?]) (.+) $2 $1 ``` This stage swaps the sentences, by repeatedly moving the last sentence in front of the `#` (which moves forwards through the string in the process). The `+`` instructs Retina to repeat this stage until the output stops changing. As an example, here is how the input `foo. bar! blah?` would be processed: ``` #foo. bar! blah? blah? #foo. bar! blah? bar! #foo. ``` And finally we simply remove the marker: ``` # <empty> ``` [Answer] # Java, 113 ``` s->{String t[]=s.split("(?<=[\\.?!]) "),u="";for(int i=t.length;i-->0;)u+=t[i]+" ";return u.replaceAll(".$","");} ``` [Answer] # JavaScript (ES6) 47 ~~45~~ As it's stated, it's a simple regex exercise. In javascript: ``` // ES6 - FireFox only F=t=>t.match(/\S[^.!?]+./g).reverse().join(' ') // ES5 - so much longer function G(t){return t.match(/\S[^.!?]+./g).reverse().join(' ')} // TEST alert(G("Hello friend. What are you doing? I bet it is something I want to do too!")) ``` [Answer] # Python 2, 62 Not going to improve for the bonus, as it's probably not worth the byte cost. ``` import re print' '.join(re.split('(?<=[?!.]).',input())[::-1]) ``` [Answer] # Matlab (93 bytes) ``` y=[32 input('','s')];y=sortrows([cumsum(ismember(y,'?!.'),'reverse');y]',1)';disp(y(4:2:end)) ``` * This assumes the input doesn't contain leading or trailing spaces * Uses standard input and output * Tested in Matlab 2014b [Answer] # Ruby 41 The other Ruby answers don't have enough WTF. ``` #!ruby -apF(?<=[.!?])\s $_=$F.reverse*" " ``` This at least works in Ruby 2. If the `a` and `F` switch works in 1.8.7, I guess you could drop `$_=` to save three characters. Reverses every line on stdin and print to stdout: ``` $ ruby foo.rb <<< "Hello. Hi. How are you? Good, you? fine, thanks." fine, thanks. Good, you? How are you? Hi. Hello. ``` [Answer] # Ruby, 48(42 without the puts) bytes reverse\_sentence.rb ``` puts $*[0].scan(/\S[^.!?]+./).reverse.join(" ") ``` Usage: ``` ruby reverse_sentence.rb 'Hello friend. What are you doing? I bet it is something I want to do too!' ``` Output: ``` I bet it is something I want to do too! What are you doing? Hello friend. ``` Criticism more than welcome. [Answer] # k, 31 ``` {1_,/|(0,1+&x in"?!.")_x:" ",x} ``` . ``` k){1_,/|(0,1+&x in"?!.")_x:" ",x} "Hello friend. What are you doing? I bet it is something I want to do too!" "I bet it is something I want to do too! What are you doing? Hello friend." ``` [Answer] **C# - LINQPAD - 93 - 5 = 88 bytes** ``` void Main(){string.Join(" ",Regex.Split(Console.ReadLine(),"(?<=[.?!]) ").Reverse()).Dump();} ``` **C# Console App 189 - 5 = 184 bytes** ``` using System;using System.Linq;using System.Text.RegularExpressions;class P{static void Main(){Console.WriteLine(string.Join(" ",Regex.Split(Console.ReadLine(), "(?<=[.?!]) ").Reverse()));}} ``` *regex shamelessly flogged from Alex A. :)* [Answer] # Clojure - 44 71 chars ``` (defn rs[s](reverse(re-seq #"\S.+?[.!?]"s))) ``` Improved and simplified RE, eliminated unnecessary whitespace. Output is a sequence of the sentences in the original string, with the order of the sentences reversed: Input: "Hello friend. What are you doing? I bet it is something I want to do too!" Output: ("I bet it is something I want to do too!" "What are you doing?" "Hello friend.") [Answer] # Ruby, 47 ``` $><<gets.strip.split(/(?<=[.?!]) /).reverse*' ' ``` credits to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner), for saving some characters. [Answer] # CJam, 21 bytes ``` 1q{1?_"!.?"-}%1a/W%S* ``` This works by turning spaces after `!`s, `.`s and `?`s into the number 1 (not the *character* 1 nor the character with code point 1, so the input can still contain those), splitting at 1's, reversing the order of the resulting chunks and joining by spaces. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=1q%7B1%3F_%22!.%3F%22-%7D%251a%2FW%25S*&input=Hello%20friend.%201%20is%20number%20one!%20What%20are%20you%20doing%3F%20I%20bet%20it%20is%20something%20I%20want%20to%20do%20too!). ### How it works ``` 1 e# B := 1 q e# Q := input() { }% e# for each C in Q (map): 1? e# C := B ? C : 1 _"!.?"- e# B := string(C).strip("!.?") 1a/ e# Q := Q.split([1]) W% e# Q := reverse(Q) S* e# Q := Q.join(" ") e# print(Q) ``` ]
[Question] [ Two points `p`and `q` in a topological space can be separated if there are open sets `U` and `V` such that: 1. `p` is an element of `U` and `q` is an element of `V` 2. `U` and `V` do not have any elements in common Your task is given a topology (a set of open sets) and two points `p` and `q` (`p!=q`) to output sets `U` and `V` satisfying the above conditions, or decide that such sets do not exist. ## Examples: ``` {{},{0},{1},{0,1}} 0 1 -> {0},{1} {{},{0},{1,2},{0,1,2}} 0 1 -> {0},{1,2} {{},{0,1},{2,3},{2,3,4},{0,1,2,3},{0,1,2,3,4}} 1 2 -> {0,1},{2,3} or {0,1},{2,3,4} {{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 3 -> {1,2},{3,4} or {1,2},{3,4,5,6} or {1,2,5,6},{3,4} {{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 5 -> {1,2},{5,6} or {1,2,3,4},{5,6} or {1,2},{3,4,5,6} {{},{0,1}} 0 1 -> "not separable" {{},{1},{1,2}} 1 2 -> "not seperable" {{},{1,2,3},{1,3},{2,3},{3}} 1 2 -> "not seperable" {{},{0},{1,2},{0,1,2}} 1 2 -> "not separable" {{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 2 -> "not separable" ``` ## Rules: * You can assume the the Input is valid (a set of sets, that defines a Topology1) * You may assume that the two given points are different and contained in at least one of the sets in the Topology * You may use lists instead of sets for input/output * If you use lists you can assume that the elements are unique and sorted in any convenient order * If there are multiple possibilities to separate the elements you may return any **one** of them * Outputting the complete list of all matches is **not** allowed * If the two points cannot be separated, you may output any value, as long as it cannot be mistaken for the output in a separable case * It is allowed to throw an exception to indicate the non-separable case * Your code should be able to handle sets with at least 31 distinct elements * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins --- 1 *A set S of sets is a topology if:* 1. It contains the empty set and the set of all elements 2. Any (finite) intersection of elements in S is an element of S 3. Any union of elements in S is an element of S [Answer] # [Python](https://www.python.org), 63 bytes ``` lambda l,*I:(O:=[min(l,key={c}.__xor__)for c in I])[0]&O[1]or O ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pZLNToQwEMcTj_sUPblgRrOwrjEkxPOeeIDakMKWLLEUUrrGDeFJvJAYfSd9GvvBxqxw0knoDP_5zTClff1ojmpfi-GtiB_fD6q4vv984LTKdhRxuNpGXhLFuCqFx-GJHeMu72_S9KWWaeoXtUQ5KgXaEh-vyGWCA6KlxLX5usgNQCEDC-EF0oZx10O30k9gPAQ9Ab0S-J2F0OW1nyHAVIewdivcnlgbExOd8a6b4zZw55SxbozA6KZy_efKzWTG6eTB2HN2Rruf4LQr890Zbvp3_rPbkCxIZGupPkIUo5Ypz3eCeaulYjuPgmTPTLYsDuwt4Ew4RrL2wJUGC88etFMrqvL9mHPNjeW0Zchg_o9mrJGlUFY_R9M5bClqpWdsqKQZZ0vf3bVhcP4b) This expects a list of sets for the topology. The list shall be ordered by descending length as allowed per OP. (Actually, it suffices that the longest set comes first.) ## How? This depends on the specific implementation of `min`. It assumes that `min` works left to right and updates the current minimum whenever the next element is smaller than it. In particular, elements that cannot be compared to the current minimum are ignored. We use this to have `min` ignore exactly the subsets that contain `c` by starting off with the full set minus `c`. As this is the opposite of what we actually need we `key` `min` with `^{c}`, so we can start with the full set and ignore all subsets *not* containing `c`. Other than that it works like the other versions. # [Python](https://www.python.org), 65 bytes ``` lambda l,*I:(O:=[min(l&{x|{c}for x in l})for c in I])[0]&O[1]or O ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVLBaoNAEIUe8xV7StwwhWiaUgQPvTUnP2C7lI1dibCuohtIa_2SXoTS_lP7NXV2DSXVUzvgzuPNe-OM7utH-WT2he7e0uj-_WDSy5vPWyXy3aMgCpbb0IvDiOWZ9tS8Ob40SZsWFTmSTBPVUsQJ4i2nbMXnMfN5T8Wu0dfFHQoE7MCK2Iz0wVjTQrPqHx8z-C2H_uTwuwqBq_d5QgHoDmDtTrg6aS3miM70rpvTbeDaMYNvQIA8Otd_dm5GM44n94eekzPaffzTVvjeCd346_xn24DPeGi9ImqWuSi9tCqepa6lAUFbW6lkfVCGRCT17N-kls2FSfZDzXXASEQtCcroD4dRVpk2lj-XPkzJFrowpJalqMROyQV1F6rrXP4G) This takes a set of frozensets for the topology. # [Python](https://www.python.org), 66 bytes ``` lambda l,*I:(O:=[min(x for x in l if{c}&x)for c in I])[0]&O[1]or O ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVJLasMwEIUucwqtEjtMIXKaEgym0F1WPoAqiuzaxOAflgIuxifpxtDPndrTVCM5lNRetQPSDG_eG81Ievmon9WxKofXNHh4P6n0ev95n4siehIkh_XBd0I_YEVWOi1Jq4a0JCtJTrK0i_tl6yIUI3TgLtvwZcgo11D4JqNYfl3dYV5ABIbDFkQbY10P3UYvih5oz0HvHH5nwbN57WcYgGoPtnaHmzPXxByjC76tZnk7uLXIqBsjQByV2z8rd5Mep53TseZsj2Yeep4Kz53hTW_nP9N6fMF9oxX6BUlAZKIc1wBNIk-50lDqmEe0aCFUfBxzVogWC5kQpLk_GFrdZKUy-CX1cY62Kiulz69FI6I8Wbn2Qw6D9d8) Returns a disjoint pair of sets containing either point. Or a single set in case of failure. Test harness stolen from @solid.py. ## How? Being a finite topology `l` contains the intersections of all sets containing `p=I[0]` and of all sets containing `q=I[1]`. We need only check these. To obtain the intersections we use the fact that they are minimal within the subset of subsets containing `p` (or `q`). Note that it does not matter that typically some subsets will not be comparable (both `<` and `>=` return `False`). For the `min` function to succeed it suffices that there is a minimum, i.e. one element that is comparable to and smaller than all the others. [Answer] # [R](https://www.r-project.org), ~~60~~ 75 bytes *Edit: +15 bytes to fix bug* ``` \(t,p,q){for(i in t)for(j in t)if(p%in%i&q%in%j&!any(i%in%j))F=list(i,j);F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH64tSCxKLEksy89OLUkmLbpaUlaboWN71jNEp0CnQKNavT8os0MhUy8xRKNEHMLAgzM02jQDUzTzVTrRBEZakpJuZVamSC2ZqabrY5mcUlGpk6WZrWbrUQI28xfS0uKdJAtU4DrC5ZQ1MnWcMARBiCWTqGmpo6YFJBWUHXTgGqCqpCk4sYg3SMoEYBGUDDFHCYBpIlZJ4O2FVGOsZQSscEbjSYowmxBNV0hCaF_CJMUZA2AvZCvQC1zlTHDCoIcwCUqQOSATnBGM0JSPqpbZUpdqtA0ki-RTIArJGLiIBGiXelvPwSBYj6pJxUJTLiHSliSDOM1BDBaQ0k9S9YAKEB) Outputs a list of two separating sets, or `FALSE` if no separating sets can be found. [Answer] # [Python](https://www.python.org), 64 bytes -8 bytes, -3 bytes and -2 bytes thanks to `Value Ink`, `loopy walt` and `xnor` respectively. Also, thanks to `Neil` and `bsoelch` for their suggestions. Takes as input a list of sets, and returns a pair (tuples) of separated sets. In the `not separable` case it raises an exception. ``` lambda l,p,q:[(u,v)for u in l for v in l if{p}-u=={q}-v==u&v][0] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pZLBasMgGMdhx77DwNMa4Qsk6TpKQehlhz2D85C0ygKZsdaElpAn2SUwtnfanmZR00vrThXUP_L7f35_k49vdTJvtRw-BXn9aoyIVz-bKn8vdjmqQMF-TaMGWixqjRpUSlQhK1svS9GpPm4I6fZ93BLSPLSMJszX-b27t2gOBWwtTmdoHJQeuIkwdEkPXTrOBNKewbgyCACQeWTcwxDYGhks_AqPZ9xpZtWlxdf06BKe_C2TdVJgz615cYt5GWo2mCKdov7Xr4uXnkPaBsLo9ZPdmD9jM7Z2dqNPXtihdClNJCL3bTF25_y45cqgF7njx2eta32Jz2Vt0IGrXOdFxefY_yXD4Pc_) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ãʒ`åyIδ嫘J₄- ``` Inputs in the order \$topology, [p,q]\$. Outputs all possible results, so an empty list for 'not separable'. (Although all given test cases have \$p<q\$, it'll also work if \$p>q\$.) [Try it online](https://tio.run/##yy9OTMpM/f//8OJTkxIOL630PLfl8NJDq0/P8XrU1KL7/390dKxOtIGOIZA00jGGkDomEDEdCDuWKxrIjAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZoBRdoFMYa6tkb6@kkJiXolCSX5Cfk59eCRTR4VLyLy0BKoWoDP1/ePGpSQmHl1ZGnNtyeOmh1afneD1qatH9X6tzaJv9/2ggiNWJNgBiQxCtYxgLpxSQ5HSMIMJAGkNeB6TTSMcYQuqYwFSC2VDNcNUQkyCqTHXMICJQXVCWDkgczDUmU58pquuI8BG6G8G@MYT5CWQzpiq4AAU@NCIhHI1AfogFAA). **Explanation:** ``` ã # Cartesian power of 2 to create all pairs of the first (implicit) input-list # of lists (including pairs of the same topology-sets) ʒ # Filter this list of pairs of lists by: `å # Verify (the inverse of) rule 2: ` # Pop and push both lists separated to the stack å # Check for each value in the second list whether it's in the first list yIδå # Verify (a portion of) rule 1: y # Push the current pair of lists again I # Push the second input-pair of integers δ # Pop both, and apply double-vectorized: å # Contains-check «˜J₄- # Combine the checks of the two rules: « # Merge the two lists together ˜J # Flatten and join it to a string ₄- # Subtract 1000, to verify whether the string is of the form "0...01001", # where "0...0" comes from the check of rule 2 # and "1001" from the check of rule 1 # (only 1 is truthy in 05AB1E) # (after which the filtered list is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes Returns `nil` if no pair exists. ``` ->s,x,*y{s.product(s).find{[x]-_1|y-_2|_1&_2==[]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZJRToNAEIYTHznFBK20zUAKbdUXehEkm9aCkpBC2EUhdONBfGmiHsVD6Gm6y9JSq21TEnaWyfwf_8zu20eWz8rVe-jef-YsNO--HXNCscB-WVErzZJ5_sC6tGeF0WJeeYVvEntZmsRZEvuaOK7r-Zw3yteXpygO4DFgVAPJKLFPwIUrYtE0jpgGac4o6B1zdEvhsiq4WEoO5kTE0Auep3GXWiwzKm6g4flGD6GwWEIihLKOPiQZ6IuEAQ3SaTadxYHOdegA1YLFXNlY_Vx8VRXHaiBeW0a0OYcB2HDsESYahdaq0VF6EY8TtmpR2ehR_tvBoVpxtCHVey5Yzr5-q5Bdtp-iXCGVHYUa443KNOhmhzIv4cMa2SrOJ4x3CDJXm2rLZart9PR8dzrdO8DGWmNvfzInKcEvCqqJ25u5y3YPMg9R_p79MU8HOzpj2M4_FHWd1w) ``` ->s,x,*y{ # Anonymous lambda that takes three arguments # (y is splatted to make it a one-element array) s.product(s) # Cartesian product of the topology against itself .find{ # Find first pair that matches the following [x]-_1 # Subtract elements of U (_1) from an array w/ only x # (empty array if x is in U) |y-_2 # intersect w/ subtraction of V (_2) from y # (empty if y is in V) |_1&_2 # intersect w/ union of U and V (empty if no overlap) ==[] # If the intersection of these three is an empty array, # the conditions have been met } # End find call } # End lambda definition ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` f!+@FTs-VvzT* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8GCpaUlaboWa9MUtR3cQop1w8qqQrQgYlCpBTctootTSzQ0daoNdYxqdaqNdUyApKmOWS1YRAfCh7J0QOKxXBqGOgrGmhADAA) Returns a list of all possible separating pairs, `[]` if none exist. ### Explanation ``` f!+@FTs-VvzT*QQ # implicitly add QQ # implicitly assign Q=eval(input()) z=input() *QQ # cartesian product of Q and Q f # filter on lambda T -VvzT # vectorize subtraction on eval(z) and T s # sum (empty set for valid pairs) @FT # fold T on intersection + # add (empty set for valid pairs) ! # not (true for empty set) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 99 bytes ``` ~L$`(.)¶(.)$ ,-5G`¶O$$`.$\*($2).$\*|.+¶$$1¶Lw$$m`^(.$\*$1.$\*)$$[\S\s]+^(.$*$2.$*)$$¶$$1,$$2¶A`(.).$*\1 ``` [Try it online!](https://tio.run/##fY4xDsIwDEX3nuMPKTVpnVB2JpZKDB0pEAYGBhgAiQVxrBwgFwsOoWwgRd/@z9Z3Lofb8bznWOuq3qneUXx2cEqXwYugoGm7dMGvAKcxUTCllIeuggc4@O4OnNxWCQSLlMB66IfrpsrMZPbeJsAEv0jhQgeOkRpiajiVokhqxJnRMhkrb5aYqFihMpa@nVNmIqkn@3vU5qwcymlrTLLE6QDZD/l@4O8p8wI "Retina – Try It Online") Uses strings as sets. Takes input on separate lines but test suite splits on commas for convenience. Outputs all possible results. Explanation: The program itself is only one stage, but works by generating a program to do the actual work and then using the `~` flag to run the resulting program. As an example, it generates the following code for the last test case: ``` ,-5G` ``` Delete the two points leaving just the sets. ``` O$`.*(2).*|.+ $1 ``` Sort the sets containing the second point to the end. ``` Lw$m`^(.*1.*)$[\S\s]+^(.*2.*)$ $1,$2 ``` List most pairs of sets where the first set contains the first point and the second set contains the second point. (Some pairs where the first set contains both points are missed but they're not relevant anyway.) ``` A`(.).*\1 ``` Delete pairs that have an element in common. [Answer] # [Factor](https://factorcode.org) + `combinators.extras sets.extras`, 77 bytes Returns the first two separating sets found, or two `f`. ``` [| s x y | s s [| a b | a b disjoint? x a in? y b in? 3and ] cartesian-find ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nVJLTsMwEJVY9hTvAq1oTBGCRZdVF7BBXUUsnNSRDMQJtiu1KjkJm2zgTnAa_I0K1EgQK_PG4zfPM9a8vFW01I3sP05Wq9vlzeISD0wK9gjFtJqwrZZUOd-Ypw0TJVNoJdN610ouNMqmLrigRmJgX432I5hv71Zn_lNnp8G32HlM8LKBmf3C9XoZyIBnB3l-1wUNfMuOd8ScGc6HeIxF359ZJfKjiv_pzBLdHO90enBT6OdIFSR45MurkGRO6q1T-n_v0up0rxtdjS_er_NnKGyxg0UFs6Uo4O2aq_vGDNPcECi4mBta4ZBQscYdSio1U5yKccVtIIhmOSoulSaGYmaybRRD7krO4rDa5KZ2JzVtMfGZfe_xEw) * `[| s x y | ... ]` A quotation (anonymous function) taking named inputs s (for the sets), x, and y. * `s s [| a b | ... ] cartesian-find` Find the first pair in `s` that is true when `...` is run on it. Name the inputs (the two sets) to the quotation `a` and `b`. * `a b disjoint?` Is the intersection of `a` and `b` empty? (Leaves a boolean on the stack.) * `x a in?` Is `x` in `a`? (Leaves a boolean on the stack.) * `y b in?` Is `y` in `b`? (Leaves a boolean on the stack.) * `3and` Take the logical and of three objects. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` fƇⱮf/€Ṇf/¡ ``` A dyadic Link that accepts the topology as a list of lists\* on the left and the points as a list on the right and yields the smallest cardinality separating sets or `0` if no separating set is possible. \* Jelly has no sets. **[Try it online!](https://tio.run/##y0rNyan8/z/tWPujjevS9B81rXm4sy1N/9DC////R0fH6kQb6hgBSWMdEyBpqmMGEdGB8EEsiBiQr4MiC@bF/gdyTWMB "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/tWPujjevS9B81rXm4sy1N/9DC/4eXKx2d9HDnDKBQ5P//0dHRsTrRBkBsCKJ1DGNjdbgUEII6RhBhII2Q0AGpNdIxhpA6JjAlYBEoCygK1wAxBaLQVMcMIgLVCGJBxIB8HRRZMI@6hqB40BBqKrIVYC8YwrwGMpCIAKHQabHAWACHqQKMAhuoAHEHiDLFJodOxQIA "Jelly – Try It Online"). ### How? ``` fƇⱮf/€Ṇf/¡ - Link: Topology; Points Ɱ - map across {Points} with: Ƈ - keep those Sets of {Topology} for which: f - {Set} filter keep {Point} € - for each of these two FilteredTopolgies: / - reduce by: f - filter keep -> Intersection of the FilteredTopology ¡ - repeat... / - ...times: reduce {Intersections} by: f - filter keep N.B. [] is falsey so repeat zero times other lists are truthy so repeat once Ṇ - ...action: logical NOT ``` [Answer] # [Haskell](https://www.haskell.org), ~~89~~ 88 bytes ``` f t p q=head[x|x@[u,v]<-t#t,p%u&&q%v&&all(\[i,j]->i/=j)(u#v)];s#t=sequence[s,t];(%)=elem ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVTdbtMwFL7hKk9xpNLKlk7E0jGEumWi3IHEhAQXSK7FQusu2dIkjZ0qlfYm3PQG8TQ8wHga_JOU7ocuQJTE9mef7zs_tr9-jyN5JdJ0c_M5WRR5qeB9KdJqJiBOZkl2ASQW0Yx6nmlgNAIWcfBP4V20_iIgcjDjYJ4QznIVayOHknpUS6rRt5VUUH-r1Nx_efNpDgoKWIZmDauv61eswhU_8VVPYdGvBoNlfzUYRGlKJizBS-6fJs_CS0qq3oryY9lToRTLSmRTwSQqfkz6NBSpWDj-n09-qHUh4INQEGlt7a5ngY95kaf5xdqiZpbYJToyOz3W6JtMeUpINY2kkDZWQrZmY7QvxSZ0ZszHNhev8zylfMdUy3oAhDDGkR3oLzAtBpwjHCAEFPY8CGRSGtoSzk1c57CICpdDxho2zinFOxI4dCK6fUymg4RhuSOCJoohHro_Pm_lbF9LBghD2llky6Ytd4aG6rauC8zpHeELhzT6TQ8N7jw4pPt1f7P9l8xRJ5lmPduhstD9xHbZGA8kNtweuduxtBW8V5R_ZkRX-KAtv8nVHv7HGR_Ys3t97eTjX1RwSP_AyD1vESWZPsRFmWQKntrCkgmZxmJ6hVAKWaWKGsNkDhZsMFCxyFoiEKkUbj-0FqylMFdgDWsK19p3hVCjHqDjonDiw_Yq4e5W22xc-ws) Note that `head` is redefined for testing purposes only. If you remove the header, function `f` returns the two open sets if they exists, otherwise throws the exception `*** Exception: Prelude.head: empty list`. [Answer] # JavaScript (ES6), 79 bytes *-6 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects `(a,p,q)` where `a` is a list of sets. Returns either a pair of sets or `[ undefined, undefined ]`. ``` (a,p,q)=>[a.find(U=>b=a.find(V=>U.has(p)&V.has(q)>[...V].some(v=>U.has(v)))),b] ``` [Try it online!](https://tio.run/##rZTfb8IgEMff/SsuPiyQ3NDWuZelfdtfsOgL4YEqnS619Idxf34Hhc52M5q6kbQcB3y@3B3hQ55kvan2xfEx11vVpFFDJBZY0ijmkqX7fEtWUZxE3l5H8YrtZE0K@rBujZLGnDG2FqzWB0VO3YITNQ0T0bzwCQAHzgXyufkC22MgBMIcIYCxzeybzcCjfqAxdHDT34Pvow2iB0d76hAX7o9PnUzr8ZbxGkCAEF6Ff6NAV72h2X3Wc4E4nSU@O4/XtZbzmTEOZtuRO8Oi0zuj/hO/HOLtRBvOmWNdwwTeW/BhAqe5PkKtClnJJFPTXlA@sGs1GCehfkn4ggfdRbBZGil4Q@LCNR4dza1E/bn6IQi4JCEmLNXVq9zsCOESoUAoBYUoho3Oa50plul3khLJDrIgiZ3I1Se8qSNJzGPRrqcUaPMF "JavaScript (Node.js) – Try It Online") Patiently waiting for [new ECMAScript set methods](https://github.com/tc39/proposal-set-methods) ... ### Commented ``` (a, p, q) => [ // a[] = list of sets, (p, q) = integers a.find(U => // look for some set U in a[]: b = a.find(V => // and some other set V in a[], saved in b: U.has(p) & // such that p belongs to U, V.has(q) > // q belongs to V, [...V].some(v => // and there's not any value v from V ... U.has(v) // ... that also belongs to U ) // end of some() ) // end of inner find() ), // end of outer find() b // output the 2nd set ] // (if the 1st set is undefined, so is b) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` FθEΦθ∧№ιη∧№κζ⁼ι⁻ικ⭆¹⟦ικ ``` [Try it online!](https://tio.run/##TYw9DwIhGIP/yjtCUgfUc3EyRrdLTBwJAzk/jhwBQXDwzyN4DnZo2qdJh1HHwWtbys1HYoHTKRqXWK8f7GhsukYWQDt3YXufKzegkf@DCfSu4BCyts8298blb5h4Feic6uG9/QmQbFy1YVuKlFJBCiyrr7Cu3mEzE8z9l9C4gkCnyuJlPw "Charcoal – Try It Online") Link is to verbose version of code. Uses lists as sets. Outputs all possible results. Explanation: ``` θ List of lists F Loop over elements θ List of lists Φ Filtered where ι Outer list № Contains η First point ∧ Logical And κ Inner list № Contains ζ Second point ∧ Logical And ι First list ⁼ Equals ι First list ⁻ Removing elements in κ Second list E Map over results ⭆¹⟦ικ Pretty-print both lists ``` [Answer] # [Scala 3](https://www.scala-lang.org/), 89 bytes ``` (l,p,q)=>for{u<-l;v<-l;if u.contains(p)&&v.contains(q)&&u.intersect(v).isEmpty}yield(u,v) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=vVS9bsIwEB665SlODMiWDGqgVBWFSh06VGon1KFCGUxwkCuThNiJhBBPwsLSvlP7NPVPAqFSm05Ysu8u9_f5rC-7DxlSQfv7zyKZvbFQwTPlMWw8gDmLYKkNRLOFHMJ9ltH1dKIyHi8CPISXmCsY60jPK6iAaIieuFTTCVPTx1gFAdGn2Xh8Zx2o8hCoNBzA-D1XUefm8xUJkpKVDo6SbJOPOuK2MAePIO-GSaw0EIlS3G4XR3OlzbzLY8UyqaGjAne5fFimar1dcybmKCcFdg2-Lnagl0EaUsnk0GH6ARkMZnMYZGCcyAO7bKS5AsIWP7ospV_ZBHysdStJYxaBXi3RWM251mvVHoF-TSVwdVqs_IbL0r-WrMGoFRkQuK4FnDQ4fiBg41yP_hl6DBpG0zhAv47oX7M5jtk_nXh1oeYyf7_4mZ6nh20L7FmhGQZI8w1SAisMo46jBLasr1iSMZkLQ_DoEFl6NSWR81Zsw5Dqv4ISMWrFiQLJUprRmWCtKoUJyQ4xLte5tp7ZW8fR_d7Jbw) [Answer] # [Arturo](https://arturo-lang.io), 65 bytes ``` $[s m n][loop s'a->loop s'b->if∧∧a<>a--m b<>b--n a=a--b[a b]] ``` [Try it!](http://arturo-lang.io/playground?0All4g) Returns every valid pair. ``` $[s m n][ ; a function taking three arguments (s is sets) loop s'a-> ; loop over s, assign current elt to a loop s'b-> ; loop over s, assign current elt to b if∧∧ ; if the following 3 statements are true... a<>a--m ; m is in a b<>b--n ; n is in b a=a--b ; a intersect b is empty [a b] ; then return a and b ] ; end function ``` [Answer] # [Perl 5](https://www.perl.org/), 86 bytes ``` sub{($s,$p,$q)=@_;map{$u=$_;map[$u,$_],grep$p~~@$u&$q~~@$_&!(grep$_~~@$u,@$_),@$s}@$s} ``` [Try it online!](https://tio.run/##rZRNb@IwEIbv@RWzrkWINEINLXsAuc19pe1lbyaKUq1BrMA4CahdIfrX2bGdD6Dbql9IiccznvcZY2eMKpejg17DQ17qhZ5XEKpHo8rFSulNvgwnAZ@JQ7W93/V5hdwgLyKRZJNVbnZ8K7izJN8iz1Kcl8pw8/SU8G2PF3bMet/6zps5L5Inole1t89hEszWZT@QAFKmKC/pie2IcZoivPd3iRCDuAEJtRKkbSzFUwoOPYfGd5LOKaTQco4paHcyxCv/xuuG5zy1Rd4X6DHCsKG0SrRWdlObfEz0e/KkEX73nppsLe@jOZ5E3YyUiXhVEzslcMh23qyVp4JUx9cWMjopxPpfLaRDpc/O4AP36PykSeKC6fUGKmXyMr9fKtbttd7vBzHNMR8j1DmivjNxc5fsX/B24FsQn/wk/ofIn@/ik5fiRUS0C2wVq79th8KEelgEAqjdTOogJHNKE9Djs66TtUFOCRT8vTL9qUvuIj7NR8iuI6Zc6I1PU4VfdAvs7geDMbCfd7@AzOOVjAzBjXUUghd2rAQbWFleRQM21dZFcmMn6qekOnbaU80w2AfUhm0huz/rhQ4xRNuESzW7DWXolGx3HYRpOObZPsn2h38 "Perl 5 – Try It Online") ]
[Question] [ The [persistence](https://en.wikipedia.org/wiki/Persistence_of_a_number) of a number \$x = d\_1d\_2d\_3...d\_n\$, with \$d\_1 \ne 0\$, under some function \$f : \mathbb N\_0 \times \mathbb N\_0 \to \mathbb N\_0\$ is defined as the number of applications of \$f\$ to the digits of \$x\$ before it reaches a single digit integer. That is, if we have the map $$I\_f: (x = d\_1d\_2d\_3...d\_n) \mapsto f(f(...f(d\_1, d\_2), d\_3), ...), d\_n),$$ the persistence is defined as $$P\_f(x) = \begin{cases} 0, & x \in \{0,1,2,3,4,5,6,7,8,9\} \\ 1 + P\_f(I\_f(x)), & \text{otherwise} \end{cases}$$ Some examples include: * [Additive persistence](https://en.wikipedia.org/wiki/Digital_root#Additive_persistence): \$P\_+(2718) = 2\$, \$P\_+(5) = 0\$ and \$P\_+(2677889) = 3\$ * [Multiplicative persistence](https://mathworld.wolfram.com/MultiplicativePersistence.html): \$P\_\times(68889) = 7\$, \$P\_\times(25) = 2\$ and \$P\_\times(8) = 0\$ * Minimal/maximal digit: \$P\_{\min}(1734) = 1\$, \$P\_{\max}(48203) = 1\$ and \$P\_{\min}(5) = 0\$ --- Given a blackbox function \$f : \mathbb N\_0 \times \mathbb N\_0 \to \mathbb N\_0\$ and a positive integer \$x = d\_1d\_2d\_3...d\_n\$, where \$d\_i\$ are digits with \$d\_1 \ne 0\$, output the persistence of \$x\$ under \$f\$. You may assume that \$f\$ will eventually reach a single digit number when repeatedly applied to \$x\$'s digits. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins. ## Test cases ``` f(x, y), x -> output x + y, 2677889 -> 3 x × y, 68889 -> 7 x ** y, 29 -> 4 φ(x × y), 736 -> 2 (φ is the Euler Totient function) x/2 + (x × y), 1234567 -> 5 (using floor division) |x - y|, 9 -> 0 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes ``` {#1_(x/.'$:)\} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdj0FuwjAQRfc+xVQg1XESXByI0yzYcYPuQtRFG7eWUIyIXdkibLkCB+oBuFJtE7VSvZr/5vvPjKhPs+UrtnTxOK+T3Rkh0aRtw0rOq+q59Yq0TVlN9YlQN7Nn379LbIlL0pw9BLZkxWpd8tgYaV7vbO489k5EkcA2A5dkYCHfgDL6YDSykILLYBoWGoVn39cA48yAuEeERF/UK3S74LvLx/GiDJDB/4dvF5AD6M8OtmbfHeFFadn1GoTp37RUfYIsZX6Bv6zpgJC3/o0xg+w/QOyVOsK7/JJD/Dr6M8CNGcSVnn4AYkNXKA==) Uses `.'$:` instead of `10\` because the latter gives `()` for 0 (and `*/` of `()` is 1), breaking the `(*, 68889)` test case. ``` {#1_(x/.'$:)\} Curried function, 1st arg: f, 2nd arg: n ( )\ repeat and collect starting from n until convergence: .'$: digits x/ reduce by x #1_ length minus 1 ``` [Answer] # [Python](https://www.python.org), ~~70~~ 71 bytes ``` p=lambda f,n:n>9and-~p(f,(i:=lambda n:f(i(n//10),n%10)if n>9else n)(n)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY33QtscxJzk1ISFdJ08qzy7CwT81J06wo00nQ0Mq1gUnlWaRqZGnn6-oYGmjp5qkAyM00BqDY1pzhVIU9TI09TE2LcvoKizLwSjQINqMYKnUqrCu1KHQUjc0MLmCKY3QA) Takes in an anonymous function `f` and an integer `n`. --- +1 bytes from [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for noticing an error when `n=0` in `i`. # [Python](https://www.python.org), 65 bytes ``` p=lambda f,n:~-len(n)and-~p(f,reduce(f,n)) from functools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3HQtscxJzk1ISFdJ08qzqdHNS8zTyNBPzUnTrCjTSdIpSU0qTU4GMPE1NrrSi_FyFtNK85JL8_JxihczcgvyiEi2oQXoFRZl5JRoFGlDjKnQqrYpLijRAghWa2iCqUlNTR8nI3NBCSVMTogvmDAA) Takes in an anonymous function `f` and a *string* `n` representing an integer. # [Python 2](https://docs.python.org/2/), 42 bytes ``` p=lambda f,n:~-len(n)and-~p(f,reduce(f,n)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN7UKbHMSc5NSEhXSdPKs6nRzUvM08jQT81J06wo00nSKUlNKk1OBjDxNTagOvYKizLwSjQINqL4KnUqr4pIiDZBghaY2iKrU1NRRMjI3tFCC6YLZBwA) Same as above. Posted based on the recommendation of [@tsh](https://codegolf.stackexchange.com/users/44718/tsh). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` £‡¥RİL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCI2ODg4OSDOuzJ8KjsiLCLCo+KAocKlUsSwTCIsIiIsIiJd) Takes inputs from the stack due to technical limits. ``` £ # Store function to register ‡-- # Next two elements as a function... R # Reduce by (implicit digits)... ¥ # The function stored in the register İ # Apply that function until the result doesn't change, not including the initial value L # Count the number of different values. ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 38 bytes ``` g->p(n)=if(n>9,1+p(fold(g,digits(n)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY9NDoIwEIWvMmFhWi0LilJYwEWwmhpobUKw4SeBs7ghMcYzcRsLslDiLNppv_feZO4vIyp9VmZ4SIifbSPdcNwoNzGoxLGWqEwi4u0MkrciQ4pkWummtszWoh6FMUWPBLgJmEqXjW2d6eGARCL1OLYn5RgTSFPUEejxRDvYQU-ABoyFYcQt_GbbiQXhH3KaXavvvC3yylw1mp12EvODtfEI1I5coj3q7w8B-9WIS20D3Dkg4nxZcBg-9xs) A curried function that takes input as `(f)(x)`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Dç/$ƬL’ ``` [Try it online!](https://tio.run/##y0rNyan8f3j6f5fDy/VVjq3xedQw8////2YWFhaWAA "Jelly – Try It Online") Takes a function from the previous line and a number from an argument. ``` Dç/$ Convert an integer to its decimal digits and reduce by the input function Ƭ Repeat and collect the results until the results are not unique (repeats after reaching a single digit number) L’ Get its length minus 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔÅ»X.V}θ}N ``` [Assumes the function is defined as a string in variable `X`.](https://codegolf.meta.stackexchange.com/a/13707/52210) [Try it online](https://tio.run/##yy9OTMpM/R/6/9yUw62HdkfohdWe21Hr9/@/FpeZhYWFJQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQQuj/c1MOtx7aHaEXVntuR63ff53/0dFK2ko6RuaGFrE6YKYplDYyMze3sLAE8bSUdMwsEGwjUygDrOVRw6zD85V0DM2NTZC4JhZGBsZIfLCWXKBeiCGHpyrpmBubgdjFh1ZqHVpndHg70E5DI2MTUzNzkPC5jUo6lrGxAA). **Explanation:** ``` Δ # Apply until the result no longer changes, # using the (implicit) input-integer in the first iteration: Å» # Reduce the digits of the integer by, keeping all intermediate results: X # Push function-string `X` .V # Evaluate and execute it as 05AB1E code }θ # After the reduce-by: only keep the resulting last value }N # After the until-no-more-changes-loop: push the last 0-based index of the loop # (which is output implicitly as result) ``` Unfortunately, 05AB1E lacks functions, so we'll have to store the 'black box function' in a string and execute it as 05AB1E code with `.V`. In addition, 05AB1E's regular reduce-by builtin `.»` only works with single builtins (e.g. `.»*`), so we'll have to use the reduce-by that keeps intermediate results and then just keep the final result, in order to have a larger body with multiple builtins (pushing `X`, and executing as 05AB1E `.V` in this case). (e.g. `Å»*}θ`). [Answer] # [Haskell](https://www.haskell.org/), ~~47~~ 44 bytes ``` f#n=sum[1+f#foldl1 f[read[x]|x<-show n]|n>9] ``` [Try it online!](https://tio.run/##TctLCoMwGATgfU/xQ7owSha@EoXqRWwKQgwGY1K0jwjePTV0426Yb2bs12nQ2nuJTLO@5y5NJJJWC52C7JahF53ju7uRdbRfMHw3bc393CsDDQh7geeizAuuECUYZZSxqqqBEMhPEmNEq9BDEHaSx/EJ9V@Kk9wdbKSNhPrAkXDi4g2jNMuLkrKwLf0P "Haskell – Try It Online") * saved 3 Bytes thanks to @xnor `#` is an infix function taking the function to apply as *f* and a integer number as *n*. Uses the trick [shorter conditionals when one outcome is the empty list](https://codegolf.stackexchange.com/a/150792/84844) combined with a recursive approach by @xnor idea. If *n* > 9 yeld 1+ result of *#* with number transformed, the result is the sum. [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Black-box function is pre-assigned to variable V, although functions that consist of a single basic operation can be passed via input variable V. ``` @=ìrV)¨A}fÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=CkBYKlk&code=QD3sclYpqEF9ZsQ&input=Njg4ODk) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 90 bytes ``` X/Y/Z:-Y<10,Z=0;number_codes(Y,A),maplist(plus(48),[F|B],A),foldl(X,B,F,S),X/S/H,Z is H+1. ``` [Try it online!](https://tio.run/##XZDfToMwGMXv@xS9MWm10ME2wPkn2RKXXS6ZF4DRhUHBJh0ltLgbr309HwkLEubsXc/v@07PaVVLIQtLnXjbhjSi8cKK7p0JiR8md2VzPLB6n8qMKRSRJSbHpBJcaVSJRqFZgMnL@nP12pFcikygkKzImuwwCemObkgMuYKbG8duj00HIxLjhdWr4XVkg0qeLtXoLbSBlnpf1SzrkAFOB4r099rTcWc7OJGkKGpWJJrtEyFQKptSE3Rg@sRYiRyy7RKOtkuyxdjsGy@m9PwyAYoodfENMq5mIDmojOf55YgRUWgZ3HbfQF3P94PglsY2vILWI5wCG5i61Av@qj7o61L3LM1A34b6U2/UXPj/oO@v7lH9zuBTI1gNn6XmrNQwb8pUc1liMBShjjudzT1/NJuPHo3iZQFzIWUNM/7B1bA39KPnUBNg/wA "Prolog (SWI) – Try It Online") 90 bytes by Steffan. [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` ->g,n{n>9?1+f[g,n.digits.reverse.reduce(&g)]:0} ``` [Try it online!](https://tio.run/##Vc5NDoIwEAXgvadoYmKotEUKtGi0HoSwoKUgGyT8GA327FhdaF3NJN97mekn@Viq04JFjdq5Fftz6FeZ3UnZ1M04kF7fdD9oO8tJaW9Tw/ywM0t3aU5YqNkLCVGQqOvUjvPz/lSkVqV3h0dqzGrVgSrDokByLnxpEGWcp@k@B@sgAFhErm@ts9RRwP/47fSHsYP2l8z2c4MAj9g3Qt1@QP3PiZBGccL4N5Q4Ia/AEpJCDgb9Du2WFw "Ruby – Try It Online") [Answer] # JavaScript (ES6), 48 bytes Expects `(F)(n)`, where `n` is passed as a string. [Returns *false* for *0*](https://codegolf.meta.stackexchange.com/a/9067/58563). ``` F=>g=n=>n>9&&g([...n].map(x=>+x).reduce(F)+'')+1 ``` [Try it online!](https://tio.run/##fdDdboIwFAfwe5/ixEQ8HVBHUYrL2l2YeLcnWHZREPFrhYhb8OlZWy4WF7E3PTnt79@Pg/pRTX7e15dQV5ui24puLWQptJBaLj2vxA9Kqf6kX6rGVki/JfRcbL7zAtfEn06JH3X1bg8CUAdwNLMmICQcwxA8D3BlV1QAmetm8AYrzAJQMLGtF1O8AiPOEvDBRPX1aJRXuqlOBT1VJW4R2wCuLqM1264ExyzhPE2XY0LgZsxmED/ATw4n6T3qMH@Ee83uUYfng9i@rD/dBPA4@Z9gMBvERkoJkf2hv5CIxfNFwm2QwYtB/K4uO6qyxsiwl7fXN/i5@wU "JavaScript (Node.js) – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes ``` {XXr[}j1ia1jC~qlnfi ``` [Try it online!](https://tio.run/##SyotykktLixN/V9dUJwT/786IqIoujbLMDPRMMu5rjAnLy3zf214zn89bQUjM3NzCwtLLj0tBTMLEENLS8EIxI2LS3P2c6ouSMksq82NNsyy1y1I0dMqSFEwNzbjyvKq0NfTyjLS0wcaYWhkbGJqZs6lp5uYpGAJAA "Burlesque – Try It Online") ``` {XX # As digits r[ # Reduce by F }j1ia # Insert F before reduce 1jC~ # Evaluate infinitely qlnfi # Find first single digit index ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 25 bytes ``` {𝕩>9?1+𝕊𝔽˜´⌽'0'-˜•Fmt𝕩;0} ``` Defines a 1-modifier that can be applied to a dyadic function F, turning it into a monadic function that takes a single number and returns its persistence under F. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=X3Ag4oaQIHvwnZWpPjk/MSvwnZWK8J2UvcucwrTijL0nMCcty5zigKJGbXTwnZWpOzB9Cgrii4ZfcCAyOQ==) ### Explanation Here `𝔽` is the original dyadic function, `𝕊` is the modified function, and `𝕩` is the single argument of the modified function. ``` {𝕩>9?1+𝕊𝔽˜´⌽'0'-˜•Fmt𝕩;0} { } Block (which is a 1-modifier due to the presence of 𝔽 in it) 𝕩>9 Does the argument have multiple digits? ? If so (recursive case): •Fmt𝕩 Format the argument as a string '0'-˜ Subtract '0' from each char, giving a list of digits ⌽ Reverse ´ Right fold on: 𝔽˜ 𝔽 with reversed arguments 𝕊 Recurse on that value 1+ Add one to the result of the recursive call ;0 Otherwise (base case), return 0 ``` Unfortunately, BQN doesn't have a left-fold modifier. Scan works left-to-right, but then it costs two bytes to extract the last value from the result list. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 66 bytes ``` (load library (d P(q((F N)(i(l N 10)0(a 1(P F(foldl F(to-base 10 N ``` Defines a function `P` that takes a function `F` and a number `N` and returns the persistence of `N` under `F`. [Try it online!](https://tio.run/##FYk7DsIwEAV7TvHKtwVSYn43SGnlChstSJY2GJKA4tMbU81oZkvP4ml91UrPavA0LbqUAw0j3@SAKEx0RPSddFT0HDHwkd28ccvHSdd7m4i1HbrOkym4owioZgG09A3YEVqYP/7XIiLow@l8ud6k/gA "tinylisp – Try It Online") ### Explanation ``` (load library ``` The library contains definitions for `foldl` and `to-base`. ``` (d P(q((F N) ``` Define `P` to be a function of two arguments, `F` and `N`. ``` (i(l N 10)0 ``` If `N` is less than 10, return 0. Otherwise... ``` (a 1(P F ``` Add 1 to the result of calling `P` recursively on `F` and the result of... ``` (foldl F(to-base 10 N ``` Convert `N` to its base-10 digits and left-fold on `F`. ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. Related to [AoC2017 Day 3](https://adventofcode.com/2017/day/3), Part 2. --- You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: ``` 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... ``` As a stress test on the system, the programs here clear the grid and then store the value 1 in square 1. Then, in the same allocation order as shown above, they store the sum of the values in all adjacent squares, *not* including diagonals. So, the first few squares' values are chosen as follows: * Square 1 starts with the value 1. * Square 2 has only one adjacent filled square (with value 1), so it also stores 1. * Square 3 is the same (diagonal neighbors don't count), so it also stores 1. * Square 4 has squares 1 and 3 as neighbors and stores the sum of their values, 2. * Square 5 has square 4 as its only neighbor, so it gets the value 2. Once a square is written, its value does not change. Therefore, the first few squares would receive the following values: ``` 12 12 10 8 7 14 2 2 1 7 17 3 1 1 6 20 3 4 5 5 20 23 27---> ... ``` What is the first value written that is at least as large as the input (a positive integer)? Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` 1 -> 1 2 -> 2 9 -> 10 18 -> 20 50 -> 55 100 -> 111 200 -> 214 500 -> 552 1000 -> 1070 1070 -> 1070 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes ``` Ժƌ∏‚âî‚ü¶¬π‚üߌ∑Ôº∑‚Äπ‚åàŒ∑Œ∏¬´‚äûœÖŒ∑‚âîÔº•Œ∑Ôº•‚ÆåœÖ¬ßŒºŒªœÖ‚âîÔº•¬ßœÖ‚Å∞Œ£‚Ķ¬ßœÖ¬±¬π‚äŒ∑¬ªÔº©‚å䌶Œ∑¬¨‚ÄπŒπŒ∏ ``` [Try it online!](https://tio.run/##XU/LCsIwEDzbr8hxAxXas6dSEAq2iB7FQ6yLCSRpm4cPxG@PaasH3cuyOzuzMy1npu2YDKHSvXeNVyc0MNBVUlgrLhoO@TElPM43LiQS2KC1ULO7UF4BpykZKCXPZLH1loOfTxcfbs164CkZ2w6vaCyCj4zCVfqMd1ApkZTGhf/jfA@iXBbhffxUPlqJJe9@wAYvzCHko0alW4MKtcMzjKp0tvJKtkZoByWzDmqhJ9trIV1MGa01nZsTiSnIWKsQ8iwLy6t8Aw "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation: ``` Ժƌ∏ ``` Input the target. ``` ‚âî‚ü¶¬π‚üߌ∑ ``` Start with the middle cell. ``` Ôº∑‚Äπ‚åàŒ∑Œ∏¬´ ``` Repeat until the target is reached. ``` ‚äûœÖŒ∑ ``` Add the latest row to the grid. ``` ‚âîÔº•Œ∑Ôº•‚ÆåœÖ¬ßŒºŒªœÖ ``` Rotate the grid. ``` ‚âîÔº•¬ßœÖ‚Å∞Œ£‚Ķ¬ßœÖ¬±¬π‚äŒ∑ ``` Take the cumulative sum of the new last row. ``` ¬ªÔº©‚å䌶Œ∑¬¨‚ÄπŒπŒ∏ ``` Output the smallest value not lower than the target. [Answer] # [J](http://jsoftware.com/), 39 37 bytes ``` {{y(<:<./@#]),|:@|.@(,+/\@{:)^:y,.1}} ``` *-2 thanks to Olius's idea of using direct definition `{{ }}` instead of a tacit verb* YAPONA - Yet Another Port of Neil's Answer. To save bytes, we repeat the iteration `<input>` times -- which is always enough, and usually returns much more than we need -- then find the first valid number within that result. No TIO for this one because the TIO J version is too old and doesn't have `{{ }}` yet. I tested locally though and it works. TIO'd tacit version below. # [J](http://jsoftware.com/), 39 bytes tacit solution with TIO ``` (<:<./@#&,])]1&(](,~+/\.@{.)@|:@|.),.@1 ``` [Try it online!](https://tio.run/##DcMxCoQwEAXQ3lN8FDTB7DgjCBpcGBCsrKxNJYrYeIAVr571wTtjSsWOr0cBB4Z/fwjDPI3R9L6nSrPcBRskN8G4p6wW0h9Zvb3eZB2pRJts63FhT0sIanSQFg1DmFG/G@b4Bw "J ‚Äì Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~80 78 75~~ 66 bytes ``` ->n,*r{(n+a=1).times{|x|r<<a;(1..x/2).map{a<n&&r<<a+=r[1-x-x]}};a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6uoWiNPO9HWUFOvJDM3tbi6pqKmyMYm0VrDUE@vQt9IUy83saA60SZPTQ0krG1bFG2oW6FbEVtba51Y@79AIdpQx0jHUsfQQsfUQMfQwEDHCIhNDcBsEGFuEAsyQkMtTfM/AA "Ruby ‚Äì Try It Online") ### Explanation (if it still matters): * We need at most (n+1) segments to find the number (n=2,3,4 can't be found on the 2nd 3rd and 4th segment). * Length of segments (removing corners) is 0, 0, 1, 1, 2, 2, 3, 3 ... * In the corners we can reuse the previous value: x[n]=x[n-1] * For the other cells: x[n]=x[n-1]+x[n-m] where m is increased by 2 for every side. Maybe there is a way to skip the corners? we don't need the repeated values to find the final result, only to calculate the other intermediate values. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 96, 94, 92 (@dingledooper), 90 bytes (@xnor) ``` def f(i): *T,s=1,;t=T,[1],[1] while i>s:T,*t=*t,[s:=s+x*(i>s)for x in[0,*T,0]] return s ``` [Try it online!](https://tio.run/##NVBBbsMgELzvK1acwN1W4NZq6oi8gpvrQ6XaClKKEVA19efdxWkOy87szMCK@FvOS3g@xLRtn9OMs/SqB2wcZWvoWKyjwYy1AH/O/jKhP@XeUVNsU2jIvc0P10byUM1Lwiv6MGjiuB45kabynQLmzVkhhMHHExpoa2vhbWcazGHnGjpdQdeB0Tsyhr032JoXlv/1thpuDv3KeT7uhB8BZ4evjyh9KFSecrz4IkXVhVJYVyy8Irq78h6EGqHOPS270q@2fsIxJr5CelpptXZRsP0B "Python 3.8 (pre-release) ‚Äì Try It Online") Older versions [Try it online!](https://tio.run/##NZBBbsMgEEX3c4oRKyCkAlqrqSNyCnbUi0q1FaQEIyBq6su74DQb@H/en2FE/C3nObweYlrX73HCiXrWA3IrslHiWIyzw05z59QwAP6c/WVEf8q9FbwYXoTLvcm7O6e1yKY54R19cFLUAbJ1pLHcUsC8WkMIUbg/oQLdLg0fm5OgDpuX0Mkmug6U3JRSNfuQWr1V/M91CzwS8r321@Np6iNgjbt@RepDEeUlx4svlDROGMO2Yqkron2Sz0DYAK3uxbyRfjHtG44x1RHUi0UsxswM1j8 "Python 3.8 (pre-release) ‚Äì Try It Online") [Try it online!](https://tio.run/##NZBBbsMgEEX3c4oRKyCkAlqrqSNyCnbUi0q1FaQEIyBq6su74DQb@H/en2FE/C3nObweYlrX73HCiXrWA3IrslHiWIyzw05z59QwAP6c/WVEf8q9FbwYXoSjuTd5d@e0Vhmb5oR39MFJUUfI1pPGcksB82oNIUTh/oQKdLs0fGxOgjpsXkInm@g6UHJTStXsQ2r1VvE/1y3wSMj32l@Pp6mPgDXu@hWpD0WUlxwvvlDSOGEM24qlroj2ST4DYQO0uhfzRvrFtI84xlRHUC8WsRgzM1j/AA "Python 3.8 (pre-release) ‚Äì Try It Online") [Try it online!](https://tio.run/##NZBBbsMgEEX3c4oRK6CkAqdWU0fkFOwoi0q1FaQEIyBq6su74DQb@H/en2FE/C3nOewPMa3r9zjhRD0bALkRRWS959Yq54Q6FiudNoA/Z38Z0Z/yYAQvmhdhaR50frlzWquMTXPCO/pgpahDpHOAaSy3FDCvRhNCFO5OqKBrVwcfm5OgDpuX0Msm@h6U3JRSNfuQnXqr@J93LfBIyPfaX4@nqY@A0fb6FakPRZTXHC@@UNI4YQzbiqWuiOZJPgNhDlrdi3kjw6LbVxxjqiOoF4tYtJ4ZrH8 "Python 3.8 (pre-release) ‚Äì Try It Online") This keeps a running sum `s` and the four sides of the growing rectangle/spiral double accounting for corners. `T` holds the "active" side, `t` the three others. [Answer] # JavaScript (ES6), 73 bytes ``` n=>eval("for(j=k=0,a=[t=q=1];q<n;)a.push(q+=j--?a[++t-k]:![j=++k>>1]);q") ``` [Try it online!](https://tio.run/##Zc5NDoIwEAXgvadAVm0q0DY2/uDgQQiLRkEtpKWAXB@BBIgwy/nyXp6Srawf1adsPG2eaZdBpyFKW1kgNzMVUpADPUiIG7DAktDedIilX37rN7IElOfdZUxI4@XJdR8rICSPIpbg0Lq4exhdmyL1C/NCGWIYO/0FgcN2/8Jn4Su5LBm6InYebQitSdCJhFin6GhDIdvMmI2z46ZyMiH4tnPAceRpM7N/Ldj9AA "JavaScript (Node.js) ‚Äì Try It Online") ### Commented This is a version without `eval()` for easier formatting. ``` n => { // n = input for( // main loop: j = // j is the length of the current segment minus 1 k = 0, // k is incremented after each segment // (which means that it holds the number of turns) // the length of the next segment is floor((k+1)/2) a = [ // a[] is used to store the sequence t = // t+1-k is the index of the neighbor cell in the // previous layer of the spiral q = 1 // q is the current value of the sequence ]; // q < n; // we keep going until q >= n ) // a.push( // append to a[]: q += // the updated value of q j-- // decrement j ? // if we haven't reached the end of the segment: a[++t - k] // increment t and add the value of the // neighbor cell in the previous layer : // else (this is a corner): ![ // leave q unchanged j = // increment k and update j to ++k >> 1 // floor(k/2) ] // ); // end of push() return q // end of for(); return q } // ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 91 bytes ``` f=(n,o=p=[X=x=y=0,Y=v=1])=>n>(o[[x+=o[p]?X:X+=Y+(Y=-X),y+=Y]]=v+=o[p=[x+Y,y-X]]|0)?f(n,o):v ``` [Try it online!](https://tio.run/##Zc7dCoIwHAXw@57Cyw1nbtKojL@@xobsQkyjECcZQ6F3Nz9Aze1q7LdzOK/UpE32ftYfr9L3vO8LQBXRUEMioIUOKJFggCkMURUhnSStCzqpVSxC4YJ0kQRPYNINd6XATAjDJ0k6Tyj1pTguxkYcmj7TVaPL/FjqByoQw/jmDMf3HXb4p2ClYEfXTYrujF1mHGN743Qxzvc5OuPYyawtKwbsZLUuyHlg1046TT1bY4enjfY/ "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 87 bytes ``` n->a=Mat(1);until(d=[b|b<-c,b>=n],s=0;a=Mat(Vecrev(concat(c=[s+=b|b<-a[,1]],a~))));d[1] ``` [Try it online!](https://tio.run/##JYrBCoMwEER/ZfGU0A0kgtBi1z/otZeQQ4xaBFmD2kKh9NfTWOfwZh5M9MuoHjENQIlV4@nmN2Fk/eRtnERHtv20VxWwbYgdrqTr43Lvw9K/RJg5ZAtk1xP9r96icQ79V@bUnTUu@Rint2BQDcRl5C3PYpcCBsFSIliDUCJcEMwZodK5dUa5o9KHaifTDw "Pari/GP ‚Äì Try It Online") A port of [@Neil's answer](https://codegolf.stackexchange.com/a/238259/9288). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1¬∏¬∏IF√∏√≠¬§Œ∑O¬™}Àú íI@}√ü ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/238259/52210). [Try it online](https://tio.run/##yy9OTMpM/f/f8NCOQzs83Q7vOLz20JJz2/0Prao9PefUJE@H2sPzgbIWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/w0P7Ti0Izqq0kH58I7Daw8tObfd/9Cq2tNzTk06tM6h9vD8/zr/ow11jHQsdQwtdEwNdAwNDHSMgNjUAMwGEeYGsQA) (the test suite loops until the result is found (`IF` replaced with `[ZI@#`), since looping \$n\$ times will time out for the larger test cases). **Explanation:** ``` 1¬∏¬∏ # Start matrix at center [[1]] IF # Loop the input amount of times: √∏√≠ # Rotate the matrix once clockwise: √∏ # Zip/transpose; swapping rows/columns √≠ # Reverse each row ¬§ # Get the last row (without popping the matrix) Œ∑O # Get the cumulative sum: Œ∑ # Pop and push a list of its prefixes O # Sum each inner list ¬™ # Add this row to the matrix }Àú # After the loop: flatten the matrix to a list  í # Filter this list of integers by: I@ # Keep those larger than or equal to the input }√ü # After the filter: pop and push the minimum # (which is output implicitly as result) ``` `íI@}√ü` could alternatively be `I<LK√ü` (push list \$[1,input)\$, remove those values, minimum) or `{.Œî>‚Äπ` (sort, find first \$n\$ which is \$input\lt n+1\$) for the same byte-count. [Answer] # [Rust](https://www.rust-lang.org/), 155 151 bytes ``` |a|{let(mut s,mut v)=(1,vec![0,1,1]);for i in(0..).flat_map(|i|{s+=i/2;(0..1).chain(s-i/2..=s)}){let r=v[i]+v[v.len()-1];v.push(r);if r>=a{return r}}0} ``` [Try it online!](https://tio.run/##XVHLbsMgELznK9Y5RNBgClaiPiynH2JZEYqwguRQF7B7sPl2F6yqDdkDaGZndgdhBuuWVsNNKI0wTBsI1UkHLVSwzGKeAkC3wYEl8RxxhTgZ5SWrGeGEN7hsPw0oCHZGKaZtJ9z5Jno0q3my@0o9F2XscEwv17jE5oGitLLY4zgcTDXWqtmP9Ug7GULkvClH2g/2igwuVQvmVInJSDcYDcZ75pcYslyjxuVI6X5wBIS239LgEAV29dqNFeICx@QfFwSKe/wW@uye4K9BkTBHRuB4TDQsUJyngyNX8EPqXK3Fgzea2Uu6NeCEbX5/I1ZvlHadztB2ev/wkJ8g3lsC6dPLP4OwVhp3ll8Z2rXoaZXhB53f@OUH "Rust ‚Äì Try It Online") This works by generating [A334742](https://oeis.org/A334742) (the actual numbers in the spiral) using [A265400](https://oeis.org/A265400) (indices of adjacent squares), which is generated using [A004526](https://oeis.org/A004526) (length of each corner, which increases every two rotations). * -4 bytes by replacing the outer iterator with `for` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 31 bytes [SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {‚äë‚â•‚üúùï©‚ä∏/‚àß‚•ä{‚åΩÀò‚çâùï©‚àæ+`‚äè‚åΩùï©}‚çüùï©‚âç‚âç1} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KKkeKJpeKfnPCdlaniirgv4oin4qWKe+KMvcuY4o2J8J2VqeKIvitg4oqP4oy98J2VqX3ijZ/wnZWp4omN4omNMX0KCkbCqDHigL8y4oC/OeKAvzE44oC/NTDigL8xMDDigL8yMDDigL81MDAgI+KAvzEwMDDigL8xMDcwIHRvbyBzbG93Li4gbWF5YmUgdHJ5IG9uIENCUU4K) Similar idea to Neil's answer. Some combinators come in really handy here. [Answer] # TypeScript Types, 389 bytes ``` //@ts-ignore type a<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type b<T,N=[],U=[]>=T extends[infer A,...infer T]?b<T,[...N,...A],[...U,[...N,...A]]>:U;type c<N,A=[[0]],B=A,C=A,D=A,E=b<A>,F=E[number]>=1 extends(F extends N?1:0)?a<Extract<F,N>>:E extends[...{}[],infer L]?c<N,[L,...B],C,[...D,A[0]],E>:0;type M<N,m=[]>=N extends m["length"]?c<[...m,...0[]]>["length"]:M<N,[...m,0]> ``` [Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgGkBeAa3R2QDNDyA+W8w9AD3DpEAE0jsA-I2Zse-QSLHVx5AFyJ0AN3SoVABgDcuAoQBGFSgDlaAbQC6lAKo3bXWQKGjrsRC22EAgpQAdCHevqjstuJmVNYhQRbBIf72cSEOlGkJSUEpLioOhvhEAMakif421rq29gBCtIEAwo2UACKtAKK0Zv4clABitJ3WiACuALYm2i60AIy87goAFAOL8qKEFuJzegCU4mSdAqjEJeCkA5YcHCqd6x6QWQDeAL52lGF+ADJRZYnWb45Or2JqZeJtSj+aq1SidW4GIxEACy5UoE2cXAsDwUhAm1gARAAbITwcAACwJf1IWQmOV0dhchJJiDJlNsKlRAPidJqHEw2GK7F0hFohFRc35IEIMoAeuJBcZyAsxaiAExS4AywjyxVEchq0Xi0gATk12t1SPYAGYjRKABzmuUKq3kAAsdtIAFZdE6dS6heQvZ65rpfZhpc69ewAGyetVhv2WwMAdk9PvDkf9mCAA) ## Ungolfed / Explanation ``` // Filters a union of tuples for those with the shortest length type Shortest<T, K = keyof T> = T extends T ? keyof T extends K ? T : never : 0 // Turns [a, b, c, d] into [a, a+b, a+b+c, a+b+c+d] type CumSum<T, N=[], U=[]> = T extends [infer A,...infer T] ? CumSum<T, [...N, ...A], [...U, [...N, ...A]]> : U // Extends the spiral one side at a time until one of the numbers is matches N // If the spiral is // a b c d // e f g h // i j k l // '-> // (where g was the start) // It will be represented as A=[i,j,k,l] ; B=[l,h,d] ; C=[d,c,b,a] ; D=[a,e,i] // The next iteration will be // a b c d // e f g h // i j k l ^ // m n o p-' // Where m=i ; n=m+j ; o=n+k ; p=o+l // And is represented as A=[p,l,h,d] ; B=[d,c,b,a] ; C=[a,e,i,m] ; D=[m,n,o,p] // The spiral starts as A=B=C=D=[1] ([[0]] in tuple form) type Iterate<Cond, A=[[0]], B=A, C=A, D=A, New=CumSum<A>, NewNums=New[number]> = 1 extends (NewNums extends Cond ? 1 : 0) // If any of NewNums match Cond, return the shortest of those that do ? Shortest<Extract<NewNums, Cond>> : New extends [...{}[],infer L] // Get the last element of New, and update the spiral sides ? Iterate<Cond, [L,...B], C, [...D, A[0]], New> // Unreachable : 0 type Main<N,M=[]> = N extends M["length"] // If M's length is N, return Iterate where Cond is >= M ? Iterate<[...M,...0[]]>["length"] // Increment M and repeat : Main<N, [...M, 0]> ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes ``` Min@Cases[Nest[Reverse@Append[#,Accumulate@Last@#]Ôèá&,{{1}},#],b_/;b>=#,2]& ``` [Try it online!](https://tio.run/##JcdBC4IwGIDhv/LBYKcvnIJQhDLpWhFdx4hpnyg0ETe7yM4d@6n9hGV0eV5ea3xH1vi@MbGFIp76QR6MI6fO5Ly60pMmR7IaRxruimHVNLOdH8aTPBrnJdOf94vjsqQhINNY35J9XRYMM83jZeoHrxhsSmgV0xo4JBKWFCFD2CGkW4RcrBUr2Y9c/FeE@AU "Wolfram Language (Mathematica) ‚Äì Try It Online") A port of [@Neil's answer](https://codegolf.stackexchange.com/a/238259/9288). [Answer] # Python3, 261 bytes ``` f=lambda n,c=[[1],[1],[1]]:c[-1][-1]if c[-1][-1]>=n else(f(n,c[:-1]+[(c[-1]+[c[-1][-1]+k[len(c[-1])-1]if len(k:=c[len(c)>4 and -5]+([]if len(c)<4 else[c[-4][0]]))>=len(c[-1])else c[-1][0]])])if all(len(c[-1])<= len(i)for i in c[-3:-1])else f(n,c+[[c[-1][-1]]])) ``` Not a very fancy solution, at each recursive call, builds a side of the spiral square. [Try it online!](https://tio.run/##RU5LDoMgEL3KLCHQBH9pa8SLTFhQKykpolE3Pb0FbHUxw8y8D2/6rK/RF7dp3jYjnR4eTw2edxIxU/xXqu7wkqlY1sAxt9JD75aeGBIUWIcTQ5JghgeLvdH1fj/T3SHu71p2O0DbErR/wqVSjOAf72hTJvfoVCoUSlHaytMqYr8sEVM0CLVz5GQ0MjlZasYZLFgf6UV9iFNshmfU@MU2zdavxNllJYOeiOGAGYecw51DduNQifCK0PLYKrGvqV9FMKDbFw) [Answer] # [R](https://www.r-project.org/), 91 bytes ``` function(x,m=t(1)){while(x>max(m))m=rbind(cumsum((m=t(m[,ncol(m):1]))[1,]),m);min(m[m>=x])} ``` [Try it online!](https://tio.run/##Tc1BCsMgFEXR7fwHDnTaYjYSHKQ2oR98Boy2QunabTrr@Fy4ZWxajvpcUlv92FqOVfcs3dBXccD79dC0Sp@4dCFAX26a7xIbj0aRX8bZ5Linky8uALMzAYa4UvNpnHwP@Px9xFlrMb4 "R ‚Äì Try It Online") ]
[Question] [ *Rest in peace, John Horton Conway* There are a **ton** of different Game of Life interpreters out there! A **ton**! Currently for you, getting an interpreter is just a dozen types and a couple of clicks away. But wait, do you notice a common thing in the interpreters? Every interpreter is *graphical*, i.e there are only images and no ASCII text! # The Problem Fun fact: I was in the middle of creating a [2DF](https://tio.run/#2dfuck) interpreter in [my favourite practical programming language](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)) while writing this question. 2DF has a command that performs a step of Game of Life on its memory field. I needed to implement that command in my code. I have not done it yet, so this question is technically an actual question rather than a challenge. I have a **list of some points or coordinates** on a *Cartesian plane*. Each point has an X and a Y value. This is your input! Input can be formated in anyway (you can use any type of formatting, so specify your format in your answers). Example input format: ``` [[0, 0], [1, 0], [2, 0], [2, 1], [1, 2]] ``` This is a representation of a period of [Glider](https://www.conwaylife.com/wiki/Glider) (The Hacker Logo). Draw the points on a grid, and you will see a shape that resembles this: [![A CGoL Glider](https://i.stack.imgur.com/HvdX0.png)](https://i.stack.imgur.com/HvdX0.png) What I want for output is the same list, but modified! These are the modification steps. * A new point is added if it has exactly three existing neighbours. * An existing point is removed if it has more than three or less than two existing neighbours. ### What is a neighbour? A neighbour of a point X is defined as a point adjacent to X either horizontally, vertically, or diagonaly. The neighbours of point \$(2, 3)\$ are: * \$(1, 3)\$ * \$(1, 2)\$ * \$(2, 2)\$ * \$(3, 2)\$ * \$(3, 3)\$ * \$(3, 4)\$ * \$(2, 4)\$ * \$(1, 4)\$ In this case, the output should be similar to this: ``` [[1, 0], [2, 0], [2, 1], [0, 1], [1, -1]] ``` # Task Write a program or implement a function that takes a list of points, and prints or returns a list of points that displays the modified list according to the above modification rules (The order of the output list does not matter). Oh, and be sure to make the code as short as possible! (`code-golf`) P.S It would be great if you included an explanation of your program in your answer! ## Some Example Test Cases ``` Example STDIN Example STDOUT [[0, 0]] => [] [[0, 0], [0, 1]] => [] [[0, 0], [0, 1], [1, 0]] => [[0, 0], [0, 1], [1, 0], [1, 1]] [[0, 0], [0, 1], [1, 0], [1, 1]] => [[0, 0], [0, 1], [1, 0], [1, 1]] [[0, 0], [0, 1], [0, -1]] => [[0, 0], [1, 0], [-1, 0]] [[1, 0], [1, 1], [1, 2]] => [[2, 1], [1, 1], [0, 1]] ``` # Good Luck! :) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~34~~ 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous tacit prefix function. Requires `⎕IO←0` (zero-based indexing). ``` ⌊/{⍺-1-⍸⌂life 0,∘⌽∘⍉⍣4⍸⍣¯1∧⍵-⍺}⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x/1dOlXP@rdpWuo@6h3x6OeppzMtFQFA51HHTMe9ewFkb2dj3oXm4AkexcfWm/4qGP5o96tQMW7ah91LfqfBjTlUW/fo67mR71rHvVuObTe@FHbRKD5wUHOQDLEwzMYZJtXsL@fQpoCjKUeHW2go2AQG6uuQBg86p1ra4dVJjqWC7fZOgog2hC/HRSaDaQNcfoDj9nYTYHQQBeTYDNcjzodbQbSutgDlhibYTbqQoIOAA "APL (Dyalog Extended) – Try It Online") `⌊/{`…`}⊢` call the following anonymous lambda with the smallest existing x and y coordinates as left argument (`⍺`) and the full list as right argument (`⍵`):  `⍵-⍺` subtract smallest point from all points (scales so every number is non-negative)  `∧` sort ascending  `⍸⍣¯1` generate a Boolean matrix with 1s in those positions (lit. inverse of "**ɩ**ndices of 1s")  `0`…`⍣4` repeat four times with zero as left argument:   …`∘⍉` transpose, then    …`∘⌽` mirror, then (this constitutes a 90° clockwise turn)     …`,` concatenate zeros to the left edge  `⌂life` compute the next Game of Life generation  `⍸` **ɩ**ndices of 1s  `1-` subtract those from 1  `⍺-` subtract those from the offset of the lowest x and y coordinates [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` uṠfo≈6#-¹×z+π2ṡ1D ``` [Try it online!](https://tio.run/##yygtzv7/v/ThzgVp@Y86O8yUdQ/tPDy9Svt8g9HDnQsNXf7//x8dbaBjEKsTbQgmjaCkIVjEKDYWAA "Husk – Try It Online") Note that the interpreter doesn't like extra spaces in inputs. ## Explanation ``` uṠfo≈6#-¹×z+π2ṡ1D Input is a list of lists, e.g. L=[[0,0],[1,0],[2,1]] D Repeat twice: X=[[0,0],[1,0],[2,1],[0,0],[1,0],[2,1]] ṡ1 Symmetric range to 1: [-1,0,1] π2 Cartesian second power: [[-1,-1],[-1,0],…,[1,1]] × Pick all elements from this and X and combine with z+ zipping by addition: [[-1,-1],[0,-1],…,[3,2]] -¹ Remove one occurrence of each element of L. Call the result Y. f Filter by condition: Ṡ # number of occurrences in Y o≈6 is close to 6 (so 5, 6 or 7). u Remove duplicates: [[1,1],[1,0]] ``` [Answer] # [R](https://www.r-project.org/), ~~164~~ 156 bytes *Note: now outgolfed in [R](https://www.r-project.org/) by my own [other answer](https://codegolf.stackexchange.com/a/211827/95126)* ``` function(p){m=matrix(F,u<-max(p)-(r=min(p)-2)+1,u) m[t(p-r)]=T t(which(m[]<-(s=sapply(1:u^2,function(j)sum(m[(j+-3:5%/%3*u+-2:0)%%u^2+1])))==3|m&s==4,T))+r} ``` [Try it online!](https://tio.run/##tVFBTsMwELznFZFQ0C6xRezAJao58oLeqoBCCq2rOLGcWBQBbw@mVps2apBAwpeR17Mzs2vTr5rqUTey7lrRv9i67GRTg8Z3JVTRGbmFe2JnVBVbV6RghJLfz5RjzIjFQC060NRgLuZBB69rWa5BLfIZhVa0hdbVG7DMPnBy0N5ga5XjwCamaXYbXUfplY0pzxKMIseMWY6IQqQf6rIV4obMEWPz2a8quXw2onyS9RJKSEiCpATmge@B@SJHDINhNPDNGAT6SCBMHGv6XITibrgBHutpHCuRHbKzin9T2g0yyjhSmujw6LL8zujQ9o9GDunJkiaN9gbUL2HS4SSIR/7zzvjAZMO/jQz6Lw "R – Try It Online") Function that accepts and returns coordinates as columns of a 2-row matrix. Works by creating a matrix & filling it at the specified coordinates, then calculating the next generation & outputting the indices of filled elements. **How?** ``` gol_points= function(p){ # p = matrix with coords in columns m=matrix(F, # create a matrix, filled with FALSE... u<-diff( # with row number u equal to the difference... r<-range(p))+3, # between the range r of values in p, plus 3, u) # and the same number of columns # (so it's a square matrix with dimensions 1 bigger # than the largest range of p) m[t(p-r[1]+2)]=T # Now, set the elements of m at coordinates p + offset to TRUE t(which( # Then, return the coordinates of elements that satisfy... m[]<-(s= # m, filled with... sapply(1:u^2, # the results for each of 1..u^2 (each element of m)... function(j) # of a function taking argument j... sum(m[(j+ # and returning the sum of elements of m at position j... -3:5%/%3*u+-2:0 # plus the elements at all adjacent positions... )%%u^2 # (modulo the matrix size u^2 to wrap-around the edges) +1]) # +1 (R uses 1-based indices), ))==3 # is equal to 3 (3 neighbours, or filled cell with 2 neighbours) |m&s==4, # or is itself TRUE and sum is equal to 4 (filled cell with 3 neighbours) T)) # (arr.ind=TRUE = return coordinates, rather than linear indices), +r[1]-2} # minus the offset used in the first place. ``` [Answer] # [Julia 1.0](http://julialang.org/), ~~121~~ 91 bytes ``` f=g->[v for v=Set(h+[j,k] for h=g,j=-1:1,k=-1:1)if 2<sum(i->all(abs.(v-i).<2),g)<4+in(v,g)] ``` [Try it online!](https://tio.run/##rVRLboMwEN1ziqnVhd2aKKCuohCpitp1pXRnWZWbmtQJIQibqEfIOXuRdDAkJMqnqlQEzDAz79nzMfMqMyr62m7TZBaOxBrSVQnrZKId/bwXc76Q3vKZzPg8CaNBxBdeMJNCPLTVkppwpLKMqnfbo@vQsN4wZnzGhg/3Jqdr1OS2KE3uspySiVOlg1dtnSUsmCqrLSQgAsCreXtN9Dn0JQcRtTLuZNTaYyn5AeJSZL9DhJGUHtECTxY8JLweuSP@O2KX1NHmz0Y08rc9X0T9P3@/KSG/0qewye0S49G6Z9t40OCufS1fIIMgrfKpM6scrCtfVjhVlqqyZD6ACAJ3MEcrFUTc0kJEknGolVgySfwgF/C92SAEyQneDBFEkkDnH0iO/nomweReWk9ba28mLyqHo1p/IG3n0F@Fnjr9sfPFjU9NXaUyNKa0hbDAO/DY1Ger8TNIEv/ZQtm@EvsTA/CirEX@MYYMMJku8W5jDIlGR76Wn5GGUmdWn3Lf3Dwrk/3KTdg56FOb@BncriaXoI9NcWBwdcvYkfrZ4/xfA8arZZFppwnb/gA "Julia 1.0 – Try It Online") ## Explanation ``` f=g->[v for v= # Array Comprehension of final result Set(h+[j,k] for h=g,j=-1:1,k=-1:1) # Set Comprehension of all neighboring cells # of occupied cells, including self if 2< sum(i->all(abs.(v-i).<2),g) # Count the number of neighbors, including self. # For i in g, count iff the distance # between v and i is less than 2 # for all dimensions <4+in(v,g) # <4 if cell is empty, <5 if occupied ] ``` [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 92 bytes ``` CellularAutomaton["GameOfLife",{SparseArray[#+1-Min@#->(1&/@#)],0}][[1]]~Position~1-2+Min@#& ``` `#+1-Min@#->(1&/@#)` converts the input to rules for [SparseArray](https://reference.wolfram.com/language/ref/SparseArray.html): `#+1-Min@#` generates the proper shift to make the indices positive and `(1&/@#)` makes a list of ones of the proper length. This is then fed into [CellularAutomaton](https://reference.wolfram.com/language/ref/CellularAutomaton.html) to generate a step of Conway's Game of Life. The result is extracted and fed into [Position](https://reference.wolfram.com/language/ref/Position.html) to find the positions of living cells, then the index shift is reversed with `-2+Min@#` (it's minus 2 rather than minus 1 because CellularAutomaton adds padding to encompass all cells that could be affected). [Try it online!](https://tio.run/##dYtBC4IwAIXP@StCQQo3dN6LSYcuRULHscOIjQa6xZyHGPOvL8s8BHb6Hu99r2X2zltm5Y0FsVuFA2@avmGm6q0ea61IfGQtv4iTFDwG7vpgpuOVMexJkgzBs1Q4gfsNSnOcbCkoPCUEUTrUupNWajUgWGYfKw21kcrmWOTYRc4VYF14D@YE1m@ihWYkWnbnZeKf70j4nX7kiaX3kQ8v "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), 59 bytes ``` (([(~.#~3=#/.~)@-.~[:,+/),[#~3 4 e.~[:+/[e."1+/)&(,j./~i:1) ``` [Try it online!](https://tio.run/##XY3BasMwEETv/oohBnuFrZXk9BAELqaFnkoPvYo2h@LQ6BLyA/vr7tpqadqDYObNzCovO25PGCNa9PCI@izj8fX5aSFKJFzLfqwdi5ksS4p950yfFOIO8wo6l2beBcUN9ZmdnGMwi6leHhjCEyXokekNtWA9o4powH4bG3S8yWBVkyJhY1B@aeiefQ7vNp75YKpqvo4MGxtyUVb78XlB22K@4gT/z0KHBYUcikW4yfCTlnzr3KYrLg2v5vhn6vPxOxvy734rFBvysHwB "J – Try It Online") Explanation later. [Answer] # [Python 3](https://docs.python.org/3/), ~~215~~ \$\cdots\$ ~~129~~ 127 bytes Saved a whopping 36 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` lambda l:{(a+c,b+d)for c in(-1,0,1)for d in(-1,0,1)for a,b in l if((a+c,b+d)in l)+4>sum(abs(a+c-e+(b+d-f)*1j)<2for e,f in l)>2} ``` [Try it online!](https://tio.run/##pVLLbsMgELznK/ZmqCEyTqRKUe0fIT74AWoiJ7EMPlSWv90FTPNAaauqXJjdndldwXQf@v1y3swy289teaqaEtrdiMq4JlXcYHnpoYbDGVFGEsJc3ARxSSqTgRYOEl2FNoHjba6GEyorZfNUxMiUqMQv7IjfUqsVRDotztNp1kJpBRmgFZjDOU8IJAUBzvyd3m7m82lhAU/WhsvWSzXEyYKZxZTdBbZg9OG4xLd3dN8/2IQ68EQbEO61QdtAayvf7fJT7Wvm01HsthUrfutw5f2n01/e7KHnw3fefTC7vYJR4lVvDRLth/R1W0cEHGKbCK@snTQR1k7OSDs3xvpJIq6HrhWow2BZneMU2BG6/nDWSEajnoDmMKoJxp6rS69FgxTOMg@Rsfki934XuJgiPH8C "Python 3 – Try It Online") Inputs of a list of points and returns the next generation as a list of points. ### Explanation (before some golfs) ``` def f(z): # input a list of complex numbers n={ # create a set of neighbouring complex numbers p+ # by adding to every point a+b*1j # a vector of for a in(-1,0,1) # one left, 0, one right: all combined with each of for b in(-1,0,1) # one down, 0, one up for p in z}; # for all the input points g=lambda # create a function p: # mapping a point sum( # to the sum... 0<abs(a-p)<2 # if the distance between them # is either 1 or root 2 for a in z) # ...of the live points return[(p # return a list of complex numbers for p in n # for all the points in the neighborhood if g[p]==3 # if it has 3 neighbors or g[p]==2and p in z]# or 2 neighbors and is alive ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` -r1ṗ2⁸+€Ẏċ€@Ḅe6,7,9ʋƇ,¥⁸Q ``` A monadic Link accepting a list of coordinates which yields the same after an iteration of the Game Of Life. **[Try it online!](https://tio.run/##y0rNyan8/1@3yPDhzulGjxp3aD9qWvNwV9@RbiDt8HBHS6qZjrmO5anuY@06h5YC5QP///8fHW2go2AQq6MQbQiljRC0IVTcKDYWAA "Jelly – Try It Online")** ### How? ``` -r1ṗ2⁸+€Ẏċ€@Ḅe6,7,9ʋƇ,¥⁸Q - Link: list of coordinates, A -r1 - -1 inclusive range 1 -> [-1,0,1] ṗ2 - Cartesian power two -> [0,0] and its the eight neighbours ⁸+€ - add to each of A -> list of lists of an existing cell + its neighbours Ẏ - tighten -> list of all existing cells and their neighbours call this B ¥⁸ - last two links as a dyad - f(B, A): , - pair -> [B, A] Ƈ - filter keep those c in B for which: ʋ - last four links as a dyad - f(c, [B, A]) ċ€@ - count occurrence of c in each of [B, A] -> i.e. X = [n_neighbours + is_existing, is_existing] Ḅ - convert from binary -> 2×n_neighbours+3×is_existing 6,7,9 - [6,7,9] e - exists in? -> i.e. is X in [[3,0],[3,1],[4,1]]? Q - deduplicate ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~151~~ 118 bytes Uses stuff from the [Julia answer](https://codegolf.stackexchange.com/a/211707/95792) by [@Vole](https://codegolf.stackexchange.com/users/98458/vole). Go upvote that! ``` g=>for{x->y<-g r= -1 to 1 a<-r b<-r n=(for(i<-r;j<-r)yield(x+a+i,y+b+j))count g if n==3|g(x+a,y+b)&n==4}yield(x+a,y+b) ``` [Try it online!](https://tio.run/##lY@xTsMwEIZ3P8VNyCYOrYGFpo7EUqkDEyNicBI7cmTZkWNQotJnD3aEipoJls@@/@6k74ZaGDG7qpN1gBehLcgxSNsM8Nz3cEJos2HsKbLlpXL@hEc6kX3eFp5DziA4YIXY576oEizHcQjr9O8iyKSlafCYiUzTKauyjpDafdgALWgFlvOHrza1U5PcxPrxfFlZMoQ@hYHDDl5leMNHGyhEkHfgJRyD9KIy8jqfV6bo1xQlU5RM0T9M0d9M50YqUHjYwaKTbG4JcOi9tsFYfMDDXXDxDBKPUnibl1vy89IIdlVQtm4vScJqMCKel7LLQMI9Qef5Gw "Scala – Try It Online") TIO says 119 bytes, but that's because I have to use `(x,y)` to extract a Tuple2 instead of just `x->y`, which was added after Scala 2.10 (the version TIO uses). # Dotty, 117 bytes ``` g=>for{x->y<-g;r= -1 to 1;a<-r;b<-r;n=g.count((i,j)=>math.hypot(x+a-i,y+b-j)<2)if n==3|g(x+a,y+b)&n==4}yield(x+a,y+b) ``` [Try it online](https://scastie.scala-lang.org/j4a00MyeQwiLjnScYcwXig) ## Explanation ``` g => for { x -> y <- g //For every point in the grid, r = -1 to 1 //Create range from -1 to 1 to use later a <- r //For every a in r b <- r //For every b in r ((x+a, y+b) is a neighbor of (x,y) or (x,y) itself) n = (for(i <- r; j <- r) yield (x + a + i, y + b + j) //(x+a, y+b) and all its neighbors ) count g //How many of them are in g? if n == 3 | g(x + a, y + b) & n == 4 //Filter the cells that'll be live next round //If n=3, it's live and has 2 neighbors, or it's not live and has 3 neighbors, so it'll be live next round. //Otherwise, check if it's live and has 3 neighbors } yield (x + a, y + b) //Yield every such point ``` [Answer] # [R](https://www.r-project.org/), ~~132~~ ~~125~~ 122 bytes ``` function(x,y,n=rep(q<-x+1i*y,e=9)+-3:5%/%3+1i*-1:1,s=rowSums(outer(n,n,`==`)))list(Re(c<-unique(n[s>2&s-n%in%q<4])),Im(c)) ``` [Try it online!](https://tio.run/##lZBRT4MwEMef5VOQGMydu0aO6YML3buv@mjMlmBdmrAyKET49FhwDNFhst5De9f7//q/Fu0uSzeHTJvSyvajMkmpMwM1NWRkoQ6Qx6JesL5tSMlHXIjl6iG4C5ZdSfCKycoi@3yp9hayqlQFGDK0lXKLiKm2JTwrSGJRGZ1XCsyrXUc3VphAmyCP798Q6WkPCWK7S/W7Kja1TCAkpsgFo3esNn21C3fjqifLUMtBSM1wbNCbtoTuLkR/Zl37cj1m8AvfP4z07YARL9Y60aB2IJzVdh2@e6nfudv5mHOX49VZ9oQ@@ruQfQ49Dk3i59yz6AEp@sMfJk/NRv9@RTTa5JNt9Nov "R – Try It Online") A completely different approach to my other R answer, so posting separately. Manipulates complex coordinates instead of filling a matrix. Input is 2 vectors containing x- and y-coordinates of points. Output is a list containing 2 vectors of x- and y-coordinates. **How?** ``` gol_points= function(x,y, q=x+1i*y, # convert x and y into complex coordinates q; d=-3:5%/%3+1i*-1:1, # create vector d of all differences to neighbouring cells: # (so, d = -1-i, -1, -1+i, -i, 0, i, 1-i 1, and 1+i) n=q+rep(d,e=ncol(p)), # n = coordinates of neighbouring cells, # by adding d to each element of q s=rowSums(outer(n,n,`==`)), # s = the number of copies of each element in n # and, therefore, the number of live neighbours it has (including itself) i=(s==3|s==4&n%in%q), # i = indices in n of new generation of cells: # TRUE if neighbours (including self) ==3, # or if neighbours (including self) ==4 AND it's a living cell (so: in q) c=unique(n[i])) # c = unique set of new generation of cells list(Re(c),Im(c)) # output list containing Real & Imaginary parts of c ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes ``` żIAṀo-4×<2$$ 3Ḷ’p`+þẎẎQçⱮ³$SṪe-2,-,3Ʋ$Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8///oHk/Hhzsb8nVNDk@3MVJR4TJ@uGPbo4aZBQnah/c93NUHRIGHlz/auO7QZpXghztXpeoa6ejqGB/bpHKs/f///9HRhjoKRrE6CtEGOgqGUNoARBtCaSMQHQsA "Jelly – Try It Online") This is probably really bad [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes ``` l#&@@@Cases[Tally@Array[l+#+I#2&,{3,3},-1,Join],{_,3}|{#|##&@@l,4}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@f9pIXKag4ODs6JxanF0SGJOTmVDo5FRYmV0TnaytqeykZqOtXGOsa1OrqGOl75mXmxOtXxQG5NtXKNMkhjjo5Jbez/gKLMvJJoZV27oFTPXIe0aOf83IKc1AqgucqxsWp1wcmJeXXVXNXVBjoKBrW1OjCWjgKINsQiAqQNsauFyUBoHHqBtC5UCkUxhDZC1QRTYYSgMVQCJYB8EKkLoQx0gHJctf8B "Wolfram Language (Mathematica) – Try It Online") Takes and returns a list of complex numbers. [Answer] # JavaScript (ES10), ~~156~~ 152 bytes ``` a=>a.flatMap(a=>g(a,b=[])+.5|0?b:[...b,a],g=(B,b,k=9)=>k--?g(B,b,k,g[A=[B[0]+k%3-1,B[1]+~-(k/3)]]|a.some(a=>k=a+''==A)|!b||g(B=A)?0:g[B]=b.push(B))-k:3) ``` [Try it online!](https://tio.run/##rZDBTsQgFEX3fgUuzEAKFKZxYZM3zbD3CwgLGFtU6tDY0VXjr1cmVZuxYzIL2VxeePfcXJ7tu@13r0/dge3jQz02MFrYWN609nBvO5wGjy11oA3J@O0gKldqzrmj1lAPWFFHA9wR2ATGKj/N1OstaKWFycJNwSRVWprsg@GQF8SYwfI@vtRHdgCbrVYAWzJcu2FI/nStROm1MuB499Y/YkUIC2VBxl3c97GteRs9brDWgiJhDPrjEILyHGlzddZG0VHl0n6ZLak8Sf@ynd@aNIVdBv1Z/ydoUjY3/Q39hrGp0IJ2Ejbpetl7Pb/K@XPHTw "JavaScript (Node.js) – Try It Online") ### How? The helper function \$g\$ counts the number \$N\$ of cells around a reference position `B[] = [x,y]`. For golfing reasons, the reference position is counted as well. The value returned by \$g\$ is \$3-N\$. Therefore: * \$g\$ returns \$0\$ or \$-1\$ for a cell surrounded by \$2\$ or \$3\$ other cells respectively, which is characterized by `(g() + 0.5 | 0) == 0` * \$g\$ returns \$0\$ for an empty position surrounded by exactly \$3\$ cells When it's called with a 2nd argument `b[]`, \$g\$ also pushes into this array the coordinates of all cells that are currently off and must be turned on, provided that this is the first time they are encountered. ### Commented ``` a => // a[] = input array a.flatMap(a => // for each coordinate pairs a[] in a[]: g(a, b = []) // invoke g with an empty array b[] + .5 | 0 ? // if the result is neither -1 or 0: b // return b[] without a[] : // else: [...b, a], // return b[] with a[] g = ( // g is a recursive function taking: B, // B[] = [x, y] b, // b[] = list of coordinate pairs k = 9 // k = counter ) => // k-- ? // decrement k; if it was not 0: g( // recursive call: B, b, k, // pass B[], b[] and k unchanged g[ // A = [ // define the coordinates A[] of the neighbor: B[0] + k % 3 - 1, // x' = x + (k mod 3) - 1 B[1] + ~-(k / 3) // y' = y + floor(k / 3) - 1 ] // ] | // abort if g[A] is already defined a.some(a => // or A[] exists in a[] k = a + '' == A // (in which case k is set to true) ) // | !b // or b is not defined || g(B = A) // otherwise, invoke g with B = A and without ? // the 2nd argument; if the result is not 0: 0 // do nothing : // else: g[B] = b.push(B) // append B[] to b[] and set g[B] ) - k // end of recursive call; subtract k : // else: 3 // return 3 and stop the recursion ) // end of flatMap() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2и2Ý<©ãδ+€`D€»DI€»õ.;s¢®6+såÏê ``` Port of [*@Zgarb* Husk answer](https://codegolf.stackexchange.com/a/211699/52210), so make sure to upvote him as well. The reason it's so much longer is due to less convenient builtins. One is that there isn't a remove\_first builtin, so we'll use a replace\_first builtin instead. In addition, the count doesn't vectorize on a list of pairs, so we have to join each string with a newline delimiter for both the replace\_first and count builtins. [Try it online](https://tio.run/##yy9OTMpM/f/f6MIOo8NzbQ6tPLz43BbtR01rElyAxKHdLp5g6vBWPeviQ4sOrTPTLj689HD/4VX//0dHG@gYxOpEG4JJIx3D2FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/ows7jA7PtTm08vDic1u0HzWtSXABEod2u1SCqcNb9ayLDy06tM5Mu/jw0sP9h1f91/kfHR1toGMQG6ujAGHoAElDdK5OtCGmGoggiMSi3kBHFyqKUAQijZCVQqSMQPpjAQ). **Explanation:** ``` 2и # Repeat the (implicit) input-list twice # i.e. [[0,0],[1,0],[2,1]] → [[0,0],[1,0],[2,1],[0,0],[1,0],[2,1]] 2Ý # Push list [0,1,2] < # Decrease each by 1: [-1,0,1] © # Store this list in variable `®` (without popping) ã # Take the cartesian product of this list with itself # → [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]] δ # Apply double vectorized on the two lists: + # Add the values at the same positions in the pairs together # → [[[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]], # [[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1],[2,-1],[2,0],[2,1]], # [[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]], # [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]], # [[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1],[2,-1],[2,0],[2,1]], # [[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]]] €` # Flatten it one level down to a list of pairs D # Duplicate this list of pairs €» # Join each inner pair together with a newline delimiter # → ["1\n1","1\n0","1\n-1","0\n1","0\n0","0\n-1","-1\n1","-1\n0", # "-1\n-1","2\n1","2\n0","2\n-1","1\n1","1\n0","1\n-1","0\n1", # "0\n0","0\n-1","3\n2","3\n1","3\n0","2\n2","2\n1","2\n0", # "1\n2","1\n1","1\n0","1\n1","1\n0","1\n-1","0\n1","0\n0", # "0\n-1","-1\n1","-1\n0","-1\n-1","2\n1","2\n0","2\n-1","1\n1", # "1\n0","1\n-1","0\n1","0\n0","0\n-1","3\n2","3\n1","3\n0", # "2\n2","2\n1","2\n0","1\n2","1\n1","1\n0"] D # Duplicate this list of strings I # Push the input list of pairs €» # Join each inner pair with a newline delimiter as well # → ["0\n0","1\n0","2\n1"] õ.; # Replace every first occurrence of the input-pair with an empty string # → ["1\n1","","1\n-1","0\n1","","0\n-1","-1\n1","-1\n0", # "-1\n-1","","2\n0","2\n-1","1\n1","1\n0","1\n-1","0\n1", # "0\n0","0\n-1","3\n2","3\n1","3\n0","2\n2","2\n1","2\n0", # "1\n2","1\n1","1\n0","1\n1","1\n0","1\n-1","0\n1","0\n0", # "0\n-1","-1\n1","-1\n0","-1\n-1","2\n1","2\n0","2\n-1","1\n1", # "1\n0","1\n-1","0\n1","0\n0","0\n-1","3\n2","3\n1","3\n0", # "2\n2","2\n1","2\n0","1\n2","1\n1","1\n0"] s # Swap so the other list of strings is at the top of the stack again ¢ # Count the amount of occurrences of each item # → [6,3,4,4,3,4,2,2,2,3,4,2,6,5,4,4,3,4,2,2,2,2,3,4,2,6,5,6,5,4,4, # 3,4,2,2,2,3,4,2,6,5,4,4,3,4,2,2,2,2,3,4,2,6,5] ® # Push list [-1,0,1] from variable `®` 6+ # Add 6 to each: [5,6,7] s # Swap so the list of counts are at the top of the stack å # Check for each count if it occurs in the [5,6,7] list # → [1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0, # 0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1] Ï # Only keep the pairs at the truthy indices # → [[1,1],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0]] ê # Sort and uniquify the remaining pairs # → [[1,0],[1,1]] # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~80~~ ~~75~~ ~~48~~ 43 bytes ``` F³F³F⊕⌈↔⊖⟦ικ⟧Fθ⊞υ⊖Eμ⁺ν⎇ξκιIΦυ∧⁼κ⌕υι›²↔⁻⁶№υι ``` [Try it online!](https://tio.run/##VY47CwIxEIR7f8WWe7CCD7CxEl9YHFxhd6SIZ8RgLqdJVvTXx8QH6jbDst/MbHOUrumkifHQOcBxAX@6sY1TrbJB7bGUN91yi7Od7wwHhQv1Pdaa4CSKPC/npYCK/RGZ4Jcr5RlbgsqwR0uwVc5Kd8dbchPobJ/2KqdtwLn0AVfaBOVyyMzucXlhaTwmcqXTyk8HwdopmalRoj6/ldqmhgnBvOMUxu/wZ0GMdV0PCAaCIOvwrf2hECL2r@YB "Charcoal – Try It Online") Link is to verbose version of code. Just a boring port of @Zgarb's Husk answer. Outputs points using Charcoal's default format which is each coordinate on its own line with points double-spaced from each other. Explanation: ``` F³F³ ``` Loop through all neighbourhoods. ``` F⊕⌈↔⊖⟦ικ⟧ ``` Loop through adjacent cells twice but the cell itself only once. ``` Fθ⊞υ⊖Eμ⁺ν⎇ξκι ``` Push all of the resulting cells to the predefined empty list. ``` IΦυ∧⁼κ⌕υι›²↔⁻⁶№υι ``` Print the first appearance of those cells that appear between 5 and 7 times. Previous ~~80~~ 75-byte more Charcoal-y solution: ``` ≔E²Eθ§λιηUMη…·⊖⌊ι⊕⌈ιFθ«J⊟ι⊟ιUMKMI⌊⟦⁹⁺²Σκ⟧I⊕ΣKK»F⊟ηF§η⁰«Jικ¿№567KK⊞υ⟦κι⟧»⎚Iυ ``` [Try it online!](https://tio.run/##TVBBasMwEDw7r1hyWoECSaEtpafgXlIwmLY3o4OwlVjYkhzZCoHSt7srO2l9GomZnZndspa@dLIdx33f65PFTHb4wCHCmcN@ONhKXbHloBljHGr2uiIudcZIW2HN4WDLNvT6oj6kPSl8U6VXRtlBVZhpq00wqOMk6f4Jeb0TjAyPzgOeGXyvkvdgui@HueuI5DAjSZJFaK5UkznnFZIilf3wF1S80Ai1iRt80r9hTEwJSe61HXASL4tEUbRDNjf5mbvE2JoxmD73G9CuW7YsqTk00VsfAVMXyH/9@PS8pgo3R8hDX2PgUDR0PzH5p62SHum5aBQoehyLothShCA54e6Gm50QYtxc2l8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs points using Charcoal's default format which is each coordinate on its own line with points double-spaced from each other. Explanation: ``` ≔E²Eθ§λιη ``` Get a transposed copy of the points. ``` UMη…·⊖⌊ι⊕⌈ι ``` Replace each row of the transpose with a padded range. ``` Fθ« ``` Loop over each point. ``` J⊟ι⊟ι ``` Jump to that point. ``` UMKMI⌊⟦⁹⁺²Σκ⟧ ``` Doubly increment each of the neighbours, limited to 9. ``` I⊕ΣKK ``` Increment the cell. ``` »F⊟ηF§η⁰« ``` Loop over the padded ranges. ``` Jικ ``` Jump to that point. ``` ¿№567KK ``` If it's between 5 and 7, then... ``` ⊞υ⟦κι⟧ ``` ... save that point in the predefined empty list. ``` »⎚Iυ ``` Clear the canvas and output the new points. ]
[Question] [ ## Introduction One of the first things I learned in chemistry, was giving the formula for the combustion of alkanes. The most basic example was: `2CH4 + 4O2 -> 4H2O + 2CO2`. **Note that the equation could have been simplified by dividing every coefficient by 2, we would get** `CH4 + 2O2 -> 2H2O + CO2`. **To make things easier, we are going to ignore this to not complicate things**. You can see that with the combustion of any alkane, oxygen is used. After the reaction, only `CO2` and `H2O` are made. # The task The input will always be in the form `C(n)H(2n+2)`, with `n>0`. These are some example inputs: ``` CH4 C2H6 C3H8 C4H10 C5H12 C6H14 ``` ## Useful tip: Every alkane has a standard pattern in the combustion reaction: ``` 2C(n)H(2n+2) + (3n+1)O2 -> (2n+2)H2O + (2n)CO2 ``` e.g. `C4H10` gives the following equation: `2C(4)H(2*4+2) + (3*4+1)O2 -> (2*4+2)H2O + (2*4)CO2`. After calculating everything, we get this final equation `2C4H10 + 13O2 -> 10H2O + 8CO2` ## Testcases ``` CH4 2CH4 + 4O2 -> 4H2O + 2CO2 C3H8 2C3H8 + 10O2 -> 8H2O + 6CO2 C4H10 2C4H10 + 13O2 -> 10H2O + 8CO2 C12H26 2C12H26 + 37O2 -> 26H2O + 24CO2 ``` # Rules * Note that I used spaces for the examples to increase readability, **these are not necessary**. `2CH4 + 4O2 -> 4H2O + 2CO2` and `2CH4+4O2->4H2O+2CO2` are both valid outputs. However, if you *consistently* use spaces for the output, you get a **-10% bonus** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the least amount of bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), 86 \* 0.9 = 77.4 bytes ``` s=input() N=int(s.split('H')[1]) print("2%s + %dO2 > %dH20 + %dCO2"%(s,N*1.5-2,N,N-2)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v9g2M6@gtERDk8sPyCrRKNYrLsjJLNFQ91DXjDaM1eQqKAIJKxmpFitoK6im@Bsp2AEpDyMDMNfZ30hJVaNYx0/LUM9U10jHT8dP10hT8/9/Z2MPCwA) Extracts the number of `H`'s rather than the number of `C`'s from the input. This avoid special-casing `CH4` and simplifies the output expressions in terms of `N=2n+2`. The output has parameters plugged in via string formatting. The first summand is just the input string, and the rest have calculated numbers plugged in. Note that `N*1.5-2` (same as `N*3/2-2`) gives a float, but the string formatting converts it to an int. [Answer] # Java, 202 \* 0.9 = 181.8 bytes Sometimes, I wonder if I'm just hurting myself with Java. Thanks to @TNT and @TFeld for shaving off a good 20 bytes! ``` class A{public static void main(String[]a){String s=a[0].substring(1,a[0].indexOf("H"));long n=Long.parseLong((s.length()>0)?s:"1");System.out.printf("2%s + %dO2 > %dH2O + %dCO2",a[0],3*n+1,2*n+2,2*n);}} ``` Pretty simple. Basically, I cut the input from `C` to `H`, and get that substring. If it's nothing, I set `n` to one. Otherwise, I set it to the number between `C` and `H`. The code following just prints it out and puts it into proper notation. Ungolfed ``` class A{ public static void main(String[]a) { String s=a[0].substring(1,a[0].indexOf("H")); long n=Long.parseLong((s.length()>0)?s:"1"); System.out.printf("2%s + %dO2 > %dH2O + %dCO2",a[0],3*n+1,2*n+2,2*n); } } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~122~~ 91 \* 0.9 = 81.9 bytes ``` i=input() n=2*int(i[1:i.find('H')]or 1) print'2%s + %dO2 > %dH2O + %dCO2'%(i,n*3/2+1,n+2,n) ``` [Try it online!](https://tio.run/##HcmxCoAgFEDR3a@QQNSUwtcSQS0ubn5AtEX0lpeUDX29RdPlcNOT94OgFByR0p2VZjRCjZQVzm7AZkNalQxSL8fJnWbp/J4EcXHDxRqBT18CxJ8@ghQKLdVdC8ZZMmBJl1L5LvTVCw) [Answer] # JavaScript ES6, 63 \* 0.9 = 56.7 bytes ``` _=>`2${_} + ${$=_.split`H`[1],$*1.5-2}O2 > ${$}H2O + ${$-2}CO2` ``` Similar to my ESMin answer [Answer] # Pyth, 53\*0.9 = 48 bytes Previous byte count: * 69 \* 0.9 = 62 * 63 \* 0.9 = 57 * 56 \* 0.9 = 50 ``` Js>z+xz\H1s[\2z%" + %dO2 > %dH2O + %dCO2"[-*1.5J2J-J2 ``` It is just like xnor's answer, where I use the H values. A variable J is used to store the amount of H's in the molecular formula of the molecule. [Try it here](https://pyth.herokuapp.com/?code=Js%3Ez%2Bxz%5CH1s%5B%5C2z%25%22+%2B+%25dO2+%3E+%25dH2O+%2B+%25dCO2%22%5B-%2a1.5J2J-J2&input=CH4&debug=0) [Answer] # Javascript ES6, 96\*0.9 = 86.4 ``` f=s=>`2C${(n=(s.match(/\d+(?!.*\d)/)[0]-2))>2?n/2:''}H${n+2} + ${1.5*n+1}O2 > ${n+2}H2O + ${n}CO2` ``` [Answer] # CJam, ~~45~~ 44 bytes ``` 2r_'H/1=[i_((_2/1$+)@@]"+%dO2>%dH2O+%dCO2"e% ``` [Try it online](http://cjam.aditsu.net/#code=2r_'H%2F1%3D%5Bi_((_2%2F1%24%2B)%40%40%5D%22%2B%25dO2%3E%25dH2O%2B%25dCO2%22e%25&input=C12H26) To avoid special casing `CH4`, I don't use the first number at all, and only extract the number after the `H`. This gives the value of `2n+2`. The remaining values are then calculated based on that, and formatted. Explanation: ``` 2 Push leading 2 for output. r Get input. _'H/ Copy and split at 'H. 1= Take second part after split, this is 2n+2. [ Start list. i Convert string value to integer. _(( Copy and decrement twice, giving 2n. _2/ Copy and divide by 2, giving n. 1$ Copy the 2n to the top. + Add, to get 3n. ) Increment, giving 3n+1. We now have 2n+2, 2n, 3n+1 on stack. @@ Rotate top 3 entries twice, to get 3n+1, 2n+2, 2n. ] Close list. "+%dO2>%dH2O+%dCO2" Format string for output. e% "printf" operator. ``` [Answer] ## Perl, (84 + 1) \* 0.9 = 76.5 (+1 char for running with the `-n` flag) My first Perl golf! ``` @x=(1,m/C(\d)/g);$n=$x[$#x];say"2$_ + ".(3*$n+1)."O2 > ".(($n*=2)+2)."H20 + ${n}CO2" ``` It's important that STDIN not contain a trailing newline. Example usage: ``` llama@llama:...code/perl/ppcg64412chemistry$ printf CH4 | perl -n chemistry.pl 2CH4 + 4O2 > 4H20 + 2CO2 ``` Ungolfed-ish: ``` #!/usr/bin/perl use 5.10.0; $_ = 'C3H8'; my @x = (1, m/C(\d)/g); my $n = $x[$#x]; say "2$_ + ".(3*$n+1)."O2 > ".(($n*=2)+2)."H20 + ${n}CO2"; ``` The lines ``` my @x = (1, m/C(\d)/g); my $n = $x[$#x]; ``` are fairly interesting here. `$#x` represents the "last populated index" of `@x` (and SE's syntax highlighting thinks it's a comment because it's dumb), so `$x[$#x]` will select the captured part of the `C(\d)` regex *if* it exists, or `1` otherwise. (Perl doesn't care that it'll be a string in all other cases except `1`; you can use numerical operators on strings just fine in Perl.) [Answer] # [Python](https://www.python.org/download/releases/1.6.1/), 148 \* 0.9 = 133 bytes Prev byte counts * 0.9\*195 = 175 * 0.9\*190 = 171 ``` i=raw_input() O=3*int(i[1:i.find('H')]or 1)+1;C=2*int(i[1:i.find('H')]or 1);print"2"+i+" + "+`O`+"O2"+" > "+i[i.find('H')+1:]+"H2O"+ " + "+`C`+"CO2" ``` [Try it online!](https://tio.run/##K6gsycjPM/z/P9O2KLE8PjOvoLREQ5PL39ZYKzOvRCMz2tAqUy8tMy9FQ91DXTM2v0jBUFPb0NrZ1gi3vHVBEVBOyUhJO1NbSUFbQUk7wT9BW8kfKKCkYAfkZkYj6dE2tIrVVvIw8lcCqoSodgaqdgYq///f2djDAgA "Python 1 – Try It Online") [Answer] # 𝔼𝕊𝕄𝕚𝕟, 64 \* 0.9 = 57.6 bytes ``` a=ïČ`H”[1],`2⦃ï} + ⦃a*1.5-2}O2 > ⦃a}H2O + ⦃a-2}CO2` ``` [Try it here (Firefox only)](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=CH4&code=a%3D%C3%AF%C4%8C%60H%E2%80%9D%5B1%5D%2C%602%E2%A6%83%C3%AF%7D%20%2B%20%E2%A6%83a*1.5-2%7DO2%20%3E%20%E2%A6%83a%7DH2O%20%2B%20%E2%A6%83a-2%7DCO2%60) ## Explanation ``` a=ïČ`H”[1], // split input along H to get 2n+2 ` 2⦃ï} // 2C(n)H(2n+2) – this is the same as 2[input alkane's formula] + ⦃a*1.5-2}O2 // + 2(3n+1)O2 > ⦃a}H2O // > (2n+2)H2O + ⦃a-2}CO2 // + (2n)O2 ` // implicitly output the template string above ``` [Answer] # Pyth, 40 bytes ``` s[2z\+h*3Jv|hctz\H\1"O2>"yhJ"H2O+"yJ"CO2 ``` [Try it online.](https://pyth.herokuapp.com/?code=s%5B2z%5C%2Bh*3Jv%7Chctz%5CH%5C1%22O2%3E%22yhJ%22H2O%2B%22yJ%22CO2&input=C4H10&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=s%5B2z%5C%2Bh*3Jv%7Chctz%5CH%5C1%22O2%3E%22yhJ%22H2O%2B%22yJ%22CO2&test_suite=1&test_suite_input=CH4%0AC2H6%0AC3H8%0AC4H10%0AC5H12%0AC6H14%0AC12H26&debug=0) [Answer] ## JS, 118 (106) bytes ``` x=prompt();y=x.replace("CH","C1H").match(/\d{1,}/g)[0];alert(2+x+" + "+(3*y+1)+"O2 > "+(2*y+2)+"H2O + "+(2*y)+"CO2"); ``` [Answer] # MATLAB, 96 \* 0.9 = 86.4 bytes ``` s=input('');i=[sscanf(s,'C%dH'),1];n=i(1);fprintf('%s + %dO2 > %dH2O + %dCO2',s,3*n+1,2*n+2,2*n) ``` Fairly self explanatory. Takes an input string (need to wrap it in quote marks so MATLAB doesn't try to execute it!). Then converts the number between the C and the H in the input to decimal. The value 1 is appended as an array to the output of sscanf so that in the case `CH4` when we extract the first index in the array into `n` we get a 1 if there was no number between the C and H. Then just prints out with the spaces following the formula in the question. This should also work with **Octave** using the online interpreter [here](http://octave-online.net/). [Answer] # Clojure/ClojureScript, 98\*0.9 = 88.2 bytes ``` #(let[n(max 1(int((re-find #"C(.*)H"%)1)))m(* 2 n)](str "2"%" + "(inc(* 3 n))"O2 > "(+ 2 m)"H2O + "m"CO2")) ``` Creates an anonymous function. Try it by going [here](http://clojurescript.net/) and entering `(def f #(let...))`, then `(f "C3H8")`. [Answer] # Excel, 123 \* 0.9 = 110.7 bytes ``` =="2"&A1&" + "&(3*MID(A1,FIND("H",A1)+1,9)/2-2)&"O2 > "&MID(A1,FIND("H",A1)+1,9)&"H2O + "&(MID(A1,FIND("H",A1)+1,9)-2)&"CO2" ``` If we could take CH4 input as C1H4, can be reduced to 122 \* 0.9 = 109.8 bytes ``` ="2"&A1&" + "&3*MID(A1,2,FIND("H",A1)-2)+1&"O2"&" > "&MID(A1,FIND("H",A1)+1,9)&"H2O + "&(MID(A1,FIND("H",A1)+1,9)-2)&"CO2" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes ``` ṣ”HṪVµ2³”+2⁸_©+H“O2>”⁸“H2O+”®“CO2 ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuZ6PNy5KuzQVqNDm4EcbaNHjTviD63U9njUMMffyA4oBBQAsj2M/LWBnEPrgGxnf6P///87e5gAAA "Jelly – Try It Online") The bonus doesn't help here. [Answer] # [C++ (clang)](http://clang.llvm.org/), 160 bytes ``` #include<iostream> int main(){int n=1,t;std::cin.get();std::cin>>n;t=2*n;printf("2C");n-1&&printf("%i",n);printf("H%i + %iO2 > %iH2O + %iCO2",t+2,t+n+1,t+2,t);} ``` [Try it online!](https://tio.run/##PYpBDoIwFET3nqKpgbQCJi0bQ6UbNt1xBlIq@Ql8CXxXxrNX1MhiMvMmz89z4ccOhxiPgH589OEK95WW0E32AEhs6gCFfH4m1ions1JfVR7wPAQSckdr0VCtT2jmZZNvguuGS4OFStP/kwDPUe6CS4BlLIFWM7uV0@0Xm1bznDK9BTP1W9K8YmxKd3kD "C++ (clang) – Try It Online") A bit more that I expected. Reads first char and discards it, then reads int and outputs the result. Problem is with `n` being 1. I can't think of shorter way to output it. Ungolfed ``` #include <iostream> int main() { int n = 1, t; std::cin.get(); std::cin >> n; t = 2 * n; printf("2C"); n - 1 && printf("%i", n); printf("H%i + %iO2 > %iH2O + %iCO2", t + 2, t + n + 1, t + 2, t); } ``` [Answer] # [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 113 bytes ``` let s=stdin.ReadLine() float s.[1+s.IndexOf 'H'..]|>fun f->printf"2%s + %gO2 > %gH2O + %gCO2"s<|f*1.5-2.<|f<|f-2. ``` [Try it online!](https://tio.run/##SyvWTc4vSv3/Pye1RKHYtrgkJTNPLyg1McUnMy9VQ5MrLSc/ESihF22oXaznmZeSWuGfpqDuoa6nF1tjl1aap5Cma1dQlJlXkqZkpFqsoK2gmu5vpGAHpDyM/MFcZ38jpWKbmjQtQz1TXSM9IAuIgIz//52NPSwA "F# (.NET Core) – Try It Online") ]
[Question] [ **Edit: There will be a bonus of -20 for random masking** Hello fellow Whistleblowers and carriers of secret knowledge. I am due to an interview by mail and I - of course - cannot say specific names in full length. But as I want to disclose it in a rather not-so-obvious-way I need your help. I will provide these names in the form of > > "evil\_company\_that\_makes\_me\_shiver" > > > but surely I do not want to spell it out completely. Your task to help me and the whole world is that you provide a nice program that turns the above into ``` "ev**************************" ``` or ``` "**il************************" ``` or even ``` "****_c**********************" ``` I think you get it. But there is one flaw: I want to disclose the name in total, so I need to pass the number of occurrences and the word itself to the script and it will disclose the letters bit by bit. An example could be ``` ~$ ./whistle NSA 3 > "N**" > "**A" > "*S*" ``` or ``` ~$ ./whistle nuclear 3 > "nu*****" > "***lea*" > "**c***r" ``` or ``` ~$ ./whistle nuclear 2 > "nuc****" > "***lear" ``` I hope you can help me and as we know that size matters the shortest code wins. Help make this world a better place! [Answer] ### GolfScript, 26 charaters Since no specific way of disclosure was specified I decided to go for the shortest: ``` :f,\`{{\)f%.!@42if}%\;n}+% ``` You may experiment with this code [online](http://golfscript.apphb.com/?c=IkFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaIiA3Cgo6ZixcYHt7XClmJS4hQDQyaWZ9JVw7bn0rJQ%3D%3D&run=true). *Example:* ``` > "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 7 ******G******N******U***** *****F******M******T****** ****E******L******S******Z ***D******K******R******Y* **C******J******Q******X** *B******I******P******W*** A******H******O******V**** ``` *Commented code:* ``` :f # Save the second input to variable f , # Makes the array [0 1 2 .... f-1] \`{ # \´{}+% builds a code block where # first the input string is pushed (done # via the + operator and afterwards the whole # block is applied to above array, i.e. # For each line 0, 1, ... # Here, the stack contains the line number (counter) # and the string { # {}% -> map to each character of the string # Stack contains counter and current character \)f% # Increase the counter by one and calculate modulo f . # Duplicate counter (will be used for the if below) ! # and test for zero # I.e. if counter==0 @ # Then Current character 42 # Else 42 (which is '*') if # }% # The mapping operation masked most of the characters \; # Discard the counter n # Add newline }+% ``` [Answer] ## PHP - 80 bytes ``` <?for(;($c=$argv[1][~-$i+=1])?:$k^++$j;)echo$c?$i%$k=&$argv[2]^$j?'*':$c:$i=' '; ``` Sample usage: ``` $ php whistle-blower.php ABCDEFGHIJKLMNOPQRSTUVWXYZ 7 ******G******N******U***** A******H******O******V**** *B******I******P******W*** **C******J******Q******X** ***D******K******R******Y* ****E******L******S******Z *****F******M******T****** ``` [Answer] # Python (~~157~~ ~~149~~ ~~139~~ 138-20=118): ``` def f(a,b): from random import*;c=[["*"]*len(a) for i in range(b)] for d in range(len(a)):choice(c)[d]=a[d] for e in c:print "".join(e) ``` # Cheesy python (~~55~~ 35): You didn't tell me the required distribution ;) ``` g=lambda a,b:["*"*len(a)]*(b-1)+[a] ``` # Uniform python (~~129~~ ~~123~~ 122): ``` def h(a,b): c=[["*"]*len(a)for i in range(b)] for d in range(len(a)):c=c[1:]+c[:1];c[0][d]=a[d] for e in c:print"".join(e) ``` # Output: ``` a="Synthetica 'Evil' the Second" b=7 f(a,b) print for i in g(a,b): print i print h(a,b) ``` gives ``` ***t***i***'***** *********d ******************t** ****** ******t*** ***********Se**n* S**************l****e******* *y******c***E************o** **n*h****a**************c*** *****e*******vi*'**h******** **************************** **************************** **************************** **************************** **************************** **************************** Synthetica 'Evil' the Second ******t******v******e******d S******i******i****** ****** *y******c******l******S***** **n******a******'******e**** ***t****** ****** ******c*** ****h******'******t******o** *****e******E******h******n* ``` [Answer] # Bash, 80 bytes ``` m=${1//?/*} for((i=1;d=i*${#1}/$2,i++<=$2;c=d)){ echo "${m:0:c}${1:c:d-c}${m:d}" } ``` In action: ``` $ ./anon.sh stackoverflow.com 6 st*************** **ack************ *****ove********* ********rfl****** ***********ow.*** **************com $ ``` [Answer] ## C#, 226 This can be trimmed down if you replace the random stuff with a more simple distribution (think modulus) but the randomness is what got me interested. =) Anyway, putting everything on just one line I get 226 characters. In readable code it looks like this: ``` private void F(string n, int i) { var l = n.Length; var r = new Random(); var a = new string[i]; for (var p = 0; p < l; p++) { var x = r.Next(0, i); for (var j = 0; j < i; j++) { a[j] += j == x ? n.Substring(p, 1) : "*"; } } for (var j = 0; j < i; j++) { Console.WriteLine(a[j]); } } ``` Sample output: ``` Anonymize.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ 7 *****F**I**********T**W*** A*****************S****X** **CDE**H*JKL************** *************N************ **************O*****U****Z *B****G*****M***QR******** ***************P*****V**Y* ``` [Answer] # Perl, 24 ``` $_ x=<>;s/(.| )./\1*/g ``` Requires the `-p` switch, which accounts for two of the bytes. Reads from STDIN. ### How it works * Because of the `-p` switch, Perl reads the first input lie and stores its contents in `$_`. * The command `$_ x=<>;` duplicates the first input line the number of times the second input line (`<>`) specifies. * The command `s/(.|\n)./\1*/g;` consumes two characters and replaces the second (which cannot be a newline) with an asterisk. It does this until it has consumed the entire contents of `$_`. Since newlines count as the first character, this will obfuscate all even characters on the first line and all odd characters on the remaining lines. * Because of the `-p` switch, Perl prints the contents of `$_`. ### Example input ``` codegolf 4 ``` ### Example output ``` c*d*g*l* *o*e*o*f *o*e*o*f *o*e*o*f ``` [Answer] # Java - 490 Yeah, not really golfed or anything. Oh well, here it is: ``` import java.util.ArrayList;public class Anonymise {public static void main(String[] args){ArrayList[] c=new ArrayList[Integer.parseInt(args[1])];for(int i=0;i<c.length;i++)c[i]=new ArrayList();for(char a:args[0].toCharArray()){int f=new java.util.Random().nextInt(c.length);c[f].add(a);for(int i=0;i<c.length;i++)if(i!=f)c[i].add('*');}ArrayList<String> b = new ArrayList<String>();for(ArrayList a:c){String s = "";for(Object o : a)s += o;b.add(s);}for(String s : b)System.out.println(s);}} ``` In a nice, legible format: ``` import java.util.ArrayList; public class Anonymise { public static void main(String[] args){ ArrayList[] c = new ArrayList[Integer.parseInt(args[1])]; for(int i=0;i<c.length;i++) c[i]=new ArrayList(); for(char a:args[0].toCharArray()){ int f = new java.util.Random().nextInt(c.length); c[f].add(a); for(int i=0;i<c.length;i++) if(i!=f)c[i].add('*'); } ArrayList<String> b = new ArrayList<String>(); for(ArrayList a:c){ String s = ""; for(Object o : a) s += o;b.add(s); } for(String s : b) System.out.println(s); } } ``` Sample usage (When run from the compiled class) ``` > java Anonymise OnlinePerson 3 *n****P***o* O*li***e**** ****ne**rs*n ``` [Answer] # Python 3 - 187 (-20 = 167) Took me a while to write, could probably be golfed more. ``` import sys,random as a b=sys.argv x=[""for i in' '*int(b[2])] for i in range(len(b[1])):n=a.randrange(len(x));x=[c+["*",b[1][len(c)]][j==n]for j,c in enumerate(x)] for i in x:print(i) ``` Sample usage: ``` $ python tx.py super_anonymous_user 3 s******n**y*ou****e* **p***a**n*m**s_us*r *u*er_**o*********** ``` ## As a function - 161 (-20 = 141) ``` from random import* def f(c,n): x=[""for i in' '*n] for i in range(len(c)):n=randrange(len(x));x=[v+["*",c[len(v)]][j==n]for j,v in enumerate(x)] return x ``` [Answer] # C# 184 ``` namespace System.Linq{class P{static void Main(string[] a){int n=int.Parse(a[1]);for(int i=0;i<n;i++)Console.WriteLine(new String(a[0].Select((c,x)=>(i+x)%n==0?c:'*').ToArray()));}}} ``` Non-golfed ``` namespace System.Linq { class P { static void Main(string[] a) { int n = int.Parse(a[1]); for (int i = 0; i < n; i++) Console.WriteLine(new String(a[0].Select((c, x) => (i + x) % n == 0 ? c : '*').ToArray())); } } } ``` Sample: ``` > Anonymize.exe "qwertyuio" 4 q***t***o ***r***i* **e***u** *w***y*** ``` [Answer] # Perl 6 (77 bytes) This may count as cheating, but it solves the problem (it doesn't print the string entirely). ``` ($_,$!)=@*ARGS;.say for .chop~"*","*"x.chars-1~.substr(*-1),"*"x.chars xx$!-2 ``` And the sample output. ``` > ./script.p6 ultimately_awesome 6 ultimately_awesom* *****************e ****************** ****************** ****************** ****************** ``` [Answer] # JavaScript - 170 ``` function s(a,e){o="",b=a.length,x=b/e|0,y=b-x*e;for(c=1;c<=e;c++){r="*";o+=Array((c-1)*x+1).join(r)+a.substr(c*x-x,c==e?x+y:x)+Array(c<e?b-c*x+1:0).join(r)+"\n"}return o} ``` Quick one, breaks if you supply a name and ask for more pieces than characters, but works up to that point and down to 1. Could be golfed more I assume, so may revise or take advice, as it's a bit of a mess. Edit: Golfed further (from 187) with removal of brackets (@Synthetica) and Math.floor replacement from @toothbrush. For loop change as suggested results in errors in the output. [Answer] # R, (120-20)=100 bytes (2 different solutions of same length) Beside the conciseness, R for sure features the best random number generator! :) Here the 1st solution of length 120: ``` function(s,n){ c=strsplit(s,"")[[1]] e=sample(n,nchar(s),T) sapply(1:n,function(i)paste(ifelse(e==i,c,"*"),collapse="")) } ``` If the function is named as *f*, the output looks like: ``` > f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 7) "******GH*****************Z" "ABCD*********N************" "***********L**O***********" "*********J**M**P*RS*U**X**" "**********K***********W***" "*****F**I*******Q*********" "****E**************T*V**Y*" ``` And here the 2nd solution, again with random masking, and again 120 bytes long: ``` function(s,n){ x=matrix("*",n,(m=nchar(s))) x[cbind(sample(n,m,T),1:m)]=strsplit(s,"")[[1]] apply(x,1,paste,collapse="") } ``` [Answer] # Scala (1) 177 bytes After the solution in R I also found one in Scala, here it is: ``` def f(s:String, n:Int)={ def c=s map (z=>z.toString) def r=(1 to s.length) map (v=>v%n+1) (for (i<-1 to n) yield s zip r map (t=>if(t._2==i) t._1 else "*") mkString "") map println } ``` # Scala (2) 129 bytes After a short research I found the method *zipWithIndex*. Wonderful :) ``` def f(s:String, n:Int)={ (for (i<-0 until n) yield s.zipWithIndex.map (t=>if(t._2 % n==i) t._1 else "*") mkString "") map println } ``` Here the solution: ``` f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4) ***D***H***L***P***T***X** A***E***I***M***Q***U***Y* *B***F***J***N***R***V***Z **C***G***K***O***S***W*** ``` [Answer] # Javascript - 166 ``` function s(b,a){o="";k=Array(a).join("*");t=k+b+k;for(i=a;0<i;i--)o+=t.replace(RegExp(".{"+(a-1)+"}(.)","g"),k+"$1").substr(i-1,b.length)+"\n",t=t.substr(1);return o} ``` Using regex. Sample ``` > s("four",5) f*** *o** **u* ***r **** > s("evil_company_that_makes_me_shiver",3) e**l**o**a**_**a**m**e**m**s**v** *v**_**m**n**t**t**a**s**e**h**e* **i**c**p**y**h**_**k**_**_**i**r ``` [Answer] # k [50-20=30 chars] ``` {.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x} ``` ### Explanation 1. Input: x=String which needs to be masked, y=number of lines 2. Count the number of characters c in string and create y buckets. 3. Place c mod y characters in each bucket. 4. For each bucket, print "\*" for the remaining numbers not in that bucket. ### Example ``` {.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x}["abcdefghijklmnopqrstuvwxyz";4] ``` ### Output ``` "ab*d*f***j**********u*w***" "**c*e*gh**k*****q*s*******" "********i***mn*****t*v**y*" "***********l**op*r*****x*z" ``` [Answer] ## JavaScript - 139-20=119 ``` function e(s,c){r=[];for(i=c;i--;)r[i]='';for(i=0;i<s.length*c;i++)x=i%c,n=(x<1?Math.random()*c|0:n),r[x]+=(n!=x?'*':s[(i/c)|0]);return r} ``` Usage and sample output: ``` console.log(e("evil_company_that_makes_me_shiver", 3)); ["**i*_**mp*****h**_ma**********v**", "*****co**a***t*a******s*me_*hi*e*", "ev*l******ny_***t***ke*_***s****r"] ``` As the masking is random, the output may also look like this: ``` console.log(e("evil_company_that_makes_me_shiver", 2)); ["evil_company_that_makes_me_shiver", "*********************************"] ``` [Answer] # Julia 56-20=36 (works often) ``` f(s,n)=[join([rand()<1.9/n?c:"*" for c in s]) for r=1:n] julia> f("evilcompany!!!",4) 4-element Array{Union(UTF8String,ASCIIString),1}: "e**l**mp*ny*!*" "***lco********" "e*il**m*a*y!*!" "evil**m*an***!" ``` Trying to go for a shorter random solution I decided to sacrifice guaranteed functioning for a shorter solution. It's really not a very good solution. [Answer] # F# - ~~81~~ ~~80~~ 75 This is fairly similar to others that have been offered: ``` let a s n=[for i in 0..n-1->String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])s] ``` Sample: ``` a "evil_company_that_makes_me_shiver" 7 e******m******h******e******h**** ******o******t******k******s***** *****c******_******a******_****** ****_******y******m******e******r ***l******n******_******m******e* **i******a******t******_******v** *v******p******a******s******i*** ``` As a full, stand-alone application it comes out to ~~160~~ ~~155~~ 156 characters: ``` [<EntryPoint>]let m (a:string array)= let n=System.Int32.Parse a.[1] for i in 0..n-1 do printfn"%s"(String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])a.[0]) 0 ``` ]
[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/21841/edit). Closed 3 years ago. [Improve this question](/posts/21841/edit) ***EDIT: If you're using Lisp, I have given some guidelines at the bottom in counting bytes.*** **Objective:** Make the shortest function that splits a string at non-digits and returns an array consisting of only digits in each string, without the use of any regular expressions. Leading zeroes are to be included in each string. ## Current Standings (separated in categories): * **C/C++/C#/Java:** 68 (C) .... * **GolfScript/APL/J:** 13 (APL) * **All others:** 17 (Bash, uses `tr`), 24 (Ruby) ## Rules: * The format must be as a function with a single string argument. Up to two additional arguments may be added if necessary for the proper return of the array (e.g. sh/csh/DOS Batch needs an extra variable reference to return, etc.). * The primary function declaration doesn't count, and nor does importing other standard libraries. `#include`s, `import`s, and `using`s don't count. Everything else does. This does include `#define`s and helper functions. Sorry for the confusion. Refer to this as a helpful guide as to what does/does not count (written in C-style syntax) ``` // doesn't count toward total, may be omitted unless // non-obvious, like half of Java's standard library. #include &lt;stdio.h&gt; import some.builtin.Class // doesn't count, see above #define printf p // counts towards total /* Any other preprocessor directives, etc. count. */ int i = 0; // counts someFunction(); // counts char[][] myMainSplitFunction(char[][] array) { // doesn't count // Everything in here counts return returnArray; // Even this counts. } // doesn't count /* Everything in here counts, including the declaration */ char[][] someHelperFunction(char[] string) { // stuff } // even this counts ``` * The output must be a string array or similar (Array lists in Java and similar are acceptable). Examples of accepted output: `String[]`, `char[][]`, `Array<String>`, `List<String>`, and `Array` (object). * The array must contain only contain variable-length string primitives or string objects. No empty strings should be present in the return, with the exception below. **Note:** the strings are to contain a string of consecutive matches, such as the example input and output below. * If there are no matches, then the function body should return `null`, an empty array/list, or an array/list containing an empty string. * No external libraries allowed. * DOS line endings count as one byte, not two (already covered in meta, but needs to be emphasized) * **And the biggest rule here: no regular expressions allowed.** This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, so shortest code wins. Good luck! And here are some example inputs and outputs (with C-style escapes): ``` Input: "abc123def456" Output: ["123", "456"] Input: "aitew034snk582:3c" Output: ["034", "582", "3"] Input: "as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)" Output: ["5493", "54", "430", "52", "9"] Input: "sasprs]tore\"re\\forz" Output: null, [], [""], or similar ``` Please put how many bytes used by your answers, and as always, happy golfing! --- ## Guidelines for Lisp Here's what does and doesn't count in Lisp dialects: ``` ;;; Option 1 (defun extract-strings (a b) ; Doesn't count (stuff) ;;; Everything in here counts ) ; Doesn't count ;;; Option 2 (defun extract-strings (string &aux (start 0) (end 0)) ; Doesn't count (stuff) ;;; Everything in here counts ) ; Doesn't count. ``` All other lambdas fully count towards the byte count. [Answer] # APL, 13 chars (or 28 / 30 bytes, read below) ``` {⍵⊂⍨⍵∊∊⍕¨⍳10} ``` I see you've banned GolfScript from your question. I understand your sentiment, but I hope this community won't eventually ban APL, because it's a truly remarkable programming language with a long history, not to mention a lot of fun to code in. Maybe it could just be scored differently, if people feel it's competing unfairly. I'll post my thoughts on this matter to that thread you've linked. On that same token, I've always added a footnote to my APL posts, claiming that APL could be scored as 1 char = 1 byte. My claim rests on the fact that a few (mostly commercial) APL implementations still support their own legacy single-byte encoding, with the APL symbols mapped to the upper 128 byte values. But maybe this is too much of a stretch, in which case you may want to score this entry as 28 bytes in UTF-16 or 30 bytes in UTF-8. **Explanation** ``` { ⍳10} make an array of naturals from 1 to 10 ⍕¨ convert each number into a string ∊ concatenate the strings into one (it doesn't matter that there are two 1s) ⍵∊ test which chars from the argument are contained in the digit string ⍵⊂⍨ use it to perform a partitioned enclose, which splits the string as needed ``` **Examples** ``` {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x' 5 0 {⍵⊂⍨⍵∊∊⍕¨⍳10} 'z526ks4f.;8]\p' 526 4 8 ``` The default output format for an array of strings does not make it clear how many strings are there in the array, nor how many blanks. But a quick manipulation to add quotes should make it clear enough: ``` {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x' "5" "0" {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10} 'z526ks4f.;8]\p' "526" "4" "8" ``` [Answer] ## Python 47 **Implementation** ``` f=lambda s:"".join([' ',e][e.isdigit()]for e in s).split() ``` **Demo** ``` >>> sample=["abc123def456","aitew034snk582:3c","as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)","sasprs]tore\"re\\forz"] >>> [f(data) for data in sample] [['123', '456'], ['034', '582', '3'], ['5493', '54', '430', '52', '9'], []] ``` **Algorithm** *Convert each non-digit character to space and then split the resultant string. A simple and clear approach.* **And a fun solution with itertools (71 characters)** ``` f1=lambda s:[''.join(v)for k,v in __import__("itertools").groupby(s,key=str.isdigit)][::2] ``` [Answer] ### Ruby, 70 ``` f=->(s){s.chars.chunk{|c|c.to_i.to_s==c}.select{|e|e[0]}.transpose[1]} ``` [Online Version](https://ideone.com/JC3uH2) for testing Since converting any non-digit character to an int returns 0 in Ruby (with to\_i), converting every char to int and back to char is the non-regex way to check for a digit... [Answer] # Bash, 21 bytes 17/21 bytes (improved by [DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digitaltrauma)) Building a space-separated list with `tr` ``` function split() { tr -c 0-9 \ <<E $1 E } ``` replaces any non digit by a space ## Usage ``` $ for N in $(split 'abc123def456'); do echo $N; done 123 456 ``` ## Edit as pointed by the comments below, the code can be stripped down to 17 bytes: ``` function split() (tr -c 0-9 \ <<<$1) ``` and as the result is not stricly speaking a Bash array, the usage should be ``` a=(`split "abc123def456"`); echo ${a[@]} ``` and the extra `(``)` should be counted [Answer] # bash, 26 (function contents: 22 + array assignment overhead 4) This isn't going to beat [the other `bash` answer](https://codegolf.stackexchange.com/a/21990/11259), but its interesting because it might make you double-take: ``` f()(echo ${1//+([!0-9])/ }) ``` Usage is: ``` $ a=(`f "ab5c0x"`); echo ${a[@]} 5 0 $ a=(`f "z526ks4f.;8]\p"`); echo ${a[@]} 526 4 8 $ ``` At the first quick glance, `//+([!0-9])/` looks a lot like a regexp substitution, but it isn't. It is a [bash parameter expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html), which follows [pattern-matching rules](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html), instead of regular expression rules. Returning true bash array types from bash functions is a pain, so I chose to return a space-delimited list instead, then convert to an array in an array assignment outside of the function call. So in the interests of fairness, I feel the `(` `)` around the function call should be included in my score. [Answer] # Mathematica 32 ``` StringCases[#,DigitCharacter..]& ``` Usage ``` inps ={"abc123def456", "aitew034snk582:3c", "as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)", "sasprs]tore\"re\\forz"} StringCases[#,DigitCharacter..]&/@inps {{"123", "456"}, {"034", "582", "3"}, {"5493", "54", "430", "52", "9"}, {} } ``` The equivalent using regexes is much longer!: ``` StringCases[#, RegularExpression["[0-9]+"]] & ``` [Answer] # Smalltalk (Smalltalk/X), 81 ``` f := [:s|s asCollectionOfSubCollectionsSeparatedByAnyForWhich:[:ch|ch isDigit not]] ``` f value:'abc123def456' -> OrderedCollection('123' '456') f value:'aitew034snk582:3c' -> OrderedCollection('034' '582' '3') f value:'as5493tax54\[[email protected]](/cdn-cgi/l/email-protection)' -> OrderedCollection('5493' '54' '430' '52' '9') f value:'sasprs]tore\"re\forz' -> OrderedCollection() sigh - Smalltalk has a tendency to use veeeery long function names... [Answer] # C, 68 bytes (only the function's body) ``` void split (char *s, char **a) { int c=1;for(;*s;s++)if(isdigit(*s))c?*a++=s:0,c=0;else*s=0,c=1;*a=0; } ``` The first argument is the input string, the second one is the output array, which is a NULL-terminated string array. Sufficient memory must be reserved for `a` before calling the function (worst case: `sizeof(char*)*((strlen(s)+1)/2)`). The input string is modified by the function (every non-digit character is replaced by `'\0'`) ## Usage example ``` #include <stdio.h> #include <stdlib.h> #include <ctype.h> void split (char *s, char **a) { int c=1;for(;*s;s++)if(isdigit(*s))c?*a++=s:0,c=0;else*s=0,c=1;*a=0; } void dump(char **t) { printf("[ ");for(;*t;t++)printf("%s ", *t);printf("]\n"); } int main() { char **r = malloc(1024); char test1[] = "abc123def456"; char test2[] = "aitew034snk582:3c"; char test3[] = "as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)"; char test4[] = "sasprs]tore\"re\\forz"; split(test1,r); dump(r); split(test2,r); dump(r); split(test3,r); dump(r); split(test4,r); dump(r); return 0; } ``` ## Output ``` [ 123 456 ] [ 034 582 3 ] [ 5493 54 430 52 9 ] [ ] ``` ## Un-golfed version: ``` void split (char *s, char **a) { int c=1; // boolean: the latest examined character is not a digit for(;*s;s++) { if(isdigit(*s)) { if(c) *a++ = s; // stores the address of the beginning of a digit sequence c=0; } else { *s=0; // NULL-terminate the digit sequence c=1; } } *a = 0; // NULL-terminate the result array } ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 27 bytes ``` {[[email protected]](/cdn-cgi/l/email-protection)@=t-!#t:&~^(,/$!10)?x} ``` [Try it online!](https://tio.run/##FcndCsIgGIDha5lFbTCX82c0I/JCLLClIwYu9IOkqFu3dvCePO@E/ehzdvKdVAPqCLhYgdx8L2W9WxctqU7pk922ROY6tJTdrOOiQwdk7mCfhPHoJ7Gnkg2LRcF7BiYJrjVnBAuqxr5xy4smPkI8wxysRv@0m8MLVfkH "K (ngn/k) – Try It Online") * `(,/$!10)` generate "0123456789" * `&~^(...)?x` identify indices of digits in the input (e.g. `"abc123def456"` => `3 4 5 9 10 11`) * `.t@=t-!#t:` split the indices into groups of adjacent indices (e.g. `3 4 5 9 10 11` => `(3 4 5;9 10 11)`) * `x@` index back into the original output and return (e.g. `x[(3 4 5;9 10 11)]` => `("123";"456")`) [Answer] ## R, 81 ``` f=function(x){ s=strsplit(x,"",T)[[1]] i=s%in%0:9 split(s,c(0,cumsum(!!diff(i))))[c(i[1],!i[1])] } ``` The function accepts a string and returns a list of strings. Examples: ``` > f("abc123def456") $`1` [1] "1" "2" "3" $`3` [1] "4" "5" "6" ``` - ``` > f("aitew034snk582:3c") $`1` [1] "0" "3" "4" $`3` [1] "5" "8" "2" $`5` [1] "3" ``` - ``` > f("as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)") $`1` [1] "5" "4" "9" "3" $`3` [1] "5" "4" $`5` [1] "4" "3" "0" $`7` [1] "5" "2" $`9` [1] "9" ``` - ``` > f("sasprs]tore\"re\\forz") $<NA> NULL ``` Note: `$x` is the name of the list element. [Answer] ## Perl, 53 **Edit:** on no matches, sub now returns list with empty string (instead of empty list) as required. It also avoids splitting on single space character, as it triggers *'split on any white-space'* behavior, which probably violates the rules. I could use `/ /` delimiter, which would split on single space, but paradoxically it would *look* like using regexp pattern. I could use `unpack` at the cost of some extra characters and so get rid of `split` controversy altogether, but I think that, what I finish with, splitting on a literal character (other than space) is OK. ``` sub f{shift if(@_=split a,pop=~y/0-9/a/csr)[0]eq''and$#_;@_} ``` And, no, Perl's transliteration operator doesn't do regular expressions. I can unroll 0-9 range to `0123456789` if that's the problem. [Answer] ## VBScript, 190 (164 without function declaration) ``` Function f(i) For x=1 To Len(i) c=Mid(i,x,1) If Not IsNumeric(c) Then Mid(i,x,1)=" " End If Next Do l=Len(i) i=Replace(i," "," ") l=l-Len(i) Loop Until l=0 f=Split(Trim(i)," ") End Function ``` While not competitive at all, I'm surprised that VBScript comes out this short on this given how verbose it is (13 bytes for the CRs alone). It loops through the string, replacing any non-numeric characters with spaces, then reduces all the whitespace to single spaces, and then uses a space delimiter to divide it. **Test cases** ``` Input: "ab5c0x" Output: 5,0 Input: "z526ks4f.;8]\p" Output: 526,4,8 ``` [Answer] ## Common Lisp (1 according to the letter; ≈173 according to the spirit) Here's a readable version. The byte count is fairly high because of the long names in things like `digit-char-p` and `position-if` and `vector-push-extend`. ``` (defun extract-numeric-substrings (string &aux (start 0) (end 0) (result (make-array 0 :adjustable t :fill-pointer 0))) (loop (unless (and end (setq start (position-if #'digit-char-p string :start end))) (return result)) (setq end (position-if (complement #'digit-char-p) string :start (1+ start))) (vector-push-extend (subseq string start end) result))) ``` ``` (extract-numeric-substrings "abc123def456") #("123" "456") (extract-numeric-substrings "aitew034snk582:3c") #("034" "582" "3") (extract-numeric-substrings "as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)") #("5493" "54" "430" "52" "9") (extract-numeric-substrings "sasprs]tore\"re\\forz") #() ``` The concept of "function declaration" is sort of vague. Here's a version that only has one byte (the character `x` in the function body); everything else is bundled in to the auxiliary variables of the function's lamba list (part of the function's declaration): ``` (defun extract-numeric-substrings (string &aux (start 0) (end 0) (result (make-array 0 :adjustable t :fill-pointer 0)) (x (loop (unless (and end (setq start (position-if #'digit-char-p string :start end))) (return result)) (setq end (position-if (complement #'digit-char-p) string :start (1+ start))) (vector-push-extend (subseq string start end) result)))) x) ``` The actual byte count will depend on how many of auxiliary declarations would have to be moved into the body for this to be deemed acceptable. Some local function renaming would help, too (e.g., shorten `position-if` since it appears twice, use single letter variables, etc.). This rendering of the program has 220 characters: ``` (LOOP(UNLESS(AND END(SETQ START(POSITION-IF #'DIGIT-CHAR-P STRING :START END)))(RETURN RESULT))(SETQ END(POSITION-IF(COMPLEMENT #'DIGIT-CHAR-P)STRING :START(1+ START)))(VECTOR-PUSH-EXTEND(SUBSEQ STRING START END)RESULT)) ``` If nothing else, this should promote [Common Lisp's &aux variables](http://www.lispworks.com/documentation/HyperSpec/Body/03_dae.htm). This can be written more concisely with `loop`, of course: ``` (defun extract-numeric-substrings (s &aux (b 0) (e 0) (r (make-array 0 :fill-pointer 0))) (loop with d = #'digit-char-p while (and e (setq b (position-if d s :start e))) finally (return r) do (setq e (position-if-not d s :start (1+ b))) (vector-push-extend (subseq s b e) r))) ``` The `loop` form, with extra space removed, has 173 characters: ``` (LOOP WITH D = #'DIGIT-CHAR-P WHILE(AND E(SETQ B(POSITION-IF D S :START E)))FINALLY(RETURN R)DO(SETQ E(POSITION-IF-NOT D S :START(1+ B)))(VECTOR-PUSH-EXTEND(SUBSEQ S B E)R)) ``` [Answer] # JavaScript, 240 bytes And for those of you who are curious, here's my probably huge golf: ``` function split(a) { // begin function function f(c){for(var a=-1,d=9;d--;){var e=c.indexOf(d+"");0 >e||e<a&&(a=e)}return 0<a?a:null}var c=f(a);if(null==c)retur n null;var d=[];for(i=0;;){a=a.substring(c);d[i]||(d[i]=""); c=f(a);if(null==c)break;d[i]+=a.charAt(c);0<c&&i++}return d; } // end function ``` ### Above in pretty print: ``` function split(a) { function f(c) { for (var a = -1, d = 9;d--;) { var e = c.indexOf(d + ""); 0 > e || e < a && (a = e); } return 0 < a ? a : null; } var c = f(a); if (null == c) return null; var d = []; for (i = 0;;) { a = a.substring(c); d[i] || (d[i] = ""); c = f(a); if (null == c) break; d[i] += a.charAt(c); 0 < c && i++; } return d; } ``` ### Above in normal descriptive code ``` function split(a) { function findLoop(string) { var lowest = -1; var i = 9; while (i--) { var index = string.indexOf(i + ''); if (index < 0) continue; if (index < lowest) lowest = index; } return (lowest > 0) ? lowest : null; } var index = findLoop(a); if (index == null) return null; var ret = []; i = 0; for ( ; ; ) { a = a.substring(index); if (!ret[i]) ret[i] = ''; index = findLoop(a); if (index == null) break; ret[i] += a.charAt(index); if (index > 0) i++; } return ret; } ``` [Answer] ## PHP 134 ``` function f($a){ $i=0;while($i<strlen($a)){!is_numeric($a[$i])&&$a[$i]='-';$i++;}return array_filter(explode('-',$a),function($v){return!empty($v);}); } ``` [Answer] # C, 158 ``` #define p printf char s[100],c;int z,i;int main(){while(c=getchar())s[z++]=(c>47&&c<58)*c;p("[");for(;i<z;i++)if(s[i]){p("\"");while(s[i])p("%c",s[i++]);p("\",");}p("]");} ``` Since C doesnt have array print functions built-in I had to do that work on my own so I apologive that there is a final comma in every output. Essentially what that code does is it reads the string if it is not a digit it replaces it with '\0' and then I just loop through the code and print out all of the chains of digits.(EOF=0) > > Input: ab5c0x > > > Output: ["5","0",] > > > > Input: z526ks4f.;8]\p > > > Output: ["526","4","8",] > > > [Answer] # C#, 98 ``` static string[] SplitAtNonDigits(string s) { return new string(s.Select(c=>47<c&c<58?c:',').ToArray()).Split(new[]{','},(StringSplitOptions)1); } ``` First, this uses the LINQ `.Select()` extension method to turn all non-digits into commas. `string.Replace()` would be preferable, since it returns a `string` rather than a `IEnumerable<char>`, but `string.Replace()` can only take a single char or string and can't make use of a predicate like `char.IsDigit()` or `47<c&c<58`. As mentioned, `.Select()` applied to a string returns an `IEnumerable<char>`, so we need to turn it back into a string by turning it into an array and passing the array into the `string` constructor. Finally, we split the string at commas using `string.Split()`. `(StringSplitOptions)1` is a shorter way of saying `StringSplitOptions.RemoveEmptyEntries`, which will automatically takes care of multiple consecutive commas and commas at the start/end of the string. [Answer] **JS/Node : 168 162 147 138 Chars** ``` function n(s){ var r=[];s.split('').reduce(function(p,c){if(!isNaN(parseInt(c))){if(p)r.push([]);r[r.length-1].push(c);return 0;}return 1;},1);return r; } ``` Beautified version: ``` function n(s) { var r = []; s.split('').reduce(function (p, c) { if (!isNaN(parseInt(c))) { if (p) { r.push([]); } r[r.length - 1].push(c); return 0; } return 1; }, 1); return r; } ``` [Answer] ## Ruby, 24 ``` f=->s{s.tr(" -/:-~",' ').split} ``` Defines digits using negative space within the printable ascii range. [Answer] **php**, **204** ``` function s($x){$a=str_split($x);$c=-1;$o=array(); for($i= 0;$i<count($a);$i++){if(ord($a[$i])>=48&&ord($a[$i])<=57) {$c++;$o[$c]=array();}while(ord($a[$i])>=48&&ord($a[$i])<=57) {array_push($o[$c],$a[$i]);$i++;}}return $o;} ``` **Descriptive Code:** ``` function splitdigits($input){ $arr = str_split($input); $count = -1; $output = array(); for($i = 0; $i < count($arr); $i++){ if(ord($arr[$i]) >= 48 && ord($arr[$i]) <= 57){ $count++; $output[$count] = array(); } while(ord($arr[$i]) >= 48 && ord($arr[$i]) <= 57){ array_push($output[$count], $arr[$i]); $i++; } } return $output; } ``` This is pretty long code and I'm sure there will be a much shorter php version for this code golf. This is what I could come up with in php. [Answer] **Python** ``` def find_digits(_input_): a,b = [], "" for i in list(_input_): if i.isdigit(): b += i else: if b != "": a.append(b) b = "" if b != "": a.append(b) return a ``` [Answer] ## Python ~~104~~ 83 ``` def f(s, o=[], c=""): for i in s: try:int(i);c+=i except:o+=[c];c="" return [i for i in o+[c] if i] ``` @Abhijit answer is far clever, this is just a "minified" version of what i had in mind. ``` assert f("abc123def456") == ["123", "456"] assert f("aitew034snk582:3c") == ["034", "582", "3"] assert f("as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)") == ["5493", "54", "430", "52", "9"] assert f("sasprs]tore\"re\\forz") == [] ``` This yields no output, so the code is working, if ran one by one, as some variables are defined at the declaration. [Answer] ## PHP ~~98~~ 89 As in DigitalTrauma's bash answer, this doesn't use a regex. ``` function f($x) { // Only the following line counts: for($h=$i=0;sscanf(substr("a$x",$h+=$i),"%[^0-9]%[0-9]%n",$j,$s,$i)>1;)$a[]=$s;return@$a; } ``` Test cases: ``` php > echo json_encode(f("abc123def456")), "\n"; ["123","456"] php > echo json_encode(f("aitew034snk582:3c")), "\n"; ["034","582","3"] php > echo json_encode(f("as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)")), "\n"; ["5493","54","430","52","9"] php > echo json_encode(f("sasprs]tore\"re\\forz")), "\n"; null ``` [Answer] # Haskell 31 ``` {-# LANGUAGE OverloadedStrings #-} import Data.Char (isDigit) import Data.Text (split) f=filter(/="").split(not.isDigit) ``` It splits the string on all non-numeric characters and removes the empty strings generated by consecutive delimiters. [Answer] ## VBA 210, 181 without function declaration ``` Function t(s) Dim o() For Each c In Split(StrConv(s,64),Chr(0)) d=IsNumeric(c) If b And d Then n=n&c ElseIf d Then:ReDim Preserve o(l):b=1:n=c ElseIf b Then:b=0:o(l)=n:l=l+1:End If:Next:t=o End Function ``` [Answer] # Rebol (66 chars) ``` remove-each n s: split s complement charset"0123456789"[empty? n]s ``` Ungolfed and wrapped in function declaration: ``` f: func [s] [ remove-each n s: split s complement charset "0123456789" [empty? n] s ] ``` Example code in Rebol console: ``` >> f "abc123def456" == ["123" "456"] >> f "aitew035snk582:3c" == ["035" "582" "3"] >> f "as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)" == ["5493" "54" "430" "52" "9"] >> f {sasprs]torer"re\\forz} == [] ``` [Answer] # JavaScript, 104 97 89 *Golfed:* **Edit:** When the loops walks off the end of the array, `c` is `undefined`, which is falsy and terminates the loop. **2/27:** Using `?:` saves the wordiness of `if/else`. ``` function nums(s) { s+=l='length';r=[''];for(k=i=0;c=s[i];i++)r[k]+=+c+1?c:r[k+=!!r[k][l]]=''; r[l]--;return r } ``` The carriage return in the body is for readability and is not part of the solution. *Ungolfed:* The idea is to append each character to the last entry in the array if it is a digit and to ensure the last array entry is a string otherwise. ``` function nums(s) { var i, e, r, c, k; k = 0; s+='x'; // ensure the input does not end with a digit r=['']; for (i=0;i<s.length;i++) { c=s[i]; if (+c+1) { // if the current character is a digit, append it to the last entry r[k] += c; } else { // otherwise, add a new entry if the last entry is not blank k+=!!r[k].length; r[k] = ''; } } r.length--; // strip the last entry, known to be blank return r; } ``` [Answer] # Javascript, 72 ``` function f(a){ a+=".",b="",c=[];for(i in a)b=+a[i]+1?b+a[i]:b?(c.push(b),""):b;return c } ``` Ungolfed ``` a+=".",b="",c=[]; //add '.' to input so we dont have to check if it ends in a digit for(i in a) b=+a[i]+1? //check if digit, add to string if it is b+a[i]: b? //if it wasnt a digit and b contains digits push it (c.push(b),""): //into the array c and clear b b; //else give me b back return c ``` Sample input/output ``` console.log(f("abc123def456")); console.log(f("aitew034snk582:3c")); console.log(f("as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)")); console.log(f("sasprs]tore\"re\\forz")); ["123", "456"] ["034", "582", "3"] ["5493", "54", "430", "52", "9"] [] ``` **[JSFiddle](http://jsfiddle.net/dschu012/age5H/)** [Answer] ## R 52 This function splits strings by character class (this is not regex! :)) class is N - numeric characters and P{N} means negation of this class. o=T means omit empty substrings. ``` x ## [1] "wNEKbS0q7hAXRVCF6I4S" "DpqW50YfaDMURB8micYd" "gwSuYstMGi8H7gDAoHJu" require(stringi) stri_split_charclass(x,"\\P{N}",o=T) ## [[1]] ## [1] "0" "7" "6" "4" ## [[2]] ## [1] "50" "8" ## [[3]] ## [1] "8" "7" ``` [Answer] ## PHP 99 ``` <?php $a = function($s) { foreach(str_split($s)as$c)$b[]=is_numeric($c)?$c:".";return array_filter(explode('.',implode($b))); }; var_dump($a("abc123def456")); var_dump($a("aitew034snk582:3c")); var_dump($a("as5493tax54\\[[email protected]](/cdn-cgi/l/email-protection)")); var_dump($a("sasprs]tore\"re\\forz")); ``` ### Output ``` array(2) { [3]=> string(3) "123" [6]=> string(3) "456" } array(3) { [5]=> string(3) "034" [8]=> string(3) "582" [9]=> string(1) "3" } array(5) { [2]=> string(4) "5493" [5]=> string(2) "54" [6]=> string(3) "430" [7]=> string(2) "52" [9]=> string(1) "9" } array(0) { } ``` ]
[Question] [ The objective is to write java code that detects the JVM version relying in compatibility changes, side effects, bugs and/or undefined behavior that works in a way in one version and another way in another version. Further, the code should be at least a bit readable, without sacrificing whitespaces and legible variable names. To ensure that objective, the exact formal rules are: 1. The code must be written in java and should output the JRE version in which it is running. 2. The code must not use any JDK or JRE API provided specifically for detecting the java version or which gives the JDK or JRE version for free. 3. The code must not use reflection. 4. The code is only required to work in Hotspot Java SE 5, 6 and 7, but may work in other JVMs. 5. The code must not use any third-party libraries in the classpath. 6. The code must not start any other process, java or not. 7. The code must not use environment variables. 8. The code must not search the file system looking for pre-existing files or folders. 9. The code must be contained in a single file and be called via `public static void main(String[] args)` or `public static void main(String... args)`. 10. The code must not use any non-public API present in the JRE. 11. The code must not generate any NoClassDefFoundError, NoSuchMethodError, ClassNotFoundException or NoSuchMethodException during its execution. 12. The code should run in a system disconnected from the internet or from any local network. 13. You should provide an explanation of why it behaves in one way in a version and another way in another version. # Scoring The method used for measuring the best solution is max(n/s), where n is the number of different java versions detected without violating any of these rules (at least versions 5, 6 and 7) and s is the number of lexical tokens in the solution. [Answer] I'm not sure what my score is, because it depends on what precisely you consider to be a lexical token, but I'm trying to abuse that counting system as much as possible with a long string... It also depends on whether you count this as identifying 7 different versions or 16... (It could trivially be extended up to 190). ``` class V extends ClassLoader { public static void main(String[]args) { for(byte b=60;;) try { byte[]buf="\u00ca\u00fe\u00ba\u00be\u0000\u0000\u00002\u0000\u0005\u0007\u0000\u0003\u0007\u0000\u0004\u0001\u0000\u0001A\u0001\u0000\u0010java/lang/Object\u0006\u0000\u0000\u0001\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000".getBytes("ISO-8859-1"); buf[7]=b--; new V().defineClass(buf,0,53); System.out.println(b-43); break; } catch(Throwable t){} } } ``` It works by attempting to define an interface in a custom classloader with descending major version numbers of the class format. The first one which doesn't throw a `java.lang.UnsupportedClassVersionError` corresponds to the VM's version. [Answer] # 6/102 = 0.0588 Detects 6 versions. Has 102 lexical tokens (down from 103, after I deleted `public` in `public class`). ``` import java.security.Signature; class GuessVersion { public static void main(String[] args) { String version = "Java 1.1"; try { "".getBytes("ISO8859_13"); version = "Java 1.3"; "".getBytes("ISO8859_15"); version = "Java 1.4"; Signature.getInstance("SHA256withRSA"); version = "Java 5"; "".getBytes("KOI8_U"); version = "Java 6"; Signature.getInstance("SHA256withECDSA"); version = "Java 7"; } catch(Exception e) {} System.out.println(version); } } ``` [Java 1.1](https://duckduckgo.com/?q=JDK%201.1.x%20documentation) introduced character encodings and cryptographic algorithms to Java. Later versions added more encodings and algorithms. This program tries to use encodings and algorithms until it catches an exception. I expect a missing encoding to throw `java.io.UnsupportedEncodingException` and a missing algorithm to throw `java.security.NoSuchAlgorithmException`. I had an old PowerPC Macintosh with four old versions of Java. My OpenBSD machine has two more versions, so I tested these six versions: * Java 1.1.8 in MRJ 2.2.6 for Mac OS 9.2.2 * Java 1.3.1\_16 for Mac OS X Panther * Java 1.4.2\_21 for Mac OS X Tiger * Java 1.5.0\_19 for Mac OS X Tiger * OpenJDK 1.6.0\_32 for OpenBSD 5.5 * OpenJDK 1.7.0\_21 for OpenBSD 5.5 This program can also run in JamVM 1.5.4 and gcj 4.8.2 for OpenBSD, but does not identify them as different implementations. It only prints "Java 5". ## Mac OS Runtime for Java Thanks to "Write once, run everywhere!", I may write this program once, compile it once, and run one GuessVersion.class in all eight virtual machines. I need a compiler for Java 1.1, the oldest version in my collection. My compiler is the `javac` tool from MRJ SDK 2.2. Because the Classic Mac OS had no command line, `javac` is a pretty graphical tool where I select files and options and click "Do Javac". After I edit my code, I just click "Do Javac" again. ![javac from MRJ SDK 2.2 for Classic Mac OS](https://i.stack.imgur.com/IgyVU.png) The easiest way to run GuessVersion.class is to open it in JBindery, another tool from MRJ SDK 2.2. The runtime is MRJ 2.2.6, an implementation of Java 1.1.8. [Answer] ``` class Evil { public static void main(String... args) { String s1 = "Good"; s1 += "morning"; int a = 7; if (s1 != s1.intern()) try { a--; javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar().equals(null); } catch (Throwable e) { a--; } System.out.println(a); } } ``` The interning algorithm changed between Java 6 and 7. See <https://stackoverflow.com/a/7224864/540552> XMLGregorianCalendar.equals(null) used to throw NullPointerException in java 5, but this was fixed in java 6. See <https://bugs.java.com/bugdatabase/view_bug?bug_id=6285370> 100 96 92 87 85 tokens here. Thanks to Peter Taylor for reducing 7 tokens. ]
[Question] [ The following picture shows the problem: ![enter image description here](https://i.stack.imgur.com/XmqFf.png) Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the *centered* circle (including the boundary). The image shows: ``` f[1] = 5 (blue points) f[2] = 13 (blue + red points) ``` other values for your checking/debugging: ``` f[3] = 29 f[10] = 317 f[1000] = 3,141,549 f[2000] = 12,566,345 ``` Should have a reasonable performance. Let's say less than a minute for f[1000]. Shortest code wins. Usual Code-Golf rules apply. Please post the calculation and timing of f[1001] as an example. [Answer] ## J, 21 19 18 ``` +/@,@(>:|@j./~@i:) ``` Builds complexes from -x-xj to x+xj and takes magnitude. Edit: With `>:` Edit 2: With hook and monadic `~`. Runs a few times slower for some reason, but still 10-ish seconds for f(1000). [Answer] ## J, ~~27~~ 21 ``` 3 :'+/,y>:%:+/~*:i:y' ``` Very brutal: computes *sqrt(x²+y²)* over the *[-n,n]* range and counts items *≤n*. Still very acceptable times for 1000. **Edit**: `i:y` is quite a bit shorter than `y-i.>:+:y`. Thanks [Jesse Millikan](https://codegolf.stackexchange.com/questions/1938/code-golf-lattice-points-inside-a-circle/1943#1943)! [Answer] ## Ruby 1.9, ~~62 58~~ 54 characters ``` f=->r{1+4*eval((0..r).map{|i|"%d"%(r*r-i*i)**0.5}*?+)} ``` Example: ``` f[1001] => 3147833 t=Time.now;f[1001];Time.now-t => 0.003361411 ``` [Answer] **Python 55 Chars** ``` f=lambda n:1+4*sum(int((n*n-i*i)**.5)for i in range(n)) ``` [Answer] ## Haskell, 41 bytes ``` f n=1+4*sum[floor$sqrt$n*n-x*x|x<-[0..n]] ``` Counts points in the quadrant `x>=0, y>0`, multiplies by 4, adds 1 for the center point. [Answer] # [Uiua](https://www.uiua.org), 13 bytes ``` ∧+1×4⌊√×⊃+-⇡. ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oinKzHDlzTijIriiJot4oipJ8OXLuKHoS4KZiDihpAg4oinKzHDlzTijIriiJrDl-KKgyst4oehLgoKZiAxCmYgMgpmIDMKZiAxMApmIDEwMDAKZiAyMDAw) Uses the formula on [A057655](https://oeis.org/A057655) \$ 1+4\sum\_{k=0}^{n}{\left\lfloor\sqrt{n^2-k^2}\right\rfloor} \$, and uses the fact that `k=n` part can be removed. ``` ∧+1×4⌊√×⊃+-⇡. input: integer n ⇡. keep n and generate the range for k ×⊃+- (n+k) * (n-k) for each k ⌊√ sqrt, floor ∧+1×4 multiply 4, sum, and add 1 ``` [Answer] # Haskell, 44 bytes ``` f n|w<-[-n..n]=sum[1|x<-w,y<-w,x*x+y*y<=n*n] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, 12 bytes ``` òUn)ï Ëx²§U² ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=8lVuKe8gy3iyp1Wy&input=MTAwCi14) Explanation: ``` òUn) #Get the range [-input ... input] ï #Get each pair of numbers in that range Ë #For each pair: x # Get the sum... ² # Of the squares § # Check if that sum is less than or equal to... U² # The input squared #Output the number of pairs that passed the check ``` [Answer] ## Python 2, 48 bytes ``` f=lambda n,i=0:i>n or(n*n-i*i)**.5//1*4+f(n,i+1) ``` Like [fR0DDY's solution](https://codegolf.stackexchange.com/a/1940/20260), but recursive, and returns a float. Returning an int is 51 bytes: ``` f=lambda n,i=0:i>n or 4*int((n*n-i*i)**.5)+f(n,i+1) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 60 bytes ``` r,a;f(x){for(a=r=x*x;a--;)r-=hypot(a%x+1,a/x)>x;x=4*r+1;} ``` [Try it online!](https://tio.run/##bci9CoMwEADg3ccQhDtNqLHdjvRJuhwpsYJ/nA5XxFdvunRrvvELtg8hJTFMERSPuAiwF6@1EltLKNa/3uuyA1faOMMXxbuS@lstjaMzTTzMgEdRrDLMe4Syej7m0kRwiPSXXS6vuXRtftvsd78/0yfEkfst2XH6Ag "C (gcc) – Try It Online") Loops over the first quadrant, multiplies the result by 4 and adds one. Slightly less golfed ``` r,a; f(x){ for(a=r=x*x;a--;) r-=hypot(a%x+1,a/x)>x; x=4*r+1; } ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 bytes ``` {≢⍸⍵≥|⌾⍀⍨⍵…-⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sfdS561LvjUe/WR51Lax717HvU2/CodwWI37BMF0jV/k8DKnzU2wfR09V8aL3xo7aJQF5wkDOQDPHwDP6fpmBoYPAfAA "APL (Dyalog Extended) – Try It Online") Despite lacking the `i:` (inclusive range from -n to n) builtin of J, APL Extended has shorter syntax in other areas. ``` {≢⍸⍵≥|⌾⍀⍨⍵…-⍵} Monadic function taking an argument n. ⍵…-⍵ n, n-1, ..., -n ⌾⍀ Make a table of complex numbers (equivalent to ∘.{⍺+1J×⍵} in Dyalog APL) ⍨ with both real and imaginary parts from that list. | Take their magnitudes. ⍵≥ 1 where a magnitude are is at most n, and 0 elsewhere. ⍸ Get all indices of truthy values. ≢ Find the length of the resulting list. ``` [Answer] # PHP, 85 83 bytes The code: ``` function f($n){for($x=$n;$x;$c+=$x,$y++)for(;$n*$n<$x*$x+$y*$y;$x--);return$c*4+1;} ``` Its outcome (check <https://3v4l.org/bC0cY> for multiple PHP versions): ``` f(1001)=3147833 time=0.000236 seconds. ``` The ungolfed code: ``` /** * Count all the points having x > 0, y >= 0 (a quarter of the circle) * then multiply by 4 and add the origin. * * Walk the lattice points in zig-zag starting at ($n,0) towards (0,$n), in the * neighbourhood of the circle. While outside the circle, go left. * Go one line up and repeat until $x == 0. * This way it checks about 2*$n points (i.e. its complexity is linear, O(n)) * * @param int $n * @return int */ function countLatticePoints2($n) { $count = 0; // Start on the topmost right point of the circle ($n,0), go towards the topmost point (0,$n) // Stop when reach it (but don't count it) for ($y = 0, $x = $n; $x > 0; $y ++) { // While outside the circle, go left; for (; $n * $n < $x * $x + $y * $y; $x --) { // Nothing here } // ($x,$y) is the rightmost lattice point on row $y that is inside the circle // There are exactly $x lattice points on the row $y that have x > 0 $count += $x; } // Four quarters plus the center return 4 * $count + 1; } ``` A naive implementation that checks `$n*($n+1)` points (and runs 1000 times slower but still computes `f(1001)` in less than 0.5 seconds) and the test suite (using the sample data provided in the question) can be found [on github](https://github.com/axiac/code-golf/blob/master/lattice-points-inside-a-circle.php). [Answer] ## JavaScript (ES6), 80 bytes ``` n=>(a=[...Array(n+n+1)].map(_=>i--,i=n)).map(x=>a.map(y=>r+=x*x+y*y<=n*n),r=0)|r ``` Alternative version, also 80 bytes: ``` n=>[...Array(n+n+1)].map((_,x,a)=>a.map((_,y)=>r+=x*x+(y-=n)*y<=n*n,x-=n),r=0)|r ``` ES7 version, also 80 bytes: ``` n=>[...Array(n+n+1)].map((_,x,a)=>a.map((_,y)=>r+=(x-n)**2+(y-n)**2<=n*n),r=0)|r ``` [Answer] # [Scala](http://www.scala-lang.org/), 55 bytes [Try it online!](https://tio.run/##FY2xCsIwFEV3v@KOScXQglOhBUeHTuIkDs/a1kj6WpNXQaTfHuNyhwP3nNCSozjdnl0raMgyvhvgTQ59iSNLVadBhchVrXIsLNaBtRlpVraqG5KHCS8vijPe2cxqI1N6aBOWMdtviwjcux5jMivyQyhx8J4@l5N4y8NVlzizTYF/FZgTFMeqV0WeF1onuG7W@AM) ``` n=>(0 until n).map(i=>Math.sqrt(n*n-i*i).toInt).sum*4+1 ``` [Answer] # JavaScript (ES7), 42 bytes ``` f=(n,k=n)=>k--?((n*n-k*k)**.5<<2)+f(n,k):1 ``` [Try it online!](https://tio.run/##ZctLDsIgFIXhuavokIvQ9vKo0RRdS1OLsTRgrHH7WByQiGf6/Wce3sM6Pu@PF/fhOsVoDfHMGQ/m7Di/EOKp5446oLTWfS9gb1MAJ4xj8GtYpnoJN2IJAlTbmqbSu18RWVAWJDOJY0HYfm0jiYc/a5MmY6iQaVW@RS5QMN11TCodPw "JavaScript (Node.js) – Try It Online") [Answer] # Clojure/ClojureScript, 85 chars ``` #(apply + 1(for[m[(inc %)]x(range 1 m)y(range m):when(<=(+(* x x)(* y y))(* % %))]4)) ``` Brute forces the first quadrant, including the y axis but not the x axis. Generates a 4 for every point, then adds them together with 1 for the origin. Runs in under 2 seconds for input of 1000. Abuses the hell out of `for` to define a variable and save a few characters. Doing the same to create an alias for `range` doesn't save any characters (and makes it run significantly slower), and it seems unlikely that you're going to save anything by making a square function. [Answer] ## Mathematica, 35 characters ``` f[n_]:=Sum[SquaresR[2,k],{k,0,n^2}] ``` Lifted from <https://oeis.org/A000328> <https://reference.wolfram.com/language/ref/SquaresR.html> `SquaresR[2,k]` is the number of ways to represent k as the sum of two squares, which is the same as the number of lattice points on a circle of radius k^2. Sum from k=0 to k=n^2 to find all the points on or inside a circle of radius n. [Answer] # Tcl, 111 bytes ``` lassign {1001 0 -1} r R x while {[incr x]<$r} {set R [expr {$R+floor(sqrt($r*$r-$x*$x))}]} puts [expr {4*$R+1}] ``` Simple discrete **x** loop over quadrant I, counting largest **y** using the Pythagorean Theorem at each step. Result is 4 times the sum plus one (for the center point). The size of the program depends on the value of **r**. Replace `{1001 0 -1}` with `"$argv 0 -1"` and you can run it with any command-line argument value for **r**. Computes f(1001) → `3147833.0` in about 1030 microseconds, AMD Sempron 130 2.6GHz 64-bit processor, Windows 7. Obviously, the larger the radius, the closer the approximation to PI: f(10000001) runs in about 30 seconds producing a 15-digit value, which is about the precision of a IEEE double. [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ä÷²M╨⌐■╝^₧░ ``` [Run and debug it](https://staxlang.xyz/#p=84f6fd4dd0a9febc5e9eb0&i=1%0A2%0A3%0A10%0A1000%0A2000&a=1&m=2) [Answer] ## Pyke, 14 bytes ``` QFXQX-_,B)s}}h ``` [Try it here!](http://pyke.catbus.co.uk/?code=QFXQX-_%2CB%29s%7D%7Dh&input=1) [Answer] ## Pascal, 128 B This just walks the lattice grid and checks whether the distance to the origin is less than or equal to the radius. ``` type Z=integer;function f(r:Z):Z;var x,y,n:Z;begin n:=0;for x:=-r to r do for y:=-r to r do n:=n+ord(sqrt(x*x+y*y)<=r);f:=n end; ``` User time on a *busy* Linux x86‑64 machine for calculating `f(1001) = 3147833`: ca. 80 ms. Calculate just the points in one quadrant to cut the time. [Answer] # C (gcc), 116 bytes ``` a,x,y;c(r){for(x=-r;x<=r;x++)for(y=-r;y<=r;a+=x*x+y*y<=r*r,y++);return a;}main(r){scanf("%u",&r);printf("%d",c(r));} ``` **How it works** This inefficient method draws a square around the circle then iterates through all lattice points \$(x,y)\$ within it and checking if \$x^2+y^2 \le r^2 \$. [Try it online!](https://tio.run/##FY3bCsIwEER/RQJKrtA@r/mYZTWloFG2LSZIf921@zJwDsMMpYlIBGOLHciy@5YX25YTQ7vmI0JwarqargZDbr6F7pU8x340gO/rxvWEsD9xrjqzENZizXkz8cIO3jzXVflmot442EXGYRh/VB44LZI@fw) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) ([SBCS](https://github.com/abrudz/SBCS)), 28 bytes ``` {1+4×⍵++/,(×⍨⍵)≥+/¨×⍨∘.,⍨⍳⍵} { } dfn ∘.,⍨⍳⍵ get cartesian square of 1..n ×⍨ square each half of each pair +/¨ add each half of each pair +/, ≥ count sums greater than (×⍨⍵) the input squared 1+4×⍵+ add the input, multiply by 4, and add 1 ``` Finds the lattice points in one quadrant, then multiplies it by 4 and adds the points on the axes. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9pQ2@Tw9Ee9W7W19XU0QKwVQI7mo86l2vqHVkD4HTP0dMDim4FStf/dHrVNIF0b16O@qUCNbgqGcJYRnGWMkDUwMPgPAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` (Ÿn¬sãO@O ``` Port of [*@KamilDrakari*'s Japt answer](https://codegolf.stackexchange.com/a/179659/52210), so make sure to upvote that answer as well! [Try it online](https://tio.run/##yy9OTMpM/f9f4@iOvENrig8v9nfw///f0MDAEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf42jO/IOrSk@vNjfwf@/zv9oQx0jHWMdQwMgAmMwARQEsmIB). (Runs `1001` in about 3.5 seconds on TIO.) **Explanation:** ``` ( # Negate the (implicit) input-integer Ÿ # Push a list in the range [(implicit) input,-input] n # Square each inner value ¬ # Push the first item (without popping the list), which is input² s # Swap so the list is at the top again ã # Cartesian power of 2 to get all possible pairs O # Sum all those inner pairs together @ # Check for each whether the input² is >= this value O # Sum to get the amount of truthy values # (which is output implicitly as result) ``` [Try it online with a step-by-step output.](https://tio.run/##VZAxSwQxEIV7f8Ww1R6soK1wKliIjSdYisXcObsJ7ia5ZOLi77G1ukKsV/xdazI5PSzCQN5737zEBlxrmufqxrjIZ1A1y@nj4qi6pQ6ZgBWB/lXqIt1ZB2iewMWgAKHXgZNHrB5NR/AgieZYxmNOfn@W6P02oicg3Ch4wT5SFk3RromF0WqfgUwD1EKYdgsYNSsbGZx1TptOjHlxzk/ve/iIrpFmXUJh3yd3CHrdEzhMULDtv1z4etsH41AqaWPIiznrq6JeKdo8Q2t98YyKEsQffmbagQ5wvkw3af696vLAZiuNcgIHGw1LEx9ZvRZ/gHpUOhdIJaNPhxN4ISWaeT49@QE) [Answer] # APL(NARS), 25 chars ``` {1+4×+/⌊√(⍵*2)-¨2*⍨¯1+⍳⍵} ``` test: ``` f←{1+4×+/⌊√(⍵*2)-¨2*⍨¯1+⍳⍵} f 0 1 f 1 5 f 3 29 f 10 317 f 1000 3141549 f 2000 12566345 ``` ]
[Question] [ Given a list of countries in alphabetical order, put them in the same order as they are given in the song ["Yakko's World"](https://animaniacs.fandom.com/wiki/Yakko%27s_World_(song)). Specifically, you are given the following list of countries\* exactly: ``` Abu Dhabi, Afghanistan, Albania, Algeria, Algiers, Angola, Argentina, Australia, Austria, Bahamas, Bahrain, Bangladesh, Barbados, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, Borneo, Botswana, Brazil, Bulgaria, Burma, Burundi, Cameroon, Canada, Caribbean, Cayman, Chad, Chile, China, Colombia, Congo, Costa Rica, Crete, Cuba, Cyprus, Czechoslovakia, Dahomey, Denmark, Djibouti, Ecuador, Egypt, El Salvador, England, Ethiopia, Fiji, Finland, France, French Guiana, Gabon, Gambia, Germany, Ghana, Greece, Greenland, Guam, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Honduras, Hong Kong, Hungary, Iceland, India, Indonesia, Iran, Iraq, Ireland, Israel, Italy, Jamaica, Japan, Jordan, Kampuchea, Kenya, Korea, Kuwait, Laos, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Luxembourg, Madagascar, Mahore, Malawi, Malaysia, Mali, Malta, Mauritania, Mexico, Monaco, Mongolia, Morocco, Mozambique, Namibia, Nepal, New Guinea, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Pakistan, Palestine, Panama, Paraguay, Peru, Poland, Portugal, Puerto Rico, Qatar, Republic Dominican, Romania, Russia, Rwanda, San Juan, Saudi Arabia, Scotland, Senegal, Sierra Leone, Somalia, Spain, Sri Lanka, Sudan, Sumatra, Surinam, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tanzania, Thailand, The Netherlands, The Philippine Islands, Tibet, Tobago, Togo, Transylvania, Tunisia, Turkey, Uganda, United States, Uruguay, Venezuela, Vietnam, Yemen, Yugoslavia, Zaire, Zambia, Zimbabwe ``` And required to output the countries in this order: ``` United States, Canada, Mexico, Panama, Haiti, Jamaica, Peru, Republic Dominican, Cuba, Caribbean, Greenland, El Salvador, Puerto Rico, Colombia, Venezuela, Honduras, Guyana, Guatemala, Bolivia, Argentina, Ecuador, Chile, Brazil, Costa Rica, Belize, Nicaragua, Bermuda, Bahamas, Tobago, San Juan, Paraguay, Uruguay, Surinam, French Guiana, Barbados, Guam, Norway, Sweden, Iceland, Finland, Germany, Switzerland, Austria, Czechoslovakia, Italy, Turkey, Greece, Poland, Romania, Scotland, Albania, Ireland, Russia, Oman, Bulgaria, Saudi Arabia, Hungary, Cyprus, Iraq, Iran, Syria, Lebanon, Israel, Jordan, Yemen, Kuwait, Bahrain, The Netherlands, Luxembourg, Belgium, Portugal, France, England, Denmark, Spain, India, Pakistan, Burma, Afghanistan, Thailand, Nepal, Bhutan, Kampuchea, Malaysia, Bangladesh, China, Korea, Japan, Mongolia, Laos, Tibet, Indonesia, The Philippine Islands, Taiwan, Sri Lanka, New Guinea, Sumatra, New Zealand, Borneo, Vietnam, Tunisia, Morocco, Uganda, Angola, Zimbabwe, Djibouti, Botswana, Mozambique, Zambia, Swaziland, Gambia, Guinea, Algeria, Ghana, Burundi, Lesotho, Malawi, Togo, Niger, Nigeria, Chad, Liberia, Egypt, Benin, Gabon, Tanzania, Somalia, Kenya, Mali, Sierra Leone, Algiers, Dahomey, Namibia, Senegal, Libya, Cameroon, Congo, Zaire, Ethiopia, Guinea-Bissau, Madagascar, Rwanda, Mahore, Cayman, Hong Kong, Abu Dhabi, Qatar, Yugoslavia, Crete, Mauritania, Transylvania, Monaco, Liechtenstein, Malta, Palestine, Fiji, Australia, Sudan ``` You have some flexibility in the form of the input and output; you can take or output the countries as all uppercase, all lowercase, or maintaining case, and can choose to omit spaces as well. Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. --- \*Note that *Yakko's World* includes several places that aren't countries, and that several countries aren't included in the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 121 bytes ``` “wỴḅKṭḞ2Ṅðȧ¤[Ạ⁺©iṆȦẉ&ŒÐḷ<⁸Ṛ⁵Ƙ#A½Ƈ'¥ṚPċṢSḥSQUmṘẉL>²XɼNĠ¥ṆỊẋi¥@ȯ⁺CḲKSḌȮC²ß5LṂJṁȮr]zƬe§^YVœX<ḃç%ƝṪƬṣ$¹Ṗa?⁵ḤẠÐẈ}ƬỊhR=zḢɱ¿z’œ? ``` [Try it online!](https://tio.run/##PVRbbxw1FP4rK3F7KS9IvBVKsmm3STZhu5NETRBIZ2YPM05m7K3HznZXQmq4tNDygIgEBXGpSkMEKgUiEDsJF2nTRMnP8P6RcI696Yu/z8f25@Nz8Trmef/sbHzrm547@MMNP5p31S9u@N0rrvrw8LeT3dGjt9z@g/HW/ugn4arbJz@6/U9ePPr88DM3/OvieGvoqq/HW38e339uavTP8Z2XRjtkaD2956qHkRvuRNeWC1fdpzPN10d710//Xnz6gLfcdgd33f49Mdp54@RXEq@74d48Hfj05El9tHf4/atNV70/56qtkyf67cHxYxztvrO6crR9/aIbfnC4@8Lxt676@fixq354flS56gu4RE644SNylTzb//g9Wju4m7VfG7jhw9PfR/8Nxre@Otq@dHa0TWcO76yffjne@vdC7exsKra1mQxicaE29W6agRSlAUmTPCYOTFLUEyJQl0RkqnI26BSlEZKpLY2GXJxTJtOQQQGlJxqEZCLTHDpYZsx1DB3Fy0jCtvBEDJBR@t2oC9thocx6l6ZVLja9stISFaMpe8D3T2sYiJzQ5imE260uAljZocfVoUCtlGQmgWXrtDGOEbypX3jMoMOjyNEDS9dVropYeEYPZ6AI1doiYZNGw1ttzJN@V1t6UH2ASabKXG3CBp@bgUwV2CeCsgC9QWRdxMoacutyYikKmkja7xqCvBZBvjmxcbgkeXTZZEJ1WeuKWBc8yrBwRYNMkBFlktUaVvhwNCDmlzYgON6gSIIkBxpZWNaIfIpxItSwUPjRYAGcXJKS@AxfnhZlCZanfS9xFQS7f1XJjtWcZGJpbZ4GolZSEui62QSD@iylADwoiaWnmuNN4w0ez7eVGpCyOGsgp@NzVD4@ynPQ5d1zSncY56Ho2iRj7@ZR9hmU9jPbI7cu1JrAddVEqmAOQxNLZTLKXFPEoZSJ9D1QogzK0iAXXNPexILyoukNC1QiKZQJaOYZ6TPm0BMB@/4VxMLc@InVwoSmWcCbIqEbF5SECVLP@BWlVRJMA07PDUvKi1AIn6lF7ELO0HuWAOZrCCFCixQPDallu6C@nIA/qnQPKGpv@kpuUemFRm5BjiV1KTKVwE3RChq0uYWaktpSQb2ltLEpO9CyqI3iIidPr4HhMLSxa@NcJLUZVQhJjpB4WxXhwW1b@oi0qR@5uSKQtTnLWyKwHUF/BfgHRoky4bIIJfq7IvpVNFCWFPsYkaIPVNT1f0akBeVTbrDF@vRHtgD6bJho6lAq26jH3R9Ue9hB3tQTZoB6Yuz7CC2B6LHAEshB8Hopg8m5pQwp0iYLR8pgaNFHILpdih2V5rmdaohKbEnFwJ/BkvIjVXPZp7YNqpY@0UD0Bvf9chqCsiyFwU4tMtRlJLWsbcjCCoViYJHbbkWg8W9axYLfsWpT@knAf3trILgM1yZdvSaKGOIe/g8 "Jelly – Try It Online") Boring, but it's not clear what further logic could bring it down. The program is just a giant compressed integer representing a permutation, and a builtin to apply it. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 205 bytes *-2 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* This is based on a specific implementation of `sort()` but probably works with several engines. The source code contains unprintable characters. ``` a=>a.sort(_=>Buffer(`!IF<@E*JGL8*' M-&LDJ>!F%8 +,.C?$9C- =M#10-G!G7B*D 9,,2!:F"@BF5H;#3-$IK.EK;(%H+F 'L'I2,-J2'7M55 1;,;8*! /%92  D&@J?0E:<2G3EG.K-I'`)[i/6|0]-14<<31-i++%6,i=0) ``` [Try it online!](https://tio.run/##PVT7Uxs3EP4PmnZICi0EjibEBmyHR0kgPEL8xMYQF5vMhE6n2Tsvd4I7ydFJOPb0f6e7kpNftJ9W0qd938ED5JEWI1OWaoiPt8ePcHwClVxpU/z3@KRqb29RF7@stptHp42NTqu7v1F4/stF@VW33jlZba7tL2@WKrX3Lw9q5aUnxxdP515sz2/Nl1urrbcr1Y36/PLzg1JpZ/W3xXfNn/44rT5t7p0tHL7YLb9sn/9eaZwfFtfONptLhWfPuoX2TmlxodyZ2ym8vdjbW9r@deGwdLi/sRq8XjvYWQkWl5fqr07nOu9/frLVeHe009pdabQq5@V24cv63@L1m/@2/ilv/3l0tLtdFpuba29K4nhr/TFSMlcpVlIVF2@LhQ@hDeoJhKIUfLiNE5AiNyBpk4aEgUGMegYE6pyAjFXKCh2jNEIytLnRkIrvkEEVEsggd0CDkAxknMIQ84SxDmGo@BiJ2GYOiCmylO426swOmSixzqSqSsWDY1ZaomJp8jHw/1UNU5GStGkM/nerMy@sHJJzNchQKyUZSWDaGl0MQwSnmmROJjDkVaToBFPXVKqyUDhEjrOgCAVXImKVRsNXbcibyUhbcqg2xShReaoe4J7f1SFRGU4IoMxA3xO4E6GyhsxqRJaioAnEk5EhkQZ9SB9mOg6XJIsaJhFqxFxNcSd4lf6gqUFGyBJllAQtK1w4WhCypy3whrcokiDJgFbijzUiv2I5I2pZyNxqMANOLlFJ/CHLVZHnYHk7cRRnINj8MyWHVnOSCcXBOS0EraQk0HftCD17m1IATiiJuYOa403rV16/X8s1IGWxbSCl5x0qHxflDoz4dkfpIctzyEY2Sti6c5QTFkq7nR2TWaWgC1xXXaQK5jB0MVcmocx1RehLmcDECUqUQZkb5ILr2m@YUV40@XBBJRLTIADNOCF@limMhZcT5wUhvzduY7Uwvmku8JuI6McLJWEmqWfcidIq8qopp@erJeZLyITL1CWOIGUx/pEAxjcIPkKXFA8NsWW9oL6cCfdU6TFQ1D66Su5R6flG7kGKOXUpMpTATdHzHHS5h5qS2lOevUczzsZsQM@iNoqLnCz9CwyH4QpHNkxFFNRVJiQZQuRXKvMOX9ncReSK@pGbqw8y6Fi@0gc7FDQrwDnYj5Txn/VRovurT1NFA2VJsY19YnSB6o/czOhrQfmU96yxLv19mwENGwaaOpTKtj/m7vesYxwiXxoLM0U9U05chAYgxkwwADn1Vg8SmL0bJEiRNol/kntFjwaBGI0odlSa3/VUQ1RiAxUCD4OBcitVcz6htvWsloaoB/qe@/469kG5lsLgMOgb6jKiutbWZ@EThWJqkdvuk0DjfPqMGfvx2cY0ScCNvRsQXIY3s66@EVkI4RgLlXyUClMslILC@nrlTgk5w4//Aw "JavaScript (Node.js) – Try It Online") ### How? We make the callback function of `sort()` returning either a negative or non-negative value, depending on whether the items must be swapped or not. We need one bit per iteration and the data string encodes \$6\$ bits per character, using the ASCII range \$[14\dots77]\$. The list is fully sorted after \$943\$ iterations, which requires \$\lceil 943/6\rceil=158\$ characters. It happens to be equal to the number of countries in the list, but that's a pure coincidence. ### Commented ``` a => // a[] = input list, in alphabetical order a.sort(_ => // sort it, ignoring the arguments of the callback Buffer(`...`) // turn the data string into a list of ASCII codes [i / 6 | 0] // extract the entry at index floor(i / 6) - 14 // subtract a fixed encoding offset, chosen to avoid // characters that can't be included as literals or // must be escaped << 31 - // left-shift the result such that the sign bit i++ % 6, // is replaced with the bit at position (i mod 6) i = 0 // start with i = 0 ) // end of sort() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 121 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •Caиβ”œ`äÔÚ×3ιØ>ãA8Cγ“Ø₄XмK £#_¯½%˜‚-Z†b}g3EqÄúé…¹ζzŒWmRç°¶вåΔBв„6J0й%∍¬üë¯β±B[λ9fΩÙ„¶g¹`Hk¹ʒJ.≠|”ΩoK"Âc9„Ƶι–+@ÌèÊ$§₅•.I ``` I/O as a list. It's currently in the default titlecase, but can also be lowercase or uppercase without a change in functionality. [Try it online.](https://tio.run/##TVVfbxtFEH/nU5wCfYJWSJUQfUHETurEcYLxOYWmQnTuPL3b5m7X2butawskKyoSIJBQW4lSFVRRoEQgFYKIMJSXO5UHkKx8Bn@RdLyz5/Di/c3c7vz5zR@rDAKBJyez8bd1OP5jejgbf/3sztXyu/Jueb/88vx0Ut57o3y0/Hp9@tts/KC8N9u/9e7x040Xikcvvl88Kf4@89@D2fj@2Z3Z@GHwYXR@da@8Vf5ZHszGPxST6dHo2e130k75uPilODo@LL@f3q0dk4tvXmu@Wn5RTM7MPv68@Ll8Wv5UPJkeFr/Wrkz/unBtelB@RXeKo6iYXF3bLSb/3m6em33y8AOKbXqgNpbK/fACXfjn9@lkNr7z8pvlZ@WP5acvFY9n@x9RIufWT06uLC0HxluJKbulV7yl5WtRDFJkOUgrJgFJwDBCvYACdWahjFTCSh2hzIVkwWS5hkScCgxrEEMKmYMahGQoowR6mMUs6QB6ii8huTKpg2KEjKR7hzo1PTYcGxdyTSXihvOmtETFKM8GwLHVNIxEYpFJIqgiMzqtgJE9S0YdUtRKScYS2FWdngQBglMPU4di6PEpEnSAHdZVotJAOEyEMSCOvY4IWa0x50cmYMWwr42loD7CMFZZom7ALttYgVilOLQQZQp618LrIlAmt4GvhoYY1BZGw35uQeL5kNxY6OeUSxvxah4L1WfbF8V1waesPl/UIENkhDKMvYYRjsoGBMxOA6oEG1QTkDa4Rlxd04hsYY4WhhsGUnfmmAK3ERmX@D90tiayDAwrhs7gGghOdE3JntHcUIQjb4N@rGAkldaGsR5i5XGdCgsOKImZEzRXkM49Pk8fZBrQ9sp6Dok116QGdlVrQp9fNpXuMdqAtG/CmDPYQDlkoLTTmAGFPkct4A5vIU0Yk9jCTOWx7Y6WCKphIzh0gBohR5nlyO3fMjcxpZprm/EmtWcEWQiapZh8MkpgICo0dDkTrnS5Uxgt8mrYN/GmCG0km0rCAtGsu@9Kq7BSj@bF3zPW2xakwnXCFvYhYTDwTss6l3YQKoa3iEsNkeFvgnbMAjgzSg/AMv@Wm7Q2DUK1oNqQYEZbB1mQwEPcZpv2WRu1bZ@2qny2lc5NxMG1DepczQfRZvM25ExgB/smSETorahUSArSuuuotKKoYzLHZYc2C68GH6TXNHzVB9MT3rIGR4cfqrwKwEeJzr9Pm1SD10LFOfjkwZHs991@9LXwWiB3WWtcq/kmBVqyDDXtGjtM/mC@3So/A@whXx6IfIR68WHo2O2CGLC5LshRlVs3hoWNbozeFuYxP84qVZvWnOj3iXlvPTv9Qn1r27urAuBF11XupCnLhrSAKh@G/mYqqHd5n21HFZXbUuTY8/ycdoM1va1NVdFLRN/IIC@MSwJzl/tlTDnbyyaijQnub2AHBI/CzmJL7Yg0gGCAS@89Bw) **Explanation:** ``` •Caи...$§₅• # Push compressed integer 17496935826677579314159550205809193960505801935712671712608685729996785341091982271028672893034204123066468970588179871093613064855657604902698437005706906805554153425206759252074826136162698098035155104304651724366320520871306820060929813088043319762751700033987752258296072690622 .I # Get the (0-based) ^'th permutation of the (implicit) input-list # (after which the list 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 `•Caиβ”œ`äÔÚ×3ιØ>ãA8Cγ“Ø₄XмK\n£#_¯½%˜‚-Z†b}g3EqÄúé…¹ζzŒWmRç°¶вåΔBв„6J0й%∍¬üë¯β±B[λ9fΩÙ„¶g¹`Hk¹ʒJ.≠|”ΩoK"Âc9„Ƶι–+@ÌèÊ$§₅•` is `17496935826677579314159550205809193960505801935712671712608685729996785341091982271028672893034204123066468970588179871093613064855657604902698437005706906805554153425206759252074826136162698098035155104304651724366320520871306820060929813088043319762751700033987752258296072690622`. [Answer] # MS-DOS .COM format (8086), ~~220~~ 213 bytes Takes a CR-LF delimited list of countries from standard input. ``` 0000000 b4 08 b1 9e bf 11 03 57 cd 21 3c 0d 75 02 b0 24 0000020 aa 75 f5 cd 21 e2 f0 bb 36 01 b1 9e 8b ec 33 c0 0000040 8a c1 d7 d1 e0 8b f0 8d 3a 8b 15 b4 09 cd 21 b0 0000060 20 cd 29 e2 e9 cd 20 1b 96 6e 2f 40 47 3d 0c 3f 0000100 7a 03 28 9d 5d 81 44 24 45 61 6f 02 7c 84 48 20 0000120 39 76 99 1f 41 4f 1e 13 6a 8e 72 49 80 33 34 0d 0000140 43 4a 85 67 9a 62 69 18 01 3a 89 74 00 98 09 3b 0000160 0b 05 8a 36 1a 37 1c 14 10 59 0f 4c 3c 52 4e 7e 0000200 92 42 50 8c 38 12 9c 86 30 5a 1d 75 70 6c 2a 90 0000220 46 11 93 4d 04 51 55 4b 15 58 57 78 5c 22 87 31 0000240 25 56 9b 21 26 2b 66 0a 54 77 95 16 68 6d 5b 17 0000260 32 64 91 6b 19 07 2d 23 0e 94 8d 35 8f 7b 88 7f 0000300 73 97 8b 63 60 5e 06 7d 29 71 65 82 79 27 2c 53 0000320 5f 2e 3e 83 08 ``` [Input file](https://pastebin.com/ShSifjAb) Assembler source (TASM): ``` IDEAL P8086 MODEL TINY CODESEG ORG 100H MAIN: MOV AH,8 ; Read from STDIN, no echo MOV CL,158 ; Do for all strings MOV DI,OFFSET STRINGS ; String storage STORE: PUSH DI ; Store index of string LOAD: INT 21H ; Get character CMP AL,0DH ; End of line? JNZ LOAD1 ; No, keep going MOV AL,'$' ; Replace end of string with $ terminator LOAD1: STOSB JNZ LOAD ; End of line? (No, keep going) INT 21H ; Yes, skip LF LOOP STORE ; Store next offset until done DONE: MOV BX,OFFSET CONVS-1 ; Conversion table MOV CL,158 ; Do for all strings MOV BP,SP PRINT: XOR AX,AX ; Line number MOV AL,CL XLAT ; Get conversion SHL AX,1 ; Turn into pointer MOV SI,AX LEA DI,[BP+SI] ; Get address of array index MOV DX,[DI] ; Get string address MOV AH,9 ; Print string INT 21H MOV AL,' ' ; Print separator INT 29H LOOP PRINT ; Until done INT 20H ; Conversion table CONVS DB 27,150,110,47,64,71,61,12,63,122,3,40,157,93 DB 129,68,36,69,97,111,2,124,132,72,32,57,118,153 DB 31,65,79,30,19,106,142,114,73,128,51,52,13,67,74 DB 133,103,154,98,105,24,1,58,137,116,0,152,9,59,11 DB 5,138,54,26,55,28,20,16,89,15,76,60,82,78,126,146 DB 66,80,140,56,18,156,134,48,90,29,117,112,108,42 DB 144,70,17,147,77,4,81,85,75,21,88,87,120,92,34,135 DB 49,37,86,155,33,38,43,102,10,84,119,149,22,104,109 DB 91,23,50,100,145,107,25,7,45,35,14,148,141,53,143 DB 123,136,127,115,151,139,99,96,94,6,125,41,113,101 DB 130,121,39,44,83,95,46,62,131,8 STRINGS DB ? END MAIN ENDS ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 253 bytes ``` a=>a.map((_,i)=>a[Buffer("lRpfbz5KcXYkGzgsdCCXPz06EgYqHhUiDmgQCY96cJaEMgw5a4ZCMDWHCCZJkzdyd3wCR3hsFntBJUZFiFJITJlQCoxXDXMxLSiAQ20XAYtlEU1bCx9PS2FRjkSNiYFmg2cTmJJilAWdKRRjnIU0OwM2GFNakGlqHVQrDzOKf05cfgQnZH1VGSGbLjxYeVkcQAB1miNekWBWXW4vB4I",'base64')[i]]) ``` [Try it online!](https://tio.run/##PVRtTyI7FP4rZL@AiWvUVZPNzd5EBgERFBhQYLO5OTNzmKl02rHTOsKf957T4n7peXraPj3vr/AOdWpEZb8rneHn9tcn/PoXzkqoOp3/TsUJbX533XaLpvNNzqttcrh@SFfr3eCQ11kUraaH85u7fP02LJaiV@azaP3zJh3B3SRvruFqE016L8Mo2ox2h2yf/Wii@Y@i7ivbHS03fdEf3S9Gchbpj1VvNfkYx@J2dnm@ul1bebe8SKKPn9P4sj9/3cWPYt0v88t0UY5GQt6@ZA/z@au6X54/NZPLQf8RdgP5Nnyemd7h6WF7fp1u85naDC@eB/EgGb9@rPF5l85uuxeleMTdS/dl9XL13r26/3baTqDGm6v2yW/x58/JZ6pVrSWeSZ13tp32beJavQIScdq63eYFKFFbULSRCWFgkKM5AoGmJqByLVlhclRWKIautgak@IIMulBACbUHBoRioHIJGdYFY5NApvkYidiVHogDslT@NprSZUxUOG9SV0vx7pm1UahZ2roB/r9r4CAkSSdzCL87UwbhVEbORVCi0VoxUsC0EV1MEgSv2pdeFpDxKiR6wdSRlrpMhEfkOAuKUGsuUlYZtHzVJbzZV8aRQ9EB00LXUr/Djt/1oNAl7gmgKsHsCLyKRDtLZt2ljqJgCOT7ypKQrRjk@1HH4VJk0Z0thK6Yqy9eBa8qHPQNqBRZokqL1sAJH44BJOzpAILhA4okKDJgUIRjg8ivWB6JBg5Kv1osgZNLVAr/yu9dUdfgeLv3FEMQbP5Qq8wZTjKhvPVAC0GnKAn03X2Kgf2eUgBeaIW1h4bjTesbr1/XagNIWby3IOn5iMrHR3kEFd8eaZOxfICycmnB1j2g2rPQxu9cQ2adtsbAdTVGqmAOwxhrbQvK3FgkoZQJ7L2gRFlUtUUuuLH7wJLyYsiHCZVIToMDDOOC@FlKaESQe@8FobC3fuOMsKFpJvghUvpxohUcJfWMP9FGp0F14PS8OWJ@hFL4TD1iBZJF8zcBjDcIIUKPFA8DuWO9oL48Cv9UmwYoak@@kqdUeqGRpyCxpi5Fhgq4KaaBgy5P0VBSpzqwT7WxLmcDpg6N1VzkZOkMLIdhjpVLpEhbPV0KRYYQ@VyXweG5q31E5tSP3FwxqNbI8ZUYXCZoVoB3ME61DZ/FqND/FdNUMUBZ0mxjTIw@UHHlZ0ZsBOVT7VjjfPpjVwINGwaGOpTKNm64@wNrgxnypUbYA5qjcu8jtADRMMEC1CFYvSjg@G5RIEXaFuFJHRRTGgSiqih2VJpfeqohKrGFToCHwUL7laq53lPbBlZHQzQAs@O@X@YhKEslLGat2FKXEdXSuJCFZwrFwSG33bNA631aY8l@rF1OkwT82NuA4DLcHLt6I8oEkgbbZ3Ulhe20T1vtk5OTfz7/Bw "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 355 bytes not using `Buffer` ``` a=>"951a5f6f3e4a7176241b382c7420973f3d3a12062a1e15220e6810098f7a709684320c396b8642303587082649933772777c0247786c167b412546458852484c99500a8c570d73312d2880436d17018b65114d5b0b1f4f4b61518e448d89816683671398926294059d2914639c85343b033618535a90696a1d542b0f338a7f4e5c7e0427647d5519219b2e3c5879591c4000759a235e9160565d6e2f0782".replace(/../g,i=>a['0x'+i-0]+` `) ``` [Try it online!](https://tio.run/##PVRtb9Q4EP5@v2LFl7aiFNtJnEQnkGiBQincXrcg0dNJTJLZxDSxFyfusvvny4yz8MXzeGw/nvfv8ABj7c1memZdg4/rF4/w4uWTMpOQrfU6wRRymWuVyiopVJ2nSpR5sk6aBKQSWoFEmSklUBdSiLJY55CLUhdpokSdlLoqdKoSkWRFLgql07JMkjxXeZ7XQqV5Xuha6rxKpcpSnWZFkam0SOuyzISAos5y0eRJIlWjikKkiW5kLmRR6UzKtMkqUcl1uk4rLTNZYJoWTVEWUusi0blMyqJUWpWpyMpGlTLVSVkXWZImlUgSLQlmUApdapBNlqpKrJOkgHydYlbnKFKV6zRvskyWSpaVwqQmN8qslHUqhMizElSSYSm1yHTWaFRrkRfqyZnHTQ81Hj8/O3venpoXL@G/I/Hz6Kl5Jv5/@u2vbyePtbOj6/Gsd@3x@vjoVRUWrzuozOni1brtwJpxAkubviIMDFr0B2DQjwRs63pW@BbtZCzDME4eevMbMjiHDgYYI/BgLAPb9tDg2DH2FTSOj5GIwxCB2SNLG2@jH0LDRF2IJp273jxEZuctOpbTuAX@/9zD3vQkQ9/C/HvwwyyCbci5CxjQO2cZWWDaC7pYVQhRtRui7KDh1fQYBVNfuN4NlYmIHGdBEVrcmJpVHie@Gire7DY@kEMXe6w7N/buAe753Wvo3IA7AmgH8PcEvpvKhYnMelMHioIn0O42E4l@sYL@4aDjcFmy6M3UGbdhrrfmu@HVzgdvPdgaWaKtu8VlMDEcl1Cxp5cwG35JkQRLBlx287FH5FcsD0SXAYa4TjgAJ5eoLP6Rz87NOELg7S5SvAPD5r9ztgmek0yoXXyghWCwlAT67n2NM/t7SgFE4SyOEXqON60/eP19bfSAlMX3E/T0/IrKJ0b5CjZ8@8r5huUHGDah7ti6D2h3LJyPu7Als04X18B1dY1UwRyGaxzd1FHmrk01lzKBXRSUqAntOCEX3HX4iQPlxZMPH6lEWhpP4Bl3xM@yh62Z5S56QWjeT3ETvJnmpvmIP01NP350Fg6SeiaeOO/qWbXn9PwIxPwJBhMz9Qk30LPY/kkA4zuEOUKfKB4e2sB6Q315EPGp81ugqP0TK3lJpTc38hJ6HKlLkaEFborlzEGXl@gpqUs3sy@dn0LLBiwD@slxkZOl/8LEYbjBTah6Uy9eu8FYMoTIb9wwO3wTxhiRG@pHbq4V2MVV4CsrCI2hWQHRwVXtpvmzFVqMf61oqnigLDm2cUWMMVCrTZwZK28on/aeNSGmfxUGoGHDwFOHUtmuttz9M@sWG@RLWzPt0R@UuxihWzBbJrgFu5@tvu3g8O62Q4r01M1PxlmxpEFgNhuKHZXmbz3VEJXYrauAh8GtiytV87ijtp1ZAw3RGfh77vvP7RyUz9ZM2CxWE3UZUX32Yc7CFwrFPiC33ReDU/TpKw7sx9fQ0iSBOPbuwHAZ3h26@s4MFVRbPDobN72Zjo9OF0cnJyd/P/4C "JavaScript (Node.js) – Try It Online") Nothing but table [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 140 bytes ``` »÷¤xŻλjb↑+k2x₴O₍‟ḂṀṫ. ɖ`‟z¦¼ẇeRʁ>j:t{*0 Nq;*₅1z⟑-¶±↓`ṡF²k•-ṡ⁼₌]L₇ḊṪṗ₃h¦SεĠT$₴∴∇ǎ)¾ŀ⟇ḟṡ₄↲ḣ×£↳ǎrq°ʁ₀∇ẋ≠↑⁽5₍↑¯₈¤⌈←±e«∷¦jẇʁ»⁺9(n›ḋ÷$)_WṘ(n~i⅛⟇)¾ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLigJssIOKCrHfCqFMiLCLCu8O3wqR4xbvOu2pi4oaRK2syeOKCtE/igo3igJ/huILhuYDhuasuIMmWYOKAn3rCpsK84bqHZVLKgT5qOnR7KjAgTnE7KuKChTF64p+RLcK2wrHihpNg4bmhRsKya+KAoi3huaHigbzigoxdTOKCh+G4iuG5quG5l+KCg2jCplPOtcSgVCTigrTiiLTiiIfHjinCvsWA4p+H4bif4bmh4oKE4oay4bijw5fCo+KGs8eOcnHCsMqB4oKA4oiH4bqL4omg4oaR4oG9NeKCjeKGkcKv4oKIwqTijIjihpDCsWXCq+KIt8KmauG6h8qBwrvigbo5KG7igLrhuIvDtyQpX1fhuZgobn5p4oWb4p+HKcK+IiwiIiwiQWJ1IERoYWJpLCBBZmdoYW5pc3RhbiwgQWxiYW5pYSwgQWxnZXJpYSwgQWxnaWVycywgQW5nb2xhLCBBcmdlbnRpbmEsIEF1c3RyYWxpYSwgQXVzdHJpYSwgQmFoYW1hcywgQmFocmFpbiwgQmFuZ2xhZGVzaCwgQmFyYmFkb3MsIEJlbGdpdW0sIEJlbGl6ZSwgQmVuaW4sIEJlcm11ZGEsIEJodXRhbiwgQm9saXZpYSwgQm9ybmVvLCBCb3Rzd2FuYSwgQnJhemlsLCBCdWxnYXJpYSwgQnVybWEsIEJ1cnVuZGksIENhbWVyb29uLCBDYW5hZGEsIENhcmliYmVhbiwgQ2F5bWFuLCBDaGFkLCBDaGlsZSwgQ2hpbmEsIENvbG9tYmlhLCBDb25nbywgQ29zdGEgUmljYSwgQ3JldGUsIEN1YmEsIEN5cHJ1cywgQ3plY2hvc2xvdmFraWEsIERhaG9tZXksIERlbm1hcmssIERqaWJvdXRpLCBFY3VhZG9yLCBFZ3lwdCwgRWwgU2FsdmFkb3IsIEVuZ2xhbmQsIEV0aGlvcGlhLCBGaWppLCBGaW5sYW5kLCBGcmFuY2UsIEZyZW5jaCBHdWlhbmEsIEdhYm9uLCBHYW1iaWEsIEdlcm1hbnksIEdoYW5hLCBHcmVlY2UsIEdyZWVubGFuZCwgR3VhbSwgR3VhdGVtYWxhLCBHdWluZWEsIEd1aW5lYS1CaXNzYXUsIEd1eWFuYSwgSGFpdGksIEhvbmR1cmFzLCBIb25nIEtvbmcsIEh1bmdhcnksIEljZWxhbmQsIEluZGlhLCBJbmRvbmVzaWEsIElyYW4sIElyYXEsIElyZWxhbmQsIElzcmFlbCwgSXRhbHksIEphbWFpY2EsIEphcGFuLCBKb3JkYW4sIEthbXB1Y2hlYSwgS2VueWEsIEtvcmVhLCBLdXdhaXQsIExhb3MsIExlYmFub24sIExlc290aG8sIExpYmVyaWEsIExpYnlhLCBMaWVjaHRlbnN0ZWluLCBMdXhlbWJvdXJnLCBNYWRhZ2FzY2FyLCBNYWhvcmUsIE1hbGF3aSwgTWFsYXlzaWEsIE1hbGksIE1hbHRhLCBNYXVyaXRhbmlhLCBNZXhpY28sIE1vbmFjbywgTW9uZ29saWEsIE1vcm9jY28sIE1vemFtYmlxdWUsIE5hbWliaWEsIE5lcGFsLCBOZXcgR3VpbmVhLCBOZXcgWmVhbGFuZCwgTmljYXJhZ3VhLCBOaWdlciwgTmlnZXJpYSwgTm9yd2F5LCBPbWFuLCBQYWtpc3RhbiwgUGFsZXN0aW5lLCBQYW5hbWEsIFBhcmFndWF5LCBQZXJ1LCBQb2xhbmQsIFBvcnR1Z2FsLCBQdWVydG8gUmljbywgUWF0YXIsIFJlcHVibGljIERvbWluaWNhbiwgUm9tYW5pYSwgUnVzc2lhLCBSd2FuZGEsIFNhbiBKdWFuLCBTYXVkaSBBcmFiaWEsIFNjb3RsYW5kLCBTZW5lZ2FsLCBTaWVycmEgTGVvbmUsIFNvbWFsaWEsIFNwYWluLCBTcmkgTGFua2EsIFN1ZGFuLCBTdW1hdHJhLCBTdXJpbmFtLCBTd2F6aWxhbmQsIFN3ZWRlbiwgU3dpdHplcmxhbmQsIFN5cmlhLCBUYWl3YW4sIFRhbnphbmlhLCBUaGFpbGFuZCwgVGhlIE5ldGhlcmxhbmRzLCBUaGUgUGhpbGlwcGluZSBJc2xhbmRzLCBUaWJldCwgVG9iYWdvLCBUb2dvLCBUcmFuc3lsdmFuaWEsIFR1bmlzaWEsIFR1cmtleSwgVWdhbmRhLCBVbml0ZWQgU3RhdGVzLCBVcnVndWF5LCBWZW5lenVlbGEsIFZpZXRuYW0sIFllbWVuLCBZdWdvc2xhdmlhLCBaYWlyZSwgWmFtYmlhLCBaaW1iYWJ3ZSJd) This uses [factorial number system](https://en.wikipedia.org/wiki/Factorial_number_system) to encode the permutation. A shorter solution would be to index into the list of all permutations of the input but that wouldn't complete before the heat death of the universe. This code starts with a big integer encoding the permutation on the stack: ``` ⁺9( # for n in range(158): n› # increment ḋ # divmod ÷$ # push each to stack and swap ) # end for _WṘ # pop, wrap stack and reverse ( # for each: n~i⅛ # index into input and push result to global array ⟇ # remove this index from input ) # end for ¾ # push global array ``` [Answer] # [Zsh](https://www.zsh.org/), 264 bytes ``` for c (`basenc -d --z85<<<'Mk:jJktc3vb]!]%BS)bqk06z.d<2JK4}#Q.KB7#lG! <f0y>>wjhI.U!n%zqRCZPV+D2jvBlmbh(IbM#uNO:DLspPBde?8utzwSClw!E<z3)nwuv P5mQJ/5B3GLh6/LvG<ZO*>E=ORx0:1udh$tAJVo9-T:5g(D(Wu4i2awQWU#baHqHs:Bl( k((d#bWVZys6//02.J9S'|basenc --base2msbf -w8`)<<<$@[2#$c] ``` [Try it Online!](https://tio.run/##NVRrU9w2FP0rYiCTJZ0FugRKmA1tCRkSQgqEBmboMJMr@66tXT28eqyxp/3t9MhLPvieI1m676s@1M/kq9X7EclU1iSVoFlVk1UhkhWkJSgBK/ZrVOyDIFs5jaWv2EZlwVKInrR6YUBJNRkKGT0pC7SVppJDDeollQ7/GPqSyah6Bth8kL1JJRTUKbsgnVarrM95yw4QQ0uwKD31SguZdEWDveTNIJMtlSjIsHfOgliCsgJnpGTKG53JUFMJoTRnCX2F085IlQmCg0QCvCqw9hxxKEnQrvEpiKLnonZBuxUtcKGk2hnuRMnWkF@Icq6kS1EJLhLC9IKrromCdSC9Wm/kVNhScKyVa6BipuYKwg67M0@2YADboq6SytFWJBFMRYOHqAVC6ESuE1aeGcczrO9XiUwWkQ2hSNBg@SeMpQqBElZdvluTgp@1s2XyqBVItcAn6mSR1U6oggeVCjmlLJ3lkBlczGIJ8XIieGItVCTdiTkqn1M3pwbn5s6XgAWZJhU1XFmw7SCdzzy18EFoQjtoRpMgTM3BxdoJreTQdcAuS2Q9sg2R0SU6PbFBmn0lDApcUUCJQWtoFTnuVg3QZXdBhlXMNHk4mZva8JMqnDDO0hrQ03nbeVcMG31O9zKxsGRUTrzlhjRk@5JTsJ5piN8iXk/IOhjqs5b5ivMtdcLlnmvQLsNYQQsHzA2DQTcBhrudaNgn0bhBZeN8TBUMNol9dD47uyR0pfDcJKlVUTqjsmErfDYAc2jPHDBsWnR9IDtP@IuKo36ecgyhcHFQH9hy1h4w0RhdRmlFcGYY4tDkkQ1e4eQCy5QLGJIhDDnQY2CMwBz2aq2qZTQ/QMWe/Xqry9FHUvAEYPvBvYiGG37HGtYhhsMhLxvMomoaJEWFl02UP4roJGEeo8sCbRc6DNGgK@GRGtAvMH3IVA4Zm5FLZDlyEHgMhqyuYKxPaFSxUhyz7x0bONylCmNM@XnpCZ0s@vWA9cpIki1vP88wrYUY/ZCEdBViXIrxuD86mE6nr78ujucXi1jsr@TjxuOr09ttuVzsHfY75XRy8eXtf5s3O19Of9vU5xvT2V53ctLO68873zfsq3757cPD9d0vZ5P56lQbWY8@y6@b6a@r47PL0Fyflvz7UYp9e/tBtxsfp/3@tm3T6vrA3FzsHpzun1/Wh7uXq/Ppw9Wbk4/vr7497R3/ird7K/55cefejf8@PqhGZ6P79FZNqL25/74p6dPyUzg@1aPFaFRuyvu7hy4c7u7uTXYu3t2@/vdncONMJibImRi3Rz@2EeXWH/9MNreKx@fn/wE) Uses z85 encoding. Reformatted the code above for readability. It doesn't work on TIO (no `basenc`), but [here's a full version](https://gist.github.com/roblogic/5ca31cbfca7379602dddabb250f665ed) that should run on MacOS or Linux. ### 355 bytes, hex encoded ``` s=951a5f6f3e4a7176241b382c7420973f3d3a12062a1e15220e6810098f7a709684320c396b8642303587082649933772777c0247786c167b412546458852484c99500a8c570d73312d2880436d17018b65114d5b0b1f4f4b61518e448d89816683671398926294059d2914639c85343b033618535a90696a1d542b0f338a7f4e5c7e0427647d5519219b2e3c5879591c4000759a235e9160565d6e2f0782 for i j (${(s::)s})echo $@[0x$i$j+1] ``` [Try it online!](https://tio.run/##NVTLruQmEN3nK1jcxR1FkcDGr5FGyn9EWRR22abbBg@P2@OO8u03B/fNwnUOGOpdPOP6SWH5@PFOJk8rGStoXlZyNiZygjYDSsCFwwsthyjILX7DMizsknVgOaZAm/1iQEMr7RQLBrIO6JaNJo4raDA0efxj6Mt7QftkgCsHOex5goI1FxeM3@xH0eeDYw9I8UGwaAI97SZM3ha67OWwXzK7yYqRdg7eOxBHUDbijDFMZePcC6w0QdiNi4S@0W9@N7YQBAeJBAQ7Yh044VA2oOcRchTjk8fVx81/0B0XJlr9zqeY2O0U7mK6WeNzsoLHjDCD4OU8kuAt0vbx2iipcJPgtFp/QMVsbxbCXbtzIDcygN24LtmWaBcyCGahy0PUAiGcotQJq8CM4wVe95dMexGJd0KRoMHx//CHsTFSxuosd1ey8HP1bsoBtQJZ7vjEmh2yego78qXSIqdUpHccC4OLRfyE@DoRA/EmbKLtFDdUvqTuRgfO3XyYAHfajzyucOXO7oT0ofD8gA9iI7TDxmgShLlx9Gn1YrPm6jrgWSSyntjFxOiSLf/iHWkOi9hR4IUiSgy6QqsocT/sBWdxF@RapUJzgJOlqXf@ZUcvdu/oBejpsu2DH6@NZ0n3z8zC0W5L4h0ftEE@vnIK9mS64neINxCyDob6vGS54sODTuFLzx1ol2usoIUj5obBoJsA191THByyOPyl8vAh5QUGj8wh@VCc/UnoShH4yGaz4@R3Www7EYoBmEN7loBh06HrI7lbxl9UHPULVGKIo0@X@siOi/aIicboMkorot@vIY5HGdkYLE7escylgDHvhCEHBgzMLjCHT/tS9WA0P8CmJ4fX1lmiT2ThCcA9L/cSGu76nVZYh7gOx7I8MIv2OJAUG782Uf4kkjeEeUy@CLRdPDFEl66MR@rCcMf0IVMlZGwmnpDlxFHgMbiy@gFjz4xGFR@WU/H95B0On3nBGFN5Xp6EThbP14A97W7IPPjbZ/wxNIqauZ1r1tSprq20MnVfjZ2u5NDVcz3VpCrZVqRYNVUlue2VlEM/d9TJoe11XcmxHlrTt7qqZd30neyrVg9DXXdd1XXdKCvddX07qrYzWlWNbnXT902lez0OQyMl9WPTyamra1VNVd9LXbeT6qTqTdsopafGSKNmPWvTqkb1rHU/9UOv2rav207VQz9UbTVo2QxTNSjd1sPYN7WujazrVoE2NMh2aElNja6MnOu6p27W3IwdS111re6mplFDpQZTcT0ijKEZ1KillF0zUFU3PKhWNm0ztVzNsuur32Y8dlbcxPvbP@/x@/dv8d9v5ekUb3/@JX@92bfb7@rvz8//AA "Zsh – Try It Online") Uses the hex string in @lm42's answer. Could save 2 bytes by editing `$s` (so I don't need to have `+1` in there), but that's a bit painful. I might add a shorter solution later, using z85 encoding. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~212~~ 150 bytes ``` ≔⪪S, θ≔I”)¶‴k~r~↷⊙α¤ψςF8→⊖"]´τDβ²×ju÷↷Hγ0÷≕⊙≧↖Gⅈσ¦⊕ANQWo0Ex⟧/DT✳o?L:Jμ∧LY<γ⊗⬤νGΠ↗φWε﹪πχ5₂{“⊗K»§″^⁶↘;R⁷↧C�nεKΣ⌊⪫lY×≔>¦³mZ⎇Π⊟⁵↶⦃~D”ηW⁻θυ«⊞υ§ιη≧÷Lιη»⪫υ, ``` [Try it online!](https://tio.run/##PVTbbts4EH1uvkLokwOkgG7UBX1qkjZNmnS9UVqgeRvJXImNRDoUGcde7Ld3z1BuAYFzOBoezpXdQLYzNP769WGeVa9XzXZUbnWtt941zirdr07Porf4IJ5P358czS5odqu3Ik6SoqzyLC5LRnWZxXmWx7VIRJ6IuE7qiv@mSSqSpMzqvKizIs7KJE1FiV2SlblI0lxksRCZKLJcpFVdizzOk6zKi6Iu6rxKRJaXaZ6LQpRFVeSxiMuqKHBBKbKyTvK4SPKqrOtciFSIMsYRwLpOqjrGwbQScRyDoEiqJMEPnCiTSpRwp8jSKinZ6aLMqiqtyzKuEtxXYklrgaCSWuA2HILLMTwuixRxCWgKxFlgVxVlUoAfvhVxXAlO1oBk7QY1ymh1p7SfV89nkT89jf49ebP287DyZ9EHd6038nWl2Brmb@5ou@T3XvUDV8Fdqhe1kWfRrdS9G1bqSPzfyRq1casbozQzhQKdvkcVWx9dDtSC8sM//UBazY40NmMLTAx6aY9ASTsD6N6MrLC91E5phn52lkb1GzI4p4EmmgOwpDQD3Y@0kfPA2La0MfxbgthPAaiDZKmDtbST3zDR4INL52ZEcKwwVkvD0s074vvPLR3UCOnHnpbbvZ0W4fUGwV3QJK0xmpEmpr2AYdtKCqr9FORAG15RhCCY@sKMZmpVQAicBTIU3auOVVY6NvUtb/Zb6xHQxUF2g5lH80JPfO6SBjPJPYDUE9kngJ@qNd7BrY@dRxYsQL/fOogxamh8Oeo4XRoefXSDMlvm@qR@Kl718uOTJd1JllJ3Q3TlVUjHFbUc6RUtjl8hk6ThwNWw/LZS8imWR6IrT1NYnZyIiwsqLf/Id@dqnsnzdh8oPpNi9z8bvfGWiwzUR1@wAHqNIuC6604u7Oha9gPCaDkHaDnfWJ95/W02W5Ko4rWjEcdv0D4hyze0ZesbYzcsv9C09d3A3n2Res/C2LDzO7iF3ifuq1uJDuY03MrZuAGVu1Xt0soA@yBQKCf17CQ33K1/lRPqYhHDHVqkp7kjy3gAP8uRdmqR@xAF0LJ3YeOtcsvQ3MlX1eHGO6PpKDEz4Y@xpltUBy7PswfzV5pUqNRXuaWRxe5PARg/Sloy9BX5sNR71ivM5VGEo8buCFn7K3TyGq23DPKaRjljSiVDTTwU64UDxmtpUdS1WdjXxjrfswNrL60z3OTw9G9ynIZ7ufXtqLro0kxKwxGQ35tpCfjezyEj95hHHq6GdHTj2aQhv1F4KygE2HTGLZc1UstwV4NXxRKqZNjHBowhUc02vBmNVainfmKND@Vv/ER4bBjgSeO2bXY8/QvrTm4kG@2UO0h7VO5Dhh5I7ZjggfRh8fphoOO5h0Ei025YjsyLYo2HQG23yB1a87cePYQWezAt8WPwYMKKbp73GNuF1eMRXYB94rn/1i9J@aaVk5uocZgyUH2zfqnCd6Ti4CWP3XclXYjph5w4jh@@x0tC4dl7JMVt@Hic6kc1tdTu5Mmvdy/j/w "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now uses the reverse factorial number system. ``` ≔⪪S, θ ``` Split the input on commas. ``` ≔I”...”η ``` Start with a large compressed integer. ``` W⁻θυ« ``` Repeat until all of the countries have been extracted. ``` ⊞υ§ιη ``` Cyclically index the remaining countries with the large integer and push the result to the predefined empty list. ``` ≧÷Lιη ``` Integer divide the integer by the count of remaining countries. ``` »⪫υ, ``` Output all of the countries joined by commas. [Answer] # [Python 2](https://docs.python.org/2/), 226 bytes ``` lambda x:list(permutations(x))[eval('...'.decode('zip'))] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVXNbhs3EEYPveQptgYaS20S2HKcyAESILZjxT9xFK8SII5SYHZ3tEt7l9xwSWulPkovAYqi79RDj32OfkMqOYjzcTj7cTh_-uPvduUqo0df_1w8n__l3eLh-J8f_qupyQpK-me16tygZdt4R04Z3Q364fAT31E92O7n_UE-t_N-XMz77GDe7-7O-50dWcb47X3CMspxxLa_hYByMZr3-QJfHJzAPKtgsQ8WaOhJ8hYqYXp8h2UXXxd794FgQIQNmMb8DjZy05N4CQkXY79fjH-FzdNm3vOoii4xyd2g330kt6cww44yaEa_A4hrT8EDjsXOxxfXz05XOHrSyrKE8WIER3ZHkWxnp8MGjPx0dCCPuMSCs2L_04sXr6LNwR5YC9FFds4-4EO4mu-L3IsEC7lz_zeYQDEeH85-Go1-hs3jtZDP7datRPJu8lBOQVrEJ2bFZ5xLEA6u4wmBiHGaQ7mATzu7N6Nj8Xv7UcG5KXiwvVbt9nD4-d7CmiZRjq0zpu4S1bTGul826f7x3_r51svMJ8cVZepB8nJRVqSReNLY1BkwCSjZboBi2wHo0tSisCVrp7RA3zlLtfoGBRxSRQ11AVhSWoAuayq4qwTbjAojxwxi3wSg1ixSB2upvkKIKh9cOjS1ugvMxmo2Il23JLn_0NJa1ZC-Line7m0ThdcFHndEDVtjtCBNQnsEwyxjCqpVE2RFhayq5iCE-sjUpslUQHi4CEQouVK5qCw7MfWZbFat9XjQ0ZrzynS1uaNb-e6YKtPwCoB1Q_YW4EZlxju49Sr3iIIFKFetg6iTlOq7jU7CpeHRK1cp0wrXibpRsup4cGJJ5yySdV4lE69COCaUyUsnFB2fIJKk4cCkiseWWb4SuSGaeGrC6rghSS6oNH-XDw9V15GX7SpQvCYl7r82uvBWkgxUJudYAL1GEnDdac6R_RQpoCCM5i5AK_HG-kXWb2adJUYWTx3V-PwM5ROifEatWJ8ZW4g8p6b1eSXenbNeiTA27PwSbj1ILkjq6oJRwRKGC-4MZh2AymIpA6yCQKIc686xFNyF77lBXize8AYlUlKXkxVcgV9kTUsV5Sq8AijuXdh4q1xsmjfcqxw3vjGaNhI9E06MNXlUrSU9XzyYL6lRIVOX3FItYvk9AYKvmWKELhEPS6UXvUJfbkT41NglIWpvQyVPUXqxkadUc4cuZYGapCmmkQPGU7ZI6tRE9imGgy_FgamXkSFFDk_fkZMwXHHrs1rlybFplIYjIL8yTXzwle9CRK7Qj9JcKenkzItJSr5QmBUUHpjmxsXLUtYc7koxVSwhS0Z8TMEYApW2YWakViGf-lY0PqQ_9Q1h2Aiw6FCUbbqU7o-sSy5YjJbKrdlulKsQoRmppRDMSK-j17OKNt_NKkakXRU_6aJiikGg2haxQ2l-06OGUGIzk5EMg5kJK6q5W6FtI6vHEI3A3krfvy9jUN5rjOIiSfGXyqB6b33MwgeEYu1Z2u6DYhfe9JEbecdHX2KSUBh716SkDK83XX2tmoyyJW896tpaucHWg2RreK9FTNxgMaiHwzjmv36N8n8) (Times out on ATO) Here's a hexdump of the string: ``` 00000000 78 9c 0d 8d b9 11 00 31 08 03 5b 02 63 be 72 78 | x......1..[.c.rx | 00000010 6b b8 f2 cf 89 46 1b 68 05 9f a6 20 4f 1d b4 76 | k....F.h... O..v | 00000020 b1 5b d3 26 b5 aa dc 8e 51 19 16 08 af 8e 15 64 | .[.&....Q......d | 00000030 38 2b d7 6d e2 68 8d ea be 91 2e b8 53 1e ab 92 | 8+.m.h......S... | 00000040 7b ac b7 0f f0 59 3e 5a 3a 49 79 96 70 96 77 1f | {....Y>Z:Iy.p.w. | 00000050 32 76 12 8d 00 73 1a e7 32 39 cf 4e c2 d5 5b 3e | 2v...s..29.N..[> | 00000060 3e 45 8d 93 ad d5 ac eb 56 06 c5 06 33 1a f7 05 | >E......V...3... | 00000070 5e a3 88 42 54 21 32 32 25 c4 7a e7 0d 22 6b 11 | ^..BT!22%.z.."k. | 00000080 76 47 2d 88 9d 8e bd 5d ec 89 5a 88 a7 ed cc f9 | vG-....]..Z..... | 00000090 01 6a 32 44 1f | .j2D. | ``` Verify the bytecount [here](https://ato.pxeger.com/run?1=NZJNTsMwEIXFTUokSELVKnGbNumiC8SP2IAQCAlqkJzYUUPzp9QtLhyFDRs4FFdhwxsZFpl43jx_M7b8_tXu9LKpPz4-NzofxN97P21X1NorVe05pahSKXpmVhZr7bWqqzZa6KKp157x_YXaitJznb5ruEky3nETS27ShJsw5CYIKMT4RgsElqGkOrPCD2LOuMly7EjOYE-XcESgQBGT3hUkIo23CCF2y9EhVjAIgQSkWF3DQ50mtokglkIeybgPz7TiRrGlHUkJ6g18OKTuN7AhEykU9oYFjTYFB4w8uJ8_zC52KE1aCi8w5wyDhMzCgmCNBEQ1ZQkd4hIBNRkt5vNT60lGoErSLF2ld9iIUbOI_iMLyKln9AQLhDg-vt1n7ACe8SvBeees6Ca35wOqAirtEVP5iDpdQvJgKwIghWoGMcdMQfjMTmhut--4Q6myRirPfS1a1_cfeZ13TdUrtOp005TrXlG1TaePHN-3b-DvKfw_iV8). # [Python](https://www.python.org), 287 bytes ``` lambda x:[*permutations(x)][0x7b615ec218d9684ced86cf775d91acba8a10d91e8c0ba9575c4d35ad7acdd4ab961fec9af76bf28dfd2052f527c7eb3b2f31ef5ffc7e51db33e6055b85bf5395efeb0474c9e9ec3d1ebd7cd57f98c80c580ee7a4ee71483aac1176338387311cfecd066f8aa84e78a359328c58af2acf0a9ecdbbe] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVXNcts2EJ4eeslLlOOTnUk6oiiKVGdyiJ3EseOkquVkJk5zWABLEjEJMCAQWXqVXDLTaR-qhz5LdwElF3wfQGCx-PaHX_8Zd76z5ttfzZM__w6-eVz_-9MvPQxCQXb_24eHI7ohePDamun4_uTjh9l9JZZ5iXKe12q1rBcSVb2UTVWVapWDFFBDPiOKtZwJWJVVKReqKEFVIJVagFgt8wblCppqKZp5rRo1n5XzppxXskJRiHlT5NiUTUPTMleiKHA5K0tRl6Ipi1WJDYrZolrIFa5QFipHoSqpyqpZ1bKeybKeIVawoCFf1AWAzPNqWRR1UVdFnku6XM2Wy6YGqBdY1VCUq2Je0zlo5iCbGZBZJQR-fNA4O2Tao_PW9lOmh9E6__Cg08__9U-OnoqQPetA6EfZ06btwOjJg6FJL4gDkxbdgWh0ExHT2p4XXIvGa8M0TN5Br79TJqfQwQBTJA60YWLaHhROHXMnQFn-jGQ4DJHoPTKauJsjp9hQF6JLp7bXX6Jl6wxaRj9tge8_dbDXPWHoW0i3BzckCEbR485gQGetYWaAzZ7RRhIJ4tJuiNiB4lH3GIFNn9neDkJHRg9nIIWyay15yaHnrUHwZDe6QA8626Ps7NTbL3DH555BZwfcEUEzgLsj8kkLGzy59VwGUsERaXejJ-izDfRfDmsslyGPnvtO25FtvdCfNI8mfXjhwEhkRCO77DzoKMc5CH7pOSTHz0lJMOTAeZc-O0Q-xXgwdB5giKPHATi4ZMrgD3x8qqcJAk930cRL0Oz-S2tUcBxkYm32igaiwVAQ6LoLicn6BYUAIliDU6SO9abxM4_ft00OkKJ44aGn45eUPlHlSxh596V1ivEVDGOQHXv3Cs2Owbo4C1ty61F2BZxXV0gZzDJc4WSpRxDRIqUykV0ECpRHM3nkhLsK9zhQXBy94TWlSAuTBMe8I_uMPWx1wl18BbE093ESnPapaF7jvZZ042tr4IBUM_GLdVampT2H53Mgy29g0DFSb3CEnmH7IwDMbxGSQm9IDwdt4HVNdXmAeNS6LZBqv8dMXlPqpUJeQ48TVSkyNcBFsU42aPMaHQV1bZP1NTWH0LID68Atg5OcPP0DPMtwjWMQvZbZMztoQ46Q8Ws7pAdfhykqck31yMW1AZNdBt6ygaA09QqID9xI69NlGzQY79pQV3FAUbLs44YsRqE2Y-wZG6cpnuaOV0IM_yYMQM2GiaMKpbTdbLn6k9UtKuRNW-336A6Lu6jQDegtG7gBs09e33RwOHfTISntu3RkSgtragR6HEk7Ss3v65RDlGI3VgA3gxsbR8rmaUdlm6wGaqKJuDuu-7dtEuWtoVassg39jpBMvXUhReEdSbEPyGX3TqOPb3qPA7_jfWipk0Bse7egOQ1vD1V9qwcBYotHv05jr_3x0aPs6OTBSJr44-a4PzlJbf7bt4T_Aw) (Times out on ATO) Port of Kevin Cruijssen's 05AB1E answer. Gets the (a very big number)th permutation of the input list. ]
[Question] [ A listening party is an event where a bunch of people get together to listen to some music (like a viewing party, but for music). In the age of the internet you can do Listening Parties online with friends, where you just all hit play together. The problem is on the internet everyone is in different time-zones so you can't just say "Let's start at 5:35". As a solution we just type `x`s in the hours position. So `xx:35` means whenever the minute hand is next at 35. If the minute hand is already at that value then the party happens in 1 hour. If you need to specify more than one hour ahead you can add `1+`, `2+` etc. to the beginning. So `1+xx:35` is an hour after the next time the minute hand is at 35. Your task is to take the current local time, and a string representing when the listening party happens in the above format and output when the listening party will occur in local time. # IO You can take and output the local time either as a 24 hour string with the minutes and hours separated by a colon (e.g. `19:45`), as a tuple of the minutes and hours or as some native time type when available. If you take a string you may assume a leading zero when the hour hand is a one digit number otherwise. The two should be the same format. You can take the string representing when the listening party will happen either as a native string type or as a list of chars. The string will always match the following regex: ``` ([1-9]+\d*\+)?xx:[0-5]\d ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer being better. # Test cases ``` 5:35 xx:45 -> 5:45 19:12 xx:11 -> 20:11 5:15 1+xx:35 -> 6:35 12:30 1+xx:15 -> 14:15 8:29 3+xx:12 -> 12:12 4:30 xx:30 -> 5:30 23:59 xx:01 -> 0:01 15:30 25+xx:12 -> 17:12 12:09 xx:08 -> 13:08 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes ``` Ṗ+<¬Ṫɗ+%"24ɓṣ”:f€ØDV ``` [Try it online!](https://tio.run/##TY0xCsJAEEX7OcUiWAVxZzarZhErzxDwAFqIB9BObOwV1MYqRUBSiUWCncEix1gvss5uLKz@nzf/zyznq9XGOVudovGrsNWtOUfdDsXN0VbZZ3s1i8@uqC/T1P3m1M852PJuy4zqvP8@2OoC9vmo97yaOaeN0mK9NrEWvYnQrICJQfIM0TOSbEAb1AIjpiokB6yAZJRsKQaKMRsYGUqECpQCJTYQ@6zvy/aTkkDK6MQzGT5JVkC/EaT/6kNf5yOyzY4CVGy@ "Jelly – Try It Online") Takes the time as `[hh, mm]` on the left and the `xx` string on the right. -2 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) by a clever exploitation of Jelly's vectorising atoms! ## How it works This uses the `ɓ` chaining structure to group a series of links to act only on the string, then we run the main links on the result of those links and on `[hh, mm]`. The `ɓ` splits the program into two links: `Ṗ+<¬Ṫɗ+%"24` and `ṣ”:f€ØDV`. The first one is dyadic (as two arguments are passed to the program), and the second one is dyadic but with the arguments in the opposite order as the first. For a program that consists of two dyadic links `x (f g) y`, we calculate `x f (x g y)`. Non-notationally, this means that we run the second dyad on the two arguments, returning a value `z`. We then run the first dyad with `x` on the left and `z` on the right. The standard way of writing this would be `f ð g`. Using `ɓ` however, we reverse the arguments to `g`, so `f ɓ g` is `x f (y g x)`. `g` is `ṣ”:f€ØDV`, run dyadically with the string `S` on the left and the time `T` on the right. `g` consists of 5 atoms: `ṣ`, `”:`, `f€`, `ØD`, `V`, which can be grouped into `ṣ”:`, `f€ØD`, `V`, a series of dyad-nilad pairs and a monad. This means that the right argument to the link is essentially ignored, and only the left argument is modified. We could try to use a monadic link for this, but by reversing the arguments implicitly with `ɓ`, we can avoid any quicks to indicate that a monadic link should be run on `S`. `g`, given `S`, extracts the offset and minutes from the string, returning `[offset, mins]` as a pair of integers. `f` is then run as a dyadic link, with `T` (the time) on the left and `[offset, mins]` on the right. [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) noticed a clever exploitation of Jelly's vectoriser that allows us to save 2 bytes here. Essentially, if we have a list and an integer, `[a, b] + x` will vectorise across that list, yielding `[a+x, b+x]`, and if we have two lists `[a,b,c] + [x,y]`, we'll get `[a+x,b+y,c]`. The `"` (*vectorise*) quick will take a dyad `h` and force this behaviour. Therefore, if we want to apply a dyad to just the first element of a list, we can use `"` and turn the right argument into a singleton list. For example: `[a, b] +" x ⁼ [a+x, b]`. Here, we calculate whether or not the `mins` is already past the current `minutes` of `T`. If so, we add `1` to `hours`. Therefore, we remove `minutes` from `T`, yielding `[hours]` and add this to the comparison, to yield `[hours + (mins ≥ minutes)]`. We then add this to `[offset, mins]`, to yield `[hours + (mins ≥ minutes) + offset, mins]`. Finally, we use `"` on `%24` so that we only modulo the first element by 24. ### How it works, in detail ``` Ṗ+<¬Ṫɗ+%"24ɓṣ”:f€ØDV - Main link. Takes [h, m] on the left and S on the right ɓṣ”:f€ØDV - Dyadic chain with S on the left, [h,m] on the right: ṣ”: - Split S on ”: € - Over each half: f ØD - Only keep digits V - Evaluate each as integers, [a, b] Ṗ+<¬Ṫɗ+%"24ɓ - Links to the left as a dyadic chain g([h,m], [a,b]): Ṗ - Pop; Yield [h] ɗ - Last 3 links as a dyad f([h,m], [a,b]): <¬ - [¬(h < a), ¬(m < b)] Ṫ - ¬(m < b) + - [h + ¬(m < b)] + - [h + ¬(m < b) + a, b] %"24 - [(h + ¬(m < b) + a) % 24, b] ``` [Answer] # JavaScript (ES6), 52 bytes I/O format: tuple of integers ``` ([h,m],s)=>[([H,M]=s.split(/\D+/),h-~H-(M>m))%24,+M] ``` [Try it online!](https://tio.run/##bc9NCsIwEAXgvacYBCGhU5tMGrVCXblw0xPULsR/qVaMiCuvXketVay7efDxeLObXWZuftoez/6hWCzLVVyKdIP7DJ2MR6lIJ5hkseu6Y749i2A69gKJG/828UUy2kvZoRC9JCvnxcEV@bKbF2uxEilYBGMzhPb1OgxtGwCkhCAAy6n1g3WEoKnCWn8wKY6tP9X6Wa099obLX7rHd6OaeIeqsa6xDjk0qgcIFD20eWqqNXFo6PDd/Zihvn806heTQbBRhdXXj4pTY7V9N5OthlQ7@nyXdw "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` (h,m)%s|[(b,_:c)]<-reads s=(h+b,m)%c|n<-read$drop 3s=(mod(h+sum[1|m>=n])24,n) ``` [Try it online!](https://tio.run/##Xc/disIwEAXge59iEIUGR8jkZ7eVzb6IyFKtUNG00rjgRd@9m9gE272d@XJOpi7d9Xy7DUNWo2Vr1@@zI/7sTuzwte3OZeXAmazeHMPy1DfjcFV17R2k39i28lv3a/fU22/THJhQ2LDBlpcGDFTtAuDeXZoHrCDTKDWDNSyfz53SSzAmzJRmU0QFkkiKaFSCIxGbZ9GYRRvvZEz7CA2zNIGSvx1FRyo8n8IcRfFy8uVEdCJ8ZupUygutPN3gZ1MkJOoiKR5v4MjnJ5BOWULPSj//l/pv8HdeHplEnrPF8Ac "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 56 bytes ``` s/(.+):(.+) (.+\+)?xx:(.+)/(($1+$3+($4<=$2))%24).":$4"/e ``` [Try it online!](https://tio.run/##LYxBCsMgEEX3nkKCBUUandGBOLT0It1mUQhNaLLI6WudpJvPf/Mfs4yfiWpdg@29Ywnd4undY98PDNYa8CZ5a/LtbtC5C2bXd2xyF8ZaiRPp5mZSUBhQOoAiBtLgG6Q2IKd4EpAaGItOB6DKsogVFSamIj2CApI70t9qD@I5Dd952V7ze63XafkB "Perl 5 – Try It Online") We match the input regex and do some fun math. The minute hand of the result is always `$4` (the fourth capture group). The hour hand is the initial hour hand (`$1`), plus the time offset (`$3`), plus one extra if we've already passed the minute in the current hour (`$4<=$2`), mod 24. Perl's numerical coercion rules help us a lot here. `$4<=$2` coerces to zero or one, which is the exact number we need to add to the hour hand. `$3` is the offset value, such as `2+`, which coerces to `2` under numerical coercion. If there's no offset, then `$3` is undefined which conveniently coerces to zero. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~81~~ 76 bytes ``` \d+ $* :(1*) (1*).*:((?!1\1))? $#3$*1$2: +`1{24}: : 1* $.& \B0\b \b\d\b 0$& ``` [Try it online!](https://tio.run/##JYoxDsIwFEN3nyKIqGpTqYp/@iX6l0qcIwNUMLAwIIZKiLOHhi62n@3X/f14XkvJtx4@wFqGzlUZgrXtfGBm183wx@QDvRj6Cz8yfg0GBvihQT7HvAB5ybfNo29KUUvq1tVGBSej1ExCjerYb5C2QSzFnag4mUwu/UEw1qW@IiSZTjVHglp70f31Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 5 bytes thanks to @user41805. Explanation: ``` \d+ $* ``` Convert to unary. ``` :(1*) (1*).*:((?!1\1))? $#3$*1$2: ``` Add the extra hours, plus check whether the minutes are behind and if not add another hour. ``` +`1{24}: : ``` Reduce the hours modulo 24. ``` 1* $.& \B0\b ``` Convert the hours and minutes to decimal. Due to the way `1*` matches again at the end of a row of `1`s, this actually ends up multiplying the result by 10, so the trailing 0 needs to be deleted in this case (but not in the `0` case, as that just becomes `0` as expected). ``` \b\d\b 0$& ``` Add leading zeros to single digits. [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda t,s:(str((eval(s[:-5]+t[0])+(t[1]>=s[-2:]))%24),s[-2:]) ``` [Try it online!](https://tio.run/##VY7NbsIwEITvfoq9VNgiqfwTt42lcKPXXnpLoyqAKVFDsBzThqdP1wmq4DTjb2dn7S7hcOrUuC8@xrY@bnY1hKQ3tA@eUvtTt7QvTaqrZSh5xZY0lKJaFX2ZSlMx9iAzllwf4@@haS28@7M1BCD4SxQ0zdEmgH1N95XAZwJ2cHYb7A4KaDp3DpQ99q5tUP/zOIpy5QuzmEcOOwLd09tKdtcZc3bYWhdg/fa69v7k519svK2/R22UhmEwmYZ0BRqViNwIGZkQkUmOhmgjNIglUjUln1CJkEbxmYqJigwNeTEyBzVROVGJhmQxG/f5fElxIpXReWR8usRRiYgTkPpm/RnNHw "Python 3 – Try It Online") Inputs and outputs a tuple of strings. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ':¡€þø``©@ªþO24%®‚ ``` [Try it online](https://tio.run/##ATYAyf9vc2FiaWX//yc6wqHigqzDvsO4YGDCqUDCqsO@TzI0JcKu4oCa//8xK3h4OjE1ClsxMiwzMF0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8X91q0MLHzWtObzv8I6EhEMrHQ6tOrzP38hE9dC6Rw2z/uv8j45WqqiwMjFV0ok21TE2jY3VUQCLGBoCRQwtdQyNIEKG2kBBY4gyQ1MkMUOQmKGRjrEBRNAYLGgEFLTQMbKEm2dsABQxgasCihiAbDAy1jGFKjIyhes0NAUrjAUA). I/O of the times as pairs of `[HH,mm]`; input-order is the string followed by the pair. **Explanation:** ``` ':¡ '# Split the first (implicit) input-string on ":" €þ # Only leave the digits of both parts (will be "" for "xx") ø # Zip the pair with the second (implicit) input-pair ` # Pop and push both pairs separated to the stack ` # Pop and push both minutes separated to the stack © # Store the minutes of the string in variable `®` (without popping) @ # Check if the minutes from the input-pair are larger than or equal # to the minutes of the input-string ª # Append this 1 or 0 to the pair of hours þ # Only leave the numbers (to potentially remove the "") O # Sum this list 24% # Modulo-24 ®‚ # And pair it with minutes `®` # (after which the result is output implicitly) ``` [Answer] # [jq](https://stedolan.github.io/jq/), 123 bytes ``` .[2]|=[scan("\\d+")|tonumber]|.[0]+=((.[2][-1]>.[1]//1)?+0//0)+(.[2]|length-1|./.?//0)*.[2][0]|.[1]=.[2][-1]|.[0]%=24|.[:2] ``` [Try it online!](https://tio.run/##RYzLCsIwEEX3fkZAaE2aZCYNtIXaD0mz8IUiWlErdJF/r8mouJtz5t57vs@zdOhD6567zZCxvt9zlofxNryu28PDB@m0522WpZQrwK@lA68U5B3XSumc0ydcDsNxPBUQpJJd8isq6DQAvv21aW7ZYhmPBv08OyuMFWyamtIyv3BQC0BigMRWQHwDj8J8AiiM/hogUwmsBTMkMImSEqmhE6IRtibWNBkH0x/tvxFH9TdSRX4D "jq – Try It Online") Takes input as `[hh,mm,string]` and returns `[hh,mm]`. jq does not have a way to cast a boolean, so the try statements are used(thanks ovs). The modification ops are quite convenient, though. -5 bytes from ovs. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` 0p\:€⌊Z÷÷:£≥J∑24%¥" ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=0p%5C%3A%E2%82%AC%E2%8C%8AZ%C3%B7%C3%B7%3A%C2%A3%E2%89%A5J%E2%88%9124%25%C2%A5%22&inputs=%601%2Bxx%3A15%60%0A%E2%9F%A812%7C30%E2%9F%A9&header=&footer=) [Answer] # [R](https://www.r-project.org/), ~~111~~ ~~108~~ ~~105~~ 102 bytes ``` function(t,x,k=scan(t=el(regmatches(s<-paste0(0,x),gregexpr("\\d+",s)))))c(el(t+k+rev(t>=k))%%24,k[2]) ``` [Try it online!](https://tio.run/##VY5BbsIwEEX3nAIFIY2VQbLHcUuqhouULiLXQJQ2RbELvn06aWqUePUkv/n/98P94rrGN6EaTj@dDc13BwEjtpW3NWPlPqF356862Ivz4F9319oHJ0FiFHjmLxevPWTH40eeoRfjs8BHIW/z3t0gHKpWiO2WCmzf6F08CsGCQW0EZjG@FCYTm/XusDaMq5miSlQ0OUr9OySZV4scNeaonC2dkp4YF0mEWiZLJUsVzHNtj1Sypf8sShYxz61iyhr75GO5lnOFNJpycmRaLhkXm8yUQ2ZZ98w8/AI "R – Try It Online") --- Slightly different solution with the same byte-count: ### [R](https://www.r-project.org/), 102 bytes ``` function(t,x,k=scan(t=el(regmatches(s<-paste0(0,x),gregexpr("\\d+",s)))))c(k,(t+k+rev(t>=k))%%24)[3:2] ``` [Try it online!](https://tio.run/##VY5BboMwEEX3OUVEFWksJpI9xm2JSi6SdIFcN0G0NMJu4tuTodQRePUkP735/XA7u67xTaiGz9/Ohuang4AR28rbmrFyX9C703cd7Nl58G/bS@2DkyAxCjzxl4uXHrLj8SPP0IvxWWgRQt7mvbtC2FetEJsNFeKgd/T@OAgWDGojMItxV5hMPK23@7VhXM0UVaKiyVHq3yHJvFp01NhROVs6lZ4ZFyVCLZOlkqUK5rn2ilSypf8sShYxz61iao335GO5lnOFNJpycmRaLhkXm8zUIbM898I83AE "R – Try It Online") --- [R](https://www.r-project.org/) is terrible in string challenges... [Answer] # [V (vim)](https://github.com/DJMcMayhem/V) `-v` calling `bc`, 105 bytes Thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) for filling in some V documentation gaps. One could reduce the byte count by using raw byte source code instead of `-v`: [81 bytes](https://tio.run/##K/v/P82qQikxpUShQikppcSqmEtaKTklJV9aKbHAUdsQyAFSBtJh2VbF@UUlXCkpBikl2tlKSQEZFRVenhrSjpqqRibSVnqKSclcQLXZXkVW//8bmloZGygYmWpXVFgZGgEA) courtesy of [Aaroneous Miller](https://codegolf.stackexchange.com/users/101522/aaroneous-miller). As [user41805](https://codegolf.stackexchange.com/users/41805/user41805) pointed out [in chat](https://chat.stackexchange.com/transcript/message/59196532#59196532), using `bc` is most likely inferior to V's built-ins. ``` f:x"adt x"bdt:s <esc>"cddo<esc>"apA+1<esc>"cpA+0<esc>Vk:sort dd0dt+k"bPhxxJI(<esc>A)%24<esc>:.!bc "cpkJr: ``` [Try it online!](https://tio.run/##K/v/P82qQikxpUShQikppcSqmMsmtTjZTik5JSUfwkoscNQ2hAoCmQZgZli2VXF@UQlXSopBSol2tlJSQEZFhZenBljSUVPVyATMstJTTErmAurL9iqy@v/f0NTK2EDByFS7osLK0Oi/bhkA "V (vim) – Try It Online"), [Test it online!](https://tio.run/##XY/dasJAEIXv8xTTRY0iMbsb0@qigkgFpdBCaW@sF5qNKEoiZpXQ2mdPZ5L4Q3NzJvPNOTP7nayzbB0uNDgBCO7DAFpBrMOW2cTQ68Hz69haqZQttIGULbVRidULk2DAAq3jolrsh01RNrHkefm5VUl8MJbWXJvmli3f1mk6ndRzOGxUZTuvVOthGVjo204PyqJtlgkTA/UG/FiA3yba91lFMAhTKiTLu/vDJjIrsKuJDayCM4wORz0aujyfiY8GDXU33hv35J7u3uWs7mbBScE5gRy4Ojy50XG3axQ7ZpiMGQz6WOB2BnOo1a6rZ@8fo9EcbDifb73xcPKCvX83gjOAavIVXW8tgq3f8rG2rzwf0lS1fZt@UEogukpIIkIgkZz06hE@iCYyj1yPJBeXVB4vmCAm2qQl7CjZBS9n0s5nUUvWJh8l8vwOlBJIT/ldIpzu4CSXXTQG0r8FPt0FYjovfB1CHmmW/QE) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~144~~ 143 bytes ``` n;h;m;o;x,y;f(t,p)char*p,*t;{x=sscanf(p,"%d+xx:%d"+y*3,(y=*p>58)?&m:&o,&m);sscanf(t,"%d:%d",&h,&n);printf("%d:%02d",(h+(y?x:o+1)-(n<m))%24,m);} ``` [Try it online!](https://tio.run/##dZL9aoMwFMX/71MEQUk0ZRp1a5N@PMg2RrGxClNDDcyu9NXnkhht1zIRPF5Pfif3mmx@yLK@r1nBKtawDp9YDiUWKCt2R19gX7Jzt27bbFfnUGDH3QddR929E5z8GMPT2hebdIG2XkW9BnsVYtYrtVcbsVdgr0ZMHMta5tBUQ6LqsAjgadvRJojQHNarCiGXJFghLr2ygmpX1hCB8wyoy2wHSN7K9kO@voM1ODspjVMHAyda0ohokdJoKBAah1osKFnqZ2LfSUxTU4hSXbmwB7awbNVkYlhKRJFZohu3gVoOUbGRxDqHFCVCs4Sk9uufIN4Jnkm@n7oYgkhog57HlOTaztjfEBBafvRyA8@bI4B6bmW9551Ch8zKFWjLb97kcExGT7bgTxUGgsC4x4HfDEaxxsEbyzu7c4jJIR4c029vgbrnG6A2LjEQ6GoZDtw9lCvoNKr/qAC6LXqrFZNbwGV26X@y/HN3aPv51y8 "C (gcc) – Try It Online") *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* [Answer] # [Python 2](https://docs.python.org/2/), ~~83~~ 65 bytes ``` a,b=input();print(eval(b[:-5]+a[:-3])+(a[-2:]>=b[-2:]))%24,b[-2:] ``` [Try it online!](https://tio.run/##JcZBCoAgEADAr4QQKCrkmhfDPiIeFIKEMAkLe71FnWbyXdY9QWueBRNTPgsmUz5iKni5/IaD1Vw56l@kIxR7y0G72YRPQnoY2f/WLBJKywGxDoGitWoByD0 "Python 2 – Try It Online") pretty simple Thanks @caird for changing language and saving 18 bytes! (That's a lot of bytes!) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ≔⪪S:θ≔⪪S:ηI﹪⁺¬›⊟θ§η¹Σ⁺§η⁰⊟θ²⁴:⊟η ``` [Try it online!](https://tio.run/##hY3BCoMwEETv/YrgaQMWbOvJnqSH4qFF8AuCBiOkSUw2xb9P14rQWy8zy8xbplfC91bolOoQptFA5/SE0BgXsUM/mRF4zrIqI5359fCfUkS1FCHcREB42CFqC62OAZ4W4e6lQOmhtQ5mwmtszCAXUDk7cU5BF18b/dMUlG8PX@Rcku0r6@p@r4yiKqWyuhRsWUjT8a0/ "Charcoal – Try It Online") Link is to verbose version of code. Could output in `HH:mm` format at a cost of 4 bytes. Explanation: ``` ≔⪪S:θ ``` Input the local time and split on `:`. ``` ≔⪪S:η ``` Input the party time and split on `:`. This means that the hours still contains the `xx`. ``` I﹪⁺¬›⊟θ§η¹Σ⁺§η⁰⊟θ²⁴ ``` Compare the two sets of minutes. Concatenate the party hours with the local time, resulting in something like `1+xx5`. Because it contains non-digit characters, taking its sum actually extracts all of the embedded integers and sums those, giving us the resulting local hour (after the potential minutes adjustment). ``` :⊟η ``` Output the `:` and party minutes. ]
[Question] [ The \$d\$-dimensional vector space \$\mathbb{F}\_2^d\$ over the field with two elements \$\mathbb{F}\_2\$ is the set of vectors of \$d\$ bits. Addition of vectors is bitwise xor. A linear dependence is a set of vectors whose total (xor them all together) is \$0\$. Every set of \$d+1\$ vectors in \$\mathbb{F}\_2^d\$ contains a linear dependence. We will represent the elements of \$\mathbb{F}\_2^d\$ as the integers \$0\$ through \$2^{d}-1\$ using the binary expansion. ## Task Input: a positive integer \$d\$ and a list of \$d+1\$ positive integers between \$1\$ and \$2^{d}-1\$. You may assume that the list is sorted and you may assume that the entries are distinct. Output: A nonempty subset of the \$d+1\$ numbers whose bitwise xor is zero. ## Scoring: This is code golf so shortest answer in bytes wins. ## Examples: ``` Input: (3, [1,3,4,7]) Output: [3, 4, 7] ``` In binary, these are 001, 011, 100, and 111. We see that 100 xor 011 xor 111 = 000. In this case this is the only solution, so we must output [3, 4, 7]. ## Test cases: ``` Input: (3, [1,3,4,7]) Output: [3, 4, 7] Input: (4, [1, 2, 6, 10, 30]) Output: Behavior undetermined because 30 > 15 = 2^4 - 1. Input: (5, [3, 5, 6, 9, 14]) Output: [3, 5, 6] Input: (5, [4, 8, 10, 12, 14]) Output: [4, 8, 12] or [4, 10, 14], or [8, 10, 12, 14]. Input: (6, [4, 15, 17, 21, 49, 51, 57]) Output: [4, 17, 21] Input: (6, [1, 7, 8, 15, 39, 55, 57]) Output: [7, 8, 15] or [1, 15, 55, 57] or [1, 7, 8, 55, 57] Input: (6, [13, 14, 24, 33, 35, 36, 63]) Output: [13, 14, 24, 36, 63] Input: (6, [10, 11, 25, 28, 40, 59, 62]) Output: [10, 25, 40, 59] or [10, 28, 40, 62], or [25, 28, 59, 62] Input: (6, [1, 3, 5, 11, 19, 32, 63]) Output: [1, 3, 5, 11, 19, 32, 63] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒPḊ^/ÞḢ ``` A monadic Link accepting the list of distinct integers representing the vectors which yields a subset representing the linear dependence. (May be employed as a dyadic Link also accepting the number of dimensions on the right.) **[Try it online!](https://tio.run/##y0rNyan8///opICHO7ri9A/Pe7hj0f///6MNjXUUDE10FIyA2BjINjYFYjMdBTPj2P9mAA "Jelly – Try It Online")** ### How? ``` ŒPḊ^/ÞḢ - Link: list of distinct integers e.g. [1,3,4,7] ŒP - power-set [[],[1],[3],[4],[7],[1,3],[1,4],[1,7],[3,4],[3,7],[4,7],[1,3,4],[1,3,7],[1,4,7],[3,4,7],[1,3,4,7]],[3,4,7],[1,3,4,7]] Ḋ - dequeue [[1],[3],[4],[7],[1,3],[1,4],[1,7],[3,4],[3,7],[4,7],[1,3,4],[1,3,7],[1,4,7],[3,4,7],[1,3,4,7]],[3,4,7],[1,3,4,7]] Þ - sort by: / - reduce by: ^ - XOR ( [1,3,4,7,2,5,6,7,4,3,6,5,2,0,1] ) - } [[3,4,7],[1],[1,3,4,7],[1,3],[1,4,7],[3],[4,7],[4],[3,7],[1,4],[1,3,7],[1,7],[1,3,4],7,[3,4]] Ḣ - head [3,4,7] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes ``` {first {![+^] $_},.combinations(1..$_)} ``` [Try it online!](https://tio.run/##ZY/bCsIwEETf/YoViiiGYu6Klx8ptVSxULCttH0ppd8eJwS8PizJzp6ZTR639m5cNdCioKMbi7LtehrnyfqcUpRNLL421aWs875s6m7J4zjKVpPr8oEKOnCSpMie9rMgJJKRZmQY7Rhxlb50xWgLZYMSfxMOC7eMBGekYNQ4tX0jaG3wA5Qe0D@A9JkIQEncpefwCCM/GL8bSQIzgSyFXiPLiK9F4QMe5BhKEULcEw "Perl 6 – Try It Online") Returns the first combination of the input that is zero when reduced XOR. I wish `{![+^] $_}` could be changed to `!*.&[+^]`. [Answer] # Pyth, 6 bytes ``` hxFDty ``` [Try it online!](https://tio.run/##K6gsyfj/P6PCzaWk8v//aEMdBXMdBQsdBUNTHQVjSx0FUyBtah4LAA "Pyth – Try It Online") To explain, back to front: * `y` generates all subsets of the input. * `t` (tail) removes the first, empty subset. * `D` means order by the following function: * `F` means reduce on: * `x` is the xor function. * `h` (head) takes the first element of the sorted list. The lists that xor to 0 will be sorted to the front. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æ¦.Δ.»^> ``` **[Try it online!](https://tio.run/##yy9OTMpM/f//8LJDy/TOTdE7tDvO7v//aENjHQVDEx0FIyA2BrKNTYHYTEfBzDgWAA "05AB1E – Try It Online")** ### How? ``` æ¦.Δ.»^> - implicitly take input æ - power-set ¦ - tail .Δ - keep first which is 1 under: .» - reduce by: ^ - XOR > - increment - implicit print ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 74 bytes ``` f=lambda a,s=[],v=0:s*(v<1)or a and(f(n:=a[1:],s+a[:1],v^a[0])or f(n,s,v)) ``` **[Try it online!](https://tio.run/##FYpRCsIwEESvks@N7kfjapFgThIibKnFQk1DEgOePm4HHgwzL/3qe490T7n3xW38mWZWjMX5gM0NtpygPYzes5I5zrBAtI69sQHLmb01oj3ZD@FQ5MSCTeue8hqryK/GG6wxfStoSfeGUJkrqotA0ukmjKhGCn8 "Python 3.8 (pre-release) – Try It Online")** [Answer] # [Haskell](https://www.haskell.org/), 79 bytes ``` import Data.Bits p[a]=[[a]] p(a:b)=map(a:)(p b)++p b filter((1>).foldl xor 0).p ``` [Try it online!](https://tio.run/##FcaxDsIgEADQna@4wQHShljdSHAwLn4DYbjGEokHXOgN/j3W5eW9cf9sRGPkwq0LPFDQ3rPsigNGHw6iYo1uNb7gP0YzrGaaDlXyKZNsXevlZmxq9CL4tg5nY3kUzNVzz1VOKSzzZb6Cc/CsEscP "Haskell – Try It Online") Defines the power set (ignoring the empty set) as `p`, then our solution is: ``` filter((1>).foldl xor 0).p ``` Or in english: > > Get the power set and then select all the members whose xor sum is less than 1 (i.e. zero). > > > [Answer] # JavaScript (ES6), ~~84 60~~ 58 bytes [Ignores \$d\$](https://codegolf.meta.stackexchange.com/a/12442/58563). Returns \$0\$ if there's no solution. ``` f=([v,...a],x,o=[])=>x<1?o:v?f(a,x,o)||f(a,x^v,[...o,v]):0 ``` [Try it online!](https://tio.run/##dY9BDoIwEEX3nqJLmoyEthSUiByE1ISgGA2hRkzDgrvjL7gTFk2n7ftvps/KVX39frw@@85eb9PU5EHpKAzDytBANi8Nz8/DSRQ2c0UTVP6Sj@NcXRyVIC05w7Noqm3X2/YWtvYeNEEpiCliMbHUcL77f5TEEmIiAhatEMjqmTgCilcAmA9LXshtREAiUnRDxxgqjV1vTJQuRiSUJ/UWqXw7KLEUauUDGDRRa7Cfz/8WkIQ9xlnDnsj1GZZv@4QApeRPO30B "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [v, // v = next value from the input set ...a], // a[] = array of remaining values x, // x = 'XOR total', initially undefined o = [] // o[] = output subset ) => // x < 1 ? // if x is defined and equal to 0: o // success: return o[] : // else: v ? // if v is defined: f(a, x, o) || // try a recursive call where v is ignored f(a, x ^ v, [...o, v]) // try a recursive call where v is used : // else: 0 // failed ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` f=->a{(1..a.size).map{|x|a.combination(x).map{|x|return x if x.reduce(:^)<1}}} ``` [Try it online!](https://tio.run/##bY9dC4IwFIbv@xW7nLBG@9KK6o9EwbQJglmsBCv97fYuI7C6GNvO@5znbL5Ob32fr6cb@6CCc8svxd1F/GjPj7ZpLc9Ox7So7LU4VbT51L271r4iDSly0nDvDnXm6HIfrUTXdf2Z5jyzZUm3ghHFiGYk2UXRZFSXjMSMiBmI2ThEh3mFC@R6nEE1H7qE/JsKtIoEeozQEBjs5nd6MngAqwCZP5AKfoiwFM4qsHhUrL648JbwH@QSTo27gTOWP0OHjwVYAFDyLeuf "Ruby – Try It Online") :^) Probably golfable. [Answer] # [J](http://jsoftware.com/), 36 bytes ``` 0-.~1{ ::0[:(#~0=XOR/"1)]#~2#:@i.@^# ``` [Try it online!](https://tio.run/##dY@xigIxEIZ7n@LDLVbhsmYyya4bEATBShCsBNFGTu6uuQc42Fffm8XCJhZThO/L/PP/jPOmfrDJ1HzgyTauYXc67EfvmkH@yNlf8qIa/OZ8PK3msrxWQ6jy9rvZ3qpxOWP2ef/65YGgRLrns3bO1S8SaBGP@gJVktEeiQUYWU8fJbzDkpCOIMSeJKRyfjetSag56Y2jlkCIqKJmtrRa0uwWq5MIa6In9bShmDi1MlN61Mrr@A8 "J – Try It Online") [Answer] # Mathematica, 61 bytes ``` f[d_,l_]:=NullSpace[IntegerDigits[#,2,d]&/@l,Modulus->2][[1]] ``` This gives a bitmask (well a list of zeros and ones) of which elements of the list are in the set, as was allowed by the OP. [Answer] # Mathematica, 38 bytes ``` Select[Rest@Subsets@#,BitXor@@#==0&]& ``` Returns the list of solutions or an empty list if no solutions exist. [Try it online!](https://tio.run/##VY5NC8IgGMfvfQphsJOHqXOrgyB9gmiXQDys4WrQCjY7RZ/d/ubo5SD6/F9@j2Prz25s/dC1IfSqcRfXebN3s9fN/Tg7P@uMbgd/uE1aZ0oVuc3DSe2m4epNbzJr89XJPBglgpKSkvppl5lTUlHCCjhFEpGQb3EDvUwaKuuUYvxPZYiyGhigShQkbvml16mHkIim/DFF5KCII/AWMYOllVj8uCv@DzoHo8Qswaj4B54@GkMMhuCpHF4 "Wolfram Language (Mathematica) – Try It Online") [Answer] # x86 machine code, 27 bytes ``` 578B7C240831C04031D231C90FA3C8730333148F67E2F575EE5FC3 ``` Iterating through bit masks and XORing together the items as selected by the mask. In MASM-format assembly: ``` _lindep PROC push edi mov edi, [esp + 8] xor eax, eax _loop: inc eax xor edx, edx xor ecx, ecx _inner: bt eax, ecx jnc _skip xor edx, [edi + 4 * ecx] _skip: byte 67h loop _inner jnz _loop pop edi ret _lindep ENDP ``` It's a cdecl function, not stdcall. There is an odd requirement: the input array must be padded to 65536 items long, but only 32 items are actually used. That's because I used a 16-bit `loop` and relied it on it wrapping from 0 to 65535, The padding has to exist in order to make the program not die with an access violation. Using `loop` this way, in addition to gaining the benefit from it being small, means the zero flag is not modified between the `xor` and the `jnz` of the outer loop. Almost any other construct would need an extra instruction just to re-test whether `edx` is zero, except using `lea` to increment the loop counter and `bt ecx, 5` to stop when it hits 32, which is bigger. Driver program in case you want to run it: ``` #include <iostream> extern "C" int lindep(int* vecs, int d); int vecs[65536] = { 1, 3, 4, 7 }; int main() { std::cout << lindep(vecs, 3) << "\n"; } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` IΦEX²LθΦθ﹪÷ιX²μ²∧ι⬤↨⌈責﹪Σ÷ιX²μ² ``` [Try it online!](https://tio.run/##dYzBCsIwEER/ZY8bWA@tlCqeqiIIVgoeSw@hCTaQJrZNq38fEyje3MPssjPz2o6PreXa@2pUxuGJTw4vSjs5YslfWNl3uFKCmzRP1@HAGMHqDwSlFbO2eDXurBYlJCqCX6WP2ZRFLYyIVqE1HvkkA/qj@rkPuJgguFuHK@sR3n95KzDOwfu6Tghygh1BkhFs9wRZ2FneNH6z6C8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs all matches. Explanation: ``` ² Literal 2 X Raised to power θ Input array L Length E Map over implicit range θ Input array Φ Filtered where nonzero ι Outer index ÷ Integer divide by ² Literal 2 X Raised to power μ Inner index ﹪ Modulo ² Literal 2 Φ Filter powerset where ι Current subset (is not empty) ∧ Logical And θ Input array ⌈ Maximum ↨ Convert to base ² Literal 2 ⬤ Has all values where ι Current powerset ÷ Vectorised integer divide by ² Literal 2 X Raised to power μ Inner index Σ Sum ﹪ Modulo ² Literal 2 ¬ Is zero I Cast to string Implicitly print ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 16 bytes ``` peR@{{$$}r[n!}fe ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/IDXIobpaRaW2KDpPsTYNKGKiUG1ooGBoqGBkqmBkoWBioGBqqWBmVAsA "Burlesque – Try It Online") Takes arguments as `d {1 2 3 4...}` ``` pe # Read vals and push to stack R@ # Generate all subsets { {$$}r[ # Reduce by xor n! # Boolean not }fe # Find first element ``` ]
[Question] [ ## Task The prepend,append-Sequence is defined recursively, like this * a(1) = 1 * a(n) = a(n-1).n , if n is even * a(n) = n.a(n-1) , if n is odd where the . represents an integer concatenation. So the first few terms are: `1,12,312,3124,53124,531246,7531246,...` This is [A053064](http://oeis.org/A053064). Your task is, given an integer **a > 0** to return **n**, such that the **n**th element in the prepend,append-Sequence is equal to **a** and if no such **n** exists return 0, a negative number or error out etc. ## Rules * Input can be taken as an integer, string, list of characters/digits etc. * Output can be printed to STDOUT or returned (integer, string etc. is fine) * On invalid input & in the case no such **n** exists your program may do anything but return a positive integer (eg. loop forever, return 0 etc.) * You may choose to use 0-indexing, but then the output in case no **n** exists cannot be 0 ## Test cases ``` 1 -> 1 12 -> 2 21 -> 0 123 -> 0 312 -> 3 213 -> 0 211917151311975312468101214161820 -> 21 2119171513119753102468101214161820 -> 0 333129272523211917151311975312468101214161820222426283031 -> 0 999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100 -> 100 ``` [Answer] ## JavaScript (ES6), 40 bytes Takes input as a string. Throws a recursion error if no index is found. ``` f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k) ``` ### Demo ``` f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k) console.log(f('1')) // 1 console.log(f('12')) // 2 console.log(f('312')) // 3 console.log(f('211917151311975312468101214161820')) // 21 console.log(f('999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100')) // 100 ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 83, 80, 60 59 bytes ``` n=>{int i=0;for(var t="";t!=n;)t=++i%2<1?t+i:i+t;return i;} ``` [Try it online!](https://tio.run/##jVDLattQFNz7K24NARunyT3vc6IoXRS6alZddG1U1VxIJCpdB4Lxt7uCbmva3cA8mJlu/tiNU385zmU4pG/vc@1fm1X3sp/n9Ou0muu@li69jeVHet6XYbM9rb4ch@5xrtNiuE1lqE/p0F6G9um04FTa3Pwcp83bfkq1Xa@b@qEdmm1td7tyg4/wqe7KQ9nVZurrcRpSac6XZvV5HObxpb/7PpXafy1Dvzls1gS43m6vkAgQYCBACzBZtKwOGRAYFBzzdStcpyLCQoICPNxcnBwszEyMDDTUVJQUJMREhAQ42FiYGCjISIiWKoGGgvTPjojIqOiUCYlJyTkzMrOySxYUFhXXrKisqm7Z0NjU3LOjs6t75MDg0FiS/4y@v/@/x/JfLzufL78B "C# (.NET Core) – Try It Online") Takes the input as a string into a lambda function. 1-indexed. Returns the index of the value for truthy, or infitnitely loops for a "falsey" [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes *-1 byte thanks to [@EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).* ``` f=lambda x,i='1',j=2:i!=`x`and f(x,[i+`j`,`j`+i][j%2],j+1)or~-j ``` [Try it online!](https://tio.run/##DcqxCoAgEADQX7EhTLwGbQv8khA0JLqjTMLAln7dHN720pv3K@paN3P4cw2eFUDDFQcyesbOuOJ8DGwbCiwoHTloJNqFem2BpBLX/Y1U040xt4YxPXkQok5K/w "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 64 bytes ***-18 bytes thanks to [@officialaimm](https://codegolf.stackexchange.com/users/59523/officialaimm), because I didn't notice erroring out was allowed!*** ``` x,i,j=input(),'1',1 while i!=x:j+=1;i=[i+`j`,`j`+i][j%2] print j ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/v0InUyfLNjOvoLREQ1NH3VBdx5CrPCMzJ1UhU9G2wipL29bQOtM2OlM7IStBB4i1M2Ojs1SNYrkKijLzShSy/v9XNzI2UQcA "Python 2 – Try It Online")** # [Python 2](https://docs.python.org/2/), 82 bytes (does not loop forever) This one returns `0` for invalid inputs. ``` def f(n,t="",i=1): while len(t)<len(n):t=[t+`i`,`i`+t][i%2];i+=1 print(n==t)*~-i ``` **[Try it online!](https://tio.run/##nU3LSgNBELzvVyyCsGsiTL@7o/sX3kIwghsyEMYQJgQv/vq60WMOgod60FRVHz/r/qPgNL2Pu3bXlWUd7u6WeYB@1bSXfT6M7WEsXe2fr1L6VR3WdbHN2@WMRd2s8z1unvJigKY9nnKpXRmG2j98Pebpt/5yOo@rXXd6u7zmcjzXru8naAAbvDI19GNpBgQYCNBsTOYzq0MCBAYFx3SbSDcRorkXaChIfw4iIqOiUyJoIsJCggI83FycHCzMTIwMNNRUlBQkxESEBDjYWJgYKMhI/vsbiUnJOTEys7JLEhQWFdekqKyqbsnQ2NTck6Ozq3ukwODQmJfTNw "Python 2 – Try It Online")** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Rs2ZU1¦ẎVµ€i ``` [Try it online!](https://tio.run/##y0rNyan8/z@o2Cgq1PDQsoe7@sIObX3UtCbz////hkYA "Jelly – Try It Online") Explanation: ``` Rs2ZU1¦ẎVµ€i µ€ Eval this link for each (automatic [1..n] range) R Range s2 Split in pieces of: 2 Z Zip U1¦ Only keep index: 1 of: Vectorized reverse Ẏ Flatten 1-deep V Concatenate string versions and eval i Find index of y in x (y = implicit input) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` $vDNÌNFs}«})Ik ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fpczF73CPn1tx7aHVtZqe2f//GxkaWhqaG5oaGgMZ5qbGhkYmZhaGBoZGhiaGZoYWRgYA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##nU09akJhEOzfKYJdwGJ3Z2d/rCWlXcA2gpVlQAjEG@QmHkLwHezlS1qLQIoZhmF@hG8HPS6fZ/3Yvi7n7W7@2r28X@7Xy/P@tOxX823zNN9W60Untcl@GBN@JQa0NZWKIZLD9igVNXUNLZPHhDxEgNFrS6Phz0EzcwsrCHTq7mw2Wqsri4XS7MxkIjU6MhgIZTNJgurt6XS4opHgf78NjkC5uLl7eFFodAYrJCw8IiolLT0jq6SsvKKqpa29o8eyfAM) **Explanation** *0-indexed*. Returns **-1** if the input is not in the sequence. ``` $ # push 1 and input v # for each y,N (element, index) in input do: D # duplicate top of stack NÌ # push N+2 NF } # N times do: s # swap the top 2 elements on the stack « # concatenate the top 2 elements on the stack }) # end loop and wrap in a list Ik # get the index of the input in this list ``` [Answer] # [R](https://www.r-project.org/), 73 bytes ``` p=paste0;n=scan(,'');l='';while(l!=n){F=F+1;l="if"(F%%2,p(F,l),p(l,F))};F ``` Reads from stdin and returns the value of the index (implicitly printed). Infinite loops when the value isn't in the sequence. `F` is by default `FALSE` which is cast to `0` when used in arithmetic. [Try it online!](https://tio.run/##K/r/v8C2ILG4JNXAOs@2ODkxT0NHXV3TOsdWXd26PCMzJ1UjR9E2T7PazdZN2xAorJSZpqThpqpqpFOg4aaTowmkcnTcNDVrrd3@Gxsa/QcA "R – Try It Online") [Answer] ## Haskell, ~~75~~ ~~71~~ 57 bytes ``` f n=[i|i<-[1..],(show=<<reverse[1,3..i]++[2,4..i])==n]!!0 ``` Takes `n` as a string. [Try it online!](https://tio.run/##FcZLDsIgFAXQrbw2DjSlhAv0YwIrIQw6oCmxogFTJ@4d9YzOtpRb2PdaV0rWxU80vQPnnp3L9nhbY3I4Qi7BgSnOo@86J5n@72Jt8k0j6n2JiSw9c0wvOtFKrQSumDBA/TINClKPMwQkNEbMUrT1Cw "Haskell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ 15 bytes ``` £moiṁsṁṠehGJC2N ``` [Try it online!](https://tio.run/##yygtzv7//9Di3PzMhzsbi4H44c4FqRnuXs5Gfv///zcyNLQ0NDc0NTQGMsxNjQ2NTMwsDA0MjQxNDM0MLYwMAA "Husk – Try It Online") 1-indexed. Returns 0 if not in the sequence. -2 bytes from Leo, `GJ`! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 12 bytes ``` ɾɖ≬wJṘyRYvṅḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBIiwiIiwiyb7JluKJrHdK4bmYeVJZduG5heG4nyIsIiIsIjFcbjEyXG4yMVxuMTIzXG4zMTJcbjIxM1xuMjExOTE3MTUxMzExOTc1MzEyNDY4MTAxMjE0MTYxODIwXG4yMTE5MTcxNTEzMTE5NzUzMTAyNDY4MTAxMjE0MTYxODIwXG4zMzMxMjkyNzI1MjMyMTE5MTcxNTEzMTE5NzUzMTI0NjgxMDEyMTQxNjE4MjAyMjI0MjYyODMwMzFcbjk5OTc5NTkzOTE4OTg3ODU4MzgxNzk3Nzc1NzM3MTY5Njc2NTYzNjE1OTU3NTU1MzUxNDk0NzQ1NDM0MTM5MzczNTMzMzEyOTI3MjUyMzIxMTkxNzE1MTMxMTk3NTMxMjQ2ODEwMTIxNDE2MTgyMDIyMjQyNjI4MzAzMjM0MzYzODQwNDI0NDQ2NDg1MDUyNTQ1NjU4NjA2MjY0NjY2ODcwNzI3NDc2Nzg4MDgyODQ4Njg4OTA5Mjk0OTY5ODEwMCJd) Uses 0-indexing, outputs -1 for invalid. ``` ḟ # Find index of input in... ɖ # Scan ɾ # range(1, input) ≬--- # by wJ # Concatenate Ṙ # Reverse yRY # Reverse every other element vṅ # Concatenate each list into a number ``` [Answer] # Mathematica, 135 bytes ``` s=t={};x=1;While[x<5!,{s~AppendTo~#&,s~PrependTo~#&}[[x~Mod~2+1]]@x;AppendTo[t,FromDigits@Flatten[IntegerDigits/@s]];x++];t~Position~#& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19 18~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +ḂḶṚm2;RḤ$ṁµ€Vi ``` A monadic link taking and returning integers. **[Try it online!](https://tio.run/##ASkA1v9qZWxsef//K@G4guG4tuG5mm0yO1LhuKQk4bmBwrXigqxWaf///zMxMg "Jelly – Try It Online")** (very slow - takes ~50s on TIO just to confirm that `3124` is at index `4`) For a much faster version use the [previous 18 byter](https://tio.run/##y0rNyan8/1/74Y6mhzu2Pdw5K9fIOujhjiUqD3c2crn4HG5/1LQmLPP///9GhoaWhuaGpobGQIa5qbGhkYmZhaGBoZGhiaGZoYWRAQA "Jelly – Try It Online") (only checks up to the length of the input, which is sufficient). ### How? ``` +ḂḶṚm2;RḤ$ṁµ€Vi - Link: number, v µ€ - perform the monadic link to the left for €ach k in [1,2,3,...v] - (v can be big, lots of k values makes it slow!) Ḃ - modulo k by 2 = 1 if odd 0 if even + - add to k = k+isOdd(k) Ḷ - lowered range = [0,1,2,...,k+isOdd(k)] Ṛ - reverse = [k+isOdd(k),...,2,1,0]) m2 - modulo slice by 2 = [k+isOdd(k),k+isOdd(k)-2,...,3,1] $ - last two links as a monad: R - range(k) = [1,2,3,...,k] Ḥ - double = [2,4,6,...,2k] ; - concatenate = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,2k] ṁ - mould like range(k) = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,k-isOdd(k)] - (this is a list of the integers to be concatenated for index k) V - evaluate as Jelly code (yields a list of the concatenated integers) i - first index of v in that (or 0 if not found) ``` [Answer] # [Swift 4](https://developer.apple.com/swift/), 92 bytes This loops infinitely for invalid cases, so I didn't include them in the testing link. ``` func f(x:String){var i="1",j=1;while i != x{j+=1;i=[i+String(j),String(j)+i][j%2]};print(j)} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/5988a150357207286768e0b3)** Amusingly, it is longer with a closure: ``` var f:(String)->Int={var i="1",j=1;while i != $0{j+=1;i=[i+String(j),String(j)+i][j%2]};return j} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/5988a323357207286768e0b6)** [Answer] # [Haskell](https://www.haskell.org/), ~~115~~ 85 bytes ``` s=read.(show=<<) f 1=1 f x|odd x=s[x,f$x-1] f x=s[f$x-1,x] g x=[n|n<-[1..],x==f n]!!0 ``` [Try it online!](https://tio.run/##HchBCoMwEEDRvacYwUWFJDh2mzlJyCIQo6IdxRQ6C@@ept18eH8JeZv2vZRM1xSieeTl@JC1fZMACWvlPmIEoexEpU40@t@s/EOJb@ZKxzdb7dAYr4QoAfu2HcorrEzntfK7m@GJI2iNOJQv "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 54 + 1 (-n) = 55 bytes ``` $a=++$,%2?$,.$a:$a.$,while length$a<length;say/$a/&&$, ``` [Try it online!](https://tio.run/##JcxJasNQEEXRrWTw44llubpXTRqygixCAxEbhGxsQ8jm8yPI7MCFe51vC3pv0/t@34Zn@WjD2KaXNo1t@D6dl/lpmdevx6lNb/94vU8/xzYdd7s29F5VUSgtzspIpCZHRQRCg708HK7OKAQABVtZGEyNtTQUqspSEgJRYS4OBuuGwBbMk4mFjZ1TSERMXFJJRU1d08jEzNwSBIHBkU4ubu6eQSFh4ZFJKWnpmUUlZeW1nen3cn2cL@u9Hz4xElM/rH8 "Perl 5 – Try It Online") Returns nothing if not found. [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 bytes ``` @P=PiXv n X;¥P}a1 ``` [Try it online!](https://tio.run/##y0osKPn/3yHANiAzokwhTyHC@tDSgNpEw///lYwMDS0NzQ1NDY2BDHNTY0MjEzMLQwNDI0MTQzNDCyMDJQA "Japt – Try It Online") or [check (valid) test cases](https://tio.run/##hY1BSkRBEEOv8um1QldVkqpiGPAIfyMMiItZKiguxJ3H8SJzsW/jBdw8Qggvr9ePz@PxtJ/HOB728/5y@dret8vp9rN/X@04noaNu2G@EH90s7Y0WqyQXCVUNs0NJiufa9Pd2exoq64sVpRlZyYz0tRKUSFjM0kGDY0EEbDoyGDEEren0@PfR3eHyytmeCAUhQkHIBQnnaBYmnJBUuVMT6SyapYXSlU92xutXuY5nrf7t18 "Japt – Try It Online") Takes input as a string or integer. On invalid input, continues "forever" looking for a solution (thus why I didn't include them in the test cases). Explanation: ``` @P=PiXv n X;¥P}a1 # Implicitly start with P = "" @ }a1 # Repeat the function for each integer X > 0 until one returns true P=Pi X # Insert X into P at index: Xv # X is divisible by 2? n # Times -1 ;¥P # Return whether P now equals the input # Implicitly output the last value of X ``` The "insert at index" portion might be a bit confusing, so I'll add more detail here. In Japt, `NvD` is a function which returns 1 if N is divisible by D, and 0 otherwise. If D is not provided, it defaults to 2. Thus `Xv` here is equal to 1 if X is even, and 0 if X is odd. `NnD` is a function that returns `D - N`. If D is not provided it defaults to 0, effectively returning `-N`. In this program, that results in -1 if X is even, and still 0 if X is odd. Finally, in Japt indexing negative numbers count from the end of a string or array. Thus the segment `PiXv n X` evaluates to `Pi0 X` if X is odd, prepending X, but it evaluates to `Pi-1 X` if X is even, appending it instead. ]
[Question] [ The goal of this challenge is to write a program where the length of the following three are exactly the same: * the length of the source code * the length of the output it prints to the standard output * the length of the compiler warnings it generates with the (unmodded) compiler of your choice **The winner is the shortest code to fulfill all three criteria, and has to be at least 1 character long.** To spice things up, if the output has less than three different characters, it gets a **5 point penalty** added to the length for each one (so +10 if only a single type, +5 for two). (Newlines count either as 1 or 2 characters, your choice, but it has to be consistent through all three criteria. Leading and trailing white-spaces are ignored in all lines in all three criteria) In case of equal score, the one printing the most interesting result (instead of garbage) is the winner. [Answer] ## Bash, 23 characters Error: ``` bash: /: Is a directory ``` Source: ``` echo $0-$01234;/; ``` Output: ``` /bin/bash-/bin/bash1234 ``` ## Brainf\*ck, 32 characters This code executes for about 3 seconds and stops and displays the following error and output. Error: ``` bff: out of memory (-2058691272) ``` Source: ``` +++++[......-]..+[>>>>>>>>>>>>-] ``` Output: (Hexdump) ``` 0505 0505 0505 0404 0404 0404 0303 0303 0303 0202 0202 0202 0101 0101 0101 0000 ``` ## C, 35 characters Warning: ``` b.c:1:30: warning: division by zero ``` Source and Output: ``` main(){system("cat "__FILE__)/0;;;} ``` ## PHP, 50 characters Warning: ``` PHP Warning: Division by zero in /tmp/3 on line 1 ``` Source and Output: ``` <?php echo (0/0).''.file_get_contents(__FILE__);?> ``` [Answer] ## C - 48 chars ``` main(i){while(++i<49)putchar(i);putchar('\z');} ``` Note: includes a final (Unix-style) newline. Output from `gcc a.c` reads: ``` a.c:1:41: warning: unknown escape sequence '\z' ``` The output from `a.out` is mostly non-printing chars, so here's what it looks like after piping through hexdump: ``` 00000000: 0203 0405 0607 0809 0A0B 0C0D 0E0F 1011 ................ 00000010: 1213 1415 1617 1819 1A1B 1C1D 1E1F 2021 .............. ! 00000020: 2223 2425 2627 2829 2A2B 2C2D 2E2F 307A "#$%&'()*+,-./0z ``` [Answer] # JavaScript, 63 ~~66~~ ``` !function x(){console.log(x+'...');eval(Array(33).join('$'))}() ``` The output is: ``` function x(){console.log(x+'...');eval(Array(33).join('$'))}... ``` In Chrome, the error is: ``` ReferenceError: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ is not defined ``` [Answer] # Visual Basic .NET, 185 Gee, `vbc` is pretty verbose with its compilation warnings. Anyway, the code is this: ``` Public Module Main Public Sub Main() Console.WriteLine(New String("a"c,185)) End Sub Public Function A() 'This is actually just padding. 'Hi End Function End Module ``` (Note that they're supposed to be tabs, not spaces.) The output is this: ``` aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ``` And the compiler warning is this: ``` warning BC42105: Function 'A' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ ``` (This time, it's actually four spaces, not tabs.) [Answer] # [Zsh](https://www.zsh.org/), 20 bytes ``` <<< $-$_$_$_$_$_ [ ``` The problem we face here is alluded to in a comment above: Zsh prints the **program name** in addition to the line number before every error. The solution here uses a one-character filename to abuse this. [I've wrapped it up in a helper script to show exactly what it prints, and used `wc -c` on stderr, stdout, and the source file.](https://tio.run/##fZBBSwMxEIXv@RUPLEYPEeyxrHsRvXrRUwUJ2dEEdhOYSV0o/vfttNuKh9bJIfB475uXbCVOLQRNA/v08myBK7wJwUNS/uoJIXr2oRLDioUX1Ej4TD1lP9AdXmMSRGLqSsDIqdLsCKUj1PLrhkyN7gAWbvFxOmY96U5TeZODrwQncPdaRjswDeVbCexTr0WQadRbWVyGA9BsJap12aK9qaT82hEz2uvlLX5wVMqmGkMhlr0O@zCPnSWXYR9PrxOUfGSs8B7sPmDGABfQ/GH/k9RdZ5OqX0ymPH8OziRxGJWmHQ "Zsh – Try It Online") Output: `569Xcatcatcatcatcat` followed by a newline Errors: `s:[:2: ']' expected` followed by a newline --- EDIT: Alternate 20 byte solution with no file restriction: ``` <<<$-$-$-$-$_>&1 >&2 ``` [Try it online!](https://tio.run/##fZAxSwQxEIX7/IoHykWLCHelxDSHtjbaCRKyownsJpDJuXD439fZ21UsTidF4DHvmzdz5Dg5MKyFvn980MAFnpngwSm/94QQffWhUYVmDc9okfCWesp@oBs8xcSIVKkrAWNNjZaOUDpCKz/d4Mlae2nW9@o2W7jNbpKZqtVDDr4RDMNsJYxkqDSUDyFUn3oJgkyj/MKqZTgB1ZGjtO4c3FUj4beOap2Z1/jEqpRDU4pCLLMOfbeUXiSTofff2zFKXhm3eAl6NqgxwATYX@x/nDLrrFP0P50pL8fBGSdONd/oCw "Zsh – Try It Online") # [Zsh](https://www.zsh.org/), `zsh -x`, 10 bytes ``` <<<$_$_$_ ``` `-x` flag enables xtrace. This again requires a single-character filename. [Try it online!](https://tio.run/##fZAxSwQxEIX7/IoHitEigldK3Ea0tdFOkJAdTWA3gZmcK4f/fZ29PcXidFIEHu97b5KdpLmDwHvYu4d7C5zgSQgBksvbQIgpcIiNGFYsgqAlwmseqISRLvGYsiARU18jJs6NVkesPaHVHzdk9t6fvizHzNpkGm9LDI3gBO5KV9BmprG@K8chD1qPQpPemsB13MeYnSS4D3VvOnTnjTS49cSM7mxzgU8clLptxlBMddFhb9axq@QK7O33swS1HDKu8RztApgpwkX4X9n/kNp1lFT9TzKX9VdwhMR@VJq/AA "Zsh – Try It Online") # [Zsh](https://www.zsh.org/) `zsh -JNTwEDY`, 12 bytes ``` <<<$->&1 >&2 ``` Shortest `-flag` answer with no filename requirement. Sets more flags, and `$-` prints them all. [Try it online!](https://tio.run/##fZAxTwMxDIX3@xVPompgCFI7opCFloEBljIgsUQ5QyLdJVKcclLFfz98vYIYCl4sPfl7z/aBw2jBMAZq@3SvgAs8M8GBY3rvCD644nylAsUKjlED4S12lFxP19iFyAhUqM0eQ4mV5gmfW0LNP9Pg0Riz0Ha5gl2uR8lqatkn7ypBM/RKlpDsQn3@ELK42MkCSDRIF4@S@6NRc@AA/fC4G7abF2HWFvaykgTUlkqZzK/wiZOS97VpyIc86VC3c6lZ0gnq7vs8Rk4njxu8ejUBzeChPcwv739IyTpLiv4nGdP8HZwhcazpWV8 "Zsh – Try It Online") [Answer] # JavaScript (Firefox 54), 34 bytes ``` alert((f=function(x)1234)(56)+f+f) ``` Outputs: ``` 1234function(x)1234function(x)1234 ``` And it sends this warning to the browser console: ``` expression closures are deprecated ``` It looks like [this](https://i.stack.imgur.com/6al0m.png) in my copy of Firefox Developer Edition (54.0a2). It may work in other versions of Firefox as well. [Answer] ## Ruby, 48 characters ``` IO=1;puts ?a*48;# let's make it 48 bytes long :) ``` Outputs ``` aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ``` Warns ``` r.rb:1: warning: already initialized constant IO ``` (the file is r.rb, I removed the path, if you run it from irb, you'll get (irb):1: warning...) There is the warn method in Ruby, but it just outputs its arguments to $stderr, making it look less like a warning. [Answer] # Python, 57 bytes Other interpreters may display the warning differently. This was only tested to work on TIO. ``` from warnings import* print("prt"*19) warn("Warning...!") ``` [**Try it online**](https://tio.run/nexus/python2#@59WlJ@rUJ5YlJeZl16skJlbkF9UosVVUJSZV6KhVFBUoqRlaKnJBVKgoRQOUaanp6eopPn/PwA) **Output** ``` prtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprt ``` **Warning** ``` .code.tio:3: UserWarning: Warning...! warn("Warning...!") ``` Note that the leading spaces are not counted toward the byte count. If the leading spaces were not ignored, this could be done in 51 bytes. [Answer] # Javascript (ES6), ~~32~~ 30 bytes ``` Screen(console.log(Function)); ``` prints ``` ƒ Function() { [native code] } ``` in Chrome, and then throws ``` TypeError: Illegal constructor ``` ## My original 32 byte solution: ``` (x=y=>console.log(x+!0+10)||z)() ``` first, prints ``` y=>console.log(x+!0+10)||ztrue10 ``` And throws the error ``` ReferenceError: z is not defined ``` [Answer] ## VBA, 39 Bytes Not sure if this qualifies, given the compiler constraint, but: **Input:** (in the immediate window) ``` For i=1 To 39:a=a & Chr(i):Next:Print a ``` \*The output includes non-printing characters that don't play well in this window. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 10 bytes ``` dd say 1e9 ``` [Try it online!](https://tio.run/##K0gtyjH7/z8lRaE4sVLBMNXy/38A "Perl 6 – Try It Online") Prints `1000000000` to STDOUT, and `Bool::True` to STDERR. Both produce a trailing newline, but trailing whitespace is ignored in this challenge. `dd` is a Rakudo specific [debugging function](https://docs.perl6.org/programs/01-debugging#Dumper_function_dd) ]
[Question] [ Your task is to write a program \$p\$ which outputs a string \$s\$ with the same length as \$p\$, where \$s \neq p\$. If I remove the \$n\$th byte from your program to get program \$q\$, then either \$q\$ outputs \$s\$ with the \$n\$th byte removed, or it does something else. Your score is the number of ways a single byte being removed from \$p\$ results in a program that does "something else" or that has become a quine, with a lower score being the goal. Ties will be broken by code golf. *Note that the effective smallest byte count for an answer with score 0 is 2 bytes (not accounting for fractional byte systems).* [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 2 bytes, score 0 ``` .. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fT@//fwA "brainfuck – Try It Online") Outputs two null bytes. Removing either `.` leaves `.`, which outputs one null byte. ([Try it online!](https://tio.run/##SypKzMxLK03O/v9f7/9/AA "brainfuck – Try It Online")) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 4 bytes, score 0 ``` ¹--¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///QTl3dQzv//wcA "Charcoal – Try It Online") Explanation: `¹` on its own outputs a `-`, so the whole program outputs 4 `-`s. (I could have used any two ASCII characters in the middle; I just chose `-` to be confusing.) Removing any character results in a program that outputs 3 `-`s. I need both `¹`s to prevent the program from becoming a (trivial) quine, and I need two `-`s to prevent the `¹`s from being interpreted as `11` when they are adjacent. [Answer] # [R](https://www.r-project.org) [REPL](https://codegolf.meta.stackexchange.com/q/7842/95126)\*, ~~125~~ 90 bytes, score 0 \**(or any other R environment in which errors do not halt execution of subsequent commands: entering the program into the R interactive console works fine; alternatively (and as simulated in the ATO link) we can use the command-line option `-e 'options(error=function(){})'`, which would define the language as "`R -e 'options(error=function(){})'`".* ``` x=1;if(x)cat(strrep(x,9*(2)*5-(nchar(readLines(c=stdin(),n=1))<9*(2)))) cat(strrep(1,89))# ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFN4_yCksz8vGKN1KKi_CLbtNK8ZBBfQ7O6VlNBWaE4M7c0J7EkVSHINcBHoTi1pCQzL31paUmarsXNqApbQ-vMNI0KzeTEEo3ikqKi1AKNCh1LLQ0jTS1TXY285IzEIo2i1MQUn8y81GKNZNvikpRMoNE6ebaGmpo2YIVAwIWk3VDHwlJTUxliwwIoBaUB) The strategy here is to write a 2-line program. If the first line runs Ok, it uses the second line as input (and, as a side-effect, prevents the second line from running), and checks that it contains the expected number of characters: if it does, print string `s` (90 `1`s); if it doesn't, print string `s` without one character (all the characters are the same, so this is equivalent to removing the `n`th character for any `n`). The first line is written to error (and so do nothing) if any character is removed. In this case, the second line won't be used as input, and it will run: it always prints string `s` without 1 character. The length of the entire program is expressed as `9*(2)*5` (so removing any character will error). For a similar reason, the second line is adjusted to be 18 characters long, so we can check whether its length is less than `9*(2)`. --- # [R](https://www.r-project.org), 8 bytes, score 8 ``` cat(8^8) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhYrkhNLNCziLDQh3MVpGlDWggUQGgA) In principle, we could try to wrap the R+REPL program above into a `tryCatch()` expression to force it to run in base R, but this would already inflate the score to at least 10, and this trivial approach is both shorter and scores better (even though it's rather boring). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes, score 0 ``` ₴₴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLigrTigrQiLCIiLCIiXQ==) Prints 2 0s. Removing either print without newline prints only 1 0. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 2 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py), score: 0 ``` ⌂⌂ ``` Outputs `**`: [Try it online.](https://tio.run/##y00syUjPz0n7//9RTxMQ/f8PAA) If either `⌂` is removed, it'll only output a single `*`: [Try it online.](https://tio.run/##y00syUjPz0n7//9RT9P//wA) **Explanation:** ``` ⌂ # Push "*" to the stack ⌂ # Push "*" to the stack again # (after which the entire stack is joined together and output implicitly as result) ``` [Answer] # Score 0 All of these work by repeating one of following commands twice: * output the accumulator * print top of stack, when empty default to printing some value (usually 0) * push something to stack, and language implicitly outputs stack at end ## [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 2 bytes, score 0 ``` ## ``` [Try it online!](https://tio.run/##S03OSylITkzMKcop@P9fWfn/fwA "!@#$%^&*()_+ – Try It Online") ## [33](https://github.com/TheOnlyMrCat/33)/[Alphabetti spaghetti](https://github.com/stasoid/Alphabetti-spaghetti)/[Deadfish~](https://github.com/TryItOnline/deadfish-), 2 bytes, score 0 ``` oo ``` [Try it online! (33)](https://tio.run/##Mzb@/z8///9/AA "33 – Try It Online") [Try it online! (Deadfish~)](https://tio.run/##S0lNTEnLLM7Q/f8/P///fwA "Deadfish~ – Try It Online") [Try it online! (Alphabetti spaghetti)](https://tio.run/##S8wpyEhMSi0pydQtLkhMzwCx/v/Pz///HwA "Alphabetti spaghetti – Try It Online") ## [Aceto](https://github.com/aceto/aceto), 2 bytes, score 0 ``` pp ``` [Try it online!](https://tio.run/##S0xOLcn//7@g4P9/AA "Aceto – Try It Online") ## [Actually](https://github.com/Mego/Seriously), 2 bytes, score 0 ``` εε ``` [Try it online!](https://tio.run/##S0wuKU3Myan8///c1nNb//8HAA "Actually – Try It Online") ## [AlphaBeta](https://github.com/TryItOnline/alphabeta), 2 bytes, score 0 ``` MM ``` [Try it online!](https://tio.run/##S8wpyEhMSi1J/P/f1/f/fwA "AlphaBeta – Try It Online") ## [anyfix](https://github.com/alexander-liao/anyfix), 2 bytes, score 0 ``` ®® ``` [Try it online!](https://tio.run/##S8yrTMus@P//0LpD6/7/BwA "anyfix – Try It Online") --- # Score 1 All of these work the same way as the zero score solutions, but require an extra character to terminate the program ## [Ahead](https://github.com/ajc2/ahead)/[Backhand](https://github.com/GuyJoKing/Backhand), 3 bytes, score 1 ``` OO@ ``` [Try it online! (Ahead)](https://tio.run/##S8xITUz5/9/f3@H/fwA "Ahead – Try It Online") [Try it online! (Backhand)](https://tio.run/##S0pMzs5IzEv5/9/f3@H/fwA "Backhand – Try It Online") ## [axo](https://esolangs.org/wiki/Axo), 3 bytes, score 1 ``` {{\ ``` [Try it online!](https://tio.run/##S6zI//@/ujrm/38A "axo – Try It Online") ## [Hexagony](https://github.com/m-ender/hexagony), 3 bytes, score 1 ``` !!@ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/19R0eH/fwA "Hexagony – Try It Online") ]
[Question] [ Write the shortest program or function that will determine if an input is a valid Go type. ## Spec This challenge will use the following simplified subset of Go types. For more information, see the [Golang specification](https://go.dev/ref/spec#Types). * "Primitive" types: + `bool` + `int`,`uint`,`float(32|64)`,`complex(64|128)`,`byte`,`rune` + `string` * `*T` where `T` is any type * `[]T`, a slice of `T` * `[n]T`, an array of `T`, and `n` is some positive non-zero integer * `map[K]V`, where `K` and `V` are any type * `chan T` (note the required whitespace) * `struct{...}`, where `...` is a list of 0 or more semicolon-separated types (such as `struct{int;float64;*struct{int;bool}}`). * `func(args)return`, a function. + `args` is an optional comma-separated list of types. + `return` is optionally either a type, or a *non-empty* list of types in parentheses `(a,b,c)`. All truthy inputs have characters in the set `[][a-z0-9(){},;* \t\n]`. It is not guaranteed that an input that matches this regex is truthy. Whitespace is allowed everywhere within the type, as long as it does not break apart keywords (`struct`, `chan`, `map`, `func`) or primitive types. ## Test Cases ### Truthy ``` bool int complex128 *int *********int []string [][]int [ 10 ] [ ][123] * [567] [ ] [890 ] *rune map[int]string map[ []int ] [] string map[map[map[int]string]map[bool]chan map[int]int]struct{int;string;bool} struct{ } struct{int; float64; *struct{int;bool} } struct{struct{bool;struct{int; *[]chan complex128}; *float64}; map[string]string} func() func(int,uint,int,bool)string func(int,uint,int,bool)(string,string,string) func(func(int) int) func(func([]map[string]int) int) func(int) int chan chan chan chan chan chan int map[func() func() func()]func() func() func() chan []string func(int)(int) ``` ### Falsy ``` integer // unknown primitive float // unknown primitive imaginary // unknown primitive int* // * with no type [] // missing contained type []asdfghjkl // unknown type [[]]int // [] is invalid for array length [-1]string // negative ints are invalid for array length [123.456]float64 // floats are invalid for array length struct{int,float64} // missing semicolon between member types func(int)(int,string // missing closing paren struct{func(int)map[int]string // missing closing brace structfunc(int)map[int]string} // missing opening brace, unknown type chanint // missing required whitespace chan[]string // missing space whitespace func()() // non-empty parenthesized return type only [0]int // positive non-zero integers only func(int)(int)(iint) // dangling leftovers `(iint)` is not a type ``` [Answer] ## Regex (PCRE), 241 bytes ``` ^(bool|u?int|float(32|64)|complex(64|128)|byte|rune|string|&\s*(?1)|\*\s*(?1)|\[\s*\d*\s*\]\s*(?1)|map\s*\[\s*(?1)\s*\]\s*(?1)|chan (?1)|struct\s*\{\s*(|((?1);\s*)*\s*(?1)\s*;?\s*)\}|func\(\s*(((?1),\s*)*(?1),?\s*)?\)\s*(\s*(?1)|\((?6)\))?)$ ``` Fixed to handle `func()()` case [Try it on regex 101](https://regex101.com/r/vanW2f/1) [Answer] # [BNFC](https://bnfc.readthedocs.io/) + [Haskell](https://www.haskell.org) + [Bash](https://www.gnu.org/software/bash/) + coreutils, 175 + 96 = 271 bytes ``` bool" int" uint" float32" float64" complex64" complex128" byte" rune" string" *"T [""]"T ["Integer"]"T map""["T"]"T chan "T struct""{"[T]"}" Q QT Q"("[T2]")"Z2","Z";";_.T2::=T ``` Compile with ``` sed 's/Q/func""("[T2]")"/g;s/Z/;separator T/g'|awk '{print"A"NR".T::=\""$0";"}'>g;bnfc -m g;make ``` Produces an executable named `TestG` which accepts input from `stdin` and exits with code `0` if the parse was successfull, `1` otherwise. Possibly can be golfed more with a better use of sed and awk. --- Script to test it: ``` cat truthy falsy | sed "s|//.*||" | xargs -d "\n" -I {} sh -c 'echo "{}" | ./TestG >/dev/null ; echo $? "{}"' ``` [Answer] # [Raku](https://raku.org/), ~~205~~ 193 bytes ``` *~~/^$(/:s \s*[bool|u?int|float[32|64]|complex[64|128]|byte|rune|string|\*<~~>|\[ \d* \]<~~>|map \[<~~>\]<~~>|chan\s+<~~>|struct \{ <~~>*%\; \}|func \(<~~>*%\,\)[<~~>| \( <~~>*%\, \) ]?]\s*/)$/ ``` [Try it online!](https://tio.run/##dVJtU@JADP7ur8g4eLRrlQOxp/ZOfshujqnYIh60TF9mjmHLX8fNvtBWhZnuJk@ehOTZbJNiHR43O/iRwp8jOxxGfwfe6KkEUTL@kudrWc9WWSXTdR5X/G4iwynKRb7ZrpP/PJzK8eQB5cuuSmRRZ4ksq2KVLaVgvw@HZyn4hXhlIFB7m3gLgpNpgcVbnInyWtsqsV5UIPZALrsSEYhGpnW2AOFZKBC@TpcXwnO0AIQPOEPV7sgfjI4RlPEOLvez1BvM/eYJBvNLSPMChjTMMIChmoYuO4PqnzxmUeZ@1udoJjI2RwfD@CcgcEA@ntwhMOD34S8NAH94pBgjPYirxuYqrVOIENC1iI7Qj7ivzUFyqX0kxcAFLUHJtldmZLgR8RqqZUPQdYgH@inDaQSsg@q0HtdeFIi66YybNloBGwXaosqk9mzf5tJF6SU9/2SpSkFNB330F34rwhmCZxhB72oruiwf9NFiHDsdfSI4Vy@EHurcYUlUyowCvQu/A@22Jcuk0G2SRBrbxMtVFhc7S2Bmu8wZl6/p8u39n95VzvG0cjfj7i6qtbud3odode@/ceBeoyunrzVtS1j6Kfx1Tw3jDKFxmlF/xw8 "Perl 6 – Try It Online") This is an anonymous function that matches its argument against the giant regex following the leftmost `~~`. That regex is of the form ``` /^$(/.../)$/ ``` It interpolates the inner regex `$(/.../)` into the outer one. The outer regex requires that the overall match be anchored at the beginning and end of the string. The inner regex matches a Go type. It is recursive, calling itself using the expression `<~~>`. [Answer] # JavaScript (ES6), 250 bytes *Thanks to [@Bbrk24](https://codegolf.stackexchange.com/users/106545/bbrk24) and [@Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) for reporting bugs* Returns a Boolean value. ``` f=(s,t)=>s!=(s=s[R='replace'](T='T',t)[R](/chan |\[([1-9]\d*)?\]|map\[T\]/g,'*')[R](/\w \w/)[R](/ /,'')[R](/bool|u?int|float(32|64)|complex(64|128)|byte|rune|string|\*T|struct{(T(;T)*)?}|func\((T(,T)*)?\)(T|\(T(,T)*\)|(?=[,;})\]])|$)/,T))?f(s,T):s==T ``` [Try it online!](https://tio.run/##jVXbctowEH3nK7aZztjyOKEkKb0wbp7aD@j4TdaDMQKUGsmV5FBa8@2pLsYYGpMyY0va3XO82huP@VOuCskqfc3Fgj4/L5NQxRolX9Qbs0sU/p4EklZlXtCAhGkSpIFR4@8kHBfrnEOT4RBPrj@RbBGhh4w0m7zKcJqR8SoOosBbZlvItmO/h3EctOK5EGVTPzCum2Upch3e3TbTe9QUYlOV9Fc4vW8mtx9RM99p2sia00ZpyfiqyaLUbutC/wnTcJYi8@l9s6x5kYVGEDtBhsK0ydpjhprwIcHxbI8yQlDzFo2NGD0szW1T9FklSfpcCK5ESW9KsQoDnMpar3ckQLMRHgFcWWevYrsz/vpN66fx0Z@jThMdfp0EE@/74YTJUQWTd0AAA8GT2zsCEeD30w9OAPjjJ6uL7O29tYkvNtATOisDx2ghBM51h@eII/Zor0RcFg/K1sAG1mxn3nZm7faerVXC6dHagkvh9H4GUU/qoGfW7WJVsz5BhL0zx7DujbClNVvrZOu9X1pam/cQ9faGLa7tyz72M6gfkAGT0NvEJ0uf9YBD4F5HGSY9z84MDse2YNz1hl6dmaXzl4KThbwkPPcQxe3ShtafZn7Zo6sRGd0shfyaF@tQQfIF@mVv2gEhU/Gjk17IOP6Wl6rXDMZVuqLyKoaB33gMNf/BxZZDJdmGafZEnZ82m8OwYSDb5CvGc7kbAg8CuY4ufdACI9gyvQYuQO8q6hv0IsahNkwpk3IbQJ0zThc9dK4Wy9X68Uf5Mk3P2Q6DiR8JF75oWpspUydPeckWYLIIuZT5DkrKV3rtWK4n3WQYYuF0ldvo2IJThoFeZjQz6eb@/ZS0jfgPr2F0qtepjs0eH7r6lK0XVEU3rBCl4DCnekupmVF0M6fSxUv1@xi5Zn7h0v0UlcKtlXGR91zpOM6n6kvguTR/gkfwAHZ/ChYV5R04/ifrtvFfy/qBStKfNZOmzLZrpqmqWm8sBb6U9H5ULegM7yeDHSTDLnDBr@mm0jsfQb2miv02nkiqa@lvA4KXO1cw7y7XseWrTERdCVri31QKaCeK6mjMhaCb2el/ja3nvw "JavaScript (Node.js) – Try It Online") ### How? At each iteration: * If we find a `"T"` and this is the first iteration, we replace it with `"undefined"` to invalidate the input. * We replace all occurrences of `/chan /`, `/\[([1-9]\d*)?\]/` and `/map\[T\]/` with `"*"`. They all boil down to a valid prefix of another type. * If we find `/\w \w/`, we replace it with `"undefined"` to invalidate the input. * If we find a space somewhere else, we remove it. * We then look for the first valid type and replace it with `"T"`: + primitive types: `/bool|u?int|float(32|64)|complex(64|128)|byte|rune|string/` + a type preceded with `*`: `/\*T/` + a `struct` type: `/struct{(T(;T)*)?}/` + a `func` type: `/func\((T(,T)*)?\)(T|\(T(,T)*\)|(?=[,;})\]])|$)/` The `func` type is the trickiest one because we must not ignore a *return* statement that is not yet fully simplified. That's why we make sure that `func(...)` is followed by either a valid *return* statement or the end of the line or one of `,;}]`. This process is repeated recursively until there's nothing more to replace. If the input string is valid, we should end up with a single `"T"`. ### Example 1 ``` func(int,uint,int,bool)(string,string,string) func(T,uint,int,bool)(string,string,string) func(T,T,int,bool)(string,string,string) func(T,T,T,bool)(string,string,string) func(T,T,T,T)(string,string,string) func(T,T,T,T)(T,string,string) func(T,T,T,T)(T,T,string) func(T,T,T,T)(T,T,T) T ``` ### Example 2 ``` map[map[map[int]string]map[bool]chan map[int]int]struct{int;string;bool} map[map[map[T]string]map[bool]*map[int]int]struct{int;string;bool} map[map[*T]map[bool]*map[int]int]struct{int;string;bool} map[map[T]map[bool]*map[int]int]struct{int;string;bool} map[*map[T]*map[int]int]struct{int;string;bool} map[***map[T]int]struct{int;string;bool} map[****T]struct{int;string;bool} map[***T]struct{int;string;bool} map[**T]struct{int;string;bool} map[*T]struct{int;string;bool} map[T]struct{int;string;bool} *struct{T;string;bool} *struct{T;T;bool} *struct{T;T;T} *T T ``` [Answer] # [Go](https://go.dev), ~~1279~~ 1277 bytes ``` import(."regexp";."strings";U"unicode") func P(s string)(string,bool){S,M,C,t,Z:=U.IsSpace,MustCompile,CutPrefix,0,0<1 T,X:=func(){for len(s)>0&&S(rune(s[0])){s=TrimSpace(s[1:])}},!Z N:=func(){T();s=s[1:];T()} T() if len(s)<1{return s,X} if k:=M(`^(bool|u?int|float(32|64)|complex(64|128)|byte|rune|string)($|[]});,\s])`).FindStringIndex(s);k!=nil&&k[0]<1{s=s[k[1]-1:];T();return s,Z} if s[0]=='*'{return P(s[1:])} if s[0]=='['{N();k:=M("^[1-9][0-9]+").FindStringIndex(s);if k!=nil{s=s[k[1]:];N();return P(s)};N();return P(s)} if r,o:=C(s,"map");o{s=r;N();s,o=P(s);if!o{return s,X};if s[0]==']'{N()};return P(s)} if r,o:=C(s,"chan");o{s=r;if!S(rune(s[0])){return s,X};T();return P(s)} if r,o:=C(s,"struct");o{s=r;T();if s[0]!='{'{return s,X};N();for s[0]!='}'{s,o=P(s);if!o{return s,X};if s[0]=='}'{break};if s[0]!=';'{return s,X};N()};N();return s,Z} if r,o:=C(s,"func");o{s=r;T();if s[0]!='('{return s,X};N();for s[0]!=')'{s,o=P(s);if!o{return s,X};if s[0]==')'{break};if s[0]!=','{return s,X};N()};N();if len(s)<1||M(`^[]});,\s]`).MatchString(s){return s,Z} if s[0]=='('{N();for s[0]!=')'{s,o=P(s);if!o{return s,X};t++;if s[0]==')'{break};if s[0]!=','{return s,X};N()};if t<1{return s,X};N()} if M(`^[iufcmbrsc*[]`).MatchString(s){return P(s)};return s,len(s)<1} return s,X} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=vVbNbuM2EL70Yj0FLXRj0mEMO5t1s9aqPQRYYA8JDDgLLKJoG0WRHNWy5IoUkEDSk_QSLLDv0GfpY_ReoDPUj2XHDoIealgkNTP8-HH-7D--zeOnP1eOu3DmHlk6QaQFy1WcSN1fSv17Kv2j079--KeU0YGeeHPvYaUbA13IJIjmQjc-62kUuPGdpzPNTyOXTKkgpZbRcua3cRyybMbP-RmX_Gpifh58EjM41uPnqZBn8XIVhB4_S-U08fzggQ_58MNIu-RfJiZiUpb5cUJCL6KC_Tw8OJjRJI08KqyhzVgmzMskWCo8EI0mNisK3r3SLprdl5QZwlQ6A9aFBoMW-BXih1GWeDJNIiL4lwLli4l5Tm--UiSep78Ekcz9MHYkfXucj09Y7gLj0Hug45N8dHzK8ttH6eVIKa9v_mNu2QUz-LWw2Q0bfAyiu5lSfYruYKNgxqJrRkF4cLCASwADpLewRvZRxdFoKF0pSnhX0-z1ezXXaX3XltbqZRewVdHXv1qjo_e2NYThUN9JAW-qWDSnw9kX67PhCFY8E-B5CY8n5hkVXF86K50ZMSAkylLw2JyW4N247VdjTdNWNIsXUN17J2pgAWkz4G3UyxfZQThSVzZIaFzR6Jq9rLeBhOwxzSpt0ctecxcwu008Z1G0gI1nwBterEO6polpuockfZEkex1JtoMk30OyVRZ5jlXQJDLk8bkj3fsyi8Ai252jtMzC19KUh4f_gSpo5WbhKjnSUKSD1HeXt4lw-9Z-4mWCNxj1vQutBVt3wb9Vd8MeSRnJtA5klrx_JBOTzFZhIOmN6jXQKniKAz6q79VNcGMqeyWttzCihrXMsqGurNLW3jKoXzUsErJ3QAsEKVsg2ZjsXUIN6WoKuGxv0Nq0Pr736w--WHZJCxaWrQRkNCQ2sYhtjY7f2qRPrHfjn5SAWKfvUdfH6lVsYEO9H1-JgkBDm7TE9bO2Vv5Agra6XK2sDKDGM1gapa2BdoVWyUmzQgui-vj4xCD9llRtWBtWE0qN9l5IpdK_jX8KEFaIsGzFrJwKrXLtntyortyEVQ03nOjX0P00reM7ofB25ZiyrHKpZt3otvxcqvdoC5VFdTY1sS1pA3EoQFTCAz_9iabuCv8RnHkQOckjyvuQCPB1xJ0_v_9tEWqWZZd5cTRqUgUSY3DybmxXvmpFhNfu2_ICDbZ9sZSDKaDJMKK6acJvPtYfLEDbwV7zKycSXZU4EfyZqcoTCrUjOIlRMaUSTDvQIbqxUqwxfaoHkRsniefKCXkjriMCH0eSN7_D8QDMicC9BfEgIlubkVC80JVew29bw54z_6iiupd5FfTdzP9P4lXre3oq538B) An *extremely* straight-forward recursive solution. The parser makes use of the fact that Go types are mainly right-recursive, with an unambiguous prefix determining the parser state. Most definitely can be golfed down by using a different algorithm, or making it iterative. (Fun fact: the builtin `go/parser` package fails some test cases due to the recursive anonymous `struct`s. It expects typenames or field names there. Though, in normal usage with gofmt, nested anonymous structs tends to not happen.) * -2 bytes: account for "dangling" leftovers, move true/false into variables (@The Thonnu) ### Ungolfed ``` func parse(s string) (string, bool) { trimSpace := func() { for len(s) > 0 && unicode.IsSpace(rune(s[0])) { s = strings.TrimSpace(s[1:]) } } nextChar := func() { trimSpace() s = s[1:] trimSpace() } trimSpace() // false on empty if len(s) == 0 { return s, false } // primitive types if k := regexp.MustCompile(`^(bool|u?int|float(32|64)|complex(64|128)|byte|rune|string)($|[]});,\s])`).FindStringIndex(s); k != nil && k[0] < 1 { s = s[k[1]-1:] trimSpace() return s, true } // pointer if s[0] == '*' { return parse(s[1:]) } // slice/array if s[0] == '[' { nextChar() // look for a positive int k := regexp.MustCompile("^[1-9][0-9]+").FindStringIndex(s) if k != nil { s = s[k[1]:] nextChar() return parse(s) } nextChar() // contained type return parse(s) } // maps if rest, ok := strings.CutPrefix(s, "map"); ok { s = rest nextChar() // key s, ok = parse(s) if !ok { return s, false } // account for primitive if s[0] == ']' { nextChar() } // value return parse(s) } // chan if rest, ok := strings.CutPrefix(s, "chan"); ok { s = rest // required space if !unicode.IsSpace(rune(s[0])) { return s, false } trimSpace() // contained type return parse(s) } // struct if rest, ok := strings.CutPrefix(s, "struct"); ok { s = rest trimSpace() if s[0] != '{' { return s, false } nextChar() // semicolon-separated list of types for s[0] != '}' { // type s, ok = parse(s) if !ok { return s, false } // when 1 type, next is a '}' if s[0] == '}' { break } // semicolon if s[0] != ';' { return s, false } nextChar() } nextChar() return s, true } // func if rest, ok := strings.CutPrefix(s, "func"); ok { s = rest trimSpace() // comma-separated args if s[0] != '(' { return s, false } nextChar() for s[0] != ')' { // type s, ok = parse(s) if !ok { return s, false } // when 1 type, next is a ')' if s[0] == ')' { break } // comma if s[0] != ',' { return s, false } nextChar() } nextChar() // return type // can be nothing, 1 type, or parened comma-separated types // nothing if len(s) == 0 || regexp.MustCompile(`^[]});,\s]`).MatchString(s) { return s, true } // multiple types if s[0] == '(' { nextChar() typeCount := 0 for s[0] != ')' { // type s, ok = parse(s) if !ok { return s, false } typeCount++ // when 1 type, next is a ')' if s[0] == ')' { // nextChar() break } // comma if s[0] != ',' { return s, false } nextChar() } // no non-empty paren return type if typeCount == 0 { return s, false } nextChar() } // 1 type if regexp.MustCompile(`^[iufcmbrsc*[]`).MatchString(s) { return parse(s) } return s, len(s) == 0 } return s, false } ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, ~~239~~ 234 bytes Uses the replacement strategy from Arnauld's [Javascript answer](https://codegolf.stackexchange.com/a/263881/52194) as a full program using the `-nl` flag to loop the code over each line of input. Since Ruby doesn't let you inject `undefined` by leaving out arguments, the relevant replacements to force disqualification use `X` instead. I had a slightly different regex strategy for solving the `func` issue but it turns out using the regexes from that answer was shorter. ``` sub'T',?X 1until$_==(gsub /\[([1-9]\d*)?\]|map\[T\]|chan\s/,?*;sub /\w\s\w/,?X;sub /\s/,'';sub /bool|u?int|float(32|64)|complex(64|128)|byte|rune|string|\*T|struct{(T(;T)*)?}|func\((T(,T)*)?\)(T|\(T(,T)*\)|(?=[,;})\]])|$)/,?T) p$_==?T ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVNdbtpAEH7oU32KUYTErmWamBBKZCFfwg-RdleRIYaQGoPAVoq6Pklf-pCqZ2qP0FN0Zn8wVMGSd2e--Wb8zez6-9uumR1-iatBVV6pty30Hn829WIw-f1338z6WT9KH4K4qepV2XucTtkSUbiWgol4cK_kU8hTqfQ630qRoTF_ziu5v47SMLHEV7mXr-g_OB9j_b61Z5tNqZt0VdV6UW7ymt0O9XjE9Xyz3pbFVzYe6Xg44Xp2qAu9a6pC7-vdqlpqGWZkNvP6G8tYknEU0epFU80lQyAygOQs09K5kmuWTkWUtFwqxXWPo6SMB1vqKc1sxz_c9ufDgqQFKCxwWlBHEJIf-occoawgNIQyAMQ3oD4KUCIe3ioIQdyNPytAAMTkHmMQUiMBzktggs8nF0wJIio4gf3bsRW5JFDRsMEHHYGGgmZiuQnx2sDhcLSIAWbo41EC4QlqEjqi2whNTnNDYb_ezadF0FVEk1Q5uXZrAzofxu2GNaKGFnqpOHctX4gyG47ONlfLp3AwS4cJdaLiP4J3A9vFpYUYVMRqh7NNvQfaeseLgfnFstgBQGBmA2St1vlyVeW7A1A8NBgeun3QyvdPi-Xzy5cSHaHMrbCRQezqkoMX7NPobqzczC2lO6LInwV92ndsJutKeO4xeH7LfPxCuAXTqddmPXHMtcPAqZDSG9XRMiprTOTZ_-0f) ]
[Question] [ [Inverse function of this challenge](https://codegolf.stackexchange.com/questions/132002/) > > To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing). > > > Now, you are given the multiplied string and the result of multiplication, and your task is to output the multiplied integer. You can assume such integer exist. If multiple exist, output any of them. Test cases: ``` abc, cba => -1 abc, aabbcc => 2 abc, ccbbaa => -2 aaa, aaaaaa => 2 or -2 (empty), (empty) => any integer aaa, aa => undefined behavior abaa, aaaabbaa => -2 abaa, aabbaaaa => 2 hello, (empty) => 0 a, aaaaaaaaaaa => 11 or -11 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins! [Answer] # JavaScript (ES6), 61 bytes Expects `(original_string)(other_string)`. ``` a=>b=>b.match([...a].join(`{${q=b.length/a.length|0}}`))?q:-q ``` [Try it online!](https://tio.run/##dc5fC4IwEADw9z7FkB62B6fYW2B9kAi8W/MftqWOIMzPvlYqRtpxcAf34@5KuEMrmuJmfKUv0qaxhfiALvkVjMjpiXMOZ17qQtGk23Z1jLySKjN5AGPzDPs@YexY7/3aCq1aXUle6Yym1AMUHnMFEIXrGHERBCTarDshEAFm5y/he/wp8A0jops1jTOfNq@vnf50zH0qRrj748bDQzgX/roFGhyoBymUkZls7As "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org), ~~100~~ 98 bytes ``` \(x,y,r=rle(x),s=rle(y))`if`(sum(t<-s$l),`if`(any(r$v!=s$v)|sd(c(a<-t/r$l,a)),-rev(t)/r$l,a)[1],0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9NTgQhEEb3ngKxF1UJxNGVi8GLqMkADS0JQxugO9OJN3HTmngoT-LW_mFiG9kU9V6-fKm39zh-WPHZZcvvvtQjnNjAoojewAlZWj4D4sHZA6TuCHnPU-WRLUCGAWLVX4pU9fiaatAg9zxfx8ozich4ND1kLPvDzRPbYWn6boTtgs6uDXMlWjAeUo7pxbs8EUqn_BYNC8KLBqhUmjJCpVRKa4pXRNyT243QWikpi-CrmfYlMr9zhLTxrNWv_5edRQHTwcSFbBoTl9hG7f7UFNiF2lgXTE2UeZa9a-N6_jiu8wc) Takes input as vectors of characters. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input in reverse order. ``` ÊzVÊ *JpNÎÀVmpU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ynpWygoqSnBOzsBWbXBV&input=ImNjYmJhYSIKImFiYyI) ``` ÊzVÊ\n*JpNÎÀVmpU :Implicit input of strings U=result & V=original Ê :Length of U z :(Floor) Divided by VÊ :Length of V \n :Reassign to U * :Multiply U by J :-1 p :Raised to the power of N :Array of all inputs Î :First element (original U) À :Is not equal to Vm :Map V pU :Repeat U times ``` [Answer] # [J](http://jsoftware.com/), 17 bytes ``` %&#*_1+2*[-:%&##] ``` [Try it online!](https://tio.run/##XY3RCoIwFIbv9xTHpJamkl4EDuwm6KqrbkPibM40aIZY5NOvTa2gwYF/377/7KpTh8X5xmEppWQW0RIyBhQCWAMzE0awOx72er5w/XO8SvxTyEx2c@0RKaoGqBCcI1IogSIXdKKInAvxT4f7T7HSt2oCIUS@6s4YphPAuAOyLSQjGL@yIDQE0Sr2DAo0rcVLebt3vRfAFOwbqh5q1cmLbD81ix@qkGWtZAFcVvism1a/AQ "J – Try It Online") * `%&#` Scaling factor -- longer length divided by shorter length * `#]` Use that to duplicate the shorter string elementwise * `[-:` Does that match the longer string? (will be 0 or 1) * `_1+2*` Double and subtract 1. This will be -1 if the string was reversed and 1 otherwise. * `%&#*` Multiply that by the scaling factor from step 1. Sadly repeating the 3 characters `%&#` is shorter than any other approach which re-uses the result, at least that I could find. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gIg÷DI×S¹Êi( ``` Inputs in reversed order as lists of characters. Will output the positive result for palindromes, where two results are possible. [Try it online](https://tio.run/##yy9OTMpM/f8/3TP98HYXz8PTgw/tPNyVqfH/f7RSspIOGCdBcSIYx3JFg1lJYNlYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/9Mj0g9vd4k4PD340LrDXZka/2t1/kdHRyslKumAcRIUJ4NxrE40XBTIA3KjoTIIlRCd2FQmwmWRMUwllAdSCcTYdeC2A0k3DtUEdIGEM4DcVCDOgeJ8vA7H7ZnY2FgA). **Explanation:** ``` g # Push the length of the first (implicit) input-list Ig # Push the length of the second input-list ÷ # Integer-divide this longer first by the shorter second length D # Duplicate this integer I×S # Repeat each character in the second input-list that many times, and then # convert it to a flattened list of characters ¹Êi # If it's NOT equal to the first input-list: ( # Negate it # (after which it is output implicitly as result) ``` [Answer] # [Python](https://www.python.org), 60 bytes -17 bytes thanks to `l4m2` and -14 bytes thanks to `friddo` ``` lambda a,b:a and(a==b[::(d:=len(b)//len(a))or 1]or-1)*d or 0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY89DsIwDIV3TuGtCWpVuqGInKR0sJNGrVQSVJWBs7BUQnAdZm5DQn8hQ5z35flZvj3P165ytr8beXxcOpPs34cGT6QRMCbhb6sZSkm5EEwL2ZSWEU_TUJFz10JWuDbJ-FaDF7sx42W88AFQW8jzCElFMUSKMCpimDUikVI_SCkinFz-8XWFM6Cg_z6n9sW8SphpYBOtyqZxq6RlyDipEBuAc1vbjhnmt-B8WKvvh_oB) [Answer] # [C (GCC)](https://gcc.gnu.org), ~~141~~ ~~137~~ 125 bytes * *-4 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* * *-12 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` f(x,y,d,k,r,i,z)char*x,*y;{for(k=d=!!*y;r=1;(k=-k)>0&&++d){for(i=z=strlen(y);i--;)r&=y[k>0?i:z+~i]==x[i/d];if(r)return d*k;}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZHRTsIwFIbjJXuKQw1khS6gV8ameOlDMGK6tmPNtJjDMAwyX8QbbngofRrbTYR4ZS_anP__8vf09OOonpZKHQ7HTZUnd59NHm9ZzTQrGTLLdlQVEkdbNqr5Pl9hXAot-n1fobjhvkpKOpsOh-Oxpq1vxU6sK3w2Lq4pt0nCKQ5FPS9n0wd7vxu_24UQ27md6AW3eYwUTbVBB3pU8qbpmvi6erzWJrfOQGXWlW8Iagp7SKOedRUgCMg7kQftFb2axyQlg3VK4OcYaEgdYRA4BtiiTRSFgBdpXewDo14bT2SmPEikzDKliCcnExAzuP3jK5VlUp795Ax4uQ0I6yIAVnhBBSSYv6ujpKvBd2WWBk9kUfyH9ZK_jvktWBvXjUxDZgr5Zlfon9vN8_S53w) [Answer] # [Elm](https://elm-lang.org), ~~108~~ 107 bytes *-1 byte thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)* ``` f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0 l=List.length ``` Takes two lists of chars, the shorter one first. You can try it [here](https://elm-lang.org/try). Here's a full test program: ``` import Html exposing (text) f : List Char -> List Char -> Int f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0 l=List.length main = f ['a','b','c'] ['c','c','b','b','a','a'] |> String.fromInt |> text ``` ### Explanation * If the shorter list `a` is not empty: + Let `r` be the integer quotient of the length of `b` and the length of `a` + Multiply `a` by `r` (approach copied from [my Elm answer](https://codegolf.stackexchange.com/a/256437/16766) to the string-multiplication question) + If the result equals `b`, return `r` + If not, assume it's because `a` was reversed and return `-r` * The only valid case when `a` is empty is both `a` and `b` empty; in this case, any number can be returned; we choose `0` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ȧ¹•nṠ¬ßṘ⁰=)N ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiyKfCueKAom7huaDCrMOf4bmY4oGwPSlOIiwiIiwiYWJjLCBhYWJiY2NcbmFiYywgY2NiYmFhXG5hYWEsIGFhYWFhYVxuXCJcIixcIlwiIl0=) Outputs the smallest integer needed, with preference given to positive integers if there are 2 possible answers. ## Explained ``` ȧ¹•nṠ¬ßṘ⁰=)N )N # Find the first integer n (pos or neg) where: ¹• # the divisor with characters repeated ȧ # abs(n) times ßṘ # reversed if: nṠ¬ # n is negative ⁰= # equals the dividend ``` [Answer] # [Haskell](https://www.haskell.org/), 85 bytes ``` l=length _#""=0 p#m=let q=l p`div`l m in if p==concatMap(replicate q)m then q else -q ``` [Try it online!](https://tio.run/##PYpBDsIwDATvfYWVXEACiQ/kCbwAIeoYQyIck7QR3w9pQd2Lx7MbcH6xSGvihPVZw3CzxrjTkG3qpkJxAnm8x88okCAqxAdk5@ithPWMeTdxltiZoewT1MAKBVhmhmNpCaO6PEWtF4M93iMaa3A5B/PjFTusYskmibY9ra33RP/32r4 "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` I∧Lη×÷LηLθ∨⁼⭆θ×ι÷LηLθη±¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzEvRcMnNS@9JEMjQ1NHISQzN7VYwzOvxCWzLDMlFVkKyizUBLL9izRcC0sTc4o1gkuAZqX7JhZoFMJ0Z@ooEDAAZARIxC81PbEkVcNQEwys//9PTErmSk5OSkpM/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Second input L Take the length ∧ Logical And η Second input L Take the length ÷ Integer divided by θ First input L Take the length × Multiplied by θ First input ⭆ Map over characters and join ι Current character × Repeated by η Second input L Take the length ÷ Integer divided by θ First input L Take the length ⁼ Is equal to η Second input ∨ Logical Or ¹ Literal integer `1` ± Negated I Cast to string Implicitly print ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 30 \log\_{256}(96) \approx \$ 24.69 bytes ``` LDns1+:gD0<?z1r(z1(sZAZkz0=Pkw ``` Port of Kevin Cruijssen's 05AB1E answer. Append `0~` to the end if outputting `[]` for 0 isn't allowed. #### Explanation ``` L # Push the length of the first (implicit) input-string Dn # Duplicate and negate the top one s1+ # Swap and add one to the top one # (The range works like Python's in that range(a, b) will give [a..b)) : # range of the two items on the stack g # Filter for items where the following is truthy: D # Duplicate the number 0<? # If it's less than 0: z1r # Push a reversed copy of the second (implicit) input ( # Else: z1 # Push the second (implicit) input ( # Endif sZA # Get the absolute value of the integer Zk # And uninterleave the string with a length of this integer z0= # Check if each part is equal to the first input P # Are all of these true? k # End filter w # Keep truthy items only # (It was somehow including 0 in the output for all test cases, so I had to discard it) ``` #### Screenshots [![Screenshot 1](https://i.stack.imgur.com/B533xm.png)](https://i.stack.imgur.com/B533x.png) [![Screenshot 2](https://i.stack.imgur.com/Mr56im.png)](https://i.stack.imgur.com/Mr56i.png) [![Screenshot 3](https://i.stack.imgur.com/f23MKm.png)](https://i.stack.imgur.com/f23MK.png) [Answer] # [Python 3](https://docs.python.org/3.8/), 53 bytes ``` lambda x,y:len(y)and[d:=len(y)//len(x),-d][y[::d]!=x] ``` [Try it online!](https://tio.run/##XZDNDoMgEITvPsU2PSCJxtJeGhKPfQrqYQFNTSwaYxN4egtYf1IuZOcbZicMbnr15nYfxrkpn3OHb6kRbOZ4V5vUUTRaaF4uQ1GE29Is15VwgnNdnUpbzU0/@ifgoDUgkpSgVCQDoiQSmsEZcraLiFIqtejXg1dJias96n6K9nB@dvB7Igxk0dC4o3kRPzIG7wn/2RsKYIv35FV3Xb@nX4J5r3Howlgsw1hS8QRgGh2HYWzNlDZp@ApKvVpbVQ/TCsgjjm1vCJ2/ "Python 3.8 (pre-release) – Try It Online") [Answer] # [R](https://www.r-project.org), 62 bytes ``` \(a,b,`?`=length)`if`(k<-?b,(l=k/?a)*(-1)^any(a!=b[!1:l-1]),0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9NTsMwEEb3nMI1Gw-yRcMKIdwchB9lxrVTq5aDXAeRs7AJSByKk7AlTVIR1NmM5j19M5r3j9R_Ov3VZqduvzePAiXJqqx0sLHOO6i8q8T-XpUkRdD76xLhSqgCnjF2AleaHlbFXVDFE8g1zFt-au3aaLJvoniTHThhgzjkdHgJPg-EcwC5RN2I4KIWHMlwyTgikTEcLpnesJuFMIYIcRZqMsM8Ro51irAmnTT9-bPsUcxgeIj5mG1t0xhbqPW_MzNs49Y6H-2Wkd3hq2_S9H7fT_0X) Test setup stolen from [pajonk's R answer](https://codegolf.stackexchange.com/a/256420/95126). [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8 bytes (16 nibbles) ``` ?,%$`%;/,@,$_*~@ ``` ``` ?,%$`%;/,@,$_*~@ / # divide ,@ # length of arg2 ,$ # by length of arg1 ; # and save the result n; `% _ # now get every n-th element of arg2 %$ # and use this to split arg1 # (result will be empty list if they're equal, # or arg1 unchanged if they're unequal); ?, # if the length of this is nonzero *~@ # return n multiplied by -1 # otherwise implicitly return n ``` [![enter image description here](https://i.stack.imgur.com/6ga1Z.png)](https://i.stack.imgur.com/6ga1Z.png) ]
[Question] [ Given a matrix of integers \$M\$ and a list of four integers \$L\$, find the sub-matrix \$N\$ whose corners are given by \$L\$ and return the sum of its elements. Suppose you're given the list \$L = [-8, -3, 2, 9]\$ and the following matrix \$M\$. The numbers in the list are highlighted in blue to illustrate: $$ \begin{bmatrix}0 & 2 & -7 & -5 & -6\\ 6 & \boldsymbol{\color{blue}{-3}} & 4 & -2 & \boldsymbol{\color{blue}{9}}\\ -9 & 1 & 8 & -1 & -8\\ 3 & \boldsymbol{\color{blue}{2}} & -4 & 2 & \boldsymbol{\color{blue}{-8}} \end{bmatrix} $$ Your task is to sum the elements in the sub-matrix \$N\$ described by those four corners, in other words the sum of all of the blue numbers below: $$ \begin{bmatrix}0 & 2 & -7 & -5 & -6\\ 6 & \boldsymbol{\color{blue}{-3}} & \color{blue}{4} & \color{blue}{-2} & \boldsymbol{\color{blue}{9}}\\ -9 & \color{blue}{1} & \color{blue}{8} & \color{blue}{-1} & \color{blue}{-8}\\ 3 & \boldsymbol{\color{blue}{2}} & \color{blue}{-4} & \color{blue}{2} & \boldsymbol{\color{blue}{-8}} \end{bmatrix} $$ In this case the sum (by sheer coincidence) is \$0\$. ## Input Input will consist of a matrix \$M\$ and a list \$L\$ in any convenient format. The matrix may contain duplicate numbers and may even have duplicates of the numbers in \$L\$ but there will be only one sub-matrix whose corners are the numbers in \$L\$. The numbers in \$L\$ may be in any order and will not necessarily correspond to the order of the corners of \$N\$. The numbers in \$L\$ might not be unique. \$M\$ will always have at least two rows and two columns. \$N\$ will also always be at least \$2 \times 2\$. ## Output The output should be a single integer—the sum of the elements of \$N\$—in any convenient format. ## Rules * [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) and [standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest solution in bytes wins. ## Test cases ``` Input: M = 6 9 -7 3 8 -1 -6 -4 2 -7 7 -7 -1 4 7 9 L = -1 8 -7 2 Output: 2 ``` ``` Input: M = 2 5 -7 4 -6 -4 -2 2 0 -6 1 -4 5 7 6 3 2 -7 -6 -4 L = 6 -6 2 5 Output: 14 ``` ``` Input: M = 9 6 4 7 5 0 -3 -2 8 -4 -7 9 L = 7 8 9 9 Output: 32 ``` ``` M = 1 2 3 2 3 2 3 2 1 L = 1 3 3 1 Output: 19 ``` [Answer] # R 4.1, ~~188 bytes~~ ~~120 bytes~~ 97 bytes I have wanted to answer a code golf question for a while and this seemed perfect for trying in R. These approaches are both functions which expect a matrix and a vector as arguments. ## v2.1, 97 bytes entirely thanks to Giuseppe [Attempt this online](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FjcTYzRydXJ0ErQTbIvzi0p0EnSBjMTcgpxUzeryjMycVA3FxJwcDe0cW1vt3OhMG928ovxyjVxNXSOdLCAnOT8HzInV1DTkKi7N1QCqscqMNorVybLKAlKxmrUQixZAKSgNAA). ``` \(m,l,`+`=sort,`-`=sample){while(!all(+l==+m[i<-nrow(m)-2,j<-ncol(m)-2]))1 sum(m[i:i[2],j:j[2]])} ``` ### How? I can't take any credit for this awesome set of improvements posted in the comments but I will try to explain them - hopefully I will do them justice. The most significant changes seem to be: 1. Replacement of `s=sort,e=sample` with ``+`=sort,`-`=sample`. It would never have occurred to me to try this and I am amazed and slightly horrified that R allows it, but obviously these operators don't require brackets meaning we can do `nrow(m)-2` rather than `s(nrow(m),2)` (and the same for `ncol`). The backticks in the definition cost 4 bytes but it saves us 3 bytes each time. Total: -2 bytes. 2. Doing the assignment when we subset `m`, allowing us to replace the verbose `{i=e(nrow(m),2);j=e(ncol(m),2);!all(s(l)==s(m[i,j]))}` with `!all(+l==+m[i<-nrow(m)-2,j<-ncol(m)-2])` (which makes my head hurt because `-` now means `sample()`. This is [this](https://codegolf.stackexchange.com/a/9123/115882) trick - assigning a variable to the environment while using it in a function (in this case the function being ``[``). -15 bytes. 3. Replacing `m[i[1]:i[2],j[1]:j[2]]` (ugh so many square brackets) with `m[i:i[2],j:j[2]]`. This generates a warning that it will only use the first element (which is what we want), and the output is the same. -6 bytes. Great improvements which I will try to get my brain to store in the code golf part and not allow to leak into the writing R code for work part... Thanks Gisuseppe :). ## v2.0, 120 bytes [Attempt this online](https://ato.pxeger.com/run?1=lVRLboMwEN105VO4aRe2ZKTyyYe2LLrpCbJLoooiooJMgjBRgqKcJJt00Uv1NPXYWJRConREwszzePzeGPv4WZxOX5tyaU2-b47LYE4yxpkIxLooWRyIMMt5TPfbj4THZJ8EMVkV6y3JKHPoUwphtOZ1eBtyTgThNAgEyWYJSxeUHqj2kNhkAM7sxWMycxYsBS-V3oIeELrDr0khSlzG8i8KRYwy_GzhLCyLZEcigrC0EcM-w9aYYZcpYCIjW_7kgOVpyNEJY_VSCGR4CvERZRj44wCQ90q7U4oQh9UiArkTXcGRaF4kq5IMpoYUtnERiw0vB3JwCa1qkl44b9gLSIDoTUVQnCei1DIaD2wnGbRlGuvINdYj21hXvrHfbTDYmXY0EysZ_-2KntivpLViv6qa5VDX85SMToIFuMySz0N_hq20QxlZpWfcZaYXuk2thCt1j_RkYGtkX715PrDSDW_hQ63IVfo6u-ppyn075F5iOlYbJNf0L-_PGbK2Eul2PiXVxBao22r_l5-tasnHrvkhOHNhnvOKNMeE4TkBh-Klet_vmDpN9xWl-o6qrypzZf0A). ``` f=\(m,l,s=sort,e=sample){while({i=e(nrow(m),2);j=e(ncol(m),2);!all(s(l)==s(m[i,j]))})m[i,j] sum(m[i[1]:i[2],j[1]:j[2]])} ``` ### How? Inspired by Jonah's excellent [approach](https://codegolf.stackexchange.com/a/255146/115882) in J, I realised it was unnecessary to start with the apparently reasonable step of subsetting the matrix to those indices which match the input list. This method just randomly picks four corners, checks if when sorted they match the sorted input vector, and if so takes the sum of the "box" bounded by the corners. Once again, highly inefficient and will scale horrendously. But it is shorter than my original approach. Both answers use the `do-while` loop [trick](https://codegolf.stackexchange.com/a/157131/115882) set out by Giuseppe to evaluate `i` and `j` in the loop condition, so we can refer to them in the `while` condition without having to define them both before the loop and in the loop body. ## v1.0, 188 bytes [Attempt this online](https://ato.pxeger.com/run?1=lVTBbtQwEL1w8ldYopVsNEE4Sbu7FTlwQeIMt-0KmTRLLTnp4iTqZoEv4VIO_RB-g69hPN4ohKRVGSXxeDyeeW8m9o-f7u7uvm220fL3s1_b7FKUYOXXQ6ad09276krcXpv8WpSnpjq1Eq5MKUopmcnURcp0pnc72zH0sYXQVSfyG_u-LWshDmsDmxe5UBApifLN1C-tqRuhwxLE0FbmS1vgmslqXe4wQuVubsVBQiqZywZHp6vPhWR1i7nXbq1AbS7cOsYB_CwOs3izkew7Y8_5W-PqhjcFfnJdF6zkryNe6saZvcgF4yjnwFfAowXwBMiwxJnCFxeiNJji4LCggSzeIyXLikngHi7PvOVTF9QPkjHrs-XC-y5DhBitWyqsR_fG2gFbzbz6kVS_j0pEuQbNyx6Djxn0MmHSywyjXqbMevmbYW97gOmwscP5v4TDxnkmo4zzrI4oz0K8lGhMHCJvRy98Xs17KOLuw2CUmfUE-lqEMo0cnsj7PGz2aHvaT27eyqMKBR_ZzwKjhPhNupoGyHMdSh5DuqAGYc7V4_15AKwiksnkV6IijoyhrOp_8SmKhY864mP-ONEVI4ZjAvxSeEXyLY0ne6CjdNJJGW6y44XWX2x_AA) ``` f=\(m,l){z=arrayInd(which(m%in%l),dim(m)) a=apply while({i=sample(nrow(z),4);any(colSums((z[i,]*c(1,-1))))|is.list(a(z[i,],2,unique))})0 r=a(z[i,],2,range) sum(m[r[1,1]:r[2,1],r[1,2]:r[2,2]]) } ``` ### How? This is a highly computationally inefficient approach that does one reasonable thing and then is based on random guessing. Initially, it creates a 2-column matrix of the indices of the values in the input matrix which match the input list. Then it randomly selects four rows from that matrix (each of which is an `x,y` coordinate) until the following conditions are satisfied: 1. The second two coordinates subtracted from the first two coordinates give (0,0). 2. There are exactly 2 unique x and y values. This means (as we started with indices which match the input) that we have the bounds of the "box" - at which point we can select the desired values and sum them. This is my first response to a code golf question ever. I am sure the answer can be improved and am keen for suggestions. Also if I have made a mistake - whether a fatal error of logic or how the input is allowed -- please let me know. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~53~~ 52 bytes ``` xZyXH:2XN!"@XJxHP:2XN!"&GJ@3$)leSwS=?2GJ@,wX{:]3$)ss ``` [Try it online!](https://tio.run/##y00syfn/vyKqMsLDyijCT1HJIcKrwiMAwlZz93IwVtHMSQ0uD7a1NwLydMojqq1igWLFxf//R@saKihYKOiaKygYxXJFmykoWII5xtYgUUMFXTMFXRNrBSOwoDmQtAaJKpiAOAqWsQA) Or [verfy all test cases](https://tio.run/##JU49C8IwEN39FaeIIBiwSWxNg9hBsHQQoR1CS0AHtzpVaMUfH1@uSy7v3fu49/PTh0eY2q8rc@luy1Xhqqm8z//NtSrUetu/6rE@nSXQbnS/3IMbhuC9v7RTEzqREB1JZETSL7qUyDBQNrIJiZSEtiSZzPDayJKOgAw7IMGeDgA8WapBQ4ohebtnnEQGimgGVDQHcwnsGToNpxrs5xYb5XArJPFNmvON/wM). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes ``` ⟨{szs}{⟨hzt⟩ⁱ²cp}⟩c+ ``` [Try it online!](https://tio.run/##LY6xDoIwEIZfhbB6JlJKC4s@CCFEGWQw0YgJEcIgg4mbb8Cqm5q4OPom9EXwP2qbXL//rvffrfbLLD9utmsx1KXrTOeOWy7M@WHatv9cmv59HUx3q4uqaGpAXh1Mdzen5/eV7RpgNhmGGEdRRKkmP6E4pNSjVFEqIQRnNQIYaQmOEsshlwSLGN8CVhJ9XMQrSNDMSrhJ1DWx8Gm0tP7QihHt1icixTPAAXf78LEbSW4aJ2sMjizGsBbjzogk/u5eMs70cYHJDw "Brachylog – Try It Online") Takes a list `[M, L]` through the input variable and yields the box sum through the output variable. ``` s Take a substring of z a transposed s substring ⟨{ }{ }⟩ of the matrix, for which z zipping ⟨h t⟩ the first element with the last element ⁱ² twice results in a list c which concatenated p is a permutation of L. c+ Concatenate the rows, and sum. ``` [Answer] # JavaScript (ES6), 152 bytes Expects `(L)(M)`. ``` L=>M=>(g=(x,y,X,Y)=>M.map((r,j)=>r.map((v,i)=>1/Y?j<y|j>Y|i<x|i>X?0:t+=v:X?[X[x],v,X[i],r[x]].sort()+''==L.sort()&i>x&j>y&&g(x,y,i,j):g(i,j,r))))(t=0)|t ``` [Try it online!](https://tio.run/##hZDbjoIwEIbvfYpeYRsHl5MHjIUXcO8xhAviKilxxQAhkPDu7LQF1gs3S0ja@Wfmn2@ap01aXUrxrM1H8XUdbnw48eCTBzTjtIUOIjgzFNbf6ZPSEnIMSh00IDCwP85hfuz6PDj34tj2IohC61CveHOIwjiK2wQaiGKRQIn3ZF0VZU3Zarnk/DQGhghaIw86w8jUSIFTDhnFA0qGH625xfp6uBSPqrhf1/cioze6ICQmpg2E7IGYOzwdkiwYjVWCbFHwx4RLEtCqLMUWE7OmN6vOWLeT56Qqa0@rxEfrhLHFG4SttpMmZCObZwSljNaerJqtZeSMPdZrhkg4T/epwb8ZF2bQCf8vJCzBRXF7/5XHB/0qaqfJdjMSuJJoEvcawvxnc2R11W@/jkEVMecnd1TFbO2qrK1Nhx8 "JavaScript (Node.js) – Try It Online") ### How? In order to limit the number of `map()` loops, we use just two of them within a recursive function which processes up to 3 passes: 1. We unconditionally consider each cell as a possible top-left corner. 2. We test whether we've found the 4 requested corners. 3. We compute the sum of the sub-matrix. ### Commented ``` L => M => // L[] = corner list, M[] = matrix ( g = (x, y, X, Y) => // g is a recursive function M.map((r, j) => // for each row r[] at position j in M[]: r.map((v, i) => // for each value v at position i in r[]: 1 / Y ? // if Y is defined, this is the 3rd pass: j < y | j > Y | // if j is invalid i < x | i > X ? // or i is invalid: 0 // do nothing : // else: t += v // add v to t : // else: X ? // if X is defined, this is the 2nd pass: [ X[x], // build a vector v, // consisting of the 4 corners X[i], // (note that we have X = M[y]) r[x] // ].sort() // sort this vector + '' // and coerce it to a string == L.sort() // if it's equal to L[] (also sorted) & i > x & j > y // and the sub-matrix is at least 2x2, && // then: g(x, y, i, j) // process the 3rd pass : // else: g(i, j, r) // it's the 1st pass: process the 2nd one ) // end of inner map() ) // end of outer map() )(t = 0) // initial call to g(); start with t = 0 | t // return t ``` [Answer] # Python3, 222 Bytes: ``` from itertools import* S=sorted R=range def f(B,e): for x,X,y,Y in product(*[R(len(B))]*2,*[R(len(B[0]))]*2): if S([B[x][y],B[x][Y],B[X][y],B[X][Y]])==S(e)and x<X and y<Y:return sum(map(sum,[i[y:Y+1]for i in B[x:X+1]])) ``` [Try it online!](https://tio.run/##bZHNjqMwDMfPm6fwjdAJq@GjtKDh0gfYw/RClUWr7hJ2o2kTFFKpPH3XDqinSiHGzs9/O844@3/W5PvRPR6Ds1fQXjlv7WUCfR2t8xt2bCa0qmefjTubv4r1aoCBH4SKawaDdXAXrZjFCbSB0dn@9sfzjfzkF2X4IY67TSaernzvQoRSQQ9w5PIg752cOxHsiWy7@i35Xdw0R67is@nh/tEC2fnjVDvlb87AdLvy63nkaIXUcq5Pb2lHTWlqBzXrFgNY9LHcB9xyAW9//bZn12OHNfu2ikm5IS1tvEDu@zRetOfRz@ktEvCFfZPuF@kO@oJz4j@sUQIOT9BECLGpgSiKWAlQQbIDyNkekhSSEpKCZSG0w51hDAr6h4pRwpTCkpkBbANWYBJLcMcIrndyUaigc8orWU4HiC7iQSVbVSo8XwqwbcjNUYdaKYL2WjNf6TRUyKk2aS7CkAZodDgRPvDnzKZYyCQVsBcoJZDE@b6gUsRKREpC8Nu@xjLEdgK1KmSq10yODBbMw0rpOf8D) [Answer] # [J](http://jsoftware.com/), 75 72 71 70 68 66 bytes ``` +/@,@;@((-:&(/:~)"1(;/-#:i.4)&{&>)#])&,[:g@|:&>g=.[:;@,<@(1}.<\)\. ``` [Try it online!](https://tio.run/##NU/LbsMgELznKzYPYVBtHAy2C44jpEo99dRrEnGI4rS99AP6@HV3FqtCLLOzs7PLx@zXwVy6dfBFsdroYqIxUEEl7SngVpqeXl@e54c6lnGIUlZByDr8qo2RQ11tw7t2SnyJo9pelChP4R6/gzjeR30KQywPUZoffTirs57V6nZ9@6SGRkqGHin1wBM5nB115JmwxAVDqaPkCHVwPQcmHaBfTIyDS8eyhtps0sKEMbSOee5PDah9zgznLQyA7eKbZyx2lpfqMdrjTBDwSh5aHok2eFh24@Uc9/6v4dFnoLeIU353QA3/o8lzcjDzHw "J – Try It Online") This takes all submatrices, filters them based on whether their 4 corners sorted matches the target sorted, and returns the sum. The two parts that required the most experimentation to golf were: * `(;/-#:i.4)&{` The phrase to pull the 4 corners from a matrix. It generates the numbers 0 through 3 in binary, negates the ones, and uses those as a 2d index for "take" `{`: + `0 0` top left corner + `0 _1` top right corner + `_1 0` bottom left corner + `_1 _1` bottom right corner * `[:g@|:&>g=.[:;@,<@(1}.<\)\.` The phrase to generate all submatrixes. It has two parts: + `<@(1}.<\)\.` First we generate all possible heights for valid full width rectangles. We do this by calculating all prefixes of all suffixes, deleting the first element of each prefix list, because it has dimension 1. `[:;@,` is a technicality required to keep the list flat. Note that we also save this phrase as `g`... + `[:g@|:&>` We now reapply `g` to the *transpose* of every result from the first step, generating all the possible widths for each possible height. Together, these step generate all possible widths for every possible height rectangle, accounting for all possible submatrices. [Answer] # [Python 3](https://docs.python.org/3/), 134 bytes ``` f=lambda m,l,n=4,s=sorted:m*n>[]and[f(m[1:],l)|f([*zip(*m[::-1])],l,n-1),sum(sum(m,()))][s(m[x][y]for x in(0,-1)for y in(0,-1))==s(l)] ``` [Try it online!](https://tio.run/##VVJRbsMgDP3PKfiEikhNITSNlJ2gPQHiI1MXrVJIoyaV2ml3z2xwaCdhgY393rNhfM7f10EtS9f0rf88t8zLXg6NllMzXW/z17n2m@HDunY42457W9RO9uK343bzcxn5xtu6zgsnHJblhZDT3XM0L7kQwtkJih7OPl13vbEHuwx8KyEPvWfyRNNMvBduwfBJsiPcMJtZWKyQLAdjhZOZDactRtB7u8vQhyMtB24sh2S2g7Q9WAlmQqGBk4IbDTvcskMAPyAUWBVh8yrkKkLQtFeRLK8iBoQOLzqDYJGOqVC@giGlDhGSw1DSPnWlYwTAshSrKHP3IkC1JYX12k@@9rGj8Zg0Hh3zA7T5188@icrSTAxhlC9CHIpZ9YXEkkgUkqYeNYki/YGwitN4H1BBDGodRdTzrmx9zpCryOBJM1ez8XYZZs7x//l25PN97L/kCb7fEX7b8gc "Python 3 – Try It Online") Recursively removes edges from the matrix until a solution is found. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes ``` FLθFιFL⌊θFλ«≔⟦⟧ζF⟦ικ⟧F⟦λμ⟧⊞ζ§§θνξ¿⬤⁺ζη⁼№ζν№ηνIΣE✂θκ⊕ι¹Σ✂νμ⊕λ ``` [Try it online!](https://tio.run/##VU9Na8MgGD43v@I9KrzC@rEupadQdiisEOhRcgiprVJjlqijdOy3Z2qywwR9eb5eHhtZD01X63G8dgOQD2FuTpKeUkhYzXPmT8qo1rdRnwVN4TtbFNaqmyG8QnjSfbZIElcI92r2cY3QBlB6K8kToXBHcxEP8jd7BEMRHjTG1RVIoTUptbfRLIPy3vtaW3LovHGRi@4JyAhioXJQAR5q68g5lDzVn@SsVSPi8jvC0TSDaIVx4hL@hbAMN/omjwn9/ns0nc4@@xlHzjm8IKyQvSF7RbatMAPgsEW2RtggWyHsJo7twm6EHNkSWT771im7SW9eRZKzPGVTsBrZl/4F "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FLθFι ``` Loop over all possible row ranges. ``` FL⌊θFλ« ``` Loop over all possible column ranges. ``` ≔⟦⟧ζF⟦ικ⟧F⟦λμ⟧⊞ζ§§θνξ ``` Get the corners of the submatrix. ``` ¿⬤⁺ζη⁼№ζν№ην ``` If this multiset equals the input list, then... ``` IΣE✂θκ⊕ι¹Σ✂νμ⊕λ ``` Output the sum of the submatrix. 57 bytes using the newer version of Charcoal on ATO: ``` FLθFιFL⌊θFλ«≔ΣE⟦ικ⟧E⟦λμ⟧§§θνπζ¿⬤⁺ζη⁼№ζν№ηνIΣE✂θκ⊕ι¹Σ✂νμ⊕λ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVBPS8MwFMfjevULPHZK4QXcH2fHTmV4GDgY7BgK1i5dw9J0bVKRiZ_Eyw6KfiX9NCZpFQwk7_3-vLyXvH5mRdpkVSrP5_fW5DT6vrjMqwbIHVd7U5A6DMFj0ceeXwslyrZ0ei_IEJ6DQay12CuytdI6PRImEA4Jgs8lQmnz2KzUjj-R31gjqBDhaG-y4RQugoHIgcRSko1sNTkhFFa4rdtUarKsWmUc52o6UDjg5tg0wsJlqs3fAFspMu5aHBBWKmt4yZXhO_schJHdztd5lJ3uv0eG3VoEL2_6IdP9D32wIX2Uw-TrnjEGVwhjpDdIr5HOEgwAGMyQThCmSMcI846jc9sPIUI6Qhr1vomvnfozShzJaORrfWHS9fsB "Charcoal – Attempt This Online") Link is to verbose version of code. Saves 3 bytes by being able to flatten the nested array obtained when extracting the corners of `N`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ẆZẆ$€ẎØ.p¤œịœ|ƑɗƇṪFS ``` [Try it online!](https://tio.run/##LU5BCsIwEPyMF2GjNklT8wE/4ElDj16kB6@CJw96EATpQR8gCOIHrDdLCz4jfiTONhKymdnNzOxyURTrEHy1m@P2vtuHr471ZbB6X5vSvw5NuWlPn3O798/7ZBrq27A/C8E5Z8iSyEjl5MYkEhKGhAaR3M1QgNHWwDaPeMwjycThW8pMQ8dDvJIkjSKFm8Y8IyaKOsvoD24YQh59LBnOAE5ZreATN9Is6pIzBNsIHaxltzMqyb97kneZCgfwBw "Jelly – Try It Online") Dyadic link taking \$M\$ on the left and \$L\$ on the right. ``` Ẇ Get all contiguous sublists of the matrix, Ẇ get all contiguous sublists of Z the transpose of $€ each sublist, Ẏ and concatenate into a single list of submatrices. ɗƇ Filter by: œị Multidimensional-index into the submatrix with p the Cartesian product of Ø. [0, 1] ¤ with itself; Ƒ is it unchanged by œ| multiset union with L? Ṫ Keep only the largest passing submatrix, FS and flatten and sum it. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` U˜āãε`"€üÿø€üÿ".V}€`€`ʒÁ2£øÁ2£˜{X{Q}˜O ``` Inputs in the order \$L,M\$. [Try it online](https://tio.run/##yy9OTMpM/f8/9PScI42HF5/bmqD0qGnN4T2H9x/eAWUo6YXVApkJIHxq0uFGo0OLD@8AU6fnVEdUB9aenuP//3@0mY6umY6RjmksV3Q0kNLRNQcRZrE60bomOrpGQCkDCNdQByhgqmOuA@IYA8WBKoFaTWJjAQ) or [verify all test cases](https://tio.run/##NY/NSsNAFIX3PkWY9Z3i/DQxhdK1oBQXihACqeiim1ZIK0jJoj6C6@yyEsSVlaKCMOPKQB7CF4nnppUwM@f@nO/ezPPJ1fSmvRPHs9vlIh8Ep0NB95ny781GN689VxXugw7EZHYdnAzFCDX3lLfndfm99lWzycTvw7P/9F9@uxfCveS9iwJRxufn0a@1q/y2e@pydbk6K@py3IrxcoGRgwBQ9zZqkySRio5IRqRTSpKQYtYGGklFMiRpEWjORrigkbbQcZqmFLAFTZr6bMfDjbhCbrQkNUqHuxA0i1JEHBjqkLDaPSfCGjGowMQU8gjIPpsNMLuFLHv@Bysy@BQbFGimW9N0/8F0hbb0Dw). **Explanation:** ``` U # Pop the first (implicit) input-list and store it in variable `X` ˜ # Flatten the second (implicit) input-matrix ā # Push a list in the range [1,length] (without popping the list) ã # Create all possible pairs of this list with the cartesian product ε # Map over each pair: ` # Pop and push them both separated to the stack "€üÿø€üÿ" # Push this string, where both `ÿ` are filled with the two values .V # Evaluate and execute it as 05AB1E code: € # Map over each row of the (implicit) input-matrix üA # Convert it into overlapping lists of size A ø # Zip/transpose; swapping rows/columns € # Map over each the list of lists üB # Convert it into overlapping lists of size B } # Close the map €`€` # Flatten two levels down so we have a list of blocks of various sizes ʒ # Filter this list of AxB blocks by: Á2£øÁ2£ # Convert the current AxB block to a 2x2 block of its corners: Á # Rotate the rows once towards the right 2£ # Then only keep the first two rows ø # Zip/transpose; swapping rows/columns Á # Rotate the list of pairs towards the right again 2£ # Keep the first two pair ˜ # Flatten this block of corners { # Sort it from lowest to highest X # Push the first input from variable `X` { # Sort it as well Q # Check if these two lists are the same }˜ # After the filter: flatten the only remaining block to a single list O # Sum its values together # (after which this sum is output implicitly as result) ``` Some minor notes: 1. `ā` leaves the flattened list on the stack, which will affect the first iteration of the map. But since this is the 1x1 block anyway, it doesn't affect the final result. 2. The `üN` builtin will result in an empty list if `N` exceeds the list's length, so it doesn't matter that `˜ā` will also try to make blocks of 20x20 for a 4x5 input matrix. 3. Because we use `Á2£øÁ2£` to get our 2x2 block of corners from an AxB block, it doesn't matter that there are 1x1 or 3x1 blocks among (which could for example have caused issues for the final test case). ]
[Question] [ [Carryless multiplication](https://en.wikipedia.org/wiki/Carry-less_product) is an operation similar to binary long multiplication, but with XOR instead of addition: ``` 1011 11 × 101 5 ----- 1011 0 1011 ------ 100111 39 ``` In this challenge, you'll be given a positive integer `>= 2`, and must return a list of all positive integers which are carryless factors of that number, meaning that they can be carryless-multiplied by another number to get the input. For example, for 39, 5 and 11 would be two of those. Rules: * You may choose whether or not to include 1 and/or the input itself * You may output the factors in any order, and may include duplicates * You may choose how to represent the numbers (binary strings are allowed) Test cases: ``` 2 (1) (2) 4 (1) 2 (4) 5 (1) 3 (5) 6 (1) 2 3 (6) 25 (1) (25) 39 (1) 3 5 11 29 (39) 42 (1) 2 7 14 21 (42) 100 (1) 2 4 25 50 (100) 574 (1) 2 3 5 6 7 9 10 11 14 15 18 22 27 29 30 39 45 49 54 58 78 83 90 98 105 166 210 245 287 490 (574) 5040 (1) 2 3 4 6 7 8 9 12 13 14 16 18 21 23 24 26 28 35 36 42 46 48 52 56 63 70 72 84 92 101 104 112 126 140 144 168 184 202 208 233 252 280 315 336 368 404 466 504 560 630 808 932 1008 1260 1616 1864 2520 3728 (5040) 848640 (1) 2 3 4 5 6 7 8 9 10 12 14 15 16 17 18 20 21 24 27 28 30 32 34 36 40 42 45 48 51 54 56 60 63 64 65 68 72 80 84 85 90 96 102 108 112 119 120 126 128 130 136 144 153 160 168 170 180 192 195 204 216 224 238 240 252 255 256 260 272 288 306 320 325 336 340 360 384 390 408 427 432 448 476 480 504 510 520 544 576 612 640 650 672 680 720 765 768 780 816 854 864 896 952 960 975 1008 1020 1040 1088 1105 1152 1224 1280 1300 1344 1360 1440 1530 1560 1632 1708 1728 1792 1904 1920 1950 2016 2040 2080 2176 2210 2304 2448 2600 2688 2720 2880 3060 3120 3264 3315 3416 3456 3808 3840 3900 4032 4080 4160 4352 4420 4896 5200 5376 5440 5760 6120 6240 6528 6630 6832 6912 7616 7800 8064 8160 8320 8840 9792 10400 10880 11520 12240 12480 13056 13260 13664 15232 15600 16128 16320 16640 17680 19584 20800 21760 24480 24960 26520 27328 30464 31200 32640 35360 39168 41600 48960 49920 53040 54656 62400 65280 70720 83200 97920 106080 109312 124800 141440 195840 212160 249600 282880 424320 (848640) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes (per language) wins! [Answer] # [JavaScript (V8)](https://v8.dev/), 69 bytes *-4 by using a single loop as in [@jdt's C port](https://codegolf.stackexchange.com/a/252192/58563)* *-1 thanks to another suggestion from @jdt* Prints all carryless factors, excluding 1 and the input itself. ``` n=>{for(p=n*n;--p;g(p/n|0,q=p%n)^n||print(q))g=p=>p&&p%2*q^g(p>>1)*2} ``` [Try it online!](https://tio.run/##JY3NDoIwEITvPsVegBaLQsW/NNubV1/ASEJIQDysCxIuwLPXGi4zk282O@9yLL9V3/KQjBdXoyO0U/3pBSPFZJKETSN4T3OqOuSAZEHzzH1Lg@ikbJDRchhyoOOu8IfWZjLWizMPrSBXcFRwUqC9Ha4eeJilqcfn/LnZ@ZlbWb0EAVqYYP0a3QEhgi2QNFCLv66FD4t0Pw "JavaScript (V8) – Try It Online") Or **68 bytes** for a much slower version relying on arithmetic underflow: ``` n=>{for(p=n*n;--p;g(p/n,q=p%n)^n||print(q))g=p=>p&&(p&1)*q^g(p/2)*2} ``` [Try it online!](https://tio.run/##JY3NDoIwEITvPsVehBaLQsW/NMvNqy9gJGlIQDysCxIuwLPXEi4zk282Ox872F/ZNdzHw9VV6Ajzsfp2gpEiMnHMphZ8INUib0kWNE3cNdSLVsoaGXMOAsFBKqO2WA61jPTszFMryBScFJwVaG/Hmwcepkni8SV7bfZ@5W7LtyDAHEZY34YPQAhhByQNVGLRtfBhlu4P "JavaScript (V8) – Try It Online") ### Commented ``` n => { // n = input for( // loop: p = n * n; // start with p = n² --p; // decrement p until p = 0 g( // invoke g with: p / n | 0, // floor(p / n) q = p % n // q = p mod n ) // end of call ^ n // XOR the result with n || print(q) // print q if the result of g is equal to n ) // g = p => // g is a recursive function taking p: p && // stop if p = 0 p % 2 * q ^ // XOR the result with q if the LSB of p is set g(p >> 1) // recursive call with p right-shifted by 1 * 2 // double the result to account for the shift } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly) ``` B€æcþ`Ḃċ€BT ``` A monadic Link that accepts an integer and yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8/9/pUdOaw8uSD@9LeLij6Ug3kOcU8v//f2NLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/pUdOaw8uSD@9LeLij6Ug3kOcU8l/ncPvRSQ93zlDx1oz8/99Ix0THVMdMx8hUx9hSx8RIx9DAAAA "Jelly – Try It Online") (reduced set as code is slow). ### How? ``` B€æcþ`Ḃċ€BT - Link: integer, n € - for each i in [1,n]: B - convert to binary ` - use as both arguments of: þ - table with: æc - convolution Ḃ - modulo 2 (vectorises) B - convert n to binary € - for each row in the table: ċ - count occurrences (of n in binary) T - truthy indices ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~54~~ 53 bytes ``` BitXor@@(#~NumberExpand~2#2)&~Array~{#,#}~Position~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ymzJCK/yMFBQ7nOrzQ3KbXItaIgMS@lzkjZSFOtzrGoKLGyrlpZR7m2LiC/OLMkMz@vTlntf0BRZl5JtLKuXZqDcqxaXXByYl5dNZeRDpeJDpepDpeZDpcRkDK25Kr9DwA "Wolfram Language (Mathematica) – Try It Online") Returns all pairs that xor-multiply to the input. Loosely based on [alephalpha's answer](https://codegolf.stackexchange.com/a/50307) to the multiplication question. [`NumberExpand`](https://reference.wolfram.com/language/ref/NumberExpand.html) was introduced in 2016 with version 11.0. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 55 bytes ``` n->[eval(lift(d))|d<-divisors(Mod(Pol(binary(n)),x=2))] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN83zdO2iU8sSczRyMtNKNFI0NWtSbHRTMssyi_OLijV881M0AvJzNJIy8xKLKjXyNDV1KmyNNDVjodqDEgsKcoDiCrp2CgVFmXklQKYSiKOkkAZWrRBtpKNgoqNgqqNgpqNgBKSMLYECQEFDAwOgsDlIzsAEyLQwsTAzMYjVhJi8YAGEBgA) This is just factoring in the polynomial ring \$\mathbb{F}\_2[x]\$. --- ## [PARI/GP](https://pari.math.u-bordeaux.fr), 56 bytes ``` n->[d|d<-[1..n],!(g(n)%g(d))] g(n)=Mod(Pol(binary(n)),2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YGW0km6xmUmuUuziNAXbpaUlaboWNy3ydO2iU2pSbHSjDfX08mJ1FDXSNfI0VdM1UjQ1Y7lAbFvf_BSNgPwcjaTMvMSiSqCIpo6RJlR_UGJBQQ5QTEHXTqGgKDOvBMhUAnGUFNLAKhWijXQUTHQUTHUUzHQUjICUsSVQAChoaGAAFDYHyRmYAJkWJhZmJgaxUJMXLIDQAA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~89~~ 86 bytes ``` i;r(k,p){k=k?k%2*p^r(k/2,p*2):0;}f(n){for(i=n*n;--i;)r(i/n,i%n)^n||printf("%d ",i%n);} ``` [Try it online!](https://tio.run/##TY5dDsIgEITfe4pNkyZQaUT8i5LGG3gBo4mp0pAqkhbjQ@Xq4lqtygvsN7PMFFlZFCFoWZOKWdpWebWqEpHaHYKhYDYVdMmlV8TQVl1qonOTGpllWlIchobpxNCdud9trY1TJE4OEHdQ@oAEznttCI3aCPC8gDs2brOFHFoQDCYMpgxmDARe4wUChCPOEc9R4@Blt4nZQLp13OTy/Yvb4mMwoJ3jndCnrNHWe75C3/ElYs8lNoU1/emK/E/26hoSxx/iIx8ehTrtyyZktyc "C (gcc) – Try It Online") Port of Arnauld's answer -2 bytes thanks to AZTECCO -2 bytes thanks to Arnauld [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LʒULε0sbv·yX*^}Q}à ``` [Try it online](https://tio.run/##yy9OTMpM/f/f59SkUJ9zWw2Kk8oOba@M0IqrDaw9vOD/f2NLAA) or [verify (almost) all test cases](https://tio.run/##AUoAtf9vc2FiaWX/dnk/IiDihpIgIj95wqn/TMqSVcKuTM61MHNidsK3eVgqXn3CrlF9w6D/fSz/WzIsNCw1LDYsMjUsMzksNDIsMTAwXQ) (the largest two test cases are omitted because they'll time out). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] ʒ # Filter it by: U # Pop and put the current integer in variable `X` L # Push a list in the range [1, (implicit) input] again ε # Map it to: 0 # Push a 0 s # Swap so the current map-integer is at the top b # Convert it to a binary string v # Loop over each bit `y` of this string: · # Double the current integer y # Push bit `y` X* # Multiply it by integer `X` ^ # Bitwise-XOR the two integers together }Q # After the loop: check if it's equal to the (implicit) input }à # After the map: max to check if any was turthy # (after which the filtered list is output implicitly as result) ``` [Answer] # Java 8, ~~120~~ ~~119~~ 117 bytes ``` n->{for(int x=n,y,r,i;x>0;)for(y=x--;--y>0;System.out.print(r==n?x+" "+y+" ":""))for(r=i=0;i<32;)r^=(y>>i&1)*x<<i++;} ``` -2 bytes thanks to *@ceilingcat*. Outputs the results space-delimited to STDOUT in pairs, excluding `1`/`n` (to save a byte). May contain duplicates if a pair of the same integer XOR-multiplies into the input (e.g. `n=4`). Limited to `n=2147483647`, but could be raised to `n=9223372036854775807` by changing `int`/`32` to `long`/`64` (although already times out for test case `n=848640` anyway, tbh..) [Try it online.](https://tio.run/##ZZBBboMwEEX3OcXIiwoXGzkktCrG9ATNJssolVxCKqfERIakWIizU5vSLlovRprvP6M3/yRvkp4OH2NRyaaBF6l0vwBQui3NURYlbHwLcKvVAYrA6aAxd9KwcKVpZasK2IAGMWqa98faTJ5OaGKJIYp3OePYy1Z0lHJKrRO2tmnLc1Rf2@hinD8wQujnLkSAQutrihCepoxQgnGVrWKOzasIbJ6ruyW@77JMhSEfRu45Lte3ynHMOBPr2V0SbFu3/X23l/j7ih88lery0x@52/cxWZOEPJA4Iasnso7JkjGSPDqRrdkwDwL8Q1YhSgFNWfinI5fOb/fXXelg/hum7IbxCw) **Explanation:** ``` n->{ // Method with integer parameter and no return-type for(int x=n,y,r,i; // Temp-integers x>0;) // Loop `x` in the range [n,0): for(y=x--;--y>0 // Inner loop `y` in the range [x,0): ; // After every iteration: System.out.print( // Print: r==n? // If `r` is equal to input `n`: x+" "+y+" " // Print `x` and `y` with space delimiters : // Else: "")) // Print nothing instead for(r=i=0; // Reset `r` and `i` both to 0 i<32;) // Inner loop `i` in the range [0,32): r^= // Bitwise-XOR `r` by: (y>>i // Bitwise right-shift `y` by `i` positions &1) // Modulo-2 that (using Bitwise-AND by 1, so we won't // need parenthesis) *x // Multiply that by `x` <<i // Bitwise left-shift that by `i` positions ++;} // And increase `i` by 1 afterwards with `i++` ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~70~~ 68 bytes ``` ->n{(k=0..n).select{|b|k.any?{|a|r=0 k.map{|x|r^=a*(b&2**x)} r==n}}} ``` [Try it online!](https://tio.run/##VY7BboMwEETv/opRDpWNXGQvXsAH2g@JUgkiolS0KKKpRAR8O13UC/FtxzPzZvhtHuulWl/f@kl3lUvT3qQ/7Vd7vk9zM3dp3T/ep7meh8qpLv2ub9M8zsNHVSe6eaEkGc2ihqrql2VZj2SDZZtbYptFG8h65ywX4ZS29fm6JRVuw2d/x2gvx/FkD@qgllUR/p/2BpqMCruboINRvFMyaDYqf/KIlhtFvO8RUxb3MYb3oAidRWHQPl/AB5AXluBl9e5LdAY7uZyTIUV4wjJyCUd4t5VLiRdKCSJQsbEyBxkRGCGCA7hEUaLMEB1iKSlx57mQHUhMVBZiFJZghOWCDPkD "Ruby – Try It Online") * Saved 2 thanks to @G B reminding me that *f=* doesn't need to be counted. Very inefficient lambda function. Uses the range (0..input) three times: check each number up to input, try carryless multiply it for each and bitmask 2nd operand by 2^ each. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` '£?ƛ0$b(dn¥*꘍)?=;a ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInwqM/xpswJGIoZG7CpSrqmI0pPz07YSIsIiIsIjM5Il0=) Port of 05AB1E. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` NθFθ«≔θηF⮌×⊕ιX²…·⁰⁻L↨θ²L↨⊕ι²≔⌊⟦η⁻|ηκ&ηκ⟧η¿¬η⟦I⊕ι ``` [Try it online!](https://tio.run/##XY8/iwJBDMVr91NMmYEVxKvESq0WPE/ETq6YW@NOcCd7zp@1ED/7XDhXEFOF915@SWprfN2ZNueKf1PcJPeDHi56Xpw6r6RRt2K0CIEahkuprBijf2eHPfqAsCeHASquPTrkiEcgXaptdxXMtFRitClQjzvDDcKkVJ/EKcAauYkWlkYQwp1qGXrV3oESeJQajhEMueTgYJ/IJcUrBfzyINJZZgZhwceHor/18AGdFGy6CFZ4W08c4bAyIb5tlfy8uOf8Mcvjvv0D "Charcoal – Try It Online") Link is to verbose version of code. Outputs includes `1` and `n` as divisors. Explanation: ``` Nθ ``` Input `n`. ``` Fθ« ``` Loop up to `n`. (The loop variable is incremented whenever it is used effectively looping the trial factor from `1` to `n` inclusive.) ``` ≔θη ``` Start with `n`. ``` F⮌×⊕ιX²…·⁰⁻L↨θ²L↨⊕ι² ``` Take all possible shifts of the trial factor up to and including the same length as `n`, highest first. ``` ≔⌊⟦η⁻|ηκ&ηκ⟧η ``` Perform trial division by updating the running total with the XOR of the running total with the current shifted trial factor if this reduces it. ``` ¿¬η⟦I⊕ι ``` If there was no remainder then output the trial factor. [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` N=k=input() while k: k-=1;i=n=N while i:i-=1;n=min(k<<i^n,n) if n<1:print k ``` [Try it online!](https://tio.run/##JYzBCsIwEAXv7yuWnlpQaGKiGLO/0E/wIpEu0TVIRP36SO1pYAamfOv8UNves9wSmZA@6dJ1XZs4s2h51X7A2nIA5S2bk7DyBFqtBFmc8l20zzHKWTc6gORKGk0oT9FKuf2JZWzh4LGH9dgd4SzMOMIf3A8 "Python 2 – Try It Online") Prints the factors backwards, excluding the input itself. The idea is to test divisibility using a carryless analogue of long-division to compute the remainder and see if it's zero. The number `k` is a factor of `n` if we can xor some collection of leftward bit-shifts of `k` onto `n` to get zero. It suffices to use the greedy strategy of making `n` as small as possible at each step, which is achieved by clearing the leftmost bit of `n` (without introducing larger-valued bits) by taking the bit-shift of `k` whose leftmost bit aligns with that of `n`. The code achieves this by taking the bit-shifts `k<<i` for some large `i` counting down to `0`, and checking if xor-ing this value onto `n` makes `n` smaller. An alternative approach to repeatedly try to clear the rightmost bit of `n` while shifting `k` leftward. **[Python 2](https://docs.python.org/2/), 79 bytes** ``` N=k=input() while k: n=N;c=k=k-1;exec"n^=c*(n&c&-c>0);c*=2;"*N if n<1:print k ``` [Try it online!](https://tio.run/##JYxBCsIwFAX37xQhi9IGCk1sBRPjEXIEN59IQ@QbJKKePmpdzWKGKe@63ti055quUWgbX5GklC347BOXR@0H/F22EOyDo6/Jo3ZbyWdPqueOupFO0@BIeeOkChDpIviobbknriK3jfidDWYs2MMs2B0wG@hp@gA "Python 2 – Try It Online") ]
[Question] [ It's time to conclude [the series of John Conway challenges of mine](https://codegolf.stackexchange.com/search?tab=newest&q=conway%20is%3aq%20user%3a78410). ## Background A **FRACTRAN** program consists of an ordered list of fractions. The program starts by taking a single integer as input. Each iteration of the program, it searches the list for the first fraction such that multiplying the number by that fraction produces another integer. It then repeats this process with the new number, starting back at the beginning of the list. When there is no fraction on the list that can be multiplied with the number, the program terminates and gives the number as the output. You can find some tips and tricks for writing FRACTRAN programs in the previous challenge [Collatz in FRACTRAN](https://codegolf.stackexchange.com/q/203680/78410). ## Challenge Write a FRACTRAN program that * takes a FRACTRAN program **P** and its input number **N** encoded as an integer, and * halts if and only if the program **P** halts with the input **N**. Use the following procedure for encoding **P** to get a single positive integer **f(P)**: * Write down the numerator and denominator of each fraction in P in base `b`, using the value `b` as a separator. * Read the whole thing as a single number in base `b+1`. You can choose the value of `b`, whether to put a separator at either end or not, and which number (numerator/denominator, first fraction/last fraction) comes first in the representation. One possible encoding is: ``` [455/33, 11/13, 1/11, 3/7, 11/2, 1/3] int("1a3a11a2a3a7a1a11a11a13a455a33", 11) = 3079784207925154324249736405657 ``` The input value must be in the form of \$p^{f(P)} q^N n\$, where \$p, q\$ are two distinct primes and \$n\$ is a number coprime to \$pq\$. You can choose the values of \$p,q,n\$. (This format is consistent with the [84-fraction answer on SO](https://stackoverflow.com/a/1802570/4595904) and the 48-fraction one linked below.) The shortest program in terms of **the number of fractions** wins. The best record available is [~~**48**~~](https://web.archive.org/web/20180104084828/http://clomont.com/a-universal-fractran-interpreter-in-fractran/) [~~**30**~~](https://codegolf.stackexchange.com/a/231006/87594) [**24 fractions**](https://codegolf.stackexchange.com/a/246682/100664) by [benrg](https://codegolf.stackexchange.com/users/89587/benrg)! [Answer] # 30 fractions ``` 37^1/41^1 43^1/47^1 41^10*31^1*13^1/37^10*29^1 1/37^10 47^9*5^1/43^9*7^1 47^9/43^9*17^1 47^9/43^9*13^1 47^9/43^9*23^1 41^1*47^8/37^1*43^8*29^1 41^6*47^3/37^1*43^8*53^2 41^2*47^7*23^1*7^1/37^2*43^7*13^1*5^1 47^9*53^2/37^2*43^7*13^1 41^3*47^6*13^1/37^3*43^6*23^1 41^2*47^7*23^1*7^1*29^1/37^3*43^6*13^1*5^1 41^3*47^6/37^3*43^6*13^1 41^4*47^5*11^1/37^4*43^5*17^1 41^5*47^4*5^1/37^5*43^4*13^1 41^5*47^4/37^5*43^4*7^1 41^5*47^4/37^5*43^4*29^1 41^5*47^4*3^1/37^5*43^4*2^1 41^6*47^3*17^1/37^6*43^3*13^1 41^7*47^2*23^1/37^7*43^2*3^1 41^8*47^1*3^1*2^3/37^8*43^1*23^4 41^1*47^8*2^3*53^1/37^8*43^1*23^3 41^8*47^1*11^1*2^1/37^8*43^1*23^1 41^9*31^3/37^9*29^1 41^7*47^2*23^1*29^2/37^9*3^1 29^1/31^1 37^10*13^1/11^1 37^1/43^1 ``` p = 2, q = 5, n = 37^5 \* 43^4 \* 53^1 b = 3, denominators first, last fraction first, separator at start and not at end ## How does this work? To make it easier to understand, assign meaningful names to the primes used: ``` ifracs=2 ifracsw=3 inum=5 inum_r=7 multiplicand=11 products=13 denominator=13 numerator=17 temp=23 multiplier=29 multiplier_r=31 stateA=37 stateA_r=41 stateB=43 stateB_r=47 p_indicator=53 ``` Convert denominators to negative exponents, and then we can omit the `^` and `*` symbols (always including exponents even if 1). This produces a notation similar to [Subtractpocalypse](https://esolangs.org/wiki/Subtractpocalypse) (which, as the linked page notes, becomes equivalent to FRACTRAN with a single change). Together with this, we use the name of a prime to refer to the exponent of that prime in the current number. ### The state mechanism `stateA` and `stateB` together form a state. 10 standard states (0,9), (1,8), (2,7), ..., (9,0) are chosen such that none has both components greater than or equal to another's; this way, an instruction can single out one state that it will execute only in, by subtracting the appropriate values from `stateA` and `stateB`. To restore the state (same or different), we can't simply add back to `stateA` and `stateB`, as that would give the numerator and denominator a common factor. Instead, we add values corresponding to the new state to `stateA_r` and `stateB_r`, and the first two instructions transfer those values back to `stateA` and `stateB`: ``` # At the start stateA_r -1 stateA +1 stateB_r -1 stateB +1 ``` We use an abbreviated notation for these common parts: ``` State[M -> N] = stateA -M stateB -(9-M) stateA_r +N stateB_r +(9-N) State[N] = State[N -> N] ``` Also, the last instruction is used to automatically advance from one state to the next when nothing else executes: ``` # At the end stateA +1 stateB -1 ``` ### Parsing f(P) ``` # Start here-ish State[5] ifracs -1 ifracsw +1 State[6] products -1 numerator +1 State[7] ifracsw -1 temp +1 State[8] temp -4 ifracsw +1 ifracs +3 State[8 -> 1] temp -3 ifracs +3 p_indicator +1 ``` We start in state 5. There are some other instructions in state 5, but they do nothing at the start. First, the value of f(P) is transferred from `ifracs` to `ifracsw`. The instruction in state 6 does nothing at the start. The value is transferred from `ifracsw` to `temp` next. Then, in state 8, divide by 4 by repeatedly subtracting 4 from `temp` and adding 1 to `ifracsw`; simultaneously, 'refill' `ifracs` by adding the difference, which is 3, to it. After this finishes, the remainder will be left in `temp`. The next instruction tests for the separator (3), changing to state 1 and also incrementing `p_indicator` and 'refilling' `ifracs`. Suppose we haven't reached a separator. To reconstruct the base-3 number, we need to multiply the digits by 1, 3, 9, etc. This uses... ### The multiplication subroutine Multiplication happens automatically whenever the end of a state is reached, before moving on to the next state, with `multiplicand` nonzero. It adds to `products` the product of `multiplicand` and (`multiplier`+1), for a few reasons. It is implemented by these instructions: ``` # Multiplication (near the start) stateA -10 stateA_r +10 multiplier -1 multiplier_r +1 products +1 stateA -10 # Multiplication (near the end) multiplier_r -1 multiplier +1 multiplicand -1 stateA +10 products +1 ``` The fourth of these instructions executes first. It decrements `multiplicand`, increments `products` (for the 1 added to `multiplier`), and adds 10 to `stateA`, enabling the upper two instructions. Then the first instruction runs repeatedly, transferring `multiplier` to `multiplier_r` while adding to `products`. The second instruction subtracts the added 10 from `stateA`, exiting this section, then the third instruction transfers `multiplier_r` back to `multiplier`, and this repeats until `multiplicand` is zero. ### Back to parsing f(P) ``` State[8] temp -1 multiplicand +1 ifracs +1 # Multiplication occurs State[9] multiplier -1 multiplier_r +3 State[9 -> 7] ifracsw -1 temp +1 multiplier +2 ``` To activate multiplication, the last instruction of state 8 transfers `temp` to `multiplicand`, while 'refilling' `ifracs`. Multiplication occurs before the transition to state 9, adding the appropriate value for this digit to `products`. Finally, we need to triple the effective multiplier, which means tripling `multiplier` and adding 2 to it. The instructions in state 9 accomplish that; the second one duplicates the instruction in state 7 as a way of testing whether we have reached the end of `f(P)`, ending the program (since this is the last state) if so. (Note that, because we specified that `f(P)` begins with a separator, the end always happens after only one digit 0 is read, with `multiplier`=0, avoiding an infinite loop.) Changing state immediately after filling `multiplier_r` from `multiplier` avoids a similar infinite loop. Going to state 7, the process repeats to read the next digit of f(P). ### Handling the fraction ``` State[0] inum_r -1 inum +1 State[0] numerator -1 State[0] denominator -1 State[0] temp -1 State[1] multiplier -1 State[1 -> 6] p_indicator -2 State[2] denominator -1 temp +1 inum -1 inum_r +1 State[2 -> 0] denominator -1 p_indicator +2 State[3] temp -1 denominator +1 State[3 -> 2] denominator -1 temp +1 inum -1 inum_r +1 multiplier +1 ``` `p_indicator` is initialised to 1, and incremented upon changing from state 8 to state 1. Thus, after reading the first (in this process; the last in the base-4 expansion) of each pair of numbers, which we have specified to be the numerator, `multiplier` is reset to 0, and since `p_indicator` is now 2, it becomes 0 with a change to state 6, where the value is transferred from `products` to `numerator`. After reading the denominator, state 1 ends with `p_indicator`=1. (Note that `denominator` is an alias for `products` -- they refer to the same prime.) In state 2, the first instruction transfers `denominator` to `temp` and `inum` to `inum_r` simultaneously. This ends when `denominator` or `inum` reaches zero. The second instruction checks for `denominator` being nonzero, which indicates that the number (original value of `inum`) was not divisible by the (original) `denominator`; it changes to state 0 while increasing `p_indicator` to 3. Then, the instructions in state 0 transfer `inum_r` back to `inum`, clear several values, and then continue to state 1 to clear `multiplier` and proceed to state 6 to resume reading f(P), with `p_indicator` reduced back to 1. In state 3, `temp` is transferred back to `denominator`, and the second instruction returns to state 2 while repeating its first instruction (as before, this checks for completion) and incrementing `multiplier`. If the loop exits here, then the number (original value of `inum`) was divisible by the (original) `denominator`, and `multiplier` contains the quotient minus 1 (for each iteration except the last). ``` State[3] denominator -1 State[4] numerator -1 multiplicand +1 # Multiplication occurs State[5] products -1 inum +1 State[5] inum_r -1 State[5] multiplier -1 ``` The final instruction of state 3 clears `denominator` (which is `product`). Then, in state 4, we transfer `numerator` to `multiplicand`, and with the transition to state 5, that value is multiplied by the quotient (recall that the multiplication subroutine uses `multiplier`+1). In state 5, we transfer `products` to `inum`, clear some values, and continue to repeat from the start. ## The whole program with the updated notation ``` # Initialise: ifracs, inum; p_indicator=1, stateA=5, stateB=4 stateA_r -1 stateA +1 stateB_r -1 stateB +1 # Multiplication stateA -10 stateA_r +10 multiplier -1 multiplier_r +1 products +1 stateA -10 State[0] inum_r -1 inum +1 State[0] numerator -1 State[0] denominator -1 State[0] temp -1 State[1] multiplier -1 State[1 -> 6] p_indicator -2 State[2] denominator -1 temp +1 inum -1 inum_r +1 State[2 -> 0] denominator -1 p_indicator +2 State[3] temp -1 denominator +1 State[3 -> 2] denominator -1 temp +1 inum -1 inum_r +1 multiplier +1 State[3] denominator -1 State[4] numerator -1 multiplicand +1 # Multiplication occurs State[5] products -1 inum +1 State[5] inum_r -1 State[5] multiplier -1 # Start here-ish State[5] ifracs -1 ifracsw +1 State[6] products -1 numerator +1 State[7] ifracsw -1 temp +1 State[8] temp -4 ifracsw +1 ifracs +3 State[8 -> 1] temp -3 ifracs +3 p_indicator +1 State[8] temp -1 multiplicand +1 ifracs +1 # Multiplication occurs State[9] multiplier -1 multiplier_r +3 State[9 -> 7] ifracsw -1 temp +1 multiplier +2 # Multiplication multiplier_r -1 multiplier +1 multiplicand -1 stateA +10 products +1 stateA +1 stateB -1 ``` [Answer] # 24 fractions $$\frac{2}{3}, \frac{5}{7}, \frac{7^{12} 41}{5^{12} 23}, \frac{7^{13}}{5^{13} 37}, \frac{3^{10} 7^3 13}{5^{13} 31}, \frac{3^2 7^{11} 19^1 41}{2^2 5^{11} 29}, \frac{3^3 7^{10} 19^1 23}{2^3 5^{10} 29^1 41}, \frac{3^1 7^{12} 19^1 37}{2^3 5^{10} 29}, \frac{3^4 7^8 29}{2^4 5^8 19}, \frac{3^4 7^8 11^b 31}{2^4 5^8 13^{b+1}}, \frac{3^{13} 11^b}{2^4 5^9 13^b 41}, \frac{3^{12} 7^1 11^b 19}{2^5 5^8 13^b}, \frac{3^2 7^{10} 11}{2^4 5^8 13}, \frac{3^8 7^4 19^b}{2^8 5^4 29}, \frac{3^8 7^4 13}{2^8 5^4 31}, \frac{3^{12}}{2^{12} 29}, \frac{3^{13} 17^1 19}{2^{13} 37}, \frac{7^{13}}{2^{12} 5^1 23}, \frac{3^{12} 7^1 31}{2^{12} 5^1 11}, \frac{3^{12} 7}{2^{12} 5^1 17}, \frac{3^{10} 7}{2^{10} 5^1 41}, \frac{3^{10} 7^3 37}{2^{10} 5^3 17}, \frac{3^3 7^4}{2^1 5^6}, \frac{3^4 7^4}{2^8}$$ Plug in a base \$b\ge2\$ of your choice. The start state is \$31^{f(P)} 17^N 5^{13} 19\$. The program encoding has a sentinel digit on the high end only (same as m90's), and the denominator on the low end (opposite of m90's). If \$b=10\$, the program \$\frac{22}{7},\frac{355}{113}\$ encodes to `int("a355a113a22a7", 11) = 32383861120629`. ### Explanation and annotated listing This program uses the same double/quadruple state system as m90's 30-fraction program, but I'll call them "modes" to avoid confusion with FRACTRAN states. A lot of the improvement of this solution comes from the observation that fractions can match ranges of modes as easily as single modes. Instead of using a subroutine or a loop variable (like m90's `p_indicator`) for code reuse, I use different modes with adjacent numbers, which can have any mix of shared and unshared code. Also, where m90's program has a single mode fallthrough rule at the bottom, I have two: if the mode is 1-7 then it's increased by 2, otherwise it's decreased by 4. Those two rules account for the majority of the control flow. The basic algorithm is: * Modes 2, 4, 6, 8 read the denominator. * Modes 1, 3, 5, 7, 9 read the numerator while calculating \$\text{divmod}(\text{state} \times \text{numerator}, \text{denominator})\$. The intermediates (numerator and product) are never stored anywhere. * Modes 0 and 10-13 test the remainder, update the state, rewind the program, etc. I tried to assign similar-looking (in base 10) register numbers to related purposes. The registers are: * 2,3,5,7 are the mode variables. * 11,13,31 hold the program. 13 and 31 are used to parse it, and 11 is a "counterweight" adjusted so that the full program is preserved as the sum. (m90 used a similar trick.) * 23 and 41 hold the remainder and divisor (denominator). Values of (0, d-1), (1, d−2), …, (d−1, 0) represent a divisor of d and a remainder of 0, 1, … d-1. * 17 and 37 hold the old state (saved in case the remainder is nonzero) and the new state (quotient of the division). * 19 and 29 hold the place value when reading the denominator, and the old state times the place value when reading the numerator (so state × numerator is calculated for free). I'll write \$[a{,}b]\rightarrow[c{,}d]\$ (where \$d-c=b-a\ge 0\$), or just \$[a{,}b]\$ if \$a=c\$, for a factor of \$\displaystyle \frac{3^c \, 7^{13-d}}{2^a \, 5^{13-b}}\$, which means "if we're in modes \$a\$ to \$b\$ inclusive then switch to modes \$c\$ to \$d\$ and also do whatever else is in this fraction." Also, I'll give the two-digit primes slightly more descriptive names: prg11, prg13, prg31, div23, div41, st17, st37, plc19, plc29. Stack Exchange tables and MathJax don't play well together, so no MathJax in the table. | | | | --- | --- | | 3−1 2+1,7−1 5+1 | Mode management, same as m90's program. | | [0,0] st37−1,[0,1] div23−1 div41+1,[0,0]→[10,10] prg31−1 prg13+1 | Mode 0: the designated starting point and also reached when division fails. Clear the quotient (st37) and remainder (div23). Halt if the program is exhausted, otherwise go to mode 10. The second instruction is shared with mode 1 (in fact, it's the only instruction in mode 1 aside from the default mode transition). | | [10,12] div41−1,[10,10] st17−1 st37+1 | Mode 10: clear the divisor and copy the saved FRACTRAN state back, then go to mode 8 (via the empty mode 6). The first instruction is shared with mode 12 (mode 11 is unused). | | [8,9] plc29−1 plc19+b,[8,9] prg31−1 prg13+1 | Mode 8 (denominator) or 9 (numerator): multiply the place value by b (does nothing on initial entry), and move the program to prg13, then go to mode 4/5. | | [4,5] plc19−1 plc29+1,[4,5] prg13−(b+1) prg31+1 prg11+b | Mode 4/5 (den./num.): move the place value back to plc29, and compute prg31, prg13 = divmod(prg13, b+1). | | [4,4]→[13,13] prg13−b prg11+b div41−1,[5,5]→[12,12] prg13−b prg11+b plc19+1 | Mode 4/5: exit the loop if the sentinel digit is reached. Duplicated because they need different off-by-one fixups: after reading the denominator, decrement it, and after reading the numerator, set the place value to 1 for next time. | | [4,5]→[2,3] prg13−1 prg11+1 | Mode 4/5: if the digit is anything else, go to mode 2/3 to add the place value an appropriate number of times, then go to mode 8/9 (via the empty 6/7) | | [2,2] plc29−1 plc19+1 div41+1 | Mode 2/3: if we're reading the denominator, just add the place value. | | [3,3] plc29−1 plc19+1 div41−1 div23+1,[3,3]→[1,1] plc29−1 plc19+1 st37+1 | Mode 2/3: if we're reading the numerator, increment the remainder, or if it's equal to divisor−1, zero it (using mode 1) and increment the quotient. Exit to mode 4/5. | | [12,13] plc29−1 | Mode 12/13 (found the sentinel digit): discard the place value. | | [13,13] st37−1 st17+1 plc19+1 | Mode 13 (finished with the denominator): copy it to the place value and go to mode 9 to read the numerator. | | [12,12]→[0,0] div23−1,[12,12] prg11−1 prg31+1,[12,12] st17−1 | Mode 12 (finished with the numerator): if the remainder is nonzero then go to mode 0; otherwise, restore the original program, discard the divisor (see mode 10) and old state, and go to mode 8 to read the denominator. | | [1,7]→[3,9],[8,13]→[4,9] | Default mode transitions. | ### Can this be improved? Probably. It's just a PITA to satisfy all the constraints: * The modes have to be numbered to take advantage of default fallthrough, and also to keep modes with shareable instructions together, and also the halting mode has to be on the edge so it doesn't get caught in the default-fallthrough whirlpool. * One-time adjustments to registers can only be done during mode changes, but most of the mode changes are shared across a large number of modes. For example, m90's program tracks the place value minus 1. But that means that after you multiply it by b, you have to add b−1. But the mode transition where that would need to happen in my program is handled by the default rule, so I can't do it, or at least I don't see how. * The challenge has strict input requirements that limit potential optimizations. For example, if I could compute the quotient (new state) minus one, it would avoid an off-by-one error when the state is added to the place value which would otherwise be 1. But then there would be no point in the loop where the interpreter state had the form \$p^\text{state}q^\text{program}n\$; the closest you'd get would be \$p^{\text{state}-1}q^\text{program}n\$. I think the ripest candidate for improvement is the unshared fractions in modes 4 and 5. The mode offsets of the jumps are different, but that's easy to fix by rearranging the modes. plc19+1 could be shared if I could subtract one from the state somewhere (as mentioned above). div41−1 could be eliminated by decrementing the program before parsing the denominator. The failed-division path does that anyway, but there's no place to do it in the successful-division path. That would be a nonissue if the challenge allowed the input state to be \$p^\text{state}q^{\text{program}-1}n\$. (It's funny that both input parameters seem to be improved by subtracting 1.) [Answer] Here are a few solutions not written by me! If one of these is yours, please feel free to post it separately and I'll remove it from this answer. These have all been in [this comment](https://codegolf.stackexchange.com/questions/204779/final-tribute-to-john-conway-fractran-self-interpreter#comment485938_204779) for a while, but I'm converting it to an answer for greater visibility. ## Collected Answers * [48 fracs](http://lomont.org/posts/2017/fractran/) by [Chris Lomont](http://lomont.org) –– [SE profile](https://stackoverflow.com/users/5637097/chris-lomont), I think. * [84 fracs](https://stackoverflow.com/a/1750591) by [Hai-Anh Trinh](https://github.com/aht) –– [SE profile.](https://stackoverflow.com/users/191069/hai-anh-trinh) * [1779 fracs](https://stackoverflow.com/a/1773868) by [Jesse Beder](https://bederstudios.com/optia/) –– [SE profile.](https://stackoverflow.com/users/112/jesse-beder) [Generating code.](https://github.com/jbeder/fractran) ]
[Question] [ We say two positive integers are *anagrams* of each other if the digits in one of them (in decimal representation) can be rearranged to form the other. Leading zeros don't count. For example, 110020222 is an anagram of 212102020, but not of 221100011; neither is 22002211 even though it can be written as 022002211. Interestingly enough, every arithmetic sequence of positive integers contains arbitrarily large sets of elements, all anagrams of each other. In this challenge, we use a special case of this fact. ### Task For this challenge, you have to write a program or function in a language of your choice, that takes as input two positive integers: `k` and `N`, and outputs `N` *different* positive integers, all of which are multiples of `k` and anagrams of each other. ### Rules * You can assume `N` is bigger than 1. * Input and output can be taken in any of the standard ways. * Standard loopholes are forbidden. * Output may contain spaces and newlines. ### Winning Criterion This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ### Examples Note that there are more than one possible output (infinitely many, in fact) given any `k` and `N`. Here are some examples: ``` k | N | Possible output -----+-------+------------------ 9 | 4 | 234 | | 243 | | 342 | | 432 -----+-------+------------------ 351 | 6 | 142857 | | 428571 | | 285714 | | 857142 | | 571428 | | 714285 ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda k,N:[k*(10**N**k+10**i)for i in range(N)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFbx88qOltLw9BAS8tPSytbG8TI1EzLL1LIVMjMUyhKzEtP1fDTjP0PEqoACaVpGBrpGGlacSkUFGXmlShU/AcA "Python 2 – Try It Online") For example, `k=12,n=4` produces this list of numbers, written out in lines for clarity, with the `...`'s hiding a big string of zeroes: ``` 1200...0000012 1200...0000120 1200...0001200 1200...0012000 ``` So, we have a prefix of `k`, followed by another `k` in a position that moves one place left each time, and the rest zeroes. We need the prefix because leading zeroes aren't allowed for the anagrams, so we make it so that all the outputs have the same number of digits. We leave enough zeroes to ensure that the right string to never bump into the left one. `N**k` zeroes more than suffices for this, giving extremely big numbers; `N+k` or even `N+log_10(k)` would be enough. Note that Python right-associates `10**N**k` as `10**(N**k)`. Unfortunately this variable bound doesn't lend well to recursive solutions that update `k` as they go. An upper bound on how big `k` can be, even if enormous, would simplify this. [Answer] # [J](http://jsoftware.com/), 18 bytes ``` 10#.[,.[}.[*=@i.@+ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ2U9aJ19KJr9aK1bB0y9Ry0/2typSZn5CsYGimkKZj8BwA "J – Try It Online") [xnor's wonderful technique](https://codegolf.stackexchange.com/a/204064/15469), adapted for J. Be sure to upvote him. ### explanation Taking n=4, k=12 as an example, we notice that... ``` 12 0 0 0 0 0 0 0 0 0 0 0 0 12 0 0 0 12 0 0 0 0 0 0 0 0 0 0 0 0 0 12 0 0 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12 0 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12 ``` is actually just 12 zipped with a (12 + 4) x (12 + 4) identity matrix, multiplied by 12, with the first 12 rows chopped off. Then we convert back to numbers with `10#.` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` m°IL<°+* ``` Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/204064/52210), so make sure to upvote him!! [Try it online.](https://tio.run/##yy9OTMpM/f8/99AGTx@bQxu0D@3U@v/fkssYAA) A more original (although extremely slow) approach, is this **11-[byter](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: ``` ∞*æIù.Δ€{íË ``` [Try it online.](https://tio.run/##ASIA3f9vc2FiaWX//@KInirDpknDuS7OlOKCrHvDrcOL//8xMQoy) (Will time out if \$N\geq3\$..) Both take \$k\$ as first input and \$N\$ as second. **Explanation:** ``` m # Take the 2nd (implicit) input to the power of the 1st (implicit) input: N^k ° # Take 10 to the power that: 10^(N^k) IL # Push a list in the range [1, N] < # Decrease it by 1 to make the range [0, N) ° # Push 10 to the power for each value: [10^0, 10^1, ..., 10^{N-1}, 10^N] + # Add the earlier 10^(N^k) to each * # And multiply it by the second (implicit) input N # (after which the list is output implicitly) ∞ # Push an infinite list of positive integer: [1,2,3,...] * # Multiply each by the first (implicit) input k: [k,2k,3k,...] æ # Take the (lazy) powerset of that infinite list Iù # And only leave the inner lists of a size equal to the second input N .Δ # Find the first inner list which is truthy for: €{ # Sort the digits of each integer in the list í # in descending order (since we aren't allowed to start with a leading 0) Ë # And check if all are equal # (after which the list is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), 101 bytes ``` k,n=input() l=[];m=0;s=sorted while 1:m+=k;l+=m,;t=[x for x in l if s(`x`)==s(`m`)];n==len(t)>exit(t) ``` [Try it online!](https://tio.run/##DcVBDoMgEAXQvaeYJUQW1aZdlPxexJiwKEYiDEamKT09@jZv/8uaeWxtM4zA@1eU7iKm2SbcbEHJh/hP91tD9DS8Uo/Nxh7JWMFUackHVQpMkcJCRbnqNHCdnJ4tA9GzEv32Nch1a/fHYJ4n "Python 2 – Try It Online") Generate all multiples `m` of `k`, each time checking if there are `n` anagrams of `m` in the list of current multiples. The result is printed as exit message. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes ``` ^.+ $*0 0(?=.*¶(.+)) $1$`$1$%'¶ ¶¶.+ ``` [Try it online!](https://tio.run/##K0otycxL/P8/Tk@bS0XLgMtAw95WT@vQNg09bU1NLhVDlQQgVlU/tI3r0LZD24CK/v834zI2NQQA "Retina 0.8.2 – Try It Online") Takes input in the order `N`, `k`. Uses @xnor's algorithm. Explanation: ``` ^.+ $*0 ``` Convert `N` to `N` zeros. ``` 0(?=.*¶(.+)) ``` Match each zero in turn. ``` $1$`$1$%'¶ ``` Output `k`, the zeros to the left of this zero, `k` again, then the zeros to the right of this zero. ``` ¶¶.+ ``` Delete `k`. Using Retina 1 would save 5 bytes, mostly from the use of `L$` which effectively automatically delets `k`: ``` ^.+ *0 L$`0(?=.*¶(.+)) $1$`$1$%' ``` [Try it online!](https://tio.run/##K0otycxLNPz/P05Pm0vLgMtHJcFAw95WT@vQNg09bU1NLhVDlQQgVlX//9@My9jUEAA "Retina – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 12 bytes ``` &A(t^n^A+t^$ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X81RoyQuL85RuyRO5f9/QyMFEwA "cQuents – Try It Online") [Port of xnor's Python answer](https://codegolf.stackexchange.com/a/204064/65836). Go upvote his answer! ## Explanation ``` takes two inputs, A n & output first n terms in sequence each term equals: A( A * ( ) t^n^A 10 ** n ** A + + t^$ 10 ** index ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~61~~ 65 bytes Added 4 bytes to fix a bug kindly pointed out by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s idea in his [Python answer](https://codegolf.stackexchange.com/a/204064/9481). ``` i;f(k,n){for(i=0;i<n;)printf("%d%0*d%0*d ",k,n+k+i,k,n+k-i++,0);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jWydPszotv0gj09bAOtMmz1qzoCgzryRNQ0k1RdVAC4wVlHSAyrSztTMhtG6mtraOgaZ17X@gSoXcxMw8DU2Faq40DUMjHVNNay6YCTF5SkBemoaljgkWUWNTQx0zLOJGpjpGmOK1/wE "C (gcc) – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes Port of Kevin Cruijssen's 05AB1E answer. Don't forget to upvote him! ``` {⍺×(10*⍵*⍺)+10*¯1+⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvrsPTNQwNtB71bgXiXZraQPah9Ybaj3o3A4Vq/6c9apvwqLfvUVfzo941j3q3HFpv/Kht4qO@qcFBzkAyxMMz@L@hQpqCMQA "APL (Dyalog Classic) – Try It Online") ]
[Question] [ # Summary A teacher was told to prepare word problems for the students. She is given a list of equations and told to write them as the corresponding word problem. However, she is very lazy, so she doesn't put much creativity into it. Instead, she simply writes it literally. For example, when she reads `1+1`, she writes `one plus one`, `47 * 2` would turn into `forty seven times two`, and `56.2 / 7.4` would become `fifty six point two divided by seven point four`. Write some code to help this lazy teacher out. ## Details * Numbers may include a decimal point and a negative sign. * Numbers should be written in the short scale. (i.e., `1,000,000,000` is `one billion`) * Numbers can go up to 999,999,999,999,999,999 (`nine hundred ninety nine quadrillion...nine hundred ninety nine`). * Groups of zeros must be left out. e.g. `1,000,000` is `one million` not `one million zero thousand zero hundred`. * There can be arbitrarily many digits past the decimal point. * Digits after the decimal point must be listed digit by digit. e.g. `12.34` is `twelve point three four` not `twelve point thirty four`. * Two numbers are always separated by an operator. * The valid operators are plus (`+`), minus (`-`), times (`*`), and divided by (`/`). * There are no parentheses. * Numbers such as `1234` may optionally include an `and` in their output, as in `one thousand two hundred *and* thirty four`. * Commas and whitespace on the input may be ignored. ## Examples Input: `24 + 65` Output: `twenty four plus sixty five` Input: `3.33333 - 0` Output: `three point three three three three three minus zero` Input: `3.6 * 18.18 / 999.0` Output: `three point six times eighteen point one eight divided by nine hundred ninety nine point zero` Input: `1-1` Output: `one minus one` Input: `1+-1` Output: `one plus negative one` Input: `1,000,000,000 + 0.2` Output: `one billion plus zero point two` Input: `123,000,456,789,012,345.6789` Output: `one hundred twenty three quadrillion four hundred fifty six billion seven hundred eighty nine million twelve thousand three hundred forty five point six seven eight nine` Input: `-4.3 * 7` Output: `negative four point three times seven` Input: `-1-1--1` Output: `negative one minus one minus negative one` [Answer] # JavaScript (ES6), ~~552~~ 532 bytes This filthy monster comes straight from the depths of code-golfing hell. Expects an input string without any whitespace. ``` S=>S[R='replace'](/[\d.,]+|./g,s=>1/s[0]?a(+s[S=0]&&14)+s[R](/(\D?)(\d+)/g,(_,s,n)=>s>','?' point'+n[R](/./g,a):j--*n?(u=a(n%10||14),n>99?a(n[0])+' hundred':'')+((n%=100)<13?a(n||14):n<20?(a(n)||u)+'teen':(a(n/10+18)||a(n/10))+'ty'+u)+a(j+27)+(j>1?'illion':''):'',j=s.split`,`.length):a(S='+-*/'.indexOf(s=='-'&&S||s)+34),a=n=>(s='zero0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir00fif000eigh00twen0thir0for0fif000eigh00thousand0m0b0tr0quadr0negative0plus0minus0times0divided by'.split`0`[n|0])&&' '+s).trim() ``` [Try it online!](https://tio.run/##bZJRb9owEMff9ymsSsM2TsyZAAVah5e9TyqPgNaUOGAULix2aDvluzOHbtI6EcnJ3f//u7vY8iE7Z25b25OPscrNpdCXpU6XqydNa3Mqs62hGzZYrXMZbUQrB7vI6VQN3Ao2i4wJt1pq2PR6asRD/BRQtv624GydCx5Y9iNyEXKdupRGdEHJqbLoqcAr2nXL@PwQx31csEZnDL8qaNvQLMJ0NgsDMMzhgpJ9g3ltcjqnlAsWOK0A@KNKOuZaMcfHISxYSHnbNqHGG4N03gkDBUJNg/wR8858pyJAGTuI4X3oeEjVgtqytBVeZ4QVHbST7lRa/xw9y9Lgzu/5PGNLTUXcH1BpMTdv3wvmtKYx7fWWbeu4SMLPZxp1GnT6y9QVVGjAv1bg97UxUFRNDYU9G3D2DZw5GwRjd3sPaDuwS8ur6l9NGTC/tzWEigLgCkJn4IdcVPVnZ181LsMcjvACvoafTZbXgGaX@W7iqWwcHC2Gt7dH4yC3Z5ubnLy80z9bhecVtuHMez1KqHBc@toeGb9sK3RVaWRZ7VjB7oYjMRnfcf7lPz2RSffEcNOb9NVUqulgNpvJW4SK1S1V3JajsO2/S4Ac3mKGyZUYjSfR/XQWgRpGyWgsJyG5gccjmfTvO@OTwx9IOGiGRBN4IEgeNQm3L0RCcPIviEQQOic0fIqPhHJ@@Q0 "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~434 401 387~~ 359 bytes ``` {~S:g/\d+/{n($//100+64184)x($/>100),$/%100>19&&(n($//10%10+64175),n($!=$/%10)x?$!)||n($/%100+7679),[$,"thousand",|(<m b tr quadr>X~"illion")][+$/.postmatch.words[0].comb(',')]if +$/} /.trans("+,-/*"=><<plus''minus"divided by"times>>).words}o{S:g/\.(\d)+/ point {$0>>.&n}/}o{S:g/[\s|^]0/ zero/}o{S:g/\-(\d)/negative $0/} my&n=(*+1632+|0).uniname.lc.words[2..*] ``` [Try it online!](https://tio.run/##dZPtkpowFIZ/16s4y1Alggn4gdpd6UX0T2fUzqBEzQwES4K7Vt1btwkJu05n6gySc857vh7gSKs8vhdn6O5gAffL@49ve7LKfHLhnktIFIZ@PI5mY/SmzESZKHDJV3VPonm361mRcmjZdIIC5XlaNBL09t19Qter1ugMfxpP5yhYuoEjD2UtUp45wdV7KWADsoLfdZpVyc93h@U5K7mD1kvfJfhYClmkcnvAr2WViWW4xtuy2Hi9oIfWbAdKcwOCZZVy4Tl@MCB9Z5G8vBzzWvR6BeO1cDJ2YhnNYHN2JCuoSBJkqt3KS7Mv9lYZ8gkcS8YlXNwwSXCX34iNL1fi@msdEvhDq7J1rgY6iXC6TyU7UXBDcusU5y5feH0/ikdD/xoiXHPG04LifGvnH2LcX9@fO7uyAi9nnAqkmoljzqTXU4@gh@DS@SLSM@w8rLZFz8bCy2j93Lndh2PwIZ4opXylXCpZWVegtwXB3rSthumM8Ej/YAChVh4qSu1y5vy//4ZXs6YqEUMfohmOZkBgPp/jf0upftDwBMr2B0kpt4GSU@OCT/KgQFA41DyrlK0NaX0mp@kZqYEj1UUXMKOok/L6MGjdzaYf0JtwEIZheylpiIdWuzGvksnRDVoGr6rVcNTkjCdxMJ3NgzAaBqPxBMfKsOntsBa0Wb15TW3dBn2r2rGdEmkmbVtBTwpJG2@A2JULq1CV85Nmbz4H2@KjYlnZ5/kA3BQ1dHWtzsBAGxhEj2Q@EdrTY/Av "Perl 6 – Try It Online") Definitely room for improvement here. I say that, but I keep noticing edge cases I haven't handled `:(`. Assumes that the input has operators separated by whitespace and the negative of a number isn't separated. ### Explanation: ``` my&n=(*+1632+|0).uniname.lc.words[2..*] # Define a helper function # This gets the unicode name, e.g ARABIC-INDIC DIGIT ZERO # or AEGEAN NUMBER ONE HUNDRED # And returns the 3rd word onwards in lowercase e.g. 'zero' or 'one hundred' {S:g/\-(\d)/negative $0/} # Turn dashes before numbers to negative {S:g/[\s|^]0/ zero/} # Handle zeros {S:g/\.(\d)+/ point {$0>>.&n}/} # Replace decimals {~S:g/\d+/ # Replace series of numbers with n($//100+64184)x($/>100) # The hundreds if the num is bigger than 100 $/%100>19&& # If the number is bigger than 19 ( n($//10%10+64175), # The tens number n($!=$/%10)x?$! # And the singles number (if it's not zero) ) || # Else n($/%100+7679) # The name of the number below 20 , # Then [$,"thousand",|(<m b tr quadr>X~"illion")][ # Index into the list of postfixes + .comb(',') # The number of commas $/.postmatch.words[0] # in the rest of the number if +$/ # All if the number is not 0 .trans("+,-/*"=><<plus''minus"divided by"times>>) # Translate operators # And remove commas .words} # And remove all the excess spaces between words ``` [Answer] # Ruby + Swift 4, ~~283~~ ~~279~~ 270 bytes ``` $_=gsub(/(?<=\d)-/,"minus ").gsub(/[*-\/]/,?.=>"point ",?-=>"negative ",?+=>"plus ",?*=>"times ",?/=>"divided by ").gsub(/(?<=^|[^t] )\d+|\d/){`echo "import Foundation var f=NumberFormatter() f.numberStyle = .spellOut print(f.string(from:#$&)!)">.a swift .a`.tr'- ',' '} ``` [Try it online!](https://tio.run/##RY9dT4MwFIbv@ysqLvLVFgqMDSNyt0u98HJsDqTMJkBJKTOL86@LZcZ4knPyPufkfMmxPE/T4jU9DmNpeVb2kOaVjT1ktLwbB2jY5LeydXDu7TyUkfTR6AXvFDRQhjV07FgofmIzu3OxmftQ5miteMuu4Gmo@IlXrILl@X/svHB/2e7VDtp55V7yyrM/D@ztXUCDt72QCm7E2FV6g@jAqZCwTp/GtmRyI2RbKMWkZYOadNfcizo3DKaQDD1rmudRgV7qS62aDEqLo1VL0d7fLu7sG9t4JAUYPnitICkOREkTAxOZ0PyapiBy4yUISTgb9rWKHbomdO0lSUJ8QDEF1J0D8n3/z12fBIAG4ZWjZYxW6wT5NEBhtCSxBoAjEjorgHU/xvRb9PNXw4T75gc "Ruby – Try It Online") I must be mad to propose such a Frankenstein solution, but on one hand, it is very tempting to use Swift's built-in functionality for this task, and on the other hand, processing strings with Regexes in Swift looks to be a golfing catastrophe. Therefore, I decided to do basic string processing in Ruby, but to spell out numbers, I store them in a Swift source file, run Swift in a shell command, and collect the output. I turns out that Swift's "spellOut" number formatter does almost exactly what we need, except inserting unnecessary hyphens for two-digit numbers, as in `twenty-two`. In fact, even the floating point output in the format of `integer part point digit digit...` is good, but here comes the caveat - there is no infinite precision, and with large enough numbers or a lot of decimal digits, the results go wrong. Therefore, I had to separate the integer and fractional parts and to feed the fraction digit by digit. [Answer] # [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 853 bytes ``` xed -i "_*_ [part1]_" +xed _+_plus_ _\*_times_ "_/_divided by_" "_- _minus _" "_-_negative _" +xed "_,[keep][19 chars of 0-9,]_quadr@ _" "_,[keep][15 chars of 0-9,]_tr@ _" "_,[keep][11 chars of 0-9,]_b@ _" "_,[keep][digits],[digits],_b@ _" "_,[keep][digits],_m@ _" "_,_ thousand _" +xed "_ 000[chars]@__" "_ 000__" "_ 00[keep][digit]_ _" "_ 0[keep][2 digits]_ @_" "_ [digit][keep][2 digits]_[part2]hundred @_" "_ [ortext] 0[digit]0_ @[part2]_" "_ [keep][2 digits]_ @_" "_@_illion _" +xed _@11_eleven_ _@12_twelve_ _@1[digit]_@[part2]teen_ _@1_ten_ _@4_forty_ _@[digit]_@[part2]ty_ +xed _@2_twen_ _@3_thir_ _@4_four_ _@5_fif_ _@6_six_ _@7_seven_ _@8_eigh_ _@9_nine_ +xed "_0_ zero _" "_1_ one _" "_2_ two _" "_3_ three _" "_4_ four _" "_5_ five _" "_6_ six _" "_7_ seven _" "_8_ eight _" "_9_ nine _" "_._ point _" +xed "_[white]_ _" +xed "_[lstart] __" ``` [Try it online!](https://tio.run/##dVLbjqMwDH3nKyweW2ASboW3/kcXWcwSSjQUOhDazv5817lQVa0GCXKOfXJsnMzt1/1@Ew2E0vNxg3A415PiFfrelsIebvHcLzN6@GeDSp4EQR8/sJEX2dC2zx9S@hgCnuSwzGAZDuJYK3kRsPr4GBy@hDhXB17C366eZhhbYGEZVPi91M20t1sfquxVpd4k/FXy@aJo5FGquQoe4FcFntYEgurGZa6H5ql3YIwdTLFqj0anIw/0bFYhuLCLxuCKIOxtxgnf8mb0cdUtQzPRaFf1OClxUxUZ2n2MjJzUKX4ptEfZ93IcHj@Ce85R9OIiBtQkRnUV/UUYsra/eivhVKgsSLGlVn40fNNS1FUwnkafoOrktO5cDMqwla0GOc7ypsEO57WfAoU8dhqVOMhB4Dp@@uN/YhrtYDnCOAiLYzqtq4sn@uQm4TIpgq5pSUbEXUYfcwQqbfGOsK5uWYGgG1CWlQi6CUsihPMoB/V0Jw7XTiphj3sN9bOieVSgb8b9HqewhTzzkijRD4TACOewAV5EvIAPKMsyYh6nDKfvFkJaArpZ9JqVQiyKPR4nJppmebAryoDxOEjSLMqJeGEaJWS580LjQy@5MGNZsv8 "sfk – Try It Online") Requires operators and numbers be separated by at least one space character. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~766~~ ... 687 bytes ``` import StdEnv,Text m="" z="zero" @ =digitToInt r=reverse l k=(!!)k o@ ^s=l[s:split" ""one two three four five six seven eight nine"] g s=l[m,m,"twen","thir",s,"fif","six","seven","eigh","nine"] ~['0':t]= ~t ~[a,b,c]= ^""a+" hundred "+ ~[b,c] ~[b,c]|b>'1'=g"for"b+"ty "+ ^""c|c>'2'=g"four"c+"teen"=["ten","eleven","twelve"]!!(@c) ~[c]= ^""c ~_=m $[]=m $[x:y]#(h,t)=span(\e=e>'/'||e==',')if(x<'1')y[x:y] =trim(join" "((case x of'0'=[z];'-'=["negative",$h];'.'=["point":map(^z)h];_=(r[u+v\\u<-r(map~(split[',']h))&v<-[m," thousand":[" "+k+"illion"\\k<-["m","b","tr","quadr"]]]|u>m]))++[?t])) ?['-':t]="minus "+ $t ?['+':t]="plus "+ $t ?['/':t]="divided by "+ $t ?['*':t]="times "+ $t ?t= $t ``` [Try it online!](https://tio.run/##TVLbbtswDH2uvoJli9mu7dROes2itA/bQ4ECHdC@OW7h2HKi1ZYzW86lCPLpy6gk6xYgonmODkmRTAuRqG1ZZW0hoEyk2spyVtUannX2Xc29F7HUrOSI7IPjh6grZPfAMzmR@qV6UJrVvBZzUTeCFfDO7eNj5x2qe/ba8CJq@s2skBoBsVIC9KICPa2FgLxqa8jlXEAjl9BQAAVCTqYalFQCYzYBoy@90kO9EArJTGWNXuNhLnNySWdOoyRrtGQO4k1kBVZfxxw2mpzEG3spOa@IiYswbVVWiwzQhU1kGLY36/HQCi0@wbyqceyiXpkrJErX6dDq7pm2xpQoQVl5RHaXvDhUQZUWcyrg@Ni@Tx0Ke8iass0bL9lpFO/OZX8Vn9hTTzu8mSXKHgkuhta5tV4Lzi3PcmRuLwdUi7Pa3WVc17K0f1ZSUSdtO00aAUuocnoljz7ir5ZPFpWYJJpait7plLCOwWak0dgvk5n9@uEQ/MbtOmrd@WjUDvzaJmJj72YUUeJ46jhf5gOf@o40qKptEpVhP6Ks7ruLsihkpXA0eqcrWNKDx@bRNBX81SZZjXEcr9thGTuO60Z3miy7i6g4MwospWob09FTbVB3j86K/8HzPZjJucxoQuPVP@psT2lZik@B5mQ@93XVaFF2Hp4Yy1uVaioViGfsWSdEL9jRCdgFLYgHC4cYMU@KhyeYCP1IoOHXYGjgnNaVHR1xiGIDVnoq6oWkBd9hn8GjdDRKB37fiNbpYGiBFYMLOFLYh0PSeNu9IOzqkvU6PfMDHwL6voIzCG864Q2cw@3tbSdgoR@y0DWHFwTB3z9pg06Xhd3eDrm4vPKub269IOx6vYvLzhU5zL/o9CjcNfMphk8RAj/8neZFMmm2/sPj9ttKJaVM986PItG03@XWH/8B "Clean – Try It Online") Expects a string without whitespace. [Answer] # [Python 2](https://docs.python.org/2/), ~~790~~ 774 bytes ``` lambda T:B("([+/*-])",lambda m:dict(zip("+/*-",S("z"," plus z divided by z times z minus ")))[m.group(0)],B("([+/*-]|^)-",r"\1negative ",B("[^+/*-]+","{}",T))).format(*[J([g[int(S("\.",j)[0])]+S("z",B("y","illion","z thousandz myz byz tryz quadry"))[len(S(",",m))+~i]+(" point "+J(s[int(c)]for c in S("\.",j)[-1]))*("."in j)for i,j in E(S(",",m))if 0<float(j)+(m<"1")])for m in S("[+/*-]+",T)[T[0]=='-':]]) from re import* E,S,B,P=enumerate,split,sub," ";J=P.join s,e=S(P,"zero one two three four five six seven eight nine"),[B("urty","rty",j)for i,j in E(c+d for d in S(P,"teen ty")for c in S(P,"twen thir four fif six seven eigh nine"))] g=s+S(P,"ten eleven twelve")+e[1:8]+[a+(P+b)*(i>0)for a in e[8:]for i,b in E(s)] g=[(j+" hundred ")*(i>0)+k for i,j in E(s)for k in g] ``` [Try it online!](https://tio.run/##dVRLc9owEL77V@zoUgkL1waSElp66EwvOWUmuTnujMEyiPpBbTkp6eOvp7uSDSRtmcEj7fPbb3e1P5htXU2e8@X9c5GWqyyFu8Unznjsvx2NE8FkLy0XmV4b/qT3nJGKyVvOnphksC@6Fp4g0w86UxmsDngxulQkLHWFSiaEiMtg09TdnocikacEP78IDNWw@6hSm9ToBwWM1PEXq/YxwY9fTN5hhCCvmzI1fBRf83gT68pwhHAfMLkTcZiIxHeI0PuAbroodF3hAdFs665NqwzxHJ4QIEoa/Hzr0qw5ILi4UBXFkkyWQvi/deJzrKvGFMD8a97aZGuRIAJYg67glHgcJUKMOAsYineCLLTckc3nU0idQ/ghL2pEvxM@Lz@wiInEGpd9uHio907Ed1jOcvlm/GaRJMLLm7qERoEu93VjRt5neSs/yZulqrpSNalRst0X2si2W2E32Pvr5U2wQ@xeK9Xylt8gA6qpoa4UmMcayWiUgrzuGsiJ7lZ/h1Y9qAqU3mwNVLpSTMgYaewaQ0za76vS1n4GJMgcfExiFIZAS3FGEokfSbzVzZAyf5WxTygSb7Ns/T4Uqgprge7FA6p9FUeLeeLHqc9v/BUyrj@GNlVKqVQ8XyQO4MoBbG3AmO98BtuuyhocTda7@V/hRTGtDfSVLpvk2ajWtLCE2AP8cTaZgQ@XF0yCLcYcXCV27LEUumuCKL3eYRpM6QdjCK2TJdxNkzv/7@u2hbr1ItoljCCaB9Ec3sLV1VXwV1Qi1G2cbSE1wimo566rZ9tJfB8poYvpZc7nVfpoHFE6iuTg1dV5rZF/0ltGjmv8yk6GYTj8kc8wmAxuK7ep/TtCo9pz9fgCx2Rq3WcXl/Ld/EqG0UROZxfBJV6GSENRfZscRXbL@xS2cYMVjiIaEXcDAjeUg94S11NT9hZuHI8PSp/iGBH3003DWWP@sVtDTeNZMMXeviP8R97ccJ1Pi@2sDXPui40ZO@7PKT81qT/9px@zGY5nNCP3HjWldS50pCFiwks8j1aDVkLiG9R2haEtsSuysKH2jUVqDdgC4@WcLkGj9kW6VviO4guC631mzNjzHw "Python 2 – Try It Online") So many bad practices. This almost hurt to write.... Expects a non-unicode string with no whitespace as input. **Explanation:** ``` # import all functions from re (python regex library) from re import* # rename some repeatedly-used functions/variables for reduced bytecount E,S,B,P=enumerate,split,sub," ";J=P.join # list the names of 0-9 s=S(P,"zero one two three four five six seven eight nine") # generate "twenteen" through nineteen and twenty though ninety, changing "fourty" to forty # using enumerate (E) even though i is not required b/c it's shorter than range(len(x)) # using re.split (S) instead of string.split since it's shorter e=[B("urty","rty",j)for i,j in E(c+d for d in S(P,"teen ty")for c in S(P,"twen thir four fif six seven eigh nine"))] # generate 0-999 # 0-9 g=s+ # 10, 11, 12 +S(P,"ten eleven twelve")+ # remove "twenteen", 13-19 +e[1:8]+ # tens' place + ones' place, if ones' place is not zero +[a+(P+b)*(i>0) ] # for each tens' place in 20-90 for a in e[8:] # for each index, value in ones' places 0-9 for i,b in E(s) # hundreds' place if at least 100, plus tens' and ones' place (already calculated and stored in g from before) g=[(j+" hundred ")*(i>0)+k ] # (s) stores names for 0-9, need index to avoid "zero hundred" for i,j in E(s) # for each hundred, iterate over all values (0-99) already in g for k in g # actual function to call. uses previously declared global variable g. def f(T): # gets the numbers in the supplied string (T) by splitting (T) on any operator character # remove first item if blank (only happens when staring with a - for negative numbers) n=S("[+/*-]+",T)[T[0]=='-':] # triply-nested set of re.subs to convert (T) to a sting of where the operators are replaced by their names and numbers are replaced by "{}" # EX: "-1-1--1" -> "-{}-{}--{}" -> "negative {}-{}-negative {}" -> "negative {} minus {} minus negative {}" # this sub happens last # re.sub (B) any operator, with the operators in a group "()" so that they return in match.group T=B("([+/*-])", ) # an anonymous function to accept match objects (m) from re.sub's search. ,lambda m: # create a dictionary from the combination of operators and their names # like {"+":" plus ",...} # operator names are surrounded by spaces since number names are NOT dict(zip("+/*-",S("z"," plus z divided by z times z minus "))) # from the constructed dictionary, select the operator matched by re.sub's search and return it for replacement [m.group(0)], # this substitution is second # re.sub (B) any operator followed by a minus (-), OR a minus at the beginning of the string # operators/start are grouped, trailing minus is not ,B("([+/*-]|^)-", ) # replace match with the grouped items plus the word "negative" # EX: "-1-1--1" -> "-{}-{}--{}" -> "negative {}-{}-negative {}" ,r"\1negative ", # this substitution is done first # replace any sequence of NON-operators with "{}" # this removes numbers so the names can be inserted later # EX: "-1-1--1" -> "-{}-{}--{}" ,B("[^+/*-]+","{}",T)) # technically the previous construction of (T) and (n) can be placed here to save 5 bytes but my poor eyes can't handle that. # insert constructed names back into original string. # EX: "-1-1--1" -> "negative {} minus {} minus negative {}" -> "negative one minus one minus negative one" print T.format( ) # string.format needs items in array unpacked, or it will attempt to insert the string representation of the array itself *[ ] # for each number pulled from (T), generate names and join generated items back together with spaces # EX: "1,456" -> ["1", "456"] -> ["one thousand", "four hundred fifty six"] -> "one thousand four hundred fifty six" J( )for m in n # split j on periods (.) and take the first item # convert that item into an integer and find the item at that index in g (0-999) [g[int(S("\.",j)[0])]+ ] # insert prefix for millions +, split string on "z" (spaces must be preserved for proper separation) +S("z",B("y","illion","z thousandz myz byz tryz quadry")) # left is largest, so take the item at index (total # of groups - current place - 1) [len(S(",",m))+~i]+ # if group had a period, split string on period and take last item # replace every character in group with number 0-9 name # join them with spaces and add back to rest of group +(" point "+J(s[int(c)]for c in S("\.",j)[-1]))*("."in j) # split number into groups by comma # EX: "123,456" -> ["123","456"] # only return item if j != 0 (avoids returning empty string which will result in too many joined spaces) # OR if m == 0 (avoids not returning anything when should return "zero") for i,j in E(S(",",m))if 0 ``` I reduced by about 150 bytes while writing the explanation. Let it never be said that commenting/reviewing your code isn't helpful! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~315~~ ~~295~~ ~~282~~ 276 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "+-*/"DˆS¡εDõQi'¢…ë'.¡VYнD_i\'¡×ðë',¡DgUε0›i.•6b©•ð“†ìˆÈŒšï¿Ÿ¯¥Š“©'tKJ#'…§«…€µ‚•„í#®#«…—¿áÓÁÏ#«ìD9£©.•4º»Ÿć'Rþн•ŽH$S£“Œšï¿Ÿ¯¥Š“'tK#«„ty«sõšâðý«õšD®'°¡ðì«sâðý«yèð.•cG3₅¦„¥F•8ô'¾ß«…¡›‡È±°#«õªRXN-<èJëõ}}ðý}Yg<i®'¡×šYθSè'…®šðý}}J}s¯`Ã哉´Øè„ƺߓ#¤… by«¸s¨ì¯`ykè}.ιðý„ ð:„¢…Øè'¢…: ``` Takes input without any spaces. [Try it online](https://tio.run/##bVFBaxNBGP0roREW0t3tJJumSelxsRJBsEExILSNSFk8eEgvOSxsK8beBC0oImmntXZj0mSFLsRIWnifeyos/Q3zR@I3W4/uZXbe@@a9N29et7db3sv5fGHRKiwtuDfdBmQauxQ/9gycqOA7DQwb8mnzduZues8NSPpEEYMmpLvzJI2FCqaerYKTSgt9XihSwVcVHNPwpksHyYdE0hjXyQRjnCXHzKFv7D6s5w3WxjkGvKj9IWIVfOHTKujRRR6j/B0RHOKaJH2kPXrPEA3dGk7R13ZlTPE7mfx5Z2zQ1e2MkWT24F4Dp2zxH1f2zDR7ux0M2hTzAEelGYvyv4uRgYjvFtFQ0/@oDoUUabMX647afwsO1MPZfQaqdGngio6ymJDcgQokHeAnIp0zxo@NZ4@sNQrrxDvf13p@c2fN00ZcYSKb6aRBYdbCKJEZ79f9NsZb9CaNsw4jXNJnCnUnXUzpiME8vvGJXIsvgUkbIccdb3VeUejb6S8twsO5HEWrOmn2fCxw95Cr83mx5JhCCLO8XDFXqjVTFEumU67ZFd4UHNvhr2xZxeKSVTGXnRLzjs3zK6WqWBS2cAriLw) or [verify all test cases](https://tio.run/##bVHfa9NQFH7PX1FWIZAmaX41TcpgL0GlguCKYkFwVmQEH3zoEAIG4sS6N0GFDZFu2ZymtrYRGqmVbnCOeRqE/Q35R@q5qb4tcHPvOec73/fdc591H3XcJ8sXz70NviF6znKtIgnVNeei14IwSxxM7rg8HOfBFxzyMoT32pcL56H7gIcQ9zGmpAihs303S5Q8mLtyHhybHRjQhnEefMqDIxxd9HAvfZeGOIHzdAYTOE2PqAYDfudWs8wTN3yFIW357giSPPhI3XnQx@9lGJdXheADnGOI7/ElvqUUjhwbTmDA5AyYw@909ucNv4lnlwvKpIub11pwQhJXqJJmwdnf8WDYxYQAZBUXREpnB8Y8xHS3GEes/K/kYYQxE3t8Q893XwMZ6sPpdUpYOOXhDA8LmxDSDPIgxD34ATHzmcC3zfu3pXWMmkiR7zM@v7297jIhGmEatrNZC6NiCuM0LOp@0@/CZAtfZUkxwximeIARm0kP5nhIyTJ8po5Shy4Bsy5EZHey5T3FyJezX4yEwKUSxg3mtHg@Ilg9ZGMpws8NmC41o2LWOF3W2ScpdDIF1ZJVq2rbtqxwqqRyaoX9REVR/q@KImucqulFbNRMsW7ZoqJqom7UZJMCTjJkXahzEvVLrPtKrF1ghZW6QTi1KpliTdeorsuEr2sW01J0QfkL). **Explanation:** ``` "+-*/" # Push string "+-*/" Dˆ # Duplicate it, pop the copy, and push it to the global array S¡ # Split the input by any "+", "-", "*", or "/" ε # Map each number to: DõQi # If the item is empty (happens for negative numbers) '¢… '# Push string "negative" ë # Else: '.¡ '# Split by "." VY # Store it in variable `Y` н # Take the first number (the integer part) D # Duplicate this integer part _i # If the integer part is exactly 0: \ # Discard the duplicated integer part '¡× '# Push string "zero" ð # Push a space " " ë # Else: ',¡ '# Split by "," DgU # Pop and store the amount of items in variable `X` ε # Map each part to: 0›i # If it's larger than 0: .•6b©• # Push string "thir" ð # Push a space " " “†ìˆÈŒšï¿Ÿ¯¥Š“ # Push string "four five six seven eight nine" © # Store it in the register (without popping) 'tK '# Remove all "t" (so "eight" becomes "eigh") J # Join it together with the "thir" and space # # Split by spaces '…§ '# Push string "teen" « # And append it to every string in the list # (We now have ["thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]) …€µ‚•„í # Push string "one two three" # # Split by spaces ® # Push the string from the register ("four" through "nine") #« # Split by spaces, and merge both lists together …—¿áÓÁÏ # Push string "ten eleven twelve" #« # Split by spaces, and also merge both lists together ì # Prepend "one" through "twelve" before "thirteen" through "nineteen" D9£ # Duplicate it, and take the first nine ("one" through "nine") © # Store it in the register (without popping) .•4º»Ÿć'Rþн• '# Push string "twenthirforfif" ŽH$ # Push integer 4433 S # Split to digits: [4,4,3,3] £ # And split the to parts of that size: ["twen","thir","for","fif"] “Œšï¿Ÿ¯¥Š“ # Push string "six seven eight nine" 'tK '# Remove all "t" (so "eight" becomes "eigh") #« # Split by spaces, and merge both lists together „ty # Push string "ty" « # And append it to every string in the list # (We now have ["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]) s # Swap so the list "one" through "nine" is at the top again õš # Prepend an empty string to that list â # Create every possible pair of "one" through "nine" with "twenty" through "ninety" ðý # Join each pair with a space delimiter « # Merge the "twenty" through "ninety nine" list with "one" through "nineteen" õš # Prepend an empty string to that list D # Duplicate the entire list ® # Push the string from the register ("one" through "nine") '°¡ '# Push string "hundred" ðì # Prepend it with a space " " « # Append it to every string in the list # (We now have ["one hundred","two hundred",...,"nine hundred"]) s # Swap the two lists â # Create every possible pair of "one hundred" through "nine hundred" with "" through "ninety nine" ðý # Join each pair with a space delimiter « # Merge the "one" through "ninety nine" with "one hundred " through "nine hundred ninety nine" # (We now have ["","one",...,"nine hundred ninety nine"]) y # Get the current number of the map è # And index it into this list ð # Push a space " " .•cG3₅¦„¥F• # Push string "quadrilltrill" 8ô # Split into pieces of size 8: ["quadrill","trill"] '¾ß '# Push string "ion" « # Append it to every string in the list …¡›‡È±° # Push string "billion million thousand" # # Split by spaces « # And merge both lists together õª # Append an empty string R # Reverse the list # (We now have ["","thousand","million","billion","trillion","quadrillion"]) X # Push variable `X` N- # Subtract the map-index from it < # Subtract an additional 1 è # And index it into the list J # Join the stack together ë # Else: õ # Push an empty string "" } # Close the if-else } # Close the map ðý # Join the mapped values with space delimiter } # Close the if-else Y # Push variable `Y` g<i # If its length is exactly 2: ® # Push the string from the register ("one" through "nine") '¡× '# Push "zero" š # Prepend it to the list Yθ # Push variable `Y` again, and leave the second number (the decimal part) S # Split it to digits è # And index each into the list '…® '# Push string "point" š # Prepend it in front of that list ðý # Join the list with space delimiter } # Close the if } # Close the if-else J # Join the stack together } # Close the map s # Swap to take the (implicit) input again ¯` # Push the global array, and dump it's content (string "+-*/") à # Only keep all "+", "-", "*", and "/", and remove everything else ε # Map each to: “‰´Øè„ƺߓ # Push string "plus minus times divided" # # Split by spaces ¤ # Take the last item (without popping the list) … by« # Append it with string " by" ¸ # Wrap it to a list: ["divided by"] s # Swap to take the list again ¨ # Remove the last item ì # Prepend it in front of the list: ["plus","minus","times","divided by"] ¯` # Push the global array, and dump it's content (string "+-*/") yk # Push the index in this string for the current map-value `y` è # And use that index to index into the string-list } # Close the map .ι # Interweave the list of numbers and list of operators ðý # Join everything with space delimiter „ ð: # Replace every two spaces for a single space „¢…Øè'¢…: '# And replace every "negative minus" with "negative" # (and output the result implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress strings not part of the dictionary?*, and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * (*How to use the dictionary?*) -- `'¢…` is `"negative"`; `'¡×` is `"zero"`; `“†ìˆÈŒšï¿Ÿ¯¥Š“` is `"four five six seven eight nine"`; `'…§` is `"teen"`; `…€µ‚•„í` is `"one two three"`; `…—¿áÓÁÏ` is `"ten eleven twelve"`; `'°¡` is `"hundred"`; `'¾ß` is `"ion"`; `…¡›‡È±°` is `"billion million thousand"`; `'…®` is `"point"`; and `“‰´Øè„ƺߓ` is `"plus minus times divided"`. * (*How to compress strings not part of the dictionary?*) -- `.•6b©•` is `"thir"`; `.•4º»Ÿć'Rþн•` is `"twenthirforfif"`; and `.•cG3₅¦„¥F•` is `"quadrilltrill"`. * (*How to compress large integers?*) -- `ŽH$` is `4433`. ]
[Question] [ Given a set of two strings guaranteed to be the same length, print their *criss cross*. The *criss cross* of two strings is obtained as follows. 1. Yield the second character of the second string, then the first character of the first string. 2. Yield the first character of the second string, then the second character of the first string. 3. Discard the first character of each string. 4. If the strings have more than one character each, go back to step 1. For example, if the two strings are ``` Truck Tower ``` the *criss cross* is ``` oTTrwroueuwcrcek ``` as illustrated in the following diagram. ![diagram](https://i.stack.imgur.com/YNN9b.png) Each color represents a different iteration of criss-crossing. The numbers show the corresponding character's indices in the output. [Answer] ## JavaScript (ES6), 51 bytes ``` f=([G,...O],[L,...F])=>O[0]?F[0]+G+L+O[0]+f(O,F):'' ``` ``` f=([G,...O],[L,...F])=>O[0]?F[0]+G+L+O[0]+f(O,F):'' console.log(f("Truck", "Tower")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes ``` żṚj@¥2\U ``` [Try it online!](https://tio.run/##y0rNyan8///onoc7Z2U5HFpqFBP6////kKLS5Oz/IfnlqUUA "Jelly – Try It Online") ### How it works ``` żṚj@¥2\U Main link. Arguments: s, t (strings) Arguments: "Truck", Tower" ż Ziphwith; create all pairs of corresponding characters. Return value: ["TT", "ro", "uw", "ce", "kr"]. 2\ Reduce each pair of adjacent strings by the quicklink to the left. ¥ Combine the two links to the left into a dyadic chain. Ṛ Reverse the left string. j@ Join the second string, using the previous result as separator. Map: "TT", "ro" -> join("ro", "TT") -> "rTTo" "ro", "uw" -> join("uw", "or") -> "uorw" etc. Return value: ["rTTo", "uorw", "cwue", "kecr"] U Upend; reverse each string. Return value: ["oTTr", "wrou", "euwc", "rcek"] (implicit) Flatten and print. ``` [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda s,t:s[1:]and t[1]+s[0]+t[0]+s[1]+f(s[1:],t[1:]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoVinxKo42tAqNjEvRaEk2jBWuzjaIFa7BEQUg7hpGmBpnRIQqfm/oCgzr0QjTUM9pKg0OVtdR0E9JL88tUhdU/M/AA "Python 3 – Try It Online") [Answer] ## [Haskell](https://www.haskell.org/), ~~44~~ 38 bytes *Crossed out 44 is still 44* ``` [_]#_="" (a:b)#(x:y)=y!!0:a:x:b!!0:b#y ``` Slightly less golfed / maybe a little more readable: ``` [_] # [_] = "" (a:b:bs) # (x:y:ys) = y:a:x:b:((b:bs) # (y:ys)) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes ``` param($a,$b)-join($a|% t*y|%{$b[+$i],$a[$i-1],$b[$i-1],$a[+$i]*!!$i++}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUzcrPzMPyK5RVSjRqqxRrVZJitZWyYzVUUmMVsnUNQQykmCMRLCMlqKiSqa2dq3m////Q4pKk7P/h4DMBgA "PowerShell – Try It Online") Less golfed: ``` param($a,$b) -join( $a|foreach ToCharArray|foreach{ # transform each string from $a to an array and apply for each char... $CrissCross = $b[+$i],$a[$i-1],$b[$i-1],$a[+$i] $NotFirst = !!$i++ # =0 if $i is 0; =1 if $i is not 0 $CrissCross*$NotFirst # repeat the $CrissCross array $NotFirst times } # and implicitly output ) # join all outputed chars to one string and implicitly output it as result ``` [Answer] # PHP>=7.1, 64 bytes ``` for([,$a,$b]=$argv;$c=$b[++$i];)echo$c,$a[$i-1],$b[$i-1],$a[$i]; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/7d342a9c2328277e0a44e04cdc63c6fc76b37c91) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 203 bytes ``` param($a,$b)$s=$k=@() function q($x){$u=$x|% t*y;($u|%{$u[--$q]})-join''} $a|% t*y|%{$s+=$_+$b[($i++)]} $n=1;$s|%{$k+="$($s[$n][0])$(q($s[$n-1]))$($s[$n][1])";$n++} ($k[0..($k.length-2)]|%{q($_)})-join'' ``` [Try it online!](https://tio.run/##PY/BDoIwEETvfIUxQ@haS9QraeJHeGsagwQVwSIUIkb59lpCwmky83Y3O6/6nbf2nleVc6@0TZ8M6RYXgpUo5ZFRcO1N1hW1WTUMA33RSwy/cNVtPglD/wt9ooRAo0cSj7owUTQGSOeJiVoucea4KIaCc9KeGrlPYCdYcrkGg1UwWu00gTWzE3tNtBBv1gkM52PAUKpdHHuJq9zcurs4kPan/N6Zlhecc6e2z0p3mvr9AQ "PowerShell – Try It Online") golfed, used negative indexing iteration for reversing array # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 210 bytes ``` param($a,$b)$s=$k=@() function q($x){$u=$x|% t*y;[array]::reverse($u);$u-join''} $a|% t*y|%{$s+=$_+$b[($i++)]} $n=1;$s|%{$k+="$($s[$n][0])$(q($s[$n-1]))$($s[$n][1])";$n++} ($k[0..($k.length-2)]|%{q($_)})-join'' ``` [Try it online!](https://tio.run/##PY/RisIwFETf@xVFRsw126L72BLwI/oWgkTJrrXdVJNmV9F@ezai@HQZzsww9zT8GecPpu9jPGmnfxj0B3YEL9CJDaPsK9j92A42PzNc6IYgcLnP83F5raV2Tl9VVTnzm1oMQ6AaoTgOrV0spgz6abzPb/BcYMuxkwwt56QStWJdwz9gx8UMDF7CKrlSBHZ@qmKtiN4kiVkNy/mUMXRyVZbplL2x3@Oh@CSVqlJuSxO9JsQYGxf2XWweb/4D "PowerShell – Try It Online") To Criss-Cross the string, I use the following algorithm: * Take two strings: `Truck` and `Tower` * Zip them and form a new array. Two zip them means to pair each character in the string with another, so it results an array with these 5 elements: `TT ro uw ce kr` * Iterate the array in `0,1` `1,2` `2,3` pairs. So it results a new array in `TT ro` `ro uw` `uw ce` `ce kr` form. * Iterate the array again and swap the elements in each iteration and reverse the new second element. So it results `ro TT` `uw or` `ce wu` `kr ec` * Reverse each element in the array again and join them `oTTrwroueuwcrcek`! **Code explanation** * First take two parameters `$a` and `$b`, it is done using `param()` block * Then define two empty arrays `$s` and `$k`, in Powershell Empty array is `@()` * Then define a function `q` to reverse strings (I wonder why there is no string `.reverse()` method on .NET), First it takes a string `$x`, then defines `$u` as the character array of `$x` (`t*y` is the shorthand for `ToCharArray()` .NET string method, Powrshell can automatically expand it using `Foreach` loop), then reverse the `$u` array in-place using the `reverse()` static method of `[array]` type (`::` is used to invoke a static method), and at last, join the `$u` array with seperator `''` meaning nothing (`-join` is an operator which does that), which result in the reversed string * Then again iterate over the character array of first string (`$a`, I have said in the previous step how character array works), and build a string with the each element of array (`$_` represents that, it is an automatic variable which contains the iterated element in an object supplied from pipeline) and `$i++`th index of `$b` string (You can see that I haven't defined `$i` anywhere, because it is not needed, in powershell non-declared variables are automatically assigned to 0, `++` operator increments a variable, and surrounding parentheses around this increments and then outputs the variable, no need to explicitly increment and use latter), and each builded string is added to the `$s` array through the assignment operator `+=` (Does the 2nd step in algorithm, no builtin Zip function in powershell) * Then I declare another variable `$n` to value of 1 (a semicolon `;` is used to seperate statements and fit in a single line), iterate over the `$s` array, and build a string with the first character in `$n`th indexed element of the `$s` array, then `$n-1`th indexed element in the `$s` array and then the second (In fact the last, but negative indexing with `-1` would cost one more precious byte) character in `$n`th indexed element of the `$s` array and append to `$k` array using `+=` assignment operator, and increment `$n` variable using `++` operator at end (Does the 3rd and 4th step in algorithm, In python and some other languages it would be easier using enumeration and slicing) * Then I iterate in the `$k` array with the last element removed (In powershell .NET `.RemoveAt()` method for removing array elements using index don't work for normal arrays), to do this I used indexing, first started index from 0 and ended 2 subtracted from array length, and `..` range operator is used to multiple index here, and I then apply `q()` function (reverse, that I built earlier), and parenthesise the whole expression to form an array, and then join it with `''` seperator using `-join` operator, and the string is implicitly outputted (Does the last step in algorithm, .NET has severe lack of builtins, at least it should have a map function!) [Answer] # [J](http://jsoftware.com/), 14 bytes ``` [:,19&A.@,;._3 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o610DC3VHPUcdKz14o3/a3JxpSZn5Cuo54eEFJUX5ZemlpYnFyWnZqsr6FoppCmohxSVJmer61iph@SXpxap/wcA "J – Try It Online") J's "Max cubes" verb `;._3` is made to order here. It works by creating a maximal "sliding window" and then using that to tile a matrix. So for example if we just box things to see how it works: ``` echo i.2 6 0 1 2 3 4 5 6 7 8 9 10 11 echo <;._3 i.2 6 ┌───┬───┬───┬────┬─────┐ │0 1│1 2│2 3│3 4│ 4 5│ │6 7│7 8│8 9│9 10│10 11│ └───┴───┴───┴────┴─────┘ ``` Now we just flatten each of those boxes `,`, apply the required permutation `19&A.`, and flatten the final result `[:,`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes ``` ,/{(|x),y}.'+2':' ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs9LRr9aoqdDUqazVU9c2UrdS5+JK01AKyS9PLVKyVgopKk3OVtIEANRcCsA=) Takes (implicit) input as a list of two strings, e.g. `f ("Tower"; "Truck")`. * `+2':'` take 2-length sliding windows, transposing the results to obtain `(("To";"Tr");("ow";"ru");("we";"uc");("er";"ck"))` * `{(|x),y}.'` apply the desired transformation to each pair of the above * `,/` flatten the result [Answer] # C++14, ~~115~~ 112 bytes As unnamed lambda, parameters should be like `std::string`: ``` #define P putchar( [](auto A,auto B){for(int i=0;++i<A.size()&&i<B.size();P B[i]),P A[i-1]),P B[i-1]),P A[i]));} ``` Ungolfed and usage: ``` #include<iostream> #include<string> using namespace std; #define P putchar( auto f= [](auto A,auto B){ for(int i=0; ++i<A.size() && i<B.size(); P B[i]), P A[i-1]), P B[i-1]), P A[i])); } ; int main(){ string A="Truck",B="Tower"; f(A,B); } ``` [Answer] # [Factor](https://factorcode.org/), 101 bytes ``` 2 clump [ reverse 1 group ] map concat swap 2 clump [ 1 group ] map concat swap [ write write ] 2each ``` [Try it online!](https://tio.run/##dYwxDsIwFEN3TmHlBnSEAyAWFmCqOkRfpkRtk/CbEHH6EAkkJhY/D8@@WUlB6/V8PB12mKieM6IypVdU5xNWPjK9cMWoIUfnR7iA/cZcNMtkGkOhmtpB5rxE9FA@qSux/SwwYLERErzYdlda/7n/nR5FXeI3B3S0cq/1DQ "Factor – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes ``` Z2lƛṠ÷$Ṙj ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiWjJsxpvhuaDDtyThuZhqIiwiIiwiVHJ1Y2tcblRvd2VyIl0=) ``` Z # Zip 2l # Slices of length 2 ƛ # Map... Ṡ # Stringify ÷$Ṙj # Join second by first reversed ``` ]
[Question] [ Given a number *N*, draw a left aligned *N*x*N* board of numbers, leaving 1 blank (as a space) (I will show diagrams with *N*=5) ``` 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ``` Your job is to construct the Sieve of Eratosthenes, step by step. First, start with 2. It's prime, so leave it there, and replace all other numbers divisible by 2 with the proper number of spaces. ``` 2 3 5 7 9 11 13 15 17 19 21 23 25 ``` Next, go to the next unprinted number (`3` in this case) and do the same. ``` 2 3 5 7 11 13 17 19 23 25 ``` And so on, until you reach *N*. You need to first print the complete grid, and every time you go to a new number, print the board with the multiples removed. Make sure you print a blank line in between! ## Examples Text in parenthesis `()` are just for reference, you don't need to print it *N* = 2: ``` 2 (complete grid) 3 4 2 (remove multiples of 2) 3 ``` *N* = 3: ``` 2 3 (complete grid) 4 5 6 7 8 9 2 3 (remove multiples of 2) 5 7 9 2 3 (remove multiples of 3) 5 7 ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṿ€“1“ ”ys³G >®i©1ḍoṛ®¦ ²R;1©ÇÐĿÑ€Y ``` [Try it online!](http://jelly.tryitonline.net/#code=4bm-4oKs4oCcMeKAnCDigJ15c8KzRwo-wq5pwqkx4biNb-G5m8KuwqYKwrJSOzHCqcOHw5DEv8OR4oKsWQ&input=&args=NQ) ### How it works ``` ²R;1©ÇÐĿÑ€Y Main link. Argument: n (integer) ² Yield n². R Range; yield [1, ..., n²]. 1© Yield 1 and copy it to the register. ; Append 1 to the range. This is the initial state. Let's call it S. ÇÐĿ Call the second helper link until the results are no longer unique. This returns all unique results as an array. Ṅ€ Call the first helper link on each result. Y Join, separating by linefeeds. >®i©1ḍoṛ®¦ Second helper link. Argument: S (state) >® Compare all integers in S with the value in the register. i 1 Find the first index of 1 (i.e., the first number that is greater than the register. © Copy the index to the register. Let's call the index p. ḍ Test all numbers in S for divisibility by p. This yield 1 for multiples of p, 0 otherwise. o Logical OR; replace 0's with the corresponding values of S. ṛ®¦ Replace the 0 at index p with the corresponding element of S (p). For the purposes of the explanation, S is now the updated state. Ṿ€“1“ ”ys³G First helper link. Argument: A (array) Ṿ€ Uneval each; convert all integers in A into strings. “1“ ”y Replace each string "1" with the string " ". s³ Split into chunks of length n (command-line argument). G Grid; separate row items by spaces (left-padding since the row items are strings), the rows themselves by linefeeds. ``` [Answer] # Perl, ~~250~~ ~~243~~ ~~231~~ ~~202~~ 157 bytes ``` $n=<>;@a=0..($e=$n*$n);$a[1]=$";for$p(1..$n){next if!$a[$p];for(1..$e){$a[$_]=""if!($p~~[(1,$_)]||$_%$p);printf"%-*s",1+length$e,$a[$_];say""if!($_%$n)}say} ``` [Test the current golf online!](https://goo.gl/2pXEWQ) (be sure to run as `perl -M5.010 main.pl`) The two literal newlines each save 1 byte in place of \n. Sample output (input of 7): ``` 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 2 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 2 3 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 49 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 ``` I'm positive I didn't golf it very well, so when I get home I'll take another look at it to see just how much I can shave off. Edit 1: -7 bytes (changing "print sprintf" to the obvious "printf") Edit 2: Saved 12 bytes by using $d explicitly in the one place it was called instead of creating a separate variable, by combining some declarations, and by eliminating one of my conditions for the `next` statement inside the first `foreach` loop by adding a space somewhere else. An additional 29 bytes were golfed out by reworking two for loops into a single loop, eliminating two variable declarations, and turning `unless` statements into if-not statements. Declaring `my$e=$n*$n;` then replacing the three instances of $n\*$n with $e (allowing me to drop a paren for one of them) turned out to yield ±0 bytes, but I kept it in anyway. Edit 3: Thanks to @Dada, another 40 bytes were golfed out (variable declarations, 'foreach' becoming 'for', implicit $\_ in several locations, and cutting down on the printf statement size). An additional 1 byte was shaved off by turning `if!($c%$p||$c==$p||$p==1)` into `if!($p~~[(1,$_)]||$_%$p)`. Unfortunately, the [] around the array is necessary, because the smartmatch operator ~~ is still experimental and doesn't seem to work properly on actual arrays, but does work on references to them instead. 4 more bytes were removed by removing two semicolons and an empty set of quotation marks after the last `say`. [Answer] # PHP, 155 Bytes ``` for(;$d++<$n=$argv[1];$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))for($i=$d*$x=$d>1;$n**2>=$i+=$d;)$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1); ``` @Crypto -3 Bytes Thank You @Titus -6 Bytes Thank You [Try it](http://sandbox.onlinephpfunctions.com/code/4e0784d5a9a5633acbb7f18580e048d49554af0e) First time that I use print in a after loop condition Breakdown ``` for(;$d++<$n=$argv[1]; $x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l)) #after loop print the grid if $d = 1 or is prime for($i=$d*$x=$d>1;$n**2>=$i+=$d;) $a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1); #fills the array at first run and replace positions with space in the next runs ``` Previous Version 174 Bytes ``` for(;$d++<=$n=$argv[1];!($d<2||$a[$d]>0)?:print chunk_split(join($a),$n*$l)."\n")for($i=$d<2?1:2*$d;$i<=$m=$n**2;$i+=$d)$a[$i]=str_pad($d<2?($i<2?"":$i):" ",$l=strlen($m)+1); ``` [Answer] # R, ~~195~~ ~~191~~ ~~185~~ 204 bytes ``` f=function(N){a=b=1:N^2;i=1;a[1]="";S=sprintf;while(i<=N){for(j in b)cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),if(j%%N)"" else"\n");cat("\n");i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1]}} ``` Thanks to @Billywob for 6 extra bytes saved! Indented, with newlines: ``` f=function(N){ a=b=1:N^2 #Initial array i=1 #Turn counter a[1]="" #1 never shown S=sprintf while(i<=N){ for(j in b) cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""), if(j%%N)"" else"\n") #Newline at end of row cat("\n") #Newline between turns i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1] #Select next prime as next i } } ``` Usage: ``` > f(2) 2 3 4 2 3 > f(3) 2 3 4 5 6 7 8 9 2 3 5 7 9 2 3 5 7 > f(9) 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 2 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 2 3 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 49 53 59 61 67 71 73 77 79 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 > f(12) 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 2 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 2 3 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97 101 103 107 109 113 115 119 121 125 127 131 133 137 139 143 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 49 53 59 61 67 71 73 77 79 83 89 91 97 101 103 107 109 113 119 121 127 131 133 137 139 143 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 121 127 131 137 139 143 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 ``` [Answer] # Python 2, ~~199 202~~ 201 bytes +3 bytes (I wasn't stopping early) -1 byte thanks to @Oliver (missed a space) ``` def f(n,p={()}): m=n*n;g=['']+[[i,''][any(i>n and i%n<1for n in p)]for i in range(2,m+1)];x=min(set(g)-p);i=0 while i<m+n:print' '.join('%%%ds'%-len(`m`)%v for v in g[i:i+n]);i+=n if x<=n:f(n,p|{x}) ``` **[repl.it](https://repl.it/EBNG/4)** [Answer] # Groovy, ~~201~~ ~~195~~ 191 Bytes ``` {n->a=(1..n*n).toArray();y={a.collect{(it?"$it":"").padRight((""+n*n).size())}.collate(n).each{println it.join(" ")}};a[0]=0;y(a);(2..n).each{b->(b+1..n*n).each{if(it%b==0){a[it-1]=0}};y(a)}} ``` This is an absolute cluster... The left-align murdered my byte count. But hey, it works. Here's the output for 4: ``` 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 3 5 7 9 11 13 15 2 3 5 7 11 13 2 3 5 7 11 13 ``` # Ungolfed: ``` { n-> a = (1..n*n).toArray(); // Create initial array. y = { // Createa printing utility closure. a.collect { // Create an array collection of... (it ? "$it":"").padRight((""+n*n).size()) // If 0, store "", else store number & right pad it. }.collate(n).each{ // Collate by n (break into nxn grid). println it.join(" ") // print each separated by spaces. } }; a[0]=0; // Remove first element. y(a); // Print initial status. (2..n).each{ // From 2 to n... b-> (b+1..n*n).each{ // From current number + 1 to end of grid... if(it%b==0){ // If current grid position is divisible... a[it-1]=0 // Replace with 0. } } y(a) // Print it. } } ``` ​ [Answer] # Perl, ~~115~~ ~~114~~ ~~113~~ 112 bytes Includes +1 for `-a` Run with input number on STDIN: ``` perl -M5.010 sieving.pl <<< 7 ``` `sieving.pl`: ``` #!/usr/bin/perl -a $_*=$_;$a.="$_"x$|++|$"x"@+".($_%"@F"?$":$/)for/\d+/..$_;*_=a;s^^$$_++||say;$.++;s//$&%$.|$&==$.?$&:$&&$_/eg^eg ``` Needs a recent enough perl so that `-a` implies `-n`. If your perl is too old add a `-n` option. Prints a trailing newline which is allowed. [Answer] ## JavaScript (ES6), ~~190~~ 189 bytes Directly prints to the console. ``` f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''} `.slice(0,`_${w*w}`.length)+(++x%w?'':` `)).join``),f(w,k,a.map(n=>n==k|n%k&&n))) ``` ### Demo ``` f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''} `.slice(0,`_${w*w}`.length)+(++x%w?'':` `)).join``),f(w,k,a.map(n=>n==k|n%k&&n))) f(5) ``` [Answer] ## Batch, 464 bytes ``` @echo off set/an=%1,s=n*n,t=s,c=1 set p= :l set/ac+=1,t/=10 set p= %p% if %t% gtr 0 goto l for /l %%i in (1,1,%1)do call:i %%i exit/b :i set l= set/af=0 call:f %1 %1 if %f%==0 for /l %%j in (1,1,%s%)do call:j %1 %%j exit/b :j set/am=%2,f=!(m-1),g=%2%%n call:f %1 %2 if %f% gtr 0 set m= set m=%m% %p% call set l=%%l%%%%m:~0,%c%%% if %g%==0 echo(%l%&set l= if %2==%s% echo( exit/b :f for /l %%l in (2,1,%1)do if %%l neq %2 set/af+=!(%2%%%%l) ``` This was somewhat laborious. Explanation: Starts by squaring `n` so that it can calculate the desired column width `c`, and the appropriate amount of padding `p`, using the loop `:l`. The outer loop from `1` to `n` then runs once for each grid, calling the subroutine `:i`. First the value is checked to see whether it is 1 or prime; if not then that grid is skipped. The inner loop from `1` to `n*n` then handles the rows and columns of the grid, calling the subroutine `:j`. Each value is checked to see whether it is one of the prime numbers found so far, or if none of the prime numbers found so far divide it. If so then the value is concatenated to the output buffer, which is then padded to the desired column width. The buffer is printed and cleared every `n` lines, and an extra blank line is added at the end of the grid. The `:f` label denotes the factor-checking subroutine; f(x,y) adds 1 to `f` for each integer between 2 and `x` that divides `y`, excluding `y` itself. [Answer] # J, 125 bytes ``` p=:3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y' 3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y' ``` This is explicit, not tacit J, but there should be a way to golf it tacitly. ## Usage ``` p =: 3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y' f =: 3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y' f 2 2 3 4 2 3 f 3 2 3 4 5 6 7 8 9 2 3 5 7 9 2 3 5 7 f 4 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 3 5 7 9 11 13 15 2 3 5 7 11 13 f 5 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 2 3 5 7 9 11 13 15 17 19 21 23 25 2 3 5 7 11 13 17 19 23 25 2 3 5 7 11 13 17 19 23 ``` [Answer] # Mathematica, 133 bytes ``` Grid[#,Alignment->Left]~Print~" "&/@FoldList[#/.(##|1&@@(2~r~i#2)->Null)&,(r=Range)[i=#^2]~Partition~#/.Rule[1,],Prime@r@PrimePi@#];& ``` [Answer] # PHP, ~~155~~ ~~150~~ ~~147~~ ~~145~~ ~~142~~ 140 bytes ``` for(;$k++<$n=$argv[1];)if($k<2||$a[$k]){for($i=0;$i++<$n*$n;)echo$a[$i]=$k>1?$i>$k&$i%$k<1?"":$a[$i]:($i<2?"":$i),"\t\n"[$i%$n<1];echo"\n";} ``` **breakdown** ``` for(;$k++<$n=$argv[1];) if($k<2||$a[$k]) // if first iteration or number unprinted ... { for($i=0;$i++<$n*$n;) echo $a[$i]=$k>1 ?$i>$k&$i%$k<1 ?"" // sieve :$a[$i] // or copy value :($i<2?"":$i) // first iteration: init grid , // append tab, linebreak every $n columns "\t\n"[$i%$n<1] ; // blank line after each iteration echo"\n"; } ``` ]
[Question] [ # Challenge Forsyth–Edwards Notation (FEN) is a standard notation for describing a particular board position of a chess game. Your challenge is to evaluate the score using the FEN string. This is an example of a FEN string: ``` 5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8 ``` Using this string, you can calculate the material score for each color with the following score table: > > * p / P = Pawn = 1 point > * n / N = Knight = 3 points > * b / B = Bishop = 3 points > * r / R = Rook = 5 points > * q / Q = Queen = 9 points > * k / K = King, these don't have any points because every legal position contains a king for each side > > > White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk"). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks. From the example FEN string, we can calculate the material scores for each side: For black: > > 5**k**2/**ppp**5/4P3/3R3**p**/6P1/1K2N**r**2/PP3P2/8 > > > All the black pieces left: p + p + p + p + r, this is a total of 9 > > > For white: > > 5k2/ppp5/4**P**3/3**R**3p/6**P**1/1**K**2**N**r2/**PP**3**P**2/8 > > > All the white pieces left: P + R + P + N + P + P + P, this is a total of 13 > > > The final score is determined with the following formula: **White score** - **Black score** = **Final score**, so for the example the final score would be: 13 - 9 = 4 **Example** : *Input:* ``` 5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8 ``` *Output:* ``` 4 ``` --- All [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply here, the solution with the least amount of bytes wins. --- # How to post ``` # Language Name, N bytes [code] [explaination, etc.] ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~64~~ ~~57~~ ~~56~~ 53 bytes ``` "QRBNP"013359v $0p4}:{:v?=1l<p4+' '{- g4v?(0:i<+ n~<; ``` *(-7 bytes with some inspiration from @El'endiaStarman's answer, -3 bytes thanks to @randomra)* ### Explanation The program uses the codebox as a lookup table. Out-of-range puts/gets don't work with the online interpreter, so this only works with the official Python interpreter. The first line pushes the pieces, followed by the piece values. It also pushes an initial 0 to kick off the total for the third line. The second line then puts the appropriate positive or negative value at the corresponding piece cell, e.g. `-1` is placed at `('p', 4)` and `1` is placed `('P', 4)`. The length of the stack is checked to make sure the loop runs 5 times. After the loop is over, the stack consists of our single zero from the first line. For each char we perform a lookup at the corresponding cell in the table and add it to our total. By default, uninitialised cell values are 0, which is perfect for our purposes. The last line merely prints the result. [Answer] ## Ruby, 88 chars ``` ->s{s.chars.map{|c|({P:1,N:3,B:3,R:5,Q:9}[:"#{c.upcase}"]||0)*(c.ord<90?1:-1)}.inject:+} ``` This is awkward and ugly, and there's probably a better way, but oh well. Ruby's `{foo: 'bar'}` syntax is actually just sugar for `{:foo => 'bar'}`—this is annoying for golf because it means I have to convert the key to a symbol before using it to access a hash element (`:"#{x}"` is one char shorter than `x.to_sym`). [Answer] # Pip, 39 bytes I'll take my brief turn in the lead before the CJam and Pyth answers come along... ``` $+Y(95<=>A_)*013359@{"KPNBRQ"@?UCa|0}Ma ``` Takes the FEN string as a command-line argument. Here's an explanation for a slightly ungolfed version: ``` $+({(95<=>Aa)*013359@("KPNBRQ"@?UCa|0)}Ma) { }Ma Map this function to each character in input: UCa Uppercase version of character "KPNBRQ"@? Its index in this string, nil if not present |0 Logical or with 0 (to turn nil into 0) 013359@( ) Index into this number to get piece's score Aa ASCII value of character 95<=> 1 if less than 95, -1 if greater than 95 ( )* Multiply by the score $+( ) Sum all scores and autoprint result ``` [Answer] # Perl, 44 bytes ``` #!perl -p $\+=lc=~y/pnbrq/13359/r*(a cmp$_)for/\D/g}{ ``` Counting the shebang as one, input is taken from stdin. --- **Sample Usage** ``` $ echo 5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8 | perl fen-score.pl 4 ``` --- **Explanation** Pieces are transliterated with their respective values. If the piece is capitalized (i.e. less than `a`), its value is added to the sum, if not it is subtracted. [Answer] # CJam, ~~28~~ ~~27~~ 26 bytes ``` 0l{i32mdD%[5ZZX9]=\3%(*+}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0l%7Bi32mdD%25%5B5ZZX9%5D%3D%5C3%25(*%2B%7D%2F&input=5k2%2Fppp5%2F4P3%2F3R3p%2F6P1%2F1K2Nr2%2FPP3P2%2F8). ### How it works ``` 0l e# Push a 0 (accumulator) and a line from STDIN. { e# For each character of that line: i32md e# Divide its code point by 32; push quotient and residue. e# This serves two purposes: e# 1. The quotient will let us distinguish between uppercase e# letters, lowercase letters and non-letters. e# 2. The residue will be the same for uppercase and lowercase e# variants of the same letter. D% e# Take the residue modulo 13. e# This maps R,N,B,P,Q -> 5,1,2,3,4 [5ZZX9]= e# Select the element at that index (5 ≡ 0) from [5 3 3 1 9]. \ e# Swap the quotient on top of the stack. e# 1 is digit or slash, 1 is uppercase, 2 is lowercase. 3%( e# Take the quotient modulo 3 and subtract 1 from the result. e# This maps 1,2,3 -> 0,1,-1. *+ e# Multiply the generated integers. + e# Add the product to the accumulator. }/ e# ``` [Answer] # JavaScript ES7, 79 bytes ~~124~~ ~~131~~ ``` s=>(i=0,[for(q of s)i+={P:1,N:3,B:3,R:5,Q:9,p:-1,n:-3,b:-3,r:-5,q:-9}[q]||0],i) ``` As short as I can get. Uses fancy array comprehensions, to loop through the string. # Explanation ``` s=>( // Define function with an argument i=0, // this var will store the score [for(q of s) // Loops through input i+= // Adds to score by... {P:1,..., // Defines value of each letter p:-1,...} // Negative value instead, which will subtract || 0 // Otherwise add 0 ], i // Return score ``` [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), ~~72~~ ~~65~~ ~~64~~ ~~60~~ ~~44~~ ~~42~~ 41 bytes ``` 13359"QRBNP"m5[d3~c~$r48*+0p0p]$I[o0q+]N. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=13359%22QRBNP%22m5%5Bd3%7Ec%7E%24r48*%2B0p0p%5D%24I%5Bo0q%2B%5DN.&input=5k2%2Fppp5%2F4P3%2F3R3p%2F6P1%2F1K2Nr2%2FPP3P2%2F8) Much thanks to Sp3000 for pointing out a much more efficient way to do this! ### Explanation `13359"QRBNP"m` pushes the scores and their corresponding characters, then *interleaves* them, so the stack looks like this: `[1,80,3,78,3,66,5,82,9,81]`. Then `5[d3~c~$r48*+0p0p]` puts the score of each character, both lowercase and uppercase, at its location in the code space. Finally, `$I[o0q+]N.` loops through the input until it's empty, adding up the scores as it goes along. [Answer] # CJam, 33 bytes ``` q{"PNBRQ"_el+#13359Ab_Wf*+0+=}%:+ ``` Here's the super-naïve string-find way. [Try it online](http://cjam.aditsu.net/#code=q%7B%22PNBRQ%22_el%2B%2313359Ab_Wf*%2B0%2B%3D%7D%25%3A%2B&input=5k2%2Fppp5%2F4P3%2F3R3p%2F6P1%2F1K2Nr2%2FPP3P2%2F8). [Answer] # [Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), 82 Ouroboros is an esolang I designed this week. Time to take it for a spin! ``` i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+ )L!4*(4Sn1( ``` Each line of single-char commands1 represents an ouroboros snake, wherein execution proceeds from head (start) to tail (end) and loops back to the head. The `(` and `)` commands let you eat part of the tail or regurgitate it, thus changing what commands get executed. If the instruction pointer is ever swallowed, the snake dies (stops executing). An Ouroboros program consists of one or more snakes executing in parallel. Each snake has a stack of its own, and there is also a shared stack. 1One exception, which distinguishes Ouroboros from many 2D languages: multi-digit numbers can be written straightforwardly, without having to do math or push a 0 first. ### Snake 1 The first snake reads a character (`i`) and checks whether it's -1 / EOF (`.1+!`). If so, it eats most of its tail, up to and including the `M` (`57*(`). The snake then swaps the character code with the tally that is above it on the stack (`\`), moves the tally to the shared stack (`m`), and swallows another character (`1(`). If it had already swallowed a bunch, this means it swallows the `(` that the IP is currently on and dies. Otherwise, execution proceeds by moving the tally back to snake 1's stack, swapping it with the char code, and regurgitating the character that was previously swallowed (`M\1)`). We then use math and stack operations to generate the appropriate score for the character. `.96>` tests whether it's lowercase or not; the subsequent `32*-` converts to uppercase. Then the long stretch from `.80=` to `81=9*++++` maps `P` -> `1`, `N` -> `3`, etc. Finally, `\2*1\-*` negates the score if the letter was lowercase, and `+` adds it to the running tally. The snake then loops and reads another character. ### Snake 2 The second snake starts with a regurgitate operation (`)`), which does nothing the first time through (since nothing's been swallowed yet, and also since popping an empty stack gives `0`). Next, it pushes the length of the shared stack to its own stack and logically negates (`L!`). This gives `1` if the stack is empty, `0` otherwise. The snake multiplies by 4 and eats that many characters (`4*(`). If the shared stack was empty, this means the snake now ends before the `S`. It pushes `4` and loops back to the `)`, where it regurgitates the characters it just swallowed and starts over again. If there was a value on the shared stack, however, no characters are swallowed and execution continues. The snake switches to the shared stack and outputs the number there (`Sn`); then it swallows its last character and dies (`1(`). ### Synchronization The two snakes must be carefully synchronized so that there is never a value on the shared stack when snake 2 does its check, until the end of input is reached. Snake 1 puts a value on the shared stack briefly on each pass through its loop. Thus, snake 2's `L` command must never be executed between the `m` and `M` commands in snake 1. Fortunately, the snakes line up very well. Crucially, the length of snake 1's loop (70 instructions) is a multiple of snake 2's loop (7 instructions), so the two will never get out of sync: ``` i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+ )L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5)L!5*(5 |__| Danger zone ``` If the numbers hadn't worked out so perfectly, I would have padded one or both snakes with spaces to make them align as needed. ### All of this is very well, but I want to see it in action! Here is the above program via Stack Snippet. Even on 1000 operations per second, it takes about 10 seconds to spit out the answer for the sample input--but it does get there! ``` // Define Stack class function Stack() { this.stack = []; this.length = 0; } Stack.prototype.push = function(item) { this.stack.push(item); this.length++; } Stack.prototype.pop = function() { var result = 0; if (this.length > 0) { result = this.stack.pop(); this.length--; } return result; } Stack.prototype.top = function() { var result = 0; if (this.length > 0) { result = this.stack[this.length - 1]; } return result; } Stack.prototype.toString = function() { return "" + this.stack; } // Define Snake class function Snake(code) { this.code = code; this.length = this.code.length; this.ip = 0; this.ownStack = new Stack(); this.currStack = this.ownStack; this.alive = true; this.wait = 0; this.partialString = this.partialNumber = null; } Snake.prototype.step = function() { if (!this.alive) { return null; } if (this.wait > 0) { this.wait--; return null; } var instruction = this.code.charAt(this.ip); var output = null; if (this.partialString !== null) { // We're in the middle of a double-quoted string if (instruction == '"') { // Close the string and push its character codes in reverse order for (var i = this.partialString.length - 1; i >= 0; i--) { this.currStack.push(this.partialString.charCodeAt(i)); } this.partialString = null; } else { this.partialString += instruction; } } else if (instruction == '"') { this.partialString = ""; } else if ("0" <= instruction && instruction <= "9") { if (this.partialNumber !== null) { this.partialNumber = this.partialNumber + instruction; // NB: concatenation! } else { this.partialNumber = instruction; } next = this.code.charAt((this.ip + 1) % this.length); if (next < "0" || "9" < next) { // Next instruction is non-numeric, so end number and push it this.currStack.push(+this.partialNumber); this.partialNumber = null; } } else if ("a" <= instruction && instruction <= "f") { // a-f push numbers 10 through 15 var value = instruction.charCodeAt(0) - 87; this.currStack.push(value); } else if (instruction == "$") { // Toggle the current stack if (this.currStack === this.ownStack) { this.currStack = this.program.sharedStack; } else { this.currStack = this.ownStack; } } else if (instruction == "s") { this.currStack = this.ownStack; } else if (instruction == "S") { this.currStack = this.program.sharedStack; } else if (instruction == "l") { this.currStack.push(this.ownStack.length); } else if (instruction == "L") { this.currStack.push(this.program.sharedStack.length); } else if (instruction == ".") { var item = this.currStack.pop(); this.currStack.push(item); this.currStack.push(item); } else if (instruction == "m") { var item = this.ownStack.pop(); this.program.sharedStack.push(item); } else if (instruction == "M") { var item = this.program.sharedStack.pop(); this.ownStack.push(item); } else if (instruction == "y") { var item = this.ownStack.top(); this.program.sharedStack.push(item); } else if (instruction == "Y") { var item = this.program.sharedStack.top(); this.ownStack.push(item); } else if (instruction == "\\") { var top = this.currStack.pop(); var next = this.currStack.pop() this.currStack.push(top); this.currStack.push(next); } else if (instruction == "@") { var c = this.currStack.pop(); var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(c); this.currStack.push(a); this.currStack.push(b); } else if (instruction == ";") { this.currStack.pop(); } else if (instruction == "+") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a + b); } else if (instruction == "-") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a - b); } else if (instruction == "*") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a * b); } else if (instruction == "/") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a / b); } else if (instruction == "%") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a % b); } else if (instruction == "_") { this.currStack.push(-this.currStack.pop()); } else if (instruction == "I") { var value = this.currStack.pop(); if (value < 0) { this.currStack.push(Math.ceil(value)); } else { this.currStack.push(Math.floor(value)); } } else if (instruction == ">") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a > b)); } else if (instruction == "<") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a < b)); } else if (instruction == "=") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a == b)); } else if (instruction == "!") { this.currStack.push(+!this.currStack.pop()); } else if (instruction == "?") { this.currStack.push(Math.random()); } else if (instruction == "n") { output = "" + this.currStack.pop(); } else if (instruction == "o") { output = String.fromCharCode(this.currStack.pop()); } else if (instruction == "r") { var input = this.program.io.getNumber(); this.currStack.push(input); } else if (instruction == "i") { var input = this.program.io.getChar(); this.currStack.push(input); } else if (instruction == "(") { this.length -= Math.floor(this.currStack.pop()); this.length = Math.max(this.length, 0); } else if (instruction == ")") { this.length += Math.floor(this.currStack.pop()); this.length = Math.min(this.length, this.code.length); } else if (instruction == "w") { this.wait = this.currStack.pop(); } // Any instruction not covered by the above cases is ignored if (this.ip >= this.length) { // We've swallowed the IP, so this snake dies this.alive = false; this.program.snakesLiving--; } else { // Increment IP and loop if appropriate this.ip = (this.ip + 1) % this.length; } return output; } // Define Program class function Program(source, speed, io) { this.sharedStack = new Stack(); this.snakes = source.split(/\r?\n/).map(function(snakeCode) { var snake = new Snake(snakeCode); snake.program = this; snake.sharedStack = this.sharedStack; return snake; }.bind(this)); this.snakesLiving = this.snakes.length; this.io = io; this.speed = speed || 10; this.halting = false; } Program.prototype.run = function() { if (this.snakesLiving) { this.step(); this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed); } } Program.prototype.step = function() { for (var s = 0; s < this.snakes.length; s++) { var output = this.snakes[s].step(); if (output) { this.io.print(output); } } } Program.prototype.halt = function() { window.clearTimeout(this.timeout); } var ioFunctions = { print: function(item) { var stdout = document.getElementById('stdout'); stdout.value += "" + item; }, getChar: function() { if (inputData) { var inputChar = inputData[0]; inputData = inputData.slice(1); return inputChar.charCodeAt(0); } else { return -1; } }, getNumber: function() { while (inputData && (inputData[0] < "0" || "9" < inputData[0])) { inputData = inputData.slice(1); } if (inputData) { var inputNumber = inputData.match(/\d+/)[0]; inputData = inputData.slice(inputNumber.length); return +inputNumber; } else { return -1; } } }; var program = null; var inputData = null; function resetProgram() { var stdout = document.getElementById('stdout'); stdout.value = null; if (program !== null) { program.halt(); } program = null; inputData = null; } function initProgram() { var source = document.getElementById('source'), stepsPerSecond = document.getElementById('steps-per-second'), stdin = document.getElementById('stdin'); program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions); inputData = stdin.value; } function runBtnClick() { if (program === null || program.snakesLiving == 0) { resetProgram(); initProgram(); } else { program.halt(); var stepsPerSecond = document.getElementById('steps-per-second'); program.speed = +stepsPerSecond.innerHTML; } program.run(); } function stepBtnClick() { if (program === null) { initProgram(); } else { program.halt(); } program.step(); } ``` ``` .container { width: 100%; } .so-box { font-family: 'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } h1 { text-align: center; font-family: Georgia, 'Times New Roman', serif; } a { text-decoration: none; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 40px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #stdout-container, #stdin-container { height: auto; padding: 6px 0; } #reset { float: right; } #source-display-wrapper { display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display { font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f88912; } .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } ``` ``` <!-- Designed and written 2015 by D. Loscutoff Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766 --> <div class="container"> <textarea id="source" placeholder="Enter your program here" wrap="off">i.1+!57*(\m1(M\1).96>.@32*-.80=\.78=3*\.66=3*\.82=5*\81=9*++++\2*1\-*+ )L!4*(4Sn1(</textarea> <div id="source-display-wrapper"> <div id="source-display"></div> </div> </div> <div id="stdin-container" class="container"> <textarea id="stdin" placeholder="Input" wrap="off">5k2/ppp5/4P3/3R3p/6P1/1K2Nr2/PP3P2/8</textarea> </div> <div id="controls-container" class="container clearfix"> <input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /> <input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /> <input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /> <input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /> </div> <div id="stdout-container" class="container"> <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea> </div> <div id="options-container" class="container"> <div class="option so-box">Steps per Second: <span id="steps-per-second" contenteditable>1000</span> </div> </div> ``` [Answer] # JavaScript ES6, 71 As an anonymous function ``` n=>[...n].map(x=>t+=~(y='q rnb p PBN R Q'.search(x))?y-9|1:0,t=0)|t ``` [Answer] # Perl 5, ~~71~~ 63 bytes ``` %a=(P,1,N,3,B,3,R,5,Q,9);$\+=$a{$_}||-$a{uc$_}for<>=~/./g;print ``` This modifies `$\` (the line separator for `print`, which starts false) for every alphanumeric in the string that's a key of the hash `%a` defined at the beginning. It increments `$\` by the value of the hash if the letter is a key as is; otherwise, it increments by *negative* the value of the hash if the uppercased letter is a key; otherwise it adds nothing. Many thanks to [primo](/u/4098) for saving me eight bytes (in a comment on this answer). --- I can save another byte with another suggestion from primo (thanks!): change `$a{$_}||-$a{uc$_}` to `$a{$_}-$a{$"^$_}`. But that's a rather different answer than mine, I think, so I'll not take the "credit" (of −1 byte) for it. [Answer] # Clojure/ClojureScript, 63 chars ``` #(apply +(map{"P"1"N"3"B"3"R"5"Q"9"p"-1"n"-3"b"-3"r"-5"q"-9}%)) ``` Written using a ClojureScript REPL, should also be valid Clojure. Try it [here](http://clojurescript.net/). Enter it, then call it using `(*1 "FEN_string_here")` Pretty straightforward. `{"P"1..."q"-9}` is a data structure literal for a map of "P" to 1, "N" to 3, etc. `map` takes the function as the first argument and the data structure to process as the second--in this case, it's using the feature that a data structure (the map literal) can act as its own accessor function. The string parameter (`%` from the function macro) can be treated as a list of individual character strings. Any character not in the map will end up as `nil` in the resulting list, which `+` happily ignores. [Answer] # Pyth, 25 bytes ``` -Fmsmhy/4@S5%Ck12@Gd_rBz2 ``` [Demonstration](https://pyth.herokuapp.com/?code=-Fmsmhy%2F4%40S5%25Ck12%40Gd_rBz2&input=5k2%2Fppp5%2F4P3%2F3R3p%2F6P1%2F1K2Nr2%2FPP3P2%2F8&debug=0) This uses the following mapping formula for letters in `pbnrq`, if `k` is the letter: ``` (4 / (((chr(k) % 12) % 5) + 1) * 2 + 1 ``` This is represented in Pyth as: ``` hy/4@S5%Ck12 ``` First, the program creates the case-swapped version of the input, then on both strings filters for lowercase letters, then applies the above formula, then sums and subtracts the black values from the white values. [Answer] # Python 3, 93 ``` v=dict(zip('pbnrqPBNRQ',[1,3,3,5,9]*2)) print(sum(v.get(c,0)*(-1)**(c>'Z')for c in input())) ``` ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- Oh no, Santa spilled wine all over his great book. Now most of the letters are illegible. How will Santa now know who is *groovy* and who is *unspeakable*? ## Challenge There was once a sequence of words, like this: ``` groovy groovy groovy unspeakable groovy groovy unspeakable unspeakable ``` However, most of the letters have gone missing and now it looks like this: ``` v oo g unsp gr y gro b uns ``` Then squashed together: ``` voogunspgrygrobuns ``` Your task is to recover the *shortest sequence of words* that could reduce to the given damaged string. Note: The words will never have any overlapping characters. Since the book uses different words in different languages you need to handle different words. ## Test Cases | Word A | Word B | Sentence | Result | | --- | --- | --- | --- | | a | b | ab | a b | | ab | cd | abcd | ab cd | | ab | cd | abc | ab cd | | ab | cd | ac | ab cd | | ab | cd | bd | ab cd | | ab | cd | bda | ab cd ab | | ab | cd | aa | ab ab | | ooq | dr | ooqdr | ooq dr | | ooq | dr | oooqdr | ooq ooq dr | | groovy | unspeakable | voogunspgrygrobuns | groovy groovy groovy unspeakable groovy groovy unspeakable unspeakable | [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ‚[DNãvyJæ³åiyq ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOsaBe/w4vLKr0OLzu0@fDSzMrC//8Tk7iSU7hSkpIB "05AB1E – Try It Online") ``` ‚[DNãvyJæ³åiyq ‚ # pair [ # infinite loop D # double N # push current loop index ã # cartesian power v # for loop y # push current element J # join æ # powerset ³å # does it contain third input? iyq # if true, push current element and terminate ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I salvaged a previous blunder so this is now almost certainly beatable! ``` eⱮÐƤƤŒP€}SSÐṂḢ€ị ``` A dyadic Link that accepts the sentence on the left and the pair of words on the right and yields a list of words. **[Try it online!](https://tio.run/##y0rNyan8/z/10cZ1hyccW3JsydFJAY@a1tQGBx@e8HBn08Mdi4C8h7u7/x9e7v3/f1l@fnppXnFBelFlelF@EpD5P1odyMovq1TXUVAHSaUmZicm5aSqxwIA "Jelly – Try It Online")** ### How? Effectively greedily consumes the longest prefix of the remaining sentence that is a substring of one of the words and then adds that word to the, initially empty, result. The actual implementation analyses every sublist of the sentence and identifies the ends of the words and which one each is and then constructs the result. ``` eⱮÐƤƤŒP€}SSÐṂḢ€ị - Link: Sentence, Words } - using the right argument, Words: € - for each word: ŒP - powerset -> all substrings of the word Ƥ - for prefixes of Sentence: ÐƤ - for suffixes of that prefix: Ɱ - map across the pair of word substring lists with: e - exists in? S - sum the columns -> list of pairs [n,0] or [0,n] where n is the distance to the next word boundary. ÐṂ - keep those pairs with minimal: S - sum (i.e the [1,0] and [0,1] entries marking ends of words.) Ḣ€ - head each -> 1 if word 1, 0 if word 2 ị - index (1-based and modular) into (Words) ``` [Answer] # Python3, 119113 bytes: ``` lambda a,b,s:' '.join(a if x[0]in a else b for x in re.split(f"({'?'.join(a)}?|{'?'.join(b)}?)",s)if x);import re ``` [Try it online](https://tio.run/##fYxNagMxDIX3OYXIRmMwodBNSQk5SNqF1PFMnUws156GDG3PPpUDIYTiLvTz3qenOI3vEh6fYpq7zcs80JFbArJs8xoBV3vxoSHwHZx3D68@AIEbsgOGThKcQZ3kVjkOfmy6ZfOF22vG/Gy/b5JVmqXNpnwyz/4YJY0anWPyQaMNElpkLWI0ZnGzi/fWXoCOKqqRGuC2Cqj26x6IfKAFbFPpKnT5B//hfRI5TQV@hhwdHYgHV@RJpC9Wnya9YV01N/8C) [Answer] # Python3, 190 bytes: ``` Y=lambda a,b:a==''if''in[a,b]else Y(a[a[0]==b[0]:],b[1:]) f=lambda a,b,s,r=[]:r if''==s else f(a,b,s[(M:=max([x for x in range(1,len(s)+1)if Y(s[:x],a)+Y(s[:x],b)])):],r+[[a,b][Y(s[:M],b)]]) ``` [Try it online!](https://tio.run/##fY5BbsQgDEX3cwp2gMKiUTcVEkeYA4wQC7uBNGoGMjAdJadPDVLVVlW6sPnfj49Ztvtbis8vS973i5nhigMwUKjBGM6nQBUteefn4tlFgAX75IxB6toptL128hR@JFVR2VinM6tpYwpr0SAas@KszRVWYVcWUmYrmyLLEEcvejX7KIrsejkFWlWsXp0C2X1JlE5KWpo7275kGzg34OS@5CneRRAcuOJIBcilPH2P6@x1aICOQ3REjgAOhwCO3voNUrpxxfiQaydD4h/8h485pcdW4Ucsi4d3wNlX@0hprKMxb3QHSVJu/wQ) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 46 bytes ``` ~(L$`¶(.+) \G$1(?!\G)¶$1 (?<=G\w+) ? ^ L#-2$$` ``` [Try it online!](https://tio.run/##K0otycxLNPz/v07DRyXh0DYNPW1Nrhh3FUMNe8UYd81D21QMuTTsbWzdY8qBEvZccVw@yrpGKioJ//@X5eenl@YVF6QXVaYX5ScBmVxAOr@skgskmpqYnZiUkwoA "Retina – Try It Online") Takes the squashed word on the first line and the pair of words on the other two lines. Explanation: Very similar to the extended version below but the last stage hard-codes the number of words. 63 bytes for a version that decodes any number of words with non-overlapping letters: ``` ~(L$`¶(.+) \G$1(?!\G)¶$1 (?<=G\w+) ? ^(?=((!)|[^!])+) L#-$#2$$` ``` [Try it online!](https://tio.run/##K0otycxLNPz/v07DRyXh0DYNPW1Nrhh3FUMNe8UYd81D21QMuTTsbWzdY8qBEvZccRr2thoaipo10XGKsZpAIR9lXRVlIxWVhP//y/Lz00vzigvSiyrTi/KTgEwuIJ1fVskFEk1NzE5MykkFAA "Retina – Try It Online") Takes the squashed word on the first line and original words on subsequent lines. Explanation: ``` ~( ``` Evaluate the output of the rest of the program as a program on the original input. ``` L$`¶(.+) ``` For each original word... ``` \G$1(?!\G)¶$1 ``` ... construct an anchor to match after the previous word (easiest way to limit the matches to the first line), the word to be processed below, an anchor to not match after the previous word (to ensure at least one letter matched) and a copy of the word on its own line to act as a replacement. ``` (?<=G\w+) ? ``` Suffix `?`s to each letter in the word, making each letter match optionally (but greedily). ``` ^(?=((])|[^]])+) L#-$#2$$` ``` Prefix a List command with the multiple greedy match and replacement option. In the given example, the resulting program looks like this: ``` L#-2$`\Gg?r?o?o?v?y?(?!\G) groovy \Gu?n?s?p?e?a?k?a?b?l?e?(?!\G) unspeakable ``` Explanation: ``` L#-2$` ``` List matches of two regexes each with their own match result. (In this case only one of the regexes can match at a given point but the `#-` option normally allows Retina to choose which regex depending on which matches earlier in the string.) ``` \Gg?r?o?o?v?y?(?!\G) ``` Greedily match as much of the word `groovy` as possible, matching at least one character. ``` groovy ``` If this match succeeds then the resulting list item is the word `groovy`. ``` \Gu?n?s?p?e?a?k?a?b?l?e?(?!\G) unspeakable ``` Similarly for the word `unspeakable`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 83 bytes ``` s=>a=>(g=i=>(e=t=>r=t^1?a[t&1]+[,e(t/2)]:'')(i).match([...s].join`.*`)?r:g(i+1))(1) ``` [Try it online!](https://tio.run/##FcnRDoIgFIDhd@Gizkmj0aUb@iCMJhoSZhwH5ObTk938@7Z/NptJY/RrvgZ62jLJkmRrZAtO@qNWZtlGmR@iMyqfhK5UbSHf7qib8xnBI/@YPL5Acc6T5jP50PNLj11sHPhKIILAMlJItFi@kIMJ2EbkviGtLu4u0nCQISh2mLad1ez/rHmbYbFMI5Yf "JavaScript (Node.js) – Try It Online") As a compare with `find` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 77 bytes ``` a=>b=>g=(t,s='',...r)=>s.match([...t].join`.*`)?s:g(t,...r,(s&&=s+' ')+a,s+b) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZBNDoIwEIXj1lO4oq1g18akeAJPYExo-ak_2BEKJJzFDTF6KD2NHdkZTTdv5s372knmejeQ5cOtEI-2KRbL50aKWIlYC9pEVhAScc5rJmLLz7JJ93TrfLPjRziYhM8TtrYr7VCkImqDQNiQzAgLZWRDxcZPX5MqBWOhzHkJmhaUSMIoUSjSKZt-x58ozUYAqw_xET5A-XaoTPp2_AIAKsyyGtUZbHzQH0rXAF2PSGvsJZcnqcocbQegcaTr3jHKte71ePlhGOsb) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` Fθ«F¬№ωι«≔⎇№ηιηζω⟦ω⟧»≔Φω›λ⌕ωιω ``` [Try it online!](https://tio.run/##NY3BDsIgEETP5Ss4QoJf4MmY1Jvx4M14oBUpkbC6pRA0/XaEak9vdmdmtx8k9iBtzndAyl6cfkizyCN4tofJeRYFNZwvTrMbR6MdOyt0EtM/MNSAoAXvgsi3JXhCU5xLvNZpJmuxNdYrrCcPqGSVVtDWuNv65defcw4AenLjU2PSCF2RpBBCInWr5EN2VuVNsF8 "Charcoal – Try It Online") Link is to verbose version of code. Takes the squashed sentence as the first input. Explanation: ``` Fθ« ``` Loop over the characters of the squashed sentence. ``` F¬№ωι« ``` If the current character isn't present in the current string (initially the empty string), then... ``` ≔⎇№ηιηζω ``` ... update the current string to the word that contains the current character, and... ``` ⟦ω⟧ ``` ... output that word on its own line. ``` »≔Φω›λ⌕ωιω ``` Delete up to the first occurrence of the current character in the current word. 37 bytes for a version that decodes any number of words with non-overlapping letters: ``` SθWS⊞υιFθ«F¬№ωι«≔⊟Φυ№λιω⟦ω⟧»≔Φω›λ⌕ωιω ``` [Try it online!](https://tio.run/##TY1NCsIwEEbXySmyTKCewJUIFTdScCku0hrTYMjU/DQU6dlj0lpwNd/MvDfT9dx2wHVKZzMEf/VWGUnfbI9jr7Qg9H/MGGmC62moiMrEEyzJKPlgtMQLeHqEYDyNBWDLBh2cU9LQBgZaK@2FLfqK6RWrSMzXEGryE09v8V66GW/mz8o3T1bwErNXK/PY3qz@nNIIIINxg7STtNDmiHOFccJlKviLt1rgtBv1Fw "Charcoal – Try It Online") Link is to verbose version of code. Takes the squashed sentence as the first input followed by a list of newline-terminated words. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` Kwm?-dzKzhf!-T+yzyK./w ``` [Try it online!](https://tio.run/##K6gsyfj/37s81143pcq7KiNNUTdEu7Kq0ltPv/z//8QkruQUrqSURAA "Pyth – Try It Online") Takes the two words as the first two inputs and the sentence as the third. Returns a list. Brutally slow brute force method. ### Explanation ``` # z=input() implicitly Kw # set K to the second input ./w # all partitions of the third input (given sorted by number of elements in the partition) f # filter over lambda T ! # not (true for empty list) -T # remove from T +yzyK # sum of the power sets of the first two inputs h # take the first element of the filtered list (this will be a valid partition with the least elements) m # map each element (d) to ?-dzKz # z if d consists of characters in z, K otherwise ``` [Answer] # JavaScript (ES10), 86 bytes Expects `(sentence)(word_list)`. Returns a comma-separated string of words. ``` s=>a=>(g=b=>b.find(w=>w.match([...s].join`.*`))||g(b.flatMap(p=>a.map(q=>p+[,q]))))(a) ``` [Try it online!](https://tio.run/##FYxRDoMgEETvwtfS2r0B3KAnMCYuilRLWQSrMfHulM7XS@bNLLRTHtIct0fg0ZZJlaw0KQ1OGaUNTnMY4VD6wA9twwtaRMwdLjyHHm@9lNfloGqetidFiHVczQir0vHeNmsna4BkGThk9hY9O5hA7MzuG3J06XSJTUUhoRWVeT9FI/6dpTcZb0X9KD8 "JavaScript (Node.js) – Try It Online") [Answer] # Excel (ms365), 241 bytes [![enter image description here](https://i.stack.imgur.com/ogfoE.png)](https://i.stack.imgur.com/ogfoE.png) Formula in `D1`: ``` =LET(x,SEQUENCE(LEN(C1)),y,SCAN(C1,x,LAMBDA(a,b,LET(z,MAP(x,LAMBDA(c,TEXTJOIN("*",,MID(a,SEQUENCE(c),1)))),SUBSTITUTE(a,TAKE(TOCOL(IF(SEARCH(z,A1:B1),LEFT(a,x),),2),-1),,1)))),TOCOL(IF(FIND(LEFT(VSTACK(C1,FILTER(y,y<>""))),A1:B1),A1:B1,),3)) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 41 bytes ``` Y@_NIag@yMFIc@(@>(aJW"?").`|`.@>(bJW"?")) ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZQF9OSWFnQHlNRkljQChAPihhSldcIj9cIikuYHxgLkA+KGJKV1wiP1wiKSkiLCIiLCJcImdyb292eVwiIFwidW5zcGVha2FibGVcIiBcInZvb2d1bnNwZ3J5Z3JvYnVuc1wiIiwiLXAiXQ==) Expects the first word, second word and sentence as inputs. Shamelessly stole the regex from [@David's answer](https://codegolf.stackexchange.com/a/255761/110555). Full test suite [here](https://dso.surge.sh/#@WyJwaXAiLCIoeygoX0prKU1hKUpcIiAtPiBcIn1NZ1ooeyIsIllAX05JYWdAeU1GSWNAKEA+KGFKV1wiP1wiKS5gfGAuQD4oYkpXXCI/XCIpKSIsIn1NVWcpKUpuIiwiJ1tcImFcIjtcImJcIjtcImFiXCJdJyAnW1wiYWJcIjtcImNkXCI7XCJhYmNkXCJdJyAnW1wiYWJcIjtcImNkXCI7XCJhYmNcIl0nICdbXCJhYlwiO1wiY2RcIjtcImFjXCJdJyAnW1wiYWJcIjtcImNkXCI7XCJiZFwiXScgJ1tcImFiXCI7XCJjZFwiO1wiYmRhXCJdJyAnW1wiYWJcIjtcImNkXCI7XCJhYVwiXScgJ1tcIm9vcVwiO1wiZHJcIjtcIm9vcWRyXCJdJyAnW1wib29xXCI7XCJkclwiO1wib29vcWRyXCJdJyAnW1wiZ3Jvb3Z5XCI7XCJ1bnNwZWFrYWJsZVwiO1widm9vZ3Vuc3Bncnlncm9idW5zXCJdJyAiLCItcHgiXQ==) (Thanks to @emanresuA for help with the test suite) ]
[Question] [ ## Specification Write the shortest possible code in any language that does the following: It takes two arguments, x and y, and generates x + y lines of text. The first x lines should consist of y nested pairs of square brackets separated by a space surrounding a single digit, which cycles from 1 to 9, then 0 to 9, etc. from line to line. The following y lines have the letter X in place of the digit and successively replace the innermost remaining pair of square brackets with spaces. The last line only contains the X, surrounded by spaces. All output is ASCII. You may choose to output a final newline (following a space), but you may also choose not to. You may use either CR, CRLF, or LF as newline sequences. The last line must contain an appropriate number of spaces following the central X. The only valid inputs are positive integers. Zero is not a valid input. You’re free to impose a reasonable, technically-driven limit on input size, even if the problem is solvable without. For instance, if there’s some function available for 16 bit integers that isn’t for bigints for some reason, and using it makes your program shorter, that’s a valid reason for a input size constraint. Your code may reject invalid input or simply behave in any way on invalid input. ## Examples Example with x = 12, y = 8: ``` [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 3 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 4 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 5 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 6 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 7 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 8 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 9 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 0 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ X ] ] ] ] ] ] ] [ [ [ [ [ [ X ] ] ] ] ] ] [ [ [ [ [ X ] ] ] ] ] [ [ [ [ X ] ] ] ] [ [ [ X ] ] ] [ [ X ] ] [ X ] X ``` Example with x = 5, y = 1 ``` [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] X ``` Example with x = 1, y = 10: ``` [ [ [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ [ X ] ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ [ X ] ] ] ] ] ] ] ] [ [ [ [ [ [ [ X ] ] ] ] ] ] ] [ [ [ [ [ [ X ] ] ] ] ] ] [ [ [ [ [ X ] ] ] ] ] [ [ [ [ X ] ] ] ] [ [ [ X ] ] ] [ [ X ] ] [ X ] X ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes Takes the inputs in reversed order. ``` L<+'[δиR²LT%¹'Xи«ªζ».º ``` [Try it online!](https://tio.run/##AS4A0f9vc2FiaWX//0w8KydbzrTQuFLCskxUJcK5J1jQuMKrwqrOtsK7LsK6//84CjEy "05AB1E – Try It Online") This works by creating half of the columns, transposing to rows and adding the other half with a mirror. ``` L<+ # push range [x .. x+y-1] '[δи # for each number in the range, create a list of that many '[' R # reverse the list of lists ²L # push range [1 .. x] T% # each number %10 ¹'Xи # a list of y 'X' « # append this to the modulo range ª # append to the list of columns ζ # transpose to list of rows, filling with space » # join each row by spaces, rows by newlines .º # self-intersected mirror ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (use of `)`) ``` Ø[j %⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G ``` A full program that accepts \$x\$ and \$y\$ and prints the result. **[Try it online!](https://tio.run/##y0rNyan8///wjOgsLtVHjVsPtx9aqGn9qGFuBIj1qHFbJpAda@2sonJo2bE1D3d0HVri/v//f0Oj/xYA "Jelly – Try It Online")** ### How? ``` Ø[j - Link 1, wrap in []: a Ø[ - list of characters = ['[', ']'] j - join (with a) = ['[', a, ']'] %⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G - Main Link: x, y ) - for each (v in [1..x]): ⁵ - ten % - (v) modulo (10) ¡ - repeat (y times): Ç - call last Link (1) as a monad ¤ - nilad followed by link(s) as a nilad: ”X - character = 'X' ¡ - repeat (y times): Ç - call last Link (1) as a monad Ƭ - loop until no change, collecting up inputs: ¦ - sparse application... $ - ...to (1-based) indices: last two links as a monad: i”] - first index of character ']' (call this i) $ - last two links as a monad: C - complement -> 1-i ; - concatenate -> [i, 1-i] ⁶ - ...of: space character (replaces innermost [] with spaces) Ḋ - dequeue (remove the leading one with all []s present) ; - concatenate G - format as a grid - implicit print ``` [Answer] # JavaScript (ES6), 99 bytes Building line by line. Expects `(x)(y)`. ``` (x,n=0)=>g=y=>y?'[ '[R='repeat'](y-=++n>x)+(n>x?(p=' '[R](n-x))+'X'+p:n%10)+' ]'[R](y)+` `+g(y):'' ``` [Try it online!](https://tio.run/##ZYzBCsIwEETvfkUusruslUYQpLDtP3gSSqGlpkUpSWiLNF8fozfxMjzeDPPsXt3Szw@/ZtbdTRwk4nawkpOUowQpQwW1gvoqMBtvuhUaDJkw23IjxpQVegH1mTRos42I4QbsC7vXeWLVfJtA3O5aHhMUALF3dnGTOU5uxAH1iVBdiHa/Wp2T1v9aE6Zrim8 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 115 bytes Building character by character. Expects `(x)(y)`. ``` x=>y=>(k=x-1,g=n=>k-~y?` ][X${(x-k)%10}`[--n?(q=n-y+~y)?n&(k>0|q*q>k*k*4)&&2^q>0:5^k<0:k---k]+g(n||w):'')(w=y*4+2) ``` [Try it online!](https://tio.run/##ZcjBCoJAEADQe1/hoWxGm9gVhZB2/Y1AisRKamRtM9Il69eta/SO71I8ira8na93Ms3hOJ7U2CvtlAZWPclFpYzSTG@X7b3JNt9Mn9AT40yK1z4nMhlYZciFb4eZ8YG1GGxgNQccxOj70c5qkSY7XouUiYi3YQVmGDpM53OETrkgDiMcy8a0TX1c1k0FJ5ARgrdCnPy2l3xb/rdEkAJx/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes *-1 byte thanks to @Lynn, with a `min` trick* The main difference from the previous answer is a clever use of `min`. When `i <= x`, `v+'X'+v` equals `X`, which is lexicographically larger than any digit `[0-9]`. When `i > x`, `v` starts with leading spaces, which causes `i%10` to be chosen instead. ``` x,y=input() i=0 while y:i+=1;y-=i>x;v=(i-x)*' ';print'[ '*y+min(`i%10`,v+'X'+v)+' ]'*y ``` [Try it online!](https://tio.run/##JY1RCgIhFAD/PcVDiKerC7oQxIqdI4hgIYR9UCZhpqe3rX7mZwYmtbw@4tTfK90C2BlCDVfgnPeqm6eYXllIRt6wf9FmUt66Nno6Vle8oLHKAQHQpSfFjGfAoak7RbHQzppFF4UnVEUqhMum@i/7Duyk4cD2GiyzG8wH "Python 2 – Try It Online") ### [Python 2](https://docs.python.org/2/), 88 bytes Input is taken from STDIN. ``` x,y=input() i=0 while y:i+=1;y-=i>x;v=-x%i*' ';print'[ '*y+[`i%10`,v+'X'+v][i>x]+' ]'*y ``` I finally get an oppurtunity to show off this nice trick: `-x%i*' '`. It turns out that `-x%i` is equivalent to `i-x`, when `i>=x`. On its own, it is one byte longer, but it allows us to drop the parentheses in the string multiplication. [Try it online!](https://tio.run/##Jc3RCsIgFMbxe5/iMBinpgMdBDGx5whEGISwA2ESZvr0ZnXz3fx/8MWa9kdY2nunuwe1gi/@BsMwtCKqoRBf6XBkZCT7i7oSN0rX2dCl6GzmMtKEAKjjk0JCCzhVbjcaldxE5nhFnp3t2HEE12P7we@DWgSc2UmAYqqP/AA "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 92 bytes ``` x=>h=(y,N=x+y)=>N?h(y,N-1)+(g=_=>y--?x+y<N?` ${g()} `:`[ ${g()} ]`:N>x?'X':N%10)(y)+` `:'' ``` [Try it online!](https://tio.run/##ZclBCsIwEEDRfU@RhZIZaqQRBAlOcoOsBRFTapsqpREr0iCePdaFC3H537@Uj3KobufrXfThVKeG0ki6JYgLS2MekbQ17aeExBw8HUlHIcy0ttY4xmZPD/hizCm3/8bBKatHw3dc2bksECLmLnOK81SFfghdveyChwbkCmGDmP3qGkH@oZywQExv "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 56 bytes ``` (‛[ ¹*n₀%‛ ]¹*++,)¹‹(‛ n›*‛[ ¹nε‹*p\X+‛ n›*+‛ ]¹nε‹*+, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%E2%80%9B%5B%20%C2%B9*n%E2%82%80%25%E2%80%9B%20%5D%C2%B9*%2B%2B%2C%29%C2%B9%E2%80%B9%28%E2%80%9B%20%20n%E2%80%BA*%E2%80%9B%5B%20%C2%B9n%CE%B5%E2%80%B9*p%5CX%2B%E2%80%9B%20%20n%E2%80%BA*%2B%E2%80%9B%20%5D%C2%B9n%CE%B5%E2%80%B9*%2B%2C&inputs=4%0A4&header=&footer=) Its bad I know. [Answer] # [J](http://jsoftware.com/), 73 bytes ``` +:@[|."1((,'X'$~,&1)~10":@|1+i.),.~' []'{~[:(,.~2*|."1)@|.@,.0,~"0+>/&i.[ ``` [Try it online!](https://tio.run/##VcqxCgIxEATQ3q9YgtwmZl2zB4IElIBgZWUlBCu5w7PxAwz76zGHNhYDM495VsM4wj4CAkGA2LJmOF7Op@pjyoWNWEt4xaVSJ04lmJiK@IkdsSLkG741R9tGv5rfLhVOxIHUBH/YdBPn6hbD/fECgRG234r4o9BM/m03U18/ "J – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~105~~ 115 bytes ``` function(x,y,`|`=strrep,l="[ ",r=" ]",p=paste0)cat(p(l|y,1:x%%10,r|y),p(l|y:1-1,s<-" "|1:y,"X",s,r|y:1-1),sep=" ") ``` [Try it online!](https://tio.run/##HYrRBsMwGEbv@xTxUxK@kn9XE/vfY8xoVcKoLpKMhrx7tu7qcM5JPUgPn30tr/euD1TMbZZcUvIRm9BDEZKQehKixCUXb826FB311irYHePIFqlVg79yPDHybSKlqLGroDshn8NZDLKPQgOZHjRfcDXDj2Br@hc "R – Try It Online") ~~Returns a vector of lines.~~ Prints the result. ``` function(x,y, # function taking x and y as input `|`=strrep, # assign strrep to operator with low precedence l="[ ",r=" ]",p=paste0) # defining variables in function's arguments saves bytes cat( # concatenate the two parts p( # paste element-wise (recycling if necessary) l|y, # left bracket with space y times 1:x%%10, # row index mod 10 r|y), # and right bracket preceded by space y times p( # the second part l|y:1-1, # `l` declining number of times s<-" "|1:y, # required number of spaces (save as s for later) "X", # literal X s, # we've seen that before r|y:1-1), # right brackets sep="\n") # join elements by newline ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` [×*ω[]k⇵∔⁷{A%]╶X*∔+ *│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JTVCJUQ3JXVGRjBBJXUwM0M5JXVGRjNCJXVGRjNEJXVGRjRCJXUyMUY1JXUyMjE0JXUyMDc3JXVGRjVCJXVGRjIxJXVGRjA1JXVGRjNEJXUyNTc2WCV1RkYwQSV1MjIxNCV1RkYwQiUyMCV1RkYwQSV1MjUwMg__,i=OCUwQTEy,v=8) Takes input as `y` on the first line and `x` on the second line. [Answer] # Excel, 112 bytes ``` =LET(z,SEQUENCE(A1+B1),s,IF(z>A1,z-A1,0),b,REPT(" ",s),REPT("[",B1-s)&b&IF(z>A1,"X",MOD(z,10))&b&REPT("]",B1-s)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnDuRswxrUqsG4D1g?e=q59go5) ## Explanation * `=LET(z,SEQUENCE(A1+B1),` z = vertical array of numbers from 1 to x+y * `s,IF(z>A1,z-A1,0),` if z > x then s = z - x else z = 0 * `b,REPT(" ",s),` string of spaces for each row * `REPT("[",B1-s)` string of "[" for each row * `&b&IF(z>A1,"X",MOD(z,10))&b` spaces and middle for each row * `&REPT("]",B1-s))` string of "]" for each row [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~166 164~~ 128 bytes ``` x=>y=>[...Array(x+y)].map((e,i)=>'[ '[r='repeat'](d=i<x?y:y-i+x-1)+(m=' '[r](i>=x&&y-d))+(i<x?++i%10:'X')+m+' ]'[r](d)).join` ` ``` [Try it online!](https://tio.run/##HcrRCoIwFIDh@57Cm9w5rI3sKqSz6C0CERw6Y6JOpsT29Eu7/f9v0F@9tt4um5hdZ1JPKZCKpCop5ct7HSHwiLWc9AJgLhZJsSpjlSfmzWL0xmroyD7CM5ZRWB5EgRwmYtmBarCKQp5H0eGeD8a5PRfXkr0Z8omzrP6zfcvB2bk5Nal18@pGI0f3gR6KG8IdMf0A "JavaScript (Node.js) – Try It Online") Unlike my previous submission which replaced a string of spaces, this simply builds each line. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ ~~30~~ 28 bytes ``` NθNη↷²⭆θ﹪⊕ιχ×Xη⸿Eη×[⁺θι‖BUE¹ ``` [Try it online!](https://tio.run/##TYyxCoMwFEX3fkVwegEL1angVujQwSK2Q6FdbHyaQIwaX6T9@tRAsZ0u53LuFbKyoq@09yczODq77okWRp5t/lkuXKi5p1K1kiANaJUhuNASbV4NMMYs72unezgZYbFDQ1iD4jFLdnz1r6rDCaJbFDP5a6OHjVYIZzJmX/O@mIV2U/hXnIdNiY1GQQdHhLbRb1i644vQ1JDwzPskZXu/nfUH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input `x` and `y`. ``` ↷² ``` Change the default output direction to downwards. ``` ⭆θ﹪⊕ιχ ``` Print the central column of digits. ``` ×Xη ``` Print the `X`s. ``` ⸿Eη×[⁺θι ``` Move to the previous column and print the right trapezium of `[`s to the left. ``` ‖B ``` Mirror the canvas. ``` UE¹ ``` Spread out the columns. [Answer] # Haskell, 122 bytes ``` x%y=mapM putStrLn[(r>>"[ ")++min[last$show i](v++"X"++v)++(r>>" ]")|i<-[1..x+y],r<-[[1+max i x..x+y]],v<-[[1..i-x]>>" "]] ``` [Try it online!](https://tio.run/##JYtBCsIwEEWvMgwWWqYNxJUL2xPUlRshzCILocGkliTGFLx7rHX3eO//SYfH3dpScrX2Ti8XWF7xGv04q9oPAyrAhsiZWVkd4iFMzzcYrhMR3pAobXHfAWPzMedOSSEyrdz6jZUkpzMYyH/JbdqtEKbL/HsBMhenzQw9yCNUcCpf "Haskell – Try It Online") The most noteworthy trick here is using `min` to decide between digits and `X`. Namely, `"X"` > `"9"` > `" X "` > `" X "` > … so that if we only make `v` have the right amount of spaces, then `min(digit, v++"X"++v)` will choose the appropriate string. [Answer] # [Python 2](https://docs.python.org/2/), 147 bytes ``` lambda x,y,N=" ":"\n".join(["[ "*y+`z%10`+y*" ]"for z in range(1,x+1)]+["[ "*z+N*(y-z)+"X"+N*(y-z)+" "+z*"] "for z in range(y,0,-1)])+"\n"+N*y+"X" ``` [Try it online!](https://tio.run/##Xc1BCsIwEIXhqwwDQpJJpelKhF6ha6ENtKLRiiYldNHJ5WPEheDuLb6ft/B6D77Jrh3yc3qdLxNsmnXXIgAecfC4f4TZix57QMU0pp2pR2KFYNGFCAlmD3Hyt6sweiMjLX1tok4JrpIkPOFvA1JSaOE/Zl3rqtSFlNPi@dPlJc5@FU6YRh@kzG8 "Python 2 – Try It Online") -8 bytes thanks to @ophact ]
[Question] [ The International Phonetic Alphabet is a system of phonetic notation intended to be able to accurately represent every sound used in spoken language. The alphabet contains 29 vowel letters `iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶäɑɒ` and 81 consonant letters, although I missed three (`ɦǀǂ`) when I first posted this challenge, so you only need to consider the following 78: `mɱnɳɲŋɴpbtdʈɖcɟkɡqɢʡʔszʃʒʂʐɕʑɸβfvθðçʝxɣχʁħʕhʋɹɻjɰⱱɾɽʙrʀʜʢɬɮlɭʎʟɺǃʘǁɓɗᶑʄɠʛɧɥʍwɫ` and . We'll be ignoring the various diacritics in use. Your job is to output those characters exactly once each, *not* including the three letters I missed, and output no other non-whitespace characters. Since the IPA does not have an official ordering, you may output these characters in *any* order so if you find an order that permits a shorter approach feel free to use that. You may output as much or as little whitespace as you want. The output of your program does *not* need to be constant, as long as the output always meets the specification above (so the order may vary, as may the amount and location of whitespace). For the sake of convenience, here's a sorted list of all the characters and their unicode codepoints: ``` U+0061 LATIN SMALL LETTER A: a U+0062 LATIN SMALL LETTER B: b U+0063 LATIN SMALL LETTER C: c U+0064 LATIN SMALL LETTER D: d U+0065 LATIN SMALL LETTER E: e U+0066 LATIN SMALL LETTER F: f U+0068 LATIN SMALL LETTER H: h U+0069 LATIN SMALL LETTER I: i U+006a LATIN SMALL LETTER J: j U+006b LATIN SMALL LETTER K: k U+006c LATIN SMALL LETTER L: l U+006d LATIN SMALL LETTER M: m U+006e LATIN SMALL LETTER N: n U+006f LATIN SMALL LETTER O: o U+0070 LATIN SMALL LETTER P: p U+0071 LATIN SMALL LETTER Q: q U+0072 LATIN SMALL LETTER R: r U+0073 LATIN SMALL LETTER S: s U+0074 LATIN SMALL LETTER T: t U+0075 LATIN SMALL LETTER U: u U+0076 LATIN SMALL LETTER V: v U+0077 LATIN SMALL LETTER W: w U+0078 LATIN SMALL LETTER X: x U+0079 LATIN SMALL LETTER Y: y U+007a LATIN SMALL LETTER Z: z U+00e4 LATIN SMALL LETTER A WITH DIAERESIS: ä U+00e6 LATIN SMALL LETTER AE: æ U+00e7 LATIN SMALL LETTER C WITH CEDILLA: ç U+00f0 LATIN SMALL LETTER ETH: ð U+00f8 LATIN SMALL LETTER O WITH STROKE: ø U+0127 LATIN SMALL LETTER H WITH STROKE: ħ U+014b LATIN SMALL LETTER ENG: ŋ U+0153 LATIN SMALL LIGATURE OE: œ U+01c1 LATIN LETTER LATERAL CLICK: ǁ U+01c3 LATIN LETTER RETROFLEX CLICK: ǃ U+0250 LATIN SMALL LETTER TURNED A: ɐ U+0251 LATIN SMALL LETTER ALPHA: ɑ U+0252 LATIN SMALL LETTER TURNED ALPHA: ɒ U+0253 LATIN SMALL LETTER B WITH HOOK: ɓ U+0254 LATIN SMALL LETTER OPEN O: ɔ U+0255 LATIN SMALL LETTER C WITH CURL: ɕ U+0256 LATIN SMALL LETTER D WITH TAIL: ɖ U+0257 LATIN SMALL LETTER D WITH HOOK: ɗ U+0258 LATIN SMALL LETTER REVERSED E: ɘ U+0259 LATIN SMALL LETTER SCHWA: ə U+025b LATIN SMALL LETTER OPEN E: ɛ U+025c LATIN SMALL LETTER REVERSED OPEN E: ɜ U+025e LATIN SMALL LETTER CLOSED REVERSED OPEN E: ɞ U+025f LATIN SMALL LETTER DOTLESS J WITH STROKE: ɟ U+0260 LATIN SMALL LETTER G WITH HOOK: ɠ U+0261 LATIN SMALL LETTER SCRIPT G: ɡ U+0262 LATIN LETTER SMALL CAPITAL G: ɢ U+0263 LATIN SMALL LETTER GAMMA: ɣ U+0264 LATIN SMALL LETTER RAMS HORN: ɤ U+0265 LATIN SMALL LETTER TURNED H: ɥ U+0267 LATIN SMALL LETTER HENG WITH HOOK: ɧ U+0268 LATIN SMALL LETTER I WITH STROKE: ɨ U+026a LATIN LETTER SMALL CAPITAL I: ɪ U+026b LATIN SMALL LETTER L WITH MIDDLE TILDE: ɫ U+026c LATIN SMALL LETTER L WITH BELT: ɬ U+026d LATIN SMALL LETTER L WITH RETROFLEX HOOK: ɭ U+026e LATIN SMALL LETTER LEZH: ɮ U+026f LATIN SMALL LETTER TURNED M: ɯ U+0270 LATIN SMALL LETTER TURNED M WITH LONG LEG: ɰ U+0271 LATIN SMALL LETTER M WITH HOOK: ɱ U+0272 LATIN SMALL LETTER N WITH LEFT HOOK: ɲ U+0273 LATIN SMALL LETTER N WITH RETROFLEX HOOK: ɳ U+0274 LATIN LETTER SMALL CAPITAL N: ɴ U+0275 LATIN SMALL LETTER BARRED O: ɵ U+0276 LATIN LETTER SMALL CAPITAL OE: ɶ U+0278 LATIN SMALL LETTER PHI: ɸ U+0279 LATIN SMALL LETTER TURNED R: ɹ U+027a LATIN SMALL LETTER TURNED R WITH LONG LEG: ɺ U+027b LATIN SMALL LETTER TURNED R WITH HOOK: ɻ U+027d LATIN SMALL LETTER R WITH TAIL: ɽ U+027e LATIN SMALL LETTER R WITH FISHHOOK: ɾ U+0280 LATIN LETTER SMALL CAPITAL R: ʀ U+0281 LATIN LETTER SMALL CAPITAL INVERTED R: ʁ U+0282 LATIN SMALL LETTER S WITH HOOK: ʂ U+0283 LATIN SMALL LETTER ESH: ʃ U+0284 LATIN SMALL LETTER DOTLESS J WITH STROKE AND HOOK: ʄ U+0288 LATIN SMALL LETTER T WITH RETROFLEX HOOK: ʈ U+0289 LATIN SMALL LETTER U BAR: ʉ U+028a LATIN SMALL LETTER UPSILON: ʊ U+028b LATIN SMALL LETTER V WITH HOOK: ʋ U+028c LATIN SMALL LETTER TURNED V: ʌ U+028d LATIN SMALL LETTER TURNED W: ʍ U+028e LATIN SMALL LETTER TURNED Y: ʎ U+028f LATIN LETTER SMALL CAPITAL Y: ʏ U+0290 LATIN SMALL LETTER Z WITH RETROFLEX HOOK: ʐ U+0291 LATIN SMALL LETTER Z WITH CURL: ʑ U+0292 LATIN SMALL LETTER EZH: ʒ U+0294 LATIN LETTER GLOTTAL STOP: ʔ U+0295 LATIN LETTER PHARYNGEAL VOICED FRICATIVE: ʕ U+0298 LATIN LETTER BILABIAL CLICK: ʘ U+0299 LATIN LETTER SMALL CAPITAL B: ʙ U+029b LATIN LETTER SMALL CAPITAL G WITH HOOK: ʛ U+029c LATIN LETTER SMALL CAPITAL H: ʜ U+029d LATIN SMALL LETTER J WITH CROSSED-TAIL: ʝ U+029f LATIN LETTER SMALL CAPITAL L: ʟ U+02a1 LATIN LETTER GLOTTAL STOP WITH STROKE: ʡ U+02a2 LATIN LETTER REVERSED GLOTTAL STOP WITH STROKE: ʢ U+03b2 GREEK SMALL LETTER BETA: β U+03b8 GREEK SMALL LETTER THETA: θ U+03c7 GREEK SMALL LETTER CHI: χ U+1d91 LATIN SMALL LETTER D WITH HOOK AND TAIL: ᶑ U+2c71 LATIN SMALL LETTER V WITH RIGHT HOOK: ⱱ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so golf your code! [Answer] # [International Phonetic Esoteric Language](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language), 110 bytes Felt my esolang was appropriate for this. Naïve approach. Pushes the characters as a string onto the stack, then prints with a newline: ``` "mɱnɳɲŋɴpbtdʈɖcɟkɡqɢʡʔszʃʒʂʐɕʑɸβfvθðçʝxɣχʁħʕhʋɹɻjɰⱱɾɽʙrʀʜʢɬɮlɭʎʟɺǃʘǁɓɗᶑʄɠʛɧɥʍwɫiyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶäɑɒ"o ``` Less naïve approach involving loops, **239 bytes**. ``` {3F}{2P}ɑe{2V}əɐʌɔ|i|eχu|i|e1søɒ"äæçðøħŋœǁǃ"{HW}{GG}ɑe{GQ}əe{GT}əe{HJ}əe{HO}əe{HR}əɞɞɞɞɐʌɔ|j|eχu|j|e1søɒ{IQ}{I0}ɑe{IB}əe{IE}əe{IF}əe{II}əe{IM}əe{IO}əɞɞɞɞɞɐʌɔ|h|eχu|h|e1søɒ"βθχᶑⱱ"o ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~163 161 156~~ 154 bytes ``` _=>(c=96,i=20,g=n=>n?String.fromCharCode(c+=n&1n?1:1-~[...'10'+2e7,139,,108,6,34,45,6,7,,104][i--])+g(n/2n):'βθχᶑⱱ')(0x26affdebbffd7f5ff009ffffbfn) ``` [Try it online!](https://tio.run/##FYpLDoIwFEV3I20otQUEISkMWIJDYgy/hxh8NUCMI6eOXYoOjKvQNehGEO/gnOTk7rJj1hddcxgs1GU1gho3KiKFCjzWKFuwWqGKMF4NXYM1h07vk23WJdOXFKbCmcRYhtI6p5xzQwrDtCufSSdgTIol85jjMncx2f8Hd502lrWmZk1wbiMNjdf99XxfPo/r93YzKBEn28sAyirPJ/qwABAigGk5IB0Ljb1uK97qmgChdPwB "JavaScript (Node.js) – Try It Online") ### How? The characters are ordered from lowest to highest code point. Each **1** in the BigInt bit mask `0x26affdebbffd7f5ff009ffffbfn` means that the code point **c** of the next character immediately follows the previous one. Each **0** means that the code point difference must be picked from a lookup array instead, which happens for the first time between `f` and `h`. ``` 111010111111111000000001001111111111111111110111111 ɡɠɟɞɜɛəɘɗɖɕɔɓɒɑɐǃǁœŋħøðçæäzyxwvutsrqponmlkjihfedcba 100110101011111111110111101011101111111111110101111 ʢʡʟʝʜʛʙʘʕʔʒʑʐʏʎʍʌʋʊʉʈʄʃʂʁʀɾɽɻɺɹɸɶɵɴɳɲɱɰɯɮɭɬɫɪɨɧɥɤɣɢ ``` We add an offset of **+2** to each value in the lookup array, including undefined entries. The values are stored in reverse order to allow the compression trick `[...'10'+2e7]` for the last 10 entries, which expands to: ``` ['1','0','2','0','0','0','0','0','0','0'] ``` Because the code point differences for the last 5 characters `βθχᶑⱱ` are significantly larger, it's more beneficial to just hard-code them. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ ~~71~~ ~~68~~ ~~66~~ 62 bytes ``` ⁻βg⭆⪪”)¶←@8⊘Φ@◧%↘Z⪪ξρ”³℅Iι⭆⌕A”)∧←₂⁰Y⟧Gψ⊟∧⬤º”1℅⁺⁵⁹²ι”yβθχᶑⱱ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3M6@0WCNJR0EpXUlT05oLIhpcAqTSfRMLNIILcjJLNJSMjCyMjA2MjA2NTAyMTCyMLE2NjQ2NjS1NTCxNTA2VdBSMNXUUnIFmJyaXpBZpOCcWl2hkampiM9EtMy/FMSdHQ8kQDgzACJMNE0ASNTAwQJUzgEoZgEigQ5QMlVCcEpAD9J@ppZGOAop7lM5tOrfjfPvDbRMfbdyopGn9//9/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code (yay!). Explanation: ``` ⁻βg ``` Output all of the lowercase letters except `g`. ``` ⭆⪪”)¶←@8⊘Φ@◧%↘Z⪪ξρ”³℅Iι ``` Split the compressed string `228230231240248295331339449451` into 3-digit numbers and convert the code points into characters. ``` ⭆⌕A”)∧←₂⁰Y⟧Gψ⊟∧⬤º”1℅⁺⁵⁹²ι ``` Add 592 to the indices of all the `1`s in the compressed string `11111111110110111111110110111111111111101111011011111000111111111110110011011101011` and convert the code points to characters. ``` ”yβθχᶑⱱ ``` Output 3 literal Greek letters and two literal characters. The Greek letters are in Charcoal's code page so they only cost 1 byte, but they have to be quoted by the `”y` to avoid being interpreted as Charcoal variable names. The final characters cost 3 bytes each. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 63 bytes Outputs the non-ascii characters in ascending order first, then the lowercase alphabet (without `g`). ``` •2£cÈ‹Jd$…•Ƶf╤4Àǝ„Æ43†ÂÄт4H·âeš¬•5вƵ¬6 15ŽPäŽEï)˜.¥ƵƵ+çJA'gK« ``` [Try it online!](https://tio.run/##AXUAiv9vc2FiaWX//@KAojLCo2PDiOKAuUpkJOKApuKAosa1ZtCy4oCiwqQ0w4DHneKAnsOGNDPigKDDgsOE0YI0SMK3w6JlxaHCrOKAojXQssa1wqw2IDE1xb1Qw6TFvUXDrynLnC7Cpca1xrUrw6dKQSdnS8Kr//8 "05AB1E – Try It Online") **Commented**: `•2£c ... ŽEï)˜` encodes the deltas using a mix of integer and integer list compression. ``` ... # compressed deltas .¥ # undelta ƵƵ+ # add 228 (ä) ç # convert to characters J # join to a single string A # push the lowercase alphabet 'gK # without 'g' « # concatenate both strings # implicit output ``` [Answer] # JavaScript, ~~184~~ 183 bytes *-1 byte thanks to @Neil* ``` _=>"a6h19äæ2ðøħŋœǁǃɐ10ɛ2ɞ8ɧ2ɪ13ɸ4ɽ2ʀ5ʈ11ʔ2ʘ2ʛ3ʟʡ2βθχᶑⱱ".replace(/.(\d+)/g,(c,n)=>[...Array(+n)].map(_=>String.fromCharCode(a++),a=c.charCodeAt()).join``) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k4p0SzD0PLwksPLjA5vOLzjyPKj3UcnH2883nxygqHBydlGJ@dZnFxudHKVofHJHSYn9xqdajA91WFoeGqK0akZRqdmG5@af2qh0blN53acb3@4beKjjRuV9IpSC3ISk1M19PU0YlK0NfXTdTSSdfI0be2i9fT0HIuKEis1tPM0Y/VyEws0gC4ILinKzEvXSyvKz3XOSCxyBrpNI1FbW1Mn0TZZLxkq4liioampl5WfmZeQoPk/OT@vOD8nVS8nP10jDShh/R8A "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 131 bytes ``` a=0 n="\x01" for c in f"a\x01\x01\x01\x01\x01\x02{n*18}j\x02\x01 \x08/$\x08n\x02\x8d{n*9}\x02\x01\x02{n*7}\x02\x01\x02{n*12}\x02\x01\x01\x01\x02\x01\x02\x01\x01\x01\x01\x04{n*10}\x02\x01\x03\x01\x02\x01\x01\x02\x02\x01Đ\x06\x0f\u19ca\u0ee0":a+=ord(c);print(chr(a)) ``` The string's characters have been encoded here for readability, but they are raw (1 byte each for all except the unicode) on TIO. [Try it online!](https://tio.run/##K6gsycjPM/7/P9HWgCvPVolRiSstv0ghWSEzTyFNKZERBJiq87QMLWqzmBg5OfRVOPKYDvUCRSxrmcAy5lDa0AjIACpmBJGMLCARA6AIM4jPxMR4ZAIb/8PlXQ92L1CyStS2zS9K0UjWtC4oyswr0UjOKNJI1NT8/x8A "Python 3 – Try It Online") Simple idea: we can encode the characters as a set of deltas with some hand rolled run length encoding. I tried compression but the overhead is just too large. We abuse the allowance for whitespace by printing each character on a separate line. --- ## [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 152 bytes ``` for c,d in zip("ahäæðøħŋœǁǃɐɛɞɧɪɸɽʀʈʔʘʛʟʡβθχᶑⱱ",b"\x06\x13\x01\x02\x01\x01\x01\x01\x01\x01\x01\n\x02\x08\x02\n\x04\x02\x05\x0b\x02\x02\x03\x01\x02\x01\x01\x01\x01\x01"):print(*map(chr,range(k:=ord(c),k+d))) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFZJ0UhM0@hKrNAQykx4/CSw8sObzi848jyo91HJx9vPN58csLJ2SfnnVx@ctXJHSf3nmo41XFqyqkZp2afmn9q4blN53acb3@4beKjjRuVdJKU2IQZmRghICaPiYMpJo@FiZWbiYkZKqykaVVQlJlXoqGVm1igkZxRpFOUmJeeqpFtZZtflKKRrKmTrZ2iqan5/z8A "Python 3.8 (pre-release) – Try It Online") [Answer] # MATLAB, 62 chars, 95 bytes (UTF-8) ``` setxor([97:122,'äæçðøħŋœǁǃβθχᶑⱱ',592:674],'gɷɿɼɦɩɚɝʚʞʠʓʖʗʅʆʇ') ``` Outputs char array. ...or if we want lowest bytecount, not charcount: ## MATLAB, 71 chars, 88 bytes (UTF-8) ``` setxor([97:122,'äæçðøħŋœǁǃβθχᶑⱱ',592:674],['g',550+'47@CQVY_`ampqtxz']) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~59~~ 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “#×2DHṬ“Ð`“ƥ’ḃ2ż4,3F“ỵ£¢µ®/$®n£⁽“¡©Ð‘jo272;⁽æe,⁽¿9ÄỌ;Øaḟ”g ``` A niladic Link yielding a list of characters (or a full program printing them to STDOUT). **[Try it online!](https://tio.run/##y0rNyan8//9Rwxzlw9ONXDwe7lwDZB@ekAAkjy191DDz4Y5mo6N7THSM3YAiD3dvPbT40KJDWw@t01c5tC7v0OJHjXuB4ocWHlp5eMKjhhlZ@UbmRtZAwcPLUnWA1KH9lodbHu7usT48I/HhjvmPGuam//8PAA "Jelly – Try It Online")** ### How? ``` “#×2DHṬ“Ð`“ƥ’ḃ2ż4,3F - Link: no arguments “#×2DHṬ“Ð`“ƥ’ - list of base 250 numbers = [35227363705935,4097,165] ḃ2 - convert to bijective-base 2 = [[1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,2,1],[1,2,1,1,2,2,1]] 4,3 - [4,3] ż - zip together = [[[1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1],4],[[1,1,1,1,1,1,1,1,1,1,2,1],3],[1,2,1,1,2,2,1]] F - flatten = [1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1,4,1,1,1,1,1,1,1,1,1,1,2,1,3,1,2,1,1,2,2,1] “...“¡©Ð‘jo272;⁽æe,⁽¿9ÄỌ;Øaḟ”g - (continued Link) “...“¡©Ð‘ - lists of code-page indices = [[228,2,1,9,8,47,36,8,110,2,141],[0,6,15]] j - join that (with the previous list) = [228,2,1,9,8,47,36,8,110,2,141,1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1,4,1,1,1,1,1,1,1,1,1,1,2,1,3,1,2,1,1,2,2,1,0,6,15] 272 - 272 o - logical OR (replace the single 0 with 272) ⁽æe,⁽¿9 - [6602,3808] ; - concatenate Ä - cumulative sums = [228,230,231,240,248,295,331,339,449,451,592,593,594,595,596,597,598,599,600,601,603,604,606,607,608,609,610,611,612,613,615,616,618,619,620,621,622,623,624,625,626,627,628,629,630,632,633,634,635,637,638,640,641,642,643,644,648,649,650,651,652,653,654,655,656,657,658,660,661,664,665,667,668,669,671,673,674,946,952,967,7569,11377] Ọ - cast to characters = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱ" Øa - lower-case English alphabet ; - concatenate = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱabcdefghijklmnopqrstuvwxyz" ”g - 'g' ḟ - filter-discard = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱabcdefhijklmnopqrstuvwxyz" ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 70 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç┼☺►┴┬φ3π╓ùδ±║≈§←¬b☻╬₧○ôT»╤↔ñ¢≤♣=≈î⌂╖ì(P┐Φ│xøïº9r═A,Åáï☼♀εwccù√╞Æ3äö▐π ``` [Run and debug it](https://staxlang.xyz/#p=80c50110c1c2ed33e3d697ebf1baf7151baa6202ce9e099354afd11da49bf3053df78c7fb78d2850bfe8b378008ba73972cd412c8fa08b0f0cee77636397fbc692338494dee3&i=) [Run and debug it uncompressed](https://staxlang.xyz/#c=Va%27g-p%22%29%25EA%26%23%21jA*E%29.%27%22%21228s%2B35141380471727%3AB%7B2s-m%221%25%25%25%25%25%25%25%25%25%25%29%25-%25%29%25%25%29%29%256v9%5D.,Q%26kj%22%21%2B%2B%3A%2Bp&i=) This is my first proper answer to a compression based question. Hope I did well. Uses a combo of stax's number array compression and binary to print the alphabet. ## Explanation `Va'g-p` Print the lowercase alphabet without g `")%EA&#!jA*E).'"!` Deltas of first few symbols, compressed `228s+` add 228 to the beginning of it (first letter) `35141380471727:B` 35141380471727 converted to array of bits `{2s-m` subtract each bit from two `"1%%%%%%%%%%)%-%)%%))%6v9].,Q&kj"!` deltas of last few symbols, compressed `++` join all the deltas together `:+` sums of all prefixes `p` print, converting ASCII values [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 139 bytes ``` FromCharacterCode@Accumulate@Developer`RawUncompress@"xKd&FÅÄÈÉ¡¯ÂÇÔc+dBÕÂbAe111\.00¼£"<>"βθχᶑⱱ"& ``` [Try it online!](https://tio.run/##XY87L0NhHIdDxMJgYm3OYJGIzlTqEotFiKmaOD19m5aenjo9dZuoCnVtaV2iLm1Rca9LU9fhfYn8/gOfgS9SJgnr8yzPo8qGm6my4VHkostkKXbomtrmlnVZMZjepjmZtUVRgmrQKxvM2s6GmVfzM72/Wx7p9Sma6tdZIGCVRnmy01lWUttRyaNiWoTFrIjwFL8QIR4TMyJeUaPwUJ2zVSR@SLjK0VLNynnEbDaX9tU3NPDHUp6Rmpql96v3wsfMZz72lctJtcUu3eMzbD2abth@kwI2l81ut5ssFtN/IckOxclcbs/AoFf1af4hPWAEh0dGx8bFvjgUWXEpCi/Z1/nX1bfJtylEEcMKVhFHAmtYxwY2sYUkdrCLPaSQRgb7OEAWRzjGCU5xhnNc4BI5XOEaN7hFHgXc4R4PeMIzTdAkhWiKwjRLEZqjeVqgRVqiZYpSjFYoTgnaoE3aoiRt0y6lKP3n@OersfgN "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes no arguments and returns a string as output. Note that the compressed string contains multiple unprintable characters. For reference, the shortest solution I could come up with that doesn't use built-in compression is 140 bytes long (ignore the `Join::heads` message): ``` Complement[CharacterRange@@@Join[97**122,228|231,592|644,648|674],Characters@"gåɚɝɦɩɷɼɿʓʖʗʚʞʠ"]<>"ðøħŋœǁǃβθχᶑⱱ"& ``` ]
[Question] [ Create a program that can be run in 4 different languages such that: * One language prints "Hello World!" * One language outputs its own source code * One language outputs 99 bottles of beer on the wall, that is: ``` 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one down... <the pattern continues for a while> ...pass it around 1 bottle of beer on the wall 1 bottle of beer on the wall 1 bottle of beer Take one down, pass it around No more bottles of beer on the wall ``` * One language takes a nonnegative integer as an input and outputs that integer + 1 ## Rules and Scoring * This is code golf, so shortest code wins. **Score in character count** rather than byte count for this challenge so that golfing languages that use specialized codepages are not disadvantaged by their UTF-8 representations. * Standard rules and loopholes apply * Each language may optionally output a trailing newline for its designated output * Each language may use any I/O convention that is convenient to that language. The convention does not need to be consistent across all four languages; for instance, one uses stdout, another uses the return value, one writes to a file, and the last one spawns an alert containing the text. * Golfing languages that have the option to use specialized codepages must use a standard encoding; they may not take advantage of a byte being interpreted as a different character in another encoding. * Hello World may optionally include a comma after "Hello", thus `Hello, World!` is a valid output. * Standard quine rules apply and the only superfluous output allowed is a trailing newline. + [Text](https://esolangs.org/wiki/Text), or any other "language" where all programs are quines, is not a valid language for the quine. * 99 Bottles of Beer requires: + A blank line between each verse + No blank lines within any verse + The singular/plural distinction of 'bottle' vs 'bottles' + `no more` instead of `0` on the last line + Each line may have any amount of trailing whitespace (or none at all) * The incrementing program must support all input integers that can be incremented natively by its language. + For languages which support unsigned integers, the largest unsigned integer should be used + For languages which represent all numbers as floating point numbers, this would require supporting all input numbers up to \$2^{53}-1\$. + For languages which natively support arbitrary-sized integers, *all* positive integers must be supported. Format the header of your answer like this: ``` # <language for H, <language for Q>, <language for 9>, <language for +>, n characters ``` [Answer] # Ruby, ><>, HQ9+, Befunge-93, 62 characters ``` #9&[[email protected]](/cdn-cgi/l/email-protection)[0[fr' puts"\u0048ello World!"#.1*57;!?lo r]r}:*3da' ``` **["Hello World!"](https://tio.run/##KypNqvz/X9lSzVBbz0HP0CDaIDqtSJ2roLSkWCmm1MDAxCI1JydfITy/KCdFUUlZz1DL1Nxa0R4oVBRbVGulZZySqP7/PwA)** (Ruby) Relevant part of code: `puts"\u0048ello World!"` **[quine](https://tio.run/##S8sszvj/X9lSzVBbz0HP0CDaIDqtSJ2roLSkWCmm1MDAxCI1JydfITy/KCdFUUlZz1DL1Nxa0R4oVBRbVGulZZySqP7/PwA)** (><>) After colliding with the `#` mirror, both lines are read as string literals and printed with a newline between. **[99 bottles of beer on the wall](https://www.youtube.com/watch?v=u-lV0vrEWXw)** (HQ9+) Code contains no `H` or `Q`, and exactly one `9`, so the lyrics of the song are printed once. **[+1 program](https://tio.run/##S0pNK81LT/3/X9lSzVBbz0HP0CDaIDqtSJ2roLSkWCmm1MDAxCI1JydfITy/KCdFUUlZz1DL1Nxa0R4oVBRbVGulZZySqP7/vykA)** (Befunge-93) After jumping over `9` due to the `#` trampoline, a simple +1 program is run `&1+.@` [Answer] # [Python 2](https://docs.python.org/2/), [Perl 5](https://www.perl.org/), [JavaScript (Node.js)](https://nodejs.org), [Ruby](https://www.ruby-lang.org/), 524 characters ``` 0//1;q=0;print"Hello, World!";'''/.__id__;puts STDIN.read.succ;%q[=;$_=q{print q@0//1;q=0;print"Hello, World!";'@.qq@''/.__id__;puts STDIN.read.succ;%q[=;\$_=q{$_};eval;q[\[[email protected]](/cdn-cgi/l/email-protection)@for(x=99,z=(a=' on the wall\n')=>`${x||'No more'} bottle${1-x?'s':''} of beer`+a;x;)console.log(z()+z(n='\n')+'Take one down and pass it around\n'+(x--,z()))//]#]#'@.q@''@};eval;q[ for(x=99,z=(a=' on the wall\n')=>`${x||'No more'} bottle${1-x?'s':''} of beer`+a;x;)console.log(z()+z(n='\n')+'Take one down and pass it around\n'+(x--,z()))//]#]#''' ``` ## `Hello, World!`, Python 2 Pretty straightforward, this performs integer division in void context, then sets `q` to `0`, prints `Hello, World!` and the rest of the program is contained in a `'''` quoted multi-line string. With long, unprocessed, strings removed: ``` 0//1;q=0;print"Hello, World!";'''...''' ``` [Try it online!](https://tio.run/##1Y8xU8JAEIV7f8UKcTaZQAJ2eHOawkIbGpmxACYcySEZz9vc5ZBI4LfHQGGrre3Oft97r/xyW9K3bTuK4zEzfMRKW2jXe5JK0QBeyar8uscQMY7StMjTlJU7V8HL7PF5Glkp8qjaZRm7MXPOvJSb5sKDSX4RJpExyZ@si4vWS09MfgrFzHyhOzjZkPVrPpkMDtwXHIE0uK2EvVBqoTHg9yuvqY9HnBJ8kJV4gjU5p6TXjIf1A1Z4h92NNrCW0q5CwWoWZKQrUjJS9OYf/CA8@Jrj2RbiTLzLLkNCTnsNQudQiqqCwoGwtNN59xX69XA46LggiONlf9k/j@w2Jj/Nr/5DacS2/QY "Python 2 ‚Äì Try It Online") ## Quine, Perl 5 Probably the most complicated, but not overly. It's a pretty standard `$_="...";eval` quine template, but we have to include the preceding code for other languages too. The `0//1` performs integer division in a void context and then `q=...=` is a single-quoted string delimited by `=` in a void context. Then the quine is built into `$_` using an `@`-delimited string. I switched from using `$<` in Ruby for `STDOUT` to avoid having to keep switching in and out of quotes more, although I ended up having to do that for Python 2's `'''` anyway, which needed to be broken up to avoid being triggered. Once `$_` is built, `eval` is called and the rest of the program is contained in `q[...]` (a `[`...`]` delimited, single-quoted string). Here's a simplified version: ``` 0//1;q=...=;$_=q{print q@...'@.qq@''...=;\$_=q{$_};eval;q[\[[email protected]](/cdn-cgi/l/email-protection)@...'@.q@''@};eval;q[...]... ``` [Try it online!](https://tio.run/##1Y89U8JAFEV7f8UT4rxk8gWFBe6sprDQhkZmLIAJS7JoxnVfdpNIhsBvj4HCVlvbN@@ce28prbrt@0kcT5nhE1baQtejJ6kUBfBKVuXXI4aIcZSmRZ6mrGzqCl4Wj8/zyEqRR1WTZezGLDlzUm66Cw8m@UWYRMYkf7KuLlonPTH5JRQzy5Ue4GRH1m35bBYcuCs4Ammo3yXshVIrjR6/3zhdezzinOCTrMQTbKmulXS6adg@YIV3ONxoB1sp7cYXrGVeRroiJSNFb@7B9fyDqzmebT4uxIccMiTktNcgdA6lqCooahCWGp0PX77bhmEwcJ4Xx@vxenweOWxMfppf/YfSiH3/DQ "Perl 5 ‚Äì Try It Online") [Verification.](https://tio.run/##1Y8/b8IwFMR3PsUrpHKikASGDtRym6FDu7AUiQFQMLEpUY0d20mJ@PPZU0OlqlWHdu1673737lbUbtp2l0OUQ1zIsq7iqlC4s2U3tt5@k0puxBcBjvBh@nHBbTtIkiHWZIBLU8iq@8iFUH2YKiPYVRcjhJI4ywqWZdgxFp4nD0/j2HDKYlvnOb7WM4K9jOjDhQed/hKYxlqnf0qdX2K97IT5GxVYz@bSwelaGb8ho1F/T3xKECgJ1YbDjgoxlyggd0vv0ByPaKxgqwxHJ1ipqhLcOwyj5h5ZdIucptaw4twsQ4obHORKWiV4LNSLv/eDcO9Lgs5pIZrQV@5@cGBqJ4FKBiW1FooKqFG1ZM4V@k0U9R0XBEmy6C1655FuY/rZvPMfSiP0Dg "Bash ‚Äì Try It Online") ## 99 bottles of beer, JavaScript (Node.js) JavaScript is relatively easy to have in other code as `//` comments out the rest of the line, so `0//1` is just `0` in void context, followed by a comment and the string closing delimiters of the other three languages are avoided using `//` too. I [borrowed the main code from here for this](https://codegolf.stackexchange.com/a/64235/9365), amending as necessary as using `\n` instead of a literal newline was slightly easier for the quine contents. ``` 0//... for(x=99,z=(a=' on the wall\n')=>`${x||'No more'} bottle${1-x?'s':''} of beer`+a;x;)console.log(z()+z(n='\n')+'Take one down and pass it around\n'+(x--,z()))//... ``` [Try it online!](https://tio.run/##1Y87U8JAFIV7f8UKcW4yIQmUuLOawkIbGpmxACYs2UWj697sA8jw@O0hUNhqa3vnft8555NvuSttVftEo5BtO8yyETVsSGtbad97lkrhgLyhVeK2RwEgS4uiEkVB64135HX69DJJreQidZuypHdmxmhQMHO48sTkvwjz1Jj8T9b5VRsUJyq3XFEzm@sOztdow4aNx4M9CzkDgpr4D0l2XKm5hog9LINDczzCBMk3WgknskLvlQwOo6R5BAf30N1wTVZS2mXMaUOjErVDJVOF7@E@jOJ9qBlcbDFM@ZfsMiQRuNOEa0Fq7hypPOEWN1p0X3HYJMmg46Ioyxb9Rf8ystuY/zS/@Q@lAdr2DA "JavaScript (Node.js) ‚Äì Try It Online") ## Accumulator, Ruby This uses a technique I've used in quite a few polyglots with Ruby in the past. The `0//.../.__id__` construct is parsed as `0` dividede by the `__id__` property of the `/.../` regex (`__id__` is chosen as it's a short property that returns a number to avoid a type mismatch error). Then `STDIN.read.succ` returns the next string that succeeds it, so `9` results in `10`, etc. The rest of the code is wrapped in `%q[...]` effectively hiding it. ``` 0//.../.__id__;puts STDIN.read.succ;%q[...]#... ``` [Try it online!](https://tio.run/##1U/PT4MwGL37V9QNUwgbDAaU2qAcPOhlF5d42BbWjU4XazsKc7gffzuWmZh40qtNvy@vL@@9fp/aLj6aZuC6HimSAdmotag694xz2QNPUvH8skMghK6TZes8y8hmW5XgcXz3MHIUo7lTbpdLclVMEmJkSXE4@0GR/hKYOkWR/il1eo41shNh75STYjIV2pyupDLrBOPePjFpAoEUoHphYEc5nwpoJTdz41Afj3AkwZtUDJ7AQlYVZ8bB69e3sITXUHNyBRaMqblNSU2spRSl5Mzh8tncm5a9N0UC2zQbjukr038wkMudAFTkYEPLEqwrQJXcilyrbLPu93vaZ1muO@vOuu2Sesf0e/KL/zA0hE2D49DHURx4MfJw/HUDXWEUeppvUdAC3TUThUEUtGoU@B7CPtI@7dfPc/kBCjHyMYqGAcKR3xJYE1qNhpGGP88n "Ruby ‚Äì Try It Online") --- # [Python 2](https://docs.python.org/2/), [Perl 5](https://www.perl.org/), [HQ9+](https://esolangs.org/wiki/HQ9+), [Ruby](https://www.ruby-lang.org/), 181 characters Using HQ9+ for the `99 Bottles` implementation, reduces code size considerably: ``` 0//1;q=9;print chr(72)+'ello, World!'#/.__id__;puts STDIN.read.succ;#=;$_=q{print"0//1;q=@{[1^8]};print chr(72)+'ello, World!'#/.__id__;puts STDIN.read.succ;#=;\$_=q{$_};eval"};eval ``` ## `Hello, World!`, Python 2 [Try it online!](https://tio.run/##K6gsycjPM/r/30Bf39C60NbSuqAoM69EITmjSMPcSFNbPTUnJ19HITy/KCdFUV1ZXy8@PjMlPt66oLSkWCE4xMXTT68oNTFFr7g0Odla2dZaJd62sBpshBLURIfqaMM4i9haCg2OAZusEl9rnVqWmKMEof7/BwA "Python 2 ‚Äì Try It Online") ## Quine, Perl 5 [Try it online!](https://tio.run/##K0gtyjH9/99AX9/QutDW0rqgKDOvRCE5o0jD3EhTWz01JydfRyE8vygnRVFdWV8vPj4zJT7euqC0pFghOMTF00@vKDUxRa@4NDnZWtnWWiXetrAabIQS1ESH6mjDOIvYWgoNjgGbrBJfa51alpijBKH@/wcA "Perl 5 ‚Äì Try It Online") [Verification.](https://tio.run/##S0oszvj/vzxZQTdZQS8zr6C0RK8kM9@aKzfFtLg0F0WoILUoB0lAoUYBoghDxvr/fwN9fUPrQltL64KizLwSheSMIg1zI01t9dScnHwdhfD8opwURXVlfb34@MyU@HhroMZiheAQF08/vaLUxBS94tLkZGtlW2uVeNvCarARSlATHaqjDeMsYmspNDgGbLJKfK11allijhKEAgA "Bash ‚Äì Try It Online") ## 99 bottles of beer, HQ9+ Since the code only contains `9` from `HQ9` (and `+` doesn't cause any output) it's all that's executed. My main worry with this is finding an interpreter that complies with the requirements, which might make this invalid perhaps. ``` 9 ``` ## Accumulator, Ruby [Try it online!](https://tio.run/##KypNqvz/30Bf39C60NbSuqAoM69EITmjSMPcSFNbPTUnJ19HITy/KCdFUV1ZXy8@PjMlPt66oLSkWCE4xMXTT68oNTFFr7g0Odla2dZaJd62sBpshBLURIfqaMM4i9haCg2OAZusEl9rnVqWmKMEof7/N7Q0tLQAIQNLCxM4NrM0sTAwNjO0MDczNjc2MzW3NAOqMTC0NLEEAQA "Ruby ‚Äì Try It Online") [Answer] # [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html), [Ruby](https://www.ruby-lang.org/), [Fortran (GFortran)](https://gcc.gnu.org/fortran/), [COW](https://bigzaphod.github.io/COW/), ~~371~~ ~~370~~ 312 characters ``` !t='HHHeeelll lllooom WWWooorrrlllddd!!!MoO qOOM character*35::n="No more bottles of beer on the wall",f="(2(a,/),a)",b do i=99,1,-1 write(b,"(i0,a)")i,n(8:14)//n(15+1/i:) if(i<99)print f,b print f,b,b(:18-1/i),"Take one down, pass it around" enddo print"(a)",n end!';eval$s=%q($><<"!t='#{t}';eval$s=%q(#$s)") ``` What an unholy combination this is! ### *Hello World!*, Trigger The idea to use Trigger came from some of the answers to [this question](https://codegolf.stackexchange.com/q/207490/92901). The main advantage is that it's relatively easy to embed within other garbage. The interpreter effectively sees ``` !t='HHHeeelll lllooom WWWooorrrlllddd!!!MoO q q($><<"!t='#{t}';eval$s=%q(#$s)") ``` [Try it online!](https://tio.run/##TVBBTsMwELznFRs3qDa4CgEqNSHh3EvpBSlnp960Fq63dQw5IN4eHCEhDiuNZnZ3RhO8OR7RT1MamuV2u0VEay3EIaIzALRtG5H3PlJa6zRNd7QHuO73u@RwUl4dAvrbx3VVuYa9EpzJI3QUgsUBqIcO0QM5CCeEUVnLZN8w/sCVzIVUgsku0QSmKUtZyFWRjN4E5J1k3NzPujDS8U1VPIk8d7xY3xW5qURiem7qshQXb1yAPn75Q7LjVbFZxT0h2Zt6x2iPoGl0Ei5qGMAEUJ4@nGYJOq3p95TxOY2bqXT5jJ/KZkNzc@XZS12zuZ3FV/j@LyyyIcabph8 "Trigger ‚Äì Try It Online") The functional part is `HHHeeelll lllooo WWWooorrrlllddd!!!`: triple letters are printed once. (The space between the two `lll` groups is needed for proper parsing.) The `q` (two leading spaces) at the end of the first line is essential to avoid double letters later in the full code (such as those in `bottles` and `beer`) that would otherwise create conditional jumps with hard-to-predict consequences. (Indeed, without `q` the code appears to enter an infinite loop.) This possibility is headed off by jumping forward to the next `q`, which happens to be in the last line of the full program. As far as the outside world is concerned, the remainder of the program is no-ops. ### Quine, Ruby The full program is really just a straightforward extension of the [Ruby quine](https://stackoverflow.com/q/2474861) ``` eval s=%q(puts"eval s=%q(#{s})") ``` with two modifications: (i) the global variable `$s` saves a byte on the string interpolation and (ii) `$><<` is used instead of `puts` to avoid a trailing newline. The rest of the program defines a string variable `t`, which contains all the functional code for the other three parts of the polyglot. The exclamation mark (negation) in `!t` at the top of the program is effectively a no-op (though a warning is emitted to STDERR). [Try it online!](https://tio.run/##TVBBTsMwELznFRu3qDa4CgYqNSHh3EvpBSlnp96oFq63dVwqhHh7cISEOKw0mtndGU24dJ/jmMdmsdlsENE5B2mI6AgAbdsmFEJIlDEmz/Mt7QDOu9022x900PuI4fZxVVW@Ya8ERwoIHcXocADqoUMMQB7iAeGqnWOybxh/4FoWQmrBZJcZAtuUpVRyqbJrsBF5Jxm395MurPR8XaknURSeq9WdKmwlMttzW5elOAXrI/Tpyx@SHa/Uepn2hGRv@h2TPYKhq5dw0sMANoIOdPGGZeiNod9Txqc0fqLyxTN@aDcfmpszn7/UNZvamX3F7//CbD6keOP4Aw "Ruby ‚Äì Try It Online") or [verify quine](https://tio.run/##XVBBTsMwELz7FRu3qDa4hACVmqTh3EvpBalnO3ZUC8dubYcIAW8PiSqhisNKszOzu6MVPByHoa9hWcO9tqcu3kftStTKVejaKwr5Tnxe9fANF0/5XymHIYnVYrvdKqWMMTCWc64FgMPhMCLv/UhJKZMk2bk9wHm/36H6yD2vo/K3T6uisBV@ddA6r0C4GI0K4BoQSnlwFuJRQc@NwaypMHkknKWUcYqZQNKBrvKcZWyZod7rqIhgmOiHSaeaWbIusmeappZkq7ss1QVFuiF6k@f05LWN0Ixb/hATpMjWy9FHGX7j72o8r0C63jI48RBAR@DedVZipKyU7jKKyZTGTlSyKNUHN/NQ3ZzJ/GWzwdN3Zl/x51qYzcMY7xc "Bash ‚Äì Try It Online") (thanks to @DomHastings for the idea) ### *99 Bottles of Beer*, Fortran Fortran's string manipulation capabilities are truly horrendous, but it's one of the few languages I'm proficient enough in to golf *99 Bottles* from scratch. As `!` is the comment character in Fortran, the compiler sees ``` character*35::n="No more bottles of beer on the wall",f="(2(a,/),a)",b do i=99,1,-1 write(b,"(i0,a)")i,n(8:14)//n(15+1/i:) if(i<99)print f,b print f,b,b(:18-1/i),"Take one down, pass it around" enddo print"(a)",n end ``` [Try it online!](https://tio.run/##TZDNTsMwEITveYqNW1QbXAUDlZrQcM6l5ILUs1NvqIXrbR1DD4hnD44qIQ4rfZrZn9H2FGLQfvneX2Ec81gvmqZBROccpCKiIwDsdrtEIYQkGWPyPN9SC3Bu2222P@ig9xHD7eOqqnzNXgmOFBA6itHhANRDhxiAPMQDwkU7x2RfM/7AtSyE1ILJLjMEti5LqeRSZZdgI/JOMm7vJ19Y6fm6Uk@iKDxXqztV2Epktud2U5biFKyP0KctfyQ7Xqn1MvUJyd70B6bzCIYuXsJJDwPYCDrQpzcsQ28MXUcZn9L4ScoXz/il3Xyob858/rLZsOk7s@/489@YzYcUbxx/AQ "Fortran (GFortran) ‚Äì Try It Online") Except for the first and last verses, each iteration of the loop actually prints the last line of the previous verse followed by the first three lines of the current verse. ### Increment, COW As COW completely ignores all non-instructions, all the interpreter sees is ``` oomMoOOOM ``` [Try it online!](https://tio.run/##TVBBbsIwELznFRtDhd0apYZASUp65kK5VOLs4I2warzguM2h6tvTRJWqHlYazezujOZEXd@nsZrtdjtEdM7BMER0AYDj8TigEMJAGWPSNN3TAeB2OOyT01kHfYoY7persvQVeyW4UECoKUaHLVADNWIA8hDPCJ12jsmmYnzBtcyE1ILJOjEEtioKqeRcJV2wEXktGbePoy6s9HxTqlxkmedq9aAyW4rENtxui0Jcg/URmuHLH5I1L9VmPuwJyd70Ow72CIY6L@Gq2xZsBB3owxuWoDeGfk8ZH9P4kUpnz/ip3bSt7m58@rLdsrGdyVf8/i9Mpu0Qr@8XKn/KN8t1vv4B "COW ‚Äì Try It Online") This is a simple sequence of three operations: read an integer from STDIN (`oom`), increment it (`MoO`), and print to STDOUT (`OOM`). TIO's COW interpreter uses signed 32-bit integers so the largest input for which the output is correct is \$2^{31}-2\$. [Answer] # [Help, WarDoq!](https://esolangs.org/wiki/Help,_WarDoq!), [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), HQ9+, [SOGL](https://dzaima.github.io/SOGLOnline/), 15 characters ``` I‚Üê9La@,+1!',kf" ``` I already feel bad for writing this. At least the quine is not in PHP. # Explanation ## Help, WarDoq! Ignores the first 3 characters, `L` prints `Hello World!` and `a` tries to read 2 integers (and exits with an error). ## Befunge [Mostly stolen from this](https://codegolf.stackexchange.com/a/15841). `I` bounces unless redefined by a fingerprint, so it can be used instead of the starting `<`. ## HQ9+ I used the interpreter <http://web.archive.org/web/20060714044320/http://www.safalra.com/programming/interpreters/hq9plus/>. Its output is very similar to the lyrics in the question, but, unfortunately, it's not exactly the same. When I found it, I assumed that there is at least one HQ9+ interpreter that outputs the correct lyrics. However, finding it is left as an exercise to the reader. and since the challenge is inspired by HQ9+, how can HQ9+ be wrong? ## SOGL Implicit input, then `I` increments and `‚Üê` exits (with implicit output). [Answer] # [Hello++](https://esolangs.org/wiki/Hello%2B%2B), [Hüåç](https://esolangs.org/wiki/H%F0%9F%8C%8D), [99](https://esolangs.org/wiki/99), brainf\*\*\*, 5 characters ``` #H,+. ``` --- # "Hello World" in Hello++ According to the language spec: > > Hello++ will print out "Hello World" whenever it encounters 'h' or 'H'. It ignores all other characters silently. > > > So it prints out "Hello World" when it encounters that `H` and ignores everything else. --- # Quine in Hüåç The only needed characters in Hüåç are "h", "w", and "q". All incorrect programs become quines. --- # 99 bottles of beer in 99 All valid programs in 99 print the lyrics to the song we all love. For a program to be valid, it just needs to start each line with a `#` --- # + in brainf\*\*\* All the characters before `,+.` are ignored, and those last three read a number, increment it, and print, respectively. --- I'm not sure if this is valid, but if it isn't, just let me know and I'll remove it. [Answer] # brainf\*\*\*, Java, Groovy, Whitespace, 1461 bytes A tad long, but I'm sure it can be golfed further ``` class Q{//++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.>[ public static void main(String[]a){ Character c=10;char Q=34;char w=32;char t=9;String x="classzz$Q{//++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.>[#publiczstaticzvoidzmain(String[]a){#%#Character%c=10;char%Q=34;char%w=32;char%t=9;String%x=WXW;if(x.contains(WW+Q)){StringzC=WW+c;for(Integerzi=100;--i>0;)z%#%System.out.println(String.join(WW+w,WW+i,i<2?WbottleW:WbottlesW,WofW,WbeerW,WonW,WtheW,WwallW,C.concat(WW+i),i==1?WbottleW:WbottlesW,WofW,WbeerW,C.concat(WTakeW),WoneW,Wdown,W,WpasszitzaroundW,C.concat(i==1?WNozmoreW:WW+(i-1)),i==2?WbottleW:WbottlesW,WofW,WbeerW,WonW,WtheW,WwallW,C));%}#z%else###System.out.println(x.replace((char)122,w).replace((char)35,c).replace((char)87,Q).replace((char)37,t).replace((char)36,w).replace(c.toString(88),x));}}//]";if(x.contains(""+Q)){String C=""+c;for(Integer i=100;--i>0;) System.out.println(String.join(""+w,""+i,i<2?"bottle":"bottles","of","beer","on","the","wall",C.concat(""+i),i==1?"bottle":"bottles","of","beer",C.concat("Take"),"one","down,","pass it around",C.concat(i==1?"No more":""+(i-1)),i==2?"bottle":"bottles","of","beer","on","the","wall",C)); } else System.out.println(x.replace((char)122,w).replace((char)35,c).replace((char)87,Q).replace((char)37,t).replace((char)36,w).replace(c.toString(88),x));}}//] ``` --- ## brainf\*\*\* code (ignoring other characters): ``` ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. >[[]++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.>[[].++-->...+,+,<,,,,,,.+,,,,.,,,,,.+-,,,,,,,...,.,.,.,.,..,].++-->...+,+,<,,,,,,.+,,,,.,,,,,.+-,,,,,,,...,.,.,.,.,..,] ``` [Try it in brainf\*\*\* online!](https://tio.run/##zVJNi9swED3bv0LINVhEdr7abrqO3UNOvSyELbgQcnAUZVddxwq2UqcO@e3pKPLmawuhPZQKPHoSM8/zRm9WpCJfrNnLfs@ytCwRQuNtu91q1iR@jRqYbwjLn8aAYj@OW5PhVB/jIPZ9P2jqAg0CuBz6wfCA/cNqNgBQGcQ6Z2Kv1rNMMFSqVMH2Q4o5WkJX3qMqRP40maZka1v26DktUqZ4YbGo2wkZHK1x1H9vUBX1ewap6FNoKq1NhA@i6vrdvxblGFG1EVVrUfW1KMd1jqLcoyj3KMo9inJPotxNlHxLQrHwNgGTuQLO0kuS1piQrcmoRxGcWbiQhfclV/yJF7UA9k7o@yLuhKR2HffxZ6n4MpBrFaygSGWvnQXfJXQJBBWFIKgY9j4nM6lUxpP7BpQJTeQCwozzQuMcgnrmEKs0yxI60q2xVGkeQaiIou4tklPJ1/SFJ0SzasK5rHIK@0q/o1B1Wsh1Pj/LN@QPsl7KQrMnLU/4XXL469@0Tkjo7pza5VnJHcf5zaA2QcFXWcq45@nHId1ej1bk6rL/gbLru8EdHb/Ju6Pqzd3Hcz4WKGnexhsMCN1Ag7tduz3FVybA@MwEaBTB@cIE6MIEyLKtGyYAgopCMCbAZoD4vgElplguIOhJapxDgElC1JPEpxfSFI0JbpCcSrQJMNGsmvBgAti1CZBQyJgAX5kAP0ikTQDs@MIEf946zNja2cjSJrBt@/81wX7/Cw "brainfuck ‚Äì Try It Online") **Edit**: Originally, this didn't work because while testing, I used the wrong version of my code. It's fixed now, but even longer than it was before. The first line prints "Hello world!", and the second line basically just makes sure the rest of the code never runs by moving to a cell that's 0 and wrapping everything inside square brackets. --- ## Whitespace code (ignoring other characters): ``` [S] [S] [S] [LF] [S] [S] [S] [LF] [T] [LF] [T] [T] [T] [T] [T] [S] [S] [S] [T] [LF] [T] [S] [S] [S] [T] [LF] [S] [T] [LF] [LF] [LF] ``` Explanation: ``` [S][S][S][L] ---- push 0 [S][S][S][L] ---- push 0 [T][L][T][T] ---- read a number and put it at address 0 in the heap (0 because the top of the stack is 0) [T][T][T] ---- retrieve the number at address 0 in the heap [S][S][S][T][L] ---- push 1 [T][S][S][S] ---- add [T][L][S][T] ---- print the number at the top of the stack [L][L][L] ---- exit the program ``` [Try it in Whitespace online!](https://tio.run/##zVNNj9owED0nv8JyGikWjlmg7dINSQ@celkJbaVUQhxCMIvbEKPENGwQv52OcZavrYTaQ1VLzDxbnse88Uu1EIqXqyTl@32aJWWJEBpt2@1Ws8bRa9TA/Aaw/EkEKPKjqDUeTPQ2YpHv@6ypYxowOBz4bHDA/mE1CQBUskjfGdur9TQTKSpVoiD9lGKGlonIvSdViPx5PEnI1rbs4SIpklTxwkrDzl2QwtYahb33BlVhr2uQCj8FptLahPggqq7f/WtRjhFVG1G1FlVfi3Jc5yjKPYpyj6Lcoyj3JMrdhPG3OBBzb8NSmSvgLL04bo0I2Zob9TCEfRrMZeF9yRV/5kUtgP0u8H0R3QWkdh336aVUfMnkWrEVFKnstTP2XUKXQFBRCIKKQfdzPJVKZTx@aEAZ01jOIUw5LzTOIagFh1glWRbToW4tTZTmEYSKMOzcIjmVfE1@8JhoVk04k1VOIa/0OwpVJ4Vc57Oz@4b8UdZLWWj2uOUJv0MO//o3rRMSuDundnlWcsdxfjOoDSv4KoNvxvP045BOt0srcnXY@0DT67P@PR29uXdP1Zuzj@d8KVPSvI3X7xO6gQZ3u3Z7gq9MgPGZCdAwhP2FCdCFCZBlWzdMAAQVhWBMgM0A8UMDSkyxnEPQk9Q4hwCThKgniU8vpCkaE9wgOZVoE2CiWTXhwQSQtQmQUMiYAF@ZAD9KpE0A7PjCBH/eOszY2tnI0iawbfv/NcF@3/kF "Whitespace ‚Äì Try It Online") --- [Try it in Java online!](https://tio.run/##zVJNj9owED0nv8JyGikWTvhqu3RD0gOnXlZCWymVEAcTzK7ZEKPELDSI307HOMvXVkLtoaqljJ@tmZd54zdnr8yfT1/2@zRjZYkQGm6bzUa9RvFb1MB8fVj@OAYU@3HcGPXH@hgHse/7QV0XaBDAZd8P@gfsH1a9AYDKINY5I3u5mmQiRaViCrZXKaZowUTuPapC5E@jMSNb27IHz6xgqeKFlUbtVpjC0RpG3Y8GraNuxyAVfQlNpbWJ8EFUVX3416IcI6oyoiotqroW5bjOUZR7FOUeRblHUe5JlLuJkh9JKGbeJkhlroCz9JKkMSRkazKqQQTnNJzJwvuWK/7Ei0oAeyv0fRG3QlK5jvv4s1R8EciVCpZQpLK3zoK5hC6BYE0hCCr6na/JRCqV8eS@BmVCEzmDMOG80DiHoJ45xDXLsoQOdGspU5pHECqiqH2L5FTynb3whGhWTTiV65zCvtTvKFTFCrnKp2f5hvxBVgtZaPak4Qm/TQ5//ZvWCQndnVO5PCu54zi/GdQmKPgyYyn3PP04pN3p0DW5uux@oun1Xe@ODt/l3VH17u7zOV8aKGnexuv1CN1Ag7tdsznGVybA@MwEaBDB@cIE6MIEyLKtGyYAgjWFYEyAzQDxfQ1KTLGcQdCT1DiHAJOEqCeJTy@kKWoT3CA5lWgTYKJZNeHBBLBrEyChkDEBvjIBfpBImwDY8YUJ/rx1mLG1s5GlTWDb9v9rgv3@Fw "Java (JDK) ‚Äì Try It Online") --- [Try it in Groovy online!](https://tio.run/##zVJNj9owED0nv8JyGikWjvlqu3RD0gOnvayEtlIqIQ4hGNZtiFFiFjaI307HOMvXVkLtoaqljJ@tmZd54zcvpHx53e/TLClLhNBw22w26jWK3qIG5uvD8scRoMiPosaoP9bHiEW@77O6jmnA4LLvs/4B@4dVbwCgkkU6Z2QvV5NMpKhUiYLtRYopWiQi955UIfL5aJyQrW3Zg@ekSFLFCysN260ghaM1DLsfDVqH3Y5BKvwSmEprE@KDqKr68K9FOUZUZURVWlR1LcpxnaMo9yjKPYpyj6Lckyh3E8bf40DMvA1LZa6As/TiuDEkZGsyqkEI5zSYycJ7yBWf86ISwN4KfF9ErYBUruM@vZaKL5hcKbaEIpW9dcZ@SOgSCNYUgqCi3/kaT6RSGY/va1DGNJYzCBPOC41zCOqZQ1wnWRbTgW4tTZTmEYSKMGzfIjmVfEt@8phoVk04leucwr7U7yhUlRRylU/P8g35o6wWstDsccMTfpsc/vo3rRMSuDuncnlWcsdxfjOoDSv4MktS7nn6cUi706FrcnXZ/UTT67veHR2@y7uj6t3d53O@lClp3sbr9QjdQIO7XbM5xlcmwPjMBGgQwvnCBOjCBMiyrRsmAII1hWBMgM0A8X0NSkyxnEHQk9Q4hwCThKgniU8vpClqE9wgOZVoE2CiWTXhwQSwaxMgoZAxAb4yAX6USJsA2PGFCf68dZixtbORpU1g2/b/a4L9/hc "Groovy ‚Äì Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), [Python 3](https://docs.python.org/3/), HQ9+, [Python 2](https://docs.python.org/2/) [`-O`](https://codegolf.meta.stackexchange.com/a/14339/91267), 84 bytes ``` s="print(8/9and's=%r;exec(s)'%s or __debug__*'\\x48ello World!'or-~input())";exec(s) ``` [Try H online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM69Ew0LfMjEvRb3YVrXIOrUiNVmjWFNdtVghv0ghPj4lNak0PT5eSz0mpsLEIjUnJ18hPL8oJ0VRPb9Ity4zr6C0RENTUwmm7/9/AA "Python 2 ‚Äì Try It Online") [Try Q online!](https://tio.run/##K6gsycjPM/7/v9hWqaAoM69Ew0LfMjEvRb3YVrXIOrUiNVmjWFNdtVghv0ghPj4lNak0PT5eSz0mpsLEIjUnJ18hPL8oJ0VRPb9Ity4zr6C0RENTUwmm7/9/AA "Python 3 ‚Äì Try It Online") [Try + online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM69Ew0LfMjEvRb3YVrXIOrUiNVmjWFNdtVghv0ghPj4lNak0PT5eSz0mpsLEIjUnJ18hPL8oJ0VRPb9Ity4zr6C0RENTUwmm7/9/QwODf/kFJZn5ecX/df0B "Python 2 ‚Äì Try It Online") ]
[Question] [ With this challenge we pay homage to everyone around the whole world fighting against the coronavirus crisis; particularly represented are the people tied to medicine, as the [*Rod of Asclepius*](https://en.wikipedia.org/wiki/Rod_of_Asclepius) is a symbol associated with medicine and health care. For that matter, we resort to some ASCII art found at [asciiart.eu](https://www.asciiart.eu/logos/caduceus) (wrongfully) listed under the ASCII art associated with the Rod of Caduceus. # Task Your task is to print or return the following modified art of an original by Juergen Jakubowski: ``` LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LLL LLLLLLLLLLLLLLLLLLL LLL LLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLL LLLLLLLLLL LLLLLLLLL LLLLLLLL LLLLLLLLLL LLLLLLLLLLLLL LLLLLLLLL LLLL LLLLLLLLLLLLL LLLLLLLLLLLLLLLLL LLLLL L LL LLLL LLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLL LLL LL LLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLL LLLLLL LLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLL LLLL LLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLL LLL LLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLL L LLLLLLLLLLLLL LLLLLLLLLLLLLLLL LL L LLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LL L LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLL LLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL L LLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLL LLLLLL L LLLLLLL LLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLL LLLLLL LLLLLLLLL LLLLLLLLLLLLLLL LLLLLLLLLLLL LLLLLLL LLLLLLL LLLLLLLLLLLL LLLLLLLL LLLLLLLLL LLLLL LLLLLLLL LLLLL LLLLLLLLLLL LLLLLL LLLLL LL LLLLLLLLLLLLLLLLLLL LL LLLLLLLLLL LLLLLLLL LLLLLLLLLL LLLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLL ``` This art has been made more symmetrical, non-L characters have been replaced by Ls and the author name and e-mail have been removed from the art. You may add/remove leading/trailing whitespace as long as the layout of the Ls and the whitespace within them doesn't change. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing! [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~304~~ ~~291~~ ~~288~~ 284 bytes -2 bytes thanks to xnor. ``` i=k=0 for c in b"b!FjnuaV5 k6[ZvtUk]-M81/DoW(3D|I]wB$j;D0mR' |tBjimp?$NAWR5N^21ZLk#sqG:GRQcB XMAgSYaZL\:%El2:=T{Kw%o,pd3Tav[pM$ -&pN|jVdYlavl^;8E?zI\"PQ5:%A>yHa:7^) ,LX~3RH^bG;dGg.2{xsqLW5o":i=i*100+c-27 s='' while~i+k:c=i%37;i//=37;s+=' L'[k]*c;k^=1;c or print(f'{s:^71}'+(s:='')) ``` [Try it online!](https://tio.run/##Dc/bboIwAIDhe19hmXZOVhWdHMIwJZ3R6NAMzWTOsySIp1KEKkzndL468@q/@5KfnaJN4Mtlto9jgikWEqtgDxxAfDBPzx/eXP/b7iv39GUyvjtEX3RWbJfFUj0YZOX6pTU71jKuVhe2JgSXqOaSLatkOtWBqXQsSUyNDfoY7nSkm12nlhy2q@vPkT02pohreBLCvfP7kQsKbCH37MOEtTPJ4hPrXNz@YuTZB8/Syo3Kb2ua/ugqiKu@npo2Uq1cChSM4VU2m9Zc1xb6@lk6/4Q7Y6AEaUQwyYuCwDtFSU2EGMLEcUO85ZXwFDmYcLKqkVIJ3xLyGAIDTugs72jUwqLmgNs42xM/yq7gOUSWKv5BPhuiG5PLxfE/ "Python 3.8 (pre-release) – Try It Online") Since the string contains some unprintables, here is a hexdump: ``` 00000000: 6221 466a 6e75 6156 351d 6b36 5b5a 1b76 b!FjnuaV5.k6[Z.v 00000010: 7455 6b5d 2d4d 3831 2f44 6f57 2833 447c tUk]-M81/DoW(3D| 00000020: 495d 7742 246a 3b44 306d 5227 207c 7442 I]wB$j;D0mR' |tB 00000030: 6a69 6d70 3f24 4e41 5752 354e 5e32 311f jimp?$NAWR5N^21. 00000040: 5a4c 6b23 7371 473a 4752 5163 421e 584d ZLk#sqG:GRQcB.XM 00000050: 4167 5359 615a 4c5c 3a25 456c 323a 3d54 AgSYaZL\:%El2:=T 00000060: 7b4b 7725 6f2c 7064 3354 6176 5b70 4d24 {Kw%o,pd3Tav[pM$ 00000070: 1e2d 2670 4e7c 6a56 6459 6c61 766c 5e3b .-&pN|jVdYlavl^; 00000080: 3845 3f7a 4922 5051 353a 2541 3e79 4861 8E?zI"PQ5:%A>yHa 00000090: 3a37 5e29 1f20 2c4c 587e 3352 485e 6247 :7^). ,LX~3RH^bG 000000a0: 3b64 4767 2e32 7b78 7371 4c57 356f ;dGg.2{xsqLW5o ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~325 ... 276 273~~ 260 bytes ``` s="";i=0 for n in b"_____)393O-090S0-/(.-V3+/,*+Y7(+''((**(]=))((*b=,,(d=*/(e>+*+gA.nC0jC/eC-aC,\<()+Y:*'+Y6(()')X9)((''_;,d?-eC.fH-hJ*gF'))fE)'(fA,h8',)'(-'^5*,*/*[2,-+-,X.//++/T+21(,2Q(494N0'T0'T___": s+=n%38*"L "[i];i^=1 if n>75:print(f"{s:^71}");s="";i=0 ``` [Try it online!](https://tio.run/##NY9RS8MwFIXf@ytCQHKTmzRZu9m1NZNRJiKiiENW5joca9b6kI11LyL@9lofPJyH7@WDc05fl@bo477vLKV5a03gjmfiSevJjm7/wuM0flYmNa9GaQjVW4xaCiwTQMYAhICN5XyAnZUS9lZoqGco8DAPfWE@C10X6qOQ7zfAscwEw/IagDO@SgeJsW0u97eqLkJ3r5oHcbhjnLsFZ@DmspkyOZBi1URIocU6kgqVXIVaI@olRiOQ0QuM0/GTYcuhw1yaBaRD66/iqaCPhK7bTd5WdhSQ1hE/SybZ6dz6Czj63WVVMvqhPP//3ve/ "Python 3 – Try It Online") **How**: The big idea is to encode each line as a list of integer, each denotes the number of consecutive `"L"` or `" "` characters. For example, `[1, 2, 3]` denotes `L LLL` (1 `L`, 2 spaces, 3 `L`). Each list of integer can be further encoded as a byte-string (Python3 byte string acts similarly to a list of code points). The run lengths are between `1` and `36`, most of which are unprintable ASCII code points. Thus, I map each integer `i` to `i+38` instead. The above example would maps to: ``` "L LLL" -> [1,2,3] -> [39,40,41] -> "'()" ``` (38 is chosen instead of 37 because it prevents a backslash character `\` that needs to be escaped). The new line character can be sneaked into a sequence by adding an extra `38` to the end of each line. ``` "L LLL\n" -> [39,40,41] -> [39,40,79] -> "'(O" ``` In summary: for each code point `n` in the byte string, `n%38` gives the length of the current run, and `n>=76` if the current run is the end of a line. ~~I use [Neil's idea](https://codegolf.stackexchange.com/a/204304/92237) of only compressing the left two thirds of each line, then mirror the rest to save more characters.~~ I additionally exploit the symmetry of the shape by ignoring the spaces on both side of each line. When decoding, I center align each line in a block of width 71. (This idea is the same as [ovs's approach](https://codegolf.stackexchange.com/a/204295/92237), though I came up with it independently). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 170 bytes -9 bytes thanks to @mypronounismonicareinstate. -1 byte thanks to @KevinCruijssen. ``` •2yÂ6:å₂øǝ₄²¤ΩàΘ₄IüÊX¹åêøë®Ñ¼(á׿ìŒΓÉnγΘi‰—θвƶ\`α\ǝ)t~óÌ dHD{iÍ;½vŽć·µ°Ãô-©ã„jΛ":иdC{!hâ'gÊć'Ž?«*9¢h¬βÉšGƶ¿Ć9₄>G>„FèQäªj'₂¿TNt …ΣSjδ!¯„мŸ>₅&¯!E-&&Wž™è°‹aтćËà•₆в„ LÞ×J69ô» ``` [Try it online!](https://tio.run/##DZDNSgJhGIX3XYW20ArctBA0sEU/VkQQBbVwkWGkLmqRBCHEMJmi1SILFELRUcM/0kazkTThPTO6@5hu4buR6VseeB54OJdXwdPImWVxSVm@gez2osZlGdqswOUEqVRlDZRYXoxtjJA5piFqaEJDiz7wTKMFlJGjCdpGlr0gfcF6LB/hUpdLr0wz1ekgcMI@A7PCYuwWPTzOhbbW4xE8rdD42hjrKfqmL@riDn0XNVDhUjHK3ua9phZai9vDUJznyOgppzFepdaSh5QwtZmKtFH2Twc00ZMeEebz@4S3ifo@qtSMOkU/TQ73YjYuvbPKQZT17dQRhDkyNB@X7x3UsW@4HI4j45cnFNRJxA6Df7KewgNK4gguJ01VCLZdFJHbcXvQpx/L@gc "05AB1E – Try It Online") ## Explanation ``` •...• Gigantic packed integer-list of run-lengths 37в Convert it from base 37 „ L Length-2 string " L" Þ Extend to the length of the other operand × Multiply them J Join the output string 69ô Split into chunks of length 69 » Join by newlines ``` [Answer] # [Python 3](https://docs.python.org/3/), 341 bytes ``` for c in b'[S [S [S [S [S KCMSMC JGJSJG JJGIBHGJ IMEIFDEM HQBEAABBDDBQ GWCCBBDV FWFFBX EWDIBY DXEDE[ B[Hb B]J^ E]IY H]GU K]FP NVBCEM OTDAEM QPBBCACL MSCBBAAS KUFX HYGY E]HZ BbG\\ CdD[ D`ACCZ E_CABZ F[F\\ HRAFCABGAR HODFDIDO ILFGEGFL JHIIEEIH JELKBFLE KBNSNB [JAH [JAH [S [S [S'.split():print(''.join(' L'[i%2]*(j-64)for i,j in enumerate(c))) ``` [Try it online!](https://tio.run/##TVDLTsNADPyVuaAkCHoAxIHbet@bpK/Qpuk2PFqKSAVpVcKBrw9bqQckazwjyyN7Dr/dx7697fv3/REbNC3WkS/wv1KeFzmH065wGs5pS0Y72FxaJWQOMyHJGJEQNIEuOQ90DlUqRQvIUliqIBZSSA/yZg2q3RNkbSuYWs@Q1mqM4Zx4sBo9ChbaZEzEGc@QF8GMsXDDTC1gKl2FRbMErfVqBf4mPMQL43wJ@cwZLaG8CgMzZSpIzaYwI6GEFSPYTGmpVQZnrJXSGjiZpaQyiZSGxZDgHTNnOL8eDb4Pn00XJw@HY9N2cRQNdvumjSNkkW8uburLeHd9f5ecsmuudqf0tu3P1/b42m3jTZIkff8H "Python 3 – Try It Online") Basic run-length encoding [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 202 bytes Uses the file with all unnecessary leading and trailing whitespace removed. Since the code is a raw DEFLATE stream, here's a hex dump (not that it helps significantly): ``` 00000000: d596 410a 4331 0805 f739 8507 eafd cf53 ..A.C1...9.....S 00000010: 0882 30e2 2059 b559 257d ce53 acc2 8fe9 ..0. Y.Y%}.S.... 00000020: 7cfa 39ff 195c a207 77fd 2076 0933 758b |.9..\..w. v.3u. 00000030: a977 7405 74cf 0137 fe9e 3868 648c 7b29 .wt.t..7..8hd.{) 00000040: bcf7 0d38 cb48 6a0e 3aca 9788 2038 0c12 ...8.Hj.:... 8.. 00000050: 9b28 1693 24bd 8387 6832 0e7b 171b 2c6f .(..$...h2.{..,o 00000060: 8918 a9c5 d2c5 f89d 85ae ee04 da3c 0365 .............<.e 00000070: 4607 4b44 be24 89f9 b25f 141a d07d 6708 F.KD.$..._...}g. 00000080: efff 9ad7 09d9 8faa 5521 2e54 7d91 657f ........U!.T}.e. 00000090: fde4 b8bc ef4c f26e e11e 8b6e 4c21 810a .....L.n...nL!.. 000000a0: eec3 78e6 c50d 0ff0 3156 8dfb b40d c5d2 ..x.....1V...... 000000b0: b05e d440 0fcb 980f c858 27ae 320f 0276 .^[[email protected]](/cdn-cgi/l/email-protection)'.2..v 000000c0: df0a acd3 837f edfb e60b .......... ``` [Try it online!](https://tio.run/##XZNbaxRBEIXf/RUnoKggRfW9OvigKCKYt6gYEKWvCaLxJZsIMb99rdmdZMGCbXpnOF@dukzd1PpznG9@bbe8xjF6yBHecIF3zoCFA2ZyGRI4YZTZ0WZwANFremOIKNMSp4/2BKMMFrFwPCwsh4wa9LAhqXKosrRmIXPkhcGEMzp7ckenC2RlWGWkNgtcnhMmh4ZiNXtKml0vEZydQwpSgb@Lga9EN4Rrcpt7hlNGyUlFXitIvk2wcQmad8BJFEQvDanaxcfNFV0RJSK56HT7fGV4ZdQ2E7g7QateRYVVXlpBTiJqRl9wM3aphYTe/6BjvUAeagnKyNUKTMwO1tcOcZIQxVnwSBUmmQrb4lTGM6LHqr@wdEv04vfKiMqQbEQLagHd6jElKyiUgTHYoxfXwC6GnY9DvKSxMpIyfNQm@uo96rBekVOHY4O22JuCzjqhmFiAd/Th7c7Id/3dnd/XIsoYU0eSS9em5K5bMUtBCNbAjuCRejaIIc2Dj09H9PGOxj0jK2P2oRakNqX5hmmjlmHMgFS9@aY0WTZwzzihSz0vT44eeloWH6PpBsiIaIE7eE6GMyFC@qyoXp@10Hdz@bPDmM97PyujLrPlMNC9Z5W3iiw80SToWJM21ln9y1a3DfSNXu3EX56SJbpeGW35XqYaLa07HauWPZbsI7Iu5n9xGMp2@w8 "Bubblegum – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~186~~ ~~175~~ 174 bytes ``` “ç⁺lñỊɓ¡ḌỌKḃßƇ[Æ÷ịœi#⁵Q#^Fo$Q$'ẠKẏȤ⁴ịɲɦʋỌ⁷ḄLqẏ⁺nÄẉ⁾ṀⱮsọḢɲlọȮḄṡ-$ɓv?KggjḞƭCid/ Ȥx?ßɓṇȯ¢ḋ®ṖIQṁ"œıṚ/£;ẉ*ȧ%¹ȯḷŻṖ4eS⁸w÷ƭʋịṢḤUKGɦðþḥ³-_?ß§lÇĠⱮkĠƝẎ3UỌYBTẋŒØL®œƇỊ⁼Ẓd’b37⁶”L2ƭx$€Fs69Y ``` The part at the end can almost certainly be golfed, as I'm relatively bad at Jelly. Certain very long run lengths are replaced by shorter ones and a zero in the integer (e.g. `[..., 63, ...]` is changed to `[..., 32, 0, 31, ...]`). ### Explanation: ``` “...Ẓd’ very large integer b37 decode into base 37 digits ⁶”L2ƭ magically alternate between spaces and Ls x$€ those characters repeated each element times Fs69Y flatten, split into 69-long slices and join by newline ``` [Try it online!](https://tio.run/##FZBNSwJRGIX/SuREEIiQUUQLocCIcSPlQoKCUEQbihDKdnNLkhorcCAqMj8y3eSY9jH3zoSLe51hpn/x3j8y3XYvnHMeznsKWUU5DQKuPrEeR5bChmBf@TptAa6CXZUBn7OGW9lmF8wEW3P0fIijr2RoJ34oJaVZsJoyWLdeh6NPIfsjv/uriRxHJuBy4khognrAymBdcjQGovKhUQT7GnDbHyni8AxhBNIKS75@HJNzuQLgZ7e/ls9EprxOKcYavg6k4g1oG7BGDSB3G0kgaNrRJ0MgjxH6siLgc15vhhJvANh0bOFZyG5yhE@Y6fb/C2lARLyTktf9LntnY8Cv9CO8K@i0p7DKpClq7U@abh2sm2hKPJBe3QJLc2rsPkENR3crYhaOfsCqZbj6sBdd4uibq/XEvNsvSfzsLV5cXE4HQfAH "Jelly – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 167 bytes ``` ”}∨|Sλχ6?↗⊕H4R¬.Y3nLïB⁷ζ↧*⟧﹪∨?F⬤SYηT⌊…δⅈJK´u&⸿ZÀec⎚υιw↙SkêX⁼E³ZGςδ=⪫s{εηB(⊘{⁷,W∧⸿ηSBiYγ\>tI;~↓EjZ0⪫|∨_D?YT⟧?↘JIψ∨;2≔↑⁵C⊕W⦄M↓|⮌κ¬Qb›b{″FJHo??◨χcμχ‴Z⁷ⅈ5Oν⭆.¶◨D3e]”‖OO←¹⁹ ``` [Try it online!](https://tio.run/##vZTBCoMwDIbve4rgSWE77Lj5CoWNnb2IVDYobhTx9TvQ1rZp0/Yw5kVoPn@TP0mHZy@Hdy@UusvXNNcVC59u@tMhuE8eCqX2M@YjmDIhxFgMVimLxfPfwi4ZL9TNheJW0pOhSYMSNVAJJDGv/sDjJO1@kEdjzaEHI07ilpN91LEEoLvHUNzMwRZmQGeartv@ptCevPHBJENRi6wZZdL7fBelwUrQ8mw9RUgrporzbSVnClsan2nPSrvPaFnyNxugbYiuyI@u1KppDw8@Cj7Mt4VL0X/0q74yPs5HOF@aVil1WsQX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The compressed string literal encodes the right two thirds of the output and then the right third is reflected to complete the image. If the image was more vertically symmetric then it might have been possible to save a few more bytes. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~290~~ 285 bytes ``` 19¶19¶19¶19¶19¶3je19¶7jb19¶10h9c8¶13f9g4¶17c5b1c2e4¶23d3c2e2¶23g6c3¶23e9c3¶24f4f4¶27i9¶29jb5¶29j3¶29h2¶29g¶22c3f¶20e1f1¶16c2d1d2¶19d2c1b5¶21g8¶25h6¶29i4¶34h3¶36e3¶32b3d3¶31d1c4¶27g7¶18b6d1c7¶15e6e9¶12g7f7¶8j9f5¶5jd11c6¶2jf19¶10b8¶10b8¶19¶19¶19 \d+ *L T`l`d \d * P^`.+ %`.{19}$ $&$^$` ``` [Try it online!](https://tio.run/##XZA9TgQxDIX7nIJioNiVVmtnkkzuQEFBiVYhvzPRigLRIa7FAbjY8BykLVAUf3ai9@zkvXxsb6@074r8z/f/rXsRuB7HyXn1aQF19W0GXTKREhfkrLNGxpI1m7Sw@MG5YoFugwf7Hs2AXPlVBL4hcNIVOBeqBGubOFNmGSNzoqGhhuZsViuaDZZ6XuGibZHIESOAlCmNds1BvUSLWjJTbJFHcHMV9dJ9hanpmSiJY69/b4zLLd5@Qr3kozo8qudwDRmFOtypp0s4HdV9OH2S/5rU9DBdprDvvw "Retina – Try It Online") Edit: Saved 4 bytes by encoding the left two thirds instead of the right two thirds. Explanation: Uses run-length encoding. The integers encode runs of up to 34 `L`s while the letters `b-j` encode runs of 1-9 spaces with `jb-jf` encoding runs of 10-14 spaces as this saves a byte in the decoder. The first line simply inserts the encoded data. ``` \d+ *L ``` Run-length decode the integers to `L`s. ``` T`l`d ``` Transpose the lower case letters to digits in preparation for run-length decoding. ``` \d * ``` Run-length decode the digits to spaces (each digit decoded separately). ``` P^`.+ ``` Left-pad all of the lines to the same length. Annoyingly the `P` command (unlike, say, the `O` command) does not have a useful default, which might save 2 bytes here. ``` %`.{19}$ ``` Match the last 19 characters on each line. ``` $&$^$` ``` Append their reversed prefixes, thus mirroring the output. [Answer] # JavaScript (ES6), ~~315 308~~ 305 bytes *Saved 3 bytes thanks to @ASCII-only* The data string is only 163 bytes long, which is pretty good. But the decompression code is too verbose. ``` _=>`jJJJJ 3dj 7ajA7928D5964H25112244N332242N6623N4923O5454R89Ta5T93T72T6M235K4151G223132J322115L68P76T84Y73Z0143W1333V3124R67I163127F4649C6757 89955 5cb26 2ejA18A18JJJ`[R='replace'](/[A-Z]/g,` $&`)[R](/.+/g,s=>(s=s[R](k=/./g,x=>' L'[k^=1].repeat(parseInt(x,36))).padStart(45))+(g=k=>k--?s[k]+g(k):'')(26)) ``` [Try it online!](https://tio.run/##FY7dToNAEIXveQovjOymhboz@wMmi2k0amutBonGEpSVUiI0hQAxffu6nkwyZ77MTE5tfs1Q9D/d6B3abXna6dOXjvJ6aeXgtnaUqecqhOBWhJI/gGAMgPM1om2wlhJwzUPAZ8EFj4MwMSIJMVGQyCdA8ciZYPcAyBCW9oQxsZLBi5JJwD8Ubi4Zx3eGiG/IgMdSLZi0Tt1xycMbqYRygjAUwhHFN0gHynrOAls2XZ7G2u3Lbm@K0s3ILJ17m2xWTXPn/CKnaWyRP7HzoCMy6OEfNHrmW3LUkXu2ctPmU7PMty9KM5LO9EO5OIzkOEVJKfU7s30dTT8SLiidkEo3Omo873pIm2xSkYZeuS4lYHdPRXsY2n3p79uK7IgFfw "JavaScript (Node.js) – Try It Online") ### Decompression We first insert a line-feed before each letter in upper case. For instance, `7ajA7928D5964H25112244` is turned into: ``` 7aj A7928 D5964 H25112244 ``` For a given line, we convert each character from base 36 to decimal: ``` "D5964" ~> [ 13, 5, 9, 6, 4 ] ``` For each value \$n\$ in this list, we generate a string of \$n\$ characters, alternating between `"L"` and `" "`: ``` [ 13, 5, 9, 6, 4 ] ~> "LLLLLLLLLLLLL LLLLLLLLL LLLL" ``` We insert as many leading spaces as necessary to reach 45 characters and append the first 26 characters at the end in reverse order: ``` <-------------------- 45 -------------------> " LLLLLLLLLLLLL LLLLLLLLL LLLL" " LLLLLLLLLLLLL LLLLLLLLL LLLL LLLLLLLLLLLLL " <---------- 26 ----------> <---------- 26 ----------> ``` [Answer] # Deadfish~, 5802 bytes ``` {i}{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{{i}dddddd}iiiiccc{{d}iiiiii}dddd{c}ccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}ccc{{i}dddddd}iiiiccc{{d}iiiiii}dddd{c}{d}{d}ddc{i}{i}iiccccccccc{{i}dddddd}iiiiccccccc{{d}iiiiii}dddd{c}{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{{i}dddddd}iiiiccccccc{{d}iiiiii}ddddccccccccc{d}{d}ddc{i}{i}iiccccccccc{{i}dddddd}iiii{c}{{d}iiiiii}ddddccccccc{{i}dddddd}iiiiccccccccc{{d}iiiiii}ddddcc{{i}dddddd}iiiicccccccc{{d}iiiiii}ddddccccccc{{i}dddddd}iiii{c}{{d}iiiiii}ddddccccccccc{d}{d}ddc{i}{i}iicccccccc{{i}dddddd}iiii{c}ccc{{d}iiiiii}ddddccccc{{i}dddddd}iiiiccccccccc{{d}iiiiii}ddddcccccc{{i}dddddd}iiiicccc{{d}iiiiii}ddddccccc{{i}dddddd}iiii{c}ccc{{d}iiiiii}ddddcccccccc{d}{d}ddc{i}{i}iiccccccc{{i}dddddd}iiii{c}ccccccc{{d}iiiiii}ddddcc{{i}dddddd}iiiiccccc{{d}iiiiii}ddddc{{i}dddddd}iiiic{{d}iiiiii}ddddcc{{i}dddddd}iiiicc{{d}iiiiii}ddddcccc{{i}dddddd}iiiicccc{{d}iiiiii}ddddcc{{i}dddddd}iiii{c}ccccccc{{d}iiiiii}ddddccccccc{d}{d}ddc{i}{i}iicccccc{{i}dddddd}iiii{c}{c}ccc{{d}iiiiii}ddddccc{{i}dddddd}iiiiccc{{d}iiiiii}ddddcc{{i}dddddd}iiiicc{{d}iiiiii}ddddcccc{{i}dddddd}iiii{c}{c}cc{{d}iiiiii}ddddcccccc{d}{d}ddc{i}{i}iiccccc{{i}dddddd}iiii{c}{c}ccc{{d}iiiiii}ddddcccccc{{i}dddddd}iiiicccccc{{d}iiiiii}ddddcc{{i}dddddd}iiii{c}{c}cccc{{d}iiiiii}ddddccccc{d}{d}ddc{i}{i}iicccc{{i}dddddd}iiii{c}{c}ccc{{d}iiiiii}ddddcccc{{i}dddddd}iiiiccccccccc{{d}iiiiii}ddddcc{{i}dddddd}iiii{c}{c}ccccc{{d}iiiiii}ddddcccc{d}{d}ddc{i}{i}iiccc{{i}dddddd}iiii{c}{c}cccc{{d}iiiiii}ddddccccc{{i}dddddd}iiiicccc{{d}iiiiii}ddddccccc{{i}dddddd}iiii{c}{c}ccccccc{{d}iiiiii}ddddccc{d}{d}ddc{i}{i}iic{{i}dddddd}iiii{c}{c}ccccccc{{d}iiiiii}ddddcccccccc{{i}dddddd}iiii{c}{c}{c}cccc{{d}iiiiii}ddddc{d}{d}ddc{i}{i}iic{{i}dddddd}iiii{c}{c}ccccccccc{{d}iiiiii}dddd{c}{{i}dddddd}iiii{c}{c}{c}{{d}iiiiii}ddddc{d}{d}ddc{i}{i}iicccc{{i}dddddd}iiii{c}{c}ccccccccc{{d}iiiiii}ddddccccccccc{{i}dddddd}iiii{c}{c}ccccc{{d}iiiiii}ddddcccc{d}{d}ddc{i}{i}iiccccccc{{i}dddddd}iiii{c}{c}ccccccccc{{d}iiiiii}ddddccccccc{{i}dddddd}iiii{c}{c}c{{d}iiiiii}ddddccccccc{d}{d}ddc{i}{i}ii{c}{{i}dddddd}iiii{c}{c}ccccccccc{{d}iiiiii}ddddcccccc{{i}dddddd}iiii{c}cccccc{{d}iiiiii}dddd{c}{d}{d}ddc{i}{i}ii{c}ccc{{i}dddddd}iiii{c}{c}cc{{d}iiiiii}ddddcc{{i}dddddd}iiiiccc{{d}iiiiii}ddddccccc{{i}dddddd}iiii{c}ccc{{d}iiiiii}dddd{c}ccc{d}{d}ddc{i}{i}ii{c}cccc{{i}dddddd}iiii{c}{c}{{d}iiiiii}ddddcccc{{i}dddddd}iiiic{{d}iiiiii}ddddccccc{{i}dddddd}iiii{c}ccc{{d}iiiiii}dddd{c}cccc{d}{d}ddc{i}{i}ii{c}cccccc{{i}dddddd}iiii{c}cccccc{{d}iiiiii}ddddcc{{i}dddddd}iiiicc{{d}iiiiii}ddddccc{{i}dddddd}iiiic{{d}iiiiii}ddddccc{{i}dddddd}iiii{c}cc{{d}iiiiii}dddd{c}cccccc{d}{d}ddc{i}{i}ii{c}cc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}ddddccc{{i}dddddd}iiiicc{{d}iiiiii}ddddcc{{i}dddddd}iiiic{{d}iiiiii}ddddc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}cc{d}{d}ddc{i}{i}ii{c}{{i}dddddd}iiii{c}{c}c{{d}iiiiii}ddddcccccc{{i}dddddd}iiii{c}{c}cccc{{d}iiiiii}dddd{c}{d}{d}ddc{i}{i}iiccccccc{{i}dddddd}iiii{c}{c}ccccc{{d}iiiiii}ddddccccccc{{i}dddddd}iiii{c}{c}ccccc{{d}iiiiii}ddddccccccc{d}{d}ddc{i}{i}iicccc{{i}dddddd}iiii{c}{c}ccccccccc{{d}iiiiii}ddddcccccccc{{i}dddddd}iiii{c}{c}cccccc{{d}iiiiii}ddddcccc{d}{d}ddc{i}{i}iic{{i}dddddd}iiii{c}{c}{c}cccc{{d}iiiiii}ddddccccccc{{i}dddddd}iiii{c}{c}cccccccc{{d}iiiiii}ddddc{d}{d}ddc{i}{i}iicc{{i}dddddd}iiii{c}{c}{c}cccccc{{d}iiiiii}ddddcccc{{i}dddddd}iiii{c}{c}ccccccc{{d}iiiiii}ddddcc{d}{d}ddc{i}{i}iiccc{{i}dddddd}iiii{c}{c}{c}cc{{d}iiiiii}ddddc{{i}dddddd}iiiiccc{{d}iiiiii}ddddccc{{i}dddddd}iiii{c}{c}cccccc{{d}iiiiii}ddddccc{d}{d}ddc{i}{i}iicccc{{i}dddddd}iiii{c}{c}{c}c{{d}iiiiii}ddddccc{{i}dddddd}iiiic{{d}iiiiii}ddddcc{{i}dddddd}iiii{c}{c}cccccc{{d}iiiiii}ddddcccc{d}{d}ddc{i}{i}iiccccc{{i}dddddd}iiii{c}{c}ccccccc{{d}iiiiii}ddddcccccc{{i}dddddd}iiii{c}{c}cccccccc{{d}iiiiii}ddddccccc{d}{d}ddc{i}{i}iiccccccc{{i}dddddd}iiii{c}cccccccc{{d}iiiiii}ddddc{{i}dddddd}iiiicccccc{{d}iiiiii}ddddccc{{i}dddddd}iiiic{{d}iiiiii}ddddcc{{i}dddddd}iiiiccccccc{{d}iiiiii}ddddc{{i}dddddd}iiii{c}cccccccc{{d}iiiiii}ddddccccccc{d}{d}ddc{i}{i}iiccccccc{{i}dddddd}iiii{c}ccccc{{d}iiiiii}ddddcccc{{i}dddddd}iiiicccccc{{d}iiiiii}ddddcccc{{i}dddddd}iiiiccccccccc{{d}iiiiii}ddddcccc{{i}dddddd}iiii{c}ccccc{{d}iiiiii}ddddccccccc{d}{d}ddc{i}{i}iicccccccc{{i}dddddd}iiii{c}cc{{d}iiiiii}ddddcccccc{{i}dddddd}iiiiccccccc{{d}iiiiii}ddddccccc{{i}dddddd}iiiiccccccc{{d}iiiiii}ddddcccccc{{i}dddddd}iiii{c}cc{{d}iiiiii}ddddcccccccc{d}{d}ddc{i}{i}iiccccccccc{{i}dddddd}iiiicccccccc{{d}iiiiii}ddddccccccccc{{i}dddddd}iiiiccccccccc{{d}iiiiii}ddddccccc{{i}dddddd}iiiiccccc{{d}iiiiii}ddddccccccccc{{i}dddddd}iiiicccccccc{{d}iiiiii}ddddccccccccc{d}{d}ddc{i}{i}iiccccccccc{{i}dddddd}iiiiccccc{{d}iiiiii}dddd{c}cc{{i}dddddd}iiii{c}c{{d}iiiiii}ddddcc{{i}dddddd}iiiicccccc{{d}iiiiii}dddd{c}cc{{i}dddddd}iiiiccccc{{d}iiiiii}ddddccccccccc{d}{d}ddc{i}{i}ii{c}{{i}dddddd}iiiicc{{d}iiiiii}dddd{c}cccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}cccc{{i}dddddd}iiiicc{{d}iiiiii}dddd{c}{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}{{d}iiiiii}ddddc{{i}dddddd}iiiicccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}{{d}iiiiii}ddddc{{i}dddddd}iiiicccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc{d}{d}ddc{i}{i}ii{c}{c}cccccc{{i}dddddd}iiii{c}ccccccccc{{d}iiiiii}dddd{c}{c}cccccc ``` Thought all the Ls would make this shorter - nope! [Answer] # [C (gcc)](https://gcc.gnu.org/), 726 bytes ``` z;int x[]={25,211,25,211,25,211,25,211,25,211,9,67,13,83,13,195,8,71,10,83,10,199,8,74,7,73,2,72,7,202,7,77,5,73,6,68,5,205,6,81,2,69,1,65,2,66,4,68,2,209,5,87,3,67,2,66,4,214,4,87,6,70,2,216,3,87,4,73,2,217,2,88,5,68,5,219,91,8,226,93,10,222,3,93,9,217,6,93,7,213,9,93,6,208,12,86,2,67,5,205,13,84,4,65,5,205,15,80,2,66,3,65,3,204,11,83,3,66,2,65,1,211,9,85,6,216,6,89,7,217,3,93,8,218,98,7,220,1,100,4,219,2,96,1,67,3,218,3,95,3,65,2,218,4,91,6,220,6,82,1,70,3,65,2,71,1,210,6,79,4,70,4,73,4,207,7,76,6,71,5,71,6,204,8,72,9,73,5,69,9,200,8,69,12,75,2,70,12,197,9,66,14,83,14,194,25,74,1,200,25,74,1,200,25,211,25,211,25,83,0},*y=x;f(){while(*y){for(z=*y&0x3f;z;--z)printf("%c",(*y&0x40)?'L':' ');if(*y++&0x80)printf("\n");}} ``` [Try it online!](https://tio.run/##fVLtahtBDPyfpwiG1neODCvd3u6qh@kL9A3S/igm1xoSN4RA/YGf3Z3ZOwLNj4BZ60azmpG02/Wv7fZ6PQ27/evt4f7H5my9mKp89OeSsmgnpeOp3kuRrKKhIgGIE4mSJXdikvETCzxzlp5gklQQWegRFlSW5KKSekZJItOGtINUsnRUnDOmESfAJDmQpAl5fMdJzZTUwvKThrq4wpBZEq8GzQxXEHtlVxiXlIDTnIUiiiKJonk2yo4pDZMzAG9hstURhXqIggFhDB1RI6rzzApbpVk07FUuTybgTIt4IWaYHhyG2ifciSeOhUySwO8nLavfkZ2leg1VDVSMZM5zIyAxk53DCdOEUDlkroJOQOp5pGq9cFVOUs99QB9OSl0N6tWigaF65iOAtVhXjqY98nVg51ovvYv/f0O4Ei6yOm4Ow9i057@/d48PzerYnsc/L81pszp@DoduHE7Den1qn1/wNMdm8Wm7kKamYmi/Lr8tvyxvl@2wGwHe3QEu4Y37fb9oh8vl@vRzt4fADVSGm8v1Hw "C (gcc) – Try It Online") The compression is a run time encoding. Every byte consists of a number(the bottom 6 bits), a flag if the character is a 'L' or a ' ' (the 6th bit) and a flag for a newline (the 7th bit) [Answer] # [C (gcc)](https://gcc.gnu.org/), 473 bytes ``` *y=L"øûøûøûøûøûøûúøû„;úøãô;ûøø{„ûûx šûûÄûûcüûûäûû øøûûôûûƒûøûûüûû úûû úûû ôûûû;úûû;ûûû;ôûûûøûû„ûûû üûûøûû{äûäûûãäûÄûûGôûûûˆü{ôû{Hûûøû{äûû„ûûû„ûûûôûûûúûûúûûûøûû;øûûû;øûûüûûûsøûû ôûûûCúûûäûûûÄûûû„ûûùÌÛûû„û;øôúûû øÅü{úøÄ;:ø›:øû øëøëøûøûøû";main(i,j,z){for(;*y;puts(""))for(i=9;i--;)for(z=4^*y++,j=8;j--;z/=2)putchar(z&1?76:32);} ``` [Try it online!](https://tio.run/##jVK7TsNAECx8kZHyAxEHjQsUJ7YQAfHIyaKggIJvQIosJTjiJQKC5ERFkCj4AlKGLm0K40vl/S/M7e05aePCs7Pe3Zm9cxz24rgoGsPo0mOMQQqKM/OsH9ZsWNO5jOJ8LJA4mkw5zJEoDqmzCalk@RgUqNft/BuRgaE8hgViBX4QqrozxcCFOUL@rt8m4VCdU4WMCi2YMlCCuGAltfmK7SZxbDBjaA1QEmX1NqQOU0SXWW/nOKSCK6OTT1hIjHVOXpiZNERSL2elRIls5SGjDTLiDmkLgmXAyRqoAfHlbmdlP5lUYAVcq/QLXzAxipjAaXOOLWgcD/SDG@uQ6cNwOOAdtbX1fMI1sg17jVv2cmere56t9SN44raT3NWToB@MfNm9f6yLxlA8PD8N6p7n@5hIohORhKEwZBQdXDWGzWbQj45FX2dHu1HL1/XxdUd/3dk7PTps77d88VYUf3H3ptMbFOHLPw "C (gcc) – Try It Online") binary encoding just as a reference, -> `0`, `L` -> `1`. xor'd with 4 so there are no `\0` bytes. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~310~~ 300 bytes ``` y,c,l;main(z){for(;z="ICbCbCbCbCR3=C=3A7:C:7@:79287:?=59645==A251122442A;G33224F9G662H7G492I5H545K2K8o:N3M9I9M7E?M6@EF235=ID415=L@22313<JC32211CDE6H?I7I9M8J3R7L1T4K3P133J5O312J7K6L:B1631271B<?46494?=<67576<?8995598@5<;26<5A2>C>2R:18b:18bCbCbC"[y++];l=!l)for(;z-->48;++c%69||puts(""))printf(L" L"+l);} ``` [Try it online!](https://tio.run/##LY9Za8JAFIX/ShsoJMQ8zJ25s2ayGJdstkX6VvqgAUVIVdRStPavN00XDge@h3MeviZYN03XnQfNoDWvi83WvXgfq93BNRfrFNnyP3NqM0tToTMtEi0USKFji4oztDYFJASAMUjNlNKeJmrKOeRiyhQUmCPDCiq50/d0pgo1E@N4xpPxBCjaYsQI2joBoISGZdbfCclGY57Hhei3sqRzUZMnVtFHQmmJD5RAKSpe6yHhPQsyDGPGmWKxDblAwcNYKoWoZIKhAR5iClEWwVwTufzpr5HzfPb9F9Pa29b78w2CiEnj@80dV9fr/u10dB3H8/aHzfa0cmvnpnb81jOfXffVrNrF@tgF798 "C (gcc) – Try It Online") a simple RLE. newlines inserted every 69 characters. left and right columns removed to combine some `L` runs. add `I` to the end of the data string for nice padding thanks [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for -10 bytes [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~313~~ 307 bytes ``` 19¶19¶19¶19¶19¶3je19¶7jb19¶10h9c8¶13f9g4¶17c5b1c2e4¶23d3c2e2¶23g6c3¶23e9c3¶24f4f4¶27i9¶29jb5¶29j3¶29h2¶29g¶22c3f¶20e1f1¶16c2d1d2¶19d2c1b5¶21g8¶25h6¶29i4¶34h3¶36e3¶32b3d3¶31d1c4¶27g7¶18b6d1c7¶15e6e9¶12g7f7¶8j9f5¶5jd11c6¶2jf19¶10b8¶10b8¶19¶19¶19 \d+ $*L T`l`d \d $* %+`^.{1,43}$ $& +`(.){34}.(?<-1>.)* $&$1 ``` [Try it online!](https://tio.run/##XZBNTsMwEIX3PkUXoWobiDrjxIklBBdgyRKh4N/EQl1U7KpeiwNwsfAmSF0gy/PNszVvxj7Hr/n0sSyK7M/3/61LFPTFrSfHyfoB1MnmFux958hzRM46aGQsWTZeC6Nd2SYssJ/hwba4boVc2UkKbEZgrxNwjJQI1sZzoMAyRmBPaw1lNOduMlIzw1K3E1y0iRLZYQSQAvm1Xe5RPTgDLVkXTZRHcO4T9FBsgmlXApEXx5L@3uiGW7z9hHoLtaoOL@p1/BwDFMRG3dXje3Oh@1ZfK7Wptqoed83@ottrs3t@fKCnZn9Q1baiZfkF "Retina 0.8.2 – Try It Online") Edit: Saved 4 bytes by encoding the left two thirds instead of the right two thirds. Explanation: Uses run-length encoding. The integers encode runs of up to 34 Ls while the letters `b-j` encode runs of 1-9 spaces with `jb-jf` encoding runs of 10-14 spaces as this saves a byte in the decoder. The first stage simply inserts the encoded data. ``` \d+ $*L ``` Run-length decode the integers to `L`s. ``` T`l`d ``` Transpose the lower case letters to digits in preparation for run-length decoding. ``` \d $* ``` Run-length decode the digits to spaces (each digit decoded separately). ``` %+`^.{1,43}$ $& ``` Pad all the lines to 44 characters. ``` +`(.){34}.(?<-1>.)* $&$1 ``` Note down the first 34 characters of each line, then skip a character, then start forgetting the noted characters. Append the first remaining character. Repeat until all lines are 69 characters long. This mirrors the left-hand third of the output to the right. ]
[Question] [ ## Introduction > > Adam (A) and Bubbler (B) are playing coin toss, where the one who wins 5 times first would win the prize of $32. If the game is aborted when the scores are `A:B = 4:3`, how should they distribute the prize? Assume the coin toss is fair, so the winning chance of either player is 1/2 for each game. > > > The answer is: > > Adam should take $24 and Bubbler should take $8. Possible cases are as follows: > > > > ``` > A wins (score 5:3, chance 1/2): A wins the prize > B wins (score 4:4) then A wins (score 5:4, chance 1/4): A wins the prize > B wins (score 4:4) then B wins (score 4:5, chance 1/4): B wins the prize > > ``` > > Therefore, the chance of A winning is `3/4` and that of B is `1/4`. > > > ## Challenge In order to do the fair splitting of prizes, we should compute the chance of winning the prize for each player. Given the following information, * `X`, how many times a player should win coin toss to win the prize * `Wa`, how many times player A has already won * `Wb`, how many times player B has already won compute the chance of **player A** winning the prize. ## Input and output You can assume the three input numbers `X`, `Wa`, `Wb` satisfy the following: * All numbers are non-negative integers. * `X > max(Wa, Wb)`, i.e. the game hasn't finished already. You can choose to output a fraction or a floating-point number. ## Scoring and winning criterion Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. ## Test cases ``` X Wa Wb => Expected output -------------------------- 5 4 3 => 3/4 = 0.75 5 3 4 => 1/4 = 0.25 1 0 0 => 1/2 = 0.5 4 3 1 => 7/8 = 0.875 4 2 1 => 11/16 = 0.6875 6 4 2 => 13/16 = 0.8125 ``` [Answer] # [R](https://www.r-project.org/), ~~36~~ 32 bytes ``` function(X,A,B)pbeta(.5,X-A,X-B) ``` [Try it online!](https://tio.run/##DYq7CoAwEAR/xTIHq8Q8rLRIviKtigFBYxAt/PrzWKaZ2ZtzM7ac37I@@1VUQkCkumzPrDqP1AYhEp9zrcenMtK0Kg@PHk42EIIIBwstGDhCFGGlafn0MET8Aw "R – Try It Online") The closed formula from [this answer](https://codegolf.stackexchange.com/a/197365/67312) suggested a natural probability distribution to use -- this is a Negative Binomial with \$X - W\_b - 1\$ failures and \$X - W\_a\$ successes, i.e., the probability that there are \$X - W\_a\$ "successes" before there are \$X - W\_b\$ "failures". Further identities reduce the CDF of the negative binomial to the CDF of a beta distribution or in terms of the (regularized) incomplete beta function. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Binomial[g=#-#2+t,k]~Sum~{k,0,t=#-#3-1}/2^g& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ykzLz83MzEnOt1WWVfZSLtEJzu2Lrg0t646W8dApwQkaKxrWKtvFJeu9j@gKDOvJFqjWlm5VkHXTiEtWlk5VlPNwcGhutpUR8FER8G4VkcBxDQG8kBMQx0FAyACMU3AooZQphGUaQbWZlRbG/sfAA "Wolfram Language (Mathematica) – Try It Online") Not super short, but uses an algorithm that might lead to shorter code in other languages: the code calculates the sum of binomial coefficients [![formula](https://i.stack.imgur.com/b3AiL.png)](https://i.stack.imgur.com/b3AiL.png) which is the closed form for the result of the path-counting algorithms in other solutions. [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 56 bytes ``` f=lambda n,a,b:a<n>b and(f(n,a+1,b)+f(n,a,b+1))/2.or a>b ``` [Try it online!](https://tio.run/##NY7RCoMwDEWf16/IWxXDNK1VGdMfER9ahmyw1TEGY1/v0jih9KbnhKTP7/u6RLOuc3/3j3DxENFjOPlzHAL4eMnmjElBGPJCSgwF5XlpjssL/BDWmTPix@MnwC3CODqs0U7IabHmJKyw4mSKJGkkG@4z03RSh@frFt/7ENT9oDGtkmeutNbKAdQAFvqB75LLHqpj6xK3SSVOOzdOEUCVzsbNxp2SGUCC27LbcNeKMH9BVFIjokmmkc1GjN1NR7yD/7X@AA "Python 2 – Try It Online") Returns a float. Uses a recursive approach. Ungolfed: ``` def f(n,wa,wb): if wa<n and wb<n: return (f(n, wa+1, wb) + f(n, wa, wb+1))/2.0 elif wa==n: return 1 else: return 0 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` x"TF1GEZ^!Ys@+1G<~s]P>Ym ``` [Try it online!](https://tio.run/##y00syfn/v0IpxM3Q3TUqTjGy2EHb0N2mrjg2wC4y9/9/M65oEwWjWAA) Or [verify all test cases](https://tio.run/##y00syfmf8L9CKcTN0N01Kk4xsthB29Ddpq44NsAuMve/S1RFyH9TrmgTBeNYLiBtrGASy2XIFW2gYBDLZQLiG4JpIxBtBlJnFAsA). Input is `X`, then `[Wa Wb]`. Output is a floating-point number. ### How it works This enumerates all possible paths of length `2*X` that emanate from the initial conditions defined by `Wa` and `Wb`. This length is enough to ensure that someone wins (actually length `2*X-Wa-Wb-1` would suffice). For each path, the code determines who wins as follows. It keeps a cumultive sum of score for each player, computes how long each player has had score `X` or more along the path, and the winner is the player who has maintained that condition for longer. This is equivalent to, but golfier than, asking who reached `X` earlier in that path. Note that there can be no ties. The result is the proportion of paths in which player A wins. ``` x % Implicit input: X. Delete it " % Implicit input: [Wa Wb]. For each TF % Push [0 1] 1G % Push X E % Multiply by 2 Z^ % Cartesian power of [0 1] with exponent 2*X. Gives a matrix with each % Cartesian tuple contained in a row. Rows are in lexicographical order % Each column is a step in the path, containing 1 if the user wins or 0 % otherwise ! % Transpose. Each tuple is now a column Ys % Cumulative sum of each column. This is the accumulated gain along each % path. Note that the matrix has more than one row; otherwise the % cumulative sum would work along the single row @ % Push Wa (first iteration) or Wb (second iteration) + % Add. This gives the total accumulated score along each path, including % the initial score 1G % Push X <~ % Not less than? s % Sum of each column. This indicates for how long the score X has been % reached, or exceeded, in each path ] % End P % Flip. This reverses the results for player B, to reflect the fact that % the paths of the two users are complementary: user B increases their % score when user A doesn't. Reversing the vector is equivalent to % replacing each path by its complement, thanks to the lexicographical % order of the Cartesian tuples > % Greater than? This indicates for which paths player A wins Ym % Mean. Implicit display ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` .5ii-Z}3$Yg ``` [Try it online!](https://tio.run/##y00syfn/X880M1M3qtZYJTL9/39TrmgTBeNYAA "MATL – Try It Online") This is a port of my [R answer](https://codegolf.stackexchange.com/a/197372/67312). Thanks to Luis Mendo for helping golf it down. ``` .5 # push .5 ii # push both inputs, X, and [Wa, Wb] - # subtract, so stack is [.5, [X - Wa, X - Wb]] Z} # split array onto stack # so stack is [.5, X - Wa, X - Wb] 3$Yg # (regularized) incomplete beta function with 3 arguments # implicitly output the probability ``` Also a nice short Octave solution: # [Octave](https://www.gnu.org/software/octave/), 27 bytes ``` @(X,A,B)betainc(.5,X-A,X-B) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjQsdRx0kzKbUkMTMvWUPPVCdC1xGInTT/p2mY6pjoGGv@BwA "Octave – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17 16~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to Kevin Cruijssen ``` _µS’2*ḶB§‘>ḢÆm ``` A dyadic Link accepting the end-goal, `X`, on the left and the current state `[Wa,Wb]` on the right which yields a float of A's chances. **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//X8K1U@KAmTIq4bi2QsKn4oCYPuG4osOGbf///zb/NCwy "Jelly – Try It Online")** ### How? Forms all binary strings of \$X-Wa+X-Wb-1\$ bits, treating 1s as a win for A and 0s as a win for B. Identifies those with at least \$X-Wa\$ 1s and takes the mean (i.e. winCount / total). ``` _µS’2*ḶB§‘>ḢÆm - Link: X, [Wa, Wb] _ - subtract (vectorises) -> V=[X-Wa, X-Wb] µ - start a new monadic chain, f(V) S - sum X-Wa+X-Wb ’ - decrement X-Wa+X-Wb-1 2* - two raised to that power 2^(X-Wa+X-Wb-1) Ḷ - lowered range [0,1,2,3,4,...,2^(X-Wa+X-Wb-1)-1] B - to binary (vectorises) [[0],[1],[1,0],[1,1],[1,0,0],...,[1,1,...,1]] § - sums [0,1,1,2,1,...,X-Wa+X-Wb-1] ‘ - increment (vectorises) [1,2,2,3,2,...,X-Wa+X-Wb] Ḣ - head (V) X-Wa > - greater than? (vectorises) A=[0>=X-Wa,1>=X-Wa, ...] Æm - mean A's win probability ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` _Ä’Żc@SH⁹¡ʋ/ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//X8OE4oCZxbtjQFNI4oG5wqHKiy////80/zEsMg "Jelly – Try It Online") A dyadic link taking the number to win as left argument and the coin tosses won so far by players b and a respectively as the right argument. Based on [the formula described by @GregMartin](https://codegolf.stackexchange.com/a/197365/42248) so be sure to upvote his answer too! ## Explanation ``` _ | Subtract Ä | Cumulative sum ’ | Decrease by 1 ʋ/ | Reduce using the following as a dyad (left argument represents X - Wb - 1; right argument represents 2X - Wa - Wb - 1) Ż | - Range from 0..left argument c@ | - Number of combinations for each using right argument as n S | - Sum H⁹¡ | - Half the number of times indicated by the right argument ``` # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` MḢ’¹2Ṭ+Çɗ€ÆmƊ}Ị? ``` [Try it online!](https://tio.run/##AVQAq/9qZWxsef//TeG4ouKAmcK5MuG5rCvDh8mX4oKsw4Ztxop94buKP///4bik4oCZw5gu4bmX4bijU31TPeG4osKlyovGh8KnPOKBuMOGbUP/Miw0LDY "Jelly – Try It Online") An alternative Jelly answer that uses a recursive approach. A full program that takes as its argument a list of `Wb, Wa, n` and returns the answer as a float. ## Explanation ``` M | Indices of maximum Ḣ | Head ’ | Subtract 1 Ị? | If absolute of this less than or equal to one: ¹ | Then: Return this value Ɗ} | Else following as a monad applied to the original argument to this link: 2 | - Literal 2 ɗ€ | - Apply the following to the implicit range 1..2 with the original argument as the right argument Ṭ | - Convert to logical list with 1 at the relevant index + | - Add to the original argument (effectively increments Wa for 1 and Wb for 2) Ç | - Call this link with the updated argument Æm | - Arithmetic mean ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes ``` Beta[.5,a=#-#2,b=#-#3]/a~Beta~b& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ym1JDFaz1Qn0VZZV9lIJwlEGcfqJ9aBJOqS1P4HFGXmlURrVCsr1yro2imkRSsrx2qqOTg4VFeb6iiY6CgY1@oogJjGQB6IaaijYABEIKYJWNQQyjSCMs3A2oxqa2P/AwA "Wolfram Language (Mathematica) – Try It Online") Yet [another port](https://codegolf.stackexchange.com/a/197413/67312) of the negative binomial CDF approach suggested by [this answer](https://codegolf.stackexchange.com/a/197365/67312). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` Nθ≔E⁻θN⁰ηFE⁻θN¹FLη«≔⊘⁺ι§ηκι§≔ηκι»I⊟η ``` [Try it online!](https://tio.run/##fY2xDoIwGIRneYp//P@kJmqMCxNxkUQMr1Ch0sZaoC3ExPjstSgDk8MNl/vurpLcVi3XIeSmG/xleFyFxZ7SJHNONQYL3mGhzOCwZ7BkiBhsomRkb62F/@SWCL7UWZjGS5TRv5LVfHLiehQ1ljqWFYPM56YWT5QM7jS1VfyY2WX2C95JaZXxeOTOY9l20zalIRxgD7uwHvUH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the desired number of coin tosses. ``` E⁻θN⁰η ``` Calculate the number of remaining tosses player A needs, and create an array of that length of zeros. The (1-indexed) `n`th entry represents that the probability of `A` winning given that he still has `n` tosses remaining and `B` initially has no tosses remaining. ``` FE⁻θN¹ ``` Loop over the number of remaining tosses player B needs. Start with the probability of `A` winning given that he still has `0` tosses remaining and `B` has `m` tosses remaining as `1`. ``` FLη« ``` Loop over the probabilities. ``` ≔⊘⁺ι§ηκι ``` Average the current probability (representing the case where `A` wins this toss) with the probability from the array (representing the case where `B` wins this toss). ``` §≔ηκι ``` Save this new probability in the array. ``` »I⊟η ``` Output the last probability calculated, which is for `n=X-Wa,m=X-Wb`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 44 bytes ``` a=>g=(b,c)=>a==b||a>c&&(g(b+1,c)+g(b,c+1))/2 ``` [Try it online!](https://tio.run/##NY7daoQwEEbvfYq52p2gTYzWHyjxrk/RLWxM1VqyKkaWhW6f3SZRIYThnHzf5EfepVFzPy0vw/jVrK1Ypag6gXWkiKikEPXzKSt1OmGHdcgtDTsnQ04IS9alMYuSpgEB1yADeAVIQVT2ZnYUENMiczx1ynF@8CQLOEDszsaTjWeB7wDuccHKDZeFF8kuOGc89yJ3JvebE2/Sw5Tc7rjSZe5vSKiZdL/g@TKcSXD8mrbj/C7VN2qX/A0A7nKGDxlBHYH6tC16z7GLCZkt0b1qMI4gJfQmJ3y4XPggbzaqxsGMuqF67HBviKBFSdCNxL75I@s/ "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` {m:g/\-//$_}o{[X+] .[1],|(^2 xx+^.sum)}o&[X-] ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtcqXT9GV19fJb42vzo6QjtWQS/aMFanRiPOSKGiQjtOr7g0V7M2Xy06Qjf2vzVXcWKlQhpIiY5RrA6QNohVSMsv4tIw1VEw0VEw1tQBM42BPBDTUEfBAIhATBOwqCGUaQRlmoG1GWn@BwA "Perl 6 – Try It Online") Takes arguments as `f((a, b), x)`. Counts `2x-a-b-1`-bit numbers with popcount less than `x-b`. ### Explanation ``` &[X-] # Compute a-x, b-x { }o # Feed into block ^2 # Range 0..1 xx # repeated +^.sum # ~(a-x+b-x) = 2x-a-b-1 times |( ) # flattened .[1] # b-x [X+] , # Cartesian product with addition, # computes popcount(i)-(x-b) for all i { }o # Feed into block m:g/\-/ # Regex match '-' chars in string representation, # counting negative values /$_ # Divide by number of values ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 77 bytes ``` double f(int x,int a,int b){return(a<x&b<x?f(x,a+1,b)+f(x,a,b+1):a>b?2:0)/2;} ``` [Try it online!](https://tio.run/##dY/RaoMwFIbv@xSHgiPBrFPb7cLW9Ql21YsNpBcnVUs6q5JEcYjP7tJohxQGyTk/3wn/@XPBBp8vyfdQ1TwXJzjlqBR8oCigWwAojdrQISnNOIWMiEJDy24VbeW0k6muZUFw1z7xXbvPSMvQ9RmnrpWMuz4N8Z3vg9CjL8G2H4zxtG7yb0qRwNUsJQctRXGOj4DyrKjNAGAWxUfDdKq0gmiiAB28MtgwWEPP5mht6Bz5DDxz5mhjX/kPKHhAb9Y@uKN@a1tWSiANSpsnHFPRv1CHH6XT66qs9aoyf9EZWX5FTsLgE8fGbVNVLnTkKKdYMmsRe8dJ@HcRGJGRf4eUjnn6xe32wy8 "Java (JDK) – Try It Online") ## Credits * Port of [Chas Brown's Python 2 answer](https://codegolf.stackexchange.com/a/197355/16236). * -1 byte, thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ## Iterative version, 89 bytes ``` (x,a,b)->{int r=0,i=1<<x*2>>a-~b,n=i;for(;i-->0;)r+=x.bitCount(i)<x-a?0:1;return 1.*r/n;} ``` [Try it online!](https://tio.run/##dZFBa8IwFMfvfoqHICQu7drqdjCmO@y0w9jBwwbSQ1qjxGkqSSod0n31LqZ1E2EQeC@/vPzf@ydbfuTBdvXZHqp8JwsodtwYeOVSwWkAIJUVes0LAYvDTlo4wVu@FYUFc96iF3e8ERpqApeU/6U5ptA4EWO5ddKdgr8IrEU14STHQXpyPUCziEgWz@f1OElTHnznRDFJ16VGVAZBGlGs71gd5tI@l5WySOJ5HfCnaBZTLWylFcThWN8r2rTUtezd9J2PpVzB3nlCC6ul2iwz4HpjsLfoTS4zx6ww1gDrKTizDwSmBCbQkGs0cfQaxQQit67R1FfFNyi5QY9ePrmghvrgTAM6cu3nmXVT4d@hFl/Gin1YVjY8OC92jYYfbLQi8M67kPvgn5mNzEgNiZdYRlmfxJckyfq6sPvNf8sw7iY7f2YzaNof "Java (JDK) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` -¤sO<oL<2вO›ÅA ``` Inputs in the format and order `[Wa, Wb], X`. Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/197356/52210). [Try it online](https://tio.run/##yy9OTMpM/f9f99CSYn@bfB8bowub/B817Drc6vj/f7SJjnEslykA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m5mKvpJCYl6KgZO/pYl@spPCobRKQ/V/30JJif5t8HxujC5v8HzXsOtzq@F/nf7SJjnEslylXtLGOCZg20DGI5TIE8Q1juUy4oo2gtImOUSyXGQA). A port of [*@GregMartin*'s formula](https://codegolf.stackexchange.com/a/197365/52210) would be 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage): ``` -¤sO<UFXNc}OXoz* ``` [Try it online](https://tio.run/##yy9OTMpM/f9f99CSYn@bULcIv@Ra/4j8Kq3//6NNdIxjuUwB) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m5mKvpJCYl6KgZO/pYl@spPCobRKQ/V/30JJif5tQtwi/5Fr/iPwqrf86/6NNdIxjuUy5oo11TMC0gY5BLJchiG8Yy2XCFW0EpU10jGK5zAA). **Explanation:** ``` - # Subtract each value of the first (implicit) input-pair from the second # (implicit) input: [X-Wa,X-Wb] ¤ # Push its last value (without popping the list itself): X-Wb s # Swap to get the list again O # Sum them together: 2X-Wa-Wb < # Decrease it by 1: 2X-Wa-Wb-1 o # Take 2 to the power this: 2^(2X-Wa-Wb-1) L # Pop and push a list in the range [1,2^(2X-Wa-Wb-1)] < # Decrease each value by 1 to make it [1,2^(2X-Wa-Wb-1)) 2в # Convert each to a binary-list O # Sum each inner list of bits › # Check for each if it's larger than the X-Wb: [X-Wb>1,X-Wb>2,...] ÅA # Take the arithmetic mean of that list # (which is output implicitly as result) -¤sO< # The same as above U # Pop and store this 2X-Wa-Wb-1 in variable `X` F # Loop `N` in the range [0,X-Wb): c # Take the binomial coefficient (a.k.a. number of combinations) of: X # The 2X-Wa-Wb-1 of variable `X` N # And the loop-index `N` }O # After the loop: sum all values on the stack X # Push 2X-Wa-Wb-1 from variable `X` again o # Take 2 to the power this: 2^(2X-Wa-Wb-1) z # Take the invert of this: 1/(2^(2X-Wa-Wb-1)) * # And multiply it with the sum # (after which this is output implicitly as result) ``` ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/17035/78039) The major scale (or Ionian scale) is one of the most commonly used musical scales, especially in Western music. It is one of the diatonic scales. Like many musical scales, it is made up of seven notes: the eighth duplicates the first at double its frequency so that it is called a higher octave of the same note. The seven musical notes are: > > **C, D, E, F, G, A, B**, C (repeated for example purposes) > > > A major scale is a diatonic scale. Take the previous succession of notes as a major scale *(Actually, It is the scale C Major)*. The sequence of intervals between the notes of a major scale is: > > whole, whole, half, whole, whole, whole, half > > > where "whole" stands for a whole tone (a red u-shaped curve in the figure), and "half" stands for a semitone (a red broken line in the figure). [![enter image description here](https://i.stack.imgur.com/aMk6a.png)](https://i.stack.imgur.com/aMk6a.png) In this case, from C to D exist a **whole** tone, from D to E exist a **whole** tone, from E to F exist **half** tone, etc... We have 2 components that affects the tone distance between notes. These are the Sharp symbol (♯) and the flat symbol (♭). The Sharp symbol (♯) adds half tone to the note. Example. From C to D we mentioned that exists a whole tone, if we use C♯ instead C then from C♯ to D exists half tone. The Flat symbol (♭) do the opposite of the Sharp symbol, it subtract half tone from the note. Example: From D to E we mentioned that exists a whole tone, if we use Db instead D then from Db to E exists a tone and a half. By default, from Note to Note exist a whole tone except for `E to F` and `B to C` in where just half tone exists. **Note** in some cases using enharmonic pitches can create an equivalent to a Major Scale. An example of this is `C#, D#, E#, F#, G#, A#, B#, C#` where `E#` and `B#` are enharmonic but the scale follows the sequence of a Major Scale. --- ## Challenge Given a scale, output a truthy value if it is a Major Scale or equivalent, otherwise output a falsey value. **Rules** * Standard I/O method allowed * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply * You don't need to take in consideration the 8th note. Assume the input will only consist of 7 notes * Assume double flat (♭♭), double sharp (♯♯) or natural sign (♮) don't exist --- ## Test cases ``` C, D, E, F, G, A, B => true C#, D#, E#, F#, G#, A#, B# => true Db, Eb, F, Gb, Ab, Bb, C => true D, E, Gb, G, A, Cb, C# => true Eb, E#, G, G#, Bb, B#, D => true ----------------------------------------------- C, D#, E, F, G, A, B => false Db, Eb, F, Gb, Ab, B, C => false G#, E, F, A, B, D#, C => false C#, C#, E#, F#, G#, A#, B# => false Eb, E#, Gb, G#, Bb, B#, D => false ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~76~~ ~~65~~ ~~63~~ 59 bytes *-4 bytes thanks to Phil H* ``` {221222==[~] (.skip Z-$_)X%12}o*>>.&{13*.ord+>3+?/\#/-?/b/} ``` [Try it online!](https://tio.run/##bY7PCoJAHITvPcXAVpSm4gpdyhVdbV8h@kO0lBAVip5C7NXtt9YhouvwzTdTnqvbvLs/MM4Rdg3nPuc8DLfPPSZufb2U2DjDw3Q98nlbWEK448YPLLeoTrYI7MjbMc@JPO213WJQHx/IJ0QjL6rBUiJFhhUUYiRiRgFDypAxrBgUQ8yQMJOnGpk2oEaskWjIPqUyJaYtKepJwqiuTJuwhHy9t9d@L/0Y30L1hggxvPw8kv8efXb091D3Ag "Perl 6 – Try It Online") ### Explanation ``` *>>.&{ ... } # Map notes to integers 13*.ord # 13 * ASCII code: A=845 B=858 C=871 D=884 E=897 F=910 G=923 +>3 # Right shift by 3: A=105 B=107 C=108 D=110 E=112 F=113 G=115 # Subtracting 105 would yield A=0 B=2 C=3 D=5 E=7 F=8 G=10 # but isn't necessary because we only need differences +?/\#/ # Add 1 for '#' -?/b/ # Subtract 1 for 'b' { }o # Compose with block (.skip Z-$_) # Pairwise difference X%12 # modulo 12 [~] # Join 221222== # Equals 221222 ``` [Answer] # [Node.js v10.9.0](https://nodejs.org), ~~78~~ ~~76~~ ~~71~~ 69 bytes ``` a=>!a.some(n=>(a-(a=~([x,y]=Buffer(n),x/.6)-~y%61)+48)%12-2+!i--,i=3) ``` [Try it online!](https://tio.run/##lZHNjoIwFIX3PgVCTNpIIerEzKYmtCoPYVwUbSdMGDoBNbrx1XF6G2T86cRh8YXN/XLO6ac4iHpT5d87UuqtbBRtBJ31RVTrL4lKOkOCIEHPaHUMT2vK9krJCpU4PMbRFJPzaTAd4eHbOx6MxmQ87OeEhDmd4Gajy1oXMir0B1Jo5XM/9Py5wcJgaZAaJAbMX2PstV8ce7tqL3sPjgAkwAVwCUyBCZAFVuVyzDO4zroQ8JsAGZC3YZyOaw173PXgVhB0dVwOm8C2SLsSNgGzRe9z9J6PGry06o9EiaL@7yI3g7gl6V2I5Hps4/FfUZwS@7781fd9LrkZNvt72VbSXAA "JavaScript (Node.js) – Try It Online") ### How? Each note \$n\$ is converted to a negative number in \$[-118,-71]\$ with: ``` [x, y] = Buffer(n) // split n into two ASCII codes x and y ~(x / .6) // base value, using the ASCII code of the 1st character - ~y % 61 // +36 if the 2nd character is a '#' (ASCII code 35) // +38 if the 2nd character is a 'b' (ASCII code 98) // +1 if the 2nd character is undefined ``` Which gives: ``` n | x | x / 0.6 | ~(x / 0.6) | -~y % 61 | sum ------+----+---------+------------+----------+------ "Ab" | 65 | 108.333 | -109 | 38 | -71 "A" | 65 | 108.333 | -109 | 1 | -108 "A#" | 65 | 108.333 | -109 | 36 | -73 "Bb" | 66 | 110.000 | -111 | 38 | -73 "B" | 66 | 110.000 | -111 | 1 | -110 "B#" | 66 | 110.000 | -111 | 36 | -75 "Cb" | 67 | 111.667 | -112 | 38 | -74 "C" | 67 | 111.667 | -112 | 1 | -111 "C#" | 67 | 111.667 | -112 | 36 | -76 "Db" | 68 | 113.333 | -114 | 38 | -76 "D" | 68 | 113.333 | -114 | 1 | -113 "D#" | 68 | 113.333 | -114 | 36 | -78 "Eb" | 69 | 115.000 | -116 | 38 | -78 "E" | 69 | 115.000 | -116 | 1 | -115 "E#" | 69 | 115.000 | -116 | 36 | -80 "Fb" | 70 | 116.667 | -117 | 38 | -79 "F" | 70 | 116.667 | -117 | 1 | -116 "F#" | 70 | 116.667 | -117 | 36 | -81 "Gb" | 71 | 118.333 | -119 | 38 | -81 "G" | 71 | 118.333 | -119 | 1 | -118 "G#" | 71 | 118.333 | -119 | 36 | -83 ``` We compute the pairwise differences modulo \$12\$ between these values. The lowest possible difference between 2 notes is \$-47\$, so it's enough to add \$4\times12=48\$ before applying the modulo to make sure that we get a positive result. Because we apply a modulo \$12\$, the offset produced by a `'#'` is actually \$36 \bmod 12 = 0\$ semitone, while the offset produced by a `'b'` is \$38 \bmod 12 = 2\$ semitones. We are reusing the input variable \$a\$ to store the previous value, so the first iteration just generates \$\text{NaN}\$. For a major scale, we should get \$[ \text{NaN}, 2, 2, 1, 2, 2, 2 ]\$. We use the counter \$i\$ to compare the 4th value with \$1\$ rather than \$2\$. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~150~~ ~~131~~ 125 bytes ``` l=>(l=l.map(x=>'C0D0EF0G0A0B'.search(x[0])+(x[1]=='#'|-(x[1]=='b')))).slice(1).map((n,i)=>(b=n-l[i])<0?2:b)+""=='2,2,1,2,2,2' ``` [Try it online!](https://tio.run/##dVDRbpswFH0uX3HVRLKtOojwMimtWwFJkPawTdpjFgmTmdSbBxH2qlaUb8@uYcvSVkU6GHHOPef4/pAP0u5afXCzuvmujg@yhUocjbilRpjwlzzQR3FLsmgZrdZRHiVRSkKrZLu7p4@baMuu8JhvhSAT8jz7910Shk9ojd4pOmeDDa25ZmhbinpmNnrLbqK7eFGyq8tLnIh5zOfcv2NyNMqBU9ZZ0QUXJOOw5LDisOaQc0g4pGQBrv2tuGcnSCNWiDUiRySIdHImWpYoKEcHPBJEisjOJUOEZ8eMzPPnHn7eh@Rjhp9PffZ5l79VXlWtpLHv1hhbnCT5aT4ZSO/3QuDvm71335PqVLZ823YQBf11EFRNS3@qJ9D1uG4GuG@/fKOtAwHIhfZgtKOEA2HXwcWuqW1jVGiaPS2mHQr6xbQjQMJWHZR0NP4As2HOqHrv7ln/zU072iqLdhX1voyBEGPeBoVbuIPii7QW6LT7/7dnBSygWEttPPHx6@dPoXWtrve6evJ@DBV9gZ364x8 "JavaScript (Node.js) – Try It Online") *-19 bytes thanks to Luis felipe* *-6 bytes thanks to Shaggy* ## Ungolfed: ``` function isMajor(l) { // Get tone index of each entry let array = l.map(function (x) { // Use this to get indices of each note, using 0s as spacers for sharp keys let tones = 'C0D0EF0G0A0B'; // Get the index of the letter component. EG D = 2, F = 5 let tone = tones.search(x[0]); // Add 1 semitone if note is sharp // Use bool to number coercion to make this shorter tone += x[1] == '#' | -(x[1]=='b'); }); // Calculate deltas let deltas = array.slice(1).map(function (n,i) { // If delta is negative, replace it with 2 // This accounts for octaves if (n - array[i] < 0) return 2; // Otherwise return the delta return n - array[i]; }); // Pseudo array-comparison return deltas+"" == '2,2,1,2,2,2'; } ``` [Answer] # [Dart](https://www.dartlang.org/), ~~198 197 196~~ 189 bytes ``` f(l){var i=0,j='',k,n=l.map((m){k=m.runes.first*2-130;k-=k>3?k>9?2:1:0;return m.length<2?k:m[1]=='#'?k+1:m[1]=='b'?k-1:k;}).toList();for(;++i<7;j+='${(n[i]-n[i-1])%12}');return'221222'==j;} ``` [Try it online!](https://tio.run/##hVHLboMwELz3KyzRyqa8gnOoCnEQkMClx94iDqBCS3ikMqQXxLdT25CkTVB72NGuPeudHb/FtB2GDJVy9xVTkJOFuicQqoVak1Kv4k@EKrkrSKXTY502epbTpn3Emrlc2IVGivXSKdbPDrZMa2HTtD3SGlR6mdbv7ccKO4VV7cyIEChBp1DMU5WwSjOtwu5lvT285E2LZDs7UGQrSr56svcKgfcdqnd5pDHQzEh@MHEP5WkExNjEGENC9nY/VHFeI7m7A8AwXukxZcknzesWQV4Bi7WdjzK0gz5U4YbFlkXAImThsvBgJF9TJc7lsOUQcAg5uBw86bZjk3BycnqaJy4Hj4M/w4cq4EqA4AIuBnA1APqi9mdmbMUNVzTxQ5F64tgT@ebUdTFjtMEwgrhsfngkylmTgNh8Uhf8FudBMLs6mMQFl43cUZZY5naX8GqEeyaPw/35TwETjiYE0sUFV5pc@Nu25D/f@uEb "Dart – Try It Online") Loose port of the old Perl 6 answer <https://codegolf.stackexchange.com/a/175522/64722> ``` f(l){ var i=0,j='',k, n=l.map((m){ k=m.runes.first*2-130; k-=k>3?k>9?2:1:0; return m.length<2?k:m[1]=='#'?k+1:m[1]=='b'?k-1:k; }).toList(); for(;++i<7;j+='${(n[i]-n[i-1])%12}'); return'221222'==j; } ``` * -1 byte by using ternary operators for #/b * -1 byte by using ifs instead of ternaries for the scale shifts * -7 bytes thanks to @Kevin Cruijssen --- **Old version :** # [Dart](https://www.dartlang.org/), 210 bytes ``` f(l){var i=0,k=0,n={'C':0,'D':2,'E':4,'F':5,'G':7,'A':9,'B':11,'b':-1,'#':1},j='',y=[0,0];for(;++i<7;j+='${(y[0]-y[1])%12}')for(k=0;k<2;k++)y[k]=n[l[i-k][0]]+(l[i-k].length>1?n[l[i-k][1]]:0);return'221222'==j;} ``` [Try it online!](https://tio.run/##hVFdT4MwFH33VzRBc2no5COaxXZogA3@gG@kDxA3ZSAaZCaE8Nsnt7BNHdEHDve2p73nnD4lVb3fb/SCtp9JRTLXYnn/lW4LAXCLwRK4w2AF/IZBCPyWQQR8zsADfsfAB27bDFLgs/6n9V3Hti4Aa9zYYpYUm7dKF4aRLeZia7hw2epNbMlZE9uSXtlOBxQZ/UiRLxyRGwZt4ly6ZVzE2SyXPVca@lBfF@vyuX65tx@Ou7aU3KKiWte7qgTHsR3HAdfdim7/mmSlTtsLQkzzsdqt@@K9yspaB@wIByqOSxs97t2iV3SKPtElekSHkv6mashFWCGECBGCh@Br5yeWKZLTw9VYeAg@QjDBB0ZQCVFcgmIIqiEQqD6YmLFSO6ho5Eeq9NWyr@rl4dQpjCEG0wyT4uNbRqqdDIko56O68Kc4H8ikdTKKC0@OvEGWMnPuJfo1wjuSh@HB9KOQEYcQQu2UgqeNKfwdW/pfbt3@Cw "Dart – Try It Online") Ungolfed: ``` f(l){ var i=0,k=0,n={'C':0,'D':2,'E':4,'F':5,'G':7,'A':9,'B':11,'b':-1,'#':1},j='',y=[0,0]; for(;++i<7;j+='${(y[0]-y[1])%12}') for(k=0;k<2;k++) y[k]=n[l[i-k][0]]+(l[i-k].length>1?n[l[i-k][1]]:0); return'221222'==j; } ``` A whole step is 2, a quarter is 1. Mod 12 in case you jump to a higher octave. Iterates through all notes and computes the difference between the ith note and the i-1th note. Concatenates the result and should expect 221222 (2 whole, 1 half, 3 wholes). * -2 bytes by not assigning 0 to k * -4 bytes by using j as a String and not a List * -6 bytes thanks to @Kevin Cruijssen by removing unnecessary clutter in loops [Answer] # [C (gcc)](https://gcc.gnu.org/), `-DA=a[i]` + 183 = 191 bytes ``` f(int*a){char s[9],b[9],h=0,i=0,j=0,d;for(;A;A==35?b[i-h++-1]++:A^98?(b[i-h]=A*13>>3):b[i-h++-1]--,i++);for(;j<7;d=(b[j]-b[j-1])%12,d=d<0?d+12:d,s[j++-1]=d+48);a=!strcmp(s,"221222");} ``` [Try it online!](https://tio.run/##VVBdb4IwFH2GX4E0Jq0tieCWKbWa8iEve9sjYwmlQyHTGcqyB@NfHys65vZwb3LuOefe0xbOtii6roTVoZ3k6FTs8sZS6SIjom87NiWVrlqXpOV7AymnnLHZ/VqklbPD2HEzjH3@spiv4WWUMT5xZ6vVDPk3ieOQCmN03VAvH6hkWl1njm6aRmPXI5LJ5XQtsev5kqi0vhiZxHdzRHM2Um1T7I9QEdvzXM/zbETPnU5t7fPqANHJNHowaV9Vq9KMaWw82mEUbxIe2OSKQARisAEJ4CAANrEu00jEYpMILgIR/gijOBEJD0UIBqc2/ll0swyORPM8iED4eyr8d8o0pmdqGv37@5j6T6l1jVplox7039NnPjaaL6E9frJ8ayyfDzrmICRWCT8LJT@OcBghhPTas3nuvoryLd@qzok4yzXzDQ "C (gcc) – Try It Online") Based on the Perl answer. Takes input as a wide string. Ungolfed: ``` int f(int *a){ char s[9], b[9]; int h, i, j; h = 0; for(i = 0; a[i] != NULL; i++){ if(a[i] == '#'){ b[i-h-1] += 1; h++; } else if(a[i] == 'b'){ b[i-1-h] -= 1; h++; } else{ b[i-h] = (a[i] * 13) >> 3; } } for(j = 1; j < 7; j++){ int d = (b[j] - b[j-1]) % 12; d = d < 0? d + 12: d; s[j-1] = d + '0'; } return strcmp(s, "221222") == 0; } ``` [Answer] # [Wolfram Language (Mathematica) + Music` package], 114 bytes I love music and found this interesting, but I was out playing real golf when this code golf opportunity came down the pike so my submission is a little tardy. I figured I'd try this a totally different way, utilizing some actual music knowledge. It turns out the music package of Mathematica knows the fundamental frequency of the named notes. First I convert the input string into sequence of named notes. Next, I take the ratios of each successive note and double any that are less than 2 (to account for octave shift). Then I compare these ratios to the ratios of the Ionian scale which has roughly a 6% frequency difference between half notes and 12% between full notes. More than half of the bytes spent here are to convert the input into named symbols. ``` .06{2,2,1,2,2,2}+1==Round[Ratios[Symbol[#~~"0"]&/@StringReplace[# ,{"b"->"flat","#"->"sharp"}]]/.x_/;x<1->2x,.01]& ``` [Try it online!](https://tio.run/##lZDPb4IwHMXv/hXm28TLKr8OuziMgMppy4LHptlahEkCYqQmLET/dUbbRCZxy3b5pIf3Xt/7FkzskoKJLGbtS5JsKwLPpyqL34HOUrc1rMfGwQ62saRzfrBdNypP@y2JOk9Zkc1nwcucoMsFLKATc7ERx2z/ESWHnMUJQWPcAIfpHNKcCcCA5LvaseMBzpSaRv1mzuonezp3amxYNp20r51fkHTRQAB4DEuJlcRaIpTwJPwuYPRNjJRacaW4VgwVPUUf3XqWXKl5n66enqKvGAwc1zZa2tcJtHzwg87WfcK@js72dWXpGA1Xoz/O/n3CnQXhINm7CvWfwb2zBv86681o/vPq9gs "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~175~~ ~~136~~ ~~134~~ ~~114~~ 112 bytes ``` def f(t):r=[ord(x[0])//.6+ord(x[1:]or'"')%13-8for x in t];return[(y-x)%12for x,y in zip(r,r[1:])]==[2,2,1,2,2,2] ``` [Try it online!](https://tio.run/##jY9Ba4MwHMXvforHwkjC0nZaGMXhQaP1C@wmHhaqVCgqaQq6L@/@qbus7LBLIO/9Xt7LOLvz0O@X5dS0aIWTsU2qwZ7EVL3Wcrfbvr2stzCuB8ufuHwO95tDO1hM6Hq4@t027mb7SsybiczobqnZm1/dKKyyPivrJKkiFalQ@TOqF4YPe2sCjzsPc40cBY4okSLjimuGnKFgODKUDClDxkjODQrjMYPUIDPQXqQkCT6qSfEcQZQtfZSgjB7jcQCMtuudoJ9ur@Olc0JKGQTU8Xm5Poxhv9Y81N5byxUhwNN63az/2PyzxfxjzPIN "Python 3 – Try It Online") --- An one-liner Python 3 implementation. Thanks to @Arnauld for idea of calculate tones using division and modulo. Thanks to @Jo King for -39 bytes. [Answer] # [Python] ~~269~~ 202 bytes Improvements from `Jo King`: ``` p=lambda z:"A BC D EF G".index(z[0])+"b #".index(z[1:]or' ')-1 def d(i,j):f=abs(p(i)-p(j));return min(f,12-f) q=input().replace(' ','').split(',') print([d(q[i],q[i+1])for i in range(6)]==[2,2,1,2,2,2]) ``` [Try it!](https://tio.run/##bY/BboMwEETv/ooVHPAqTlSo1AMVB3ASPgJxgGAaR8Q4hKhpfp6uQ5WqVQ6ztkbjN2v7Ne578zrt@kYlnudNNumqY91UcIu9FDIJa9hsIfdW2jTqym/FS4kLrwb/1wnjsh8CCHAZska10HAtDhi3SVWfueUal5YfEN8HNV4GA0dteCvCaNkiOyXa2MvIcTUo21U7xYkjggBXZ9vpkdMdmR20GXnR8FOhS0FjEZbY9gNo0AaGynwo/oZlkhSRiEQo3IxKnOg77HOvOwVhrK5qx90ncZIC1gI2ArYCcgGpgIxJn0zShrQl5aSUlPlsXZNdz2k6UlJGkmyGOG@mSOf6zGUdJp8pLps5OpM/FX@Kn9EdPH8k07vjXsr7mvL5mo/a@l/vNw) Ungolfed, with test driver: ``` tone = "A BC D EF G" # tones in "piano" layout adj = "b #" # accidentals def note_pos(note): if len(note) == 1: note += ' ' n,a = note return tone.index(n) + adj[a] def note_diff(i, j): x, y = note_pos(i), note_pos(j) diff = abs(x-y) return min(diff, 12-diff) def is_scale(str): seq = str.replace(' ','').split(',') div = [note_diff(seq[i], seq[i+1]) for i in (0,1,2,3,4,5)] return div == [2,2,1,2,2,2] case = [ ("C, D, E, F, G, A, B", True), ("C#, D#, E#, F#, G#, A#, B#", True), ("Db, Eb, F, Gb, Ab, Bb, C", True), ("D, E, Gb, G, A, Cb, C#", True), ("Eb, E#, G, G#, Bb, B#, D", True), ("C, D#, E, F, G, A, B", False), ("Db, Eb, F, Gb, Ab, B, C", False), ("G#, E, F, A, B, D#, C", False), ("C#, C#, E#, F#, G#, A#, B#", False), ("Eb, E#, Gb, G#, Bb, B#, D", False), ] for test, result in case: print(test + ' '*(30-len(test)), result, '\t', "valid" if is_scale(test) == result else "ERROR") ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 109 bytes ``` ->s{(0..11).any?{|t|s.map{|n|(w="Cef;DXg<E=Fhi>G j8A d9B:")[(w.index(""<<n.sum%107)/2-t)%12]}*''=='CfDX<=h'}} ``` [Try it online!](https://tio.run/##fY/baoNAGITvfYrBRdYtdRtz05ObouvhFQLiRZbEJoWIVEWD@ux2JYdCS3s78/3zz3w26jTlYnJWVW8vOHddxjfF6a0f6qHix03ZD8Vgt8KUu/w1XL97kYj3h1WCjycf2@fgxWSp3fJDsd11tml6XsGr5mi5i0f2sHRqZrnLbLyjVAgq83DtiT0dxym1WlsiRIQYCXwE7N7ArBGEBBFBTJAQ@AQBuVihQqRmXMFXCBTk1dApWpxjpFavvIZ1TjLHaDjQwSw77@mGEnnaZaNhlE1dgTqOQw3j0on8KvXj8@1xckY1OF/J7wnyjwmXSuq/TtMX "Ruby – Try It Online") ]
[Question] [ Your task is to create a program which, given an input string, will output the first Google autocomplete result for that search. The format of input/output is up to you. ## Rules 1. Your program must take 1 input, a string, and output the top Google autocomplete/auto-fill suggestions result. The format of input/output is up to you. Just be sure to mention what your I/O format is. 2. Obviously, accessing the Internet is allowed. 3. URL shorteners (like bit.ly, TinyURL, etc.) are strictly *disallowed*. You should fetch your autocomplete results from this URL: <http://suggestqueries.google.com/complete/search?client=your_browser&q=your_query> or <http://google.com/complete/search?client=your_browser&q=your_query>. You are allowed to assume any browser name (or string, for that matter) for `client`. In the [program I wrote](https://gist.github.com/ckjbgames/f7bfa353e639f4a449fc57ab0a7befd3), I assume Chrome. Any browser name or string should work. You are allowed to pass any options to the webpage as long as you are using some variant of <http://suggestqueries.google.com/complete/search>. 4. Please provide an explanation of how your program works. It is not mandatory, but I strongly advise it. 5. All standard loopholes are *strictly forbidden*. ## Test Cases These are constantly changing, so edit this post if these become out-of-date. ``` 'how to' => 'how to make slime' 'code golf' => 'code golf languages' 'you' => 'youtube' 'g' => 'google' (why would you google 'google'?) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code win and the best programmer prosper... [Answer] # Vim 8 + [unimpaired.vim](https://github.com/tpope/vim-unimpaired), 93 89 85 70 73 71 bytes * -4 bytes thanks to tsh * -2 bytes thanks to Ian Emnace * -2 bytes thanks to FatalMerlin * -1 byte thanks to tsh/ckjbgames ``` :s/ /+/g D:e http://google.us/complete/search?client=gma&q=" d3f";D]yy ``` As a bonus, the last bytes look like they're winking at you `;D` Since this contains non-printing characters, the explanation contains substitutions (and I've replaced the pre-querystring part of the url with `[url]`, for brevity): ``` :s/ /+/g<CR>D:e [url]?client=gma&q=<C-R>"<CR>d3f";D]yy :s/ /+/g<CR> " Replace spaces with + D " Delete and yank result :e " Type :e ('edit' command) and a space [url]?client=gma&q= " Type the url, except the query <C-R>" " Paste from the default register <CR> " Execute the command, which opens the response " in a new buffer d3f" " Delete through the first three quotation marks " This deletes everything before the suggestion ; " Repeat motion; this jumps to the next \" D " Delete everything from there, leaving only the suggestion ]yy " unimpaired.vim C string unescape to handle escaped ' ``` As far as running goes, it works fine if you save it to a file named `script` and run with `vim -s script input.txt` on macOS, at least. It doesn't work if you add `-u NONE`, but it works fine if my `.vimrc` is empty. I assume it is using something from the system `.vimrc` to make the URL stuff work. This means, however, that it doesn't work in V, so no TIO link. Some more test cases: ``` 'what' => 'whataburger' 'what ' => 'what time is it' (Seriously? People Google that?) ``` --- What I really need is a way to open a URL with spaces in it. Replacing them with `+` first is just too many bytes! [Answer] # [Zsh](https://www.zsh.org/) + coreutils + w3m, ~~88~~ ~~71~~ 68 bytes ``` echo `w3m "google.com/complete/search?client=gma&q=$*"|cut -d\" -f4` ``` Switching from Bash to Zsh saved 3 bytes. *Thanks to @FatalMerlin for the shorter URL, saving 17 bytes!* ### Sample run ``` $ zsh complete.sh how to how to make slime $ zsh complete.sh dont you don't you forget about me $ zsh complete.sh don\'t you don't you worry child ``` [Answer] # Python + [requests](http://docs.python-requests.org/en/master/) ~~121~~ ~~117~~ 103 bytes ``` from requests import* lambda s:get("http://google.com/complete/search?client=gma&q="+s).json()[1][0][0] ``` [Answer] # JavaScript, 109 Bytes ``` q=>fetch("//suggestqueries.google.com/complete/search?client=chrome&q="+q).then(r=>r.json()).then(r=>r[1][0]) ``` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), you gotta love it, but man is it verbose! This answer uses [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), a promise-based fetch API present in modern browsers. Promises work by establishing handlers for async actions at the beginning, like callbacks, but better. The `.then()` takes a function which will be called with the result of the async action. `.then(r=>r.json())` uses the [`.json()`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json) response method to convert the text array to a manipulable variable, the second `.then()` just pulls the first response. Usage: ``` S = q=>fetch("//suggestqueries.google.com/complete/search?client=chrome&q="+q).then(r=>r.json()).then(r=>r[1][0]) S("node.js").then(console.log); // Prints the result to the debug console ``` [Answer] # C#, 192 112 111 Bytes Saved 80 Bytes thanks to @TheLethalCoder. Thanks for reformatting my code, I didn't know it was allowed to just leave off the surrounding Class and Method Body :) Saved another Byte by replacing `gma` by `hp`, as it doesn't matter for the parsing and there is just some gibberish before the response body. I litterally brute-forced the API to find `gma` and `hp`. ``` s=>new System.Net.WebClient().DownloadString("http://google.com/complete/search?client=hp&q="+s).Split('"')[3]; ``` [Answer] # Groovy, 122 bytes ``` {Eval.me(new URL("http://suggestqueries.google.com/complete/search?client=chrome&q="+it).text.split(",\\{")[0]+"]")[1][0]} ``` Basically: 1. Get the text from the end-point. 2. Remove the part with the brackets at the end, this isn't valid syntax. 3. Parse the remaining bit as a groovy array. 4. Grab the second element of the result array. [![enter image description here](https://i.stack.imgur.com/3Wf35.png)](https://i.stack.imgur.com/3Wf35.png) [Answer] # PowerShell, 133 115 bytes ``` ([net.webclient]::new().downloadstring("http://google.com/complete/search?client=gma&q=$_")|convertfrom-json)[1][0] ``` **Sample run** **Windows CMD command line:** ``` powershell.exe -c "'code golf l'|%{([net.webclient]::new().downloadstring(""""http://google.com/complete/search?client=gma&q=$_"""")|convertfrom-json)[1][0]}" ``` **PowerShell console:** ``` 'code golf l'|%{([net.webclient]::new().downloadstring("http://google.com/complete/search?client=gma&q=$_")|convertfrom-json)[1][0]} ``` [Answer] ## R, 111 bytes Long time since I last came here but giving it a shot: ``` jsonlite::fromJSON(readLines(url(paste0("http://google.com/complete/search?client=gma&q=",scan(,"")))))[[2]][1] ``` Using the package `jsonlite` to convert the string fetched from `readLines()` into a list object. Subsequently extract the second element, e.g (gives a warning that we don't have to care about): ``` > jsonlite::fromJSON(readLines(url(paste0("http://google.com/complete/search?client=gma&q=",scan(,"")))))[[2]][1] 1: "how to" 2: Read 1 item [[1]] [1] "how to make slime" Warning message: In readLines(url(paste0("http://google.com/complete/search?client=gma&q=", : incomplete final line found on 'http://google.com/complete/search?client=gma&q=how to' ``` [Answer] ## C#, 127 bytes ``` s=>new System.Net.WebClient().DownloadString("http://suggestqueries.google.com/complete/search?client=gma&q="+s).Split('"')[3]; ``` Complete and formatted version: ``` static void Main() { System.Func<string, string> f = s => new System.Net.WebClient() .DownloadString("http://suggestqueries.google.com/complete/search?client=gma&q="+s) .Split('"')[3]; System.Console.WriteLine(f("you")); System.Console.ReadLine(); } ``` ]
[Question] [ # Task There is a set of numbers `x`, such that `x^2` divides `7^x-1`. Your task is to find these numbers. Given an input of n, the code will print the nth number that follows this rule. # Examples 1-index ``` In Out 3 3 9 24 31 1140 ``` The relevant sequence can be found [here](http://oeis.org/A127107). ## Rules Shortest answer will be the winner\* Standard golfing rules apply [Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed Your answer can either be 0 or 1 indexed, please state in your answer [Answer] ## Haskell, 34 bytes ``` ([x|x<-[1..],mod(7^x-1)(x^2)<1]!!) ``` This uses 0-based indexing. Usage example: `([x|x<-[1..],mod(7^x-1)(x^2)<1]!!) 30` -> `1140`. It's a direct implementation of the definition. It builds a list of all numbers `x` and picks the `n`th. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` e.f!%t^7Z* ``` A program that takes input of an integer and prints a one-indexed value. [Try it online!](https://tio.run/nexus/pyth#@5@ql6aoWhJnHqX1/7@xIQA "Pyth – TIO Nexus") **How it works** ``` e.f!%t^7Z* Program. Input: Q e.f!%t^7Z*ZZQ Implicit variable fill Implicitly print e the last .f Q of the first Q positive integers Z t^7Z for which 7^Z - 1 % mod *ZZ Z^2 ! is zero ``` [Answer] # JavaScript (ES7), 40 bytes ``` f=(n,i=1)=>n?f(n-!((7**++i-1)%i**2),i):i ``` This loses precision fairly quickly due to the fact that JS loses precision by `7**19`. Here's a nearly arbitrary-precision ES6 version: ``` f=(n,i=0)=>n?f(n-!(~-(s=++i*i,g=j=>j?g(j-1)*7%s:1)(i)%s),i):i ``` This finishes within about a second for test case 31. A few longer approaches: ``` f=(n,i=0)=>n?f(n-!(~-(s=>g=j=>j?g(j-1)*7%s:1)(++i*i)(i)%s),i):i f=(n,i=0)=>n?f(n-!(s=++i*i,g=(j,n=1)=>j?g(j-1,n*7%s):~-n%s)(i),i):i f=(n,i=0)=>n?f(n-!(s=>g=(j,n=1)=>j?g(j-1,n*7%s):~-n%s)(++i*i)(i),i):i ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` µ7Nm<NnÖiN¼ ``` [Try it online!](https://tio.run/nexus/05ab1e#@39oq7lfro1f3uFpmX6H9vz/b2wIAA "05AB1E – TIO Nexus") For some reason I can't get `½` to work in `µ7Nm<NnÖ½N` or I'd be tied with Pyth. ``` µ # Loop until the counter equals n. 7Nm< # Calc 7^x+1. Nn # Calc x^2. Ö # Check divisibility. iN¼ # If divisible, push current x and increment counter. # Implicit loop end. # Implicitly return top of stack (x) ``` . [Answer] # [Python 2](https://docs.python.org/2/), ~~48~~ 46 bytes *Thanks to @Dennis for -2 bytes!* ``` f=lambda n,i=1:n and-~f(n-(~-7**i%i**2<1),i+1) ``` A one-indexed recursive function that takes input via argument and returns the result. [Try it online!](https://tio.run/nexus/python2#DcxBCsIwEEDRfU8xFAJJTIRpBbFYLyIuom1hoJmUTFy46dVrFn/3@BS3lAvIT5raWeaS5883CyVeKVLRiJfOHMu4hvieArCjEQeGwJPfF81e7/5qLSmytrujcXTCylMGBmJ49g5uDnp8DQ1smbjoVgn4ByhplWZXF8aY4w8 "Python 2 – TIO Nexus") (Recursion limit increased to allow the final test case to run) **How it works** `n` is the desired index, and `i` is the counting variable. The expression `~-7**i%i**2<1` returns `True` (equivalent to `1`) if `i^2` divides `7^i - 1`, and `False` (equivalent to `0`) otherwise. Each time the function is called, the result of the expression is subtracted from `n`, decrementing `n` each time a hit is found; `i` is also incremented. The short-circuiting behaviour of `and` means that when `n` is `0`, `0` is returned; this is the base case. Once this is reached, recursion stops, and the current value of `i` is returned by the original function call. Rather than explicitly using `i`, this is done using the fact that for each function call, an increment has been performed using the `-~` in front of the call; incrementing `0` `i` times gives `i`, as required. [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ ~~53~~ 51 bytes -4 bytes thanks to ETHproductions -2 bytes thanks to TuukkaX ``` i=0 g=input() while g:i+=1;g-=~-7**i%i**2<1 print i ``` [Try it online!](https://tio.run/nexus/python2#@59pa8CVbpuZV1BaoqHJVZ6RmZOqkG6VqW1raJ2ua1una66llamaqaVlZGPIVVCUmVeikPn/vyUA "Python 2 – TIO Nexus") the sequence is 1-indexed [Answer] # Python 2, 57 bytes This takes a really, *really* long time for large values. It also uses plenty of memory, because it builds the entire list way farther than necessary. The result is zero-indexed. ``` lambda n:[x for x in range(1,2**n+1)if(7**x-1)%x**2<1][n] ``` [**Try it online**](https://tio.run/nexus/python2#@59mm5OYm5SSqJBnFV2hkJZfpFChkJmnUJSYl56qYahjpKWVp22omZmmYa6lVaFrqKlaoaVlZGMYG50X@7@gKDOvRCFNw1LzPwA) [Answer] ## Mathematica, 43 bytes I've currently got three different solutions at this byte count: ``` Nest[#+1//.x_/;!(x^2∣(7^x-1)):>x+1&,0,#]& Nest[#+1//.x_/;Mod[7^x-1,x^2]>0:>x+1&,0,#]& Nest[#+1//.x_:>x+Sign@Mod[7^x-1,x^2]&,0,#]& ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 42 bytes Pretty straightforward. 1-indexed, though this could easily be changed. ``` n->=k=1;while(n--,while((7^k++-1)%k^2,));k ``` or ``` n->=k=1;for(i=2,n,while((7^k++-1)%k^2,));k ``` [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` f=lambda n,k=2:n<2or-~f(n-(7**k%k**2==1),k+1) ``` Return *True* for input **1**, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/9067/12012). [Try it online!](https://tio.run/nexus/python3#RYpBCsIwFETX9hSfQiA/TaUJYqEY71JtKyHNT0niwo1Xr0VFB4Z5PMb6JcQM6ZGKrfs05jhe7zHZQLP1NnPdNA2uk5l7fxl6IOmM7uikQ6yfE6eat0I45oTQxiiUrlLbO0QgsASxp9vI1RG7YrdES5mXTA9Qn4EdBvjmb0pgwAkqUBKmD6CE97Y/0yLi@gI "Python 3 – TIO Nexus") [Answer] # R, 35 bytes This only works for `n<=8`. ``` z=1:20;which(!(7^z-1)%%z^2)[scan()] ``` However, here's a longer version which works for `n<=25`, for **50 bytes**: ``` z=1:1e6;which(gmp::as.bigz(7^z-1)%%z^2==0)[scan()] ``` [Answer] # PHP, ~~47~~ 49 bytes ``` while($n<$argv[1])$n+=(7**++$x-1)%$x**2<1;echo$x; ``` Only works for n<9 (`7**9` is larger than `PHP_INT_MAX` with 64bit) **62 bytes** using arbitrary length integers: (not tested; PHP on my machine doesn´t have bcmath) ``` for($x=$n=1;$n<$argv[1];)$n+=bcpowmod(7,++$x,$x**2)==1;echo$x; ``` Run with `php -nr '<code>' <n>`. **pseudo code** ``` implicit: $x = 0, $n = 0 while $n < first command line argument increment $x if equation is satisfied increment $n print $x ``` [Answer] ## Pyke, 10 bytes ``` ~1IX7i^tR% ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7E1IX7i%5EtR%25&input=9) ``` ~1 - infinite(1) IX7i^tR% - filter(^, not V) 7i^ - 7**i t - ^-1 R% - ^ % v X - i**2 - implicit: print nth value ``` [Answer] # [Clojure](https://clojure.org/), 83 bytes ``` (fn[n](nth(filter #(= 0(rem(-(reduce *(repeat % 7N))1)(* % %)))(iterate inc 1N))n)) ``` [Try it online!](https://tio.run/nexus/clojure#DYxBCoMwFET3OcVAEeYLBW0X7aZX8AIhC9EfGtBfG1Pw9jabx4PHzMlZI6IDGM1boJU3Y1qKZlz4QsesK6@V829StFU2HQsaPAaRXthWbUSEqU7Gokg2oa/NRJw4x/mz6xf@ANdxQ4S/4Yl7FySAW05WFgP3knHUl/P8Aw "Clojure – TIO Nexus") This builds an infinite list of Java BigIntegers starting at 1 and filters them by the definition. It uses zero-based indexing to select the *nth* value from the filtered list. [Answer] # Perl 5, 35 Bytes Well, this was missing, so here it is: `map{$_ if!((7**$_-1)%($_**2))}1..<>` [Answer] # Powershell, too many bytes Just to see if it was possible and it is. ``` [System.Linq.Enumerable]::Range(1,10000)|?{[System.Numerics.BigInteger]::Remainder([System.Numerics.BigInteger]::Pow(7,$_)-1,$_*$_) -eq 0} ``` [Answer] # [Perl 6](http://perl6.org/), ~~35~~ 34 bytes ``` {grep({(7**$_-1)%%$_²},^∞)[$_]} ``` 0-indexed. Shaved off one byte thanks to Brad Gilbert. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 39 bytes ``` :{~(7^q-1)%(q^2)=0|b=b+1]~b=a|_Xq\q=q+1 ``` I couldn't get it to run in QBasic 4.5, but it seems to run fine in QB64. For some inexplicable reason, QBasic refuses to cleanly divide 13,841,287,200 by 144, but instead gives a remainder of -128. It then returns 16 as the 7th term of this sequence instead of 12... ``` :{ get N from the command line, start an infinite DO-loop ~ IF (7^q-1) Part 1 of the formula (Note that 'q' is set to 1 as QBIC starts) % Modulus (q^2) The second part =0 has no remainder |b=b+1 Then, register a 'hit' ] END IF ~b=a If we have scored N hits |_Xq Quit, printing the last used number (q) \q=q+1 Else, increase q by 1. [DO-loop and last IF are implicitly closed by QBIC] ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 28 bytes ``` @:^#0(!>@! % - ^7#0 1^#0 2)N ``` Zero-indexed. Usage: ``` (@:^#0(!>@! % - ^7#0 1^#0 2)N)2 ``` Filters from the list of natural numbers with a predicate that determines whether `x^2` is divisible by `7^x-1`, then gets the nth item in that list. [Answer] # [Tcl](http://tcl.tk/), 73 bytes ``` while {[incr i]} {if 0==(7**$i-1)%$i**2 {incr j;if $j==$n break}} puts $i ``` [Try it online!](https://tio.run/##K0nO@V@cWqKQp2D5vzwjMydVoTo6My@5SCEztlahOjNNwcDWVsNcS0slU9dQU1UlU0vLCCgMUpBlDZRVybK1VclTSCpKTcyureUqKC0pVlDJ/P8fAA "Tcl – Try It Online") ]
[Question] [ Write a program which gets a string as its input, and counts the number of alphanumeric and non-alphanumeric characters in it. It has to display its result like this: input: `http://stackexchange.com` output: `20 + 4 = 24` The catch is, your source code has to have the same number of alphanumeric characters as non-alphanumeric ones. Comments are not allowed, whitespace is ignored. (The language called *Whitespace* might compete for votes, but will not be selected as winner, obviously) Characters in the code must have at least **some** minor justification, they should not be **completely** superfluous. For example, longer variable names are allowed, `i = (j*3)+4;` instead of `i = j*3+4;` is also allowed. However, `i = i + 1;;;;;;` is not. Besides this, standard code-golf rules apply. [Answer] # Perl, 32 + 32 = 64 The string is expected in STDIN. The output is written to STDOUT. White space is ignored. My interpretation of the task is that the program should be able to run on itself to get the score. ``` $/ = $,; $_ = <>; s x\sxxg; $\ = length; print s x[0-9a-z]xxgi, ' + ', s x.xxg, ' = ' ``` ## Ungolfed with comments ``` $/ = $,; # The input separator becomes undefined, because the default for $, is "undef" $_ = <>; # now $_ takes the whole file (STDIN) instead of the first line s x\sxxg; # $_ =~ s/\s//g; # white space is removed from $_ $\ = length; # The number of the other characters are put into $\, # which is automatically printed the end of "print". print s x[0-9a-z]xxgi, # s/[0-9a-z]//gi # Remove alphanumeric characters and return their count ' + ', s x.xxg, # s/.//g # Remove the remaining special characters and return their count. # "." does not catch new lines, but we have already # removed white spaces including new lines. ' = ' ``` I found several variations with the same byte counts, e.g.: ``` $/ = $x; $_ = <>, s x\sxxg; $\ = split $x; print s x[\da-z]xxgi, " + ", s x.xxg, ' = ' ``` ## Examples * Example from the question: ``` echo 'http://stackexchange.com' | perl a.pl 20 + 4 = 24 ``` * Running on itself (`a.pl`): ``` cat a.pl | perl a.pl 32 + 32 = 64 ``` The file size is 104 bytes, thus 40 bytes are ignored as white space. # Perl, 29 + 29 = 58 ``` $_=<>;s x\sxxg;$\=length;print s x[0-9a-z]xxgi,' + ',s/.//g,' = ' ``` The string is expected at STDIN and it is limited to the first line. The result is printed to STDOUT. White space is ignored. ## Ungolfed ``` $_ = <>; s x\sxxg; # same as s/\s//gx; removes white space; $\ = length($_); # sum is automatically appended at the end of print print sx[0-9a-z]xxgi, # same as s/[0-9a-z]//gi; # the number of alphanumeric characters ' + ', s/.//g, # the number of the remaining special characters ' = ' ``` ## Examples File `a.pl` contains the Perl script. * Example from the question: ``` echo 'http://stackexchange.com' | perl a.pl 20 + 4 = 24 ``` * Running on itself: ``` cat a.pl | perl a.pl 29 + 29 = 58 ``` The file size of `a.pl` is 65 bytes, thus 7 bytes are ignored as white space. [Answer] # C - 96 (48+48) characters It's somewhat readable. There's room for improvement, though. ``` i,j;main(_){while((_=getchar())>=0)isspace(_)||(isalnum(_)?i++:j++);printf("%i + %i = %i",i,j ,i+j);} ``` [Answer] # Bash + coreutils, 72 (36 + 36) non-whitespace chars ``` a=`tr -dc [:alnum:]<<<$1|wc -c` n=`tr -dt [:space:]<<<$1|wc -c` echo $a + $[n-a] = $n ``` Output: ``` $ ./alnumbalance.sh http://stackexchange.com 20 + 4 = 24 $ ./alnumbalance.sh "$(cat alnumbalance.sh)" 36 + 36 = 72 $ ``` --- *Previous answer:* ### Pure Bash, 92 (46 + 46) non-whitespace chars ``` nosp=${1//[[:space:]]} noaln=${nosp//[[:alnum:]]} echo $[${#nosp}-${#noaln}] + ${#noaln} = ${#nosp} ``` Output: ``` $ ./alnumbalance.sh http://stackexchange.com 20 + 4 = 24 $ ./alnumbalance.sh "$(cat alnumbalance.sh)" 46 + 46 = 92 $ ``` [Answer] # PowerShell (43+43=86) **Golfed** ``` function alf($i){$a=0;$n=0;[char[]]$i|%{if($_-match"[a-zA-Z0-9]"){$a++}else{$n++}}; write-host "$a+$n=$($a+$n)"} ``` **Un-golfed** ``` function alf($i){ $a=0;$n=0; [char[]] $i | %{ if ($_ -match "[a-zA-Z0-9]") { $a++ } else { $n++ } }; write-host "$a+$n=$($a + $n)" } ``` **Test** ``` PS > alf "http://stackexchange.com" 20+4=24 ``` **Testing with the code itself to pass the criteria** ``` PS > alf "function alf($i){$a=0;$n=0;[char[]]$i|%{if($_-match`"[a-zA-Z0-9]`"){$a++}else{$n++}}; write-host `"$a+$n=$($a+$n)`"}" 43+43=86 ``` `"` has been escaped with ` which is not part of string. [Answer] ### GolfScript, 74 characters (=37+37) ``` {+}:PLUS;.,.@10,''*26,{65PLUS.32|}%PLUS$-,\1$-' + 'PLUS\PLUS' = 'PLUS\PLUS ``` [Online test](http://golfscript.apphb.com/?c=OyJ7K306UExVUzsuLC5AMTAsJycqMjYsezY1UExVUy4zMnx9JVBMVVMkLSxcXDEkLScgKyAnUExVU1xcUExVUycgPSAnUExVU1xcUExVUyIKCnsrfTpQTFVTOy4sLkAxMCwnJyoyNix7NjVQTFVTLjMyfH0lUExVUyQtLFwxJC0nICsgJ1BMVVNcUExVUycgPSAnUExVU1xQTFVTCgo%3D&run=true) for the code with the code as input. [Answer] # Ruby 38+38=76 This program counts trailing newline in the input. ``` puts"#{a=gets.scan(/[a-z0-9]/i).length}+#{b=$_.scan(/\W|_/).length}=#{a+b}" ``` The character count is done by the program itself: `$ ruby alphabalance.rb alphabalance.rb` :) [Answer] # Powershell, 70 bytes (=35+35) ``` param($s)"$(($l=$s.Length)-($n=($s|sls '\W' -a).Matches.Count))+$n=$l" ``` Test script: ``` $f = { param($s)"$(($l=$s.Length)-($n=($s|sls '\W' -a).Matches.Count))+$n=$l" } &$f "http://stackexchange.com" &$f $f.toString().Trim() ``` Output: ``` 20+4=24 35+35=70 ``` --- # Powershell, 70 bytes (=35+35), alternative ``` "$(($l="$args"|% Length)-($n=($args|sls '\W'-a).Matches.Count))+$n=$l" ``` [Answer] # Python 2 (60+60 = 120) Tough one, there is probably room for improvement. Like the fact the function itself can be used to evalulate its own alphnumeric balance. ``` def f(s): i=j=0 for c in s: t=ord(c) if (t!=2**5): i+=1 if (48<=t<=57 or 65<=t<=90 or 97<=t<=122): j+=1 print `j`,'+',`i-j`,'=',i ``` Test: ``` >>> f("http://stackexchange.com") 20 + 4 = 24 ``` [Answer] # C++, 146 (73+73) ~~178 (89+89)~~ non-whitespace characters# Original included `<algorithm>` for no good reason. Oops. ``` //create a test string #include<string> std::string a = "\?\?=include <cstdio>\ int x,y;\ int main()\?\?<\ for(char c : a)\ !isspace(c) ? (isalnum(c) ? y++ : x++) : 0;\ printf(\"%d\?\?/t%c\?\?/t%d\?\?/t%c\?\?/t%d\?\?/n\",y,'+',x,'=',(x+y));\ \?\?>"; //Code itself starts here ??=include <cstdio> int x,y; int main()??< for(char c : a) !isspace(c) ? (isalnum(c) ? y++ : x++) : 0; printf("%d??/t%c??/t%d??/t%c??/t%d??/n",y,'+',x,'=',(x+y)); ??> ``` I am only counting characters in the lines after `//Code itself starts here`. In particular, this means not counting `#include <string>`. I am also counting trigraphs as three characters each, which is perhaps debatable. Note that in testing the program on its own source code some care is required to prevent trigraph replacement within the string literal. There are some peculiar design decisions here -- in most production code you will not encounter trigraphs and range-based-for loops in the same function -- but I think all within the bounds of 'justifiable'. [Answer] # python 52 +52 = 104 Interesting challnge because python avoids non-alphanumeric characters. ``` def f(_): _=_.replace(" ","");l=len(_);a=sum([c.isalnum() for c in _][:l]);print("{0} + {1} = {2}".format(a,l-a,l)) ``` Minor justification for using slice: it speeds it up (maybe?) [Answer] # Julia, 64 ``` f(s)=(b=endof(s);a=sum([isalnum(c) for c in s]);"$(a) + $(b-a) = $(b)";) ``` All the only unnecessary non alphanumeric characters are the last `;` and some of the `()` in the string formatting., it came out almost perfectly balanced, and as a power of 2 without much fiddling. ``` julia> f("http://stackexchange.com") "20 + 4 = 24" julia> nowhite(s)=join(split("s"," ")) julia> f(nowhite("f(s)=(b=endof(s);a=sum([isalnum(c) for c in s]);\"\$(a)+\$(b-a)=\$(b)\";)")) "32 + 32 = 64" ``` [Answer] # perl, 64 non-whitespace chars: ``` $/=$,; $_=<>; s 0\s00g; $\=length; print s 1[a-z0-9]11ig . " + " . s 2.22g . " = " ``` Clarified slightly via perl -MO=Deparse and some comments: ``` $/ = $,; # input record separator = a variable defaulting to undef $_ = <ARGV>; # slurp stdin s/\s//g; # strip whitespace $\ = length $_; # output record separator = total length of string sans whitespace print s/[a-z0-9]//gi . ' + ' . s/.//g . ' = '; # count alphanumerics, then everything else ``` The ORS, $\ is appended automatically in every call to print, putting the total count at the end. [Answer] ## Python 2, 50 + 50 = 100 ``` import re def f(i): w = re.sub('\s', '', i) s = re.subn('[\W_]', '', w) a = len(s[0]) print '%d + %d = %d' % (a, s[1], a+s[1]) ``` [**Try it Online!**](https://tio.run/##zY5BCsIwFET3OcUnUJLQIOpSyDm6SItEmmBA05AfKZ4@fq14BgdmBuZtJj/rdUnH1uI9L6VC8Wz2AYKM6sSAtIKhcYePixQjCg2CHNWH4Y8lKew4nKcvXzfuiN98kmj307bkElMF0c3QA4WhENCBdBrQHiYNrn@3amg45//1iQ6xIFG1Fw) [Answer] # Rebol (64 + 64 = 128) ``` f: func [x] [ c: :charset a: c [#"a" - #"z"] s: c [#" " #"^/" #"^-"] n: complement union a s a+: n+: 0 parse x [ some [ a (++ a+) | n (++ n+) | s ] ] print [a+ "+" n+ "=" a+ + n+] ] ``` ### Usage example (in Rebol console): ``` >> f "http://stackexchange.com" 20 + 4 = 24 ``` NB. Program ignores spaces, tabs & newlines from counts. [Answer] # J - 46 + 46 = 92 Counts whitespace, so you can't self-test without a modification. Takes input on stdin. Has a bad mouth, should go wash it out with soap. ``` ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10 ``` Usage: ``` ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10 http://stackexchange.com 20 + 4 = 24 NB. modification for self-test: vvvvvv - remove spaces, the only whitespace ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~' '-.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10 ;":&.>(+/;' + ';(#-+/);' = ';#)(e.~1!:1@1:)(,toupper)'golfscriptSUCKSabdehjkmnquvwxyz',,":"0 i.10 46 + 46 = 92 ``` [Answer] # Javascript - 76 (38 + 38) ``` _ = prompt() o = _.match(/[a-z0-9]/gi).length $ = _.length - o alert(o + " + " + $ + " = " + (o + $)) ``` Sample Input: `http://stackexchange.com` Output: `20 + 4 = 24` Running on self: ``` var a = '_ = prompt()o = _.match(/[a-z0-9]/gi).length$ = _.length - oalert(o + " + " + $ + " = " + (o + $))' var letters = a.match(/[a-z0-9]/g).length; var nons = a.match(/[^a-z0-9 ]/g).length; // excludes whitespace from count console.log(nons + " = " + letters); // 38 = 38 :) ``` P.S. For those concerned with `(o + $)` being done to maintain alphanumeric balance, it is not so. Because after seeing `o + " + "` JS would decide all `+` to be string concatenaters rather than number adders. Thus the parentheses are necessary, or `20 + 4` would become `204` rather than `24` :D Happy Coding! [Answer] # Clojure: (31 + 31 = 62) non-whitespace chars ``` (def ff #(let [c count y (c %) x (c (re-seq #"\w" %))] (str x " + " (- y x) " = " y))) ``` Output: ``` alphabalance.core=> (ff "http://stackexchange.com") "20 + 4 = 24" ``` [Answer] # CJam, 27 + 27 = 54 CJam is a couple of months newer than this challenge, so this answer is not eligible for the green checkmark. It was a fun exercise anyway, though! ``` ea0=eu{A,s'[,65>+#)g}%_:+1@f-:+ea0=,]"DODDaD"36f-3/]zo ``` It takes the input string as a command-line argument, so it won't work in the online interpreter, but you can test it with the [Java interpreter](https://sourceforge.net/projects/cjam/). ## Explanation ``` "Distinguish alphanumeric characters:"; ea0=eu{A,s'[,65>+#)g}% ea0= "Get the first command-line argument."; eu "Convert it to upper case."; { }% "Map this block onto each character."; A,s "Get the string '0123456789'."; '[, "Get a string with all characters from the null byte to Z."; 65> "Remove the first 65 characters, to leave A to Z."; + "Add to digit."; # "Find character in that string. Returns -1 if not alphanumeric.": )g "Increment and get signum. Yields 1 for alphanumeric characters, 0 otherwise."; "Now we've got an array of 0s and 1s. Let's do the counting:"; _:+1@f-:+ea0=,] _ "Duplicate array."; :+ "Get the sum. This is the number of alphanumeric characters."; 1@ "Push a 1 and pull up the other copy of the array."; f- "Subtract each element from 1, this swaps 0s and 1s."; :+ "Get the sum. This is the number of symbol characters."; ea0= "Get the first command-line argument again."; , "Get its length. This is the total number of characters."; ] "Collect everything in an array."; "And now the formatting:"; "DODDaD"36f-3/]zo "DODDaD" "Push this string."; 36f- "Subtract 36 from each character. This yields ' + = '."; 3/ "Split into two halves of 3 characters each."; ] "Wrap this and the previous array in another array."; z "Zip. Transposes the array to interleave strings with numbers."; o "Output the resulting array without delimiters."; ``` ]
[Question] [ # Input A single positive integer \$ 10 \geq n \geq 2\$ # Output A list of strings, each of length \$2n\$, satisfying the following properties. * Each string will contain each of the first \$n\$ lowercase letters of the alphabet exactly twice. * No letter can occur twice consecutively. That is `abbcac` is not allowed. * No two strings that are `equivalent` can be in the list. Equivalence will be defined below. * All non-equivalent strings satisfying the rules must be in the list. # Equivalence We say that two strings of the same length are equivalent if there is a [bijection](https://en.wikipedia.org/wiki/Bijection#:%7E:text=In%20mathematics%2C%20a%20bijection%2C%20also,with%20exactly%20one%20element%20of) from the letters in the first string to the letters in the second string which makes them equal. For example, `abcbca` and `bcacab` are equivalent. # Examples * \$n = 2\$: `abab` * \$n = 3\$: `abacbc abcabc abcacb abcbac abcbca` The length of these lists is [A278990](https://oeis.org/A278990). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes ``` ≔⪪…βN¹θ⊞υωF⁺θθ≔ΣEυ⁺κΦθ∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY_PagIxEMbvfYrgaQLxoHgQepKFQkFF9Cg97K6xG8wmMZPxz7N4sdDSvlIfwnfopFWhAwOT3_fxzeT0VTdlrH1pz-cPSuvu8PsyQjSvDhbBmgTFsba6aHyASolnFyhNqa10BCmV6HFv5ePDjLABUmLP89pHATNLCNssSnGLoxYmZci2X3WjxJOxiZPYN3IrmBjHuL3jud7piBo2vGTqEwSZV2bnWCNC4cmlnNIy7WfF2v_XOoZ310FeSwnKF0fDnKd3rGq8fv1z2enubOflbfD3_gE) Link is to verbose version of code. Theoretically supports `n` up to `26`. Explanation: ``` ≔⪪…βN¹θ ``` Get the first `n` letters of the lowercase alphabet. ``` ⊞υω ``` Start with an empty string. ``` F⁺θθ ``` Loop `2n` times. ``` ≔ΣEυ⁺κΦθ∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυ ``` For each string so far, create strings with all of the first `n` lowercase letters appended to it, but exclude those that fail to satisfy the criteria. ``` υ ``` Output the final strings. There are three criteria that are checked when considering candidate letters to append: * The letter must not already be the last letter of the string * The letter must not have already appeared twice * All previous letters must already appear in the string [Answer] # JavaScript (ES6), 107 bytes Returns a single space-separated string. ``` f=(n,s=' ',m=1,i=m,g=q=>i?f(n,"abcdefghij"[--i]+s,+q+m)+g``:q)=>s[2*n]?/(.)(|.*\1.*)\1/.test(s)?'':s:g(m<n) ``` [Try it online!](https://tio.run/##HY1BboMwEEX3PYUVRcKDjRGRsiFxOESXcSQoMcYRHhdsdUM5O3W6etJ//8@8up8u9Iv9jgX6p973QVLkQWYk405W3ErHjZzlzTZDEofuq3/qwYz2dbgXhX2wwNnMHDDTtvUM8hbupxwfTUkF0F@Rq0rkoKpSRB0iDdBkWR1qQ90VYR/8QicdCRJJTpeEqyTnRMaArB@EvN2iQ7LpN1xS0nsMftJi8oa279lxxU3hcU21jf5DuC72Iy3VJysNiEmjieMGCtt0Ydv/AA "JavaScript (Node.js) – Try It Online") Or **[106 bytes](https://tio.run/##HY1BboMwEEX3PYUXkZjBxohIVVUSB6lX6DKOBKK2Q4WHgt1uKGenTldP@u//mc/upwv9MnzFgqYPs@9WAYmgMpYJryoxKC@cmtVlKIrGJvX2ba1Z4Drw15cb8iD4zD1y17b1jOoSrsecbk0JEuFX5rqSOeqqlNGECAGbLKtD7cCfCXc7LTCayIgpdjwlnBV7TuQc2frE2MMtJiSbHuMpJf1EYRqNHCcH7WN2WGnTdFhTbYN/SN/F/g6lfuelQzkacvG@oaY2Xdj2Pw)** in Node.js. ### Method We recursively build all non-equivalent strings of length \$2n\$ with \$n\$ distinct characters. The non-equivalence is enforced by using an upper bound \$m\$ which is initialized to \$1\$ and incremented as soon as the \$m\$-th character has been inserted and while we have \$m<n\$. The other criteria are tested at the end of the recursion with a regular expression which should *not* be matched by a valid string: ``` /(.)(|.*\1.*)\1/ ``` ### Commented ``` f = ( // f is a recursive function taking: n, // n = input s = ' ', // s = current output string m = 1, // m = upper character bound i = m, // i = counter g = q => // g is a recursive function taking a flag q: i ? // if i is not zero: f( // 1st recursive call to f: n, // pass n unchanged "abcdefghij" // lookup string of letters [--i] // decrement i and append the i-th letter + s, // followed by s +q + m // increment m if q is set ) // end of recursive call + g`` // 2nd recursive call to g with q zero'ish : // else: q // stop (at this point, we have q = ['']) ) => // s[2 * n] ? // if s has 2n + 1 characters: /(.)(|.*\1.*)\1/ // if there's any character in s immediately .test(s) ? // followed by itself or appearing 3+ times: '' // s is invalid, so append nothing : // else: s // append s : // else: g(m < n) // initial call to g with q set if m < n ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 69 bytes ``` .+ * Y`\_`l ^ <$'> />./+Lrv$`(?(2)(\3.+))<(.+)?(\w) $%`$1$3<$2$%' <> ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srMiEmPiGHK47LRkXdjkvfTk9f26eoTCVBw17DSFMjxlhPW1PTRgNI2mvElGtyqagmqBiqGNuoGKmoqnPZ2HH9/28CAA "Retina – Try It Online") Might work up to `n=26`. Explanation: ``` .+ * Y`\_`l ``` Generate the first `n` lowercase letters. ``` ^ <$'> ``` Make a duplicate set, and wrap the first set in `<` and `>`. ``` Lrv$`(?(2)(\3.+))<(.+)?(\w) $%`$1$3<$2$%' ``` For each string, make new strings by either a) moving the first character from the first set or b) moving a character from the second set that was moved from the first set but not in the immediately previous iteration. ``` />./+` ``` Repeat until the second set is empty for all strings. ``` <> ``` Remove the `<>` markers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 15 [bytes](https://github.com/DennisMitchell/jelly) ``` Øaḣx2Œ!Q⁼Ɲ;QƊÐṂ ``` A monadic Link that accepts \$n\$ and yields a list of lists of characters. **[Try it online!](https://tio.run/##y0rNyan8///wjMSHOxZXGB2dpBj4qHHPsbnWgce6Dk94uLPp/@H2yP@JSYnJSclciUnJiVAqOQlEAYXBVHLif2MA "Jelly – Try It Online")** ### How? ``` Øaḣx2Œ!Q⁼Ɲ;QƊÐṂ - Link: n Øa - alphabet ḣ - head to index {n} x2 - times two Œ! - all permutations Q - deduplicate ÐṂ - keep those {P in those permutations} minimal under: Ɲ - to neighbouring pairs {P}: ⁼ - equal? Q - deduplicate {P} ; - concatenate ...e.g. 'accbab' -> [0,1,0,0,0,'a','c','b'] (minimal entries would be [0,0,0,..,0,'a','b','c',...]) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 127 bytes ``` f=(n,z=[],L)=>[...n?f(n-1,[c=(n+9).toString(36),...z],c+[L]):z+z?[]:[L],...z.flatMap(t=>t==L[0]?[]:f(n,z.filter(y=>y!=t),t+L))] ``` [Try it online!](https://tio.run/##ZY2xCsIwFEV3/8Itj6ZBrQhWXvsDcXIMGUJsSiUkpX0Izc/H1lG3yzkH7su8zWynYaQyxGeXs0MWeEKluQRslBAitI6F8siVXVVxBUHxQdMQelZdgK9B0twWSmqoU5Fapet1f7lw3tDdjIywIUSpDnrTbnsQbvDUTWzBZtkjAadCAuh829kY5ug74WPPHDsB/JDqj5wB8gc "JavaScript (Node.js) – Try It Online") [Its `print` version](https://tio.run/##Zcy9CsIwFEDh3bdwyyXXoFbEH1JfIJtjyFBCUyo1Ke2l0JB3j3HV9XxwXs3SzHbqR9otl5ydZB6j1AYVyDqKdzMykjVJqfTepOS@LFw/UDuxVdbrVhIgcQXoHwV3B9S2PPgVBIUnTb3vWHUGFEJEg5ZrZeAWeUxpLEZMAeT7xrEjoA1@DkMrhtAxKKn6T6eflD8) is 116 bytes [Answer] # Python3, 323 bytes: ``` def B(a,b): d={} for a,b in zip(a,b): if b not in(T:=d.get(a,[])):d[a]={*T,b} return d def F(n): r,q=[],[['abcdefghijklmnopqrstuvwxyz'[:n]*2,'']] for s,k in q: if''==s: if all(any(len(K)>1for K in B(j,k).values())for j in r):r+=[k] for i,a in enumerate(s):q+=[[s[:i]+s[i+1:],k+a]]*(k==''or a!=k[-1]) return r ``` [Try it online!](https://tio.run/##TVCxbsIwFNzzFe5kP@IiAR2QJXdgYGFlszw4jQHHwUlshxZQvz21i6i6ne7u3bv3@ms8dW617v001fqANkTRCliBan7/LtCh8ygRyDh0M/1TQ@aAKuS6mHiyZ7yeH3VMopAArBZK8vtsT6s073UcvUN1kbO3xOVpTwcuJBUCq@oj8ceTaWx7dl0/@BDHy@fX9YYFc3K2pBhL@WgRqM0thsd6jDkPGeYqqm2JclfSakd28L7I9l02b0hDLcwvqh11IABZaLLggfmSC5uyf8MNVZnWbjxrr6ImAdiQDCIIZmQZhCkXTFJbKilnxHKOcX7MC7fidSHh704/9d64SLZkCVA88eoffgOYfgA) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 18 bytes ``` r:,↕ũ∆Zç∫:ux=¿97+H ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FruLrHQetU09uvJRR1vU4eWPOlZblVbYHtpvaa7tsaQ4KbkYqm7BYiMuYwgTAA) ``` r:,↕ũ∆Zç∫:ux=¿97+H r:,↕ũ Find a list of length 2n that contains each number from 0 to n exactly twice r Range from 0 to input : Duplicate , Join ↕ũ Permutation ∆Zç∫ Check that no two adjacent values are equal ∆ Delta Z Check no values are 0 ç Prepend 0 ∫ Cumsum to get back to the original list :ux=¿ Check that the list is in the standard order : Duplicate u Uniquify x= Check that the result is [0, 1, 2, ..., n] ¿ If so, get back to the original list 97+H Convert to string 97+ Add 97 H Convert from codepoints to string ``` [Answer] # [Python 3.10](https://docs.python.org/3.10/), 204 bytes ``` from itertools import* def f(n):z,F='abcdefghij'[:n],frozenset;q=F();return[x for x in permutations(z*2)if all(a!=b for a,b in pairwise(x))and q!=(q:=q|{F(F(I for I,c in enumerate(x)if c==d)for d in z)})] ``` Testable as `f(n)`, outputs list of tuples. Each tuple contains "characters" (strings of length 1) and is thus equivalent to a string. # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 205 bytes `itertools.pairwise` was added in 3.10 and is not supported by TIO, so here's another version: ``` from itertools import* def f(n):z,F='abcdefghij'[:n],frozenset;q=F();return[x for x in permutations(z*2)if all(a!=b for a,b in zip(x,x[1:]))and q!=(q:=q|{F(F(I for I,c in enumerate(x)if c==d)for d in z)})] ``` [Try it online!](https://tio.run/##TYzBboMwEETv@QrnlN3IlyY9VES@IuUbEAcDduMK1mZZJJe2304DUqXeRjNvXvqUR6TrW@J19RwHFcSxxNhPKgwpspwPnfPKA2Gx6NKcbNM@i/dH@DhVBdX6eVocTU5uoykBb@xkZqqy8pFVVoFUcjzMYiVEmmA5XzB4Zfse7NE0O2V1s3FLSJB1rl6KGtFSp8ajgbEw4/dXCSXcd/au2411NA@OrTjIm641psNt7nYR/mC9Jg4k4OGCePjL13/5FXH9BQ) Works by simple bruteforce, will likely time out for \$n \ge 6\$. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 (or 16*†*) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L€DœÙʒDüÊ*ÙāQ}.bl ``` Output as a list of lists. *†*: Could be -1 byte removing the trailing `l` by outputting in uppercase. [Try it online](https://tio.run/##ASUA2v9vc2FiaWX//0zigqxExZPDmcqSRMO8w4oqw5nEgVF9LmJs//8z) or [verify both test cases](https://tio.run/##ATMAzP9vc2FiaWX/MkVOPkQ/IiDihpIgIj//TOKCrETFk8OZypJEw7zDiirDmcSBUX0uYmz/LP8). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] €D # Duplicate each value within the list œ # Get all permutations of this list Ù # Uniquify it ʒ # Filter this list of lists by: D # Duplicate the current list ü # For each overlapping pair: Ê # Check that they are NOT equal * # Multiply the values in the lists at the same positions # (removing the trailing item, but this doesn't matter) Ù # Uniquify it ā # Push a list in the range [1,length] (without popping) Q # Check whether the two lists are the same }.b # After the second filter: convert all integers to their 1-based alphabetic # uppercase letters l # Convert those to lowercase # (after which the result is output implicitly) ``` [Answer] # [Perl 5](https://www.perl.org/), 161 bytes ``` sub{$_=substr(abcdefghij,0,pop)x2;my%r;1while s/^(.*)(.)(.*)(.)(??{($t="$1$4$3$2$'")=~m,(.)(\1|.*(.).*\3(??{$1lt$3})),||$r{$t}++;$s{$t}++||''})/$1$4$3$2/;keys%r} ``` [Try it online!](https://tio.run/##bZddU1tHDIbv@RU77qHYjgcCJP3A48B9Z5qb3oU2s9KKhJav2O4kDNC/Tlfafd/DTMvNeZB19GpX0q59Z@urt8/Dxep587c8DB9X9bHZrqdZtNjFp8@Xfy5eL@5u72bfjpbX97vr5eHXz5dXljYHf0z357Pp/gyP09OH6bBdTYbD4c1wPBwNe5PZ6p/rhX92fvi4P6@wPz8/dsfh8Go7HD/NZovHx2H9MGyfXr1aDpsGj497e0@zA8Q5WP5l95vd9dPzcufidj3dSelDOkqrd@nL12nKkiXN0u@LMB@/MKtofWjuDxV/VHM8NI8vvXkZS4uW9jagCKFog/phhyJNozlrOAX0txyKVpnxL4wKtx5Bco9QX8sNSlZAaUkXxUfVyaHkrlLy/6iU3FU8kjQobTc8ZLNIVynSVYp0FV9BU/FUOmj@j4qvvkNX8dV06BE8wQ7yYuff9p3vG2/Feg1MX6AVYHUhmvYil/6ab8uIiBBoKCkiBPYIdZ14rYRzR0ZwNLQAIzga@4ER6ksCNCkjIkINNTpU54YmVDOhmgnVPJYCTelg6ElTqplSzZRqvh6oeWrEAqvvBJFqvjoiI3iaRO1TgFrEQIzYd7KhFWBbW0PDkDJC2@COfSe1LxnY1qY9H8wdXmM1HZkDqxlYRgfkwGrGdJoAmQOrGVhGB@aAajaEL6rZEGqoZsMCq1IN1QykGqoZaEIHK7D2ajakWq9mQ0bo1WzIkxK1kMxqSmY1JbOakllNyaxmD4dTbUTLL9Bw7Fl1IVrGGYjXSkY1KzIHR8MxyRxCjGcmI4RcR@bgiAjKHGLBPQfLVLNMNctU81gKNKWD4dw2pZop1Uyp5uuBmqdGLLD6ThCp5qsjMoKnSVTeFH0fSuZcVMROBhouE@xkoCluE0bgXHhaUkZEBM5FqyBvHwrHEHU00RGhFn1PRAROViDUOFmBiMDJCiywKvPlZEVDCa3Ml5PV2gzWwnw5WdF8jFDGfDFZrSV552InhV1dkbUQdrVjGR2wNmFXF2FXe1q5jIgI7Op2NvJOp3CMQEfLOiLUomuJiMC5CIQa5yIQETgXgfimwbkIZARlvpyL6JxMB8M3E85FINUK8@VcxAmf6YC50MyubidwR3a1Zna1ZnZ17D@/7TCCsBYqrIUKa6HCWsQ08dsRhWN/OlqWEaFWZUcHQQTLzNffKkDm69kIEF0dTQKrMF9XgIMwX98RqAlqESMPa2G@vkrELczXd4@@lulQ9QItc7otc7otc7pjlQpER8WCYeV0W@Z0W@Z0R88KEPsQ7Qsrpzt2D3E53dHf9MV0R6vDasLMTJiZKdVMqWaFEQzfyU04WSacLBNOVtRKgdwH4WSZcLJMOFkmnKw4RzMQ1YwjFVZOVvQA4nKy4sylLyYrjl9YLTMzy8zMlGqmVLPCCD69DZVdbcquNmVXx/khQFZT2dWm7GpTdrUpuzpuA6ixq@NigJVdHecS4rKr4@agL7o6LhFYLTMzy8zMhGomVLPCCD45DeP2JqIWcSMTkVlcjER0VNw5REYQVjNuDCCrGedyR@U@xJkI5D7EOQfkPsRp0tEyM7PMzEyo5r0KVEbwysVPxu/Shx9W7xr8CPgJ8DPg8HXQ7CF@ol7fT4ebxZl9u5ulVTobPi53mjmdfbrdVtPmdr1N3w8X1W3WPrtbX95sLya7m5RuqsNwc37j5hrCdGvlJHm0ZqshTtpPYY92fjNZpIl/Okn2pVK1TdJp2nv/y146SXvz@fzX97@l@t9y52nn@V8 "Perl 5 – Try It Online") ``` $f= sub{ $_=substr(abcdefghij,0,pop)x2; #set $_ to first n chars times 2 my%r; #init %r where results are collected 1 while #repeat while untested perms exists s/ #permute $_ by swap of two random chars ^(.*)(.)(.*)(.) (??{ $t="$1$4$3$2$'"; #test new permutation in $t $t=~ m,(.)(\1|.*(.).*\3(??{$1lt$3})), #two of same not neighbors and #no higher char before two equal lower || #if no error then tests passed and... $r{$t}++; #register current perm $t as a result $s{$t}++||'' #register current perm as seen/done }) /$1$4$3$2/x; #if not seen change $_ to new perm keys%r #return registered results } ; ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~528~~ 521 bytes Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/264123/110802) in Scala. **521 bytes, it can be golfed much more.** --- Golfed version. [Try it online!](https://tio.run/##ZZFBb9swDIXv/RVaTiTicsu2kzMHGIYeBqwYhmCnIChkm05Uy7ItyWkT1789k91kKDadyAfx8dOTy6SW5zp95MyLe6mM6G@EyLkQVWhA2p2LxVdr5XGz9laZ3RZj8dsoL5LpphBNUL02UMBHxH@UT/8pnydlOI8bUpDxq2mUXgpM4F42xFXjj5tve2mjNfup2G7fx5JOqoEUsYc8ajBZ5XNo6GFxu4Kcdux/2jvteJLGuVcbnIsgBLbhZlxagIm/G49Jf5BatIkbA6Cs1jokoGpDVedlqpl@ddzxBi6AF7wtwBQGFUrr8GCYyTQLtru9eix1Zeqmtc53h6fn42lGrkvdNAcfIoNIVXlxm80QlwdphU1@KOev0QIun/ZKM7RkanM30Y@Y4K45lX9zainndkRcqgIcKXe5HjpLRW1l4FsnqxTWUYkUTDp2xM9hm4MHcurEqwWGJG1SxrEdBg7J9WEO1JfbYGdylbGb7Mqr@cuLA4XvkpK0dB77lthMCBAA3r5V4fytoOYLjMr5OBx@IZylJcsHto6Xw3k4/wE) ``` def b(a:String,b:String)=(Map.empty[Char,Set[Char]]/:a.zip(b)){(d,p)=>d+(p._1->(d.getOrElse(p._1,Set.empty)+ p._2))} def f(n:Int)={val q=scala.collection.mutable.Queue[(String,String)]((Array.fill(2)("abcdefghijklmnopqrstuvwxyz".substring(0,n)).mkString,""));var r=List[String]();while(q.nonEmpty){val(s:String,k:String)=q.dequeue;if(s.isEmpty){if(r.forall(S=>b(S,k).values.exists(_.size>1))){r=k::r}}else{for(i<-s.indices){if(k.isEmpty||s(i)!=k.last){q.enqueue((s.substring(0,i)+s.substring(i+1),k+s(i)))}}}};r.reverse;} ``` Ungolfded version. [Try it online!](https://tio.run/##fVLLbtswELz7K7Y@kYhD1G1PQmOgaHMokKAojJ4MI6Cklc2IohSScmI7/nZnRUm23AA5idrH7MzsukRqeTyW8SMmHu6lMrAfAaSYQUE/TNqVi@CHtXK7mHurzGrJI/hnlIebUAlQUdRrwzJl0jk@1WgSdOwL5x9kv36Y/Rayh1FHJK6VTn@pxKvSSLtlMoKWygTi/kmk7mW1@LmWdgJz9OG1XJ5ISrFTFYu5yEqd3mHmGZULLCq/fdfEYQ8spXkTqKSyHG5mAYPYUBCugDVh8TCF61lbKFbo/9hb7bBPBbwWn1NHG@09OQzVXUo3Efw2ntTcKed7x08qNtKCIu@V1G2KMmE3IlNak@dsLOOEUFdr9ZjrwpTVk3W@3jy/bHdj4erYhTb2eWI4F0XeonTYGohFjYTpmqsQSak1BtdFUXsZaxR/m4IF6@3vvF8ydsFqAuNxJ7VhbNHVurmXoSbGR6Hgea00sjBYmNLcto7tO8MbUsyd952f9k1wbVOK4dvjAaiMOaHcf0gh3jKhG7CS7CI7aLXvzovCNIgLml2jE/hCrB17EE7tEGYw5XyICmd5OURR93dKH7rXAZCuY9BHHJiC79dAXA3dELpLVGKb9yrg9RUcUxw@0RChpfOXtdBZgaa1gvQPVw2qOcFhTF1NOWlsogTbreqS8IB6d7Ojs1hhcYPWYbjjw@h4fAM) ``` object Main { def main(args: Array[String]): Unit = { println(findSequences(2)) println(findSequences(3)) println(findSequences(4)) } def buildDictionary(a: String, b: String): Map[Char, Set[Char]] = { a.zip(b).foldLeft(Map.empty[Char, Set[Char]]) { (dict, pair) => dict + (pair._1 -> (dict.getOrElse(pair._1, Set.empty) + pair._2)) } } def findSequences(n: Int): List[String] = { var initialString = Array.fill(2)("abcdefghijklmnopqrstuvwxyz".substring(0,n)).mkString val queue = scala.collection.mutable.Queue[(String, String)]((initialString, "")) var result = List[String]() while(queue.nonEmpty) { val (s: String, k: String) = queue.dequeue() if(s.isEmpty) { if(result.forall(sub => buildDictionary(sub, k).values.exists(_.size > 1))) { result = k :: result } } else { for(i <- s.indices) { if(k.isEmpty || s(i) != k.last) { queue.enqueue((s.substring(0, i) + s.substring(i+1), k + s(i))) } } } } result.reverse } } ``` ]
[Question] [ Let \$\sigma(n)\$ represent the divisor sum of \$n\$ and \$\sigma^m(n)\$ represent the [repeated application](https://en.wikipedia.org/wiki/Iterated_function) of the divisor function \$m\$ times. [Perfect numbers](https://en.wikipedia.org/wiki/Perfect_number) are numbers whose divisor sum equals their double or \$\sigma(n) = 2n\$. For example, \$\sigma(6) = 12 = 2\times6\$ [Superperfect numbers](https://en.wikipedia.org/wiki/Superperfect_number) are numbers whose twice iterated divisor sum equals their double. For example, \$\sigma^2(16) = \sigma(\sigma(16)) = \sigma(31) = 32 = 2\times16\$ [\$m\$-superperfect numbers](https://en.wikipedia.org/wiki/Superperfect_number#Generalizations) are numbers such that \$\sigma^m(n) = 2n\$ for \$m \ge 1\$. For \$m \ge 3\$, there are no such numbers. [\$(m,k)\$-perfect numbers](https://en.wikipedia.org/wiki/Superperfect_number#Generalizations) are numbers such that \$\sigma^m(n) = kn\$. For example, \$\sigma^3(12) = 120 = 12\times10\$, so \$12\$ is a \$(3,10)\$-perfect number. You are to choose one of the following three tasks to do: * Take three positive integers \$n, m, k\$ and output the \$n\$th \$(m,k)\$-perfect number (0 or 1 indexed, your choice) * Take three positive integers \$n, m, k\$ and output the first \$n\$ \$(m,k)\$-perfect numbers * Take two positive integers \$m, k\$ and output all \$(m,k)\$-perfect numbers You may assume that the inputs will never represent an impossible sequence (e.g. \$m = 5, k = 2\$) and that the sequences are all infinite in length. You may take input in [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Note that methods that count up starting from either \$m\$ or \$k\$ are not valid, as they fail for \$(4,4)\$-perfect numbers, the smallest of which is \$2\$ (credit to [Carl Schildkraut](https://math.stackexchange.com/a/4045163/427632) for finding this) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. --- ## Test cases This lists the first few outputs\${}^\*\$ for example inputs of \$(m, k)\$ ``` m, k -> out 3, 10 -> 12, 156, 32704, ... 2, 2 -> 2, 4, 16, 64, 4096, 65536, ... 1, 2 -> 6, 28, 496, 8128, ... 4, 48 -> 160, 455, 5920, ... 3, 28 -> 4480, ... 3, 16 -> 294, 6882, ... 1, 4 -> 30240, 32760, ... 4, 4 -> 2, ... ``` \${}^\*\$: Aka, the outputs I could get from my generating program without timing out on TIO [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 95 92 87 bytes -8 bytes thanks to mazzy! This takes two parameters, m and k, and calculates all (m,k) perfect numbers (up to the maximum for a 64-bit signed integer). ``` param($m,$k)for(;$n=++$x){1..$m|%{$a=0;1..$n|%{$a+=$_*!($n%$_)};$n=$a} ,$x*!($a-$k*$x)} ``` [Try it online!](https://tio.run/##HYtBCoAgFAX33SJ4gaZF0TI8S/xFEZgWtigwz/7LljPMHPs1h3Odt435oEBOwGlYuexBjPBGKdwy9m0L91QRZLoxg/9BGUx1KeArTDLlHJQKjTtLamDrb07MPHDfvQ "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Outputs the infinite sequence given \$m\$ and \$k\$. ``` ∞ʒ¹FÑO}y/Q ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5MO7XQ7PNG/tlI/8P9/Yy5DAwA "05AB1E – Try It Online") ``` ∞ # push an infinite list of positice integers ʒ # iterate over the list and keep y if: ¹ # push the first input m F } # iterate m times: ÑO # take sum O of divisors Ñ # sigma^m(y) y/ # divide by y Q # is this equal to the second input k? # sigma^m(y) / y == k ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1Æs⁴¡÷¥Ƒ# ``` A full program accepting `k m n` which prints a list representation of the first `n` \$k\$-\$m\$-generalised-perfect-numbers. **[Try it online!](https://tio.run/##y0rNyan8/9/wcFvxo8YthxYe3n5o6bGJyv@BQgb/jf8bAQA "Jelly – Try It Online")** ### How? ``` 1Æs⁴¡÷¥Ƒ# - Main Link: k 1 # - count up from j=1 & find the first (3rd argument, n) truthy results of f(j, k): Ƒ - is (j) invariant under?: ¥ - last two links as a dyad - g(j, k): ¡ - repeated application... ⁴ - ...number of times: 1st argument, m Æs - ...action: divisor sum ÷ - divide (by k) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` fS=ö/⁰!²t¡oΣḊN ``` [Try it online!](https://tio.run/##ASoA1f9odXNr/@KGkTLigoH/ZlM9w7Yv4oGwIcKydMKhb86j4biKTv///zP/MTA "Husk – Try It Online") Outputs the infinite sequence of (m [arg1], k [arg2])-perfect numbers. TIO header gets just the first two terms, to avoid timing-out. ``` N # from the sequence N of all integers, f # output the elements that are truthy with this function: ¡o # construct an infinite list by repeatedly getting ΣḊ # the sum of divisors; t # discard the first element, !² # and get the element at index given by arg1, /⁰ # then divide it by arg2, S=ö # and check whether it's equal to the original number ``` [Answer] # Scala `-language:postfixOps`, 80 bytes ``` m=>k=>Stream from 2 filter(n=>(n/:1.to(m))((n,_)=>1 to n filter(n%_<1)sum)==k*n) ``` [Try it online!](https://scastie.scala-lang.org/aM1eBJ1xT8ykeKvSKFZ1qQ) Outputs all (m, k)-perfect numbers. The flag just saves a couple bytes, but why not use it? ``` m=>k=> //Curried arguments Stream from 2 //Infinite stream of integers starting at 2 filter(n=> //Filter every n in the Stream according to this predicate k*n== //Check if k * n equals //The iterated divisor sum (n/:1.to(m)) //Fold left over the range [1..m] starting with n //We don't actually care about the values in [1..m], it's just to repeatedly find the divisor sum ((n,_)=> //Find the divisor sum of the left argument: 1 to n //Range [1..n] of possible divisors filter(n%_<1) //Filter the ones that divide n sum //Sum them ) ) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~139~~ 123 bytes ``` g=lambda n,m:m and g(n+sum(i*(n%i<1)for i in range(1,n)),m-1)or n f=lambda m,k,n,x=1:n and f(m,k,n-(g(x,m)==k*x),x+1)or x-1 ``` [Try it online!](https://tio.run/##TY/dCoMwDEbvfYogDBqNsKgXQ@ZeZOzC4XTFNYpz0D29q3@4Qujh4@Sj7b7Ds5VkHOv8VZh7WYCQyQwUUkKtJHx/jNKBkoM@M1ZtDxq0QF9I/VBMgkgmYnS5eNXWYKghIZtzJnNPpeYkUrWyZDDPm8Ai2XDesxGPU68haAhkar@qhICPbpBg43ji2N1rvOBfmuyYTsi7y7vLu5s68bQaK8d4yzxwp@u1DMuzyY8uPm2fQBx/ "Python 3 – Try It Online") Very direct approach, brute-forces for every number and runs until a result is found. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes outputs all (m,k) ``` Do[Nest[Tr@*Divisors,n,#]==n#2&&Print@n,{n,∞}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yU/2i@1uCQ6pMhByyWzLLM4v6hYJ09HOdbWNk/ZSE0toCgzr8QhT6c6T@dRx7zaWLX/YBEFh/RoYx1Dg9j//wE "Wolfram Language (Mathematica) – Try It Online") -3 bytes from @att [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes Takes two positive integers \$ m,k \$ and outputs all \$(m,k)\$-perfect numbers. ``` def f(m,k,n=1): s=n;exec"i=t=s\nwhile~-i:i-=1;s+=i>>t%i*t\n"*m if s==k*n:print n f(m,k,n+1) ``` [Try it online!](https://tio.run/##NYzLDoIwEADv/YqGxITyMFZPQpYv4YZt2ECXprtGufjrFQ9OMseZuMu80TVjiFsSzTurwzM7SW56JsaNVgwo5f2HyQ/ntS9DszQE1nRKM1Dv3m4qEAR4pNeMq/u02GELtucacBjkhJWMVFRBafRHAktFXUxIokn9f7U12Ze3RtuLyV8 "Python 2 – Try It Online") A straightforward implementation of the problem. The one obfuscation used is the `s+=i>>t%i*t`, which is equivalent to `s+=i*(t%i<1)`, or `if t%i<1:s+=i`. [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╩╔◘8┌╜♀ñêP=e ``` [Run and debug it](https://staxlang.xyz/#p=81cac90838dabd0ca488503d65&i=3,10) the divisor sum part takes a lot of space due to two byte builtins. Outputs the sequence for `m,k` infinitely. [Answer] # JavaScript (V8), 119 bytes ``` f=(m,k,i=1)=>((g=x=>(s=[...Array(x+1).keys()].reduce((a,b)=>a+(x%b<1)*b),--t?g(s):s))(i,t=m)==k*i&&print(i),f(m,k,i+1)) ``` [Try it online!](https://tio.run/##JY1BCsIwEABfY9ltN8HgRcRVfId4SGpSYmgpSSzp62PA01yGmY/edBqjX7PYzrU6hpkCeVbIN4CJS0Pip5TyEaPeoQwKZbB7AnzJaN/f0QJoMk3XA5SDuSrsDZIQ@T5BwktCBE@ZZ2QOve@6Nfolg0dy/1ULYnVwInXE@gM) [Answer] # JavaScript (ES6), 86 bytes Expects `(m,k,n)` and returns the \$n\$th \$(m,k)\$-perfect number (1-indexed). ``` (m,k,n)=>{for(i=0;n;n-=s==i*k)for(M=m,s=++i,d=0;d||(j=d=s,M--);)s+=j%--d?0:d;return i} ``` [Try it online!](https://tio.run/##PY7PboMwDIfvPIUPnZqUJCIUTVORO@2wY58AoRXxZws0SZV0kybaZ2cpnTjZn3/@LPfVT@Vrp84XbmzTTh1ORLOBGYr7sbOOKExykxuOHlFtBnqfHVAzj3GsWBPS5nolPTbo2YFzmlMfY//EefOa7JrctZdvZ0DdpryIAIotA5kwSEt2pzR0DLIHyBm2D8jC@GXZC1YaSC4kn5csaNkC2QyyjMpIhE/fq/qLkEIzGBiYkgLuobbG21MrTvaTHDWuRn0LcajDbQersRBCvDlX/RJDS6GrMyEfwZ3VjvxfghgkpaK3ypA1gzUNJ4J3pHT6Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` f m k n=take n[r|r<-[1..],r*k==iterate(\a->sum[x|x<-[1..a],a`mod`x==0])r!!m] ``` [Try it online!](https://tio.run/##JclBCoMwEAXQq3yhC1tUrNBdpxeJAQeMGOKkMqaQhXdPC@Ut38pHcNtWygJBQKTEwSEaPfXZmnvX2UZvgcgnp5xcPXL7Oj5i8pn/z7bhSd7zlIl6e9WqEluEfQRhVx8TLlgw/DzKFw "Haskell – Try It Online") * returns first n terms [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes ``` NθNηNζ≔¹εW‹ⅉθ«≦⊕ε≔εδFη≔ΣΦ…·¹δ¬﹪δλδ¿⁼δ×εζ⟦Iε ``` [Try it online!](https://tio.run/##XY09C8JADIZn/RUZc1AHxc1JREFQEXURcTjb1B5c7@x9KCj@9jPFDmK2J@@bPHklXW6lTmlpbjFsYn0hh42Y9H@5@uMn89R7dTU4zICYHpXSBLgi7/GIIoNGCHj1e2t564pLkzuqyQQqvie9LqAMihZL64BN0K33scaF0oF1fKqjV3faSXOlVlmwYWMDrm0RtUX@qAVP90mVgPMmSu3b5KBq8q3lyQ3YOmUCnmbSByRx5vo7pTGMYJQGd/0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηNζ ``` Input `n`, `m` and `k`. ``` ≔¹ε ``` Initialise the loop at one. ``` W‹ⅉθ« ``` Repeat until `n` values have been output. ``` ≦⊕ε ``` Try the next integer. ``` ≔εδ ``` Make a copy of it. ``` Fη ``` Repeat `m` times... ``` ≔ΣΦ…·¹δ¬﹪δλδ ``` ... replace the copy with the sum of its divisors. ``` ¿⁼δ×εζ ``` If the result is `k` times the loop counter, ... ``` ⟦Iε ``` Output the loop counter on its own line. [Answer] # [Clojure](https://clojure.org/), 112 bytes ``` #(rest(for[i(range):when(=(* %2 i)(nth(iterate(fn[j](apply + j(for[k(range 1 j):when(=(rem j k)0)]k)))i)%1))]i)) ``` [Try it online!](https://tio.run/##PY3BasMwEETv/oqBENhNLpGihFLIlwgdTLNqJDmyoyiUfr1rOdDTG9h5O1/DGF9FZrqKh583VORZyY/FBip9/hb@/LlJpgvtsNUITLneKFQpfRXy2UZH/TQNv9gjrl56e1CI/26ROyISH9glZg68VcwuMM/c0XV8ygPWZtyRnO2swhHq4Dp7goZeaJZnjUcYmA/3bugWdKue16Bg1otpdK6jqYRchwyqfRIs9G1gmef5Dw "Clojure – Try It Online") Anonymous function that returns an infinite lazy sequence of all \$(m,k)\$-perfect numbers. Test suite extracts \$n\$ first members of the sequences, albeit a bit fewer than in the task specification in order to fit within a minute on TIO. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` È*V¥_â x}g[X]}iW ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yCpWpV/iIHh9Z1tYXX1pVw&input=MgoyCjU) ``` Prints nth element 1-indexed 1st input(U) = m 2nd input(V) = k 3rd input(W) = n @ ... }iW - return W-th number that satisfy Om(n)==kn _â x} - sum of divisors g[X] - repeated U times starting with X ¥X*V - ==kn ? ``` ]
[Question] [ This problem is based on non-terminating, repeating decimal points. Let \$n\$ be any positive integer \$(n > 1 \text{ and } n < 10000)\$, say \$7\$. Then, \$1/n = 1/7 = 0.142857142857142857...\$ We see a pattern like, `0. 142857 142857 142857 ...` In this, the `142857` part is always repeating, which has length of \$6\$. Or, if \$n = 11\$, then \$1/n = 1/11 = 0.0909090909090909...\$ Here the length of the pattern is `2`. So, here goes the problem! # Task Given a positive integer \$n\$, \$(n > 1 \text{ and } n < 10000)\$, find the length of pattern in \$1/n\$, if it's repeating. Otherwise, return *any non-positive integer* (e.g., cases: \$1/5, 1/94, 1/22\$). **Note that,** the pattern should start just after the decimal point. Hint: \$1/22 = 0.04545454545454545454545\$. ## Sample I/O * `5 -> -1` * `13 -> 6` * `21 -> 6` * `27 -> 3` * `33 -> 2` * `37 -> 3` * `94 -> -1` * `22 -> -1` * `69 -> 22` * `197 -> 98` * `65 -> -1` * [\$1/9979\$](https://www.wolframalpha.com/input/?i=1%2F9979) * [\$1/9967\$](https://www.wolframalpha.com/input/?i=1%2F9967) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes will win! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` R⁵*%i1 ``` [Try it online!](https://tio.run/##y0rNyan8/z/oUeNWLdVMw/@H2x81rfn/31RHwdBYR8HIEIjNdRSMgWxjIG1pAuQb6SiYWQLlLYECZkCFlpbmliDSzBwA "Jelly – Try It Online") Basically compute `10**[1..n] % n` and get the 1-based index of `1`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 39 bytes Expects a BigInt. Returns \$0\$ if there's no repeating pattern. ``` f=(n,k=1n)=>10n**(k%=n)%n-1n?f(n,-~k):k ``` [Try it online!](https://tio.run/##ddBBDoIwEAXQvafohqQlVpyCpWNSPQtBMFIyNWJcevXqgrqw6frl/z@ZqXt1S/@43Z@S/GUIYbScts4CCXuCPZUld4UlUZAEOo9fk28nji70nhY/D7vZX/nIGWMHEoJVFZOw@TeoV9MJKchTu1KdUB0LVUr5FDb5E5XKm8a4lswBxjk0aS77EsQ2djbamET1rxW1Dh8 "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L.Δ°I% ``` Port of [*@Bubbler*'s Jelly answer](https://codegolf.stackexchange.com/a/214160/52210), so make sure to upvote him! -1 byte thanks to *@ovs*. Outputs `-1` if it's non-repeating. [Try it online](https://tio.run/##yy9OTMpM/f/fR@/clEMbPFX//zcyAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koPCobZKCkn3loZX/ffTOTTm04dA61f@1Ov@jTXUMjXWMDHWMzHWMjXWMzXUsTXSMjHTMLHUMLc11zEx1LC3NLYGEmXksAA) (times out for the final test case). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] .Δ # Find the first value in this list which is truthy for: # (results in -1 if none are found) ° # Take 10 to the power the current integer I% # Modulo the input-integer # (Note: Only 1 is truthy in 05AB1E) # (after which the result is output implicitly as result) ``` [Answer] # [K (ngn/k)](https://git.sr.ht/%7Engn/k), ~~16~~ ~~23~~ 19 bytes ``` {1+(x(x!10*)\10)?1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwNxDEOgCAQBMCeV6yVoA17J1zWxo9Y8wYS4991ihnnwz3PPBfWrdys5eKb0lgb6DDCAu7wgA6YoQtUoDdIob8eH/HTDcM=) As suggested by @traws (returns INT\_MIN+1 if there's no repeating pattern), adapted to work with longer patterns that would otherwise overflow 64-bit integers. * `x(...)\10` set up a monadic-do-scan, run for `x` iterations and seeded with `10` * `(x!10*)` multiply the current value by 10, modding by the original `x` input * `(...)?1` get the index of the first `1` showing up in the result (returns `0N` if no `1` is present, i.e. if there is no repeating pattern) * `1+` add one to that result; converts `0N` to `-9223372036854775807` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` €1m%¹↑İ⁰ ``` [Try it online!](https://tio.run/##AT8AwP9odXNr/23igoH/4oKsMW0lwrnihpHEsOKBsP///1s1LDEzLDIxLDI3LDMzLDM3LDk0LDIyLDY5LDE5Nyw2NV0 "Husk – Try It Online") Same approach as [Bubbler's answer](https://codegolf.stackexchange.com/a/214160/95126). ``` €1m%¹↑İ⁰ €1 # index of first '1' in m # list of results of applying %¹ # MOD n ↑ # to first n elements of İ⁰ # series of powers of 10 (starting at 10) ``` [Answer] # [Perl 5](https://www.perl.org/) (`-p` `-Mbigint`), 31 bytes ``` $_=++$i<$_?9x$i*1%$_?redo:$i:-1 ``` [Try it online!](https://tio.run/##NYzLDoIwEEX3/QpC6gZSSVsYOuBr5c5vIBqJmQSBAAuN8detUOvqnjtzZvp6aDJ7f3IqxyRYR0lSviyvtnHMacOrPT44RXI101Bfu4JTIaR9l7MRHo6B2AW8Cm22gJBM6gWAKekzX1Iz7eaKad8x9QdKeQB0hmISnYOGwf8rYu62KRgzF/gJCPDp@om6drTi3PRWnC50o3b6Ag "Perl 5 – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~20~~ 19 bytes ``` ~:x,{10\?x%1=},0+1= ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v86qQqfa0CDGvkLV0LZWx0Db0Pb/f0NjAA "GolfScript – Try It Online") ``` ~:x # Assign the input to x 13 , # Make an array from 0 to x-1 [0 1 2 3 4 5 6 7 8 9 10 11 12] { }, # Find all numbers that pass this test 10\?x% # (10^k)%x [1 10 9 12 3 4 1 10 9 12 3 4 1] 1= # Is it 1? [1 0 0 0 0 0 1 0 0 0 0 0 1] # Only the index of the 1s are kept [0 6 12] 0+ # Append 0 [0 6 12 0] 1= # Get the second number 6 ``` If it doesn't repeat, the array will be `[0 0]` and `0` will be outputted. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` R⁵*’ḍ@¹TṂȧ@⁸g10¤’¬¤o- ``` [Try it online!](https://tio.run/##y0rNyan8/z/oUeNWrUcNMx/u6HU4tDPk4c6mE8sdHjXuSDc0OLQEKH5ozaEl@br/D7c/alrz/7@pjoKhsY6CkSEQm@soGAPZxkDa0gTIN9JRMLMEylsCBcyACi0tzS1BpJk5AA "Jelly – Try It Online") This is probably very suboptimal (edit yes it is, i don't know why i didn't think to combine the two checks together cuz that would've given Bubbler's algorithm which is pretty smart). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~55~~ 52 bytes Saved 3 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` i;m;f(n){for(i=m=1;(m*=10)%n&&m%n-1;++i);m=m%n?i:0;} ``` [Try it online!](https://tio.run/##XVBNb4QgEL37KyYmbsDF1I/aZktpD01/hXrYKLYcYDfiwdT42@2grumWDAPz3jzgUUdfdT3PimveEkPH9tIRJbRIONGhSGIamMNBByZK@PGoKNcCi3f1EvNpVqYHfVaGUG/0AIcDeml7W1RizBkkGYM0wfnMIMN9huvpEeuUwVM@8V0kh6use9k4XYzcEk685HiNrb/@PnchdEUFAka/HD7Tcjh94Mx9Bn/rzN8U6AmIu0aZRg4oi/m2fQWrfuSlJbcH0IcNCHeEAxp33RRWl7dHGzxpdbvQFb9jLbLuR@9Riehu9r/s2mFLS/yggegNMAe2ND4zzLKusELIajtt8qb5Fw "C (gcc) – Try It Online") Returns either the length of repeated pattern of \$\frac{1}{\space n \space}\$ or \$0\$ for no repeated pattern. [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` f=lambda n,i=1:i*(10**i%n==1)or~(i<n and~f(n,i+1)) ``` [Try it online!](https://tio.run/##DcoxDoAgEATA3ldcYwJIwcWOyGMwiF6iiyE2Nn4dmXru9zkK5tZyOOO1pkiwEtiLUeyMkREhsC71U7KAItKXVR8Ta91yqQQSUI3YN8WWnXPaD3RXwdNbr739 "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~45~~ ~~41~~ 39 bytes ``` n_:>Lookup[Mod[10^#,n]->#&~Array~n,1,0] ``` [Try it online!](https://tio.run/##DcTRCsIgGAbQVxkIo@Bbm9omf5DUfUH3YiGr0YhpiF1EtFe3zsWZXLrfJpfG3uVhm/1low8hPF5PcwxXw5szg7eVZuW8j9G9Zw@OxuZTHH0yrNILVq@GpS2Leld8WnAJwSEUpIRUoDWEQEfgpNC1IFL0r1Pf/AM "Wolfram Language (Mathematica) – Try It Online") Defined as a [delayed rule](https://reference.wolfram.com/language/ref/RuleDelayed.html) that can be applied to any integer. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes ``` 0&@@10~MultiplicativeOrder~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b730DNwcHQoM63NKcksyAHKFiSWZbqX5SSWlSnrPY/oCgzryRaWdcuzUE5Vk1B30Gh2lTH0FjHyFDHyFzH2FjH2FzH0kTHyEjHzFLH0NJcx8xUx9LS3BJImJnX/gcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 68 bytes ``` .+[1379]$ _,$&*_,; \d+ 0 {`; ;_ \G_ 10* +`(_+,)\1 ,$1 ^_,.+;(_+) $.1 ``` [Try it online!](https://tio.run/##DcgxDsIgFIDh/T8HmrYQ0ge2hHCAHkL0YaKDi4Nx8/C03/h9X7/35yH9NGyte3uVmPLNoM6cJ3WF@rTM/FuhKHVTZJ6wbVDrxio4I9zVeVuOGTFeel@QSBBCIkZiIl8IgTUjObEuOw "Retina – Try It Online") Link includes faster test cases. Explanation: ``` .+[1379]$ _,$&*_,; ``` If the number is coprime to `10`, then create a work area with the values `p=1`, `n` and `k=0` (in unary). ``` \d+ 0 ``` But if it is not coprime to `10` then set the answer to `0` immediately. ``` {` ``` Repeat until the answer is found. ``` ; ;_ ``` Increment `k`. ``` \G_ 10* ``` Multiply `p` by `10`. ``` +`(_+,)\1 ,$1 ``` Reduce `p` modulo `n`. ``` ^_,.+;(_+) $.1 ``` If `p=1`, then set the answer to `k` converted to decimal, which allows the loop to exit. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` NθI⊕⌕﹪Xχ…¹θθ¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMzL7koNTc1ryQ1RcMtMy9Fwzc/pTQnXyMgvxyo2NBARyEoMS89VcNQR6FQUxNE6CgYagKB9f//hpbm/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Basically a port of @Bubbler's answer, except that my range goes from `1` to `n-1`. Explanation: ``` Nθ Take input as a number … Exclusive range ¹ From literal `1` θ To input number X Vectorised raise to power χ Predefined variable `10` ﹪ Vectorised reduce modulo θ Input number ⌕ Find index of ¹ Literal `1` ⊕ Increment I Cast to string Implicitly print ``` [Answer] ## Batch, 91 bytes ``` @set/ap=1,k=0 :g @set/ak=-~k%%%1,p=p*10%%%1 @if %k% neq 0 if %p% neq 1 goto g @echo %k% ``` Explanation: Repeatedly increments the answer and multiplies the power by 10 until (modulo the input) the answer wraps around to zero or the power reduces to 1. ]
[Question] [ We all know what a quine is. A quine is a program which prints its own source code. And we also know about the printable ASCII characters. Well... this challenge mixes both. Your mission, should you accept it, is to create an *index quine*. An index quine is a non-empty program, composed only of the printable ASCII characters, which prints its own *index*. The index of a string is its position within an infinite dictionary where all strings composed of exactly the printable ASCII characters appear, sorted by size then ASCII code. The index is a non-negative whole number, assigning 0 to the empty string then continuing with the space, !, " onward. For example, `*!` precedes `**` as the ending `!` in the first string has lower ASCII code than the ending `*` in the second, but both are preceded by `{`, which has a higher ASCII code than the characters of the last two examples, but is shorter. The printed index should be in base 10, outputted through STDOUT or closest equivalent, with no other output unless your language requires trailing newlines/other characters. Also, a bit like actual quines, do not access your source code directly (as a file, etc.) Your program should be non-empty, as a reminder to those reading these rules. If there are multiple programs of shortest length, the tiebreaker is the program with the lower index. The shortest program following these very rules wins. Have fun. [Answer] ## [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 1 byte ``` ``` [Try it online!](https://tio.run/##S0nNLyou@f9f4f9/AA "Deorst – Try It Online") ## [Commentator](https://github.com/cairdcoinheringaahing/Commentator), 1 byte ``` ``` [Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/1/h/38A "Commentator – Try It Online") ## [Snails](https://github.com/feresum/PMA), 1 byte ``` ``` [Try it online!](https://tio.run/##K85LzMwp/v9f4f9/AA "Snails – Try It Online") --- So far, I have found three one-byte solutions, all of which print 1 with a space in the source code. The first two languages were created by [@cairdcoinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing), and the last one by [@feersum](https://codegolf.stackexchange.com/users/30688/feersum). [Answer] # [J](http://jsoftware.com/), 52 bytes ``` echo-95x#.31-3 u:(,quote)'echo-95x#.31-3 u:(,quote)' ``` [Try it online!](https://tio.run/##dctLCsIAEATRqwRcqGBk/t3jdSQgboJgILeP0b1Qu0c9t226P@axcz1cXUcfltvp8lrm93Q@/pffNKRWozTd2WhouESgqZqVaTC2E4gSJpvQvQrREgjMwyuKTIha7RQmtTNo9V3aHUgTrtsH "J – Try It Online") ### How it works ``` echo-95x#.31-3 u:(,quote)'echo-95x#.31-3 u:(,quote)' '...' NB. a string literal (,quote) NB. concatenate self with single-quoted self 3 u: NB. convert to Unicode codepoints 31- NB. subtract from 31 (negation of 1-based index) 95x#. NB. convert from base 95 to integer (using extended integer) - NB. negate echo NB. print with newline ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~39~~ ~~37~~ 33 bytes -2 bytes thanks to @Mukundan ``` hiR95]m-Cd31jN B"hiR95]m-Cd31jN B ``` [Try it online!](https://tio.run/##K6gsyfj/PyMzyNI0NlfXOcXYMMtPwUkJXeD/fwA "Pyth – Try It Online") ``` hiR95]m-Cd31jN B"... "... ( String literal B ( Wrap in an array and duplicate jN ( Join using `"` (this gives us the full source code) m-Cd31 ( For each character, take its codepoint minus 31 ] ( Wrap in an array iR95 ( Map base 95-conversion to that array h ( Take the first (only) element ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~82~~ ~~66~~ 63 bytes -3 bytes thanks to @dingledooper ``` exec(a:='g=0\nfor i in b"exec(a:=%r)"%a:g=g*95+i-31\nprint(g)') ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWPd3WICYvLb9IIVMhM08hSQkmoVqkqaSaaJVum65laaqdqWtsGJNXUJSZV6KRrqmu@f8/AA "Python 3.8 (pre-release) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 471 bytes ``` using System.Numerics;class A{static void Main(){var s="using System.Numerics;Class A{{static void Main(){{var s={0}{1}{0};System.Console.Write(V(string.Format(s,(char)34,s)));}}static BigInteger V(string s){{BigInteger r=0;for(int i=0;i<s.Length;++i)r+=(s[i]-31)*BigInteger.Pow(95,i);return r;}}}}";System.Console.Write(V(string.Format(s,(char)34,s)));}static BigInteger V(string s){BigInteger r=0;for(int i=0;i<s.Length;++i)r+=(s[i]-31)*BigInteger.Pow(95,i);return r;}} ``` [Try it online!](https://tio.run/##tc7BSgMxEAbgVxl6StxtaKkeJO6hLQiCiiDoQTyEGLcD3QRmZiuy5NnXHFb0UDwIvQzDwPfP73nuE4Vx7BljC4@fLKEz930XCD1bv3fMsB5YnKCHQ8I3uHMYlR4OjoCb2XG3ndwxOMlhkYdlLtNOeJsip30wz4QS1JNioRJtrhN1ThTXyu8c6dV5zVprm/MUvcH2JkpoA8G3AS5fft2pWdj3RAqjAJYdr9jchtjKzlYVaqoaxS/4Ol8t9dkPMw/pQ11e1KgtBekpApWvOc/@WfjvvieqO45f "C# (.NET Core) – Try It Online") This is the basic C# quine with the scoring function built in. Is my scoring function a little off? It doesn't quite agree with the Python one linked in the comments. [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 15 bytes ``` "r3lMF`_*+fs-|h ``` [Try it online!](https://tio.run/##S8/PScsszvj/X6nIOMfXLSFeSzutWLcm47@hhaWBkZGxmZmRobmhqYmJkaGxqZmxpZGZuYWF8X8A "Gol><> – Try It Online") An extension from [my own 6-byte quine](https://codegolf.stackexchange.com/a/160994/78410). ### How it works ``` "r3lMF`_*+fs-|h "... Start string ("), push all characters, and end string(") r3 Reverse the stack and push 3 (= 34 - 31) lMF | Loop (stack length - 1) times... `_*+ [... n2 n1] -> [... n2+n1*95] fs- Subtract 31 equivalent to "-31 from each except top and base 95 convert" h Print the top number and halt ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ 65 bytes *-3 bytes thanks to @Mukundan* ``` x="g=0\nfor i in'x=%r;exec x'%x:g=95*g+ord(i)-31\nprint g";exec x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8JWKd3WICYvLb9IIVMhM0@9wla1yDq1IjVZoUJdtcIq3dbSVCtdO78oRSNTU9fYMCavoCgzr0QhXQmq6P9/AA "Python 2 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 724 bytes ``` import java.math.*;class D{public static void main(String[]a0){char q=34;String s="import java.math.*;class D{public static void main(String[]a0){char q=34;String s=;String u=s.substring(0,82)+q+s+q+s.substring(82);BigInteger n=new BigInteger(s.substring(60,61));for(int i=0;i<u.length();)n=n.add(new BigInteger(new Long(95).toString()).pow(i).multiply(new BigInteger(new Long(u.charAt(u.length()-i++-1)-31).toString())));System.out.print(n);}}";String u=s.substring(0,82)+q+s+q+s.substring(82);BigInteger n=new BigInteger(s.substring(60,61));for(int i=0;i<u.length();)n=n.add(new BigInteger(new Long(95).toString()).pow(i).multiply(new BigInteger(new Long(u.charAt(u.length()-i++-1)-31).toString())));System.out.print(n);}} ``` [Try it online!](https://tio.run/##7ZBNT8MwDIb/SrRTTNeoZTCBQg8gLkjcdkQcsra0Lm2SNc6madpvLykT2obgxpGDZfuR/fqjUWsVG1vqpngfBuys6Yk1AYpOUS0uZN4q59jjzvplizlzpCi4tcGCdQo1X1CPunp5VQns8lr1bJXNruSBMpdN/l7yK/KZE84v3WfGk@nNJUSryI12wgOVD1g9aSqrsmc60@WGHQE/rZ0n03kKIN9Mz1ETwyyReOdFW@qKag4SQrtQRcG/iYzpswkKt9cgyBwW5ADCmg1HEJ1vCW27/bXPi/HQe@LHYTFGUZxCPEvPJMN6i62jshPGk7CBEtcg9/vJ/19@/MswfAA "Java (OpenJDK 8) – Try It Online") [Answer] # [R](https://www.r-project.org/) + GMP, ~~156~~ 116 bytes or [126 bytes](https://tio.run/##pY/LboMwEEXX@CsQEdK4gTYUISUgd999uqrayDGGmIdN7aGqivh26n2WXcxi7jzuuXbTbNmi9IVXyGZsjmfzqhE4TfOscvMI7TiVJXePV9X@wqmgn5A9F@WBPgjIE0x8UfrP820lmuxCcZOiL4lDq3R7aawZL0rX8oc1sxaojAZFFxLUTEg1@BUYTAtqnyVX7iTzvykJHPuWAo2FSNy45QKljbzceKULlQ6d/IKaphkNl57dsXWVe6/T7oMpjWfz5uOAH/tGttKCip/iPo5PxT7PKF1JMHGH8gAuEWYY@OQhIm@2EsER7lKA9nzbHw) in R ``` "->a;t=utf8ToInt(a)-31;sum(as.bigz(95)^(115:0)*c(3,t,3,t))"->a;t=utf8ToInt(a)-31;sum(as.bigz(95)^(115:0)*c(3,t,3,t)) ``` [Try it online!](https://tio.run/##nY9PT4QwEMXP9FMQDMmMC7qEkLhL6t37ejK6KaWw5U@LbTEq4bNjvZnszcMc5uXNvN8z2yArw8wXtOOERNFli9JHVjo6u@bhpJ@UA4ZpnpV2HoHZu0q233Ao8A2yrDju8ZZDnrjED@L/L7eVKHIT8ovg/ZFYZ6Rqz43R41mqWnzSZlbcSa1A4kKCmnIhB2@BQbcgd1lSMSuo/40ksPRDcKcNRPzCDONOmMjLjVe6UKrQineoMc0wXHr6F6sr7Uuddq9UKnfSz77EL7VfRCsMyPg@7uP4UOzyDHElwcSsE3uwCdfDwCafH/mclXDm4KoAKI@2/QA "R – Try It Online") *Edit: Big improvement by re-arranging to start immedidately with quoted string, which really simplifies the re-construction of the full program text.* ~~This seems horribly uncompetitive, but I don't seem to be able to do any better, I'm afraid.~~ The enormously-verbose `utf8ToInt()` function name isn't really helping much. [Answer] # [Stax](https://github.com/tomtheisen/stax), 34 bytes 1-byte difference with Pyth, since I can't get rid of the prepending quote in Stax. ``` "c34|Ss+{31-m95|E"c34|Ss+{31-m95|E ``` [Try it online!](https://tio.run/##Ky5JrPj/XynZ2KQmuFi72thQN9fStMYVQ@D/fwA "Stax – Try It Online") ## Explanation ``` "..." The second half of the program c Copy this operand 34|S Surround it with quotes s+ Prepend the quoted string with the original string { m Map: (Since direct - removes items) 31- Codepoint - 31 (Stax strings consist of codepoints) 95|E Convert from base 95 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 bytes ``` 0|?F31-s94*+ ``` [Run and debug it](https://staxlang.xyz/#c=0%7C%3FF32-s94*%2B&i=) Note that this uses the `|?` program source operand, which may be cheating ``` 0 # Push a zero to the stack |? # Return program's source as a string F # for each character (as an ascii value)... 31- # subtract 31 from the character's value s # get the running total 94* # multiply it by 94 + # add the character's value ``` [Answer] # [Perl 5](https://www.perl.org/) + `-Mbigint -M5.10.0`, 71 bytes ``` $_=q($n+=(95**(70-$-++))*(-31+ord)for"\$_=q($_);eval"=~/./g;say$n);eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rZQQyVP21bD0lRLS8PcQFdFV1tbU1NLQ9fYUDu/KEUzLb9IKQaiLF7TOrUsMUfJtk5fTz/dujixUiUPIvT//7/8gpLM/Lzi/7q@SZnpmXklQIapnqGBngEA "Perl 5 – Try It Online") ]
[Question] [ The Seidel Triangle is a mathematical construction similar to Pascal's Triangle, and is known for it's connection to the Bernoulli numbers. The first few rows are: ``` 1 1 1 2 2 1 2 4 5 5 16 16 14 10 5 16 32 46 56 61 61 ``` Each row is generated as follows: If the row number is even (1-indexed): * Bring down the first item of the previous row * Every next item is the sum of the previous item and the item above it * Duplicate the last item If the row number is odd: * Bring down the last item of the previous row * Going *backwards*, each item is the sum of the previous item and the item above it * Duplicate what is now the first item. Basically, we construct the triangle in a zig-zag pattern: ``` 1 v 1 > 1 v 2 < 2 < 1 v 2 > 4 > 5 > 5 ``` For more information, see [the Wikipedia page](https://en.wikipedia.org/wiki/Bernoulli_number#An_algorithmic_view:_the_Seidel_triangle) on Bernoulli numbers. ### The Challenge: Given `n`, either as a function argument or from STDIN, print or return either the `n`th row of the Seidel triangle or the first `n` rows. You may use either 0 or 1 indexing. You do not need to handle negative or non-integer input (nor 0, if 1-indexed). You do not have to handle outputs larger than `2147483647 = 2^31 - 1` As this is code-golf, do this in as few bytes as possible. ### Examples: In these examples the return value is the `n`th row, 0-indexed. ``` Input -> Output 0 1 1 1 1 2 2 2 1 6 272 272 256 224 178 122 61 13 22368256 44736512 66750976 88057856 108311296 127181312 144361456 159575936 172585936 183194912 191252686 196658216 199360981 199360981 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 66 bytes ``` <>(())<>{({}[()]<(()[{}]<<>{(({}<>{}))<>}>)>)}{}{{}<>{({}<>)<>}}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/38ZOQ0NT08auWqO6NlpDM9YGyI2uro21AQkBxYBULUi@1k7TTrO2urYaLASWAIkCqf//DY0B "Brain-Flak – Try It Online") Row is 0-indexed. ``` # Push 1 (the contents of row 0) on other stack; use implicit zero as parity of current row <>(())<> # Do a number of times equal to input: {({}[()]< # Subtract the row parity from 1 (()[{}]< # For each entry in old row: <>{ # Add to previous entry in new row and push twice (({}<>{}))<> } >) >)}{} # If row parity is odd: {{} # Reverse stack for output <>{({}<>)<>} # Switch stacks for output }<> ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 67 bytes This code abuses the `sort()` method and doesn't work on all engines. Rows are 0-indexed. ``` f=(n,a=[1],r)=>n--?f(n,[...a.map(n=>k+=n,k=0),k].sort(_=>n|r),!r):a ``` [Try it online!](https://tio.run/##DYxBCoMwEADvvmJ7MosxKL3Vrn2ISAlWi0Z3JZFCafv2NLdhGGaxLxsGP@9HGfb5MfpN2I3vGCdSrC11da89UstleZuS6Ywx1mx2V0ytK4i1owq1600Qf6h7Kr8e9cnjxcZJvGIgqBpguBLU5wRFgfDJAAbhIOtoVnmmL6Q5mkVmVrnOEZvsF/8 "JavaScript (SpiderMonkey) – Try It Online") ### How? We conditionally reverse an array by using the `sort()` method with a callback function that ignores its parameters and returns either **0** or a positive integer. *Don't try this at home!* This only works reliably on SpiderMonkey. ``` let A = [1,2,3,4,5] and B = [1,2,3,4,5,6,7,8,9,10,11] | SpiderMonkey (Firefox) | V8 (Chrome) | Chakra (Edge) -------------+-------------------------+-------------------------+------------------------ A.sort(_=>0) | 1,2,3,4,5 | 1,2,3,4,5 | 1,2,3,4,5 A.sort(_=>1) | 5,4,3,2,1 | 5,4,3,2,1 | 1,2,3,4,5 B.sort(_=>0) | 1,2,3,4,5,6,7,8,9,10,11 | 6,1,3,4,5,2,7,8,9,10,11 | 1,2,3,4,5,6,7,8,9,10,11 B.sort(_=>1) | 11,10,9,8,7,6,5,4,3,2,1 | 6,11,1,10,9,8,7,2,5,4,3 | 1,2,3,4,5,6,7,8,9,10,11 ``` Note that V8 is probably using different sort algorithms depending on the length of the array (less or more than 10 elements). ### Commented ``` f = ( // f = recursive function taking: n, // n = row counter a = [1], // a[] = current row, initialized to [1] r // r = 'reverse' flag, initially undefined ) => // n-- ? // decrement n; if it was not equal to zero: f( // do a recursive call with: n, // - the updated value of n [ ...a.map(n => // - a new array: k += n, k = 0 // - made of the cumulative sum of a[] ), k // with the last value appended twice ].sort(_ => n | r), // - reversed if n is not equal to 0 or r is set !r // - the updated flag r ) // end of recursive call : // else: a // stop recursion and return a[] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes ``` {(1,{[[\+] |.reverse,0]}...*)[$_].sort((-1)**$_*-*)} ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr@xBQjdbEqJL9BIz6aCnolgjEOvtNnMF3sd6ZGgizLVIo4u1S@vgJQ5P4BR07z4iQmWFd5ROvqXsjEIUHjtUX01bhiiFVxBPhtUMU/0B "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` 1;0SƤUƊ⁸¡U⁸¡ ``` [Try it online!](https://tio.run/##y0rNyan8/9/Q2iD42JLQY12PGnccWhgKJv///28CAA "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~98~~ 91 bytes ``` from itertools import* f=lambda n:n and[*accumulate(f(n-1)[::n&1or-1]+[0])][::n&1or-1]or[1] ``` [Try it online!](https://tio.run/##TcyxCsIwEADQvV9xkyS1hQYHIeCXhAxnm2gguSvX6@DXR0fXN7z9o2@mW@9ZuEHRJMpcDyhtZ9FxyI@K7bkhkCdA2sKI63q2s6Imkw3Nzgbv6eJYZhevYYk2/gFLcLFnFiAoBIL0SmaZ7tYPALBLITU0wS@ytn8B "Python 3 – Try It Online") Switching to 0-based row numbering saved 7 bytes. [Answer] # [Haskell](https://www.haskell.org/), ~~89~~ ~~87~~ 82 bytes ``` (cycle[r,id]!!)<*>s r=reverse s 0=[1] s n=let a=zipWith(+)(0:a)$(r.s$n-1)++[0]in a ``` Just `s` prints the lines in the zig-zag order, the anonymous function on the first row reverses half of the rows. Thanks to @nimi for saving 5 bytes! [Try it online!](https://tio.run/##DcUxDsIgFADQvaf4TTqAWAKrEW/g7IDE/ABaUkoIEBM9vNi3vAXr6mPsDhTcO7EfG70ux@DMONLz4VKHoop/@1L9UEEoLc1@UtE3QPUN@RbaQhgl4oR0IoXXKc2SMqaFCQmwb7inYMN8fQDJJaQGHBwFLTmX0vSffUZ81T7bnP8 "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ 97 bytes ``` f=lambda n,r=[1],k=2:n and f(n-1,[sum(r[-2::-1][:i],r[-1])for i in range(k)],k+1)or r[::-(-1)**k] ``` [Try it online!](https://tio.run/##XYsxDsMgDADn5hUecQqDUSckXoIYqFJai8aJnHTo6ylzxzvd7d/ztYnvvcZ3We9LAbEaE2Xbog8CRRaoRhzZdHxWo8n5EBzlFDjbQZSxbgoMLKBFng/TcLxXwmE1jdY4wnluuf91dMMwXXZlOYFtNYxT/wE "Python 2 – Try It Online") Non-recursive version (easier to read): # [Python 2](https://docs.python.org/2/), 106 bytes ``` def f(n,r=[1],j=1): while n: a=r[-2::-1];r=r[-1:];n-=1;j=-j for x in a+[0]:r+=[r[-1]+x] return r[::-j] ``` [Try it online!](https://tio.run/##Fc1BCsMgEIXhtZ5ilgYVaujK4ElkFkK1UcokDAlNT2/j7i2@x7//jnWjufdXLlAUGQ7RoWnBTV7Cd62fDOSlSIGjnb23Dhce23lcyAa3tGCbFGVjuKASJB0f6FmHOBDqCyVwPk4m4Hj/G/Zh67Cc6J2Ve94psXOlA6opqk6y/wE "Python 2 – Try It Online") Surely, better is possible! [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` from numpy import * s=lambda n:n and cumsum(s(n-1)[::n%2*2-1]+[0]).tolist()[::n%2*2-1]or[1] ``` [Try it online!](https://tio.run/##TcyxDsIgFAXQvV/xFhOo1kh1IvFLCANaqyTlPvKAoV@Pjs4nOXmvH8a191U4EVrKO8WUWSqNQ7lvIT2WQLCggIWeLZWWVFGYjHbW4jCP82T80V28PlfeYqnqH1ic8X1lIVAEScD7pcxN24EoS0RVOP02rfsX "Python 3 – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 85 bytes ``` r(l,n=cumsum(l))=[n...,n[end]] w=reverse f(n)=n<2?[1]:n%2<1?r(f(n-1)):w(r(w(f(n-1)))) ``` [Try it online!](https://tio.run/##XY3RasQgEEXf9yvyUlCwITM6oy4r@yEhD6VNYUtWFrdpPj/VNGmbhUGu557Rj3G4vPA8JzGoGF7H6328ikHK0Ma6rlVs@/jWdYcppP6rT/f@8C6iDPGE5xa6Y3zCE5yTyPAZpDxOIolpu0k539Ilfg4xE5BVCFXekYc/iCtUe6x/MCp8KMxWGEWKdhWtT7EqYxQ0DwL/CjrvsyJWDHl2Emw/oGaHWamMsZoJUFXMlhpvM3OuIetKC43TAOhLRAsOdDHBGM1gFoE8WfK6RIvk1pi3vPGLm09CdoV6ZnIIS8xe4x38i52cvwE "Julia 0.6 – Try It Online") This is a recursive solution in Julia. Note that it has 1-based indexing. Hence the tests. Ungolfed version, to understand the logic: ``` function new_row(last_row) new_row = cumsum(last_row) push!(new_row, new_row[end]) return new_row end function triangle(n) if n == 1 return [1] elseif mod(n,2) == 0 return new_row(triangle(n-1)) else return reverse(new_row(reverse(triangle(n-1)))) end end ``` Asa bonus, here's a non-recursive version, but this is longer: ``` w=reverse;c=cumsum r(l,i)=i%2<1?c([l...,0]):w(c(w([0,l...]))) f(n,l=[1])=(for i=2:n l=r(l,i)end;l) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` !z*:1İ_¡ȯ↔S:→∫;1 ``` [Try it online!](https://tio.run/##ASQA2/9odXNr//8heio6McSwX8KhyK/ihpRTOuKGkuKIqzsx////MTM "Husk – Try It Online") There may be a better way for arriving at the rows in the correct order. To get the correct output, this program reverses every other row. ## Explanation ``` !z*:1İ_¡ȯ↔S:→∫;1 ;1 array [1] ¡ȯ apply the following functions repeatedly on it, collecting results: ∫ cumulative sum S:→ repeat the last element ↔ reverse it this generates all the required rows z* zip multiply that with: :1İ_ [1,-1,1,-1,1,-1,...] which reverses every other row ! Get row at input index ``` # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ?I↔%2¹!¡ȯ↔S:→∫;1 ``` [Try it online!](https://tio.run/##yygtzv7/397zUdsUVaNDOxUPLTyxHsgOtnrUNulRx2prw////xsaAwA "Husk – Try It Online") Uses a ternary instead. [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` (k!!)<*>(iterate(r.scanr1(+).(0:))[1]!!) r=reverse k=r:id:k ``` [Try it online!](https://tio.run/##DcpBDsIgEADAO6/Y3haNpL14IOIPfEFtzIYuSmiRLMTni855XlQTb1sP7t4xDYO@HK4YGws1RjHVU5YJj9rgaLWep@VflDjhD0tllZzYuNrUd4oZHKxvBbBTuT0Ai8TcTNAwj8acl/71YaNn7Sdfyg8 "Haskell – Try It Online") [Answer] # [k4](https://code.kx.com/q/ref/), 17 bytes ``` {x|:/x{|+\x,0}/1} ``` Adapted from @razetime's APL answer. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22~~ 18 bytes ``` {⊖⍣⍵{⌽+\⍵,0}⍣⍵,1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR17RHvYsf9W6tftSzVzsGyNAxqIWI6BjWKvxPe9Q24VFv36Ou5ke9ax71bjm03vhR28RHfVODg5yBZIiHZ/D/NAVTAA "APL (Dyalog Unicode) – Try It Online") Same method as my Husk answer. -4 bytes from coltim. ## Explanation ``` {⊖⍣⍵{⌽(⊢,⊢/)+\⍵}⍣⍵,1} ⍵ ← input(n) ,1 convert 1 to an array [1] { }⍣⍵ apply the following n times: +\⍵ cumulative sum (⊢,⊢/) duplicate the last element ⌽ reverse ⊖⍣⍵ then reverse n times ``` ]
[Question] [ **Sequence:** 1. We start at `1`. 2. We first add the current 1-indexed value to the previous number in the sequence. 3. Then we apply the following mathematical operations in order if they apply to this current value: * Divisible by `2`? => Addition * Divisible by `3`? => Subtraction * Divisible by `4`? => (Addition AND) Multiply * Not divisible by neither `2`, `3` nor `4`? -> Continue with current sum-result **Output:** Output the first 100 numbers in this sequence: ``` 1, 1, 21, 25, 30, 216, 223, 223, 2169, 2179, 2190, 2202, 2215, 2215, 2245, 2261, 2295, 2295, 2333, 2353, 2395, 2417, 56649, 56649, 56699, 56725, 1533033, 1533061, 1533090, 45993600, 45993631, 45993631, 1517792001, 1517792035, 1517792070, 1517792106, 1517792143, 1517792143, 1517792221, 1517792261, 1517792343, 1517792343, 1517792429, 1517792473, 1517792563, 1517792609, 71336257041, 71336257041, 71336257139, 71336257189, 3638149121841, 3638149121893, 3638149121946, 196460052588000, 196460052588055, 196460052588055, 11198222997525633, 11198222997525691, 11198222997525750, 11198222997525810, 11198222997525871, 11198222997525871, 11198222997525997, 11198222997526061, 11198222997526191, 11198222997526191, 11198222997526325, 11198222997526393, 11198222997526531, 11198222997526601, 795073832824398753, 795073832824398753, 795073832824398899, 795073832824398973, 59630537461829934225, 59630537461829934301, 59630537461829934378, 4651181922022734887568, 4651181922022734887647, 4651181922022734887647, 376745735683841525912529, 376745735683841525912611, 376745735683841525912694, 376745735683841525912778, 376745735683841525912863, 376745735683841525912863, 376745735683841525913037, 376745735683841525913125, 376745735683841525913303, 376745735683841525913303, 376745735683841525913485, 376745735683841525913577, 376745735683841525913763, 376745735683841525913857, 35790844889964944961834465, 35790844889964944961834465, 35790844889964944961834659, 35790844889964944961834757, 3543293644106529551221660545, 3543293644106529551221660645 ``` **Here are the first 10 numbers in the sequence with explanation:** ``` // Starting number of the sequence: 1 // 1 (previous number in the sequence) // + 2 (current index in 1-indexed sequence) // = 3 -> 3 - 2 (3 is divisible by 3, so we subtract the current index 2) // = 1 1 // 1 (previous number in the sequence) // + 3 (current index in 1-indexed sequence) // = 4 -> 4 + 3 (4 is divisible by 2, so we first add the current index 3) // = 7 -> 7 * 3 (and 4 is also divisible by 4, so we then also multiply the current index 3) // = 21 21 // 21 (previous number in the sequence) // + 4 (current index in 1-indexed sequence) // = 25 (25 is not divisible by 2, 3 nor 4) 25 // 25 (previous number in the sequence) // + 5 (current index in 1-indexed sequence) // = 30 -> 30 + 5 (30 is divisible by 2, so we first add the current index 5) // = 35 -> 35 - 5 (and 30 is also divisible by 3, so we then also subtract the current index 5) // = 30 30 // 30 (previous number in the sequence) // + 6 (current index in 1-indexed sequence) // = 36 -> 36 + 6 (36 is divisible by 2, so we first add the current index 6) // = 42 -> 42 - 6 (and 36 is also divisible by 3, so we then also subtract the current index 6) // = 36 -> 36 * 6 (and 36 is also divisible by 4, so we then also multiply the current index 6) // = 216 216 // 216 (previous number in the sequence) // + 7 (current index in 1-indexed sequence) // = 223 (223 is not divisible by 2, 3 nor 4) 223 // 223 (previous number in the sequence) // + 8 (current index in 1-indexed sequence) // = 231 -> 231 - 8 (231 is divisible by 3, so we subtract the current index 8) // = 223 223 // 223 (previous number in the sequence) // + 9 (current index in 1-indexed sequence) // = 232 -> 232 + 9 (232 is divisible by 2, so we first add the current index 9) // = 241 -> 241 * 9 (and 232 is also divisible by 4, so we then also multiply the current index 9) // = 2169 2169 // 2169 (previous number in the sequence) // + 10 (current index in 1-indexed sequence) // 2179 (2179 is not divisible by 2, 3 nor 4) 2179 ``` **Challenge rules:** * If your language doesn't support anything bigger than 231-1, you can continue the sequence until that max (so the first 46 numbers, up until - and including - `1,517,792,609`). * The output format is flexible. You can return an array or list, a string separated with spaces, commas, etc. Your call. **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](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](http://meta.codegolf.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. [Answer] # R, ~~85~~ ~~82~~ ~~79~~ ~~76~~ ~~72~~ 70 bytes ``` for(i in 2:56)T[i]=((z=i+T[i-1])+i*(!z%%2)-i*(!z%%3))*`if`(z%%4,1,i);T ``` ungolfed: ``` s=1 ## formerly s=1:56, formerly s=1:100 for(i in 2:56){ z=i+s[i-1] s[i]=(z+i*(z%%2<1)-i*(z%%3<1))*(1+(i-1)*(z%%4<1)) } s ``` Thanks to @rturnbull for pointing out that I can use `(!z%%3)` instead of `(z%%3<1)` to check the moduli, and that the definition of `z` an happen when it is first used. Golfed away 3-4 chars by abusing vector extension: the answer originally started `s=1:56...` but we don't need to do that, the length of `s` will be extended as needed. Saved 3 more bytes by replacing the last condition with a call to the `"if"` function (yes, it's a proper function in R!) Saved 4 more bytes by replacing `s` with `T`, which is a builtin equal to `TRUE` which is also equal to `1`. I realised it at the same time as @rturnbull (honest!) This does suffer from some numerical issues once we exceed 2^52, but there is nothing I can do about that --- R can only use `double` types for numbers larger than `2^31-1`, but they store integers up to 2^52 exactly. Thus, I am allowed to only output the first 56 terms (the last term which is "right") which saves one byte over the 100-length case. Here's the output from the 56-length version: ``` > for(i in 2:56){z=i+T[i-1];T[i]=(z+i*(!z%%2)-i*(!z%%3))*`if`(z%%4,1,i)};T [1] 1 1 21 25 30 216 [7] 223 223 2169 2179 2190 2202 [13] 2215 2215 2245 2261 2295 2295 [19] 2333 2353 2395 2417 56649 56649 [25] 56699 56725 1533033 1533061 1533090 45993600 [31] 45993631 45993631 1517792001 1517792035 1517792070 1517792106 [37] 1517792143 1517792143 1517792221 1517792261 1517792343 1517792343 [43] 1517792429 1517792473 1517792563 1517792609 71336257041 71336257041 [49] 71336257139 71336257189 3638149121841 3638149121893 3638149121946 196460052588000 [55] 196460052588055 196460052588055 ``` [Answer] # Python 3, ~~82~~ ~~78~~ ~~76~~ ~~74~~ 72 bytes ``` i=s=1 exec('print(s);i+=1;s+=i;s=(s+i-i*(s%2+(s%3<1)))*i**(s%4<1);'*100) ``` Output: ``` 1 1 21 25 30 216 223 223 2169 2179 2190 2202 2215 2215 2245 2261 2295 2295 2333 2353 2395 2417 56649 56649 56699 56725 1533033 1533061 1533090 45993600 45993631 45993631 1517792001 1517792035 1517792070 1517792106 1517792143 1517792143 1517792221 1517792261 1517792343 1517792343 1517792429 1517792473 1517792563 1517792609 71336257041 71336257041 71336257139 71336257189 3638149121841 3638149121893 3638149121946 196460052588000 196460052588055 196460052588055 11198222997525633 11198222997525691 11198222997525750 11198222997525810 11198222997525871 11198222997525871 11198222997525997 11198222997526061 11198222997526191 11198222997526191 11198222997526325 11198222997526393 11198222997526531 11198222997526601 795073832824398753 795073832824398753 795073832824398899 795073832824398973 59630537461829934225 59630537461829934301 59630537461829934378 4651181922022734887568 4651181922022734887647 4651181922022734887647 376745735683841525912529 376745735683841525912611 376745735683841525912694 376745735683841525912778 376745735683841525912863 376745735683841525912863 376745735683841525913037 376745735683841525913125 376745735683841525913303 376745735683841525913303 376745735683841525913485 376745735683841525913577 376745735683841525913763 376745735683841525913857 35790844889964944961834465 35790844889964944961834465 35790844889964944961834659 35790844889964944961834757 3543293644106529551221660545 3543293644106529551221660645 ``` Suggestions are welcome! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~34~~ ~~31~~ 30 bytes ``` XTnFD,NÌ©+D3L>%_`X®‚sèrŠs-®*+* ``` [Try it online!](http://05ab1e.tryitonline.net/#code=WFRuRkQsTsOMwqkrRDNMPiVfYFjCruKAmnPDqHLFoHMtwq4qKyo&input=) **Explanation** ``` X # initialize stack with 1 TnF # for N in [0 ... 99] D, # print a copy of top of stack NÌ© # increase index N by 2 and store in register + # add this to current value D # make a copy of the current value 3L> # push the list [2,3,4] % # take current value mod elements in list _ # invert this ` # push the elements from the list to stack X®‚sè # index into list [1,N+2] with the result of mod 4 rŠs- # subtract result of mod 3 from result of mod 2 ®* # multiply by N+2 + # add this to current value * # multiply current value with the result from index operation ``` [Answer] # Python 2, 76 Bytes Pretty standard implementation, I think using an exec statement rather than a while loop saved 2 bytes or so. A recursive method may be shorter, I imagine xnor will pop up soon ;) ``` n=1 f=1 exec'print f;n+=1;d=f+n;f=(d+n*(d%2<1)-n*(d%3<1))*[1,n][d%4<1];'*100 ``` If I used the updates that TheNumberOne figured out, I would be at 69 bytes (but then I would be copying) ``` n=f=1;exec'print f;n+=1;d=f+n;f=(d+n-n*(d%2+(d%3<1))*n**(d%4<1);'*100 ``` Output: ``` 1 1 21 25 30 216 223 223 2169 2179 2190 2202 2215 2215 2245 2261 2295 2295 2333 2353 2395 2417 56649 56649 56699 56725 1533033 1533061 1533090 45993600 45993631 45993631 1517792001 1517792035 1517792070 1517792106 1517792143 1517792143 1517792221 1517792261 1517792343 1517792343 1517792429 1517792473 1517792563 1517792609 71336257041 71336257041 71336257139 71336257189 3638149121841 3638149121893 3638149121946 196460052588000 196460052588055 196460052588055 11198222997525633 11198222997525691 11198222997525750 11198222997525810 11198222997525871 11198222997525871 11198222997525997 11198222997526061 11198222997526191 11198222997526191 11198222997526325 11198222997526393 11198222997526531 11198222997526601 795073832824398753 795073832824398753 795073832824398899 795073832824398973 59630537461829934225 59630537461829934301 59630537461829934378 4651181922022734887568 4651181922022734887647 4651181922022734887647 376745735683841525912529 376745735683841525912611 376745735683841525912694 376745735683841525912778 376745735683841525912863 376745735683841525912863 376745735683841525913037 376745735683841525913125 376745735683841525913303 376745735683841525913303 376745735683841525913485 376745735683841525913577 376745735683841525913763 376745735683841525913857 35790844889964944961834465 35790844889964944961834465 35790844889964944961834659 35790844889964944961834757 3543293644106529551221660545 3543293644106529551221660645 ``` [Answer] # JavaScript, ~~75~~ 63 bytes ``` for(n=p=0;n++<57;alert(p=p%4?q:q*n))q=(p+=n)%2?p:p+n,q-=p%3?0:n ``` Another version: ``` for(n=p=0;n++<57;)alert(p=((p+=n)+(!(p%2)-!(p%3))*n)*(p%4?1:n)) ``` Both stop at index 57 (0-indexed) because that's when the output surpasses JavaScript's safe number size (253 - 1). Turns out a loop is way shorter than a recursive function, even with ES6: ``` f=(n=0,p=0)=>n++>56?[]:(q=(p+=n)%2?p:p+n,q-=p%3?0:n,[q*=p%4?1:n,...f(n,q)]) ``` This one returns an array of the first 57 elements. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~476 466 462 456~~ 446 Bytes Saved 6 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) ``` (((((((())<>()(())()){}){}){}())){}{}){({}[()]<(((({})<>({}())<>))<({}(()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}({}<>({})<>)>)}{}>)(({})<({}(()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}({}<>[({})]<>)>)}{}>)({}(()()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}(<>({}))({<({}[()])><>({})<>}{}<><{}>)>)}{}>)}{} ``` [Try it Online!](http://brain-flak.tryitonline.net/#code=IygoKCgoKCgoKSgpKTw-KCgpKSgpKXt9KXt9KXt9KCkpKXt9e30pICAjVElPIGNhbid0IGhhbmRsZSBhbGwgMTAwIG51bWJlcnMKKCgoKCgoKSgpKTw-KCgpKSl7fSkpe317fSgpKSAgICAgICAgICAgICAjaW5zdGVhZCB3ZSdsbCBqdXN0IGxvb2sgYXQgdGhlIGZpcnN0IDIwCgp7KHt9WygpXTwoKCgoe30pPD4oe30oKSk8PikpPCh7fSgoKSgpKSg8KCk-KSl7KHt9WygpXTwoKHt9KClbKHt9KV0pKXt7fSg8KHt9KHt9KSk-KX17fT4pfSh7fXt9PHt9KCgpKT4peygoPHt9e30-KSl9e317KDx7fSh7fTw-KHt9KTw-KT4pfXt9PikoKHt9KTwoe30oKCkoKSgpKSg8KCk-KSl7KHt9WygpXTwoKHt9KClbKHt9KV0pKXt7fSg8KHt9KHt9KSk-KX17fT4pfSh7fXt9PHt9KCgpKT4peygoPHt9e30-KSl9e317KDx7fSh7fTw-Wyh7fSldPD4pPil9e30-KSh7fSgoKSgpKCkoKSkoPCgpPikpeyh7fVsoKV08KCh7fSgpWyh7fSldKSl7e30oPCh7fSh7fSkpPil9e30-KX0oe317fTx7fSgoKSk-KXsoKDx7fXt9PikpfXt9eyg8e30oPD4oe30pKSh7PCh7fVsoKV0pPjw-KHt9KTw-fXt9PD48e30-KT4pfXt9Pil9e30&input=&debug=on) This is really slow. TIO can't handle the whole 100 numbers (the limit seems to be 22 or 23). So, this example only generates the first 20, but the code would work for 100 as well. **Brief Explanation:** ``` (())<> # push a 1 (the index) and switch stacks (()) # then push a 1 (the starting number) (((((( ()()){}){}){}())){}{}) # and a 99 (a counter so that we only print the # first 100 numbers) # repeat until the counter is 0 { # pop the counter and push it minus 1 after: ({}[()]< # hold onto the current number plus the index (leave a copy on the stack to be printed) # and increment the index (((({})<>({}())<>))< # push logical not of (current mod 2) ({}(()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{} # if !(current mod 2) is 1, add the index {(<{}({}<>({})<>)>)}{} # push the current number back on >) # hold onto the current number (({})< # push logical not of (current mod 3) ({}(()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{} # if !(current mod 3) is 1, then subtract the index {(<{}({}<>[({})]<>)>)}{} # push the current number back on >) # push logical not of (current mod 4) ({}(()()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{} # if !(current mod 4) is 1, multiply by the index {(<{}(<>({}))({<({}[()])><>({})<>}{}<><{}>)>)}{} # put the counter back on >) # loop until done } # pop the counter {} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 23 bytes *-1 byte thanks to Kevin Crujissen* ``` ¼¾тF=¼¾+©…+-*v®NÌÖi¾y.V ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0J5D@y42udmCaO1DKx81LNPW1So7tM7vcM/haZmH9lXqhf3/DwA "05AB1E – Try It Online") Explanation: ``` ¼¾ # set the counter to 1, then push 1 тF # repeat the following 100 times = # print the current number in the sequence ¼¾ # increment the counter + # add it to the current number © # save the result in the register …+-*v # for each of '+', '-', and '*'... ® i # if the register... Ö # is divisible by... NÌ # the loop index + 2... ¾y.V # then apply the current operation ``` [Answer] # Java 7, 316 bytes ``` import java.math.*;String c(){String r="";BigInteger t=BigInteger.ONE,x,p;for(int i=2;i<102;){r+=t+" ";p=(t=t.add(x=new BigInteger(i+++"")));t=x(p,2)?t.add(x):t;t=x(p,3)?t.subtract(x):t;t=x(p,4)?t.multiply(x):t;}return r;}boolean x(BigInteger p,int i){return p.mod(new BigInteger(i+"")).compareTo(BigInteger.ONE)<0;} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/aEQzgk) ``` import java.math.*; class M{ static String c(){ String r = ""; BigInteger t = BigInteger.ONE, x, p; for(int i = 2; i < 102;){ r += t+" "; p = (t = t.add(x = new BigInteger(i++ + ""))); t = x(p, 2) ? t.add(x) : t; t = x(p, 3) ? t.subtract(x) : t; t = x(p, 4) ? t.multiply(x) : t; } return r; } public static void main(String[] a){ System.out.println(c()); } static boolean x(BigInteger p, int i){ return p.mod(new BigInteger(i+"")).compareTo(BigInteger.ONE) < 0; } } ``` **Output:** ``` 1 1 21 25 30 216 223 223 2169 2179 2190 2202 2215 2215 2245 2261 2295 2295 2333 2353 2395 2417 56649 56649 56699 56725 1533033 1533061 1533090 45993600 45993631 45993631 1517792001 1517792035 1517792070 1517792106 1517792143 1517792143 1517792221 1517792261 1517792343 1517792343 1517792429 1517792473 1517792563 1517792609 71336257041 3424140340272 3424140340321 3424140340371 3424140340473 3424140340525 3424140340631 3424140340631 3424140340741 3424140340797 3424140340911 3424140340969 202024280124133 202024280124193 202024280124315 202024280124377 12727529647843689 814561897462000192 52946523335030016705 52946523335030016771 52946523335030016905 52946523335030016973 52946523335030017111 52946523335030017111 52946523335030017253 52946523335030017253 52946523335030017399 52946523335030017473 3970989250127251321725 301795183009671100456876 301795183009671100456953 301795183009671100457031 301795183009671100457110 301795183009671100457270 301795183009671100457351 301795183009671100457433 25049000189802701337980717 25049000189802701337980801 25049000189802701337980971 25049000189802701337981057 2179263016512835016404367097 191775145453129481443584312280 17067987945328523848479003800841 1536118915079567146363110342083790 1536118915079567146363110342083790 1536118915079567146363110342083974 1536118915079567146363110342083974 144395178017479311758132372155911228 13717541911660534617022575354811575685 13717541911660534617022575354811575781 13717541911660534617022575354811575975 13717541911660534617022575354811576073 1358036649254392927085234960126346050829 ``` [Answer] # C#, 120 Bytes Just as no sane person would golf in Java, no sane person should golf in C#! But screw that, I wanted to see what I can do. The `1M` casts `f` to be a decimal which has enough precision for this answer without me having to write `decimal`. Also, the in-place incrementing saves some bytes on my Python answer. in the end it is still 50 bytes longer. ``` void k(){int n=1;var f=1M;while(n<101){Console.WriteLine(f);var d=++n+f;f=(d+n*((d%2<1?1:0)-(d%3<1?1:0)))*(d%4<1?n:1);}} ``` Here's the more readable (and runnable) version: ``` using System; class P { static void Main(string[]a) { int n = 1; var f = 1M; while (n < 101) { Console.WriteLine(f); var d = ++n + f; f = (d + n * ((d % 2 < 1 ? 1 : 0) - (d % 3 < 1 ? 1 : 0))) * (d % 4 < 1 ? n : 1); } Console.Read(); } } ``` [Answer] ## Batch, 110 bytes ``` @set n=0 @for /l %%i in (1,1,46)do @set/an=((n+=%%i)+(!(n%%2)-!(n%%3))*%%i)*(~-%%i*!(n%%4)+1)&call echo %%n%% ``` Uses @ETHproductions' formula, but tweaked slightly because Batch doesn't have `?:`. Batch uses 32-bit signed integers so the loops stops at 46. [Answer] # Perl, 75 Bytes ``` use bigint;$a+=$_,say$a=($a+($a%2?0:$_)-($a%3?0:$_))*($a%4?1:$_)for(1..100) ``` The code outputs each value on a new line, and computes all 100 values. [Answer] ## Haskell, ~~70~~ 64 bytes ``` a%b=0^mod a b n#i|s<-n+i=(s+s%2*i-s%3*i)*i^s%4 scanl1(#)[1..100] ``` `scanl1(#)[1..100]` returns the list with the first 100 elements. One byte less if I can stay in the 2^31 range (-> `[1..46]`). `scanl1` is like `foldl1` but collects the intermediate results in a list. The divisibility tests are done via the helper function `%` which returns `0^0 = 1` if divisible and `0^x = 0` if not. [Answer] # J, 46 bytes ``` (,{:((]^0=4|+)*(]*0=2|+)++-]*0=3|+)1+#)^:99]1x ``` Applies the method described in the challenge. ## Usage The extra command `(,.~#\)` is used to add indices to each value. ``` (,.~#\) (,{:((]^0=4|+)*(]*0=2|+)++-]*0=3|+)1+#)^:99]1x 1 1 2 1 3 21 4 25 5 30 6 216 7 223 8 223 9 2169 10 2179 11 2190 12 2202 13 2215 14 2215 15 2245 16 2261 17 2295 18 2295 19 2333 20 2353 21 2395 22 2417 23 56649 24 56649 25 56699 26 56725 27 1533033 28 1533061 29 1533090 30 45993600 31 45993631 32 45993631 33 1517792001 34 1517792035 35 1517792070 36 1517792106 37 1517792143 38 1517792143 39 1517792221 40 1517792261 41 1517792343 42 1517792343 43 1517792429 44 1517792473 45 1517792563 46 1517792609 47 71336257041 48 71336257041 49 71336257139 50 71336257189 51 3638149121841 52 3638149121893 53 3638149121946 54 196460052588000 55 196460052588055 56 196460052588055 57 11198222997525633 58 11198222997525691 59 11198222997525750 60 11198222997525810 61 11198222997525871 62 11198222997525871 63 11198222997525997 64 11198222997526061 65 11198222997526191 66 11198222997526191 67 11198222997526325 68 11198222997526393 69 11198222997526531 70 11198222997526601 71 795073832824398753 72 795073832824398753 73 795073832824398899 74 795073832824398973 75 59630537461829934225 76 59630537461829934301 77 59630537461829934378 78 4651181922022734887568 79 4651181922022734887647 80 4651181922022734887647 81 376745735683841525912529 82 376745735683841525912611 83 376745735683841525912694 84 376745735683841525912778 85 376745735683841525912863 86 376745735683841525912863 87 376745735683841525913037 88 376745735683841525913125 89 376745735683841525913303 90 376745735683841525913303 91 376745735683841525913485 92 376745735683841525913577 93 376745735683841525913763 94 376745735683841525913857 95 35790844889964944961834465 96 35790844889964944961834465 97 35790844889964944961834659 98 35790844889964944961834757 99 3543293644106529551221660545 100 3543293644106529551221660645 ``` [Answer] # [Perl 6](http://perl6.org/), 62 bytes ``` 1,{((my \v=$_+my \n=++$+1)+n*(v%%2-v%%3))*(v%%4*n||1)}.../645/ ``` [Try it online!](https://tio.run/##K0gtyjH7X5xY@d9Qp1pDI7dSIabMViVeG8TIs9XWVtE21NTO09IoU1U10gUSxpqaYI6JVl5NjaFmrZ6enr6Zian@//8A "Perl 6 – Try It Online") REALLY had to work to get my byte count below those of the other non-golf-language solutions. [Answer] # [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` üµu█QZN/┴¶▬▲▌∙.h├û:╬πa⌠ú-Bq ``` [Run and debug it](https://staxlang.xyz/#p=81e675db515a4e2fc114161eddf92e68c3963acee361f4a32d4271&i=) Can be improved, definitely, just can't find a way to remove the register usage. ## Explanation ``` 1AJDQ_^Y+X"+-*"{]xi^^%{ysl}{d}?F 1 push 1 AJ push 10 squared D repeat the rest of the program 100 times Q print the current number _^ iteration number Y store in Y +X add the two, store in X "+-*"{ F for each of +,-,* ] convert to string xi^^% x modulo (iteration count + 2) { } ? if true: ysl push y and apply the operation { } else: d delete the operation ``` ]
[Question] [ There exists a very simple cipher that replaces a letter with it's position in the alphabet. For example, `abc` would become `1 2 3` in this cipher. This challenge is an alternative take on this cipher. --- # The Challenge Create a program that takes an input of ASCII characters, and outputs a space-separated string of: * integers `-26` through `26` * letters `a` through `j` The output should come through STDOUT or your language's closest alternative. --- # Specifications * Capital letters should be negated. A capital `D` for example would be `-4`, while a lowercase `d` would be `4`. * Digits should be changed to their alpha counterparts. `1` being `a`, and so on. Any zeroes in the input will be `j`. * All non-alphanumeric characters (except spaces) should be ignored. * Spaces are `0`. * Adjacent spaces in the output should be reduced to a single space. ``` Input: You + Me Correct Output: -25 15 21 0 -13 5 Incorrect Output: -25 15 21 0 0 0 -13 5 ``` * A single trailing space or newline is allowed. --- # Examples ``` Input: programming puzzles Output: 16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19 Input: Code Golf Output: -3 15 4 5 0 -7 15 12 6 Input: Programming Puzzles & Code Golf Output: -16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6 Input: C0d3 G0lf Output: -3 j 4 c 0 -7 j 12 6 Input: abc_ABC Output: 1 2 3 -1 -2 -3 ``` --- # Scoreboard For your score to appear on the board, it should be in this format: ``` # Language, Bytes ``` Strikethroughs shouldn't cause a problem. ``` function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58107,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/; ``` ``` body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 10px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table> ``` [Answer] # CJam, ~~58~~ ~~57~~ ~~54~~ ~~51~~ ~~50~~ 49 bytes *Just* when I wrote up the explanation, I noticed that one of the alternative 50 byte versions can be shortened by a byte... ``` q_el_eu&S-A,s--S%S*{i_32md\2*5-*48md@)A%'a+\?}%S* ``` [Test it here.](http://cjam.aditsu.net/#code=q_el_eu%26S-A%2Cs--S%25S*%7Bi_32md%5C2*5-*48md%40)A%25'a%2B%5C%3F%7D%25S*&input=019%20Programming%20Puzzles%20%26%20C0d3%20G0lf) 50 byte solutions: ``` q_el_eu&S-A,s--S%S*{_A,s&\i_)A%'a+\32md\2*5-*?}%S* q_el_eu&S-A,s--S%'`*{i32md:D;(_(2*(D*D3+A%'a+?}%S* q_el_eu&S-A,s--S%'`*{i32md\(_@_@(2*(*\3+A%'a+?}%S* q_el_eu&S-A,s--S%'`*{i32md\(_(2*(g@*_z3+A%'a+?}%S* ``` ## Explanation ``` q e# Read input. _el_eu& e# Intersect a lower-case version with an upper-case version to remove e# all letters. S- e# Remove spaces from that string. A,s- e# Remove digit characters from that string. It now contains all the e# the characters from the input we should ignore. - e# Remove these characters from the input. S%S* e# Split on runs of spaces and join by spaces, collapsing multiple into one. { e# Map this block onto each character... i_ e# Convert to character code and make a copy. 32md e# Get divmod 32. Note that digits have character codes 32 + something, e# the upper case letters have character codes 64 + n (where n is the e# absolute value we want), while lower case letters have codes 96 + n. e# So the div gives 2 or 3 to distinguish capitalisation (and 1 for digits) e# and the mod gives the correct absolute value for letters. e# As it happens, the mod also gives 0 for spaces. \2*5- e# Pull up the div, duplicate, subtract 5. Turns 2 into -1 and 3 into 1. e# It also turns 1 (digits) into -3. * e# Multiply the mod by this sign. e# We now have the correct result for everything but digits. Note that e# the absolute value for digits is more than 26, and for everything e# else it's less than 27. 48md e# Get divmod 48. This gives div 0 and mod n for all correct results n. e# For digits it gives div -1 and we don't care about the mod. We'll e# use the div as a truthy/falsy value to select the right result. @)A% e# Pull up the other copy of the character code, increment e# (range 49..58), take modulo 10. e# This gives 9 for 0 and n-1 for any other digit n. 'a+ e# Add to the character a. \? e# Select the correct result based on the div 48. }% S* e# Join the resulting values by spaces. ``` This must be the first time, that CJam's modulo behaviour for negative values was useful for me. [Answer] # JavaScript (ES6), ~~110~~ ~~107~~ ~~133~~ 120 bytes Take that, old me! ``` a=>[...a.replace(/[\W_]*?( ?)[\W_]*/g,'$1')].map(x=>(c=x.charCodeAt())<40?0:c<60?'jabcdefghi'[x]:c<91?64-c:c-96).join` ` ``` There's potentially a lot more room for golfing, ~~especially in the regexes~~ nope, got that one down pretty well. Ungolfed version: ``` function f(a) { // Replaces each run of bad chars and spaces with // a space if it contained one, nothing otherwise: a = a.replace(/[\W_]*?( ?)[\W_]*/g, '$1'); var b = a.split(''); b = b.map(function(x) { var c = x.charCodeAt(); if (c == 32) // space return 0; else if (c < 60) // numbers return 'jabcdefghi'.charAt(x); else if (c < 91) return 64 - c; // uppercase else return c - 96; // lowercase }); b = b.join(' '); return b; } ``` Suggestions welcome! [Answer] # Pyth, ~~50~~ 49 bytes ``` jdm?>d26C+70ddm-xZd26:-z-z=Zs[_rG1dGjk.<UT1)" +"d ``` Try it out [here](https://pyth.herokuapp.com/?code=jdm%3F%3Ed26C%2B70ddm-xZd26%3A-z-z%3DZs%5B_rG1dGjk.%3CUT1%29%22+%2B%22d&input=You+%2B+Me&test_suite=1&test_suite_input=You+%2B+Me%0Aprogramming+puzzles%0ACode+Golf%0AProgramming+Puzzles+%26+Code+Golf%0AC0d3+G0lf%0Aabc_ABC&debug=0). Edit: restructured string sanitisation to ensure underscores are handled correctly. It even saved a byte too, yay! This program creates a lookup string, which is used to sanitise the input. This is then mapped to the corresponding index in that string. Finally, any index greater than 26 is converted to the correct ASCII character. ``` Implicit: z=input(), d=' ', , k='', G=[a-z] _rG1 Reversed, capitalised alphabet d Single space G Lower case alphabet jk.<UT1 '1234567890' s[ ) Concatenate the 4 previous statements =Z Store in Z -z Setwise difference of input and above (to get all illegal characters) -z Setwise difference of input and illegal chars : " +"d Regex replace to lose multiple spaces m Map the above over d: xZd Get index of d in Z - 26 Subtract 26 m Map the above over d: ?>d26 If d > 26 C+70d Convert (d+70) to ASCII d Otherwise, select d jd Join on spaces and print ``` Previous version, which made use of `\W` regex, at 50 bytes: ``` jdm?>d26C+70ddm-xs[_rG1\ Gjk.<UT1)d26::z"\W"d" +"d ``` [Answer] # Julia, ~~145~~ 136 bytes ``` r=replace;print(join([47<x<58?x+58-10(x>48):x==32?0:cmp(x,96)*(lowercase(x)-96)for x=r(r(readline(),r"[^a-z0-9 ]"i,""),r" +"," ")]," ")) ``` Ungolfed: ``` # Read a string from STDIN input = readline() # Remove non-alphanumeric characters and replace duplicated spaces r = replace(replace(input, r"[^a-z0-9 ]"i, ""), r" +", " ") # Construct an array using comprehension over the replaced input string A = [47 < x < 58 ? x + 58 - 10(x > 48) : x == 32 ? 0 : cmp(x, 96) * (lowercase(x) - 96) for x = r] # Join the array elements with spaces j = join(A, " ") # Print to STDOUT print(j) ``` To get the digits as letters we add 58 to the ASCII value and subtract 10 if the current character isn't 0. That ensures that 0 maps to `j` and the other digits map to `a`-`i`. Negating uppercase letters is done using `cmp`. This will return -1 for uppercase letters and 1 for lowercase. [Try it online](http://goo.gl/XUlNXB) [Answer] # Perl 5, ~~120~~ ~~116~~ ~~113~~ 105 Bytes First cleans up the unwanted characters & extra spaces. Then climbs down the ascii table for each character. ``` $_=pop;s/[^\w ]|_//g;s/ +/ /g;map{$n=ord;say$".($n>96?$n-96:$n>64?64-$n:$n>48?chr$n+48:$n>47?j:0)}split// ``` ### Test ``` $ perl -M5.01 numbers4letters.pl "zZaA _ 190" 26 -26 1 -1 0 a i j $ perl -M5.01 numbers4letters.pl "PrOgr4mm1n9 Puz2l3s & C0d3_G0lf!" -16 18 -15 7 18 d 13 13 a 14 i 0 -16 21 26 b 12 c 19 0 -3 j 4 c -7 j 12 6 ``` [Answer] # C, ~~142~~ ~~138~~ 135 ``` c,d;main(s){while(c=getchar()+1)d=c|32,c=d-98<26u?s=(d-97)*(c/32*2-5),0:c-48<11u?s='a'+c%10,4:c==33&&s?s=0,0:3,printf("%d \0%c "+c,s);} ``` Ungolfed a bit: ``` int c,d; int main(int s) // s initially non-zero, meaning spaces are allowed { while(c=getchar()+1) // getchar until EOF (-1) encountered { d=c|32; // d becomes lowercase c (both incremented by 1) if (d-98<26u) // check for letter { s=(d-97)*(c/32*2-5); // print this number and allow subsequent spaces c=0; // format string will be "%d " } else if (c-48<11u) // check for digit { s='a'+c%10; // print this letter and allow subsequent spaces c=4; // format string will be "%c " } else if (c==33&&s) // else if space and allowed to output spaces { s=0; // print 0 and disallow subsequent spaces c=0; // format string will be "%c " } else { c=3; // format string will be "", prints nothing } printf("%d \0%c "+c,s); // final c is treated as index into string literal } } ``` Passes the given tests in GCC 4.9.3 & Clang 3.5.2. [Answer] # ><> (fish), ~~219~~ 209 bytes ``` >i:84*=?v:86*1-)?!^:f4*2-(?v:88*)?!v:a9*1+(?v:c8*)?!^:ca*3+ (?v~ >4*(?vov>~86*$:@=?v86*00. >:86*=?v77*1-+00.>88*-::-$-00.01-*8c< >.! ! ! 00~v?( 0:\00. >.!00+6*aa~<>~ 92*2!.<2*29< ^7:;?=0:<r0~< *o73.>n>84 ``` Try it out [here](http://fishlanguage.com/playground/JdgqD73EkYYYp39Zc) This is my first code golf answer! Finally been able to use the language I wanted to use for a code golf challenge, and this seemed like the perfect one given that characters are automatically converted to decimals. I expected my result to be way shorter, but apparently not. Though, I haven't golfed this one too much. There are a few places the code could be cleaner/make more sense, but won't save any bytes since they're in places where whitespace is needed anyway. There might be a way to save some bytes on the last bit on the second line, making it go the opposite direction and mashing up with the 00 already there, I'll have to play with it more later Basically, this checks to see whether the current char is a space, number, uppercase letter, or lowercase letter, by checking if it's in range of the highest/lowest values of that group. If it isn't any of those, it gets discarded. If it is in one of those, it gets converted to a number if it's a letter, and a letter if it's a number (or rather, a number from 97-106 which are the values for letters a-j). Then it checks if the top value is less than 28, in which case it's a number and outputs a number, otherwise it's a letter and outputs the letter that number represents, outputs a space, then loops until the stack is empty. [Answer] # JavaScript (ES6), 108 ~~122 124~~ **Edit** Using the regexp from @Max's comment **Edit2** 14 bytes saved thanks ETHProductions EcmaScript 6 just for the arrow functions, so it should work in Firefox and latest Chrome. Test running the snippet below ``` F= t=>t[R='replace'](/[^\w ]|_/g,'')[R](/ +|./g,c=>((v=parseInt(c,36))>9?c>'Z'?v-9:9-v:'jabcdefghi'[v]||0)+' ') // Less golfed U=t=> t.replace(/[^\w ]|_/g,'') // remove invalid characters .replace(/ +/g,' ') // collapse spaces .replace(/./g, c => ( // valid character replacing v = parseInt(c,36), // '0'..'9'-> 0..9, 'a'..'z' -> 10..25, ' ' -> NaN ( v > 9 ? c > 'Z' ? v-9 : 9-v // manage upper vs lower : 'jabcdefghi'[v] || 0 // digits, NaN as an index gives undefined, substituted with 0 ) + ' ' // separator space )) // TEST out=x=>O.textContent=x+'\n'+O.textContent; function go() { out(I.value + ' --> ' + F(I.value) +'\n')} // test cases, a trailing blank added to the expected output as ... // "A single trailing space or newline is allowed." ;[ ['A$b','-1 2 '] , ['123___abc', 'a b c 1 2 3 '] , ['You + Me','-25 15 21 0 -13 5 '] , ['programming puzzles', '16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19 '] , ['Code Golf', '-3 15 4 5 0 -7 15 12 6 '] , ['Programming Puzzles & Code Golf', '-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6 '] , ['C0d3 G0lf', '-3 j 4 c 0 -7 j 12 6 '] ].forEach(t=>{ k=t[1],r=F(t[0]), out('Test '+(k==r?'OK':'Fail')+'\nInput: '+t[0]+'\nResult: '+r+'\nCheck: '+k+'\n') }) ``` ``` Custom test: <input id=I><button onclick='go()'>-></button> <pre id=O></pre> ``` [Answer] # Pyth, 57 bytes ``` :jdm@s[r_26Zr1 27Zc<GT1"")xs[_rG1G\ jkr1TZ)dz"0[0 ]+""0 " ``` [Live demo and test cases.](https://pyth.herokuapp.com/?code=%3Ajdm%40s%5Br_26Zr1+27Zc%3CGT1%22%22%29xs%5B_rG1G%5C+jkr1TZ%29dz%220%5B0+%5D%2B%22%220+%22&input=You+%2B+Me&test_suite=1&test_suite_input=You+%2B+Me%0Aprogramming+puzzles%0ACode+Golf%0AProgramming+Puzzles+%26+Code+Golf%0AC0d3+G0lf&debug=1) [Answer] # CJam, 52 bytes ``` '{,97>:L_eu+A,s(++S+l{1$&},S%S*\26,:)_Wf*+LA<+0+erS* ``` [Try it online](http://cjam.aditsu.net/#code='%7B%2C97%3E%3AL_eu%2BA%2Cs(%2B%2BS%2Bl%7B1%24%26%7D%2CS%25S*%5C26%2C%3A)_Wf*%2BLA%3C%2B0%2BerS*&input=C0d3%20G0lf) The key part with the solution is that it uses the CJam `er` (transliteration) operator. As arguments to the operator, it needs the list of all characters, and a list of the corresponding values. As a pre-processing step on the input, it removes characters that are not part of the translation table (special characters), and reduces repeated spaces to a single space. Explanation: ``` '{,97> Build list of all lower case letters. :L Save it in variable L for later reuse. _eu+ Add list of upper case letters. A,s Build digits "0123456789". (+ Pop off first digit and append it at the end, to get "1234567890". + Add digits to list of characters. S+ Add a space. List of characters that have values is now complete. l Get input. {1$&}, Filter out all input characters that are not in list. S% Split input at spaces. S* And re-assemble it with spaces. This reduces multiple spaces to one space. \ Swap input and character list. 26, Start building list of values. Start with [0 ... 25]. :) Use "smilie operator" to increment all values, to get [1 ... 26]. These are the values for the lower case letters. _Wf* Copy the list and negate the values to get [-1 ... -26] for upper case. + Concatenate the two lists. L Retrieve the list of lower case letters we saved away earlier. A< Keep the first 10, which are the values for the digits. + Concatenate to list of values. 0+ Add 0 to list, as value for space. er Transliterate input string to corresponding values. S* Join with spaces for output. ``` [Answer] # Python 2, ~~191~~ ~~179~~ ~~177~~ ~~173~~ ~~172~~ ~~168~~ 160 bytes ``` import re print" ".join([[[chr(x+48),"j"][x<49],[`[x-96,-x+64][x<96]`,"0"][x<65]][x>57or x<33]for x in map(ord,re.sub(" +"," ",re.sub("[^\w ]|_","",input())))]) ``` # Test ``` "programming puzzles" 16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19 "Code Golf" -3 15 4 5 0 -7 15 12 6 "Programming Puzzles & Code Golf" -16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6 "C0d3 G0lf" -3 j 4 c 0 -7 j 12 6 "You + Me" -25 15 21 0 -13 5 ``` [Answer] # PHP, 116 bytes ``` while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn))[$i++])echo$c<96?jabcdefghi[$c-48]?:64-$c:$c-96," "; ``` takes input from STDIN; run with `-nR`. **breakdown** ``` while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn) # sanitize input [$i++]))echo # loop through string and print ... $c<96 # if not lowercase: ?jabcdefghi[$c-48] # digit -> letter ?: # if that turned out falsy (=empty): 64-$c # uppercase (or former spaces) -> negative (or 0) :$c-96 # else -> positive ," "; # append space ``` You can replace the `@` with a backtick to handle spaces in the lowercase part. ~~With `jabcdefghi0` for the digits, you could also use `:`.~~ [Answer] # [Hassium](https://github.com/HassiumTeam/Hassium), 1156 Bytes ``` func main() {s = input();c="";for(x=0;x<s.length;x++){c=s[Convert.toNumber(Convert.toString(x))].toString();if (c.toLower()!=c)print(r(c.toLower())*-1);else if(r(c)=="")continue;else print(r(c));print(" ");}}func r(c) {if(c=="a")return 1;else if(c=="b")return 2;else if(c=="c")return 3;else if(c=="d")return 4;else if(c=="e")return 5;else if(c=="f")return 6;else if(c=="g")return 7;else if(c=="h")return 8;else if(c=="i")return 9;else if(c=="j")return 10;else if(c=="k")return 11;else if(c=="l")return 12;else if(c=="m")return 13;else if(c=="n")return 14;else if(c=="o")return 15;else if(c=="p")return 16;else if(c=="q")return 17;else if(c=="r")return 18;else if(c=="s")return 19;else if(c=="t")return 20;else if(c=="u")return 21;else if(c=="v")return 22;else if(c=="w")return 23;else if(c=="x")return 24;else if(c=="y")return 25;else if(c=="z")return 26;else if(c==" ")return 0;else if(c=="1")return "a";else if(c=="2")return "b";else if(c=="3")return "c";else if(c=="4")return "d";else if(c=="5")return "e";else if(c=="6")return "f";else if(c=="7")return "g";else if(c=="8")return "h";else if(c=="9")return "i";else if(c=="0")return "j";else return"";} ``` [Very long answer](http://pastebin.com/3cgFAfbS) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes, language postdates challenge ``` ⁶ØB;µ³fi@€ Øaḣ⁵ṙ9 26RµN;;0¢;ị@ÑK ``` [Try it online!](https://tio.run/nexus/jelly#AUMAvP//4oG2w5hCO8K1wrNmaUDigqwKw5hh4bij4oG14bmZOQoyNlLCtU47OzDCojvhu4tAw5FL////IkMwL2QzIEcwbGYi "Jelly – TIO Nexus") ## Explanation **Helper function `1Ŀ`** (translates each alphanumeric/space in the input into a number) ``` ⁶ØB;µ³fi@€ ⁶ space ØB; append all digits, uppercase and lowercase letters (in that order) µ set as the new default for missing arguments ³ first command-line argument f delete all characters not in {space + alphanumerics} i@€ take index of each element within {space + alphanumerics} ``` **Helper function `2£`** (returns the constant string `“jabcdefghi”`) ``` Øaḣ⁵ṙ9 Øa lowercase alphabet ḣ⁵ take first 10 elements ṙ9 rotate 9 elements to the left ``` **Main program** ``` 26RµN;;0¢;ị@ÑK 26R Range from 1 to 26 µ set as default for missing arguments N Minus {each element of the range from 1 to 26} ; with {the range from 1 to 26} appended ;0 with a 0 appended ¢; with the result of 2£ prepended ị@ index into this using Ñ the result of 1Ŀ K separate by spaces ``` [Answer] # Java 7, ~~257~~ 254 bytes ``` class M{public static void main(String[]a){String r="",x;for(int c:a[0].getBytes()){x=(c>96&c<123?c-96:c>64&c<91?"-"+(c-64):c>48&c<58?(char)(c+48):c==48?"j":c<33?0:"")+"";r+=!x.isEmpty()&&!(r.endsWith("0 ")&x.equals("0"))?x+" ":"";}System.out.print(r);}} ``` [Try it here.](https://tio.run/##JY/LboMwFER/xbkLZIuCSKGIRwhSq6qrSpGy6CLKwjUOMeVV20QQxLcTV13NzJFmcSp6o07X87YqftaV1VQp9Dn3w3ctGFKaahO3ThSooaLFRy1FW57OlMz/FckM4GlML53EotWIJfTknd2S69dJc4UJmccMs30cWmy3ffZz5sRhwvZhYHa8zcEBGzMnDIiBQWTgS5RjdqWSYGYHkcFZFkQ5VJCwne/nXgJAbIBU2tlmdIV6b3o9YWJZGyxd3hbqS@grBg8BsUaX/w60VmYCIfloAwLzT5fjpDRv3G7Qbm80NJYkXZZ1XQ@yKyVtmj@1w3C/11whC715hY8@vPryAA) **Explanation:** ``` class M{ // Class public static void main(String[]a){ // Required main-method String r="", // Result-String x; // Temp String for(int c:a[0].getBytes()){ // Loop over the characters of the input-String x=( // Set the temp String to: c>96&c<123? // If it's a lowercase letter: c-96 // Set `x` to the 1-indexed alphabetic index :c>64&c<91? // Else-if it's a uppercase letter: "-"+(c-64) // Set `x` to the 1-indexed alphabetic index as negative :c>48&c<58? // Else-if it's a digit 1-9: (char)(c+48) // Set `x` to the 1-indexed alphabetic character :c==48? // Else if it's a zero: "j" // Set `x` to "j" :c<33? // Else if it's a space: 0 // Set `x` to "0" : // Else: "" // Set `x` to an empty String )+""; // Required `+""` because `(char)` and `0` aren't Strings r+= // Append the result-String with: !x.isEmpty() // If `x` has a value &&!(r.endsWith("0 ")&x.equals("0"))? // and it's not "0" with the previous value also being a zero x+" " // Append the value of `x`, plus a space : // Else: ""; // Append nothing } // End of loop System.out.print(r); // Print the result to STDOUT } // End of main-method } // End of class ``` **Example input & output:** ``` Input: Programming Puzzles & C0d3 G0lf Output: -16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 j 4 c 0 -7 j 12 6 ``` [Answer] # Retina, ~~74~~ 70 bytes Note the leading space on line 3, the trailing space on line 6, and the empty second line. ``` [^\w ]|_ + ~ . $+ [A-Z] -$+ T`L`l [j-s] a$+ [t-z] b$+ T`~ld`dd0-6jl ``` [Try it Online!](https://tio.run/nexus/retina#U9VwT/gfHRdTrhBbE8/FpaDNVcelx6WircAV7agbFculq6LNFZLgk5DDFZ2lWxzLlQjkR5foVsVyJYFl6nJSElJSDHTNsnL@/y8oyk8vSszNzcxLVygorarKSS3mcs5PSVVwz89J4wpAkg2AyCqoKSDknQ1SjBXcDYCsxKTkeEcnZwA) ]
[Question] [ # Challenge Write the shortest program that converts a human readable time interval to date components of the form: ``` {±YEARS|±MONTHS|±DAYS|±HOURS|±MINUTES|±SECONDS} ``` # Sample cases Each test case is two lines, input followed by output: ``` 1 year 2 months 3 seconds {1|2|0|0|0|3} -2 day 5 year 8months {5|8|-2|0|0|0} 3day 9 years 4 seconds -5 minute 4 years 4 years -3seconds {17|0|3|0|-5|1} ``` # Rules * You can not use `strtotime` or any built-in function that does the whole job. * Shortest code wins (bytes) * You can print your output to `stdout` or a file, the result can also be returned by a function, it's up to you * The token can be in singular or plural form. * The components may be in a random order * There may be no white space between the number and the token * Sign is optional when the time interval is positive (input and output) * If a component appears more than once the values should be added * Each component has its own sign * The components should be handled separately (e.g. `80 minutes` remains as 80 in the output) * The input is guaranteed to be lower case Happy Golfing! [Answer] # Perl: 61 characters Thanks to @nutki. ``` s/-?\d+ *m?(.)/$$1+=$&/ge;$_="{y|o|d|h|i|s}";s/\w/${$&}+0/ge ``` Sample run: ``` bash-4.3$ perl -pe 's/-?\d+ *m?(.)/$$1+=$&/ge;$_="{y|o|d|h|i|s}";s/\w/${$&}+0/ge' <<< '1 year 2 months 3 seconds' {1|2|0|0|0|3} bash-4.3$ perl -pe 's/-?\d+ *m?(.)/$$1+=$&/ge;$_="{y|o|d|h|i|s}";s/\w/${$&}+0/ge' <<< '-2 day 5 year 8months' {5|8|-2|0|0|0} bash-4.3$ perl -pe 's/-?\d+ *m?(.)/$$1+=$&/ge;$_="{y|o|d|h|i|s}";s/\w/${$&}+0/ge' <<< '3day 9 years 4 seconds -5 minute 4 years 4 years -3seconds' {17|0|3|0|-5|1} ``` ### My poor efforts: ~~78~~ 77 characters ``` s/([+-]?\d+) *(..)/$a{$2}+=$1/ge;$_="{ye|mo|da|ho|mi|se}";s/\w./$a{$&}||0/ge ``` [Answer] # Python 2, 99 bytes ``` import re f=lambda I:"{%s}"%"|".join(`sum(map(int,re.findall("(-?\d+) *m?"+t,I)))`for t in"yodhis") ``` This is a lambda function which takes in a string and simply uses a regex to extract the necessary numbers. Thanks to Martin for pointing out that `\s*` could just be `<space>*`. It's easy to forget that regexes match spaces literally... [Answer] # Ruby, ~~119~~ ~~106~~ ~~86~~ ~~85~~ 84 bytes One byte saved thanks to Sp3000. ``` ->i{?{+"yodhis".chars.map{|w|s=0;i.scan(/-?\d+(?= *m?#{w})/){|n|s+=n.to_i};s}*?|+?}} ``` This is an unnamed function, which takes the input as a string, and returns the result (also as a string). You can test it by assigning it to `f`, say, and calling it like ``` f["3day 9 years 4 seconds -5 minute 4 years 4 years -3seconds"] ``` [Answer] # JavaScript 100 ~~105 112~~ **Edit** Adding template strings (first implemented dec 2014, so valid for this challenge) - at time I was not aware of them **Edit** Eureka, at last I got the meaning of `m?` in all the other answers! ``` s=>s.replace(/(-?\d+) *m?(.)/g,(a,b,c)=>o['yodhis'.search(c)]-=-b,o=[0,0,0,0,0,0])&&`{${o.join`|`}}` ``` **Test** ``` F= s=>s.replace(/(-?\d+) *m?(.)/g,(a,b,c)=>o['yodhis'.search(c)]-=-b,o=[0,0,0,0,0,0])&&`{${o.join`|`}}` ;['1 year 2 months 3 seconds','-2 day 5 year 8months' ,'3day 9 years 4 seconds -5 minute 4 years 4 years -3seconds'] .forEach(i=>console.log(i,F(i))) ``` [Answer] # CJam, 60 bytes After being stuck in the 60's for a long time, I finally managed to squeeze this down to 60 bytes. Good enough! Ship it! [Try it online](http://cjam.aditsu.net/#code='%7B0a6*q%5B%7B_A%2Cs'-%2B%23)!%7B%22ytdhic%22%23%3AI)%7B%5D'0%2BiA%2FI_3%24%3D%40%2Bt%5B%7D*%7D*%7D%2F'%7C*'%7D&input=3day%209%20%20%20%20%20years%204%20seconds%20-5%20minute%204%20years%204%20years%20-3seconds) Squished: ``` '{0a6*q[{_A,s'-+#)!{"ytdhic"#:I){]'0+iA/I_3$=@+t[}*}*}/'|*'} ``` Expanded and commented: ``` '{ "Add '{' to output"; 0a6* "Initialize time to a list of 6 zeros"; q "Read the input"; [ "Open an empty numeric character buffer"; { "For each character in the input:"; _ "Append the character to the numeric character buffer"; A,s'-+#)! "Check if the character is not part of a number"; { "If so:"; "ytdhic"#:I "Remove the character from the numeric character buffer and convert it to the corresponding time unit index, or -1 if not recognized (Time units are recognized by a character in their name that does not appear before the recognition character in any other name)"; ){ "Repeat (time unit index + 1) times:"; ]'0+iA/ "Close the numeric character buffer and parse it as an integer (empty buffer is parsed as 0)"; I_3$=@+t "Add the integer to the value of the indexed time unit"; [ "Open an empty numeric character buffer"; }* "End repeat (This is used like an if statement, taking advantage of the fact that iterations after the first have no effect)"; }* "End if"; }/ "End for"; '|* "Insert a '|' between each time unit value (implicitly added to output)"; '} "Add '}' to output"; ``` I initially started using a token-based approach, but that got pretty firmly stuck at... 61 bytes. Sigh. So I totally changed gears and switched to this character-based approach, which is much more interesting anyways. My parsing method works by adding any valid numeric characters reached (`0`-`9` and `-`) to a buffer and parsing the buffer as an integer when a certain character from one of the time unit names is reached. Those characters are `y`, `t`, `d`, `h`, `i`, and `c`, which all satisfy the conditions that they appear in a time unit name and don't appear before the recognition character in any other time unit name. In other words, when one of these time unit recognition characters is reached, the numeric buffer will be filled with the last number seen if this actually signals a time unit, or the numeric buffer will be empty if this just appears in, but shouldn't signal, some other time unit. In either case, the numeric buffer is parsed as an integer, or 0 if it was empty, and this is added to the corresponding time unit value. Thus recognition characters appearing in other time units after their recognition character have no effect. Other crazy hacks include: * Abusing loops so numeric characters are left on the stack (which acts as the numeric character buffer) "for free." * Repeating a block zero or multiple times instead of conditionally because the loop is more compact than an if statement, and iterations after the first have no effect. --- For anyone curious about my token-based solution that got stuck at 61 bytes, I'll post it here as well. I never got around to expanding or commenting it, though. ### CJam, 61 bytes ``` '{0a6*q'm-'{,64/~m*{:X/XS**}/S%2/{~0="yodhis"#_3$=@i+t}/'|*'} ``` [Answer] # R, 197 bytes I realize this isn't a competitive entry at all, I mostly just wanted to come up with a solution in R. Any help shortening this is of course welcome. ``` function(x){s="{";for(c in strsplit("yodhis","")[[1]])s=paste0(s,ifelse(c=="y","","|"),sum(as.numeric(gsub("[^0-9-]","",str_extract_all(x,perl(paste0("(-?\\d+) *m?",c)))[[1]]))));s=paste0(s,"}");s} ``` Like Martin's answer, this is an unnamed function. To call it, assign it to `f` and pass a string. This is pretty hideous, so let's take a look at an un-golfed version. ``` function(x) { s <- "{" for (c in strsplit("yodhis", "")[[1]]) { matches <- str_extract_all(x, perl(paste0("(-?\\d+) *m?", c)))[[1]] nums <- gsub("[^0-9-]", "", matches) y <- sum(as.numeric(nums)) s <- paste0(s, ifelse(c == "y", "", "|"), y) } s <- paste0(s, "}") return(s) } ``` Based on the structure alone it's easy to see what's going on, even if you aren't too familiar with R. I'll elaborate on some of the stranger looking aspects. `paste0()` is how R combines strings with no separator. The `str_extract_all()` function comes from Hadley Wickham's `stringr` package. R's handling of regular expressions in the base package leaves much to be desired, which is where `stringr` comes in. This function returns a list of regular expression matches in the input string. Notice how the regex is surrounded in a function `perl()`--this is just saying that the regex is Perl-style, not R-style. `gsub()` does a find-and-replace using a regex for each element of the input vector. Here we're telling it to replace everything that isn't a number or minus sign with an empty string. And there you have it. Further explanation will be gladly provided upon request. [Answer] # Cobra - 165 ``` def f(s='') l=int[](6) for i in 6,for n in RegularExpressions.Regex.matches(s,'(-?\\d+) *m?['yodhis'[i]]'),l[i]+=int.parse('[n.groups[1]]') print'{[l.join('|')]}' ``` [Answer] # C++14, 234 229 bytes ***Edit:*** cut down 5 bytes by using old style declaration instead of `auto`. I know the winner has already been chosen, and that this would be the longest submission so far, but I just had to post a C++ solution, because I bet nobody expected one at all :) To be honest, I'm pretty much happy with how short it turned out to be (by C++ measurements, of course), and I'm sure it can't get any shorter that this (with just one remark, see below). It is also quite a nice collection of features new to C++11/14. No third-party libraries here, only standard library is used. The solution is in a form of lambda function: ``` [](auto&s){sregex_iterator e;auto r="{"s;for(auto&t:{"y","mo","d","h","mi","s"}){int a=0;regex g("-?\\d+ *"s+t);decltype(e)i(begin(s),end(s),g);for_each(i,e,[&](auto&b){a+=stoi(b.str());});r+=to_string(a)+"|";}r.back()='}';s=r;}; ``` Ungolfed: ``` [](auto&s) { sregex_iterator e; auto r="{"s; for(auto&t:{"y","mo","d","h","mi","s"}) { int a=0; regex g("-?\\d+\\s*"s+t); decltype(e)i(begin(s),end(s),g); for_each(i,e,[&](auto&b) { a+=stoi(b.str()); }); r+=to_string(a)+"|"; } r.back()='}'; s=r; } ``` For some reason, I had to write ``` regex g("-?\\d+\\s*"s+t); decltype(e)i(begin(s),end(s),g); ``` instead of just ``` decltype(e)i(begin(s),end(s),regex("-?\\d+\\s*"s+t)); ``` because the iterator would only return one match if I pass in a temporary object. This doesn't seem right to me, so I wonder if there's a problem with GCC's regex implementation. Full test file (compiled with GCC 4.9.2 with `-std=c++14`): ``` #include <iostream> #include <string> #include <regex> using namespace std; int main() { string arr[] = {"1 year 2 months 3 seconds", "-2 day 5 year 8months", "3day 9 years 4 seconds -5 minute 4 years 4 years -3seconds"}; for_each(begin(arr), end(arr), [](auto&s){sregex_iterator e;auto r="{"s;for(auto&t:{"y","mo","d","h","mi","s"}){int a=0;auto g=regex("-?\\d+ *"s+t);decltype(e)i(begin(s),end(s),g);for_each(i,e,[&](auto&b){a+=stoi(b.str());});r+=to_string(a)+"|";}r.back()='}';s=r;}); for(auto &s : arr) {cout << s << endl;} } ``` Output: ``` {1|2|0|0|0|3} {5|8|-2|0|0|0} {17|0|3|0|-5|1} ``` [Answer] # PHP, 141 bytes ``` preg_match_all("#(.?\d+)\s*m?(.)#",$argv[1],$m);$r=[0,0,0,0,0,0];foreach($m[1]as$i=>$n)$r[strpos(yodhis,$m[2][$i])]+=$n;echo json_encode($r); ``` takes input from first command line argument; uses `[,]` for output instead of `{|}`. Run with `-r`. **breakdown** ``` preg_match_all("#(.?\d+)\s*m?(.)#",$argv[1],$m); # find intervals. # (The initial dot will match the sign, the space before the number or a first digit.) $r=[0,0,0,0,0,0]; # init result foreach($m[1]as$i=>$n) # loop through matches $r[strpos(yodhis,$m[2][$i])]+=$n; # map token to result index, increase value echo json_encode($r); # print result: "[1,2,3,4,5,6]" ``` ]
[Question] [ In this challenge, your task is to construct an undirected graph from a sequence of directives. There is one directive for each nonnegative integer, and each transforms a given graph into a new one. * Directive `0`: Add a new disconnected node. * Directive `1`: Add a new node, and connect it to every existing node. * Directive `m > 1`: Remove all nodes whose degree (number of neighbors) is divisible by `m`. Note that `0` is divisible by all `m`, so disconnected nodes are always removed. The directives are applied one by one, from left to right, starting with the empty graph. For example, the sequence `[0,1,0,1,0,1,3]` is processed as follows, explained using awesome ASCII art. We start with the empty graph, and add a single vertex as directed by `0`: ``` a ``` Then, add another vertex and connect it to the first, as directed by `1`: ``` a--b ``` We add another disconnected vertex and then a connected one, as directed by `0` and `1`: ``` a--b c \ \ / `--d ``` We repeat this one more time, as directed by `0` and `1`: ``` ,--f--e / /|\ a--b | c \ \|/ `--d ``` Finally, we remove the degree-3 vertices `a` and `b`, as directed by `3`: ``` f--e |\ | c |/ d ``` This is the graph defined by the sequence `[0,1,0,1,0,1,3]`. # Input A list of nonnegative integers, representing a sequence of directives. # Output The number of nodes in the graph defined by the sequence. # Test cases ``` [] -> 0 [5] -> 0 [0,0,0,11] -> 0 [0,1,0,1,0,1,3] -> 4 [0,0,0,1,1,1] -> 6 [0,0,1,1,0,0,1,1,2,5,7,0,1] -> 6 [0,0,1,1,1,1,5,1,4,3,1,0,0,0,1,2] -> 6 [0,0,1,1,0,0,1,1,5,2,3,0,0,1,1,0,0,1,1,3,4,0,0,1,1,2,1,1] -> 8 [0,0,1,1,0,0,1,1,2,5,7,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,8] -> 14 ``` # Detailed rules You can write a function or a full program. The shortest byte count wins. Standard loopholes are disallowed. Please explain your algorithm in your answer. --- It's been a week, so I have accepted the shortest answer. If an even shorter one comes along later, I'll update my choice. An honorable mention goes to [Peter Taylor's answer](https://codegolf.stackexchange.com/questions/42890/construct-a-graph/42907#42907), on which several others were based on, including the winner. [Answer] ## GolfScript (53 bytes) ``` ])~{:^1>{.-1:H)-,:T;{..H):H*T@-:T+^%!{;}*}%}{^+}if}/, ``` [Online demo](http://golfscript.apphb.com/?c=OydbMCAwIDEgMSAwIDAgMSAxIDIgNSA3IDAgMSAxIDEgMSAxIDAgMSAxIDEgMSAxIDEgMSAxIDhdJwoKXSl%2BezpeMT57Li0xOkgpLSw6VDt7Li5IKTpIKlRALTpUK14lIXs7fSp9JX17Xit9aWZ9Lyw%3D) I haven't actually golfed this yet, but I have discovered that it's not very easy to eliminate the `H` and `T` variables so this might be a local minimum. Takes input on stdin in the format `[0 1 2 3]`. Leaves output on stdout. Ungolfed: ``` ])~{ :^1>{ # array of 0s and 1s # Each 0 has degree equal to the number of 1s after it # Each 1 has degree equal to the number of values before it plus the number of 1s after it .-1:H)-,:T; { # Stack: x # T' = T - x is the number of 1s after it # H' = H + 1 is the number of values before it # Degree is therefore H' * x + T' = H * x + T - x = (H-1)*x + T # Keep x unless degree % ^ == 0 ..H):H*T@-:T+^%!{;}* }% }{^+}if }/, ``` [Answer] # [Pyth](http://github.com/isaacg1/pyth), ~~37~~ 31 ``` lu?+GH<H2m@Gdf%+*@GTtTs>GTHUGQY ``` This solution uses a reduce function (`u`) to build up a list, where each entry corresponds to a node remaining in the list, and the value of the entry corresponding to whether the node was originally added under directive 0 or 1. `G` is the accumulator variable in the reduce function, and holds the aforementioned list. It is initialized to the empty list, `Y`. `H` takes the value of each member of `Q`, the input, one by one. The result of the expression is assigned to `G` each time, and the next entry of `Q` is assigned to `H`, and the expression is rerun. To update `G` properly, there are two possibilities, one for directive 0 or 1, and one for the other directives. These case are distinguished with the ternary `? ... <H2 ...` If `H` is 0 or 1, then all we need to do is append `H` to `G`. `+GH` accomplishes this. Otherwise, the first thing that is need is to determine, for every node in the graph, how many neighbors it has. This is accomplished in two steps: First, `s>GT` counts the number of nodes at or after the input node which are 1s. These are all connected to the input node, except that we will over count by 1 if the input node is a 1. Second, we need the number of nodes earlier than the input node which are connected to it. This is 0 if the input node is a 0, and the index of the input node, `T`, if the input node is a 1. This value would be given by `*@GTT`. However, there is still the over count from the first section which needs to be corrected. Thus, we calculate `*@GTtT` instead, which is 1 less if the input node is a 1. These values are summed, to give the number of nodes connected to the input node. `% ... H` will give 0 is that number is divisible by `H`, and thus should be removed, and will not give 0 otherwise. `f ... UG` will thus give the indices of the input which should not be removed, since `f` is a filter, and 0 is falsy. `m@Gd` converts these indices to the 0s and 1s of the corresponding nodes. Finally, once the resultant list of nodes labeled 0 and 1 is found, its length is computed (`l`) and printed (implicit). Broad idea thanks to @PeterTaylor. [Answer] # APL, ~~71~~ ~~65~~ 55 characters ~~[`{⍬≡⍺:≢⍵⋄r←1↓⍺⋄1<c←⊃⍺:r∇i⌿⍵/⍨i←0≠c|+/⍵⋄c:r∇∨⌿↑a(⍉a←⍵,1)⋄r∇0,0⍪⍵}∘(0 0⍴0)`](http://tryapl.org/?a=%7B%u236C%u2261%u237A%3A%u2262%u2375%u22C4r%u21901%u2193%u237A%u22C41%3Cc%u2190%u2283%u237A%3Ar%u2207i%u233F%u2375/%u2368i%u21900%u2260c%7C+/%u2375%u22C4c%3Ar%u2207%u2228%u233F%u2191a%28%u2349a%u2190%u2375%2C1%29%u22C4r%u22070%2C0%u236A%u2375%7D%u2218%280%200%u23740%29%20%A8%20%u236C%28%2C5%29%280%200%200%2011%29%280%201%200%201%200%201%203%29%280%200%200%201%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%29%280%200%201%201%201%201%205%201%204%203%201%200%200%200%201%202%29%280%200%201%201%200%200%201%201%205%202%203%200%200%201%201%200%200%201%201%203%204%200%200%201%201%202%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%201%201%201%201%200%201%201%201%201%201%201%201%201%208%29&run)~~ ~~[`{⍺←0 0⍴0⋄⍬≡⍵:≢⍺⋄(⍺{1<⍵:i⌿⍺/⍨i←×⍵|+/⍺⋄⍵:-⌿↑(1,1⍪⍺)1⋄0,0⍪⍺}⊃⍵)∇1↓⍵}`](http://tryapl.org/?a=%7B%u237A%u21900%200%u23740%u22C4%u236C%u2261%u2375%3A%u2262%u237A%u22C4%28%u237A%7B1%3C%u2375%3Ai%u233F%u237A/%u2368i%u2190%D7%u2375%7C+/%u237A%u22C4%u2375%3A-%u233F%u2191%281%2C1%u236A%u237A%291%u22C40%2C0%u236A%u237A%7D%u2283%u2375%29%u22071%u2193%u2375%7D%20%A8%20%u236C%28%2C5%29%280%200%200%2011%29%280%201%200%201%200%201%203%29%280%200%200%201%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%29%280%200%201%201%201%201%205%201%204%203%201%200%200%200%201%202%29%280%200%201%201%200%200%201%201%205%202%203%200%200%201%201%200%200%201%201%203%204%200%200%201%201%202%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%201%201%201%201%200%201%201%201%201%201%201%201%201%208%29&run)~~ [`{g←0 0⍴0⋄(≢g)⊣{1<⍵:g⌿⍨←g/⍨←×⍵|+/g⋄(⊃g)-←g⍪⍨←g,⍨←⍵}¨2,⍵}`](http://tryapl.org/?a=%7Bg%u21900%200%u23740%u22C4%28%u2262g%29%u22A3%7B1%3C%u2375%3Ag%u233F%u2368%u2190g/%u2368%u2190%D7%u2375%7C+/g%u22C4%28%u2283g%29-%u2190g%u236A%u2368%u2190g%2C%u2368%u2190%u2375%7D%A82%2C%u2375%7D%20%A8%20%u236C%28%2C5%29%280%200%200%2011%29%280%201%200%201%200%201%203%29%280%200%200%201%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%29%280%200%201%201%201%201%205%201%204%203%201%200%200%200%201%202%29%280%200%201%201%200%200%201%201%205%202%203%200%200%201%201%200%200%201%201%203%204%200%200%201%201%202%201%201%29%280%200%201%201%200%200%201%201%202%205%207%200%201%201%201%201%201%200%201%201%201%201%201%201%201%201%208%29&run) The graph is represented as a boolean adjacency matrix. Rows/columns are added and removed as necessary. [Answer] # CJam, ~~129 75 73 68 61 46~~ 42 bytes Solution based on Peter's algorithm: ``` Lq~{I+I1>{0:U(<:L{LU<,*LU):U>1b+I%},}*}fI, ``` Code expansion to follow. --- Previous solution (61 bytes): ``` Lq~{:N2<{U):UaN{f+U1$0f=+}*a+}{{:X,(N%_!{X0=L+:L;}*},Lf-}?}/, ``` Takes input from STDIN like: ``` [0 0 1 1 0 0 1 1 5 2 3 0 0 1 1 0 0 1 1 3 4 0 0 1 1 2 1 1] ``` Output is the number on STDOUT: ``` 8 ``` **Algorithm**: * Maintain an incrementing variable `U` which stores id of the node to be added. * Maintain a list of list in which , each list is a node with a unique id made up by the first element of the list and the remaining elements being the ids of connected nodes. * In each iteration (while reading the input directives), + If the directive is `0`, add `[U]` to a list of list + If the directive is `1`, add `U` to each list in the list of list and add another list comprised of first element of each of the list of list and `U` + For directive to remove, I filter out all lists of `length - 1` divisible by `m` and keep noting the first element of those lists. After filtering, I remove all the removed id from remaining list of ids. **Code expansion**: ``` Lq~{:N2<{U):UaN{f+U1$0f=+}*a+}{{:X,(N%_!{X0=L+:L;}*},Lf-}?}/, L "Put an empty array on stack"; q~ "Evaluate the input"; { }/ "For each directive"; :N "Store the directive in N"; 2<{ ... }{ ... }? "If directive is 0 or 1, run the first"; "block, else second"; {U):UaN{f+U1$0f=+}*a+} U):U "Increment and update U (initially 0)"; a "Wrap it in an array"; N{ }* "Run this block if directive is 1"; f+ "Add U to each list in list of list"; U1$ "Put U and list of lists on stack"; 0f= "Get first element of each list"; + "Prepend U to the above array"; a+ "Wrap in array and append to list of list"; {{:X,(N%_!{X0=L+:L;}*},Lf-} { }, "Filter the list of list on this block"; :X,( "Get number of connections of this node"; N%_ "mod with directive and copy the result"; !{ }* "If the mod is 0, run this block"; X0= "Get the id of this node"; L+:L; "Add to variable L and update L"; Lf- "Remove all the filtered out ids from the"; "remaining nodes"; , "After the whole process is completed for" "all directives, take length of remaining "; "nodes in the list of list"; ``` [Try it here](http://cjam.aditsu.net/) [Answer] # Pyth, ~~88~~ ~~80~~ 75 characters ``` JYFHQI!H~Y]]lY)IqH1=Y+m+dlYY]UhlY)VYI&Hq%l@YNH1~J]N))=Ymf!}TJ@YkUlYY;-lYl{J ``` I'm done. Maybe someone else has some golfing tips. `Y` is the adjacency list of the graph. For golfing reasons, I also keep a node in this list, even after the node got deleted (Otherwise I would have to update all indices). Each node has itself as neighbor. The list `J` keeps track of the deleted nodes. I show the changes of the adjacency list on the example input `[0,1,0,1,0,1,3]`: ``` input 0: Y=[[0]] J=[] input 1: Y=[[0,1],[0,1]] 0 J=[] input 0: Y=[[0,1],[0,1],[2]] J=[] input 1: Y=[[0,1,3],[0,1,3],[2,3],[0,1,2,3]] J=[] input 0: Y=[[0,1,3],[0,1,3],[2,3],[0,1,2,3],[4]] J=[] input 1: Y=[[0,1,3,5],[0,1,3,5],[2,3,5],[0,1,2,3,5],[4,5],[0,1,2,3,4,5]] J=[] input 3: Y=[[3,5],[3,5],[2,3,5],[2,3,5],[4,5],[2,3,4,5]] J=[0,1] ``` The algorithm then is pretty simple: Iterate over all inputs, if input==0: add a new node with itself as neighbour, if input==1: add a new node with all nodes as neighbors (also the deleted ones) and add this node to the adjacency list of all nodes, if input>1: determine the nodes with #neighbor-1%input==0 and add them to `J`, in each case, update the neighbors of each node using `J`. At the end print the length of `Y` minus the length of (the set of) `J`. ``` JYFHQI!H~Y]]lY)IqH1=Y+m+dlYY]UhlY)VYI&Hq%l@YNH1~J]N))=Ymf!}TJ@YkUlYY;-lYl{J JY set J=[] FHQ for H in: input() I!H ) if H==0: ~Y]]lY Y.append([len(Y)]) IqH1 ) if H==1: =Y+ Y= + m+dlYY old nodes updated ]UhlY new node with all neighbors VY ) for N in range(len(Q)): I&Hq%l@YNH1 ) if H>0 and len(Y[N])%H==1: ~J]N J.append(N) //this node gets deleted =Ym Y Y=[ for k in Y] f!}TJ@YkUlY k-filtered //all items of J are removed ; end input for loop -lYl{J print len(Y) - len(set(J)) ``` ## Usage Just call the script and give as input `[0,1,0,1,0,1,3]` or some other test-case. [Answer] ## Python 2, 296 ``` s=input();e=[];n=[];c=0 for t in s: if t<2:e=e+[[]]if t==0 else [x+[c]for x in e]+[n[:]];n+=[c];c+=1 else: M=zip(*[(i,n[i])for i,x in enumerate(e)if not len(x)%t]) if M:e=[list(set(z)-set(M[1]))for j,z in enumerate(e)if j not in M[0]];n=list(set(n)-set(M[1])) print len(n) ``` Each node is given a unique id and the neighbor ids of each node are recorded. When the directive is 0, an empty neighbor list is added for the new node. When the directive is 1, the ids of all existing nodes become the neighbor list for the new node, and all other neighbor lists are updated to include the new node id. For m>1, nodes with neighbor lists that are a multiple of m are removed from the node list and all neighbor lists. Thanks to @Optimizer for catching a bug in an earlier version. [Answer] # NetLogo, 160 ``` to f[t]foreach t[if ? = 0[crt 1]if ? = 1[crt 1[create-links-with other turtles]]if ? > 1[ask turtles with[count my-links mod ? = 0][die]]]show count turtles end ``` The implementation is straightforward, reading each symbol and doing the appropriate action. ``` to f[t] foreach t [ if ? = 0 [ crt 1 ] if ? = 1 [ crt 1 [create-links-with other turtles] ] if ? > 1 [ ask turtles with [count my-links mod ? = 0] [die] ] ] show count turtles end ``` You can run from the command line as `f[0 0 1 1 0 0 1 1 2 5 7 0 1]`. [Answer] ## Ruby ~~159~~ 157 ([demo](http://ideone.com/zR0Uq5)) ``` N=Struct.new:l G=->c{n=[] c.map{|m|m<1?n<<N.new([]):m<2?(w=N.new([]) n.map{|x|x.l<<w;w.l<<x} n<<w):(n-=r=n.select{|x|x.l.size%m<1} n.map{|x|x.l-=r})} n.size} ``` This defines a function called `G` using stabby-lambda syntax. Use `G[[0, 1]]` to call it with commands `0` and `1`. The implementation is pretty straightforward: there is a `Node` structure (called `N` above) which holds references to all linked nodes via the `l` property. `G` creates nodes as needed and manipulates their links. A readable version is available [here](http://pastie.org/9802697). [Answer] # CJam, ~~99~~ 97 bytes ``` Lal~{I2<{_0={{If+z}2*));0+a+}{;Iaa}?}{_0=!!{{{_:+I%+}%z}2*));1+a+{{W=},z}2*);z_{);}{a}?}*}?}fI0=, ``` There is still a lot to be golfed in this. The algorithm is based on keeping track of the adjacency matrix, but representing the empty matrix without having to treat it specially is giving me headaches. [Test it here.](http://cjam.aditsu.net/) Input is a CJam-style array: ``` [0 0 1 1 0 0 1 1 2 5 7 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 8] ``` You can use this test harness to run all tests: ``` "[] [5] [0,0,0,11] [0,1,0,1,0,1,3] [0,0,0,1,1,1] [0,0,1,1,0,0,1,1,2,5,7,0,1] [0,0,1,1,1,1,5,1,4,3,1,0,0,0,1,2] [0,0,1,1,0,0,1,1,5,2,3,0,0,1,1,0,0,1,1,3,4,0,0,1,1,2,1,1] [0,0,1,1,0,0,1,1,2,5,7,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,8]" ","SerN/{ La\~{I2<{_0={{If+z}2*));0+a+}{;Iaa}?}{_0=!!{{{_:+I%+}%z}2*));1+a+{{W=},z}2*);z_{);}{a}?}*}?}fI0=, N}/ ``` [Answer] ## Python 2, 174 ``` l=input() g={} n=0 for x in l: n+=1;g[n]=set() if x>1:h={i for i in g if len(g[i])%x};g={i:g[i]&h for i in set(g)&h} if x==1: for i in g:g[i]^={n};g[n]^={i} print len(g) ``` This can probably still be golfed a lot. I used a dictionary `g` to represent the graph. The nodes are labelled by numbers, and they map to the set of adjacent nodes. This means that each update of an edge needs to be executed at both of its endpoints. Fresh node indices are created by counting up `n`. Each time, I create a new empty node `n`. For command `0`, it just remains. For command `1`, it's connected to each other node via `g[i]^={n};g[n]^={i}`; using xor make its so that the node isn't connected to itself. For commands >1, it's immediately deleted. The filtering of nodes whose degree is a multiple is done by first finding nodes that the remain (`h`), then `and`ing it with the list of nodes and the neighbors of each node. Finally, the number of entries in the graph dictionary is the answer. [Answer] # Mathematica, 223 bytes Wow, this turned out longer than I expected. ``` f=(g={};t=Append;l=Length;m=ListQ;h=Flatten;k=Position;o=If;(d=#;o[d==0,g=g~t~{},o[d==1,g=o[m@#,t[#,l@g+1],#]&/@g;g=t[g,h@k[g,_?m,1]],g=o[l@#~Mod~d==0,0,#]&/@g;p=h@k[g,0];(c=#;g=#~DeleteCases~c&/@g)&/@p]])&/@#;g~Count~_?m)& ``` Usage: ``` f@{0, 1, 0, 1, 0, 1, 3} ``` Here are the results from the test cases: ``` f /@ { {}, {5}, {0, 0, 0, 11}, {0, 1, 0, 1, 0, 1, 3}, {0, 0, 0, 1, 1, 1}, {0, 0, 1, 1, 0, 0, 1, 1, 2, 5, 7, 0, 1}, {0, 0, 1, 1, 1, 1, 5, 1, 4, 3, 1, 0, 0, 0, 1, 2}, {0, 0, 1, 1, 0, 0, 1, 1, 5, 2, 3, 0, 0, 1, 1, 0, 0, 1, 1, 3, 4, 0, 0, 1, 1, 2, 1, 1}, {0, 0, 1, 1, 0, 0, 1, 1, 2, 5, 7, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 8} } Out: {0, 0, 0, 4, 6, 6, 6, 8, 14} ``` Less golfed: ``` f = ( a = #; g = {}; Table[ If[a[[n]] == 0, AppendTo[g, {}], If[a[[n]] == 1, g = If[ListQ@#, Append[#, Length@g + 1], #] & /@ g; g = Append[g, Flatten@Position[g, _?ListQ, 1]], If[a[[n]] > 1, g = If[Mod[Length@#, a[[n]]] == 0, 0, #] & /@ g; p = Flatten@Position[g, 0]; (c = #; g = DeleteCases[#, c] & /@ g) & /@ p ] ] ], {n, Length@a}]; Count[g, _?ListQ] ) & ``` The way this works is by representing the graph as list of "lists of neighbors". For the **0** directive, I just append an empty list. For the **1** directive, I append a list of all the previous nodes, and add the new node to all the previous nodes. For a directive **>1**, I removed the specified nodes and update the rest. ]
[Question] [ The JavaScript compressor [RegPack](https://siorki.github.io/regPack.html) uses a very simple string compression algorithm. Given a piece of code, it will make a list of characters that aren't used in that code and use them to delimit repeated strings that are inserted back into the string. To show how strings are compressed, it's necessary to show how the decompressor works. If you give RegPack the tongue-twister `How much wood would a woodchuck chuck if a woodchuck could chuck wood?`, it will spit out `How much } w|a }~~if a }~c|~}?~chuck }wood|ould` along with the list of characters `|}~`. The decompressor starts by splitting this string on the first character in the char list, `|`, resulting in `["How much } w", "a }~~if a }~c", "~}?~chuck }wood", "ould "]`. It then pops the last item, `"ould "`, and joins what remains by this, resulting in `"How much } would a }~~if a }~could ~}?~chuck }wood"`. It then does the same thing for `}`, replacing `}` with `wood` to result in `"How much wood would a wood~~if a wood~could ~wood?~chuck "`, and finally replaces `~` with `"chuck "` to result in the whole thing, `How much wood would a woodchuck chuck if a woodchuck could chuck wood?`. The advantage of this algorithm is that it's very simple and short to implement. RegPack itself implements it in 39 bytes of JavaScript: `for(i of<chars>)with(_.split(i))_=join(pop())` (where `<chars>` is a hardcoded char list), which basically performs the steps described above. Your challenge is to, given a compressed string and a list of characters, decompress it using the above algorithm. ## Testcases ``` 'a|b|c|hello', '|' => ahellobhelloc 'He||o, wor|d!|l', '|' => Hello, world! '| | & &&|house|green', '|&' => green green greenhouse greenhouse 'N~give}up,n~let}down~ever gonna } you ', '}~' => Never gonna give you up,never gonna let you down 'How much } w|a }~~if a }~c|~}?~chuck }wood|ould ', '|}~' => How much wood would a woodchuck chuck if a woodchuck could chuck wood? 'She sells~ells by the~ore~ sea sh', '~' => She sells sea shells by the sea shore ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes -1 thanks to @KevinCruijssen ``` vy¡`ý ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/rPLQwoTDe///r6mt4/LIL1fILU3OUKhVKK9JVKitq8tMUwDRyTV1tfZ1yRmlydkKteX5@Sk1@aU5KQoA "05AB1E – Try It Online") ## Explanation ``` v # for each char in the char list y # push it ¡ # split the current string by it ` # dump the parts to stack ý # join the stack by the last part ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` F(↔ΓJx↔ ``` [Try it online!](https://tio.run/##yygtzv7/303jUduUc5O9KoDU////PfLLFXJLkzMUahXKaxIVauvqMtMUQHRyTV2tfV1yRmlytkJteX5@Sk1@aU6Kwv@a2joA "Husk – Try It Online") ### Explanation ``` F(↔ΓJx↔ F For each character in the character list: ↔ flip the string x split it on the given character ΓJ use the first element to join the rest of the list ↔ flip the string back ``` Why all that flipping back and forth? Because in Husk it's often easier to operate on the first element of a list than the last (`Γ` here does exactly that). We could manually take the last element and everything except that, but the program would have the same length: `F(§J→hx` We could solve the challenge in 5 bytes (`F(ΓJx`) if we were allowed to [operate on the reversed string](https://tio.run/##yygtzv7/303j3GSviv///yuk5JTm16Tk55fXKmQnl2Yk19nX1tUk19UqJCqkZdaB6JpyhVqFjOTSXIXyfI//NbV1AA "Husk – Try It Online"), or to [have the changes listed at the beginning of the string](https://tio.run/##yygtzv7/303j3GSviv///@eX5qQo1JTn56fUJmeUJmcr1HnklyvkliZnKNQqlNckKtTW1WWmKYDo5Jq6Wvv/NbV1AA "Husk – Try It Online"). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` +`(?=.*¶(.))\1((?=.*\1(.+))|.+)|(?<=¶).|¶$ $3 ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0HD3lZP69A2DT1NzRhDDTAPSOtpa2rWAIkaDXsb20PbNPVqDm1T4VIx/v/fI79cIbc0OUOhVqG8JlGhtq4uM00BRCfX1NXa1yVnlCZnK9SW5@en1OSX5qQocNXU1gEA "Retina 0.8.2 – Try It Online") No test suite because I can't think of a good separator between the two strings. Explanation: ``` +` ``` Repeat for each character in the list. ``` (?=.*¶(.))\1((?=.*\1(.+))|.+)|(?<=¶).|¶$ $3 ``` Search the string for occurrences of the first character in the list, and try to replace it with the word after the last occurrence, otherwise delete the last occurrence and the word after it. Finish by deleting the character from the list and the list itself once the last character has been processed. [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->s,l{l.chars{|x|*k,w=s.split x;s=k*w};s} ``` [Try it online!](https://tio.run/##TZDBboMwEETv/YqNKoEU0fxARHLNKZccqx7AODHCxQjjOFHW/nVqLzTyZbBn38wCo6mf87Wcvw66kC@5Y6Ia9QsfuO0KW@qdHmQ7wWOvy25r3V67eYDrd15hjQwFl1LlBeSY/3xCeYCKnJqUfRB54oiqAKtGbDYoU/oUMRrJZrPQCAgZZBkKZTTH28h5T5FszZCTKoHJcek5@1t7584MRe8ln1yjbO/5nY9wU31fgYOnMhCbnV@bz8k4homIBYkfqsiOdevnKQu/honQaDH0et9eIT4Zenf0TBjWgbNKNaiMbGglvne@0xEIEomKLktwUWpMTMKWc3SPy5tcBAcd/qj2UaB@wiS4VyP3wa5Ai7j6f/EbXmdJZHVCcP4D "Ruby – Try It Online") Not particularly original, I guess. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ṣjṪ$¥ƒ ``` [Try it online!](https://tio.run/##TY5BasMwEEX3PcUUgkXB0COky66y6aqYLBx5aiVRNcWOIgyjOUSuEEKgN8i2hdwjJ1HktIVuZmDe@8xfobVDSpfTfnU5fU6@Dudd@j4@PT68plRVquYFazZZIlWCYjUv7yr1jMxUQqCOm3u2/wgDQwFFwYZ8j9x2iO6Gix8@k3a5xeg/SicWN7Gh4AS32EFLztUQYSAPYyLK7y8K8O61yShwFkSWbzBuzRKnoo3Xa4iBqGHytrll@S/8YhD6XL6XccBigI1BoQ4ln2vozWhnd34F "Jelly – Try It Online") Takes the delimiters on the left and the compressed string on the right. ``` ¥ƒ Reduce the delimiters by, starting with the compressed string: ṣ Split on the delimiter j and join that on Ṫ$ its last element (removed). ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 74 bytes ``` param($t)$args|%{$j=($o=$t|% S*t $_)[-1] $t=$o[0..($o.Count-2)]-join$j} $t ``` [Try it online!](https://tio.run/##VVLJbtswEL3rKyYGI1iFZLS9CzEQpMgpLereDCOgqbFlVxZdLlECU/x1l0uisjw8iW8bajnzAYVssesqxgVeya6@XM9U0NOcqIJQsZfm9kKO9ZzwmihzC6tPCshzsa6@bDKiasLXnxcLpy7uue5V9bXYVEd@6MlxdPJ1zLLlPAO3SljOZ9RsDTN@HJ@VMDMeaNhuA7JZ8c/8iMbwEgYuTHNjuinw6J2B75qbNGDAQA55blquJZq9QOxDKvcYtpBgcCW3adWT3R9ecNTnsrcdqrHhQ2/xBQXsed9TGOGNa/C1o/X4lGg@GWSfTnjXE2jf9d9z8gFOmrWudDCu2trDDvyVGTveWdZq9hvGgfPGcN01YaqJY6eoVx14mYZNTEUMdQkZbPHes3fpYVYtgnQvWFoPsH0D1aJ1v4Z1NAXZ@rFh9uR8FxL/O@NSrrpwX@UbFw@UtdX37RGZgkuYRxS@qhIIa6mQ7oqvZydiA7X7waJDoNSdckROdtEPy2DPgr7@sbrXUvFT7N0sY7FfK80YSum7pt4K/3xUTr5fvtOtOtZP/ENymI@CSfwZjxVSSd@Yjde/ "PowerShell Core – Try It Online") Or [using `""::Join`](https://tio.run/##VVLbbpswGL7nKf4iF8EE0bbLSqiRqk7VLrpp2V0UTY5xQjaCMx9Kq9h@9dSHlnm@@MDf6TeHE5soFz0dhoYwTi9o154vJ8zxsUSyQpjvhb4@I9nm@c3NV3YYyxKxFkl9DasPEtCvat182tSIrT8uFk5a3DE1yuZztalMhuTFZNmyzMCtGpZljvVWE@3HsbyGXHvAYbsNSPLqn/mBas1qmBjX3ZUe5sCDdwZ@6K7SgAYNBRSF7pkSVO85pWNIFR7DFhIMruQ2rXq0@8MTNepUj3ag0nRsGi19ohz2bBwxGHhhCnytsR4fE80ng@zTCe96Au27/ntONsFRkd6VTtpVW3vYgb8Sbc2tJb0if8BMjHWaqaELU3UcO0e96sDLOGxiKmKoS8hgi/eevU0Ps@opCPeChfUA2xeQPbXu17COxiB6PzbMnp1vQuJ/Y1zKVVfuq3xh/B6Tvvm2/U2JhHOYhyR9ljUg0mMu3JU@n5xIO2jdfxUdnAo1SEcUaBf9sAz2LOjr76s7JSQ7xt7NMhb7tVKEUCF819zb0L/vlbPvp@90q431M3@fHOa9YBZ/xGOFVNJnMnN5BQ) Or [using `$ofs`](https://tio.run/##VVJbb5swFH7nV5wiF4UJom3vqJGqTn3qpmVvUTQ55iS0JTizTWkV238986Vlnh8@4@92TMKJTyhkh31fMy7wQvbN@XKigh4XRJWEioPU12fC97JZEN4Qpa9h/UkB@V1u6i/bjKgmJ07ZfF4u3ba85eOg6q/ltsyNEy8my1aLDNyqYLXIqd5ppv04nleQaw80HHcBWV7@M9@j1ryCiQvdXul@Dtx7Z@D79ioNaNBQQFHojo8S9UEgDiFVeAxHSDC4kse06sEeHl/QjKdqsD0q0/JpsPiCAg58GCgYeOMj@FpjPT4kmk8G2acT3vUE2nf99558guPIOlc6aVdt7eMe/M60NTeWdSN7BjNx3mo@9m2YquPYOepVB16m4RBTEUNdQgZbfPbsTXqZdYcg3Q8srQfYvYHq0LpPwzqaguz82DB7dr4Lif@dcSlXXbp/5RsXd5R19ffdEzIF5zCPKHxVFRDWUSHdjq8nJ2ILjfu8okOgHHvliILsox9WwZ4FffNjfTtKxY@xd7uKxX6tR8ZQSt8199b456Ny9v3ynW41sX7m75LLfBTM4s94rZBK@kxmLn8B) [Answer] # [Go](https://go.dev), 121 bytes ``` import."strings" type S=string func f(s,c S)S{for _,r:=range c{L:=Split(s,S(r)) l:=len(L)-1 s=Join(L[:l],L[l])} return s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVLLitswFIUu9RU3hgk29ZROVyXgznYoYSh4mTFFkeUHUSRXkscNlv0j3YRCP6Kf0n5Cv6J6JMGbK91zzzlXj_vjZy3OvztMDrimcMQtR-2xE1K_i6qjjn71urr_-Od0xZSWLa9VhPSpo5BnIUdVzwlUsUoJ5Ek-VkLC11RuMom5dSXjdpPlHWu1ZeSxTBLENhmjPN4m9w9IZZ9Fa_e7DSvS7Y4VyYQk1b3koKZwgL9v_vkW7nxxAiPSVGkFmwx2xa4IhxjRGGGzN8Q0lDERpRAZF7BP9z6SaEot7YkaI1IYhDTlyrAb9clxPM7KVaAaMLCG9do0olfU1JJS7vlrF30Ki-hZi20weZ7r9pVOfZfymVE9lWLgM32lEmrBOYYJTqIHZzjNLj4vak7py069wK2Ph53X5VZigGNPGms3GGs6z20FbiVmnh5n0vTkANMgRGlEz0rfz4SGN6mr2uDK2CdBFaK3W4CeFvYOfQzHyBsKyj6kml2A_Ql0Q2ch6WxhDKpxDX3XG_NSWPAviFU50wmhMFLafXkYqjABI7Kf70C9e18g0mCpQvZQIPq9o0TTMgAfCoSJ7jFzqR1VLVNPT5A4OAhu9CyDwEToix0sXcXR3Td4CzZkcKdf3P87OXh9CuKQIPs0K-szXgW10ADZJ6t54QPm-rq30uCd3vrZafcqZifb3fQy8udzWP8D) [Answer] # [Perl 5](https://www.perl.org/) `-lp`, ~~64~~, 61 bytes ``` s/(\S+) //;for$c($1=~/./g){@a=split/\Q$c/;$_=join pop(@a),@a} ``` [Try it online!](https://tio.run/##FY7BasMwEETv/ootGONQt6KHnoKpjzkVSq6Bosgby62qFZYVE7raT6/rMDADb@YwASf3uq5R1afj4w6U2l9oKk1dvrSintWw@@10G4MbZ3X6KI3al5/tF40eAoW607um03ldGTSf2bBF56hgOCAzNbDQxP0Du4Ir4E0VVBVbShF5mBB9kQXeZRivmFNovDicc0@LF7ziBAN5ryHDjRIUvE0PtMBPMnZjC2@NyHiBexqW/CbGJvMNeSHqmZLroRA4WoS4nYpyNzjfYLYoNKFsWEO0fxTmkXxcn1z4Bw "Perl 5 – Try It Online") Another using regex # [Perl 5](https://www.perl.org/) `-lp`, ~~64~~, 54 bytes ``` s/^(\S)(?|.*\K\1(?=.*\1(.*)$)|(.*)\1.*)/$2/&&redo;s; ; ``` [Try it online!](https://tio.run/##FU7BaoNAFLz7Fa8QFg1pxEJPUrwGCr3kKgWjr65ku0923Ujg7fv02pWBmWFmDjOjM@/b5svvvL0WecPnY/vZVnnzkUyVn4/FoeBd2ipReXgrlXI4UO1rqLeNoeMb96zRGMoYLshMJ1jJ8fDCJmMFnKBAKdYUPPLoEG0WBb5knB4Yw3yyYnCJA61W8IEORrK2gwhPCpBxml5ohd/Q65StnBqR6Qd27VliI70O/R3iSjQwBTNAJnDVCD6d8rIT3J6waBRyKCnuwOs/mpeJrN9ezfwP "Perl 5 – Try It Online") [Answer] # Java 10, ~~121~~ ~~101~~ 99 bytes ``` a->s->{int i;for(var c:a)s=s.substring(0,i=s.lastIndexOf(c)).replace(c,s.substring(i+1));return s;} ``` -17 bytes (and an additional -3 implicit) thanks to *@NahuelFouilleul* by using `substring`s instead of `split` to an array. -2 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jZHNjtsgEMfveYoph6ytONbmuummh0rV9tD2kGOUA8HjmCwBiw@7UYBjH6CP2BdJcXYtpTkVCQZmfgzzZw60o/ND9XphghoD3yiX5wmAsdRyBocULZ3loqydZJYrWX5533xcW83lfrMt/oMq4M2uVlDD84XOV2a@OnNpgS9rpbOOamBPNDfPpjRuZ65w9ljwdE512a@ywp8/6ozleamxFZRhxopbls8Web7UaJ2WYJbhspwkGa3biSTjXU2neAXHpDAba6f5IBZgrMGisZ@pwSeJPYzQZvsGDeNMPCnIC3qvCuiV9tUHL0goboFpIjx4mMJ06hvlDPq9RpT/YiEm7Hvc8w6DawsZBdpQqV5G7FDDXklJIcBJObjLf735ono4OtYkpPcJjJHXMFjmY/gUWePYK4ReqcorJ6q7HEOGdYNgUAgThwV2J7ANRqUxJjcF05AQ8lH5@mQsHkvlbNmmX7FCZuSBzMb/2jxuZ6SAW88ieR7gz6/fQGZ1SdtWnLIbvDSt4DYjJHX0LrjYpk5e3w2TYYbLXw) **Explanation:** ``` a->s->{ // Method with String-array & String parameters and String return int i; // Index-integer `i`, starting uninitialized for(var c:a) // Loop over the input-characters: s= // Overwrite String `s` with: s.substring(0,i=s.lastIndexOf(c)) // A substring until (excluding) the last occurrence of the // current character (and also set `i` to this last index // of the character at the same time) .replace(c, // From which the current character is replaced with s.substring(i+1));// the trailing substring after index `i` return s;} // Return the modified `s` as result-String ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` Fη«≔⪪θιυ≔⪫υ⊟υθ»θ ``` [Try it online!](https://tio.run/##PcqxDsIgEIDhWZ7iRkjwCToYN@PUxCdorqkQkWupJ4Mcr464OP3D96ObEtIUWlsogXYGPupw3nd/j/q2Bv/SmwVvLLAZ/nAlHzVbGGnVbDpuHUWNycf@m6G1C2V4MjoQyGUCqdUv8CuWKqeKjvEBkonmQhxmUEVqO77DFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal doesn't have a good way to refer to the split string twice, so it costs a block and an assignment. ``` Fη« ``` Loop over the list of characters. ``` ≔⪪θιυ ``` Split the string. ``` ≔⪫υ⊟υθ ``` Join it on the popped element. ``` »θ ``` Output the final result. [Answer] # [Python](https://www.python.org), 59 bytes ``` lambda x,y:[x:=(z:=x.split(i)).pop().join(z)for i in y][-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9BTsMwEEX3nGLYJLaURuoOBUVsWXGB0kUaO4mp67HSuEmqsS_STSQEd2LJTUhbhFSx-ot58_T_6dOOXYNmeq_y1w_XVYuHr0dd7DaigCEZs9WQ5eyY5UO6t1p1THGeWrSMp2-oDDvyCltQoAyM69Viuf5VfNtWmY5VLC5oQyU1UmuME4gp5vzu7_gsiTCBHlsS96T_AwQEEUQRNej2kupWSnOhohvsJdTqIL2zCZigZecF9ibIg2yhRmMK8DCig_OnD7cNsIedK5uZ6GnmQlAVnLOk4J9C2bhyC75HFIROi1kR00VxHTpN1_wB) [Answer] # [R](https://www.r-project.org), 95 bytes ``` f=\(s,L,`?`=length,x=el(strsplit(s,L[1],T)),t=?x)`if`(?L,f(paste(x[-t],collapse=x[t]),L[-1]),s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVK9TsMwEJYYO_IEVyE1ieQObCwha4eqC2ylImni_AgTR7HTpNLFL8JSkHgoeBpsp6oMLHf25-_nHOftvT195OFnJ_Pl3ddzHj75gqxJHMUho3UhSzKElPlCtqJhlTSH29sdeQwCIsNoCOIqj_1oTXK_SYSk_rBdyh1JOWNJI2g4bOUu0JLlrW4imGK-r65z30twjymWlDHuEfDQC24gvIfEIntb05nmrSgiJ9DzFrM5Mpe7MiR7xLK54SIgLGCxwJJ3gmLRUlprgXsBDxce8bwgmCwsxa1W6SyN7UYV1YGOXUNqxagcM97Xih5oCwWv6wRGOPIO_gaNyg3aOHzjZiXG0cG1t4WNv7067-G1S0sd0KOOUarKwfQU1RiptOzSFxh7zjPkHcv-TYC_R7jYGYUuRpLYzeQ0VRvhgJY2rQ0amcEeSgpCf3yhTIH9EWRJFW-p0nACojSvpM6vdCGfzxzJGdHC2fRrnE5T_wE) [Answer] # [Haskell](https://www.haskell.org/), 89 85 bytes ``` f=foldl(\s c->(\(a,b)->reverse$tail b>>=(\x->last$[x]:[a|x==c])).span(c/=)$reverse s) ``` [Try it online!](https://tio.run/##fZBBa4NAEIXPza94FRGFpL0XNNeeeukx5rCua1ay2QmuRgPj/nW7QiktpZ3DDAzfvHkzWrizMmZZmrwhU5u0dJC7Ii1Tsa2yXdGpm@qcinvRGlRFkafltCuMcH18mI4vB8FTnstjlj25q7CpfM6z@HMGLlsuorXIUROuXWt7xGgQCa5Ysg5rKULE0QZf8Y16Vcy0xUgd149s/iEZjARJwpoGp/jUKWVXPPmDf/On9qbm4bq13qh@rmm0fvWME1krMONOA4LC7KPNw09TNOIySB2YkQPpfdtgrZL9vPdSD/KMeSSqmQZTryL8W@Vdh@eE851fE6o7eq08dcqHtoDTYcxHywc "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org), 81 bytes ``` \(x,y)Reduce(\(x,y)paste(head(a<-el(strsplit(x,y,T)),-1),collapse=tail(a,1)),y,x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZU6xCsIwFNz9ipApgXTo5mBxdVUcFQkvr7YYSWgS2kKTH3Gpg1_g1_g3VuvmcBx3B3d3uzfjs8GzlXA5KQRztQ06VzyCL7Pla3tgnej5DlUAZLOw0nlkFUrF5CpDzZxvnNW1_6Riz7nIci7AaC2tw8LLWjMp8snvRcd_xceuoBvTkmuAikTSDpLElOqSfBiGFNcJqgAXEltj1GCCVoQu-gIYHaigcUKifPH__HtxHhnHmd8) Port of [unrelated string's Jelly answer](https://codegolf.stackexchange.com/a/265753/95126). ]
[Question] [ *This is a simpler variant of my previous challenge [Don't touch the walls!](https://codegolf.stackexchange.com/q/248571), as suggested by [Jonah](https://codegolf.stackexchange.com/users/15469/jonah).* Given a multi-dimensional rectangular array of integers between 0 and 9, output all the elements which are "touching the edges". Output is very flexible: it can be in any order, and may be flattened or partially nested, but must contain every edge element the correct number of times, and may not contain any others. ## Specification "Touching the edges" is a hopefully fairly intuitive concept, but here is a specification: Let's use this array, with shape `4, 3`. ``` [[1, 3, 0], [2, 6, 7], [4, 0, 2], [0, 0, 0]] ``` Using *one-based indexing*, we can index any element of the array using two integers in the ranges \$ [1, 4] \$ and \$ [1, 3] \$. The elements which are touching the edge are those with coordinates of the form `1, y`, `4, y`, `x, 1`, or `x, 3`. So, formally, we can say, for an element to be "touching the edge", at least one part of its multidimensional indices is either 1 (the minimum possible coordinate), or the maximum possible coordinate (which is the size of the array in the respective dimension). Here is the same array with the elements which are "touching the edge" ***highlighted***: ``` [[***1***, ***3***, ***0***], [***2***, 6, ***7***], [***4***, 0, ***2***], [***0***, ***0***, ***0***]] ``` The output could be anything like: ``` 1 3 0 2 7 4 2 0 0 0 ``` ``` [1, 2, 4, 0, [0, 0, [2, 7, 0], [3]]] ``` ``` [[[[[[4]]]]], [[[0, 0, 0, 0]]], [[2, 2]], [1, 7, 3]] ``` --- For the 1-dimensional array `[3, 4, 9, 0, 0]`, the edges are `[***3***, 4, 9, 0, ***0***]`, so the output is `[3, 0]`. --- For this 3-dimensional array: ``` [[[4, 0, 4, 1], [0, 0, 5, 8], [6, 0, 0, 0], [0, 3, 7, 0]], [[4, 9, 8, 5], [0, 6, 4, 0], [0, 0, 0, 3], [0, 9, 6, 1]], [[0, 4, 7, 9], [0, 2, 0, 6], [0, 0, 0, 0], [7, 0, 3, 0]], [[0, 5, 3, 5], [0, 0, 0, 0], [6, 5, 3, 0], [4, 6, 0, 8]]] ``` the edges are: ``` [[[***4***, ***0***, ***4***, ***1***], [***0***, ***0***, ***5***, ***8***], [***6***, ***0***, ***0***, ***0***], [***0***, ***3***, ***7***, ***0***]], [[***4***, ***9***, ***8***, ***5***], [***0***, 6, 4, ***0***], [***0***, 0, 0, ***3***], [***0***, ***9***, ***6***, ***1***]], [[***0***, ***4***, ***7***, ***9***], [***0***, 2, 0, ***6***], [***0***, 0, 0, ***0***], [***7***, ***0***, ***3***, ***0***]], [[***0***, ***5***, ***3***, ***5***], [***0***, ***0***, ***0***, ***0***], [***6***, ***5***, ***3***, ***0***], [***4***, ***6***, ***0***, ***8***]]] ``` The output is something like: ``` [4, 0, 4, 1, 0, 0, 5, 8, 6, 0, 0, 0, 0, 3, 7, 0, 4, 9, 8, 5, 0, 0, 0, 3, 0, 9, 6, 1, 0, 4, 7, 9, 0, 6, 0, 0, 7, 0, 3, 0, 0, 5, 3, 5, 0, 0, 0, 0, 6, 5, 3, 0, 4, 6, 0, 8] ``` Imagine each inner 2-dimensional array as a cross-section of a 3-dimensional box. The only elements which are not *touching the edges* are the ones on the *inside* of the box. Note that arrays which have one of their dimensions as only 1, such as `[4]` or `[[3, 6, 5]]`, may need to be treated with care. Their respective outputs should be `[4]` and `[3, 6, 5]`. ## Rules * You do not need to handle empty arrays, e.g. `[]` or `[[[], [], []], [[], [], []]]` * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` def f(a):a[1:-1]*=a>[f];map(f,a[1:-1]) ``` [Try it online!](https://tio.run/##XVHLqoMwEN3nK4au9JIWozZWS/sjIQu5Va6LahAX5uvtZJKIvSDDmZyHx2js8jeN@ba9uh76pE2bVonmLPTPo32qXt/frUl6Hg7TbXibaV7gdzKW9dMMKwwjqIJDyaHmkOGjuVKCQ0GQgco5SA4V4ZIkOeEsyJ0@EDiF4yJ55XDzu/TikEk8vqDyfoZpyhe4oWlXSErMjonOt@81SURM8AUws94VOTnkv4SQWPm4QwdfuTh2@HLIyIe9pAKZ@0qMwN3dRUGHV60bBvbhbvry6jrjQLKmDP@SxWnmYVxgjeB0fp4itgHcaW4f "Python 2 – Try It Online") Expects a nested list and removes all non surface elements inplace. #### How? `a>[f]` uses that in Python 2 every list is greater than every function is greater than every number to check whether `a` is a nested or flat list. If nested the middle of `a` is multiplied by one, in other words, nothing changes. The recursion will then descend one level. If flat the middle of `a` is multiplied by zero, in other words, excised. This will stop the recursion because `map` will run over an empty list. [Answer] # [J](http://jsoftware.com/), 25 24 bytes ``` #~&,(<:0&e.@:|"1]#:i.)@$ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/levUdDRsrAzUUvUcrGqUDGOVrTL1NB1U/mty@TnpKeRmFhdn5qUrmHClJmfkK6QpZOoZKxijSBkZw@QMDRS0gQoUjEHwPwA "J – Try It Online") * Create multidimensional indices for each element using mixed base binary * Mod each of those by the (input dimensions- 1) * Check if the multidimensional index has a 0. If so, keep that element. Otherwise, remove it. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` MapAt[#0,#,2;;-2]~Check~#/._MapAt->{}& ``` [Try it online!](https://tio.run/##TU/LCsIwELz3K4SCp1HTJE1bilIRj4LgUURCUVrEB9JbSH@9JttWvc3sPHb3rpvqctdNXeruuux2@rVujiFDCJ7nM35qN9WlvLXhYn4mbbYydtrt3/WjKa7FtqyeRThtD6V@tCYwJoIAswgmhkMhISTBwAkxh5h10AhIZMQcMWSRiLypd8VIe6LABhspAknfMPGhDCniUVKugf0anHckmdOiIeT3JMhGiTuf@g8NDYnPfzf5e8Rv059PkTIQCX9taulDSZ8JN4qtDWz3AQ "Wolfram Language (Mathematica) – Try It Online") Replaces non-edge elements with `{}`. [Answer] # JavaScript, 44 bytes ``` f=a=>a.at?[a.shift(),a.pop()??a,a.map(f)]:[] ``` ``` f=a=>a.at?[a.shift(),a.pop()??a,a.map(f)]:[] test = a => console.log(JSON.stringify(f(a))) test([[[4, 0, 4, 1], [0, 0, 5, 8], [6, 0, 0, 0], [0, 3, 7, 0]], [[4, 9, 8, 5], [0, 6, 4, 0], [0, 0, 0, 3], [0, 9, 6, 1]], [[0, 4, 7, 9], [0, 2, 0, 6], [0, 0, 0, 0], [7, 0, 3, 0]], [[0, 5, 3, 5], [0, 0, 0, 0], [6, 5, 3, 0], [4, 6, 0, 8]]]) test([[1, 3, 0], [2, 6, 7], [4, 0, 2], [0, 0, 0]]) test([4]) test([[3, 6, 5]]) ``` [Answer] # [R](https://www.r-project.org), ~~60~~ 59 bytes *Edit: -1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` \(a,i=which(a|1,T))a[i[apply(i,1,\(x)!all(x-1&x-dim(a))),]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3rWM0EnUybcszMpMzNBJrDHVCNDUTozOjEwsKcio1MnUMdWI0KjQVE3NyNCp0DdUqdFMyczUSNTU1dWJjoUYEaSTaJhYVJVZqGFqZWOgka5joGOuYAJVwpQFVciHJmgIlTbFJGBpBtMHkICYvWAChAQ) [Answer] # [Factor](https://factorcode.org/), ~~73~~ ~~72~~ 83 bytes ``` : f ( x -- ) dup real? [ drop ] [ 1 cut 1 short cut* rot append . [ f ] each ] if ; ``` [Try it online!](https://tio.run/##ZU/BToQwFLzzFXNUkzXAFthlDx7NXvZiPBkPBIoQkdZSEg3h2/HxKIrKC2XevJl5pcxyq8z0@HC@3Kd4y2yFV2la2aCT771sc9lBG2ntpzZ1a1ErnLzzJcWLasopRYkrfGC3wzWKXsPIrLnDEwqjNJ4JBMh7S2dXKWNnfAOjLDKtZVvglhQl6WSWV/SpS5ymwQM9A5WAT2@AkbBPFeHAOObOd/weCeNx4zuSMnLzmHPWjFm/4CNNgl@@eVtC/DIP2fvjWzISTvD/@CLion/amPkFC771gX0j/XPbeN5A@0NSCPY6zqUGi9N1IbmT707w7dbO7dukDuwfuVZOYDvf8914Pn0B "Factor – Try It Online") Recursive function that (maybe) slices both ends off the input, prints them, then calls itself on all the remaining elements until an atom (real number) is reached. ((Now handles arrays with a single element properly at the cost of 11 bytes...)) [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 20 bytes ``` ⊢⌿⍥,⍨1∊¨⍳∘⍴∊¨¨∘⊂1,¨⍴ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R12LHvXsf9S7VOdR7wrDRx1dh1Y86t38qGPGo94tYB6QD@R0NRnqgGS2/NfketQ3Fag1TcNEAQiBQiYKBkCWIZA0UDBVsFAw09EACRto6hgrmIPlLIGipkCWmYIJkpwBUNwMrM8EqM4SSBuB1MBVgPQaQ001VjCFi5uB@SBdZkDSQvM/AA "APL (dzaima/APL) – Try It Online") `⍴` shape (length along each dimension) of the array `1,¨` prepend 1 to each …`∊¨¨∘⊂` for each of each of the following, is it a member of the corresponding element of that?  `⍳∘⍴` the indices of an array of the shape of the argument `1∊¨` for each of those, is 1 a member? …`⌿⍥,⍨` use that flattened, to filter the flattened…  `⊢` argument [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 19 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` 1¨⌾⊏⟜⍉⟜⌽⍟=⍟2∘≠˜⥊⊸/⥊ ``` `1¨` one for each `⌾⊏` of the elements of the first major cells (n−1 dimensional sub-array) `⟜⍉` of the single-step-rotated-axes version `⟜⌽` of the reverse `⍟=` done as many times as there are dimensions `⍟2` done twice `∘≠˜` of the self-inequality (an all-zero array of same shape) `⥊⊸/` when flattened, filters `⥊` the flattened argument [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkDHCqOKMvuKKj+KfnOKNieKfnOKMveKNnz3ijZ8y4oiY4omgy5zipYriirgv4qWKCkYgNOKAvzTigL804qWKNOKAvzDigL804oC/MeKAvzDigL8w4oC/NeKAvzjigL824oC/MOKAvzDigL8w4oC/MOKAvzPigL834oC/MOKAvzTigL854oC/OOKAvzXigL8w4oC/NuKAvzTigL8w4oC/MOKAvzDigL8w4oC/M+KAvzDigL854oC/NuKAvzHigL8w4oC/NOKAvzfigL854oC/MOKAvzLigL8w4oC/NuKAvzDigL8w4oC/MOKAvzDigL834oC/MOKAvzPigL8w4oC/MOKAvzXigL8z4oC/NeKAvzDigL8w4oC/MOKAvzDigL824oC/NeKAvzPigL8w4oC/NOKAvzbigL8w4oC/OAo=) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 84 bytes ``` L`(?<=\[(\[(?(3)$)((])|(?<-3>\[)|\d|,)+)*)\d|\d(?=(((\[)|(?<-6>])|\d|,)+(?(6)^)])*]) ``` [Try it online!](https://tio.run/##PY5BCsJADEX3nkMh0S9MOzptwbZLN95gGlGoCzcuxGXP5QG8WE3GVhj44eX/P3neXvfHNRtXdLyMpwu1h7qLpK8lz0smEh4Ubn3TRR66fgBveM06dD21NREZN0doZDZoOPCZhdfC4@e9wBhjBg8niDkCCtUdHHJVp@pEFjEmtEM2wT1KnQJ@BmMehVlhzgol9okGzbi5CD5NldIsOa2xQJVorvvwd1qmsMTUaT/6qXPeh8RcOtcuKUXkCw "Retina – Try It Online") Outputs each edge element on its own line but link is to test suite that joins on commas for convenience. Explanation: ``` L` ``` List matches. ``` (?<=\[(\[(?(3)$)((])|(?<-3>\[)|\d|,)+)*)\d| ``` Similar to the following, but using a lookbehind to find whether the element is the first in any of its dimensions. Due to the way lookbehinds are evaluated, this version is harder to explain, so you'll just have to take my word for it that it's the mirror image of the following test. ``` \d(?= ``` Match a digit. In Retina 1 it's possible to use overlapping matches and captures to avoid using a lookahead but it costs 7 bytes to do that and you only save 4 so it's not worth it. ``` (((\[)|(?<-6>])|\d|,)+(?(6)^) ``` Match any number of brackets, digits, or commas, but there must be the same number of opening and closing brackets. ``` ])* ``` Match the close bracket at the end of this subarray, thus considering the parent subarray. Go out as many dimensions as necessary. ``` ]) ``` Match an extra close bracket, showing that this element or one of its container subarrays was the last in its parent. Replacing the `L` with `!` results in a version that works in Retina 0.8.2 but in this case it's no longer possible to use the same test suite. [Answer] # Python3, 95 bytes: ``` f=lambda x,t=0:[x]*t if x*0==0 else f(x[0],1)+[j for k in x[1:-1]if(j:=f(k,t or 0))]+f(x[-1],1) ``` [Try it online!](https://tio.run/##XZDNjoMgFIX3PsVdQnsnAbX4k/AkhEUnLaltxxqHBfP0Dn8a24QQrueczwPTn729xqqd5mUx8nn@@b6cwaGVrFdOHywMBtyBScng@vy9giFOMY2cHtUdzGuGBwwjOMX7L64HQ@69NOSBFrzEKNXHEPCSTyzTPIyWGKIqhBqhQ2B@aUqLTVEcoQofsQBVIgiEJp7raC7jmeXgezJb/M6Da7WdENo0ixTL9Kj7XzWRhIXnqlSq9aHNISKR7Ykht81dtPCVkAp4Zrc5ypgQH4RMbBJu1yFVrvYd3hJi1fNcxwIs3DI8yPIP) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒJ%þ`ṪỊ§TịF ``` A monadic Link that accepts a rectangular multi-dimensional list and yields the elements that are on its "surface". **[Try it online!](https://tio.run/##y0rNyan8///oJC/Vw/sSHu5c9XB316HlIQ93d7v9//8/OjraREfBQEcBSBrG6nApKEQbgPmmOgoWEL4ZmA9CcHljHQVzEB8owKUANsESqByoCa7CDGyiAbKJIH1wviVYiSHMBIgDgGZawlUYgXWYoZkANdEcYhySGyBONkZ2A4oOM5g8lG8CdoAByJexsQA "Jelly – Try It Online")** ### How? ``` ŒJ%þ`ṪỊ§TịF - Link: rectangular multi-dimensional list, M ŒJ - multi-dimensional indices of M -> [[1,1,1,...],...,[height,width,depth,...]] ` - use as both arguments of: þ - make a table of: % - modulo (vectorises) Ṫ - tail -> [...[x%height,y%width,z%depth,...]...] Ị - abs(x)<=1? (vectorises) § - sums (of those) T - truthy indices (of that) F - flatten (M) (N.B. same order as the indices produced by ŒJ) ị - index-into ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜s"DdiëdƶZ%2‹εZ≠i®.V"©.V˜Ï ``` 05AB1E is very verbose with recursive approaches, and it's also not too good in most matrix-based challenges, so the combination ends up as this horrendously long program (although can probably still be golfed a bit). [Try it online](https://tio.run/##HY4/SgNBHEbvErB7hP39m9npPUOKDFsosdjKIhewtfICKWyDYKdgm4BNwEPkIutMuu8V7/E97x8e56dluRz2q/vdfP7Y/X5v7/T68vP3tb2@vs@nz/VmdTquN5fD@W1Zaq2CYvhEDRKZsa2CDIgg2kAMcSSQNDWskpERKejQUJuvqKE9oYEmNKM9owUbMMH0ZpphjgWWGlrGRqzgveOCK96e9I4HnvCMjzfTCzEQQvRHYYQTQfROZGIkCql3kpCUZCSfpukf) or [verify all test cases](https://tio.run/##PVGxTkJBEOz9CvISuwl5e3t7986GhsbKjoKXV2iwoFETwMTO1sofoLA1JnaS2EJiQ@JH8CO4u4DV3s7Nzs3s3c@ub6a3@8fq8u5hMb/oVYMnnFVXi/mpG@63y1k1nEw3H5Of1fg87J6/f7/Gu5e36fqzP6rW7/3Rdrl53WO9GuzbtiUw6g5tQELWGlEjaK211l2HXsuIKN5p0zohgo4UQaOnhAPdMEb2QWMWNBBHk87UJ1mwn4qi5ExTzCiOBr1P/0ybyTZx1LQX@ah5uk@O1W7enDSd@47ulxWS7mCdVFzTKFEsrVsvoBpEIAtNDNJsAkr@GmVQAyoIviKdDwiMYBJBEBJCRjCZUMDqUrcZfJIZHMFqzLJwBjfgguguCTEgqhPTiYKo28mIzWFrBaIpCWKORMNGiEBMRzJEN6qL89yEpN@mCaMm7v4A). **Explanation:** ``` ˜ # Flatten the (implicit) multi-dimensional input-list s # Swap to get the actual input again "..." # Push the recursive string explained below © # Store it in variable `®` (without popping) .V # Evaluate and execute it as 05AB1E code, # using the multi-dimensional list as argument ˜ # Flatten the result as well Ï # Keep all values of the flattened input at the truthy (==1) indices # (after which the result is output implicitly) D # Copy the current list or integer dië # If it's a list: i # If d # the current value is truthy after a >=0 check: # (only a non-negative integer would be truthy, and lists falsey) # Do nothing ë # Else (it's a list): d # Transform each integer to a 1 with a >=0 check ƶ # Multiply each 1 by its 1-based index Z # Push the flattened maximum integer (without popping) % # Modulo 2‹ # Check which are smaller than 2 (first row=1s; last row=0s) # (all first and last items are now 1s) ε # Then map over each inner list: Z # Push the flattened maximum (without popping) ≠i # If this maximum is NOT 1: ®.V # Do a recursive call with the current inner list ``` ]
[Question] [ Consider you have a [hash function](https://en.wikipedia.org/wiki/Hash_function) \$\mathcal{H}\$ which takes strings of length \$2n\$ and returns strings of length \$n\$ and has the nice property that it is [*collision resistant*](https://en.wikipedia.org/wiki/Collision_resistance), i.e. it is hard to find two different strings \$s \neq s'\$ with the same hash \$\mathcal{H}(s) = \mathcal{H}(s')\$. You would now like to build a new hash function \$\mathcal{H'}\$ which takes strings of **arbitrary length** and maps them to strings of length \$n\$, while still being collision resistant. Lucky for you, already in 1979 a method now known as the [Merkle–Damgård construction](https://en.wikipedia.org/wiki/Merkle%E2%80%93Damg%C3%A5rd_construction) was published which achieves exactly this. The task of this challenge will be to implement this algorithm, so we'll first have a look at a formal description of the Merkle–Damgård construction, before going through a step-by-step example which should show that the approach is simpler than it might appear at first. > > Given some integer \$n > 0\$, a hash function \$\mathcal{H}\$ as > described above and an input string \$s\$ of arbitrary > length, the new hash function \$\mathcal{H'}\$ does the following: > > > * Set \$ l = |s|\$, the length of \$s\$, and split \$s\$ in chunks of length \$n\$, filling up the last chunk with **trailing** zeros if > necessary. This yields \$m = \lceil \frac{l}{n} \rceil \$ many chunks > which are labeled \$c\_1, c\_2, \dots, c\_m \$. > * Add a leading and a trailing chunk \$c\_0\$ and \$c\_{m+1}\$, where \$c\_0\$ is a string consisting of \$n\$ zeros and \$c\_{m+1}\$ is \$n\$ in binary, padded with **leading** zeros to length \$n\$. > * Now iteratively apply \$\mathcal{H}\$ to the current chunk \$c\_i\$ appended to the previous result \$r\_{i-1}\$: \$ r\_i = > \mathcal{H}(r\_{i-1}c\_i)\$, where \$r\_0 = c\_0\$. *(This step might be > more clear after looking at the example below.)* > * The output of \$\mathcal{H'}\$ is the final result \$r\_{m+1}\$. > > > ### The Task Write a program or function which takes as input a positive integer \$n\$, a hash function \$\mathcal{H}\$ as [black box](https://codegolf.meta.stackexchange.com/a/13706/56433) and a non-empty string \$s\$ and returns the same result as \$\mathcal{H'}\$ on the same inputs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. ### Example Let's say \$n = 5\$, so our given hash function \$\mathcal{H}\$ takes strings of length 10 and returns strings of length 5. * Given an input of \$s = \texttt{"Programming Puzzles"} \$, we get the following chunks: \$s\_1 = \texttt{"Progr"} \$, \$s\_2 = \texttt{"ammin"} \$, \$s\_3 = \texttt{"g Puz"} \$ and \$s\_4 = \texttt{"zles0"} \$. Note that \$s\_4\$ needed to be padded to length 5 with one trailing zero. * \$ c\_0 = \texttt{"00000"}\$ is just a string of five zeros and \$ c\_5 = \texttt{"00101"}\$ is five in binary (\$\texttt{101}\$), padded with two leading zeros. * Now the chunks are combined with \$\mathcal{H}\$: \$r\_0 = c\_0 = \texttt{"00000"} \$ \$ r\_1 = \mathcal{H}(r\_0c\_1) = \mathcal{H}(\texttt{"00000Progr"})\$ \$ r\_2 = \mathcal{H}(r\_1c\_2) = \mathcal{H}(\mathcal{H}(\texttt{"00000Progr"})\texttt{"ammin"})\$ \$ r\_3 = \mathcal{H}(r\_2c\_3) = \mathcal{H}(\mathcal{H}(\mathcal{H}(\texttt{"00000Progr"})\texttt{"ammin"})\texttt{"g Puz"})\$ \$ r\_4 = \mathcal{H}(r\_3c\_4) = \mathcal{H}(\mathcal{H}(\mathcal{H}(\mathcal{H}(\texttt{"00000Progr"})\texttt{"ammin"})\texttt{"g Puz"})\texttt{"zles0"})\$ \$ r\_5 = \mathcal{H}(r\_4c\_5) = \mathcal{H}(\mathcal{H}(\mathcal{H}(\mathcal{H}(\mathcal{H}(\texttt{"00000Progr"})\texttt{"ammin"})\texttt{"g Puz"})\texttt{"zles0"})\texttt{"00101"})\$ * \$r\_5\$ is our output. Let's have a look how this output would look depending on some choices1 for \$\mathcal{H}\$: * If \$\mathcal{H}(\texttt{"0123456789"}) = \texttt{"13579"}\$, i.e. \$\mathcal{H}\$ just returns every second character, we get: \$r\_1 = \mathcal{H}(\texttt{"00000Progr"}) = \texttt{"00Por"}\$ \$r\_2 = \mathcal{H}(\texttt{"00Porammin"}) = \texttt{"0oamn"}\$ \$r\_3 = \mathcal{H}(\texttt{"0oamng Puz"}) = \texttt{"omgPz"}\$ \$r\_4 = \mathcal{H}(\texttt{"omgPzzles0"}) = \texttt{"mPze0"}\$ \$r\_5 = \mathcal{H}(\texttt{"mPze000101"}) = \texttt{"Pe011"}\$ So \$\texttt{"Pe011"}\$ needs to be the output if such a \$\mathcal{H}\$ is given as black box function. * If \$\mathcal{H}\$ simply returns the first 5 chars of its input, the output of \$\mathcal{H'}\$ is \$\texttt{"00000"}\$. Similarly if \$\mathcal{H}\$ returns the last 5 chars, the output is \$\texttt{"00101"}\$. * If \$\mathcal{H}\$ multiplies the character codes of its input and returns the first five digits of this number, e.g. \$\mathcal{H}(\texttt{"PPCG123456"}) = \texttt{"56613"}\$, then \$\mathcal{H}'(\texttt{"Programming Puzzles"}) = \texttt{"91579"}\$. --- 1 For simplicity, those \$\mathcal{H}\$ are actually not collision resistant, though this does not matter for testing your submission. [Answer] # [Haskell](https://www.haskell.org/), ~~91~~ ~~90~~ 86 bytes * -1 byte thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) * -4 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) ``` n!h|let a='0'<$[1..n];c?""=c;c?z=h(c++take n(z++a))?drop n z=h.(++mapM(:"1")a!!n).(a?) ``` [Try it online!](https://tio.run/##fY5Ba4NAFITP8VeMSyD72K00h17aGP9AC4EejcjrZslK9EXUXKT/3a7k3sPweDPM8AUeb75tl0XS8Nv6CZzvXneHbbnPMqk@XKFU7uKZ86CdMRPfPETPxjBRcRnuPQQxy7QxHfdf@l3tFXGaCmWaC1oa6R/TiDzZlNBvFloFrWAMIUPsQJEiC3Ua7teBu66RK06PeW79qCjZ2GfnXNaWbW1/olzUJcpXeDmi5Gi6aPjqn5kqSTpuBDlWxho6Mn1Pw6esEGctFsFipHVQkCJgGz/Ck335Aw "Haskell – Try It Online") ## Explanation ``` a='0'<$[1..n] ``` Just assigns the string `"00...0"` (`'0'` \$n\$ times) to `a` --- ``` c?""=c c?z=h(c++take n(z++a))?drop n z ``` The function `?` implements the recursive application of `h`: `c` is the hash we have obtained so far (length \$n\$), `z` is the rest of the string. If `z` is empty then we simply return `c`, otherwise we take the first \$n\$ characters of `z` (possibly padding with zeros from `a`), prepend `c` and apply `h`. This gives the new hash, and then we call `?` recursively on this hash and the remaining characters of `z`. --- ``` n!h=h.(++mapM(:"1")a!!n).(a?) ``` The function `!` is the one actually solving the challenge. It takes `n`, `h` and `s` (implicit) as inputs. We compute `a?s`, and all we have to do is append `n` in binary and apply `h` once more. `mapM(:"1")a!!n` returns the binary representation of \$n\$. [Answer] # [R](https://www.r-project.org/), ~~159~~ 154 bytes ``` function(n,H,s,`?`=paste0,`*`=strrep,`/`=Reduce,`+`=nchar,S=0*n?s?0*-(+s%%-n)?"?"/n%/%2^(n:1-1)%%2)(function(x,y)H(x?y))/substring(S,s<-seq(,+S,n),s--n-1) ``` [Try it online!](https://tio.run/##jY/RSsNAEEXf@xUhENhJZ0laCIh0CYJIfLJYn2Vj3MRAO4k7G2j783G12kpF6OvMvWfO2LEOFnKsB6pc25EgLJBR51r1JTuToo61Ymet6VEnWj2a16EyqKdaUfVWWlypNKac8zSWYspRJAnyMA8TipJo/izoeiZnEEVzEMcbW9xBIbb5DiDh4cXTW2rECnkh2bwLnK6QAFlK8tXxZu2MpdIZ9qLBEcJwUBHfnicQ4yclxS8/n8M5/J0ATO5ayy47g/7GzDD7Sd22Tev4oV7azh91/5Z6vxeDq6@euntyfgUHyqQWpDJkFXpCY8vNxqeD5bDfrw2HWAQqOP0JF6QPWpcnzx6A8QM "R – Try It Online") Yuck! Answering [string](/questions/tagged/string "show questions tagged 'string'") challenges in R is never pretty, but this is horrible. This is an instructive answer on how not to write "normal" R code... *Thanks to [nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof) for fixing a bug, at a cost of 0 bytes!* *Thanks to [J.Doe](https://codegolf.stackexchange.com/users/81549/j-doe) for swapping the operator aliasing to change the precedence, good for -4 bytes.* The explanation below is for the previous version of the code, but the principles remain the same. ``` function(n,H,s, # harmless-looking function arguments with horrible default arguments # to prevent the use of {} and save two bytes # then come the default arguments, # replacing operators as aliases for commonly used functions: `+`=paste0, # paste0 with binary + `*`=strrep, # strrep for binary * `/`=Reduce, # Reduce with binary / `?`=nchar, # nchar with unary ? S= # final default argument S, the padded string: 0*n+ # rep 0 n times s+ # the original string 0*-((?s)%%-n)+ # 0 padding as a multiple of n "+"/n%/%2^(n:1-1)%%2) # n as an n-bit number # finally, the function body: (function(x,y)H(x+y)) / # Reduce/Fold (/) by H operating on x + y substring(S,seq(1,?S,n),seq(n,?S,n)) # operating on the n-length substrings of S ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 251 bytes ``` #define P sprintf(R, b(_){_=_>1?10*b(_/2)+_%2:_;}f(H,n,x)void(*H)(char*);char*x;{char R[2*n+1],c[n+1],*X=x;P"%0*d",n,0);while(strlen(x)>n){strncpy(c,x,n);x+=n;strcat(R,c);H(R);}P"%s%s%0*d",R,x,n-strlen(x),0);H(R);P"%s%0*d",R,n,b(n));H(R);strcpy(X,R);} ``` [Try it online!](https://tio.run/##VZFfa4MwFMXf/RSho5CkKVO7MrZg99pH8WngRGyMVmhvS7SdrfjZXf50g5GHk5/35HhvIpa1ENP0VMqqAYli1J5VA12FE@btcE6GPMo3wUfgU03PIVnk8/A952OFtwxYT66npsR0S7DYF4oSbqXng1GUpCGFRZAxkVqhn1HP49ncp@VMn/YJ/943B4nbTh0k4J5sgAwaQJxvWLCeAeH9IgKuv4mi0z0Jwrc4IXzUKa1eNikxzuVfiMm1Jut5OIDtMJBHwcTpP3wykzSZEZC8SnULoXRzaINtJPWzyEiQcSeWVo5CR2tHK0evjl4cvTlaZ5HPR0/fKzoWDWCzKVQtGLLXRPX@mmYEDR5CFf5thaE1Q7YUZITr0uNl9FRfMPtfUrK7KEA@98ZpitWpVsXx2ECN4sv9fpDtDw "C (gcc) – Try It Online") Not as clean as the bash solution, and highly improvable. The function is `f` taking `H` as a function that replaces its string input with that string's hash, `n` as in the description, and `x` the input string and output buffer. Description: ``` #define P sprintf(R, // Replace P with sprintf(R, leading to unbalanced parenthesis // This is replaced and expanded for the rest of the description b(_){ // Define b(x). It will return the integer binary expansion of _ // e.g. 5 -> 101 (still as integer) _=_>1? // If _ is greater than 1 10*b(_/2)+_%2 // return 10*binary expansion of _/2 + last binary digit :_;} // otherwise just _ f(H,n,x) // Define f(H,n,x) void(*H)(char*); // H is a function taking a string char*x; { // x is a string char R[2*n+1],c[n+1], // Declare R as a 2n-length string and c as a n-length string *X=x; // save x so we can overwrite it later sprintf(R,"%0*d",n,0); // print 'n' 0's into R while(strlen(x)>n){ // while x has at least n characters strncpy(c,x,n);x+=n; // 'move' the first n characters of x into c strcat(R,c); // concatenate c and R H(R);} // Hash R sprintf(R,"%s%s%0*d" // set R to two strings concatenated followed by some zeroes R,x, // the two strings being R and (what's left of) x n-strlen(x),0); // and n-len(x) zeroes H(R); // Hash R sprintf(R,"%s%*d",R,n, // append to R the decimal number, 0 padded to width n b(n)); // The binary expansion of n as a decimal number H(R);strcpy(X,R);} // Hash R and copy it into where x used to be ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->n,s,g{(([?0*n]*2*s).chop.scan(/.{#{n}}/)+["%0#{n}b"%n]).reduce{|s,x|g[s+x]}} ``` [Try it online!](https://tio.run/##FcbBCoMgGADg@54iGpGVWW3E2KH2Ct3FQ7lyg2XhP6FlPrvDy8en9PBzU@PyVmLAwiBEH2UqWXpJISH8tawEeC9RQczZSGuLJKNhVPoPYSRZQtT41Hw0B@DtEBSyjVnrRJO3YIBWLAN69dSem@fO7GnVXwgmWuO4U4tQ/Ty/pQg6ve@fEWIsmPsD "Ruby – Try It Online") ### How it works: ``` ([?0*n]*2*s).chop # Padding: add leading and trailing # zeros, then remove the last one .scan(/.{#{n}}/) # Split the string into chunks # of length n +["%0#{n}b"%n] # Add the trailing block .reduce{|s,x|g[s+x]} # Apply the hashing function # repeatedly ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` 0Ṿ;s;BṾ€ṚWƲ}z”0ZU0¦;Ç¥/ ``` [Try it online!](https://tio.run/##XZHNbtNAFIX38xSHFSChkLbKJlk58bixSMaWPRYqiIXlTJNBjqeaGVMlElLFBolHQO0KwYoVG9INSAXxHs6LmCGFVGIxP/feued@R/NSlOWqbTbvloek2XzokShurr/tbkc/v6PZfN1eXBIyjfwwOAEfhylYNh3SBA9c/SGsQm0EVOXWKexCuOBMu93itK4KK1Vl@uSgD/pK6BWMKFQ1Q7HIdV5YoclhH4HUxqJ3lzTk6C47k3NpzV9xJ61mdWH/hfsWFGomDJ77NPCyCX9ByImqUeQV8tIo@HRCOb3Fp4yHCcWYer5zkTsaLc7KvBCQFufSLrBStYY6r/YOOn/U9D7ENEs5uPeEwmM@EsqzhMFDypOQHT@C7IgOcpTS7EDjlV24JmO1rOY7J6Wo5m7OwX@6941DMXVpbwcMHaQ3CRw1xYSyYz5GFCDkKUIWZ7xDvNEoyhhHECWI3KsEQcZGPIxYeo@Q7cVV23V/OTCDoTu2bz431@@f/vryeu0q3WdZ9@bT4Mfbm4@P27aNtZrrfLl0gIjr9boUpu39Bg "Jelly – Try It Online") Accepts \$\mathcal H\$ at the line above it, \$s\$ as its left argument, and \$n\$ as its right argument. [Answer] # [Bash](https://www.gnu.org/software/bash/), 127-ε bytes ``` Z=`printf %0*d $1` R=$Z while IFS= read -rn$1 c;do R=$R$c$Z;R=`H<<<${R::2*$1}`;done H< <(printf $R%0*d $1 `bc <<<"obase=2;$1"`) ``` [Try it online!](https://tio.run/##LYxPC4IwGIfvfooXe0MN0hZ0ye0adpN1Ew@bulQwja0IlD77MvH28PvzFNI0NvEDmBwAoyrwTBTmfpgHUU6i2pvTTaNkBfvy9OeXbLuFvzZj4qnb/nWH7WFXARIBnGHmfJq2U3C93Bjo5al7JFDG1fDvOZaYxZyJhFKKEz@fjzskXzHXvXISCtRfrchXL4iihHntDoU0ih1jJK4IrE31UGv5eLR9Del7HDtlHHv6AQ "Bash – Try It Online") This works as a program/function/script/snippet. H must be resolveable to a program or function that will perform the hashing. N is the argument. Example call: ``` $ H() { > sed 's/.\(.\)/\1/g' > } $ ./wherever_you_put_the_script.sh 5 <<< "Programming Puzzles" # if you add a shebang Pe011 ``` Description: ``` Z=`printf %0*d $1` ``` This creates a string of `$1` zeroes. This works by calling printf and telling it to print an integer padded to ***extra argument*** width. That extra argument we pass is `$1`, the argument to the program/function/script which stores n. ``` R=$Z ``` This merely copies Z, our zero string, to R, our result string, in preparation for the hashing loop. ``` while IFS= read -rn$1 c; do ``` This loops over the input every `$1` (n) characters loading the read characters into c. If the input ends then c merely ends up too short. The `r` option ensures that any special characters in the input don't get bash-interpreted. This is the `-ε` in the title - that `r` isn't strictly necessary, but makes the function more accurately match the input. ``` R=$R$c$Z ``` This concatenates the n characters read from input to R along with zeroes for padding (too many zeroes for now). ``` R=`H<<<${R::2*$1}`;done ``` This uses a here string as input to the hash function. The contents `${R::2*$1}` are a somewhat esoteric bash parameter substitution which reads: R, starting from 0, only 2n characters. Here the loop ends and we finish with: ``` H< <(printf $R%0*d $1 `bc <<<"obase=2;$1"`) ``` Here the same format string trick is used to 0 pad the number. `bc` is used to convert it to binary by setting the output base (obase) to 2. The result is passed to the hash function/program whose output is not captured and thus is shown to the user. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes Since Pyth doesn't allow H to be used for a function name, I use `y` instead. ``` uy+GH+c.[E=`ZQQ.[ZQ.BQ*Z ``` [Try it online!](https://tio.run/##K6gsyfjvo2pUkvS/tFLb3UM7WS/a1TYhKjBQLzoqUM8pUCvq/39TLqWAovz0osTc3My8dIWA0qqqnNRiJQA "Pyth – Try It Online") Example is with the "every second character" version of H. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~79~~ 68 bytes ``` {reduce &^h o&[~],comb 0 x$^n~$^s~$n.fmt("%.{$n-$s.comb%-$n}b"): $n} ``` [Try it online!](https://tio.run/##HcrdCoIwGIDhW/kYUzTmRxF1UHQPnosDtc0Ut8WWkA536@vn6D143qew0zmqBVIJt@ituM@dgJQ/wKRVqFlnVAt7eFOuA@UuUI1SvTKSoKe6oA5/Q1JQvbUkv8C30TULyMz/pTqwIyLuahzNoDcGJwaktKa3jVKD7qGc13USjuTX@AE "Perl 6 – Try It Online") ### Explanation ``` { reduce # Reduce with &^h o&[~], # composition of string concat and hash function comb # Split string 0 x$^n # Zero repeated n times ~$^s # Append input string s ~$n.fmt(" # Append n formatted %. # with leading zeroes, {$n # field width n for final chunk -$s.comb%-$n} # -(len(s)%-n) for padding, b") # as binary number : # Method call with colon syntax $n # Split into substrings of length n } ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 47 bytes ``` ~:π'0'*:s\+s+π/);[sπ2base{48+}%+0π->]+{+1$~}*\; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPmfp1r9v87qfIO6gbqWVXGMdrH2@QZ9Tevo4vMNRkmJxanVJhbataraBucbdO1itau1DVXqarVirP/XquZp/a82tDNSrVVQDyjKTy9KzM3NzEtXCCitqspJLVZXMOWqNrXBJ2mHR7Jaq1YrAZ92AA "GolfScript – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 143 bytes ``` import StdEnv r=['0':r] $n h s=foldl(\a b=h(a++b))(r%(1,n))([(s++r)%(i,i+n-1)\\i<-[0,n..length s]]++[['0'+toChar((n>>(n-p))rem 2)\\p<-[1..n]]]) ``` [Try it online!](https://tio.run/##JY7NSgMxFEb3fYq7aJ2EzIRWcCOdbtSFIDjQZZJFOr@B5GZIUsHisxuj7s63OIevt6PG7PxwtSM4bTAbt/qQ4JyGF/zYhFZU@@oxqM0WYYHYTt4OlkgNl3YhmrELpSTsyKHGAoJExgLdEVMbhs2BSmmOjdjXyLkdcU6loBRj4jfKkn9adCAETyeCzUppGB3cF2ctzoFzVErRfE663GlhCw9AZCwkein7YxPv/tqcqy8T34cBjKIgqi74OWjnDM7QXW83O8ZK5e9@snqOuXl9y8@fqJ3p/0dndZp8cD8 "Clean – Try It Online") [Answer] # [oK](https://github.com/JohnEarnest/ok), 41 bytes ``` {(x#48)(y@,)/(0N,x)#z,,/$((x+x!-#z)#2)\x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqNC2cRCU6PSQUdTX8PAT6dCU7lKR0dfRUOjQrtCUVe5SlPZSDOmovZ/mp66hoapdXWFg5qRoqJyRa21UkBRfnpRYm5uZl66QkBpVVVOarGSJhdIkamyipY@TiWa/wE "K (oK) – Try It Online") ``` { } /x is n, y is H, z is s. (x+x!-#z) /number of padding 0's needed + x ( #2)\x /binary(x) with this length ,/$ /to string z, /append to z (0N,x)# /split into groups of length x (y@,)/ /foldl of y(concat(left, right))... (x#48) /...with "0"*x as the first left string ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~126~~ 113 bytes ``` lambda n,H,s:reduce(lambda x,y:H(x+y),re.findall('.'*n,'0'*n+s+'0'*(n-len(s)%n))+[bin(n)[2:].zfill(n)]) import re ``` [Try it online!](https://tio.run/##XY6xCoMwFEV3vyJLSV6TSit0CXR3dLcOaU1sIHmGGEH9@dRCu3Q5Bw5cuGFNrxGrbG737JR/9IqgqMUko@7np2bftohV1mzhK4ioS2OxV84xWtIjCnreySf@McOT08gmOCAAbx8WGUJbya7cjN0XCB0U1ocxJhJ1DtFiIoZZDHNiIP4M@Vr8DsilvUhZdQVt4jhE5b3FgTTzttE3 "Python 2 – Try It Online") -13 thanks to [Triggernometry](https://codegolf.stackexchange.com/users/73368/triggernometry). Yeah, this is an abomination, why can't I just use a built-in to split a string into chunks...? :-( [Answer] # [Python 2](https://docs.python.org/2/), ~~106~~ 102 bytes For once, the function outgolfs the lambda. -4 bytes for simple syntax manipulation, thanks to Jo King. ``` def f(n,H,s): x='0'*n;s+='0'*(n-len(s)%n)+bin(n)[2:].zfill(n) while s:x=H(x+s[:n]);s=s[n:] return x ``` [Try it online!](https://tio.run/##XY2xDoMgFAB3vuItDVBt05p0ecbd0d0waEQlwacBTKk/T03HTnc33fYJ80pFSoMeYRSU17mXyCBW/MGvVPrsJ4JuVpPw8kIy6w0Jkm2B6n6MxtozGLxnYzV4jFUtYuZbJCVLX/mWUDFwOuyOIKbNGQrnyNC2ByHzP8r0YrZb@qGDiLF9IhaK8catk@uWxdAEzX4cVnv@BQ "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` òV ú'0 pV¤ùTV)rÈ+Y gOvW}VçT ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=8lYg+icwIHBWpPlUVilyyCtZIGdPdld9VudU&input=IlByb2dyYW1taW5nIFB1enpsZXMiCjUKIl/rMiwxIgotUQ==) I haven't found any capability for Japt to take functions directly as an input, so this takes a string which is interpreted as Japt code and expects it to define a function. Specifically, `OvW` takes the third input and interprets it as Japt, then `g` calls it. Replacing that with `OxW` allows input as a Javascript function instead, or if the function were (somehow) already stored in W it could just be `W` and save 2 bytes. The link above has the worked example of \$\mathcal{H}\$ that takes characters at odd indexes, while [this one](https://ethproductions.github.io/japt/?v=1.4.6&code=8lYg+icwIHBWpPlUVilyyCtZIGdPdld9VudU&input=IlByb2dyYW1taW5nIFB1enpsZXMiCjUKIl9xIG1jINdzIHMwLDUiCi1R) is the "multiply char-codes and take the 5 highest digits" example. Due to the way Japt takes inputs, \$s\$ will be `U`, \$n\$ will be `V`, and \$\mathcal{H}\$ will be `W` Explanation: ``` òV Split U into segments of length V ú'0 Right-pad the short segment with "0" to the same length as the others p ) Add an extra element: V¤ V as a base-2 string ùTV Left-pad with "0" until it is V digits long r Reduce... VçT ...Starting with "0" repeated V times... È } ...By applying: +Y Combine with the previous result gOvW And run W as Japt code ``` ]
[Question] [ I ran into this problem while working on another challenge I'm making for this site. In that challenge I utilize "[Mario Kart 8 Scoring](http://mariokart.wikia.com/wiki/Driver%27s_Points)". The amount of points the player in *k*th place gets is represented by this 1-indexed array: [15,12,10,9,8,7,6,5,4,3,2,1]. So 1st place gets 15 points, 2nd place gets 12 points, etc. It's easy enough to assign points like this, however the tricky part comes with how I handle ties. What I do is give each tying player the average of the points given for each tying place. For example, if only 1st and 2nd tied, then both players get (15+12)/2 = 13.5 points. (Note: You're allowed to round to the nearest int, so 13 or 14 are both also acceptable.) Then 3rd - 12th place get the normal amount of points for their position. ## Challenge Given 12 non-negative integer scores that are decreasingly sorted, output the number of points each player gets. You can also take the points list [15,12,10,9,...] as input. Note that the number of points each player gets does not depend on the actual values of the scores, but how they compare to the other scores. ## Test Cases * [21,21,15,14,12,9,6,5,4,3,2,1] => [**14,14**,10,9,8,7,6,5,4,3,2,1] * [20,15,15,15,10,9,8,7,6,5,4,3] => [15,**10,10,10**,8,7,6,5,4,3,2,1] + explanation: (12+10+9)/3 = 10.3333 * [1,1,1,1,1,1,1,1,1,1,1,1] => [**7,7,7,7,7,7,7,7,7,7,7,7**] + explanation: (15+12+10+9+8+7+6+5+4+3+2+1)/12 = 6.8333 * [20,20,20,20,10,10,10,9,8,7,6,5] => [**12,12,12,12**,***7,7,7***,5,4,3,2,1] + explanation: (15+12+10+9)/4 = 11.5, (8+7+6)/3 = 7 * [100,99,98,95,95,95,94,93,93,92,91,91] => [15,12,10,**8,8,8**,6,**5,5**,3,**2,2**] + explanation: (9+8+7)/3 = 8, (5+4)/2 = 4.5, (2+1)/2 = 1.5 Related: [Rank a list of scores with "skips"](https://codegolf.stackexchange.com/questions/35528/rank-a-list-of-scores-with-skips) [Answer] # JavaScript (ES6), 57 bytes Takes input in currying syntax `(p)(s)`, where ***p*** is the list of points and ***s*** is the list of scores. ``` p=>s=>s.map(v=>s.reduce((t,x,i)=>x-v?t:t+p[n++,i],n=0)/n) ``` ### Test cases ``` let f = p=>s=>s.map(v=>s.reduce((t,x,i)=>x-v?t:t+p[n++,i],n=0)/n) points = [15,12,10,9,8,7,6,5,4,3,2,1]; console.log(JSON.stringify(f(points)([21,21,15,14,12,9,6,5,4,3,2,1]))) console.log(JSON.stringify(f(points)([20,15,15,15,10,9,8,7,6,5,4,3]))) console.log(JSON.stringify(f(points)([1,1,1,1,1,1,1,1,1,1,1,1]))) console.log(JSON.stringify(f(points)([20,20,20,20,10,10,10,9,8,7,6,5]))) console.log(JSON.stringify(f(points)([100,99,98,95,95,95,94,93,93,92,91,91]))) ``` [Answer] # [R](https://www.r-project.org/), 3 bytes Apparently R has a built-in for this. Takes a list of `p`oints and `s`cores as input. ``` ave ``` [Try it online!](https://tio.run/##Nck7CoAwEADR3pMkMEU2H80WHiaIfTDg9dcoCK@auazvh5OCRCSgVDZWCpnETH4Z7w9zKVrR8sto@kRUJm/tPl1neLMH "R – Try It Online") Example: ``` p=c(15,12,10,9,8,7,6,5,4,3,2,1) > ave(p,c(20,15,15,15,10,9,8,7,6,5,4,3)) [1] 15.00000 10.33333 10.33333 10.33333 8.00000 7.00000 6.00000 5.00000 4.00000 3.00000 2.00000 1.00000 > ave(p,c(1,1,1,1,1,1,1,1,1,1,1,1)) [1] 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 ``` [Answer] # [Perl 5](https://www.perl.org/), 109 +1 (-a) = 110 bytes ``` @p=(1..10,12,15);while(@F){$/=$,=0;do{$,++;$/+=pop@p}while($w=shift@F)==$F[0];push@r,(int.5+$//$,)x$,}say"@r" ``` [Try it online!](https://tio.run/##PcrdCoIwGADQVxnyXUw29yOsH8ZgV971BNGFkOFA3IczLMRXbwVRcC4PdtNgcvboqBZCK65rrk1plz4MHfVNuYJ0wJ2y17gCZ8yCZA4jety@BxaX@nCbP9c5aM7qYvGeej9xGsZZGAZSAi8fwLfUPgs/FTnXivzpnyM5kD3ZEfOKOIc4plydjFBa5ap9Aw "Perl 5 – Try It Online") Includes 17 bytes to hardcode the point values. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes *2 bytes off thanks to [@geokavel](https://codegolf.stackexchange.com/users/46313/geokavel)!* ``` 7#uti2XQw) ``` Inputs are a column vector (`;` as separator) of integer scores and a column vector with the points. The output contains the results separated by newlines. [Try it online!](https://tio.run/##y00syfn/31y5tCTTKCKwXPP//2gjQ2sgMjS1NjSxNjSytrQ2sza1NrE2tjayNozligZJAFkGQAkLa3MUSQA) Or [verify all test cases](https://tio.run/##y00syfmf8N9cubQk0ygisFzzv6JLyP9oI0NrIDI0tTY0sTY0sra0NrM2tTaxNrY2sjaM5YoGSQBZBkAJC2tzNEkjA7BGCEJTQkgv0E5skAgr4cgQhuAKCVpqABS3tLa0sLY0hSETa0tjMAJ63hCI8JsBAA). ### Explanation ``` % Implicitly take first input. % STACK: [21;21;15;14;12;9;6;5;4;3;2;1] 7#u % Unique consecutive integer labels % STACK: [1;1;2;3;4;5;6;7;8;9;10;11] t % Duplicate % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [1;1;2;3;4;5;6;7;8;9;10;11] i % Take second input % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [1;1;2;3;4;5;6;7;8;9;10;11], [15;12;10;9;8;7;6;5;4;3;2;1] 2XQ % Average second argument as grouped by the first % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [13.5;10;9;8;7;6;5;4;3;2;1] w % Swap % STACK: [[13.5;10;9;8;7;6;5;4;3;2;1], [1;1;2;3;4;5;6;7;8;9;10;11] ) % Reference indexing % STACK: [13.5;10;9;8;7;6;5;4;3;2;1] % Implicitly display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` γ€g£vygFyÅAˆ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OZHTWvSDy0uq0x3qzzc6ni67f//aEMDAx1LSx1LCx1LUxgy0bE0BiMjHUtDIIrlijY01TE00jEEqtWx0DHXMdMx1THRMdYBCsUCAA "05AB1E – Try It Online") **Explanation** ``` γ # group the scores into chunks of consecutive equal elements €g # get the length of each chunk £ # split the points list into chunks of these sizes v # for each chunk y in the points list ygF # len(y) times do: yÅA # get the arithmetic mean of y ˆ # add to global list # implicitly output global list ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 154 bytes ``` x=>s=>{for(int i=0;i<12;){int b=0,j=i,a=0,c=0;for(;j<12&&x[i]==x[j];j++,b++){a+=s[j];}a=(int)Math.Round(a/(b+.0));for(;c<b;c++){x[i+c]=a;}i+=b;}return x;} ``` [Try it online!](https://tio.run/##VU89b4MwEJ3DrzhliGxxpZCPNsgxS6UOVbM0QwfEYBw3NUpMhElKhfjt1FBFan3PZ9979judtHeyrFRvxEnZs5AKdt@2VqfWk0dhLZxbz9ai1hKeL0ZutKnTDP/ex5wkYHjf8MTypP0oK@JY0DxkehPNGW2HMuchFlyjcKd00vCMFU6fzZpUZ5w3aZGxwvcx933aCp/bgegEH9zoVtSfwVt5MXsi7knuByGlvx5ykzM5fHE2vsy4YJ32ec66StWXykDDup7dpriWeg9boQ2xdaXNIc1AVAdLvdabXEUFFjgY9QXjWNBCtEKI5m6HCDHCGuER4QHB0UuEBcKgQce8yVNpbHlUwXula/WqjSK7sUPwUrpuU5wiMeSfdRhiHGO8xnh1wxLjxYg5xpEDdJRY6hbzuiH6Hw "C# (.NET Core) – Try It Online") # [C# (.NET Core)](https://www.microsoft.com/net/core/platform) + using Linq, 170 + 23 bytes ``` x=>s=>x.GroupBy(z=>z).Select(y=>Enumerable.Repeat(Math.Round(s.Skip(Array.IndexOf(x,y.Key)).Take(y.Count()).Average()),y.Count())).Aggregate((a,b)=>a.Concat(b)).ToArray() ``` [Try it online!](https://tio.run/##VVDLasMwEDzXX7HkJMNW5NnGpDakpS19hEJc6CHkoNgb1ySRXUlO7Zh8u6sYQgkawe6sNMNspK@jTFEjxY50LiKCsNKGdvw9lT@1E22F1pDXjjbCpBE8FTK6S6VZLPGijrNitaXFMghg7TelH2g/KPmzyor8vmIHPzi4PKQtRYZVfvAoix0pYX/wOeUkDJsJ883nWSFjpnm4SXM2VUpU/EXGVH6sWYkVf6PKdfmn2BCr@IN9a5jtp3urlJAt8Z@1dJIoSoQhxgSuXD8Qdigja7U6iWStPHObyTnZPktjmIlUMm1UKpPFEoRKtFs7V3uhQIMPkn6hzQs19EYIvb69XQQPYYxwi3CDYOkhwgDhNIPjxLmytjqzSb9UashulVjYGvDXzJp1sINszS6ku130PPTG6I3OGKI3aNFHr2cBR5dpm9OdOMfTaf4A "C# (.NET Core) – Try It Online") [Answer] # J, 15 bytes ``` [:;<@(##+/%#)/. ``` [Try it online!](https://tio.run/##ZYzNCsIwEITveYqFILQ4bLNpI261Ij6AL@DBQ2mpXgr2/YmJPyAI32WG@eYe49jxpd3tj4W162ply4qNWfr5MSzUMUmAeBzaG1/FmfMpNySexJESc4rGDP00U@EFibxvsqLYIKBBDQ8paaT352cszkEVuoWGLw20fpFkSfxL3v6UMT4B) Takes the list of scores (`1 2 ... 12 15`) as a right-hand argument and the values to score as a left-hand argument. If this isn't a logical input, add 1 byte for a `~`-passive to invert the order in which the inputs are taken. There might be a few things to golf, which include * My usage of boxing * The cap at the end # Explanation I'll split this into a couple functions. ``` avg_and_dupe =. # # +/ % # score =. [: ; <@avg_and_dupe/. ``` * `avg_and_dupe` takes the average of a list and duplicates it as many times as the list's length * `score` scores an input (left argument) given a list of scores (right argument). # avg\_and\_dupe ``` # # +/ % # # Length # Copy as many times as the left argument +/ % # Average +/ Sum % Divided by # Length ``` This works so nicely because it's treated as two [forks](http://code.jsoftware.com/wiki/Vocabulary/fork). If you're still scratching your head (I know I was at first), ask and I can provide a more in-depth explanation for why this works as it does. ### score ``` [: ; <@avg_and_dupe/. /. Key: using the values given, partition the scores <@avg_and_dupe For each partition: avg_and_dupe Average and duplicate < Then box ; Raze the boxes into a single list ``` If it's still confusing, I can also add an explanation for `/.`-key, but I think the [wiki page](http://code.jsoftware.com/wiki/Vocabulary/slashdot#dyadic) explains it pretty well. [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes *-8 bytes thanks to Leaky Nun.* ``` lambda s,p:[sum(p[s.index(i):][:s.count(i)])/s.count(i)for i in s] ``` [Try it online!](https://tio.run/##bY/djoMgFITveYpzqcmkK1S7xcQnYbnonylJi6Ro0n169yxW26SF7@aQYc5M@O3PnVdj2/yMl911f9xRRKhNHK5ZMHHl/PF0z1xeW1PH1aEbfM@Tzb@eQ9vdyJHzFO3Yn2IfqSEjiI9REoysIEtIBY0NKpRYQ0FaPDRFEkwUrNnie9bNGvb4dF8sFuTMYrSYFPyoobfQ1UwJvU5wOMlYYYUInfNTi/9I6i1VSi/E0juVrtOScOOv1GYONLnk4x8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṁ⁴Œg¤Æmṁ$€F ``` [Try it online!](https://tio.run/##y0rNyan8///hzsZHjVuOTko/tORwWy6Qp/KoaY3b////ow1NdQyNdAwNdCx1LHTMdcx0THVMdIx1gEKx/6PNdbDCWAA "Jelly – Try It Online") -3 bytes thanks to fireflame for noticing new Jelly features :D [Answer] # [Python 3](https://docs.python.org/3/), 67 bytes ``` lambda s,p:[sum(v for j,v in zip(s,p)if j==i)/s.count(i)for i in s] ``` [Try it online!](https://tio.run/##bY/NDoIwEITvPMXeaJNRaQG1JPgEvgFy8CfEEgQCaqIvj1sUL5p@h2ZnZjPbPq7npg6HIt0N1f5yOO2pR5tk/e0i7lQ0HZW4k63paVvBirQFlWlq5aKfH5tbfRVWOpd1nj4ftqnItAKjYqgISsNgiRgRQmioHF6mg1F8E7C@xmryOJ2z/94n@kVNfBeM4YAHBmYNE09EMOEIl1FMLj3Pla5c6W3iUdtZvsTf1T6oAvFntvEhJ6EQPMxcW/1TeDxKyuEF "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~108~~ 70 bytes ``` lambda s,p:[1.*sum(v for j,v in zip(s,p)if j==i)/s.count(i)for i in s] ``` [Try it online!](https://tio.run/##bY9LDoIwGIT3nOLf0ZoRaQWlJHgCb4AsfIRYg4UAmujlsUVxo@m3aObRTJtHf66NHMpsN1T76@G0pw5Nmotg1t2u7E5l3dIFd9KGnrph1uS6pEuWab7ogmN9Mz3T3KW0y3TFsM1YLgUsIoaIICQUVogRYQkJUcDLZTiab0LrJ1hPGefb7r/zqX4RE98HxnJoBQWVQMUTEdRyxI4RloJ7nhtdudHb1KOm1aYnf2d8UAV3mW98THrJrJa7sfJn7/gnPrwA "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` lambda s,p:[sum(p[s.index(i):12-s[::-1].index(i)])/s.count(i)for i in s] ``` [Try it online!](https://tio.run/##bY/BbsIwEETv@QrfEksTmnWSFluCL@APjA9QGmEpOBEGqXx92IQmlyK/gz3jWc32j9u5C@XQbPZDe7gcTwcR0Rsb75est3Hlw@nnN/PSkMqjNSYnt2hOfsTVd3cPN3403VV44YOIbthtMqsIDNWgCqSg8YkaFUookENiVTGZLwr21/ia/4w@Z9@dv@gCzSwDpnDBgoZeQ9czFXQ5wWWIcTJJxtLtWHpnEtFfPW@S7kMK0ULwJd@mkLPRZCzasa36V3haSsrhCQ "Python 3 – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 62 bytes ``` (s,p)=>[sum(p[s.index(i)to][to s.count(i)])/s.count(i)for i:s] ``` [Try it online!](https://tio.run/##bcgxCgIxEEbhq6TMwM9q1FVXWC8yTKUGUpgJmSx4@5jORl71vlK1ae5x7d5QaL2zbW9f2KaUn6@PT9RUuKmz6aFbbgOEdr@JWl26mfRS04DoOeBvAsdhRjgg7LHgigvOmHHCEYOEqH8B "Proton – Try It Online") # [Proton](https://github.com/alexander-liao/proton), 63 bytes ``` (s,p)=>map(i=>sum(p[s.index(i)to][to s.count(i)])/s.count(i),s) ``` [Try it online!](https://tio.run/##bYixDsIwDAV/paMtPRVSKNAh/ZEoAwIqZWhs1anE34dsXdAtd6ebFMl18ZUMyn5en0rJz7avpMH6lN@fLyUuEkORzvqX7Lm0Efl0BIyrbqn5QsHhLxFdcCPcAHfGhAfuuGHEFRe0FZnrDw "Proton – Try It Online") [Answer] # Dyalog APL, 14 bytes ``` ∊{(⊂≢⍴+/÷≢)⍵}⌸ ``` Takes the list of scores as left argument and points list as right argument. Add 2 bytes for wrapping it in `()` if called directly and not as a named function. `{`...`}⌸` group right argument by key in left argument and apply function in braces to each group (key operator). `⊂≢⍴+/÷≢` is a fork where: `+/÷≢` is average points for group (sum divided by tally) `≢⍴` tally reshape (replicate the average to match number of items in group) `⊂` boxes the result (this is to counteract the mixing of the result that the key operator applies) `∊` is enlist and flattens the result of the key operator (which is a nested vector of vectors) into a simple list. [TryAPL online](http://tryapl.org/?a=20%2020%2020%2020%2010%2010%2010%209%208%207%206%205%28%u220A%7B%28%u2282%u2262%u2374+/%F7%u2262%29%u2375%7D%u2338%2915%2012%2010%209%208%207%206%205%204%203%202%201&run) [Answer] # Haskell, 152 bytes ``` f::[Int]->[Int] f=concat.g(15:12:[10,9..1])[] g[q]t _=[q:t] g(q:r)t(x:z)|x>head z=(replicate(l(q:t))(sum(q:t)`div`l(q:t))):g r[]z|1<2=g r(q:t)z l=length ``` It's a pain to import `groupBy` and `on`, so I had to do my own. Averaging function will be shortened shortly. Needing the signature could probably be avoided with compiler flags. ]
[Question] [ Given a positive integer `N`, output the number of pairs of integers `0 <= a <= b < 2**N` such that `a*b >= 2**N`. ## Rules * You may assume that `N` is less than or equal to the maximum bit width for integers in your language (e.g. for C, `N` will not exceed `32` or `64`, depending on the architecture of the machine). If your language is capable of handling arbitrary-width integers, then there is no upper bound on `N`. ## Test Cases ``` 1 0 2 3 3 19 4 96 5 437 6 1876 7 7804 8 31904 9 129170 10 520135 11 2088143 12 8369175 13 33512744 14 134128704 15 536681553 16 2147082274 ``` [Answer] # Python 2, ~~75~~ 68 bytes ``` n=input() a=1<<n s=~-a*a/2 x=y=0 while y<1:s+=y;x-=1;y=a/x-x print s ``` [Try it online!](https://tio.run/##Jc1BDoIwEEDRNXOK2QFKgyVhA53DjFqlCQ4NYOxsvHqNuv7J@1H3aZHORI2ab8uKgkFwZbn7yjZ9Xw9QxDXIjtJAESQ@dySc@XG@8oAChU/@gmVZZqFfrWpgss4JbPQ2fOC2g0RKJ3hNYfaozg7bkXRMhuyoxG0yCf6LLX@hDw "Python 2 (PyPy) – Try It Online") This runs in O(2*n*/2) operations rather than O(2*n*) or O(22·*n*), so it works on much larger inputs. (Note that an even faster [O(2*n*/3) algorithm](https://arxiv.org/abs/1206.3369) exists.) ``` 1 0 2 3 3 19 4 96 5 437 6 1876 7 7804 8 31904 9 129170 10 520135 11 2088143 12 8369175 13 33512744 14 134128704 15 536681553 16 2147082274 17 8589086503 18 34357951447 19 137435198086 20 549747939928 21 2199006781125 22 8796058620153 23 35184300378083 24 140737339120148 25 562949643323164 26 2251799170232606 27 9007197921321922 28 36028794259096612 29 144115182370060793 30 576460740519709546 31 2305842984902014765 32 9223371986742908935 33 36893488044218344323 34 147573952377320833218 35 590295809922086353118 36 2361183240537767708679 37 9444732963897547996897 38 37778931859178411534913 39 151115727444080615797321 40 604462909791437463796926 41 2417851639196741979223299 42 9671406556850476410936322 43 38685626227531971124247499 44 154742504910394112443480979 45 618970019642121099638818409 46 2475880078569598086230187969 47 9903520314280668496162705117 48 39614081257127323838921620439 49 158456325028518790167805606609 50 633825300114094540502620959956 51 2535301200456417702087608942034 52 10141204801825751449333352568660 53 40564819207303170200956592005599 54 162259276829213015854387448792578 55 649037107316852746005301421147606 56 2596148429267412374169967907532731 57 10384593717069652326923914077600197 58 41538374868278615068076777292632146 59 166153499473114471992855423428749242 60 664613997892457911812090466987383188 61 2658455991569831695728843704244440740 62 10633823966279326881474627069404687424 63 42535295865117307726213589942623257944 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes ``` 2*ṖµṀ:«ạ¹S ``` Finishes the combined test cases in under 3 seconds. [Try it online!](https://tio.run/##ASkA1v9qZWxsef//MirhuZbCteG5gDrCq@G6ocK5U/8xNlLCtcW8w4figqxH/w "Jelly – Try It Online") ### How it works ``` 2*ṖµṀ:«ạ¹S Main link. Argument: n 2* Yield 2ⁿ. Ṗ Pop; yield A := [1, ..., 2ⁿ-1]. µ New monadic chain. Argument: A Ṁ Maximum; yield 2ⁿ-1. : Divide 2ⁿ-1 by each k in A. « Dyadic minimum; yield min((2ⁿ-1)/k, k) for each k in A. ¹ Identity; yield A. ạ Absolute difference; yield k - min((2ⁿ-1)/k, k) for each k in A. S Take the sum. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes ``` Wqt:&*R<z ``` [Try it online!](https://tio.run/##y00syfn/P7ywxEpNK8im6v9/cwA) This tries all possible pairs. It runs out of memory in the online interpreter for input exceeding `12`. ### Explanation ``` W % Implicitly input N. Push 2^N ('^' denotes power) q % Subtract 1: gives 2^N-1 t: % Duplicate, range: pushes [0 1 2 ... 2^N-1] &* % Matrix of all pair-wise products R % Upper triangular part (including diagonal) < % Less-than comparison; element-wise. This gives true for products % that are greater than 2^N-1 z % Number of non-zeros- Implicitly display ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` ;2↔^P>B≥Aℕ;B C×≥P∧C≜ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39roUduUuAA7p0edSx0ftUy1dlJwPjwdyAl41LHc@VHnnIfb5vz/b/o/CgA "Brachylog – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes -1 byte thanks to Emigna ``` oDL<ã€{ÙP›_O ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/38XH5vDiR01rqg/PDHjUsCve//9/YwA "05AB1E – Try It Online") ### Explanation ``` oDL<ã€{ÙP›_O Argument n oD 2^n, push twice to the stack L< List: [0 .. a] ã Cartesian product with itself €{ Sort each element Ù Uniquify P Total product of each element ›_ Each element is greater or equal than 2^n O Total sum ``` [Answer] ## JavaScript (ES7), ~~70~~ ~~65~~ 60 bytes ``` n=>[...Array(k=2**n-1)].reduce(p=>p+=k<++i*i&&i-(k/i|0),i=0) ``` ### Test cases ``` let f = n=>[...Array(k=2**n-1)].reduce(p=>p+=k<++i*i&&i-(k/i|0),i=0) for(n = 1; n <= 16; n++) { console.log(n, f(n)) } ``` [Answer] ## Mathematica, 37 bytes ``` Sum[#-⌈#/a⌉~Max~a,{a,#-1}]&[2^#]& ``` Try it online at <http://sandbox.open.wolframcloud.com>. Mathematica does not have limit on integers, and this algorithm run in time 2n, so it is very slow for large `n`. [Answer] ## Clojure, 78 bytes ``` #(count(for[l[(bit-shift-left 1 %)]a(range l)b(range a l):when(>=(* a b)l)]1)) ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 13 bytes ``` ╙;r⌠;R*i⌡M♀≥Σ ``` [Try it online!](https://tio.run/##ASUA2v9hY3R1YWxsef//4pWZO3LijKA7Uipp4oyhTeKZgOKJpc6j//82 "Actually – Try It Online") A literal implementation of the problem. Quite slow. [Answer] # [PHP](https://php.net/), 62 bytes ``` for($x=$n=2**$argn;$y=--$x;)for(;$y;)$x*$y--<$n?:$r++;echo+$r; ``` [Try it online!](https://tio.run/##HcmhDsIwEIBhv8dYTqxtLiFIbs3EMoEBg1@WpqyYu@aC6Axvje4G8v/@nHLth5xyE1VFZ41Z9P3itftM8@3@uI6ToQYWXdm3p5bqU7SD4oH92dq/E2weEQqZ3zuKDBQLG2IPPFxAnaMYkjhQqvXLgmEJKe4 "PHP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` lambda n:sum(k-min(~-2**n/k,k)for k in range(1,2**n)) ``` [Try it online!](https://tio.run/##TcuxDsIgFEbhuT7Fv5BeGojC0qRJ@yQuGEUJctvQMrj46hg21@/kbJ/jtbKtHjOu9e3S7e7A014SRZ0C01fbYeBzVFH6NSMiMLLj54OMakXK2pz/HWaU06nbcuADvbAFeoEwl9JDgFjBU/t@ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 2*’©ŒċP€>®S ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//MirigJnCqcWSxItQ4oKsPsKuU////zY "Jelly – Try It Online") A literal implementation of the problem. Quite slow. ]
[Question] [ A language that is very useful in restricted source and other such challenges is [Unary](http://esolangs.org/wiki/Unary), a brainfuck derivative in which programs are written in with only one character. Your job is to write a program to convert programs from brainfuck to unary and a program to do the opposite, both programs in the same language. Your score will be the sum of the lengths of the two programs. ## How do you convert from brainfuck to Unary? * First convert your brainfuck code to binary according to this table: | Brainfuck | Binary | | --- | --- | | > | 000 | | < | 001 | | + | 010 | | - | 011 | | . | 100 | | , | 101 | | [ | 110 | | ] | 111 | * Now concatenate the code into one giant binary number in order of the code. * Prepend a `1` to the string to ensure a unique binary number. * Convert from a binary number to a unary number using any character. * Example: ``` +. ``` would become ``` 000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ``` which is 84 zeroes. ## brainfuck → Unary specification: * Since the resulting programs will be impossibly huge, print not the actual program but merely the length of the resulting program. * Take the brainfuck program as a string through stdin, function arg, etc and output the length. * The program will always be valid and have only those 8 chars in it. ## Unary → brainfuck specification: * You will have to implement the reverse of the above algorithm. * Again because of the huge sizes in question, the input will be a number describing the length of the Unary code. * Same I/O rules as always. * The program will always be valid and have only those 8 chars in it. ## Test Cases * Hello World: ``` ++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+. ``` becomes: ``` 239234107117088762456728667968602154633390994619022073954825877681363348343524058579165785448174718768772358485472231582844556848101441556` ``` * Fibonacci: ``` ++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++>++++++++++++++++>>+<<[>>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[<+>-]>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<.>.>>[>>+<<-]>[>+<<+>-]>[<+>-]<<<-]<<++... ``` becomes: ``` 13067995222095367150854793937817629722033205198624522624687536186118993888926522550140580142585590431635487113180955099384652678100247403485397450658564826143160529351955621991895221530908461364045400531236124980271740502887704217664044858614821622360156740992393765239123681327824577149595724956207165558106099868913919959549896553103116795519592552089266360725543244154867904980260 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins! Anyone up for a solution in Unary? ;P [Answer] # Pyth, 17 + 17 = 34 bytes BF -> Unary, 17 bytes ``` i+1xL"><+-.,[]"z8 ``` Unary -> BF, 17 bytes ``` s@L"><+-.,[]"tjQ8 ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~563 335 318 316~~ 296 + ~~529 373 366~~ 336 = 632 bytes Since this was obviously missing a solution in a related language, here is the solution in brainfuck and Golunar. I couldn't post an answer in unary, because that would need a few fantasticatillion times more memory than there are atoms in the universe ^^ The "back" routine won't check if the Golunar/Unary code is valid. If the bit count mod 3 != 1 then it will run into an endless loop printing a lot of ">"s. Thanks to Nitrodon for helping me getting below 300 chars for the bf to unary code **brainfuck to unary** ``` ->+>>>>,[>+++[>+++++<-]>[<+<---->>-]<<--[<+>++[<<+>>>[<+>-]<[<->++[<<<+>->+>-[<->--[<<+>>>+++++++++[<----->-]<[<+>--]]]]]]]>[-]>>,]<<<<+[<+]>[>]->+[<]>+[[->+]->[->[<++>-[<++>-[<++>-[<++>-[<-------->>[-]++<-[<++>-]]]]]]<[>+<-]+>>]<<[<<]>[<]>-[[->+]->>+<[<<]>[<]]>+]>[>>]<<[+++++++[>++++++<-]>.<<<] ``` [Try it online!](https://tio.run/##7ZDBDQJBCEULYtkKCI0QDq6JiTHxYGL964OZOXmxADkwA3w@H47X5f68va@P81QXx7ZwEWknYpoexoO5axo/YophVvAKSIfpyFUIj1aioA2SZdFEOjpAaQ7zYI5v0NNAhYQnPGGJC35EPJSa@9vrNC@q0j0Kg97Yhk2QwgQ01U5J1ySmuJKMq9mNW5qn/DrFjr78X@rXS30A "brainfuck – Try It Online") **and back** ``` ->>,[<++++++[>--------<-]+>>>>>>,]>->-<<<+[-<+]>[[->[->+<[->->+>]<[<<<]>]<+>>>[-<<+>>]<[>>>>++++++++++<<<<-]>>>]>>>+[->+]>-<+[-<+]-<[>>+[->+]-<++[-<+]-<[-]]<<<<<<[<<<<<]>>>>>>[<<]<[->>>]>>]>>>+[->+]<-<+[-[<++>-]<[<++>-]>+++[>+++++<-]>[<+<++++>>-]<<++<[>--<-[>>[<->-]<--<-[>++<-[>+<-[>--<-[>+[>+<-]>[<++>-]<+<-[>++<-]]]]]]]>.[-]>[-]<<<+] ``` [Try it online!](https://tio.run/##RU9bihwxDDxQrxe9bElgfJHGH9lAIATyEcj5JyXP7Eb0SCO5VFX6@PPt5@8ff7//ejzaWm/3vE7cq71itn2tE297tdXmnNfd5rXXfbeF75pIKGvPG48btRaAqYph7V5fAQgoMarfVfugfVG2Aj9naL9mbe954j55P@2g2SV9mP6TzUNWd6xWjk5d56SnPjpMz52rIPg369zZ7iJtNXt2BUau9Bqc7uwf9usTtZ@x3u96LVI4fzzUvXc3i06irDpsDE4Z6SrdSJOHRzCb4SlymLhRDBGXPsKAkhAeHKis3VJd1bGX1EWD1DprqHLn0Yk4uQOSKpZgG5rmzmHJYBrKQjacHFpCDDspbOC2UDfYGCCNJAOTBzmBVatwwh4M4YZkKb1IY2dhHjkCfFDtaek8hOBNmNjDu0tQOiST7QjiZBEWGwGdVGSIppGRwyH5Pw "brainfuck – Try It Online") # [Golunar](https://esolangs.org/wiki/Golunar)/unary-digits, ~~509 303 288 286~~ 268 + ~~478 337 331~~ 304 = 572 bytes **brainfuck to unary** ``` 2845581296974449674357817038179762273623136917867627972159702240227366875240878616687779429553529795902322625321040063298921498529640547483869509829184440577052825434462245755576011912505085065586076069824710351537537205287083477698633592357950165322060367940923703887 ``` **and back** ``` 3775574485023133646619269732540391678811443648964274086227256847322821618228135493733703990523803451383315165001915937932498966394771849173263120467073642011339214182483748816052890450078070151307011943625602391238338941712116968736593594971620990210178757280976709140113340322124688909388916094040773207 ``` --- **Source codes** brainfuck to unary ``` [ unary: ><+-.,[] 01234567 62 > 62 60 < -2 45 - 15 43 + 2 44 , 1 46 . 2 91 [ 45 93 ] 2 tape (while reading input): Left tape end marker/LTE, [binary data], input, 15, (15 multiplicator) tape (while base conversion): LTE, [binary data], Value Start/VS, [decimal digits] decimal digits: digit used/DU, value ] - set LTE >+ set leading 1 >>>>,[ while input >+++[>+++++<-] set 15 (multiplicator) >[<+<---->>-] set 15 and decrease input by 60 check for greater than set current bits = 000 (greater than) <<--[ if input != 62 try next char check for less than <+> set current bits = 001 (less than) ++[ if input != 60 try next char check for minus <<+>> set current bits = 011 (minus) >[<+>-]<[ if input != 45 try next char check for plus <-> set current bits = 010 (plus) ++[ if input != 43 try next char check for comma <<<+>->+> set current bits = 101 (comma) -[ if input != 44 try next char check for dot <-> set current bits = 100 (dot) --[ if input != 46 try next char check for left bracket <<+>> set current bits = 110 (left bracket) >+++++++++[<----->-]<[ if input != 91 go to next char use right bracket <+> set current bits = 111 (right bracket) -- decrease input by 2 / should be 0 now ]]]]]]] close all ifs >[-]>> delete 15 if still existant , input next character ] <<<<+[<+]>[>] add one to each bit and delete LTE (for shorter search routine) Start of binary to decimal routine - set value start marker (VS) >+ set digit used marker (DU) [<] go to LTE binary to decimal loop: use "double and add algorithm" to calculate the digits of the decimal value >+[ if not on VS then [->+]- restore current bit value and go to VS > go to first DU [ digit doubling loop -> remove DU and go to corresponding digit [ <++>- decrement current value and add 2 to temp value four times [ <++>- [ <++>- [ <++>- [ if value was greater than 4 then <---- ---- subtract 8 from temp >>[-]++ set next digit temp = 2 (DU plus 1) <- decrement current digit [<++>-] set temp = remaining value * 2 ] ] ] ] ] <[>+<-] set current digit = temp + set DU >> go to next digit ] end of digit doubling loop <<[<<]>[<]> go to current bit -[ if bit is 2 (used plus 1) [->+]- delete bit and go to VS >>+ increment least significant digit <[<<]>[<] go to current bit ] >+ if not on VS then repeat ] end of binary to decimal loop >[>>]< go to most significant digit <[ printing loop: for each DU print corresponding value +++++++[>++++++<-]>. add 48 to value (ASCII 0) and print <<< go to next DU ] ``` and back ``` [ tape: left tape end marker/LTE(-1), [digits], digit end marker/DE(0), carry, SB(-1), [binary data], 60, 15 digits: digit used marker/DU(1), digit, remainder, solution, 0 else] [exit else, exit if binary data: value (, else, exit if, exit else) ] input decimal value ->> set LTE ,[ while input <++++++[>--------<-] decrease input by 48 + set DU >>>>> >, input next digit ] >->- set start of bits (SB) and first CCB <<<+[-<+]> delete LTE and go to first DU division loop: calculate the remainders of the input divided by 2 repeatedly to get the (inverted) bits [ divide each digit by 2 [ for each DU - delete DU (for exit if) > go to digit [->+< dec digit / set remainder [->->+>] if digit gt 0: dec digit / del remainder / inc solution / goto 0 pointer: (value(0) remainder is set) or (0 solution gt 1) <[<<<] go to DU > go to digit ] <+ set DU >>>[-<<+>>] move solution to digit <[ if remainder >>>> go to next digit +++++ +++++ add 10 to digit/carry <<<<- go back and delete remainder ] >>> go to next DU ] append new bit >>>+[->+] go to and delete CCB >- set new CCB <+[-<+]-< go to carry [ if carry >>+[->+]-<+ set last bit +[-<+]-<[-] go to and clear carry ] check if first digit became 0 / neccessary to check if value has been completely processed < <<<<<[<<<<<]>>>>> go to first DU >[ if digit gt 0 << go to exit if ]<[ else - delete DU >>> go to exit else of next digit ] >> go to DU / DE if all digits processed ] end of division loop decode binary values >>>+[->+] go to and delete CCB (after last bit) <- delete leading 1 < go to first bit Start of bit decoder [ unary: ><+-.,[] 01234567 62 > 62 60 < -2 43 + -17 45 - 2 46 . 1 44 , -2 91 [ 47 93 ] 2 tape: start of bytes marker/SB(-1), [binary data], 60(print char/PC), 15 ] +[- while not SB Set least significant to octal value of three bits [<++>-] if first bit set add 2 to second bit <[<++>-] for each second bit add 2 to third bit >+++[>+++++<-] multiplier 15 >[<+<++++>>-] setup table 60 15 run through the 8 possibilities 0 greater than <<++ set PC = 62 (greater than) <[ if value gt 0 go to next char 1 less than >-- set PC = 60 (less than) <-[ if value gt 1 go to next char 2 plus >>[<->-]<-- set PC = 43 (plus) <-[ if value gt 1 go to next char 3 minus >++ set PC = 45 (minus) <-[ if value gt 1 go to next char 4 dot >+ set PC = 46 (dot) <-[ if value gt 1 go to next char 5 comma >-- set PC = 44 (comma) <-[ if value gt 1 go to next char 6 left bracket >+[>+<-]>[<++>-]<+ set PC = 91 (left bracket) (inc (45) / double (90) / inc (91)) <-[ if value gt 1 go to next char 7 right bracket >++ set PC = 93 (right bracket) <- decrease value the last time to exit if ]]]]]]] close all ifs >.[-] print char and clear PC >[-] clear 15 if still existant <<< go to next bits + repeat if not SB ] ``` [Answer] # Python 2, ~~80~~ ~~79~~ ~~63~~ 55 + ~~86~~ 64 = 119 Bytes *Thanks to Sp3000 for his numerous suggestions, saving a lot of bytes.* **Brainfuck to Unary, ~~78~~ ~~77~~ ~~61~~ 53 + 2 = 55 bytes** *Added two bytes to account for surrounding "s on input.* ``` print int(`[1]+map("><+-.,[]".find,input())`[1::3],8) ``` **Unary to Brainfuck, ~~86~~ 64 bytes** ``` print''.join("><+-.,[]"[int(i)]for i in oct(input())[2:]if'L'>i) ``` [Check it out on ideone here.](http://ideone.com/5AUErK) [Answer] # CJam, 35 bytes ## Brainfuck to Unary, 17 bytes ``` 1r"><+-.,[]"f#+8b ``` [Try it online.](http://cjam.aditsu.net/#code=1r%22%3E%3C%2B-.%2C%5B%5D%22f%23%2B8b&input=%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%3C-%5D%3E.%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%3C-%5D%3E%2B.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%3C-%5D%3E.%3C%2B%2B%2B%5B%3E----%3C-%5D%3E.%3C%3C%3C%3C%3C%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%3C-%5D%3E.%3E%3E.%2B%2B%2B.------.--------.%3E%3E%2B.) ### How it works ``` r e# Read a whitespace-separated token from STDIN. f e# For each character in the token: "><+-.,[]" # e# Find its index in this string. 1 + e# Prepend a 1 to the results. 8b e# Convert to integer, using base 8 conversion. ``` ## Unary to Brainfuck, 18 bytes ``` ri8b"><+-.,[]"f=1> ``` [Try it online.](http://cjam.aditsu.net/#code=ri8b%22%3E%3C%2B-.%2C%5B%5D%22f%3D1%3E&input=239234107117088762456728667968602154633390994619022073954825877681363348343524058579165785448174718768772358485472231582844556848101441556) ### How it works ``` r e# Read a whitespace separated token from STDIN. i e# Interpret as integer. 8b e# Convert to array using base 8 conversion. f e# For each digit: "><+-.,[]" = e# Select the corresponding character from the string. 1> e# Discard the first character. ``` [Answer] # Bash + coreutils, 39 + 47 = 86 ### `b2u.sh`: ``` dc -e8i1`tr '<>+-.,[]' 0-7`p|tr -dc 0-9 ``` ### `u2b.sh`: ``` dc -e8o?p|tr -dc 0-9|tr 0-7 '<>+-.,[]'|cut -c2- ``` ### Test output: ``` $ echo "++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+." | ./b2u.sh 239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789 $ echo 239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789 | ./u2b.sh ++++++[>++++++++++++<-[>.>++++++++++[>++++++++++<-[>+.+++++++..+++.>++++[>+++++++++++<-[>.<+++[>----<-[>.<<<<<+++[>+++++<-[>.>>.+++.------.--------.>>+. $ ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 + 13 = 26 bytes ## Brainfuck to Unary ``` i< n"><+-.,[] ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=aTwgbiI+PCstLixbXQ==&input=IisuIg==) Explanation: ``` i< :Insert a "<" at the start of the string (representing 1) n :Convert string to decimal by interpreting as: "><+-.,[] : A base 8 number represented by the 8 characters of BF ``` ## Unary to Brainfuck ``` s"><+-.,[]" Å ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=cyI+PCstLixbXSIgxQ==&input=ODQ=) Explanation: ``` s :Convert decimal to string representation of: "><+-.,[]" : Base 8 using the BF characters to represent the 8 digits Å :Remove the extra "<" at the front ``` ## Notes I can't find the meta post, but if my memory serves correctly answers are allowed to limit I/O to numbers that their language can support, as long as they implement an algorithm that would work if the language starts supporting larger numbers. That is the case here, Japt's ability to treat a string as "base `n` using these `n` characters for the digits" can only use the `number` data type on the other side of the operation, and thus the test cases won't actually run successfully; the [output](https://ethproductions.github.io/japt/?v=1.4.6&code=aTwgbiI+PCstLixbXQ==&input=IisrKysrK1s+KysrKysrKysrKysrPC1dPi4+KysrKysrKysrK1s+KysrKysrKysrKzwtXT4rLisrKysrKysuLisrKy4+KysrK1s+KysrKysrKysrKys8LV0+LjwrKytbPi0tLS08LV0+Ljw8PDw8KysrWz4rKysrKzwtXT4uPj4uKysrLi0tLS0tLS4tLS0tLS0tLS4+PisuIg==) of the first program and the [input](https://ethproductions.github.io/japt/?v=1.4.6&code=cyI+PCstLixbXSIgxQ==&input=MjM5MjM0MTA3MTE3MDg4NzYyNDU2NzI4NjY3OTY4NjAyMTU0NjMzMzkwOTk0NjE5MDIyMDczOTU0ODI1ODc3NjgxMzYzMzQ4MzQzNTI0MDU4NTc5MTY1Nzg1NDQ4MTc0NzE4NzY4NzcyMzU4NDg1NDcyMjMxNTgyODQ0NTU2ODQ4MTAxNDQxNTU2) of the second program will coerce the number to one which can be represented as a `number`, rather than using the actual number. For numbers which can be perfectly represented by Japt's `number` data type these programs will work as desired, and if the `number` data type changes to support larger numbers then these programs will start supporting those numbers as well. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 (17 + 16) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) **Brainfuck to Unary-length:** ``` "><+-.,[]"sSk1š8β ``` [Try it online](https://tio.run/##yy9OTMpM/f9fyc5GW1dPJzpWqTg42/DoQotzm/7/1waDaDttJGCjG2unhySCLAuS09aDcvRADIhKFBPABtiARXWBAMIFAYRCiB12YAN0wQBKARl2QBsA) or [verify all test cases](https://tio.run/##nVG7asNQDN3zGXeVJegWilDmTB0yCg8NdAiFtmCnUMjP5Bcy9AMKWftLzpGuIfbQwT3GSDpXR49737vn/eFlOH2W7dvHsX8szVdTno796A/FlFgab0u3e324nte/l6H5@d4MlHCjCZRbkwkzPY0zkjGQcGrmrEIW0GQZqGHgnlh7WBbgxGjgGDqsaAFscQJaqLoBk6nV2cgYE5q15uSsBCeinF5BgsHkjn8mhfJv3ZjvtBACWav/lOVlL9bVPVXibTwvKbYNW/dOo8FGfRFZsePDG2NBkCw3). **Explanation:** ``` "><+-.,[]" # Push string "><+-.,[]" s # Swap to take the (implicit) input S # Convert it to a list of characters k # Check for each the index in the string 1š # Prepend a 1 to the list of indices 8β # Convert the list to Base-8 (and output implicitly) ``` **Unary-length to Brainfuck** ``` 8в¦"><+-.,[]"sèJ ``` [Try it online](https://tio.run/##DYy5DUJRDAR7IeWQj7W9lhAF0AIiAImAiOD3hIgpARqgo8fLRjOrfSyX6/02Bn/vz3N12K@3u83pvFq@r@MY5m0OlVItISsNkWXMrE6mmAbS3Vu6kdpiJuUdoAWrkuozgw4PgwSjWjOKAVALpfNzDs2DmLLMXINGICKnUlFAJ/8B) or [verify all test cases](https://tio.run/##LVE7TpRRGO1Zxt86mO91vochUkPDAoyFJhY2SjIzJiSsh1hTsIBhA@xoONfY3NzHd5739/7b958/zo9/tptf98fDp233sNvujof/@3O/PZ@ets9XHy4/7r583favf2/Pu9PL9dl8zEOlVEu6Ky2QZZ1Zk51iikh3H5mJ1BEzKR9EG7oqW53P0R4OC0GjRhPViGitKCUnB83Rwcsyc0VbRwDJKxWNUO4v1IWiA6PEwLMUshDj40WutCFa3E2g08upGVfSc1o7VXvGu3ss@QSQmo640iswEq7ptM6wrk0RyAIEp5MKIhYVwjTwqYAkYcmkqQspsHEq06vpDMUoonAZIQV7CAmECFyNfiymxYodCMRYbUkYU6wxKtAumTXZR4qy86AXW1HpxmdRsFurZswqjcGgyElxflYCoOEkprNHCZg1Qc3hm6u4KtvE8juswmS1ktQqnsJtlR7NEfnnM@Vi/QL/tlk7U9k7). **Explanation:** ``` 8в # Convert the (implicit) input-list from Base-8 to Base-10 ¦ # Remove the first 1 "><+-.,[]" # Push string "><+-.,[]" s # Swap the list and string on the stack è # Index each integer into this string J # Join everything together (and output implicitly) ``` [Answer] # [Dart](https://www.dartlang.org/), 77 + 142 = 219 bytes ``` f(s)=>BigInt.parse('1'+s.split('').map('><+-.,[]'.indexOf).join(''),radix:8); F(n)=>BigInt.parse(n).toRadixString(8).split('').map((s)=>'><+-.,[]'.substring(int.parse(s),int.parse(s)+1)).join('').toString().substring(1); ``` [Try it online!](https://tio.run/##nVRNa9tAEL33V@hQkIRsMTO7sx@1rEOhgZ4K7VHo4DZx6tI4xh8lEPLb07ey28gphaYDknZn37yZHb3dy8V2//i4LHblvH27un6/3tebxXZ3VeScV7t6t/m@2hd5XtY3i02Rt001rSddn9er9eXV3YdlWX@7Xa0TYLJdXK7u3oRydlGsn5Oty3p/@zEBPu23q/V1Ecpn1EMBI/7d4fPuCF39ZtmVk/Gk4vIpPfhP1OUolsvZ480CiPL@VZb9WGyz/bzDKMu6vBqsa6uRNdO@rUee8Wpaq@rTpE6DI/KMYSBoBu8UdpwmewIec7QDwXSw0weDFhnySS4mirFMntlTCN6JVeclOOejC46E1TpjTKQYreNIIuRNVBtEg/cusMGyDcYaFUsa1Ed26oNaG9hbz@AEUIwGC6cXMaxBgrWqDi4mtpYxzvvJWbv@zdoXA7Dxpula2KiXTTdtq3aKvrVt33ZVN20qDNJs6GkDJzzoZ4fnLBSRf4874bvqhVYjrG/@M2yQwIvjjvts6qSYbmhS2m36Hvc9fJrkTfx1ndTDhqCTqAJVRDXOs1L6ydFE4/H7nUT8cDJGSDmGJC4RvKEIoDk45hCjCSFEcVhShRogIrwhL9VI1rAzUBv0aTggiVIKsEA7ZCAS6y1BgGqit0oOYQ7idJwiSSUaZIa8hGNEMiRhNRQJFJCuJauWSA0L6hEbA4mHbElJcBo8WcEuEgwZUC6Y2UHCjhjHxKIWSVtFNSYmChwH8QHb9J5t1KgenEiO8@VUFQU7xAQXIiMgJgRyRqwZJsOMbmqqN6IVQqkrDrk8ZtZIOic2AEJDnY7yHiemn73Ce18vb7fvFl@@FsVhuIGybIN7Cbfe6/tlceioH99b2XyeHTruH/Jydo69KJL/Tyz9wj7g/fD4Ew "Dart – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 254 bytes ``` #include"gmp.h" f(i,o)char*i,*o;{mpz_t l;char*c="><+-.,[]";if(*i>47&*i<58)for(mpz_init_set_str(l,i,0),mpz_get_str(o,8,l);*o;*o++=o[1]?c[o[1]-48]:0);else for(mpz_init_set_si(l,1);mpz_get_str(o,10,l),*i;mpz_mul_si(l,l,8),mpz_add_ui(l,l,strchr(c,*i++)-c));} ``` [Try it online!](https://tio.run/##ZZDdaoQwEIXvfYpgaUniuOiyZW2j2wexsthodCAa8acXFV@9NrpLoXRgmOE7hxMy0q@kXB@wlXoqShIPY49tdagvv8ytmu5Qu46iCIbJOu85Ajdibrqv60i02JFM3Evs@QdIM1egohwvp/MTx/g5Ysr0dDNji@N1KG2PPdWAEDDYeHVHBiLQTNhsbjwvMWmYvcl0G/4pyl4DJko9lOR/HNq0kIm/WWFgw4DjjptJ32waotujeVFcpxuxfln3VFqz5zFfMiaWFduRNDm2dFvyvpJAto8SbvfPNGNkdoitnZmPSaUvtjKSkDlYxC4pulvDDDadCWennb3vqKj7OLy3LpC7tKzr@Xj8lkrn1bD62t78Bw "C (gcc) – Try It Online") Determines which direction to go based on input (`i`), stores the result in the passed buffer (`o`). Note that some compilers allow saving of 4 bytes based on the implementation-defined ordering of the o++. In these cases the provided solution will truncate an extra character off of the Unary->BF conversion and the `o[1]`'s can all be replaced by `*o` to recover behaviour. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 17 + 15 = 32 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` "><+-.,[]"$€Ȯ1Ƥ8ḋ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSUyMiUzRSUzQyUyQi0uJTJDJTVCJTVEJTIyJTI0JUUyJTgyJUFDJUM4JUFFMSVDNiVBNDglRTElQjglOEImZm9vdGVyPSZpbnB1dD0lMkIlMkIlMkIlMkIlMkIlMkIlNUIlM0UlMkIlMkIlMkIlMkIlMkIlMkIlMkIlMkIlMkIlMkIlMkIlMkIlM0MtJTVEJTNFLiUzRSUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiU1QiUzRSUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiUyQiUzQy0lNUQlM0UlMkIuJTJCJTJCJTJCJTJCJTJCJTJCJTJCLi4lMkIlMkIlMkIuJTNFJTJCJTJCJTJCJTJCJTVCJTNFJTJCJTJCJTJCJTJCJTJCJTJCJTJCJTJCJTJCJTJCJTJCJTNDLSU1RCUzRS4lM0MlMkIlMkIlMkIlNUIlM0UtLS0tJTNDLSU1RCUzRS4lM0MlM0MlM0MlM0MlM0MlMkIlMkIlMkIlNUIlM0UlMkIlMkIlMkIlMkIlMkIlM0MtJTVEJTNFLiUzRSUzRS4lMkIlMkIlMkIuLS0tLS0tLi0tLS0tLS0tLiUzRSUzRSUyQi4mZmxhZ3M9) (Brainfuck -> Unary) ``` 8Bḣ"><+-.,[]"si ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPThCJUUxJUI4JUEzJTIyJTNFJTNDJTJCLS4lMkMlNUIlNUQlMjJzaSZmb290ZXI9JmlucHV0PTIzOTIzNDEwNzExNzA4ODc2MjQ1NjcyODY2Nzk2ODYwMjE1NDYzMzM5MDk5NDYxOTAyMjA3Mzk1NDgyNTg3NzY4MTM2MzM0ODM0MzUyNDA1ODU3OTE2NTc4NTQ0ODE3NDcxODc2ODc3MjM1ODQ4NTQ3MjIzMTU4Mjg0NDU1Njg0ODEwMTQ0MTU1NiZmbGFncz1K) (Unary -> Brainfuck) #### Explanation ``` "><+-.,[]"$€Ȯ1Ƥ8ḋ # Implicit input "><+-.,[]" # Push the string $€Ȯ # Index of each character in the input 1Ƥ # Prepend a 1 8ḋ # Convert from base 8 # Implicit output ``` ``` 8Bḣ"><+-.,[]"si # Implicit input 8B # Convert to base 8 ḣ # Remove the leading 1 "><+-.,[]"si # Index into the string # Implicit output ``` ]
[Question] [ Transposition is an operation on 2-dimensional arrays that flips every element across the main diagonal: ``` [[1,2,3], [[1,4], [4,5,6]] -> [2,5], [3,6]] ``` If we call the above array `m`, then the `2` is the second item of the first row of `m`, or `m[0][1]`. The `2` can be thought of as having a *coordinate* of `[0, 1]` in the array because of this. When the matrix is transposed, the `2` moves to the first item of the second row, or `m[1][0]`, and its coordinate is now `[1, 0]`. In general, tranposition can be described as taking the coordinate of every item in the array and swapping the first and second item. This can be generalised to higher dimensions by taking the coordinate rotating it left by one item - moving the first item of the coordinate to the end. This idea of a coordinate extends fairly easily to arrays of higher dimensions. For example, with the array `z = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]`, the `6` is `z[1][0][1]`, and its coordinate is `[1, 0, 1]`. If we apply the same idea of transposition to this coordinate, the coordinate of 6 `[1, 0, 1]` is shifted left by one item to result in `[0, 1, 1]`, meaning it is now `z[0][1][1]`. Similarly, the `2` with coordinate `[0, 0, 1]` is rotated left to result in `[0, 1, 0]`If we apply this operation to every element of the array, we get `[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]`. Your challenge is to apply this transformation to a multidimensional rectangular array of positive integers. You may additionally take the dimensions of the array. ## Testcases ``` [[1]] -> [[1]] [[[[1, 2]]]] -> [[[[1], [2]]]] [[1, 2, 3], [4, 5, 6]] -> [[1, 4], [2, 5], [3, 6]] [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] -> [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] [[[[9]], [[10]]]] -> [[[[9]]], [[[10]]]] [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]] -> [[[1, 7], [2, 8], [3, 9]], [[4, 10], [5, 11], [6, 12]]] ``` [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` f=lambda a,b:b<2and[*a]or[f(x,b-1)for x in zip(*a)] ``` [Try it online!](https://tio.run/##bY/BbsIwEETP5CvmRow2CCfQAir9EWsPG0URlohjmVRK@vOpHQonTvt2Z3ak8dNw7V01z@3lJl3dCITqc/1VimvMRrgPps1Hqgut2j5ghHX4tT7fiOLZdr4PA9xP5yfIHc5nggtMZoxmpjgiEErmx5aYUDHB7AkHwse/azHFa0XYcwKziBE@CUd@Zp0emt49A98nRkt6I5wS6x1BR58ulyfOXj3knK18sG6IBbEuvteE1DXW2EoIMuWj2rrGdkrNfw "Python 3 – Try It Online") Takes as input the list and then the dimension. If we look at the list of dimensions, a 2D transpose is equivalent to swapping the first two, so if we recursively do that we swap dimensions 0,1, then 1,2, and so on, so we move the first dimension to the last position. If the output can contain have tuples in the topmost level it can be -1 by replacing `and[*a]or` with `and a or`. # [Python 3](https://docs.python.org/3/) + [numpy](https://numpy.org/), ~~37~~ 36 bytes -1 thanks to @loopwalt ``` lambda a,b:a.transpose(range(1-b,1)) ``` [Try it online!](https://tio.run/##bY/LDoIwEEXX9ivuzpKMxIrvRH@kdjFEURIpTcEEvh4H1J2b9kzvI9PQt4/aZ0NZhTq28K8q9OAGPqjidBmeXOVXBlN@5LSN7JtQNzctcL9ps8jJJMnAOMEqa41zJJcAYeXcZxqZkDmCXRM2hO3XNZnkNSOs3Qh2EgV2hL37dR0@mln@Cv83imWMEQ4jmyXBiM@sppBTRR3RofTgo5pxjLKxD6kA97pL1CzE0re6I8wX5zmh0CIR5Ej9tazkj28 "Python 3 – Try It Online") Takes a numpy array and the dimension as input. [Answer] # [R](https://www.r-project.org), 23 bytes ``` \(x,d)aperm(x,1:d%%d+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhbbYzQqdFI0EwtSi3KBLEOrFFXVFG1DTYjsTe0KBRtdhcSiosRKDUMrIxMdhZTMXAVbhWQNIx0FYx0FE01NrgquNKBOY6iWBQsgNAA) A situation where R has a built-in that meets the requirements! A function that takes a multidimensional array and the number of dimensions as its two parameters and returns a multidimensional array with the coordinates transposed left one. Note that in the printout R loops through dimensions that are 3 or above, printing a 2d matrix for each 2d plane. Within that matrix, rows are dimension 1 and columns are dimension 2. Thanks to @Giuseppe for suggesting a fix that works for 1-dimensional arrays. [Answer] # [Uiua](https://uiua.org), 1 [byte](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==) ``` ⍉ ``` [Try it!](https://uiua.org/pad?src=4o2JW1sxXV0K4o2JW1tbWzEgMl1dXV0K4o2JW1sxIDIgM10gWzQgNSA2XV0K4o2JW1tbMSAyXSBbMyA0XV0gW1s1IDZdIFs3IDhdXV0K4o2JW1tbWzldXSBbWzEwXV1dXQrijYlbW1sxIDIgM10gWzQgNSA2XV0gW1s3IDggOV0gWzEwIDExIDEyXV1d) (When reading the output, dashes on the left indicate the rank of the array and whitespace separates axes.) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes ``` ʷ∑→ᵉbD ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmtPbX_UMfFR26SHWzuTXJYUJyUXQ2UW3KyOjjaMjeWKBgJDHaPYWDAbyNIxjtWJNtEx1TGDyIIkdaKNdUxigVQ0SFgn2lzHIhaq1xIsbGgANQDdBKAcULGOJZBhaKBjaKhjCLIK4gYA) ``` ʷ∑→ᵉbD Take [[[1,2],[3,4]],[[5,6],[7,8]]] as an example ʷ∑ Sum of the nested array [[[1,2],[3,4]],[[5,6],[7,8]]] -> 36 → Increment 36 -> 37 ᵉb Convert the input from a list of digits in that base [[[1,2],[3,4]],[[5,6],[7,8]]], 37 -> [[42,80],[118,156]] D Convert each number back to a list of digits in that base [[42,80],[118,156]], 37 -> [[[1,5],[2,6]],[[3,7],[4,8]]] ``` This works because `b` and `D` are vectorized in different ways. `b` (`\fromBase`) is not vectorized by itself. It simply views the input as a list of digits in that base. However, when converting the list of digits to a number, the addition and multiplication are vectorized. For example `[[[1,2],[3,4]],[[5,6],[7,8]]] 37 b` is `[[1,2],[3,4]]*37+[[5,6],[7,8]]=[[42,80],[118,156]]`. `D` (`\toBase`) is vectorized in the usual way. It converts each number in the input to a list of digits in that base. For example `[[42,80],[118,156]] 37 D` converts each number (`42`,`80`,`118`,`156`) to a list of digits in base 37, which is `[[[1,5],[2,6]],[[3,7],[4,8]]]`. [Answer] # [Python 2](https://docs.python.org/2/), 33 bytes ``` f=lambda*L:L*(L<(f,))or map(f,*L) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNxXTbHMSc5NSErV8rHy0NHxsNNJ0NDXzixRyEwuATC0fTajCz2lAwUSdZJ1Uhcw8hWhDHSMdw1idaCMdYx2TWCsuhQoFW4Xo6Ogk7RTtdAWQ2nSQuqLEvPRUjVTNWJBICkIkGSKShBBJ1IzlUigoyswrUajQSdPQqtDkgtoItg9iG4pdQKsUyDYWpMJQxwRqGEwtmlKI12FhBQA) Ports @Command Masters Python 3 (non numpy). Takes splatted input. Innermost lists will be tuples. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` JΔ€`}\N<Ý®K"€"×'ø«J.V ``` [Try it online](https://tio.run/##yy9OTMpM/f/f69yUR01rEmpj/GwOzz20zlsJyFM6PF398I5Dq730wv7/j46ONtQx0jGO1Yk20THVMYsFMqLNdSx0LIEMQwMdQ0MdQ6PY2FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf69zUx41rUmojfGzOTz30DpvJSBP6fB09cM7Dq320gv7r/M/OjraMDZWRyEaxNAxio2FcIBMHeNYnWgTHVMdM6g8SFon2ljHBMiPjgaJ60Sb61jEwrRbgsUNDWBmYBgSDVKuYwlkGBroGBrqGIKtAwA). **Explanation:** ``` J # Join each inner-most list together to a single item Δ€`}\N< # Then determine the depth-2 of this multidimensional list Δ } # Loop until it no longer changes: €` # Flatten it one level down \ # After the changes-loop, discard the resulting flattened list N # Push the last 0-based index < # Decrease it by 1 Ý # Push a list in the range [0,depth-2] ®K # Remove -1 so [0,-1] becomes [0] "€"× # Convert each value in this list to that many "€" as string 'ø« '# Append an "ø" to each string J # Join this list of strings together .V # Evaluate and execute it as 05AB1E code on the (implicit) input # (after which the result is output implicitly) ``` [Try all test cases without the `.V`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf69zUx41rUmojfGzOTz30DpvJSBP6fB09cM7Dq32@q/zPzo62jA2VkchGsTQMYqNhXCATB3jWJ1oEx1THTOoPEhaJ9pYxwTIj44GietEm@tYxMK0W4LFDQ1gZmAYEg1SrmMJZBga6Bga6hiCrQMA) to see which maps/transpose builtins are actually being generated by `JΔ€`}\N<Ý®K"€"×'ø«J`, where `€` is a map (and therefore `€€` a nested map) and `ø` transposes a matrix/2D-list, swapping its rows/columns. ***Minor notes:*** 1. Using `Δ€`}\NÍ` (where `Í` is -2) only seems to work for the last test case: [try it online](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3NTHjWtSaiN8Tvce3juoXXeSkCu0uHp6od3HFrtpRf2X@d/dHS0YWysjkI0iKFjFBsL4QCZOsaxOtEmOqY6ZlB5kLROtLGOCZAfHQ0S14k217GIhWm3BIsbGsDMwDAkGqRcxxLIMDTQMTTUMQRbBwA); and with `<` but without the leading `J` it works for some of the test cases, but not the last two: [try it online](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3NTHjWtSaiN8bM5PPfQOm8lIE/p8HT1wzsOrfbSC/uv8z86OtowNlZHIRrE0DGKjYVwgEwd41idaBMdUx0zqDxIWifaWMcEyI@OBonrRJvrWMTCtFuCxQ0NYGZgGBINUq5jCWQYGugYGuoYgq0DAA); so using a leading `J` and `>` works for all test cases. 2. The range builtin `Ý` also accepts negative values for its \$[0,n]\$-ranged list. So for singular lists, it'll result in `[0,-1]` after both the `J` and `Δ€`}\N<`, for which the `-1` are ignored by the `×` and it basically evaluates `ø-1ø`: [try it online](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf69zUx41rUmojfGzOTxXCchUOjxd/fCOQ6u99ML@6/yPjo42jI3VUYgGMXSMYmMhHCBTxzhWJ9pEx1THDCoPktaJNtYxAfKjo0HiOtHmOhaxMO2WYHFDA5gZGIZEg5TrWAIZhgY6hoY6hmDrAA). 3. Why use `"€"` for string `€` but `'ø` for string `ø`? Because `'` is also used for pushing [a dictionary word](https://codegolf.stackexchange.com/a/166851/52210), and `'€×` is apparently the dictionary word `view`: [try it online](https://tio.run/##yy9OTMpM/f9f/VHTmsPT//8HAA); whereas `'ø«` is coincidentally none: [try it online](https://tio.run/##yy9OTMpM/f9f/fCOQ6v//wcA). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ⊞υθFυ«≔E⌊ιEι§μληWι≔⊟ικFη⊞ικFη¿⁺⟦⟧⌊κ⊞υκ»⭆¹θ ``` [Try it online!](https://tio.run/##XU65asNAEK2tr3jlLIwhcnwFVy5dGAQphQrhawetJFvSJoHgb1/PCrvxNHO962DL7tCWLoTM95Y842Y2ybntQN7gP5ls@14uDe3LK@2lkdrXJIYRd2Fsh11zPP1RzXDG6N0qe/JrxZ2gODzZWXsdWVX8juLWYDSUt6OcQZnzPeWFmjwNK5XGK1@E35Osk2ag70HbJWZJY3CzCSHX0mXG@FSFfM5YMJZFnPMVY834inP6wUgVl84KrTD9cQ8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @CommandMaster's Python 3 answer. ``` ⊞υθ ``` Start by processing the input array. ``` Fυ« ``` Loop over the arrays that need to be transposed. ``` ≔E⌊ιEι§μλη ``` Transpose the top two dimensions of the current array. ``` Wι≔⊟ικFη⊞ικ ``` Replace the contents of the original array with that of the transposed array, thus transposing the array in-place. ``` Fη¿⁺⟦⟧⌊κ⊞υκ ``` If the elements of the transposed arrays are themselves arrays rather than lists of numbers, then push those arrays so that they get transposed in-place. ``` »⭆¹θ ``` Pretty-print the final state of the original array. 41 bytes using the newer version of Charcoal on ATO: ``` W⁺⟦⟧ΣΣθ«⊞υL⌊⌊θUMθΣκ»≔E⌊θEθ§λκθF⮌υ≔⪪θιθ⭆¹θ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY_BasMwDIbPzVOInmRQYenWtaWnstNghbAcQw5Z6iamjtPEdjcYe5JdetjY3menvs1kmsEERrL0_T_S-3dZF33ZFvp0-vRuN1mcf55rpSVgor3FLCdIfYPhdUIIeI1Gibc1eoIHaSpX40YZ1fD4LwdMrKLRpjjctU1TmC12F5N96L9Fa2tVZZDn_zQE4c_g2t2brXxBTcA89zsW7doe8FEeZW8lel5j8EgPWrmgUgOY9Mo4TB2nKhjGoS1WH_aptMOBX9l4ctTj_DzLOBiYElzzmdkNwYzgNg91NidYECxDHV8RxMzF05zjYvIL "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: ``` W⁺⟦⟧ΣΣθ« ``` Until the input array has two dimensions, ... ``` ⊞υL⌊⌊θ ``` ... record the number of elements in the third dimension, and... ``` UMθΣκ ``` ... flatten the third dimension into the second dimension. ``` »≔E⌊θEθ§λκθ ``` Transpose the array. ``` F⮌υ ``` Loop over the sizes of the dimensions. ``` ≔⪪θιθ ``` Unflatten the array. ``` ⭆¹θ ``` Pretty-print the final array. 32 bytes by taking the dimensions of the array as a second argument: ``` F✂η²UMθΣκ≔E⌊θEθ§λκθF⮌✂η²≔⪪θιθ⭆¹θ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY49DsIwDIV3TmExJZKRaPkrYgExMSAhOlYZSgkQkaa0CYi7sDDwdyVugwNd8GLr-XvPvryyXVplRaqv1_vRbVrR-7EpKmCxVplkO4SQc5inh2mR56lZsxIhPuZsz_moMbFWbQ2jLZsro3LSS46e9tjEzcxanplGIJr0kizf7KU8ycrKvxsc6rT4oJXzflVbFpUyjsWO2tZHB17mo5tdZbb--Zk0WyfdFO9xQkVAiNARCEkXoYfQF35OBggRwtDPQRshIC4IxXcX1hbxy_sA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: As above, but using the input dimensions, ignoring the first two which aren't needed. 26 bytes by taking a list of dimensions and a flattened array as I/O: ``` F…θ¹I⟦⊞OΦθλιEη§§⪪η÷Lηιλ÷λι ``` [Try it online!](https://tio.run/##RY7dCsIwDIVfJZcpRHDzH69kIgwUB16WXZSt2kLpZleHPn3tNkTIIeF8OSGVEq5qhAnh3jjA7FMZmammxSdBwhgUTluPmeg88uLVqWsrnfCNw5M2XrphzTACHXURLSqCg89tLd/467fWaD@A3Pqj7nUt8SztwytUY5BNF/7UjC4rGduHwHlKEGtREvBkGgmWBCuCNcGGYEuwi7/OoyJP0rIMs958AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input dimensions … Truncated to length ¹ Literal integer `1` F Loop over dimension θ Input dimensions Φ Filtered where λ Not first dimension ⊞O Concatenated with ι First dimension η Input array E Map over elements η Input array ⪪ Split into arrays of length η Input array L Length ÷ Integer divided by ι First dimension § Cyclically indexed by λ Current index § Indexed by λ Current index ÷ Integer divided by ι First dimension ⟦ Separate dimensions from elements I Implicitly print ``` `F…θ¹` saves a byte over `≔§θ⁰ι` and two bytes over repeating `§θ⁰` instead of `ι`. (Length of array could also be product of dimensions of course.) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` #0/@Thread@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lA3yEkoyg1McVBWe1/QFFmXkm0sq5dWrRybKxaXXByYl5dNVd1tWFtrQ6QAjJ0jGprIRwgU8e4VqfaRMdUxwwqD5LWqTbWMQHyq6tB4jrV5joWtTDtlmBxQwOQGVy1/wE "Wolfram Language (Mathematica) – Try It Online") Input `[array]`. Recursively `Thread`s the first dimension through all other dimensions. `Thread` behaves more nicely than `\[Transpose]` on arrays of dimension <2. --- ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` D'[[0]][,{##},Listable] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b730U9OtogNjZap1pZuVbHJ7O4JDEpJzX2f0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXdbVhba0OkAIydIxqayEcIFPHuFan2kTHVMcMKg@S1qk21jEB8qurQeI61eY6FrUw7ZZgcUMDkBlctf8B "Wolfram Language (Mathematica) – Try It Online") Taking a rare chance to showcase [`Function`](https://reference.wolfram.com/language/ref/Function.html)'s 3-argument form, which lets us set [attributes](https://reference.wolfram.com/language/guide/Attributes.html) on a pure function, even if this ends up being almost twice the length of the shortest solution. Input `[array...]`. Append `@@#&` to take `[array]` input. A [`Listable`](https://reference.wolfram.com/language/ref/Listable.html) function that enlists its arguments. `D'[[0]]` is slightly shorter than writing out `Function`. [Answer] # [Julia](https://julialang.org), 37 bytes ``` ~=ndims !x=permutedims(x,[~x;1:~x-1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVFBbtswEESufMXaRQEKpYXQcWJHhXppfcihTQ8pYEDQgbUplIVEqRLV0hd_JBdf8oQ-pnlNlhQdO81eNJyd2R2s7h9-9qUS-_1Db4rJ4t_bXao3qurIyKaNbKveSPeklmU7-54nOzvheTSIH8_-irYVW1VsqU2SG20iSMGSI8lW6eERUxu59loYuorjmIGbOyyjqwyHvuMRIUXdggKloZViUyotOxoRwBJM2gb9x3nytyhj-lkaETei7WRMu6ZUhioGY5h8gHGE5b1Nq7Sh45svCZKe2SjUii0VLwS33-5eKUZBogoYCRilgDE8ceJbrr4uP94tPz2bTwegfiCl3hyXlZqO01eFdqcib3RtZALmh4RCtZ1xt5K6U7WGugABlTCtsqA6L1nXZV9p5jDerf7D4HtvQBnXX9dVU0pTbkH-6hVeTGoz_L3949kyw7vn7lYekAyLM5jm-YF1PIPMM2RoMrhw1IzBJYOrZzuDmVci7b4XvkcOAwdmljuQeR-COYPFcRMPzql3Oh065mHVIg_xrocWPz_NiKRnA33Y-n9SJ3E7GVw7zM8ZcNTx6YsQ8xBiEUKHjTgFpyO6dC4HroJ1OOcT) ]
[Question] [ Say I have a grid with some obstacles: ``` ---- | X | | | |XX | | | ---- ``` I can fill this with numbers, as distance from the top left corner. But, because there are obstacles in the way some cells will take further to reach than a straight line: ``` ---- |01X5| |1234| |XX45| |7656| ---- ``` This can be done through flood filling: ``` ---- ---- ---- ---- ---- ---- ---- ---- |0 X | |01X | |01X | |01X | |01X | |01X5| |01X5| |01X5| | | |1 | |12 | |123 | |1234| |1234| |1234| |1234| |XX | |XX | |XX | |XX | |XX4 | |XX45| |XX45| |XX45| | | | | | | | | | | | 5 | | 656| |7656| ---- ---- ---- ---- ---- ---- ---- ---- ``` Your challenge is to, given a binary matrix containing obstacles, flood fill it like so from the top left hand corner and output a corresponding matrix. The first example of a grid is equivalent to the following matrix: ``` [ [0, 0, 1, 0], [0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0] ] ``` And the corresponding output would be: ``` [ [0, 1, X, 5], [1, 2, 3, 4], [X, X, 4, 5], [7, 6, 5, 6] ] ``` Where X is any value that isn't a positive integer. You may take any two consistent values in the matrix instead of 1 and 0, and you may choose any value to represent obstacles. Distances may be 0 or 1-indexed. You may assume the whole matrix can be flood filled from the top left corner, which cannot be an obstacle. You must be able to support numbers with multiple digits. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases These use -1 as X. ``` [ [0, 0, 1, 0], [0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0] ] -> [ [0, 1, -1, 5], [1, 2, 3, 4], [-1, -1, 4, 5], [7, 6, 5, 6] ] [ [0, 0, 0] ] -> [ [0, 1, 2] ] [ [0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0] ] -> [ [0, -1, 4, 5, 6, -1, 10], [1, 2, 3, -1, 7, 8, 9] ] ``` [Answer] # [J](http://jsoftware.com/), 54 46 bytes ``` [:(#-+/)](+[:+./(0,(,-)=0 1)|.!.0=&1)^:a:${.1: ``` [Try it online!](https://tio.run/##dY5NCsJADIX3PUW0xc7YmcxUBCHSMii4EhduSy0iiu3GA7T06jX9UVcSAu8l@ZJU3RzDByQEISiwQJwaYX8@HrqMhK8jI3MRZRShEVYJpWViIZYNztAmi1he6EpBjTF10jvtEBiq0dWoc8mQ@bKpqrdtSROZJzH90AHUOF5zgscBl323ZbdKG6cNK3@hggqN86lEF3je/fZ8wQNgzRHw2xYKThhUH2yLUUyVkQi1Dj@son@dFWyGpcUEF789U6l7Aw "J – Try It Online") [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~36~~ 34 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Uses `∞` for obstacles in input and output. ``` {(𝕩⌈⊢⌊1+(«˘⌈«⌈»⌈»˘)⌾÷)⍟(≠⥊)0⌾⊑∞¨𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjwnZWp4oyI4oqi4oyKMSsowqvLmOKMiMKr4oyIwrvijIjCu8uYKeKMvsO3KeKNnyjiiaDipYopMOKMvuKKkeKInsKo8J2VqX0KCkbCqCDin6gKWyBbMCwgMCwg4oieLCAwXSwgWzAsIDAsIDAsIDBdLCBb4oieLCDiiJ4sIDAsIDBdLCBbMCwgMCwgMCwgMF0gXQpbIFswLCAwLCAwXSBdClsgWzAsIOKIniwgMCwgMCwgMCwg4oieLCAwXSwgWzAsIDAsIDAsIOKIniwgMCwgMCwgMF0gXQrin6k=) `0⌾⊑∞¨𝕩` Generate a matrix of the same shape as the input, with a 0 in the top left corner and ∞ anywhere else. `( ... )⍟(≠⥊)` Iterate the function on the left as many times as there are values in the matrix. (You could get away with less iterations, but this is golfy) `(𝕩⌈⊢⌊1+(«˘⌈«⌈»⌈»˘)⌾÷)` Tacit function that performs one step of flood filling: `( ... )⌾÷` Take the reciprocal of each value, do some transformations on that, then take the reciprocal (its own inverse) again. The idea is that we want to shift in ∞ from each side, then take the element-wise minimum between the four matrices. BQN shift builtins `»` and `«` push in 0 instead, which is why do the shifting in "reciprocal space". `«˘⌈«⌈»⌈»˘` pushes in 0s from all four directions, and takes the element-wise maximum. Now we increment each value (`1+`), take the minimum with the previous step (`⊢⌊`) and the maximum with the input (`𝕩⌈`) to make sure the obstacles stay at ∞. --- An adjacency matrix based approach is much longer at 52 bytes: ``` ↕∘≢{𝕩⌈+˝¬⊏˘>(𝕩=⌜˜⊸≥(+´|∘-)⌜˜𝕨)∨˝∘∧⎉1‿∞⍟(↕≠𝕩)≡⌜˜𝕨}⌾⥊⊢ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oaV4oiY4omie/CdlanijIgry53CrOKKj8uYPijwnZWpPeKMnMuc4oq44omlKCvCtHziiJgtKeKMnMuc8J2VqCniiKjLneKImOKIp+KOiTHigL/iiJ7ijZ8o4oaV4omg8J2VqSniiaHijJzLnPCdlah94oy+4qWK4oqiCgpGwqgg4p+oClsgWzAsIDAsIOKIniwgMF0sIFswLCAwLCAwLCAwXSwgW+KIniwg4oieLCAwLCAwXSwgWzAsIDAsIDAsIDBdIF0KWyBbMCwgMCwgMF0gXQpbIFswLCDiiJ4sIDAsIDAsIDAsIOKIniwgMF0sIFswLCAwLCAwLCDiiJ4sIDAsIDAsIDBdIF0K4p+p) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes ``` ẸŻạ§ỊẸʋƇ@ƬŒMŒṬ+C¬S: ``` [Try it online!](https://tio.run/##y0rNyan8///hrh1Hdz/ctfDQ8oe7u4CcU93H2h2OrTk6yffopIc712g7H1oTbPX/cLv7///R0YY6CkBkACRjdRSiDcA8QygPKoHgweRiAQ "Jelly – Try It Online") Inspired by @Jonathan Allan's answer (it started as a golf of that answer, but portions were rewritten, and it changed so extensively that it makes more sense to post a new answer); this answer uses a similar algorithm (although not exactly the same). Output is 1-based, using NaN for walls. ## Explanation ``` ẸŻạ§ỊẸʋƇ@ƬŒMŒṬ+C¬S: Ẹ 1 if the input contains any nonzeros (it does) Ż prepend 0 (thus creating [0,1]) Ƭ Loop until we reach a steady state: Ƈ {Set the loop variable to} a filtered subset of @ ŒM the multidimensional indexes of {the input} Ƈ keeping only those elements for which ʋ the following four-step procedure {returns true}: ạ absolute difference of {the index} from {the loop variable, or each of its elements} § add the x-difference to the y-difference Ẹ at least one of those difference sums Ị has a magnitude of at most 1 ŒṬ {For each iteration}, create an array with 1s at the indexes {in that iteration's loop variable} + {For each iteration's array}, add, and reshape to, C {the input} with each element subtracted from 1 ¬ Replace 0s with 1s, other values with 0s S Sum {the arrays from each iteration} : Integer divide by {the input grid} ``` The basic idea is that we maintain a list of coordinates that our flood fill has reached, and repeatedly filter the list of non-wall coordinates to find those coordinates which are close to those in the previous iteration. The initial coordinate, used on the first iteration, is [0,1]. Jelly uses 1-based indexing, so this is actually outside the array (but still at a distance of 1 from the top-left corner, allowing the loop to get started). The loop is written as a data-type polyglot; it works both on a single coordinate pair (such as [0,1]), and on a list of coordinate pairs (which is what it gets on every subsequent iteration). After the loop, the `ŒṬ` can treat the [0,1] the same way as all the coordinate lists (basically producing an array with no coordinates), so it doesn't matter that the loop variable is a coordinate pair on the first iteration and a list of coordinate pairs on subsequent iterations. The `+C` doesn't have any effect on the array values (other than setting the value of walls to 1); its purpose is to pad out all the arrays generated by `ŒṬ` so that they're the same size as the input, making it possible to use `¬` to place 1s in all the squares that the flood-fill hadn't reached by that iteration. Then we can just sum the arrays to learn how long it took to reach each square, as in the other two Jelly answers. Although Jelly has a constant `Ø.` to produce the list [0,1], writing it at the start of the program would trigger a special case in the parser, which would subsequently cause the `ŒM` later in the program to parse incorrectly. As a consequence, we need to generate the [0,1] as a function of the input, rather than using a constant, but fortunately this is possible in two bytes and thus the special case in question ends up not costing. (Because the input has a 1 in the top-left corner, there's guaranteed to be at least one nonzero value in the input.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ŒM_Ø.ŒṬ»ḤZUµ4¡«³ FJỊṁ³ÇƬ¬S: ``` [Try it online!](https://tio.run/##y0rNyan8///oJN/4wzP0jk56uHPNod0PdyyJCj201eTQwkOrD23mcvN6uLvr4c7GQ5sPtx9bc2hNsNX///@jow11DHUMdECkYaxONJQFEgHyYHIgXiwA "Jelly – Try It Online") Input format: 0 for wall, 1 for passable cell. Output format: 0-based, walls are represented as floating-point infinity. This only works as a full program, because it assumes that the first command-line argument and the input to the main function are the same as each other (which they will be for a full program, but not for a function run as part of a larger program). ## Explanation ### Helper function `1Ŀ` The helper function takes a matrix of 1s and 0s as its input; everywhere that's a 0 in the program input must be a 0 in the helper function input, but otherwise the helper function can have 1s and 0s anywhere. The output from the helper function is the same matrix with every non-wall space (based on the input to the program as a whole) filled with a 1 if it was or was adjacent to a 1 in the helper function input, or 0 otherwise. The basic algorithm is to double the value of every cell of the helper function input, and place a 1 to the left of every maximal-valued cell unless there was already a higher value there. Then we rotate our working value 90 degrees, and repeat a further three times. The values that were 1 in the helper function input will always be the maximal-valued cells (having been doubled more often than the cells we set to 1 during the helper function), so the four iterations set the cells to the left, beneath, to the right, and above them to positive values respectively (and then we're rotated back to the array's original orientation). Once we've done our placing of 1s to the left four times, we simply just maximum with the input to the program as a whole; this sets all the 1s, 2s, 4s, 8s, and 16s to 1, except for cells which were 0 in the program input which are set to 0, implementing the desired behaviour of the helper function. ``` ŒM_Ø.ŒṬ»ḤZUµ4¡«³ ŒM Indexes of maximal elements _Ø. Subtract [0, 1] (i.e. the indexes to their left) ŒṬ Create an array with 1s at only those indexes » Take the maximum of that array and Ḥ twice {the working value as of the start of this iteration} ZU Transpose and flip (i.e. rotate 90°) ¡ Repeat µ everything in this function so far 4 4 times « Take the {element-wise} minimum of that and ³ the first command-line argument to this program ``` Jelly helpfully handles the edge of the array for us – if `ŒṬ` sees a coordinate before the left edge of the array, it won't add it to the array it's creating. (However, it will nonetheless make use of the coordinate to know how many dimensions the array it's creating is meant to have, avoiding a crash if there are no indexes in range.) ### Main program Half the code in this is to create an array that's the same shape as the input array, but has a 1 in the top-left corner and 0s everywhere else (i.e. the location we're flood-filling from). Then, we run the helper function repeatedly to flood-fill, and convert the output to the desired format. ``` FJỊṁ³ÇƬ¬S: F Flatten the input array J Create a list from 1 to the length {of the flattened array} Ị Map 1 to 1, larger values to 0 ṁ Reshape back to the shape of the input ³ {no-op, fixes a parsing ambiguity by breaking up ṁÇ} Ç Call the function 1Ŀ Ƭ in a loop, until nothing changes, remember all results ¬ Swap 0s and 1s {in the list of outputs of 1Ŀ} S Sum {for each cell, the number of iterations it was 0} : Divide {cells by the corresponding input cell} ``` The basic idea is that a cell that should be 0 in the output has been 0 for no iterations of `1Ŀ` calls; a cell that should be 1 in the output has been 0 for one iteration; a cell that should be 2 in the output has been 0 for two iterations, and so on (i.e. we can use the length of time the one-step floodfills took to reach a particular square to discover its distance from the starting point). So we can just count the number of iterations for which each cell was 0. In order to place non-integers in the cells which are walls in the input (these cells would "naturally" hold the largest value in the output plus 1), it's possible to use division with the input; for non-wall cells, this divides by 1 (a no-op), and for wall cells, this divides by 0 (returning floating-point infinity, which is not a positive integer). (`:` is normally integer division, so it returns an integer in most cases, but it returns floating-point infinity when dividing by 0.) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 121 bytes ``` ^. 0 {P^` +\S+ (?<=(.)*) +_(?=(.*¶(?<-1>.)*(?(1)^))? +(\d+)|(?<=(?<3>\d+)((?(5)$)(?<-5>.)*¶.*)? +_(?=(.)*))) $.($3*__ ``` [Try it online!](https://tio.run/##JYwxCsMwDEV3ncKDB8kmpiZkS@MrFLp4CFYL7dClQ@nWnisHyMUcyQbB/3p66PP8vt73WGsJcAIw8LuUm/Hr1QOm@YyBHBnPmKS6fRM2xEUgJoxUiJLxuD48/Zud5nHRDeU8kSXVJ9X3LTh1@yP5SQTGBrSjY66VMzPnDJLSWuoA9wKCO5dsvPl6b@0A "Retina – Try It Online") Uses `_` for `0` and `X` for `1`. Explanation: ``` ^. 0 ``` Start flood filling at the top left. ``` ``` Space everything apart. ``` {` ``` Repeat until everything has been filled. ``` P^` +\S+ ``` Align all of the columns to the largest value found so far. ``` (?<=(.)*) +_(?=(.*¶(?<-1>.)*(?(1)^))? +(\d+)|(?<=(?<3>\d+)((?(5)$)(?<-5>.)*¶.*)? +_(?=(.)*))) ``` Match underscores that are either to the left ( `+_(?= +(\d+))`), above (`(?<=(.)*) +_(?=.*¶(?<-1>.)*(?(1)^) +(\d+)`), to the right ( `+_(?<=(?<3>\d+) +_)`) or below ( `+_(?<=(?<3>\d+)(?(5)$)(?<-5>.)*¶.* +_(?=(.)*))`) an integer, ensuring to capture the integer in capture group `3`. ``` $.($3*__ ``` Replace the underscore with the incremented integer. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 114 bytes Expects a matrix filled with \$0\$ and \$-1\$. Outputs by updating the input matrix with 1-indexed distances. ``` f=(m,n=m[0][0]=1)=>m.map(q=(r,y)=>r.map((v,x)=>(h=d=>d+2?v|m[y+d--%2]?.[x+d%2]^n?h(d):r[x]=q=n+1:0)(2)))|q&&f(m,q) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVFBboMwEFSlnniFLw1rYSzgFAUZTn1Bjq4roTiERLEdXIqImr6klxzaR7WvqYFQpaoqrTQ7O95Ze_32ro1cn88fz00Zzj9tyUARzRSPhAsWY5YpqooD1AwsOTpqBwot6RyBikmWySDJ25Pix0CG4V0icsq7QLrkUecVSLywvBOsZjqIFxGGBGN8qmez0o2q8Tj56-Y25R5CHPGIIBdh7ECQiUYX1pcH6a-KBLk2-F2Yev7xvpJdmyc8Whp7X6wqUIhl6MX5uNvi1OHK6CezX9O92cC4GtsfGdfS9mlLG7Ns7FZvANNDIZdNYZv-1XRnthp85P-kD9rHKEADpt7rZRnTd3wD) ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input matrix n = // n = distance counter m[0][0] = 1 // set m[0][0] to 1 ) => // m.map(q = // initialize q to a zero'ish value (r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each value v at position x in r[]: ( h = // h is a recursive function taking d => // a direction d d + 2 ? // if d is not equal to -2: v | // if v is already set m[y + d-- % 2] // or the neighbor cell ?.[x + d % 2] // in direction d ^ n ? // is not equal to n: h(d) // try again with the next direction : // else: r[x] = // update the cell to n + 1 q = n + 1 // and set q to a non-zero value : // else: 0 // stop the recursion )(2) // initial call to h with d = 2 ) // end of inner map() ) // end of outer map() | q && f(m, q) // if q was set, do a recursive call ``` [Answer] # [Julia](https://julialang.org) ## 97 bytes ``` h(X,r=1,c=1,d=0)=try d<X[r][c]&&(X[r][c]=d for i=[5,7,1,3] h(X,r+i÷3-1,c+i%3-1,d+1)end)catch;end ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBLTsMwEBXL5hSzobJVO437oYUyAbHLqttKkRdW0qpBTUFpCuUsbLrpGTgAp4DTME7cn4pke-b5zbw39ufueb3IzPb36j01pcHYiyEOBNBSdGqxR4FDqiYuOdAY1r3ES9p9V94R0BXQs0g6qufYgYAbSumkdnG0tmqAIRz0Oie8Onj-M6M6HegosTet_CxQwdl09oqGGQq4rZy0l7vvyM0ry2Vow0aGG8QAHkC1A7ijpjZJ51xEHMOLOqmoUNaVm6pszGH2UgCLbJYtwTp4ercuZ3L4Y-ZsIgpUIqGdYsCxLD4gvZ_EhY4T3Wwyl2E6sioZxn0xEEp0NVStrez7q0vvSFrZtY1pS_HpMuWJKZP5iDJn9HQ2Q_VMrzFnEfcaj2a1mhYlmMWCvVEfG_u-z33ECkQWcO-gtN3W8Q8) ## 81 bytes A greatly improved version provided by @MarcMush. ``` h(X,r=1,c=1,d=0)=d<get(X,(r,c),0)&&1:2:7 .|>i->h(X,r+i÷3-1,c+i%3-1,(X[r,c]=d)+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBLTsMwEBXL5hSzobLVcWqnhZYIG7ZZVewqRVlESUuCSEFpKnXBBTgDm256Bg7AKeA0HSfpT1SKPR6_3zhf25fVax5v_q4-07iKdeiEEEoE-hTtEe472XaqAf5jEGnTaAkXtG5auocwQBjaTrTQsEVHCLd0pJ3keIy2bqANHPy8E1wdMi_MqE4HOlrsQ-s82yh5Np29omHGCHd1UuQU7e_IkrhiRfzOCmFsWQuz1lrCA6i-BJ-UffIvOAbcdV2uzWWBUKQQjWRd8yc1H-ZvJbCAOsgXYDOdaLuq5mL8-5SxKZZaYUIr1ZLr9P55VtElKzHhKHm3q3zPH4H7YXJhanov__ke0GuSXn5tK5uGRI50ynuKt8Z4llk_1OlkLOBO5zFeLmdlBQFoDRNntkgbzWbT1B0) ### representation: * free slots -> Inf * forbidden slots -> -Inf * 0-based distance [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 32 bytes ``` k₁w≬ƛ£?ÞT›'¥ε∑ṅ}ÞfU↔‹vÞǔ∑:fGε›*‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwia+KCgXfiiazGm8KjP8OeVOKAuifCpc614oiR4bmFfcOeZlXihpTigLl2w57HlOKIkTpmR8614oC6KuKAuSIsIiIsIltbMSwgMSwgMCwgMV0sIFsxLCAxLCAxLCAxXSwgWzAsIDAsIDEsIDFdLCBbMSwgMSwgMSwgMV1dIl0=) Port of Jonathan Allan's Jelly answer, byte count can certainly be way less. [Answer] # Python3, 194 bytes: ``` def f(b): q=[(0,0,0)] while q: (x,y,v),*q=q for X,Y in[(0,1),(0,-1),(1,0),(-1,0)]: X+=x;Y+=y if-1<X<len(b)and-1<Y<len(b[0])and(X|Y)and 0==b[X][Y]:b[X][Y]=v+1;q+=[(X,Y,v+1)] return b ``` [Try it online!](https://tio.run/##VU5NC4MwDL37K3JsZ4TKLsPZ/9FSepjMMmFUW9yHsP/uEubBEZLHe0l4b1rm2xiPpymv67UPEEQnmwKSdkIhlfQFvG7DvYdEMog3LviUeEg6EQ1jBoMWhsjntUSaFUNNnygqBs9/YEr9PttSL0yGUNWtae99JLdLvBKzP@aUZ0GYj2UEpXXnjHfWNxvqZ1mfU0n5yBiJcMLcz48coVunPMRZBOHIxikkLxoUA5THvcS9Sbzl3kn/V@ClXL8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 25 ~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 using [ais523's trick](https://codegolf.stackexchange.com/a/249092/53748) of using integer division to place `inf` as walls. ``` Ø1Wạ§ỊɗƇⱮẎQɗ@ƬŒMŒṬSFṀ_Ɗ: ``` A monadic Link that accepts the grid with `1` as space and `0` as wall and yields another grid containing the fill distances at spaces and `inf` at walls. **[Try it online!](https://tio.run/##y0rNyan8///wDMPwh7sWHlr@cHfXyenH2h9tXPdwV1/gyekOx9YcneR7dNLDnWuC3R7ubIg/1mX1/3C7@///0dGGOgpAZAAkY7l0oDxDKM8AIoFFLhYA "Jelly – Try It Online")** ### How? ``` Ø1Wạ§ỊɗƇⱮẎQɗ@ƬŒMŒṬSFṀ_Ɗ: - Link: Grid Ø1 - literal [1, 1] W - wrap -> [[1, 1]] ŒM - maximal multidimensional indices of Grid -> space coordinates Ƭ - start with A=[[1, 1]] and collect up while distinct applying: @ - with swapped arguments: ɗ - last three links as a dyad - f(space coordinates, A): Ɱ - map (for a in A) with: Ƈ - keep those (s in space-cordinates) for which: ɗ - last three links as a dyad - f(s, a): ạ - absolute difference § - sums Ị - insignificant? -> is s a neighbour of, or equal to, a? Ẏ - tighten -> flat list of neighbours Q - deduplicate ŒṬ - multidimensional grids with 1s at those indices S - sum -> 0 at walls, 1 at furthest, 2 at next nearest, etc. Ɗ - last three links as a monad - f(X=that): F - flatten Ṁ - maximum -> value at top-left _ - subtract X (vectorises) : - integer divide by the grid -> keeps space values, replaces wall with inf ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 110 bytes ``` a=>[,...0+a].map((_,i)=>a=a.map((r,y)=>r.map((c,x)=>x+y?c||i*[2,1,0,-1].some(k=>a[y+k%2]?.[x+--k%2]>0):1)))&&a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVBLTsMwFBTbnOJtaGziWE7YoFZOVpygGyQTIStNSmhjV26oUlFOwiZCcCg4DXbdogJCsv1m3ryPxi9vSs-q4bXm749dHV99KMkzQSilLJIFbeUKoTvSYJ5JLj01ZGup8aQkvSV9tM3L3a65EClJCCNxUtC1biu0sH1iGy3O0yKnoo_i2MGM4XGCMR6NpN_6eXY5EQGAAMEI2BMnNhTkSNmBufRe-qtCQU4H_Ewce_6ZfSLbtsDblsAz8JaNg95w6aB9OAcGub1jCG9C6yWgtTbXsrxHrSt5srtLrdZ6WdGlnqMatfj3rI2DG9rpaWcaNUeYruRs2knToRRj-qAbhUIIv-GtCjFEsI-T4Bn7vxsGH78A) ]